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
lean engine support added
tilakpatel228d41258f705b
diff --git a/fincept-terminal-desktop/src-tauri/Cargo.lock b/fincept-terminal-desktop/src-tauri/Cargo.lockindex fe3c44077..aeb8c4b10 100644--- a/fincept-terminal-desktop/src-tauri/Cargo.lock+++ b/fincept-terminal-desktop/src-tauri/Cargo.lock@@ -376,6 +376,17 @@ dependencies = ["alloc-stdlib",]+[[package]]+name = "bstr"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab"+dependencies = [+ "memchr",+ "regex-automata",+ "serde",+]+[[package]]name = "bumpalo"version = "3.19.0"@@ -1157,6 +1168,7 @@ version = "3.0.11"dependencies = ["anyhow","chrono",+ "printpdf","reqwest 0.11.27","serde","serde_json",@@ -1168,6 +1180,7 @@ dependencies = ["tauri-plugin-http","tauri-plugin-opener","tauri-plugin-process",+ "tauri-plugin-shell","tauri-plugin-sql","tauri-plugin-updater","tokio",@@ -2393,6 +2406,12 @@ dependencies = ["vcpkg",]+[[package]]+name = "linked-hash-map"+version = "0.5.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"+[[package]]name = "linux-raw-sys"version = "0.11.0"@@ -2427,6 +2446,23 @@ version = "0.4.28"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"+[[package]]+name = "lopdf"+version = "0.31.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "07c8e1b6184b1b32ea5f72f572ebdc40e5da1d2921fa469947ff7c480ad1f85a"+dependencies = [+ "encoding_rs",+ "flate2",+ "itoa",+ "linked-hash-map",+ "log",+ "md5",+ "pom",+ "time",+ "weezl",+]+[[package]]name = "lru-slab"version = "0.1.2"@@ -2480,6 +2516,12 @@ dependencies = ["digest",]+[[package]]+name = "md5"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"+[[package]]name = "memchr"version = "2.7.5"@@ -3032,6 +3074,16 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "os_pipe"+version = "1.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"+dependencies = [+ "libc",+ "windows-sys 0.61.0",+]+[[package]]name = "osakit"version = "0.3.1"@@ -3046,6 +3098,15 @@ dependencies = ["thiserror 2.0.16",]+[[package]]+name = "owned_ttf_parser"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "706de7e2214113d63a8238d1910463cfce781129a6f263d13fdb09ff64355ba4"+dependencies = [+ "ttf-parser",+]+[[package]]name = "pango"version = "0.18.3"@@ -3345,6 +3406,15 @@ dependencies = ["windows-sys 0.61.0",]+[[package]]+name = "pom"+version = "3.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c972d8f86e943ad532d0b04e8965a749ad1d18bb981a9c7b3ae72fe7fd7744b"+dependencies = [+ "bstr",+]+[[package]]name = "potential_utf"version = "0.1.3"@@ -3375,6 +3445,18 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"+[[package]]+name = "printpdf"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c30a4cc87c3ca9a98f4970db158a7153f8d1ec8076e005751173c57836380b1d"+dependencies = [+ "js-sys",+ "lopdf",+ "owned_ttf_parser",+ "time",+]+[[package]]name = "proc-macro-crate"version = "1.3.1"@@ -4292,12 +4374,44 @@ dependencies = ["digest",]+[[package]]+name = "shared_child"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e362d9935bc50f019969e2f9ecd66786612daae13e8f277be7bfb66e8bed3f7"+dependencies = [+ "libc",+ "sigchld",+ "windows-sys 0.60.2",+]+[[package]]name = "shlex"version = "1.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"+[[package]]+name = "sigchld"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47106eded3c154e70176fc83df9737335c94ce22f821c32d17ed1db1f83badb1"+dependencies = [+ "libc",+ "os_pipe",+ "signal-hook",+]++[[package]]+name = "signal-hook"+version = "0.3.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"+dependencies = [+ "libc",+ "signal-hook-registry",+]+[[package]]name = "signal-hook-registry"version = "1.4.6"@@ -5117,6 +5231,27 @@ dependencies = ["tauri-plugin",]+[[package]]+name = "tauri-plugin-shell"+version = "2.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c374b6db45f2a8a304f0273a15080d98c70cde86178855fc24653ba657a1144c"+dependencies = [+ "encoding_rs",+ "log",+ "open",+ "os_pipe",+ "regex",+ "schemars 0.8.22",+ "serde",+ "serde_json",+ "shared_child",+ "tauri",+ "tauri-plugin",+ "thiserror 2.0.16",+ "tokio",+]+[[package]]name = "tauri-plugin-sql"version = "2.3.0"@@ -5665,6 +5800,12 @@ version = "0.2.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"+[[package]]+name = "ttf-parser"+version = "0.19.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "49d64318d8311fc2668e48b63969f4343e0a85c4a109aa8460d6672e364b8bd1"+[[package]]name = "typeid"version = "1.0.3"@@ -6163,6 +6304,12 @@ dependencies = ["windows-core",]+[[package]]+name = "weezl"+version = "0.1.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"+[[package]]name = "which"version = "7.0.3"diff --git a/fincept-terminal-desktop/src-tauri/Cargo.toml b/fincept-terminal-desktop/src-tauri/Cargo.tomlindex 9a6b25a76..16679171e 100644--- a/fincept-terminal-desktop/src-tauri/Cargo.toml+++ b/fincept-terminal-desktop/src-tauri/Cargo.toml@@ -29,6 +29,7 @@ tauri-plugin-sql = { version = "2", features = ["sqlite"] }tauri-plugin-dialog = "2"tauri-plugin-updater = "2"tauri-plugin-process = "2"+tauri-plugin-shell = "2"serde = { version = "1", features = ["derive"] }serde_json = "1"sha2 = "0.10"@@ -38,6 +39,7 @@ chrono = "0.4"uuid = { version = "1.11", features = ["v4", "serde"] }reqwest = { version = "0.11", features = ["json"] }which = "7.0"+printpdf = "0.7"[target.'cfg(target_os = "windows")'.dependencies][target.'cfg(target_os = "macos")'.dependencies]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/base/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/base/__init__.pynew file mode 100644index 000000000..c4ba518e2--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/base/__init__.py@@ -0,0 +1,8 @@+"""+Backtesting Base Module+Platform-independent base classes for backtesting providers+"""++from .base_provider import BacktestingProviderBase, BacktestResult, PerformanceMetrics++__all__ = ['BacktestingProviderBase', 'BacktestResult', 'PerformanceMetrics']diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/base/base_provider.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/base/base_provider.pynew file mode 100644index 000000000..95b2dd5fa--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/base/base_provider.py@@ -0,0 +1,417 @@+"""+Base Provider for Backtesting Engines+Abstract base class that all Python backtesting providers must implement+Mirrors the TypeScript IBacktestingProvider interface+"""++from abc import ABC, abstractmethod+from typing import Dict, Any, List, Optional+from dataclasses import dataclass, asdict+from datetime import datetime+import json+++# ============================================================================+# Data Classes (Python equivalents of TypeScript interfaces)+# ============================================================================++@dataclass+class PerformanceMetrics:+ """Performance metrics for backtest results"""+ total_return: float+ annualized_return: float+ sharpe_ratio: float+ sortino_ratio: float+ max_drawdown: float+ win_rate: float+ loss_rate: float+ profit_factor: float+ volatility: float+ calmar_ratio: float+ total_trades: int+ winning_trades: int+ losing_trades: int+ average_win: float+ average_loss: float+ largest_win: float+ largest_loss: float+ average_trade_return: float+ expectancy: float+ alpha: Optional[float] = None+ beta: Optional[float] = None+ max_drawdown_duration: Optional[int] = None+ information_ratio: Optional[float] = None+ treynor_ratio: Optional[float] = None+++@dataclass+class BacktestStatistics:+ """General statistics about the backtest"""+ start_date: str+ end_date: str+ initial_capital: float+ final_capital: float+ total_fees: float+ total_slippage: float+ total_trades: int+ winning_days: int+ losing_days: int+ average_daily_return: float+ best_day: float+ worst_day: float+ consecutive_wins: int+ consecutive_losses: int+ max_drawdown_date: Optional[str] = None+ recovery_time: Optional[int] = None+++@dataclass+class Trade:+ """Single trade record"""+ id: str+ symbol: str+ entry_date: str+ side: str # 'long' or 'short'+ quantity: float+ entry_price: float+ commission: float+ slippage: float+ exit_date: Optional[str] = None+ exit_price: Optional[float] = None+ pnl: Optional[float] = None+ pnl_percent: Optional[float] = None+ holding_period: Optional[int] = None+ exit_reason: Optional[str] = None # 'signal', 'stop_loss', 'take_profit', 'time_limit'+++@dataclass+class EquityPoint:+ """Single point on equity curve"""+ date: str+ equity: float+ returns: float+ drawdown: float+ benchmark: Optional[float] = None+++@dataclass+class BacktestResult:+ """Complete backtest result"""+ id: str+ status: str # 'completed', 'failed', 'running', 'cancelled'+ performance: PerformanceMetrics+ trades: List[Trade]+ equity: List[EquityPoint]+ statistics: BacktestStatistics+ logs: List[str]+ error: Optional[str] = None+ start_time: Optional[str] = None+ end_time: Optional[str] = None+ duration: Optional[int] = None+ charts: Optional[List[Dict[str, Any]]] = None++ def to_dict(self) -> Dict[str, Any]:+ """Convert to dictionary for JSON serialization"""+ return {+ 'id': self.id,+ 'status': self.status,+ 'performance': asdict(self.performance),+ 'trades': [asdict(t) for t in self.trades],+ 'equity': [asdict(e) for e in self.equity],+ 'statistics': asdict(self.statistics),+ 'logs': self.logs,+ 'error': self.error,+ 'start_time': self.start_time,+ 'end_time': self.end_time,+ 'duration': self.duration,+ 'charts': self.charts or []+ }+++@dataclass+class OptimizationResult:+ """Optimization run result"""+ id: str+ status: str+ best_parameters: Dict[str, Any]+ best_result: BacktestResult+ all_results: List[Dict[str, Any]]+ iterations: int+ duration: int+ error: Optional[str] = None++ def to_dict(self) -> Dict[str, Any]:+ """Convert to dictionary for JSON serialization"""+ return {+ 'id': self.id,+ 'status': self.status,+ 'best_parameters': self.best_parameters,+ 'best_result': self.best_result.to_dict(),+ 'all_results': self.all_results,+ 'iterations': self.iterations,+ 'duration': self.duration,+ 'error': self.error+ }+++@dataclass+class HistoricalData:+ """Historical price data"""+ symbol: str+ timeframe: str+ data: List[Dict[str, Any]] # List of price bars+++@dataclass+class IndicatorResult:+ """Technical indicator calculation result"""+ indicator: str+ symbol: str+ values: List[Dict[str, Any]]+++# ============================================================================+# Base Provider Class+# ============================================================================++class BacktestingProviderBase(ABC):+ """+ Abstract base class for all backtesting providers++ All provider implementations (Lean, Backtrader, VectorBT, etc.)+ must inherit from this class and implement all abstract methods.++ This ensures platform independence - the terminal can work with+ any backtesting engine through this unified interface.+ """++ def __init__(self):+ self.initialized = False+ self.connected = False+ self.config: Optional[Dict[str, Any]] = None++ # ========================================================================+ # Properties (must be defined in subclasses)+ # ========================================================================++ @property+ @abstractmethod+ def name(self) -> str:+ """Provider name (e.g., "QuantConnect Lean", "Backtrader")"""+ pass++ @property+ @abstractmethod+ def version(self) -> str:+ """Provider version"""+ pass++ @property+ @abstractmethod+ def capabilities(self) -> Dict[str, Any]:+ """+ Provider capabilities+ Example:+ {+ 'backtesting': True,+ 'optimization': True,+ 'liveTrading': False,+ 'research': False,+ 'multiAsset': ['stocks', 'options', 'crypto'],+ 'indicators': True,+ 'customStrategies': True,+ 'maxConcurrentBacktests': 5+ }+ """+ pass++ # ========================================================================+ # Abstract Methods (must be implemented by all providers)+ # ========================================================================++ @abstractmethod+ def initialize(self, config: Dict[str, Any]) -> Dict[str, Any]:+ """+ Initialize the provider with configuration++ Args:+ config: Provider-specific configuration dictionary++ Returns:+ Dictionary with {'success': bool, 'message': str, 'error': Optional[str]}+ """+ pass++ @abstractmethod+ def test_connection(self) -> Dict[str, Any]:+ """+ Test connection to provider++ Returns:+ Dictionary with {'success': bool, 'message': str, 'error': Optional[str]}+ """+ pass++ @abstractmethod+ def run_backtest(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """+ Run a backtest++ Args:+ request: Backtest request dictionary containing:+ - strategy: Strategy definition+ - startDate: Start date string+ - endDate: End date string+ - initialCapital: Initial capital amount+ - assets: List of asset selections+ - parameters: Strategy parameters+ - benchmark: Optional benchmark symbol++ Returns:+ Dictionary representation of BacktestResult+ """+ pass++ @abstractmethod+ def get_historical_data(self, request: Dict[str, Any]) -> List[Dict[str, Any]]:+ """+ Get historical price data++ Args:+ request: Data request dictionary containing:+ - symbols: List of symbols+ - startDate: Start date string+ - endDate: End date string+ - timeframe: Timeframe ('daily', 'minute', etc.)++ Returns:+ List of HistoricalData dictionaries+ """+ pass++ @abstractmethod+ def calculate_indicator(self, indicator_type: str, params: Dict[str, Any]) -> Dict[str, Any]:+ """+ Calculate technical indicator++ Args:+ indicator_type: Type of indicator ('sma', 'ema', 'rsi', etc.)+ params: Indicator parameters (period, etc.)++ Returns:+ Dictionary representation of IndicatorResult+ """+ pass++ # ========================================================================+ # Optional Methods (providers can override if supported)+ # ========================================================================++ def optimize(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """+ Run parameter optimization (optional)++ Args:+ request: Optimization request dictionary++ Returns:+ Dictionary representation of OptimizationResult++ Raises:+ NotImplementedError if optimization not supported+ """+ raise NotImplementedError(f"Optimization not supported by {self.name}")++ def disconnect(self) -> None:+ """Clean up resources and disconnect"""+ self.connected = False+ self.initialized = False++ def validate_strategy(self, strategy: Dict[str, Any]) -> Dict[str, Any]:+ """+ Validate strategy before running (optional)++ Args:+ strategy: Strategy definition dictionary++ Returns:+ Dictionary with {'valid': bool, 'errors': List[str], 'warnings': List[str]}+ """+ errors = []+ warnings = []++ if not strategy.get('name'):+ errors.append('Strategy name is required')++ if not strategy.get('type'):+ errors.append('Strategy type is required')++ return {+ 'valid': len(errors) == 0,+ 'errors': errors,+ 'warnings': warnings+ }++ # ========================================================================+ # Helper Methods+ # ========================================================================++ def _generate_id(self) -> str:+ """Generate unique ID for backtest/optimization runs"""+ import uuid+ return str(uuid.uuid4())++ def _current_timestamp(self) -> str:+ """Get current timestamp as ISO string"""+ return datetime.utcnow().isoformat() + 'Z'++ def _ensure_initialized(self) -> None:+ """Check if provider is initialized, raise error if not"""+ if not self.initialized:+ raise RuntimeError(f"{self.name} is not initialized. Call initialize() first.")++ def _ensure_connected(self) -> None:+ """Check if provider is connected, raise error if not"""+ self._ensure_initialized()+ if not self.connected:+ raise RuntimeError(f"{self.name} is not connected. Call test_connection() first.")++ def _create_success_result(self, message: str) -> Dict[str, Any]:+ """Create success result dictionary"""+ return {+ 'success': True,+ 'message': message+ }++ def _create_error_result(self, error: str) -> Dict[str, Any]:+ """Create error result dictionary"""+ return {+ 'success': False,+ 'message': 'Operation failed',+ 'error': error+ }++ def _log(self, message: str) -> None:+ """Log message"""+ print(f"[{self.name}] {message}")++ def _error(self, message: str, exception: Optional[Exception] = None) -> None:+ """Log error message"""+ error_msg = f"[{self.name}] ERROR: {message}"+ if exception:+ error_msg += f"\n{str(exception)}"+ print(error_msg, file=__import__('sys').stderr)+++# ============================================================================+# Utility Functions+# ============================================================================++def json_response(data: Any) -> str:+ """Convert data to JSON string for stdout output"""+ return json.dumps(data, default=str, ensure_ascii=False)+++def parse_json_input(json_str: str) -> Dict[str, Any]:+ """Parse JSON input from command line argument"""+ return json.loads(json_str)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/lean/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/lean/__init__.pynew file mode 100644index 000000000..2369a9903--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/lean/__init__.py@@ -0,0 +1,8 @@+"""+Lean Provider Module+QuantConnect Lean integration for backtesting+"""++from .lean_provider import LeanProvider++__all__ = ['LeanProvider']diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/lean/lean_provider.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/lean/lean_provider.pynew file mode 100644index 000000000..1947123da--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/lean/lean_provider.py@@ -0,0 +1,564 @@+"""+Lean Provider Implementation++Python-side implementation of QuantConnect Lean provider.+Handles execution of Lean CLI, parsing results, and data operations.+"""++import os+import sys+import json+import subprocess+import time+from typing import Dict, Any, List, Optional+from datetime import datetime+from pathlib import Path++# Import base provider+sys.path.append(str(Path(__file__).parent.parent))+from base.base_provider import (+ BacktestingProviderBase,+ BacktestResult,+ PerformanceMetrics,+ Trade,+ EquityPoint,+ BacktestStatistics,+ OptimizationResult,+ json_response,+ parse_json_input+)+++class LeanProvider(BacktestingProviderBase):+ """+ QuantConnect Lean Provider++ Executes backtests using Lean CLI and parses results.+ """++ def __init__(self):+ super().__init__()+ self.lean_cli_path: Optional[str] = None+ self.projects_path: Optional[str] = None+ self.data_path: Optional[str] = None+ self.results_path: Optional[str] = None+ self.running_processes: Dict[str, subprocess.Popen] = {}++ # ========================================================================+ # Properties+ # ========================================================================++ @property+ def name(self) -> str:+ return "QuantConnect Lean"++ @property+ def version(self) -> str:+ return "2.5.0"++ @property+ def capabilities(self) -> Dict[str, Any]:+ return {+ 'backtesting': True,+ 'optimization': True,+ 'liveTrading': True,+ 'research': True,+ 'multiAsset': ['equity', 'forex', 'crypto', 'option', 'future', 'cfd'],+ 'indicators': True,+ 'customStrategies': True,+ 'maxConcurrentBacktests': 5,+ 'supportedTimeframes': ['tick', 'second', 'minute', 'hour', 'daily'],+ }++ # ========================================================================+ # Core Methods+ # ========================================================================++ def initialize(self, config: Dict[str, Any]) -> Dict[str, Any]:+ """Initialize Lean provider with configuration"""+ try:+ # Extract config+ self.lean_cli_path = config.get('leanCliPath')+ self.projects_path = config.get('projectsPath')+ self.data_path = config.get('dataPath')+ self.results_path = config.get('resultsPath')++ if not self.lean_cli_path:+ return self._create_error_result('leanCliPath is required')++ # Check if Lean CLI exists+ if not os.path.exists(self.lean_cli_path):+ return self._create_error_result(f'Lean CLI not found at: {self.lean_cli_path}')++ # Create directories+ for path in [self.projects_path, self.data_path, self.results_path]:+ if path:+ os.makedirs(path, exist_ok=True)++ self.config = config+ self.initialized = True+ self.connected = True # For CLI-based, no separate connection needed++ self._log(f'Lean provider initialized. CLI: {self.lean_cli_path}')+ return self._create_success_result('Lean provider initialized successfully')++ except Exception as e:+ self._error('Failed to initialize Lean provider', e)+ return self._create_error_result(str(e))++ def test_connection(self) -> Dict[str, Any]:+ """Test Lean CLI availability"""+ self._ensure_initialized()++ try:+ # Run --version to test CLI+ result = subprocess.run(+ [self.lean_cli_path, '--version'],+ capture_output=True,+ text=True,+ timeout=10+ )++ if result.returncode == 0:+ self.connected = True+ return self._create_success_result(f'Lean CLI operational. Version: {result.stdout.strip()}')+ else:+ return self._create_error_result(f'Lean CLI test failed: {result.stderr}')++ except Exception as e:+ self._error('Connection test failed', e)+ return self._create_error_result(str(e))++ def run_backtest(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Run a backtest using Lean CLI"""+ self._ensure_connected()++ backtest_id = self._generate_id()+ logs = []++ try:+ logs.append(f'{self._current_timestamp()}: Starting backtest {backtest_id}')++ # 1. Extract request parameters+ strategy = request.get('strategy', {})+ start_date = request.get('startDate')+ end_date = request.get('endDate')+ initial_capital = request.get('initialCapital', 100000)+ parameters = request.get('parameters', {})++ # 2. Create project directory+ project_path = os.path.join(self.projects_path, backtest_id)+ os.makedirs(project_path, exist_ok=True)+ logs.append(f'{self._current_timestamp()}: Created project at {project_path}')++ # 3. Write strategy code to main.py+ strategy_code = self._extract_strategy_code(strategy)+ main_file = os.path.join(project_path, 'main.py')+ with open(main_file, 'w') as f:+ f.write(strategy_code)+ logs.append(f'{self._current_timestamp()}: Wrote strategy to main.py')++ # 4. Build CLI command+ results_folder = os.path.join(self.results_path, backtest_id)+ os.makedirs(results_folder, exist_ok=True)++ command = self._build_cli_command(+ mode='backtest',+ project_path=project_path,+ algorithm='main.py',+ start_date=start_date,+ end_date=end_date,+ cash=initial_capital,+ data_folder=self.data_path,+ results_folder=results_folder,+ parameters=parameters+ )++ logs.append(f'{self._current_timestamp()}: Executing: {" ".join(command)}')++ # 5. Execute backtest+ process = subprocess.Popen(+ command,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ cwd=project_path+ )++ self.running_processes[backtest_id] = process++ # Wait for completion+ stdout, stderr = process.communicate(timeout=3600) # 1 hour timeout++ if stderr:+ logs.append(f'{self._current_timestamp()}: STDERR: {stderr}')++ if process.returncode != 0:+ logs.append(f'{self._current_timestamp()}: Backtest failed with code {process.returncode}')+ return BacktestResult(+ id=backtest_id,+ status='failed',+ performance=self._get_empty_metrics(),+ trades=[],+ equity=[],+ statistics=self._get_empty_statistics(),+ logs=logs,+ error=f'Lean CLI exited with code {process.returncode}: {stderr}'+ ).to_dict()++ logs.append(f'{self._current_timestamp()}: Backtest completed successfully')++ # 6. Read and parse results+ results_file = os.path.join(results_folder, 'results.json')+ if not os.path.exists(results_file):+ raise FileNotFoundError(f'Results file not found: {results_file}')++ with open(results_file, 'r') as f:+ lean_results = json.load(f)++ logs.append(f'{self._current_timestamp()}: Parsed results from {results_file}')++ # 7. Convert to platform-independent format+ result = self._parse_lean_results(backtest_id, lean_results, logs)+ return result.to_dict()++ except subprocess.TimeoutExpired:+ logs.append(f'{self._current_timestamp()}: Backtest timeout')+ if backtest_id in self.running_processes:+ self.running_processes[backtest_id].kill()+ del self.running_processes[backtest_id]++ return BacktestResult(+ id=backtest_id,+ status='failed',+ performance=self._get_empty_metrics(),+ trades=[],+ equity=[],+ statistics=self._get_empty_statistics(),+ logs=logs,+ error='Backtest timed out after 1 hour'+ ).to_dict()++ except Exception as e:+ self._error(f'Backtest {backtest_id} failed', e)+ logs.append(f'{self._current_timestamp()}: Error: {str(e)}')++ return BacktestResult(+ id=backtest_id,+ status='failed',+ performance=self._get_empty_metrics(),+ trades=[],+ equity=[],+ statistics=self._get_empty_statistics(),+ logs=logs,+ error=str(e)+ ).to_dict()++ def get_historical_data(self, request: Dict[str, Any]) -> List[Dict[str, Any]]:+ """Download historical data using Lean CLI"""+ self._ensure_connected()++ try:+ symbols = request.get('symbols', [])+ timeframe = request.get('timeframe', 'daily')+ start_date = request.get('startDate')+ end_date = request.get('endDate')++ # Build data download command+ command = [+ self.lean_cli_path,+ 'data',+ 'download',+ '--tickers', ','.join(symbols),+ '--resolution', timeframe,+ '--start', self._format_date(start_date),+ '--end', self._format_date(end_date),+ '--market', 'usa',+ '--data-folder', self.data_path+ ]++ # Execute download+ result = subprocess.run(+ command,+ capture_output=True,+ text=True,+ timeout=600 # 10 minutes+ )++ if result.returncode != 0:+ raise RuntimeError(f'Data download failed: {result.stderr}')++ # Read downloaded data+ # (Simplified - would parse Lean data files)+ return []++ except Exception as e:+ self._error('Historical data fetch failed', e)+ raise++ def calculate_indicator(self, indicator_type: str, params: Dict[str, Any]) -> Dict[str, Any]:+ """Calculate technical indicator"""+ # Lean calculates indicators within backtests+ raise NotImplementedError('Standalone indicator calculation not supported by Lean')++ # ========================================================================+ # Optional Methods+ # ========================================================================++ def optimize(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Run parameter optimization"""+ self._ensure_connected()++ optimization_id = self._generate_id()++ try:+ # Similar to backtest but with optimization config+ # (Full implementation would set up optimization parameters)+ raise NotImplementedError('Optimization implementation in progress')++ except Exception as e:+ self._error(f'Optimization {optimization_id} failed', e)+ raise++ # ========================================================================+ # Helper Methods+ # ========================================================================++ def _build_cli_command(+ self,+ mode: str,+ project_path: str,+ algorithm: str,+ start_date: Optional[str] = None,+ end_date: Optional[str] = None,+ cash: Optional[float] = None,+ data_folder: Optional[str] = None,+ results_folder: Optional[str] = None,+ parameters: Optional[Dict[str, Any]] = None+ ) -> List[str]:+ """Build Lean CLI command"""+ command = [self.lean_cli_path, mode]++ command.extend(['--project', project_path])+ command.extend(['--algorithm-file', algorithm])++ if start_date:+ command.extend(['--start', self._format_date(start_date)])++ if end_date:+ command.extend(['--end', self._format_date(end_date)])++ if cash:+ command.extend(['--cash', str(cash)])++ if data_folder:+ command.extend(['--data-folder', data_folder])++ if results_folder:+ command.extend(['--results', results_folder])++ if parameters:+ command.extend(['--parameters', json.dumps(parameters)])++ return command++ def _extract_strategy_code(self, strategy: Dict[str, Any]) -> str:+ """Extract Python code from strategy definition"""+ strategy_type = strategy.get('type')++ if strategy_type == 'code':+ code = strategy.get('code', {})+ if code.get('language') == 'python':+ return code.get('source', '')+ else:+ raise ValueError('Only Python strategies are supported')++ elif strategy_type == 'visual':+ visual = strategy.get('visual', {})+ generated = visual.get('generatedPython')+ if generated:+ return generated+ else:+ raise ValueError('Visual strategy must have generated Python code')++ elif strategy_type == 'template':+ raise NotImplementedError('Template strategies not yet implemented')++ else:+ raise ValueError(f'Unknown strategy type: {strategy_type}')++ def _parse_lean_results(+ self,+ backtest_id: str,+ lean_results: Dict[str, Any],+ logs: List[str]+ ) -> BacktestResult:+ """Parse Lean results to platform-independent format"""++ # Extract statistics+ stats = lean_results.get('TotalPerformance', {}).get('PortfolioStatistics', {})+ trade_stats = lean_results.get('TotalPerformance', {}).get('TradeStatistics', {})++ # Parse performance metrics+ performance = PerformanceMetrics(+ total_return=self._parse_percent(stats.get('TotalReturn', '0%')),+ annualized_return=self._parse_percent(stats.get('AnnualReturn', '0%')),+ sharpe_ratio=self._parse_float(stats.get('SharpeRatio', '0')),+ sortino_ratio=self._parse_float(stats.get('SortinoRatio', '0')),+ max_drawdown=self._parse_percent(stats.get('MaxDrawdown', '0%')),+ win_rate=self._parse_percent(trade_stats.get('WinRate', '0%')),+ loss_rate=self._parse_percent(trade_stats.get('LossRate', '0%')),+ profit_factor=self._parse_float(trade_stats.get('ProfitLossRatio', '0')),+ volatility=self._parse_percent(stats.get('AnnualStandardDeviation', '0%')),+ calmar_ratio=0, # Calculate+ total_trades=int(trade_stats.get('TotalNumberOfTrades', 0)),+ winning_trades=0, # Calculate from win_rate+ losing_trades=0, # Calculate from loss_rate+ average_win=self._parse_float(trade_stats.get('AverageWin', '0')),+ average_loss=abs(self._parse_float(trade_stats.get('AverageLoss', '0'))),+ largest_win=self._parse_float(trade_stats.get('LargestWin', '0')),+ largest_loss=abs(self._parse_float(trade_stats.get('LargestLoss', '0'))),+ average_trade_return=0,+ expectancy=0,+ )++ # Parse trades (simplified)+ trades: List[Trade] = []+ # (Would parse from lean_results['Orders'])++ # Parse equity curve (simplified)+ equity: List[EquityPoint] = []+ # (Would parse from lean_results['Charts']['Strategy Equity'])++ # Parse general statistics+ statistics = BacktestStatistics(+ start_date=self._extract_statistic(lean_results, 'Start') or '',+ end_date=self._extract_statistic(lean_results, 'End') or '',+ initial_capital=100000, # From request+ final_capital=100000, # Calculate+ total_fees=0,+ total_slippage=0,+ total_trades=performance.total_trades,+ winning_days=0,+ losing_days=0,+ average_daily_return=0,+ best_day=0,+ worst_day=0,+ consecutive_wins=0,+ consecutive_losses=0,+ )++ return BacktestResult(+ id=backtest_id,+ status='completed',+ performance=performance,+ trades=trades,+ equity=equity,+ statistics=statistics,+ logs=logs,+ start_time=self._current_timestamp(),+ end_time=self._current_timestamp(),+ )++ def _parse_float(self, value: Any) -> float:+ """Parse float from string or number"""+ if value is None:+ return 0.0+ if isinstance(value, (int, float)):+ return float(value)+ if isinstance(value, str):+ try:+ return float(value.replace('%', ''))+ except:+ return 0.0+ return 0.0++ def _parse_percent(self, value: str) -> float:+ """Parse percentage string to decimal"""+ if not value:+ return 0.0+ cleaned = value.replace('%', '').strip()+ try:+ return float(cleaned) / 100.0+ except:+ return 0.0++ def _extract_statistic(self, results: Dict[str, Any], key: str) -> Optional[str]:+ """Extract statistic by key"""+ stats = results.get('Statistics', [])+ for stat in stats:+ if stat.get('Key') == key:+ return stat.get('Value')+ return None++ def _format_date(self, iso_date: str) -> str:+ """Convert ISO date to YYYYMMDD"""+ dt = datetime.fromisoformat(iso_date.replace('Z', '+00:00'))+ return dt.strftime('%Y%m%d')++ def _get_empty_metrics(self) -> PerformanceMetrics:+ """Get empty performance metrics"""+ return PerformanceMetrics(+ total_return=0, annualized_return=0, sharpe_ratio=0, sortino_ratio=0,+ max_drawdown=0, win_rate=0, loss_rate=0, profit_factor=0, volatility=0,+ calmar_ratio=0, total_trades=0, winning_trades=0, losing_trades=0,+ average_win=0, average_loss=0, largest_win=0, largest_loss=0,+ average_trade_return=0, expectancy=0+ )++ def _get_empty_statistics(self) -> BacktestStatistics:+ """Get empty statistics"""+ return BacktestStatistics(+ start_date='', end_date='', initial_capital=0, final_capital=0,+ total_fees=0, total_slippage=0, total_trades=0, winning_days=0,+ losing_days=0, average_daily_return=0, best_day=0, worst_day=0,+ consecutive_wins=0, consecutive_losses=0+ )+++# ============================================================================+# CLI Entry Point (for direct Python execution)+# ============================================================================++def main():+ """Main entry point for CLI execution"""+ if len(sys.argv) < 3:+ print(json_response({+ 'success': False,+ 'error': 'Usage: python lean_provider.py <command> <json_args>'+ }))+ sys.exit(1)++ command = sys.argv[1]+ json_args = sys.argv[2]++ try:+ args = parse_json_input(json_args)+ provider = LeanProvider()++ if command == 'initialize':+ result = provider.initialize(args)+ elif command == 'test_connection':+ result = provider.test_connection()+ elif command == 'run_backtest':+ result = provider.run_backtest(args)+ elif command == 'get_historical_data':+ result = provider.get_historical_data(args)+ elif command == 'optimize':+ result = provider.optimize(args)+ else:+ result = {'success': False, 'error': f'Unknown command: {command}'}++ print(json_response(result))++ except Exception as e:+ print(json_response({+ 'success': False,+ 'error': str(e),+ 'traceback': __import__('traceback').format_exc()+ }))+ sys.exit(1)+++if __name__ == '__main__':+ main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/__init__.pynew file mode 100644index 000000000..bbe030345--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/__init__.py@@ -0,0 +1,8 @@+"""+VectorBT Provider Module+Ultra-fast vectorized backtesting+"""++from .vectorbt_provider import VectorBTProvider++__all__ = ['VectorBTProvider']diff --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.pynew file mode 100644index 000000000..e5b9cc5f1--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/Analytics/backtesting/vectorbt/vectorbt_provider.py@@ -0,0 +1,327 @@+"""+VectorBT Provider Implementation++Ultra-fast vectorized backtesting using VectorBT.+"""++import sys+import json+from typing import Dict, Any+from pathlib import Path++# Import base provider+sys.path.append(str(Path(__file__).parent.parent))+from base.base_provider import (+ BacktestingProviderBase,+ BacktestResult,+ PerformanceMetrics,+ Trade,+ EquityPoint,+ BacktestStatistics,+ json_response,+ parse_json_input+)+++class VectorBTProvider(BacktestingProviderBase):+ """+ VectorBT Provider++ Executes ultra-fast vectorized backtests using VectorBT library.+ """++ def __init__(self):+ super().__init__()++ @property+ def name(self) -> str:+ return "VectorBT"++ @property+ def version(self) -> str:+ try:+ import vectorbt as vbt+ return vbt.__version__+ except:+ return "0.25.0"++ @property+ def capabilities(self) -> Dict[str, Any]:+ return {+ 'backtesting': True,+ 'optimization': True,+ 'liveTrading': False,+ 'research': True,+ 'multiAsset': ['equity', 'crypto', 'forex'],+ 'indicators': True,+ 'customStrategies': True,+ 'maxConcurrentBacktests': 10,+ 'vectorization': True,+ }++ def initialize(self, config: Dict[str, Any]) -> Dict[str, Any]:+ """Initialize VectorBT provider"""+ try:+ # Check if vectorbt is installed+ import vectorbt as vbt+ import pandas as pd+ import numpy as np++ self.initialized = True+ self.connected = True+ self.config = config++ self._log('VectorBT provider initialized successfully')+ return self._create_success_result(f'VectorBT {vbt.__version__} initialized')++ except ImportError as e:+ self._error('VectorBT not installed', e)+ return self._create_error_result('VectorBT not installed. Run: pip install vectorbt')+ except Exception as e:+ self._error('Initialization failed', e)+ return self._create_error_result(str(e))++ def test_connection(self) -> Dict[str, Any]:+ """Test VectorBT availability"""+ try:+ import vectorbt as vbt+ return self._create_success_result(f'VectorBT {vbt.__version__} is available')+ except ImportError:+ return self._create_error_result('VectorBT not installed')++ def run_backtest(self, request: Dict[str, Any]) -> Dict[str, Any]:+ """Run backtest using VectorBT"""+ self._ensure_connected()++ backtest_id = self._generate_id()+ logs = []++ try:+ import vectorbt as vbt+ import pandas as pd+ import numpy as np+ import yfinance as yf++ logs.append(f'{self._current_timestamp()}: Starting VectorBT backtest {backtest_id}')++ # Extract request parameters+ strategy = request.get('strategy', {})+ start_date = request.get('startDate')+ end_date = request.get('endDate')+ initial_capital = request.get('initialCapital', 100000)+ assets = request.get('assets', [])++ # Download data using yfinance+ symbols = [asset['symbol'] for asset in assets]+ logs.append(f'{self._current_timestamp()}: Downloading data for {symbols}')++ data = yf.download(symbols, start=start_date, end=end_date)['Close']++ if data.empty:+ raise ValueError('No data downloaded')++ logs.append(f'{self._current_timestamp()}: Data downloaded: {len(data)} rows')++ # Execute strategy code+ # For VectorBT, we expect vectorized operations+ strategy_code = self._extract_strategy_code(strategy)++ # Create execution context+ context = {+ 'vbt': vbt,+ 'pd': pd,+ 'np': np,+ 'data': data,+ 'initial_capital': initial_capital,+ }++ # Execute strategy+ exec(strategy_code, context)++ # Get portfolio from context (strategy should create 'portfolio')+ portfolio = context.get('portfolio')++ if portfolio is None:+ raise ValueError('Strategy must create a "portfolio" variable')++ logs.append(f'{self._current_timestamp()}: Backtest completed')++ # Extract results+ total_return = portfolio.total_return+ stats = portfolio.stats()++ # Build result+ performance = PerformanceMetrics(+ total_return=total_return,+ annualized_return=stats.get('Annualized Return [%]', 0) / 100,+ sharpe_ratio=stats.get('Sharpe Ratio', 0),+ sortino_ratio=stats.get('Sortino Ratio', 0),+ max_drawdown=abs(stats.get('Max Drawdown [%]', 0)) / 100,+ win_rate=stats.get('Win Rate [%]', 0) / 100,+ loss_rate=1 - (stats.get('Win Rate [%]', 0) / 100),+ profit_factor=stats.get('Profit Factor', 0),+ volatility=stats.get('Annualized Volatility [%]', 0) / 100,+ calmar_ratio=stats.get('Calmar Ratio', 0),+ total_trades=int(stats.get('Total Trades', 0)),+ winning_trades=0, # Calculate from trades+ losing_trades=0,+ average_win=0,+ average_loss=0,+ largest_win=0,+ largest_loss=0,+ average_trade_return=0,+ expectancy=0,+ )++ statistics = BacktestStatistics(+ start_date=start_date,+ end_date=end_date,+ initial_capital=initial_capital,+ final_capital=portfolio.final_value,+ total_fees=0,+ total_slippage=0,+ total_trades=int(stats.get('Total Trades', 0)),+ winning_days=0,+ losing_days=0,+ average_daily_return=0,+ best_day=0,+ worst_day=0,+ consecutive_wins=0,+ 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()+ ]++ result = BacktestResult(+ id=backtest_id,+ status='completed',+ performance=performance,+ trades=[], # Would parse from portfolio.trades+ equity=equity,+ statistics=statistics,+ logs=logs,+ start_time=self._current_timestamp(),+ end_time=self._current_timestamp(),+ )++ return result.to_dict()++ except Exception as e:+ self._error(f'Backtest {backtest_id} failed', e)+ logs.append(f'{self._current_timestamp()}: Error: {str(e)}')++ return BacktestResult(+ id=backtest_id,+ status='failed',+ performance=self._get_empty_metrics(),+ trades=[],+ equity=[],+ statistics=self._get_empty_statistics(),+ logs=logs,+ error=str(e)+ ).to_dict()++ def get_historical_data(self, request: Dict[str, Any]) -> list:+ """Get historical data using yfinance"""+ try:+ import yfinance as yf++ symbols = request.get('symbols', [])+ start_date = request.get('startDate')+ end_date = request.get('endDate')++ data = yf.download(symbols, start=start_date, end=end_date)++ return [] # Would convert to HistoricalData format++ except Exception as e:+ self._error('Data fetch failed', e)+ raise++ def calculate_indicator(self, indicator_type: str, params: Dict[str, Any]) -> Dict[str, Any]:+ """Calculate indicator using VectorBT"""+ raise NotImplementedError('Use VectorBT indicators within backtests')++ def _extract_strategy_code(self, strategy: Dict[str, Any]) -> str:+ """Extract Python code from strategy"""+ strategy_type = strategy.get('type')++ if strategy_type == 'code':+ code = strategy.get('code', {})+ if code.get('language') == 'python':+ return code.get('source', '')+ else:+ raise ValueError('Only Python strategies supported')+ else:+ raise ValueError(f'Strategy type {strategy_type} not supported yet')++ def _get_empty_metrics(self) -> PerformanceMetrics:+ return PerformanceMetrics(+ total_return=0, annualized_return=0, sharpe_ratio=0, sortino_ratio=0,+ max_drawdown=0, win_rate=0, loss_rate=0, profit_factor=0, volatility=0,+ calmar_ratio=0, total_trades=0, winning_trades=0, losing_trades=0,+ average_win=0, average_loss=0, largest_win=0, largest_loss=0,+ average_trade_return=0, expectancy=0+ )++ def _get_empty_statistics(self) -> BacktestStatistics:+ return BacktestStatistics(+ start_date='', end_date='', initial_capital=0, final_capital=0,+ total_fees=0, total_slippage=0, total_trades=0, winning_days=0,+ losing_days=0, average_daily_return=0, best_day=0, worst_day=0,+ consecutive_wins=0, consecutive_losses=0+ )+++# CLI Entry Point+def main():+ if len(sys.argv) < 3:+ print(json_response({+ 'success': False,+ 'error': 'Usage: python vectorbt_provider.py <command> <json_args>'+ }))+ sys.exit(1)++ command = sys.argv[1]+ json_args = sys.argv[2]++ try:+ args = parse_json_input(json_args)+ provider = VectorBTProvider()++ if command == 'test_import':+ import vectorbt as vbt+ print(json_response({'success': True, 'version': vbt.__version__}))+ elif command == 'test_connection':+ result = provider.test_connection()+ print(json_response(result))+ elif command == 'initialize':+ result = provider.initialize(args)+ print(json_response(result))+ elif command == 'run_backtest':+ result = provider.run_backtest(args)+ print(json_response(result))+ else:+ print(json_response({'success': False, 'error': f'Unknown command: {command}'}))++ except Exception as e:+ print(json_response({+ 'success': False,+ 'error': str(e),+ 'traceback': __import__('traceback').format_exc()+ }))+ sys.exit(1)+++if __name__ == '__main__':+ main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/compute_technicals.py b/fincept-terminal-desktop/src-tauri/resources/scripts/compute_technicals.pynew file mode 100644index 000000000..4d400e737--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/compute_technicals.py@@ -0,0 +1,121 @@+"""+Compute all technical indicators from historical data+This script receives historical OHLCV data as JSON and returns all computed technicals+"""++import sys+import json+import pandas as pd++# Add technicals directory to path+import os+sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'technicals'))++from technicals.momentum_indicators import calculate_all_momentum_indicators+from technicals.volume_indicators import calculate_all_volume_indicators+from technicals.volatility_indicators import calculate_all_volatility_indicators+from technicals.trend_indicators import calculate_all_trend_indicators+from technicals.others_indicators import calculate_all_others_indicators+++def compute_all_technicals(historical_data_json):+ """+ Compute all technical indicators from historical data++ Args:+ historical_data_json: JSON string with array of OHLCV data++ Returns:+ JSON string with all computed technical indicators+ """+ try:+ # Parse input data+ data = json.loads(historical_data_json)+ df = pd.DataFrame(data)++ # Ensure required columns exist and are properly named+ required_columns = ['open', 'high', 'low', 'close']+ for col in required_columns:+ if col not in df.columns:+ return json.dumps({+ "success": False,+ "error": f"Missing required column: {col}"+ })++ # Compute all indicators+ result_df = df.copy()++ # Trend indicators+ result_df = calculate_all_trend_indicators(result_df)++ # Momentum indicators+ result_df = calculate_all_momentum_indicators(result_df)++ # Volatility indicators+ result_df = calculate_all_volatility_indicators(result_df)++ # Volume indicators (only if volume data exists)+ if 'volume' in result_df.columns:+ result_df = calculate_all_volume_indicators(result_df)++ # Other indicators+ result_df = calculate_all_others_indicators(result_df)++ # Replace NaN with None for proper JSON encoding+ result_df = result_df.where(pd.notnull(result_df), None)++ # Convert to JSON+ result_json = result_df.to_json(orient='records')++ return json.dumps({+ "success": True,+ "data": json.loads(result_json),+ "indicator_columns": {+ "trend": [+ "sma_20", "ema_12", "wma_9", "macd", "macd_signal", "macd_diff",+ "trix", "mass_index", "ichimoku_conversion", "ichimoku_base",+ "ichimoku_a", "ichimoku_b", "kst", "kst_signal", "dpo", "cci",+ "adx", "adx_pos", "adx_neg", "vortex_pos", "vortex_neg",+ "psar", "psar_up", "psar_down", "psar_up_indicator", "psar_down_indicator",+ "stc", "aroon_up", "aroon_down", "aroon_indicator"+ ],+ "momentum": [+ "rsi", "stoch_k", "stoch_d", "stoch_rsi", "stoch_rsi_k", "stoch_rsi_d",+ "williams_r", "ao", "kama", "roc", "tsi", "uo",+ "ppo", "ppo_signal", "ppo_hist", "pvo", "pvo_signal", "pvo_hist"+ ],+ "volatility": [+ "atr", "bb_mavg", "bb_hband", "bb_lband", "bb_pband", "bb_wband",+ "bb_hband_indicator", "bb_lband_indicator",+ "kc_mavg", "kc_hband", "kc_lband", "kc_pband", "kc_wband",+ "kc_hband_indicator", "kc_lband_indicator",+ "dc_hband", "dc_lband", "dc_mband", "dc_pband", "dc_wband", "ui"+ ],+ "volume": [+ "adi", "obv", "cmf", "fi", "eom", "eom_signal",+ "vpt", "nvi", "vwap", "mfi"+ ],+ "others": [+ "daily_return", "daily_log_return", "cumulative_return"+ ]+ }+ })++ except Exception as e:+ return json.dumps({+ "success": False,+ "error": str(e)+ })+++if __name__ == "__main__":+ if len(sys.argv) < 2:+ print(json.dumps({+ "success": False,+ "error": "Usage: python compute_technicals.py '<historical_data_json>'"+ }))+ sys.exit(1)++ historical_data_json = sys.argv[1]+ result = compute_all_technicals(historical_data_json)+ print(result)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/fetch_company_news.py b/fincept-terminal-desktop/src-tauri/resources/scripts/fetch_company_news.pynew file mode 100644index 000000000..fa543df2e--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/fetch_company_news.py@@ -0,0 +1,287 @@+"""+Fetch company news using GNews+This script fetches latest news articles for a given company/symbol+"""++import sys+import json+from datetime import datetime+from gnews import GNews++def fetch_company_news(query, max_results=10, period='7d', language='en', country='US'):+ """+ Fetch news articles for a company++ Args:+ query: Company name or symbol to search+ max_results: Maximum number of articles to return (default: 10)+ period: Time period - format: '7d', '1M', '1y' (default: '7d')+ language: Language code (default: 'en')+ country: Country code (default: 'US')++ Returns:+ JSON string with news articles+ """+ try:+ # Initialize GNews+ google_news = GNews(+ language=language,+ country=country,+ period=period,+ max_results=max_results+ )++ # Fetch news+ news = google_news.get_news(query)++ if not news:+ return json.dumps({+ "success": True,+ "data": [],+ "query": query,+ "count": 0,+ "message": "No news found for this query"+ })++ # Process and format news articles+ articles = []+ for article in news:+ processed_article = {+ "title": article.get('title', 'N/A'),+ "description": article.get('description', 'N/A'),+ "url": article.get('url', '#'),+ "publisher": article.get('publisher', {}).get('title', 'Unknown'),+ "publisher_url": article.get('publisher', {}).get('href', '#'),+ "published_date": article.get('published date', 'Unknown'),+ "image_url": None # GNews doesn't provide images directly+ }+ articles.append(processed_article)++ return json.dumps({+ "success": True,+ "data": articles,+ "query": query,+ "count": len(articles),+ "period": period,+ "language": language,+ "country": country+ })++ except Exception as e:+ return json.dumps({+ "success": False,+ "error": str(e),+ "query": query+ })+++def fetch_news_by_topic(topic, max_results=10):+ """+ Fetch news by topic++ Args:+ topic: Topic to search (WORLD, NATION, BUSINESS, TECHNOLOGY, ENTERTAINMENT, SPORTS, SCIENCE, HEALTH)+ max_results: Maximum number of articles++ Returns:+ JSON string with news articles+ """+ try:+ google_news = GNews(max_results=max_results)+ news = google_news.get_news_by_topic(topic)++ if not news:+ return json.dumps({+ "success": True,+ "data": [],+ "topic": topic,+ "count": 0+ })++ articles = []+ for article in news:+ processed_article = {+ "title": article.get('title', 'N/A'),+ "description": article.get('description', 'N/A'),+ "url": article.get('url', '#'),+ "publisher": article.get('publisher', {}).get('title', 'Unknown'),+ "publisher_url": article.get('publisher', {}).get('href', '#'),+ "published_date": article.get('published date', 'Unknown'),+ }+ articles.append(processed_article)++ return json.dumps({+ "success": True,+ "data": articles,+ "topic": topic,+ "count": len(articles)+ })++ except Exception as e:+ return json.dumps({+ "success": False,+ "error": str(e),+ "topic": topic+ })+++def get_full_article(url):+ """+ Get full article content from URL++ Args:+ url: Article URL++ Returns:+ JSON string with article content+ """+ try:+ google_news = GNews()+ article = google_news.get_full_article(url)++ if article:+ return json.dumps({+ "success": True,+ "data": {+ "title": article.title if hasattr(article, 'title') else 'N/A',+ "text": article.text if hasattr(article, 'text') else 'N/A',+ "authors": article.authors if hasattr(article, 'authors') else [],+ "publish_date": str(article.publish_date) if hasattr(article, 'publish_date') else 'Unknown',+ "top_image": article.top_image if hasattr(article, 'top_image') else None,+ "url": url+ }+ })+ else:+ return json.dumps({+ "success": False,+ "error": "Could not fetch article content",+ "url": url+ })++ except Exception as e:+ return json.dumps({+ "success": False,+ "error": str(e),+ "url": url+ })+++if __name__ == "__main__":+ if len(sys.argv) < 3:+ print(json.dumps({+ "success": False,+ "error": "Usage: python fetch_company_news.py <command> <args>",+ "commands": {+ "search": "python fetch_company_news.py search <query> [max_results] [period] [language] [country]",+ "topic": "python fetch_company_news.py topic <topic> [max_results]",+ "article": "python fetch_company_news.py article <url>",+ "help": "python fetch_company_news.py help"+ }+ }))+ sys.exit(1)++ command = sys.argv[1]++ try:+ if command == "help":+ help_text = {+ "description": "Company News Fetcher - Get latest news articles using Google News",+ "commands": {+ "search": {+ "description": "Search news by company name or symbol",+ "usage": "python fetch_company_news.py search <query> [max_results] [period] [language] [country]",+ "arguments": {+ "query": "Company name or symbol (e.g., 'Apple', 'AAPL', 'Tesla Inc')",+ "max_results": "Maximum articles to return (default: 10)",+ "period": "Time period: '7d', '1M', '1y' (default: '7d')",+ "language": "Language code (default: 'en')",+ "country": "Country code (default: 'US')"+ },+ "examples": [+ "python fetch_company_news.py search 'Apple Inc'",+ "python fetch_company_news.py search TSLA 20 1M",+ "python fetch_company_news.py search 'Microsoft' 15 7d en US"+ ]+ },+ "topic": {+ "description": "Get news by topic",+ "usage": "python fetch_company_news.py topic <topic> [max_results]",+ "arguments": {+ "topic": "Topic name (WORLD, NATION, BUSINESS, TECHNOLOGY, ENTERTAINMENT, SPORTS, SCIENCE, HEALTH)",+ "max_results": "Maximum articles to return (default: 10)"+ },+ "examples": [+ "python fetch_company_news.py topic BUSINESS",+ "python fetch_company_news.py topic TECHNOLOGY 20"+ ]+ },+ "article": {+ "description": "Get full article content from URL",+ "usage": "python fetch_company_news.py article <url>",+ "arguments": {+ "url": "Full article URL"+ },+ "examples": [+ "python fetch_company_news.py article 'https://example.com/news/article'"+ ]+ }+ }+ }+ print(json.dumps(help_text, indent=2))++ elif command == "search":+ if len(sys.argv) < 3:+ print(json.dumps({+ "success": False,+ "error": "Usage: python fetch_company_news.py search <query> [max_results] [period] [language] [country]"+ }))+ sys.exit(1)++ query = sys.argv[2]+ max_results = int(sys.argv[3]) if len(sys.argv) > 3 else 10+ period = sys.argv[4] if len(sys.argv) > 4 else '7d'+ language = sys.argv[5] if len(sys.argv) > 5 else 'en'+ country = sys.argv[6] if len(sys.argv) > 6 else 'US'++ result = fetch_company_news(query, max_results, period, language, country)+ print(result)++ elif command == "topic":+ if len(sys.argv) < 3:+ print(json.dumps({+ "success": False,+ "error": "Usage: python fetch_company_news.py topic <topic> [max_results]"+ }))+ sys.exit(1)++ topic = sys.argv[2]+ max_results = int(sys.argv[3]) if len(sys.argv) > 3 else 10++ result = fetch_news_by_topic(topic, max_results)+ print(result)++ elif command == "article":+ if len(sys.argv) < 3:+ print(json.dumps({+ "success": False,+ "error": "Usage: python fetch_company_news.py article <url>"+ }))+ sys.exit(1)++ url = sys.argv[2]+ result = get_full_article(url)+ print(result)++ else:+ print(json.dumps({+ "success": False,+ "error": f"Unknown command: {command}. Use 'help' for available commands."+ }))+ sys.exit(1)++ except Exception as e:+ print(json.dumps({+ "success": False,+ "error": str(e)+ }))+ sys.exit(1)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/financial_report_generator.py b/fincept-terminal-desktop/src-tauri/resources/scripts/financial_report_generator.pyindex aae6790cd..51a523165 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/financial_report_generator.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/financial_report_generator.py@@ -17,9 +17,27 @@ from io import BytesIOtry:from weasyprint import HTML, CSSWEASYPRINT_AVAILABLE = True-except ImportError:+except (ImportError, OSError) as e:WEASYPRINT_AVAILABLE = False- print("Warning: WeasyPrint not available. Install with: pip install weasyprint", file=sys.stderr)+ print(f"Warning: WeasyPrint not available: {e}", file=sys.stderr)++# Alternative: Try pdfkit (wkhtmltopdf wrapper)+try:+ import pdfkit+ PDFKIT_AVAILABLE = True+except ImportError:+ PDFKIT_AVAILABLE = False++# Alternative: Try reportlab+try:+ from reportlab.lib.pagesizes import letter, A4+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak, Table, TableStyle, Image as RLImage+ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle+ from reportlab.lib.units import inch+ from reportlab.lib import colors as rl_colors+ REPORTLAB_AVAILABLE = True+except ImportError:+ REPORTLAB_AVAILABLE = Falsetry:import matplotlib@@ -378,31 +396,144 @@ class FinancialReportGenerator:return html- def generate_pdf(self, template_data: Dict[str, Any], output_path: str, template_name: str = 'default.html') -> Dict[str, Any]:+ def generate_pdf_reportlab(self, template_data: Dict[str, Any], output_path: str) -> Dict[str, Any]:"""- Generate PDF from template data+ Generate PDF using ReportLab (pure Python, cross-platform)Args:template_data: Report template dataoutput_path: Path to save PDF- template_name: Name of Jinja2 template fileReturns:Result dict with success status"""- if not WEASYPRINT_AVAILABLE:+ if not REPORTLAB_AVAILABLE:return {"success": False,- "error": "WeasyPrint not available. Install with: pip install weasyprint",+ "error": "ReportLab not available. Install with: pip install reportlab","output_path": None}try:- # Generate HTML- html_content = self.generate_html(template_data, template_name)-- # Generate PDF- HTML(string=html_content).write_pdf(output_path)+ # Determine page size+ page_size_map = {+ 'A4': A4,+ 'Letter': letter,+ 'Legal': (8.5*inch, 14*inch)+ }+ page_size = page_size_map.get(template_data.get('styles', {}).get('pageSize', 'A4'), A4)++ # Create PDF+ doc = SimpleDocTemplate(+ output_path,+ pagesize=page_size,+ rightMargin=72,+ leftMargin=72,+ topMargin=72,+ bottomMargin=18,+ )++ # Styles+ styles = getSampleStyleSheet()+ title_style = ParagraphStyle(+ 'CustomTitle',+ parent=styles['Heading1'],+ fontSize=24,+ textColor=rl_colors.HexColor('#0066cc'),+ spaceAfter=30,+ )+ heading_style = ParagraphStyle(+ 'CustomHeading',+ parent=styles['Heading2'],+ fontSize=18,+ textColor=rl_colors.HexColor('#0066cc'),+ spaceAfter=12,+ )+ normal_style = styles['BodyText']++ # Build story+ story = []++ # Header+ metadata = template_data.get('metadata', {})+ if metadata.get('title'):+ story.append(Paragraph(metadata['title'], title_style))++ if metadata.get('company'):+ company_style = ParagraphStyle(+ 'Company',+ parent=styles['Normal'],+ fontSize=14,+ textColor=rl_colors.HexColor('#0066cc'),+ spaceAfter=12,+ )+ story.append(Paragraph(metadata['company'], company_style))++ # Metadata line+ meta_text = []+ if metadata.get('author'):+ meta_text.append(f"Author: {metadata['author']}")+ if metadata.get('date'):+ meta_text.append(f"Date: {metadata['date']}")+ if meta_text:+ meta_style = ParagraphStyle('Meta', parent=styles['Normal'], fontSize=10, textColor=rl_colors.grey)+ story.append(Paragraph(' | '.join(meta_text), meta_style))++ story.append(Spacer(1, 0.3*inch))++ # Components+ for component in template_data.get('components', []):+ comp_type = component.get('type')+ content = component.get('content', '')++ if comp_type == 'heading':+ if content:+ story.append(Paragraph(content, heading_style))++ elif comp_type == 'text':+ if content:+ story.append(Paragraph(content, normal_style))+ story.append(Spacer(1, 0.1*inch))++ elif comp_type == 'divider':+ story.append(Spacer(1, 0.2*inch))++ elif comp_type == 'code':+ if content:+ code_style = ParagraphStyle(+ 'Code',+ parent=styles['Code'],+ fontSize=9,+ leftIndent=20,+ rightIndent=20,+ backColor=rl_colors.HexColor('#f5f5f5'),+ )+ story.append(Paragraph(f'<pre>{content}</pre>', code_style))+ story.append(Spacer(1, 0.1*inch))++ elif comp_type == 'table':+ config = component.get('config', {})+ columns = config.get('columns', [])+ rows_data = component.get('content', {}).get('rows', [])++ if columns and rows_data:+ table_data = [columns] + rows_data+ t = Table(table_data)+ t.setStyle(TableStyle([+ ('BACKGROUND', (0, 0), (-1, 0), rl_colors.HexColor('#0066cc')),+ ('TEXTCOLOR', (0, 0), (-1, 0), rl_colors.white),+ ('ALIGN', (0, 0), (-1, -1), 'LEFT'),+ ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),+ ('FONTSIZE', (0, 0), (-1, 0), 12),+ ('BOTTOMPADDING', (0, 0), (-1, 0), 12),+ ('BACKGROUND', (0, 1), (-1, -1), rl_colors.white),+ ('GRID', (0, 0), (-1, -1), 1, rl_colors.grey),+ ]))+ story.append(t)+ story.append(Spacer(1, 0.2*inch))++ # Build PDF+ doc.build(story)return {"success": True,@@ -418,6 +549,43 @@ class FinancialReportGenerator:"output_path": None}+ def generate_pdf(self, template_data: Dict[str, Any], output_path: str, template_name: str = 'default.html') -> Dict[str, Any]:+ """+ Generate PDF from template data (tries multiple backends)++ Args:+ template_data: Report template data+ output_path: Path to save PDF+ template_name: Name of Jinja2 template file++ Returns:+ Result dict with success status+ """+ # Try WeasyPrint first (best HTML/CSS support)+ if WEASYPRINT_AVAILABLE:+ try:+ html_content = self.generate_html(template_data, template_name)+ HTML(string=html_content).write_pdf(output_path)+ return {+ "success": True,+ "output_path": output_path,+ "file_size": os.path.getsize(output_path),+ "error": None+ }+ except Exception as e:+ print(f"WeasyPrint failed: {e}", file=sys.stderr)++ # Fallback to ReportLab (pure Python, always works)+ if REPORTLAB_AVAILABLE:+ return self.generate_pdf_reportlab(template_data, output_path)++ # No PDF library available+ return {+ "success": False,+ "error": "No PDF generation library available. Install reportlab: pip install reportlab",+ "output_path": None+ }+def main():"""Main CLI function"""diff --git a/fincept-terminal-desktop/src-tauri/src/commands/backtesting.rs b/fincept-terminal-desktop/src-tauri/src/commands/backtesting.rsnew file mode 100644index 000000000..c42b123e4--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/commands/backtesting.rs@@ -0,0 +1,321 @@+/**+ * Backtesting Tauri Commands+ *+ * Rust commands for executing Python backtesting providers.+ * Bridges TypeScript frontend to Python backend.+ */++use serde::{Deserialize, Serialize};+use std::process::{Command, Stdio};+use std::io::{BufRead, BufReader};+use std::sync::{Arc, Mutex};+use std::collections::HashMap;+use tauri::State;++// ============================================================================+// Types+// ============================================================================++#[derive(Debug, Serialize, Deserialize)]+pub struct CommandResult {+ success: bool,+ stdout: String,+ stderr: String,+ exit_code: i32,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct ProcessInfo {+ process_id: u32,+}++#[derive(Debug, Clone)]+struct RunningProcess {+ pid: u32,+ // In production, would store child process handle for cancellation+}++// State for tracking running processes+pub struct BacktestingState {+ running_processes: Arc<Mutex<HashMap<String, RunningProcess>>>,+}++impl Default for BacktestingState {+ fn default() -> Self {+ Self {+ running_processes: Arc::new(Mutex::new(HashMap::new())),+ }+ }+}++// ============================================================================+// Commands+// ============================================================================++/**+ * Execute Lean CLI command+ *+ * Runs Lean backtesting engine and returns process information.+ */+#[tauri::command]+pub async fn execute_lean_cli(+ command: String,+ working_dir: String,+ backtest_id: String,+ state: State<'_, BacktestingState>,+) -> Result<ProcessInfo, String> {+ println!("[Lean CLI] Executing: {}", command);+ println!("[Lean CLI] Working directory: {}", working_dir);++ // Parse command into parts+ let parts: Vec<&str> = command.split_whitespace().collect();+ if parts.is_empty() {+ return Err("Empty command".to_string());+ }++ let program = parts[0];+ let args = &parts[1..];++ // Execute command+ let mut child = Command::new(program)+ .args(args)+ .current_dir(&working_dir)+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .map_err(|e| format!("Failed to spawn Lean CLI: {}", e))?;++ let pid = child.id();++ // Store process info+ {+ let mut processes = state.running_processes.lock().unwrap();+ processes.insert(+ backtest_id.clone(),+ RunningProcess { pid },+ );+ }++ // In production, would spawn a thread to monitor output+ // For now, we'll wait for completion in the background++ println!("[Lean CLI] Started process with PID: {}", pid);++ Ok(ProcessInfo { process_id: pid })+}++/**+ * Execute generic command+ *+ * Used for testing connections, running utilities, etc.+ */+#[tauri::command]+pub async fn execute_command(command: String) -> Result<CommandResult, String> {+ println!("[Command] Executing: {}", command);++ // Parse command+ let parts: Vec<&str> = command.split_whitespace().collect();+ if parts.is_empty() {+ return Err("Empty command".to_string());+ }++ let program = parts[0];+ let args = &parts[1..];++ // Execute+ let output = Command::new(program)+ .args(args)+ .output()+ .map_err(|e| format!("Failed to execute command: {}", e))?;++ Ok(CommandResult {+ success: output.status.success(),+ stdout: String::from_utf8_lossy(&output.stdout).to_string(),+ stderr: String::from_utf8_lossy(&output.stderr).to_string(),+ exit_code: output.status.code().unwrap_or(-1),+ })+}++/**+ * Kill Lean process+ *+ * Terminates a running backtest by process ID.+ */+#[tauri::command]+pub async fn kill_lean_process(+ process_id: u32,+ state: State<'_, BacktestingState>,+) -> Result<(), String> {+ println!("[Lean CLI] Killing process: {}", process_id);++ #[cfg(unix)]+ {+ use nix::sys::signal::{kill, Signal};+ use nix::unistd::Pid;++ let pid = Pid::from_raw(process_id as i32);+ kill(pid, Signal::SIGTERM).map_err(|e| format!("Failed to kill process: {}", e))?;+ }++ #[cfg(windows)]+ {+ use std::process::Command;+ Command::new("taskkill")+ .args(&["/PID", &process_id.to_string(), "/F"])+ .output()+ .map_err(|e| format!("Failed to kill process: {}", e))?;+ }++ // Remove from tracking+ {+ let mut processes = state.running_processes.lock().unwrap();+ processes.retain(|_, p| p.pid != process_id);+ }++ println!("[Lean CLI] Process {} terminated", process_id);++ Ok(())+}++/**+ * Execute Python backtesting provider+ *+ * Runs a Python provider script with given command and arguments.+ */+#[tauri::command]+pub async fn execute_python_backtest(+ provider: String,+ command: String,+ args: String,+) -> Result<String, String> {+ println!("[Python Backtest] Provider: {}", provider);+ println!("[Python Backtest] Command: {}", command);++ // Determine Python path (bundled or system)+ let python_path = get_python_path();++ // Build script path+ let script_path = format!(+ "resources/scripts/Analytics/backtesting/{}/{}",+ provider.to_lowercase(),+ format!("{}_provider.py", provider.to_lowercase())+ );++ // Execute Python script+ let output = Command::new(&python_path)+ .arg(&script_path)+ .arg(&command)+ .arg(&args)+ .output()+ .map_err(|e| format!("Failed to execute Python script: {}", e))?;++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ return Err(format!("Python script failed: {}", stderr));+ }++ let stdout = String::from_utf8_lossy(&output.stdout).to_string();+ Ok(stdout)+}++/**+ * Check if file exists+ *+ * Utility to verify file paths.+ */+#[tauri::command]+pub async fn check_file_exists(path: String) -> Result<bool, String> {+ use std::path::Path;+ Ok(Path::new(&path).exists())+}++/**+ * Create directory+ *+ * Creates a directory if it doesn't exist.+ */+#[tauri::command]+pub async fn create_directory(path: String) -> Result<(), String> {+ use std::fs;+ fs::create_dir_all(&path).map_err(|e| format!("Failed to create directory: {}", e))+}++/**+ * Write file+ *+ * Writes content to a file.+ */+#[tauri::command]+pub async fn write_file(path: String, content: String) -> Result<(), String> {+ use std::fs;+ fs::write(&path, content).map_err(|e| format!("Failed to write file: {}", e))+}++/**+ * Read file+ *+ * Reads content from a file.+ */+#[tauri::command]+pub async fn read_file(path: String) -> Result<String, String> {+ use std::fs;+ fs::read_to_string(&path).map_err(|e| format!("Failed to read file: {}", e))+}++// ============================================================================+// Helper Functions+// ============================================================================++/**+ * Get Python executable path+ *+ * Returns path to bundled Python or system Python.+ */+fn get_python_path() -> String {+ // Check for bundled Python first+ #[cfg(target_os = "windows")]+ {+ let bundled_path = "resources/python/python.exe";+ if std::path::Path::new(bundled_path).exists() {+ return bundled_path.to_string();+ }+ "python".to_string()+ }++ #[cfg(target_os = "macos")]+ {+ let bundled_path = "resources/python/bin/python3";+ if std::path::Path::new(bundled_path).exists() {+ return bundled_path.to_string();+ }+ "python3".to_string()+ }++ #[cfg(target_os = "linux")]+ {+ let bundled_path = "resources/python/bin/python3";+ if std::path::Path::new(bundled_path).exists() {+ return bundled_path.to_string();+ }+ "python3".to_string()+ }+}++/**+ * Parse command string into program and arguments+ */+fn parse_command(command: &str) -> (String, Vec<String>) {+ let parts: Vec<String> = command+ .split_whitespace()+ .map(|s| s.to_string())+ .collect();++ if parts.is_empty() {+ return (String::new(), Vec::new());+ }++ let program = parts[0].clone();+ let args = parts[1..].to_vec();++ (program, args)+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/company_news.rs b/fincept-terminal-desktop/src-tauri/src/commands/company_news.rsnew file mode 100644index 000000000..3122f7d51--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/commands/company_news.rs@@ -0,0 +1,104 @@+use crate::utils::python::{execute_python_command, get_script_path};+use tauri::AppHandle;++/// Fetch company news using GNews+///+/// # Arguments+/// * `query` - Company name or symbol (e.g., "Apple", "AAPL", "Tesla Inc")+/// * `max_results` - Maximum number of articles to return (default: 10)+/// * `period` - Time period: "7d", "1M", "1y" (default: "7d")+/// * `language` - Language code (default: "en")+/// * `country` - Country code (default: "US")+#[tauri::command]+pub async fn fetch_company_news(+ app: AppHandle,+ query: String,+ max_results: Option<u32>,+ period: Option<String>,+ language: Option<String>,+ country: Option<String>,+) -> Result<String, String> {+ let mut args = vec!["search".to_string(), query.clone()];++ if let Some(max) = max_results {+ args.push(max.to_string());+ }++ if let Some(p) = period {+ args.push(p);+ }++ if let Some(lang) = language {+ args.push(lang);+ }++ if let Some(c) = country {+ args.push(c);+ }++ execute_news_command(app, args).await+}++/// Fetch news by topic+///+/// # Arguments+/// * `topic` - Topic name (WORLD, NATION, BUSINESS, TECHNOLOGY, ENTERTAINMENT, SPORTS, SCIENCE, HEALTH)+/// * `max_results` - Maximum number of articles to return+#[tauri::command]+pub async fn fetch_news_by_topic(+ app: AppHandle,+ topic: String,+ max_results: Option<u32>,+) -> Result<String, String> {+ let mut args = vec!["topic".to_string(), topic];++ if let Some(max) = max_results {+ args.push(max.to_string());+ }++ execute_news_command(app, args).await+}++/// Get full article content from URL+///+/// # Arguments+/// * `url` - Article URL+#[tauri::command]+pub async fn get_full_article(+ app: AppHandle,+ url: String,+) -> Result<String, String> {+ let args = vec!["article".to_string(), url];+ execute_news_command(app, args).await+}++/// Get help information for company news commands+#[tauri::command]+pub async fn get_company_news_help(app: AppHandle) -> Result<String, String> {+ let args = vec!["help".to_string()];+ execute_news_command(app, args).await+}++/// Internal helper function to execute news commands+async fn execute_news_command(app: AppHandle, args: Vec<String>) -> Result<String, String> {+ let script_name = "fetch_company_news.py";+ let script_path = get_script_path(&app, script_name)+ .map_err(|e| format!("Failed to locate script: {}", e))?;++ if !script_path.exists() {+ return Err(format!(+ "Company news script not found at: {}",+ script_path.display()+ ));+ }++ match execute_python_command(&app, script_name, &args) {+ Ok(output) => {+ if output.contains("\"success\":false") || output.contains("\"error\"") {+ return Err(output);+ }+ Ok(output)+ }+ Err(e) => Err(format!("News fetch failed: {}", e)),+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rsindex 2dcda5c80..246842de8 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs@@ -78,3 +78,9 @@ pub mod ai_agents;// Report Generatorpub mod report_generator;++// Backtesting+pub mod backtesting;++// Company News+pub mod company_news;diff --git a/fincept-terminal-desktop/src-tauri/src/commands/report_generator.rs b/fincept-terminal-desktop/src-tauri/src/commands/report_generator.rsindex b496c45be..a70524632 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/report_generator.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/report_generator.rs@@ -1,33 +1,482 @@-// Financial Report Generator Commands using Jinja2+// Financial Report Generator Commands using Rust printpdf#![allow(dead_code)]-use crate::utils::python::execute_python_command;+use serde::{Deserialize, Serialize};+use printpdf::*;+use std::fs::File;+use std::io::BufWriter;-/// Generate HTML from report template-#[tauri::command]-pub async fn generate_report_html(- app: tauri::AppHandle,- template_json: String,-) -> Result<String, String> {- let args = vec!["generate_html".to_string(), template_json];- execute_python_command(&app, "financial_report_generator.py", &args)+#[derive(Debug, Serialize, Deserialize, Clone)]+pub struct ReportComponent {+ pub id: String,+ #[serde(rename = "type")]+ pub component_type: String,+ pub content: Option<String>,+ pub config: ReportComponentConfig,+}++#[derive(Debug, Serialize, Deserialize, Clone)]+pub struct ReportComponentConfig {+ #[serde(rename = "fontSize")]+ pub font_size: Option<String>,+ #[serde(rename = "fontWeight")]+ pub font_weight: Option<String>,+ pub color: Option<String>,+ pub alignment: Option<String>,+ #[serde(rename = "chartType")]+ pub chart_type: Option<String>,+ pub columns: Option<Vec<String>>,+ #[serde(rename = "imageUrl")]+ pub image_url: Option<String>,+}++#[derive(Debug, Serialize, Deserialize, Clone)]+pub struct ReportMetadata {+ pub author: Option<String>,+ pub company: Option<String>,+ pub date: Option<String>,+ pub title: Option<String>,+}++#[derive(Debug, Serialize, Deserialize, Clone)]+pub struct ReportStyles {+ #[serde(rename = "pageSize")]+ pub page_size: Option<String>,+ pub orientation: Option<String>,+ pub margins: Option<String>,+ #[serde(rename = "headerFooter")]+ pub header_footer: Option<bool>,+}++#[derive(Debug, Serialize, Deserialize, Clone)]+pub struct ReportTemplate {+ pub id: String,+ pub name: String,+ pub description: String,+ pub components: Vec<ReportComponent>,+ pub metadata: ReportMetadata,+ pub styles: ReportStyles,+}++#[derive(Debug, Serialize)]+pub struct ReportGenerationResult {+ pub success: bool,+ pub output_path: Option<String>,+ pub file_size: Option<u64>,+ pub error: Option<String>,}-/// Generate PDF from report template+/// Generate PDF from report template using Rust printpdf library#[tauri::command]pub async fn generate_report_pdf(- app: tauri::AppHandle,template_json: String,output_path: String,) -> Result<String, String> {- let args = vec!["generate_pdf".to_string(), template_json, output_path];- execute_python_command(&app, "financial_report_generator.py", &args)+ // Parse template+ let template: ReportTemplate = match serde_json::from_str(&template_json) {+ Ok(t) => t,+ Err(e) => {+ let result = ReportGenerationResult {+ success: false,+ output_path: None,+ file_size: None,+ error: Some(format!("Failed to parse template: {}", e)),+ };+ return Ok(serde_json::to_string(&result).unwrap());+ }+ };++ // Generate PDF+ match generate_pdf_document(&template, &output_path) {+ Ok(file_size) => {+ let result = ReportGenerationResult {+ success: true,+ output_path: Some(output_path),+ file_size: Some(file_size),+ error: None,+ };+ Ok(serde_json::to_string(&result).unwrap())+ }+ Err(e) => {+ let result = ReportGenerationResult {+ success: false,+ output_path: None,+ file_size: None,+ error: Some(e),+ };+ Ok(serde_json::to_string(&result).unwrap())+ }+ }}-/// Create default Jinja2 template+fn generate_pdf_document(template: &ReportTemplate, output_path: &str) -> Result<u64, String> {+ // Create PDF document+ let (doc, page1, layer1) = PdfDocument::new(+ &template.metadata.title.clone().unwrap_or_else(|| "Financial Report".to_string()),+ Mm(210.0), // A4 width+ Mm(297.0), // A4 height+ "Layer 1",+ );++ let current_layer = doc.get_page(page1).get_layer(layer1);++ // Built-in font+ let font = doc.add_builtin_font(BuiltinFont::Helvetica).map_err(|e| format!("Font error: {}", e))?;+ let font_bold = doc.add_builtin_font(BuiltinFont::HelveticaBold).map_err(|e| format!("Font error: {}", e))?;++ let mut y_position = 270.0; // Start from top (A4 height is 297mm)+ let margin_left = 20.0;+ let margin_right = 190.0; // 210 - 20+ let line_height = 7.0;++ // Title+ if let Some(title) = &template.metadata.title {+ current_layer.use_text(+ title,+ 24.0,+ Mm(margin_left),+ Mm(y_position),+ &font_bold,+ );+ y_position -= 12.0;+ }++ // Company+ if let Some(company) = &template.metadata.company {+ current_layer.use_text(+ company,+ 14.0,+ Mm(margin_left),+ Mm(y_position),+ &font,+ );+ y_position -= 8.0;+ }++ // Metadata (Author and Date)+ let mut metadata_line = String::new();+ if let Some(author) = &template.metadata.author {+ metadata_line.push_str(&format!("Author: {} ", author));+ }+ if let Some(date) = &template.metadata.date {+ if !metadata_line.is_empty() {+ metadata_line.push_str("| ");+ }+ metadata_line.push_str(&format!("Date: {}", date));+ }+ if !metadata_line.is_empty() {+ current_layer.use_text(+ &metadata_line,+ 10.0,+ Mm(margin_left),+ Mm(y_position),+ &font,+ );+ y_position -= 10.0;+ }++ // Separator line+ let line_points = vec![+ (Point::new(Mm(margin_left), Mm(y_position)), false),+ (Point::new(Mm(margin_right), Mm(y_position)), false),+ ];+ let line = Line {+ points: line_points,+ is_closed: false,+ };+ current_layer.set_outline_thickness(0.5);+ current_layer.add_line(line);+ y_position -= 10.0;++ // Process components+ for component in &template.components {+ // Check if we need a new page+ if y_position < 30.0 {+ let (new_page, new_layer) = doc.add_page(Mm(210.0), Mm(297.0), "Layer 1");+ let _current_layer = doc.get_page(new_page).get_layer(new_layer);+ y_position = 270.0;+ }++ match component.component_type.as_str() {+ "heading" => {+ if let Some(content) = &component.content {+ if !content.is_empty() {+ current_layer.use_text(+ content,+ 18.0,+ Mm(margin_left),+ Mm(y_position),+ &font_bold,+ );+ y_position -= line_height * 2.0;+ }+ }+ }+ "text" => {+ if let Some(content) = &component.content {+ if !content.is_empty() {+ // Word wrap for long text+ let wrapped_lines = wrap_text(content, 85); // ~85 chars per line for A4+ for line in wrapped_lines {+ if y_position < 30.0 {+ let (new_page, new_layer) = doc.add_page(Mm(210.0), Mm(297.0), "Layer 1");+ let _current_layer = doc.get_page(new_page).get_layer(new_layer);+ y_position = 270.0;+ }+ current_layer.use_text(+ &line,+ 11.0,+ Mm(margin_left),+ Mm(y_position),+ &font,+ );+ y_position -= line_height;+ }+ y_position -= 3.0; // Extra space after paragraph+ }+ }+ }+ "divider" => {+ y_position -= 5.0;+ let line_points = vec![+ (Point::new(Mm(margin_left), Mm(y_position)), false),+ (Point::new(Mm(margin_right), Mm(y_position)), false),+ ];+ let line = Line {+ points: line_points,+ is_closed: false,+ };+ current_layer.set_outline_thickness(0.5);+ current_layer.add_line(line);+ y_position -= 5.0;+ }+ "code" => {+ if let Some(content) = &component.content {+ if !content.is_empty() {+ y_position -= 3.0;+ // Background rectangle for code block+ let _rect = Rect::new(+ Mm(margin_left - 2.0),+ Mm(y_position - (content.lines().count() as f32 * 5.0) + 2.0),+ Mm(margin_right - margin_left + 4.0),+ Mm(content.lines().count() as f32 * 5.0 + 4.0),+ );+ // TODO: Add gray background (requires setting fill color)++ for line in content.lines() {+ if y_position < 30.0 {+ let (new_page, new_layer) = doc.add_page(Mm(210.0), Mm(297.0), "Layer 1");+ let _current_layer = doc.get_page(new_page).get_layer(new_layer);+ y_position = 270.0;+ }+ current_layer.use_text(+ line,+ 9.0,+ Mm(margin_left),+ Mm(y_position),+ &font,+ );+ y_position -= 5.0;+ }+ y_position -= 3.0;+ }+ }+ }+ "table" => {+ // Simple table rendering+ current_layer.use_text(+ "[Table component - detailed tables coming soon]",+ 10.0,+ Mm(margin_left),+ Mm(y_position),+ &font,+ );+ y_position -= line_height * 2.0;+ }+ "chart" => {+ current_layer.use_text(+ "[Chart component - charts coming soon]",+ 10.0,+ Mm(margin_left),+ Mm(y_position),+ &font,+ );+ y_position -= line_height * 2.0;+ }+ "image" => {+ current_layer.use_text(+ "[Image component - images coming soon]",+ 10.0,+ Mm(margin_left),+ Mm(y_position),+ &font,+ );+ y_position -= line_height * 2.0;+ }+ _ => {}+ }+ }++ // Save PDF+ let file = File::create(output_path).map_err(|e| format!("Failed to create file: {}", e))?;+ let mut writer = BufWriter::new(file);+ doc.save(&mut writer).map_err(|e| format!("Failed to save PDF: {}", e))?;++ // Get file size+ let metadata = std::fs::metadata(output_path).map_err(|e| format!("Failed to get file metadata: {}", e))?;+ Ok(metadata.len())+}++fn wrap_text(text: &str, max_width: usize) -> Vec<String> {+ let mut lines = Vec::new();+ let mut current_line = String::new();++ for word in text.split_whitespace() {+ if current_line.len() + word.len() + 1 > max_width {+ if !current_line.is_empty() {+ lines.push(current_line.trim().to_string());+ current_line = String::new();+ }+ }+ if !current_line.is_empty() {+ current_line.push(' ');+ }+ current_line.push_str(word);+ }++ if !current_line.is_empty() {+ lines.push(current_line.trim().to_string());+ }++ if lines.is_empty() {+ lines.push(String::new());+ }++ lines+}++/// Generate HTML from report template (kept for compatibility)#[tauri::command]-pub async fn create_default_report_template(- app: tauri::AppHandle,+pub async fn generate_report_html(+ template_json: String,) -> Result<String, String> {- let args = vec!["create_template".to_string()];- execute_python_command(&app, "financial_report_generator.py", &args)+ // Simple HTML generation as fallback+ let template: ReportTemplate = serde_json::from_str(&template_json)+ .map_err(|e| format!("Failed to parse template: {}", e))?;++ let mut html = format!(+ r#"<!DOCTYPE html>+<html>+<head>+ <meta charset="UTF-8">+ <title>{}</title>+ <style>+ body {{ font-family: Arial, sans-serif; max-width: 800px; margin: 40px auto; padding: 20px; }}+ h1 {{ color: #0066cc; border-bottom: 3px solid #0066cc; padding-bottom: 10px; }}+ h2 {{ color: #0066cc; margin-top: 30px; }}+ .metadata {{ color: #666; font-size: 0.9em; }}+ pre {{ background: #f5f5f5; padding: 15px; border-left: 4px solid #0066cc; }}+ </style>+</head>+<body>+ <h1>{}</h1>+"#,+ template.metadata.title.as_deref().unwrap_or("Report"),+ template.metadata.title.as_deref().unwrap_or("Report")+ );++ if let Some(company) = &template.metadata.company {+ html.push_str(&format!("<p><strong>{}</strong></p>", company));+ }++ let mut meta_parts = Vec::new();+ if let Some(author) = &template.metadata.author {+ meta_parts.push(format!("Author: {}", author));+ }+ if let Some(date) = &template.metadata.date {+ meta_parts.push(format!("Date: {}", date));+ }+ if !meta_parts.is_empty() {+ html.push_str(&format!("<p class=\"metadata\">{}</p>", meta_parts.join(" | ")));+ }++ for component in &template.components {+ match component.component_type.as_str() {+ "heading" => {+ if let Some(content) = &component.content {+ html.push_str(&format!("<h2>{}</h2>", html_escape(content)));+ }+ }+ "text" => {+ if let Some(content) = &component.content {+ html.push_str(&format!("<p>{}</p>", html_escape(content)));+ }+ }+ "divider" => html.push_str("<hr>"),+ "code" => {+ if let Some(content) = &component.content {+ html.push_str(&format!("<pre><code>{}</code></pre>", html_escape(content)));+ }+ }+ _ => {}+ }+ }++ html.push_str("</body></html>");++ let result = serde_json::json!({+ "success": true,+ "html": html,+ "error": null+ });++ Ok(serde_json::to_string(&result).unwrap())+}++fn html_escape(s: &str) -> String {+ s.replace('&', "&")+ .replace('<', "<")+ .replace('>', ">")+ .replace('"', """)+ .replace('\'', "'")+}++/// Create default template (kept for compatibility)+#[tauri::command]+pub async fn create_default_report_template() -> Result<String, String> {+ let result = serde_json::json!({+ "success": true,+ "message": "Using built-in Rust PDF generator",+ "template_path": null+ });+ Ok(serde_json::to_string(&result).unwrap())+}++/// Open folder in file explorer+#[tauri::command]+pub async fn open_folder(path: String) -> Result<(), String> {+ #[cfg(target_os = "windows")]+ {+ std::process::Command::new("explorer")+ .arg(&path)+ .spawn()+ .map_err(|e| format!("Failed to open folder: {}", e))?;+ }++ #[cfg(target_os = "macos")]+ {+ std::process::Command::new("open")+ .arg(&path)+ .spawn()+ .map_err(|e| format!("Failed to open folder: {}", e))?;+ }++ #[cfg(target_os = "linux")]+ {+ std::process::Command::new("xdg-open")+ .arg(&path)+ .spawn()+ .map_err(|e| format!("Failed to open folder: {}", e))?;+ }++ Ok(())}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/technical_analysis.rs b/fincept-terminal-desktop/src-tauri/src/commands/technical_analysis.rsindex 1073439f4..ffa678ee0 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/technical_analysis.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/technical_analysis.rs@@ -108,3 +108,37 @@ pub async fn calculate_indicators_json(}execute_technical_analysis_command(app, "json".to_string(), args).await}++/// Compute all technical indicators from historical OHLCV data+/// This command receives historical data and returns all computed technicals+#[tauri::command]+pub async fn compute_all_technicals(+ app: AppHandle,+ historical_data: String,+) -> Result<String, String> {+ // Get script path for compute_technicals.py+ let script_name = "compute_technicals.py";+ let script_path = get_script_path(&app, script_name)+ .map_err(|e| format!("Failed to locate script: {}", e))?;++ // Verify script exists+ if !script_path.exists() {+ return Err(format!(+ "Compute technicals script not found at: {}",+ script_path.display()+ ));+ }++ // Execute Python command with historical data as argument+ let args = vec![historical_data];+ match execute_python_command(&app, script_name, &args) {+ Ok(output) => {+ // Check if output contains error JSON+ if output.contains("\"success\":false") || output.contains("\"error\"") {+ return Err(output);+ }+ Ok(output)+ }+ Err(e) => Err(format!("Technical computation failed: {}", e)),+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rsindex c953bb442..95bb4b3d0 100644--- a/fincept-terminal-desktop/src-tauri/src/lib.rs+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs@@ -388,6 +388,7 @@ pub fn run() {.manage(MCPState {processes: Mutex::new(HashMap::new()),})+ .manage(commands::backtesting::BacktestingState::default()).invoke_handler(tauri::generate_handler![greet,cleanup_running_workflows,@@ -952,6 +953,7 @@ pub fn run() {commands::technical_analysis::calculate_indicators_yfinance,commands::technical_analysis::calculate_indicators_csv,commands::technical_analysis::calculate_indicators_json,+ commands::technical_analysis::compute_all_technicals,// FiscalData Commandscommands::fiscaldata::execute_fiscaldata_command,commands::fiscaldata::get_fiscaldata_debt_to_penny,@@ -1052,7 +1054,21 @@ pub fn run() {// Report Generator Commandscommands::report_generator::generate_report_html,commands::report_generator::generate_report_pdf,- commands::report_generator::create_default_report_template+ commands::report_generator::create_default_report_template,+ commands::report_generator::open_folder,+ commands::backtesting::execute_lean_cli,+ commands::backtesting::execute_command,+ commands::backtesting::kill_lean_process,+ commands::backtesting::execute_python_backtest,+ commands::backtesting::check_file_exists,+ commands::backtesting::create_directory,+ commands::backtesting::write_file,+ commands::backtesting::read_file,+ // Company News Commands+ commands::company_news::fetch_company_news,+ commands::company_news::fetch_news_by_topic,+ commands::company_news::get_full_article,+ commands::company_news::get_company_news_help]).run(tauri::generate_context!()).expect("error while running tauri application");diff --git a/fincept-terminal-desktop/src/App.tsx b/fincept-terminal-desktop/src/App.tsxindex 11a63de2b..240bd67ef 100644--- a/fincept-terminal-desktop/src/App.tsx+++ b/fincept-terminal-desktop/src/App.tsx@@ -6,6 +6,7 @@ import { useAuth } from './contexts/AuthContext';import { NavigationProvider } from './contexts/NavigationContext';import { ThemeProvider } from './contexts/ThemeContext';import { DataSourceProvider } from './contexts/DataSourceContext';+import { ProviderProvider } from './contexts/ProviderContext';import { setPaymentWindowManager } from './services/paymentApi';import { workflowService } from './services/workflowService';@@ -213,13 +214,15 @@ const App: React.FC = () => {if (session?.authenticated && currentScreen === 'dashboard') {return (<>- <DataSourceProvider>- <ThemeProvider>- <NavigationProvider onNavigate={setCurrentScreen} onSetActiveTab={setActiveTab}>- <DashboardScreen />- </NavigationProvider>- </ThemeProvider>- </DataSourceProvider>+ <ProviderProvider>+ <DataSourceProvider>+ <ThemeProvider>+ <NavigationProvider onNavigate={setCurrentScreen} onSetActiveTab={setActiveTab}>+ <DashboardScreen />+ </NavigationProvider>+ </ThemeProvider>+ </DataSourceProvider>+ </ProviderProvider>{/* In-App Payment Window Overlay */}<PaymentOverlay paymentWindow={paymentWindow} /></>diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsxindex 658740ee6..341564d92 100644--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx@@ -36,7 +36,9 @@ import FyersTab from '@/components/tabs/fyers';import SupportTicketTab from '@/components/tabs/SupportTicketTab';import PolygonEqTab from '@/components/tabs/PolygonEqTab';import KrakenTab from '@/components/tabs/KrakenTab';+import { TradingTab } from '@/components/tabs/TradingTab';import ReportBuilderTab from '@/components/tabs/ReportBuilderTab';+import BacktestingTab from '@/components/tabs/BacktestingTab';import RecordedContextsManager from '@/components/common/RecordedContextsManager';// Dropdown Menu Component@@ -623,6 +625,12 @@ export default function FinxeptTerminal() {>Analytics</TabsTrigger>+ <TabsTrigger+ value="backtesting"+ style={activeTab === 'backtesting' ? tabStyles.active : tabStyles.default}+ >+ Backtesting+ </TabsTrigger><TabsTriggervalue="research"style={activeTab === 'research' ? tabStyles.active : tabStyles.default}@@ -677,6 +685,12 @@ export default function FinxeptTerminal() {>Kraken</TabsTrigger>+ <TabsTrigger+ value="trading"+ style={activeTab === 'trading' ? tabStyles.active : tabStyles.default}+ >+ Trading+ </TabsTrigger><TabsTriggervalue="settings"style={activeTab === 'settings' ? tabStyles.active : tabStyles.default}@@ -713,6 +727,12 @@ export default function FinxeptTerminal() {>Recorded Contexts</TabsTrigger>+ <TabsTrigger+ value="reportbuilder"+ style={activeTab === 'reportbuilder' ? tabStyles.active : tabStyles.default}+ >+ Report Builder+ </TabsTrigger></TabsList></Tabs></div>@@ -812,6 +832,9 @@ export default function FinxeptTerminal() {<TabsContent value="analytics" className="h-full m-0 p-0"><AnalyticsTab /></TabsContent>+ <TabsContent value="backtesting" className="h-full m-0 p-0">+ <BacktestingTab />+ </TabsContent><TabsContent value="research" className="h-full m-0 p-0"><EquityResearchTab /></TabsContent>@@ -839,6 +862,9 @@ export default function FinxeptTerminal() {<TabsContent value="kraken" className="h-full m-0 p-0"><KrakenTab /></TabsContent>+ <TabsContent value="trading" className="h-full m-0 p-0">+ <TradingTab />+ </TabsContent><TabsContent value="settings" className="h-full m-0 p-0"><SettingsTab /></TabsContent>diff --git a/fincept-terminal-desktop/src/components/settings/BacktestingProvidersPanel.tsx b/fincept-terminal-desktop/src/components/settings/BacktestingProvidersPanel.tsxnew file mode 100644index 000000000..e7091920d--- /dev/null+++ b/fincept-terminal-desktop/src/components/settings/BacktestingProvidersPanel.tsx@@ -0,0 +1,670 @@+/**+ * Backtesting Providers Panel+ *+ * Manages backtesting provider configurations in Settings tab.+ * Allows users to register, configure, activate, and test providers.+ */++import React, { useState, useEffect } from 'react';+import {+ Activity,+ Check,+ X,+ Settings,+ PlayCircle,+ RefreshCw,+ AlertCircle,+ CheckCircle,+ Loader,+ Edit,+ Trash2,+ Plus,+} from 'lucide-react';+import { sqliteService, type BacktestingProvider } from '@/services/sqliteService';+import { backtestingRegistry } from '@/services/backtesting/BacktestingProviderRegistry';+import { LeanAdapter } from '@/services/backtesting/adapters/lean';++interface ProviderPanelProps {+ colors: {+ background: string;+ surface: string;+ text: string;+ textSecondary: string;+ border: string;+ accent: string;+ success: string;+ error: string;+ };+}++interface ProviderStatus {+ connected: boolean;+ testing: boolean;+ error?: string;+ message?: string;+}++export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {+ const [providers, setProviders] = useState<BacktestingProvider[]>([]);+ const [loading, setLoading] = useState(true);+ const [statuses, setStatuses] = useState<Record<string, ProviderStatus>>({});+ const [editingProvider, setEditingProvider] = useState<string | null>(null);+ const [showAddForm, setShowAddForm] = useState(false);+ const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);++ // New provider form+ const [newProviderForm, setNewProviderForm] = useState({+ name: 'lean',+ adapter_type: 'LeanAdapter',+ config: JSON.stringify(+ {+ leanCliPath: 'lean',+ projectsPath: './lean_projects',+ dataPath: './lean_data',+ resultsPath: './lean_results',+ environment: 'backtesting',+ },+ null,+ 2+ ),+ });++ useEffect(() => {+ loadProviders();+ registerDefaultProviders();+ }, []);++ /**+ * Register default providers with the registry+ */+ const registerDefaultProviders = () => {+ try {+ // Register Lean adapter+ const leanAdapter = new LeanAdapter();+ backtestingRegistry.registerProvider(leanAdapter);++ console.log('[Backtesting] Registered providers:', backtestingRegistry.listProviders());+ } catch (error) {+ console.error('[Backtesting] Failed to register providers:', error);+ }+ };++ /**+ * Load providers from database+ */+ const loadProviders = async () => {+ try {+ setLoading(true);+ const dbProviders = await sqliteService.getBacktestingProviders();+ setProviders(dbProviders);++ // Initialize statuses+ const initialStatuses: Record<string, ProviderStatus> = {};+ for (const provider of dbProviders) {+ initialStatuses[provider.name] = {+ connected: false,+ testing: false,+ };+ }+ setStatuses(initialStatuses);+ } catch (error) {+ console.error('[Backtesting] Failed to load providers:', error);+ showMessage('error', 'Failed to load providers');+ } finally {+ setLoading(false);+ }+ };++ /**+ * Test connection to provider+ */+ const testConnection = async (provider: BacktestingProvider) => {+ setStatuses((prev) => ({+ ...prev,+ [provider.name]: { ...prev[provider.name], testing: true, error: undefined },+ }));++ try {+ // Get provider from registry+ const registeredProvider = backtestingRegistry.getProvider(provider.name);+ if (!registeredProvider) {+ throw new Error(`Provider "${provider.name}" not registered`);+ }++ // Initialize with config+ const config = JSON.parse(provider.config);+ const initResult = await registeredProvider.initialize(config);++ if (!initResult.success) {+ throw new Error(initResult.error || 'Initialization failed');+ }++ // Test connection+ const testResult = await registeredProvider.testConnection();++ setStatuses((prev) => ({+ ...prev,+ [provider.name]: {+ connected: testResult.success,+ testing: false,+ error: testResult.error,+ message: testResult.message,+ },+ }));++ if (testResult.success) {+ showMessage('success', `${provider.name}: ${testResult.message}`);+ } else {+ showMessage('error', `${provider.name}: ${testResult.error}`);+ }+ } catch (error) {+ setStatuses((prev) => ({+ ...prev,+ [provider.name]: {+ connected: false,+ testing: false,+ error: String(error),+ },+ }));+ showMessage('error', `Connection test failed: ${error}`);+ }+ };++ /**+ * Activate provider+ */+ const activateProvider = async (providerName: string) => {+ try {+ // Set active in database+ await sqliteService.setActiveBacktestingProvider(providerName);++ // Set active in registry+ await backtestingRegistry.setActiveProvider(providerName);++ // Reload providers to update UI+ await loadProviders();++ showMessage('success', `Activated provider: ${providerName}`);+ } catch (error) {+ showMessage('error', `Failed to activate provider: ${error}`);+ }+ };++ /**+ * Save new provider+ */+ const saveNewProvider = async () => {+ try {+ // Validate config JSON+ JSON.parse(newProviderForm.config);++ const newProvider: Omit<BacktestingProvider, 'created_at' | 'updated_at'> = {+ id: crypto.randomUUID(),+ name: newProviderForm.name,+ adapter_type: newProviderForm.adapter_type,+ config: newProviderForm.config,+ enabled: true,+ is_active: false,+ };++ await sqliteService.saveBacktestingProvider(newProvider);+ await loadProviders();+ setShowAddForm(false);+ showMessage('success', 'Provider added successfully');++ // Reset form+ setNewProviderForm({+ name: 'lean',+ adapter_type: 'LeanAdapter',+ config: JSON.stringify(+ {+ leanCliPath: 'lean',+ projectsPath: './lean_projects',+ dataPath: './lean_data',+ resultsPath: './lean_results',+ environment: 'backtesting',+ },+ null,+ 2+ ),+ });+ } catch (error) {+ showMessage('error', `Failed to save provider: ${error}`);+ }+ };++ /**+ * Delete provider+ */+ const deleteProvider = async (providerName: string) => {+ if (!confirm('Are you sure you want to delete this provider?')) return;++ try {+ await sqliteService.deleteBacktestingProvider(providerName);+ await loadProviders();+ showMessage('success', 'Provider deleted');+ } catch (error) {+ showMessage('error', `Failed to delete provider: ${error}`);+ }+ };++ /**+ * Show message+ */+ const showMessage = (type: 'success' | 'error', text: string) => {+ setMessage({ type, text });+ setTimeout(() => setMessage(null), 5000);+ };++ /**+ * Get provider capabilities+ */+ const getProviderCapabilities = (providerName: string) => {+ const provider = backtestingRegistry.getProvider(providerName);+ return provider?.capabilities;+ };++ if (loading) {+ return (+ <div style={{ padding: '20px', color: colors.text }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>+ <Loader size={20} className="animate-spin" />+ <span>Loading providers...</span>+ </div>+ </div>+ );+ }++ return (+ <div style={{ padding: '20px' }}>+ {/* Header */}+ <div style={{ marginBottom: '20px' }}>+ <h2 style={{ color: colors.text, fontSize: '1.5rem', marginBottom: '8px' }}>+ Backtesting Providers+ </h2>+ <p style={{ color: colors.textSecondary, fontSize: '0.9rem' }}>+ Manage backtesting engines. Switch between Lean, Backtrader, and other providers seamlessly.+ </p>+ </div>++ {/* Message Banner */}+ {message && (+ <div+ style={{+ padding: '12px',+ marginBottom: '20px',+ borderRadius: '6px',+ backgroundColor: message.type === 'success' ? colors.success + '20' : colors.error + '20',+ border: `1px solid ${message.type === 'success' ? colors.success : colors.error}`,+ color: message.type === 'success' ? colors.success : colors.error,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ }}+ >+ {message.type === 'success' ? <CheckCircle size={18} /> : <AlertCircle size={18} />}+ <span>{message.text}</span>+ </div>+ )}++ {/* Add Provider Button */}+ <button+ onClick={() => setShowAddForm(!showAddForm)}+ style={{+ padding: '10px 16px',+ marginBottom: '20px',+ backgroundColor: colors.accent,+ color: colors.background,+ border: 'none',+ borderRadius: '6px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ fontWeight: '500',+ }}+ >+ <Plus size={18} />+ Add Provider+ </button>++ {/* Add Provider Form */}+ {showAddForm && (+ <div+ style={{+ marginBottom: '20px',+ padding: '20px',+ backgroundColor: colors.surface,+ border: `1px solid ${colors.border}`,+ borderRadius: '8px',+ }}+ >+ <h3 style={{ color: colors.text, marginBottom: '16px' }}>Add New Provider</h3>++ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>+ <div>+ <label style={{ color: colors.text, display: 'block', marginBottom: '6px' }}>+ Provider Type+ </label>+ <select+ value={newProviderForm.name}+ onChange={(e) => setNewProviderForm({ ...newProviderForm, name: e.target.value })}+ style={{+ width: '100%',+ padding: '8px',+ backgroundColor: colors.background,+ color: colors.text,+ border: `1px solid ${colors.border}`,+ 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>+ </select>+ </div>++ <div>+ <label style={{ color: colors.text, display: 'block', marginBottom: '6px' }}>+ Configuration (JSON)+ </label>+ <textarea+ value={newProviderForm.config}+ onChange={(e) => setNewProviderForm({ ...newProviderForm, config: e.target.value })}+ rows={10}+ style={{+ width: '100%',+ padding: '8px',+ backgroundColor: colors.background,+ color: colors.text,+ border: `1px solid ${colors.border}`,+ borderRadius: '4px',+ fontFamily: 'monospace',+ fontSize: '0.9rem',+ }}+ />+ </div>++ <div style={{ display: 'flex', gap: '10px' }}>+ <button+ onClick={saveNewProvider}+ style={{+ padding: '8px 16px',+ backgroundColor: colors.success,+ color: 'white',+ border: 'none',+ borderRadius: '4px',+ cursor: 'pointer',+ }}+ >+ Save+ </button>+ <button+ onClick={() => setShowAddForm(false)}+ style={{+ padding: '8px 16px',+ backgroundColor: colors.surface,+ color: colors.text,+ border: `1px solid ${colors.border}`,+ borderRadius: '4px',+ cursor: 'pointer',+ }}+ >+ Cancel+ </button>+ </div>+ </div>+ </div>+ )}++ {/* Providers List */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>+ {providers.length === 0 ? (+ <div+ style={{+ padding: '40px',+ textAlign: 'center',+ color: colors.textSecondary,+ backgroundColor: colors.surface,+ border: `1px dashed ${colors.border}`,+ borderRadius: '8px',+ }}+ >+ <Activity size={48} style={{ margin: '0 auto 16px', opacity: 0.5 }} />+ <p>No providers configured</p>+ <p style={{ fontSize: '0.9rem', marginTop: '8px' }}>+ Click "Add Provider" to configure your first backtesting engine+ </p>+ </div>+ ) : (+ providers.map((provider) => {+ const status = statuses[provider.name] || { connected: false, testing: false };+ const capabilities = getProviderCapabilities(provider.name);++ return (+ <div+ key={provider.id}+ style={{+ padding: '20px',+ backgroundColor: colors.surface,+ border: `2px solid ${provider.is_active ? colors.accent : colors.border}`,+ borderRadius: '8px',+ }}+ >+ {/* Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <Activity size={24} style={{ color: colors.accent }} />+ <div>+ <h3 style={{ color: colors.text, margin: 0 }}>{provider.name}</h3>+ <p style={{ color: colors.textSecondary, fontSize: '0.85rem', margin: 0 }}>+ {provider.adapter_type}+ </p>+ </div>+ </div>++ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ {/* Active Badge */}+ {provider.is_active && (+ <span+ style={{+ padding: '4px 12px',+ backgroundColor: colors.success + '20',+ color: colors.success,+ borderRadius: '12px',+ fontSize: '0.85rem',+ fontWeight: '500',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <Check size={14} />+ Active+ </span>+ )}++ {/* Connection Status */}+ {status.connected && (+ <span+ style={{+ padding: '4px 12px',+ backgroundColor: colors.success + '20',+ color: colors.success,+ borderRadius: '12px',+ fontSize: '0.85rem',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}+ >+ <CheckCircle size={14} />+ Connected+ </span>+ )}+ </div>+ </div>++ {/* Capabilities */}+ {capabilities && (+ <div style={{ marginBottom: '12px' }}>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>+ {capabilities.backtesting && (+ <span style={{ ...capabilityBadgeStyle, color: colors.text }}>Backtesting</span>+ )}+ {capabilities.optimization && (+ <span style={{ ...capabilityBadgeStyle, color: colors.text }}>Optimization</span>+ )}+ {capabilities.liveTrading && (+ <span style={{ ...capabilityBadgeStyle, color: colors.text }}>Live Trading</span>+ )}+ {capabilities.research && (+ <span style={{ ...capabilityBadgeStyle, color: colors.text }}>Research</span>+ )}+ </div>+ </div>+ )}++ {/* Status Message */}+ {status.message && (+ <div+ style={{+ padding: '8px 12px',+ marginBottom: '12px',+ backgroundColor: status.connected ? colors.success + '10' : colors.error + '10',+ borderRadius: '4px',+ fontSize: '0.9rem',+ color: status.connected ? colors.success : colors.error,+ }}+ >+ {status.message}+ </div>+ )}++ {/* Error Message */}+ {status.error && (+ <div+ style={{+ padding: '8px 12px',+ marginBottom: '12px',+ backgroundColor: colors.error + '10',+ borderRadius: '4px',+ fontSize: '0.9rem',+ color: colors.error,+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ }}+ >+ <AlertCircle size={16} />+ {status.error}+ </div>+ )}++ {/* Actions */}+ <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>+ <button+ onClick={() => testConnection(provider)}+ disabled={status.testing}+ style={{+ padding: '8px 16px',+ backgroundColor: colors.accent,+ color: colors.background,+ border: 'none',+ borderRadius: '4px',+ cursor: status.testing ? 'not-allowed' : 'pointer',+ opacity: status.testing ? 0.6 : 1,+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ }}+ >+ {status.testing ? (+ <>+ <Loader size={16} className="animate-spin" />+ Testing...+ </>+ ) : (+ <>+ <PlayCircle size={16} />+ Test Connection+ </>+ )}+ </button>++ {!provider.is_active && (+ <button+ onClick={() => activateProvider(provider.name)}+ style={{+ padding: '8px 16px',+ backgroundColor: colors.success,+ color: 'white',+ border: 'none',+ borderRadius: '4px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ }}+ >+ <Check size={16} />+ Activate+ </button>+ )}++ <button+ onClick={() => deleteProvider(provider.name)}+ style={{+ padding: '8px 16px',+ backgroundColor: colors.error,+ color: 'white',+ border: 'none',+ borderRadius: '4px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ }}+ >+ <Trash2 size={16} />+ Delete+ </button>+ </div>+ </div>+ );+ })+ )}+ </div>++ {/* Registry Info */}+ <div+ style={{+ marginTop: '20px',+ padding: '16px',+ backgroundColor: colors.surface,+ border: `1px solid ${colors.border}`,+ borderRadius: '8px',+ }}+ >+ <h4 style={{ color: colors.text, marginBottom: '12px' }}>Provider Registry Status</h4>+ <div style={{ color: colors.textSecondary, fontSize: '0.9rem' }}>+ <p>+ Registered providers: {backtestingRegistry.listProviders().length}+ </p>+ <p>+ Active provider: {backtestingRegistry.getActiveProvider()?.name || 'None'}+ </p>+ </div>+ </div>+ </div>+ );+}++const capabilityBadgeStyle: React.CSSProperties = {+ padding: '4px 8px',+ backgroundColor: 'rgba(255, 255, 255, 0.1)',+ borderRadius: '4px',+ fontSize: '0.8rem',+};diff --git a/fincept-terminal-desktop/src/components/tabs/BacktestingTab.tsx b/fincept-terminal-desktop/src/components/tabs/BacktestingTab.tsxnew file mode 100644index 000000000..dc4d53625--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/BacktestingTab.tsx@@ -0,0 +1,653 @@+/**+ * Backtesting Tab+ *+ * Dedicated interface for creating, running, and analyzing backtests.+ * Features strategy editor, configuration, results display, and history.+ */++import React, { useState, useEffect } from 'react';+import {+ Activity,+ Play,+ Save,+ FolderOpen,+ TrendingUp,+ TrendingDown,+ BarChart3,+ Calendar,+ DollarSign,+ Settings,+ RefreshCw,+ Download,+ Code,+ Eye,+ Loader,+ CheckCircle,+ AlertCircle,+ FileText,+} from 'lucide-react';+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';++type EditorMode = 'code' | 'visual' | 'template';++export default function BacktestingTab() {+ const { colors } = useTerminalTheme();++ // State+ const [editorMode, setEditorMode] = useState<EditorMode>('code');+ const [strategyCode, setStrategyCode] = useState(DEFAULT_STRATEGY_CODE);+ const [strategyName, setStrategyName] = useState('My Strategy');++ // Configuration+ const [config, setConfig] = useState({+ startDate: new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],+ endDate: new Date().toISOString().split('T')[0],+ initialCapital: 100000,+ assets: [{ symbol: 'SPY', assetClass: 'stocks' as const, timeframe: 'daily' as const }],+ });++ // Execution state+ const [isRunning, setIsRunning] = useState(false);+ const [currentResult, setCurrentResult] = useState<BacktestResult | null>(null);+ const [error, setError] = useState<string | null>(null);++ // History+ const [backtestHistory, setBacktestHistory] = useState<BacktestRun[]>([]);+ const [selectedHistoryId, setSelectedHistoryId] = useState<string | null>(null);++ // Provider+ const [activeProvider, setActiveProvider] = useState<string | null>(null);++ useEffect(() => {+ loadBacktestHistory();+ const provider = backtestingRegistry.getActiveProvider();+ setActiveProvider(provider?.name || null);+ }, []);++ const loadBacktestHistory = async () => {+ try {+ const runs = await sqliteService.getBacktestRuns();+ setBacktestHistory(runs);+ } catch (error) {+ console.error('Failed to load backtest history:', error);+ }+ };++ const handleRunBacktest = async () => {+ if (!activeProvider) {+ setError('No backtesting provider active. Please activate a provider in Settings.');+ return;+ }++ setIsRunning(true);+ setError(null);+ setCurrentResult(null);++ try {+ // Build strategy definition+ const strategy: StrategyDefinition = {+ name: strategyName,+ version: '1.0.0',+ description: 'User-created strategy',+ author: 'User',+ type: 'code',+ code: {+ language: 'python',+ source: strategyCode,+ },+ parameters: [],+ requires: {+ dataFeeds: [],+ indicators: [],+ assetClasses: config.assets.map(a => a.assetClass),+ },+ };++ // Build backtest request+ const request: BacktestRequest = {+ strategy,+ startDate: config.startDate,+ endDate: config.endDate,+ initialCapital: config.initialCapital,+ assets: config.assets,+ parameters: {},+ };++ // Run backtest+ const 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();+ } catch (err) {+ setError(String(err));+ console.error('Backtest failed:', err);+ } finally {+ setIsRunning(false);+ }+ };++ const handleLoadHistory = async (runId: string) => {+ const run = backtestHistory.find((r) => r.id === runId);+ if (run && run.results) {+ try {+ const result = JSON.parse(run.results);+ setCurrentResult(result);+ setSelectedHistoryId(runId);++ // Load config if available+ if (run.config) {+ const savedConfig = JSON.parse(run.config);+ setConfig(savedConfig);+ }+ } catch (error) {+ console.error('Failed to load backtest result:', error);+ }+ }+ };++ const formatPercentage = (value: number) => {+ return (value * 100).toFixed(2) + '%';+ };++ const formatCurrency = (value: number) => {+ return '$' + value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });+ };++ return (+ <div style={{+ height: '100%',+ display: 'flex',+ flexDirection: 'column',+ background: colors.background,+ color: colors.text,+ overflow: 'hidden',+ }}>+ {/* Header */}+ <div style={{+ padding: '16px 20px',+ borderBottom: `1px solid ${colors.textMuted}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <Activity size={24} style={{ color: colors.accent }} />+ <div>+ <h1 style={{ margin: 0, fontSize: '1.5rem' }}>Backtesting</h1>+ <p style={{ margin: 0, fontSize: '0.85rem', color: colors.textMuted }}>+ {activeProvider ? `Using ${activeProvider}` : 'No provider active'}+ </p>+ </div>+ </div>++ <div style={{ display: 'flex', gap: '8px' }}>+ <button+ onClick={handleRunBacktest}+ disabled={isRunning || !activeProvider}+ style={{+ padding: '8px 16px',+ background: isRunning || !activeProvider ? colors.panel : colors.accent,+ color: 'white',+ border: 'none',+ borderRadius: '6px',+ cursor: isRunning || !activeProvider ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ fontWeight: '600',+ opacity: isRunning || !activeProvider ? 0.6 : 1,+ }}+ >+ {isRunning ? (+ <>+ <Loader size={16} className="animate-spin" />+ Running...+ </>+ ) : (+ <>+ <Play size={16} />+ Run Backtest+ </>+ )}+ </button>+ </div>+ </div>++ {/* Main Content */}+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>+ {/* Left Panel - Strategy Editor */}+ <div style={{+ width: '40%',+ borderRight: `1px solid ${colors.textMuted}`,+ display: 'flex',+ flexDirection: 'column',+ overflow: 'hidden',+ }}>+ {/* Editor Tabs */}+ <div style={{+ display: 'flex',+ borderBottom: `1px solid ${colors.textMuted}`,+ background: colors.panel,+ }}>+ {(['code', 'visual', 'template'] as EditorMode[]).map((mode) => (+ <button+ key={mode}+ onClick={() => setEditorMode(mode)}+ style={{+ padding: '12px 20px',+ background: editorMode === mode ? colors.background : 'transparent',+ color: editorMode === mode ? colors.text : colors.textMuted,+ border: 'none',+ borderBottom: editorMode === mode ? `2px solid ${colors.accent}` : '2px solid transparent',+ cursor: 'pointer',+ fontSize: '0.9rem',+ fontWeight: editorMode === mode ? '600' : '400',+ textTransform: 'capitalize',+ }}+ >+ {mode}+ </button>+ ))}+ </div>++ {/* Strategy Name */}+ <div style={{ padding: '12px 16px', borderBottom: `1px solid ${colors.textMuted}` }}>+ <input+ type="text"+ value={strategyName}+ onChange={(e) => setStrategyName(e.target.value)}+ placeholder="Strategy Name"+ style={{+ width: '100%',+ padding: '8px 12px',+ background: colors.panel,+ border: `1px solid ${colors.textMuted}`,+ borderRadius: '4px',+ color: colors.text,+ fontSize: '0.9rem',+ }}+ />+ </div>++ {/* Code Editor */}+ {editorMode === 'code' && (+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>+ <div style={{ padding: '12px 16px', background: colors.panel, borderBottom: `1px solid ${colors.textMuted}` }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '0.85rem' }}>+ <Code size={14} />+ <span>Python Strategy Code</span>+ </div>+ </div>+ <textarea+ value={strategyCode}+ onChange={(e) => setStrategyCode(e.target.value)}+ style={{+ flex: 1,+ padding: '16px',+ background: colors.background,+ color: colors.text,+ border: 'none',+ fontFamily: 'Consolas, Monaco, monospace',+ fontSize: '0.85rem',+ resize: 'none',+ outline: 'none',+ }}+ spellCheck={false}+ />+ </div>+ )}++ {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>+ </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>+ </div>+ )}++ {/* Configuration Panel */}+ <div style={{+ padding: '16px',+ borderTop: `1px solid ${colors.textMuted}`,+ background: colors.panel,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>+ <Settings size={16} />+ <span style={{ fontWeight: '600' }}>Configuration</span>+ </div>++ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>+ <div>+ <label style={{ display: 'block', fontSize: '0.85rem', marginBottom: '4px', color: colors.textMuted }}>+ Start Date+ </label>+ <input+ type="date"+ value={config.startDate}+ onChange={(e) => setConfig({ ...config, startDate: 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>+ <label style={{ display: 'block', fontSize: '0.85rem', marginBottom: '4px', color: colors.textMuted }}>+ End Date+ </label>+ <input+ type="date"+ value={config.endDate}+ onChange={(e) => setConfig({ ...config, endDate: 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 style={{ gridColumn: '1 / -1' }}>+ <label style={{ display: 'block', fontSize: '0.85rem', marginBottom: '4px', color: colors.textMuted }}>+ Initial Capital+ </label>+ <input+ type="number"+ value={config.initialCapital}+ onChange={(e) => setConfig({ ...config, initialCapital: Number(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>+ </div>+ </div>++ {/* Right Panel - Results */}+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>+ {/* Results Tabs */}+ <div style={{+ display: 'flex',+ borderBottom: `1px solid ${colors.textMuted}`,+ background: colors.panel,+ }}>+ <button+ style={{+ padding: '12px 20px',+ background: colors.background,+ color: colors.text,+ border: 'none',+ borderBottom: `2px solid ${colors.accent}`,+ cursor: 'pointer',+ fontSize: '0.9rem',+ fontWeight: '600',+ }}+ >+ Results+ </button>+ <button+ style={{+ padding: '12px 20px',+ background: 'transparent',+ color: colors.textMuted,+ border: 'none',+ borderBottom: '2px solid transparent',+ cursor: 'pointer',+ fontSize: '0.9rem',+ }}+ >+ History+ </button>+ </div>++ {/* Results Content */}+ <div style={{ flex: 1, overflow: 'auto', padding: '20px' }}>+ {error && (+ <div style={{+ padding: '16px',+ background: colors.alert + '20',+ border: `1px solid ${colors.alert}`,+ borderRadius: '6px',+ marginBottom: '20px',+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ }}>+ <AlertCircle size={20} color={colors.alert} />+ <div>+ <div style={{ fontWeight: '600', marginBottom: '4px' }}>Backtest Failed</div>+ <div style={{ fontSize: '0.85rem', color: colors.textMuted }}>{error}</div>+ </div>+ </div>+ )}++ {currentResult && currentResult.status === 'completed' && (+ <div>+ {/* Performance Metrics */}+ <div style={{ marginBottom: '24px' }}>+ <h3 style={{ fontSize: '1.1rem', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '8px' }}>+ <TrendingUp size={18} />+ Performance Metrics+ </h3>++ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '12px' }}>+ {[+ { label: 'Total Return', value: formatPercentage(currentResult.performance.totalReturn), positive: currentResult.performance.totalReturn > 0 },+ { label: 'Annualized Return', value: formatPercentage(currentResult.performance.annualizedReturn), positive: currentResult.performance.annualizedReturn > 0 },+ { label: 'Sharpe Ratio', value: currentResult.performance.sharpeRatio.toFixed(2), positive: currentResult.performance.sharpeRatio > 0 },+ { label: 'Max Drawdown', value: formatPercentage(currentResult.performance.maxDrawdown), positive: false },+ { label: 'Win Rate', value: formatPercentage(currentResult.performance.winRate), positive: true },+ { label: 'Total Trades', value: currentResult.performance.totalTrades.toString(), positive: true },+ ].map((metric) => (+ <div key={metric.label} style={{+ padding: '16px',+ background: colors.panel,+ border: `1px solid ${colors.textMuted}`,+ borderRadius: '6px',+ }}>+ <div style={{ fontSize: '0.85rem', color: colors.textMuted, marginBottom: '4px' }}>+ {metric.label}+ </div>+ <div style={{+ fontSize: '1.5rem',+ fontWeight: 'bold',+ color: metric.positive ? colors.success : colors.alert,+ }}>+ {metric.value}+ </div>+ </div>+ ))}+ </div>+ </div>++ {/* Statistics */}+ <div style={{ marginBottom: '24px' }}>+ <h3 style={{ fontSize: '1.1rem', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '8px' }}>+ <BarChart3 size={18} />+ Statistics+ </h3>++ <div style={{+ padding: '16px',+ background: colors.panel,+ border: `1px solid ${colors.textMuted}`,+ borderRadius: '6px',+ }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', fontSize: '0.9rem' }}>+ <div>+ <span style={{ color: colors.textMuted }}>Initial Capital:</span>+ <span style={{ float: 'right', fontWeight: '600' }}>+ {formatCurrency(currentResult.statistics.initialCapital)}+ </span>+ </div>+ <div>+ <span style={{ color: colors.textMuted }}>Final Capital:</span>+ <span style={{ float: 'right', fontWeight: '600' }}>+ {formatCurrency(currentResult.statistics.finalCapital)}+ </span>+ </div>+ <div>+ <span style={{ color: colors.textMuted }}>Total Fees:</span>+ <span style={{ float: 'right', fontWeight: '600' }}>+ {formatCurrency(currentResult.statistics.totalFees)}+ </span>+ </div>+ <div>+ <span style={{ color: colors.textMuted }}>Total Trades:</span>+ <span style={{ float: 'right', fontWeight: '600' }}>+ {currentResult.statistics.totalTrades}+ </span>+ </div>+ </div>+ </div>+ </div>++ {/* Success Badge */}+ <div style={{+ padding: '12px',+ background: colors.success + '20',+ border: `1px solid ${colors.success}`,+ borderRadius: '6px',+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ }}>+ <CheckCircle size={20} color={colors.success} />+ <span>Backtest completed successfully</span>+ </div>+ </div>+ )}++ {!currentResult && !error && !isRunning && (+ <div style={{+ height: '100%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: colors.textMuted,+ }}>+ <div style={{ textAlign: 'center' }}>+ <Activity size={64} style={{ opacity: 0.3, margin: '0 auto 20px' }} />+ <p>No backtest results yet</p>+ <p style={{ fontSize: '0.85rem' }}>Configure your strategy and click "Run Backtest"</p>+ </div>+ </div>+ )}+ </div>+ </div>+ </div>++ {/* Footer / Status Bar */}+ <div style={{+ borderTop: `1px solid ${colors.textMuted}`,+ backgroundColor: colors.panel,+ padding: '4px 12px',+ fontSize: '10px',+ color: colors.textMuted,+ flexShrink: 0+ }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <div style={{ display: 'flex', gap: '16px' }}>+ <span>Backtesting System v1.0 | Strategy testing and optimization platform</span>+ <span>+ {activeProvider ? `Provider: ${activeProvider}` : 'No provider active'} |+ {backtestHistory.length > 0 ? ` History: ${backtestHistory.length} runs` : ' No backtest history'}+ </span>+ </div>+ <div style={{ display: 'flex', gap: '16px' }}>+ {currentResult && currentResult.status === 'completed' && (+ <>+ <span>Total Return: {formatPercentage(currentResult.performance.totalReturn)}</span>+ <span>Sharpe: {currentResult.performance.sharpeRatio.toFixed(2)}</span>+ <span>Max DD: {formatPercentage(currentResult.performance.maxDrawdown)}</span>+ </>+ )}+ <span style={{ color: isRunning ? colors.warning : colors.secondary }}>+ {isRunning ? 'RUNNING...' : 'READY'}+ </span>+ </div>+ </div>+ </div>+ </div>+ );+}++const DEFAULT_STRATEGY_CODE = `# 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/components/tabs/ChatTab.tsx b/fincept-terminal-desktop/src/components/tabs/ChatTab.tsxindex 14f1b6980..e920481e6 100644--- a/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx@@ -42,6 +42,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {const messagesEndRef = useRef<HTMLDivElement>(null);const sessionsListRef = useRef<HTMLDivElement>(null);+ const streamedContentRef = useRef<string>(''); // Track accumulated streaming content// Check if current provider supports MCP toolsconst providerSupportsMCP = () => {@@ -355,12 +356,24 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {// Prepend linked contexts to the conversationif (linkedContexts.length > 0) {+ console.log('[ChatTab] 🔗 Active contexts linked:', linkedContexts.length);const contextIds = linkedContexts.map(ctx => ctx.id);+ console.log('[ChatTab] 📋 Context IDs:', contextIds);+const contextData = await contextRecorderService.formatMultipleContexts(contextIds, 'markdown');- conversationHistory.unshift({- role: 'system',+ console.log('[ChatTab] 📊 Formatted context data length:', contextData.length, 'characters');+ console.log('[ChatTab] 📝 Context data preview (first 500 chars):\n', contextData.substring(0, 500));++ const systemMessage: APIMessage = {+ role: 'system' as const,content: `The following recorded data contexts are provided for your reference:\n\n${contextData}\n\n---\n\nPlease use this information to help answer the user's questions.`- });+ };++ conversationHistory.unshift(systemMessage);+ console.log('[ChatTab] ✅ System message with context added to conversation');+ console.log('[ChatTab] 📤 Total conversation history length:', conversationHistory.length);+ } else {+ console.log('[ChatTab] ℹ️ No active contexts linked');}// Get MCP tools if available using the unified service@@ -372,6 +385,9 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {// MCP tools not available}+ // Reset the ref before starting new stream+ streamedContentRef.current = '';+// Call LLM API with tools if availableconst response = mcpTools.length > 0? await llmApiService.chatWithTools(@@ -380,6 +396,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {mcpTools,(chunk: string, done: boolean) => {if (!done) {+ streamedContentRef.current += chunk;flushSync(() => {setStreamingContent(prev => prev + chunk);});@@ -407,6 +424,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {conversationHistory,(chunk: string, done: boolean) => {if (!done) {+ streamedContentRef.current += chunk;flushSync(() => {setStreamingContent(prev => prev + chunk);});@@ -431,9 +449,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {setStreamingContent('');setSystemStatus(`ERROR: ${response.error}`);} else {- // Make sure we have content to save- const contentToSave = response.content || streamingContent || '(No response generated)';- console.log('[Chat] Saving AI response, length:', contentToSave.length);+ // Use the ref which contains all streamed content, fallback to response.content+ const contentToSave = response.content || streamedContentRef.current || '(No response generated)';const aiMessage = await sqliteService.addChatMessage({session_uuid: currentSessionUuid,@@ -447,6 +464,8 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {setMessages(prev => [...prev, aiMessage]);setIsTyping(false);setStreamingContent('');+ // Clear the ref for next message+ streamedContentRef.current = '';}// Reload sessions and statisticsdiff --git a/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx b/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsxindex cc98c3508..e744854c6 100644--- a/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx@@ -115,7 +115,7 @@ const EquityResearchTab: React.FC = () => {const [loading, setLoading] = useState(false);const [chartPeriod, setChartPeriod] = useState<'1M' | '3M' | '6M' | '1Y' | '5Y'>('6M');const [currentTime, setCurrentTime] = useState(new Date());- const [activeTab, setActiveTab] = useState<'overview' | 'financials' | 'analysis'>('overview');+ const [activeTab, setActiveTab] = useState<'overview' | 'financials' | 'analysis' | 'technicals' | 'news'>('overview');const [fontSize, setFontSize] = useState(12);const [selectedMetrics, setSelectedMetrics] = useState<string[]>(['Total Revenue', 'Gross Profit', 'Operating Income', 'Net Income', 'EBITDA', 'Basic EPS', 'Diluted EPS']);const [showYearsCount, setShowYearsCount] = useState(4);@@ -125,6 +125,14 @@ const EquityResearchTab: React.FC = () => {const [chart2Metrics, setChart2Metrics] = useState<string[]>(['Net Income', 'Operating Income']);const [chart3Metrics, setChart3Metrics] = useState<string[]>(['EBITDA']);+ // Technicals state+ const [technicalsData, setTechnicalsData] = useState<any>(null);+ const [technicalsLoading, setTechnicalsLoading] = useState(false);++ // News state+ const [newsData, setNewsData] = useState<any>(null);+ const [newsLoading, setNewsLoading] = useState(false);+const chartContainerRef = useRef<HTMLDivElement>(null);const chartRef = useRef<any>(null);const candlestickSeriesRef = useRef<any>(null);@@ -481,11 +489,55 @@ const EquityResearchTab: React.FC = () => {}}, [financials, activeTab, chart1Metrics, chart2Metrics, chart3Metrics]);+ // Compute technicals from historical data+ const computeTechnicals = async (historical: HistoricalData[]) => {+ setTechnicalsLoading(true);+ try {+ // Convert historical data to format expected by Python script+ const historicalJson = JSON.stringify(historical.map(d => ({+ timestamp: d.timestamp,+ open: d.open,+ high: d.high,+ low: d.low,+ close: d.close,+ volume: d.volume+ })));++ const response: any = await invoke('compute_all_technicals', {+ historicalData: historicalJson+ });++ console.log('Technicals response:', response);++ if (typeof response === 'string') {+ const parsed = JSON.parse(response);+ if (parsed.success && parsed.data) {+ setTechnicalsData(parsed);+ } else {+ console.error('Error computing technicals:', parsed.error);+ }+ } else if (response.success && response.data) {+ setTechnicalsData(response);+ }+ } catch (error) {+ console.error('Error computing technicals:', error);+ } finally {+ setTechnicalsLoading(false);+ }+ };+// Load initial datauseEffect(() => {fetchStockData(currentSymbol);}, [currentSymbol, chartPeriod]);+ // Compute technicals when historical data changes+ useEffect(() => {+ if (historicalData.length > 0) {+ computeTechnicals(historicalData);+ }+ }, [historicalData]);+const handleSearch = () => {if (searchSymbol.trim()) {setCurrentSymbol(searchSymbol.trim().toUpperCase());@@ -549,7 +601,7 @@ const EquityResearchTab: React.FC = () => {return (<div style={{- height: '100vh',+ height: '100%',width: '100%',backgroundColor: COLORS.DARK_BG,color: COLORS.WHITE,@@ -558,7 +610,6 @@ const EquityResearchTab: React.FC = () => {flexDirection: 'column',fontSize: '11px',overflow: 'hidden',- position: 'relative',}}>{/* Header */}<div style={{@@ -621,6 +672,7 @@ const EquityResearchTab: React.FC = () => {scrollbarColor: 'rgba(120, 120, 120, 0.3) transparent',scrollbarWidth: 'thin',minHeight: 0,+ backgroundColor: COLORS.DARK_BG,}} className="custom-scrollbar">{/* Stock Header with Price */}@@ -682,7 +734,7 @@ const EquityResearchTab: React.FC = () => {display: 'flex',gap: '1px',}}>- {(['overview', 'financials', 'analysis'] as const).map((tab) => (+ {(['overview', 'financials', 'analysis', 'technicals', 'news'] as const).map((tab) => (<buttonkey={tab}onClick={() => setActiveTab(tab)}@@ -1648,20 +1700,219 @@ const EquityResearchTab: React.FC = () => {</div></div>)}++ {/* Technicals Tab */}+ {activeTab === 'technicals' && (+ <div style={{ padding: '8px' }}>+ {technicalsLoading ? (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '400px',+ gap: '16px',+ }}>+ <div style={{ color: COLORS.YELLOW, fontSize: '14px', fontWeight: 'bold' }}>+ ⏳ COMPUTING TECHNICAL INDICATORS...+ </div>+ <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>+ Analyzing {historicalData.length} data points+ </div>+ </div>+ ) : !technicalsData ? (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '400px',+ gap: '16px',+ }}>+ <div style={{ color: COLORS.RED, fontSize: '14px', fontWeight: 'bold' }}>+ ⚠️ NO TECHNICAL DATA AVAILABLE+ </div>+ <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>+ Please wait for historical data to load+ </div>+ </div>+ ) : (+ <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '8px', height: 'calc(100vh - 280px)' }}>+ {/* Left Side - Charts */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', overflow: 'auto' }} className="custom-scrollbar">+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '12px',+ }}>+ <div style={{ color: COLORS.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>+ TECHNICAL INDICATORS - CHARTS (Coming Soon)+ </div>+ <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>+ Interactive charts for RSI, MACD, Bollinger Bands, and other indicators will be displayed here.+ </div>+ </div>+ </div>++ {/* Right Side - Values */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', overflow: 'auto' }} className="custom-scrollbar">+ {/* Trend Indicators */}+ {technicalsData.indicator_columns?.trend && (+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '8px',+ }}>+ <div style={{ color: COLORS.CYAN, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ TREND INDICATORS+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: '9px' }}>+ {technicalsData.indicator_columns.trend.slice(0, 10).map((indicator: string) => {+ const latestValue = technicalsData.data[technicalsData.data.length - 1]?.[indicator];+ return (+ <div key={indicator} style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0' }}>+ <span style={{ color: COLORS.GRAY }}>{indicator.toUpperCase()}:</span>+ <span style={{ color: COLORS.WHITE }}>{latestValue != null ? formatNumber(latestValue, 4) : 'N/A'}</span>+ </div>+ );+ })}+ </div>+ </div>+ )}++ {/* Momentum Indicators */}+ {technicalsData.indicator_columns?.momentum && (+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '8px',+ }}>+ <div style={{ color: COLORS.GREEN, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ MOMENTUM INDICATORS+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: '9px' }}>+ {technicalsData.indicator_columns.momentum.slice(0, 10).map((indicator: string) => {+ const latestValue = technicalsData.data[technicalsData.data.length - 1]?.[indicator];+ return (+ <div key={indicator} style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0' }}>+ <span style={{ color: COLORS.GRAY }}>{indicator.toUpperCase()}:</span>+ <span style={{ color: COLORS.WHITE }}>{latestValue != null ? formatNumber(latestValue, 4) : 'N/A'}</span>+ </div>+ );+ })}+ </div>+ </div>+ )}++ {/* Volatility Indicators */}+ {technicalsData.indicator_columns?.volatility && (+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '8px',+ }}>+ <div style={{ color: COLORS.YELLOW, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ VOLATILITY INDICATORS+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: '9px' }}>+ {technicalsData.indicator_columns.volatility.slice(0, 10).map((indicator: string) => {+ const latestValue = technicalsData.data[technicalsData.data.length - 1]?.[indicator];+ return (+ <div key={indicator} style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0' }}>+ <span style={{ color: COLORS.GRAY }}>{indicator.toUpperCase()}:</span>+ <span style={{ color: COLORS.WHITE }}>{latestValue != null ? formatNumber(latestValue, 4) : 'N/A'}</span>+ </div>+ );+ })}+ </div>+ </div>+ )}++ {/* Volume Indicators */}+ {technicalsData.indicator_columns?.volume && (+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '8px',+ }}>+ <div style={{ color: COLORS.BLUE, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ VOLUME INDICATORS+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: '9px' }}>+ {technicalsData.indicator_columns.volume.map((indicator: string) => {+ const latestValue = technicalsData.data[technicalsData.data.length - 1]?.[indicator];+ return (+ <div key={indicator} style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0' }}>+ <span style={{ color: COLORS.GRAY }}>{indicator.toUpperCase()}:</span>+ <span style={{ color: COLORS.WHITE }}>{latestValue != null ? formatNumber(latestValue, 4) : 'N/A'}</span>+ </div>+ );+ })}+ </div>+ </div>+ )}++ {/* Others Indicators */}+ {technicalsData.indicator_columns?.others && (+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '8px',+ }}>+ <div style={{ color: COLORS.MAGENTA, fontSize: '11px', fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ RETURN METRICS+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: '9px' }}>+ {technicalsData.indicator_columns.others.map((indicator: string) => {+ const latestValue = technicalsData.data[technicalsData.data.length - 1]?.[indicator];+ return (+ <div key={indicator} style={{ display: 'flex', justifyContent: 'space-between', padding: '2px 0' }}>+ <span style={{ color: COLORS.GRAY }}>{indicator.toUpperCase()}:</span>+ <span style={{ color: COLORS.WHITE }}>{latestValue != null ? formatNumber(latestValue, 6) : 'N/A'}</span>+ </div>+ );+ })}+ </div>+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ )}</div>- {/* Status Bar */}+ {/* Footer / Status Bar */}<div style={{borderTop: `1px solid ${COLORS.BORDER}`,backgroundColor: COLORS.PANEL_BG,- padding: '3px 12px',- fontSize: '9px',+ padding: '4px 12px',+ fontSize: '10px',color: COLORS.GRAY,flexShrink: 0,}}>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span>Fincept Equity Research Terminal | Real-time Data via YFinance | Powered by Rust + React</span>- <span>{currentSymbol} | {stockInfo?.exchange || 'N/A'} | {currentTime.toLocaleString()}</span>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <div style={{ display: 'flex', gap: '16px' }}>+ <span>Equity Research Terminal v1.0 | Real-time data analysis and company fundamentals</span>+ <span>Data Source: YFinance</span>+ </div>+ <div style={{ display: 'flex', gap: '16px' }}>+ <span style={{ color: COLORS.CYAN, fontWeight: 'bold' }}>{currentSymbol}</span>+ {stockInfo?.exchange && <span>{stockInfo.exchange}</span>}+ {currentPrice > 0 && (+ <>+ <span>Price: ${currentPrice.toFixed(2)}</span>+ {priceChange !== 0 && (+ <span style={{ color: priceChange >= 0 ? COLORS.GREEN : COLORS.RED }}>+ {priceChange >= 0 ? '▲' : '▼'} {Math.abs(priceChangePercent).toFixed(2)}%+ </span>+ )}+ </>+ )}+ <span style={{ color: loading ? COLORS.YELLOW : COLORS.GREEN }}>+ {loading ? 'LOADING...' : 'READY'}+ </span>+ </div></div></div>diff --git a/fincept-terminal-desktop/src/components/tabs/MarketplaceTab.tsx b/fincept-terminal-desktop/src/components/tabs/MarketplaceTab.tsxindex 05ceceb66..e934b722a 100644--- a/fincept-terminal-desktop/src/components/tabs/MarketplaceTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/MarketplaceTab.tsx@@ -3,6 +3,25 @@ import { useAuth } from '@/contexts/AuthContext';import { MarketplaceApiService, Dataset } from '@/services/marketplaceApi';import { useTerminalTheme } from '@/contexts/ThemeContext';+interface PricingTier {+ tier: string;+ price_credits: number;+ description: string;+ features?: string[];+}++interface RevenueAnalytics {+ total_revenue: number;+ total_transactions: number;+ revenue_by_tier?: Record<string, number>;+ top_datasets?: Array<{+ id: number;+ title: string;+ downloads: number;+ revenue: number;+ }>;+}+interface MarketProduct {id: string;type: 'DATA' | 'ALGO' | 'API' | 'MODEL' | 'SIGNAL' | 'PLUGIN';diff --git a/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx b/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsxindex 3d14dce50..92488863d 100644--- a/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx@@ -1,36 +1,75 @@-import React, { useState, useCallback, useRef } from 'react';+import React, { useState, useCallback, useEffect, useRef } from 'react';import {FileText,Download,Save,- Layout,Type,BarChart3,Table,Image as ImageIcon,- Plus,Trash2,- Eye,- Settings,Copy,AlignLeft,- Grid,- Layers,- Code+ Code,+ Minus,+ FolderOpen,+ Plus,+ Edit2,+ Move,+ Settings as SettingsIcon,+ X,+ Columns as ColumnsIcon,+ Layout,+ BookOpen,+ FileX,+ Bold,+ Italic,+ Bot,+ Send,+ User,+ Sparkles,+ ChevronDown} from 'lucide-react';import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragEndEvent } from '@dnd-kit/core';import { arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';import { CSS } from '@dnd-kit/utilities';import { reportService, ReportTemplate, ReportComponent } from '@/services/reportService';-import { save } from '@tauri-apps/plugin-dialog';+import { save, open } from '@tauri-apps/plugin-dialog';+import { invoke } from '@tauri-apps/api/core';import { toast } from 'sonner';+import { useTerminalTheme } from '@/contexts/ThemeContext';+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';+import { Button } from '@/components/ui/button';+import { llmApiService, ChatMessage as APIMessage } from '@/services/llmApi';+import { sqliteService } from '@/services/sqliteService';+import MarkdownRenderer from '../common/MarkdownRenderer';++// Bloomberg color palette+const BLOOMBERG_COLORS = {+ ORANGE: '#FFA500',+ WHITE: '#FFFFFF',+ BLACK: '#000000',+ DARK_BG: '#0a0a0a',+ PANEL_BG: '#1a1a1a',+ BORDER: '#333333',+ HOVER: '#2a2a2a',+ TEXT_PRIMARY: '#FFFFFF',+ TEXT_SECONDARY: '#999999',+};// Sortable component wrapper-function SortableComponent({ component, onEdit, onDelete, onDuplicate }: {+function SortableComponent({+ component,+ isSelected,+ onClick,+ onDelete,+ onDuplicate+}: {component: ReportComponent;- onEdit: (id: string) => void;- onDelete: (id: string) => void;- onDuplicate: (id: string) => void;+ isSelected: boolean;+ onClick: () => void;+ onDelete: () => void;+ onDuplicate: () => void;}) {const {attributes,@@ -45,118 +84,71 @@ function SortableComponent({ component, onEdit, onDelete, onDuplicate }: {transition,};- const renderComponentPreview = () => {+ const getComponentIcon = () => {switch (component.type) {- case 'heading':- return (- <h2 className={`font-bold text-${component.config.fontSize || '2xl'} text-${component.config.alignment || 'left'}`}>- {component.content || 'Heading'}- </h2>- );- case 'text':- return (- <p className={`text-${component.config.alignment || 'left'}`}>- {component.content || 'Text content goes here...'}- </p>- );- case 'chart':- return (- <div className="border border-gray-600 rounded p-4 bg-gray-800/50">- <BarChart3 className="w-full h-32 text-blue-400" />- <p className="text-center text-sm text-gray-400 mt-2">- {component.config.chartType || 'Chart'} Preview- </p>- </div>- );- case 'table':- return (- <div className="border border-gray-600 rounded overflow-hidden">- <table className="w-full">- <thead className="bg-gray-700">- <tr>- {(component.config.columns || ['Column 1', 'Column 2', 'Column 3']).map((col, idx) => (- <th key={idx} className="px-4 py-2 text-left text-sm">{col}</th>- ))}- </tr>- </thead>- <tbody>- <tr className="border-t border-gray-600">- {(component.config.columns || ['Column 1', 'Column 2', 'Column 3']).map((_, idx) => (- <td key={idx} className="px-4 py-2 text-sm text-gray-400">Sample data</td>- ))}- </tr>- </tbody>- </table>- </div>- );- case 'image':- return (- <div className="border border-gray-600 rounded p-8 bg-gray-800/50 flex items-center justify-center">- <ImageIcon className="w-16 h-16 text-gray-500" />- </div>- );- case 'divider':- return <hr className="border-gray-600" />;- case 'code':- return (- <pre className="bg-gray-900 border border-gray-600 rounded p-4 overflow-x-auto">- <code className="text-sm text-green-400">- {component.content || '# Code block'}- </code>- </pre>- );- default:- return <div className="text-gray-400">Unknown component type</div>;+ case 'heading': return <Type size={14} />;+ case 'text': return <AlignLeft size={14} />;+ case 'chart': return <BarChart3 size={14} />;+ case 'table': return <Table size={14} />;+ case 'image': return <ImageIcon size={14} />;+ case 'code': return <Code size={14} />;+ case 'divider': return <Minus size={14} />;+ default: return <FileText size={14} />;}};+ const getPreviewText = () => {+ if (component.content) {+ return String(component.content).substring(0, 40);+ }+ return `${component.type.charAt(0).toUpperCase() + component.type.slice(1)} component`;+ };+return (<divref={setNodeRef}style={style}- className="bg-gray-800/30 border border-gray-700 rounded-lg p-4 mb-3 hover:border-blue-500 transition-colors group"+ className={`flex items-center justify-between p-2 mb-1 cursor-pointer transition-colors border-l-2 ${+ isSelected+ ? 'bg-[#2a2a2a] border-l-[#FFA500]'+ : 'bg-transparent border-l-transparent hover:bg-[#1a1a1a]'+ }`}+ onClick={onClick}>- <div className="flex items-center justify-between mb-2">- <div className="flex items-center gap-2">- <div {...attributes} {...listeners} className="cursor-move p-1 hover:bg-gray-700 rounded">- <Grid className="w-4 h-4 text-gray-400" />- </div>- <span className="text-sm font-medium capitalize">{component.type}</span>+ <div className="flex items-center gap-2 flex-1 min-w-0">+ <div {...attributes} {...listeners} className="cursor-move text-gray-500 hover:text-[#FFA500]">+ <Move size={14} /></div>- <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">- <button- onClick={() => onEdit(component.id)}- className="p-1 hover:bg-gray-700 rounded"- title="Edit"- >- <Settings className="w-4 h-4" />- </button>- <button- onClick={() => onDuplicate(component.id)}- className="p-1 hover:bg-gray-700 rounded"- title="Duplicate"- >- <Copy className="w-4 h-4" />- </button>- <button- onClick={() => onDelete(component.id)}- className="p-1 hover:bg-red-700 rounded text-red-400"- title="Delete"- >- <Trash2 className="w-4 h-4" />- </button>+ <div className="text-[#FFA500]">+ {getComponentIcon()}</div>+ <span className="text-xs text-gray-400 truncate">{getPreviewText()}</span></div>- <div className="pointer-events-none">- {renderComponentPreview()}+ <div className="flex gap-1">+ <button+ onClick={(e) => { e.stopPropagation(); onDuplicate(); }}+ className="p-1 hover:bg-[#333333] rounded text-gray-400 hover:text-[#FFA500]"+ title="Duplicate"+ >+ <Copy size={12} />+ </button>+ <button+ onClick={(e) => { e.stopPropagation(); onDelete(); }}+ className="p-1 hover:bg-[#333333] rounded text-gray-400 hover:text-red-500"+ title="Delete"+ >+ <Trash2 size={12} />+ </button></div></div>);}const ReportBuilderTab: React.FC = () => {+ const { colors } = useTerminalTheme();+ const [currentTime, setCurrentTime] = useState(new Date());const [template, setTemplate] = useState<ReportTemplate>({- id: 'new-report',+ id: `report-${Date.now()}`,name: 'New Financial Report',description: 'Professional financial research report',components: [],@@ -175,8 +167,26 @@ const ReportBuilderTab: React.FC = () => {});const [selectedComponent, setSelectedComponent] = useState<string | null>(null);- const [showPreview, setShowPreview] = useState(false);const [isGenerating, setIsGenerating] = useState(false);+ const [isSaving, setIsSaving] = useState(false);+ const [showSuccessDialog, setShowSuccessDialog] = useState(false);+ const [generatedPdfPath, setGeneratedPdfPath] = useState<string>('');+ const [pageTheme, setPageTheme] = useState<'classic' | 'modern' | 'geometric' | 'gradient' | 'minimal' | 'pattern'>('classic');+ const [fontFamily, setFontFamily] = useState<string>('Arial, sans-serif');+ const [defaultFontSize, setDefaultFontSize] = useState<number>(11);+ const [isBold, setIsBold] = useState<boolean>(false);+ const [isItalic, setIsItalic] = useState<boolean>(false);+ const [customBgColor, setCustomBgColor] = useState<string>('#ffffff');+ const [showColorPicker, setShowColorPicker] = useState<boolean>(false);++ // AI Chat state+ const [aiMessages, setAiMessages] = useState<{role: string, content: string}[]>([]);+ const [aiInput, setAiInput] = useState('');+ const [isAiTyping, setIsAiTyping] = useState(false);+ const [currentProvider, setCurrentProvider] = useState('ollama');+ const [availableModels, setAvailableModels] = useState<{id: string, name: string, provider: string}[]>([]);+ const [streamingContent, setStreamingContent] = useState('');+ const aiMessagesEndRef = useRef<HTMLDivElement>(null);const sensors = useSensors(useSensor(PointerSensor),@@ -185,31 +195,106 @@ const ReportBuilderTab: React.FC = () => {}));- const addComponent = (type: ReportComponent['type']) => {+ // Update time+ React.useEffect(() => {+ const timer = setInterval(() => setCurrentTime(new Date()), 1000);+ return () => clearInterval(timer);+ }, []);++ // Load available AI models+ useEffect(() => {+ const loadModels = async () => {+ try {+ const configs = await sqliteService.getLLMConfigs();+ const models = configs.map((config: any) => ({+ id: config.config_name,+ name: config.model_name || config.config_name,+ provider: config.provider+ }));+ setAvailableModels(models);++ // Set active provider+ const activeConfig = await sqliteService.getActiveLLMConfig();+ if (activeConfig) {+ setCurrentProvider(activeConfig.provider);+ }+ } catch (error) {+ console.error('Failed to load models:', error);+ }+ };+ loadModels();+ }, []);++ // Auto-scroll AI chat+ useEffect(() => {+ aiMessagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });+ }, [aiMessages, streamingContent]);++ // Get selected component data+ const selectedComp = template.components.find(c => c.id === selectedComponent);++ // Add component+ const addComponent = useCallback((type: ReportComponent['type']) => {const newComponent: ReportComponent = {id: `component-${Date.now()}`,type,- content: '',+ content: (type === 'divider' || type === 'pagebreak' || type === 'coverpage' || type === 'section' || type === 'columns') ? '' :+ type === 'heading' ? 'New Heading' :+ type === 'subheading' ? 'New Subheading' :+ type === 'text' ? 'Enter text here...' : '',config: {- fontSize: type === 'heading' ? '2xl' : 'base',+ fontSize: type === 'heading' ? '2xl' : type === 'subheading' ? 'xl' : 'base',+ fontWeight: type === 'heading' || type === 'subheading' ? 'bold' : 'normal',alignment: 'left',+ ...(type === 'columns' && { columnCount: 2 }),+ ...(type === 'section' && {+ sectionTitle: 'New Section',+ sectionStyle: 'default',+ backgroundColor: '#f8f9fa',+ borderColor: '#FFA500',+ padding: '15px'+ }),+ ...(type === 'coverpage' && {+ subtitle: '',+ backgroundColor: '#0a0a0a',+ }),},+ ...(type === 'columns' || type === 'section' ? { children: [] } : {}),};setTemplate(prev => ({...prev,components: [...prev.components, newComponent],}));- };- const deleteComponent = (id: string) => {+ setSelectedComponent(newComponent.id);+ toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} added`);+ }, []);++ // Update component+ const updateComponent = useCallback((id: string, updates: Partial<ReportComponent>) => {setTemplate(prev => ({...prev,- components: prev.components.filter(c => c.id !== id),+ components: prev.components.map(comp =>+ comp.id === id ? { ...comp, ...updates } : comp+ ),}));- };+ }, []);- const duplicateComponent = (id: string) => {+ // Delete component+ const deleteComponent = useCallback((id: string) => {+ setTemplate(prev => ({+ ...prev,+ components: prev.components.filter(comp => comp.id !== id),+ }));+ if (selectedComponent === id) {+ setSelectedComponent(null);+ }+ toast.success('Component deleted');+ }, [selectedComponent]);++ // Duplicate component+ const duplicateComponent = useCallback((id: string) => {const component = template.components.find(c => c.id === id);if (component) {const newComponent = {@@ -220,17 +305,17 @@ const ReportBuilderTab: React.FC = () => {...prev,components: [...prev.components, newComponent],}));+ toast.success('Component duplicated');}- };+ }, [template.components]);+ // Handle drag endconst handleDragEnd = (event: DragEndEvent) => {const { active, over } = event;-if (over && active.id !== over.id) {setTemplate(prev => {const oldIndex = prev.components.findIndex(c => c.id === active.id);const newIndex = prev.components.findIndex(c => c.id === over.id);-return {...prev,components: arrayMove(prev.components, oldIndex, newIndex),@@ -239,360 +324,1371 @@ const ReportBuilderTab: React.FC = () => {}};- const updateComponent = (id: string, updates: Partial<ReportComponent>) => {- setTemplate(prev => ({- ...prev,- components: prev.components.map(c =>- c.id === id ? { ...c, ...updates } : c- ),- }));+ // Save template+ const saveTemplate = async () => {+ try {+ setIsSaving(true);+ const filePath = await save({+ filters: [{+ name: 'JSON',+ extensions: ['json']+ }],+ defaultPath: `${template.name}.json`+ });++ if (filePath) {+ await reportService.saveTemplate(template);+ toast.success('Template saved successfully');+ }+ } catch (error) {+ console.error('Error saving template:', error);+ toast.error('Failed to save template');+ } finally {+ setIsSaving(false);+ }+ };++ // Load template+ const loadTemplate = async () => {+ try {+ const filePath = await open({+ filters: [{+ name: 'JSON',+ extensions: ['json']+ }],+ multiple: false+ });++ // For now, we'll just load from saved templates in localStorage+ // In the future, could add file system loading+ const templates = await reportService.getTemplates();+ if (templates.length > 0) {+ // Use the first template or show a selection dialog+ setTemplate(templates[0]);+ toast.success('Template loaded successfully');+ } else {+ toast.info('No saved templates found. Use a sample template instead.');+ }+ } catch (error) {+ console.error('Error loading template:', error);+ toast.error('Failed to load template');+ }};- const generatePDF = async () => {- setIsGenerating(true);+ // Generate PDF+ const generatePdf = async () => {try {- // Show file save dialog- const outputPath = await save({+ setIsGenerating(true);++ const filePath = await save({filters: [{name: 'PDF',extensions: ['pdf']}],- defaultPath: `${template.name.replace(/\s+/g, '-')}.pdf`+ defaultPath: `${template.metadata.title || 'report'}.pdf`});- if (!outputPath) {- setIsGenerating(false);+ if (filePath) {+ await invoke('generate_report_pdf', {+ templateJson: JSON.stringify(template),+ outputPath: filePath+ });++ setGeneratedPdfPath(filePath);+ setShowSuccessDialog(true);+ }+ } catch (error) {+ console.error('Error generating PDF:', error);+ toast.error('Failed to generate PDF');+ } finally {+ setIsGenerating(false);+ }+ };++ // Handle show in folder+ const handleShowInFolder = async () => {+ try {+ const folderPath = generatedPdfPath.substring(0, generatedPdfPath.lastIndexOf('\\'));+ await invoke('open_folder', { path: folderPath });+ setShowSuccessDialog(false);+ } catch (error) {+ console.error('Error opening folder:', error);+ toast.error('Failed to open folder');+ }+ };++ // AI Chat - Send message+ const handleAiSendMessage = async () => {+ if (!aiInput.trim()) return;++ const userMessage = { role: 'user', content: aiInput.trim() };+ setAiMessages(prev => [...prev, userMessage]);+ setAiInput('');+ setIsAiTyping(true);+ setStreamingContent('');++ try {+ // Get active LLM config+ const activeConfig = await sqliteService.getActiveLLMConfig();+ if (!activeConfig) {+ setAiMessages(prev => [...prev, {+ role: 'assistant',+ content: 'Please configure your LLM settings first in the Chat tab or Settings.'+ }]);+ setIsAiTyping(false);return;}- // Generate PDF using Jinja2- const result = await reportService.generatePDF(template, outputPath);+ // Add context about the current report+ const contextMessage = `I'm working on a report titled "${template.metadata.title}". ${+ template.components.length > 0+ ? `It has ${template.components.length} components including ${template.components.map(c => c.type).join(', ')}.`+ : 'It\'s empty so far.'+ } The report uses ${fontFamily} font at ${defaultFontSize}pt with ${pageTheme} theme.`;- if (result.success) {- toast.success('PDF generated successfully!', {- description: `Saved to: ${result.output_path}`- });- } else {- toast.error('Failed to generate PDF', {- description: result.error || 'Unknown error'- });+ const conversationHistory: APIMessage[] = [+ { role: 'system', content: `You are a professional writing assistant helping to create financial reports. ${contextMessage}` },+ ...aiMessages.map(msg => ({+ role: msg.role as 'user' | 'assistant',+ content: msg.content+ })),+ { role: 'user', content: userMessage.content }+ ];++ let fullResponse = '';++ const response = await llmApiService.chat(+ userMessage.content,+ conversationHistory,+ (chunk, done) => {+ if (!done) {+ fullResponse += chunk;+ setStreamingContent(fullResponse);+ }+ }+ );++ if (response.error) {+ throw new Error(response.error);}++ fullResponse = response.content;++ setAiMessages(prev => [...prev, {+ role: 'assistant',+ content: fullResponse+ }]);+ setStreamingContent('');} catch (error) {- console.error('Failed to generate PDF:', error);- toast.error('Failed to generate PDF', {- description: error instanceof Error ? error.message : 'Unknown error'- });+ console.error('AI Error:', error);+ setAiMessages(prev => [...prev, {+ role: 'assistant',+ content: 'Sorry, I encountered an error. Please try again.'+ }]);} finally {- setIsGenerating(false);+ setIsAiTyping(false);}};- const saveTemplate = () => {- const json = JSON.stringify(template, null, 2);- const blob = new Blob([json], { type: 'application/json' });- const url = window.URL.createObjectURL(blob);- const a = document.createElement('a');- a.href = url;- a.download = `${template.name.replace(/\s+/g, '-')}.json`;- document.body.appendChild(a);- a.click();- window.URL.revokeObjectURL(url);- document.body.removeChild(a);+ // AI Quick actions+ const handleAiQuickAction = (action: string) => {+ const prompts: Record<string, string> = {+ improve: 'Can you help me improve the content of this report? Suggest better wording and structure.',+ expand: 'Can you help me expand on the current content with more details and insights?',+ summarize: 'Can you help me create a concise executive summary for this report?',+ grammar: 'Can you check the grammar and suggest improvements for professional writing?'+ };++ setAiInput(prompts[action] || '');+ };++ // Get theme background style+ const getThemeBackground = () => {+ switch (pageTheme) {+ case 'modern':+ return {+ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',+ backgroundSize: 'cover',+ color: '#ffffff',+ };+ case 'geometric':+ return {+ backgroundColor: '#ffffff',+ backgroundImage: `+ linear-gradient(30deg, rgba(255,165,0,0.08) 12%, transparent 12.5%, transparent 87%, rgba(255,165,0,0.08) 87.5%, rgba(255,165,0,0.08)),+ linear-gradient(150deg, rgba(255,165,0,0.08) 12%, transparent 12.5%, transparent 87%, rgba(255,165,0,0.08) 87.5%, rgba(255,165,0,0.08)),+ linear-gradient(30deg, rgba(255,165,0,0.05) 12%, transparent 12.5%, transparent 87%, rgba(255,165,0,0.05) 87.5%, rgba(255,165,0,0.05)),+ linear-gradient(150deg, rgba(255,165,0,0.05) 12%, transparent 12.5%, transparent 87%, rgba(255,165,0,0.05) 87.5%, rgba(255,165,0,0.05))+ `,+ backgroundSize: '80px 140px',+ backgroundPosition: '0 0, 0 0, 40px 70px, 40px 70px',+ color: '#000000',+ };+ case 'gradient':+ return {+ background: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%)',+ color: '#ffffff',+ };+ case 'minimal':+ return {+ backgroundColor: '#ffffff',+ backgroundImage: `+ linear-gradient(rgba(200,200,200,0.3) 1px, transparent 1px),+ linear-gradient(90deg, rgba(200,200,200,0.3) 1px, transparent 1px)+ `,+ backgroundSize: '20px 20px',+ color: '#000000',+ };+ case 'pattern':+ return {+ backgroundColor: '#ffffff',+ backgroundImage: `+ repeating-linear-gradient(45deg, transparent, transparent 10px, rgba(255,165,0,0.02) 10px, rgba(255,165,0,0.02) 20px),+ repeating-linear-gradient(-45deg, transparent, transparent 10px, rgba(255,165,0,0.02) 10px, rgba(255,165,0,0.02) 20px),+ radial-gradient(circle at 10% 10%, rgba(255,165,0,0.03) 0%, transparent 50%),+ radial-gradient(circle at 90% 90%, rgba(255,165,0,0.03) 0%, transparent 50%)+ `,+ backgroundSize: 'cover',+ color: '#000000',+ };+ case 'classic':+ default:+ return {+ backgroundColor: customBgColor,+ color: '#000000',+ };+ }};- const selectedComp = selectedComponent- ? template.components.find(c => c.id === selectedComponent)- : null;+ // Handle image upload+ const handleImageUpload = async () => {+ try {+ const selected = await open({+ multiple: false,+ filters: [{+ name: 'Images',+ extensions: ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp']+ }]+ });++ if (selected && typeof selected === 'string' && selectedComp) {+ updateComponent(selectedComp.id, {+ config: { ...selectedComp.config, imageUrl: selected }+ });+ toast.success('Image uploaded');+ }+ } catch (error) {+ toast.error('Failed to upload image');+ }+ };return (- <div className="h-full flex flex-col bg-gray-900 text-white">+ <div className="h-full flex flex-col" style={{ backgroundColor: BLOOMBERG_COLORS.DARK_BG, color: BLOOMBERG_COLORS.TEXT_PRIMARY }}>{/* Header */}- <div className="flex items-center justify-between p-4 border-b border-gray-700">- <div className="flex items-center gap-3">- <FileText className="w-6 h-6 text-blue-400" />- <div>- <h1 className="text-xl font-bold">{template.name}</h1>- <p className="text-sm text-gray-400">{template.description}</p>+ <div className="flex items-center justify-between px-4 py-2 border-b" style={{ borderColor: BLOOMBERG_COLORS.BORDER, backgroundColor: BLOOMBERG_COLORS.PANEL_BG }}>+ <div className="flex items-center gap-4">+ <div className="flex items-center gap-2">+ <FileText className="w-5 h-5" style={{ color: BLOOMBERG_COLORS.ORANGE }} />+ <span className="font-bold text-sm" style={{ color: BLOOMBERG_COLORS.ORANGE }}>REPORT BUILDER</span></div>+ <span className="text-xs" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ {currentTime.toLocaleTimeString()}+ </span></div>- <div className="flex gap-2">+ <div className="flex items-center gap-2"><button- onClick={() => setShowPreview(!showPreview)}- className="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg flex items-center gap-2"+ onClick={loadTemplate}+ className="px-3 py-1 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-1"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}>- <Eye className="w-4 h-4" />- {showPreview ? 'Edit' : 'Preview'}+ <FolderOpen size={14} />+ Load</button><buttononClick={saveTemplate}- className="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg flex items-center gap-2"+ disabled={isSaving}+ className="px-3 py-1 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-1 disabled:opacity-50"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}>- <Save className="w-4 h-4" />- Save Template+ <Save size={14} />+ {isSaving ? 'Saving...' : 'Save'}</button><button- onClick={generatePDF}- disabled={isGenerating}- className="px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg flex items-center gap-2 disabled:opacity-50"+ onClick={generatePdf}+ disabled={isGenerating || template.components.length === 0}+ className="px-3 py-1 text-xs rounded transition-colors flex items-center gap-1 disabled:opacity-50"+ style={{+ backgroundColor: BLOOMBERG_COLORS.ORANGE,+ color: BLOOMBERG_COLORS.BLACK,+ fontWeight: 'bold'+ }}>- <Download className="w-4 h-4" />- {isGenerating ? 'Generating...' : 'Generate PDF'}+ <Download size={14} />+ {isGenerating ? 'Generating...' : 'Export PDF'}</button></div></div>+ {/* Main Content */}<div className="flex-1 flex overflow-hidden">- {/* Component Palette */}- <div className="w-64 border-r border-gray-700 p-4 overflow-y-auto">- <h2 className="text-sm font-semibold mb-3 flex items-center gap-2">- <Layers className="w-4 h-4" />- Components- </h2>- <div className="space-y-2">- <button- onClick={() => addComponent('heading')}- className="w-full px-3 py-2 bg-gray-800 hover:bg-gray-700 rounded flex items-center gap-2 text-sm"- >- <Type className="w-4 h-4" />- Heading- </button>- <button- onClick={() => addComponent('text')}- className="w-full px-3 py-2 bg-gray-800 hover:bg-gray-700 rounded flex items-center gap-2 text-sm"- >- <AlignLeft className="w-4 h-4" />- Text Block- </button>- <button- onClick={() => addComponent('chart')}- className="w-full px-3 py-2 bg-gray-800 hover:bg-gray-700 rounded flex items-center gap-2 text-sm"- >- <BarChart3 className="w-4 h-4" />- Chart- </button>- <button- onClick={() => addComponent('table')}- className="w-full px-3 py-2 bg-gray-800 hover:bg-gray-700 rounded flex items-center gap-2 text-sm"- >- <Table className="w-4 h-4" />- Table- </button>- <button- onClick={() => addComponent('image')}- className="w-full px-3 py-2 bg-gray-800 hover:bg-gray-700 rounded flex items-center gap-2 text-sm"- >- <ImageIcon className="w-4 h-4" />- Image- </button>- <button- onClick={() => addComponent('code')}- className="w-full px-3 py-2 bg-gray-800 hover:bg-gray-700 rounded flex items-center gap-2 text-sm"- >- <Code className="w-4 h-4" />- Code Block- </button>- <button- onClick={() => addComponent('divider')}- className="w-full px-3 py-2 bg-gray-800 hover:bg-gray-700 rounded flex items-center gap-2 text-sm"- >- <Layout className="w-4 h-4" />- Divider- </button>- </div>-- <div className="mt-6">- <h2 className="text-sm font-semibold mb-3">Report Settings</h2>- <div className="space-y-3">- <div>- <label className="text-xs text-gray-400">Title</label>- <input- type="text"- value={template.metadata.title}- onChange={(e) => setTemplate(prev => ({- ...prev,- metadata: { ...prev.metadata, title: e.target.value }- }))}- className="w-full px-2 py-1 bg-gray-800 border border-gray-700 rounded text-sm"- />- </div>- <div>- <label className="text-xs text-gray-400">Author</label>- <input- type="text"- value={template.metadata.author}- onChange={(e) => setTemplate(prev => ({- ...prev,- metadata: { ...prev.metadata, author: e.target.value }- }))}- className="w-full px-2 py-1 bg-gray-800 border border-gray-700 rounded text-sm"- />- </div>- <div>- <label className="text-xs text-gray-400">Company</label>- <input- type="text"- value={template.metadata.company}- onChange={(e) => setTemplate(prev => ({- ...prev,- metadata: { ...prev.metadata, company: e.target.value }- }))}- className="w-full px-2 py-1 bg-gray-800 border border-gray-700 rounded text-sm"- />- </div>- <div>- <label className="text-xs text-gray-400">Page Size</label>- <select- value={template.styles.pageSize}- onChange={(e) => setTemplate(prev => ({- ...prev,- styles: { ...prev.styles, pageSize: e.target.value as any }- }))}- className="w-full px-2 py-1 bg-gray-800 border border-gray-700 rounded text-sm"+ {/* Left Panel - Components */}+ <div className="w-1/5 border-r overflow-y-auto" style={{ borderColor: BLOOMBERG_COLORS.BORDER, backgroundColor: BLOOMBERG_COLORS.PANEL_BG }}>+ <div className="p-3">+ {/* Add Components */}+ <div className="mb-4">+ <h3 className="text-xs font-bold mb-2" style={{ color: BLOOMBERG_COLORS.ORANGE }}>ADD COMPONENTS</h3>+ <div className="space-y-1">+ <button+ onClick={() => addComponent('heading')}+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}>- <option value="A4">A4</option>- <option value="Letter">Letter</option>- <option value="Legal">Legal</option>- </select>+ <Type size={14} />+ Heading+ </button>+ <button+ onClick={() => addComponent('text')}+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ <AlignLeft size={14} />+ Text+ </button>+ <button+ onClick={() => addComponent('chart')}+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ <BarChart3 size={14} />+ Chart+ </button>+ <button+ onClick={() => addComponent('table')}+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ <Table size={14} />+ Table+ </button>+ <button+ onClick={() => addComponent('image')}+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ <ImageIcon size={14} />+ Image+ </button>+ <button+ onClick={() => addComponent('code')}+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ <Code size={14} />+ Code Block+ </button>+ <button+ onClick={() => addComponent('divider')}+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ <Minus size={14} />+ Divider+ </button></div>- <div>- <label className="text-xs text-gray-400">Orientation</label>- <select- value={template.styles.orientation}- onChange={(e) => setTemplate(prev => ({- ...prev,- styles: { ...prev.styles, orientation: e.target.value as any }- }))}- className="w-full px-2 py-1 bg-gray-800 border border-gray-700 rounded text-sm"+ </div>++ {/* Layout Components */}+ <div className="mb-4">+ <h3 className="text-xs font-bold mb-2" style={{ color: BLOOMBERG_COLORS.ORANGE }}>LAYOUT</h3>+ <div className="grid grid-cols-2 gap-1">+ <button+ onClick={() => addComponent('section')}+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ <Layout size={14} />+ <span className="text-[9px]">Section</span>+ </button>+ <button+ onClick={() => addComponent('columns')}+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ <ColumnsIcon size={14} />+ <span className="text-[9px]">Columns</span>+ </button>+ <button+ onClick={() => addComponent('coverpage')}+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}>- <option value="portrait">Portrait</option>- <option value="landscape">Landscape</option>- </select>+ <BookOpen size={14} />+ <span className="text-[9px]">Cover</span>+ </button>+ <button+ onClick={() => addComponent('pagebreak')}+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ <FileX size={14} />+ <span className="text-[9px]">Break</span>+ </button>+ </div>+ </div>++ {/* Settings */}+ <div className="mb-4">+ <h3 className="text-xs font-bold mb-2" style={{ color: BLOOMBERG_COLORS.ORANGE }}>SETTINGS</h3>+ <div className="space-y-2">+ <div>+ <label className="text-[9px] block mb-1" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Page Theme+ </label>+ <select+ value={pageTheme}+ onChange={(e) => setPageTheme(e.target.value as any)}+ className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ <option value="classic">Classic White</option>+ <option value="minimal">Minimal Grid</option>+ <option value="geometric">Geometric Triangles</option>+ <option value="pattern">Diagonal Pattern</option>+ <option value="modern">Modern Gradient (Dark)</option>+ <option value="gradient">Professional Gradient (Dark)</option>+ </select>+ </div>++ {/* Color Picker for Classic Theme */}+ {pageTheme === 'classic' && (+ <div>+ <div className="flex items-center justify-between mb-1">+ <label className="text-[9px]" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Background Color+ </label>+ <button+ onClick={() => setShowColorPicker(!showColorPicker)}+ className="text-[9px] px-2 py-1 rounded hover:bg-[#2a2a2a]"+ style={{ color: BLOOMBERG_COLORS.ORANGE }}+ >+ {showColorPicker ? 'Hide Picker' : 'Show Picker'}+ </button>+ </div>++ {/* Current Color Display */}+ <div className="flex items-center gap-2 mb-2">+ <div+ className="w-8 h-8 rounded border-2 border-[#333333]"+ style={{ backgroundColor: customBgColor }}+ />+ <input+ type="text"+ value={customBgColor}+ onChange={(e) => setCustomBgColor(e.target.value)}+ className="flex-1 px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ placeholder="#ffffff"+ />+ </div>++ {/* Advanced Color Picker */}+ {showColorPicker && (+ <div className="p-3 rounded bg-[#0a0a0a] border border-[#333333] space-y-3">+ {/* Main Gradient Palette */}+ <div>+ <label className="text-[9px] mb-1 block" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Color Palette+ </label>+ <div+ className="w-full h-32 rounded cursor-crosshair border border-[#333333] relative"+ style={{+ background: `+ linear-gradient(to bottom, transparent, black),+ linear-gradient(to right, white, hsl(${customBgColor.startsWith('#') ? 0 : 120}, 100%, 50%))+ `+ }}+ onClick={(e) => {+ const rect = e.currentTarget.getBoundingClientRect();+ const x = e.clientX - rect.left;+ const y = e.clientY - rect.top;+ const percentX = x / rect.width;+ const percentY = y / rect.height;++ // Calculate color based on position+ const hue = percentX * 360;+ const saturation = 100;+ const lightness = 100 - (percentY * 50); // Top is white (100%), bottom is mid-dark (50%)++ const hslToHex = (h: number, s: number, l: number) => {+ l /= 100;+ const a = s * Math.min(l, 1 - l) / 100;+ const f = (n: number) => {+ const k = (n + h / 30) % 12;+ const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);+ return Math.round(255 * color).toString(16).padStart(2, '0');+ };+ return `#${f(0)}${f(8)}${f(4)}`;+ };++ setCustomBgColor(hslToHex(hue, saturation, lightness));+ }}+ >+ {/* Current color indicator */}+ <div+ className="absolute w-3 h-3 border-2 border-white rounded-full shadow-lg pointer-events-none"+ style={{+ left: '50%',+ top: '10%',+ transform: 'translate(-50%, -50%)'+ }}+ />+ </div>+ </div>++ {/* Hue Slider */}+ <div>+ <label className="text-[9px] mb-1 block" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Hue+ </label>+ <div+ className="w-full h-6 rounded cursor-pointer border border-[#333333]"+ style={{+ background: 'linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)'+ }}+ onClick={(e) => {+ const rect = e.currentTarget.getBoundingClientRect();+ const x = e.clientX - rect.left;+ const percent = x / rect.width;+ const hue = Math.round(percent * 360);++ const hslToHex = (h: number, s: number, l: number) => {+ l /= 100;+ const a = s * Math.min(l, 1 - l) / 100;+ const f = (n: number) => {+ const k = (n + h / 30) % 12;+ const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);+ return Math.round(255 * color).toString(16).padStart(2, '0');+ };+ return `#${f(0)}${f(8)}${f(4)}`;+ };++ setCustomBgColor(hslToHex(hue, 100, 50));+ }}+ />+ </div>++ {/* Lightness Slider */}+ <div>+ <label className="text-[9px] mb-1 block" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Lightness+ </label>+ <div+ className="w-full h-6 rounded cursor-pointer border border-[#333333]"+ style={{+ background: 'linear-gradient(to right, #000000, #808080, #ffffff)'+ }}+ onClick={(e) => {+ const rect = e.currentTarget.getBoundingClientRect();+ const x = e.clientX - rect.left;+ const percent = x / rect.width;+ const lightness = Math.round(percent * 100);++ const hslToHex = (h: number, s: number, l: number) => {+ l /= 100;+ const a = s * Math.min(l, 1 - l) / 100;+ const f = (n: number) => {+ const k = (n + h / 30) % 12;+ const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);+ return Math.round(255 * color).toString(16).padStart(2, '0');+ };+ return `#${f(0)}${f(8)}${f(4)}`;+ };++ setCustomBgColor(hslToHex(120, 0, lightness));+ }}+ />+ </div>++ {/* Preset Colors */}+ <div>+ <label className="text-[9px] mb-1 block" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Preset Colors+ </label>+ <div className="grid grid-cols-8 gap-1">+ {[+ '#ffffff', '#f8f9fa', '#e9ecef', '#dee2e6', '#ced4da', '#adb5bd', '#6c757d', '#495057',+ '#fff3cd', '#d1ecf1', '#d4edda', '#f8d7da', '#e2e3e5', '#d6d8db', '#fef5e7', '#ebf5fb',+ '#ff0000', '#ff7f00', '#ffff00', '#00ff00', '#00ffff', '#0000ff', '#8b00ff', '#ff00ff',+ '#fff5f5', '#ffe6e6', '#ffd6cc', '#ffe5cc', '#fff4cc', '#ffffcc', '#f0fff4', '#f0f9ff'+ ].map(color => (+ <button+ key={color}+ onClick={() => setCustomBgColor(color)}+ className={`w-full aspect-square rounded border-2 transition-all hover:scale-110 ${+ customBgColor.toLowerCase() === color.toLowerCase()+ ? 'border-[#FFA500] ring-2 ring-[#FFA500]'+ : 'border-[#333333] hover:border-[#666]'+ }`}+ style={{ backgroundColor: color }}+ title={color}+ />+ ))}+ </div>+ </div>+ </div>+ )}+ </div>+ )}+ <div>+ <label className="text-[9px] block mb-1" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Report Title+ </label>+ <input+ type="text"+ value={template.metadata.title}+ onChange={(e) => setTemplate(prev => ({+ ...prev,+ metadata: { ...prev.metadata, title: e.target.value }+ }))}+ className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ placeholder="Enter report title..."+ />+ </div>+ <div>+ <label className="text-[9px] block mb-1" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Author+ </label>+ <input+ type="text"+ value={template.metadata.author}+ onChange={(e) => setTemplate(prev => ({+ ...prev,+ metadata: { ...prev.metadata, author: e.target.value }+ }))}+ className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ placeholder="Enter author name..."+ />+ </div>+ <div>+ <label className="text-[9px] block mb-1" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Company+ </label>+ <input+ type="text"+ value={template.metadata.company}+ onChange={(e) => setTemplate(prev => ({+ ...prev,+ metadata: { ...prev.metadata, company: e.target.value }+ }))}+ className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ placeholder="Enter company name..."+ />+ </div>+ <div>+ <label className="text-[9px] block mb-1" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Font Family+ </label>+ <select+ value={fontFamily}+ onChange={(e) => setFontFamily(e.target.value)}+ className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ <option value="Arial, sans-serif">Arial</option>+ <option value="'Times New Roman', serif">Times New Roman</option>+ <option value="Georgia, serif">Georgia</option>+ <option value="'Courier New', monospace">Courier New</option>+ <option value="Verdana, sans-serif">Verdana</option>+ <option value="'Trebuchet MS', sans-serif">Trebuchet MS</option>+ <option value="'Palatino Linotype', serif">Palatino</option>+ <option value="Garamond, serif">Garamond</option>+ <option value="'Comic Sans MS', cursive">Comic Sans MS</option>+ <option value="'Lucida Console', monospace">Lucida Console</option>+ </select>+ </div>+ <div>+ <label className="text-[9px] block mb-1" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Base Font Size+ </label>+ <div className="flex items-center gap-2">+ <input+ type="range"+ min="8"+ max="16"+ value={defaultFontSize}+ onChange={(e) => setDefaultFontSize(Number(e.target.value))}+ className="flex-1"+ style={{ accentColor: BLOOMBERG_COLORS.ORANGE }}+ />+ <span className="text-xs" style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY, minWidth: '30px' }}>+ {defaultFontSize}pt+ </span>+ </div>+ </div>+ <div>+ <label className="text-[9px] block mb-1" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Text Style+ </label>+ <div className="flex gap-2">+ <button+ onClick={() => setIsBold(!isBold)}+ className={`flex-1 px-3 py-2 rounded border transition-all ${+ isBold+ ? 'bg-[#FFA500] border-[#FFA500] text-black'+ : 'bg-[#0a0a0a] border-[#333333] text-gray-400 hover:border-[#FFA500]'+ }`}+ title="Toggle Bold"+ >+ <Bold size={16} className="mx-auto" />+ </button>+ <button+ onClick={() => setIsItalic(!isItalic)}+ className={`flex-1 px-3 py-2 rounded border transition-all ${+ isItalic+ ? 'bg-[#FFA500] border-[#FFA500] text-black'+ : 'bg-[#0a0a0a] border-[#333333] text-gray-400 hover:border-[#FFA500]'+ }`}+ title="Toggle Italic"+ >+ <Italic size={16} className="mx-auto" />+ </button>+ </div>+ </div>+ </div>+ </div>++ {/* Document Structure */}+ <div>+ <h3 className="text-xs font-bold mb-2" style={{ color: BLOOMBERG_COLORS.ORANGE }}>DOCUMENT STRUCTURE</h3>+ <div className="space-y-0">+ {template.components.length === 0 ? (+ <p className="text-xs text-center py-4" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ No components yet+ </p>+ ) : (+ <DndContext+ sensors={sensors}+ collisionDetection={closestCenter}+ onDragEnd={handleDragEnd}+ >+ <SortableContext+ items={template.components.map(c => c.id)}+ strategy={verticalListSortingStrategy}+ >+ {template.components.map((component) => (+ <SortableComponent+ key={component.id}+ component={component}+ isSelected={selectedComponent === component.id}+ onClick={() => setSelectedComponent(component.id)}+ onDelete={() => deleteComponent(component.id)}+ onDuplicate={() => duplicateComponent(component.id)}+ />+ ))}+ </SortableContext>+ </DndContext>+ )}</div></div></div></div>- {/* Canvas */}- <div className="flex-1 overflow-y-auto p-6">- <div className="max-w-4xl mx-auto bg-white text-black p-12 min-h-full shadow-2xl">- {/* Report Header */}- <div className="mb-8 border-b-2 border-gray-800 pb-4">+ {/* Center - Canvas */}+ <div className="w-3/5 overflow-y-auto p-6" style={{ backgroundColor: '#0f0f0f' }}>+ <div+ className="mx-auto shadow-lg"+ style={{+ width: '210mm',+ minHeight: '297mm',+ padding: '20mm',+ fontFamily: fontFamily,+ fontSize: `${defaultFontSize}pt`,+ fontWeight: isBold ? 'bold' : 'normal',+ fontStyle: isItalic ? 'italic' : 'normal',+ ...getThemeBackground(),+ }}+ >+ {/* Document Metadata */}+ <div className="mb-8 border-b border-gray-300 pb-4"><h1 className="text-3xl font-bold mb-2">{template.metadata.title}</h1>{template.metadata.company && (<p className="text-lg text-gray-600">{template.metadata.company}</p>)}- <div className="flex justify-between text-sm text-gray-500 mt-2">- {template.metadata.author && <span>By: {template.metadata.author}</span>}- {template.metadata.date && <span>Date: {template.metadata.date}</span>}- </div>+ {template.metadata.author && (+ <p className="text-sm text-gray-500">By {template.metadata.author}</p>+ )}+ <p className="text-sm text-gray-500">{template.metadata.date}</p></div>{/* Components */}{template.components.length === 0 ? (- <div className="text-center py-12 text-gray-400">- <FileText className="w-16 h-16 mx-auto mb-4 opacity-50" />- <p>Add components from the left sidebar to build your report</p>+ <div className="text-center py-16 text-gray-400">+ <FileText className="w-16 h-16 mx-auto mb-4 opacity-30" />+ <p className="text-lg">Your report is empty</p>+ <p className="text-sm mt-2">Add components from the left panel to start building your report</p></div>) : (- <DndContext- sensors={sensors}- collisionDetection={closestCenter}- onDragEnd={handleDragEnd}- >- <SortableContext- items={template.components.map(c => c.id)}- strategy={verticalListSortingStrategy}- >- {template.components.map((component) => (- <SortableComponent+ <div className="space-y-4">+ {template.components.map((component) => {+ const isSelected = selectedComponent === component.id;+ return (+ <divkey={component.id}- component={component}- onEdit={setSelectedComponent}- onDelete={deleteComponent}- onDuplicate={duplicateComponent}- />- ))}- </SortableContext>- </DndContext>+ onClick={() => setSelectedComponent(component.id)}+ className={`cursor-pointer transition-all ${+ isSelected ? 'ring-2 ring-orange-500 ring-offset-2' : 'hover:ring-1 hover:ring-gray-300'+ }`}+ >+ {/* Render component based on type */}+ {component.type === 'heading' && (+ <h2 className={`font-bold text-2xl text-${component.config.alignment || 'left'}`}>+ {component.content || 'Heading'}+ </h2>+ )}+ {component.type === 'text' && (+ <p className={`text-${component.config.alignment || 'left'}`}>+ {component.content || 'Text content'}+ </p>+ )}+ {component.type === 'chart' && (+ <div className="border border-gray-300 rounded p-8 bg-gray-50 text-center">+ <BarChart3 className="w-16 h-16 mx-auto text-gray-400" />+ <p className="text-sm text-gray-500 mt-2">Chart Placeholder</p>+ </div>+ )}+ {component.type === 'table' && (+ <div className="border border-gray-300 rounded overflow-hidden">+ <table className="w-full">+ <thead className="bg-gray-100">+ <tr>+ {(component.config.columns || ['Column 1', 'Column 2', 'Column 3']).map((col, idx) => (+ <th key={idx} className="px-4 py-2 text-left text-sm font-semibold">{col}</th>+ ))}+ </tr>+ </thead>+ <tbody>+ <tr className="border-t border-gray-200">+ {(component.config.columns || ['Column 1', 'Column 2', 'Column 3']).map((_, idx) => (+ <td key={idx} className="px-4 py-2 text-sm">Sample data</td>+ ))}+ </tr>+ </tbody>+ </table>+ </div>+ )}+ {component.type === 'image' && (+ <div className="border border-gray-300 rounded p-4 bg-gray-50">+ {component.config.imageUrl ? (+ <img+ src={`file://${component.config.imageUrl}`}+ alt="Report Image"+ className="max-w-full h-auto"+ />+ ) : (+ <div className="text-center py-8 text-gray-400">+ <ImageIcon className="w-12 h-12 mx-auto mb-2" />+ <p className="text-sm">No image selected</p>+ </div>+ )}+ </div>+ )}+ {component.type === 'code' && (+ <pre className="bg-gray-900 text-green-400 p-4 rounded overflow-x-auto text-sm font-mono">+ <code>{component.content || '// Code block'}</code>+ </pre>+ )}+ {component.type === 'divider' && (+ <hr className="border-t-2 border-gray-300 my-4" />+ )}+ {component.type === 'section' && (+ <div className="border-l-4 p-4 my-4" style={{+ borderColor: component.config.borderColor || '#FFA500',+ backgroundColor: component.config.backgroundColor || '#f8f9fa'+ }}>+ <h3 className="font-bold text-lg mb-2" style={{ color: component.config.borderColor || '#FFA500' }}>+ {component.config.sectionTitle || 'SECTION'}+ </h3>+ <p className="text-sm text-gray-600">Section content area - add child components here</p>+ </div>+ )}+ {component.type === 'columns' && (+ <div className={`grid gap-4 my-4 ${component.config.columnCount === 3 ? 'grid-cols-3' : 'grid-cols-2'}`}>+ {Array.from({ length: component.config.columnCount || 2 }).map((_, idx) => (+ <div key={idx} className="border border-gray-300 rounded p-4 bg-gray-50">+ <p className="text-sm text-gray-500 text-center">Column {idx + 1}</p>+ </div>+ ))}+ </div>+ )}+ {component.type === 'coverpage' && (+ <div className="min-h-[400px] flex flex-col items-center justify-center text-center p-12" style={{+ backgroundColor: component.config.backgroundColor || '#0a0a0a',+ color: '#FFA500'+ }}>+ <h1 className="text-4xl font-bold mb-4">{template.metadata.title}</h1>+ {component.config.subtitle && (+ <p className="text-xl mb-8">{component.config.subtitle}</p>+ )}+ <div className="text-sm text-gray-400 mt-auto">+ {template.metadata.company}<br />+ {template.metadata.author}<br />+ {template.metadata.date}+ </div>+ </div>+ )}+ {component.type === 'pagebreak' && (+ <div className="my-8 py-4 border-t-2 border-dashed border-gray-400 text-center">+ <span className="text-xs text-gray-400 bg-white px-3 py-1 rounded-full">Page Break</span>+ </div>+ )}+ </div>+ );+ })}+ </div>)}</div></div>- {/* Properties Panel */}- {selectedComp && (- <div className="w-80 border-l border-gray-700 p-4 overflow-y-auto">- <div className="flex items-center justify-between mb-4">- <h2 className="text-sm font-semibold">Component Settings</h2>- <button- onClick={() => setSelectedComponent(null)}- className="text-gray-400 hover:text-white"- >- ×- </button>- </div>+ {/* Right Panel - Properties and AI Chat */}+ <div className="w-1/5 border-l flex flex-col" style={{ borderColor: BLOOMBERG_COLORS.BORDER, backgroundColor: BLOOMBERG_COLORS.PANEL_BG }}>+ {/* Properties Section - Top Half */}+ <div className="flex-1 overflow-y-auto border-b" style={{ borderColor: BLOOMBERG_COLORS.BORDER }}>+ {selectedComp ? (+ <div className="p-4">+ <div className="flex items-center justify-between mb-4">+ <h3 className="text-sm font-bold" style={{ color: BLOOMBERG_COLORS.ORANGE }}>PROPERTIES</h3>+ <button+ onClick={() => setSelectedComponent(null)}+ className="p-1 hover:bg-[#2a2a2a] rounded"+ style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}+ >+ <X size={16} />+ </button>+ </div>++ <div className="space-y-4">+ {/* Component Type */}+ <div>+ <label className="text-xs font-semibold mb-1 block" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Type+ </label>+ <div className="px-3 py-2 text-xs rounded bg-[#0a0a0a] capitalize">+ {selectedComp.type}+ </div>+ </div>- <div className="space-y-4">- {(selectedComp.type === 'heading' || selectedComp.type === 'text') && (- <>+ {/* Content Editor */}+ {(selectedComp.type === 'heading' || selectedComp.type === 'text' || selectedComp.type === 'code') && (<div>- <label className="text-xs text-gray-400 mb-1 block">Content</label>+ <label className="text-xs font-semibold mb-1 block" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Content+ </label><textarea- value={selectedComp.content}+ value={selectedComp.content || ''}onChange={(e) => updateComponent(selectedComp.id, { content: e.target.value })}- className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-sm"- rows={4}+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ rows={selectedComp.type === 'code' ? 10 : 4}+ placeholder="Enter content..."/></div>+ )}++ {/* Alignment */}+ {(selectedComp.type === 'heading' || selectedComp.type === 'text') && (+ <div>+ <label className="text-xs font-semibold mb-1 block" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Alignment+ </label>+ <div className="flex gap-2">+ {['left', 'center', 'right'].map((align) => (+ <button+ key={align}+ onClick={() => updateComponent(selectedComp.id, {+ config: { ...selectedComp.config, alignment: align as any }+ })}+ className={`flex-1 px-3 py-2 text-xs rounded transition-colors capitalize ${+ selectedComp.config.alignment === align+ ? 'bg-[#FFA500] text-black'+ : 'bg-[#0a0a0a] hover:bg-[#2a2a2a]'+ }`}+ >+ {align}+ </button>+ ))}+ </div>+ </div>+ )}++ {/* Font Size */}+ {(selectedComp.type === 'heading' || selectedComp.type === 'text') && (<div>- <label className="text-xs text-gray-400 mb-1 block">Alignment</label>+ <label className="text-xs font-semibold mb-1 block" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Font Size+ </label><select- value={selectedComp.config.alignment}+ value={selectedComp.config.fontSize || 'base'}onChange={(e) => updateComponent(selectedComp.id, {- config: { ...selectedComp.config, alignment: e.target.value as any }+ config: { ...selectedComp.config, fontSize: e.target.value }})}- className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-sm"+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}>- <option value="left">Left</option>- <option value="center">Center</option>- <option value="right">Right</option>+ <option value="xs">Extra Small</option>+ <option value="sm">Small</option>+ <option value="base">Base</option>+ <option value="lg">Large</option>+ <option value="xl">Extra Large</option>+ <option value="2xl">2X Large</option>+ <option value="3xl">3X Large</option></select></div>- </>- )}+ )}- {selectedComp.type === 'chart' && (- <div>- <label className="text-xs text-gray-400 mb-1 block">Chart Type</label>- <select- value={selectedComp.config.chartType}- onChange={(e) => updateComponent(selectedComp.id, {- config: { ...selectedComp.config, chartType: e.target.value }- })}- className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-sm"- >- <option value="line">Line Chart</option>- <option value="bar">Bar Chart</option>- <option value="pie">Pie Chart</option>- <option value="area">Area Chart</option>- </select>+ {/* Image Upload */}+ {selectedComp.type === 'image' && (+ <div>+ <label className="text-xs font-semibold mb-2 block" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Image+ </label>+ {selectedComp.config.imageUrl ? (+ <div className="space-y-2">+ <div className="text-xs text-gray-400 break-all bg-[#0a0a0a] p-2 rounded">+ {selectedComp.config.imageUrl.split('\\').pop()}+ </div>+ <div className="flex gap-2">+ <button+ onClick={handleImageUpload}+ className="flex-1 px-3 py-2 text-xs rounded bg-blue-600 hover:bg-blue-700 transition-colors"+ >+ Change Image+ </button>+ <button+ onClick={() => updateComponent(selectedComp.id, {+ config: { ...selectedComp.config, imageUrl: undefined }+ })}+ className="flex-1 px-3 py-2 text-xs rounded bg-red-600 hover:bg-red-700 transition-colors"+ >+ Remove+ </button>+ </div>+ </div>+ ) : (+ <button+ onClick={handleImageUpload}+ className="w-full px-3 py-2 text-xs rounded transition-colors flex items-center justify-center gap-2"+ style={{ backgroundColor: BLOOMBERG_COLORS.ORANGE, color: BLOOMBERG_COLORS.BLACK }}+ >+ <Plus size={14} />+ Upload Image+ </button>+ )}+ </div>+ )}++ {/* Table Columns */}+ {selectedComp.type === 'table' && (+ <div>+ <label className="text-xs font-semibold mb-1 block" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Columns (comma-separated)+ </label>+ <input+ type="text"+ value={(selectedComp.config.columns || []).join(', ')}+ onChange={(e) => updateComponent(selectedComp.id, {+ config: { ...selectedComp.config, columns: e.target.value.split(',').map(s => s.trim()) }+ })}+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ placeholder="Column 1, Column 2, Column 3"+ />+ </div>+ )}++ {/* Chart Type */}+ {selectedComp.type === 'chart' && (+ <div>+ <label className="text-xs font-semibold mb-1 block" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Chart Type+ </label>+ <select+ value={selectedComp.config.chartType || 'bar'}+ onChange={(e) => updateComponent(selectedComp.id, {+ config: { ...selectedComp.config, chartType: e.target.value }+ })}+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ <option value="bar">Bar Chart</option>+ <option value="line">Line Chart</option>+ <option value="pie">Pie Chart</option>+ <option value="area">Area Chart</option>+ </select>+ </div>+ )}++ {/* Actions */}+ <div className="pt-4 border-t" style={{ borderColor: BLOOMBERG_COLORS.BORDER }}>+ <div className="flex gap-2">+ <button+ onClick={() => duplicateComponent(selectedComp.id)}+ className="flex-1 px-3 py-2 text-xs rounded bg-[#0a0a0a] hover:bg-[#2a2a2a] transition-colors flex items-center justify-center gap-2"+ >+ <Copy size={14} />+ Duplicate+ </button>+ <button+ onClick={() => deleteComponent(selectedComp.id)}+ className="flex-1 px-3 py-2 text-xs rounded bg-red-600 hover:bg-red-700 transition-colors flex items-center justify-center gap-2"+ >+ <Trash2 size={14} />+ Delete+ </button>+ </div></div>+ </div>+ </div>+ ) : (+ <div className="p-4 text-center" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ <SettingsIcon size={32} className="mx-auto mb-2 opacity-30" />+ <p className="text-xs">Select a component to edit properties</p>+ </div>+ )}+ </div>++ {/* AI Writing Assistant Section - Bottom Half */}+ <div className="flex-1 flex flex-col" style={{ backgroundColor: BLOOMBERG_COLORS.PANEL_BG }}>+ {/* AI Assistant Header */}+ <div className="p-4 border-b border-[#333333]">+ <div className="flex items-center justify-between mb-3">+ <div className="flex items-center gap-2">+ <Bot size={18} style={{ color: BLOOMBERG_COLORS.ORANGE }} />+ <h3 className="text-sm font-bold" style={{ color: BLOOMBERG_COLORS.ORANGE }}>+ AI WRITING ASSISTANT+ </h3>+ </div>+ <Sparkles size={16} style={{ color: BLOOMBERG_COLORS.ORANGE }} />+ </div>++ {/* Model Selector */}+ <div className="mb-3">+ <label className="text-[9px] block mb-1" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ AI Model+ </label>+ <select+ value={currentProvider}+ onChange={(e) => setCurrentProvider(e.target.value)}+ className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ {availableModels.map(model => (+ <option key={model.id} value={model.provider}>+ {model.name} ({model.provider})+ </option>+ ))}+ {availableModels.length === 0 && (+ <option value="ollama">Configure in Settings</option>)}+ </select>+ </div>- {selectedComp.type === 'code' && (- <div>- <label className="text-xs text-gray-400 mb-1 block">Code</label>- <textarea- value={selectedComp.content}- onChange={(e) => updateComponent(selectedComp.id, { content: e.target.value })}- className="w-full px-3 py-2 bg-gray-800 border border-gray-700 rounded text-sm font-mono"- rows={8}- placeholder="Enter code here..."- />+ {/* Quick Actions */}+ <div className="grid grid-cols-2 gap-1">+ <button+ onClick={() => handleAiQuickAction('improve')}+ className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ ✨ Improve+ </button>+ <button+ onClick={() => handleAiQuickAction('expand')}+ className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ 📝 Expand+ </button>+ <button+ onClick={() => handleAiQuickAction('summarize')}+ className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ 📋 Summary+ </button>+ <button+ onClick={() => handleAiQuickAction('grammar')}+ className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ >+ ✓ Grammar+ </button>+ </div>+ </div>++ {/* AI Chat Messages */}+ <div className="flex-1 overflow-y-auto p-4 space-y-3">+ {aiMessages.length === 0 && (+ <div className="text-center py-8">+ <Bot size={32} className="mx-auto mb-3" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }} />+ <p className="text-xs" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Ask me to help you write better reports!+ </p>+ <p className="text-[9px] mt-2" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ Try: "Help me write an introduction"+ </p>+ </div>+ )}++ {aiMessages.map((msg, idx) => (+ <div key={idx} className={`flex gap-2 ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>+ {msg.role === 'assistant' && (+ <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center" style={{ backgroundColor: BLOOMBERG_COLORS.ORANGE }}>+ <Bot size={14} style={{ color: '#000' }} />+ </div>+ )}+ <div+ className={`max-w-[85%] rounded-lg p-3 ${+ msg.role === 'user'+ ? 'bg-[#FFA500] text-black'+ : 'bg-[#1a1a1a] border border-[#333333]'+ }`}+ >+ <div className="text-xs" style={{ color: msg.role === 'user' ? '#000' : BLOOMBERG_COLORS.TEXT_PRIMARY }}>+ {msg.role === 'assistant' ? (+ <MarkdownRenderer content={msg.content} />+ ) : (+ msg.content+ )}+ </div>+ </div>+ {msg.role === 'user' && (+ <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center bg-[#333333]">+ <User size={14} style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }} /></div>)}</div>+ ))}++ {isAiTyping && streamingContent && (+ <div className="flex gap-2 justify-start">+ <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center" style={{ backgroundColor: BLOOMBERG_COLORS.ORANGE }}>+ <Bot size={14} style={{ color: '#000' }} />+ </div>+ <div className="max-w-[85%] rounded-lg p-3 bg-[#1a1a1a] border border-[#333333]">+ <div className="text-xs" style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}>+ <MarkdownRenderer content={streamingContent} />+ </div>+ </div>+ </div>+ )}++ {isAiTyping && !streamingContent && (+ <div className="flex gap-2 justify-start">+ <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center" style={{ backgroundColor: BLOOMBERG_COLORS.ORANGE }}>+ <Bot size={14} style={{ color: '#000' }} />+ </div>+ <div className="max-w-[85%] rounded-lg p-3 bg-[#1a1a1a] border border-[#333333]">+ <div className="text-xs flex gap-1" style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ <span className="animate-bounce">●</span>+ <span className="animate-bounce delay-100">●</span>+ <span className="animate-bounce delay-200">●</span>+ </div>+ </div>+ </div>+ )}++ <div ref={aiMessagesEndRef} />+ </div>++ {/* AI Input */}+ <div className="p-4 border-t border-[#333333]">+ <div className="flex gap-2">+ <input+ type="text"+ value={aiInput}+ onChange={(e) => setAiInput(e.target.value)}+ onKeyPress={(e) => e.key === 'Enter' && handleAiSendMessage()}+ placeholder="Ask AI to help with your report..."+ className="flex-1 px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"+ style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}+ disabled={isAiTyping}+ />+ <button+ onClick={handleAiSendMessage}+ disabled={isAiTyping || !aiInput.trim()}+ className="px-3 py-2 rounded transition-all disabled:opacity-50 disabled:cursor-not-allowed"+ style={{+ backgroundColor: BLOOMBERG_COLORS.ORANGE,+ color: '#000'+ }}+ >+ <Send size={16} />+ </button>+ </div>+ </div>+ </div>+ </div>+ </div>++ {/* Success Dialog */}+ <Dialog open={showSuccessDialog} onOpenChange={setShowSuccessDialog}>+ <DialogContent className="bg-[#1a1a1a] border-[#333333]">+ <DialogHeader>+ <DialogTitle className="text-[#FFA500]">PDF Generated Successfully!</DialogTitle>+ <DialogDescription className="text-gray-400">+ Your report has been generated and saved.+ </DialogDescription>+ </DialogHeader>+ <div className="py-4">+ <p className="text-sm text-gray-300 mb-2">File saved to:</p>+ <p className="text-xs text-gray-500 break-all bg-[#0a0a0a] p-2 rounded border border-[#333333]">+ {generatedPdfPath}+ </p></div>- )}+ <DialogFooter>+ <Button+ variant="outline"+ onClick={() => setShowSuccessDialog(false)}+ className="bg-transparent border-[#333333] text-white hover:bg-[#2a2a2a]"+ >+ Close+ </Button>+ <Button+ onClick={handleShowInFolder}+ className="bg-[#FFA500] text-black hover:bg-[#ff8c00]"+ >+ <FolderOpen className="w-4 h-4 mr-2" />+ Show in Folder+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {/* Footer */}+ <div style={{+ borderTop: `2px solid ${BLOOMBERG_COLORS.ORANGE}`,+ padding: '8px 16px',+ background: `linear-gradient(180deg, ${BLOOMBERG_COLORS.PANEL_BG} 0%, #0a0a0a 100%)`,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ flexShrink: 0,+ flexWrap: 'wrap',+ gap: '12px'+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px', fontSize: '9px' }}>+ <span style={{ color: BLOOMBERG_COLORS.ORANGE, fontWeight: 'bold' }}>REPORT BUILDER v1.0.0</span>+ <span style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>|</span>+ <span style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}>Components: {template.components.length}</span>+ <span style={{ color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>|</span>+ <span style={{ color: BLOOMBERG_COLORS.TEXT_PRIMARY }}>Theme: {pageTheme.charAt(0).toUpperCase() + pageTheme.slice(1)}</span>+ </div>+ <div style={{ fontSize: '9px', color: BLOOMBERG_COLORS.TEXT_SECONDARY }}>+ {currentTime.toLocaleTimeString()} | PDF Generator: Rust printpdf+ </div></div></div>);diff --git a/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx.backup b/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx.backupnew file mode 100644index 000000000..d711f18aa--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx.backup@@ -0,0 +1,1793 @@+import React, { useState } from 'react';+import {+ FileText,+ Download,+ Save,+ Type,+ BarChart3,+ Table,+ Image as ImageIcon,+ Trash2,+ Copy,+ AlignLeft,+ Code,+ Minus,+ FolderOpen,+ Check,+ Plus,+ RefreshCw,+ Edit2,+ Move,+ Columns as ColumnsIcon,+ Layout,+ BookOpen,+ FileX+} from 'lucide-react';+import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragEndEvent } from '@dnd-kit/core';+import { arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';+import { CSS } from '@dnd-kit/utilities';+import { reportService, ReportTemplate, ReportComponent } from '@/services/reportService';+import { save, open } from '@tauri-apps/plugin-dialog';+import { toast } from 'sonner';+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';+import { Button } from '@/components/ui/button';++// Bloomberg color palette+const BLOOMBERG_COLORS = {+ ORANGE: '#FFA500',+ WHITE: '#FFFFFF',+ RED: '#ef4444',+ GREEN: '#10b981',+ YELLOW: '#fbbf24',+ GRAY: '#787878',+ BLUE: '#3b82f6',+ CYAN: '#06b6d4',+ DARK_BG: '#0a0a0a',+ PANEL_BG: '#1a1a1a',+ BORDER: '#333333',+};++// Sortable component wrapper+function SortableComponent({ component, onEdit, onDelete, onDuplicate, isSelected }: {+ component: ReportComponent;+ onEdit: (id: string) => void;+ onDelete: (id: string) => void;+ onDuplicate: (id: string) => void;+ isSelected: boolean;+}) {+ const {+ attributes,+ listeners,+ setNodeRef,+ transform,+ transition,+ } = useSortable({ id: component.id });++ const style = {+ transform: CSS.Transform.toString(transform),+ transition,+ };++ const getComponentIcon = () => {+ switch (component.type) {+ case 'heading': return <Type size={10} />;+ case 'text': return <AlignLeft size={10} />;+ case 'chart': return <BarChart3 size={10} />;+ case 'table': return <Table size={10} />;+ case 'image': return <ImageIcon size={10} />;+ case 'code': return <Code size={10} />;+ case 'divider': return <Minus size={10} />;+ default: return <FileText size={10} />;+ }+ };++ return (+ <div+ ref={setNodeRef}+ style={{+ ...style,+ backgroundColor: isSelected ? '#2a2a2a' : 'transparent',+ borderBottom: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ padding: '6px 8px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ cursor: 'pointer',+ borderLeft: isSelected ? `2px solid ${BLOOMBERG_COLORS.ORANGE}` : 'none'+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1 }}>+ <div {...attributes} {...listeners} style={{ color: BLOOMBERG_COLORS.GRAY, cursor: 'move', display: 'flex' }}>+ <Move size={12} />+ </div>+ <div style={{ color: BLOOMBERG_COLORS.CYAN, display: 'flex' }}>+ {getComponentIcon()}+ </div>+ <span style={{ color: BLOOMBERG_COLORS.ORANGE, fontSize: '9px', fontWeight: 'bold' }}>+ {component.type.toUpperCase()}+ </span>+ <span style={{ color: BLOOMBERG_COLORS.GRAY, fontSize: '9px', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {component.content ? component.content.substring(0, 20) : 'Empty'}+ </span>+ </div>+ <div style={{ display: 'flex', gap: '4px' }}>+ <button+ onClick={(e) => { e.stopPropagation(); onEdit(component.id); }}+ style={{+ background: 'transparent',+ border: 'none',+ color: BLOOMBERG_COLORS.BLUE,+ cursor: 'pointer',+ padding: '2px',+ display: 'flex'+ }}+ title="Edit"+ >+ <Edit2 size={10} />+ </button>+ <button+ onClick={(e) => { e.stopPropagation(); onDuplicate(component.id); }}+ style={{+ background: 'transparent',+ border: 'none',+ color: BLOOMBERG_COLORS.GREEN,+ cursor: 'pointer',+ padding: '2px',+ display: 'flex'+ }}+ title="Duplicate"+ >+ <Copy size={10} />+ </button>+ <button+ onClick={(e) => { e.stopPropagation(); onDelete(component.id); }}+ style={{+ background: 'transparent',+ border: 'none',+ color: BLOOMBERG_COLORS.RED,+ cursor: 'pointer',+ padding: '2px',+ display: 'flex'+ }}+ title="Delete"+ >+ <Trash2 size={10} />+ </button>+ </div>+ </div>+ );+}++const ReportBuilderTab: React.FC = () => {+ const [currentTime, setCurrentTime] = useState(new Date());+ const [template, setTemplate] = useState<ReportTemplate>({+ id: `report-${Date.now()}`,+ name: 'New Financial Report',+ description: 'Professional financial research report',+ components: [],+ metadata: {+ author: '',+ company: '',+ date: new Date().toISOString().split('T')[0],+ title: 'Financial Research Report',+ },+ styles: {+ pageSize: 'A4',+ orientation: 'portrait',+ margins: '20mm',+ headerFooter: true,+ },+ });++ const [selectedComponent, setSelectedComponent] = useState<string | null>(null);+ const [isGenerating, setIsGenerating] = useState(false);+ const [isSaving, setIsSaving] = useState(false);+ const [showSuccessDialog, setShowSuccessDialog] = useState(false);+ const [generatedPdfPath, setGeneratedPdfPath] = useState<string>('');++ const sensors = useSensors(+ useSensor(PointerSensor),+ useSensor(KeyboardSensor, {+ coordinateGetter: sortableKeyboardCoordinates,+ })+ );++ // Update time+ React.useEffect(() => {+ const timer = setInterval(() => setCurrentTime(new Date()), 1000);+ return () => clearInterval(timer);+ }, []);++ const addComponent = (type: ReportComponent['type']) => {+ const newComponent: ReportComponent = {+ id: `component-${Date.now()}`,+ type,+ content: type === 'divider' || type === 'pagebreak' || type === 'coverpage' ? null : '',+ config: {+ fontSize: type === 'heading' ? '2xl' : type === 'subheading' ? 'xl' : 'base',+ alignment: 'left',+ ...(type === 'columns' && { columnCount: 2 }),+ ...(type === 'section' && {+ sectionTitle: 'New Section',+ sectionStyle: 'default',+ backgroundColor: '#f8f9fa',+ borderColor: '#FFA500',+ padding: '15px'+ }),+ ...(type === 'coverpage' && {+ subtitle: '',+ backgroundColor: '#0a0a0a',+ color: '#FFA500'+ }),+ },+ ...(type === 'columns' || type === 'section' ? { children: [] } : {}),+ };++ setTemplate(prev => ({+ ...prev,+ components: [...prev.components, newComponent],+ }));+ setSelectedComponent(newComponent.id);+ };++ const deleteComponent = (id: string) => {+ setTemplate(prev => ({+ ...prev,+ components: prev.components.filter(c => c.id !== id),+ }));+ if (selectedComponent === id) {+ setSelectedComponent(null);+ }+ };++ const duplicateComponent = (id: string) => {+ const component = template.components.find(c => c.id === id);+ if (component) {+ const newComponent = {+ ...component,+ id: `component-${Date.now()}`,+ };+ setTemplate(prev => ({+ ...prev,+ components: [...prev.components, newComponent],+ }));+ }+ };++ const handleDragEnd = (event: DragEndEvent) => {+ const { active, over } = event;++ if (over && active.id !== over.id) {+ setTemplate(prev => {+ const oldIndex = prev.components.findIndex(c => c.id === active.id);+ const newIndex = prev.components.findIndex(c => c.id === over.id);++ return {+ ...prev,+ components: arrayMove(prev.components, oldIndex, newIndex),+ };+ });+ }+ };++ const updateComponent = (id: string, updates: Partial<ReportComponent>) => {+ setTemplate(prev => ({+ ...prev,+ components: prev.components.map(c =>+ c.id === id ? { ...c, ...updates } : c+ ),+ }));+ };++ const handleOpenFolder = async () => {+ try {+ const success = await reportService.openInFolder(generatedPdfPath);+ if (success) {+ toast.success('Folder opened');+ } else {+ toast.error('Failed to open folder');+ }+ } catch (error) {+ console.error('Failed to open folder:', error);+ toast.error('Failed to open folder');+ }+ setShowSuccessDialog(false);+ };++ const generatePDF = async () => {+ setIsGenerating(true);+ try {+ const outputPath = await save({+ filters: [{+ name: 'PDF',+ extensions: ['pdf']+ }],+ defaultPath: `${template.name.replace(/\s+/g, '-')}.pdf`+ });++ if (!outputPath) {+ setIsGenerating(false);+ return;+ }++ console.log('[ReportBuilder] Generating PDF at:', outputPath);+ const result = await reportService.generatePDF(template, outputPath);+ console.log('[ReportBuilder] PDF generation result:', result);++ if (result.success) {+ // Use the path returned by the service, or fall back to the selected path+ const finalPath = result.output_path || outputPath;+ console.log('[ReportBuilder] PDF saved to:', finalPath);+ setGeneratedPdfPath(finalPath);+ setShowSuccessDialog(true);+ toast.success('PDF generated successfully');+ } else {+ console.error('[ReportBuilder] PDF generation failed:', result.error);++ // Check if it's a missing dependency error+ if (result.error && result.error.includes('reportlab')) {+ toast.error('PDF Library Missing', {+ description: 'Please install: pip install reportlab',+ duration: 10000+ });+ } else {+ toast.error('Failed to generate PDF', {+ description: result.error || 'Unknown error'+ });+ }+ }+ } catch (error) {+ console.error('[ReportBuilder] Exception during PDF generation:', error);++ // Check if it's because the Rust command doesn't exist yet+ if (error instanceof Error && error.message.includes('not found')) {+ toast.error('PDF generation not implemented yet', {+ description: 'The backend PDF generation command is not available. Please implement the generate_report_pdf Rust command.'+ });+ } else {+ toast.error('Failed to generate PDF', {+ description: error instanceof Error ? error.message : 'Unknown error'+ });+ }+ } finally {+ setIsGenerating(false);+ }+ };++ const saveTemplate = async () => {+ setIsSaving(true);+ try {+ await reportService.saveTemplate(template);+ toast.success('Template saved');+ } catch (error) {+ console.error('Failed to save template:', error);+ toast.error('Failed to save template');+ } finally {+ setIsSaving(false);+ }+ };++ const selectedComp = selectedComponent+ ? template.components.find(c => c.id === selectedComponent)+ : null;++ return (+ <div style={{+ height: '100%',+ backgroundColor: BLOOMBERG_COLORS.DARK_BG,+ color: BLOOMBERG_COLORS.WHITE,+ fontFamily: 'Consolas, monospace',+ overflow: 'hidden',+ display: 'flex',+ flexDirection: 'column'+ }}>+ <style>{`+ *::-webkit-scrollbar { width: 8px; height: 8px; }+ *::-webkit-scrollbar-track { background: #1a1a1a; }+ *::-webkit-scrollbar-thumb { background: #404040; border-radius: 4px; }+ *::-webkit-scrollbar-thumb:hover { background: #525252; }+ `}</style>++ {/* Success Dialog */}+ <Dialog open={showSuccessDialog} onOpenChange={setShowSuccessDialog}>+ <DialogContent+ className="bg-gray-900 border-2 border-orange-500 text-white"+ style={{+ backgroundColor: BLOOMBERG_COLORS.PANEL_BG,+ borderColor: BLOOMBERG_COLORS.ORANGE,+ maxWidth: '600px'+ }}+ >+ <DialogHeader>+ <DialogTitle+ className="flex items-center gap-3 text-lg"+ style={{ color: BLOOMBERG_COLORS.ORANGE }}+ >+ <Check className="w-6 h-6" style={{ color: BLOOMBERG_COLORS.GREEN }} />+ PDF GENERATED SUCCESSFULLY+ </DialogTitle>+ <DialogDescription+ className="text-sm mt-2"+ style={{ color: BLOOMBERG_COLORS.GRAY }}+ >+ Your financial report has been exported successfully.+ </DialogDescription>+ </DialogHeader>+ <div className="py-4">+ <div+ className="text-xs mb-2 uppercase font-bold"+ style={{ color: BLOOMBERG_COLORS.CYAN }}+ >+ FILE LOCATION:+ </div>+ <p+ className="text-sm break-all font-mono p-3 rounded"+ style={{+ backgroundColor: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.WHITE+ }}+ >+ {generatedPdfPath}+ </p>+ </div>+ <DialogFooter className="flex gap-3 justify-end">+ <button+ onClick={() => setShowSuccessDialog(false)}+ style={{+ background: BLOOMBERG_COLORS.GRAY,+ color: 'black',+ border: 'none',+ padding: '8px 16px',+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ CLOSE+ </button>+ <button+ onClick={handleOpenFolder}+ style={{+ background: BLOOMBERG_COLORS.ORANGE,+ color: 'black',+ border: 'none',+ padding: '8px 16px',+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ fontFamily: 'Consolas, monospace'+ }}+ >+ <FolderOpen className="w-4 h-4" />+ SHOW IN FOLDER+ </button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {/* Header Bar */}+ <div style={{+ backgroundColor: BLOOMBERG_COLORS.PANEL_BG,+ borderBottom: `1px solid ${BLOOMBERG_COLORS.GRAY}`,+ padding: '8px 12px',+ flexShrink: 0+ }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <span style={{ color: BLOOMBERG_COLORS.ORANGE, fontWeight: 'bold', fontSize: '14px' }}>+ FINCEPT REPORT BUILDER+ </span>+ <span style={{ color: BLOOMBERG_COLORS.WHITE }}>|</span>+ <span style={{ color: BLOOMBERG_COLORS.GREEN, fontSize: '10px' }}>+ ● ACTIVE+ </span>+ <span style={{ color: BLOOMBERG_COLORS.WHITE }}>|</span>+ <span style={{ color: BLOOMBERG_COLORS.CYAN, fontSize: '11px' }}>+ {currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC+ </span>+ </div>++ <div style={{ display: 'flex', gap: '8px' }}>+ <button+ onClick={() => {+ const equityTemplate = reportService.getEquityResearchTemplate();+ setTemplate(equityTemplate);+ toast.success('Loaded Equity Research template');+ }}+ style={{+ background: BLOOMBERG_COLORS.DARK_BG,+ color: BLOOMBERG_COLORS.CYAN,+ border: `1px solid ${BLOOMBERG_COLORS.CYAN}`,+ padding: '4px 12px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <FileText size={12} />+ LOAD TEMPLATE+ </button>+ <button+ onClick={saveTemplate}+ disabled={isSaving}+ style={{+ background: isSaving ? BLOOMBERG_COLORS.GRAY : BLOOMBERG_COLORS.CYAN,+ color: 'black',+ border: 'none',+ padding: '4px 12px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: isSaving ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ opacity: isSaving ? 0.5 : 1+ }}+ >+ <Save size={12} />+ {isSaving ? 'SAVING...' : 'SAVE'}+ </button>+ <button+ onClick={generatePDF}+ disabled={isGenerating}+ style={{+ background: isGenerating ? BLOOMBERG_COLORS.GRAY : BLOOMBERG_COLORS.ORANGE,+ color: 'black',+ border: 'none',+ padding: '4px 12px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: isGenerating ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ opacity: isGenerating ? 0.5 : 1+ }}+ >+ <Download size={12} />+ {isGenerating ? 'GENERATING...' : 'EXPORT PDF'}+ </button>+ </div>+ </div>+ </div>++ {/* Main Content Area */}+ <div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>+ {/* Left Panel - Component Palette & List */}+ <div style={{+ width: '280px',+ backgroundColor: BLOOMBERG_COLORS.PANEL_BG,+ borderRight: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ display: 'flex',+ flexDirection: 'column'+ }}>+ {/* Report Metadata */}+ <div style={{+ borderBottom: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ padding: '12px'+ }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG_COLORS.ORANGE, fontWeight: 'bold', marginBottom: '8px' }}>+ REPORT METADATA+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>+ <div>+ <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '2px' }}>+ TITLE+ </label>+ <input+ type="text"+ value={template.metadata.title}+ onChange={(e) => setTemplate(prev => ({+ ...prev,+ metadata: { ...prev.metadata, title: e.target.value }+ }))}+ style={{+ width: '100%',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.WHITE,+ padding: '4px 6px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>+ <div>+ <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '2px' }}>+ AUTHOR+ </label>+ <input+ type="text"+ value={template.metadata.author}+ onChange={(e) => setTemplate(prev => ({+ ...prev,+ metadata: { ...prev.metadata, author: e.target.value }+ }))}+ style={{+ width: '100%',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.WHITE,+ padding: '4px 6px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>+ <div>+ <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '2px' }}>+ COMPANY+ </label>+ <input+ type="text"+ value={template.metadata.company}+ onChange={(e) => setTemplate(prev => ({+ ...prev,+ metadata: { ...prev.metadata, company: e.target.value }+ }))}+ style={{+ width: '100%',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.WHITE,+ padding: '4px 6px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ />+ </div>+ </div>+ </div>++ {/* Component Palette */}+ <div style={{+ borderBottom: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ padding: '12px'+ }}>+ <div style={{ fontSize: '10px', color: BLOOMBERG_COLORS.ORANGE, fontWeight: 'bold', marginBottom: '8px' }}>+ CONTENT+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px', marginBottom: '12px' }}>+ <button+ onClick={() => addComponent('heading')}+ style={{+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.CYAN,+ padding: '8px 4px',+ fontSize: '9px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <Type size={14} />+ HEADING+ </button>+ <button+ onClick={() => addComponent('subheading')}+ style={{+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.CYAN,+ padding: '8px 4px',+ fontSize: '9px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <Type size={12} />+ SUBHEAD+ </button>+ <button+ onClick={() => addComponent('text')}+ style={{+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.CYAN,+ padding: '8px 4px',+ fontSize: '9px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <AlignLeft size={14} />+ TEXT+ </button>+ <button+ onClick={() => addComponent('image')}+ style={{+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.CYAN,+ padding: '8px 4px',+ fontSize: '9px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <ImageIcon size={14} />+ IMAGE+ </button>+ <button+ onClick={() => addComponent('chart')}+ style={{+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.CYAN,+ padding: '8px 4px',+ fontSize: '9px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <BarChart3 size={14} />+ CHART+ </button>+ <button+ onClick={() => addComponent('table')}+ style={{+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.CYAN,+ padding: '8px 4px',+ fontSize: '9px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <Table size={14} />+ TABLE+ </button>+ <button+ onClick={() => addComponent('code')}+ style={{+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.CYAN,+ padding: '8px 4px',+ fontSize: '9px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <Code size={14} />+ CODE+ </button>+ <button+ onClick={() => addComponent('divider')}+ style={{+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.CYAN,+ padding: '8px 4px',+ fontSize: '9px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <Minus size={14} />+ DIVIDER+ </button>+ </div>++ <div style={{ fontSize: '10px', color: BLOOMBERG_COLORS.ORANGE, fontWeight: 'bold', marginBottom: '8px' }}>+ LAYOUT+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px', marginBottom: '12px' }}>+ <button+ onClick={() => addComponent('section')}+ style={{+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.ORANGE,+ padding: '8px 4px',+ fontSize: '9px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <Layout size={14} />+ SECTION+ </button>+ <button+ onClick={() => addComponent('columns')}+ style={{+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.ORANGE,+ padding: '8px 4px',+ fontSize: '9px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <ColumnsIcon size={14} />+ COLUMNS+ </button>+ <button+ onClick={() => addComponent('coverpage')}+ style={{+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.ORANGE,+ padding: '8px 4px',+ fontSize: '9px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <BookOpen size={14} />+ COVER+ </button>+ <button+ onClick={() => addComponent('pagebreak')}+ style={{+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.ORANGE,+ padding: '8px 4px',+ fontSize: '9px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <FileX size={14} />+ PAGE BREAK+ </button>+ </div>+ </div>++ {/* Component List */}+ <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>+ <div style={{+ padding: '8px 12px',+ borderBottom: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ fontSize: '10px',+ color: BLOOMBERG_COLORS.ORANGE,+ fontWeight: 'bold'+ }}>+ DOCUMENT STRUCTURE ({template.components.length})+ </div>+ <div style={{ flex: 1, overflow: 'auto' }}>+ {template.components.length === 0 ? (+ <div style={{+ padding: '24px 12px',+ textAlign: 'center',+ fontSize: '9px',+ color: BLOOMBERG_COLORS.GRAY+ }}>+ <FileText size={32} style={{ margin: '0 auto 8px', opacity: 0.3 }} />+ <div>NO COMPONENTS</div>+ <div style={{ marginTop: '4px' }}>Add components above</div>+ </div>+ ) : (+ <DndContext+ sensors={sensors}+ collisionDetection={closestCenter}+ onDragEnd={handleDragEnd}+ >+ <SortableContext+ items={template.components.map(c => c.id)}+ strategy={verticalListSortingStrategy}+ >+ {template.components.map((component) => (+ <SortableComponent+ key={component.id}+ component={component}+ onEdit={setSelectedComponent}+ onDelete={deleteComponent}+ onDuplicate={duplicateComponent}+ isSelected={selectedComponent === component.id}+ />+ ))}+ </SortableContext>+ </DndContext>+ )}+ </div>+ </div>+ </div>++ {/* Main Panel - Visual Canvas */}+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>+ {/* Always show preview mode with inline editing */}+ <div style={{ flex: 1, overflow: 'auto', padding: '24px', backgroundColor: '#0d0d0d' }}>+ <div style={{+ maxWidth: '900px',+ margin: '0 auto',+ backgroundColor: '#ffffff',+ color: '#000000',+ padding: '48px',+ boxShadow: '0 4px 12px rgba(0,0,0,0.3)',+ fontFamily: 'Georgia, serif'+ }}>+ {/* Report Header */}+ <div style={{+ borderBottom: '2px solid #000',+ paddingBottom: '16px',+ marginBottom: '24px'+ }}>+ <h1 style={{ fontSize: '28px', fontWeight: 'bold', marginBottom: '8px' }}>+ {template.metadata.title}+ </h1>+ {template.metadata.company && (+ <div style={{ fontSize: '16px', color: '#333', marginBottom: '8px' }}>+ {template.metadata.company}+ </div>+ )}+ <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', color: '#666' }}>+ {template.metadata.author && <span>Author: {template.metadata.author}</span>}+ {template.metadata.date && <span>Date: {template.metadata.date}</span>}+ </div>+ </div>++ {/* Components - Click to Edit Inline */}+ {template.components.length === 0 ? (+ <div style={{+ textAlign: 'center',+ padding: '64px 24px',+ color: '#999'+ }}>+ <FileText size={64} style={{ margin: '0 auto 16px', opacity: 0.2 }} />+ <div style={{ fontSize: '14px' }}>No components added yet</div>+ <div style={{ fontSize: '12px', marginTop: '8px' }}>Add components from the left panel</div>+ </div>+ ) : (+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>+ {template.components.map((component) => {+ const isEditing = selectedComponent === component.id;++ return (+ <div+ key={component.id}+ onClick={() => setSelectedComponent(component.id)}+ style={{+ cursor: 'pointer',+ padding: isEditing ? '16px' : '12px',+ borderRadius: '4px',+ border: isEditing ? `3px solid ${BLOOMBERG_COLORS.ORANGE}` : '2px dashed transparent',+ transition: 'all 0.2s',+ backgroundColor: isEditing ? '#fff8f0' : 'transparent',+ position: 'relative'+ }}+ onMouseEnter={(e) => {+ if (!isEditing) {+ e.currentTarget.style.backgroundColor = '#f9f9f9';+ e.currentTarget.style.borderColor = '#ddd';+ }+ }}+ onMouseLeave={(e) => {+ if (!isEditing) {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.borderColor = 'transparent';+ }+ }}+ >+ {/* Editing Toolbar */}+ {isEditing && (+ <div style={{+ position: 'absolute',+ top: '-32px',+ right: '0',+ display: 'flex',+ gap: '4px',+ backgroundColor: BLOOMBERG_COLORS.ORANGE,+ padding: '4px 8px',+ borderRadius: '4px 4px 0 0',+ fontSize: '9px',+ fontWeight: 'bold',+ color: 'black'+ }}>+ <span>{component.type.toUpperCase()}</span>+ <span>|</span>+ <button+ onClick={(e) => {+ e.stopPropagation();+ duplicateComponent(component.id);+ }}+ style={{+ background: 'none',+ border: 'none',+ color: 'black',+ cursor: 'pointer',+ padding: '0 4px'+ }}+ >+ COPY+ </button>+ <button+ onClick={(e) => {+ e.stopPropagation();+ deleteComponent(component.id);+ setSelectedComponent(null);+ }}+ style={{+ background: 'none',+ border: 'none',+ color: 'black',+ cursor: 'pointer',+ padding: '0 4px'+ }}+ >+ DELETE+ </button>+ </div>+ )}++ {/* Inline Editor for Selected Component */}+ {isEditing ? (+ <div style={{+ backgroundColor: 'white',+ padding: '8px',+ borderRadius: '4px'+ }}>++ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>+ {(selectedComp.type === 'heading' || selectedComp.type === 'subheading' || selectedComp.type === 'text') && (+ <>+ <div>+ <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>+ CONTENT+ </label>+ <textarea+ value={selectedComp.content}+ onChange={(e) => updateComponent(selectedComp.id, { content: e.target.value })}+ style={{+ width: '100%',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.WHITE,+ padding: '8px',+ fontSize: '11px',+ fontFamily: 'Consolas, monospace',+ minHeight: '120px',+ resize: 'vertical'+ }}+ placeholder={`Enter ${selectedComp.type} content...`}+ />+ </div>+ <div>+ <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>+ ALIGNMENT+ </label>+ <select+ value={selectedComp.config.alignment}+ onChange={(e) => updateComponent(selectedComp.id, {+ config: { ...selectedComp.config, alignment: e.target.value as any }+ })}+ style={{+ width: '100%',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.WHITE,+ padding: '6px 8px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ >+ <option value="left">LEFT</option>+ <option value="center">CENTER</option>+ <option value="right">RIGHT</option>+ </select>+ </div>+ </>+ )}++ {selectedComp.type === 'chart' && (+ <div>+ <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>+ CHART TYPE+ </label>+ <select+ value={selectedComp.config.chartType || 'line'}+ onChange={(e) => updateComponent(selectedComp.id, {+ config: { ...selectedComp.config, chartType: e.target.value }+ })}+ style={{+ width: '100%',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.WHITE,+ padding: '6px 8px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace'+ }}+ >+ <option value="line">LINE CHART</option>+ <option value="bar">BAR CHART</option>+ <option value="pie">PIE CHART</option>+ <option value="area">AREA CHART</option>+ </select>+ <div style={{+ marginTop: '16px',+ padding: '48px',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center'+ }}>+ <BarChart3 size={64} style={{ color: BLOOMBERG_COLORS.CYAN, opacity: 0.3 }} />+ </div>+ </div>+ )}++ {selectedComp.type === 'code' && (+ <div>+ <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>+ CODE BLOCK+ </label>+ <textarea+ value={selectedComp.content}+ onChange={(e) => updateComponent(selectedComp.id, { content: e.target.value })}+ style={{+ width: '100%',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.GREEN,+ padding: '12px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace',+ minHeight: '240px',+ resize: 'vertical'+ }}+ placeholder="Enter code here..."+ />+ </div>+ )}++ {selectedComp.type === 'table' && (+ <div style={{+ padding: '32px',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ textAlign: 'center'+ }}>+ <Table size={48} style={{ color: BLOOMBERG_COLORS.CYAN, opacity: 0.3, margin: '0 auto' }} />+ <div style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, marginTop: '12px' }}>+ TABLE EDITOR COMING SOON+ </div>+ </div>+ )}++ {selectedComp.type === 'image' && (+ <div>+ <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>+ IMAGE FILE+ </label>+ <div style={{+ padding: '24px',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px dashed ${BLOOMBERG_COLORS.BORDER}`,+ textAlign: 'center'+ }}>+ {selectedComp.config.imageUrl ? (+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>+ <div style={{+ padding: '12px',+ background: BLOOMBERG_COLORS.PANEL_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ borderRadius: '4px'+ }}>+ <div style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, marginBottom: '6px' }}>+ SELECTED FILE:+ </div>+ <div style={{+ fontSize: '10px',+ color: BLOOMBERG_COLORS.WHITE,+ fontFamily: 'Consolas, monospace',+ wordBreak: 'break-all'+ }}>+ {selectedComp.config.imageUrl}+ </div>+ </div>+ {selectedComp.config.imageUrl.match(/\.(jpg|jpeg|png|gif|bmp|webp)$/i) && (+ <div style={{+ maxWidth: '100%',+ maxHeight: '300px',+ overflow: 'hidden',+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ borderRadius: '4px'+ }}>+ <img+ src={`file://${selectedComp.config.imageUrl}`}+ alt="Preview"+ style={{+ maxWidth: '100%',+ maxHeight: '300px',+ objectFit: 'contain'+ }}+ onError={(e) => {+ (e.target as HTMLImageElement).style.display = 'none';+ }}+ />+ </div>+ )}+ <div style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}>+ <button+ onClick={async () => {+ try {+ const selected = await open({+ multiple: false,+ filters: [{+ name: 'Images',+ extensions: ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp']+ }]+ });+ if (selected && typeof selected === 'string') {+ updateComponent(selectedComp.id, {+ config: { ...selectedComp.config, imageUrl: selected }+ });+ toast.success('Image updated successfully');+ }+ } catch (error) {+ console.error('Failed to select image:', error);+ toast.error('Failed to select image');+ }+ }}+ style={{+ background: BLOOMBERG_COLORS.CYAN,+ color: 'black',+ border: 'none',+ padding: '6px 12px',+ fontSize: '9px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ CHANGE IMAGE+ </button>+ <button+ onClick={() => {+ updateComponent(selectedComp.id, {+ config: { ...selectedComp.config, imageUrl: undefined }+ });+ toast.success('Image removed');+ }}+ style={{+ background: BLOOMBERG_COLORS.RED,+ color: 'white',+ border: 'none',+ padding: '6px 12px',+ fontSize: '9px',+ fontWeight: 'bold',+ cursor: 'pointer',+ fontFamily: 'Consolas, monospace'+ }}+ >+ REMOVE+ </button>+ </div>+ </div>+ ) : (+ <div>+ <ImageIcon size={48} style={{ color: BLOOMBERG_COLORS.CYAN, opacity: 0.3, margin: '0 auto 12px' }} />+ <div style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, marginBottom: '12px' }}>+ NO IMAGE SELECTED+ </div>+ <button+ onClick={async () => {+ try {+ const selected = await open({+ multiple: false,+ filters: [{+ name: 'Images',+ extensions: ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp']+ }]+ });+ if (selected && typeof selected === 'string') {+ updateComponent(selectedComp.id, {+ config: { ...selectedComp.config, imageUrl: selected }+ });+ toast.success('Image selected successfully');+ }+ } catch (error) {+ console.error('Failed to select image:', error);+ toast.error('Failed to select image');+ }+ }}+ style={{+ background: BLOOMBERG_COLORS.ORANGE,+ color: 'black',+ border: 'none',+ padding: '8px 16px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ margin: '0 auto',+ fontFamily: 'Consolas, monospace'+ }}+ >+ <Plus size={14} />+ SELECT IMAGE FROM COMPUTER+ </button>+ </div>+ )}+ </div>+ </div>+ )}++ {selectedComp.type === 'divider' && (+ <div style={{+ padding: '16px',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`+ }}>+ <hr style={{ border: 'none', borderTop: `1px solid ${BLOOMBERG_COLORS.BORDER}` }} />+ </div>+ )}++ {selectedComp.type === 'pagebreak' && (+ <div style={{+ padding: '24px',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px dashed ${BLOOMBERG_COLORS.BORDER}`,+ textAlign: 'center'+ }}>+ <FileX size={48} style={{ color: BLOOMBERG_COLORS.ORANGE, opacity: 0.3, margin: '0 auto 12px' }} />+ <div style={{ fontSize: '10px', color: BLOOMBERG_COLORS.GRAY }}>+ PAGE BREAK - Starts new page in PDF+ </div>+ </div>+ )}++ {selectedComp.type === 'coverpage' && (+ <div>+ <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>+ SUBTITLE+ </label>+ <input+ type="text"+ value={selectedComp.config.subtitle || ''}+ onChange={(e) => updateComponent(selectedComp.id, {+ config: { ...selectedComp.config, subtitle: e.target.value }+ })}+ style={{+ width: '100%',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.WHITE,+ padding: '8px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace',+ marginBottom: '12px'+ }}+ placeholder="Enter subtitle..."+ />+ <div style={{+ padding: '48px',+ background: selectedComp.config.backgroundColor || '#0a0a0a',+ border: `2px solid ${BLOOMBERG_COLORS.ORANGE}`,+ textAlign: 'center'+ }}>+ <BookOpen size={64} style={{ color: BLOOMBERG_COLORS.ORANGE, opacity: 0.5, margin: '0 auto 24px' }} />+ <div style={{ fontSize: '24px', color: BLOOMBERG_COLORS.ORANGE, fontWeight: 'bold', marginBottom: '12px' }}>+ COVER PAGE+ </div>+ <div style={{ fontSize: '12px', color: BLOOMBERG_COLORS.GRAY }}>+ {selectedComp.config.subtitle || 'Subtitle here'}+ </div>+ </div>+ </div>+ )}++ {selectedComp.type === 'section' && (+ <div>+ <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>+ SECTION TITLE+ </label>+ <input+ type="text"+ value={selectedComp.config.sectionTitle || ''}+ onChange={(e) => updateComponent(selectedComp.id, {+ config: { ...selectedComp.config, sectionTitle: e.target.value }+ })}+ style={{+ width: '100%',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.WHITE,+ padding: '8px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace',+ marginBottom: '12px'+ }}+ placeholder="Enter section title..."+ />+ <div style={{+ padding: selectedComp.config.padding || '15px',+ background: selectedComp.config.backgroundColor || '#f8f9fa',+ border: `3px solid ${selectedComp.config.borderColor || BLOOMBERG_COLORS.ORANGE}`+ }}>+ <div style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '8px', color: BLOOMBERG_COLORS.ORANGE }}>+ {selectedComp.config.sectionTitle || 'SECTION TITLE'}+ </div>+ <div style={{ fontSize: '10px', color: BLOOMBERG_COLORS.GRAY }}>+ Section content goes here. Add child components to populate this section.+ </div>+ </div>+ </div>+ )}++ {selectedComp.type === 'columns' && (+ <div>+ <label style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, display: 'block', marginBottom: '6px' }}>+ COLUMN COUNT+ </label>+ <select+ value={selectedComp.config.columnCount || 2}+ onChange={(e) => updateComponent(selectedComp.id, {+ config: { ...selectedComp.config, columnCount: parseInt(e.target.value) as 2 | 3 }+ })}+ style={{+ width: '100%',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ color: BLOOMBERG_COLORS.WHITE,+ padding: '8px',+ fontSize: '10px',+ fontFamily: 'Consolas, monospace',+ marginBottom: '12px'+ }}+ >+ <option value="2">2 COLUMNS</option>+ <option value="3">3 COLUMNS</option>+ </select>+ <div style={{+ display: 'grid',+ gridTemplateColumns: selectedComp.config.columnCount === 3 ? '1fr 1fr 1fr' : '1fr 1fr',+ gap: '12px',+ padding: '16px',+ background: BLOOMBERG_COLORS.DARK_BG,+ border: `1px solid ${BLOOMBERG_COLORS.BORDER}`+ }}>+ {[...Array(selectedComp.config.columnCount || 2)].map((_, i) => (+ <div+ key={i}+ style={{+ padding: '24px 12px',+ border: `1px dashed ${BLOOMBERG_COLORS.BORDER}`,+ textAlign: 'center',+ fontSize: '9px',+ color: BLOOMBERG_COLORS.GRAY+ }}+ >+ COLUMN {i + 1}+ </div>+ ))}+ </div>+ <div style={{ fontSize: '9px', color: BLOOMBERG_COLORS.GRAY, marginTop: '12px' }}>+ Add child components to populate columns+ </div>+ </div>+ )}+ </div>+ </div>+ </div>+ ) : (+ // Preview Mode+ <div style={{ flex: 1, overflow: 'auto', padding: '24px', backgroundColor: '#0d0d0d' }}>+ <div style={{+ maxWidth: '900px',+ margin: '0 auto',+ backgroundColor: '#ffffff',+ color: '#000000',+ padding: '48px',+ boxShadow: '0 4px 12px rgba(0,0,0,0.3)',+ fontFamily: 'Georgia, serif'+ }}>+ {/* Report Header */}+ <div style={{+ borderBottom: '2px solid #000',+ paddingBottom: '16px',+ marginBottom: '24px'+ }}>+ <h1 style={{ fontSize: '28px', fontWeight: 'bold', marginBottom: '8px' }}>+ {template.metadata.title}+ </h1>+ {template.metadata.company && (+ <div style={{ fontSize: '16px', color: '#333', marginBottom: '8px' }}>+ {template.metadata.company}+ </div>+ )}+ <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', color: '#666' }}>+ {template.metadata.author && <span>Author: {template.metadata.author}</span>}+ {template.metadata.date && <span>Date: {template.metadata.date}</span>}+ </div>+ </div>++ {/* Components */}+ {template.components.length === 0 ? (+ <div style={{+ textAlign: 'center',+ padding: '64px 24px',+ color: '#999'+ }}>+ <FileText size={64} style={{ margin: '0 auto 16px', opacity: 0.2 }} />+ <div style={{ fontSize: '14px' }}>No components added yet</div>+ <div style={{ fontSize: '12px', marginTop: '8px' }}>Add components from the left panel</div>+ </div>+ ) : (+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>+ {template.components.map((component) => (+ <div+ key={component.id}+ onClick={() => setSelectedComponent(component.id)}+ style={{+ cursor: 'pointer',+ padding: '12px',+ borderRadius: '4px',+ border: '1px solid transparent',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = '#f9f9f9';+ e.currentTarget.style.borderColor = BLOOMBERG_COLORS.CYAN;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.borderColor = 'transparent';+ }}+ >+ {component.type === 'coverpage' && (+ <div style={{+ minHeight: '400px',+ backgroundColor: component.config.backgroundColor || '#0a0a0a',+ border: `3px solid ${BLOOMBERG_COLORS.ORANGE}`,+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ padding: '48px',+ textAlign: 'center'+ }}>+ <h1 style={{ fontSize: '32px', fontWeight: 'bold', color: BLOOMBERG_COLORS.ORANGE, marginBottom: '16px' }}>+ {template.metadata.title}+ </h1>+ {component.config.subtitle && (+ <div style={{ fontSize: '16px', color: BLOOMBERG_COLORS.GRAY, marginBottom: '32px' }}>+ {component.config.subtitle}+ </div>+ )}+ <div style={{ fontSize: '12px', color: BLOOMBERG_COLORS.GRAY, marginTop: '32px' }}>+ {template.metadata.company}<br />+ {template.metadata.date}+ </div>+ </div>+ )}+ {component.type === 'pagebreak' && (+ <div style={{+ padding: '24px',+ border: '2px dashed #ddd',+ textAlign: 'center',+ backgroundColor: '#f9f9f9'+ }}>+ <FileX size={32} style={{ color: '#999', margin: '0 auto 8px' }} />+ <div style={{ fontSize: '11px', color: '#999' }}>PAGE BREAK</div>+ </div>+ )}+ {component.type === 'section' && (+ <div style={{+ padding: component.config.padding || '20px',+ backgroundColor: component.config.backgroundColor || '#f8f9fa',+ border: `3px solid ${component.config.borderColor || BLOOMBERG_COLORS.ORANGE}`,+ borderRadius: '4px'+ }}>+ <h3 style={{+ fontSize: '18px',+ fontWeight: 'bold',+ marginBottom: '12px',+ color: component.config.borderColor || BLOOMBERG_COLORS.ORANGE+ }}>+ {component.config.sectionTitle || 'SECTION'}+ </h3>+ <div style={{ fontSize: '12px', color: '#666' }}>+ {component.children && component.children.length > 0 ? (+ <div>Child components: {component.children.length}</div>+ ) : (+ <div>No child components added yet</div>+ )}+ </div>+ </div>+ )}+ {component.type === 'columns' && (+ <div style={{+ display: 'grid',+ gridTemplateColumns: component.config.columnCount === 3 ? '1fr 1fr 1fr' : '1fr 1fr',+ gap: '16px',+ padding: '12px',+ border: '1px solid #ddd',+ borderRadius: '4px',+ backgroundColor: '#fafafa'+ }}>+ {[...Array(component.config.columnCount || 2)].map((_, i) => (+ <div+ key={i}+ style={{+ padding: '16px',+ border: '1px dashed #ccc',+ minHeight: '100px',+ backgroundColor: 'white'+ }}+ >+ <div style={{ fontSize: '10px', color: '#999', textAlign: 'center' }}>+ Column {i + 1}+ </div>+ </div>+ ))}+ </div>+ )}+ {component.type === 'heading' && (+ <h2 style={{ fontSize: '22px', fontWeight: 'bold' }}>+ {component.content || 'Heading'}+ </h2>+ )}+ {component.type === 'subheading' && (+ <h3 style={{ fontSize: '18px', fontWeight: '600', color: '#444' }}>+ {component.content || 'Subheading'}+ </h3>+ )}+ {component.type === 'text' && (+ <p style={{ fontSize: '14px', lineHeight: '1.6' }}>+ {component.content || 'Text content...'}+ </p>+ )}+ {component.type === 'chart' && (+ <div style={{+ border: '1px solid #ddd',+ borderRadius: '4px',+ padding: '24px',+ backgroundColor: '#f5f5f5',+ textAlign: 'center'+ }}>+ <BarChart3 size={80} style={{ margin: '0 auto', color: '#3b82f6' }} />+ <div style={{ fontSize: '12px', color: '#666', marginTop: '8px' }}>+ {component.config.chartType || 'Chart'} Preview+ </div>+ </div>+ )}+ {component.type === 'table' && (+ <div style={{ border: '1px solid #ddd', borderRadius: '4px', overflow: 'hidden' }}>+ <table style={{ width: '100%', fontSize: '12px', borderCollapse: 'collapse' }}>+ <thead style={{ backgroundColor: '#f0f0f0' }}>+ <tr>+ {['Column 1', 'Column 2', 'Column 3'].map((col, i) => (+ <th key={i} style={{ padding: '8px 12px', textAlign: 'left', borderBottom: '1px solid #ddd' }}>+ {col}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ <tr>+ <td style={{ padding: '8px 12px' }}>Sample</td>+ <td style={{ padding: '8px 12px' }}>Sample</td>+ <td style={{ padding: '8px 12px' }}>Sample</td>+ </tr>+ </tbody>+ </table>+ </div>+ )}+ {component.type === 'image' && (+ <div style={{+ border: '1px solid #ddd',+ borderRadius: '4px',+ padding: component.config.imageUrl ? '12px' : '48px',+ backgroundColor: '#f5f5f5',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center'+ }}>+ {component.config.imageUrl ? (+ <img+ src={`file://${component.config.imageUrl}`}+ alt="Report Image"+ style={{+ maxWidth: '100%',+ maxHeight: '400px',+ objectFit: 'contain'+ }}+ onError={(e) => {+ const target = e.target as HTMLImageElement;+ target.style.display = 'none';+ const parent = target.parentElement;+ if (parent) {+ parent.innerHTML = '<div style="color: #999; text-align: center; padding: 24px;"><svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/></svg><div style="margin-top: 12px; font-size: 14px;">Image not found</div></div>';+ }+ }}+ />+ ) : (+ <ImageIcon size={64} style={{ color: '#999' }} />+ )}+ </div>+ )}+ {component.type === 'code' && (+ <pre style={{+ backgroundColor: '#1a1a1a',+ border: '1px solid #333',+ borderRadius: '4px',+ padding: '16px',+ overflow: 'auto',+ fontSize: '11px',+ color: '#10b981',+ fontFamily: 'Consolas, monospace'+ }}>+ <code>{component.content || '# Code block'}</code>+ </pre>+ )}+ {component.type === 'divider' && (+ <hr style={{ border: 'none', borderTop: '1px solid #ddd' }} />+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ </div>+ </div>+ );+};++export default ReportBuilderTab;diff --git a/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab_new.tsx.bak b/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab_new.tsx.baknew file mode 100644index 000000000..594a5c7af--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab_new.tsx.bak@@ -0,0 +1,200 @@+import React, { useState } from 'react';+import {+ FileText,+ Download,+ Save,+ Type,+ BarChart3,+ Table,+ Image as ImageIcon,+ Trash2,+ Copy,+ AlignLeft,+ Code,+ Minus,+ FolderOpen,+ Check,+ Plus,+ RefreshCw,+ Edit2,+ Move,+ Columns as ColumnsIcon,+ Layout,+ BookOpen,+ FileX+} from 'lucide-react';+import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragEndEvent } from '@dnd-kit/core';+import { arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';+import { CSS } from '@dnd-kit/utilities';+import { reportService, ReportTemplate, ReportComponent } from '@/services/reportService';+import { save, open } from '@tauri-apps/plugin-dialog';+import { toast } from 'sonner';+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';+import { Button } from '@/components/ui/button';++// Bloomberg color palette+const BLOOMBERG_COLORS = {+ ORANGE: '#FFA500',+ WHITE: '#FFFFFF',+ RED: '#ef4444',+ GREEN: '#10b981',+ YELLOW: '#fbbf24',+ GRAY: '#787878',+ BLUE: '#3b82f6',+ CYAN: '#06b6d4',+ DARK_BG: '#0a0a0a',+ PANEL_BG: '#1a1a1a',+ BORDER: '#333333',+};++// Sortable component wrapper+function SortableComponent({ component, onEdit, onDelete, onDuplicate, isSelected }: {+ component: ReportComponent;+ onEdit: (id: string) => void;+ onDelete: (id: string) => void;+ onDuplicate: (id: string) => void;+ isSelected: boolean;+}) {+ const {+ attributes,+ listeners,+ setNodeRef,+ transform,+ transition,+ } = useSortable({ id: component.id });++ const style = {+ transform: CSS.Transform.toString(transform),+ transition,+ };++ const getComponentIcon = () => {+ switch (component.type) {+ case 'heading': return <Type size={10} />;+ case 'text': return <AlignLeft size={10} />;+ case 'chart': return <BarChart3 size={10} />;+ case 'table': return <Table size={10} />;+ case 'image': return <ImageIcon size={10} />;+ case 'code': return <Code size={10} />;+ case 'divider': return <Minus size={10} />;+ default: return <FileText size={10} />;+ }+ };++ return (+ <div+ ref={setNodeRef}+ style={{+ ...style,+ backgroundColor: isSelected ? '#2a2a2a' : 'transparent',+ borderBottom: `1px solid ${BLOOMBERG_COLORS.BORDER}`,+ padding: '6px 8px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ cursor: 'pointer',+ borderLeft: isSelected ? `2px solid ${BLOOMBERG_COLORS.ORANGE}` : 'none'+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1 }}>+ <div {...attributes} {...listeners} style={{ color: BLOOMBERG_COLORS.GRAY, cursor: 'move', display: 'flex' }}>+ <Move size={12} />+ </div>+ <div style={{ color: BLOOMBERG_COLORS.CYAN, display: 'flex' }}>+ {getComponentIcon()}+ </div>+ <span style={{ color: BLOOMBERG_COLORS.ORANGE, fontSize: '9px', fontWeight: 'bold' }}>+ {component.type.toUpperCase()}+ </span>+ <span style={{ color: BLOOMBERG_COLORS.GRAY, fontSize: '9px', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {component.content ? component.content.substring(0, 20) : 'Empty'}+ </span>+ </div>+ <div style={{ display: 'flex', gap: '4px' }}>+ <button+ onClick={(e) => { e.stopPropagation(); onEdit(component.id); }}+ style={{+ background: 'transparent',+ border: 'none',+ color: BLOOMBERG_COLORS.BLUE,+ cursor: 'pointer',+ padding: '2px',+ display: 'flex'+ }}+ title="Edit"+ >+ <Edit2 size={10} />+ </button>+ <button+ onClick={(e) => { e.stopPropagation(); onDuplicate(component.id); }}+ style={{+ background: 'transparent',+ border: 'none',+ color: BLOOMBERG_COLORS.GREEN,+ cursor: 'pointer',+ padding: '2px',+ display: 'flex'+ }}+ title="Duplicate"+ >+ <Copy size={10} />+ </button>+ <button+ onClick={(e) => { e.stopPropagation(); onDelete(component.id); }}+ style={{+ background: 'transparent',+ border: 'none',+ color: BLOOMBERG_COLORS.RED,+ cursor: 'pointer',+ padding: '2px',+ display: 'flex'+ }}+ title="Delete"+ >+ <Trash2 size={10} />+ </button>+ </div>+ </div>+ );+}++const ReportBuilderTab: React.FC = () => {+ const [currentTime, setCurrentTime] = useState(new Date());+ const [template, setTemplate] = useState<ReportTemplate>({+ id: `report-${Date.now()}`,+ name: 'New Financial Report',+ description: 'Professional financial research report',+ components: [],+ metadata: {+ author: '',+ company: '',+ date: new Date().toISOString().split('T')[0],+ title: 'Financial Research Report',+ },+ styles: {+ pageSize: 'A4',+ orientation: 'portrait',+ margins: '20mm',+ headerFooter: true,+ },+ });++ const [selectedComponent, setSelectedComponent] = useState<string | null>(null);+ const [isGenerating, setIsGenerating] = useState(false);+ const [isSaving, setIsSaving] = useState(false);+ const [showSuccessDialog, setShowSuccessDialog] = useState(false);+ const [generatedPdfPath, setGeneratedPdfPath] = useState<string>('');++ const sensors = useSensors(+ useSensor(PointerSensor),+ useSensor(KeyboardSensor, {+ coordinateGetter: sortableKeyboardCoordinates,+ })+ );++ // Update time+ React.useEffect(() => {+ const timer = setInterval(() => setCurrentTime(new Date()), 1000);+ return () => clearInterval(timer);+ }, []);+diff --git a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsxindex e79ce6ade..41f849a7a 100644--- a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx@@ -7,10 +7,11 @@ import { terminalThemeService, FONT_FAMILIES, COLOR_THEMES, FontSettings } fromimport { getWebSocketManager, ConnectionStatus, getAvailableProviders } from '@/services/websocket';import { useWebSocketManager } from '@/hooks/useWebSocket';import { DataSourcesPanel } from '@/components/settings/DataSourcesPanel';+import { BacktestingProvidersPanel } from '@/components/settings/BacktestingProvidersPanel';export default function SettingsTab() {const { theme, updateTheme, resetTheme, colors, fontSize: themeFontSize, fontFamily: themeFontFamily, fontWeight: themeFontWeight, fontStyle } = useTerminalTheme();- const [activeSection, setActiveSection] = useState<'credentials' | 'profile' | 'terminal' | 'notifications' | 'llm' | 'dataConnections'>('credentials');+ const [activeSection, setActiveSection] = useState<'credentials' | 'profile' | 'terminal' | 'notifications' | 'llm' | 'dataConnections' | 'backtesting'>('credentials');const [credentials, setCredentials] = useState<Credential[]>([]);const [showPasswords, setShowPasswords] = useState<Record<number, boolean>>({});const [loading, setLoading] = useState(false);@@ -613,6 +614,7 @@ export default function SettingsTab() {{ id: 'credentials', icon: Lock, label: 'Credentials' },{ id: 'llm', icon: Bot, label: 'LLM Configuration' },{ id: 'dataConnections', icon: Database, label: 'Data Sources' },+ { id: 'backtesting', icon: Activity, label: 'Backtesting Providers' },{ id: 'profile', icon: User, label: 'User Profile' },{ id: 'terminal', icon: Terminal, label: 'Terminal Config' },{ id: 'notifications', icon: Bell, label: 'Notifications' }@@ -1322,6 +1324,20 @@ export default function SettingsTab() {<DataSourcesPanel colors={colors} />)}+ {/* Backtesting Providers Section */}+ {activeSection === 'backtesting' && (+ <BacktestingProvidersPanel colors={{+ background: colors.background,+ surface: colors.panel,+ text: colors.text,+ textSecondary: colors.textMuted,+ border: colors.textMuted,+ accent: colors.accent,+ success: colors.success,+ error: colors.alert+ }} />+ )}+{/* Other sections */}{activeSection === 'profile' && <div style={{ color: colors.text }}>User Profile section (implementation same as before)</div>}{activeSection === 'notifications' && <div style={{ color: colors.text }}>Notifications section (implementation same as before)</div>}diff --git a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsxnew file mode 100644index 000000000..09689f58d--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx@@ -0,0 +1,414 @@+// File: src/components/tabs/TradingTab.tsx+// Unified trading tab with multi-provider support and paper trading++import React, { useState, useEffect } from 'react';+import { Activity, TrendingUp } from 'lucide-react';+import { ProviderSwitcher } from './trading/ProviderSwitcher';+import { PaperTradingPanel } from './trading/PaperTradingPanel';+import { TickerDisplay } from './trading/TickerDisplay';+import { OrderBook } from './trading/OrderBook';+import { TradesFeed } from './trading/TradesFeed';+import { OrderForm } from './trading/OrderForm';+import { PositionsTable } from './trading/PositionsTable';+import { useProviderContext } from '../../contexts/ProviderContext';+import { usePaperTrading } from '../../hooks/usePaperTrading';+import { useWebSocket } from '../../hooks/useWebSocket';+import { getWebSocketManager } from '../../services/websocket';+import type { OrderRequest } from '../../types/trading';++// Symbol configurations per provider+const KRAKEN_PAIRS = ['BTC/USD', 'ETH/USD', 'SOL/USD', 'AVAX/USD', 'MATIC/USD'];+const HYPERLIQUID_SYMBOLS = ['BTC', 'ETH', 'SOL', 'AVAX', 'MATIC'];++// Bloomberg color scheme+const BLOOMBERG_COLORS = {+ ORANGE: '#ea580c',+ WHITE: '#ffffff',+ RED: '#dc2626',+ GREEN: '#10b981',+ GRAY: '#525252',+ DARK_BG: '#0d0d0d',+ PANEL_BG: '#1a1a1a',+ CYAN: '#22d3ee',+ YELLOW: '#fbbf24'+};++export function TradingTab() {+ const { activeProvider } = useProviderContext();+ const [portfolioId, setPortfolioId] = useState<string | null>(null);+ const [isResetting, setIsResetting] = useState(false);+ const [currentTime, setCurrentTime] = useState(new Date());+ const [isConnected, setIsConnected] = useState(false);++ // Get symbols based on active provider+ const popularSymbols = activeProvider === 'kraken' ? KRAKEN_PAIRS : HYPERLIQUID_SYMBOLS;+ const [selectedSymbol, setSelectedSymbol] = useState(popularSymbols[0]);++ // Initialize WebSocket connection for active provider+ useEffect(() => {+ const manager = getWebSocketManager();++ const initProvider = async () => {+ try {+ console.log(`[TradingTab] Initializing ${activeProvider} provider...`);++ if (activeProvider === 'kraken') {+ manager.setProviderConfig('kraken', {+ provider_name: 'kraken',+ enabled: true,+ endpoint: 'wss://ws.kraken.com/v2'+ });+ await manager.connect('kraken');+ console.log('[TradingTab] Kraken connected successfully');+ } else if (activeProvider === 'hyperliquid') {+ manager.setProviderConfig('hyperliquid', {+ provider_name: 'hyperliquid',+ enabled: true,+ endpoint: 'wss://api.hyperliquid.xyz/ws'+ });+ await manager.connect('hyperliquid');+ console.log('[TradingTab] HyperLiquid connected successfully');+ }+ setIsConnected(true);+ } catch (error) {+ console.error(`[TradingTab] Failed to connect to ${activeProvider}:`, error);+ setIsConnected(false);+ }+ };++ initProvider();+ }, [activeProvider]);++ // Update selected symbol when provider changes+ useEffect(() => {+ const symbols = activeProvider === 'kraken' ? KRAKEN_PAIRS : HYPERLIQUID_SYMBOLS;+ setSelectedSymbol(symbols[0]);+ }, [activeProvider]);++ // Update clock+ useEffect(() => {+ const timer = setInterval(() => {+ setCurrentTime(new Date());+ }, 1000);+ return () => clearInterval(timer);+ }, []);++ // Paper trading hook+ const {+ portfolio,+ positions,+ orders,+ isLoading: isPaperTradingLoading,+ placeOrder,+ closePosition,+ resetPortfolio+ } = usePaperTrading({ portfolioId: portfolioId || undefined });++ // Get current price from ticker+ const { message: tickerMessage } = useWebSocket(+ isConnected ? `${activeProvider}.ticker.${selectedSymbol}` : null,+ null,+ { autoSubscribe: true }+ );++ const currentPrice = tickerMessage?.data?.last || tickerMessage?.data?.close || tickerMessage?.data?.mid;++ // Handle order placement+ const handlePlaceOrder = async (order: OrderRequest) => {+ if (!portfolioId) {+ throw new Error('Paper trading not enabled');+ }++ const result = await placeOrder(order);++ if (!result.success) {+ throw new Error(result.error || 'Failed to place order');+ }+ };++ // Handle position close+ const handleClosePosition = async (positionId: string) => {+ await closePosition(positionId);+ };++ // Handle portfolio reset+ const handleReset = async () => {+ if (!portfolioId) return;++ setIsResetting(true);+ try {+ await resetPortfolio();+ } finally {+ setIsResetting(false);+ }+ };++ const { ORANGE, WHITE, RED, GREEN, GRAY, DARK_BG, PANEL_BG, CYAN } = BLOOMBERG_COLORS;++ return (+ <div style={{+ height: '100%',+ backgroundColor: DARK_BG,+ color: WHITE,+ fontFamily: 'Consolas, monospace',+ overflow: 'hidden',+ display: 'flex',+ flexDirection: 'column'+ }}>+ <style>{`+ *::-webkit-scrollbar { width: 8px; height: 8px; }+ *::-webkit-scrollbar-track { background: #1a1a1a; }+ *::-webkit-scrollbar-thumb { background: #404040; border-radius: 4px; }+ *::-webkit-scrollbar-thumb:hover { background: #525252; }+ `}</style>++ {/* Header Bar */}+ <div style={{+ backgroundColor: PANEL_BG,+ borderBottom: `1px solid ${GRAY}`,+ padding: '8px 12px',+ flexShrink: 0+ }}>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <TrendingUp size={16} style={{ color: ORANGE }} />+ <span style={{ color: ORANGE, fontWeight: 'bold', fontSize: '14px' }}>+ FINCEPT TRADING TERMINAL+ </span>+ <span style={{ color: WHITE }}>|</span>+ <span style={{ color: portfolioId ? GREEN : GRAY, fontSize: '10px' }}>+ ● {portfolioId ? 'PAPER TRADING' : 'VIEW ONLY'}+ </span>+ <span style={{ color: WHITE }}>|</span>+ <span style={{ color: CYAN, fontSize: '11px' }}>+ {currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC+ </span>+ </div>++ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Activity size={14} style={{ color: GREEN }} />+ <span style={{ color: GREEN, fontSize: '10px', fontWeight: 'bold' }}>+ LIVE MARKET DATA+ </span>+ </div>+ </div>+ </div>++ {/* Provider Switcher */}+ <ProviderSwitcher />++ {/* Paper Trading Panel */}+ <PaperTradingPanel+ portfolioId={portfolioId}+ balance={portfolio?.balance}+ totalPnL={portfolio?.totalPnL}+ onPortfolioChange={setPortfolioId}+ onReset={handleReset}+ isResetting={isResetting}+ />++ {/* Symbol Selector */}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ backgroundColor: PANEL_BG,+ padding: '8px 12px',+ borderBottom: `1px solid ${GRAY}`,+ flexShrink: 0+ }}>+ <span style={{ fontSize: '10px', color: GRAY, fontWeight: 'bold', textTransform: 'uppercase' }}>+ {activeProvider === 'kraken' ? 'Pair:' : 'Symbol:'}+ </span>+ <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>+ {popularSymbols.map(symbol => (+ <button+ key={symbol}+ onClick={() => setSelectedSymbol(symbol)}+ style={{+ padding: '4px 12px',+ fontSize: '11px',+ fontWeight: 'bold',+ textTransform: 'uppercase',+ backgroundColor: selectedSymbol === symbol ? ORANGE : '#2d2d2d',+ color: selectedSymbol === symbol ? WHITE : GRAY,+ border: selectedSymbol === symbol ? `1px solid ${ORANGE}` : '1px solid #404040',+ cursor: 'pointer',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ if (selectedSymbol !== symbol) {+ e.currentTarget.style.backgroundColor = '#404040';+ e.currentTarget.style.borderColor = GRAY;+ }+ }}+ onMouseLeave={(e) => {+ if (selectedSymbol !== symbol) {+ e.currentTarget.style.backgroundColor = '#2d2d2d';+ e.currentTarget.style.borderColor = '#404040';+ }+ }}+ >+ {symbol}+ </button>+ ))}+ </div>+ <input+ type="text"+ placeholder={activeProvider === 'kraken' ? 'BTC/USD' : 'BTC'}+ value={selectedSymbol}+ onChange={(e) => setSelectedSymbol(e.target.value.toUpperCase())}+ style={{+ marginLeft: '12px',+ padding: '4px 8px',+ backgroundColor: '#2d2d2d',+ color: WHITE,+ border: '1px solid #404040',+ fontSize: '11px',+ outline: 'none',+ width: '150px'+ }}+ onFocus={(e) => e.currentTarget.style.borderColor = ORANGE}+ onBlur={(e) => e.currentTarget.style.borderColor = '#404040'}+ />+ <span style={{ fontSize: '10px', color: isConnected ? GREEN : GRAY, marginLeft: '12px' }}>+ {isConnected ? '● CONNECTED' : '● CONNECTING...'}+ </span>+ </div>++ {/* Main Trading Layout */}+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>+ {/* Left Panel - Ticker & Trades */}+ <div style={{+ width: '280px',+ display: 'flex',+ flexDirection: 'column',+ borderRight: `1px solid ${GRAY}`,+ backgroundColor: PANEL_BG+ }}>+ <TickerDisplay symbol={selectedSymbol} provider={activeProvider} />+ <TradesFeed symbol={selectedSymbol} provider={activeProvider} />+ </div>++ {/* Center Panel - Chart Placeholder */}+ <div style={{+ flex: 1,+ display: 'flex',+ flexDirection: 'column',+ backgroundColor: DARK_BG+ }}>+ <div style={{+ flex: 1,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ borderBottom: `1px solid ${GRAY}`+ }}>+ <div style={{ textAlign: 'center', color: GRAY }}>+ <div style={{ fontSize: '48px', marginBottom: '12px' }}>📊</div>+ <div style={{ fontSize: '14px', fontWeight: 'bold', color: WHITE, marginBottom: '8px' }}>+ ADVANCED CHARTING+ </div>+ <div style={{ fontSize: '11px', color: GRAY }}>+ TradingView Integration Coming Soon+ </div>+ <div style={{ fontSize: '10px', marginTop: '8px', color: GRAY }}>+ Showing {selectedSymbol} on {activeProvider.toUpperCase()}+ </div>+ </div>+ </div>++ {/* Positions Table (if paper trading enabled) */}+ {portfolioId && (+ <PositionsTable+ positions={positions}+ onClosePosition={handleClosePosition}+ isLoading={isPaperTradingLoading}+ />+ )}+ </div>++ {/* Right Panel - Order Book & Order Form */}+ <div style={{+ width: '320px',+ display: 'flex',+ flexDirection: 'column',+ borderLeft: `1px solid ${GRAY}`,+ backgroundColor: PANEL_BG+ }}>+ <OrderBook symbol={selectedSymbol} provider={activeProvider} depth={25} />++ {/* Order Form (only if paper trading enabled) */}+ {portfolioId && (+ <OrderForm+ symbol={selectedSymbol}+ currentPrice={currentPrice}+ onPlaceOrder={handlePlaceOrder}+ isLoading={isPaperTradingLoading}+ />+ )}++ {/* Paper Trading Disabled Message */}+ {!portfolioId && (+ <div style={{+ backgroundColor: DARK_BG,+ borderTop: `1px solid ${GRAY}`,+ padding: '16px',+ textAlign: 'center'+ }}>+ <div style={{ fontSize: '12px', color: GRAY, marginBottom: '8px', fontWeight: 'bold' }}>+ PAPER TRADING DISABLED+ </div>+ <div style={{ fontSize: '10px', color: GRAY, lineHeight: '1.4' }}>+ Enable paper trading to place orders and manage positions with $100,000 virtual balance+ </div>+ </div>+ )}+ </div>+ </div>++ {/* Status Bar / Footer */}+ <div style={{+ borderTop: `1px solid ${GRAY}`,+ backgroundColor: PANEL_BG,+ padding: '6px 12px',+ fontSize: '9px',+ color: GRAY,+ flexShrink: 0+ }}>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ flexWrap: 'wrap',+ gap: '8px'+ }}>+ <span>+ Fincept Trading Terminal v1.0.0 | WebSocket real-time data via {activeProvider.toUpperCase()}+ </span>+ <span style={{ whiteSpace: 'nowrap' }}>+ {portfolioId ? (+ <>+ <span style={{ color: GREEN }}>● PAPER TRADING ACTIVE</span>+ <span style={{ marginLeft: '8px' }}>|</span>+ <span style={{ marginLeft: '8px' }}>+ {positions.filter(p => p.status === 'open').length} Open Position{positions.filter(p => p.status === 'open').length !== 1 ? 's' : ''}+ </span>+ <span style={{ marginLeft: '8px' }}>|</span>+ <span style={{ marginLeft: '8px' }}>+ {orders.filter(o => o.status === 'pending').length} Pending Order{orders.filter(o => o.status === 'pending').length !== 1 ? 's' : ''}+ </span>+ </>+ ) : (+ <>+ <span style={{ color: GRAY }}>● VIEW ONLY MODE</span>+ <span style={{ marginLeft: '8px' }}>|</span>+ <span style={{ marginLeft: '8px' }}>Enable paper trading to trade</span>+ </>+ )}+ </span>+ </div>+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/BacktestNode.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/BacktestNode.tsxnew file mode 100644index 000000000..d96c0a4b7--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/BacktestNode.tsx@@ -0,0 +1,369 @@+/**+ * Backtest Node+ *+ * ReactFlow node for running backtests in the workflow editor.+ * Connects to strategy inputs and outputs backtest results.+ */++import React, { useState } from 'react';+import { Handle, Position } from 'reactflow';+import { Activity, Play, Settings, Check, AlertCircle, TrendingUp, Loader } from 'lucide-react';+import { backtestingService } from '@/services/backtesting/BacktestingService';+import { BacktestRequest, BacktestResult } from '@/services/backtesting/interfaces/types';++interface BacktestNodeProps {+ data: {+ label: string;+ strategyCode?: string;+ startDate?: string;+ endDate?: string;+ initialCapital?: number;+ status: 'idle' | 'running' | 'completed' | 'error';+ result?: BacktestResult;+ error?: string;+ onStrategyChange?: (code: string) => void;+ onConfigChange?: (config: any) => void;+ onExecute?: () => Promise<void>;+ };+ selected: boolean;+}++const BacktestNode: React.FC<BacktestNodeProps> = ({ data, selected }) => {+ const [showSettings, setShowSettings] = useState(false);+ const [localConfig, setLocalConfig] = useState({+ startDate: data.startDate || new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],+ endDate: data.endDate || new Date().toISOString().split('T')[0],+ initialCapital: data.initialCapital || 100000,+ });++ const handleSaveSettings = () => {+ if (data.onConfigChange) {+ data.onConfigChange(localConfig);+ }+ setShowSettings(false);+ };++ const handleRunBacktest = async () => {+ if (data.onExecute) {+ await data.onExecute();+ }+ };++ const getStatusColor = () => {+ switch (data.status) {+ case 'running': return '#3b82f6';+ case 'completed': return '#10b981';+ case 'error': return '#ef4444';+ default: return '#6b7280';+ }+ };++ const getStatusIcon = () => {+ switch (data.status) {+ case 'running': return <Loader size={14} className="animate-spin" color="#3b82f6" />;+ case 'completed': return <Check size={14} color="#10b981" />;+ case 'error': return <AlertCircle size={14} color="#ef4444" />;+ default: return <Activity size={14} color="#6b7280" />;+ }+ };++ const formatPerformance = () => {+ if (!data.result) return null;+ const perf = data.result.performance;+ return {+ totalReturn: (perf.totalReturn * 100).toFixed(2) + '%',+ sharpe: perf.sharpeRatio.toFixed(2),+ maxDD: (perf.maxDrawdown * 100).toFixed(2) + '%',+ trades: perf.totalTrades,+ };+ };++ const performance = formatPerformance();++ return (+ <div style={{+ background: selected ? '#252525' : '#1a1a1a',+ border: `2px solid ${selected ? '#3b82f6' : getStatusColor()}`,+ borderRadius: '8px',+ minWidth: '300px',+ maxWidth: '400px',+ fontFamily: 'Consolas, monospace',+ boxShadow: selected ? `0 0 16px #3b82f660` : '0 2px 8px rgba(0,0,0,0.3)',+ position: 'relative'+ }}>+ {/* Input Handle - Strategy */}+ <Handle+ type="target"+ position={Position.Left}+ id="strategy"+ style={{+ background: '#8b5cf6',+ width: '12px',+ height: '12px',+ border: '2px solid #1a1a1a',+ top: '30%'+ }}+ />++ {/* Output Handle - Results */}+ <Handle+ type="source"+ position={Position.Right}+ id="results"+ style={{+ background: '#10b981',+ width: '12px',+ height: '12px',+ border: '2px solid #1a1a1a',+ }}+ />++ {/* Header */}+ <div style={{+ padding: '12px',+ borderBottom: '1px solid #2a2a2a',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ background: '#1f1f1f'+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Activity size={16} color={getStatusColor()} />+ <span style={{ color: '#e5e7eb', fontSize: '12px', fontWeight: 'bold' }}>+ {data.label}+ </span>+ </div>+ <div style={{ display: 'flex', gap: '6px' }}>+ {getStatusIcon()}+ <Settings+ size={14}+ color="#9ca3af"+ style={{ cursor: 'pointer' }}+ onClick={() => setShowSettings(!showSettings)}+ />+ </div>+ </div>++ {/* Settings Panel */}+ {showSettings && (+ <div style={{+ padding: '12px',+ borderBottom: '1px solid #2a2a2a',+ background: '#1a1a1a'+ }}>+ <div style={{ marginBottom: '8px' }}>+ <label style={{ color: '#9ca3af', fontSize: '10px', display: 'block', marginBottom: '4px' }}>+ Start Date+ </label>+ <input+ type="date"+ value={localConfig.startDate}+ onChange={(e) => setLocalConfig({ ...localConfig, startDate: e.target.value })}+ style={{+ width: '100%',+ padding: '6px',+ background: '#252525',+ border: '1px solid #3a3a3a',+ borderRadius: '4px',+ color: '#e5e7eb',+ fontSize: '10px'+ }}+ />+ </div>++ <div style={{ marginBottom: '8px' }}>+ <label style={{ color: '#9ca3af', fontSize: '10px', display: 'block', marginBottom: '4px' }}>+ End Date+ </label>+ <input+ type="date"+ value={localConfig.endDate}+ onChange={(e) => setLocalConfig({ ...localConfig, endDate: e.target.value })}+ style={{+ width: '100%',+ padding: '6px',+ background: '#252525',+ border: '1px solid #3a3a3a',+ borderRadius: '4px',+ color: '#e5e7eb',+ fontSize: '10px'+ }}+ />+ </div>++ <div style={{ marginBottom: '8px' }}>+ <label style={{ color: '#9ca3af', fontSize: '10px', display: 'block', marginBottom: '4px' }}>+ Initial Capital ($)+ </label>+ <input+ type="number"+ value={localConfig.initialCapital}+ onChange={(e) => setLocalConfig({ ...localConfig, initialCapital: Number(e.target.value) })}+ style={{+ width: '100%',+ padding: '6px',+ background: '#252525',+ border: '1px solid #3a3a3a',+ borderRadius: '4px',+ color: '#e5e7eb',+ fontSize: '10px'+ }}+ />+ </div>++ <button+ onClick={handleSaveSettings}+ style={{+ width: '100%',+ padding: '6px',+ background: '#3b82f6',+ color: 'white',+ border: 'none',+ borderRadius: '4px',+ fontSize: '10px',+ cursor: 'pointer',+ fontWeight: 'bold'+ }}+ >+ Save Configuration+ </button>+ </div>+ )}++ {/* Content */}+ <div style={{ padding: '12px' }}>+ {/* Configuration Display */}+ <div style={{ marginBottom: '12px' }}>+ <div style={{ fontSize: '10px', color: '#9ca3af', marginBottom: '6px' }}>+ Configuration:+ </div>+ <div style={{ fontSize: '9px', color: '#d1d5db', fontFamily: 'monospace' }}>+ {localConfig.startDate} → {localConfig.endDate}+ </div>+ <div style={{ fontSize: '9px', color: '#d1d5db', fontFamily: 'monospace' }}>+ Capital: ${localConfig.initialCapital.toLocaleString()}+ </div>+ </div>++ {/* Results Display */}+ {performance && data.status === 'completed' && (+ <div style={{+ padding: '8px',+ background: '#1f1f1f',+ borderRadius: '4px',+ marginBottom: '8px'+ }}>+ <div style={{ fontSize: '10px', color: '#9ca3af', marginBottom: '6px', display: 'flex', alignItems: 'center', gap: '4px' }}>+ <TrendingUp size={12} />+ Results:+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px', fontSize: '9px' }}>+ <div>+ <div style={{ color: '#6b7280' }}>Total Return</div>+ <div style={{ color: performance.totalReturn.startsWith('-') ? '#ef4444' : '#10b981', fontWeight: 'bold' }}>+ {performance.totalReturn}+ </div>+ </div>+ <div>+ <div style={{ color: '#6b7280' }}>Sharpe Ratio</div>+ <div style={{ color: '#e5e7eb', fontWeight: 'bold' }}>+ {performance.sharpe}+ </div>+ </div>+ <div>+ <div style={{ color: '#6b7280' }}>Max DD</div>+ <div style={{ color: '#ef4444', fontWeight: 'bold' }}>+ {performance.maxDD}+ </div>+ </div>+ <div>+ <div style={{ color: '#6b7280' }}>Trades</div>+ <div style={{ color: '#e5e7eb', fontWeight: 'bold' }}>+ {performance.trades}+ </div>+ </div>+ </div>+ </div>+ )}++ {/* Error Display */}+ {data.error && data.status === 'error' && (+ <div style={{+ padding: '8px',+ background: '#3a0a0a',+ border: '1px solid #ef4444',+ borderRadius: '4px',+ marginBottom: '8px'+ }}>+ <div style={{ fontSize: '10px', color: '#ef4444', marginBottom: '4px' }}>+ Error:+ </div>+ <div style={{ fontSize: '9px', color: '#fca5a5' }}>+ {data.error}+ </div>+ </div>+ )}++ {/* Run Button */}+ <button+ onClick={handleRunBacktest}+ disabled={data.status === 'running' || !data.strategyCode}+ style={{+ width: '100%',+ padding: '8px',+ background: data.status === 'running' ? '#6b7280' : '#3b82f6',+ color: 'white',+ border: 'none',+ borderRadius: '4px',+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: data.status === 'running' || !data.strategyCode ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ opacity: data.status === 'running' || !data.strategyCode ? 0.6 : 1+ }}+ >+ {data.status === 'running' ? (+ <>+ <Loader size={14} className="animate-spin" />+ Running Backtest...+ </>+ ) : (+ <>+ <Play size={14} />+ Run Backtest+ </>+ )}+ </button>+ </div>++ {/* Handle Labels */}+ <div style={{+ position: 'absolute',+ left: '-60px',+ top: '30%',+ transform: 'translateY(-50%)',+ fontSize: '9px',+ color: '#6b7280',+ whiteSpace: 'nowrap'+ }}>+ Strategy+ </div>+ <div style={{+ position: 'absolute',+ right: '-50px',+ top: '50%',+ transform: 'translateY(-50%)',+ fontSize: '9px',+ color: '#6b7280',+ whiteSpace: 'nowrap'+ }}>+ Results+ </div>+ </div>+ );+};++export default BacktestNode;diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/OptimizationNode.tsx b/fincept-terminal-desktop/src/components/tabs/node-editor/OptimizationNode.tsxnew file mode 100644index 000000000..29c128810--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/OptimizationNode.tsx@@ -0,0 +1,501 @@+/**+ * Optimization Node+ *+ * ReactFlow node for running parameter optimization in workflows.+ * Supports grid search and genetic algorithms.+ */++import React, { useState } from 'react';+import { Handle, Position } from 'reactflow';+import { Zap, Play, Settings, Check, AlertCircle, Loader, TrendingUp } from 'lucide-react';+import { backtestingService } from '@/services/backtesting/BacktestingService';+import { OptimizationRequest, OptimizationResult } from '@/services/backtesting/interfaces/types';++interface OptimizationNodeProps {+ data: {+ label: string;+ strategyCode?: string;+ optimizationTarget: 'sharpe_ratio' | 'total_return' | 'sortino_ratio';+ parameterRanges?: Record<string, { min: number; max: number; step: number }>;+ method: 'grid' | 'genetic';+ status: 'idle' | 'running' | 'completed' | 'error';+ result?: OptimizationResult;+ error?: string;+ onConfigChange?: (config: any) => void;+ onExecute?: () => Promise<void>;+ };+ selected: boolean;+}++const OptimizationNode: React.FC<OptimizationNodeProps> = ({ data, selected }) => {+ const [showSettings, setShowSettings] = useState(false);+ const [localConfig, setLocalConfig] = useState({+ target: data.optimizationTarget || 'sharpe_ratio',+ method: data.method || 'grid',+ maxIterations: 100,+ });++ const [paramRanges, setParamRanges] = useState<Record<string, { min: number; max: number; step: number }>>(+ data.parameterRanges || {+ fast_period: { min: 10, max: 50, step: 5 },+ slow_period: { min: 100, max: 200, step: 10 },+ }+ );++ const handleSaveSettings = () => {+ if (data.onConfigChange) {+ data.onConfigChange({ ...localConfig, parameterRanges: paramRanges });+ }+ setShowSettings(false);+ };++ const handleRunOptimization = async () => {+ if (data.onExecute) {+ await data.onExecute();+ }+ };++ const getStatusColor = () => {+ switch (data.status) {+ case 'running': return '#f59e0b';+ case 'completed': return '#10b981';+ case 'error': return '#ef4444';+ default: return '#6b7280';+ }+ };++ const getStatusIcon = () => {+ switch (data.status) {+ case 'running': return <Loader size={14} className="animate-spin" color="#f59e0b" />;+ case 'completed': return <Check size={14} color="#10b981" />;+ case 'error': return <AlertCircle size={14} color="#ef4444" />;+ default: return <Zap size={14} color="#6b7280" />;+ }+ };++ const formatBestParams = () => {+ if (!data.result || !data.result.bestParameters) return null;+ return Object.entries(data.result.bestParameters)+ .map(([key, value]) => `${key}: ${value}`)+ .join(', ');+ };++ const addParameterRange = () => {+ const paramName = prompt('Parameter name:');+ if (paramName) {+ setParamRanges({+ ...paramRanges,+ [paramName]: { min: 0, max: 100, step: 1 },+ });+ }+ };++ return (+ <div style={{+ background: selected ? '#252525' : '#1a1a1a',+ border: `2px solid ${selected ? '#f59e0b' : getStatusColor()}`,+ borderRadius: '8px',+ minWidth: '320px',+ maxWidth: '450px',+ fontFamily: 'Consolas, monospace',+ boxShadow: selected ? `0 0 16px #f59e0b60` : '0 2px 8px rgba(0,0,0,0.3)',+ position: 'relative'+ }}>+ {/* Input Handle - Strategy */}+ <Handle+ type="target"+ position={Position.Left}+ id="strategy"+ style={{+ background: '#8b5cf6',+ width: '12px',+ height: '12px',+ border: '2px solid #1a1a1a',+ top: '30%'+ }}+ />++ {/* Output Handle - Best Parameters */}+ <Handle+ type="source"+ position={Position.Right}+ id="best_params"+ style={{+ background: '#f59e0b',+ width: '12px',+ height: '12px',+ border: '2px solid #1a1a1a',+ top: '30%'+ }}+ />++ {/* Output Handle - All Results */}+ <Handle+ type="source"+ position={Position.Right}+ id="all_results"+ style={{+ background: '#10b981',+ width: '12px',+ height: '12px',+ border: '2px solid #1a1a1a',+ top: '60%'+ }}+ />++ {/* Header */}+ <div style={{+ padding: '12px',+ borderBottom: '1px solid #2a2a2a',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ background: 'linear-gradient(135deg, #1f1f1f 0%, #2a1f0f 100%)'+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Zap size={16} color={getStatusColor()} />+ <span style={{ color: '#e5e7eb', fontSize: '12px', fontWeight: 'bold' }}>+ {data.label}+ </span>+ </div>+ <div style={{ display: 'flex', gap: '6px' }}>+ {getStatusIcon()}+ <Settings+ size={14}+ color="#9ca3af"+ style={{ cursor: 'pointer' }}+ onClick={() => setShowSettings(!showSettings)}+ />+ </div>+ </div>++ {/* Settings Panel */}+ {showSettings && (+ <div style={{+ padding: '12px',+ borderBottom: '1px solid #2a2a2a',+ background: '#1a1a1a',+ maxHeight: '400px',+ overflowY: 'auto'+ }}>+ <div style={{ marginBottom: '12px' }}>+ <label style={{ color: '#9ca3af', fontSize: '10px', display: 'block', marginBottom: '4px' }}>+ Optimization Target+ </label>+ <select+ value={localConfig.target}+ onChange={(e) => setLocalConfig({ ...localConfig, target: e.target.value as any })}+ style={{+ width: '100%',+ padding: '6px',+ background: '#252525',+ border: '1px solid #3a3a3a',+ borderRadius: '4px',+ color: '#e5e7eb',+ fontSize: '10px'+ }}+ >+ <option value="sharpe_ratio">Sharpe Ratio</option>+ <option value="total_return">Total Return</option>+ <option value="sortino_ratio">Sortino Ratio</option>+ <option value="calmar_ratio">Calmar Ratio</option>+ <option value="profit_factor">Profit Factor</option>+ </select>+ </div>++ <div style={{ marginBottom: '12px' }}>+ <label style={{ color: '#9ca3af', fontSize: '10px', display: 'block', marginBottom: '4px' }}>+ Method+ </label>+ <select+ value={localConfig.method}+ onChange={(e) => setLocalConfig({ ...localConfig, method: e.target.value as any })}+ style={{+ width: '100%',+ padding: '6px',+ background: '#252525',+ border: '1px solid #3a3a3a',+ borderRadius: '4px',+ color: '#e5e7eb',+ fontSize: '10px'+ }}+ >+ <option value="grid">Grid Search</option>+ <option value="genetic">Genetic Algorithm</option>+ <option value="bayesian">Bayesian Optimization</option>+ </select>+ </div>++ <div style={{ marginBottom: '12px' }}>+ <label style={{ color: '#9ca3af', fontSize: '10px', display: 'block', marginBottom: '4px' }}>+ Max Iterations+ </label>+ <input+ type="number"+ value={localConfig.maxIterations}+ onChange={(e) => setLocalConfig({ ...localConfig, maxIterations: Number(e.target.value) })}+ style={{+ width: '100%',+ padding: '6px',+ background: '#252525',+ border: '1px solid #3a3a3a',+ borderRadius: '4px',+ color: '#e5e7eb',+ fontSize: '10px'+ }}+ />+ </div>++ <div style={{ marginBottom: '12px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>+ <label style={{ color: '#9ca3af', fontSize: '10px' }}>+ Parameter Ranges+ </label>+ <button+ onClick={addParameterRange}+ style={{+ padding: '2px 6px',+ background: '#3b82f6',+ color: 'white',+ border: 'none',+ borderRadius: '3px',+ fontSize: '9px',+ cursor: 'pointer'+ }}+ >+ + Add+ </button>+ </div>++ {Object.entries(paramRanges).map(([param, range]) => (+ <div key={param} style={{ marginBottom: '8px', padding: '8px', background: '#252525', borderRadius: '4px' }}>+ <div style={{ fontSize: '10px', color: '#e5e7eb', marginBottom: '4px', fontWeight: 'bold' }}>+ {param}+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '4px' }}>+ <div>+ <label style={{ fontSize: '8px', color: '#6b7280' }}>Min</label>+ <input+ type="number"+ value={range.min}+ onChange={(e) => setParamRanges({+ ...paramRanges,+ [param]: { ...range, min: Number(e.target.value) }+ })}+ style={{+ width: '100%',+ padding: '4px',+ background: '#1a1a1a',+ border: '1px solid #3a3a3a',+ borderRadius: '3px',+ color: '#e5e7eb',+ fontSize: '9px'+ }}+ />+ </div>+ <div>+ <label style={{ fontSize: '8px', color: '#6b7280' }}>Max</label>+ <input+ type="number"+ value={range.max}+ onChange={(e) => setParamRanges({+ ...paramRanges,+ [param]: { ...range, max: Number(e.target.value) }+ })}+ style={{+ width: '100%',+ padding: '4px',+ background: '#1a1a1a',+ border: '1px solid #3a3a3a',+ borderRadius: '3px',+ color: '#e5e7eb',+ fontSize: '9px'+ }}+ />+ </div>+ <div>+ <label style={{ fontSize: '8px', color: '#6b7280' }}>Step</label>+ <input+ type="number"+ value={range.step}+ onChange={(e) => setParamRanges({+ ...paramRanges,+ [param]: { ...range, step: Number(e.target.value) }+ })}+ style={{+ width: '100%',+ padding: '4px',+ background: '#1a1a1a',+ border: '1px solid #3a3a3a',+ borderRadius: '3px',+ color: '#e5e7eb',+ fontSize: '9px'+ }}+ />+ </div>+ </div>+ </div>+ ))}+ </div>++ <button+ onClick={handleSaveSettings}+ style={{+ width: '100%',+ padding: '6px',+ background: '#f59e0b',+ color: 'white',+ border: 'none',+ borderRadius: '4px',+ fontSize: '10px',+ cursor: 'pointer',+ fontWeight: 'bold'+ }}+ >+ Save Configuration+ </button>+ </div>+ )}++ {/* Content */}+ <div style={{ padding: '12px' }}>+ {/* Configuration Display */}+ <div style={{ marginBottom: '12px' }}>+ <div style={{ fontSize: '10px', color: '#9ca3af', marginBottom: '6px' }}>+ Configuration:+ </div>+ <div style={{ fontSize: '9px', color: '#d1d5db', fontFamily: 'monospace' }}>+ Target: {localConfig.target.replace('_', ' ')}+ </div>+ <div style={{ fontSize: '9px', color: '#d1d5db', fontFamily: 'monospace' }}>+ Method: {localConfig.method}+ </div>+ <div style={{ fontSize: '9px', color: '#d1d5db', fontFamily: 'monospace' }}>+ Parameters: {Object.keys(paramRanges).length}+ </div>+ </div>++ {/* Results Display */}+ {data.result && data.status === 'completed' && (+ <div style={{+ padding: '8px',+ background: '#1f1f1f',+ borderRadius: '4px',+ marginBottom: '8px'+ }}>+ <div style={{ fontSize: '10px', color: '#9ca3af', marginBottom: '6px', display: 'flex', alignItems: 'center', gap: '4px' }}>+ <TrendingUp size={12} />+ Best Parameters:+ </div>+ <div style={{ fontSize: '9px', color: '#10b981', fontFamily: 'monospace', marginBottom: '6px' }}>+ {formatBestParams()}+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px', fontSize: '9px' }}>+ <div>+ <div style={{ color: '#6b7280' }}>Iterations</div>+ <div style={{ color: '#e5e7eb', fontWeight: 'bold' }}>+ {data.result.iterations}+ </div>+ </div>+ <div>+ <div style={{ color: '#6b7280' }}>Duration</div>+ <div style={{ color: '#e5e7eb', fontWeight: 'bold' }}>+ {Math.round(data.result.duration / 1000)}s+ </div>+ </div>+ </div>+ </div>+ )}++ {/* Error Display */}+ {data.error && data.status === 'error' && (+ <div style={{+ padding: '8px',+ background: '#3a0a0a',+ border: '1px solid #ef4444',+ borderRadius: '4px',+ marginBottom: '8px'+ }}>+ <div style={{ fontSize: '10px', color: '#ef4444', marginBottom: '4px' }}>+ Error:+ </div>+ <div style={{ fontSize: '9px', color: '#fca5a5' }}>+ {data.error}+ </div>+ </div>+ )}++ {/* Run Button */}+ <button+ onClick={handleRunOptimization}+ disabled={data.status === 'running' || !data.strategyCode}+ style={{+ width: '100%',+ padding: '8px',+ background: data.status === 'running' ? '#6b7280' : '#f59e0b',+ color: 'white',+ border: 'none',+ borderRadius: '4px',+ fontSize: '11px',+ fontWeight: 'bold',+ cursor: data.status === 'running' || !data.strategyCode ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ opacity: data.status === 'running' || !data.strategyCode ? 0.6 : 1+ }}+ >+ {data.status === 'running' ? (+ <>+ <Loader size={14} className="animate-spin" />+ Optimizing... ({data.result?.iterations || 0}/{localConfig.maxIterations})+ </>+ ) : (+ <>+ <Play size={14} />+ Run Optimization+ </>+ )}+ </button>+ </div>++ {/* Handle Labels */}+ <div style={{+ position: 'absolute',+ left: '-60px',+ top: '30%',+ transform: 'translateY(-50%)',+ fontSize: '9px',+ color: '#6b7280',+ whiteSpace: 'nowrap'+ }}>+ Strategy+ </div>+ <div style={{+ position: 'absolute',+ right: '-80px',+ top: '30%',+ transform: 'translateY(-50%)',+ fontSize: '9px',+ color: '#6b7280',+ whiteSpace: 'nowrap'+ }}>+ Best Params+ </div>+ <div style={{+ position: 'absolute',+ right: '-70px',+ top: '60%',+ transform: 'translateY(-50%)',+ fontSize: '9px',+ color: '#6b7280',+ whiteSpace: 'nowrap'+ }}>+ All Results+ </div>+ </div>+ );+};++export default OptimizationNode;diff --git a/fincept-terminal-desktop/src/components/tabs/trading/OrderBook.tsx b/fincept-terminal-desktop/src/components/tabs/trading/OrderBook.tsxnew file mode 100644index 000000000..0a2839f11--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/OrderBook.tsx@@ -0,0 +1,154 @@+// File: src/components/tabs/trading/OrderBook.tsx+// Provider-agnostic order book component++import React, { useState, useEffect } from 'react';+import { useWebSocket } from '../../../hooks/useWebSocket';++interface OrderBookLevel {+ price: number;+ size: number;+ total?: number;+}++interface OrderBookProps {+ symbol: string;+ provider: string;+ depth?: number;+}++export function OrderBook({ symbol, provider, depth = 25 }: OrderBookProps) {+ const [bids, setBids] = useState<OrderBookLevel[]>([]);+ const [asks, setAsks] = useState<OrderBookLevel[]>([]);+ const [spread, setSpread] = useState<number>(0);++ const { message } = useWebSocket(+ `${provider}.book.${symbol}`,+ null,+ { autoSubscribe: true, params: { depth } }+ );++ useEffect(() => {+ if (!message || message.type !== 'orderbook') return;++ const data = message.data;++ // Process bids (buy orders) - highest first+ const processedBids = (data.bids || [])+ .slice(0, depth)+ .sort((a: any, b: any) => b.price - a.price);++ // Process asks (sell orders) - lowest first+ const processedAsks = (data.asks || [])+ .slice(0, depth)+ .sort((a: any, b: any) => a.price - b.price);++ // Calculate running totals+ let bidTotal = 0;+ const bidsWithTotal = processedBids.map((level: any) => {+ bidTotal += level.size;+ return { price: level.price, size: level.size, total: bidTotal };+ });++ let askTotal = 0;+ const asksWithTotal = processedAsks.map((level: any) => {+ askTotal += level.size;+ return { price: level.price, size: level.size, total: askTotal };+ });++ setBids(bidsWithTotal);+ setAsks(asksWithTotal);++ // Calculate spread+ if (processedBids.length > 0 && processedAsks.length > 0) {+ const bestBid = processedBids[0].price;+ const bestAsk = processedAsks[0].price;+ setSpread(bestAsk - bestBid);+ }+ }, [message, depth]);++ const maxTotal = Math.max(+ bids[bids.length - 1]?.total || 0,+ asks[asks.length - 1]?.total || 0+ );++ return (+ <div className="flex flex-col h-full bg-[#0d0d0d] text-white font-mono text-xs">+ {/* Header */}+ <div className="flex items-center justify-between px-3 py-2 border-b border-gray-800">+ <h3 className="text-sm font-bold text-gray-400">ORDER BOOK</h3>+ <div className="text-xs text-gray-500">+ Spread: <span className="text-orange-500">{spread.toFixed(2)}</span>+ </div>+ </div>++ {/* Column Headers */}+ <div className="flex justify-between px-3 py-1 bg-[#1a1a1a] text-gray-500 text-[10px] font-semibold">+ <div className="w-1/3">PRICE</div>+ <div className="w-1/3 text-right">SIZE</div>+ <div className="w-1/3 text-right">TOTAL</div>+ </div>++ <div className="flex-1 overflow-hidden">+ {/* Asks (Sell Orders) - Reversed to show lowest at bottom */}+ <div className="h-1/2 overflow-y-auto flex flex-col-reverse border-b border-gray-800">+ {asks.slice().reverse().map((level, idx) => (+ <OrderBookRow+ key={`ask-${idx}`}+ price={level.price}+ size={level.size}+ total={level.total || 0}+ maxTotal={maxTotal}+ side="ask"+ />+ ))}+ </div>++ {/* Bids (Buy Orders) */}+ <div className="h-1/2 overflow-y-auto">+ {bids.map((level, idx) => (+ <OrderBookRow+ key={`bid-${idx}`}+ price={level.price}+ size={level.size}+ total={level.total || 0}+ maxTotal={maxTotal}+ side="bid"+ />+ ))}+ </div>+ </div>+ </div>+ );+}++interface OrderBookRowProps {+ price: number;+ size: number;+ total: number;+ maxTotal: number;+ side: 'bid' | 'ask';+}++function OrderBookRow({ price, size, total, maxTotal, side }: OrderBookRowProps) {+ const percentage = (total / maxTotal) * 100;+ const bgColor = side === 'bid' ? 'bg-green-900/20' : 'bg-red-900/20';++ return (+ <div className="relative px-3 py-0.5 hover:bg-gray-800/50 cursor-pointer">+ {/* Background bar */}+ <div+ className={`absolute right-0 top-0 bottom-0 ${bgColor}`}+ style={{ width: `${percentage}%` }}+ />++ {/* Content */}+ <div className="relative flex justify-between">+ <div className={`w-1/3 ${side === 'bid' ? 'text-green-400' : 'text-red-400'}`}>+ {price.toFixed(2)}+ </div>+ <div className="w-1/3 text-right text-gray-300">{size.toFixed(4)}</div>+ <div className="w-1/3 text-right text-gray-500">{total.toFixed(4)}</div>+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/OrderForm.tsx b/fincept-terminal-desktop/src/components/tabs/trading/OrderForm.tsxnew file mode 100644index 000000000..b45d51ab5--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/OrderForm.tsx@@ -0,0 +1,186 @@+// File: src/components/tabs/trading/OrderForm.tsx+// Order placement form with all order types++import React, { useState } from 'react';+import type { OrderRequest, OrderType, OrderSide } from '../../../types/trading';++interface OrderFormProps {+ symbol: string;+ currentPrice?: number;+ onPlaceOrder: (order: OrderRequest) => Promise<void>;+ isLoading?: boolean;+}++export function OrderForm({ symbol, currentPrice, onPlaceOrder, isLoading }: OrderFormProps) {+ const [side, setSide] = useState<OrderSide>('buy');+ const [orderType, setOrderType] = useState<OrderType>('market');+ const [quantity, setQuantity] = useState<string>('');+ const [price, setPrice] = useState<string>('');+ const [stopPrice, setStopPrice] = useState<string>('');+ const [error, setError] = useState<string>('');++ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault();+ setError('');++ // Validation+ if (!quantity || parseFloat(quantity) <= 0) {+ setError('Please enter a valid quantity');+ return;+ }++ if ((orderType === 'limit' || orderType === 'stop_limit') && (!price || parseFloat(price) <= 0)) {+ setError('Please enter a valid limit price');+ return;+ }++ if ((orderType === 'stop_market' || orderType === 'stop_limit') && (!stopPrice || parseFloat(stopPrice) <= 0)) {+ setError('Please enter a valid stop price');+ return;+ }++ const order: OrderRequest = {+ symbol,+ side,+ type: orderType,+ quantity: parseFloat(quantity),+ ...(price && { price: parseFloat(price) }),+ ...(stopPrice && { stopPrice: parseFloat(stopPrice) })+ };++ try {+ await onPlaceOrder(order);++ // Reset form on success+ setQuantity('');+ setPrice('');+ setStopPrice('');+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Failed to place order');+ }+ };++ const estimatedCost = currentPrice && quantity+ ? (parseFloat(quantity) * (parseFloat(price) || currentPrice)).toFixed(2)+ : '0.00';++ return (+ <div className="bg-[#0d0d0d] border-t border-gray-800 p-4">+ <h3 className="text-sm font-bold text-gray-400 mb-3">PLACE ORDER</h3>++ <form onSubmit={handleSubmit} className="space-y-3">+ {/* Buy/Sell Toggle */}+ <div className="flex gap-2">+ <button+ type="button"+ onClick={() => setSide('buy')}+ className={`flex-1 py-2 rounded font-semibold text-sm transition-colors ${+ side === 'buy'+ ? 'bg-green-600 text-white'+ : 'bg-gray-800 text-gray-400 hover:bg-gray-700'+ }`}+ >+ BUY+ </button>+ <button+ type="button"+ onClick={() => setSide('sell')}+ className={`flex-1 py-2 rounded font-semibold text-sm transition-colors ${+ side === 'sell'+ ? 'bg-red-600 text-white'+ : 'bg-gray-800 text-gray-400 hover:bg-gray-700'+ }`}+ >+ SELL+ </button>+ </div>++ {/* Order Type */}+ <div>+ <label className="block text-xs text-gray-500 mb-1">Order Type</label>+ <select+ value={orderType}+ onChange={(e) => setOrderType(e.target.value as OrderType)}+ className="w-full bg-gray-800 text-white rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-500"+ >+ <option value="market">Market</option>+ <option value="limit">Limit</option>+ <option value="stop_market">Stop Market</option>+ <option value="stop_limit">Stop Limit</option>+ </select>+ </div>++ {/* Quantity */}+ <div>+ <label className="block text-xs text-gray-500 mb-1">Quantity</label>+ <input+ type="number"+ step="0.0001"+ value={quantity}+ onChange={(e) => setQuantity(e.target.value)}+ placeholder="0.00"+ className="w-full bg-gray-800 text-white rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-500"+ />+ </div>++ {/* Limit Price (for limit and stop_limit) */}+ {(orderType === 'limit' || orderType === 'stop_limit') && (+ <div>+ <label className="block text-xs text-gray-500 mb-1">Limit Price</label>+ <input+ type="number"+ step="0.01"+ value={price}+ onChange={(e) => setPrice(e.target.value)}+ placeholder={currentPrice?.toFixed(2) || '0.00'}+ className="w-full bg-gray-800 text-white rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-500"+ />+ </div>+ )}++ {/* Stop Price (for stop_market and stop_limit) */}+ {(orderType === 'stop_market' || orderType === 'stop_limit') && (+ <div>+ <label className="block text-xs text-gray-500 mb-1">Stop Price</label>+ <input+ type="number"+ step="0.01"+ value={stopPrice}+ onChange={(e) => setStopPrice(e.target.value)}+ placeholder={currentPrice?.toFixed(2) || '0.00'}+ className="w-full bg-gray-800 text-white rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-orange-500"+ />+ </div>+ )}++ {/* Estimated Cost */}+ {currentPrice && (+ <div className="flex justify-between text-xs">+ <span className="text-gray-500">Estimated {side === 'buy' ? 'Cost' : 'Proceeds'}:</span>+ <span className="text-white font-mono">${estimatedCost}</span>+ </div>+ )}++ {/* Error Message */}+ {error && (+ <div className="bg-red-900/20 border border-red-600 rounded p-2 text-xs text-red-400">+ {error}+ </div>+ )}++ {/* Submit Button */}+ <button+ type="submit"+ disabled={isLoading}+ className={`w-full py-2 rounded font-semibold text-sm transition-colors ${+ side === 'buy'+ ? 'bg-green-600 hover:bg-green-700 text-white'+ : 'bg-red-600 hover:bg-red-700 text-white'+ } ${isLoading ? 'opacity-50 cursor-not-allowed' : ''}`}+ >+ {isLoading ? 'Placing Order...' : `${side.toUpperCase()} ${symbol}`}+ </button>+ </form>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/PaperTradingPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/PaperTradingPanel.tsxnew file mode 100644index 000000000..333ac45bb--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/PaperTradingPanel.tsx@@ -0,0 +1,110 @@+// File: src/components/tabs/trading/PaperTradingPanel.tsx+// Paper trading control panel with toggle and portfolio display++import React, { useState, useEffect } from 'react';+import { useCreatePaperPortfolio } from '../../../hooks/usePaperTrading';+import { useProviderContext } from '../../../contexts/ProviderContext';++interface PaperTradingPanelProps {+ portfolioId: string | null;+ balance?: number;+ totalPnL?: number;+ onPortfolioChange: (portfolioId: string | null) => void;+ onReset?: () => void;+ isResetting?: boolean;+}++export function PaperTradingPanel({+ portfolioId,+ balance = 0,+ totalPnL = 0,+ onPortfolioChange,+ onReset,+ isResetting+}: PaperTradingPanelProps) {+ const [enabled, setEnabled] = useState(!!portfolioId);+ const { createPortfolio, isCreating } = useCreatePaperPortfolio();+ const { activeProvider } = useProviderContext();++ const handleToggle = async () => {+ if (!enabled) {+ // Enable paper trading - create new portfolio+ const newPortfolioId = await createPortfolio(+ `${activeProvider.toUpperCase()} Paper Trading`,+ activeProvider,+ 100000+ );++ if (newPortfolioId) {+ setEnabled(true);+ onPortfolioChange(newPortfolioId);+ }+ } else {+ // Disable paper trading+ setEnabled(false);+ onPortfolioChange(null);+ }+ };++ const pnlColor = totalPnL >= 0 ? 'text-green-400' : 'text-red-400';+ const pnlPercentage = balance > 0 ? ((totalPnL / balance) * 100).toFixed(2) : '0.00';++ return (+ <div className="bg-[#0d0d0d] border-b border-gray-800 px-4 py-2 flex items-center justify-between">+ <div className="flex items-center gap-4">+ {/* Toggle */}+ <div className="flex items-center gap-2">+ <button+ onClick={handleToggle}+ disabled={isCreating}+ className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${+ enabled ? 'bg-orange-600' : 'bg-gray-700'+ } ${isCreating ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}+ >+ <span+ className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${+ enabled ? 'translate-x-6' : 'translate-x-1'+ }`}+ />+ </button>+ <span className="text-xs font-semibold text-gray-400 uppercase">+ Paper Trading {isCreating ? '(Creating...)' : ''}+ </span>+ </div>++ {/* Portfolio Stats */}+ {enabled && portfolioId && (+ <>+ <div className="h-4 w-px bg-gray-700" />+ <div className="flex items-center gap-4">+ <div className="text-xs">+ <span className="text-gray-500">Balance:</span>+ <span className="text-green-400 ml-2 font-mono font-semibold">+ ${balance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}+ </span>+ </div>++ <div className="text-xs">+ <span className="text-gray-500">Total P&L:</span>+ <span className={`${pnlColor} ml-2 font-mono font-semibold`}>+ {totalPnL >= 0 ? '+' : ''}${totalPnL.toFixed(2)} ({pnlPercentage}%)+ </span>+ </div>+ </div>+ </>+ )}+ </div>++ {/* Reset Button */}+ {enabled && portfolioId && onReset && (+ <button+ onClick={onReset}+ disabled={isResetting}+ className="text-xs text-orange-500 hover:text-orange-400 font-semibold disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {isResetting ? 'RESETTING...' : 'RESET PORTFOLIO'}+ </button>+ )}+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/PositionsTable.tsx b/fincept-terminal-desktop/src/components/tabs/trading/PositionsTable.tsxnew file mode 100644index 000000000..1569af9cd--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/PositionsTable.tsx@@ -0,0 +1,155 @@+// File: src/components/tabs/trading/PositionsTable.tsx+// Display open and closed positions++import React from 'react';+import type { Position } from '../../../types/trading';++interface PositionsTableProps {+ positions: Position[];+ onClosePosition?: (positionId: string) => void;+ isLoading?: boolean;+}++export function PositionsTable({ positions, onClosePosition, isLoading }: PositionsTableProps) {+ const openPositions = positions.filter(p => p.status === 'open');+ const closedPositions = positions.filter(p => p.status === 'closed');++ return (+ <div className="bg-[#0d0d0d] border-t border-gray-800">+ <div className="px-4 py-2 border-b border-gray-800">+ <h3 className="text-sm font-bold text-gray-400">POSITIONS</h3>+ </div>++ {/* Open Positions */}+ <div className="max-h-64 overflow-y-auto">+ {openPositions.length === 0 ? (+ <div className="p-4 text-center text-gray-500 text-xs">+ No open positions+ </div>+ ) : (+ <table className="w-full text-xs font-mono">+ <thead className="bg-[#1a1a1a] text-gray-500 sticky top-0">+ <tr>+ <th className="px-3 py-2 text-left">SYMBOL</th>+ <th className="px-3 py-2 text-left">SIDE</th>+ <th className="px-3 py-2 text-right">QTY</th>+ <th className="px-3 py-2 text-right">ENTRY</th>+ <th className="px-3 py-2 text-right">CURRENT</th>+ <th className="px-3 py-2 text-right">P&L</th>+ <th className="px-3 py-2 text-center">ACTION</th>+ </tr>+ </thead>+ <tbody>+ {openPositions.map(position => (+ <PositionRow+ key={position.id}+ position={position}+ onClose={onClosePosition}+ isLoading={isLoading}+ />+ ))}+ </tbody>+ </table>+ )}+ </div>++ {/* Closed Positions (Collapsible) */}+ {closedPositions.length > 0 && (+ <details className="border-t border-gray-800">+ <summary className="px-4 py-2 cursor-pointer text-xs text-gray-500 hover:bg-gray-800/50">+ Closed Positions ({closedPositions.length})+ </summary>+ <div className="max-h-48 overflow-y-auto">+ <table className="w-full text-xs font-mono">+ <thead className="bg-[#1a1a1a] text-gray-500">+ <tr>+ <th className="px-3 py-2 text-left">SYMBOL</th>+ <th className="px-3 py-2 text-left">SIDE</th>+ <th className="px-3 py-2 text-right">QTY</th>+ <th className="px-3 py-2 text-right">ENTRY</th>+ <th className="px-3 py-2 text-right">REALIZED P&L</th>+ <th className="px-3 py-2 text-right">CLOSED</th>+ </tr>+ </thead>+ <tbody>+ {closedPositions.map(position => (+ <ClosedPositionRow key={position.id} position={position} />+ ))}+ </tbody>+ </table>+ </div>+ </details>+ )}+ </div>+ );+}++interface PositionRowProps {+ position: Position;+ onClose?: (positionId: string) => void;+ isLoading?: boolean;+}++function PositionRow({ position, onClose, isLoading }: PositionRowProps) {+ const pnl = position.unrealizedPnL || 0;+ const pnlColor = pnl >= 0 ? 'text-green-400' : 'text-red-400';++ return (+ <tr className="border-b border-gray-800 hover:bg-gray-800/50">+ <td className="px-3 py-2 text-white font-semibold">{position.symbol}</td>+ <td className="px-3 py-2">+ <span className={`px-2 py-0.5 rounded text-[10px] font-semibold ${+ position.side === 'long' ? 'bg-green-900/30 text-green-400' : 'bg-red-900/30 text-red-400'+ }`}>+ {position.side.toUpperCase()}+ </span>+ </td>+ <td className="px-3 py-2 text-right text-gray-300">{position.quantity.toFixed(4)}</td>+ <td className="px-3 py-2 text-right text-gray-300">${position.entryPrice.toFixed(2)}</td>+ <td className="px-3 py-2 text-right text-white">+ ${position.currentPrice?.toFixed(2) || '-'}+ </td>+ <td className={`px-3 py-2 text-right font-semibold ${pnlColor}`}>+ {pnl >= 0 ? '+' : ''}{pnl.toFixed(2)}+ </td>+ <td className="px-3 py-2 text-center">+ {onClose && (+ <button+ onClick={() => onClose(position.id)}+ disabled={isLoading}+ className="px-2 py-1 bg-red-600 hover:bg-red-700 text-white rounded text-[10px] font-semibold disabled:opacity-50 disabled:cursor-not-allowed"+ >+ CLOSE+ </button>+ )}+ </td>+ </tr>+ );+}++function ClosedPositionRow({ position }: { position: Position }) {+ const pnl = position.realizedPnL;+ const pnlColor = pnl >= 0 ? 'text-green-400' : 'text-red-400';+ const closedDate = position.closedAt+ ? new Date(position.closedAt).toLocaleDateString()+ : '-';++ return (+ <tr className="border-b border-gray-800 hover:bg-gray-800/50 text-gray-500">+ <td className="px-3 py-2">{position.symbol}</td>+ <td className="px-3 py-2">+ <span className={`px-2 py-0.5 rounded text-[10px] ${+ position.side === 'long' ? 'bg-green-900/20 text-green-600' : 'bg-red-900/20 text-red-600'+ }`}>+ {position.side.toUpperCase()}+ </span>+ </td>+ <td className="px-3 py-2 text-right">{position.quantity.toFixed(4)}</td>+ <td className="px-3 py-2 text-right">${position.entryPrice.toFixed(2)}</td>+ <td className={`px-3 py-2 text-right font-semibold ${pnlColor}`}>+ {pnl >= 0 ? '+' : ''}{pnl.toFixed(2)}+ </td>+ <td className="px-3 py-2 text-right">{closedDate}</td>+ </tr>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/ProviderSwitcher.tsx b/fincept-terminal-desktop/src/components/tabs/trading/ProviderSwitcher.tsxnew file mode 100644index 000000000..afcd71d1f--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/ProviderSwitcher.tsx@@ -0,0 +1,50 @@+// File: src/components/tabs/trading/ProviderSwitcher.tsx+// Provider selection component for multi-provider trading++import React from 'react';+import { useProviderContext } from '../../../contexts/ProviderContext';++export function ProviderSwitcher() {+ const { activeProvider, availableProviders, setActiveProvider, isLoading } = useProviderContext();++ if (isLoading) {+ return (+ <div className="flex items-center gap-2 bg-[#0d0d0d] px-4 py-2 border-b border-gray-800">+ <span className="text-xs text-gray-500">PROVIDER:</span>+ <div className="text-xs text-gray-400">Loading...</div>+ </div>+ );+ }++ return (+ <div className="flex items-center gap-2 bg-[#0d0d0d] px-4 py-2 border-b border-gray-800">+ <span className="text-xs text-gray-500 uppercase font-semibold">Provider:</span>+ <div className="flex gap-2">+ {availableProviders.map(provider => (+ <button+ key={provider}+ onClick={() => setActiveProvider(provider)}+ disabled={isLoading}+ className={`+ px-3 py-1 rounded text-xs font-bold uppercase transition-colors+ ${activeProvider === provider+ ? 'bg-orange-600 text-black'+ : 'bg-gray-800 text-gray-400 hover:bg-gray-700 hover:text-gray-300'+ }+ ${isLoading ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}+ `}+ >+ {provider}+ </button>+ ))}+ </div>++ {activeProvider && (+ <div className="ml-4 flex items-center gap-2">+ <div className="w-2 h-2 rounded-full bg-green-500 animate-pulse"></div>+ <span className="text-xs text-gray-500">Connected to {activeProvider}</span>+ </div>+ )}+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/TickerDisplay.tsx b/fincept-terminal-desktop/src/components/tabs/trading/TickerDisplay.tsxnew file mode 100644index 000000000..1e8916bc0--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/TickerDisplay.tsx@@ -0,0 +1,101 @@+// File: src/components/tabs/trading/TickerDisplay.tsx+// Provider-agnostic ticker display component++import React, { useState, useEffect } from 'react';+import { useWebSocket } from '../../../hooks/useWebSocket';++interface TickerDisplayProps {+ symbol: string;+ provider: string;+}++interface TickerData {+ last: number;+ bid: number;+ ask: number;+ volume: number;+ high: number;+ low: number;+ change: number;+ changePct: number;+}++export function TickerDisplay({ symbol, provider }: TickerDisplayProps) {+ const [ticker, setTicker] = useState<TickerData | null>(null);++ const { message } = useWebSocket(+ `${provider}.ticker.${symbol}`,+ null,+ { autoSubscribe: true }+ );++ useEffect(() => {+ if (!message || message.type !== 'ticker') return;++ const data = message.data;++ setTicker({+ last: data.last || data.close || data.mid || 0,+ bid: data.bid || 0,+ ask: data.ask || 0,+ volume: data.volume || data.v || 0,+ high: data.high || data.h || 0,+ low: data.low || data.l || 0,+ change: data.change || 0,+ changePct: data.change_pct || data.changePct || 0+ });+ }, [message]);++ if (!ticker) {+ return (+ <div className="bg-[#0d0d0d] p-4 text-center text-gray-500">+ Loading ticker data...+ </div>+ );+ }++ const isPositive = ticker.change >= 0;++ return (+ <div className="bg-[#0d0d0d] border-b border-gray-800">+ {/* Main Price */}+ <div className="px-4 py-3 border-b border-gray-800">+ <div className="text-2xl font-bold font-mono text-white mb-1">+ ${ticker.last.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}+ </div>+ <div className={`text-sm font-semibold ${isPositive ? 'text-green-400' : 'text-red-400'}`}>+ {isPositive ? '+' : ''}{ticker.change.toFixed(2)} ({isPositive ? '+' : ''}{ticker.changePct.toFixed(2)}%)+ </div>+ </div>++ {/* Stats Grid */}+ <div className="grid grid-cols-2 gap-2 px-4 py-3 text-xs font-mono">+ <StatItem label="BID" value={ticker.bid.toFixed(2)} valueColor="text-green-400" />+ <StatItem label="ASK" value={ticker.ask.toFixed(2)} valueColor="text-red-400" />+ <StatItem label="HIGH" value={ticker.high.toFixed(2)} valueColor="text-gray-300" />+ <StatItem label="LOW" value={ticker.low.toFixed(2)} valueColor="text-gray-300" />+ <StatItem label="VOLUME" value={ticker.volume.toFixed(2)} valueColor="text-blue-400" />+ <StatItem+ label="SPREAD"+ value={(ticker.ask - ticker.bid).toFixed(2)}+ valueColor="text-orange-400"+ />+ </div>+ </div>+ );+}++interface StatItemProps {+ label: string;+ value: string;+ valueColor: string;+}++function StatItem({ label, value, valueColor }: StatItemProps) {+ return (+ <div>+ <div className="text-gray-500 text-[10px] mb-0.5">{label}</div>+ <div className={`${valueColor} font-semibold`}>{value}</div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/TradesFeed.tsx b/fincept-terminal-desktop/src/components/tabs/trading/TradesFeed.tsxnew file mode 100644index 000000000..faec27c55--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/TradesFeed.tsx@@ -0,0 +1,110 @@+// File: src/components/tabs/trading/TradesFeed.tsx+// Provider-agnostic trades feed component++import React, { useState, useEffect } from 'react';+import { useWebSocket } from '../../../hooks/useWebSocket';++interface Trade {+ price: number;+ size: number;+ side: 'buy' | 'sell';+ time: number;+}++interface TradesFeedProps {+ symbol: string;+ provider: string;+ maxTrades?: number;+}++export function TradesFeed({ symbol, provider, maxTrades = 50 }: TradesFeedProps) {+ const [trades, setTrades] = useState<Trade[]>([]);++ const { message } = useWebSocket(+ `${provider}.trades.${symbol}`,+ null,+ { autoSubscribe: true }+ );++ useEffect(() => {+ if (!message || message.type !== 'trade') return;++ const data = message.data;++ // Handle different data formats+ let newTrades: Trade[] = [];++ if (Array.isArray(data.trades)) {+ // Multiple trades (e.g., HyperLiquid)+ newTrades = data.trades.map((trade: any) => ({+ price: trade.price || parseFloat(trade.px),+ size: trade.size || parseFloat(trade.sz),+ side: trade.side === 'sell' || trade.side === 'A' ? 'sell' : 'buy',+ time: trade.time || Date.now()+ }));+ } else {+ // Single trade (e.g., Kraken)+ newTrades = [{+ price: data.price || parseFloat(data.px),+ size: data.size || parseFloat(data.sz),+ side: data.side === 'sell' || data.side === 'A' ? 'sell' : 'buy',+ time: data.time || Date.now()+ }];+ }++ setTrades(prev => {+ const updated = [...newTrades, ...prev];+ return updated.slice(0, maxTrades);+ });+ }, [message, maxTrades]);++ return (+ <div className="flex flex-col h-full bg-[#0d0d0d] text-white font-mono text-xs">+ {/* Header */}+ <div className="px-3 py-2 border-b border-gray-800">+ <h3 className="text-sm font-bold text-gray-400">RECENT TRADES</h3>+ </div>++ {/* Column Headers */}+ <div className="flex justify-between px-3 py-1 bg-[#1a1a1a] text-gray-500 text-[10px] font-semibold">+ <div className="w-1/3">TIME</div>+ <div className="w-1/3 text-right">PRICE</div>+ <div className="w-1/3 text-right">SIZE</div>+ </div>++ {/* Trades List */}+ <div className="flex-1 overflow-y-auto">+ {trades.length === 0 ? (+ <div className="p-4 text-center text-gray-500">No trades yet...</div>+ ) : (+ trades.map((trade, idx) => (+ <TradeRow key={`${trade.time}-${idx}`} trade={trade} />+ ))+ )}+ </div>+ </div>+ );+}++interface TradeRowProps {+ trade: Trade;+}++function TradeRow({ trade }: TradeRowProps) {+ const timeStr = new Date(trade.time).toLocaleTimeString('en-US', {+ hour12: false,+ hour: '2-digit',+ minute: '2-digit',+ second: '2-digit'+ });++ return (+ <div className="flex justify-between px-3 py-1 hover:bg-gray-800/50">+ <div className="w-1/3 text-gray-400">{timeStr}</div>+ <div className={`w-1/3 text-right font-semibold ${trade.side === 'buy' ? 'text-green-400' : 'text-red-400'}`}>+ {trade.price.toFixed(2)}+ </div>+ <div className="w-1/3 text-right text-gray-300">{trade.size.toFixed(4)}</div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/contexts/ProviderContext.tsx b/fincept-terminal-desktop/src/contexts/ProviderContext.tsxnew file mode 100644index 000000000..adf0ee241--- /dev/null+++ b/fincept-terminal-desktop/src/contexts/ProviderContext.tsx@@ -0,0 +1,163 @@+// File: src/contexts/ProviderContext.tsx+// Global provider selection context for multi-provider trading++import React, { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';+import { getWebSocketManager } from '../services/websocket';+import type { ProviderConfig } from '../services/websocket/types';+import { getAvailableProviders } from '../services/websocket/adapters';++interface ProviderContextType {+ activeProvider: string;+ availableProviders: string[];+ setActiveProvider: (provider: string) => Promise<void>;+ providerConfigs: Map<string, ProviderConfig>;+ updateProviderConfig: (provider: string, config: Partial<ProviderConfig>) => Promise<void>;+ isLoading: boolean;+}++const ProviderContext = createContext<ProviderContextType | null>(null);++interface ProviderProviderProps {+ children: ReactNode;+}++export function ProviderProvider({ children }: ProviderProviderProps) {+ const [activeProvider, setActiveProviderState] = useState<string>('kraken');+ const [providerConfigs, setProviderConfigs] = useState<Map<string, ProviderConfig>>(new Map());+ const [isLoading, setIsLoading] = useState(true);++ // Get available providers from adapter registry+ const availableProviders = getAvailableProviders();++ // Load provider configurations and preferences on mount+ useEffect(() => {+ const loadConfigurations = async () => {+ setIsLoading(true);++ try {+ const manager = getWebSocketManager();++ // Initialize default configurations for available providers+ const configs = new Map<string, ProviderConfig>();++ // Kraken config+ configs.set('kraken', {+ provider_name: 'kraken',+ enabled: true,+ endpoint: 'wss://ws.kraken.com/v2'+ });++ // HyperLiquid config+ configs.set('hyperliquid', {+ provider_name: 'hyperliquid',+ enabled: true,+ endpoint: 'wss://api.hyperliquid.xyz/ws',+ config_data: JSON.stringify({ testnet: false })+ });++ setProviderConfigs(configs);++ // Load saved provider preference from localStorage+ const savedProvider = localStorage.getItem('active_trading_provider');+ if (savedProvider && configs.has(savedProvider)) {+ setActiveProviderState(savedProvider);+ }++ // Apply configurations to WebSocket manager+ configs.forEach((config, provider) => {+ manager.setProviderConfig(provider, config);+ });+ } catch (error) {+ console.error('Failed to load provider configurations:', error);+ } finally {+ setIsLoading(false);+ }+ };++ loadConfigurations();+ }, []);++ const setActiveProvider = useCallback(async (provider: string) => {+ if (!availableProviders.includes(provider)) {+ throw new Error(`Provider ${provider} is not available`);+ }++ setActiveProviderState(provider);++ // Save preference to localStorage+ localStorage.setItem('active_trading_provider', provider);++ // Ensure the provider is connected+ const manager = getWebSocketManager();+ const status = manager.getStatus(provider);++ if (status !== 'connected') {+ try {+ await manager.connect(provider);+ } catch (error) {+ console.error(`Failed to connect to ${provider}:`, error);+ }+ }+ }, [availableProviders]);++ const updateProviderConfig = useCallback(async (+ provider: string,+ config: Partial<ProviderConfig>+ ) => {+ setProviderConfigs(prev => {+ const newConfigs = new Map(prev);+ const existingConfig = newConfigs.get(provider);++ const updatedConfig: ProviderConfig = {+ ...existingConfig,+ ...config,+ provider_name: provider+ } as ProviderConfig;++ newConfigs.set(provider, updatedConfig);++ // Update WebSocket manager+ const manager = getWebSocketManager();+ manager.setProviderConfig(provider, updatedConfig);++ return newConfigs;+ });+ }, []);++ return (+ <ProviderContext.Provider value={{+ activeProvider,+ availableProviders,+ setActiveProvider,+ providerConfigs,+ updateProviderConfig,+ isLoading+ }}>+ {children}+ </ProviderContext.Provider>+ );+}++export function useProviderContext(): ProviderContextType {+ const context = useContext(ProviderContext);++ if (!context) {+ throw new Error('useProviderContext must be used within a ProviderProvider');+ }++ return context;+}++/**+ * Hook for quick provider selection+ */+export function useProviderSelection() {+ const { activeProvider, availableProviders, setActiveProvider, isLoading } = useProviderContext();++ return {+ provider: activeProvider,+ providers: availableProviders,+ setProvider: setActiveProvider,+ isLoading+ };+}diff --git a/fincept-terminal-desktop/src/hooks/usePaperTrading.ts b/fincept-terminal-desktop/src/hooks/usePaperTrading.tsnew file mode 100644index 000000000..f0fb26fa4--- /dev/null+++ b/fincept-terminal-desktop/src/hooks/usePaperTrading.ts@@ -0,0 +1,258 @@+// File: src/hooks/usePaperTrading.ts+// React hook for paper trading functionality++import { useState, useEffect, useCallback, useRef } from 'react';+import { createPaperTradingService } from '../services/trading';+import type {+ VirtualPortfolio,+ Position,+ Order,+ OrderRequest,+ OrderResult+} from '../types/trading';++interface UsePaperTradingOptions {+ portfolioId?: string;+ autoRefreshInterval?: number; // milliseconds, default 1000+}++interface UsePaperTradingReturn {+ portfolio: VirtualPortfolio | null;+ positions: Position[];+ orders: Order[];+ isLoading: boolean;+ error: string | null;+ placeOrder: (order: OrderRequest) => Promise<OrderResult>;+ cancelOrder: (orderId: string) => Promise<boolean>;+ closePosition: (positionId: string) => Promise<boolean>;+ resetPortfolio: () => Promise<boolean>;+ refresh: () => Promise<void>;+}++export function usePaperTrading(+ options: UsePaperTradingOptions = {}+): UsePaperTradingReturn {+ const { portfolioId, autoRefreshInterval = 1000 } = options;++ const [portfolio, setPortfolio] = useState<VirtualPortfolio | null>(null);+ const [positions, setPositions] = useState<Position[]>([]);+ const [orders, setOrders] = useState<Order[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const serviceRef = useRef(createPaperTradingService());+ const refreshIntervalRef = useRef<NodeJS.Timeout | null>(null);++ // Load portfolio data+ const loadPortfolio = useCallback(async () => {+ if (!portfolioId) {+ setPortfolio(null);+ setPositions([]);+ setOrders([]);+ return;+ }++ try {+ const service = serviceRef.current;+ await service.initialize();++ const [portfolioData, positionsData, ordersData] = await Promise.all([+ service.getPortfolio(portfolioId),+ service.getPositions(portfolioId, 'all'),+ service.getOrders(portfolioId)+ ]);++ setPortfolio(portfolioData);+ setPositions(positionsData);+ setOrders(ordersData);+ setError(null);+ } catch (err) {+ console.error('[usePaperTrading] Failed to load portfolio:', err);+ setError(err instanceof Error ? err.message : 'Failed to load portfolio');+ }+ }, [portfolioId]);++ // Initial load+ useEffect(() => {+ setIsLoading(true);+ loadPortfolio().finally(() => setIsLoading(false));+ }, [loadPortfolio]);++ // Auto-refresh positions (for real-time P&L updates)+ useEffect(() => {+ if (!portfolioId || !autoRefreshInterval) return;++ refreshIntervalRef.current = setInterval(() => {+ loadPortfolio();+ }, autoRefreshInterval);++ return () => {+ if (refreshIntervalRef.current) {+ clearInterval(refreshIntervalRef.current);+ }+ };+ }, [portfolioId, autoRefreshInterval, loadPortfolio]);++ // Place order+ const placeOrder = useCallback(async (order: OrderRequest): Promise<OrderResult> => {+ if (!portfolioId) {+ return { success: false, error: 'No portfolio selected' };+ }++ setIsLoading(true);+ try {+ const service = serviceRef.current;+ const result = await service.placeOrder(portfolioId, order);++ if (result.success) {+ // Refresh data+ await loadPortfolio();+ }++ setError(null);+ return result;+ } catch (err) {+ const errorMsg = err instanceof Error ? err.message : 'Failed to place order';+ setError(errorMsg);+ return { success: false, error: errorMsg };+ } finally {+ setIsLoading(false);+ }+ }, [portfolioId, loadPortfolio]);++ // Cancel order+ const cancelOrder = useCallback(async (orderId: string): Promise<boolean> => {+ setIsLoading(true);+ try {+ const service = serviceRef.current;+ const success = await service.cancelOrder(orderId);++ if (success) {+ await loadPortfolio();+ }++ setError(null);+ return success;+ } catch (err) {+ console.error('[usePaperTrading] Failed to cancel order:', err);+ setError(err instanceof Error ? err.message : 'Failed to cancel order');+ return false;+ } finally {+ setIsLoading(false);+ }+ }, [loadPortfolio]);++ // Close position+ const closePosition = useCallback(async (positionId: string): Promise<boolean> => {+ setIsLoading(true);+ try {+ const service = serviceRef.current;+ const success = await service.closePosition(positionId);++ if (success) {+ await loadPortfolio();+ }++ setError(null);+ return success;+ } catch (err) {+ console.error('[usePaperTrading] Failed to close position:', err);+ setError(err instanceof Error ? err.message : 'Failed to close position');+ return false;+ } finally {+ setIsLoading(false);+ }+ }, [loadPortfolio]);++ // Reset portfolio+ const resetPortfolio = useCallback(async (): Promise<boolean> => {+ if (!portfolioId) return false;++ setIsLoading(true);+ try {+ const service = serviceRef.current;+ const success = await service.resetPortfolio(portfolioId);++ if (success) {+ await loadPortfolio();+ }++ setError(null);+ return success;+ } catch (err) {+ console.error('[usePaperTrading] Failed to reset portfolio:', err);+ setError(err instanceof Error ? err.message : 'Failed to reset portfolio');+ return false;+ } finally {+ setIsLoading(false);+ }+ }, [portfolioId, loadPortfolio]);++ // Manual refresh+ const refresh = useCallback(async () => {+ setIsLoading(true);+ await loadPortfolio();+ setIsLoading(false);+ }, [loadPortfolio]);++ // Cleanup on unmount+ useEffect(() => {+ return () => {+ serviceRef.current.cleanup();+ if (refreshIntervalRef.current) {+ clearInterval(refreshIntervalRef.current);+ }+ };+ }, []);++ return {+ portfolio,+ positions,+ orders,+ isLoading,+ error,+ placeOrder,+ cancelOrder,+ closePosition,+ resetPortfolio,+ refresh+ };+}++/**+ * Hook for creating a new paper trading portfolio+ */+export function useCreatePaperPortfolio() {+ const [isCreating, setIsCreating] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const serviceRef = useRef(createPaperTradingService());++ const createPortfolio = useCallback(async (+ name: string,+ provider: string,+ initialBalance: number = 100000+ ): Promise<string | null> => {+ setIsCreating(true);+ setError(null);++ try {+ const service = serviceRef.current;+ await service.initialize();++ const portfolioId = await service.createPortfolio(name, provider, initialBalance);+ return portfolioId;+ } catch (err) {+ console.error('[useCreatePaperPortfolio] Failed to create portfolio:', err);+ setError(err instanceof Error ? err.message : 'Failed to create portfolio');+ return null;+ } finally {+ setIsCreating(false);+ }+ }, []);++ return {+ createPortfolio,+ isCreating,+ error+ };+}diff --git a/fincept-terminal-desktop/src/services/backtesting/BacktestingProviderRegistry.ts b/fincept-terminal-desktop/src/services/backtesting/BacktestingProviderRegistry.tsnew file mode 100644index 000000000..807defd2f--- /dev/null+++ b/fincept-terminal-desktop/src/services/backtesting/BacktestingProviderRegistry.ts@@ -0,0 +1,398 @@+/**+ * Backtesting Provider Registry+ * Central registry for managing all backtesting providers+ * Enables easy provider switching and discovery+ */++import { IBacktestingProvider } from './interfaces/IBacktestingProvider';+import { ProviderInfo, ProviderConfig } from './interfaces/types';++/**+ * BacktestingProviderRegistry+ *+ * Singleton registry that manages all available backtesting providers.+ * Provides provider registration, activation, and discovery.+ */+export class BacktestingProviderRegistry {+ private providers: Map<string, IBacktestingProvider> = new Map();+ private activeProviderId: string | null = null;+ private configs: Map<string, ProviderConfig> = new Map();+ private listeners: Set<RegistryListener> = new Set();++ // ============================================================================+ // Provider Registration+ // ============================================================================++ /**+ * Register a new provider+ *+ * @param provider Provider instance implementing IBacktestingProvider+ * @throws Error if provider with same name already exists+ */+ registerProvider(provider: IBacktestingProvider): void {+ if (this.providers.has(provider.name)) {+ throw new Error(`Provider "${provider.name}" is already registered`);+ }++ this.providers.set(provider.name, provider);+ this.notifyListeners('provider:registered', { provider: provider.name });++ console.log(`✓ Registered backtesting provider: ${provider.name}`);+ }++ /**+ * Unregister a provider+ *+ * @param name Provider name+ * @returns true if provider was found and removed+ */+ unregisterProvider(name: string): boolean {+ const provider = this.providers.get(name);+ if (!provider) {+ return false;+ }++ // Disconnect provider before removing+ provider.disconnect().catch(console.error);++ this.providers.delete(name);+ this.configs.delete(name);++ // If this was the active provider, clear it+ if (this.activeProviderId === name) {+ this.activeProviderId = null;+ }++ this.notifyListeners('provider:unregistered', { provider: name });++ console.log(`✓ Unregistered backtesting provider: ${name}`);+ return true;+ }++ // ============================================================================+ // Provider Selection+ // ============================================================================++ /**+ * Set active provider+ *+ * @param name Provider name+ * @throws Error if provider not found+ */+ async setActiveProvider(name: string): Promise<void> {+ const provider = this.providers.get(name);+ if (!provider) {+ throw new Error(`Provider "${name}" not found`);+ }++ // Test connection before activating+ const testResult = await provider.testConnection();+ if (!testResult.success) {+ throw new Error(+ `Cannot activate provider "${name}": ${testResult.error || 'Connection test failed'}`+ );+ }++ const previousProvider = this.activeProviderId;+ this.activeProviderId = name;++ this.notifyListeners('provider:activated', {+ provider: name,+ previous: previousProvider,+ });++ console.log(`✓ Activated backtesting provider: ${name}`);+ }++ /**+ * Get active provider+ *+ * @returns Active provider instance or null if none active+ */+ getActiveProvider(): IBacktestingProvider | null {+ if (!this.activeProviderId) {+ return null;+ }+ return this.providers.get(this.activeProviderId) || null;+ }++ /**+ * Get active provider name+ *+ * @returns Active provider name or null+ */+ getActiveProviderName(): string | null {+ return this.activeProviderId;+ }++ /**+ * Check if a provider is active+ *+ * @param name Provider name+ * @returns true if this provider is active+ */+ isActive(name: string): boolean {+ return this.activeProviderId === name;+ }++ // ============================================================================+ // Provider Discovery+ // ============================================================================++ /**+ * Get provider by name+ *+ * @param name Provider name+ * @returns Provider instance or null if not found+ */+ getProvider(name: string): IBacktestingProvider | null {+ return this.providers.get(name) || null;+ }++ /**+ * List all registered providers+ *+ * @returns Array of provider info+ */+ listProviders(): ProviderInfo[] {+ return Array.from(this.providers.values()).map((provider) => ({+ name: provider.name,+ version: provider.version,+ capabilities: provider.capabilities,+ description: provider.description || '',+ isActive: this.activeProviderId === provider.name,+ isEnabled: true,+ config: this.configs.get(provider.name),+ }));+ }++ /**+ * Get providers by capability+ *+ * @param capability Capability to filter by+ * @returns Array of provider info that support this capability+ */+ getProvidersByCapability(+ capability: keyof ProviderInfo['capabilities']+ ): ProviderInfo[] {+ return this.listProviders().filter((info) => info.capabilities[capability]);+ }++ /**+ * Get providers supporting specific asset class+ *+ * @param assetClass Asset class (stocks, options, crypto, etc.)+ * @returns Array of provider info+ */+ getProvidersByAssetClass(assetClass: string): ProviderInfo[] {+ return this.listProviders().filter((info) =>+ info.capabilities.multiAsset.includes(assetClass as any)+ );+ }++ /**+ * Check if any providers are registered+ *+ * @returns true if at least one provider is registered+ */+ hasProviders(): boolean {+ return this.providers.size > 0;+ }++ /**+ * Get total number of registered providers+ *+ * @returns Number of providers+ */+ getProviderCount(): number {+ return this.providers.size;+ }++ // ============================================================================+ // Configuration Management+ // ============================================================================++ /**+ * Save provider configuration+ *+ * @param name Provider name+ * @param config Provider configuration+ */+ saveProviderConfig(name: string, config: ProviderConfig): void {+ this.configs.set(name, config);+ this.notifyListeners('config:saved', { provider: name });+ }++ /**+ * Load provider configuration+ *+ * @param name Provider name+ * @returns Configuration or null if not found+ */+ loadProviderConfig(name: string): ProviderConfig | null {+ return this.configs.get(name) || null;+ }++ /**+ * Delete provider configuration+ *+ * @param name Provider name+ * @returns true if config was found and deleted+ */+ deleteProviderConfig(name: string): boolean {+ const deleted = this.configs.delete(name);+ if (deleted) {+ this.notifyListeners('config:deleted', { provider: name });+ }+ return deleted;+ }++ // ============================================================================+ // Provider Switching+ // ============================================================================++ /**+ * Switch from one provider to another+ *+ * @param fromProvider Current provider name (optional)+ * @param toProvider Target provider name+ */+ async switchProvider(+ fromProvider: string | null,+ toProvider: string+ ): Promise<void> {+ // Validate target provider exists+ if (!this.providers.has(toProvider)) {+ throw new Error(`Target provider "${toProvider}" not found`);+ }++ // If fromProvider specified, validate it's currently active+ if (fromProvider && this.activeProviderId !== fromProvider) {+ console.warn(+ `Warning: fromProvider "${fromProvider}" is not active. Current: ${this.activeProviderId}`+ );+ }++ // Disconnect from current provider+ if (this.activeProviderId) {+ const currentProvider = this.providers.get(this.activeProviderId);+ if (currentProvider) {+ await currentProvider.disconnect();+ }+ }++ // Activate new provider+ await this.setActiveProvider(toProvider);++ console.log(`✓ Switched provider: ${fromProvider} → ${toProvider}`);+ }++ // ============================================================================+ // Event System+ // ============================================================================++ /**+ * Add event listener+ *+ * @param listener Listener function+ */+ addListener(listener: RegistryListener): void {+ this.listeners.add(listener);+ }++ /**+ * Remove event listener+ *+ * @param listener Listener function+ */+ removeListener(listener: RegistryListener): void {+ this.listeners.delete(listener);+ }++ /**+ * Notify all listeners of an event+ *+ * @param event Event type+ * @param data Event data+ */+ private notifyListeners(event: RegistryEvent, data: any): void {+ this.listeners.forEach((listener) => {+ try {+ listener(event, data);+ } catch (error) {+ console.error('Error in registry listener:', error);+ }+ });+ }++ // ============================================================================+ // Utility Methods+ // ============================================================================++ /**+ * Clear all providers and reset registry+ * WARNING: This disconnects all providers and clears all data+ */+ async clearAll(): Promise<void> {+ // Disconnect all providers+ await Promise.all(+ Array.from(this.providers.values()).map((p) =>+ p.disconnect().catch(console.error)+ )+ );++ this.providers.clear();+ this.configs.clear();+ this.activeProviderId = null;+ this.listeners.clear();++ console.log('✓ Cleared all backtesting providers');+ }++ /**+ * Get registry statistics+ *+ * @returns Registry stats+ */+ getStats(): RegistryStats {+ return {+ totalProviders: this.providers.size,+ activeProvider: this.activeProviderId,+ providersWithOptimization: this.getProvidersByCapability('optimization')+ .length,+ providersWithLiveTrading: this.getProvidersByCapability('liveTrading')+ .length,+ providersWithResearch: this.getProvidersByCapability('research').length,+ };+ }+}++// ============================================================================+// Types+// ============================================================================++export type RegistryEvent =+ | 'provider:registered'+ | 'provider:unregistered'+ | 'provider:activated'+ | 'config:saved'+ | 'config:deleted';++export type RegistryListener = (event: RegistryEvent, data: any) => void;++export interface RegistryStats {+ totalProviders: number;+ activeProvider: string | null;+ providersWithOptimization: number;+ providersWithLiveTrading: number;+ providersWithResearch: number;+}++// ============================================================================+// Singleton Export+// ============================================================================++/**+ * Global singleton instance of the backtesting provider registry+ */+export const backtestingRegistry = new BacktestingProviderRegistry();diff --git a/fincept-terminal-desktop/src/services/backtesting/BacktestingService.ts b/fincept-terminal-desktop/src/services/backtesting/BacktestingService.tsnew file mode 100644index 000000000..59e7be2f8--- /dev/null+++ b/fincept-terminal-desktop/src/services/backtesting/BacktestingService.ts@@ -0,0 +1,188 @@+/**+ * Backtesting Service+ * High-level facade for backtesting operations+ * Simplifies interaction with the provider registry+ */++import { backtestingRegistry } from './BacktestingProviderRegistry';+import { IBacktestingProvider } from './interfaces/IBacktestingProvider';+import { StrategyDefinition } from './interfaces/IStrategyDefinition';+import {+ BacktestRequest,+ BacktestResult,+ OptimizationRequest,+ OptimizationResult,+ DataRequest,+ HistoricalData,+ IndicatorType,+ IndicatorParams,+ IndicatorResult,+} from './interfaces/types';++/**+ * BacktestingService+ *+ * Provides a convenient API for backtesting operations.+ * Automatically uses the active provider from the registry.+ */+export class BacktestingService {+ /**+ * Get active provider+ * @throws Error if no provider is active+ */+ private getActiveProvider(): IBacktestingProvider {+ const provider = backtestingRegistry.getActiveProvider();+ if (!provider) {+ throw new Error(+ 'No backtesting provider active. Please activate a provider in Settings.'+ );+ }+ return provider;+ }++ /**+ * Run a backtest using the active provider+ */+ async runBacktest(request: BacktestRequest): Promise<BacktestResult> {+ const provider = this.getActiveProvider();+ return provider.runBacktest(request);+ }++ /**+ * Run optimization using the active provider+ */+ async optimize(request: OptimizationRequest): Promise<OptimizationResult> {+ const provider = this.getActiveProvider();++ if (!provider.optimize) {+ throw new Error(+ `Active provider "${provider.name}" does not support optimization`+ );+ }++ return provider.optimize(request);+ }++ /**+ * Get historical data using the active provider+ */+ async getHistoricalData(+ request: DataRequest+ ): Promise<HistoricalData[]> {+ const provider = this.getActiveProvider();+ return provider.getHistoricalData(request);+ }++ /**+ * Calculate indicator using the active provider+ */+ async calculateIndicator(+ type: IndicatorType,+ params: IndicatorParams+ ): Promise<IndicatorResult> {+ const provider = this.getActiveProvider();+ return provider.calculateIndicator(type, params);+ }++ /**+ * Validate strategy using the active provider+ */+ async validateStrategy(strategy: StrategyDefinition): Promise<{+ valid: boolean;+ errors: string[];+ warnings: string[];+ }> {+ const provider = this.getActiveProvider();++ if (provider.validateStrategy) {+ const result = await provider.validateStrategy(strategy);+ return {+ ...result,+ warnings: result.warnings || []+ };+ }++ // Default basic validation+ const errors: string[] = [];+ const warnings: string[] = [];++ if (!strategy.name) errors.push('Strategy name is required');+ if (!strategy.type) errors.push('Strategy type is required');++ return { valid: errors.length === 0, errors, warnings };+ }++ /**+ * Get available data catalog from active provider+ */+ async getAvailableData() {+ const provider = this.getActiveProvider();+ return provider.getAvailableData();+ }++ /**+ * Get available indicators from active provider+ */+ async getAvailableIndicators() {+ const provider = this.getActiveProvider();+ return provider.getAvailableIndicators();+ }++ /**+ * Check if optimization is supported by active provider+ */+ isOptimizationSupported(): boolean {+ const provider = backtestingRegistry.getActiveProvider();+ return provider?.capabilities.optimization || false;+ }++ /**+ * Check if live trading is supported by active provider+ */+ isLiveTradingSupported(): boolean {+ const provider = backtestingRegistry.getActiveProvider();+ return provider?.capabilities.liveTrading || false;+ }++ /**+ * Check if research/notebooks is supported by active provider+ */+ isResearchSupported(): boolean {+ const provider = backtestingRegistry.getActiveProvider();+ return provider?.capabilities.research || false;+ }++ /**+ * Get active provider info+ */+ getActiveProviderInfo() {+ const provider = backtestingRegistry.getActiveProvider();+ if (!provider) return null;++ return {+ name: provider.name,+ version: provider.version,+ capabilities: provider.capabilities,+ description: provider.description,+ };+ }++ /**+ * Get health status of active provider+ */+ async getProviderHealth() {+ const provider = this.getActiveProvider();+ if (provider.getHealth) {+ return provider.getHealth();+ }+ return {+ status: 'healthy' as const,+ message: 'Health check not supported',+ };+ }+}++/**+ * Singleton instance export+ */+export const backtestingService = new BacktestingService();diff --git a/fincept-terminal-desktop/src/services/backtesting/StrategyTemplates.ts b/fincept-terminal-desktop/src/services/backtesting/StrategyTemplates.tsnew file mode 100644index 000000000..abd1db55f--- /dev/null+++ b/fincept-terminal-desktop/src/services/backtesting/StrategyTemplates.ts@@ -0,0 +1,510 @@+/**+ * Strategy Templates Library+ *+ * Pre-built strategy templates for quick backtesting.+ * Each template is a working strategy with configurable parameters.+ */++export interface StrategyTemplate {+ id: string;+ name: string;+ category: 'momentum' | 'mean-reversion' | 'trend-following' | 'breakout' | 'ml' | 'arbitrage';+ description: string;+ difficulty: 'beginner' | 'intermediate' | 'advanced';+ pythonCode: string;+ parameters: Array<{+ name: string;+ type: 'number' | 'string' | 'boolean';+ default: any;+ min?: number;+ max?: number;+ description: string;+ }>;+ requiredData: {+ symbols: string[];+ assetClass: string;+ resolution: string;+ minHistoryDays: number;+ };+ expectedPerformance?: {+ avgReturn: string;+ sharpeRange: string;+ maxDD: string;+ };+}++export const STRATEGY_TEMPLATES: StrategyTemplate[] = [+ {+ id: 'sma_crossover',+ name: 'Simple Moving Average Crossover',+ category: 'trend-following',+ difficulty: 'beginner',+ description: 'Classic trend-following strategy using fast and slow moving averages. Buys when fast crosses above slow, sells when fast crosses below slow.',+ pythonCode: `from AlgorithmImports import *++class SMA_Crossover(QCAlgorithm):+ """+ Simple Moving Average Crossover Strategy++ Parameters:+ - fast_period: Fast SMA period (default: {{fast_period}})+ - slow_period: Slow SMA period (default: {{slow_period}})+ - symbol: Trading symbol (default: {{symbol}})+ """++ def Initialize(self):+ self.SetStartDate(2020, 1, 1)+ self.SetEndDate(2023, 12, 31)+ self.SetCash(100000)++ # Parameters (will be replaced with actual values)+ self.fast_period = {{fast_period}}+ self.slow_period = {{slow_period}}+ self.symbol_name = "{{symbol}}"++ # Add equity+ self.symbol = self.AddEquity(self.symbol_name, Resolution.Daily).Symbol++ # Create indicators+ self.fast_sma = self.SMA(self.symbol, self.fast_period, Resolution.Daily)+ self.slow_sma = self.SMA(self.symbol, self.slow_period, Resolution.Daily)++ # Warm up indicators+ self.SetWarmUp(self.slow_period)++ def OnData(self, data):+ if self.IsWarmingUp:+ return++ if not self.fast_sma.IsReady or not self.slow_sma.IsReady:+ return++ # Get current indicator values+ fast = self.fast_sma.Current.Value+ slow = self.slow_sma.Current.Value++ # Buy signal: fast crosses above slow+ if fast > slow:+ if not self.Portfolio.Invested:+ self.SetHoldings(self.symbol, 1.0)+ self.Debug(f"BUY: Fast SMA ({fast:.2f}) > Slow SMA ({slow:.2f})")++ # Sell signal: fast crosses below slow+ elif fast < slow:+ if self.Portfolio.Invested:+ self.Liquidate(self.symbol)+ self.Debug(f"SELL: Fast SMA ({fast:.2f}) < Slow SMA ({slow:.2f})")+`,+ parameters: [+ { name: 'fast_period', type: 'number', default: 50, min: 10, max: 100, description: 'Fast moving average period' },+ { name: 'slow_period', type: 'number', default: 200, min: 100, max: 300, description: 'Slow moving average period' },+ { name: 'symbol', type: 'string', default: 'SPY', description: 'Trading symbol' },+ ],+ requiredData: {+ symbols: ['SPY'],+ assetClass: 'equity',+ resolution: 'daily',+ minHistoryDays: 365,+ },+ expectedPerformance: {+ avgReturn: '8-12% annually',+ sharpeRange: '0.8-1.2',+ maxDD: '15-25%',+ },+ },++ {+ id: 'rsi_mean_reversion',+ name: 'RSI Mean Reversion',+ category: 'mean-reversion',+ difficulty: 'beginner',+ description: 'Mean reversion strategy using RSI indicator. Buys when oversold (RSI < 30), sells when overbought (RSI > 70).',+ pythonCode: `from AlgorithmImports import *++class RSI_MeanReversion(QCAlgorithm):+ """+ RSI Mean Reversion Strategy++ Parameters:+ - rsi_period: RSI period (default: {{rsi_period}})+ - oversold_threshold: Oversold level (default: {{oversold_threshold}})+ - overbought_threshold: Overbought level (default: {{overbought_threshold}})+ """++ def Initialize(self):+ self.SetStartDate(2020, 1, 1)+ self.SetEndDate(2023, 12, 31)+ self.SetCash(100000)++ # Parameters+ self.rsi_period = {{rsi_period}}+ self.oversold = {{oversold_threshold}}+ self.overbought = {{overbought_threshold}}+ self.symbol_name = "{{symbol}}"++ # Add equity+ self.symbol = self.AddEquity(self.symbol_name, Resolution.Daily).Symbol++ # Create RSI indicator+ self.rsi = self.RSI(self.symbol, self.rsi_period, MovingAverageType.Wilders, Resolution.Daily)++ self.SetWarmUp(self.rsi_period)++ def OnData(self, data):+ if self.IsWarmingUp:+ return++ if not self.rsi.IsReady:+ return++ rsi_value = self.rsi.Current.Value++ # Buy signal: RSI below oversold threshold+ if rsi_value < self.oversold:+ if not self.Portfolio.Invested:+ self.SetHoldings(self.symbol, 1.0)+ self.Debug(f"BUY: RSI {rsi_value:.2f} < {self.oversold}")++ # Sell signal: RSI above overbought threshold+ elif rsi_value > self.overbought:+ if self.Portfolio.Invested:+ self.Liquidate(self.symbol)+ self.Debug(f"SELL: RSI {rsi_value:.2f} > {self.overbought}")+`,+ parameters: [+ { name: 'rsi_period', type: 'number', default: 14, min: 5, max: 30, description: 'RSI calculation period' },+ { name: 'oversold_threshold', type: 'number', default: 30, min: 20, max: 40, description: 'Oversold threshold for buying' },+ { name: 'overbought_threshold', type: 'number', default: 70, min: 60, max: 80, description: 'Overbought threshold for selling' },+ { name: 'symbol', type: 'string', default: 'SPY', description: 'Trading symbol' },+ ],+ requiredData: {+ symbols: ['SPY'],+ assetClass: 'equity',+ resolution: 'daily',+ minHistoryDays: 180,+ },+ expectedPerformance: {+ avgReturn: '10-15% annually',+ sharpeRange: '0.9-1.3',+ maxDD: '12-20%',+ },+ },++ {+ id: 'macd_momentum',+ name: 'MACD Momentum',+ category: 'momentum',+ difficulty: 'intermediate',+ description: 'Momentum strategy using MACD indicator. Trades based on MACD line crossing signal line.',+ pythonCode: `from AlgorithmImports import *++class MACD_Momentum(QCAlgorithm):+ """+ MACD Momentum Strategy++ Parameters:+ - fast_period: MACD fast period (default: {{fast_period}})+ - slow_period: MACD slow period (default: {{slow_period}})+ - signal_period: Signal line period (default: {{signal_period}})+ """++ def Initialize(self):+ self.SetStartDate(2020, 1, 1)+ self.SetEndDate(2023, 12, 31)+ self.SetCash(100000)++ # Parameters+ self.fast = {{fast_period}}+ self.slow = {{slow_period}}+ self.signal = {{signal_period}}+ self.symbol_name = "{{symbol}}"++ # Add equity+ self.symbol = self.AddEquity(self.symbol_name, Resolution.Daily).Symbol++ # Create MACD indicator+ self.macd = self.MACD(self.symbol, self.fast, self.slow, self.signal, MovingAverageType.Exponential, Resolution.Daily)++ self.SetWarmUp(max(self.fast, self.slow) + self.signal)++ def OnData(self, data):+ if self.IsWarmingUp:+ return++ if not self.macd.IsReady:+ return++ macd_value = self.macd.Current.Value+ signal_value = self.macd.Signal.Current.Value++ # Buy signal: MACD crosses above signal+ if macd_value > signal_value:+ if not self.Portfolio.Invested:+ self.SetHoldings(self.symbol, 1.0)+ self.Debug(f"BUY: MACD {macd_value:.2f} > Signal {signal_value:.2f}")++ # Sell signal: MACD crosses below signal+ elif macd_value < signal_value:+ if self.Portfolio.Invested:+ self.Liquidate(self.symbol)+ self.Debug(f"SELL: MACD {macd_value:.2f} < Signal {signal_value:.2f}")+`,+ parameters: [+ { name: 'fast_period', type: 'number', default: 12, min: 8, max: 20, description: 'Fast EMA period' },+ { name: 'slow_period', type: 'number', default: 26, min: 20, max: 40, description: 'Slow EMA period' },+ { name: 'signal_period', type: 'number', default: 9, min: 5, max: 15, description: 'Signal line period' },+ { name: 'symbol', type: 'string', default: 'SPY', description: 'Trading symbol' },+ ],+ requiredData: {+ symbols: ['SPY'],+ assetClass: 'equity',+ resolution: 'daily',+ minHistoryDays: 180,+ },+ expectedPerformance: {+ avgReturn: '12-18% annually',+ sharpeRange: '1.0-1.5',+ maxDD: '10-18%',+ },+ },++ {+ id: 'bollinger_breakout',+ name: 'Bollinger Bands Breakout',+ category: 'breakout',+ difficulty: 'intermediate',+ description: 'Breakout strategy using Bollinger Bands. Buys on upper band breakout, sells on lower band breakdown.',+ pythonCode: `from AlgorithmImports import *++class BollingerBreakout(QCAlgorithm):+ """+ Bollinger Bands Breakout Strategy++ Parameters:+ - bb_period: Bollinger Bands period (default: {{bb_period}})+ - bb_std_dev: Standard deviation multiplier (default: {{bb_std_dev}})+ """++ def Initialize(self):+ self.SetStartDate(2020, 1, 1)+ self.SetEndDate(2023, 12, 31)+ self.SetCash(100000)++ # Parameters+ self.period = {{bb_period}}+ self.std_dev = {{bb_std_dev}}+ self.symbol_name = "{{symbol}}"++ # Add equity+ self.symbol = self.AddEquity(self.symbol_name, Resolution.Daily).Symbol++ # Create Bollinger Bands+ self.bb = self.BB(self.symbol, self.period, self.std_dev, MovingAverageType.Simple, Resolution.Daily)++ self.SetWarmUp(self.period)++ def OnData(self, data):+ if self.IsWarmingUp:+ return++ if not self.bb.IsReady:+ return++ if not data.ContainsKey(self.symbol):+ return++ price = data[self.symbol].Close+ upper = self.bb.UpperBand.Current.Value+ lower = self.bb.LowerBand.Current.Value+ middle = self.bb.MiddleBand.Current.Value++ # Buy signal: price breaks above upper band+ if price > upper:+ if not self.Portfolio.Invested:+ self.SetHoldings(self.symbol, 1.0)+ self.Debug(f"BUY: Price {price:.2f} > Upper Band {upper:.2f}")++ # Sell signal: price breaks below lower band+ elif price < lower:+ if self.Portfolio.Invested:+ self.Liquidate(self.symbol)+ self.Debug(f"SELL: Price {price:.2f} < Lower Band {lower:.2f}")++ # Exit on mean reversion to middle band+ elif self.Portfolio.Invested and abs(price - middle) < (upper - middle) * 0.2:+ self.Liquidate(self.symbol)+ self.Debug(f"EXIT: Price {price:.2f} near Middle Band {middle:.2f}")+`,+ parameters: [+ { name: 'bb_period', type: 'number', default: 20, min: 10, max: 50, description: 'Bollinger Bands period' },+ { name: 'bb_std_dev', type: 'number', default: 2, min: 1, max: 3, description: 'Standard deviation multiplier' },+ { name: 'symbol', type: 'string', default: 'SPY', description: 'Trading symbol' },+ ],+ requiredData: {+ symbols: ['SPY'],+ assetClass: 'equity',+ resolution: 'daily',+ minHistoryDays: 120,+ },+ expectedPerformance: {+ avgReturn: '15-20% annually',+ sharpeRange: '1.1-1.6',+ maxDD: '12-22%',+ },+ },++ {+ id: 'pairs_trading',+ name: 'Pairs Trading (Cointegration)',+ category: 'arbitrage',+ difficulty: 'advanced',+ description: 'Statistical arbitrage strategy trading two cointegrated assets. Goes long/short based on spread deviation.',+ pythonCode: `from AlgorithmImports import *+import numpy as np++class PairsTrading(QCAlgorithm):+ """+ Pairs Trading Strategy++ Parameters:+ - symbol1: First symbol (default: {{symbol1}})+ - symbol2: Second symbol (default: {{symbol2}})+ - lookback: Lookback period for spread calculation (default: {{lookback}})+ - entry_z: Z-score threshold for entry (default: {{entry_z}})+ - exit_z: Z-score threshold for exit (default: {{exit_z}})+ """++ def Initialize(self):+ self.SetStartDate(2020, 1, 1)+ self.SetEndDate(2023, 12, 31)+ self.SetCash(100000)++ # Parameters+ self.lookback = {{lookback}}+ self.entry_z = {{entry_z}}+ self.exit_z = {{exit_z}}++ # Add symbols+ self.symbol1 = self.AddEquity("{{symbol1}}", Resolution.Daily).Symbol+ self.symbol2 = self.AddEquity("{{symbol2}}", Resolution.Daily).Symbol++ # Store price history+ self.history = []+ self.SetWarmUp(self.lookback)++ def OnData(self, data):+ if self.IsWarmingUp:+ return++ if not data.ContainsKey(self.symbol1) or not data.ContainsKey(self.symbol2):+ return++ price1 = data[self.symbol1].Close+ price2 = data[self.symbol2].Close++ # Calculate spread+ spread = price1 - price2+ self.history.append(spread)++ if len(self.history) < self.lookback:+ return++ # Keep only lookback period+ self.history = self.history[-self.lookback:]++ # Calculate z-score+ mean_spread = np.mean(self.history)+ std_spread = np.std(self.history)++ if std_spread == 0:+ return++ z_score = (spread - mean_spread) / std_spread++ # Entry signals+ if z_score > self.entry_z and not self.Portfolio.Invested:+ # Spread too high: short symbol1, long symbol2+ self.SetHoldings(self.symbol1, -0.5)+ self.SetHoldings(self.symbol2, 0.5)+ self.Debug(f"SHORT PAIR: Z-score {z_score:.2f}")++ elif z_score < -self.entry_z and not self.Portfolio.Invested:+ # Spread too low: long symbol1, short symbol2+ self.SetHoldings(self.symbol1, 0.5)+ self.SetHoldings(self.symbol2, -0.5)+ self.Debug(f"LONG PAIR: Z-score {z_score:.2f}")++ # Exit signals+ elif abs(z_score) < self.exit_z and self.Portfolio.Invested:+ self.Liquidate()+ self.Debug(f"EXIT: Z-score {z_score:.2f}")+`,+ parameters: [+ { name: 'symbol1', type: 'string', default: 'SPY', description: 'First symbol' },+ { name: 'symbol2', type: 'string', default: 'IWM', description: 'Second symbol (should be cointegrated)' },+ { name: 'lookback', type: 'number', default: 60, min: 30, max: 120, description: 'Lookback period for spread' },+ { name: 'entry_z', type: 'number', default: 2.0, min: 1.5, max: 3.0, description: 'Z-score entry threshold' },+ { name: 'exit_z', type: 'number', default: 0.5, min: 0.1, max: 1.0, description: 'Z-score exit threshold' },+ ],+ requiredData: {+ symbols: ['SPY', 'IWM'],+ assetClass: 'equity',+ resolution: 'daily',+ minHistoryDays: 180,+ },+ expectedPerformance: {+ avgReturn: '8-12% annually',+ sharpeRange: '1.5-2.0',+ maxDD: '8-15%',+ },+ },+];++/**+ * Get template by ID+ */+export function getTemplateById(id: string): StrategyTemplate | undefined {+ return STRATEGY_TEMPLATES.find((t) => t.id === id);+}++/**+ * Get templates by category+ */+export function getTemplatesByCategory(category: string): StrategyTemplate[] {+ return STRATEGY_TEMPLATES.filter((t) => t.category === category);+}++/**+ * Get templates by difficulty+ */+export function getTemplatesByDifficulty(difficulty: string): StrategyTemplate[] {+ return STRATEGY_TEMPLATES.filter((t) => t.difficulty === difficulty);+}++/**+ * Fill template with parameter values+ */+export function fillTemplate(template: StrategyTemplate, params: Record<string, any>): string {+ let code = template.pythonCode;++ // Replace all {{parameter}} placeholders+ for (const [key, value] of Object.entries(params)) {+ const placeholder = new RegExp(`\\{\\{${key}\\}\\}`, 'g');+ code = code.replace(placeholder, String(value));+ }++ // Fill any remaining placeholders with defaults+ for (const param of template.parameters) {+ const placeholder = new RegExp(`\\{\\{${param.name}\\}\\}`, 'g');+ code = code.replace(placeholder, String(param.default));+ }++ return code;+}++/**+ * Get all categories+ */+export function getAllCategories(): string[] {+ return Array.from(new Set(STRATEGY_TEMPLATES.map((t) => t.category)));+}diff --git a/fincept-terminal-desktop/src/services/backtesting/adapters/BaseAdapter.ts b/fincept-terminal-desktop/src/services/backtesting/adapters/BaseAdapter.tsnew file mode 100644index 000000000..a81339458--- /dev/null+++ b/fincept-terminal-desktop/src/services/backtesting/adapters/BaseAdapter.ts@@ -0,0 +1,434 @@+/**+ * Base Adapter for Backtesting Providers+ * Abstract base class that provides common functionality for all adapters+ */++import { IBacktestingProvider } from '../interfaces/IBacktestingProvider';+import { StrategyDefinition } from '../interfaces/IStrategyDefinition';+import {+ ProviderCapabilities,+ ProviderConfig,+ InitResult,+ TestResult,+ BacktestRequest,+ BacktestResult,+ BacktestStatus,+ OptimizationRequest,+ OptimizationResult,+ DataRequest,+ HistoricalData,+ DataCatalog,+ IndicatorType,+ IndicatorParams,+ IndicatorResult,+ IndicatorCatalog,+ LiveDeployRequest,+ LiveDeployResult,+ LiveStatus,+ NotebookResult,+} from '../interfaces/types';++/**+ * BaseBacktestingAdapter+ *+ * Base class that all provider adapters should extend.+ * Provides common functionality and helper methods.+ */+export abstract class BaseBacktestingAdapter implements IBacktestingProvider {+ // ============================================================================+ // Abstract Properties (must be implemented by subclasses)+ // ============================================================================++ abstract readonly name: string;+ abstract readonly version: string;+ abstract readonly capabilities: ProviderCapabilities;+ abstract readonly description?: string;++ // ============================================================================+ // Protected State+ // ============================================================================++ protected config: ProviderConfig | null = null;+ protected initialized: boolean = false;+ protected connected: boolean = false;++ // ============================================================================+ // Constructor+ // ============================================================================++ constructor() {+ // Base constructor - subclasses can extend if needed+ }++ // ============================================================================+ // Abstract Methods (must be implemented by subclasses)+ // ============================================================================++ abstract initialize(config: ProviderConfig): Promise<InitResult>;+ abstract testConnection(): Promise<TestResult>;+ abstract runBacktest(request: BacktestRequest): Promise<BacktestResult>;+ abstract getHistoricalData(request: DataRequest): Promise<HistoricalData[]>;+ abstract getAvailableData(): Promise<DataCatalog>;+ abstract calculateIndicator(+ type: IndicatorType,+ params: IndicatorParams+ ): Promise<IndicatorResult>;+ abstract getAvailableIndicators(): Promise<IndicatorCatalog>;++ // ============================================================================+ // Connection Management (default implementation)+ // ============================================================================++ async disconnect(): Promise<void> {+ this.connected = false;+ this.initialized = false;+ console.log(`Disconnected from ${this.name}`);+ }++ // ============================================================================+ // Backtest Status (default implementation - override if needed)+ // ============================================================================++ async getBacktestStatus(id: string): Promise<BacktestStatus> {+ // Default implementation - subclasses should override with actual status checking+ return {+ id,+ status: 'running',+ progress: 0,+ };+ }++ async cancelBacktest(id: string): Promise<void> {+ // Default implementation - subclasses should override+ console.warn(`Cancel backtest not implemented for ${this.name}`);+ }++ // ============================================================================+ // Optional Features (default implementations)+ // ============================================================================++ async optimize(request: OptimizationRequest): Promise<OptimizationResult> {+ throw new Error(`Optimization not supported by ${this.name}`);+ }++ async getOptimizationStatus(id: string): Promise<BacktestStatus> {+ throw new Error(`Optimization not supported by ${this.name}`);+ }++ async cancelOptimization(id: string): Promise<void> {+ throw new Error(`Optimization not supported by ${this.name}`);+ }++ async deployLive(request: LiveDeployRequest): Promise<LiveDeployResult> {+ throw new Error(`Live trading not supported by ${this.name}`);+ }++ async getLiveStatus(id: string): Promise<LiveStatus> {+ throw new Error(`Live trading not supported by ${this.name}`);+ }++ async stopLive(id: string): Promise<void> {+ throw new Error(`Live trading not supported by ${this.name}`);+ }++ async pauseLive(id: string): Promise<void> {+ throw new Error(`Live trading pause not supported by ${this.name}`);+ }++ async resumeLive(id: string): Promise<void> {+ throw new Error(`Live trading resume not supported by ${this.name}`);+ }++ async createNotebook(+ name: string,+ template?: string+ ): Promise<NotebookResult> {+ throw new Error(`Notebooks not supported by ${this.name}`);+ }++ async getNotebookTemplates(): Promise<string[]> {+ throw new Error(`Notebooks not supported by ${this.name}`);+ }++ async validateStrategy(strategy: StrategyDefinition): Promise<{+ valid: boolean;+ errors: string[];+ warnings?: string[];+ }> {+ // Default basic validation+ const errors: string[] = [];+ const warnings: string[] = [];++ if (!strategy.name) {+ errors.push('Strategy name is required');+ }++ if (!strategy.type) {+ errors.push('Strategy type is required');+ }++ if (strategy.type === 'code' && !strategy.code) {+ errors.push('Code strategy requires code definition');+ }++ if (strategy.type === 'visual' && !strategy.visual) {+ errors.push('Visual strategy requires visual definition');+ }++ if (strategy.type === 'template' && !strategy.template) {+ errors.push('Template strategy requires template definition');+ }++ return {+ valid: errors.length === 0,+ errors,+ warnings: warnings.length > 0 ? warnings : undefined,+ };+ }++ async getExampleStrategies(): Promise<StrategyDefinition[]> {+ // Default: no examples+ return [];+ }++ async getHealth(): Promise<{+ status: 'healthy' | 'degraded' | 'unhealthy';+ message?: string;+ details?: Record<string, any>;+ }> {+ // Default health check+ try {+ if (!this.initialized) {+ return {+ status: 'unhealthy',+ message: 'Provider not initialized',+ };+ }++ const testResult = await this.testConnection();++ return {+ status: testResult.success ? 'healthy' : 'unhealthy',+ message: testResult.message,+ details: {+ connected: this.connected,+ initialized: this.initialized,+ },+ };+ } catch (error) {+ return {+ status: 'unhealthy',+ message: error instanceof Error ? error.message : 'Unknown error',+ };+ }+ }++ async getUsageStats(): Promise<{+ totalBacktests: number;+ totalOptimizations: number;+ apiCallsRemaining?: number;+ quotaReset?: string;+ }> {+ // Default: no stats+ return {+ totalBacktests: 0,+ totalOptimizations: 0,+ };+ }++ // ============================================================================+ // Protected Helper Methods+ // ============================================================================++ /**+ * Validate configuration has required fields+ */+ protected validateConfig(+ config: ProviderConfig,+ requiredFields: string[]+ ): { valid: boolean; errors: string[] } {+ const errors: string[] = [];++ for (const field of requiredFields) {+ if (!(field in config) || !config[field as keyof ProviderConfig]) {+ errors.push(`Missing required configuration field: ${field}`);+ }+ }++ return {+ valid: errors.length === 0,+ errors,+ };+ }++ /**+ * Create success result+ */+ protected createSuccessResult(message: string): InitResult {+ return {+ success: true,+ message,+ };+ }++ /**+ * Create error result+ */+ protected createErrorResult(error: string | Error): InitResult {+ return {+ success: false,+ message: 'Initialization failed',+ error: error instanceof Error ? error.message : error,+ };+ }++ /**+ * Create test success result+ */+ protected createTestSuccessResult(+ message: string,+ metadata?: Record<string, any>+ ): TestResult {+ return {+ success: true,+ message,+ metadata,+ };+ }++ /**+ * Create test error result+ */+ protected createTestErrorResult(error: string | Error): TestResult {+ return {+ success: false,+ message: 'Connection test failed',+ error: error instanceof Error ? error.message : error,+ };+ }++ /**+ * Generate unique ID+ */+ protected generateId(): string {+ return `${this.name.toLowerCase().replace(/\s+/g, '-')}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;+ }++ /**+ * Log info message+ */+ protected log(message: string): void {+ console.log(`[${this.name}] ${message}`);+ }++ /**+ * Log warning message+ */+ protected warn(message: string): void {+ console.warn(`[${this.name}] ${message}`);+ }++ /**+ * Log error message+ */+ protected error(message: string, error?: Error): void {+ console.error(`[${this.name}] ${message}`, error || '');+ }++ /**+ * Check if provider is initialized+ */+ protected ensureInitialized(): void {+ if (!this.initialized) {+ throw new Error(`${this.name} is not initialized. Call initialize() first.`);+ }+ }++ /**+ * Check if provider is connected+ */+ protected ensureConnected(): void {+ this.ensureInitialized();+ if (!this.connected) {+ throw new Error(+ `${this.name} is not connected. Call testConnection() first.`+ );+ }+ }++ /**+ * Safe async operation with error handling+ */+ protected async safeAsync<T>(+ operation: () => Promise<T>,+ errorMessage: string+ ): Promise<T> {+ try {+ return await operation();+ } catch (error) {+ this.error(errorMessage, error as Error);+ throw error;+ }+ }++ /**+ * Parse date string to Date object+ */+ protected parseDate(dateStr: string): Date {+ const date = new Date(dateStr);+ if (isNaN(date.getTime())) {+ throw new Error(`Invalid date: ${dateStr}`);+ }+ return date;+ }++ /**+ * Format date to YYYY-MM-DD string+ */+ protected formatDate(date: Date): string {+ return date.toISOString().split('T')[0];+ }++ /**+ * Calculate date range in days+ */+ protected calculateDateRange(startDate: string, endDate: string): number {+ const start = this.parseDate(startDate);+ const end = this.parseDate(endDate);+ return Math.floor((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));+ }++ /**+ * Validate date range+ */+ protected validateDateRange(+ startDate: string,+ endDate: string+ ): { valid: boolean; error?: string } {+ try {+ const start = this.parseDate(startDate);+ const end = this.parseDate(endDate);++ if (start >= end) {+ return {+ valid: false,+ error: 'Start date must be before end date',+ };+ }++ if (end > new Date()) {+ return {+ valid: false,+ error: 'End date cannot be in the future',+ };+ }++ return { valid: true };+ } catch (error) {+ return {+ valid: false,+ error: error instanceof Error ? error.message : 'Invalid date range',+ };+ }+ }+}diff --git a/fincept-terminal-desktop/src/services/backtesting/adapters/custom/SimpleBacktester.ts b/fincept-terminal-desktop/src/services/backtesting/adapters/custom/SimpleBacktester.tsnew file mode 100644index 000000000..4cc52a747--- /dev/null+++ b/fincept-terminal-desktop/src/services/backtesting/adapters/custom/SimpleBacktester.ts@@ -0,0 +1,326 @@+/**+ * 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.tsnew file mode 100644index 000000000..168324410--- /dev/null+++ b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanAdapter.ts@@ -0,0 +1,545 @@+/**+ * Lean Adapter+ *+ * Main adapter implementation for QuantConnect Lean engine.+ * Implements IBacktestingProvider interface to enable platform-independent backtesting.+ */++import { invoke } from '@tauri-apps/api/core';+import { BaseBacktestingAdapter } from '../BaseAdapter';+import {+ ProviderCapabilities,+ ProviderConfig,+ InitResult,+ TestResult,+ BacktestRequest,+ BacktestResult,+ BacktestStatus,+ OptimizationRequest,+ OptimizationResult,+ DataRequest,+ HistoricalData,+ IndicatorType,+ IndicatorParams,+ IndicatorResult,+ DataCatalog,+ IndicatorCatalog,+ LiveDeployRequest,+ LiveDeployResult,+ NotebookResult,+ ValidationResult,+ HealthStatus,+} from '../../interfaces/types';+import { StrategyDefinition } from '../../interfaces/IStrategyDefinition';+import { LeanConfig, LEAN_CAPABILITIES, LeanRawBacktestResult } from './types';+import { LeanStrategyTranslator } from './LeanStrategyTranslator';+import { LeanCliExecutor } from './LeanCliExecutor';+import { LeanResultsParser } from './LeanResultsParser';++/**+ * LeanAdapter+ *+ * Complete implementation of IBacktestingProvider for QuantConnect Lean.+ * Handles strategy translation, CLI execution, and results parsing.+ */+export class LeanAdapter extends BaseBacktestingAdapter {+ readonly name = 'QuantConnect Lean';+ readonly version = '2.5.0'; // Lean CLI version+ readonly capabilities = LEAN_CAPABILITIES;+ readonly description = 'Institutional-grade algorithmic trading engine with 400TB+ of data';++ private leanConfig: LeanConfig | null = null;+ private cliExecutor: LeanCliExecutor | null = null;+ private strategyTranslator: LeanStrategyTranslator = new LeanStrategyTranslator();+ private resultsParser: LeanResultsParser = new LeanResultsParser();++ // Running backtests tracking+ private activeBacktests: Map<string, BacktestStatus> = new Map();++ // ============================================================================+ // Helper Methods for Path Operations+ // ============================================================================++ /**+ * Join path segments (cross-platform)+ */+ private joinPath(...segments: string[]): string {+ return segments.join('/').replace(/\/+/g, '/');+ }++ // ============================================================================+ // Core Methods (Required by IBacktestingProvider)+ // ============================================================================++ async initialize(config: ProviderConfig): Promise<InitResult> {+ try {+ // Validate Lean-specific config+ const leanConfig = config.settings as LeanConfig;++ if (!leanConfig.leanCliPath) {+ return this.createErrorResult('leanCliPath is required in config');+ }++ // Check if Lean CLI exists+ const cliExists = await this.checkLeanCliExists(leanConfig.leanCliPath);+ if (!cliExists) {+ return this.createErrorResult(+ `Lean CLI not found at: ${leanConfig.leanCliPath}. Please install Lean or update the path.`+ );+ }++ // Create necessary directories+ await this.ensureDirectories(leanConfig);++ // Initialize CLI executor+ this.leanConfig = leanConfig;+ this.cliExecutor = new LeanCliExecutor(leanConfig);++ this.config = config;+ this.initialized = true;++ return this.createSuccessResult(+ `Lean initialized successfully. CLI: ${leanConfig.leanCliPath}`+ );+ } catch (error) {+ return this.createErrorResult(error instanceof Error ? error : String(error));+ }+ }++ async testConnection(): Promise<TestResult> {+ this.ensureInitialized();++ try {+ // Test Lean CLI by running version check+ const result = await invoke<{+ success: boolean;+ stdout: string;+ stderr: string;+ }>('execute_command', {+ command: `${this.leanConfig!.leanCliPath} --version`,+ });++ if (!result.success) {+ return {+ success: false,+ message: 'Lean CLI test failed',+ error: result.stderr,+ };+ }++ this.connected = true;++ return {+ success: true,+ message: `Lean CLI is operational. Version: ${result.stdout.trim()}`,+ latency: 0,+ };+ } catch (error) {+ return {+ success: false,+ message: 'Failed to connect to Lean CLI',+ error: String(error),+ };+ }+ }++ async disconnect(): Promise<void> {+ // Cancel all running backtests+ for (const backtestId of this.activeBacktests.keys()) {+ try {+ await this.cancelBacktest(backtestId);+ } catch (error) {+ console.error(`Failed to cancel backtest ${backtestId}:`, error);+ }+ }++ this.activeBacktests.clear();+ this.connected = false;+ this.initialized = false;+ }++ async runBacktest(request: BacktestRequest): Promise<BacktestResult> {+ this.ensureConnected();++ const backtestId = this.generateId();++ try {+ // 1. Translate strategy to Lean Python code+ const pythonCode = this.strategyTranslator.translate(request.strategy);++ // 2. Create Lean project+ const projectPath = await this.createLeanProject(backtestId, pythonCode, request);++ // 3. Build CLI arguments+ const cliArgs = {+ algorithm: 'main.py',+ startDate: this.formatDateForLean(request.startDate),+ endDate: this.formatDateForLean(request.endDate),+ cash: request.initialCapital,+ parameters: request.parameters,+ dataFolder: this.leanConfig!.dataPath,+ resultsFolder: this.joinPath(this.leanConfig!.resultsPath, backtestId),+ };++ // 4. Execute backtest via CLI+ const execution = await this.cliExecutor!.runBacktest(projectPath, cliArgs);++ // Track as active+ this.activeBacktests.set(backtestId, {+ id: backtestId,+ status: 'running',+ progress: 0,+ message: 'Backtest started',+ });++ // 5. Wait for completion (or poll in production)+ const resultJson = await this.waitForBacktestCompletion(backtestId, execution.processId);++ // 6. Parse results+ const logs = this.cliExecutor!.getProcessStatus(backtestId)?.logs || [];+ const result = this.resultsParser.parseBacktestResult(backtestId, resultJson, logs);++ // Mark as completed+ this.activeBacktests.delete(backtestId);++ return result;+ } catch (error) {+ this.activeBacktests.delete(backtestId);+ throw new Error(`Backtest failed: ${error}`);+ }+ }++ async getBacktestStatus(id: string): Promise<BacktestStatus> {+ const status = this.activeBacktests.get(id);++ if (!status) {+ return {+ id,+ status: 'completed',+ progress: 100,+ message: 'Backtest not found or already completed',+ };+ }++ // Update progress from CLI executor+ const processStatus = this.cliExecutor!.getProcessStatus(id);+ if (processStatus) {+ status.progress = processStatus.progress || 0;+ status.message = processStatus.logs[processStatus.logs.length - 1] || status.message;+ }++ return status;+ }++ async cancelBacktest(id: string): Promise<void> {+ this.ensureConnected();++ await this.cliExecutor!.cancelBacktest(id);+ this.activeBacktests.delete(id);+ }++ async getHistoricalData(request: DataRequest): Promise<HistoricalData[]> {+ this.ensureConnected();++ try {+ // Use Lean's data download command+ await this.cliExecutor!.downloadData(+ request.symbols,+ request.timeframe,+ this.formatDateForLean(request.startDate),+ this.formatDateForLean(request.endDate),+ 'usa'+ );++ // Read downloaded data and convert to HistoricalData format+ const dataFiles = await this.readDownloadedData(request.symbols, request.timeframe);++ return dataFiles;+ } catch (error) {+ throw new Error(`Failed to fetch historical data: ${error}`);+ }+ }++ async getAvailableData(): Promise<DataCatalog> {+ return {+ markets: [+ { id: 'us-equity', name: 'US Equities', assetClasses: ['equity'] },+ { id: 'us-options', name: 'US Options', assetClasses: ['option'] },+ { id: 'forex', name: 'Forex', assetClasses: ['forex'] },+ { id: 'crypto', name: 'Cryptocurrency', assetClasses: ['crypto'] },+ { id: 'futures', name: 'Futures', assetClasses: ['future'] },+ ],+ timeframes: ['tick', 'second', 'minute', 'hour', 'daily'],+ dateRange: {+ start: '1998-01-01',+ end: new Date().toISOString().split('T')[0],+ },+ dataSize: '400TB+',+ description: 'QuantConnect data library with institutional-grade quality',+ };+ }++ async calculateIndicator(type: IndicatorType, params: IndicatorParams): Promise<IndicatorResult> {+ // For Lean, indicators are calculated within backtests+ // For standalone calculation, we'd need to create a minimal backtest+ throw new Error(+ 'Standalone indicator calculation not supported by Lean. Use indicators within backtests.'+ );+ }++ async getAvailableIndicators(): Promise<IndicatorCatalog> {+ return {+ categories: [+ {+ name: 'Trend',+ indicators: [+ { id: 'sma', name: 'Simple Moving Average', params: ['period'] },+ { id: 'ema', name: 'Exponential Moving Average', params: ['period'] },+ { id: 'macd', name: 'MACD', params: ['fast', 'slow', 'signal'] },+ ],+ },+ {+ name: 'Momentum',+ indicators: [+ { id: 'rsi', name: 'Relative Strength Index', params: ['period'] },+ { id: 'stoch', name: 'Stochastic Oscillator', params: ['period'] },+ ],+ },+ {+ name: 'Volatility',+ indicators: [+ { id: 'bb', name: 'Bollinger Bands', params: ['period', 'stdDev'] },+ { id: 'atr', name: 'Average True Range', params: ['period'] },+ ],+ },+ ],+ total: 100, // Lean has 100+ indicators+ description: 'Full suite of technical indicators built into Lean',+ };+ }++ // ============================================================================+ // Optional Methods+ // ============================================================================++ async optimize(request: OptimizationRequest): Promise<OptimizationResult> {+ this.ensureConnected();++ const optimizationId = this.generateId();++ try {+ // Create Lean project with optimization config+ const pythonCode = this.strategyTranslator.translate(request.strategy);+ const projectPath = await this.createLeanProject(optimizationId, pythonCode, request);++ // Build optimization CLI arguments+ const optimizationConfig = {+ target: request.optimizationTarget,+ constraints: request.constraints,+ parameters: request.parameterRanges,+ };++ // Execute optimization+ const execution = await this.cliExecutor!.runOptimization(+ projectPath,+ {+ algorithm: 'main.py',+ dataFolder: this.leanConfig!.dataPath,+ resultsFolder: this.joinPath(this.leanConfig!.resultsPath, optimizationId),+ },+ optimizationConfig+ );++ // Wait for completion+ const results = await this.waitForOptimizationCompletion(optimizationId, execution.processId);++ // Parse results+ const logs = this.cliExecutor!.getProcessStatus(optimizationId)?.logs || [];+ return this.resultsParser.parseOptimizationResult(optimizationId, results, logs);+ } catch (error) {+ throw new Error(`Optimization failed: ${error}`);+ }+ }++ async validateStrategy(strategy: StrategyDefinition): Promise<ValidationResult> {+ try {+ // Translate to Lean code+ const pythonCode = this.strategyTranslator.translate(strategy);++ // Validate syntax+ const syntaxValidation = this.strategyTranslator.validate(pythonCode);++ if (!syntaxValidation.valid) {+ return {+ valid: false,+ errors: syntaxValidation.errors,+ warnings: [],+ };+ }++ // Additional Lean-specific validation+ const errors: string[] = [];+ const warnings: string[] = [];++ // Check asset support+ if (strategy.requires.assets) {+ for (const asset of strategy.requires.assets) {+ if (!this.capabilities.multiAsset.includes(asset.assetClass as any)) {+ errors.push(`Asset class "${asset.assetClass}" not supported by Lean`);+ }+ }+ }++ return {+ valid: errors.length === 0,+ errors,+ warnings,+ };+ } catch (error) {+ return {+ valid: false,+ errors: [String(error)],+ warnings: [],+ };+ }+ }++ async deployLive(request: LiveDeployRequest): Promise<LiveDeployResult> {+ // Live trading would require Lean cloud or local brokerage connection+ throw new Error('Live trading deployment requires QuantConnect cloud subscription');+ }++ async createNotebook(name: string, template?: string): Promise<NotebookResult> {+ // Research notebooks would require Lean cloud or Jupyter integration+ throw new Error('Research notebooks require QuantConnect cloud subscription');+ }++ async getHealth(): Promise<HealthStatus> {+ if (!this.initialized) {+ return { status: 'unhealthy', message: 'Not initialized' };+ }++ if (!this.connected) {+ return { status: 'degraded', message: 'Not connected' };+ }++ return { status: 'healthy', message: 'All systems operational' };+ }++ // ============================================================================+ // Helper Methods+ // ============================================================================++ private async checkLeanCliExists(cliPath: string): Promise<boolean> {+ try {+ const result = await invoke<boolean>('check_file_exists', { path: cliPath });+ return result;+ } catch {+ return false;+ }+ }++ private async ensureDirectories(config: LeanConfig): Promise<void> {+ const dirs = [config.projectsPath, config.dataPath, config.resultsPath];++ for (const dir of dirs) {+ try {+ await invoke('create_directory', { path: dir });+ } catch (error) {+ console.error(`Failed to create directory ${dir}:`, error);+ }+ }+ }++ private async createLeanProject(+ projectId: string,+ pythonCode: string,+ request: BacktestRequest | OptimizationRequest+ ): Promise<string> {+ const projectPath = this.joinPath(this.leanConfig!.projectsPath, projectId);++ // Create project directory+ await invoke('create_directory', { path: projectPath });++ // Write main.py+ const mainFilePath = this.joinPath(projectPath, 'main.py');+ await invoke('write_file', {+ path: mainFilePath,+ content: pythonCode,+ });++ // Write config.json if needed+ // (Lean config would go here)++ return projectPath;+ }++ private async waitForBacktestCompletion(+ backtestId: string,+ processId: number+ ): Promise<LeanRawBacktestResult> {+ // In production, this would poll the process status+ // For now, simulate with a wait++ return new Promise((resolve, reject) => {+ const checkInterval = setInterval(async () => {+ const status = this.cliExecutor!.getProcessStatus(backtestId);++ if (status?.status === 'completed') {+ clearInterval(checkInterval);++ // Read results file+ const resultsPath = this.joinPath(+ this.leanConfig!.resultsPath,+ backtestId,+ 'results.json'+ );++ try {+ const resultsJson = await invoke<string>('read_file', {+ path: resultsPath,+ });+ resolve(JSON.parse(resultsJson));+ } catch (error) {+ reject(new Error(`Failed to read results: ${error}`));+ }+ } else if (status?.status === 'failed') {+ clearInterval(checkInterval);+ reject(new Error(status.error || 'Backtest failed'));+ }+ }, 1000);++ // Timeout after 1 hour+ setTimeout(() => {+ clearInterval(checkInterval);+ reject(new Error('Backtest timeout'));+ }, 3600000);+ });+ }++ private async waitForOptimizationCompletion(+ optimizationId: string,+ processId: number+ ): Promise<any[]> {+ // Similar to backtest completion, but returns array of results+ return [];+ }++ private async readDownloadedData(+ symbols: string[],+ timeframe: string+ ): Promise<HistoricalData[]> {+ // Read Lean data files and convert to our format+ // Lean stores data in specific directory structure+ return [];+ }++ private formatDateForLean(isoDate: string): string {+ // Convert ISO date to YYYYMMDD format for Lean CLI+ const date = new Date(isoDate);+ const year = date.getFullYear();+ const month = String(date.getMonth() + 1).padStart(2, '0');+ const day = String(date.getDate()).padStart(2, '0');+ return `${year}${month}${day}`;+ }+}diff --git a/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanCliExecutor.ts b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanCliExecutor.tsnew file mode 100644index 000000000..f00bc92fd--- /dev/null+++ b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanCliExecutor.ts@@ -0,0 +1,340 @@+/**+ * Lean CLI Executor+ *+ * Handles execution of Lean CLI commands through Tauri.+ * Manages process lifecycle, output parsing, and error handling.+ */++import { invoke } from '@tauri-apps/api/core';+import { LeanCliArgs, LeanConfig, LeanProcessStatus, LeanError } from './types';++/**+ * CLI Command Result+ */+interface CliCommandResult {+ success: boolean;+ stdout?: string;+ stderr?: string;+ exitCode?: number;+ error?: string;+}++/**+ * LeanCliExecutor+ *+ * Executes Lean CLI commands and manages process lifecycle.+ * Uses Tauri commands to bridge to Rust backend which runs actual CLI.+ */+export class LeanCliExecutor {+ private config: LeanConfig;+ private runningProcesses: Map<string, LeanProcessStatus> = new Map();++ constructor(config: LeanConfig) {+ this.config = config;+ }++ /**+ * Run a backtest using Lean CLI+ *+ * @param projectPath Path to Lean project+ * @param args CLI arguments+ * @returns Process ID for tracking+ */+ async runBacktest(+ projectPath: string,+ args: LeanCliArgs+ ): Promise<{ id: string; processId: number }> {+ const backtestId = this.generateId();++ // Build CLI command+ const command = this.buildCliCommand('backtest', projectPath, args);++ // Initialize process status+ this.runningProcesses.set(backtestId, {+ status: 'running',+ progress: 0,+ logs: [],+ });++ try {+ // Execute via Tauri command (Rust backend)+ const result = await invoke<{ process_id: number }>('execute_lean_cli', {+ command,+ workingDir: projectPath,+ backtestId,+ });++ this.runningProcesses.get(backtestId)!.pid = result.process_id;++ return {+ id: backtestId,+ processId: result.process_id,+ };+ } catch (error) {+ this.runningProcesses.get(backtestId)!.status = 'failed';+ this.runningProcesses.get(backtestId)!.error = String(error);+ throw error;+ }+ }++ /**+ * Run optimization using Lean CLI+ */+ async runOptimization(+ projectPath: string,+ args: LeanCliArgs,+ optimizationConfig: any+ ): Promise<{ id: string; processId: number }> {+ const optimizationId = this.generateId();++ const command = this.buildCliCommand('optimize', projectPath, {+ ...args,+ optimizationConfig,+ });++ this.runningProcesses.set(optimizationId, {+ status: 'running',+ progress: 0,+ logs: [],+ });++ try {+ const result = await invoke<{ process_id: number }>('execute_lean_cli', {+ command,+ workingDir: projectPath,+ backtestId: optimizationId,+ });++ this.runningProcesses.get(optimizationId)!.pid = result.process_id;++ return {+ id: optimizationId,+ processId: result.process_id,+ };+ } catch (error) {+ this.runningProcesses.get(optimizationId)!.status = 'failed';+ this.runningProcesses.get(optimizationId)!.error = String(error);+ throw error;+ }+ }++ /**+ * Download historical data using Lean CLI+ */+ async downloadData(+ tickers: string[],+ resolution: string,+ startDate: string,+ endDate: string,+ market: string = 'usa'+ ): Promise<CliCommandResult> {+ const command = [+ this.config.leanCliPath,+ 'data',+ 'download',+ '--tickers',+ tickers.join(','),+ '--resolution',+ resolution,+ '--start',+ startDate,+ '--end',+ endDate,+ '--market',+ market,+ '--data-folder',+ this.config.dataPath,+ ].join(' ');++ return this.executeCommand(command);+ }++ /**+ * Create a new Lean project+ */+ async createProject(+ projectName: string,+ language: 'python' = 'python'+ ): Promise<CliCommandResult> {+ const command = [+ this.config.leanCliPath,+ 'project',+ 'create',+ '--name',+ projectName,+ '--language',+ language,+ '--path',+ this.config.projectsPath,+ ].join(' ');++ return this.executeCommand(command);+ }++ /**+ * Get status of a running process+ */+ getProcessStatus(backtestId: string): LeanProcessStatus | null {+ return this.runningProcesses.get(backtestId) || null;+ }++ /**+ * Cancel a running backtest+ */+ async cancelBacktest(backtestId: string): Promise<void> {+ const process = this.runningProcesses.get(backtestId);+ if (!process || !process.pid) {+ throw new Error(`Process ${backtestId} not found or not running`);+ }++ try {+ await invoke('kill_lean_process', {+ processId: process.pid,+ });++ process.status = 'completed'; // Mark as stopped+ this.runningProcesses.delete(backtestId);+ } catch (error) {+ throw new Error(`Failed to cancel backtest: ${error}`);+ }+ }++ /**+ * Update process status (called by Rust backend via events)+ */+ updateProcessStatus(backtestId: string, update: Partial<LeanProcessStatus>): void {+ const existing = this.runningProcesses.get(backtestId);+ if (existing) {+ this.runningProcesses.set(backtestId, {+ ...existing,+ ...update,+ });+ }+ }++ /**+ * Append log to process+ */+ appendLog(backtestId: string, log: string): void {+ const process = this.runningProcesses.get(backtestId);+ if (process) {+ process.logs.push(log);+ }+ }++ /**+ * Build CLI command from arguments+ */+ private buildCliCommand(+ mode: 'backtest' | 'optimize' | 'live' | 'research',+ projectPath: string,+ args: LeanCliArgs+ ): string {+ const commandParts = [this.config.leanCliPath];++ // Mode+ commandParts.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());+ }++ // Data folder+ if (args.dataFolder || this.config.dataPath) {+ commandParts.push('--data-folder', args.dataFolder || this.config.dataPath);+ }++ // Results folder+ if (args.resultsFolder || this.config.resultsPath) {+ commandParts.push('--results', args.resultsFolder || this.config.resultsPath);+ }++ // Parameters (as JSON)+ if (args.parameters && Object.keys(args.parameters).length > 0) {+ commandParts.push('--parameters', JSON.stringify(args.parameters));+ }++ // Environment+ if (args.environment) {+ commandParts.push('--environment', args.environment);+ }++ // Flags+ if (args.release) {+ commandParts.push('--release');+ }+ if (args.update) {+ commandParts.push('--update');+ }++ return commandParts.join(' ');+ }++ /**+ * Execute a generic CLI command+ */+ private async executeCommand(command: string): Promise<CliCommandResult> {+ try {+ const result = await invoke<{+ success: boolean;+ stdout: string;+ stderr: string;+ exit_code: number;+ }>('execute_command', { command });++ return {+ success: result.success,+ stdout: result.stdout,+ stderr: result.stderr,+ exitCode: result.exit_code,+ };+ } catch (error) {+ return {+ success: false,+ error: String(error),+ };+ }+ }++ /**+ * Generate unique ID+ */+ private generateId(): string {+ return `lean_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;+ }++ /**+ * Clean up completed processes (optional)+ */+ cleanupCompletedProcesses(): void {+ for (const [id, process] of this.runningProcesses.entries()) {+ if (process.status === 'completed' || process.status === 'failed') {+ this.runningProcesses.delete(id);+ }+ }+ }++ /**+ * Get all running processes+ */+ getRunningProcesses(): Map<string, LeanProcessStatus> {+ return new Map(this.runningProcesses);+ }+}diff --git a/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanResultsParser.ts b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanResultsParser.tsnew file mode 100644index 000000000..8576a9cc0--- /dev/null+++ b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanResultsParser.ts@@ -0,0 +1,432 @@+/**+ * Lean Results Parser+ *+ * Parses Lean backtest results from JSON output into platform-independent format.+ * Converts Lean-specific structures to our BacktestResult interface.+ */++import {+ BacktestResult,+ PerformanceMetrics,+ Trade,+ EquityPoint,+ BacktestStatistics,+ ChartData,+} from '../../interfaces/types';+import {+ LeanRawBacktestResult,+ LeanRawOptimizationResult,+ LeanChartSeries,+ LeanOrder,+} from './types';++/**+ * LeanResultsParser+ *+ * Converts Lean CLI output to platform-independent BacktestResult.+ */+export class LeanResultsParser {+ /**+ * Parse complete backtest result from Lean JSON output+ */+ parseBacktestResult(+ backtestId: string,+ leanResult: LeanRawBacktestResult,+ logs: string[]+ ): BacktestResult {+ try {+ return {+ id: backtestId,+ status: 'completed',+ performance: this.parsePerformanceMetrics(leanResult),+ trades: this.parseTrades(leanResult),+ equity: this.parseEquityCurve(leanResult),+ statistics: this.parseStatistics(leanResult),+ charts: this.parseCharts(leanResult),+ logs,+ startTime: this.extractStatistic(leanResult, 'Start'),+ endTime: this.extractStatistic(leanResult, 'End'),+ duration: this.calculateDuration(leanResult),+ };+ } catch (error) {+ return this.createErrorResult(backtestId, String(error), logs);+ }+ }++ /**+ * Parse performance metrics+ */+ private parsePerformanceMetrics(result: LeanRawBacktestResult): PerformanceMetrics {+ const stats = result.TotalPerformance?.PortfolioStatistics || {};+ const tradeStats = result.TotalPerformance?.TradeStatistics || {};++ return {+ // Returns+ totalReturn: this.parsePercent(stats.TotalReturn) || 0,+ annualizedReturn: this.parsePercent(stats.AnnualReturn) || 0,++ // Risk Metrics+ sharpeRatio: this.parseFloat(stats.SharpeRatio) || 0,+ sortinoRatio: this.parseFloat(stats.SortinoRatio) || 0,+ maxDrawdown: this.parsePercent(stats.MaxDrawdown) || 0,+ volatility: this.parsePercent(stats.AnnualStandardDeviation) || 0,++ // Trade Statistics+ winRate: this.parsePercent(tradeStats.WinRate) || 0,+ lossRate: this.parsePercent(tradeStats.LossRate) || 0,+ totalTrades: Number(tradeStats.TotalNumberOfTrades) || 0,+ winningTrades: this.calculateWinningTrades(tradeStats),+ losingTrades: this.calculateLosingTrades(tradeStats),++ // Win/Loss Metrics+ averageWin: this.parseFloat(tradeStats.AverageWin) || 0,+ averageLoss: Math.abs(this.parseFloat(tradeStats.AverageLoss) || 0),+ largestWin: this.parseFloat(tradeStats.LargestWin) || 0,+ largestLoss: Math.abs(this.parseFloat(tradeStats.LargestLoss) || 0),++ // Other Metrics+ profitFactor: this.parseFloat(tradeStats.ProfitLossRatio) || 0,+ averageTradeReturn: this.parseFloat(tradeStats.AverageProfit) || 0,+ expectancy: this.calculateExpectancy(tradeStats),++ // Advanced (optional)+ calmarRatio: this.calculateCalmarRatio(stats),+ alpha: this.parseFloat(stats.Alpha),+ beta: this.parseFloat(stats.Beta),+ informationRatio: this.parseFloat(stats.InformationRatio),+ treynorRatio: this.parseFloat(stats.TreynorRatio),+ };+ }++ /**+ * Parse trades from Lean orders+ */+ private parseTrades(result: LeanRawBacktestResult): Trade[] {+ if (!result.Orders) return [];++ const orders = Object.values(result.Orders);+ const trades: Trade[] = [];++ // Group orders into trades (entry + exit pairs)+ // Simplified - Lean has complex order tracking+ // Full implementation would match entries and exits properly++ for (const order of orders) {+ if (order.Status !== 'Filled') continue;++ trades.push({+ id: `trade_${order.Id}`,+ symbol: order.Symbol,+ entryDate: order.Time,+ side: order.Quantity > 0 ? 'long' : 'short',+ quantity: Math.abs(order.Quantity),+ entryPrice: order.Price,+ commission: 0, // Would need to extract from Lean+ slippage: 0,+ // Exit fields would be filled when matching exit order+ exitDate: undefined,+ exitPrice: undefined,+ pnl: undefined,+ pnlPercent: undefined,+ holdingPeriod: undefined,+ exitReason: undefined,+ });+ }++ return trades;+ }++ /**+ * Parse equity curve+ */+ private parseEquityCurve(result: LeanRawBacktestResult): EquityPoint[] {+ if (!result.Charts || !result.Charts['Strategy Equity']) {+ return [];+ }++ const equityChart = result.Charts['Strategy Equity'];+ const equitySeries = equityChart.Series['Equity'];++ if (!equitySeries || !equitySeries.Values) {+ return [];+ }++ const points: EquityPoint[] = [];+ let previousEquity = 0;++ for (const point of equitySeries.Values) {+ const equity = point.y;+ const returns = previousEquity > 0 ? (equity - previousEquity) / previousEquity : 0;++ points.push({+ date: new Date(point.x * 1000).toISOString(), // Unix timestamp to ISO+ equity,+ returns,+ drawdown: this.calculateDrawdown(equity, points),+ benchmark: this.extractBenchmark(result, point.x),+ });++ previousEquity = equity;+ }++ return points;+ }++ /**+ * Parse general statistics+ */+ private parseStatistics(result: LeanRawBacktestResult): BacktestStatistics {+ const stats = result.Statistics || [];+ const runtimeStats = result.RuntimeStatistics || [];++ return {+ startDate: this.extractStatistic(result, 'Start') || '',+ endDate: this.extractStatistic(result, 'End') || '',+ initialCapital: this.parseFloat(this.extractStatistic(result, 'Equity')) || 100000,+ finalCapital:+ this.parseFloat(this.extractStatistic(result, 'Net Profit')) || 100000,+ totalFees: this.parseFloat(this.extractStatistic(result, 'Fees')) || 0,+ totalSlippage: 0, // Would extract from Lean if available+ totalTrades: this.parseFloat(this.extractStatistic(result, 'Total Trades')) || 0,+ winningDays: 0, // Calculate from equity curve+ losingDays: 0,+ averageDailyReturn: 0,+ bestDay: 0,+ worstDay: 0,+ consecutiveWins: 0,+ consecutiveLosses: 0,+ maxDrawdownDate: undefined,+ recoveryTime: undefined,+ };+ }++ /**+ * Parse charts for visualization+ */+ private parseCharts(result: LeanRawBacktestResult): ChartData[] | undefined {+ if (!result.Charts) return undefined;++ const charts: ChartData[] = [];++ for (const [chartName, chartData] of Object.entries(result.Charts)) {+ for (const [seriesName, seriesData] of Object.entries(chartData.Series)) {+ charts.push({+ type: this.mapChartType(chartData.ChartType) as any,+ title: `${chartName} - ${seriesName}`,+ data: seriesData.Values.map((v) => ({+ x: new Date(v.x * 1000).toISOString(),+ y: v.y,+ })),+ });+ }+ }++ return charts;+ }++ /**+ * Parse optimization result+ */+ parseOptimizationResult(+ optimizationId: string,+ results: LeanRawOptimizationResult[],+ logs: string[]+ ): any {+ if (!results || results.length === 0) {+ throw new Error('No optimization results found');+ }++ // Find best result (highest Sharpe Ratio or other metric)+ const bestResult = this.findBestOptimizationResult(results);++ return {+ id: optimizationId,+ status: 'completed',+ best_parameters: bestResult.ParameterSet,+ best_result: bestResult, // Would parse to full BacktestResult+ all_results: results.map((r) => ({+ parameters: r.ParameterSet,+ statistics: this.parseStatisticsArray(r.Statistics),+ })),+ iterations: results.length,+ duration: 0, // Calculate from timestamps+ error: undefined,+ };+ }++ /**+ * Create error result+ */+ private createErrorResult(+ backtestId: string,+ error: string,+ logs: string[]+ ): BacktestResult {+ return {+ id: backtestId,+ status: 'failed',+ error,+ logs,+ performance: this.getEmptyMetrics(),+ trades: [],+ equity: [],+ statistics: this.getEmptyStatistics(),+ };+ }++ // ============================================================================+ // Helper Methods+ // ============================================================================++ private parseFloat(value: any): number | undefined {+ if (value === null || value === undefined) return undefined;+ const num = typeof value === 'string' ? parseFloat(value) : Number(value);+ return isNaN(num) ? undefined : num;+ }++ private parsePercent(value: any): number {+ if (!value) return 0;+ const str = String(value).replace('%', '');+ return parseFloat(str) / 100;+ }++ private extractStatistic(result: LeanRawBacktestResult, key: string): string | undefined {+ const stat = result.Statistics?.find((s) => s.Key === key);+ return stat?.Value;+ }++ private parseStatisticsArray(stats: Array<{ Key: string; Value: string }>): any {+ const parsed: any = {};+ for (const stat of stats) {+ parsed[stat.Key] = stat.Value;+ }+ return parsed;+ }++ private calculateWinningTrades(tradeStats: any): number {+ const total = Number(tradeStats.TotalNumberOfTrades) || 0;+ const winRate = this.parsePercent(tradeStats.WinRate) || 0;+ return Math.round(total * winRate);+ }++ private calculateLosingTrades(tradeStats: any): number {+ const total = Number(tradeStats.TotalNumberOfTrades) || 0;+ const lossRate = this.parsePercent(tradeStats.LossRate) || 0;+ return Math.round(total * lossRate);+ }++ private calculateExpectancy(tradeStats: any): number {+ const avgWin = this.parseFloat(tradeStats.AverageWin) || 0;+ const avgLoss = Math.abs(this.parseFloat(tradeStats.AverageLoss) || 0);+ const winRate = this.parsePercent(tradeStats.WinRate) || 0;+ const lossRate = this.parsePercent(tradeStats.LossRate) || 0;++ return winRate * avgWin - lossRate * avgLoss;+ }++ private calculateCalmarRatio(stats: any): number {+ const annualReturn = this.parsePercent(stats.AnnualReturn) || 0;+ const maxDrawdown = Math.abs(this.parsePercent(stats.MaxDrawdown) || 1);+ return maxDrawdown !== 0 ? annualReturn / maxDrawdown : 0;+ }++ private calculateDrawdown(currentEquity: number, points: EquityPoint[]): number {+ if (points.length === 0) return 0;++ const maxEquity = Math.max(...points.map((p) => p.equity), currentEquity);+ return maxEquity > 0 ? (currentEquity - maxEquity) / maxEquity : 0;+ }++ private extractBenchmark(result: LeanRawBacktestResult, timestamp: number): number | undefined {+ // Extract benchmark data if available in charts+ const benchmarkChart = result.Charts?.['Benchmark'];+ if (!benchmarkChart) return undefined;++ // Would find closest benchmark point to timestamp+ return undefined;+ }++ private calculateDuration(result: LeanRawBacktestResult): number | undefined {+ const start = this.extractStatistic(result, 'Start');+ const end = this.extractStatistic(result, 'End');++ if (!start || !end) return undefined;++ const startTime = new Date(start).getTime();+ const endTime = new Date(end).getTime();++ return endTime - startTime;+ }++ private findBestOptimizationResult(+ results: LeanRawOptimizationResult[]+ ): LeanRawOptimizationResult {+ // Find result with highest Sharpe Ratio+ let best = results[0];+ let bestSharpe = -Infinity;++ for (const result of results) {+ const sharpe =+ this.parseFloat(result.Statistics.find((s) => s.Key === 'Sharpe Ratio')?.Value) || 0;+ if (sharpe > bestSharpe) {+ bestSharpe = sharpe;+ best = result;+ }+ }++ return best;+ }++ private mapChartType(leanType: string): 'line' | 'candlestick' | 'bar' | 'area' {+ const map: Record<string, any> = {+ Line: 'line',+ Stock: 'candlestick',+ Scatter: 'line',+ Pie: 'bar',+ };+ return map[leanType] || 'line';+ }++ 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/LeanStrategyTranslator.ts b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanStrategyTranslator.tsnew file mode 100644index 000000000..21b2824f5--- /dev/null+++ b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanStrategyTranslator.ts@@ -0,0 +1,378 @@+/**+ * Lean Strategy Translator+ *+ * Translates platform-independent StrategyDefinition to Lean Python code.+ * Handles code, visual (node editor), and template-based strategies.+ */++import { StrategyDefinition } from '../../interfaces/IStrategyDefinition';+import { LeanStrategyTemplate } from './types';++/**+ * LeanStrategyTranslator+ *+ * Converts generic strategy definitions to Lean-compatible Python code.+ */+export class LeanStrategyTranslator {+ /**+ * Translate StrategyDefinition to Lean Python code+ */+ translate(strategy: StrategyDefinition): string {+ switch (strategy.type) {+ case 'code':+ return this.translateCodeStrategy(strategy);+ case 'visual':+ return this.translateVisualStrategy(strategy);+ case 'template':+ return this.translateTemplateStrategy(strategy);+ default:+ throw new Error(`Unknown strategy type: ${strategy.type}`);+ }+ }++ /**+ * Translate code-based strategy+ *+ * For code strategies, we wrap the user's Python code in a Lean QCAlgorithm class+ * if it's not already wrapped.+ */+ private translateCodeStrategy(strategy: StrategyDefinition): string {+ if (!strategy.code || strategy.code.language !== 'python') {+ throw new Error('Code strategy must have Python code');+ }++ const userCode = strategy.code.source;++ // Check if code already defines a QCAlgorithm class+ if (userCode.includes('class') && userCode.includes('QCAlgorithm')) {+ // User provided complete Lean algorithm, use as-is+ return this.addStrategyMetadata(userCode, strategy);+ }++ // Otherwise, wrap in a basic QCAlgorithm template+ return this.wrapInQCAlgorithm(userCode, strategy);+ }++ /**+ * Translate visual (node-based) strategy+ *+ * Generates Lean Python code from node editor graph.+ */+ private translateVisualStrategy(strategy: StrategyDefinition): string {+ if (!strategy.visual) {+ throw new Error('Visual strategy must have visual definition');+ }++ // If already generated, use that+ if (strategy.visual.generatedPython) {+ return this.wrapInQCAlgorithm(strategy.visual.generatedPython, strategy);+ }++ // Otherwise, generate from nodes+ const generatedCode = this.generateFromNodes(strategy.visual.nodes, strategy.visual.edges);+ return this.wrapInQCAlgorithm(generatedCode, strategy);+ }++ /**+ * Translate template-based strategy+ *+ * Fills in a pre-built template with user parameters.+ */+ private translateTemplateStrategy(strategy: StrategyDefinition): string {+ if (!strategy.template) {+ throw new Error('Template strategy must have template definition');+ }++ // Load template (templates would be stored in a registry)+ const template = this.loadTemplate(strategy.template.templateId);++ // Replace parameters+ const filledCode = this.fillTemplate(template.pythonCode, strategy.template.parameters);++ return this.addStrategyMetadata(filledCode, strategy);+ }++ /**+ * Wrap user code in QCAlgorithm class structure+ */+ private wrapInQCAlgorithm(userCode: string, strategy: StrategyDefinition): string {+ const className = this.sanitizeClassName(strategy.name);++ return `+# ==============================================================================+# Lean Algorithm: ${strategy.name}+# Version: ${strategy.version}+# Author: ${strategy.author}+# Description: ${strategy.description}+# Generated by Fincept Terminal+# ==============================================================================++from AlgorithmImports import *++class ${className}(QCAlgorithm):+ """+ ${strategy.description}+ """++ def Initialize(self):+ """Initialize algorithm settings and data subscriptions"""++ # Set date range (will be overridden by CLI args)+ self.SetStartDate(${this.formatDateForLean(strategy.requires.startDate || '2020-01-01')})+ self.SetEndDate(${this.formatDateForLean(strategy.requires.endDate || new Date().toISOString())})++ # Set initial capital+ self.SetCash(${strategy.requires.capital})++ # Set brokerage model+ ${this.getBrokerageModel(strategy)}++ # Subscribe to data+ ${this.generateDataSubscriptions(strategy)}++ # User initialization code+ ${this.indentCode(userCode, 2)}++ def OnData(self, data):+ """Event handler for data updates"""+ # User OnData logic would be extracted from userCode+ # For now, pass to user-defined methods+ pass++ def OnEndOfAlgorithm(self):+ """Called at the end of the algorithm"""+ self.Debug(f"Algorithm completed: {self.Portfolio.TotalPortfolioValue}")++# ==============================================================================+# End of Algorithm+# ==============================================================================+`.trim();+ }++ /**+ * Generate code from visual nodes+ *+ * This is a simplified version - full implementation would traverse the node graph+ * and generate appropriate code for each node type.+ */+ private generateFromNodes(nodes: any[], edges: any[]): string {+ const codeLines: string[] = [];++ // Sort nodes by execution order (based on edges)+ const sortedNodes = this.topologicalSort(nodes, edges);++ for (const node of sortedNodes) {+ switch (node.type) {+ case 'dataSource':+ codeLines.push(this.generateDataSourceCode(node));+ break;+ case 'indicator':+ codeLines.push(this.generateIndicatorCode(node));+ break;+ case 'condition':+ codeLines.push(this.generateConditionCode(node));+ break;+ case 'signal':+ codeLines.push(this.generateSignalCode(node));+ break;+ case 'order':+ codeLines.push(this.generateOrderCode(node));+ break;+ default:+ codeLines.push(`# Unknown node type: ${node.type}`);+ }+ }++ return codeLines.join('\n\n');+ }++ /**+ * Generate data subscription code+ */+ private generateDataSubscriptions(strategy: StrategyDefinition): string {+ const subscriptions: string[] = [];++ if (strategy.requires.assets) {+ for (const asset of strategy.requires.assets) {+ const symbol = asset.symbol;+ const resolution = this.getLeanResolution('daily'); // Use default as asset doesn't have timeframe++ subscriptions.push(+ `self.AddEquity("${symbol}", ${resolution})`+ );+ }+ }++ return subscriptions.join('\n ');+ }++ /**+ * Get Lean brokerage model+ */+ private getBrokerageModel(strategy: StrategyDefinition): string {+ // Default to simulation for backtesting+ return 'self.SetBrokerageModel(BrokerageName.Default)';+ }++ /**+ * Convert timeframe to Lean resolution+ */+ private getLeanResolution(timeframe: string): string {+ const map: Record<string, string> = {+ 'tick': 'Resolution.Tick',+ 'second': 'Resolution.Second',+ 'minute': 'Resolution.Minute',+ 'hour': 'Resolution.Hour',+ 'daily': 'Resolution.Daily',+ };+ return map[timeframe] || 'Resolution.Daily';+ }++ /**+ * Format date for Lean (year, month, day)+ */+ private formatDateForLean(isoDate: string): string {+ const date = new Date(isoDate);+ return `${date.getFullYear()}, ${date.getMonth() + 1}, ${date.getDate()}`;+ }++ /**+ * Sanitize class name (remove special chars, spaces)+ */+ private sanitizeClassName(name: string): string {+ return name+ .replace(/[^a-zA-Z0-9]/g, '_')+ .replace(/^[0-9]/, '_$&')+ .replace(/_+/g, '_');+ }++ /**+ * Add metadata comments to existing code+ */+ private addStrategyMetadata(code: string, strategy: StrategyDefinition): string {+ const metadata = `+# ==============================================================================+# Strategy: ${strategy.name}+# Version: ${strategy.version}+# Author: ${strategy.author}+# Description: ${strategy.description}+# Generated by Fincept Terminal+# ==============================================================================++`.trim();++ return metadata + '\n\n' + code;+ }++ /**+ * Indent code by specified levels (2 spaces per level)+ */+ private indentCode(code: string, levels: number): string {+ const indent = ' '.repeat(levels);+ return code+ .split('\n')+ .map((line) => (line.trim() ? indent + line : line))+ .join('\n');+ }++ /**+ * Topological sort for node execution order+ */+ private topologicalSort(nodes: any[], edges: any[]): any[] {+ // Simplified - just return nodes in order for now+ // Full implementation would do proper topological sort based on edges+ return [...nodes];+ }++ /**+ * Generate code for data source node+ */+ private generateDataSourceCode(node: any): string {+ const symbol = node.data.symbol;+ const resolution = this.getLeanResolution(node.data.timeframe || 'daily');+ return `self.${node.id} = self.AddEquity("${symbol}", ${resolution})`;+ }++ /**+ * Generate code for indicator node+ */+ private generateIndicatorCode(node: any): string {+ const indicator = node.data.indicator;+ const period = node.data.period;+ const symbol = node.data.symbol;++ return `self.${node.id} = self.${indicator}("${symbol}", ${period})`;+ }++ /**+ * Generate code for condition node+ */+ private generateConditionCode(node: any): string {+ const condition = node.data.condition;+ return `# Condition: ${condition}`;+ }++ /**+ * Generate code for signal node+ */+ private generateSignalCode(node: any): string {+ const signal = node.data.signal;+ return `# Signal: ${signal}`;+ }++ /**+ * Generate code for order node+ */+ private generateOrderCode(node: any): string {+ const action = node.data.action;+ const symbol = node.data.symbol;+ const quantity = node.data.quantity;++ return `self.${action}("${symbol}", ${quantity})`;+ }++ /**+ * Load template by ID (stub - would load from registry)+ */+ private loadTemplate(templateId: string): LeanStrategyTemplate {+ // This would load from a template registry+ // For now, return a stub+ throw new Error(`Template ${templateId} not found`);+ }++ /**+ * Fill template with parameters+ */+ private fillTemplate(template: string, params: Record<string, any>): string {+ let filled = template;++ for (const [key, value] of Object.entries(params)) {+ const placeholder = new RegExp(`\\{\\{${key}\\}\\}`, 'g');+ filled = filled.replace(placeholder, String(value));+ }++ return filled;+ }++ /**+ * Validate generated Lean code (basic syntax check)+ */+ validate(pythonCode: string): { valid: boolean; errors: string[] } {+ const errors: string[] = [];++ // Check for required imports+ if (!pythonCode.includes('QCAlgorithm')) {+ errors.push('Code must define or import QCAlgorithm');+ }++ // Check for Initialize method+ if (!pythonCode.includes('def Initialize')) {+ errors.push('Algorithm must have Initialize method');+ }++ return {+ valid: errors.length === 0,+ errors,+ };+ }+}diff --git a/fincept-terminal-desktop/src/services/backtesting/adapters/lean/index.ts b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/index.tsnew file mode 100644index 000000000..a568ba241--- /dev/null+++ b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/index.ts@@ -0,0 +1,11 @@+/**+ * Lean Adapter Module+ *+ * Exports all Lean-related components for easy importing.+ */++export { LeanAdapter } from './LeanAdapter';+export { LeanStrategyTranslator } from './LeanStrategyTranslator';+export { LeanCliExecutor } from './LeanCliExecutor';+export { LeanResultsParser } from './LeanResultsParser';+export * from './types';diff --git a/fincept-terminal-desktop/src/services/backtesting/adapters/lean/types.ts b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/types.tsnew file mode 100644index 000000000..2a1388dce--- /dev/null+++ b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/types.ts@@ -0,0 +1,343 @@+/**+ * Lean-Specific Types+ *+ * Type definitions specific to QuantConnect Lean integration.+ * These types map to Lean's CLI arguments, configuration, and response formats.+ */++import { ProviderCapabilities, AssetClass, Timeframe } from '../../interfaces/types';++/**+ * Lean CLI Configuration+ * Maps to Lean CLI arguments and config.json settings+ */+export interface LeanConfig {+ // Paths+ leanCliPath: string; // Path to lean executable+ projectsPath: string; // Path to Lean projects directory+ dataPath: string; // Path to Lean data directory+ resultsPath: string; // Path to results output++ // API Configuration (optional - for cloud features)+ apiUrl?: string; // QuantConnect API URL+ apiToken?: string; // User API token+ organizationId?: string; // Organization ID++ // Environment+ environment: 'backtesting' | 'live' | 'optimization' | 'research';++ // Advanced Settings+ maxConcurrentBacktests?: number; // Max parallel backtests+ pythonPath?: string; // Custom Python interpreter path+ enableLogging?: boolean; // Enable detailed logging+ logLevel?: 'debug' | 'info' | 'warn' | 'error';++ // Data Settings+ dataProvider?: 'local' | 'quantconnect' | 'iqfeed' | 'interactive-brokers';+ resolution?: Timeframe;+}++/**+ * Lean Project Structure+ * Represents a Lean algorithm project+ */+export interface LeanProject {+ name: string;+ description: string;+ created: string;+ modified: string;++ // Files+ mainFile: string; // main.py+ configFile?: string; // config.json+ requirementsFile?: string; // requirements.txt++ // Settings+ language: 'Python'; // We only support Python+ parameters?: Record<string, any>; // Algorithm parameters+}++/**+ * Lean CLI Arguments+ * Command-line arguments for running Lean+ */+export interface LeanCliArgs {+ // Required+ algorithm: string; // Algorithm file path++ // Backtest Settings+ startDate?: string; // YYYYMMDD format+ endDate?: string; // YYYYMMDD format+ cash?: number; // Initial capital++ // Data Settings+ dataFolder?: string;+ resultsFolder?: string;++ // Advanced+ parameters?: Record<string, any>; // Algorithm parameters as JSON+ environment?: string; // Environment name++ // Optimization Settings+ optimizationConfig?: any; // Optimization configuration++ // Flags+ release?: boolean; // Release mode+ update?: boolean; // Update data+}++/**+ * Lean Backtest Result (Raw from Lean)+ * Structure returned by Lean CLI after backtest+ */+export interface LeanRawBacktestResult {+ // Run Information+ AlgorithmId?: string;++ // Statistics+ Statistics?: Array<{+ Key: string;+ Value: string;+ }>;++ // Performance+ TotalPerformance?: {+ PortfolioStatistics?: {+ TotalReturn?: string;+ AnnualReturn?: string;+ AnnualStandardDeviation?: string;+ SharpeRatio?: string;+ SortinoRatio?: string;+ MaxDrawdown?: string;+ Alpha?: string;+ Beta?: string;+ InformationRatio?: string;+ TreynorRatio?: string;+ // ... more statistics+ };+ TradeStatistics?: {+ TotalNumberOfTrades?: number;+ WinRate?: string;+ LossRate?: string;+ AverageWin?: string;+ AverageLoss?: string;+ LargestWin?: string;+ LargestLoss?: string;+ AverageProfit?: string;+ ProfitLossRatio?: string;+ // ... more trade stats+ };+ };++ // Charts+ Charts?: Record<string, LeanChartSeries>;++ // Orders+ Orders?: Record<string, LeanOrder>;++ // Runtime Statistics+ RuntimeStatistics?: Array<{+ Key: string;+ Value: string;+ }>;++ // Alpha Runtime Statistics+ AlphaRuntimeStatistics?: any;++ // Logs+ Logs?: string[];++ // State (for live)+ State?: string;+}++/**+ * Lean Chart Series+ */+export interface LeanChartSeries {+ Name: string;+ ChartType: 'Stock' | 'Line' | 'Scatter' | 'Pie';+ Series: Record<string, {+ Name: string;+ Unit: string;+ Values: Array<{+ x: number; // Unix timestamp+ y: number;+ }>;+ }>;+}++/**+ * Lean Order+ */+export interface LeanOrder {+ Id: number;+ Type: string;+ Status: string;+ Time: string;+ Symbol: string;+ Quantity: number;+ Price: number;+ Value: number;+ Tag: string;+}++/**+ * Lean Optimization Result (Raw)+ */+export interface LeanRawOptimizationResult {+ ParameterSet: Record<string, any>;+ Statistics: Array<{+ Key: string;+ Value: string;+ }>;+ BacktestId?: string;+}++/**+ * Lean Data Request Format+ * Maps to Lean's data download CLI+ */+export interface LeanDataRequest {+ tickers: string[];+ resolution: 'daily' | 'hour' | 'minute' | 'second' | 'tick';+ startDate: string; // YYYYMMDD+ endDate: string; // YYYYMMDD+ market?: string; // us-equity, forex, crypto, etc.+ securityType?: 'Equity' | 'Forex' | 'Crypto' | 'Option' | 'Future';+}++/**+ * Lean Indicator Configuration+ */+export interface LeanIndicatorConfig {+ name: string; // SMA, EMA, RSI, etc.+ period?: number;+ symbol: string;+ resolution: Timeframe;+ parameters?: Record<string, any>;+}++/**+ * Lean Capabilities (Static)+ * What Lean supports as a platform+ */+export const LEAN_CAPABILITIES: ProviderCapabilities = {+ backtesting: true,+ optimization: true,+ liveTrading: true,+ research: true,++ multiAsset: [+ 'equity' as AssetClass,+ 'forex' as AssetClass,+ 'crypto' as AssetClass,+ 'option' as AssetClass,+ 'future' as AssetClass,+ 'cfd' as AssetClass+ ],++ indicators: true,+ customStrategies: true,+ maxConcurrentBacktests: 5,++ supportedTimeframes: [+ 'tick' as Timeframe,+ 'second' as Timeframe,+ 'minute' as Timeframe,+ 'hour' as Timeframe,+ 'daily' as Timeframe+ ],++ supportedMarkets: [+ 'us-equity',+ 'us-options',+ 'forex',+ 'crypto',+ 'futures',+ 'cfd'+ ]+};++/**+ * Lean Error Response+ */+export interface LeanError {+ message: string;+ stackTrace?: string;+ type?: string;+ timestamp: string;+}++/**+ * Lean Process Status+ */+export interface LeanProcessStatus {+ pid?: number;+ status: 'idle' | 'running' | 'completed' | 'failed';+ progress?: number; // 0-100+ currentDate?: string; // Current backtest date+ logs: string[];+ error?: string;+}++/**+ * Lean Strategy Template+ * Pre-built strategy templates+ */+export interface LeanStrategyTemplate {+ id: string;+ name: string;+ description: string;+ category: 'momentum' | 'mean-reversion' | 'arbitrage' | 'ml' | 'custom';+ pythonCode: string;+ parameters: Array<{+ name: string;+ type: 'number' | 'string' | 'boolean';+ default: any;+ min?: number;+ max?: number;+ options?: any[];+ }>;+ requiredData: {+ symbols: string[];+ resolution: Timeframe;+ assetClass: AssetClass;+ };+}++/**+ * Lean Config.json Structure+ * The configuration file Lean reads+ */+export interface LeanConfigJson {+ 'algorithm-type-name': string;+ 'algorithm-language': 'Python';+ 'algorithm-location': string;++ 'data-folder': string;+ 'data-provider': string;++ 'job-user-id': string;+ 'api-access-token': string;++ 'parameters': Record<string, string>;++ 'debugging': boolean;+ 'debugging-method': string;++ 'log-handler': string;+ 'messaging-handler': string;+ 'job-queue-handler': string;+ 'api-handler': string;++ 'result-handler': string;+ 'map-file-provider': string;+ 'factor-file-provider': string;+ 'data-downloader': string;++ 'environments': {+ backtesting: any;+ live: any;+ };+}diff --git a/fincept-terminal-desktop/src/services/backtesting/adapters/vectorbt/VectorBTAdapter.ts b/fincept-terminal-desktop/src/services/backtesting/adapters/vectorbt/VectorBTAdapter.tsnew file mode 100644index 000000000..564960f05--- /dev/null+++ b/fincept-terminal-desktop/src/services/backtesting/adapters/vectorbt/VectorBTAdapter.ts@@ -0,0 +1,269 @@+/**+ * VectorBT Adapter+ *+ * Adapter for VectorBT - fast backtesting library using vectorized operations.+ * Specializes in high-performance backtesting with NumPy/Pandas.+ */++import { invoke } from '@tauri-apps/api/core';+import { BaseBacktestingAdapter } from '../BaseAdapter';+import {+ ProviderCapabilities,+ ProviderConfig,+ InitResult,+ TestResult,+ BacktestRequest,+ BacktestResult,+ BacktestStatus,+ DataRequest,+ HistoricalData,+ IndicatorType,+ IndicatorParams,+ IndicatorResult,+ DataCatalog,+ IndicatorCatalog,+ ValidationResult,+ HealthStatus,+} from '../../interfaces/types';+import { StrategyDefinition } from '../../interfaces/IStrategyDefinition';++/**+ * VectorBT Capabilities+ */+const VECTORBT_CAPABILITIES: ProviderCapabilities = {+ backtesting: true,+ optimization: true,+ liveTrading: false,+ research: true,++ multiAsset: ['stocks' as const, 'crypto' as const, 'forex' as const],++ indicators: true,+ customStrategies: true,+ maxConcurrentBacktests: 10, // VectorBT is very fast++ supportedTimeframes: ['tick', 'second', 'minute', 'hour', 'daily'],++ supportedMarkets: ['us-equity', 'crypto', 'forex']+};++/**+ * VectorBT Adapter+ */+export class VectorBTAdapter extends BaseBacktestingAdapter {+ readonly name = 'VectorBT';+ readonly version = '0.25.0';+ readonly capabilities = VECTORBT_CAPABILITIES;+ readonly description = 'Ultra-fast vectorized backtesting with NumPy/Pandas';++ private activeBacktests: Map<string, BacktestStatus> = new Map();++ async initialize(config: ProviderConfig): Promise<InitResult> {+ try {+ this.ensureInitialized();++ // Test Python and VectorBT availability+ const result = await invoke<{ success: boolean; stdout: string }>('execute_python_backtest', {+ provider: 'vectorbt',+ command: 'test_import',+ args: JSON.stringify({}),+ });++ if (!result.success) {+ return this.createErrorResult('VectorBT not installed. Run: pip install vectorbt');+ }++ this.config = config;+ this.initialized = true;++ return this.createSuccessResult('VectorBT initialized successfully');+ } catch (error) {+ return this.createErrorResult(error instanceof Error ? error : String(error));+ }+ }++ async testConnection(): Promise<TestResult> {+ this.ensureInitialized();++ try {+ const result = await invoke<{ success: boolean; stdout: string }>('execute_python_backtest', {+ provider: 'vectorbt',+ command: 'test_connection',+ args: JSON.stringify({}),+ });++ if (!result.success) {+ return {+ success: false,+ message: 'VectorBT connection test failed',+ error: 'Failed to import vectorbt module',+ };+ }++ this.connected = true;++ const response = JSON.parse(result.stdout);+ return {+ success: true,+ message: `VectorBT ${response.version} is available`,+ latency: 0,+ };+ } catch (error) {+ return {+ success: false,+ message: 'Connection test failed',+ error: String(error),+ };+ }+ }++ async disconnect(): Promise<void> {+ this.activeBacktests.clear();+ this.connected = false;+ this.initialized = false;+ }++ async runBacktest(request: BacktestRequest): Promise<BacktestResult> {+ this.ensureConnected();++ const backtestId = this.generateId();++ try {+ // Track as active+ this.activeBacktests.set(backtestId, {+ id: backtestId,+ status: 'running',+ progress: 0,+ message: 'Running VectorBT backtest...',+ });++ // Execute Python backtest+ const result = await invoke<{ success: boolean; stdout: string }>('execute_python_backtest', {+ provider: 'vectorbt',+ command: 'run_backtest',+ args: JSON.stringify({+ id: backtestId,+ strategy: request.strategy,+ startDate: request.startDate,+ endDate: request.endDate,+ initialCapital: request.initialCapital,+ assets: request.assets,+ parameters: request.parameters,+ }),+ });++ this.activeBacktests.delete(backtestId);++ if (!result.success) {+ throw new Error('VectorBT backtest failed');+ }++ const backtestResult = JSON.parse(result.stdout);+ return backtestResult as BacktestResult;+ } catch (error) {+ this.activeBacktests.delete(backtestId);+ throw new Error(`VectorBT backtest failed: ${error}`);+ }+ }++ async getBacktestStatus(id: string): Promise<BacktestStatus> {+ const status = this.activeBacktests.get(id);+ if (!status) {+ return {+ id,+ status: 'completed',+ progress: 100,+ message: 'Backtest not found or already completed',+ };+ }+ return status;+ }++ async cancelBacktest(id: string): Promise<void> {+ this.activeBacktests.delete(id);+ }++ async getHistoricalData(request: DataRequest): Promise<HistoricalData[]> {+ // VectorBT can use any data source (yfinance, ccxt, etc.)+ return [];+ }++ async getAvailableData(): Promise<DataCatalog> {+ return {+ markets: [+ { id: 'us-equity', name: 'US Equities', assetClasses: ['equity'] },+ { id: 'crypto', name: 'Cryptocurrency', assetClasses: ['crypto'] },+ { id: 'forex', name: 'Forex', assetClasses: ['forex'] },+ ],+ timeframes: ['tick', 'second', 'minute', 'hour', 'daily'],+ dateRange: {+ start: '2000-01-01',+ end: new Date().toISOString().split('T')[0],+ },+ dataSize: 'Flexible (uses yfinance, ccxt, etc.)',+ description: 'VectorBT supports multiple data sources',+ };+ }++ async calculateIndicator(type: IndicatorType, params: IndicatorParams): Promise<IndicatorResult> {+ throw new Error('Use VectorBT indicators within backtests');+ }++ async getAvailableIndicators(): Promise<IndicatorCatalog> {+ return {+ categories: [+ {+ name: 'Trend',+ indicators: [+ { id: 'sma', name: 'Simple Moving Average', params: ['window'] },+ { id: 'ema', name: 'Exponential Moving Average', params: ['span'] },+ { id: 'bb', name: 'Bollinger Bands', params: ['window', 'alpha'] },+ ],+ },+ {+ name: 'Momentum',+ indicators: [+ { id: 'rsi', name: 'RSI', params: ['window'] },+ { id: 'macd', name: 'MACD', params: ['fast', 'slow', 'signal'] },+ ],+ },+ {+ name: 'Volatility',+ indicators: [+ { id: 'atr', name: 'ATR', params: ['window'] },+ { id: 'stdev', name: 'Standard Deviation', params: ['window'] },+ ],+ },+ ],+ total: 50,+ description: 'VectorBT has 50+ vectorized indicators',+ };+ }++ async validateStrategy(strategy: StrategyDefinition): Promise<ValidationResult> {+ const errors: string[] = [];+ const warnings: string[] = [];++ if (!strategy.code || strategy.code.language !== 'python') {+ errors.push('VectorBT requires Python strategy code');+ }++ return {+ valid: errors.length === 0,+ errors,+ warnings,+ };+ }++ async getHealth(): Promise<HealthStatus> {+ if (!this.initialized) {+ return { status: 'unhealthy', message: 'Not initialized' };+ }++ if (!this.connected) {+ return { status: 'degraded', message: 'Not connected' };+ }++ return { status: 'healthy', message: 'VectorBT operational' };+ }+}diff --git a/fincept-terminal-desktop/src/services/backtesting/interfaces/IBacktestingProvider.ts b/fincept-terminal-desktop/src/services/backtesting/interfaces/IBacktestingProvider.tsnew file mode 100644index 000000000..4b4b580bd--- /dev/null+++ b/fincept-terminal-desktop/src/services/backtesting/interfaces/IBacktestingProvider.ts@@ -0,0 +1,347 @@+/**+ * Backtesting Provider Interface+ * Core interface that ALL backtesting engines must implement+ * This ensures platform independence - terminal works with any provider+ */++import { StrategyDefinition } from './IStrategyDefinition';+import {+ ProviderCapabilities,+ ProviderConfig,+ InitResult,+ TestResult,+ BacktestRequest,+ BacktestResult,+ BacktestStatus,+ OptimizationRequest,+ OptimizationResult,+ DataRequest,+ HistoricalData,+ DataCatalog,+ IndicatorType,+ IndicatorParams,+ IndicatorResult,+ IndicatorCatalog,+ LiveDeployRequest,+ LiveDeployResult,+ LiveStatus,+ NotebookResult,+} from './types';++/**+ * IBacktestingProvider - Provider-agnostic interface+ *+ * All backtesting engines (Lean, Backtrader, VectorBT, QuantLib, custom)+ * must implement this interface to work with Fincept Terminal.+ *+ * This is the ONLY interface the terminal core uses for backtesting.+ * No provider-specific code should exist outside of adapter implementations.+ */+export interface IBacktestingProvider {+ // ============================================================================+ // Provider Metadata (readonly properties)+ // ============================================================================++ /**+ * Provider name (e.g., "QuantConnect Lean", "Backtrader", "VectorBT")+ */+ readonly name: string;++ /**+ * Provider version+ */+ readonly version: string;++ /**+ * Provider capabilities - what features this provider supports+ */+ readonly capabilities: ProviderCapabilities;++ /**+ * Provider description+ */+ readonly description?: string;++ // ============================================================================+ // Connection & Initialization+ // ============================================================================++ /**+ * Initialize the provider with configuration+ * Called when provider is first registered or when config changes+ *+ * @param config Provider-specific configuration+ * @returns Result indicating success or failure+ */+ initialize(config: ProviderConfig): Promise<InitResult>;++ /**+ * Test connection to provider+ * Used to validate configuration and check provider availability+ *+ * @returns Result with connection status and metadata+ */+ testConnection(): Promise<TestResult>;++ /**+ * Disconnect from provider+ * Clean up resources, close connections+ */+ disconnect(): Promise<void>;++ // ============================================================================+ // Backtesting (Core Feature)+ // ============================================================================++ /**+ * Run a backtest with the given strategy and configuration+ * This is the core functionality that all providers MUST implement+ *+ * @param request Backtest request with strategy, dates, capital, assets+ * @returns Backtest result with performance metrics, trades, equity curve+ */+ runBacktest(request: BacktestRequest): Promise<BacktestResult>;++ /**+ * Get status of a running backtest+ *+ * @param id Backtest ID+ * @returns Current status and progress+ */+ getBacktestStatus(id: string): Promise<BacktestStatus>;++ /**+ * Cancel a running backtest+ *+ * @param id Backtest ID+ */+ cancelBacktest(id: string): Promise<void>;++ // ============================================================================+ // Optimization (Optional but Recommended)+ // ============================================================================++ /**+ * Run parameter optimization+ * Tests multiple parameter combinations to find optimal values+ *+ * @param request Optimization request with parameter grid and objective+ * @returns Optimization result with best parameters and all iterations+ */+ optimize?(request: OptimizationRequest): Promise<OptimizationResult>;++ /**+ * Get status of running optimization+ *+ * @param id Optimization ID+ * @returns Current status and progress+ */+ getOptimizationStatus?(id: string): Promise<BacktestStatus>;++ /**+ * Cancel running optimization+ *+ * @param id Optimization ID+ */+ cancelOptimization?(id: string): Promise<void>;++ // ============================================================================+ // Data Access+ // ============================================================================++ /**+ * Get historical price data+ *+ * @param request Data request with symbols, dates, timeframe+ * @returns Historical data for requested symbols+ */+ getHistoricalData(request: DataRequest): Promise<HistoricalData[]>;++ /**+ * Get catalog of available data+ * Lists what data this provider can access+ *+ * @returns Data catalog with providers, asset classes, date ranges+ */+ getAvailableData(): Promise<DataCatalog>;++ // ============================================================================+ // Indicators+ // ============================================================================++ /**+ * Calculate technical indicator+ *+ * @param type Indicator type (sma, ema, rsi, etc.)+ * @param params Indicator parameters (period, etc.)+ * @returns Indicator values+ */+ calculateIndicator(+ type: IndicatorType,+ params: IndicatorParams+ ): Promise<IndicatorResult>;++ /**+ * Get list of available indicators+ *+ * @returns Catalog of supported indicators with parameters+ */+ getAvailableIndicators(): Promise<IndicatorCatalog>;++ // ============================================================================+ // Live Trading (Optional)+ // ============================================================================++ /**+ * Deploy strategy to live trading+ *+ * @param request Live deployment request+ * @returns Deployment result with ID and status+ */+ deployLive?(request: LiveDeployRequest): Promise<LiveDeployResult>;++ /**+ * Get status of live trading deployment+ *+ * @param id Deployment ID+ * @returns Current live status with equity, positions, trades+ */+ getLiveStatus?(id: string): Promise<LiveStatus>;++ /**+ * Stop live trading+ *+ * @param id Deployment ID+ */+ stopLive?(id: string): Promise<void>;++ /**+ * Pause live trading (if supported)+ *+ * @param id Deployment ID+ */+ pauseLive?(id: string): Promise<void>;++ /**+ * Resume paused live trading+ *+ * @param id Deployment ID+ */+ resumeLive?(id: string): Promise<void>;++ // ============================================================================+ // Research/Notebooks (Optional)+ // ============================================================================++ /**+ * Create research notebook+ * For providers that support Jupyter/notebook environments+ *+ * @param name Notebook name+ * @param template Optional template to use+ * @returns Notebook result with URL+ */+ createNotebook?(name: string, template?: string): Promise<NotebookResult>;++ /**+ * Get list of available notebook templates+ *+ * @returns Array of template names+ */+ getNotebookTemplates?(): Promise<string[]>;++ // ============================================================================+ // Strategy Management (Optional)+ // ============================================================================++ /**+ * Validate strategy before running+ * Checks if strategy is compatible with this provider+ *+ * @param strategy Strategy definition+ * @returns Validation result with errors/warnings+ */+ validateStrategy?(strategy: StrategyDefinition): Promise<{+ valid: boolean;+ errors: string[];+ warnings?: string[];+ }>;++ /**+ * Get example strategies for this provider+ *+ * @returns Array of example strategy definitions+ */+ getExampleStrategies?(): Promise<StrategyDefinition[]>;++ // ============================================================================+ // Utility Methods (Optional)+ // ============================================================================++ /**+ * Get provider-specific health status+ *+ * @returns Health status information+ */+ getHealth?(): Promise<{+ status: 'healthy' | 'degraded' | 'unhealthy';+ message?: string;+ details?: Record<string, any>;+ }>;++ /**+ * Get provider usage statistics+ *+ * @returns Usage stats (API calls, backtests run, etc.)+ */+ getUsageStats?(): Promise<{+ totalBacktests: number;+ totalOptimizations: number;+ apiCallsRemaining?: number;+ quotaReset?: string;+ }>;+}++/**+ * Type guard to check if optimization is supported+ */+export function supportsOptimization(+ provider: IBacktestingProvider+): provider is IBacktestingProvider & {+ optimize: NonNullable<IBacktestingProvider['optimize']>;+} {+ return (+ provider.capabilities.optimization &&+ typeof provider.optimize === 'function'+ );+}++/**+ * Type guard to check if live trading is supported+ */+export function supportsLiveTrading(+ provider: IBacktestingProvider+): provider is IBacktestingProvider & {+ deployLive: NonNullable<IBacktestingProvider['deployLive']>;+ getLiveStatus: NonNullable<IBacktestingProvider['getLiveStatus']>;+ stopLive: NonNullable<IBacktestingProvider['stopLive']>;+} {+ return (+ provider.capabilities.liveTrading &&+ typeof provider.deployLive === 'function'+ );+}++/**+ * Type guard to check if research/notebooks is supported+ */+export function supportsResearch(+ provider: IBacktestingProvider+): provider is IBacktestingProvider & {+ createNotebook: NonNullable<IBacktestingProvider['createNotebook']>;+} {+ return (+ provider.capabilities.research &&+ typeof provider.createNotebook === 'function'+ );+}diff --git a/fincept-terminal-desktop/src/services/backtesting/interfaces/IStrategyDefinition.ts b/fincept-terminal-desktop/src/services/backtesting/interfaces/IStrategyDefinition.tsnew file mode 100644index 000000000..98077024b--- /dev/null+++ b/fincept-terminal-desktop/src/services/backtesting/interfaces/IStrategyDefinition.ts@@ -0,0 +1,223 @@+/**+ * Strategy Definition Interface+ * Platform-independent strategy representation that works across all providers+ */++import { Node, Edge } from 'reactflow';+import { StrategyParameter } from './types';++// ============================================================================+// Main Strategy Definition+// ============================================================================++export interface StrategyDefinition {+ // Metadata+ id?: string;+ name: string;+ version: string;+ description: string;+ author: string;+ createdAt?: string;+ updatedAt?: string;+ tags?: string[];++ // Strategy type determines how it's executed+ type: 'code' | 'visual' | 'template';++ // Code-based strategy (Python only)+ code?: CodeStrategy;++ // Visual strategy (from node editor)+ visual?: VisualStrategy;++ // Template strategy (pre-built)+ template?: TemplateStrategy;++ // Parameters that can be optimized+ parameters: StrategyParameter[];++ // Requirements+ requires: StrategyRequirements;++ // Provider-specific metadata (optional, stored but not used by other providers)+ providerMetadata?: Record<string, any>;+}++// ============================================================================+// Code Strategy+// ============================================================================++export interface CodeStrategy {+ language: 'python'; // Python only+ source: string; // Actual Python code+ entryPoint?: string; // Main class or function name+ dependencies?: string[]; // Required Python packages+ version?: string; // Python version requirement+}++// ============================================================================+// Visual Strategy+// ============================================================================++export interface VisualStrategy {+ nodes: Node[]; // ReactFlow nodes+ edges: Edge[]; // ReactFlow edges+ metadata: VisualStrategyMetadata;+ generatedPython?: string; // Auto-generated Python code from visual+ lastGenerated?: string; // Timestamp of last code generation+}++export interface VisualStrategyMetadata {+ canvasWidth?: number;+ canvasHeight?: number;+ zoom?: number;+ version: string;+ nodeTypes: string[];+}++// ============================================================================+// Template Strategy+// ============================================================================++export interface TemplateStrategy {+ templateId: string;+ templateName: string;+ parameters: Record<string, any>;+ customizations?: TemplateCustomization[];+}++export interface TemplateCustomization {+ section: string;+ field: string;+ value: any;+}++// ============================================================================+// Strategy Requirements+// ============================================================================++export interface StrategyRequirements {+ dataFeeds: DataFeed[];+ indicators: string[];+ minCapital?: number;+ assetClasses?: string[];+ assets?: Array<{ symbol: string; assetClass: string }>;+ timeframes?: string[];+ brokerages?: string[];+ startDate?: string;+ endDate?: string;+ capital?: number;+}++export interface DataFeed {+ type: 'price' | 'fundamental' | 'alternative' | 'news' | 'sentiment';+ resolution: 'tick' | 'second' | 'minute' | 'hour' | 'daily';+ provider?: string;+ required: boolean;+}++// ============================================================================+// Strategy Templates Catalog+// ============================================================================++export interface StrategyTemplate {+ id: string;+ name: string;+ category: StrategyCategory;+ description: string;+ difficulty: 'beginner' | 'intermediate' | 'advanced';+ parameters: StrategyParameter[];+ previewImage?: string;+ tags: string[];+ author: string;+ rating?: number;+ downloads?: number;+}++export type StrategyCategory =+ | 'momentum'+ | 'mean_reversion'+ | 'trend_following'+ | 'arbitrage'+ | 'market_making'+ | 'statistical_arbitrage'+ | 'machine_learning'+ | 'options'+ | 'portfolio_rebalancing'+ | 'risk_parity';++// ============================================================================+// Strategy Builder Helpers+// ============================================================================++export interface StrategyValidationResult {+ valid: boolean;+ errors: string[];+ warnings: string[];+}++export interface StrategyComponents {+ entryRules: Rule[];+ exitRules: Rule[];+ positionSizing: PositionSizingRule;+ riskManagement: RiskManagementRule[];+ filters?: Filter[];+}++export interface Rule {+ id: string;+ type: string;+ condition: Condition;+ action: Action;+ enabled: boolean;+}++export interface Condition {+ indicator?: string;+ operator: 'gt' | 'lt' | 'eq' | 'gte' | 'lte' | 'cross_above' | 'cross_below';+ value: number | string;+ lookback?: number;+}++export interface Action {+ type: 'buy' | 'sell' | 'close_long' | 'close_short' | 'hold';+ quantity?: number;+ price?: 'market' | 'limit' | 'stop';+ offset?: number;+}++export interface PositionSizingRule {+ method: 'fixed' | 'percentage' | 'volatility' | 'kelly' | 'risk_parity';+ value: number;+ maxPosition?: number;+}++export interface RiskManagementRule {+ type: 'stop_loss' | 'take_profit' | 'trailing_stop' | 'time_limit';+ value: number;+ unit: 'percentage' | 'points' | 'atr' | 'days';+}++export interface Filter {+ type: 'time' | 'volatility' | 'volume' | 'trend' | 'correlation';+ condition: Condition;+}++// ============================================================================+// Strategy Conversion+// ============================================================================++export interface ConversionResult {+ success: boolean;+ convertedStrategy: StrategyDefinition;+ warnings: string[];+ errors: string[];+ unsupportedFeatures?: string[];+}++// ============================================================================+// Helper Functions Types+// ============================================================================++export type StrategyType = StrategyDefinition['type'];+export type StrategyLanguage = CodeStrategy['language'];diff --git a/fincept-terminal-desktop/src/services/backtesting/interfaces/types.ts b/fincept-terminal-desktop/src/services/backtesting/interfaces/types.tsnew file mode 100644index 000000000..9b53f37c9--- /dev/null+++ b/fincept-terminal-desktop/src/services/backtesting/interfaces/types.ts@@ -0,0 +1,511 @@+/**+ * Shared types for backtesting system+ * Platform-independent types used across all providers+ */++import { Node, Edge } from 'reactflow';++// ============================================================================+// Provider Capabilities+// ============================================================================++export interface ProviderCapabilities {+ backtesting: boolean;+ optimization: boolean;+ liveTrading: boolean;+ research: boolean;+ multiAsset: AssetClass[];+ indicators: boolean;+ customStrategies: boolean;+ maxConcurrentBacktests: number;+ supportedTimeframes: Timeframe[];+ supportedMarkets?: string[];+}++export type AssetClass = 'stocks' | 'options' | 'futures' | 'crypto' | 'forex' | 'cfd' | 'bonds';+export type Timeframe = 'tick' | 'second' | 'minute' | 'hour' | 'daily' | 'weekly' | 'monthly';++// ============================================================================+// Provider Configuration+// ============================================================================++export interface ProviderConfig {+ name: string;+ adapterType: string;+ apiKey?: string;+ apiSecret?: string;+ endpoint?: string;+ mode?: 'cli' | 'api' | 'local';+ settings?: Record<string, any>;+ options?: Record<string, any>;+}++export interface ProviderInfo {+ name: string;+ version: string;+ capabilities: ProviderCapabilities;+ description: string;+ isActive: boolean;+ isEnabled: boolean;+ config?: ProviderConfig;+}++// ============================================================================+// Initialization & Connection+// ============================================================================++export interface InitResult {+ success: boolean;+ message: string;+ version?: string;+ error?: string;+}++export interface TestResult {+ success: boolean;+ message: string;+ latency?: number;+ metadata?: Record<string, any>;+ error?: string;+}++// ============================================================================+// Strategy Parameters+// ============================================================================++export interface StrategyParameter {+ name: string;+ type: 'int' | 'float' | 'bool' | 'string' | 'enum';+ defaultValue: any;+ min?: number;+ max?: number;+ step?: number;+ options?: string[];+ description: string;+ required?: boolean;+}++// ============================================================================+// Asset Selection+// ============================================================================++export interface AssetSelection {+ symbol: string;+ assetClass: AssetClass;+ exchange?: string;+ weight?: number;+}++// ============================================================================+// Slippage & Commission Models+// ============================================================================++export interface SlippageModel {+ type: 'fixed' | 'percentage' | 'volumeShare';+ value: number;+}++export interface CommissionModel {+ type: 'fixed' | 'percentage' | 'perShare' | 'tiered';+ value: number;+ minimum?: number;+ maximum?: number;+}++// ============================================================================+// Backtest Request & Configuration+// ============================================================================++export interface BacktestRequest {+ strategy: any; // Will be StrategyDefinition from IStrategyDefinition.ts+ startDate: string;+ endDate: string;+ initialCapital: number;+ assets: AssetSelection[];+ parameters?: Record<string, any>;+ benchmark?: string;+ slippageModel?: SlippageModel;+ commissionModel?: CommissionModel;+ timeframe?: Timeframe;+ warmupPeriod?: number;+}++export interface BacktestConfig {+ startDate: string;+ endDate: string;+ initialCapital: number;+ assets: AssetSelection[];+ benchmark?: string;+ slippageModel?: SlippageModel;+ commissionModel?: CommissionModel;+ timeframe?: Timeframe;+}++// ============================================================================+// Backtest Results+// ============================================================================++export interface BacktestResult {+ id: string;+ status: 'completed' | 'failed' | 'running' | 'cancelled';+ performance: PerformanceMetrics;+ trades: Trade[];+ equity: EquityPoint[];+ statistics: BacktestStatistics;+ charts?: ChartData[];+ logs: string[];+ error?: string;+ startTime?: string;+ endTime?: string;+ duration?: number;+}++export interface BacktestStatus {+ id: string;+ status: 'completed' | 'failed' | 'running' | 'cancelled';+ progress?: number;+ currentDate?: string;+ message?: string;+ error?: string;+}++// ============================================================================+// Performance Metrics+// ============================================================================++export interface PerformanceMetrics {+ totalReturn: number;+ annualizedReturn: number;+ sharpeRatio: number;+ sortinoRatio: number;+ maxDrawdown: number;+ maxDrawdownDuration?: number;+ winRate: number;+ lossRate: number;+ profitFactor: number;+ alpha?: number;+ beta?: number;+ volatility: number;+ calmarRatio: number;+ informationRatio?: number;+ treynorRatio?: number;+ totalTrades: number;+ winningTrades: number;+ losingTrades: number;+ averageWin: number;+ averageLoss: number;+ largestWin: number;+ largestLoss: number;+ averageTradeReturn: number;+ expectancy: number;+}++export interface BacktestStatistics {+ startDate: string;+ endDate: string;+ initialCapital: number;+ finalCapital: number;+ totalFees: number;+ totalSlippage: number;+ totalTrades: number;+ winningDays: number;+ losingDays: number;+ averageDailyReturn: number;+ bestDay: number;+ worstDay: number;+ consecutiveWins: number;+ consecutiveLosses: number;+ maxDrawdownDate?: string;+ recoveryTime?: number;+}++// ============================================================================+// Trades+// ============================================================================++export interface Trade {+ id: string;+ symbol: string;+ entryDate: string;+ exitDate?: string;+ side: 'long' | 'short';+ quantity: number;+ entryPrice: number;+ exitPrice?: number;+ commission: number;+ slippage: number;+ pnl?: number;+ pnlPercent?: number;+ holdingPeriod?: number;+ exitReason?: 'signal' | 'stop_loss' | 'take_profit' | 'time_limit';+}++// ============================================================================+// Equity Curve+// ============================================================================++export interface EquityPoint {+ date: string;+ equity: number;+ returns: number;+ drawdown: number;+ benchmark?: number;+}++// ============================================================================+// Chart Data+// ============================================================================++export interface ChartData {+ type: 'equity' | 'drawdown' | 'returns' | 'exposure' | 'trades';+ title: string;+ data: any[];+ config?: Record<string, any>;+}++// ============================================================================+// Optimization+// ============================================================================++export interface OptimizationRequest {+ strategy: any; // StrategyDefinition+ parameterGrid: ParameterGrid[];+ optimizationTarget?: OptimizationObjective;+ constraints?: Record<string, any>;+ parameterRanges?: Record<string, ParameterGrid>;+ objective: OptimizationObjective;+ config: BacktestConfig;+ startDate?: string;+ endDate?: string;+ initialCapital?: number;+ assets?: AssetSelection[];+ parameters?: Record<string, any>;+ maxIterations?: number;+ algorithm?: 'grid' | 'random' | 'genetic' | 'bayesian';+}++export interface ParameterGrid {+ name: string;+ min: number;+ max: number;+ step: number;+ values?: any[];+}++export type OptimizationObjective =+ | 'sharpe_ratio'+ | 'total_return'+ | 'profit_factor'+ | 'max_drawdown'+ | 'calmar_ratio'+ | 'sortino_ratio';++export interface OptimizationResult {+ id: string;+ status: 'completed' | 'failed' | 'running';+ bestParameters: Record<string, any>;+ bestResult: BacktestResult;+ allResults: OptimizationIteration[];+ iterations: number;+ duration: number;+ error?: string;+}++export interface OptimizationIteration {+ iteration: number;+ parameters: Record<string, any>;+ performance: PerformanceMetrics;+ objectiveValue: number;+}++// ============================================================================+// Historical Data+// ============================================================================++export interface DataRequest {+ symbols: string[];+ startDate: string;+ endDate: string;+ timeframe: Timeframe;+ fields?: string[];+}++export interface HistoricalData {+ symbol: string;+ timeframe: Timeframe;+ data: PriceBar[];+}++export interface PriceBar {+ date: string;+ open: number;+ high: number;+ low: number;+ close: number;+ volume: number;+ adjustedClose?: number;+}++// ============================================================================+// Data Catalog+// ============================================================================++export interface DataCatalog {+ providers?: string[];+ markets?: Array<{+ id: string;+ name: string;+ assetClasses: string[];+ }>;+ assetClasses?: AssetClass[];+ timeframes: Timeframe[];+ dateRange?: {+ start: string;+ end: string;+ };+ startDate?: string;+ endDate?: string;+ totalSymbols?: number;+ dataSize?: string;+ description?: string;+}++// ============================================================================+// Indicators+// ============================================================================++export type IndicatorType =+ | 'sma' | 'ema' | 'rsi' | 'macd' | 'bollinger_bands'+ | 'atr' | 'adx' | 'stochastic' | 'cci' | 'roc'+ | 'williams_r' | 'momentum' | 'volume';++export interface IndicatorParams {+ period?: number;+ fastPeriod?: number;+ slowPeriod?: number;+ signalPeriod?: number;+ stdDev?: number;+ [key: string]: any;+}++export interface IndicatorResult {+ indicator: IndicatorType;+ symbol: string;+ values: IndicatorValue[];+}++export interface IndicatorValue {+ date: string;+ value: number | number[];+ signal?: number;+}++export interface IndicatorCatalog {+ categories?: Array<{+ name: string;+ indicators: Array<{+ id: string;+ name: string;+ params: string[];+ description?: string;+ }>;+ }>;+ indicators?: {+ type: IndicatorType;+ name: string;+ description: string;+ parameters: StrategyParameter[];+ }[];+ total?: number;+ description?: string;+}++// ============================================================================+// Live Trading+// ============================================================================++export interface LiveDeployRequest {+ strategy: any; // StrategyDefinition+ brokerage: string;+ initialCapital: number;+ assets: AssetSelection[];+ parameters?: Record<string, any>;+ riskLimits?: RiskLimits;+}++export interface RiskLimits {+ maxPositionSize?: number;+ maxDrawdown?: number;+ dailyLossLimit?: number;+ maxLeverage?: number;+}++export interface LiveDeployResult {+ id: string;+ status: 'deployed' | 'failed';+ deploymentTime: string;+ message: string;+ error?: string;+}++export interface LiveStatus {+ id: string;+ status: 'running' | 'stopped' | 'paused' | 'error';+ equity: number;+ pnl: number;+ openPositions: Position[];+ todayTrades: number;+ lastUpdate: string;+ error?: string;+}++export interface Position {+ symbol: string;+ quantity: number;+ side: 'long' | 'short';+ entryPrice: number;+ currentPrice: number;+ unrealizedPnl: number;+ unrealizedPnlPercent: number;+}++// ============================================================================+// Research/Notebooks+// ============================================================================++export interface NotebookResult {+ id: string;+ name: string;+ url?: string;+ status: 'created' | 'failed';+ error?: string;+}++// ============================================================================+// Utility Types+// ============================================================================++export interface ExecutionResult {+ nodeId: string;+ success: boolean;+ data?: any;+ error?: string;+}++/**+ * Strategy Validation Result+ */+export interface ValidationResult {+ valid: boolean;+ errors: string[];+ warnings?: string[];+}++/**+ * Provider Health Status+ */+export interface HealthStatus {+ status: 'healthy' | 'degraded' | 'unhealthy';+ message?: string;+ lastCheck?: string;+}diff --git a/fincept-terminal-desktop/src/services/hyperliquid/hyperliquidApi.ts b/fincept-terminal-desktop/src/services/hyperliquid/hyperliquidApi.tsnew file mode 100644index 000000000..3fc21b6ea--- /dev/null+++ b/fincept-terminal-desktop/src/services/hyperliquid/hyperliquidApi.ts@@ -0,0 +1,309 @@+// File: src/services/hyperliquid/hyperliquidApi.ts+// HyperLiquid REST API service+// Documentation: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint++import type {+ HyperLiquidCandle,+ HyperLiquidCandleInterval,+ HyperLiquidAssetInfo,+ HyperLiquidL2BookData,+ HyperLiquidClearinghouseState+} from '../../types/hyperliquid';++/**+ * HyperLiquid REST API Client+ * Provides methods for fetching historical data and account information+ */+export class HyperLiquidApi {+ private readonly baseUrl: string;+ private readonly testnet: boolean;++ constructor(testnet: boolean = false) {+ this.testnet = testnet;+ this.baseUrl = testnet+ ? 'https://api.hyperliquid-testnet.xyz'+ : 'https://api.hyperliquid.xyz';+ }++ /**+ * Make POST request to /info endpoint+ */+ private async request<T>(body: any): Promise<T> {+ const response = await fetch(`${this.baseUrl}/info`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json'+ },+ body: JSON.stringify(body)+ });++ if (!response.ok) {+ throw new Error(`HyperLiquid API error: ${response.status} ${response.statusText}`);+ }++ return response.json();+ }++ /**+ * Get candlestick/OHLC data+ * @param coin - Symbol (e.g., 'BTC', 'ETH')+ * @param interval - Candle interval (1m, 5m, 15m, 30m, 1h, 4h, 1d, etc.)+ * @param startTime - Start timestamp in milliseconds+ * @param endTime - End timestamp in milliseconds (optional, defaults to now)+ * @returns Array of candles (max 5000)+ */+ async getCandles(+ coin: string,+ interval: HyperLiquidCandleInterval,+ startTime: number,+ endTime?: number+ ): Promise<HyperLiquidCandle[]> {+ const body = {+ type: 'candleSnapshot',+ req: {+ coin,+ interval,+ startTime,+ ...(endTime && { endTime })+ }+ };++ const response = await this.request<HyperLiquidCandle[]>(body);+ return response;+ }++ /**+ * Get mid-prices for all coins+ * @returns Record of coin -> mid price+ */+ async getAllMids(): Promise<Record<string, string>> {+ const body = {+ type: 'allMids'+ };++ const response = await this.request<Record<string, string>>(body);+ return response;+ }++ /**+ * Get L2 order book snapshot+ * @param coin - Symbol (e.g., 'BTC', 'ETH')+ * @param nSigFigs - Number of significant figures (2-5, default: 5)+ * @param mantissa - Mantissa value (1, 2, or 5, only with nSigFigs=5)+ * @returns Order book with bids and asks+ */+ async getL2Book(+ coin: string,+ nSigFigs: number = 5,+ mantissa?: 1 | 2 | 5+ ): Promise<HyperLiquidL2BookData> {+ const body: any = {+ type: 'l2Book',+ coin,+ nSigFigs+ };++ if (mantissa && nSigFigs === 5) {+ body.mantissa = mantissa;+ }++ const response = await this.request<HyperLiquidL2BookData>(body);+ return response;+ }++ /**+ * Get user's clearinghouse state (positions, balances, etc.)+ * @param userAddress - User's wallet address+ * @returns User state including positions and account value+ */+ async getUserState(userAddress: string): Promise<HyperLiquidClearinghouseState> {+ const body = {+ type: 'clearinghouseState',+ user: userAddress+ };++ const response = await this.request<HyperLiquidClearinghouseState>(body);+ return response;+ }++ /**+ * Get user's open orders+ * @param userAddress - User's wallet address+ * @returns Array of open orders+ */+ async getOpenOrders(userAddress: string): Promise<any[]> {+ const body = {+ type: 'openOrders',+ user: userAddress+ };++ const response = await this.request<any[]>(body);+ return response;+ }++ /**+ * Get user's fill history+ * @param userAddress - User's wallet address+ * @param aggregateByTime - Whether to aggregate fills by time (default: false)+ * @returns Array of fills (max 2000 most recent)+ */+ async getUserFills(userAddress: string, aggregateByTime: boolean = false): Promise<any[]> {+ const body = {+ type: 'userFills',+ user: userAddress,+ aggregateByTime+ };++ const response = await this.request<any[]>(body);+ return response;+ }++ /**+ * Get user's fills by time range+ * @param userAddress - User's wallet address+ * @param startTime - Start timestamp in milliseconds+ * @param endTime - End timestamp in milliseconds (optional, defaults to now)+ * @returns Array of fills (max 2000)+ */+ async getUserFillsByTime(+ userAddress: string,+ startTime: number,+ endTime?: number+ ): Promise<any[]> {+ const body = {+ type: 'userFillsByTime',+ user: userAddress,+ startTime,+ ...(endTime && { endTime })+ };++ const response = await this.request<any[]>(body);+ return response;+ }++ /**+ * Get metadata about available assets+ * @returns Universe of tradeable assets with their properties+ */+ async getMeta(): Promise<{ universe: HyperLiquidAssetInfo[] }> {+ const body = {+ type: 'meta'+ };++ const response = await this.request<{ universe: HyperLiquidAssetInfo[] }>(body);+ return response;+ }++ /**+ * Get funding rate history for a coin+ * @param coin - Symbol (e.g., 'BTC', 'ETH')+ * @param startTime - Start timestamp in milliseconds+ * @param endTime - End timestamp in milliseconds (optional)+ * @returns Array of funding rate data+ */+ async getFundingHistory(+ coin: string,+ startTime: number,+ endTime?: number+ ): Promise<any[]> {+ const body = {+ type: 'fundingHistory',+ coin,+ startTime,+ ...(endTime && { endTime })+ };++ const response = await this.request<any[]>(body);+ return response;+ }++ /**+ * Convenience method: Get latest price for a coin+ * @param coin - Symbol (e.g., 'BTC', 'ETH')+ * @returns Current mid-price as number+ */+ async getCurrentPrice(coin: string): Promise<number> {+ const allMids = await this.getAllMids();+ const price = allMids[coin];++ if (!price) {+ throw new Error(`No price found for ${coin}`);+ }++ return parseFloat(price);+ }++ /**+ * Convenience method: Get recent candles (last N periods)+ * @param coin - Symbol (e.g., 'BTC', 'ETH')+ * @param interval - Candle interval+ * @param count - Number of candles to fetch (max 5000)+ * @returns Array of recent candles+ */+ async getRecentCandles(+ coin: string,+ interval: HyperLiquidCandleInterval,+ count: number = 100+ ): Promise<HyperLiquidCandle[]> {+ // Calculate time range based on interval+ const intervalMs = this.intervalToMs(interval);+ const endTime = Date.now();+ const startTime = endTime - (intervalMs * count);++ return this.getCandles(coin, interval, startTime, endTime);+ }++ /**+ * Convert interval string to milliseconds+ */+ private intervalToMs(interval: HyperLiquidCandleInterval): number {+ const map: Record<string, number> = {+ '1m': 60 * 1000,+ '3m': 3 * 60 * 1000,+ '5m': 5 * 60 * 1000,+ '15m': 15 * 60 * 1000,+ '30m': 30 * 60 * 1000,+ '1h': 60 * 60 * 1000,+ '2h': 2 * 60 * 60 * 1000,+ '4h': 4 * 60 * 60 * 1000,+ '8h': 8 * 60 * 60 * 1000,+ '12h': 12 * 60 * 60 * 1000,+ '1d': 24 * 60 * 60 * 1000,+ '3d': 3 * 24 * 60 * 60 * 1000,+ '1w': 7 * 24 * 60 * 60 * 1000,+ '1M': 30 * 24 * 60 * 60 * 1000+ };++ return map[interval] || 60 * 1000;+ }+}++/**+ * Create API instance+ * @param testnet - Whether to use testnet (default: false)+ */+export function createHyperLiquidApi(testnet: boolean = false): HyperLiquidApi {+ return new HyperLiquidApi(testnet);+}++/**+ * Usage Examples:+ *+ * // Create API instance+ * const api = createHyperLiquidApi();+ *+ * // Get candles+ * const candles = await api.getCandles('BTC', '1h', startTime, endTime);+ *+ * // Get current price+ * const price = await api.getCurrentPrice('BTC');+ *+ * // Get order book+ * const book = await api.getL2Book('ETH', 5);+ *+ * // Get user state+ * const state = await api.getUserState('0x...');+ *+ * // Get metadata+ * const meta = await api.getMeta();+ */diff --git a/fincept-terminal-desktop/src/services/hyperliquid/index.ts b/fincept-terminal-desktop/src/services/hyperliquid/index.tsnew file mode 100644index 000000000..8e248e064--- /dev/null+++ b/fincept-terminal-desktop/src/services/hyperliquid/index.ts@@ -0,0 +1,5 @@+// File: src/services/hyperliquid/index.ts+// HyperLiquid services exports++export { HyperLiquidApi, createHyperLiquidApi } from './hyperliquidApi';+export type * from '../../types/hyperliquid';diff --git a/fincept-terminal-desktop/src/services/llmApi.ts b/fincept-terminal-desktop/src/services/llmApi.tsindex f2d237cbf..89a8df710 100644--- a/fincept-terminal-desktop/src/services/llmApi.ts+++ b/fincept-terminal-desktop/src/services/llmApi.ts@@ -134,7 +134,12 @@ class LLMApiService {// Convert messages to Gemini formatconst systemPrompt = messages.find(m => m.role === 'system')?.content || '';- const conversationMessages = messages.filter(m => m.role !== 'system');+ // Filter out system messages AND any placeholder/empty responses+ const conversationMessages = messages.filter(m =>+ m.role !== 'system' &&+ m.content.trim() !== '' &&+ m.content !== '(No response generated)'+ );// Gemini requires alternating roles - merge consecutive messages from same roleconst contents: any[] = [];@@ -173,7 +178,11 @@ class LLMApiService {}};- console.log('[Gemini] Request body:', JSON.stringify(requestBody, null, 2));+ console.log('[Gemini] 📨 Request details:');+ console.log('[Gemini] - Contents count:', contents.length);+ console.log('[Gemini] - System instruction length:', systemPrompt?.length || 0, 'characters');+ console.log('[Gemini] - First content role:', contents[0]?.role);+ console.log('[Gemini] - First content preview:', JSON.stringify(contents[0]).substring(0, 200));try {const response = await fetch(url, {@@ -201,7 +210,6 @@ class LLMApiService {return await this.handleGeminiStream(response, onStream);} else {const data = await response.json();- console.log('[Gemini] Response data:', JSON.stringify(data, null, 2));// Extract text content safelyconst candidate = data.candidates?.[0];@@ -241,31 +249,47 @@ class LLMApiService {const reader = response.body?.getReader();const decoder = new TextDecoder();let fullContent = '';+ let accumulatedJson = '';if (!reader) {throw new Error('No response body');}try {+ // Accumulate all chunks into complete JSON stringwhile (true) {const { done, value } = await reader.read();if (done) break;const chunk = decoder.decode(value);- const lines = chunk.split('\n').filter(line => line.trim());+ accumulatedJson += chunk;+ }- for (const line of lines) {- try {- const parsed = JSON.parse(line);- const content = parsed.candidates?.[0]?.content?.parts?.[0]?.text || '';+ // Parse the complete JSON response (Gemini returns an array)+ try {+ const parsed = JSON.parse(accumulatedJson);++ // Gemini returns an array of response objects+ if (Array.isArray(parsed)) {+ for (const item of parsed) {+ const content = item.candidates?.[0]?.content?.parts?.[0]?.text || '';if (content) {fullContent += content;onStream(content, false);}- } catch (e) {- // Skip invalid JSON+ }+ } else {+ // Single object response+ const content = parsed.candidates?.[0]?.content?.parts?.[0]?.text || '';+ if (content) {+ fullContent = content;+ onStream(content, false);}}+ } catch (e) {+ console.error('[Gemini Stream] Failed to parse JSON:', e);+ console.error('[Gemini Stream] Accumulated JSON:', accumulatedJson);+ throw new Error('Failed to parse Gemini response');}onStream('', true);diff --git a/fincept-terminal-desktop/src/services/reportService.ts b/fincept-terminal-desktop/src/services/reportService.tsindex bba133d59..9e4786849 100644--- a/fincept-terminal-desktop/src/services/reportService.ts+++ b/fincept-terminal-desktop/src/services/reportService.ts@@ -1,8 +1,10 @@import { invoke } from '@tauri-apps/api/core';+import { open as shellOpen } from '@tauri-apps/plugin-shell';+import { sqliteService } from './sqliteService';export interface ReportComponent {id: string;- type: 'text' | 'heading' | 'chart' | 'table' | 'image' | 'divider' | 'code';+ type: 'text' | 'heading' | 'subheading' | 'chart' | 'table' | 'image' | 'divider' | 'code' | 'section' | 'columns' | 'coverpage' | 'pagebreak';content: any;config: {fontSize?: string;@@ -14,7 +16,20 @@ export interface ReportComponent {imageUrl?: string;code?: string;language?: string;+ // Layout configs+ columnCount?: 2 | 3;+ backgroundColor?: string;+ borderColor?: string;+ padding?: string;+ // Section configs+ sectionTitle?: string;+ sectionStyle?: 'default' | 'highlight' | 'sidebar';+ // Cover page configs+ subtitle?: string;+ logo?: string;};+ // For column and section types that contain other components+ children?: ReportComponent[];}export interface ReportTemplate {@@ -34,6 +49,8 @@ export interface ReportTemplate {margins?: string;headerFooter?: boolean;};+ created_at?: string;+ updated_at?: string;}export interface ReportGenerationResult {@@ -106,42 +123,119 @@ class ReportService {}/**- * Save template to local storage+ * Open folder in file explorer (cross-platform)*/- saveTemplate(template: ReportTemplate): void {- const templates = this.getTemplates();- const existingIndex = templates.findIndex(t => t.id === template.id);-- if (existingIndex >= 0) {- templates[existingIndex] = template;- } else {- templates.push(template);+ async openInFolder(filePath: string): Promise<boolean> {+ try {+ console.log('[ReportService] Opening folder for:', filePath);++ // Extract directory from file path+ const pathParts = filePath.replace(/\\/g, '/').split('/');+ pathParts.pop(); // Remove filename+ const folderPath = pathParts.join('/');++ // Detect platform+ const platform = await this.getPlatform();+ console.log('[ReportService] Platform:', platform);++ if (platform === 'windows') {+ // Windows: Use explorer with /select flag to highlight the file+ // Need to use native Windows path separators+ const windowsPath = filePath.replace(/\//g, '\\');+ await shellOpen(`explorer /select,"${windowsPath}"`);+ } else if (platform === 'darwin') {+ // macOS: Use open with -R flag to reveal in Finder+ await shellOpen(`open -R "${filePath}"`);+ } else {+ // Linux: Open the folder+ await shellOpen(`xdg-open "${folderPath}"`);+ }++ return true;+ } catch (error) {+ console.error('Failed to open folder:', error);+ return false;}+ }- localStorage.setItem('financial_report_templates', JSON.stringify(templates));+ /**+ * Get current platform+ */+ private async getPlatform(): Promise<string> {+ try {+ const platform = await invoke<string>('plugin:os|platform');+ return platform;+ } catch {+ // Fallback to navigator+ const userAgent = navigator.userAgent.toLowerCase();+ if (userAgent.includes('win')) return 'windows';+ if (userAgent.includes('mac')) return 'darwin';+ return 'linux';+ }}/**- * Get all saved templates+ * Save template to SQLite database*/- getTemplates(): ReportTemplate[] {+ async saveTemplate(template: ReportTemplate): Promise<void> {+ await sqliteService.initialize();+ const now = new Date().toISOString();++ const templateData = {+ ...template,+ updated_at: now,+ created_at: template.created_at || now+ };++ const templateJson = JSON.stringify({+ components: templateData.components,+ metadata: templateData.metadata,+ styles: templateData.styles+ });++ // For now, use localStorage until SQLite service is fully integrated+ try {+ const templates = this.getTemplatesFromLocalStorage();+ const existingIndex = templates.findIndex(t => t.id === template.id);++ if (existingIndex >= 0) {+ templates[existingIndex] = templateData;+ } else {+ templates.push(templateData);+ }++ localStorage.setItem('financial_report_templates', JSON.stringify(templates));+ } catch (error) {+ console.error('Failed to save template:', error);+ throw error;+ }+ }++ private getTemplatesFromLocalStorage(): ReportTemplate[] {const stored = localStorage.getItem('financial_report_templates');return stored ? JSON.parse(stored) : [];}+ /**+ * Get all saved templates+ */+ async getTemplates(): Promise<ReportTemplate[]> {+ return this.getTemplatesFromLocalStorage();+ }+/*** Get template by ID*/- getTemplate(id: string): ReportTemplate | null {- const templates = this.getTemplates();+ async getTemplate(id: string): Promise<ReportTemplate | null> {+ const templates = this.getTemplatesFromLocalStorage();return templates.find(t => t.id === id) || null;}/*** Delete template*/- deleteTemplate(id: string): void {- const templates = this.getTemplates();+ async deleteTemplate(id: string): Promise<void> {+ const templates = this.getTemplatesFromLocalStorage();const filtered = templates.filter(t => t.id !== id);localStorage.setItem('financial_report_templates', JSON.stringify(filtered));}@@ -170,6 +264,136 @@ class ReportService {};}+ /**+ * Get professional equity research report template+ */+ getEquityResearchTemplate(): ReportTemplate {+ return {+ id: 'equity-research-template',+ name: 'Equity Research Report',+ description: 'Professional equity research report with multi-column layout',+ components: [+ {+ id: 'cover-page',+ type: 'coverpage',+ content: null,+ config: {+ subtitle: 'Equity Research | Technology Sector',+ backgroundColor: '#0a0a0a',+ color: '#FFA500'+ }+ },+ {+ id: 'page-break-1',+ type: 'pagebreak',+ content: null,+ config: {}+ },+ {+ id: 'exec-summary-section',+ type: 'section',+ content: null,+ config: {+ sectionTitle: 'EXECUTIVE SUMMARY',+ sectionStyle: 'highlight',+ backgroundColor: '#f8f9fa',+ borderColor: '#FFA500',+ padding: '20px'+ },+ children: [+ {+ id: 'exec-summary-content',+ type: 'text',+ content: 'We initiate coverage on XYZ Corporation with a BUY rating and 12-month price target of $185. The company demonstrates strong fundamentals with market-leading positions in cloud infrastructure and AI services. Key investment highlights include accelerating revenue growth, margin expansion, and strategic acquisitions.',+ config: { fontSize: 'medium', alignment: 'left' }+ }+ ]+ },+ {+ id: 'investment-highlights',+ type: 'columns',+ content: null,+ config: {+ columnCount: 2,+ padding: '15px'+ },+ children: [+ {+ id: 'col1-heading',+ type: 'subheading',+ content: 'Bull Case',+ config: { fontSize: 'medium', color: '#10b981', fontWeight: 'bold' }+ },+ {+ id: 'col1-text',+ type: 'text',+ content: '• Market share gains in cloud computing\n• Strong pricing power and gross margin expansion\n• Robust free cash flow generation\n• Strategic AI partnerships',+ config: { fontSize: 'small' }+ },+ {+ id: 'col2-heading',+ type: 'subheading',+ content: 'Bear Case',+ config: { fontSize: 'medium', color: '#ef4444', fontWeight: 'bold' }+ },+ {+ id: 'col2-text',+ type: 'text',+ content: '• Regulatory scrutiny in key markets\n• Intensifying competition\n• Currency headwinds\n• Execution risks on large projects',+ config: { fontSize: 'small' }+ }+ ]+ },+ {+ id: 'financial-metrics',+ type: 'heading',+ content: 'Key Financial Metrics',+ config: { fontSize: 'xl', alignment: 'left' }+ },+ {+ id: 'metrics-3col',+ type: 'columns',+ content: null,+ config: {+ columnCount: 3+ },+ children: [+ {+ id: 'metric1',+ type: 'text',+ content: 'Revenue Growth\n+23.5% YoY',+ config: { alignment: 'center', fontWeight: 'bold', fontSize: 'medium' }+ },+ {+ id: 'metric2',+ type: 'text',+ content: 'Operating Margin\n32.1%',+ config: { alignment: 'center', fontWeight: 'bold', fontSize: 'medium' }+ },+ {+ id: 'metric3',+ type: 'text',+ content: 'FCF Yield\n4.8%',+ config: { alignment: 'center', fontWeight: 'bold', fontSize: 'medium' }+ }+ ]+ }+ ],+ metadata: {+ author: 'Fincept Research',+ company: 'Fincept Corporation',+ date: new Date().toISOString().split('T')[0],+ title: 'XYZ Corp - Initiate with BUY',+ },+ styles: {+ pageSize: 'A4',+ orientation: 'portrait',+ margins: '15mm',+ headerFooter: true,+ },+ };+ }+/*** Get sample financial report template*/diff --git a/fincept-terminal-desktop/src/services/sqliteService.ts b/fincept-terminal-desktop/src/services/sqliteService.tsindex 661b976ae..e86b45dae 100644--- a/fincept-terminal-desktop/src/services/sqliteService.ts+++ b/fincept-terminal-desktop/src/services/sqliteService.ts@@ -132,6 +132,62 @@ export interface ChatContextLink {is_active: boolean;}+export interface BacktestingProvider {+ id: string;+ name: string;+ adapter_type: string;+ config: string;+ enabled: boolean;+ is_active: boolean;+ created_at: string;+ updated_at: string;+}++export interface BacktestingStrategy {+ id: string;+ name: string;+ description?: string;+ version: string;+ author?: string;+ provider_type: string;+ strategy_type: 'code' | 'visual' | 'template';+ strategy_definition: string;+ tags?: string;+ created_at: string;+ updated_at: string;+}++export interface BacktestRun {+ id: string;+ strategy_id?: string;+ provider_name: string;+ config: string;+ results?: string;+ status: 'completed' | 'failed' | 'running' | 'cancelled';+ performance_metrics?: string;+ error_message?: string;+ created_at: string;+ completed_at?: string;+ duration_seconds?: number;+}++export interface OptimizationRun {+ id: string;+ strategy_id?: string;+ provider_name: string;+ parameter_grid: string;+ objective: string;+ best_parameters?: string;+ best_result?: string;+ all_results?: string;+ iterations?: number;+ status: 'completed' | 'failed' | 'running' | 'cancelled';+ error_message?: string;+ created_at: string;+ completed_at?: string;+ duration_seconds?: number;+}+class SQLiteService {private db: Database | null = null;private initPromise: Promise<void> | null = null;@@ -260,6 +316,74 @@ class SQLiteService {updated_at TEXT DEFAULT CURRENT_TIMESTAMP)`,+ // Paper trading portfolios table+ `CREATE TABLE IF NOT EXISTS paper_trading_portfolios (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ provider TEXT NOT NULL,+ initial_balance REAL NOT NULL DEFAULT 100000,+ current_balance REAL NOT NULL,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ )`,++ // Paper trading positions table+ `CREATE TABLE IF NOT EXISTS paper_trading_positions (+ id TEXT PRIMARY KEY,+ portfolio_id TEXT NOT NULL,+ symbol TEXT NOT NULL,+ side TEXT NOT NULL CHECK (side IN ('long', 'short')),+ entry_price REAL NOT NULL,+ quantity REAL NOT NULL,+ current_price REAL,+ unrealized_pnl REAL,+ realized_pnl REAL DEFAULT 0,+ opened_at TEXT DEFAULT CURRENT_TIMESTAMP,+ closed_at TEXT,+ status TEXT NOT NULL CHECK (status IN ('open', 'closed')),+ FOREIGN KEY (portfolio_id) REFERENCES paper_trading_portfolios(id) ON DELETE CASCADE+ )`,++ // Paper trading orders table+ `CREATE TABLE IF NOT EXISTS paper_trading_orders (+ id TEXT PRIMARY KEY,+ portfolio_id TEXT NOT NULL,+ symbol TEXT NOT NULL,+ side TEXT NOT NULL CHECK (side IN ('buy', 'sell')),+ type TEXT NOT NULL CHECK (type IN ('market', 'limit', 'stop_market', 'stop_limit')),+ quantity REAL NOT NULL,+ price REAL,+ stop_price REAL,+ filled_quantity REAL DEFAULT 0,+ avg_fill_price REAL,+ status TEXT NOT NULL CHECK (status IN ('pending', 'filled', 'partial', 'cancelled', 'rejected', 'triggered')),+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ filled_at TEXT,+ FOREIGN KEY (portfolio_id) REFERENCES paper_trading_portfolios(id) ON DELETE CASCADE+ )`,++ // Paper trading trades table+ `CREATE TABLE IF NOT EXISTS paper_trading_trades (+ id TEXT PRIMARY KEY,+ portfolio_id TEXT NOT NULL,+ order_id TEXT NOT NULL,+ symbol TEXT NOT NULL,+ side TEXT NOT NULL,+ price REAL NOT NULL,+ quantity REAL NOT NULL,+ fee REAL DEFAULT 0,+ timestamp TEXT DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY (portfolio_id) REFERENCES paper_trading_portfolios(id) ON DELETE CASCADE,+ FOREIGN KEY (order_id) REFERENCES paper_trading_orders(id) ON DELETE CASCADE+ )`,++ // Indexes for paper trading tables+ `CREATE INDEX IF NOT EXISTS idx_paper_positions_portfolio ON paper_trading_positions(portfolio_id)`,+ `CREATE INDEX IF NOT EXISTS idx_paper_positions_status ON paper_trading_positions(status)`,+ `CREATE INDEX IF NOT EXISTS idx_paper_orders_portfolio ON paper_trading_orders(portfolio_id)`,+ `CREATE INDEX IF NOT EXISTS idx_paper_orders_status ON paper_trading_orders(status)`,+ `CREATE INDEX IF NOT EXISTS idx_paper_trades_portfolio ON paper_trading_trades(portfolio_id)`,+// MCP servers table`CREATE TABLE IF NOT EXISTS mcp_servers (id TEXT PRIMARY KEY,@@ -389,6 +513,89 @@ class SQLiteService {FOREIGN KEY(context_id) REFERENCES recorded_contexts(id) ON DELETE CASCADE)`,+ `CREATE TABLE IF NOT EXISTS report_templates (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT,+ template_data TEXT NOT NULL,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ )`,++ // Backtesting providers table+ `CREATE TABLE IF NOT EXISTS backtesting_providers (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL UNIQUE,+ adapter_type TEXT NOT NULL,+ config TEXT NOT NULL,+ enabled INTEGER DEFAULT 1,+ is_active INTEGER DEFAULT 0,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ )`,++ // Backtesting strategies table+ `CREATE TABLE IF NOT EXISTS backtesting_strategies (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ description TEXT,+ version TEXT DEFAULT '1.0.0',+ author TEXT,+ provider_type TEXT NOT NULL,+ strategy_type TEXT NOT NULL CHECK (strategy_type IN ('code', 'visual', 'template')),+ strategy_definition TEXT NOT NULL,+ tags TEXT,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ )`,++ `CREATE INDEX IF NOT EXISTS idx_strategies_provider ON backtesting_strategies(provider_type)`,+ `CREATE INDEX IF NOT EXISTS idx_strategies_type ON backtesting_strategies(strategy_type)`,++ // Backtest runs table+ `CREATE TABLE IF NOT EXISTS backtest_runs (+ id TEXT PRIMARY KEY,+ strategy_id TEXT,+ provider_name TEXT NOT NULL,+ config TEXT NOT NULL,+ results TEXT,+ status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'running', 'cancelled')),+ performance_metrics TEXT,+ error_message TEXT,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ completed_at TEXT,+ duration_seconds INTEGER,+ FOREIGN KEY(strategy_id) REFERENCES backtesting_strategies(id) ON DELETE SET NULL+ )`,++ `CREATE INDEX IF NOT EXISTS idx_backtest_runs_strategy ON backtest_runs(strategy_id)`,+ `CREATE INDEX IF NOT EXISTS idx_backtest_runs_provider ON backtest_runs(provider_name)`,+ `CREATE INDEX IF NOT EXISTS idx_backtest_runs_status ON backtest_runs(status)`,+ `CREATE INDEX IF NOT EXISTS idx_backtest_runs_created ON backtest_runs(created_at DESC)`,++ // Optimization runs table+ `CREATE TABLE IF NOT EXISTS optimization_runs (+ id TEXT PRIMARY KEY,+ strategy_id TEXT,+ provider_name TEXT NOT NULL,+ parameter_grid TEXT NOT NULL,+ objective TEXT NOT NULL,+ best_parameters TEXT,+ best_result TEXT,+ all_results TEXT,+ iterations INTEGER,+ status TEXT NOT NULL CHECK (status IN ('completed', 'failed', 'running', 'cancelled')),+ error_message TEXT,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ completed_at TEXT,+ duration_seconds INTEGER,+ FOREIGN KEY(strategy_id) REFERENCES backtesting_strategies(id) ON DELETE SET NULL+ )`,++ `CREATE INDEX IF NOT EXISTS idx_optimization_runs_strategy ON optimization_runs(strategy_id)`,+ `CREATE INDEX IF NOT EXISTS idx_optimization_runs_provider ON optimization_runs(provider_name)`,+ `CREATE INDEX IF NOT EXISTS idx_optimization_runs_status ON optimization_runs(status)`,+// Insert default LLM global settings`INSERT OR IGNORE INTO llm_global_settings (id, temperature, max_tokens, system_prompt)VALUES (1, 0.7, 2000, 'You are a helpful AI assistant specialized in financial analysis and market data.')`,@@ -1709,6 +1916,396 @@ class SQLiteService {);}+ // =========================+ // BACKTESTING METHODS+ // =========================++ async saveBacktestingProvider(provider: Omit<BacktestingProvider, 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string }> {+ try {+ await this.ensureInitialized();++ await this.db!.execute(+ `INSERT OR REPLACE INTO backtesting_providers (id, name, adapter_type, config, enabled, is_active, updated_at)+ VALUES ($1, $2, $3, $4, $5, $6, CURRENT_TIMESTAMP)`,+ [provider.id, provider.name, provider.adapter_type, provider.config, provider.enabled ? 1 : 0, provider.is_active ? 1 : 0]+ );++ return { success: true, message: 'Backtesting provider saved successfully' };+ } catch (error) {+ console.error('[SQLite] Failed to save backtesting provider:', error);+ return { success: false, message: 'Failed to save backtesting provider' };+ }+ }++ async getBacktestingProviders(): Promise<BacktestingProvider[]> {+ await this.ensureInitialized();+ return await this.db!.select<BacktestingProvider[]>('SELECT * FROM backtesting_providers ORDER BY name');+ }++ async getBacktestingProvider(name: string): Promise<BacktestingProvider | null> {+ await this.ensureInitialized();+ const results = await this.db!.select<BacktestingProvider[]>(+ 'SELECT * FROM backtesting_providers WHERE name = $1',+ [name]+ );+ return results[0] || null;+ }++ async getActiveBacktestingProvider(): Promise<BacktestingProvider | null> {+ await this.ensureInitialized();+ const results = await this.db!.select<BacktestingProvider[]>(+ 'SELECT * FROM backtesting_providers WHERE is_active = 1 LIMIT 1'+ );+ return results[0] || null;+ }++ async setActiveBacktestingProvider(name: string): Promise<{ success: boolean; message: string }> {+ try {+ await this.ensureInitialized();++ // Deactivate all providers first+ await this.db!.execute('UPDATE backtesting_providers SET is_active = 0');++ // Activate the specified provider+ await this.db!.execute(+ 'UPDATE backtesting_providers SET is_active = 1, updated_at = CURRENT_TIMESTAMP WHERE name = $1',+ [name]+ );++ return { success: true, message: `Activated backtesting provider: ${name}` };+ } catch (error) {+ console.error('[SQLite] Failed to set active provider:', error);+ return { success: false, message: 'Failed to set active provider' };+ }+ }++ async deleteBacktestingProvider(name: string): Promise<{ success: boolean; message: string }> {+ try {+ await this.ensureInitialized();++ await this.db!.execute(+ 'DELETE FROM backtesting_providers WHERE name = $1',+ [name]+ );++ return { success: true, message: 'Provider deleted successfully' };+ } catch (error) {+ console.error('[SQLite] Failed to delete provider:', error);+ return { success: false, message: 'Failed to delete provider' };+ }+ }++ async saveBacktestingStrategy(strategy: Omit<BacktestingStrategy, 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string }> {+ try {+ await this.ensureInitialized();++ await this.db!.execute(+ `INSERT OR REPLACE INTO backtesting_strategies+ (id, name, description, version, author, provider_type, strategy_type, strategy_definition, tags, updated_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, CURRENT_TIMESTAMP)`,+ [+ strategy.id,+ strategy.name,+ strategy.description || null,+ strategy.version,+ strategy.author || null,+ strategy.provider_type,+ strategy.strategy_type,+ strategy.strategy_definition,+ strategy.tags || null,+ ]+ );++ return { success: true, message: 'Strategy saved successfully' };+ } catch (error) {+ console.error('[SQLite] Failed to save strategy:', error);+ return { success: false, message: 'Failed to save strategy' };+ }+ }++ async getBacktestingStrategies(): Promise<BacktestingStrategy[]> {+ await this.ensureInitialized();+ return await this.db!.select<BacktestingStrategy[]>('SELECT * FROM backtesting_strategies ORDER BY updated_at DESC');+ }++ async getBacktestingStrategy(id: string): Promise<BacktestingStrategy | null> {+ await this.ensureInitialized();+ const results = await this.db!.select<BacktestingStrategy[]>(+ 'SELECT * FROM backtesting_strategies WHERE id = $1',+ [id]+ );+ return results[0] || null;+ }++ async getBacktestingStrategiesByProvider(providerType: string): Promise<BacktestingStrategy[]> {+ await this.ensureInitialized();+ return await this.db!.select<BacktestingStrategy[]>(+ 'SELECT * FROM backtesting_strategies WHERE provider_type = $1 ORDER BY updated_at DESC',+ [providerType]+ );+ }++ async deleteBacktestingStrategy(id: string): Promise<{ success: boolean; message: string }> {+ try {+ await this.ensureInitialized();++ await this.db!.execute(+ 'DELETE FROM backtesting_strategies WHERE id = $1',+ [id]+ );++ return { success: true, message: 'Strategy deleted successfully' };+ } catch (error) {+ console.error('[SQLite] Failed to delete strategy:', error);+ return { success: false, message: 'Failed to delete strategy' };+ }+ }++ async saveBacktestRun(run: Omit<BacktestRun, 'created_at' | 'completed_at' | 'duration_seconds'>): Promise<{ success: boolean; message: string }> {+ try {+ await this.ensureInitialized();++ await this.db!.execute(+ `INSERT INTO backtest_runs+ (id, strategy_id, provider_name, config, results, status, performance_metrics, error_message)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,+ [+ run.id,+ run.strategy_id || null,+ run.provider_name,+ run.config,+ run.results || null,+ run.status,+ run.performance_metrics || null,+ run.error_message || null,+ ]+ );++ return { success: true, message: 'Backtest run saved successfully' };+ } catch (error) {+ console.error('[SQLite] Failed to save backtest run:', error);+ return { success: false, message: 'Failed to save backtest run' };+ }+ }++ async updateBacktestRun(id: string, updates: Partial<BacktestRun>): Promise<{ success: boolean; message: string }> {+ try {+ await this.ensureInitialized();++ const fields: string[] = [];+ const values: any[] = [];++ if (updates.results !== undefined) {+ fields.push('results = $' + (values.length + 1));+ values.push(updates.results);+ }+ if (updates.status !== undefined) {+ fields.push('status = $' + (values.length + 1));+ values.push(updates.status);+ }+ if (updates.performance_metrics !== undefined) {+ fields.push('performance_metrics = $' + (values.length + 1));+ values.push(updates.performance_metrics);+ }+ if (updates.error_message !== undefined) {+ fields.push('error_message = $' + (values.length + 1));+ values.push(updates.error_message);+ }+ if (updates.completed_at !== undefined) {+ fields.push('completed_at = $' + (values.length + 1));+ values.push(updates.completed_at);+ }+ if (updates.duration_seconds !== undefined) {+ fields.push('duration_seconds = $' + (values.length + 1));+ values.push(updates.duration_seconds);+ }++ if (fields.length === 0) {+ return { success: true, message: 'No updates to apply' };+ }++ values.push(id);+ await this.db!.execute(+ `UPDATE backtest_runs SET ${fields.join(', ')} WHERE id = $${values.length}`,+ values+ );++ return { success: true, message: 'Backtest run updated successfully' };+ } catch (error) {+ console.error('[SQLite] Failed to update backtest run:', error);+ return { success: false, message: 'Failed to update backtest run' };+ }+ }++ async getBacktestRuns(limit?: number): Promise<BacktestRun[]> {+ await this.ensureInitialized();+ const sql = limit+ ? `SELECT * FROM backtest_runs ORDER BY created_at DESC LIMIT ${limit}`+ : 'SELECT * FROM backtest_runs ORDER BY created_at DESC';+ return await this.db!.select<BacktestRun[]>(sql);+ }++ async getBacktestRun(id: string): Promise<BacktestRun | null> {+ await this.ensureInitialized();+ const results = await this.db!.select<BacktestRun[]>(+ 'SELECT * FROM backtest_runs WHERE id = $1',+ [id]+ );+ return results[0] || null;+ }++ async getBacktestRunsByStrategy(strategyId: string): Promise<BacktestRun[]> {+ await this.ensureInitialized();+ return await this.db!.select<BacktestRun[]>(+ 'SELECT * FROM backtest_runs WHERE strategy_id = $1 ORDER BY created_at DESC',+ [strategyId]+ );+ }++ async getBacktestRunsByProvider(providerName: string): Promise<BacktestRun[]> {+ await this.ensureInitialized();+ return await this.db!.select<BacktestRun[]>(+ 'SELECT * FROM backtest_runs WHERE provider_name = $1 ORDER BY created_at DESC',+ [providerName]+ );+ }++ async deleteBacktestRun(id: string): Promise<{ success: boolean; message: string }> {+ try {+ await this.ensureInitialized();++ await this.db!.execute(+ 'DELETE FROM backtest_runs WHERE id = $1',+ [id]+ );++ return { success: true, message: 'Backtest run deleted successfully' };+ } catch (error) {+ console.error('[SQLite] Failed to delete backtest run:', error);+ return { success: false, message: 'Failed to delete backtest run' };+ }+ }++ async saveOptimizationRun(run: Omit<OptimizationRun, 'created_at' | 'completed_at' | 'duration_seconds'>): Promise<{ success: boolean; message: string }> {+ try {+ await this.ensureInitialized();++ await this.db!.execute(+ `INSERT INTO optimization_runs+ (id, strategy_id, provider_name, parameter_grid, objective, best_parameters, best_result, all_results, iterations, status, error_message)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,+ [+ run.id,+ run.strategy_id || null,+ run.provider_name,+ run.parameter_grid,+ run.objective,+ run.best_parameters || null,+ run.best_result || null,+ run.all_results || null,+ run.iterations || null,+ run.status,+ run.error_message || null,+ ]+ );++ return { success: true, message: 'Optimization run saved successfully' };+ } catch (error) {+ console.error('[SQLite] Failed to save optimization run:', error);+ return { success: false, message: 'Failed to save optimization run' };+ }+ }++ async updateOptimizationRun(id: string, updates: Partial<OptimizationRun>): Promise<{ success: boolean; message: string }> {+ try {+ await this.ensureInitialized();++ const fields: string[] = [];+ const values: any[] = [];++ if (updates.best_parameters !== undefined) {+ fields.push('best_parameters = $' + (values.length + 1));+ values.push(updates.best_parameters);+ }+ if (updates.best_result !== undefined) {+ fields.push('best_result = $' + (values.length + 1));+ values.push(updates.best_result);+ }+ if (updates.all_results !== undefined) {+ fields.push('all_results = $' + (values.length + 1));+ values.push(updates.all_results);+ }+ if (updates.iterations !== undefined) {+ fields.push('iterations = $' + (values.length + 1));+ values.push(updates.iterations);+ }+ if (updates.status !== undefined) {+ fields.push('status = $' + (values.length + 1));+ values.push(updates.status);+ }+ if (updates.error_message !== undefined) {+ fields.push('error_message = $' + (values.length + 1));+ values.push(updates.error_message);+ }+ if (updates.completed_at !== undefined) {+ fields.push('completed_at = $' + (values.length + 1));+ values.push(updates.completed_at);+ }+ if (updates.duration_seconds !== undefined) {+ fields.push('duration_seconds = $' + (values.length + 1));+ values.push(updates.duration_seconds);+ }++ if (fields.length === 0) {+ return { success: true, message: 'No updates to apply' };+ }++ values.push(id);+ await this.db!.execute(+ `UPDATE optimization_runs SET ${fields.join(', ')} WHERE id = $${values.length}`,+ values+ );++ return { success: true, message: 'Optimization run updated successfully' };+ } catch (error) {+ console.error('[SQLite] Failed to update optimization run:', error);+ return { success: false, message: 'Failed to update optimization run' };+ }+ }++ async getOptimizationRuns(limit?: number): Promise<OptimizationRun[]> {+ await this.ensureInitialized();+ const sql = limit+ ? `SELECT * FROM optimization_runs ORDER BY created_at DESC LIMIT ${limit}`+ : 'SELECT * FROM optimization_runs ORDER BY created_at DESC';+ return await this.db!.select<OptimizationRun[]>(sql);+ }++ async getOptimizationRun(id: string): Promise<OptimizationRun | null> {+ await this.ensureInitialized();+ const results = await this.db!.select<OptimizationRun[]>(+ 'SELECT * FROM optimization_runs WHERE id = $1',+ [id]+ );+ return results[0] || null;+ }++ async deleteOptimizationRun(id: string): Promise<{ success: boolean; message: string }> {+ try {+ await this.ensureInitialized();++ await this.db!.execute(+ 'DELETE FROM optimization_runs WHERE id = $1',+ [id]+ );++ return { success: true, message: 'Optimization run deleted successfully' };+ } catch (error) {+ console.error('[SQLite] Failed to delete optimization run:', error);+ return { success: false, message: 'Failed to delete optimization run' };+ }+ }+// =========================// UTILITY METHODS// =========================diff --git a/fincept-terminal-desktop/src/services/terminalThemeService.ts b/fincept-terminal-desktop/src/services/terminalThemeService.tsindex 33f523b73..9d968ade4 100644--- a/fincept-terminal-desktop/src/services/terminalThemeService.ts+++ b/fincept-terminal-desktop/src/services/terminalThemeService.ts@@ -12,6 +12,7 @@ export interface ColorTheme {name: string;primary: string; // Replaces BLOOMBERG_ORANGEsecondary: string; // Replaces BLOOMBERG_GREEN+ success: string; // Success/positive states (same as secondary)alert: string; // Replaces BLOOMBERG_REDwarning: string; // BLOOMBERG_YELLOWinfo: string; // BLOOMBERG_BLUE@@ -42,6 +43,7 @@ export const COLOR_THEMES: Record<string, ColorTheme> = {name: 'Bloomberg Classic',primary: '#FFA500',secondary: '#00C800',+ success: '#00C800',alert: '#FF0000',warning: '#FFFF00',info: '#6496FA',@@ -56,6 +58,7 @@ export const COLOR_THEMES: Record<string, ColorTheme> = {name: 'Matrix Green',primary: '#00FF41',secondary: '#008F11',+ success: '#00FF41',alert: '#FF0000',warning: '#FFD700',info: '#00D4AA',@@ -70,6 +73,7 @@ export const COLOR_THEMES: Record<string, ColorTheme> = {name: 'Blue Terminal',primary: '#00D4FF',secondary: '#00FF88',+ success: '#6BCF7F',alert: '#FF6B6B',warning: '#FFD93D',info: '#6BCF7F',@@ -84,6 +88,7 @@ export const COLOR_THEMES: Record<string, ColorTheme> = {name: 'Amber Retro',primary: '#FFAA00',secondary: '#00FF00',+ success: '#00FF00',alert: '#FF0000',warning: '#FFCC00',info: '#88CCFF',@@ -98,6 +103,7 @@ export const COLOR_THEMES: Record<string, ColorTheme> = {name: 'Purple Neon',primary: '#C864FF',secondary: '#00FFA3',+ success: '#00FFA3',alert: '#FF4D6D',warning: '#FFD23F',info: '#64D2FF',diff --git a/fincept-terminal-desktop/src/services/trading/index.ts b/fincept-terminal-desktop/src/services/trading/index.tsnew file mode 100644index 000000000..8e3c0defe--- /dev/null+++ b/fincept-terminal-desktop/src/services/trading/index.ts@@ -0,0 +1,5 @@+// File: src/services/trading/index.ts+// Trading services exports++export { PaperTradingService, createPaperTradingService } from './paperTradingService';+export type * from '../../types/trading';diff --git a/fincept-terminal-desktop/src/services/trading/paperTradingService.ts b/fincept-terminal-desktop/src/services/trading/paperTradingService.tsnew file mode 100644index 000000000..80c3d5f63--- /dev/null+++ b/fincept-terminal-desktop/src/services/trading/paperTradingService.ts@@ -0,0 +1,712 @@+// File: src/services/trading/paperTradingService.ts+// Paper trading engine - simulates trading with virtual money++import Database from '@tauri-apps/plugin-sql';+import type {+ VirtualPortfolio,+ Position,+ Order,+ Trade,+ OrderRequest,+ OrderResult,+ PaperTradingConfig,+ DbPortfolio,+ DbPosition,+ DbOrder,+ DbTrade+} from '../../types/trading';+import { getWebSocketManager } from '../websocket';+import type { NormalizedMessage, Subscription } from '../websocket/types';++/**+ * Paper Trading Service+ * Manages virtual portfolios, positions, orders, and trades+ */+export class PaperTradingService {+ private db: Database | null = null;+ private config: PaperTradingConfig;+ private marketPrices = new Map<string, number>(); // symbol -> current price+ private priceSubscriptions = new Map<string, Subscription>(); // symbol -> subscription+ private orderMonitorInterval: NodeJS.Timeout | null = null;++ constructor(config?: Partial<PaperTradingConfig>) {+ this.config = {+ portfolioId: config?.portfolioId || '',+ feeRate: config?.feeRate || 0.0002, // 0.02% fee+ slippage: config?.slippage || 0.0001 // 0.01% slippage+ };+ }++ /**+ * Initialize database connection+ */+ async initialize(): Promise<void> {+ if (!this.db) {+ this.db = await Database.load('sqlite:fincept_terminal.db');+ }+ }++ /**+ * Create a new paper trading portfolio+ */+ async createPortfolio(+ name: string,+ provider: string,+ initialBalance: number = 100000+ ): Promise<string> {+ await this.initialize();++ const id = crypto.randomUUID();++ await this.db!.execute(+ `INSERT INTO paper_trading_portfolios (id, name, provider, initial_balance, current_balance)+ VALUES ($1, $2, $3, $4, $5)`,+ [id, name, provider, initialBalance, initialBalance]+ );++ this.config.portfolioId = id;++ return id;+ }++ /**+ * Get portfolio by ID+ */+ async getPortfolio(portfolioId: string): Promise<VirtualPortfolio | null> {+ await this.initialize();++ const results = await this.db!.select<DbPortfolio[]>(+ 'SELECT * FROM paper_trading_portfolios WHERE id = $1',+ [portfolioId]+ );++ if (results.length === 0) return null;++ const dbPortfolio = results[0];+ const positions = await this.getPositions(portfolioId);++ // Calculate total P&L+ const totalPnL = positions.reduce((sum, pos) => {+ return sum + (pos.unrealizedPnL || 0) + pos.realizedPnL;+ }, 0);++ return {+ id: dbPortfolio.id,+ name: dbPortfolio.name,+ provider: dbPortfolio.provider,+ initialBalance: dbPortfolio.initial_balance,+ balance: dbPortfolio.current_balance,+ totalPnL,+ positions,+ createdAt: dbPortfolio.created_at,+ updatedAt: dbPortfolio.updated_at+ };+ }++ /**+ * Get all open positions for a portfolio+ */+ async getPositions(portfolioId: string, status: 'open' | 'closed' | 'all' = 'open'): Promise<Position[]> {+ await this.initialize();++ let query = 'SELECT * FROM paper_trading_positions WHERE portfolio_id = $1';+ const params: any[] = [portfolioId];++ if (status !== 'all') {+ query += ' AND status = $2';+ params.push(status);+ }++ query += ' ORDER BY opened_at DESC';++ const results = await this.db!.select<DbPosition[]>(query, params);++ return results.map(dbPos => this.mapDbPosition(dbPos));+ }++ /**+ * Get all orders for a portfolio+ */+ async getOrders(portfolioId: string): Promise<Order[]> {+ await this.initialize();++ const results = await this.db!.select<DbOrder[]>(+ 'SELECT * FROM paper_trading_orders WHERE portfolio_id = $1 ORDER BY created_at DESC',+ [portfolioId]+ );++ return results.map(dbOrder => this.mapDbOrder(dbOrder));+ }++ /**+ * Place an order+ */+ async placeOrder(portfolioId: string, order: OrderRequest): Promise<OrderResult> {+ await this.initialize();++ const portfolio = await this.getPortfolio(portfolioId);++ if (!portfolio) {+ return { success: false, error: 'Portfolio not found' };+ }++ // Validate balance for buy orders+ if (order.side === 'buy') {+ const estimatedPrice = order.price || await this.getCurrentPrice(order.symbol);+ const requiredBalance = order.quantity * estimatedPrice;++ if (portfolio.balance < requiredBalance) {+ return { success: false, error: 'Insufficient balance' };+ }+ }++ // Validate order parameters+ if ((order.type === 'limit' || order.type === 'stop_limit') && !order.price) {+ return { success: false, error: 'Limit orders require a price' };+ }++ if ((order.type === 'stop_market' || order.type === 'stop_limit') && !order.stopPrice) {+ return { success: false, error: 'Stop orders require a stop price' };+ }++ // Create order record+ const orderId = crypto.randomUUID();++ await this.db!.execute(+ `INSERT INTO paper_trading_orders+ (id, portfolio_id, symbol, side, type, quantity, price, stop_price, status)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'pending')`,+ [+ orderId,+ portfolioId,+ order.symbol,+ order.side,+ order.type,+ order.quantity,+ order.price || null,+ order.stopPrice || null+ ]+ );++ // Execute market orders immediately+ if (order.type === 'market') {+ await this.executeMarketOrder(portfolioId, orderId, order);+ }++ // Subscribe to price updates for this symbol+ await this.subscribeToPriceUpdates(order.symbol, portfolio.provider);++ return { success: true, orderId };+ }++ /**+ * Execute a market order+ */+ private async executeMarketOrder(+ portfolioId: string,+ orderId: string,+ order: OrderRequest+ ): Promise<void> {+ const currentPrice = await this.getCurrentPrice(order.symbol);++ // Apply slippage+ const executionPrice = order.side === 'buy'+ ? currentPrice * (1 + this.config.slippage)+ : currentPrice * (1 - this.config.slippage);++ // Calculate fee+ const fee = executionPrice * order.quantity * this.config.feeRate;++ // Total cost/proceeds+ const totalCost = order.side === 'buy'+ ? (executionPrice * order.quantity) + fee+ : (executionPrice * order.quantity) - fee;++ // Update order status+ await this.db!.execute(+ `UPDATE paper_trading_orders+ SET status = 'filled', filled_quantity = $1, avg_fill_price = $2, filled_at = CURRENT_TIMESTAMP+ WHERE id = $3`,+ [order.quantity, executionPrice, orderId]+ );++ // Create trade record+ await this.createTrade(portfolioId, orderId, order, executionPrice, fee);++ // Update position+ await this.updatePosition(portfolioId, order, executionPrice);++ // Update balance+ const balanceChange = order.side === 'buy' ? -totalCost : totalCost;+ await this.updateBalance(portfolioId, balanceChange);+ }++ /**+ * Execute a limit order (called by order monitor)+ */+ private async executeLimitOrder(+ portfolioId: string,+ orderId: string,+ order: DbOrder,+ currentPrice: number+ ): Promise<void> {+ const fee = currentPrice * order.quantity * this.config.feeRate;++ // Update order status+ await this.db!.execute(+ `UPDATE paper_trading_orders+ SET status = 'filled', filled_quantity = $1, avg_fill_price = $2, filled_at = CURRENT_TIMESTAMP+ WHERE id = $3`,+ [order.quantity, currentPrice, order.id]+ );++ // Create trade record+ const tradeRequest: OrderRequest = {+ symbol: order.symbol,+ side: order.side,+ type: order.type,+ quantity: order.quantity+ };++ await this.createTrade(portfolioId, orderId, tradeRequest, currentPrice, fee);++ // Update position+ await this.updatePosition(portfolioId, tradeRequest, currentPrice);++ // Update balance+ const totalCost = order.side === 'buy'+ ? (currentPrice * order.quantity) + fee+ : (currentPrice * order.quantity) - fee;++ const balanceChange = order.side === 'buy' ? -totalCost : totalCost;+ await this.updateBalance(portfolioId, balanceChange);+ }++ /**+ * Create trade record+ */+ private async createTrade(+ portfolioId: string,+ orderId: string,+ order: OrderRequest,+ price: number,+ fee: number+ ): Promise<void> {+ const tradeId = crypto.randomUUID();++ await this.db!.execute(+ `INSERT INTO paper_trading_trades+ (id, portfolio_id, order_id, symbol, side, price, quantity, fee)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,+ [tradeId, portfolioId, orderId, order.symbol, order.side, price, order.quantity, fee]+ );+ }++ /**+ * Update or create position+ */+ private async updatePosition(+ portfolioId: string,+ order: OrderRequest,+ price: number+ ): Promise<void> {+ // Check if position exists+ const existing = await this.db!.select<DbPosition[]>(+ `SELECT * FROM paper_trading_positions+ WHERE portfolio_id = $1 AND symbol = $2 AND status = 'open'`,+ [portfolioId, order.symbol]+ );++ if (existing.length > 0) {+ const position = existing[0];++ // Determine if we're adding to or closing position+ const isSameSide = (order.side === 'buy' && position.side === 'long') ||+ (order.side === 'sell' && position.side === 'short');++ if (isSameSide) {+ // Add to position+ const newQuantity = position.quantity + order.quantity;+ const newAvgPrice = ((position.entry_price * position.quantity) + (price * order.quantity)) / newQuantity;++ await this.db!.execute(+ `UPDATE paper_trading_positions+ SET quantity = $1, entry_price = $2, updated_at = CURRENT_TIMESTAMP+ WHERE id = $3`,+ [newQuantity, newAvgPrice, position.id]+ );+ } else {+ // Opposite side - reduce or close position+ if (order.quantity >= position.quantity) {+ // Close entire position+ const pnl = (price - position.entry_price) * position.quantity *+ (position.side === 'long' ? 1 : -1);++ await this.db!.execute(+ `UPDATE paper_trading_positions+ SET status = 'closed', realized_pnl = $1, closed_at = CURRENT_TIMESTAMP+ WHERE id = $2`,+ [pnl, position.id]+ );++ // If order quantity exceeds position, create new opposite position+ if (order.quantity > position.quantity) {+ await this.createPosition(+ portfolioId,+ order.symbol,+ order.side === 'buy' ? 'long' : 'short',+ price,+ order.quantity - position.quantity+ );+ }+ } else {+ // Reduce position+ const newQuantity = position.quantity - order.quantity;+ const partialPnl = (price - position.entry_price) * order.quantity *+ (position.side === 'long' ? 1 : -1);++ await this.db!.execute(+ `UPDATE paper_trading_positions+ SET quantity = $1, realized_pnl = realized_pnl + $2, updated_at = CURRENT_TIMESTAMP+ WHERE id = $3`,+ [newQuantity, partialPnl, position.id]+ );+ }+ }+ } else {+ // Create new position+ await this.createPosition(+ portfolioId,+ order.symbol,+ order.side === 'buy' ? 'long' : 'short',+ price,+ order.quantity+ );+ }+ }++ /**+ * Create new position+ */+ private async createPosition(+ portfolioId: string,+ symbol: string,+ side: 'long' | 'short',+ entryPrice: number,+ quantity: number+ ): Promise<void> {+ const positionId = crypto.randomUUID();++ await this.db!.execute(+ `INSERT INTO paper_trading_positions+ (id, portfolio_id, symbol, side, entry_price, quantity, status)+ VALUES ($1, $2, $3, $4, $5, $6, 'open')`,+ [positionId, portfolioId, symbol, side, entryPrice, quantity]+ );+ }++ /**+ * Update portfolio balance+ */+ private async updateBalance(portfolioId: string, amount: number): Promise<void> {+ await this.db!.execute(+ `UPDATE paper_trading_portfolios+ SET current_balance = current_balance + $1, updated_at = CURRENT_TIMESTAMP+ WHERE id = $2`,+ [amount, portfolioId]+ );+ }++ /**+ * Subscribe to market price updates for a symbol+ */+ private async subscribeToPriceUpdates(symbol: string, provider: string): Promise<void> {+ // Avoid duplicate subscriptions+ if (this.priceSubscriptions.has(symbol)) {+ return;+ }++ const manager = getWebSocketManager();+ const topic = `${provider}.ticker.${symbol}`;++ const subscription = await manager.subscribe(topic, (message: NormalizedMessage) => {+ this.handlePriceUpdate(message);+ });++ this.priceSubscriptions.set(symbol, subscription);++ // Start order monitor if not already running+ if (!this.orderMonitorInterval) {+ this.startOrderMonitor();+ }+ }++ /**+ * Handle incoming price updates+ */+ private handlePriceUpdate(message: NormalizedMessage): void {+ const symbol = message.symbol;+ if (!symbol) return;++ let price: number | undefined;++ // Extract price from different message types+ if (message.type === 'ticker') {+ price = message.data.last || message.data.close || message.data.mid;+ } else if (message.type === 'trade') {+ price = message.data.price || message.data.last;+ }++ if (price) {+ this.marketPrices.set(symbol, price);++ // Update unrealized P&L for open positions+ this.updateUnrealizedPnL(symbol, price);+ }+ }++ /**+ * Get current market price for a symbol+ */+ private async getCurrentPrice(symbol: string): Promise<number> {+ const price = this.marketPrices.get(symbol);++ if (!price) {+ throw new Error(`No market price available for ${symbol}`);+ }++ return price;+ }++ /**+ * Update unrealized P&L for all positions of a symbol+ */+ private async updateUnrealizedPnL(symbol: string, currentPrice: number): Promise<void> {+ await this.initialize();++ const positions = await this.db!.select<DbPosition[]>(+ `SELECT * FROM paper_trading_positions WHERE symbol = $1 AND status = 'open'`,+ [symbol]+ );++ for (const position of positions) {+ const pnl = (currentPrice - position.entry_price) * position.quantity *+ (position.side === 'long' ? 1 : -1);++ await this.db!.execute(+ `UPDATE paper_trading_positions+ SET current_price = $1, unrealized_pnl = $2, updated_at = CURRENT_TIMESTAMP+ WHERE id = $3`,+ [currentPrice, pnl, position.id]+ );+ }+ }++ /**+ * Monitor pending orders and execute when conditions are met+ */+ private startOrderMonitor(): void {+ // Check every 500ms+ this.orderMonitorInterval = setInterval(async () => {+ await this.checkPendingOrders();+ }, 500);+ }++ /**+ * Check all pending orders and execute if conditions are met+ */+ private async checkPendingOrders(): Promise<void> {+ await this.initialize();++ const pendingOrders = await this.db!.select<DbOrder[]>(+ `SELECT * FROM paper_trading_orders WHERE status IN ('pending', 'triggered')`+ );++ for (const order of pendingOrders) {+ const currentPrice = this.marketPrices.get(order.symbol);+ if (!currentPrice) continue;++ if (order.type === 'limit' && order.price) {+ // Buy limit: execute if market <= limit+ // Sell limit: execute if market >= limit+ const shouldExecute = order.side === 'buy'+ ? currentPrice <= order.price+ : currentPrice >= order.price;++ if (shouldExecute) {+ await this.executeLimitOrder(order.portfolio_id, order.id, order, currentPrice);+ }+ } else if (order.type === 'stop_market' && order.stop_price) {+ // Buy stop: trigger if market >= stop+ // Sell stop: trigger if market <= stop+ const triggered = order.side === 'buy'+ ? currentPrice >= order.stop_price+ : currentPrice <= order.stop_price;++ if (triggered) {+ // Execute as market order+ const orderRequest: OrderRequest = {+ symbol: order.symbol,+ side: order.side,+ type: 'market',+ quantity: order.quantity+ };++ await this.executeMarketOrder(order.portfolio_id, order.id, orderRequest);+ }+ } else if (order.type === 'stop_limit' && order.stop_price && order.price) {+ // Two-step: first trigger, then wait for limit+ if (order.status === 'pending') {+ // Check if stop triggered+ const triggered = order.side === 'buy'+ ? currentPrice >= order.stop_price+ : currentPrice <= order.stop_price;++ if (triggered) {+ await this.db!.execute(+ `UPDATE paper_trading_orders SET status = 'triggered' WHERE id = $1`,+ [order.id]+ );+ }+ } else if (order.status === 'triggered') {+ // Now check limit condition+ const shouldExecute = order.side === 'buy'+ ? currentPrice <= order.price+ : currentPrice >= order.price;++ if (shouldExecute) {+ await this.executeLimitOrder(order.portfolio_id, order.id, order, currentPrice);+ }+ }+ }+ }+ }++ /**+ * Cancel an order+ */+ async cancelOrder(orderId: string): Promise<boolean> {+ await this.initialize();++ await this.db!.execute(+ `UPDATE paper_trading_orders SET status = 'cancelled' WHERE id = $1 AND status IN ('pending', 'triggered')`,+ [orderId]+ );++ return true;+ }++ /**+ * Close a position+ */+ async closePosition(positionId: string): Promise<boolean> {+ await this.initialize();++ const results = await this.db!.select<DbPosition[]>(+ `SELECT * FROM paper_trading_positions WHERE id = $1 AND status = 'open'`,+ [positionId]+ );++ if (results.length === 0) return false;++ const position = results[0];+ const currentPrice = this.marketPrices.get(position.symbol);++ if (!currentPrice) {+ throw new Error(`No current price for ${position.symbol}`);+ }++ // Create closing order+ const orderRequest: OrderRequest = {+ symbol: position.symbol,+ side: position.side === 'long' ? 'sell' : 'buy',+ type: 'market',+ quantity: position.quantity+ };++ await this.placeOrder(position.portfolio_id, orderRequest);++ return true;+ }++ /**+ * Reset portfolio to initial state+ */+ async resetPortfolio(portfolioId: string): Promise<boolean> {+ await this.initialize();++ const portfolio = await this.getPortfolio(portfolioId);+ if (!portfolio) return false;++ // Delete all positions, orders, and trades+ await this.db!.execute(`DELETE FROM paper_trading_trades WHERE portfolio_id = $1`, [portfolioId]);+ await this.db!.execute(`DELETE FROM paper_trading_orders WHERE portfolio_id = $1`, [portfolioId]);+ await this.db!.execute(`DELETE FROM paper_trading_positions WHERE portfolio_id = $1`, [portfolioId]);++ // Reset balance+ await this.db!.execute(+ `UPDATE paper_trading_portfolios SET current_balance = initial_balance, updated_at = CURRENT_TIMESTAMP WHERE id = $1`,+ [portfolioId]+ );++ return true;+ }++ /**+ * Cleanup - unsubscribe from price updates and stop monitoring+ */+ cleanup(): void {+ // Unsubscribe from all price updates+ this.priceSubscriptions.forEach(sub => sub.unsubscribe());+ this.priceSubscriptions.clear();++ // Stop order monitor+ if (this.orderMonitorInterval) {+ clearInterval(this.orderMonitorInterval);+ this.orderMonitorInterval = null;+ }+ }++ // Helper mappers+ private mapDbPosition(dbPos: DbPosition): Position {+ return {+ id: dbPos.id,+ portfolioId: dbPos.portfolio_id,+ symbol: dbPos.symbol,+ side: dbPos.side,+ entryPrice: dbPos.entry_price,+ quantity: dbPos.quantity,+ currentPrice: dbPos.current_price || undefined,+ unrealizedPnL: dbPos.unrealized_pnl || undefined,+ realizedPnL: dbPos.realized_pnl,+ openedAt: dbPos.opened_at,+ closedAt: dbPos.closed_at || undefined,+ status: dbPos.status+ };+ }++ private mapDbOrder(dbOrder: DbOrder): Order {+ return {+ id: dbOrder.id,+ portfolioId: dbOrder.portfolio_id,+ symbol: dbOrder.symbol,+ side: dbOrder.side,+ type: dbOrder.type,+ quantity: dbOrder.quantity,+ price: dbOrder.price || undefined,+ stopPrice: dbOrder.stop_price || undefined,+ filledQuantity: dbOrder.filled_quantity,+ avgFillPrice: dbOrder.avg_fill_price || undefined,+ status: dbOrder.status,+ createdAt: dbOrder.created_at,+ filledAt: dbOrder.filled_at || undefined+ };+ }+}++/**+ * Create a new paper trading service instance+ */+export function createPaperTradingService(config?: Partial<PaperTradingConfig>): PaperTradingService {+ return new PaperTradingService(config);+}diff --git a/fincept-terminal-desktop/src/services/websocket/adapters/HyperLiquidAdapter.ts b/fincept-terminal-desktop/src/services/websocket/adapters/HyperLiquidAdapter.tsnew file mode 100644index 000000000..cbec9fb60--- /dev/null+++ b/fincept-terminal-desktop/src/services/websocket/adapters/HyperLiquidAdapter.ts@@ -0,0 +1,619 @@+// File: src/services/websocket/adapters/HyperLiquidAdapter.ts+// HyperLiquid WebSocket API adapter+// Documentation: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/websocket++import { BaseAdapter } from './BaseAdapter';+import { ProviderConfig, NormalizedMessage } from '../types';+import type {+ HyperLiquidMessage,+ HyperLiquidSubscriptionRequest,+ HyperLiquidSubscriptionType,+ HyperLiquidAllMidsData,+ HyperLiquidL2BookData,+ HyperLiquidTradesData,+ HyperLiquidCandleData,+ HyperLiquidBBOData,+ HyperLiquidUserFillsData,+ HyperLiquidOpenOrdersData,+ HyperLiquidUserFundingsData,+ HyperLiquidCandleInterval+} from '../../../types/hyperliquid';++/**+ * HyperLiquidAdapter - WebSocket adapter for HyperLiquid exchange+ *+ * Supported channels:+ * - allMids: Mid-prices for all coins+ * - l2Book: Level 2 order book (nSigFigs: 2-5, depth configurable)+ * - trades: Recent trades+ * - candle: OHLC candlestick data (intervals: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 8h, 12h, 1d, 3d, 1w, 1M)+ * - bbo: Best bid/offer updates+ * - userFills: User-specific fill history (requires user address)+ * - openOrders: User open orders (requires user address)+ * - userFundings: User funding payments (requires user address)+ * - clearinghouseState: User position state (requires user address)+ *+ * Topic format: "channel.symbol" e.g., "l2Book.BTC" or "trades.ETH"+ * User-specific: "userFills" (no symbol, requires config.api_key as user address)+ */+export class HyperLiquidAdapter extends BaseAdapter {+ readonly provider = 'hyperliquid';++ private readonly WS_URL = 'wss://api.hyperliquid.xyz/ws';+ private readonly WS_TESTNET_URL = 'wss://api.hyperliquid-testnet.xyz/ws';++ // Track pending subscriptions for response matching+ private pendingSubscriptions = new Map<string, { channel: string; symbol?: string }>();++ /**+ * Get WebSocket URL based on config+ */+ protected getWebSocketUrl(config: ProviderConfig): string {+ // Check if testnet mode is enabled in config_data+ const useTestnet = config.config_data+ ? JSON.parse(config.config_data).testnet === true+ : false;++ return useTestnet ? this.WS_TESTNET_URL : this.WS_URL;+ }++ /**+ * Handle incoming messages from HyperLiquid+ */+ protected handleMessage(event: MessageEvent): void {+ try {+ const message: HyperLiquidMessage = JSON.parse(event.data);++ this.log('Received message:', message);++ // Handle subscription responses+ if (message.channel === 'subscriptionResponse') {+ this.handleSubscriptionResponse(message);+ return;+ }++ // Handle channel data messages+ if (message.channel && message.data) {+ this.handleChannelMessage(message);+ }+ } catch (error) {+ console.error('[HyperLiquidAdapter] Failed to parse message:', error);+ }+ }++ /**+ * Channel aliasing map: Generic channel names → HyperLiquid-specific channels+ * This allows components to use generic names like "ticker" and "book"+ */+ private readonly CHANNEL_ALIAS_MAP: Record<string, string> = {+ 'ticker': 'bbo', // ticker → bbo (best bid/offer - per symbol ticker data)+ 'book': 'l2Book', // book → l2Book (level 2 order book)+ 'trade': 'trades', // trade → trades (recent trades)+ 'ohlc': 'candle', // ohlc → candle (candlestick data)+ };++ /**+ * Reverse alias map for normalization: HyperLiquid channels → Generic names+ */+ private readonly REVERSE_ALIAS_MAP: Record<string, string> = {+ 'bbo': 'ticker',+ 'l2Book': 'book',+ 'trades': 'trade',+ 'candle': 'ohlc',+ };++ /**+ * Subscribe to a channel+ * @param topic - Format: "channel.symbol" e.g., "ticker.BTC" or "book.ETH"+ * @param params - Optional parameters (nSigFigs, mantissa, interval, aggregateByTime)+ */+ protected async performSubscribe(topic: string, params?: Record<string, any>): Promise<void> {+ const { channel, symbol } = this.parseTopic(topic);++ // Map generic channel name to HyperLiquid-specific channel+ const hlChannel = this.CHANNEL_ALIAS_MAP[channel] || channel;++ this.log(`Subscribing to topic: ${topic} → HyperLiquid channel: ${hlChannel}${symbol ? ` (${symbol})` : ''}`);++ // Build subscription request+ const subscription: any = {+ type: hlChannel as HyperLiquidSubscriptionType+ };++ // Add symbol if provided (coin parameter in HyperLiquid)+ if (symbol) {+ subscription.coin = symbol;+ }++ // Add user address for user-specific channels+ if (this.isUserSpecificChannel(channel)) {+ if (!this.config?.api_key) {+ throw new Error(`Channel ${channel} requires user address (set api_key in config)`);+ }+ subscription.user = this.config.api_key;+ }++ // Channel-specific parameters (use HyperLiquid channel name)+ if (hlChannel === 'l2Book') {+ subscription.nSigFigs = params?.nSigFigs ?? 5;+ if (params?.mantissa) {+ subscription.mantissa = params.mantissa;+ }+ }++ if (hlChannel === 'candle') {+ subscription.interval = params?.interval ?? '1m';+ }++ if (hlChannel === 'userFills' && params?.aggregateByTime !== undefined) {+ subscription.aggregateByTime = params.aggregateByTime;+ }++ const subscribeMessage: HyperLiquidSubscriptionRequest = {+ method: 'subscribe',+ subscription+ };++ // Track pending subscription (store original generic channel for proper routing)+ const subscriptionKey = this.buildSubscriptionKey(subscribeMessage.subscription);+ this.pendingSubscriptions.set(subscriptionKey, { channel, symbol });++ await this.send(subscribeMessage);+ this.log(`✅ Subscription sent: ${topic} → ${hlChannel}${symbol ? ` (${symbol})` : ''}`);+ }++ /**+ * Unsubscribe from a channel+ */+ protected async performUnsubscribe(topic: string): Promise<void> {+ const { channel, symbol } = this.parseTopic(topic);++ // Map generic channel name to HyperLiquid-specific channel+ const hlChannel = this.CHANNEL_ALIAS_MAP[channel] || channel;++ this.log(`Unsubscribing from topic: ${topic} → HyperLiquid channel: ${hlChannel}${symbol ? ` (${symbol})` : ''}`);++ // Build unsubscribe request (must match original subscription)+ const subscription: any = {+ type: hlChannel as HyperLiquidSubscriptionType+ };++ if (symbol) {+ subscription.coin = symbol;+ }++ if (this.isUserSpecificChannel(channel)) {+ if (!this.config?.api_key) {+ this.log(`Cannot unsubscribe from ${channel}: no user address`);+ return;+ }+ subscription.user = this.config.api_key;+ }++ const unsubscribeMessage: HyperLiquidSubscriptionRequest = {+ method: 'unsubscribe',+ subscription+ };++ await this.send(unsubscribeMessage);+ this.log(`Sent unsubscription request for ${topic}`);+ }++ /**+ * Perform ping (HyperLiquid uses message activity for heartbeat)+ */+ protected async performPing(): Promise<void> {+ // HyperLiquid doesn't have explicit ping/pong+ // Heartbeat is maintained by message activity+ // We can send a subscription status check or just log+ this.log('Heartbeat check (no explicit ping for HyperLiquid)');+ }++ /**+ * Called after successful connection+ */+ protected async onConnected(): Promise<void> {+ this.log('WebSocket connected successfully to HyperLiquid');+ }++ /**+ * Handle subscription response+ */+ private handleSubscriptionResponse(message: any): void {+ this.log('Subscription response:', message);++ if (message.data) {+ const { method, subscription } = message.data;++ if (method === 'subscribe') {+ this.log('Subscription confirmed:', subscription);+ } else if (method === 'unsubscribe') {+ this.log('Unsubscription confirmed:', subscription);+ }+ }+ }++ /**+ * Handle channel data messages+ */+ private handleChannelMessage(message: HyperLiquidMessage): void {+ const channel = message.channel;++ // Normalize based on channel type+ const normalizedMessages = this.normalizeMessage(message);++ // Emit each normalized message+ normalizedMessages.forEach(msg => {+ this.notifyMessage(msg);+ });+ }++ /**+ * Normalize HyperLiquid message to standard format+ */+ private normalizeMessage(message: HyperLiquidMessage): NormalizedMessage[] {+ const normalized: NormalizedMessage[] = [];+ const channel = message.channel;++ if (!message.data) {+ return normalized;+ }++ try {+ switch (channel) {+ case 'allMids':+ normalized.push(...this.normalizeAllMids(message.data as HyperLiquidAllMidsData));+ break;++ case 'l2Book':+ normalized.push(this.normalizeL2Book(message.data as HyperLiquidL2BookData));+ break;++ case 'trades':+ normalized.push(this.normalizeTrades(message.data as HyperLiquidTradesData));+ break;++ case 'candle':+ normalized.push(this.normalizeCandle(message.data as HyperLiquidCandleData));+ break;++ case 'bbo':+ normalized.push(this.normalizeBBO(message.data as HyperLiquidBBOData));+ break;++ case 'userFills':+ normalized.push(this.normalizeUserFills(message.data as HyperLiquidUserFillsData));+ break;++ case 'openOrders':+ normalized.push(this.normalizeOpenOrders(message.data as HyperLiquidOpenOrdersData));+ break;++ case 'userFundings':+ normalized.push(this.normalizeUserFundings(message.data as HyperLiquidUserFundingsData));+ break;++ default:+ // Generic normalization for other channels+ normalized.push({+ provider: this.provider,+ channel,+ type: 'custom',+ timestamp: Date.now(),+ data: message.data,+ raw: message+ });+ }+ } catch (error) {+ console.error(`[HyperLiquidAdapter] Error normalizing ${channel} message:`, error);+ }++ return normalized;+ }++ /**+ * Normalize allMids (ticker data for all coins)+ */+ private normalizeAllMids(data: HyperLiquidAllMidsData): NormalizedMessage[] {+ const messages: NormalizedMessage[] = [];++ if (data.mids) {+ Object.entries(data.mids).forEach(([coin, midPrice]) => {+ messages.push({+ provider: this.provider,+ channel: 'allMids',+ type: 'ticker',+ symbol: coin,+ timestamp: Date.now(),+ data: {+ mid: parseFloat(midPrice),+ coin+ },+ raw: data+ });+ });+ }++ return messages;+ }++ /**+ * Normalize L2 order book+ */+ private normalizeL2Book(data: HyperLiquidL2BookData): NormalizedMessage {+ const [bids, asks] = data.levels;++ return {+ provider: this.provider,+ channel: this.REVERSE_ALIAS_MAP['l2Book'] || 'l2Book', // Use generic 'book' channel name+ type: 'orderbook',+ symbol: data.coin,+ timestamp: data.time,+ data: {+ coin: data.coin,+ bids: bids.map(level => ({+ price: parseFloat(level.px),+ size: parseFloat(level.sz),+ count: level.n+ })),+ asks: asks.map(level => ({+ price: parseFloat(level.px),+ size: parseFloat(level.sz),+ count: level.n+ })),+ time: data.time+ },+ raw: data+ };+ }++ /**+ * Normalize trades+ */+ private normalizeTrades(data: HyperLiquidTradesData): NormalizedMessage {+ return {+ provider: this.provider,+ channel: this.REVERSE_ALIAS_MAP['trades'] || 'trades', // Use generic 'trade' channel name+ type: 'trade',+ symbol: data.coin,+ timestamp: Date.now(),+ data: {+ coin: data.coin,+ trades: data.trades.map(trade => ({+ price: parseFloat(trade.px),+ size: parseFloat(trade.sz),+ side: trade.side === 'A' ? 'sell' : 'buy', // A = Ask (sell), B = Bid (buy)+ time: trade.time,+ tradeId: trade.tid,+ hash: trade.hash+ }))+ },+ raw: data+ };+ }++ /**+ * Normalize candle data+ */+ private normalizeCandle(data: HyperLiquidCandleData): NormalizedMessage {+ const candle = data.candle;++ if (!candle) {+ throw new Error('No candle data in message');+ }++ return {+ provider: this.provider,+ channel: this.REVERSE_ALIAS_MAP['candle'] || 'candle', // Use generic 'ohlc' channel name+ type: 'candle',+ symbol: candle.s,+ timestamp: candle.t,+ data: {+ symbol: candle.s,+ interval: candle.i,+ openTime: candle.t,+ closeTime: candle.T,+ open: parseFloat(candle.o),+ high: parseFloat(candle.h),+ low: parseFloat(candle.l),+ close: parseFloat(candle.c),+ volume: parseFloat(candle.v),+ trades: candle.n+ },+ raw: data+ };+ }++ /**+ * Normalize BBO (best bid/offer) - This is HyperLiquid's ticker data+ */+ private normalizeBBO(data: HyperLiquidBBOData): NormalizedMessage {+ const bbo = data.bbo;++ if (!bbo) {+ throw new Error('No BBO data in message');+ }++ const bid = parseFloat(bbo.bid);+ const ask = parseFloat(bbo.ask);+ const mid = (bid + ask) / 2;++ return {+ provider: this.provider,+ channel: this.REVERSE_ALIAS_MAP['bbo'] || 'bbo', // Use generic 'ticker' channel name+ type: 'ticker',+ symbol: bbo.coin,+ timestamp: bbo.time,+ data: {+ coin: bbo.coin,+ symbol: bbo.coin,+ bid: bid,+ ask: ask,+ mid: mid,+ last: mid, // Use mid as last price approximation+ spread: ask - bid,+ time: bbo.time+ },+ raw: data+ };+ }++ /**+ * Normalize user fills+ */+ private normalizeUserFills(data: HyperLiquidUserFillsData): NormalizedMessage {+ return {+ provider: this.provider,+ channel: 'userFills',+ type: 'trade',+ timestamp: Date.now(),+ data: {+ user: data.user,+ isSnapshot: data.isSnapshot,+ fills: data.fills.map(fill => ({+ coin: fill.coin,+ price: parseFloat(fill.px),+ size: parseFloat(fill.sz),+ side: fill.side === 'A' ? 'sell' : 'buy',+ time: fill.time,+ closedPnl: parseFloat(fill.closedPnl),+ fee: parseFloat(fill.fee),+ orderId: fill.oid,+ tradeId: fill.tid,+ hash: fill.hash+ }))+ },+ raw: data+ };+ }++ /**+ * Normalize open orders+ */+ private normalizeOpenOrders(data: HyperLiquidOpenOrdersData): NormalizedMessage {+ return {+ provider: this.provider,+ channel: 'openOrders',+ type: 'status',+ timestamp: Date.now(),+ data: {+ user: data.user,+ orders: data.orders?.map(order => ({+ coin: order.coin,+ side: order.side === 'A' ? 'sell' : 'buy',+ price: parseFloat(order.limitPx),+ size: parseFloat(order.sz),+ origSize: parseFloat(order.origSz),+ orderId: order.oid,+ clientOrderId: order.cloid,+ timestamp: order.timestamp+ })) || []+ },+ raw: data+ };+ }++ /**+ * Normalize user fundings+ */+ private normalizeUserFundings(data: HyperLiquidUserFundingsData): NormalizedMessage {+ return {+ provider: this.provider,+ channel: 'userFundings',+ type: 'custom',+ timestamp: Date.now(),+ data: {+ user: data.user,+ isSnapshot: data.isSnapshot,+ fundings: data.fundings.map(funding => ({+ time: funding.time,+ coin: funding.coin,+ usdc: parseFloat(funding.usdc),+ szi: parseFloat(funding.szi),+ fundingRate: parseFloat(funding.fundingRate)+ }))+ },+ raw: data+ };+ }++ /**+ * Check if channel requires user address+ */+ private isUserSpecificChannel(channel: string): boolean {+ const userChannels = [+ 'userFills',+ 'openOrders',+ 'userFundings',+ 'clearinghouseState',+ 'userEvents',+ 'orderUpdates',+ 'userNonFundingLedgerUpdates',+ 'userTwapSliceFills',+ 'userTwapHistory',+ 'activeAssetData',+ 'twapStates',+ 'notification',+ 'webData2',+ 'webData3'+ ];++ return userChannels.includes(channel);+ }++ /**+ * Parse topic into channel and symbol+ */+ private parseTopic(topic: string): { channel: string; symbol?: string } {+ const parts = topic.split('.');++ if (parts.length === 1) {+ // Just channel, no symbol+ return { channel: parts[0] };+ } else {+ // channel.symbol format+ return {+ channel: parts[0],+ symbol: parts.slice(1).join('.')+ };+ }+ }++ /**+ * Build subscription key for tracking+ */+ private buildSubscriptionKey(subscription: any): string {+ const parts = [subscription.type];+ if (subscription.coin) parts.push(subscription.coin);+ if (subscription.user) parts.push(subscription.user);+ if (subscription.interval) parts.push(subscription.interval);+ return parts.join(':');+ }+}++/**+ * HyperLiquid WebSocket Usage Examples:+ *+ * All Mids (mid-prices for all coins):+ * subscribe('allMids')+ *+ * Level 2 Order Book (nSigFigs: 2-5):+ * subscribe('l2Book.BTC', { nSigFigs: 5 })+ * subscribe('l2Book.ETH', { nSigFigs: 5, mantissa: 1 })+ *+ * Trades:+ * subscribe('trades.BTC')+ *+ * Candles (intervals: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 8h, 12h, 1d, 3d, 1w, 1M):+ * subscribe('candle.BTC', { interval: '1m' })+ * subscribe('candle.ETH', { interval: '1h' })+ *+ * Best Bid/Offer:+ * subscribe('bbo.BTC')+ *+ * User Fills (requires api_key set to wallet address):+ * subscribe('userFills', { aggregateByTime: true })+ *+ * Open Orders (requires api_key set to wallet address):+ * subscribe('openOrders')+ */diff --git a/fincept-terminal-desktop/src/services/websocket/adapters/index.ts b/fincept-terminal-desktop/src/services/websocket/adapters/index.tsindex 8d3b94933..0c5ac000f 100644--- a/fincept-terminal-desktop/src/services/websocket/adapters/index.ts+++ b/fincept-terminal-desktop/src/services/websocket/adapters/index.ts@@ -4,6 +4,7 @@import { AdapterRegistry, IWebSocketAdapter } from '../types';import { BaseAdapter } from './BaseAdapter';import { KrakenAdapter } from './KrakenAdapter';+import { HyperLiquidAdapter } from './HyperLiquidAdapter';/*** Global registry of available WebSocket adapters@@ -11,6 +12,7 @@ import { KrakenAdapter } from './KrakenAdapter';*/export const adapters: AdapterRegistry = {kraken: KrakenAdapter,+ hyperliquid: HyperLiquidAdapter,// Add more adapters here:// fyers: FyersAdapter,// polygon: PolygonAdapter,@@ -48,3 +50,4 @@ export function createAdapter(provider: string): IWebSocketAdapter {// Export adapter classesexport { BaseAdapter } from './BaseAdapter';export { KrakenAdapter } from './KrakenAdapter';+export { HyperLiquidAdapter } from './HyperLiquidAdapter';diff --git a/fincept-terminal-desktop/src/types/hyperliquid.d.ts b/fincept-terminal-desktop/src/types/hyperliquid.d.tsnew file mode 100644index 000000000..d949a5127--- /dev/null+++ b/fincept-terminal-desktop/src/types/hyperliquid.d.ts@@ -0,0 +1,321 @@+// File: src/types/hyperliquid.d.ts+// HyperLiquid exchange TypeScript type definitions+// Documentation: https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api++/**+ * HyperLiquid WebSocket subscription types+ */+export type HyperLiquidSubscriptionType =+ | 'allMids'+ | 'notification'+ | 'webData2'+ | 'webData3'+ | 'candle'+ | 'l2Book'+ | 'trades'+ | 'orderUpdates'+ | 'userEvents'+ | 'userFills'+ | 'userFundings'+ | 'userNonFundingLedgerUpdates'+ | 'userTwapSliceFills'+ | 'userTwapHistory'+ | 'activeAssetCtx'+ | 'activeAssetData'+ | 'twapStates'+ | 'clearinghouseState'+ | 'openOrders'+ | 'bbo';++/**+ * Candle intervals supported by HyperLiquid+ */+export type HyperLiquidCandleInterval =+ | '1m' | '3m' | '5m' | '15m' | '30m'+ | '1h' | '2h' | '4h' | '8h' | '12h'+ | '1d' | '3d' | '1w' | '1M';++/**+ * HyperLiquid WebSocket base message structure+ */+export interface HyperLiquidMessage {+ channel: string;+ data: any;+}++/**+ * HyperLiquid subscription request+ */+export interface HyperLiquidSubscriptionRequest {+ method: 'subscribe' | 'unsubscribe';+ subscription: {+ type: HyperLiquidSubscriptionType;+ coin?: string;+ user?: string;+ interval?: HyperLiquidCandleInterval;+ nSigFigs?: number; // 2-5 for l2Book+ mantissa?: 1 | 2 | 5; // Only with nSigFigs=5+ aggregateByTime?: boolean; // For userFills+ };+}++/**+ * HyperLiquid subscription response+ */+export interface HyperLiquidSubscriptionResponse {+ channel: 'subscriptionResponse';+ data: {+ method: 'subscribe' | 'unsubscribe';+ subscription: any;+ };+}++/**+ * All Mids (mid-price for all coins)+ */+export interface HyperLiquidAllMidsData {+ mids: Record<string, string>; // Coin -> mid price+}++/**+ * Level 2 Order Book+ */+export interface HyperLiquidL2BookLevel {+ px: string; // Price+ sz: string; // Size+ n: number; // Number of orders+}++export interface HyperLiquidL2BookData {+ coin: string;+ time: number;+ levels: [HyperLiquidL2BookLevel[], HyperLiquidL2BookLevel[]]; // [bids, asks]+}++/**+ * Trade data+ */+export interface HyperLiquidTrade {+ coin: string;+ side: 'A' | 'B'; // Ask (sell) or Bid (buy)+ px: string; // Price+ sz: string; // Size+ time: number; // Timestamp+ tid: number; // Trade ID+ hash?: string; // Transaction hash+}++export interface HyperLiquidTradesData {+ coin?: string;+ trades: HyperLiquidTrade[];+}++/**+ * Candle (OHLCV) data+ */+export interface HyperLiquidCandle {+ t: number; // Timestamp (open time)+ T: number; // Close timestamp+ s: string; // Symbol+ i: HyperLiquidCandleInterval; // Interval+ o: string; // Open+ c: string; // Close+ h: string; // High+ l: string; // Low+ v: string; // Volume+ n: number; // Number of trades+}++export interface HyperLiquidCandleData {+ candle?: HyperLiquidCandle;+}++/**+ * BBO (Best Bid Offer)+ */+export interface HyperLiquidBBO {+ coin: string;+ bid: string; // Best bid price+ ask: string; // Best ask price+ time: number; // Timestamp+}++export interface HyperLiquidBBOData {+ bbo?: HyperLiquidBBO;+}++/**+ * User Fills+ */+export interface HyperLiquidUserFill {+ coin: string;+ px: string; // Fill price+ sz: string; // Fill size+ side: 'A' | 'B'; // Ask or Bid+ time: number; // Timestamp+ startPosition: string;+ dir: string; // Direction+ closedPnl: string;+ hash: string;+ oid: number; // Order ID+ crossed: boolean;+ fee: string;+ tid: number; // Trade ID+ builderFee?: string;+}++export interface HyperLiquidUserFillsData {+ isSnapshot: boolean;+ user: string;+ fills: HyperLiquidUserFill[];+}++/**+ * Open Orders+ */+export interface HyperLiquidOpenOrder {+ coin: string;+ side: 'A' | 'B';+ limitPx: string;+ sz: string;+ oid: number;+ timestamp: number;+ origSz: string;+ cloid?: string; // Client order ID+}++export interface HyperLiquidOpenOrdersData {+ user?: string;+ orders?: HyperLiquidOpenOrder[];+}++/**+ * User Fundings+ */+export interface HyperLiquidUserFunding {+ time: number;+ coin: string;+ usdc: string;+ szi: string;+ fundingRate: string;+}++export interface HyperLiquidUserFundingsData {+ isSnapshot: boolean;+ user: string;+ fundings: HyperLiquidUserFunding[];+}++/**+ * Clearinghouse State (User Position State)+ */+export interface HyperLiquidAssetPosition {+ type: 'oneWay';+ position: {+ coin: string;+ szi: string; // Signed position size+ leverage: {+ type: 'cross' | 'isolated';+ value: number;+ rawUsd?: string;+ };+ entryPx: string | null;+ positionValue: string;+ unrealizedPnl: string;+ returnOnEquity: string;+ liquidationPx: string | null;+ marginUsed: string;+ maxTrade: string;+ cumFunding: {+ allTime: string;+ sinceOpen: string;+ sinceChange: string;+ };+ };+}++export interface HyperLiquidClearinghouseState {+ assetPositions: HyperLiquidAssetPosition[];+ crossMarginSummary: {+ accountValue: string;+ totalNtlPos: string;+ totalRawUsd: string;+ totalMarginUsed: string;+ withdrawable: string;+ };+ marginSummary: {+ accountValue: string;+ totalNtlPos: string;+ totalRawUsd: string;+ totalMarginUsed: string;+ };+ time: number;+}++/**+ * REST API Response Types+ */++export interface HyperLiquidCandleSnapshotRequest {+ type: 'candleSnapshot';+ req: {+ coin: string;+ interval: HyperLiquidCandleInterval;+ startTime: number; // Milliseconds+ endTime?: number; // Milliseconds+ };+}++export interface HyperLiquidAllMidsRequest {+ type: 'allMids';+ dex?: string; // Optional, defaults to first perp dex+}++export interface HyperLiquidL2BookSnapshotRequest {+ type: 'l2Book';+ coin: string;+ nSigFigs?: number; // 2-5+ mantissa?: 1 | 2 | 5;+}++export interface HyperLiquidUserStateRequest {+ type: 'clearinghouseState';+ user: string; // Wallet address+}++export interface HyperLiquidOpenOrdersRequest {+ type: 'openOrders';+ user: string;+ dex?: string;+}++export interface HyperLiquidUserFillsRequest {+ type: 'userFills';+ user: string;+ aggregateByTime?: boolean;+}++export interface HyperLiquidUserFillsByTimeRequest {+ type: 'userFillsByTime';+ user: string;+ startTime: number;+ endTime?: number;+}++/**+ * Meta info for available assets+ */+export interface HyperLiquidAssetInfo {+ name: string;+ szDecimals: number;+ maxLeverage: number;+ onlyIsolated: boolean;+}++export interface HyperLiquidMetaRequest {+ type: 'meta';+}++export interface HyperLiquidMetaResponse {+ universe: HyperLiquidAssetInfo[];+}diff --git a/fincept-terminal-desktop/src/types/trading.d.ts b/fincept-terminal-desktop/src/types/trading.d.tsnew file mode 100644index 000000000..f00fc3b65--- /dev/null+++ b/fincept-terminal-desktop/src/types/trading.d.ts@@ -0,0 +1,144 @@+// File: src/types/trading.d.ts+// Trading and paper trading type definitions++export interface VirtualPortfolio {+ id: string;+ name: string;+ provider: string;+ initialBalance: number;+ balance: number;+ totalPnL: number;+ positions: Position[];+ createdAt: string;+ updatedAt: string;+}++export interface Position {+ id: string;+ portfolioId: string;+ symbol: string;+ side: 'long' | 'short';+ entryPrice: number;+ quantity: number;+ currentPrice?: number;+ unrealizedPnL?: number;+ realizedPnL: number;+ openedAt: string;+ closedAt?: string;+ status: 'open' | 'closed';+}++export type OrderSide = 'buy' | 'sell';+export type OrderType = 'market' | 'limit' | 'stop_market' | 'stop_limit';+export type OrderStatus = 'pending' | 'filled' | 'partial' | 'cancelled' | 'rejected' | 'triggered';++export interface OrderRequest {+ symbol: string;+ side: OrderSide;+ type: OrderType;+ quantity: number;+ price?: number; // Required for limit and stop_limit+ stopPrice?: number; // Required for stop_market and stop_limit+}++export interface Order {+ id: string;+ portfolioId: string;+ symbol: string;+ side: OrderSide;+ type: OrderType;+ quantity: number;+ price?: number;+ stopPrice?: number;+ filledQuantity: number;+ avgFillPrice?: number;+ status: OrderStatus;+ createdAt: string;+ filledAt?: string;+}++export interface Trade {+ id: string;+ portfolioId: string;+ orderId: string;+ symbol: string;+ side: OrderSide;+ price: number;+ quantity: number;+ fee: number;+ timestamp: string;+}++export interface OrderResult {+ success: boolean;+ orderId?: string;+ error?: string;+}++export interface PaperTradingConfig {+ portfolioId: string;+ feeRate: number; // Default: 0.0002 (0.02%)+ slippage: number; // Default: 0.0001 (0.01%)+}++export interface MarketPrice {+ symbol: string;+ price: number;+ timestamp: number;+}++/**+ * Database row types (matching SQLite schema)+ */+export interface DbPortfolio {+ id: string;+ name: string;+ provider: string;+ initial_balance: number;+ current_balance: number;+ created_at: string;+ updated_at: string;+}++export interface DbPosition {+ id: string;+ portfolio_id: string;+ symbol: string;+ side: 'long' | 'short';+ entry_price: number;+ quantity: number;+ current_price: number | null;+ unrealized_pnl: number | null;+ realized_pnl: number;+ opened_at: string;+ closed_at: string | null;+ status: 'open' | 'closed';+}++export interface DbOrder {+ id: string;+ portfolio_id: string;+ symbol: string;+ side: OrderSide;+ type: OrderType;+ quantity: number;+ price: number | null;+ stop_price: number | null;+ filled_quantity: number;+ avg_fill_price: number | null;+ status: OrderStatus;+ created_at: string;+ filled_at: string | null;+}++export interface DbTrade {+ id: string;+ portfolio_id: string;+ order_id: string;+ symbol: string;+ side: OrderSide;+ price: number;+ quantity: number;+ fee: number;+ timestamp: string;+}diff --git a/fincept-terminal-desktop/vite.config.ts b/fincept-terminal-desktop/vite.config.tsindex 33f687f1f..6cd1485ff 100644--- a/fincept-terminal-desktop/vite.config.ts+++ b/fincept-terminal-desktop/vite.config.ts@@ -13,6 +13,21 @@ export default defineConfig({optimizeDeps: {exclude: ['@mapbox/node-pre-gyp', 'mock-aws-s3', 'aws-sdk', 'nock']},+ build: {+ rollupOptions: {+ output: {+ manualChunks: {+ // Split vendor chunks+ 'react-vendor': ['react', 'react-dom', 'react-router-dom'],+ 'chart-vendor': ['recharts', 'lightweight-charts'],+ 'ui-vendor': ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu', '@radix-ui/react-popover', '@radix-ui/react-tabs'],+ 'flow-vendor': ['reactflow'],+ 'tauri-vendor': ['@tauri-apps/api', '@tauri-apps/plugin-dialog', '@tauri-apps/plugin-sql'],+ }+ }+ },+ chunkSizeWarningLimit: 1000, // Increase limit to 1000kb to reduce warnings+ },clearScreen: false,server: {port: 1420,