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
general updates and bug fixes
tilakpatel22473147ea90d3
diff --git a/fincept-qt/CMakePresets.json b/fincept-qt/CMakePresets.jsonindex 48f2fd37e..c7dc06d56 100644--- a/fincept-qt/CMakePresets.json+++ b/fincept-qt/CMakePresets.json@@ -86,6 +86,21 @@"displayName": "macOS Debug (Apple Clang 15.0, Qt 6.8.3)","inherits": "macos-release","cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" }+ },+ {+ "name": "macos-asan",+ "displayName": "macOS AddressSanitizer (Apple Clang, Qt 6.8.3)",+ "description": "Debug build with -fsanitize=address,undefined for catching use-after-free / heap-buffer-overflow / UB. Pair with scripts/stress_network.sh to exercise the network paths under load. Symbolicated reports go to stderr at the crash site with full alloc+free stacks.",+ "inherits": "macos-release",+ "cacheVariables": {+ "CMAKE_BUILD_TYPE": "RelWithDebInfo",+ "CMAKE_PREFIX_PATH": "$env{HOME}/Qt/6.8.3/macos;$env{HOME}/projects/FinceptTerminal/.qt/6.8.3/macos",+ "CMAKE_CXX_FLAGS": "-fsanitize=address,undefined -fno-omit-frame-pointer -fno-optimize-sibling-calls -g",+ "CMAKE_C_FLAGS": "-fsanitize=address,undefined -fno-omit-frame-pointer -fno-optimize-sibling-calls -g",+ "CMAKE_EXE_LINKER_FLAGS": "-fsanitize=address,undefined",+ "CMAKE_SHARED_LINKER_FLAGS": "-fsanitize=address,undefined",+ "CMAKE_UNITY_BUILD": "OFF"+ }}],@@ -97,6 +112,7 @@{ "name": "linux-release", "configurePreset": "linux-release" },{ "name": "linux-debug", "configurePreset": "linux-debug" },{ "name": "macos-release", "configurePreset": "macos-release" },- { "name": "macos-debug", "configurePreset": "macos-debug" }+ { "name": "macos-debug", "configurePreset": "macos-debug" },+ { "name": "macos-asan", "configurePreset": "macos-asan" }]}diff --git a/fincept-qt/docs/DEBUGGING_CRASHES.md b/fincept-qt/docs/DEBUGGING_CRASHES.mdnew file mode 100644index 000000000..f28b0e3b5--- /dev/null+++ b/fincept-qt/docs/DEBUGGING_CRASHES.md@@ -0,0 +1,144 @@+# Debugging long-running crashes on macOS++This page is a runbook for diagnosing the class of crash where the app runs+for hours and then dies inside Qt internals with `EXC_BAD_ACCESS` — typically+inside `doActivate`, `channelReadyRead`, or `qt_mac_socket_callback`. These+are almost always use-after-free / wild-pointer reads against an object that+was destroyed minutes-to-hours earlier; the stack trace shows the *use* site+but tells you nothing about *which allocation went bad*.++The runbook below pinpoints the exact alloc + free pair with full backtraces.++---++## TL;DR++```bash+# 1. Launch the signed bundle under macOS malloc instrumentation.+./scripts/diagnose-macos-crash.sh++# 2. Use the app normally until it crashes (could be minutes to hours).++# 3. Open the crash report:+# ~/Library/Logs/DiagnosticReports/FinceptTerminal-*.ips+# Find the faulting address (look for `far:` in the ARM thread state,+# or `Exception Subtype: KERN_INVALID_ADDRESS at 0x…`).+#+# With MallocScribble enabled, a use-after-free shows up as the address+# `0x5555…` or pattern-derived bytes — that's the smoking gun.++# 4. Get the alloc + free backtraces for that address:+malloc_history $(pgrep -n FinceptTerminal) -allEvents 0x<address>+# If the process has already exited, run against the snapshot:+malloc_history ~/Library/Logs/DiagnosticReports/FinceptTerminal-*.ips 0x<address>+```++You now have:+- the line of code that **allocated** the object,+- the line of code that **freed** it,+- the line of code that **tried to use it after free** (from the crash stack).++Root cause is a 3-way grep, not a guess.++---++## Why the malloc-debug approach is right here++| Approach | Catches this bug? | Requires rebuild? | Works on signed bundle? |+|---|---|---|---|+| **MallocStackLoggingNoCompact + MallocScribble** | yes (UAF) | no | **yes** |+| AddressSanitizer | yes (UAF + UB) | yes (incl. Qt) | no |+| Crashpad / Sentry telemetry | statistically, across many users | no | yes |+| ThreadSanitizer | only data races | yes | no |+| Static analysis (clang-tidy) | sometimes (patterns) | no | no |+| Code review / guess | no — wastes time | no | no |++`MallocScribble` is the killer feature: every `free()` writes `0x55` over the+returned region, so a subsequent read crashes **at the use site** instead of+2+ hours later when the region happens to be reused for an int. The crash+becomes deterministic in the sense that the bad read becomes immediate.++For details on each env var see Apple's+[Malloc Debug Environment Variables](https://developer.apple.com/library/archive/releasenotes/DeveloperTools/RN-MallocOptions/)+and the+[`malloc_history(1)` man page](https://keith.github.io/xcode-man-pages/malloc_history.1.html).++---++## When to reach for AddressSanitizer instead++ASan beats `malloc_history` when:++- You can **reproduce the crash on demand** (under a synthetic stress harness, in+ a unit test, etc.).+- You care about **uninitialised reads / heap overflows / stack UAF**, which+ `MallocScribble` doesn't cover.++To build it:++```bash+cmake --preset macos-asan+cmake --build build/macos-asan+./scripts/diagnose-macos-crash.sh --asan+```++The `macos-asan` preset is defined in `CMakePresets.json`. It uses+`-fsanitize=address,undefined` and disables unity builds so backtraces are+clean.++> Caveat: ASan only instruments **your** code by default — Qt's frameworks+> are untouched. Most QObject UAFs still get caught (ASan flags the use, even+> if the alloc is in Qt) but bugs inside Qt itself are invisible. For those,+> stay on `malloc_history`.++---++## When to ship telemetry instead++If the crash only happens for **specific users** (specific brokers configured,+specific LLM providers, specific OS versions) and you can't repro locally:++- Integrate **Crashpad** (Chromium's crash reporter, used by Slack/Spotify).+ ~200 LOC to wire to `QApplication`, uploads to your own backend or+ Backtrace/Sentry. After a week of real users you'll have N similar crashes+ with full state.++This is more work than the malloc-debug recipe, but it's the right answer+when "use the app for 2 hours then it crashes" can't be reproduced on a+developer machine.++---++## Reading the crash report++The `.ips` files under `~/Library/Logs/DiagnosticReports/` are JSON-formatted+crash reports. Useful fields:++```+exception.type: EXC_BAD_ACCESS / EXC_BREAKPOINT / ...+exception.subtype: "KERN_INVALID_ADDRESS at 0x…" ← the faulting address+faultingThread: <index into threads[]>+threads[*].frames: array of {imageOffset, symbol, …} ← per-frame symbols+threadState.far: the address that triggered the page fault on ARM64+```++For the kind of crash this runbook covers:++- `far` will be a small number (`0x3f`, `0x40`, etc.) — that means the object+ pointer was 0 and the code read a member at that offset, **or** it'll be+ a `0x5555…` pattern — that's `MallocScribble`'s signature confirming the+ region was freed before reuse.+- The frame at index 0 is the *use* site. It's the most-recently-executed+ code touching the bad pointer, **not** the bug location.+- The bug is at the line that *freed* the object too early. That's what+ `malloc_history -allEvents <far>` tells you.++---++## Background reading++- [Apple — Enabling the Malloc Debugging Features](https://developer.apple.com/library/archive/documentation/Performance/Conceptual/ManagingMemory/Articles/MallocDebug.html)+- [Apple — Malloc Debug Environment Variables Release Notes](https://developer.apple.com/library/archive/releasenotes/DeveloperTools/RN-MallocOptions/)+- [`malloc_history(1)` man page](https://keith.github.io/xcode-man-pages/malloc_history.1.html)+- [Qt forum — Random crashes on Apple Silicon (Qt 6)](https://forum.qt.io/topic/135220/random-application-crash-on-apple-silicon-m1-qt-6-2-3/42)+- [KDAB — Building Qt with AddressSanitizer](https://www.kdab.com/qt-asan-windows/)diff --git a/fincept-qt/scripts/Analytics/backtesting/bt/bt_provider.py b/fincept-qt/scripts/Analytics/backtesting/bt/bt_provider.pyindex d61eccc4e..b8bf52172 100644--- a/fincept-qt/scripts/Analytics/backtesting/bt/bt_provider.py+++ b/fincept-qt/scripts/Analytics/backtesting/bt/bt_provider.py@@ -614,14 +614,35 @@ class BtProvider(BacktestingProviderBase):data = (best_result or {}).get('data') or {}data.setdefault('id', self._generate_id())data.setdefault('status', 'completed')++ best_objective_value = float(best_score) if best_score != -np.inf else 0.0+ best_performance = data.get('performance', {})++ # Legacy `optimization` block kept for any callers still parsing it.data['optimization'] = {'objective': objective,'method': method,- 'objective_value': float(best_score) if best_score != -np.inf else 0.0,+ 'objective_value': best_objective_value,'best_params': best_params,'iterations': len(combos),- 'all_results': all_results[:100], # cap to keep payload small+ 'all_results': all_results[:100],}+ # Top-level vectorbt-compatible fields so the frontend's "optimize"+ # renderer (which expects bestParameters/bestObjectiveValue/etc.)+ # displays this result correctly.+ data['bestParameters'] = best_params+ data['bestObjectiveValue'] = best_objective_value+ data['bestPerformance'] = best_performance+ data['iterations'] = len(combos)+ data['totalCombinations'] = len(combos)+ data['method'] = method+ data['objective'] = objective+ data['allResults'] = [+ {'parameters': r.get('parameters', {}),+ 'objective_value': float(r.get('score', 0) or 0),+ 'performance': {}}+ for r in all_results[:100]+ ]return {'success': True, 'message': 'Optimization completed', 'data': data}except Exception as e:@@ -717,13 +738,32 @@ class BtProvider(BacktestingProviderBase):data_out = (last_result or {}).get('data') or {}data_out.setdefault('id', self._generate_id())data_out.setdefault('status', 'completed')+ avg_oos_return = float(np.mean([f['testReturn'] for f in folds]))+ avg_oos_sharpe = float(np.mean([f['testSharpe'] for f in folds]))data_out['walk_forward'] = {'n_splits': n_splits,'train_ratio': train_ratio,'folds': folds,- 'mean_test_return': float(np.mean([f['testReturn'] for f in folds])),- 'mean_test_sharpe': float(np.mean([f['testSharpe'] for f in folds])),+ 'mean_test_return': avg_oos_return,+ 'mean_test_sharpe': avg_oos_sharpe,}+ # Top-level vectorbt-compatible shape for the frontend renderer.+ data_out['nWindows'] = len(folds)+ data_out['avgOosReturn'] = avg_oos_return+ data_out['avgOosSharpe'] = avg_oos_sharpe+ data_out['oosReturnStd'] = float(np.std([f['testReturn'] for f in folds])) if folds else 0.0+ data_out['robustnessScore'] = float(np.mean([1.0 if f['testReturn'] > 0 else 0.0 for f in folds])) if folds else 0.0+ data_out['windows'] = [+ {+ 'window': f['fold'] + 1,+ 'trainStart': f['trainStart'], 'trainEnd': f['trainEnd'],+ 'testStart': f['testStart'], 'testEnd': f['testEnd'],+ 'inSampleReturn': 0.0, 'inSampleSharpe': 0.0,+ 'outOfSampleReturn': f['testReturn'],+ 'outOfSampleSharpe': f['testSharpe'],+ }+ for f in folds+ ]return {'success': True, 'message': 'Walk-forward completed', 'data': data_out}except Exception as e:diff --git a/fincept-qt/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py b/fincept-qt/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.pyindex 286a2b05c..52ddd5eb3 100644--- a/fincept-qt/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py+++ b/fincept-qt/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py@@ -332,43 +332,64 @@ class VectorBTProvider(BacktestingProviderBase):return error_resultdef optimize(self, request: Dict[str, Any]) -> Dict[str, Any]:- """Run parameter optimization."""+ """Run parameter optimization. Accepts the UI's arg shape:+ - symbols (flat list) ← UI sends this+ - strategy: {type, params} ← strategy.params holds the seed values+ - paramRanges: {<name>: {min,max,step}} ← UI's ranges (also accepts `parameters`)+ - optimizeObjective / objective+ - optimizeMethod / method+ - maxIterations+ """try:vbt = self._import_vbt()except Exception as e:return self._create_error_result(str(e))try:- import pandas as pdimport vbt_optimization as optstrategy = request.get('strategy', {})strategy_type = strategy.get('type', 'sma_crossover')- parameters = request.get('parameters', {})- objective = request.get('objective', 'sharpe')++ # Accept both UI's `paramRanges` and legacy `parameters` / strategy.params seeds+ parameters = (request.get('paramRanges')+ or request.get('parameters')+ or strategy.get('params', {}))+ objective = request.get('optimizeObjective') or request.get('objective', 'sharpe')+ method = request.get('optimizeMethod') or request.get('method', 'grid')initial_capital = request.get('initialCapital', 100000)start_date = request.get('startDate')end_date = request.get('endDate')- assets = request.get('assets', [])- method = request.get('method', 'grid')max_iterations = request.get('maxIterations', 500)- symbols = [asset['symbol'] for asset in assets]- close_series, _ = self._load_market_data(symbols, start_date, end_date)+ # Accept UI's flat symbols OR legacy assets list+ symbols = request.get('symbols') or [a.get('symbol') for a in request.get('assets', []) if a.get('symbol')]+ if not symbols:+ return {'success': False, 'error': 'No symbols provided'}+ close_series, using_synthetic = self._load_market_data(self._normalize_symbols(symbols), start_date, end_date)result = opt.optimize(vbt, close_series, strategy_type, parameters,objective, initial_capital, method, max_iterations, request)+ # opt.optimize returns its own success flag — surface failures+ if not result.get('success', True):+ return {'success': False, 'error': result.get('error', 'Optimization failed')}++ result['usingSyntheticData'] = using_syntheticreturn {'success': True, 'data': result}except Exception as e:self._error('Optimization failed', e)- return self._create_error_result(f'Optimization failed: {str(e)}')+ return {'success': False, 'error': f'Optimization failed: {str(e)}'}def walk_forward(self, request: Dict[str, Any]) -> Dict[str, Any]:- """Run walk-forward optimization."""+ """Walk-forward optimization. Accepts UI's arg shape:+ - symbols, strategy.{type,params}+ - paramRanges (or parameters or strategy.params)+ - wfSplits / nSplits, wfTrainRatio / trainRatio+ """try:vbt = self._import_vbt()except Exception as e:@@ -379,28 +400,35 @@ class VectorBTProvider(BacktestingProviderBase):strategy = request.get('strategy', {})strategy_type = strategy.get('type', 'sma_crossover')- parameters = request.get('parameters', {})- objective = request.get('objective', 'sharpe')+ parameters = (request.get('paramRanges')+ or request.get('parameters')+ or strategy.get('params', {}))+ objective = request.get('optimizeObjective') or request.get('objective', 'sharpe')initial_capital = request.get('initialCapital', 100000)start_date = request.get('startDate')end_date = request.get('endDate')- assets = request.get('assets', [])- n_splits = request.get('nSplits', 5)- train_ratio = request.get('trainRatio', 0.7)+ n_splits = request.get('wfSplits') or request.get('nSplits', 5)+ train_ratio = request.get('wfTrainRatio') or request.get('trainRatio', 0.7)- symbols = [asset['symbol'] for asset in assets]- close_series, _ = self._load_market_data(symbols, start_date, end_date)+ symbols = request.get('symbols') or [a.get('symbol') for a in request.get('assets', []) if a.get('symbol')]+ if not symbols:+ return {'success': False, 'error': 'No symbols provided'}+ close_series, using_synthetic = self._load_market_data(self._normalize_symbols(symbols), start_date, end_date)result = opt.walk_forward_optimize(vbt, close_series, strategy_type, parameters,objective, initial_capital, n_splits, train_ratio, request)+ if not result.get('success', True):+ return {'success': False, 'error': result.get('error', 'Walk-forward failed')}++ result['usingSyntheticData'] = using_syntheticreturn {'success': True, 'data': result}except Exception as e:self._error('Walk-forward optimization failed', e)- return self._create_error_result(f'Walk-forward failed: {str(e)}')+ return {'success': False, 'error': f'Walk-forward failed: {str(e)}'}def get_strategies(self, request: Dict[str, Any]) -> Dict[str, Any]:"""Return available strategy catalog."""@@ -421,18 +449,22 @@ class VectorBTProvider(BacktestingProviderBase):return {'indicators': grouped}def get_command_options(self, request: Dict[str, Any]) -> Dict[str, Any]:- """Return provider-specific option lists for all command dropdowns."""+ """Return provider-specific option lists for all command dropdowns.+ Names here MUST match what the Python dispatchers below actually accept —+ these strings are sent back unchanged in execute() requests.+ """return {'success': True,'data': {'position_sizing_methods': ['percent', 'fixed', 'kelly', 'vol_target', 'risk'],'optimize_objectives': ['sharpe', 'sortino', 'calmar', 'return', 'omega'],- 'optimize_methods': ['grid', 'random', 'optuna'],+ 'optimize_methods': ['grid', 'random'],'label_types': ['FIXLB', 'MEANLB', 'LEXLB', 'TRENDLB', 'BOLB'],- 'splitter_types': ['RollingSplitter', 'ExpandingSplitter', 'PurgedKFold'],+ 'splitter_types': ['RollingSplitter', 'ExpandingSplitter', 'PurgedKFoldSplitter'],'signal_generators': ['RAND', 'RANDX', 'RANDNX', 'RPROB', 'RPROBX'],- 'indicator_signal_modes': ['crossover', 'threshold', 'breakout', 'mean_reversion', 'filter'],- 'returns_analysis_types': ['cumulative', 'rolling', 'drawdown', 'distribution', 'benchmark_comparison'],+ 'indicator_signal_modes': ['crossover_signals', 'threshold_signals', 'breakout_signals',+ 'mean_reversion_signals', 'signal_filter'],+ 'returns_analysis_types': ['returns_stats', 'drawdowns', 'ranges', 'rolling'],},}@@ -653,16 +685,21 @@ class VectorBTProvider(BacktestingProviderBase):else:index = pd.date_range(start='2020-01-01', end='2024-01-01', freq='B')+ # Accept both snake_case Python names AND the UI's camelCase aliases.+ # The UI exposes generic WINDOW LENGTH / STEP SIZE inputs — for the+ # test window we derive a sensible split (1/3 of window) so users get+ # non-empty splits without having to expose every internal knob.+ window_len = params.get('window_len') or params.get('windowLength') or 60+ step = params.get('step') or params.get('stepSize') or max(1, window_len // 4)+ test_len = params.get('test_len') or params.get('testLength') or max(5, window_len // 3)+splitter_map = {'RollingSplitter': lambda: sp.RollingSplitter(- window_len=params.get('window_len', 252),- test_len=params.get('test_len', 63),- step=params.get('step', 21),+ window_len=window_len, test_len=test_len, step=step,),'ExpandingSplitter': lambda: sp.ExpandingSplitter(- min_len=params.get('min_len', 252),- test_len=params.get('test_len', 63),- step=params.get('step', 21),+ min_len=params.get('min_len') or params.get('windowLength') or window_len,+ test_len=test_len, step=step,),'PurgedKFoldSplitter': lambda: sp.PurgedKFoldSplitter(n_splits=params.get('n_splits', 5),@@ -670,6 +707,9 @@ class VectorBTProvider(BacktestingProviderBase):embargo_len=params.get('embargo_len', 5),),}+ # Back-compat alias — older UI may send the short form+ if splitter_type == 'PurgedKFold':+ splitter_type = 'PurgedKFoldSplitter'# RangeSplitter: user supplies date ranges directlyif splitter_type == 'RangeSplitter':@@ -701,15 +741,20 @@ class VectorBTProvider(BacktestingProviderBase):splitter = splitter_map[splitter_type]()splits = []- for i, (train_idx, test_idx) in enumerate(splitter.split(index)):+ for i, (train_mask, test_mask) in enumerate(splitter.split(index)):+ # Splitters yield boolean masks — convert to positional indices.+ train_pos = np.where(np.asarray(train_mask))[0]+ test_pos = np.where(np.asarray(test_mask))[0]+ if len(train_pos) == 0 or len(test_pos) == 0:+ continuesplits.append({'fold': i,- 'trainStart': str(index[train_idx[0]]),- 'trainEnd': str(index[train_idx[-1]]),- 'trainSize': len(train_idx),- 'testStart': str(index[test_idx[0]]),- 'testEnd': str(index[test_idx[-1]]),- 'testSize': len(test_idx),+ 'trainStart': str(index[train_pos[0]]),+ 'trainEnd': str(index[train_pos[-1]]),+ 'trainSize': int(len(train_pos)),+ 'testStart': str(index[test_pos[0]]),+ 'testEnd': str(index[test_pos[-1]]),+ 'testSize': int(len(test_pos)),})result_data = {@@ -737,8 +782,12 @@ class VectorBTProvider(BacktestingProviderBase):symbols = request.get('symbols', ['SPY'])start_date = request.get('startDate')end_date = request.get('endDate')- benchmark = request.get('benchmark', '')- params = request.get('params', {})+ # UI sends benchmarkSymbol; legacy callers pass benchmark+ benchmark = request.get('benchmark') or request.get('benchmarkSymbol') or ''+ params = dict(request.get('params') or {})+ # UI surfaces a "ROLLING WINDOW" spinbox at the top level — fold it into params.+ if 'rollingWindow' in request and 'window' not in params:+ params['window'] = request['rollingWindow']close_series, using_synthetic = self._load_market_data(self._normalize_symbols(symbols), start_date, end_date@@ -1152,11 +1201,33 @@ class VectorBTProvider(BacktestingProviderBase):import pandas as pdimport vbt_indicators as ind+ # UI alias: `sma` is the same as `ma` in this provider's indicator catalogindicator = request.get('indicator', 'rsi')+ if indicator == 'sma':+ indicator = 'ma'symbols = request.get('symbols', ['SPY'])start_date = request.get('startDate')end_date = request.get('endDate')- param_ranges = request.get('paramRanges', {})++ # Accept either paramRanges (keyed-by-name dict) OR paramRange (singular+ # min/max/step from the UI). For the singular form we sweep the+ # indicator's primary period-style argument.+ primary_param_by_indicator = {+ 'momentum': 'lookback',+ 'macd': 'fast', 'stoch': 'k_period',+ 'obv': None, 'vwap': None,+ }+ param_ranges = request.get('paramRanges')+ if not param_ranges:+ pr = request.get('paramRange')+ if pr:+ primary = primary_param_by_indicator.get(indicator, 'period')+ if primary:+ param_ranges = {primary: pr}+ else:+ return {'success': False, 'error': f'Indicator {indicator} has no sweep parameter'}+ else:+ param_ranges = {}print(f"[INDICATOR_SWEEP] Got request: indicator={indicator}, symbols={symbols}", flush=True)print(f"[INDICATOR_SWEEP] param_ranges={param_ranges}", flush=True)@@ -1391,9 +1462,129 @@ class VectorBTProvider(BacktestingProviderBase):except Exception as e:return {'success': False, 'error': str(e), 'traceback': __import__('traceback').format_exc()}- def calculate_indicator(self, indicator_type: str, params: Dict[str, Any]) -> Dict[str, Any]:- """Calculate a technical indicator."""- raise NotImplementedError('Use VectorBT indicators within backtests')+ def calculate_indicator(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Compute one indicator over a symbol's close series and return a value series.+ The UI's Indicators page picks one of the IDs from get_indicators() and a+ date range; we return enough samples to plot a small preview.+ """+ try:+ import numpy as np+ import pandas as pd+ import vbt_indicators as ind++ indicator = request.get('indicator', 'sma')+ if indicator == 'sma':+ indicator = 'ma'+ symbols = request.get('symbols', ['SPY'])+ start_date = request.get('startDate')+ end_date = request.get('endDate')+ params = request.get('params', {}) or {}+ period = int(params.get('period', 14))++ close_series, using_synthetic = self._load_market_data(+ self._normalize_symbols(symbols), start_date, end_date+ )++ # Try to grab full OHLCV for indicators that need high/low/volume.+ high = low = volume = None+ try:+ import yfinance as yf+ normalized = self._normalize_symbols(symbols)+ raw = yf.download(normalized if len(normalized) > 1 else normalized[0],+ start=start_date, end=end_date, progress=False)+ if raw is not None and not raw.empty:+ high = raw['High'].values.flatten() if 'High' in raw.columns else None+ low = raw['Low'].values.flatten() if 'Low' in raw.columns else None+ volume = raw['Volume'].values.flatten() if 'Volume' in raw.columns else None+ except Exception:+ pass+ if high is None:+ high = close_series.values * 1.02+ low = close_series.values * 0.98+ volume = np.random.randint(1_000_000, 10_000_000, len(close_series))++ close_arr = close_series.values+ calc_map = {+ 'sma': lambda: ind.calculate_ma(None, close_arr, period, ewm=False),+ 'ma': lambda: ind.calculate_ma(None, close_arr, period, ewm=False),+ 'ema': lambda: ind.calculate_ma(None, close_arr, period, ewm=True),+ 'mstd':lambda: ind.calculate_mstd(None, close_arr, period, ewm=False),+ 'rsi': lambda: ind.calculate_rsi(None, close_arr, period),+ 'momentum': lambda: ind.calculate_momentum(close_arr, period),+ 'zscore': lambda: ind.calculate_zscore(close_arr, period),+ 'donchian': lambda: ind.calculate_donchian(close_arr, period),+ 'bbands': lambda: ind.calculate_bbands(None, close_arr, period, alpha=2.0),+ 'macd': lambda: ind.calculate_macd(None, close_arr, 12, 26, 9),+ 'adx': lambda: ind.calculate_adx(close_arr, high=high, low=low, period=period),+ 'atr': lambda: ind.calculate_atr(None, high, low, close_arr, period),+ 'cci': lambda: ind.calculate_cci(high, low, close_arr, period),+ 'williams_r': lambda: ind.calculate_williams_r(high, low, close_arr, period),+ 'keltner': lambda: ind.calculate_keltner(high, low, close_arr, ema_period=period, atr_period=10, multiplier=2.0),+ 'stochastic': lambda: ind.calculate_stoch(None, high, low, close_arr, period, 3),+ 'stoch': lambda: ind.calculate_stoch(None, high, low, close_arr, period, 3),+ 'obv': lambda: ind.calculate_obv(None, close_arr, volume),+ 'vwap': lambda: ind.calculate_vwap(high, low, close_arr, volume),+ }+ if indicator not in calc_map:+ return {'success': False, 'error': f'Unknown indicator: {indicator}'}++ out = calc_map[indicator]()++ # Indicators return either an array (single output) or dict (multi-output).+ def sample_series(arr):+ arr = np.asarray(arr, dtype=float)+ idx = close_series.index+ # Down-sample to ~200 points for the UI+ stride = max(1, len(arr) // 200)+ return [+ {'date': str(idx[i]), 'value': (None if np.isnan(arr[i]) else float(arr[i]))}+ for i in range(0, len(arr), stride)+ ]++ result_data = {+ 'indicator': indicator,+ 'period': period,+ 'symbol': symbols[0] if symbols else '',+ 'totalBars': len(close_arr),+ 'usingSyntheticData': using_synthetic,+ }++ if isinstance(out, dict):+ # Multi-output indicator: emit one series per component+ series = {}+ stats = {}+ for name, comp in out.items():+ if comp is None or not hasattr(comp, '__len__'):+ continue+ series[name] = sample_series(comp)+ vals = np.asarray(comp, dtype=float)+ vals = vals[~np.isnan(vals)]+ if len(vals):+ stats[name] = {+ 'mean': float(np.mean(vals)),+ 'std': float(np.std(vals)),+ 'min': float(np.min(vals)),+ 'max': float(np.max(vals)),+ 'last': float(vals[-1]),+ }+ result_data['series'] = series+ result_data['stats'] = stats+ else:+ vals = np.asarray(out, dtype=float)+ clean = vals[~np.isnan(vals)]+ result_data['series'] = sample_series(vals)+ if len(clean):+ result_data['stats'] = {+ 'mean': float(np.mean(clean)),+ 'std': float(np.std(clean)),+ 'min': float(np.min(clean)),+ 'max': float(np.max(clean)),+ 'last': float(clean[-1]),+ }++ return {'success': True, 'data': result_data}+ except Exception as e:+ return {'success': False, 'error': str(e), 'traceback': __import__('traceback').format_exc()}# ========================================================================# Private Helpers@@ -1890,6 +2081,9 @@ def main():elif command == 'indicator_signals':result = provider.indicator_signals(args)result_str = json_response(result)+ elif command == 'calculate_indicator':+ result = provider.calculate_indicator(args)+ result_str = json_response(result)elif command == 'indicator_param_sweep':print("[MAIN] About to call indicator_param_sweep")sys.stdout.flush()diff --git a/fincept-qt/scripts/Analytics/backtesting/zipline/zipline_provider.py b/fincept-qt/scripts/Analytics/backtesting/zipline/zipline_provider.pyindex e570ab2d0..6506af723 100644--- a/fincept-qt/scripts/Analytics/backtesting/zipline/zipline_provider.py+++ b/fincept-qt/scripts/Analytics/backtesting/zipline/zipline_provider.py@@ -1523,7 +1523,7 @@ class ZiplineProvider(BacktestingProviderBase):start_date = request.get('startDate', '2023-01-01')end_date = request.get('endDate', '2024-01-01')indicator = request.get('indicator', 'ma')- params = request.get('parameters', {})+ params = request.get('params') or request.get('parameters') or {}if isinstance(symbols, str):symbols = [s.strip() for s in symbols.split(',')]@@ -1665,18 +1665,22 @@ class ZiplineProvider(BacktestingProviderBase):return {'indicators': grouped}def get_command_options(self, request: Dict[str, Any]) -> Dict[str, Any]:- """Return provider-specific option lists for all command dropdowns."""+ """Return provider-specific option lists for all command dropdowns.+ Names match the canonical strings the dispatchers below accept (any UI→python+ aliases get normalized at command entry).+ """return {'success': True,'data': {'position_sizing_methods': ['percent', 'fixed', 'kelly', 'vol_target', 'risk'],'optimize_objectives': ['sharpe', 'sortino', 'calmar', 'return'],'optimize_methods': ['grid', 'random'],- 'label_types': [],- 'splitter_types': [],- 'signal_generators': [],- 'indicator_signal_modes': ['crossover', 'threshold', 'breakout', 'mean_reversion', 'filter'],- 'returns_analysis_types': [],+ 'label_types': ['FIXLB', 'MEANLB', 'LEXLB', 'TRENDLB', 'BOLB'],+ 'splitter_types': ['RollingSplitter', 'ExpandingSplitter', 'PurgedKFoldSplitter'],+ 'signal_generators': ['RAND', 'RANDX', 'RANDNX', 'RPROB', 'RPROBX'],+ 'indicator_signal_modes': ['crossover_signals', 'threshold_signals', 'breakout_signals',+ 'mean_reversion_signals', 'signal_filter'],+ 'returns_analysis_types': ['returns_stats', 'drawdowns', 'ranges', 'rolling'],},}@@ -1873,7 +1877,7 @@ class ZiplineProvider(BacktestingProviderBase):start_date = request.get('startDate', '2023-01-01')end_date = request.get('endDate', '2024-01-01')gen_type = request.get('generatorType', 'RAND')- params = request.get('parameters', {})+ params = request.get('params') or request.get('parameters') or {}seed = int(params.get('seed', 42))close_series, synthetic = self._load_close_series(symbols, start_date, end_date)@@ -2061,7 +2065,7 @@ class ZiplineProvider(BacktestingProviderBase):start_date = request.get('startDate', '2023-01-01')end_date = request.get('endDate', '2024-01-01')label_type = request.get('labelType', 'FIXLB')- params = request.get('parameters', {})+ params = request.get('params') or request.get('parameters') or {}close_series, synthetic = self._load_close_series(symbols, start_date, end_date)close = np.asarray(close_series, dtype=float)@@ -2183,8 +2187,22 @@ class ZiplineProvider(BacktestingProviderBase):symbols = request.get('symbols', ['SPY'])start_date = request.get('startDate', '2023-01-01')end_date = request.get('endDate', '2024-01-01')- splitter_type = request.get('splitterType', 'rolling')- params = request.get('parameters', {})+ # UI sends camelCase splitter names matching vectorbt; map to zipline's+ # internal short names ('rolling' / 'expanding' / 'purged_kfold' / 'range').+ splitter_alias = {+ 'RollingSplitter': 'rolling',+ 'ExpandingSplitter': 'expanding',+ 'PurgedKFoldSplitter': 'purged_kfold',+ 'PurgedKFold': 'purged_kfold',+ 'RangeSplitter': 'range',+ }+ raw_type = request.get('splitterType', 'rolling')+ splitter_type = splitter_alias.get(raw_type, raw_type)+ params = dict(request.get('params') or request.get('parameters') or {})+ # UI exposes a generic WINDOW LENGTH spinbox; map to zipline's windowLen.+ if 'windowLength' in params and 'windowLen' not in params:+ params['windowLen'] = params['windowLength']+ params.setdefault('testLen', max(5, int(params['windowLength']) // 3))close_series, synthetic = self._load_close_series(symbols, start_date, end_date)dates = [str(d.date()) if hasattr(d, 'date') else str(d) for d in close_series.index]@@ -2302,7 +2320,7 @@ class ZiplineProvider(BacktestingProviderBase):start_date = request.get('startDate', '2023-01-01')end_date = request.get('endDate', '2024-01-01')analysis_type = request.get('analysisType', 'returns_stats')- params = request.get('parameters', {})+ params = request.get('params') or request.get('parameters') or {}close_series, synthetic = self._load_close_series(symbols, start_date, end_date)close = np.asarray(close_series, dtype=float)@@ -2585,7 +2603,7 @@ class ZiplineProvider(BacktestingProviderBase):start_date = request.get('startDate', '2023-01-01')end_date = request.get('endDate', '2024-01-01')label_type = request.get('labelType', 'FIXLB')- params = request.get('parameters', {})+ params = request.get('params') or request.get('parameters') or {}entry_label = int(params.get('entryLabel', 1))exit_label = int(params.get('exitLabel', -1))diff --git a/fincept-qt/scripts/diagnose-macos-crash.sh b/fincept-qt/scripts/diagnose-macos-crash.shnew file mode 100755index 000000000..5a6b02b26--- /dev/null+++ b/fincept-qt/scripts/diagnose-macos-crash.sh@@ -0,0 +1,143 @@+#!/usr/bin/env bash+# diagnose-macos-crash.sh — launch FinceptTerminal under macOS' malloc+# debugging instrumentation so a use-after-free / wild-pointer crash+# fails LOUDLY at the use site (not 2+ hours later when the freed+# region happens to get reused).+#+# Usage:+# scripts/diagnose-macos-crash.sh # signed bundle from build/macos-release+# scripts/diagnose-macos-crash.sh path/to/Fincept.app # any bundle+# scripts/diagnose-macos-crash.sh --asan # build/macos-asan binary+#+# When the app crashes:+# 1. Note the crash address (often shown as `far=0x…` or in x-registers).+# 2. If the address is `0x55…55` — that's MallocScribble's signature.+# The freed region was written before reuse → confirmed UAF.+# 3. Run:+# malloc_history $(pgrep FinceptTerminal) -allEvents <addr>+# (or pass a memgraph file if the app already exited).+# 4. The output shows the EXACT alloc backtrace + free backtrace+# for that address. Root cause becomes a single grep.+#+# References:+# - https://developer.apple.com/library/archive/documentation/Performance/Conceptual/ManagingMemory/Articles/MallocDebug.html+# - https://keith.github.io/xcode-man-pages/malloc_history.1.html+# - https://forum.qt.io/topic/135220/random-application-crash-on-apple-silicon-m1-qt-6-2-3/42++set -euo pipefail++# ── Locate the .app bundle ────────────────────────────────────────────────────+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+REPO_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"++MODE="signed"+TARGET=""+while [[ $# -gt 0 ]]; do+ case "$1" in+ --asan)+ MODE="asan"+ shift+ ;;+ --help|-h)+ sed -n '2,/^set -e/p' "$0" | sed 's/^# \{0,1\}//'+ exit 0+ ;;+ *)+ TARGET="$1"+ shift+ ;;+ esac+done++if [[ -z "${TARGET}" ]]; then+ if [[ "${MODE}" == "asan" ]]; then+ TARGET="${REPO_DIR}/build/macos-asan/FinceptTerminal.app"+ else+ TARGET="${REPO_DIR}/build/macos-release/FinceptTerminal.app"+ fi+fi++if [[ ! -d "${TARGET}" ]]; then+ echo "error: bundle not found at ${TARGET}" >&2+ echo " build it first:" >&2+ if [[ "${MODE}" == "asan" ]]; then+ echo " cmake --preset macos-asan && cmake --build build/macos-asan" >&2+ else+ echo " cmake --preset macos-release && cmake --build build/macos-release" >&2+ fi+ exit 1+fi++BIN="${TARGET}/Contents/MacOS/FinceptTerminal"+if [[ ! -x "${BIN}" ]]; then+ echo "error: executable missing or not executable: ${BIN}" >&2+ exit 1+fi++# ── Malloc instrumentation (works on signed bundles too) ──────────────────────+# MallocStackLoggingNoCompact: record every alloc + free with full backtrace.+# MallocScribble: fill freed memory with 0x55 → crash at use site.+# MallocGuardEdges: place guard pages around allocations.+# MallocCheckHeapEach: periodic heap consistency check (slows runtime).+#+# These work on shipped, signed, notarised apps — no rebuild required.+# Performance cost: app runs ~2-5× slower; memory usage ~2-3× higher.+# That's fine for a diagnostic session; it's not a release config.+export MallocStackLoggingNoCompact=1+export MallocScribble=1+export MallocGuardEdges=1+export MallocErrorAbort=1+export MallocCheckHeapEach=10000++# ── Qt logging — surface socket / network / TLS lifecycle ─────────────────────+# These categories print to stderr; redirect to a file via the wrapper below.+# Disabled by default in Release builds; explicit rules re-enable them.+export QT_LOGGING_RULES="qt.network.*=true;qt.qpa.events=false;qt.qpa.input.events=false"+export QT_FATAL_WARNINGS=0 # set to 1 to abort on first Qt warning (sometimes useful)++# ── ASan options if running an ASan build ─────────────────────────────────────+if [[ "${MODE}" == "asan" ]]; then+ export ASAN_OPTIONS="detect_leaks=0:halt_on_error=1:abort_on_error=1:print_stacktrace=1:strict_string_checks=1:detect_stack_use_after_return=1:check_initialization_order=1:strict_init_order=1"+ export UBSAN_OPTIONS="halt_on_error=1:abort_on_error=1:print_stacktrace=1"+fi++# ── Launch ────────────────────────────────────────────────────────────────────+LOG_DIR="${REPO_DIR}/diagnostic-logs"+mkdir -p "${LOG_DIR}"+STAMP="$(date +%Y%m%d-%H%M%S)"+LOG_FILE="${LOG_DIR}/fincept-${MODE}-${STAMP}.log"++echo "──────────────────────────────────────────────────────────────────────"+echo " Diagnostic launch: ${MODE}"+echo " Binary: ${BIN}"+echo " Log file: ${LOG_FILE}"+echo ""+echo " When it crashes:"+echo " 1. Note the crash address (look for far= or x19/x20 in crash log)"+echo " 2. Run: malloc_history \$(pgrep FinceptTerminal) -allEvents <addr>"+echo " (or post-mortem on the ips file under ~/Library/Logs/DiagnosticReports/)"+echo " 3. The alloc + free stacks pinpoint the leaking owner."+echo "──────────────────────────────────────────────────────────────────────"++# Use `tee` so we can both watch the run live AND keep a permanent log.+# `script` would capture pty colors but we want plain text for grep.+"${BIN}" 2>&1 | tee "${LOG_FILE}"+EXIT_CODE=${PIPESTATUS[0]}++if [[ "${EXIT_CODE}" -ne 0 ]]; then+ echo ""+ echo "── Process exited with code ${EXIT_CODE} ──────────────────────────────"+ echo "Log saved to: ${LOG_FILE}"+ # If the crash registered with ReportCrash, point at it.+ LATEST_IPS="$(ls -t ~/Library/Logs/DiagnosticReports/FinceptTerminal-*.ips 2>/dev/null | head -1 || true)"+ if [[ -n "${LATEST_IPS}" ]]; then+ echo "Latest crash report: ${LATEST_IPS}"+ echo ""+ echo "Faulting addresses (from crash report):"+ # 'far' is the Translation-fault target address on ARM64; x19/x20 are+ # commonly the stale-pointer holders in doActivate-style crashes.+ grep -E 'far:|x19:|x20:' "${LATEST_IPS}" | head -5 || true+ fi+fi++exit "${EXIT_CODE}"diff --git a/fincept-qt/src/ai_chat/LlmHttpHelpers.cpp b/fincept-qt/src/ai_chat/LlmHttpHelpers.cppindex 38d742eed..d23132df5 100644--- a/fincept-qt/src/ai_chat/LlmHttpHelpers.cpp+++ b/fincept-qt/src/ai_chat/LlmHttpHelpers.cpp@@ -4,6 +4,8 @@#include "ai_chat/LlmService.h"+#include <QCoreApplication>+#include <QEvent>#include <QEventLoop>#include <QJsonArray>#include <QJsonDocument>@@ -41,13 +43,24 @@ LlmService::HttpResult LlmService::blocking_get(const QString& url, const QMap<QLlmService::HttpResult LlmService::eventloop_request(const QString& method, const QString& url, const QByteArray& body,const QMap<QString, QString>& headers, int timeout_ms) {HttpResult result;- QNetworkAccessManager nam;++ // ── Lifetime note ─────────────────────────────────────────────────────────+ // The QNetworkAccessManager and its QNetworkReply MUST outlive the local+ // QEventLoop *and* drain pending DeferredDelete events before this+ // function returns. A stack-allocated QNAM here used to crash the main+ // thread hours later (issue: KERN_INVALID_ADDRESS @ 0x3f inside+ // QIODevice::channelReadyRead via qt_mac_socket_callback) — Qt's macOS+ // CFSocket bridge fires runloop callbacks against socket QObjects whose+ // d_ptr has been torn down with the NAM. Heap-allocate and explicitly+ // process DeferredDelete so the socket-notifier teardown completes+ // before the function returns.+ auto* nam = new QNetworkAccessManager;QNetworkRequest req{QUrl(url)};req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");for (auto it = headers.constBegin(); it != headers.constEnd(); ++it)req.setRawHeader(it.key().toUtf8(), it.value().toUtf8());- QNetworkReply* reply = (method == "GET") ? nam.get(req) : nam.post(req, body);+ QNetworkReply* reply = (method == "GET") ? nam->get(req) : nam->post(req, body);QEventLoop loop;QTimer timer;@@ -57,10 +70,18 @@ LlmService::HttpResult LlmService::eventloop_request(const QString& method, consQObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);loop.exec();+ auto drain = [&]() {+ reply->deleteLater();+ nam->deleteLater();+ // Drain DeferredDelete events on the current thread so the NAM and+ // its socket subscribers tear down while a dispatcher still exists.+ QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);+ };+if (!reply->isFinished()) {reply->abort();- reply->deleteLater();result.error = "Request timed out";+ drain();return result;}@@ -94,7 +115,7 @@ LlmService::HttpResult LlmService::eventloop_request(const QString& method, consresult.error = server_msg.isEmpty() ? QString("HTTP %1: %2").arg(result.status).arg(reply->errorString()): QString("HTTP %1: %2").arg(result.status).arg(server_msg);}- reply->deleteLater();+ drain();return result;}diff --git a/fincept-qt/src/ai_chat/LlmService.cpp b/fincept-qt/src/ai_chat/LlmService.cppindex 5866c765f..8a0558085 100644--- a/fincept-qt/src/ai_chat/LlmService.cpp+++ b/fincept-qt/src/ai_chat/LlmService.cpp@@ -17,6 +17,8 @@# include "datahub/DataHub.h"# include "datahub/TopicPolicy.h"+#include <QCoreApplication>+#include <QEvent>#include <QEventLoop>#include <QJsonDocument>#include <QJsonObject>@@ -694,7 +696,11 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,QJsonObject req_body = (provider_ == "anthropic") ? build_anthropic_request(user_message, history, true): build_openai_request(user_message, history, true, true);- QNetworkAccessManager nam;+ // Heap-allocate the QNAM so we can deleteLater() it and drain+ // DeferredDelete before this function returns — a stack QNAM here used+ // to leak socket-notifier teardown work onto the main runloop and crash+ // hours later inside qt_mac_socket_callback. See eventloop_request().+ auto* nam = new QNetworkAccessManager;QNetworkRequest req{QUrl(url)};req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");req.setRawHeader("Accept", "text/event-stream");@@ -702,7 +708,7 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,req.setRawHeader(it.key().toUtf8(), it.value().toUtf8());QByteArray json_data = QJsonDocument(req_body).toJson(QJsonDocument::Compact);- QNetworkReply* reply = nam.post(req, json_data);+ QNetworkReply* reply = nam->post(req, json_data);QByteArray partial_line;QString accumulated;@@ -832,10 +838,19 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,loop.exec();timeout.stop();+ auto drain_nam = [&]() {+ reply->deleteLater();+ nam->deleteLater();+ // Pump DeferredDelete on this thread so socket-notifier teardown+ // completes while a dispatcher still exists — prevents the+ // qt_mac_socket_callback use-after-free on the main thread later.+ QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);+ };+if (tool_call_detected) {LOG_INFO(kLlmSvcTag, "Tool call detected in stream — falling back to tool loop");reply->abort();- reply->deleteLater();+ drain_nam();// Sentinel tells the chat screen to reset the bubble before the real reply arrives.on_chunk("\x01__TOOL_CALL_CLEAR__", false);@@ -862,7 +877,7 @@ LlmResponse LlmService::do_streaming_request(const QString& user_message,resp.error = QString("HTTP %1").arg(status);}- reply->deleteLater();+ drain_nam();if (!done)on_chunk("", true);diff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp b/fincept-qt/src/screens/backtesting/BacktestingScreen.cppindex 2f9f768fb..49a98b69d 100644--- a/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen.cpp@@ -20,6 +20,7 @@#include <QScrollArea>#include <QSplitter>+#include <algorithm>#include <cmath>namespace fincept::screens {@@ -324,11 +325,17 @@ QWidget* BacktestingScreen::build_left_panel() {command_buttons_.append(btn);}- // ── Strategies section ──- vl->addSpacing(8);- auto* strat_title = new QLabel("STRATEGY", content);+ // ── Strategy block (only meaningful for backtest/optimize/walk_forward) ──+ // Wrapped in a named container so update_section_visibility() can hide it+ // when the active command doesn't run a strategy (ML labels, splits, etc.).+ strategy_section_ = new QWidget(content);+ auto* strat_outer = new QVBoxLayout(strategy_section_);+ strat_outer->setContentsMargins(0, 8, 0, 0);+ strat_outer->setSpacing(4);++ auto* strat_title = new QLabel("STRATEGY", strategy_section_);strat_title->setStyleSheet(section_style);- vl->addWidget(strat_title);+ strat_outer->addWidget(strat_title);auto combo_style = QString("QComboBox { background:%1; color:%2; border:1px solid %3;""font-family:%4; font-size:%5px; padding:4px 6px; }"@@ -339,36 +346,35 @@ QWidget* BacktestingScreen::build_left_panel() {.arg(ui::fonts::DATA_FAMILY).arg(ui::fonts::SMALL);- auto* cat_lbl = new QLabel("CATEGORY", content);+ auto* cat_lbl = new QLabel("CATEGORY", strategy_section_);cat_lbl->setStyleSheet(label_style);- vl->addWidget(cat_lbl);- strategy_category_combo_ = new QComboBox(content);+ strat_outer->addWidget(cat_lbl);+ strategy_category_combo_ = new QComboBox(strategy_section_);strategy_category_combo_->setStyleSheet(combo_style);- // Populated dynamically via on_result("get_strategies")connect(strategy_category_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,[this](int) { populate_strategies(); });- vl->addWidget(strategy_category_combo_);+ strat_outer->addWidget(strategy_category_combo_);- auto* strat_lbl = new QLabel("STRATEGY", content);+ auto* strat_lbl = new QLabel("STRATEGY", strategy_section_);strat_lbl->setStyleSheet(label_style);- vl->addWidget(strat_lbl);- strategy_combo_ = new QComboBox(content);+ strat_outer->addWidget(strat_lbl);+ strategy_combo_ = new QComboBox(strategy_section_);strategy_combo_->setStyleSheet(combo_style);connect(strategy_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,&BacktestingScreen::on_strategy_changed);- vl->addWidget(strategy_combo_);+ strat_outer->addWidget(strategy_combo_);- // ── Strategy parameters ──- vl->addSpacing(4);- auto* params_title = new QLabel("PARAMETERS", content);+ auto* params_title = new QLabel("PARAMETERS", strategy_section_);params_title->setStyleSheet(label_style);- vl->addWidget(params_title);+ strat_outer->addWidget(params_title);- strategy_params_container_ = new QWidget(content);+ strategy_params_container_ = new QWidget(strategy_section_);strategy_params_layout_ = new QVBoxLayout(strategy_params_container_);strategy_params_layout_->setContentsMargins(0, 0, 0, 0);strategy_params_layout_->setSpacing(4);- vl->addWidget(strategy_params_container_);+ strat_outer->addWidget(strategy_params_container_);++ vl->addWidget(strategy_section_);vl->addStretch();scroll->setWidget(content);@@ -505,7 +511,7 @@ QWidget* BacktestingScreen::build_center_panel() {trades_table_->horizontalHeader()->setStretchLastSection(true);trades_table_->verticalHeader()->setVisible(false);trades_table_->setStyleSheet(metrics_table_->styleSheet());- result_tabs_->addTab(trades_table_, "TRADES");+ result_tabs_->addTab(trades_table_, "DETAILS");// RAW JSON tabraw_json_edit_ = new QTextEdit;@@ -577,131 +583,151 @@ QWidget* BacktestingScreen::build_right_panel() {.arg(ui::fonts::DATA_FAMILY).arg(ui::fonts::SMALL);- // ── MARKET DATA ──- auto* mkt_title = new QLabel("MARKET DATA", content);+ // Each section is a named QWidget so update_section_visibility() can+ // toggle whole blocks at once depending on the active command.++ // ── MARKET DATA (always shown) ──+ market_data_section_ = new QWidget(content);+ auto* mkt_layout = new QVBoxLayout(market_data_section_);+ mkt_layout->setContentsMargins(0, 0, 0, 0);+ mkt_layout->setSpacing(4);++ auto* mkt_title = new QLabel("MARKET DATA", market_data_section_);mkt_title->setStyleSheet(section_style);- vl->addWidget(mkt_title);+ mkt_layout->addWidget(mkt_title);- auto* sym_lbl = new QLabel("SYMBOLS", content);+ auto* sym_lbl = new QLabel("SYMBOLS", market_data_section_);sym_lbl->setStyleSheet(label_style);- vl->addWidget(sym_lbl);- symbols_edit_ = new QLineEdit("SPY", content);+ mkt_layout->addWidget(sym_lbl);+ symbols_edit_ = new QLineEdit("SPY", market_data_section_);symbols_edit_->setPlaceholderText("SPY,AAPL,MSFT");symbols_edit_->setStyleSheet(input_style);- vl->addWidget(symbols_edit_);- // Publish the first symbol to the linked group when the user finishes editing.+ mkt_layout->addWidget(symbols_edit_);connect(symbols_edit_, &QLineEdit::editingFinished, this,[this]() { publish_first_symbol_to_group(); });- auto* cap_lbl = new QLabel("INITIAL CAPITAL ($)", content);- cap_lbl->setStyleSheet(label_style);- vl->addWidget(cap_lbl);- capital_spin_ = new QDoubleSpinBox(content);- capital_spin_->setRange(1000, 1e12);- capital_spin_->setValue(100000);- capital_spin_->setDecimals(0);- capital_spin_->setStyleSheet(input_style);- vl->addWidget(capital_spin_);-auto* dates = new QGridLayout;dates->setSpacing(8);- auto* sd_lbl = new QLabel("START", content);+ auto* sd_lbl = new QLabel("START", market_data_section_);sd_lbl->setStyleSheet(label_style);dates->addWidget(sd_lbl, 0, 0);- start_date_ = new QDateEdit(QDate::currentDate().addYears(-1), content);+ start_date_ = new QDateEdit(QDate::currentDate().addYears(-1), market_data_section_);start_date_->setDisplayFormat("yyyy-MM-dd");start_date_->setCalendarPopup(true);start_date_->setStyleSheet(input_style);dates->addWidget(start_date_, 1, 0);- auto* ed_lbl = new QLabel("END", content);+ auto* ed_lbl = new QLabel("END", market_data_section_);ed_lbl->setStyleSheet(label_style);dates->addWidget(ed_lbl, 0, 1);- end_date_ = new QDateEdit(QDate::currentDate().addDays(-1), content);+ end_date_ = new QDateEdit(QDate::currentDate().addDays(-1), market_data_section_);end_date_->setDisplayFormat("yyyy-MM-dd");end_date_->setCalendarPopup(true);end_date_->setStyleSheet(input_style);dates->addWidget(end_date_, 1, 1);- vl->addLayout(dates);+ mkt_layout->addLayout(dates);- // ── EXECUTION SETTINGS ──- vl->addSpacing(8);- auto* exec_title = new QLabel("EXECUTION", content);+ vl->addWidget(market_data_section_);++ // ── EXECUTION (backtest-family only) ──+ // Holds the cost/cash-flow knobs: initial capital, commission, slippage.+ execution_section_ = new QWidget(content);+ auto* exec_layout = new QVBoxLayout(execution_section_);+ exec_layout->setContentsMargins(0, 8, 0, 0);+ exec_layout->setSpacing(4);++ auto* exec_title = new QLabel("EXECUTION", execution_section_);exec_title->setStyleSheet(section_style);- vl->addWidget(exec_title);+ exec_layout->addWidget(exec_title);++ auto* cap_lbl = new QLabel("INITIAL CAPITAL ($)", execution_section_);+ cap_lbl->setStyleSheet(label_style);+ exec_layout->addWidget(cap_lbl);+ capital_spin_ = new QDoubleSpinBox(execution_section_);+ capital_spin_->setRange(1000, 1e12);+ capital_spin_->setValue(100000);+ capital_spin_->setDecimals(0);+ capital_spin_->setStyleSheet(input_style);+ exec_layout->addWidget(capital_spin_);- auto* comm_lbl = new QLabel("COMMISSION (%)", content);+ auto* comm_lbl = new QLabel("COMMISSION (%)", execution_section_);comm_lbl->setStyleSheet(label_style);- vl->addWidget(comm_lbl);- commission_spin_ = new QDoubleSpinBox(content);+ exec_layout->addWidget(comm_lbl);+ commission_spin_ = new QDoubleSpinBox(execution_section_);commission_spin_->setRange(0, 10);commission_spin_->setValue(0.1);commission_spin_->setDecimals(3);commission_spin_->setSuffix("%");commission_spin_->setStyleSheet(input_style);- vl->addWidget(commission_spin_);+ exec_layout->addWidget(commission_spin_);- auto* slip_lbl = new QLabel("SLIPPAGE (%)", content);+ auto* slip_lbl = new QLabel("SLIPPAGE (%)", execution_section_);slip_lbl->setStyleSheet(label_style);- vl->addWidget(slip_lbl);- slippage_spin_ = new QDoubleSpinBox(content);+ exec_layout->addWidget(slip_lbl);+ slippage_spin_ = new QDoubleSpinBox(execution_section_);slippage_spin_->setRange(0, 10);slippage_spin_->setValue(0.05);slippage_spin_->setDecimals(4);slippage_spin_->setSuffix("%");slippage_spin_->setStyleSheet(input_style);- vl->addWidget(slippage_spin_);+ exec_layout->addWidget(slippage_spin_);- // ── ADVANCED ──- vl->addSpacing(8);- auto* adv_title = new QLabel("ADVANCED", content);+ vl->addWidget(execution_section_);++ // ── ADVANCED (backtest-family only) ──+ advanced_section_ = new QWidget(content);+ auto* adv_layout = new QVBoxLayout(advanced_section_);+ adv_layout->setContentsMargins(0, 8, 0, 0);+ adv_layout->setSpacing(4);++ auto* adv_title = new QLabel("ADVANCED", advanced_section_);adv_title->setStyleSheet(section_style);- vl->addWidget(adv_title);+ adv_layout->addWidget(adv_title);- auto* lev_lbl = new QLabel("LEVERAGE", content);+ auto* lev_lbl = new QLabel("LEVERAGE", advanced_section_);lev_lbl->setStyleSheet(label_style);- vl->addWidget(lev_lbl);- leverage_spin_ = new QDoubleSpinBox(content);+ adv_layout->addWidget(lev_lbl);+ leverage_spin_ = new QDoubleSpinBox(advanced_section_);leverage_spin_->setRange(0.1, 10);leverage_spin_->setValue(1.0);leverage_spin_->setDecimals(1);leverage_spin_->setSuffix("x");leverage_spin_->setStyleSheet(input_style);- vl->addWidget(leverage_spin_);+ adv_layout->addWidget(leverage_spin_);- auto* sl_lbl = new QLabel("STOP LOSS (%)", content);+ auto* sl_lbl = new QLabel("STOP LOSS (%)", advanced_section_);sl_lbl->setStyleSheet(label_style);- vl->addWidget(sl_lbl);- stop_loss_spin_ = new QDoubleSpinBox(content);+ adv_layout->addWidget(sl_lbl);+ stop_loss_spin_ = new QDoubleSpinBox(advanced_section_);stop_loss_spin_->setRange(0, 100);stop_loss_spin_->setValue(0);stop_loss_spin_->setDecimals(1);stop_loss_spin_->setSuffix("%");stop_loss_spin_->setSpecialValueText("None");stop_loss_spin_->setStyleSheet(input_style);- vl->addWidget(stop_loss_spin_);+ adv_layout->addWidget(stop_loss_spin_);- auto* tp_lbl = new QLabel("TAKE PROFIT (%)", content);+ auto* tp_lbl = new QLabel("TAKE PROFIT (%)", advanced_section_);tp_lbl->setStyleSheet(label_style);- vl->addWidget(tp_lbl);- take_profit_spin_ = new QDoubleSpinBox(content);+ adv_layout->addWidget(tp_lbl);+ take_profit_spin_ = new QDoubleSpinBox(advanced_section_);take_profit_spin_->setRange(0, 1000);take_profit_spin_->setValue(0);take_profit_spin_->setDecimals(1);take_profit_spin_->setSuffix("%");take_profit_spin_->setSpecialValueText("None");take_profit_spin_->setStyleSheet(input_style);- vl->addWidget(take_profit_spin_);+ adv_layout->addWidget(take_profit_spin_);- auto* ps_lbl = new QLabel("POSITION SIZING", content);+ auto* ps_lbl = new QLabel("POSITION SIZING", advanced_section_);ps_lbl->setStyleSheet(label_style);- vl->addWidget(ps_lbl);- pos_sizing_combo_ = new QComboBox(content);+ adv_layout->addWidget(ps_lbl);+ pos_sizing_combo_ = new QComboBox(advanced_section_);pos_sizing_combo_->setStyleSheet(combo_style);for (const auto& m : position_sizing_methods())pos_sizing_combo_->addItem(m);- vl->addWidget(pos_sizing_combo_);+ adv_layout->addWidget(pos_sizing_combo_);- allow_short_check_ = new QCheckBox("Allow Short Selling", content);+ allow_short_check_ = new QCheckBox("Allow Short Selling", advanced_section_);allow_short_check_->setStyleSheet(QString("QCheckBox { color:%1; font-family:%2; font-size:%3px; spacing:6px; }""QCheckBox::indicator { width:14px; height:14px; border:1px solid %4; background:%5; }"@@ -712,14 +738,30 @@ QWidget* BacktestingScreen::build_right_panel() {.arg(ui::colors::BORDER_MED()).arg(ui::colors::BG_RAISED()).arg(ui::colors::AMBER()));- vl->addWidget(allow_short_check_);+ adv_layout->addWidget(allow_short_check_);++ vl->addWidget(advanced_section_);- auto* bm_lbl = new QLabel("BENCHMARK", content);+ // ── BENCHMARK (backtest-family + returns) ──+ // Used as the comparison baseline for performance metrics and for the+ // benchmark-aware returns_stats analysis (alpha/beta/info-ratio).+ benchmark_section_ = new QWidget(content);+ auto* bm_layout = new QVBoxLayout(benchmark_section_);+ bm_layout->setContentsMargins(0, 8, 0, 0);+ bm_layout->setSpacing(4);++ auto* bm_title = new QLabel("BENCHMARK", benchmark_section_);+ bm_title->setStyleSheet(section_style);+ bm_layout->addWidget(bm_title);++ auto* bm_lbl = new QLabel("SYMBOL", benchmark_section_);bm_lbl->setStyleSheet(label_style);- vl->addWidget(bm_lbl);- benchmark_edit_ = new QLineEdit("SPY", content);+ bm_layout->addWidget(bm_lbl);+ benchmark_edit_ = new QLineEdit("SPY", benchmark_section_);benchmark_edit_->setStyleSheet(input_style);- vl->addWidget(benchmark_edit_);+ bm_layout->addWidget(benchmark_edit_);++ vl->addWidget(benchmark_section_);// ── COMMAND-SPECIFIC CONFIG ──vl->addSpacing(8);@@ -821,6 +863,15 @@ QWidget* BacktestingScreen::build_right_panel() {// Populated dynamically via on_result("get_indicators")pl->addWidget(indicator_combo_);+ auto* pl_period = new QLabel("PERIOD", page);+ pl_period->setStyleSheet(label_style);+ pl->addWidget(pl_period);+ indicator_period_spin_ = new QSpinBox(page);+ indicator_period_spin_->setRange(2, 500);+ indicator_period_spin_->setValue(14);+ indicator_period_spin_->setStyleSheet(input_style);+ pl->addWidget(indicator_period_spin_);+pl->addStretch();cmd_config_stack_->addWidget(page);}@@ -852,11 +903,114 @@ QWidget* BacktestingScreen::build_right_panel() {ind_signal_mode_combo_->addItem(m);pl->addWidget(ind_signal_mode_combo_);+ // Helpers+ auto make_int_row = [&](const QString& text, QSpinBox*& spin, int mn, int mx, int dv) -> QWidget* {+ auto* row = new QWidget(page);+ auto* rl = new QVBoxLayout(row);+ rl->setContentsMargins(0, 0, 0, 0); rl->setSpacing(4);+ auto* lab = new QLabel(text, row); lab->setStyleSheet(label_style);+ rl->addWidget(lab);+ spin = new QSpinBox(row);+ spin->setRange(mn, mx); spin->setValue(dv); spin->setStyleSheet(input_style);+ rl->addWidget(spin);+ return row;+ };+ auto make_dbl_row = [&](const QString& text, QDoubleSpinBox*& spin,+ double mn, double mx, double dv, int decimals = 2) -> QWidget* {+ auto* row = new QWidget(page);+ auto* rl = new QVBoxLayout(row);+ rl->setContentsMargins(0, 0, 0, 0); rl->setSpacing(4);+ auto* lab = new QLabel(text, row); lab->setStyleSheet(label_style);+ rl->addWidget(lab);+ spin = new QDoubleSpinBox(row);+ spin->setRange(mn, mx); spin->setValue(dv);+ spin->setDecimals(decimals); spin->setStyleSheet(input_style);+ rl->addWidget(spin);+ return row;+ };+ auto make_combo_row = [&](const QString& text, QComboBox*& combo,+ const QStringList& items) -> QWidget* {+ auto* row = new QWidget(page);+ auto* rl = new QVBoxLayout(row);+ rl->setContentsMargins(0, 0, 0, 0); rl->setSpacing(4);+ auto* lab = new QLabel(text, row); lab->setStyleSheet(label_style);+ rl->addWidget(lab);+ combo = new QComboBox(row);+ combo->setStyleSheet(combo_style);+ for (const auto& it : items) combo->addItem(it);+ rl->addWidget(combo);+ return row;+ };++ // ── crossover_signals: fast period + slow period + ma type ──+ is_fast_period_row_ = make_int_row("FAST PERIOD", is_fast_period_spin_, 2, 200, 10);+ is_slow_period_row_ = make_int_row("SLOW PERIOD", is_slow_period_spin_, 2, 500, 20);+ is_ma_type_row_ = make_combo_row("MA TYPE", is_ma_type_combo_, {"ma", "ema"});+ pl->addWidget(is_fast_period_row_);+ pl->addWidget(is_slow_period_row_);+ pl->addWidget(is_ma_type_row_);++ // ── threshold_signals: period + lower + upper ──+ is_period_row_ = make_int_row("PERIOD", is_period_spin_, 2, 200, 14);+ is_lower_row_ = make_dbl_row("LOWER THRESHOLD", is_lower_spin_, -200, 200, 30);+ is_upper_row_ = make_dbl_row("UPPER THRESHOLD", is_upper_spin_, -200, 200, 70);+ pl->addWidget(is_period_row_);+ pl->addWidget(is_lower_row_);+ pl->addWidget(is_upper_row_);++ // ── breakout_signals: channel + period (shares is_period) ──+ is_channel_row_ = make_combo_row("CHANNEL", is_channel_combo_, {"donchian", "bbands", "keltner"});+ pl->addWidget(is_channel_row_);++ // ── mean_reversion_signals: period + z_entry + z_exit ──+ is_z_entry_row_ = make_dbl_row("Z ENTRY (sigma)", is_z_entry_spin_, 0.1, 5.0, 2.0, 2);+ is_z_exit_row_ = make_dbl_row("Z EXIT (sigma)", is_z_exit_spin_, 0.0, 5.0, 0.0, 2);+ pl->addWidget(is_z_entry_row_);+ pl->addWidget(is_z_exit_row_);++ // ── signal_filter: filter_indicator + filter_period + filter_threshold + filter_type ──+ is_filter_indicator_row_ = make_combo_row("FILTER INDICATOR", is_filter_indicator_combo_,+ {"adx", "atr", "mstd", "zscore", "rsi"});+ is_filter_period_row_ = make_int_row("FILTER PERIOD", is_filter_period_spin_, 2, 200, 14);+ is_filter_threshold_row_ = make_dbl_row("FILTER THRESHOLD", is_filter_threshold_spin_,+ -100, 100, 25, 3);+ is_filter_type_row_ = make_combo_row("FILTER TYPE", is_filter_type_combo_, {"above", "below"});+ pl->addWidget(is_filter_indicator_row_);+ pl->addWidget(is_filter_period_row_);+ pl->addWidget(is_filter_threshold_row_);+ pl->addWidget(is_filter_type_row_);++ auto update_is_rows = [this]() {+ const QString m = ind_signal_mode_combo_->currentText();+ const bool is_cross = (m == "crossover_signals" || m == "crossover");+ const bool is_thresh = (m == "threshold_signals" || m == "threshold");+ const bool is_break = (m == "breakout_signals" || m == "breakout");+ const bool is_mr = (m == "mean_reversion_signals" || m == "mean_reversion");+ const bool is_filt = (m == "signal_filter" || m == "filter");+ is_fast_period_row_->setVisible(is_cross);+ is_slow_period_row_->setVisible(is_cross);+ is_ma_type_row_->setVisible(is_cross);+ // PERIOD reused by threshold + breakout + mean_reversion (+ filter base period inferred).+ is_period_row_->setVisible(is_thresh || is_break || is_mr);+ is_lower_row_->setVisible(is_thresh);+ is_upper_row_->setVisible(is_thresh);+ is_channel_row_->setVisible(is_break);+ is_z_entry_row_->setVisible(is_mr);+ is_z_exit_row_->setVisible(is_mr);+ is_filter_indicator_row_->setVisible(is_filt);+ is_filter_period_row_->setVisible(is_filt);+ is_filter_threshold_row_->setVisible(is_filt);+ is_filter_type_row_->setVisible(is_filt);+ };+ connect(ind_signal_mode_combo_, &QComboBox::currentTextChanged, this,+ [update_is_rows](const QString&) { update_is_rows(); });+ update_is_rows();+pl->addStretch();cmd_config_stack_->addWidget(page);}- // Page 5: labels+ // Page 5: labels — params shown depend on the selected label generator.{auto* page = new QWidget(this);auto* pl = new QVBoxLayout(page);@@ -875,31 +1029,88 @@ QWidget* BacktestingScreen::build_right_panel() {labels_type_combo_->addItem(lt);pl->addWidget(labels_type_combo_);- auto* hl = new QLabel("HORIZON", page);+ // ── HORIZON row (FIXLB only) ──+ labels_horizon_row_ = new QWidget(page);+ auto* hr = new QVBoxLayout(labels_horizon_row_);+ hr->setContentsMargins(0, 0, 0, 0);+ hr->setSpacing(4);+ auto* hl = new QLabel("HORIZON (bars)", labels_horizon_row_);hl->setStyleSheet(label_style);- pl->addWidget(hl);- labels_horizon_spin_ = new QSpinBox(page);+ hr->addWidget(hl);+ labels_horizon_spin_ = new QSpinBox(labels_horizon_row_);labels_horizon_spin_->setRange(1, 100);labels_horizon_spin_->setValue(5);labels_horizon_spin_->setStyleSheet(input_style);- pl->addWidget(labels_horizon_spin_);-- auto* thl = new QLabel("THRESHOLD", page);+ hr->addWidget(labels_horizon_spin_);+ pl->addWidget(labels_horizon_row_);++ // ── WINDOW row (MEANLB / LEXLB / TRENDLB / BOLB) ──+ labels_window_row_ = new QWidget(page);+ auto* wr = new QVBoxLayout(labels_window_row_);+ wr->setContentsMargins(0, 0, 0, 0);+ wr->setSpacing(4);+ auto* wl = new QLabel("WINDOW", labels_window_row_);+ wl->setStyleSheet(label_style);+ wr->addWidget(wl);+ labels_window_spin_ = new QSpinBox(labels_window_row_);+ labels_window_spin_->setRange(2, 500);+ labels_window_spin_->setValue(20);+ labels_window_spin_->setStyleSheet(input_style);+ wr->addWidget(labels_window_spin_);+ pl->addWidget(labels_window_row_);++ // ── THRESHOLD row (FIXLB / MEANLB / TRENDLB) ──+ labels_threshold_row_ = new QWidget(page);+ auto* tr = new QVBoxLayout(labels_threshold_row_);+ tr->setContentsMargins(0, 0, 0, 0);+ tr->setSpacing(4);+ auto* thl = new QLabel("THRESHOLD", labels_threshold_row_);thl->setStyleSheet(label_style);- pl->addWidget(thl);- labels_threshold_spin_ = new QDoubleSpinBox(page);- labels_threshold_spin_->setRange(0.001, 1.0);+ tr->addWidget(thl);+ labels_threshold_spin_ = new QDoubleSpinBox(labels_threshold_row_);+ labels_threshold_spin_->setRange(0.0, 5.0);labels_threshold_spin_->setValue(0.02);labels_threshold_spin_->setDecimals(3);labels_threshold_spin_->setSingleStep(0.005);labels_threshold_spin_->setStyleSheet(input_style);- pl->addWidget(labels_threshold_spin_);+ tr->addWidget(labels_threshold_spin_);+ pl->addWidget(labels_threshold_row_);++ // ── ALPHA row (BOLB only — Bollinger Band sigma multiplier) ──+ labels_alpha_row_ = new QWidget(page);+ auto* ar = new QVBoxLayout(labels_alpha_row_);+ ar->setContentsMargins(0, 0, 0, 0);+ ar->setSpacing(4);+ auto* al = new QLabel("ALPHA (sigma)", labels_alpha_row_);+ al->setStyleSheet(label_style);+ ar->addWidget(al);+ labels_alpha_spin_ = new QDoubleSpinBox(labels_alpha_row_);+ labels_alpha_spin_->setRange(0.1, 5.0);+ labels_alpha_spin_->setValue(2.0);+ labels_alpha_spin_->setDecimals(2);+ labels_alpha_spin_->setSingleStep(0.1);+ labels_alpha_spin_->setStyleSheet(input_style);+ ar->addWidget(labels_alpha_spin_);+ pl->addWidget(labels_alpha_row_);++ // Toggle row visibility based on the chosen label generator.+ auto update_label_rows = [this]() {+ const QString lt = labels_type_combo_->currentText();+ labels_horizon_row_->setVisible(lt == "FIXLB");+ labels_window_row_->setVisible(lt == "MEANLB" || lt == "LEXLB"+ || lt == "TRENDLB" || lt == "BOLB");+ labels_threshold_row_->setVisible(lt == "FIXLB" || lt == "MEANLB" || lt == "TRENDLB");+ labels_alpha_row_->setVisible(lt == "BOLB");+ };+ connect(labels_type_combo_, &QComboBox::currentTextChanged, this,+ [update_label_rows](const QString&) { update_label_rows(); });+ update_label_rows();pl->addStretch();cmd_config_stack_->addWidget(page);}- // Page 6: splits+ // Page 6: splits — fields shown depend on the chosen splitter.{auto* page = new QWidget(this);auto* pl = new QVBoxLayout(page);@@ -918,29 +1129,76 @@ QWidget* BacktestingScreen::build_right_panel() {splitter_type_combo_->addItem(st);pl->addWidget(splitter_type_combo_);- auto* wl = new QLabel("WINDOW LENGTH", page);- wl->setStyleSheet(label_style);- pl->addWidget(wl);- splitter_window_spin_ = new QSpinBox(page);- splitter_window_spin_->setRange(10, 500);- splitter_window_spin_->setValue(60);- splitter_window_spin_->setStyleSheet(input_style);- pl->addWidget(splitter_window_spin_);-- auto* stl = new QLabel("STEP SIZE", page);- stl->setStyleSheet(label_style);- pl->addWidget(stl);- splitter_step_spin_ = new QSpinBox(page);- splitter_step_spin_->setRange(1, 100);- splitter_step_spin_->setValue(10);- splitter_step_spin_->setStyleSheet(input_style);- pl->addWidget(splitter_step_spin_);+ // Helper to build a labeled spinbox row inside its own QWidget container.+ auto make_row = [&](const QString& label_text, QSpinBox*& spin_out,+ int min_v, int max_v, int default_v) -> QWidget* {+ auto* row = new QWidget(page);+ auto* rl = new QVBoxLayout(row);+ rl->setContentsMargins(0, 0, 0, 0);+ rl->setSpacing(4);+ auto* lab = new QLabel(label_text, row);+ lab->setStyleSheet(label_style);+ rl->addWidget(lab);+ spin_out = new QSpinBox(row);+ spin_out->setRange(min_v, max_v);+ spin_out->setValue(default_v);+ spin_out->setStyleSheet(input_style);+ rl->addWidget(spin_out);+ return row;+ };++ // Rolling-specific: training window length (in bars).+ splitter_window_row_ = make_row("WINDOW LENGTH", splitter_window_spin_, 10, 2000, 252);+ pl->addWidget(splitter_window_row_);++ // Expanding-specific: minimum training-set length before first split.+ splitter_min_row_ = make_row("MIN TRAIN LENGTH", splitter_min_spin_, 10, 2000, 252);+ pl->addWidget(splitter_min_row_);++ // Rolling + Expanding: out-of-sample window per fold.+ splitter_test_row_ = make_row("TEST LENGTH", splitter_test_spin_, 5, 1000, 63);+ pl->addWidget(splitter_test_row_);++ // Rolling + Expanding: bars to advance between folds.+ splitter_step_row_ = make_row("STEP SIZE", splitter_step_spin_, 1, 500, 21);+ pl->addWidget(splitter_step_row_);++ // PurgedKFold-specific: number of folds.+ splitter_n_splits_row_ = make_row("N SPLITS", splitter_n_splits_spin_, 2, 20, 5);+ pl->addWidget(splitter_n_splits_row_);++ // PurgedKFold-specific: bars to drop between train end and test start+ // (purge) and between test end and next train (embargo) — guards against+ // information leakage in financial-ML CV (López de Prado).+ splitter_purge_row_ = make_row("PURGE LENGTH", splitter_purge_spin_, 0, 100, 5);+ pl->addWidget(splitter_purge_row_);++ splitter_embargo_row_ = make_row("EMBARGO LENGTH", splitter_embargo_spin_, 0, 100, 5);+ pl->addWidget(splitter_embargo_row_);++ // Toggle row visibility based on the chosen splitter.+ auto update_split_rows = [this]() {+ const QString st = splitter_type_combo_->currentText();+ const bool is_rolling = (st == "RollingSplitter");+ const bool is_expanding = (st == "ExpandingSplitter");+ const bool is_purged = (st == "PurgedKFoldSplitter" || st == "PurgedKFold");+ splitter_window_row_->setVisible(is_rolling);+ splitter_min_row_->setVisible(is_expanding);+ splitter_test_row_->setVisible(is_rolling || is_expanding);+ splitter_step_row_->setVisible(is_rolling || is_expanding);+ splitter_n_splits_row_->setVisible(is_purged);+ splitter_purge_row_->setVisible(is_purged);+ splitter_embargo_row_->setVisible(is_purged);+ };+ connect(splitter_type_combo_, &QComboBox::currentTextChanged, this,+ [update_split_rows](const QString&) { update_split_rows(); });+ update_split_rows();pl->addStretch();cmd_config_stack_->addWidget(page);}- // Page 7: returns+ // Page 7: returns — extra inputs only appear for the analysis types that use them.{auto* page = new QWidget(this);auto* pl = new QVBoxLayout(page);@@ -959,20 +1217,71 @@ QWidget* BacktestingScreen::build_right_panel() {returns_type_combo_->addItem(rt);pl->addWidget(returns_type_combo_);- auto* wl = new QLabel("ROLLING WINDOW", page);+ // ── ROLLING WINDOW row (rolling analysis only) ──+ returns_window_row_ = new QWidget(page);+ auto* wr = new QVBoxLayout(returns_window_row_);+ wr->setContentsMargins(0, 0, 0, 0);+ wr->setSpacing(4);+ auto* wl = new QLabel("ROLLING WINDOW", returns_window_row_);wl->setStyleSheet(label_style);- pl->addWidget(wl);- returns_window_spin_ = new QSpinBox(page);- returns_window_spin_->setRange(5, 252);- returns_window_spin_->setValue(21);+ wr->addWidget(wl);+ returns_window_spin_ = new QSpinBox(returns_window_row_);+ returns_window_spin_->setRange(5, 504);+ returns_window_spin_->setValue(63);returns_window_spin_->setStyleSheet(input_style);- pl->addWidget(returns_window_spin_);+ wr->addWidget(returns_window_spin_);+ pl->addWidget(returns_window_row_);++ // ── METRIC row (rolling analysis only) ──+ // Names must match the vbt_returns / zl_returns rolling_map dispatch keys.+ returns_metric_row_ = new QWidget(page);+ auto* mr = new QVBoxLayout(returns_metric_row_);+ mr->setContentsMargins(0, 0, 0, 0);+ mr->setSpacing(4);+ auto* ml = new QLabel("METRIC", returns_metric_row_);+ ml->setStyleSheet(label_style);+ mr->addWidget(ml);+ returns_metric_combo_ = new QComboBox(returns_metric_row_);+ returns_metric_combo_->setStyleSheet(combo_style);+ for (const auto& m : {"sharpe", "sortino", "calmar", "omega",+ "info_ratio", "downside_risk",+ "total", "annualized", "volatility"})+ returns_metric_combo_->addItem(m);+ mr->addWidget(returns_metric_combo_);+ pl->addWidget(returns_metric_row_);++ // ── THRESHOLD row (ranges analysis only — defines what counts as a "range") ──+ returns_threshold_row_ = new QWidget(page);+ auto* thr = new QVBoxLayout(returns_threshold_row_);+ thr->setContentsMargins(0, 0, 0, 0);+ thr->setSpacing(4);+ auto* thl = new QLabel("THRESHOLD", returns_threshold_row_);+ thl->setStyleSheet(label_style);+ thr->addWidget(thl);+ returns_threshold_spin_ = new QDoubleSpinBox(returns_threshold_row_);+ returns_threshold_spin_->setRange(-1.0, 1.0);+ returns_threshold_spin_->setValue(0.0);+ returns_threshold_spin_->setDecimals(4);+ returns_threshold_spin_->setSingleStep(0.001);+ returns_threshold_spin_->setStyleSheet(input_style);+ thr->addWidget(returns_threshold_spin_);+ pl->addWidget(returns_threshold_row_);++ auto update_returns_rows = [this]() {+ const QString at = returns_type_combo_->currentText();+ returns_window_row_->setVisible(at == "rolling");+ returns_metric_row_->setVisible(at == "rolling");+ returns_threshold_row_->setVisible(at == "ranges");+ };+ connect(returns_type_combo_, &QComboBox::currentTextChanged, this,+ [update_returns_rows](const QString&) { update_returns_rows(); });+ update_returns_rows();pl->addStretch();cmd_config_stack_->addWidget(page);}- // Page 8: signals+ // Page 8: signals — generator-aware param rows.{auto* page = new QWidget(this);auto* pl = new QVBoxLayout(page);@@ -991,6 +1300,61 @@ QWidget* BacktestingScreen::build_right_panel() {signal_gen_combo_->addItem(sg);pl->addWidget(signal_gen_combo_);+ // Helpers to build a row inside its own container so we can toggle visibility.+ auto make_int_row = [&](const QString& text, QSpinBox*& spin, int mn, int mx, int dv) -> QWidget* {+ auto* row = new QWidget(page);+ auto* rl = new QVBoxLayout(row);+ rl->setContentsMargins(0, 0, 0, 0); rl->setSpacing(4);+ auto* lab = new QLabel(text, row); lab->setStyleSheet(label_style);+ rl->addWidget(lab);+ spin = new QSpinBox(row);+ spin->setRange(mn, mx); spin->setValue(dv); spin->setStyleSheet(input_style);+ rl->addWidget(spin);+ return row;+ };+ auto make_prob_row = [&](const QString& text, QDoubleSpinBox*& spin, double dv) -> QWidget* {+ auto* row = new QWidget(page);+ auto* rl = new QVBoxLayout(row);+ rl->setContentsMargins(0, 0, 0, 0); rl->setSpacing(4);+ auto* lab = new QLabel(text, row); lab->setStyleSheet(label_style);+ rl->addWidget(lab);+ spin = new QDoubleSpinBox(row);+ spin->setRange(0.001, 1.0); spin->setValue(dv);+ spin->setDecimals(3); spin->setSingleStep(0.01);+ spin->setStyleSheet(input_style);+ rl->addWidget(spin);+ return row;+ };++ signal_count_row_ = make_int_row("COUNT (n)", signal_count_spin_, 1, 1000, 10);+ signal_entry_prob_row_ = make_prob_row("ENTRY PROB", signal_entry_prob_spin_, 0.05);+ signal_exit_prob_row_ = make_prob_row("EXIT PROB", signal_exit_prob_spin_, 0.10);+ signal_min_hold_row_ = make_int_row("MIN HOLD (bars)", signal_min_hold_spin_, 1, 500, 5);+ signal_max_hold_row_ = make_int_row("MAX HOLD (bars)", signal_max_hold_spin_, 1, 500, 20);++ pl->addWidget(signal_count_row_);+ pl->addWidget(signal_entry_prob_row_);+ pl->addWidget(signal_exit_prob_row_);+ pl->addWidget(signal_min_hold_row_);+ pl->addWidget(signal_max_hold_row_);++ auto update_signal_rows = [this]() {+ const QString g = signal_gen_combo_->currentText();+ const bool is_rand = (g == "RAND");+ const bool is_randx = (g == "RANDX");+ const bool is_randnx = (g == "RANDNX");+ const bool is_rprob = (g == "RPROB");+ const bool is_rprobx = (g == "RPROBX");+ signal_count_row_->setVisible(is_rand || is_randx || is_randnx);+ signal_entry_prob_row_->setVisible(is_rprob || is_rprobx);+ signal_exit_prob_row_->setVisible(is_rprobx);+ signal_min_hold_row_->setVisible(is_randnx);+ signal_max_hold_row_->setVisible(is_randnx);+ };+ connect(signal_gen_combo_, &QComboBox::currentTextChanged, this,+ [update_signal_rows](const QString&) { update_signal_rows(); });+ update_signal_rows();+pl->addStretch();cmd_config_stack_->addWidget(page);}@@ -1017,6 +1381,26 @@ QWidget* BacktestingScreen::build_right_panel() {l2s_label_type_combo_->addItem(lt);pl->addWidget(l2s_label_type_combo_);+ // Entry/exit label override — defaults match vectorbt + zipline (entry=1, exit=-1)+ // but users can flip the mapping (e.g. enter on -1 for mean-reversion).+ auto* elbl = new QLabel("ENTRY LABEL", page);+ elbl->setStyleSheet(label_style);+ pl->addWidget(elbl);+ l2s_entry_label_spin_ = new QSpinBox(page);+ l2s_entry_label_spin_->setRange(-2, 2);+ l2s_entry_label_spin_->setValue(1);+ l2s_entry_label_spin_->setStyleSheet(input_style);+ pl->addWidget(l2s_entry_label_spin_);++ auto* xlbl = new QLabel("EXIT LABEL", page);+ xlbl->setStyleSheet(label_style);+ pl->addWidget(xlbl);+ l2s_exit_label_spin_ = new QSpinBox(page);+ l2s_exit_label_spin_->setRange(-2, 2);+ l2s_exit_label_spin_->setValue(-1);+ l2s_exit_label_spin_->setStyleSheet(input_style);+ pl->addWidget(l2s_exit_label_spin_);+pl->addStretch();cmd_config_stack_->addWidget(page);}@@ -1182,6 +1566,36 @@ void BacktestingScreen::on_command_changed(int index) {// indicator_signals(4), labels(5), splits(6), returns(7),// signals(8), labels_to_signals(9), indicator_sweep(10)cmd_config_stack_->setCurrentIndex(index);+ update_section_visibility();+}++void BacktestingScreen::update_section_visibility() {+ // Show/hide whole right + left panel sections based on the active command.+ //+ // Sections map to the args each command actually consumes (see gather_args):+ // - backtest/optimize/walk_forward : execution, advanced, benchmark, strategy+ // - returns : benchmark (only — for benchmark-relative analysis)+ // - everything else (labels, splits, : MARKET DATA + per-command page only+ // signals, labels_to_signals,+ // indicator, indicator_signals,+ // indicator_sweep)+ //+ // MARKET DATA is always visible — every command reads symbols + dates.+ if (active_command_ < 0 || active_command_ >= commands_.size())+ return;+ const QString cmd = commands_[active_command_].id;+ const bool is_backtest_family = (cmd == "backtest" || cmd == "optimize" || cmd == "walk_forward");+ const bool needs_benchmark = is_backtest_family || cmd == "returns";++ if (execution_section_) execution_section_->setVisible(is_backtest_family);+ if (advanced_section_) advanced_section_->setVisible(is_backtest_family);+ if (benchmark_section_) benchmark_section_->setVisible(needs_benchmark);+ if (strategy_section_) strategy_section_->setVisible(is_backtest_family);++ // Show explicit MIN/MAX/STEP rows under each strategy param only for `optimize`.+ const bool is_optimize = (cmd == "optimize");+ for (auto* row : param_range_rows_)+ if (row) row->setVisible(is_optimize);}void BacktestingScreen::update_command_buttons() {@@ -1242,6 +1656,10 @@ void BacktestingScreen::populate_strategies() {void BacktestingScreen::rebuild_strategy_params() {clear_layout(strategy_params_layout_);param_spinboxes_.clear();+ param_min_spinboxes_.clear();+ param_max_spinboxes_.clear();+ param_step_spinboxes_.clear();+ param_range_rows_.clear();auto strategy_id = strategy_combo_->currentData().toString();if (strategy_id.isEmpty())@@ -1265,11 +1683,20 @@ void BacktestingScreen::rebuild_strategy_params() {.arg(ui::fonts::SMALL).arg(ui::colors::BORDER_BRIGHT());+ auto sublabel_style = QString("color:%1; font-size:%2px; font-family:%3;")+ .arg(ui::colors::TEXT_DIM())+ .arg(ui::fonts::TINY)+ .arg(ui::fonts::DATA_FAMILY);+auto label_style = QString("color:%1; font-size:%2px; font-family:%3;").arg(ui::colors::TEXT_TERTIARY()).arg(ui::fonts::TINY).arg(ui::fonts::DATA_FAMILY);+ const bool is_optimize = (active_command_ >= 0+ && active_command_ < commands_.size()+ && commands_[active_command_].id == "optimize");+for (const auto& p : strat->params) {auto* lbl = new QLabel(p.label.toUpper(), strategy_params_container_);lbl->setStyleSheet(label_style);@@ -1284,6 +1711,45 @@ void BacktestingScreen::rebuild_strategy_params() {spin->setProperty("param_name", p.name);strategy_params_layout_->addWidget(spin);param_spinboxes_.append(spin);++ // ── Optimize-only: explicit MIN / MAX / STEP range editor ──+ // Built up front so we can flip visibility in update_section_visibility()+ // without having to rebuild the whole strategy form on command change.+ auto* range_row = new QWidget(strategy_params_container_);+ auto* hl = new QGridLayout(range_row);+ hl->setContentsMargins(0, 0, 0, 4);+ hl->setHorizontalSpacing(4);+ hl->setVerticalSpacing(2);++ auto build_subspin = [&](const QString& sub_label, double default_val, int col) -> QDoubleSpinBox* {+ auto* sl = new QLabel(sub_label, range_row);+ sl->setStyleSheet(sublabel_style);+ hl->addWidget(sl, 0, col);+ auto* s = new QDoubleSpinBox(range_row);+ s->setRange(p.min_val, p.max_val);+ s->setValue(default_val);+ s->setSingleStep(p.step);+ s->setDecimals(p.step < 1.0 ? 2 : 0);+ s->setStyleSheet(input_style);+ hl->addWidget(s, 1, col);+ return s;+ };++ // Default range: seed value ± a couple of steps, snapped to param bounds.+ const double span = qMax(p.step, (p.max_val - p.min_val) * 0.1);+ const double min_default = qMax(p.min_val, p.default_val - span);+ const double max_default = qMin(p.max_val, p.default_val + span);+ auto* min_spin = build_subspin("MIN", min_default, 0);+ auto* max_spin = build_subspin("MAX", max_default, 1);+ auto* step_spin = build_subspin("STEP", p.step, 2);++ strategy_params_layout_->addWidget(range_row);+ range_row->setVisible(is_optimize);++ param_min_spinboxes_.append(min_spin);+ param_max_spinboxes_.append(max_spin);+ param_step_spinboxes_.append(step_spin);+ param_range_rows_.append(range_row);}}@@ -1343,18 +1809,26 @@ QJsonObject BacktestingScreen::gather_args() {if (cmd_id == "optimize") {args["optimizeObjective"] = opt_objective_combo_->currentText();- args["optimizeMethod"] = opt_method_combo_->currentText();- args["maxIterations"] = opt_iterations_spin_->value();+ args["optimizeMethod"] = opt_method_combo_->currentText();+ args["maxIterations"] = opt_iterations_spin_->value();- // Build param ranges from strategy params+ // Build paramRanges from the explicit per-param MIN/MAX/STEP editor.+ // rebuild_strategy_params keeps param_spinboxes_ and the three range+ // vectors index-aligned, so we can zip them.QJsonObject ranges;- for (auto* spin : param_spinboxes_) {- auto name = spin->property("param_name").toString();- double val = spin->value();+ for (int i = 0; i < param_spinboxes_.size(); ++i) {+ auto name = param_spinboxes_[i]->property("param_name").toString();+ if (name.isEmpty()) continue;+ if (i >= param_min_spinboxes_.size() || i >= param_max_spinboxes_.size()+ || i >= param_step_spinboxes_.size()) continue;+ double mn = param_min_spinboxes_[i]->value();+ double mx = param_max_spinboxes_[i]->value();+ double st = qMax(0.0001, param_step_spinboxes_[i]->value());+ if (mx < mn) std::swap(mn, mx);QJsonObject range;- range["min"] = qMax(spin->minimum(), val * 0.8);- range["max"] = qMin(spin->maximum(), val * 1.2);- range["step"] = spin->singleStep();+ range["min"] = mn;+ range["max"] = mx;+ range["step"] = st;ranges[name] = range;}args["paramRanges"] = ranges;@@ -1367,48 +1841,171 @@ QJsonObject BacktestingScreen::gather_args() {if (cmd_id == "indicator") {args["indicator"] = indicator_combo_->currentData().toString();+ QJsonObject p;+ p["period"] = indicator_period_spin_->value();+ args["params"] = p;}if (cmd_id == "indicator_signals") {args["indicator"] = ind_signal_indicator_combo_->currentData().toString();- args["mode"] = ind_signal_mode_combo_->currentText();+ const QString m = ind_signal_mode_combo_->currentText();+ args["mode"] = m;+ QJsonObject params;+ // vectorbt uses long mode names ('crossover_signals'); zipline uses both+ // long and short forms. The params keys are the same across providers.+ if (m == "crossover_signals" || m == "crossover") {+ params["fast_period"] = is_fast_period_spin_->value();+ params["slow_period"] = is_slow_period_spin_->value();+ params["fastPeriod"] = is_fast_period_spin_->value(); // zipline alias+ params["slowPeriod"] = is_slow_period_spin_->value();+ params["ma_type"] = is_ma_type_combo_->currentText();+ params["maType"] = is_ma_type_combo_->currentText();+ params["fast_indicator"] = is_ma_type_combo_->currentText(); // vectorbt key+ params["slow_indicator"] = is_ma_type_combo_->currentText();+ } else if (m == "threshold_signals" || m == "threshold") {+ params["period"] = is_period_spin_->value();+ params["lower"] = is_lower_spin_->value();+ params["upper"] = is_upper_spin_->value();+ } else if (m == "breakout_signals" || m == "breakout") {+ params["period"] = is_period_spin_->value();+ params["channel"] = is_channel_combo_->currentText();+ } else if (m == "mean_reversion_signals" || m == "mean_reversion") {+ params["period"] = is_period_spin_->value();+ params["z_entry"] = is_z_entry_spin_->value();+ params["z_exit"] = is_z_exit_spin_->value();+ } else if (m == "signal_filter" || m == "filter") {+ params["base_indicator"] = ind_signal_indicator_combo_->currentData().toString();+ params["base_period"] = is_period_spin_->value();+ params["filter_indicator"] = is_filter_indicator_combo_->currentText();+ params["filter_period"] = is_filter_period_spin_->value();+ params["filter_threshold"] = is_filter_threshold_spin_->value();+ params["filter_type"] = is_filter_type_combo_->currentText();+ }+ args["params"] = params;}if (cmd_id == "labels") {- args["labelType"] = labels_type_combo_->currentText();+ const QString lt = labels_type_combo_->currentText();+ args["labelType"] = lt;QJsonObject params;- params["horizon"] = labels_horizon_spin_->value();- params["threshold"] = labels_threshold_spin_->value();+ // Send only the params the chosen generator consumes so the JSON stays+ // unambiguous; Python providers use defaults for anything missing.+ if (lt == "FIXLB") {+ params["horizon"] = labels_horizon_spin_->value();+ params["threshold"] = labels_threshold_spin_->value();+ } else if (lt == "MEANLB" || lt == "TRENDLB") {+ params["window"] = labels_window_spin_->value();+ params["threshold"] = labels_threshold_spin_->value();+ } else if (lt == "LEXLB") {+ params["window"] = labels_window_spin_->value();+ } else if (lt == "BOLB") {+ params["window"] = labels_window_spin_->value();+ params["alpha"] = labels_alpha_spin_->value();+ }args["params"] = params;}if (cmd_id == "splits") {- args["splitterType"] = splitter_type_combo_->currentText();+ const QString st = splitter_type_combo_->currentText();+ args["splitterType"] = st;QJsonObject params;- params["windowLength"] = splitter_window_spin_->value();- params["step"] = splitter_step_spin_->value();+ // vectorbt reads snake_case (window_len/test_len/min_len/n_splits/purge_len/embargo_len);+ // zipline reads camelCase (windowLen/testLen/minLen/nSplits/purgeLen/embargoLen).+ // Sending both keeps the JSON contract provider-agnostic.+ if (st == "RollingSplitter") {+ params["window_len"] = splitter_window_spin_->value();+ params["windowLen"] = splitter_window_spin_->value();+ params["test_len"] = splitter_test_spin_->value();+ params["testLen"] = splitter_test_spin_->value();+ params["step"] = splitter_step_spin_->value();+ } else if (st == "ExpandingSplitter") {+ params["min_len"] = splitter_min_spin_->value();+ params["minLen"] = splitter_min_spin_->value();+ params["test_len"] = splitter_test_spin_->value();+ params["testLen"] = splitter_test_spin_->value();+ params["step"] = splitter_step_spin_->value();+ } else if (st == "PurgedKFoldSplitter" || st == "PurgedKFold") {+ params["n_splits"] = splitter_n_splits_spin_->value();+ params["nSplits"] = splitter_n_splits_spin_->value();+ params["purge_len"] = splitter_purge_spin_->value();+ params["purgeLen"] = splitter_purge_spin_->value();+ params["embargo_len"] = splitter_embargo_spin_->value();+ params["embargoLen"] = splitter_embargo_spin_->value();+ }args["params"] = params;}if (cmd_id == "returns") {- args["analysisType"] = returns_type_combo_->currentText();- args["rollingWindow"] = returns_window_spin_->value();- if (returns_type_combo_->currentText() == "benchmark_comparison")+ const QString at = returns_type_combo_->currentText();+ args["analysisType"] = at;+ // Benchmark is consumed by returns_stats for alpha/beta/info-ratio.+ if (!benchmark_edit_->text().trimmed().isEmpty())args["benchmarkSymbol"] = benchmark_edit_->text().trimmed();++ QJsonObject params;+ if (at == "rolling") {+ params["window"] = returns_window_spin_->value();+ // vectorbt reads `metric` (singular string); zipline reads+ // `metrics` (list, used as a set-membership check). Send both.+ const QString m = returns_metric_combo_->currentText();+ params["metric"] = m;+ QJsonArray ml; ml.append(m);+ params["metrics"] = ml;+ } else if (at == "ranges") {+ params["threshold"] = returns_threshold_spin_->value();+ }+ if (!params.isEmpty())+ args["params"] = params;}if (cmd_id == "signals") {- args["generatorType"] = signal_gen_combo_->currentText();+ const QString g = signal_gen_combo_->currentText();+ args["generatorType"] = g;+ // vectorbt reads snake_case (n / entry_prob / exit_prob / min_hold / max_hold);+ // zipline reads camelCase (n / entryProb / exitProb / minHold / maxHold).+ // Send both so every provider gets what it needs.+ QJsonObject params;+ if (g == "RAND" || g == "RANDX" || g == "RANDNX") {+ params["n"] = signal_count_spin_->value();+ }+ if (g == "RANDNX") {+ params["min_hold"] = signal_min_hold_spin_->value();+ params["max_hold"] = signal_max_hold_spin_->value();+ params["minHold"] = signal_min_hold_spin_->value();+ params["maxHold"] = signal_max_hold_spin_->value();+ }+ if (g == "RPROB" || g == "RPROBX") {+ params["entry_prob"] = signal_entry_prob_spin_->value();+ params["entryProb"] = signal_entry_prob_spin_->value();+ }+ if (g == "RPROBX") {+ params["exit_prob"] = signal_exit_prob_spin_->value();+ params["exitProb"] = signal_exit_prob_spin_->value();+ }+ args["params"] = params;}if (cmd_id == "labels_to_signals") {- // Wire the same horizon/threshold inputs the labels page uses — the- // Python pipeline first generates labels and then converts them to- // signals, so the upstream label config still applies.- args["labelType"] = l2s_label_type_combo_->currentText();+ // Shares the labels page's widgets (the labels_to_signals page only+ // re-picks the generator). Apply the same type→params mapping so we+ // don't send irrelevant params and so non-FIXLB types still get window.+ const QString lt = l2s_label_type_combo_->currentText();+ args["labelType"] = lt;+ args["entryLabel"] = l2s_entry_label_spin_->value();+ args["exitLabel"] = l2s_exit_label_spin_->value();QJsonObject params;- params["horizon"] = labels_horizon_spin_->value();- params["threshold"] = labels_threshold_spin_->value();+ if (lt == "FIXLB") {+ params["horizon"] = labels_horizon_spin_->value();+ params["threshold"] = labels_threshold_spin_->value();+ } else if (lt == "MEANLB" || lt == "TRENDLB") {+ params["window"] = labels_window_spin_->value();+ params["threshold"] = labels_threshold_spin_->value();+ } else if (lt == "LEXLB") {+ params["window"] = labels_window_spin_->value();+ } else if (lt == "BOLB") {+ params["window"] = labels_window_spin_->value();+ params["alpha"] = labels_alpha_spin_->value();+ }args["params"] = params;}@@ -1470,151 +2067,451 @@ void BacktestingScreen::clear_results() {raw_json_edit_->clear();}-void BacktestingScreen::display_result(const QJsonObject& payload) {+void BacktestingScreen::display_result(const QString& command, const QJsonObject& payload) {clear_results();- auto accent = providers_[active_provider_].color.name();+ const auto accent = providers_[active_provider_].color.name();- // ── SUMMARY tab: metric cards ──- auto* header = new QLabel("BACKTEST RESULTS", summary_container_);- header->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;"- "letter-spacing:1px;")- .arg(accent)- .arg(ui::fonts::TINY)- .arg(ui::fonts::DATA_FAMILY));- summary_layout_->addWidget(header);-- // Extract performance metrics (handle nested structures)- auto perf = payload.contains("performance") ? payload["performance"].toObject()- : payload.contains("payload") ? payload["payload"].toObject().value("performance").toObject()- : payload;-- // Key metric cards in grid- auto* cards = new QWidget(summary_container_);- auto* gl = new QGridLayout(cards);- gl->setContentsMargins(0, 0, 0, 0);- gl->setSpacing(8);-- QStringList key_metrics = {"total_return", "sharpe_ratio", "max_drawdown", "win_rate", "profit_factor",- "total_trades", "annualized_return", "sortino_ratio", "calmar_ratio", "volatility",- "alpha", "beta",- // camelCase variants- "totalReturn", "sharpeRatio", "maxDrawdown", "winRate", "profitFactor", "totalTrades",- "annualizedReturn", "sortinoRatio", "calmarRatio"};-- int col = 0, row = 0;- QStringList shown;- for (const auto& key : key_metrics) {- if (!perf.contains(key))- continue;- // Skip duplicate camelCase if we already showed snake_case- auto normalized = key;- normalized.replace(QRegularExpression("([a-z])([A-Z])"), "\\1_\\2");- normalized = normalized.toLower();- if (shown.contains(normalized))- continue;- shown.append(normalized);-- auto display_label = key;- display_label.replace('_', ' ');- // Also handle camelCase- display_label.replace(QRegularExpression("([a-z])([A-Z])"), "\\1 \\2");-- auto* card = new QWidget(cards);- card->setStyleSheet(- QString("background:%1; border:1px solid %2;").arg(ui::colors::BG_RAISED()).arg(ui::colors::BORDER_DIM()));- auto* cvl = new QVBoxLayout(card);- cvl->setContentsMargins(10, 8, 10, 8);- cvl->setSpacing(2);-- auto* lbl = new QLabel(display_label.toUpper(), card);- lbl->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3;")- .arg(ui::colors::TEXT_TERTIARY())+ // ── Local helpers (capture summary_container_ / metrics_table_ / trades_table_) ──++ auto add_section_header = [&](const QString& text, const QString& color = QString()) {+ auto* lbl = new QLabel(text, summary_container_);+ lbl->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; font-family:%3; "+ "letter-spacing:1px; padding-top:4px;")+ .arg(color.isEmpty() ? accent : color).arg(ui::fonts::TINY).arg(ui::fonts::DATA_FAMILY));- auto* val = new QLabel(fmt_metric(key, perf[key]), card);- val->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")- .arg(accent)- .arg(ui::fonts::DATA)- .arg(ui::fonts::DATA_FAMILY));- cvl->addWidget(lbl);- cvl->addWidget(val);- gl->addWidget(card, row, col);- if (++col >= 3) {- col = 0;- row++;- }- }-- if (row > 0 || col > 0)- summary_layout_->addWidget(cards);- else- cards->deleteLater();-- // If result has a status/message, show it- if (payload.contains("status")) {- auto status = payload["status"].toString();- auto* status_lbl = new QLabel(QString("Status: %1").arg(status), summary_container_);- status_lbl->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3; padding:8px;")- .arg(status == "success" ? ui::colors::POSITIVE() : ui::colors::WARNING())- .arg(ui::fonts::SMALL)- .arg(ui::fonts::DATA_FAMILY));- summary_layout_->addWidget(status_lbl);- }+ summary_layout_->addWidget(lbl);+ };- summary_layout_->addStretch();+ auto humanize = [](QString key) {+ key.replace('_', ' ');+ key.replace(QRegularExpression("([a-z])([A-Z])"), "\\1 \\2");+ return key.toUpper();+ };- // ── METRICS tab: full metrics table ──- QStringList all_keys;- for (auto it = perf.begin(); it != perf.end(); ++it)- if (!it.value().isObject() && !it.value().isArray())- all_keys.append(it.key());-- if (!all_keys.isEmpty()) {- metrics_table_->setRowCount(all_keys.size());- for (int r = 0; r < all_keys.size(); ++r) {- auto label = all_keys[r];- label.replace('_', ' ');- label.replace(QRegularExpression("([a-z])([A-Z])"), "\\1 \\2");- auto* name_item = new QTableWidgetItem(label.toUpper());- metrics_table_->setItem(r, 0, name_item);-- auto* val_item = new QTableWidgetItem(fmt_metric(all_keys[r], perf[all_keys[r]]));- val_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);- metrics_table_->setItem(r, 1, val_item);+ auto add_cards_from = [&](const QJsonObject& obj, const QStringList& ordered_keys,+ int cols_per_row = 3) {+ if (obj.isEmpty())+ return;+ auto* cards = new QWidget(summary_container_);+ auto* gl = new QGridLayout(cards);+ gl->setContentsMargins(0, 0, 0, 0);+ gl->setSpacing(8);++ // Build the display order: explicit keys first, then any remaining scalars.+ QStringList order = ordered_keys;+ if (order.isEmpty()) {+ for (auto it = obj.begin(); it != obj.end(); ++it)+ if (!it.value().isObject() && !it.value().isArray())+ order.append(it.key());}- metrics_table_->resizeColumnsToContents();- }- // ── TRADES tab ──- auto trades = payload.contains("trades") ? payload["trades"].toArray()- : payload.contains("payload") ? payload["payload"].toObject().value("trades").toArray()- : QJsonArray();+ int col = 0, row = 0;+ QStringList shown;+ for (const auto& key : order) {+ if (!obj.contains(key))+ continue;+ const auto& val = obj[key];+ if (val.isObject() || val.isArray() || val.isNull())+ continue;+ auto canon = key;+ canon.replace(QRegularExpression("([a-z])([A-Z])"), "\\1_\\2");+ canon = canon.toLower();+ if (shown.contains(canon))+ continue;+ shown.append(canon);++ auto* card = new QWidget(cards);+ card->setStyleSheet(QString("background:%1; border:1px solid %2;")+ .arg(ui::colors::BG_RAISED(), ui::colors::BORDER_DIM()));+ auto* cvl = new QVBoxLayout(card);+ cvl->setContentsMargins(10, 8, 10, 8);+ cvl->setSpacing(2);+ auto* lbl = new QLabel(humanize(key), card);+ lbl->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3;")+ .arg(ui::colors::TEXT_TERTIARY())+ .arg(ui::fonts::TINY)+ .arg(ui::fonts::DATA_FAMILY));+ auto* vlbl = new QLabel(fmt_metric(key, val), card);+ vlbl->setStyleSheet(QString("color:%1; font-size:%2px; font-weight:700; font-family:%3;")+ .arg(accent)+ .arg(ui::fonts::DATA)+ .arg(ui::fonts::DATA_FAMILY));+ cvl->addWidget(lbl);+ cvl->addWidget(vlbl);+ gl->addWidget(card, row, col);+ if (++col >= cols_per_row) { col = 0; row++; }+ }+ if (row > 0 || col > 0)+ summary_layout_->addWidget(cards);+ else+ cards->deleteLater();+ };- if (!trades.isEmpty() && trades[0].isObject()) {- auto first = trades[0].toObject();- QStringList cols;- for (auto it = first.begin(); it != first.end(); ++it)- if (!it.value().isObject() && !it.value().isArray())- cols.append(it.key());+ auto fill_kv_table = [&](const QJsonObject& obj) {+ QStringList keys;+ for (auto it = obj.begin(); it != obj.end(); ++it)+ if (!it.value().isObject() && !it.value().isArray() && !it.value().isNull())+ keys.append(it.key());+ metrics_table_->setRowCount(keys.size());+ for (int r = 0; r < keys.size(); ++r) {+ auto* name = new QTableWidgetItem(humanize(keys[r]));+ metrics_table_->setItem(r, 0, name);+ auto* val = new QTableWidgetItem(fmt_metric(keys[r], obj[keys[r]]));+ val->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);+ metrics_table_->setItem(r, 1, val);+ }+ metrics_table_->resizeColumnsToContents();+ };- int show = qMin(static_cast<int>(trades.size()), 100);+ auto fill_details_table = [&](const QJsonArray& arr, const QStringList& preferred_cols = {}) {+ if (arr.isEmpty() || !arr[0].isObject())+ return;+ auto first = arr[0].toObject();+ QStringList cols = preferred_cols;+ if (cols.isEmpty()) {+ for (auto it = first.begin(); it != first.end(); ++it)+ if (!it.value().isObject() && !it.value().isArray())+ cols.append(it.key());+ }+ const int rows = qMin(static_cast<int>(arr.size()), 200);trades_table_->setColumnCount(cols.size());trades_table_->setHorizontalHeaderLabels(cols);- trades_table_->setRowCount(show);-- for (int r = 0; r < show; ++r) {- auto trade = trades[r].toObject();+ trades_table_->setRowCount(rows);+ for (int r = 0; r < rows; ++r) {+ auto rec = arr[r].toObject();for (int c = 0; c < cols.size(); ++c) {- auto* item = new QTableWidgetItem(fmt_metric(cols[c], trade[cols[c]]));+ auto* item = new QTableWidgetItem(fmt_metric(cols[c], rec[cols[c]]));item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);trades_table_->setItem(r, c, item);}}trades_table_->resizeColumnsToContents();+ };++ // ── Header (per-command title) ──+ QString cmd_label = command.toUpper();+ for (const auto& c : commands_) if (c.id == command) { cmd_label = c.label.toUpper(); break; }+ add_section_header(cmd_label + " RESULTS");++ // ── Synthetic-data warning (Python sets this when yfinance is unavailable) ──+ if (payload.value("usingSyntheticData").toBool()) {+ auto* warn = new QLabel(+ "Using synthetic price data (yfinance unavailable). Results do not reflect real markets.",+ summary_container_);+ warn->setWordWrap(true);+ warn->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3; padding:8px 10px; "+ "background:rgba(245,158,11,0.10); border:1px solid %4;")+ .arg(ui::colors::WARNING())+ .arg(ui::fonts::SMALL)+ .arg(ui::fonts::DATA_FAMILY)+ .arg(ui::colors::WARNING()));+ summary_layout_->addWidget(warn);+ }++ // ── Per-command rendering ──++ if (command == "backtest") {+ auto perf = payload.value("performance").toObject();+ add_cards_from(perf, {"totalReturn", "annualizedReturn", "sharpeRatio", "sortinoRatio",+ "maxDrawdown", "winRate", "profitFactor", "calmarRatio",+ "totalTrades", "volatility"});+ if (payload.contains("status")) {+ auto status = payload["status"].toString();+ auto* sl = new QLabel(QString("Status: %1").arg(status), summary_container_);+ sl->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3; padding:8px;")+ .arg(status == "success" ? ui::colors::POSITIVE() : ui::colors::WARNING())+ .arg(ui::fonts::SMALL)+ .arg(ui::fonts::DATA_FAMILY));+ summary_layout_->addWidget(sl);+ }+ fill_kv_table(perf);+ auto trades = payload.value("trades").toArray();+ fill_details_table(trades);+ }+ else if (command == "optimize") {+ QJsonObject summary{+ {"iterations", payload.value("iterations")},+ {"totalCombinations", payload.value("totalCombinations")},+ {"method", payload.value("method")},+ {"objective", payload.value("objective")},+ {"bestObjectiveValue", payload.value("bestObjectiveValue")},+ };+ add_cards_from(summary, {"bestObjectiveValue", "iterations", "totalCombinations",+ "method", "objective"});++ auto best_params = payload.value("bestParameters").toObject();+ if (!best_params.isEmpty()) {+ add_section_header("BEST PARAMETERS");+ add_cards_from(best_params, {}, 4);+ }+ auto best_perf = payload.value("bestPerformance").toObject();+ if (!best_perf.isEmpty()) {+ add_section_header("BEST PERFORMANCE");+ add_cards_from(best_perf, {"totalReturn", "sharpeRatio", "maxDrawdown",+ "winRate", "profitFactor", "totalTrades"});+ fill_kv_table(best_perf);+ }+ // Details: top results — flatten params into the row+ auto all_results = payload.value("allResults").toArray();+ QJsonArray flat;+ for (const auto& v : all_results) {+ auto o = v.toObject();+ QJsonObject row;+ auto params = o.value("parameters").toObject();+ for (auto it = params.begin(); it != params.end(); ++it)+ row[it.key()] = it.value();+ row["objective"] = o.value("objective_value");+ auto perf = o.value("performance").toObject();+ for (const auto& k : QStringList{"totalReturn", "sharpeRatio", "maxDrawdown", "winRate"}) {+ if (perf.contains(k)) row[k] = perf.value(k);+ }+ flat.append(row);+ }+ fill_details_table(flat);+ }+ else if (command == "walk_forward") {+ QJsonObject summary{+ {"nWindows", payload.value("nWindows")},+ {"avgOosReturn", payload.value("avgOosReturn")},+ {"avgOosSharpe", payload.value("avgOosSharpe")},+ {"oosReturnStd", payload.value("oosReturnStd")},+ {"robustnessScore", payload.value("robustnessScore")},+ {"degradationRatio", payload.value("degradationRatio")},+ };+ add_cards_from(summary, {"nWindows", "avgOosReturn", "avgOosSharpe",+ "robustnessScore", "degradationRatio", "oosReturnStd"});+ fill_kv_table(summary);+ auto windows = payload.value("windows").toArray();+ fill_details_table(windows, {"window", "trainStart", "trainEnd", "testStart", "testEnd",+ "inSampleReturn", "inSampleSharpe",+ "outOfSampleReturn", "outOfSampleSharpe"});+ }+ else if (command == "indicator") {+ QJsonObject summary{+ {"indicator", payload.value("indicator")},+ {"symbol", payload.value("symbol")},+ {"period", payload.value("period")},+ {"totalBars", payload.value("totalBars")},+ };+ add_cards_from(summary, {"indicator", "symbol", "period", "totalBars"}, 4);+ auto stats = payload.value("stats").toObject();+ // Multi-output indicators have stats per component — flatten one level.+ if (!stats.isEmpty()) {+ QJsonObject flat;+ bool nested = false;+ for (auto it = stats.begin(); it != stats.end(); ++it) {+ if (it.value().isObject()) { nested = true; break; }+ }+ if (nested) {+ for (auto it = stats.begin(); it != stats.end(); ++it) {+ auto sub = it.value().toObject();+ for (auto sit = sub.begin(); sit != sub.end(); ++sit)+ flat[it.key() + "." + sit.key()] = sit.value();+ }+ } else {+ flat = stats;+ }+ add_section_header("STATISTICS");+ add_cards_from(flat, {"last", "mean", "std", "min", "max"});+ fill_kv_table(flat);+ }+ // Details: series sample. For multi-output use the first non-empty component.+ auto series_v = payload.value("series");+ QJsonArray sample;+ if (series_v.isArray()) {+ sample = series_v.toArray();+ } else if (series_v.isObject()) {+ auto so = series_v.toObject();+ for (auto it = so.begin(); it != so.end(); ++it) {+ if (it.value().isArray() && !it.value().toArray().isEmpty()) {+ sample = it.value().toArray();+ break;+ }+ }+ }+ fill_details_table(sample, {"date", "value"});+ }+ else if (command == "indicator_signals") {+ add_cards_from(payload, {"totalSignals", "winRate", "profitFactor", "avgReturn",+ "medianReturn", "bestTrade", "worstTrade",+ "avgHoldingPeriod", "signalDensity",+ "entryCount", "exitCount", "originalEntryCount", "filteredEntryCount"});+ fill_kv_table(payload);+ // Combine entry & exit signals into a single details table with a Type column.+ auto entries = payload.value("entrySignals").toArray();+ auto exits = payload.value("exitSignals").toArray();+ QJsonArray combined;+ for (const auto& v : entries) { auto o = v.toObject(); o["type"] = "ENTRY"; combined.append(o); }+ for (const auto& v : exits) { auto o = v.toObject(); o["type"] = "EXIT"; combined.append(o); }+ if (combined.isEmpty()) {+ // Some modes only emit plain entries[]/exits[] string arrays+ QJsonArray plain;+ for (const auto& v : payload.value("entries").toArray()) {+ QJsonObject o; o["type"] = "ENTRY"; o["date"] = v.toString(); plain.append(o);+ }+ for (const auto& v : payload.value("exits").toArray()) {+ QJsonObject o; o["type"] = "EXIT"; o["date"] = v.toString(); plain.append(o);+ }+ combined = plain;+ }+ fill_details_table(combined);+ }+ else if (command == "labels") {+ QJsonObject summary{+ {"labelType", payload.value("labelType")},+ {"totalBars", payload.value("totalBars")},+ {"labeledBars", payload.value("labeledBars")},+ };+ add_cards_from(summary, {"labelType", "totalBars", "labeledBars"}, 3);++ auto dist = payload.value("distribution").toObject();+ if (!dist.isEmpty()) {+ add_section_header("CLASS DISTRIBUTION");+ // Re-key so cards show "Class -1 / Class 0 / Class 1"+ QJsonObject relabeled;+ QStringList ordered;+ QStringList raw_keys = dist.keys();+ std::sort(raw_keys.begin(), raw_keys.end(), [](const QString& a, const QString& b) {+ return a.toInt() < b.toInt();+ });+ for (const auto& k : raw_keys) {+ QString rk = "Class " + k;+ relabeled[rk] = dist.value(k);+ ordered.append(rk);+ }+ add_cards_from(relabeled, ordered, 5);+ fill_kv_table(relabeled);+ }+ fill_details_table(payload.value("sampleLabels").toArray(), {"date", "label"});}+ else if (command == "splits") {+ QJsonObject summary{+ {"splitterType", payload.value("splitterType")},+ {"nSplits", payload.value("nSplits")},+ {"totalBars", payload.value("totalBars")},+ {"indexStart", payload.value("indexStart")},+ {"indexEnd", payload.value("indexEnd")},+ };+ add_cards_from(summary, {"splitterType", "nSplits", "totalBars", "indexStart", "indexEnd"}, 3);+ fill_kv_table(summary);+ fill_details_table(payload.value("splits").toArray(),+ {"fold", "trainStart", "trainEnd", "trainSize",+ "testStart", "testEnd", "testSize"});+ }+ else if (command == "returns") {+ QJsonObject summary{+ {"analysisType", payload.value("analysisType")},+ {"totalBars", payload.value("totalBars")},+ {"returnBars", payload.value("returnBars")},+ };+ add_cards_from(summary, {"analysisType", "totalBars", "returnBars"}, 3);++ // The interesting numbers live in payload.stats (returns_stats / drawdowns / ranges)+ // OR scattered at the top level for other shapes.+ auto stats = payload.value("stats").toObject();+ if (!stats.isEmpty()) {+ add_section_header("STATISTICS");+ add_cards_from(stats, {"Total Return", "Annualized Return", "Sharpe Ratio",+ "Sortino Ratio", "Calmar Ratio", "Max Drawdown",+ "Annualized Volatility", "Downside Risk"});+ fill_kv_table(stats);+ } else {+ // rolling-style payloads expose top-level fields+ QJsonObject topnum;+ for (const auto& k : QStringList{"metric", "window", "dataPoints", "maxDrawdown",+ "avgDrawdown", "totalDrawdowns", "activeDrawdown",+ "activeDuration", "totalRanges", "avgDuration",+ "maxDuration", "coverage"}) {+ if (payload.contains(k)) topnum[k] = payload.value(k);+ }+ if (!topnum.isEmpty()) {+ add_cards_from(topnum, {});+ fill_kv_table(topnum);+ }+ }++ // Details: the series / records that ship with the chosen analysis type+ QJsonArray detail;+ for (const auto& k : QStringList{"records", "cumulativeReturns", "drawdownSeries", "series"}) {+ if (payload.value(k).isArray()) {+ auto a = payload.value(k).toArray();+ if (!a.isEmpty()) { detail = a; break; }+ }+ }+ fill_details_table(detail);+ }+ else if (command == "signals") {+ QJsonObject summary{+ {"generatorType", payload.value("generatorType")},+ {"totalBars", payload.value("totalBars")},+ {"entryCount", payload.value("entryCount")},+ {"exitCount", payload.value("exitCount")},+ };+ add_cards_from(summary, {"generatorType", "entryCount", "exitCount", "totalBars"}, 4);+ fill_kv_table(summary);++ QJsonArray combined;+ for (const auto& v : payload.value("entries").toArray()) {+ QJsonObject o; o["type"] = "ENTRY"; o["date"] = v.toString(); combined.append(o);+ }+ for (const auto& v : payload.value("exits").toArray()) {+ QJsonObject o; o["type"] = "EXIT"; o["date"] = v.toString(); combined.append(o);+ }+ fill_details_table(combined, {"type", "date"});+ }+ else if (command == "labels_to_signals") {+ QJsonObject summary{+ {"labelType", payload.value("labelType")},+ {"entryLabel", payload.value("entryLabel")},+ {"exitLabel", payload.value("exitLabel")},+ {"entryCount", payload.value("entryCount")},+ {"exitCount", payload.value("exitCount")},+ {"totalBars", payload.value("totalBars")},+ };+ add_cards_from(summary, {"labelType", "entryCount", "exitCount", "totalBars",+ "entryLabel", "exitLabel"}, 3);+ fill_kv_table(summary);+ QJsonArray combined;+ for (const auto& v : payload.value("entries").toArray()) {+ QJsonObject o; o["type"] = "ENTRY"; o["date"] = v.toString(); combined.append(o);+ }+ for (const auto& v : payload.value("exits").toArray()) {+ QJsonObject o; o["type"] = "EXIT"; o["date"] = v.toString(); combined.append(o);+ }+ fill_details_table(combined, {"type", "date"});+ }+ else if (command == "indicator_sweep") {+ QJsonObject summary{+ {"indicator", payload.value("indicator")},+ {"totalCombinations", payload.value("totalCombinations")},+ };+ add_cards_from(summary, {"indicator", "totalCombinations"}, 2);+ // Flatten each result row: params + scalar stats+ auto results = payload.value("results").toArray();+ QJsonArray flat;+ for (const auto& v : results) {+ auto o = v.toObject();+ QJsonObject row;+ auto params = o.value("params").toObject();+ for (auto it = params.begin(); it != params.end(); ++it)+ row[it.key()] = it.value();+ for (const auto& k : QStringList{"mean", "std", "min", "max", "last"})+ if (o.contains(k)) row[k] = o.value(k);+ flat.append(row);+ }+ fill_details_table(flat);+ }+ else {+ // Unknown command — best-effort: show all scalar fields as cards.+ add_cards_from(payload, {});+ fill_kv_table(payload);+ }++ summary_layout_->addStretch();- // ── RAW JSON tab ──+ // ── RAW JSON tab (always populated) ──raw_json_edit_->setPlainText(QJsonDocument(payload).toJson(QJsonDocument::Indented));// Switch to summary tab@@ -1688,7 +2585,7 @@ void BacktestingScreen::on_result(const QString& provider, const QString& commanis_running_ = false;run_button_->setEnabled(true);set_status_state("READY", ui::colors::POSITIVE, "rgba(22,163,74,0.08)");- display_result(payload);+ display_result(command, payload);LOG_INFO("Backtesting", QString("[%1/%2] Complete").arg(provider, command));}diff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen.h b/fincept-qt/src/screens/backtesting/BacktestingScreen.hindex 18876ff79..76a1395aa 100644--- a/fincept-qt/src/screens/backtesting/BacktestingScreen.h+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen.h@@ -72,7 +72,11 @@ class BacktestingScreen : public QWidget, public IStatefulScreen, public IGroupLvoid update_command_buttons();void populate_strategies();void rebuild_strategy_params();- void display_result(const QJsonObject& data);+ void display_result(const QString& command, const QJsonObject& data);+ /// Toggle the right/left-panel section containers based on the active command.+ /// Each command consumes a different subset of the global config (e.g. ML+ /// Labels doesn't use commission/slippage/leverage/benchmark/strategy).+ void update_section_visibility();void display_error(const QString& msg);void clear_results();QJsonObject gather_args();@@ -97,6 +101,24 @@ class BacktestingScreen : public QWidget, public IStatefulScreen, public IGroupLQWidget* strategy_params_container_ = nullptr;QVBoxLayout* strategy_params_layout_ = nullptr;QVector<QDoubleSpinBox*> param_spinboxes_;+ // Per-param explicit-range editor (one trio per strategy param). Always built+ // alongside param_spinboxes_, but only made visible when the active command+ // is `optimize`. Indexed in lockstep with param_spinboxes_.+ QVector<QDoubleSpinBox*> param_min_spinboxes_;+ QVector<QDoubleSpinBox*> param_max_spinboxes_;+ QVector<QDoubleSpinBox*> param_step_spinboxes_;+ // Wrapper widgets for each (min/max/step) row so we toggle them as a group.+ QVector<QWidget*> param_range_rows_;++ // Right panel - section containers (toggled per-command).+ // Each wraps a labeled visual block (title + inputs) so the whole+ // section can be hidden when the active command doesn't consume it.+ QWidget* market_data_section_ = nullptr;+ QWidget* execution_section_ = nullptr;+ QWidget* advanced_section_ = nullptr;+ QWidget* benchmark_section_ = nullptr;+ // Left panel strategy block — only meaningful for backtest/optimize/walk_forward.+ QWidget* strategy_section_ = nullptr;// Right panel - configQLineEdit* symbols_edit_ = nullptr;@@ -123,24 +145,116 @@ class BacktestingScreen : public QWidget, public IStatefulScreen, public IGroupLQDoubleSpinBox* wf_train_ratio_spin_ = nullptr;// Indicator configQComboBox* indicator_combo_ = nullptr;- // Indicator signals config+ QSpinBox* indicator_period_spin_ = nullptr;+ // Indicator signals config — params shown depend on the chosen mode:+ // crossover_signals: fast_period + slow_period + ma_type+ // threshold_signals: period + lower + upper+ // breakout_signals: channel + period+ // mean_reversion_signals: period + z_entry + z_exit+ // signal_filter: base_indicator + base_period + filter_indicator+ // + filter_period + filter_threshold + filter_typeQComboBox* ind_signal_indicator_combo_ = nullptr;QComboBox* ind_signal_mode_combo_ = nullptr;- // Labels config+ // crossover_signals+ QWidget* is_fast_period_row_ = nullptr;+ QSpinBox* is_fast_period_spin_ = nullptr;+ QWidget* is_slow_period_row_ = nullptr;+ QSpinBox* is_slow_period_spin_ = nullptr;+ QWidget* is_ma_type_row_ = nullptr;+ QComboBox* is_ma_type_combo_ = nullptr;+ // threshold_signals+ QWidget* is_period_row_ = nullptr;+ QSpinBox* is_period_spin_ = nullptr;+ QWidget* is_lower_row_ = nullptr;+ QDoubleSpinBox* is_lower_spin_ = nullptr;+ QWidget* is_upper_row_ = nullptr;+ QDoubleSpinBox* is_upper_spin_ = nullptr;+ // breakout_signals+ QWidget* is_channel_row_ = nullptr;+ QComboBox* is_channel_combo_ = nullptr;+ // mean_reversion_signals+ QWidget* is_z_entry_row_ = nullptr;+ QDoubleSpinBox* is_z_entry_spin_ = nullptr;+ QWidget* is_z_exit_row_ = nullptr;+ QDoubleSpinBox* is_z_exit_spin_ = nullptr;+ // signal_filter+ QWidget* is_filter_indicator_row_ = nullptr;+ QComboBox* is_filter_indicator_combo_ = nullptr;+ QWidget* is_filter_period_row_ = nullptr;+ QSpinBox* is_filter_period_spin_ = nullptr;+ QWidget* is_filter_threshold_row_ = nullptr;+ QDoubleSpinBox* is_filter_threshold_spin_ = nullptr;+ QWidget* is_filter_type_row_ = nullptr;+ QComboBox* is_filter_type_combo_ = nullptr;+ // Labels config — different label generators use different params:+ // FIXLB: horizon, threshold (forward-return classification)+ // MEANLB: window, threshold (z-score mean reversion)+ // LEXLB: window only (local extrema)+ // TRENDLB: window, threshold (rolling regression slope)+ // BOLB: window, alpha (Bollinger Band zones)+ // Each row is wrapped in a container so labels_type_combo's change handler+ // can show/hide rows that don't apply to the chosen generator.QComboBox* labels_type_combo_ = nullptr;+ QWidget* labels_horizon_row_ = nullptr;QSpinBox* labels_horizon_spin_ = nullptr;+ QWidget* labels_window_row_ = nullptr;+ QSpinBox* labels_window_spin_ = nullptr;+ QWidget* labels_threshold_row_ = nullptr;QDoubleSpinBox* labels_threshold_spin_ = nullptr;- // Splitters config+ QWidget* labels_alpha_row_ = nullptr;+ QDoubleSpinBox* labels_alpha_spin_ = nullptr;+ // Splitters config — different splitters consume different params:+ // RollingSplitter: window_len + test_len + step+ // ExpandingSplitter: min_len + test_len + step+ // PurgedKFoldSplitter: n_splits + purge_len + embargo_lenQComboBox* splitter_type_combo_ = nullptr;+ QWidget* splitter_window_row_ = nullptr;QSpinBox* splitter_window_spin_ = nullptr;+ QWidget* splitter_min_row_ = nullptr;+ QSpinBox* splitter_min_spin_ = nullptr;+ QWidget* splitter_test_row_ = nullptr;+ QSpinBox* splitter_test_spin_ = nullptr;+ QWidget* splitter_step_row_ = nullptr;QSpinBox* splitter_step_spin_ = nullptr;- // Returns config+ QWidget* splitter_n_splits_row_ = nullptr;+ QSpinBox* splitter_n_splits_spin_ = nullptr;+ QWidget* splitter_purge_row_ = nullptr;+ QSpinBox* splitter_purge_spin_ = nullptr;+ QWidget* splitter_embargo_row_ = nullptr;+ QSpinBox* splitter_embargo_spin_ = nullptr;+ // Returns config — different analysis types consume different params:+ // returns_stats: (no extra knobs beyond benchmark + risk_free)+ // drawdowns: (no extra)+ // ranges: threshold+ // rolling: window + metricQComboBox* returns_type_combo_ = nullptr;+ QWidget* returns_window_row_ = nullptr;QSpinBox* returns_window_spin_ = nullptr;- // Signals config+ QWidget* returns_metric_row_ = nullptr;+ QComboBox* returns_metric_combo_ = nullptr;+ QWidget* returns_threshold_row_ = nullptr;+ QDoubleSpinBox* returns_threshold_spin_ = nullptr;+ // Signals config — params shown depend on the chosen generator:+ // RAND: n+ // RANDX: n+ // RANDNX: n + min_hold + max_hold+ // RPROB: entry_prob+ // RPROBX: entry_prob + exit_probQComboBox* signal_gen_combo_ = nullptr;+ QWidget* signal_count_row_ = nullptr;+ QSpinBox* signal_count_spin_ = nullptr;+ QWidget* signal_entry_prob_row_ = nullptr;+ QDoubleSpinBox* signal_entry_prob_spin_ = nullptr;+ QWidget* signal_exit_prob_row_ = nullptr;+ QDoubleSpinBox* signal_exit_prob_spin_ = nullptr;+ QWidget* signal_min_hold_row_ = nullptr;+ QSpinBox* signal_min_hold_spin_ = nullptr;+ QWidget* signal_max_hold_row_ = nullptr;+ QSpinBox* signal_max_hold_spin_ = nullptr;// Labels-to-signals configQComboBox* l2s_label_type_combo_ = nullptr;+ QSpinBox* l2s_entry_label_spin_ = nullptr;+ QSpinBox* l2s_exit_label_spin_ = nullptr;// Indicator sweep configQComboBox* sweep_indicator_combo_ = nullptr;QSpinBox* sweep_min_spin_ = nullptr;diff --git a/fincept-qt/src/services/backtesting/BacktestingService.cpp b/fincept-qt/src/services/backtesting/BacktestingService.cppindex 7d8c3f740..94370bdb9 100644--- a/fincept-qt/src/services/backtesting/BacktestingService.cpp+++ b/fincept-qt/src/services/backtesting/BacktestingService.cpp@@ -78,6 +78,18 @@ void BacktestingService::execute(const QString& provider, const QString& commandQJsonObject payload = root.contains("data") && root.value("data").isObject()? root.value("data").toObject(): root;+ // Some providers (optimize, walk_forward) historically returned+ // `{success: True, data: {success: false, error: ...}}`. Surface the+ // inner failure too so the UI doesn't render an empty result panel.+ if (payload.contains("success") && payload.value("success").isBool()+ && !payload.value("success").toBool()) {+ auto err = payload.value("error").toString();+ if (err.isEmpty())+ err = payload.value("message").toString("Command failed");+ LOG_ERROR("Backtesting", QString("[%1] Provider inner error: %2").arg(ctx, err));+ emit self->error_occurred(ctx, err);+ return;+ }LOG_INFO("Backtesting", QString("[%1] Result ready").arg(ctx));emit self->result_ready(provider, command, payload);});@@ -115,7 +127,10 @@ void BacktestingService::load_strategies(const QString& provider) {}void BacktestingService::load_command_options(const QString& provider) {- const QString cache_key = "backtest:options:" + provider;+ // Cache key versioned (v2) — Python option names changed (e.g. mode names,+ // splitter names, returns analysis types) and older cached entries will+ // serve UI strings that no longer round-trip through the provider.+ const QString cache_key = "backtest:options:v2:" + provider;const QVariant cached = fincept::CacheManager::instance().get(cache_key);if (!cached.isNull()) {auto doc = QJsonDocument::fromJson(cached.toString().toUtf8());diff --git a/fincept-qt/src/services/backtesting/BacktestingTypes.h b/fincept-qt/src/services/backtesting/BacktestingTypes.hindex e9c8175de..dd9727ccd 100644--- a/fincept-qt/src/services/backtesting/BacktestingTypes.h+++ b/fincept-qt/src/services/backtesting/BacktestingTypes.h@@ -28,14 +28,25 @@ struct Provider {};inline QVector<Provider> all_providers() {+ // Per-provider command list is the set of commands whose Python implementation+ // (1) accepts the args BacktestingScreen sends, AND (2) returns a payload that+ // display_result() can render. Commands that fail either test are deliberately+ // omitted — the UI's command sidebar is filtered against this list, so dropped+ // commands don't appear as broken buttons.return {{"vectorbt","VectorBT",QColor("#00E5FF"),{"backtest", "optimize", "walk_forward", "indicator", "indicator_signals", "labels", "splits", "returns","signals", "labels_to_signals", "indicator_sweep"}},- {"backtestingpy", "Backtesting.py", QColor("#00D66F"), {"backtest", "optimize", "walk_forward", "indicator"}},- {"fasttrade", "FastTrade", QColor("#FFC400"), {"backtest", "indicator"}},+ {"backtestingpy", "Backtesting.py", QColor("#00D66F"),+ // Requires `pip install backtesting`. All commands surface a clean install+ // error when the dep is missing; kept in the provider list so users see+ // the option and can install it.+ {"backtest", "optimize", "walk_forward", "indicator"}},+ {"fasttrade", "FastTrade", QColor("#FFC400"),+ // Requires `pip install fast_trade`. Same rationale as backtestingpy.+ {"backtest"}},{"zipline","Zipline",QColor("#FF3B8E"),@@ -44,8 +55,10 @@ inline QVector<Provider> all_providers() {{"bt","BT",QColor("#FF6B35"),- {"backtest", "optimize", "walk_forward", "indicator", "indicator_signals", "labels", "splits", "returns",- "signals", "labels_to_signals"}},+ // BT's extended commands (indicator/labels/splits/signals/returns/...) return+ // per-symbol-nested shapes that don't match the frontend renderer; only the+ // backtest-shaped commands are exposed.+ {"backtest", "optimize", "walk_forward"}},{"fincept", "Fincept", QColor("#d97706"), {"backtest", "optimize", "walk_forward"}},};}diff --git a/fincept-qt/src/trading/brokers/zerodha/ZerodhaAutoLogin.cpp b/fincept-qt/src/trading/brokers/zerodha/ZerodhaAutoLogin.cppindex 487d9b6ee..dd5752fb1 100644--- a/fincept-qt/src/trading/brokers/zerodha/ZerodhaAutoLogin.cpp+++ b/fincept-qt/src/trading/brokers/zerodha/ZerodhaAutoLogin.cpp@@ -3,8 +3,10 @@#include "core/logging/Logger.h"#include "trading/brokers/zerodha/Totp.h"+#include <QCoreApplication>#include <QCryptographicHash>#include <QDateTime>+#include <QEvent>#include <QEventLoop>#include <QJsonDocument>#include <QJsonObject>@@ -75,7 +77,20 @@ AutoLoginResult run_auto_login(const QString& user_id, const QString& password,return out;}- QNetworkAccessManager nam;+ // Heap-allocate so we can deleteLater() + drain DeferredDelete before+ // returning. A stack QNAM here lets socket-notifier teardown work leak+ // into the main runloop and crash the GUI hours later inside+ // qt_mac_socket_callback. RAII guard handles every early-return path.+ struct NamGuard {+ QNetworkAccessManager* p;+ ~NamGuard() {+ p->deleteLater();+ QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);+ }+ };+ auto* nam_holder = new QNetworkAccessManager;+ NamGuard nam_guard{nam_holder};+ QNetworkAccessManager& nam = *nam_holder;nam.setCookieJar(new QNetworkCookieJar(&nam));QString request_id;diff --git a/fincept-qt/src/trading/instruments/InstrumentService.cpp b/fincept-qt/src/trading/instruments/InstrumentService.cppindex f9c19ba60..e5935bcfb 100644--- a/fincept-qt/src/trading/instruments/InstrumentService.cpp+++ b/fincept-qt/src/trading/instruments/InstrumentService.cpp@@ -7,8 +7,10 @@#include "trading/instruments/InstrumentRepository.h"#include "trading/instruments/ZerodhaInstrumentParser.h"+#include <QCoreApplication>#include <QDate>#include <QDateTime>+#include <QEvent>#include <QEventLoop>#include <QJsonArray>#include <QJsonDocument>@@ -625,12 +627,15 @@ QByteArray InstrumentService::download_angel_master_json() {// mutex (which would starve all concurrent quote/history API calls for 10-20s).static const QString kUrl = "https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json";- QNetworkAccessManager nam;+ // Heap-allocate QNAM with deleteLater + DeferredDelete drain. A stack+ // QNAM here would leak Qt's macOS CFSocket-notifier teardown onto the+ // main runloop, causing a use-after-free crash hours later.+ auto* nam = new QNetworkAccessManager;QNetworkRequest req{QUrl(kUrl)};req.setRawHeader("Accept", "application/json");req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);- QNetworkReply* reply = nam.get(req);+ QNetworkReply* reply = nam->get(req);QEventLoop loop;QTimer timer;@@ -640,22 +645,28 @@ QByteArray InstrumentService::download_angel_master_json() {timer.start(60000); // 60s — large file on slow connectionloop.exec();+ auto drain = [&]() {+ reply->deleteLater();+ nam->deleteLater();+ QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);+ };+if (!timer.isActive()) {reply->abort();- reply->deleteLater();LOG_ERROR("InstrumentService", "AngelOne master contract download timed out");+ drain();return {};}timer.stop();if (reply->error() != QNetworkReply::NoError) {LOG_ERROR("InstrumentService", "Failed to download AngelOne master contract: " + reply->errorString());- reply->deleteLater();+ drain();return {};}QByteArray data = reply->readAll();- reply->deleteLater();+ drain();LOG_INFO("InstrumentService", QString("Downloaded AngelOne master contract: %1 bytes").arg(data.size()));return data;}@@ -666,12 +677,12 @@ QByteArray InstrumentService::download_groww_csv() {// mutex for 10-30s on slow links and would starve concurrent quote/order calls.static const QString kUrl = "https://growwapi-assets.groww.in/instruments/instrument.csv";- QNetworkAccessManager nam;+ auto* nam = new QNetworkAccessManager;QNetworkRequest req{QUrl(kUrl)};req.setRawHeader("Accept", "text/csv");req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);- QNetworkReply* reply = nam.get(req);+ QNetworkReply* reply = nam->get(req);QEventLoop loop;QTimer timer;@@ -681,22 +692,28 @@ QByteArray InstrumentService::download_groww_csv() {timer.start(60000); // 60s — ~27MB file on slow connectionloop.exec();+ auto drain = [&]() {+ reply->deleteLater();+ nam->deleteLater();+ QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);+ };+if (!timer.isActive()) {reply->abort();- reply->deleteLater();LOG_ERROR("InstrumentService", "Groww instrument CSV download timed out");+ drain();return {};}timer.stop();if (reply->error() != QNetworkReply::NoError) {LOG_ERROR("InstrumentService", "Failed to download Groww instrument CSV: " + reply->errorString());- reply->deleteLater();+ drain();return {};}QByteArray data = reply->readAll();- reply->deleteLater();+ drain();LOG_INFO("InstrumentService", QString("Downloaded Groww instrument CSV: %1 bytes").arg(data.size()));return data;}