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
py update
tilakpatel22ab4657391a01
diff --git a/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765458411167-lwpazelt6/main.py b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765458411167-lwpazelt6/main.pynew file mode 100644index 000000000..8ca1c8d3a--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765458411167-lwpazelt6/main.py@@ -0,0 +1,39 @@+# ==============================================================================+# Strategy: My Strategy+# Version: 1.0.0+# Author: User+# Description: User-created strategy+# Generated by Fincept Terminal+# ==============================================================================++# Simple Moving Average Crossover Strategy+# This is a basic example - modify as needed++from AlgorithmImports import *++class MyStrategy(QCAlgorithm):+ def Initialize(self):+ self.SetStartDate(2020, 1, 1)+ self.SetEndDate(2023, 12, 31)+ self.SetCash(100000)++ # Add equity+ self.symbol = self.AddEquity("SPY", Resolution.Daily).Symbol++ # Create indicators+ self.fast_sma = self.SMA(self.symbol, 50, Resolution.Daily)+ self.slow_sma = self.SMA(self.symbol, 200, Resolution.Daily)++ def OnData(self, data):+ if not self.fast_sma.IsReady or not self.slow_sma.IsReady:+ return++ # Buy signal: fast SMA crosses above slow SMA+ if self.fast_sma.Current.Value > self.slow_sma.Current.Value:+ if not self.Portfolio.Invested:+ self.SetHoldings(self.symbol, 1.0)++ # Sell signal: fast SMA crosses below slow SMA+ elif self.fast_sma.Current.Value < self.slow_sma.Current.Value:+ if self.Portfolio.Invested:+ self.Liquidate(self.symbol)diff --git a/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765458659674-tydnpsanu/main.py b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765458659674-tydnpsanu/main.pynew file mode 100644index 000000000..8ca1c8d3a--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765458659674-tydnpsanu/main.py@@ -0,0 +1,39 @@+# ==============================================================================+# Strategy: My Strategy+# Version: 1.0.0+# Author: User+# Description: User-created strategy+# Generated by Fincept Terminal+# ==============================================================================++# Simple Moving Average Crossover Strategy+# This is a basic example - modify as needed++from AlgorithmImports import *++class MyStrategy(QCAlgorithm):+ def Initialize(self):+ self.SetStartDate(2020, 1, 1)+ self.SetEndDate(2023, 12, 31)+ self.SetCash(100000)++ # Add equity+ self.symbol = self.AddEquity("SPY", Resolution.Daily).Symbol++ # Create indicators+ self.fast_sma = self.SMA(self.symbol, 50, Resolution.Daily)+ self.slow_sma = self.SMA(self.symbol, 200, Resolution.Daily)++ def OnData(self, data):+ if not self.fast_sma.IsReady or not self.slow_sma.IsReady:+ return++ # Buy signal: fast SMA crosses above slow SMA+ if self.fast_sma.Current.Value > self.slow_sma.Current.Value:+ if not self.Portfolio.Invested:+ self.SetHoldings(self.symbol, 1.0)++ # Sell signal: fast SMA crosses below slow SMA+ elif self.fast_sma.Current.Value < self.slow_sma.Current.Value:+ if self.Portfolio.Invested:+ self.Liquidate(self.symbol)diff --git a/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765459184481-2h0i5mama/main.py b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765459184481-2h0i5mama/main.pynew file mode 100644index 000000000..8ca1c8d3a--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765459184481-2h0i5mama/main.py@@ -0,0 +1,39 @@+# ==============================================================================+# Strategy: My Strategy+# Version: 1.0.0+# Author: User+# Description: User-created strategy+# Generated by Fincept Terminal+# ==============================================================================++# Simple Moving Average Crossover Strategy+# This is a basic example - modify as needed++from AlgorithmImports import *++class MyStrategy(QCAlgorithm):+ def Initialize(self):+ self.SetStartDate(2020, 1, 1)+ self.SetEndDate(2023, 12, 31)+ self.SetCash(100000)++ # Add equity+ self.symbol = self.AddEquity("SPY", Resolution.Daily).Symbol++ # Create indicators+ self.fast_sma = self.SMA(self.symbol, 50, Resolution.Daily)+ self.slow_sma = self.SMA(self.symbol, 200, Resolution.Daily)++ def OnData(self, data):+ if not self.fast_sma.IsReady or not self.slow_sma.IsReady:+ return++ # Buy signal: fast SMA crosses above slow SMA+ if self.fast_sma.Current.Value > self.slow_sma.Current.Value:+ if not self.Portfolio.Invested:+ self.SetHoldings(self.symbol, 1.0)++ # Sell signal: fast SMA crosses below slow SMA+ elif self.fast_sma.Current.Value < self.slow_sma.Current.Value:+ if self.Portfolio.Invested:+ self.Liquidate(self.symbol)diff --git a/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765459744490-cepk41rte/main.py b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765459744490-cepk41rte/main.pynew file mode 100644index 000000000..8ca1c8d3a--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765459744490-cepk41rte/main.py@@ -0,0 +1,39 @@+# ==============================================================================+# Strategy: My Strategy+# Version: 1.0.0+# Author: User+# Description: User-created strategy+# Generated by Fincept Terminal+# ==============================================================================++# Simple Moving Average Crossover Strategy+# This is a basic example - modify as needed++from AlgorithmImports import *++class MyStrategy(QCAlgorithm):+ def Initialize(self):+ self.SetStartDate(2020, 1, 1)+ self.SetEndDate(2023, 12, 31)+ self.SetCash(100000)++ # Add equity+ self.symbol = self.AddEquity("SPY", Resolution.Daily).Symbol++ # Create indicators+ self.fast_sma = self.SMA(self.symbol, 50, Resolution.Daily)+ self.slow_sma = self.SMA(self.symbol, 200, Resolution.Daily)++ def OnData(self, data):+ if not self.fast_sma.IsReady or not self.slow_sma.IsReady:+ return++ # Buy signal: fast SMA crosses above slow SMA+ if self.fast_sma.Current.Value > self.slow_sma.Current.Value:+ if not self.Portfolio.Invested:+ self.SetHoldings(self.symbol, 1.0)++ # Sell signal: fast SMA crosses below slow SMA+ elif self.fast_sma.Current.Value < self.slow_sma.Current.Value:+ if self.Portfolio.Invested:+ self.Liquidate(self.symbol)diff --git a/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765459826495-rbzq3jr6n/main.py b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765459826495-rbzq3jr6n/main.pynew file mode 100644index 000000000..8ca1c8d3a--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765459826495-rbzq3jr6n/main.py@@ -0,0 +1,39 @@+# ==============================================================================+# Strategy: My Strategy+# Version: 1.0.0+# Author: User+# Description: User-created strategy+# Generated by Fincept Terminal+# ==============================================================================++# Simple Moving Average Crossover Strategy+# This is a basic example - modify as needed++from AlgorithmImports import *++class MyStrategy(QCAlgorithm):+ def Initialize(self):+ self.SetStartDate(2020, 1, 1)+ self.SetEndDate(2023, 12, 31)+ self.SetCash(100000)++ # Add equity+ self.symbol = self.AddEquity("SPY", Resolution.Daily).Symbol++ # Create indicators+ self.fast_sma = self.SMA(self.symbol, 50, Resolution.Daily)+ self.slow_sma = self.SMA(self.symbol, 200, Resolution.Daily)++ def OnData(self, data):+ if not self.fast_sma.IsReady or not self.slow_sma.IsReady:+ return++ # Buy signal: fast SMA crosses above slow SMA+ if self.fast_sma.Current.Value > self.slow_sma.Current.Value:+ if not self.Portfolio.Invested:+ self.SetHoldings(self.symbol, 1.0)++ # Sell signal: fast SMA crosses below slow SMA+ elif self.fast_sma.Current.Value < self.slow_sma.Current.Value:+ if self.Portfolio.Invested:+ self.Liquidate(self.symbol)diff --git a/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765459889779-mvrzrg0vd/main.py b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765459889779-mvrzrg0vd/main.pynew file mode 100644index 000000000..8ca1c8d3a--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765459889779-mvrzrg0vd/main.py@@ -0,0 +1,39 @@+# ==============================================================================+# Strategy: My Strategy+# Version: 1.0.0+# Author: User+# Description: User-created strategy+# Generated by Fincept Terminal+# ==============================================================================++# Simple Moving Average Crossover Strategy+# This is a basic example - modify as needed++from AlgorithmImports import *++class MyStrategy(QCAlgorithm):+ def Initialize(self):+ self.SetStartDate(2020, 1, 1)+ self.SetEndDate(2023, 12, 31)+ self.SetCash(100000)++ # Add equity+ self.symbol = self.AddEquity("SPY", Resolution.Daily).Symbol++ # Create indicators+ self.fast_sma = self.SMA(self.symbol, 50, Resolution.Daily)+ self.slow_sma = self.SMA(self.symbol, 200, Resolution.Daily)++ def OnData(self, data):+ if not self.fast_sma.IsReady or not self.slow_sma.IsReady:+ return++ # Buy signal: fast SMA crosses above slow SMA+ if self.fast_sma.Current.Value > self.slow_sma.Current.Value:+ if not self.Portfolio.Invested:+ self.SetHoldings(self.symbol, 1.0)++ # Sell signal: fast SMA crosses below slow SMA+ elif self.fast_sma.Current.Value < self.slow_sma.Current.Value:+ if self.Portfolio.Invested:+ self.Liquidate(self.symbol)diff --git a/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765460676743-7in89xz6n/lean.json b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765460676743-7in89xz6n/lean.jsonnew file mode 100644index 000000000..7127bf637--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765460676743-7in89xz6n/lean.json@@ -0,0 +1,7 @@+{+ "algorithm-language": "Python",+ "parameters": {},+ "description": "quantconnect-lean-1765460676743-7in89xz6n",+ "cloud-id": 0,+ "local-id": 0+}\ No newline at end of filediff --git a/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765460676743-7in89xz6n/main.py b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765460676743-7in89xz6n/main.pynew file mode 100644index 000000000..8ca1c8d3a--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/lean_projects/quantconnect-lean-1765460676743-7in89xz6n/main.py@@ -0,0 +1,39 @@+# ==============================================================================+# Strategy: My Strategy+# Version: 1.0.0+# Author: User+# Description: User-created strategy+# Generated by Fincept Terminal+# ==============================================================================++# Simple Moving Average Crossover Strategy+# This is a basic example - modify as needed++from AlgorithmImports import *++class MyStrategy(QCAlgorithm):+ def Initialize(self):+ self.SetStartDate(2020, 1, 1)+ self.SetEndDate(2023, 12, 31)+ self.SetCash(100000)++ # Add equity+ self.symbol = self.AddEquity("SPY", Resolution.Daily).Symbol++ # Create indicators+ self.fast_sma = self.SMA(self.symbol, 50, Resolution.Daily)+ self.slow_sma = self.SMA(self.symbol, 200, Resolution.Daily)++ def OnData(self, data):+ if not self.fast_sma.IsReady or not self.slow_sma.IsReady:+ return++ # Buy signal: fast SMA crosses above slow SMA+ if self.fast_sma.Current.Value > self.slow_sma.Current.Value:+ if not self.Portfolio.Invested:+ self.SetHoldings(self.symbol, 1.0)++ # Sell signal: fast SMA crosses below slow SMA+ elif self.fast_sma.Current.Value < self.slow_sma.Current.Value:+ if self.Portfolio.Invested:+ self.Liquidate(self.symbol)diff --git a/fincept-terminal-desktop/src-tauri/resources/requirements.txt b/fincept-terminal-desktop/src-tauri/resources/requirements.txtindex 38dce51e9..fc1fba2a7 100644--- a/fincept-terminal-desktop/src-tauri/resources/requirements.txt+++ b/fincept-terminal-desktop/src-tauri/resources/requirements.txt@@ -19,6 +19,7 @@ multidict==6.7.0multitasking==0.0.12numpy==1.26.4pandas==2.3.3+vectorbt==0.26.1peewee==3.18.3pip_system_certs==5.3platformdirs==4.5.0diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.pyindex e5b9cc5f1..c416e7e37 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py@@ -190,23 +190,17 @@ class VectorBTProvider(BacktestingProviderBase):consecutive_losses=0,)- # Equity curve- equity_curve = portfolio.value()- equity = [- EquityPoint(- date=str(date),- equity=float(value),- returns=0,- drawdown=0,- )- for date, value in equity_curve.items()- ]+ # Parse trades from portfolio+ trades = self._parse_trades(portfolio)++ # Equity curve with proper returns and drawdown+ equity = self._build_equity_curve(portfolio, initial_capital)result = BacktestResult(id=backtest_id,status='completed',performance=performance,- trades=[], # Would parse from portfolio.trades+ trades=trades,equity=equity,statistics=statistics,logs=logs,@@ -235,14 +229,42 @@ class VectorBTProvider(BacktestingProviderBase):"""Get historical data using yfinance"""try:import yfinance as yf+ import pandas as pdsymbols = request.get('symbols', [])start_date = request.get('startDate')end_date = request.get('endDate')+ timeframe = request.get('timeframe', 'daily')+ # Download datadata = yf.download(symbols, start=start_date, end=end_date)- return [] # Would convert to HistoricalData format+ if data.empty:+ return []++ # Convert to HistoricalData format+ result = []+ for symbol in symbols:+ symbol_data = data if len(symbols) == 1 else data[symbol]++ bars = []+ for date, row in symbol_data.iterrows():+ bars.append({+ 'date': date.isoformat(),+ 'open': float(row['Open']) if 'Open' in row else 0,+ 'high': float(row['High']) if 'High' in row else 0,+ 'low': float(row['Low']) if 'Low' in row else 0,+ 'close': float(row['Close']) if 'Close' in row else 0,+ 'volume': int(row['Volume']) if 'Volume' in row else 0,+ })++ result.append({+ 'symbol': symbol,+ 'timeframe': timeframe,+ 'data': bars+ })++ return resultexcept Exception as e:self._error('Data fetch failed', e)@@ -282,6 +304,65 @@ class VectorBTProvider(BacktestingProviderBase):consecutive_wins=0, consecutive_losses=0)+ def _parse_trades(self, portfolio) -> list:+ """Parse trades from VectorBT portfolio"""+ trades = []+ try:+ if hasattr(portfolio, 'trades') and hasattr(portfolio.trades, 'records'):+ trade_records = portfolio.trades.records++ for idx, trade in enumerate(trade_records):+ entry_idx = trade['entry_idx'] if hasattr(trade, '__getitem__') else getattr(trade, 'entry_idx', 0)+ exit_idx = trade['exit_idx'] if hasattr(trade, '__getitem__') else getattr(trade, 'exit_idx', 0)+ pnl = trade['pnl'] if hasattr(trade, '__getitem__') else getattr(trade, 'pnl', 0)++ trades.append(Trade(+ id=f'trade_{idx}',+ symbol=str(getattr(trade, 'col', 'UNKNOWN')),+ entry_date=str(entry_idx),+ side='long' if pnl >= 0 else 'short',+ quantity=float(getattr(trade, 'size', 0)),+ entry_price=float(getattr(trade, 'entry_price', 0)),+ commission=float(getattr(trade, 'fees', 0)),+ slippage=0,+ exit_date=str(exit_idx),+ exit_price=float(getattr(trade, 'exit_price', 0)),+ pnl=float(pnl),+ pnl_percent=float(getattr(trade, 'return', 0)),+ holding_period=int(exit_idx - entry_idx) if exit_idx > entry_idx else 0,+ exit_reason='signal'+ ))+ except Exception as e:+ self._error('Failed to parse trades', e)++ return trades++ def _build_equity_curve(self, portfolio, initial_capital: float) -> list:+ """Build equity curve with returns and drawdown"""+ equity = []+ try:+ value_series = portfolio.value()+ peak = initial_capital++ for date, value in value_series.items():+ # Calculate returns+ returns = (value - initial_capital) / initial_capital if initial_capital > 0 else 0++ # Calculate drawdown+ peak = max(peak, value)+ drawdown = (value - peak) / peak if peak > 0 else 0++ equity.append(EquityPoint(+ date=str(date),+ equity=float(value),+ returns=float(returns),+ drawdown=float(drawdown),+ ))+ except Exception as e:+ self._error('Failed to build equity curve', e)++ return equity+# CLI Entry Pointdef main():diff --git a/fincept-terminal-desktop/src/components/settings/BacktestingProvidersPanel.tsx b/fincept-terminal-desktop/src/components/settings/BacktestingProvidersPanel.tsxindex e7091920d..2914dd5a9 100644--- a/fincept-terminal-desktop/src/components/settings/BacktestingProvidersPanel.tsx+++ b/fincept-terminal-desktop/src/components/settings/BacktestingProvidersPanel.tsx@@ -54,14 +54,14 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {// New provider formconst [newProviderForm, setNewProviderForm] = useState({- name: 'lean',+ name: 'QuantConnect Lean',adapter_type: 'LeanAdapter',config: JSON.stringify({- leanCliPath: 'lean',- projectsPath: './lean_projects',- dataPath: './lean_data',- resultsPath: './lean_results',+ leanCliPath: 'C:/Users/Tilak/AppData/Roaming/Python/Python313/Scripts/lean.exe',+ projectsPath: 'C:/windowsdisk/finceptTerminal/fincept-terminal-desktop/lean_projects',+ dataPath: 'C:/windowsdisk/finceptTerminal/fincept-terminal-desktop/lean_data',+ resultsPath: 'C:/windowsdisk/finceptTerminal/fincept-terminal-desktop/lean_results',environment: 'backtesting',},null,@@ -79,11 +79,14 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {*/const registerDefaultProviders = () => {try {- // Register Lean adapter- const leanAdapter = new LeanAdapter();- backtestingRegistry.registerProvider(leanAdapter);+ // Check if already registered to avoid duplicates+ if (!backtestingRegistry.getProvider('QuantConnect Lean')) {+ // Register Lean adapter+ const leanAdapter = new LeanAdapter();+ backtestingRegistry.registerProvider(leanAdapter);- console.log('[Backtesting] Registered providers:', backtestingRegistry.listProviders());+ console.log('[Backtesting] Registered providers:', backtestingRegistry.listProviders());+ }} catch (error) {console.error('[Backtesting] Failed to register providers:', error);}@@ -133,7 +136,7 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {// Initialize with configconst config = JSON.parse(provider.config);- const initResult = await registeredProvider.initialize(config);+ const initResult = await registeredProvider.initialize({ settings: config });if (!initResult.success) {throw new Error(initResult.error || 'Initialization failed');@@ -175,6 +178,26 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {*/const activateProvider = async (providerName: string) => {try {+ // Get provider from registry+ const registeredProvider = backtestingRegistry.getProvider(providerName);+ if (!registeredProvider) {+ throw new Error(`Provider "${providerName}" not registered`);+ }++ // Get provider config from database+ const dbProvider = providers.find(p => p.name === providerName);+ if (!dbProvider) {+ throw new Error(`Provider "${providerName}" not found in database`);+ }++ // Initialize with config+ const config = JSON.parse(dbProvider.config);+ const initResult = await registeredProvider.initialize({ settings: config });++ if (!initResult.success) {+ throw new Error(initResult.error || 'Initialization failed');+ }+// Set active in databaseawait sqliteService.setActiveBacktestingProvider(providerName);@@ -214,14 +237,14 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {// Reset formsetNewProviderForm({- name: 'lean',+ name: 'QuantConnect Lean',adapter_type: 'LeanAdapter',config: JSON.stringify({- leanCliPath: 'lean',- projectsPath: './lean_projects',- dataPath: './lean_data',- resultsPath: './lean_results',+ leanCliPath: 'C:/Users/Tilak/AppData/Roaming/Python/Python313/Scripts/lean.exe',+ projectsPath: 'C:/windowsdisk/finceptTerminal/fincept-terminal-desktop/lean_projects',+ dataPath: 'C:/windowsdisk/finceptTerminal/fincept-terminal-desktop/lean_data',+ resultsPath: 'C:/windowsdisk/finceptTerminal/fincept-terminal-desktop/lean_results',environment: 'backtesting',},null,@@ -358,11 +381,11 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {borderRadius: '4px',}}>- <option value="lean">QuantConnect Lean</option>- <option value="backtrader">Backtrader</option>- <option value="vectorbt">VectorBT</option>- <option value="quantlib">QuantLib</option>- <option value="custom">Custom</option>+ <option value="QuantConnect Lean">QuantConnect Lean</option>+ <option value="Backtrader">Backtrader</option>+ <option value="VectorBT">VectorBT</option>+ <option value="QuantLib">QuantLib</option>+ <option value="Custom">Custom</option></select></div>diff --git a/fincept-terminal-desktop/src/components/tabs/BacktestingTab.tsx b/fincept-terminal-desktop/src/components/tabs/BacktestingTab.tsxindex dc4d53625..9ef4f878b 100644--- a/fincept-terminal-desktop/src/components/tabs/BacktestingTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/BacktestingTab.tsx@@ -26,12 +26,14 @@ import {AlertCircle,FileText,} from 'lucide-react';+import { LineChart, Line, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';import { backtestingService } from '@/services/backtesting/BacktestingService';import { backtestingRegistry } from '@/services/backtesting/BacktestingProviderRegistry';import { sqliteService, type BacktestRun } from '@/services/sqliteService';import { useTerminalTheme } from '@/contexts/ThemeContext';import { BacktestRequest, BacktestResult } from '@/services/backtesting/interfaces/types';import { StrategyDefinition } from '@/services/backtesting/interfaces/IStrategyDefinition';+import { STRATEGY_TEMPLATES, fillTemplate, type StrategyTemplate } from '@/services/backtesting/StrategyTemplates';type EditorMode = 'code' | 'visual' | 'template';@@ -55,6 +57,7 @@ export default function BacktestingTab() {const [isRunning, setIsRunning] = useState(false);const [currentResult, setCurrentResult] = useState<BacktestResult | null>(null);const [error, setError] = useState<string | null>(null);+ const [executionLogs, setExecutionLogs] = useState<string[]>([]);// Historyconst [backtestHistory, setBacktestHistory] = useState<BacktestRun[]>([]);@@ -63,12 +66,59 @@ export default function BacktestingTab() {// Providerconst [activeProvider, setActiveProvider] = useState<string | null>(null);+ // Template state+ const [selectedTemplate, setSelectedTemplate] = useState<StrategyTemplate | null>(null);+ const [templateParams, setTemplateParams] = useState<Record<string, any>>({});++ // Visual builder state+ const [visualNodes, setVisualNodes] = useState<any[]>([]);+useEffect(() => {loadBacktestHistory();- const provider = backtestingRegistry.getActiveProvider();- setActiveProvider(provider?.name || null);+ checkAndInitializeProvider();}, []);+ const checkAndInitializeProvider = async () => {+ try {+ // Check if provider is active in registry+ let provider = backtestingRegistry.getActiveProvider();+ console.log('[BacktestingTab] Active provider from registry:', provider);++ // If no active provider, try to load from database and activate+ if (!provider) {+ console.log('[BacktestingTab] No active provider, checking database...');+ const dbProviders = await sqliteService.getBacktestingProviders();+ const activeDbProvider = dbProviders.find(p => p.is_active);++ console.log('[BacktestingTab] Active provider from DB:', activeDbProvider);++ if (activeDbProvider) {+ // Get provider from registry+ const registeredProvider = backtestingRegistry.getProvider(activeDbProvider.name);++ if (registeredProvider) {+ console.log('[BacktestingTab] Found registered provider:', registeredProvider.name);++ // Initialize it+ const config = JSON.parse(activeDbProvider.config);+ await registeredProvider.initialize({ settings: config });++ // Set as active+ await backtestingRegistry.setActiveProvider(activeDbProvider.name);++ provider = registeredProvider;+ console.log('[BacktestingTab] Provider initialized and activated');+ }+ }+ }++ console.log('[BacktestingTab] All registered providers:', backtestingRegistry.listProviders());+ setActiveProvider(provider?.name || null);+ } catch (error) {+ console.error('[BacktestingTab] Failed to initialize provider:', error);+ }+ };+const loadBacktestHistory = async () => {try {const runs = await sqliteService.getBacktestRuns();@@ -78,17 +128,83 @@ export default function BacktestingTab() {}};+ const validatePythonSyntax = (code: string): { valid: boolean; error?: string } => {+ // Basic Python syntax checks+ const lines = code.split('\n');++ // Check for common syntax errors+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i].trim();++ // Skip empty lines and comments+ if (!line || line.startsWith('#')) continue;++ // Check for unmatched parentheses in the line+ const openParen = (line.match(/\(/g) || []).length;+ const closeParen = (line.match(/\)/g) || []).length;+ const openBracket = (line.match(/\[/g) || []).length;+ const closeBracket = (line.match(/\]/g) || []).length;++ if (line.endsWith(':') && i + 1 < lines.length) {+ const nextLine = lines[i + 1];+ if (nextLine.trim() && !nextLine.startsWith(' ') && !nextLine.startsWith('\t')) {+ return { valid: false, error: `Line ${i + 1}: Expected indentation after ':'` };+ }+ }+ }++ // Check for required Lean class+ if (!code.includes('class ') || !code.includes('QCAlgorithm')) {+ return { valid: false, error: 'Strategy must define a class inheriting from QCAlgorithm' };+ }++ if (!code.includes('def Initialize(')) {+ return { valid: false, error: 'Strategy must have an Initialize() method' };+ }++ return { valid: true };+ };++ const addLog = (message: string) => {+ setExecutionLogs(prev => [...prev, `[${new Date().toLocaleTimeString()}] ${message}`]);+ };+const handleRunBacktest = async () => {if (!activeProvider) {- setError('No backtesting provider active. Please activate a provider in Settings.');+ setError('No backtesting provider active. Please activate a provider in Settings → Backtesting Providers.');+ return;+ }++ // Validate syntax first+ const validation = validatePythonSyntax(strategyCode);+ if (!validation.valid) {+ setError(`Syntax Error: ${validation.error}`);return;}setIsRunning(true);setError(null);setCurrentResult(null);+ setExecutionLogs([]);++ // Set timeout to prevent infinite loading+ const timeoutId = setTimeout(() => {+ if (isRunning) {+ setError('Backtest timed out after 5 minutes. The backtest may still be running in the background.');+ setIsRunning(false);+ }+ }, 300000); // 5 minutestry {+ addLog('Starting backtest...');+ console.log('[Backtest] Starting backtest with provider:', activeProvider);+ console.log('[Backtest] Config:', config);++ addLog(`Using provider: ${activeProvider}`);+ addLog(`Strategy: ${strategyName}`);+ addLog(`Period: ${config.startDate} to ${config.endDate}`);+ addLog(`Initial Capital: $${config.initialCapital.toLocaleString()}`);+// Build strategy definitionconst strategy: StrategyDefinition = {name: strategyName,@@ -108,6 +224,8 @@ export default function BacktestingTab() {},};+ addLog('Building backtest request...');+// Build backtest requestconst request: BacktestRequest = {strategy,@@ -118,27 +236,46 @@ export default function BacktestingTab() {parameters: {},};+ console.log('[Backtest] Request:', request);+ addLog('Submitting to Lean engine...');+// Run backtestconst result = await backtestingService.runBacktest(request);- setCurrentResult(result);-- // Save to database- await sqliteService.saveBacktestRun({- id: result.id,- strategy_id: undefined,- provider_name: activeProvider,- config: JSON.stringify(config),- results: JSON.stringify(result),- status: result.status,- performance_metrics: JSON.stringify(result.performance),- error_message: result.error,- });-- // Reload history- await loadBacktestHistory();+ console.log('[Backtest] Result:', result);++ clearTimeout(timeoutId);++ if (result.status === 'completed') {+ addLog('✓ Backtest completed successfully!');+ setCurrentResult(result);++ // Save to database+ await sqliteService.saveBacktestRun({+ id: result.id,+ strategy_id: undefined,+ provider_name: activeProvider,+ config: JSON.stringify(config),+ results: JSON.stringify(result),+ status: result.status,+ performance_metrics: JSON.stringify(result.performance),+ error_message: result.error,+ });++ addLog('Results saved to history');++ // Reload history+ await loadBacktestHistory();+ } else if (result.status === 'failed') {+ addLog('✗ Backtest failed');+ setError(result.error || 'Backtest failed with unknown error');+ }} catch (err) {- setError(String(err));- console.error('Backtest failed:', err);+ clearTimeout(timeoutId);+ const errorMessage = err instanceof Error ? err.message : String(err);+ addLog(`✗ Error: ${errorMessage}`);+ setError(errorMessage);+ console.error('[Backtest] Failed:', err);+ console.error('[Backtest] Stack:', err instanceof Error ? err.stack : 'No stack');} finally {setIsRunning(false);}@@ -171,6 +308,26 @@ export default function BacktestingTab() {return '$' + value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });};+ const handleSelectTemplate = (template: StrategyTemplate) => {+ setSelectedTemplate(template);++ // Initialize params with defaults+ const defaultParams: Record<string, any> = {};+ template.parameters.forEach(param => {+ defaultParams[param.name] = param.default;+ });+ setTemplateParams(defaultParams);+ };++ const handleApplyTemplate = () => {+ if (!selectedTemplate) return;++ const filledCode = fillTemplate(selectedTemplate, templateParams);+ setStrategyCode(filledCode);+ setStrategyName(selectedTemplate.name);+ setEditorMode('code');+ };+return (<div style={{height: '100%',@@ -199,6 +356,23 @@ export default function BacktestingTab() {</div><div style={{ display: 'flex', gap: '8px' }}>+ <button+ onClick={checkAndInitializeProvider}+ style={{+ padding: '8px 16px',+ background: colors.panel,+ color: colors.text,+ border: `1px solid ${colors.textMuted}`,+ borderRadius: '6px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ }}+ >+ <RefreshCw size={16} />+ Refresh Provider+ </button><buttononClick={handleRunBacktest}disabled={isRunning || !activeProvider}@@ -316,21 +490,235 @@ export default function BacktestingTab() {)}{editorMode === 'visual' && (- <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: colors.textMuted }}>- <div style={{ textAlign: 'center' }}>- <Eye size={48} style={{ opacity: 0.5, margin: '0 auto 16px' }} />- <p>Visual strategy builder</p>- <p style={{ fontSize: '0.85rem' }}>Coming soon...</p>+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '16px' }}>+ <div style={{ marginBottom: '16px' }}>+ <h3 style={{ fontSize: '1rem', marginBottom: '8px' }}>Visual Strategy Builder</h3>+ <p style={{ fontSize: '0.85rem', color: colors.textMuted }}>Build strategies using blocks - no coding required</p>+ </div>++ {/* Building Blocks */}+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px', marginBottom: '16px' }}>+ {[+ { name: 'Entry Condition', type: 'condition', icon: '🎯' },+ { name: 'Exit Condition', type: 'condition', icon: '🚪' },+ { name: 'Indicator (SMA)', type: 'indicator', icon: '📊' },+ { name: 'Indicator (RSI)', type: 'indicator', icon: '📈' },+ { name: 'Buy Order', type: 'order', icon: '🟢' },+ { name: 'Sell Order', type: 'order', icon: '🔴' },+ ].map((block) => (+ <div+ key={block.name}+ style={{+ padding: '12px',+ background: colors.panel,+ border: `1px solid ${colors.textMuted}`,+ borderRadius: '6px',+ cursor: 'pointer',+ textAlign: 'center',+ }}+ onClick={() => setVisualNodes([...visualNodes, { ...block, id: Date.now() }])}+ >+ <div style={{ fontSize: '2rem', marginBottom: '4px' }}>{block.icon}</div>+ <div style={{ fontSize: '0.8rem' }}>{block.name}</div>+ </div>+ ))}+ </div>++ {/* Canvas */}+ <div style={{ flex: 1, background: colors.background, border: `1px solid ${colors.textMuted}`, borderRadius: '6px', padding: '16px', overflowY: 'auto' }}>+ {visualNodes.length === 0 ? (+ <div style={{ textAlign: 'center', color: colors.textMuted, paddingTop: '40px' }}>+ <Eye size={48} style={{ opacity: 0.5, margin: '0 auto 16px' }} />+ <p>Click blocks above to add them to your strategy</p>+ </div>+ ) : (+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>+ {visualNodes.map((node, idx) => (+ <div+ key={node.id}+ style={{+ padding: '12px',+ background: colors.panel,+ border: `1px solid ${colors.accent}`,+ borderRadius: '4px',+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{ fontSize: '1.5rem' }}>{node.icon}</span>+ <span>{node.name}</span>+ </div>+ <button+ onClick={() => setVisualNodes(visualNodes.filter((_, i) => i !== idx))}+ style={{+ background: colors.alert,+ color: 'white',+ border: 'none',+ padding: '4px 8px',+ borderRadius: '4px',+ cursor: 'pointer',+ fontSize: '0.75rem',+ }}+ >+ Remove+ </button>+ </div>+ ))}+ </div>+ )}</div>++ {/* Generate Code Button */}+ {visualNodes.length > 0 && (+ <button+ onClick={() => {+ // Simple code generation+ const code = `# Auto-generated from visual builder\nfrom AlgorithmImports import *\n\nclass VisualStrategy(QCAlgorithm):\n def Initialize(self):\n self.SetStartDate(2020, 1, 1)\n self.SetCash(100000)\n # Add your logic here based on blocks\n`;+ setStrategyCode(code);+ setStrategyName('Visual Strategy');+ setEditorMode('code');+ }}+ style={{+ marginTop: '12px',+ padding: '10px 20px',+ background: colors.accent,+ color: 'white',+ border: 'none',+ borderRadius: '6px',+ cursor: 'pointer',+ fontWeight: '600',+ width: '100%',+ }}+ >+ Generate Code from Blocks+ </button>+ )}</div>)}{editorMode === 'template' && (- <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: colors.textMuted }}>- <div style={{ textAlign: 'center' }}>- <FileText size={48} style={{ opacity: 0.5, margin: '0 auto 16px' }} />- <p>Strategy templates</p>- <p style={{ fontSize: '0.85rem' }}>Coming soon...</p>+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>+ {/* Template List */}+ <div style={{ width: '300px', borderRight: `1px solid ${colors.textMuted}`, overflowY: 'auto', padding: '16px' }}>+ <h3 style={{ fontSize: '0.9rem', marginBottom: '12px', color: colors.text }}>Strategy Templates</h3>+ {STRATEGY_TEMPLATES.map((template) => (+ <div+ key={template.id}+ onClick={() => handleSelectTemplate(template)}+ style={{+ padding: '12px',+ marginBottom: '8px',+ background: selectedTemplate?.id === template.id ? colors.accent + '20' : colors.panel,+ border: `1px solid ${selectedTemplate?.id === template.id ? colors.accent : colors.textMuted}`,+ borderRadius: '4px',+ cursor: 'pointer',+ }}+ >+ <div style={{ fontWeight: '600', fontSize: '0.85rem', marginBottom: '4px' }}>{template.name}</div>+ <div style={{ fontSize: '0.75rem', color: colors.textMuted, marginBottom: '4px' }}>{template.description}</div>+ <div style={{ display: 'flex', gap: '6px', fontSize: '0.7rem' }}>+ <span style={{ padding: '2px 6px', background: colors.background, borderRadius: '3px' }}>{template.category}</span>+ <span style={{ padding: '2px 6px', background: colors.background, borderRadius: '3px' }}>{template.difficulty}</span>+ </div>+ </div>+ ))}+ </div>++ {/* Template Details & Parameters */}+ <div style={{ flex: 1, overflowY: 'auto', padding: '16px' }}>+ {selectedTemplate ? (+ <>+ <h2 style={{ fontSize: '1.2rem', marginBottom: '8px' }}>{selectedTemplate.name}</h2>+ <p style={{ fontSize: '0.85rem', color: colors.textMuted, marginBottom: '16px' }}>{selectedTemplate.description}</p>++ {/* Parameters */}+ <div style={{ marginBottom: '20px' }}>+ <h3 style={{ fontSize: '0.9rem', marginBottom: '12px' }}>Parameters</h3>+ {selectedTemplate.parameters.map((param) => (+ <div key={param.name} style={{ marginBottom: '12px' }}>+ <label style={{ display: 'block', fontSize: '0.85rem', marginBottom: '4px' }}>+ {param.name} - {param.description}+ </label>+ {param.type === 'number' ? (+ <input+ type="number"+ value={templateParams[param.name] ?? param.default}+ onChange={(e) => setTemplateParams({ ...templateParams, [param.name]: Number(e.target.value) })}+ min={param.min}+ max={param.max}+ style={{+ width: '100%',+ padding: '8px',+ background: colors.background,+ border: `1px solid ${colors.textMuted}`,+ borderRadius: '4px',+ color: colors.text,+ fontSize: '0.85rem',+ }}+ />+ ) : param.type === 'boolean' ? (+ <input+ type="checkbox"+ checked={templateParams[param.name] ?? param.default}+ onChange={(e) => setTemplateParams({ ...templateParams, [param.name]: e.target.checked })}+ />+ ) : (+ <input+ type="text"+ value={templateParams[param.name] ?? param.default}+ onChange={(e) => setTemplateParams({ ...templateParams, [param.name]: e.target.value })}+ style={{+ width: '100%',+ padding: '8px',+ background: colors.background,+ border: `1px solid ${colors.textMuted}`,+ borderRadius: '4px',+ color: colors.text,+ fontSize: '0.85rem',+ }}+ />+ )}+ </div>+ ))}+ </div>++ {/* Expected Performance */}+ {selectedTemplate.expectedPerformance && (+ <div style={{ marginBottom: '20px', padding: '12px', background: colors.panel, borderRadius: '4px' }}>+ <h3 style={{ fontSize: '0.9rem', marginBottom: '8px' }}>Expected Performance</h3>+ <div style={{ fontSize: '0.85rem' }}>+ <div>Avg Return: {selectedTemplate.expectedPerformance.avgReturn}</div>+ <div>Sharpe Ratio: {selectedTemplate.expectedPerformance.sharpeRange}</div>+ <div>Max Drawdown: {selectedTemplate.expectedPerformance.maxDD}</div>+ </div>+ </div>+ )}++ {/* Apply Button */}+ <button+ onClick={handleApplyTemplate}+ style={{+ padding: '10px 20px',+ background: colors.accent,+ color: 'white',+ border: 'none',+ borderRadius: '6px',+ cursor: 'pointer',+ fontWeight: '600',+ width: '100%',+ }}+ >+ Apply Template to Code Editor+ </button>+ </>+ ) : (+ <div style={{ textAlign: 'center', color: colors.textMuted, paddingTop: '40px' }}>+ <FileText size={48} style={{ opacity: 0.5, margin: '0 auto 16px' }} />+ <p>Select a template from the list</p>+ </div>+ )}</div></div>)}@@ -419,37 +807,106 @@ export default function BacktestingTab() {background: colors.panel,}}><button+ onClick={() => setSelectedHistoryId(null)}style={{padding: '12px 20px',- background: colors.background,- color: colors.text,+ background: !selectedHistoryId ? colors.background : 'transparent',+ color: !selectedHistoryId ? colors.text : colors.textMuted,border: 'none',- borderBottom: `2px solid ${colors.accent}`,+ borderBottom: !selectedHistoryId ? `2px solid ${colors.accent}` : '2px solid transparent',cursor: 'pointer',fontSize: '0.9rem',- fontWeight: '600',+ fontWeight: !selectedHistoryId ? '600' : '400',}}>Results</button><button+ onClick={() => setSelectedHistoryId('history')}style={{padding: '12px 20px',- background: 'transparent',- color: colors.textMuted,+ background: selectedHistoryId === 'history' ? colors.background : 'transparent',+ color: selectedHistoryId === 'history' ? colors.text : colors.textMuted,border: 'none',- borderBottom: '2px solid transparent',+ borderBottom: selectedHistoryId === 'history' ? `2px solid ${colors.accent}` : '2px solid transparent',cursor: 'pointer',fontSize: '0.9rem',+ fontWeight: selectedHistoryId === 'history' ? '600' : '400',}}>- History+ History ({backtestHistory.length})</button></div>{/* Results Content */}<div style={{ flex: 1, overflow: 'auto', padding: '20px' }}>- {error && (+ {/* Show running state with logs */}+ {isRunning && (+ <div>+ <div style={{+ padding: '20px',+ textAlign: 'center',+ color: colors.text,+ borderBottom: `1px solid ${colors.textMuted}`,+ }}>+ <Loader size={48} className="animate-spin" style={{ margin: '0 auto 16px', color: colors.accent }} />+ <p style={{ fontSize: '1.1rem', fontWeight: '600' }}>Running Backtest...</p>+ <p style={{ fontSize: '0.85rem', color: colors.textMuted, marginTop: '8px' }}>+ {executionLogs.length > 0 ? executionLogs[executionLogs.length - 1] : 'Initializing...'}+ </p>++ {/* Progress Bar */}+ <div style={{+ width: '100%',+ maxWidth: '400px',+ height: '8px',+ background: colors.panel,+ borderRadius: '4px',+ margin: '16px auto 0',+ overflow: 'hidden',+ border: `1px solid ${colors.textMuted}`,+ }}>+ <div+ style={{+ height: '100%',+ background: `linear-gradient(90deg, ${colors.accent}, ${colors.success})`,+ width: `${Math.min((executionLogs.length / 10) * 100, 90)}%`,+ transition: 'width 0.3s ease',+ animation: 'pulse 2s ease-in-out infinite',+ }}+ />+ </div>+ </div>++ {/* Execution Logs */}+ <div style={{+ padding: '16px',+ background: colors.background,+ fontFamily: 'Consolas, Monaco, monospace',+ fontSize: '0.8rem',+ maxHeight: '400px',+ overflowY: 'auto',+ }}>+ <h4 style={{ fontSize: '0.9rem', marginBottom: '12px', color: colors.text }}>Execution Log:</h4>+ {executionLogs.map((log, idx) => (+ <div key={idx} style={{+ padding: '4px 0',+ color: log.includes('✓') ? colors.success : log.includes('✗') ? colors.alert : colors.textMuted,+ borderLeft: `2px solid ${log.includes('✓') ? colors.success : log.includes('✗') ? colors.alert : 'transparent'}`,+ paddingLeft: '8px',+ marginBottom: '2px',+ }}>+ {log}+ </div>+ ))}+ {executionLogs.length === 0 && (+ <div style={{ color: colors.textMuted, fontStyle: 'italic' }}>Waiting for logs...</div>+ )}+ </div>+ </div>+ )}++ {error && !isRunning && (<div style={{padding: '16px',background: colors.alert + '20',@@ -468,7 +925,50 @@ export default function BacktestingTab() {</div>)}- {currentResult && currentResult.status === 'completed' && (+ {/* History View */}+ {selectedHistoryId === 'history' && (+ <div>+ <h3 style={{ fontSize: '1.1rem', marginBottom: '16px' }}>Backtest History</h3>+ {backtestHistory.length === 0 ? (+ <div style={{ textAlign: 'center', color: colors.textMuted, paddingTop: '40px' }}>+ <Activity size={48} style={{ opacity: 0.3, margin: '0 auto 16px' }} />+ <p>No backtest history yet</p>+ </div>+ ) : (+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>+ {backtestHistory.map((run) => (+ <div+ key={run.id}+ onClick={() => handleLoadHistory(run.id)}+ style={{+ padding: '16px',+ background: colors.panel,+ border: `1px solid ${colors.textMuted}`,+ borderRadius: '6px',+ cursor: 'pointer',+ transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => e.currentTarget.style.borderColor = colors.accent}+ onMouseLeave={(e) => e.currentTarget.style.borderColor = colors.textMuted}+ >+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>+ <div style={{ fontWeight: '600' }}>Run #{run.id.slice(0, 8)}</div>+ <div style={{ fontSize: '0.85rem', color: colors.textMuted }}>+ {new Date(run.created_at || Date.now()).toLocaleString()}+ </div>+ </div>+ <div style={{ fontSize: '0.85rem', color: colors.textMuted }}>+ Provider: {run.provider_name} | Status: {run.status}+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ )}++ {/* Results View */}+ {!selectedHistoryId && currentResult && currentResult.status === 'completed' && (<div>{/* Performance Metrics */}<div style={{ marginBottom: '24px' }}>@@ -507,6 +1007,112 @@ export default function BacktestingTab() {</div></div>+ {/* Equity Curve Chart */}+ {currentResult.equity && currentResult.equity.length > 0 && (+ <div style={{ marginBottom: '24px' }}>+ <h3 style={{ fontSize: '1.1rem', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '8px' }}>+ <TrendingUp size={18} />+ Equity Curve+ </h3>+ <div style={{+ padding: '16px',+ background: colors.panel,+ border: `1px solid ${colors.textMuted}`,+ borderRadius: '6px',+ height: '300px',+ }}>+ <ResponsiveContainer width="100%" height="100%">+ <LineChart data={currentResult.equity}>+ <CartesianGrid strokeDasharray="3 3" stroke={colors.textMuted} opacity={0.3} />+ <XAxis+ dataKey="date"+ stroke={colors.textMuted}+ tick={{ fill: colors.textMuted, fontSize: 12 }}+ tickFormatter={(value) => new Date(value).toLocaleDateString()}+ />+ <YAxis+ stroke={colors.textMuted}+ tick={{ fill: colors.textMuted, fontSize: 12 }}+ tickFormatter={(value) => `$${(value / 1000).toFixed(0)}k`}+ />+ <Tooltip+ contentStyle={{+ backgroundColor: colors.background,+ border: `1px solid ${colors.textMuted}`,+ borderRadius: '4px',+ color: colors.text+ }}+ labelFormatter={(value) => new Date(value).toLocaleDateString()}+ formatter={(value: any) => [`$${Number(value).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`, 'Equity']}+ />+ <Legend wrapperStyle={{ color: colors.text }} />+ <Line+ type="monotone"+ dataKey="equity"+ stroke={colors.accent}+ strokeWidth={2}+ dot={false}+ name="Portfolio Value"+ />+ </LineChart>+ </ResponsiveContainer>+ </div>+ </div>+ )}++ {/* Drawdown Chart */}+ {currentResult.equity && currentResult.equity.length > 0 && (+ <div style={{ marginBottom: '24px' }}>+ <h3 style={{ fontSize: '1.1rem', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '8px' }}>+ <TrendingDown size={18} />+ Drawdown+ </h3>+ <div style={{+ padding: '16px',+ background: colors.panel,+ border: `1px solid ${colors.textMuted}`,+ borderRadius: '6px',+ height: '250px',+ }}>+ <ResponsiveContainer width="100%" height="100%">+ <AreaChart data={currentResult.equity}>+ <CartesianGrid strokeDasharray="3 3" stroke={colors.textMuted} opacity={0.3} />+ <XAxis+ dataKey="date"+ stroke={colors.textMuted}+ tick={{ fill: colors.textMuted, fontSize: 12 }}+ tickFormatter={(value) => new Date(value).toLocaleDateString()}+ />+ <YAxis+ stroke={colors.textMuted}+ tick={{ fill: colors.textMuted, fontSize: 12 }}+ tickFormatter={(value) => `${(value * 100).toFixed(0)}%`}+ />+ <Tooltip+ contentStyle={{+ backgroundColor: colors.background,+ border: `1px solid ${colors.textMuted}`,+ borderRadius: '4px',+ color: colors.text+ }}+ labelFormatter={(value) => new Date(value).toLocaleDateString()}+ formatter={(value: any) => [`${(Number(value) * 100).toFixed(2)}%`, 'Drawdown']}+ />+ <Legend wrapperStyle={{ color: colors.text }} />+ <Area+ type="monotone"+ dataKey="drawdown"+ stroke={colors.alert}+ fill={colors.alert}+ fillOpacity={0.3}+ name="Drawdown %"+ />+ </AreaChart>+ </ResponsiveContainer>+ </div>+ </div>+ )}+{/* Statistics */}<div style={{ marginBottom: '24px' }}><h3 style={{ fontSize: '1.1rem', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '8px' }}>@@ -565,7 +1171,7 @@ export default function BacktestingTab() {</div>)}- {!currentResult && !error && !isRunning && (+ {!selectedHistoryId && !currentResult && !error && !isRunning && (<div style={{height: '100%',display: 'flex',@@ -580,6 +1186,13 @@ export default function BacktestingTab() {</div></div>)}++ {/* Debug info */}+ {!isRunning && (+ <div style={{ marginTop: '20px', padding: '12px', background: colors.panel, borderRadius: '4px', fontSize: '0.75rem', color: colors.textMuted }}>+ <div>Debug: isRunning={String(isRunning)} | hasError={String(!!error)} | hasResult={String(!!currentResult)} | resultStatus={currentResult?.status}</div>+ </div>+ )}</div></div></div>diff --git a/fincept-terminal-desktop/src/main.tsx b/fincept-terminal-desktop/src/main.tsxindex 410d48e1f..05d1dbcf5 100644--- a/fincept-terminal-desktop/src/main.tsx+++ b/fincept-terminal-desktop/src/main.tsx@@ -11,6 +11,24 @@ import './i18n/config' // Initialize i18nimport './App.css' // Make sure this line existsimport './tauri-cors-config' // Initialize Tauri CORS plugin+// Initialize backtesting providers+import { backtestingRegistry } from './services/backtesting/BacktestingProviderRegistry'+import { LeanAdapter } from './services/backtesting/adapters/lean'+import { VectorBTAdapter } from './services/backtesting/adapters/vectorbt/VectorBTAdapter'++// Register default backtesting providers+try {+ const leanAdapter = new LeanAdapter();+ backtestingRegistry.registerProvider(leanAdapter);++ const vectorbtAdapter = new VectorBTAdapter();+ backtestingRegistry.registerProvider(vectorbtAdapter);++ console.log('[App] Registered backtesting providers:', backtestingRegistry.listProviders());+} catch (error) {+ console.error('[App] Failed to register backtesting providers:', error);+}+// Error Boundary Componentclass ErrorBoundary extends React.Component<{ children: React.ReactNode },diff --git a/fincept-terminal-desktop/src/services/backtesting/adapters/custom/SimpleBacktester.ts b/fincept-terminal-desktop/src/services/backtesting/adapters/custom/SimpleBacktester.tsdeleted file mode 100644index 4cc52a747..000000000--- a/fincept-terminal-desktop/src/services/backtesting/adapters/custom/SimpleBacktester.ts+++ /dev/null@@ -1,326 +0,0 @@-/**- * Simple Custom Backtester- *- * Minimal backtesting engine for educational purposes.- * Demonstrates how easy it is to add new providers to the platform.- */--import { BaseBacktestingAdapter } from '../BaseAdapter';-import {- ProviderCapabilities,- ProviderConfig,- InitResult,- TestResult,- BacktestRequest,- BacktestResult,- BacktestStatus,- DataRequest,- HistoricalData,- IndicatorType,- IndicatorParams,- IndicatorResult,- DataCatalog,- IndicatorCatalog,- ValidationResult,- HealthStatus,- PerformanceMetrics,- BacktestStatistics,-} from '../../interfaces/types';-import { StrategyDefinition } from '../../interfaces/IStrategyDefinition';--const SIMPLE_CAPABILITIES: ProviderCapabilities = {- backtesting: true,- optimization: false,- liveTrading: false,- research: false,-- multiAsset: ['stocks'],-- indicators: false,- customStrategies: true,- maxConcurrentBacktests: 1,-- supportedTimeframes: ['daily'],-};--/**- * Simple Backtester Adapter- *- * Ultra-simple backtesting engine that runs entirely in TypeScript.- * No external dependencies required - perfect for learning and testing.- */-export class SimpleBacktester extends BaseBacktestingAdapter {- readonly name = 'Simple Backtester';- readonly version = '1.0.0';- readonly capabilities = SIMPLE_CAPABILITIES;- readonly description = 'Simple in-memory backtester for education and testing';-- async initialize(config: ProviderConfig): Promise<InitResult> {- this.config = config;- this.initialized = true;- this.connected = true;-- return this.createSuccessResult('Simple Backtester initialized');- }-- async testConnection(): Promise<TestResult> {- return {- success: true,- message: 'Simple Backtester is always available (in-memory)',- latency: 0,- };- }-- async disconnect(): Promise<void> {- this.connected = false;- this.initialized = false;- }-- async runBacktest(request: BacktestRequest): Promise<BacktestResult> {- this.ensureConnected();-- const backtestId = this.generateId();-- try {- // Simple buy-and-hold backtest- const startDate = new Date(request.startDate);- const endDate = new Date(request.endDate);- const days = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));-- // Simulate price movement (random walk)- const prices: number[] = [100]; // Start at $100- const returns: number[] = [0];-- for (let i = 1; i < days; i++) {- // Random daily return between -2% and +2%- const dailyReturn = (Math.random() - 0.5) * 0.04;- const newPrice = prices[i - 1] * (1 + dailyReturn);- prices.push(newPrice);- returns.push(dailyReturn);- }-- // Calculate metrics- const finalPrice = prices[prices.length - 1];- const totalReturn = (finalPrice - 100) / 100;-- const avgReturn = returns.reduce((a, b) => a + b, 0) / returns.length;- const stdDev = Math.sqrt(- returns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / returns.length- );- const sharpeRatio = avgReturn / stdDev * Math.sqrt(252); // Annualized-- const maxDrawdown = this.calculateMaxDrawdown(prices);-- const performance: PerformanceMetrics = {- totalReturn: totalReturn,- annualizedReturn: Math.pow(1 + totalReturn, 365 / days) - 1,- sharpeRatio: sharpeRatio,- sortinoRatio: sharpeRatio * 0.9, // Approximation- maxDrawdown: maxDrawdown,- winRate: returns.filter((r) => r > 0).length / returns.length,- lossRate: returns.filter((r) => r < 0).length / returns.length,- profitFactor: 1.5,- volatility: stdDev * Math.sqrt(252),- calmarRatio: totalReturn / Math.abs(maxDrawdown),- totalTrades: 1,- winningTrades: totalReturn > 0 ? 1 : 0,- losingTrades: totalReturn < 0 ? 1 : 0,- averageWin: totalReturn > 0 ? totalReturn : 0,- averageLoss: totalReturn < 0 ? totalReturn : 0,- largestWin: totalReturn > 0 ? totalReturn : 0,- largestLoss: totalReturn < 0 ? totalReturn : 0,- averageTradeReturn: totalReturn,- expectancy: totalReturn,- };-- const statistics: BacktestStatistics = {- startDate: request.startDate,- endDate: request.endDate,- initialCapital: request.initialCapital,- finalCapital: request.initialCapital * (1 + totalReturn),- totalFees: 0,- totalSlippage: 0,- totalTrades: 1,- winningDays: returns.filter((r) => r > 0).length,- losingDays: returns.filter((r) => r < 0).length,- averageDailyReturn: avgReturn,- bestDay: Math.max(...returns),- worstDay: Math.min(...returns),- consecutiveWins: 0,- consecutiveLosses: 0,- };-- // Equity curve- const equity = prices.map((price, i) => ({- date: new Date(startDate.getTime() + i * 24 * 60 * 60 * 1000).toISOString(),- equity: request.initialCapital * (price / 100),- returns: returns[i],- drawdown: this.calculateDrawdown(prices.slice(0, i + 1)),- }));-- return {- id: backtestId,- status: 'completed',- performance,- trades: [- {- id: 'trade_1',- symbol: request.assets[0]?.symbol || 'SPY',- entryDate: request.startDate,- side: 'long',- quantity: request.initialCapital / 100,- entryPrice: 100,- commission: 0,- slippage: 0,- exitDate: request.endDate,- exitPrice: finalPrice,- pnl: request.initialCapital * totalReturn,- pnlPercent: totalReturn,- holdingPeriod: days,- exitReason: 'signal',- },- ],- equity,- statistics,- logs: [- `${new Date().toISOString()}: Started simple backtest`,- `${new Date().toISOString()}: Simulated ${days} days of trading`,- `${new Date().toISOString()}: Final return: ${(totalReturn * 100).toFixed(2)}%`,- `${new Date().toISOString()}: Backtest completed`,- ],- startTime: new Date().toISOString(),- endTime: new Date().toISOString(),- duration: 100, // 100ms- };- } catch (error) {- return {- id: backtestId,- status: 'failed',- error: String(error),- performance: this.getEmptyMetrics(),- trades: [],- equity: [],- statistics: this.getEmptyStatistics(),- logs: [`Error: ${error}`],- };- }- }-- async getBacktestStatus(id: string): Promise<BacktestStatus> {- return {- id,- status: 'completed',- progress: 100,- };- }-- async cancelBacktest(id: string): Promise<void> {- // Nothing to cancel - runs instantly- }-- async getHistoricalData(request: DataRequest): Promise<HistoricalData[]> {- return [];- }-- async getAvailableData(): Promise<DataCatalog> {- return {- providers: ['simulated'],- assetClasses: ['stocks'],- timeframes: ['daily'],- startDate: '2000-01-01',- endDate: new Date().toISOString().split('T')[0],- totalSymbols: 0,- description: 'Simple backtester generates random price data for testing',- };- }-- async calculateIndicator(type: IndicatorType, params: IndicatorParams): Promise<IndicatorResult> {- throw new Error('Indicators not supported by Simple Backtester');- }-- async getAvailableIndicators(): Promise<IndicatorCatalog> {- return {- indicators: [],- };- }-- async validateStrategy(strategy: StrategyDefinition): Promise<{ valid: boolean; errors: string[]; warnings: string[] }> {- return {- valid: true,- errors: [],- warnings: ['Simple Backtester ignores strategy code and runs buy-and-hold simulation'],- };- }-- async getHealth(): Promise<HealthStatus> {- return { status: 'healthy', message: 'Always available' };- }-- // Helper methods- private calculateMaxDrawdown(prices: number[]): number {- let maxDD = 0;- let peak = prices[0];-- for (const price of prices) {- if (price > peak) {- peak = price;- }- const dd = (price - peak) / peak;- if (dd < maxDD) {- maxDD = dd;- }- }-- return maxDD;- }-- private calculateDrawdown(prices: number[]): number {- if (prices.length === 0) return 0;- const peak = Math.max(...prices);- const current = prices[prices.length - 1];- return (current - peak) / peak;- }-- private getEmptyMetrics(): PerformanceMetrics {- return {- totalReturn: 0,- annualizedReturn: 0,- sharpeRatio: 0,- sortinoRatio: 0,- maxDrawdown: 0,- winRate: 0,- lossRate: 0,- profitFactor: 0,- volatility: 0,- calmarRatio: 0,- totalTrades: 0,- winningTrades: 0,- losingTrades: 0,- averageWin: 0,- averageLoss: 0,- largestWin: 0,- largestLoss: 0,- averageTradeReturn: 0,- expectancy: 0,- };- }-- private getEmptyStatistics(): BacktestStatistics {- return {- startDate: '',- endDate: '',- initialCapital: 0,- finalCapital: 0,- totalFees: 0,- totalSlippage: 0,- totalTrades: 0,- winningDays: 0,- losingDays: 0,- averageDailyReturn: 0,- bestDay: 0,- worstDay: 0,- consecutiveWins: 0,- consecutiveLosses: 0,- };- }-}diff --git a/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanAdapter.ts b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanAdapter.tsindex 168324410..83cc52905 100644--- a/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanAdapter.ts+++ b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanAdapter.ts@@ -164,11 +164,17 @@ export class LeanAdapter extends BaseBacktestingAdapter {const backtestId = this.generateId();try {+ console.log('[LeanAdapter] Starting backtest:', backtestId);+// 1. Translate strategy to Lean Python code+ console.log('[LeanAdapter] Translating strategy...');const pythonCode = this.strategyTranslator.translate(request.strategy);+ console.log('[LeanAdapter] Strategy code length:', pythonCode.length);// 2. Create Lean project+ console.log('[LeanAdapter] Creating Lean project...');const projectPath = await this.createLeanProject(backtestId, pythonCode, request);+ console.log('[LeanAdapter] Project created at:', projectPath);// 3. Build CLI argumentsconst cliArgs = {@@ -181,8 +187,12 @@ export class LeanAdapter extends BaseBacktestingAdapter {resultsFolder: this.joinPath(this.leanConfig!.resultsPath, backtestId),};+ console.log('[LeanAdapter] CLI args:', cliArgs);+// 4. Execute backtest via CLI+ console.log('[LeanAdapter] Executing Lean CLI...');const execution = await this.cliExecutor!.runBacktest(projectPath, cliArgs);+ console.log('[LeanAdapter] Execution started, process ID:', execution.processId);// Track as activethis.activeBacktests.set(backtestId, {@@ -193,19 +203,47 @@ export class LeanAdapter extends BaseBacktestingAdapter {});// 5. Wait for completion (or poll in production)+ console.log('[LeanAdapter] Waiting for completion...');const resultJson = await this.waitForBacktestCompletion(backtestId, execution.processId);+ console.log('[LeanAdapter] Backtest completed');// 6. Parse resultsconst logs = this.cliExecutor!.getProcessStatus(backtestId)?.logs || [];const result = this.resultsParser.parseBacktestResult(backtestId, resultJson, logs);+ console.log('[LeanAdapter] Results parsed successfully');+// Mark as completedthis.activeBacktests.delete(backtestId);return result;} catch (error) {+ console.error('[LeanAdapter] Backtest error:', error);this.activeBacktests.delete(backtestId);- throw new Error(`Backtest failed: ${error}`);++ // Return failed result instead of throwing+ return {+ id: backtestId,+ status: 'failed',+ error: error instanceof Error ? error.message : String(error),+ performance: {+ totalReturn: 0,+ annualizedReturn: 0,+ sharpeRatio: 0,+ maxDrawdown: 0,+ winRate: 0,+ totalTrades: 0,+ },+ statistics: {+ initialCapital: request.initialCapital,+ finalCapital: request.initialCapital,+ totalFees: 0,+ totalTrades: 0,+ },+ trades: [],+ equity: [],+ logs: [`Error: ${error instanceof Error ? error.message : String(error)}`],+ };}}@@ -432,9 +470,20 @@ export class LeanAdapter extends BaseBacktestingAdapter {private async checkLeanCliExists(cliPath: string): Promise<boolean> {try {- const result = await invoke<boolean>('check_file_exists', { path: cliPath });- return result;- } catch {+ // Try to execute 'lean --version' to check if it's available+ const result = await invoke<{+ success: boolean;+ stdout: string;+ stderr: string;+ }>('execute_command', {+ command: `${cliPath} --version`,+ });++ console.log('[Lean] CLI check result:', result);++ return result.success;+ } catch (error) {+ console.error('[Lean] CLI check failed:', error);return false;}}@@ -468,8 +517,22 @@ export class LeanAdapter extends BaseBacktestingAdapter {content: pythonCode,});- // Write config.json if needed- // (Lean config would go here)+ // Write lean.json config file (required by Lean CLI)+ const leanConfigPath = this.joinPath(projectPath, 'lean.json');+ const leanConfigContent = {+ "algorithm-language": "Python",+ "parameters": {},+ "description": projectId,+ "cloud-id": 0,+ "local-id": 0+ };++ await invoke('write_file', {+ path: leanConfigPath,+ content: JSON.stringify(leanConfigContent, null, 2),+ });++ console.log('[LeanAdapter] Created lean.json config file');return projectPath;}diff --git a/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanCliExecutor.ts b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanCliExecutor.tsindex f00bc92fd..1bfbaacbc 100644--- a/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanCliExecutor.ts+++ b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanCliExecutor.ts@@ -57,18 +57,32 @@ export class LeanCliExecutor {});try {- // Execute via Tauri command (Rust backend)- const result = await invoke<{ process_id: number }>('execute_lean_cli', {+ console.log('[LeanCliExecutor] Executing command:', command);+ console.log('[LeanCliExecutor] Working directory:', projectPath);++ // Execute via Tauri command and wait for completion+ const result = await invoke<{ success: boolean; stdout: string; stderr: string; exit_code: number }>('execute_command', {command,- workingDir: projectPath,- backtestId,});- this.runningProcesses.get(backtestId)!.pid = result.process_id;+ console.log('[LeanCliExecutor] Command completed:', result);++ if (!result.success) {+ this.runningProcesses.get(backtestId)!.status = 'failed';+ this.runningProcesses.get(backtestId)!.error = result.stderr || 'Command failed';+ this.runningProcesses.get(backtestId)!.logs.push(result.stdout);+ this.runningProcesses.get(backtestId)!.logs.push(result.stderr);+ throw new Error(result.stderr || 'Lean CLI execution failed');+ }++ // Mark as completed+ this.runningProcesses.get(backtestId)!.status = 'completed';+ this.runningProcesses.get(backtestId)!.progress = 100;+ this.runningProcesses.get(backtestId)!.logs.push(result.stdout);return {id: backtestId,- processId: result.process_id,+ processId: 0, // Not tracking PID since we wait for completion};} catch (error) {this.runningProcesses.get(backtestId)!.status = 'failed';@@ -235,46 +249,19 @@ export class LeanCliExecutor {// ModecommandParts.push(mode);- // Project- commandParts.push('--project', projectPath);-- // Algorithm- if (args.algorithm) {- commandParts.push('--algorithm-file', args.algorithm);- }-- // Dates- if (args.startDate) {- commandParts.push('--start', args.startDate);- }- if (args.endDate) {- commandParts.push('--end', args.endDate);- }-- // Capital- if (args.cash) {- commandParts.push('--cash', args.cash.toString());- }+ // Project path (positional argument, not a flag)+ commandParts.push(projectPath);- // Data folder- if (args.dataFolder || this.config.dataPath) {- commandParts.push('--data-folder', args.dataFolder || this.config.dataPath);- }-- // Results folder+ // Output directory for resultsif (args.resultsFolder || this.config.resultsPath) {- commandParts.push('--results', args.resultsFolder || this.config.resultsPath);+ commandParts.push('--output', args.resultsFolder || this.config.resultsPath);}- // Parameters (as JSON)- if (args.parameters && Object.keys(args.parameters).length > 0) {- commandParts.push('--parameters', JSON.stringify(args.parameters));- }+ // Data provider (use local data)+ commandParts.push('--data-provider-historical', 'Local');- // Environment- if (args.environment) {- commandParts.push('--environment', args.environment);- }+ // Don't pull updates+ commandParts.push('--no-update');// Flagsif (args.release) {