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
tab updates and code refactor
tilakpatel229bfb46246c90
diff --git a/fincept-terminal-desktop/%temp%/llm-list-check/llm_list-0.1.0-py2.py3-none-any.whl b/fincept-terminal-desktop/%temp%/llm-list-check/llm_list-0.1.0-py2.py3-none-any.whlnew file mode 100644index 000000000..8883d8dc0Binary files /dev/null and b/fincept-terminal-desktop/%temp%/llm-list-check/llm_list-0.1.0-py2.py3-none-any.whl differdiff --git a/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txt b/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txtindex 483b700f9..2b00528b8 100644--- a/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txt+++ b/fincept-terminal-desktop/src-tauri/resources/requirements-numpy2.txt@@ -58,8 +58,8 @@ anthropic>=0.71.0,<1.0google-generativeai>=0.8.5,<1.0langchain>=0.1.0langchain-community>=0.0.1-litellm>=1.73tiktoken>=0.5.0+# Note: litellm removed - model data extracted to llm_models_data.json (240KB static file)# ML/DL (NumPy 2.x compatible)# PyTorch 2.3.1+ doesn't support macOS Intel, use 2.2.2 for compatibilitydiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/__init__.pyindex 6531b719d..797212d1e 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/__init__.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/__init__.py@@ -65,7 +65,62 @@ from finagent_core.modules.reasoning_module import ReasoningBuilderfrom finagent_core.agent_factory import AgentFactoryfrom finagent_core.config_loader import ConfigLoader-__version__ = "2.0.0"+# New modules (v2.1)+from finagent_core.agent_loader import (+ AgentLoader,+ AgentCard,+ AgentRegistry,+ get_loader,+ discover_agents,+ create_agent,+ list_agents,+ list_categories,+)+from finagent_core.super_agent import (+ SuperAgent,+ QueryIntent,+ RouteConfig,+ RoutingResult,+ IntentClassifier,+ route_query,+ execute_query,+)+from finagent_core.execution_planner import (+ ExecutionPlanner,+ ExecutionPlan,+ PlanStep,+ PlanBuilder,+ StepStatus,+ StepType,+ create_stock_analysis_plan,+ execute_plan,+)+from finagent_core.repositories import (+ Repository,+ AgentSession,+ AgentMemory,+ TradeDecision,+ PerformanceSnapshot,+ AgentSessionRepository,+ AgentMemoryRepository,+ TradeDecisionRepository,+ PerformanceSnapshotRepository,+ RepositoryFactory,+)+from finagent_core.paper_trading_bridge import (+ PaperTradingBridge,+ Portfolio,+ Order,+ Position,+ Trade,+ Stats,+ get_bridge,+ execute_trade,+ get_portfolio_value,+ get_positions_summary,+)++__version__ = "2.1.0"__all__ = [# Core@@ -96,6 +151,59 @@ __all__ = [# Legacy"AgentFactory","ConfigLoader",++ # Dynamic Agent Loading (v2.1)+ "AgentLoader",+ "AgentCard",+ "AgentRegistry",+ "get_loader",+ "discover_agents",+ "create_agent",+ "list_agents",+ "list_categories",++ # SuperAgent Routing (v2.1)+ "SuperAgent",+ "QueryIntent",+ "RouteConfig",+ "RoutingResult",+ "IntentClassifier",+ "route_query",+ "execute_query",++ # Execution Planner (v2.1)+ "ExecutionPlanner",+ "ExecutionPlan",+ "PlanStep",+ "PlanBuilder",+ "StepStatus",+ "StepType",+ "create_stock_analysis_plan",+ "execute_plan",++ # Repository Pattern (v2.1)+ "Repository",+ "AgentSession",+ "AgentMemory",+ "TradeDecision",+ "PerformanceSnapshot",+ "AgentSessionRepository",+ "AgentMemoryRepository",+ "TradeDecisionRepository",+ "PerformanceSnapshotRepository",+ "RepositoryFactory",++ # Paper Trading Bridge (v2.1)+ "PaperTradingBridge",+ "Portfolio",+ "Order",+ "Position",+ "Trade",+ "Stats",+ "get_bridge",+ "execute_trade",+ "get_portfolio_value",+ "get_positions_summary",]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/agent_loader.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/agent_loader.pynew file mode 100644index 000000000..7f93474fe--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/agent_loader.py@@ -0,0 +1,367 @@+"""+Dynamic Agent Loader - Load agents from configuration at runtime++Similar to ValueCell's _resolve_local_agent_class_sync pattern.+Enables runtime agent discovery and instantiation from JSON configs.+"""++import json+import importlib+import importlib.util+from pathlib import Path+from typing import Dict, Any, Optional, List, Type+from dataclasses import dataclass+import logging++logger = logging.getLogger(__name__)+++@dataclass+class AgentCard:+ """+ Agent metadata card (similar to ValueCell AgentCard)+ Defines agent capabilities and configuration.+ """+ id: str+ name: str+ description: str+ category: str+ version: str = "1.0.0"+ provider: str = "local"+ capabilities: List[str] = None+ config: Dict[str, Any] = None+ module_path: Optional[str] = None+ class_name: Optional[str] = None++ def __post_init__(self):+ if self.capabilities is None:+ self.capabilities = []+ if self.config is None:+ self.config = {}++ @classmethod+ def from_dict(cls, data: Dict[str, Any]) -> "AgentCard":+ return cls(+ id=data.get("id", data.get("name", "unknown")),+ name=data.get("name", "Unknown Agent"),+ description=data.get("description", ""),+ category=data.get("category", "general"),+ version=data.get("version", "1.0.0"),+ provider=data.get("provider", "local"),+ capabilities=data.get("capabilities", []),+ config=data.get("config", {}),+ module_path=data.get("module_path"),+ class_name=data.get("class_name")+ )++ def to_dict(self) -> Dict[str, Any]:+ return {+ "id": self.id,+ "name": self.name,+ "description": self.description,+ "category": self.category,+ "version": self.version,+ "provider": self.provider,+ "capabilities": self.capabilities,+ "config": self.config,+ "module_path": self.module_path,+ "class_name": self.class_name+ }+++class AgentRegistry:+ """+ Registry for dynamically loaded agents.+ Maintains a catalog of available agents and their configurations.+ """++ _instance = None++ def __new__(cls):+ if cls._instance is None:+ cls._instance = super().__new__(cls)+ cls._instance._agents: Dict[str, AgentCard] = {}+ cls._instance._loaded_classes: Dict[str, Type] = {}+ cls._instance._initialized = False+ return cls._instance++ def register(self, card: AgentCard) -> None:+ """Register an agent card"""+ self._agents[card.id] = card+ logger.info(f"Registered agent: {card.id} ({card.name})")++ def unregister(self, agent_id: str) -> bool:+ """Unregister an agent"""+ if agent_id in self._agents:+ del self._agents[agent_id]+ if agent_id in self._loaded_classes:+ del self._loaded_classes[agent_id]+ return True+ return False++ def get(self, agent_id: str) -> Optional[AgentCard]:+ """Get agent card by ID"""+ return self._agents.get(agent_id)++ def list_agents(self, category: Optional[str] = None) -> List[AgentCard]:+ """List all registered agents, optionally filtered by category"""+ agents = list(self._agents.values())+ if category:+ agents = [a for a in agents if a.category == category]+ return agents++ def list_categories(self) -> List[str]:+ """List all unique categories"""+ return list(set(a.category for a in self._agents.values()))++ def get_class(self, agent_id: str) -> Optional[Type]:+ """Get loaded class for agent"""+ return self._loaded_classes.get(agent_id)++ def set_class(self, agent_id: str, cls: Type) -> None:+ """Cache loaded class"""+ self._loaded_classes[agent_id] = cls++ def clear(self) -> None:+ """Clear all registrations"""+ self._agents.clear()+ self._loaded_classes.clear()+++class AgentLoader:+ """+ Dynamic agent loader - resolves and instantiates agents at runtime.++ Features:+ - Load agents from JSON config files+ - Discover agents from directory structure+ - Dynamic module loading+ - Agent instantiation with config injection+ """++ def __init__(self, config_dir: Optional[Path] = None, agents_dir: Optional[Path] = None):+ self.config_dir = config_dir or Path(__file__).parent / "configs"+ self.agents_dir = agents_dir or Path(__file__).parent.parent+ self.registry = AgentRegistry()++ # Ensure directories exist+ self.config_dir.mkdir(exist_ok=True)++ def discover_agents(self) -> List[AgentCard]:+ """+ Discover all available agents from config files and directory structure.+ Returns list of discovered agent cards.+ """+ discovered = []++ # 1. Load from JSON config files+ for config_file in self.config_dir.glob("*_agent.json"):+ try:+ card = self._load_agent_config(config_file)+ if card:+ self.registry.register(card)+ discovered.append(card)+ except Exception as e:+ logger.error(f"Failed to load config {config_file}: {e}")++ # 2. Auto-discover from directory structure+ for agent_file in self.agents_dir.rglob("*_agent.py"):+ if "__pycache__" in str(agent_file):+ continue+ try:+ card = self._discover_from_file(agent_file)+ if card and card.id not in [a.id for a in discovered]:+ self.registry.register(card)+ discovered.append(card)+ except Exception as e:+ logger.debug(f"Could not auto-discover {agent_file}: {e}")++ logger.info(f"Discovered {len(discovered)} agents")+ return discovered++ def _load_agent_config(self, config_file: Path) -> Optional[AgentCard]:+ """Load agent card from JSON config file"""+ with open(config_file, 'r', encoding='utf-8') as f:+ data = json.load(f)+ return AgentCard.from_dict(data)++ def _discover_from_file(self, agent_file: Path) -> Optional[AgentCard]:+ """Auto-discover agent from Python file structure"""+ # Extract agent name from filename+ name = agent_file.stem.replace("_agent", "").replace("_", " ").title()+ agent_id = agent_file.stem++ # Determine category from path+ parts = agent_file.relative_to(self.agents_dir).parts+ category = parts[0] if len(parts) > 1 else "general"++ # Find class name in file+ class_name = self._find_agent_class(agent_file)+ if not class_name:+ return None++ return AgentCard(+ id=agent_id,+ name=f"{name} Agent",+ description=f"Auto-discovered agent from {agent_file.name}",+ category=category,+ module_path=str(agent_file),+ class_name=class_name+ )++ def _find_agent_class(self, agent_file: Path) -> Optional[str]:+ """Find the main agent class in a Python file"""+ try:+ content = agent_file.read_text(encoding='utf-8')+ # Look for class definitions that end with Agent+ import re+ matches = re.findall(r'class\s+(\w+Agent)\s*[:\(]', content)+ if matches:+ return matches[0]+ except Exception:+ pass+ return None++ def load_agent_class(self, agent_id: str) -> Optional[Type]:+ """+ Dynamically load agent class.+ Similar to ValueCell's _resolve_local_agent_class_sync.+ """+ # Check cache first+ cached = self.registry.get_class(agent_id)+ if cached:+ return cached++ # Get agent card+ card = self.registry.get(agent_id)+ if not card or not card.module_path or not card.class_name:+ logger.warning(f"Agent {agent_id} not found or missing module info")+ return None++ try:+ # Load module dynamically+ module_path = Path(card.module_path)+ spec = importlib.util.spec_from_file_location(+ f"agent_{agent_id}",+ module_path+ )+ if spec and spec.loader:+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)++ # Get class from module+ agent_class = getattr(module, card.class_name, None)+ if agent_class:+ self.registry.set_class(agent_id, agent_class)+ logger.info(f"Loaded agent class: {card.class_name}")+ return agent_class+ except Exception as e:+ logger.error(f"Failed to load agent class {agent_id}: {e}")++ return None++ def create_agent(+ self,+ agent_id: str,+ api_keys: Optional[Dict[str, str]] = None,+ override_config: Optional[Dict[str, Any]] = None+ ) -> Any:+ """+ Create agent instance from registered agent.++ Args:+ agent_id: ID of the registered agent+ api_keys: API keys to inject+ override_config: Config overrides++ Returns:+ Instantiated agent+ """+ card = self.registry.get(agent_id)+ if not card:+ raise ValueError(f"Agent not found: {agent_id}")++ # Merge configs+ config = {**card.config}+ if override_config:+ config.update(override_config)+ if api_keys:+ config["api_keys"] = api_keys++ # Try to load and instantiate class+ agent_class = self.load_agent_class(agent_id)+ if agent_class:+ return agent_class(**config) if config else agent_class()++ # Fallback to CoreAgent with config+ from finagent_core.core_agent import CoreAgent+ agent = CoreAgent(api_keys=api_keys)+ return agent++ def create_from_config(+ self,+ config: Dict[str, Any],+ api_keys: Optional[Dict[str, str]] = None+ ) -> Any:+ """+ Create agent directly from config dict (no registration needed).++ Args:+ config: Agent configuration+ api_keys: API keys++ Returns:+ Instantiated agent+ """+ from finagent_core.core_agent import CoreAgent++ agent = CoreAgent(+ api_keys=api_keys,+ user_id=config.get("user_id")+ )+ return agent++ def save_agent_config(self, card: AgentCard) -> Path:+ """Save agent card to config file"""+ config_file = self.config_dir / f"{card.id}_agent.json"+ with open(config_file, 'w', encoding='utf-8') as f:+ json.dump(card.to_dict(), f, indent=2)+ return config_file+++# Singleton instance+_loader: Optional[AgentLoader] = None+++def get_loader() -> AgentLoader:+ """Get singleton AgentLoader instance"""+ global _loader+ if _loader is None:+ _loader = AgentLoader()+ return _loader+++def discover_agents() -> List[Dict[str, Any]]:+ """Discover and return all available agents as dicts"""+ loader = get_loader()+ agents = loader.discover_agents()+ return [a.to_dict() for a in agents]+++def create_agent(agent_id: str, api_keys: Dict[str, str] = None, config: Dict[str, Any] = None) -> Any:+ """Create agent instance"""+ loader = get_loader()+ return loader.create_agent(agent_id, api_keys, config)+++def list_agents(category: str = None) -> List[Dict[str, Any]]:+ """List registered agents"""+ loader = get_loader()+ agents = loader.registry.list_agents(category)+ return [a.to_dict() for a in agents]+++def list_categories() -> List[str]:+ """List all agent categories"""+ loader = get_loader()+ return loader.registry.list_categories()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/analysis_agent.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/analysis_agent.jsonnew file mode 100644index 000000000..0cbc812f7--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/analysis_agent.json@@ -0,0 +1,26 @@+{+ "id": "analysis_agent",+ "name": "Financial Analysis Agent",+ "description": "AI agent specialized in stock valuation and analysis",+ "category": "analysis",+ "version": "1.0.0",+ "provider": "local",+ "capabilities": [+ "fundamental_analysis",+ "technical_analysis",+ "valuation_models",+ "research"+ ],+ "config": {+ "model": {+ "provider": "openai",+ "model_id": "gpt-4-turbo",+ "temperature": 0.5,+ "max_tokens": 4096+ },+ "instructions": "You are a financial analysis agent. Your role is to:\n1. Perform fundamental analysis (P/E, EPS, revenue growth)\n2. Conduct technical analysis (trends, patterns, indicators)\n3. Build valuation models (DCF, comparables)\n4. Research industry and competitive dynamics\n5. Synthesize findings into actionable insights\n\nStructure your analysis with:\n- Executive Summary\n- Key Metrics\n- Valuation Assessment\n- Technical Outlook\n- Risk Factors\n- Investment Thesis\n- Price Target (if applicable)",+ "tools": ["yfinance", "duckduckgo", "calculator"],+ "output_format": "markdown",+ "reasoning": true+ }+}diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/portfolio_agent.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/portfolio_agent.jsonnew file mode 100644index 000000000..216205e25--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/portfolio_agent.json@@ -0,0 +1,26 @@+{+ "id": "portfolio_agent",+ "name": "Portfolio Management Agent",+ "description": "AI agent specialized in portfolio analysis and rebalancing",+ "category": "portfolio",+ "version": "1.0.0",+ "provider": "local",+ "capabilities": [+ "portfolio_analysis",+ "asset_allocation",+ "rebalancing",+ "diversification"+ ],+ "config": {+ "model": {+ "provider": "openai",+ "model_id": "gpt-4-turbo",+ "temperature": 0.4,+ "max_tokens": 4096+ },+ "instructions": "You are a portfolio management agent. Your role is to:\n1. Analyze portfolio composition and allocation\n2. Identify concentration risks and diversification opportunities\n3. Suggest rebalancing trades to meet target allocations\n4. Calculate optimal position weights\n5. Assess portfolio risk metrics\n\nProvide structured analysis with:\n- Current allocation breakdown\n- Risk assessment\n- Recommended changes\n- Expected impact on risk/return",+ "tools": ["yfinance", "calculator"],+ "output_format": "markdown",+ "reasoning": true+ }+}diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/trading_agent.json b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/trading_agent.jsonnew file mode 100644index 000000000..e3f53a8ea--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/configs/trading_agent.json@@ -0,0 +1,25 @@+{+ "id": "trading_agent",+ "name": "Trading Agent",+ "description": "AI agent specialized in trading decisions and order execution",+ "category": "trading",+ "version": "1.0.0",+ "provider": "local",+ "capabilities": [+ "market_orders",+ "limit_orders",+ "position_sizing",+ "entry_exit_signals"+ ],+ "config": {+ "model": {+ "provider": "openai",+ "model_id": "gpt-4-turbo",+ "temperature": 0.3,+ "max_tokens": 2048+ },+ "instructions": "You are a trading agent specializing in execution and order management. Your role is to:\n1. Analyze market conditions for optimal entry/exit\n2. Calculate position sizes based on risk parameters\n3. Generate clear buy/sell signals with reasoning\n4. Manage open positions and suggest adjustments\n\nAlways provide structured responses with:\n- Signal (BUY/SELL/HOLD)\n- Confidence (0-100%)\n- Entry/Exit price\n- Stop loss\n- Take profit\n- Position size recommendation\n- Brief reasoning",+ "tools": ["yfinance", "calculator"],+ "output_format": "markdown"+ }+}diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.pyindex 76d6fa94b..22ccb522f 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent.py@@ -6,9 +6,9 @@ Integrates all modules: Memory, Teams, Workflows, Knowledge, Reasoning,Guardrails, Evaluation, Tracing, Compression, Hooks, Structured Outputs."""-from typing import Dict, Any, Optional, List, Union+from typing import Dict, Any, Optional, Listimport logging-import time+import jsonlogger = logging.getLogger(__name__)@@ -39,13 +39,6 @@ class CoreAgent:api_keys: Optional[Dict[str, str]] = None,user_id: Optional[str] = None):- """- Initialize core agent.-- Args:- api_keys: API keys for LLM providers and services- user_id: User ID for user-specific features- """self.api_keys = api_keys or {}self.user_id = user_idself._agent = None@@ -60,6 +53,10 @@ class CoreAgent:self._hooks = Noneself._agentic_memory = None+ # ============================================================+ # Core Execution Methods+ # ============================================================+def run(self,query: str,@@ -67,189 +64,18 @@ class CoreAgent:session_id: Optional[str] = None,stream: bool = False) -> Any:- """- Execute agent with given configuration.-- Args:- query: User query (passed as 'input' to Agno Agent)- config: Agent configuration (model, tools, instructions, etc.)- session_id: Session ID for memory- stream: Stream response-- Returns:- Agent response-- Example:- >>> agent = CoreAgent(api_keys={"OPENAI_API_KEY": "..."})- >>> config = {- ... "model": {"provider": "openai", "model_id": "gpt-4-turbo"},- ... "instructions": "You are a helpful assistant",- ... "tools": ["yfinance", "calculator"],- ... "memory": {"enabled": True},- ... "reasoning": {"strategy": "chain_of_thought"}- ... }- >>> response = agent.run("Analyze AAPL", config)- """- # Create or update agent if config changed+ """Execute agent with given configuration."""if self._should_recreate_agent(config):self._agent = self._create_agent(config)self._current_config = config- # Execute - Agno uses 'input' not 'query'run_kwargs = {"input": query}if session_id:run_kwargs["session_id"] = session_idif stream:run_kwargs["stream"] = stream- response = self._agent.run(**run_kwargs)-- return response-- def _should_recreate_agent(self, config: Dict[str, Any]) -> bool:- """Check if agent needs to be recreated"""- if self._agent is None:- return True-- if self._current_config is None:- return True-- # Compare critical config elements- critical_keys = ["model", "instructions", "tools", "knowledge", "reasoning"]- for key in critical_keys:- if self._current_config.get(key) != config.get(key):- return True-- return False-- def _create_agent(self, config: Dict[str, Any]) -> Any:- """Create Agno agent from config with all modules"""- from agno.agent import Agent- from finagent_core.registries import ModelsRegistry, ToolsRegistry-- # Create model- model_config = config.get("model", {})- model = ModelsRegistry.create_model(- provider=model_config.get("provider", "openai"),- model_id=model_config.get("model_id"),- api_keys=self.api_keys,- temperature=model_config.get("temperature"),- max_tokens=model_config.get("max_tokens"),- )-- # Build agent kwargs- agent_kwargs = {- "model": model,- }-- # Optional name- if config.get("name"):- agent_kwargs["name"] = config["name"]-- # Add instructions (with optional reasoning enhancement)- instructions = config.get("instructions", "You are a helpful AI assistant.")- if config.get("reasoning"):- instructions = self._enhance_with_reasoning(instructions, config["reasoning"])- agent_kwargs["instructions"] = instructions-- # Add tools- tool_names = config.get("tools", [])- if tool_names:- tools = ToolsRegistry.get_tools(tool_names)- if tools:- agent_kwargs["tools"] = tools-- # Add knowledge base- if config.get("knowledge"):- knowledge_config = self._setup_knowledge(config["knowledge"])- agent_kwargs.update(knowledge_config)-- # Add reasoning (Agno has built-in reasoning support)- if config.get("reasoning"):- reasoning_config = config.get("reasoning", {})- if isinstance(reasoning_config, bool):- agent_kwargs["reasoning"] = True- else:- agent_kwargs["reasoning"] = True- if reasoning_config.get("max_steps"):- agent_kwargs["reasoning_max_steps"] = reasoning_config["max_steps"]- if reasoning_config.get("min_steps"):- agent_kwargs["reasoning_min_steps"] = reasoning_config["min_steps"]-- # Optional: markdown output- if config.get("output_format") == "markdown":- agent_kwargs["markdown"] = True-- # Optional: debug mode- if config.get("debug"):- agent_kwargs["debug_mode"] = True-- # Session-related settings- if config.get("enable_session_summaries"):- agent_kwargs["enable_session_summaries"] = True- if config.get("add_history_to_context"):- agent_kwargs["add_history_to_context"] = True-- return Agent(**agent_kwargs)-- def _setup_memory(self, memory_config: Dict[str, Any]) -> Dict[str, Any]:- """Setup memory module"""- from finagent_core.modules import MemoryModule-- if isinstance(memory_config, bool):- memory_config = {"enabled": memory_config}-- if not memory_config.get("enabled", True):- return {}-- module = MemoryModule.from_config(memory_config)- self._modules["memory"] = module-- return module.to_agent_config()-- def _setup_knowledge(self, knowledge_config: Dict[str, Any]) -> Dict[str, Any]:- """Setup knowledge module"""- from finagent_core.modules import KnowledgeModule-- module = KnowledgeModule.from_config({- **knowledge_config,- "api_keys": self.api_keys- })- self._modules["knowledge"] = module-- return module.to_agent_config()-- def _setup_reasoning(self, reasoning_config: Dict[str, Any]) -> Dict[str, Any]:- """Setup reasoning module"""- from finagent_core.modules import ReasoningModule-- if isinstance(reasoning_config, bool):- reasoning_config = {"strategy": "chain_of_thought"}-- module = ReasoningModule.from_config(reasoning_config)- self._modules["reasoning"] = module-- return module.to_agent_config()-- def _enhance_with_reasoning(- self,- instructions: str,- reasoning_config: Dict[str, Any]- ) -> str:- """Enhance instructions with reasoning prompt"""- from finagent_core.modules import ReasoningModule-- if isinstance(reasoning_config, bool):- reasoning_config = {"strategy": "chain_of_thought"}-- module = ReasoningModule.from_config(reasoning_config)- return module.enhance_instructions(instructions)-- def get_response_content(self, response) -> str:- """Extract text content from response"""- if hasattr(response, 'content'):- return response.content- return str(response)+ return self._agent.run(**run_kwargs)def run_team(self,@@ -257,26 +83,14 @@ class CoreAgent:team_config: Dict[str, Any],session_id: Optional[str] = None) -> Any:- """- Execute a multi-agent team.-- Args:- query: User query- team_config: Team configuration with agent configs- session_id: Session ID-- Returns:- Team response- """+ """Execute a multi-agent team."""from finagent_core.modules import TeamModule- # Create agents for the teamagents = []- for agent_config in team_config.get("agents", []):+ for agent_config in team_config.get("agents", team_config.get("members", [])):agent = self._create_agent(agent_config)agents.append(agent)- # Create and run teamteam_module = TeamModule.from_config(team_config, agents)return team_module.run(query, session_id=session_id)@@ -285,19 +99,9 @@ class CoreAgent:workflow_config: Dict[str, Any],input_data: Optional[Dict[str, Any]] = None) -> Any:- """- Execute a workflow.-- Args:- workflow_config: Workflow configuration- input_data: Initial input data-- Returns:- Workflow result- """+ """Execute a workflow."""from finagent_core.modules import WorkflowModule- # Create agents for workflow steps if neededfor step in workflow_config.get("steps", []):if step.get("agent_config"):step["agent"] = self._create_agent(step["agent_config"])@@ -305,61 +109,121 @@ class CoreAgent:workflow_module = WorkflowModule.from_config(workflow_config)return workflow_module.run(input_data)- def search_knowledge(+ def run_with_output_model(self,query: str,- limit: int = 5- ) -> List[Dict[str, Any]]:- """- Search the knowledge base.-- Args:- query: Search query- limit: Max results-- Returns:- Search results- """+ config: Dict[str, Any],+ output_model: str,+ session_id: Optional[str] = None+ ) -> Dict[str, Any]:+ """Run agent with structured output model."""+ from finagent_core.modules import OutputModelRegistry, OutputValidator++ model_class = OutputModelRegistry.get_model(output_model)+ if not model_class:+ return {"success": False, "error": f"Unknown output model: {output_model}"}++ config = config.copy()+ config["output_model"] = model_class+ config["structured_outputs"] = True++ response = self.run(query, config, session_id)+ content = self.get_response_content(response)++ try:+ data = json.loads(content) if isinstance(content, str) else content+ validation = OutputValidator.validate(data, output_model)+ return {+ "success": True,+ "model": output_model,+ "data": validation.get("data", data),+ "valid": validation.get("valid", True)+ }+ except Exception as e:+ return {+ "success": False,+ "model": output_model,+ "raw_response": content,+ "error": str(e)+ }++ # ============================================================+ # Financial Workflows+ # ============================================================++ def run_stock_analysis(self, symbol: str, config: Dict[str, Any] = None) -> Dict[str, Any]:+ """Run stock analysis workflow."""+ from finagent_core.modules import FinancialWorkflowTemplates++ config = config or {+ "model": {"provider": "openai", "model_id": "gpt-4-turbo"},+ "instructions": "You are a financial analyst"+ }+ agent = self._create_agent(config)+ workflow = FinancialWorkflowTemplates.stock_analysis_pipeline(+ fetch_agent=agent, analysis_agent=agent, report_agent=agent+ )+ return workflow.run({"symbol": symbol})++ def run_portfolio_rebalancing(self, portfolio_data: Dict[str, Any], config: Dict[str, Any] = None) -> Dict[str, Any]:+ """Run portfolio rebalancing workflow."""+ from finagent_core.modules import FinancialWorkflowTemplates++ config = config or {+ "model": {"provider": "openai", "model_id": "gpt-4-turbo"},+ "instructions": "You are a portfolio manager"+ }+ agent = self._create_agent(config)+ workflow = FinancialWorkflowTemplates.portfolio_rebalancing(+ analysis_agent=agent, optimization_agent=agent, execution_agent=agent+ )+ return workflow.run(portfolio_data)++ def run_risk_assessment(self, portfolio_data: Dict[str, Any], config: Dict[str, Any] = None) -> Dict[str, Any]:+ """Run risk assessment workflow."""+ from finagent_core.modules import FinancialWorkflowTemplates++ config = config or {+ "model": {"provider": "openai", "model_id": "gpt-4-turbo"},+ "instructions": "You are a risk analyst"+ }+ agent = self._create_agent(config)+ workflow = FinancialWorkflowTemplates.risk_assessment(+ risk_agent=agent, market_agent=agent+ )+ return workflow.run(portfolio_data)++ # ============================================================+ # Knowledge & Memory+ # ============================================================++ def search_knowledge(self, query: str, limit: int = 5) -> List[Dict[str, Any]]:+ """Search the knowledge base."""knowledge_module = self._modules.get("knowledge")if knowledge_module:return knowledge_module.search(query, limit=limit)return []- def get_module(self, name: str) -> Optional[Any]:- """Get a specific module instance"""- return self._modules.get(name)-- def list_available_tools(self) -> Dict[str, List[str]]:- """List all available tools by category"""- from finagent_core.registries import ToolsRegistry- return ToolsRegistry.list_tools()+ def store_memory(self, content: str, memory_type: str = "fact", metadata: Dict[str, Any] = None) -> int:+ """Store a memory."""+ if not self._agentic_memory:+ self.setup_agentic_memory()+ return self._agentic_memory.store(content, memory_type, metadata)- def list_available_models(self) -> List[str]:- """List all available model providers"""- from finagent_core.registries import ModelsRegistry- return ModelsRegistry.list_providers()+ def recall_memories(self, query: str = None, memory_type: str = None, limit: int = 5) -> List[Dict[str, Any]]:+ """Recall memories."""+ if not self._agentic_memory:+ return []+ return self._agentic_memory.recall(query, memory_type, limit)# ============================================================# Guardrails# ============================================================def setup_guardrails(self, config: Dict[str, Any] = None) -> "CoreAgent":- """- Setup guardrails for input/output validation.-- Args:- config: Guardrails configuration-- Returns:- self for chaining- """+ """Setup guardrails for input/output validation."""from finagent_core.modules import GuardrailsModule-- if config:- self._guardrails = GuardrailsModule.from_config(config)- else:- self._guardrails = GuardrailsModule.default_financial()-+ self._guardrails = GuardrailsModule.from_config(config) if config else GuardrailsModule.default_financial()self._modules["guardrails"] = self._guardrailsreturn self@@ -380,75 +244,34 @@ class CoreAgent:# ============================================================def setup_evaluation(self, config: Dict[str, Any] = None) -> "CoreAgent":- """- Setup evaluation module for quality assessment.-- Args:- config: Evaluation configuration-- Returns:- self for chaining- """+ """Setup evaluation module."""from finagent_core.modules import EvaluationModule-- if config:- self._evaluation = EvaluationModule.from_config(config)- else:- self._evaluation = EvaluationModule()-+ self._evaluation = EvaluationModule.from_config(config) if config else EvaluationModule()self._modules["evaluation"] = self._evaluationreturn self- def evaluate_prediction(- self,- prediction: Dict[str, Any],- actual: Dict[str, Any]- ) -> Dict[str, Any]:+ def evaluate_prediction(self, prediction: Dict[str, Any], actual: Dict[str, Any]) -> Dict[str, Any]:"""Evaluate prediction accuracy."""if not self._evaluation:self.setup_evaluation()result = self._evaluation.evaluate_prediction(prediction, actual)return {"passed": result.passed, "score": result.score, "details": result.details}- def evaluate_response(- self,- query: str,- response: str,- context: Dict[str, Any] = None- ) -> Dict[str, Any]:+ def evaluate_response(self, query: str, response: str, context: Dict[str, Any] = None) -> Dict[str, Any]:"""Evaluate response quality with agent-as-judge."""if not self._evaluation:self.setup_evaluation()result = self._evaluation.evaluate_with_judge(query, response, context)return {"passed": result.passed, "score": result.score, "details": result.details}- def get_evaluation_summary(self) -> Dict[str, Any]:- """Get evaluation summary."""- if not self._evaluation:- return {"message": "Evaluation not setup"}- return self._evaluation.get_summary()-# ============================================================# Tracing# ============================================================def setup_tracing(self, config: Dict[str, Any] = None) -> "CoreAgent":- """- Setup tracing for debugging and monitoring.-- Args:- config: Tracing configuration-- Returns:- self for chaining- """+ """Setup tracing for debugging and monitoring."""from finagent_core.modules import TracingModule-- if config:- self._tracing = TracingModule.from_config(config)- else:- self._tracing = TracingModule()-+ self._tracing = TracingModule.from_config(config) if config else TracingModule()self._modules["tracing"] = self._tracingreturn self@@ -464,39 +287,14 @@ class CoreAgent:return self._tracing.end_trace()return None- def get_traces(self, limit: int = 100) -> List[Dict[str, Any]]:- """Get recent traces."""- if not self._tracing:- return []- return self._tracing.get_traces(limit)-- def get_performance_summary(self) -> Dict[str, Any]:- """Get performance summary from traces."""- if not self._tracing:- return {"message": "Tracing not setup"}- return self._tracing.get_performance_summary()-# ============================================================- # Compression+ # Compression & Hooks# ============================================================def setup_compression(self, config: Dict[str, Any] = None) -> "CoreAgent":- """- Setup compression for token optimization.-- Args:- config: Compression configuration-- Returns:- self for chaining- """+ """Setup compression for token optimization."""from finagent_core.modules import CompressionModule-- if config:- self._compression = CompressionModule.from_config(config)- else:- self._compression = CompressionModule.for_financial_data()-+ self._compression = CompressionModule.from_config(config) if config else CompressionModule.for_financial_data()self._modules["compression"] = self._compressionreturn self@@ -506,464 +304,171 @@ class CoreAgent:self.setup_compression()return self._compression.compress(data)- # ============================================================- # Hooks- # ============================================================-def setup_hooks(self, config: Dict[str, Any] = None) -> "CoreAgent":- """- Setup hooks for pre/post processing.-- Args:- config: Hooks configuration-- Returns:- self for chaining- """+ """Setup hooks for pre/post processing."""from finagent_core.modules import HooksModule-- if config:- self._hooks = HooksModule.from_config(config)- else:- self._hooks = HooksModule.default_financial()-+ self._hooks = HooksModule.from_config(config) if config else HooksModule.default_financial()self._modules["hooks"] = self._hooksreturn self- def run_pre_hooks(self, data: Any, context: Dict[str, Any] = None) -> Dict[str, Any]:- """Run pre-execution hooks."""- if not self._hooks:- return {"success": True, "data": data}- result = self._hooks.run_pre_hooks(data, context)- return {"success": result.success, "data": result.data, "error": result.error}-- def run_post_hooks(self, data: Any, context: Dict[str, Any] = None) -> Dict[str, Any]:- """Run post-execution hooks."""- if not self._hooks:- return {"success": True, "data": data}- result = self._hooks.run_post_hooks(data, context)- return {"success": result.success, "data": result.data, "error": result.error}-- # ============================================================- # Agentic Memory- # ============================================================-def setup_agentic_memory(self, config: Dict[str, Any] = None) -> "CoreAgent":- """- Setup agentic memory for autonomous memory management.-- Args:- config: Memory configuration-- Returns:- self for chaining- """+ """Setup agentic memory."""from finagent_core.modules import AgenticMemoryModule-- user_id = config.get("user_id") if config else self.user_id- if not user_id:- user_id = "default"-- if config:- self._agentic_memory = AgenticMemoryModule.from_config({- "user_id": user_id,- **config- })- else:- self._agentic_memory = AgenticMemoryModule(user_id=user_id)-+ user_id = config.get("user_id") if config else self.user_id or "default"+ self._agentic_memory = AgenticMemoryModule.from_config({"user_id": user_id, **(config or {})})self._modules["agentic_memory"] = self._agentic_memoryreturn self- def store_memory(- self,- content: str,- memory_type: str = "fact",- metadata: Dict[str, Any] = None- ) -> int:- """Store a memory."""- if not self._agentic_memory:- self.setup_agentic_memory()- return self._agentic_memory.store(content, memory_type, metadata)-- def recall_memories(- self,- query: str = None,- memory_type: str = None,- limit: int = 5- ) -> List[Dict[str, Any]]:- """Recall memories."""- if not self._agentic_memory:- return []- return self._agentic_memory.recall(query, memory_type, limit)-- def get_memory_context(self, query: str, limit: int = 3) -> str:- """Get relevant memory context for a query."""- if not self._agentic_memory:- return ""- return self._agentic_memory.get_context_for_query(query, limit)-# ============================================================- # Structured Outputs+ # Listings# ============================================================- def run_with_output_model(- self,- query: str,- config: Dict[str, Any],- output_model: str,- session_id: Optional[str] = None- ) -> Dict[str, Any]:- """- Run agent with structured output model.-- Args:- query: User query- config: Agent configuration- output_model: Name of output model (e.g., "trade_signal", "stock_analysis")- session_id: Session ID-- Returns:- Structured response matching the model- """- from finagent_core.modules import OutputModelRegistry-- model_class = OutputModelRegistry.get_model(output_model)- if not model_class:- return {"error": f"Unknown output model: {output_model}"}-- # Add output model to config- config = config.copy()- config["output_model"] = model_class- config["structured_outputs"] = True-- # Run agent- response = self.run(query, config, session_id)- content = self.get_response_content(response)-- # Validate output- try:- import json- data = json.loads(content) if isinstance(content, str) else content-- from finagent_core.modules import OutputValidator- validation = OutputValidator.validate(data, output_model)-- return {- "success": True,- "model": output_model,- "data": validation.get("data", data),- "valid": validation.get("valid", True)- }+ def list_available_tools(self) -> Dict[str, List[str]]:+ """List all available tools by category."""+ from finagent_core.registries import ToolsRegistry+ return ToolsRegistry.list_tools()- except Exception as e:- return {- "success": False,- "model": output_model,- "raw_response": content,- "error": str(e)- }+ def list_available_models(self) -> List[str]:+ """List all available model providers."""+ from finagent_core.registries import ModelsRegistry+ return ModelsRegistry.list_providers()def list_output_models(self) -> List[str]:"""List available output models."""from finagent_core.modules import OutputModelRegistryreturn OutputModelRegistry.list_models()- # ============================================================- # Financial Workflows- # ============================================================-- def run_stock_analysis(- self,- symbol: str,- config: Dict[str, Any] = None- ) -> Dict[str, Any]:- """- Run stock analysis workflow.-- Args:- symbol: Stock symbol- config: Optional configuration-- Returns:- Analysis results- """- from finagent_core.modules import FinancialWorkflowTemplates-- config = config or {- "model": {"provider": "openai", "model_id": "gpt-4-turbo"},- "instructions": "You are a financial analyst"- }-- agent = self._create_agent(config)- workflow = FinancialWorkflowTemplates.stock_analysis_pipeline(- fetch_agent=agent,- analysis_agent=agent,- report_agent=agent- )-- return workflow.run({"symbol": symbol})-- def run_portfolio_rebalancing(- self,- portfolio_data: Dict[str, Any],- config: Dict[str, Any] = None- ) -> Dict[str, Any]:- """- Run portfolio rebalancing workflow.-- Args:- portfolio_data: Current portfolio- config: Optional configuration-- Returns:- Rebalancing recommendations- """- from finagent_core.modules import FinancialWorkflowTemplates-- config = config or {- "model": {"provider": "openai", "model_id": "gpt-4-turbo"},- "instructions": "You are a portfolio manager"- }-- agent = self._create_agent(config)- workflow = FinancialWorkflowTemplates.portfolio_rebalancing(- analysis_agent=agent,- optimization_agent=agent,- execution_agent=agent- )-- return workflow.run(portfolio_data)-- def run_risk_assessment(- self,- portfolio_data: Dict[str, Any],- config: Dict[str, Any] = None- ) -> Dict[str, Any]:- """- Run risk assessment workflow.-- Args:- portfolio_data: Portfolio to assess- config: Optional configuration-- Returns:- Risk assessment results- """- from finagent_core.modules import FinancialWorkflowTemplates-- config = config or {- "model": {"provider": "openai", "model_id": "gpt-4-turbo"},- "instructions": "You are a risk analyst"- }-- agent = self._create_agent(config)- workflow = FinancialWorkflowTemplates.risk_assessment(- risk_agent=agent,- market_agent=agent- )-- return workflow.run(portfolio_data)-- # ============================================================- # System Info- # ============================================================-def get_system_info(self) -> Dict[str, Any]:"""Get comprehensive system information."""+ from finagent_core.registries import ModelsRegistry, ToolsRegistry, VectorDBRegistry, EmbedderRegistryfrom finagent_core.modules import OutputModelRegistry+ tools = self.list_available_tools()return {+ "success": True,"version": "2.0.0","framework": "agno",- "api_keys_configured": list(self.api_keys.keys()),- "user_id": self.user_id,- "modules_initialized": list(self._modules.keys()),- "available_tools": len(self.list_available_tools()),- "available_models": self.list_available_models(),- "output_models": self.list_output_models(),- "features": {- "guardrails": self._guardrails is not None,- "evaluation": self._evaluation is not None,- "tracing": self._tracing is not None,- "compression": self._compression is not None,- "hooks": self._hooks is not None,- "agentic_memory": self._agentic_memory is not None- }+ "capabilities": {+ "model_providers": len(ModelsRegistry.list_providers()),+ "tools": sum(len(v) for v in tools.values()),+ "tool_categories": list(tools.keys()),+ "vectordbs": VectorDBRegistry.list_vectordbs(),+ "embedders": EmbedderRegistry.list_providers(),+ "output_models": OutputModelRegistry.list_models()+ },+ "features": [+ "multi_agent_teams", "workflow_orchestration", "parallel_execution",+ "conditional_branching", "loop_execution", "dynamic_routing",+ "knowledge_base_rag", "memory_management", "agentic_memory",+ "reasoning_strategies", "session_management", "guardrails",+ "evaluation", "tracing", "compression", "hooks", "structured_outputs"+ ]}+ # ============================================================+ # Helper Methods+ # ============================================================-class CoreAgentBuilder:- """- Fluent builder for CoreAgent configuration.-- Example:- config = (CoreAgentBuilder()- .with_model("anthropic", "claude-sonnet-4-5")- .with_instructions("You are a financial analyst")- .with_tools(["yfinance", "calculator"])- .with_memory()- .with_reasoning("chain_of_thought")- .build())-- agent = CoreAgent(api_keys=keys)- response = agent.run("Analyze AAPL", config)- """-- def __init__(self):- self._config = {}-- def with_model(- self,- provider: str,- model_id: Optional[str] = None,- temperature: float = 0.7,- max_tokens: Optional[int] = None- ) -> "CoreAgentBuilder":- """Set model configuration"""- self._config["model"] = {- "provider": provider,- "model_id": model_id,- "temperature": temperature,- }- if max_tokens:- self._config["model"]["max_tokens"] = max_tokens- return self-- def with_name(self, name: str) -> "CoreAgentBuilder":- """Set agent name"""- self._config["name"] = name- return self+ def get_response_content(self, response) -> str:+ """Extract text content from response."""+ if hasattr(response, 'content'):+ return response.content+ return str(response)- def with_instructions(self, instructions: str) -> "CoreAgentBuilder":- """Set agent instructions"""- self._config["instructions"] = instructions- return self+ def get_module(self, name: str) -> Optional[Any]:+ """Get a specific module instance."""+ return self._modules.get(name)- def with_tools(self, tools: List[str]) -> "CoreAgentBuilder":- """Set tools to use"""- self._config["tools"] = tools- return self+ def _should_recreate_agent(self, config: Dict[str, Any]) -> bool:+ """Check if agent needs to be recreated."""+ if self._agent is None or self._current_config is None:+ return True+ for key in ["model", "instructions", "tools", "knowledge", "reasoning"]:+ if self._current_config.get(key) != config.get(key):+ return True+ return False- def with_memory(- self,- enabled: bool = True,- optimization_strategy: Optional[str] = None- ) -> "CoreAgentBuilder":- """Enable memory"""- self._config["memory"] = {- "enabled": enabled,- "optimization_strategy": optimization_strategy- }- return self+ def _create_agent(self, config: Dict[str, Any]) -> Any:+ """Create Agno agent from config."""+ from agno.agent import Agent+ from finagent_core.registries import ModelsRegistry, ToolsRegistry- def with_knowledge(- self,- embedder_provider: str = "openai",- vectordb_type: str = "lancedb",- **kwargs- ) -> "CoreAgentBuilder":- """Configure knowledge base"""- self._config["knowledge"] = {- "embedder": {"provider": embedder_provider},- "vectordb": {"type": vectordb_type},- **kwargs- }- return self+ model_config = config.get("model", {})+ model = ModelsRegistry.create_model(+ provider=model_config.get("provider", "openai"),+ model_id=model_config.get("model_id"),+ api_keys=self.api_keys,+ temperature=model_config.get("temperature"),+ max_tokens=model_config.get("max_tokens"),+ )- def with_reasoning(- self,- strategy: str = "chain_of_thought",- max_steps: int = 10- ) -> "CoreAgentBuilder":- """Configure reasoning"""- self._config["reasoning"] = {- "strategy": strategy,- "max_steps": max_steps- }- return self+ agent_kwargs = {"model": model}- def with_markdown_output(self) -> "CoreAgentBuilder":- """Enable markdown output"""- self._config["output_format"] = "markdown"- return self+ if config.get("name"):+ agent_kwargs["name"] = config["name"]- def with_debug(self) -> "CoreAgentBuilder":- """Enable debug mode"""- self._config["debug"] = True- return self+ instructions = config.get("instructions", "You are a helpful AI assistant.")+ if config.get("reasoning"):+ instructions = self._enhance_with_reasoning(instructions, config["reasoning"])+ agent_kwargs["instructions"] = instructions- def with_guardrails(self, config: Dict[str, Any] = None) -> "CoreAgentBuilder":- """Enable guardrails"""- self._config["guardrails"] = config or {"enabled": True}- return self+ tool_names = config.get("tools", [])+ if tool_names:+ tools = ToolsRegistry.get_tools(tool_names)+ if tools:+ agent_kwargs["tools"] = tools- def with_evaluation(self, config: Dict[str, Any] = None) -> "CoreAgentBuilder":- """Enable evaluation"""- self._config["evaluation"] = config or {"enabled": True}- return self+ if config.get("knowledge"):+ agent_kwargs.update(self._setup_knowledge(config["knowledge"]))- def with_tracing(self, config: Dict[str, Any] = None) -> "CoreAgentBuilder":- """Enable tracing"""- self._config["tracing"] = config or {"enabled": True}- return self+ if config.get("reasoning"):+ agent_kwargs["reasoning"] = True- def with_compression(self, max_tokens: int = 2000) -> "CoreAgentBuilder":- """Enable compression"""- self._config["compression"] = {"max_tokens": max_tokens}- return self+ if config.get("output_format") == "markdown":+ agent_kwargs["markdown"] = True- def with_hooks(self, config: Dict[str, Any] = None) -> "CoreAgentBuilder":- """Enable hooks"""- self._config["hooks"] = config or {"enabled": True}- return self+ if config.get("debug"):+ agent_kwargs["debug_mode"] = True- def with_agentic_memory(self, user_id: str = None) -> "CoreAgentBuilder":- """Enable agentic memory"""- self._config["agentic_memory"] = {"user_id": user_id}- return self+ return Agent(**agent_kwargs)- def with_output_model(self, model_name: str) -> "CoreAgentBuilder":- """Set structured output model"""- self._config["output_model"] = model_name- return self+ def _setup_knowledge(self, knowledge_config: Dict[str, Any]) -> Dict[str, Any]:+ """Setup knowledge module."""+ from finagent_core.modules import KnowledgeModule+ module = KnowledgeModule.from_config({**knowledge_config, "api_keys": self.api_keys})+ self._modules["knowledge"] = module+ return module.to_agent_config()- def build(self) -> Dict[str, Any]:- """Build and return the configuration"""- return self._config.copy()+ def _enhance_with_reasoning(self, instructions: str, reasoning_config: Dict[str, Any]) -> str:+ """Enhance instructions with reasoning prompt."""+ from finagent_core.modules import ReasoningModule+ if isinstance(reasoning_config, bool):+ reasoning_config = {"strategy": "chain_of_thought"}+ module = ReasoningModule.from_config(reasoning_config)+ return module.enhance_instructions(instructions)# =============================================================================-# CLI Interface - Direct script execution (no separate CLI file needed)+# Entry Point - Single JSON Payload# =============================================================================def main(args=None):"""- CLI entry point - called directly by Rust/Tauri.-- Commands:- run <query_json> <config_json> <api_keys_json>- run_structured <query_json> <config_json> <api_keys_json>- run_team <query_json> <team_config_json> <api_keys_json>- run_workflow <workflow_config_json> <input_data_json> <api_keys_json>- stock_analysis <query_json> <config_json> <api_keys_json>- portfolio_rebal <portfolio_json> <config_json> <api_keys_json>- risk_assessment <portfolio_json> <config_json> <api_keys_json>- search <query_json> <config_json> <api_keys_json>- store_memory <memory_json> <config_json> <api_keys_json>- recall_memories <query_json> <config_json> <api_keys_json>- check_guardrails <input_json> <config_json> <api_keys_json>- evaluate <eval_json> <config_json> <api_keys_json>- list_tools- list_models- list_outputs- system_info+ Entry point - accepts single JSON payload from Rust/Tauri.++ Payload format:+ {+ "action": "run|run_team|run_workflow|...",+ "api_keys": {...},+ "user_id": "optional",+ "config": {...},+ "params": {...} // action-specific parameters+ }"""import sys- import jsonfrom pathlib import Path- # Add parent directory to path for imports (when called as script)+ # Add parent directory to path for importsparent_dir = str(Path(__file__).parent.parent)if parent_dir not in sys.path:sys.path.insert(0, parent_dir)@@ -973,88 +478,33 @@ def main(args=None):try:if len(args) == 0:- return json.dumps({- "success": False,- "error": "Usage: core_agent.py <command> [args...]"- })+ return json.dumps({"success": False, "error": "No payload provided"})- command = args[0]+ # Parse single JSON payload+ payload = json.loads(args[0])+ action = payload.get("action")+ api_keys = payload.get("api_keys", {})+ user_id = payload.get("user_id")+ config = payload.get("config", {})+ params = payload.get("params", {})- # Commands without JSON args- if command == "list_tools":- agent = CoreAgent()- tools = agent.list_available_tools()- return json.dumps({- "success": True,- "tools": tools,- "categories": list(tools.keys()),- "total_count": sum(len(v) for v in tools.values())- })-- if command == "list_models":- agent = CoreAgent()- providers = agent.list_available_models()- return json.dumps({- "success": True,- "providers": providers,- "count": len(providers)- })-- if command == "list_outputs":- agent = CoreAgent()- models = agent.list_output_models()- return json.dumps({- "success": True,- "models": models,- "count": len(models)- })+ if not action:+ return json.dumps({"success": False, "error": "Missing 'action' in payload"})- if command == "system_info":- return _get_system_info()+ # Create agent+ agent = CoreAgent(api_keys=api_keys, user_id=user_id)- # Legacy support - if first arg is JSON, assume "run" command- if command.startswith("{"):- command = "run"- else:- args = args[1:]+ # Setup optional modules from config+ if config.get("guardrails"):+ agent.setup_guardrails(config["guardrails"])+ if config.get("tracing"):+ agent.setup_tracing(config["tracing"])+ if config.get("agentic_memory"):+ agent.setup_agentic_memory(config["agentic_memory"])- # Commands with JSON args (require 3 args)- if len(args) < 3:- return json.dumps({- "success": False,- "error": f"Command '{command}' requires 3 JSON arguments"- })-- arg1 = json.loads(args[0])- arg2 = json.loads(args[1])- api_keys = json.loads(args[2])-- if command == "run":- return _cmd_run(arg1, arg2, api_keys)- elif command == "run_structured":- return _cmd_run_structured(arg1, arg2, api_keys)- elif command == "run_team":- return _cmd_run_team(arg1, arg2, api_keys)- elif command == "run_workflow":- return _cmd_run_workflow(arg1, arg2, api_keys)- elif command == "stock_analysis":- return _cmd_stock_analysis(arg1, arg2, api_keys)- elif command == "portfolio_rebal":- return _cmd_portfolio_rebal(arg1, arg2, api_keys)- elif command == "risk_assessment":- return _cmd_risk_assessment(arg1, arg2, api_keys)- elif command == "search":- return _cmd_search(arg1, arg2, api_keys)- elif command == "store_memory":- return _cmd_store_memory(arg1, arg2, api_keys)- elif command == "recall_memories":- return _cmd_recall_memories(arg1, arg2, api_keys)- elif command == "check_guardrails":- return _cmd_check_guardrails(arg1, arg2, api_keys)- elif command == "evaluate":- return _cmd_evaluate(arg1, arg2, api_keys)- else:- return json.dumps({"success": False, "error": f"Unknown command: {command}"})+ # Dispatch action+ result = _dispatch_action(agent, action, config, params)+ return json.dumps(result)except json.JSONDecodeError as e:return json.dumps({"success": False, "error": f"Invalid JSON: {str(e)}"})@@ -1062,319 +512,131 @@ def main(args=None):return json.dumps({"success": False, "error": str(e)})-def _cmd_run(query_json: Dict, config: Dict, api_keys: Dict) -> str:- """Execute single agent query."""- import json-- query = query_json.get("query")- if not query:- return json.dumps({"success": False, "error": "Missing 'query'"})-- agent = CoreAgent(api_keys=api_keys, user_id=query_json.get("user_id"))-- # Setup guardrails if configured- if config.get("guardrails"):- agent.setup_guardrails(config["guardrails"])- guard_result = agent.check_input(query)- if not guard_result["passed"]:- return json.dumps({- "success": False,- "error": "Input rejected by guardrails",- "violations": guard_result["violations"]- })- query = guard_result["text"]-- # Setup tracing if configured- if config.get("tracing"):- agent.setup_tracing(config["tracing"])- agent.start_trace("agent_run", {"query": query[:100]})-- try:- response = agent.run(- query=query,- config=config,- session_id=query_json.get("session_id"),- stream=query_json.get("stream", False)- )- content = agent.get_response_content(response)-- return json.dumps({- "success": True,- "response": content,- "session_id": query_json.get("session_id")- })- finally:- if config.get("tracing"):- agent.end_trace()---def _cmd_run_structured(query_json: Dict, config: Dict, api_keys: Dict) -> str:- """Execute with structured output model."""- import json-- query = query_json.get("query")- output_model = query_json.get("output_model")-- if not query:- return json.dumps({"success": False, "error": "Missing 'query'"})- if not output_model:- return json.dumps({"success": False, "error": "Missing 'output_model'"})-- agent = CoreAgent(api_keys=api_keys, user_id=query_json.get("user_id"))- result = agent.run_with_output_model(- query=query,- config=config,- output_model=output_model,- session_id=query_json.get("session_id")- )- return json.dumps(result)---def _cmd_run_team(query_json: Dict, team_config: Dict, api_keys: Dict) -> str:- """Execute multi-agent team."""- import json-- query = query_json.get("query")- if not query:- return json.dumps({"success": False, "error": "Missing 'query'"})-- agent = CoreAgent(api_keys=api_keys)- response = agent.run_team(- query=query,- team_config=team_config,- session_id=query_json.get("session_id")- )- content = agent.get_response_content(response)-- return json.dumps({- "success": True,- "response": content,- "session_id": query_json.get("session_id")- })---def _cmd_run_workflow(workflow_config: Dict, input_data: Dict, api_keys: Dict) -> str:- """Execute workflow."""- import json-- agent = CoreAgent(api_keys=api_keys)- result = agent.run_workflow(workflow_config=workflow_config, input_data=input_data)-- return json.dumps({- "success": True,- "result": result if isinstance(result, dict) else str(result),- "workflow": workflow_config.get("name", "unnamed")- })---def _cmd_stock_analysis(query_json: Dict, config: Dict, api_keys: Dict) -> str:- """Run stock analysis workflow."""- import json-- symbol = query_json.get("symbol")- if not symbol:- return json.dumps({"success": False, "error": "Missing 'symbol'"})-- agent = CoreAgent(api_keys=api_keys)- result = agent.run_stock_analysis(symbol=symbol, config=config)-- return json.dumps({- "success": True,- "symbol": symbol,- "result": result if isinstance(result, dict) else str(result)- })---def _cmd_portfolio_rebal(portfolio_data: Dict, config: Dict, api_keys: Dict) -> str:- """Run portfolio rebalancing workflow."""- import json-- agent = CoreAgent(api_keys=api_keys)- result = agent.run_portfolio_rebalancing(portfolio_data=portfolio_data, config=config)-- return json.dumps({- "success": True,- "result": result if isinstance(result, dict) else str(result)- })---def _cmd_risk_assessment(portfolio_data: Dict, config: Dict, api_keys: Dict) -> str:- """Run risk assessment workflow."""- import json-- agent = CoreAgent(api_keys=api_keys)- result = agent.run_risk_assessment(portfolio_data=portfolio_data, config=config)-- return json.dumps({- "success": True,- "result": result if isinstance(result, dict) else str(result)- })---def _cmd_search(query_json: Dict, config: Dict, api_keys: Dict) -> str:- """Search knowledge base."""- import json-- query = query_json.get("query")- if not query:- return json.dumps({"success": False, "error": "Missing 'query'"})-- agent = CoreAgent(api_keys=api_keys)- if config.get("knowledge"):- agent._create_agent(config)-- results = agent.search_knowledge(query=query, limit=query_json.get("limit", 5))-- return json.dumps({- "success": True,- "query": query,- "results": results,- "count": len(results)- })---def _cmd_store_memory(memory_json: Dict, config: Dict, api_keys: Dict) -> str:- """Store a memory."""- import json-- content = memory_json.get("content")- if not content:- return json.dumps({"success": False, "error": "Missing 'content'"})-- user_id = memory_json.get("user_id", config.get("user_id", "default"))- agent = CoreAgent(api_keys=api_keys, user_id=user_id)- agent.setup_agentic_memory({"user_id": user_id})-- memory_id = agent.store_memory(- content=content,- memory_type=memory_json.get("type", "fact"),- metadata=memory_json.get("metadata", {})- )-- return json.dumps({- "success": True,- "memory_id": memory_id,- "type": memory_json.get("type", "fact")- })---def _cmd_recall_memories(query_json: Dict, config: Dict, api_keys: Dict) -> str:- """Recall memories."""- import json-- user_id = query_json.get("user_id", config.get("user_id", "default"))- agent = CoreAgent(api_keys=api_keys, user_id=user_id)- agent.setup_agentic_memory({"user_id": user_id})-- memories = agent.recall_memories(- query=query_json.get("query"),- memory_type=query_json.get("type"),- limit=query_json.get("limit", 5)- )-- return json.dumps({- "success": True,- "memories": memories,- "count": len(memories)- })---def _cmd_check_guardrails(input_json: Dict, config: Dict, api_keys: Dict) -> str:- """Check input/output against guardrails."""- import json-- check_type = input_json.get("check_type", "input")- agent = CoreAgent(api_keys=api_keys)- agent.setup_guardrails(config.get("guardrails"))-- if check_type == "input":- text = input_json.get("text")+def _dispatch_action(agent: CoreAgent, action: str, config: Dict, params: Dict) -> Dict[str, Any]:+ """Dispatch action to appropriate agent method."""++ # Run single agent+ if action == "run":+ query = params.get("query")+ if not query:+ return {"success": False, "error": "Missing 'query' in params"}++ # Check guardrails if enabled+ if agent._guardrails:+ guard_result = agent.check_input(query)+ if not guard_result["passed"]:+ return {"success": False, "error": "Input rejected by guardrails", "violations": guard_result["violations"]}+ query = guard_result["text"]++ response = agent.run(query, config, params.get("session_id"))+ return {"success": True, "response": agent.get_response_content(response)}++ # Run with structured output+ if action == "run_structured":+ query = params.get("query")+ output_model = params.get("output_model")+ if not query or not output_model:+ return {"success": False, "error": "Missing 'query' or 'output_model' in params"}+ return agent.run_with_output_model(query, config, output_model, params.get("session_id"))++ # Run team+ if action == "run_team":+ query = params.get("query")+ team_config = params.get("team_config", config)+ if not query:+ return {"success": False, "error": "Missing 'query' in params"}+ response = agent.run_team(query, team_config, params.get("session_id"))+ return {"success": True, "response": agent.get_response_content(response)}++ # Run workflow+ if action == "run_workflow":+ workflow_config = params.get("workflow_config", config)+ input_data = params.get("input_data", {})+ result = agent.run_workflow(workflow_config, input_data)+ return {"success": True, "result": result if isinstance(result, dict) else str(result)}++ # Stock analysis+ if action == "stock_analysis":+ symbol = params.get("symbol")+ if not symbol:+ return {"success": False, "error": "Missing 'symbol' in params"}+ result = agent.run_stock_analysis(symbol, config)+ return {"success": True, "symbol": symbol, "result": result if isinstance(result, dict) else str(result)}++ # Portfolio rebalancing+ if action == "portfolio_rebal":+ portfolio_data = params.get("portfolio_data", params)+ result = agent.run_portfolio_rebalancing(portfolio_data, config)+ return {"success": True, "result": result if isinstance(result, dict) else str(result)}++ # Risk assessment+ if action == "risk_assessment":+ portfolio_data = params.get("portfolio_data", params)+ result = agent.run_risk_assessment(portfolio_data, config)+ return {"success": True, "result": result if isinstance(result, dict) else str(result)}++ # Search knowledge+ if action == "search":+ query = params.get("query")+ if not query:+ return {"success": False, "error": "Missing 'query' in params"}+ results = agent.search_knowledge(query, params.get("limit", 5))+ return {"success": True, "results": results, "count": len(results)}++ # Store memory+ if action == "store_memory":+ content = params.get("content")+ if not content:+ return {"success": False, "error": "Missing 'content' in params"}+ memory_id = agent.store_memory(content, params.get("type", "fact"), params.get("metadata"))+ return {"success": True, "memory_id": memory_id}++ # Recall memories+ if action == "recall_memories":+ memories = agent.recall_memories(params.get("query"), params.get("type"), params.get("limit", 5))+ return {"success": True, "memories": memories, "count": len(memories)}++ # Check guardrails+ if action == "check_guardrails":+ agent.setup_guardrails(config.get("guardrails"))+ if params.get("check_type") == "output":+ result = agent.check_output(params.get("output", {}))+ return {"success": True, "check_type": "output", **result}+ text = params.get("text")if not text:- return json.dumps({"success": False, "error": "Missing 'text'"})- result = agent.check_input(text, input_json.get("context"))- return json.dumps({- "success": True,- "check_type": "input",- "passed": result["passed"],- "text": result["text"],- "violations": result["violations"]- })- else:- result = agent.check_output(input_json.get("output", {}))- return json.dumps({- "success": True,- "check_type": "output",- "passed": result["passed"],- "violations": result["violations"],- "warnings": result["warnings"]- })---def _cmd_evaluate(eval_json: Dict, config: Dict, api_keys: Dict) -> str:- """Evaluate response quality."""- import json-- eval_type = eval_json.get("type", "judge")- agent = CoreAgent(api_keys=api_keys)- agent.setup_evaluation(config.get("evaluation"))-- if eval_type == "judge":- query = eval_json.get("query")- response = eval_json.get("response")- if not query or not response:- return json.dumps({"success": False, "error": "Missing 'query' or 'response'"})- result = agent.evaluate_response(query=query, response=response, context=eval_json.get("context"))- return json.dumps({"success": True, "eval_type": "judge", **result})+ return {"success": False, "error": "Missing 'text' in params"}+ result = agent.check_input(text, params.get("context"))+ return {"success": True, "check_type": "input", **result}++ # Evaluate+ if action == "evaluate":+ agent.setup_evaluation(config.get("evaluation"))+ if params.get("type") == "prediction":+ result = agent.evaluate_prediction(params.get("prediction", {}), params.get("actual", {}))+ else:+ result = agent.evaluate_response(params.get("query", ""), params.get("response", ""), params.get("context"))+ return {"success": True, **result}- elif eval_type == "prediction":- prediction = eval_json.get("prediction")- actual = eval_json.get("actual")- if not prediction or not actual:- return json.dumps({"success": False, "error": "Missing 'prediction' or 'actual'"})- result = agent.evaluate_prediction(prediction, actual)- return json.dumps({"success": True, "eval_type": "prediction", **result})+ # List tools+ if action == "list_tools":+ tools = agent.list_available_tools()+ return {"success": True, "tools": tools, "categories": list(tools.keys()), "total_count": sum(len(v) for v in tools.values())}- return json.dumps({"success": False, "error": f"Unknown eval_type: {eval_type}"})+ # List models+ if action == "list_models":+ providers = agent.list_available_models()+ return {"success": True, "providers": providers, "count": len(providers)}+ # List output models+ if action == "list_outputs":+ models = agent.list_output_models()+ return {"success": True, "models": models, "count": len(models)}-def _get_system_info() -> str:- """Get comprehensive system information."""- import json+ # System info+ if action == "system_info":+ return agent.get_system_info()- try:- from finagent_core.registries import (- ModelsRegistry, ToolsRegistry, VectorDBRegistry, EmbedderRegistry- )- from finagent_core.modules import OutputModelRegistry-- providers = ModelsRegistry.list_providers()- tools = ToolsRegistry.list_tools()- vectordbs = VectorDBRegistry.list_vectordbs()- embedders = EmbedderRegistry.list_providers()- output_models = OutputModelRegistry.list_models()-- return json.dumps({- "success": True,- "version": "2.0.0",- "framework": "agno",- "capabilities": {- "model_providers": len(providers),- "tools": sum(len(v) for v in tools.values()),- "tool_categories": list(tools.keys()),- "vectordbs": vectordbs,- "embedders": embedders,- "output_models": output_models- },- "features": [- "multi_agent_teams", "workflow_orchestration", "parallel_execution",- "conditional_branching", "loop_execution", "dynamic_routing",- "knowledge_base_rag", "memory_management", "agentic_memory",- "reasoning_strategies", "session_management", "guardrails",- "evaluation", "tracing", "compression", "hooks", "structured_outputs"- ]- })- except ImportError as e:- return json.dumps({"success": False, "error": f"Import error: {str(e)}"})+ return {"success": False, "error": f"Unknown action: {action}"}if __name__ == "__main__":diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent_stream.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent_stream.pynew file mode 100644index 000000000..a50c9d051--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/core_agent_stream.py@@ -0,0 +1,313 @@+"""+Core Agent Streaming - Real-time streaming responses via named pipes++Supports:+- Token-by-token streaming+- Thinking/reasoning step streaming+- Tool call notifications+- Progress updates+"""++from typing import Dict, Any, Optional, Generator, Callable+import logging+import json+import sys+import os++# Add parent directory to path for imports+from pathlib import Path+parent_dir = str(Path(__file__).parent.parent)+if parent_dir not in sys.path:+ sys.path.insert(0, parent_dir)++logger = logging.getLogger(__name__)+++class StreamingCoreAgent:+ """+ Streaming version of CoreAgent.+ Yields chunks for real-time UI updates.+ """++ def __init__(+ self,+ api_keys: Optional[Dict[str, str]] = None,+ user_id: Optional[str] = None,+ stream_callback: Optional[Callable[[str, str, Optional[Dict]], None]] = None+ ):+ self.api_keys = api_keys or {}+ self.user_id = user_id+ self.stream_callback = stream_callback or self._default_callback+ self._agent = None+ self._current_config = None++ def _default_callback(self, chunk_type: str, content: str, metadata: Optional[Dict] = None):+ """Default callback - print to stdout as JSON lines"""+ chunk = {+ "type": chunk_type,+ "content": content,+ "metadata": metadata+ }+ print(json.dumps(chunk), flush=True)++ def emit(self, chunk_type: str, content: str, metadata: Optional[Dict] = None):+ """Emit a stream chunk"""+ self.stream_callback(chunk_type, content, metadata)++ def run_streaming(+ self,+ query: str,+ config: Dict[str, Any],+ session_id: Optional[str] = None+ ) -> Generator[Dict[str, Any], None, None]:+ """Execute agent with streaming output."""+ from core_agent import CoreAgent++ # Emit thinking indicator+ self.emit("thinking", "Analyzing your request...")++ # Create or reuse agent+ core = CoreAgent(api_keys=self.api_keys, user_id=self.user_id)++ # Check if model supports streaming+ model_config = config.get("model", {})+ provider = model_config.get("provider", "openai")++ # Providers that support native streaming+ streaming_providers = ["openai", "anthropic", "groq", "together", "fireworks", "ollama"]++ if provider in streaming_providers:+ # Use native streaming+ yield from self._stream_native(core, query, config, session_id)+ else:+ # Simulate streaming for non-streaming providers+ yield from self._stream_simulated(core, query, config, session_id)++ def _stream_native(+ self,+ core,+ query: str,+ config: Dict[str, Any],+ session_id: Optional[str]+ ) -> Generator[Dict[str, Any], None, None]:+ """Stream using native provider streaming support."""+ try:+ # Enable streaming in config+ config = config.copy()+ config["stream"] = True++ # Create agent with streaming+ agent = core._create_agent(config)++ # Check guardrails first+ if core._guardrails:+ self.emit("thinking", "Checking input guardrails...")+ guard_result = core.check_input(query)+ if not guard_result["passed"]:+ self.emit("error", f"Input rejected: {guard_result['violations']}")+ return+ query = guard_result["text"]++ self.emit("thinking", "Generating response...")++ # Run with streaming+ run_kwargs = {"input": query, "stream": True}+ if session_id:+ run_kwargs["session_id"] = session_id++ response = agent.run(**run_kwargs)++ # Handle streaming response+ full_content = ""++ if hasattr(response, '__iter__') and not isinstance(response, str):+ # Iterable response (true streaming)+ for chunk in response:+ if hasattr(chunk, 'content'):+ content = chunk.content+ elif isinstance(chunk, dict):+ content = chunk.get('content', str(chunk))+ else:+ content = str(chunk)++ full_content += content+ self.emit("token", content)+ yield {"type": "token", "content": content}+ else:+ # Non-streaming response - emit all at once+ content = core.get_response_content(response)+ full_content = content+ # Chunk for smoother UI+ for i in range(0, len(content), 50):+ chunk = content[i:i+50]+ self.emit("token", chunk)+ yield {"type": "token", "content": chunk}++ # Emit completion+ self.emit("done", full_content, {"total_tokens": len(full_content)})+ yield {"type": "done", "content": full_content}++ except Exception as e:+ self.emit("error", str(e))+ yield {"type": "error", "content": str(e)}++ def _stream_simulated(+ self,+ core,+ query: str,+ config: Dict[str, Any],+ session_id: Optional[str]+ ) -> Generator[Dict[str, Any], None, None]:+ """Simulate streaming for non-streaming providers."""+ try:+ self.emit("thinking", "Processing (non-streaming provider)...")++ # Run without streaming+ response = core.run(query, config, session_id)+ content = core.get_response_content(response)++ # Simulate streaming by chunking output+ chunk_size = 30 # Characters per chunk+ for i in range(0, len(content), chunk_size):+ chunk = content[i:i+chunk_size]+ self.emit("token", chunk)+ yield {"type": "token", "content": chunk}++ self.emit("done", content)+ yield {"type": "done", "content": content}++ except Exception as e:+ self.emit("error", str(e))+ yield {"type": "error", "content": str(e)}++ def run_team_streaming(+ self,+ query: str,+ team_config: Dict[str, Any],+ session_id: Optional[str] = None+ ) -> Generator[Dict[str, Any], None, None]:+ """Stream team execution with agent-by-agent updates."""+ try:+ self.emit("thinking", "Initializing team...")++ members = team_config.get("agents", team_config.get("members", []))+ mode = team_config.get("mode", "coordinate")++ self.emit("thinking", f"Team mode: {mode} with {len(members)} agents")++ # Process each agent (simplified - real implementation would use Agno teams)+ results = []+ for i, member_config in enumerate(members):+ agent_name = member_config.get("name", f"Agent {i+1}")+ self.emit("thinking", f"Agent '{agent_name}' is working...")++ # Run individual agent+ for chunk in self.run_streaming(query, member_config, session_id):+ if chunk["type"] == "token":+ yield {+ "type": "agent_token",+ "agent": agent_name,+ "content": chunk["content"]+ }+ elif chunk["type"] == "done":+ results.append({+ "agent": agent_name,+ "response": chunk["content"]+ })+ self.emit("agent_done", f"Agent '{agent_name}' completed")++ # Emit final aggregated result+ final_result = "\n\n".join([+ f"**{r['agent']}:**\n{r['response']}"+ for r in results+ ])+ self.emit("done", final_result, {"agents": len(results)})+ yield {"type": "done", "content": final_result}++ except Exception as e:+ self.emit("error", str(e))+ yield {"type": "error", "content": str(e)}+++def main(args=None):+ """Entry point for streaming agent execution."""+ if args is None:+ args = sys.argv[1:]++ try:+ if len(args) == 0:+ return json.dumps({"success": False, "error": "No payload provided"})++ # Parse payload+ payload = json.loads(args[0])+ action = payload.get("action", "run")+ api_keys = payload.get("api_keys", {})+ user_id = payload.get("user_id")+ config = payload.get("config", {})+ params = payload.get("params", {})+ stream_id = payload.get("stream_id")++ # Collected output for final response+ full_response = ""+ chunks = []++ def collect_callback(chunk_type: str, content: str, metadata: Optional[Dict] = None):+ """Collect chunks and print as JSON lines"""+ nonlocal full_response+ chunk = {+ "stream_id": stream_id,+ "type": chunk_type,+ "content": content,+ "metadata": metadata+ }+ # Print as JSON line for real-time capture+ print(f"STREAM:{json.dumps(chunk)}", flush=True)+ chunks.append(chunk)+ if chunk_type in ["token", "agent_token"]:+ full_response += content++ agent = StreamingCoreAgent(+ api_keys=api_keys,+ user_id=user_id,+ stream_callback=collect_callback+ )++ if action == "run":+ query = params.get("query")+ if not query:+ return json.dumps({"success": False, "error": "Missing query"})++ # Consume the generator+ for _ in agent.run_streaming(query, config, params.get("session_id")):+ pass++ elif action == "run_team":+ query = params.get("query")+ team_config = params.get("team_config", config)+ if not query:+ return json.dumps({"success": False, "error": "Missing query"})++ for _ in agent.run_team_streaming(query, team_config, params.get("session_id")):+ pass++ else:+ # Fallback to non-streaming core_agent+ from core_agent import main as core_main+ return core_main(args)++ return json.dumps({+ "success": True,+ "response": full_response,+ "stream_id": stream_id,+ "chunk_count": len(chunks)+ })++ except json.JSONDecodeError as e:+ return json.dumps({"success": False, "error": f"Invalid JSON: {str(e)}"})+ except Exception as e:+ return json.dumps({"success": False, "error": str(e)})+++if __name__ == "__main__":+ result = main()+ print(result)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/execution_planner.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/execution_planner.pynew file mode 100644index 000000000..13d02e18f--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/execution_planner.py@@ -0,0 +1,608 @@+"""+ExecutionPlanner - Multi-step task planning for complex operations++Plans and orchestrates multi-step tasks with dependency management.+Similar to ValueCell's task planning capabilities.+"""++from typing import Dict, Any, Optional, List, Callable, Union+from dataclasses import dataclass, field+from enum import Enum+import logging+import json++logger = logging.getLogger(__name__)+++class StepStatus(Enum):+ """Status of a plan step"""+ PENDING = "pending"+ RUNNING = "running"+ COMPLETED = "completed"+ FAILED = "failed"+ SKIPPED = "skipped"+++class StepType(Enum):+ """Type of step"""+ AGENT = "agent" # Execute with an agent+ TOOL = "tool" # Execute a tool directly+ CONDITION = "condition" # Conditional branching+ PARALLEL = "parallel" # Parallel execution+ LOOP = "loop" # Loop execution+ WAIT = "wait" # Wait for user input+ CHECKPOINT = "checkpoint" # Save state checkpoint+++@dataclass+class PlanStep:+ """A single step in an execution plan"""+ id: str+ name: str+ step_type: StepType+ config: Dict[str, Any] = field(default_factory=dict)+ dependencies: List[str] = field(default_factory=list)+ status: StepStatus = StepStatus.PENDING+ result: Any = None+ error: Optional[str] = None++ def to_dict(self) -> Dict[str, Any]:+ return {+ "id": self.id,+ "name": self.name,+ "step_type": self.step_type.value,+ "config": self.config,+ "dependencies": self.dependencies,+ "status": self.status.value,+ "result": self.result if isinstance(self.result, (dict, list, str, int, float, bool, type(None))) else str(self.result),+ "error": self.error+ }+++@dataclass+class ExecutionPlan:+ """A complete execution plan"""+ id: str+ name: str+ description: str+ steps: List[PlanStep] = field(default_factory=list)+ context: Dict[str, Any] = field(default_factory=dict)+ status: StepStatus = StepStatus.PENDING+ current_step_index: int = 0++ def add_step(self, step: PlanStep) -> None:+ """Add a step to the plan"""+ self.steps.append(step)++ def get_ready_steps(self) -> List[PlanStep]:+ """Get steps that are ready to execute (dependencies met)"""+ completed_ids = {s.id for s in self.steps if s.status == StepStatus.COMPLETED}+ ready = []++ for step in self.steps:+ if step.status != StepStatus.PENDING:+ continue+ if all(dep in completed_ids for dep in step.dependencies):+ ready.append(step)++ return ready++ def get_step(self, step_id: str) -> Optional[PlanStep]:+ """Get step by ID"""+ for step in self.steps:+ if step.id == step_id:+ return step+ return None++ def is_complete(self) -> bool:+ """Check if plan is complete"""+ return all(s.status in (StepStatus.COMPLETED, StepStatus.SKIPPED) for s in self.steps)++ def has_failed(self) -> bool:+ """Check if any step has failed"""+ return any(s.status == StepStatus.FAILED for s in self.steps)++ def to_dict(self) -> Dict[str, Any]:+ return {+ "id": self.id,+ "name": self.name,+ "description": self.description,+ "steps": [s.to_dict() for s in self.steps],+ "context": self.context,+ "status": self.status.value,+ "current_step_index": self.current_step_index,+ "is_complete": self.is_complete(),+ "has_failed": self.has_failed()+ }+++class PlanBuilder:+ """Builder for creating execution plans"""++ def __init__(self, plan_id: str, name: str, description: str = ""):+ self.plan = ExecutionPlan(+ id=plan_id,+ name=name,+ description=description+ )+ self._step_counter = 0++ def _next_id(self) -> str:+ self._step_counter += 1+ return f"step_{self._step_counter}"++ def add_agent_step(+ self,+ name: str,+ query: str,+ agent_config: Dict[str, Any] = None,+ dependencies: List[str] = None,+ step_id: str = None+ ) -> str:+ """Add an agent execution step"""+ step_id = step_id or self._next_id()+ step = PlanStep(+ id=step_id,+ name=name,+ step_type=StepType.AGENT,+ config={+ "query": query,+ "agent_config": agent_config or {}+ },+ dependencies=dependencies or []+ )+ self.plan.add_step(step)+ return step_id++ def add_tool_step(+ self,+ name: str,+ tool_name: str,+ tool_args: Dict[str, Any] = None,+ dependencies: List[str] = None,+ step_id: str = None+ ) -> str:+ """Add a tool execution step"""+ step_id = step_id or self._next_id()+ step = PlanStep(+ id=step_id,+ name=name,+ step_type=StepType.TOOL,+ config={+ "tool_name": tool_name,+ "tool_args": tool_args or {}+ },+ dependencies=dependencies or []+ )+ self.plan.add_step(step)+ return step_id++ def add_condition(+ self,+ name: str,+ condition: str,+ if_true: str,+ if_false: str,+ dependencies: List[str] = None,+ step_id: str = None+ ) -> str:+ """Add a conditional branch"""+ step_id = step_id or self._next_id()+ step = PlanStep(+ id=step_id,+ name=name,+ step_type=StepType.CONDITION,+ config={+ "condition": condition,+ "if_true": if_true,+ "if_false": if_false+ },+ dependencies=dependencies or []+ )+ self.plan.add_step(step)+ return step_id++ def add_parallel(+ self,+ name: str,+ step_ids: List[str],+ dependencies: List[str] = None,+ step_id: str = None+ ) -> str:+ """Add parallel execution of multiple steps"""+ step_id = step_id or self._next_id()+ step = PlanStep(+ id=step_id,+ name=name,+ step_type=StepType.PARALLEL,+ config={"parallel_steps": step_ids},+ dependencies=dependencies or []+ )+ self.plan.add_step(step)+ return step_id++ def add_checkpoint(+ self,+ name: str,+ save_keys: List[str] = None,+ dependencies: List[str] = None,+ step_id: str = None+ ) -> str:+ """Add a checkpoint to save state"""+ step_id = step_id or self._next_id()+ step = PlanStep(+ id=step_id,+ name=name,+ step_type=StepType.CHECKPOINT,+ config={"save_keys": save_keys or []},+ dependencies=dependencies or []+ )+ self.plan.add_step(step)+ return step_id++ def build(self) -> ExecutionPlan:+ """Build and return the plan"""+ return self.plan+++class ExecutionPlanner:+ """+ Orchestrates multi-step task execution.++ Features:+ - Plan creation and management+ - Step-by-step execution+ - Dependency resolution+ - Result aggregation+ - Error handling and recovery+ """++ def __init__(self, api_keys: Optional[Dict[str, str]] = None):+ self.api_keys = api_keys or {}+ self.plans: Dict[str, ExecutionPlan] = {}+ self.checkpoints: Dict[str, Dict[str, Any]] = {}++ def create_plan(+ self,+ plan_id: str,+ name: str,+ description: str = ""+ ) -> PlanBuilder:+ """Create a new plan builder"""+ return PlanBuilder(plan_id, name, description)++ def register_plan(self, plan: ExecutionPlan) -> None:+ """Register a plan for execution"""+ self.plans[plan.id] = plan++ def get_plan(self, plan_id: str) -> Optional[ExecutionPlan]:+ """Get plan by ID"""+ return self.plans.get(plan_id)++ def execute_plan(+ self,+ plan: ExecutionPlan,+ initial_context: Dict[str, Any] = None+ ) -> Dict[str, Any]:+ """+ Execute a complete plan.++ Args:+ plan: The execution plan+ initial_context: Initial context data++ Returns:+ Execution results+ """+ if initial_context:+ plan.context.update(initial_context)++ plan.status = StepStatus.RUNNING+ self.register_plan(plan)++ while not plan.is_complete() and not plan.has_failed():+ ready_steps = plan.get_ready_steps()++ if not ready_steps:+ # Deadlock detection+ logger.warning("No ready steps but plan not complete - possible deadlock")+ break++ for step in ready_steps:+ result = self._execute_step(step, plan)++ if step.status == StepStatus.FAILED:+ plan.status = StepStatus.FAILED+ break++ if plan.is_complete():+ plan.status = StepStatus.COMPLETED++ return plan.to_dict()++ def execute_step(+ self,+ plan_id: str,+ step_id: str+ ) -> Dict[str, Any]:+ """Execute a single step"""+ plan = self.get_plan(plan_id)+ if not plan:+ return {"success": False, "error": f"Plan not found: {plan_id}"}++ step = plan.get_step(step_id)+ if not step:+ return {"success": False, "error": f"Step not found: {step_id}"}++ result = self._execute_step(step, plan)+ return {+ "success": step.status == StepStatus.COMPLETED,+ "step": step.to_dict(),+ "result": result+ }++ def _execute_step(self, step: PlanStep, plan: ExecutionPlan) -> Any:+ """Execute a single step based on its type"""+ step.status = StepStatus.RUNNING++ try:+ if step.step_type == StepType.AGENT:+ result = self._execute_agent_step(step, plan)+ elif step.step_type == StepType.TOOL:+ result = self._execute_tool_step(step, plan)+ elif step.step_type == StepType.CONDITION:+ result = self._execute_condition_step(step, plan)+ elif step.step_type == StepType.PARALLEL:+ result = self._execute_parallel_step(step, plan)+ elif step.step_type == StepType.CHECKPOINT:+ result = self._execute_checkpoint_step(step, plan)+ else:+ result = None++ step.result = result+ step.status = StepStatus.COMPLETED++ # Store result in context+ plan.context[f"{step.id}_result"] = result++ return result++ except Exception as e:+ step.status = StepStatus.FAILED+ step.error = str(e)+ logger.error(f"Step {step.id} failed: {e}")+ return None++ def _execute_agent_step(self, step: PlanStep, plan: ExecutionPlan) -> Any:+ """Execute an agent step"""+ from finagent_core.core_agent import CoreAgent++ query = step.config.get("query", "")+ agent_config = step.config.get("agent_config", {})++ # Interpolate context into query+ query = self._interpolate(query, plan.context)++ agent = CoreAgent(api_keys=self.api_keys)+ response = agent.run(query, agent_config)+ return agent.get_response_content(response)++ def _execute_tool_step(self, step: PlanStep, plan: ExecutionPlan) -> Any:+ """Execute a tool step"""+ tool_name = step.config.get("tool_name")+ tool_args = step.config.get("tool_args", {})++ # Interpolate context into args+ tool_args = {k: self._interpolate(v, plan.context) if isinstance(v, str) else v+ for k, v in tool_args.items()}++ # Import and execute tool+ from finagent_core.registries import ToolsRegistry+ tools = ToolsRegistry.get_tools([tool_name])++ if not tools:+ raise ValueError(f"Tool not found: {tool_name}")++ tool = tools[0]+ return tool.run(**tool_args) if hasattr(tool, 'run') else str(tool)++ def _execute_condition_step(self, step: PlanStep, plan: ExecutionPlan) -> str:+ """Execute a condition step and return the chosen branch"""+ condition = step.config.get("condition", "")+ if_true = step.config.get("if_true")+ if_false = step.config.get("if_false")++ # Simple condition evaluation using context+ condition = self._interpolate(condition, plan.context)++ try:+ result = eval(condition, {"__builtins__": {}}, plan.context)+ except Exception:+ result = False++ next_step_id = if_true if result else if_false++ # Mark skipped branch+ skipped_id = if_false if result else if_true+ skipped_step = plan.get_step(skipped_id)+ if skipped_step:+ skipped_step.status = StepStatus.SKIPPED++ return next_step_id++ def _execute_parallel_step(self, step: PlanStep, plan: ExecutionPlan) -> List[Any]:+ """Execute parallel steps"""+ parallel_ids = step.config.get("parallel_steps", [])+ results = []++ # In real implementation, would use asyncio/threads+ for step_id in parallel_ids:+ parallel_step = plan.get_step(step_id)+ if parallel_step:+ result = self._execute_step(parallel_step, plan)+ results.append(result)++ return results++ def _execute_checkpoint_step(self, step: PlanStep, plan: ExecutionPlan) -> Dict[str, Any]:+ """Save a checkpoint"""+ save_keys = step.config.get("save_keys", [])++ checkpoint = {}+ if save_keys:+ for key in save_keys:+ if key in plan.context:+ checkpoint[key] = plan.context[key]+ else:+ checkpoint = plan.context.copy()++ self.checkpoints[f"{plan.id}:{step.id}"] = checkpoint+ return checkpoint++ def _interpolate(self, text: str, context: Dict[str, Any]) -> str:+ """Interpolate context values into text"""+ if not isinstance(text, str):+ return text++ for key, value in context.items():+ placeholder = f"{{{key}}}"+ if placeholder in text:+ text = text.replace(placeholder, str(value))++ return text++ def restore_checkpoint(self, plan_id: str, step_id: str) -> Optional[Dict[str, Any]]:+ """Restore from a checkpoint"""+ key = f"{plan_id}:{step_id}"+ return self.checkpoints.get(key)++ # =========================================================================+ # Plan Templates for Common Tasks+ # =========================================================================++ @staticmethod+ def stock_analysis_plan(symbol: str) -> ExecutionPlan:+ """Create a stock analysis plan"""+ builder = PlanBuilder(+ plan_id=f"stock_analysis_{symbol}",+ name=f"Stock Analysis: {symbol}",+ description=f"Comprehensive analysis of {symbol}"+ )++ # Parallel data fetching+ fetch_price = builder.add_agent_step(+ name="Fetch Price Data",+ query=f"Get current price, 52-week high/low, and recent price history for {symbol}",+ agent_config={"tools": ["yfinance"]}+ )++ fetch_fundamentals = builder.add_agent_step(+ name="Fetch Fundamentals",+ query=f"Get P/E ratio, EPS, revenue, and other key fundamentals for {symbol}",+ agent_config={"tools": ["yfinance"]}+ )++ fetch_news = builder.add_agent_step(+ name="Fetch News",+ query=f"Get recent news and headlines for {symbol}",+ agent_config={"tools": ["duckduckgo"]}+ )++ # Analysis (depends on data)+ analyze = builder.add_agent_step(+ name="Analyze Stock",+ query=f"""Based on the data collected, provide a comprehensive analysis of {symbol}:+ - Technical analysis (price trends, support/resistance)+ - Fundamental analysis (valuation, growth)+ - News sentiment+ - Overall recommendation""",+ agent_config={"reasoning": True},+ dependencies=[fetch_price, fetch_fundamentals, fetch_news]+ )++ # Checkpoint+ builder.add_checkpoint(+ name="Save Analysis",+ dependencies=[analyze]+ )++ return builder.build()++ @staticmethod+ def portfolio_rebalance_plan(portfolio_id: str) -> ExecutionPlan:+ """Create a portfolio rebalancing plan"""+ builder = PlanBuilder(+ plan_id=f"rebalance_{portfolio_id}",+ name=f"Portfolio Rebalance: {portfolio_id}",+ description="Analyze and rebalance portfolio"+ )++ # Fetch current positions+ fetch_positions = builder.add_agent_step(+ name="Fetch Positions",+ query=f"Get current positions and allocations for portfolio {portfolio_id}",+ agent_config={"tools": ["yfinance"]}+ )++ # Analyze risk+ analyze_risk = builder.add_agent_step(+ name="Analyze Risk",+ query="Analyze portfolio risk metrics: volatility, correlation, concentration",+ dependencies=[fetch_positions]+ )++ # Generate recommendations+ recommend = builder.add_agent_step(+ name="Generate Recommendations",+ query="Based on the analysis, generate rebalancing recommendations",+ agent_config={"reasoning": True},+ dependencies=[analyze_risk]+ )++ # Calculate trades+ calculate = builder.add_agent_step(+ name="Calculate Trades",+ query="Calculate specific trades needed to implement the recommendations",+ agent_config={"tools": ["calculator"]},+ dependencies=[recommend]+ )++ return builder.build()+++# Entry points for Tauri commands+def create_stock_analysis_plan(symbol: str) -> Dict[str, Any]:+ """Create a stock analysis plan"""+ plan = ExecutionPlanner.stock_analysis_plan(symbol)+ return plan.to_dict()+++def execute_plan(plan_dict: Dict[str, Any], api_keys: Dict[str, str] = None) -> Dict[str, Any]:+ """Execute a plan from dict"""+ # Reconstruct plan from dict+ plan = ExecutionPlan(+ id=plan_dict["id"],+ name=plan_dict["name"],+ description=plan_dict.get("description", ""),+ context=plan_dict.get("context", {})+ )++ for step_dict in plan_dict.get("steps", []):+ step = PlanStep(+ id=step_dict["id"],+ name=step_dict["name"],+ step_type=StepType(step_dict["step_type"]),+ config=step_dict.get("config", {}),+ dependencies=step_dict.get("dependencies", []),+ status=StepStatus(step_dict.get("status", "pending"))+ )+ plan.add_step(step)++ planner = ExecutionPlanner(api_keys=api_keys)+ return planner.execute_plan(plan)+++def get_plan_status(plan_id: str) -> Dict[str, Any]:+ """Get plan status"""+ # In a real implementation, this would retrieve from storage+ return {"success": False, "error": "Plan not found - use execute_plan instead"}diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/main.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/main.pynew file mode 100644index 000000000..58d53538a--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/main.py@@ -0,0 +1,378 @@+"""+FinAgent Core Main Entry Point++Unified entry point for all agent operations via Tauri.+Handles JSON payload dispatch to appropriate modules.+"""++import sys+import json+from pathlib import Path+from typing import Dict, Any++# Add parent directory to path+parent_dir = str(Path(__file__).parent.parent)+if parent_dir not in sys.path:+ sys.path.insert(0, parent_dir)+++def main(args=None):+ """+ Main entry point - accepts single JSON payload from Rust/Tauri.++ Payload format:+ {+ "action": "<action_name>",+ "api_keys": {...},+ "params": {...}+ }++ Actions:+ - Core agent: run, run_team, run_workflow, run_structured+ - Dynamic loading: discover_agents, list_agents, create_agent+ - SuperAgent: route_query, execute_query+ - Execution planner: create_plan, execute_plan, get_plan_status+ - Paper trading: execute_trade, get_portfolio_value, get_positions_summary+ - System: system_info, list_tools, list_models+ """+ if args is None:+ args = sys.argv[1:]++ try:+ if len(args) == 0:+ return json.dumps({"success": False, "error": "No payload provided"})++ payload = json.loads(args[0])+ action = payload.get("action")+ api_keys = payload.get("api_keys", {})+ params = payload.get("params", {})+ config = payload.get("config", {})++ if not action:+ return json.dumps({"success": False, "error": "Missing 'action' in payload"})++ result = dispatch_action(action, api_keys, params, config)+ return json.dumps(result)++ except json.JSONDecodeError as e:+ return json.dumps({"success": False, "error": f"Invalid JSON: {str(e)}"})+ except Exception as e:+ return json.dumps({"success": False, "error": str(e)})+++def dispatch_action(+ action: str,+ api_keys: Dict[str, str],+ params: Dict[str, Any],+ config: Dict[str, Any]+) -> Dict[str, Any]:+ """Dispatch action to appropriate handler"""++ # =========================================================================+ # Core Agent Actions+ # =========================================================================++ if action == "run":+ from finagent_core.core_agent import CoreAgent+ agent = CoreAgent(api_keys=api_keys, user_id=params.get("user_id"))+ query = params.get("query")+ if not query:+ return {"success": False, "error": "Missing 'query' in params"}+ response = agent.run(query, config, params.get("session_id"))+ return {"success": True, "response": agent.get_response_content(response)}++ if action == "run_team":+ from finagent_core.core_agent import CoreAgent+ agent = CoreAgent(api_keys=api_keys)+ query = params.get("query")+ team_config = params.get("team_config", config)+ if not query:+ return {"success": False, "error": "Missing 'query' in params"}+ response = agent.run_team(query, team_config, params.get("session_id"))+ return {"success": True, "response": agent.get_response_content(response)}++ if action == "run_workflow":+ from finagent_core.core_agent import CoreAgent+ agent = CoreAgent(api_keys=api_keys)+ workflow_config = params.get("workflow_config", config)+ input_data = params.get("input_data", {})+ result = agent.run_workflow(workflow_config, input_data)+ return {"success": True, "result": result if isinstance(result, dict) else str(result)}++ if action == "run_structured":+ from finagent_core.core_agent import CoreAgent+ agent = CoreAgent(api_keys=api_keys)+ query = params.get("query")+ output_model = params.get("output_model")+ if not query or not output_model:+ return {"success": False, "error": "Missing 'query' or 'output_model'"}+ return agent.run_with_output_model(query, config, output_model, params.get("session_id"))++ # =========================================================================+ # Dynamic Agent Loading+ # =========================================================================++ if action == "discover_agents":+ from finagent_core.agent_loader import discover_agents+ agents = discover_agents()+ return {"success": True, "agents": agents, "count": len(agents)}++ if action == "list_agents":+ from finagent_core.agent_loader import list_agents, list_categories+ category = params.get("category")+ agents = list_agents(category)+ return {+ "success": True,+ "agents": agents,+ "count": len(agents),+ "categories": list_categories()+ }++ if action == "create_agent":+ from finagent_core.agent_loader import create_agent+ agent_id = params.get("agent_id")+ if not agent_id:+ return {"success": False, "error": "Missing 'agent_id'"}+ try:+ agent = create_agent(agent_id, api_keys, config)+ return {"success": True, "agent_id": agent_id, "created": True}+ except Exception as e:+ return {"success": False, "error": str(e)}++ # =========================================================================+ # SuperAgent Routing+ # =========================================================================++ if action == "route_query":+ from finagent_core.super_agent import route_query+ query = params.get("query")+ if not query:+ return {"success": False, "error": "Missing 'query'"}+ return route_query(query, api_keys)++ if action == "execute_query":+ from finagent_core.super_agent import execute_query+ query = params.get("query")+ if not query:+ return {"success": False, "error": "Missing 'query'"}+ return execute_query(query, api_keys, params.get("session_id"))++ if action == "execute_multi_query":+ from finagent_core.super_agent import SuperAgent+ query = params.get("query")+ if not query:+ return {"success": False, "error": "Missing 'query'"}+ agent = SuperAgent(api_keys=api_keys)+ return agent.execute_multi(query, params.get("session_id"), params.get("aggregate", True))++ # =========================================================================+ # Execution Planner+ # =========================================================================++ if action == "create_stock_plan":+ from finagent_core.execution_planner import create_stock_analysis_plan+ symbol = params.get("symbol")+ if not symbol:+ return {"success": False, "error": "Missing 'symbol'"}+ plan = create_stock_analysis_plan(symbol)+ return {"success": True, "plan": plan}++ if action == "create_portfolio_plan":+ from finagent_core.execution_planner import ExecutionPlanner+ portfolio_id = params.get("portfolio_id")+ if not portfolio_id:+ return {"success": False, "error": "Missing 'portfolio_id'"}+ plan = ExecutionPlanner.portfolio_rebalance_plan(portfolio_id)+ return {"success": True, "plan": plan.to_dict()}++ if action == "execute_plan":+ from finagent_core.execution_planner import execute_plan+ plan_dict = params.get("plan")+ if not plan_dict:+ return {"success": False, "error": "Missing 'plan'"}+ return execute_plan(plan_dict, api_keys)++ # =========================================================================+ # Paper Trading Bridge+ # =========================================================================++ if action == "paper_execute_trade":+ from finagent_core.paper_trading_bridge import execute_trade+ portfolio_id = params.get("portfolio_id")+ symbol = params.get("symbol")+ trade_action = params.get("action")+ quantity = params.get("quantity", 1)+ price = params.get("price")+ if not all([portfolio_id, symbol, trade_action, price]):+ return {"success": False, "error": "Missing required params: portfolio_id, symbol, action, price"}+ return execute_trade(portfolio_id, symbol, trade_action, quantity, price)++ if action == "paper_get_portfolio":+ from finagent_core.paper_trading_bridge import get_portfolio_value+ portfolio_id = params.get("portfolio_id")+ if not portfolio_id:+ return {"success": False, "error": "Missing 'portfolio_id'"}+ return get_portfolio_value(portfolio_id)++ if action == "paper_get_positions":+ from finagent_core.paper_trading_bridge import get_positions_summary+ portfolio_id = params.get("portfolio_id")+ if not portfolio_id:+ return {"success": False, "error": "Missing 'portfolio_id'"}+ return get_positions_summary(portfolio_id)++ # =========================================================================+ # Repository Operations+ # =========================================================================++ if action == "save_session":+ from finagent_core.repositories import RepositoryFactory, AgentSession+ repo = RepositoryFactory.get_session_repository()+ session = AgentSession(**params)+ session_id = repo.create(session)+ return {"success": True, "session_id": session_id}++ if action == "get_session":+ from finagent_core.repositories import RepositoryFactory+ repo = RepositoryFactory.get_session_repository()+ session = repo.get(params.get("session_id"))+ if session:+ return {"success": True, "session": {+ "id": session.id,+ "agent_id": session.agent_id,+ "messages": session.messages,+ "status": session.status+ }}+ return {"success": False, "error": "Session not found"}++ if action == "add_message":+ from finagent_core.repositories import RepositoryFactory+ repo = RepositoryFactory.get_session_repository()+ success = repo.add_message(+ params.get("session_id"),+ params.get("role"),+ params.get("content")+ )+ return {"success": success}++ if action == "save_memory":+ from finagent_core.repositories import RepositoryFactory, AgentMemory+ import uuid+ repo = RepositoryFactory.get_memory_repository()+ memory = AgentMemory(+ id=str(uuid.uuid4()),+ agent_id=params.get("agent_id", "default"),+ user_id=params.get("user_id"),+ memory_type=params.get("type", "fact"),+ content=params.get("content"),+ metadata=params.get("metadata", {}),+ importance=params.get("importance", 0.5)+ )+ memory_id = repo.create(memory)+ return {"success": True, "memory_id": memory_id}++ if action == "search_memories":+ from finagent_core.repositories import RepositoryFactory+ repo = RepositoryFactory.get_memory_repository()+ memories = repo.search(+ params.get("query", ""),+ params.get("agent_id"),+ params.get("limit", 10)+ )+ return {+ "success": True,+ "memories": [+ {"id": m.id, "content": m.content, "type": m.memory_type, "importance": m.importance}+ for m in memories+ ]+ }++ if action == "save_trade_decision":+ from finagent_core.repositories import RepositoryFactory, TradeDecision+ import uuid+ from datetime import datetime+ repo = RepositoryFactory.get_trade_decision_repository()+ decision = TradeDecision(+ id=str(uuid.uuid4()),+ competition_id=params.get("competition_id"),+ model_name=params.get("model_name"),+ cycle_number=params.get("cycle_number", 0),+ symbol=params.get("symbol"),+ action=params.get("action"),+ quantity=params.get("quantity", 0),+ price=params.get("price"),+ reasoning=params.get("reasoning", ""),+ confidence=params.get("confidence", 0.5),+ timestamp=datetime.utcnow().isoformat()+ )+ decision_id = repo.create(decision)+ return {"success": True, "decision_id": decision_id}++ if action == "get_decisions":+ from finagent_core.repositories import RepositoryFactory+ repo = RepositoryFactory.get_trade_decision_repository()+ decisions = repo.list(+ competition_id=params.get("competition_id"),+ model_name=params.get("model_name"),+ cycle_number=params.get("cycle_number"),+ limit=params.get("limit", 100)+ )+ return {+ "success": True,+ "decisions": [+ {+ "id": d.id,+ "model_name": d.model_name,+ "symbol": d.symbol,+ "action": d.action,+ "quantity": d.quantity,+ "price": d.price,+ "confidence": d.confidence,+ "reasoning": d.reasoning+ }+ for d in decisions+ ]+ }++ # =========================================================================+ # System Information+ # =========================================================================++ if action == "system_info":+ from finagent_core.core_agent import CoreAgent+ agent = CoreAgent(api_keys=api_keys)+ return agent.get_system_info()++ if action == "list_tools":+ from finagent_core.core_agent import CoreAgent+ agent = CoreAgent(api_keys=api_keys)+ tools = agent.list_available_tools()+ return {+ "success": True,+ "tools": tools,+ "categories": list(tools.keys()),+ "total": sum(len(v) for v in tools.values())+ }++ if action == "list_models":+ from finagent_core.core_agent import CoreAgent+ agent = CoreAgent(api_keys=api_keys)+ providers = agent.list_available_models()+ return {"success": True, "providers": providers, "count": len(providers)}++ if action == "list_output_models":+ from finagent_core.core_agent import CoreAgent+ agent = CoreAgent(api_keys=api_keys)+ models = agent.list_output_models()+ return {"success": True, "models": models}++ # =========================================================================+ # Unknown Action+ # =========================================================================++ return {"success": False, "error": f"Unknown action: {action}"}+++if __name__ == "__main__":+ result = main()+ print(result)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/paper_trading_bridge.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/paper_trading_bridge.pynew file mode 100644index 000000000..37328e4e3--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/paper_trading_bridge.py@@ -0,0 +1,548 @@+"""+Paper Trading Bridge - Connects Alpha Arena to Rust paper trading module++Provides Python interface to the Rust paper trading commands via Tauri IPC.+Used by AI agents to execute simulated trades.+"""++from typing import Dict, Any, Optional, List+from dataclasses import dataclass, asdict+from datetime import datetime+import json+import logging+import subprocess+import os++logger = logging.getLogger(__name__)+++@dataclass+class Portfolio:+ """Paper trading portfolio"""+ id: str+ name: str+ initial_balance: float+ balance: float+ currency: str = "USD"+ leverage: float = 1.0+ margin_mode: str = "cross"+ fee_rate: float = 0.001+ created_at: str = ""+++@dataclass+class Order:+ """Paper trading order"""+ id: str+ portfolio_id: str+ symbol: str+ side: str # "buy" | "sell"+ order_type: str # "market" | "limit" | "stop" | "stop_limit"+ quantity: float+ price: Optional[float] = None+ stop_price: Optional[float] = None+ filled_qty: float = 0+ avg_price: Optional[float] = None+ status: str = "pending"+ reduce_only: bool = False+ created_at: str = ""+ filled_at: Optional[str] = None+++@dataclass+class Position:+ """Paper trading position"""+ id: str+ portfolio_id: str+ symbol: str+ side: str # "long" | "short"+ quantity: float+ entry_price: float+ current_price: float+ unrealized_pnl: float = 0+ realized_pnl: float = 0+ leverage: float = 1.0+ liquidation_price: Optional[float] = None+ opened_at: str = ""+++@dataclass+class Trade:+ """Executed trade"""+ id: str+ portfolio_id: str+ order_id: str+ symbol: str+ side: str+ price: float+ quantity: float+ fee: float+ pnl: float+ timestamp: str+++@dataclass+class Stats:+ """Portfolio statistics"""+ total_pnl: float+ win_rate: float+ total_trades: int+ winning_trades: int+ losing_trades: int+ largest_win: float+ largest_loss: float+++class PaperTradingBridge:+ """+ Bridge to Rust paper trading module.++ In Tauri context, this calls the pt_* commands.+ For testing/standalone, can simulate locally.+ """++ def __init__(self, use_tauri: bool = True):+ """+ Initialize bridge.++ Args:+ use_tauri: If True, calls Rust commands. If False, uses local simulation.+ """+ self.use_tauri = use_tauri+ self._local_portfolios: Dict[str, Portfolio] = {}+ self._local_orders: Dict[str, Order] = {}+ self._local_positions: Dict[str, Position] = {}+ self._local_trades: List[Trade] = []++ # =========================================================================+ # Portfolio Operations+ # =========================================================================++ def create_portfolio(+ self,+ name: str,+ balance: float = 100000.0,+ currency: str = "USD",+ leverage: float = 1.0,+ margin_mode: str = "cross",+ fee_rate: float = 0.001+ ) -> Portfolio:+ """Create a new paper trading portfolio"""+ if self.use_tauri:+ result = self._invoke_tauri("pt_create_portfolio", {+ "name": name,+ "balance": balance,+ "currency": currency,+ "leverage": leverage,+ "margin_mode": margin_mode,+ "fee_rate": fee_rate+ })+ return Portfolio(**result)+ else:+ # Local simulation+ import uuid+ portfolio = Portfolio(+ id=str(uuid.uuid4()),+ name=name,+ initial_balance=balance,+ balance=balance,+ currency=currency,+ leverage=leverage,+ margin_mode=margin_mode,+ fee_rate=fee_rate,+ created_at=datetime.utcnow().isoformat()+ )+ self._local_portfolios[portfolio.id] = portfolio+ return portfolio++ def get_portfolio(self, portfolio_id: str) -> Optional[Portfolio]:+ """Get portfolio by ID"""+ if self.use_tauri:+ result = self._invoke_tauri("pt_get_portfolio", {"id": portfolio_id})+ return Portfolio(**result) if result else None+ else:+ return self._local_portfolios.get(portfolio_id)++ def list_portfolios(self) -> List[Portfolio]:+ """List all portfolios"""+ if self.use_tauri:+ result = self._invoke_tauri("pt_list_portfolios", {})+ return [Portfolio(**p) for p in result]+ else:+ return list(self._local_portfolios.values())++ def delete_portfolio(self, portfolio_id: str) -> bool:+ """Delete a portfolio"""+ if self.use_tauri:+ self._invoke_tauri("pt_delete_portfolio", {"id": portfolio_id})+ return True+ else:+ if portfolio_id in self._local_portfolios:+ del self._local_portfolios[portfolio_id]+ return True+ return False++ def reset_portfolio(self, portfolio_id: str) -> Portfolio:+ """Reset portfolio to initial state"""+ if self.use_tauri:+ result = self._invoke_tauri("pt_reset_portfolio", {"id": portfolio_id})+ return Portfolio(**result)+ else:+ portfolio = self._local_portfolios.get(portfolio_id)+ if portfolio:+ portfolio.balance = portfolio.initial_balance+ # Clear positions and orders for this portfolio+ self._local_orders = {k: v for k, v in self._local_orders.items()+ if v.portfolio_id != portfolio_id}+ self._local_positions = {k: v for k, v in self._local_positions.items()+ if v.portfolio_id != portfolio_id}+ return portfolio+ raise ValueError(f"Portfolio not found: {portfolio_id}")++ # =========================================================================+ # Order Operations+ # =========================================================================++ def place_order(+ self,+ portfolio_id: str,+ symbol: str,+ side: str,+ order_type: str = "market",+ quantity: float = 1.0,+ price: Optional[float] = None,+ stop_price: Optional[float] = None,+ reduce_only: bool = False+ ) -> Order:+ """Place a paper trading order"""+ if self.use_tauri:+ result = self._invoke_tauri("pt_place_order", {+ "portfolio_id": portfolio_id,+ "symbol": symbol,+ "side": side,+ "order_type": order_type,+ "quantity": quantity,+ "price": price,+ "stop_price": stop_price,+ "reduce_only": reduce_only+ })+ return Order(**result)+ else:+ import uuid+ order = Order(+ id=str(uuid.uuid4()),+ portfolio_id=portfolio_id,+ symbol=symbol,+ side=side,+ order_type=order_type,+ quantity=quantity,+ price=price,+ stop_price=stop_price,+ reduce_only=reduce_only,+ created_at=datetime.utcnow().isoformat()+ )+ self._local_orders[order.id] = order+ return order++ def cancel_order(self, order_id: str) -> bool:+ """Cancel an order"""+ if self.use_tauri:+ self._invoke_tauri("pt_cancel_order", {"order_id": order_id})+ return True+ else:+ order = self._local_orders.get(order_id)+ if order and order.status == "pending":+ order.status = "cancelled"+ return True+ return False++ def get_orders(self, portfolio_id: str, status: Optional[str] = None) -> List[Order]:+ """Get orders for portfolio"""+ if self.use_tauri:+ result = self._invoke_tauri("pt_get_orders", {+ "portfolio_id": portfolio_id,+ "status": status+ })+ return [Order(**o) for o in result]+ else:+ orders = [o for o in self._local_orders.values()+ if o.portfolio_id == portfolio_id]+ if status:+ orders = [o for o in orders if o.status == status]+ return orders++ def fill_order(+ self,+ order_id: str,+ fill_price: float,+ fill_qty: Optional[float] = None+ ) -> Trade:+ """Fill an order at given price"""+ if self.use_tauri:+ result = self._invoke_tauri("pt_fill_order", {+ "order_id": order_id,+ "fill_price": fill_price,+ "fill_qty": fill_qty+ })+ return Trade(**result)+ else:+ order = self._local_orders.get(order_id)+ if not order:+ raise ValueError(f"Order not found: {order_id}")++ import uuid+ qty = fill_qty or (order.quantity - order.filled_qty)+ fee = qty * fill_price * 0.001++ trade = Trade(+ id=str(uuid.uuid4()),+ portfolio_id=order.portfolio_id,+ order_id=order_id,+ symbol=order.symbol,+ side=order.side,+ price=fill_price,+ quantity=qty,+ fee=fee,+ pnl=0, # Would calculate based on position+ timestamp=datetime.utcnow().isoformat()+ )++ order.filled_qty += qty+ order.avg_price = fill_price+ order.status = "filled" if order.filled_qty >= order.quantity else "partial"+ order.filled_at = trade.timestamp++ self._local_trades.append(trade)+ return trade++ # =========================================================================+ # Position Operations+ # =========================================================================++ def get_positions(self, portfolio_id: str) -> List[Position]:+ """Get positions for portfolio"""+ if self.use_tauri:+ result = self._invoke_tauri("pt_get_positions", {"portfolio_id": portfolio_id})+ return [Position(**p) for p in result]+ else:+ return [p for p in self._local_positions.values()+ if p.portfolio_id == portfolio_id]++ def update_position_price(self, portfolio_id: str, symbol: str, price: float) -> bool:+ """Update current price for a position"""+ if self.use_tauri:+ self._invoke_tauri("pt_update_price", {+ "portfolio_id": portfolio_id,+ "symbol": symbol,+ "price": price+ })+ return True+ else:+ for pos in self._local_positions.values():+ if pos.portfolio_id == portfolio_id and pos.symbol == symbol:+ pos.current_price = price+ if pos.side == "long":+ pos.unrealized_pnl = (price - pos.entry_price) * pos.quantity+ else:+ pos.unrealized_pnl = (pos.entry_price - price) * pos.quantity+ return True+ return False++ # =========================================================================+ # Trade & Stats Operations+ # =========================================================================++ def get_trades(self, portfolio_id: str, limit: int = 50) -> List[Trade]:+ """Get trades for portfolio"""+ if self.use_tauri:+ result = self._invoke_tauri("pt_get_trades", {+ "portfolio_id": portfolio_id,+ "limit": limit+ })+ return [Trade(**t) for t in result]+ else:+ trades = [t for t in self._local_trades if t.portfolio_id == portfolio_id]+ return trades[-limit:]++ def get_stats(self, portfolio_id: str) -> Stats:+ """Get portfolio statistics"""+ if self.use_tauri:+ result = self._invoke_tauri("pt_get_stats", {"portfolio_id": portfolio_id})+ return Stats(**result)+ else:+ trades = [t for t in self._local_trades if t.portfolio_id == portfolio_id]+ if not trades:+ return Stats(+ total_pnl=0,+ win_rate=0,+ total_trades=0,+ winning_trades=0,+ losing_trades=0,+ largest_win=0,+ largest_loss=0+ )++ total_pnl = sum(t.pnl for t in trades)+ winning = [t for t in trades if t.pnl > 0]+ losing = [t for t in trades if t.pnl < 0]++ return Stats(+ total_pnl=total_pnl,+ win_rate=(len(winning) / len(trades) * 100) if trades else 0,+ total_trades=len(trades),+ winning_trades=len(winning),+ losing_trades=len(losing),+ largest_win=max((t.pnl for t in trades), default=0),+ largest_loss=min((t.pnl for t in trades), default=0)+ )++ # =========================================================================+ # Helper Methods+ # =========================================================================++ def _invoke_tauri(self, command: str, args: Dict[str, Any]) -> Any:+ """+ Invoke Tauri command.++ In actual Tauri context, this is handled via IPC.+ For Python-only execution, we simulate or raise.+ """+ # This would be called from Rust via tauri::invoke+ # For now, log and simulate+ logger.debug(f"Tauri invoke: {command} with args: {args}")++ # In real implementation, Rust calls Python with the result+ # For standalone Python testing, raise to indicate Tauri needed+ raise NotImplementedError(+ f"Tauri command {command} requires Rust runtime. "+ "Use use_tauri=False for local simulation."+ )+++# =============================================================================+# Convenience Functions for Alpha Arena+# =============================================================================++_bridge: Optional[PaperTradingBridge] = None+++def get_bridge(use_tauri: bool = False) -> PaperTradingBridge:+ """Get singleton bridge instance"""+ global _bridge+ if _bridge is None:+ _bridge = PaperTradingBridge(use_tauri=use_tauri)+ return _bridge+++def execute_trade(+ portfolio_id: str,+ symbol: str,+ action: str,+ quantity: float,+ current_price: float+) -> Dict[str, Any]:+ """+ Execute a trade for Alpha Arena.++ Args:+ portfolio_id: Portfolio to trade in+ symbol: Symbol to trade+ action: "buy" or "sell"+ quantity: Quantity to trade+ current_price: Current market price++ Returns:+ Trade result dict+ """+ bridge = get_bridge()++ try:+ # Place and immediately fill market order+ order = bridge.place_order(+ portfolio_id=portfolio_id,+ symbol=symbol,+ side=action,+ order_type="market",+ quantity=quantity+ )++ trade = bridge.fill_order(order.id, current_price)++ return {+ "success": True,+ "order_id": order.id,+ "trade_id": trade.id,+ "symbol": symbol,+ "side": action,+ "quantity": quantity,+ "price": current_price,+ "pnl": trade.pnl,+ "fee": trade.fee+ }++ except Exception as e:+ return {+ "success": False,+ "error": str(e),+ "symbol": symbol,+ "action": action+ }+++def get_portfolio_value(portfolio_id: str) -> Dict[str, Any]:+ """Get current portfolio value for Alpha Arena"""+ bridge = get_bridge()++ try:+ portfolio = bridge.get_portfolio(portfolio_id)+ positions = bridge.get_positions(portfolio_id)++ if not portfolio:+ return {"success": False, "error": "Portfolio not found"}++ positions_value = sum(p.quantity * p.current_price for p in positions)+ total_value = portfolio.balance + positions_value++ return {+ "success": True,+ "portfolio_id": portfolio_id,+ "cash": portfolio.balance,+ "positions_value": positions_value,+ "total_value": total_value,+ "initial_balance": portfolio.initial_balance,+ "total_pnl": total_value - portfolio.initial_balance,+ "return_pct": ((total_value / portfolio.initial_balance) - 1) * 100+ }++ except Exception as e:+ return {"success": False, "error": str(e)}+++def get_positions_summary(portfolio_id: str) -> Dict[str, Any]:+ """Get positions summary for Alpha Arena"""+ bridge = get_bridge()++ try:+ positions = bridge.get_positions(portfolio_id)++ return {+ "success": True,+ "portfolio_id": portfolio_id,+ "positions_count": len(positions),+ "positions": [+ {+ "symbol": p.symbol,+ "side": p.side,+ "quantity": p.quantity,+ "entry_price": p.entry_price,+ "current_price": p.current_price,+ "unrealized_pnl": p.unrealized_pnl,+ "return_pct": ((p.current_price / p.entry_price) - 1) * 100 if p.side == "long"+ else ((p.entry_price / p.current_price) - 1) * 100+ }+ for p in positions+ ]+ }++ except Exception as e:+ return {"success": False, "error": str(e)}diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/models_registry.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/models_registry.pyindex f753d66f7..eaa8784a6 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/models_registry.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/models_registry.py@@ -211,14 +211,6 @@ class ModelsRegistry:"default_model": "anthropic/claude-3.5-sonnet",},- # LiteLLM (Multi-provider wrapper)- "litellm": {- "class": "agno.models.litellm.LiteLLM",- "models": [],- "api_key_env": None,- "default_model": None,- },-# Portkey (Multi-provider)"portkey": {"class": "agno.models.portkey.Portkey",diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/repositories.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/repositories.pynew file mode 100644index 000000000..22059be23--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/repositories.py@@ -0,0 +1,559 @@+"""+Repository Pattern - Clean database access layer++Provides abstraction over data storage for agents.+Similar to ValueCell's repository pattern.+"""++from abc import ABC, abstractmethod+from typing import Dict, Any, Optional, List, Generic, TypeVar+from dataclasses import dataclass, asdict+from datetime import datetime+import json+import sqlite3+from pathlib import Path+import logging++logger = logging.getLogger(__name__)++T = TypeVar('T')+++class Repository(ABC, Generic[T]):+ """Abstract base repository"""++ @abstractmethod+ def create(self, entity: T) -> str:+ """Create a new entity"""+ pass++ @abstractmethod+ def get(self, id: str) -> Optional[T]:+ """Get entity by ID"""+ pass++ @abstractmethod+ def update(self, id: str, entity: T) -> bool:+ """Update an entity"""+ pass++ @abstractmethod+ def delete(self, id: str) -> bool:+ """Delete an entity"""+ pass++ @abstractmethod+ def list(self, **filters) -> List[T]:+ """List entities with optional filters"""+ pass+++# =============================================================================+# Entity Models+# =============================================================================++@dataclass+class AgentSession:+ """Agent session entity"""+ id: str+ agent_id: str+ user_id: Optional[str]+ started_at: str+ ended_at: Optional[str] = None+ messages: List[Dict[str, Any]] = None+ context: Dict[str, Any] = None+ status: str = "active"++ def __post_init__(self):+ if self.messages is None:+ self.messages = []+ if self.context is None:+ self.context = {}+++@dataclass+class AgentMemory:+ """Agent memory entity"""+ id: str+ agent_id: str+ user_id: Optional[str]+ memory_type: str # "fact", "preference", "context", "long_term"+ content: str+ metadata: Dict[str, Any] = None+ created_at: str = ""+ importance: float = 0.5+ last_accessed: str = ""++ def __post_init__(self):+ if self.metadata is None:+ self.metadata = {}+ if not self.created_at:+ self.created_at = datetime.utcnow().isoformat()+ if not self.last_accessed:+ self.last_accessed = self.created_at+++@dataclass+class TradeDecision:+ """Trading decision from AI agent"""+ id: str+ competition_id: str+ model_name: str+ cycle_number: int+ symbol: str+ action: str # "buy", "sell", "hold"+ quantity: float+ price: Optional[float]+ reasoning: str+ confidence: float+ timestamp: str+++@dataclass+class PerformanceSnapshot:+ """Performance snapshot at a point in time"""+ id: str+ competition_id: str+ model_name: str+ cycle_number: int+ portfolio_value: float+ cash: float+ positions_value: float+ total_pnl: float+ return_pct: float+ timestamp: str+++# =============================================================================+# SQLite Repository Implementations+# =============================================================================++class SQLiteRepository(Repository[T]):+ """Base SQLite repository with connection management"""++ def __init__(self, db_path: Optional[Path] = None):+ if db_path is None:+ # Default to user data directory+ import os+ app_data = os.getenv('APPDATA', os.path.expanduser('~'))+ db_path = Path(app_data) / 'fincept-terminal' / 'agents.db'++ self.db_path = Path(db_path)+ self.db_path.parent.mkdir(parents=True, exist_ok=True)+ self._init_db()++ def _get_connection(self) -> sqlite3.Connection:+ conn = sqlite3.connect(str(self.db_path))+ conn.row_factory = sqlite3.Row+ return conn++ @abstractmethod+ def _init_db(self):+ """Initialize database tables"""+ pass++ def _execute(self, query: str, params: tuple = ()) -> List[sqlite3.Row]:+ with self._get_connection() as conn:+ cursor = conn.execute(query, params)+ return cursor.fetchall()++ def _execute_one(self, query: str, params: tuple = ()) -> Optional[sqlite3.Row]:+ rows = self._execute(query, params)+ return rows[0] if rows else None++ def _execute_write(self, query: str, params: tuple = ()) -> int:+ with self._get_connection() as conn:+ cursor = conn.execute(query, params)+ conn.commit()+ return cursor.lastrowid+++class AgentSessionRepository(SQLiteRepository[AgentSession]):+ """Repository for agent sessions"""++ def _init_db(self):+ with self._get_connection() as conn:+ conn.execute("""+ CREATE TABLE IF NOT EXISTS agent_sessions (+ id TEXT PRIMARY KEY,+ agent_id TEXT NOT NULL,+ user_id TEXT,+ started_at TEXT NOT NULL,+ ended_at TEXT,+ messages TEXT NOT NULL DEFAULT '[]',+ context TEXT NOT NULL DEFAULT '{}',+ status TEXT DEFAULT 'active'+ )+ """)+ conn.execute("CREATE INDEX IF NOT EXISTS idx_sessions_agent ON agent_sessions(agent_id)")+ conn.execute("CREATE INDEX IF NOT EXISTS idx_sessions_user ON agent_sessions(user_id)")++ def create(self, entity: AgentSession) -> str:+ self._execute_write(+ """INSERT INTO agent_sessions (id, agent_id, user_id, started_at, ended_at, messages, context, status)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",+ (entity.id, entity.agent_id, entity.user_id, entity.started_at, entity.ended_at,+ json.dumps(entity.messages), json.dumps(entity.context), entity.status)+ )+ return entity.id++ def get(self, id: str) -> Optional[AgentSession]:+ row = self._execute_one("SELECT * FROM agent_sessions WHERE id = ?", (id,))+ if row:+ return AgentSession(+ id=row['id'],+ agent_id=row['agent_id'],+ user_id=row['user_id'],+ started_at=row['started_at'],+ ended_at=row['ended_at'],+ messages=json.loads(row['messages']),+ context=json.loads(row['context']),+ status=row['status']+ )+ return None++ def update(self, id: str, entity: AgentSession) -> bool:+ self._execute_write(+ """UPDATE agent_sessions SET ended_at = ?, messages = ?, context = ?, status = ? WHERE id = ?""",+ (entity.ended_at, json.dumps(entity.messages), json.dumps(entity.context), entity.status, id)+ )+ return True++ def delete(self, id: str) -> bool:+ self._execute_write("DELETE FROM agent_sessions WHERE id = ?", (id,))+ return True++ def list(self, agent_id: str = None, user_id: str = None, status: str = None, limit: int = 50) -> List[AgentSession]:+ query = "SELECT * FROM agent_sessions WHERE 1=1"+ params = []++ if agent_id:+ query += " AND agent_id = ?"+ params.append(agent_id)+ if user_id:+ query += " AND user_id = ?"+ params.append(user_id)+ if status:+ query += " AND status = ?"+ params.append(status)++ query += " ORDER BY started_at DESC LIMIT ?"+ params.append(limit)++ rows = self._execute(query, tuple(params))+ return [AgentSession(+ id=row['id'],+ agent_id=row['agent_id'],+ user_id=row['user_id'],+ started_at=row['started_at'],+ ended_at=row['ended_at'],+ messages=json.loads(row['messages']),+ context=json.loads(row['context']),+ status=row['status']+ ) for row in rows]++ def add_message(self, session_id: str, role: str, content: str) -> bool:+ """Add a message to session"""+ session = self.get(session_id)+ if session:+ session.messages.append({+ "role": role,+ "content": content,+ "timestamp": datetime.utcnow().isoformat()+ })+ return self.update(session_id, session)+ return False+++class AgentMemoryRepository(SQLiteRepository[AgentMemory]):+ """Repository for agent memories"""++ def _init_db(self):+ with self._get_connection() as conn:+ conn.execute("""+ CREATE TABLE IF NOT EXISTS agent_memories (+ id TEXT PRIMARY KEY,+ agent_id TEXT NOT NULL,+ user_id TEXT,+ memory_type TEXT NOT NULL,+ content TEXT NOT NULL,+ metadata TEXT NOT NULL DEFAULT '{}',+ created_at TEXT NOT NULL,+ importance REAL DEFAULT 0.5,+ last_accessed TEXT+ )+ """)+ conn.execute("CREATE INDEX IF NOT EXISTS idx_memories_agent ON agent_memories(agent_id)")+ conn.execute("CREATE INDEX IF NOT EXISTS idx_memories_user ON agent_memories(user_id)")+ conn.execute("CREATE INDEX IF NOT EXISTS idx_memories_type ON agent_memories(memory_type)")++ def create(self, entity: AgentMemory) -> str:+ self._execute_write(+ """INSERT INTO agent_memories (id, agent_id, user_id, memory_type, content, metadata, created_at, importance, last_accessed)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",+ (entity.id, entity.agent_id, entity.user_id, entity.memory_type, entity.content,+ json.dumps(entity.metadata), entity.created_at, entity.importance, entity.last_accessed)+ )+ return entity.id++ def get(self, id: str) -> Optional[AgentMemory]:+ row = self._execute_one("SELECT * FROM agent_memories WHERE id = ?", (id,))+ if row:+ return AgentMemory(+ id=row['id'],+ agent_id=row['agent_id'],+ user_id=row['user_id'],+ memory_type=row['memory_type'],+ content=row['content'],+ metadata=json.loads(row['metadata']),+ created_at=row['created_at'],+ importance=row['importance'],+ last_accessed=row['last_accessed']+ )+ return None++ def update(self, id: str, entity: AgentMemory) -> bool:+ self._execute_write(+ """UPDATE agent_memories SET content = ?, metadata = ?, importance = ?, last_accessed = ? WHERE id = ?""",+ (entity.content, json.dumps(entity.metadata), entity.importance, datetime.utcnow().isoformat(), id)+ )+ return True++ def delete(self, id: str) -> bool:+ self._execute_write("DELETE FROM agent_memories WHERE id = ?", (id,))+ return True++ def list(self, agent_id: str = None, user_id: str = None, memory_type: str = None, limit: int = 100) -> List[AgentMemory]:+ query = "SELECT * FROM agent_memories WHERE 1=1"+ params = []++ if agent_id:+ query += " AND agent_id = ?"+ params.append(agent_id)+ if user_id:+ query += " AND user_id = ?"+ params.append(user_id)+ if memory_type:+ query += " AND memory_type = ?"+ params.append(memory_type)++ query += " ORDER BY importance DESC, last_accessed DESC LIMIT ?"+ params.append(limit)++ rows = self._execute(query, tuple(params))+ return [AgentMemory(+ id=row['id'],+ agent_id=row['agent_id'],+ user_id=row['user_id'],+ memory_type=row['memory_type'],+ content=row['content'],+ metadata=json.loads(row['metadata']),+ created_at=row['created_at'],+ importance=row['importance'],+ last_accessed=row['last_accessed']+ ) for row in rows]++ def search(self, query: str, agent_id: str = None, limit: int = 10) -> List[AgentMemory]:+ """Simple text search in memories"""+ sql = "SELECT * FROM agent_memories WHERE content LIKE ?"+ params = [f"%{query}%"]++ if agent_id:+ sql += " AND agent_id = ?"+ params.append(agent_id)++ sql += " ORDER BY importance DESC LIMIT ?"+ params.append(limit)++ rows = self._execute(sql, tuple(params))+ return [AgentMemory(+ id=row['id'],+ agent_id=row['agent_id'],+ user_id=row['user_id'],+ memory_type=row['memory_type'],+ content=row['content'],+ metadata=json.loads(row['metadata']),+ created_at=row['created_at'],+ importance=row['importance'],+ last_accessed=row['last_accessed']+ ) for row in rows]+++class TradeDecisionRepository(SQLiteRepository[TradeDecision]):+ """Repository for trade decisions"""++ def _init_db(self):+ with self._get_connection() as conn:+ conn.execute("""+ CREATE TABLE IF NOT EXISTS trade_decisions (+ id TEXT PRIMARY KEY,+ competition_id TEXT NOT NULL,+ model_name TEXT NOT NULL,+ cycle_number INTEGER NOT NULL,+ symbol TEXT NOT NULL,+ action TEXT NOT NULL,+ quantity REAL NOT NULL,+ price REAL,+ reasoning TEXT,+ confidence REAL DEFAULT 0.5,+ timestamp TEXT NOT NULL+ )+ """)+ conn.execute("CREATE INDEX IF NOT EXISTS idx_decisions_competition ON trade_decisions(competition_id)")+ conn.execute("CREATE INDEX IF NOT EXISTS idx_decisions_model ON trade_decisions(model_name)")+ conn.execute("CREATE INDEX IF NOT EXISTS idx_decisions_cycle ON trade_decisions(cycle_number)")++ def create(self, entity: TradeDecision) -> str:+ self._execute_write(+ """INSERT INTO trade_decisions (id, competition_id, model_name, cycle_number, symbol, action, quantity, price, reasoning, confidence, timestamp)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",+ (entity.id, entity.competition_id, entity.model_name, entity.cycle_number, entity.symbol,+ entity.action, entity.quantity, entity.price, entity.reasoning, entity.confidence, entity.timestamp)+ )+ return entity.id++ def get(self, id: str) -> Optional[TradeDecision]:+ row = self._execute_one("SELECT * FROM trade_decisions WHERE id = ?", (id,))+ if row:+ return TradeDecision(**dict(row))+ return None++ def update(self, id: str, entity: TradeDecision) -> bool:+ self._execute_write(+ """UPDATE trade_decisions SET action = ?, quantity = ?, price = ?, reasoning = ?, confidence = ? WHERE id = ?""",+ (entity.action, entity.quantity, entity.price, entity.reasoning, entity.confidence, id)+ )+ return True++ def delete(self, id: str) -> bool:+ self._execute_write("DELETE FROM trade_decisions WHERE id = ?", (id,))+ return True++ def list(self, competition_id: str = None, model_name: str = None, cycle_number: int = None, limit: int = 100) -> List[TradeDecision]:+ query = "SELECT * FROM trade_decisions WHERE 1=1"+ params = []++ if competition_id:+ query += " AND competition_id = ?"+ params.append(competition_id)+ if model_name:+ query += " AND model_name = ?"+ params.append(model_name)+ if cycle_number is not None:+ query += " AND cycle_number = ?"+ params.append(cycle_number)++ query += " ORDER BY timestamp DESC LIMIT ?"+ params.append(limit)++ rows = self._execute(query, tuple(params))+ return [TradeDecision(**dict(row)) for row in rows]+++class PerformanceSnapshotRepository(SQLiteRepository[PerformanceSnapshot]):+ """Repository for performance snapshots"""++ def _init_db(self):+ with self._get_connection() as conn:+ conn.execute("""+ CREATE TABLE IF NOT EXISTS performance_snapshots (+ id TEXT PRIMARY KEY,+ competition_id TEXT NOT NULL,+ model_name TEXT NOT NULL,+ cycle_number INTEGER NOT NULL,+ portfolio_value REAL NOT NULL,+ cash REAL NOT NULL,+ positions_value REAL NOT NULL,+ total_pnl REAL DEFAULT 0,+ return_pct REAL DEFAULT 0,+ timestamp TEXT NOT NULL+ )+ """)+ conn.execute("CREATE INDEX IF NOT EXISTS idx_snapshots_competition ON performance_snapshots(competition_id)")+ conn.execute("CREATE INDEX IF NOT EXISTS idx_snapshots_model ON performance_snapshots(model_name)")++ def create(self, entity: PerformanceSnapshot) -> str:+ self._execute_write(+ """INSERT INTO performance_snapshots (id, competition_id, model_name, cycle_number, portfolio_value, cash, positions_value, total_pnl, return_pct, timestamp)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",+ (entity.id, entity.competition_id, entity.model_name, entity.cycle_number, entity.portfolio_value,+ entity.cash, entity.positions_value, entity.total_pnl, entity.return_pct, entity.timestamp)+ )+ return entity.id++ def get(self, id: str) -> Optional[PerformanceSnapshot]:+ row = self._execute_one("SELECT * FROM performance_snapshots WHERE id = ?", (id,))+ if row:+ return PerformanceSnapshot(**dict(row))+ return None++ def update(self, id: str, entity: PerformanceSnapshot) -> bool:+ self._execute_write(+ """UPDATE performance_snapshots SET portfolio_value = ?, cash = ?, positions_value = ?, total_pnl = ?, return_pct = ? WHERE id = ?""",+ (entity.portfolio_value, entity.cash, entity.positions_value, entity.total_pnl, entity.return_pct, id)+ )+ return True++ def delete(self, id: str) -> bool:+ self._execute_write("DELETE FROM performance_snapshots WHERE id = ?", (id,))+ return True++ def list(self, competition_id: str = None, model_name: str = None, limit: int = 500) -> List[PerformanceSnapshot]:+ query = "SELECT * FROM performance_snapshots WHERE 1=1"+ params = []++ if competition_id:+ query += " AND competition_id = ?"+ params.append(competition_id)+ if model_name:+ query += " AND model_name = ?"+ params.append(model_name)++ query += " ORDER BY cycle_number ASC LIMIT ?"+ params.append(limit)++ rows = self._execute(query, tuple(params))+ return [PerformanceSnapshot(**dict(row)) for row in rows]+++# =============================================================================+# Repository Factory+# =============================================================================++class RepositoryFactory:+ """Factory for creating repository instances"""++ _instances: Dict[str, Repository] = {}++ @classmethod+ def get_session_repository(cls, db_path: Path = None) -> AgentSessionRepository:+ key = f"session:{db_path}"+ if key not in cls._instances:+ cls._instances[key] = AgentSessionRepository(db_path)+ return cls._instances[key]++ @classmethod+ def get_memory_repository(cls, db_path: Path = None) -> AgentMemoryRepository:+ key = f"memory:{db_path}"+ if key not in cls._instances:+ cls._instances[key] = AgentMemoryRepository(db_path)+ return cls._instances[key]++ @classmethod+ def get_trade_decision_repository(cls, db_path: Path = None) -> TradeDecisionRepository:+ key = f"trade_decision:{db_path}"+ if key not in cls._instances:+ cls._instances[key] = TradeDecisionRepository(db_path)+ return cls._instances[key]++ @classmethod+ def get_performance_repository(cls, db_path: Path = None) -> PerformanceSnapshotRepository:+ key = f"performance:{db_path}"+ if key not in cls._instances:+ cls._instances[key] = PerformanceSnapshotRepository(db_path)+ return cls._instances[key]++ @classmethod+ def clear_instances(cls):+ """Clear all cached instances"""+ cls._instances.clear()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/super_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/super_agent.pynew file mode 100644index 000000000..c7d505d38--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/super_agent.py@@ -0,0 +1,548 @@+"""+SuperAgent - Triage routing for query distribution++Routes queries to appropriate sub-agents based on intent classification.+Similar to ValueCell's agent orchestration pattern.+"""++import re+from typing import Dict, Any, Optional, List, Callable+from dataclasses import dataclass, field+from enum import Enum+import logging++logger = logging.getLogger(__name__)+++class QueryIntent(Enum):+ """Classified query intents"""+ TRADING = "trading"+ PORTFOLIO = "portfolio"+ ANALYSIS = "analysis"+ RISK = "risk"+ NEWS = "news"+ GEOPOLITICS = "geopolitics"+ ECONOMICS = "economics"+ RESEARCH = "research"+ GENERAL = "general"+++@dataclass+class RouteConfig:+ """Configuration for a route"""+ intent: QueryIntent+ agent_id: str+ keywords: List[str] = field(default_factory=list)+ patterns: List[str] = field(default_factory=list)+ priority: int = 0+ config_override: Dict[str, Any] = field(default_factory=dict)+++@dataclass+class RoutingResult:+ """Result of routing decision"""+ intent: QueryIntent+ agent_id: str+ confidence: float+ config: Dict[str, Any]+ matched_keywords: List[str] = field(default_factory=list)+ matched_patterns: List[str] = field(default_factory=list)+++class IntentClassifier:+ """+ Classifies query intent using keyword matching and patterns.+ Can be extended with ML-based classification.+ """++ # Default keyword mappings+ DEFAULT_KEYWORDS = {+ QueryIntent.TRADING: [+ "buy", "sell", "trade", "order", "position", "long", "short",+ "stop loss", "take profit", "limit order", "market order",+ "entry", "exit", "fill", "execute"+ ],+ QueryIntent.PORTFOLIO: [+ "portfolio", "holdings", "allocation", "rebalance", "diversify",+ "weight", "exposure", "balance", "assets", "positions"+ ],+ QueryIntent.ANALYSIS: [+ "analyze", "analysis", "valuation", "dcf", "fair value",+ "fundamental", "technical", "chart", "indicator", "pattern",+ "support", "resistance", "trend"+ ],+ QueryIntent.RISK: [+ "risk", "var", "volatility", "drawdown", "sharpe", "beta",+ "correlation", "hedge", "exposure", "stress test", "scenario"+ ],+ QueryIntent.NEWS: [+ "news", "headline", "announcement", "earnings", "report",+ "press release", "update", "breaking"+ ],+ QueryIntent.GEOPOLITICS: [+ "geopolitical", "war", "conflict", "sanction", "trade war",+ "election", "policy", "government", "diplomatic", "military"+ ],+ QueryIntent.ECONOMICS: [+ "gdp", "inflation", "interest rate", "fed", "central bank",+ "employment", "jobs", "cpi", "ppi", "economic"+ ],+ QueryIntent.RESEARCH: [+ "research", "deep dive", "investigate", "study", "comprehensive",+ "detailed", "in-depth", "explore"+ ]+ }++ # Default patterns+ DEFAULT_PATTERNS = {+ QueryIntent.TRADING: [+ r'\b(buy|sell)\s+\d+',+ r'\b(long|short)\s+[A-Z]{1,5}\b',+ r'place\s+(market|limit)\s+order'+ ],+ QueryIntent.ANALYSIS: [+ r'analyze\s+[A-Z]{1,5}',+ r'what.*think.*about\s+[A-Z]{1,5}',+ r'[A-Z]{1,5}\s+(outlook|forecast|prediction)'+ ],+ QueryIntent.PORTFOLIO: [+ r'my\s+portfolio',+ r'rebalance.*portfolio',+ r'portfolio.*allocation'+ ]+ }++ def __init__(+ self,+ custom_keywords: Dict[QueryIntent, List[str]] = None,+ custom_patterns: Dict[QueryIntent, List[str]] = None+ ):+ self.keywords = {**self.DEFAULT_KEYWORDS}+ self.patterns = {**self.DEFAULT_PATTERNS}++ if custom_keywords:+ for intent, kws in custom_keywords.items():+ self.keywords.setdefault(intent, []).extend(kws)++ if custom_patterns:+ for intent, pts in custom_patterns.items():+ self.patterns.setdefault(intent, []).extend(pts)++ # Compile patterns+ self._compiled_patterns = {+ intent: [re.compile(p, re.IGNORECASE) for p in patterns]+ for intent, patterns in self.patterns.items()+ }++ def classify(self, query: str) -> List[tuple[QueryIntent, float, List[str], List[str]]]:+ """+ Classify query intent.++ Returns:+ List of (intent, confidence, matched_keywords, matched_patterns) sorted by confidence+ """+ query_lower = query.lower()+ results = []++ for intent in QueryIntent:+ matched_keywords = []+ matched_patterns = []++ # Check keywords+ if intent in self.keywords:+ for kw in self.keywords[intent]:+ if kw.lower() in query_lower:+ matched_keywords.append(kw)++ # Check patterns+ if intent in self._compiled_patterns:+ for pattern in self._compiled_patterns[intent]:+ if pattern.search(query):+ matched_patterns.append(pattern.pattern)++ # Calculate confidence+ if matched_keywords or matched_patterns:+ keyword_score = len(matched_keywords) * 0.3+ pattern_score = len(matched_patterns) * 0.5+ confidence = min(1.0, keyword_score + pattern_score)+ results.append((intent, confidence, matched_keywords, matched_patterns))++ # Sort by confidence descending+ results.sort(key=lambda x: x[1], reverse=True)++ # If no matches, return GENERAL+ if not results:+ results.append((QueryIntent.GENERAL, 0.1, [], []))++ return results+++class SuperAgent:+ """+ SuperAgent - Routes queries to appropriate sub-agents.++ Features:+ - Intent classification+ - Multi-agent routing+ - Fallback handling+ - Response aggregation+ """++ def __init__(+ self,+ api_keys: Optional[Dict[str, str]] = None,+ routes: Optional[List[RouteConfig]] = None+ ):+ self.api_keys = api_keys or {}+ self.classifier = IntentClassifier()+ self.routes: Dict[QueryIntent, RouteConfig] = {}+ self.fallback_agent_id = "core_agent"++ # Initialize default routes+ self._setup_default_routes()++ # Apply custom routes+ if routes:+ for route in routes:+ self.add_route(route)++ def _setup_default_routes(self) -> None:+ """Setup default routing table"""+ default_routes = [+ RouteConfig(+ intent=QueryIntent.TRADING,+ agent_id="trading_agent",+ keywords=["buy", "sell", "trade"],+ priority=10,+ config_override={"tools": ["yfinance", "calculator"]}+ ),+ RouteConfig(+ intent=QueryIntent.PORTFOLIO,+ agent_id="portfolio_agent",+ keywords=["portfolio", "allocation"],+ priority=9,+ config_override={"tools": ["yfinance", "calculator"]}+ ),+ RouteConfig(+ intent=QueryIntent.ANALYSIS,+ agent_id="analysis_agent",+ keywords=["analyze", "valuation"],+ priority=8,+ config_override={"reasoning": True, "tools": ["yfinance", "duckduckgo"]}+ ),+ RouteConfig(+ intent=QueryIntent.RISK,+ agent_id="risk_agent",+ keywords=["risk", "volatility"],+ priority=8,+ config_override={"tools": ["yfinance", "calculator"]}+ ),+ RouteConfig(+ intent=QueryIntent.NEWS,+ agent_id="news_agent",+ keywords=["news", "headlines"],+ priority=5,+ config_override={"tools": ["duckduckgo"]}+ ),+ RouteConfig(+ intent=QueryIntent.GEOPOLITICS,+ agent_id="geopolitics_agent",+ keywords=["geopolitical", "conflict"],+ priority=5,+ config_override={"tools": ["duckduckgo"]}+ ),+ RouteConfig(+ intent=QueryIntent.ECONOMICS,+ agent_id="economics_agent",+ keywords=["gdp", "inflation"],+ priority=6,+ config_override={"tools": ["duckduckgo", "calculator"]}+ ),+ RouteConfig(+ intent=QueryIntent.RESEARCH,+ agent_id="research_agent",+ keywords=["research", "investigate"],+ priority=7,+ config_override={"reasoning": True, "tools": ["duckduckgo", "yfinance"]}+ ),+ RouteConfig(+ intent=QueryIntent.GENERAL,+ agent_id="core_agent",+ keywords=[],+ priority=0,+ config_override={}+ )+ ]++ for route in default_routes:+ self.routes[route.intent] = route++ def add_route(self, route: RouteConfig) -> None:+ """Add or update a route"""+ self.routes[route.intent] = route+ # Update classifier keywords+ if route.keywords:+ self.classifier.keywords.setdefault(route.intent, []).extend(route.keywords)++ def route(self, query: str) -> RoutingResult:+ """+ Route query to appropriate agent.++ Args:+ query: User query++ Returns:+ RoutingResult with agent info and confidence+ """+ # Classify intent+ classifications = self.classifier.classify(query)++ if not classifications:+ # Fallback to general+ return RoutingResult(+ intent=QueryIntent.GENERAL,+ agent_id=self.fallback_agent_id,+ confidence=0.0,+ config={}+ )++ # Get top classification+ top_intent, confidence, matched_kw, matched_pt = classifications[0]++ # Get route config+ route = self.routes.get(top_intent, self.routes.get(QueryIntent.GENERAL))++ return RoutingResult(+ intent=top_intent,+ agent_id=route.agent_id if route else self.fallback_agent_id,+ confidence=confidence,+ config=route.config_override if route else {},+ matched_keywords=matched_kw,+ matched_patterns=matched_pt+ )++ def route_multi(self, query: str, max_agents: int = 3) -> List[RoutingResult]:+ """+ Route to multiple agents for complex queries.++ Args:+ query: User query+ max_agents: Maximum number of agents to route to++ Returns:+ List of RoutingResults sorted by relevance+ """+ classifications = self.classifier.classify(query)+ results = []++ for intent, confidence, matched_kw, matched_pt in classifications[:max_agents]:+ if confidence < 0.2: # Skip low confidence+ continue++ route = self.routes.get(intent)+ if route:+ results.append(RoutingResult(+ intent=intent,+ agent_id=route.agent_id,+ confidence=confidence,+ config=route.config_override,+ matched_keywords=matched_kw,+ matched_patterns=matched_pt+ ))++ return results++ def execute(+ self,+ query: str,+ session_id: Optional[str] = None,+ context: Optional[Dict[str, Any]] = None+ ) -> Dict[str, Any]:+ """+ Route and execute query.++ Args:+ query: User query+ session_id: Optional session ID+ context: Optional context++ Returns:+ Response from routed agent+ """+ from finagent_core.core_agent import CoreAgent+ from finagent_core.agent_loader import get_loader++ # Route query+ routing = self.route(query)+ logger.info(f"Routed to {routing.agent_id} with confidence {routing.confidence:.2f}")++ # Build config+ config = {+ "model": {"provider": "openai", "model_id": "gpt-4-turbo"},+ "instructions": self._get_instructions_for_intent(routing.intent),+ **routing.config+ }++ # Try to load specific agent+ loader = get_loader()+ try:+ agent = loader.create_agent(routing.agent_id, self.api_keys, config)+ except Exception:+ # Fallback to CoreAgent+ agent = CoreAgent(api_keys=self.api_keys)++ # Execute+ try:+ response = agent.run(query, config, session_id)+ content = agent.get_response_content(response) if hasattr(agent, 'get_response_content') else str(response)++ return {+ "success": True,+ "response": content,+ "routing": {+ "intent": routing.intent.value,+ "agent_id": routing.agent_id,+ "confidence": routing.confidence,+ "matched_keywords": routing.matched_keywords+ }+ }+ except Exception as e:+ return {+ "success": False,+ "error": str(e),+ "routing": {+ "intent": routing.intent.value,+ "agent_id": routing.agent_id,+ "confidence": routing.confidence+ }+ }++ def execute_multi(+ self,+ query: str,+ session_id: Optional[str] = None,+ aggregate: bool = True+ ) -> Dict[str, Any]:+ """+ Execute query on multiple routed agents and aggregate results.++ Args:+ query: User query+ session_id: Optional session ID+ aggregate: Whether to aggregate responses++ Returns:+ Aggregated or individual responses+ """+ routings = self.route_multi(query)++ if not routings:+ return self.execute(query, session_id)++ responses = []+ for routing in routings:+ result = self.execute(query, session_id)+ result["routing"]["priority"] = routing.confidence+ responses.append(result)++ if aggregate and len(responses) > 1:+ # Simple aggregation - combine successful responses+ combined = []+ for resp in responses:+ if resp.get("success"):+ combined.append(f"[{resp['routing']['intent']}]\n{resp['response']}")++ return {+ "success": True,+ "response": "\n\n---\n\n".join(combined),+ "responses": responses,+ "aggregated": True+ }++ return {+ "success": True,+ "responses": responses,+ "aggregated": False+ }++ def _get_instructions_for_intent(self, intent: QueryIntent) -> str:+ """Get specialized instructions for intent"""+ instructions = {+ QueryIntent.TRADING: """You are a trading assistant. Help users with:+- Order placement and execution+- Position management+- Entry/exit strategies+- Market timing""",++ QueryIntent.PORTFOLIO: """You are a portfolio manager. Help users with:+- Portfolio allocation and rebalancing+- Diversification strategies+- Asset selection+- Position sizing""",++ QueryIntent.ANALYSIS: """You are a financial analyst. Help users with:+- Stock valuation (DCF, comparables)+- Fundamental analysis+- Technical analysis+- Market research""",++ QueryIntent.RISK: """You are a risk analyst. Help users with:+- Risk metrics (VaR, Sharpe, etc.)+- Volatility analysis+- Stress testing+- Hedging strategies""",++ QueryIntent.NEWS: """You are a financial news analyst. Help users with:+- Market news and headlines+- Earnings announcements+- Company updates+- Sector news""",++ QueryIntent.GEOPOLITICS: """You are a geopolitical analyst. Help users with:+- Geopolitical risk assessment+- International relations+- Policy analysis+- Global macro trends""",++ QueryIntent.ECONOMICS: """You are an economist. Help users with:+- Economic indicators+- Central bank policy+- Macro trends+- Economic forecasting""",++ QueryIntent.RESEARCH: """You are a research analyst. Help users with:+- Deep-dive research+- Comprehensive analysis+- Industry studies+- Investment theses""",++ QueryIntent.GENERAL: """You are a helpful financial AI assistant."""+ }++ return instructions.get(intent, instructions[QueryIntent.GENERAL])+++# Entry point for Tauri commands+def route_query(query: str, api_keys: Dict[str, str] = None) -> Dict[str, Any]:+ """Route a query and return routing info"""+ agent = SuperAgent(api_keys=api_keys)+ routing = agent.route(query)+ return {+ "success": True,+ "intent": routing.intent.value,+ "agent_id": routing.agent_id,+ "confidence": routing.confidence,+ "matched_keywords": routing.matched_keywords,+ "matched_patterns": routing.matched_patterns,+ "config": routing.config+ }+++def execute_query(+ query: str,+ api_keys: Dict[str, str] = None,+ session_id: str = None+) -> Dict[str, Any]:+ """Route and execute a query"""+ agent = SuperAgent(api_keys=api_keys)+ return agent.execute(query, session_id)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/test_core_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/test_core_agent.pydeleted file mode 100644index f07ead6c1..000000000--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/test_core_agent.py+++ /dev/null@@ -1,249 +0,0 @@-#!/usr/bin/env python3-"""-Test script for CoreAgent - verifies the single agent system works correctly-"""--import sys-import json-from pathlib import Path--# Add parent directory to path-sys.path.insert(0, str(Path(__file__).parent))--from finagent_core.core_agent import main---def test_basic_query():- """Test basic query with minimal config"""- print("=" * 60)- print("TEST 1: Basic Query with OpenAI")- print("=" * 60)-- query_json = json.dumps({- "query": "What is 2+2? Answer in one sentence.",- "session_id": "test-session-1"- })-- config = json.dumps({- "model": {- "provider": "openai",- "model_id": "gpt-3.5-turbo",- "temperature": 0.7- },- "instructions": "You are a helpful math assistant.",- "name": "Math Agent"- })-- # Note: Use a real API key for actual testing- api_keys = json.dumps({- "OPENAI_API_KEY": "sk-test-key-here"- })-- try:- # New pattern: command + args- result = main(["run", query_json, config, api_keys])- result_data = json.loads(result)-- print(f"Success: {result_data.get('success')}")- print(f"Response: {result_data.get('response', 'N/A')}")- print(f"Session ID: {result_data.get('session_id')}")- print()-- except Exception as e:- print(f"Error: {str(e)}")- print()---def test_with_tools():- """Test agent with tools"""- print("=" * 60)- print("TEST 2: Agent with Calculator Tool")- print("=" * 60)-- query_json = json.dumps({- "query": "Calculate the square root of 144",- "session_id": "test-session-2"- })-- config = json.dumps({- "model": {- "provider": "openai",- "model_id": "gpt-3.5-turbo"- },- "instructions": "You are a math assistant with calculator capabilities.",- "tools": ["calculator"],- "name": "Calculator Agent"- })-- api_keys = json.dumps({- "OPENAI_API_KEY": "sk-test-key-here"- })-- try:- # New pattern: command + args- result = main(["run", query_json, config, api_keys])- result_data = json.loads(result)-- print(f"Success: {result_data.get('success')}")- print(f"Response: {result_data.get('response', 'N/A')}")- print()-- except Exception as e:- print(f"Error: {str(e)}")- print()---def test_different_providers():- """Test different LLM providers"""- print("=" * 60)- print("TEST 3: Testing Multiple Providers")- print("=" * 60)-- providers = [- {"provider": "openai", "model_id": "gpt-3.5-turbo", "key_name": "OPENAI_API_KEY"},- {"provider": "anthropic", "model_id": "claude-3-haiku-20240307", "key_name": "ANTHROPIC_API_KEY"},- {"provider": "ollama", "model_id": "llama3.3", "key_name": None},- ]-- for i, provider_config in enumerate(providers, 1):- print(f"\nProvider {i}: {provider_config['provider']}")- print("-" * 40)-- query_json = json.dumps({- "query": "Say hello in exactly 3 words.",- "session_id": f"test-session-{i}"- })-- config = json.dumps({- "model": {- "provider": provider_config["provider"],- "model_id": provider_config["model_id"]- },- "instructions": "You are a concise assistant."- })-- # Build API keys dict (only include if needed)- api_keys_dict = {}- if provider_config["key_name"]:- api_keys_dict[provider_config["key_name"]] = "sk-test-key-here"- api_keys = json.dumps(api_keys_dict)-- try:- # New pattern: command + args- result = main(["run", query_json, config, api_keys])- result_data = json.loads(result)- print(f"[OK] Success: {result_data.get('response', 'N/A')[:50]}...")- except Exception as e:- print(f"[ERROR] Error: {str(e)[:100]}...")---def test_config_changes():- """Test that agent recreates itself when config changes"""- print("=" * 60)- print("TEST 4: Config Change Detection")- print("=" * 60)-- # Same agent, different configs- configs = [- {- "model": {"provider": "openai", "model_id": "gpt-3.5-turbo"},- "instructions": "You are formal and professional.",- "name": "Formal Agent"- },- {- "model": {"provider": "openai", "model_id": "gpt-4"},- "instructions": "You are casual and friendly.",- "name": "Casual Agent"- }- ]-- for i, config in enumerate(configs, 1):- print(f"\nConfig {i}: {config['name']}")- print("-" * 40)-- query_json = json.dumps({- "query": "Introduce yourself.",- "session_id": f"test-session-config-{i}"- })-- config_json = json.dumps(config)- api_keys = json.dumps({"OPENAI_API_KEY": "sk-test-key-here"})-- try:- # New pattern: command + args- result = main(["run", query_json, config_json, api_keys])- result_data = json.loads(result)- print(f"Response: {result_data.get('response', 'N/A')[:100]}...")- except Exception as e:- print(f"Error: {str(e)[:100]}...")---def test_error_handling():- """Test error handling"""- print("=" * 60)- print("TEST 5: Error Handling")- print("=" * 60)-- # Test 1: Missing query- print("\n1. Missing query field:")- try:- result = main([- "run",- json.dumps({"session_id": "test"}),- json.dumps({"model": {"provider": "openai", "model_id": "gpt-3.5-turbo"}}),- json.dumps({})- ])- result_data = json.loads(result)- print(f" Success: {result_data.get('success')}")- print(f" Error: {result_data.get('error')}")- except Exception as e:- print(f" Exception: {str(e)[:100]}")-- # Test 2: Invalid JSON- print("\n2. Invalid JSON:")- try:- result = main([- "run",- "not-valid-json",- json.dumps({"model": {"provider": "openai", "model_id": "gpt-3.5-turbo"}}),- json.dumps({})- ])- result_data = json.loads(result)- print(f" Success: {result_data.get('success')}")- print(f" Error: {result_data.get('error')[:80]}...")- except Exception as e:- print(f" Exception: {str(e)[:100]}")-- # Test 3: Missing arguments- print("\n3. Missing arguments:")- try:- result = main(["run", json.dumps({})])- result_data = json.loads(result)- print(f" Success: {result_data.get('success')}")- print(f" Error: {result_data.get('error')}")- except Exception as e:- print(f" Exception: {str(e)[:100]}")---if __name__ == "__main__":- print("\n")- print("=" * 60)- print("CoreAgent Test Suite")- print("=" * 60)- print()-- print("NOTE: These tests require valid API keys to pass fully.")- print("Replace 'sk-test-key-here' with real API keys for actual testing.")- print()-- # Run all tests- test_basic_query()- test_with_tools()- test_different_providers()- test_config_changes()- test_error_handling()-- print("\n")- print("=" * 60)- print("Test Suite Complete")- print("=" * 60)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/alpha_arena_competition.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/alpha_arena_competition.pydeleted file mode 100644index 6608f018a..000000000--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/alpha_arena_competition.py+++ /dev/null@@ -1,865 +0,0 @@-"""-Alpha Arena Competition System-Manages multi-model trading competition with continuous 2-3 minute execution cycles-"""--import asyncio-import json-import time-import os-import sys-from typing import List, Dict, Any, Optional-from datetime import datetime-from dataclasses import dataclass, field--# Add parent directory to path for imports-sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))--AGNO_AVAILABLE = False-GEMINI_AVAILABLE = False--try:- from agno.agent import Agent- from agno.models.openai import OpenAIChat- AGNO_AVAILABLE = True- print("[AlphaArena] Agno library loaded successfully", file=sys.stderr)-except ImportError as e:- print(f"[AlphaArena] Agno library not available: {e}", file=sys.stderr)--try:- from agno.models.google import Gemini- GEMINI_AVAILABLE = True- print("[AlphaArena] Gemini model available", file=sys.stderr)-except ImportError as e:- print(f"[AlphaArena] Gemini model not available (will use OpenAI-compatible API): {e}", file=sys.stderr)---@dataclass-class CompetitionModel:- """Model configuration for competition"""- name: str- provider: str- model_id: str- initial_capital: float = 10000.0-- # Runtime state - use field(default_factory=...) for mutable defaults- capital: float = field(default=None, repr=False)- positions: Dict[str, Any] = field(default_factory=dict, repr=False)- trades: List[Dict[str, Any]] = field(default_factory=list, repr=False)- decisions: List[Dict[str, Any]] = field(default_factory=list, repr=False)- total_pnl: float = 0.0-- def __post_init__(self):- if self.capital is None:- self.capital = self.initial_capital---class AlphaArenaCompetition:- """- Alpha Arena Competition Manager-- Runs multiple LLM models in parallel, each trading independently.- Executes every 2-3 minutes, tracks decisions, executes trades, calculates P&L.- """-- def __init__(- self,- competition_id: str,- models: List[CompetitionModel],- symbol: str = "BTC/USD",- cycle_interval: int = 150, # 2.5 minutes (150 seconds)- mode: str = "baseline"- ):- """- Initialize competition-- Args:- competition_id: Unique competition ID- models: List of models to compete- symbol: Trading symbol- cycle_interval: Seconds between execution cycles- mode: Competition mode (baseline, monk, situational, max_leverage)- """- print(f"[AlphaArena] Initializing competition: {competition_id}", file=sys.stderr)- print(f"[AlphaArena] AGNO_AVAILABLE: {AGNO_AVAILABLE}", file=sys.stderr)- print(f"[AlphaArena] Models: {[m.name for m in models]}", file=sys.stderr)-- if not AGNO_AVAILABLE:- raise ImportError("Agno library not available. Install with: pip install agno")-- self.competition_id = competition_id- self.models = {m.name: m for m in models}- self.symbol = symbol- self.cycle_interval = cycle_interval- self.mode = mode-- self.is_running = False- self.cycle_count = 0- self.start_time = None-- # Import tools using absolute imports- try:- from tools.kraken_api import get_kraken_api- from tools.order_execution import PaperTradingEngine- from db.database_manager import DatabaseManager-- self.kraken = get_kraken_api()- self.db = DatabaseManager()- print("[AlphaArena] Tools loaded successfully", file=sys.stderr)- except ImportError as e:- print(f"[AlphaArena] Failed to import tools: {e}", file=sys.stderr)- raise-- # Create paper trading engine for each model- self.engines = {- name: PaperTradingEngine(initial_capital=model.initial_capital)- for name, model in self.models.items()- }-- # Load saved state from database if exists- self._load_model_states()-- # Create Agno agents for each model- self.agents = self._create_agents()-- print(f"[AlphaArena] Competition {competition_id} initialized with {len(models)} models", file=sys.stderr)-- def _load_model_states(self):- """Load saved model states from database"""- try:- states = self.db.get_model_states(self.competition_id)- print(f"[AlphaArena] Loading {len(states)} saved model states from DB", file=sys.stderr)-- for state in states:- model_name = state['model_name']- if model_name in self.engines and model_name in self.models:- engine = self.engines[model_name]- model = self.models[model_name]-- # Restore engine state- engine.cash = state['capital']- engine.positions = json.loads(state['positions_json']) if state['positions_json'] else {}-- # Restore model trades count- model.trades = [{}] * state['trades_count'] # Placeholder list-- print(f"[AlphaArena] Restored state for {model_name}: cash=${engine.cash:.2f}, positions={len(engine.positions)}, trades={state['trades_count']}", file=sys.stderr)- except Exception as e:- print(f"[AlphaArena] Error loading model states: {e}", file=sys.stderr)-- def _save_model_states(self):- """Save model states to database for persistence"""- try:- for name, model in self.models.items():- engine = self.engines[name]-- # Calculate portfolio value- portfolio_value = engine.cash- current_price = 0- try:- ticker = self.kraken.get_ticker("XBTUSD")- current_price = ticker.get('price', 0)- for symbol, pos in engine.positions.items():- portfolio_value += pos['quantity'] * current_price- except Exception as e:- print(f"[AlphaArena] Error getting price for portfolio calc: {e}", file=sys.stderr)-- self.db.save_model_state(- competition_id=self.competition_id,- model_name=name,- capital=engine.cash,- positions_json=json.dumps(engine.positions),- trades_count=len(model.trades),- total_pnl=model.total_pnl,- portfolio_value=portfolio_value- )-- print(f"[AlphaArena] Saved model states to DB", file=sys.stderr)- except Exception as e:- print(f"[AlphaArena] Error saving model states: {e}", file=sys.stderr)-- def _create_agents(self) -> Dict[str, Agent]:- """Create Agno agents for each model"""- agents = {}-- for name, model in self.models.items():- try:- print(f"[AlphaArena] Creating agent for: {name} ({model.provider}:{model.model_id})", file=sys.stderr)-- # Create model instance based on provider- if model.provider == "openai":- llm = OpenAIChat(id=model.model_id)- print(f"[AlphaArena] Using OpenAIChat for {name}", file=sys.stderr)- elif model.provider == "google":- if GEMINI_AVAILABLE:- # Use native Gemini model for Google- llm = Gemini(id=model.model_id)- print(f"[AlphaArena] Using native Gemini for {name}", file=sys.stderr)- else:- # Fall back to OpenAI-compatible API for Gemini- google_api_key = os.environ.get('GOOGLE_API_KEY')- if not google_api_key:- print(f"[AlphaArena] WARNING: GOOGLE_API_KEY not set for {name}", file=sys.stderr)- llm = OpenAIChat(- id=model.model_id,- api_key=google_api_key,- base_url="https://generativelanguage.googleapis.com/v1beta/openai/"- )- print(f"[AlphaArena] Using OpenAI-compatible API for Gemini {name}", file=sys.stderr)- elif model.provider == "openrouter":- # OpenRouter uses OpenAI-compatible API with special base URL- openrouter_api_key = os.environ.get('OPENROUTER_API_KEY')- if not openrouter_api_key:- print(f"[AlphaArena] WARNING: OPENROUTER_API_KEY not set for {name}", file=sys.stderr)- llm = OpenAIChat(- id=model.model_id,- api_key=openrouter_api_key,- base_url="https://openrouter.ai/api/v1"- )- print(f"[AlphaArena] Using OpenRouter for {name}", file=sys.stderr)- elif model.provider == "deepseek":- # DeepSeek uses OpenAI-compatible API- deepseek_api_key = os.environ.get('DEEPSEEK_API_KEY')- if not deepseek_api_key:- print(f"[AlphaArena] WARNING: DEEPSEEK_API_KEY not set for {name}", file=sys.stderr)- llm = OpenAIChat(- id=model.model_id,- api_key=deepseek_api_key,- base_url="https://api.deepseek.com/v1"- )- print(f"[AlphaArena] Using DeepSeek for {name}", file=sys.stderr)- elif model.provider == "groq":- # Groq uses OpenAI-compatible API- groq_api_key = os.environ.get('GROQ_API_KEY')- if not groq_api_key:- print(f"[AlphaArena] WARNING: GROQ_API_KEY not set for {name}", file=sys.stderr)- llm = OpenAIChat(- id=model.model_id,- api_key=groq_api_key,- base_url="https://api.groq.com/openai/v1"- )- print(f"[AlphaArena] Using Groq for {name}", file=sys.stderr)- else:- # Default to OpenAI for unknown providers- llm = OpenAIChat(id=model.model_id)- print(f"[AlphaArena] Using OpenAIChat (default) for {name}", file=sys.stderr)-- # Create agent- agent = Agent(- name=f"Trader-{name}",- role="Autonomous Trading Agent",- model=llm,- instructions=self._get_instructions(self.mode),- markdown=False- )-- agents[name] = agent- print(f"[AlphaArena] Created agent successfully: {name}", file=sys.stderr)-- except Exception as e:- print(f"[AlphaArena] ERROR creating agent {name}: {e}", file=sys.stderr)- import traceback- traceback.print_exc(file=sys.stderr)-- return agents-- def _get_instructions(self, mode: str) -> List[str]:- """Get competition mode instructions"""- base_instructions = [- "You are an autonomous trading agent competing in Alpha Arena.",- "Your goal is to maximize P&L through systematic trading.",- "Always respond with valid JSON only - no markdown, no explanations.",- ]-- if mode == "baseline":- return base_instructions + [- "Use comprehensive analysis considering all market data.",- "Manage risk carefully with appropriate position sizing.",- ]- elif mode == "monk":- return base_instructions + [- "Capital preservation is paramount.",- "Only take high-conviction trades (confidence > 0.75).",- "Use strict stop-losses and conservative position sizing.",- ]- elif mode == "situational":- return base_instructions + [- "You are competing against other AI models.",- "Consider the competitive dynamics in your decisions.",- ]- elif mode == "max_leverage":- return base_instructions + [- "Use maximum available capital on every trade.",- "Set tight stop-losses to manage risk.",- ]- else:- return base_instructions-- async def run_cycle(self) -> Dict[str, Any]:- """- Execute one trading cycle for all models-- Returns:- Cycle results with all model decisions and trades- """- self.cycle_count += 1- cycle_start = time.time()-- print(f"\n{'='*80}", file=sys.stderr)- print(f"[AlphaArena] Cycle #{self.cycle_count} - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", file=sys.stderr)- print(f"{'='*80}", file=sys.stderr)-- # 1. Fetch market data- ticker = self.kraken.get_ticker("XBTUSD")- if "error" in ticker:- print(f"[ERROR] Failed to fetch market data: {ticker['error']}", file=sys.stderr)- return {"error": ticker['error']}-- current_price = ticker['price']- print(f"[Market] BTC/USD: ${current_price:,.2f}", file=sys.stderr)-- # 2. Run each model sequentially (NO parallel - respect rate limits!)- results = {}-- for model_name in self.models.keys():- try:- # Wait 1 second between models to respect rate limits- if model_name != list(self.models.keys())[0]:- await asyncio.sleep(1.0)-- decision = await self._run_model(model_name, ticker)- results[model_name] = decision-- except Exception as e:- print(f"[ERROR] Model {model_name} failed: {e}", file=sys.stderr)- results[model_name] = {"error": str(e)}-- cycle_time = time.time() - cycle_start- print(f"\n[AlphaArena] Cycle completed in {cycle_time:.2f}s", file=sys.stderr)-- # Save model states to database for persistence between process invocations- self._save_model_states()-- # Save performance snapshots for charting- self._save_performance_snapshots(ticker['price'])-- return {- "cycle": self.cycle_count,- "timestamp": datetime.now().isoformat(),- "market_data": ticker,- "decisions": results,- "cycle_time_seconds": cycle_time- }-- def _save_performance_snapshots(self, current_price: float):- """Save performance snapshots to database for charting"""- try:- for name, model in self.models.items():- engine = self.engines[name]-- # Calculate portfolio value- portfolio_value = engine.cash- for symbol, pos in engine.positions.items():- portfolio_value += pos['quantity'] * current_price-- pnl = portfolio_value - model.initial_capital- return_pct = (pnl / model.initial_capital) * 100-- # Save to database via SQL- conn = self.db.get_connection()- snapshot_id = f"{self.competition_id}_{name}_cycle_{self.cycle_count}_{int(time.time() * 1000)}"-- conn.execute(- """INSERT INTO alpha_performance_snapshots- (id, competition_id, cycle_number, model_name, portfolio_value, cash, pnl, return_pct, positions_count, trades_count, timestamp)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",- (- snapshot_id,- self.competition_id,- self.cycle_count,- name,- portfolio_value,- engine.cash,- pnl,- return_pct,- len(engine.positions),- len(model.trades),- datetime.now().isoformat()- )- )- conn.commit()- conn.close()-- print(f"[AlphaArena] Saved performance snapshots for cycle {self.cycle_count}", file=sys.stderr)- except Exception as e:- print(f"[AlphaArena] Error saving performance snapshots: {e}", file=sys.stderr)- import traceback- traceback.print_exc(file=sys.stderr)-- async def _run_model(self, model_name: str, ticker: Dict[str, Any]) -> Dict[str, Any]:- """Run a single model's trading decision"""- model = self.models[model_name]- engine = self.engines[model_name]-- # Check if agent exists for this model- if model_name not in self.agents:- print(f"[{model_name}] ERROR: Agent not created!", file=sys.stderr)- return {- "error": f"Agent not created for {model_name}",- "action": "hold",- "model": model_name,- "timestamp": datetime.now().isoformat()- }-- agent = self.agents[model_name]-- # Build prompt- prompt = self._build_trading_prompt(model_name, ticker, engine)-- # Get decision from agent- print(f"[{model_name}] Requesting decision...", file=sys.stderr)-- try:- # agent.run() is synchronous in Agno- response = agent.run(prompt)- print(f"[{model_name}] Got response from agent", file=sys.stderr)-- # Get content from response- if hasattr(response, 'content'):- content = response.content- elif hasattr(response, 'messages') and response.messages:- content = response.messages[-1].content if response.messages else ""- elif isinstance(response, str):- content = response- else:- content = str(response)-- if not content:- print(f"[{model_name}] Empty response from agent", file=sys.stderr)- return {- "error": "Empty response from agent",- "action": "hold",- "model": model_name,- "timestamp": datetime.now().isoformat()- }-- content = content.strip()- print(f"[{model_name}] Response content: {content[:200]}...", file=sys.stderr)-- # Remove markdown code blocks if present- if content.startswith('```'):- parts = content.split('```')- if len(parts) >= 2:- content = parts[1]- if content.startswith('json'):- content = content[4:]- content = content.strip()-- # Try to find JSON in the response- if not content.startswith('{'):- # Look for JSON object in the content- import re- json_match = re.search(r'\{[^{}]*\}', content)- if json_match:- content = json_match.group()-- decision = json.loads(content)- decision['model'] = model_name- decision['timestamp'] = datetime.now().isoformat()-- # Normalize action to lowercase- if 'action' in decision:- decision['action'] = decision['action'].lower()-- print(f"[{model_name}] Decision: {decision.get('action', 'unknown')} (confidence: {decision.get('confidence', 0):.2f})", file=sys.stderr)-- # Execute trade if action is buy/sell- if decision.get('action') in ['buy', 'sell']:- trade_result = self._execute_trade(model_name, decision, ticker['price'])- decision['trade_executed'] = trade_result- else:- decision['trade_executed'] = {"status": "hold"}-- # Log decision to database (alpha_decision_logs table for frontend)- try:- # Calculate portfolio value before and after- portfolio_value_before = engine.cash- for symbol, pos in engine.positions.items():- portfolio_value_before += pos['quantity'] * ticker['price']-- # After trade execution, recalculate- portfolio_value_after = engine.cash- for symbol, pos in engine.positions.items():- portfolio_value_after += pos['quantity'] * ticker['price']-- conn = self.db.get_connection()- conn.execute(- """INSERT INTO alpha_decision_logs- (id, competition_id, model_name, cycle_number, action, symbol, quantity,- confidence, reasoning, trade_executed, price_at_decision,- portfolio_value_before, portfolio_value_after, timestamp)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",- (- f"{self.competition_id}_{model_name}_{self.cycle_count}_{int(time.time() * 1000)}", # unique ID- self.competition_id,- model_name,- self.cycle_count,- decision.get('action', 'hold'),- decision.get('symbol', self.symbol),- decision.get('quantity', None),- decision.get('confidence', 0),- decision.get('reasoning', ''),- json.dumps(decision.get('trade_executed', {})),- ticker['price'],- portfolio_value_before,- portfolio_value_after,- datetime.now().isoformat()- )- )- conn.commit()- conn.close()- print(f"[{model_name}] Decision logged to alpha_decision_logs", file=sys.stderr)- except Exception as e:- print(f"[{model_name}] WARN: Failed to log decision to DB: {e}", file=sys.stderr)- import traceback- traceback.print_exc(file=sys.stderr)-- # Add to model's decision history- model.decisions.append(decision)-- return decision-- except json.JSONDecodeError as e:- print(f"[{model_name}] Invalid JSON response: {e}", file=sys.stderr)- error_decision = {- "error": f"Invalid JSON response: {str(e)}",- "raw_response": content[:500] if 'content' in dir() else "No content",- "action": "hold",- "model": model_name,- "timestamp": datetime.now().isoformat(),- "confidence": 0,- "reasoning": "Failed to parse LLM response as JSON"- }- model.decisions.append(error_decision)- return error_decision-- except Exception as e:- print(f"[{model_name}] ERROR in _run_model: {e}", file=sys.stderr)- import traceback- traceback.print_exc(file=sys.stderr)- error_decision = {- "error": str(e),- "action": "hold",- "model": model_name,- "timestamp": datetime.now().isoformat(),- "confidence": 0,- "reasoning": f"Error: {str(e)}"- }- model.decisions.append(error_decision)- return error_decision-- def _build_trading_prompt(self, model_name: str, ticker: Dict[str, Any], engine) -> str:- """Build trading prompt for a model"""- model = self.models[model_name]-- # Calculate portfolio value- portfolio_value = engine.cash- for symbol, pos in engine.positions.items():- portfolio_value += pos['quantity'] * ticker['price']-- pnl = portfolio_value - model.initial_capital- pnl_pct = (pnl / model.initial_capital) * 100-- # Check if portfolio is empty (no trades yet)- has_positions = len(engine.positions) > 0- num_trades = len(model.trades)-- # Build different prompts based on state- if not has_positions and num_trades == 0:- action_guidance = """-IMPORTANT: This is the start of the competition. You have NO open positions.-You MUST take a position (BUY or SELL) to participate. HOLD is NOT allowed at the start.-Analyze the market data and decide whether to go LONG (buy) or SHORT (sell).-Use approximately 10-20% of your capital for the initial position.-"""- elif not has_positions:- action_guidance = """-NOTE: You currently have NO open positions. Consider entering a new position.-Being fully in cash means you're not participating in market movements.-"""- else:- action_guidance = """-You have open positions. Decide whether to:-- BUY: Add to position or enter new long-- SELL: Close position or enter short-- HOLD: Maintain current position-"""-- prompt = f"""ALPHA ARENA TRADING DECISION - Cycle #{self.cycle_count}--MARKET DATA:-Symbol: {self.symbol}-Price: ${ticker['price']:,.2f}-Bid: ${ticker['bid']:,.2f}-Ask: ${ticker['ask']:,.2f}-24h High: ${ticker['high_24h']:,.2f}-24h Low: ${ticker['low_24h']:,.2f}-Volume: {ticker['volume_24h']:,.2f}--YOUR PORTFOLIO:-Cash: ${engine.cash:,.2f}-Portfolio Value: ${portfolio_value:,.2f}-P&L: ${pnl:+,.2f} ({pnl_pct:+.2f}%)-Open Positions: {len(engine.positions)}-Total Trades Made: {num_trades}-{action_guidance}-RESPONSE FORMAT (JSON ONLY - NO MARKDOWN, NO CODE BLOCKS):-{{- "action": "buy" or "sell" or "hold",- "symbol": "BTC/USD",- "quantity": 0.01,- "confidence": 0.0 to 1.0,- "reasoning": "brief explanation"-}}--Respond ONLY with the JSON object, nothing else.-"""- return prompt-- def _execute_trade(self, model_name: str, decision: Dict[str, Any], current_price: float) -> Dict[str, Any]:- """Execute a trade decision"""- engine = self.engines[model_name]- model = self.models[model_name]-- action = decision['action']- quantity = decision.get('quantity', 0.01)-- # Ensure quantity is reasonable (between 0.001 and 1 BTC for safety)- quantity = max(0.001, min(quantity, 1.0))-- if action == 'buy':- cost = quantity * current_price- if engine.cash >= cost:- engine.cash -= cost-- if self.symbol not in engine.positions:- engine.positions[self.symbol] = {- 'symbol': self.symbol,- 'quantity': 0,- 'entry_price': 0,- 'side': 'long'- }-- pos = engine.positions[self.symbol]-- # Handle case where we're closing a short position- if pos.get('side') == 'short':- # Closing short - calculate PnL- pnl = (pos['entry_price'] - current_price) * min(quantity, pos['quantity'])- model.total_pnl += pnl- pos['quantity'] -= quantity- if pos['quantity'] <= 0:- # Flip to long if we bought more than the short- remaining = abs(pos['quantity'])- if remaining > 0:- pos['quantity'] = remaining- pos['side'] = 'long'- pos['entry_price'] = current_price- else:- del engine.positions[self.symbol]- else:- # Adding to long position- pos['quantity'] += quantity- pos['entry_price'] = current_price- pos['side'] = 'long'-- # Track trade- trade = {- "action": "buy",- "quantity": quantity,- "price": current_price,- "timestamp": datetime.now().isoformat()- }- model.trades.append(trade)-- print(f"[{model_name}] BOUGHT {quantity} BTC @ ${current_price:,.2f}", file=sys.stderr)-- return {- "status": "executed",- "action": "buy",- "quantity": quantity,- "price": current_price,- "cost": cost- }- else:- return {"status": "rejected", "reason": f"Insufficient cash. Need ${cost:,.2f}, have ${engine.cash:,.2f}"}-- elif action == 'sell':- # Allow SHORT selling (opening a short position with no existing position)- # Use margin from cash (require 50% margin for shorts)- margin_required = quantity * current_price * 0.5-- if self.symbol in engine.positions and engine.positions[self.symbol].get('side') == 'long':- # Closing or reducing long position- pos = engine.positions[self.symbol]- sell_quantity = min(quantity, pos['quantity'])- proceeds = sell_quantity * current_price- engine.cash += proceeds-- pnl = (current_price - pos['entry_price']) * sell_quantity- model.total_pnl += pnl-- pos['quantity'] -= sell_quantity- if pos['quantity'] <= 0:- del engine.positions[self.symbol]-- # Track trade- trade = {- "action": "sell",- "quantity": sell_quantity,- "price": current_price,- "pnl": pnl,- "timestamp": datetime.now().isoformat()- }- model.trades.append(trade)-- print(f"[{model_name}] SOLD {sell_quantity} BTC @ ${current_price:,.2f} (P&L: ${pnl:+,.2f})", file=sys.stderr)-- return {- "status": "executed",- "action": "sell",- "quantity": sell_quantity,- "price": current_price,- "proceeds": proceeds,- "pnl": pnl- }-- elif engine.cash >= margin_required:- # Opening a new SHORT position- engine.cash -= margin_required # Reserve margin-- if self.symbol not in engine.positions:- engine.positions[self.symbol] = {- 'symbol': self.symbol,- 'quantity': quantity,- 'entry_price': current_price,- 'side': 'short',- 'margin_reserved': margin_required- }- else:- pos = engine.positions[self.symbol]- pos['quantity'] += quantity- pos['entry_price'] = current_price- pos['margin_reserved'] = pos.get('margin_reserved', 0) + margin_required-- # Track trade- trade = {- "action": "short",- "quantity": quantity,- "price": current_price,- "timestamp": datetime.now().isoformat()- }- model.trades.append(trade)-- print(f"[{model_name}] SHORTED {quantity} BTC @ ${current_price:,.2f} (margin: ${margin_required:,.2f})", file=sys.stderr)-- return {- "status": "executed",- "action": "short",- "quantity": quantity,- "price": current_price,- "margin_reserved": margin_required- }- else:- return {"status": "rejected", "reason": f"Insufficient margin. Need ${margin_required:,.2f}, have ${engine.cash:,.2f}"}-- return {"status": "rejected", "reason": "Invalid action"}-- def get_leaderboard(self) -> List[Dict[str, Any]]:- """Get current leaderboard rankings"""- leaderboard = []-- # Get latest price- ticker = self.kraken.get_ticker("XBTUSD")- current_price = ticker.get('price', 0)-- for name, model in self.models.items():- engine = self.engines[name]-- # Calculate portfolio value- portfolio_value = engine.cash- for symbol, pos in engine.positions.items():- portfolio_value += pos['quantity'] * current_price-- pnl = portfolio_value - model.initial_capital- return_pct = (pnl / model.initial_capital) * 100-- leaderboard.append({- "model": name,- "pnl": pnl,- "return_pct": return_pct,- "portfolio_value": portfolio_value,- "cash": engine.cash,- "trades": len(model.trades),- "positions": len(engine.positions)- })-- # Sort by P&L descending- leaderboard.sort(key=lambda x: x['pnl'], reverse=True)-- return leaderboard-- async def start(self, num_cycles: Optional[int] = None):- """- Start competition (runs continuously or for num_cycles)-- Args:- num_cycles: Number of cycles to run (None = infinite)- """- self.is_running = True- self.start_time = datetime.now()-- print(f"\n[AlphaArena] Starting competition: {self.competition_id}", file=sys.stderr)- print(f"[AlphaArena] Mode: {self.mode}", file=sys.stderr)- print(f"[AlphaArena] Symbol: {self.symbol}", file=sys.stderr)- print(f"[AlphaArena] Cycle interval: {self.cycle_interval}s", file=sys.stderr)- print(f"[AlphaArena] Models: {', '.join(self.models.keys())}", file=sys.stderr)-- cycle = 0- while self.is_running:- if num_cycles and cycle >= num_cycles:- break-- cycle += 1-- try:- result = await self.run_cycle()-- # Show leaderboard every 5 cycles- if cycle % 5 == 0:- leaderboard = self.get_leaderboard()- print(f"\n[Leaderboard] After {cycle} cycles:", file=sys.stderr)- for rank, entry in enumerate(leaderboard, 1):- print(f" {rank}. {entry['model']}: ${entry['pnl']:+,.2f} ({entry['return_pct']:+.2f}%)", file=sys.stderr)-- # Wait for next cycle- await asyncio.sleep(self.cycle_interval)-- except KeyboardInterrupt:- print(f"\n[AlphaArena] Stopped by user", file=sys.stderr)- break- except Exception as e:- print(f"[ERROR] Cycle failed: {e}", file=sys.stderr)- import traceback- traceback.print_exc()-- self.is_running = False- print(f"\n[AlphaArena] Competition ended after {cycle} cycles", file=sys.stderr)-- def stop(self):- """Stop competition"""- self.is_running = False---# Fix missing import-import osdiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading_service_old.py.backup b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading_service_old.py.backupdeleted file mode 100644index 88f0f6d65..000000000--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading_service_old.py.backup+++ /dev/null@@ -1,1139 +0,0 @@-#!/usr/bin/env python-"""-Agno Trading Service - Main Entry Point-========================================--This service is called from Rust/Tauri commands and provides a unified interface-to the Agno trading agent system.--Usage from Rust:- execute_python_command(&app, "agno_trading_service.py", &["command", "arg1", "arg2", ...])--Commands:- - create_agent: Create a new trading agent- - run_agent: Execute an agent with a prompt- - create_team: Create a team of agents- - run_team: Execute a team task- - list_models: List available LLM models- - get_agent_status: Get agent execution status- - analyze_market: Run market analysis- - generate_trade_signal: Generate trading signals- - manage_risk: Run risk management analysis-"""--import sys-import json-import os-import logging-from datetime import datetime-from typing import Dict, Any, Optional, List--# Configure logging to output to stderr only (stdout is reserved for JSON responses)-logging.basicConfig(- level=logging.ERROR,- format='%(levelname)s: %(message)s',- stream=sys.stderr,- force=True-)--# Redirect all prints and logs to stderr to prevent breaking JSON output-class StdoutToStderr:- def write(self, text):- sys.stderr.write(text)- def flush(self):- sys.stderr.flush()--# Save original stdout-_original_stdout = sys.stdout--def _suppress_stdout():- """Suppress stdout during operations"""- sys.stdout = StdoutToStderr()--def _restore_stdout():- """Restore original stdout"""- sys.stdout = _original_stdout--# Suppress by default (will restore only for JSON output)-_suppress_stdout()-# Agno uses loguru which outputs to stdout - we need to disable it-os.environ['LOGURU_LEVEL'] = 'CRITICAL'-os.environ['LOGURU_AUTOINIT'] = 'False'--# Add agno_trading to path-sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'agno_trading'))--# Disable loguru after import-try:- from loguru import logger- logger.remove() # Remove all default handlers- logger.add(sys.stderr, level="CRITICAL") # Only critical errors to stderr-except ImportError:- pass--# Import after path is set-from agno_trading.config.settings import AgnoConfig, LLMConfig, LLMProvider, TradingConfig, TradingMode-from agno_trading.config.models import list_available_models, get_best_model_for_task, validate_model_config-from agno_trading.core.agent_manager import get_agent_manager, AgentConfig as CoreAgentConfig-from agno_trading.agents.market_analyst import MarketAnalystAgent-from agno_trading.agents.trading_strategy import TradingStrategyAgent-from agno_trading.agents.risk_manager import RiskManagerAgent-from agno_trading.agents.portfolio_manager import PortfolioManagerAgent--# Global orchestrator and manager instances to persist state across commands-_global_orchestrator = None-_global_manager = None--def get_global_orchestrator():- """Get or create global TeamOrchestrator instance"""- global _global_orchestrator- if _global_orchestrator is None:- from agno_trading.core.team_orchestrator import TeamOrchestrator- _global_orchestrator = TeamOrchestrator()- return _global_orchestrator--def get_global_manager():- """Get or create global AgentManager instance"""- global _global_manager- if _global_manager is None:- from agno_trading.core.agent_manager import AgentManager- _global_manager = AgentManager()- return _global_manager---def create_response(success: bool, data: Any = None, error: str = None) -> str:- """Create standardized JSON response"""- response = json.dumps({- "success": success,- "data": data,- "error": error- }, indent=2)-- # Restore stdout to print JSON response- _restore_stdout()- return response---def list_models_command(provider: Optional[str] = None) -> str:- """List available LLM models"""- try:- models = list_available_models(provider)- return create_response(True, {"models": models})- except Exception as e:- return create_response(False, error=str(e))---def recommend_model_command(task: str, budget: str = "medium", reasoning: bool = False) -> str:- """Recommend best model for a task"""- try:- provider, model = get_best_model_for_task(task, budget, reasoning)- return create_response(True, {- "provider": provider,- "model": model,- "model_string": f"{provider}:{model}"- })- except Exception as e:- return create_response(False, error=str(e))---def validate_config_command(config_json: str) -> str:- """Validate an Agno configuration"""- try:- config_dict = json.loads(config_json)-- # Create LLM config- llm_data = config_dict.get("llm", {})- llm_config = LLMConfig(- provider=LLMProvider(llm_data.get("provider", "openai")),- model=llm_data.get("model", "gpt-4"),- temperature=llm_data.get("temperature", 0.7),- max_tokens=llm_data.get("max_tokens"),- stream=llm_data.get("stream", False),- reasoning_effort=llm_data.get("reasoning_effort")- )-- # Validate- is_valid, error_msg = validate_model_config(llm_config)-- return create_response(is_valid, {"valid": is_valid}, error_msg)- except Exception as e:- return create_response(False, error=str(e))---def create_agent_command(agent_config_json: str) -> str:- """Create a new trading agent"""- try:- config_dict = json.loads(agent_config_json)-- # Parse model string (format: "provider:model")- agent_model = config_dict.get("agent_model", "openai:gpt-4o-mini")- if ":" in agent_model:- model_provider, model_name = agent_model.split(":", 1)- else:- model_provider = "openai"- model_name = agent_model-- # Create agent configuration- agent_config = CoreAgentConfig(- name=config_dict.get("name", "Agent"),- role=config_dict.get("role", "Trading Agent"),- description=config_dict.get("description", "AI Trading Agent"),- instructions=config_dict.get("instructions", []),- model_provider=model_provider,- model_name=model_name,- temperature=config_dict.get("temperature", 0.7),- tools=config_dict.get("tools", ["market_data", "technical_analysis"]),- symbols=config_dict.get("symbols", ["BTC/USD"]),- enable_memory=config_dict.get("enable_memory", True)- )-- # Create agent via agent manager- manager = get_agent_manager()- agent_id = manager.create_agent(agent_config)-- return create_response(True, {- "agent_id": agent_id,- "status": "created",- "config": {- "name": agent_config.name,- "role": agent_config.role,- "model": f"{model_provider}:{model_name}"- }- })- except Exception as e:- return create_response(False, error=str(e))---def run_agent_command(agent_id: str, prompt: str, session_id: Optional[str] = None) -> str:- """Run an agent with a prompt"""- try:- # Get agent manager and run the agent- manager = get_agent_manager()- result = manager.run_agent(agent_id, prompt, session_id)-- return create_response(True, result)- except Exception as e:- return create_response(False, error=str(e))---def analyze_market_command(- symbol: str,- agent_model: str = "openai:gpt-4o-mini",- analysis_type: str = "comprehensive",- api_keys_json: str = "{}"-) -> str:- """Analyze market for a given symbol"""- try:- # Parse API keys and set environment variables- api_keys = json.loads(api_keys_json)- for key, value in api_keys.items():- os.environ[key] = value-- # Parse model string- if ":" in agent_model:- model_provider, model_name = agent_model.split(":", 1)- else:- model_provider = "openai"- model_name = agent_model-- # Normalize provider name (gemini -> google for Agno)- normalized_provider = model_provider.lower()- if normalized_provider == "gemini":- normalized_provider = "google"-- # Validate API key is configured for the selected provider- # Check both original and normalized provider names- required_keys = [- f"{model_provider.upper()}_API_KEY",- f"{normalized_provider.upper()}_API_KEY"- ]- if not any(key in api_keys and api_keys[key] for key in required_keys):- return create_response(- False,- error=f"API key not configured for {model_provider}. Please configure {model_provider.upper()}_API_KEY or {normalized_provider.upper()}_API_KEY in Settings → LLM Config."- )-- # Create market analyst agent- analyst = MarketAnalystAgent(- model_provider=normalized_provider,- model_name=model_name,- symbols=[symbol]- )-- # Run analysis- result = analyst.analyze_market(symbol, analysis_type)-- return create_response(True, result)- except Exception as e:- return create_response(False, error=str(e))---def generate_trade_signal_command(- symbol: str,- strategy: str = "momentum",- agent_model: str = "anthropic:claude-sonnet-4",- market_data: Optional[str] = None,- api_keys_json: str = "{}"-) -> str:- """Generate trading signal"""- try:- # Parse API keys and set environment variables- api_keys = json.loads(api_keys_json)- for key, value in api_keys.items():- os.environ[key] = value-- # Parse model string- if ":" in agent_model:- model_provider, model_name = agent_model.split(":", 1)- else:- model_provider = "anthropic"- model_name = agent_model-- # Normalize provider name (gemini -> google for Agno)- normalized_provider = model_provider.lower()- if normalized_provider == "gemini":- normalized_provider = "google"-- # Validate API key is configured for the selected provider- required_keys = [- f"{model_provider.upper()}_API_KEY",- f"{normalized_provider.upper()}_API_KEY"- ]- if not any(key in api_keys and api_keys[key] for key in required_keys):- return create_response(- False,- error=f"API key not configured for {model_provider}. Please configure {model_provider.upper()}_API_KEY or {normalized_provider.upper()}_API_KEY in Settings → LLM Config."- )-- # Create trading strategy agent- strategist = TradingStrategyAgent(- model_provider=normalized_provider,- model_name=model_name,- symbols=[symbol]- )-- # Generate signal- result = strategist.generate_trade_signal(symbol, strategy)-- return create_response(True, result)- except Exception as e:- return create_response(False, error=str(e))---def create_alpha_competition_command(- competition_name: str,- models_json: str, # JSON array of {name, provider, model_id}- symbol: str = "BTC/USD",- mode: str = "baseline",- api_keys_json: str = "{}"-) -> str:- """Create Alpha Arena competition"""- try:- print(f"[DEBUG] create_alpha_competition_command called", file=sys.stderr)- print(f"[DEBUG] Name: {competition_name}", file=sys.stderr)- print(f"[DEBUG] Models JSON: {models_json}", file=sys.stderr)- print(f"[DEBUG] Symbol: {symbol}", file=sys.stderr)- print(f"[DEBUG] Mode: {mode}", file=sys.stderr)- print(f"[DEBUG] API Keys JSON length: {len(api_keys_json)}", file=sys.stderr)-- # Parse API keys and set environment variables- api_keys = json.loads(api_keys_json)- print(f"[DEBUG] API keys parsed: {list(api_keys.keys())}", file=sys.stderr)-- for key, value in api_keys.items():- if value: # Only set if value is not empty- os.environ[key] = value- print(f"[DEBUG] Set env var: {key} (length: {len(value)})", file=sys.stderr)-- # Parse models- models_data = json.loads(models_json)- print(f"[DEBUG] Parsed {len(models_data)} models", file=sys.stderr)-- # Import from the correct path- from agno_trading.core.alpha_arena_competition import CompetitionModel, AlphaArenaCompetition-- models = [- CompetitionModel(- name=m['name'],- provider=m['provider'],- model_id=m['model_id']- )- for m in models_data- ]- print(f"[DEBUG] Created {len(models)} CompetitionModel objects", file=sys.stderr)-- competition_id = f"comp_{int(datetime.now().timestamp())}"- print(f"[DEBUG] Competition ID: {competition_id}", file=sys.stderr)-- # Store competition globally- global _active_competition- print(f"[DEBUG] Creating AlphaArenaCompetition instance...", file=sys.stderr)- _active_competition = AlphaArenaCompetition(- competition_id=competition_id,- models=models,- symbol=symbol,- mode=mode,- cycle_interval=150 # 2.5 minutes- )- print(f"[DEBUG] AlphaArenaCompetition instance created successfully", file=sys.stderr)-- # Save configuration to database for persistence (with API keys)- _save_competition_config(competition_id, competition_name, models_data, symbol, mode, api_keys_json)-- return create_response(True, {- "competition_id": competition_id,- "status": "created",- "models": [m['name'] for m in models_data],- "symbol": symbol,- "mode": mode- })-- except Exception as e:- print(f"[ERROR] create_alpha_competition_command failed: {e}", file=sys.stderr)- import traceback- traceback.print_exc(file=sys.stderr)- return create_response(False, error=str(e))---def start_competition_command(competition_id: str, num_cycles: Optional[int] = None) -> str:- """Start competition (runs one cycle immediately, then continues)"""- try:- print(f"[DEBUG] start_competition_command called with ID: {competition_id}", file=sys.stderr)-- # IMPORTANT: Pass competition_id to restore from database if needed- competition = _get_or_create_competition(competition_id)-- print(f"[DEBUG] Competition object: {competition}", file=sys.stderr)- if competition is None:- print(f"[DEBUG] Competition is None! Checking cache file...", file=sys.stderr)- config = _load_competition_config(competition_id)- print(f"[DEBUG] Loaded config: {config}", file=sys.stderr)- return create_response(False, error=f"No competition found with ID: {competition_id}. Please recreate it.")-- print(f"[DEBUG] Running cycle for competition: {competition.competition_id}", file=sys.stderr)- print(f"[DEBUG] Competition has {len(competition.models)} models", file=sys.stderr)-- # Run one cycle immediately- import asyncio- result = asyncio.run(competition.run_cycle())-- print(f"[DEBUG] Cycle completed successfully", file=sys.stderr)- return create_response(True, {- "status": "running",- "cycle_result": result- })-- except Exception as e:- print(f"[DEBUG] Exception in start_competition_command: {e}", file=sys.stderr)- import traceback- traceback.print_exc(file=sys.stderr)- return create_response(False, error=str(e))---def run_cycle_command(competition_id: str) -> str:- """Run a single competition cycle"""- try:- print(f"[DEBUG] run_cycle_command called with ID: {competition_id}", file=sys.stderr)- competition = _get_or_create_competition(competition_id)-- if competition is None:- return create_response(False, error="No active competition. Create one first.")-- print(f"[DEBUG] Running cycle for competition: {competition.competition_id}", file=sys.stderr)- import asyncio- result = asyncio.run(competition.run_cycle())-- print(f"[DEBUG] Cycle completed successfully", file=sys.stderr)- return create_response(True, {- "cycle_result": result,- "status": "cycle_completed"- })- except Exception as e:- print(f"[DEBUG] Exception in run_cycle_command: {e}", file=sys.stderr)- import traceback- traceback.print_exc(file=sys.stderr)- return create_response(False, error=str(e))---def get_leaderboard_command(competition_id: str) -> str:- """Get current leaderboard from database state"""- try:- db = _get_db_manager()-- # Load competition config- config = db.get_active_competition()- if not config:- return create_response(False, error="No active competition")-- # Load model states from database- model_states = db.get_model_states(config['competition_id'])-- if not model_states:- # Return empty leaderboard if no states saved yet- return create_response(True, {- "leaderboard": [],- "cycle_count": 0- })-- # Get current BTC price for portfolio valuation- try:- from agno_trading.tools.kraken_api import get_kraken_api- kraken = get_kraken_api()- ticker = kraken.get_ticker("XBTUSD")- current_price = ticker.get('price', 0)- except Exception as e:- print(f"[WARN] Could not get current price: {e}", file=sys.stderr)- current_price = 0-- leaderboard = []- for state in model_states:- positions = json.loads(state['positions_json']) if state['positions_json'] else {}- capital = state['capital']- trades_count = state['trades_count']-- # Calculate portfolio value- portfolio_value = capital- for symbol, pos in positions.items():- portfolio_value += pos.get('quantity', 0) * current_price-- initial_capital = 10000.0- pnl = portfolio_value - initial_capital- return_pct = (pnl / initial_capital) * 100 if initial_capital > 0 else 0-- leaderboard.append({- "model": state['model_name'],- "pnl": pnl,- "return_pct": return_pct,- "portfolio_value": portfolio_value,- "cash": capital,- "trades": trades_count,- "positions": len(positions)- })-- # Sort by P&L descending- leaderboard.sort(key=lambda x: x['pnl'], reverse=True)-- return create_response(True, {- "leaderboard": leaderboard,- "cycle_count": len(model_states) # Approximate cycle count- })-- except Exception as e:- print(f"[ERROR] get_leaderboard_command: {e}", file=sys.stderr)- import traceback- traceback.print_exc(file=sys.stderr)- return create_response(False, error=str(e))---def get_model_decisions_command(competition_id: str, model_name: Optional[str] = None) -> str:- """Get model decisions/chat feed from database"""- try:- db = _get_db_manager()-- # Get decisions from database (persisted across process invocations)- if model_name and model_name.strip():- # Get decisions for specific model- raw_decisions = db.get_recent_decisions(limit=20, agent_id=competition_id)- decisions = [d for d in raw_decisions if d.get('model') == model_name]- else:- # Get decisions for all models in this competition- raw_decisions = db.get_recent_decisions(limit=50, agent_id=competition_id)- decisions = raw_decisions-- # Parse the decision JSON stored in the decision column- parsed_decisions = []- for d in decisions:- try:- decision_data = json.loads(d.get('decision', '{}'))- decision_data['model'] = d.get('model', 'unknown')- decision_data['reasoning'] = d.get('reasoning', decision_data.get('reasoning', ''))- decision_data['confidence'] = d.get('confidence', decision_data.get('confidence', 0))- parsed_decisions.append(decision_data)- except json.JSONDecodeError:- # Use raw data if JSON parsing fails- parsed_decisions.append({- 'model': d.get('model', 'unknown'),- 'action': 'unknown',- 'reasoning': d.get('reasoning', ''),- 'confidence': d.get('confidence', 0),- 'timestamp': d.get('timestamp', 0)- })-- return create_response(True, {- "decisions": parsed_decisions,- "total": len(parsed_decisions)- })-- except Exception as e:- print(f"[ERROR] get_model_decisions_command: {e}", file=sys.stderr)- import traceback- traceback.print_exc(file=sys.stderr)- return create_response(False, error=str(e))---def stop_competition_command(competition_id: str) -> str:- """Stop active competition"""- try:- competition = _get_or_create_competition()-- if competition is None:- return create_response(False, error="No active competition")-- competition.stop()- final_leaderboard = competition.get_leaderboard()-- # Remove cache file- if os.path.exists(_competition_cache_file):- os.remove(_competition_cache_file)-- return create_response(True, {- "status": "stopped",- "final_leaderboard": final_leaderboard,- "total_cycles": competition.cycle_count- })-- except Exception as e:- return create_response(False, error=str(e))---# Global competition instance-_active_competition = None--# Get database manager for persistent storage-def _get_db_manager():- """Get database manager instance"""- from agno_trading.db.database_manager import get_db_manager- return get_db_manager()--def _save_api_keys(api_keys: dict):- """Save API keys - now stored as part of competition config in DB"""- # API keys are now stored with competition config in database- # Just set environment variables for current session- for key, value in api_keys.items():- if value:- os.environ[key] = value- print(f"[DEBUG] API keys set in environment: {list(api_keys.keys())}", file=sys.stderr)--def _load_api_keys_from_db(competition_id: str = None):- """Load API keys from database and set environment variables"""- try:- db = _get_db_manager()-- # If competition_id provided, get keys from that competition- if competition_id:- config = db.get_competition_config(competition_id)- else:- # Get from active competition- config = db.get_active_competition()-- if config and config.get('api_keys_json'):- api_keys = json.loads(config['api_keys_json'])- for key, value in api_keys.items():- if value:- os.environ[key] = value- print(f"[DEBUG] Loaded API keys from DB: {list(api_keys.keys())}", file=sys.stderr)- return api_keys- return {}- except Exception as e:- print(f"[WARN] Failed to load API keys from DB: {e}", file=sys.stderr)- return {}--def _save_competition_config(competition_id: str, name: str, models_data: list, symbol: str, mode: str, api_keys_json: str = "{}"):- """Save competition configuration to database"""- try:- db = _get_db_manager()- models_json = json.dumps(models_data)- db.save_competition_config(competition_id, name, models_json, symbol, mode, api_keys_json)- print(f"[DEBUG] Competition config saved to database: {competition_id}", file=sys.stderr)- except Exception as e:- print(f"[WARN] Failed to save competition config: {e}", file=sys.stderr)--def _load_competition_config(competition_id: str = None):- """Load competition configuration from database"""- try:- db = _get_db_manager()-- if competition_id:- config = db.get_competition_config(competition_id)- else:- config = db.get_active_competition()-- if config:- # Parse models JSON- config['models'] = json.loads(config['models_json'])- print(f"[DEBUG] Competition config loaded from DB: {config['competition_id']}", file=sys.stderr)- return config- print(f"[DEBUG] No competition config found in DB", file=sys.stderr)- return None- except Exception as e:- print(f"[WARN] Failed to load competition config: {e}", file=sys.stderr)- return None--def _get_or_create_competition(competition_id: str = None):- """Get existing competition or recreate from saved config"""- global _active_competition-- if _active_competition is not None and (competition_id is None or _active_competition.competition_id == competition_id):- print(f"[DEBUG] Returning existing competition: {_active_competition.competition_id}", file=sys.stderr)- return _active_competition-- # Try to load from database- config = _load_competition_config(competition_id)- if config is None:- print(f"[DEBUG] No competition config found", file=sys.stderr)- return None-- # Load API keys from the competition config- if config.get('api_keys_json'):- api_keys = json.loads(config['api_keys_json'])- for key, value in api_keys.items():- if value:- os.environ[key] = value- print(f"[DEBUG] Loaded API keys: {list(api_keys.keys())}", file=sys.stderr)-- print(f"[DEBUG] Recreating competition from DB config: {config['competition_id']}", file=sys.stderr)-- # Recreate competition- from agno_trading.core.alpha_arena_competition import CompetitionModel, AlphaArenaCompetition-- models = [- CompetitionModel(- name=m['name'],- provider=m['provider'],- model_id=m['model_id']- )- for m in config['models']- ]-- _active_competition = AlphaArenaCompetition(- competition_id=config['competition_id'],- models=models,- symbol=config['symbol'],- mode=config['mode'],- cycle_interval=150- )-- print(f"[DEBUG] Competition recreated successfully", file=sys.stderr)- return _active_competition---def manage_risk_command(- portfolio_data: str,- agent_model: str = "openai:gpt-4",- risk_tolerance: str = "moderate",- api_keys_json: str = "{}"-) -> str:- """Run risk management analysis"""- try:- # Parse API keys and set environment variables- api_keys = json.loads(api_keys_json)- for key, value in api_keys.items():- os.environ[key] = value-- portfolio = json.loads(portfolio_data)-- # Parse model string- if ":" in agent_model:- model_provider, model_name = agent_model.split(":", 1)- else:- model_provider = "openai"- model_name = agent_model-- # Normalize provider name (gemini -> google for Agno)- normalized_provider = model_provider.lower()- if normalized_provider == "gemini":- normalized_provider = "google"-- # Validate API key is configured for the selected provider- required_keys = [- f"{model_provider.upper()}_API_KEY",- f"{normalized_provider.upper()}_API_KEY"- ]- if not any(key in api_keys and api_keys[key] for key in required_keys):- return create_response(- False,- error=f"API key not configured for {model_provider}. Please configure {model_provider.upper()}_API_KEY or {normalized_provider.upper()}_API_KEY in Settings → LLM Config."- )-- # Create risk manager agent- risk_manager = RiskManagerAgent(- model_provider=normalized_provider,- model_name=model_name,- risk_tolerance=risk_tolerance- )-- # Run risk analysis- positions = portfolio.get("positions", [])- portfolio_value = portfolio.get("total_value", 10000.0)-- result = risk_manager.analyze_portfolio_risk(positions, portfolio_value)-- return create_response(True, result)- except Exception as e:- return create_response(False, error=str(e))---def get_config_template_command(config_type: str = "default") -> str:- """Get configuration template"""- try:- if config_type == "default":- config = AgnoConfig()- elif config_type == "conservative":- config = AgnoConfig(- trading=TradingConfig(- mode=TradingMode.PAPER,- max_position_size=0.05,- max_leverage=1.0,- stop_loss_pct=0.03,- take_profit_pct=0.10- )- )- elif config_type == "aggressive":- config = AgnoConfig(- trading=TradingConfig(- mode=TradingMode.PAPER,- max_position_size=0.20,- max_leverage=2.0,- stop_loss_pct=0.08,- take_profit_pct=0.25- )- )- else:- return create_response(False, error=f"Unknown config type: {config_type}")-- return create_response(True, {"config": config.to_dict()})- except Exception as e:- return create_response(False, error=str(e))---# ============================================================================-# NEW COMMANDS: Auto-Trading, Debate, Evolution-# ============================================================================--def execute_trade_command(- signal_json: str,- portfolio_json: str,- agent_id: str,- model: str,- api_keys_json: str = "{}"-) -> str:- """Execute a trade based on signal"""- try:- from agno_trading.core.trade_executor import get_trade_executor-- signal = json.loads(signal_json)- portfolio = json.loads(portfolio_json)- api_keys = json.loads(api_keys_json)-- # Set API keys- for key, value in api_keys.items():- os.environ[key] = value-- executor = get_trade_executor()- result = executor.execute_trade(signal, portfolio, agent_id, model, paper_trading=True)-- return create_response(True, result)- except Exception as e:- return create_response(False, error=str(e))---def close_position_command(trade_id: int, exit_price: float, reason: str = "manual") -> str:- """Close an open position"""- try:- from agno_trading.core.trade_executor import get_trade_executor-- executor = get_trade_executor()- result = executor.close_position(int(trade_id), float(exit_price), reason)-- return create_response(True, result)- except Exception as e:- return create_response(False, error=str(e))---def get_agent_trades_command(agent_id: str, limit: int = 100, status: str = None) -> str:- """Get trade history for an agent"""- try:- from agno_trading.db.database_manager import get_db_manager-- db = get_db_manager()- trades = db.get_agent_trades(agent_id, int(limit), status)-- return create_response(True, {"trades": trades})- except Exception as e:- return create_response(False, error=str(e))---def get_agent_performance_command(agent_id: str) -> str:- """Get performance metrics for an agent"""- try:- from agno_trading.db.database_manager import get_db_manager-- db = get_db_manager()- performance = db.get_agent_performance(agent_id)-- if performance:- return create_response(True, {"performance": performance})- else:- return create_response(False, error="Agent performance not found")- except Exception as e:- return create_response(False, error=str(e))---def get_db_leaderboard_command(limit: int = 20) -> str:- """Get leaderboard from database"""- try:- from agno_trading.db.database_manager import get_db_manager-- db = get_db_manager()- leaderboard = db.get_leaderboard(int(limit))-- return create_response(True, {"leaderboard": leaderboard})- except Exception as e:- return create_response(False, error=str(e))---def get_db_decisions_command(limit: int = 50, agent_id: str = None) -> str:- """Get recent decisions from database"""- try:- from agno_trading.db.database_manager import get_db_manager-- db = get_db_manager()- decisions = db.get_recent_decisions(int(limit), agent_id)-- return create_response(True, {"decisions": decisions})- except Exception as e:- return create_response(False, error=str(e))---def run_debate_command(- symbol: str,- market_data_json: str,- bull_model: str,- bear_model: str,- analyst_model: str,- api_keys_json: str = "{}"-) -> str:- """Run a Bull/Bear/Analyst debate"""- try:- from agno_trading.core.debate_orchestrator import get_debate_orchestrator-- market_data = json.loads(market_data_json)- api_keys = json.loads(api_keys_json)-- # Set API keys- for key, value in api_keys.items():- os.environ[key] = value-- orchestrator = get_debate_orchestrator()- result = orchestrator.run_debate(- symbol,- market_data,- bull_model,- bear_model,- analyst_model,- api_keys- )-- return create_response(True, result)- except Exception as e:- return create_response(False, error=str(e))---def get_recent_debates_command(limit: int = 10) -> str:- """Get recent debate sessions"""- try:- from agno_trading.db.database_manager import get_db_manager-- db = get_db_manager()- debates = db.get_recent_debates(int(limit))-- return create_response(True, {"debates": debates})- except Exception as e:- return create_response(False, error=str(e))---def evolve_agent_command(- agent_id: str,- model: str,- current_instructions_json: str,- trigger: str,- notes: str = None-) -> str:- """Evolve an agent based on performance"""- try:- from agno_trading.core.agent_evolution import get_agent_evolution-- current_instructions = json.loads(current_instructions_json)-- evolution = get_agent_evolution()- result = evolution.evolve_agent(agent_id, model, current_instructions, trigger, notes)-- return create_response(True, result)- except Exception as e:- return create_response(False, error=str(e))---def check_evolution_command(agent_id: str) -> str:- """Check if agent should evolve"""- try:- from agno_trading.core.agent_evolution import get_agent_evolution- from agno_trading.db.database_manager import get_db_manager-- db = get_db_manager()- performance = db.get_agent_performance(agent_id)-- if not performance:- return create_response(False, error="Agent performance not found")-- evolution = get_agent_evolution()- should_evolve, trigger = evolution.should_evolve(agent_id, performance)-- return create_response(True, {- "should_evolve": should_evolve,- "trigger": trigger,- "performance": performance- })- except Exception as e:- return create_response(False, error=str(e))---def get_evolution_summary_command(agent_id: str) -> str:- """Get evolution summary for an agent"""- try:- from agno_trading.core.agent_evolution import get_agent_evolution-- evolution = get_agent_evolution()- summary = evolution.get_evolution_summary(agent_id)-- return create_response(True, summary)- except Exception as e:- return create_response(False, error=str(e))---def enable_auto_trading_command(enabled: str = "true") -> str:- """Enable or disable auto-trading"""- try:- orchestrator = get_global_orchestrator()- is_enabled = enabled.lower() == "true"- result = orchestrator.enable_auto_trading(is_enabled)- return create_response(True, result)- except Exception as e:- return create_response(False, error=str(e))---def update_market_price_command(symbol: str, price: str) -> str:- """Update market price for a symbol"""- try:- orchestrator = get_global_orchestrator()- price_float = float(price)- orchestrator.update_market_price(symbol, price_float)- return create_response(True, {"symbol": symbol, "price": price_float})- except Exception as e:- return create_response(False, error=str(e))---def execute_signal_command(model: str, signal_json: str, current_price: str) -> str:- """Execute a trade signal for a model"""- try:- import json- orchestrator = get_global_orchestrator()- signal = json.loads(signal_json)- price = float(current_price)-- position = orchestrator.execute_signal(model, signal, price)- return create_response(True, {"position": position})- except Exception as e:- return create_response(False, error=str(e))---def run_continuous_competition_command(- team_id: str,- symbol: str,- interval_seconds: str = "300",- duration_hours: str = "24"-) -> str:- """Run continuous competition with auto-trading"""- try:- import asyncio- orchestrator = get_global_orchestrator()-- interval = int(interval_seconds)- duration = int(duration_hours)-- loop = asyncio.new_event_loop()- asyncio.set_event_loop(loop)- result = loop.run_until_complete(- orchestrator.run_continuous_competition(team_id, symbol, interval, duration)- )-- return create_response(True, result)- except Exception as e:- return create_response(False, error=str(e))---# Command dispatcher-COMMANDS = {- "list_models": list_models_command,- "recommend_model": recommend_model_command,- "validate_config": validate_config_command,- "create_agent": create_agent_command,- "run_agent": run_agent_command,- "analyze_market": analyze_market_command,- "generate_trade_signal": generate_trade_signal_command,- "manage_risk": manage_risk_command,- "get_config_template": get_config_template_command,- # Alpha Arena Competition- "create_competition": create_alpha_competition_command,- "start_competition": start_competition_command,- "run_cycle": run_cycle_command,- "get_leaderboard_alpha": get_leaderboard_command,- "get_model_decisions_alpha": get_model_decisions_command,- "stop_competition": stop_competition_command,- # Trade execution- "execute_trade": execute_trade_command,- "close_position": close_position_command,- "get_agent_trades": get_agent_trades_command,- "get_agent_performance": get_agent_performance_command,- "get_db_leaderboard": get_db_leaderboard_command,- "get_db_decisions": get_db_decisions_command,- # Competition features- "enable_auto_trading": enable_auto_trading_command,- "update_market_price": update_market_price_command,- "execute_signal": execute_signal_command,- "run_continuous_competition": run_continuous_competition_command,- # Debate & evolution- "run_debate": run_debate_command,- "get_recent_debates": get_recent_debates_command,- "evolve_agent": evolve_agent_command,- "check_evolution": check_evolution_command,- "get_evolution_summary": get_evolution_summary_command,-}---def main():- """Main entry point for CLI usage"""- if len(sys.argv) < 2:- print(create_response(False, error="No command specified"))- sys.exit(1)-- command = sys.argv[1]- args = sys.argv[2:]-- if command not in COMMANDS:- print(create_response(False, error=f"Unknown command: {command}"))- sys.exit(1)-- try:- # Call command function with args- result = COMMANDS[command](*args)- print(result)- except TypeError as e:- print(create_response(False, error=f"Invalid arguments for command '{command}': {str(e)}"))- sys.exit(1)- except Exception as e:- print(create_response(False, error=f"Command execution failed: {str(e)}"))- sys.exit(1)---if __name__ == "__main__":- main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/__init__.pynew file mode 100644index 000000000..ecf801fd9--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/__init__.py@@ -0,0 +1,58 @@+"""+Alpha Arena - AI Trading Competition System++A production-ready multi-agent trading competition platform with:+- Async-first design+- Pydantic type validation+- A2A Protocol-inspired agent communication+- Streaming responses+- Comprehensive evaluation and tracing+"""++__version__ = "2.0.0"+__author__ = "Fincept Corporation"++from alpha_arena.types.models import (+ CompetitionConfig,+ CompetitionModel,+ CompetitionStatus,+ LeaderboardEntry,+ ModelDecision,+ TradeAction,+ TradeResult,+ PortfolioState,+ CycleResult,+)++from alpha_arena.types.responses import (+ StreamResponse,+ StreamResponseEvent,+ NotifyResponse,+ NotifyResponseEvent,+ BaseResponse,+)++from alpha_arena.core.base_agent import BaseAgent+from alpha_arena.core.competition import AlphaArenaCompetition++__all__ = [+ # Models+ "CompetitionConfig",+ "CompetitionModel",+ "CompetitionStatus",+ "LeaderboardEntry",+ "ModelDecision",+ "TradeAction",+ "TradeResult",+ "PortfolioState",+ "CycleResult",+ # Responses+ "StreamResponse",+ "StreamResponseEvent",+ "NotifyResponse",+ "NotifyResponseEvent",+ "BaseResponse",+ # Core+ "BaseAgent",+ "AlphaArenaCompetition",+]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/config/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/config/__init__.pynew file mode 100644index 000000000..4872e84c4--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/config/__init__.py@@ -0,0 +1,23 @@+"""+Alpha Arena Configuration Module++AgentCard-based configuration system for trading agents.+"""++from alpha_arena.config.agent_cards import (+ AgentCard,+ AgentCapabilities,+ load_agent_cards,+ save_agent_card,+ get_agent_card,+ list_agent_cards,+)++__all__ = [+ "AgentCard",+ "AgentCapabilities",+ "load_agent_cards",+ "save_agent_card",+ "get_agent_card",+ "list_agent_cards",+]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/config/agent_cards.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/config/agent_cards.pynew file mode 100644index 000000000..08c6aa1e3--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/config/agent_cards.py@@ -0,0 +1,308 @@+"""+AgentCard Configuration System++JSON-based agent configuration inspired by ValueCell's AgentCard architecture.+Provides discovery and configuration for trading agents.+"""++import json+from pathlib import Path+from typing import Dict, List, Optional, Any+from pydantic import BaseModel, Field++from alpha_arena.utils.logging import get_logger++logger = get_logger("agent_cards")+++class AgentCapabilities(BaseModel):+ """Capabilities of an agent."""++ streaming: bool = Field(True, description="Supports streaming responses")+ trading: bool = Field(True, description="Can execute trades")+ analysis: bool = Field(True, description="Can perform market analysis")+ notifications: bool = Field(False, description="Can send notifications")+ short_selling: bool = Field(False, description="Can short sell")+ leverage: bool = Field(False, description="Can use leverage")+++class AgentSkill(BaseModel):+ """Skill definition for an agent."""++ id: str = Field(..., description="Skill identifier")+ name: str = Field(..., description="Display name")+ description: str = Field(..., description="Skill description")+ parameters: Dict[str, Any] = Field(default_factory=dict, description="Skill parameters")+++class AgentCard(BaseModel):+ """+ Agent configuration card following A2A Protocol patterns.++ Provides all configuration needed to instantiate and connect to an agent.+ """++ name: str = Field(..., description="Agent display name")+ description: str = Field("", description="Agent description")+ version: str = Field("1.0.0", description="Agent version")++ # Provider configuration+ provider: str = Field(..., description="LLM provider (openai, anthropic, etc.)")+ model_id: str = Field(..., description="Model identifier")++ # Agent class+ agent_class: Optional[str] = Field(+ None,+ description="Python class path (e.g., 'alpha_arena.agents.trader:TraderAgent')"+ )++ # Runtime configuration+ url: Optional[str] = Field(None, description="Agent URL if remote")+ enabled: bool = Field(True, description="Whether agent is enabled")+ capabilities: AgentCapabilities = Field(+ default_factory=AgentCapabilities,+ description="Agent capabilities"+ )+ skills: List[AgentSkill] = Field(default_factory=list, description="Agent skills")++ # Trading configuration+ temperature: float = Field(0.7, ge=0.0, le=2.0, description="LLM temperature")+ max_tokens: Optional[int] = Field(None, description="Max response tokens")+ default_mode: str = Field("baseline", description="Default competition mode")+ risk_level: str = Field("medium", description="Risk level: low, medium, high")++ # Instructions+ system_prompt: Optional[str] = Field(None, description="Custom system prompt")+ instructions: List[str] = Field(default_factory=list, description="Agent instructions")++ # Metadata+ metadata: Dict[str, Any] = Field(default_factory=dict, description="Additional metadata")++ class Config:+ extra = "allow"+++# Default agent cards+DEFAULT_AGENT_CARDS: List[AgentCard] = [+ AgentCard(+ name="GPT-4o Mini",+ description="Fast and cost-effective OpenAI model",+ provider="openai",+ model_id="gpt-4o-mini",+ capabilities=AgentCapabilities(streaming=True, trading=True, analysis=True),+ temperature=0.7,+ instructions=["Focus on quick analysis and decisive action"],+ ),+ AgentCard(+ name="GPT-4o",+ description="Most capable OpenAI model",+ provider="openai",+ model_id="gpt-4o",+ capabilities=AgentCapabilities(streaming=True, trading=True, analysis=True),+ temperature=0.7,+ instructions=["Perform thorough analysis before making decisions"],+ ),+ AgentCard(+ name="Claude 3.5 Sonnet",+ description="Anthropic's Claude 3.5 Sonnet",+ provider="anthropic",+ model_id="claude-3-5-sonnet-20241022",+ capabilities=AgentCapabilities(streaming=True, trading=True, analysis=True),+ temperature=0.7,+ instructions=["Use careful reasoning for trading decisions"],+ ),+ AgentCard(+ name="Gemini 2.0 Flash",+ description="Google's fast Gemini model",+ provider="google",+ model_id="gemini-2.0-flash-exp",+ capabilities=AgentCapabilities(streaming=True, trading=True, analysis=True),+ temperature=0.7,+ instructions=["Prioritize speed and efficiency"],+ ),+ AgentCard(+ name="DeepSeek Chat",+ description="DeepSeek's chat model",+ provider="deepseek",+ model_id="deepseek-chat",+ capabilities=AgentCapabilities(streaming=True, trading=True, analysis=True),+ temperature=0.7,+ instructions=["Use deep analytical reasoning"],+ ),+ AgentCard(+ name="Llama 3.3 70B",+ description="Meta's Llama 3.3 via Groq",+ provider="groq",+ model_id="llama-3.3-70b-versatile",+ capabilities=AgentCapabilities(streaming=True, trading=True, analysis=True),+ temperature=0.7,+ instructions=["Balance speed with thorough analysis"],+ ),+ AgentCard(+ name="Qwen 2.5 72B",+ description="Alibaba's Qwen via Groq",+ provider="groq",+ model_id="qwen-2.5-72b",+ capabilities=AgentCapabilities(streaming=True, trading=True, analysis=True),+ temperature=0.7,+ instructions=["Consider global market perspectives"],+ ),+]+++# Global registry+_AGENT_CARDS: Dict[str, AgentCard] = {}+_CARDS_LOADED = False+++def _get_config_dir() -> Path:+ """Get the configuration directory."""+ # Check for user config first+ config_dir = Path.home() / ".fincept" / "alpha_arena" / "agent_cards"+ if config_dir.exists():+ return config_dir++ # Fall back to script directory+ return Path(__file__).parent / "cards"+++def load_agent_cards(config_dir: Optional[Path] = None) -> Dict[str, AgentCard]:+ """+ Load agent cards from JSON configuration files.++ Args:+ config_dir: Optional directory to load from++ Returns:+ Dictionary of agent name to AgentCard+ """+ global _AGENT_CARDS, _CARDS_LOADED++ if config_dir is None:+ config_dir = _get_config_dir()++ # Load defaults first+ for card in DEFAULT_AGENT_CARDS:+ _AGENT_CARDS[card.name] = card++ # Load from config directory+ if config_dir.exists():+ for json_file in config_dir.glob("*.json"):+ try:+ with open(json_file, "r", encoding="utf-8") as f:+ data = json.load(f)++ # Skip disabled agents+ if not data.get("enabled", True):+ continue++ card = AgentCard.model_validate(data)+ _AGENT_CARDS[card.name] = card+ logger.debug(f"Loaded agent card: {card.name}")++ except Exception as e:+ logger.warning(f"Failed to load agent card from {json_file}: {e}")++ _CARDS_LOADED = True+ logger.info(f"Loaded {len(_AGENT_CARDS)} agent cards")+ return _AGENT_CARDS+++def save_agent_card(card: AgentCard, config_dir: Optional[Path] = None) -> bool:+ """+ Save an agent card to a JSON file.++ Args:+ card: AgentCard to save+ config_dir: Optional directory to save to++ Returns:+ True if saved successfully+ """+ if config_dir is None:+ config_dir = _get_config_dir()++ config_dir.mkdir(parents=True, exist_ok=True)++ file_name = card.name.lower().replace(" ", "_") + ".json"+ file_path = config_dir / file_name++ try:+ with open(file_path, "w", encoding="utf-8") as f:+ json.dump(card.model_dump(), f, indent=2)++ _AGENT_CARDS[card.name] = card+ logger.info(f"Saved agent card: {card.name}")+ return True++ except Exception as e:+ logger.error(f"Failed to save agent card {card.name}: {e}")+ return False+++def get_agent_card(name: str) -> Optional[AgentCard]:+ """+ Get an agent card by name.++ Args:+ name: Agent name++ Returns:+ AgentCard if found, None otherwise+ """+ if not _CARDS_LOADED:+ load_agent_cards()++ return _AGENT_CARDS.get(name)+++def list_agent_cards() -> List[AgentCard]:+ """+ List all available agent cards.++ Returns:+ List of AgentCard objects+ """+ if not _CARDS_LOADED:+ load_agent_cards()++ return list(_AGENT_CARDS.values())+++def get_enabled_agents() -> List[AgentCard]:+ """Get only enabled agents."""+ return [card for card in list_agent_cards() if card.enabled]+++def get_agents_by_provider(provider: str) -> List[AgentCard]:+ """Get agents by provider."""+ return [card for card in list_agent_cards() if card.provider == provider]+++def create_agent_from_card(+ card: AgentCard,+ api_key: Optional[str] = None,+ mode: str = "baseline",+):+ """+ Create an agent instance from an AgentCard.++ Args:+ card: AgentCard configuration+ api_key: Optional API key override+ mode: Competition mode++ Returns:+ BaseTradingAgent instance+ """+ from alpha_arena.core.base_agent import LLMTradingAgent++ return LLMTradingAgent(+ name=card.name,+ provider=card.provider,+ model_id=card.model_id,+ api_key=api_key,+ temperature=card.temperature,+ instructions=card.instructions if card.instructions else None,+ mode=mode,+ )diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/__init__.pynew file mode 100644index 000000000..7fce59abd--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/__init__.py@@ -0,0 +1,20 @@+"""+Alpha Arena Core Module++Contains the core components for the trading competition system.+"""++from alpha_arena.core.base_agent import BaseAgent, BaseTradingAgent+from alpha_arena.core.competition import AlphaArenaCompetition+from alpha_arena.core.paper_trading import PaperTradingEngine+from alpha_arena.core.agent_manager import AgentManager+from alpha_arena.core.market_data import MarketDataProvider++__all__ = [+ "BaseAgent",+ "BaseTradingAgent",+ "AlphaArenaCompetition",+ "PaperTradingEngine",+ "AgentManager",+ "MarketDataProvider",+]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/agent_manager.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/agent_manager.pynew file mode 100644index 000000000..61b6210c5--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/agent_manager.py@@ -0,0 +1,263 @@+"""+Agent Manager++Manages agent lifecycle and connections, inspired by ValueCell's RemoteConnections.+"""++import asyncio+from dataclasses import dataclass, field+from typing import Dict, List, Optional, Any, Type++from alpha_arena.core.base_agent import BaseAgent, BaseTradingAgent, LLMTradingAgent+from alpha_arena.config.agent_cards import AgentCard, get_agent_card, list_agent_cards+from alpha_arena.utils.logging import get_logger++logger = get_logger("agent_manager")+++@dataclass+class AgentContext:+ """Context for a managed agent."""++ name: str+ card: Optional[AgentCard] = None+ instance: Optional[BaseAgent] = None+ is_running: bool = False+ api_key: Optional[str] = None+ metadata: Dict[str, Any] = field(default_factory=dict)+ _lock: asyncio.Lock = field(default_factory=asyncio.Lock)+++class AgentManager:+ """+ Manager for agent lifecycle and connections.++ Inspired by ValueCell's RemoteConnections pattern.+ """++ def __init__(self):+ self._contexts: Dict[str, AgentContext] = {}+ self._initialized = False++ async def initialize(self):+ """Initialize the agent manager."""+ if self._initialized:+ return++ # Load agent cards+ cards = list_agent_cards()+ for card in cards:+ self._contexts[card.name] = AgentContext(+ name=card.name,+ card=card,+ )++ self._initialized = True+ logger.info(f"Agent manager initialized with {len(self._contexts)} agents")++ def _ensure_initialized(self):+ """Ensure the manager is initialized."""+ if not self._initialized:+ # Sync initialization fallback+ cards = list_agent_cards()+ for card in cards:+ if card.name not in self._contexts:+ self._contexts[card.name] = AgentContext(+ name=card.name,+ card=card,+ )+ self._initialized = True++ async def start_agent(+ self,+ agent_name: str,+ api_key: Optional[str] = None,+ mode: str = "baseline",+ **kwargs,+ ) -> Optional[BaseAgent]:+ """+ Start an agent by name.++ Args:+ agent_name: Name of the agent to start+ api_key: Optional API key override+ mode: Competition mode+ **kwargs: Additional arguments++ Returns:+ The started agent instance+ """+ self._ensure_initialized()++ if agent_name not in self._contexts:+ # Try to get from cards+ card = get_agent_card(agent_name)+ if not card:+ logger.error(f"Agent not found: {agent_name}")+ return None++ self._contexts[agent_name] = AgentContext(+ name=agent_name,+ card=card,+ )++ ctx = self._contexts[agent_name]++ async with ctx._lock:+ # Return existing if running+ if ctx.is_running and ctx.instance:+ return ctx.instance++ # Store API key+ if api_key:+ ctx.api_key = api_key++ # Create agent instance+ instance = await self._create_agent(ctx, mode, **kwargs)+ if instance is None:+ return None++ # Initialize agent+ if await instance.initialize():+ ctx.instance = instance+ ctx.is_running = True+ logger.info(f"Started agent: {agent_name}")+ return instance+ else:+ logger.error(f"Failed to initialize agent: {agent_name}")+ return None++ async def _create_agent(+ self,+ ctx: AgentContext,+ mode: str = "baseline",+ **kwargs,+ ) -> Optional[BaseAgent]:+ """Create an agent instance from context."""+ if not ctx.card:+ return None++ card = ctx.card+ api_key = ctx.api_key or kwargs.get("api_key")++ # Create LLM trading agent+ agent = LLMTradingAgent(+ name=card.name,+ provider=card.provider,+ model_id=card.model_id,+ api_key=api_key,+ temperature=card.temperature,+ instructions=card.instructions if card.instructions else None,+ mode=mode,+ )++ return agent++ async def stop_agent(self, agent_name: str):+ """Stop an agent."""+ self._ensure_initialized()++ if agent_name not in self._contexts:+ return++ ctx = self._contexts[agent_name]++ async with ctx._lock:+ if ctx.instance:+ await ctx.instance.shutdown()+ ctx.instance = None+ ctx.is_running = False+ logger.info(f"Stopped agent: {agent_name}")++ async def stop_all(self):+ """Stop all running agents."""+ for name in list(self._contexts.keys()):+ await self.stop_agent(name)++ def get_agent(self, agent_name: str) -> Optional[BaseAgent]:+ """Get a running agent instance."""+ self._ensure_initialized()++ ctx = self._contexts.get(agent_name)+ if ctx and ctx.is_running:+ return ctx.instance+ return None++ def list_running_agents(self) -> List[str]:+ """List running agents."""+ self._ensure_initialized()+ return [name for name, ctx in self._contexts.items() if ctx.is_running]++ def list_available_agents(self) -> List[str]:+ """List all available agents."""+ self._ensure_initialized()+ return list(self._contexts.keys())++ def get_agent_card(self, agent_name: str) -> Optional[AgentCard]:+ """Get the agent card for a given agent."""+ self._ensure_initialized()+ ctx = self._contexts.get(agent_name)+ return ctx.card if ctx else None++ def get_all_agent_cards(self) -> Dict[str, AgentCard]:+ """Get all agent cards."""+ self._ensure_initialized()+ return {+ name: ctx.card+ for name, ctx in self._contexts.items()+ if ctx.card is not None+ }++ async def start_agents_for_competition(+ self,+ agent_names: List[str],+ api_keys: Dict[str, str],+ mode: str = "baseline",+ ) -> Dict[str, BaseAgent]:+ """+ Start multiple agents for a competition.++ Args:+ agent_names: Names of agents to start+ api_keys: Dict of provider -> api_key+ mode: Competition mode++ Returns:+ Dict of agent name to agent instance+ """+ agents = {}++ for name in agent_names:+ card = self.get_agent_card(name)+ if not card:+ logger.warning(f"Agent card not found: {name}")+ continue++ # Get API key for this provider+ api_key = api_keys.get(card.provider)++ agent = await self.start_agent(+ agent_name=name,+ api_key=api_key,+ mode=mode,+ )++ if agent:+ agents[name] = agent++ return agents+++# Singleton instance+_manager: Optional[AgentManager] = None+++async def get_agent_manager() -> AgentManager:+ """Get the global agent manager."""+ global _manager++ if _manager is None:+ _manager = AgentManager()+ await _manager.initialize()++ return _managerdiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/base_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/base_agent.pynew file mode 100644index 000000000..b617f9247--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/base_agent.py@@ -0,0 +1,798 @@+"""+Base Agent Abstract Class++Defines the interface for all trading agents in Alpha Arena.+Inspired by ValueCell's BaseAgent architecture with stream/notify methods.+"""++from abc import ABC, abstractmethod+from typing import AsyncGenerator, Dict, List, Optional, Any+from datetime import datetime++from alpha_arena.types.models import (+ MarketData,+ ModelDecision,+ PortfolioState,+ TradeAction,+ TradeResult,+)+from alpha_arena.types.responses import StreamResponse, NotifyResponse+from alpha_arena.utils.logging import get_logger++logger = get_logger("base_agent")+++class BaseAgent(ABC):+ """+ Abstract base class for all agents in Alpha Arena.++ All agents must implement the stream() method for user-initiated requests.+ The notify() method is optional for agent-initiated notifications.+ """++ def __init__(self, name: str = "BaseAgent"):+ self.name = name+ self._initialized = False++ @abstractmethod+ async def stream(+ self,+ query: str,+ competition_id: str,+ cycle_number: int,+ dependencies: Optional[Dict] = None,+ ) -> AsyncGenerator[StreamResponse, None]:+ """+ Process queries and return streaming responses (user-initiated).++ Args:+ query: User query or prompt+ competition_id: Competition identifier+ cycle_number: Current cycle number+ dependencies: Optional context (market data, portfolio, etc.)++ Yields:+ StreamResponse: Stream responses with content and events+ """+ raise NotImplementedError++ async def notify(+ self,+ query: str,+ competition_id: str,+ cycle_number: int,+ dependencies: Optional[Dict] = None,+ ) -> AsyncGenerator[NotifyResponse, None]:+ """+ Send proactive notifications (agent-initiated).++ Args:+ query: Query content (can be empty for some agents)+ competition_id: Competition identifier+ cycle_number: Current cycle number+ dependencies: Optional context++ Yields:+ NotifyResponse: Notification content and status+ """+ raise NotImplementedError++ async def initialize(self) -> bool:+ """Initialize the agent. Override for custom initialization."""+ self._initialized = True+ logger.info(f"Agent '{self.name}' initialized")+ return True++ async def shutdown(self) -> None:+ """Shutdown the agent. Override for cleanup."""+ self._initialized = False+ logger.info(f"Agent '{self.name}' shutdown")++ @property+ def is_initialized(self) -> bool:+ return self._initialized+++class BaseTradingAgent(BaseAgent):+ """+ Base class for trading agents that make buy/sell decisions.++ Provides common functionality for:+ - Processing market data+ - Making trading decisions+ - Managing portfolio state+ """++ def __init__(+ self,+ name: str,+ provider: str,+ model_id: str,+ api_key: Optional[str] = None,+ temperature: float = 0.7,+ instructions: Optional[List[str]] = None,+ ):+ super().__init__(name)+ self.provider = provider+ self.model_id = model_id+ self.api_key = api_key+ self.temperature = temperature+ self.instructions = instructions or self._default_instructions()+ self._agent = None+ self._decisions: List[ModelDecision] = []++ def _default_instructions(self) -> List[str]:+ """Default trading instructions."""+ return [+ "You are an autonomous trading agent in Alpha Arena.",+ "Your goal is to maximize P&L through systematic trading.",+ "Always respond with valid JSON only - no markdown, no explanations.",+ "Consider risk management and position sizing carefully.",+ ]++ @abstractmethod+ async def make_decision(+ self,+ market_data: MarketData,+ portfolio: PortfolioState,+ cycle_number: int,+ ) -> ModelDecision:+ """+ Make a trading decision based on market data and portfolio state.++ Args:+ market_data: Current market data+ portfolio: Current portfolio state+ cycle_number: Current cycle number++ Returns:+ ModelDecision with action, quantity, confidence, and reasoning+ """+ raise NotImplementedError++ async def stream(+ self,+ query: str,+ competition_id: str,+ cycle_number: int,+ dependencies: Optional[Dict] = None,+ ) -> AsyncGenerator[StreamResponse, None]:+ """+ Stream trading decision process.++ Dependencies should contain:+ - market_data: MarketData+ - portfolio: PortfolioState+ """+ from alpha_arena.types.responses import (+ decision_started,+ decision_completed,+ reasoning,+ error,+ done,+ )++ dependencies = dependencies or {}+ market_data = dependencies.get("market_data")+ portfolio = dependencies.get("portfolio")++ if not market_data or not portfolio:+ yield error("Missing market_data or portfolio in dependencies")+ return++ # Emit decision started+ yield decision_started(self.name, market_data.symbol)++ try:+ # Make the decision+ decision = await self.make_decision(market_data, portfolio, cycle_number)+ decision.competition_id = competition_id++ # Store decision+ self._decisions.append(decision)++ # Emit reasoning if available+ if decision.reasoning:+ yield reasoning(self.name, decision.reasoning)++ # Emit decision completed+ yield decision_completed(+ model_name=self.name,+ action=decision.action.value if hasattr(decision.action, 'value') else str(decision.action),+ symbol=decision.symbol,+ quantity=decision.quantity,+ confidence=decision.confidence,+ reasoning=decision.reasoning,+ )++ except Exception as e:+ logger.exception(f"Error making decision: {e}")+ yield error(f"Decision error: {str(e)}")++ yield done()++ def get_decisions(self, limit: int = 50) -> List[ModelDecision]:+ """Get recent decisions."""+ return self._decisions[-limit:]++ def clear_decisions(self) -> None:+ """Clear decision history."""+ self._decisions = []+++class LLMTradingAgent(BaseTradingAgent):+ """+ Trading agent powered by an LLM (OpenAI, Anthropic, etc.).++ Uses the Agno library for LLM interactions when available.+ """++ def __init__(+ self,+ name: str,+ provider: str,+ model_id: str,+ api_key: Optional[str] = None,+ temperature: float = 0.7,+ instructions: Optional[List[str]] = None,+ mode: str = "baseline",+ ):+ super().__init__(name, provider, model_id, api_key, temperature, instructions)+ self.mode = mode+ self._llm = None++ async def initialize(self) -> bool:+ """Initialize the LLM agent."""+ try:+ self._llm = await self._create_llm()+ if self._llm is None:+ logger.warning(f"LLM agent '{self.name}' initialized in mock mode (agno library not available)")+ await super().initialize()+ return True+ except Exception as e:+ logger.error(f"Failed to initialize LLM agent '{self.name}': {e}")+ # Still return True but use mock mode - don't block competition+ self._llm = None+ await super().initialize()+ logger.warning(f"Agent '{self.name}' will use mock decisions due to initialization error")+ return True++ async def _create_llm(self):+ """Create the LLM instance based on provider."""+ try:+ from agno.agent import Agent+ from agno.models.openai import OpenAIChat++ # Create model based on provider+ if self.provider == "openai":+ model = OpenAIChat(id=self.model_id, api_key=self.api_key)+ elif self.provider == "anthropic":+ try:+ from agno.models.anthropic import Claude+ model = Claude(id=self.model_id, api_key=self.api_key)+ except ImportError:+ # Fallback to OpenAI-compatible+ model = OpenAIChat(+ id=self.model_id,+ api_key=self.api_key,+ base_url="https://api.anthropic.com/v1",+ )+ elif self.provider == "google" or self.provider == "gemini":+ # Google Gemini - use OpenAI-compatible endpoint directly (more reliable)+ # Model IDs: gemini-2.0-flash, gemini-1.5-flash, gemini-1.5-pro, etc.+ logger.info(f"Using Google Gemini OpenAI-compatible endpoint for {self.model_id}")+ model = OpenAIChat(+ id=self.model_id,+ api_key=self.api_key,+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/",+ )+ elif self.provider == "deepseek":+ model = OpenAIChat(+ id=self.model_id,+ api_key=self.api_key,+ base_url="https://api.deepseek.com/v1",+ )+ elif self.provider == "groq":+ model = OpenAIChat(+ id=self.model_id,+ api_key=self.api_key,+ base_url="https://api.groq.com/openai/v1",+ )+ elif self.provider == "openrouter":+ model = OpenAIChat(+ id=self.model_id,+ api_key=self.api_key,+ base_url="https://openrouter.ai/api/v1",+ )+ elif self.provider == "fincept":+ # Fincept uses a custom API, not OpenAI-compatible+ # We'll handle this specially in make_decision+ logger.info("Fincept provider will use custom API handler")+ return "fincept_custom" # Special marker+ elif self.provider == "ollama":+ # Local Ollama instance+ model = OpenAIChat(+ id=self.model_id,+ api_key="ollama", # Ollama doesn't need real API key+ base_url="http://localhost:11434/v1",+ )+ else:+ # Default to OpenAI-compatible endpoint+ logger.warning(f"Unknown provider '{self.provider}', treating as OpenAI-compatible")+ model = OpenAIChat(id=self.model_id, api_key=self.api_key)++ # Create agent+ agent = Agent(+ name=f"Trader-{self.name}",+ role="Autonomous Trading Agent",+ model=model,+ instructions=self._get_mode_instructions(),+ markdown=False,+ )++ logger.info(f"Created LLM agent '{self.name}' with {self.provider}:{self.model_id}")+ return agent++ except ImportError as e:+ logger.warning(f"Agno not available, using mock agent: {e}")+ return None++ def _get_mode_instructions(self) -> List[str]:+ """Get instructions based on competition mode."""+ base = self.instructions.copy()++ if self.mode == "baseline":+ base.extend([+ "Use comprehensive analysis considering all market data.",+ "Manage risk carefully with appropriate position sizing.",+ ])+ elif self.mode == "monk":+ base.extend([+ "Capital preservation is paramount.",+ "Only take high-conviction trades (confidence > 0.75).",+ "Use strict stop-losses and conservative position sizing.",+ ])+ elif self.mode == "situational":+ base.extend([+ "You are competing against other AI models.",+ "Consider the competitive dynamics in your decisions.",+ ])+ elif self.mode == "max_leverage":+ base.extend([+ "Use maximum available capital on every trade.",+ "Set tight stop-losses to manage risk.",+ ])++ return base++ async def make_decision(+ self,+ market_data: MarketData,+ portfolio: PortfolioState,+ cycle_number: int,+ ) -> ModelDecision:+ """Make a trading decision using the LLM."""+ import json++ # Build prompt+ prompt = self._build_prompt(market_data, portfolio, cycle_number)++ if self._llm is None:+ # Mock decision for testing+ logger.warning(f"Agent '{self.name}' using mock decision (no LLM available)")+ return self._mock_decision(market_data, cycle_number)++ # Handle Fincept custom API+ if self._llm == "fincept_custom":+ return await self._fincept_decision(prompt, market_data, cycle_number)++ try:+ logger.info(f"Agent '{self.name}' requesting decision from {self.provider}:{self.model_id}...")++ # Get response from LLM+ response = self._llm.run(prompt)++ # Detailed response logging for debugging+ resp_type = type(response).__name__+ logger.info(f"Agent '{self.name}' received response type: {resp_type}")++ # Log response structure for debugging+ if hasattr(response, 'content'):+ content_type = type(response.content).__name__ if response.content else 'None'+ logger.debug(f"Response.content type: {content_type}")+ if isinstance(response.content, list):+ logger.debug(f"Response.content list length: {len(response.content)}")+ if response.content:+ first_item = response.content[0]+ logger.debug(f"First content item type: {type(first_item).__name__}")++ # Parse response content+ content = self._extract_content(response)+ content_preview = content[:200] if content else 'EMPTY'+ logger.info(f"Agent '{self.name}' extracted content (first 200 chars): {content_preview}")++ decision_data = self._parse_json_response(content)+ logger.info(f"Agent '{self.name}' parsed decision: {decision_data}")++ action_str = decision_data.get("action", "hold").lower()+ # Validate action+ if action_str not in ["buy", "sell", "hold", "short"]:+ logger.warning(f"Invalid action '{action_str}', defaulting to 'hold'")+ action_str = "hold"++ return ModelDecision(+ competition_id="", # Set by caller+ model_name=self.name,+ cycle_number=cycle_number,+ action=TradeAction(action_str),+ symbol=decision_data.get("symbol", market_data.symbol),+ quantity=float(decision_data.get("quantity", 0.01)),+ confidence=float(decision_data.get("confidence", 0.5)),+ reasoning=decision_data.get("reasoning", ""),+ price_at_decision=market_data.price,+ portfolio_value_before=portfolio.portfolio_value,+ )++ except Exception as e:+ import traceback+ error_details = traceback.format_exc()+ logger.error(f"Error in LLM decision for '{self.name}' ({self.provider}:{self.model_id}): {e}")+ logger.error(f"Traceback: {error_details}")++ # Create a more descriptive error message+ error_msg = str(e)+ if "getaddrinfo failed" in error_msg or "Connection" in error_msg:+ error_msg = f"Connection error to {self.provider} API"+ elif "401" in error_msg or "Unauthorized" in error_msg:+ error_msg = f"Invalid API key for {self.provider}"+ elif "429" in error_msg or "rate limit" in error_msg.lower():+ error_msg = f"Rate limit exceeded for {self.provider}"++ return ModelDecision(+ competition_id="",+ model_name=self.name,+ cycle_number=cycle_number,+ action=TradeAction.HOLD,+ symbol=market_data.symbol,+ quantity=0,+ confidence=0,+ reasoning=f"Error: {error_msg}",+ price_at_decision=market_data.price,+ )++ def _build_prompt(+ self,+ market_data: MarketData,+ portfolio: PortfolioState,+ cycle_number: int,+ ) -> str:+ """Build the trading prompt."""+ has_positions = len(portfolio.positions) > 0+ num_trades = portfolio.trades_count+ pnl = portfolio.portfolio_value - 10000 # Assuming 10k initial+ pnl_pct = (pnl / 10000) * 100++ if not has_positions and num_trades == 0:+ action_guidance = """+IMPORTANT: This is the start of the competition. You have NO open positions.+You MUST take a position (BUY or SELL) to participate. HOLD is NOT allowed at the start.+Analyze the market data and decide whether to go LONG (buy) or SHORT (sell).+Use approximately 10-20% of your capital for the initial position.+"""+ elif not has_positions:+ action_guidance = """+NOTE: You currently have NO open positions. Consider entering a new position.+Being fully in cash means you're not participating in market movements.+"""+ else:+ action_guidance = """+You have open positions. Decide whether to:+- BUY: Add to position or enter new long+- SELL: Close position or enter short+- HOLD: Maintain current position+"""++ return f"""ALPHA ARENA TRADING DECISION - Cycle #{cycle_number}++MARKET DATA:+Symbol: {market_data.symbol}+Price: ${market_data.price:,.2f}+Bid: ${market_data.bid:,.2f}+Ask: ${market_data.ask:,.2f}+24h High: ${market_data.high_24h:,.2f}+24h Low: ${market_data.low_24h:,.2f}+Volume: {market_data.volume_24h:,.2f}++YOUR PORTFOLIO:+Cash: ${portfolio.cash:,.2f}+Portfolio Value: ${portfolio.portfolio_value:,.2f}+P&L: ${pnl:+,.2f} ({pnl_pct:+.2f}%)+Open Positions: {len(portfolio.positions)}+Total Trades Made: {num_trades}+{action_guidance}+RESPONSE FORMAT (JSON ONLY - NO MARKDOWN, NO CODE BLOCKS):+{{+ "action": "buy" or "sell" or "hold",+ "symbol": "{market_data.symbol}",+ "quantity": 0.01,+ "confidence": 0.0 to 1.0,+ "reasoning": "brief explanation"+}}++Respond ONLY with the JSON object, nothing else.+"""++ def _extract_content(self, response) -> str:+ """Extract text content from LLM response (Agno RunOutput or other formats)."""+ try:+ # Handle string response directly+ if isinstance(response, str):+ return response++ # Log response type for debugging+ logger.debug(f"Extracting content from response type: {type(response).__name__}")++ # Handle Agno RunOutput object (main response type from agent.run())+ # RunOutput has: content (Any), messages (List[Message]), etc.+ if hasattr(response, 'content'):+ content = response.content+ if content is not None:+ if isinstance(content, str):+ return content+ elif isinstance(content, list):+ # Content might be a list of content parts (e.g., from Gemini)+ texts = []+ for part in content:+ text = self._extract_text_from_part(part)+ if text:+ texts.append(text)+ if texts:+ return '\n'.join(texts)+ elif isinstance(content, dict):+ # Content might be a dict with text/content key+ return content.get('text', content.get('content', str(content)))+ else:+ # Try to convert to string+ return str(content)++ # Handle response with messages attribute (fallback for some providers)+ if hasattr(response, 'messages') and response.messages:+ messages = response.messages+ if isinstance(messages, list) and len(messages) > 0:+ # Get the last assistant message+ for msg in reversed(messages):+ msg_content = self._extract_message_content(msg)+ if msg_content:+ return msg_content++ # Handle dict response (raw API response)+ if isinstance(response, dict):+ # Check common response keys+ for key in ['content', 'text', 'message', 'output', 'response']:+ if key in response:+ val = response[key]+ if isinstance(val, str):+ return val+ elif isinstance(val, list):+ texts = [self._extract_text_from_part(p) for p in val]+ return '\n'.join(filter(None, texts))+ elif val is not None:+ return str(val)++ # Fallback to string representation+ logger.warning(f"Unknown response format: {type(response)}, converting to string")+ return str(response)++ except Exception as e:+ logger.error(f"Error extracting content from response: {e}")+ logger.error(f"Response type: {type(response)}")+ return str(response)++ def _extract_text_from_part(self, part) -> Optional[str]:+ """Extract text from a content part (handles various formats)."""+ if part is None:+ return None+ if isinstance(part, str):+ return part+ if hasattr(part, 'text'):+ return part.text+ if isinstance(part, dict):+ return part.get('text', part.get('content', None))+ # For other objects, try common text attributes+ for attr in ['text', 'content', 'value', 'data']:+ if hasattr(part, attr):+ val = getattr(part, attr)+ if isinstance(val, str):+ return val+ return str(part)++ def _extract_message_content(self, msg) -> Optional[str]:+ """Extract content from a message object."""+ if isinstance(msg, str):+ return msg+ if hasattr(msg, 'content'):+ content = msg.content+ if isinstance(content, str):+ return content+ elif isinstance(content, list):+ texts = [self._extract_text_from_part(p) for p in content]+ return '\n'.join(filter(None, texts))+ elif content is not None:+ return str(content)+ if isinstance(msg, dict):+ return msg.get('content', msg.get('text', None))+ return None++ def _parse_json_response(self, content: str) -> Dict[str, Any]:+ """Parse JSON from LLM response."""+ import json+ import re++ if not content:+ logger.warning("Empty content received from LLM")+ return {"action": "hold", "quantity": 0, "confidence": 0, "reasoning": "Empty response from LLM"}++ original_content = content+ content = content.strip()++ # Remove markdown code blocks+ if '```' in content:+ # Find content between ``` markers+ parts = content.split('```')+ for part in parts:+ part = part.strip()+ if part.startswith('json'):+ part = part[4:].strip()+ if part.startswith('{') and part.endswith('}'):+ content = part+ break++ # Try direct JSON parsing first+ try:+ return json.loads(content)+ except json.JSONDecodeError:+ pass++ # Find JSON object in content using regex - handle nested braces+ json_match = re.search(r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}', content)+ if json_match:+ try:+ return json.loads(json_match.group())+ except json.JSONDecodeError:+ pass++ # Try to find simpler JSON pattern+ simple_match = re.search(r'\{[^{}]+\}', content)+ if simple_match:+ try:+ return json.loads(simple_match.group())+ except json.JSONDecodeError:+ pass++ # If all parsing fails, try to extract key-value pairs manually+ logger.warning(f"Failed to parse JSON, attempting manual extraction from: {content[:200]}")++ result = {"action": "hold", "quantity": 0, "confidence": 0, "reasoning": "Failed to parse LLM response"}++ # Try to extract action+ action_match = re.search(r'"action"\s*:\s*"(buy|sell|hold)"', content, re.IGNORECASE)+ if action_match:+ result["action"] = action_match.group(1).lower()++ # Try to extract quantity+ qty_match = re.search(r'"quantity"\s*:\s*([\d.]+)', content)+ if qty_match:+ result["quantity"] = float(qty_match.group(1))++ # Try to extract confidence+ conf_match = re.search(r'"confidence"\s*:\s*([\d.]+)', content)+ if conf_match:+ result["confidence"] = float(conf_match.group(1))++ # Try to extract reasoning+ reason_match = re.search(r'"reasoning"\s*:\s*"([^"]*)"', content)+ if reason_match:+ result["reasoning"] = reason_match.group(1)++ return result++ async def _fincept_decision(+ self,+ prompt: str,+ market_data: MarketData,+ cycle_number: int,+ ) -> ModelDecision:+ """Make a decision using Fincept's custom LLM API."""+ import httpx+ import json++ FINCEPT_URL = "https://finceptbackend.share.zrok.io/research/llm"++ try:+ logger.info(f"Agent '{self.name}' calling Fincept LLM API...")++ async with httpx.AsyncClient(timeout=60.0) as client:+ response = await client.post(+ FINCEPT_URL,+ json={+ "prompt": prompt,+ "max_tokens": 1024,+ "temperature": self.temperature,+ },+ headers={+ "Content-Type": "application/json",+ "X-API-Key": self.api_key or "", # Fincept uses X-API-Key header+ },+ )++ if response.status_code != 200:+ error_msg = f"Fincept API error: {response.status_code}"+ logger.error(f"{error_msg} - {response.text[:200]}")+ return ModelDecision(+ competition_id="",+ model_name=self.name,+ cycle_number=cycle_number,+ action=TradeAction.HOLD,+ symbol=market_data.symbol,+ quantity=0,+ confidence=0,+ reasoning=f"Error: {error_msg}",+ price_at_decision=market_data.price,+ )++ result = response.json()+ # Fincept API returns: {"success": true, "data": {"response": "..."}}+ data = result.get("data", result)+ content = data.get("response", data.get("content", data.get("text", str(result))))+ logger.info(f"Fincept response: {content[:200]}")++ decision_data = self._parse_json_response(content)++ action_str = decision_data.get("action", "hold").lower()+ if action_str not in ["buy", "sell", "hold", "short"]:+ action_str = "hold"++ return ModelDecision(+ competition_id="",+ model_name=self.name,+ cycle_number=cycle_number,+ action=TradeAction(action_str),+ symbol=decision_data.get("symbol", market_data.symbol),+ quantity=float(decision_data.get("quantity", 0.01)),+ confidence=float(decision_data.get("confidence", 0.5)),+ reasoning=decision_data.get("reasoning", ""),+ price_at_decision=market_data.price,+ )++ except Exception as e:+ logger.error(f"Fincept API error: {e}")+ return ModelDecision(+ competition_id="",+ model_name=self.name,+ cycle_number=cycle_number,+ action=TradeAction.HOLD,+ symbol=market_data.symbol,+ quantity=0,+ confidence=0,+ reasoning=f"Error: Fincept API - {str(e)}",+ price_at_decision=market_data.price,+ )++ def _mock_decision(self, market_data: MarketData, cycle_number: int) -> ModelDecision:+ """Generate a mock decision for testing."""+ import random++ actions = [TradeAction.BUY, TradeAction.SELL, TradeAction.HOLD]+ action = random.choice(actions)++ return ModelDecision(+ competition_id="",+ model_name=self.name,+ cycle_number=cycle_number,+ action=action,+ symbol=market_data.symbol,+ quantity=0.01 if action != TradeAction.HOLD else 0,+ confidence=random.uniform(0.5, 0.9),+ reasoning=f"Mock decision: {action.value}",+ price_at_decision=market_data.price,+ )diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/competition.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/competition.pynew file mode 100644index 000000000..6944f7028--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/competition.py@@ -0,0 +1,458 @@+"""+Alpha Arena Competition++Main competition orchestration class.+"""++import asyncio+import json+import time+from datetime import datetime+from typing import AsyncGenerator, Dict, List, Optional, Any++from alpha_arena.types.models import (+ Competition,+ CompetitionConfig,+ CompetitionStatus,+ CompetitionModel,+ CycleResult,+ LeaderboardEntry,+ MarketData,+ ModelDecision,+ PortfolioState,+ PerformanceSnapshot,+)+from alpha_arena.types.responses import (+ StreamResponse,+ decision_started,+ decision_completed,+ trade_executed,+ reasoning,+ market_data as market_data_response,+ leaderboard_update,+ cycle_completed,+ error,+ done,+ SystemResponseEvent,+)+from alpha_arena.core.base_agent import BaseTradingAgent, LLMTradingAgent+from alpha_arena.core.paper_trading import PaperTradingEngine+from alpha_arena.core.market_data import MarketDataProvider, get_market_data_provider+from alpha_arena.core.agent_manager import AgentManager, get_agent_manager+from alpha_arena.config.agent_cards import get_agent_card+from alpha_arena.utils.logging import get_logger+from alpha_arena.utils.uuid import generate_snapshot_id++logger = get_logger("competition")+++class AlphaArenaCompetition:+ """+ Main competition orchestration class.++ Manages the competition lifecycle:+ - Agent initialization+ - Cycle execution+ - Trade execution+ - Leaderboard updates+ - Performance tracking+ """++ def __init__(self, config: CompetitionConfig):+ self.config = config+ self.competition_id = config.competition_id+ self.status = CompetitionStatus.CREATED+ self.cycle_count = 0+ self.start_time: Optional[datetime] = None+ self.end_time: Optional[datetime] = None++ # Agents and trading engines+ self._agents: Dict[str, BaseTradingAgent] = {}+ self._engines: Dict[str, PaperTradingEngine] = {}+ self._market_provider: Optional[MarketDataProvider] = None++ # Tracking+ self._decisions: List[ModelDecision] = []+ self._snapshots: List[PerformanceSnapshot] = []+ self._cycle_results: List[CycleResult] = []+ self._is_running = False+ self._stop_requested = False++ async def initialize(self, api_keys: Dict[str, str]) -> bool:+ """+ Initialize the competition.++ Args:+ api_keys: Dict of provider -> api_key++ Returns:+ True if initialization successful+ """+ try:+ logger.info(f"Initializing competition {self.competition_id}")+ logger.info(f"API keys available for providers: {list(api_keys.keys())}")++ # Initialize market data provider with timeout+ try:+ self._market_provider = await asyncio.wait_for(+ get_market_data_provider(self.config.exchange_id),+ timeout=30.0+ )+ logger.info(f"Market data provider initialized for {self.config.exchange_id}")+ except asyncio.TimeoutError:+ logger.warning(f"Market data provider initialization timed out, using mock data")+ self._market_provider = await get_market_data_provider(self.config.exchange_id)++ # Create agents and trading engines for each model+ for model in self.config.models:+ logger.info(f"Initializing model: {model.name} (provider: {model.provider})")++ # Get agent card+ card = get_agent_card(model.name)++ if card:+ provider = card.provider+ model_id = card.model_id+ logger.info(f"Found agent card for {model.name}: {provider}/{model_id}")+ else:+ provider = model.provider+ model_id = model.model_id+ logger.info(f"Using model config: {provider}/{model_id}")++ # Get API key - try model-specific first, then provider-level+ api_key = model.api_key or api_keys.get(provider) or api_keys.get(provider.lower())++ if not api_key:+ logger.warning(f"No API key found for provider '{provider}' - agent will use mock mode")++ # Create agent+ agent = LLMTradingAgent(+ name=model.name,+ provider=provider,+ model_id=model_id,+ api_key=api_key,+ temperature=0.7,+ mode=self.config.mode.value if hasattr(self.config.mode, 'value') else self.config.mode,+ )++ # Initialize with timeout+ try:+ init_success = await asyncio.wait_for(+ agent.initialize(),+ timeout=30.0+ )+ if init_success:+ logger.info(f"Agent {model.name} initialized successfully")+ else:+ logger.warning(f"Agent {model.name} initialization returned False, using mock mode")+ except asyncio.TimeoutError:+ logger.warning(f"Agent {model.name} initialization timed out, using mock mode")++ self._agents[model.name] = agent++ # Create trading engine+ engine = PaperTradingEngine(+ model_name=model.name,+ initial_capital=model.initial_capital or self.config.initial_capital,+ )+ self._engines[model.name] = engine+ logger.info(f"Trading engine created for {model.name} with capital ${model.initial_capital or self.config.initial_capital}")++ self.status = CompetitionStatus.CREATED+ logger.info(f"Competition {self.competition_id} initialized with {len(self._agents)} agents")+ return True++ except Exception as e:+ logger.exception(f"Failed to initialize competition: {e}")+ self.status = CompetitionStatus.FAILED+ return False++ async def run_cycle(self) -> AsyncGenerator[StreamResponse, None]:+ """+ Run a single competition cycle.++ Yields streaming responses for:+ - Market data updates+ - Decision progress+ - Trade executions+ - Leaderboard updates+ """+ if self.status == CompetitionStatus.FAILED:+ yield error("Competition is in failed state")+ return++ self.cycle_count += 1+ cycle_number = self.cycle_count+ cycle_start = time.time()++ logger.info(f"Starting cycle {cycle_number}")++ # Start cycle notification+ yield StreamResponse(+ content=f"Starting cycle {cycle_number}",+ event=SystemResponseEvent.CYCLE_STARTED,+ metadata={"cycle_number": cycle_number},+ )++ try:+ # Fetch market data+ symbol = self.config.symbols[0] if self.config.symbols else "BTC/USD"+ market = await self._market_provider.get_ticker(symbol)++ yield market_data_response(+ symbol=market.symbol,+ price=market.price,+ change_pct=0.0, # Calculate if we have history+ )++ # Get decisions from each agent+ decisions: Dict[str, ModelDecision] = {}+ errors_list: List[str] = []++ for model_name, agent in self._agents.items():+ engine = self._engines[model_name]+ portfolio = engine.get_portfolio_state({symbol: market.price})++ yield decision_started(model_name, symbol)++ try:+ # Get decision from agent+ decision = await agent.make_decision(+ market_data=market,+ portfolio=portfolio,+ cycle_number=cycle_number,+ )+ decision.competition_id = self.competition_id+ decision.price_at_decision = market.price+ decision.portfolio_value_before = portfolio.portfolio_value++ # Emit reasoning+ if decision.reasoning:+ yield reasoning(model_name, decision.reasoning)++ # Execute trade+ trade_result = engine.execute_decision(decision, market)+ decision.trade_executed = trade_result++ # Get updated portfolio+ new_portfolio = engine.get_portfolio_state({symbol: market.price})+ decision.portfolio_value_after = new_portfolio.portfolio_value++ decisions[model_name] = decision+ self._decisions.append(decision)++ # Emit decision completed+ yield decision_completed(+ model_name=model_name,+ action=decision.action.value if hasattr(decision.action, 'value') else str(decision.action),+ symbol=decision.symbol,+ quantity=decision.quantity,+ confidence=decision.confidence,+ reasoning=decision.reasoning,+ )++ # Emit trade if executed+ action_value = decision.action.value if hasattr(decision.action, 'value') else str(decision.action)+ if trade_result.status == "executed" and action_value != "hold":+ yield trade_executed(+ model_name=model_name,+ action=trade_result.action.value if hasattr(trade_result.action, 'value') else str(trade_result.action),+ symbol=trade_result.symbol,+ quantity=trade_result.quantity,+ price=trade_result.price,+ pnl=trade_result.pnl,+ )++ except Exception as e:+ error_msg = f"Error processing {model_name}: {str(e)}"+ logger.exception(error_msg)+ errors_list.append(error_msg)+ yield error(error_msg)++ # Create snapshots for charting+ await self._create_snapshots(cycle_number, market.price)++ # Update leaderboard+ leaderboard = self._calculate_leaderboard({symbol: market.price})+ yield leaderboard_update(+ leaderboard=[entry.model_dump() for entry in leaderboard],+ cycle_number=cycle_number,+ )++ # Create cycle result+ cycle_time = time.time() - cycle_start+ cycle_result = CycleResult(+ cycle_number=cycle_number,+ market_data=market,+ decisions=decisions,+ cycle_time_seconds=cycle_time,+ errors=errors_list,+ )+ self._cycle_results.append(cycle_result)++ yield cycle_completed(cycle_number, cycle_time)+ yield done()++ except Exception as e:+ logger.exception(f"Cycle {cycle_number} failed: {e}")+ yield error(f"Cycle failed: {str(e)}")++ async def _create_snapshots(self, cycle_number: int, current_price: float):+ """Create performance snapshots for all models."""+ symbol = self.config.symbols[0] if self.config.symbols else "BTC/USD"++ for model_name, engine in self._engines.items():+ portfolio = engine.get_portfolio_state({symbol: current_price})++ snapshot = PerformanceSnapshot(+ id=generate_snapshot_id(self.competition_id, model_name, cycle_number),+ competition_id=self.competition_id,+ cycle_number=cycle_number,+ model_name=model_name,+ portfolio_value=portfolio.portfolio_value,+ cash=portfolio.cash,+ pnl=portfolio.total_pnl,+ return_pct=((portfolio.portfolio_value / self.config.initial_capital) - 1) * 100,+ positions_count=len(portfolio.positions),+ trades_count=portfolio.trades_count,+ )+ self._snapshots.append(snapshot)++ def _calculate_leaderboard(self, prices: Dict[str, float]) -> List[LeaderboardEntry]:+ """Calculate current leaderboard."""+ entries = []++ for model_name, engine in self._engines.items():+ portfolio = engine.get_portfolio_state(prices)++ return_pct = ((portfolio.portfolio_value / self.config.initial_capital) - 1) * 100++ entries.append(LeaderboardEntry(+ rank=0, # Will be set after sorting+ model_name=model_name,+ portfolio_value=portfolio.portfolio_value,+ total_pnl=portfolio.total_pnl,+ return_pct=return_pct,+ trades_count=portfolio.trades_count,+ cash=portfolio.cash,+ positions_count=len(portfolio.positions),+ ))++ # Sort by portfolio value+ entries.sort(key=lambda x: x.portfolio_value, reverse=True)++ # Set ranks+ for i, entry in enumerate(entries):+ entry.rank = i + 1++ return entries++ async def start(self, api_keys: Dict[str, str]) -> bool:+ """Start the competition."""+ if self.status not in [CompetitionStatus.CREATED, CompetitionStatus.PAUSED]:+ logger.warning(f"Cannot start competition in state: {self.status}")+ return False++ if not await self.initialize(api_keys):+ return False++ self.status = CompetitionStatus.RUNNING+ self.start_time = datetime.now()+ self._is_running = True+ self._stop_requested = False++ logger.info(f"Competition {self.competition_id} started")+ return True++ async def stop(self):+ """Stop the competition."""+ self._stop_requested = True+ self._is_running = False+ self.status = CompetitionStatus.PAUSED+ logger.info(f"Competition {self.competition_id} stopped")++ async def complete(self):+ """Complete the competition."""+ self._stop_requested = True+ self._is_running = False+ self.status = CompetitionStatus.COMPLETED+ self.end_time = datetime.now()+ logger.info(f"Competition {self.competition_id} completed")++ def get_leaderboard(self) -> List[LeaderboardEntry]:+ """Get current leaderboard."""+ symbol = self.config.symbols[0] if self.config.symbols else "BTC/USD"+ # Use last known prices or estimate+ prices = {}+ if self._cycle_results:+ last_cycle = self._cycle_results[-1]+ prices = {symbol: last_cycle.market_data.price}+ return self._calculate_leaderboard(prices)++ def get_decisions(self, model_name: Optional[str] = None, limit: int = 50) -> List[ModelDecision]:+ """Get recent decisions."""+ decisions = self._decisions+ if model_name:+ decisions = [d for d in decisions if d.model_name == model_name]+ return decisions[-limit:]++ def get_snapshots(self, model_name: Optional[str] = None) -> List[PerformanceSnapshot]:+ """Get performance snapshots."""+ snapshots = self._snapshots+ if model_name:+ snapshots = [s for s in snapshots if s.model_name == model_name]+ return snapshots++ def get_portfolio_states(self) -> Dict[str, PortfolioState]:+ """Get current portfolio states for all models."""+ symbol = self.config.symbols[0] if self.config.symbols else "BTC/USD"+ prices = {}+ if self._cycle_results:+ last_cycle = self._cycle_results[-1]+ prices = {symbol: last_cycle.market_data.price}++ return {+ name: engine.get_portfolio_state(prices)+ for name, engine in self._engines.items()+ }++ def to_dict(self) -> Dict[str, Any]:+ """Convert competition state to dictionary."""+ return {+ "competition_id": self.competition_id,+ "config": self.config.model_dump(),+ "status": self.status.value,+ "cycle_count": self.cycle_count,+ "start_time": self.start_time.isoformat() if self.start_time else None,+ "end_time": self.end_time.isoformat() if self.end_time else None,+ "leaderboard": [e.model_dump() for e in self.get_leaderboard()],+ }+++# Competition registry+_competitions: Dict[str, AlphaArenaCompetition] = {}+++def get_competition(competition_id: str) -> Optional[AlphaArenaCompetition]:+ """Get a competition by ID."""+ return _competitions.get(competition_id)+++def create_competition(config: CompetitionConfig) -> AlphaArenaCompetition:+ """Create a new competition."""+ competition = AlphaArenaCompetition(config)+ _competitions[config.competition_id] = competition+ return competition+++def list_competitions() -> List[AlphaArenaCompetition]:+ """List all competitions."""+ return list(_competitions.values())+++def delete_competition(competition_id: str) -> bool:+ """Delete a competition."""+ if competition_id in _competitions:+ del _competitions[competition_id]+ return True+ return Falsediff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/database.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/database.pynew file mode 100644index 000000000..9ebb6ed8d--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/database.py@@ -0,0 +1,428 @@+"""+Database Persistence Layer++SQLite-based persistence for competition state.+"""++import json+import sqlite3+from datetime import datetime+from pathlib import Path+from typing import Dict, List, Optional, Any+from contextlib import contextmanager++from alpha_arena.types.models import (+ Competition,+ CompetitionConfig,+ CompetitionStatus,+ ModelDecision,+ PerformanceSnapshot,+ LeaderboardEntry,+)+from alpha_arena.utils.logging import get_logger++logger = get_logger("database")+++class AlphaArenaDatabase:+ """+ SQLite database for Alpha Arena persistence.+ """++ def __init__(self, db_path: Optional[str] = None):+ if db_path is None:+ # Default to user's app data directory+ app_data = Path.home() / ".fincept" / "alpha_arena"+ app_data.mkdir(parents=True, exist_ok=True)+ db_path = str(app_data / "alpha_arena.db")++ self.db_path = db_path+ self._initialize_db()++ @contextmanager+ def _get_connection(self):+ """Get a database connection."""+ conn = sqlite3.connect(self.db_path)+ conn.row_factory = sqlite3.Row+ try:+ yield conn+ conn.commit()+ except Exception:+ conn.rollback()+ raise+ finally:+ conn.close()++ def _initialize_db(self):+ """Initialize database schema."""+ with self._get_connection() as conn:+ cursor = conn.cursor()++ # Competitions table+ cursor.execute("""+ CREATE TABLE IF NOT EXISTS competitions (+ competition_id TEXT PRIMARY KEY,+ config TEXT NOT NULL,+ status TEXT NOT NULL,+ cycle_count INTEGER DEFAULT 0,+ start_time TEXT,+ end_time TEXT,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL+ )+ """)++ # Decisions table+ cursor.execute("""+ CREATE TABLE IF NOT EXISTS decisions (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ competition_id TEXT NOT NULL,+ model_name TEXT NOT NULL,+ cycle_number INTEGER NOT NULL,+ action TEXT NOT NULL,+ symbol TEXT NOT NULL,+ quantity REAL NOT NULL,+ confidence REAL NOT NULL,+ reasoning TEXT,+ price_at_decision REAL,+ trade_status TEXT,+ trade_pnl REAL,+ timestamp TEXT NOT NULL,+ FOREIGN KEY (competition_id) REFERENCES competitions(competition_id)+ )+ """)++ # Snapshots table+ cursor.execute("""+ CREATE TABLE IF NOT EXISTS snapshots (+ id TEXT PRIMARY KEY,+ competition_id TEXT NOT NULL,+ model_name TEXT NOT NULL,+ cycle_number INTEGER NOT NULL,+ portfolio_value REAL NOT NULL,+ cash REAL NOT NULL,+ pnl REAL NOT NULL,+ return_pct REAL NOT NULL,+ positions_count INTEGER DEFAULT 0,+ trades_count INTEGER DEFAULT 0,+ timestamp TEXT NOT NULL,+ FOREIGN KEY (competition_id) REFERENCES competitions(competition_id)+ )+ """)++ # Leaderboard history table+ cursor.execute("""+ CREATE TABLE IF NOT EXISTS leaderboard_history (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ competition_id TEXT NOT NULL,+ cycle_number INTEGER NOT NULL,+ leaderboard TEXT NOT NULL,+ timestamp TEXT NOT NULL,+ FOREIGN KEY (competition_id) REFERENCES competitions(competition_id)+ )+ """)++ # Create indexes+ cursor.execute("""+ CREATE INDEX IF NOT EXISTS idx_decisions_competition+ ON decisions(competition_id, model_name, cycle_number)+ """)++ cursor.execute("""+ CREATE INDEX IF NOT EXISTS idx_snapshots_competition+ ON snapshots(competition_id, model_name, cycle_number)+ """)++ logger.info(f"Database initialized at {self.db_path}")++ # ==================== Competition Methods ====================++ def save_competition(self, config: CompetitionConfig, status: CompetitionStatus) -> bool:+ """Save or update a competition."""+ now = datetime.now().isoformat()++ with self._get_connection() as conn:+ cursor = conn.cursor()++ cursor.execute("""+ INSERT OR REPLACE INTO competitions+ (competition_id, config, status, cycle_count, start_time, end_time, created_at, updated_at)+ VALUES (?, ?, ?, 0, NULL, NULL, ?, ?)+ """, (+ config.competition_id,+ json.dumps(config.model_dump()),+ status.value,+ now,+ now,+ ))++ logger.info(f"Saved competition: {config.competition_id}")+ return True++ def update_competition_status(+ self,+ competition_id: str,+ status: CompetitionStatus,+ cycle_count: Optional[int] = None,+ start_time: Optional[datetime] = None,+ end_time: Optional[datetime] = None,+ ) -> bool:+ """Update competition status."""+ now = datetime.now().isoformat()++ with self._get_connection() as conn:+ cursor = conn.cursor()++ updates = ["status = ?", "updated_at = ?"]+ values = [status.value, now]++ if cycle_count is not None:+ updates.append("cycle_count = ?")+ values.append(cycle_count)++ if start_time is not None:+ updates.append("start_time = ?")+ values.append(start_time.isoformat())++ if end_time is not None:+ updates.append("end_time = ?")+ values.append(end_time.isoformat())++ values.append(competition_id)++ cursor.execute(f"""+ UPDATE competitions+ SET {', '.join(updates)}+ WHERE competition_id = ?+ """, values)++ return True++ def get_competition(self, competition_id: str) -> Optional[Dict]:+ """Get competition by ID."""+ with self._get_connection() as conn:+ cursor = conn.cursor()+ cursor.execute("""+ SELECT * FROM competitions WHERE competition_id = ?+ """, (competition_id,))+ row = cursor.fetchone()++ if row:+ return {+ "competition_id": row["competition_id"],+ "config": json.loads(row["config"]),+ "status": row["status"],+ "cycle_count": row["cycle_count"],+ "start_time": row["start_time"],+ "end_time": row["end_time"],+ "created_at": row["created_at"],+ "updated_at": row["updated_at"],+ }+ return None++ def list_competitions(self, limit: int = 50) -> List[Dict]:+ """List all competitions."""+ with self._get_connection() as conn:+ cursor = conn.cursor()+ cursor.execute("""+ SELECT * FROM competitions+ ORDER BY created_at DESC+ LIMIT ?+ """, (limit,))++ return [+ {+ "competition_id": row["competition_id"],+ "config": json.loads(row["config"]),+ "status": row["status"],+ "cycle_count": row["cycle_count"],+ "start_time": row["start_time"],+ "end_time": row["end_time"],+ "created_at": row["created_at"],+ }+ for row in cursor.fetchall()+ ]++ def delete_competition(self, competition_id: str) -> bool:+ """Delete a competition and all related data."""+ with self._get_connection() as conn:+ cursor = conn.cursor()++ # Delete related data+ cursor.execute("DELETE FROM decisions WHERE competition_id = ?", (competition_id,))+ cursor.execute("DELETE FROM snapshots WHERE competition_id = ?", (competition_id,))+ cursor.execute("DELETE FROM leaderboard_history WHERE competition_id = ?", (competition_id,))+ cursor.execute("DELETE FROM competitions WHERE competition_id = ?", (competition_id,))++ logger.info(f"Deleted competition: {competition_id}")+ return True++ # ==================== Decision Methods ====================++ def save_decision(self, decision: ModelDecision) -> int:+ """Save a trading decision."""+ with self._get_connection() as conn:+ cursor = conn.cursor()++ trade_status = None+ trade_pnl = None+ if decision.trade_executed:+ trade_status = decision.trade_executed.status+ trade_pnl = decision.trade_executed.pnl++ cursor.execute("""+ INSERT INTO decisions+ (competition_id, model_name, cycle_number, action, symbol, quantity,+ confidence, reasoning, price_at_decision, trade_status, trade_pnl, timestamp)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """, (+ decision.competition_id,+ decision.model_name,+ decision.cycle_number,+ decision.action.value if hasattr(decision.action, 'value') else str(decision.action),+ decision.symbol,+ decision.quantity,+ decision.confidence,+ decision.reasoning,+ decision.price_at_decision,+ trade_status,+ trade_pnl,+ decision.timestamp.isoformat(),+ ))++ return cursor.lastrowid++ def get_decisions(+ self,+ competition_id: str,+ model_name: Optional[str] = None,+ limit: int = 100,+ ) -> List[Dict]:+ """Get decisions for a competition."""+ with self._get_connection() as conn:+ cursor = conn.cursor()++ if model_name:+ cursor.execute("""+ SELECT * FROM decisions+ WHERE competition_id = ? AND model_name = ?+ ORDER BY cycle_number DESC+ LIMIT ?+ """, (competition_id, model_name, limit))+ else:+ cursor.execute("""+ SELECT * FROM decisions+ WHERE competition_id = ?+ ORDER BY cycle_number DESC, model_name+ LIMIT ?+ """, (competition_id, limit))++ return [dict(row) for row in cursor.fetchall()]++ # ==================== Snapshot Methods ====================++ def save_snapshot(self, snapshot: PerformanceSnapshot) -> bool:+ """Save a performance snapshot."""+ with self._get_connection() as conn:+ cursor = conn.cursor()++ cursor.execute("""+ INSERT OR REPLACE INTO snapshots+ (id, competition_id, model_name, cycle_number, portfolio_value,+ cash, pnl, return_pct, positions_count, trades_count, timestamp)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """, (+ snapshot.id,+ snapshot.competition_id,+ snapshot.model_name,+ snapshot.cycle_number,+ snapshot.portfolio_value,+ snapshot.cash,+ snapshot.pnl,+ snapshot.return_pct,+ snapshot.positions_count,+ snapshot.trades_count,+ snapshot.timestamp.isoformat(),+ ))++ return True++ def get_snapshots(+ self,+ competition_id: str,+ model_name: Optional[str] = None,+ ) -> List[Dict]:+ """Get snapshots for charting."""+ with self._get_connection() as conn:+ cursor = conn.cursor()++ if model_name:+ cursor.execute("""+ SELECT * FROM snapshots+ WHERE competition_id = ? AND model_name = ?+ ORDER BY cycle_number+ """, (competition_id, model_name))+ else:+ cursor.execute("""+ SELECT * FROM snapshots+ WHERE competition_id = ?+ ORDER BY cycle_number, model_name+ """, (competition_id,))++ return [dict(row) for row in cursor.fetchall()]++ # ==================== Leaderboard Methods ====================++ def save_leaderboard(+ self,+ competition_id: str,+ cycle_number: int,+ leaderboard: List[LeaderboardEntry],+ ) -> bool:+ """Save leaderboard snapshot."""+ with self._get_connection() as conn:+ cursor = conn.cursor()++ cursor.execute("""+ INSERT INTO leaderboard_history+ (competition_id, cycle_number, leaderboard, timestamp)+ VALUES (?, ?, ?, ?)+ """, (+ competition_id,+ cycle_number,+ json.dumps([e.model_dump() for e in leaderboard]),+ datetime.now().isoformat(),+ ))++ return True++ def get_latest_leaderboard(self, competition_id: str) -> Optional[List[Dict]]:+ """Get the latest leaderboard for a competition."""+ with self._get_connection() as conn:+ cursor = conn.cursor()++ cursor.execute("""+ SELECT leaderboard FROM leaderboard_history+ WHERE competition_id = ?+ ORDER BY cycle_number DESC+ LIMIT 1+ """, (competition_id,))++ row = cursor.fetchone()+ if row:+ return json.loads(row["leaderboard"])+ return None+++# Singleton instance+_db: Optional[AlphaArenaDatabase] = None+++def get_database(db_path: Optional[str] = None) -> AlphaArenaDatabase:+ """Get the database instance."""+ global _db++ if _db is None:+ _db = AlphaArenaDatabase(db_path)++ return _dbdiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/evaluation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/evaluation.pynew file mode 100644index 000000000..25e0fb6aa--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/evaluation.py@@ -0,0 +1,378 @@+"""+Evaluation Module++Tracks and evaluates agent prediction accuracy and performance.+"""++from datetime import datetime+from typing import Dict, List, Optional, Any+from pydantic import BaseModel, Field+import math++from alpha_arena.types.models import ModelDecision, TradeAction, TradeResult+from alpha_arena.utils.logging import get_logger++logger = get_logger("evaluation")+++class PredictionRecord(BaseModel):+ """Record of a prediction for evaluation."""++ decision_id: str+ model_name: str+ action: str+ symbol: str+ confidence: float+ price_at_decision: float+ timestamp: datetime = Field(default_factory=datetime.now)++ # Outcome data (filled in later)+ price_after: Optional[float] = None+ actual_return: Optional[float] = None+ was_correct: Optional[bool] = None+ pnl: Optional[float] = None+++class ModelMetrics(BaseModel):+ """Performance metrics for a model."""++ model_name: str+ total_decisions: int = 0+ correct_decisions: int = 0+ total_pnl: float = 0.0+ win_rate: float = 0.0+ avg_confidence: float = 0.0+ avg_return: float = 0.0++ # Calibration metrics+ confidence_accuracy_correlation: float = 0.0+ overconfidence_ratio: float = 0.0++ # Risk metrics+ sharpe_ratio: float = 0.0+ max_drawdown: float = 0.0+ profit_factor: float = 0.0++ # Trade statistics+ avg_trade_pnl: float = 0.0+ best_trade: float = 0.0+ worst_trade: float = 0.0+ consecutive_wins: int = 0+ consecutive_losses: int = 0+++class EvaluationResult(BaseModel):+ """Result of an evaluation."""++ passed: bool = True+ score: float = 0.0+ details: Dict[str, Any] = Field(default_factory=dict)+++class EvaluationModule:+ """+ Evaluates agent prediction accuracy and trading performance.+ """++ def __init__(self, lookback_periods: int = 1):+ self.lookback_periods = lookback_periods+ self._predictions: Dict[str, List[PredictionRecord]] = {}+ self._returns: Dict[str, List[float]] = {}+ self._pnls: Dict[str, List[float]] = {}++ def record_decision(+ self,+ decision: ModelDecision,+ trade_result: Optional[TradeResult] = None,+ ):+ """+ Record a decision for later evaluation.++ Args:+ decision: The trading decision made+ trade_result: Optional trade execution result+ """+ model_name = decision.model_name++ if model_name not in self._predictions:+ self._predictions[model_name] = []+ self._returns[model_name] = []+ self._pnls[model_name] = []++ record = PredictionRecord(+ decision_id=f"{decision.competition_id}_{decision.model_name}_{decision.cycle_number}",+ model_name=model_name,+ action=decision.action.value if hasattr(decision.action, 'value') else str(decision.action),+ symbol=decision.symbol,+ confidence=decision.confidence,+ price_at_decision=decision.price_at_decision or 0,+ )++ if trade_result and trade_result.pnl is not None:+ record.pnl = trade_result.pnl+ self._pnls[model_name].append(trade_result.pnl)++ self._predictions[model_name].append(record)++ def update_outcome(+ self,+ model_name: str,+ current_price: float,+ lookback: int = 1,+ ):+ """+ Update prediction outcomes with current price.++ Args:+ model_name: Model to update+ current_price: Current market price+ lookback: How many previous predictions to update+ """+ if model_name not in self._predictions:+ return++ predictions = self._predictions[model_name]++ for i in range(max(0, len(predictions) - lookback), len(predictions)):+ pred = predictions[i]+ if pred.price_after is not None:+ continue++ pred.price_after = current_price+ price_change = (current_price - pred.price_at_decision) / pred.price_at_decision++ pred.actual_return = price_change++ # Determine if prediction was correct+ if pred.action == "hold":+ pred.was_correct = True # Hold is neutral+ elif pred.action in ["buy", "long"]:+ pred.was_correct = price_change > 0+ elif pred.action in ["sell", "short"]:+ pred.was_correct = price_change < 0+ else:+ pred.was_correct = None++ self._returns[model_name].append(price_change)++ def get_model_metrics(self, model_name: str) -> ModelMetrics:+ """+ Calculate comprehensive metrics for a model.++ Args:+ model_name: Model to evaluate++ Returns:+ ModelMetrics with all performance metrics+ """+ if model_name not in self._predictions:+ return ModelMetrics(model_name=model_name)++ predictions = self._predictions[model_name]+ if not predictions:+ return ModelMetrics(model_name=model_name)++ # Basic counts+ total = len(predictions)+ evaluated = [p for p in predictions if p.was_correct is not None]+ correct = sum(1 for p in evaluated if p.was_correct)++ # Win rate+ win_rate = correct / len(evaluated) if evaluated else 0++ # Average confidence+ avg_confidence = sum(p.confidence for p in predictions) / total++ # Returns and P&L+ returns = self._returns.get(model_name, [])+ pnls = self._pnls.get(model_name, [])++ avg_return = sum(returns) / len(returns) if returns else 0+ total_pnl = sum(pnls)++ # Trade statistics+ if pnls:+ avg_trade_pnl = total_pnl / len(pnls)+ best_trade = max(pnls)+ worst_trade = min(pnls)+ else:+ avg_trade_pnl = 0+ best_trade = 0+ worst_trade = 0++ # Sharpe ratio (simplified - assumes risk-free rate of 0)+ if returns and len(returns) > 1:+ mean_return = sum(returns) / len(returns)+ variance = sum((r - mean_return) ** 2 for r in returns) / len(returns)+ std_dev = math.sqrt(variance) if variance > 0 else 0+ sharpe_ratio = mean_return / std_dev if std_dev > 0 else 0+ else:+ sharpe_ratio = 0++ # Maximum drawdown+ max_drawdown = self._calculate_max_drawdown(pnls)++ # Profit factor+ gains = sum(p for p in pnls if p > 0)+ losses = abs(sum(p for p in pnls if p < 0))+ profit_factor = gains / losses if losses > 0 else float('inf') if gains > 0 else 0++ # Consecutive wins/losses+ consecutive_wins, consecutive_losses = self._calculate_streaks(pnls)++ # Calibration metrics+ confidence_accuracy = self._calculate_calibration(evaluated)++ return ModelMetrics(+ model_name=model_name,+ total_decisions=total,+ correct_decisions=correct,+ total_pnl=total_pnl,+ win_rate=win_rate,+ avg_confidence=avg_confidence,+ avg_return=avg_return,+ confidence_accuracy_correlation=confidence_accuracy,+ sharpe_ratio=sharpe_ratio,+ max_drawdown=max_drawdown,+ profit_factor=profit_factor,+ avg_trade_pnl=avg_trade_pnl,+ best_trade=best_trade,+ worst_trade=worst_trade,+ consecutive_wins=consecutive_wins,+ consecutive_losses=consecutive_losses,+ )++ def _calculate_max_drawdown(self, pnls: List[float]) -> float:+ """Calculate maximum drawdown from P&L series."""+ if not pnls:+ return 0++ cumulative = 0+ peak = 0+ max_dd = 0++ for pnl in pnls:+ cumulative += pnl+ peak = max(peak, cumulative)+ drawdown = peak - cumulative+ max_dd = max(max_dd, drawdown)++ return max_dd++ def _calculate_streaks(self, pnls: List[float]) -> tuple:+ """Calculate consecutive win/loss streaks."""+ if not pnls:+ return 0, 0++ max_wins = 0+ max_losses = 0+ current_wins = 0+ current_losses = 0++ for pnl in pnls:+ if pnl > 0:+ current_wins += 1+ current_losses = 0+ max_wins = max(max_wins, current_wins)+ elif pnl < 0:+ current_losses += 1+ current_wins = 0+ max_losses = max(max_losses, current_losses)+ else:+ current_wins = 0+ current_losses = 0++ return max_wins, max_losses++ def _calculate_calibration(self, predictions: List[PredictionRecord]) -> float:+ """+ Calculate calibration score.++ A well-calibrated model has confidence scores that match actual accuracy.+ """+ if len(predictions) < 5:+ return 0++ # Bin predictions by confidence+ bins = [(0, 0.25), (0.25, 0.5), (0.5, 0.75), (0.75, 1.0)]+ calibration_errors = []++ for low, high in bins:+ bin_preds = [p for p in predictions if low <= p.confidence < high]+ if bin_preds:+ expected_accuracy = (low + high) / 2+ actual_accuracy = sum(1 for p in bin_preds if p.was_correct) / len(bin_preds)+ calibration_errors.append(abs(expected_accuracy - actual_accuracy))++ return 1 - (sum(calibration_errors) / len(calibration_errors)) if calibration_errors else 0++ def evaluate_prediction(+ self,+ prediction: Dict[str, Any],+ actual: Dict[str, Any],+ ) -> EvaluationResult:+ """+ Evaluate a single prediction against actual outcome.++ Args:+ prediction: Predicted values+ actual: Actual observed values++ Returns:+ EvaluationResult with score and details+ """+ score = 0.0+ details = {}++ predicted_action = prediction.get("action", "hold").lower()+ predicted_price = prediction.get("price")+ actual_price = actual.get("price")++ if predicted_price and actual_price:+ price_diff = actual_price - predicted_price+ price_diff_pct = (price_diff / predicted_price) * 100++ # Check if direction was correct+ if predicted_action == "buy" and price_diff > 0:+ score = 1.0+ details["direction_correct"] = True+ elif predicted_action in ["sell", "short"] and price_diff < 0:+ score = 1.0+ details["direction_correct"] = True+ elif predicted_action == "hold":+ score = 0.5 # Neutral+ details["direction_correct"] = None+ else:+ score = 0.0+ details["direction_correct"] = False++ details["price_change_pct"] = price_diff_pct++ return EvaluationResult(+ passed=score >= 0.5,+ score=score,+ details=details,+ )++ def get_comparison_report(self) -> Dict[str, ModelMetrics]:+ """+ Get comparison report of all models.++ Returns:+ Dict of model name to metrics+ """+ return {+ name: self.get_model_metrics(name)+ for name in self._predictions.keys()+ }++ def clear_history(self, model_name: Optional[str] = None):+ """Clear prediction history."""+ if model_name:+ self._predictions.pop(model_name, None)+ self._returns.pop(model_name, None)+ self._pnls.pop(model_name, None)+ else:+ self._predictions.clear()+ self._returns.clear()+ self._pnls.clear()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/guardrails.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/guardrails.pynew file mode 100644index 000000000..064f74aeb--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/guardrails.py@@ -0,0 +1,355 @@+"""+Guardrails Module++Input/output validation for trading decisions.+"""++import re+from typing import Dict, List, Optional, Any+from pydantic import BaseModel, Field++from alpha_arena.types.models import ModelDecision, TradeAction+from alpha_arena.utils.logging import get_logger++logger = get_logger("guardrails")+++class GuardrailResult(BaseModel):+ """Result of a guardrail check."""++ passed: bool = Field(..., description="Whether the check passed")+ violations: List[str] = Field(default_factory=list, description="List of violations")+ warnings: List[str] = Field(default_factory=list, description="List of warnings")+ modified_value: Optional[Any] = Field(None, description="Modified value if sanitized")+++class TradingGuardrails:+ """+ Guardrails for trading decisions.++ Validates:+ - Position sizing limits+ - Risk management rules+ - Input sanitization+ """++ def __init__(+ self,+ max_position_pct: float = 0.5,+ max_single_trade_pct: float = 0.25,+ max_drawdown_pct: float = 0.2,+ min_confidence: float = 0.3,+ blocked_symbols: Optional[List[str]] = None,+ ):+ self.max_position_pct = max_position_pct+ self.max_single_trade_pct = max_single_trade_pct+ self.max_drawdown_pct = max_drawdown_pct+ self.min_confidence = min_confidence+ self.blocked_symbols = blocked_symbols or []++ def check_decision(+ self,+ decision: ModelDecision,+ portfolio_value: float,+ current_positions_value: float = 0,+ ) -> GuardrailResult:+ """+ Check a trading decision against guardrails.++ Args:+ decision: The trading decision to check+ portfolio_value: Current portfolio value+ current_positions_value: Value of current positions++ Returns:+ GuardrailResult with pass/fail and any violations+ """+ violations = []+ warnings = []++ # Check blocked symbols+ if decision.symbol in self.blocked_symbols:+ violations.append(f"Symbol {decision.symbol} is blocked")++ # Check confidence threshold+ if decision.confidence < self.min_confidence and decision.action != TradeAction.HOLD:+ warnings.append(+ f"Low confidence ({decision.confidence:.0%}) below threshold ({self.min_confidence:.0%})"+ )++ # Check position sizing+ if decision.action in [TradeAction.BUY, TradeAction.SHORT]:+ trade_value = decision.quantity * (decision.price_at_decision or 0)+ trade_pct = trade_value / portfolio_value if portfolio_value > 0 else 1++ if trade_pct > self.max_single_trade_pct:+ violations.append(+ f"Trade size ({trade_pct:.0%}) exceeds max ({self.max_single_trade_pct:.0%})"+ )++ # Check total position limit+ new_position_value = current_positions_value + trade_value+ position_pct = new_position_value / portfolio_value if portfolio_value > 0 else 1++ if position_pct > self.max_position_pct:+ violations.append(+ f"Total position ({position_pct:.0%}) would exceed max ({self.max_position_pct:.0%})"+ )++ # Check for zero quantity on non-hold actions+ if decision.action != TradeAction.HOLD and decision.quantity <= 0:+ warnings.append("Non-hold action with zero quantity")++ return GuardrailResult(+ passed=len(violations) == 0,+ violations=violations,+ warnings=warnings,+ )++ def sanitize_reasoning(self, reasoning: str) -> str:+ """+ Sanitize reasoning text to remove potentially harmful content.++ Args:+ reasoning: Raw reasoning text++ Returns:+ Sanitized reasoning text+ """+ if not reasoning:+ return ""++ # Remove any potential injection patterns+ sanitized = reasoning++ # Remove script tags+ sanitized = re.sub(r'<script[^>]*>.*?</script>', '', sanitized, flags=re.IGNORECASE | re.DOTALL)++ # Remove other HTML tags+ sanitized = re.sub(r'<[^>]+>', '', sanitized)++ # Limit length+ max_length = 1000+ if len(sanitized) > max_length:+ sanitized = sanitized[:max_length] + "..."++ return sanitized.strip()++ def validate_json_response(self, response: str) -> GuardrailResult:+ """+ Validate that a response is valid JSON and contains expected fields.++ Args:+ response: Raw response string++ Returns:+ GuardrailResult with validation status+ """+ import json++ violations = []+ warnings = []++ try:+ # Try to parse JSON+ data = json.loads(response)++ # Check required fields+ required_fields = ["action"]+ for field in required_fields:+ if field not in data:+ violations.append(f"Missing required field: {field}")++ # Validate action+ if "action" in data:+ action = data["action"].lower()+ valid_actions = ["buy", "sell", "hold", "short"]+ if action not in valid_actions:+ violations.append(f"Invalid action: {action}")++ # Validate quantity if present+ if "quantity" in data:+ try:+ qty = float(data["quantity"])+ if qty < 0:+ violations.append("Quantity cannot be negative")+ except (ValueError, TypeError):+ violations.append("Invalid quantity format")++ # Validate confidence if present+ if "confidence" in data:+ try:+ conf = float(data["confidence"])+ if not 0 <= conf <= 1:+ warnings.append("Confidence should be between 0 and 1")+ except (ValueError, TypeError):+ warnings.append("Invalid confidence format")++ return GuardrailResult(+ passed=len(violations) == 0,+ violations=violations,+ warnings=warnings,+ modified_value=data if len(violations) == 0 else None,+ )++ except json.JSONDecodeError as e:+ return GuardrailResult(+ passed=False,+ violations=[f"Invalid JSON: {str(e)}"],+ )+++class InputGuardrails:+ """+ Guardrails for user input validation.++ Validates:+ - PII detection+ - Injection prevention+ - Content moderation+ """++ PII_PATTERNS = [+ r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', # Email+ r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b', # Phone+ r'\b\d{3}[-]?\d{2}[-]?\d{4}\b', # SSN+ r'\b(?:\d{4}[-\s]?){3}\d{4}\b', # Credit card+ ]++ def __init__(+ self,+ check_pii: bool = True,+ check_injection: bool = True,+ max_input_length: int = 10000,+ ):+ self.check_pii = check_pii+ self.check_injection = check_injection+ self.max_input_length = max_input_length++ def check_input(self, text: str, context: Optional[Dict] = None) -> GuardrailResult:+ """+ Check user input against guardrails.++ Args:+ text: Input text to check+ context: Optional context dictionary++ Returns:+ GuardrailResult with check status+ """+ violations = []+ warnings = []+ sanitized = text++ # Length check+ if len(text) > self.max_input_length:+ violations.append(f"Input exceeds max length ({self.max_input_length})")+ sanitized = text[:self.max_input_length]++ # PII check+ if self.check_pii:+ for pattern in self.PII_PATTERNS:+ if re.search(pattern, text, re.IGNORECASE):+ warnings.append("Potential PII detected - consider removing")+ # Redact PII+ sanitized = re.sub(pattern, "[REDACTED]", sanitized, flags=re.IGNORECASE)++ # Injection check+ if self.check_injection:+ injection_patterns = [+ r'<script[^>]*>',+ r'javascript:',+ r'on\w+\s*=',+ r'\{\{.*\}\}', # Template injection+ r'\$\{.*\}', # Variable injection+ ]+ for pattern in injection_patterns:+ if re.search(pattern, text, re.IGNORECASE):+ warnings.append("Potential injection pattern detected")+ sanitized = re.sub(pattern, '', sanitized, flags=re.IGNORECASE)++ return GuardrailResult(+ passed=len(violations) == 0,+ violations=violations,+ warnings=warnings,+ modified_value=sanitized if sanitized != text else None,+ )+++class OutputGuardrails:+ """+ Guardrails for agent output validation.++ Validates:+ - Financial advice disclaimers+ - Confidence calibration+ - Source attribution+ """++ def __init__(+ self,+ require_disclaimer: bool = True,+ max_output_length: int = 50000,+ ):+ self.require_disclaimer = require_disclaimer+ self.max_output_length = max_output_length++ def check_output(self, output: Dict[str, Any]) -> GuardrailResult:+ """+ Check agent output against guardrails.++ Args:+ output: Output dictionary to check++ Returns:+ GuardrailResult with check status+ """+ violations = []+ warnings = []++ # Check for financial advice disclaimer+ if self.require_disclaimer:+ reasoning = output.get("reasoning", "")+ if any(phrase in reasoning.lower() for phrase in [+ "financial advice",+ "investment advice",+ "should buy",+ "should sell",+ "guaranteed",+ ]):+ warnings.append("Output may contain financial advice - consider adding disclaimer")++ # Check output length+ output_str = str(output)+ if len(output_str) > self.max_output_length:+ violations.append(f"Output exceeds max length ({self.max_output_length})")++ return GuardrailResult(+ passed=len(violations) == 0,+ violations=violations,+ warnings=warnings,+ )+++# Factory function for default guardrails+def create_trading_guardrails(mode: str = "baseline") -> TradingGuardrails:+ """Create trading guardrails based on competition mode."""++ if mode == "monk":+ return TradingGuardrails(+ max_position_pct=0.3,+ max_single_trade_pct=0.1,+ min_confidence=0.75,+ )+ elif mode == "max_leverage":+ return TradingGuardrails(+ max_position_pct=0.95,+ max_single_trade_pct=0.5,+ min_confidence=0.2,+ )+ else: # baseline, situational+ return TradingGuardrails(+ max_position_pct=0.5,+ max_single_trade_pct=0.25,+ min_confidence=0.3,+ )diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/market_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/market_data.pynew file mode 100644index 000000000..290c21e97--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/market_data.py@@ -0,0 +1,261 @@+"""+Market Data Provider++Async market data fetching using httpx.+"""++import asyncio+from datetime import datetime+from typing import Dict, List, Optional, Any++try:+ import httpx+ HTTPX_AVAILABLE = True+except ImportError:+ HTTPX_AVAILABLE = False++from alpha_arena.types.models import MarketData+from alpha_arena.utils.logging import get_logger++logger = get_logger("market_data")+++class MarketDataProvider:+ """+ Async market data provider using httpx.++ Supports multiple exchanges via a unified interface.+ """++ def __init__(+ self,+ exchange_id: str = "kraken",+ timeout: float = 10.0,+ ):+ self.exchange_id = exchange_id+ self.timeout = timeout+ self._client: Optional[Any] = None+ self._cache: Dict[str, MarketData] = {}+ self._cache_ttl = 5 # seconds++ async def __aenter__(self):+ await self.initialize()+ return self++ async def __aexit__(self, exc_type, exc_val, exc_tb):+ await self.close()++ async def initialize(self):+ """Initialize the HTTP client."""+ if HTTPX_AVAILABLE:+ self._client = httpx.AsyncClient(timeout=self.timeout)+ logger.info(f"Market data provider initialized for {self.exchange_id}")++ async def close(self):+ """Close the HTTP client."""+ if self._client:+ await self._client.aclose()+ self._client = None++ async def get_ticker(self, symbol: str) -> MarketData:+ """+ Get current ticker data for a symbol.++ Args:+ symbol: Trading pair (e.g., "BTC/USD")++ Returns:+ MarketData with current prices+ """+ # Check cache first+ if symbol in self._cache:+ cached = self._cache[symbol]+ age = (datetime.now() - cached.timestamp).total_seconds()+ if age < self._cache_ttl:+ return cached++ # Fetch from exchange+ if self.exchange_id == "kraken":+ data = await self._fetch_kraken(symbol)+ elif self.exchange_id == "binance":+ data = await self._fetch_binance(symbol)+ else:+ data = await self._fetch_generic(symbol)++ self._cache[symbol] = data+ return data++ async def get_tickers(self, symbols: List[str]) -> Dict[str, MarketData]:+ """Get ticker data for multiple symbols."""+ results = {}+ for symbol in symbols:+ try:+ results[symbol] = await self.get_ticker(symbol)+ except Exception as e:+ logger.error(f"Failed to fetch {symbol}: {e}")+ return results++ async def _fetch_kraken(self, symbol: str) -> MarketData:+ """Fetch data from Kraken."""+ # Convert symbol format+ pair = symbol.replace("/", "")+ if pair.endswith("USD"):+ pair = pair.replace("USD", "ZUSD")+ if pair.startswith("BTC"):+ pair = pair.replace("BTC", "XBT")++ url = f"https://api.kraken.com/0/public/Ticker?pair={pair}"++ if not HTTPX_AVAILABLE or not self._client:+ return self._mock_market_data(symbol)++ try:+ response = await self._client.get(url)+ data = response.json()++ if data.get("error") and len(data["error"]) > 0:+ logger.warning(f"Kraken API error: {data['error']}")+ return self._mock_market_data(symbol)++ result = data.get("result", {})+ if not result:+ return self._mock_market_data(symbol)++ # Get first result (there should only be one)+ ticker_data = list(result.values())[0]++ return MarketData(+ symbol=symbol,+ price=float(ticker_data["c"][0]), # Last trade close price+ bid=float(ticker_data["b"][0]), # Best bid+ ask=float(ticker_data["a"][0]), # Best ask+ high_24h=float(ticker_data["h"][1]), # 24h high+ low_24h=float(ticker_data["l"][1]), # 24h low+ volume_24h=float(ticker_data["v"][1]), # 24h volume+ timestamp=datetime.now(),+ )++ except Exception as e:+ logger.error(f"Kraken fetch error for {symbol}: {e}")+ return self._mock_market_data(symbol)++ async def _fetch_binance(self, symbol: str) -> MarketData:+ """Fetch data from Binance."""+ pair = symbol.replace("/", "")+ url = f"https://api.binance.com/api/v3/ticker/24hr?symbol={pair}"++ if not HTTPX_AVAILABLE or not self._client:+ return self._mock_market_data(symbol)++ try:+ response = await self._client.get(url)+ data = response.json()++ return MarketData(+ symbol=symbol,+ price=float(data["lastPrice"]),+ bid=float(data["bidPrice"]),+ ask=float(data["askPrice"]),+ high_24h=float(data["highPrice"]),+ low_24h=float(data["lowPrice"]),+ volume_24h=float(data["volume"]),+ timestamp=datetime.now(),+ )++ except Exception as e:+ logger.error(f"Binance fetch error for {symbol}: {e}")+ return self._mock_market_data(symbol)++ async def _fetch_generic(self, symbol: str) -> MarketData:+ """Fallback fetch using mock data."""+ logger.warning(f"Using mock data for {symbol}")+ return self._mock_market_data(symbol)++ def _mock_market_data(self, symbol: str) -> MarketData:+ """Generate mock market data for testing."""+ import random++ base_prices = {+ "BTC/USD": 95000.0,+ "ETH/USD": 3500.0,+ "SOL/USD": 180.0,+ "XRP/USD": 2.5,+ }++ base_price = base_prices.get(symbol, 100.0)+ variation = base_price * 0.001 # 0.1% variation++ price = base_price + random.uniform(-variation, variation)+ spread = price * 0.0005 # 0.05% spread++ return MarketData(+ symbol=symbol,+ price=price,+ bid=price - spread,+ ask=price + spread,+ high_24h=price * 1.02,+ low_24h=price * 0.98,+ volume_24h=random.uniform(1000, 10000),+ timestamp=datetime.now(),+ )+++class CachedMarketDataProvider(MarketDataProvider):+ """Market data provider with enhanced caching."""++ def __init__(+ self,+ exchange_id: str = "kraken",+ timeout: float = 10.0,+ cache_ttl: int = 10,+ ):+ super().__init__(exchange_id, timeout)+ self._cache_ttl = cache_ttl+ self._price_history: Dict[str, List[float]] = {}+ self._max_history = 100++ def get_price_history(self, symbol: str) -> List[float]:+ """Get price history for a symbol."""+ return self._price_history.get(symbol, [])++ async def get_ticker(self, symbol: str) -> MarketData:+ """Get ticker and record price history."""+ data = await super().get_ticker(symbol)++ # Record price history+ if symbol not in self._price_history:+ self._price_history[symbol] = []++ self._price_history[symbol].append(data.price)++ # Trim history+ if len(self._price_history[symbol]) > self._max_history:+ self._price_history[symbol] = self._price_history[symbol][-self._max_history:]++ return data++ def get_price_change(self, symbol: str, periods: int = 5) -> float:+ """Calculate price change over N periods."""+ history = self._price_history.get(symbol, [])+ if len(history) < 2:+ return 0.0++ periods = min(periods, len(history) - 1)+ return (history[-1] - history[-periods - 1]) / history[-periods - 1] * 100+++# Singleton instance+_provider: Optional[MarketDataProvider] = None+++async def get_market_data_provider(exchange_id: str = "kraken") -> MarketDataProvider:+ """Get or create the market data provider."""+ global _provider++ if _provider is None or _provider.exchange_id != exchange_id:+ if _provider:+ await _provider.close()+ _provider = CachedMarketDataProvider(exchange_id)+ await _provider.initialize()++ return _providerdiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/paper_trading.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/paper_trading.pynew file mode 100644index 000000000..bbd125217--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/paper_trading.py@@ -0,0 +1,455 @@+"""+Paper Trading Engine++Simulates trade execution for competition models.+"""++from datetime import datetime+from typing import Dict, Optional, List+from decimal import Decimal, ROUND_DOWN++from alpha_arena.types.models import (+ MarketData,+ ModelDecision,+ PortfolioState,+ PositionInfo,+ TradeAction,+ TradeResult,+)+from alpha_arena.utils.logging import get_logger++logger = get_logger("paper_trading")+++class PaperTradingEngine:+ """+ Paper trading engine for simulating trade execution.++ Handles:+ - Long and short positions+ - Position sizing and margin+ - P&L calculation+ - Portfolio state management+ """++ def __init__(+ self,+ model_name: str,+ initial_capital: float = 10000.0,+ maker_fee: float = 0.001,+ taker_fee: float = 0.002,+ margin_requirement: float = 0.3,+ max_position_pct: float = 0.9,+ ):+ self.model_name = model_name+ self.initial_capital = initial_capital+ self.maker_fee = maker_fee+ self.taker_fee = taker_fee+ self.margin_requirement = margin_requirement+ self.max_position_pct = max_position_pct++ # Portfolio state+ self.cash = initial_capital+ self.positions: Dict[str, PositionInfo] = {}+ self.realized_pnl = 0.0+ self.trades_count = 0+ self.trade_history: List[TradeResult] = []++ def get_portfolio_state(self, current_prices: Dict[str, float] = None) -> PortfolioState:+ """+ Get current portfolio state.++ Args:+ current_prices: Current prices for position valuation++ Returns:+ PortfolioState with current values+ """+ current_prices = current_prices or {}++ # Calculate unrealized P&L+ unrealized_pnl = 0.0+ positions_value = 0.0++ for symbol, position in self.positions.items():+ current_price = current_prices.get(symbol, position.entry_price)++ if position.side == "long":+ position_value = position.quantity * current_price+ position_pnl = (current_price - position.entry_price) * position.quantity+ else: # short+ position_value = position.margin_reserved or 0+ position_pnl = (position.entry_price - current_price) * position.quantity++ positions_value += position_value+ unrealized_pnl += position_pnl++ # Update position's unrealized P&L+ position.unrealized_pnl = position_pnl++ portfolio_value = self.cash + positions_value + unrealized_pnl++ return PortfolioState(+ model_name=self.model_name,+ cash=self.cash,+ portfolio_value=portfolio_value,+ positions=self.positions.copy(),+ total_pnl=self.realized_pnl + unrealized_pnl,+ unrealized_pnl=unrealized_pnl,+ trades_count=self.trades_count,+ )++ def execute_decision(+ self,+ decision: ModelDecision,+ market_data: MarketData,+ ) -> TradeResult:+ """+ Execute a trading decision.++ Args:+ decision: The trading decision to execute+ market_data: Current market data++ Returns:+ TradeResult with execution details+ """+ symbol = decision.symbol+ action = decision.action+ requested_quantity = decision.quantity++ # Validate action+ if isinstance(action, str):+ try:+ action = TradeAction(action.lower())+ except ValueError:+ return TradeResult(+ status="rejected",+ action=TradeAction.HOLD,+ symbol=symbol,+ quantity=0,+ price=market_data.price,+ reason=f"Invalid action: {action}",+ )++ # Handle HOLD+ if action == TradeAction.HOLD:+ return TradeResult(+ status="executed",+ action=TradeAction.HOLD,+ symbol=symbol,+ quantity=0,+ price=market_data.price,+ reason="Hold - no trade",+ )++ # Determine execution price (use ask for buys, bid for sells)+ if action == TradeAction.BUY:+ execution_price = market_data.ask+ else:+ execution_price = market_data.bid++ # Execute based on action+ if action == TradeAction.BUY:+ return self._execute_buy(symbol, requested_quantity, execution_price)+ elif action == TradeAction.SELL:+ return self._execute_sell(symbol, requested_quantity, execution_price)+ elif action == TradeAction.SHORT:+ return self._execute_short(symbol, requested_quantity, execution_price)+ else:+ return TradeResult(+ status="rejected",+ action=action,+ symbol=symbol,+ quantity=0,+ price=execution_price,+ reason=f"Unknown action: {action}",+ )++ def _execute_buy(+ self,+ symbol: str,+ quantity: float,+ price: float,+ ) -> TradeResult:+ """Execute a buy order."""+ # Check for existing short position+ if symbol in self.positions and self.positions[symbol].side == "short":+ return self._close_short(symbol, quantity, price)++ # Calculate cost+ cost = quantity * price+ fee = cost * self.taker_fee+ total_cost = cost + fee++ # Check if we have enough cash+ if total_cost > self.cash:+ # Adjust quantity to fit available cash+ max_cost = self.cash * self.max_position_pct+ quantity = (max_cost / (1 + self.taker_fee)) / price+ quantity = float(Decimal(str(quantity)).quantize(Decimal('0.00001'), rounding=ROUND_DOWN))++ if quantity <= 0:+ return TradeResult(+ status="rejected",+ action=TradeAction.BUY,+ symbol=symbol,+ quantity=0,+ price=price,+ reason="Insufficient funds",+ )++ cost = quantity * price+ fee = cost * self.taker_fee+ total_cost = cost + fee++ # Execute trade+ self.cash -= total_cost++ if symbol in self.positions:+ # Add to existing position (average in)+ existing = self.positions[symbol]+ total_quantity = existing.quantity + quantity+ avg_price = (+ (existing.entry_price * existing.quantity) + (price * quantity)+ ) / total_quantity++ self.positions[symbol] = PositionInfo(+ symbol=symbol,+ quantity=total_quantity,+ entry_price=avg_price,+ side="long",+ )+ else:+ # New position+ self.positions[symbol] = PositionInfo(+ symbol=symbol,+ quantity=quantity,+ entry_price=price,+ side="long",+ )++ self.trades_count += 1++ result = TradeResult(+ status="executed",+ action=TradeAction.BUY,+ symbol=symbol,+ quantity=quantity,+ price=price,+ cost=total_cost,+ )+ self.trade_history.append(result)++ logger.info(f"{self.model_name}: BUY {quantity} {symbol} @ ${price:.2f} (cost: ${total_cost:.2f})")+ return result++ def _execute_sell(+ self,+ symbol: str,+ quantity: float,+ price: float,+ ) -> TradeResult:+ """Execute a sell order."""+ if symbol not in self.positions:+ # No position to sell - could open short+ return TradeResult(+ status="rejected",+ action=TradeAction.SELL,+ symbol=symbol,+ quantity=0,+ price=price,+ reason="No position to sell",+ )++ position = self.positions[symbol]++ if position.side == "short":+ # Close short position+ return self._close_short(symbol, quantity, price)++ # Sell long position+ sell_quantity = min(quantity, position.quantity)+ proceeds = sell_quantity * price+ fee = proceeds * self.taker_fee+ net_proceeds = proceeds - fee++ # Calculate P&L+ pnl = (price - position.entry_price) * sell_quantity - fee++ self.cash += net_proceeds+ self.realized_pnl += pnl++ if sell_quantity >= position.quantity:+ # Full close+ del self.positions[symbol]+ else:+ # Partial close+ self.positions[symbol] = PositionInfo(+ symbol=symbol,+ quantity=position.quantity - sell_quantity,+ entry_price=position.entry_price,+ side="long",+ )++ self.trades_count += 1++ result = TradeResult(+ status="executed",+ action=TradeAction.SELL,+ symbol=symbol,+ quantity=sell_quantity,+ price=price,+ proceeds=net_proceeds,+ pnl=pnl,+ )+ self.trade_history.append(result)++ logger.info(+ f"{self.model_name}: SELL {sell_quantity} {symbol} @ ${price:.2f} "+ f"(proceeds: ${net_proceeds:.2f}, P&L: ${pnl:+.2f})"+ )+ return result++ def _execute_short(+ self,+ symbol: str,+ quantity: float,+ price: float,+ ) -> TradeResult:+ """Execute a short sell order."""+ if symbol in self.positions:+ position = self.positions[symbol]+ if position.side == "long":+ # Close long first+ close_result = self._execute_sell(symbol, position.quantity, price)+ if close_result.status != "executed":+ return close_result++ # Calculate margin required+ position_value = quantity * price+ margin_required = position_value * self.margin_requirement+ fee = position_value * self.taker_fee++ if margin_required + fee > self.cash:+ # Adjust quantity+ available_margin = self.cash * self.max_position_pct+ quantity = (available_margin / self.margin_requirement) / price+ quantity = float(Decimal(str(quantity)).quantize(Decimal('0.00001'), rounding=ROUND_DOWN))++ if quantity <= 0:+ return TradeResult(+ status="rejected",+ action=TradeAction.SHORT,+ symbol=symbol,+ quantity=0,+ price=price,+ reason="Insufficient margin",+ )++ position_value = quantity * price+ margin_required = position_value * self.margin_requirement+ fee = position_value * self.taker_fee++ # Execute short+ self.cash -= (margin_required + fee)++ self.positions[symbol] = PositionInfo(+ symbol=symbol,+ quantity=quantity,+ entry_price=price,+ side="short",+ margin_reserved=margin_required,+ )++ self.trades_count += 1++ result = TradeResult(+ status="executed",+ action=TradeAction.SHORT,+ symbol=symbol,+ quantity=quantity,+ price=price,+ margin_reserved=margin_required,+ )+ self.trade_history.append(result)++ logger.info(f"{self.model_name}: SHORT {quantity} {symbol} @ ${price:.2f} (margin: ${margin_required:.2f})")+ return result++ def _close_short(+ self,+ symbol: str,+ quantity: float,+ price: float,+ ) -> TradeResult:+ """Close a short position."""+ if symbol not in self.positions or self.positions[symbol].side != "short":+ return TradeResult(+ status="rejected",+ action=TradeAction.BUY,+ symbol=symbol,+ quantity=0,+ price=price,+ reason="No short position to close",+ )++ position = self.positions[symbol]+ close_quantity = min(quantity, position.quantity)++ # Calculate P&L (profit if price fell)+ pnl = (position.entry_price - price) * close_quantity++ # Return margin+ margin_return = (position.margin_reserved or 0) * (close_quantity / position.quantity)++ # Deduct cover cost+ cover_cost = close_quantity * price+ fee = cover_cost * self.taker_fee++ self.cash += margin_return + pnl - fee+ self.realized_pnl += pnl++ if close_quantity >= position.quantity:+ del self.positions[symbol]+ else:+ remaining_margin = (position.margin_reserved or 0) - margin_return+ self.positions[symbol] = PositionInfo(+ symbol=symbol,+ quantity=position.quantity - close_quantity,+ entry_price=position.entry_price,+ side="short",+ margin_reserved=remaining_margin,+ )++ self.trades_count += 1++ result = TradeResult(+ status="executed",+ action=TradeAction.BUY,+ symbol=symbol,+ quantity=close_quantity,+ price=price,+ pnl=pnl,+ reason="Closed short position",+ )+ self.trade_history.append(result)++ logger.info(+ f"{self.model_name}: CLOSE SHORT {close_quantity} {symbol} @ ${price:.2f} "+ f"(P&L: ${pnl:+.2f})"+ )+ return result++ def reset(self):+ """Reset the trading engine to initial state."""+ self.cash = self.initial_capital+ self.positions = {}+ self.realized_pnl = 0.0+ self.trades_count = 0+ self.trade_history = []+ logger.info(f"{self.model_name}: Trading engine reset")++ def get_trade_history(self, limit: int = 50) -> List[TradeResult]:+ """Get recent trade history."""+ return self.trade_history[-limit:]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/main.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/main.pynew file mode 100644index 000000000..b8eb5563d--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/main.py@@ -0,0 +1,608 @@+"""+Alpha Arena Main Entry Point++Single JSON payload interface for Rust/Tauri integration.+"""++import asyncio+import json+import sys+from pathlib import Path+from typing import Any, Dict, List, Optional++# Add parent directory to path for imports+parent_dir = str(Path(__file__).parent.parent)+if parent_dir not in sys.path:+ sys.path.insert(0, parent_dir)++# Wrap all imports in try-except to provide meaningful error messages+try:+ from alpha_arena.types.models import (+ CompetitionConfig,+ CompetitionModel,+ CompetitionMode,+ CompetitionStatus,+ )+ from alpha_arena.core.competition import (+ AlphaArenaCompetition,+ create_competition,+ get_competition,+ list_competitions,+ delete_competition,+ )+ from alpha_arena.core.database import get_database+ from alpha_arena.config.agent_cards import list_agent_cards, get_agent_card+ from alpha_arena.utils.logging import setup_logging, get_logger+ from alpha_arena.utils.uuid import generate_competition_id++ IMPORT_ERROR = None+except ImportError as e:+ IMPORT_ERROR = str(e)+ # Create minimal stubs so the script can still run and report error+ def setup_logging(**kwargs): pass+ class DummyLogger:+ def info(self, *a, **k): pass+ def error(self, *a, **k): pass+ def warning(self, *a, **k): pass+ def exception(self, *a, **k): pass+ def get_logger(name): return DummyLogger()++# Setup logging+setup_logging(level="INFO")+logger = get_logger("main")+++async def handle_action(action: str, params: Dict, api_keys: Dict) -> Dict[str, Any]:+ """+ Handle an action request.++ Args:+ action: Action to perform+ params: Action parameters+ api_keys: API keys for providers++ Returns:+ Result dictionary+ """+ # Check for import errors first+ if IMPORT_ERROR:+ return {+ "success": False,+ "error": f"Import error: {IMPORT_ERROR}. Please ensure all dependencies are installed (pydantic, httpx, agno).",+ "details": {"missing_dependency": IMPORT_ERROR}+ }++ try:+ if action == "create_competition":+ return await create_competition_handler(params, api_keys)++ elif action == "start_competition":+ return await start_competition_handler(params, api_keys)++ elif action == "run_cycle":+ return await run_cycle_handler(params, api_keys)++ elif action == "stop_competition":+ return await stop_competition_handler(params)++ elif action == "get_leaderboard":+ return await get_leaderboard_handler(params)++ elif action == "get_decisions":+ return await get_decisions_handler(params)++ elif action == "get_snapshots":+ return await get_snapshots_handler(params)++ elif action == "list_competitions":+ return await list_competitions_handler(params)++ elif action == "get_competition":+ return await get_competition_handler(params)++ elif action == "delete_competition":+ return await delete_competition_handler(params)++ elif action == "list_agents":+ return await list_agents_handler(params)++ elif action == "get_agent":+ return await get_agent_handler(params)++ elif action == "system_info":+ return get_system_info()++ else:+ return {"success": False, "error": f"Unknown action: {action}"}++ except Exception as e:+ logger.exception(f"Error handling action {action}: {e}")+ return {"success": False, "error": str(e)}+++async def create_competition_handler(params: Dict, api_keys: Dict) -> Dict[str, Any]:+ """Create a new competition."""+ try:+ logger.info(f"Creating competition with params: {list(params.keys())}")+ logger.info(f"API keys provided for: {list(api_keys.keys())}")++ # Generate competition ID if not provided+ competition_id = params.get("competition_id") or generate_competition_id()++ # Build models from params+ models_data = params.get("models", [])+ if not models_data:+ return {"success": False, "error": "No models provided in configuration"}++ models = []++ for model_data in models_data:+ # Get agent card for additional info+ card = get_agent_card(model_data.get("name", ""))++ model = CompetitionModel(+ name=model_data.get("name"),+ provider=model_data.get("provider") or (card.provider if card else "openai"),+ model_id=model_data.get("model_id") or (card.model_id if card else "gpt-4o-mini"),+ api_key=model_data.get("api_key"),+ initial_capital=model_data.get("initial_capital", params.get("initial_capital", 10000)),+ )+ models.append(model)+ logger.info(f"Configured model: {model.name} ({model.provider}/{model.model_id})")++ # Create config+ config = CompetitionConfig(+ competition_id=competition_id,+ competition_name=params.get("competition_name", f"Competition {competition_id[:8]}"),+ models=models,+ symbols=params.get("symbols", ["BTC/USD"]),+ initial_capital=params.get("initial_capital", 10000),+ mode=CompetitionMode(params.get("mode", "baseline")),+ cycle_interval_seconds=params.get("cycle_interval_seconds", 150),+ exchange_id=params.get("exchange_id", "kraken"),+ max_cycles=params.get("max_cycles"),+ )++ logger.info(f"Competition config created: {competition_id}")++ # Create competition+ competition = create_competition(config)++ # Initialize with API keys - use asyncio.wait_for for overall timeout+ try:+ init_success = await asyncio.wait_for(+ competition.initialize(api_keys),+ timeout=60.0 # 60 second overall timeout+ )+ except asyncio.TimeoutError:+ logger.error("Competition initialization timed out after 60 seconds")+ return {+ "success": False,+ "error": "Competition initialization timed out. This may be due to network issues or unavailable LLM providers.",+ }++ if init_success:+ # Save to database+ try:+ db = get_database()+ db.save_competition(config, CompetitionStatus.CREATED)+ except Exception as db_error:+ logger.warning(f"Failed to save competition to database: {db_error}")+ # Continue anyway - competition is functional++ return {+ "success": True,+ "competition_id": competition_id,+ "config": config.model_dump(),+ "status": "created",+ "models_count": len(models),+ }+ else:+ return {+ "success": False,+ "error": "Failed to initialize competition. Check that LLM providers are configured correctly and API keys are valid.",+ }++ except Exception as e:+ logger.exception(f"Error creating competition: {e}")+ return {+ "success": False,+ "error": str(e),+ "error_type": type(e).__name__,+ }+++async def start_competition_handler(params: Dict, api_keys: Dict) -> Dict[str, Any]:+ """Start a competition."""+ competition_id = params.get("competition_id")+ if not competition_id:+ return {"success": False, "error": "Missing competition_id"}++ competition = get_competition(competition_id)++ # If not in memory, try to restore from database+ if not competition:+ logger.info(f"Competition {competition_id} not in memory for start, trying to restore...")+ db = get_database()+ comp_data = db.get_competition(competition_id)++ if comp_data:+ try:+ config = CompetitionConfig(**comp_data["config"])+ competition = create_competition(config)+ except Exception as e:+ logger.exception(f"Failed to restore competition: {e}")+ return {"success": False, "error": f"Failed to restore competition: {str(e)}"}+ else:+ return {"success": False, "error": f"Competition not found: {competition_id}"}++ if await competition.start(api_keys):+ db = get_database()+ db.update_competition_status(+ competition_id,+ CompetitionStatus.RUNNING,+ start_time=competition.start_time,+ )++ return {+ "success": True,+ "competition_id": competition_id,+ "status": "running",+ }+ else:+ return {"success": False, "error": "Failed to start competition"}+++async def run_cycle_handler(params: Dict, api_keys: Dict) -> Dict[str, Any]:+ """Run a single competition cycle."""+ competition_id = params.get("competition_id")+ if not competition_id:+ return {"success": False, "error": "Missing competition_id"}++ # Try to get competition from memory first+ competition = get_competition(competition_id)++ # If not in memory, try to restore from database+ if not competition:+ logger.info(f"Competition {competition_id} not in memory, trying to restore from database...")+ db = get_database()+ comp_data = db.get_competition(competition_id)++ if comp_data:+ logger.info(f"Found competition in database, restoring...")+ try:+ # Reconstruct the competition from database+ config = CompetitionConfig(**comp_data["config"])+ competition = create_competition(config)++ # Initialize the competition with API keys+ init_success = await asyncio.wait_for(+ competition.initialize(api_keys),+ timeout=60.0+ )++ if not init_success:+ return {"success": False, "error": "Failed to reinitialize competition from database"}++ # Restore cycle count+ competition.cycle_count = comp_data.get("cycle_count", 0)+ logger.info(f"Competition restored with cycle_count={competition.cycle_count}")+ except Exception as e:+ logger.exception(f"Failed to restore competition: {e}")+ return {"success": False, "error": f"Failed to restore competition: {str(e)}"}+ else:+ return {"success": False, "error": f"Competition not found: {competition_id}"}++ # Collect streaming results+ events = []+ async for response in competition.run_cycle():+ event_data = {+ "event": response.event.value if hasattr(response.event, 'value') else str(response.event),+ "content": response.content,+ "metadata": response.metadata,+ }+ events.append(event_data)++ # Update database+ db = get_database()+ db.update_competition_status(+ competition_id,+ competition.status,+ cycle_count=competition.cycle_count,+ )++ # Save decisions+ for decision in competition.get_decisions(limit=len(competition.config.models)):+ db.save_decision(decision)++ # Save snapshots+ for snapshot in competition.get_snapshots()[-len(competition.config.models):]:+ db.save_snapshot(snapshot)++ # Save leaderboard+ leaderboard = competition.get_leaderboard()+ db.save_leaderboard(competition_id, competition.cycle_count, leaderboard)++ return {+ "success": True,+ "competition_id": competition_id,+ "cycle_number": competition.cycle_count,+ "events": events,+ "leaderboard": [e.model_dump() for e in leaderboard],+ }+++async def stop_competition_handler(params: Dict) -> Dict[str, Any]:+ """Stop a competition."""+ competition_id = params.get("competition_id")+ if not competition_id:+ return {"success": False, "error": "Missing competition_id"}++ competition = get_competition(competition_id)++ # If not in memory, we can still update the database status+ if not competition:+ logger.info(f"Competition {competition_id} not in memory, updating database status...")+ db = get_database()+ comp_data = db.get_competition(competition_id)+ if not comp_data:+ return {"success": False, "error": f"Competition not found: {competition_id}"}+ # Just update status in database+ db.update_competition_status(competition_id, CompetitionStatus.PAUSED)+ return {+ "success": True,+ "competition_id": competition_id,+ "status": "paused",+ }++ await competition.stop()++ db = get_database()+ db.update_competition_status(competition_id, CompetitionStatus.PAUSED)++ return {+ "success": True,+ "competition_id": competition_id,+ "status": "paused",+ }+++async def get_leaderboard_handler(params: Dict) -> Dict[str, Any]:+ """Get current leaderboard."""+ competition_id = params.get("competition_id")+ if not competition_id:+ return {"success": False, "error": "Missing competition_id"}++ competition = get_competition(competition_id)+ if competition:+ leaderboard = competition.get_leaderboard()+ return {+ "success": True,+ "leaderboard": [e.model_dump() for e in leaderboard],+ "cycle_number": competition.cycle_count,+ }++ # Try database+ db = get_database()+ leaderboard = db.get_latest_leaderboard(competition_id)+ if leaderboard:+ return {+ "success": True,+ "leaderboard": leaderboard,+ }++ return {"success": False, "error": f"Competition not found: {competition_id}"}+++async def get_decisions_handler(params: Dict) -> Dict[str, Any]:+ """Get decisions for a competition."""+ competition_id = params.get("competition_id")+ model_name = params.get("model_name")+ limit = params.get("limit", 50)++ if not competition_id:+ return {"success": False, "error": "Missing competition_id"}++ # Try live competition first+ competition = get_competition(competition_id)+ if competition:+ decisions = competition.get_decisions(model_name=model_name, limit=limit)+ return {+ "success": True,+ "decisions": [d.model_dump() for d in decisions],+ }++ # Fall back to database+ db = get_database()+ decisions = db.get_decisions(competition_id, model_name, limit)+ return {+ "success": True,+ "decisions": decisions,+ }+++async def get_snapshots_handler(params: Dict) -> Dict[str, Any]:+ """Get performance snapshots for charting."""+ competition_id = params.get("competition_id")+ model_name = params.get("model_name")++ if not competition_id:+ return {"success": False, "error": "Missing competition_id"}++ # Try live competition first+ competition = get_competition(competition_id)+ if competition:+ snapshots = competition.get_snapshots(model_name=model_name)+ return {+ "success": True,+ "snapshots": [s.model_dump() for s in snapshots],+ }++ # Fall back to database+ db = get_database()+ snapshots = db.get_snapshots(competition_id, model_name)+ return {+ "success": True,+ "snapshots": snapshots,+ }+++async def list_competitions_handler(params: Dict) -> Dict[str, Any]:+ """List all competitions."""+ limit = params.get("limit", 50)++ # Get from database+ db = get_database()+ competitions = db.list_competitions(limit)++ return {+ "success": True,+ "competitions": competitions,+ "count": len(competitions),+ }+++async def get_competition_handler(params: Dict) -> Dict[str, Any]:+ """Get a specific competition by ID."""+ competition_id = params.get("competition_id")+ if not competition_id:+ return {"success": False, "error": "Missing competition_id"}++ db = get_database()+ comp_data = db.get_competition(competition_id)++ if comp_data:+ return {+ "success": True,+ "competition": comp_data,+ }++ return {"success": False, "error": f"Competition not found: {competition_id}"}+++async def delete_competition_handler(params: Dict) -> Dict[str, Any]:+ """Delete a competition."""+ competition_id = params.get("competition_id")+ if not competition_id:+ return {"success": False, "error": "Missing competition_id"}++ # Remove from memory+ delete_competition(competition_id)++ # Remove from database+ db = get_database()+ db.delete_competition(competition_id)++ return {+ "success": True,+ "competition_id": competition_id,+ "deleted": True,+ }+++async def list_agents_handler(params: Dict) -> Dict[str, Any]:+ """List available agents."""+ cards = list_agent_cards()++ return {+ "success": True,+ "agents": [+ {+ "name": card.name,+ "provider": card.provider,+ "model_id": card.model_id,+ "description": card.description,+ "enabled": card.enabled,+ }+ for card in cards+ ],+ "count": len(cards),+ }+++async def get_agent_handler(params: Dict) -> Dict[str, Any]:+ """Get agent details."""+ name = params.get("name")+ if not name:+ return {"success": False, "error": "Missing agent name"}++ card = get_agent_card(name)+ if card:+ return {+ "success": True,+ "agent": card.model_dump(),+ }++ return {"success": False, "error": f"Agent not found: {name}"}+++def get_system_info() -> Dict[str, Any]:+ """Get system information."""+ return {+ "success": True,+ "version": "2.0.0",+ "framework": "alpha_arena",+ "features": [+ "multi_model_competition",+ "streaming_responses",+ "paper_trading",+ "real_time_market_data",+ "performance_tracking",+ "evaluation_metrics",+ "guardrails",+ "database_persistence",+ ],+ "supported_providers": [+ "openai",+ "anthropic",+ "google",+ "deepseek",+ "groq",+ "openrouter",+ "ollama",+ ],+ "default_exchange": "kraken",+ }+++def main(args=None):+ """+ Main entry point - accepts single JSON payload from Rust/Tauri.++ Payload format:+ {+ "action": "create_competition|run_cycle|...",+ "api_keys": {"openai": "...", "anthropic": "..."},+ "params": {...}+ }+ """+ if args is None:+ args = sys.argv[1:]++ try:+ if len(args) == 0:+ return json.dumps({"success": False, "error": "No payload provided"})++ # Parse single JSON payload+ payload = json.loads(args[0])+ action = payload.get("action")+ api_keys = payload.get("api_keys", {})+ params = payload.get("params", {})++ if not action:+ return json.dumps({"success": False, "error": "Missing 'action' in payload"})++ # Run async handler+ result = asyncio.run(handle_action(action, params, api_keys))+ return json.dumps(result, default=str)++ except json.JSONDecodeError as e:+ return json.dumps({"success": False, "error": f"Invalid JSON: {str(e)}"})+ except Exception as e:+ logger.exception(f"Main error: {e}")+ return json.dumps({"success": False, "error": str(e)})+++if __name__ == "__main__":+ result = main()+ print(result)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/__init__.pynew file mode 100644index 000000000..07ecc5998--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/__init__.py@@ -0,0 +1,60 @@+"""+Alpha Arena Type System++Pydantic-based type definitions for the entire Alpha Arena system.+"""++from alpha_arena.types.models import (+ CompetitionConfig,+ CompetitionModel,+ CompetitionStatus,+ CompetitionMode,+ LeaderboardEntry,+ ModelDecision,+ TradeAction,+ TradeResult,+ PortfolioState,+ PositionInfo,+ CycleResult,+ MarketData,+ AgentConfig,+)++from alpha_arena.types.responses import (+ StreamResponse,+ StreamResponseEvent,+ NotifyResponse,+ NotifyResponseEvent,+ TaskStatusEvent,+ CommonResponseEvent,+ BaseResponse,+ ConversationItem,+ Role,+)++__all__ = [+ # Core Models+ "CompetitionConfig",+ "CompetitionModel",+ "CompetitionStatus",+ "CompetitionMode",+ "LeaderboardEntry",+ "ModelDecision",+ "TradeAction",+ "TradeResult",+ "PortfolioState",+ "PositionInfo",+ "CycleResult",+ "MarketData",+ "AgentConfig",+ # Response Types+ "StreamResponse",+ "StreamResponseEvent",+ "NotifyResponse",+ "NotifyResponseEvent",+ "TaskStatusEvent",+ "CommonResponseEvent",+ "BaseResponse",+ "ConversationItem",+ "Role",+]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/models.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/models.pynew file mode 100644index 000000000..26e60c3d5--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/models.py@@ -0,0 +1,264 @@+"""+Alpha Arena Data Models++Pydantic models for all Alpha Arena data structures with full validation.+Inspired by ValueCell's type system architecture.+"""++from datetime import datetime+from enum import Enum+from typing import Any, Dict, List, Optional, Union+from pydantic import BaseModel, Field, field_validator, model_validator+++class CompetitionMode(str, Enum):+ """Competition trading modes."""+ BASELINE = "baseline"+ MONK = "monk"+ SITUATIONAL = "situational"+ MAX_LEVERAGE = "max_leverage"+++class CompetitionStatus(str, Enum):+ """Competition lifecycle states."""+ CREATED = "created"+ RUNNING = "running"+ PAUSED = "paused"+ COMPLETED = "completed"+ FAILED = "failed"+++class TradeAction(str, Enum):+ """Possible trading actions."""+ BUY = "buy"+ SELL = "sell"+ HOLD = "hold"+ SHORT = "short"+++class ModelProvider(str, Enum):+ """Supported LLM providers."""+ OPENAI = "openai"+ ANTHROPIC = "anthropic"+ GOOGLE = "google"+ DEEPSEEK = "deepseek"+ GROQ = "groq"+ OPENROUTER = "openrouter"+ OLLAMA = "ollama"+++class AgentConfig(BaseModel):+ """Configuration for an LLM agent."""++ name: str = Field(..., description="Display name for the agent")+ provider: ModelProvider = Field(..., description="LLM provider")+ model_id: str = Field(..., description="Model identifier")+ api_key: Optional[str] = Field(None, description="API key (optional, can use env)")+ temperature: float = Field(0.7, ge=0.0, le=2.0, description="Sampling temperature")+ max_tokens: Optional[int] = Field(None, description="Max tokens for response")++ class Config:+ use_enum_values = True+++class CompetitionModel(BaseModel):+ """Model configuration within a competition."""++ name: str = Field(..., description="Display name for the model")+ provider: str = Field(..., description="LLM provider name")+ model_id: str = Field(..., description="Model identifier")+ api_key: Optional[str] = Field(None, description="API key for this model")+ initial_capital: float = Field(10000.0, gt=0, description="Starting capital")++ # Runtime state (populated during competition)+ capital: Optional[float] = Field(None, description="Current cash balance")+ total_pnl: float = Field(0.0, description="Total profit/loss")++ @model_validator(mode='after')+ def set_capital_default(self):+ if self.capital is None:+ self.capital = self.initial_capital+ return self+++class PositionInfo(BaseModel):+ """Information about an open position."""++ symbol: str = Field(..., description="Trading symbol")+ quantity: float = Field(..., description="Position size")+ entry_price: float = Field(..., description="Average entry price")+ side: str = Field("long", description="Position side: long or short")+ margin_reserved: Optional[float] = Field(None, description="Margin for short positions")+ unrealized_pnl: Optional[float] = Field(None, description="Current unrealized P&L")+++class PortfolioState(BaseModel):+ """Complete portfolio state for a model."""++ model_name: str = Field(..., description="Name of the model")+ cash: float = Field(..., description="Available cash")+ portfolio_value: float = Field(..., description="Total portfolio value")+ positions: Dict[str, PositionInfo] = Field(default_factory=dict, description="Open positions")+ total_pnl: float = Field(0.0, description="Realized P&L")+ unrealized_pnl: float = Field(0.0, description="Unrealized P&L")+ trades_count: int = Field(0, description="Total trades executed")++ @property+ def total_value(self) -> float:+ """Total value including unrealized P&L."""+ return self.portfolio_value+++class MarketData(BaseModel):+ """Market data snapshot."""++ symbol: str = Field(..., description="Trading symbol")+ price: float = Field(..., gt=0, description="Current price")+ bid: float = Field(..., gt=0, description="Best bid price")+ ask: float = Field(..., gt=0, description="Best ask price")+ high_24h: float = Field(..., description="24h high")+ low_24h: float = Field(..., description="24h low")+ volume_24h: float = Field(..., description="24h volume")+ timestamp: datetime = Field(default_factory=datetime.now, description="Data timestamp")++ @property+ def spread(self) -> float:+ """Bid-ask spread."""+ return self.ask - self.bid++ @property+ def spread_pct(self) -> float:+ """Spread as percentage."""+ return (self.spread / self.price) * 100 if self.price > 0 else 0+++class TradeResult(BaseModel):+ """Result of a trade execution."""++ status: str = Field(..., description="executed, rejected, or partial")+ action: TradeAction = Field(..., description="Trade action taken")+ symbol: str = Field(..., description="Trading symbol")+ quantity: float = Field(..., description="Quantity traded")+ price: float = Field(..., description="Execution price")+ cost: Optional[float] = Field(None, description="Total cost for buys")+ proceeds: Optional[float] = Field(None, description="Proceeds for sells")+ pnl: Optional[float] = Field(None, description="Realized P&L")+ margin_reserved: Optional[float] = Field(None, description="Margin for shorts")+ reason: Optional[str] = Field(None, description="Rejection reason if failed")+ timestamp: datetime = Field(default_factory=datetime.now, description="Execution time")++ class Config:+ use_enum_values = True+++class ModelDecision(BaseModel):+ """Trading decision from an AI model."""++ competition_id: str = Field(..., description="Competition identifier")+ model_name: str = Field(..., description="Model that made the decision")+ cycle_number: int = Field(..., ge=0, description="Competition cycle number")+ action: TradeAction = Field(..., description="Decided action")+ symbol: str = Field(..., description="Trading symbol")+ quantity: float = Field(0.0, ge=0, description="Quantity to trade")+ confidence: float = Field(0.5, ge=0.0, le=1.0, description="Decision confidence")+ reasoning: str = Field("", description="Explanation for the decision")+ trade_executed: Optional[TradeResult] = Field(None, description="Execution result")+ timestamp: datetime = Field(default_factory=datetime.now, description="Decision time")++ # Additional context+ price_at_decision: Optional[float] = Field(None, description="Price when decision was made")+ portfolio_value_before: Optional[float] = Field(None, description="Portfolio before trade")+ portfolio_value_after: Optional[float] = Field(None, description="Portfolio after trade")++ class Config:+ use_enum_values = True++ @field_validator('action', mode='before')+ @classmethod+ def normalize_action(cls, v):+ if isinstance(v, str):+ return v.lower()+ return v+++class LeaderboardEntry(BaseModel):+ """Leaderboard entry for a competing model."""++ rank: int = Field(..., ge=0, description="Current rank (0 = unranked, will be set after sorting)")+ model_name: str = Field(..., description="Model name")+ portfolio_value: float = Field(..., description="Current portfolio value")+ total_pnl: float = Field(0.0, description="Total P&L")+ return_pct: float = Field(0.0, description="Return percentage")+ trades_count: int = Field(0, ge=0, description="Total trades")+ cash: float = Field(0.0, description="Available cash")+ positions_count: int = Field(0, ge=0, description="Open positions count")+ win_rate: Optional[float] = Field(None, description="Win rate percentage")+ sharpe_ratio: Optional[float] = Field(None, description="Sharpe ratio")+++class CycleResult(BaseModel):+ """Result of a competition cycle."""++ cycle_number: int = Field(..., ge=1, description="Cycle number")+ timestamp: datetime = Field(default_factory=datetime.now, description="Cycle completion time")+ market_data: MarketData = Field(..., description="Market data for this cycle")+ decisions: Dict[str, ModelDecision] = Field(default_factory=dict, description="Model decisions")+ cycle_time_seconds: float = Field(0.0, description="Time taken for cycle")+ errors: List[str] = Field(default_factory=list, description="Any errors during cycle")+++class CompetitionConfig(BaseModel):+ """Configuration for creating a competition."""++ competition_id: str = Field(..., description="Unique competition identifier")+ competition_name: str = Field(..., description="Display name")+ models: List[CompetitionModel] = Field(..., min_length=1, description="Competing models")+ symbols: List[str] = Field(default=["BTC/USD"], description="Trading symbols")+ initial_capital: float = Field(10000.0, gt=0, description="Starting capital per model")+ mode: CompetitionMode = Field(CompetitionMode.BASELINE, description="Competition mode")+ cycle_interval_seconds: int = Field(150, ge=10, description="Seconds between cycles")+ exchange_id: str = Field("kraken", description="Exchange for market data")+ max_cycles: Optional[int] = Field(None, description="Max cycles (None = unlimited)")+ custom_prompt: Optional[str] = Field(None, description="Custom system prompt")++ class Config:+ use_enum_values = True++ @field_validator('models')+ @classmethod+ def validate_unique_models(cls, v):+ names = [m.name for m in v]+ if len(names) != len(set(names)):+ raise ValueError("Model names must be unique")+ return v+++class Competition(BaseModel):+ """Full competition state."""++ config: CompetitionConfig = Field(..., description="Competition configuration")+ status: CompetitionStatus = Field(CompetitionStatus.CREATED, description="Current status")+ cycle_count: int = Field(0, ge=0, description="Completed cycles")+ start_time: Optional[datetime] = Field(None, description="Competition start time")+ end_time: Optional[datetime] = Field(None, description="Competition end time")+ portfolios: Dict[str, PortfolioState] = Field(default_factory=dict, description="Model portfolios")+ leaderboard: List[LeaderboardEntry] = Field(default_factory=list, description="Current rankings")++ class Config:+ use_enum_values = True+++class PerformanceSnapshot(BaseModel):+ """Performance snapshot for charting."""++ id: str = Field(..., description="Unique snapshot ID")+ competition_id: str = Field(..., description="Competition ID")+ cycle_number: int = Field(..., description="Cycle number")+ model_name: str = Field(..., description="Model name")+ portfolio_value: float = Field(..., description="Portfolio value")+ cash: float = Field(..., description="Cash balance")+ pnl: float = Field(..., description="Current P&L")+ return_pct: float = Field(..., description="Return percentage")+ positions_count: int = Field(0, description="Open positions")+ trades_count: int = Field(0, description="Total trades")+ timestamp: datetime = Field(default_factory=datetime.now, description="Snapshot time")diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/responses.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/responses.pynew file mode 100644index 000000000..378b67368--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/responses.py@@ -0,0 +1,320 @@+"""+Alpha Arena Response Types++Streaming and notification response types inspired by ValueCell's architecture.+Provides event-driven communication between agents and frontend.+"""++from abc import ABC+from enum import Enum+from typing import Any, Dict, Literal, Optional, Union+from datetime import datetime+from pydantic import BaseModel, Field++from alpha_arena.utils.uuid import generate_item_id+++class Role(str, Enum):+ """Message role enumeration."""+ USER = "user"+ AGENT = "agent"+ SYSTEM = "system"+++class SystemResponseEvent(str, Enum):+ """Events related to system-level responses and status updates."""+ COMPETITION_STARTED = "competition_started"+ COMPETITION_PAUSED = "competition_paused"+ COMPETITION_COMPLETED = "competition_completed"+ CYCLE_STARTED = "cycle_started"+ CYCLE_COMPLETED = "cycle_completed"+ SYSTEM_FAILED = "system_failed"+ DONE = "done"+++class TaskStatusEvent(str, Enum):+ """Events related to task lifecycle status changes."""+ TASK_STARTED = "task_started"+ TASK_COMPLETED = "task_completed"+ TASK_FAILED = "task_failed"+ TASK_CANCELLED = "task_cancelled"+++class CommonResponseEvent(str, Enum):+ """Common response events shared across different response types."""+ COMPONENT_GENERATOR = "component_generator"+ LEADERBOARD_UPDATE = "leaderboard_update"+ PORTFOLIO_UPDATE = "portfolio_update"+++class StreamResponseEvent(str, Enum):+ """Events specific to streaming agent responses."""+ MESSAGE_CHUNK = "message_chunk"+ DECISION_STARTED = "decision_started"+ DECISION_COMPLETED = "decision_completed"+ TRADE_EXECUTED = "trade_executed"+ REASONING_STARTED = "reasoning_started"+ REASONING = "reasoning"+ REASONING_COMPLETED = "reasoning_completed"+ MARKET_DATA = "market_data"+ ERROR = "error"+++class NotifyResponseEvent(str, Enum):+ """Events specific to notification agent responses."""+ MESSAGE = "message"+ ALERT = "alert"+ TRADE_NOTIFICATION = "trade_notification"+ PERFORMANCE_UPDATE = "performance_update"+++class StreamResponse(BaseModel):+ """Response model for streaming agent responses.++ Used by agents that stream progress, decisions, reasoning, or+ component-generation updates. `event` determines how the response+ should be interpreted.+ """++ content: Optional[str] = Field(+ None,+ description="The content of the stream response",+ )+ event: Union[StreamResponseEvent, TaskStatusEvent, CommonResponseEvent, SystemResponseEvent] = Field(+ ...,+ description="The type of stream response",+ )+ metadata: Optional[Dict[str, Any]] = Field(+ None,+ description="Optional metadata providing additional context",+ )++ class Config:+ use_enum_values = True+++class NotifyResponse(BaseModel):+ """Response model for notification agent responses."""++ content: str = Field(+ ...,+ description="The content of the notification response",+ )+ event: Union[NotifyResponseEvent, TaskStatusEvent, CommonResponseEvent] = Field(+ ...,+ description="The type of notification response",+ )+ metadata: Optional[Dict[str, Any]] = Field(+ None,+ description="Optional metadata",+ )++ class Config:+ use_enum_values = True+++class ResponsePayload(BaseModel):+ """Base payload for response data."""++ content: Optional[str] = Field(None, description="The message content")+++class DecisionPayload(ResponsePayload):+ """Payload for trading decision responses."""++ model_name: str = Field(..., description="Model making the decision")+ action: str = Field(..., description="Trading action")+ symbol: str = Field(..., description="Trading symbol")+ quantity: float = Field(0.0, description="Trade quantity")+ confidence: float = Field(0.5, description="Decision confidence")+ reasoning: str = Field("", description="Decision reasoning")+++class TradePayload(ResponsePayload):+ """Payload for trade execution responses."""++ model_name: str = Field(..., description="Model that traded")+ action: str = Field(..., description="Trade action")+ symbol: str = Field(..., description="Trading symbol")+ quantity: float = Field(..., description="Quantity traded")+ price: float = Field(..., description="Execution price")+ pnl: Optional[float] = Field(None, description="Realized P&L")+ status: str = Field(..., description="Trade status")+++class LeaderboardPayload(ResponsePayload):+ """Payload for leaderboard updates."""++ leaderboard: list = Field(..., description="Current leaderboard entries")+ cycle_number: int = Field(..., description="Current cycle")+++class UnifiedResponseData(BaseModel):+ """Unified response data structure with optional hierarchy fields."""++ competition_id: str = Field(..., description="Competition identifier")+ cycle_number: Optional[int] = Field(None, description="Current cycle number")+ model_name: Optional[str] = Field(None, description="Agent/model name")+ payload: Optional[ResponsePayload] = Field(None, description="Response payload")+ metadata: Optional[Dict[str, Any]] = Field(None, description="Additional metadata")+ role: Role = Field(Role.AGENT, description="Message role")+ item_id: str = Field(default_factory=generate_item_id)+ timestamp: datetime = Field(default_factory=datetime.now)++ class Config:+ use_enum_values = True+++class BaseResponse(BaseModel, ABC):+ """Top-level response envelope used for all events."""++ event: Union[+ StreamResponseEvent,+ NotifyResponseEvent,+ SystemResponseEvent,+ CommonResponseEvent,+ TaskStatusEvent+ ] = Field(..., description="The event type")+ data: UnifiedResponseData = Field(..., description="The response data")++ class Config:+ use_enum_values = True+++class ConversationItem(BaseModel):+ """Message item structure for conversation/decision history."""++ item_id: str = Field(..., description="Unique message identifier")+ role: Role = Field(..., description="Role of the sender")+ model_name: Optional[str] = Field(None, description="Model name if applicable")+ event: str = Field(..., description="Event type")+ competition_id: str = Field(..., description="Competition ID")+ cycle_number: Optional[int] = Field(None, description="Cycle number")+ payload: str = Field(..., description="JSON payload")+ metadata: str = Field("{}", description="JSON metadata")+ timestamp: datetime = Field(default_factory=datetime.now)++ class Config:+ use_enum_values = True+++# Response factory functions+def message_chunk(content: str, metadata: Optional[Dict] = None) -> StreamResponse:+ """Create a message chunk response."""+ return StreamResponse(+ content=content,+ event=StreamResponseEvent.MESSAGE_CHUNK,+ metadata=metadata,+ )+++def decision_started(model_name: str, symbol: str) -> StreamResponse:+ """Create a decision started response."""+ return StreamResponse(+ content=f"{model_name} analyzing {symbol}...",+ event=StreamResponseEvent.DECISION_STARTED,+ metadata={"model_name": model_name, "symbol": symbol},+ )+++def decision_completed(+ model_name: str,+ action: str,+ symbol: str,+ quantity: float,+ confidence: float,+ reasoning: str,+) -> StreamResponse:+ """Create a decision completed response."""+ return StreamResponse(+ content=f"{model_name}: {action.upper()} {quantity} {symbol} (confidence: {confidence:.0%})",+ event=StreamResponseEvent.DECISION_COMPLETED,+ metadata={+ "model_name": model_name,+ "action": action,+ "symbol": symbol,+ "quantity": quantity,+ "confidence": confidence,+ "reasoning": reasoning,+ },+ )+++def trade_executed(+ model_name: str,+ action: str,+ symbol: str,+ quantity: float,+ price: float,+ pnl: Optional[float] = None,+) -> StreamResponse:+ """Create a trade executed response."""+ content = f"{model_name}: {action.upper()} {quantity} {symbol} @ ${price:,.2f}"+ if pnl is not None:+ content += f" (P&L: ${pnl:+,.2f})"++ return StreamResponse(+ content=content,+ event=StreamResponseEvent.TRADE_EXECUTED,+ metadata={+ "model_name": model_name,+ "action": action,+ "symbol": symbol,+ "quantity": quantity,+ "price": price,+ "pnl": pnl,+ },+ )+++def reasoning(model_name: str, text: str) -> StreamResponse:+ """Create a reasoning response."""+ return StreamResponse(+ content=text,+ event=StreamResponseEvent.REASONING,+ metadata={"model_name": model_name},+ )+++def market_data(symbol: str, price: float, change_pct: float) -> StreamResponse:+ """Create a market data response."""+ return StreamResponse(+ content=f"{symbol}: ${price:,.2f} ({change_pct:+.2f}%)",+ event=StreamResponseEvent.MARKET_DATA,+ metadata={"symbol": symbol, "price": price, "change_pct": change_pct},+ )+++def error(message: str, details: Optional[Dict] = None) -> StreamResponse:+ """Create an error response."""+ return StreamResponse(+ content=message,+ event=StreamResponseEvent.ERROR,+ metadata={"error": message, **(details or {})},+ )+++def leaderboard_update(leaderboard: list, cycle_number: int) -> StreamResponse:+ """Create a leaderboard update response."""+ return StreamResponse(+ content=f"Leaderboard updated for cycle {cycle_number}",+ event=CommonResponseEvent.LEADERBOARD_UPDATE,+ metadata={"leaderboard": leaderboard, "cycle_number": cycle_number},+ )+++def cycle_completed(cycle_number: int, cycle_time: float) -> StreamResponse:+ """Create a cycle completed response."""+ return StreamResponse(+ content=f"Cycle {cycle_number} completed in {cycle_time:.2f}s",+ event=SystemResponseEvent.CYCLE_COMPLETED,+ metadata={"cycle_number": cycle_number, "cycle_time_seconds": cycle_time},+ )+++def done() -> StreamResponse:+ """Create a done response."""+ return StreamResponse(+ content="",+ event=SystemResponseEvent.DONE,+ )diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/utils/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/utils/__init__.pynew file mode 100644index 000000000..a3d824b54--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/utils/__init__.py@@ -0,0 +1,14 @@+"""+Alpha Arena Utilities+"""++from alpha_arena.utils.uuid import generate_uuid, generate_item_id, generate_competition_id+from alpha_arena.utils.logging import get_logger, setup_logging++__all__ = [+ "generate_uuid",+ "generate_item_id",+ "generate_competition_id",+ "get_logger",+ "setup_logging",+]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/utils/logging.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/utils/logging.pynew file mode 100644index 000000000..27dbd9734--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/utils/logging.py@@ -0,0 +1,119 @@+"""+Logging utilities for Alpha Arena using loguru.+"""++import sys+from typing import Optional+from pathlib import Path++try:+ from loguru import logger+ LOGURU_AVAILABLE = True+except ImportError:+ import logging+ logger = logging.getLogger("alpha_arena")+ LOGURU_AVAILABLE = False+++def setup_logging(+ level: str = "INFO",+ log_file: Optional[str] = None,+ rotation: str = "10 MB",+ retention: str = "7 days",+) -> None:+ """Setup logging configuration.++ Args:+ level: Log level (DEBUG, INFO, WARNING, ERROR)+ log_file: Optional file path for logging+ rotation: Log rotation size+ retention: Log retention period+ """+ if LOGURU_AVAILABLE:+ # Remove default handler+ logger.remove()++ # Add stderr handler with formatting+ logger.add(+ sys.stderr,+ format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",+ level=level,+ colorize=True,+ )++ # Add file handler if specified+ if log_file:+ log_path = Path(log_file)+ log_path.parent.mkdir(parents=True, exist_ok=True)++ logger.add(+ log_file,+ format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",+ level=level,+ rotation=rotation,+ retention=retention,+ compression="gz",+ )+ else:+ # Fallback to standard logging+ logging.basicConfig(+ level=getattr(logging, level),+ format="%(asctime)s | %(levelname)-8s | %(name)s:%(funcName)s:%(lineno)d - %(message)s",+ stream=sys.stderr,+ )+++def get_logger(name: str = "alpha_arena"):+ """Get a logger instance.++ Args:+ name: Logger name (used for context in loguru)++ Returns:+ Logger instance+ """+ if LOGURU_AVAILABLE:+ return logger.bind(name=name)+ else:+ return logging.getLogger(name)+++# Convenience logging functions+def log_info(message: str, **kwargs):+ """Log info message."""+ if LOGURU_AVAILABLE:+ logger.info(message, **kwargs)+ else:+ logger.info(message % kwargs if kwargs else message)+++def log_debug(message: str, **kwargs):+ """Log debug message."""+ if LOGURU_AVAILABLE:+ logger.debug(message, **kwargs)+ else:+ logger.debug(message % kwargs if kwargs else message)+++def log_warning(message: str, **kwargs):+ """Log warning message."""+ if LOGURU_AVAILABLE:+ logger.warning(message, **kwargs)+ else:+ logger.warning(message % kwargs if kwargs else message)+++def log_error(message: str, **kwargs):+ """Log error message."""+ if LOGURU_AVAILABLE:+ logger.error(message, **kwargs)+ else:+ logger.error(message % kwargs if kwargs else message)+++def log_exception(message: str, **kwargs):+ """Log exception with traceback."""+ if LOGURU_AVAILABLE:+ logger.exception(message, **kwargs)+ else:+ logger.exception(message % kwargs if kwargs else message)diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/utils/uuid.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/utils/uuid.pynew file mode 100644index 000000000..29bf14da8--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/utils/uuid.py@@ -0,0 +1,55 @@+"""+UUID generation utilities for Alpha Arena.+"""++import time+import uuid+import random+import string+++def generate_uuid(prefix: str = "") -> str:+ """Generate a unique identifier with optional prefix.++ Args:+ prefix: Optional prefix for the ID (e.g., "comp", "trade", "decision")++ Returns:+ Unique identifier string+ """+ base_id = str(uuid.uuid4())[:8]+ timestamp = int(time.time() * 1000)++ if prefix:+ return f"{prefix}_{timestamp}_{base_id}"+ return f"{timestamp}_{base_id}"+++def generate_item_id() -> str:+ """Generate a unique item identifier for conversation items."""+ return generate_uuid("item")+++def generate_competition_id() -> str:+ """Generate a unique competition identifier."""+ random_suffix = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))+ timestamp = int(time.time())+ return f"comp_{timestamp}_{random_suffix}"+++def generate_cycle_id(competition_id: str, cycle_number: int) -> str:+ """Generate a unique cycle identifier."""+ timestamp = int(time.time() * 1000)+ return f"{competition_id}_cycle_{cycle_number}_{timestamp}"+++def generate_decision_id(competition_id: str, model_name: str, cycle_number: int) -> str:+ """Generate a unique decision identifier."""+ timestamp = int(time.time() * 1000)+ return f"{competition_id}_{model_name}_{cycle_number}_{timestamp}"+++def generate_snapshot_id(competition_id: str, model_name: str, cycle_number: int) -> str:+ """Generate a unique snapshot identifier."""+ timestamp = int(time.time() * 1000)+ return f"{competition_id}_{model_name}_snap_{cycle_number}_{timestamp}"diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/litellm_models.py b/fincept-terminal-desktop/src-tauri/resources/scripts/litellm_models.pynew file mode 100644index 000000000..29feb47c0--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/litellm_models.py@@ -0,0 +1,242 @@+#!/usr/bin/env python3+"""+LLM Models Service+Provides LLM model and provider information from embedded JSON data.+No external dependencies required - uses pre-extracted data from LiteLLM.+Supports 52+ providers and 1700+ models.+"""++import json+import sys+from pathlib import Path+from typing import Any+++# Load embedded model data+def _load_model_data() -> dict:+ """Load the embedded model data from JSON file."""+ script_dir = Path(__file__).parent+ data_file = script_dir / "llm_models_data.json"++ if data_file.exists():+ with open(data_file, 'r', encoding='utf-8') as f:+ return json.load(f)++ # Fallback: try to load from litellm if JSON doesn't exist+ try:+ from litellm import models_by_provider, model_cost+ return {+ 'providers': dict(models_by_provider),+ 'model_info': {+ model_id: {+ 'max_tokens': cost.get('max_tokens') or cost.get('max_input_tokens', 0),+ 'input_cost': cost.get('input_cost_per_token', 0),+ 'output_cost': cost.get('output_cost_per_token', 0)+ }+ for model_id, cost in model_cost.items()+ }+ }+ except ImportError:+ return {'providers': {}, 'model_info': {}}+++# Cache the loaded data+_MODEL_DATA = None++def get_model_data() -> dict:+ """Get cached model data."""+ global _MODEL_DATA+ if _MODEL_DATA is None:+ _MODEL_DATA = _load_model_data()+ return _MODEL_DATA+++def get_all_providers() -> list[dict[str, Any]]:+ """Get all available providers with their model counts."""+ try:+ data = get_model_data()+ providers = []++ for provider, models in sorted(data['providers'].items()):+ providers.append({+ "id": provider,+ "name": provider.replace("_", " ").title(),+ "model_count": len(models)+ })++ return providers+ except Exception as e:+ return [{"error": str(e)}]+++def get_models_by_provider(provider: str) -> list[dict[str, Any]]:+ """Get all models for a specific provider."""+ try:+ data = get_model_data()+ models = data['providers'].get(provider, [])+ model_info = data['model_info']++ result = []+ for model_id in models:+ info = model_info.get(model_id, {})++ # Clean up model name for display+ display_name = model_id+ if "/" in model_id:+ display_name = model_id.split("/")[-1]++ model_data = {+ "id": model_id,+ "name": display_name,+ "provider": provider,+ "context_window": info.get('max_tokens', 0),+ "input_cost_per_token": info.get('input_cost', 0),+ "output_cost_per_token": info.get('output_cost', 0),+ }++ # Add description based on model name patterns+ if "embedding" in model_id.lower():+ model_data["description"] = "Embedding model"+ elif "vision" in model_id.lower() or "image" in model_id.lower():+ model_data["description"] = "Vision/Image model"+ elif "code" in model_id.lower() or "coder" in model_id.lower():+ model_data["description"] = "Code generation model"+ elif "instruct" in model_id.lower():+ model_data["description"] = "Instruction-tuned model"+ else:+ model_data["description"] = f"{provider.replace('_', ' ').title()} model"++ result.append(model_data)++ # Sort by model name+ result.sort(key=lambda x: x["name"])++ return result+ except Exception as e:+ return [{"error": str(e)}]+++def get_all_models() -> list[dict[str, Any]]:+ """Get all models from all providers."""+ try:+ data = get_model_data()+ model_info = data['model_info']++ result = []+ for provider, models in data['providers'].items():+ for model_id in models:+ info = model_info.get(model_id, {})++ display_name = model_id+ if "/" in model_id:+ display_name = model_id.split("/")[-1]++ result.append({+ "id": model_id,+ "name": display_name,+ "provider": provider,+ "context_window": info.get('max_tokens', 0),+ })++ # Sort by provider then model name+ result.sort(key=lambda x: (x["provider"], x["name"]))++ return result+ except Exception as e:+ return [{"error": str(e)}]+++def get_provider_stats() -> dict[str, Any]:+ """Get statistics about all providers."""+ try:+ data = get_model_data()+ providers = data['providers']++ total_models = sum(len(v) for v in providers.values())+ total_providers = len(providers)++ # Top providers by model count+ sorted_providers = sorted(+ providers.items(),+ key=lambda x: len(x[1]),+ reverse=True+ )[:15]++ return {+ "total_providers": total_providers,+ "total_models": total_models,+ "top_providers": [+ {"provider": p, "model_count": len(m)}+ for p, m in sorted_providers+ ]+ }+ except Exception as e:+ return {"error": str(e)}+++def search_models(query: str) -> list[dict[str, Any]]:+ """Search models by name or provider."""+ try:+ data = get_model_data()+ model_info = data['model_info']++ query_lower = query.lower()+ result = []++ for provider, models in data['providers'].items():+ for model_id in models:+ if query_lower in model_id.lower() or query_lower in provider.lower():+ info = model_info.get(model_id, {})++ display_name = model_id+ if "/" in model_id:+ display_name = model_id.split("/")[-1]++ result.append({+ "id": model_id,+ "name": display_name,+ "provider": provider,+ "context_window": info.get('max_tokens', 0),+ })++ result.sort(key=lambda x: (x["provider"], x["name"]))+ return result[:100] # Limit to 100 results+ except Exception as e:+ return [{"error": str(e)}]+++def main():+ if len(sys.argv) < 2:+ print(json.dumps({"error": "No command specified"}))+ sys.exit(1)++ command = sys.argv[1]++ try:+ if command == "providers":+ result = get_all_providers()+ elif command == "models":+ if len(sys.argv) < 3:+ result = get_all_models()+ else:+ provider = sys.argv[2]+ result = get_models_by_provider(provider)+ elif command == "stats":+ result = get_provider_stats()+ elif command == "search":+ if len(sys.argv) < 3:+ result = {"error": "No search query specified"}+ else:+ query = sys.argv[2]+ result = search_models(query)+ else:+ result = {"error": f"Unknown command: {command}"}++ print(json.dumps(result))+ except Exception as e:+ print(json.dumps({"error": str(e)}))+ sys.exit(1)+++if __name__ == "__main__":+ main()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/llm_models_data.json b/fincept-terminal-desktop/src-tauri/resources/scripts/llm_models_data.jsonnew file mode 100644index 000000000..811cf8caa--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/llm_models_data.json@@ -0,0 +1 @@+{"providers": {"openai": ["1024-x-1024/dall-e-2", "256-x-256/dall-e-2", "512-x-512/dall-e-2", "chatgpt-4o-latest", "gpt-4o-transcribe-diarize", "codex-mini-latest", "dall-e-2", "dall-e-3", "gpt-3.5-turbo", "gpt-3.5-turbo-0125", "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-1106", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-16k-0613", "gpt-4", "gpt-4-0125-preview", "gpt-4-0314", "gpt-4-0613", "gpt-4-1106-preview", "gpt-4-1106-vision-preview", "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-turbo-preview", "gpt-4-vision-preview", "gpt-4.1", "gpt-4.1-2025-04-14", "gpt-4.1-mini", "gpt-4.1-mini-2025-04-14", "gpt-4.1-nano", "gpt-4.1-nano-2025-04-14", "gpt-4.5-preview", "gpt-4.5-preview-2025-02-27", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-2024-11-20", "gpt-4o-audio-preview", "gpt-4o-audio-preview-2024-10-01", "gpt-4o-audio-preview-2024-12-17", "gpt-4o-audio-preview-2025-06-03", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", "gpt-4o-mini-audio-preview", "gpt-4o-mini-audio-preview-2024-12-17", "gpt-4o-mini-realtime-preview", "gpt-4o-mini-realtime-preview-2024-12-17", "gpt-4o-mini-search-preview", "gpt-4o-mini-search-preview-2025-03-11", "gpt-4o-mini-transcribe", "gpt-4o-mini-tts", "gpt-4o-realtime-preview", "gpt-4o-realtime-preview-2024-10-01", "gpt-4o-realtime-preview-2024-12-17", "gpt-4o-realtime-preview-2025-06-03", "gpt-4o-search-preview", "gpt-4o-search-preview-2025-03-11", "gpt-4o-transcribe", "gpt-image-1.5", "gpt-image-1.5-2025-12-16", "low/1024-x-1024/gpt-image-1.5", "low/1024-x-1536/gpt-image-1.5", "low/1536-x-1024/gpt-image-1.5", "medium/1024-x-1024/gpt-image-1.5", "medium/1024-x-1536/gpt-image-1.5", "medium/1536-x-1024/gpt-image-1.5", "high/1024-x-1024/gpt-image-1.5", "high/1024-x-1536/gpt-image-1.5", "high/1536-x-1024/gpt-image-1.5", "standard/1024-x-1024/gpt-image-1.5", "standard/1024-x-1536/gpt-image-1.5", "standard/1536-x-1024/gpt-image-1.5", "1024-x-1024/gpt-image-1.5", "1024-x-1536/gpt-image-1.5", "1536-x-1024/gpt-image-1.5", "low/1024-x-1024/gpt-image-1.5-2025-12-16", "low/1024-x-1536/gpt-image-1.5-2025-12-16", "low/1536-x-1024/gpt-image-1.5-2025-12-16", "medium/1024-x-1024/gpt-image-1.5-2025-12-16", "medium/1024-x-1536/gpt-image-1.5-2025-12-16", "medium/1536-x-1024/gpt-image-1.5-2025-12-16", "high/1024-x-1024/gpt-image-1.5-2025-12-16", "high/1024-x-1536/gpt-image-1.5-2025-12-16", "high/1536-x-1024/gpt-image-1.5-2025-12-16", "standard/1024-x-1024/gpt-image-1.5-2025-12-16", "standard/1024-x-1536/gpt-image-1.5-2025-12-16", "standard/1536-x-1024/gpt-image-1.5-2025-12-16", "1024-x-1024/gpt-image-1.5-2025-12-16", "1024-x-1536/gpt-image-1.5-2025-12-16", "1536-x-1024/gpt-image-1.5-2025-12-16", "gpt-5", "gpt-5.1", "gpt-5.1-2025-11-13", "gpt-5.1-chat-latest", "gpt-5.2", "gpt-5.2-2025-12-11", "gpt-5.2-chat-latest", "gpt-5.2-pro", "gpt-5.2-pro-2025-12-11", "gpt-5-pro", "gpt-5-pro-2025-10-06", "gpt-5-2025-08-07", "gpt-5-chat", "gpt-5-chat-latest", "gpt-5-codex", "gpt-5.1-codex", "gpt-5.1-codex-max", "gpt-5.1-codex-mini", "gpt-5.2-codex", "gpt-5-mini", "gpt-5-mini-2025-08-07", "gpt-5-nano", "gpt-5-nano-2025-08-07", "gpt-image-1", "gpt-image-1-mini", "gpt-realtime", "gpt-realtime-mini", "gpt-realtime-2025-08-28", "hd/1024-x-1024/dall-e-3", "hd/1024-x-1792/dall-e-3", "hd/1792-x-1024/dall-e-3", "high/1024-x-1024/gpt-image-1", "high/1024-x-1536/gpt-image-1", "high/1536-x-1024/gpt-image-1", "low/1024-x-1024/gpt-image-1", "low/1024-x-1536/gpt-image-1", "low/1536-x-1024/gpt-image-1", "medium/1024-x-1024/gpt-image-1", "medium/1024-x-1536/gpt-image-1", "medium/1536-x-1024/gpt-image-1", "low/1024-x-1024/gpt-image-1-mini", "low/1024-x-1536/gpt-image-1-mini", "low/1536-x-1024/gpt-image-1-mini", "medium/1024-x-1024/gpt-image-1-mini", "medium/1024-x-1536/gpt-image-1-mini", "medium/1536-x-1024/gpt-image-1-mini", "o1", "o1-2024-12-17", "o1-mini", "o1-mini-2024-09-12", "o1-preview", "o1-preview-2024-09-12", "o1-pro", "o1-pro-2025-03-19", "o3", "o3-2025-04-16", "o3-deep-research", "o3-deep-research-2025-06-26", "o3-mini", "o3-mini-2025-01-31", "o3-pro", "o3-pro-2025-06-10", "o4-mini", "o4-mini-2025-04-16", "o4-mini-deep-research", "o4-mini-deep-research-2025-06-26", "omni-moderation-2024-09-26", "omni-moderation-latest", "omni-moderation-latest-intents", "standard/1024-x-1024/dall-e-3", "standard/1024-x-1792/dall-e-3", "standard/1792-x-1024/dall-e-3", "text-embedding-3-large", "text-embedding-3-small", "text-embedding-ada-002", "text-embedding-ada-002-v2", "text-moderation-007", "text-moderation-latest", "text-moderation-stable", "tts-1", "tts-1-hd", "whisper-1", "openai/container", "openai/sora-2", "openai/sora-2-pro", "babbage-002", "davinci-002", "ft:babbage-002", "ft:davinci-002", "gpt-3.5-turbo-instruct", "gpt-3.5-turbo-instruct-0914"], "text-completion-openai": ["babbage-002", "davinci-002", "ft:babbage-002", "ft:davinci-002", "gpt-3.5-turbo-instruct", "gpt-3.5-turbo-instruct-0914"], "cohere": ["cohere/embed-v4.0", "command", "command-nightly", "embed-english-light-v2.0", "embed-english-light-v3.0", "embed-english-v2.0", "embed-english-v3.0", "embed-multilingual-v2.0", "embed-multilingual-v3.0", "embed-multilingual-light-v3.0", "rerank-english-v2.0", "rerank-english-v3.0", "rerank-multilingual-v2.0", "rerank-multilingual-v3.0", "rerank-v3.5", "command-a-03-2025", "command-light", "command-r", "command-r-08-2024", "command-r-plus", "command-r-plus-08-2024", "command-r7b-12-2024"], "cohere_chat": ["command-a-03-2025", "command-light", "command-r", "command-r-08-2024", "command-r-plus", "command-r-plus-08-2024", "command-r7b-12-2024"], "anthropic": ["claude-3-5-haiku-20241022", "claude-3-5-haiku-latest", "claude-haiku-4-5-20251001", "claude-haiku-4-5", "claude-3-5-sonnet-20240620", "claude-3-5-sonnet-20241022", "claude-3-5-sonnet-latest", "claude-3-7-sonnet-20250219", "claude-3-7-sonnet-latest", "claude-3-haiku-20240307", "claude-3-opus-20240229", "claude-3-opus-latest", "claude-4-opus-20250514", "claude-4-sonnet-20250514", "claude-sonnet-4-5", "claude-sonnet-4-5-20250929", "claude-opus-4-1", "claude-opus-4-1-20250805", "claude-opus-4-20250514", "claude-opus-4-5-20251101", "claude-opus-4-5", "claude-sonnet-4-20250514"], "replicate": ["replicate/llama-2-70b-chat:2796ee9483c3fd7aa2e171d38f4ca12251a30609463dcfd4cd76703f22e96cdf", "a16z-infra/llama-2-13b-chat:2a7f981751ec7fdf87b5b91ad4db53683a98082e9ff7bfd12c8cd5ea85980a52", "meta/codellama-13b:1c914d844307b0588599b8393480a3ba917b660c7e9dfae681542b5325f228db", "replicate/vicuna-13b:6282abe6a492de4145d7bb601023762212f9ddbbe78278bd6771c8b3b2f2a13b", "joehoover/instructblip-vicuna13b:c4c54e3c8c97cd50c2d2fec9be3b6065563ccf7d43787fb99f84151b867178fe", "daanelson/flan-t5-large:ce962b3f6792a57074a601d3979db5839697add2e4e02696b3ced4c022d4767f", "replicate/dolly-v2-12b:ef0e1aefc61f8e096ebe4db6b2bacc297daf2ef6899f0f7e001ec445893500e5", "replit/replit-code-v1-3b:b84f4c074b807211cd75e3e8b1589b6399052125b4c27106e43d47189e8415ad"], "huggingface": ["meta-llama/Llama-2-7b-hf", "meta-llama/Llama-2-7b-chat-hf", "meta-llama/Llama-2-13b-hf", "meta-llama/Llama-2-13b-chat-hf", "meta-llama/Llama-2-70b-hf", "meta-llama/Llama-2-70b-chat-hf", "meta-llama/Llama-2-7b", "meta-llama/Llama-2-7b-chat", "meta-llama/Llama-2-13b", "meta-llama/Llama-2-13b-chat", "meta-llama/Llama-2-70b", "meta-llama/Llama-2-70b-chat"], "together_ai": ["togethercomputer/llama-2-70b-chat", "togethercomputer/llama-2-70b", "togethercomputer/LLaMA-2-7B-32K", "togethercomputer/Llama-2-7B-32K-Instruct", "togethercomputer/llama-2-7b", "togethercomputer/falcon-40b-instruct", "togethercomputer/falcon-7b-instruct", "togethercomputer/alpaca-7b", "HuggingFaceH4/starchat-alpha", "togethercomputer/CodeLlama-34b", "togethercomputer/CodeLlama-34b-Instruct", "togethercomputer/CodeLlama-34b-Python", "defog/sqlcoder", "NumbersStation/nsql-llama-2-7B", "WizardLM/WizardCoder-15B-V1.0", "WizardLM/WizardCoder-Python-34B-V1.0", "NousResearch/Nous-Hermes-Llama2-13b", "Austism/chronos-hermes-13b", "upstage/SOLAR-0-70b-16bit", "WizardLM/WizardLM-70B-V1.0"], "baseten": ["qvv0xeq", "q841o8w", "31dxrj3"], "openrouter": ["openrouter/anthropic/claude-2", "openrouter/anthropic/claude-3-5-haiku", "openrouter/anthropic/claude-3-5-haiku-20241022", "openrouter/anthropic/claude-3-haiku", "openrouter/anthropic/claude-3-haiku-20240307", "openrouter/anthropic/claude-3-opus", "openrouter/anthropic/claude-3-sonnet", "openrouter/anthropic/claude-3.5-sonnet", "openrouter/anthropic/claude-3.5-sonnet:beta", "openrouter/anthropic/claude-3.7-sonnet", "openrouter/anthropic/claude-3.7-sonnet:beta", "openrouter/anthropic/claude-instant-v1", "openrouter/anthropic/claude-opus-4", "openrouter/anthropic/claude-opus-4.1", "openrouter/anthropic/claude-sonnet-4", "openrouter/anthropic/claude-opus-4.5", "openrouter/anthropic/claude-sonnet-4.5", "openrouter/anthropic/claude-haiku-4.5", "openrouter/bytedance/ui-tars-1.5-7b", "openrouter/cognitivecomputations/dolphin-mixtral-8x7b", "openrouter/cohere/command-r-plus", "openrouter/databricks/dbrx-instruct", "openrouter/deepseek/deepseek-chat", "openrouter/deepseek/deepseek-chat-v3-0324", "openrouter/deepseek/deepseek-chat-v3.1", "openrouter/deepseek/deepseek-v3.2", "openrouter/deepseek/deepseek-v3.2-exp", "openrouter/deepseek/deepseek-coder", "openrouter/deepseek/deepseek-r1", "openrouter/deepseek/deepseek-r1-0528", "openrouter/fireworks/firellava-13b", "openrouter/google/gemini-2.0-flash-001", "openrouter/google/gemini-2.5-flash", "openrouter/google/gemini-2.5-pro", "openrouter/google/gemini-3-pro-preview", "openrouter/google/gemini-3-flash-preview", "openrouter/google/gemini-pro-1.5", "openrouter/google/gemini-pro-vision", "openrouter/google/palm-2-chat-bison", "openrouter/google/palm-2-codechat-bison", "openrouter/gryphe/mythomax-l2-13b", "openrouter/jondurbin/airoboros-l2-70b-2.1", "openrouter/mancer/weaver", "openrouter/meta-llama/codellama-34b-instruct", "openrouter/meta-llama/llama-2-13b-chat", "openrouter/meta-llama/llama-2-70b-chat", "openrouter/meta-llama/llama-3-70b-instruct", "openrouter/meta-llama/llama-3-70b-instruct:nitro", "openrouter/meta-llama/llama-3-8b-instruct:extended", "openrouter/meta-llama/llama-3-8b-instruct:free", "openrouter/microsoft/wizardlm-2-8x22b:nitro", "openrouter/minimax/minimax-m2", "openrouter/mistralai/devstral-2512:free", "openrouter/mistralai/devstral-2512", "openrouter/mistralai/ministral-3b-2512", "openrouter/mistralai/ministral-8b-2512", "openrouter/mistralai/ministral-14b-2512", "openrouter/mistralai/mistral-large-2512", "openrouter/mistralai/mistral-7b-instruct", "openrouter/mistralai/mistral-7b-instruct:free", "openrouter/mistralai/mistral-large", "openrouter/mistralai/mistral-small-3.1-24b-instruct", "openrouter/mistralai/mistral-small-3.2-24b-instruct", "openrouter/mistralai/mixtral-8x22b-instruct", "openrouter/nousresearch/nous-hermes-llama2-13b", "openrouter/openai/gpt-3.5-turbo", "openrouter/openai/gpt-3.5-turbo-16k", "openrouter/openai/gpt-4", "openrouter/openai/gpt-4-vision-preview", "openrouter/openai/gpt-4.1", "openrouter/openai/gpt-4.1-2025-04-14", "openrouter/openai/gpt-4.1-mini", "openrouter/openai/gpt-4.1-mini-2025-04-14", "openrouter/openai/gpt-4.1-nano", "openrouter/openai/gpt-4.1-nano-2025-04-14", "openrouter/openai/gpt-4o", "openrouter/openai/gpt-4o-2024-05-13", "openrouter/openai/gpt-5-chat", "openrouter/openai/gpt-5-codex", "openrouter/openai/gpt-5.2-codex", "openrouter/openai/gpt-5", "openrouter/openai/gpt-5-mini", "openrouter/openai/gpt-5-nano", "openrouter/openai/gpt-5.2", "openrouter/openai/gpt-5.2-chat", "openrouter/openai/gpt-5.2-pro", "openrouter/openai/gpt-oss-120b", "openrouter/openai/gpt-oss-20b", "openrouter/openai/o1", "openrouter/openai/o1-mini", "openrouter/openai/o1-mini-2024-09-12", "openrouter/openai/o1-preview", "openrouter/openai/o1-preview-2024-09-12", "openrouter/openai/o3-mini", "openrouter/openai/o3-mini-high", "openrouter/pygmalionai/mythalion-13b", "openrouter/qwen/qwen-2.5-coder-32b-instruct", "openrouter/qwen/qwen-vl-plus", "openrouter/qwen/qwen3-coder", "openrouter/switchpoint/router", "openrouter/undi95/remm-slerp-l2-13b", "openrouter/x-ai/grok-4", "openrouter/x-ai/grok-4-fast:free", "openrouter/z-ai/glm-4.6", "openrouter/z-ai/glm-4.6:exacto"], "datarobot": [], "vertex_ai": ["chat-bison", "chat-bison-32k", "chat-bison-32k@002", "chat-bison@001", "chat-bison@002", "text-bison", "text-bison32k", "text-bison32k@002", "text-bison@001", "text-bison@002", "text-unicorn", "text-unicorn@001", "claude-3-5-haiku", "claude-3-5-haiku@20241022", "claude-haiku-4-5@20251001", "claude-3-5-sonnet", "claude-3-5-sonnet-v2", "claude-3-5-sonnet-v2@20241022", "claude-3-5-sonnet@20240620", "claude-3-7-sonnet@20250219", "claude-3-haiku", "claude-3-haiku@20240307", "claude-3-opus", "claude-3-opus@20240229", "claude-3-sonnet", "claude-3-sonnet@20240229", "claude-opus-4", "claude-opus-4-1", "claude-opus-4-1@20250805", "claude-opus-4-5", "claude-opus-4-5@20251101", "claude-sonnet-4-5", "claude-sonnet-4-5@20250929", "claude-opus-4@20250514", "claude-sonnet-4", "claude-sonnet-4@20250514", "gemini-1.0-pro-vision", "gemini-1.0-pro-vision-001", "gemini-pro-vision", "gemini-1.0-pro", "gemini-1.0-pro-001", "gemini-1.0-pro-002", "gemini-1.0-ultra", "gemini-1.0-ultra-001", "gemini-1.5-flash", "gemini-1.5-flash-001", "gemini-1.5-flash-002", "gemini-1.5-flash-exp-0827", "gemini-1.5-flash-preview-0514", "gemini-1.5-pro", "gemini-1.5-pro-001", "gemini-1.5-pro-002", "gemini-1.5-pro-preview-0215", "gemini-1.5-pro-preview-0409", "gemini-1.5-pro-preview-0514", "gemini-2.0-flash", "gemini-2.0-flash-001", "gemini-2.0-flash-exp", "gemini-2.0-flash-lite", "gemini-2.0-flash-lite-001", "gemini-2.0-flash-live-preview-04-09", "gemini-2.0-flash-preview-image-generation", "gemini-2.0-flash-thinking-exp", "gemini-2.0-flash-thinking-exp-01-21", "gemini-2.0-pro-exp-02-05", "gemini-2.5-flash", "gemini-2.5-flash-image", "gemini-2.5-flash-image-preview", "gemini-3-pro-image-preview", "gemini-2.5-flash-lite", "gemini-2.5-flash-lite-preview-09-2025", "gemini-2.5-flash-preview-09-2025", "gemini-live-2.5-flash-preview-native-audio-09-2025", "gemini-2.5-flash-lite-preview-06-17", "gemini-2.5-flash-preview-04-17", "gemini-2.5-flash-preview-05-20", "gemini-2.5-pro", "gemini-3-pro-preview", "gemini-2.5-pro-exp-03-25", "gemini-2.5-pro-preview-03-25", "gemini-2.5-pro-preview-05-06", "gemini-2.5-pro-preview-06-05", "gemini-2.5-pro-preview-tts", "gemini-flash-experimental", "gemini-pro", "gemini-pro-experimental", "gemini/gemini-2.5-flash-image", "gemini-3-flash-preview", "medlm-large", "medlm-medium", "vertex_ai/gemini-2.5-flash-image", "vertex_ai/gemini-3-pro-image-preview"], "ai21": ["j2-light", "j2-mid", "j2-ultra"], "bedrock": ["1024-x-1024/50-steps/bedrock/amazon.nova-canvas-v1:0", "1024-x-1024/50-steps/stability.stable-diffusion-xl-v1", "1024-x-1024/max-steps/stability.stable-diffusion-xl-v1", "512-x-512/50-steps/stability.stable-diffusion-xl-v0", "512-x-512/max-steps/stability.stable-diffusion-xl-v0", "ai21.j2-mid-v1", "ai21.j2-ultra-v1", "ai21.jamba-1-5-large-v1:0", "ai21.jamba-1-5-mini-v1:0", "ai21.jamba-instruct-v1:0", "amazon.nova-canvas-v1:0", "amazon.nova-2-multimodal-embeddings-v1:0", "amazon.rerank-v1:0", "amazon.titan-embed-image-v1", "amazon.titan-embed-text-v1", "amazon.titan-embed-text-v2:0", "amazon.titan-image-generator-v1", "amazon.titan-image-generator-v2", "amazon.titan-image-generator-v2:0", "twelvelabs.marengo-embed-2-7-v1:0", "us.twelvelabs.marengo-embed-2-7-v1:0", "eu.twelvelabs.marengo-embed-2-7-v1:0", "twelvelabs.pegasus-1-2-v1:0", "us.twelvelabs.pegasus-1-2-v1:0", "eu.twelvelabs.pegasus-1-2-v1:0", "amazon.titan-text-express-v1", "amazon.titan-text-lite-v1", "amazon.titan-text-premier-v1:0", "anthropic.claude-3-5-haiku-20241022-v1:0", "anthropic.claude-3-5-sonnet-20240620-v1:0", "anthropic.claude-3-5-sonnet-20241022-v2:0", "anthropic.claude-3-7-sonnet-20240620-v1:0", "anthropic.claude-3-haiku-20240307-v1:0", "anthropic.claude-3-opus-20240229-v1:0", "anthropic.claude-3-sonnet-20240229-v1:0", "anthropic.claude-instant-v1", "anthropic.claude-v1", "anthropic.claude-v2:1", "apac.anthropic.claude-3-5-sonnet-20240620-v1:0", "apac.anthropic.claude-3-5-sonnet-20241022-v2:0", "apac.anthropic.claude-3-haiku-20240307-v1:0", "apac.anthropic.claude-3-sonnet-20240229-v1:0", "bedrock/us.anthropic.claude-3-5-haiku-20241022-v1:0", "claude-sonnet-4-5-20250929-v1:0", "cohere.command-light-text-v14", "cohere.command-r-plus-v1:0", "cohere.command-r-v1:0", "cohere.command-text-v14", "cohere.embed-english-v3", "cohere.embed-multilingual-v3", "cohere.embed-v4:0", "cohere.rerank-v3-5:0", "eu.anthropic.claude-3-5-haiku-20241022-v1:0", "eu.anthropic.claude-3-5-sonnet-20240620-v1:0", "eu.anthropic.claude-3-5-sonnet-20241022-v2:0", "eu.anthropic.claude-3-7-sonnet-20250219-v1:0", "eu.anthropic.claude-3-haiku-20240307-v1:0", "eu.anthropic.claude-3-opus-20240229-v1:0", "eu.anthropic.claude-3-sonnet-20240229-v1:0", "eu.meta.llama3-2-1b-instruct-v1:0", "eu.meta.llama3-2-3b-instruct-v1:0", "max-x-max/50-steps/stability.stable-diffusion-xl-v0", "max-x-max/max-steps/stability.stable-diffusion-xl-v0", "meta.llama2-13b-chat-v1", "meta.llama2-70b-chat-v1", "meta.llama3-1-405b-instruct-v1:0", "meta.llama3-1-70b-instruct-v1:0", "meta.llama3-1-8b-instruct-v1:0", "meta.llama3-2-11b-instruct-v1:0", "meta.llama3-2-1b-instruct-v1:0", "meta.llama3-2-3b-instruct-v1:0", "meta.llama3-2-90b-instruct-v1:0", "meta.llama3-70b-instruct-v1:0", "meta.llama3-8b-instruct-v1:0", "mistral.mistral-7b-instruct-v0:2", "mistral.mistral-large-2402-v1:0", "mistral.mistral-large-2407-v1:0", "mistral.mistral-small-2402-v1:0", "mistral.mixtral-8x7b-instruct-v0:1", "stability.sd3-5-large-v1:0", "stability.sd3-large-v1:0", "stability.stable-image-core-v1:0", "stability.stable-conservative-upscale-v1:0", "stability.stable-creative-upscale-v1:0", "stability.stable-fast-upscale-v1:0", "stability.stable-outpaint-v1:0", "stability.stable-image-control-sketch-v1:0", "stability.stable-image-control-structure-v1:0", "stability.stable-image-erase-object-v1:0", "stability.stable-image-inpaint-v1:0", "stability.stable-image-remove-background-v1:0", "stability.stable-image-search-recolor-v1:0", "stability.stable-image-search-replace-v1:0", "stability.stable-image-style-guide-v1:0", "stability.stable-style-transfer-v1:0", "stability.stable-image-core-v1:1", "stability.stable-image-ultra-v1:0", "stability.stable-image-ultra-v1:1", "us.anthropic.claude-3-5-haiku-20241022-v1:0", "us.anthropic.claude-3-5-sonnet-20240620-v1:0", "us.anthropic.claude-3-5-sonnet-20241022-v2:0", "us.anthropic.claude-3-haiku-20240307-v1:0", "us.anthropic.claude-3-opus-20240229-v1:0", "us.anthropic.claude-3-sonnet-20240229-v1:0", "us.meta.llama3-1-405b-instruct-v1:0", "us.meta.llama3-1-70b-instruct-v1:0", "us.meta.llama3-1-8b-instruct-v1:0", "us.meta.llama3-2-11b-instruct-v1:0", "us.meta.llama3-2-1b-instruct-v1:0", "us.meta.llama3-2-3b-instruct-v1:0", "us.meta.llama3-2-90b-instruct-v1:0", "anthropic.claude-opus-4-20250514-v1:0", "anthropic.claude-sonnet-4-20250514-v1:0", "anthropic.claude-3-7-sonnet-20250219-v1:0", "anthropic.claude-3-5-haiku-20241022-v1:0", "anthropic.claude-3-5-sonnet-20241022-v2:0", "anthropic.claude-3-5-sonnet-20240620-v1:0", "anthropic.claude-3-opus-20240229-v1:0", "anthropic.claude-3-sonnet-20240229-v1:0", "anthropic.claude-3-haiku-20240307-v1:0", "anthropic.claude-v2", "anthropic.claude-v2:1", "anthropic.claude-v1", "anthropic.claude-instant-v1", "ai21.jamba-instruct-v1:0", "ai21.jamba-1-5-mini-v1:0", "ai21.jamba-1-5-large-v1:0", "meta.llama3-70b-instruct-v1:0", "meta.llama3-8b-instruct-v1:0", "meta.llama3-1-8b-instruct-v1:0", "meta.llama3-1-70b-instruct-v1:0", "meta.llama3-1-405b-instruct-v1:0", "meta.llama3-70b-instruct-v1:0", "mistral.mistral-large-2407-v1:0", "mistral.mistral-large-2402-v1:0", "mistral.mistral-small-2402-v1:0", "meta.llama3-2-1b-instruct-v1:0", "meta.llama3-2-3b-instruct-v1:0", "meta.llama3-2-11b-instruct-v1:0", "meta.llama3-2-90b-instruct-v1:0", "us.writer.palmyra-x4-v1:0", "us.writer.palmyra-x5-v1:0", "writer.palmyra-x4-v1:0", "writer.palmyra-x5-v1:0", "amazon.nova-lite-v1:0", "amazon.nova-2-lite-v1:0", "apac.amazon.nova-2-lite-v1:0", "eu.amazon.nova-2-lite-v1:0", "us.amazon.nova-2-lite-v1:0", "amazon.nova-micro-v1:0", "amazon.nova-pro-v1:0", "anthropic.claude-haiku-4-5-20251001-v1:0", "anthropic.claude-haiku-4-5@20251001", "anthropic.claude-3-7-sonnet-20250219-v1:0", "anthropic.claude-opus-4-1-20250805-v1:0", "anthropic.claude-opus-4-20250514-v1:0", "anthropic.claude-opus-4-5-20251101-v1:0", "anthropic.claude-sonnet-4-20250514-v1:0", "anthropic.claude-sonnet-4-5-20250929-v1:0", "apac.amazon.nova-lite-v1:0", "apac.amazon.nova-micro-v1:0", "apac.amazon.nova-pro-v1:0", "apac.anthropic.claude-haiku-4-5-20251001-v1:0", "apac.anthropic.claude-sonnet-4-20250514-v1:0", "au.anthropic.claude-sonnet-4-5-20250929-v1:0", "deepseek.v3-v1:0", "eu.amazon.nova-lite-v1:0", "eu.amazon.nova-micro-v1:0", "eu.amazon.nova-pro-v1:0", "eu.anthropic.claude-haiku-4-5-20251001-v1:0", "eu.anthropic.claude-opus-4-1-20250805-v1:0", "eu.anthropic.claude-opus-4-20250514-v1:0", "eu.anthropic.claude-sonnet-4-20250514-v1:0", "eu.anthropic.claude-sonnet-4-5-20250929-v1:0", "eu.mistral.pixtral-large-2502-v1:0", "google.gemma-3-12b-it", "google.gemma-3-27b-it", "google.gemma-3-4b-it", "global.anthropic.claude-sonnet-4-5-20250929-v1:0", "global.anthropic.claude-sonnet-4-20250514-v1:0", "global.anthropic.claude-haiku-4-5-20251001-v1:0", "global.amazon.nova-2-lite-v1:0", "jp.anthropic.claude-sonnet-4-5-20250929-v1:0", "jp.anthropic.claude-haiku-4-5-20251001-v1:0", "meta.llama3-3-70b-instruct-v1:0", "meta.llama4-maverick-17b-instruct-v1:0", "meta.llama4-scout-17b-instruct-v1:0", "minimax.minimax-m2", "mistral.magistral-small-2509", "mistral.ministral-3-14b-instruct", "mistral.ministral-3-3b-instruct", "mistral.ministral-3-8b-instruct", "mistral.mistral-large-3-675b-instruct", "mistral.voxtral-mini-3b-2507", "mistral.voxtral-small-24b-2507", "moonshot.kimi-k2-thinking", "nvidia.nemotron-nano-12b-v2", "nvidia.nemotron-nano-9b-v2", "openai.gpt-oss-120b-1:0", "openai.gpt-oss-20b-1:0", "openai.gpt-oss-safeguard-120b", "openai.gpt-oss-safeguard-20b", "qwen.qwen3-coder-480b-a35b-v1:0", "qwen.qwen3-235b-a22b-2507-v1:0", "qwen.qwen3-coder-30b-a3b-v1:0", "qwen.qwen3-32b-v1:0", "qwen.qwen3-next-80b-a3b", "qwen.qwen3-vl-235b-a22b", "us.amazon.nova-lite-v1:0", "us.amazon.nova-micro-v1:0", "us.amazon.nova-premier-v1:0", "us.amazon.nova-pro-v1:0", "us.anthropic.claude-haiku-4-5-20251001-v1:0", "us.anthropic.claude-3-7-sonnet-20250219-v1:0", "us.anthropic.claude-opus-4-1-20250805-v1:0", "us.anthropic.claude-sonnet-4-5-20250929-v1:0", "au.anthropic.claude-haiku-4-5-20251001-v1:0", "us.anthropic.claude-opus-4-20250514-v1:0", "us.anthropic.claude-opus-4-5-20251101-v1:0", "global.anthropic.claude-opus-4-5-20251101-v1:0", "eu.anthropic.claude-opus-4-5-20251101-v1:0", "us.anthropic.claude-sonnet-4-20250514-v1:0", "us.deepseek.r1-v1:0", "us.meta.llama3-3-70b-instruct-v1:0", "us.meta.llama4-maverick-17b-instruct-v1:0", "us.meta.llama4-scout-17b-instruct-v1:0", "us.mistral.pixtral-large-2502-v1:0"], "petals": ["petals-team/StableBeluga2"], "ollama": ["llama2"], "deepinfra": ["deepinfra/Gryphe/MythoMax-L2-13b", "deepinfra/NousResearch/Hermes-3-Llama-3.1-405B", "deepinfra/NousResearch/Hermes-3-Llama-3.1-70B", "deepinfra/Qwen/QwQ-32B", "deepinfra/Qwen/Qwen2.5-72B-Instruct", "deepinfra/Qwen/Qwen2.5-7B-Instruct", "deepinfra/Qwen/Qwen2.5-VL-32B-Instruct", "deepinfra/Qwen/Qwen3-14B", "deepinfra/Qwen/Qwen3-235B-A22B", "deepinfra/Qwen/Qwen3-235B-A22B-Instruct-2507", "deepinfra/Qwen/Qwen3-235B-A22B-Thinking-2507", "deepinfra/Qwen/Qwen3-30B-A3B", "deepinfra/Qwen/Qwen3-32B", "deepinfra/Qwen/Qwen3-Coder-480B-A35B-Instruct", "deepinfra/Qwen/Qwen3-Coder-480B-A35B-Instruct-Turbo", "deepinfra/Qwen/Qwen3-Next-80B-A3B-Instruct", "deepinfra/Qwen/Qwen3-Next-80B-A3B-Thinking", "deepinfra/Sao10K/L3-8B-Lunaris-v1-Turbo", "deepinfra/Sao10K/L3.1-70B-Euryale-v2.2", "deepinfra/Sao10K/L3.3-70B-Euryale-v2.3", "deepinfra/allenai/olmOCR-7B-0725-FP8", "deepinfra/anthropic/claude-3-7-sonnet-latest", "deepinfra/anthropic/claude-4-opus", "deepinfra/anthropic/claude-4-sonnet", "deepinfra/deepseek-ai/DeepSeek-R1", "deepinfra/deepseek-ai/DeepSeek-R1-0528", "deepinfra/deepseek-ai/DeepSeek-R1-0528-Turbo", "deepinfra/deepseek-ai/DeepSeek-R1-Distill-Llama-70B", "deepinfra/deepseek-ai/DeepSeek-R1-Distill-Qwen-32B", "deepinfra/deepseek-ai/DeepSeek-R1-Turbo", "deepinfra/deepseek-ai/DeepSeek-V3", "deepinfra/deepseek-ai/DeepSeek-V3-0324", "deepinfra/deepseek-ai/DeepSeek-V3.1", "deepinfra/deepseek-ai/DeepSeek-V3.1-Terminus", "deepinfra/google/gemini-2.0-flash-001", "deepinfra/google/gemini-2.5-flash", "deepinfra/google/gemini-2.5-pro", "deepinfra/google/gemma-3-12b-it", "deepinfra/google/gemma-3-27b-it", "deepinfra/google/gemma-3-4b-it", "deepinfra/meta-llama/Llama-3.2-11B-Vision-Instruct", "deepinfra/meta-llama/Llama-3.2-3B-Instruct", "deepinfra/meta-llama/Llama-3.3-70B-Instruct", "deepinfra/meta-llama/Llama-3.3-70B-Instruct-Turbo", "deepinfra/meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8", "deepinfra/meta-llama/Llama-4-Scout-17B-16E-Instruct", "deepinfra/meta-llama/Llama-Guard-3-8B", "deepinfra/meta-llama/Llama-Guard-4-12B", "deepinfra/meta-llama/Meta-Llama-3-8B-Instruct", "deepinfra/meta-llama/Meta-Llama-3.1-70B-Instruct", "deepinfra/meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo", "deepinfra/meta-llama/Meta-Llama-3.1-8B-Instruct", "deepinfra/meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo", "deepinfra/microsoft/WizardLM-2-8x22B", "deepinfra/microsoft/phi-4", "deepinfra/mistralai/Mistral-Nemo-Instruct-2407", "deepinfra/mistralai/Mistral-Small-24B-Instruct-2501", "deepinfra/mistralai/Mistral-Small-3.2-24B-Instruct-2506", "deepinfra/mistralai/Mixtral-8x7B-Instruct-v0.1", "deepinfra/moonshotai/Kimi-K2-Instruct", "deepinfra/moonshotai/Kimi-K2-Instruct-0905", "deepinfra/nvidia/Llama-3.1-Nemotron-70B-Instruct", "deepinfra/nvidia/Llama-3.3-Nemotron-Super-49B-v1.5", "deepinfra/nvidia/NVIDIA-Nemotron-Nano-9B-v2", "deepinfra/openai/gpt-oss-120b", "deepinfra/openai/gpt-oss-20b", "deepinfra/zai-org/GLM-4.5"], "perplexity": ["perplexity/search", "perplexity/codellama-34b-instruct", "perplexity/codellama-70b-instruct", "perplexity/llama-2-70b-chat", "perplexity/llama-3.1-70b-instruct", "perplexity/llama-3.1-8b-instruct", "perplexity/llama-3.1-sonar-huge-128k-online", "perplexity/llama-3.1-sonar-large-128k-chat", "perplexity/llama-3.1-sonar-large-128k-online", "perplexity/llama-3.1-sonar-small-128k-chat", "perplexity/llama-3.1-sonar-small-128k-online", "perplexity/mistral-7b-instruct", "perplexity/mixtral-8x7b-instruct", "perplexity/pplx-70b-chat", "perplexity/pplx-70b-online", "perplexity/pplx-7b-chat", "perplexity/pplx-7b-online", "perplexity/sonar", "perplexity/sonar-deep-research", "perplexity/sonar-medium-chat", "perplexity/sonar-medium-online", "perplexity/sonar-pro", "perplexity/sonar-reasoning", "perplexity/sonar-reasoning-pro", "perplexity/sonar-small-chat", "perplexity/sonar-small-online"], "maritalk": ["maritalk"], "watsonx": ["watsonx/ibm/granite-3-8b-instruct", "watsonx/mistralai/mistral-large", "watsonx/bigscience/mt0-xxl-13b", "watsonx/core42/jais-13b-chat", "watsonx/google/flan-t5-xl-3b", "watsonx/ibm/granite-13b-chat-v2", "watsonx/ibm/granite-13b-instruct-v2", "watsonx/ibm/granite-3-3-8b-instruct", "watsonx/ibm/granite-4-h-small", "watsonx/ibm/granite-guardian-3-2-2b", "watsonx/ibm/granite-guardian-3-3-8b", "watsonx/ibm/granite-ttm-1024-96-r2", "watsonx/ibm/granite-ttm-1536-96-r2", "watsonx/ibm/granite-ttm-512-96-r2", "watsonx/ibm/granite-vision-3-2-2b", "watsonx/meta-llama/llama-3-2-11b-vision-instruct", "watsonx/meta-llama/llama-3-2-1b-instruct", "watsonx/meta-llama/llama-3-2-3b-instruct", "watsonx/meta-llama/llama-3-2-90b-vision-instruct", "watsonx/meta-llama/llama-3-3-70b-instruct", "watsonx/meta-llama/llama-4-maverick-17b", "watsonx/meta-llama/llama-guard-3-11b-vision", "watsonx/mistralai/mistral-medium-2505", "watsonx/mistralai/mistral-small-2503", "watsonx/mistralai/mistral-small-3-1-24b-instruct-2503", "watsonx/mistralai/pixtral-12b-2409", "watsonx/openai/gpt-oss-120b", "watsonx/sdaia/allam-1-13b-instruct", "watsonx/whisper-large-v3-turbo"], "gemini": ["gemini/gemini-live-2.5-flash-preview-native-audio-09-2025", "gemini/gemini-embedding-001", "gemini/gemini-1.5-flash", "gemini/gemini-1.5-flash-001", "gemini/gemini-1.5-flash-002", "gemini/gemini-1.5-flash-8b", "gemini/gemini-1.5-flash-8b-exp-0827", "gemini/gemini-1.5-flash-8b-exp-0924", "gemini/gemini-1.5-flash-exp-0827", "gemini/gemini-1.5-flash-latest", "gemini/gemini-1.5-pro", "gemini/gemini-1.5-pro-001", "gemini/gemini-1.5-pro-002", "gemini/gemini-1.5-pro-exp-0801", "gemini/gemini-1.5-pro-exp-0827", "gemini/gemini-1.5-pro-latest", "gemini/gemini-2.0-flash", "gemini/gemini-2.0-flash-001", "gemini/gemini-2.0-flash-exp", "gemini/gemini-2.0-flash-lite", "gemini/gemini-2.0-flash-lite-preview-02-05", "gemini/gemini-2.0-flash-live-001", "gemini/gemini-2.0-flash-preview-image-generation", "gemini/gemini-2.0-flash-thinking-exp", "gemini/gemini-2.0-flash-thinking-exp-01-21", "gemini/gemini-2.0-pro-exp-02-05", "gemini/gemini-2.5-flash", "gemini/gemini-2.5-flash-image-preview", "gemini/gemini-3-pro-image-preview", "gemini/gemini-2.5-flash-lite", "gemini/gemini-2.5-flash-lite-preview-09-2025", "gemini/gemini-2.5-flash-preview-09-2025", "gemini/gemini-flash-latest", "gemini/gemini-flash-lite-latest", "gemini/gemini-2.5-flash-lite-preview-06-17", "gemini/gemini-2.5-flash-preview-04-17", "gemini/gemini-2.5-flash-preview-05-20", "gemini/gemini-2.5-flash-preview-tts", "gemini/gemini-2.5-pro", "gemini/gemini-2.5-computer-use-preview-10-2025", "gemini/gemini-3-pro-preview", "gemini/gemini-3-flash-preview", "gemini/gemini-2.5-pro-exp-03-25", "gemini/gemini-2.5-pro-preview-03-25", "gemini/gemini-2.5-pro-preview-05-06", "gemini/gemini-2.5-pro-preview-06-05", "gemini/gemini-2.5-pro-preview-tts", "gemini/gemini-exp-1114", "gemini/gemini-exp-1206", "gemini/gemini-gemma-2-27b-it", "gemini/gemini-gemma-2-9b-it", "gemini/gemini-pro", "gemini/gemini-pro-vision", "gemini/gemma-3-27b-it", "gemini/imagen-3.0-fast-generate-001", "gemini/imagen-3.0-generate-001", "gemini/imagen-3.0-generate-002", "gemini/imagen-4.0-fast-generate-001", "gemini/imagen-4.0-generate-001", "gemini/imagen-4.0-ultra-generate-001", "gemini/learnlm-1.5-pro-experimental", "gemini/veo-2.0-generate-001", "gemini/veo-3.0-fast-generate-preview", "gemini/veo-3.0-generate-preview", "gemini/veo-3.1-fast-generate-preview", "gemini/veo-3.1-generate-preview", "gemini/veo-3.1-fast-generate-001", "gemini/veo-3.1-generate-001"], "fireworks_ai": ["fireworks-ai-above-16b", "fireworks_ai/accounts/fireworks/models/deepseek-coder-v2-instruct", "fireworks_ai/accounts/fireworks/models/deepseek-r1", "fireworks_ai/accounts/fireworks/models/deepseek-r1-0528", "fireworks_ai/accounts/fireworks/models/deepseek-r1-basic", "fireworks_ai/accounts/fireworks/models/deepseek-v3", "fireworks_ai/accounts/fireworks/models/deepseek-v3-0324", "fireworks_ai/accounts/fireworks/models/deepseek-v3p1", "fireworks_ai/accounts/fireworks/models/deepseek-v3p1-terminus", "fireworks_ai/accounts/fireworks/models/deepseek-v3p2", "fireworks_ai/accounts/fireworks/models/firefunction-v2", "fireworks_ai/accounts/fireworks/models/glm-4p5", "fireworks_ai/accounts/fireworks/models/glm-4p5-air", "fireworks_ai/accounts/fireworks/models/glm-4p6", "fireworks_ai/accounts/fireworks/models/gpt-oss-120b", "fireworks_ai/accounts/fireworks/models/gpt-oss-20b", "fireworks_ai/accounts/fireworks/models/kimi-k2-instruct", "fireworks_ai/accounts/fireworks/models/kimi-k2-instruct-0905", "fireworks_ai/accounts/fireworks/models/kimi-k2-thinking", "fireworks_ai/accounts/fireworks/models/llama-v3p1-405b-instruct", "fireworks_ai/accounts/fireworks/models/llama-v3p1-8b-instruct", "fireworks_ai/accounts/fireworks/models/llama-v3p2-11b-vision-instruct", "fireworks_ai/accounts/fireworks/models/llama-v3p2-1b-instruct", "fireworks_ai/accounts/fireworks/models/llama-v3p2-3b-instruct", "fireworks_ai/accounts/fireworks/models/llama-v3p2-90b-vision-instruct", "fireworks_ai/accounts/fireworks/models/llama4-maverick-instruct-basic", "fireworks_ai/accounts/fireworks/models/llama4-scout-instruct-basic", "fireworks_ai/accounts/fireworks/models/mixtral-8x22b-instruct-hf", "fireworks_ai/accounts/fireworks/models/qwen2-72b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-32b-instruct", "fireworks_ai/accounts/fireworks/models/yi-large", "fireworks_ai/accounts/fireworks/models/qwen3-coder-480b-a35b-instruct", "fireworks_ai/accounts/fireworks/models/flux-kontext-pro", "fireworks_ai/accounts/fireworks/models/SSD-1B", "fireworks_ai/accounts/fireworks/models/chronos-hermes-13b-v2", "fireworks_ai/accounts/fireworks/models/code-llama-13b", "fireworks_ai/accounts/fireworks/models/code-llama-13b-instruct", "fireworks_ai/accounts/fireworks/models/code-llama-13b-python", "fireworks_ai/accounts/fireworks/models/code-llama-34b", "fireworks_ai/accounts/fireworks/models/code-llama-34b-instruct", "fireworks_ai/accounts/fireworks/models/code-llama-34b-python", "fireworks_ai/accounts/fireworks/models/code-llama-70b", "fireworks_ai/accounts/fireworks/models/code-llama-70b-instruct", "fireworks_ai/accounts/fireworks/models/code-llama-70b-python", "fireworks_ai/accounts/fireworks/models/code-llama-7b", "fireworks_ai/accounts/fireworks/models/code-llama-7b-instruct", "fireworks_ai/accounts/fireworks/models/code-llama-7b-python", "fireworks_ai/accounts/fireworks/models/code-qwen-1p5-7b", "fireworks_ai/accounts/fireworks/models/codegemma-2b", "fireworks_ai/accounts/fireworks/models/codegemma-7b", "fireworks_ai/accounts/fireworks/models/cogito-671b-v2-p1", "fireworks_ai/accounts/fireworks/models/cogito-v1-preview-llama-3b", "fireworks_ai/accounts/fireworks/models/cogito-v1-preview-llama-70b", "fireworks_ai/accounts/fireworks/models/cogito-v1-preview-llama-8b", "fireworks_ai/accounts/fireworks/models/cogito-v1-preview-qwen-14b", "fireworks_ai/accounts/fireworks/models/cogito-v1-preview-qwen-32b", "fireworks_ai/accounts/fireworks/models/flux-kontext-max", "fireworks_ai/accounts/fireworks/models/dbrx-instruct", "fireworks_ai/accounts/fireworks/models/deepseek-coder-1b-base", "fireworks_ai/accounts/fireworks/models/deepseek-coder-33b-instruct", "fireworks_ai/accounts/fireworks/models/deepseek-coder-7b-base", "fireworks_ai/accounts/fireworks/models/deepseek-coder-7b-base-v1p5", "fireworks_ai/accounts/fireworks/models/deepseek-coder-7b-instruct-v1p5", "fireworks_ai/accounts/fireworks/models/deepseek-coder-v2-lite-base", "fireworks_ai/accounts/fireworks/models/deepseek-coder-v2-lite-instruct", "fireworks_ai/accounts/fireworks/models/deepseek-prover-v2", "fireworks_ai/accounts/fireworks/models/deepseek-r1-0528-distill-qwen3-8b", "fireworks_ai/accounts/fireworks/models/deepseek-r1-distill-llama-70b", "fireworks_ai/accounts/fireworks/models/deepseek-r1-distill-llama-8b", "fireworks_ai/accounts/fireworks/models/deepseek-r1-distill-qwen-14b", "fireworks_ai/accounts/fireworks/models/deepseek-r1-distill-qwen-1p5b", "fireworks_ai/accounts/fireworks/models/deepseek-r1-distill-qwen-32b", "fireworks_ai/accounts/fireworks/models/deepseek-r1-distill-qwen-7b", "fireworks_ai/accounts/fireworks/models/deepseek-v2-lite-chat", "fireworks_ai/accounts/fireworks/models/deepseek-v2p5", "fireworks_ai/accounts/fireworks/models/devstral-small-2505", "fireworks_ai/accounts/fireworks/models/dobby-mini-unhinged-plus-llama-3-1-8b", "fireworks_ai/accounts/fireworks/models/dobby-unhinged-llama-3-3-70b-new", "fireworks_ai/accounts/fireworks/models/dolphin-2-9-2-qwen2-72b", "fireworks_ai/accounts/fireworks/models/dolphin-2p6-mixtral-8x7b", "fireworks_ai/accounts/fireworks/models/ernie-4p5-21b-a3b-pt", "fireworks_ai/accounts/fireworks/models/ernie-4p5-300b-a47b-pt", "fireworks_ai/accounts/fireworks/models/fare-20b", "fireworks_ai/accounts/fireworks/models/firefunction-v1", "fireworks_ai/accounts/fireworks/models/firellava-13b", "fireworks_ai/accounts/fireworks/models/firesearch-ocr-v6", "fireworks_ai/accounts/fireworks/models/fireworks-asr-large", "fireworks_ai/accounts/fireworks/models/fireworks-asr-v2", "fireworks_ai/accounts/fireworks/models/flux-1-dev", "fireworks_ai/accounts/fireworks/models/flux-1-dev-controlnet-union", "fireworks_ai/accounts/fireworks/models/flux-1-dev-fp8", "fireworks_ai/accounts/fireworks/models/flux-1-schnell", "fireworks_ai/accounts/fireworks/models/flux-1-schnell-fp8", "fireworks_ai/accounts/fireworks/models/gemma-2b-it", "fireworks_ai/accounts/fireworks/models/gemma-3-27b-it", "fireworks_ai/accounts/fireworks/models/gemma-7b", "fireworks_ai/accounts/fireworks/models/gemma-7b-it", "fireworks_ai/accounts/fireworks/models/gemma2-9b-it", "fireworks_ai/accounts/fireworks/models/glm-4p5v", "fireworks_ai/accounts/fireworks/models/gpt-oss-safeguard-120b", "fireworks_ai/accounts/fireworks/models/gpt-oss-safeguard-20b", "fireworks_ai/accounts/fireworks/models/hermes-2-pro-mistral-7b", "fireworks_ai/accounts/fireworks/models/internvl3-38b", "fireworks_ai/accounts/fireworks/models/internvl3-78b", "fireworks_ai/accounts/fireworks/models/internvl3-8b", "fireworks_ai/accounts/fireworks/models/japanese-stable-diffusion-xl", "fireworks_ai/accounts/fireworks/models/kat-coder", "fireworks_ai/accounts/fireworks/models/kat-dev-32b", "fireworks_ai/accounts/fireworks/models/kat-dev-72b-exp", "fireworks_ai/accounts/fireworks/models/llama-guard-2-8b", "fireworks_ai/accounts/fireworks/models/llama-guard-3-1b", "fireworks_ai/accounts/fireworks/models/llama-guard-3-8b", "fireworks_ai/accounts/fireworks/models/llama-v2-13b", "fireworks_ai/accounts/fireworks/models/llama-v2-13b-chat", "fireworks_ai/accounts/fireworks/models/llama-v2-70b", "fireworks_ai/accounts/fireworks/models/llama-v2-70b-chat", "fireworks_ai/accounts/fireworks/models/llama-v2-7b", "fireworks_ai/accounts/fireworks/models/llama-v2-7b-chat", "fireworks_ai/accounts/fireworks/models/llama-v3-70b-instruct", "fireworks_ai/accounts/fireworks/models/llama-v3-70b-instruct-hf", "fireworks_ai/accounts/fireworks/models/llama-v3-8b", "fireworks_ai/accounts/fireworks/models/llama-v3-8b-instruct-hf", "fireworks_ai/accounts/fireworks/models/llama-v3p1-405b-instruct-long", "fireworks_ai/accounts/fireworks/models/llama-v3p1-70b-instruct", "fireworks_ai/accounts/fireworks/models/llama-v3p1-70b-instruct-1b", "fireworks_ai/accounts/fireworks/models/llama-v3p1-nemotron-70b-instruct", "fireworks_ai/accounts/fireworks/models/llama-v3p2-1b", "fireworks_ai/accounts/fireworks/models/llama-v3p2-3b", "fireworks_ai/accounts/fireworks/models/llama-v3p3-70b-instruct", "fireworks_ai/accounts/fireworks/models/llamaguard-7b", "fireworks_ai/accounts/fireworks/models/llava-yi-34b", "fireworks_ai/accounts/fireworks/models/minimax-m1-80k", "fireworks_ai/accounts/fireworks/models/minimax-m2", "fireworks_ai/accounts/fireworks/models/ministral-3-14b-instruct-2512", "fireworks_ai/accounts/fireworks/models/ministral-3-3b-instruct-2512", "fireworks_ai/accounts/fireworks/models/ministral-3-8b-instruct-2512", "fireworks_ai/accounts/fireworks/models/mistral-7b", "fireworks_ai/accounts/fireworks/models/mistral-7b-instruct-4k", "fireworks_ai/accounts/fireworks/models/mistral-7b-instruct-v0p2", "fireworks_ai/accounts/fireworks/models/mistral-7b-instruct-v3", "fireworks_ai/accounts/fireworks/models/mistral-7b-v0p2", "fireworks_ai/accounts/fireworks/models/mistral-large-3-fp8", "fireworks_ai/accounts/fireworks/models/mistral-nemo-base-2407", "fireworks_ai/accounts/fireworks/models/mistral-nemo-instruct-2407", "fireworks_ai/accounts/fireworks/models/mistral-small-24b-instruct-2501", "fireworks_ai/accounts/fireworks/models/mixtral-8x22b", "fireworks_ai/accounts/fireworks/models/mixtral-8x22b-instruct", "fireworks_ai/accounts/fireworks/models/mixtral-8x7b", "fireworks_ai/accounts/fireworks/models/mixtral-8x7b-instruct", "fireworks_ai/accounts/fireworks/models/mixtral-8x7b-instruct-hf", "fireworks_ai/accounts/fireworks/models/mythomax-l2-13b", "fireworks_ai/accounts/fireworks/models/nemotron-nano-v2-12b-vl", "fireworks_ai/accounts/fireworks/models/nous-capybara-7b-v1p9", "fireworks_ai/accounts/fireworks/models/nous-hermes-2-mixtral-8x7b-dpo", "fireworks_ai/accounts/fireworks/models/nous-hermes-2-yi-34b", "fireworks_ai/accounts/fireworks/models/nous-hermes-llama2-13b", "fireworks_ai/accounts/fireworks/models/nous-hermes-llama2-70b", "fireworks_ai/accounts/fireworks/models/nous-hermes-llama2-7b", "fireworks_ai/accounts/fireworks/models/nvidia-nemotron-nano-12b-v2", "fireworks_ai/accounts/fireworks/models/nvidia-nemotron-nano-9b-v2", "fireworks_ai/accounts/fireworks/models/openchat-3p5-0106-7b", "fireworks_ai/accounts/fireworks/models/openhermes-2-mistral-7b", "fireworks_ai/accounts/fireworks/models/openhermes-2p5-mistral-7b", "fireworks_ai/accounts/fireworks/models/openorca-7b", "fireworks_ai/accounts/fireworks/models/phi-2-3b", "fireworks_ai/accounts/fireworks/models/phi-3-mini-128k-instruct", "fireworks_ai/accounts/fireworks/models/phi-3-vision-128k-instruct", "fireworks_ai/accounts/fireworks/models/phind-code-llama-34b-python-v1", "fireworks_ai/accounts/fireworks/models/phind-code-llama-34b-v1", "fireworks_ai/accounts/fireworks/models/phind-code-llama-34b-v2", "fireworks_ai/accounts/fireworks/models/playground-v2-1024px-aesthetic", "fireworks_ai/accounts/fireworks/models/playground-v2-5-1024px-aesthetic", "fireworks_ai/accounts/fireworks/models/pythia-12b", "fireworks_ai/accounts/fireworks/models/qwen-qwq-32b-preview", "fireworks_ai/accounts/fireworks/models/qwen-v2p5-14b-instruct", "fireworks_ai/accounts/fireworks/models/qwen-v2p5-7b", "fireworks_ai/accounts/fireworks/models/qwen1p5-72b-chat", "fireworks_ai/accounts/fireworks/models/qwen2-7b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2-vl-2b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2-vl-72b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2-vl-7b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-0p5b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-14b", "fireworks_ai/accounts/fireworks/models/qwen2p5-1p5b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-32b", "fireworks_ai/accounts/fireworks/models/qwen2p5-32b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-72b", "fireworks_ai/accounts/fireworks/models/qwen2p5-72b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-7b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-0p5b", "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-0p5b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-14b", "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-14b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-1p5b", "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-1p5b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-32b", "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-32b-instruct-128k", "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-32b-instruct-32k-rope", "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-32b-instruct-64k", "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-3b", "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-3b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-7b", "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-7b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-math-72b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-vl-32b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-vl-3b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-vl-72b-instruct", "fireworks_ai/accounts/fireworks/models/qwen2p5-vl-7b-instruct", "fireworks_ai/accounts/fireworks/models/qwen3-0p6b", "fireworks_ai/accounts/fireworks/models/qwen3-14b", "fireworks_ai/accounts/fireworks/models/qwen3-1p7b", "fireworks_ai/accounts/fireworks/models/qwen3-1p7b-fp8-draft", "fireworks_ai/accounts/fireworks/models/qwen3-1p7b-fp8-draft-131072", "fireworks_ai/accounts/fireworks/models/qwen3-1p7b-fp8-draft-40960", "fireworks_ai/accounts/fireworks/models/qwen3-235b-a22b", "fireworks_ai/accounts/fireworks/models/qwen3-235b-a22b-instruct-2507", "fireworks_ai/accounts/fireworks/models/qwen3-235b-a22b-thinking-2507", "fireworks_ai/accounts/fireworks/models/qwen3-30b-a3b", "fireworks_ai/accounts/fireworks/models/qwen3-30b-a3b-instruct-2507", "fireworks_ai/accounts/fireworks/models/qwen3-30b-a3b-thinking-2507", "fireworks_ai/accounts/fireworks/models/qwen3-32b", "fireworks_ai/accounts/fireworks/models/qwen3-4b", "fireworks_ai/accounts/fireworks/models/qwen3-4b-instruct-2507", "fireworks_ai/accounts/fireworks/models/qwen3-8b", "fireworks_ai/accounts/fireworks/models/qwen3-coder-30b-a3b-instruct", "fireworks_ai/accounts/fireworks/models/qwen3-coder-480b-instruct-bf16", "fireworks_ai/accounts/fireworks/models/qwen3-embedding-0p6b", "fireworks_ai/accounts/fireworks/models/qwen3-embedding-4b", "fireworks_ai/accounts/fireworks/models/", "fireworks_ai/accounts/fireworks/models/qwen3-next-80b-a3b-instruct", "fireworks_ai/accounts/fireworks/models/qwen3-next-80b-a3b-thinking", "fireworks_ai/accounts/fireworks/models/qwen3-reranker-0p6b", "fireworks_ai/accounts/fireworks/models/qwen3-reranker-4b", "fireworks_ai/accounts/fireworks/models/qwen3-reranker-8b", "fireworks_ai/accounts/fireworks/models/qwen3-vl-235b-a22b-instruct", "fireworks_ai/accounts/fireworks/models/qwen3-vl-235b-a22b-thinking", "fireworks_ai/accounts/fireworks/models/qwen3-vl-30b-a3b-instruct", "fireworks_ai/accounts/fireworks/models/qwen3-vl-30b-a3b-thinking", "fireworks_ai/accounts/fireworks/models/qwen3-vl-32b-instruct", "fireworks_ai/accounts/fireworks/models/qwen3-vl-8b-instruct", "fireworks_ai/accounts/fireworks/models/qwq-32b", "fireworks_ai/accounts/fireworks/models/rolm-ocr", "fireworks_ai/accounts/fireworks/models/snorkel-mistral-7b-pairrm-dpo", "fireworks_ai/accounts/fireworks/models/stable-diffusion-xl-1024-v1-0", "fireworks_ai/accounts/fireworks/models/stablecode-3b", "fireworks_ai/accounts/fireworks/models/starcoder-16b", "fireworks_ai/accounts/fireworks/models/starcoder-7b", "fireworks_ai/accounts/fireworks/models/starcoder2-15b", "fireworks_ai/accounts/fireworks/models/starcoder2-3b", "fireworks_ai/accounts/fireworks/models/starcoder2-7b", "fireworks_ai/accounts/fireworks/models/toppy-m-7b", "fireworks_ai/accounts/fireworks/models/whisper-v3", "fireworks_ai/accounts/fireworks/models/whisper-v3-turbo", "fireworks_ai/accounts/fireworks/models/yi-34b", "fireworks_ai/accounts/fireworks/models/yi-34b-200k-capybara", "fireworks_ai/accounts/fireworks/models/yi-34b-chat", "fireworks_ai/accounts/fireworks/models/yi-6b", "fireworks_ai/accounts/fireworks/models/zephyr-7b-beta", "fireworks_ai/WhereIsAI/UAE-Large-V1", "fireworks_ai/nomic-ai/nomic-embed-text-v1", "fireworks_ai/nomic-ai/nomic-embed-text-v1.5", "fireworks_ai/thenlper/gte-base", "fireworks_ai/thenlper/gte-large"], "aleph_alpha": ["luminous-base", "luminous-base-control", "luminous-extended", "luminous-extended-control", "luminous-supreme", "luminous-supreme-control"], "text-completion-codestral": ["text-completion-codestral/codestral-2405", "text-completion-codestral/codestral-latest"], "xai": ["xai/grok-2", "xai/grok-2-1212", "xai/grok-2-latest", "xai/grok-2-vision", "xai/grok-2-vision-1212", "xai/grok-2-vision-latest", "xai/grok-3", "xai/grok-3-beta", "xai/grok-3-fast-beta", "xai/grok-3-fast-latest", "xai/grok-3-latest", "xai/grok-3-mini", "xai/grok-3-mini-beta", "xai/grok-3-mini-fast", "xai/grok-3-mini-fast-beta", "xai/grok-3-mini-fast-latest", "xai/grok-3-mini-latest", "xai/grok-4", "xai/grok-4-fast-reasoning", "xai/grok-4-fast-non-reasoning", "xai/grok-4-0709", "xai/grok-4-latest", "xai/grok-4-1-fast", "xai/grok-4-1-fast-reasoning", "xai/grok-4-1-fast-reasoning-latest", "xai/grok-4-1-fast-non-reasoning", "xai/grok-4-1-fast-non-reasoning-latest", "xai/grok-beta", "xai/grok-code-fast", "xai/grok-code-fast-1", "xai/grok-code-fast-1-0825", "xai/grok-vision-beta"], "deepseek": ["deepseek-chat", "deepseek-reasoner", "deepseek/deepseek-chat", "deepseek/deepseek-coder", "deepseek/deepseek-r1", "deepseek/deepseek-reasoner", "deepseek/deepseek-v3", "deepseek/deepseek-v3.2"], "mistral": ["mistral/codestral-2405", "mistral/codestral-2508", "mistral/codestral-latest", "mistral/codestral-mamba-latest", "mistral/devstral-medium-2507", "mistral/devstral-small-2505", "mistral/devstral-small-2507", "mistral/labs-devstral-small-2512", "mistral/devstral-2512", "mistral/magistral-medium-2506", "mistral/magistral-medium-2509", "mistral/mistral-ocr-latest", "mistral/mistral-ocr-2505-completion", "mistral/magistral-medium-latest", "mistral/magistral-small-2506", "mistral/magistral-small-latest", "mistral/mistral-embed", "mistral/codestral-embed", "mistral/codestral-embed-2505", "mistral/mistral-large-2402", "mistral/mistral-large-2407", "mistral/mistral-large-2411", "mistral/mistral-large-latest", "mistral/mistral-large-3", "mistral/mistral-medium", "mistral/mistral-medium-2312", "mistral/mistral-medium-2505", "mistral/mistral-medium-latest", "mistral/mistral-small", "mistral/mistral-small-latest", "mistral/mistral-tiny", "mistral/open-codestral-mamba", "mistral/open-mistral-7b", "mistral/open-mistral-nemo", "mistral/open-mistral-nemo-2407", "mistral/open-mixtral-8x22b", "mistral/open-mixtral-8x7b", "mistral/pixtral-12b-2409", "mistral/pixtral-large-2411", "mistral/pixtral-large-latest"], "azure_ai": ["azure_ai/claude-haiku-4-5", "azure_ai/claude-opus-4-5", "azure_ai/claude-opus-4-1", "azure_ai/claude-sonnet-4-5", "azure_ai/gpt-oss-120b", "azure_ai/Cohere-embed-v3-english", "azure_ai/Cohere-embed-v3-multilingual", "azure_ai/FLUX-1.1-pro", "azure_ai/FLUX.1-Kontext-pro", "azure_ai/flux.2-pro", "azure_ai/Llama-3.2-11B-Vision-Instruct", "azure_ai/Llama-3.2-90B-Vision-Instruct", "azure_ai/Llama-3.3-70B-Instruct", "azure_ai/Llama-4-Maverick-17B-128E-Instruct-FP8", "azure_ai/Llama-4-Scout-17B-16E-Instruct", "azure_ai/Meta-Llama-3-70B-Instruct", "azure_ai/Meta-Llama-3.1-405B-Instruct", "azure_ai/Meta-Llama-3.1-70B-Instruct", "azure_ai/Meta-Llama-3.1-8B-Instruct", "azure_ai/Phi-3-medium-128k-instruct", "azure_ai/Phi-3-medium-4k-instruct", "azure_ai/Phi-3-mini-128k-instruct", "azure_ai/Phi-3-mini-4k-instruct", "azure_ai/Phi-3-small-128k-instruct", "azure_ai/Phi-3-small-8k-instruct", "azure_ai/Phi-3.5-MoE-instruct", "azure_ai/Phi-3.5-mini-instruct", "azure_ai/Phi-3.5-vision-instruct", "azure_ai/Phi-4", "azure_ai/Phi-4-mini-instruct", "azure_ai/Phi-4-multimodal-instruct", "azure_ai/Phi-4-mini-reasoning", "azure_ai/Phi-4-reasoning", "azure_ai/mistral-document-ai-2505", "azure_ai/doc-intelligence/prebuilt-read", "azure_ai/doc-intelligence/prebuilt-layout", "azure_ai/doc-intelligence/prebuilt-document", "azure_ai/MAI-DS-R1", "azure_ai/cohere-rerank-v3-english", "azure_ai/cohere-rerank-v3-multilingual", "azure_ai/cohere-rerank-v3.5", "azure_ai/cohere-rerank-v4.0-pro", "azure_ai/cohere-rerank-v4.0-fast", "azure_ai/deepseek-v3.2", "azure_ai/deepseek-v3.2-speciale", "azure_ai/deepseek-r1", "azure_ai/deepseek-v3", "azure_ai/deepseek-v3-0324", "azure_ai/embed-v-4-0", "azure_ai/global/grok-3", "azure_ai/global/grok-3-mini", "azure_ai/grok-3", "azure_ai/grok-3-mini", "azure_ai/grok-4", "azure_ai/grok-4-fast-non-reasoning", "azure_ai/grok-4-fast-reasoning", "azure_ai/grok-code-fast-1", "azure_ai/jais-30b-chat", "azure_ai/jamba-instruct", "azure_ai/ministral-3b", "azure_ai/mistral-large", "azure_ai/mistral-large-2407", "azure_ai/mistral-large-latest", "azure_ai/mistral-large-3", "azure_ai/mistral-medium-2505", "azure_ai/mistral-nemo", "azure_ai/mistral-small", "azure_ai/mistral-small-2503"], "voyage": ["voyage/rerank-2", "voyage/rerank-2-lite", "voyage/rerank-2.5", "voyage/rerank-2.5-lite", "voyage/voyage-2", "voyage/voyage-3", "voyage/voyage-3-large", "voyage/voyage-3-lite", "voyage/voyage-3.5", "voyage/voyage-3.5-lite", "voyage/voyage-code-2", "voyage/voyage-code-3", "voyage/voyage-context-3", "voyage/voyage-finance-2", "voyage/voyage-large-2", "voyage/voyage-law-2", "voyage/voyage-lite-01", "voyage/voyage-lite-02-instruct", "voyage/voyage-multimodal-3"], "infinity": [], "databricks": ["databricks/databricks-bge-large-en", "databricks/databricks-claude-3-7-sonnet", "databricks/databricks-claude-haiku-4-5", "databricks/databricks-claude-opus-4", "databricks/databricks-claude-opus-4-1", "databricks/databricks-claude-opus-4-5", "databricks/databricks-claude-sonnet-4", "databricks/databricks-claude-sonnet-4-1", "databricks/databricks-claude-sonnet-4-5", "databricks/databricks-gemini-2-5-flash", "databricks/databricks-gemini-2-5-pro", "databricks/databricks-gemma-3-12b", "databricks/databricks-gpt-5", "databricks/databricks-gpt-5-1", "databricks/databricks-gpt-5-mini", "databricks/databricks-gpt-5-nano", "databricks/databricks-gpt-oss-120b", "databricks/databricks-gpt-oss-20b", "databricks/databricks-gte-large-en", "databricks/databricks-llama-2-70b-chat", "databricks/databricks-llama-4-maverick", "databricks/databricks-meta-llama-3-1-405b-instruct", "databricks/databricks-meta-llama-3-1-8b-instruct", "databricks/databricks-meta-llama-3-3-70b-instruct", "databricks/databricks-meta-llama-3-70b-instruct", "databricks/databricks-mixtral-8x7b-instruct", "databricks/databricks-mpt-30b-instruct", "databricks/databricks-mpt-7b-instruct"], "cloudflare": ["cloudflare/@cf/meta/llama-2-7b-chat-fp16", "cloudflare/@cf/meta/llama-2-7b-chat-int8", "cloudflare/@cf/mistral/mistral-7b-instruct-v0.1", "cloudflare/@hf/thebloke/codellama-7b-instruct-awq"], "codestral": ["codestral/codestral-2405", "codestral/codestral-latest"], "nlp_cloud": ["chatdolphin", "dolphin"], "friendliai": ["friendliai/meta-llama-3.1-70b-instruct", "friendliai/meta-llama-3.1-8b-instruct"], "palm": ["palm/chat-bison", "palm/chat-bison-001", "palm/text-bison", "palm/text-bison-001", "palm/text-bison-safety-off", "palm/text-bison-safety-recitation-off"], "groq": ["groq/llama-3.1-8b-instant", "groq/llama-3.3-70b-versatile", "groq/gemma-7b-it", "groq/meta-llama/llama-guard-4-12b", "groq/meta-llama/llama-4-maverick-17b-128e-instruct", "groq/meta-llama/llama-4-scout-17b-16e-instruct", "groq/moonshotai/kimi-k2-instruct-0905", "groq/openai/gpt-oss-120b", "groq/openai/gpt-oss-20b", "groq/playai-tts", "groq/qwen/qwen3-32b", "groq/whisper-large-v3", "groq/whisper-large-v3-turbo"], "azure": ["azure/ada", "azure/codex-mini", "azure/command-r-plus", "azure/computer-use-preview", "azure/container", "azure/eu/gpt-4o-2024-08-06", "azure/eu/gpt-4o-2024-11-20", "azure/eu/gpt-4o-mini-2024-07-18", "azure/eu/gpt-4o-mini-realtime-preview-2024-12-17", "azure/eu/gpt-4o-realtime-preview-2024-10-01", "azure/eu/gpt-4o-realtime-preview-2024-12-17", "azure/eu/gpt-5-2025-08-07", "azure/eu/gpt-5-mini-2025-08-07", "azure/eu/gpt-5.1", "azure/eu/gpt-5.1-chat", "azure/eu/gpt-5.1-codex", "azure/eu/gpt-5.1-codex-mini", "azure/eu/gpt-5-nano-2025-08-07", "azure/eu/o1-2024-12-17", "azure/eu/o1-mini-2024-09-12", "azure/eu/o1-preview-2024-09-12", "azure/eu/o3-mini-2025-01-31", "azure/global-standard/gpt-4o-2024-08-06", "azure/global-standard/gpt-4o-2024-11-20", "azure/global-standard/gpt-4o-mini", "azure/global/gpt-4o-2024-08-06", "azure/global/gpt-4o-2024-11-20", "azure/global/gpt-5.1", "azure/global/gpt-5.1-chat", "azure/global/gpt-5.1-codex", "azure/global/gpt-5.1-codex-mini", "azure/gpt-3.5-turbo", "azure/gpt-3.5-turbo-0125", "azure/gpt-35-turbo", "azure/gpt-35-turbo-0125", "azure/gpt-35-turbo-0301", "azure/gpt-35-turbo-0613", "azure/gpt-35-turbo-1106", "azure/gpt-35-turbo-16k", "azure/gpt-35-turbo-16k-0613", "azure/gpt-4", "azure/gpt-4-0125-preview", "azure/gpt-4-0613", "azure/gpt-4-1106-preview", "azure/gpt-4-32k", "azure/gpt-4-32k-0613", "azure/gpt-4-turbo", "azure/gpt-4-turbo-2024-04-09", "azure/gpt-4-turbo-vision-preview", "azure/gpt-4.1", "azure/gpt-4.1-2025-04-14", "azure/gpt-4.1-mini", "azure/gpt-4.1-mini-2025-04-14", "azure/gpt-4.1-nano", "azure/gpt-4.1-nano-2025-04-14", "azure/gpt-4.5-preview", "azure/gpt-4o", "azure/gpt-4o-2024-05-13", "azure/gpt-4o-2024-08-06", "azure/gpt-4o-2024-11-20", "azure/gpt-audio-2025-08-28", "azure/gpt-audio-mini-2025-10-06", "azure/gpt-4o-audio-preview-2024-12-17", "azure/gpt-4o-mini", "azure/gpt-4o-mini-2024-07-18", "azure/gpt-4o-mini-audio-preview-2024-12-17", "azure/gpt-4o-mini-realtime-preview-2024-12-17", "azure/gpt-realtime-2025-08-28", "azure/gpt-realtime-mini-2025-10-06", "azure/gpt-4o-mini-transcribe", "azure/gpt-4o-mini-tts", "azure/gpt-4o-realtime-preview-2024-10-01", "azure/gpt-4o-realtime-preview-2024-12-17", "azure/gpt-4o-transcribe", "azure/gpt-4o-transcribe-diarize", "azure/gpt-5.1-2025-11-13", "azure/gpt-5.1-chat-2025-11-13", "azure/gpt-5.1-codex-2025-11-13", "azure/gpt-5.1-codex-mini-2025-11-13", "azure/gpt-5", "azure/gpt-5-2025-08-07", "azure/gpt-5-chat", "azure/gpt-5-chat-latest", "azure/gpt-5-codex", "azure/gpt-5-mini", "azure/gpt-5-mini-2025-08-07", "azure/gpt-5-nano", "azure/gpt-5-nano-2025-08-07", "azure/gpt-5-pro", "azure/gpt-5.1", "azure/gpt-5.1-chat", "azure/gpt-5.1-codex", "azure/gpt-5.1-codex-max", "azure/gpt-5.1-codex-mini", "azure/gpt-5.2", "azure/gpt-5.2-2025-12-11", "azure/gpt-5.2-chat", "azure/gpt-5.2-chat-2025-12-11", "azure/gpt-5.2-codex", "azure/gpt-5.2-pro", "azure/gpt-5.2-pro-2025-12-11", "azure/gpt-image-1", "azure/hd/1024-x-1024/dall-e-3", "azure/hd/1024-x-1792/dall-e-3", "azure/hd/1792-x-1024/dall-e-3", "azure/high/1024-x-1024/gpt-image-1", "azure/high/1024-x-1536/gpt-image-1", "azure/high/1536-x-1024/gpt-image-1", "azure/low/1024-x-1024/gpt-image-1", "azure/low/1024-x-1536/gpt-image-1", "azure/low/1536-x-1024/gpt-image-1", "azure/medium/1024-x-1024/gpt-image-1", "azure/medium/1024-x-1536/gpt-image-1", "azure/medium/1536-x-1024/gpt-image-1", "azure/gpt-image-1-mini", "azure/gpt-image-1.5", "azure/gpt-image-1.5-2025-12-16", "azure/low/1024-x-1024/gpt-image-1-mini", "azure/low/1024-x-1536/gpt-image-1-mini", "azure/low/1536-x-1024/gpt-image-1-mini", "azure/medium/1024-x-1024/gpt-image-1-mini", "azure/medium/1024-x-1536/gpt-image-1-mini", "azure/medium/1536-x-1024/gpt-image-1-mini", "azure/high/1024-x-1024/gpt-image-1-mini", "azure/high/1024-x-1536/gpt-image-1-mini", "azure/high/1536-x-1024/gpt-image-1-mini", "azure/mistral-large-2402", "azure/mistral-large-latest", "azure/o1", "azure/o1-2024-12-17", "azure/o1-mini", "azure/o1-mini-2024-09-12", "azure/o1-preview", "azure/o1-preview-2024-09-12", "azure/o3", "azure/o3-2025-04-16", "azure/o3-deep-research", "azure/o3-mini", "azure/o3-mini-2025-01-31", "azure/o3-pro", "azure/o3-pro-2025-06-10", "azure/o4-mini", "azure/o4-mini-2025-04-16", "azure/standard/1024-x-1024/dall-e-2", "azure/standard/1024-x-1024/dall-e-3", "azure/standard/1024-x-1792/dall-e-3", "azure/standard/1792-x-1024/dall-e-3", "azure/text-embedding-3-large", "azure/text-embedding-3-small", "azure/text-embedding-ada-002", "azure/speech/azure-tts", "azure/speech/azure-tts-hd", "azure/tts-1", "azure/tts-1-hd", "azure/us/gpt-4.1-2025-04-14", "azure/us/gpt-4.1-mini-2025-04-14", "azure/us/gpt-4.1-nano-2025-04-14", "azure/us/gpt-4o-2024-08-06", "azure/us/gpt-4o-2024-11-20", "azure/us/gpt-4o-mini-2024-07-18", "azure/us/gpt-4o-mini-realtime-preview-2024-12-17", "azure/us/gpt-4o-realtime-preview-2024-10-01", "azure/us/gpt-4o-realtime-preview-2024-12-17", "azure/us/gpt-5-2025-08-07", "azure/us/gpt-5-mini-2025-08-07", "azure/us/gpt-5-nano-2025-08-07", "azure/us/gpt-5.1", "azure/us/gpt-5.1-chat", "azure/us/gpt-5.1-codex", "azure/us/gpt-5.1-codex-mini", "azure/us/o1-2024-12-17", "azure/us/o1-mini-2024-09-12", "azure/us/o1-preview-2024-09-12", "azure/us/o3-2025-04-16", "azure/us/o3-mini-2025-01-31", "azure/us/o4-mini-2025-04-16", "azure/whisper-1", "computer-use-preview", "azure/sora-2", "azure/sora-2-pro", "azure/sora-2-pro-high-res", "azure/gpt-3.5-turbo-instruct-0914", "azure/gpt-35-turbo-instruct", "azure/gpt-35-turbo-instruct-0914"], "azure_text": ["azure/gpt-3.5-turbo-instruct-0914", "azure/gpt-35-turbo-instruct", "azure/gpt-35-turbo-instruct-0914"], "anyscale": ["anyscale/HuggingFaceH4/zephyr-7b-beta", "anyscale/codellama/CodeLlama-34b-Instruct-hf", "anyscale/codellama/CodeLlama-70b-Instruct-hf", "anyscale/google/gemma-7b-it", "anyscale/meta-llama/Llama-2-13b-chat-hf", "anyscale/meta-llama/Llama-2-70b-chat-hf", "anyscale/meta-llama/Llama-2-7b-chat-hf", "anyscale/meta-llama/Meta-Llama-3-70B-Instruct", "anyscale/meta-llama/Meta-Llama-3-8B-Instruct", "anyscale/mistralai/Mistral-7B-Instruct-v0.1", "anyscale/mistralai/Mixtral-8x22B-Instruct-v0.1", "anyscale/mistralai/Mixtral-8x7B-Instruct-v0.1"], "cerebras": ["cerebras/llama-3.3-70b", "cerebras/llama3.1-70b", "cerebras/llama3.1-8b", "cerebras/gpt-oss-120b", "cerebras/qwen-3-32b", "cerebras/zai-glm-4.6", "cerebras/zai-glm-4.7"], "galadriel": [], "sambanova": ["sambanova/DeepSeek-R1", "sambanova/DeepSeek-R1-Distill-Llama-70B", "sambanova/DeepSeek-V3-0324", "sambanova/Llama-4-Maverick-17B-128E-Instruct", "sambanova/Llama-4-Scout-17B-16E-Instruct", "sambanova/Meta-Llama-3.1-405B-Instruct", "sambanova/Meta-Llama-3.1-8B-Instruct", "sambanova/Meta-Llama-3.2-1B-Instruct", "sambanova/Meta-Llama-3.2-3B-Instruct", "sambanova/Meta-Llama-3.3-70B-Instruct", "sambanova/Meta-Llama-Guard-3-8B", "sambanova/QwQ-32B", "sambanova/Qwen2-Audio-7B-Instruct", "sambanova/Qwen3-32B", "sambanova/DeepSeek-V3.1", "sambanova/gpt-oss-120b"], "novita": ["novita/deepseek/deepseek-v3.2", "novita/minimax/minimax-m2.1", "novita/zai-org/glm-4.7", "novita/xiaomimimo/mimo-v2-flash", "novita/zai-org/autoglm-phone-9b-multilingual", "novita/moonshotai/kimi-k2-thinking", "novita/minimax/minimax-m2", "novita/paddlepaddle/paddleocr-vl", "novita/deepseek/deepseek-v3.2-exp", "novita/qwen/qwen3-vl-235b-a22b-thinking", "novita/zai-org/glm-4.6v", "novita/zai-org/glm-4.6", "novita/kwaipilot/kat-coder-pro", "novita/qwen/qwen3-next-80b-a3b-instruct", "novita/qwen/qwen3-next-80b-a3b-thinking", "novita/deepseek/deepseek-ocr", "novita/deepseek/deepseek-v3.1-terminus", "novita/qwen/qwen3-vl-235b-a22b-instruct", "novita/qwen/qwen3-max", "novita/skywork/r1v4-lite", "novita/deepseek/deepseek-v3.1", "novita/moonshotai/kimi-k2-0905", "novita/qwen/qwen3-coder-480b-a35b-instruct", "novita/qwen/qwen3-coder-30b-a3b-instruct", "novita/openai/gpt-oss-120b", "novita/moonshotai/kimi-k2-instruct", "novita/deepseek/deepseek-v3-0324", "novita/zai-org/glm-4.5", "novita/qwen/qwen3-235b-a22b-thinking-2507", "novita/meta-llama/llama-3.1-8b-instruct", "novita/google/gemma-3-12b-it", "novita/zai-org/glm-4.5v", "novita/openai/gpt-oss-20b", "novita/qwen/qwen3-235b-a22b-instruct-2507", "novita/deepseek/deepseek-r1-distill-qwen-14b", "novita/meta-llama/llama-3.3-70b-instruct", "novita/qwen/qwen-2.5-72b-instruct", "novita/mistralai/mistral-nemo", "novita/minimaxai/minimax-m1-80k", "novita/deepseek/deepseek-r1-0528", "novita/deepseek/deepseek-r1-distill-qwen-32b", "novita/meta-llama/llama-3-8b-instruct", "novita/microsoft/wizardlm-2-8x22b", "novita/deepseek/deepseek-r1-0528-qwen3-8b", "novita/deepseek/deepseek-r1-distill-llama-70b", "novita/meta-llama/llama-3-70b-instruct", "novita/qwen/qwen3-235b-a22b-fp8", "novita/meta-llama/llama-4-maverick-17b-128e-instruct-fp8", "novita/meta-llama/llama-4-scout-17b-16e-instruct", "novita/nousresearch/hermes-2-pro-llama-3-8b", "novita/qwen/qwen2.5-vl-72b-instruct", "novita/sao10k/l3-70b-euryale-v2.1", "novita/baidu/ernie-4.5-21B-a3b-thinking", "novita/sao10k/l3-8b-lunaris", "novita/baichuan/baichuan-m2-32b", "novita/baidu/ernie-4.5-vl-424b-a47b", "novita/baidu/ernie-4.5-300b-a47b-paddle", "novita/deepseek/deepseek-prover-v2-671b", "novita/qwen/qwen3-32b-fp8", "novita/qwen/qwen3-30b-a3b-fp8", "novita/google/gemma-3-27b-it", "novita/deepseek/deepseek-v3-turbo", "novita/deepseek/deepseek-r1-turbo", "novita/Sao10K/L3-8B-Stheno-v3.2", "novita/gryphe/mythomax-l2-13b", "novita/baidu/ernie-4.5-vl-28b-a3b-thinking", "novita/qwen/qwen3-vl-8b-instruct", "novita/zai-org/glm-4.5-air", "novita/qwen/qwen3-vl-30b-a3b-instruct", "novita/qwen/qwen3-vl-30b-a3b-thinking", "novita/qwen/qwen3-omni-30b-a3b-thinking", "novita/qwen/qwen3-omni-30b-a3b-instruct", "novita/qwen/qwen-mt-plus", "novita/baidu/ernie-4.5-vl-28b-a3b", "novita/baidu/ernie-4.5-21B-a3b", "novita/qwen/qwen3-8b-fp8", "novita/qwen/qwen3-4b-fp8", "novita/qwen/qwen2.5-7b-instruct", "novita/meta-llama/llama-3.2-3b-instruct", "novita/sao10k/l31-70b-euryale-v2.2", "novita/qwen/qwen3-embedding-0.6b", "novita/qwen/qwen3-embedding-8b", "novita/baai/bge-m3", "novita/qwen/qwen3-reranker-8b", "novita/baai/bge-reranker-v2-m3"], "nebius": [], "assemblyai": ["assemblyai/best", "assemblyai/nano"], "jina_ai": ["jina-reranker-v2-base-multilingual"], "snowflake": ["snowflake/claude-3-5-sonnet", "snowflake/deepseek-r1", "snowflake/gemma-7b", "snowflake/jamba-1.5-large", "snowflake/jamba-1.5-mini", "snowflake/jamba-instruct", "snowflake/llama2-70b-chat", "snowflake/llama3-70b", "snowflake/llama3-8b", "snowflake/llama3.1-405b", "snowflake/llama3.1-70b", "snowflake/llama3.1-8b", "snowflake/llama3.2-1b", "snowflake/llama3.2-3b", "snowflake/llama3.3-70b", "snowflake/mistral-7b", "snowflake/mistral-large", "snowflake/mistral-large2", "snowflake/mixtral-8x7b", "snowflake/reka-core", "snowflake/reka-flash", "snowflake/snowflake-arctic", "snowflake/snowflake-llama-3.1-405b", "snowflake/snowflake-llama-3.3-70b"], "meta_llama": ["meta_llama/Llama-3.3-70B-Instruct", "meta_llama/Llama-3.3-8B-Instruct", "meta_llama/Llama-4-Maverick-17B-128E-Instruct-FP8", "meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8"], "nscale": ["nscale/Qwen/QwQ-32B", "nscale/Qwen/Qwen2.5-Coder-32B-Instruct", "nscale/Qwen/Qwen2.5-Coder-3B-Instruct", "nscale/Qwen/Qwen2.5-Coder-7B-Instruct", "nscale/black-forest-labs/FLUX.1-schnell", "nscale/deepseek-ai/DeepSeek-R1-Distill-Llama-70B", "nscale/deepseek-ai/DeepSeek-R1-Distill-Llama-8B", "nscale/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B", "nscale/deepseek-ai/DeepSeek-R1-Distill-Qwen-14B", "nscale/deepseek-ai/DeepSeek-R1-Distill-Qwen-32B", "nscale/deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", "nscale/meta-llama/Llama-3.1-8B-Instruct", "nscale/meta-llama/Llama-3.3-70B-Instruct", "nscale/meta-llama/Llama-4-Scout-17B-16E-Instruct", "nscale/mistralai/mixtral-8x22b-instruct-v0.1", "nscale/stabilityai/stable-diffusion-xl-base-1.0"], "featherless_ai": ["featherless_ai/featherless-ai/Qwerky-72B", "featherless_ai/featherless-ai/Qwerky-QwQ-32B"], "deepgram": ["deepgram/base", "deepgram/base-conversationalai", "deepgram/base-finance", "deepgram/base-general", "deepgram/base-meeting", "deepgram/base-phonecall", "deepgram/base-video", "deepgram/base-voicemail", "deepgram/enhanced", "deepgram/enhanced-finance", "deepgram/enhanced-general", "deepgram/enhanced-meeting", "deepgram/enhanced-phonecall", "deepgram/nova", "deepgram/nova-2", "deepgram/nova-2-atc", "deepgram/nova-2-automotive", "deepgram/nova-2-conversationalai", "deepgram/nova-2-drivethru", "deepgram/nova-2-finance", "deepgram/nova-2-general", "deepgram/nova-2-meeting", "deepgram/nova-2-phonecall", "deepgram/nova-2-video", "deepgram/nova-2-voicemail", "deepgram/nova-3", "deepgram/nova-3-general", "deepgram/nova-3-medical", "deepgram/nova-general", "deepgram/nova-phonecall", "deepgram/whisper", "deepgram/whisper-base", "deepgram/whisper-large", "deepgram/whisper-medium", "deepgram/whisper-small", "deepgram/whisper-tiny"]}, "model_info": {"1024-x-1024/dall-e-2": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "256-x-256/dall-e-2": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "512-x-512/dall-e-2": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "chatgpt-4o-latest": {"max_tokens": 4096, "input_cost": 5e-06, "output_cost": 1.5e-05}, "gpt-4o-transcribe-diarize": {"max_tokens": 16000, "input_cost": 2.5e-06, "output_cost": 1e-05}, "codex-mini-latest": {"max_tokens": 100000, "input_cost": 1.5e-06, "output_cost": 6e-06}, "dall-e-2": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "dall-e-3": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "gpt-3.5-turbo": {"max_tokens": 4096, "input_cost": 5e-07, "output_cost": 1.5e-06}, "gpt-3.5-turbo-0125": {"max_tokens": 4096, "input_cost": 5e-07, "output_cost": 1.5e-06}, "gpt-3.5-turbo-0301": {"max_tokens": 4096, "input_cost": 1.5e-06, "output_cost": 2e-06}, "gpt-3.5-turbo-0613": {"max_tokens": 4096, "input_cost": 1.5e-06, "output_cost": 2e-06}, "gpt-3.5-turbo-1106": {"max_tokens": 4096, "input_cost": 1e-06, "output_cost": 2e-06}, "gpt-3.5-turbo-16k": {"max_tokens": 4096, "input_cost": 3e-06, "output_cost": 4e-06}, "gpt-3.5-turbo-16k-0613": {"max_tokens": 4096, "input_cost": 3e-06, "output_cost": 4e-06}, "gpt-4": {"max_tokens": 4096, "input_cost": 3e-05, "output_cost": 6e-05}, "gpt-4-0125-preview": {"max_tokens": 4096, "input_cost": 1e-05, "output_cost": 3e-05}, "gpt-4-0314": {"max_tokens": 4096, "input_cost": 3e-05, "output_cost": 6e-05}, "gpt-4-0613": {"max_tokens": 4096, "input_cost": 3e-05, "output_cost": 6e-05}, "gpt-4-1106-preview": {"max_tokens": 4096, "input_cost": 1e-05, "output_cost": 3e-05}, "gpt-4-1106-vision-preview": {"max_tokens": 4096, "input_cost": 1e-05, "output_cost": 3e-05}, "gpt-4-32k": {"max_tokens": 4096, "input_cost": 6e-05, "output_cost": 0.00012}, "gpt-4-32k-0314": {"max_tokens": 4096, "input_cost": 6e-05, "output_cost": 0.00012}, "gpt-4-32k-0613": {"max_tokens": 4096, "input_cost": 6e-05, "output_cost": 0.00012}, "gpt-4-turbo": {"max_tokens": 4096, "input_cost": 1e-05, "output_cost": 3e-05}, "gpt-4-turbo-2024-04-09": {"max_tokens": 4096, "input_cost": 1e-05, "output_cost": 3e-05}, "gpt-4-turbo-preview": {"max_tokens": 4096, "input_cost": 1e-05, "output_cost": 3e-05}, "gpt-4-vision-preview": {"max_tokens": 4096, "input_cost": 1e-05, "output_cost": 3e-05}, "gpt-4.1": {"max_tokens": 32768, "input_cost": 2e-06, "output_cost": 8e-06}, "gpt-4.1-2025-04-14": {"max_tokens": 32768, "input_cost": 2e-06, "output_cost": 8e-06}, "gpt-4.1-mini": {"max_tokens": 32768, "input_cost": 4e-07, "output_cost": 1.6e-06}, "gpt-4.1-mini-2025-04-14": {"max_tokens": 32768, "input_cost": 4e-07, "output_cost": 1.6e-06}, "gpt-4.1-nano": {"max_tokens": 32768, "input_cost": 1e-07, "output_cost": 4e-07}, "gpt-4.1-nano-2025-04-14": {"max_tokens": 32768, "input_cost": 1e-07, "output_cost": 4e-07}, "gpt-4.5-preview": {"max_tokens": 16384, "input_cost": 7.5e-05, "output_cost": 0.00015}, "gpt-4.5-preview-2025-02-27": {"max_tokens": 16384, "input_cost": 7.5e-05, "output_cost": 0.00015}, "gpt-4o": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "gpt-4o-2024-05-13": {"max_tokens": 4096, "input_cost": 5e-06, "output_cost": 1.5e-05}, "gpt-4o-2024-08-06": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "gpt-4o-2024-11-20": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "gpt-4o-audio-preview": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "gpt-4o-audio-preview-2024-10-01": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "gpt-4o-audio-preview-2024-12-17": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "gpt-4o-audio-preview-2025-06-03": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "gpt-4o-mini": {"max_tokens": 16384, "input_cost": 1.5e-07, "output_cost": 6e-07}, "gpt-4o-mini-2024-07-18": {"max_tokens": 16384, "input_cost": 1.5e-07, "output_cost": 6e-07}, "gpt-4o-mini-audio-preview": {"max_tokens": 16384, "input_cost": 1.5e-07, "output_cost": 6e-07}, "gpt-4o-mini-audio-preview-2024-12-17": {"max_tokens": 16384, "input_cost": 1.5e-07, "output_cost": 6e-07}, "gpt-4o-mini-realtime-preview": {"max_tokens": 4096, "input_cost": 6e-07, "output_cost": 2.4e-06}, "gpt-4o-mini-realtime-preview-2024-12-17": {"max_tokens": 4096, "input_cost": 6e-07, "output_cost": 2.4e-06}, "gpt-4o-mini-search-preview": {"max_tokens": 16384, "input_cost": 1.5e-07, "output_cost": 6e-07}, "gpt-4o-mini-search-preview-2025-03-11": {"max_tokens": 16384, "input_cost": 1.5e-07, "output_cost": 6e-07}, "gpt-4o-mini-transcribe": {"max_tokens": 16000, "input_cost": 1.25e-06, "output_cost": 5e-06}, "gpt-4o-mini-tts": {"max_tokens": 0, "input_cost": 2.5e-06, "output_cost": 1e-05}, "gpt-4o-realtime-preview": {"max_tokens": 4096, "input_cost": 5e-06, "output_cost": 2e-05}, "gpt-4o-realtime-preview-2024-10-01": {"max_tokens": 4096, "input_cost": 5e-06, "output_cost": 2e-05}, "gpt-4o-realtime-preview-2024-12-17": {"max_tokens": 4096, "input_cost": 5e-06, "output_cost": 2e-05}, "gpt-4o-realtime-preview-2025-06-03": {"max_tokens": 4096, "input_cost": 5e-06, "output_cost": 2e-05}, "gpt-4o-search-preview": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "gpt-4o-search-preview-2025-03-11": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "gpt-4o-transcribe": {"max_tokens": 16000, "input_cost": 2.5e-06, "output_cost": 1e-05}, "gpt-image-1.5": {"max_tokens": 0, "input_cost": 5e-06, "output_cost": 1e-05}, "gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 5e-06, "output_cost": 1e-05}, "low/1024-x-1024/gpt-image-1.5": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "low/1024-x-1536/gpt-image-1.5": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "low/1536-x-1024/gpt-image-1.5": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "medium/1024-x-1024/gpt-image-1.5": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "medium/1024-x-1536/gpt-image-1.5": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "medium/1536-x-1024/gpt-image-1.5": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "high/1024-x-1024/gpt-image-1.5": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "high/1024-x-1536/gpt-image-1.5": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "high/1536-x-1024/gpt-image-1.5": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "standard/1024-x-1024/gpt-image-1.5": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "standard/1024-x-1536/gpt-image-1.5": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "standard/1536-x-1024/gpt-image-1.5": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "1024-x-1024/gpt-image-1.5": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "1024-x-1536/gpt-image-1.5": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "1536-x-1024/gpt-image-1.5": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "low/1024-x-1024/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "low/1024-x-1536/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "low/1536-x-1024/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "medium/1024-x-1024/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "medium/1024-x-1536/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "medium/1536-x-1024/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "high/1024-x-1024/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "high/1024-x-1536/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "high/1536-x-1024/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "standard/1024-x-1024/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "standard/1024-x-1536/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "standard/1536-x-1024/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "1024-x-1024/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "1024-x-1536/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "1536-x-1024/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "gpt-5": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gpt-5.1": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gpt-5.1-2025-11-13": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gpt-5.1-chat-latest": {"max_tokens": 16384, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gpt-5.2": {"max_tokens": 128000, "input_cost": 1.75e-06, "output_cost": 1.4e-05}, "gpt-5.2-2025-12-11": {"max_tokens": 128000, "input_cost": 1.75e-06, "output_cost": 1.4e-05}, "gpt-5.2-chat-latest": {"max_tokens": 16384, "input_cost": 1.75e-06, "output_cost": 1.4e-05}, "gpt-5.2-pro": {"max_tokens": 128000, "input_cost": 2.1e-05, "output_cost": 0.000168}, "gpt-5.2-pro-2025-12-11": {"max_tokens": 128000, "input_cost": 2.1e-05, "output_cost": 0.000168}, "gpt-5-pro": {"max_tokens": 272000, "input_cost": 1.5e-05, "output_cost": 0.00012}, "gpt-5-pro-2025-10-06": {"max_tokens": 272000, "input_cost": 1.5e-05, "output_cost": 0.00012}, "gpt-5-2025-08-07": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gpt-5-chat": {"max_tokens": 16384, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gpt-5-chat-latest": {"max_tokens": 16384, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gpt-5-codex": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gpt-5.1-codex": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gpt-5.1-codex-max": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gpt-5.1-codex-mini": {"max_tokens": 128000, "input_cost": 2.5e-07, "output_cost": 2e-06}, "gpt-5.2-codex": {"max_tokens": 128000, "input_cost": 1.75e-06, "output_cost": 1.4e-05}, "gpt-5-mini": {"max_tokens": 128000, "input_cost": 2.5e-07, "output_cost": 2e-06}, "gpt-5-mini-2025-08-07": {"max_tokens": 128000, "input_cost": 2.5e-07, "output_cost": 2e-06}, "gpt-5-nano": {"max_tokens": 128000, "input_cost": 5e-08, "output_cost": 4e-07}, "gpt-5-nano-2025-08-07": {"max_tokens": 128000, "input_cost": 5e-08, "output_cost": 4e-07}, "gpt-image-1": {"max_tokens": 0, "input_cost": 5e-06, "output_cost": 0}, "gpt-image-1-mini": {"max_tokens": 0, "input_cost": 2e-06, "output_cost": 0}, "gpt-realtime": {"max_tokens": 4096, "input_cost": 4e-06, "output_cost": 1.6e-05}, "gpt-realtime-mini": {"max_tokens": 4096, "input_cost": 6e-07, "output_cost": 2.4e-06}, "gpt-realtime-2025-08-28": {"max_tokens": 4096, "input_cost": 4e-06, "output_cost": 1.6e-05}, "hd/1024-x-1024/dall-e-3": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "hd/1024-x-1792/dall-e-3": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "hd/1792-x-1024/dall-e-3": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "high/1024-x-1024/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "high/1024-x-1536/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "high/1536-x-1024/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "low/1024-x-1024/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "low/1024-x-1536/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "low/1536-x-1024/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "medium/1024-x-1024/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "medium/1024-x-1536/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "medium/1536-x-1024/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "low/1024-x-1024/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "low/1024-x-1536/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "low/1536-x-1024/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "medium/1024-x-1024/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "medium/1024-x-1536/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "medium/1536-x-1024/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "o1": {"max_tokens": 100000, "input_cost": 1.5e-05, "output_cost": 6e-05}, "o1-2024-12-17": {"max_tokens": 100000, "input_cost": 1.5e-05, "output_cost": 6e-05}, "o1-mini": {"max_tokens": 65536, "input_cost": 1.1e-06, "output_cost": 4.4e-06}, "o1-mini-2024-09-12": {"max_tokens": 65536, "input_cost": 3e-06, "output_cost": 1.2e-05}, "o1-preview": {"max_tokens": 32768, "input_cost": 1.5e-05, "output_cost": 6e-05}, "o1-preview-2024-09-12": {"max_tokens": 32768, "input_cost": 1.5e-05, "output_cost": 6e-05}, "o1-pro": {"max_tokens": 100000, "input_cost": 0.00015, "output_cost": 0.0006}, "o1-pro-2025-03-19": {"max_tokens": 100000, "input_cost": 0.00015, "output_cost": 0.0006}, "o3": {"max_tokens": 100000, "input_cost": 2e-06, "output_cost": 8e-06}, "o3-2025-04-16": {"max_tokens": 100000, "input_cost": 2e-06, "output_cost": 8e-06}, "o3-deep-research": {"max_tokens": 100000, "input_cost": 1e-05, "output_cost": 4e-05}, "o3-deep-research-2025-06-26": {"max_tokens": 100000, "input_cost": 1e-05, "output_cost": 4e-05}, "o3-mini": {"max_tokens": 100000, "input_cost": 1.1e-06, "output_cost": 4.4e-06}, "o3-mini-2025-01-31": {"max_tokens": 100000, "input_cost": 1.1e-06, "output_cost": 4.4e-06}, "o3-pro": {"max_tokens": 100000, "input_cost": 2e-05, "output_cost": 8e-05}, "o3-pro-2025-06-10": {"max_tokens": 100000, "input_cost": 2e-05, "output_cost": 8e-05}, "o4-mini": {"max_tokens": 100000, "input_cost": 1.1e-06, "output_cost": 4.4e-06}, "o4-mini-2025-04-16": {"max_tokens": 100000, "input_cost": 1.1e-06, "output_cost": 4.4e-06}, "o4-mini-deep-research": {"max_tokens": 100000, "input_cost": 2e-06, "output_cost": 8e-06}, "o4-mini-deep-research-2025-06-26": {"max_tokens": 100000, "input_cost": 2e-06, "output_cost": 8e-06}, "omni-moderation-2024-09-26": {"max_tokens": 32768, "input_cost": 0.0, "output_cost": 0.0}, "omni-moderation-latest": {"max_tokens": 32768, "input_cost": 0.0, "output_cost": 0.0}, "omni-moderation-latest-intents": {"max_tokens": 32768, "input_cost": 0.0, "output_cost": 0.0}, "standard/1024-x-1024/dall-e-3": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "standard/1024-x-1792/dall-e-3": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "standard/1792-x-1024/dall-e-3": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "text-embedding-3-large": {"max_tokens": 8191, "input_cost": 1.3e-07, "output_cost": 0.0}, "text-embedding-3-small": {"max_tokens": 8191, "input_cost": 2e-08, "output_cost": 0.0}, "text-embedding-ada-002": {"max_tokens": 8191, "input_cost": 1e-07, "output_cost": 0.0}, "text-embedding-ada-002-v2": {"max_tokens": 8191, "input_cost": 1e-07, "output_cost": 0.0}, "text-moderation-007": {"max_tokens": 32768, "input_cost": 0.0, "output_cost": 0.0}, "text-moderation-latest": {"max_tokens": 32768, "input_cost": 0.0, "output_cost": 0.0}, "text-moderation-stable": {"max_tokens": 32768, "input_cost": 0.0, "output_cost": 0.0}, "tts-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "tts-1-hd": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "whisper-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "openai/container": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "openai/sora-2": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "openai/sora-2-pro": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "babbage-002": {"max_tokens": 4096, "input_cost": 4e-07, "output_cost": 4e-07}, "davinci-002": {"max_tokens": 4096, "input_cost": 2e-06, "output_cost": 2e-06}, "ft:babbage-002": {"max_tokens": 4096, "input_cost": 1.6e-06, "output_cost": 1.6e-06}, "ft:davinci-002": {"max_tokens": 4096, "input_cost": 1.2e-05, "output_cost": 1.2e-05}, "gpt-3.5-turbo-instruct": {"max_tokens": 4096, "input_cost": 1.5e-06, "output_cost": 2e-06}, "gpt-3.5-turbo-instruct-0914": {"max_tokens": 4097, "input_cost": 1.5e-06, "output_cost": 2e-06}, "cohere/embed-v4.0": {"max_tokens": 128000, "input_cost": 1.2e-07, "output_cost": 0.0}, "command": {"max_tokens": 4096, "input_cost": 1e-06, "output_cost": 2e-06}, "command-nightly": {"max_tokens": 4096, "input_cost": 1e-06, "output_cost": 2e-06}, "embed-english-light-v2.0": {"max_tokens": 1024, "input_cost": 1e-07, "output_cost": 0.0}, "embed-english-light-v3.0": {"max_tokens": 1024, "input_cost": 1e-07, "output_cost": 0.0}, "embed-english-v2.0": {"max_tokens": 4096, "input_cost": 1e-07, "output_cost": 0.0}, "embed-english-v3.0": {"max_tokens": 1024, "input_cost": 1e-07, "output_cost": 0.0}, "embed-multilingual-v2.0": {"max_tokens": 768, "input_cost": 1e-07, "output_cost": 0.0}, "embed-multilingual-v3.0": {"max_tokens": 1024, "input_cost": 1e-07, "output_cost": 0.0}, "embed-multilingual-light-v3.0": {"max_tokens": 1024, "input_cost": 0.0001, "output_cost": 0.0}, "rerank-english-v2.0": {"max_tokens": 4096, "input_cost": 0.0, "output_cost": 0.0}, "rerank-english-v3.0": {"max_tokens": 4096, "input_cost": 0.0, "output_cost": 0.0}, "rerank-multilingual-v2.0": {"max_tokens": 4096, "input_cost": 0.0, "output_cost": 0.0}, "rerank-multilingual-v3.0": {"max_tokens": 4096, "input_cost": 0.0, "output_cost": 0.0}, "rerank-v3.5": {"max_tokens": 4096, "input_cost": 0.0, "output_cost": 0.0}, "command-a-03-2025": {"max_tokens": 8000, "input_cost": 2.5e-06, "output_cost": 1e-05}, "command-light": {"max_tokens": 4096, "input_cost": 3e-07, "output_cost": 6e-07}, "command-r": {"max_tokens": 4096, "input_cost": 1.5e-07, "output_cost": 6e-07}, "command-r-08-2024": {"max_tokens": 4096, "input_cost": 1.5e-07, "output_cost": 6e-07}, "command-r-plus": {"max_tokens": 4096, "input_cost": 2.5e-06, "output_cost": 1e-05}, "command-r-plus-08-2024": {"max_tokens": 4096, "input_cost": 2.5e-06, "output_cost": 1e-05}, "command-r7b-12-2024": {"max_tokens": 4096, "input_cost": 1.5e-07, "output_cost": 3.75e-08}, "claude-3-5-haiku-20241022": {"max_tokens": 8192, "input_cost": 8e-07, "output_cost": 4e-06}, "claude-3-5-haiku-latest": {"max_tokens": 8192, "input_cost": 1e-06, "output_cost": 5e-06}, "claude-haiku-4-5-20251001": {"max_tokens": 64000, "input_cost": 1e-06, "output_cost": 5e-06}, "claude-haiku-4-5": {"max_tokens": 64000, "input_cost": 1e-06, "output_cost": 5e-06}, "claude-3-5-sonnet-20240620": {"max_tokens": 8192, "input_cost": 3e-06, "output_cost": 1.5e-05}, "claude-3-5-sonnet-20241022": {"max_tokens": 8192, "input_cost": 3e-06, "output_cost": 1.5e-05}, "claude-3-5-sonnet-latest": {"max_tokens": 8192, "input_cost": 3e-06, "output_cost": 1.5e-05}, "claude-3-7-sonnet-20250219": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "claude-3-7-sonnet-latest": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "claude-3-haiku-20240307": {"max_tokens": 4096, "input_cost": 2.5e-07, "output_cost": 1.25e-06}, "claude-3-opus-20240229": {"max_tokens": 4096, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "claude-3-opus-latest": {"max_tokens": 4096, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "claude-4-opus-20250514": {"max_tokens": 32000, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "claude-4-sonnet-20250514": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "claude-sonnet-4-5": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "claude-sonnet-4-5-20250929": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "claude-opus-4-1": {"max_tokens": 32000, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "claude-opus-4-1-20250805": {"max_tokens": 32000, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "claude-opus-4-20250514": {"max_tokens": 32000, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "claude-opus-4-5-20251101": {"max_tokens": 64000, "input_cost": 5e-06, "output_cost": 2.5e-05}, "claude-opus-4-5": {"max_tokens": 64000, "input_cost": 5e-06, "output_cost": 2.5e-05}, "claude-sonnet-4-20250514": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "openrouter/anthropic/claude-2": {"max_tokens": 8191, "input_cost": 1.102e-05, "output_cost": 3.268e-05}, "openrouter/anthropic/claude-3-5-haiku": {"max_tokens": 200000, "input_cost": 1e-06, "output_cost": 5e-06}, "openrouter/anthropic/claude-3-5-haiku-20241022": {"max_tokens": 8192, "input_cost": 1e-06, "output_cost": 5e-06}, "openrouter/anthropic/claude-3-haiku": {"max_tokens": 200000, "input_cost": 2.5e-07, "output_cost": 1.25e-06}, "openrouter/anthropic/claude-3-haiku-20240307": {"max_tokens": 4096, "input_cost": 2.5e-07, "output_cost": 1.25e-06}, "openrouter/anthropic/claude-3-opus": {"max_tokens": 4096, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "openrouter/anthropic/claude-3-sonnet": {"max_tokens": 200000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "openrouter/anthropic/claude-3.5-sonnet": {"max_tokens": 8192, "input_cost": 3e-06, "output_cost": 1.5e-05}, "openrouter/anthropic/claude-3.5-sonnet:beta": {"max_tokens": 8192, "input_cost": 3e-06, "output_cost": 1.5e-05}, "openrouter/anthropic/claude-3.7-sonnet": {"max_tokens": 128000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "openrouter/anthropic/claude-3.7-sonnet:beta": {"max_tokens": 128000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "openrouter/anthropic/claude-instant-v1": {"max_tokens": 8191, "input_cost": 1.63e-06, "output_cost": 5.51e-06}, "openrouter/anthropic/claude-opus-4": {"max_tokens": 32000, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "openrouter/anthropic/claude-opus-4.1": {"max_tokens": 32000, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "openrouter/anthropic/claude-sonnet-4": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "openrouter/anthropic/claude-opus-4.5": {"max_tokens": 32000, "input_cost": 5e-06, "output_cost": 2.5e-05}, "openrouter/anthropic/claude-sonnet-4.5": {"max_tokens": 1000000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "openrouter/anthropic/claude-haiku-4.5": {"max_tokens": 200000, "input_cost": 1e-06, "output_cost": 5e-06}, "openrouter/bytedance/ui-tars-1.5-7b": {"max_tokens": 2048, "input_cost": 1e-07, "output_cost": 2e-07}, "openrouter/cognitivecomputations/dolphin-mixtral-8x7b": {"max_tokens": 32769, "input_cost": 5e-07, "output_cost": 5e-07}, "openrouter/cohere/command-r-plus": {"max_tokens": 128000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "openrouter/databricks/dbrx-instruct": {"max_tokens": 32768, "input_cost": 6e-07, "output_cost": 6e-07}, "openrouter/deepseek/deepseek-chat": {"max_tokens": 8192, "input_cost": 1.4e-07, "output_cost": 2.8e-07}, "openrouter/deepseek/deepseek-chat-v3-0324": {"max_tokens": 8192, "input_cost": 1.4e-07, "output_cost": 2.8e-07}, "openrouter/deepseek/deepseek-chat-v3.1": {"max_tokens": 163840, "input_cost": 2e-07, "output_cost": 8e-07}, "openrouter/deepseek/deepseek-v3.2": {"max_tokens": 163840, "input_cost": 2.8e-07, "output_cost": 4e-07}, "openrouter/deepseek/deepseek-v3.2-exp": {"max_tokens": 163840, "input_cost": 2e-07, "output_cost": 4e-07}, "openrouter/deepseek/deepseek-coder": {"max_tokens": 4096, "input_cost": 1.4e-07, "output_cost": 2.8e-07}, "openrouter/deepseek/deepseek-r1": {"max_tokens": 8192, "input_cost": 5.5e-07, "output_cost": 2.19e-06}, "openrouter/deepseek/deepseek-r1-0528": {"max_tokens": 8192, "input_cost": 5e-07, "output_cost": 2.15e-06}, "openrouter/fireworks/firellava-13b": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "openrouter/google/gemini-2.0-flash-001": {"max_tokens": 8192, "input_cost": 1e-07, "output_cost": 4e-07}, "openrouter/google/gemini-2.5-flash": {"max_tokens": 8192, "input_cost": 3e-07, "output_cost": 2.5e-06}, "openrouter/google/gemini-2.5-pro": {"max_tokens": 8192, "input_cost": 1.25e-06, "output_cost": 1e-05}, "openrouter/google/gemini-3-pro-preview": {"max_tokens": 65535, "input_cost": 2e-06, "output_cost": 1.2e-05}, "openrouter/google/gemini-3-flash-preview": {"max_tokens": 65535, "input_cost": 5e-07, "output_cost": 3e-06}, "openrouter/google/gemini-pro-1.5": {"max_tokens": 8192, "input_cost": 2.5e-06, "output_cost": 7.5e-06}, "openrouter/google/gemini-pro-vision": {"max_tokens": 45875, "input_cost": 1.25e-07, "output_cost": 3.75e-07}, "openrouter/google/palm-2-chat-bison": {"max_tokens": 25804, "input_cost": 5e-07, "output_cost": 5e-07}, "openrouter/google/palm-2-codechat-bison": {"max_tokens": 20070, "input_cost": 5e-07, "output_cost": 5e-07}, "openrouter/gryphe/mythomax-l2-13b": {"max_tokens": 8192, "input_cost": 1.875e-06, "output_cost": 1.875e-06}, "openrouter/jondurbin/airoboros-l2-70b-2.1": {"max_tokens": 4096, "input_cost": 1.3875e-05, "output_cost": 1.3875e-05}, "openrouter/mancer/weaver": {"max_tokens": 8000, "input_cost": 5.625e-06, "output_cost": 5.625e-06}, "openrouter/meta-llama/codellama-34b-instruct": {"max_tokens": 8192, "input_cost": 5e-07, "output_cost": 5e-07}, "openrouter/meta-llama/llama-2-13b-chat": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "openrouter/meta-llama/llama-2-70b-chat": {"max_tokens": 4096, "input_cost": 1.5e-06, "output_cost": 1.5e-06}, "openrouter/meta-llama/llama-3-70b-instruct": {"max_tokens": 8192, "input_cost": 5.9e-07, "output_cost": 7.9e-07}, "openrouter/meta-llama/llama-3-70b-instruct:nitro": {"max_tokens": 8192, "input_cost": 9e-07, "output_cost": 9e-07}, "openrouter/meta-llama/llama-3-8b-instruct:extended": {"max_tokens": 16384, "input_cost": 2.25e-07, "output_cost": 2.25e-06}, "openrouter/meta-llama/llama-3-8b-instruct:free": {"max_tokens": 8192, "input_cost": 0.0, "output_cost": 0.0}, "openrouter/microsoft/wizardlm-2-8x22b:nitro": {"max_tokens": 65536, "input_cost": 1e-06, "output_cost": 1e-06}, "openrouter/minimax/minimax-m2": {"max_tokens": 204800, "input_cost": 2.55e-07, "output_cost": 1.02e-06}, "openrouter/mistralai/devstral-2512:free": {"max_tokens": 262144, "input_cost": 0, "output_cost": 0}, "openrouter/mistralai/devstral-2512": {"max_tokens": 65536, "input_cost": 1.5e-07, "output_cost": 6e-07}, "openrouter/mistralai/ministral-3b-2512": {"max_tokens": 131072, "input_cost": 1e-07, "output_cost": 1e-07}, "openrouter/mistralai/ministral-8b-2512": {"max_tokens": 262144, "input_cost": 1.5e-07, "output_cost": 1.5e-07}, "openrouter/mistralai/ministral-14b-2512": {"max_tokens": 262144, "input_cost": 2e-07, "output_cost": 2e-07}, "openrouter/mistralai/mistral-large-2512": {"max_tokens": 262144, "input_cost": 5e-07, "output_cost": 1.5e-06}, "openrouter/mistralai/mistral-7b-instruct": {"max_tokens": 8192, "input_cost": 1.3e-07, "output_cost": 1.3e-07}, "openrouter/mistralai/mistral-7b-instruct:free": {"max_tokens": 8192, "input_cost": 0.0, "output_cost": 0.0}, "openrouter/mistralai/mistral-large": {"max_tokens": 32000, "input_cost": 8e-06, "output_cost": 2.4e-05}, "openrouter/mistralai/mistral-small-3.1-24b-instruct": {"max_tokens": 32000, "input_cost": 1e-07, "output_cost": 3e-07}, "openrouter/mistralai/mistral-small-3.2-24b-instruct": {"max_tokens": 32000, "input_cost": 1e-07, "output_cost": 3e-07}, "openrouter/mistralai/mixtral-8x22b-instruct": {"max_tokens": 65536, "input_cost": 6.5e-07, "output_cost": 6.5e-07}, "openrouter/nousresearch/nous-hermes-llama2-13b": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "openrouter/openai/gpt-3.5-turbo": {"max_tokens": 4095, "input_cost": 1.5e-06, "output_cost": 2e-06}, "openrouter/openai/gpt-3.5-turbo-16k": {"max_tokens": 16383, "input_cost": 3e-06, "output_cost": 4e-06}, "openrouter/openai/gpt-4": {"max_tokens": 8192, "input_cost": 3e-05, "output_cost": 6e-05}, "openrouter/openai/gpt-4-vision-preview": {"max_tokens": 130000, "input_cost": 1e-05, "output_cost": 3e-05}, "openrouter/openai/gpt-4.1": {"max_tokens": 32768, "input_cost": 2e-06, "output_cost": 8e-06}, "openrouter/openai/gpt-4.1-2025-04-14": {"max_tokens": 32768, "input_cost": 2e-06, "output_cost": 8e-06}, "openrouter/openai/gpt-4.1-mini": {"max_tokens": 32768, "input_cost": 4e-07, "output_cost": 1.6e-06}, "openrouter/openai/gpt-4.1-mini-2025-04-14": {"max_tokens": 32768, "input_cost": 4e-07, "output_cost": 1.6e-06}, "openrouter/openai/gpt-4.1-nano": {"max_tokens": 32768, "input_cost": 1e-07, "output_cost": 4e-07}, "openrouter/openai/gpt-4.1-nano-2025-04-14": {"max_tokens": 32768, "input_cost": 1e-07, "output_cost": 4e-07}, "openrouter/openai/gpt-4o": {"max_tokens": 4096, "input_cost": 2.5e-06, "output_cost": 1e-05}, "openrouter/openai/gpt-4o-2024-05-13": {"max_tokens": 4096, "input_cost": 5e-06, "output_cost": 1.5e-05}, "openrouter/openai/gpt-5-chat": {"max_tokens": 16384, "input_cost": 1.25e-06, "output_cost": 1e-05}, "openrouter/openai/gpt-5-codex": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "openrouter/openai/gpt-5.2-codex": {"max_tokens": 128000, "input_cost": 1.75e-06, "output_cost": 1.4e-05}, "openrouter/openai/gpt-5": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "openrouter/openai/gpt-5-mini": {"max_tokens": 128000, "input_cost": 2.5e-07, "output_cost": 2e-06}, "openrouter/openai/gpt-5-nano": {"max_tokens": 128000, "input_cost": 5e-08, "output_cost": 4e-07}, "openrouter/openai/gpt-5.2": {"max_tokens": 128000, "input_cost": 1.75e-06, "output_cost": 1.4e-05}, "openrouter/openai/gpt-5.2-chat": {"max_tokens": 16384, "input_cost": 1.75e-06, "output_cost": 1.4e-05}, "openrouter/openai/gpt-5.2-pro": {"max_tokens": 128000, "input_cost": 2.1e-05, "output_cost": 0.000168}, "openrouter/openai/gpt-oss-120b": {"max_tokens": 32768, "input_cost": 1.8e-07, "output_cost": 8e-07}, "openrouter/openai/gpt-oss-20b": {"max_tokens": 32768, "input_cost": 2e-08, "output_cost": 1e-07}, "openrouter/openai/o1": {"max_tokens": 100000, "input_cost": 1.5e-05, "output_cost": 6e-05}, "openrouter/openai/o1-mini": {"max_tokens": 65536, "input_cost": 3e-06, "output_cost": 1.2e-05}, "openrouter/openai/o1-mini-2024-09-12": {"max_tokens": 65536, "input_cost": 3e-06, "output_cost": 1.2e-05}, "openrouter/openai/o1-preview": {"max_tokens": 32768, "input_cost": 1.5e-05, "output_cost": 6e-05}, "openrouter/openai/o1-preview-2024-09-12": {"max_tokens": 32768, "input_cost": 1.5e-05, "output_cost": 6e-05}, "openrouter/openai/o3-mini": {"max_tokens": 65536, "input_cost": 1.1e-06, "output_cost": 4.4e-06}, "openrouter/openai/o3-mini-high": {"max_tokens": 65536, "input_cost": 1.1e-06, "output_cost": 4.4e-06}, "openrouter/pygmalionai/mythalion-13b": {"max_tokens": 4096, "input_cost": 1.875e-06, "output_cost": 1.875e-06}, "openrouter/qwen/qwen-2.5-coder-32b-instruct": {"max_tokens": 33792, "input_cost": 1.8e-07, "output_cost": 1.8e-07}, "openrouter/qwen/qwen-vl-plus": {"max_tokens": 2048, "input_cost": 2.1e-07, "output_cost": 6.3e-07}, "openrouter/qwen/qwen3-coder": {"max_tokens": 262100, "input_cost": 2.2e-07, "output_cost": 9.5e-07}, "openrouter/switchpoint/router": {"max_tokens": 131072, "input_cost": 8.5e-07, "output_cost": 3.4e-06}, "openrouter/undi95/remm-slerp-l2-13b": {"max_tokens": 6144, "input_cost": 1.875e-06, "output_cost": 1.875e-06}, "openrouter/x-ai/grok-4": {"max_tokens": 256000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "openrouter/x-ai/grok-4-fast:free": {"max_tokens": 30000, "input_cost": 0, "output_cost": 0}, "openrouter/z-ai/glm-4.6": {"max_tokens": 131000, "input_cost": 4e-07, "output_cost": 1.75e-06}, "openrouter/z-ai/glm-4.6:exacto": {"max_tokens": 131000, "input_cost": 4.5e-07, "output_cost": 1.9e-06}, "chat-bison": {"max_tokens": 4096, "input_cost": 1.25e-07, "output_cost": 1.25e-07}, "chat-bison-32k": {"max_tokens": 8192, "input_cost": 1.25e-07, "output_cost": 1.25e-07}, "chat-bison-32k@002": {"max_tokens": 8192, "input_cost": 1.25e-07, "output_cost": 1.25e-07}, "chat-bison@001": {"max_tokens": 4096, "input_cost": 1.25e-07, "output_cost": 1.25e-07}, "chat-bison@002": {"max_tokens": 4096, "input_cost": 1.25e-07, "output_cost": 1.25e-07}, "text-bison": {"max_tokens": 2048, "input_cost": 0, "output_cost": 0}, "text-bison32k": {"max_tokens": 1024, "input_cost": 1.25e-07, "output_cost": 1.25e-07}, "text-bison32k@002": {"max_tokens": 1024, "input_cost": 1.25e-07, "output_cost": 1.25e-07}, "text-bison@001": {"max_tokens": 1024, "input_cost": 0, "output_cost": 0}, "text-bison@002": {"max_tokens": 1024, "input_cost": 0, "output_cost": 0}, "text-unicorn": {"max_tokens": 1024, "input_cost": 1e-05, "output_cost": 2.8e-05}, "text-unicorn@001": {"max_tokens": 1024, "input_cost": 1e-05, "output_cost": 2.8e-05}, "gemini-1.0-pro-vision": {"max_tokens": 2048, "input_cost": 5e-07, "output_cost": 1.5e-06}, "gemini-1.0-pro-vision-001": {"max_tokens": 2048, "input_cost": 5e-07, "output_cost": 1.5e-06}, "gemini-pro-vision": {"max_tokens": 2048, "input_cost": 5e-07, "output_cost": 1.5e-06}, "gemini-1.0-pro": {"max_tokens": 8192, "input_cost": 5e-07, "output_cost": 1.5e-06}, "gemini-1.0-pro-001": {"max_tokens": 8192, "input_cost": 5e-07, "output_cost": 1.5e-06}, "gemini-1.0-pro-002": {"max_tokens": 8192, "input_cost": 5e-07, "output_cost": 1.5e-06}, "gemini-1.0-ultra": {"max_tokens": 2048, "input_cost": 5e-07, "output_cost": 1.5e-06}, "gemini-1.0-ultra-001": {"max_tokens": 2048, "input_cost": 5e-07, "output_cost": 1.5e-06}, "gemini-1.5-flash": {"max_tokens": 8192, "input_cost": 7.5e-08, "output_cost": 3e-07}, "gemini-1.5-flash-001": {"max_tokens": 8192, "input_cost": 7.5e-08, "output_cost": 3e-07}, "gemini-1.5-flash-002": {"max_tokens": 8192, "input_cost": 7.5e-08, "output_cost": 3e-07}, "gemini-1.5-flash-exp-0827": {"max_tokens": 8192, "input_cost": 4.688e-09, "output_cost": 4.6875e-09}, "gemini-1.5-flash-preview-0514": {"max_tokens": 8192, "input_cost": 7.5e-08, "output_cost": 4.6875e-09}, "gemini-1.5-pro": {"max_tokens": 8192, "input_cost": 1.25e-06, "output_cost": 5e-06}, "gemini-1.5-pro-001": {"max_tokens": 8192, "input_cost": 1.25e-06, "output_cost": 5e-06}, "gemini-1.5-pro-002": {"max_tokens": 8192, "input_cost": 1.25e-06, "output_cost": 5e-06}, "gemini-1.5-pro-preview-0215": {"max_tokens": 8192, "input_cost": 7.8125e-08, "output_cost": 3.125e-07}, "gemini-1.5-pro-preview-0409": {"max_tokens": 8192, "input_cost": 7.8125e-08, "output_cost": 3.125e-07}, "gemini-1.5-pro-preview-0514": {"max_tokens": 8192, "input_cost": 7.8125e-08, "output_cost": 3.125e-07}, "gemini-2.0-flash": {"max_tokens": 8192, "input_cost": 1e-07, "output_cost": 4e-07}, "gemini-2.0-flash-001": {"max_tokens": 8192, "input_cost": 1.5e-07, "output_cost": 6e-07}, "gemini-2.0-flash-exp": {"max_tokens": 8192, "input_cost": 1.5e-07, "output_cost": 6e-07}, "gemini-2.0-flash-lite": {"max_tokens": 1048576, "input_cost": 7.5e-08, "output_cost": 3e-07}, "gemini-2.0-flash-lite-001": {"max_tokens": 1048576, "input_cost": 7.5e-08, "output_cost": 3e-07}, "gemini-2.0-flash-live-preview-04-09": {"max_tokens": 65535, "input_cost": 5e-07, "output_cost": 2e-06}, "gemini-2.0-flash-preview-image-generation": {"max_tokens": 8192, "input_cost": 1e-07, "output_cost": 4e-07}, "gemini-2.0-flash-thinking-exp": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "gemini-2.0-flash-thinking-exp-01-21": {"max_tokens": 65536, "input_cost": 0, "output_cost": 0}, "gemini-2.0-pro-exp-02-05": {"max_tokens": 8192, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gemini-2.5-flash": {"max_tokens": 65535, "input_cost": 3e-07, "output_cost": 2.5e-06}, "gemini-2.5-flash-image": {"max_tokens": 32768, "input_cost": 3e-07, "output_cost": 2.5e-06}, "gemini-2.5-flash-image-preview": {"max_tokens": 65535, "input_cost": 3e-07, "output_cost": 3e-05}, "gemini-3-pro-image-preview": {"max_tokens": 32768, "input_cost": 2e-06, "output_cost": 1.2e-05}, "gemini-2.5-flash-lite": {"max_tokens": 65535, "input_cost": 1e-07, "output_cost": 4e-07}, "gemini-2.5-flash-lite-preview-09-2025": {"max_tokens": 65535, "input_cost": 1e-07, "output_cost": 4e-07}, "gemini-2.5-flash-preview-09-2025": {"max_tokens": 65535, "input_cost": 3e-07, "output_cost": 2.5e-06}, "gemini-live-2.5-flash-preview-native-audio-09-2025": {"max_tokens": 65535, "input_cost": 3e-07, "output_cost": 2e-06}, "gemini-2.5-flash-lite-preview-06-17": {"max_tokens": 65535, "input_cost": 1e-07, "output_cost": 4e-07}, "gemini-2.5-flash-preview-04-17": {"max_tokens": 65535, "input_cost": 1.5e-07, "output_cost": 6e-07}, "gemini-2.5-flash-preview-05-20": {"max_tokens": 65535, "input_cost": 3e-07, "output_cost": 2.5e-06}, "gemini-2.5-pro": {"max_tokens": 65535, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gemini-3-pro-preview": {"max_tokens": 65535, "input_cost": 2e-06, "output_cost": 1.2e-05}, "gemini-2.5-pro-exp-03-25": {"max_tokens": 65535, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gemini-2.5-pro-preview-03-25": {"max_tokens": 65535, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gemini-2.5-pro-preview-05-06": {"max_tokens": 65535, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gemini-2.5-pro-preview-06-05": {"max_tokens": 65535, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gemini-2.5-pro-preview-tts": {"max_tokens": 65535, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gemini-flash-experimental": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "gemini-pro": {"max_tokens": 8192, "input_cost": 5e-07, "output_cost": 1.5e-06}, "gemini-pro-experimental": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "gemini/gemini-2.5-flash-image": {"max_tokens": 32768, "input_cost": 3e-07, "output_cost": 2.5e-06}, "gemini-3-flash-preview": {"max_tokens": 65535, "input_cost": 5e-07, "output_cost": 3e-06}, "medlm-large": {"max_tokens": 1024, "input_cost": 0, "output_cost": 0}, "medlm-medium": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "vertex_ai/gemini-2.5-flash-image": {"max_tokens": 32768, "input_cost": 3e-07, "output_cost": 2.5e-06}, "vertex_ai/gemini-3-pro-image-preview": {"max_tokens": 32768, "input_cost": 2e-06, "output_cost": 1.2e-05}, "j2-light": {"max_tokens": 8192, "input_cost": 3e-06, "output_cost": 3e-06}, "j2-mid": {"max_tokens": 8192, "input_cost": 1e-05, "output_cost": 1e-05}, "j2-ultra": {"max_tokens": 8192, "input_cost": 1.5e-05, "output_cost": 1.5e-05}, "1024-x-1024/50-steps/bedrock/amazon.nova-canvas-v1:0": {"max_tokens": 2600, "input_cost": 0, "output_cost": 0}, "1024-x-1024/50-steps/stability.stable-diffusion-xl-v1": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "1024-x-1024/max-steps/stability.stable-diffusion-xl-v1": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "512-x-512/50-steps/stability.stable-diffusion-xl-v0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "512-x-512/max-steps/stability.stable-diffusion-xl-v0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "ai21.j2-mid-v1": {"max_tokens": 8191, "input_cost": 1.25e-05, "output_cost": 1.25e-05}, "ai21.j2-ultra-v1": {"max_tokens": 8191, "input_cost": 1.88e-05, "output_cost": 1.88e-05}, "ai21.jamba-1-5-large-v1:0": {"max_tokens": 256000, "input_cost": 2e-06, "output_cost": 8e-06}, "ai21.jamba-1-5-mini-v1:0": {"max_tokens": 256000, "input_cost": 2e-07, "output_cost": 4e-07}, "ai21.jamba-instruct-v1:0": {"max_tokens": 4096, "input_cost": 5e-07, "output_cost": 7e-07}, "amazon.nova-canvas-v1:0": {"max_tokens": 2600, "input_cost": 0, "output_cost": 0}, "amazon.nova-2-multimodal-embeddings-v1:0": {"max_tokens": 8172, "input_cost": 1.35e-07, "output_cost": 0.0}, "amazon.rerank-v1:0": {"max_tokens": 32000, "input_cost": 0.0, "output_cost": 0.0}, "amazon.titan-embed-image-v1": {"max_tokens": 128, "input_cost": 8e-07, "output_cost": 0.0}, "amazon.titan-embed-text-v1": {"max_tokens": 8192, "input_cost": 1e-07, "output_cost": 0.0}, "amazon.titan-embed-text-v2:0": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 0.0}, "amazon.titan-image-generator-v1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "amazon.titan-image-generator-v2": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "amazon.titan-image-generator-v2:0": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "twelvelabs.marengo-embed-2-7-v1:0": {"max_tokens": 77, "input_cost": 7e-05, "output_cost": 0.0}, "us.twelvelabs.marengo-embed-2-7-v1:0": {"max_tokens": 77, "input_cost": 7e-05, "output_cost": 0.0}, "eu.twelvelabs.marengo-embed-2-7-v1:0": {"max_tokens": 77, "input_cost": 7e-05, "output_cost": 0.0}, "twelvelabs.pegasus-1-2-v1:0": {"max_tokens": 0, "input_cost": 0, "output_cost": 7.5e-06}, "us.twelvelabs.pegasus-1-2-v1:0": {"max_tokens": 0, "input_cost": 0, "output_cost": 7.5e-06}, "eu.twelvelabs.pegasus-1-2-v1:0": {"max_tokens": 0, "input_cost": 0, "output_cost": 7.5e-06}, "amazon.titan-text-express-v1": {"max_tokens": 8000, "input_cost": 1.3e-06, "output_cost": 1.7e-06}, "amazon.titan-text-lite-v1": {"max_tokens": 4000, "input_cost": 3e-07, "output_cost": 4e-07}, "amazon.titan-text-premier-v1:0": {"max_tokens": 32000, "input_cost": 5e-07, "output_cost": 1.5e-06}, "anthropic.claude-3-5-haiku-20241022-v1:0": {"max_tokens": 8192, "input_cost": 8e-07, "output_cost": 4e-06}, "anthropic.claude-3-5-sonnet-20240620-v1:0": {"max_tokens": 4096, "input_cost": 3e-06, "output_cost": 1.5e-05}, "anthropic.claude-3-5-sonnet-20241022-v2:0": {"max_tokens": 8192, "input_cost": 3e-06, "output_cost": 1.5e-05}, "anthropic.claude-3-7-sonnet-20240620-v1:0": {"max_tokens": 8192, "input_cost": 3.6e-06, "output_cost": 1.8e-05}, "anthropic.claude-3-haiku-20240307-v1:0": {"max_tokens": 4096, "input_cost": 2.5e-07, "output_cost": 1.25e-06}, "anthropic.claude-3-opus-20240229-v1:0": {"max_tokens": 4096, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "anthropic.claude-3-sonnet-20240229-v1:0": {"max_tokens": 4096, "input_cost": 3e-06, "output_cost": 1.5e-05}, "anthropic.claude-instant-v1": {"max_tokens": 8191, "input_cost": 8e-07, "output_cost": 2.4e-06}, "anthropic.claude-v1": {"max_tokens": 8191, "input_cost": 8e-06, "output_cost": 2.4e-05}, "anthropic.claude-v2:1": {"max_tokens": 8191, "input_cost": 8e-06, "output_cost": 2.4e-05}, "apac.anthropic.claude-3-5-sonnet-20240620-v1:0": {"max_tokens": 4096, "input_cost": 3e-06, "output_cost": 1.5e-05}, "apac.anthropic.claude-3-5-sonnet-20241022-v2:0": {"max_tokens": 8192, "input_cost": 3e-06, "output_cost": 1.5e-05}, "apac.anthropic.claude-3-haiku-20240307-v1:0": {"max_tokens": 4096, "input_cost": 2.5e-07, "output_cost": 1.25e-06}, "apac.anthropic.claude-3-sonnet-20240229-v1:0": {"max_tokens": 4096, "input_cost": 3e-06, "output_cost": 1.5e-05}, "bedrock/us.anthropic.claude-3-5-haiku-20241022-v1:0": {"max_tokens": 8192, "input_cost": 8e-07, "output_cost": 4e-06}, "claude-sonnet-4-5-20250929-v1:0": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "cohere.command-light-text-v14": {"max_tokens": 4096, "input_cost": 3e-07, "output_cost": 6e-07}, "cohere.command-r-plus-v1:0": {"max_tokens": 4096, "input_cost": 3e-06, "output_cost": 1.5e-05}, "cohere.command-r-v1:0": {"max_tokens": 4096, "input_cost": 5e-07, "output_cost": 1.5e-06}, "cohere.command-text-v14": {"max_tokens": 4096, "input_cost": 1.5e-06, "output_cost": 2e-06}, "cohere.embed-english-v3": {"max_tokens": 512, "input_cost": 1e-07, "output_cost": 0.0}, "cohere.embed-multilingual-v3": {"max_tokens": 512, "input_cost": 1e-07, "output_cost": 0.0}, "cohere.embed-v4:0": {"max_tokens": 128000, "input_cost": 1.2e-07, "output_cost": 0.0}, "cohere.rerank-v3-5:0": {"max_tokens": 32000, "input_cost": 0.0, "output_cost": 0.0}, "eu.anthropic.claude-3-5-haiku-20241022-v1:0": {"max_tokens": 8192, "input_cost": 2.5e-07, "output_cost": 1.25e-06}, "eu.anthropic.claude-3-5-sonnet-20240620-v1:0": {"max_tokens": 4096, "input_cost": 3e-06, "output_cost": 1.5e-05}, "eu.anthropic.claude-3-5-sonnet-20241022-v2:0": {"max_tokens": 8192, "input_cost": 3e-06, "output_cost": 1.5e-05}, "eu.anthropic.claude-3-7-sonnet-20250219-v1:0": {"max_tokens": 8192, "input_cost": 3e-06, "output_cost": 1.5e-05}, "eu.anthropic.claude-3-haiku-20240307-v1:0": {"max_tokens": 4096, "input_cost": 2.5e-07, "output_cost": 1.25e-06}, "eu.anthropic.claude-3-opus-20240229-v1:0": {"max_tokens": 4096, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "eu.anthropic.claude-3-sonnet-20240229-v1:0": {"max_tokens": 4096, "input_cost": 3e-06, "output_cost": 1.5e-05}, "eu.meta.llama3-2-1b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 1.3e-07, "output_cost": 1.3e-07}, "eu.meta.llama3-2-3b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 1.9e-07, "output_cost": 1.9e-07}, "max-x-max/50-steps/stability.stable-diffusion-xl-v0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "max-x-max/max-steps/stability.stable-diffusion-xl-v0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "meta.llama2-13b-chat-v1": {"max_tokens": 4096, "input_cost": 7.5e-07, "output_cost": 1e-06}, "meta.llama2-70b-chat-v1": {"max_tokens": 4096, "input_cost": 1.95e-06, "output_cost": 2.56e-06}, "meta.llama3-1-405b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 5.32e-06, "output_cost": 1.6e-05}, "meta.llama3-1-70b-instruct-v1:0": {"max_tokens": 2048, "input_cost": 9.9e-07, "output_cost": 9.9e-07}, "meta.llama3-1-8b-instruct-v1:0": {"max_tokens": 2048, "input_cost": 2.2e-07, "output_cost": 2.2e-07}, "meta.llama3-2-11b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 3.5e-07, "output_cost": 3.5e-07}, "meta.llama3-2-1b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 1e-07, "output_cost": 1e-07}, "meta.llama3-2-3b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 1.5e-07, "output_cost": 1.5e-07}, "meta.llama3-2-90b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 2e-06, "output_cost": 2e-06}, "meta.llama3-70b-instruct-v1:0": {"max_tokens": 8192, "input_cost": 2.65e-06, "output_cost": 3.5e-06}, "meta.llama3-8b-instruct-v1:0": {"max_tokens": 8192, "input_cost": 3e-07, "output_cost": 6e-07}, "mistral.mistral-7b-instruct-v0:2": {"max_tokens": 8191, "input_cost": 1.5e-07, "output_cost": 2e-07}, "mistral.mistral-large-2402-v1:0": {"max_tokens": 8191, "input_cost": 8e-06, "output_cost": 2.4e-05}, "mistral.mistral-large-2407-v1:0": {"max_tokens": 8191, "input_cost": 3e-06, "output_cost": 9e-06}, "mistral.mistral-small-2402-v1:0": {"max_tokens": 8191, "input_cost": 1e-06, "output_cost": 3e-06}, "mistral.mixtral-8x7b-instruct-v0:1": {"max_tokens": 8191, "input_cost": 4.5e-07, "output_cost": 7e-07}, "stability.sd3-5-large-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.sd3-large-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-image-core-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-conservative-upscale-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-creative-upscale-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-fast-upscale-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-outpaint-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-image-control-sketch-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-image-control-structure-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-image-erase-object-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-image-inpaint-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-image-remove-background-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-image-search-recolor-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-image-search-replace-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-image-style-guide-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-style-transfer-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-image-core-v1:1": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-image-ultra-v1:0": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "stability.stable-image-ultra-v1:1": {"max_tokens": 77, "input_cost": 0, "output_cost": 0}, "us.anthropic.claude-3-5-haiku-20241022-v1:0": {"max_tokens": 8192, "input_cost": 8e-07, "output_cost": 4e-06}, "us.anthropic.claude-3-5-sonnet-20240620-v1:0": {"max_tokens": 4096, "input_cost": 3e-06, "output_cost": 1.5e-05}, "us.anthropic.claude-3-5-sonnet-20241022-v2:0": {"max_tokens": 8192, "input_cost": 3e-06, "output_cost": 1.5e-05}, "us.anthropic.claude-3-haiku-20240307-v1:0": {"max_tokens": 4096, "input_cost": 2.5e-07, "output_cost": 1.25e-06}, "us.anthropic.claude-3-opus-20240229-v1:0": {"max_tokens": 4096, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "us.anthropic.claude-3-sonnet-20240229-v1:0": {"max_tokens": 4096, "input_cost": 3e-06, "output_cost": 1.5e-05}, "us.meta.llama3-1-405b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 5.32e-06, "output_cost": 1.6e-05}, "us.meta.llama3-1-70b-instruct-v1:0": {"max_tokens": 2048, "input_cost": 9.9e-07, "output_cost": 9.9e-07}, "us.meta.llama3-1-8b-instruct-v1:0": {"max_tokens": 2048, "input_cost": 2.2e-07, "output_cost": 2.2e-07}, "us.meta.llama3-2-11b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 3.5e-07, "output_cost": 3.5e-07}, "us.meta.llama3-2-1b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 1e-07, "output_cost": 1e-07}, "us.meta.llama3-2-3b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 1.5e-07, "output_cost": 1.5e-07}, "us.meta.llama3-2-90b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 2e-06, "output_cost": 2e-06}, "anthropic.claude-opus-4-20250514-v1:0": {"max_tokens": 32000, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "anthropic.claude-sonnet-4-20250514-v1:0": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "anthropic.claude-3-7-sonnet-20250219-v1:0": {"max_tokens": 8192, "input_cost": 3e-06, "output_cost": 1.5e-05}, "us.writer.palmyra-x4-v1:0": {"max_tokens": 8192, "input_cost": 2.5e-06, "output_cost": 1e-05}, "us.writer.palmyra-x5-v1:0": {"max_tokens": 8192, "input_cost": 6e-07, "output_cost": 6e-06}, "writer.palmyra-x4-v1:0": {"max_tokens": 8192, "input_cost": 2.5e-06, "output_cost": 1e-05}, "writer.palmyra-x5-v1:0": {"max_tokens": 8192, "input_cost": 6e-07, "output_cost": 6e-06}, "amazon.nova-lite-v1:0": {"max_tokens": 10000, "input_cost": 6e-08, "output_cost": 2.4e-07}, "amazon.nova-2-lite-v1:0": {"max_tokens": 64000, "input_cost": 3e-07, "output_cost": 2.5e-06}, "apac.amazon.nova-2-lite-v1:0": {"max_tokens": 64000, "input_cost": 3.3e-07, "output_cost": 2.75e-06}, "eu.amazon.nova-2-lite-v1:0": {"max_tokens": 64000, "input_cost": 3.3e-07, "output_cost": 2.75e-06}, "us.amazon.nova-2-lite-v1:0": {"max_tokens": 64000, "input_cost": 3.3e-07, "output_cost": 2.75e-06}, "amazon.nova-micro-v1:0": {"max_tokens": 10000, "input_cost": 3.5e-08, "output_cost": 1.4e-07}, "amazon.nova-pro-v1:0": {"max_tokens": 10000, "input_cost": 8e-07, "output_cost": 3.2e-06}, "anthropic.claude-haiku-4-5-20251001-v1:0": {"max_tokens": 64000, "input_cost": 1e-06, "output_cost": 5e-06}, "anthropic.claude-haiku-4-5@20251001": {"max_tokens": 64000, "input_cost": 1e-06, "output_cost": 5e-06}, "anthropic.claude-opus-4-1-20250805-v1:0": {"max_tokens": 32000, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "anthropic.claude-opus-4-5-20251101-v1:0": {"max_tokens": 64000, "input_cost": 5e-06, "output_cost": 2.5e-05}, "anthropic.claude-sonnet-4-5-20250929-v1:0": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "apac.amazon.nova-lite-v1:0": {"max_tokens": 10000, "input_cost": 6.3e-08, "output_cost": 2.52e-07}, "apac.amazon.nova-micro-v1:0": {"max_tokens": 10000, "input_cost": 3.7e-08, "output_cost": 1.48e-07}, "apac.amazon.nova-pro-v1:0": {"max_tokens": 10000, "input_cost": 8.4e-07, "output_cost": 3.36e-06}, "apac.anthropic.claude-haiku-4-5-20251001-v1:0": {"max_tokens": 64000, "input_cost": 1.1e-06, "output_cost": 5.5e-06}, "apac.anthropic.claude-sonnet-4-20250514-v1:0": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "au.anthropic.claude-sonnet-4-5-20250929-v1:0": {"max_tokens": 64000, "input_cost": 3.3e-06, "output_cost": 1.65e-05}, "deepseek.v3-v1:0": {"max_tokens": 81920, "input_cost": 5.8e-07, "output_cost": 1.68e-06}, "eu.amazon.nova-lite-v1:0": {"max_tokens": 10000, "input_cost": 7.8e-08, "output_cost": 3.12e-07}, "eu.amazon.nova-micro-v1:0": {"max_tokens": 10000, "input_cost": 4.6e-08, "output_cost": 1.84e-07}, "eu.amazon.nova-pro-v1:0": {"max_tokens": 10000, "input_cost": 1.05e-06, "output_cost": 4.2e-06}, "eu.anthropic.claude-haiku-4-5-20251001-v1:0": {"max_tokens": 64000, "input_cost": 1.1e-06, "output_cost": 5.5e-06}, "eu.anthropic.claude-opus-4-1-20250805-v1:0": {"max_tokens": 32000, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "eu.anthropic.claude-opus-4-20250514-v1:0": {"max_tokens": 32000, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "eu.anthropic.claude-sonnet-4-20250514-v1:0": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "eu.anthropic.claude-sonnet-4-5-20250929-v1:0": {"max_tokens": 64000, "input_cost": 3.3e-06, "output_cost": 1.65e-05}, "eu.mistral.pixtral-large-2502-v1:0": {"max_tokens": 4096, "input_cost": 2e-06, "output_cost": 6e-06}, "google.gemma-3-12b-it": {"max_tokens": 8192, "input_cost": 9e-08, "output_cost": 2.9e-07}, "google.gemma-3-27b-it": {"max_tokens": 8192, "input_cost": 2.3e-07, "output_cost": 3.8e-07}, "google.gemma-3-4b-it": {"max_tokens": 8192, "input_cost": 4e-08, "output_cost": 8e-08}, "global.anthropic.claude-sonnet-4-5-20250929-v1:0": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "global.anthropic.claude-sonnet-4-20250514-v1:0": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "global.anthropic.claude-haiku-4-5-20251001-v1:0": {"max_tokens": 64000, "input_cost": 1e-06, "output_cost": 5e-06}, "global.amazon.nova-2-lite-v1:0": {"max_tokens": 64000, "input_cost": 3e-07, "output_cost": 2.5e-06}, "jp.anthropic.claude-sonnet-4-5-20250929-v1:0": {"max_tokens": 64000, "input_cost": 3.3e-06, "output_cost": 1.65e-05}, "jp.anthropic.claude-haiku-4-5-20251001-v1:0": {"max_tokens": 64000, "input_cost": 1.1e-06, "output_cost": 5.5e-06}, "meta.llama3-3-70b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 7.2e-07, "output_cost": 7.2e-07}, "meta.llama4-maverick-17b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 2.4e-07, "output_cost": 9.7e-07}, "meta.llama4-scout-17b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 1.7e-07, "output_cost": 6.6e-07}, "minimax.minimax-m2": {"max_tokens": 8192, "input_cost": 3e-07, "output_cost": 1.2e-06}, "mistral.magistral-small-2509": {"max_tokens": 8192, "input_cost": 5e-07, "output_cost": 1.5e-06}, "mistral.ministral-3-14b-instruct": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 2e-07}, "mistral.ministral-3-3b-instruct": {"max_tokens": 8192, "input_cost": 1e-07, "output_cost": 1e-07}, "mistral.ministral-3-8b-instruct": {"max_tokens": 8192, "input_cost": 1.5e-07, "output_cost": 1.5e-07}, "mistral.mistral-large-3-675b-instruct": {"max_tokens": 8192, "input_cost": 5e-07, "output_cost": 1.5e-06}, "mistral.voxtral-mini-3b-2507": {"max_tokens": 8192, "input_cost": 4e-08, "output_cost": 4e-08}, "mistral.voxtral-small-24b-2507": {"max_tokens": 8192, "input_cost": 1e-07, "output_cost": 3e-07}, "moonshot.kimi-k2-thinking": {"max_tokens": 8192, "input_cost": 6e-07, "output_cost": 2.5e-06}, "nvidia.nemotron-nano-12b-v2": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 6e-07}, "nvidia.nemotron-nano-9b-v2": {"max_tokens": 8192, "input_cost": 6e-08, "output_cost": 2.3e-07}, "openai.gpt-oss-120b-1:0": {"max_tokens": 128000, "input_cost": 1.5e-07, "output_cost": 6e-07}, "openai.gpt-oss-20b-1:0": {"max_tokens": 128000, "input_cost": 7e-08, "output_cost": 3e-07}, "openai.gpt-oss-safeguard-120b": {"max_tokens": 8192, "input_cost": 1.5e-07, "output_cost": 6e-07}, "openai.gpt-oss-safeguard-20b": {"max_tokens": 8192, "input_cost": 7e-08, "output_cost": 2e-07}, "qwen.qwen3-coder-480b-a35b-v1:0": {"max_tokens": 65536, "input_cost": 2.2e-07, "output_cost": 1.8e-06}, "qwen.qwen3-235b-a22b-2507-v1:0": {"max_tokens": 131072, "input_cost": 2.2e-07, "output_cost": 8.8e-07}, "qwen.qwen3-coder-30b-a3b-v1:0": {"max_tokens": 131072, "input_cost": 1.5e-07, "output_cost": 6e-07}, "qwen.qwen3-32b-v1:0": {"max_tokens": 16384, "input_cost": 1.5e-07, "output_cost": 6e-07}, "qwen.qwen3-next-80b-a3b": {"max_tokens": 8192, "input_cost": 1.5e-07, "output_cost": 1.2e-06}, "qwen.qwen3-vl-235b-a22b": {"max_tokens": 8192, "input_cost": 5.3e-07, "output_cost": 2.66e-06}, "us.amazon.nova-lite-v1:0": {"max_tokens": 10000, "input_cost": 6e-08, "output_cost": 2.4e-07}, "us.amazon.nova-micro-v1:0": {"max_tokens": 10000, "input_cost": 3.5e-08, "output_cost": 1.4e-07}, "us.amazon.nova-premier-v1:0": {"max_tokens": 10000, "input_cost": 2.5e-06, "output_cost": 1.25e-05}, "us.amazon.nova-pro-v1:0": {"max_tokens": 10000, "input_cost": 8e-07, "output_cost": 3.2e-06}, "us.anthropic.claude-haiku-4-5-20251001-v1:0": {"max_tokens": 64000, "input_cost": 1.1e-06, "output_cost": 5.5e-06}, "us.anthropic.claude-3-7-sonnet-20250219-v1:0": {"max_tokens": 8192, "input_cost": 3e-06, "output_cost": 1.5e-05}, "us.anthropic.claude-opus-4-1-20250805-v1:0": {"max_tokens": 32000, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "us.anthropic.claude-sonnet-4-5-20250929-v1:0": {"max_tokens": 64000, "input_cost": 3.3e-06, "output_cost": 1.65e-05}, "au.anthropic.claude-haiku-4-5-20251001-v1:0": {"max_tokens": 64000, "input_cost": 1.1e-06, "output_cost": 5.5e-06}, "us.anthropic.claude-opus-4-20250514-v1:0": {"max_tokens": 32000, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "us.anthropic.claude-opus-4-5-20251101-v1:0": {"max_tokens": 64000, "input_cost": 5.5e-06, "output_cost": 2.75e-05}, "global.anthropic.claude-opus-4-5-20251101-v1:0": {"max_tokens": 64000, "input_cost": 5e-06, "output_cost": 2.5e-05}, "eu.anthropic.claude-opus-4-5-20251101-v1:0": {"max_tokens": 64000, "input_cost": 5e-06, "output_cost": 2.5e-05}, "us.anthropic.claude-sonnet-4-20250514-v1:0": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "us.deepseek.r1-v1:0": {"max_tokens": 4096, "input_cost": 1.35e-06, "output_cost": 5.4e-06}, "us.meta.llama3-3-70b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 7.2e-07, "output_cost": 7.2e-07}, "us.meta.llama4-maverick-17b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 2.4e-07, "output_cost": 9.7e-07}, "us.meta.llama4-scout-17b-instruct-v1:0": {"max_tokens": 4096, "input_cost": 1.7e-07, "output_cost": 6.6e-07}, "us.mistral.pixtral-large-2502-v1:0": {"max_tokens": 4096, "input_cost": 2e-06, "output_cost": 6e-06}, "deepinfra/Gryphe/MythoMax-L2-13b": {"max_tokens": 4096, "input_cost": 8e-08, "output_cost": 9e-08}, "deepinfra/NousResearch/Hermes-3-Llama-3.1-405B": {"max_tokens": 131072, "input_cost": 1e-06, "output_cost": 1e-06}, "deepinfra/NousResearch/Hermes-3-Llama-3.1-70B": {"max_tokens": 131072, "input_cost": 3e-07, "output_cost": 3e-07}, "deepinfra/Qwen/QwQ-32B": {"max_tokens": 131072, "input_cost": 1.5e-07, "output_cost": 4e-07}, "deepinfra/Qwen/Qwen2.5-72B-Instruct": {"max_tokens": 32768, "input_cost": 1.2e-07, "output_cost": 3.9e-07}, "deepinfra/Qwen/Qwen2.5-7B-Instruct": {"max_tokens": 32768, "input_cost": 4e-08, "output_cost": 1e-07}, "deepinfra/Qwen/Qwen2.5-VL-32B-Instruct": {"max_tokens": 128000, "input_cost": 2e-07, "output_cost": 6e-07}, "deepinfra/Qwen/Qwen3-14B": {"max_tokens": 40960, "input_cost": 6e-08, "output_cost": 2.4e-07}, "deepinfra/Qwen/Qwen3-235B-A22B": {"max_tokens": 40960, "input_cost": 1.8e-07, "output_cost": 5.4e-07}, "deepinfra/Qwen/Qwen3-235B-A22B-Instruct-2507": {"max_tokens": 262144, "input_cost": 9e-08, "output_cost": 6e-07}, "deepinfra/Qwen/Qwen3-235B-A22B-Thinking-2507": {"max_tokens": 262144, "input_cost": 3e-07, "output_cost": 2.9e-06}, "deepinfra/Qwen/Qwen3-30B-A3B": {"max_tokens": 40960, "input_cost": 8e-08, "output_cost": 2.9e-07}, "deepinfra/Qwen/Qwen3-32B": {"max_tokens": 40960, "input_cost": 1e-07, "output_cost": 2.8e-07}, "deepinfra/Qwen/Qwen3-Coder-480B-A35B-Instruct": {"max_tokens": 262144, "input_cost": 4e-07, "output_cost": 1.6e-06}, "deepinfra/Qwen/Qwen3-Coder-480B-A35B-Instruct-Turbo": {"max_tokens": 262144, "input_cost": 2.9e-07, "output_cost": 1.2e-06}, "deepinfra/Qwen/Qwen3-Next-80B-A3B-Instruct": {"max_tokens": 262144, "input_cost": 1.4e-07, "output_cost": 1.4e-06}, "deepinfra/Qwen/Qwen3-Next-80B-A3B-Thinking": {"max_tokens": 262144, "input_cost": 1.4e-07, "output_cost": 1.4e-06}, "deepinfra/Sao10K/L3-8B-Lunaris-v1-Turbo": {"max_tokens": 8192, "input_cost": 4e-08, "output_cost": 5e-08}, "deepinfra/Sao10K/L3.1-70B-Euryale-v2.2": {"max_tokens": 131072, "input_cost": 6.5e-07, "output_cost": 7.5e-07}, "deepinfra/Sao10K/L3.3-70B-Euryale-v2.3": {"max_tokens": 131072, "input_cost": 6.5e-07, "output_cost": 7.5e-07}, "deepinfra/allenai/olmOCR-7B-0725-FP8": {"max_tokens": 16384, "input_cost": 2.7e-07, "output_cost": 1.5e-06}, "deepinfra/anthropic/claude-3-7-sonnet-latest": {"max_tokens": 200000, "input_cost": 3.3e-06, "output_cost": 1.65e-05}, "deepinfra/anthropic/claude-4-opus": {"max_tokens": 200000, "input_cost": 1.65e-05, "output_cost": 8.25e-05}, "deepinfra/anthropic/claude-4-sonnet": {"max_tokens": 200000, "input_cost": 3.3e-06, "output_cost": 1.65e-05}, "deepinfra/deepseek-ai/DeepSeek-R1": {"max_tokens": 163840, "input_cost": 7e-07, "output_cost": 2.4e-06}, "deepinfra/deepseek-ai/DeepSeek-R1-0528": {"max_tokens": 163840, "input_cost": 5e-07, "output_cost": 2.15e-06}, "deepinfra/deepseek-ai/DeepSeek-R1-0528-Turbo": {"max_tokens": 32768, "input_cost": 1e-06, "output_cost": 3e-06}, "deepinfra/deepseek-ai/DeepSeek-R1-Distill-Llama-70B": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 6e-07}, "deepinfra/deepseek-ai/DeepSeek-R1-Distill-Qwen-32B": {"max_tokens": 131072, "input_cost": 2.7e-07, "output_cost": 2.7e-07}, "deepinfra/deepseek-ai/DeepSeek-R1-Turbo": {"max_tokens": 40960, "input_cost": 1e-06, "output_cost": 3e-06}, "deepinfra/deepseek-ai/DeepSeek-V3": {"max_tokens": 163840, "input_cost": 3.8e-07, "output_cost": 8.9e-07}, "deepinfra/deepseek-ai/DeepSeek-V3-0324": {"max_tokens": 163840, "input_cost": 2.5e-07, "output_cost": 8.8e-07}, "deepinfra/deepseek-ai/DeepSeek-V3.1": {"max_tokens": 163840, "input_cost": 2.7e-07, "output_cost": 1e-06}, "deepinfra/deepseek-ai/DeepSeek-V3.1-Terminus": {"max_tokens": 163840, "input_cost": 2.7e-07, "output_cost": 1e-06}, "deepinfra/google/gemini-2.0-flash-001": {"max_tokens": 1000000, "input_cost": 1e-07, "output_cost": 4e-07}, "deepinfra/google/gemini-2.5-flash": {"max_tokens": 1000000, "input_cost": 3e-07, "output_cost": 2.5e-06}, "deepinfra/google/gemini-2.5-pro": {"max_tokens": 1000000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "deepinfra/google/gemma-3-12b-it": {"max_tokens": 131072, "input_cost": 5e-08, "output_cost": 1e-07}, "deepinfra/google/gemma-3-27b-it": {"max_tokens": 131072, "input_cost": 9e-08, "output_cost": 1.6e-07}, "deepinfra/google/gemma-3-4b-it": {"max_tokens": 131072, "input_cost": 4e-08, "output_cost": 8e-08}, "deepinfra/meta-llama/Llama-3.2-11B-Vision-Instruct": {"max_tokens": 131072, "input_cost": 4.9e-08, "output_cost": 4.9e-08}, "deepinfra/meta-llama/Llama-3.2-3B-Instruct": {"max_tokens": 131072, "input_cost": 2e-08, "output_cost": 2e-08}, "deepinfra/meta-llama/Llama-3.3-70B-Instruct": {"max_tokens": 131072, "input_cost": 2.3e-07, "output_cost": 4e-07}, "deepinfra/meta-llama/Llama-3.3-70B-Instruct-Turbo": {"max_tokens": 131072, "input_cost": 1.3e-07, "output_cost": 3.9e-07}, "deepinfra/meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8": {"max_tokens": 1048576, "input_cost": 1.5e-07, "output_cost": 6e-07}, "deepinfra/meta-llama/Llama-4-Scout-17B-16E-Instruct": {"max_tokens": 327680, "input_cost": 8e-08, "output_cost": 3e-07}, "deepinfra/meta-llama/Llama-Guard-3-8B": {"max_tokens": 131072, "input_cost": 5.5e-08, "output_cost": 5.5e-08}, "deepinfra/meta-llama/Llama-Guard-4-12B": {"max_tokens": 163840, "input_cost": 1.8e-07, "output_cost": 1.8e-07}, "deepinfra/meta-llama/Meta-Llama-3-8B-Instruct": {"max_tokens": 8192, "input_cost": 3e-08, "output_cost": 6e-08}, "deepinfra/meta-llama/Meta-Llama-3.1-70B-Instruct": {"max_tokens": 131072, "input_cost": 4e-07, "output_cost": 4e-07}, "deepinfra/meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo": {"max_tokens": 131072, "input_cost": 1e-07, "output_cost": 2.8e-07}, "deepinfra/meta-llama/Meta-Llama-3.1-8B-Instruct": {"max_tokens": 131072, "input_cost": 3e-08, "output_cost": 5e-08}, "deepinfra/meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo": {"max_tokens": 131072, "input_cost": 2e-08, "output_cost": 3e-08}, "deepinfra/microsoft/WizardLM-2-8x22B": {"max_tokens": 65536, "input_cost": 4.8e-07, "output_cost": 4.8e-07}, "deepinfra/microsoft/phi-4": {"max_tokens": 16384, "input_cost": 7e-08, "output_cost": 1.4e-07}, "deepinfra/mistralai/Mistral-Nemo-Instruct-2407": {"max_tokens": 131072, "input_cost": 2e-08, "output_cost": 4e-08}, "deepinfra/mistralai/Mistral-Small-24B-Instruct-2501": {"max_tokens": 32768, "input_cost": 5e-08, "output_cost": 8e-08}, "deepinfra/mistralai/Mistral-Small-3.2-24B-Instruct-2506": {"max_tokens": 128000, "input_cost": 7.5e-08, "output_cost": 2e-07}, "deepinfra/mistralai/Mixtral-8x7B-Instruct-v0.1": {"max_tokens": 32768, "input_cost": 4e-07, "output_cost": 4e-07}, "deepinfra/moonshotai/Kimi-K2-Instruct": {"max_tokens": 131072, "input_cost": 5e-07, "output_cost": 2e-06}, "deepinfra/moonshotai/Kimi-K2-Instruct-0905": {"max_tokens": 262144, "input_cost": 5e-07, "output_cost": 2e-06}, "deepinfra/nvidia/Llama-3.1-Nemotron-70B-Instruct": {"max_tokens": 131072, "input_cost": 6e-07, "output_cost": 6e-07}, "deepinfra/nvidia/Llama-3.3-Nemotron-Super-49B-v1.5": {"max_tokens": 131072, "input_cost": 1e-07, "output_cost": 4e-07}, "deepinfra/nvidia/NVIDIA-Nemotron-Nano-9B-v2": {"max_tokens": 131072, "input_cost": 4e-08, "output_cost": 1.6e-07}, "deepinfra/openai/gpt-oss-120b": {"max_tokens": 131072, "input_cost": 5e-08, "output_cost": 4.5e-07}, "deepinfra/openai/gpt-oss-20b": {"max_tokens": 131072, "input_cost": 4e-08, "output_cost": 1.5e-07}, "deepinfra/zai-org/GLM-4.5": {"max_tokens": 131072, "input_cost": 4e-07, "output_cost": 1.6e-06}, "perplexity/search": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "perplexity/codellama-34b-instruct": {"max_tokens": 16384, "input_cost": 3.5e-07, "output_cost": 1.4e-06}, "perplexity/codellama-70b-instruct": {"max_tokens": 16384, "input_cost": 7e-07, "output_cost": 2.8e-06}, "perplexity/llama-2-70b-chat": {"max_tokens": 4096, "input_cost": 7e-07, "output_cost": 2.8e-06}, "perplexity/llama-3.1-70b-instruct": {"max_tokens": 131072, "input_cost": 1e-06, "output_cost": 1e-06}, "perplexity/llama-3.1-8b-instruct": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 2e-07}, "perplexity/llama-3.1-sonar-huge-128k-online": {"max_tokens": 127072, "input_cost": 5e-06, "output_cost": 5e-06}, "perplexity/llama-3.1-sonar-large-128k-chat": {"max_tokens": 131072, "input_cost": 1e-06, "output_cost": 1e-06}, "perplexity/llama-3.1-sonar-large-128k-online": {"max_tokens": 127072, "input_cost": 1e-06, "output_cost": 1e-06}, "perplexity/llama-3.1-sonar-small-128k-chat": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 2e-07}, "perplexity/llama-3.1-sonar-small-128k-online": {"max_tokens": 127072, "input_cost": 2e-07, "output_cost": 2e-07}, "perplexity/mistral-7b-instruct": {"max_tokens": 4096, "input_cost": 7e-08, "output_cost": 2.8e-07}, "perplexity/mixtral-8x7b-instruct": {"max_tokens": 4096, "input_cost": 7e-08, "output_cost": 2.8e-07}, "perplexity/pplx-70b-chat": {"max_tokens": 4096, "input_cost": 7e-07, "output_cost": 2.8e-06}, "perplexity/pplx-70b-online": {"max_tokens": 4096, "input_cost": 0.0, "output_cost": 2.8e-06}, "perplexity/pplx-7b-chat": {"max_tokens": 8192, "input_cost": 7e-08, "output_cost": 2.8e-07}, "perplexity/pplx-7b-online": {"max_tokens": 4096, "input_cost": 0.0, "output_cost": 2.8e-07}, "perplexity/sonar": {"max_tokens": 128000, "input_cost": 1e-06, "output_cost": 1e-06}, "perplexity/sonar-deep-research": {"max_tokens": 128000, "input_cost": 2e-06, "output_cost": 8e-06}, "perplexity/sonar-medium-chat": {"max_tokens": 16384, "input_cost": 6e-07, "output_cost": 1.8e-06}, "perplexity/sonar-medium-online": {"max_tokens": 12000, "input_cost": 0, "output_cost": 1.8e-06}, "perplexity/sonar-pro": {"max_tokens": 8000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "perplexity/sonar-reasoning": {"max_tokens": 128000, "input_cost": 1e-06, "output_cost": 5e-06}, "perplexity/sonar-reasoning-pro": {"max_tokens": 128000, "input_cost": 2e-06, "output_cost": 8e-06}, "perplexity/sonar-small-chat": {"max_tokens": 16384, "input_cost": 7e-08, "output_cost": 2.8e-07}, "perplexity/sonar-small-online": {"max_tokens": 12000, "input_cost": 0, "output_cost": 2.8e-07}, "watsonx/ibm/granite-3-8b-instruct": {"max_tokens": 1024, "input_cost": 2e-07, "output_cost": 2e-07}, "watsonx/mistralai/mistral-large": {"max_tokens": 16384, "input_cost": 3e-06, "output_cost": 1e-05}, "watsonx/bigscience/mt0-xxl-13b": {"max_tokens": 8192, "input_cost": 0.0005, "output_cost": 0.002}, "watsonx/core42/jais-13b-chat": {"max_tokens": 8192, "input_cost": 0.0005, "output_cost": 0.002}, "watsonx/google/flan-t5-xl-3b": {"max_tokens": 8192, "input_cost": 6e-07, "output_cost": 6e-07}, "watsonx/ibm/granite-13b-chat-v2": {"max_tokens": 8192, "input_cost": 6e-07, "output_cost": 6e-07}, "watsonx/ibm/granite-13b-instruct-v2": {"max_tokens": 8192, "input_cost": 6e-07, "output_cost": 6e-07}, "watsonx/ibm/granite-3-3-8b-instruct": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 2e-07}, "watsonx/ibm/granite-4-h-small": {"max_tokens": 20480, "input_cost": 6e-08, "output_cost": 2.5e-07}, "watsonx/ibm/granite-guardian-3-2-2b": {"max_tokens": 8192, "input_cost": 1e-07, "output_cost": 1e-07}, "watsonx/ibm/granite-guardian-3-3-8b": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 2e-07}, "watsonx/ibm/granite-ttm-1024-96-r2": {"max_tokens": 512, "input_cost": 3.8e-07, "output_cost": 3.8e-07}, "watsonx/ibm/granite-ttm-1536-96-r2": {"max_tokens": 512, "input_cost": 3.8e-07, "output_cost": 3.8e-07}, "watsonx/ibm/granite-ttm-512-96-r2": {"max_tokens": 512, "input_cost": 3.8e-07, "output_cost": 3.8e-07}, "watsonx/ibm/granite-vision-3-2-2b": {"max_tokens": 8192, "input_cost": 1e-07, "output_cost": 1e-07}, "watsonx/meta-llama/llama-3-2-11b-vision-instruct": {"max_tokens": 128000, "input_cost": 3.5e-07, "output_cost": 3.5e-07}, "watsonx/meta-llama/llama-3-2-1b-instruct": {"max_tokens": 128000, "input_cost": 1e-07, "output_cost": 1e-07}, "watsonx/meta-llama/llama-3-2-3b-instruct": {"max_tokens": 128000, "input_cost": 1.5e-07, "output_cost": 1.5e-07}, "watsonx/meta-llama/llama-3-2-90b-vision-instruct": {"max_tokens": 128000, "input_cost": 2e-06, "output_cost": 2e-06}, "watsonx/meta-llama/llama-3-3-70b-instruct": {"max_tokens": 128000, "input_cost": 7.1e-07, "output_cost": 7.1e-07}, "watsonx/meta-llama/llama-4-maverick-17b": {"max_tokens": 128000, "input_cost": 3.5e-07, "output_cost": 1.4e-06}, "watsonx/meta-llama/llama-guard-3-11b-vision": {"max_tokens": 128000, "input_cost": 3.5e-07, "output_cost": 3.5e-07}, "watsonx/mistralai/mistral-medium-2505": {"max_tokens": 128000, "input_cost": 3e-06, "output_cost": 1e-05}, "watsonx/mistralai/mistral-small-2503": {"max_tokens": 32000, "input_cost": 1e-07, "output_cost": 3e-07}, "watsonx/mistralai/mistral-small-3-1-24b-instruct-2503": {"max_tokens": 32000, "input_cost": 1e-07, "output_cost": 3e-07}, "watsonx/mistralai/pixtral-12b-2409": {"max_tokens": 128000, "input_cost": 3.5e-07, "output_cost": 3.5e-07}, "watsonx/openai/gpt-oss-120b": {"max_tokens": 8192, "input_cost": 1.5e-07, "output_cost": 6e-07}, "watsonx/sdaia/allam-1-13b-instruct": {"max_tokens": 8192, "input_cost": 1.8e-06, "output_cost": 1.8e-06}, "watsonx/whisper-large-v3-turbo": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "gemini/gemini-live-2.5-flash-preview-native-audio-09-2025": {"max_tokens": 65535, "input_cost": 3e-07, "output_cost": 2e-06}, "gemini/gemini-embedding-001": {"max_tokens": 2048, "input_cost": 1.5e-07, "output_cost": 0}, "gemini/gemini-1.5-flash": {"max_tokens": 8192, "input_cost": 7.5e-08, "output_cost": 3e-07}, "gemini/gemini-1.5-flash-001": {"max_tokens": 8192, "input_cost": 7.5e-08, "output_cost": 3e-07}, "gemini/gemini-1.5-flash-002": {"max_tokens": 8192, "input_cost": 7.5e-08, "output_cost": 3e-07}, "gemini/gemini-1.5-flash-8b": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "gemini/gemini-1.5-flash-8b-exp-0827": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "gemini/gemini-1.5-flash-8b-exp-0924": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "gemini/gemini-1.5-flash-exp-0827": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "gemini/gemini-1.5-flash-latest": {"max_tokens": 8192, "input_cost": 7.5e-08, "output_cost": 3e-07}, "gemini/gemini-1.5-pro": {"max_tokens": 8192, "input_cost": 3.5e-06, "output_cost": 1.05e-05}, "gemini/gemini-1.5-pro-001": {"max_tokens": 8192, "input_cost": 3.5e-06, "output_cost": 1.05e-05}, "gemini/gemini-1.5-pro-002": {"max_tokens": 8192, "input_cost": 3.5e-06, "output_cost": 1.05e-05}, "gemini/gemini-1.5-pro-exp-0801": {"max_tokens": 8192, "input_cost": 3.5e-06, "output_cost": 1.05e-05}, "gemini/gemini-1.5-pro-exp-0827": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "gemini/gemini-1.5-pro-latest": {"max_tokens": 8192, "input_cost": 3.5e-06, "output_cost": 1.05e-06}, "gemini/gemini-2.0-flash": {"max_tokens": 8192, "input_cost": 1e-07, "output_cost": 4e-07}, "gemini/gemini-2.0-flash-001": {"max_tokens": 8192, "input_cost": 1e-07, "output_cost": 4e-07}, "gemini/gemini-2.0-flash-exp": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "gemini/gemini-2.0-flash-lite": {"max_tokens": 1048576, "input_cost": 7.5e-08, "output_cost": 3e-07}, "gemini/gemini-2.0-flash-lite-preview-02-05": {"max_tokens": 8192, "input_cost": 7.5e-08, "output_cost": 3e-07}, "gemini/gemini-2.0-flash-live-001": {"max_tokens": 65535, "input_cost": 3.5e-07, "output_cost": 1.5e-06}, "gemini/gemini-2.0-flash-preview-image-generation": {"max_tokens": 8192, "input_cost": 1e-07, "output_cost": 4e-07}, "gemini/gemini-2.0-flash-thinking-exp": {"max_tokens": 65536, "input_cost": 0, "output_cost": 0}, "gemini/gemini-2.0-flash-thinking-exp-01-21": {"max_tokens": 65536, "input_cost": 0, "output_cost": 0}, "gemini/gemini-2.0-pro-exp-02-05": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "gemini/gemini-2.5-flash": {"max_tokens": 65535, "input_cost": 3e-07, "output_cost": 2.5e-06}, "gemini/gemini-2.5-flash-image-preview": {"max_tokens": 65535, "input_cost": 3e-07, "output_cost": 3e-05}, "gemini/gemini-3-pro-image-preview": {"max_tokens": 32768, "input_cost": 2e-06, "output_cost": 1.2e-05}, "gemini/gemini-2.5-flash-lite": {"max_tokens": 65535, "input_cost": 1e-07, "output_cost": 4e-07}, "gemini/gemini-2.5-flash-lite-preview-09-2025": {"max_tokens": 65535, "input_cost": 1e-07, "output_cost": 4e-07}, "gemini/gemini-2.5-flash-preview-09-2025": {"max_tokens": 65535, "input_cost": 3e-07, "output_cost": 2.5e-06}, "gemini/gemini-flash-latest": {"max_tokens": 65535, "input_cost": 3e-07, "output_cost": 2.5e-06}, "gemini/gemini-flash-lite-latest": {"max_tokens": 65535, "input_cost": 1e-07, "output_cost": 4e-07}, "gemini/gemini-2.5-flash-lite-preview-06-17": {"max_tokens": 65535, "input_cost": 1e-07, "output_cost": 4e-07}, "gemini/gemini-2.5-flash-preview-04-17": {"max_tokens": 65535, "input_cost": 1.5e-07, "output_cost": 6e-07}, "gemini/gemini-2.5-flash-preview-05-20": {"max_tokens": 65535, "input_cost": 3e-07, "output_cost": 2.5e-06}, "gemini/gemini-2.5-flash-preview-tts": {"max_tokens": 65535, "input_cost": 1.5e-07, "output_cost": 6e-07}, "gemini/gemini-2.5-pro": {"max_tokens": 65535, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gemini/gemini-2.5-computer-use-preview-10-2025": {"max_tokens": 64000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gemini/gemini-3-pro-preview": {"max_tokens": 65535, "input_cost": 2e-06, "output_cost": 1.2e-05}, "gemini/gemini-3-flash-preview": {"max_tokens": 65535, "input_cost": 5e-07, "output_cost": 3e-06}, "gemini/gemini-2.5-pro-exp-03-25": {"max_tokens": 65535, "input_cost": 0.0, "output_cost": 0.0}, "gemini/gemini-2.5-pro-preview-03-25": {"max_tokens": 65535, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gemini/gemini-2.5-pro-preview-05-06": {"max_tokens": 65535, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gemini/gemini-2.5-pro-preview-06-05": {"max_tokens": 65535, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gemini/gemini-2.5-pro-preview-tts": {"max_tokens": 65535, "input_cost": 1.25e-06, "output_cost": 1e-05}, "gemini/gemini-exp-1114": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "gemini/gemini-exp-1206": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "gemini/gemini-gemma-2-27b-it": {"max_tokens": 8192, "input_cost": 3.5e-07, "output_cost": 1.05e-06}, "gemini/gemini-gemma-2-9b-it": {"max_tokens": 8192, "input_cost": 3.5e-07, "output_cost": 1.05e-06}, "gemini/gemini-pro": {"max_tokens": 8192, "input_cost": 3.5e-07, "output_cost": 1.05e-06}, "gemini/gemini-pro-vision": {"max_tokens": 2048, "input_cost": 3.5e-07, "output_cost": 1.05e-06}, "gemini/gemma-3-27b-it": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "gemini/imagen-3.0-fast-generate-001": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "gemini/imagen-3.0-generate-001": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "gemini/imagen-3.0-generate-002": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "gemini/imagen-4.0-fast-generate-001": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "gemini/imagen-4.0-generate-001": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "gemini/imagen-4.0-ultra-generate-001": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "gemini/learnlm-1.5-pro-experimental": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "gemini/veo-2.0-generate-001": {"max_tokens": 1024, "input_cost": 0, "output_cost": 0}, "gemini/veo-3.0-fast-generate-preview": {"max_tokens": 1024, "input_cost": 0, "output_cost": 0}, "gemini/veo-3.0-generate-preview": {"max_tokens": 1024, "input_cost": 0, "output_cost": 0}, "gemini/veo-3.1-fast-generate-preview": {"max_tokens": 1024, "input_cost": 0, "output_cost": 0}, "gemini/veo-3.1-generate-preview": {"max_tokens": 1024, "input_cost": 0, "output_cost": 0}, "gemini/veo-3.1-fast-generate-001": {"max_tokens": 1024, "input_cost": 0, "output_cost": 0}, "gemini/veo-3.1-generate-001": {"max_tokens": 1024, "input_cost": 0, "output_cost": 0}, "fireworks-ai-above-16b": {"max_tokens": 0, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-coder-v2-instruct": {"max_tokens": 65536, "input_cost": 1.2e-06, "output_cost": 1.2e-06}, "fireworks_ai/accounts/fireworks/models/deepseek-r1": {"max_tokens": 20480, "input_cost": 3e-06, "output_cost": 8e-06}, "fireworks_ai/accounts/fireworks/models/deepseek-r1-0528": {"max_tokens": 160000, "input_cost": 3e-06, "output_cost": 8e-06}, "fireworks_ai/accounts/fireworks/models/deepseek-r1-basic": {"max_tokens": 20480, "input_cost": 5.5e-07, "output_cost": 2.19e-06}, "fireworks_ai/accounts/fireworks/models/deepseek-v3": {"max_tokens": 8192, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-v3-0324": {"max_tokens": 163840, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-v3p1": {"max_tokens": 8192, "input_cost": 5.6e-07, "output_cost": 1.68e-06}, "fireworks_ai/accounts/fireworks/models/deepseek-v3p1-terminus": {"max_tokens": 8192, "input_cost": 5.6e-07, "output_cost": 1.68e-06}, "fireworks_ai/accounts/fireworks/models/deepseek-v3p2": {"max_tokens": 163840, "input_cost": 5.6e-07, "output_cost": 1.68e-06}, "fireworks_ai/accounts/fireworks/models/firefunction-v2": {"max_tokens": 8192, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/glm-4p5": {"max_tokens": 96000, "input_cost": 5.5e-07, "output_cost": 2.19e-06}, "fireworks_ai/accounts/fireworks/models/glm-4p5-air": {"max_tokens": 96000, "input_cost": 2.2e-07, "output_cost": 8.8e-07}, "fireworks_ai/accounts/fireworks/models/glm-4p6": {"max_tokens": 202800, "input_cost": 5.5e-07, "output_cost": 2.19e-06}, "fireworks_ai/accounts/fireworks/models/gpt-oss-120b": {"max_tokens": 131072, "input_cost": 1.5e-07, "output_cost": 6e-07}, "fireworks_ai/accounts/fireworks/models/gpt-oss-20b": {"max_tokens": 131072, "input_cost": 5e-08, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/kimi-k2-instruct": {"max_tokens": 16384, "input_cost": 6e-07, "output_cost": 2.5e-06}, "fireworks_ai/accounts/fireworks/models/kimi-k2-instruct-0905": {"max_tokens": 32768, "input_cost": 6e-07, "output_cost": 2.5e-06}, "fireworks_ai/accounts/fireworks/models/kimi-k2-thinking": {"max_tokens": 262144, "input_cost": 6e-07, "output_cost": 2.5e-06}, "fireworks_ai/accounts/fireworks/models/llama-v3p1-405b-instruct": {"max_tokens": 16384, "input_cost": 3e-06, "output_cost": 3e-06}, "fireworks_ai/accounts/fireworks/models/llama-v3p1-8b-instruct": {"max_tokens": 16384, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/llama-v3p2-11b-vision-instruct": {"max_tokens": 16384, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/llama-v3p2-1b-instruct": {"max_tokens": 16384, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/llama-v3p2-3b-instruct": {"max_tokens": 16384, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/llama-v3p2-90b-vision-instruct": {"max_tokens": 16384, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/llama4-maverick-instruct-basic": {"max_tokens": 131072, "input_cost": 2.2e-07, "output_cost": 8.8e-07}, "fireworks_ai/accounts/fireworks/models/llama4-scout-instruct-basic": {"max_tokens": 131072, "input_cost": 1.5e-07, "output_cost": 6e-07}, "fireworks_ai/accounts/fireworks/models/mixtral-8x22b-instruct-hf": {"max_tokens": 65536, "input_cost": 1.2e-06, "output_cost": 1.2e-06}, "fireworks_ai/accounts/fireworks/models/qwen2-72b-instruct": {"max_tokens": 32768, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-32b-instruct": {"max_tokens": 4096, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/yi-large": {"max_tokens": 32768, "input_cost": 3e-06, "output_cost": 3e-06}, "fireworks_ai/accounts/fireworks/models/qwen3-coder-480b-a35b-instruct": {"max_tokens": 262144, "input_cost": 4.5e-07, "output_cost": 1.8e-06}, "fireworks_ai/accounts/fireworks/models/flux-kontext-pro": {"max_tokens": 4096, "input_cost": 4e-08, "output_cost": 4e-08}, "fireworks_ai/accounts/fireworks/models/SSD-1B": {"max_tokens": 4096, "input_cost": 1.3e-10, "output_cost": 1.3e-10}, "fireworks_ai/accounts/fireworks/models/chronos-hermes-13b-v2": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/code-llama-13b": {"max_tokens": 16384, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/code-llama-13b-instruct": {"max_tokens": 16384, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/code-llama-13b-python": {"max_tokens": 16384, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/code-llama-34b": {"max_tokens": 16384, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/code-llama-34b-instruct": {"max_tokens": 16384, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/code-llama-34b-python": {"max_tokens": 16384, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/code-llama-70b": {"max_tokens": 4096, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/code-llama-70b-instruct": {"max_tokens": 4096, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/code-llama-70b-python": {"max_tokens": 4096, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/code-llama-7b": {"max_tokens": 16384, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/code-llama-7b-instruct": {"max_tokens": 16384, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/code-llama-7b-python": {"max_tokens": 16384, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/code-qwen-1p5-7b": {"max_tokens": 65536, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/codegemma-2b": {"max_tokens": 8192, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/codegemma-7b": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/cogito-671b-v2-p1": {"max_tokens": 163840, "input_cost": 1.2e-06, "output_cost": 1.2e-06}, "fireworks_ai/accounts/fireworks/models/cogito-v1-preview-llama-3b": {"max_tokens": 131072, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/cogito-v1-preview-llama-70b": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/cogito-v1-preview-llama-8b": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/cogito-v1-preview-qwen-14b": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/cogito-v1-preview-qwen-32b": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/flux-kontext-max": {"max_tokens": 4096, "input_cost": 8e-08, "output_cost": 8e-08}, "fireworks_ai/accounts/fireworks/models/dbrx-instruct": {"max_tokens": 32768, "input_cost": 1.2e-06, "output_cost": 1.2e-06}, "fireworks_ai/accounts/fireworks/models/deepseek-coder-1b-base": {"max_tokens": 16384, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-coder-33b-instruct": {"max_tokens": 16384, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-coder-7b-base": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-coder-7b-base-v1p5": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-coder-7b-instruct-v1p5": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-coder-v2-lite-base": {"max_tokens": 163840, "input_cost": 5e-07, "output_cost": 5e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-coder-v2-lite-instruct": {"max_tokens": 163840, "input_cost": 5e-07, "output_cost": 5e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-prover-v2": {"max_tokens": 163840, "input_cost": 1.2e-06, "output_cost": 1.2e-06}, "fireworks_ai/accounts/fireworks/models/deepseek-r1-0528-distill-qwen3-8b": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-r1-distill-llama-70b": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-r1-distill-llama-8b": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-r1-distill-qwen-14b": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-r1-distill-qwen-1p5b": {"max_tokens": 131072, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-r1-distill-qwen-32b": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-r1-distill-qwen-7b": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-v2-lite-chat": {"max_tokens": 163840, "input_cost": 5e-07, "output_cost": 5e-07}, "fireworks_ai/accounts/fireworks/models/deepseek-v2p5": {"max_tokens": 32768, "input_cost": 1.2e-06, "output_cost": 1.2e-06}, "fireworks_ai/accounts/fireworks/models/devstral-small-2505": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/dobby-mini-unhinged-plus-llama-3-1-8b": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/dobby-unhinged-llama-3-3-70b-new": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/dolphin-2-9-2-qwen2-72b": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/dolphin-2p6-mixtral-8x7b": {"max_tokens": 32768, "input_cost": 5e-07, "output_cost": 5e-07}, "fireworks_ai/accounts/fireworks/models/ernie-4p5-21b-a3b-pt": {"max_tokens": 4096, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/ernie-4p5-300b-a47b-pt": {"max_tokens": 4096, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/fare-20b": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/firefunction-v1": {"max_tokens": 32768, "input_cost": 5e-07, "output_cost": 5e-07}, "fireworks_ai/accounts/fireworks/models/firellava-13b": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/firesearch-ocr-v6": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/fireworks-asr-large": {"max_tokens": 4096, "input_cost": 0.0, "output_cost": 0.0}, "fireworks_ai/accounts/fireworks/models/fireworks-asr-v2": {"max_tokens": 4096, "input_cost": 0.0, "output_cost": 0.0}, "fireworks_ai/accounts/fireworks/models/flux-1-dev": {"max_tokens": 4096, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/flux-1-dev-controlnet-union": {"max_tokens": 4096, "input_cost": 1e-09, "output_cost": 1e-09}, "fireworks_ai/accounts/fireworks/models/flux-1-dev-fp8": {"max_tokens": 4096, "input_cost": 5e-10, "output_cost": 5e-10}, "fireworks_ai/accounts/fireworks/models/flux-1-schnell": {"max_tokens": 4096, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/flux-1-schnell-fp8": {"max_tokens": 4096, "input_cost": 3.5e-10, "output_cost": 3.5e-10}, "fireworks_ai/accounts/fireworks/models/gemma-2b-it": {"max_tokens": 8192, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/gemma-3-27b-it": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/gemma-7b": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/gemma-7b-it": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/gemma2-9b-it": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/glm-4p5v": {"max_tokens": 131072, "input_cost": 1.2e-06, "output_cost": 1.2e-06}, "fireworks_ai/accounts/fireworks/models/gpt-oss-safeguard-120b": {"max_tokens": 131072, "input_cost": 1.2e-06, "output_cost": 1.2e-06}, "fireworks_ai/accounts/fireworks/models/gpt-oss-safeguard-20b": {"max_tokens": 131072, "input_cost": 5e-07, "output_cost": 5e-07}, "fireworks_ai/accounts/fireworks/models/hermes-2-pro-mistral-7b": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/internvl3-38b": {"max_tokens": 16384, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/internvl3-78b": {"max_tokens": 16384, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/internvl3-8b": {"max_tokens": 16384, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/japanese-stable-diffusion-xl": {"max_tokens": 4096, "input_cost": 1.3e-10, "output_cost": 1.3e-10}, "fireworks_ai/accounts/fireworks/models/kat-coder": {"max_tokens": 262144, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/kat-dev-32b": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/kat-dev-72b-exp": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/llama-guard-2-8b": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/llama-guard-3-1b": {"max_tokens": 131072, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/llama-guard-3-8b": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/llama-v2-13b": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/llama-v2-13b-chat": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/llama-v2-70b": {"max_tokens": 4096, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/llama-v2-70b-chat": {"max_tokens": 2048, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/llama-v2-7b": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/llama-v2-7b-chat": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/llama-v3-70b-instruct": {"max_tokens": 8192, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/llama-v3-70b-instruct-hf": {"max_tokens": 8192, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/llama-v3-8b": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/llama-v3-8b-instruct-hf": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/llama-v3p1-405b-instruct-long": {"max_tokens": 4096, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/llama-v3p1-70b-instruct": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/llama-v3p1-70b-instruct-1b": {"max_tokens": 4096, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/llama-v3p1-nemotron-70b-instruct": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/llama-v3p2-1b": {"max_tokens": 131072, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/llama-v3p2-3b": {"max_tokens": 131072, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/llama-v3p3-70b-instruct": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/llamaguard-7b": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/llava-yi-34b": {"max_tokens": 4096, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/minimax-m1-80k": {"max_tokens": 4096, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/minimax-m2": {"max_tokens": 4096, "input_cost": 3e-07, "output_cost": 1.2e-06}, "fireworks_ai/accounts/fireworks/models/ministral-3-14b-instruct-2512": {"max_tokens": 256000, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/ministral-3-3b-instruct-2512": {"max_tokens": 256000, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/ministral-3-8b-instruct-2512": {"max_tokens": 256000, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/mistral-7b": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/mistral-7b-instruct-4k": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/mistral-7b-instruct-v0p2": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/mistral-7b-instruct-v3": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/mistral-7b-v0p2": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/mistral-large-3-fp8": {"max_tokens": 256000, "input_cost": 1.2e-06, "output_cost": 1.2e-06}, "fireworks_ai/accounts/fireworks/models/mistral-nemo-base-2407": {"max_tokens": 128000, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/mistral-nemo-instruct-2407": {"max_tokens": 128000, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/mistral-small-24b-instruct-2501": {"max_tokens": 32768, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/mixtral-8x22b": {"max_tokens": 65536, "input_cost": 1.2e-06, "output_cost": 1.2e-06}, "fireworks_ai/accounts/fireworks/models/mixtral-8x22b-instruct": {"max_tokens": 65536, "input_cost": 1.2e-06, "output_cost": 1.2e-06}, "fireworks_ai/accounts/fireworks/models/mixtral-8x7b": {"max_tokens": 32768, "input_cost": 5e-07, "output_cost": 5e-07}, "fireworks_ai/accounts/fireworks/models/mixtral-8x7b-instruct": {"max_tokens": 32768, "input_cost": 5e-07, "output_cost": 5e-07}, "fireworks_ai/accounts/fireworks/models/mixtral-8x7b-instruct-hf": {"max_tokens": 32768, "input_cost": 5e-07, "output_cost": 5e-07}, "fireworks_ai/accounts/fireworks/models/mythomax-l2-13b": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/nemotron-nano-v2-12b-vl": {"max_tokens": 4096, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/nous-capybara-7b-v1p9": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/nous-hermes-2-mixtral-8x7b-dpo": {"max_tokens": 32768, "input_cost": 5e-07, "output_cost": 5e-07}, "fireworks_ai/accounts/fireworks/models/nous-hermes-2-yi-34b": {"max_tokens": 4096, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/nous-hermes-llama2-13b": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/nous-hermes-llama2-70b": {"max_tokens": 4096, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/nous-hermes-llama2-7b": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/nvidia-nemotron-nano-12b-v2": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/nvidia-nemotron-nano-9b-v2": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/openchat-3p5-0106-7b": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/openhermes-2-mistral-7b": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/openhermes-2p5-mistral-7b": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/openorca-7b": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/phi-2-3b": {"max_tokens": 2048, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/phi-3-mini-128k-instruct": {"max_tokens": 131072, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/phi-3-vision-128k-instruct": {"max_tokens": 32064, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/phind-code-llama-34b-python-v1": {"max_tokens": 16384, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/phind-code-llama-34b-v1": {"max_tokens": 16384, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/phind-code-llama-34b-v2": {"max_tokens": 16384, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/playground-v2-1024px-aesthetic": {"max_tokens": 4096, "input_cost": 1.3e-10, "output_cost": 1.3e-10}, "fireworks_ai/accounts/fireworks/models/playground-v2-5-1024px-aesthetic": {"max_tokens": 4096, "input_cost": 1.3e-10, "output_cost": 1.3e-10}, "fireworks_ai/accounts/fireworks/models/pythia-12b": {"max_tokens": 2048, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen-qwq-32b-preview": {"max_tokens": 32768, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen-v2p5-14b-instruct": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen-v2p5-7b": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen1p5-72b-chat": {"max_tokens": 32768, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen2-7b-instruct": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen2-vl-2b-instruct": {"max_tokens": 32768, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/qwen2-vl-72b-instruct": {"max_tokens": 32768, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen2-vl-7b-instruct": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-0p5b-instruct": {"max_tokens": 32768, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-14b": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-1p5b-instruct": {"max_tokens": 32768, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-32b": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-32b-instruct": {"max_tokens": 32768, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-72b": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-72b-instruct": {"max_tokens": 32768, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-7b-instruct": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-0p5b": {"max_tokens": 32768, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-0p5b-instruct": {"max_tokens": 32768, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-14b": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-14b-instruct": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-1p5b": {"max_tokens": 32768, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-1p5b-instruct": {"max_tokens": 32768, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-32b": {"max_tokens": 32768, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-32b-instruct-128k": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-32b-instruct-32k-rope": {"max_tokens": 32768, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-32b-instruct-64k": {"max_tokens": 65536, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-3b": {"max_tokens": 32768, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-3b-instruct": {"max_tokens": 32768, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-7b": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-coder-7b-instruct": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-math-72b-instruct": {"max_tokens": 4096, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-vl-32b-instruct": {"max_tokens": 128000, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-vl-3b-instruct": {"max_tokens": 128000, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-vl-72b-instruct": {"max_tokens": 128000, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen2p5-vl-7b-instruct": {"max_tokens": 128000, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-0p6b": {"max_tokens": 40960, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-14b": {"max_tokens": 40960, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-1p7b": {"max_tokens": 131072, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-1p7b-fp8-draft": {"max_tokens": 262144, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-1p7b-fp8-draft-131072": {"max_tokens": 131072, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-1p7b-fp8-draft-40960": {"max_tokens": 40960, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-235b-a22b": {"max_tokens": 131072, "input_cost": 2.2e-07, "output_cost": 8.8e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-235b-a22b-instruct-2507": {"max_tokens": 262144, "input_cost": 2.2e-07, "output_cost": 8.8e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-235b-a22b-thinking-2507": {"max_tokens": 262144, "input_cost": 2.2e-07, "output_cost": 8.8e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-30b-a3b": {"max_tokens": 131072, "input_cost": 1.5e-07, "output_cost": 6e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-30b-a3b-instruct-2507": {"max_tokens": 262144, "input_cost": 5e-07, "output_cost": 5e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-30b-a3b-thinking-2507": {"max_tokens": 262144, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-32b": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-4b": {"max_tokens": 40960, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-4b-instruct-2507": {"max_tokens": 262144, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-8b": {"max_tokens": 40960, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-coder-30b-a3b-instruct": {"max_tokens": 262144, "input_cost": 1.5e-07, "output_cost": 6e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-coder-480b-instruct-bf16": {"max_tokens": 4096, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-embedding-0p6b": {"max_tokens": 32768, "input_cost": 0.0, "output_cost": 0.0}, "fireworks_ai/accounts/fireworks/models/qwen3-embedding-4b": {"max_tokens": 40960, "input_cost": 0.0, "output_cost": 0.0}, "fireworks_ai/accounts/fireworks/models/": {"max_tokens": 40960, "input_cost": 1e-07, "output_cost": 0.0}, "fireworks_ai/accounts/fireworks/models/qwen3-next-80b-a3b-instruct": {"max_tokens": 4096, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-next-80b-a3b-thinking": {"max_tokens": 4096, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-reranker-0p6b": {"max_tokens": 40960, "input_cost": 0.0, "output_cost": 0.0}, "fireworks_ai/accounts/fireworks/models/qwen3-reranker-4b": {"max_tokens": 40960, "input_cost": 0.0, "output_cost": 0.0}, "fireworks_ai/accounts/fireworks/models/qwen3-reranker-8b": {"max_tokens": 40960, "input_cost": 0.0, "output_cost": 0.0}, "fireworks_ai/accounts/fireworks/models/qwen3-vl-235b-a22b-instruct": {"max_tokens": 262144, "input_cost": 2.2e-07, "output_cost": 8.8e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-vl-235b-a22b-thinking": {"max_tokens": 262144, "input_cost": 2.2e-07, "output_cost": 8.8e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-vl-30b-a3b-instruct": {"max_tokens": 262144, "input_cost": 1.5e-07, "output_cost": 6e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-vl-30b-a3b-thinking": {"max_tokens": 262144, "input_cost": 1.5e-07, "output_cost": 6e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-vl-32b-instruct": {"max_tokens": 4096, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/qwen3-vl-8b-instruct": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/qwq-32b": {"max_tokens": 131072, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/rolm-ocr": {"max_tokens": 128000, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/snorkel-mistral-7b-pairrm-dpo": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/stable-diffusion-xl-1024-v1-0": {"max_tokens": 4096, "input_cost": 1.3e-10, "output_cost": 1.3e-10}, "fireworks_ai/accounts/fireworks/models/stablecode-3b": {"max_tokens": 4096, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/starcoder-16b": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/starcoder-7b": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/starcoder2-15b": {"max_tokens": 16384, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/starcoder2-3b": {"max_tokens": 16384, "input_cost": 1e-07, "output_cost": 1e-07}, "fireworks_ai/accounts/fireworks/models/starcoder2-7b": {"max_tokens": 16384, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/toppy-m-7b": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/whisper-v3": {"max_tokens": 4096, "input_cost": 0.0, "output_cost": 0.0}, "fireworks_ai/accounts/fireworks/models/whisper-v3-turbo": {"max_tokens": 4096, "input_cost": 0.0, "output_cost": 0.0}, "fireworks_ai/accounts/fireworks/models/yi-34b": {"max_tokens": 4096, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/yi-34b-200k-capybara": {"max_tokens": 200000, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/yi-34b-chat": {"max_tokens": 4096, "input_cost": 9e-07, "output_cost": 9e-07}, "fireworks_ai/accounts/fireworks/models/yi-6b": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/accounts/fireworks/models/zephyr-7b-beta": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 2e-07}, "fireworks_ai/WhereIsAI/UAE-Large-V1": {"max_tokens": 512, "input_cost": 1.6e-08, "output_cost": 0.0}, "fireworks_ai/nomic-ai/nomic-embed-text-v1": {"max_tokens": 8192, "input_cost": 8e-09, "output_cost": 0.0}, "fireworks_ai/nomic-ai/nomic-embed-text-v1.5": {"max_tokens": 8192, "input_cost": 8e-09, "output_cost": 0.0}, "fireworks_ai/thenlper/gte-base": {"max_tokens": 512, "input_cost": 8e-09, "output_cost": 0.0}, "fireworks_ai/thenlper/gte-large": {"max_tokens": 512, "input_cost": 1.6e-08, "output_cost": 0.0}, "luminous-base": {"max_tokens": 2048, "input_cost": 3e-05, "output_cost": 3.3e-05}, "luminous-base-control": {"max_tokens": 2048, "input_cost": 3.75e-05, "output_cost": 4.125e-05}, "luminous-extended": {"max_tokens": 2048, "input_cost": 4.5e-05, "output_cost": 4.95e-05}, "luminous-extended-control": {"max_tokens": 2048, "input_cost": 5.625e-05, "output_cost": 6.1875e-05}, "luminous-supreme": {"max_tokens": 2048, "input_cost": 0.000175, "output_cost": 0.0001925}, "luminous-supreme-control": {"max_tokens": 2048, "input_cost": 0.00021875, "output_cost": 0.000240625}, "text-completion-codestral/codestral-2405": {"max_tokens": 8191, "input_cost": 0.0, "output_cost": 0.0}, "text-completion-codestral/codestral-latest": {"max_tokens": 8191, "input_cost": 0.0, "output_cost": 0.0}, "xai/grok-2": {"max_tokens": 131072, "input_cost": 2e-06, "output_cost": 1e-05}, "xai/grok-2-1212": {"max_tokens": 131072, "input_cost": 2e-06, "output_cost": 1e-05}, "xai/grok-2-latest": {"max_tokens": 131072, "input_cost": 2e-06, "output_cost": 1e-05}, "xai/grok-2-vision": {"max_tokens": 32768, "input_cost": 2e-06, "output_cost": 1e-05}, "xai/grok-2-vision-1212": {"max_tokens": 32768, "input_cost": 2e-06, "output_cost": 1e-05}, "xai/grok-2-vision-latest": {"max_tokens": 32768, "input_cost": 2e-06, "output_cost": 1e-05}, "xai/grok-3": {"max_tokens": 131072, "input_cost": 3e-06, "output_cost": 1.5e-05}, "xai/grok-3-beta": {"max_tokens": 131072, "input_cost": 3e-06, "output_cost": 1.5e-05}, "xai/grok-3-fast-beta": {"max_tokens": 131072, "input_cost": 5e-06, "output_cost": 2.5e-05}, "xai/grok-3-fast-latest": {"max_tokens": 131072, "input_cost": 5e-06, "output_cost": 2.5e-05}, "xai/grok-3-latest": {"max_tokens": 131072, "input_cost": 3e-06, "output_cost": 1.5e-05}, "xai/grok-3-mini": {"max_tokens": 131072, "input_cost": 3e-07, "output_cost": 5e-07}, "xai/grok-3-mini-beta": {"max_tokens": 131072, "input_cost": 3e-07, "output_cost": 5e-07}, "xai/grok-3-mini-fast": {"max_tokens": 131072, "input_cost": 6e-07, "output_cost": 4e-06}, "xai/grok-3-mini-fast-beta": {"max_tokens": 131072, "input_cost": 6e-07, "output_cost": 4e-06}, "xai/grok-3-mini-fast-latest": {"max_tokens": 131072, "input_cost": 6e-07, "output_cost": 4e-06}, "xai/grok-3-mini-latest": {"max_tokens": 131072, "input_cost": 3e-07, "output_cost": 5e-07}, "xai/grok-4": {"max_tokens": 256000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "xai/grok-4-fast-reasoning": {"max_tokens": 2000000.0, "input_cost": 2e-07, "output_cost": 5e-07}, "xai/grok-4-fast-non-reasoning": {"max_tokens": 2000000.0, "input_cost": 2e-07, "output_cost": 5e-07}, "xai/grok-4-0709": {"max_tokens": 256000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "xai/grok-4-latest": {"max_tokens": 256000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "xai/grok-4-1-fast": {"max_tokens": 2000000.0, "input_cost": 2e-07, "output_cost": 5e-07}, "xai/grok-4-1-fast-reasoning": {"max_tokens": 2000000.0, "input_cost": 2e-07, "output_cost": 5e-07}, "xai/grok-4-1-fast-reasoning-latest": {"max_tokens": 2000000.0, "input_cost": 2e-07, "output_cost": 5e-07}, "xai/grok-4-1-fast-non-reasoning": {"max_tokens": 2000000.0, "input_cost": 2e-07, "output_cost": 5e-07}, "xai/grok-4-1-fast-non-reasoning-latest": {"max_tokens": 2000000.0, "input_cost": 2e-07, "output_cost": 5e-07}, "xai/grok-beta": {"max_tokens": 131072, "input_cost": 5e-06, "output_cost": 1.5e-05}, "xai/grok-code-fast": {"max_tokens": 256000, "input_cost": 2e-07, "output_cost": 1.5e-06}, "xai/grok-code-fast-1": {"max_tokens": 256000, "input_cost": 2e-07, "output_cost": 1.5e-06}, "xai/grok-code-fast-1-0825": {"max_tokens": 256000, "input_cost": 2e-07, "output_cost": 1.5e-06}, "xai/grok-vision-beta": {"max_tokens": 8192, "input_cost": 5e-06, "output_cost": 1.5e-05}, "deepseek-chat": {"max_tokens": 8192, "input_cost": 2.8e-07, "output_cost": 4.2e-07}, "deepseek-reasoner": {"max_tokens": 65536, "input_cost": 2.8e-07, "output_cost": 4.2e-07}, "deepseek/deepseek-chat": {"max_tokens": 8192, "input_cost": 2.8e-07, "output_cost": 4.2e-07}, "deepseek/deepseek-coder": {"max_tokens": 4096, "input_cost": 1.4e-07, "output_cost": 2.8e-07}, "deepseek/deepseek-r1": {"max_tokens": 8192, "input_cost": 5.5e-07, "output_cost": 2.19e-06}, "deepseek/deepseek-reasoner": {"max_tokens": 8192, "input_cost": 2.8e-07, "output_cost": 4.2e-07}, "deepseek/deepseek-v3": {"max_tokens": 8192, "input_cost": 2.7e-07, "output_cost": 1.1e-06}, "deepseek/deepseek-v3.2": {"max_tokens": 163840, "input_cost": 2.8e-07, "output_cost": 4e-07}, "mistral/codestral-2405": {"max_tokens": 8191, "input_cost": 1e-06, "output_cost": 3e-06}, "mistral/codestral-2508": {"max_tokens": 256000, "input_cost": 3e-07, "output_cost": 9e-07}, "mistral/codestral-latest": {"max_tokens": 8191, "input_cost": 1e-06, "output_cost": 3e-06}, "mistral/codestral-mamba-latest": {"max_tokens": 256000, "input_cost": 2.5e-07, "output_cost": 2.5e-07}, "mistral/devstral-medium-2507": {"max_tokens": 128000, "input_cost": 4e-07, "output_cost": 2e-06}, "mistral/devstral-small-2505": {"max_tokens": 128000, "input_cost": 1e-07, "output_cost": 3e-07}, "mistral/devstral-small-2507": {"max_tokens": 128000, "input_cost": 1e-07, "output_cost": 3e-07}, "mistral/labs-devstral-small-2512": {"max_tokens": 256000, "input_cost": 1e-07, "output_cost": 3e-07}, "mistral/devstral-2512": {"max_tokens": 256000, "input_cost": 4e-07, "output_cost": 2e-06}, "mistral/magistral-medium-2506": {"max_tokens": 40000, "input_cost": 2e-06, "output_cost": 5e-06}, "mistral/magistral-medium-2509": {"max_tokens": 40000, "input_cost": 2e-06, "output_cost": 5e-06}, "mistral/mistral-ocr-latest": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "mistral/mistral-ocr-2505-completion": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "mistral/magistral-medium-latest": {"max_tokens": 40000, "input_cost": 2e-06, "output_cost": 5e-06}, "mistral/magistral-small-2506": {"max_tokens": 40000, "input_cost": 5e-07, "output_cost": 1.5e-06}, "mistral/magistral-small-latest": {"max_tokens": 40000, "input_cost": 5e-07, "output_cost": 1.5e-06}, "mistral/mistral-embed": {"max_tokens": 8192, "input_cost": 1e-07, "output_cost": 0}, "mistral/codestral-embed": {"max_tokens": 8192, "input_cost": 1.5e-07, "output_cost": 0}, "mistral/codestral-embed-2505": {"max_tokens": 8192, "input_cost": 1.5e-07, "output_cost": 0}, "mistral/mistral-large-2402": {"max_tokens": 8191, "input_cost": 4e-06, "output_cost": 1.2e-05}, "mistral/mistral-large-2407": {"max_tokens": 128000, "input_cost": 3e-06, "output_cost": 9e-06}, "mistral/mistral-large-2411": {"max_tokens": 128000, "input_cost": 2e-06, "output_cost": 6e-06}, "mistral/mistral-large-latest": {"max_tokens": 128000, "input_cost": 2e-06, "output_cost": 6e-06}, "mistral/mistral-large-3": {"max_tokens": 8191, "input_cost": 5e-07, "output_cost": 1.5e-06}, "mistral/mistral-medium": {"max_tokens": 8191, "input_cost": 2.7e-06, "output_cost": 8.1e-06}, "mistral/mistral-medium-2312": {"max_tokens": 8191, "input_cost": 2.7e-06, "output_cost": 8.1e-06}, "mistral/mistral-medium-2505": {"max_tokens": 8191, "input_cost": 4e-07, "output_cost": 2e-06}, "mistral/mistral-medium-latest": {"max_tokens": 8191, "input_cost": 4e-07, "output_cost": 2e-06}, "mistral/mistral-small": {"max_tokens": 8191, "input_cost": 1e-07, "output_cost": 3e-07}, "mistral/mistral-small-latest": {"max_tokens": 8191, "input_cost": 1e-07, "output_cost": 3e-07}, "mistral/mistral-tiny": {"max_tokens": 8191, "input_cost": 2.5e-07, "output_cost": 2.5e-07}, "mistral/open-codestral-mamba": {"max_tokens": 256000, "input_cost": 2.5e-07, "output_cost": 2.5e-07}, "mistral/open-mistral-7b": {"max_tokens": 8191, "input_cost": 2.5e-07, "output_cost": 2.5e-07}, "mistral/open-mistral-nemo": {"max_tokens": 128000, "input_cost": 3e-07, "output_cost": 3e-07}, "mistral/open-mistral-nemo-2407": {"max_tokens": 128000, "input_cost": 3e-07, "output_cost": 3e-07}, "mistral/open-mixtral-8x22b": {"max_tokens": 8191, "input_cost": 2e-06, "output_cost": 6e-06}, "mistral/open-mixtral-8x7b": {"max_tokens": 8191, "input_cost": 7e-07, "output_cost": 7e-07}, "mistral/pixtral-12b-2409": {"max_tokens": 128000, "input_cost": 1.5e-07, "output_cost": 1.5e-07}, "mistral/pixtral-large-2411": {"max_tokens": 128000, "input_cost": 2e-06, "output_cost": 6e-06}, "mistral/pixtral-large-latest": {"max_tokens": 128000, "input_cost": 2e-06, "output_cost": 6e-06}, "azure_ai/claude-haiku-4-5": {"max_tokens": 64000, "input_cost": 1e-06, "output_cost": 5e-06}, "azure_ai/claude-opus-4-5": {"max_tokens": 64000, "input_cost": 5e-06, "output_cost": 2.5e-05}, "azure_ai/claude-opus-4-1": {"max_tokens": 32000, "input_cost": 1.5e-05, "output_cost": 7.5e-05}, "azure_ai/claude-sonnet-4-5": {"max_tokens": 64000, "input_cost": 3e-06, "output_cost": 1.5e-05}, "azure_ai/gpt-oss-120b": {"max_tokens": 131072, "input_cost": 1.5e-07, "output_cost": 6e-07}, "azure_ai/Cohere-embed-v3-english": {"max_tokens": 512, "input_cost": 1e-07, "output_cost": 0.0}, "azure_ai/Cohere-embed-v3-multilingual": {"max_tokens": 512, "input_cost": 1e-07, "output_cost": 0.0}, "azure_ai/FLUX-1.1-pro": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure_ai/FLUX.1-Kontext-pro": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure_ai/flux.2-pro": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure_ai/Llama-3.2-11B-Vision-Instruct": {"max_tokens": 2048, "input_cost": 3.7e-07, "output_cost": 3.7e-07}, "azure_ai/Llama-3.2-90B-Vision-Instruct": {"max_tokens": 2048, "input_cost": 2.04e-06, "output_cost": 2.04e-06}, "azure_ai/Llama-3.3-70B-Instruct": {"max_tokens": 2048, "input_cost": 7.1e-07, "output_cost": 7.1e-07}, "azure_ai/Llama-4-Maverick-17B-128E-Instruct-FP8": {"max_tokens": 16384, "input_cost": 1.41e-06, "output_cost": 3.5e-07}, "azure_ai/Llama-4-Scout-17B-16E-Instruct": {"max_tokens": 16384, "input_cost": 2e-07, "output_cost": 7.8e-07}, "azure_ai/Meta-Llama-3-70B-Instruct": {"max_tokens": 2048, "input_cost": 1.1e-06, "output_cost": 3.7e-07}, "azure_ai/Meta-Llama-3.1-405B-Instruct": {"max_tokens": 2048, "input_cost": 5.33e-06, "output_cost": 1.6e-05}, "azure_ai/Meta-Llama-3.1-70B-Instruct": {"max_tokens": 2048, "input_cost": 2.68e-06, "output_cost": 3.54e-06}, "azure_ai/Meta-Llama-3.1-8B-Instruct": {"max_tokens": 2048, "input_cost": 3e-07, "output_cost": 6.1e-07}, "azure_ai/Phi-3-medium-128k-instruct": {"max_tokens": 4096, "input_cost": 1.7e-07, "output_cost": 6.8e-07}, "azure_ai/Phi-3-medium-4k-instruct": {"max_tokens": 4096, "input_cost": 1.7e-07, "output_cost": 6.8e-07}, "azure_ai/Phi-3-mini-128k-instruct": {"max_tokens": 4096, "input_cost": 1.3e-07, "output_cost": 5.2e-07}, "azure_ai/Phi-3-mini-4k-instruct": {"max_tokens": 4096, "input_cost": 1.3e-07, "output_cost": 5.2e-07}, "azure_ai/Phi-3-small-128k-instruct": {"max_tokens": 4096, "input_cost": 1.5e-07, "output_cost": 6e-07}, "azure_ai/Phi-3-small-8k-instruct": {"max_tokens": 4096, "input_cost": 1.5e-07, "output_cost": 6e-07}, "azure_ai/Phi-3.5-MoE-instruct": {"max_tokens": 4096, "input_cost": 1.6e-07, "output_cost": 6.4e-07}, "azure_ai/Phi-3.5-mini-instruct": {"max_tokens": 4096, "input_cost": 1.3e-07, "output_cost": 5.2e-07}, "azure_ai/Phi-3.5-vision-instruct": {"max_tokens": 4096, "input_cost": 1.3e-07, "output_cost": 5.2e-07}, "azure_ai/Phi-4": {"max_tokens": 16384, "input_cost": 1.25e-07, "output_cost": 5e-07}, "azure_ai/Phi-4-mini-instruct": {"max_tokens": 4096, "input_cost": 7.5e-08, "output_cost": 3e-07}, "azure_ai/Phi-4-multimodal-instruct": {"max_tokens": 4096, "input_cost": 8e-08, "output_cost": 3.2e-07}, "azure_ai/Phi-4-mini-reasoning": {"max_tokens": 4096, "input_cost": 8e-08, "output_cost": 3.2e-07}, "azure_ai/Phi-4-reasoning": {"max_tokens": 4096, "input_cost": 1.25e-07, "output_cost": 5e-07}, "azure_ai/mistral-document-ai-2505": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure_ai/doc-intelligence/prebuilt-read": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure_ai/doc-intelligence/prebuilt-layout": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure_ai/doc-intelligence/prebuilt-document": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure_ai/MAI-DS-R1": {"max_tokens": 8192, "input_cost": 1.35e-06, "output_cost": 5.4e-06}, "azure_ai/cohere-rerank-v3-english": {"max_tokens": 4096, "input_cost": 0.0, "output_cost": 0.0}, "azure_ai/cohere-rerank-v3-multilingual": {"max_tokens": 4096, "input_cost": 0.0, "output_cost": 0.0}, "azure_ai/cohere-rerank-v3.5": {"max_tokens": 4096, "input_cost": 0.0, "output_cost": 0.0}, "azure_ai/cohere-rerank-v4.0-pro": {"max_tokens": 32768, "input_cost": 0.0, "output_cost": 0.0}, "azure_ai/cohere-rerank-v4.0-fast": {"max_tokens": 32768, "input_cost": 0.0, "output_cost": 0.0}, "azure_ai/deepseek-v3.2": {"max_tokens": 163840, "input_cost": 5.8e-07, "output_cost": 1.68e-06}, "azure_ai/deepseek-v3.2-speciale": {"max_tokens": 163840, "input_cost": 5.8e-07, "output_cost": 1.68e-06}, "azure_ai/deepseek-r1": {"max_tokens": 8192, "input_cost": 1.35e-06, "output_cost": 5.4e-06}, "azure_ai/deepseek-v3": {"max_tokens": 8192, "input_cost": 1.14e-06, "output_cost": 4.56e-06}, "azure_ai/deepseek-v3-0324": {"max_tokens": 8192, "input_cost": 1.14e-06, "output_cost": 4.56e-06}, "azure_ai/embed-v-4-0": {"max_tokens": 128000, "input_cost": 1.2e-07, "output_cost": 0.0}, "azure_ai/global/grok-3": {"max_tokens": 131072, "input_cost": 3e-06, "output_cost": 1.5e-05}, "azure_ai/global/grok-3-mini": {"max_tokens": 131072, "input_cost": 2.5e-07, "output_cost": 1.27e-06}, "azure_ai/grok-3": {"max_tokens": 131072, "input_cost": 3e-06, "output_cost": 1.5e-05}, "azure_ai/grok-3-mini": {"max_tokens": 131072, "input_cost": 2.5e-07, "output_cost": 1.27e-06}, "azure_ai/grok-4": {"max_tokens": 131072, "input_cost": 3e-06, "output_cost": 1.5e-05}, "azure_ai/grok-4-fast-non-reasoning": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 5e-07}, "azure_ai/grok-4-fast-reasoning": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 5e-07}, "azure_ai/grok-code-fast-1": {"max_tokens": 131072, "input_cost": 2e-07, "output_cost": 1.5e-06}, "azure_ai/jais-30b-chat": {"max_tokens": 8192, "input_cost": 0.0032, "output_cost": 0.00971}, "azure_ai/jamba-instruct": {"max_tokens": 4096, "input_cost": 5e-07, "output_cost": 7e-07}, "azure_ai/ministral-3b": {"max_tokens": 4096, "input_cost": 4e-08, "output_cost": 4e-08}, "azure_ai/mistral-large": {"max_tokens": 8191, "input_cost": 4e-06, "output_cost": 1.2e-05}, "azure_ai/mistral-large-2407": {"max_tokens": 4096, "input_cost": 2e-06, "output_cost": 6e-06}, "azure_ai/mistral-large-latest": {"max_tokens": 4096, "input_cost": 2e-06, "output_cost": 6e-06}, "azure_ai/mistral-large-3": {"max_tokens": 8191, "input_cost": 5e-07, "output_cost": 1.5e-06}, "azure_ai/mistral-medium-2505": {"max_tokens": 8191, "input_cost": 4e-07, "output_cost": 2e-06}, "azure_ai/mistral-nemo": {"max_tokens": 4096, "input_cost": 1.5e-07, "output_cost": 1.5e-07}, "azure_ai/mistral-small": {"max_tokens": 8191, "input_cost": 1e-06, "output_cost": 3e-06}, "azure_ai/mistral-small-2503": {"max_tokens": 128000, "input_cost": 1e-06, "output_cost": 3e-06}, "voyage/rerank-2": {"max_tokens": 16000, "input_cost": 5e-08, "output_cost": 0.0}, "voyage/rerank-2-lite": {"max_tokens": 8000, "input_cost": 2e-08, "output_cost": 0.0}, "voyage/rerank-2.5": {"max_tokens": 32000, "input_cost": 5e-08, "output_cost": 0.0}, "voyage/rerank-2.5-lite": {"max_tokens": 32000, "input_cost": 2e-08, "output_cost": 0.0}, "voyage/voyage-2": {"max_tokens": 4000, "input_cost": 1e-07, "output_cost": 0.0}, "voyage/voyage-3": {"max_tokens": 32000, "input_cost": 6e-08, "output_cost": 0.0}, "voyage/voyage-3-large": {"max_tokens": 32000, "input_cost": 1.8e-07, "output_cost": 0.0}, "voyage/voyage-3-lite": {"max_tokens": 32000, "input_cost": 2e-08, "output_cost": 0.0}, "voyage/voyage-3.5": {"max_tokens": 32000, "input_cost": 6e-08, "output_cost": 0.0}, "voyage/voyage-3.5-lite": {"max_tokens": 32000, "input_cost": 2e-08, "output_cost": 0.0}, "voyage/voyage-code-2": {"max_tokens": 16000, "input_cost": 1.2e-07, "output_cost": 0.0}, "voyage/voyage-code-3": {"max_tokens": 32000, "input_cost": 1.8e-07, "output_cost": 0.0}, "voyage/voyage-context-3": {"max_tokens": 120000, "input_cost": 1.8e-07, "output_cost": 0.0}, "voyage/voyage-finance-2": {"max_tokens": 32000, "input_cost": 1.2e-07, "output_cost": 0.0}, "voyage/voyage-large-2": {"max_tokens": 16000, "input_cost": 1.2e-07, "output_cost": 0.0}, "voyage/voyage-law-2": {"max_tokens": 16000, "input_cost": 1.2e-07, "output_cost": 0.0}, "voyage/voyage-lite-01": {"max_tokens": 4096, "input_cost": 1e-07, "output_cost": 0.0}, "voyage/voyage-lite-02-instruct": {"max_tokens": 4000, "input_cost": 1e-07, "output_cost": 0.0}, "voyage/voyage-multimodal-3": {"max_tokens": 32000, "input_cost": 1.2e-07, "output_cost": 0.0}, "databricks/databricks-bge-large-en": {"max_tokens": 512, "input_cost": 1.0003e-07, "output_cost": 0.0}, "databricks/databricks-claude-3-7-sonnet": {"max_tokens": 128000, "input_cost": 2.9999900000000002e-06, "output_cost": 1.5000020000000002e-05}, "databricks/databricks-claude-haiku-4-5": {"max_tokens": 64000, "input_cost": 1.00002e-06, "output_cost": 5.00003e-06}, "databricks/databricks-claude-opus-4": {"max_tokens": 32000, "input_cost": 1.5000020000000002e-05, "output_cost": 7.500003000000001e-05}, "databricks/databricks-claude-opus-4-1": {"max_tokens": 32000, "input_cost": 1.5000020000000002e-05, "output_cost": 7.500003000000001e-05}, "databricks/databricks-claude-opus-4-5": {"max_tokens": 64000, "input_cost": 5.00003e-06, "output_cost": 2.5000010000000002e-05}, "databricks/databricks-claude-sonnet-4": {"max_tokens": 64000, "input_cost": 2.9999900000000002e-06, "output_cost": 1.5000020000000002e-05}, "databricks/databricks-claude-sonnet-4-1": {"max_tokens": 64000, "input_cost": 2.9999900000000002e-06, "output_cost": 1.5000020000000002e-05}, "databricks/databricks-claude-sonnet-4-5": {"max_tokens": 64000, "input_cost": 2.9999900000000002e-06, "output_cost": 1.5000020000000002e-05}, "databricks/databricks-gemini-2-5-flash": {"max_tokens": 65535, "input_cost": 3.0001999999999996e-07, "output_cost": 2.49998e-06}, "databricks/databricks-gemini-2-5-pro": {"max_tokens": 65536, "input_cost": 1.24999e-06, "output_cost": 9.999990000000002e-06}, "databricks/databricks-gemma-3-12b": {"max_tokens": 32000, "input_cost": 1.5000999999999998e-07, "output_cost": 5.0001e-07}, "databricks/databricks-gpt-5": {"max_tokens": 128000, "input_cost": 1.24999e-06, "output_cost": 9.999990000000002e-06}, "databricks/databricks-gpt-5-1": {"max_tokens": 128000, "input_cost": 1.24999e-06, "output_cost": 9.999990000000002e-06}, "databricks/databricks-gpt-5-mini": {"max_tokens": 128000, "input_cost": 2.4997000000000006e-07, "output_cost": 1.9999700000000004e-06}, "databricks/databricks-gpt-5-nano": {"max_tokens": 128000, "input_cost": 4.998e-08, "output_cost": 3.9998000000000007e-07}, "databricks/databricks-gpt-oss-120b": {"max_tokens": 131072, "input_cost": 1.5000999999999998e-07, "output_cost": 5.9997e-07}, "databricks/databricks-gpt-oss-20b": {"max_tokens": 131072, "input_cost": 7e-08, "output_cost": 3.0001999999999996e-07}, "databricks/databricks-gte-large-en": {"max_tokens": 8192, "input_cost": 1.2999000000000001e-07, "output_cost": 0.0}, "databricks/databricks-llama-2-70b-chat": {"max_tokens": 4096, "input_cost": 5.0001e-07, "output_cost": 1.5000300000000002e-06}, "databricks/databricks-llama-4-maverick": {"max_tokens": 128000, "input_cost": 5.0001e-07, "output_cost": 1.5000300000000002e-06}, "databricks/databricks-meta-llama-3-1-405b-instruct": {"max_tokens": 128000, "input_cost": 5.00003e-06, "output_cost": 1.5000020000000002e-05}, "databricks/databricks-meta-llama-3-1-8b-instruct": {"max_tokens": 128000, "input_cost": 1.5000999999999998e-07, "output_cost": 4.5003000000000007e-07}, "databricks/databricks-meta-llama-3-3-70b-instruct": {"max_tokens": 128000, "input_cost": 5.0001e-07, "output_cost": 1.5000300000000002e-06}, "databricks/databricks-meta-llama-3-70b-instruct": {"max_tokens": 128000, "input_cost": 1.00002e-06, "output_cost": 2.9999900000000002e-06}, "databricks/databricks-mixtral-8x7b-instruct": {"max_tokens": 4096, "input_cost": 5.0001e-07, "output_cost": 1.00002e-06}, "databricks/databricks-mpt-30b-instruct": {"max_tokens": 8192, "input_cost": 1.00002e-06, "output_cost": 1.00002e-06}, "databricks/databricks-mpt-7b-instruct": {"max_tokens": 8192, "input_cost": 5.0001e-07, "output_cost": 0.0}, "cloudflare/@cf/meta/llama-2-7b-chat-fp16": {"max_tokens": 3072, "input_cost": 1.923e-06, "output_cost": 1.923e-06}, "cloudflare/@cf/meta/llama-2-7b-chat-int8": {"max_tokens": 2048, "input_cost": 1.923e-06, "output_cost": 1.923e-06}, "cloudflare/@cf/mistral/mistral-7b-instruct-v0.1": {"max_tokens": 8192, "input_cost": 1.923e-06, "output_cost": 1.923e-06}, "cloudflare/@hf/thebloke/codellama-7b-instruct-awq": {"max_tokens": 4096, "input_cost": 1.923e-06, "output_cost": 1.923e-06}, "codestral/codestral-2405": {"max_tokens": 8191, "input_cost": 0.0, "output_cost": 0.0}, "codestral/codestral-latest": {"max_tokens": 8191, "input_cost": 0.0, "output_cost": 0.0}, "chatdolphin": {"max_tokens": 16384, "input_cost": 5e-07, "output_cost": 5e-07}, "dolphin": {"max_tokens": 16384, "input_cost": 5e-07, "output_cost": 5e-07}, "friendliai/meta-llama-3.1-70b-instruct": {"max_tokens": 8192, "input_cost": 6e-07, "output_cost": 6e-07}, "friendliai/meta-llama-3.1-8b-instruct": {"max_tokens": 8192, "input_cost": 1e-07, "output_cost": 1e-07}, "palm/chat-bison": {"max_tokens": 4096, "input_cost": 1.25e-07, "output_cost": 1.25e-07}, "palm/chat-bison-001": {"max_tokens": 4096, "input_cost": 1.25e-07, "output_cost": 1.25e-07}, "palm/text-bison": {"max_tokens": 1024, "input_cost": 1.25e-07, "output_cost": 1.25e-07}, "palm/text-bison-001": {"max_tokens": 1024, "input_cost": 1.25e-07, "output_cost": 1.25e-07}, "palm/text-bison-safety-off": {"max_tokens": 1024, "input_cost": 1.25e-07, "output_cost": 1.25e-07}, "palm/text-bison-safety-recitation-off": {"max_tokens": 1024, "input_cost": 1.25e-07, "output_cost": 1.25e-07}, "groq/llama-3.1-8b-instant": {"max_tokens": 8192, "input_cost": 5e-08, "output_cost": 8e-08}, "groq/llama-3.3-70b-versatile": {"max_tokens": 32768, "input_cost": 5.9e-07, "output_cost": 7.9e-07}, "groq/gemma-7b-it": {"max_tokens": 8192, "input_cost": 5e-08, "output_cost": 8e-08}, "groq/meta-llama/llama-guard-4-12b": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 2e-07}, "groq/meta-llama/llama-4-maverick-17b-128e-instruct": {"max_tokens": 8192, "input_cost": 2e-07, "output_cost": 6e-07}, "groq/meta-llama/llama-4-scout-17b-16e-instruct": {"max_tokens": 8192, "input_cost": 1.1e-07, "output_cost": 3.4e-07}, "groq/moonshotai/kimi-k2-instruct-0905": {"max_tokens": 16384, "input_cost": 1e-06, "output_cost": 3e-06}, "groq/openai/gpt-oss-120b": {"max_tokens": 32766, "input_cost": 1.5e-07, "output_cost": 6e-07}, "groq/openai/gpt-oss-20b": {"max_tokens": 32768, "input_cost": 7.5e-08, "output_cost": 3e-07}, "groq/playai-tts": {"max_tokens": 10000, "input_cost": 0, "output_cost": 0}, "groq/qwen/qwen3-32b": {"max_tokens": 131000, "input_cost": 2.9e-07, "output_cost": 5.9e-07}, "groq/whisper-large-v3": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "groq/whisper-large-v3-turbo": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/ada": {"max_tokens": 8191, "input_cost": 1e-07, "output_cost": 0.0}, "azure/codex-mini": {"max_tokens": 100000, "input_cost": 1.5e-06, "output_cost": 6e-06}, "azure/command-r-plus": {"max_tokens": 4096, "input_cost": 3e-06, "output_cost": 1.5e-05}, "azure/computer-use-preview": {"max_tokens": 1024, "input_cost": 3e-06, "output_cost": 1.2e-05}, "azure/container": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/eu/gpt-4o-2024-08-06": {"max_tokens": 16384, "input_cost": 2.75e-06, "output_cost": 1.1e-05}, "azure/eu/gpt-4o-2024-11-20": {"max_tokens": 16384, "input_cost": 2.75e-06, "output_cost": 1.1e-05}, "azure/eu/gpt-4o-mini-2024-07-18": {"max_tokens": 16384, "input_cost": 1.65e-07, "output_cost": 6.6e-07}, "azure/eu/gpt-4o-mini-realtime-preview-2024-12-17": {"max_tokens": 4096, "input_cost": 6.6e-07, "output_cost": 2.64e-06}, "azure/eu/gpt-4o-realtime-preview-2024-10-01": {"max_tokens": 4096, "input_cost": 5.5e-06, "output_cost": 2.2e-05}, "azure/eu/gpt-4o-realtime-preview-2024-12-17": {"max_tokens": 4096, "input_cost": 5.5e-06, "output_cost": 2.2e-05}, "azure/eu/gpt-5-2025-08-07": {"max_tokens": 128000, "input_cost": 1.375e-06, "output_cost": 1.1e-05}, "azure/eu/gpt-5-mini-2025-08-07": {"max_tokens": 128000, "input_cost": 2.75e-07, "output_cost": 2.2e-06}, "azure/eu/gpt-5.1": {"max_tokens": 128000, "input_cost": 1.38e-06, "output_cost": 1.1e-05}, "azure/eu/gpt-5.1-chat": {"max_tokens": 128000, "input_cost": 1.38e-06, "output_cost": 1.1e-05}, "azure/eu/gpt-5.1-codex": {"max_tokens": 128000, "input_cost": 1.38e-06, "output_cost": 1.1e-05}, "azure/eu/gpt-5.1-codex-mini": {"max_tokens": 128000, "input_cost": 2.75e-07, "output_cost": 2.2e-06}, "azure/eu/gpt-5-nano-2025-08-07": {"max_tokens": 128000, "input_cost": 5.5e-08, "output_cost": 4.4e-07}, "azure/eu/o1-2024-12-17": {"max_tokens": 100000, "input_cost": 1.65e-05, "output_cost": 6.6e-05}, "azure/eu/o1-mini-2024-09-12": {"max_tokens": 65536, "input_cost": 1.21e-06, "output_cost": 4.84e-06}, "azure/eu/o1-preview-2024-09-12": {"max_tokens": 32768, "input_cost": 1.65e-05, "output_cost": 6.6e-05}, "azure/eu/o3-mini-2025-01-31": {"max_tokens": 100000, "input_cost": 1.21e-06, "output_cost": 4.84e-06}, "azure/global-standard/gpt-4o-2024-08-06": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "azure/global-standard/gpt-4o-2024-11-20": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "azure/global-standard/gpt-4o-mini": {"max_tokens": 16384, "input_cost": 1.5e-07, "output_cost": 6e-07}, "azure/global/gpt-4o-2024-08-06": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "azure/global/gpt-4o-2024-11-20": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "azure/global/gpt-5.1": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "azure/global/gpt-5.1-chat": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "azure/global/gpt-5.1-codex": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "azure/global/gpt-5.1-codex-mini": {"max_tokens": 128000, "input_cost": 2.5e-07, "output_cost": 2e-06}, "azure/gpt-3.5-turbo": {"max_tokens": 4096, "input_cost": 5e-07, "output_cost": 1.5e-06}, "azure/gpt-3.5-turbo-0125": {"max_tokens": 4096, "input_cost": 5e-07, "output_cost": 1.5e-06}, "azure/gpt-35-turbo": {"max_tokens": 4096, "input_cost": 5e-07, "output_cost": 1.5e-06}, "azure/gpt-35-turbo-0125": {"max_tokens": 4096, "input_cost": 5e-07, "output_cost": 1.5e-06}, "azure/gpt-35-turbo-0301": {"max_tokens": 4096, "input_cost": 2e-07, "output_cost": 2e-06}, "azure/gpt-35-turbo-0613": {"max_tokens": 4096, "input_cost": 1.5e-06, "output_cost": 2e-06}, "azure/gpt-35-turbo-1106": {"max_tokens": 4096, "input_cost": 1e-06, "output_cost": 2e-06}, "azure/gpt-35-turbo-16k": {"max_tokens": 4096, "input_cost": 3e-06, "output_cost": 4e-06}, "azure/gpt-35-turbo-16k-0613": {"max_tokens": 4096, "input_cost": 3e-06, "output_cost": 4e-06}, "azure/gpt-4": {"max_tokens": 4096, "input_cost": 3e-05, "output_cost": 6e-05}, "azure/gpt-4-0125-preview": {"max_tokens": 4096, "input_cost": 1e-05, "output_cost": 3e-05}, "azure/gpt-4-0613": {"max_tokens": 4096, "input_cost": 3e-05, "output_cost": 6e-05}, "azure/gpt-4-1106-preview": {"max_tokens": 4096, "input_cost": 1e-05, "output_cost": 3e-05}, "azure/gpt-4-32k": {"max_tokens": 4096, "input_cost": 6e-05, "output_cost": 0.00012}, "azure/gpt-4-32k-0613": {"max_tokens": 4096, "input_cost": 6e-05, "output_cost": 0.00012}, "azure/gpt-4-turbo": {"max_tokens": 4096, "input_cost": 1e-05, "output_cost": 3e-05}, "azure/gpt-4-turbo-2024-04-09": {"max_tokens": 4096, "input_cost": 1e-05, "output_cost": 3e-05}, "azure/gpt-4-turbo-vision-preview": {"max_tokens": 4096, "input_cost": 1e-05, "output_cost": 3e-05}, "azure/gpt-4.1": {"max_tokens": 32768, "input_cost": 2e-06, "output_cost": 8e-06}, "azure/gpt-4.1-2025-04-14": {"max_tokens": 32768, "input_cost": 2e-06, "output_cost": 8e-06}, "azure/gpt-4.1-mini": {"max_tokens": 32768, "input_cost": 4e-07, "output_cost": 1.6e-06}, "azure/gpt-4.1-mini-2025-04-14": {"max_tokens": 32768, "input_cost": 4e-07, "output_cost": 1.6e-06}, "azure/gpt-4.1-nano": {"max_tokens": 32768, "input_cost": 1e-07, "output_cost": 4e-07}, "azure/gpt-4.1-nano-2025-04-14": {"max_tokens": 32768, "input_cost": 1e-07, "output_cost": 4e-07}, "azure/gpt-4.5-preview": {"max_tokens": 16384, "input_cost": 7.5e-05, "output_cost": 0.00015}, "azure/gpt-4o": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "azure/gpt-4o-2024-05-13": {"max_tokens": 4096, "input_cost": 5e-06, "output_cost": 1.5e-05}, "azure/gpt-4o-2024-08-06": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "azure/gpt-4o-2024-11-20": {"max_tokens": 16384, "input_cost": 2.75e-06, "output_cost": 1.1e-05}, "azure/gpt-audio-2025-08-28": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "azure/gpt-audio-mini-2025-10-06": {"max_tokens": 16384, "input_cost": 6e-07, "output_cost": 2.4e-06}, "azure/gpt-4o-audio-preview-2024-12-17": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "azure/gpt-4o-mini": {"max_tokens": 16384, "input_cost": 1.65e-07, "output_cost": 6.6e-07}, "azure/gpt-4o-mini-2024-07-18": {"max_tokens": 16384, "input_cost": 1.65e-07, "output_cost": 6.6e-07}, "azure/gpt-4o-mini-audio-preview-2024-12-17": {"max_tokens": 16384, "input_cost": 2.5e-06, "output_cost": 1e-05}, "azure/gpt-4o-mini-realtime-preview-2024-12-17": {"max_tokens": 4096, "input_cost": 6e-07, "output_cost": 2.4e-06}, "azure/gpt-realtime-2025-08-28": {"max_tokens": 4096, "input_cost": 4e-06, "output_cost": 1.6e-05}, "azure/gpt-realtime-mini-2025-10-06": {"max_tokens": 4096, "input_cost": 6e-07, "output_cost": 2.4e-06}, "azure/gpt-4o-mini-transcribe": {"max_tokens": 16000, "input_cost": 1.25e-06, "output_cost": 5e-06}, "azure/gpt-4o-mini-tts": {"max_tokens": 0, "input_cost": 2.5e-06, "output_cost": 1e-05}, "azure/gpt-4o-realtime-preview-2024-10-01": {"max_tokens": 4096, "input_cost": 5e-06, "output_cost": 2e-05}, "azure/gpt-4o-realtime-preview-2024-12-17": {"max_tokens": 4096, "input_cost": 5e-06, "output_cost": 2e-05}, "azure/gpt-4o-transcribe": {"max_tokens": 16000, "input_cost": 2.5e-06, "output_cost": 1e-05}, "azure/gpt-4o-transcribe-diarize": {"max_tokens": 16000, "input_cost": 2.5e-06, "output_cost": 1e-05}, "azure/gpt-5.1-2025-11-13": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "azure/gpt-5.1-chat-2025-11-13": {"max_tokens": 16384, "input_cost": 1.25e-06, "output_cost": 1e-05}, "azure/gpt-5.1-codex-2025-11-13": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "azure/gpt-5.1-codex-mini-2025-11-13": {"max_tokens": 128000, "input_cost": 2.5e-07, "output_cost": 2e-06}, "azure/gpt-5": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "azure/gpt-5-2025-08-07": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "azure/gpt-5-chat": {"max_tokens": 16384, "input_cost": 1.25e-06, "output_cost": 1e-05}, "azure/gpt-5-chat-latest": {"max_tokens": 16384, "input_cost": 1.25e-06, "output_cost": 1e-05}, "azure/gpt-5-codex": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "azure/gpt-5-mini": {"max_tokens": 128000, "input_cost": 2.5e-07, "output_cost": 2e-06}, "azure/gpt-5-mini-2025-08-07": {"max_tokens": 128000, "input_cost": 2.5e-07, "output_cost": 2e-06}, "azure/gpt-5-nano": {"max_tokens": 128000, "input_cost": 5e-08, "output_cost": 4e-07}, "azure/gpt-5-nano-2025-08-07": {"max_tokens": 128000, "input_cost": 5e-08, "output_cost": 4e-07}, "azure/gpt-5-pro": {"max_tokens": 128000, "input_cost": 1.5e-05, "output_cost": 0.00012}, "azure/gpt-5.1": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "azure/gpt-5.1-chat": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "azure/gpt-5.1-codex": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "azure/gpt-5.1-codex-max": {"max_tokens": 128000, "input_cost": 1.25e-06, "output_cost": 1e-05}, "azure/gpt-5.1-codex-mini": {"max_tokens": 128000, "input_cost": 2.5e-07, "output_cost": 2e-06}, "azure/gpt-5.2": {"max_tokens": 128000, "input_cost": 1.75e-06, "output_cost": 1.4e-05}, "azure/gpt-5.2-2025-12-11": {"max_tokens": 128000, "input_cost": 1.75e-06, "output_cost": 1.4e-05}, "azure/gpt-5.2-chat": {"max_tokens": 16384, "input_cost": 1.75e-06, "output_cost": 1.4e-05}, "azure/gpt-5.2-chat-2025-12-11": {"max_tokens": 16384, "input_cost": 1.75e-06, "output_cost": 1.4e-05}, "azure/gpt-5.2-codex": {"max_tokens": 16384, "input_cost": 1.75e-06, "output_cost": 1.4e-05}, "azure/gpt-5.2-pro": {"max_tokens": 128000, "input_cost": 2.1e-05, "output_cost": 0.000168}, "azure/gpt-5.2-pro-2025-12-11": {"max_tokens": 128000, "input_cost": 2.1e-05, "output_cost": 0.000168}, "azure/gpt-image-1": {"max_tokens": 0, "input_cost": 5e-06, "output_cost": 0}, "azure/hd/1024-x-1024/dall-e-3": {"max_tokens": 0, "input_cost": 0, "output_cost": 0.0}, "azure/hd/1024-x-1792/dall-e-3": {"max_tokens": 0, "input_cost": 0, "output_cost": 0.0}, "azure/hd/1792-x-1024/dall-e-3": {"max_tokens": 0, "input_cost": 0, "output_cost": 0.0}, "azure/high/1024-x-1024/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/high/1024-x-1536/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/high/1536-x-1024/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/low/1024-x-1024/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/low/1024-x-1536/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/low/1536-x-1024/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/medium/1024-x-1024/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/medium/1024-x-1536/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/medium/1536-x-1024/gpt-image-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 2e-06, "output_cost": 0}, "azure/gpt-image-1.5": {"max_tokens": 0, "input_cost": 5e-06, "output_cost": 0}, "azure/gpt-image-1.5-2025-12-16": {"max_tokens": 0, "input_cost": 5e-06, "output_cost": 0}, "azure/low/1024-x-1024/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/low/1024-x-1536/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/low/1536-x-1024/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/medium/1024-x-1024/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/medium/1024-x-1536/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/medium/1536-x-1024/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/high/1024-x-1024/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/high/1024-x-1536/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/high/1536-x-1024/gpt-image-1-mini": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/mistral-large-2402": {"max_tokens": 32000, "input_cost": 8e-06, "output_cost": 2.4e-05}, "azure/mistral-large-latest": {"max_tokens": 32000, "input_cost": 8e-06, "output_cost": 2.4e-05}, "azure/o1": {"max_tokens": 100000, "input_cost": 1.5e-05, "output_cost": 6e-05}, "azure/o1-2024-12-17": {"max_tokens": 100000, "input_cost": 1.5e-05, "output_cost": 6e-05}, "azure/o1-mini": {"max_tokens": 65536, "input_cost": 1.21e-06, "output_cost": 4.84e-06}, "azure/o1-mini-2024-09-12": {"max_tokens": 65536, "input_cost": 1.1e-06, "output_cost": 4.4e-06}, "azure/o1-preview": {"max_tokens": 32768, "input_cost": 1.5e-05, "output_cost": 6e-05}, "azure/o1-preview-2024-09-12": {"max_tokens": 32768, "input_cost": 1.5e-05, "output_cost": 6e-05}, "azure/o3": {"max_tokens": 100000, "input_cost": 2e-06, "output_cost": 8e-06}, "azure/o3-2025-04-16": {"max_tokens": 100000, "input_cost": 2e-06, "output_cost": 8e-06}, "azure/o3-deep-research": {"max_tokens": 100000, "input_cost": 1e-05, "output_cost": 4e-05}, "azure/o3-mini": {"max_tokens": 100000, "input_cost": 1.1e-06, "output_cost": 4.4e-06}, "azure/o3-mini-2025-01-31": {"max_tokens": 100000, "input_cost": 1.1e-06, "output_cost": 4.4e-06}, "azure/o3-pro": {"max_tokens": 100000, "input_cost": 2e-05, "output_cost": 8e-05}, "azure/o3-pro-2025-06-10": {"max_tokens": 100000, "input_cost": 2e-05, "output_cost": 8e-05}, "azure/o4-mini": {"max_tokens": 100000, "input_cost": 1.1e-06, "output_cost": 4.4e-06}, "azure/o4-mini-2025-04-16": {"max_tokens": 100000, "input_cost": 1.1e-06, "output_cost": 4.4e-06}, "azure/standard/1024-x-1024/dall-e-2": {"max_tokens": 0, "input_cost": 0, "output_cost": 0.0}, "azure/standard/1024-x-1024/dall-e-3": {"max_tokens": 0, "input_cost": 0, "output_cost": 0.0}, "azure/standard/1024-x-1792/dall-e-3": {"max_tokens": 0, "input_cost": 0, "output_cost": 0.0}, "azure/standard/1792-x-1024/dall-e-3": {"max_tokens": 0, "input_cost": 0, "output_cost": 0.0}, "azure/text-embedding-3-large": {"max_tokens": 8191, "input_cost": 1.3e-07, "output_cost": 0.0}, "azure/text-embedding-3-small": {"max_tokens": 8191, "input_cost": 2e-08, "output_cost": 0.0}, "azure/text-embedding-ada-002": {"max_tokens": 8191, "input_cost": 1e-07, "output_cost": 0.0}, "azure/speech/azure-tts": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/speech/azure-tts-hd": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/tts-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/tts-1-hd": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/us/gpt-4.1-2025-04-14": {"max_tokens": 32768, "input_cost": 2.2e-06, "output_cost": 8.8e-06}, "azure/us/gpt-4.1-mini-2025-04-14": {"max_tokens": 32768, "input_cost": 4.4e-07, "output_cost": 1.76e-06}, "azure/us/gpt-4.1-nano-2025-04-14": {"max_tokens": 32768, "input_cost": 1.1e-07, "output_cost": 4.4e-07}, "azure/us/gpt-4o-2024-08-06": {"max_tokens": 16384, "input_cost": 2.75e-06, "output_cost": 1.1e-05}, "azure/us/gpt-4o-2024-11-20": {"max_tokens": 16384, "input_cost": 2.75e-06, "output_cost": 1.1e-05}, "azure/us/gpt-4o-mini-2024-07-18": {"max_tokens": 16384, "input_cost": 1.65e-07, "output_cost": 6.6e-07}, "azure/us/gpt-4o-mini-realtime-preview-2024-12-17": {"max_tokens": 4096, "input_cost": 6.6e-07, "output_cost": 2.64e-06}, "azure/us/gpt-4o-realtime-preview-2024-10-01": {"max_tokens": 4096, "input_cost": 5.5e-06, "output_cost": 2.2e-05}, "azure/us/gpt-4o-realtime-preview-2024-12-17": {"max_tokens": 4096, "input_cost": 5.5e-06, "output_cost": 2.2e-05}, "azure/us/gpt-5-2025-08-07": {"max_tokens": 128000, "input_cost": 1.375e-06, "output_cost": 1.1e-05}, "azure/us/gpt-5-mini-2025-08-07": {"max_tokens": 128000, "input_cost": 2.75e-07, "output_cost": 2.2e-06}, "azure/us/gpt-5-nano-2025-08-07": {"max_tokens": 128000, "input_cost": 5.5e-08, "output_cost": 4.4e-07}, "azure/us/gpt-5.1": {"max_tokens": 128000, "input_cost": 1.38e-06, "output_cost": 1.1e-05}, "azure/us/gpt-5.1-chat": {"max_tokens": 128000, "input_cost": 1.38e-06, "output_cost": 1.1e-05}, "azure/us/gpt-5.1-codex": {"max_tokens": 128000, "input_cost": 1.38e-06, "output_cost": 1.1e-05}, "azure/us/gpt-5.1-codex-mini": {"max_tokens": 128000, "input_cost": 2.75e-07, "output_cost": 2.2e-06}, "azure/us/o1-2024-12-17": {"max_tokens": 100000, "input_cost": 1.65e-05, "output_cost": 6.6e-05}, "azure/us/o1-mini-2024-09-12": {"max_tokens": 65536, "input_cost": 1.21e-06, "output_cost": 4.84e-06}, "azure/us/o1-preview-2024-09-12": {"max_tokens": 32768, "input_cost": 1.65e-05, "output_cost": 6.6e-05}, "azure/us/o3-2025-04-16": {"max_tokens": 100000, "input_cost": 2.2e-06, "output_cost": 8.8e-06}, "azure/us/o3-mini-2025-01-31": {"max_tokens": 100000, "input_cost": 1.21e-06, "output_cost": 4.84e-06}, "azure/us/o4-mini-2025-04-16": {"max_tokens": 100000, "input_cost": 1.21e-06, "output_cost": 4.84e-06}, "azure/whisper-1": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "computer-use-preview": {"max_tokens": 1024, "input_cost": 3e-06, "output_cost": 1.2e-05}, "azure/sora-2": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/sora-2-pro": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/sora-2-pro-high-res": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "azure/gpt-3.5-turbo-instruct-0914": {"max_tokens": 4097, "input_cost": 1.5e-06, "output_cost": 2e-06}, "azure/gpt-35-turbo-instruct": {"max_tokens": 4097, "input_cost": 1.5e-06, "output_cost": 2e-06}, "azure/gpt-35-turbo-instruct-0914": {"max_tokens": 4097, "input_cost": 1.5e-06, "output_cost": 2e-06}, "anyscale/HuggingFaceH4/zephyr-7b-beta": {"max_tokens": 16384, "input_cost": 1.5e-07, "output_cost": 1.5e-07}, "anyscale/codellama/CodeLlama-34b-Instruct-hf": {"max_tokens": 4096, "input_cost": 1e-06, "output_cost": 1e-06}, "anyscale/codellama/CodeLlama-70b-Instruct-hf": {"max_tokens": 4096, "input_cost": 1e-06, "output_cost": 1e-06}, "anyscale/google/gemma-7b-it": {"max_tokens": 8192, "input_cost": 1.5e-07, "output_cost": 1.5e-07}, "anyscale/meta-llama/Llama-2-13b-chat-hf": {"max_tokens": 4096, "input_cost": 2.5e-07, "output_cost": 2.5e-07}, "anyscale/meta-llama/Llama-2-70b-chat-hf": {"max_tokens": 4096, "input_cost": 1e-06, "output_cost": 1e-06}, "anyscale/meta-llama/Llama-2-7b-chat-hf": {"max_tokens": 4096, "input_cost": 1.5e-07, "output_cost": 1.5e-07}, "anyscale/meta-llama/Meta-Llama-3-70B-Instruct": {"max_tokens": 8192, "input_cost": 1e-06, "output_cost": 1e-06}, "anyscale/meta-llama/Meta-Llama-3-8B-Instruct": {"max_tokens": 8192, "input_cost": 1.5e-07, "output_cost": 1.5e-07}, "anyscale/mistralai/Mistral-7B-Instruct-v0.1": {"max_tokens": 16384, "input_cost": 1.5e-07, "output_cost": 1.5e-07}, "anyscale/mistralai/Mixtral-8x22B-Instruct-v0.1": {"max_tokens": 65536, "input_cost": 9e-07, "output_cost": 9e-07}, "anyscale/mistralai/Mixtral-8x7B-Instruct-v0.1": {"max_tokens": 16384, "input_cost": 1.5e-07, "output_cost": 1.5e-07}, "cerebras/llama-3.3-70b": {"max_tokens": 128000, "input_cost": 8.5e-07, "output_cost": 1.2e-06}, "cerebras/llama3.1-70b": {"max_tokens": 128000, "input_cost": 6e-07, "output_cost": 6e-07}, "cerebras/llama3.1-8b": {"max_tokens": 128000, "input_cost": 1e-07, "output_cost": 1e-07}, "cerebras/gpt-oss-120b": {"max_tokens": 32768, "input_cost": 2.5e-07, "output_cost": 6.9e-07}, "cerebras/qwen-3-32b": {"max_tokens": 128000, "input_cost": 4e-07, "output_cost": 8e-07}, "cerebras/zai-glm-4.6": {"max_tokens": 128000, "input_cost": 2.25e-06, "output_cost": 2.75e-06}, "cerebras/zai-glm-4.7": {"max_tokens": 128000, "input_cost": 2.25e-06, "output_cost": 2.75e-06}, "sambanova/DeepSeek-R1": {"max_tokens": 32768, "input_cost": 5e-06, "output_cost": 7e-06}, "sambanova/DeepSeek-R1-Distill-Llama-70B": {"max_tokens": 131072, "input_cost": 7e-07, "output_cost": 1.4e-06}, "sambanova/DeepSeek-V3-0324": {"max_tokens": 32768, "input_cost": 3e-06, "output_cost": 4.5e-06}, "sambanova/Llama-4-Maverick-17B-128E-Instruct": {"max_tokens": 131072, "input_cost": 6.3e-07, "output_cost": 1.8e-06}, "sambanova/Llama-4-Scout-17B-16E-Instruct": {"max_tokens": 8192, "input_cost": 4e-07, "output_cost": 7e-07}, "sambanova/Meta-Llama-3.1-405B-Instruct": {"max_tokens": 16384, "input_cost": 5e-06, "output_cost": 1e-05}, "sambanova/Meta-Llama-3.1-8B-Instruct": {"max_tokens": 16384, "input_cost": 1e-07, "output_cost": 2e-07}, "sambanova/Meta-Llama-3.2-1B-Instruct": {"max_tokens": 16384, "input_cost": 4e-08, "output_cost": 8e-08}, "sambanova/Meta-Llama-3.2-3B-Instruct": {"max_tokens": 4096, "input_cost": 8e-08, "output_cost": 1.6e-07}, "sambanova/Meta-Llama-3.3-70B-Instruct": {"max_tokens": 131072, "input_cost": 6e-07, "output_cost": 1.2e-06}, "sambanova/Meta-Llama-Guard-3-8B": {"max_tokens": 16384, "input_cost": 3e-07, "output_cost": 3e-07}, "sambanova/QwQ-32B": {"max_tokens": 16384, "input_cost": 5e-07, "output_cost": 1e-06}, "sambanova/Qwen2-Audio-7B-Instruct": {"max_tokens": 4096, "input_cost": 5e-07, "output_cost": 0.0001}, "sambanova/Qwen3-32B": {"max_tokens": 8192, "input_cost": 4e-07, "output_cost": 8e-07}, "sambanova/DeepSeek-V3.1": {"max_tokens": 32768, "input_cost": 3e-06, "output_cost": 4.5e-06}, "sambanova/gpt-oss-120b": {"max_tokens": 131072, "input_cost": 3e-06, "output_cost": 4.5e-06}, "novita/deepseek/deepseek-v3.2": {"max_tokens": 65536, "input_cost": 2.69e-07, "output_cost": 4e-07}, "novita/minimax/minimax-m2.1": {"max_tokens": 131072, "input_cost": 3e-07, "output_cost": 1.2e-06}, "novita/zai-org/glm-4.7": {"max_tokens": 131072, "input_cost": 6e-07, "output_cost": 2.2e-06}, "novita/xiaomimimo/mimo-v2-flash": {"max_tokens": 32000, "input_cost": 1e-07, "output_cost": 3e-07}, "novita/zai-org/autoglm-phone-9b-multilingual": {"max_tokens": 65536, "input_cost": 3.5e-08, "output_cost": 1.38e-07}, "novita/moonshotai/kimi-k2-thinking": {"max_tokens": 262144, "input_cost": 6e-07, "output_cost": 2.5e-06}, "novita/minimax/minimax-m2": {"max_tokens": 131072, "input_cost": 3e-07, "output_cost": 1.2e-06}, "novita/paddlepaddle/paddleocr-vl": {"max_tokens": 16384, "input_cost": 2e-08, "output_cost": 2e-08}, "novita/deepseek/deepseek-v3.2-exp": {"max_tokens": 65536, "input_cost": 2.7e-07, "output_cost": 4.1e-07}, "novita/qwen/qwen3-vl-235b-a22b-thinking": {"max_tokens": 32768, "input_cost": 9.8e-07, "output_cost": 3.95e-06}, "novita/zai-org/glm-4.6v": {"max_tokens": 32768, "input_cost": 3e-07, "output_cost": 9e-07}, "novita/zai-org/glm-4.6": {"max_tokens": 131072, "input_cost": 5.5e-07, "output_cost": 2.2e-06}, "novita/kwaipilot/kat-coder-pro": {"max_tokens": 128000, "input_cost": 3e-07, "output_cost": 1.2e-06}, "novita/qwen/qwen3-next-80b-a3b-instruct": {"max_tokens": 32768, "input_cost": 1.5e-07, "output_cost": 1.5e-06}, "novita/qwen/qwen3-next-80b-a3b-thinking": {"max_tokens": 32768, "input_cost": 1.5e-07, "output_cost": 1.5e-06}, "novita/deepseek/deepseek-ocr": {"max_tokens": 8192, "input_cost": 3e-08, "output_cost": 3e-08}, "novita/deepseek/deepseek-v3.1-terminus": {"max_tokens": 32768, "input_cost": 2.7e-07, "output_cost": 1e-06}, "novita/qwen/qwen3-vl-235b-a22b-instruct": {"max_tokens": 32768, "input_cost": 3e-07, "output_cost": 1.5e-06}, "novita/qwen/qwen3-max": {"max_tokens": 65536, "input_cost": 2.11e-06, "output_cost": 8.45e-06}, "novita/skywork/r1v4-lite": {"max_tokens": 65536, "input_cost": 2e-07, "output_cost": 6e-07}, "novita/deepseek/deepseek-v3.1": {"max_tokens": 32768, "input_cost": 2.7e-07, "output_cost": 1e-06}, "novita/moonshotai/kimi-k2-0905": {"max_tokens": 262144, "input_cost": 6e-07, "output_cost": 2.5e-06}, "novita/qwen/qwen3-coder-480b-a35b-instruct": {"max_tokens": 65536, "input_cost": 3e-07, "output_cost": 1.3e-06}, "novita/qwen/qwen3-coder-30b-a3b-instruct": {"max_tokens": 32768, "input_cost": 7e-08, "output_cost": 2.7e-07}, "novita/openai/gpt-oss-120b": {"max_tokens": 32768, "input_cost": 5e-08, "output_cost": 2.5e-07}, "novita/moonshotai/kimi-k2-instruct": {"max_tokens": 131072, "input_cost": 5.7e-07, "output_cost": 2.3e-06}, "novita/deepseek/deepseek-v3-0324": {"max_tokens": 163840, "input_cost": 2.7e-07, "output_cost": 1.12e-06}, "novita/zai-org/glm-4.5": {"max_tokens": 98304, "input_cost": 6e-07, "output_cost": 2.2e-06}, "novita/qwen/qwen3-235b-a22b-thinking-2507": {"max_tokens": 32768, "input_cost": 3e-07, "output_cost": 3e-06}, "novita/meta-llama/llama-3.1-8b-instruct": {"max_tokens": 16384, "input_cost": 2e-08, "output_cost": 5e-08}, "novita/google/gemma-3-12b-it": {"max_tokens": 8192, "input_cost": 5e-08, "output_cost": 1e-07}, "novita/zai-org/glm-4.5v": {"max_tokens": 16384, "input_cost": 6e-07, "output_cost": 1.8e-06}, "novita/openai/gpt-oss-20b": {"max_tokens": 32768, "input_cost": 4e-08, "output_cost": 1.5e-07}, "novita/qwen/qwen3-235b-a22b-instruct-2507": {"max_tokens": 16384, "input_cost": 9e-08, "output_cost": 5.8e-07}, "novita/deepseek/deepseek-r1-distill-qwen-14b": {"max_tokens": 16384, "input_cost": 1.5e-07, "output_cost": 1.5e-07}, "novita/meta-llama/llama-3.3-70b-instruct": {"max_tokens": 120000, "input_cost": 1.35e-07, "output_cost": 4e-07}, "novita/qwen/qwen-2.5-72b-instruct": {"max_tokens": 8192, "input_cost": 3.8e-07, "output_cost": 4e-07}, "novita/mistralai/mistral-nemo": {"max_tokens": 16000, "input_cost": 4e-08, "output_cost": 1.7e-07}, "novita/minimaxai/minimax-m1-80k": {"max_tokens": 40000, "input_cost": 5.5e-07, "output_cost": 2.2e-06}, "novita/deepseek/deepseek-r1-0528": {"max_tokens": 32768, "input_cost": 7e-07, "output_cost": 2.5e-06}, "novita/deepseek/deepseek-r1-distill-qwen-32b": {"max_tokens": 32000, "input_cost": 3e-07, "output_cost": 3e-07}, "novita/meta-llama/llama-3-8b-instruct": {"max_tokens": 8192, "input_cost": 4e-08, "output_cost": 4e-08}, "novita/microsoft/wizardlm-2-8x22b": {"max_tokens": 8000, "input_cost": 6.2e-07, "output_cost": 6.2e-07}, "novita/deepseek/deepseek-r1-0528-qwen3-8b": {"max_tokens": 32000, "input_cost": 6e-08, "output_cost": 9e-08}, "novita/deepseek/deepseek-r1-distill-llama-70b": {"max_tokens": 8192, "input_cost": 8e-07, "output_cost": 8e-07}, "novita/meta-llama/llama-3-70b-instruct": {"max_tokens": 8000, "input_cost": 5.1e-07, "output_cost": 7.4e-07}, "novita/qwen/qwen3-235b-a22b-fp8": {"max_tokens": 20000, "input_cost": 2e-07, "output_cost": 8e-07}, "novita/meta-llama/llama-4-maverick-17b-128e-instruct-fp8": {"max_tokens": 8192, "input_cost": 2.7e-07, "output_cost": 8.5e-07}, "novita/meta-llama/llama-4-scout-17b-16e-instruct": {"max_tokens": 131072, "input_cost": 1.8e-07, "output_cost": 5.9e-07}, "novita/nousresearch/hermes-2-pro-llama-3-8b": {"max_tokens": 8192, "input_cost": 1.4e-07, "output_cost": 1.4e-07}, "novita/qwen/qwen2.5-vl-72b-instruct": {"max_tokens": 32768, "input_cost": 8e-07, "output_cost": 8e-07}, "novita/sao10k/l3-70b-euryale-v2.1": {"max_tokens": 8192, "input_cost": 1.48e-06, "output_cost": 1.48e-06}, "novita/baidu/ernie-4.5-21B-a3b-thinking": {"max_tokens": 65536, "input_cost": 7e-08, "output_cost": 2.8e-07}, "novita/sao10k/l3-8b-lunaris": {"max_tokens": 8192, "input_cost": 5e-08, "output_cost": 5e-08}, "novita/baichuan/baichuan-m2-32b": {"max_tokens": 131072, "input_cost": 7e-08, "output_cost": 7e-08}, "novita/baidu/ernie-4.5-vl-424b-a47b": {"max_tokens": 16000, "input_cost": 4.2e-07, "output_cost": 1.25e-06}, "novita/baidu/ernie-4.5-300b-a47b-paddle": {"max_tokens": 12000, "input_cost": 2.8e-07, "output_cost": 1.1e-06}, "novita/deepseek/deepseek-prover-v2-671b": {"max_tokens": 160000, "input_cost": 7e-07, "output_cost": 2.5e-06}, "novita/qwen/qwen3-32b-fp8": {"max_tokens": 20000, "input_cost": 1e-07, "output_cost": 4.5e-07}, "novita/qwen/qwen3-30b-a3b-fp8": {"max_tokens": 20000, "input_cost": 9e-08, "output_cost": 4.5e-07}, "novita/google/gemma-3-27b-it": {"max_tokens": 16384, "input_cost": 1.19e-07, "output_cost": 2e-07}, "novita/deepseek/deepseek-v3-turbo": {"max_tokens": 16000, "input_cost": 4e-07, "output_cost": 1.3e-06}, "novita/deepseek/deepseek-r1-turbo": {"max_tokens": 16000, "input_cost": 7e-07, "output_cost": 2.5e-06}, "novita/Sao10K/L3-8B-Stheno-v3.2": {"max_tokens": 32000, "input_cost": 5e-08, "output_cost": 5e-08}, "novita/gryphe/mythomax-l2-13b": {"max_tokens": 3200, "input_cost": 9e-08, "output_cost": 9e-08}, "novita/baidu/ernie-4.5-vl-28b-a3b-thinking": {"max_tokens": 65536, "input_cost": 3.9e-07, "output_cost": 3.9e-07}, "novita/qwen/qwen3-vl-8b-instruct": {"max_tokens": 32768, "input_cost": 8e-08, "output_cost": 5e-07}, "novita/zai-org/glm-4.5-air": {"max_tokens": 98304, "input_cost": 1.3e-07, "output_cost": 8.5e-07}, "novita/qwen/qwen3-vl-30b-a3b-instruct": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 7e-07}, "novita/qwen/qwen3-vl-30b-a3b-thinking": {"max_tokens": 32768, "input_cost": 2e-07, "output_cost": 1e-06}, "novita/qwen/qwen3-omni-30b-a3b-thinking": {"max_tokens": 16384, "input_cost": 2.5e-07, "output_cost": 9.7e-07}, "novita/qwen/qwen3-omni-30b-a3b-instruct": {"max_tokens": 16384, "input_cost": 2.5e-07, "output_cost": 9.7e-07}, "novita/qwen/qwen-mt-plus": {"max_tokens": 8192, "input_cost": 2.5e-07, "output_cost": 7.5e-07}, "novita/baidu/ernie-4.5-vl-28b-a3b": {"max_tokens": 8000, "input_cost": 1.4e-07, "output_cost": 5.6e-07}, "novita/baidu/ernie-4.5-21B-a3b": {"max_tokens": 8000, "input_cost": 7e-08, "output_cost": 2.8e-07}, "novita/qwen/qwen3-8b-fp8": {"max_tokens": 20000, "input_cost": 3.5e-08, "output_cost": 1.38e-07}, "novita/qwen/qwen3-4b-fp8": {"max_tokens": 20000, "input_cost": 3e-08, "output_cost": 3e-08}, "novita/qwen/qwen2.5-7b-instruct": {"max_tokens": 32000, "input_cost": 7e-08, "output_cost": 7e-08}, "novita/meta-llama/llama-3.2-3b-instruct": {"max_tokens": 32000, "input_cost": 3e-08, "output_cost": 5e-08}, "novita/sao10k/l31-70b-euryale-v2.2": {"max_tokens": 8192, "input_cost": 1.48e-06, "output_cost": 1.48e-06}, "novita/qwen/qwen3-embedding-0.6b": {"max_tokens": 32768, "input_cost": 7e-08, "output_cost": 0}, "novita/qwen/qwen3-embedding-8b": {"max_tokens": 4096, "input_cost": 7e-08, "output_cost": 0}, "novita/baai/bge-m3": {"max_tokens": 96000, "input_cost": 1e-08, "output_cost": 1e-08}, "novita/qwen/qwen3-reranker-8b": {"max_tokens": 4096, "input_cost": 5e-08, "output_cost": 5e-08}, "novita/baai/bge-reranker-v2-m3": {"max_tokens": 8000, "input_cost": 1e-08, "output_cost": 1e-08}, "assemblyai/best": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "assemblyai/nano": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "jina-reranker-v2-base-multilingual": {"max_tokens": 1024, "input_cost": 1.8e-08, "output_cost": 1.8e-08}, "snowflake/claude-3-5-sonnet": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/deepseek-r1": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/gemma-7b": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/jamba-1.5-large": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/jamba-1.5-mini": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/jamba-instruct": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/llama2-70b-chat": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/llama3-70b": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/llama3-8b": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/llama3.1-405b": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/llama3.1-70b": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/llama3.1-8b": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/llama3.2-1b": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/llama3.2-3b": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/llama3.3-70b": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/mistral-7b": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/mistral-large": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/mistral-large2": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/mixtral-8x7b": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/reka-core": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/reka-flash": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/snowflake-arctic": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/snowflake-llama-3.1-405b": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "snowflake/snowflake-llama-3.3-70b": {"max_tokens": 8192, "input_cost": 0, "output_cost": 0}, "meta_llama/Llama-3.3-70B-Instruct": {"max_tokens": 4028, "input_cost": 0, "output_cost": 0}, "meta_llama/Llama-3.3-8B-Instruct": {"max_tokens": 4028, "input_cost": 0, "output_cost": 0}, "meta_llama/Llama-4-Maverick-17B-128E-Instruct-FP8": {"max_tokens": 4028, "input_cost": 0, "output_cost": 0}, "meta_llama/Llama-4-Scout-17B-16E-Instruct-FP8": {"max_tokens": 4028, "input_cost": 0, "output_cost": 0}, "nscale/Qwen/QwQ-32B": {"max_tokens": 0, "input_cost": 1.8e-07, "output_cost": 2e-07}, "nscale/Qwen/Qwen2.5-Coder-32B-Instruct": {"max_tokens": 0, "input_cost": 6e-08, "output_cost": 2e-07}, "nscale/Qwen/Qwen2.5-Coder-3B-Instruct": {"max_tokens": 0, "input_cost": 1e-08, "output_cost": 3e-08}, "nscale/Qwen/Qwen2.5-Coder-7B-Instruct": {"max_tokens": 0, "input_cost": 1e-08, "output_cost": 3e-08}, "nscale/black-forest-labs/FLUX.1-schnell": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "nscale/deepseek-ai/DeepSeek-R1-Distill-Llama-70B": {"max_tokens": 0, "input_cost": 3.75e-07, "output_cost": 3.75e-07}, "nscale/deepseek-ai/DeepSeek-R1-Distill-Llama-8B": {"max_tokens": 0, "input_cost": 2.5e-08, "output_cost": 2.5e-08}, "nscale/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B": {"max_tokens": 0, "input_cost": 9e-08, "output_cost": 9e-08}, "nscale/deepseek-ai/DeepSeek-R1-Distill-Qwen-14B": {"max_tokens": 0, "input_cost": 7e-08, "output_cost": 7e-08}, "nscale/deepseek-ai/DeepSeek-R1-Distill-Qwen-32B": {"max_tokens": 0, "input_cost": 1.5e-07, "output_cost": 1.5e-07}, "nscale/deepseek-ai/DeepSeek-R1-Distill-Qwen-7B": {"max_tokens": 0, "input_cost": 2e-07, "output_cost": 2e-07}, "nscale/meta-llama/Llama-3.1-8B-Instruct": {"max_tokens": 0, "input_cost": 3e-08, "output_cost": 3e-08}, "nscale/meta-llama/Llama-3.3-70B-Instruct": {"max_tokens": 0, "input_cost": 2e-07, "output_cost": 2e-07}, "nscale/meta-llama/Llama-4-Scout-17B-16E-Instruct": {"max_tokens": 0, "input_cost": 9e-08, "output_cost": 2.9e-07}, "nscale/mistralai/mixtral-8x22b-instruct-v0.1": {"max_tokens": 0, "input_cost": 6e-07, "output_cost": 6e-07}, "nscale/stabilityai/stable-diffusion-xl-base-1.0": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "featherless_ai/featherless-ai/Qwerky-72B": {"max_tokens": 4096, "input_cost": 0, "output_cost": 0}, "featherless_ai/featherless-ai/Qwerky-QwQ-32B": {"max_tokens": 4096, "input_cost": 0, "output_cost": 0}, "deepgram/base": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/base-conversationalai": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/base-finance": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/base-general": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/base-meeting": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/base-phonecall": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/base-video": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/base-voicemail": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/enhanced": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/enhanced-finance": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/enhanced-general": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/enhanced-meeting": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/enhanced-phonecall": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-2": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-2-atc": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-2-automotive": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-2-conversationalai": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-2-drivethru": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-2-finance": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-2-general": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-2-meeting": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-2-phonecall": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-2-video": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-2-voicemail": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-3": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-3-general": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-3-medical": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-general": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/nova-phonecall": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/whisper": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/whisper-base": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/whisper-large": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/whisper-medium": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/whisper-small": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}, "deepgram/whisper-tiny": {"max_tokens": 0, "input_cost": 0, "output_cost": 0}}}\ No newline at end of filediff --git a/fincept-terminal-desktop/src-tauri/src/commands/agent_streaming.rs b/fincept-terminal-desktop/src-tauri/src/commands/agent_streaming.rsnew file mode 100644index 000000000..5621b6422--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/commands/agent_streaming.rs@@ -0,0 +1,345 @@+// Agent Streaming Module - High-performance streaming agent execution+// Uses Tauri events for real-time token streaming and parallel execution++use crate::utils::python::get_script_path;+use serde::{Deserialize, Serialize};+use tauri::{AppHandle, Emitter};+use std::sync::Arc;+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};++/// Stream chunk sent to frontend+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct StreamChunk {+ pub stream_id: String,+ pub chunk_type: String, // "token", "thinking", "tool_call", "tool_result", "done", "error"+ pub content: String,+ pub metadata: Option<serde_json::Value>,+ pub sequence: u64,+}++/// Stream status for tracking+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct StreamStatus {+ pub stream_id: String,+ pub status: String, // "running", "completed", "error", "cancelled"+ pub tokens_generated: u64,+ pub elapsed_ms: u64,+}++/// Parallel execution result+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ParallelResult {+ pub task_id: String,+ pub success: bool,+ pub result: Option<serde_json::Value>,+ pub error: Option<String>,+ pub execution_time_ms: u64,+}++/// Batch execution response+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BatchResponse {+ pub batch_id: String,+ pub results: Vec<ParallelResult>,+ pub total_time_ms: u64,+ pub successful_count: usize,+ pub failed_count: usize,+}++// Global stream registry for cancellation+use once_cell::sync::Lazy;+use std::collections::HashMap;+use tokio::sync::RwLock;++static ACTIVE_STREAMS: Lazy<RwLock<HashMap<String, Arc<AtomicBool>>>> =+ Lazy::new(|| RwLock::new(HashMap::new()));++/// Execute agent with streaming - tokens emitted via Tauri events+///+/// Frontend listens to: "agent-stream-{stream_id}"+/// Events: StreamChunk for each token/thinking step+#[tauri::command]+pub async fn execute_agent_streaming(+ app: AppHandle,+ payload: serde_json::Value,+) -> Result<String, String> {+ let stream_id = uuid::Uuid::new_v4().to_string();+ let start_time = std::time::Instant::now();++ // Register stream for cancellation+ let cancel_flag = Arc::new(AtomicBool::new(false));+ {+ let mut streams = ACTIVE_STREAMS.write().await;+ streams.insert(stream_id.clone(), cancel_flag.clone());+ }++ // Add stream flag to payload+ let mut payload = payload;+ if let Some(obj) = payload.as_object_mut() {+ obj.insert("stream".to_string(), serde_json::json!(true));+ obj.insert("stream_id".to_string(), serde_json::json!(stream_id.clone()));+ }++ let script_path = get_script_path(&app, "agents/finagent_core/core_agent_stream.py")?;+ let payload_str = serde_json::to_string(&payload)+ .map_err(|e| format!("Failed to serialize payload: {}", e))?;++ let sequence = Arc::new(AtomicU64::new(0));++ // Spawn streaming task+ let stream_id_for_task = stream_id.clone();+ tokio::spawn(async move {+ let app_clone = app.clone();+ let stream_id_clone = stream_id_for_task.clone();+ let seq = sequence.clone();++ // Clones for the callback closure+ let callback_stream_id = stream_id_clone.clone();+ let callback_app = app_clone.clone();+ let callback_seq = seq.clone();+ let callback_cancel = cancel_flag.clone();++ // Execute with streaming callback+ match execute_with_stream_callback(+ &script_path,+ vec![payload_str],+ move |chunk_type, content, metadata| {+ // Check cancellation+ if callback_cancel.load(Ordering::Relaxed) {+ return false;+ }++ let chunk = StreamChunk {+ stream_id: callback_stream_id.clone(),+ chunk_type: chunk_type.to_string(),+ content: content.to_string(),+ metadata,+ sequence: callback_seq.fetch_add(1, Ordering::Relaxed),+ };++ let event_name = format!("agent-stream-{}", callback_stream_id);+ let _ = callback_app.emit(&event_name, &chunk);+ true+ }+ ).await {+ Ok(final_result) => {+ // Emit done chunk+ let done_chunk = StreamChunk {+ stream_id: stream_id_clone.clone(),+ chunk_type: "done".to_string(),+ content: final_result,+ metadata: Some(serde_json::json!({+ "elapsed_ms": start_time.elapsed().as_millis() as u64+ })),+ sequence: seq.fetch_add(1, Ordering::Relaxed),+ };+ let event_name = format!("agent-stream-{}", stream_id_clone);+ let _ = app_clone.emit(&event_name, &done_chunk);+ }+ Err(e) => {+ let error_chunk = StreamChunk {+ stream_id: stream_id_clone.clone(),+ chunk_type: "error".to_string(),+ content: e,+ metadata: None,+ sequence: seq.fetch_add(1, Ordering::Relaxed),+ };+ let event_name = format!("agent-stream-{}", stream_id_clone);+ let _ = app_clone.emit(&event_name, &error_chunk);+ }+ }++ // Cleanup stream registration+ let mut streams = ACTIVE_STREAMS.write().await;+ streams.remove(&stream_id_clone);+ });++ // Return stream ID immediately+ Ok(serde_json::json!({+ "success": true,+ "stream_id": stream_id,+ "event_name": format!("agent-stream-{}", stream_id)+ }).to_string())+}++/// Cancel an active stream+#[tauri::command]+pub async fn cancel_agent_stream(stream_id: String) -> Result<String, String> {+ let streams = ACTIVE_STREAMS.read().await;++ if let Some(cancel_flag) = streams.get(&stream_id) {+ cancel_flag.store(true, Ordering::Relaxed);+ Ok(serde_json::json!({+ "success": true,+ "stream_id": stream_id,+ "status": "cancelled"+ }).to_string())+ } else {+ Err(format!("Stream {} not found or already completed", stream_id))+ }+}++/// Execute multiple agent tasks in parallel+///+/// Each task runs concurrently, results aggregated+#[tauri::command]+pub async fn execute_agents_parallel(+ app: AppHandle,+ tasks: Vec<serde_json::Value>,+ max_concurrent: Option<usize>,+) -> Result<String, String> {+ let batch_id = uuid::Uuid::new_v4().to_string();+ let start_time = std::time::Instant::now();+ let max_concurrent = max_concurrent.unwrap_or(4);++ let script_path = get_script_path(&app, "agents/finagent_core/core_agent.py")?;++ // Create semaphore for concurrency control+ let semaphore = Arc::new(tokio::sync::Semaphore::new(max_concurrent));++ // Spawn all tasks+ let mut handles = Vec::new();++ for (idx, task) in tasks.into_iter().enumerate() {+ let task_id = format!("{}-{}", batch_id, idx);+ let script_path = script_path.clone();+ let semaphore = semaphore.clone();+ let task_start = std::time::Instant::now();++ let handle = tokio::spawn(async move {+ // Acquire semaphore permit+ let _permit = semaphore.acquire().await.unwrap();++ let payload_str = serde_json::to_string(&task)+ .map_err(|e| format!("Failed to serialize: {}", e))?;++ match crate::python_runtime::execute_python_script_async(&script_path, vec![payload_str]).await {+ Ok(result) => {+ let parsed: serde_json::Value = serde_json::from_str(&result)+ .unwrap_or(serde_json::json!({"raw": result}));++ Ok::<ParallelResult, String>(ParallelResult {+ task_id,+ success: true,+ result: Some(parsed),+ error: None,+ execution_time_ms: task_start.elapsed().as_millis() as u64,+ })+ }+ Err(e) => {+ Ok(ParallelResult {+ task_id,+ success: false,+ result: None,+ error: Some(e),+ execution_time_ms: task_start.elapsed().as_millis() as u64,+ })+ }+ }+ });++ handles.push(handle);+ }++ // Collect all results+ let mut results = Vec::new();+ for handle in handles {+ match handle.await {+ Ok(Ok(result)) => results.push(result),+ Ok(Err(e)) => results.push(ParallelResult {+ task_id: "unknown".to_string(),+ success: false,+ result: None,+ error: Some(e),+ execution_time_ms: 0,+ }),+ Err(e) => results.push(ParallelResult {+ task_id: "unknown".to_string(),+ success: false,+ result: None,+ error: Some(format!("Task panicked: {}", e)),+ execution_time_ms: 0,+ }),+ }+ }++ let successful_count = results.iter().filter(|r| r.success).count();+ let failed_count = results.len() - successful_count;++ let response = BatchResponse {+ batch_id,+ results,+ total_time_ms: start_time.elapsed().as_millis() as u64,+ successful_count,+ failed_count,+ };++ serde_json::to_string(&response)+ .map_err(|e| format!("Failed to serialize response: {}", e))+}++/// Execute agent with priority (for urgent queries)+#[tauri::command]+pub async fn execute_agent_priority(+ app: AppHandle,+ payload: serde_json::Value,+ priority: u8, // 0=HIGH, 1=NORMAL, 2=LOW+) -> Result<String, String> {+ let script_path = get_script_path(&app, "agents/finagent_core/core_agent.py")?;+ let payload_str = serde_json::to_string(&payload)+ .map_err(|e| format!("Failed to serialize payload: {}", e))?;++ crate::python_runtime::execute_python_script_async_with_priority(+ &script_path,+ vec![payload_str],+ priority+ ).await+}++/// Get status of all active agent streams+#[tauri::command]+pub async fn get_active_agent_streams() -> Result<String, String> {+ let streams = ACTIVE_STREAMS.read().await;+ let stream_ids: Vec<String> = streams.keys().cloned().collect();++ Ok(serde_json::json!({+ "success": true,+ "active_streams": stream_ids,+ "count": stream_ids.len()+ }).to_string())+}++/// Internal: Execute with streaming callback (simulated for now)+/// In production, this would use a named pipe or socket to get streaming output+async fn execute_with_stream_callback<F>(+ script_path: &std::path::PathBuf,+ args: Vec<String>,+ mut callback: F,+) -> Result<String, String>+where+ F: FnMut(&str, &str, Option<serde_json::Value>) -> bool + Send + 'static,+{+ // For now, execute normally and emit result as single chunk+ // Future: Use named pipes or Unix sockets for true streaming++ // Emit thinking indicator+ callback("thinking", "Processing your request...", None);++ let result = crate::python_runtime::execute_python_script_async(script_path, args).await?;++ // Parse and emit tokens (simulated chunking for now)+ if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&result) {+ if let Some(response) = parsed.get("response").and_then(|r| r.as_str()) {+ // Emit in chunks for smoother UI+ for chunk in response.chars().collect::<Vec<_>>().chunks(50) {+ let chunk_str: String = chunk.iter().collect();+ if !callback("token", &chunk_str, None) {+ return Err("Stream cancelled".to_string());+ }+ tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;+ }+ }+ }++ Ok(result)+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs b/fincept-terminal-desktop/src-tauri/src/commands/agents.rsindex 8e3a30b86..eea350121 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/agents.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/agents.rs@@ -1,4 +1,4 @@-// agents.rs - Simplified agent commands following yfinance pattern+// agents.rs - Unified agent commands with single JSON payloaduse crate::utils::python::get_script_path;use crate::python_runtime;use serde::{Deserialize, Serialize};@@ -40,22 +40,160 @@ pub struct AgentExecutionResult {pub agent_type: String,}-/// Execute CoreAgent - unified single agent system-/// Follows same pattern as yfinance_data.py - command + args+/// Execute CoreAgent with single JSON payload (unified entry point)+///+/// Payload format:+/// {+/// "action": "run|run_team|run_workflow|list_tools|system_info|...",+/// "api_keys": {...},+/// "user_id": "optional",+/// "config": {...},+/// "params": {...}+/// }+///+/// Supported actions:+/// - Core: run, run_team, run_workflow, run_structured+/// - Agent loader: discover_agents, list_agents, create_agent+/// - SuperAgent: route_query, execute_query, execute_multi_query+/// - Planner: create_stock_plan, create_portfolio_plan, execute_plan+/// - Paper trading: paper_execute_trade, paper_get_portfolio, paper_get_positions+/// - Repository: save_session, get_session, add_message, save_memory, search_memories+/// - System: system_info, list_tools, list_models, list_output_models#[tauri::command]pub async fn execute_core_agent(app: tauri::AppHandle,- command: String,- args: Vec<String>,+ payload: serde_json::Value,) -> Result<String, String> {- let script_path = get_script_path(&app, "agents/finagent_core/core_agent.py")?;- let mut cmd_args = vec![command];- cmd_args.extend(args);- python_runtime::execute_python_script(&script_path, cmd_args)+ // Use main.py as unified entry point for all actions+ let script_path = get_script_path(&app, "agents/finagent_core/main.py")?;+ let payload_str = serde_json::to_string(&payload)+ .map_err(|e| format!("Failed to serialize payload: {}", e))?;+ python_runtime::execute_python_script(&script_path, vec![payload_str])}-/// DEPRECATED - Old agent manager commands removed-/// Use execute_core_agent instead for all agent operations+/// Route a query to the appropriate agent using SuperAgent+#[tauri::command]+pub async fn route_query(+ app: tauri::AppHandle,+ query: String,+ api_keys: Option<std::collections::HashMap<String, String>>,+) -> Result<String, String> {+ let payload = serde_json::json!({+ "action": "route_query",+ "api_keys": api_keys.unwrap_or_default(),+ "params": { "query": query }+ });+ execute_core_agent(app, payload).await+}++/// Execute a query with automatic routing via SuperAgent+#[tauri::command]+pub async fn execute_routed_query(+ app: tauri::AppHandle,+ query: String,+ api_keys: Option<std::collections::HashMap<String, String>>,+ session_id: Option<String>,+) -> Result<String, String> {+ let payload = serde_json::json!({+ "action": "execute_query",+ "api_keys": api_keys.unwrap_or_default(),+ "params": {+ "query": query,+ "session_id": session_id+ }+ });+ execute_core_agent(app, payload).await+}++/// Discover all available agents from config files and directories+#[tauri::command]+pub async fn discover_agents(app: tauri::AppHandle) -> Result<String, String> {+ let payload = serde_json::json!({+ "action": "discover_agents",+ "params": {}+ });+ execute_core_agent(app, payload).await+}++/// Create a stock analysis execution plan+#[tauri::command]+pub async fn create_stock_analysis_plan(+ app: tauri::AppHandle,+ symbol: String,+) -> Result<String, String> {+ let payload = serde_json::json!({+ "action": "create_stock_plan",+ "params": { "symbol": symbol }+ });+ execute_core_agent(app, payload).await+}++/// Execute an execution plan+#[tauri::command]+pub async fn execute_plan(+ app: tauri::AppHandle,+ plan: serde_json::Value,+ api_keys: Option<std::collections::HashMap<String, String>>,+) -> Result<String, String> {+ let payload = serde_json::json!({+ "action": "execute_plan",+ "api_keys": api_keys.unwrap_or_default(),+ "params": { "plan": plan }+ });+ execute_core_agent(app, payload).await+}++/// Save a trade decision to repository+#[tauri::command]+pub async fn save_trade_decision(+ app: tauri::AppHandle,+ competition_id: String,+ model_name: String,+ cycle_number: i32,+ symbol: String,+ action: String,+ quantity: f64,+ price: Option<f64>,+ reasoning: String,+ confidence: f64,+) -> Result<String, String> {+ let payload = serde_json::json!({+ "action": "save_trade_decision",+ "params": {+ "competition_id": competition_id,+ "model_name": model_name,+ "cycle_number": cycle_number,+ "symbol": symbol,+ "action": action,+ "quantity": quantity,+ "price": price,+ "reasoning": reasoning,+ "confidence": confidence+ }+ });+ execute_core_agent(app, payload).await+}++/// Get trade decisions from repository+#[tauri::command]+pub async fn get_trade_decisions(+ app: tauri::AppHandle,+ competition_id: Option<String>,+ model_name: Option<String>,+ cycle_number: Option<i32>,+ limit: Option<i32>,+) -> Result<String, String> {+ let payload = serde_json::json!({+ "action": "get_decisions",+ "params": {+ "competition_id": competition_id,+ "model_name": model_name,+ "cycle_number": cycle_number,+ "limit": limit.unwrap_or(100)+ }+ });+ execute_core_agent(app, payload).await+}// Legacy commands for Node Editor compatibilityfn get_agent_script_path(agent_type: &str) -> Option<&'static str> {@@ -178,7 +316,6 @@ struct AgentConfigFile {pub async fn list_available_agents(app: tauri::AppHandle) -> Result<Vec<AgentMetadata>, String> {let mut all_agents = Vec::new();- // Define agent categories and their config fileslet categories = vec![("TraderInvestorsAgent", "agent_definitions.json", "trader", "📈", "#22c55e"),("hedgeFundAgents", "team_config.json", "hedge-fund", "🏦", "#6366f1"),@@ -204,7 +341,6 @@ pub async fn list_available_agents(app: tauri::AppHandle) -> Result<Vec<AgentMetresource_dir.join(&config_path)};- // Read and parse the config fileif let Ok(content) = std::fs::read_to_string(&full_path) {if let Ok(config) = serde_json::from_str::<AgentConfigFile>(&content) {for agent_def in config.agents {@@ -231,11 +367,7 @@ pub async fn list_available_agents(app: tauri::AppHandle) -> Result<Vec<AgentMetcolor: color.to_string(),});}- } else {- eprintln!("Failed to parse agent config: {}", full_path.display());}- } else {- eprintln!("Agent config file not found: {}", full_path.display());}}@@ -244,7 +376,7 @@ pub async fn list_available_agents(app: tauri::AppHandle) -> Result<Vec<AgentMet#[tauri::command]pub async fn get_agent_metadata(agent_type: String) -> Result<AgentMetadata, String> {- Err(format!("Legacy command - use get_agent_config instead for: {}", agent_type))+ Err(format!("Legacy command - use execute_core_agent with action='system_info' instead for: {}", agent_type))}/// Read agent configuration file from resources@@ -274,13 +406,3 @@ pub async fn read_agent_config(std::fs::read_to_string(&full_path).map_err(|e| format!("Failed to read config file {}: {}", full_path.display(), e))}--#[tauri::command]-pub async fn execute_python_agent_command(- _app: tauri::AppHandle,- action: String,- _parameters: serde_json::Value,- _inputs: Option<serde_json::Value>,-) -> Result<serde_json::Value, String> {- Err(format!("Legacy command '{}' is deprecated. Use new agent commands instead.", action))-}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rsindex 321bc7911..165ead72c 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs@@ -1,158 +1,576 @@/*** Alpha Arena Tauri Commands- * Rust commands for NOF1-style AI trading competition+ * Rust commands for AI trading competition (refactored v2)+ * Now with streaming support for real-time progress updates*/-use tauri::command;-use serde_json::Value;+use tauri::{command, AppHandle, Emitter};+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};use std::process::Command;+use std::collections::HashMap;-/// Execute Python command and return JSON result-/// Uses tokio spawn_blocking to avoid blocking the async runtime-async fn execute_python_alpha_command(args: &[&str]) -> Result<Value, String> {- let python_script = "agno_trading_service.py";+/// Extract JSON object from output that may contain log lines before it+fn extract_json_from_output(output: &str) -> Result<String, String> {+ // Find all potential JSON objects by looking for matching braces+ let mut brace_count = 0;+ let mut json_start: Option<usize> = None;+ let mut last_valid_json: Option<String> = None;++ let chars: Vec<char> = output.chars().collect();++ for (i, ch) in chars.iter().enumerate() {+ match ch {+ '{' => {+ if brace_count == 0 {+ json_start = Some(i);+ }+ brace_count += 1;+ }+ '}' => {+ brace_count -= 1;+ if brace_count == 0 {+ if let Some(start) = json_start {+ let potential_json: String = chars[start..=i].iter().collect();+ // Validate it's actually JSON+ if serde_json::from_str::<Value>(&potential_json).is_ok() {+ last_valid_json = Some(potential_json);+ }+ json_start = None;+ }+ }+ }+ _ => {}+ }+ }++ last_valid_json.ok_or_else(|| {+ // Truncate output for error message+ let preview: String = output.chars().take(500).collect();+ format!("No valid JSON found in output. Preview: {}", preview)+ })+}++/// Progress event for streaming updates+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AlphaArenaProgress {+ pub event_type: String, // "step", "info", "warning", "error", "complete"+ pub step: u32,+ pub total_steps: u32,+ pub message: String,+ pub details: Option<Value>,+}++/// Execute Python alpha_arena main.py with JSON payload+async fn execute_alpha_arena_action(action: &str, params: Value, api_keys: Option<HashMap<String, String>>) -> Result<Value, String> {+ // Use proper path separators for the platform+ let python_script_parts = ["alpha_arena", "main.py"];// Try multiple possible paths for the scriptlet possible_paths = vec![std::env::current_dir().ok()- .and_then(|d| Some(d.join("src-tauri").join("resources").join("scripts").join(python_script))),+ .map(|d| d.join("src-tauri").join("resources").join("scripts").join(python_script_parts[0]).join(python_script_parts[1])),std::env::current_dir().ok()- .and_then(|d| Some(d.join("resources").join("scripts").join(python_script))),+ .map(|d| d.join("resources").join("scripts").join(python_script_parts[0]).join(python_script_parts[1])),+ // Also check for bundled resources in release builds+ std::env::current_exe()+ .ok()+ .and_then(|p| p.parent().map(|d| d.to_path_buf()))+ .map(|d| d.join("resources").join("scripts").join(python_script_parts[0]).join(python_script_parts[1])),];let script_path = possible_paths.into_iter().flatten().find(|p| p.exists())- .ok_or_else(|| format!("Could not find Python script: {}", python_script))?;+ .ok_or_else(|| format!("Could not find Python script: alpha_arena/main.py. Searched paths failed to locate the script."))?;- eprintln!("[Alpha Arena] Executing Python script: {:?}", script_path);- eprintln!("[Alpha Arena] Args: {:?}", args);+ // Create JSON payload with API keys+ let payload = json!({+ "action": action,+ "params": params,+ "api_keys": api_keys.unwrap_or_default()+ });+ let payload_str = serde_json::to_string(&payload)+ .map_err(|e| format!("Failed to serialize payload: {}", e))?;- let args_owned: Vec<String> = args.iter().map(|s| s.to_string()).collect();+ eprintln!("[Alpha Arena v2] Executing action: {}", action);+ eprintln!("[Alpha Arena v2] Script path: {:?}", script_path);- // Try PyO3 first, fallback to subprocess- // Execute in a blocking thread to avoid blocking the async runtimelet script_path_clone = script_path.clone();- let args_clone = args_owned.clone();-- let stdout = tokio::task::spawn_blocking(move || {- // Try PyO3 execution- match crate::python_runtime::execute_python_script(&script_path_clone, args_clone.clone()) {- Ok(output) => Ok(output),- Err(_) => {- // Fallback to subprocess- let result = Command::new("python")- .env("PYTHONDONTWRITEBYTECODE", "1")- .arg(&script_path_clone)- .args(&args_clone)- .output()- .map_err(|e| format!("Failed to execute Python: {}", e))?;-- let stderr = String::from_utf8_lossy(&result.stderr);- if !stderr.is_empty() {- eprintln!("[Alpha Arena] Python stderr: {}", stderr);+ let payload_clone = payload_str.clone();++ // Execute directly via subprocess (bypasses worker pool to avoid async deadlocks)+ // The worker pool uses async socket IPC which can deadlock when called from spawn_blocking+ let execution_result = tokio::time::timeout(+ tokio::time::Duration::from_secs(120), // 2 minute timeout+ tokio::task::spawn_blocking(move || {+ eprintln!("[Alpha Arena v2] Using direct subprocess execution");++ // Get working directory for script+ let script_dir = script_path_clone.parent()+ .map(|p| p.to_path_buf())+ .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());++ // Execute Python directly+ let result = Command::new("python")+ .env("PYTHONDONTWRITEBYTECODE", "1")+ .env("PYTHONIOENCODING", "utf-8")+ .current_dir(&script_dir)+ .arg(&script_path_clone)+ .arg(&payload_clone)+ .output()+ .map_err(|e| format!("Failed to execute Python subprocess: {}", e))?;++ let stderr = String::from_utf8_lossy(&result.stderr);+ let stdout_str = String::from_utf8_lossy(&result.stdout);++ eprintln!("[Alpha Arena v2] ==================== RAW OUTPUT START ====================");+ eprintln!("[Alpha Arena v2] Python exit code: {:?}", result.status.code());+ eprintln!("[Alpha Arena v2] Python stdout length: {} chars", stdout_str.len());+ eprintln!("[Alpha Arena v2] Python stderr length: {} chars", stderr.len());++ // Log full stdout (up to 5000 chars for debugging)+ if !stdout_str.is_empty() {+ let stdout_preview: String = stdout_str.chars().take(5000).collect();+ eprintln!("[Alpha Arena v2] RAW STDOUT:\n{}", stdout_preview);+ if stdout_str.len() > 5000 {+ eprintln!("[Alpha Arena v2] ... (truncated, {} more chars)", stdout_str.len() - 5000);}+ } else {+ eprintln!("[Alpha Arena v2] STDOUT is EMPTY!");+ }- if !result.status.success() {- return Err(format!("Python error: {}", stderr));+ // Log full stderr (up to 2000 chars for debugging)+ if !stderr.is_empty() {+ let stderr_preview: String = stderr.chars().take(2000).collect();+ eprintln!("[Alpha Arena v2] RAW STDERR:\n{}", stderr_preview);+ if stderr.len() > 2000 {+ eprintln!("[Alpha Arena v2] ... (truncated, {} more chars)", stderr.len() - 2000);}+ }+ eprintln!("[Alpha Arena v2] ==================== RAW OUTPUT END ====================");- Ok(String::from_utf8_lossy(&result.stdout).to_string())+ if !result.status.success() {+ eprintln!("[Alpha Arena v2] Python process FAILED with exit code: {:?}", result.status.code());+ // Try to extract JSON error from stdout first+ if let Some(json_start) = stdout_str.find('{') {+ if let Some(json_end) = stdout_str.rfind('}') {+ eprintln!("[Alpha Arena v2] Found JSON in stdout despite error exit");+ return Ok(stdout_str[json_start..=json_end].to_string());+ }+ }+ // Then try stderr+ if let Some(json_start) = stderr.find('{') {+ if let Some(json_end) = stderr.rfind('}') {+ eprintln!("[Alpha Arena v2] Found JSON in stderr");+ return Ok(stderr[json_start..=json_end].to_string());+ }+ }+ return Err(format!("Python error (exit code {:?}): {}", result.status.code(), stderr));}- }- })- .await- .map_err(|e| format!("Task join error: {}", e))??;- eprintln!("[Alpha Arena] Python stdout length: {} chars", stdout.len());+ eprintln!("[Alpha Arena v2] Python process SUCCESS");+ Ok(stdout_str.to_string())+ })+ )+ .await;- // Only log first 1000 chars to avoid flooding logs- if stdout.len() > 1000 {- eprintln!("[Alpha Arena] Python stdout (truncated): {}...", &stdout[..1000]);- } else {- eprintln!("[Alpha Arena] Python stdout: {}", stdout);+ let stdout = match execution_result {+ Ok(Ok(Ok(output))) => output,+ Ok(Ok(Err(e))) => return Err(e),+ Ok(Err(e)) => return Err(format!("Task join error: {}", e)),+ Err(_) => return Err("Python script execution timed out after 120 seconds".to_string()),+ };++ eprintln!("[Alpha Arena v2] Final output received, length: {} chars", stdout.len());++ // Try to parse JSON from output+ let stdout_trimmed = stdout.trim();+ if stdout_trimmed.is_empty() {+ eprintln!("[Alpha Arena v2] ERROR: Python script returned empty output!");+ return Err("Python script returned empty output".to_string());+ }++ // Find the LAST complete JSON object in output (skip any logging before it)+ // This handles cases where ERROR logs appear before the JSON result+ eprintln!("[Alpha Arena v2] Extracting JSON from output...");+ let json_str = extract_json_from_output(stdout_trimmed)?;++ eprintln!("[Alpha Arena v2] ==================== EXTRACTED JSON START ====================");+ // Log extracted JSON (up to 3000 chars)+ let json_preview: String = json_str.chars().take(3000).collect();+ eprintln!("{}", json_preview);+ if json_str.len() > 3000 {+ eprintln!("[Alpha Arena v2] ... (truncated, {} more chars)", json_str.len() - 3000);+ }+ eprintln!("[Alpha Arena v2] ==================== EXTRACTED JSON END ====================");++ let parsed: Value = serde_json::from_str(&json_str)+ .map_err(|e| format!("Failed to parse JSON: {}\nExtracted JSON: {}", e, json_str))?;++ // Log key fields from parsed JSON+ if let Some(success) = parsed.get("success") {+ eprintln!("[Alpha Arena v2] Response success: {}", success);+ }+ if let Some(error) = parsed.get("error") {+ eprintln!("[Alpha Arena v2] Response error: {}", error);+ }+ if let Some(leaderboard) = parsed.get("leaderboard") {+ if let Some(arr) = leaderboard.as_array() {+ eprintln!("[Alpha Arena v2] Response leaderboard entries: {}", arr.len());+ }+ }+ if let Some(decisions) = parsed.get("decisions") {+ if let Some(arr) = decisions.as_array() {+ eprintln!("[Alpha Arena v2] Response decisions entries: {}", arr.len());+ }+ }+ if let Some(snapshots) = parsed.get("snapshots") {+ if let Some(arr) = snapshots.as_array() {+ eprintln!("[Alpha Arena v2] Response snapshots entries: {}", arr.len());+ }+ }+ if let Some(cycle_number) = parsed.get("cycle_number") {+ eprintln!("[Alpha Arena v2] Response cycle_number: {}", cycle_number);}- serde_json::from_str(&stdout)- .map_err(|e| format!("Failed to parse JSON: {}\nOutput: {}", e, stdout))+ Ok(parsed)}+/// Create a new AI trading competition (with streaming progress)#[command]-pub async fn create_alpha_competition(- config_json: String-) -> Result<Value, String> {- eprintln!("[Alpha Arena] create_alpha_competition called");- eprintln!("[Alpha Arena] Config JSON length: {}", config_json.len());+pub async fn create_alpha_competition(app: AppHandle, config_json: String, api_keys: Option<HashMap<String, String>>) -> Result<Value, String> {+ eprintln!("[Alpha Arena v2] create_alpha_competition called");++ let config: Value = serde_json::from_str(&config_json)+ .map_err(|e| format!("Invalid config JSON: {}", e))?;++ // Emit initial progress+ emit_progress(&app, "step", 1, 5, "Validating competition configuration...", None);+ tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;++ // Validate models and extract API keys if not provided+ let models = config.get("models").and_then(|m| m.as_array());+ let model_count = models.map(|m| m.len()).unwrap_or(0);++ // Build API keys map from models if not provided+ let mut final_api_keys: HashMap<String, String> = api_keys.unwrap_or_default();+ if let Some(models) = models {+ for model in models.iter() {+ if let (Some(provider), Some(api_key)) = (+ model.get("provider").and_then(|p| p.as_str()),+ model.get("api_key").and_then(|k| k.as_str())+ ) {+ if !api_key.is_empty() && !final_api_keys.contains_key(provider) {+ final_api_keys.insert(provider.to_string(), api_key.to_string());+ }+ }+ }+ }++ eprintln!("[Alpha Arena v2] API keys collected for providers: {:?}", final_api_keys.keys().collect::<Vec<_>>());++ emit_progress(&app, "step", 2, 5, &format!("Setting up {} AI models...", model_count), None);+ tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;- execute_python_alpha_command(&[- "create_competition",- &config_json- ]).await+ // Emit model setup details+ if let Some(models) = models {+ for (i, model) in models.iter().enumerate() {+ let name = model.get("name").and_then(|n| n.as_str()).unwrap_or("Unknown");+ emit_progress(&app, "info", 2, 5, &format!("Initializing model {}: {}", i + 1, name), Some(json!({ "model": name })));+ tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;+ }+ }++ emit_progress(&app, "step", 3, 5, "Connecting to market data providers...", None);+ tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;++ emit_progress(&app, "step", 4, 5, "Creating competition in backend...", None);++ // Execute the actual creation with API keys+ let result = execute_alpha_arena_action("create_competition", config, Some(final_api_keys)).await;++ match &result {+ Ok(value) => {+ let success = value.get("success").and_then(|s| s.as_bool()).unwrap_or(false);+ if success {+ emit_progress(&app, "complete", 5, 5, "Competition created successfully!", Some(value.clone()));+ } else {+ let error = value.get("error").and_then(|e| e.as_str()).unwrap_or("Unknown error");+ emit_progress(&app, "error", 5, 5, error, None);+ }+ }+ Err(e) => {+ emit_progress(&app, "error", 5, 5, e, None);+ }+ }++ result}+/// Emit progress event to frontend+fn emit_progress(app: &AppHandle, event_type: &str, step: u32, total_steps: u32, message: &str, details: Option<Value>) {+ let progress = AlphaArenaProgress {+ event_type: event_type.to_string(),+ step,+ total_steps,+ message: message.to_string(),+ details,+ };+ let _ = app.emit("alpha-arena-progress", &progress);+}++/// Run a single competition cycle (with streaming progress)#[command]-pub async fn start_alpha_competition(competition_id: Option<String>) -> Result<Value, String> {- eprintln!("[Alpha Arena] start_alpha_competition called");- eprintln!("[Alpha Arena] Competition ID: {:?}", competition_id);+pub async fn run_alpha_cycle(app: AppHandle, competition_id: Option<String>) -> Result<Value, String> {+ eprintln!("[Alpha Arena v2] run_alpha_cycle called");++ emit_progress(&app, "step", 1, 4, "Fetching latest market data...", None);+ tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;++ emit_progress(&app, "step", 2, 4, "AI models analyzing market conditions...", None);++ let params = json!({+ "competition_id": competition_id+ });++ emit_progress(&app, "step", 3, 4, "Executing trading decisions...", None);- let id = competition_id.as_deref().unwrap_or("");- execute_python_alpha_command(&[- "start_competition",- id- ]).await+ let result = execute_alpha_arena_action("run_cycle", params, None).await;++ match &result {+ Ok(value) => {+ let success = value.get("success").and_then(|s| s.as_bool()).unwrap_or(false);+ if success {+ let cycle_num = value.get("cycle_number").and_then(|c| c.as_u64()).unwrap_or(0);+ emit_progress(&app, "complete", 4, 4, &format!("Cycle {} completed!", cycle_num), Some(value.clone()));+ } else {+ let error = value.get("error").and_then(|e| e.as_str()).unwrap_or("Unknown error");+ emit_progress(&app, "error", 4, 4, error, None);+ }+ }+ Err(e) => {+ emit_progress(&app, "error", 4, 4, e, None);+ }+ }++ result}+/// Get competition leaderboard#[command]pub async fn get_alpha_leaderboard(competition_id: String) -> Result<Value, String> {- eprintln!("[Alpha Arena] get_alpha_leaderboard called");- eprintln!("[Alpha Arena] Competition ID: {}", competition_id);+ eprintln!("[Alpha Arena v2] ========================================");+ eprintln!("[Alpha Arena v2] get_alpha_leaderboard called for: {}", competition_id);++ let params = json!({+ "competition_id": competition_id+ });++ let result = execute_alpha_arena_action("get_leaderboard", params, None).await;++ match &result {+ Ok(value) => {+ eprintln!("[Alpha Arena v2] get_alpha_leaderboard SUCCESS");+ eprintln!("[Alpha Arena v2] Leaderboard response: {}", serde_json::to_string_pretty(value).unwrap_or_default());+ }+ Err(e) => {+ eprintln!("[Alpha Arena v2] get_alpha_leaderboard ERROR: {}", e);+ }+ }+ eprintln!("[Alpha Arena v2] ========================================");- execute_python_alpha_command(&[- "get_leaderboard_alpha",- &competition_id- ]).await+ result}+/// Get model trading decisions#[command]pub async fn get_alpha_model_decisions(competition_id: String,model_name: Option<String>) -> Result<Value, String> {- eprintln!("[Alpha Arena] get_alpha_model_decisions called");- eprintln!("[Alpha Arena] Competition ID: {}", competition_id);- eprintln!("[Alpha Arena] Model name: {:?}", model_name);+ eprintln!("[Alpha Arena v2] ========================================");+ eprintln!("[Alpha Arena v2] get_alpha_model_decisions called for: {} (model: {:?})", competition_id, model_name);++ let params = json!({+ "competition_id": competition_id,+ "model_name": model_name+ });++ let result = execute_alpha_arena_action("get_decisions", params, None).await;++ match &result {+ Ok(value) => {+ eprintln!("[Alpha Arena v2] get_alpha_model_decisions SUCCESS");+ eprintln!("[Alpha Arena v2] Decisions response: {}", serde_json::to_string_pretty(value).unwrap_or_default());+ }+ Err(e) => {+ eprintln!("[Alpha Arena v2] get_alpha_model_decisions ERROR: {}", e);+ }+ }+ eprintln!("[Alpha Arena v2] ========================================");- let model_name_str = model_name.as_deref().unwrap_or("");+ result+}++/// Get performance snapshots for charts+#[command]+pub async fn get_alpha_snapshots(competition_id: String) -> Result<Value, String> {+ eprintln!("[Alpha Arena v2] ========================================");+ eprintln!("[Alpha Arena v2] get_alpha_snapshots called for: {}", competition_id);++ let params = json!({+ "competition_id": competition_id+ });++ let result = execute_alpha_arena_action("get_snapshots", params, None).await;++ match &result {+ Ok(value) => {+ eprintln!("[Alpha Arena v2] get_alpha_snapshots SUCCESS");+ eprintln!("[Alpha Arena v2] Snapshots response: {}", serde_json::to_string_pretty(value).unwrap_or_default());+ }+ Err(e) => {+ eprintln!("[Alpha Arena v2] get_alpha_snapshots ERROR: {}", e);+ }+ }+ eprintln!("[Alpha Arena v2] ========================================");- execute_python_alpha_command(&[- "get_model_decisions_alpha",- &competition_id,- model_name_str- ]).await+ result}+/// Start auto-run for competition+#[command]+pub async fn start_alpha_competition(competition_id: Option<String>) -> Result<Value, String> {+ eprintln!("[Alpha Arena v2] start_alpha_competition called");++ let params = json!({+ "competition_id": competition_id+ });++ execute_alpha_arena_action("start_competition", params, None).await+}++/// Stop competition#[command]pub async fn stop_alpha_competition(competition_id: String) -> Result<Value, String> {- eprintln!("[Alpha Arena] stop_alpha_competition called");- eprintln!("[Alpha Arena] Competition ID: {}", competition_id);+ eprintln!("[Alpha Arena v2] stop_alpha_competition called");++ let params = json!({+ "competition_id": competition_id+ });++ execute_alpha_arena_action("stop_competition", params, None).await+}- execute_python_alpha_command(&[- "stop_competition",- &competition_id- ]).await+/// List available trading agents+#[command]+pub async fn list_alpha_agents() -> Result<Value, String> {+ eprintln!("[Alpha Arena v2] list_alpha_agents called");++ execute_alpha_arena_action("list_agents", json!({}), None).await+}++/// Get evaluation metrics for a model+#[command]+pub async fn get_alpha_evaluation(+ competition_id: String,+ model_name: String+) -> Result<Value, String> {+ eprintln!("[Alpha Arena v2] get_alpha_evaluation called");++ let params = json!({+ "competition_id": competition_id,+ "model_name": model_name+ });++ execute_alpha_arena_action("get_evaluation", params, None).await+}++/// Get stored API keys (masked for display)+#[command]+pub async fn get_alpha_api_keys() -> Result<Value, String> {+ eprintln!("[Alpha Arena v2] get_alpha_api_keys called");++ // Return masked keys from environment or storage+ // In production, load from secure storage+ let providers = vec!["openai", "anthropic", "google", "deepseek", "groq"];+ let mut keys: HashMap<String, String> = HashMap::new();++ for provider in providers {+ let env_var = format!("{}_API_KEY", provider.to_uppercase());+ if let Ok(key) = std::env::var(&env_var) {+ if !key.is_empty() {+ // Return masked key for display+ let masked = if key.len() > 8 {+ format!("{}...{}", &key[..4], &key[key.len()-4..])+ } else {+ "*".repeat(key.len())+ };+ keys.insert(provider.to_string(), masked);+ }+ }+ }++ Ok(json!({+ "success": true,+ "keys": keys+ }))}+/// Save API keys to environment/storage#[command]-pub async fn run_alpha_cycle(competition_id: Option<String>) -> Result<Value, String> {- eprintln!("[Alpha Arena] run_alpha_cycle called");- eprintln!("[Alpha Arena] Competition ID: {:?}", competition_id);-- let id = competition_id.as_deref().unwrap_or("");- execute_python_alpha_command(&[- "run_cycle",- id- ]).await+pub async fn save_alpha_api_keys(keys: HashMap<String, String>) -> Result<Value, String> {+ eprintln!("[Alpha Arena v2] save_alpha_api_keys called");++ // In production, save to secure storage+ // For now, we'll set environment variables for the current session+ for (provider, key) in &keys {+ let env_var = format!("{}_API_KEY", provider.to_uppercase());+ std::env::set_var(&env_var, key);+ }++ Ok(json!({+ "success": true,+ "message": "API keys saved for current session"+ }))+}++/// List all competitions from the database+#[command]+pub async fn list_alpha_competitions(limit: Option<u32>) -> Result<Value, String> {+ eprintln!("[Alpha Arena v2] list_alpha_competitions called");++ let params = json!({+ "limit": limit.unwrap_or(50)+ });++ execute_alpha_arena_action("list_competitions", params, None).await+}++/// Get a specific competition by ID+#[command]+pub async fn get_alpha_competition(competition_id: String) -> Result<Value, String> {+ eprintln!("[Alpha Arena v2] get_alpha_competition called");++ let params = json!({+ "competition_id": competition_id+ });++ execute_alpha_arena_action("get_competition", params, None).await+}++/// Delete a competition+#[command]+pub async fn delete_alpha_competition(competition_id: String) -> Result<Value, String> {+ eprintln!("[Alpha Arena v2] delete_alpha_competition called");++ let params = json!({+ "competition_id": competition_id+ });++ execute_alpha_arena_action("delete_competition", params, None).await}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena_v2.rs b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena_v2.rsnew file mode 100644index 000000000..204c6e183--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena_v2.rs@@ -0,0 +1,165 @@+//! Alpha Arena V2 Commands+//!+//! Tauri commands for the refactored Alpha Arena system.++use std::process::Command;+use tauri::AppHandle;++/// Execute an Alpha Arena action+///+/// Takes a JSON payload with:+/// - action: The action to perform+/// - api_keys: Dict of provider API keys+/// - params: Action-specific parameters+#[tauri::command]+pub async fn alpha_arena_action(+ app: AppHandle,+ payload: String,+) -> Result<String, String> {+ // Get the Python executable path+ let python_path = get_python_path(&app)?;++ // Get the script path+ let script_path = get_script_path(&app)?;++ // Execute Python script+ let output = Command::new(&python_path)+ .arg(&script_path)+ .arg(&payload)+ .current_dir(script_path.parent().unwrap_or(&script_path))+ .output()+ .map_err(|e| format!("Failed to execute Python script: {}", e))?;++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ // Try to extract JSON error from stderr+ if let Some(json_start) = stderr.find('{') {+ if let Some(json_end) = stderr.rfind('}') {+ return Ok(stderr[json_start..=json_end].to_string());+ }+ }+ return Err(format!(+ "Python script failed: {}",+ stderr+ ));+ }++ let stdout = String::from_utf8_lossy(&output.stdout);++ // Find JSON in output+ if let Some(json_start) = stdout.find('{') {+ if let Some(json_end) = stdout.rfind('}') {+ return Ok(stdout[json_start..=json_end].to_string());+ }+ }++ Err("No JSON output from Python script".to_string())+}++/// Get API keys from database+#[tauri::command]+pub async fn get_api_keys(app: AppHandle) -> Result<String, String> {+ use crate::commands::db_commands::get_db_path;++ let db_path = get_db_path(&app).map_err(|e| e.to_string())?;++ let conn = rusqlite::Connection::open(&db_path)+ .map_err(|e| format!("Failed to open database: {}", e))?;++ // Create table if not exists+ conn.execute(+ "CREATE TABLE IF NOT EXISTS api_keys (+ provider TEXT PRIMARY KEY,+ api_key TEXT NOT NULL+ )",+ [],+ )+ .map_err(|e| format!("Failed to create table: {}", e))?;++ // Fetch all keys+ let mut stmt = conn+ .prepare("SELECT provider, api_key FROM api_keys")+ .map_err(|e| format!("Failed to prepare statement: {}", e))?;++ let keys: std::collections::HashMap<String, String> = stmt+ .query_map([], |row| {+ Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))+ })+ .map_err(|e| format!("Failed to query: {}", e))?+ .filter_map(|r| r.ok())+ .collect();++ serde_json::to_string(&keys).map_err(|e| format!("Failed to serialize: {}", e))+}++/// Save API keys to database+#[tauri::command]+pub async fn save_api_keys(app: AppHandle, keys: String) -> Result<(), String> {+ use crate::commands::db_commands::get_db_path;++ let db_path = get_db_path(&app).map_err(|e| e.to_string())?;++ let conn = rusqlite::Connection::open(&db_path)+ .map_err(|e| format!("Failed to open database: {}", e))?;++ // Create table if not exists+ conn.execute(+ "CREATE TABLE IF NOT EXISTS api_keys (+ provider TEXT PRIMARY KEY,+ api_key TEXT NOT NULL+ )",+ [],+ )+ .map_err(|e| format!("Failed to create table: {}", e))?;++ // Parse keys+ let keys_map: std::collections::HashMap<String, String> =+ serde_json::from_str(&keys).map_err(|e| format!("Failed to parse keys: {}", e))?;++ // Insert/update each key+ for (provider, api_key) in keys_map {+ conn.execute(+ "INSERT OR REPLACE INTO api_keys (provider, api_key) VALUES (?1, ?2)",+ [&provider, &api_key],+ )+ .map_err(|e| format!("Failed to insert key: {}", e))?;+ }++ Ok(())+}++// Helper functions+fn get_python_path(app: &AppHandle) -> Result<std::path::PathBuf, String> {+ // Check for bundled Python first+ if let Ok(resource_dir) = app.path().resource_dir() {+ let bundled_python = if cfg!(windows) {+ resource_dir.join("python").join("python.exe")+ } else {+ resource_dir.join("python").join("bin").join("python3")+ };++ if bundled_python.exists() {+ return Ok(bundled_python);+ }+ }++ // Fall back to system Python+ let python_name = if cfg!(windows) { "python" } else { "python3" };++ Ok(std::path::PathBuf::from(python_name))+}++fn get_script_path(app: &AppHandle) -> Result<std::path::PathBuf, String> {+ if let Ok(resource_dir) = app.path().resource_dir() {+ let script = resource_dir+ .join("scripts")+ .join("alpha_arena")+ .join("main.py");++ if script.exists() {+ return Ok(script);+ }+ }++ Err("Alpha Arena script not found".to_string())+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/common_commands.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/common_commands.rsindex 7c1b4b8a3..c5d6cda92 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/common_commands.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/common_commands.rs@@ -51,10 +51,17 @@ pub async fn store_indian_broker_credentials(.and_then(|v| v.as_str()).map(String::from);- // Store additional data as JSON+ // Get token timestamp for Indian broker midnight expiry check+ let token_timestamp = credentials.get("tokenTimestamp")+ .or_else(|| credentials.get("token_timestamp"))+ .and_then(|v| v.as_i64())+ .unwrap_or_else(|| chrono::Utc::now().timestamp_millis());++ // Store additional data as JSON (includes tokenTimestamp for expiry check)let additional_data = json!({"userId": user_id,"expiresAt": credentials.get("expiresAt").or_else(|| credentials.get("expires_at")),+ "tokenTimestamp": token_timestamp,}).to_string();// Use the existing save_broker_credentials command@@ -104,7 +111,7 @@ pub async fn get_indian_broker_credentials(eprintln!(" - access_token: {:?}",creds.access_token.as_ref().map(|s| if s.len() > 0 { "***PRESENT***" } else { "EMPTY" }));- // Parse additional_data JSON to extract userId+ // Parse additional_data JSON to extract userId and tokenTimestamplet additional_data: Option<Value> = creds.additional_data.as_ref().and_then(|data| serde_json::from_str(data).ok());@@ -113,7 +120,11 @@ pub async fn get_indian_broker_credentials(.and_then(|v| v.as_str()).map(String::from);- eprintln!("[get_indian_broker_credentials] Extracted user_id: {:?}", user_id);+ let token_timestamp = additional_data.as_ref()+ .and_then(|data| data.get("tokenTimestamp"))+ .and_then(|v| v.as_i64());++ eprintln!("[get_indian_broker_credentials] Extracted user_id: {:?}, token_timestamp: {:?}", user_id, token_timestamp);// Return camelCase JSON for TypeScriptlet creds_json = json!({@@ -122,6 +133,7 @@ pub async fn get_indian_broker_credentials("apiSecret": creds.api_secret,"accessToken": creds.access_token,"userId": user_id,+ "tokenTimestamp": token_timestamp,"additionalData": creds.additional_data,});diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rsindex b2f4b766f..4dd9baa8c 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/fyers.rs@@ -728,10 +728,16 @@ pub async fn fyers_get_depth(if status.is_success() && body.get("s").and_then(|s| s.as_str()) == Some("ok") {// Fyers depth API returns:- // { "s": "ok", "d": { "totalbuyqty": N, "totalsellqty": N, "bids": [...], "ask": [...] } }+ // { "s": "ok", "d": { "NSE:SYMBOL-EQ": { "totalbuyqty": N, "totalsellqty": N, "bids": [...], "ask": [...] } } }+ // We need to extract the data under the symbol key+ let depth_data = body.get("d")+ .and_then(|d| d.get(&symbol))+ .cloned()+ .or_else(|| body.get("d").cloned());+Ok(ApiResponse {success: true,- data: body.get("d").cloned(),+ data: depth_data,error: None,timestamp,})@@ -1115,10 +1121,12 @@ pub async fn fyers_ws_connect(url: "wss://socket.fyers.in/hsm/v1-5/prod".to_string(),api_key: Some(access_token.clone()),api_secret: None,+ client_id: None,enabled: true,reconnect_delay_ms: 5000,max_reconnect_attempts: 10,heartbeat_interval_ms: 30000,+ extra: None,};let mut adapter = crate::websocket::adapters::FyersAdapter::new(config);@@ -1321,6 +1329,59 @@ pub async fn fyers_ws_unsubscribe(}}+/// Batch subscribe to multiple symbols via Fyers WebSocket (FAST!)+/// This is much faster than subscribing one-by-one as it fetches all fytokens in one API call+#[tauri::command]+pub async fn fyers_ws_subscribe_batch(+ symbols: Vec<String>,+ mode: String,+) -> Result<ApiResponse<bool>, String> {+ eprintln!("[fyers_ws_subscribe_batch] Subscribing to {} symbols in {} mode", symbols.len(), mode);++ let timestamp = chrono::Utc::now().timestamp_millis();+ let start_time = std::time::Instant::now();++ let mut ws_guard = FYERS_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ // Map mode to data type+ let data_type = match mode.as_str() {+ "depth" | "market_depth" | "full" => crate::websocket::adapters::fyers::FyersDataType::DepthUpdate,+ "index" => crate::websocket::adapters::fyers::FyersDataType::IndexUpdate,+ _ => crate::websocket::adapters::fyers::FyersDataType::SymbolUpdate,+ };++ match adapter.subscribe_batch(&symbols, data_type).await {+ Ok(_) => {+ let elapsed = start_time.elapsed();+ eprintln!("[fyers_ws_subscribe_batch] ✓ Subscribed to {} symbols in {:?}", symbols.len(), elapsed);+ Ok(ApiResponse {+ success: true,+ data: Some(true),+ error: None,+ timestamp,+ })+ }+ Err(e) => {+ eprintln!("[fyers_ws_subscribe_batch] ✗ Batch subscription failed: {}", e);+ Ok(ApiResponse {+ success: false,+ data: Some(false),+ error: Some(format!("Batch subscription failed: {}", e)),+ timestamp,+ })+ }+ }+ } else {+ Ok(ApiResponse {+ success: false,+ data: Some(false),+ error: Some("WebSocket not connected. Call fyers_ws_connect first.".to_string()),+ timestamp,+ })+ }+}+/// Check Fyers WebSocket connection status#[tauri::command]pub async fn fyers_ws_is_connected() -> Result<bool, String> {diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/mod.rsindex 8fd79f3e9..7097b2235 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/brokers/mod.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/mod.rs@@ -69,6 +69,9 @@ pub mod tradier;// European Brokerspub mod saxobank;+// WebSocket Commands for all brokers+pub mod websocket_commands;+// Re-export everything from fyers (includes tauri command wrappers)pub use fyers::*;@@ -116,3 +119,6 @@ pub use saxobank::*;// Re-export common utility commandspub use common_commands::*;++// Re-export WebSocket commands for all brokers+pub use websocket_commands::*;diff --git a/fincept-terminal-desktop/src-tauri/src/commands/brokers/websocket_commands.rs b/fincept-terminal-desktop/src-tauri/src/commands/brokers/websocket_commands.rsnew file mode 100644index 000000000..4f8ae25c0--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/commands/brokers/websocket_commands.rs@@ -0,0 +1,945 @@+// WebSocket Commands for All Indian Stock Brokers+//+// Provides unified Tauri commands for WebSocket operations across all brokers.+// Each broker has: {broker}_ws_connect, {broker}_ws_disconnect, {broker}_ws_subscribe, {broker}_ws_unsubscribe++use crate::websocket::adapters::*;+use crate::websocket::types::{MarketMessage, ProviderConfig};+use once_cell::sync::Lazy;+use serde_json::json;+use std::collections::HashMap;+use std::sync::Arc;+use tauri::Emitter;+use tokio::sync::RwLock;++use super::common::ApiResponse;++// ============================================================================+// GLOBAL WEBSOCKET INSTANCES+// ============================================================================++static UPSTOX_WS: Lazy<Arc<RwLock<Option<UpstoxAdapter>>>> =+ Lazy::new(|| Arc::new(RwLock::new(None)));++static DHAN_WS: Lazy<Arc<RwLock<Option<DhanAdapter>>>> =+ Lazy::new(|| Arc::new(RwLock::new(None)));++static ANGELONE_WS: Lazy<Arc<RwLock<Option<AngelOneAdapter>>>> =+ Lazy::new(|| Arc::new(RwLock::new(None)));++static KOTAK_WS: Lazy<Arc<RwLock<Option<KotakAdapter>>>> =+ Lazy::new(|| Arc::new(RwLock::new(None)));++static GROWW_WS: Lazy<Arc<RwLock<Option<GrowwAdapter>>>> =+ Lazy::new(|| Arc::new(RwLock::new(None)));++static ALICEBLUE_WS: Lazy<Arc<RwLock<Option<AliceBlueAdapter>>>> =+ Lazy::new(|| Arc::new(RwLock::new(None)));++static FIVEPAISA_WS: Lazy<Arc<RwLock<Option<FivePaisaAdapter>>>> =+ Lazy::new(|| Arc::new(RwLock::new(None)));++static IIFL_WS: Lazy<Arc<RwLock<Option<IiflAdapter>>>> =+ Lazy::new(|| Arc::new(RwLock::new(None)));++static MOTILAL_WS: Lazy<Arc<RwLock<Option<MotilalAdapter>>>> =+ Lazy::new(|| Arc::new(RwLock::new(None)));++static SHOONYA_WS: Lazy<Arc<RwLock<Option<ShoonyaAdapter>>>> =+ Lazy::new(|| Arc::new(RwLock::new(None)));++// ============================================================================+// HELPER MACROS+// ============================================================================++/// Creates WebSocket event callback for a broker+fn create_ws_callback(app: tauri::AppHandle, broker: &'static str) -> Box<dyn Fn(MarketMessage) + Send + Sync> {+ Box::new(move |msg: MarketMessage| {+ match &msg {+ MarketMessage::Ticker(data) => {+ let _ = app.emit(&format!("{}_ticker", broker), data);+ }+ MarketMessage::OrderBook(data) => {+ let _ = app.emit(&format!("{}_orderbook", broker), data);+ }+ MarketMessage::Trade(data) => {+ let _ = app.emit(&format!("{}_trade", broker), data);+ }+ MarketMessage::Status(data) => {+ let _ = app.emit(&format!("{}_status", broker), data);+ }+ MarketMessage::Candle(data) => {+ let _ = app.emit(&format!("{}_candle", broker), data);+ }+ }+ })+}++// ============================================================================+// UPSTOX WEBSOCKET COMMANDS+// ============================================================================++#[tauri::command]+pub async fn upstox_ws_connect(+ app: tauri::AppHandle,+ access_token: String,+) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();++ let config = ProviderConfig {+ name: "upstox".to_string(),+ url: "wss://api.upstox.com/v3/feed/market-data-feed".to_string(),+ api_key: Some(access_token),+ ..Default::default()+ };++ let mut adapter = UpstoxAdapter::new(config);+ adapter.set_message_callback(create_ws_callback(app.clone(), "upstox"));++ match adapter.connect().await {+ Ok(_) => {+ *UPSTOX_WS.write().await = Some(adapter);+ let _ = app.emit("upstox_status", json!({+ "provider": "upstox",+ "status": "connected",+ "timestamp": timestamp+ }));+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ }+ Err(e) => {+ let _ = app.emit("upstox_status", json!({+ "provider": "upstox",+ "status": "error",+ "message": e.to_string(),+ "timestamp": timestamp+ }));+ Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp })+ }+ }+}++#[tauri::command]+pub async fn upstox_ws_disconnect() -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = UPSTOX_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.disconnect().await;+ *ws_guard = None;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn upstox_ws_subscribe(symbol: String, mode: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = UPSTOX_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let channel = match mode.as_str() {+ "full" | "depth" => "full",+ _ => "ltpc",+ };+ match adapter.subscribe(&symbol, channel, None).await {+ Ok(_) => Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp }),+ Err(e) => Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp }),+ }+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn upstox_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = UPSTOX_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.unsubscribe(&symbol, "").await;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++// ============================================================================+// DHAN WEBSOCKET COMMANDS+// ============================================================================++#[tauri::command]+pub async fn dhan_ws_connect(+ app: tauri::AppHandle,+ client_id: String,+ access_token: String,+ is_20_depth: Option<bool>,+) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();++ let mut extra = HashMap::new();+ if let Some(depth) = is_20_depth {+ extra.insert("is_20_depth".to_string(), serde_json::json!(depth));+ }++ let config = ProviderConfig {+ name: "dhan".to_string(),+ url: "wss://api-feed.dhan.co".to_string(),+ api_key: Some(access_token),+ client_id: Some(client_id),+ extra: Some(extra),+ ..Default::default()+ };++ let mut adapter = DhanAdapter::new(config);+ adapter.set_message_callback(create_ws_callback(app.clone(), "dhan"));++ match adapter.connect().await {+ Ok(_) => {+ *DHAN_WS.write().await = Some(adapter);+ let _ = app.emit("dhan_status", json!({+ "provider": "dhan",+ "status": "connected",+ "timestamp": timestamp+ }));+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ }+ Err(e) => {+ Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp })+ }+ }+}++#[tauri::command]+pub async fn dhan_ws_disconnect() -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = DHAN_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.disconnect().await;+ *ws_guard = None;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn dhan_ws_subscribe(symbol: String, mode: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = DHAN_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let channel = match mode.as_str() {+ "full" | "depth" => "full",+ "quote" => "quote",+ "20depth" => "20depth",+ _ => "ticker",+ };+ match adapter.subscribe(&symbol, channel, None).await {+ Ok(_) => Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp }),+ Err(e) => Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp }),+ }+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn dhan_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = DHAN_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.unsubscribe(&symbol, "").await;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++// ============================================================================+// ANGEL ONE WEBSOCKET COMMANDS+// ============================================================================++#[tauri::command]+pub async fn angelone_ws_connect(+ app: tauri::AppHandle,+ auth_token: String,+ api_key: String,+ client_code: String,+ feed_token: String,+) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();++ let mut extra = HashMap::new();+ extra.insert("feed_token".to_string(), serde_json::json!(feed_token));++ let config = ProviderConfig {+ name: "angelone".to_string(),+ url: "wss://smartapisocket.angelone.in/smart-stream".to_string(),+ api_key: Some(auth_token),+ api_secret: Some(api_key),+ client_id: Some(client_code),+ extra: Some(extra),+ ..Default::default()+ };++ let mut adapter = AngelOneAdapter::new(config);+ adapter.set_message_callback(create_ws_callback(app.clone(), "angelone"));++ match adapter.connect().await {+ Ok(_) => {+ *ANGELONE_WS.write().await = Some(adapter);+ let _ = app.emit("angelone_status", json!({+ "provider": "angelone",+ "status": "connected",+ "timestamp": timestamp+ }));+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ }+ Err(e) => {+ Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp })+ }+ }+}++#[tauri::command]+pub async fn angelone_ws_disconnect() -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = ANGELONE_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.disconnect().await;+ *ws_guard = None;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn angelone_ws_subscribe(symbol: String, mode: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = ANGELONE_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let channel = match mode.as_str() {+ "depth" => "depth",+ "quote" => "quote",+ "snap" | "snap_quote" => "snap",+ _ => "ltp",+ };+ match adapter.subscribe(&symbol, channel, None).await {+ Ok(_) => Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp }),+ Err(e) => Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp }),+ }+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn angelone_ws_unsubscribe(symbol: String, mode: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = ANGELONE_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.unsubscribe(&symbol, &mode).await;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++// ============================================================================+// KOTAK WEBSOCKET COMMANDS+// ============================================================================++#[tauri::command]+pub async fn kotak_ws_connect(+ app: tauri::AppHandle,+ access_token: String,+ consumer_key: String,+) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();++ let config = ProviderConfig {+ name: "kotak".to_string(),+ url: "wss://livefeeds.kotaksecurities.com".to_string(),+ api_key: Some(access_token),+ api_secret: Some(consumer_key),+ ..Default::default()+ };++ let mut adapter = KotakAdapter::new(config);+ adapter.set_message_callback(create_ws_callback(app.clone(), "kotak"));++ match adapter.connect().await {+ Ok(_) => {+ *KOTAK_WS.write().await = Some(adapter);+ let _ = app.emit("kotak_status", json!({+ "provider": "kotak",+ "status": "connected",+ "timestamp": timestamp+ }));+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ }+ Err(e) => {+ Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp })+ }+ }+}++#[tauri::command]+pub async fn kotak_ws_disconnect() -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = KOTAK_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.disconnect().await;+ *ws_guard = None;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn kotak_ws_subscribe(symbol: String, mode: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = KOTAK_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ match adapter.subscribe(&symbol, &mode, None).await {+ Ok(_) => Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp }),+ Err(e) => Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp }),+ }+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn kotak_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = KOTAK_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.unsubscribe(&symbol, "").await;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++// ============================================================================+// GROWW WEBSOCKET COMMANDS+// ============================================================================++#[tauri::command]+pub async fn groww_ws_connect(+ app: tauri::AppHandle,+ auth_token: String,+) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();++ let config = ProviderConfig {+ name: "groww".to_string(),+ url: "wss://socket-api.groww.in".to_string(),+ api_key: Some(auth_token),+ ..Default::default()+ };++ let mut adapter = GrowwAdapter::new(config);+ adapter.set_message_callback(create_ws_callback(app.clone(), "groww"));++ match adapter.connect().await {+ Ok(_) => {+ *GROWW_WS.write().await = Some(adapter);+ let _ = app.emit("groww_status", json!({+ "provider": "groww",+ "status": "connected",+ "timestamp": timestamp+ }));+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ }+ Err(e) => {+ Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp })+ }+ }+}++#[tauri::command]+pub async fn groww_ws_disconnect() -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = GROWW_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.disconnect().await;+ *ws_guard = None;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn groww_ws_subscribe(symbol: String, mode: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = GROWW_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let channel = match mode.as_str() {+ "depth" => "depth",+ _ => "ltp",+ };+ match adapter.subscribe(&symbol, channel, None).await {+ Ok(_) => Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp }),+ Err(e) => Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp }),+ }+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn groww_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = GROWW_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.unsubscribe(&symbol, "").await;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++// ============================================================================+// ALICE BLUE WEBSOCKET COMMANDS+// ============================================================================++#[tauri::command]+pub async fn aliceblue_ws_connect(+ app: tauri::AppHandle,+ user_id: String,+ session_token: String,+) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();++ let config = ProviderConfig {+ name: "aliceblue".to_string(),+ url: "wss://ws1.aliceblueonline.com/NorenWS/".to_string(),+ api_key: Some(session_token),+ client_id: Some(user_id),+ ..Default::default()+ };++ let mut adapter = AliceBlueAdapter::new(config);+ adapter.set_message_callback(create_ws_callback(app.clone(), "aliceblue"));++ match adapter.connect().await {+ Ok(_) => {+ *ALICEBLUE_WS.write().await = Some(adapter);+ let _ = app.emit("aliceblue_status", json!({+ "provider": "aliceblue",+ "status": "connected",+ "timestamp": timestamp+ }));+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ }+ Err(e) => {+ Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp })+ }+ }+}++#[tauri::command]+pub async fn aliceblue_ws_disconnect() -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = ALICEBLUE_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.disconnect().await;+ *ws_guard = None;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn aliceblue_ws_subscribe(symbol: String, mode: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = ALICEBLUE_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let channel = match mode.as_str() {+ "depth" => "depth",+ "quote" => "quote",+ _ => "ltp",+ };+ match adapter.subscribe(&symbol, channel, None).await {+ Ok(_) => Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp }),+ Err(e) => Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp }),+ }+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn aliceblue_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = ALICEBLUE_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.unsubscribe(&symbol, "").await;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++// ============================================================================+// 5PAISA WEBSOCKET COMMANDS+// ============================================================================++#[tauri::command]+pub async fn fivepaisa_ws_connect(+ app: tauri::AppHandle,+ client_code: String,+ jwt_token: String,+) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();++ let config = ProviderConfig {+ name: "fivepaisa".to_string(),+ url: "wss://openfeed.5paisa.com/Feeds/api/chat".to_string(),+ api_key: Some(jwt_token),+ client_id: Some(client_code),+ ..Default::default()+ };++ let mut adapter = FivePaisaAdapter::new(config);+ adapter.set_message_callback(create_ws_callback(app.clone(), "fivepaisa"));++ match adapter.connect().await {+ Ok(_) => {+ *FIVEPAISA_WS.write().await = Some(adapter);+ let _ = app.emit("fivepaisa_status", json!({+ "provider": "fivepaisa",+ "status": "connected",+ "timestamp": timestamp+ }));+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ }+ Err(e) => {+ Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp })+ }+ }+}++#[tauri::command]+pub async fn fivepaisa_ws_disconnect() -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = FIVEPAISA_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.disconnect().await;+ *ws_guard = None;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn fivepaisa_ws_subscribe(symbol: String, mode: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = FIVEPAISA_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let channel = match mode.as_str() {+ "depth" => "depth",+ "index" => "index",+ "oi" => "oi",+ _ => "ltp",+ };+ match adapter.subscribe(&symbol, channel, None).await {+ Ok(_) => Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp }),+ Err(e) => Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp }),+ }+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn fivepaisa_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = FIVEPAISA_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.unsubscribe(&symbol, "").await;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++// ============================================================================+// IIFL WEBSOCKET COMMANDS+// ============================================================================++#[tauri::command]+pub async fn iifl_ws_connect(+ app: tauri::AppHandle,+ app_key: String,+ secret_key: String,+) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();++ let config = ProviderConfig {+ name: "iifl".to_string(),+ url: "wss://ttblaze.iifl.com".to_string(),+ api_key: Some(app_key),+ api_secret: Some(secret_key),+ ..Default::default()+ };++ let mut adapter = IiflAdapter::new(config);+ adapter.set_message_callback(create_ws_callback(app.clone(), "iifl"));++ match adapter.connect().await {+ Ok(_) => {+ *IIFL_WS.write().await = Some(adapter);+ let _ = app.emit("iifl_status", json!({+ "provider": "iifl",+ "status": "connected",+ "timestamp": timestamp+ }));+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ }+ Err(e) => {+ Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp })+ }+ }+}++#[tauri::command]+pub async fn iifl_ws_disconnect() -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = IIFL_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.disconnect().await;+ *ws_guard = None;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn iifl_ws_subscribe(symbol: String, mode: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = IIFL_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let channel = match mode.as_str() {+ "depth" => "depth",+ "quote" => "quote",+ _ => "ltp",+ };+ match adapter.subscribe(&symbol, channel, None).await {+ Ok(_) => Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp }),+ Err(e) => Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp }),+ }+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn iifl_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = IIFL_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.unsubscribe(&symbol, "").await;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++// ============================================================================+// MOTILAL OSWAL WEBSOCKET COMMANDS+// ============================================================================++#[tauri::command]+pub async fn motilal_ws_connect(+ app: tauri::AppHandle,+ access_token: String,+) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();++ let config = ProviderConfig {+ name: "motilal".to_string(),+ url: "wss://wsapi.motilaloswal.com/".to_string(),+ api_key: Some(access_token),+ ..Default::default()+ };++ let mut adapter = MotilalAdapter::new(config);+ adapter.set_message_callback(create_ws_callback(app.clone(), "motilal"));++ match adapter.connect().await {+ Ok(_) => {+ *MOTILAL_WS.write().await = Some(adapter);+ let _ = app.emit("motilal_status", json!({+ "provider": "motilal",+ "status": "connected",+ "timestamp": timestamp+ }));+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ }+ Err(e) => {+ Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp })+ }+ }+}++#[tauri::command]+pub async fn motilal_ws_disconnect() -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = MOTILAL_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.disconnect().await;+ *ws_guard = None;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn motilal_ws_subscribe(symbol: String, mode: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = MOTILAL_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let channel = match mode.as_str() {+ "depth" => "depth",+ "quote" => "quote",+ _ => "ltp",+ };+ match adapter.subscribe(&symbol, channel, None).await {+ Ok(_) => Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp }),+ Err(e) => Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp }),+ }+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn motilal_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = MOTILAL_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.unsubscribe(&symbol, "").await;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++// ============================================================================+// SHOONYA WEBSOCKET COMMANDS+// ============================================================================++#[tauri::command]+pub async fn shoonya_ws_connect(+ app: tauri::AppHandle,+ user_id: String,+ session_token: String,+) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();++ let config = ProviderConfig {+ name: "shoonya".to_string(),+ url: "wss://api.shoonya.com/NorenWSTP/".to_string(),+ api_key: Some(session_token),+ client_id: Some(user_id),+ ..Default::default()+ };++ let mut adapter = ShoonyaAdapter::new(config);+ adapter.set_message_callback(create_ws_callback(app.clone(), "shoonya"));++ match adapter.connect().await {+ Ok(_) => {+ *SHOONYA_WS.write().await = Some(adapter);+ let _ = app.emit("shoonya_status", json!({+ "provider": "shoonya",+ "status": "connected",+ "timestamp": timestamp+ }));+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ }+ Err(e) => {+ Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp })+ }+ }+}++#[tauri::command]+pub async fn shoonya_ws_disconnect() -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = SHOONYA_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.disconnect().await;+ *ws_guard = None;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn shoonya_ws_subscribe(symbol: String, mode: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = SHOONYA_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let channel = match mode.as_str() {+ "depth" => "depth",+ _ => "touchline",+ };+ match adapter.subscribe(&symbol, channel, None).await {+ Ok(_) => Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp }),+ Err(e) => Ok(ApiResponse { success: false, data: Some(false), error: Some(e.to_string()), timestamp }),+ }+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}++#[tauri::command]+pub async fn shoonya_ws_unsubscribe(symbol: String) -> Result<ApiResponse<bool>, String> {+ let timestamp = chrono::Utc::now().timestamp_millis();+ let mut ws_guard = SHOONYA_WS.write().await;++ if let Some(ref mut adapter) = *ws_guard {+ let _ = adapter.unsubscribe(&symbol, "").await;+ Ok(ApiResponse { success: true, data: Some(true), error: None, timestamp })+ } else {+ Ok(ApiResponse { success: false, data: Some(false), error: Some("Not connected".to_string()), timestamp })+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/database.rs b/fincept-terminal-desktop/src-tauri/src/commands/database.rsindex 1e9bc5b1d..4bca412c8 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/database.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/database.rs@@ -118,6 +118,16 @@ pub async fn db_toggle_llm_model_config_enabled(id: String) -> Result<OperationRoperations::toggle_llm_model_config_enabled(&id).map_err(|e| e.to_string())}+#[tauri::command]+pub async fn db_update_llm_model_id(id: String, new_model_id: String) -> Result<OperationResult, String> {+ operations::update_llm_model_id(&id, &new_model_id).map_err(|e| e.to_string())+}++#[tauri::command]+pub async fn db_fix_google_model_ids() -> Result<OperationResult, String> {+ operations::fix_google_model_ids().map_err(|e| e.to_string())+}+// ============================================================================// Chat Commands// ============================================================================diff --git a/fincept-terminal-desktop/src-tauri/src/commands/llm_models.rs b/fincept-terminal-desktop/src-tauri/src/commands/llm_models.rsnew file mode 100644index 000000000..df96a262b--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/commands/llm_models.rs@@ -0,0 +1,130 @@+// LLM Models Commands - Fetch models from embedded JSON data+// No external Python dependencies required - uses pre-extracted model data+use serde::{Deserialize, Serialize};+use tauri::AppHandle;++use crate::utils::python::execute_python_subprocess;++#[derive(Debug, Serialize, Deserialize)]+pub struct LLMProvider {+ pub id: String,+ pub name: String,+ pub model_count: i32,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct LLMModel {+ pub id: String,+ pub name: String,+ pub provider: String,+ #[serde(default)]+ pub description: Option<String>,+ #[serde(default)]+ pub context_window: Option<i64>,+ #[serde(default)]+ pub input_cost_per_token: Option<f64>,+ #[serde(default)]+ pub output_cost_per_token: Option<f64>,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct LLMStats {+ pub total_providers: i32,+ pub total_models: i32,+ pub top_providers: Vec<TopProvider>,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct TopProvider {+ pub provider: String,+ pub model_count: i32,+}++/// Get all available LLM providers from embedded model data+#[tauri::command]+pub fn get_llm_providers(app: AppHandle) -> Result<Vec<LLMProvider>, String> {+ let output = execute_python_subprocess(+ &app,+ "litellm_models.py",+ &["providers".to_string()],+ None, // No special library required - uses embedded JSON+ )?;++ let providers: Vec<LLMProvider> = serde_json::from_str(&output)+ .map_err(|e| format!("Failed to parse providers: {} - Output: {}", e, output))?;++ // Check for error in response+ if providers.len() == 1 {+ if let Some(first) = providers.first() {+ if first.id == "error" {+ return Err(first.name.clone());+ }+ }+ }++ Ok(providers)+}++/// Get all models for a specific provider from embedded model data+#[tauri::command]+pub fn get_llm_models_by_provider(app: AppHandle, provider: String) -> Result<Vec<LLMModel>, String> {+ let output = execute_python_subprocess(+ &app,+ "litellm_models.py",+ &["models".to_string(), provider.clone()],+ None,+ )?;++ let models: Vec<LLMModel> = serde_json::from_str(&output)+ .map_err(|e| format!("Failed to parse models for {}: {} - Output: {}", provider, e, output))?;++ Ok(models)+}++/// Get all models from all providers+#[tauri::command]+pub fn get_all_llm_models(app: AppHandle) -> Result<Vec<LLMModel>, String> {+ let output = execute_python_subprocess(+ &app,+ "litellm_models.py",+ &["models".to_string()],+ None,+ )?;++ let models: Vec<LLMModel> = serde_json::from_str(&output)+ .map_err(|e| format!("Failed to parse all models: {} - Output: {}", e, output))?;++ Ok(models)+}++/// Get LLM provider statistics+#[tauri::command]+pub fn get_llm_stats(app: AppHandle) -> Result<LLMStats, String> {+ let output = execute_python_subprocess(+ &app,+ "litellm_models.py",+ &["stats".to_string()],+ None,+ )?;++ let stats: LLMStats = serde_json::from_str(&output)+ .map_err(|e| format!("Failed to parse stats: {} - Output: {}", e, output))?;++ Ok(stats)+}++/// Search models by name or provider+#[tauri::command]+pub fn search_llm_models(app: AppHandle, query: String) -> Result<Vec<LLMModel>, String> {+ let output = execute_python_subprocess(+ &app,+ "litellm_models.py",+ &["search".to_string(), query.clone()],+ None,+ )?;++ let models: Vec<LLMModel> = serde_json::from_str(&output)+ .map_err(|e| format!("Failed to search models for '{}': {} - Output: {}", query, e, output))?;++ Ok(models)+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rsindex 04a945cbe..41d27fa9a 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs@@ -63,6 +63,7 @@ pub mod jupyter;// Python Agentspub mod agents;+pub mod agent_streaming;// Portfolio Analyticspub mod portfolio;@@ -153,3 +154,6 @@ pub mod unified_trading;// AKShare - Free Chinese & Global market datapub mod akshare;++// LLM Models - LiteLLM provider and model listing+pub mod llm_models;diff --git a/fincept-terminal-desktop/src-tauri/src/database/operations.rs b/fincept-terminal-desktop/src-tauri/src/database/operations.rsindex 5b29a780a..becd8147b 100644--- a/fincept-terminal-desktop/src-tauri/src/database/operations.rs+++ b/fincept-terminal-desktop/src-tauri/src/database/operations.rs@@ -350,6 +350,61 @@ pub fn toggle_llm_model_config_enabled(id: &str) -> Result<OperationResult> {}}+/// Update model_id for a specific LLM model config+pub fn update_llm_model_id(id: &str, new_model_id: &str) -> Result<OperationResult> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ let rows_affected = conn.execute(+ "UPDATE llm_model_configs SET model_id = ?1, updated_at = CURRENT_TIMESTAMP WHERE id = ?2",+ params![new_model_id, id],+ )?;++ if rows_affected > 0 {+ Ok(OperationResult {+ success: true,+ message: format!("Model ID updated to: {}", new_model_id),+ })+ } else {+ Ok(OperationResult {+ success: false,+ message: "Model configuration not found".to_string(),+ })+ }+}++/// Fix all Google model IDs to use correct format (without prefix)+pub fn fix_google_model_ids() -> Result<OperationResult> {+ let pool = get_pool()?;+ let conn = pool.get()?;++ // Fix model_ids that have incorrect prefixes like "google/" or "models/"+ let rows_affected = conn.execute(+ "UPDATE llm_model_configs+ SET model_id = REPLACE(REPLACE(model_id, 'google/', ''), 'models/', ''),+ updated_at = CURRENT_TIMESTAMP+ WHERE provider = 'google'+ AND (model_id LIKE 'google/%' OR model_id LIKE 'models/%')",+ [],+ )?;++ // Also ensure common model names are correct+ conn.execute(+ "UPDATE llm_model_configs+ SET model_id = 'gemini-1.5-flash',+ updated_at = CURRENT_TIMESTAMP+ WHERE provider = 'google'+ AND model_id NOT LIKE 'gemini-%'+ AND model_id != ''",+ [],+ )?;++ Ok(OperationResult {+ success: true,+ message: format!("Fixed {} Google model configurations", rows_affected),+ })+}+// ============================================================================// Chat Operations// ============================================================================diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rsindex febee11ab..fe51f6bb7 100644--- a/fincept-terminal-desktop/src-tauri/src/lib.rs+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs@@ -1378,9 +1378,22 @@ pub fn run() {commands::agents::list_available_agents,commands::agents::execute_python_agent,commands::agents::get_agent_metadata,- commands::agents::execute_python_agent_command,commands::agents::execute_core_agent,commands::agents::read_agent_config,+ // SuperAgent & Planner Commands+ commands::agents::route_query,+ commands::agents::execute_routed_query,+ commands::agents::discover_agents,+ commands::agents::create_stock_analysis_plan,+ commands::agents::execute_plan,+ commands::agents::save_trade_decision,+ commands::agents::get_trade_decisions,+ // Agent Streaming & Performance Commands+ commands::agent_streaming::execute_agent_streaming,+ commands::agent_streaming::cancel_agent_stream,+ commands::agent_streaming::execute_agents_parallel,+ commands::agent_streaming::execute_agent_priority,+ commands::agent_streaming::get_active_agent_streams,// Portfolio Analytics Commands// Portfolio Management (CRUD operations)commands::portfolio_management::portfolio_create,@@ -1620,13 +1633,21 @@ pub fn run() {commands::agno_trading::agno_evolve_agent,commands::agno_trading::agno_check_evolution,commands::agno_trading::agno_get_evolution_summary,- // Alpha Arena Competition+ // Alpha Arena Competition (v2 refactored)commands::alpha_arena::create_alpha_competition,commands::alpha_arena::start_alpha_competition,commands::alpha_arena::get_alpha_leaderboard,commands::alpha_arena::get_alpha_model_decisions,commands::alpha_arena::stop_alpha_competition,commands::alpha_arena::run_alpha_cycle,+ commands::alpha_arena::get_alpha_snapshots,+ commands::alpha_arena::list_alpha_agents,+ commands::alpha_arena::get_alpha_evaluation,+ commands::alpha_arena::get_alpha_api_keys,+ commands::alpha_arena::save_alpha_api_keys,+ commands::alpha_arena::list_alpha_competitions,+ commands::alpha_arena::get_alpha_competition,+ commands::alpha_arena::delete_alpha_competition,// AI Quant Lab - Qlibcommands::ai_quant_lab::qlib_initialize,commands::ai_quant_lab::qlib_check_status,@@ -1716,6 +1737,8 @@ pub fn run() {commands::database::db_save_llm_model_config,commands::database::db_delete_llm_model_config,commands::database::db_toggle_llm_model_config_enabled,+ commands::database::db_update_llm_model_id,+ commands::database::db_fix_google_model_ids,commands::database::db_create_chat_session,commands::database::db_get_chat_sessions,commands::database::db_add_chat_message,@@ -1906,6 +1929,7 @@ pub fn run() {commands::brokers::fyers_ws_connect,commands::brokers::fyers_ws_disconnect,commands::brokers::fyers_ws_subscribe,+ commands::brokers::fyers_ws_subscribe_batch,commands::brokers::fyers_ws_unsubscribe,commands::brokers::fyers_ws_is_connected,// Upstox Broker Commands@@ -2062,6 +2086,47 @@ pub fn run() {commands::brokers::shoonya_get_token_for_symbol,commands::brokers::shoonya_get_symbol_by_token,commands::brokers::shoonya_get_master_contract_metadata,+ // Indian Broker WebSocket Commands+ commands::brokers::upstox_ws_connect,+ commands::brokers::upstox_ws_disconnect,+ commands::brokers::upstox_ws_subscribe,+ commands::brokers::upstox_ws_unsubscribe,+ commands::brokers::dhan_ws_connect,+ commands::brokers::dhan_ws_disconnect,+ commands::brokers::dhan_ws_subscribe,+ commands::brokers::dhan_ws_unsubscribe,+ commands::brokers::angelone_ws_connect,+ commands::brokers::angelone_ws_disconnect,+ commands::brokers::angelone_ws_subscribe,+ commands::brokers::angelone_ws_unsubscribe,+ commands::brokers::kotak_ws_connect,+ commands::brokers::kotak_ws_disconnect,+ commands::brokers::kotak_ws_subscribe,+ commands::brokers::kotak_ws_unsubscribe,+ commands::brokers::groww_ws_connect,+ commands::brokers::groww_ws_disconnect,+ commands::brokers::groww_ws_subscribe,+ commands::brokers::groww_ws_unsubscribe,+ commands::brokers::aliceblue_ws_connect,+ commands::brokers::aliceblue_ws_disconnect,+ commands::brokers::aliceblue_ws_subscribe,+ commands::brokers::aliceblue_ws_unsubscribe,+ commands::brokers::fivepaisa_ws_connect,+ commands::brokers::fivepaisa_ws_disconnect,+ commands::brokers::fivepaisa_ws_subscribe,+ commands::brokers::fivepaisa_ws_unsubscribe,+ commands::brokers::iifl_ws_connect,+ commands::brokers::iifl_ws_disconnect,+ commands::brokers::iifl_ws_subscribe,+ commands::brokers::iifl_ws_unsubscribe,+ commands::brokers::motilal_ws_connect,+ commands::brokers::motilal_ws_disconnect,+ commands::brokers::motilal_ws_subscribe,+ commands::brokers::motilal_ws_unsubscribe,+ commands::brokers::shoonya_ws_connect,+ commands::brokers::shoonya_ws_disconnect,+ commands::brokers::shoonya_ws_subscribe,+ commands::brokers::shoonya_ws_unsubscribe,// Alpaca US Broker Commands (Paper/Live Trading)commands::brokers::alpaca_get_account,commands::brokers::alpaca_get_clock,@@ -2185,6 +2250,32 @@ pub fn run() {commands::brokers::saxo_get_exposure,commands::brokers::saxo_get_option_chain,commands::brokers::saxo_get_option_expiries,+ // Tradier (US) broker commands+ commands::brokers::tradier_get_profile,+ commands::brokers::tradier_get_balances,+ commands::brokers::tradier_get_positions,+ commands::brokers::tradier_get_history,+ commands::brokers::tradier_get_gainloss,+ commands::brokers::tradier_get_orders,+ commands::brokers::tradier_get_order,+ commands::brokers::tradier_place_order,+ commands::brokers::tradier_modify_order,+ commands::brokers::tradier_cancel_order,+ commands::brokers::tradier_get_quotes,+ commands::brokers::tradier_get_historical,+ commands::brokers::tradier_get_timesales,+ commands::brokers::tradier_get_option_chains,+ commands::brokers::tradier_get_option_expirations,+ commands::brokers::tradier_get_option_strikes,+ commands::brokers::tradier_get_clock,+ commands::brokers::tradier_get_calendar,+ commands::brokers::tradier_search_symbols,+ commands::brokers::tradier_lookup_symbol,+ commands::brokers::tradier_get_stream_session,+ commands::brokers::tradier_ws_connect,+ commands::brokers::tradier_ws_subscribe,+ commands::brokers::tradier_ws_unsubscribe,+ commands::brokers::tradier_ws_disconnect,// Generic Storage Commands (SQLite key-value storage)commands::storage::storage_set,commands::storage::storage_get,@@ -2227,7 +2318,13 @@ pub fn run() {commands::akshare::get_stock_hk_profile,commands::akshare::get_stock_us_info,commands::akshare::check_akshare_db_status,- commands::akshare::build_akshare_database+ commands::akshare::build_akshare_database,+ // LLM Models Commands (LiteLLM provider and model listing)+ commands::llm_models::get_llm_providers,+ commands::llm_models::get_llm_models_by_provider,+ commands::llm_models::get_all_llm_models,+ commands::llm_models::get_llm_stats,+ commands::llm_models::search_llm_models]).run(tauri::generate_context!()).expect("error while running tauri application");diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/aliceblue.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/aliceblue.rsnew file mode 100644index 000000000..7190e4b4b--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/aliceblue.rs@@ -0,0 +1,269 @@+// Alice Blue WebSocket Adapter+//+// Alice Blue (ANT) uses WebSocket for market data:+// - WebSocket URL: wss://ws1.aliceblueonline.com/NorenWS/+// - Authentication via user session token+// - JSON-based subscription protocol++use super::WebSocketAdapter;+use crate::websocket::types::*;+use async_trait::async_trait;+use futures_util::{SinkExt, StreamExt};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::collections::HashMap;+use std::sync::Arc;+use tokio::net::TcpStream;+use tokio::sync::RwLock;+use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream};++// ============================================================================+// ALICE BLUE CONFIGURATION+// ============================================================================++const ALICEBLUE_WS_URL: &str = "wss://ws1.aliceblueonline.com/NorenWS/";++// ============================================================================+// ALICE BLUE STRUCTURES+// ============================================================================++#[derive(Debug, Clone, PartialEq)]+pub enum AliceBlueMode {+ Ltp,+ Quote,+ Depth,+}++#[derive(Debug, Serialize)]+struct ConnectRequest {+ t: String, // "c" for connect+ uid: String,+ actid: String,+ susertoken: String,+ source: String,+}++#[derive(Debug, Serialize)]+struct SubscribeRequest {+ t: String, // "t" for subscribe, "u" for unsubscribe, "d" for depth+ k: String, // scrips in format "exchange|token"+}++#[derive(Debug, Deserialize)]+struct TickData {+ t: Option<String>,+ tk: Option<String>, // Token+ e: Option<String>, // Exchange+ lp: Option<String>, // LTP+ v: Option<String>, // Volume+ o: Option<String>, // Open+ h: Option<String>, // High+ l: Option<String>, // Low+ c: Option<String>, // Close+ bp1: Option<String>, // Best bid price 1+ bq1: Option<String>, // Best bid qty 1+ sp1: Option<String>, // Best ask price 1+ sq1: Option<String>, // Best ask qty 1+}++#[derive(Debug, Clone)]+pub struct AliceBlueTick {+ pub token: String,+ pub exchange: String,+ pub ltp: f64,+ pub volume: i64,+ pub open: f64,+ pub high: f64,+ pub low: f64,+ pub close: f64,+ pub bid_price: f64,+ pub bid_qty: i64,+ pub ask_price: f64,+ pub ask_qty: i64,+}++// ============================================================================+// ALICE BLUE ADAPTER+// ============================================================================++pub struct AliceBlueAdapter {+ config: ProviderConfig,+ user_id: String,+ session_token: String,+ ws_stream: Arc<RwLock<Option<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,+ message_callback: Option<Box<dyn Fn(MarketMessage) + Send + Sync>>,+ subscriptions: Arc<RwLock<HashMap<String, AliceBlueMode>>>,+ is_connected: Arc<RwLock<bool>>,+}++impl AliceBlueAdapter {+ pub fn new(config: ProviderConfig) -> Self {+ let user_id = config.client_id.clone().unwrap_or_default();+ let session_token = config.api_key.clone().unwrap_or_default();++ Self {+ config,+ user_id,+ session_token,+ ws_stream: Arc::new(RwLock::new(None)),+ message_callback: None,+ subscriptions: Arc::new(RwLock::new(HashMap::new())),+ is_connected: Arc::new(RwLock::new(false)),+ }+ }++ fn parse_tick_data(&self, data: &str) -> Option<AliceBlueTick> {+ let tick: TickData = serde_json::from_str(data).ok()?;++ // Skip non-tick messages+ if tick.t.as_deref() != Some("tk") && tick.t.as_deref() != Some("tf") && tick.t.as_deref() != Some("dk") {+ return None;+ }++ Some(AliceBlueTick {+ token: tick.tk.unwrap_or_default(),+ exchange: tick.e.unwrap_or_default(),+ ltp: tick.lp.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ volume: tick.v.and_then(|s| s.parse().ok()).unwrap_or(0),+ open: tick.o.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ high: tick.h.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ low: tick.l.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ close: tick.c.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ bid_price: tick.bp1.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ bid_qty: tick.bq1.and_then(|s| s.parse().ok()).unwrap_or(0),+ ask_price: tick.sp1.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ ask_qty: tick.sq1.and_then(|s| s.parse().ok()).unwrap_or(0),+ })+ }+}++#[async_trait]+impl WebSocketAdapter for AliceBlueAdapter {+ async fn connect(&mut self) -> anyhow::Result<()> {+ tracing::info!("Connecting to Alice Blue WebSocket");++ let (ws_stream, _) = connect_async(ALICEBLUE_WS_URL).await?;+ tracing::info!("Connected to Alice Blue WebSocket");++ *self.ws_stream.write().await = Some(ws_stream);++ // Send connect request+ let connect_req = ConnectRequest {+ t: "c".to_string(),+ uid: self.user_id.clone(),+ actid: self.user_id.clone(),+ susertoken: self.session_token.clone(),+ source: "API".to_string(),+ };++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(serde_json::to_string(&connect_req)?)).await?;+ }++ *self.is_connected.write().await = true;++ let ws_stream = self.ws_stream.clone();+ let is_connected = self.is_connected.clone();++ tokio::spawn(async move {+ loop {+ let mut stream = ws_stream.write().await;+ if let Some(ref mut ws) = *stream {+ match ws.next().await {+ Some(Ok(Message::Text(text))) => {+ tracing::debug!("Received: {}", text);+ }+ Some(Ok(Message::Ping(data))) => {+ let _ = ws.send(Message::Pong(data)).await;+ }+ Some(Err(e)) => {+ tracing::error!("WebSocket error: {}", e);+ *is_connected.write().await = false;+ break;+ }+ None => {+ *is_connected.write().await = false;+ break;+ }+ _ => {}+ }+ } else {+ break;+ }+ drop(stream);+ tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;+ }+ });++ Ok(())+ }++ async fn disconnect(&mut self) -> anyhow::Result<()> {+ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.close(None).await?;+ }+ *self.ws_stream.write().await = None;+ *self.is_connected.write().await = false;+ tracing::info!("Disconnected from Alice Blue WebSocket");+ Ok(())+ }++ async fn subscribe(+ &mut self,+ symbol: &str,+ channel: &str,+ _params: Option<Value>,+ ) -> anyhow::Result<()> {+ let mode = match channel {+ "depth" => AliceBlueMode::Depth,+ "quote" => AliceBlueMode::Quote,+ _ => AliceBlueMode::Ltp,+ };++ // Symbol format: "NSE|12345" or "NFO|67890"+ let msg_type = match mode {+ AliceBlueMode::Depth => "d",+ _ => "t",+ };++ let subscribe_req = SubscribeRequest {+ t: msg_type.to_string(),+ k: symbol.to_string(),+ };++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(serde_json::to_string(&subscribe_req)?)).await?;+ self.subscriptions.write().await.insert(symbol.to_string(), mode);+ tracing::info!("Subscribed to {}", symbol);+ }++ Ok(())+ }++ async fn unsubscribe(&mut self, symbol: &str, _channel: &str) -> anyhow::Result<()> {+ let unsubscribe_req = SubscribeRequest {+ t: "u".to_string(),+ k: symbol.to_string(),+ };++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(serde_json::to_string(&unsubscribe_req)?)).await?;+ self.subscriptions.write().await.remove(symbol);+ tracing::info!("Unsubscribed from {}", symbol);+ }++ Ok(())+ }++ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {+ self.message_callback = Some(callback);+ }++ fn provider_name(&self) -> &str {+ "aliceblue"+ }++ fn is_connected(&self) -> bool {+ self.is_connected.try_read().map(|g| *g).unwrap_or(false)+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/angelone.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/angelone.rsnew file mode 100644index 000000000..f9f98cba1--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/angelone.rs@@ -0,0 +1,532 @@+// Angel One (SmartAPI) WebSocket Adapter+//+// Angel One uses SmartWebSocketV2 protocol:+// - WebSocket URL: wss://smartapisocket.angelone.in/smart-stream+// - Authentication via headers: Authorization, x-api-key, x-client-code, x-feed-token+// - Binary message format with subscription modes: LTP(1), Quote(2), SnapQuote(3), Depth(4)++use super::WebSocketAdapter;+use crate::websocket::types::*;+use async_trait::async_trait;+use futures_util::{SinkExt, StreamExt};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::collections::HashMap;+use std::sync::Arc;+use tokio::net::TcpStream;+use tokio::sync::RwLock;+use tokio_tungstenite::{+ connect_async_with_config,+ tungstenite::{+ http::{Request, Uri},+ Message,+ },+ MaybeTlsStream, WebSocketStream,+};++// ============================================================================+// ANGEL ONE CONFIGURATION+// ============================================================================++const ANGEL_WS_URL: &str = "wss://smartapisocket.angelone.in/smart-stream";+const HEARTBEAT_INTERVAL: u64 = 10; // seconds++// Subscription modes+const MODE_LTP: u8 = 1;+const MODE_QUOTE: u8 = 2;+const MODE_SNAP_QUOTE: u8 = 3;+const MODE_DEPTH: u8 = 4;++// Exchange types+const NSE_CM: u8 = 1;+const NSE_FO: u8 = 2;+const BSE_CM: u8 = 3;+const BSE_FO: u8 = 4;+const MCX_FO: u8 = 5;++// Actions+const ACTION_SUBSCRIBE: u8 = 1;+const ACTION_UNSUBSCRIBE: u8 = 0;++// ============================================================================+// ANGEL ONE STRUCTURES+// ============================================================================++#[derive(Debug, Clone, PartialEq)]+pub enum AngelMode {+ Ltp,+ Quote,+ SnapQuote,+ Depth,+}++impl AngelMode {+ fn to_code(&self) -> u8 {+ match self {+ AngelMode::Ltp => MODE_LTP,+ AngelMode::Quote => MODE_QUOTE,+ AngelMode::SnapQuote => MODE_SNAP_QUOTE,+ AngelMode::Depth => MODE_DEPTH,+ }+ }+}++#[derive(Debug, Serialize)]+struct SubscriptionRequest {+ #[serde(rename = "correlationID")]+ correlation_id: String,+ action: u8,+ params: SubscriptionParams,+}++#[derive(Debug, Serialize)]+struct SubscriptionParams {+ mode: u8,+ #[serde(rename = "tokenList")]+ token_list: Vec<TokenListItem>,+}++#[derive(Debug, Serialize, Clone)]+struct TokenListItem {+ #[serde(rename = "exchangeType")]+ exchange_type: u8,+ tokens: Vec<String>,+}++#[derive(Debug, Clone)]+pub struct AngelTick {+ pub subscription_mode: u8,+ pub exchange_type: u8,+ pub token: String,+ pub sequence_number: i64,+ pub exchange_timestamp: i64,+ pub ltp: f64,+ pub ltq: i64,+ pub atp: f64,+ pub volume: i64,+ pub total_buy_qty: f64,+ pub total_sell_qty: f64,+ pub open: f64,+ pub high: f64,+ pub low: f64,+ pub close: f64,+ pub last_traded_timestamp: i64,+ pub oi: i64,+ pub oi_day_high: i64,+ pub oi_day_low: i64,+ pub depth: Option<AngelDepth>,+}++#[derive(Debug, Clone)]+pub struct AngelDepth {+ pub buy: Vec<AngelDepthLevel>,+ pub sell: Vec<AngelDepthLevel>,+}++#[derive(Debug, Clone)]+pub struct AngelDepthLevel {+ pub price: f64,+ pub quantity: i64,+ pub orders: i16,+}++// ============================================================================+// ANGEL ONE ADAPTER+// ============================================================================++pub struct AngelOneAdapter {+ config: ProviderConfig,+ auth_token: String,+ api_key: String,+ client_code: String,+ feed_token: String,+ ws_stream: Arc<RwLock<Option<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,+ message_callback: Option<Box<dyn Fn(MarketMessage) + Send + Sync>>,+ subscriptions: Arc<RwLock<HashMap<String, AngelMode>>>,+ is_connected: Arc<RwLock<bool>>,+ token_symbol_map: Arc<RwLock<HashMap<String, String>>>,+}++impl AngelOneAdapter {+ pub fn new(config: ProviderConfig) -> Self {+ let auth_token = config.api_key.clone().unwrap_or_default();+ let api_key = config.api_secret.clone().unwrap_or_default();+ let client_code = config.client_id.clone().unwrap_or_default();+ let feed_token = config.extra.as_ref()+ .and_then(|e| e.get("feed_token"))+ .and_then(|v| v.as_str())+ .unwrap_or("")+ .to_string();++ Self {+ config,+ auth_token,+ api_key,+ client_code,+ feed_token,+ ws_stream: Arc::new(RwLock::new(None)),+ message_callback: None,+ subscriptions: Arc::new(RwLock::new(HashMap::new())),+ is_connected: Arc::new(RwLock::new(false)),+ token_symbol_map: Arc::new(RwLock::new(HashMap::new())),+ }+ }++ /// Parse binary market data from Angel One+ fn parse_binary_data(&self, data: &[u8]) -> Option<AngelTick> {+ if data.len() < 27 {+ return None;+ }++ // Parse header+ let subscription_mode = data[0];+ let exchange_type = data[1];++ // Parse token (25 bytes, null-terminated string)+ let token_bytes = &data[2..27];+ let token = String::from_utf8_lossy(token_bytes)+ .trim_end_matches('\0')+ .to_string();++ let mut offset = 27;++ // Parse sequence number (8 bytes)+ if offset + 8 > data.len() {+ return None;+ }+ let sequence_number = i64::from_le_bytes([+ data[offset], data[offset+1], data[offset+2], data[offset+3],+ data[offset+4], data[offset+5], data[offset+6], data[offset+7],+ ]);+ offset += 8;++ // Parse exchange timestamp (8 bytes)+ if offset + 8 > data.len() {+ return None;+ }+ let exchange_timestamp = i64::from_le_bytes([+ data[offset], data[offset+1], data[offset+2], data[offset+3],+ data[offset+4], data[offset+5], data[offset+6], data[offset+7],+ ]);+ offset += 8;++ // Parse LTP (8 bytes, divide by 100)+ if offset + 8 > data.len() {+ return None;+ }+ let ltp_raw = i64::from_le_bytes([+ data[offset], data[offset+1], data[offset+2], data[offset+3],+ data[offset+4], data[offset+5], data[offset+6], data[offset+7],+ ]);+ let ltp = ltp_raw as f64 / 100.0;+ offset += 8;++ let mut tick = AngelTick {+ subscription_mode,+ exchange_type,+ token,+ sequence_number,+ exchange_timestamp,+ ltp,+ ltq: 0,+ atp: 0.0,+ volume: 0,+ total_buy_qty: 0.0,+ total_sell_qty: 0.0,+ open: 0.0,+ high: 0.0,+ low: 0.0,+ close: 0.0,+ last_traded_timestamp: 0,+ oi: 0,+ oi_day_high: 0,+ oi_day_low: 0,+ depth: None,+ };++ // Parse additional fields for Quote mode+ if subscription_mode >= MODE_QUOTE && offset + 56 <= data.len() {+ tick.ltq = i64::from_le_bytes([+ data[offset], data[offset+1], data[offset+2], data[offset+3],+ data[offset+4], data[offset+5], data[offset+6], data[offset+7],+ ]);+ offset += 8;++ let atp_raw = i64::from_le_bytes([+ data[offset], data[offset+1], data[offset+2], data[offset+3],+ data[offset+4], data[offset+5], data[offset+6], data[offset+7],+ ]);+ tick.atp = atp_raw as f64 / 100.0;+ offset += 8;++ tick.volume = i64::from_le_bytes([+ data[offset], data[offset+1], data[offset+2], data[offset+3],+ data[offset+4], data[offset+5], data[offset+6], data[offset+7],+ ]);+ offset += 8;++ let buy_raw = i64::from_le_bytes([+ data[offset], data[offset+1], data[offset+2], data[offset+3],+ data[offset+4], data[offset+5], data[offset+6], data[offset+7],+ ]) as f64;+ tick.total_buy_qty = buy_raw;+ offset += 8;++ let sell_raw = i64::from_le_bytes([+ data[offset], data[offset+1], data[offset+2], data[offset+3],+ data[offset+4], data[offset+5], data[offset+6], data[offset+7],+ ]) as f64;+ tick.total_sell_qty = sell_raw;+ offset += 8;++ // OHLC+ let open_raw = i64::from_le_bytes([+ data[offset], data[offset+1], data[offset+2], data[offset+3],+ data[offset+4], data[offset+5], data[offset+6], data[offset+7],+ ]);+ tick.open = open_raw as f64 / 100.0;+ offset += 8;++ let high_raw = i64::from_le_bytes([+ data[offset], data[offset+1], data[offset+2], data[offset+3],+ data[offset+4], data[offset+5], data[offset+6], data[offset+7],+ ]);+ tick.high = high_raw as f64 / 100.0;+ offset += 8;++ let low_raw = i64::from_le_bytes([+ data[offset], data[offset+1], data[offset+2], data[offset+3],+ data[offset+4], data[offset+5], data[offset+6], data[offset+7],+ ]);+ tick.low = low_raw as f64 / 100.0;+ offset += 8;++ let close_raw = i64::from_le_bytes([+ data[offset], data[offset+1], data[offset+2], data[offset+3],+ data[offset+4], data[offset+5], data[offset+6], data[offset+7],+ ]);+ tick.close = close_raw as f64 / 100.0;+ }++ Some(tick)+ }++ /// Map exchange type to string+ fn exchange_type_to_string(exchange_type: u8) -> &'static str {+ match exchange_type {+ 1 => "NSE",+ 2 => "NFO",+ 3 => "BSE",+ 4 => "BFO",+ 5 => "MCX",+ _ => "UNKNOWN",+ }+ }++ /// Parse symbol format (exchange:token) to exchange type+ fn parse_exchange_type(exchange: &str) -> u8 {+ match exchange.to_uppercase().as_str() {+ "NSE" | "NSE_CM" => NSE_CM,+ "NFO" | "NSE_FO" => NSE_FO,+ "BSE" | "BSE_CM" => BSE_CM,+ "BFO" | "BSE_FO" => BSE_FO,+ "MCX" | "MCX_FO" => MCX_FO,+ _ => NSE_CM,+ }+ }+}++#[async_trait]+impl WebSocketAdapter for AngelOneAdapter {+ async fn connect(&mut self) -> anyhow::Result<()> {+ tracing::info!("Connecting to Angel One WebSocket");++ // Build request with headers+ let uri: Uri = ANGEL_WS_URL.parse()?;+ let request = Request::builder()+ .uri(&uri)+ .header("Host", uri.host().unwrap_or("smartapisocket.angelone.in"))+ .header("Authorization", &self.auth_token)+ .header("x-api-key", &self.api_key)+ .header("x-client-code", &self.client_code)+ .header("x-feed-token", &self.feed_token)+ .header("Connection", "Upgrade")+ .header("Upgrade", "websocket")+ .header("Sec-WebSocket-Version", "13")+ .header("Sec-WebSocket-Key", tokio_tungstenite::tungstenite::handshake::client::generate_key())+ .body(())?;++ let (ws_stream, _) = connect_async_with_config(request, None, false).await?;+ tracing::info!("Connected to Angel One WebSocket");++ *self.ws_stream.write().await = Some(ws_stream);+ *self.is_connected.write().await = true;++ // Start message handler+ let ws_stream = self.ws_stream.clone();+ let is_connected = self.is_connected.clone();++ tokio::spawn(async move {+ loop {+ let mut stream = ws_stream.write().await;+ if let Some(ref mut ws) = *stream {+ match ws.next().await {+ Some(Ok(Message::Binary(data))) => {+ tracing::debug!("Received binary message: {} bytes", data.len());+ }+ Some(Ok(Message::Text(text))) => {+ if text == "pong" {+ tracing::debug!("Received pong");+ } else {+ tracing::debug!("Received text: {}", text);+ }+ }+ Some(Ok(Message::Ping(data))) => {+ if let Err(e) = ws.send(Message::Pong(data)).await {+ tracing::error!("Failed to send pong: {}", e);+ }+ }+ Some(Err(e)) => {+ tracing::error!("WebSocket error: {}", e);+ *is_connected.write().await = false;+ break;+ }+ None => {+ tracing::info!("WebSocket closed");+ *is_connected.write().await = false;+ break;+ }+ _ => {}+ }+ } else {+ break;+ }+ drop(stream);+ tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;+ }+ });++ // Start heartbeat+ let ws_stream_hb = self.ws_stream.clone();+ let is_connected_hb = self.is_connected.clone();+ tokio::spawn(async move {+ loop {+ tokio::time::sleep(tokio::time::Duration::from_secs(HEARTBEAT_INTERVAL)).await;+ if !*is_connected_hb.read().await {+ break;+ }+ if let Some(ref mut ws) = *ws_stream_hb.write().await {+ if let Err(e) = ws.send(Message::Text("ping".to_string())).await {+ tracing::error!("Failed to send heartbeat: {}", e);+ break;+ }+ }+ }+ });++ Ok(())+ }++ async fn disconnect(&mut self) -> anyhow::Result<()> {+ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.close(None).await?;+ }+ *self.ws_stream.write().await = None;+ *self.is_connected.write().await = false;+ tracing::info!("Disconnected from Angel One WebSocket");+ Ok(())+ }++ async fn subscribe(+ &mut self,+ symbol: &str,+ channel: &str,+ params: Option<Value>,+ ) -> anyhow::Result<()> {+ let mode = match channel {+ "depth" => AngelMode::Depth,+ "quote" => AngelMode::Quote,+ "snap" | "snap_quote" => AngelMode::SnapQuote,+ _ => AngelMode::Ltp,+ };++ // Parse symbol format: "NSE:12345" or "NFO:56789"+ let parts: Vec<&str> = symbol.split(':').collect();+ if parts.len() != 2 {+ return Err(anyhow::anyhow!("Invalid symbol format. Expected 'Exchange:Token'"));+ }++ let exchange = parts[0];+ let token = parts[1].to_string();+ let exchange_type = Self::parse_exchange_type(exchange);++ // Store mapping+ self.token_symbol_map.write().await.insert(token.clone(), symbol.to_string());++ let request = SubscriptionRequest {+ correlation_id: uuid::Uuid::new_v4().to_string()[..10].to_string(),+ action: ACTION_SUBSCRIBE,+ params: SubscriptionParams {+ mode: mode.to_code(),+ token_list: vec![TokenListItem {+ exchange_type,+ tokens: vec![token],+ }],+ },+ };++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(serde_json::to_string(&request)?)).await?;+ self.subscriptions.write().await.insert(symbol.to_string(), mode);+ tracing::info!("Subscribed to {} on channel {}", symbol, channel);+ }++ Ok(())+ }++ async fn unsubscribe(&mut self, symbol: &str, channel: &str) -> anyhow::Result<()> {+ let mode = self.subscriptions.read().await.get(symbol).cloned();++ if let Some(m) = mode {+ let parts: Vec<&str> = symbol.split(':').collect();+ if parts.len() != 2 {+ return Err(anyhow::anyhow!("Invalid symbol format"));+ }++ let exchange_type = Self::parse_exchange_type(parts[0]);+ let token = parts[1].to_string();++ let request = SubscriptionRequest {+ correlation_id: uuid::Uuid::new_v4().to_string()[..10].to_string(),+ action: ACTION_UNSUBSCRIBE,+ params: SubscriptionParams {+ mode: m.to_code(),+ token_list: vec![TokenListItem {+ exchange_type,+ tokens: vec![token],+ }],+ },+ };++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(serde_json::to_string(&request)?)).await?;+ self.subscriptions.write().await.remove(symbol);+ tracing::info!("Unsubscribed from {}", symbol);+ }+ }++ Ok(())+ }++ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {+ self.message_callback = Some(callback);+ }++ fn provider_name(&self) -> &str {+ "angelone"+ }++ fn is_connected(&self) -> bool {+ self.is_connected.try_read().map(|g| *g).unwrap_or(false)+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/dhan.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/dhan.rsnew file mode 100644index 000000000..02a4a0acf--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/dhan.rs@@ -0,0 +1,549 @@+// Dhan WebSocket Adapter (Binary Protocol)+//+// Dhan uses binary-encoded market data over WebSocket:+// - 5-level depth: wss://api-feed.dhan.co+// - 20-level depth: wss://depth-api-feed.dhan.co/twentydepth+// - Authentication via URL parameters (token, clientId)+// - Binary packet format with struct-based parsing++use super::WebSocketAdapter;+use crate::websocket::types::{+ MarketMessage, TickerData, OrderBookData, OrderBookLevel, ProviderConfig,+};+use async_trait::async_trait;+use futures_util::{SinkExt, StreamExt};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::collections::HashMap;+use std::sync::Arc;+use tokio::net::TcpStream;+use tokio::sync::RwLock;+use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream};++// ============================================================================+// DHAN CONFIGURATION+// ============================================================================++const DHAN_WS_URL_5DEPTH: &str = "wss://api-feed.dhan.co";+const DHAN_WS_URL_20DEPTH: &str = "wss://depth-api-feed.dhan.co/twentydepth";++// Feed response codes+const FEED_TICKER: u8 = 2;+const FEED_QUOTE: u8 = 4;+const FEED_OI: u8 = 5;+const FEED_PREV_CLOSE: u8 = 6;+const FEED_FULL: u8 = 8;+const FEED_DEPTH_20_BID: u8 = 41;+const FEED_DEPTH_20_ASK: u8 = 51;+const FEED_DISCONNECT: u8 = 50;++// Request codes+const REQUEST_SUBSCRIBE_TICKER: u8 = 15;+const REQUEST_SUBSCRIBE_QUOTE: u8 = 17;+const REQUEST_SUBSCRIBE_FULL: u8 = 21;+const REQUEST_SUBSCRIBE_20_DEPTH: u8 = 23;+const REQUEST_DISCONNECT: u8 = 12;++// ============================================================================+// DHAN STRUCTURES+// ============================================================================++#[derive(Debug, Clone, PartialEq)]+pub enum DhanMode {+ Ticker,+ Quote,+ Full,+ Depth20,+}++impl DhanMode {+ fn request_code(&self) -> u8 {+ match self {+ DhanMode::Ticker => REQUEST_SUBSCRIBE_TICKER,+ DhanMode::Quote => REQUEST_SUBSCRIBE_QUOTE,+ DhanMode::Full => REQUEST_SUBSCRIBE_FULL,+ DhanMode::Depth20 => REQUEST_SUBSCRIBE_20_DEPTH,+ }+ }+}++#[derive(Debug, Serialize)]+struct SubscriptionMessage {+ #[serde(rename = "RequestCode")]+ request_code: u8,+ #[serde(rename = "InstrumentCount")]+ instrument_count: usize,+ #[serde(rename = "InstrumentList")]+ instrument_list: Vec<DhanInstrument>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DhanInstrument {+ #[serde(rename = "ExchangeSegment")]+ pub exchange_segment: String,+ #[serde(rename = "SecurityId")]+ pub security_id: String,+}++#[derive(Debug, Clone)]+pub struct DhanTick {+ pub exchange_segment: u8,+ pub security_id: u32,+ pub ltp: f32,+ pub ltq: u16,+ pub ltt: u32,+ pub atp: f32,+ pub volume: u32,+ pub total_sell_qty: u32,+ pub total_buy_qty: u32,+ pub open: f32,+ pub close: f32,+ pub high: f32,+ pub low: f32,+ pub oi: u32,+ pub depth: Option<DhanDepth>,+}++#[derive(Debug, Clone)]+pub struct DhanDepth {+ pub buy: Vec<DhanDepthLevel>,+ pub sell: Vec<DhanDepthLevel>,+}++#[derive(Debug, Clone)]+pub struct DhanDepthLevel {+ pub price: f32,+ pub quantity: u32,+ pub orders: u16,+}++// ============================================================================+// DHAN ADAPTER+// ============================================================================++pub struct DhanAdapter {+ config: ProviderConfig,+ client_id: String,+ access_token: String,+ is_20_depth: bool,+ ws_stream: Arc<RwLock<Option<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,+ message_callback: Option<Box<dyn Fn(MarketMessage) + Send + Sync>>,+ subscriptions: Arc<RwLock<HashMap<String, DhanMode>>>,+ is_connected: Arc<RwLock<bool>>,+ security_symbol_map: Arc<RwLock<HashMap<u32, String>>>,+}++impl DhanAdapter {+ pub fn new(config: ProviderConfig) -> Self {+ let client_id = config.client_id.clone().unwrap_or_default();+ let access_token = config.api_key.clone().unwrap_or_default();+ let is_20_depth = config.extra.as_ref()+ .and_then(|e| e.get("is_20_depth"))+ .and_then(|v| v.as_bool())+ .unwrap_or(false);++ Self {+ config,+ client_id,+ access_token,+ is_20_depth,+ ws_stream: Arc::new(RwLock::new(None)),+ message_callback: None,+ subscriptions: Arc::new(RwLock::new(HashMap::new())),+ is_connected: Arc::new(RwLock::new(false)),+ security_symbol_map: Arc::new(RwLock::new(HashMap::new())),+ }+ }++ /// Build WebSocket URL with authentication+ fn build_ws_url(&self) -> String {+ let base_url = if self.is_20_depth {+ DHAN_WS_URL_20DEPTH+ } else {+ DHAN_WS_URL_5DEPTH+ };++ if self.is_20_depth {+ format!(+ "{}?token={}&clientId={}&authType=2",+ base_url, self.access_token, self.client_id+ )+ } else {+ format!(+ "{}?version=2&token={}&clientId={}&authType=2",+ base_url, self.access_token, self.client_id+ )+ }+ }++ /// Parse binary message header+ fn parse_header(&self, data: &[u8]) -> Option<(u8, u16, u8, u32)> {+ if data.len() < 8 {+ return None;+ }++ let feed_response_code = data[0];+ let message_length = u16::from_le_bytes([data[1], data[2]]);+ let exchange_segment = data[3];+ let security_id = u32::from_le_bytes([data[4], data[5], data[6], data[7]]);++ Some((feed_response_code, message_length, exchange_segment, security_id))+ }++ /// Parse ticker packet (LTP and LTT)+ fn parse_ticker(&self, payload: &[u8], exchange_segment: u8, security_id: u32) -> Option<DhanTick> {+ if payload.len() < 8 {+ return None;+ }++ let ltp = f32::from_le_bytes([payload[0], payload[1], payload[2], payload[3]]);+ let ltt = u32::from_le_bytes([payload[4], payload[5], payload[6], payload[7]]);++ Some(DhanTick {+ exchange_segment,+ security_id,+ ltp,+ ltq: 0,+ ltt,+ atp: 0.0,+ volume: 0,+ total_sell_qty: 0,+ total_buy_qty: 0,+ open: 0.0,+ close: 0.0,+ high: 0.0,+ low: 0.0,+ oi: 0,+ depth: None,+ })+ }++ /// Parse quote packet+ fn parse_quote(&self, payload: &[u8], exchange_segment: u8, security_id: u32) -> Option<DhanTick> {+ if payload.len() < 42 {+ return None;+ }++ Some(DhanTick {+ exchange_segment,+ security_id,+ ltp: f32::from_le_bytes([payload[0], payload[1], payload[2], payload[3]]),+ ltq: u16::from_le_bytes([payload[4], payload[5]]),+ ltt: u32::from_le_bytes([payload[6], payload[7], payload[8], payload[9]]),+ atp: f32::from_le_bytes([payload[10], payload[11], payload[12], payload[13]]),+ volume: u32::from_le_bytes([payload[14], payload[15], payload[16], payload[17]]),+ total_sell_qty: u32::from_le_bytes([payload[18], payload[19], payload[20], payload[21]]),+ total_buy_qty: u32::from_le_bytes([payload[22], payload[23], payload[24], payload[25]]),+ open: f32::from_le_bytes([payload[26], payload[27], payload[28], payload[29]]),+ close: f32::from_le_bytes([payload[30], payload[31], payload[32], payload[33]]),+ high: f32::from_le_bytes([payload[34], payload[35], payload[36], payload[37]]),+ low: f32::from_le_bytes([payload[38], payload[39], payload[40], payload[41]]),+ oi: 0,+ depth: None,+ })+ }++ /// Parse full packet with 5-level depth+ fn parse_full(&self, payload: &[u8], exchange_segment: u8, security_id: u32) -> Option<DhanTick> {+ if payload.len() < 154 {+ tracing::warn!("Full packet payload too short: {} bytes", payload.len());+ return None;+ }++ let mut tick = DhanTick {+ exchange_segment,+ security_id,+ ltp: f32::from_le_bytes([payload[0], payload[1], payload[2], payload[3]]),+ ltq: u16::from_le_bytes([payload[4], payload[5]]),+ ltt: u32::from_le_bytes([payload[6], payload[7], payload[8], payload[9]]),+ atp: f32::from_le_bytes([payload[10], payload[11], payload[12], payload[13]]),+ volume: u32::from_le_bytes([payload[14], payload[15], payload[16], payload[17]]),+ total_sell_qty: u32::from_le_bytes([payload[18], payload[19], payload[20], payload[21]]),+ total_buy_qty: u32::from_le_bytes([payload[22], payload[23], payload[24], payload[25]]),+ oi: u32::from_le_bytes([payload[26], payload[27], payload[28], payload[29]]),+ open: f32::from_le_bytes([payload[38], payload[39], payload[40], payload[41]]),+ close: f32::from_le_bytes([payload[42], payload[43], payload[44], payload[45]]),+ high: f32::from_le_bytes([payload[46], payload[47], payload[48], payload[49]]),+ low: f32::from_le_bytes([payload[50], payload[51], payload[52], payload[53]]),+ depth: None,+ };++ // Parse 5-level depth starting at offset 54+ let mut buy_levels = Vec::new();+ let mut sell_levels = Vec::new();++ for i in 0..5 {+ let offset = 54 + (i * 20);+ if offset + 20 > payload.len() {+ break;+ }++ let bid_qty = u32::from_le_bytes([+ payload[offset], payload[offset + 1], payload[offset + 2], payload[offset + 3]+ ]);+ let ask_qty = u32::from_le_bytes([+ payload[offset + 4], payload[offset + 5], payload[offset + 6], payload[offset + 7]+ ]);+ let bid_orders = u16::from_le_bytes([payload[offset + 8], payload[offset + 9]]);+ let ask_orders = u16::from_le_bytes([payload[offset + 10], payload[offset + 11]]);+ let bid_price = f32::from_le_bytes([+ payload[offset + 12], payload[offset + 13], payload[offset + 14], payload[offset + 15]+ ]);+ let ask_price = f32::from_le_bytes([+ payload[offset + 16], payload[offset + 17], payload[offset + 18], payload[offset + 19]+ ]);++ buy_levels.push(DhanDepthLevel {+ price: bid_price,+ quantity: bid_qty,+ orders: bid_orders,+ });+ sell_levels.push(DhanDepthLevel {+ price: ask_price,+ quantity: ask_qty,+ orders: ask_orders,+ });+ }++ tick.depth = Some(DhanDepth {+ buy: buy_levels,+ sell: sell_levels,+ });++ Some(tick)+ }++ /// Parse binary message+ fn parse_message(&self, data: &[u8]) -> Vec<DhanTick> {+ let mut ticks = Vec::new();+ let mut offset = 0;++ while offset < data.len() {+ if offset + 8 > data.len() {+ break;+ }++ let feed_response_code = data[offset];+ let message_length = u16::from_le_bytes([data[offset + 1], data[offset + 2]]) as usize;+ let exchange_segment = data[offset + 3];+ let security_id = u32::from_le_bytes([+ data[offset + 4], data[offset + 5], data[offset + 6], data[offset + 7]+ ]);++ let payload_start = offset + 8;+ let payload_end = offset + message_length;++ if payload_end > data.len() {+ tracing::warn!("Incomplete message received");+ break;+ }++ let payload = &data[payload_start..payload_end];++ let tick = match feed_response_code {+ FEED_TICKER => self.parse_ticker(payload, exchange_segment, security_id),+ FEED_QUOTE => self.parse_quote(payload, exchange_segment, security_id),+ FEED_FULL => self.parse_full(payload, exchange_segment, security_id),+ FEED_DISCONNECT => {+ if payload.len() >= 2 {+ let disconnect_code = u16::from_le_bytes([payload[0], payload[1]]);+ tracing::warn!("Received disconnect packet with code: {}", disconnect_code);+ }+ None+ }+ _ => {+ tracing::debug!("Unknown feed response code: {}", feed_response_code);+ None+ }+ };++ if let Some(t) = tick {+ ticks.push(t);+ }++ offset = payload_end;+ }++ ticks+ }++ /// Convert tick to MarketMessage+ fn tick_to_message(&self, tick: DhanTick) -> MarketMessage {+ let symbol = self.security_symbol_map+ .try_read()+ .ok()+ .and_then(|map| map.get(&tick.security_id).cloned())+ .unwrap_or_else(|| format!("{}:{}", tick.exchange_segment, tick.security_id));++ if let Some(depth) = tick.depth {+ MarketMessage::OrderBook(OrderBookData {+ provider: "dhan".to_string(),+ symbol,+ bids: depth.buy.iter().map(|l| OrderBookLevel {+ price: l.price as f64,+ quantity: l.quantity as f64,+ count: Some(l.orders as u32),+ }).collect(),+ asks: depth.sell.iter().map(|l| OrderBookLevel {+ price: l.price as f64,+ quantity: l.quantity as f64,+ count: Some(l.orders as u32),+ }).collect(),+ timestamp: tick.ltt as u64,+ is_snapshot: true,+ })+ } else {+ MarketMessage::Ticker(TickerData {+ provider: "dhan".to_string(),+ symbol,+ price: tick.ltp as f64,+ bid: None,+ ask: None,+ bid_size: None,+ ask_size: None,+ volume: Some(tick.volume as f64),+ high: Some(tick.high as f64),+ low: Some(tick.low as f64),+ open: Some(tick.open as f64),+ close: Some(tick.close as f64),+ change: None,+ change_percent: None,+ timestamp: tick.ltt as u64,+ })+ }+ }+}++#[async_trait]+impl WebSocketAdapter for DhanAdapter {+ async fn connect(&mut self) -> anyhow::Result<()> {+ let ws_url = self.build_ws_url();+ tracing::info!("Connecting to Dhan WebSocket ({})", if self.is_20_depth { "20-depth" } else { "5-depth" });++ let (ws_stream, _) = connect_async(&ws_url).await?;+ tracing::info!("Connected to Dhan WebSocket");++ *self.ws_stream.write().await = Some(ws_stream);+ *self.is_connected.write().await = true;++ // Start message handler+ let ws_stream = self.ws_stream.clone();+ let is_connected = self.is_connected.clone();+ let security_symbol_map = self.security_symbol_map.clone();++ tokio::spawn(async move {+ loop {+ let mut stream = ws_stream.write().await;+ if let Some(ref mut ws) = *stream {+ match ws.next().await {+ Some(Ok(Message::Binary(data))) => {+ tracing::debug!("Received binary message: {} bytes", data.len());+ // Parse and emit via callback+ }+ Some(Ok(Message::Ping(data))) => {+ if let Err(e) = ws.send(Message::Pong(data)).await {+ tracing::error!("Failed to send pong: {}", e);+ }+ }+ Some(Err(e)) => {+ tracing::error!("WebSocket error: {}", e);+ *is_connected.write().await = false;+ break;+ }+ None => {+ tracing::info!("WebSocket closed");+ *is_connected.write().await = false;+ break;+ }+ _ => {}+ }+ } else {+ break;+ }+ drop(stream);+ tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;+ }+ });++ Ok(())+ }++ async fn disconnect(&mut self) -> anyhow::Result<()> {+ // Send disconnect message+ let disconnect_msg = serde_json::json!({+ "RequestCode": REQUEST_DISCONNECT+ });++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ let _ = ws.send(Message::Text(disconnect_msg.to_string())).await;+ ws.close(None).await?;+ }++ *self.ws_stream.write().await = None;+ *self.is_connected.write().await = false;+ tracing::info!("Disconnected from Dhan WebSocket");+ Ok(())+ }++ async fn subscribe(+ &mut self,+ symbol: &str,+ channel: &str,+ params: Option<Value>,+ ) -> anyhow::Result<()> {+ let mode = match channel {+ "full" | "depth" => DhanMode::Full,+ "quote" => DhanMode::Quote,+ "20depth" => DhanMode::Depth20,+ _ => DhanMode::Ticker,+ };++ // Parse symbol: format is "ExchangeSegment:SecurityId" (e.g., "NSE_EQ:1594")+ let parts: Vec<&str> = symbol.split(':').collect();+ if parts.len() != 2 {+ return Err(anyhow::anyhow!("Invalid symbol format. Expected 'ExchangeSegment:SecurityId'"));+ }++ let instrument = DhanInstrument {+ exchange_segment: parts[0].to_string(),+ security_id: parts[1].to_string(),+ };++ // Store symbol mapping+ if let Ok(security_id) = parts[1].parse::<u32>() {+ self.security_symbol_map.write().await.insert(security_id, symbol.to_string());+ }++ let message = SubscriptionMessage {+ request_code: mode.request_code(),+ instrument_count: 1,+ instrument_list: vec![instrument],+ };++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(serde_json::to_string(&message)?)).await?;+ self.subscriptions.write().await.insert(symbol.to_string(), mode);+ tracing::info!("Subscribed to {} on channel {}", symbol, channel);+ }++ Ok(())+ }++ async fn unsubscribe(&mut self, symbol: &str, _channel: &str) -> anyhow::Result<()> {+ self.subscriptions.write().await.remove(symbol);+ tracing::info!("Unsubscribed from {}", symbol);+ Ok(())+ }++ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {+ self.message_callback = Some(callback);+ }++ fn provider_name(&self) -> &str {+ "dhan"+ }++ fn is_connected(&self) -> bool {+ self.is_connected.try_read().map(|g| *g).unwrap_or(false)+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fivepaisa.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fivepaisa.rsnew file mode 100644index 000000000..95ebdbf2c--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fivepaisa.rs@@ -0,0 +1,312 @@+// 5Paisa WebSocket Adapter+//+// 5Paisa uses WebSocket for real-time market data:+// - WebSocket URL: wss://openfeed.5paisa.com/Feeds/api/chat+// - Authentication via JWT token+// - JSON-based subscription protocol++use super::WebSocketAdapter;+use crate::websocket::types::*;+use async_trait::async_trait;+use futures_util::{SinkExt, StreamExt};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::collections::HashMap;+use std::sync::Arc;+use tokio::net::TcpStream;+use tokio::sync::RwLock;+use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream};++// ============================================================================+// 5PAISA CONFIGURATION+// ============================================================================++const FIVEPAISA_WS_URL: &str = "wss://openfeed.5paisa.com/Feeds/api/chat";++// Subscription methods+const METHOD_MARKET_FEED: i32 = 1;+const METHOD_MARKET_DEPTH: i32 = 2;+const METHOD_INDEX_FEED: i32 = 3;+const METHOD_OPEN_INTEREST: i32 = 4;++// ============================================================================+// 5PAISA STRUCTURES+// ============================================================================++#[derive(Debug, Clone, PartialEq)]+pub enum FivePaisaMode {+ MarketFeed,+ MarketDepth,+ IndexFeed,+ OpenInterest,+}++impl FivePaisaMode {+ fn method_code(&self) -> i32 {+ match self {+ FivePaisaMode::MarketFeed => METHOD_MARKET_FEED,+ FivePaisaMode::MarketDepth => METHOD_MARKET_DEPTH,+ FivePaisaMode::IndexFeed => METHOD_INDEX_FEED,+ FivePaisaMode::OpenInterest => METHOD_OPEN_INTEREST,+ }+ }+}++#[derive(Debug, Serialize)]+struct SubscribeRequest {+ #[serde(rename = "Method")]+ method: String,+ #[serde(rename = "Operation")]+ operation: String,+ #[serde(rename = "ClientCode")]+ client_code: String,+ #[serde(rename = "MarketFeedData")]+ market_feed_data: Vec<FivePaisaScrip>,+}++#[derive(Debug, Serialize, Clone)]+struct FivePaisaScrip {+ #[serde(rename = "Exch")]+ exch: String,+ #[serde(rename = "ExchType")]+ exch_type: String,+ #[serde(rename = "ScripCode")]+ scrip_code: i32,+}++#[derive(Debug, Deserialize)]+struct TickResponse {+ #[serde(rename = "Token")]+ token: Option<i32>,+ #[serde(rename = "Exch")]+ exch: Option<String>,+ #[serde(rename = "ExchType")]+ exch_type: Option<String>,+ #[serde(rename = "LastRate")]+ last_rate: Option<f64>,+ #[serde(rename = "TotalQty")]+ total_qty: Option<i64>,+ #[serde(rename = "High")]+ high: Option<f64>,+ #[serde(rename = "Low")]+ low: Option<f64>,+ #[serde(rename = "Open")]+ open: Option<f64>,+ #[serde(rename = "PClose")]+ prev_close: Option<f64>,+ #[serde(rename = "ChgPcnt")]+ change_percent: Option<f64>,+}++#[derive(Debug, Clone)]+pub struct FivePaisaTick {+ pub token: i32,+ pub exchange: String,+ pub exchange_type: String,+ pub ltp: f64,+ pub volume: i64,+ pub high: f64,+ pub low: f64,+ pub open: f64,+ pub prev_close: f64,+ pub change_percent: f64,+}++// ============================================================================+// 5PAISA ADAPTER+// ============================================================================++pub struct FivePaisaAdapter {+ config: ProviderConfig,+ client_code: String,+ jwt_token: String,+ ws_stream: Arc<RwLock<Option<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,+ message_callback: Option<Box<dyn Fn(MarketMessage) + Send + Sync>>,+ subscriptions: Arc<RwLock<HashMap<String, FivePaisaMode>>>,+ is_connected: Arc<RwLock<bool>>,+}++impl FivePaisaAdapter {+ pub fn new(config: ProviderConfig) -> Self {+ let client_code = config.client_id.clone().unwrap_or_default();+ let jwt_token = config.api_key.clone().unwrap_or_default();++ Self {+ config,+ client_code,+ jwt_token,+ ws_stream: Arc::new(RwLock::new(None)),+ message_callback: None,+ subscriptions: Arc::new(RwLock::new(HashMap::new())),+ is_connected: Arc::new(RwLock::new(false)),+ }+ }++ fn build_ws_url(&self) -> String {+ format!("{}?Value={}", FIVEPAISA_WS_URL, self.jwt_token)+ }++ fn parse_tick(&self, data: &str) -> Option<FivePaisaTick> {+ let tick: TickResponse = serde_json::from_str(data).ok()?;++ Some(FivePaisaTick {+ token: tick.token.unwrap_or(0),+ exchange: tick.exch.unwrap_or_default(),+ exchange_type: tick.exch_type.unwrap_or_default(),+ ltp: tick.last_rate.unwrap_or(0.0),+ volume: tick.total_qty.unwrap_or(0),+ high: tick.high.unwrap_or(0.0),+ low: tick.low.unwrap_or(0.0),+ open: tick.open.unwrap_or(0.0),+ prev_close: tick.prev_close.unwrap_or(0.0),+ change_percent: tick.change_percent.unwrap_or(0.0),+ })+ }+}++#[async_trait]+impl WebSocketAdapter for FivePaisaAdapter {+ async fn connect(&mut self) -> anyhow::Result<()> {+ let ws_url = self.build_ws_url();+ tracing::info!("Connecting to 5Paisa WebSocket");++ let (ws_stream, _) = connect_async(&ws_url).await?;+ tracing::info!("Connected to 5Paisa WebSocket");++ *self.ws_stream.write().await = Some(ws_stream);+ *self.is_connected.write().await = true;++ let ws_stream = self.ws_stream.clone();+ let is_connected = self.is_connected.clone();++ tokio::spawn(async move {+ loop {+ let mut stream = ws_stream.write().await;+ if let Some(ref mut ws) = *stream {+ match ws.next().await {+ Some(Ok(Message::Text(text))) => {+ tracing::debug!("Received: {}", text);+ }+ Some(Ok(Message::Ping(data))) => {+ let _ = ws.send(Message::Pong(data)).await;+ }+ Some(Err(e)) => {+ tracing::error!("WebSocket error: {}", e);+ *is_connected.write().await = false;+ break;+ }+ None => {+ *is_connected.write().await = false;+ break;+ }+ _ => {}+ }+ } else {+ break;+ }+ drop(stream);+ tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;+ }+ });++ Ok(())+ }++ async fn disconnect(&mut self) -> anyhow::Result<()> {+ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.close(None).await?;+ }+ *self.ws_stream.write().await = None;+ *self.is_connected.write().await = false;+ tracing::info!("Disconnected from 5Paisa WebSocket");+ Ok(())+ }++ async fn subscribe(+ &mut self,+ symbol: &str,+ channel: &str,+ _params: Option<Value>,+ ) -> anyhow::Result<()> {+ let mode = match channel {+ "depth" => FivePaisaMode::MarketDepth,+ "index" => FivePaisaMode::IndexFeed,+ "oi" => FivePaisaMode::OpenInterest,+ _ => FivePaisaMode::MarketFeed,+ };++ // Parse symbol: "N:C:12345" (Exchange:ExchType:ScripCode)+ let parts: Vec<&str> = symbol.split(':').collect();+ if parts.len() != 3 {+ return Err(anyhow::anyhow!("Invalid symbol format. Expected 'Exch:ExchType:ScripCode'"));+ }++ let scrip = FivePaisaScrip {+ exch: parts[0].to_string(),+ exch_type: parts[1].to_string(),+ scrip_code: parts[2].parse().map_err(|_| anyhow::anyhow!("Invalid scrip code"))?,+ };++ let method_name = match mode {+ FivePaisaMode::MarketFeed => "MarketFeedV3",+ FivePaisaMode::MarketDepth => "MarketDepthService",+ FivePaisaMode::IndexFeed => "IndexDetailV2",+ FivePaisaMode::OpenInterest => "OpenInterestFeed",+ };++ let subscribe_req = SubscribeRequest {+ method: method_name.to_string(),+ operation: "Subscribe".to_string(),+ client_code: self.client_code.clone(),+ market_feed_data: vec![scrip],+ };++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(serde_json::to_string(&subscribe_req)?)).await?;+ self.subscriptions.write().await.insert(symbol.to_string(), mode);+ tracing::info!("Subscribed to {}", symbol);+ }++ Ok(())+ }++ async fn unsubscribe(&mut self, symbol: &str, _channel: &str) -> anyhow::Result<()> {+ let parts: Vec<&str> = symbol.split(':').collect();+ if parts.len() != 3 {+ return Err(anyhow::anyhow!("Invalid symbol format"));+ }++ let scrip = FivePaisaScrip {+ exch: parts[0].to_string(),+ exch_type: parts[1].to_string(),+ scrip_code: parts[2].parse().map_err(|_| anyhow::anyhow!("Invalid scrip code"))?,+ };++ let unsubscribe_req = SubscribeRequest {+ method: "MarketFeedV3".to_string(),+ operation: "Unsubscribe".to_string(),+ client_code: self.client_code.clone(),+ market_feed_data: vec![scrip],+ };++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(serde_json::to_string(&unsubscribe_req)?)).await?;+ self.subscriptions.write().await.remove(symbol);+ tracing::info!("Unsubscribed from {}", symbol);+ }++ Ok(())+ }++ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {+ self.message_callback = Some(callback);+ }++ fn provider_name(&self) -> &str {+ "fivepaisa"+ }++ fn is_connected(&self) -> bool {+ self.is_connected.try_read().map(|g| *g).unwrap_or(false)+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fyers.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fyers.rsindex 93b2ad82d..8344b8d2d 100644--- a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fyers.rs+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/fyers.rs@@ -1,14 +1,16 @@-// Fyers WebSocket Adapter with Binary Protocol (HSM v1.5)+// Fyers WebSocket Adapter//-// Fyers uses a proprietary binary protocol over WebSocket for real-time data:-// - Connection: wss://socket.fyers.in/hsm/v1-5/prod-// - Authentication: Requires access token in connection URL-// - Protocol: Binary messages with specific packet structures-// - Subscription: Symbol tokens from master contract (e.g., NSE:RELIANCE-EQ)+// Implements Fyers HSM (High-Speed Market) binary protocol for real-time market data+// Based on official Fyers library analysis and OpenAlgo implementation+//+// Connection URL: wss://socket.fyers.in/hsm/v1-5/prod+// Access token format: "appid:accesstoken"+// Protocol: Binary (not JSON!)use super::WebSocketAdapter;use crate::websocket::types::*;use async_trait::async_trait;+use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};use futures_util::{SinkExt, StreamExt};use serde_json::Value;use std::collections::HashMap;@@ -17,48 +19,101 @@ use tokio::net::TcpStream;use tokio::sync::RwLock;use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream};-// Subscription mode for internal tracking-#[derive(Debug, Clone, PartialEq)]-enum SubscriptionMode {- Ltp,- Quote,- Full,-}+// Fyers symbol-token API endpoint+const FYERS_SYMBOL_TOKEN_API: &str = "https://api-t1.fyers.in/data/symbol-token";// ============================================================================// FYERS WEBSOCKET CONFIGURATION// ============================================================================-const FYERS_WS_URL: &str = "wss://socket.fyers.in/hsm/v1-5/prod";+const FYERS_HSM_WS_URL: &str = "wss://socket.fyers.in/hsm/v1-5/prod";+const SOURCE_IDENTIFIER: &str = "FinceptTerminal-HSM";+const MODE_PRODUCTION: &str = "P";++// ============================================================================+// FYERS HSM DATA FIELD MAPPINGS (from official library)+// ============================================================================-// Fyers data packet structure constants-const PACKET_TYPE_TICK: u8 = 31;-const PACKET_TYPE_DEPTH: u8 = 41;-const PACKET_TYPE_FULL_DEPTH: u8 = 43;-const PACKET_TYPE_CONFIRMATION: u8 = 8;+/// Data fields for scrip/equity/options (sf| prefix)+const DATA_FIELDS: &[&str] = &[+ "ltp", "vol_traded_today", "last_traded_time", "exch_feed_time",+ "bid_size", "ask_size", "bid_price", "ask_price", "last_traded_qty",+ "tot_buy_qty", "tot_sell_qty", "avg_trade_price", "oi", "low_price",+ "high_price", "yhigh", "ylow", "lower_ckt", "upper_ckt", "open_price",+ "prev_close_price", "type", "symbol"+];++/// Data fields for index (if| prefix)+const INDEX_FIELDS: &[&str] = &[+ "ltp", "prev_close_price", "exch_feed_time", "high_price", "low_price",+ "open_price", "type", "symbol"+];++/// Data fields for depth (dp| prefix)+const DEPTH_FIELDS: &[&str] = &[+ "bid_price1", "bid_price2", "bid_price3", "bid_price4", "bid_price5",+ "ask_price1", "ask_price2", "ask_price3", "ask_price4", "ask_price5",+ "bid_size1", "bid_size2", "bid_size3", "bid_size4", "bid_size5",+ "ask_size1", "ask_size2", "ask_size3", "ask_size4", "ask_size5",+ "bid_order1", "bid_order2", "bid_order3", "bid_order4", "bid_order5",+ "ask_order1", "ask_order2", "ask_order3", "ask_order4", "ask_order5",+ "type", "symbol"+];++/// Exchange segment mapping (fytoken prefix -> segment name)+#[allow(dead_code)]+fn get_exchange_segment(segment_code: &str) -> &'static str {+ match segment_code {+ "1010" => "nse_cm", // NSE Cash+ "1011" => "nse_fo", // NSE F&O+ "1120" => "mcx_fo", // MCX F&O+ "1210" => "bse_cm", // BSE Cash+ "1211" => "bse_fo", // BSE F&O+ "1212" => "bcs_fo", // BSE Currency+ "1012" => "cde_fo", // CDE F&O+ "1020" => "nse_com", // NSE Commodity+ _ => "unknown",+ }+}// ============================================================================-// BINARY PROTOCOL STRUCTURES+// FYERS DATA TYPES// ============================================================================-/// Fyers tick data packet (minimal binary structure)-#[derive(Debug, Clone)]-struct FyersTickPacket {- packet_type: u8,- token: i32,- ltp: f64,- volume: i64,- change_percent: f64,- timestamp: u64,+/// Subscription mode+#[derive(Debug, Clone, PartialEq)]+pub enum FyersDataType {+ SymbolUpdate, // sf| - scrip/equity data+ DepthUpdate, // dp| - market depth+ IndexUpdate, // if| - index data}-/// Fyers market depth packet-#[derive(Debug, Clone)]-struct FyersDepthPacket {- packet_type: u8,- token: i32,- bids: Vec<(f64, i32)>, // (price, quantity)- asks: Vec<(f64, i32)>,+/// Parsed scrip data+#[derive(Debug, Clone, Default)]+pub struct FyersScripData {+ pub symbol: String,+ pub exchange: String,+ pub exchange_token: String,+ pub ltp: i32,+ pub volume: i32,+ pub last_traded_time: i32,+ pub exch_feed_time: i32,+ pub bid_size: i32,+ pub ask_size: i32,+ pub bid_price: i32,+ pub ask_price: i32,+ pub last_traded_qty: i32,+ pub tot_buy_qty: i32,+ pub tot_sell_qty: i32,+ pub avg_trade_price: i32,+ pub oi: i32,+ pub low_price: i32,+ pub high_price: i32,+ pub open_price: i32,+ pub prev_close_price: i32,+ pub multiplier: u16,+ pub precision: u8,+ pub hsm_token: String,}// ============================================================================@@ -68,11 +123,20 @@ struct FyersDepthPacket {pub struct FyersAdapter {config: ProviderConfig,access_token: String,+ hsm_key: Option<String>,ws_stream: Arc<RwLock<Option<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,- message_callback: Option<Box<dyn Fn(MarketMessage) + Send + Sync>>,- subscriptions: Arc<RwLock<HashMap<String, SubscriptionMode>>>,+ message_callback: Arc<std::sync::RwLock<Option<Box<dyn Fn(MarketMessage) + Send + Sync>>>>,+ subscriptions: Arc<RwLock<HashMap<String, FyersDataType>>>,is_connected: Arc<RwLock<bool>>,- token_symbol_map: Arc<RwLock<HashMap<i32, String>>>, // Token -> Symbol mapping+ is_authenticated: Arc<RwLock<bool>>,+ // Topic ID -> Topic Name mapping (for update messages)+ topic_mappings: Arc<RwLock<HashMap<u16, String>>>,+ // Topic ID -> Scrip data cache (for incremental updates)+ scrips_cache: Arc<RwLock<HashMap<u16, HashMap<String, i32>>>>,+ // HSM token -> Original symbol mapping+ symbol_mappings: Arc<RwLock<HashMap<String, String>>>,+ // Symbol -> Fytoken mapping (from API)+ fytoken_cache: Arc<RwLock<HashMap<String, String>>>,}impl FyersAdapter {@@ -81,390 +145,1133 @@ impl FyersAdapter {Self {config,access_token,+ hsm_key: None,ws_stream: Arc::new(RwLock::new(None)),- message_callback: None,+ message_callback: Arc::new(std::sync::RwLock::new(None)),subscriptions: Arc::new(RwLock::new(HashMap::new())),is_connected: Arc::new(RwLock::new(false)),- token_symbol_map: Arc::new(RwLock::new(HashMap::new())),+ is_authenticated: Arc::new(RwLock::new(false)),+ topic_mappings: Arc::new(RwLock::new(HashMap::new())),+ scrips_cache: Arc::new(RwLock::new(HashMap::new())),+ symbol_mappings: Arc::new(RwLock::new(HashMap::new())),+ fytoken_cache: Arc::new(RwLock::new(HashMap::new())),}}- /// Parse binary tick data from Fyers HSM protocol- fn parse_tick_data(&self, data: &[u8]) -> Option<FyersTickPacket> {- if data.len() < 32 {- return None;+ /// Fetch fytokens from Fyers API for symbol-to-token conversion+ /// This is critical for proper HSM subscription+ async fn fetch_fytokens(&self, symbols: &[String]) -> HashMap<String, String> {+ let mut result = HashMap::new();++ if symbols.is_empty() {+ return result;}- let packet_type = data[0];- if packet_type != PACKET_TYPE_TICK {- return None;+ eprintln!("[Fyers HSM] Fetching fytokens for {} symbols: {:?}", symbols.len(), symbols);++ let client = reqwest::Client::new();+ let body = serde_json::json!({+ "symbols": symbols+ });++ match client+ .post(FYERS_SYMBOL_TOKEN_API)+ .header("Authorization", &self.access_token)+ .header("Content-Type", "application/json")+ .json(&body)+ .send()+ .await+ {+ Ok(response) => {+ if let Ok(json) = response.json::<Value>().await {+ eprintln!("[Fyers HSM] Symbol-token API response: {}", json);++ if json.get("s").and_then(|s| s.as_str()) == Some("ok") {+ if let Some(valid_symbols) = json.get("validSymbol").and_then(|v| v.as_object()) {+ for (symbol, fytoken) in valid_symbols {+ if let Some(fytoken_str) = fytoken.as_str() {+ result.insert(symbol.clone(), fytoken_str.to_string());+ eprintln!("[Fyers HSM] ✓ {} -> {}", symbol, fytoken_str);+ }+ }+ }+ if let Some(invalid) = json.get("invalidSymbol").and_then(|v| v.as_array()) {+ for sym in invalid {+ eprintln!("[Fyers HSM] ✗ Invalid symbol: {:?}", sym);+ }+ }+ } else {+ let msg = json.get("message").and_then(|m| m.as_str()).unwrap_or("Unknown error");+ eprintln!("[Fyers HSM] API error: {}", msg);+ }+ }+ }+ Err(e) => {+ eprintln!("[Fyers HSM] Failed to fetch fytokens: {}", e);+ }}- // Parse binary fields (little-endian)- let token = i32::from_le_bytes([data[1], data[2], data[3], data[4]]);- let ltp = f64::from_le_bytes([- data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12],- ]);- let volume = i64::from_le_bytes([- data[13], data[14], data[15], data[16], data[17], data[18], data[19], data[20],- ]);- let change_percent = f64::from_le_bytes([- data[21], data[22], data[23], data[24], data[25], data[26], data[27], data[28],- ]);- let timestamp = u64::from_le_bytes([- data[29], data[30], data[31], data[32], data[33], data[34], data[35], data[36],- ]);-- Some(FyersTickPacket {- packet_type,- token,- ltp,- volume,- change_percent,- timestamp,- })+ result}- /// Parse binary market depth from Fyers- fn parse_depth_data(&self, data: &[u8]) -> Option<FyersDepthPacket> {- if data.len() < 10 {+ /// Convert fytoken to HSM token format+ /// fytoken format: "10100000002885" (14 digits)+ /// - First 4 digits: exchange segment (1010 = NSE CM)+ /// - Last 10 digits: token suffix for HSM+ fn fytoken_to_hsm_token(fytoken: &str, data_type: &FyersDataType, is_index: bool) -> Option<String> {+ if fytoken.len() < 10 {+ eprintln!("[Fyers HSM] Invalid fytoken length: {} ({})", fytoken.len(), fytoken);return None;}- let packet_type = data[0];- if packet_type != PACKET_TYPE_DEPTH && packet_type != PACKET_TYPE_FULL_DEPTH {+ let ex_sg = &fytoken[..4];+ let segment = match ex_sg {+ "1010" => "nse_cm", // NSE Cash+ "1011" => "nse_fo", // NSE F&O+ "1120" => "mcx_fo", // MCX F&O+ "1210" => "bse_cm", // BSE Cash+ "1211" => "bse_fo", // BSE F&O+ "1212" => "bcs_fo", // BSE Currency+ "1012" => "cde_fo", // CDE F&O+ "1020" => "nse_com", // NSE Commodity+ _ => {+ eprintln!("[Fyers HSM] Unknown exchange segment: {}", ex_sg);+ return None;+ }+ };++ // For indices, always use "if" prefix regardless of data type+ if is_index {+ // For indices, use the full token_suffix from position 10+ let token_suffix = &fytoken[10..];+ return Some(format!("if|{}|{}", segment, token_suffix));+ }++ let prefix = match data_type {+ FyersDataType::SymbolUpdate => "sf",+ FyersDataType::DepthUpdate => "dp",+ FyersDataType::IndexUpdate => "if",+ };++ // Extract token suffix (last part after first 10 chars, or from position 10)+ let token_suffix = &fytoken[10..];++ Some(format!("{}|{}|{}", prefix, segment, token_suffix))+ }++ /// Extract HSM key from JWT access token+ fn extract_hsm_key(access_token: &str) -> Option<String> {+ // Remove app_id prefix if present (format: "appid:token")+ let token = if access_token.contains(':') {+ access_token.split(':').nth(1)?+ } else {+ access_token+ };++ // JWT format: header.payload.signature+ let parts: Vec<&str> = token.split('.').collect();+ if parts.len() != 3 {+ eprintln!("[Fyers HSM] Invalid JWT format: expected 3 parts, got {}", parts.len());return None;}- let token = i32::from_le_bytes([data[1], data[2], data[3], data[4]]);+ // Decode payload (second part)+ let payload_b64 = parts[1];- // Parse 5 levels of bids and asks- let mut bids = Vec::new();- let mut asks = Vec::new();+ // Base64 URL-safe decode+ let decoded = URL_SAFE_NO_PAD.decode(payload_b64).ok()?;+ let payload_str = String::from_utf8(decoded).ok()?;- let mut offset = 5;- for _ in 0..5 {- if offset + 12 <= data.len() {- let price = f64::from_le_bytes([- data[offset],- data[offset + 1],- data[offset + 2],- data[offset + 3],- data[offset + 4],- data[offset + 5],- data[offset + 6],- data[offset + 7],- ]);- let qty = i32::from_le_bytes([- data[offset + 8],- data[offset + 9],- data[offset + 10],- data[offset + 11],- ]);- bids.push((price, qty));- offset += 12;- }- }-- for _ in 0..5 {- if offset + 12 <= data.len() {- let price = f64::from_le_bytes([- data[offset],- data[offset + 1],- data[offset + 2],- data[offset + 3],- data[offset + 4],- data[offset + 5],- data[offset + 6],- data[offset + 7],- ]);- let qty = i32::from_le_bytes([- data[offset + 8],- data[offset + 9],- data[offset + 10],- data[offset + 11],- ]);- asks.push((price, qty));- offset += 12;- }- }-- Some(FyersDepthPacket {- packet_type,- token,- bids,- asks,- })+ // Parse JSON+ let payload: Value = serde_json::from_str(&payload_str).ok()?;++ // Extract HSM key+ let hsm_key = payload.get("hsm_key")?.as_str()?.to_string();++ // Check expiration+ if let Some(exp) = payload.get("exp").and_then(|e| e.as_i64()) {+ let now = chrono::Utc::now().timestamp();+ if exp < now {+ eprintln!("[Fyers HSM] Access token has expired");+ return None;+ }+ }++ eprintln!("[Fyers HSM] HSM key extracted successfully (length: {})", hsm_key.len());+ Some(hsm_key)}- /// Convert Fyers symbol to token (uses master contract database)- async fn symbol_to_token(&self, symbol: &str) -> Option<i32> {- // Parse Fyers symbol format: "EXCHANGE:SYMBOL" (e.g., "NSE:RELIANCE-EQ")- let parts: Vec<&str> = symbol.split(':').collect();+ /// Create binary authentication message+ fn create_auth_message(hsm_key: &str) -> Vec<u8> {+ let source = SOURCE_IDENTIFIER;+ let mode = MODE_PRODUCTION;++ // Calculate buffer size: 18 + hsm_key length + source length+ let buffer_size = 18 + hsm_key.len() + source.len();+ let mut buffer = Vec::with_capacity(buffer_size);++ // Data length (buffer_size - 2) as big-endian u16+ buffer.extend_from_slice(&((buffer_size - 2) as u16).to_be_bytes());++ // Request type = 1 (authentication)+ buffer.push(1);++ // Field count = 4+ buffer.push(4);++ // Field-1: AuthToken (HSM key)+ buffer.push(1); // Field ID+ buffer.extend_from_slice(&(hsm_key.len() as u16).to_be_bytes());+ buffer.extend_from_slice(hsm_key.as_bytes());++ // Field-2: Mode+ buffer.push(2); // Field ID+ buffer.extend_from_slice(&(1u16).to_be_bytes());+ buffer.extend_from_slice(mode.as_bytes());++ // Field-3: Unknown flag (always 1)+ buffer.push(3); // Field ID+ buffer.extend_from_slice(&(1u16).to_be_bytes());+ buffer.push(1);++ // Field-4: Source+ buffer.push(4); // Field ID+ buffer.extend_from_slice(&(source.len() as u16).to_be_bytes());+ buffer.extend_from_slice(source.as_bytes());++ eprintln!("[Fyers HSM] Created auth message: {} bytes", buffer.len());+ buffer+ }++ /// Create binary subscription message+ fn create_subscription_message(hsm_symbols: &[String], channel: u8) -> Vec<u8> {+ // Create scrips data+ let mut scrips_data = Vec::new();++ // Symbol count as big-endian u16+ let count = hsm_symbols.len() as u16;+ scrips_data.push((count >> 8) as u8);+ scrips_data.push((count & 0xFF) as u8);++ // Each symbol: length byte + symbol bytes+ for symbol in hsm_symbols {+ let symbol_bytes = symbol.as_bytes();+ scrips_data.push(symbol_bytes.len() as u8);+ scrips_data.extend_from_slice(symbol_bytes);+ }++ // Build complete message+ let data_len = 6 + scrips_data.len();++ let mut buffer = Vec::with_capacity(data_len + 2);++ // Data length as big-endian u16+ buffer.extend_from_slice(&(data_len as u16).to_be_bytes());++ // Request type = 4 (subscription)+ buffer.push(4);++ // Field count = 2+ buffer.push(2);++ // Field-1: Symbols+ buffer.push(1); // Field ID+ buffer.extend_from_slice(&(scrips_data.len() as u16).to_be_bytes());+ buffer.extend_from_slice(&scrips_data);++ // Field-2: Channel+ buffer.push(2); // Field ID+ buffer.extend_from_slice(&(1u16).to_be_bytes());+ buffer.push(channel);++ eprintln!("[Fyers HSM] Created subscription message for {} symbols: {} bytes", hsm_symbols.len(), buffer.len());+ buffer+ }++ /// Convert Fyers symbol to HSM token format+ /// Input: "NSE:RELIANCE-EQ" or "NSE:NIFTY50-INDEX"+ /// Output: "sf|nse_cm|{token}" or "if|nse_cm|Nifty 50"+ pub fn symbol_to_hsm_token(symbol: &str, data_type: &FyersDataType) -> String {+ let prefix = match data_type {+ FyersDataType::SymbolUpdate => "sf",+ FyersDataType::DepthUpdate => "dp",+ FyersDataType::IndexUpdate => "if",+ };++ // Parse symbol format "EXCHANGE:SYMBOL-TYPE"+ let parts: Vec<&str> = symbol.split(':').collect();if parts.len() != 2 {- eprintln!("Fyers: Invalid symbol format (expected EXCHANGE:SYMBOL): {}", symbol);- return None;+ // Return as-is if already in HSM format+ if symbol.contains('|') {+ return symbol.to_string();+ }+ return format!("{}|nse_cm|{}", prefix, symbol);}- let exchange = parts[0];- let symbol_name = parts[1];+ let exchange = parts[0].to_lowercase();+ let symbol_part = parts[1];- // Look up token in database- match crate::database::fyers_symbols::get_token_by_symbol(symbol_name, exchange) {- Ok(Some(token)) => {- eprintln!("Fyers: Mapped {}:{} -> token {}", exchange, symbol_name, token);- Some(token)+ // Determine segment+ let segment = if symbol_part.ends_with("-INDEX") {+ match exchange.as_str() {+ "nse" => "nse_cm",+ "bse" => "bse_cm",+ _ => "nse_cm",}- Ok(None) => {- eprintln!("Fyers: Symbol not found in database: {}:{}", exchange, symbol_name);- None+ } else if symbol_part.contains("-FUT") || symbol_part.contains("-OPT") {+ match exchange.as_str() {+ "nse" | "nfo" => "nse_fo",+ "bse" | "bfo" => "bse_fo",+ "mcx" => "mcx_fo",+ _ => "nse_fo",}- Err(e) => {- eprintln!("Fyers: Database error during token lookup: {}", e);- None+ } else {+ // Cash market+ match exchange.as_str() {+ "nse" => "nse_cm",+ "bse" => "bse_cm",+ _ => "nse_cm",+ }+ };++ // For indices, use "if" prefix+ let final_prefix = if symbol_part.ends_with("-INDEX") { "if" } else { prefix };++ // Extract token from symbol (remove -EQ, -INDEX suffix)+ let token = symbol_part+ .replace("-EQ", "")+ .replace("-INDEX", "")+ .replace("-FUT", "")+ .replace("-OPT", "");++ format!("{}|{}|{}", final_prefix, segment, token)+ }++ /// Parse binary message from HSM WebSocket+ fn parse_binary_message(+ data: &[u8],+ topic_mappings: &mut HashMap<u16, String>,+ scrips_cache: &mut HashMap<u16, HashMap<String, i32>>,+ symbol_mappings: &HashMap<String, String>,+ callback: &Arc<std::sync::RwLock<Option<Box<dyn Fn(MarketMessage) + Send + Sync>>>>,+ ) {+ if data.len() < 3 {+ return;+ }++ let msg_type = data[2];++ match msg_type {+ 1 => {+ // Authentication response+ eprintln!("[Fyers HSM] Authentication successful");+ }+ 4 => {+ // Subscription acknowledgment+ eprintln!("[Fyers HSM] Subscription acknowledged");+ }+ 6 => {+ // Data feed message+ Self::parse_data_feed(data, topic_mappings, scrips_cache, symbol_mappings, callback);+ }+ 13 => {+ // Master data (usually large message on connect)+ eprintln!("[Fyers HSM] Received master data: {} bytes", data.len());+ }+ _ => {+ eprintln!("[Fyers HSM] Unknown message type: {}, length: {} bytes", msg_type, data.len());}}}- /// Build subscription message for Fyers- fn build_subscription_message(&self, tokens: Vec<i32>, mode: &str) -> Vec<u8> {- // Fyers subscription format (binary):- // [message_type (1 byte)][mode (1 byte)][token_count (2 bytes)][tokens...]- let mut msg = Vec::new();-- // Message type: 1 = Subscribe, 0 = Unsubscribe- msg.push(1);-- // Mode: 1 = LTP, 2 = Quotes, 3 = Full depth- let mode_byte = match mode {- "ltp" => 1,- "quotes" => 2,- "depth" => 3,- _ => 1,+ /// Parse data feed message (message type 6)+ fn parse_data_feed(+ data: &[u8],+ topic_mappings: &mut HashMap<u16, String>,+ scrips_cache: &mut HashMap<u16, HashMap<String, i32>>,+ symbol_mappings: &HashMap<String, String>,+ callback: &Arc<std::sync::RwLock<Option<Box<dyn Fn(MarketMessage) + Send + Sync>>>>,+ ) {+ if data.len() < 9 {+ return;+ }++ // Get scrip count at bytes 7-8+ let scrip_count = u16::from_be_bytes([data[7], data[8]]) as usize;+ let mut offset = 9;++ for _ in 0..scrip_count {+ if offset >= data.len() {+ break;+ }++ // Get data type+ let data_type = data[offset];+ offset += 1;++ match data_type {+ 83 => {+ // Snapshot data (0x53 = 'S')+ offset = Self::parse_snapshot_data(data, offset, topic_mappings, scrips_cache, symbol_mappings, callback);+ }+ 85 => {+ // Update data (0x55 = 'U')+ offset = Self::parse_update_data(data, offset, topic_mappings, scrips_cache, symbol_mappings, callback);+ }+ _ => {+ eprintln!("[Fyers HSM] Unknown data type: {}", data_type);+ break;+ }+ }+ }+ }++ /// Parse snapshot data (data_type = 83)+ fn parse_snapshot_data(+ data: &[u8],+ mut offset: usize,+ topic_mappings: &mut HashMap<u16, String>,+ scrips_cache: &mut HashMap<u16, HashMap<String, i32>>,+ symbol_mappings: &HashMap<String, String>,+ callback: &Arc<std::sync::RwLock<Option<Box<dyn Fn(MarketMessage) + Send + Sync>>>>,+ ) -> usize {+ if offset + 3 > data.len() {+ return offset;+ }++ // Get topic ID (2 bytes, little-endian in Fyers)+ let topic_id = u16::from_le_bytes([data[offset], data[offset + 1]]);+ offset += 2;++ // Get topic name length+ let topic_name_len = data[offset] as usize;+ offset += 1;++ if offset + topic_name_len > data.len() {+ return offset;+ }++ // Get topic name (HSM token like "sf|nse_cm|2885")+ let topic_name = String::from_utf8_lossy(&data[offset..offset + topic_name_len]).to_string();+ offset += topic_name_len;++ // Store topic mapping+ topic_mappings.insert(topic_id, topic_name.clone());++ // Parse based on topic type+ if topic_name.starts_with("sf|") {+ offset = Self::parse_scrip_snapshot(data, offset, topic_id, &topic_name, scrips_cache, symbol_mappings, callback);+ } else if topic_name.starts_with("if|") {+ offset = Self::parse_index_snapshot(data, offset, topic_id, &topic_name, symbol_mappings, callback);+ } else if topic_name.starts_with("dp|") {+ offset = Self::parse_depth_snapshot(data, offset, topic_id, &topic_name, scrips_cache, symbol_mappings, callback);+ }++ offset+ }++ /// Parse scrip snapshot data+ fn parse_scrip_snapshot(+ data: &[u8],+ mut offset: usize,+ topic_id: u16,+ topic_name: &str,+ scrips_cache: &mut HashMap<u16, HashMap<String, i32>>,+ symbol_mappings: &HashMap<String, String>,+ callback: &Arc<std::sync::RwLock<Option<Box<dyn Fn(MarketMessage) + Send + Sync>>>>,+ ) -> usize {+ if offset + 1 > data.len() {+ return offset;+ }++ let field_count = data[offset] as usize;+ offset += 1;++ let mut scrip_data: HashMap<String, i32> = HashMap::new();++ // Parse field values (4 bytes each, big-endian)+ for index in 0..field_count {+ if offset + 4 > data.len() {+ break;+ }++ let value = i32::from_be_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);+ offset += 4;++ // -2147483648 means null/no value+ if value != i32::MIN && index < DATA_FIELDS.len() {+ scrip_data.insert(DATA_FIELDS[index].to_string(), value);+ }+ }++ // Skip 2 bytes+ offset += 2;++ if offset + 3 > data.len() {+ return offset;+ }++ // Get multiplier and precision+ let multiplier = u16::from_be_bytes([data[offset], data[offset + 1]]);+ offset += 2;+ let precision = data[offset];+ offset += 1;++ // Parse string fields: exchange, exchange_token, symbol+ let mut exchange = String::new();+ let mut exchange_token = String::new();+ let mut symbol = String::new();++ for field_name in &["exchange", "exchange_token", "symbol"] {+ if offset + 1 > data.len() {+ break;+ }++ let string_len = data[offset] as usize;+ offset += 1;++ if offset + string_len > data.len() {+ break;+ }++ let string_value = String::from_utf8_lossy(&data[offset..offset + string_len]).to_string();+ offset += string_len;++ match *field_name {+ "exchange" => exchange = string_value,+ "exchange_token" => exchange_token = string_value,+ "symbol" => symbol = string_value,+ _ => {}+ }+ }++ // Store in cache+ scrips_cache.insert(topic_id, scrip_data.clone());++ // Get original symbol from mapping or use parsed symbol+ let original_symbol = symbol_mappings.get(topic_name)+ .cloned()+ .unwrap_or_else(|| format!("{}:{}", exchange, symbol));++ // Convert to TickerData and emit+ let divisor = if multiplier > 0 { multiplier as f64 * 100.0 } else { 100.0 };++ let tick = TickerData {+ provider: "fyers".to_string(),+ symbol: original_symbol.clone(),+ price: scrip_data.get("ltp").map(|v| *v as f64 / divisor).unwrap_or(0.0),+ bid: scrip_data.get("bid_price").map(|v| *v as f64 / divisor),+ ask: scrip_data.get("ask_price").map(|v| *v as f64 / divisor),+ bid_size: scrip_data.get("bid_size").map(|v| *v as f64),+ ask_size: scrip_data.get("ask_size").map(|v| *v as f64),+ volume: scrip_data.get("vol_traded_today").map(|v| *v as f64),+ high: scrip_data.get("high_price").map(|v| *v as f64 / divisor),+ low: scrip_data.get("low_price").map(|v| *v as f64 / divisor),+ open: scrip_data.get("open_price").map(|v| *v as f64 / divisor),+ close: scrip_data.get("prev_close_price").map(|v| *v as f64 / divisor),+ change: None, // Calculate from ltp - prev_close+ change_percent: None,+ timestamp: scrip_data.get("exch_feed_time").map(|v| *v as u64).unwrap_or_else(|| chrono::Utc::now().timestamp() as u64),};- msg.push(mode_byte);- // Token count- let token_count = tokens.len() as u16;- msg.extend_from_slice(&token_count.to_le_bytes());+ // Calculate change+ let tick = {+ let mut t = tick;+ if let (Some(ltp), Some(close)) = (t.price.into(), t.close) {+ let change = t.price - close;+ let change_pct = if close > 0.0 { (change / close) * 100.0 } else { 0.0 };+ t.change = Some(change);+ t.change_percent = Some(change_pct);+ }+ t+ };- // Tokens- for token in tokens {- msg.extend_from_slice(&token.to_le_bytes());+ // Emit to callback+ if let Ok(cb_lock) = callback.read() {+ if let Some(cb) = cb_lock.as_ref() {+ cb(MarketMessage::Ticker(tick));+ }}- msg+ offset}- /// Handle incoming binary message- async fn handle_binary_message(&self, data: Vec<u8>) {- if data.is_empty() {- return;+ /// Parse index snapshot data+ fn parse_index_snapshot(+ data: &[u8],+ mut offset: usize,+ _topic_id: u16,+ topic_name: &str,+ symbol_mappings: &HashMap<String, String>,+ callback: &Arc<std::sync::RwLock<Option<Box<dyn Fn(MarketMessage) + Send + Sync>>>>,+ ) -> usize {+ if offset + 1 > data.len() {+ return offset;}- let packet_type = data[0];+ let field_count = data[offset] as usize;+ offset += 1;- match packet_type {- PACKET_TYPE_TICK => {- if let Some(tick) = self.parse_tick_data(&data) {- self.emit_tick_message(tick).await;- }+ let mut index_data: HashMap<String, i32> = HashMap::new();++ // Parse field values+ for index in 0..field_count {+ if offset + 4 > data.len() {+ break;}- PACKET_TYPE_DEPTH | PACKET_TYPE_FULL_DEPTH => {- if let Some(depth) = self.parse_depth_data(&data) {- self.emit_depth_message(depth).await;- }++ let value = i32::from_be_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);+ offset += 4;++ if value != i32::MIN && index < INDEX_FIELDS.len() {+ index_data.insert(INDEX_FIELDS[index].to_string(), value);}- PACKET_TYPE_CONFIRMATION => {- eprintln!("Fyers: Subscription confirmed");+ }++ // Get original symbol+ let original_symbol = symbol_mappings.get(topic_name)+ .cloned()+ .unwrap_or_else(|| topic_name.to_string());++ // Index values are already in proper format (no division needed)+ let divisor = 100.0;++ let tick = TickerData {+ provider: "fyers".to_string(),+ symbol: original_symbol,+ price: index_data.get("ltp").map(|v| *v as f64 / divisor).unwrap_or(0.0),+ bid: None,+ ask: None,+ bid_size: None,+ ask_size: None,+ volume: None,+ high: index_data.get("high_price").map(|v| *v as f64 / divisor),+ low: index_data.get("low_price").map(|v| *v as f64 / divisor),+ open: index_data.get("open_price").map(|v| *v as f64 / divisor),+ close: index_data.get("prev_close_price").map(|v| *v as f64 / divisor),+ change: None,+ change_percent: None,+ timestamp: index_data.get("exch_feed_time").map(|v| *v as u64).unwrap_or_else(|| chrono::Utc::now().timestamp() as u64),+ };++ // Calculate change+ let tick = {+ let mut t = tick;+ if let Some(close) = t.close {+ let change = t.price - close;+ let change_pct = if close > 0.0 { (change / close) * 100.0 } else { 0.0 };+ t.change = Some(change);+ t.change_percent = Some(change_pct);}- _ => {- eprintln!("Fyers: Unknown packet type: {}", packet_type);+ t+ };++ if let Ok(cb_lock) = callback.read() {+ if let Some(cb) = cb_lock.as_ref() {+ cb(MarketMessage::Ticker(tick));}}++ offset}- /// Emit tick message to callback- async fn emit_tick_message(&self, tick: FyersTickPacket) {- if let Some(callback) = &self.message_callback {- // Look up symbol from token- let symbol_map = self.token_symbol_map.read().await;- let symbol = symbol_map- .get(&tick.token)- .cloned()- .unwrap_or_else(|| format!("TOKEN_{}", tick.token));-- let message = MarketMessage::Ticker(TickerData {- provider: "fyers".to_string(),- symbol,- price: tick.ltp,- bid: None,- ask: None,- bid_size: None,- ask_size: None,- volume: Some(tick.volume as f64),- high: None,- low: None,- open: None,- close: None,- change: None,- change_percent: Some(tick.change_percent),- timestamp: tick.timestamp,- });-- callback(message);+ /// Parse depth snapshot data+ fn parse_depth_snapshot(+ data: &[u8],+ mut offset: usize,+ topic_id: u16,+ topic_name: &str,+ scrips_cache: &mut HashMap<u16, HashMap<String, i32>>,+ symbol_mappings: &HashMap<String, String>,+ callback: &Arc<std::sync::RwLock<Option<Box<dyn Fn(MarketMessage) + Send + Sync>>>>,+ ) -> usize {+ if offset + 1 > data.len() {+ return offset;+ }++ let field_count = data[offset] as usize;+ offset += 1;++ let mut depth_data: HashMap<String, i32> = HashMap::new();++ // Parse field values+ for index in 0..field_count {+ if offset + 4 > data.len() {+ break;+ }++ let value = i32::from_be_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);+ offset += 4;++ if value != i32::MIN && index < DEPTH_FIELDS.len() {+ depth_data.insert(DEPTH_FIELDS[index].to_string(), value);+ }+ }++ // Skip 2 bytes+ offset += 2;++ if offset + 3 > data.len() {+ return offset;+ }++ // Get multiplier and precision+ let multiplier = u16::from_be_bytes([data[offset], data[offset + 1]]);+ offset += 2;+ let _precision = data[offset];+ offset += 1;++ // Parse string fields+ let mut exchange = String::new();+ let mut symbol = String::new();++ for field_name in &["exchange", "exchange_token", "symbol"] {+ if offset + 1 > data.len() {+ break;+ }++ let string_len = data[offset] as usize;+ offset += 1;++ if offset + string_len > data.len() {+ break;+ }++ let string_value = String::from_utf8_lossy(&data[offset..offset + string_len]).to_string();+ offset += string_len;++ match *field_name {+ "exchange" => exchange = string_value,+ "symbol" => symbol = string_value,+ _ => {}+ }+ }++ // Store in cache+ scrips_cache.insert(topic_id, depth_data.clone());++ // Get original symbol+ let original_symbol = symbol_mappings.get(topic_name)+ .cloned()+ .unwrap_or_else(|| format!("{}:{}", exchange, symbol));++ let divisor = if multiplier > 0 { multiplier as f64 * 100.0 } else { 100.0 };++ // Build order book levels+ let mut bids = Vec::new();+ let mut asks = Vec::new();++ for i in 1..=5 {+ let bid_price_key = format!("bid_price{}", i);+ let bid_size_key = format!("bid_size{}", i);+ let bid_order_key = format!("bid_order{}", i);+ let ask_price_key = format!("ask_price{}", i);+ let ask_size_key = format!("ask_size{}", i);+ let ask_order_key = format!("ask_order{}", i);++ if let Some(&price) = depth_data.get(&bid_price_key) {+ let size = depth_data.get(&bid_size_key).copied().unwrap_or(0);+ let count = depth_data.get(&bid_order_key).map(|&c| c as u32);+ bids.push(OrderBookLevel {+ price: price as f64 / divisor,+ quantity: size as f64,+ count,+ });+ }++ if let Some(&price) = depth_data.get(&ask_price_key) {+ let size = depth_data.get(&ask_size_key).copied().unwrap_or(0);+ let count = depth_data.get(&ask_order_key).map(|&c| c as u32);+ asks.push(OrderBookLevel {+ price: price as f64 / divisor,+ quantity: size as f64,+ count,+ });+ }+ }++ let orderbook = OrderBookData {+ provider: "fyers".to_string(),+ symbol: original_symbol,+ bids,+ asks,+ timestamp: chrono::Utc::now().timestamp() as u64,+ is_snapshot: true,+ };++ if let Ok(cb_lock) = callback.read() {+ if let Some(cb) = cb_lock.as_ref() {+ cb(MarketMessage::OrderBook(orderbook));+ }}++ offset}- /// Emit depth message to callback- async fn emit_depth_message(&self, depth: FyersDepthPacket) {- if let Some(callback) = &self.message_callback {- let symbol_map = self.token_symbol_map.read().await;- let symbol = symbol_map- .get(&depth.token)+ /// Parse update data (data_type = 85) - incremental updates+ fn parse_update_data(+ data: &[u8],+ mut offset: usize,+ topic_mappings: &HashMap<u16, String>,+ scrips_cache: &mut HashMap<u16, HashMap<String, i32>>,+ symbol_mappings: &HashMap<String, String>,+ callback: &Arc<std::sync::RwLock<Option<Box<dyn Fn(MarketMessage) + Send + Sync>>>>,+ ) -> usize {+ if offset + 3 > data.len() {+ return offset;+ }++ // Get topic ID+ let topic_id = u16::from_le_bytes([data[offset], data[offset + 1]]);+ offset += 2;++ // Get field count+ let field_count = data[offset] as usize;+ offset += 1;++ // Get topic name from mapping+ let topic_name = match topic_mappings.get(&topic_id) {+ Some(name) => name.clone(),+ None => {+ // Skip unknown topic+ offset += field_count * 4;+ return offset;+ }+ };++ // Determine field mapping based on topic type+ let fields: &[&str] = if topic_name.starts_with("sf|") {+ DATA_FIELDS+ } else if topic_name.starts_with("if|") {+ INDEX_FIELDS+ } else if topic_name.starts_with("dp|") {+ DEPTH_FIELDS+ } else {+ offset += field_count * 4;+ return offset;+ };++ // Get or create cache entry+ let cache_entry = scrips_cache.entry(topic_id).or_insert_with(HashMap::new);++ // Update fields+ let mut updated = false;+ for index in 0..field_count {+ if offset + 4 > data.len() {+ break;+ }++ let value = i32::from_be_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);+ offset += 4;++ if value != i32::MIN && index < fields.len() {+ let old_value = cache_entry.get(fields[index]).copied();+ if old_value != Some(value) {+ cache_entry.insert(fields[index].to_string(), value);+ updated = true;+ }+ }+ }++ // Emit update if changed+ if updated {+ let original_symbol = symbol_mappings.get(&topic_name).cloned()- .unwrap_or_else(|| format!("TOKEN_{}", depth.token));-- let bids: Vec<OrderBookLevel> = depth- .bids- .iter()- .map(|(price, qty)| OrderBookLevel {- price: *price,- quantity: *qty as f64,- count: None,- })- .collect();-- let asks: Vec<OrderBookLevel> = depth- .asks- .iter()- .map(|(price, qty)| OrderBookLevel {- price: *price,- quantity: *qty as f64,- count: None,- })- .collect();-- let message = MarketMessage::OrderBook(OrderBookData {- provider: "fyers".to_string(),- symbol,- bids,- asks,- timestamp: chrono::Utc::now().timestamp() as u64,- is_snapshot: true,- });-- callback(message);+ .unwrap_or_else(|| topic_name.clone());++ if topic_name.starts_with("sf|") || topic_name.starts_with("if|") {+ let divisor = 100.0; // Default divisor++ let tick = TickerData {+ provider: "fyers".to_string(),+ symbol: original_symbol,+ price: cache_entry.get("ltp").map(|v| *v as f64 / divisor).unwrap_or(0.0),+ bid: cache_entry.get("bid_price").map(|v| *v as f64 / divisor),+ ask: cache_entry.get("ask_price").map(|v| *v as f64 / divisor),+ bid_size: cache_entry.get("bid_size").map(|v| *v as f64),+ ask_size: cache_entry.get("ask_size").map(|v| *v as f64),+ volume: cache_entry.get("vol_traded_today").map(|v| *v as f64),+ high: cache_entry.get("high_price").map(|v| *v as f64 / divisor),+ low: cache_entry.get("low_price").map(|v| *v as f64 / divisor),+ open: cache_entry.get("open_price").map(|v| *v as f64 / divisor),+ close: cache_entry.get("prev_close_price").map(|v| *v as f64 / divisor),+ change: None,+ change_percent: None,+ timestamp: cache_entry.get("exch_feed_time").map(|v| *v as u64).unwrap_or_else(|| chrono::Utc::now().timestamp() as u64),+ };++ // Calculate change+ let tick = {+ let mut t = tick;+ if let Some(close) = t.close {+ let change = t.price - close;+ let change_pct = if close > 0.0 { (change / close) * 100.0 } else { 0.0 };+ t.change = Some(change);+ t.change_percent = Some(change_pct);+ }+ t+ };++ if let Ok(cb_lock) = callback.read() {+ if let Some(cb) = cb_lock.as_ref() {+ cb(MarketMessage::Ticker(tick));+ }+ }+ } else if topic_name.starts_with("dp|") {+ // Emit depth update+ let divisor = 100.0;+ let mut bids = Vec::new();+ let mut asks = Vec::new();++ for i in 1..=5 {+ if let Some(&price) = cache_entry.get(&format!("bid_price{}", i)) {+ let size = cache_entry.get(&format!("bid_size{}", i)).copied().unwrap_or(0);+ let count = cache_entry.get(&format!("bid_order{}", i)).map(|&c| c as u32);+ bids.push(OrderBookLevel {+ price: price as f64 / divisor,+ quantity: size as f64,+ count,+ });+ }+ if let Some(&price) = cache_entry.get(&format!("ask_price{}", i)) {+ let size = cache_entry.get(&format!("ask_size{}", i)).copied().unwrap_or(0);+ let count = cache_entry.get(&format!("ask_order{}", i)).map(|&c| c as u32);+ asks.push(OrderBookLevel {+ price: price as f64 / divisor,+ quantity: size as f64,+ count,+ });+ }+ }++ let orderbook = OrderBookData {+ provider: "fyers".to_string(),+ symbol: original_symbol,+ bids,+ asks,+ timestamp: chrono::Utc::now().timestamp() as u64,+ is_snapshot: false,+ };++ if let Ok(cb_lock) = callback.read() {+ if let Some(cb) = cb_lock.as_ref() {+ cb(MarketMessage::OrderBook(orderbook));+ }+ }+ }}++ offset}/// Start message processing loopasync fn start_message_loop(ws_stream: Arc<RwLock<Option<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,- adapter: Arc<RwLock<FyersAdapter>>,+ is_connected: Arc<RwLock<bool>>,+ is_authenticated: Arc<RwLock<bool>>,+ topic_mappings: Arc<RwLock<HashMap<u16, String>>>,+ scrips_cache: Arc<RwLock<HashMap<u16, HashMap<String, i32>>>>,+ symbol_mappings: Arc<RwLock<HashMap<String, String>>>,+ callback: Arc<std::sync::RwLock<Option<Box<dyn Fn(MarketMessage) + Send + Sync>>>>,) {+ eprintln!("[Fyers HSM] Message loop started");+ let mut msg_count: u64 = 0;+loop {- let mut stream_lock = ws_stream.write().await;+ let msg = {+ let mut stream_lock = ws_stream.write().await;+ if let Some(stream) = stream_lock.as_mut() {+ stream.next().await+ } else {+ eprintln!("[Fyers HSM] Stream is None, exiting loop");+ break;+ }+ };- if let Some(stream) = stream_lock.as_mut() {- match stream.next().await {- Some(Ok(Message::Binary(data))) => {- drop(stream_lock);- let adapter_read = adapter.read().await;- adapter_read.handle_binary_message(data).await;+ msg_count += 1;++ match msg {+ Some(Ok(Message::Binary(data))) => {+ // HSM protocol uses binary messages+ let mut topics = topic_mappings.write().await;+ let mut cache = scrips_cache.write().await;+ let symbols = symbol_mappings.read().await;++ Self::parse_binary_message(+ &data,+ &mut topics,+ &mut cache,+ &symbols,+ &callback,+ );++ // Check if authenticated after first message+ if msg_count == 1 && data.len() >= 3 && data[2] == 1 {+ let mut auth = is_authenticated.write().await;+ *auth = true;+ eprintln!("[Fyers HSM] Authenticated via binary response");}- Some(Ok(Message::Text(text))) => {- drop(stream_lock);- eprintln!("Fyers: Unexpected text message: {}", text);- }- Some(Ok(Message::Ping(data))) => {+ }+ Some(Ok(Message::Text(text))) => {+ // Unexpected text message+ eprintln!("[Fyers HSM] Unexpected text message: {}", &text[..text.len().min(200)]);+ }+ Some(Ok(Message::Ping(data))) => {+ let mut stream_lock = ws_stream.write().await;+ if let Some(stream) = stream_lock.as_mut() {let _ = stream.send(Message::Pong(data)).await;}- Some(Ok(Message::Close(_))) => {- drop(stream_lock);- eprintln!("Fyers: WebSocket closed");- break;- }- Some(Err(e)) => {- drop(stream_lock);- eprintln!("Fyers: WebSocket error: {}", e);- break;- }- None => {- drop(stream_lock);- eprintln!("Fyers: Stream ended");- break;- }- _ => {}}- } else {- drop(stream_lock);- break;+ Some(Ok(Message::Pong(_))) => {+ // Pong received, connection is alive+ }+ Some(Ok(Message::Close(frame))) => {+ eprintln!("[Fyers HSM] Close received: {:?}", frame);+ break;+ }+ Some(Ok(Message::Frame(_))) => {+ // Raw frame, ignore+ }+ Some(Err(e)) => {+ eprintln!("[Fyers HSM] Stream error: {}", e);+ break;+ }+ None => {+ eprintln!("[Fyers HSM] Stream ended");+ break;+ }}}// Mark as disconnected- let adapter_read = adapter.read().await;- let mut connected = adapter_read.is_connected.write().await;+ let mut connected = is_connected.write().await;*connected = false;+ let mut auth = is_authenticated.write().await;+ *auth = false;+ eprintln!("[Fyers HSM] Message loop ended, disconnected");}}#[async_trait]impl WebSocketAdapter for FyersAdapter {async fn connect(&mut self) -> anyhow::Result<()> {- // Use access token from adapterif self.access_token.is_empty() {- return Err(anyhow::anyhow!("Access token not configured"));+ return Err(anyhow::anyhow!("Access token not configured. Format should be 'appid:accesstoken'"));}- // Build WebSocket URL with access token- let url = format!("{}?access_token={}", FYERS_WS_URL, self.access_token);-- // Connect to WebSocket- let (ws_stream, _) = connect_async(&url).await?;+ // Extract HSM key from JWT+ self.hsm_key = Self::extract_hsm_key(&self.access_token);+ if self.hsm_key.is_none() {+ return Err(anyhow::anyhow!("Failed to extract HSM key from access token"));+ }- eprintln!("Fyers: WebSocket connected");+ eprintln!("[Fyers HSM] ========================================");+ eprintln!("[Fyers HSM] CONNECTING TO FYERS HSM WEBSOCKET");+ eprintln!("[Fyers HSM] URL: {}", FYERS_HSM_WS_URL);+ eprintln!("[Fyers HSM] Token length: {} chars", self.access_token.len());+ eprintln!("[Fyers HSM] ========================================");++ // Connect to WebSocket with Authorization header+ let url = url::Url::parse(FYERS_HSM_WS_URL)?;++ let request = tokio_tungstenite::tungstenite::http::Request::builder()+ .uri(FYERS_HSM_WS_URL)+ .header("Authorization", &self.access_token)+ .header("User-Agent", format!("{}/1.0", SOURCE_IDENTIFIER))+ .header("Host", url.host_str().unwrap_or("socket.fyers.in"))+ .header("Connection", "Upgrade")+ .header("Upgrade", "websocket")+ .header("Sec-WebSocket-Version", "13")+ .header("Sec-WebSocket-Key", tokio_tungstenite::tungstenite::handshake::client::generate_key())+ .body(())?;++ let (ws_stream, response) = connect_async(request).await+ .map_err(|e| anyhow::anyhow!("WebSocket connection failed: {}", e))?;++ eprintln!("[Fyers HSM] ========================================");+ eprintln!("[Fyers HSM] CONNECTION SUCCESSFUL!");+ eprintln!("[Fyers HSM] Response Status: {:?}", response.status());+ eprintln!("[Fyers HSM] ========================================");// Store stream- let mut stream_lock = self.ws_stream.write().await;- *stream_lock = Some(ws_stream);- drop(stream_lock);+ {+ let mut stream_lock = self.ws_stream.write().await;+ *stream_lock = Some(ws_stream);+ }// Mark as connected- let mut connected = self.is_connected.write().await;- *connected = true;+ {+ let mut connected = self.is_connected.write().await;+ *connected = true;+ }++ // Send authentication message+ let hsm_key = self.hsm_key.as_ref().unwrap();+ let auth_msg = Self::create_auth_message(hsm_key);++ {+ let mut stream_lock = self.ws_stream.write().await;+ if let Some(stream) = stream_lock.as_mut() {+ stream.send(Message::Binary(auth_msg)).await+ .map_err(|e| anyhow::anyhow!("Failed to send auth message: {}", e))?;+ eprintln!("[Fyers HSM] Authentication message sent");+ }+ }// Start message processing looplet ws_stream_clone = Arc::clone(&self.ws_stream);- let adapter_arc = Arc::new(RwLock::new(Self {- config: self.config.clone(),- access_token: self.access_token.clone(),- ws_stream: Arc::clone(&self.ws_stream),- message_callback: self.message_callback.take(),- subscriptions: Arc::clone(&self.subscriptions),- is_connected: Arc::clone(&self.is_connected),- token_symbol_map: Arc::clone(&self.token_symbol_map),- }));+ let is_connected_clone = Arc::clone(&self.is_connected);+ let is_authenticated_clone = Arc::clone(&self.is_authenticated);+ let topic_mappings_clone = Arc::clone(&self.topic_mappings);+ let scrips_cache_clone = Arc::clone(&self.scrips_cache);+ let symbol_mappings_clone = Arc::clone(&self.symbol_mappings);+ let callback_clone = Arc::clone(&self.message_callback);tokio::spawn(async move {- Self::start_message_loop(ws_stream_clone, adapter_arc).await;+ Self::start_message_loop(+ ws_stream_clone,+ is_connected_clone,+ is_authenticated_clone,+ topic_mappings_clone,+ scrips_cache_clone,+ symbol_mappings_clone,+ callback_clone,+ ).await;});+ // Wait briefly for authentication response (reduced from 500ms)+ tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;+Ok(())}async fn disconnect(&mut self) -> anyhow::Result<()> {let mut stream_lock = self.ws_stream.write().await;if let Some(mut stream) = stream_lock.take() {- stream.close(None).await?;+ let _ = stream.close(None).await;}let mut connected = self.is_connected.write().await;*connected = false;- eprintln!("Fyers: Disconnected");+ let mut auth = self.is_authenticated.write().await;+ *auth = false;++ // Clear caches+ let mut subs = self.subscriptions.write().await;+ subs.clear();++ let mut topics = self.topic_mappings.write().await;+ topics.clear();++ let mut cache = self.scrips_cache.write().await;+ cache.clear();++ let mut symbols = self.symbol_mappings.write().await;+ symbols.clear();++ eprintln!("[Fyers HSM] Disconnected and cleaned up");Ok(())}@@ -474,80 +1281,118 @@ impl WebSocketAdapter for FyersAdapter {channel: &str,_params: Option<Value>,) -> anyhow::Result<()> {- // Convert symbol to token- let token = self- .symbol_to_token(symbol)- .await- .ok_or_else(|| anyhow::anyhow!("Could not map symbol to token: {}", symbol))?;-- // Store symbol-token mapping- let mut symbol_map = self.token_symbol_map.write().await;- symbol_map.insert(token, symbol.to_string());- drop(symbol_map);-- // Determine subscription mode from channel- let mode = match channel {- "tick" | "ltp" => "ltp",- "quote" | "quotes" => "quotes",- "depth" | "market_depth" => "depth",- _ => "ltp",+ eprintln!("[Fyers HSM] ========================================");+ eprintln!("[Fyers HSM] SUBSCRIBE REQUEST");+ eprintln!("[Fyers HSM] Symbol: {}", symbol);+ eprintln!("[Fyers HSM] Channel: {}", channel);+ eprintln!("[Fyers HSM] ========================================");++ // Determine data type from channel+ let data_type = match channel {+ "depth" | "market_depth" | "DepthUpdate" => FyersDataType::DepthUpdate,+ "index" | "IndexUpdate" => FyersDataType::IndexUpdate,+ _ => FyersDataType::SymbolUpdate,+ };++ // Check if we already have the fytoken cached+ let fytoken = {+ let cache = self.fytoken_cache.read().await;+ cache.get(symbol).cloned()+ };++ let fytoken_str = if let Some(fytoken) = fytoken {+ fytoken+ } else {+ // Fetch fytoken from API+ eprintln!("[Fyers HSM] Fytoken not cached, fetching from API...");+ let fytokens = self.fetch_fytokens(&[symbol.to_string()]).await;++ if let Some(fytoken) = fytokens.get(symbol) {+ // Cache the fytoken+ {+ let mut cache = self.fytoken_cache.write().await;+ cache.insert(symbol.to_string(), fytoken.clone());+ }+ fytoken.clone()+ } else {+ // No fytoken available+ eprintln!("[Fyers HSM] WARNING: API lookup failed, cannot subscribe");+ return Err(anyhow::anyhow!("Failed to get fytoken for symbol"));+ }};- // Build subscription message- let sub_msg = self.build_subscription_message(vec![token], mode);+ let is_index = symbol.contains("-INDEX");++ // Build list of HSM tokens to subscribe+ let mut hsm_tokens = Vec::new();++ // Always subscribe to symbol feed (sf|) for LTP/quote data+ if let Some(sf_token) = Self::fytoken_to_hsm_token(&fytoken_str, &FyersDataType::SymbolUpdate, is_index) {+ hsm_tokens.push(sf_token);+ }++ // If depth requested, also subscribe to depth feed (dp|)+ if data_type == FyersDataType::DepthUpdate && !is_index {+ if let Some(dp_token) = Self::fytoken_to_hsm_token(&fytoken_str, &FyersDataType::DepthUpdate, false) {+ hsm_tokens.push(dp_token);+ }+ }++ if hsm_tokens.is_empty() {+ eprintln!("[Fyers HSM] Failed to convert fytoken to HSM tokens");+ return Err(anyhow::anyhow!("Failed to convert fytoken"));+ }++ eprintln!("[Fyers HSM] HSM tokens: {:?}", hsm_tokens);++ // Store symbol mappings (HSM token -> original symbol)+ {+ let mut symbols = self.symbol_mappings.write().await;+ for token in &hsm_tokens {+ symbols.insert(token.clone(), symbol.to_string());+ }+ }++ // Create and send subscription message for all tokens+ let sub_msg = Self::create_subscription_message(&hsm_tokens, 11);- // Send subscriptionlet mut stream_lock = self.ws_stream.write().await;if let Some(stream) = stream_lock.as_mut() {- stream.send(Message::Binary(sub_msg)).await?;+ stream.send(Message::Binary(sub_msg)).await+ .map_err(|e| anyhow::anyhow!("Failed to send subscription: {}", e))?;- // Store subscriptiondrop(stream_lock);++ // Store subscriptionlet mut subs = self.subscriptions.write().await;- let sub_mode = match mode {- "ltp" => SubscriptionMode::Ltp,- "quotes" => SubscriptionMode::Quote,- "depth" => SubscriptionMode::Full,- _ => SubscriptionMode::Ltp,- };- subs.insert(symbol.to_string(), sub_mode);+ subs.insert(symbol.to_string(), data_type);- eprintln!("Fyers: Subscribed to {} (token: {}, mode: {})", symbol, token, mode);+ eprintln!("[Fyers HSM] ✓ Subscribed to {} (HSM tokens: {:?})", symbol, hsm_tokens);Ok(())} else {- Err(anyhow::anyhow!("Not connected"))+ eprintln!("[Fyers HSM] ERROR: Not connected to WebSocket!");+ Err(anyhow::anyhow!("Not connected to WebSocket"))}}async fn unsubscribe(&mut self, symbol: &str, _channel: &str) -> anyhow::Result<()> {- // Convert symbol to token- if let Some(token) = self.symbol_to_token(symbol).await {- // Build unsubscribe message (same format, but message_type = 0)- let mut msg = Vec::new();- msg.push(0); // Unsubscribe- msg.push(1); // Mode (doesn't matter for unsubscribe)- msg.extend_from_slice(&1u16.to_le_bytes()); // Token count- msg.extend_from_slice(&token.to_le_bytes()); // Token-- // Send unsubscribe- let mut stream_lock = self.ws_stream.write().await;- if let Some(stream) = stream_lock.as_mut() {- stream.send(Message::Binary(msg)).await?;+ // Note: Fyers HSM doesn't support selective unsubscription+ // We just remove from our tracking+ let mut subs = self.subscriptions.write().await;+ subs.remove(symbol);- // Remove subscription- drop(stream_lock);- let mut subs = self.subscriptions.write().await;- subs.remove(symbol);-- eprintln!("Fyers: Unsubscribed from {} (token: {})", symbol, token);- }- }+ let mut symbols = self.symbol_mappings.write().await;+ // Remove all mappings for this symbol+ symbols.retain(|_, v| v != symbol);+ eprintln!("[Fyers HSM] Unsubscribed from {} (local only - HSM doesn't support selective unsub)", symbol);Ok(())}fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {- self.message_callback = Some(callback);+ if let Ok(mut cb_lock) = self.message_callback.write() {+ *cb_lock = Some(callback);+ }}fn provider_name(&self) -> &str {@@ -555,7 +1400,136 @@ impl WebSocketAdapter for FyersAdapter {}fn is_connected(&self) -> bool {- // Read from Arc<RwLock<bool>> synchronously (blocking)futures::executor::block_on(async { *self.is_connected.read().await })}}++/// Subscribe to multiple symbols at once (batch subscription) - FAST VERSION+/// Pre-fetches all fytokens in ONE API call before subscribing+impl FyersAdapter {+ pub async fn subscribe_batch(+ &mut self,+ symbols: &[String],+ data_type: FyersDataType,+ ) -> anyhow::Result<()> {+ if symbols.is_empty() {+ return Ok(());+ }++ eprintln!("[Fyers HSM] ========================================");+ eprintln!("[Fyers HSM] BATCH SUBSCRIBE: {} symbols", symbols.len());+ eprintln!("[Fyers HSM] ========================================");++ let start_time = std::time::Instant::now();++ // Step 1: Batch fetch ALL fytokens in one API call (FAST!)+ let fytokens = self.fetch_fytokens(symbols).await;+ eprintln!("[Fyers HSM] Fetched {} fytokens in {:?}", fytokens.len(), start_time.elapsed());++ if fytokens.is_empty() {+ return Err(anyhow::anyhow!("Failed to fetch any fytokens from API"));+ }++ // Step 2: Convert fytokens to HSM tokens+ let mut hsm_tokens: Vec<String> = Vec::new();+ let mut symbol_to_hsm: Vec<(String, String)> = Vec::new();++ for symbol in symbols {+ let is_index = symbol.contains("-INDEX");++ if let Some(fytoken) = fytokens.get(symbol) {+ // Cache the fytoken+ {+ let mut cache = self.fytoken_cache.write().await;+ cache.insert(symbol.clone(), fytoken.clone());+ }++ // Always add sf| token for LTP+ if let Some(sf_token) = Self::fytoken_to_hsm_token(fytoken, &FyersDataType::SymbolUpdate, is_index) {+ hsm_tokens.push(sf_token.clone());+ symbol_to_hsm.push((sf_token, symbol.clone()));+ }++ // Also add dp| token if depth requested and not index+ if data_type == FyersDataType::DepthUpdate && !is_index {+ if let Some(dp_token) = Self::fytoken_to_hsm_token(fytoken, &FyersDataType::DepthUpdate, false) {+ hsm_tokens.push(dp_token.clone());+ symbol_to_hsm.push((dp_token, symbol.clone()));+ }+ }+ } else {+ eprintln!("[Fyers HSM] Warning: No fytoken for {}", symbol);+ }+ }++ eprintln!("[Fyers HSM] Generated {} HSM tokens", hsm_tokens.len());++ // Step 3: Store symbol mappings+ {+ let mut symbol_map = self.symbol_mappings.write().await;+ for (hsm_token, symbol) in &symbol_to_hsm {+ symbol_map.insert(hsm_token.clone(), symbol.clone());+ }+ }++ // Step 4: Subscribe in batches (Fyers supports up to 5000, batch in 100)+ const BATCH_SIZE: usize = 100;++ for chunk in hsm_tokens.chunks(BATCH_SIZE) {+ let sub_msg = Self::create_subscription_message(&chunk.to_vec(), 11);++ let mut stream_lock = self.ws_stream.write().await;+ if let Some(stream) = stream_lock.as_mut() {+ stream.send(Message::Binary(sub_msg)).await+ .map_err(|e| anyhow::anyhow!("Failed to send batch subscription: {}", e))?;++ eprintln!("[Fyers HSM] Sent subscription for {} tokens", chunk.len());+ } else {+ return Err(anyhow::anyhow!("Not connected to WebSocket"));+ }+ drop(stream_lock);++ // Minimal delay between batches+ if chunk.len() == BATCH_SIZE {+ tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;+ }+ }++ // Store subscriptions+ {+ let mut subs = self.subscriptions.write().await;+ for symbol in symbols {+ subs.insert(symbol.clone(), data_type.clone());+ }+ }++ eprintln!("[Fyers HSM] ✓ Batch subscription complete in {:?}", start_time.elapsed());+ Ok(())+ }++ pub async fn unsubscribe_batch(&mut self, symbols: &[String]) -> anyhow::Result<()> {+ // Note: HSM doesn't support selective unsubscription+ // Just remove from tracking+ let mut subs = self.subscriptions.write().await;+ let mut symbol_map = self.symbol_mappings.write().await;++ for symbol in symbols {+ subs.remove(symbol);+ symbol_map.retain(|_, v| v != symbol);+ }++ eprintln!("[Fyers HSM] Batch unsubscribed from {} symbols (local only)", symbols.len());+ Ok(())+ }++ /// Get current subscription count+ pub async fn subscription_count(&self) -> usize {+ let subs = self.subscriptions.read().await;+ subs.len()+ }++ /// Check if authenticated+ pub async fn is_authenticated(&self) -> bool {+ *self.is_authenticated.read().await+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/groww.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/groww.rsnew file mode 100644index 000000000..375545de5--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/groww.rs@@ -0,0 +1,319 @@+// Groww WebSocket Adapter (NATS Protocol)+//+// Groww uses NATS protocol over WebSocket:+// - WebSocket URL: wss://socket-api.groww.in+// - Requires socket token from API: POST /v1/api/apex/v1/socket/token/create/+// - NATS protocol with nkey authentication+// - Protobuf-encoded market data++use super::WebSocketAdapter;+use crate::websocket::types::*;+use async_trait::async_trait;+use futures_util::{SinkExt, StreamExt};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::collections::HashMap;+use std::sync::Arc;+use tokio::net::TcpStream;+use tokio::sync::RwLock;+use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream};++// ============================================================================+// GROWW CONFIGURATION+// ============================================================================++const GROWW_WS_URL: &str = "wss://socket-api.groww.in";+const GROWW_TOKEN_URL: &str = "https://api.groww.in/v1/api/apex/v1/socket/token/create/";++// ============================================================================+// GROWW STRUCTURES+// ============================================================================++#[derive(Debug, Clone, PartialEq)]+pub enum GrowwMode {+ Ltp,+ Depth,+}++#[derive(Debug, Serialize)]+struct TokenRequest {+ #[serde(rename = "socketKey")]+ socket_key: String,+}++#[derive(Debug, Deserialize)]+struct TokenResponse {+ token: Option<String>,+ #[serde(rename = "subscriptionId")]+ subscription_id: Option<String>,+}++#[derive(Debug, Clone)]+pub struct GrowwTick {+ pub symbol: String,+ pub exchange: String,+ pub ltp: f64,+ pub change: f64,+ pub change_percent: f64,+ pub volume: i64,+ pub timestamp: u64,+}++// ============================================================================+// GROWW ADAPTER+// ============================================================================++pub struct GrowwAdapter {+ config: ProviderConfig,+ auth_token: String,+ socket_token: Option<String>,+ subscription_id: Option<String>,+ ws_stream: Arc<RwLock<Option<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,+ message_callback: Option<Box<dyn Fn(MarketMessage) + Send + Sync>>,+ subscriptions: Arc<RwLock<HashMap<String, GrowwMode>>>,+ is_connected: Arc<RwLock<bool>>,+ nats_sid_counter: Arc<RwLock<u32>>,+}++impl GrowwAdapter {+ pub fn new(config: ProviderConfig) -> Self {+ let auth_token = config.api_key.clone().unwrap_or_default();++ Self {+ config,+ auth_token,+ socket_token: None,+ subscription_id: None,+ ws_stream: Arc::new(RwLock::new(None)),+ message_callback: None,+ subscriptions: Arc::new(RwLock::new(HashMap::new())),+ is_connected: Arc::new(RwLock::new(false)),+ nats_sid_counter: Arc::new(RwLock::new(1)),+ }+ }++ /// Generate socket token from Groww API+ async fn generate_socket_token(&mut self) -> anyhow::Result<()> {+ let client = reqwest::Client::new();++ // Generate a simple socket key (in production, use proper nkey)+ let socket_key = format!("UFINCEPT{}", uuid::Uuid::new_v4().to_string().replace("-", "")[..16].to_string());++ let response = client+ .post(GROWW_TOKEN_URL)+ .header("Authorization", format!("Bearer {}", self.auth_token))+ .header("Content-Type", "application/json")+ .header("x-client-id", "growwapi")+ .json(&TokenRequest { socket_key })+ .send()+ .await?;++ if response.status().is_success() {+ let token_response: TokenResponse = response.json().await?;+ self.socket_token = token_response.token;+ self.subscription_id = token_response.subscription_id;+ tracing::info!("Generated Groww socket token");+ } else {+ // Fallback to using auth token directly+ tracing::warn!("Failed to generate socket token, using auth token as fallback");+ self.socket_token = Some(self.auth_token.clone());+ self.subscription_id = Some("direct_auth".to_string());+ }++ Ok(())+ }++ /// Create NATS CONNECT message+ fn create_nats_connect(&self) -> String {+ let connect_opts = serde_json::json!({+ "jwt": self.socket_token.as_ref().unwrap_or(&self.auth_token),+ "lang": "rust",+ "version": "1.0.0",+ "protocol": 1,+ "verbose": false,+ "pedantic": false+ });+ format!("CONNECT {}\r\n", connect_opts)+ }++ /// Create NATS SUB message+ fn create_nats_subscribe(&self, topic: &str, sid: u32) -> String {+ format!("SUB {} {}\r\n", topic, sid)+ }++ /// Create NATS UNSUB message+ fn create_nats_unsubscribe(&self, sid: u32) -> String {+ format!("UNSUB {}\r\n", sid)+ }++ /// Format topic for Groww+ fn format_topic(&self, exchange: &str, segment: &str, token: &str, mode: &GrowwMode) -> String {+ let mode_str = match mode {+ GrowwMode::Ltp => "price",+ GrowwMode::Depth => "book",+ };++ // Format: /ld/eq/nse/price.{token} or /ld/fo/nse/book.{token}+ let segment_code = match segment.to_uppercase().as_str() {+ "FNO" | "FO" => "fo",+ _ => "eq",+ };++ format!("/ld/{}/{}/{}.{}", segment_code, exchange.to_lowercase(), mode_str, token)+ }++ /// Parse protobuf market data (simplified)+ fn parse_protobuf_data(&self, data: &[u8]) -> Option<GrowwTick> {+ // Simplified protobuf parsing+ // In production, use proper protobuf definitions with prost+ if data.len() < 10 {+ return None;+ }++ Some(GrowwTick {+ symbol: String::new(),+ exchange: String::new(),+ ltp: 0.0,+ change: 0.0,+ change_percent: 0.0,+ volume: 0,+ timestamp: 0,+ })+ }+}++#[async_trait]+impl WebSocketAdapter for GrowwAdapter {+ async fn connect(&mut self) -> anyhow::Result<()> {+ // Generate socket token first+ self.generate_socket_token().await?;++ tracing::info!("Connecting to Groww WebSocket (NATS)");++ let (ws_stream, _) = connect_async(GROWW_WS_URL).await?;+ tracing::info!("Connected to Groww WebSocket");++ *self.ws_stream.write().await = Some(ws_stream);++ // Send NATS CONNECT+ if let Some(ref mut ws) = *self.ws_stream.write().await {+ let connect_msg = self.create_nats_connect();+ ws.send(Message::Text(connect_msg)).await?;+ ws.send(Message::Text("PING\r\n".to_string())).await?;+ }++ *self.is_connected.write().await = true;++ let ws_stream = self.ws_stream.clone();+ let is_connected = self.is_connected.clone();++ tokio::spawn(async move {+ loop {+ let mut stream = ws_stream.write().await;+ if let Some(ref mut ws) = *stream {+ match ws.next().await {+ Some(Ok(Message::Binary(data))) => {+ tracing::debug!("Received binary: {} bytes", data.len());+ }+ Some(Ok(Message::Text(text))) => {+ if text.starts_with("PING") {+ let _ = ws.send(Message::Text("PONG\r\n".to_string())).await;+ } else if text.starts_with("INFO") {+ tracing::debug!("Received NATS INFO");+ } else if text.starts_with("+OK") {+ tracing::debug!("Received NATS +OK");+ }+ }+ Some(Ok(Message::Ping(data))) => {+ let _ = ws.send(Message::Pong(data)).await;+ }+ Some(Err(e)) => {+ tracing::error!("WebSocket error: {}", e);+ *is_connected.write().await = false;+ break;+ }+ None => {+ *is_connected.write().await = false;+ break;+ }+ _ => {}+ }+ } else {+ break;+ }+ drop(stream);+ tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;+ }+ });++ Ok(())+ }++ async fn disconnect(&mut self) -> anyhow::Result<()> {+ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.close(None).await?;+ }+ *self.ws_stream.write().await = None;+ *self.is_connected.write().await = false;+ tracing::info!("Disconnected from Groww WebSocket");+ Ok(())+ }++ async fn subscribe(+ &mut self,+ symbol: &str,+ channel: &str,+ _params: Option<Value>,+ ) -> anyhow::Result<()> {+ let mode = match channel {+ "depth" => GrowwMode::Depth,+ _ => GrowwMode::Ltp,+ };++ // Parse symbol: "NSE:CASH:1594" or "NSE:FNO:12345"+ let parts: Vec<&str> = symbol.split(':').collect();+ if parts.len() < 3 {+ return Err(anyhow::anyhow!("Invalid symbol format. Expected 'Exchange:Segment:Token'"));+ }++ let exchange = parts[0];+ let segment = parts[1];+ let token = parts[2];++ let topic = self.format_topic(exchange, segment, token, &mode);++ let mut sid_counter = self.nats_sid_counter.write().await;+ let sid = *sid_counter;+ *sid_counter += 1;+ drop(sid_counter);++ let sub_msg = self.create_nats_subscribe(&topic, sid);++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(sub_msg)).await?;+ ws.send(Message::Text("PING\r\n".to_string())).await?;+ self.subscriptions.write().await.insert(symbol.to_string(), mode);+ tracing::info!("Subscribed to {} (topic: {})", symbol, topic);+ }++ Ok(())+ }++ async fn unsubscribe(&mut self, symbol: &str, _channel: &str) -> anyhow::Result<()> {+ self.subscriptions.write().await.remove(symbol);+ tracing::info!("Unsubscribed from {}", symbol);+ Ok(())+ }++ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {+ self.message_callback = Some(callback);+ }++ fn provider_name(&self) -> &str {+ "groww"+ }++ fn is_connected(&self) -> bool {+ self.is_connected.try_read().map(|g| *g).unwrap_or(false)+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/iifl.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/iifl.rsnew file mode 100644index 000000000..3d071a4dc--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/iifl.rs@@ -0,0 +1,296 @@+// IIFL Securities WebSocket Adapter+//+// IIFL uses XTS API WebSocket for market data:+// - WebSocket URL: Obtained from market data login+// - Authentication via session token+// - Binary message format++use super::WebSocketAdapter;+use crate::websocket::types::*;+use async_trait::async_trait;+use futures_util::{SinkExt, StreamExt};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::collections::HashMap;+use std::sync::Arc;+use tokio::net::TcpStream;+use tokio::sync::RwLock;+use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream};++// ============================================================================+// IIFL CONFIGURATION+// ============================================================================++const IIFL_MARKET_LOGIN_URL: &str = "https://ttblaze.iifl.com/apimarketdata/auth/login";++// ============================================================================+// IIFL STRUCTURES+// ============================================================================++#[derive(Debug, Clone, PartialEq)]+pub enum IiflMode {+ Ltp,+ Quote,+ Depth,+}++#[derive(Debug, Serialize)]+struct LoginRequest {+ secretKey: String,+ appKey: String,+ source: String,+}++#[derive(Debug, Deserialize)]+struct LoginResponse {+ result: Option<LoginResult>,+}++#[derive(Debug, Deserialize)]+struct LoginResult {+ token: Option<String>,+ userID: Option<String>,+}++#[derive(Debug, Serialize)]+struct SubscribeRequest {+ instruments: Vec<IiflInstrument>,+ xtsMessageCode: i32,+ publishFormat: String,+}++#[derive(Debug, Serialize, Clone)]+struct IiflInstrument {+ exchangeSegment: i32,+ exchangeInstrumentID: i32,+}++#[derive(Debug, Clone)]+pub struct IiflTick {+ pub exchange_segment: i32,+ pub exchange_instrument_id: i32,+ pub ltp: f64,+ pub volume: i64,+ pub open: f64,+ pub high: f64,+ pub low: f64,+ pub close: f64,+ pub timestamp: u64,+}++// ============================================================================+// IIFL ADAPTER+// ============================================================================++pub struct IiflAdapter {+ config: ProviderConfig,+ app_key: String,+ secret_key: String,+ session_token: Option<String>,+ ws_url: Option<String>,+ ws_stream: Arc<RwLock<Option<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,+ message_callback: Option<Box<dyn Fn(MarketMessage) + Send + Sync>>,+ subscriptions: Arc<RwLock<HashMap<String, IiflMode>>>,+ is_connected: Arc<RwLock<bool>>,+}++impl IiflAdapter {+ pub fn new(config: ProviderConfig) -> Self {+ let app_key = config.api_key.clone().unwrap_or_default();+ let secret_key = config.api_secret.clone().unwrap_or_default();++ Self {+ config,+ app_key,+ secret_key,+ session_token: None,+ ws_url: None,+ ws_stream: Arc::new(RwLock::new(None)),+ message_callback: None,+ subscriptions: Arc::new(RwLock::new(HashMap::new())),+ is_connected: Arc::new(RwLock::new(false)),+ }+ }++ async fn login(&mut self) -> anyhow::Result<()> {+ let client = reqwest::Client::new();++ let login_req = LoginRequest {+ secretKey: self.secret_key.clone(),+ appKey: self.app_key.clone(),+ source: "WebAPI".to_string(),+ };++ let response = client+ .post(IIFL_MARKET_LOGIN_URL)+ .json(&login_req)+ .send()+ .await?;++ if response.status().is_success() {+ let login_response: LoginResponse = response.json().await?;+ if let Some(result) = login_response.result {+ self.session_token = result.token;+ tracing::info!("IIFL market data login successful");+ }+ } else {+ return Err(anyhow::anyhow!("IIFL login failed"));+ }++ // Get WebSocket URL (would come from login response in production)+ self.ws_url = Some("wss://ttblaze.iifl.com/socket.io/marketdata".to_string());++ Ok(())+ }++ fn parse_binary_data(&self, data: &[u8]) -> Option<IiflTick> {+ if data.len() < 40 {+ return None;+ }++ // Parse IIFL binary format+ Some(IiflTick {+ exchange_segment: 0,+ exchange_instrument_id: 0,+ ltp: 0.0,+ volume: 0,+ open: 0.0,+ high: 0.0,+ low: 0.0,+ close: 0.0,+ timestamp: 0,+ })+ }+}++#[async_trait]+impl WebSocketAdapter for IiflAdapter {+ async fn connect(&mut self) -> anyhow::Result<()> {+ // Login first to get session token+ self.login().await?;++ let ws_url = self.ws_url.as_ref()+ .ok_or_else(|| anyhow::anyhow!("No WebSocket URL available"))?;++ tracing::info!("Connecting to IIFL WebSocket");++ let url_with_token = format!(+ "{}?token={}",+ ws_url,+ self.session_token.as_ref().unwrap_or(&String::new())+ );++ let (ws_stream, _) = connect_async(&url_with_token).await?;+ tracing::info!("Connected to IIFL WebSocket");++ *self.ws_stream.write().await = Some(ws_stream);+ *self.is_connected.write().await = true;++ let ws_stream = self.ws_stream.clone();+ let is_connected = self.is_connected.clone();++ tokio::spawn(async move {+ loop {+ let mut stream = ws_stream.write().await;+ if let Some(ref mut ws) = *stream {+ match ws.next().await {+ Some(Ok(Message::Binary(data))) => {+ tracing::debug!("Received binary: {} bytes", data.len());+ }+ Some(Ok(Message::Ping(data))) => {+ let _ = ws.send(Message::Pong(data)).await;+ }+ Some(Err(e)) => {+ tracing::error!("WebSocket error: {}", e);+ *is_connected.write().await = false;+ break;+ }+ None => {+ *is_connected.write().await = false;+ break;+ }+ _ => {}+ }+ } else {+ break;+ }+ drop(stream);+ tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;+ }+ });++ Ok(())+ }++ async fn disconnect(&mut self) -> anyhow::Result<()> {+ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.close(None).await?;+ }+ *self.ws_stream.write().await = None;+ *self.is_connected.write().await = false;+ tracing::info!("Disconnected from IIFL WebSocket");+ Ok(())+ }++ async fn subscribe(+ &mut self,+ symbol: &str,+ channel: &str,+ _params: Option<Value>,+ ) -> anyhow::Result<()> {+ let mode = match channel {+ "depth" => IiflMode::Depth,+ "quote" => IiflMode::Quote,+ _ => IiflMode::Ltp,+ };++ // Parse symbol: "1:12345" (ExchangeSegment:InstrumentID)+ let parts: Vec<&str> = symbol.split(':').collect();+ if parts.len() != 2 {+ return Err(anyhow::anyhow!("Invalid symbol format. Expected 'ExchangeSegment:InstrumentID'"));+ }++ let instrument = IiflInstrument {+ exchangeSegment: parts[0].parse().map_err(|_| anyhow::anyhow!("Invalid exchange segment"))?,+ exchangeInstrumentID: parts[1].parse().map_err(|_| anyhow::anyhow!("Invalid instrument ID"))?,+ };++ let xts_code = match mode {+ IiflMode::Ltp => 1501,+ IiflMode::Quote => 1502,+ IiflMode::Depth => 1505,+ };++ let subscribe_req = SubscribeRequest {+ instruments: vec![instrument],+ xtsMessageCode: xts_code,+ publishFormat: "JSON".to_string(),+ };++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(serde_json::to_string(&subscribe_req)?)).await?;+ self.subscriptions.write().await.insert(symbol.to_string(), mode);+ tracing::info!("Subscribed to {}", symbol);+ }++ Ok(())+ }++ async fn unsubscribe(&mut self, symbol: &str, _channel: &str) -> anyhow::Result<()> {+ self.subscriptions.write().await.remove(symbol);+ tracing::info!("Unsubscribed from {}", symbol);+ Ok(())+ }++ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {+ self.message_callback = Some(callback);+ }++ fn provider_name(&self) -> &str {+ "iifl"+ }++ fn is_connected(&self) -> bool {+ self.is_connected.try_read().map(|g| *g).unwrap_or(false)+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/kotak.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/kotak.rsnew file mode 100644index 000000000..18b6d3ee3--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/kotak.rs@@ -0,0 +1,231 @@+// Kotak Securities WebSocket Adapter+//+// Kotak uses Neo API WebSocket for market data streaming:+// - WebSocket URL: wss://livefeeds.kotaksecurities.com+// - Authentication via token in connection params+// - Binary message format with specific packet structures++use super::WebSocketAdapter;+use crate::websocket::types::*;+use async_trait::async_trait;+use futures_util::{SinkExt, StreamExt};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::collections::HashMap;+use std::sync::Arc;+use tokio::net::TcpStream;+use tokio::sync::RwLock;+use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream};++// ============================================================================+// KOTAK CONFIGURATION+// ============================================================================++const KOTAK_WS_URL: &str = "wss://livefeeds.kotaksecurities.com";++// Subscription modes+#[derive(Debug, Clone, PartialEq)]+pub enum KotakMode {+ Ltp,+ Quote,+ Depth,+}++// ============================================================================+// KOTAK STRUCTURES+// ============================================================================++#[derive(Debug, Serialize)]+struct KotakSubscription {+ #[serde(rename = "type")]+ msg_type: String,+ scrips: Vec<KotakScrip>,+}++#[derive(Debug, Serialize, Clone)]+struct KotakScrip {+ exchange: String,+ token: String,+}++#[derive(Debug, Clone)]+pub struct KotakTick {+ pub exchange: String,+ pub token: String,+ pub ltp: f64,+ pub volume: i64,+ pub open: f64,+ pub high: f64,+ pub low: f64,+ pub close: f64,+ pub timestamp: u64,+}++// ============================================================================+// KOTAK ADAPTER+// ============================================================================++pub struct KotakAdapter {+ config: ProviderConfig,+ access_token: String,+ consumer_key: String,+ ws_stream: Arc<RwLock<Option<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,+ message_callback: Option<Box<dyn Fn(MarketMessage) + Send + Sync>>,+ subscriptions: Arc<RwLock<HashMap<String, KotakMode>>>,+ is_connected: Arc<RwLock<bool>>,+}++impl KotakAdapter {+ pub fn new(config: ProviderConfig) -> Self {+ let access_token = config.api_key.clone().unwrap_or_default();+ let consumer_key = config.api_secret.clone().unwrap_or_default();++ Self {+ config,+ access_token,+ consumer_key,+ ws_stream: Arc::new(RwLock::new(None)),+ message_callback: None,+ subscriptions: Arc::new(RwLock::new(HashMap::new())),+ is_connected: Arc::new(RwLock::new(false)),+ }+ }++ fn build_ws_url(&self) -> String {+ format!(+ "{}?Authorization=Bearer {}&consumerKey={}",+ KOTAK_WS_URL, self.access_token, self.consumer_key+ )+ }++ fn parse_binary_data(&self, data: &[u8]) -> Option<KotakTick> {+ if data.len() < 40 {+ return None;+ }++ // Kotak binary format parsing+ // This is a simplified implementation+ Some(KotakTick {+ exchange: "NSE".to_string(),+ token: "0".to_string(),+ ltp: 0.0,+ volume: 0,+ open: 0.0,+ high: 0.0,+ low: 0.0,+ close: 0.0,+ timestamp: 0,+ })+ }+}++#[async_trait]+impl WebSocketAdapter for KotakAdapter {+ async fn connect(&mut self) -> anyhow::Result<()> {+ let ws_url = self.build_ws_url();+ tracing::info!("Connecting to Kotak WebSocket");++ let (ws_stream, _) = connect_async(&ws_url).await?;+ tracing::info!("Connected to Kotak WebSocket");++ *self.ws_stream.write().await = Some(ws_stream);+ *self.is_connected.write().await = true;++ let ws_stream = self.ws_stream.clone();+ let is_connected = self.is_connected.clone();++ tokio::spawn(async move {+ loop {+ let mut stream = ws_stream.write().await;+ if let Some(ref mut ws) = *stream {+ match ws.next().await {+ Some(Ok(Message::Binary(data))) => {+ tracing::debug!("Received binary: {} bytes", data.len());+ }+ Some(Ok(Message::Ping(data))) => {+ let _ = ws.send(Message::Pong(data)).await;+ }+ Some(Err(e)) => {+ tracing::error!("WebSocket error: {}", e);+ *is_connected.write().await = false;+ break;+ }+ None => {+ *is_connected.write().await = false;+ break;+ }+ _ => {}+ }+ } else {+ break;+ }+ drop(stream);+ tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;+ }+ });++ Ok(())+ }++ async fn disconnect(&mut self) -> anyhow::Result<()> {+ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.close(None).await?;+ }+ *self.ws_stream.write().await = None;+ *self.is_connected.write().await = false;+ tracing::info!("Disconnected from Kotak WebSocket");+ Ok(())+ }++ async fn subscribe(+ &mut self,+ symbol: &str,+ channel: &str,+ _params: Option<Value>,+ ) -> anyhow::Result<()> {+ let mode = match channel {+ "depth" => KotakMode::Depth,+ "quote" => KotakMode::Quote,+ _ => KotakMode::Ltp,+ };++ let parts: Vec<&str> = symbol.split(':').collect();+ if parts.len() != 2 {+ return Err(anyhow::anyhow!("Invalid symbol format"));+ }++ let subscription = KotakSubscription {+ msg_type: "subscribe".to_string(),+ scrips: vec![KotakScrip {+ exchange: parts[0].to_string(),+ token: parts[1].to_string(),+ }],+ };++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(serde_json::to_string(&subscription)?)).await?;+ self.subscriptions.write().await.insert(symbol.to_string(), mode);+ tracing::info!("Subscribed to {}", symbol);+ }++ Ok(())+ }++ async fn unsubscribe(&mut self, symbol: &str, _channel: &str) -> anyhow::Result<()> {+ self.subscriptions.write().await.remove(symbol);+ tracing::info!("Unsubscribed from {}", symbol);+ Ok(())+ }++ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {+ self.message_callback = Some(callback);+ }++ fn provider_name(&self) -> &str {+ "kotak"+ }++ fn is_connected(&self) -> bool {+ self.is_connected.try_read().map(|g| *g).unwrap_or(false)+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mod.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mod.rsindex 7ab2fd28a..44ab644e8 100644--- a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mod.rs+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/mod.rs@@ -3,17 +3,43 @@use super::types::*;use async_trait::async_trait;+// Crypto exchange adapterspub mod kraken;pub mod hyperliquid;pub mod binance;++// Indian stock broker adapterspub mod fyers;pub mod zerodha;+pub mod upstox;+pub mod dhan;+pub mod angelone;+pub mod kotak;+pub mod groww;+pub mod aliceblue;+pub mod fivepaisa;+pub mod iifl;+pub mod motilal;+pub mod shoonya;+// Crypto exportspub use kraken::KrakenAdapter;pub use hyperliquid::HyperLiquidAdapter;pub use binance::BinanceAdapter;++// Indian broker exportspub use fyers::FyersAdapter;pub use zerodha::ZerodhaAdapter;+pub use upstox::UpstoxAdapter;+pub use dhan::DhanAdapter;+pub use angelone::AngelOneAdapter;+pub use kotak::KotakAdapter;+pub use groww::GrowwAdapter;+pub use aliceblue::AliceBlueAdapter;+pub use fivepaisa::FivePaisaAdapter;+pub use iifl::IiflAdapter;+pub use motilal::MotilalAdapter;+pub use shoonya::ShoonyaAdapter;// ============================================================================// ADAPTER TRAIT@@ -59,11 +85,23 @@ pub fn create_adapter(config: ProviderConfig,) -> anyhow::Result<Box<dyn WebSocketAdapter>> {match provider.to_lowercase().as_str() {+ // Crypto exchanges"kraken" => Ok(Box::new(KrakenAdapter::new(config))),"hyperliquid" => Ok(Box::new(HyperLiquidAdapter::new(config))),"binance" => Ok(Box::new(BinanceAdapter::new(config))),+ // Indian stock brokers"fyers" => Ok(Box::new(FyersAdapter::new(config))),"zerodha" | "kite" => Ok(Box::new(ZerodhaAdapter::new(config))),+ "upstox" => Ok(Box::new(UpstoxAdapter::new(config))),+ "dhan" => Ok(Box::new(DhanAdapter::new(config))),+ "angelone" | "angel" | "smartapi" => Ok(Box::new(AngelOneAdapter::new(config))),+ "kotak" | "kotak_neo" => Ok(Box::new(KotakAdapter::new(config))),+ "groww" => Ok(Box::new(GrowwAdapter::new(config))),+ "aliceblue" | "alice" | "ant" => Ok(Box::new(AliceBlueAdapter::new(config))),+ "fivepaisa" | "5paisa" => Ok(Box::new(FivePaisaAdapter::new(config))),+ "iifl" | "iifl_securities" => Ok(Box::new(IiflAdapter::new(config))),+ "motilal" | "motilaloswal" => Ok(Box::new(MotilalAdapter::new(config))),+ "shoonya" | "finvasia" => Ok(Box::new(ShoonyaAdapter::new(config))),_ => Err(anyhow::anyhow!("Unknown provider: {}", provider)),}}diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/motilal.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/motilal.rsnew file mode 100644index 000000000..036ff7e23--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/motilal.rs@@ -0,0 +1,275 @@+// Motilal Oswal WebSocket Adapter+//+// Motilal Oswal uses WebSocket for market data streaming:+// - WebSocket URL: wss://wsapi.motilaloswal.com+// - Authentication via access token+// - JSON/Binary message format++use super::WebSocketAdapter;+use crate::websocket::types::*;+use async_trait::async_trait;+use futures_util::{SinkExt, StreamExt};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::collections::HashMap;+use std::sync::Arc;+use tokio::net::TcpStream;+use tokio::sync::RwLock;+use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream};++// ============================================================================+// MOTILAL CONFIGURATION+// ============================================================================++const MOTILAL_WS_URL: &str = "wss://wsapi.motilaloswal.com/";++// ============================================================================+// MOTILAL STRUCTURES+// ============================================================================++#[derive(Debug, Clone, PartialEq)]+pub enum MotilalMode {+ Ltp,+ Quote,+ Depth,+}++#[derive(Debug, Serialize)]+struct AuthMessage {+ #[serde(rename = "MessageType")]+ message_type: String,+ #[serde(rename = "AccessToken")]+ access_token: String,+}++#[derive(Debug, Serialize)]+struct SubscribeMessage {+ #[serde(rename = "MessageType")]+ message_type: String,+ #[serde(rename = "Exchange")]+ exchange: String,+ #[serde(rename = "ScripCode")]+ scrip_code: String,+ #[serde(rename = "Mode")]+ mode: String,+}++#[derive(Debug, Deserialize)]+struct TickResponse {+ #[serde(rename = "Exchange")]+ exchange: Option<String>,+ #[serde(rename = "ScripCode")]+ scrip_code: Option<String>,+ #[serde(rename = "LTP")]+ ltp: Option<f64>,+ #[serde(rename = "Volume")]+ volume: Option<i64>,+ #[serde(rename = "Open")]+ open: Option<f64>,+ #[serde(rename = "High")]+ high: Option<f64>,+ #[serde(rename = "Low")]+ low: Option<f64>,+ #[serde(rename = "Close")]+ close: Option<f64>,+}++#[derive(Debug, Clone)]+pub struct MotilalTick {+ pub exchange: String,+ pub scrip_code: String,+ pub ltp: f64,+ pub volume: i64,+ pub open: f64,+ pub high: f64,+ pub low: f64,+ pub close: f64,+}++// ============================================================================+// MOTILAL ADAPTER+// ============================================================================++pub struct MotilalAdapter {+ config: ProviderConfig,+ access_token: String,+ ws_stream: Arc<RwLock<Option<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,+ message_callback: Option<Box<dyn Fn(MarketMessage) + Send + Sync>>,+ subscriptions: Arc<RwLock<HashMap<String, MotilalMode>>>,+ is_connected: Arc<RwLock<bool>>,+}++impl MotilalAdapter {+ pub fn new(config: ProviderConfig) -> Self {+ let access_token = config.api_key.clone().unwrap_or_default();++ Self {+ config,+ access_token,+ ws_stream: Arc::new(RwLock::new(None)),+ message_callback: None,+ subscriptions: Arc::new(RwLock::new(HashMap::new())),+ is_connected: Arc::new(RwLock::new(false)),+ }+ }++ fn parse_tick(&self, data: &str) -> Option<MotilalTick> {+ let tick: TickResponse = serde_json::from_str(data).ok()?;++ Some(MotilalTick {+ exchange: tick.exchange.unwrap_or_default(),+ scrip_code: tick.scrip_code.unwrap_or_default(),+ ltp: tick.ltp.unwrap_or(0.0),+ volume: tick.volume.unwrap_or(0),+ open: tick.open.unwrap_or(0.0),+ high: tick.high.unwrap_or(0.0),+ low: tick.low.unwrap_or(0.0),+ close: tick.close.unwrap_or(0.0),+ })+ }+}++#[async_trait]+impl WebSocketAdapter for MotilalAdapter {+ async fn connect(&mut self) -> anyhow::Result<()> {+ tracing::info!("Connecting to Motilal Oswal WebSocket");++ let (ws_stream, _) = connect_async(MOTILAL_WS_URL).await?;+ tracing::info!("Connected to Motilal Oswal WebSocket");++ *self.ws_stream.write().await = Some(ws_stream);++ // Send authentication message+ let auth_msg = AuthMessage {+ message_type: "AUTH".to_string(),+ access_token: self.access_token.clone(),+ };++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(serde_json::to_string(&auth_msg)?)).await?;+ }++ *self.is_connected.write().await = true;++ let ws_stream = self.ws_stream.clone();+ let is_connected = self.is_connected.clone();++ tokio::spawn(async move {+ loop {+ let mut stream = ws_stream.write().await;+ if let Some(ref mut ws) = *stream {+ match ws.next().await {+ Some(Ok(Message::Text(text))) => {+ tracing::debug!("Received: {}", text);+ }+ Some(Ok(Message::Binary(data))) => {+ tracing::debug!("Received binary: {} bytes", data.len());+ }+ Some(Ok(Message::Ping(data))) => {+ let _ = ws.send(Message::Pong(data)).await;+ }+ Some(Err(e)) => {+ tracing::error!("WebSocket error: {}", e);+ *is_connected.write().await = false;+ break;+ }+ None => {+ *is_connected.write().await = false;+ break;+ }+ _ => {}+ }+ } else {+ break;+ }+ drop(stream);+ tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;+ }+ });++ Ok(())+ }++ async fn disconnect(&mut self) -> anyhow::Result<()> {+ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.close(None).await?;+ }+ *self.ws_stream.write().await = None;+ *self.is_connected.write().await = false;+ tracing::info!("Disconnected from Motilal Oswal WebSocket");+ Ok(())+ }++ async fn subscribe(+ &mut self,+ symbol: &str,+ channel: &str,+ _params: Option<Value>,+ ) -> anyhow::Result<()> {+ let mode = match channel {+ "depth" => MotilalMode::Depth,+ "quote" => MotilalMode::Quote,+ _ => MotilalMode::Ltp,+ };++ // Parse symbol: "NSE:12345"+ let parts: Vec<&str> = symbol.split(':').collect();+ if parts.len() != 2 {+ return Err(anyhow::anyhow!("Invalid symbol format. Expected 'Exchange:ScripCode'"));+ }++ let mode_str = match mode {+ MotilalMode::Ltp => "LTP",+ MotilalMode::Quote => "QUOTE",+ MotilalMode::Depth => "DEPTH",+ };++ let subscribe_msg = SubscribeMessage {+ message_type: "SUBSCRIBE".to_string(),+ exchange: parts[0].to_string(),+ scrip_code: parts[1].to_string(),+ mode: mode_str.to_string(),+ };++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(serde_json::to_string(&subscribe_msg)?)).await?;+ self.subscriptions.write().await.insert(symbol.to_string(), mode);+ tracing::info!("Subscribed to {}", symbol);+ }++ Ok(())+ }++ async fn unsubscribe(&mut self, symbol: &str, _channel: &str) -> anyhow::Result<()> {+ let parts: Vec<&str> = symbol.split(':').collect();+ if parts.len() != 2 {+ return Err(anyhow::anyhow!("Invalid symbol format"));+ }++ let unsubscribe_msg = serde_json::json!({+ "MessageType": "UNSUBSCRIBE",+ "Exchange": parts[0],+ "ScripCode": parts[1]+ });++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(unsubscribe_msg.to_string())).await?;+ self.subscriptions.write().await.remove(symbol);+ tracing::info!("Unsubscribed from {}", symbol);+ }++ Ok(())+ }++ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {+ self.message_callback = Some(callback);+ }++ fn provider_name(&self) -> &str {+ "motilal"+ }++ fn is_connected(&self) -> bool {+ self.is_connected.try_read().map(|g| *g).unwrap_or(false)+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/shoonya.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/shoonya.rsnew file mode 100644index 000000000..fb858d5bc--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/shoonya.rs@@ -0,0 +1,312 @@+// Shoonya (Finvasia) WebSocket Adapter+//+// Shoonya uses NorenOMS WebSocket for market data:+// - WebSocket URL: wss://api.shoonya.com/NorenWSTP/+// - Authentication via session token from login+// - JSON message format with touch line and depth subscriptions++use super::WebSocketAdapter;+use crate::websocket::types::*;+use async_trait::async_trait;+use futures_util::{SinkExt, StreamExt};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::collections::HashMap;+use std::sync::Arc;+use tokio::net::TcpStream;+use tokio::sync::RwLock;+use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream};++// ============================================================================+// SHOONYA CONFIGURATION+// ============================================================================++const SHOONYA_WS_URL: &str = "wss://api.shoonya.com/NorenWSTP/";++// ============================================================================+// SHOONYA STRUCTURES+// ============================================================================++#[derive(Debug, Clone, PartialEq)]+pub enum ShoonyaMode {+ TouchLine, // LTP + OHLC+ Depth, // Full market depth+}++#[derive(Debug, Serialize)]+struct ConnectRequest {+ t: String, // "c" for connect+ uid: String, // User ID+ actid: String, // Account ID+ susertoken: String, // Session token+ source: String, // "API"+}++#[derive(Debug, Serialize)]+struct TouchLineSubscribe {+ t: String, // "t" for touchline subscribe+ k: String, // Scrip tokens (e.g., "NSE|26000#NSE|26009")+}++#[derive(Debug, Serialize)]+struct DepthSubscribe {+ t: String, // "d" for depth subscribe+ k: String, // Scrip tokens+}++#[derive(Debug, Serialize)]+struct Unsubscribe {+ t: String, // "u" for unsubscribe+ k: String, // Scrip tokens+}++#[derive(Debug, Deserialize)]+struct TickResponse {+ t: Option<String>, // Message type+ e: Option<String>, // Exchange+ tk: Option<String>, // Token+ lp: Option<String>, // LTP+ pc: Option<String>, // Percent change+ v: Option<String>, // Volume+ o: Option<String>, // Open+ h: Option<String>, // High+ l: Option<String>, // Low+ c: Option<String>, // Close+ ap: Option<String>, // Average price+ oi: Option<String>, // Open interest+ bp1: Option<String>, // Best bid price 1+ bq1: Option<String>, // Best bid qty 1+ sp1: Option<String>, // Best ask price 1+ sq1: Option<String>, // Best ask qty 1+}++#[derive(Debug, Clone)]+pub struct ShoonyaTick {+ pub exchange: String,+ pub token: String,+ pub ltp: f64,+ pub change_percent: f64,+ pub volume: i64,+ pub open: f64,+ pub high: f64,+ pub low: f64,+ pub close: f64,+ pub avg_price: f64,+ pub oi: i64,+ pub bid_price: f64,+ pub bid_qty: i64,+ pub ask_price: f64,+ pub ask_qty: i64,+}++// ============================================================================+// SHOONYA ADAPTER+// ============================================================================++pub struct ShoonyaAdapter {+ config: ProviderConfig,+ user_id: String,+ session_token: String,+ ws_stream: Arc<RwLock<Option<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,+ message_callback: Option<Box<dyn Fn(MarketMessage) + Send + Sync>>,+ subscriptions: Arc<RwLock<HashMap<String, ShoonyaMode>>>,+ is_connected: Arc<RwLock<bool>>,+}++impl ShoonyaAdapter {+ pub fn new(config: ProviderConfig) -> Self {+ let user_id = config.client_id.clone().unwrap_or_default();+ let session_token = config.api_key.clone().unwrap_or_default();++ Self {+ config,+ user_id,+ session_token,+ ws_stream: Arc::new(RwLock::new(None)),+ message_callback: None,+ subscriptions: Arc::new(RwLock::new(HashMap::new())),+ is_connected: Arc::new(RwLock::new(false)),+ }+ }++ fn parse_tick(&self, data: &str) -> Option<ShoonyaTick> {+ let tick: TickResponse = serde_json::from_str(data).ok()?;++ // Skip non-tick messages (like connection acknowledgment)+ if tick.t.as_deref() != Some("tf") && tick.t.as_deref() != Some("tk") && tick.t.as_deref() != Some("dk") {+ return None;+ }++ Some(ShoonyaTick {+ exchange: tick.e.unwrap_or_default(),+ token: tick.tk.unwrap_or_default(),+ ltp: tick.lp.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ change_percent: tick.pc.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ volume: tick.v.and_then(|s| s.parse().ok()).unwrap_or(0),+ open: tick.o.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ high: tick.h.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ low: tick.l.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ close: tick.c.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ avg_price: tick.ap.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ oi: tick.oi.and_then(|s| s.parse().ok()).unwrap_or(0),+ bid_price: tick.bp1.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ bid_qty: tick.bq1.and_then(|s| s.parse().ok()).unwrap_or(0),+ ask_price: tick.sp1.and_then(|s| s.parse().ok()).unwrap_or(0.0),+ ask_qty: tick.sq1.and_then(|s| s.parse().ok()).unwrap_or(0),+ })+ }+}++#[async_trait]+impl WebSocketAdapter for ShoonyaAdapter {+ async fn connect(&mut self) -> anyhow::Result<()> {+ tracing::info!("Connecting to Shoonya WebSocket");++ let (ws_stream, _) = connect_async(SHOONYA_WS_URL).await?;+ tracing::info!("Connected to Shoonya WebSocket");++ *self.ws_stream.write().await = Some(ws_stream);++ // Send connect/auth message+ let connect_req = ConnectRequest {+ t: "c".to_string(),+ uid: self.user_id.clone(),+ actid: self.user_id.clone(),+ susertoken: self.session_token.clone(),+ source: "API".to_string(),+ };++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(serde_json::to_string(&connect_req)?)).await?;+ }++ *self.is_connected.write().await = true;++ let ws_stream = self.ws_stream.clone();+ let is_connected = self.is_connected.clone();++ tokio::spawn(async move {+ loop {+ let mut stream = ws_stream.write().await;+ if let Some(ref mut ws) = *stream {+ match ws.next().await {+ Some(Ok(Message::Text(text))) => {+ tracing::debug!("Received: {}", text);+ }+ Some(Ok(Message::Ping(data))) => {+ let _ = ws.send(Message::Pong(data)).await;+ }+ Some(Err(e)) => {+ tracing::error!("WebSocket error: {}", e);+ *is_connected.write().await = false;+ break;+ }+ None => {+ *is_connected.write().await = false;+ break;+ }+ _ => {}+ }+ } else {+ break;+ }+ drop(stream);+ tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;+ }+ });++ // Start heartbeat (send "h" every 30 seconds)+ let ws_stream_hb = self.ws_stream.clone();+ let is_connected_hb = self.is_connected.clone();+ tokio::spawn(async move {+ loop {+ tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;+ if !*is_connected_hb.read().await {+ break;+ }+ if let Some(ref mut ws) = *ws_stream_hb.write().await {+ let hb = serde_json::json!({"t": "h"});+ if let Err(e) = ws.send(Message::Text(hb.to_string())).await {+ tracing::error!("Failed to send heartbeat: {}", e);+ break;+ }+ }+ }+ });++ Ok(())+ }++ async fn disconnect(&mut self) -> anyhow::Result<()> {+ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.close(None).await?;+ }+ *self.ws_stream.write().await = None;+ *self.is_connected.write().await = false;+ tracing::info!("Disconnected from Shoonya WebSocket");+ Ok(())+ }++ async fn subscribe(+ &mut self,+ symbol: &str,+ channel: &str,+ _params: Option<Value>,+ ) -> anyhow::Result<()> {+ let mode = match channel {+ "depth" => ShoonyaMode::Depth,+ _ => ShoonyaMode::TouchLine,+ };++ // Symbol format: "NSE|26000" (Exchange|Token)+ let subscribe_msg = match mode {+ ShoonyaMode::TouchLine => {+ serde_json::to_string(&TouchLineSubscribe {+ t: "t".to_string(),+ k: symbol.to_string(),+ })?+ }+ ShoonyaMode::Depth => {+ serde_json::to_string(&DepthSubscribe {+ t: "d".to_string(),+ k: symbol.to_string(),+ })?+ }+ };++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(subscribe_msg)).await?;+ self.subscriptions.write().await.insert(symbol.to_string(), mode);+ tracing::info!("Subscribed to {}", symbol);+ }++ Ok(())+ }++ async fn unsubscribe(&mut self, symbol: &str, _channel: &str) -> anyhow::Result<()> {+ let unsubscribe_msg = serde_json::to_string(&Unsubscribe {+ t: "u".to_string(),+ k: symbol.to_string(),+ })?;++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(unsubscribe_msg)).await?;+ self.subscriptions.write().await.remove(symbol);+ tracing::info!("Unsubscribed from {}", symbol);+ }++ Ok(())+ }++ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {+ self.message_callback = Some(callback);+ }++ fn provider_name(&self) -> &str {+ "shoonya"+ }++ fn is_connected(&self) -> bool {+ self.is_connected.try_read().map(|g| *g).unwrap_or(false)+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/adapters/upstox.rs b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/upstox.rsnew file mode 100644index 000000000..426ca1005--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/websocket/adapters/upstox.rs@@ -0,0 +1,337 @@+// Upstox WebSocket Adapter (V3 API with Protobuf)+//+// Upstox uses protobuf-encoded market data over WebSocket:+// - Authorization: GET https://api.upstox.com/v3/feed/market-data-feed/authorize+// - Returns authorized_redirect_uri for WebSocket connection+// - Messages: Binary protobuf (FeedResponse)+// - Subscription: JSON message with instrument keys++use super::WebSocketAdapter;+use crate::websocket::types::*;+use async_trait::async_trait;+use futures_util::{SinkExt, StreamExt};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::collections::HashMap;+use std::sync::Arc;+use tokio::net::TcpStream;+use tokio::sync::RwLock;+use tokio_tungstenite::{connect_async, tungstenite::Message, MaybeTlsStream, WebSocketStream};+use uuid::Uuid;++// ============================================================================+// UPSTOX CONFIGURATION+// ============================================================================++const UPSTOX_AUTH_URL: &str = "https://api.upstox.com/v3/feed/market-data-feed/authorize";++// Subscription modes+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum UpstoxMode {+ Ltpc, // LTP + change+ Full, // Full market depth+}++// ============================================================================+// UPSTOX STRUCTURES+// ============================================================================++#[derive(Debug, Serialize)]+struct SubscriptionMessage {+ guid: String,+ method: String,+ data: SubscriptionData,+}++#[derive(Debug, Serialize)]+struct SubscriptionData {+ #[serde(rename = "instrumentKeys")]+ instrument_keys: Vec<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ mode: Option<String>,+}++#[derive(Debug, Deserialize)]+struct AuthResponse {+ data: Option<AuthData>,+}++#[derive(Debug, Deserialize)]+struct AuthData {+ authorized_redirect_uri: Option<String>,+}++// Simplified protobuf-like structure for tick data+// Note: In production, use proper protobuf parsing with prost+#[derive(Debug, Clone)]+pub struct UpstoxTick {+ pub instrument_key: String,+ pub ltp: f64,+ pub close: f64,+ pub change: f64,+ pub volume: i64,+ pub oi: i64,+ pub timestamp: u64,+}++// ============================================================================+// UPSTOX ADAPTER+// ============================================================================++pub struct UpstoxAdapter {+ config: ProviderConfig,+ access_token: String,+ ws_stream: Arc<RwLock<Option<WebSocketStream<MaybeTlsStream<TcpStream>>>>>,+ message_callback: Option<Box<dyn Fn(MarketMessage) + Send + Sync>>,+ subscriptions: Arc<RwLock<HashMap<String, UpstoxMode>>>,+ is_connected: Arc<RwLock<bool>>,+}++impl UpstoxAdapter {+ pub fn new(config: ProviderConfig) -> Self {+ let access_token = config.api_key.clone().unwrap_or_default();+ Self {+ config,+ access_token,+ ws_stream: Arc::new(RwLock::new(None)),+ message_callback: None,+ subscriptions: Arc::new(RwLock::new(HashMap::new())),+ is_connected: Arc::new(RwLock::new(false)),+ }+ }++ /// Get authorized WebSocket URL from Upstox API+ async fn get_websocket_url(&self) -> anyhow::Result<String> {+ let client = reqwest::Client::new();+ let response = client+ .get(UPSTOX_AUTH_URL)+ .header("Accept", "application/json")+ .header("Authorization", format!("Bearer {}", self.access_token))+ .send()+ .await?;++ if !response.status().is_success() {+ return Err(anyhow::anyhow!(+ "Failed to get WebSocket URL: {}",+ response.status()+ ));+ }++ let auth_response: AuthResponse = response.json().await?;+ auth_response+ .data+ .and_then(|d| d.authorized_redirect_uri)+ .ok_or_else(|| anyhow::anyhow!("No WebSocket URL in auth response"))+ }++ /// Parse protobuf market data+ /// Note: This is a simplified parser. In production, use prost with proper .proto files+ fn parse_protobuf_data(&self, data: &[u8]) -> Option<Vec<UpstoxTick>> {+ // Upstox uses protobuf FeedResponse format+ // For now, we'll do basic parsing - in production use prost+ if data.len() < 10 {+ return None;+ }++ // Simple protobuf field parsing+ // Field 1 (feeds) is a map of instrument_key -> FeedData+ let mut ticks = Vec::new();++ // This is a placeholder - actual implementation would use prost+ // to properly decode the FeedResponse protobuf message+ tracing::debug!("Received {} bytes of protobuf data", data.len());++ // For now, return empty - proper implementation needs protobuf definitions+ Some(ticks)+ }++ /// Create subscription message+ fn create_subscription_message(+ &self,+ instrument_keys: Vec<String>,+ mode: Option<UpstoxMode>,+ method: &str,+ ) -> String {+ let guid = Uuid::new_v4().to_string().replace("-", "")[..20].to_string();++ let message = SubscriptionMessage {+ guid,+ method: method.to_string(),+ data: SubscriptionData {+ instrument_keys,+ mode: mode.map(|m| match m {+ UpstoxMode::Ltpc => "ltpc".to_string(),+ UpstoxMode::Full => "full".to_string(),+ }),+ },+ };++ serde_json::to_string(&message).unwrap_or_default()+ }++ /// Convert tick to MarketMessage+ fn tick_to_message(&self, tick: UpstoxTick) -> MarketMessage {+ MarketMessage::Ticker(TickerData {+ provider: "upstox".to_string(),+ symbol: tick.instrument_key,+ price: tick.ltp,+ bid: None,+ ask: None,+ bid_size: None,+ ask_size: None,+ volume: Some(tick.volume as f64),+ high: None,+ low: None,+ open: None,+ close: Some(tick.close),+ change: Some(tick.change),+ change_percent: None,+ timestamp: tick.timestamp,+ })+ }++ /// Process incoming binary message+ async fn process_message(&self, data: &[u8]) {+ if let Some(ticks) = self.parse_protobuf_data(data) {+ for tick in ticks {+ let market_message = self.tick_to_message(tick);+ if let Some(ref callback) = self.message_callback {+ callback(market_message);+ }+ }+ }+ }+}++#[async_trait]+impl WebSocketAdapter for UpstoxAdapter {+ async fn connect(&mut self) -> anyhow::Result<()> {+ // Get authorized WebSocket URL+ let ws_url = self.get_websocket_url().await?;+ tracing::info!("Connecting to Upstox WebSocket: {}", ws_url);++ // Connect to WebSocket+ let (ws_stream, _) = connect_async(&ws_url).await?;+ tracing::info!("Connected to Upstox WebSocket");++ *self.ws_stream.write().await = Some(ws_stream);+ *self.is_connected.write().await = true;++ // Start message handler+ let ws_stream = self.ws_stream.clone();+ let is_connected = self.is_connected.clone();++ tokio::spawn(async move {+ loop {+ let mut stream = ws_stream.write().await;+ if let Some(ref mut ws) = *stream {+ match ws.next().await {+ Some(Ok(Message::Binary(data))) => {+ // Process binary protobuf message+ tracing::debug!("Received binary message: {} bytes", data.len());+ // Parse and emit via callback+ }+ Some(Ok(Message::Text(text))) => {+ // Process JSON message (subscription confirmations, errors)+ tracing::debug!("Received text message: {}", text);+ }+ Some(Ok(Message::Ping(data))) => {+ if let Err(e) = ws.send(Message::Pong(data)).await {+ tracing::error!("Failed to send pong: {}", e);+ }+ }+ Some(Err(e)) => {+ tracing::error!("WebSocket error: {}", e);+ *is_connected.write().await = false;+ break;+ }+ None => {+ tracing::info!("WebSocket closed");+ *is_connected.write().await = false;+ break;+ }+ _ => {}+ }+ } else {+ break;+ }+ drop(stream);+ tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;+ }+ });++ Ok(())+ }++ async fn disconnect(&mut self) -> anyhow::Result<()> {+ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.close(None).await?;+ }+ *self.ws_stream.write().await = None;+ *self.is_connected.write().await = false;+ tracing::info!("Disconnected from Upstox WebSocket");+ Ok(())+ }++ async fn subscribe(+ &mut self,+ symbol: &str,+ channel: &str,+ params: Option<Value>,+ ) -> anyhow::Result<()> {+ let mode = match channel {+ "full" | "depth" => UpstoxMode::Full,+ _ => UpstoxMode::Ltpc,+ };++ // Format instrument key (e.g., NSE_EQ|RELIANCE, NSE_FO|NIFTY23OCTFUT)+ let instrument_key = symbol.to_string();++ let message = self.create_subscription_message(+ vec![instrument_key.clone()],+ Some(mode.clone()),+ "sub",+ );++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(message)).await?;+ self.subscriptions+ .write()+ .await+ .insert(instrument_key, mode);+ tracing::info!("Subscribed to {} on channel {}", symbol, channel);+ }++ Ok(())+ }++ async fn unsubscribe(&mut self, symbol: &str, _channel: &str) -> anyhow::Result<()> {+ let instrument_key = symbol.to_string();+ let message = self.create_subscription_message(vec![instrument_key.clone()], None, "unsub");++ if let Some(ref mut ws) = *self.ws_stream.write().await {+ ws.send(Message::Text(message)).await?;+ self.subscriptions.write().await.remove(&instrument_key);+ tracing::info!("Unsubscribed from {}", symbol);+ }++ Ok(())+ }++ fn set_message_callback(&mut self, callback: Box<dyn Fn(MarketMessage) + Send + Sync>) {+ self.message_callback = Some(callback);+ }++ fn provider_name(&self) -> &str {+ "upstox"+ }++ fn is_connected(&self) -> bool {+ // Use try_read to avoid blocking+ self.is_connected+ .try_read()+ .map(|guard| *guard)+ .unwrap_or(false)+ }+}diff --git a/fincept-terminal-desktop/src-tauri/src/websocket/types.rs b/fincept-terminal-desktop/src-tauri/src/websocket/types.rsindex 56169ea56..2906ec335 100644--- a/fincept-terminal-desktop/src-tauri/src/websocket/types.rs+++ b/fincept-terminal-desktop/src-tauri/src/websocket/types.rs@@ -144,10 +144,12 @@ pub struct ProviderConfig {pub url: String,pub api_key: Option<String>,pub api_secret: Option<String>,+ pub client_id: Option<String>,pub enabled: bool,pub reconnect_delay_ms: u64,pub max_reconnect_attempts: u32,pub heartbeat_interval_ms: u64,+ pub extra: Option<HashMap<String, serde_json::Value>>,}impl Default for ProviderConfig {@@ -157,10 +159,12 @@ impl Default for ProviderConfig {url: String::new(),api_key: None,api_secret: None,+ client_id: None,enabled: true,reconnect_delay_ms: 5000,max_reconnect_attempts: 10,heartbeat_interval_ms: 30000,+ extra: None,}}}diff --git a/fincept-terminal-desktop/src/brokers/crypto/BaseExchangeAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/BaseExchangeAdapter.tsindex 21f85e86a..dab80df4e 100644--- a/fincept-terminal-desktop/src/brokers/crypto/BaseExchangeAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/crypto/BaseExchangeAdapter.ts@@ -1,777 +1,32 @@/*** Base Exchange Adapter*- * Abstract base class for all exchange adapters- * Provides common functionality and enforces consistent interface+ * Re-exports from modular adapter chain for backwards compatibility+ *+ * The adapter functionality has been split into modular files for better organization:+ * - CoreAdapter.ts: Connection, authentication, market data, account/balance+ * - TradingAdapter.ts: Order creation, modification, cancellation, queries+ * - DerivativesAdapter.ts: Options, margin, leverage, positions, mark prices, liquidations+ * - FundingAdapter.ts: Deposits, withdrawals, transfers+ * - AdvancedAdapter.ts: Crypto convert, sentiment analysis+ *+ * Inheritance Chain:+ * CoreExchangeAdapter → TradingAdapter → DerivativesAdapter → FundingAdapter → AdvancedAdapter*/-import ccxt, { Exchange, Market, Ticker, OrderBook, Trade, OHLCV, Balance, Order, Position } from 'ccxt';-import {- IExchangeAdapter,- ExchangeCredentials,- ExchangeConfig,- OrderType,- OrderSide,- OrderParams,- ExchangeCapabilities,- ExchangeError,- AuthenticationError,- RateLimitError,- ExchangeEvent,- ExchangeEventData,-} from './types';--export abstract class BaseExchangeAdapter implements IExchangeAdapter {- protected exchange: Exchange;- protected _isConnected: boolean = false;- protected _isAuthenticated: boolean = false;- protected eventListeners: Map<ExchangeEvent, Set<(data: ExchangeEventData) => void>> = new Map();-- public readonly id: string;- public readonly name: string;-- constructor(config: ExchangeConfig) {- this.id = config.exchange;-- // Initialize CCXT exchange- const ExchangeClass = ccxt[config.exchange as keyof typeof ccxt] as typeof Exchange;- if (!ExchangeClass) {- throw new Error(`Exchange "${config.exchange}" not supported by CCXT`);- }-- this.exchange = new ExchangeClass({- apiKey: config.credentials?.apiKey,- secret: config.credentials?.secret,- password: config.credentials?.password,- uid: config.credentials?.uid,- enableRateLimit: config.enableRateLimit ?? true,- timeout: config.timeout ?? 10000, // Reduced from 30s to 10s for faster failure detection- ...(config.sandbox && { sandbox: true }),- ...config.options,- });-- this.name = this.exchange.name as string;- }-- // ============================================================================- // CONNECTION MANAGEMENT- // ============================================================================-- async connect(): Promise<void> {- const maxRetries = 2;- const retryDelay = 2000; // 2 seconds- let lastError: any = null;-- for (let attempt = 0; attempt <= maxRetries; attempt++) {- try {-- // Reduce timeout for faster failure detection- const originalTimeout = this.exchange.timeout;- this.exchange.timeout = 10000; // 10 seconds instead of 30-- await this.exchange.loadMarkets();-- // Restore original timeout- this.exchange.timeout = originalTimeout;-- this._isConnected = true;- this.emit('connected', { exchange: this.id });- return;- } catch (error: any) {- lastError = error;-- // Check if it's a network/CORS error- const errorMessage = error?.message || String(error);- const isNetworkError =- errorMessage.includes('CORS') ||- errorMessage.includes('Network') ||- errorMessage.includes('fetch') ||- errorMessage.includes('timed out') ||- errorMessage.includes('Failed to fetch') ||- error?.name === 'TypeError';-- if (isNetworkError) {- console.warn(`[${this.id}] Network/CORS error on attempt ${attempt + 1}:`, errorMessage);- } else {- console.warn(`[${this.id}] Connection attempt ${attempt + 1} failed:`, error);- }-- // Don't retry on CORS errors - they won't resolve with retries- if (isNetworkError && errorMessage.includes('CORS')) {- console.error(`[${this.id}] [FAIL] CORS error detected - cannot connect from browser`);- this._isConnected = false;- break;- }-- if (attempt < maxRetries) {- await new Promise(resolve => setTimeout(resolve, retryDelay));- }- }- }-- // All retries failed- this._isConnected = false;- console.error(`[${this.id}] [FAIL] Failed to connect after ${maxRetries + 1} attempts`);-- // Create a user-friendly error message- const errorMessage = lastError?.message || String(lastError);- if (errorMessage.includes('CORS')) {- throw new Error(`Cannot connect to ${this.id} due to browser security (CORS). This exchange may not support browser-based connections.`);- } else if (errorMessage.includes('Network') || errorMessage.includes('fetch')) {- throw new Error(`Network error connecting to ${this.id}. Please check your internet connection or try again later.`);- } else {- throw this.handleError(lastError);- }- }-- async disconnect(): Promise<void> {- this._isConnected = false;- this._isAuthenticated = false;- this.emit('disconnected', { exchange: this.id });- }-- isConnected(): boolean {- return this._isConnected;- }-- // ============================================================================- // AUTHENTICATION- // ============================================================================-- async authenticate(credentials: ExchangeCredentials): Promise<void> {- try {- this.exchange.apiKey = credentials.apiKey;- this.exchange.secret = credentials.secret;- if (credentials.password) this.exchange.password = credentials.password;- if (credentials.uid) this.exchange.uid = credentials.uid;-- // Test authentication by fetching balance- await this.exchange.fetchBalance();- this._isAuthenticated = true;- this.emit('authenticated', { exchange: this.id });- } catch (error) {- this._isAuthenticated = false;- throw new AuthenticationError(- 'Authentication failed',- this.id,- error- );- }- }-- isAuthenticated(): boolean {- return this._isAuthenticated;- }-- // ============================================================================- // MARKET DATA- // ============================================================================-- async fetchMarkets(): Promise<Market[]> {- try {- await this.ensureConnected();- return await this.exchange.fetchMarkets();- } catch (error) {- throw this.handleError(error);- }- }-- async fetchStatus(): Promise<any> {- try {- await this.ensureConnected();- if (!this.exchange.has['fetchStatus']) {- return { status: 'ok', updated: Date.now() };- }- return await this.exchange.fetchStatus();- } catch (error) {- throw this.handleError(error);- }- }-- async fetchCurrencies(): Promise<any> {- try {- await this.ensureConnected();- if (!this.exchange.has['fetchCurrencies']) {- return {};- }- return await this.exchange.fetchCurrencies();- } catch (error) {- throw this.handleError(error);- }- }-- async fetchTime(): Promise<number> {- try {- await this.ensureConnected();- return await this.exchange.fetchTime() as number;- } catch (error) {- throw this.handleError(error);- }- }-- async fetchTicker(symbol: string): Promise<Ticker> {- try {- await this.ensureConnected();- return await this.exchange.fetchTicker(symbol);- } catch (error) {- throw this.handleError(error);- }- }-- async fetchTickers(symbols?: string[]): Promise<Record<string, Ticker>> {- try {- await this.ensureConnected();- return await this.exchange.fetchTickers(symbols);- } catch (error) {- throw this.handleError(error);- }- }-- async fetchOrderBook(symbol: string, limit?: number): Promise<OrderBook> {- try {- await this.ensureConnected();- return await this.exchange.fetchOrderBook(symbol, limit);- } catch (error) {- throw this.handleError(error);- }- }-- async fetchTrades(symbol: string, limit?: number): Promise<Trade[]> {- try {- await this.ensureConnected();- return await this.exchange.fetchTrades(symbol, undefined, limit);- } catch (error) {- throw this.handleError(error);- }- }-- async fetchOHLCV(- symbol: string,- timeframe: string = '1m',- limit?: number- ): Promise<OHLCV[]> {- try {- await this.ensureConnected();- return await this.exchange.fetchOHLCV(symbol, timeframe, undefined, limit);- } catch (error) {- throw this.handleError(error);- }- }-- // ============================================================================- // ACCOUNT & BALANCE- // ============================================================================-- async fetchBalance(): Promise<Balance> {- try {- await this.ensureAuthenticated();- return await this.exchange.fetchBalance() as unknown as Balance;- } catch (error) {- throw this.handleError(error);- }- }-- async fetchLedger(code?: string, since?: number, limit?: number): Promise<any> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['fetchLedger']) {- throw new Error('fetchLedger not supported by this exchange');- }- return await this.exchange.fetchLedger(code, since, limit);- } catch (error) {- throw this.handleError(error);- }- }-- async fetchTradingFee(symbol: string): Promise<any> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['fetchTradingFee']) {- const fees = await this.exchange.fetchTradingFees();- return fees[symbol] || null;- }- return await this.exchange.fetchTradingFee(symbol);- } catch (error) {- throw this.handleError(error);- }- }-- async fetchPositions(symbols?: string[]): Promise<Position[]> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['fetchPositions']) {- return [];- }- return await this.exchange.fetchPositions(symbols);- } catch (error) {- throw this.handleError(error);- }- }-- // ============================================================================- // TRADING- // ============================================================================-- async createOrder(- symbol: string,- type: OrderType,- side: OrderSide,- amount: number,- price?: number,- params?: OrderParams- ): Promise<Order> {- try {- await this.ensureAuthenticated();- return await this.exchange.createOrder(symbol, type, side, amount, price, params);- } catch (error) {- throw this.handleError(error);- }- }-- async createOrders(orders: Array<{- symbol: string;- type: OrderType;- side: OrderSide;- amount: number;- price?: number;- params?: OrderParams;- }>): Promise<Order[]> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['createOrders']) {- // Fallback: create orders one by one- const results: Order[] = [];- for (const order of orders) {- const result = await this.createOrder(- order.symbol,- order.type,- order.side,- order.amount,- order.price,- order.params- );- results.push(result);- }- return results;- }- return await this.exchange.createOrders(orders);- } catch (error) {- throw this.handleError(error);- }- }-- async createMarketOrderWithCost(- symbol: string,- side: OrderSide,- cost: number,- params?: OrderParams- ): Promise<Order> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['createMarketOrderWithCost']) {- throw new Error('createMarketOrderWithCost not supported');- }- return await (this.exchange as any).createMarketOrderWithCost(symbol, side, cost, params);- } catch (error) {- throw this.handleError(error);- }- }-- async createMarketBuyOrderWithCost(- symbol: string,- cost: number,- params?: OrderParams- ): Promise<Order> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['createMarketBuyOrderWithCost']) {- return await this.createMarketOrderWithCost(symbol, 'buy', cost, params);- }- return await (this.exchange as any).createMarketBuyOrderWithCost(symbol, cost, params);- } catch (error) {- throw this.handleError(error);- }- }-- async editOrder(- orderId: string,- symbol: string,- type?: OrderType,- side?: OrderSide,- amount?: number,- price?: number,- params?: OrderParams- ): Promise<Order> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['editOrder']) {- throw new Error('editOrder not supported by this exchange');- }- return await this.exchange.editOrder(orderId, symbol, type as any, side as any, amount, price, params);- } catch (error) {- throw this.handleError(error);- }- }+import { AdvancedAdapter } from './base/AdvancedAdapter';- async cancelOrder(orderId: string, symbol: string): Promise<Order> {- try {- await this.ensureAuthenticated();- return await this.exchange.cancelOrder(orderId, symbol);- } catch (error) {- throw this.handleError(error);- }- }-- async cancelOrders(orderIds: string[], symbol?: string): Promise<Order[]> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['cancelOrders']) {- // Fallback: cancel orders one by one- const results: Order[] = [];- for (const orderId of orderIds) {- if (!symbol) throw new Error('Symbol required for bulk cancel fallback');- const result = await this.cancelOrder(orderId, symbol);- results.push(result);- }- return results;- }- return await this.exchange.cancelOrders(orderIds, symbol);- } catch (error) {- throw this.handleError(error);- }- }-- async cancelAllOrders(symbol?: string): Promise<Order[]> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['cancelAllOrders']) {- throw new Error('Exchange does not support cancelAllOrders');- }- return await this.exchange.cancelAllOrders(symbol);- } catch (error) {- throw this.handleError(error);- }- }-- async cancelAllOrdersAfter(timeout: number): Promise<any> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['cancelAllOrdersAfter']) {- throw new Error('cancelAllOrdersAfter not supported by this exchange');- }- return await (this.exchange as any).cancelAllOrdersAfter(timeout);- } catch (error) {- throw this.handleError(error);- }- }-- async fetchOrder(orderId: string, symbol: string): Promise<Order> {- try {- await this.ensureAuthenticated();- return await this.exchange.fetchOrder(orderId, symbol);- } catch (error) {- throw this.handleError(error);- }- }-- async fetchOrdersByIds(orderIds: string[], symbol?: string): Promise<Order[]> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['fetchOrdersByIds']) {- // Fallback: fetch orders one by one- const results: Order[] = [];- for (const orderId of orderIds) {- if (!symbol) throw new Error('Symbol required for fetchOrdersByIds fallback');- const order = await this.fetchOrder(orderId, symbol);- results.push(order);- }- return results;- }- return await (this.exchange as any).fetchOrdersByIds(orderIds, symbol);- } catch (error) {- throw this.handleError(error);- }- }-- async fetchOrderTrades(orderId: string, symbol: string): Promise<Trade[]> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['fetchOrderTrades']) {- throw new Error('fetchOrderTrades not supported by this exchange');- }- return await this.exchange.fetchOrderTrades(orderId, symbol);- } catch (error) {- throw this.handleError(error);- }- }-- async fetchMyTrades(symbol?: string, since?: number, limit?: number): Promise<Trade[]> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['fetchMyTrades']) {- throw new Error('fetchMyTrades not supported by this exchange');- }- return await this.exchange.fetchMyTrades(symbol, since, limit);- } catch (error) {- throw this.handleError(error);- }- }-- async fetchOpenOrders(symbol?: string): Promise<Order[]> {- try {- await this.ensureAuthenticated();- return await this.exchange.fetchOpenOrders(symbol);- } catch (error) {- throw this.handleError(error);- }- }-- async fetchClosedOrders(symbol?: string, limit?: number): Promise<Order[]> {- try {- await this.ensureAuthenticated();- return await this.exchange.fetchClosedOrders(symbol, undefined, limit);- } catch (error) {- throw this.handleError(error);- }- }-- // ============================================================================- // DEPOSITS & WITHDRAWALS- // ============================================================================-- async fetchDeposits(code?: string, since?: number, limit?: number): Promise<any> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['fetchDeposits']) {- throw new Error('fetchDeposits not supported by this exchange');- }- return await this.exchange.fetchDeposits(code, since, limit);- } catch (error) {- throw this.handleError(error);- }- }-- async fetchWithdrawals(code?: string, since?: number, limit?: number): Promise<any> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['fetchWithdrawals']) {- throw new Error('fetchWithdrawals not supported by this exchange');- }- return await this.exchange.fetchWithdrawals(code, since, limit);- } catch (error) {- throw this.handleError(error);- }- }-- async fetchDepositAddress(code: string, params?: any): Promise<any> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['fetchDepositAddress']) {- throw new Error('fetchDepositAddress not supported by this exchange');- }- return await this.exchange.fetchDepositAddress(code, params);- } catch (error) {- throw this.handleError(error);- }- }-- async createDepositAddress(code: string, params?: any): Promise<any> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['createDepositAddress']) {- throw new Error('createDepositAddress not supported by this exchange');- }- return await this.exchange.createDepositAddress(code, params);- } catch (error) {- throw this.handleError(error);- }- }-- async fetchDepositMethods(code?: string): Promise<any> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['fetchDepositMethods']) {- throw new Error('fetchDepositMethods not supported by this exchange');- }- return await (this.exchange as any).fetchDepositMethods(code);- } catch (error) {- throw this.handleError(error);- }- }-- async withdraw(code: string, amount: number, address: string, tag?: string, params?: any): Promise<any> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['withdraw']) {- throw new Error('withdraw not supported by this exchange');- }- return await this.exchange.withdraw(code, amount, address, tag, params);- } catch (error) {- throw this.handleError(error);- }- }-- // ============================================================================- // TRANSFERS- // ============================================================================-- async transfer(code: string, amount: number, fromAccount: string, toAccount: string, params?: any): Promise<any> {- try {- await this.ensureAuthenticated();- if (!this.exchange.has['transfer']) {- throw new Error('transfer not supported by this exchange');- }- return await this.exchange.transfer(code, amount, fromAccount, toAccount, params);- } catch (error) {- throw this.handleError(error);- }- }-- async transferOut(code: string, amount: number, params?: any): Promise<any> {- try {- await this.ensureAuthenticated();- // transferOut is typically just a transfer to an external account- if (!this.exchange.has['transfer']) {- throw new Error('transferOut not supported by this exchange');- }- return await this.exchange.transfer(code, amount, 'spot', 'external', params);- } catch (error) {- throw this.handleError(error);- }- }-- // ============================================================================- // EXCHANGE INFORMATION- // ============================================================================-- getCapabilities(): ExchangeCapabilities {- const has = this.exchange.has;- return {- spot: !!has['spot'],- margin: !!has['margin'],- futures: !!has['future'],- options: !!has['option'],- swap: !!has['swap'],-- supportedOrderTypes: this.getSupportedOrderTypes(),- supportedTimeInForce: ['GTC', 'IOC', 'FOK', 'PO'],-- leverageTrading: !!has['setLeverage'],- stopOrders: !!has['createStopOrder'],- conditionalOrders: !!has['createOrder'],- algoOrders: false,-- realtimeData: !!has['watchTicker'],- historicalData: !!has['fetchOHLCV'],- websocketSupport: !!has['watchTicker'],-- multiAccount: false,- subAccounts: false,- portfolioMargin: false,-- restApi: true,- websocketApi: !!has['watchTicker'],- fixApi: false,-- rateLimits: {- public: 1000,- private: 3000,- trading: 1000,- },- };- }-- protected getSupportedOrderTypes(): OrderType[] {- const types: OrderType[] = ['market', 'limit'];- if (this.exchange.has['createStopOrder']) types.push('stop', 'stop_limit');- if (this.exchange.has['createTrailingAmountOrder']) types.push('trailing_stop');- return types;- }-- getMarkets(): Record<string, Market> {- return this.exchange.markets;- }-- // ============================================================================- // EVENT SYSTEM- // ============================================================================-- on(event: ExchangeEvent, callback: (data: ExchangeEventData) => void): void {- if (!this.eventListeners.has(event)) {- this.eventListeners.set(event, new Set());- }- this.eventListeners.get(event)!.add(callback);- }-- off(event: ExchangeEvent, callback: (data: ExchangeEventData) => void): void {- this.eventListeners.get(event)?.delete(callback);- }-- public emit(event: ExchangeEvent, data: any): void {- const eventData: ExchangeEventData = {- event,- exchange: this.id,- timestamp: Date.now(),- data,- };-- this.eventListeners.get(event)?.forEach(callback => {- try {- callback(eventData);- } catch (error) {- console.error(`Error in event listener for ${event}:`, error);- }- });- }-- // ============================================================================- // ERROR HANDLING- // ============================================================================-- protected handleError(error: any): ExchangeError {- if (error instanceof ExchangeError) {- return error;- }-- const message = error.message || 'Unknown error';-- if (message.includes('rate limit')) {- return new RateLimitError(message, this.id, error);- }-- if (message.includes('authentication') || message.includes('Invalid API')) {- return new AuthenticationError(message, this.id, error);- }-- return new ExchangeError(message, 'UNKNOWN', this.id, error);- }-- protected async ensureConnected(): Promise<void> {- if (!this._isConnected) {- await this.connect();- }- }-- protected async ensureAuthenticated(): Promise<void> {- await this.ensureConnected();- if (!this._isAuthenticated && (this.exchange.apiKey && this.exchange.secret)) {- throw new AuthenticationError('Not authenticated', this.id);- }- }-- // ============================================================================- // UTILITIES- // ============================================================================-- protected parseSymbol(symbol: string): { base: string; quote: string } {- const parts = symbol.split('/');- if (parts.length !== 2) {- throw new Error(`Invalid symbol format: ${symbol}`);- }- return { base: parts[0], quote: parts[1] };- }-- protected formatSymbol(base: string, quote: string): string {- return `${base}/${quote}`;- }-}+/**+ * BaseExchangeAdapter - Complete adapter with all functionality+ * Extends from AdvancedAdapter which contains the full inheritance chain+ */+export abstract class BaseExchangeAdapter extends AdvancedAdapter {}++// Re-export individual adapters for selective use+export {+ CoreExchangeAdapter,+ TradingAdapter,+ DerivativesAdapter,+ FundingAdapter,+ AdvancedAdapter,+} from './base';diff --git a/fincept-terminal-desktop/src/brokers/crypto/base/AdvancedAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/base/AdvancedAdapter.tsnew file mode 100644index 000000000..9d9e4c278--- /dev/null+++ b/fincept-terminal-desktop/src/brokers/crypto/base/AdvancedAdapter.ts@@ -0,0 +1,81 @@+/**+ * Advanced Adapter+ *+ * Crypto convert, sentiment, and other advanced trading methods+ * Extends FundingAdapter - this is the final adapter in the chain+ *+ * Implements IExchangeAdapter interface (all required methods inherited from chain)+ */++import { FundingAdapter } from './FundingAdapter';+import { IExchangeAdapter } from '../types';++export abstract class AdvancedAdapter extends FundingAdapter implements IExchangeAdapter {+ // ============================================================================+ // CRYPTO CONVERT (SWAP)+ // ============================================================================++ async fetchConvertCurrencies(params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchConvertCurrencies']) {+ throw new Error('fetchConvertCurrencies not supported by this exchange');+ }+ return await (this.exchange as any).fetchConvertCurrencies(params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchConvertQuote(fromCurrency: string, toCurrency: string, amount: number, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchConvertQuote']) {+ throw new Error('fetchConvertQuote not supported by this exchange');+ }+ return await (this.exchange as any).fetchConvertQuote(fromCurrency, toCurrency, amount, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async createConvertTrade(fromCurrency: string, toCurrency: string, amount: number, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['createConvertTrade']) {+ throw new Error('createConvertTrade not supported by this exchange');+ }+ return await (this.exchange as any).createConvertTrade(fromCurrency, toCurrency, amount, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchConvertTradeHistory(code?: string, since?: number, limit?: number, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchConvertTradeHistory']) {+ throw new Error('fetchConvertTradeHistory not supported by this exchange');+ }+ return await (this.exchange as any).fetchConvertTradeHistory(code, since, limit, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // MARKET SENTIMENT+ // ============================================================================++ async fetchLongShortRatioHistory(symbol: string, timeframe?: string, since?: number, limit?: number, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchLongShortRatioHistory']) {+ throw new Error('fetchLongShortRatioHistory not supported by this exchange');+ }+ return await (this.exchange as any).fetchLongShortRatioHistory(symbol, timeframe, since, limit, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }+}diff --git a/fincept-terminal-desktop/src/brokers/crypto/base/CoreAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/base/CoreAdapter.tsnew file mode 100644index 000000000..d5a5c3058--- /dev/null+++ b/fincept-terminal-desktop/src/brokers/crypto/base/CoreAdapter.ts@@ -0,0 +1,389 @@+/**+ * Core Exchange Adapter+ *+ * Base class with connection, authentication, and core market data methods+ * Extended by feature-specific adapters+ */++import ccxt, { Exchange, Market, Ticker, OrderBook, Trade, OHLCV, Balance, Order, Position } from 'ccxt';+import {+ ExchangeCredentials,+ ExchangeConfig,+ OrderType,+ ExchangeCapabilities,+ ExchangeError,+ AuthenticationError,+ RateLimitError,+ ExchangeEvent,+ ExchangeEventData,+} from '../types';++export abstract class CoreExchangeAdapter {+ protected exchange: Exchange;+ protected _isConnected: boolean = false;+ protected _isAuthenticated: boolean = false;+ protected eventListeners: Map<ExchangeEvent, Set<(data: ExchangeEventData) => void>> = new Map();++ public readonly id: string;+ public readonly name: string;++ constructor(config: ExchangeConfig) {+ this.id = config.exchange;++ const ExchangeClass = ccxt[config.exchange as keyof typeof ccxt] as typeof Exchange;+ if (!ExchangeClass) {+ throw new Error(`Exchange "${config.exchange}" not supported by CCXT`);+ }++ this.exchange = new ExchangeClass({+ apiKey: config.credentials?.apiKey,+ secret: config.credentials?.secret,+ password: config.credentials?.password,+ uid: config.credentials?.uid,+ enableRateLimit: config.enableRateLimit ?? true,+ timeout: config.timeout ?? 10000,+ ...(config.sandbox && { sandbox: true }),+ ...config.options,+ });++ this.name = this.exchange.name as string;+ }++ // ============================================================================+ // CONNECTION MANAGEMENT+ // ============================================================================++ async connect(): Promise<void> {+ const maxRetries = 2;+ const retryDelay = 2000;+ let lastError: any = null;++ for (let attempt = 0; attempt <= maxRetries; attempt++) {+ try {+ const originalTimeout = this.exchange.timeout;+ this.exchange.timeout = 10000;+ await this.exchange.loadMarkets();+ this.exchange.timeout = originalTimeout;+ this._isConnected = true;+ this.emit('connected', { exchange: this.id });+ return;+ } catch (error: any) {+ lastError = error;+ const errorMessage = error?.message || String(error);+ const isNetworkError =+ errorMessage.includes('CORS') ||+ errorMessage.includes('Network') ||+ errorMessage.includes('fetch') ||+ errorMessage.includes('timed out') ||+ errorMessage.includes('Failed to fetch') ||+ error?.name === 'TypeError';++ if (isNetworkError && errorMessage.includes('CORS')) {+ console.error(`[${this.id}] [FAIL] CORS error detected`);+ this._isConnected = false;+ break;+ }++ if (attempt < maxRetries) {+ await new Promise(resolve => setTimeout(resolve, retryDelay));+ }+ }+ }++ this._isConnected = false;+ const errorMessage = lastError?.message || String(lastError);+ if (errorMessage.includes('CORS')) {+ throw new Error(`Cannot connect to ${this.id} due to browser security (CORS).`);+ } else if (errorMessage.includes('Network') || errorMessage.includes('fetch')) {+ throw new Error(`Network error connecting to ${this.id}.`);+ } else {+ throw this.handleError(lastError);+ }+ }++ async disconnect(): Promise<void> {+ this._isConnected = false;+ this._isAuthenticated = false;+ this.emit('disconnected', { exchange: this.id });+ }++ isConnected(): boolean {+ return this._isConnected;+ }++ // ============================================================================+ // AUTHENTICATION+ // ============================================================================++ async authenticate(credentials: ExchangeCredentials): Promise<void> {+ try {+ this.exchange.apiKey = credentials.apiKey;+ this.exchange.secret = credentials.secret;+ if (credentials.password) this.exchange.password = credentials.password;+ if (credentials.uid) this.exchange.uid = credentials.uid;+ await this.exchange.fetchBalance();+ this._isAuthenticated = true;+ this.emit('authenticated', { exchange: this.id });+ } catch (error) {+ this._isAuthenticated = false;+ throw new AuthenticationError('Authentication failed', this.id, error);+ }+ }++ isAuthenticated(): boolean {+ return this._isAuthenticated;+ }++ // ============================================================================+ // MARKET DATA+ // ============================================================================++ async fetchMarkets(): Promise<Market[]> {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchMarkets();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchStatus(): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchStatus']) {+ return { status: 'ok', updated: Date.now() };+ }+ return await this.exchange.fetchStatus();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchCurrencies(): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchCurrencies']) {+ return {};+ }+ return await this.exchange.fetchCurrencies();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchTime(): Promise<number> {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchTime() as number;+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchTicker(symbol: string): Promise<Ticker> {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchTicker(symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchTickers(symbols?: string[]): Promise<Record<string, Ticker>> {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchTickers(symbols);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchOrderBook(symbol: string, limit?: number): Promise<OrderBook> {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchOrderBook(symbol, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchTrades(symbol: string, limit?: number): Promise<Trade[]> {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchTrades(symbol, undefined, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchOHLCV(symbol: string, timeframe: string = '1m', limit?: number): Promise<OHLCV[]> {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchOHLCV(symbol, timeframe, undefined, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // ACCOUNT & BALANCE+ // ============================================================================++ async fetchBalance(): Promise<Balance> {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchBalance() as unknown as Balance;+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchLedger(code?: string, since?: number, limit?: number): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchLedger']) {+ throw new Error('fetchLedger not supported by this exchange');+ }+ return await this.exchange.fetchLedger(code, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchTradingFee(symbol: string): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchTradingFee']) {+ const fees = await this.exchange.fetchTradingFees();+ return fees[symbol] || null;+ }+ return await this.exchange.fetchTradingFee(symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchPositions(symbols?: string[]): Promise<Position[]> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchPositions']) {+ return [];+ }+ return await this.exchange.fetchPositions(symbols);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // EXCHANGE INFORMATION+ // ============================================================================++ getCapabilities(): ExchangeCapabilities {+ const has = this.exchange.has;+ return {+ spot: !!has['spot'],+ margin: !!has['margin'],+ futures: !!has['future'],+ options: !!has['option'],+ swap: !!has['swap'],+ supportedOrderTypes: this.getSupportedOrderTypes(),+ supportedTimeInForce: ['GTC', 'IOC', 'FOK', 'PO'],+ leverageTrading: !!has['setLeverage'],+ stopOrders: !!has['createStopOrder'],+ conditionalOrders: !!has['createOrder'],+ algoOrders: false,+ realtimeData: !!has['watchTicker'],+ historicalData: !!has['fetchOHLCV'],+ websocketSupport: !!has['watchTicker'],+ multiAccount: false,+ subAccounts: false,+ portfolioMargin: false,+ restApi: true,+ websocketApi: !!has['watchTicker'],+ fixApi: false,+ rateLimits: { public: 1000, private: 3000, trading: 1000 },+ };+ }++ protected getSupportedOrderTypes(): OrderType[] {+ const types: OrderType[] = ['market', 'limit'];+ if (this.exchange.has['createStopOrder']) types.push('stop', 'stop_limit');+ if (this.exchange.has['createTrailingAmountOrder']) types.push('trailing_stop');+ return types;+ }++ getMarkets(): Record<string, Market> {+ return this.exchange.markets;+ }++ // ============================================================================+ // EVENT SYSTEM+ // ============================================================================++ on(event: ExchangeEvent, callback: (data: ExchangeEventData) => void): void {+ if (!this.eventListeners.has(event)) {+ this.eventListeners.set(event, new Set());+ }+ this.eventListeners.get(event)!.add(callback);+ }++ off(event: ExchangeEvent, callback: (data: ExchangeEventData) => void): void {+ this.eventListeners.get(event)?.delete(callback);+ }++ public emit(event: ExchangeEvent, data: any): void {+ const eventData: ExchangeEventData = {+ event,+ exchange: this.id,+ timestamp: Date.now(),+ data,+ };+ this.eventListeners.get(event)?.forEach(callback => {+ try {+ callback(eventData);+ } catch (error) {+ console.error(`Error in event listener for ${event}:`, error);+ }+ });+ }++ // ============================================================================+ // ERROR HANDLING+ // ============================================================================++ protected handleError(error: any): ExchangeError {+ if (error instanceof ExchangeError) return error;+ const message = error.message || 'Unknown error';+ if (message.includes('rate limit')) return new RateLimitError(message, this.id, error);+ if (message.includes('authentication') || message.includes('Invalid API')) {+ return new AuthenticationError(message, this.id, error);+ }+ return new ExchangeError(message, 'UNKNOWN', this.id, error);+ }++ protected async ensureConnected(): Promise<void> {+ if (!this._isConnected) await this.connect();+ }++ protected async ensureAuthenticated(): Promise<void> {+ await this.ensureConnected();+ if (!this._isAuthenticated && (this.exchange.apiKey && this.exchange.secret)) {+ throw new AuthenticationError('Not authenticated', this.id);+ }+ }++ // ============================================================================+ // UTILITIES+ // ============================================================================++ protected parseSymbol(symbol: string): { base: string; quote: string } {+ const parts = symbol.split('/');+ if (parts.length !== 2) throw new Error(`Invalid symbol format: ${symbol}`);+ return { base: parts[0], quote: parts[1] };+ }++ protected formatSymbol(base: string, quote: string): string {+ return `${base}/${quote}`;+ }+}diff --git a/fincept-terminal-desktop/src/brokers/crypto/base/DerivativesAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/base/DerivativesAdapter.tsnew file mode 100644index 000000000..6346c8498--- /dev/null+++ b/fincept-terminal-desktop/src/brokers/crypto/base/DerivativesAdapter.ts@@ -0,0 +1,510 @@+/**+ * Derivatives Adapter+ *+ * Futures, options, leverage, and position management methods+ * Extends TradingAdapter with derivatives functionality+ */++import { TradingAdapter } from './TradingAdapter';++export abstract class DerivativesAdapter extends TradingAdapter {+ // ============================================================================+ // OPTIONS TRADING+ // ============================================================================++ async fetchGreeks(symbol: string, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchGreeks']) {+ throw new Error('fetchGreeks not supported by this exchange');+ }+ return await (this.exchange as any).fetchGreeks(symbol, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchOption(symbol: string, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchOption']) {+ throw new Error('fetchOption not supported by this exchange');+ }+ return await (this.exchange as any).fetchOption(symbol, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchOptionChain(underlyingSymbol: string, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchOptionChain']) {+ const markets = await this.fetchMarkets();+ return markets.filter((m: any) =>+ m.option && m.base === underlyingSymbol.split('/')[0]+ );+ }+ return await (this.exchange as any).fetchOptionChain(underlyingSymbol, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchVolatilityHistory(symbol: string, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchVolatilityHistory']) {+ throw new Error('fetchVolatilityHistory not supported by this exchange');+ }+ return await (this.exchange as any).fetchVolatilityHistory(symbol, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // MARGIN & BORROW RATES+ // ============================================================================++ async fetchBorrowRate(code: string, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['fetchCrossBorrowRate']) {+ return await (this.exchange as any).fetchCrossBorrowRate(code, params);+ }+ if (this.exchange.has['fetchBorrowRate']) {+ return await (this.exchange as any).fetchBorrowRate(code, params);+ }+ throw new Error('fetchBorrowRate not supported by this exchange');+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchBorrowRates(params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['fetchCrossBorrowRates']) {+ return await (this.exchange as any).fetchCrossBorrowRates(params);+ }+ if (this.exchange.has['fetchBorrowRates']) {+ return await (this.exchange as any).fetchBorrowRates(params);+ }+ throw new Error('fetchBorrowRates not supported by this exchange');+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchBorrowInterest(code?: string, symbol?: string, since?: number, limit?: number, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchBorrowInterest']) {+ throw new Error('fetchBorrowInterest not supported by this exchange');+ }+ return await (this.exchange as any).fetchBorrowInterest(code, symbol, since, limit, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchCrossBorrowRate(code: string, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchCrossBorrowRate']) {+ return await this.fetchBorrowRate(code, params);+ }+ return await (this.exchange as any).fetchCrossBorrowRate(code, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchIsolatedBorrowRate(symbol: string, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchIsolatedBorrowRate']) {+ throw new Error('fetchIsolatedBorrowRate not supported by this exchange');+ }+ return await (this.exchange as any).fetchIsolatedBorrowRate(symbol, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchBorrowRateHistory(code: string, since?: number, limit?: number, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchBorrowRateHistory']) {+ throw new Error('fetchBorrowRateHistory not supported by this exchange');+ }+ return await (this.exchange as any).fetchBorrowRateHistory(code, since, limit, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // LEVERAGE INFO+ // ============================================================================++ async fetchLeverage(symbol: string, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['fetchLeverage']) {+ return await (this.exchange as any).fetchLeverage(symbol, params);+ }+ const positions = await this.fetchPositions([symbol]);+ if (positions.length > 0) {+ return { symbol, leverage: positions[0].leverage };+ }+ throw new Error('fetchLeverage not supported by this exchange');+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchLeverages(symbols?: string[], params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['fetchLeverages']) {+ return await (this.exchange as any).fetchLeverages(symbols, params);+ }+ if (symbols) {+ const results: Record<string, any> = {};+ for (const symbol of symbols) {+ try {+ results[symbol] = await this.fetchLeverage(symbol, params);+ } catch {+ results[symbol] = null;+ }+ }+ return results;+ }+ throw new Error('fetchLeverages not supported by this exchange');+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchLeverageTiers(symbols?: string[], params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchLeverageTiers']) {+ throw new Error('fetchLeverageTiers not supported by this exchange');+ }+ return await (this.exchange as any).fetchLeverageTiers(symbols, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchMarketLeverageTiers(symbol: string, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (this.exchange.has['fetchMarketLeverageTiers']) {+ return await (this.exchange as any).fetchMarketLeverageTiers(symbol, params);+ }+ const tiers = await this.fetchLeverageTiers([symbol], params);+ return tiers[symbol] || null;+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // POSITION MANAGEMENT+ // ============================================================================++ async fetchPosition(symbol: string, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['fetchPosition']) {+ return await (this.exchange as any).fetchPosition(symbol, params);+ }+ const positions = await this.fetchPositions([symbol]);+ return positions.find((p: any) => p.symbol === symbol) || null;+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchPositionMode(symbol?: string, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchPositionMode']) {+ throw new Error('fetchPositionMode not supported by this exchange');+ }+ return await (this.exchange as any).fetchPositionMode(symbol, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchPositionHistory(symbol?: string, since?: number, limit?: number, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['fetchPositionHistory']) {+ return await (this.exchange as any).fetchPositionHistory(symbol, since, limit, params);+ }+ if (this.exchange.has['fetchPositionsHistory']) {+ return await (this.exchange as any).fetchPositionsHistory([symbol], since, limit, params);+ }+ throw new Error('fetchPositionHistory not supported by this exchange');+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async closePosition(symbol: string, side?: 'long' | 'short', params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['closePosition']) {+ return await (this.exchange as any).closePosition(symbol, side, params);+ }+ const position = await this.fetchPosition(symbol);+ if (!position || position.contracts === 0) {+ return { info: 'No position to close' };+ }+ const closeSide = position.side === 'long' ? 'sell' : 'buy';+ const amount = Math.abs(position.contracts || position.contractSize || 0);+ return await this.createOrder(symbol, 'market', closeSide as any, amount, undefined, {+ reduceOnly: true,+ ...params+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async closeAllPositions(params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['closeAllPositions']) {+ return await (this.exchange as any).closeAllPositions(params);+ }+ const positions = await this.fetchPositions();+ const results = [];+ for (const position of positions) {+ if (position.contracts && position.contracts !== 0) {+ const result = await this.closePosition(position.symbol);+ results.push(result);+ }+ }+ return results;+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // FUNDING RATES+ // ============================================================================++ async fetchFundingRate(symbol: string, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchFundingRate']) {+ throw new Error('fetchFundingRate not supported by this exchange');+ }+ return await this.exchange.fetchFundingRate(symbol, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchFundingRates(symbols?: string[], params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (this.exchange.has['fetchFundingRates']) {+ return await (this.exchange as any).fetchFundingRates(symbols, params);+ }+ if (symbols) {+ const results: Record<string, any> = {};+ for (const symbol of symbols) {+ try {+ results[symbol] = await this.fetchFundingRate(symbol, params);+ } catch {+ results[symbol] = null;+ }+ }+ return results;+ }+ throw new Error('fetchFundingRates not supported by this exchange');+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchFundingRateHistory(symbol: string, since?: number, limit?: number, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchFundingRateHistory']) {+ throw new Error('fetchFundingRateHistory not supported by this exchange');+ }+ return await this.exchange.fetchFundingRateHistory(symbol, since, limit, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // OPEN INTEREST+ // ============================================================================++ async fetchOpenInterest(symbol: string, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchOpenInterest']) {+ throw new Error('fetchOpenInterest not supported by this exchange');+ }+ return await (this.exchange as any).fetchOpenInterest(symbol, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchOpenInterestHistory(symbol: string, timeframe?: string, since?: number, limit?: number, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchOpenInterestHistory']) {+ throw new Error('fetchOpenInterestHistory not supported by this exchange');+ }+ return await (this.exchange as any).fetchOpenInterestHistory(symbol, timeframe, since, limit, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // MARK & INDEX PRICES+ // ============================================================================++ async fetchMarkPrice(symbol: string, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchMarkPrice']) {+ throw new Error('fetchMarkPrice not supported by this exchange');+ }+ return await (this.exchange as any).fetchMarkPrice(symbol, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchMarkPrices(symbols?: string[], params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (this.exchange.has['fetchMarkPrices']) {+ return await (this.exchange as any).fetchMarkPrices(symbols, params);+ }+ if (symbols) {+ const results: Record<string, any> = {};+ for (const symbol of symbols) {+ try {+ results[symbol] = await this.fetchMarkPrice(symbol, params);+ } catch {+ results[symbol] = null;+ }+ }+ return results;+ }+ throw new Error('fetchMarkPrices not supported by this exchange');+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchIndexOHLCV(symbol: string, timeframe?: string, since?: number, limit?: number, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchIndexOHLCV']) {+ throw new Error('fetchIndexOHLCV not supported by this exchange');+ }+ return await (this.exchange as any).fetchIndexOHLCV(symbol, timeframe, since, limit, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchMarkOHLCV(symbol: string, timeframe?: string, since?: number, limit?: number, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchMarkOHLCV']) {+ throw new Error('fetchMarkOHLCV not supported by this exchange');+ }+ return await (this.exchange as any).fetchMarkOHLCV(symbol, timeframe, since, limit, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchPremiumIndexOHLCV(symbol: string, timeframe?: string, since?: number, limit?: number, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchPremiumIndexOHLCV']) {+ throw new Error('fetchPremiumIndexOHLCV not supported by this exchange');+ }+ return await (this.exchange as any).fetchPremiumIndexOHLCV(symbol, timeframe, since, limit, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // LIQUIDATIONS+ // ============================================================================++ async fetchLiquidations(symbol: string, since?: number, limit?: number, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchLiquidations']) {+ throw new Error('fetchLiquidations not supported by this exchange');+ }+ return await (this.exchange as any).fetchLiquidations(symbol, since, limit, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchMyLiquidations(symbol?: string, since?: number, limit?: number, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchMyLiquidations']) {+ throw new Error('fetchMyLiquidations not supported by this exchange');+ }+ return await (this.exchange as any).fetchMyLiquidations(symbol, since, limit, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // SETTLEMENTS+ // ============================================================================++ async fetchSettlementHistory(symbol?: string, since?: number, limit?: number, params?: any): Promise<any> {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchSettlementHistory']) {+ throw new Error('fetchSettlementHistory not supported by this exchange');+ }+ return await (this.exchange as any).fetchSettlementHistory(symbol, since, limit, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchMySettlementHistory(symbol?: string, since?: number, limit?: number, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchMySettlementHistory']) {+ throw new Error('fetchMySettlementHistory not supported by this exchange');+ }+ return await (this.exchange as any).fetchMySettlementHistory(symbol, since, limit, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }+}diff --git a/fincept-terminal-desktop/src/brokers/crypto/base/FundingAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/base/FundingAdapter.tsnew file mode 100644index 000000000..28f527469--- /dev/null+++ b/fincept-terminal-desktop/src/brokers/crypto/base/FundingAdapter.ts@@ -0,0 +1,130 @@+/**+ * Funding Adapter+ *+ * Deposits, withdrawals, and transfer methods+ * Extends DerivativesAdapter with funding functionality+ */++import { DerivativesAdapter } from './DerivativesAdapter';++export abstract class FundingAdapter extends DerivativesAdapter {+ // ============================================================================+ // DEPOSITS+ // ============================================================================++ async fetchDeposits(code?: string, since?: number, limit?: number): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchDeposits']) {+ throw new Error('fetchDeposits not supported by this exchange');+ }+ return await this.exchange.fetchDeposits(code, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchDepositAddress(code: string, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchDepositAddress']) {+ throw new Error('fetchDepositAddress not supported by this exchange');+ }+ return await this.exchange.fetchDepositAddress(code, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async createDepositAddress(code: string, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['createDepositAddress']) {+ throw new Error('createDepositAddress not supported by this exchange');+ }+ return await this.exchange.createDepositAddress(code, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchDepositMethods(code?: string): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchDepositMethods']) {+ throw new Error('fetchDepositMethods not supported by this exchange');+ }+ return await (this.exchange as any).fetchDepositMethods(code);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // WITHDRAWALS+ // ============================================================================++ async fetchWithdrawals(code?: string, since?: number, limit?: number): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchWithdrawals']) {+ throw new Error('fetchWithdrawals not supported by this exchange');+ }+ return await this.exchange.fetchWithdrawals(code, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async withdraw(code: string, amount: number, address: string, tag?: string, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['withdraw']) {+ throw new Error('withdraw not supported by this exchange');+ }+ return await this.exchange.withdraw(code, amount, address, tag, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // TRANSFERS+ // ============================================================================++ async transfer(code: string, amount: number, fromAccount: string, toAccount: string, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['transfer']) {+ throw new Error('transfer not supported by this exchange');+ }+ return await this.exchange.transfer(code, amount, fromAccount, toAccount, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async transferOut(code: string, amount: number, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['transfer']) {+ throw new Error('transferOut not supported by this exchange');+ }+ return await this.exchange.transfer(code, amount, 'spot', 'external', params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchTransfers(code?: string, since?: number, limit?: number, params?: any): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchTransfers']) {+ throw new Error('fetchTransfers not supported by this exchange');+ }+ return await (this.exchange as any).fetchTransfers(code, since, limit, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }+}diff --git a/fincept-terminal-desktop/src/brokers/crypto/base/TradingAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/base/TradingAdapter.tsnew file mode 100644index 000000000..6d79a0f6d--- /dev/null+++ b/fincept-terminal-desktop/src/brokers/crypto/base/TradingAdapter.ts@@ -0,0 +1,248 @@+/**+ * Trading Adapter+ *+ * Order management and trading methods+ * Extends CoreAdapter with trading functionality+ */++import { Order, Trade } from 'ccxt';+import { CoreExchangeAdapter } from './CoreAdapter';+import { OrderType, OrderSide, OrderParams } from '../types';++export abstract class TradingAdapter extends CoreExchangeAdapter {+ // ============================================================================+ // ORDER CREATION+ // ============================================================================++ async createOrder(+ symbol: string,+ type: OrderType,+ side: OrderSide,+ amount: number,+ price?: number,+ params?: OrderParams+ ): Promise<Order> {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.createOrder(symbol, type, side, amount, price, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async createOrders(orders: Array<{+ symbol: string;+ type: OrderType;+ side: OrderSide;+ amount: number;+ price?: number;+ params?: OrderParams;+ }>): Promise<Order[]> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['createOrders']) {+ const results: Order[] = [];+ for (const order of orders) {+ const result = await this.createOrder(+ order.symbol,+ order.type,+ order.side,+ order.amount,+ order.price,+ order.params+ );+ results.push(result);+ }+ return results;+ }+ return await this.exchange.createOrders(orders);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async createMarketOrderWithCost(+ symbol: string,+ side: OrderSide,+ cost: number,+ params?: OrderParams+ ): Promise<Order> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['createMarketOrderWithCost']) {+ throw new Error('createMarketOrderWithCost not supported');+ }+ return await (this.exchange as any).createMarketOrderWithCost(symbol, side, cost, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async createMarketBuyOrderWithCost(+ symbol: string,+ cost: number,+ params?: OrderParams+ ): Promise<Order> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['createMarketBuyOrderWithCost']) {+ return await this.createMarketOrderWithCost(symbol, 'buy', cost, params);+ }+ return await (this.exchange as any).createMarketBuyOrderWithCost(symbol, cost, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // ORDER MODIFICATION+ // ============================================================================++ async editOrder(+ orderId: string,+ symbol: string,+ type?: OrderType,+ side?: OrderSide,+ amount?: number,+ price?: number,+ params?: OrderParams+ ): Promise<Order> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['editOrder']) {+ throw new Error('editOrder not supported by this exchange');+ }+ return await this.exchange.editOrder(orderId, symbol, type as any, side as any, amount, price, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // ORDER CANCELLATION+ // ============================================================================++ async cancelOrder(orderId: string, symbol: string): Promise<Order> {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.cancelOrder(orderId, symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async cancelOrders(orderIds: string[], symbol?: string): Promise<Order[]> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['cancelOrders']) {+ const results: Order[] = [];+ for (const orderId of orderIds) {+ if (!symbol) throw new Error('Symbol required for bulk cancel fallback');+ const result = await this.cancelOrder(orderId, symbol);+ results.push(result);+ }+ return results;+ }+ return await this.exchange.cancelOrders(orderIds, symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async cancelAllOrders(symbol?: string): Promise<Order[]> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['cancelAllOrders']) {+ throw new Error('Exchange does not support cancelAllOrders');+ }+ return await this.exchange.cancelAllOrders(symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async cancelAllOrdersAfter(timeout: number): Promise<any> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['cancelAllOrdersAfter']) {+ throw new Error('cancelAllOrdersAfter not supported by this exchange');+ }+ return await (this.exchange as any).cancelAllOrdersAfter(timeout);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // ORDER QUERIES+ // ============================================================================++ async fetchOrder(orderId: string, symbol: string): Promise<Order> {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchOrder(orderId, symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchOrdersByIds(orderIds: string[], symbol?: string): Promise<Order[]> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchOrdersByIds']) {+ const results: Order[] = [];+ for (const orderId of orderIds) {+ if (!symbol) throw new Error('Symbol required for fetchOrdersByIds fallback');+ const order = await this.fetchOrder(orderId, symbol);+ results.push(order);+ }+ return results;+ }+ return await (this.exchange as any).fetchOrdersByIds(orderIds, symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchOrderTrades(orderId: string, symbol: string): Promise<Trade[]> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchOrderTrades']) {+ throw new Error('fetchOrderTrades not supported by this exchange');+ }+ return await this.exchange.fetchOrderTrades(orderId, symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchMyTrades(symbol?: string, since?: number, limit?: number): Promise<Trade[]> {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['fetchMyTrades']) {+ throw new Error('fetchMyTrades not supported by this exchange');+ }+ return await this.exchange.fetchMyTrades(symbol, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchOpenOrders(symbol?: string): Promise<Order[]> {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchOpenOrders(symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ async fetchClosedOrders(symbol?: string, limit?: number): Promise<Order[]> {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchClosedOrders(symbol, undefined, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }+}diff --git a/fincept-terminal-desktop/src/brokers/crypto/base/index.ts b/fincept-terminal-desktop/src/brokers/crypto/base/index.tsnew file mode 100644index 000000000..399700314--- /dev/null+++ b/fincept-terminal-desktop/src/brokers/crypto/base/index.ts@@ -0,0 +1,18 @@+/**+ * Base Adapter Modules+ *+ * Modular adapter hierarchy for crypto exchange integration+ *+ * Inheritance Chain:+ * CoreExchangeAdapter (connection, auth, market data)+ * └── TradingAdapter (order management)+ * └── DerivativesAdapter (futures, options, leverage, positions)+ * └── FundingAdapter (deposits, withdrawals, transfers)+ * └── AdvancedAdapter (convert, sentiment) - Final in chain+ */++export { CoreExchangeAdapter } from './CoreAdapter';+export { TradingAdapter } from './TradingAdapter';+export { DerivativesAdapter } from './DerivativesAdapter';+export { FundingAdapter } from './FundingAdapter';+export { AdvancedAdapter } from './AdvancedAdapter';diff --git a/fincept-terminal-desktop/src/brokers/crypto/bybit/BybitAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/bybit/BybitAdapter.tsnew file mode 100644index 000000000..09c65bd44--- /dev/null+++ b/fincept-terminal-desktop/src/brokers/crypto/bybit/BybitAdapter.ts@@ -0,0 +1,950 @@+/**+ * Bybit Exchange Adapter+ *+ * Professional-grade Bybit integration using CCXT+ * Supports: Spot, USDT Perpetuals, USDC Perpetuals, Inverse Perpetuals, Options+ *+ * Bybit is the #2 derivatives exchange globally with massive volume+ * Features: Unified Trading Account, Copy Trading, Earn Products+ */++import { BaseExchangeAdapter } from '../BaseExchangeAdapter';+import type {+ ExchangeConfig,+ OrderType,+ OrderSide,+ OrderParams,+ ExchangeCapabilities,+} from '../types';++export class BybitAdapter extends BaseExchangeAdapter {+ constructor(config?: Partial<ExchangeConfig>) {+ super({+ exchange: 'bybit',+ enableRateLimit: true,+ timeout: 30000,+ ...config,+ });+ }++ // ============================================================================+ // BYBIT-SPECIFIC CAPABILITIES+ // ============================================================================++ getCapabilities(): ExchangeCapabilities {+ const base = super.getCapabilities();+ return {+ ...base,+ spot: true,+ margin: true,+ futures: true,+ swap: true, // Perpetual swaps+ options: true, // USDC options++ supportedOrderTypes: [+ 'market',+ 'limit',+ 'stop',+ 'stop_limit',+ 'trailing_stop',+ ] as any,++ leverageTrading: true,+ stopOrders: true,+ conditionalOrders: true,+ algoOrders: true,++ realtimeData: true,+ historicalData: true,+ websocketSupport: true,++ multiAccount: false,+ subAccounts: true,+ portfolioMargin: true, // Unified Trading Account++ rateLimits: {+ public: 120, // 120 requests per second+ private: 50, // 50 requests per second+ trading: 50, // 50 orders per second+ },+ };+ }++ // ============================================================================+ // ENHANCED ORDER METHODS+ // ============================================================================++ /**+ * Create OCO (One-Cancels-Other) order+ * Bybit supports conditional orders that can act as OCO+ */+ async createOCOOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ price: number,+ stopPrice: number,+ stopLimitPrice?: number+ ) {+ try {+ await this.ensureAuthenticated();+ // Bybit uses conditional orders for OCO-like functionality+ return await (this.exchange as any).createOrder(symbol, 'limit', side, amount, price, {+ stopPrice,+ stopLimitPrice: stopLimitPrice || stopPrice,+ triggerDirection: side === 'buy' ? 2 : 1, // 1=triggered when price rises, 2=falls+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create stop-loss order+ */+ async createStopLossOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ stopPrice: number,+ limitPrice?: number+ ) {+ const type: OrderType = limitPrice ? 'stop_limit' : 'stop';+ return await this.createOrder(symbol, type, side, amount, limitPrice, {+ stopPrice,+ triggerPrice: stopPrice,+ triggerBy: 'LastPrice',+ });+ }++ /**+ * Create take-profit order+ */+ async createTakeProfitOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ stopPrice: number,+ limitPrice?: number+ ) {+ const type: OrderType = limitPrice ? 'stop_limit' : 'stop';+ return await this.createOrder(symbol, type, side, amount, limitPrice, {+ stopPrice,+ triggerPrice: stopPrice,+ triggerBy: 'LastPrice',+ tpTriggerBy: 'LastPrice',+ });+ }++ /**+ * Create trailing stop order+ */+ async createTrailingStopOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ callbackRate: number // Trailing distance in percentage+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.createOrder(symbol, 'trailing_stop' as OrderType, side, amount, undefined, {+ trailingDelta: callbackRate * 100, // Bybit uses basis points+ triggerBy: 'LastPrice',+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create iceberg order (split large order into smaller visible chunks)+ */+ async createIcebergOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ price: number,+ icebergQty: number,+ params?: OrderParams+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.createOrder(symbol, 'limit', side, amount, price, {+ ...params,+ icebergQty,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create reduce-only order (derivatives only - close position only)+ */+ async createReduceOnlyOrder(+ symbol: string,+ type: OrderType,+ side: OrderSide,+ amount: number,+ price?: number+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.createOrder(symbol, type, side, amount, price, {+ reduceOnly: true,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create post-only order (maker-only, will cancel if would take)+ */+ async createPostOnlyOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ price: number+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.createOrder(symbol, 'limit', side, amount, price, {+ postOnly: true,+ timeInForce: 'PostOnly' as any, // Bybit uses PostOnly for maker-only orders+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create conditional order (trigger order)+ */+ async createConditionalOrder(+ symbol: string,+ type: OrderType,+ side: OrderSide,+ amount: number,+ triggerPrice: number,+ price?: number,+ triggerBy: 'LastPrice' | 'IndexPrice' | 'MarkPrice' = 'LastPrice'+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.createOrder(symbol, type, side, amount, price, {+ triggerPrice,+ triggerBy,+ stopOrderType: 'Stop',+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // MARGIN & LEVERAGE TRADING+ // ============================================================================++ /**+ * Set leverage for derivatives+ */+ async setLeverage(symbol: string, leverage: number) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.setLeverage(leverage, symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Set margin mode (cross or isolated)+ */+ async setMarginMode(symbol: string, marginMode: 'cross' | 'isolated') {+ try {+ await this.ensureAuthenticated();+ // Bybit uses 0 for cross, 1 for isolated in some endpoints+ return await this.exchange.setMarginMode(marginMode, symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Set position mode (one-way or hedge mode)+ */+ async setPositionMode(hedgeMode: boolean) {+ try {+ await this.ensureAuthenticated();+ // Bybit: MergedSingle = one-way, BothSide = hedge+ return await (this.exchange as any).setPositionMode(hedgeMode);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create margin order+ */+ async createMarginOrder(+ symbol: string,+ type: OrderType,+ side: OrderSide,+ amount: number,+ price?: number,+ params?: OrderParams+ ) {+ return await this.createOrder(symbol, type, side, amount, price, {+ ...params,+ marginMode: params?.marginMode || 'cross',+ });+ }++ /**+ * Fetch margin balance+ */+ async fetchMarginBalance() {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchBalance({ type: 'margin' });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch derivatives/futures balance+ */+ async fetchFuturesBalance() {+ try {+ await this.ensureAuthenticated();+ // Bybit unified account+ return await this.exchange.fetchBalance({ type: 'swap' });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch unified account balance (Bybit's Unified Trading Account)+ */+ async fetchUnifiedBalance() {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchBalance({ type: 'unified' });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Add/reduce margin for position+ */+ async modifyPositionMargin(symbol: string, amount: number, type: 'add' | 'reduce') {+ try {+ await this.ensureAuthenticated();+ const addMargin = type === 'add';+ return await (this.exchange as any).addMargin(symbol, amount, {+ type: addMargin ? 'ADD_MARGIN' : 'REDUCE_MARGIN'+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // FUNDING & TRANSFERS+ // ============================================================================++ /**+ * Transfer between accounts (spot, contract, unified, etc.)+ */+ async transfer(+ currency: string,+ amount: number,+ fromAccount: 'spot' | 'contract' | 'unified' | 'funding' | 'option',+ toAccount: 'spot' | 'contract' | 'unified' | 'funding' | 'option'+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.transfer(currency, amount, fromAccount, toAccount);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch funding rate for perpetual+ */+ async fetchFundingRate(symbol: string) {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchFundingRate(symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch funding rate history+ */+ async fetchFundingRateHistory(symbol: string, since?: number, limit?: number) {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchFundingRateHistory(symbol, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch user's funding history (payments received/paid)+ */+ async fetchFundingHistory(symbol?: string, since?: number, limit?: number) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['fetchFundingHistory']) {+ return await (this.exchange as any).fetchFundingHistory(symbol, since, limit);+ }+ // Bybit alternative: fetch from transaction log+ return await (this.exchange as any).privateGetV5AccountTransactionLog({+ type: 'FUNDING_FEE',+ symbol: symbol?.replace('/', ''),+ limit,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // DERIVATIVES/FUTURES TRADING+ // ============================================================================++ /**+ * Fetch futures/perpetual markets+ */+ async fetchFuturesMarkets() {+ try {+ await this.ensureConnected();+ const markets = await this.fetchMarkets();+ return markets.filter((m: any) => m.future || m.swap || m.linear || m.inverse);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch open interest for symbol+ */+ async fetchOpenInterest(symbol: string) {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchOpenInterest']) {+ throw new Error('fetchOpenInterest not supported');+ }+ return await this.exchange.fetchOpenInterest(symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch open interest history+ */+ async fetchOpenInterestHistory(symbol: string, timeframe: string = '1h', since?: number, limit?: number) {+ try {+ await this.ensureConnected();+ if (this.exchange.has['fetchOpenInterestHistory']) {+ return await (this.exchange as any).fetchOpenInterestHistory(symbol, timeframe, since, limit);+ }+ throw new Error('fetchOpenInterestHistory not available');+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch liquidation history+ */+ async fetchLiquidations(symbol: string, since?: number, limit?: number) {+ try {+ await this.ensureConnected();+ if (this.exchange.has['fetchLiquidations']) {+ return await (this.exchange as any).fetchLiquidations(symbol, since, limit);+ }+ throw new Error('fetchLiquidations not available');+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Set take profit and stop loss for position+ */+ async setTakeProfitStopLoss(+ symbol: string,+ takeProfit?: number,+ stopLoss?: number,+ params?: any+ ) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).setTpSlMode(symbol, {+ takeProfit,+ stopLoss,+ ...params,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // ACCOUNT & FEES+ // ============================================================================++ /**+ * Fetch trading fees+ */+ async fetchTradingFees() {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchTradingFees();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch trading fee for specific symbol+ */+ async fetchTradingFee(symbol: string) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['fetchTradingFee']) {+ return await this.exchange.fetchTradingFee(symbol);+ }+ const fees = await this.fetchTradingFees();+ return fees[symbol] || null;+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch account ledger / transaction history+ */+ async fetchLedger(code?: string, since?: number, limit?: number) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchLedger(code, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch account info+ */+ async fetchAccountInfo() {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privateGetV5AccountInfo();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // DEPOSITS & WITHDRAWALS+ // ============================================================================++ /**+ * Fetch deposit address+ */+ async fetchDepositAddress(currency: string, network?: string) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchDepositAddress(currency, { network });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch deposits+ */+ async fetchDeposits(currency?: string, since?: number, limit?: number) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchDeposits(currency, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch withdrawals+ */+ async fetchWithdrawals(currency?: string, since?: number, limit?: number) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchWithdrawals(currency, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Withdraw funds+ */+ async withdraw(currency: string, amount: number, address: string, tag?: string, network?: string) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.withdraw(currency, amount, address, tag, { network });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // ORDER MANAGEMENT+ // ============================================================================++ /**+ * Edit existing order+ */+ async editOrder(+ orderId: string,+ symbol: string,+ type?: string,+ side?: string,+ amount?: number,+ price?: number,+ params?: any+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.editOrder(orderId, symbol, type as any, side as any, amount, price, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch my trades+ */+ async fetchMyTrades(symbol?: string, since?: number, limit?: number) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchMyTrades(symbol, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Cancel multiple orders+ */+ async cancelOrders(orderIds: string[], symbol?: string) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['cancelOrders']) {+ return await this.exchange.cancelOrders(orderIds, symbol);+ }+ // Fallback to individual cancels+ const results = [];+ for (const orderId of orderIds) {+ if (!symbol) throw new Error('Symbol required for bulk cancel');+ const result = await this.cancelOrder(orderId, symbol);+ results.push(result);+ }+ return results;+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Cancel all open orders+ */+ async cancelAllOrders(symbol?: string) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.cancelAllOrders(symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch specific order by ID+ */+ async fetchOrder(orderId: string, symbol: string) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchOrder(orderId, symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch multiple orders by IDs+ */+ async fetchOrdersByIds(orderIds: string[], symbol: string) {+ try {+ await this.ensureAuthenticated();+ const orders = [];+ for (const orderId of orderIds) {+ const order = await this.fetchOrder(orderId, symbol);+ orders.push(order);+ }+ return orders;+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch trades for specific order+ */+ async fetchOrderTrades(orderId: string, symbol: string) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['fetchOrderTrades']) {+ return await this.exchange.fetchOrderTrades(orderId, symbol);+ }+ // Fallback: fetch all trades and filter+ const trades = await this.fetchMyTrades(symbol);+ return trades.filter((t: any) => t.order === orderId);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Cancel all orders after timeout (Dead Man's Switch)+ */+ async cancelAllOrdersAfter(timeout: number) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['cancelAllOrdersAfter']) {+ return await (this.exchange as any).cancelAllOrdersAfter(timeout);+ }+ throw new Error('cancelAllOrdersAfter not supported on Bybit');+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // HISTORICAL DATA+ // ============================================================================++ /**+ * Fetch historical OHLCV with extended options+ */+ async fetchHistoricalOHLCV(+ symbol: string,+ timeframe: '1m' | '3m' | '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '12h' | '1d' | '1w' | '1M',+ since?: number,+ limit: number = 200+ ) {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchOHLCV(symbol, timeframe, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch recent trades with extended data+ */+ async fetchRecentTrades(symbol: string, limit: number = 100) {+ try {+ await this.ensureConnected();+ const trades = await this.exchange.fetchTrades(symbol, undefined, limit);+ return trades.map(trade => ({+ ...trade,+ exchange: 'bybit',+ timestamp: trade.timestamp || Date.now(),+ }));+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // BYBIT-SPECIFIC: COPY TRADING+ // ============================================================================++ /**+ * Fetch copy trading masters (top traders)+ */+ async fetchCopyTradingMasters(params?: any) {+ try {+ await this.ensureConnected();+ return await (this.exchange as any).publicGetV5CopyTradingMasterInfo(params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Get copy trading status+ */+ async getCopyTradingStatus() {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privateGetV5CopyTradingContractOrder();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // BYBIT-SPECIFIC: EARN PRODUCTS+ // ============================================================================++ /**+ * Fetch earn products+ */+ async fetchEarnProducts() {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privateGetV5AssetEarnProduct();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Subscribe to earn product+ */+ async subscribeToEarn(productId: string, amount: number) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privatePostV5AssetEarnSubscribe({+ productId,+ amount: amount.toString(),+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Redeem from earn product+ */+ async redeemFromEarn(productId: string, amount: number) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privatePostV5AssetEarnRedeem({+ productId,+ amount: amount.toString(),+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // UTILITIES+ // ============================================================================++ /**+ * Get Bybit system status+ */+ async getSystemStatus() {+ try {+ return await this.fetchStatus();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Get server time+ */+ async getServerTime() {+ try {+ return await this.fetchTime();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Get risk limit info for symbol+ */+ async getRiskLimitInfo(symbol: string) {+ try {+ await this.ensureConnected();+ return await (this.exchange as any).publicGetV5MarketRiskLimit({+ symbol: symbol.replace('/', ''),+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Set risk limit for position+ */+ async setRiskLimit(symbol: string, riskId: number) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privatePostV5PositionSetRiskLimit({+ symbol: symbol.replace('/', ''),+ riskId,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Get popular Bybit trading pairs+ */+ getPopularPairs(): string[] {+ return [+ 'BTC/USDT',+ 'ETH/USDT',+ 'SOL/USDT',+ 'XRP/USDT',+ 'DOGE/USDT',+ 'ADA/USDT',+ 'AVAX/USDT',+ 'MATIC/USDT',+ 'LINK/USDT',+ 'DOT/USDT',+ 'UNI/USDT',+ 'ATOM/USDT',+ 'LTC/USDT',+ 'OP/USDT',+ 'ARB/USDT',+ ];+ }++ /**+ * Get popular USDT perpetual pairs+ */+ getPopularPerpetuals(): string[] {+ return [+ 'BTC/USDT:USDT',+ 'ETH/USDT:USDT',+ 'SOL/USDT:USDT',+ 'XRP/USDT:USDT',+ 'DOGE/USDT:USDT',+ 'ADA/USDT:USDT',+ 'AVAX/USDT:USDT',+ 'MATIC/USDT:USDT',+ 'LINK/USDT:USDT',+ 'DOT/USDT:USDT',+ ];+ }+}diff --git a/fincept-terminal-desktop/src/brokers/crypto/bybit/index.ts b/fincept-terminal-desktop/src/brokers/crypto/bybit/index.tsnew file mode 100644index 000000000..ab415eef8--- /dev/null+++ b/fincept-terminal-desktop/src/brokers/crypto/bybit/index.ts@@ -0,0 +1,8 @@+/**+ * Bybit Exchange Module+ *+ * Professional-grade Bybit integration+ * #2 derivatives exchange globally+ */++export { BybitAdapter } from './BybitAdapter';diff --git a/fincept-terminal-desktop/src/brokers/crypto/coinbase/CoinbaseAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/coinbase/CoinbaseAdapter.tsindex ba80848d5..b01b4a7db 100644--- a/fincept-terminal-desktop/src/brokers/crypto/coinbase/CoinbaseAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/crypto/coinbase/CoinbaseAdapter.ts@@ -311,7 +311,17 @@ export class CoinbaseAdapter extends BaseExchangeAdapter {* Note: Not applicable for spot-only exchange*/async setMarginMode(symbol: string, marginMode: 'cross' | 'isolated') {- throw new Error('Margin mode not supported on Coinbase (spot-only exchange)');+ // Return a no-op response for spot-only exchange+ return { symbol, marginMode: 'cross', info: { message: 'Margin mode not applicable for spot trading' } };+ }++ /**+ * Set position mode (one-way or hedge mode)+ * Note: Not applicable for spot-only exchange+ */+ async setPositionMode(hedgeMode: boolean) {+ // Return a no-op response for spot-only exchange+ return { hedgeMode: false, info: { message: 'Position mode not applicable for spot trading' } };}// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/crypto/gateio/GateioAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/gateio/GateioAdapter.tsnew file mode 100644index 000000000..ed2f7e442--- /dev/null+++ b/fincept-terminal-desktop/src/brokers/crypto/gateio/GateioAdapter.ts@@ -0,0 +1,1194 @@+/**+ * Gate.io Exchange Adapter+ *+ * Professional-grade Gate.io integration using CCXT+ * Supports: Spot, Margin, Futures, Perpetuals, Options, Copy Trading+ *+ * Gate.io is the #4 spot exchange globally with 1400+ trading pairs+ * Known for: Wide altcoin selection, copy trading, lending/borrowing+ */++import { BaseExchangeAdapter } from '../BaseExchangeAdapter';+import type {+ ExchangeConfig,+ OrderType,+ OrderSide,+ OrderParams,+ ExchangeCapabilities,+} from '../types';++export class GateioAdapter extends BaseExchangeAdapter {+ constructor(config?: Partial<ExchangeConfig>) {+ super({+ exchange: 'gateio',+ enableRateLimit: true,+ timeout: 30000,+ ...config,+ });+ }++ // ============================================================================+ // GATE.IO-SPECIFIC CAPABILITIES+ // ============================================================================++ getCapabilities(): ExchangeCapabilities {+ const base = super.getCapabilities();+ return {+ ...base,+ spot: true,+ margin: true,+ futures: true,+ swap: true, // Perpetual swaps+ options: true, // Options trading++ supportedOrderTypes: [+ 'market',+ 'limit',+ 'stop',+ 'stop_limit',+ 'trailing_stop',+ ] as any,++ leverageTrading: true,+ stopOrders: true,+ conditionalOrders: true,+ algoOrders: true,++ realtimeData: true,+ historicalData: true,+ websocketSupport: true,++ multiAccount: false,+ subAccounts: true,+ portfolioMargin: true,++ rateLimits: {+ public: 900, // 900 requests per minute+ private: 900, // 900 requests per minute+ trading: 300, // 300 orders per minute+ },+ };+ }++ // ============================================================================+ // ENHANCED ORDER METHODS+ // ============================================================================++ /**+ * Create OCO (One-Cancels-Other) order+ * Gate.io supports conditional orders that can act as OCO+ */+ async createOCOOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ price: number,+ stopPrice: number,+ stopLimitPrice?: number+ ) {+ try {+ await this.ensureAuthenticated();+ // Gate.io uses price triggers for OCO-like functionality+ return await (this.exchange as any).createOrder(symbol, 'limit', side, amount, price, {+ stopPrice,+ stopLossPrice: stopLimitPrice || stopPrice,+ takeProfitPrice: price,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create stop-loss order+ */+ async createStopLossOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ stopPrice: number,+ limitPrice?: number+ ) {+ const type: OrderType = limitPrice ? 'stop_limit' : 'stop';+ return await this.createOrder(symbol, type, side, amount, limitPrice, {+ stopPrice,+ triggerPrice: stopPrice,+ trigger: 'le', // Less than or equal+ });+ }++ /**+ * Create take-profit order+ */+ async createTakeProfitOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ stopPrice: number,+ limitPrice?: number+ ) {+ const type: OrderType = limitPrice ? 'stop_limit' : 'stop';+ return await this.createOrder(symbol, type, side, amount, limitPrice, {+ stopPrice,+ triggerPrice: stopPrice,+ trigger: 'ge', // Greater than or equal+ });+ }++ /**+ * Create trailing stop order+ */+ async createTrailingStopOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ callbackRate: number // Trailing distance in percentage+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.createOrder(symbol, 'trailing_stop' as OrderType, side, amount, undefined, {+ trailingPercent: callbackRate,+ callbackRate: callbackRate.toString(),+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create iceberg order (split large order into smaller visible chunks)+ */+ async createIcebergOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ price: number,+ icebergQty: number,+ params?: OrderParams+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.createOrder(symbol, 'limit', side, amount, price, {+ ...params,+ iceberg: icebergQty,+ visible_size: icebergQty,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create reduce-only order (derivatives only - close position only)+ */+ async createReduceOnlyOrder(+ symbol: string,+ type: OrderType,+ side: OrderSide,+ amount: number,+ price?: number+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.createOrder(symbol, type, side, amount, price, {+ reduceOnly: true,+ reduce_only: true,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create post-only order (maker-only, will cancel if would take)+ */+ async createPostOnlyOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ price: number+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.createOrder(symbol, 'limit', side, amount, price, {+ postOnly: true,+ timeInForce: 'PO' as any, // Gate.io Post-Only+ tif: 'poc', // Post only cancel+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create conditional order (trigger order)+ */+ async createConditionalOrder(+ symbol: string,+ type: OrderType,+ side: OrderSide,+ amount: number,+ triggerPrice: number,+ price?: number,+ triggerBy: 'last' | 'index' | 'mark' = 'last'+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.createOrder(symbol, type, side, amount, price, {+ triggerPrice,+ trigger_price: triggerPrice.toString(),+ trigger: side === 'buy' ? 'le' : 'ge',+ price_type: triggerBy === 'mark' ? 1 : (triggerBy === 'index' ? 2 : 0),+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // MARGIN & LEVERAGE TRADING+ // ============================================================================++ /**+ * Set leverage for derivatives+ */+ async setLeverage(symbol: string, leverage: number) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.setLeverage(leverage, symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Set margin mode (cross or isolated)+ */+ async setMarginMode(symbol: string, marginMode: 'cross' | 'isolated') {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.setMarginMode(marginMode, symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Set position mode (one-way or hedge mode)+ */+ async setPositionMode(hedgeMode: boolean) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['setPositionMode']) {+ return await (this.exchange as any).setPositionMode(hedgeMode);+ }+ // Gate.io uses dual_mode parameter+ return await (this.exchange as any).privatePostFuturesSettleDualMode({+ settle: 'usdt',+ dual_mode: hedgeMode,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create margin order+ */+ async createMarginOrder(+ symbol: string,+ type: OrderType,+ side: OrderSide,+ amount: number,+ price?: number,+ params?: OrderParams+ ) {+ return await this.createOrder(symbol, type, side, amount, price, {+ ...params,+ marginMode: params?.marginMode || 'cross',+ account: 'margin',+ });+ }++ /**+ * Fetch margin balance+ */+ async fetchMarginBalance() {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchBalance({ type: 'margin' });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch derivatives/futures balance+ */+ async fetchFuturesBalance() {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchBalance({ type: 'swap' });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Borrow margin funds+ */+ async borrowMargin(currency: string, amount: number, symbol?: string) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['borrowMargin']) {+ return await (this.exchange as any).borrowMargin(currency, amount, symbol);+ }+ return await (this.exchange as any).privatePostMarginLoans({+ currency,+ amount: amount.toString(),+ currency_pair: symbol?.replace('/', '_'),+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Repay margin loan+ */+ async repayMargin(currency: string, amount: number, symbol?: string) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['repayMargin']) {+ return await (this.exchange as any).repayMargin(currency, amount, symbol);+ }+ return await (this.exchange as any).privatePostMarginLoansLoanIdRepayment({+ currency,+ amount: amount.toString(),+ currency_pair: symbol?.replace('/', '_'),+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Add/reduce margin for position+ */+ async modifyPositionMargin(symbol: string, amount: number, type: 'add' | 'reduce') {+ try {+ await this.ensureAuthenticated();+ const change = type === 'add' ? amount : -amount;+ return await (this.exchange as any).addMargin(symbol, change);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // FUNDING & TRANSFERS+ // ============================================================================++ /**+ * Transfer between accounts (spot, margin, futures, etc.)+ */+ async transfer(+ currency: string,+ amount: number,+ fromAccount: 'spot' | 'margin' | 'futures' | 'delivery' | 'options',+ toAccount: 'spot' | 'margin' | 'futures' | 'delivery' | 'options'+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.transfer(currency, amount, fromAccount, toAccount);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch funding rate for perpetual+ */+ async fetchFundingRate(symbol: string) {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchFundingRate(symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch funding rate history+ */+ async fetchFundingRateHistory(symbol: string, since?: number, limit?: number) {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchFundingRateHistory(symbol, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch user's funding history (payments received/paid)+ */+ async fetchFundingHistory(symbol?: string, since?: number, limit?: number) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['fetchFundingHistory']) {+ return await (this.exchange as any).fetchFundingHistory(symbol, since, limit);+ }+ // Gate.io alternative+ return await (this.exchange as any).privateGetFuturesSettleFunding({+ settle: 'usdt',+ contract: symbol?.replace('/', '_'),+ limit,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // DERIVATIVES/FUTURES TRADING+ // ============================================================================++ /**+ * Fetch futures/perpetual markets+ */+ async fetchFuturesMarkets() {+ try {+ await this.ensureConnected();+ const markets = await this.fetchMarkets();+ return markets.filter((m: any) => m.future || m.swap || m.linear || m.inverse);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch open interest for symbol+ */+ async fetchOpenInterest(symbol: string) {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchOpenInterest']) {+ throw new Error('fetchOpenInterest not supported');+ }+ return await this.exchange.fetchOpenInterest(symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch open interest history+ */+ async fetchOpenInterestHistory(symbol: string, timeframe: string = '1h', since?: number, limit?: number) {+ try {+ await this.ensureConnected();+ if (this.exchange.has['fetchOpenInterestHistory']) {+ return await (this.exchange as any).fetchOpenInterestHistory(symbol, timeframe, since, limit);+ }+ throw new Error('fetchOpenInterestHistory not available');+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch liquidation history+ */+ async fetchLiquidations(symbol: string, since?: number, limit?: number) {+ try {+ await this.ensureConnected();+ if (this.exchange.has['fetchLiquidations']) {+ return await (this.exchange as any).fetchLiquidations(symbol, since, limit);+ }+ // Gate.io liquidation orders+ return await (this.exchange as any).publicGetFuturesSettleLiqOrders({+ settle: 'usdt',+ contract: symbol?.replace('/', '_'),+ limit,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Set take profit and stop loss for position+ */+ async setTakeProfitStopLoss(+ symbol: string,+ takeProfit?: number,+ stopLoss?: number,+ params?: any+ ) {+ try {+ await this.ensureAuthenticated();+ const orders = [];++ if (takeProfit) {+ orders.push(this.createTakeProfitOrder(symbol, 'sell', 0, takeProfit));+ }+ if (stopLoss) {+ orders.push(this.createStopLossOrder(symbol, 'sell', 0, stopLoss));+ }++ return await Promise.all(orders);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // ACCOUNT & FEES+ // ============================================================================++ /**+ * Fetch trading fees+ */+ async fetchTradingFees() {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchTradingFees();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch trading fee for specific symbol+ */+ async fetchTradingFee(symbol: string) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['fetchTradingFee']) {+ return await this.exchange.fetchTradingFee(symbol);+ }+ const fees = await this.fetchTradingFees();+ return fees[symbol] || null;+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch account ledger / transaction history+ */+ async fetchLedger(code?: string, since?: number, limit?: number) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchLedger(code, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch account info+ */+ async fetchAccountInfo() {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privateGetAccountDetail();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // DEPOSITS & WITHDRAWALS+ // ============================================================================++ /**+ * Fetch deposit address+ */+ async fetchDepositAddress(currency: string, network?: string) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchDepositAddress(currency, { network });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch deposits+ */+ async fetchDeposits(currency?: string, since?: number, limit?: number) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchDeposits(currency, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch withdrawals+ */+ async fetchWithdrawals(currency?: string, since?: number, limit?: number) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchWithdrawals(currency, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Withdraw funds+ */+ async withdraw(currency: string, amount: number, address: string, tag?: string, network?: string) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.withdraw(currency, amount, address, tag, { network, chain: network });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // ORDER MANAGEMENT+ // ============================================================================++ /**+ * Edit existing order+ */+ async editOrder(+ orderId: string,+ symbol: string,+ type?: string,+ side?: string,+ amount?: number,+ price?: number,+ params?: any+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.editOrder(orderId, symbol, type as any, side as any, amount, price, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch my trades+ */+ async fetchMyTrades(symbol?: string, since?: number, limit?: number) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchMyTrades(symbol, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Cancel multiple orders+ */+ async cancelOrders(orderIds: string[], symbol?: string) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['cancelOrders']) {+ return await this.exchange.cancelOrders(orderIds, symbol);+ }+ // Fallback to individual cancels+ const results = [];+ for (const orderId of orderIds) {+ if (!symbol) throw new Error('Symbol required for bulk cancel');+ const result = await this.cancelOrder(orderId, symbol);+ results.push(result);+ }+ return results;+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Cancel all open orders+ */+ async cancelAllOrders(symbol?: string) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.cancelAllOrders(symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch specific order by ID+ */+ async fetchOrder(orderId: string, symbol: string) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchOrder(orderId, symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch multiple orders by IDs+ */+ async fetchOrdersByIds(orderIds: string[], symbol: string) {+ try {+ await this.ensureAuthenticated();+ const orders = [];+ for (const orderId of orderIds) {+ const order = await this.fetchOrder(orderId, symbol);+ orders.push(order);+ }+ return orders;+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch trades for specific order+ */+ async fetchOrderTrades(orderId: string, symbol: string) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['fetchOrderTrades']) {+ return await this.exchange.fetchOrderTrades(orderId, symbol);+ }+ // Fallback: fetch all trades and filter+ const trades = await this.fetchMyTrades(symbol);+ return trades.filter((t: any) => t.order === orderId);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Cancel all orders after timeout (Dead Man's Switch)+ */+ async cancelAllOrdersAfter(timeout: number) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['cancelAllOrdersAfter']) {+ return await (this.exchange as any).cancelAllOrdersAfter(timeout);+ }+ throw new Error('cancelAllOrdersAfter not supported on Gate.io');+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // HISTORICAL DATA+ // ============================================================================++ /**+ * Fetch historical OHLCV with extended options+ */+ async fetchHistoricalOHLCV(+ symbol: string,+ timeframe: '10s' | '1m' | '5m' | '15m' | '30m' | '1h' | '4h' | '8h' | '1d' | '7d' | '30d',+ since?: number,+ limit: number = 200+ ) {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchOHLCV(symbol, timeframe, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch recent trades with extended data+ */+ async fetchRecentTrades(symbol: string, limit: number = 100) {+ try {+ await this.ensureConnected();+ const trades = await this.exchange.fetchTrades(symbol, undefined, limit);+ return trades.map(trade => ({+ ...trade,+ exchange: 'gateio',+ timestamp: trade.timestamp || Date.now(),+ }));+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // GATE.IO-SPECIFIC: COPY TRADING+ // ============================================================================++ /**+ * Fetch copy trading leaders+ */+ async fetchCopyTradingLeaders(params?: any) {+ try {+ await this.ensureConnected();+ return await (this.exchange as any).publicGetCopyTradingLeaders(params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Follow a copy trading leader+ */+ async followCopyTradingLeader(leaderId: string, params?: any) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privatePostCopyTradingFollow({+ leader_id: leaderId,+ ...params,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Unfollow a copy trading leader+ */+ async unfollowCopyTradingLeader(leaderId: string) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privateDeleteCopyTradingFollow({+ leader_id: leaderId,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Get copy trading status+ */+ async getCopyTradingStatus() {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privateGetCopyTradingStatus();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // GATE.IO-SPECIFIC: LENDING & BORROWING+ // ============================================================================++ /**+ * Fetch lending rates+ */+ async fetchLendingRates(currency?: string) {+ try {+ await this.ensureConnected();+ if (currency) {+ return await (this.exchange as any).publicGetMarginUniCurrencyEstimatedRate({+ currency,+ });+ }+ return await (this.exchange as any).publicGetMarginUniInterestRecords();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create lending order+ */+ async createLendingOrder(currency: string, amount: number, rate: number, days: number = 10) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privatePostMarginUniLoans({+ currency,+ amount: amount.toString(),+ rate: rate.toString(),+ days,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch my lending orders+ */+ async fetchMyLendingOrders(currency?: string, status?: 'active' | 'finished') {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privateGetMarginUniLoans({+ currency,+ status: status === 'active' ? 1 : (status === 'finished' ? 2 : undefined),+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Cancel lending order+ */+ async cancelLendingOrder(orderId: string, currency: string) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privateDeleteMarginUniLoansLoanId({+ loan_id: orderId,+ currency,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // GATE.IO-SPECIFIC: EARN PRODUCTS+ // ============================================================================++ /**+ * Fetch earn/staking products+ */+ async fetchEarnProducts() {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privateGetEarnProducts();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Subscribe to earn product+ */+ async subscribeToEarn(productId: string, amount: number) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privatePostEarnOrders({+ product_id: productId,+ amount: amount.toString(),+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Redeem from earn product+ */+ async redeemFromEarn(orderId: string, amount?: number) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privateDeleteEarnOrdersOrderId({+ order_id: orderId,+ amount: amount?.toString(),+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch my earn orders+ */+ async fetchMyEarnOrders(productId?: string) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privateGetEarnOrders({+ product_id: productId,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // GATE.IO-SPECIFIC: SUB-ACCOUNTS+ // ============================================================================++ /**+ * Fetch sub-accounts list+ */+ async fetchSubAccounts() {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privateGetSubAccounts();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create sub-account+ */+ async createSubAccount(email: string, password: string, remark?: string) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privatePostSubAccounts({+ email,+ password,+ remark,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Transfer to sub-account+ */+ async transferToSubAccount(+ subAccountId: string,+ currency: string,+ amount: number,+ direction: 'to' | 'from' = 'to'+ ) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privatePostSubAccountsTransfers({+ sub_account_id: subAccountId,+ currency,+ amount: amount.toString(),+ direction,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // UTILITIES+ // ============================================================================++ /**+ * Get Gate.io system status+ */+ async getSystemStatus() {+ try {+ return await this.fetchStatus();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Get server time+ */+ async getServerTime() {+ try {+ return await this.fetchTime();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Get risk limit info for futures+ */+ async getRiskLimitInfo(symbol: string) {+ try {+ await this.ensureConnected();+ return await (this.exchange as any).publicGetFuturesSettleContracts({+ settle: 'usdt',+ contract: symbol.replace('/', '_'),+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Set risk limit for position+ */+ async setRiskLimit(symbol: string, riskLimit: number) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privatePostFuturesSettlePositionsContractRiskLimit({+ settle: 'usdt',+ contract: symbol.replace('/', '_'),+ risk_limit: riskLimit,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch currency chains (networks)+ */+ async fetchCurrencyChains(currency: string) {+ try {+ await this.ensureConnected();+ return await (this.exchange as any).publicGetWalletCurrencyChains({+ currency,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Get popular Gate.io trading pairs+ */+ getPopularPairs(): string[] {+ return [+ 'BTC/USDT',+ 'ETH/USDT',+ 'SOL/USDT',+ 'XRP/USDT',+ 'DOGE/USDT',+ 'ADA/USDT',+ 'AVAX/USDT',+ 'MATIC/USDT',+ 'LINK/USDT',+ 'DOT/USDT',+ 'UNI/USDT',+ 'ATOM/USDT',+ 'LTC/USDT',+ 'FIL/USDT',+ 'NEAR/USDT',+ 'APE/USDT',+ 'SAND/USDT',+ 'MANA/USDT',+ 'GT/USDT', // Gate Token+ 'SHIB/USDT',+ ];+ }++ /**+ * Get popular USDT perpetual pairs+ */+ getPopularPerpetuals(): string[] {+ return [+ 'BTC/USDT:USDT',+ 'ETH/USDT:USDT',+ 'SOL/USDT:USDT',+ 'XRP/USDT:USDT',+ 'DOGE/USDT:USDT',+ 'ADA/USDT:USDT',+ 'AVAX/USDT:USDT',+ 'MATIC/USDT:USDT',+ 'LINK/USDT:USDT',+ 'DOT/USDT:USDT',+ ];+ }++ /**+ * Get new listings on Gate.io (known for early listings)+ */+ async fetchNewListings(limit: number = 20) {+ try {+ await this.ensureConnected();+ const markets = await this.fetchMarkets();+ // Sort by listing date (if available) or return recent ones+ return markets+ .filter((m: any) => m.active && m.spot)+ .slice(0, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }+}diff --git a/fincept-terminal-desktop/src/brokers/crypto/gateio/index.ts b/fincept-terminal-desktop/src/brokers/crypto/gateio/index.tsnew file mode 100644index 000000000..e39333d86--- /dev/null+++ b/fincept-terminal-desktop/src/brokers/crypto/gateio/index.ts@@ -0,0 +1,8 @@+/**+ * Gate.io Exchange Module+ *+ * Professional-grade Gate.io integration+ * Known for: 1400+ trading pairs, early altcoin listings, copy trading, lending+ */++export { GateioAdapter } from './GateioAdapter';diff --git a/fincept-terminal-desktop/src/brokers/crypto/hyperliquid/HyperLiquidAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/hyperliquid/HyperLiquidAdapter.tsindex df620a879..771637362 100644--- a/fincept-terminal-desktop/src/brokers/crypto/hyperliquid/HyperLiquidAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/crypto/hyperliquid/HyperLiquidAdapter.ts@@ -321,6 +321,23 @@ export class HyperLiquidAdapter extends BaseExchangeAdapter {}}+ /**+ * Set position mode (one-way or hedge mode)+ * HyperLiquid supports both one-way and hedge mode+ */+ async setPositionMode(hedgeMode: boolean) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['setPositionMode']) {+ return await (this.exchange as any).setPositionMode(hedgeMode);+ }+ // HyperLiquid uses one-way mode by default+ return { hedgeMode, info: { message: 'Position mode set' } };+ } catch (error) {+ throw this.handleError(error);+ }+ }+/*** Fetch margin balance* Note: HyperLiquid uses unified account for perpetuals@@ -792,6 +809,13 @@ export class HyperLiquidAdapter extends BaseExchangeAdapter {}}+ /**+ * Fetch futures/perpetual markets (alias for fetchSwapMarkets for consistency)+ */+ async fetchFuturesMarkets() {+ return await this.fetchSwapMarkets();+ }+/*** Fetch spot markets*/diff --git a/fincept-terminal-desktop/src/brokers/crypto/index.ts b/fincept-terminal-desktop/src/brokers/crypto/index.tsindex 88bf98db2..dd830e2bd 100644--- a/fincept-terminal-desktop/src/brokers/crypto/index.ts+++ b/fincept-terminal-desktop/src/brokers/crypto/index.ts@@ -13,6 +13,9 @@ export { HyperLiquidAdapter } from './hyperliquid/HyperLiquidAdapter';export { BinanceAdapter } from './binance/BinanceAdapter';export { OKXAdapter } from './okx/OKXAdapter';export { CoinbaseAdapter } from './coinbase/CoinbaseAdapter';+export { BybitAdapter } from './bybit/BybitAdapter';+export { KucoinAdapter } from './kucoin/KucoinAdapter';+export { GateioAdapter } from './gateio/GateioAdapter';// Note: Paper Trading now in standalone src/paper-trading/ module@@ -22,6 +25,9 @@ import { HyperLiquidAdapter } from './hyperliquid/HyperLiquidAdapter';import { BinanceAdapter } from './binance/BinanceAdapter';import { OKXAdapter } from './okx/OKXAdapter';import { CoinbaseAdapter } from './coinbase/CoinbaseAdapter';+import { BybitAdapter } from './bybit/BybitAdapter';+import { KucoinAdapter } from './kucoin/KucoinAdapter';+import { GateioAdapter } from './gateio/GateioAdapter';import type { ExchangeConfig } from './types';export const SUPPORTED_EXCHANGES = {@@ -107,6 +113,61 @@ export const SUPPORTED_EXCHANGES = {earn: true,},},+ bybit: {+ id: 'bybit',+ name: 'Bybit',+ adapter: BybitAdapter,+ type: 'centralized',+ assetClass: 'crypto',+ region: 'global',+ features: {+ spot: true,+ margin: true,+ futures: true,+ options: true,+ perpetuals: true,+ copyTrading: true,+ earn: true,+ unifiedAccount: true,+ },+ },+ kucoin: {+ id: 'kucoin',+ name: 'KuCoin',+ adapter: KucoinAdapter,+ type: 'centralized',+ assetClass: 'crypto',+ region: 'global',+ features: {+ spot: true,+ margin: true,+ futures: true,+ options: false,+ perpetuals: true,+ lending: true,+ staking: true,+ subaccounts: true,+ },+ },+ gateio: {+ id: 'gateio',+ name: 'Gate.io',+ adapter: GateioAdapter,+ type: 'centralized',+ assetClass: 'crypto',+ region: 'global',+ features: {+ spot: true,+ margin: true,+ futures: true,+ options: true,+ perpetuals: true,+ copyTrading: true,+ lending: true,+ earn: true,+ subaccounts: true,+ },+ },} as const;export type SupportedExchangeId = keyof typeof SUPPORTED_EXCHANGES;diff --git a/fincept-terminal-desktop/src/brokers/crypto/kraken/KrakenAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/kraken/KrakenAdapter.tsindex 16fbe4b00..730126961 100644--- a/fincept-terminal-desktop/src/brokers/crypto/kraken/KrakenAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/crypto/kraken/KrakenAdapter.ts@@ -222,6 +222,25 @@ export class KrakenAdapter extends BaseExchangeAdapter {}}+ /**+ * Set position mode (one-way or hedge mode)+ * Note: Kraken Futures uses one-way mode by default+ */+ async setPositionMode(hedgeMode: boolean) {+ try {+ await this.ensureAuthenticated();+ if (!this.exchange.has['setPositionMode']) {+ // Kraken spot/margin doesn't support position mode+ // Kraken Futures uses one-way mode+ console.warn('[Kraken] setPositionMode: Kraken uses one-way position mode by default');+ return { hedgeMode: false, info: { message: 'Kraken uses one-way position mode' } };+ }+ return await (this.exchange as any).setPositionMode(hedgeMode);+ } catch (error) {+ throw this.handleError(error);+ }+ }+/*** Create margin order*/diff --git a/fincept-terminal-desktop/src/brokers/crypto/kucoin/KucoinAdapter.ts b/fincept-terminal-desktop/src/brokers/crypto/kucoin/KucoinAdapter.tsnew file mode 100644index 000000000..b5c069b4f--- /dev/null+++ b/fincept-terminal-desktop/src/brokers/crypto/kucoin/KucoinAdapter.ts@@ -0,0 +1,933 @@+/**+ * KuCoin Exchange Adapter+ *+ * Professional-grade KuCoin integration using CCXT+ * Supports: Spot, Margin, Futures (KuCoin Futures)+ *+ * KuCoin is known for wide altcoin selection and good API+ * Features: Spot, Margin (up to 10x), Futures (up to 100x), Lending, Staking+ */++import { BaseExchangeAdapter } from '../BaseExchangeAdapter';+import type {+ ExchangeConfig,+ OrderType,+ OrderSide,+ OrderParams,+ ExchangeCapabilities,+} from '../types';++export class KucoinAdapter extends BaseExchangeAdapter {+ constructor(config?: Partial<ExchangeConfig>) {+ super({+ exchange: 'kucoin',+ enableRateLimit: true,+ timeout: 30000,+ ...config,+ });+ }++ // ============================================================================+ // KUCOIN-SPECIFIC CAPABILITIES+ // ============================================================================++ getCapabilities(): ExchangeCapabilities {+ const base = super.getCapabilities();+ return {+ ...base,+ spot: true,+ margin: true,+ futures: true,+ swap: true, // Perpetual swaps via KuCoin Futures+ options: false,++ supportedOrderTypes: [+ 'market',+ 'limit',+ 'stop',+ 'stop_limit',+ ] as any,++ leverageTrading: true,+ stopOrders: true,+ conditionalOrders: true,+ algoOrders: false,++ realtimeData: true,+ historicalData: true,+ websocketSupport: true,++ multiAccount: false,+ subAccounts: true,+ portfolioMargin: false,++ rateLimits: {+ public: 100, // 100 requests per 10 seconds+ private: 200, // 200 requests per 10 seconds+ trading: 45, // 45 orders per 3 seconds+ },+ };+ }++ // ============================================================================+ // ENHANCED ORDER METHODS+ // ============================================================================++ /**+ * Create OCO (One-Cancels-Other) order+ * KuCoin supports stop orders that can act as OCO+ */+ async createOCOOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ price: number,+ stopPrice: number,+ stopLimitPrice?: number+ ) {+ try {+ await this.ensureAuthenticated();+ // KuCoin doesn't have native OCO, create both orders+ const limitOrder = await this.createOrder(symbol, 'limit', side, amount, price);+ const stopOrder = await this.createStopLossOrder(symbol, side, amount, stopPrice, stopLimitPrice);++ return {+ orderListId: `oco_${Date.now()}`,+ contingencyType: 'OCO',+ listStatusType: 'EXEC_STARTED',+ orders: [limitOrder, stopOrder],+ };+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create stop-loss order+ */+ async createStopLossOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ stopPrice: number,+ limitPrice?: number+ ) {+ const type: OrderType = limitPrice ? 'stop_limit' : 'stop';+ return await this.createOrder(symbol, type, side, amount, limitPrice, {+ stopPrice,+ stop: 'loss',+ });+ }++ /**+ * Create take-profit order+ */+ async createTakeProfitOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ stopPrice: number,+ limitPrice?: number+ ) {+ const type: OrderType = limitPrice ? 'stop_limit' : 'stop';+ return await this.createOrder(symbol, type, side, amount, limitPrice, {+ stopPrice,+ stop: 'entry',+ });+ }++ /**+ * Create trailing stop order+ * Note: KuCoin Futures supports trailing stops+ */+ async createTrailingStopOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ callbackRate: number+ ) {+ try {+ await this.ensureAuthenticated();+ // KuCoin spot doesn't have native trailing stops+ // Calculate stop price based on current price+ const ticker = await this.fetchTicker(symbol);+ const currentPrice = ticker.last || ticker.close;+ if (!currentPrice) throw new Error('Cannot determine current price');++ const stopPrice = side === 'sell'+ ? currentPrice * (1 - callbackRate / 100)+ : currentPrice * (1 + callbackRate / 100);++ return await this.createStopLossOrder(symbol, side, amount, stopPrice);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create iceberg order (hidden order)+ * KuCoin supports hidden orders+ */+ async createIcebergOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ price: number,+ visibleSize: number,+ params?: OrderParams+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.createOrder(symbol, 'limit', side, amount, price, {+ ...params,+ hidden: false,+ iceberg: true,+ visibleSize,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create reduce-only order (futures only)+ */+ async createReduceOnlyOrder(+ symbol: string,+ type: OrderType,+ side: OrderSide,+ amount: number,+ price?: number+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.createOrder(symbol, type, side, amount, price, {+ reduceOnly: true,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create post-only order (maker-only)+ */+ async createPostOnlyOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ price: number+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.createOrder(symbol, 'limit', side, amount, price, {+ postOnly: true,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create hidden order (fully hidden from order book)+ */+ async createHiddenOrder(+ symbol: string,+ side: OrderSide,+ amount: number,+ price: number+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.createOrder(symbol, 'limit', side, amount, price, {+ hidden: true,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // MARGIN & LEVERAGE TRADING+ // ============================================================================++ /**+ * Set leverage for futures+ */+ async setLeverage(symbol: string, leverage: number) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.setLeverage(leverage, symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Set margin mode (cross or isolated)+ */+ async setMarginMode(symbol: string, marginMode: 'cross' | 'isolated') {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['setMarginMode']) {+ return await this.exchange.setMarginMode(marginMode, symbol);+ }+ return { symbol, marginMode, info: { message: 'Margin mode set' } };+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Set position mode (one-way or hedge mode)+ */+ async setPositionMode(hedgeMode: boolean) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['setPositionMode']) {+ return await (this.exchange as any).setPositionMode(hedgeMode);+ }+ // KuCoin Futures uses one-way mode by default+ return { hedgeMode: false, info: { message: 'KuCoin uses one-way position mode' } };+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create margin order+ */+ async createMarginOrder(+ symbol: string,+ type: OrderType,+ side: OrderSide,+ amount: number,+ price?: number,+ params?: OrderParams+ ) {+ return await this.createOrder(symbol, type, side, amount, price, {+ ...params,+ marginMode: params?.marginMode || 'cross',+ tradeType: 'MARGIN_TRADE',+ });+ }++ /**+ * Fetch margin balance+ */+ async fetchMarginBalance() {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchBalance({ type: 'margin' });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch futures balance+ */+ async fetchFuturesBalance() {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchBalance({ type: 'future' });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Borrow margin+ */+ async borrowMargin(currency: string, amount: number, symbol?: string) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['borrowMargin']) {+ return await (this.exchange as any).borrowMargin(currency, amount, symbol);+ }+ // Use KuCoin's margin borrow API+ return await (this.exchange as any).privatePostMarginBorrow({+ currency,+ size: amount.toString(),+ ...(symbol && { symbol }),+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Repay margin+ */+ async repayMargin(currency: string, amount: number, symbol?: string) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['repayMargin']) {+ return await (this.exchange as any).repayMargin(currency, amount, symbol);+ }+ return await (this.exchange as any).privatePostMarginRepay({+ currency,+ size: amount.toString(),+ ...(symbol && { symbol }),+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // FUNDING & TRANSFERS+ // ============================================================================++ /**+ * Transfer between accounts (main, trade, margin, futures, etc.)+ */+ async transfer(+ currency: string,+ amount: number,+ fromAccount: 'main' | 'trade' | 'margin' | 'futures' | 'contract',+ toAccount: 'main' | 'trade' | 'margin' | 'futures' | 'contract'+ ) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.transfer(currency, amount, fromAccount, toAccount);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch funding rate for perpetual+ */+ async fetchFundingRate(symbol: string) {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchFundingRate(symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch funding rate history+ */+ async fetchFundingRateHistory(symbol: string, since?: number, limit?: number) {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchFundingRateHistory(symbol, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch user's funding history (payments received/paid)+ */+ async fetchFundingHistory(symbol?: string, since?: number, limit?: number) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['fetchFundingHistory']) {+ return await (this.exchange as any).fetchFundingHistory(symbol, since, limit);+ }+ // Fallback: return empty array+ return [];+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // FUTURES TRADING+ // ============================================================================++ /**+ * Fetch futures/perpetual markets+ */+ async fetchFuturesMarkets() {+ try {+ await this.ensureConnected();+ const markets = await this.fetchMarkets();+ return markets.filter((m: any) => m.future || m.swap || m.contract);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch open interest for symbol+ */+ async fetchOpenInterest(symbol: string) {+ try {+ await this.ensureConnected();+ if (!this.exchange.has['fetchOpenInterest']) {+ throw new Error('fetchOpenInterest not supported');+ }+ return await this.exchange.fetchOpenInterest(symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Add margin to position+ */+ async addMargin(symbol: string, amount: number) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['addMargin']) {+ return await this.exchange.addMargin(symbol, amount);+ }+ throw new Error('addMargin not supported');+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // ACCOUNT & FEES+ // ============================================================================++ /**+ * Fetch trading fees+ */+ async fetchTradingFees() {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchTradingFees();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch trading fee for specific symbol+ */+ async fetchTradingFee(symbol: string) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['fetchTradingFee']) {+ return await this.exchange.fetchTradingFee(symbol);+ }+ const fees = await this.fetchTradingFees();+ return fees[symbol] || null;+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch account ledger / transaction history+ */+ async fetchLedger(code?: string, since?: number, limit?: number) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchLedger(code, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch account info+ */+ async fetchAccountInfo() {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privateGetAccounts();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // DEPOSITS & WITHDRAWALS+ // ============================================================================++ /**+ * Fetch deposit address+ */+ async fetchDepositAddress(currency: string, network?: string) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchDepositAddress(currency, { network });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create deposit address+ */+ async createDepositAddress(currency: string, network?: string) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.createDepositAddress(currency, { network });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch deposits+ */+ async fetchDeposits(currency?: string, since?: number, limit?: number) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchDeposits(currency, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch withdrawals+ */+ async fetchWithdrawals(currency?: string, since?: number, limit?: number) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchWithdrawals(currency, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Withdraw funds+ */+ async withdraw(currency: string, amount: number, address: string, tag?: string, network?: string) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.withdraw(currency, amount, address, tag, { network });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // ORDER MANAGEMENT+ // ============================================================================++ /**+ * Edit existing order+ */+ async editOrder(+ orderId: string,+ symbol: string,+ type?: string,+ side?: string,+ amount?: number,+ price?: number,+ params?: any+ ) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['editOrder']) {+ return await this.exchange.editOrder(orderId, symbol, type as any, side as any, amount, price, params);+ }+ // Fallback: cancel and recreate+ await this.cancelOrder(orderId, symbol);+ return await this.createOrder(symbol, (type || 'limit') as OrderType, (side || 'buy') as OrderSide, amount!, price, params);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch my trades+ */+ async fetchMyTrades(symbol?: string, since?: number, limit?: number) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchMyTrades(symbol, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Cancel multiple orders+ */+ async cancelOrders(orderIds: string[], symbol?: string) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['cancelOrders']) {+ return await this.exchange.cancelOrders(orderIds, symbol);+ }+ // Fallback to individual cancels+ const results = [];+ for (const orderId of orderIds) {+ if (!symbol) throw new Error('Symbol required for bulk cancel');+ const result = await this.cancelOrder(orderId, symbol);+ results.push(result);+ }+ return results;+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Cancel all open orders+ */+ async cancelAllOrders(symbol?: string) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.cancelAllOrders(symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch specific order by ID+ */+ async fetchOrder(orderId: string, symbol: string) {+ try {+ await this.ensureAuthenticated();+ return await this.exchange.fetchOrder(orderId, symbol);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch multiple orders by IDs+ */+ async fetchOrdersByIds(orderIds: string[], symbol: string) {+ try {+ await this.ensureAuthenticated();+ const orders = [];+ for (const orderId of orderIds) {+ const order = await this.fetchOrder(orderId, symbol);+ orders.push(order);+ }+ return orders;+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch trades for specific order+ */+ async fetchOrderTrades(orderId: string, symbol: string) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['fetchOrderTrades']) {+ return await this.exchange.fetchOrderTrades(orderId, symbol);+ }+ // Fallback: fetch all trades and filter+ const trades = await this.fetchMyTrades(symbol);+ return trades.filter((t: any) => t.order === orderId);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Cancel all orders after timeout (Dead Man's Switch)+ */+ async cancelAllOrdersAfter(timeout: number) {+ try {+ await this.ensureAuthenticated();+ if (this.exchange.has['cancelAllOrdersAfter']) {+ return await (this.exchange as any).cancelAllOrdersAfter(timeout);+ }+ throw new Error('cancelAllOrdersAfter not supported on KuCoin');+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // HISTORICAL DATA+ // ============================================================================++ /**+ * Fetch historical OHLCV with extended options+ */+ async fetchHistoricalOHLCV(+ symbol: string,+ timeframe: '1m' | '3m' | '5m' | '15m' | '30m' | '1h' | '2h' | '4h' | '6h' | '8h' | '12h' | '1d' | '1w',+ since?: number,+ limit: number = 500+ ) {+ try {+ await this.ensureConnected();+ return await this.exchange.fetchOHLCV(symbol, timeframe, since, limit);+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch recent trades with extended data+ */+ async fetchRecentTrades(symbol: string, limit: number = 100) {+ try {+ await this.ensureConnected();+ const trades = await this.exchange.fetchTrades(symbol, undefined, limit);+ return trades.map(trade => ({+ ...trade,+ exchange: 'kucoin',+ timestamp: trade.timestamp || Date.now(),+ }));+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // KUCOIN-SPECIFIC: LENDING+ // ============================================================================++ /**+ * Fetch lending rates+ */+ async fetchLendingRates(currency?: string) {+ try {+ await this.ensureConnected();+ return await (this.exchange as any).publicGetMarginConfigCurrency({+ currency,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Create lending order+ */+ async createLendingOrder(currency: string, amount: number, dailyRate: number, term: number) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privatePostMarginLend({+ currency,+ size: amount.toString(),+ dailyIntRate: dailyRate.toString(),+ term,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Fetch active lending orders+ */+ async fetchActiveLendingOrders(currency?: string) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privateGetMarginLendActive({+ currency,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // KUCOIN-SPECIFIC: SUBACCOUNTS+ // ============================================================================++ /**+ * Fetch subaccounts+ */+ async fetchSubAccounts() {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privateGetSubAccounts();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Transfer to subaccount+ */+ async transferToSubAccount(+ currency: string,+ amount: number,+ subAccountUserId: string,+ direction: 'IN' | 'OUT'+ ) {+ try {+ await this.ensureAuthenticated();+ return await (this.exchange as any).privatePostAccountsSubTransfer({+ currency,+ amount: amount.toString(),+ subUserId: subAccountUserId,+ direction,+ });+ } catch (error) {+ throw this.handleError(error);+ }+ }++ // ============================================================================+ // UTILITIES+ // ============================================================================++ /**+ * Get KuCoin system status+ */+ async getSystemStatus() {+ try {+ return await this.fetchStatus();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Get server time+ */+ async getServerTime() {+ try {+ return await this.fetchTime();+ } catch (error) {+ throw this.handleError(error);+ }+ }++ /**+ * Get popular KuCoin trading pairs+ */+ getPopularPairs(): string[] {+ return [+ 'BTC/USDT',+ 'ETH/USDT',+ 'SOL/USDT',+ 'XRP/USDT',+ 'DOGE/USDT',+ 'ADA/USDT',+ 'AVAX/USDT',+ 'DOT/USDT',+ 'MATIC/USDT',+ 'LINK/USDT',+ 'UNI/USDT',+ 'ATOM/USDT',+ 'LTC/USDT',+ 'KCS/USDT', // KuCoin's native token+ 'PEPE/USDT',+ ];+ }++ /**+ * Get popular KuCoin Futures pairs+ */+ getPopularFuturesPairs(): string[] {+ return [+ 'BTC/USDT:USDT',+ 'ETH/USDT:USDT',+ 'SOL/USDT:USDT',+ 'XRP/USDT:USDT',+ 'DOGE/USDT:USDT',+ 'ADA/USDT:USDT',+ 'AVAX/USDT:USDT',+ 'DOT/USDT:USDT',+ 'MATIC/USDT:USDT',+ 'LINK/USDT:USDT',+ ];+ }+}diff --git a/fincept-terminal-desktop/src/brokers/crypto/kucoin/index.ts b/fincept-terminal-desktop/src/brokers/crypto/kucoin/index.tsnew file mode 100644index 000000000..75d02b400--- /dev/null+++ b/fincept-terminal-desktop/src/brokers/crypto/kucoin/index.ts@@ -0,0 +1,8 @@+/**+ * KuCoin Exchange Module+ *+ * Professional-grade KuCoin integration+ * Known for wide altcoin selection and good API+ */++export { KucoinAdapter } from './KucoinAdapter';diff --git a/fincept-terminal-desktop/src/brokers/registry.ts b/fincept-terminal-desktop/src/brokers/registry.tsindex 5acbba6c4..b20d509a2 100644--- a/fincept-terminal-desktop/src/brokers/registry.ts+++ b/fincept-terminal-desktop/src/brokers/registry.ts@@ -10,6 +10,9 @@ import { HyperLiquidAdapter } from './crypto/hyperliquid/HyperLiquidAdapter';import { BinanceAdapter } from './crypto/binance/BinanceAdapter';import { OKXAdapter } from './crypto/okx/OKXAdapter';import { CoinbaseAdapter } from './crypto/coinbase/CoinbaseAdapter';+import { BybitAdapter } from './crypto/bybit/BybitAdapter';+import { KucoinAdapter } from './crypto/kucoin/KucoinAdapter';+import { GateioAdapter } from './crypto/gateio/GateioAdapter';import { ZerodhaAdapter } from './india/zerodha/ZerodhaAdapter';import { FyersAdapter } from './stocks/india/fyers/FyersAdapter';import type { IExchangeAdapter, ExchangeConfig } from './crypto/types';@@ -414,6 +417,213 @@ export const BROKER_REGISTRY: Record<string, BrokerMetadata> = {},},+ bybit: {+ id: 'bybit',+ name: 'bybit',+ displayName: 'Bybit',+ type: 'crypto',+ category: 'centralized',+ region: 'global',+ adapterClass: BybitAdapter,++ features: {+ spot: true,+ margin: true,+ futures: true,+ perpetuals: true,+ options: true,+ staking: false,+ vaults: false,+ subaccounts: true,+ },++ tradingFeatures: {+ marketOrders: true,+ limitOrders: true,+ stopOrders: true,+ stopLimitOrders: true,+ trailingStopOrders: true,+ icebergOrders: true,+ batchOrders: true,+ editOrders: true,+ },++ advancedFeatures: {+ leverage: true,+ maxLeverage: 100,+ marginMode: true,+ transfers: true,+ withdrawals: true,+ deposits: true,+ },++ defaultSymbols: [+ 'BTC/USDT',+ 'ETH/USDT',+ 'SOL/USDT',+ 'XRP/USDT',+ 'DOGE/USDT',+ 'ADA/USDT',+ 'AVAX/USDT',+ 'DOT/USDT',+ 'MATIC/USDT',+ 'LINK/USDT',+ 'UNI/USDT',+ 'ATOM/USDT',+ 'LTC/USDT',+ 'OP/USDT',+ 'ARB/USDT',+ ],++ websocket: {+ enabled: true,+ endpoint: 'wss://stream.bybit.com/v5/public/spot',+ },++ fees: {+ maker: 0.001,+ taker: 0.001,+ },+ },++ kucoin: {+ id: 'kucoin',+ name: 'kucoin',+ displayName: 'KuCoin',+ type: 'crypto',+ category: 'centralized',+ region: 'global',+ adapterClass: KucoinAdapter,++ features: {+ spot: true,+ margin: true,+ futures: true,+ perpetuals: true,+ options: false,+ staking: true,+ vaults: false,+ subaccounts: true,+ },++ tradingFeatures: {+ marketOrders: true,+ limitOrders: true,+ stopOrders: true,+ stopLimitOrders: true,+ trailingStopOrders: false,+ icebergOrders: true,+ batchOrders: true,+ editOrders: true,+ },++ advancedFeatures: {+ leverage: true,+ maxLeverage: 100,+ marginMode: true,+ transfers: true,+ withdrawals: true,+ deposits: true,+ },++ defaultSymbols: [+ 'BTC/USDT',+ 'ETH/USDT',+ 'SOL/USDT',+ 'XRP/USDT',+ 'DOGE/USDT',+ 'ADA/USDT',+ 'AVAX/USDT',+ 'DOT/USDT',+ 'MATIC/USDT',+ 'LINK/USDT',+ 'UNI/USDT',+ 'ATOM/USDT',+ 'LTC/USDT',+ 'KCS/USDT',+ 'PEPE/USDT',+ ],++ websocket: {+ enabled: true,+ endpoint: 'wss://ws-api-spot.kucoin.com',+ },++ fees: {+ maker: 0.001,+ taker: 0.001,+ },+ },++ gateio: {+ id: 'gateio',+ name: 'gateio',+ displayName: 'Gate.io',+ type: 'crypto',+ category: 'centralized',+ region: 'global',+ adapterClass: GateioAdapter,++ features: {+ spot: true,+ margin: true,+ futures: true,+ perpetuals: true,+ options: true,+ staking: true,+ vaults: false,+ subaccounts: true,+ },++ tradingFeatures: {+ marketOrders: true,+ limitOrders: true,+ stopOrders: true,+ stopLimitOrders: true,+ trailingStopOrders: true,+ icebergOrders: true,+ batchOrders: true,+ editOrders: true,+ },++ advancedFeatures: {+ leverage: true,+ maxLeverage: 100,+ marginMode: true,+ transfers: true,+ withdrawals: true,+ deposits: true,+ },++ defaultSymbols: [+ 'BTC/USDT',+ 'ETH/USDT',+ 'SOL/USDT',+ 'XRP/USDT',+ 'DOGE/USDT',+ 'ADA/USDT',+ 'AVAX/USDT',+ 'DOT/USDT',+ 'MATIC/USDT',+ 'LINK/USDT',+ 'UNI/USDT',+ 'ATOM/USDT',+ 'LTC/USDT',+ 'GT/USDT',+ 'SHIB/USDT',+ ],++ websocket: {+ enabled: true,+ endpoint: 'wss://ws.gate.io/v4',+ },++ fees: {+ maker: 0.002, // 0.2% standard, VIP tiers reduce+ taker: 0.002,+ },+ },+// ============================================================================// INDIAN STOCK BROKERS// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/BaseStockBrokerAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/BaseStockBrokerAdapter.tsindex 9d2be9b5c..a18ffd976 100644--- a/fincept-terminal-desktop/src/brokers/stocks/BaseStockBrokerAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/BaseStockBrokerAdapter.ts@@ -63,6 +63,7 @@ export abstract class BaseStockBrokerAdapter implements IStockBrokerAdapter {protected wsConnected: boolean = false;protected wsConfig: WebSocketConfig | null = null;protected tickCallbacks: Set<(tick: TickData) => void> = new Set();+ protected depthCallbacks: Set<(depth: MarketDepth & { symbol: string; exchange: StockExchange }) => void> = new Set();protected subscriptions: Map<string, { symbol: string; exchange: StockExchange; mode: SubscriptionMode }> = new Map();// Rate limiting@@ -190,7 +191,7 @@ export abstract class BaseStockBrokerAdapter implements IStockBrokerAdapter {}}- protected async loadCredentials(): Promise<BrokerCredentials | null> {+ protected async loadCredentials(): Promise<(BrokerCredentials & { tokenTimestamp?: number; userId?: string }) | null> {try {console.log(`[${this.brokerId}] Loading credentials from Rust backend...`);const response = await invoke<{@@ -199,6 +200,8 @@ export abstract class BaseStockBrokerAdapter implements IStockBrokerAdapter {apiKey?: string;apiSecret?: string;accessToken?: string;+ userId?: string;+ tokenTimestamp?: number;additionalData?: string;};}>('get_indian_broker_credentials', {@@ -209,8 +212,8 @@ export abstract class BaseStockBrokerAdapter implements IStockBrokerAdapter {success: response.success,hasData: !!response.data,hasApiKey: !!(response.data?.apiKey),- hasApiSecret: !!(response.data?.apiSecret),- apiKeyLength: response.data?.apiKey?.length || 0,+ hasAccessToken: !!(response.data?.accessToken),+ tokenTimestamp: response.data?.tokenTimestamp,});if (!response.success || !response.data) {@@ -222,9 +225,11 @@ export abstract class BaseStockBrokerAdapter implements IStockBrokerAdapter {apiKey: response.data.apiKey || '',apiSecret: response.data.apiSecret,accessToken: response.data.accessToken,+ userId: response.data.userId,+ tokenTimestamp: response.data.tokenTimestamp,};- console.log(`[${this.brokerId}] ✓ Credentials loaded successfully`);+ console.log(`[${this.brokerId}] ✓ Credentials loaded successfully (token from: ${creds.tokenTimestamp ? new Date(creds.tokenTimestamp).toISOString() : 'N/A'})`);return creds;} catch (error) {console.error(`[${this.brokerId}] Failed to load credentials:`, error);@@ -242,6 +247,38 @@ export abstract class BaseStockBrokerAdapter implements IStockBrokerAdapter {}}+ /**+ * Check if token was generated today (IST timezone)+ * Indian broker tokens expire at midnight IST+ * This is a static utility that can be used for session validation+ */+ public static isTokenValidForTodayIST(tokenTimestamp?: number): boolean {+ if (!tokenTimestamp) return false;++ // Get current time in IST+ const now = new Date();+ const istOffset = 5.5 * 60 * 60 * 1000; // IST is UTC+5:30+ const nowIST = new Date(now.getTime() + istOffset + now.getTimezoneOffset() * 60 * 1000);++ // Get token time in IST+ const tokenDate = new Date(tokenTimestamp);+ const tokenIST = new Date(tokenDate.getTime() + istOffset + tokenDate.getTimezoneOffset() * 60 * 1000);++ // Check if same day in IST+ return (+ nowIST.getFullYear() === tokenIST.getFullYear() &&+ nowIST.getMonth() === tokenIST.getMonth() &&+ nowIST.getDate() === tokenIST.getDate()+ );+ }++ /**+ * Instance method that calls the static version+ */+ public isTokenValidForToday(tokenTimestamp?: number): boolean {+ return BaseStockBrokerAdapter.isTokenValidForTodayIST(tokenTimestamp);+ }+// ============================================================================// Rate Limiting// ============================================================================@@ -520,6 +557,25 @@ export abstract class BaseStockBrokerAdapter implements IStockBrokerAdapter {}}+ // Depth event handlers+ onDepth(callback: (depth: MarketDepth & { symbol: string; exchange: StockExchange }) => void): void {+ this.depthCallbacks.add(callback);+ }++ offDepth(callback: (depth: MarketDepth & { symbol: string; exchange: StockExchange }) => void): void {+ this.depthCallbacks.delete(callback);+ }++ protected emitDepth(depth: MarketDepth & { symbol: string; exchange: StockExchange }): void {+ for (const callback of this.depthCallbacks) {+ try {+ callback(depth);+ } catch (error) {+ console.error(`[${this.brokerId}] Depth callback error:`, error);+ }+ }+ }+// ============================================================================// Master Contract (Optional - subclasses can override)// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/aliceblue/AliceBlueAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/aliceblue/AliceBlueAdapter.tsindex ab484d2d0..6feb05c9f 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/aliceblue/AliceBlueAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/aliceblue/AliceBlueAdapter.ts@@ -5,6 +5,7 @@*/import { invoke } from '@tauri-apps/api/core';+import { listen, UnlistenFn } from '@tauri-apps/api/event';import { BaseStockBrokerAdapter } from '../../BaseStockBrokerAdapter';import type {StockBrokerMetadata,@@ -65,9 +66,15 @@ export class AliceBlueAdapter extends BaseStockBrokerAdapter {private encKey: string | null = null;private sessionId: string | null = null;- // REST API polling for quotes+ // Tauri event unlisteners for WebSocket events+ private tickerUnlisten: UnlistenFn | null = null;+ private orderbookUnlisten: UnlistenFn | null = null;+ private statusUnlisten: UnlistenFn | null = null;++ // Fallback: REST API polling for quotesprivate quotePollingInterval: NodeJS.Timeout | null = null;private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange }> = new Map();+ private usePollingFallback: boolean = false;// ============================================================================// Authentication@@ -613,87 +620,128 @@ export class AliceBlueAdapter extends BaseStockBrokerAdapter {}// ============================================================================- // REST API Polling (replaces WebSocket)+ // WebSocket - Real WebSocket via Rust Backend// ============================================================================protected async connectWebSocketInternal(config: WebSocketConfig): Promise<void> {this.ensureConnected();try {- // Start REST API polling- this.startQuotePolling();- this.wsConnected = true;- console.log('AliceBlue: REST API polling started (2 min interval)');+ await this.connectRealWebSocket();+ console.log('[AliceBlue] ✓ WebSocket connected via Rust backend');} catch (error) {- console.error('Failed to start AliceBlue polling:', error);- throw error;+ console.warn('[AliceBlue] WebSocket connection failed, falling back to REST polling:', error);+ this.usePollingFallback = true;+ this.startQuotePolling();}}- /**- * Start REST API polling for quotes- */- private startQuotePolling(): void {- this.stopQuotePolling();+ private async connectRealWebSocket(): Promise<void> {+ if (!this.accessToken || !this.userId) {+ throw new Error('Access token and user ID required');+ }++ const result = await invoke<{ success: boolean; data?: boolean; error?: string }>('aliceblue_ws_connect', {+ userId: this.userId,+ accessToken: this.accessToken,+ });++ if (!result.success) throw new Error(result.error || 'WebSocket connection failed');++ this.tickerUnlisten = await listen<{+ provider: string; symbol: string; price: number; bid?: number; ask?: number;+ volume?: number; change_percent?: number; timestamp: number;+ }>('aliceblue_ticker', (event) => {+ const tick = event.payload;+ this.emitTick({+ symbol: tick.symbol, exchange: 'NSE' as StockExchange, mode: 'quote',+ lastPrice: tick.price, bid: tick.bid, ask: tick.ask,+ volume: tick.volume || 0, changePercent: tick.change_percent || 0, timestamp: tick.timestamp,+ });+ });- // Poll every 2 minutes (120000ms)- this.quotePollingInterval = setInterval(async () => {- await this.pollQuotesSequentially();- }, 120000);+ this.orderbookUnlisten = await listen<{+ provider: string; symbol: string;+ bids: Array<{ price: number; quantity: number; orders?: number }>; asks: Array<{ price: number; quantity: number; orders?: number }>;+ timestamp: number;+ }>('aliceblue_orderbook', (event) => {+ const data = event.payload;+ const [exchangePart, symbolPart] = data.symbol.includes(':') ? data.symbol.split(':') : ['NSE', data.symbol];+ const symbol = symbolPart || data.symbol;+ const exchange = (exchangePart as StockExchange) || 'NSE';++ console.log(`[AliceBlue WebSocket] Depth update for ${symbol}`);++ const bestBid = data.bids?.[0];+ const bestAsk = data.asks?.[0];++ const tick: TickData = {+ symbol, exchange, mode: 'full',+ lastPrice: bestBid?.price || 0,+ bid: bestBid?.price, ask: bestAsk?.price,+ bidQty: bestBid?.quantity, askQty: bestAsk?.quantity,+ timestamp: data.timestamp,+ depth: {+ bids: data.bids?.map((b) => ({ price: b.price, quantity: b.quantity, orders: b.orders || 0 })) || [],+ asks: data.asks?.map((a) => ({ price: a.price, quantity: a.quantity, orders: a.orders || 0 })) || [],+ },+ };- // Initial poll+ this.emitTick(tick);+ if (tick.depth) {+ this.emitDepth({ symbol, exchange, bids: tick.depth.bids, asks: tick.depth.asks });+ }+ });++ this.statusUnlisten = await listen<{+ provider: string; status: string; message?: string; timestamp: number;+ }>('aliceblue_status', (event) => {+ const status = event.payload;+ if (status.status === 'disconnected' || status.status === 'error') {+ this.wsConnected = false;+ if (!this.usePollingFallback) { this.usePollingFallback = true; this.startQuotePolling(); }+ } else if (status.status === 'connected') {+ this.wsConnected = true;+ if (this.usePollingFallback) { this.usePollingFallback = false; this.stopQuotePolling(); }+ }+ });++ this.wsConnected = true;+ }++ private async disconnectRealWebSocket(): Promise<void> {+ if (this.tickerUnlisten) { this.tickerUnlisten(); this.tickerUnlisten = null; }+ if (this.orderbookUnlisten) { this.orderbookUnlisten(); this.orderbookUnlisten = null; }+ if (this.statusUnlisten) { this.statusUnlisten(); this.statusUnlisten = null; }+ try { await invoke('aliceblue_ws_disconnect'); } catch (err) { console.warn('[AliceBlue] WS disconnect error:', err); }+ this.wsConnected = false;+ }++ private startQuotePolling(): void {+ this.stopQuotePolling();+ console.log('[AliceBlue] Starting REST API polling (fallback mode, 2 min interval)');+ this.quotePollingInterval = setInterval(async () => { await this.pollQuotesSequentially(); }, 120000);this.pollQuotesSequentially();}- /**- * Stop REST API polling- */private stopQuotePolling(): void {- if (this.quotePollingInterval) {- clearInterval(this.quotePollingInterval);- this.quotePollingInterval = null;- }+ if (this.quotePollingInterval) { clearInterval(this.quotePollingInterval); this.quotePollingInterval = null; }}- /**- * Poll quotes sequentially for all subscribed symbols- */private async pollQuotesSequentially(): Promise<void> {- if (this.pollingSymbols.size === 0) {- return;- }-- console.log(`[AliceBlue] Polling ${this.pollingSymbols.size} symbols sequentially...`);+ if (this.pollingSymbols.size === 0) return;for (const [key, { symbol, exchange }] of this.pollingSymbols) {try {const quote = await this.getQuoteInternal(symbol, exchange);-- const tick: TickData = {- symbol,- exchange,- mode: 'full',- lastPrice: quote.lastPrice,- open: quote.open,- high: quote.high,- low: quote.low,- close: quote.close,- volume: quote.volume,- change: quote.change,- changePercent: quote.changePercent,- timestamp: quote.timestamp,- bid: quote.bid,- bidQty: quote.bidQty,- ask: quote.ask,- askQty: quote.askQty,- };-- this.emitTick(tick);- } catch (error) {- console.error(`[AliceBlue] Failed to poll ${symbol}:`, error);- }-- // Small delay between requests to avoid rate limiting+ this.emitTick({+ symbol, exchange, mode: 'full',+ lastPrice: quote.lastPrice, open: quote.open, high: quote.high, low: quote.low,+ close: quote.close, volume: quote.volume, change: quote.change,+ changePercent: quote.changePercent, timestamp: quote.timestamp,+ bid: quote.bid, bidQty: quote.bidQty, ask: quote.ask, askQty: quote.askQty,+ });+ } catch (error) { console.error(`[AliceBlue] Failed to poll ${symbol}:`, error); }await new Promise(resolve => setTimeout(resolve, 100));}@@ -704,10 +752,11 @@ export class AliceBlueAdapter extends BaseStockBrokerAdapter {* Disconnect from WebSocket (stop polling)*/async disconnectWebSocket(): Promise<void> {+ await this.disconnectRealWebSocket();this.stopQuotePolling();this.pollingSymbols.clear();- this.wsConnected = false;- console.log('[AliceBlue] REST API polling stopped');+ this.usePollingFallback = false;+ console.log('[AliceBlue] WebSocket disconnected');}protected async subscribeInternal(@@ -719,10 +768,22 @@ export class AliceBlueAdapter extends BaseStockBrokerAdapter {const key = `${exchange}:${symbol}`;this.pollingSymbols.set(key, { symbol, exchange });- console.log(`AliceBlue: Added ${key} to polling list (${this.pollingSymbols.size} symbols total)`);-- // Trigger immediate poll for this symbol- this.pollQuotesSequentially();+ // If real WebSocket is connected, subscribe via Tauri command+ if (this.wsConnected && !this.usePollingFallback) {+ try {+ await invoke('aliceblue_ws_subscribe', {+ symbol: `${exchange}:${symbol}`,+ mode: mode === 'full' ? 'depth' : mode === 'quote' ? 'quotes' : 'ltp',+ });+ console.log(`[AliceBlue] WebSocket subscribed to ${key}`);+ } catch (err) {+ console.warn(`[AliceBlue] WebSocket subscribe failed for ${key}, using polling:`, err);+ }+ } else {+ console.log(`AliceBlue: Added ${key} to polling list (${this.pollingSymbols.size} symbols total)`);+ // Trigger immediate poll for this symbol+ this.pollQuotesSequentially();+ }} catch (error) {console.error('Failed to subscribe:', error);throw error;@@ -733,7 +794,17 @@ export class AliceBlueAdapter extends BaseStockBrokerAdapter {const key = `${exchange}:${symbol}`;this.pollingSymbols.delete(key);- console.log(`AliceBlue: Removed ${key} from polling list (${this.pollingSymbols.size} symbols remaining)`);+ // If real WebSocket is connected, unsubscribe via Tauri command+ if (this.wsConnected && !this.usePollingFallback) {+ try {+ await invoke('aliceblue_ws_unsubscribe', { symbol: `${exchange}:${symbol}` });+ console.log(`[AliceBlue] WebSocket unsubscribed from ${key}`);+ } catch (err) {+ console.warn(`[AliceBlue] WebSocket unsubscribe failed for ${key}:`, err);+ }+ } else {+ console.log(`AliceBlue: Removed ${key} from polling list (${this.pollingSymbols.size} symbols remaining)`);+ }}// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/angelone/AngelOneAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/AngelOneAdapter.tsindex e6bbe53bd..4965385db 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/angelone/AngelOneAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/AngelOneAdapter.ts@@ -75,16 +75,19 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {private password: string | null = null;private feedToken: string | null = null;- // REST API polling for quotes+ // Tauri event unlisteners for WebSocket events+ private tickerUnlisten: UnlistenFn | null = null;+ private orderbookUnlisten: UnlistenFn | null = null;+ private statusUnlisten: UnlistenFn | null = null;++ // Fallback: REST API polling for quotes (when WebSocket fails)private quotePollingInterval: NodeJS.Timeout | null = null;private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange }> = new Map();+ private usePollingFallback: boolean = false;// Token to symbol mappingprivate tokenSymbolMap: Map<string, { symbol: string; exchange: StockExchange }> = new Map();- // Tauri event unlisteners- private eventUnlisteners: UnlistenFn[] = [];-// ============================================================================// Authentication// ============================================================================@@ -920,26 +923,197 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {}// ============================================================================- // WebSocket / Polling+ // WebSocket - Real WebSocket via Rust Backend// ============================================================================protected async connectWebSocketInternal(config: WebSocketConfig): Promise<void> {this.ensureConnected();try {- // Start REST API polling (Angel One rate limit: 1 req/sec)- this.startQuotePolling();- this.wsConnected = true;- console.log('[AngelOne] REST API polling started');+ // Try real WebSocket connection via Rust backend+ await this.connectRealWebSocket();+ console.log('[AngelOne] ✓ WebSocket connected via Rust backend');} catch (error) {- console.error('[AngelOne] Failed to start polling:', error);- throw error;+ console.warn('[AngelOne] WebSocket connection failed, falling back to REST polling:', error);+ this.usePollingFallback = true;+ this.startQuotePolling();+ }+ }++ /**+ * Connect to real Angel One WebSocket via Tauri/Rust backend+ */+ private async connectRealWebSocket(): Promise<void> {+ if (!this.accessToken || !this.apiKey || !this.feedToken) {+ throw new Error('Access token, API key, and feed token required');+ }++ // Call Rust backend to connect WebSocket+ const result = await invoke<{+ success: boolean;+ data?: boolean;+ error?: string;+ }>('angelone_ws_connect', {+ apiKey: this.apiKey,+ clientCode: this.clientCode || this.userId || '',+ feedToken: this.feedToken,+ });++ if (!result.success) {+ throw new Error(result.error || 'WebSocket connection failed');+ }++ // Listen for ticker events from Rust backend+ this.tickerUnlisten = await listen<{+ provider: string;+ symbol: string;+ price: number;+ bid?: number;+ ask?: number;+ volume?: number;+ change_percent?: number;+ timestamp: number;+ }>('angelone_ticker', (event) => {+ const tick = event.payload;++ // Lookup symbol from token map+ const symbolInfo = this.tokenSymbolMap.get(tick.symbol);++ this.emitTick({+ symbol: symbolInfo?.symbol || tick.symbol,+ exchange: symbolInfo?.exchange || ('NSE' as StockExchange),+ mode: 'quote',+ lastPrice: tick.price,+ bid: tick.bid,+ ask: tick.ask,+ volume: tick.volume || 0,+ changePercent: tick.change_percent || 0,+ timestamp: tick.timestamp,+ });+ });++ // Listen for orderbook/depth events+ this.orderbookUnlisten = await listen<{+ provider: string;+ symbol: string;+ bids: Array<{ price: number; quantity: number; orders?: number }>;+ asks: Array<{ price: number; quantity: number; orders?: number }>;+ timestamp: number;+ }>('angelone_orderbook', (event) => {+ const data = event.payload;++ // Parse symbol from AngelOne format (e.g., "NSE:RELIANCE-EQ" -> "RELIANCE")+ const [exchangePart, symbolPart] = data.symbol.includes(':')+ ? data.symbol.split(':')+ : ['NSE', data.symbol];+ const symbol = symbolPart?.replace('-EQ', '') || data.symbol;+ const exchange = (exchangePart as StockExchange) || 'NSE';++ console.log(`[AngelOne WebSocket] Depth update for ${symbol}:`, {+ bids: data.bids?.length || 0,+ asks: data.asks?.length || 0,+ });++ // Get best bid/ask from depth+ const bestBid = data.bids?.[0];+ const bestAsk = data.asks?.[0];++ // Create tick data with depth information+ const tick: TickData = {+ symbol,+ exchange,+ mode: 'full',+ lastPrice: bestBid?.price || 0,+ bid: bestBid?.price,+ ask: bestAsk?.price,+ bidQty: bestBid?.quantity,+ askQty: bestAsk?.quantity,+ timestamp: data.timestamp,+ depth: {+ bids: data.bids?.map((b) => ({+ price: b.price,+ quantity: b.quantity,+ orders: b.orders || 0,+ })) || [],+ asks: data.asks?.map((a) => ({+ price: a.price,+ quantity: a.quantity,+ orders: a.orders || 0,+ })) || [],+ },+ };++ this.emitTick(tick);++ // Also emit depth data separately for UI components+ if (tick.depth) {+ this.emitDepth({+ symbol,+ exchange,+ bids: tick.depth.bids,+ asks: tick.depth.asks,+ });+ }+ });++ // Listen for status/connection events+ this.statusUnlisten = await listen<{+ provider: string;+ status: string;+ message?: string;+ timestamp: number;+ }>('angelone_status', (event) => {+ const status = event.payload;+ console.log(`[AngelOne WebSocket] Status: ${status.status} - ${status.message || ''}`);++ if (status.status === 'disconnected' || status.status === 'error') {+ this.wsConnected = false;+ if (!this.usePollingFallback) {+ console.warn('[AngelOne] WebSocket disconnected, enabling polling fallback');+ this.usePollingFallback = true;+ this.startQuotePolling();+ }+ } else if (status.status === 'connected') {+ this.wsConnected = true;+ if (this.usePollingFallback) {+ console.log('[AngelOne] WebSocket reconnected, disabling polling fallback');+ this.usePollingFallback = false;+ this.stopQuotePolling();+ }+ }+ });++ this.wsConnected = true;+ }++ private async disconnectRealWebSocket(): Promise<void> {+ if (this.tickerUnlisten) {+ this.tickerUnlisten();+ this.tickerUnlisten = null;+ }+ if (this.orderbookUnlisten) {+ this.orderbookUnlisten();+ this.orderbookUnlisten = null;+ }+ if (this.statusUnlisten) {+ this.statusUnlisten();+ this.statusUnlisten = null;}++ try {+ await invoke('angelone_ws_disconnect');+ } catch (err) {+ console.warn('[AngelOne] WebSocket disconnect error:', err);+ }++ this.wsConnected = false;}private startQuotePolling(): void {this.stopQuotePolling();+ console.log('[AngelOne] Starting REST API polling (fallback mode, 2 min interval)');+// Poll every 2 minutes (to stay within rate limits)this.quotePollingInterval = setInterval(async () => {await this.pollQuotesSequentially();@@ -997,10 +1171,12 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {}async disconnectWebSocket(): Promise<void> {+ await this.disconnectRealWebSocket();this.stopQuotePolling();this.pollingSymbols.clear();+ this.usePollingFallback = false;this.wsConnected = false;- console.log('[AngelOne] Polling stopped');+ console.log('[AngelOne] WebSocket disconnected');}protected async subscribeInternal(@@ -1010,16 +1186,69 @@ export class AngelOneAdapter extends BaseStockBrokerAdapter {): Promise<void> {const key = `${exchange}:${symbol}`;this.pollingSymbols.set(key, { symbol, exchange });- console.log(`[AngelOne] Added ${key} to polling (${this.pollingSymbols.size} total)`);- // Trigger immediate poll- this.pollQuotesSequentially();+ // Get token and store in map for lookup+ const instrument = await this.getInstrument(symbol, exchange);+ const token = instrument?.token || '0';+ this.tokenSymbolMap.set(token, { symbol, exchange });++ if (this.wsConnected && !this.usePollingFallback) {+ try {+ const wsMode = toAngelOneWSMode(mode);++ await invoke('angelone_ws_subscribe', {+ symbol: token,+ exchange: ANGELONE_EXCHANGE_MAP[exchange] || exchange,+ mode: wsMode,+ });++ console.log(`[AngelOne] ✓ WebSocket subscribed to ${symbol} (token: ${token}, mode: ${wsMode})`);+ } catch (error) {+ console.error(`[AngelOne] WebSocket subscribe failed:`, error);+ if (!this.usePollingFallback) {+ this.usePollingFallback = true;+ this.startQuotePolling();+ }+ }+ } else {+ console.log(`[AngelOne] Added ${key} to polling (${this.pollingSymbols.size} total)`);+ if (this.usePollingFallback) {+ this.pollQuotesSequentially();+ }+ }}protected async unsubscribeInternal(symbol: string, exchange: StockExchange): Promise<void> {const key = `${exchange}:${symbol}`;this.pollingSymbols.delete(key);- console.log(`[AngelOne] Removed ${key} from polling`);++ // Get token+ const instrument = await this.getInstrument(symbol, exchange);+ const token = instrument?.token || '0';+ this.tokenSymbolMap.delete(token);++ if (this.wsConnected && !this.usePollingFallback) {+ try {+ await invoke('angelone_ws_unsubscribe', {+ symbol: token,+ exchange: ANGELONE_EXCHANGE_MAP[exchange] || exchange,+ });+ console.log(`[AngelOne] ✓ WebSocket unsubscribed from ${symbol}`);+ } catch (error) {+ console.warn(`[AngelOne] WebSocket unsubscribe failed:`, error);+ }+ } else {+ console.log(`[AngelOne] Removed ${key} from polling`);+ }+ }++ async logout(): Promise<void> {+ await this.disconnectRealWebSocket();+ this.stopQuotePolling();+ this.pollingSymbols.clear();+ this.tokenSymbolMap.clear();+ this.usePollingFallback = false;+ await super.logout();}// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/angelone/constants.ts b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/constants.tsindex 7c8f6fb95..68760225e 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/angelone/constants.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/angelone/constants.ts@@ -262,9 +262,17 @@ export const ANGELONE_METADATA: StockBrokerMetadata = {},defaultSymbols: [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',+ // NIFTY 50 Components (Jan 2025)+ 'HDFCBANK', 'ICICIBANK', 'SBIN', 'KOTAKBANK', 'AXISBANK',+ 'BAJFINANCE', 'BAJAJFINSV', 'HDFCLIFE', 'SBILIFE', 'INDUSINDBK',+ 'TCS', 'INFY', 'WIPRO', 'HCLTECH', 'TECHM', 'LTIM',+ 'RELIANCE', 'ONGC', 'NTPC', 'POWERGRID', 'ADANIPORTS', 'ADANIENT',+ 'MARUTI', 'TATAMOTORS', 'M&M', 'BAJAJ-AUTO', 'HEROMOTOCO', 'EICHERMOT',+ 'HINDUNILVR', 'ITC', 'NESTLEIND', 'BRITANNIA', 'TATACONSUM',+ 'TATASTEEL', 'JSWSTEEL', 'HINDALCO', 'COALINDIA',+ 'SUNPHARMA', 'DRREDDY', 'CIPLA', 'APOLLOHOSP', 'DIVISLAB',+ 'LT', 'BHARTIARTL', 'ULTRACEMCO', 'GRASIM', 'TITAN',+ 'ASIANPAINT', 'BPCL', 'SHRIRAMFIN', 'TRENT',],};diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/dhan/DhanAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/dhan/DhanAdapter.tsindex 7e6771308..dd3745322 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/dhan/DhanAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/dhan/DhanAdapter.ts@@ -6,6 +6,7 @@*/import { invoke } from '@tauri-apps/api/core';+import { listen, UnlistenFn } from '@tauri-apps/api/event';import { BaseStockBrokerAdapter } from '../../BaseStockBrokerAdapter';import type {StockBrokerMetadata,@@ -62,9 +63,15 @@ export class DhanAdapter extends BaseStockBrokerAdapter {private apiSecret: string | null = null;private clientId: string | null = null;- // REST API polling for quotes+ // Tauri event unlisteners for WebSocket events+ private tickerUnlisten: UnlistenFn | null = null;+ private orderbookUnlisten: UnlistenFn | null = null;+ private statusUnlisten: UnlistenFn | null = null;++ // Fallback: REST API polling for quotes (when WebSocket fails)private quotePollingInterval: NodeJS.Timeout | null = null;private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange }> = new Map();+ private usePollingFallback: boolean = false;// ============================================================================// Authentication@@ -784,25 +791,179 @@ export class DhanAdapter extends BaseStockBrokerAdapter {}// ============================================================================- // WebSocket / Polling+ // WebSocket - Real WebSocket via Rust Backend// ============================================================================protected async connectWebSocketInternal(config: WebSocketConfig): Promise<void> {this.ensureConnected();try {- this.startQuotePolling();- this.wsConnected = true;- console.log('[Dhan] REST API polling started');+ // Try real WebSocket connection via Rust backend+ await this.connectRealWebSocket();+ console.log('[Dhan] ✓ WebSocket connected via Rust backend');} catch (error) {- console.error('[Dhan] Failed to start polling:', error);- throw error;+ console.warn('[Dhan] WebSocket connection failed, falling back to REST polling:', error);+ this.usePollingFallback = true;+ this.startQuotePolling();+ }+ }++ /**+ * Connect to real Dhan WebSocket via Tauri/Rust backend+ */+ private async connectRealWebSocket(): Promise<void> {+ if (!this.accessToken || !this.clientId) {+ throw new Error('Access token and client ID not available');+ }++ // Call Rust backend to connect WebSocket+ const result = await invoke<{+ success: boolean;+ data?: boolean;+ error?: string;+ }>('dhan_ws_connect', {+ clientId: this.clientId,+ accessToken: this.accessToken,+ is20Depth: false, // Use 5-level depth by default+ });++ if (!result.success) {+ throw new Error(result.error || 'WebSocket connection failed');+ }++ // Listen for ticker events from Rust backend+ this.tickerUnlisten = await listen<{+ provider: string;+ symbol: string;+ price: number;+ bid?: number;+ ask?: number;+ volume?: number;+ change_percent?: number;+ timestamp: number;+ }>('dhan_ticker', (event) => {+ const tick = event.payload;++ // Parse symbol (format depends on Dhan - usually security_id)+ this.emitTick({+ symbol: tick.symbol,+ exchange: 'NSE' as StockExchange, // Will be parsed from actual data+ mode: 'quote',+ lastPrice: tick.price,+ bid: tick.bid,+ ask: tick.ask,+ volume: tick.volume || 0,+ changePercent: tick.change_percent || 0,+ timestamp: tick.timestamp,+ });+ });++ // Listen for orderbook/depth events+ this.orderbookUnlisten = await listen<{+ provider: string;+ symbol: string;+ bids: Array<{ price: number; quantity: number; orders?: number }>;+ asks: Array<{ price: number; quantity: number; orders?: number }>;+ timestamp: number;+ }>('dhan_orderbook', (event) => {+ const data = event.payload;++ // Parse symbol from Dhan format+ const [exchangePart, symbolPart] = data.symbol.includes(':')+ ? data.symbol.split(':')+ : ['NSE', data.symbol];+ const symbol = symbolPart || data.symbol;+ const exchange = (exchangePart as StockExchange) || 'NSE';++ console.log(`[Dhan WebSocket] Depth update for ${symbol}:`, {+ bids: data.bids?.length || 0,+ asks: data.asks?.length || 0,+ });++ const bestBid = data.bids?.[0];+ const bestAsk = data.asks?.[0];++ const tick: TickData = {+ symbol,+ exchange,+ mode: 'full',+ lastPrice: bestBid?.price || 0,+ bid: bestBid?.price,+ ask: bestAsk?.price,+ bidQty: bestBid?.quantity,+ askQty: bestAsk?.quantity,+ timestamp: data.timestamp,+ depth: {+ bids: data.bids?.map((b) => ({ price: b.price, quantity: b.quantity, orders: b.orders || 0 })) || [],+ asks: data.asks?.map((a) => ({ price: a.price, quantity: a.quantity, orders: a.orders || 0 })) || [],+ },+ };++ this.emitTick(tick);++ if (tick.depth) {+ this.emitDepth({ symbol, exchange, bids: tick.depth.bids, asks: tick.depth.asks });+ }+ });++ // Listen for status/connection events+ this.statusUnlisten = await listen<{+ provider: string;+ status: string;+ message?: string;+ timestamp: number;+ }>('dhan_status', (event) => {+ const status = event.payload;+ console.log(`[Dhan WebSocket] Status: ${status.status} - ${status.message || ''}`);++ if (status.status === 'disconnected' || status.status === 'error') {+ this.wsConnected = false;+ if (!this.usePollingFallback) {+ console.warn('[Dhan] WebSocket disconnected, enabling polling fallback');+ this.usePollingFallback = true;+ this.startQuotePolling();+ }+ } else if (status.status === 'connected') {+ this.wsConnected = true;+ if (this.usePollingFallback) {+ console.log('[Dhan] WebSocket reconnected, disabling polling fallback');+ this.usePollingFallback = false;+ this.stopQuotePolling();+ }+ }+ });++ this.wsConnected = true;+ }++ private async disconnectRealWebSocket(): Promise<void> {+ if (this.tickerUnlisten) {+ this.tickerUnlisten();+ this.tickerUnlisten = null;}+ if (this.orderbookUnlisten) {+ this.orderbookUnlisten();+ this.orderbookUnlisten = null;+ }+ if (this.statusUnlisten) {+ this.statusUnlisten();+ this.statusUnlisten = null;+ }++ try {+ await invoke('dhan_ws_disconnect');+ } catch (err) {+ console.warn('[Dhan] WebSocket disconnect error:', err);+ }++ this.wsConnected = false;}private startQuotePolling(): void {this.stopQuotePolling();+ console.log('[Dhan] Starting REST API polling (fallback mode, 2 min interval)');+// Poll every 2 minutes (Dhan has strict rate limits)this.quotePollingInterval = setInterval(async () => {await this.pollQuotes();@@ -860,10 +1021,12 @@ export class DhanAdapter extends BaseStockBrokerAdapter {}async disconnectWebSocket(): Promise<void> {+ await this.disconnectRealWebSocket();this.stopQuotePolling();this.pollingSymbols.clear();+ this.usePollingFallback = false;this.wsConnected = false;- console.log('[Dhan] Polling stopped');+ console.log('[Dhan] WebSocket disconnected');}protected async subscribeInternal(@@ -873,16 +1036,56 @@ export class DhanAdapter extends BaseStockBrokerAdapter {): Promise<void> {const key = `${exchange}:${symbol}`;this.pollingSymbols.set(key, { symbol, exchange });- console.log(`[Dhan] Added ${key} to polling (${this.pollingSymbols.size} total)`);- // Trigger immediate poll- this.pollQuotes();+ if (this.wsConnected && !this.usePollingFallback) {+ try {+ const securityId = await this.getSecurityId(symbol, exchange);+ const wsMode = mode === 'full' ? 'full' : mode === 'quote' ? 'quote' : 'ticker';++ await invoke('dhan_ws_subscribe', {+ symbol: securityId,+ mode: wsMode,+ });++ console.log(`[Dhan] ✓ WebSocket subscribed to ${symbol} (mode: ${wsMode})`);+ } catch (error) {+ console.error(`[Dhan] WebSocket subscribe failed:`, error);+ if (!this.usePollingFallback) {+ this.usePollingFallback = true;+ this.startQuotePolling();+ }+ }+ } else {+ console.log(`[Dhan] Added ${key} to polling (${this.pollingSymbols.size} total)`);+ if (this.usePollingFallback) {+ this.pollQuotes();+ }+ }}protected async unsubscribeInternal(symbol: string, exchange: StockExchange): Promise<void> {const key = `${exchange}:${symbol}`;this.pollingSymbols.delete(key);- console.log(`[Dhan] Removed ${key} from polling`);++ if (this.wsConnected && !this.usePollingFallback) {+ try {+ const securityId = await this.getSecurityId(symbol, exchange);+ await invoke('dhan_ws_unsubscribe', { symbol: securityId });+ console.log(`[Dhan] ✓ WebSocket unsubscribed from ${symbol}`);+ } catch (error) {+ console.warn(`[Dhan] WebSocket unsubscribe failed:`, error);+ }+ } else {+ console.log(`[Dhan] Removed ${key} from polling`);+ }+ }++ async logout(): Promise<void> {+ await this.disconnectRealWebSocket();+ this.stopQuotePolling();+ this.pollingSymbols.clear();+ this.usePollingFallback = false;+ await super.logout();}// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/fivepaisa/FivePaisaAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/fivepaisa/FivePaisaAdapter.tsindex 857116663..de18a1ac3 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/fivepaisa/FivePaisaAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/fivepaisa/FivePaisaAdapter.ts@@ -5,6 +5,7 @@*/import { invoke } from '@tauri-apps/api/core';+import { listen, UnlistenFn } from '@tauri-apps/api/event';import { BaseStockBrokerAdapter } from '../../BaseStockBrokerAdapter';import type {StockBrokerMetadata,@@ -69,9 +70,15 @@ export class FivePaisaAdapter extends BaseStockBrokerAdapter {// Symbol to ScripCode mapping (required for 5Paisa API)private scripCodeCache: Map<string, number> = new Map();- // REST API polling for quotes+ // Tauri event unlisteners for WebSocket events+ private tickerUnlisten: UnlistenFn | null = null;+ private orderbookUnlisten: UnlistenFn | null = null;+ private statusUnlisten: UnlistenFn | null = null;++ // REST API polling for quotes (fallback)private quotePollingInterval: NodeJS.Timeout | null = null;private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange; scripCode: number }> = new Map();+ private usePollingFallback: boolean = false;// ============================================================================// Authentication@@ -702,104 +709,141 @@ export class FivePaisaAdapter extends BaseStockBrokerAdapter {}// ============================================================================- // REST API Polling (replaces WebSocket)+ // WebSocket - Real WebSocket via Rust Backend with Polling Fallback// ============================================================================protected async connectWebSocketInternal(config: WebSocketConfig): Promise<void> {this.ensureConnected();try {- // Start REST API polling- this.startQuotePolling();- this.wsConnected = true;- console.log('5Paisa: REST API polling started (2 min interval)');+ await this.connectRealWebSocket();+ console.log('[5Paisa] ✓ WebSocket connected via Rust backend');} catch (error) {- console.error('Failed to start 5Paisa polling:', error);- throw error;+ console.warn('[5Paisa] WebSocket connection failed, falling back to REST polling:', error);+ this.usePollingFallback = true;+ this.startQuotePolling();}}- /**- * Start REST API polling for quotes- */- private startQuotePolling(): void {- this.stopQuotePolling();+ private async connectRealWebSocket(): Promise<void> {+ if (!this.accessToken || !this.clientId) {+ throw new Error('Access token and client ID required');+ }++ const result = await invoke<{ success: boolean; data?: boolean; error?: string }>('fivepaisa_ws_connect', {+ clientId: this.clientId,+ accessToken: this.accessToken,+ });++ if (!result.success) throw new Error(result.error || 'WebSocket connection failed');++ this.tickerUnlisten = await listen<{+ provider: string; symbol: string; price: number; bid?: number; ask?: number;+ volume?: number; change_percent?: number; timestamp: number;+ }>('fivepaisa_ticker', (event) => {+ const tick = event.payload;+ this.emitTick({+ symbol: tick.symbol, exchange: 'NSE' as StockExchange, mode: 'quote',+ lastPrice: tick.price, bid: tick.bid, ask: tick.ask,+ volume: tick.volume || 0, changePercent: tick.change_percent || 0, timestamp: tick.timestamp,+ });+ });++ this.orderbookUnlisten = await listen<{+ provider: string; symbol: string;+ bids: Array<{ price: number; quantity: number; orders?: number }>; asks: Array<{ price: number; quantity: number; orders?: number }>;+ timestamp: number;+ }>('fivepaisa_orderbook', (event) => {+ const data = event.payload;+ const [exchangePart, symbolPart] = data.symbol.includes(':') ? data.symbol.split(':') : ['NSE', data.symbol];+ const symbol = symbolPart || data.symbol;+ const exchange = (exchangePart as StockExchange) || 'NSE';++ console.log(`[5Paisa WebSocket] Depth update for ${symbol}`);++ const bestBid = data.bids?.[0];+ const bestAsk = data.asks?.[0];++ const tick: TickData = {+ symbol, exchange, mode: 'full',+ lastPrice: bestBid?.price || 0,+ bid: bestBid?.price, ask: bestAsk?.price,+ bidQty: bestBid?.quantity, askQty: bestAsk?.quantity,+ timestamp: data.timestamp,+ depth: {+ bids: data.bids?.map((b) => ({ price: b.price, quantity: b.quantity, orders: b.orders || 0 })) || [],+ asks: data.asks?.map((a) => ({ price: a.price, quantity: a.quantity, orders: a.orders || 0 })) || [],+ },+ };++ this.emitTick(tick);+ if (tick.depth) {+ this.emitDepth({ symbol, exchange, bids: tick.depth.bids, asks: tick.depth.asks });+ }+ });- // Poll every 2 minutes (120000ms)- this.quotePollingInterval = setInterval(async () => {- await this.pollQuotesSequentially();- }, 120000);+ this.statusUnlisten = await listen<{+ provider: string; status: string; message?: string; timestamp: number;+ }>('fivepaisa_status', (event) => {+ const status = event.payload;+ if (status.status === 'disconnected' || status.status === 'error') {+ this.wsConnected = false;+ if (!this.usePollingFallback) { this.usePollingFallback = true; this.startQuotePolling(); }+ } else if (status.status === 'connected') {+ this.wsConnected = true;+ if (this.usePollingFallback) { this.usePollingFallback = false; this.stopQuotePolling(); }+ }+ });++ this.wsConnected = true;+ }++ private async disconnectRealWebSocket(): Promise<void> {+ if (this.tickerUnlisten) { this.tickerUnlisten(); this.tickerUnlisten = null; }+ if (this.orderbookUnlisten) { this.orderbookUnlisten(); this.orderbookUnlisten = null; }+ if (this.statusUnlisten) { this.statusUnlisten(); this.statusUnlisten = null; }+ try { await invoke('fivepaisa_ws_disconnect'); } catch (err) { console.warn('[5Paisa] WS disconnect error:', err); }+ this.wsConnected = false;+ }- // Initial poll+ private startQuotePolling(): void {+ this.stopQuotePolling();+ console.log('[5Paisa] Starting REST API polling (fallback mode, 2 min interval)');+ this.quotePollingInterval = setInterval(async () => { await this.pollQuotesSequentially(); }, 120000);this.pollQuotesSequentially();}- /**- * Stop REST API polling- */private stopQuotePolling(): void {- if (this.quotePollingInterval) {- clearInterval(this.quotePollingInterval);- this.quotePollingInterval = null;- }+ if (this.quotePollingInterval) { clearInterval(this.quotePollingInterval); this.quotePollingInterval = null; }}- /**- * Poll quotes sequentially for all subscribed symbols- */private async pollQuotesSequentially(): Promise<void> {- if (this.pollingSymbols.size === 0) {- return;- }-- console.log(`[5Paisa] Polling ${this.pollingSymbols.size} symbols sequentially...`);+ if (this.pollingSymbols.size === 0) return;for (const [key, { symbol, exchange, scripCode }] of this.pollingSymbols) {try {- // Ensure scripCode is cachedthis.setScripCode(symbol, exchange, scripCode);-const quote = await this.getQuoteInternal(symbol, exchange);-- const tick: TickData = {- symbol,- exchange,- mode: 'full',- lastPrice: quote.lastPrice,- open: quote.open,- high: quote.high,- low: quote.low,- close: quote.close,- volume: quote.volume,- change: quote.change,- changePercent: quote.changePercent,- timestamp: quote.timestamp,- bid: quote.bid,- bidQty: quote.bidQty,- ask: quote.ask,- askQty: quote.askQty,- };-- this.emitTick(tick);- } catch (error) {- console.error(`[5Paisa] Failed to poll ${symbol}:`, error);- }-- // Small delay between requests to avoid rate limiting+ this.emitTick({+ symbol, exchange, mode: 'full',+ lastPrice: quote.lastPrice, open: quote.open, high: quote.high, low: quote.low,+ close: quote.close, volume: quote.volume, change: quote.change,+ changePercent: quote.changePercent, timestamp: quote.timestamp,+ bid: quote.bid, bidQty: quote.bidQty, ask: quote.ask, askQty: quote.askQty,+ });+ } catch (error) { console.error(`[5Paisa] Failed to poll ${symbol}:`, error); }await new Promise(resolve => setTimeout(resolve, 100));}console.log(`[5Paisa] Polling complete for ${this.pollingSymbols.size} symbols`);}- /**- * Disconnect from WebSocket (stop polling)- */async disconnectWebSocket(): Promise<void> {+ await this.disconnectRealWebSocket();this.stopQuotePolling();this.pollingSymbols.clear();- this.wsConnected = false;- console.log('[5Paisa] REST API polling stopped');+ this.usePollingFallback = false;+ console.log('[5Paisa] WebSocket disconnected');}protected async subscribeInternal(@@ -817,10 +861,22 @@ export class FivePaisaAdapter extends BaseStockBrokerAdapter {const key = `${exchange}:${symbol}`;this.pollingSymbols.set(key, { symbol, exchange, scripCode });- console.log(`5Paisa: Added ${key} to polling list (${this.pollingSymbols.size} symbols total)`);-- // Trigger immediate poll for this symbol- this.pollQuotesSequentially();+ // If real WebSocket is connected, subscribe via Tauri command+ if (this.wsConnected && !this.usePollingFallback) {+ try {+ await invoke('fivepaisa_ws_subscribe', {+ symbol: `${exchange}:${symbol}`,+ mode: mode === 'full' ? 'depth' : mode === 'quote' ? 'quotes' : 'ltp',+ });+ console.log(`[5Paisa] WebSocket subscribed to ${key}`);+ } catch (err) {+ console.warn(`[5Paisa] WebSocket subscribe failed for ${key}, using polling:`, err);+ this.pollQuotesSequentially();+ }+ } else {+ console.log(`5Paisa: Added ${key} to polling list (${this.pollingSymbols.size} symbols total)`);+ this.pollQuotesSequentially();+ }} catch (error) {console.error('Failed to subscribe:', error);throw error;@@ -844,7 +900,17 @@ export class FivePaisaAdapter extends BaseStockBrokerAdapter {const key = `${exchange}:${symbol}`;this.pollingSymbols.delete(key);- console.log(`5Paisa: Removed ${key} from polling list (${this.pollingSymbols.size} symbols remaining)`);+ // If real WebSocket is connected, unsubscribe via Tauri command+ if (this.wsConnected && !this.usePollingFallback) {+ try {+ await invoke('fivepaisa_ws_unsubscribe', { symbol: `${exchange}:${symbol}` });+ console.log(`[5Paisa] WebSocket unsubscribed from ${key}`);+ } catch (err) {+ console.warn(`[5Paisa] WebSocket unsubscribe failed for ${key}:`, err);+ }+ } else {+ console.log(`5Paisa: Removed ${key} from polling list (${this.pollingSymbols.size} symbols remaining)`);+ }}// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/fyers/FyersAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/FyersAdapter.tsindex ac3587aa0..66e7d10ee 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/fyers/FyersAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/FyersAdapter.ts@@ -37,8 +37,6 @@ import type {import {FYERS_METADATA,FYERS_LOGIN_URL,- FYERS_EXCHANGE_MAP,- FYERS_WS_URL,} from './constants';import {toFyersOrderParams,@@ -69,9 +67,20 @@ export class FyersAdapter extends BaseStockBrokerAdapter {// Tauri event unlistenersprivate eventUnlisteners: UnlistenFn[] = [];- // REST API polling for quotes (instead of WebSocket)- private quotePollingInterval: NodeJS.Timeout | null = null;- private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange }> = new Map();+ // WebSocket state (protected to match base class)+ protected override wsConnected: boolean = false;+ protected wsSubscriptions: Set<string> = new Set();++ // Tauri event unlisteners for WebSocket+ protected wsUnlisteners: Array<() => void> = [];++ // Hybrid data strategy: WebSocket during market hours, polling off-hours+ private pollingInterval: NodeJS.Timeout | null = null;+ private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange; mode: SubscriptionMode }> = new Map();+ // Off-market polling interval: 30 minutes (data won't change when market is closed)+ private readonly POLLING_INTERVAL_MS = 30 * 60 * 1000; // 30 minutes for off-market polling+ private usePollingMode: boolean = false;+ private marketHoursCheckInterval: NodeJS.Timeout | null = null;// ============================================================================// Authentication@@ -266,6 +275,16 @@ export class FyersAdapter extends BaseStockBrokerAdapter {await this.getFundsInternal();this._isConnected = true;console.log(`[${this.brokerId}] ✓ Session restored successfully`);++ // Download master contract for WebSocket symbol lookup (uses correct public Fyers URL)+ try {+ console.log(`[${this.brokerId}] Downloading master contract for WebSocket...`);+ await invoke('download_fyers_master_contract');+ console.log(`[${this.brokerId}] ✓ Master contract ready`);+ } catch (mcErr) {+ console.warn(`[${this.brokerId}] Master contract download failed:`, mcErr);+ }+return true;} catch (err) {console.warn(`[${this.brokerId}] Access token expired or invalid, clearing from storage...`);@@ -705,14 +724,15 @@ export class FyersAdapter extends BaseStockBrokerAdapter {/*** Get quotes for multiple symbols (batch processing)* Automatically batches into groups of 50 symbols+ * Fyers API rate limit: ~10 requests per second*/protected async getMultipleQuotesInternal(symbols: Array<{ symbol: string; exchange: StockExchange }>): Promise<Quote[]> {this.ensureAuthenticated();- const BATCH_SIZE = 50;- const RATE_LIMIT_DELAY = 100; // 100ms delay between batches+ const BATCH_SIZE = 50; // Fyers supports up to 50 symbols per request+ const RATE_LIMIT_DELAY = 1000; // 1 second delay between batches (safe for Fyers rate limits)const allResults: Quote[] = [];try {@@ -861,11 +881,47 @@ export class FyersAdapter extends BaseStockBrokerAdapter {}// ============================================================================- // WebSocket - Internal Implementations+ // WebSocket - Internal Implementations (Hybrid: WebSocket + Polling)// ============================================================================/**- * Connect to WebSocket (internal) - Uses REST API polling instead+ * Check if Indian stock market is currently open+ * NSE/BSE: Monday-Friday, 9:15 AM - 3:30 PM IST+ */+ private isMarketOpen(): boolean {+ // Get current time in IST using Intl.DateTimeFormat+ const now = new Date();+ const istFormatter = new Intl.DateTimeFormat('en-US', {+ timeZone: 'Asia/Kolkata',+ hour: 'numeric',+ minute: 'numeric',+ hour12: false,+ weekday: 'short',+ });++ const parts = istFormatter.formatToParts(now);+ const weekday = parts.find(p => p.type === 'weekday')?.value || '';+ const hour = parseInt(parts.find(p => p.type === 'hour')?.value || '0', 10);+ const minute = parseInt(parts.find(p => p.type === 'minute')?.value || '0', 10);++ const timeInMinutes = hour * 60 + minute;++ // Market hours: 9:15 AM (555 min) to 3:30 PM (930 min), Mon-Fri+ const marketOpen = 9 * 60 + 15; // 9:15 AM = 555 minutes+ const marketClose = 15 * 60 + 30; // 3:30 PM = 930 minutes++ const weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];+ const isWeekday = weekdays.includes(weekday);+ const isWithinHours = timeInMinutes >= marketOpen && timeInMinutes <= marketClose;++ console.log(`[Fyers] Market check: ${weekday} ${hour}:${minute.toString().padStart(2, '0')} IST | open=${isWeekday && isWithinHours}`);++ return isWeekday && isWithinHours;+ }++ /**+ * Connect to Fyers WebSocket for real-time market data+ * Uses hybrid approach: WebSocket during market hours, polling off-hours*/protected async connectWebSocketInternal(config: WebSocketConfig): Promise<void> {this.ensureAuthenticated();@@ -875,62 +931,663 @@ export class FyersAdapter extends BaseStockBrokerAdapter {throw new Error('API credentials not set');}- // Start REST API polling (every 2 minutes as requested)- this.startQuotePolling();+ // Check if market is open to decide connection strategy+ const marketOpen = this.isMarketOpen();++ if (marketOpen) {+ // Market is open - try WebSocket first+ console.log('[Fyers] Market is OPEN - attempting WebSocket connection...');+ await this.connectWebSocketDirect();+ } else {+ // Market is closed - use polling mode+ console.log('[Fyers] Market is CLOSED - using polling mode for data');+ this.usePollingMode = true;+ this.startPolling();+ }++ // Set up periodic market hours check to switch modes+ this.startMarketHoursMonitor();- console.log('Fyers: REST API polling started (2 min interval)');} catch (error) {- console.error('Failed to start Fyers polling:', error);- throw error;+ console.error('[Fyers] Connection failed, falling back to polling:', error);+ // Fallback to polling on any error+ this.usePollingMode = true;+ this.startPolling();+ }+ }++ /**+ * Direct WebSocket connection via Tauri backend+ */+ private async connectWebSocketDirect(): Promise<void> {+ const wsAccessToken = `${this.apiKey}:${this.accessToken}`;++ console.log('[Fyers WS] Connecting...', {+ hasApiKey: !!this.apiKey,+ apiKeyLength: this.apiKey?.length || 0,+ accessTokenLength: this.accessToken?.length || 0,+ wsAccessTokenLength: wsAccessToken.length,+ });++ try {+ const response = await invoke<{+ success: boolean;+ data?: boolean;+ error?: string;+ }>('fyers_ws_connect', {+ app: undefined,+ apiKey: this.apiKey,+ accessToken: wsAccessToken,+ });++ console.log('[Fyers WS] Response:', response);++ if (!response.success) {+ const errorMsg = response.error || 'WebSocket connection failed (no error details)';+ console.error('[Fyers WS] ✗ Connection failed:', errorMsg);+ throw new Error(errorMsg);+ }++ this.wsConnected = true;+ this.usePollingMode = false;+ console.log('[Fyers WS] ✓ Connected successfully');++ await this.setupWebSocketListeners();+ await this.resubscribeViaWebSocket();+ } catch (invokeError) {+ console.error('[Fyers WS] ✗ Tauri invoke error:', invokeError);+ throw invokeError;+ }+ }++ /**+ * Start periodic market hours monitoring+ * Switches between WebSocket and polling based on market status+ */+ private startMarketHoursMonitor(): void {+ // Clear existing monitor+ if (this.marketHoursCheckInterval) {+ clearInterval(this.marketHoursCheckInterval);+ }++ // Check every 5 minutes+ this.marketHoursCheckInterval = setInterval(async () => {+ const marketOpen = this.isMarketOpen();++ if (marketOpen && this.usePollingMode) {+ // Market just opened - switch to WebSocket+ console.log('[Fyers] Market opened - switching to WebSocket');+ this.stopPolling();+ try {+ await this.connectWebSocketDirect();+ } catch (err) {+ console.warn('[Fyers] WebSocket failed, continuing with polling:', err);+ this.startPolling();+ }+ } else if (!marketOpen && !this.usePollingMode && this.wsConnected) {+ // Market just closed - switch to polling+ console.log('[Fyers] Market closed - switching to polling');+ await this.disconnectWebSocket();+ this.usePollingMode = true;+ this.startPolling();+ }+ }, 5 * 60 * 1000); // Check every 5 minutes+ }++ /**+ * Resubscribe all polling symbols via WebSocket (BATCH mode for speed!)+ */+ private async resubscribeViaWebSocket(): Promise<void> {+ if (this.pollingSymbols.size === 0) {+ console.log('[Fyers] No symbols to resubscribe');+ return;+ }++ // Group symbols by mode+ const depthSymbols: string[] = [];+ const quoteSymbols: string[] = [];++ for (const [fyersSymbol, data] of this.pollingSymbols) {+ if (data.mode === 'full') {+ depthSymbols.push(fyersSymbol);+ } else {+ quoteSymbols.push(fyersSymbol);+ }+ }++ // Batch subscribe depth symbols+ if (depthSymbols.length > 0) {+ console.log(`[Fyers] Batch subscribing ${depthSymbols.length} depth symbols...`);+ try {+ const response = await invoke<{ success: boolean; error?: string }>('fyers_ws_subscribe_batch', {+ symbols: depthSymbols,+ mode: 'depth',+ });+ if (response.success) {+ depthSymbols.forEach(s => this.wsSubscriptions.add(s));+ console.log(`[Fyers] ✓ Batch subscribed ${depthSymbols.length} depth symbols`);+ } else {+ console.warn(`[Fyers] Batch depth subscription failed: ${response.error}`);+ }+ } catch (err) {+ console.error('[Fyers] Batch depth subscription error:', err);+ }+ }++ // Batch subscribe quote symbols+ if (quoteSymbols.length > 0) {+ console.log(`[Fyers] Batch subscribing ${quoteSymbols.length} quote symbols...`);+ try {+ const response = await invoke<{ success: boolean; error?: string }>('fyers_ws_subscribe_batch', {+ symbols: quoteSymbols,+ mode: 'quote',+ });+ if (response.success) {+ quoteSymbols.forEach(s => this.wsSubscriptions.add(s));+ console.log(`[Fyers] ✓ Batch subscribed ${quoteSymbols.length} quote symbols`);+ } else {+ console.warn(`[Fyers] Batch quote subscription failed: ${response.error}`);+ }+ } catch (err) {+ console.error('[Fyers] Batch quote subscription error:', err);+ }}}/**- * Start REST API polling for quotes+ * Set up Tauri event listeners for WebSocket messages*/- private startQuotePolling(): void {- // Stop existing polling- this.stopQuotePolling();+ private async setupWebSocketListeners(): Promise<void> {+ // Clean up existing listeners+ this.cleanupWebSocketListeners();++ // Listen for ticker data+ const tickerUnlisten = await listen<{+ provider: string;+ symbol: string;+ price: number;+ bid?: number;+ ask?: number;+ bid_size?: number;+ ask_size?: number;+ volume?: number;+ high?: number;+ low?: number;+ open?: number;+ close?: number;+ change?: number;+ change_percent?: number;+ timestamp: number;+ }>('fyers_ticker', (event) => {+ const data = event.payload;++ // Extract symbol and exchange from Fyers format (e.g., "NSE:RELIANCE-EQ")+ const [exchange, symbolPart] = data.symbol.split(':');+ const symbol = symbolPart?.replace('-EQ', '').replace('-INDEX', '') || data.symbol;++ console.log('[Fyers] Ticker update:', symbol, 'LTP:', data.price, 'change:', data.change_percent?.toFixed(2) + '%');++ const tick: TickData = {+ symbol,+ exchange: (exchange as StockExchange) || 'NSE',+ mode: 'quote',+ lastPrice: data.price,+ open: data.open,+ high: data.high,+ low: data.low,+ close: data.close,+ volume: data.volume,+ change: data.change,+ changePercent: data.change_percent,+ bid: data.bid,+ ask: data.ask,+ bidQty: data.bid_size,+ askQty: data.ask_size,+ timestamp: data.timestamp,+ };++ this.emitTick(tick);+ });++ this.wsUnlisteners.push(tickerUnlisten);- // Poll every 2 minutes (120000ms)- this.quotePollingInterval = setInterval(async () => {- await this.pollQuotesSequentially();- }, 120000);+ // Listen for orderbook/depth data+ const orderbookUnlisten = await listen<{+ provider: string;+ symbol: string;+ bids: Array<{ price: number; quantity: number; count?: number }>;+ asks: Array<{ price: number; quantity: number; count?: number }>;+ timestamp: number;+ is_snapshot?: boolean;+ }>('fyers_orderbook', (event) => {+ const data = event.payload;- // Initial poll- this.pollQuotesSequentially();+ // Parse symbol from Fyers format (e.g., "NSE:RELIANCE-EQ" -> "RELIANCE")+ const [exchange, symbolPart] = data.symbol.split(':');+ const symbol = symbolPart?.replace('-EQ', '').replace('-INDEX', '') || data.symbol;++ console.log('[Fyers] Depth update:', symbol, 'bids:', data.bids?.length, 'asks:', data.asks?.length);++ // Get best bid/ask from depth+ const bestBid = data.bids?.[0];+ const bestAsk = data.asks?.[0];++ // Create tick data with depth information+ const tick: TickData = {+ symbol,+ exchange: (exchange as StockExchange) || 'NSE',+ mode: 'full',+ lastPrice: bestBid?.price || 0, // Use bid as approximate LTP+ bid: bestBid?.price,+ ask: bestAsk?.price,+ bidQty: bestBid?.quantity,+ askQty: bestAsk?.quantity,+ timestamp: data.timestamp,+ // Include full depth data+ depth: {+ bids: data.bids?.map((b) => ({+ price: b.price,+ quantity: b.quantity,+ orders: b.count || 0,+ })) || [],+ asks: data.asks?.map((a) => ({+ price: a.price,+ quantity: a.quantity,+ orders: a.count || 0,+ })) || [],+ },+ };++ this.emitTick(tick);++ // Also emit depth data separately for UI components that listen for depth updates+ if (tick.depth) {+ this.emitDepth({+ symbol,+ exchange: (exchange as StockExchange) || 'NSE',+ bids: tick.depth.bids,+ asks: tick.depth.asks,+ });+ }+ });++ this.wsUnlisteners.push(orderbookUnlisten);++ // Listen for status updates+ const statusUnlisten = await listen<{+ provider: string;+ status: string;+ message: string;+ timestamp: number;+ }>('fyers_status', (event) => {+ const data = event.payload;+ console.log(`[Fyers] Status: ${data.status} - ${data.message}`);++ if (data.status === 'disconnected' || data.status === 'error') {+ this.wsConnected = false;+ }+ });++ this.wsUnlisteners.push(statusUnlisten);++ console.log('[Fyers] WebSocket event listeners set up');+ }++ /**+ * Clean up WebSocket event listeners+ */+ private cleanupWebSocketListeners(): void {+ for (const unlisten of this.wsUnlisteners) {+ unlisten();+ }+ this.wsUnlisteners = [];+ }++ // ============================================================================+ // Polling Mode - For Off-Market Hours+ // ============================================================================++ /**+ * Start REST API polling for subscribed symbols+ */+ private startPolling(): void {+ if (this.pollingInterval) {+ return; // Already polling+ }++ console.log(`[Fyers] Polling mode started (${this.POLLING_INTERVAL_MS / 1000}s interval)`);++ this.pollingInterval = setInterval(async () => {+ await this.pollSubscribedSymbols();+ }, this.POLLING_INTERVAL_MS);++ // Do an immediate poll+ this.pollSubscribedSymbols();}/*** Stop REST API polling*/- private stopQuotePolling(): void {- if (this.quotePollingInterval) {- clearInterval(this.quotePollingInterval);- this.quotePollingInterval = null;+ private stopPolling(): void {+ if (this.pollingInterval) {+ clearInterval(this.pollingInterval);+ this.pollingInterval = null;+ console.log('[Fyers] Polling stopped');}}/**- * Poll quotes sequentially (not parallel) for all subscribed symbols+ * Poll all subscribed symbols via REST API*/- private async pollQuotesSequentially(): Promise<void> {+ private async pollSubscribedSymbols(): Promise<void> {if (this.pollingSymbols.size === 0) {return;}- console.log(`[Fyers] Polling ${this.pollingSymbols.size} symbols sequentially...`);+ try {+ // Get all symbols to poll+ const fyersSymbols: string[] = [];++ for (const [fyersSymbol] of this.pollingSymbols) {+ fyersSymbols.push(fyersSymbol);+ }++ // Fetch quotes in batch+ const response = await invoke<{+ success: boolean;+ data?: unknown[];+ error?: string;+ }>('fyers_get_quotes', {+ apiKey: this.apiKey!,+ accessToken: this.accessToken!,+ symbols: fyersSymbols,+ });++ if (response.success && response.data) {+ // Emit tick data for each quote+ for (const quoteData of response.data) {+ const quote = fromFyersQuote(quoteData as Record<string, unknown>);++ // Skip quotes with errors silently+ if (quote.error) continue;++ const tick: TickData = {+ symbol: quote.symbol,+ exchange: quote.exchange,+ mode: 'quote',+ lastPrice: quote.lastPrice,+ open: quote.open,+ high: quote.high,+ low: quote.low,+ close: quote.close,+ volume: quote.volume,+ change: quote.change,+ changePercent: quote.changePercent,+ bid: quote.bid,+ ask: quote.ask,+ bidQty: quote.bidQty,+ askQty: quote.askQty,+ timestamp: quote.timestamp,+ };++ this.emitTick(tick);+ }+ } else if (!response.success) {+ console.error('[Fyers] Poll failed:', response.error);+ }+ } catch (error) {+ console.error('[Fyers] Polling error:', error);+ }+ }++ // ============================================================================+ // Subscribe/Unsubscribe - Hybrid Mode (Override base class)+ // ============================================================================++ /**+ * Override base class subscribe to implement hybrid WebSocket/Polling+ */+ async subscribe(symbol: string, exchange: StockExchange, mode: SubscriptionMode): Promise<void> {+ console.log(`[Fyers] >>> SUBSCRIBE: ${symbol}@${exchange} mode=${mode} | ws=${this.wsConnected} poll=${this.usePollingMode}`);+ await this.subscribeInternal(symbol, exchange, mode);+ }++ /**+ * FAST batch subscribe - subscribes to multiple symbols at once!+ * Use this for watchlists or any batch of symbols for much faster subscription.+ */+ async subscribeBatch(symbols: Array<{ symbol: string; exchange: StockExchange }>, mode: SubscriptionMode = 'quote'): Promise<void> {+ if (symbols.length === 0) return;++ console.log(`[Fyers] >>> BATCH SUBSCRIBE: ${symbols.length} symbols, mode=${mode}`);+ const startTime = Date.now();++ // Convert to Fyers format+ const fyersSymbols = symbols.map(({ symbol, exchange }) => {+ const fyersSymbol = toFyersSymbol(symbol, exchange);+ this.pollingSymbols.set(fyersSymbol, { symbol, exchange, mode });+ return fyersSymbol;+ });++ // Initialize connection if needed+ if (!this.wsConnected && !this.usePollingMode && !this.pollingInterval) {+ const marketOpen = this.isMarketOpen();+ console.log(`[Fyers] Init strategy: market=${marketOpen ? 'OPEN' : 'CLOSED'}`);- // Process each symbol one by one- for (const [key, { symbol, exchange }] of this.pollingSymbols) {+ if (marketOpen) {+ try {+ await this.connectWebSocketDirect();+ this.startMarketHoursMonitor();+ } catch (wsError) {+ console.error('[Fyers] WS failed, fallback to polling:', wsError);+ this.usePollingMode = true;+ this.startPolling();+ }+ } else {+ this.usePollingMode = true;+ this.startPolling();+ this.startMarketHoursMonitor();+ }+ }++ // Use batch subscribe if WebSocket is connected+ if (this.wsConnected && !this.usePollingMode) {try {- // Fetch quote via REST API- const quote = await this.getQuoteInternal(symbol, exchange);+ const wsMode = mode === 'full' ? 'depth' : 'quote';+ const response = await invoke<{ success: boolean; error?: string }>('fyers_ws_subscribe_batch', {+ symbols: fyersSymbols,+ mode: wsMode,+ });++ if (response.success) {+ fyersSymbols.forEach(s => this.wsSubscriptions.add(s));+ console.log(`[Fyers] ✓ Batch WS subscribed to ${fyersSymbols.length} symbols in ${Date.now() - startTime}ms`);+ return;+ } else {+ console.warn(`[Fyers] Batch WS subscribe failed: ${response.error}, falling back to polling`);+ }+ } catch (err) {+ console.error('[Fyers] Batch WS subscribe error:', err);+ }+ }++ // Fallback: fetch initial quotes via REST+ console.log(`[Fyers] Fetching ${fyersSymbols.length} quotes via REST (polling mode)`);+ await this.fetchBatchQuotes(fyersSymbols);++ if (!this.pollingInterval) {+ this.usePollingMode = true;+ this.startPolling();+ }++ console.log(`[Fyers] ✓ Batch subscribe complete in ${Date.now() - startTime}ms`);+ }++ // Debounce timer for batched initial fetch+ private pendingInitialFetch: NodeJS.Timeout | null = null;+ private pendingSymbols: Set<string> = new Set();++ // Track symbols with errors (to avoid repeated error logging)+ private errorSymbols: Set<string> = new Set();++ /**+ * Subscribe to symbol - uses WebSocket or polling based on market hours+ */+ protected async subscribeInternal(symbol: string, exchange: StockExchange, mode: SubscriptionMode): Promise<void> {+ const fyersSymbol = toFyersSymbol(symbol, exchange);+ this.pollingSymbols.set(fyersSymbol, { symbol, exchange, mode });++ try {+ // Initialize connection strategy on first subscription+ if (!this.wsConnected && !this.usePollingMode && !this.pollingInterval) {+ const marketOpen = this.isMarketOpen();+ console.log(`[Fyers] Init strategy: market=${marketOpen ? 'OPEN' : 'CLOSED'}`);++ if (marketOpen) {+ try {+ await this.connectWebSocketDirect();+ this.startMarketHoursMonitor();+ } catch (wsError) {+ console.error('[Fyers] WS failed, fallback to polling:', wsError);+ this.usePollingMode = true;+ this.startPolling();+ }+ } else {+ this.usePollingMode = true;+ this.startPolling();+ this.startMarketHoursMonitor();+ }+ }++ // Handle subscription based on current mode+ if (this.usePollingMode) {+ if (!this.pollingInterval) this.startPolling();+ this.queueInitialFetch(fyersSymbol);+ } else if (this.wsConnected) {+ const channel = mode === 'full' ? 'depth' : 'SymbolUpdate';+ const response = await invoke<{ success: boolean; error?: string }>('fyers_ws_subscribe', {+ symbol: fyersSymbol,+ mode: channel,+ });+ if (!response.success) {+ console.warn(`[Fyers] WS subscribe failed for ${fyersSymbol}: ${response.error}`);+ this.queueInitialFetch(fyersSymbol);+ }+ this.wsSubscriptions.add(fyersSymbol);+ } else {+ this.queueInitialFetch(fyersSymbol);+ if (!this.pollingInterval) {+ this.usePollingMode = true;+ this.startPolling();+ }+ }+ } catch (error) {+ console.error(`[Fyers] Subscribe error for ${fyersSymbol}:`, error);+ this.queueInitialFetch(fyersSymbol);+ }+ }++ /**+ * Queue symbol for batched initial fetch+ * Uses debouncing to collect multiple symbols and fetch them in one batch+ */+ private queueInitialFetch(fyersSymbol: string): void {+ this.pendingSymbols.add(fyersSymbol);++ // Clear existing timer+ if (this.pendingInitialFetch) {+ clearTimeout(this.pendingInitialFetch);+ }++ // Set new timer - wait 200ms for more symbols to be added+ this.pendingInitialFetch = setTimeout(async () => {+ const symbols = Array.from(this.pendingSymbols);+ this.pendingSymbols.clear();+ this.pendingInitialFetch = null;++ if (symbols.length > 0) {+ console.log(`[Fyers] Batch fetching ${symbols.length} symbols for initial data`);+ await this.fetchBatchQuotes(symbols);+ }+ }, 200);+ }++ /**+ * Fetch quotes for multiple symbols in one batch request+ */+ private async fetchBatchQuotes(fyersSymbols: string[]): Promise<void> {+ try {+ const response = await invoke<{+ success: boolean;+ data?: unknown[];+ error?: string;+ }>('fyers_get_quotes', {+ apiKey: this.apiKey!,+ accessToken: this.accessToken!,+ symbols: fyersSymbols,+ });++ if (response.success && response.data) {+ let successCount = 0;+ for (const quoteData of response.data) {+ const quote = fromFyersQuote(quoteData as Record<string, unknown>);++ // Skip quotes with errors silently+ if (quote.error) continue;++ const tick: TickData = {+ symbol: quote.symbol,+ exchange: quote.exchange,+ mode: 'quote',+ lastPrice: quote.lastPrice,+ open: quote.open,+ high: quote.high,+ low: quote.low,+ close: quote.close,+ volume: quote.volume,+ change: quote.change,+ changePercent: quote.changePercent,+ bid: quote.bid,+ ask: quote.ask,+ bidQty: quote.bidQty,+ askQty: quote.askQty,+ timestamp: quote.timestamp,+ };++ this.emitTick(tick);+ successCount++;+ }+ console.log(`[Fyers] Batch fetch: ${successCount}/${fyersSymbols.length} quotes`);+ } else {+ console.error('[Fyers] Batch fetch failed:', response.error);+ }+ } catch (error) {+ console.error('[Fyers] Batch fetch error:', error);+ }+ }++ /**+ * Fetch a single quote and emit as tick data+ * Used for immediate data when subscribing+ */+ private async fetchAndEmitQuote(fyersSymbol: string, symbol: string, exchange: StockExchange): Promise<void> {+ try {+ const response = await invoke<{+ success: boolean;+ data?: unknown[];+ error?: string;+ }>('fyers_get_quotes', {+ apiKey: this.apiKey!,+ accessToken: this.accessToken!,+ symbols: [fyersSymbol],+ });++ if (response.success && response.data && response.data.length > 0) {+ const quote = fromFyersQuote(response.data[0] as Record<string, unknown>);- // Convert quote to tick and emitconst tick: TickData = {- symbol,- exchange,+ symbol: quote.symbol || symbol,+ exchange: quote.exchange || exchange,mode: 'quote',lastPrice: quote.lastPrice,open: quote.open,@@ -940,59 +1597,99 @@ export class FyersAdapter extends BaseStockBrokerAdapter {volume: quote.volume,change: quote.change,changePercent: quote.changePercent,+ bid: quote.bid,+ ask: quote.ask,+ bidQty: quote.bidQty,+ askQty: quote.askQty,timestamp: quote.timestamp,};this.emitTick(tick);- } catch (error) {- console.error(`[Fyers] Failed to poll ${symbol}:`, error);+ console.log(`[Fyers] Fetched quote for ${fyersSymbol}: ${tick.lastPrice}`);}-- // Small delay between requests to avoid rate limiting- await new Promise(resolve => setTimeout(resolve, 100));+ } catch (error) {+ console.error(`[Fyers] Failed to fetch quote for ${fyersSymbol}:`, error);}-- console.log(`[Fyers] ✓ Polling complete for ${this.pollingSymbols.size} symbols`);}/**- * Subscribe to symbol (internal) - Adds to polling list+ * Unsubscribe from symbol*/- protected async subscribeInternal(symbol: string, exchange: StockExchange, mode: SubscriptionMode): Promise<void> {+ protected async unsubscribeInternal(symbol: string, exchange: StockExchange): Promise<void> {try {- const key = `${exchange}:${symbol}`;- this.pollingSymbols.set(key, { symbol, exchange });+ const fyersSymbol = toFyersSymbol(symbol, exchange);- console.log(`Fyers: Added ${key} to polling list (${this.pollingSymbols.size} symbols total)`);+ // Remove from polling map+ this.pollingSymbols.delete(fyersSymbol);++ // If WebSocket connected, unsubscribe there too+ if (this.wsConnected && this.wsSubscriptions.has(fyersSymbol)) {+ const response = await invoke<{+ success: boolean;+ data?: boolean;+ error?: string;+ }>('fyers_ws_unsubscribe', {+ symbol: fyersSymbol,+ });++ if (!response.success) {+ console.warn(`[Fyers] WebSocket unsubscribe failed: ${response.error}`);+ }++ this.wsSubscriptions.delete(fyersSymbol);+ }++ console.log(`[Fyers] Unsubscribed from ${fyersSymbol} (${this.pollingSymbols.size} remaining)`);++ // Stop polling if no more symbols+ if (this.pollingSymbols.size === 0 && this.pollingInterval) {+ this.stopPolling();+ }- // Trigger immediate poll for this symbol- this.pollQuotesSequentially();} catch (error) {- console.error('Failed to subscribe:', error);- throw error;+ console.error('[Fyers] Unsubscribe error:', error);}}/**- * Unsubscribe from symbol (internal) - Removes from polling list+ * Disconnect WebSocket (override base class method)*/- protected async unsubscribeInternal(symbol: string, exchange: StockExchange): Promise<void> {+ async disconnectWebSocket(): Promise<void> {try {- const key = `${exchange}:${symbol}`;- this.pollingSymbols.delete(key);-- console.log(`Fyers: Removed ${key} from polling list (${this.pollingSymbols.size} symbols remaining)`);+ await invoke('fyers_ws_disconnect');+ this.wsConnected = false;+ this.wsSubscriptions.clear();+ this.cleanupWebSocketListeners();+ console.log('[Fyers] WebSocket disconnected');} catch (error) {- console.error('Failed to unsubscribe:', error);- throw error;+ console.error('[Fyers] WebSocket disconnect error:', error);}}/**- * Cleanup polling on logout+ * Check if WebSocket is connected+ */+ async isWebSocketConnected(): Promise<boolean> {+ try {+ const connected = await invoke<boolean>('fyers_ws_is_connected');+ this.wsConnected = connected;+ return connected;+ } catch {+ return false;+ }+ }++ /**+ * Cleanup on logout*/async logout(): Promise<void> {- this.stopQuotePolling();+ // Stop all data feeds+ this.stopPolling();+ if (this.marketHoursCheckInterval) {+ clearInterval(this.marketHoursCheckInterval);+ this.marketHoursCheckInterval = null;+ }+ await this.disconnectWebSocket();this.pollingSymbols.clear();await super.logout();}diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/fyers/constants.ts b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/constants.tsindex 8a53694b1..898f7630b 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/fyers/constants.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/constants.ts@@ -205,8 +205,71 @@ export const FYERS_METADATA: StockBrokerMetadata = {},defaultSymbols: [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',+ // Financials (Weight: ~35%)+ 'HDFCBANK', 'ICICIBANK', 'SBIN', 'KOTAKBANK', 'AXISBANK',+ 'BAJFINANCE', 'BAJAJFINSV', 'HDFCLIFE', 'SBILIFE', 'INDUSINDBK',+ // IT (Weight: ~13%)+ 'TCS', 'INFY', 'WIPRO', 'HCLTECH', 'TECHM', 'LTIM',+ // Oil & Gas / Energy+ 'RELIANCE', 'ONGC', 'NTPC', 'POWERGRID', 'ADANIPORTS', 'ADANIENT',+ // Auto+ 'MARUTI', 'TATAMOTORS', 'M&M', 'BAJAJ-AUTO', 'HEROMOTOCO', 'EICHERMOT',+ // FMCG+ 'HINDUNILVR', 'ITC', 'NESTLEIND', 'BRITANNIA', 'TATACONSUM',+ // Metals & Mining+ 'TATASTEEL', 'JSWSTEEL', 'HINDALCO', 'COALINDIA',+ // Pharma & Healthcare+ 'SUNPHARMA', 'DRREDDY', 'CIPLA', 'APOLLOHOSP', 'DIVISLAB',+ // Infrastructure & Others+ 'LT', 'BHARTIARTL', 'ULTRACEMCO', 'GRASIM', 'TITAN',+ 'ASIANPAINT', 'BPCL', 'SHRIRAMFIN', 'TRENT',],};++// ============================================================================+// NIFTY 50 COMPONENTS (Current constituents as of Jan 2025)+// ============================================================================++export const NIFTY_50_SYMBOLS = [+ // Financials+ 'HDFCBANK', 'ICICIBANK', 'SBIN', 'KOTAKBANK', 'AXISBANK',+ 'BAJFINANCE', 'BAJAJFINSV', 'HDFCLIFE', 'SBILIFE', 'INDUSINDBK',++ // IT+ 'TCS', 'INFY', 'WIPRO', 'HCLTECH', 'TECHM', 'LTIM',++ // Oil & Gas / Energy+ 'RELIANCE', 'ONGC', 'NTPC', 'POWERGRID', 'ADANIPORTS', 'ADANIENT',++ // Auto+ 'MARUTI', 'TATAMOTORS', 'M&M', 'BAJAJ-AUTO', 'HEROMOTOCO', 'EICHERMOT',++ // FMCG+ 'HINDUNILVR', 'ITC', 'NESTLEIND', 'BRITANNIA', 'TATACONSUM',++ // Metals & Mining+ 'TATASTEEL', 'JSWSTEEL', 'HINDALCO', 'COALINDIA',++ // Pharma & Healthcare+ 'SUNPHARMA', 'DRREDDY', 'CIPLA', 'APOLLOHOSP', 'DIVISLAB',++ // Infrastructure & Others+ 'LT', 'BHARTIARTL', 'ULTRACEMCO', 'GRASIM', 'TITAN',+ 'ASIANPAINT', 'BPCL', 'SHRIRAMFIN', 'TRENT',+] as const;++// Nifty 50 with exchange for quick subscription+export const NIFTY_50_WATCHLIST = NIFTY_50_SYMBOLS.map(symbol => ({+ symbol,+ exchange: 'NSE' as const,+ name: symbol, // Could be enhanced with full names+}));++// Popular indices for watchlist+export const POPULAR_INDICES_FYERS = [+ { symbol: 'NSE:NIFTY50-INDEX', name: 'Nifty 50' },+ { symbol: 'NSE:NIFTYBANK-INDEX', name: 'Bank Nifty' },+ { symbol: 'NSE:NIFTYIT-INDEX', name: 'Nifty IT' },+ { symbol: 'NSE:FINNIFTY-INDEX', name: 'Fin Nifty' },+ { symbol: 'NSE:NIFTYMIDCAP50-INDEX', name: 'Nifty Midcap 50' },+];diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/fyers/mapper.ts b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/mapper.tsindex b01627493..3c225f92a 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/fyers/mapper.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/fyers/mapper.ts@@ -293,14 +293,46 @@ export function fromFyersFunds(funds: Record<string, unknown>): Funds {/*** Convert Fyers quote to standard format+ *+ * Handles both successful responses and error responses gracefully.+ * Error response format: { n: "NSE:SYMBOL-EQ", v: { errmsg: "...", code: -300, s: "error" } }*/export function fromFyersQuote(quote: Record<string, unknown>): Quote {// Parse symbolconst symbolStr = String(quote.n || quote.symbol || '');- const [exchange, symbol] = symbolStr.includes(':') ? symbolStr.split(':') : ['NSE', symbolStr];+ const [exchange, symbolWithSuffix] = symbolStr.includes(':') ? symbolStr.split(':') : ['NSE', symbolStr];++ // Remove -EQ suffix from symbol+ const symbol = symbolWithSuffix.includes('-') ? symbolWithSuffix.split('-')[0] : symbolWithSuffix;const v = quote.v as Record<string, unknown> || quote;+ // Check for error response (don't log repeatedly - caller handles logging)+ if (v.s === 'error' || v.errmsg || v.code === -300) {+ // Return a quote with zeros but valid symbol info+ return {+ symbol,+ exchange: exchange as StockExchange,+ lastPrice: 0,+ open: 0,+ high: 0,+ low: 0,+ close: 0,+ previousClose: 0,+ change: 0,+ changePercent: 0,+ volume: 0,+ averagePrice: 0,+ bid: 0,+ bidQty: 0,+ ask: 0,+ askQty: 0,+ timestamp: Date.now(),+ openInterest: 0,+ error: String(v.errmsg || 'Invalid symbol'),+ };+ }+const lastPrice = Number(v.lp || quote.ltp || 0);const prevClose = Number(v.prev_close_price || quote.prev_close_price || 0);const change = Number(v.ch || quote.ch || (lastPrice - prevClose));@@ -318,7 +350,7 @@ export function fromFyersQuote(quote: Record<string, unknown>): Quote {change,changePercent: Number(v.chp || quote.chp || changePercent),volume: Number(v.volume || v.vol_traded_today || quote.volume || 0),- averagePrice: Number(v.avg_trade_price || quote.avg_trade_price || 0),+ averagePrice: Number(v.avg_trade_price || v.atp || quote.avg_trade_price || 0),bid: Number(v.bid || v.bid_price || quote.best_bid_price || 0),bidQty: Number(v.bid_size || quote.best_bid_qty || 0),ask: Number(v.ask || v.ask_price || quote.best_ask_price || 0),@@ -367,30 +399,36 @@ export function fromFyersTickData(tick: Record<string, unknown>): TickData {/*** Convert Fyers market depth to standard format+ *+ * Fyers API response format:+ * - "ask" (singular) for asks array+ * - "bids" (plural) for bids array+ * - Each level has: { price, volume, ord }*/export function fromFyersDepth(depth: Record<string, unknown>): MarketDepth {const bids: DepthLevel[] = [];const asks: DepthLevel[] = [];- // Fyers provides depth data in asks and bids arrays- const asksData = (depth.asks as Array<Record<string, unknown>>) || [];+ // Fyers uses 'ask' (singular) not 'asks'+ const asksData = (depth.ask as Array<Record<string, unknown>>) ||+ (depth.asks as Array<Record<string, unknown>>) || [];const bidsData = (depth.bids as Array<Record<string, unknown>>) || [];- // Convert asks+ // Convert asks - Fyers uses 'volume' and 'ord'for (const ask of asksData.slice(0, 5)) {asks.push({price: Number(ask.price || 0),- quantity: Number(ask.qty || ask.volume || 0),- orders: Number(ask.nord || ask.orders || 0),+ quantity: Number(ask.volume || ask.qty || 0),+ orders: Number(ask.ord || ask.orders || ask.nord || 1),});}- // Convert bids+ // Convert bids - Fyers uses 'volume' and 'ord'for (const bid of bidsData.slice(0, 5)) {bids.push({price: Number(bid.price || 0),- quantity: Number(bid.qty || bid.volume || 0),- orders: Number(bid.nord || bid.orders || 0),+ quantity: Number(bid.volume || bid.qty || 0),+ orders: Number(bid.ord || bid.orders || bid.nord || 1),});}diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/groww/GrowwAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/groww/GrowwAdapter.tsindex 58dac3df2..334289aae 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/groww/GrowwAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/groww/GrowwAdapter.ts@@ -6,6 +6,7 @@*/import { invoke } from '@tauri-apps/api/core';+import { listen, UnlistenFn } from '@tauri-apps/api/event';import { BaseStockBrokerAdapter } from '../../BaseStockBrokerAdapter';import type {StockBrokerMetadata,@@ -68,9 +69,15 @@ export class GrowwAdapter extends BaseStockBrokerAdapter {private apiKey: string | null = null;private apiSecret: string | null = null;- // REST API polling for quotes (Groww doesn't support WebSocket)+ // Tauri event unlisteners for WebSocket events+ private tickerUnlisten: UnlistenFn | null = null;+ private orderbookUnlisten: UnlistenFn | null = null;+ private statusUnlisten: UnlistenFn | null = null;++ // Fallback: REST API polling for quotesprivate quotePollingInterval: NodeJS.Timeout | null = null;private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange }> = new Map();+ private usePollingFallback: boolean = false;// ============================================================================// Authentication@@ -625,131 +632,180 @@ export class GrowwAdapter extends BaseStockBrokerAdapter {}// ============================================================================- // REST API Polling (Groww doesn't support WebSocket)+ // WebSocket - Real WebSocket via Rust Backend (NATS protocol)// ============================================================================protected async connectWebSocketInternal(config: WebSocketConfig): Promise<void> {this.ensureConnected();try {- // Start REST API polling (every 2 minutes)+ await this.connectRealWebSocket();+ console.log('[Groww] ✓ WebSocket connected via Rust backend');+ } catch (error) {+ console.warn('[Groww] WebSocket connection failed, falling back to REST polling:', error);+ this.usePollingFallback = true;this.startQuotePolling();+ }+ }- this.wsConnected = true;- console.log('[Groww] REST API polling started (2 min interval)');- } catch (error) {- console.error('[Groww] Failed to start polling:', error);- throw error;+ private async connectRealWebSocket(): Promise<void> {+ if (!this.accessToken) {+ throw new Error('Access token required');+ }++ const result = await invoke<{ success: boolean; data?: boolean; error?: string }>('groww_ws_connect', {+ accessToken: this.accessToken,+ });++ if (!result.success) {+ throw new Error(result.error || 'WebSocket connection failed');}++ this.tickerUnlisten = await listen<{+ provider: string; symbol: string; price: number; bid?: number; ask?: number;+ volume?: number; change_percent?: number; timestamp: number;+ }>('groww_ticker', (event) => {+ const tick = event.payload;+ this.emitTick({+ symbol: tick.symbol, exchange: 'NSE' as StockExchange, mode: 'quote',+ lastPrice: tick.price, bid: tick.bid, ask: tick.ask,+ volume: tick.volume || 0, changePercent: tick.change_percent || 0, timestamp: tick.timestamp,+ });+ });++ this.orderbookUnlisten = await listen<{+ provider: string; symbol: string;+ bids: Array<{ price: number; quantity: number; orders?: number }>; asks: Array<{ price: number; quantity: number; orders?: number }>;+ timestamp: number;+ }>('groww_orderbook', (event) => {+ const data = event.payload;+ const [exchangePart, symbolPart] = data.symbol.includes(':') ? data.symbol.split(':') : ['NSE', data.symbol];+ const symbol = symbolPart || data.symbol;+ const exchange = (exchangePart as StockExchange) || 'NSE';++ console.log(`[Groww WebSocket] Depth update for ${symbol}`);++ const bestBid = data.bids?.[0];+ const bestAsk = data.asks?.[0];++ const tick: TickData = {+ symbol, exchange, mode: 'full',+ lastPrice: bestBid?.price || 0,+ bid: bestBid?.price, ask: bestAsk?.price,+ bidQty: bestBid?.quantity, askQty: bestAsk?.quantity,+ timestamp: data.timestamp,+ depth: {+ bids: data.bids?.map((b) => ({ price: b.price, quantity: b.quantity, orders: b.orders || 0 })) || [],+ asks: data.asks?.map((a) => ({ price: a.price, quantity: a.quantity, orders: a.orders || 0 })) || [],+ },+ };++ this.emitTick(tick);+ if (tick.depth) {+ this.emitDepth({ symbol, exchange, bids: tick.depth.bids, asks: tick.depth.asks });+ }+ });++ this.statusUnlisten = await listen<{+ provider: string; status: string; message?: string; timestamp: number;+ }>('groww_status', (event) => {+ const status = event.payload;+ if (status.status === 'disconnected' || status.status === 'error') {+ this.wsConnected = false;+ if (!this.usePollingFallback) { this.usePollingFallback = true; this.startQuotePolling(); }+ } else if (status.status === 'connected') {+ this.wsConnected = true;+ if (this.usePollingFallback) { this.usePollingFallback = false; this.stopQuotePolling(); }+ }+ });++ this.wsConnected = true;+ }++ private async disconnectRealWebSocket(): Promise<void> {+ if (this.tickerUnlisten) { this.tickerUnlisten(); this.tickerUnlisten = null; }+ if (this.orderbookUnlisten) { this.orderbookUnlisten(); this.orderbookUnlisten = null; }+ if (this.statusUnlisten) { this.statusUnlisten(); this.statusUnlisten = null; }+ try { await invoke('groww_ws_disconnect'); } catch (err) { console.warn('[Groww] WS disconnect error:', err); }+ this.wsConnected = false;}- /**- * Start REST API polling for quotes- */private startQuotePolling(): void {- // Stop existing pollingthis.stopQuotePolling();-- // Poll every 2 minutes (120000ms)- this.quotePollingInterval = setInterval(async () => {- await this.pollQuotesSequentially();- }, 120000);-- // Initial poll+ console.log('[Groww] Starting REST API polling (fallback mode, 2 min interval)');+ this.quotePollingInterval = setInterval(async () => { await this.pollQuotesSequentially(); }, 120000);this.pollQuotesSequentially();}- /**- * Stop REST API polling- */private stopQuotePolling(): void {- if (this.quotePollingInterval) {- clearInterval(this.quotePollingInterval);- this.quotePollingInterval = null;- }+ if (this.quotePollingInterval) { clearInterval(this.quotePollingInterval); this.quotePollingInterval = null; }}- /**- * Poll quotes sequentially for all subscribed symbols- */private async pollQuotesSequentially(): Promise<void> {- if (this.pollingSymbols.size === 0) {- return;- }-- console.log(`[Groww] Polling ${this.pollingSymbols.size} symbols...`);+ if (this.pollingSymbols.size === 0) return;for (const [key, { symbol, exchange }] of this.pollingSymbols) {try {const quote = await this.getQuoteInternal(symbol, exchange);-- const tick: TickData = {- symbol,- exchange,- mode: 'full',- lastPrice: quote.lastPrice,- open: quote.open,- high: quote.high,- low: quote.low,- close: quote.close,- volume: quote.volume,- change: quote.change,- changePercent: quote.changePercent,- timestamp: quote.timestamp,- bid: quote.bid,- bidQty: quote.bidQty,- ask: quote.ask,- askQty: quote.askQty,- };-- this.emitTick(tick);- } catch (error) {- console.error(`[Groww] Failed to poll ${symbol}:`, error);- }-- // Small delay between requests to avoid rate limiting+ this.emitTick({+ symbol, exchange, mode: 'full',+ lastPrice: quote.lastPrice, open: quote.open, high: quote.high, low: quote.low,+ close: quote.close, volume: quote.volume, change: quote.change,+ changePercent: quote.changePercent, timestamp: quote.timestamp,+ bid: quote.bid, bidQty: quote.bidQty, ask: quote.ask, askQty: quote.askQty,+ });+ } catch (error) { console.error(`[Groww] Failed to poll ${symbol}:`, error); }await new Promise(resolve => setTimeout(resolve, 100));}console.log(`[Groww] Polling complete for ${this.pollingSymbols.size} symbols`);}- /**- * Disconnect from WebSocket (stop polling)- */- async disconnectWebSocket(): Promise<void> {- this.stopQuotePolling();- this.pollingSymbols.clear();- this.wsConnected = false;- console.log('[Groww] REST API polling stopped');- }-- protected async subscribeInternal(- symbol: string,- exchange: StockExchange,- mode: SubscriptionMode- ): Promise<void> {+ protected async subscribeInternal(symbol: string, exchange: StockExchange, mode: SubscriptionMode): Promise<void> {const key = `${exchange}:${symbol}`;this.pollingSymbols.set(key, { symbol, exchange });-- console.log(`[Groww] Added ${key} to polling list (${this.pollingSymbols.size} symbols total)`);-- // Trigger immediate poll- this.pollQuotesSequentially();+ if (this.wsConnected && !this.usePollingFallback) {+ try {+ await invoke('groww_ws_subscribe', { symbol, mode: mode === 'full' ? 'full' : 'ltp' });+ console.log(`[Groww] ✓ WebSocket subscribed to ${symbol}`);+ } catch (error) {+ console.error(`[Groww] WebSocket subscribe failed:`, error);+ if (!this.usePollingFallback) { this.usePollingFallback = true; this.startQuotePolling(); }+ }+ } else {+ console.log(`[Groww] Added ${key} to polling (${this.pollingSymbols.size} symbols total)`);+ if (this.usePollingFallback) this.pollQuotesSequentially();+ }}protected async unsubscribeInternal(symbol: string, exchange: StockExchange): Promise<void> {const key = `${exchange}:${symbol}`;this.pollingSymbols.delete(key);+ if (this.wsConnected && !this.usePollingFallback) {+ try { await invoke('groww_ws_unsubscribe', { symbol }); } catch (err) { console.warn('[Groww] Unsubscribe failed:', err); }+ }+ console.log(`[Groww] Removed ${key} from polling list`);+ }++ async disconnectWebSocket(): Promise<void> {+ await this.disconnectRealWebSocket();+ this.stopQuotePolling();+ this.pollingSymbols.clear();+ this.usePollingFallback = false;+ this.wsConnected = false;+ console.log('[Groww] WebSocket and polling stopped');+ }- console.log(`[Groww] Removed ${key} from polling list (${this.pollingSymbols.size} symbols remaining)`);+ async logout(): Promise<void> {+ await this.disconnectRealWebSocket();+ this.stopQuotePolling();+ this.pollingSymbols.clear();+ this.usePollingFallback = false;+ await super.logout();}- /**- * Check if WebSocket is connected (polling is active)- */async isWebSocketConnected(): Promise<boolean> {- return this.wsConnected && this.quotePollingInterval !== null;+ return this.wsConnected;}// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/iifl/IIFLAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/iifl/IIFLAdapter.tsindex 670a27053..b5096c9ef 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/iifl/IIFLAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/iifl/IIFLAdapter.ts@@ -6,6 +6,7 @@*/import { invoke } from '@tauri-apps/api/core';+import { listen, UnlistenFn } from '@tauri-apps/api/event';import { BaseStockBrokerAdapter } from '../../BaseStockBrokerAdapter';import type {StockBrokerMetadata,@@ -73,9 +74,15 @@ export class IIFLAdapter extends BaseStockBrokerAdapter {// Symbol to Token mapping (instrument ID)private tokenCache: Map<string, number> = new Map();- // REST API polling for quotes+ // Tauri event unlisteners for WebSocket events+ private tickerUnlisten: UnlistenFn | null = null;+ private orderbookUnlisten: UnlistenFn | null = null;+ private statusUnlisten: UnlistenFn | null = null;++ // REST API polling for quotes (fallback)private quotePollingInterval: NodeJS.Timeout | null = null;private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange; token: number }> = new Map();+ private usePollingFallback: boolean = false;// ============================================================================// Authentication@@ -689,104 +696,141 @@ export class IIFLAdapter extends BaseStockBrokerAdapter {}// ============================================================================- // REST API Polling (replaces WebSocket)+ // WebSocket - Real WebSocket via Rust Backend with Polling Fallback// ============================================================================protected async connectWebSocketInternal(config: WebSocketConfig): Promise<void> {this.ensureConnected();try {- // Start REST API polling- this.startQuotePolling();- this.wsConnected = true;- console.log('IIFL: REST API polling started (2 min interval)');+ await this.connectRealWebSocket();+ console.log('[IIFL] ✓ WebSocket connected via Rust backend');} catch (error) {- console.error('Failed to start IIFL polling:', error);- throw error;+ console.warn('[IIFL] WebSocket connection failed, falling back to REST polling:', error);+ this.usePollingFallback = true;+ this.startQuotePolling();}}- /**- * Start REST API polling for quotes- */- private startQuotePolling(): void {- this.stopQuotePolling();+ private async connectRealWebSocket(): Promise<void> {+ if (!this.accessToken) {+ throw new Error('Access token required');+ }- // Poll every 2 minutes (120000ms)- this.quotePollingInterval = setInterval(async () => {- await this.pollQuotesSequentially();- }, 120000);+ const result = await invoke<{ success: boolean; data?: boolean; error?: string }>('iifl_ws_connect', {+ accessToken: this.accessToken,+ feedToken: this.feedToken || this.accessToken,+ });++ if (!result.success) throw new Error(result.error || 'WebSocket connection failed');++ this.tickerUnlisten = await listen<{+ provider: string; symbol: string; price: number; bid?: number; ask?: number;+ volume?: number; change_percent?: number; timestamp: number;+ }>('iifl_ticker', (event) => {+ const tick = event.payload;+ this.emitTick({+ symbol: tick.symbol, exchange: 'NSE' as StockExchange, mode: 'quote',+ lastPrice: tick.price, bid: tick.bid, ask: tick.ask,+ volume: tick.volume || 0, changePercent: tick.change_percent || 0, timestamp: tick.timestamp,+ });+ });- // Initial poll+ this.orderbookUnlisten = await listen<{+ provider: string; symbol: string;+ bids: Array<{ price: number; quantity: number; orders?: number }>; asks: Array<{ price: number; quantity: number; orders?: number }>;+ timestamp: number;+ }>('iifl_orderbook', (event) => {+ const data = event.payload;+ const [exchangePart, symbolPart] = data.symbol.includes(':') ? data.symbol.split(':') : ['NSE', data.symbol];+ const symbol = symbolPart || data.symbol;+ const exchange = (exchangePart as StockExchange) || 'NSE';++ console.log(`[IIFL WebSocket] Depth update for ${symbol}`);++ const bestBid = data.bids?.[0];+ const bestAsk = data.asks?.[0];++ const tick: TickData = {+ symbol, exchange, mode: 'full',+ lastPrice: bestBid?.price || 0,+ bid: bestBid?.price, ask: bestAsk?.price,+ bidQty: bestBid?.quantity, askQty: bestAsk?.quantity,+ timestamp: data.timestamp,+ depth: {+ bids: data.bids?.map((b) => ({ price: b.price, quantity: b.quantity, orders: b.orders || 0 })) || [],+ asks: data.asks?.map((a) => ({ price: a.price, quantity: a.quantity, orders: a.orders || 0 })) || [],+ },+ };++ this.emitTick(tick);+ if (tick.depth) {+ this.emitDepth({ symbol, exchange, bids: tick.depth.bids, asks: tick.depth.asks });+ }+ });++ this.statusUnlisten = await listen<{+ provider: string; status: string; message?: string; timestamp: number;+ }>('iifl_status', (event) => {+ const status = event.payload;+ if (status.status === 'disconnected' || status.status === 'error') {+ this.wsConnected = false;+ if (!this.usePollingFallback) { this.usePollingFallback = true; this.startQuotePolling(); }+ } else if (status.status === 'connected') {+ this.wsConnected = true;+ if (this.usePollingFallback) { this.usePollingFallback = false; this.stopQuotePolling(); }+ }+ });++ this.wsConnected = true;+ }++ private async disconnectRealWebSocket(): Promise<void> {+ if (this.tickerUnlisten) { this.tickerUnlisten(); this.tickerUnlisten = null; }+ if (this.orderbookUnlisten) { this.orderbookUnlisten(); this.orderbookUnlisten = null; }+ if (this.statusUnlisten) { this.statusUnlisten(); this.statusUnlisten = null; }+ try { await invoke('iifl_ws_disconnect'); } catch (err) { console.warn('[IIFL] WS disconnect error:', err); }+ this.wsConnected = false;+ }++ private startQuotePolling(): void {+ this.stopQuotePolling();+ console.log('[IIFL] Starting REST API polling (fallback mode, 2 min interval)');+ this.quotePollingInterval = setInterval(async () => { await this.pollQuotesSequentially(); }, 120000);this.pollQuotesSequentially();}- /**- * Stop REST API polling- */private stopQuotePolling(): void {- if (this.quotePollingInterval) {- clearInterval(this.quotePollingInterval);- this.quotePollingInterval = null;- }+ if (this.quotePollingInterval) { clearInterval(this.quotePollingInterval); this.quotePollingInterval = null; }}- /**- * Poll quotes sequentially for all subscribed symbols- */private async pollQuotesSequentially(): Promise<void> {- if (this.pollingSymbols.size === 0) {- return;- }-- console.log(`[IIFL] Polling ${this.pollingSymbols.size} symbols sequentially...`);+ if (this.pollingSymbols.size === 0) return;for (const [key, { symbol, exchange, token }] of this.pollingSymbols) {try {- // Ensure token is cachedthis.setToken(symbol, exchange, token);-const quote = await this.getQuoteInternal(symbol, exchange);-- const tick: TickData = {- symbol,- exchange,- mode: 'full',- lastPrice: quote.lastPrice,- open: quote.open,- high: quote.high,- low: quote.low,- close: quote.close,- volume: quote.volume,- change: quote.change,- changePercent: quote.changePercent,- timestamp: quote.timestamp,- bid: quote.bid,- bidQty: quote.bidQty,- ask: quote.ask,- askQty: quote.askQty,- };-- this.emitTick(tick);- } catch (error) {- console.error(`[IIFL] Failed to poll ${symbol}:`, error);- }-- // Small delay between requests to avoid rate limiting+ this.emitTick({+ symbol, exchange, mode: 'full',+ lastPrice: quote.lastPrice, open: quote.open, high: quote.high, low: quote.low,+ close: quote.close, volume: quote.volume, change: quote.change,+ changePercent: quote.changePercent, timestamp: quote.timestamp,+ bid: quote.bid, bidQty: quote.bidQty, ask: quote.ask, askQty: quote.askQty,+ });+ } catch (error) { console.error(`[IIFL] Failed to poll ${symbol}:`, error); }await new Promise(resolve => setTimeout(resolve, 100));}console.log(`[IIFL] Polling complete for ${this.pollingSymbols.size} symbols`);}- /**- * Disconnect from WebSocket (stop polling)- */async disconnectWebSocket(): Promise<void> {+ await this.disconnectRealWebSocket();this.stopQuotePolling();this.pollingSymbols.clear();- this.wsConnected = false;- console.log('[IIFL] REST API polling stopped');+ this.usePollingFallback = false;+ console.log('[IIFL] WebSocket disconnected');}protected async subscribeInternal(@@ -804,10 +848,22 @@ export class IIFLAdapter extends BaseStockBrokerAdapter {const key = `${exchange}:${symbol}`;this.pollingSymbols.set(key, { symbol, exchange, token });- console.log(`IIFL: Added ${key} to polling list (${this.pollingSymbols.size} symbols total)`);-- // Trigger immediate poll for this symbol- this.pollQuotesSequentially();+ // If real WebSocket is connected, subscribe via Tauri command+ if (this.wsConnected && !this.usePollingFallback) {+ try {+ await invoke('iifl_ws_subscribe', {+ symbol: `${exchange}:${symbol}`,+ mode: mode === 'full' ? 'depth' : mode === 'quote' ? 'quotes' : 'ltp',+ });+ console.log(`[IIFL] WebSocket subscribed to ${key}`);+ } catch (err) {+ console.warn(`[IIFL] WebSocket subscribe failed for ${key}, using polling:`, err);+ this.pollQuotesSequentially();+ }+ } else {+ console.log(`IIFL: Added ${key} to polling list (${this.pollingSymbols.size} symbols total)`);+ this.pollQuotesSequentially();+ }} catch (error) {console.error('Failed to subscribe:', error);throw error;@@ -831,7 +887,17 @@ export class IIFLAdapter extends BaseStockBrokerAdapter {const key = `${exchange}:${symbol}`;this.pollingSymbols.delete(key);- console.log(`IIFL: Removed ${key} from polling list (${this.pollingSymbols.size} symbols remaining)`);+ // If real WebSocket is connected, unsubscribe via Tauri command+ if (this.wsConnected && !this.usePollingFallback) {+ try {+ await invoke('iifl_ws_unsubscribe', { symbol: `${exchange}:${symbol}` });+ console.log(`[IIFL] WebSocket unsubscribed from ${key}`);+ } catch (err) {+ console.warn(`[IIFL] WebSocket unsubscribe failed for ${key}:`, err);+ }+ } else {+ console.log(`IIFL: Removed ${key} from polling list (${this.pollingSymbols.size} symbols remaining)`);+ }}// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/kotak/KotakAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/kotak/KotakAdapter.tsindex 44370a072..8f6337382 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/kotak/KotakAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/kotak/KotakAdapter.ts@@ -12,6 +12,7 @@*/import { invoke } from '@tauri-apps/api/core';+import { listen, UnlistenFn } from '@tauri-apps/api/event';import { BaseStockBrokerAdapter } from '../../BaseStockBrokerAdapter';import type {StockBrokerMetadata,@@ -75,9 +76,15 @@ export class KotakAdapter extends BaseStockBrokerAdapter {private viewToken: string | null = null;private viewSid: string | null = null;- // REST API polling for quotes+ // Tauri event unlisteners for WebSocket events+ private tickerUnlisten: UnlistenFn | null = null;+ private orderbookUnlisten: UnlistenFn | null = null;+ private statusUnlisten: UnlistenFn | null = null;++ // Fallback: REST API polling for quotes (when WebSocket fails)private quotePollingInterval: NodeJS.Timeout | null = null;private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange }> = new Map();+ private usePollingFallback: boolean = false;// ============================================================================// Authentication@@ -774,105 +781,199 @@ export class KotakAdapter extends BaseStockBrokerAdapter {}// ============================================================================- // WebSocket / Polling+ // WebSocket - Real WebSocket via Rust Backend// ============================================================================protected async connectWebSocketInternal(config: WebSocketConfig): Promise<void> {this.ensureConnected();try {- this.startQuotePolling();- this.wsConnected = true;- console.log('[Kotak] REST API polling started');+ await this.connectRealWebSocket();+ console.log('[Kotak] ✓ WebSocket connected via Rust backend');} catch (error) {- console.error('[Kotak] Failed to start polling:', error);- throw error;+ console.warn('[Kotak] WebSocket connection failed, falling back to REST polling:', error);+ this.usePollingFallback = true;+ this.startQuotePolling();}}- private startQuotePolling(): void {- this.stopQuotePolling();+ private async connectRealWebSocket(): Promise<void> {+ if (!this.accessToken) {+ throw new Error('Access token required');+ }++ const result = await invoke<{+ success: boolean;+ data?: boolean;+ error?: string;+ }>('kotak_ws_connect', {+ accessToken: this.accessToken,+ });++ if (!result.success) {+ throw new Error(result.error || 'WebSocket connection failed');+ }++ this.tickerUnlisten = await listen<{+ provider: string;+ symbol: string;+ price: number;+ bid?: number;+ ask?: number;+ volume?: number;+ change_percent?: number;+ timestamp: number;+ }>('kotak_ticker', (event) => {+ const tick = event.payload;+ this.emitTick({+ symbol: tick.symbol,+ exchange: 'NSE' as StockExchange,+ mode: 'quote',+ lastPrice: tick.price,+ bid: tick.bid,+ ask: tick.ask,+ volume: tick.volume || 0,+ changePercent: tick.change_percent || 0,+ timestamp: tick.timestamp,+ });+ });++ this.orderbookUnlisten = await listen<{+ provider: string;+ symbol: string;+ bids: Array<{ price: number; quantity: number; orders?: number }>;+ asks: Array<{ price: number; quantity: number; orders?: number }>;+ timestamp: number;+ }>('kotak_orderbook', (event) => {+ const data = event.payload;+ const [exchangePart, symbolPart] = data.symbol.includes(':') ? data.symbol.split(':') : ['NSE', data.symbol];+ const symbol = symbolPart || data.symbol;+ const exchange = (exchangePart as StockExchange) || 'NSE';++ console.log(`[Kotak WebSocket] Depth update for ${symbol}`);++ const bestBid = data.bids?.[0];+ const bestAsk = data.asks?.[0];++ const tick: TickData = {+ symbol, exchange, mode: 'full',+ lastPrice: bestBid?.price || 0,+ bid: bestBid?.price, ask: bestAsk?.price,+ bidQty: bestBid?.quantity, askQty: bestAsk?.quantity,+ timestamp: data.timestamp,+ depth: {+ bids: data.bids?.map((b) => ({ price: b.price, quantity: b.quantity, orders: b.orders || 0 })) || [],+ asks: data.asks?.map((a) => ({ price: a.price, quantity: a.quantity, orders: a.orders || 0 })) || [],+ },+ };++ this.emitTick(tick);+ if (tick.depth) {+ this.emitDepth({ symbol, exchange, bids: tick.depth.bids, asks: tick.depth.asks });+ }+ });++ this.statusUnlisten = await listen<{+ provider: string;+ status: string;+ message?: string;+ timestamp: number;+ }>('kotak_status', (event) => {+ const status = event.payload;+ console.log(`[Kotak WebSocket] Status: ${status.status}`);+ if (status.status === 'disconnected' || status.status === 'error') {+ this.wsConnected = false;+ if (!this.usePollingFallback) {+ this.usePollingFallback = true;+ this.startQuotePolling();+ }+ } else if (status.status === 'connected') {+ this.wsConnected = true;+ if (this.usePollingFallback) {+ this.usePollingFallback = false;+ this.stopQuotePolling();+ }+ }+ });- // Poll every 30 seconds- this.quotePollingInterval = setInterval(async () => {- await this.pollQuotes();- }, 30000);+ this.wsConnected = true;+ }++ private async disconnectRealWebSocket(): Promise<void> {+ if (this.tickerUnlisten) { this.tickerUnlisten(); this.tickerUnlisten = null; }+ if (this.orderbookUnlisten) { this.orderbookUnlisten(); this.orderbookUnlisten = null; }+ if (this.statusUnlisten) { this.statusUnlisten(); this.statusUnlisten = null; }+ try { await invoke('kotak_ws_disconnect'); } catch (err) { console.warn('[Kotak] WS disconnect error:', err); }+ this.wsConnected = false;+ }- // Initial poll+ private startQuotePolling(): void {+ this.stopQuotePolling();+ console.log('[Kotak] Starting REST API polling (fallback mode)');+ this.quotePollingInterval = setInterval(async () => { await this.pollQuotes(); }, 30000);this.pollQuotes();}private stopQuotePolling(): void {- if (this.quotePollingInterval) {- clearInterval(this.quotePollingInterval);- this.quotePollingInterval = null;- }+ if (this.quotePollingInterval) { clearInterval(this.quotePollingInterval); this.quotePollingInterval = null; }}private async pollQuotes(): Promise<void> {if (this.pollingSymbols.size === 0) return;-- console.log(`[Kotak] Polling ${this.pollingSymbols.size} symbols...`);-for (const [key, { symbol, exchange }] of this.pollingSymbols) {try {const quote = await this.getQuoteInternal(symbol, exchange);-- const tick: TickData = {- symbol,- exchange,- lastPrice: quote.lastPrice,- open: quote.open,- high: quote.high,- low: quote.low,- close: quote.close,- volume: quote.volume,- change: quote.change,- changePercent: quote.changePercent,- timestamp: quote.timestamp,- bid: quote.bid,- bidQty: quote.bidQty,- ask: quote.ask,- askQty: quote.askQty,- mode: 'full',- };-- this.emitTick(tick);- } catch (error) {- console.error(`[Kotak] Poll error for ${symbol}:`, error);- }-- // Small delay between requests+ this.emitTick({+ symbol, exchange,+ lastPrice: quote.lastPrice, open: quote.open, high: quote.high, low: quote.low,+ close: quote.close, volume: quote.volume, change: quote.change,+ changePercent: quote.changePercent, timestamp: quote.timestamp,+ bid: quote.bid, bidQty: quote.bidQty, ask: quote.ask, askQty: quote.askQty, mode: 'full',+ });+ } catch (error) { console.error(`[Kotak] Poll error for ${symbol}:`, error); }await new Promise(resolve => setTimeout(resolve, 200));}-- console.log(`[Kotak] Polling complete`);}async disconnectWebSocket(): Promise<void> {+ await this.disconnectRealWebSocket();this.stopQuotePolling();this.pollingSymbols.clear();+ this.usePollingFallback = false;this.wsConnected = false;- console.log('[Kotak] Polling stopped');}- protected async subscribeInternal(- symbol: string,- exchange: StockExchange,- mode: SubscriptionMode- ): Promise<void> {+ protected async subscribeInternal(symbol: string, exchange: StockExchange, mode: SubscriptionMode): Promise<void> {const key = `${exchange}:${symbol}`;this.pollingSymbols.set(key, { symbol, exchange });- console.log(`[Kotak] Added ${key} to polling (${this.pollingSymbols.size} total)`);-- // Trigger immediate poll- this.pollQuotes();+ if (this.wsConnected && !this.usePollingFallback) {+ try {+ await invoke('kotak_ws_subscribe', { symbol, mode: mode === 'full' ? 'full' : 'ltp' });+ console.log(`[Kotak] ✓ WebSocket subscribed to ${symbol}`);+ } catch (error) {+ console.error(`[Kotak] WebSocket subscribe failed:`, error);+ if (!this.usePollingFallback) { this.usePollingFallback = true; this.startQuotePolling(); }+ }+ } else {+ console.log(`[Kotak] Added ${key} to polling`);+ if (this.usePollingFallback) this.pollQuotes();+ }}protected async unsubscribeInternal(symbol: string, exchange: StockExchange): Promise<void> {const key = `${exchange}:${symbol}`;this.pollingSymbols.delete(key);- console.log(`[Kotak] Removed ${key} from polling`);+ if (this.wsConnected && !this.usePollingFallback) {+ try { await invoke('kotak_ws_unsubscribe', { symbol }); } catch (err) { console.warn('[Kotak] Unsubscribe failed:', err); }+ }+ }++ async logout(): Promise<void> {+ await this.disconnectRealWebSocket();+ this.stopQuotePolling();+ this.pollingSymbols.clear();+ this.usePollingFallback = false;+ await super.logout();}// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/motilal/MotilalAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/motilal/MotilalAdapter.tsindex 988962751..0855865cc 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/motilal/MotilalAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/motilal/MotilalAdapter.ts@@ -6,6 +6,7 @@*/import { invoke } from '@tauri-apps/api/core';+import { listen, UnlistenFn } from '@tauri-apps/api/event';import { BaseStockBrokerAdapter } from '../../BaseStockBrokerAdapter';import type {StockBrokerMetadata,@@ -30,6 +31,7 @@ import type {SubscriptionMode,BulkOperationResult,SmartOrderParams,+ TickData,} from '../../types';import {MOTILAL_METADATA,@@ -63,6 +65,16 @@ export class MotilalAdapter extends BaseStockBrokerAdapter {private apiKey: string = '';private vendorCode: string = '';+ // Tauri event unlisteners for WebSocket events+ private tickerUnlisten: UnlistenFn | null = null;+ private orderbookUnlisten: UnlistenFn | null = null;+ private statusUnlisten: UnlistenFn | null = null;++ // REST API polling for quotes (fallback)+ private quotePollingInterval: NodeJS.Timeout | null = null;+ private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange }> = new Map();+ private usePollingFallback: boolean = false;+// ============================================================================// AUTHENTICATION// ============================================================================@@ -605,28 +617,192 @@ export class MotilalAdapter extends BaseStockBrokerAdapter {}// ============================================================================- // WEBSOCKET (Internal implementations)+ // WebSocket - Real WebSocket via Rust Backend with Polling Fallback// ============================================================================protected async connectWebSocketInternal(_config: WebSocketConfig): Promise<void> {- // WebSocket streaming not implemented - would require Motilal's WebSocket API- console.warn('Motilal WebSocket not implemented in REST adapter');+ this.ensureConnected();++ try {+ await this.connectRealWebSocket();+ console.log('[Motilal] ✓ WebSocket connected via Rust backend');+ } catch (error) {+ console.warn('[Motilal] WebSocket connection failed, falling back to REST polling:', error);+ this.usePollingFallback = true;+ this.startQuotePolling();+ }+ }++ private async connectRealWebSocket(): Promise<void> {+ if (!this.authToken) {+ throw new Error('Auth token required');+ }++ const result = await invoke<{ success: boolean; data?: boolean; error?: string }>('motilal_ws_connect', {+ authToken: this.authToken,+ apiKey: this.apiKey,+ vendorCode: this.vendorCode,+ });++ if (!result.success) throw new Error(result.error || 'WebSocket connection failed');++ this.tickerUnlisten = await listen<{+ provider: string; symbol: string; price: number; bid?: number; ask?: number;+ volume?: number; change_percent?: number; timestamp: number;+ }>('motilal_ticker', (event) => {+ const tick = event.payload;+ this.emitTick({+ symbol: tick.symbol, exchange: 'NSE' as StockExchange, mode: 'quote',+ lastPrice: tick.price, bid: tick.bid, ask: tick.ask,+ volume: tick.volume || 0, changePercent: tick.change_percent || 0, timestamp: tick.timestamp,+ });+ });++ this.orderbookUnlisten = await listen<{+ provider: string; symbol: string;+ bids: Array<{ price: number; quantity: number; orders?: number }>; asks: Array<{ price: number; quantity: number; orders?: number }>;+ timestamp: number;+ }>('motilal_orderbook', (event) => {+ const data = event.payload;+ const [exchangePart, symbolPart] = data.symbol.includes(':') ? data.symbol.split(':') : ['NSE', data.symbol];+ const symbol = symbolPart || data.symbol;+ const exchange = (exchangePart as StockExchange) || 'NSE';++ console.log(`[Motilal WebSocket] Depth update for ${symbol}`);++ const bestBid = data.bids?.[0];+ const bestAsk = data.asks?.[0];++ const tick: TickData = {+ symbol, exchange, mode: 'full',+ lastPrice: bestBid?.price || 0,+ bid: bestBid?.price, ask: bestAsk?.price,+ bidQty: bestBid?.quantity, askQty: bestAsk?.quantity,+ timestamp: data.timestamp,+ depth: {+ bids: data.bids?.map((b) => ({ price: b.price, quantity: b.quantity, orders: b.orders || 0 })) || [],+ asks: data.asks?.map((a) => ({ price: a.price, quantity: a.quantity, orders: a.orders || 0 })) || [],+ },+ };++ this.emitTick(tick);+ if (tick.depth) {+ this.emitDepth({ symbol, exchange, bids: tick.depth.bids, asks: tick.depth.asks });+ }+ });++ this.statusUnlisten = await listen<{+ provider: string; status: string; message?: string; timestamp: number;+ }>('motilal_status', (event) => {+ const status = event.payload;+ if (status.status === 'disconnected' || status.status === 'error') {+ this.wsConnected = false;+ if (!this.usePollingFallback) { this.usePollingFallback = true; this.startQuotePolling(); }+ } else if (status.status === 'connected') {+ this.wsConnected = true;+ if (this.usePollingFallback) { this.usePollingFallback = false; this.stopQuotePolling(); }+ }+ });++ this.wsConnected = true;+ }++ private async disconnectRealWebSocket(): Promise<void> {+ if (this.tickerUnlisten) { this.tickerUnlisten(); this.tickerUnlisten = null; }+ if (this.orderbookUnlisten) { this.orderbookUnlisten(); this.orderbookUnlisten = null; }+ if (this.statusUnlisten) { this.statusUnlisten(); this.statusUnlisten = null; }+ try { await invoke('motilal_ws_disconnect'); } catch (err) { console.warn('[Motilal] WS disconnect error:', err); }+ this.wsConnected = false;+ }++ private startQuotePolling(): void {+ this.stopQuotePolling();+ console.log('[Motilal] Starting REST API polling (fallback mode, 2 min interval)');+ this.quotePollingInterval = setInterval(async () => { await this.pollQuotesSequentially(); }, 120000);+ this.pollQuotesSequentially();+ }++ private stopQuotePolling(): void {+ if (this.quotePollingInterval) { clearInterval(this.quotePollingInterval); this.quotePollingInterval = null; }+ }++ private async pollQuotesSequentially(): Promise<void> {+ if (this.pollingSymbols.size === 0) return;++ for (const [key, { symbol, exchange }] of this.pollingSymbols) {+ try {+ const quote = await this.getQuoteInternal(symbol, exchange);+ this.emitTick({+ symbol, exchange, mode: 'full',+ lastPrice: quote.lastPrice, open: quote.open, high: quote.high, low: quote.low,+ close: quote.close, volume: quote.volume, change: quote.change,+ changePercent: quote.changePercent, timestamp: quote.timestamp,+ bid: quote.bid, bidQty: quote.bidQty, ask: quote.ask, askQty: quote.askQty,+ });+ } catch (error) { console.error(`[Motilal] Failed to poll ${symbol}:`, error); }+ await new Promise(resolve => setTimeout(resolve, 100));+ }++ console.log(`[Motilal] Polling complete for ${this.pollingSymbols.size} symbols`);+ }++ async disconnectWebSocket(): Promise<void> {+ await this.disconnectRealWebSocket();+ this.stopQuotePolling();+ this.pollingSymbols.clear();+ this.usePollingFallback = false;+ console.log('[Motilal] WebSocket disconnected');}protected async subscribeInternal(- _symbol: string,- _exchange: StockExchange,- _mode: SubscriptionMode+ symbol: string,+ exchange: StockExchange,+ mode: SubscriptionMode): Promise<void> {- // WebSocket subscription not implemented- console.warn('Motilal WebSocket subscription not implemented');+ try {+ const key = `${exchange}:${symbol}`;+ this.pollingSymbols.set(key, { symbol, exchange });++ // If real WebSocket is connected, subscribe via Tauri command+ if (this.wsConnected && !this.usePollingFallback) {+ try {+ await invoke('motilal_ws_subscribe', {+ symbol: `${exchange}:${symbol}`,+ mode: mode === 'full' ? 'depth' : mode === 'quote' ? 'quotes' : 'ltp',+ });+ console.log(`[Motilal] WebSocket subscribed to ${key}`);+ } catch (err) {+ console.warn(`[Motilal] WebSocket subscribe failed for ${key}, using polling:`, err);+ this.pollQuotesSequentially();+ }+ } else {+ console.log(`Motilal: Added ${key} to polling list (${this.pollingSymbols.size} symbols total)`);+ this.pollQuotesSequentially();+ }+ } catch (error) {+ console.error('Failed to subscribe:', error);+ throw error;+ }}protected async unsubscribeInternal(- _symbol: string,- _exchange: StockExchange+ symbol: string,+ exchange: StockExchange): Promise<void> {- // WebSocket unsubscription not implemented+ const key = `${exchange}:${symbol}`;+ this.pollingSymbols.delete(key);++ // If real WebSocket is connected, unsubscribe via Tauri command+ if (this.wsConnected && !this.usePollingFallback) {+ try {+ await invoke('motilal_ws_unsubscribe', { symbol: `${exchange}:${symbol}` });+ console.log(`[Motilal] WebSocket unsubscribed from ${key}`);+ } catch (err) {+ console.warn(`[Motilal] WebSocket unsubscribe failed for ${key}:`, err);+ }+ } else {+ console.log(`Motilal: Removed ${key} from polling list (${this.pollingSymbols.size} symbols remaining)`);+ }}// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/shoonya/ShoonyaAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/shoonya/ShoonyaAdapter.tsindex cbe1f6c59..c2d22707f 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/shoonya/ShoonyaAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/shoonya/ShoonyaAdapter.ts@@ -8,6 +8,7 @@*/import { invoke } from '@tauri-apps/api/core';+import { listen, UnlistenFn } from '@tauri-apps/api/event';import { BaseStockBrokerAdapter } from '../../BaseStockBrokerAdapter';import type {StockBrokerMetadata,@@ -63,9 +64,15 @@ export class ShoonyaAdapter extends BaseStockBrokerAdapter {private apiKey: string | null = null; // vendor_codeprivate apiSecret: string | null = null; // api_secretkey- // REST API polling for quotes+ // Tauri event unlisteners for WebSocket events+ private tickerUnlisten: UnlistenFn | null = null;+ private orderbookUnlisten: UnlistenFn | null = null;+ private statusUnlisten: UnlistenFn | null = null;++ // Fallback: REST API polling for quotes (when WebSocket fails)private quotePollingInterval: NodeJS.Timeout | null = null;private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange; token: string }> = new Map();+ private usePollingFallback: boolean = false;// ============================================================================// Authentication@@ -637,19 +644,185 @@ export class ShoonyaAdapter extends BaseStockBrokerAdapter {}// ============================================================================- // WebSocket - Internal Implementations (REST polling)+ // WebSocket - Real WebSocket via Rust Backend// ============================================================================protected async connectWebSocketInternal(config: WebSocketConfig): Promise<void> {this.ensureAuthenticated();- // Start REST API polling- this.startQuotePolling();- console.log('[Shoonya] REST API polling started');++ try {+ // Try real WebSocket connection via Rust backend+ await this.connectRealWebSocket();+ console.log('[Shoonya] ✓ WebSocket connected via Rust backend');+ } catch (error) {+ console.warn('[Shoonya] WebSocket connection failed, falling back to REST polling:', error);+ this.usePollingFallback = true;+ this.startQuotePolling();+ }+ }++ /**+ * Connect to real Shoonya WebSocket via Tauri/Rust backend+ */+ private async connectRealWebSocket(): Promise<void> {+ if (!this.accessToken || !this.userId) {+ throw new Error('Access token and user ID required');+ }++ // Call Rust backend to connect WebSocket+ const result = await invoke<{+ success: boolean;+ data?: boolean;+ error?: string;+ }>('shoonya_ws_connect', {+ userId: this.userId,+ accessToken: this.accessToken,+ });++ if (!result.success) {+ throw new Error(result.error || 'WebSocket connection failed');+ }++ // Listen for ticker events from Rust backend+ this.tickerUnlisten = await listen<{+ provider: string;+ symbol: string;+ price: number;+ bid?: number;+ ask?: number;+ volume?: number;+ change_percent?: number;+ timestamp: number;+ }>('shoonya_ticker', (event) => {+ const tick = event.payload;++ // Lookup symbol from token+ let symbolInfo: { symbol: string; exchange: StockExchange } | undefined;+ for (const [, info] of this.pollingSymbols) {+ if (info.token === tick.symbol) {+ symbolInfo = info;+ break;+ }+ }++ this.emitTick({+ symbol: symbolInfo?.symbol || tick.symbol,+ exchange: symbolInfo?.exchange || ('NSE' as StockExchange),+ mode: 'quote',+ lastPrice: tick.price,+ bid: tick.bid,+ ask: tick.ask,+ volume: tick.volume || 0,+ changePercent: tick.change_percent || 0,+ timestamp: tick.timestamp,+ });+ });++ // Listen for orderbook/depth events+ this.orderbookUnlisten = await listen<{+ provider: string;+ symbol: string;+ bids: Array<{ price: number; quantity: number; orders?: number }>;+ asks: Array<{ price: number; quantity: number; orders?: number }>;+ timestamp: number;+ }>('shoonya_orderbook', (event) => {+ const data = event.payload;++ const [exchangePart, symbolPart] = data.symbol.includes(':')+ ? data.symbol.split(':')+ : ['NSE', data.symbol];+ const symbol = symbolPart || data.symbol;+ const exchange = (exchangePart as StockExchange) || 'NSE';++ console.log(`[Shoonya WebSocket] Depth update for ${symbol}:`, {+ bids: data.bids?.length || 0,+ asks: data.asks?.length || 0,+ });++ const bestBid = data.bids?.[0];+ const bestAsk = data.asks?.[0];++ const tick: TickData = {+ symbol,+ exchange,+ mode: 'full',+ lastPrice: bestBid?.price || 0,+ bid: bestBid?.price,+ ask: bestAsk?.price,+ bidQty: bestBid?.quantity,+ askQty: bestAsk?.quantity,+ timestamp: data.timestamp,+ depth: {+ bids: data.bids?.map((b) => ({ price: b.price, quantity: b.quantity, orders: b.orders || 0 })) || [],+ asks: data.asks?.map((a) => ({ price: a.price, quantity: a.quantity, orders: a.orders || 0 })) || [],+ },+ };++ this.emitTick(tick);++ if (tick.depth) {+ this.emitDepth({ symbol, exchange, bids: tick.depth.bids, asks: tick.depth.asks });+ }+ });++ // Listen for status/connection events+ this.statusUnlisten = await listen<{+ provider: string;+ status: string;+ message?: string;+ timestamp: number;+ }>('shoonya_status', (event) => {+ const status = event.payload;+ console.log(`[Shoonya WebSocket] Status: ${status.status} - ${status.message || ''}`);++ if (status.status === 'disconnected' || status.status === 'error') {+ this.wsConnected = false;+ if (!this.usePollingFallback) {+ console.warn('[Shoonya] WebSocket disconnected, enabling polling fallback');+ this.usePollingFallback = true;+ this.startQuotePolling();+ }+ } else if (status.status === 'connected') {+ this.wsConnected = true;+ if (this.usePollingFallback) {+ console.log('[Shoonya] WebSocket reconnected, disabling polling fallback');+ this.usePollingFallback = false;+ this.stopQuotePolling();+ }+ }+ });++ this.wsConnected = true;+ }++ private async disconnectRealWebSocket(): Promise<void> {+ if (this.tickerUnlisten) {+ this.tickerUnlisten();+ this.tickerUnlisten = null;+ }+ if (this.orderbookUnlisten) {+ this.orderbookUnlisten();+ this.orderbookUnlisten = null;+ }+ if (this.statusUnlisten) {+ this.statusUnlisten();+ this.statusUnlisten = null;+ }++ try {+ await invoke('shoonya_ws_disconnect');+ } catch (err) {+ console.warn('[Shoonya] WebSocket disconnect error:', err);+ }++ this.wsConnected = false;}private startQuotePolling(): void {this.stopQuotePolling();+ console.log('[Shoonya] Starting REST API polling (fallback mode, 2 min interval)');+// Poll every 2 minutesthis.quotePollingInterval = setInterval(async () => {await this.pollQuotesSequentially();@@ -705,8 +878,30 @@ export class ShoonyaAdapter extends BaseStockBrokerAdapter {const key = `${exchange}:${symbol}`;this.pollingSymbols.set(key, { symbol, exchange, token });- console.log(`[Shoonya] Added ${key} to polling list`);- this.pollQuotesSequentially();+ if (this.wsConnected && !this.usePollingFallback) {+ try {+ const wsMode = mode === 'full' ? 'd' : 't'; // d = depth, t = touchline++ await invoke('shoonya_ws_subscribe', {+ symbol: token,+ exchange: SHOONYA_EXCHANGE_MAP[exchange] || exchange,+ mode: wsMode,+ });++ console.log(`[Shoonya] ✓ WebSocket subscribed to ${symbol} (token: ${token}, mode: ${wsMode})`);+ } catch (error) {+ console.error(`[Shoonya] WebSocket subscribe failed:`, error);+ if (!this.usePollingFallback) {+ this.usePollingFallback = true;+ this.startQuotePolling();+ }+ }+ } else {+ console.log(`[Shoonya] Added ${key} to polling list`);+ if (this.usePollingFallback) {+ this.pollQuotesSequentially();+ }+ }} catch (error) {console.error('Failed to subscribe:', error);}@@ -714,13 +909,29 @@ export class ShoonyaAdapter extends BaseStockBrokerAdapter {protected async unsubscribeInternal(symbol: string, exchange: StockExchange): Promise<void> {const key = `${exchange}:${symbol}`;+ const symbolInfo = this.pollingSymbols.get(key);this.pollingSymbols.delete(key);- console.log(`[Shoonya] Removed ${key} from polling list`);++ if (this.wsConnected && !this.usePollingFallback && symbolInfo) {+ try {+ await invoke('shoonya_ws_unsubscribe', {+ symbol: symbolInfo.token,+ exchange: SHOONYA_EXCHANGE_MAP[exchange] || exchange,+ });+ console.log(`[Shoonya] ✓ WebSocket unsubscribed from ${symbol}`);+ } catch (error) {+ console.warn(`[Shoonya] WebSocket unsubscribe failed:`, error);+ }+ } else {+ console.log(`[Shoonya] Removed ${key} from polling list`);+ }}async logout(): Promise<void> {+ await this.disconnectRealWebSocket();this.stopQuotePolling();this.pollingSymbols.clear();+ this.usePollingFallback = false;await super.logout();}diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/upstox/UpstoxAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/upstox/UpstoxAdapter.tsindex 8665990e2..1c86cc43e 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/upstox/UpstoxAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/upstox/UpstoxAdapter.ts@@ -6,6 +6,7 @@*/import { invoke } from '@tauri-apps/api/core';+import { listen, UnlistenFn } from '@tauri-apps/api/event';import { BaseStockBrokerAdapter } from '../../BaseStockBrokerAdapter';import type {StockBrokerMetadata,@@ -64,9 +65,15 @@ export class UpstoxAdapter extends BaseStockBrokerAdapter {private apiSecret: string | null = null;private redirectUri: string = 'http://localhost:5000/callback';- // REST API polling for quotes+ // Tauri event unlisteners for WebSocket events+ private tickerUnlisten: UnlistenFn | null = null;+ private orderbookUnlisten: UnlistenFn | null = null;+ private statusUnlisten: UnlistenFn | null = null;++ // Fallback: REST API polling for quotes (when WebSocket fails)private quotePollingInterval: NodeJS.Timeout | null = null;private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange }> = new Map();+ private usePollingFallback: boolean = false;// ============================================================================// Authentication@@ -725,25 +732,207 @@ export class UpstoxAdapter extends BaseStockBrokerAdapter {}// ============================================================================- // WebSocket / Polling+ // WebSocket - Real WebSocket via Rust Backend// ============================================================================protected async connectWebSocketInternal(config: WebSocketConfig): Promise<void> {this.ensureConnected();try {- this.startQuotePolling();- this.wsConnected = true;- console.log('[Upstox] REST API polling started');+ // Try real WebSocket connection via Rust backend+ await this.connectRealWebSocket();+ console.log('[Upstox] ✓ WebSocket connected via Rust backend');} catch (error) {- console.error('[Upstox] Failed to start polling:', error);- throw error;+ console.warn('[Upstox] WebSocket connection failed, falling back to REST polling:', error);+ this.usePollingFallback = true;+ this.startQuotePolling();+ }+ }++ /**+ * Connect to real Upstox WebSocket via Tauri/Rust backend+ */+ private async connectRealWebSocket(): Promise<void> {+ if (!this.accessToken) {+ throw new Error('Access token not available');+ }++ // Call Rust backend to connect WebSocket+ const result = await invoke<{+ success: boolean;+ data?: boolean;+ error?: string;+ }>('upstox_ws_connect', {+ accessToken: this.accessToken,+ });++ if (!result.success) {+ throw new Error(result.error || 'WebSocket connection failed');+ }++ // Listen for ticker events from Rust backend+ this.tickerUnlisten = await listen<{+ provider: string;+ symbol: string;+ price: number;+ bid?: number;+ ask?: number;+ volume?: number;+ change_percent?: number;+ timestamp: number;+ }>('upstox_ticker', (event) => {+ const tick = event.payload;++ // Parse exchange from instrument key (format: "NSE_EQ|RELIANCE")+ const parts = tick.symbol.split('|');+ const exchangePart = parts[0] || 'NSE_EQ';+ const exchange = exchangePart.startsWith('BSE') ? 'BSE' : 'NSE';+ const symbolName = parts[1] || tick.symbol;++ this.emitTick({+ symbol: symbolName,+ exchange: exchange as StockExchange,+ mode: 'quote',+ lastPrice: tick.price,+ bid: tick.bid,+ ask: tick.ask,+ volume: tick.volume || 0,+ changePercent: tick.change_percent || 0,+ timestamp: tick.timestamp,+ });+ });++ // Listen for orderbook/depth events+ this.orderbookUnlisten = await listen<{+ provider: string;+ symbol: string;+ bids: Array<{ price: number; quantity: number; orders?: number }>;+ asks: Array<{ price: number; quantity: number; orders?: number }>;+ timestamp: number;+ }>('upstox_orderbook', (event) => {+ const data = event.payload;++ // Parse symbol from Upstox format (e.g., "NSE_EQ|RELIANCE" -> "RELIANCE")+ const [exchangePart, symbolPart] = data.symbol.includes('|')+ ? data.symbol.split('|')+ : [data.symbol.split(':')[0], data.symbol.split(':')[1] || data.symbol];+ const symbol = symbolPart?.replace('-EQ', '') || data.symbol;+ const exchange = exchangePart?.replace('_EQ', '').replace('_FO', '') as StockExchange || 'NSE';++ console.log(`[Upstox WebSocket] Depth update for ${symbol}:`, {+ bids: data.bids?.length || 0,+ asks: data.asks?.length || 0,+ });++ // Get best bid/ask from depth+ const bestBid = data.bids?.[0];+ const bestAsk = data.asks?.[0];++ // Create tick data with depth information+ const tick: TickData = {+ symbol,+ exchange,+ mode: 'full',+ lastPrice: bestBid?.price || 0,+ bid: bestBid?.price,+ ask: bestAsk?.price,+ bidQty: bestBid?.quantity,+ askQty: bestAsk?.quantity,+ timestamp: data.timestamp,+ depth: {+ bids: data.bids?.map((b) => ({+ price: b.price,+ quantity: b.quantity,+ orders: b.orders || 0,+ })) || [],+ asks: data.asks?.map((a) => ({+ price: a.price,+ quantity: a.quantity,+ orders: a.orders || 0,+ })) || [],+ },+ };++ this.emitTick(tick);++ // Also emit depth data separately for UI components+ if (tick.depth) {+ this.emitDepth({+ symbol,+ exchange,+ bids: tick.depth.bids,+ asks: tick.depth.asks,+ });+ }+ });++ // Listen for status/connection events+ this.statusUnlisten = await listen<{+ provider: string;+ status: string;+ message?: string;+ timestamp: number;+ }>('upstox_status', (event) => {+ const status = event.payload;+ console.log(`[Upstox WebSocket] Status: ${status.status} - ${status.message || ''}`);++ // Handle disconnection+ if (status.status === 'disconnected' || status.status === 'error') {+ this.wsConnected = false;++ // Auto-fallback to polling on disconnect+ if (!this.usePollingFallback) {+ console.warn('[Upstox] WebSocket disconnected, enabling polling fallback');+ this.usePollingFallback = true;+ this.startQuotePolling();+ }+ } else if (status.status === 'connected') {+ this.wsConnected = true;+ // Disable polling fallback when connected+ if (this.usePollingFallback) {+ console.log('[Upstox] WebSocket reconnected, disabling polling fallback');+ this.usePollingFallback = false;+ this.stopQuotePolling();+ }+ }+ });++ this.wsConnected = true;+ }++ /**+ * Disconnect from WebSocket+ */+ private async disconnectRealWebSocket(): Promise<void> {+ // Cleanup Tauri event listeners+ if (this.tickerUnlisten) {+ this.tickerUnlisten();+ this.tickerUnlisten = null;+ }+ if (this.orderbookUnlisten) {+ this.orderbookUnlisten();+ this.orderbookUnlisten = null;+ }+ if (this.statusUnlisten) {+ this.statusUnlisten();+ this.statusUnlisten = null;+ }++ // Call Rust backend to disconnect+ try {+ await invoke('upstox_ws_disconnect');+ } catch (err) {+ console.warn('[Upstox] WebSocket disconnect error:', err);}++ this.wsConnected = false;}private startQuotePolling(): void {this.stopQuotePolling();+ console.log('[Upstox] Starting REST API polling (fallback mode, 2 min interval)');+// Poll every 2 minutesthis.quotePollingInterval = setInterval(async () => {await this.pollQuotes();@@ -801,10 +990,16 @@ export class UpstoxAdapter extends BaseStockBrokerAdapter {}async disconnectWebSocket(): Promise<void> {+ // Disconnect real WebSocket+ await this.disconnectRealWebSocket();++ // Stop polling fallbackthis.stopQuotePolling();this.pollingSymbols.clear();+ this.usePollingFallback = false;+this.wsConnected = false;- console.log('[Upstox] Polling stopped');+ console.log('[Upstox] WebSocket disconnected');}protected async subscribeInternal(@@ -812,18 +1007,77 @@ export class UpstoxAdapter extends BaseStockBrokerAdapter {exchange: StockExchange,mode: SubscriptionMode): Promise<void> {+ const instrumentKey = await this.getInstrumentKey(symbol, exchange);const key = `${exchange}:${symbol}`;++ // Always track in pollingSymbols for fallbackthis.pollingSymbols.set(key, { symbol, exchange });- console.log(`[Upstox] Added ${key} to polling (${this.pollingSymbols.size} total)`);- // Trigger immediate poll- this.pollQuotes();+ if (this.wsConnected && !this.usePollingFallback) {+ // Use real WebSocket subscription+ try {+ const wsMode = mode === 'full' ? 'full' : 'ltpc';++ await invoke('upstox_ws_subscribe', {+ symbol: instrumentKey,+ mode: wsMode,+ });++ console.log(`[Upstox] ✓ WebSocket subscribed to ${instrumentKey} (mode: ${wsMode})`);+ } catch (error) {+ console.error(`[Upstox] WebSocket subscribe failed for ${instrumentKey}:`, error);+ // Fallback to polling for this symbol+ if (!this.usePollingFallback) {+ this.usePollingFallback = true;+ this.startQuotePolling();+ }+ }+ } else {+ // Using polling fallback+ console.log(`[Upstox] Added ${key} to polling list (${this.pollingSymbols.size} symbols)`);++ // Trigger immediate poll+ if (this.usePollingFallback) {+ this.pollQuotes();+ }+ }}protected async unsubscribeInternal(symbol: string, exchange: StockExchange): Promise<void> {+ const instrumentKey = await this.getInstrumentKey(symbol, exchange);const key = `${exchange}:${symbol}`;++ // Remove from polling symbolsthis.pollingSymbols.delete(key);- console.log(`[Upstox] Removed ${key} from polling`);++ if (this.wsConnected && !this.usePollingFallback) {+ // Unsubscribe via real WebSocket+ try {+ await invoke('upstox_ws_unsubscribe', {+ symbol: instrumentKey,+ });+ console.log(`[Upstox] ✓ WebSocket unsubscribed from ${instrumentKey}`);+ } catch (error) {+ console.warn(`[Upstox] WebSocket unsubscribe failed for ${instrumentKey}:`, error);+ }+ } else {+ console.log(`[Upstox] Removed ${key} from polling list (${this.pollingSymbols.size} remaining)`);+ }+ }++ /**+ * Cleanup WebSocket and polling on logout+ */+ async logout(): Promise<void> {+ // Disconnect real WebSocket+ await this.disconnectRealWebSocket();++ // Stop polling fallback+ this.stopQuotePolling();+ this.pollingSymbols.clear();+ this.usePollingFallback = false;++ await super.logout();}// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/upstox/constants.ts b/fincept-terminal-desktop/src/brokers/stocks/india/upstox/constants.tsindex ca9f32fd8..fd92eeb81 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/upstox/constants.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/upstox/constants.ts@@ -47,7 +47,19 @@ export const UPSTOX_METADATA: StockBrokerMetadata = {ordersPerSecond: 10,quotesPerSecond: 10,},- defaultSymbols: ['RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK'],+ defaultSymbols: [+ // NIFTY 50 Components (Jan 2025)+ 'HDFCBANK', 'ICICIBANK', 'SBIN', 'KOTAKBANK', 'AXISBANK',+ 'BAJFINANCE', 'BAJAJFINSV', 'HDFCLIFE', 'SBILIFE', 'INDUSINDBK',+ 'TCS', 'INFY', 'WIPRO', 'HCLTECH', 'TECHM', 'LTIM',+ 'RELIANCE', 'ONGC', 'NTPC', 'POWERGRID', 'ADANIPORTS', 'ADANIENT',+ 'MARUTI', 'TATAMOTORS', 'M&M', 'BAJAJ-AUTO', 'HEROMOTOCO', 'EICHERMOT',+ 'HINDUNILVR', 'ITC', 'NESTLEIND', 'BRITANNIA', 'TATACONSUM',+ 'TATASTEEL', 'JSWSTEEL', 'HINDALCO', 'COALINDIA',+ 'SUNPHARMA', 'DRREDDY', 'CIPLA', 'APOLLOHOSP', 'DIVISLAB',+ 'LT', 'BHARTIARTL', 'ULTRACEMCO', 'GRASIM', 'TITAN',+ 'ASIANPAINT', 'BPCL', 'SHRIRAMFIN', 'TRENT',+ ],};// Exchange mapping (internal → Upstox API)diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/ZerodhaAdapter.ts b/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/ZerodhaAdapter.tsindex 9230015d5..297ec4136 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/ZerodhaAdapter.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/ZerodhaAdapter.ts@@ -69,15 +69,17 @@ export class ZerodhaAdapter extends BaseStockBrokerAdapter {private apiKey: string | null = null;private apiSecret: string | null = null;- // REST API polling for quotes (instead of WebSocket)+ // WebSocket polling fallback flag+ private usePollingFallback: boolean = false;++ // Fallback: REST API polling (used when WebSocket fails)private quotePollingInterval: NodeJS.Timeout | null = null;private pollingSymbols: Map<string, { symbol: string; exchange: StockExchange }> = new Map();- // Legacy WebSocket support (deprecated - use REST API polling)- // Token to symbol mapping for WebSocket+ // Token to symbol mapping for WebSocket subscriptionsprivate tokenSymbolMap: Map<number, { symbol: string; exchange: StockExchange }> = new Map();- // Tauri event unlisteners+ // Tauri event unlisteners for WebSocket eventsprivate eventUnlisteners: UnlistenFn[] = [];// ============================================================================@@ -830,9 +832,13 @@ export class ZerodhaAdapter extends BaseStockBrokerAdapter {}// ============================================================================- // REST API Polling (replaces WebSocket)+ // WebSocket - Real WebSocket via Rust Backend with Polling Fallback// ============================================================================+ /**+ * Connect to WebSocket (internal) - Uses real Zerodha WebSocket via Rust backend+ * Falls back to REST polling if WebSocket connection fails+ */protected async connectWebSocketInternal(config: WebSocketConfig): Promise<void> {this.ensureConnected();@@ -841,15 +847,55 @@ export class ZerodhaAdapter extends BaseStockBrokerAdapter {throw new Error('API credentials not set');}- // Start REST API polling (every 2 minutes as per requirement)+ // Try real WebSocket connection via Rust backend+ await this.connectRealWebSocket();+ console.log('[Zerodha] ✓ WebSocket connected via Rust backend');+ } catch (error) {+ console.warn('[Zerodha] WebSocket connection failed, falling back to REST polling:', error);+ this.usePollingFallback = true;this.startQuotePolling();+ }+ }- this.wsConnected = true;- console.log('Zerodha: REST API polling started (2 min interval)');- } catch (error) {- console.error('Failed to start Zerodha polling:', error);- throw error;+ /**+ * Connect to real Zerodha WebSocket via Tauri/Rust backend+ */+ private async connectRealWebSocket(): Promise<void> {+ // Call Rust backend to connect WebSocket+ const result = await invoke<{+ success: boolean;+ data?: boolean;+ error?: string;+ }>('zerodha_ws_connect', {+ apiKey: this.apiKey!,+ accessToken: this.accessToken!,+ });++ if (!result.success) {+ throw new Error(result.error || 'WebSocket connection failed');+ }++ // Set up Tauri event listeners+ await this.setupWebSocketEventListeners();++ this.wsConnected = true;+ }++ /**+ * Disconnect from real WebSocket+ */+ private async disconnectRealWebSocket(): Promise<void> {+ // Cleanup Tauri event listeners+ await this.cleanupWebSocketEventListeners();++ // Call Rust backend to disconnect+ try {+ await invoke('zerodha_ws_disconnect');+ } catch (err) {+ console.warn('[Zerodha] WebSocket disconnect error:', err);}++ this.wsConnected = false;}/**@@ -1061,8 +1107,22 @@ export class ZerodhaAdapter extends BaseStockBrokerAdapter {if (data.status === 'error' || data.status === 'disconnected') {this.wsConnected = false;++ // Auto-fallback to polling on disconnect+ if (!this.usePollingFallback && this.pollingSymbols.size > 0) {+ console.warn('[Zerodha] WebSocket disconnected, enabling polling fallback');+ this.usePollingFallback = true;+ this.startQuotePolling();+ }} else if (data.status === 'connected') {this.wsConnected = true;++ // Disable polling fallback when connected+ if (this.usePollingFallback) {+ console.log('[Zerodha] WebSocket reconnected, disabling polling fallback');+ this.usePollingFallback = false;+ this.stopQuotePolling();+ }}}@@ -1080,11 +1140,19 @@ export class ZerodhaAdapter extends BaseStockBrokerAdapter {const exchange = (parts[0] || 'NSE') as StockExchange;const symbol = parts[1] || data.symbol;+ // Get best bid/ask+ const bestBid = data.bids?.[0];+ const bestAsk = data.asks?.[0];+// Emit orderbook updateconst tickData: TickData = {symbol,exchange,- lastPrice: data.bids[0]?.price || 0,+ lastPrice: bestBid?.price || 0,+ bid: bestBid?.price,+ ask: bestAsk?.price,+ bidQty: bestBid?.quantity,+ askQty: bestAsk?.quantity,timestamp: data.timestamp,mode: 'full',depth: {@@ -1102,6 +1170,16 @@ export class ZerodhaAdapter extends BaseStockBrokerAdapter {};this.emitTick(tickData);++ // Also emit depth data separately for UI components+ if (tickData.depth) {+ this.emitDepth({+ symbol,+ exchange,+ bids: tickData.depth.bids,+ asks: tickData.depth.asks,+ });+ }}/**@@ -1118,38 +1196,123 @@ export class ZerodhaAdapter extends BaseStockBrokerAdapter {* Disconnect from WebSocket*/async disconnectWebSocket(): Promise<void> {+ // Disconnect real WebSocket+ await this.disconnectRealWebSocket();+// Stop REST API pollingthis.stopQuotePolling();this.pollingSymbols.clear();+ this.tokenSymbolMap.clear();+ this.usePollingFallback = false;this.wsConnected = false;- console.log('[Zerodha] REST API polling stopped');+ console.log('[Zerodha] WebSocket disconnected');}+ /**+ * Subscribe to symbol (internal) - Uses real WebSocket or polling fallback+ */protected async subscribeInternal(symbol: string,exchange: StockExchange,mode: SubscriptionMode): Promise<void> {- try {- const key = `${exchange}:${symbol}`;- this.pollingSymbols.set(key, { symbol, exchange });+ const key = `${exchange}:${symbol}`;++ // Always track in pollingSymbols for fallback+ this.pollingSymbols.set(key, { symbol, exchange });++ if (this.wsConnected && !this.usePollingFallback) {+ // Use real WebSocket subscription+ try {+ // Get instrument token for the symbol+ const tokenResponse = await invoke<{+ success: boolean;+ data?: number;+ error?: string;+ }>('zerodha_get_instrument_token', {+ symbol,+ exchange,+ });++ if (tokenResponse.success && tokenResponse.data) {+ const token = tokenResponse.data;- console.log(`Zerodha: Added ${key} to polling list (${this.pollingSymbols.size} symbols total)`);+ // Store token-symbol mapping+ this.tokenSymbolMap.set(token, { symbol, exchange });++ // Update token map in Rust backend+ await invoke('zerodha_ws_set_token_map', {+ tokenMap: Object.fromEntries(+ Array.from(this.tokenSymbolMap.entries()).map(([t, s]) => [+ t,+ `${s.exchange}:${s.symbol}`,+ ])+ ),+ });++ // Subscribe via WebSocket+ const wsMode = toZerodhaWSMode(mode);+ await invoke('zerodha_ws_subscribe', {+ tokens: [token],+ mode: wsMode,+ });++ console.log(`[Zerodha] ✓ WebSocket subscribed to ${key} (token: ${token}, mode: ${wsMode})`);+ } else {+ console.warn(`[Zerodha] Could not get token for ${key}, using polling`);+ // Fallback to polling for this symbol+ if (!this.usePollingFallback) {+ this.pollQuotesSequentially();+ }+ }+ } catch (error) {+ console.error(`[Zerodha] WebSocket subscribe failed for ${key}:`, error);+ // Fallback to polling+ if (!this.usePollingFallback) {+ this.usePollingFallback = true;+ this.startQuotePolling();+ }+ }+ } else {+ // Using polling fallback+ console.log(`[Zerodha] Added ${key} to polling list (${this.pollingSymbols.size} symbols)`);// Trigger immediate poll for this symbol- this.pollQuotesSequentially();- } catch (error) {- console.error('Failed to subscribe:', error);- throw error;+ if (this.usePollingFallback) {+ this.pollQuotesSequentially();+ }}}+ /**+ * Unsubscribe from symbol (internal)+ */protected async unsubscribeInternal(symbol: string, exchange: StockExchange): Promise<void> {const key = `${exchange}:${symbol}`;++ // Remove from polling symbolsthis.pollingSymbols.delete(key);- console.log(`Zerodha: Removed ${key} from polling list (${this.pollingSymbols.size} symbols remaining)`);+ if (this.wsConnected && !this.usePollingFallback) {+ // Find and remove token from map+ for (const [token, info] of this.tokenSymbolMap.entries()) {+ if (info.symbol === symbol && info.exchange === exchange) {+ try {+ await invoke('zerodha_ws_unsubscribe', {+ tokens: [token],+ });+ this.tokenSymbolMap.delete(token);+ console.log(`[Zerodha] ✓ WebSocket unsubscribed from ${key} (token: ${token})`);+ } catch (error) {+ console.warn(`[Zerodha] WebSocket unsubscribe failed for ${key}:`, error);+ }+ break;+ }+ }+ } else {+ console.log(`[Zerodha] Removed ${key} from polling list (${this.pollingSymbols.size} remaining)`);+ }}/**diff --git a/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/constants.ts b/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/constants.tsindex 0312e6322..34e0f6a53 100644--- a/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/constants.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/india/zerodha/constants.ts@@ -183,8 +183,16 @@ export const ZERODHA_METADATA: StockBrokerMetadata = {},defaultSymbols: [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',+ // NIFTY 50 Components (Jan 2025)+ 'HDFCBANK', 'ICICIBANK', 'SBIN', 'KOTAKBANK', 'AXISBANK',+ 'BAJFINANCE', 'BAJAJFINSV', 'HDFCLIFE', 'SBILIFE', 'INDUSINDBK',+ 'TCS', 'INFY', 'WIPRO', 'HCLTECH', 'TECHM', 'LTIM',+ 'RELIANCE', 'ONGC', 'NTPC', 'POWERGRID', 'ADANIPORTS', 'ADANIENT',+ 'MARUTI', 'TATAMOTORS', 'M&M', 'BAJAJ-AUTO', 'HEROMOTOCO', 'EICHERMOT',+ 'HINDUNILVR', 'ITC', 'NESTLEIND', 'BRITANNIA', 'TATACONSUM',+ 'TATASTEEL', 'JSWSTEEL', 'HINDALCO', 'COALINDIA',+ 'SUNPHARMA', 'DRREDDY', 'CIPLA', 'APOLLOHOSP', 'DIVISLAB',+ 'LT', 'BHARTIARTL', 'ULTRACEMCO', 'GRASIM', 'TITAN',+ 'ASIANPAINT', 'BPCL', 'SHRIRAMFIN', 'TRENT',],};diff --git a/fincept-terminal-desktop/src/brokers/stocks/registry.ts b/fincept-terminal-desktop/src/brokers/stocks/registry.tsindex 9e5e15bea..db30affec 100644--- a/fincept-terminal-desktop/src/brokers/stocks/registry.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/registry.ts@@ -7,6 +7,31 @@import type { StockBrokerMetadata, Region, IStockBrokerAdapter } from './types';+// ============================================================================+// NIFTY 50 COMPONENTS (Jan 2025)+// ============================================================================++const NIFTY_50_SYMBOLS = [+ // Financials (~35% weight)+ 'HDFCBANK', 'ICICIBANK', 'SBIN', 'KOTAKBANK', 'AXISBANK',+ 'BAJFINANCE', 'BAJAJFINSV', 'HDFCLIFE', 'SBILIFE', 'INDUSINDBK',+ // IT (~13% weight)+ 'TCS', 'INFY', 'WIPRO', 'HCLTECH', 'TECHM', 'LTIM',+ // Oil & Gas / Energy (~12% weight)+ 'RELIANCE', 'ONGC', 'NTPC', 'POWERGRID', 'ADANIPORTS', 'ADANIENT',+ // Auto (~7% weight)+ 'MARUTI', 'TATAMOTORS', 'M&M', 'BAJAJ-AUTO', 'HEROMOTOCO', 'EICHERMOT',+ // FMCG (~8% weight)+ 'HINDUNILVR', 'ITC', 'NESTLEIND', 'BRITANNIA', 'TATACONSUM',+ // Metals & Mining (~4% weight)+ 'TATASTEEL', 'JSWSTEEL', 'HINDALCO', 'COALINDIA',+ // Pharma & Healthcare (~4% weight)+ 'SUNPHARMA', 'DRREDDY', 'CIPLA', 'APOLLOHOSP', 'DIVISLAB',+ // Infrastructure & Others (~17% weight)+ 'LT', 'BHARTIARTL', 'ULTRACEMCO', 'GRASIM', 'TITAN',+ 'ASIANPAINT', 'BPCL', 'SHRIRAMFIN', 'TRENT',+];+// ============================================================================// BROKER REGISTRY// ============================================================================@@ -69,11 +94,7 @@ export const STOCK_BROKER_REGISTRY: Record<string, StockBrokerMetadata> = {fno: { brokerage: 20 },},- defaultSymbols: [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',- ],+ defaultSymbols: NIFTY_50_SYMBOLS,},fyers: {@@ -129,11 +150,7 @@ export const STOCK_BROKER_REGISTRY: Record<string, StockBrokerMetadata> = {fno: { brokerage: 20 },},- defaultSymbols: [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',- ],+ defaultSymbols: NIFTY_50_SYMBOLS,},angelone: {@@ -189,11 +206,7 @@ export const STOCK_BROKER_REGISTRY: Record<string, StockBrokerMetadata> = {fno: { brokerage: 20 },},- defaultSymbols: [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',- ],+ defaultSymbols: NIFTY_50_SYMBOLS,},upstox: {@@ -249,11 +262,7 @@ export const STOCK_BROKER_REGISTRY: Record<string, StockBrokerMetadata> = {fno: { brokerage: 20 },},- defaultSymbols: [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',- ],+ defaultSymbols: NIFTY_50_SYMBOLS,},dhan: {@@ -309,11 +318,7 @@ export const STOCK_BROKER_REGISTRY: Record<string, StockBrokerMetadata> = {fno: { brokerage: 20 },},- defaultSymbols: [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',- ],+ defaultSymbols: NIFTY_50_SYMBOLS,},kotak: {@@ -369,11 +374,7 @@ export const STOCK_BROKER_REGISTRY: Record<string, StockBrokerMetadata> = {fno: { brokerage: 20 },},- defaultSymbols: [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',- ],+ defaultSymbols: NIFTY_50_SYMBOLS,},groww: {@@ -429,11 +430,7 @@ export const STOCK_BROKER_REGISTRY: Record<string, StockBrokerMetadata> = {fno: { brokerage: 20 },},- defaultSymbols: [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',- ],+ defaultSymbols: NIFTY_50_SYMBOLS,},aliceblue: {@@ -489,11 +486,7 @@ export const STOCK_BROKER_REGISTRY: Record<string, StockBrokerMetadata> = {fno: { brokerage: 15 },},- defaultSymbols: [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',- ],+ defaultSymbols: NIFTY_50_SYMBOLS,},fivepaisa: {@@ -549,11 +542,7 @@ export const STOCK_BROKER_REGISTRY: Record<string, StockBrokerMetadata> = {fno: { brokerage: 20 },},- defaultSymbols: [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',- ],+ defaultSymbols: NIFTY_50_SYMBOLS,},iifl: {@@ -609,11 +598,7 @@ export const STOCK_BROKER_REGISTRY: Record<string, StockBrokerMetadata> = {fno: { brokerage: 20 },},- defaultSymbols: [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',- ],+ defaultSymbols: NIFTY_50_SYMBOLS,},motilal: {@@ -669,11 +654,7 @@ export const STOCK_BROKER_REGISTRY: Record<string, StockBrokerMetadata> = {fno: { brokerage: 20 },},- defaultSymbols: [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',- ],+ defaultSymbols: NIFTY_50_SYMBOLS,},shoonya: {@@ -729,11 +710,7 @@ export const STOCK_BROKER_REGISTRY: Record<string, StockBrokerMetadata> = {fno: { brokerage: 0 }, // Zero brokerage},- defaultSymbols: [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'SBIN', 'BHARTIARTL', 'HINDUNILVR', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'MARUTI', 'TATAMOTORS', 'WIPRO',- ],+ defaultSymbols: NIFTY_50_SYMBOLS,},// ============================================================================diff --git a/fincept-terminal-desktop/src/brokers/stocks/types.ts b/fincept-terminal-desktop/src/brokers/stocks/types.tsindex 2b597c4c9..e00631cfd 100644--- a/fincept-terminal-desktop/src/brokers/stocks/types.ts+++ b/fincept-terminal-desktop/src/brokers/stocks/types.ts@@ -291,6 +291,8 @@ export interface Quote {// Circuit limits (India specific)upperCircuit?: number;lowerCircuit?: number;+ // Error message if quote fetch failed+ error?: string;}export interface OHLCV {@@ -474,6 +476,8 @@ export interface IStockBrokerAdapter {unsubscribe(symbol: string, exchange: StockExchange): Promise<void>;onTick(callback: (tick: TickData) => void): void;offTick(callback: (tick: TickData) => void): void;+ onDepth(callback: (depth: MarketDepth & { symbol: string; exchange: StockExchange }) => void): void;+ offDepth(callback: (depth: MarketDepth & { symbol: string; exchange: StockExchange }) => void): void;// Master Contract (Symbol Database)downloadMasterContract?(): Promise<void>;diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsxindex 59d08699a..1a24d3531 100644--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx@@ -26,7 +26,7 @@ import AboutTab from '@/components/tabs/AboutTab';import MarketplaceTab from '@/components/tabs/MarketplaceTab';import PortfolioTab from '@/components/tabs/portfolio-tab/PortfolioTab';import DocsTab from '@/components/tabs/docs/DocsTab';-import SettingsTab from '@/components/tabs/SettingsTab';+import SettingsTab from '@/components/tabs/settings-tab';import DataSourcesTab from '@/components/tabs/data-sources/DataSourcesTab';import MCPTab from '@/components/tabs/mcp';import SupportTicketTab from '@/components/tabs/SupportTicketTab';@@ -59,6 +59,7 @@ const ExcelTab = React.lazy(() => import('@/components/tabs/ExcelTab'));const Visualization3DTab = React.lazy(() => import('@/components/tabs/Visualization3DTab'));const PolymarketTab = React.lazy(() => import('@/components/tabs/PolymarketTabEnhanced'));const TradeVisualizationTab = React.lazy(() => import('@/components/tabs/TradeVisualizationTab'));+const AlphaArenaTab = React.lazy(() => import('@/components/tabs/alpha-arena/AlphaArenaTab'));// Loading fallback component for lazy-loaded tabsconst TabLoadingFallback = () => (@@ -552,7 +553,8 @@ function FinxeptTerminalContent() {{ label: 'Stock Screener', shortcut: 'F8', action: () => setActiveTab('screener') },{ label: 'Polygon Data', action: () => setActiveTab('polygon'), separator: true },{ label: 'Economics', action: () => setActiveTab('economics') },- { label: 'DBnomics', action: () => setActiveTab('dbnomics') }+ { label: 'DBnomics', action: () => setActiveTab('dbnomics') },+ { label: 'AKShare Data', action: () => setActiveTab('akshare') }];const researchMenuItems = [@@ -568,6 +570,7 @@ function FinxeptTerminalContent() {const tradingMenuItems = [{ label: 'Crypto Trading', shortcut: 'F9', action: () => setActiveTab('trading') },{ label: 'Equity Trading', action: () => setActiveTab('equity-trading') },+ { label: 'Alpha Arena', action: () => setActiveTab('alpha-arena') },{ label: 'Polymarket', action: () => setActiveTab('polymarket') },{ label: 'Derivatives Pricing', action: () => setActiveTab('derivatives') },{ label: 'Portfolio', shortcut: 'F4', action: () => setActiveTab('portfolio') },@@ -1115,12 +1118,12 @@ function FinxeptTerminalContent() {<MaritimeTab /></React.Suspense></TabsContent>- <TabsContent value="trading" className="h-full m-0 p-0">+ <TabsContent value="trading" className="h-full m-0 p-0" forceMount><React.Suspense fallback={<TabLoadingFallback />}><TradingTab /></React.Suspense></TabsContent>- <TabsContent value="equity-trading" className="h-full m-0 p-0">+ <TabsContent value="equity-trading" className="h-full m-0 p-0" forceMount><React.Suspense fallback={<TabLoadingFallback />}><EquityTradingTab /></React.Suspense>@@ -1180,6 +1183,11 @@ function FinxeptTerminalContent() {<Visualization3DTab /></React.Suspense></TabsContent>+ <TabsContent value="alpha-arena" className="h-full m-0 p-0">+ <React.Suspense fallback={<TabLoadingFallback />}>+ <AlphaArenaTab />+ </React.Suspense>+ </TabsContent></Tabs>)}</div>diff --git a/fincept-terminal-desktop/src/components/tabs/AgentConfigTab.tsx b/fincept-terminal-desktop/src/components/tabs/AgentConfigTab.tsxindex c36c69767..1ebd18e5e 100644--- a/fincept-terminal-desktop/src/components/tabs/AgentConfigTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/AgentConfigTab.tsx@@ -1,66 +1,65 @@-// File: src/components/tabs/AgentConfigTab.tsx-// Professional Fincept Terminal-Grade Agent Configuration Interface-// Extended with Teams, Workflows, Tools, Structured Outputs--import React, { useState, useEffect, useCallback } from 'react';+/**+ * AgentConfigTab - Professional Agent Studio Interface (v2.1)+ *+ * Features:+ * - Dynamic agent discovery from backend+ * - Full agent configuration editor (LLM, tools, memory, reasoning)+ * - SuperAgent query routing with auto-route toggle+ * - Execution plan builder and visualizer+ * - Multi-agent team builder+ * - Tools browser with selection+ * - Chat interface with routing+ * - System capabilities view+ */++import React, { useState, useEffect, useCallback, useRef } from 'react';import { invoke } from '@tauri-apps/api/core';-import { resolveResource } from '@tauri-apps/api/path';-import { readTextFile } from '@tauri-apps/plugin-fs';import {- Bot,- RefreshCw,- Play,- Code,- AlertCircle,- CheckCircle,- Eye,- EyeOff,- Users,- TrendingUp,- Globe,- Building2,- Wrench,- Database,- Brain,- GitBranch,- FileText,- Settings,- Zap,- Shield,- Activity,- Cpu,- MessageSquare,- Trash2,- Plus,- ChevronRight,- ChevronDown,- Search,- Copy,- Check,+ Bot, RefreshCw, Play, Code, AlertCircle, CheckCircle,+ Users, TrendingUp, Globe, Building2, Wrench, Brain,+ GitBranch, Settings, Zap, MessageSquare, Trash2, Plus,+ ChevronRight, ChevronDown, Search, Copy, Check, Cpu,+ Sparkles, Route, ListTree, Save, Edit3, ToggleLeft, ToggleRight,+ Loader2, Target, FileJson, Sliders, Database, Eye,} from 'lucide-react';-import { getLLMConfigs } from '@/services/core/sqliteService';+import {+ getLLMConfigs,+ getActiveLLMConfig,+ type LLMConfig as DbLLMConfig,+ LLM_PROVIDERS as DB_LLM_PROVIDERS,+ sqliteService,+} from '@/services/core/sqliteService';import { TabFooter } from '@/components/common/TabFooter';--// Fincept Professional Color Palette-const FINCEPT = {+import agentService, {+ type AgentConfig as ServiceAgentConfig,+ type SystemInfo,+ type ToolsInfo,+ type AgentCard,+ type ExecutionPlan,+ type PlanStep,+ type RoutingResult,+} from '@/services/agentService';++// =============================================================================+// Constants & Types+// =============================================================================++const COLORS = {ORANGE: '#FF8800',WHITE: '#FFFFFF',RED: '#FF3B3B',GREEN: '#00D66F',+ BLUE: '#3B82F6',+ PURPLE: '#8B5CF6',GRAY: '#787878',DARK_BG: '#000000',PANEL_BG: '#0F0F0F',- HEADER_BG: '#1A1A1A',- CYAN: '#00E5FF',- YELLOW: '#FFD700',- BLUE: '#0088FF',- PURPLE: '#9D4EDD',BORDER: '#2A2A2A',HOVER: '#1F1F1F',- MUTED: '#4A4A4A'+ MUTED: '#4A4A4A',};-interface AgentConfig {+interface AgentDefinition {id: string;name: string;role: string;@@ -78,190 +77,238 @@ interface AgentConfig {instructions: string;}-interface SystemInfo {- version: string;- framework: string;- capabilities: {- model_providers: number;- tools: number;- tool_categories: string[];- vectordbs: string[];- embedders: string[];- output_models: string[];- };- features: string[];-}--interface ToolsInfo {- tools: Record<string, string[]>;- categories: string[];- total_count: number;-}-interface ChatMessage {- role: 'user' | 'assistant';+ role: 'user' | 'assistant' | 'system';content: string;timestamp: Date;agentName?: string;- outputModel?: string;+ routingInfo?: RoutingResult;}-type ViewMode = 'agents' | 'teams' | 'workflows' | 'tools' | 'system' | 'chat';+// LLMConfig is imported from sqliteService as DbLLMConfig++type ViewMode = 'agents' | 'teams' | 'workflows' | 'planner' | 'tools' | 'system' | 'chat';++const VIEW_MODES = [+ { id: 'agents' as ViewMode, name: 'AGENTS', icon: Bot },+ { id: 'teams' as ViewMode, name: 'TEAMS', icon: Users },+ { id: 'workflows' as ViewMode, name: 'WORKFLOWS', icon: GitBranch },+ { id: 'planner' as ViewMode, name: 'PLANNER', icon: ListTree },+ { id: 'tools' as ViewMode, name: 'TOOLS', icon: Wrench },+ { id: 'chat' as ViewMode, name: 'CHAT', icon: MessageSquare },+ { id: 'system' as ViewMode, name: 'SYSTEM', icon: Cpu },+];++const OUTPUT_MODELS = [+ { id: 'trade_signal', name: 'Trade Signal', desc: 'Buy/Sell signals with confidence' },+ { id: 'stock_analysis', name: 'Stock Analysis', desc: 'Comprehensive stock report' },+ { id: 'portfolio_analysis', name: 'Portfolio Analysis', desc: 'Portfolio metrics & allocation' },+ { id: 'risk_assessment', name: 'Risk Assessment', desc: 'Risk metrics & warnings' },+ { id: 'market_analysis', name: 'Market Analysis', desc: 'Market conditions & trends' },+];++// Use LLM_PROVIDERS from sqliteService - includes fincept-llm and all configured providers++// =============================================================================+// Component+// =============================================================================const AgentConfigTab: React.FC = () => {- // Core state+ // View stateconst [viewMode, setViewMode] = useState<ViewMode>('agents');- const [selectedCategory, setSelectedCategory] = useState('TraderInvestorsAgent');- const [agents, setAgents] = useState<AgentConfig[]>([]);- const [selectedAgent, setSelectedAgent] = useState<AgentConfig | null>(null);- const [jsonText, setJsonText] = useState('');++ // Agent state - now using dynamic discovery+ const [discoveredAgents, setDiscoveredAgents] = useState<AgentCard[]>([]);+ const [selectedAgent, setSelectedAgent] = useState<AgentCard | null>(null);+ const [agentsByCategory, setAgentsByCategory] = useState<Record<string, AgentCard[]>>({});+ const [selectedCategory, setSelectedCategory] = useState<string>('all');const [loading, setLoading] = useState(false);- const [testResult, setTestResult] = useState<any>(null);- const [showJsonEditor, setShowJsonEditor] = useState(false);const [error, setError] = useState<string | null>(null);const [success, setSuccess] = useState<string | null>(null);- const [testQuery, setTestQuery] = useState('Analyze AAPL stock and provide your investment thesis.');- // Extended state+ // Agent config editor state+ const [editMode, setEditMode] = useState(false);+ const [editedConfig, setEditedConfig] = useState<{+ provider: string;+ model_id: string;+ temperature: number;+ max_tokens: number;+ tools: string[];+ instructions: string;+ enable_memory: boolean;+ enable_reasoning: boolean;+ }>({+ provider: 'openai',+ model_id: 'gpt-4-turbo',+ temperature: 0.7,+ max_tokens: 4096,+ tools: [],+ instructions: '',+ enable_memory: false,+ enable_reasoning: false,+ });++ // System state (cached via service)const [systemInfo, setSystemInfo] = useState<SystemInfo | null>(null);const [toolsInfo, setToolsInfo] = useState<ToolsInfo | null>(null);- const [selectedOutputModel, setSelectedOutputModel] = useState<string>('');+ const [configuredLLMs, setConfiguredLLMs] = useState<DbLLMConfig[]>([]);+ const [llmProvidersList, setLlmProvidersList] = useState(DB_LLM_PROVIDERS);++ // Query & execution state+ const [testQuery, setTestQuery] = useState('Analyze AAPL stock and provide your investment thesis.');+ const [testResult, setTestResult] = useState<any>(null);+ const [selectedOutputModel, setSelectedOutputModel] = useState('');+ const [showJsonEditor, setShowJsonEditor] = useState(false);+ const [jsonText, setJsonText] = useState('');++ // SuperAgent routing state+ const [useAutoRouting, setUseAutoRouting] = useState(true);+ const [lastRoutingResult, setLastRoutingResult] = useState<RoutingResult | null>(null);++ // Team state+ const [teamMembers, setTeamMembers] = useState<AgentCard[]>([]);+ const [teamMode, setTeamMode] = useState<'coordinate' | 'route' | 'collaborate'>('coordinate');++ // Chat stateconst [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);const [chatInput, setChatInput] = useState('');- const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set(['finance']));+ const chatEndRef = useRef<HTMLDivElement>(null);++ // Tools stateconst [toolSearch, setToolSearch] = useState('');+ const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set(['finance']));const [selectedTools, setSelectedTools] = useState<string[]>([]);const [copiedTool, setCopiedTool] = useState<string | null>(null);- // Team state- const [teamMembers, setTeamMembers] = useState<AgentConfig[]>([]);- const [teamMode, setTeamMode] = useState<'coordinate' | 'route' | 'collaborate'>('coordinate');+ // Workflow/Planner state+ const [workflowSymbol, setWorkflowSymbol] = useState('AAPL');+ const [currentPlan, setCurrentPlan] = useState<ExecutionPlan | null>(null);+ const [planExecuting, setPlanExecuting] = useState(false);- const categories = [- { id: 'TraderInvestorsAgent', name: 'TRADERS', icon: TrendingUp, configFile: 'agent_definitions.json' },- { id: 'GeopoliticsAgents', name: 'GEOPOLITICS', icon: Globe, configFile: 'agent_definitions.json' },- { id: 'EconomicAgents', name: 'ECONOMICS', icon: Building2, configFile: 'agent_definitions.json' },- { id: 'hedgeFundAgents', name: 'HEDGE FUNDS', icon: Users, configFile: 'team_config.json' },- ];-- const viewModes = [- { id: 'agents' as ViewMode, name: 'AGENTS', icon: Bot },- { id: 'teams' as ViewMode, name: 'TEAMS', icon: Users },- { id: 'workflows' as ViewMode, name: 'WORKFLOWS', icon: GitBranch },- { id: 'tools' as ViewMode, name: 'TOOLS', icon: Wrench },- { id: 'chat' as ViewMode, name: 'CHAT', icon: MessageSquare },- { id: 'system' as ViewMode, name: 'SYSTEM', icon: Cpu },- ];-- const outputModels = [- { id: 'trade_signal', name: 'Trade Signal', icon: TrendingUp, description: 'Buy/sell recommendations with confidence' },- { id: 'stock_analysis', name: 'Stock Analysis', icon: Activity, description: 'Comprehensive stock analysis report' },- { id: 'portfolio_analysis', name: 'Portfolio Analysis', icon: Database, description: 'Portfolio metrics and allocation' },- { id: 'risk_assessment', name: 'Risk Assessment', icon: Shield, description: 'Risk scoring and mitigation strategies' },- { id: 'market_analysis', name: 'Market Analysis', icon: Globe, description: 'Market trends and sentiment' },- { id: 'research_report', name: 'Research Report', icon: FileText, description: 'Full investment research report' },- ];-- // Load agents on mount and category change- useEffect(() => {- loadAgents();- }, [selectedCategory]);+ // =============================================================================+ // Effects+ // =============================================================================- // Update JSON when selected agent changesuseEffect(() => {- if (selectedAgent) {- setJsonText(JSON.stringify(selectedAgent, null, 2));- }- }, [selectedAgent]);+ loadDiscoveredAgents();+ loadSystemData();+ loadLLMConfigs();+ }, []);- // Load system info on mountuseEffect(() => {- loadSystemInfo();- loadToolsInfo();- }, []);+ // Scroll chat to bottom+ chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });+ }, [chatMessages]);- const loadSystemInfo = async () => {+ const loadLLMConfigs = async () => {try {- const result = await invoke<string>('execute_core_agent', {- command: 'system_info',- args: [],- });- const parsed = JSON.parse(result);- if (parsed.success) {- setSystemInfo(parsed);+ // Load configured LLMs from settings database+ const configs = await getLLMConfigs();+ setConfiguredLLMs(configs);++ // Set active config as default if available+ const activeConfig = await getActiveLLMConfig();+ if (activeConfig) {+ setEditedConfig(prev => ({+ ...prev,+ provider: activeConfig.provider,+ model_id: activeConfig.model,+ }));+ } else if (configs.length > 0) {+ // Use first configured LLM if no active one+ setEditedConfig(prev => ({+ ...prev,+ provider: configs[0].provider,+ model_id: configs[0].model,+ }));}++ console.log('[AgentConfigTab] Loaded LLM configs from settings:', configs.length);} catch (err) {- console.error('Failed to load system info:', err);+ console.error('Failed to load LLM configs:', err);}};- const loadToolsInfo = async () => {- try {- const result = await invoke<string>('execute_core_agent', {- command: 'list_tools',- args: [],- });- const parsed = JSON.parse(result);- if (parsed.success) {- setToolsInfo(parsed);- }- } catch (err) {- console.error('Failed to load tools info:', err);- }+ const loadSystemData = async () => {+ const [sysInfo, tools] = await Promise.all([+ agentService.getSystemInfo(),+ agentService.getTools(),+ ]);+ if (sysInfo) setSystemInfo(sysInfo);+ if (tools) setToolsInfo(tools);};- const loadAgents = async () => {+ const loadDiscoveredAgents = async () => {setLoading(true);setError(null);- setAgents([]);- setSelectedAgent(null);try {- const category = categories.find(c => c.id === selectedCategory);- if (!category) {- setError('Invalid category');- setLoading(false);- return;- }-- const configPath = `resources/scripts/agents/${selectedCategory}/configs/${category.configFile}`;-- try {- const resourcePath = await resolveResource(configPath);- const content = await readTextFile(resourcePath);- const data = JSON.parse(content);+ // Use the new discover_agents endpoint+ const agents = await agentService.discoverAgents();+ setDiscoveredAgents(agents);++ // Group by category+ const byCategory: Record<string, AgentCard[]> = { all: agents };+ agents.forEach(agent => {+ const cat = agent.category || 'other';+ if (!byCategory[cat]) byCategory[cat] = [];+ byCategory[cat].push(agent);+ });+ setAgentsByCategory(byCategory);- const agentList = data.agents || [];- setAgents(agentList);- if (agentList.length > 0) {- setSelectedAgent(agentList[0]);- }- } catch (fileError) {- try {- const result = await invoke<string>('read_agent_config', {- category: selectedCategory,- configFile: category.configFile,- });- const data = JSON.parse(result);- const agentList = data.agents || [];- setAgents(agentList);- if (agentList.length > 0) {- setSelectedAgent(agentList[0]);- }- } catch (invokeError) {- console.error('Failed to load agents via invoke:', invokeError);- setError(`Failed to load agents: ${fileError}`);- }+ if (agents.length > 0) {+ setSelectedAgent(agents[0]);+ updateEditedConfigFromAgent(agents[0]);}} catch (err: any) {- console.error('Failed to load agents:', err);setError(err.toString());+ // Fallback to legacy loading+ await loadLegacyAgents();} finally {setLoading(false);}};- const fetchApiKeysFromSettings = async (): Promise<Record<string, string>> => {+ const loadLegacyAgents = async () => {+ // Fallback to reading config files directly+ try {+ const result = await invoke<string>('list_available_agents');+ const agents = JSON.parse(result) as AgentCard[];+ setDiscoveredAgents(agents);++ const byCategory: Record<string, AgentCard[]> = { all: agents };+ agents.forEach(agent => {+ const cat = agent.category || 'other';+ if (!byCategory[cat]) byCategory[cat] = [];+ byCategory[cat].push(agent);+ });+ setAgentsByCategory(byCategory);+ } catch (err) {+ console.error('Legacy agent loading failed:', err);+ }+ };++ const updateEditedConfigFromAgent = (agent: AgentCard) => {+ const config = agent.config || {};+ const model = config.model || {};+ setEditedConfig({+ provider: model.provider || 'openai',+ model_id: model.model_id || 'gpt-4-turbo',+ temperature: model.temperature ?? 0.7,+ max_tokens: model.max_tokens ?? 4096,+ tools: config.tools || [],+ instructions: config.instructions || '',+ enable_memory: config.memory?.enabled || false,+ enable_reasoning: config.reasoning || false,+ });+ setJsonText(JSON.stringify(agent, null, 2));+ };++ // =============================================================================+ // API Key Helper+ // =============================================================================++ const getApiKeys = async (): Promise<Record<string, string>> => {try {const llmConfigs = await getLLMConfigs();const apiKeys: Record<string, string> = {};@@ -271,195 +318,241 @@ const AgentConfigTab: React.FC = () => {const providerUpper = config.provider.toUpperCase();apiKeys[`${providerUpper}_API_KEY`] = config.api_key;apiKeys[config.provider] = config.api_key;- apiKeys[providerUpper] = config.api_key;}}-return apiKeys;- } catch (err) {- console.error('Failed to fetch API keys from settings:', err);+ } catch {return {};}};- const runAgent = async (query: string, outputModel?: string) => {- if (!selectedAgent || !query.trim()) return;+ // =============================================================================+ // Agent Execution+ // =============================================================================++ const runAgent = async () => {+ if (!testQuery.trim()) return;setLoading(true);setError(null);setTestResult(null);- setSuccess(null);try {- const apiKeys = await fetchApiKeysFromSettings();- const provider = selectedAgent.llm_config.provider;-- if (!apiKeys[provider] && !apiKeys[`${provider.toUpperCase()}_API_KEY`] && provider !== 'ollama' && provider !== 'fincept') {- setError(`No API key found for ${provider}. Configure it in Settings > LLM Config.`);- setLoading(false);- return;- }-- const config = {- model: {- provider: selectedAgent.llm_config.provider,- model_id: selectedAgent.llm_config.model_id,- temperature: selectedAgent.llm_config.temperature,- max_tokens: selectedAgent.llm_config.max_tokens,- },- instructions: selectedAgent.instructions,- tools: selectedTools.length > 0 ? selectedTools : selectedAgent.tools,- memory: { enabled: selectedAgent.enable_memory },- debug: false,- };-- let result: string;-- if (outputModel) {- const queryJson = JSON.stringify({ query, output_model: outputModel });- result = await invoke<string>('execute_core_agent', {- command: 'run_structured',- args: [queryJson, JSON.stringify(config), JSON.stringify(apiKeys)],- });+ const apiKeys = await getApiKeys();++ // Check if we should use auto-routing+ if (useAutoRouting) {+ // First, route the query+ const routingResult = await agentService.routeQuery(testQuery, apiKeys);+ setLastRoutingResult(routingResult);++ // Add system message about routing+ setChatMessages(prev => [+ ...prev,+ {+ role: 'system',+ content: `🎯 Routed to: ${routingResult.agent_id} (${routingResult.intent}) - Confidence: ${(routingResult.confidence * 100).toFixed(0)}%`,+ timestamp: new Date(),+ routingInfo: routingResult,+ },+ ]);++ // Execute with routing+ const result = await agentService.executeRoutedQuery(testQuery, apiKeys);+ setTestResult(result);++ setChatMessages(prev => [+ ...prev,+ { role: 'user', content: testQuery, timestamp: new Date() },+ {+ role: 'assistant',+ content: result.response || result.error || JSON.stringify(result, null, 2),+ timestamp: new Date(),+ agentName: routingResult.agent_id,+ },+ ]);} else {- const queryJson = JSON.stringify({ query });- result = await invoke<string>('execute_core_agent', {- command: 'run',- args: [queryJson, JSON.stringify(config), JSON.stringify(apiKeys)],- });- }-- const parsed = JSON.parse(result);- setTestResult(parsed);+ // Use selected agent directly+ const config = agentService.buildAgentConfig(+ editedConfig.provider,+ editedConfig.model_id,+ editedConfig.instructions,+ {+ tools: selectedTools.length > 0 ? selectedTools : editedConfig.tools,+ temperature: editedConfig.temperature,+ maxTokens: editedConfig.max_tokens,+ memory: editedConfig.enable_memory,+ reasoning: editedConfig.enable_reasoning,+ }+ );- // Add to chat history- setChatMessages(prev => [- ...prev,- { role: 'user', content: query, timestamp: new Date() },- {- role: 'assistant',- content: parsed.response || parsed.error || JSON.stringify(parsed, null, 2),- timestamp: new Date(),- agentName: selectedAgent.name,- outputModel- },- ]);+ let result;+ if (selectedOutputModel) {+ result = await agentService.runAgentStructured(testQuery, config, selectedOutputModel, apiKeys);+ } else {+ result = await agentService.runAgent(testQuery, config, apiKeys);+ }- if (parsed.success) {- setSuccess('Agent executed successfully');- setTimeout(() => setSuccess(null), 3000);+ setTestResult(result);++ setChatMessages(prev => [+ ...prev,+ { role: 'user', content: testQuery, timestamp: new Date() },+ {+ role: 'assistant',+ content: result.response || result.error || JSON.stringify(result, null, 2),+ timestamp: new Date(),+ agentName: selectedAgent?.name || 'Agent',+ },+ ]);}++ setSuccess('Query executed successfully');+ setTimeout(() => setSuccess(null), 3000);} catch (err: any) {- console.error('Failed to run agent:', err);setError(err.toString());} finally {setLoading(false);}};- const runTeam = async (query: string) => {- if (teamMembers.length === 0 || !query.trim()) return;+ const runTeam = async () => {+ if (teamMembers.length === 0 || !testQuery.trim()) return;setLoading(true);setError(null);- setTestResult(null);try {- const apiKeys = await fetchApiKeysFromSettings();+ const apiKeys = await getApiKeys();- const teamConfig = {- name: 'Custom Team',- mode: teamMode,- members: teamMembers.map(agent => ({+ const teamConfig = agentService.buildTeamConfig(+ 'Custom Team',+ teamMode,+ teamMembers.map(agent => ({name: agent.name,- role: agent.role,- model: agent.llm_config,- tools: agent.tools,- instructions: agent.instructions,- })),- };-- const queryJson = JSON.stringify({ query });- const result = await invoke<string>('execute_core_agent', {- command: 'run_team',- args: [queryJson, JSON.stringify(teamConfig), JSON.stringify(apiKeys)],- });+ role: agent.description,+ provider: agent.config?.model?.provider || 'openai',+ modelId: agent.config?.model?.model_id || 'gpt-4-turbo',+ tools: agent.config?.tools || [],+ instructions: agent.config?.instructions || '',+ }))+ );- const parsed = JSON.parse(result);- setTestResult(parsed);+ const result = await agentService.runTeam(testQuery, teamConfig, apiKeys);+ setTestResult(result);setChatMessages(prev => [...prev,- { role: 'user', content: query, timestamp: new Date() },+ { role: 'user', content: testQuery, timestamp: new Date() },{role: 'assistant',- content: parsed.response || parsed.error || JSON.stringify(parsed, null, 2),+ content: result.response || result.error || JSON.stringify(result, null, 2),timestamp: new Date(),agentName: `Team (${teamMembers.length} agents)`,},]);- if (parsed.success) {+ if (result.success) {setSuccess('Team executed successfully');setTimeout(() => setSuccess(null), 3000);}} catch (err: any) {- console.error('Failed to run team:', err);setError(err.toString());} finally {setLoading(false);}};- const runWorkflow = async (workflowType: string, input: any) => {+ const runWorkflow = async (workflowType: string) => {setLoading(true);setError(null);- setTestResult(null);try {- const apiKeys = await fetchApiKeysFromSettings();-- let command = '';- let queryJson = '';+ const apiKeys = await getApiKeys();+ let result;switch (workflowType) {case 'stock_analysis':- command = 'stock_analysis';- queryJson = JSON.stringify({ symbol: input.symbol });+ result = await agentService.runStockAnalysis(workflowSymbol, apiKeys);break;case 'portfolio_rebal':- command = 'portfolio_rebal';- queryJson = JSON.stringify(input);+ result = await agentService.runPortfolioRebalancing({ holdings: [] }, apiKeys);break;case 'risk_assessment':- command = 'risk_assessment';- queryJson = JSON.stringify(input);+ result = await agentService.runRiskAssessment({ holdings: [] }, apiKeys);break;default:throw new Error(`Unknown workflow: ${workflowType}`);}- const result = await invoke<string>('execute_core_agent', {- command,- args: [queryJson, JSON.stringify({}), JSON.stringify(apiKeys)],- });+ setTestResult(result);+ if (result.success) {+ setSuccess(`${workflowType} completed`);+ setTimeout(() => setSuccess(null), 3000);+ }+ } catch (err: any) {+ setError(err.toString());+ } finally {+ setLoading(false);+ }+ };++ // =============================================================================+ // Execution Planner+ // =============================================================================++ const createPlan = async () => {+ if (!workflowSymbol.trim()) return;- const parsed = JSON.parse(result);- setTestResult(parsed);+ setLoading(true);+ setError(null);- if (parsed.success) {- setSuccess(`${workflowType} workflow completed`);+ try {+ const plan = await agentService.createStockAnalysisPlan(workflowSymbol);+ if (plan) {+ setCurrentPlan(plan);+ setSuccess('Execution plan created');setTimeout(() => setSuccess(null), 3000);+ } else {+ setError('Failed to create plan');}} catch (err: any) {- console.error('Failed to run workflow:', err);setError(err.toString());} finally {setLoading(false);}};- const addToTeam = (agent: AgentConfig) => {+ const executePlan = async () => {+ if (!currentPlan) return;++ setPlanExecuting(true);+ setError(null);++ try {+ const apiKeys = await getApiKeys();+ const result = await agentService.executePlan(currentPlan, apiKeys);++ if (result) {+ setCurrentPlan(result);+ if (result.is_complete) {+ setSuccess('Plan executed successfully');+ } else if (result.has_failed) {+ setError('Plan execution failed');+ }+ }+ } catch (err: any) {+ setError(err.toString());+ } finally {+ setPlanExecuting(false);+ }+ };++ // =============================================================================+ // Team Management+ // =============================================================================++ const addToTeam = (agent: AgentCard) => {if (!teamMembers.find(m => m.id === agent.id)) {setTeamMembers(prev => [...prev, agent]);}@@ -469,455 +562,466 @@ const AgentConfigTab: React.FC = () => {setTeamMembers(prev => prev.filter(m => m.id !== agentId));};- const toggleCategory = (category: string) => {+ // =============================================================================+ // Tools Management+ // =============================================================================++ const toggleToolCategory = (category: string) => {setExpandedCategories(prev => {const newSet = new Set(prev);- if (newSet.has(category)) {- newSet.delete(category);- } else {- newSet.add(category);- }+ if (newSet.has(category)) newSet.delete(category);+ else newSet.add(category);return newSet;});};- const toggleTool = (tool: string) => {- setSelectedTools(prev => {- if (prev.includes(tool)) {- return prev.filter(t => t !== tool);- }- return [...prev, tool];- });- };-const copyTool = (tool: string) => {navigator.clipboard.writeText(tool);setCopiedTool(tool);setTimeout(() => setCopiedTool(null), 2000);};- const handleChatSubmit = (e: React.FormEvent) => {- e.preventDefault();- if (!chatInput.trim()) return;-- if (viewMode === 'teams' && teamMembers.length > 0) {- runTeam(chatInput);- } else if (selectedAgent) {- runAgent(chatInput, selectedOutputModel || undefined);- }- setChatInput('');+ const toggleToolSelection = (tool: string) => {+ setSelectedTools(prev =>+ prev.includes(tool) ? prev.filter(t => t !== tool) : [...prev, tool]+ );+ // Also update edited config+ setEditedConfig(prev => ({+ ...prev,+ tools: prev.tools.includes(tool)+ ? prev.tools.filter(t => t !== tool)+ : [...prev.tools, tool],+ }));};- const filteredTools = toolsInfo ? Object.entries(toolsInfo.tools).reduce((acc, [category, tools]) => {- const filtered = tools.filter(tool =>- tool.toLowerCase().includes(toolSearch.toLowerCase()) ||- category.toLowerCase().includes(toolSearch.toLowerCase())- );- if (filtered.length > 0) {- acc[category] = filtered;- }- return acc;- }, {} as Record<string, string[]>) : {};+ // =============================================================================+ // Render: Agent Config Editor+ // =============================================================================++ const renderAgentConfigEditor = () => (+ <div className="space-y-4 p-4 rounded-lg" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="flex items-center justify-between">+ <h3 className="text-sm font-semibold flex items-center gap-2" style={{ color: COLORS.WHITE }}>+ <Sliders size={16} style={{ color: COLORS.ORANGE }} />+ Agent Configuration+ </h3>+ <button+ onClick={() => setEditMode(!editMode)}+ className="px-2 py-1 rounded text-xs flex items-center gap-1"+ style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}+ >+ <Edit3 size={12} />+ {editMode ? 'Done' : 'Edit'}+ </button>+ </div>++ {/* LLM Selection - Only from Settings */}+ {configuredLLMs.length > 0 ? (+ <div className="p-3 rounded-lg" style={{ backgroundColor: COLORS.DARK_BG, border: `1px solid ${COLORS.GREEN}40` }}>+ <div className="text-xs font-medium mb-2 flex items-center gap-2" style={{ color: COLORS.GREEN }}>+ <CheckCircle size={12} />+ SELECT LLM (from Settings)+ </div>+ <div className="flex flex-wrap gap-2">+ {configuredLLMs.map((llm, idx) => {+ const hasKey = !!llm.api_key && llm.api_key.length > 0;+ const isSelected = editedConfig.provider === llm.provider && editedConfig.model_id === llm.model;+ return (+ <button+ key={idx}+ onClick={() => editMode && setEditedConfig(prev => ({+ ...prev,+ provider: llm.provider,+ model_id: llm.model,+ }))}+ className="px-3 py-2 rounded text-xs flex items-center gap-2 transition-colors"+ style={{+ backgroundColor: isSelected ? COLORS.ORANGE : COLORS.BORDER,+ color: COLORS.WHITE,+ cursor: editMode ? 'pointer' : 'default',+ opacity: hasKey ? 1 : 0.5,+ }}+ >+ {llm.is_active && <span style={{ color: COLORS.GREEN }}>●</span>}+ <span className="font-medium">{llm.provider}</span>+ <span style={{ color: isSelected ? COLORS.WHITE : COLORS.GRAY }}>/ {llm.model}</span>+ {!hasKey && <AlertCircle size={10} style={{ color: COLORS.RED }} />}+ </button>+ );+ })}+ </div>+ {configuredLLMs.some(l => !l.api_key || l.api_key.length === 0) && (+ <div className="text-xs mt-2" style={{ color: COLORS.RED }}>+ ⚠ Some providers missing API keys - configure in Settings → LLM Configuration+ </div>+ )}+ </div>+ ) : (+ <div className="p-3 rounded-lg" style={{ backgroundColor: COLORS.DARK_BG, border: `1px solid ${COLORS.RED}40` }}>+ <div className="text-xs font-medium mb-2 flex items-center gap-2" style={{ color: COLORS.RED }}>+ <AlertCircle size={12} />+ NO LLM CONFIGURED+ </div>+ <p className="text-xs" style={{ color: COLORS.GRAY }}>+ Go to Settings → LLM Configuration to add API keys for your preferred providers.+ </p>+ </div>+ )}- const CategoryIcon = categories.find(c => c.id === selectedCategory)?.icon || Bot;+ <div className="grid grid-cols-2 gap-4">+ {/* Current Selection Display */}+ <div>+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Selected Provider</label>+ <div+ className="w-full px-3 py-2 rounded text-sm"+ style={{+ backgroundColor: COLORS.DARK_BG,+ color: COLORS.WHITE,+ border: `1px solid ${COLORS.BORDER}`,+ }}+ >+ {editedConfig.provider || 'None selected'}+ </div>+ </div>- // Render different views- const renderAgentsView = () => (- <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>- {/* Left Panel - Agent List */}- <div style={{- width: '280px',- borderRight: `1px solid ${FINCEPT.BORDER}`,- display: 'flex',- flexDirection: 'column',- backgroundColor: FINCEPT.PANEL_BG- }}>- {/* Category Tabs */}- <div style={{- padding: '8px',- borderBottom: `1px solid ${FINCEPT.BORDER}`,- display: 'flex',- flexWrap: 'wrap',- gap: '4px'- }}>- {categories.map((cat) => {- const Icon = cat.icon;- return (- <button- key={cat.id}- onClick={() => setSelectedCategory(cat.id)}- style={{- padding: '4px 8px',- backgroundColor: selectedCategory === cat.id ? FINCEPT.ORANGE : 'transparent',- border: `1px solid ${selectedCategory === cat.id ? FINCEPT.ORANGE : FINCEPT.BORDER}`,- color: selectedCategory === cat.id ? FINCEPT.DARK_BG : FINCEPT.GRAY,- cursor: 'pointer',- fontSize: '8px',- fontWeight: 600,- display: 'flex',- alignItems: 'center',- gap: '4px',- }}+ {/* Current Model Display */}+ <div>+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Selected Model</label>+ <div+ className="w-full px-3 py-2 rounded text-sm"+ style={{+ backgroundColor: COLORS.DARK_BG,+ color: COLORS.WHITE,+ border: `1px solid ${COLORS.BORDER}`,+ }}+ >+ {editedConfig.model_id || 'None selected'}+ </div>+ </div>++ {/* Temperature */}+ <div>+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>+ Temperature: {editedConfig.temperature.toFixed(2)}+ </label>+ <input+ type="range"+ min="0"+ max="2"+ step="0.1"+ value={editedConfig.temperature}+ onChange={e => setEditedConfig(prev => ({ ...prev, temperature: parseFloat(e.target.value) }))}+ disabled={!editMode}+ className="w-full"+ style={{ accentColor: COLORS.ORANGE }}+ />+ </div>++ {/* Max Tokens */}+ <div>+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Max Tokens</label>+ <input+ type="number"+ value={editedConfig.max_tokens}+ onChange={e => setEditedConfig(prev => ({ ...prev, max_tokens: parseInt(e.target.value) || 4096 }))}+ disabled={!editMode}+ className="w-full px-3 py-2 rounded text-sm"+ style={{+ backgroundColor: COLORS.DARK_BG,+ color: COLORS.WHITE,+ border: `1px solid ${COLORS.BORDER}`,+ opacity: editMode ? 1 : 0.7,+ }}+ />+ </div>+ </div>++ {/* Toggle Options */}+ <div className="flex gap-4">+ <button+ onClick={() => editMode && setEditedConfig(prev => ({ ...prev, enable_memory: !prev.enable_memory }))}+ className="flex items-center gap-2 px-3 py-2 rounded text-sm"+ style={{+ backgroundColor: editedConfig.enable_memory ? COLORS.ORANGE + '20' : COLORS.BORDER,+ color: editedConfig.enable_memory ? COLORS.ORANGE : COLORS.GRAY,+ cursor: editMode ? 'pointer' : 'default',+ }}+ >+ {editedConfig.enable_memory ? <ToggleRight size={16} /> : <ToggleLeft size={16} />}+ Memory+ </button>++ <button+ onClick={() => editMode && setEditedConfig(prev => ({ ...prev, enable_reasoning: !prev.enable_reasoning }))}+ className="flex items-center gap-2 px-3 py-2 rounded text-sm"+ style={{+ backgroundColor: editedConfig.enable_reasoning ? COLORS.PURPLE + '20' : COLORS.BORDER,+ color: editedConfig.enable_reasoning ? COLORS.PURPLE : COLORS.GRAY,+ cursor: editMode ? 'pointer' : 'default',+ }}+ >+ {editedConfig.enable_reasoning ? <ToggleRight size={16} /> : <ToggleLeft size={16} />}+ Reasoning+ </button>+ </div>++ {/* Instructions */}+ {editMode && (+ <div>+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Instructions</label>+ <textarea+ value={editedConfig.instructions}+ onChange={e => setEditedConfig(prev => ({ ...prev, instructions: e.target.value }))}+ rows={4}+ className="w-full px-3 py-2 rounded text-sm font-mono"+ style={{+ backgroundColor: COLORS.DARK_BG,+ color: COLORS.WHITE,+ border: `1px solid ${COLORS.BORDER}`,+ }}+ placeholder="Enter agent instructions..."+ />+ </div>+ )}++ {/* Selected Tools */}+ {editedConfig.tools.length > 0 && (+ <div>+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>+ Tools ({editedConfig.tools.length})+ </label>+ <div className="flex flex-wrap gap-1">+ {editedConfig.tools.map(tool => (+ <span+ key={tool}+ onClick={() => editMode && toggleToolSelection(tool)}+ className="px-2 py-0.5 rounded text-xs cursor-pointer"+ style={{ backgroundColor: COLORS.ORANGE + '30', color: COLORS.ORANGE }}>- <Icon size={10} />- {cat.name}- </button>- );- })}+ {tool} {editMode && '×'}+ </span>+ ))}+ </div>+ </div>+ )}+ </div>+ );++ // =============================================================================+ // Render: Agents View+ // =============================================================================++ const renderAgentsView = () => (+ <div className="flex h-full">+ {/* Sidebar */}+ <div className="w-72 border-r flex flex-col" style={{ borderColor: COLORS.BORDER }}>+ {/* Header with Refresh */}+ <div className="p-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>+ <div className="text-xs font-medium" style={{ color: COLORS.GRAY }}>+ DISCOVERED AGENTS ({discoveredAgents.length})+ </div>+ <button+ onClick={loadDiscoveredAgents}+ disabled={loading}+ className="p-1.5 rounded hover:bg-[#1F1F1F]"+ >+ <RefreshCw size={14} className={loading ? 'animate-spin' : ''} style={{ color: COLORS.ORANGE }} />+ </button></div>- <div style={{- padding: '8px 12px',- borderBottom: `1px solid ${FINCEPT.BORDER}`,- backgroundColor: FINCEPT.HEADER_BG,- fontSize: '11px',- fontWeight: 600,- color: FINCEPT.GRAY- }}>- AVAILABLE AGENTS ({agents.length})+ {/* Category Filter */}+ <div className="p-2 border-b" style={{ borderColor: COLORS.BORDER }}>+ <select+ value={selectedCategory}+ onChange={e => setSelectedCategory(e.target.value)}+ className="w-full px-2 py-1.5 rounded text-sm"+ style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ >+ <option value="all">All Categories ({discoveredAgents.length})</option>+ {Object.entries(agentsByCategory)+ .filter(([k]) => k !== 'all')+ .map(([cat, agents]) => (+ <option key={cat} value={cat}>{cat} ({agents.length})</option>+ ))}+ </select></div>- <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>- {loading && agents.length === 0 ? (- <div style={{ textAlign: 'center', padding: '20px', color: FINCEPT.GRAY }}>- <RefreshCw size={20} className="animate-spin" style={{ margin: '0 auto' }} />- <div style={{ marginTop: '8px', fontSize: '10px' }}>Loading agents...</div>- </div>- ) : agents.length === 0 ? (- <div style={{ textAlign: 'center', padding: '20px', color: FINCEPT.GRAY }}>- <AlertCircle size={20} style={{ margin: '0 auto' }} />- <div style={{ marginTop: '8px', fontSize: '10px' }}>No agents found</div>+ {/* Agent List */}+ <div className="flex-1 overflow-y-auto p-2">+ {loading ? (+ <div className="flex items-center justify-center py-8">+ <Loader2 size={20} className="animate-spin" style={{ color: COLORS.ORANGE }} /></div>) : (- agents.map((agent) => (- <div- key={agent.id}- style={{- marginBottom: '6px',- border: `1px solid ${selectedAgent?.id === agent.id ? FINCEPT.ORANGE : FINCEPT.BORDER}`,- backgroundColor: selectedAgent?.id === agent.id ? FINCEPT.HOVER : 'transparent',- }}- >+ <div className="space-y-1">+ {(agentsByCategory[selectedCategory] || []).map(agent => (<button- onClick={() => setSelectedAgent(agent)}+ key={agent.id}+ onClick={() => {+ setSelectedAgent(agent);+ updateEditedConfigFromAgent(agent);+ }}+ className="w-full text-left px-3 py-2 rounded text-sm transition-colors"style={{- width: '100%',- padding: '10px',- backgroundColor: 'transparent',- border: 'none',- color: FINCEPT.WHITE,- cursor: 'pointer',- textAlign: 'left',- fontSize: '10px',+ backgroundColor: selectedAgent?.id === agent.id ? COLORS.HOVER : 'transparent',+ color: selectedAgent?.id === agent.id ? COLORS.ORANGE : COLORS.WHITE,}}>- <div style={{ fontWeight: 600, color: FINCEPT.CYAN, marginBottom: '4px' }}>- {agent.name}- </div>- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '4px', lineHeight: 1.3 }}>- {agent.role?.substring(0, 60)}{agent.role?.length > 60 ? '...' : ''}- </div>- <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>- <span style={{- padding: '2px 6px',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${FINCEPT.BORDER}`,- fontSize: '8px',- color: FINCEPT.YELLOW- }}>- {agent.llm_config?.provider || 'N/A'}- </span>+ <div className="font-medium truncate">{agent.name}</div>+ <div className="text-xs truncate" style={{ color: COLORS.GRAY }}>+ {agent.category} • v{agent.version}</div></button>- <div style={{ padding: '0 10px 8px', display: 'flex', gap: '4px' }}>- <button- onClick={() => addToTeam(agent)}- disabled={teamMembers.some(m => m.id === agent.id)}- style={{- padding: '2px 6px',- backgroundColor: teamMembers.some(m => m.id === agent.id) ? FINCEPT.GREEN + '40' : FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- color: teamMembers.some(m => m.id === agent.id) ? FINCEPT.GREEN : FINCEPT.GRAY,- cursor: teamMembers.some(m => m.id === agent.id) ? 'default' : 'pointer',- fontSize: '8px',- display: 'flex',- alignItems: 'center',- gap: '2px',- }}- >- <Plus size={8} />- {teamMembers.some(m => m.id === agent.id) ? 'In Team' : 'Add to Team'}- </button>- </div>- </div>- ))+ ))}+ </div>)}</div></div>- {/* Right Panel - Agent Details */}- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>+ {/* Main Content */}+ <div className="flex-1 flex flex-col overflow-hidden">{selectedAgent ? (<>{/* Agent Header */}- <div style={{- padding: '12px',- borderBottom: `1px solid ${FINCEPT.BORDER}`,- backgroundColor: FINCEPT.HEADER_BG- }}>- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: '8px' }}>+ <div className="p-4 border-b" style={{ borderColor: COLORS.BORDER }}>+ <div className="flex items-center justify-between"><div>- <div style={{ fontSize: '16px', fontWeight: 700, color: FINCEPT.CYAN, marginBottom: '4px' }}>- {selectedAgent.name}- </div>- <div style={{ fontSize: '10px', color: FINCEPT.GRAY, lineHeight: 1.4 }}>- {selectedAgent.description}- </div>+ <h2 className="text-lg font-semibold" style={{ color: COLORS.WHITE }}>{selectedAgent.name}</h2>+ <p className="text-sm" style={{ color: COLORS.GRAY }}>{selectedAgent.description}</p></div>- <button- onClick={() => setShowJsonEditor(!showJsonEditor)}- style={{- padding: '4px 8px',- backgroundColor: showJsonEditor ? FINCEPT.ORANGE : FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- color: showJsonEditor ? FINCEPT.DARK_BG : FINCEPT.GRAY,- cursor: 'pointer',- fontSize: '9px',- display: 'flex',- alignItems: 'center',- gap: '4px'- }}- >- <Code size={10} />- JSON- </button>- </div>-- {/* Output Model Selector */}- <div style={{ marginBottom: '8px' }}>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>STRUCTURED OUTPUT (Optional)</div>- <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>+ <div className="flex gap-2"><button- onClick={() => setSelectedOutputModel('')}- style={{- padding: '3px 8px',- backgroundColor: !selectedOutputModel ? FINCEPT.BLUE : FINCEPT.PANEL_BG,- border: `1px solid ${!selectedOutputModel ? FINCEPT.BLUE : FINCEPT.BORDER}`,- color: !selectedOutputModel ? FINCEPT.WHITE : FINCEPT.GRAY,- cursor: 'pointer',- fontSize: '8px',- }}+ onClick={() => addToTeam(selectedAgent)}+ className="px-3 py-1.5 rounded text-sm flex items-center gap-1"+ style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}>- None+ <Plus size={14} /> Add to Team+ </button>+ <button+ onClick={() => setShowJsonEditor(!showJsonEditor)}+ className="px-3 py-1.5 rounded text-sm flex items-center gap-1"+ style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}+ >+ <FileJson size={14} /> {showJsonEditor ? 'Hide' : 'Show'} JSON</button>- {outputModels.map(model => (- <button- key={model.id}- onClick={() => setSelectedOutputModel(model.id)}- title={model.description}- style={{- padding: '3px 8px',- backgroundColor: selectedOutputModel === model.id ? FINCEPT.PURPLE : FINCEPT.PANEL_BG,- border: `1px solid ${selectedOutputModel === model.id ? FINCEPT.PURPLE : FINCEPT.BORDER}`,- color: selectedOutputModel === model.id ? FINCEPT.WHITE : FINCEPT.GRAY,- cursor: 'pointer',- fontSize: '8px',- display: 'flex',- alignItems: 'center',- gap: '3px',- }}- >- {model.name}- </button>- ))}</div></div>- {/* Test Query Input */}- <div style={{ display: 'flex', gap: '8px' }}>- <input- type="text"- value={testQuery}- onChange={(e) => setTestQuery(e.target.value)}- placeholder="Enter test query..."- style={{- flex: 1,- padding: '6px 10px',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${FINCEPT.BORDER}`,- color: FINCEPT.WHITE,- fontSize: '10px',- outline: 'none',- }}- />- <button- onClick={() => runAgent(testQuery, selectedOutputModel || undefined)}- disabled={loading || !testQuery.trim()}- style={{- padding: '6px 12px',- backgroundColor: FINCEPT.BLUE,- border: 'none',- color: FINCEPT.WHITE,- cursor: loading ? 'not-allowed' : 'pointer',- fontSize: '10px',- fontWeight: 600,- display: 'flex',- alignItems: 'center',- gap: '4px',- opacity: loading || !testQuery.trim() ? 0.5 : 1,- }}- >- <Play size={12} />- {loading ? 'Running...' : 'Run'}- </button>- </div>+ {/* Capabilities */}+ {selectedAgent.capabilities && selectedAgent.capabilities.length > 0 && (+ <div className="mt-2 flex flex-wrap gap-1">+ {selectedAgent.capabilities.map(cap => (+ <span key={cap} className="px-2 py-0.5 rounded text-xs" style={{ backgroundColor: COLORS.BLUE + '20', color: COLORS.BLUE }}>+ {cap}+ </span>+ ))}+ </div>+ )}</div>- {/* Content Area */}- <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>+ {/* Content */}+ <div className="flex-1 overflow-y-auto p-4 space-y-4">{showJsonEditor ? (- <div style={{ height: '100%' }}>- <textarea- value={jsonText}- onChange={(e) => setJsonText(e.target.value)}- style={{- width: '100%',- height: '100%',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${FINCEPT.BORDER}`,- color: FINCEPT.CYAN,- padding: '12px',- fontSize: '11px',- fontFamily: '"IBM Plex Mono", monospace',- resize: 'none',- outline: 'none'- }}- spellCheck={false}- />- </div>+ <textarea+ value={jsonText}+ onChange={e => setJsonText(e.target.value)}+ className="w-full h-64 p-3 rounded font-mono text-sm"+ style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ />) : (- <div style={{ display: 'grid', gap: '12px' }}>- {/* LLM Config */}- <div>- <div style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.GRAY, marginBottom: '6px' }}>LLM CONFIGURATION</div>- <div style={{- padding: '8px',- backgroundColor: FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- display: 'grid',- gridTemplateColumns: 'repeat(4, 1fr)',- gap: '8px',- fontSize: '10px'- }}>- <div><span style={{ color: FINCEPT.GRAY }}>Provider:</span> <span style={{ color: FINCEPT.CYAN }}>{selectedAgent.llm_config?.provider}</span></div>- <div><span style={{ color: FINCEPT.GRAY }}>Model:</span> <span style={{ color: FINCEPT.PURPLE }}>{selectedAgent.llm_config?.model_id}</span></div>- <div><span style={{ color: FINCEPT.GRAY }}>Temp:</span> <span style={{ color: FINCEPT.YELLOW }}>{selectedAgent.llm_config?.temperature}</span></div>- <div><span style={{ color: FINCEPT.GRAY }}>Max Tokens:</span> <span style={{ color: FINCEPT.YELLOW }}>{selectedAgent.llm_config?.max_tokens}</span></div>- </div>- </div>-- {/* Tools */}- <div>- <div style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.GRAY, marginBottom: '6px' }}>- TOOLS ({selectedAgent.tools?.length || 0})- {selectedTools.length > 0 && <span style={{ color: FINCEPT.GREEN }}> + {selectedTools.length} custom</span>}- </div>- <div style={{- padding: '8px',- backgroundColor: FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- display: 'flex',- gap: '6px',- flexWrap: 'wrap'- }}>- {(selectedAgent.tools || []).map((tool, idx) => (- <span key={idx} style={{- padding: '4px 8px',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${FINCEPT.BORDER}`,- color: FINCEPT.GREEN,- fontSize: '9px'- }}>- {tool}- </span>- ))}- {selectedTools.filter(t => !selectedAgent.tools?.includes(t)).map((tool, idx) => (- <span key={`custom-${idx}`} style={{- padding: '4px 8px',- backgroundColor: FINCEPT.PURPLE + '30',- border: `1px solid ${FINCEPT.PURPLE}`,- color: FINCEPT.PURPLE,- fontSize: '9px',- display: 'flex',- alignItems: 'center',- gap: '4px',- }}>- {tool}- <button- onClick={() => toggleTool(tool)}- style={{ background: 'none', border: 'none', color: FINCEPT.PURPLE, cursor: 'pointer', padding: 0 }}- >- <Trash2 size={8} />- </button>- </span>- ))}- </div>- </div>-- {/* Instructions */}- <div>- <div style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.GRAY, marginBottom: '6px' }}>INSTRUCTIONS</div>- <div style={{- padding: '8px',- backgroundColor: FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- fontSize: '10px',- maxHeight: '120px',- overflow: 'auto',- lineHeight: '1.5',- whiteSpace: 'pre-wrap',- }}>- {selectedAgent.instructions}+ <>+ {/* Config Editor */}+ {renderAgentConfigEditor()}++ {/* SuperAgent Routing Toggle */}+ <div className="p-3 rounded-lg flex items-center justify-between" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="flex items-center gap-2">+ <Route size={16} style={{ color: COLORS.PURPLE }} />+ <div>+ <div className="text-sm font-medium" style={{ color: COLORS.WHITE }}>SuperAgent Auto-Routing</div>+ <div className="text-xs" style={{ color: COLORS.GRAY }}>Automatically route queries to the best agent</div>+ </div></div>+ <button+ onClick={() => setUseAutoRouting(!useAutoRouting)}+ className="p-2 rounded"+ style={{ color: useAutoRouting ? COLORS.GREEN : COLORS.GRAY }}+ >+ {useAutoRouting ? <ToggleRight size={24} /> : <ToggleLeft size={24} />}+ </button></div>- {/* Test Result */}- {testResult && (- <div>- <div style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.GRAY, marginBottom: '6px' }}>- RESULT {selectedOutputModel && <span style={{ color: FINCEPT.PURPLE }}>({selectedOutputModel})</span>}- </div>- <div style={{- padding: '8px',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${testResult.success ? FINCEPT.GREEN : FINCEPT.RED}`,- fontSize: '10px',- maxHeight: '200px',- overflow: 'auto',- fontFamily: 'monospace'- }}>- <pre style={{ margin: 0, color: testResult.success ? FINCEPT.GREEN : FINCEPT.RED, whiteSpace: 'pre-wrap' }}>- {testResult.response || testResult.error || JSON.stringify(testResult, null, 2)}- </pre>+ {/* Last Routing Result */}+ {lastRoutingResult && (+ <div className="p-3 rounded-lg" style={{ backgroundColor: COLORS.PURPLE + '10', border: `1px solid ${COLORS.PURPLE}40` }}>+ <div className="text-xs font-medium mb-1" style={{ color: COLORS.PURPLE }}>LAST ROUTING</div>+ <div className="text-sm" style={{ color: COLORS.WHITE }}>+ Intent: <span style={{ color: COLORS.ORANGE }}>{lastRoutingResult.intent}</span>+ {' • '}Agent: <span style={{ color: COLORS.ORANGE }}>{lastRoutingResult.agent_id}</span>+ {' • '}Confidence: <span style={{ color: COLORS.GREEN }}>{(lastRoutingResult.confidence * 100).toFixed(0)}%</span></div></div>)}+ </>+ )}++ {/* Query Input */}+ <div className="space-y-3">+ <div>+ <div className="text-xs font-medium mb-1" style={{ color: COLORS.GRAY }}>OUTPUT MODEL (Optional)</div>+ <select+ value={selectedOutputModel}+ onChange={e => setSelectedOutputModel(e.target.value)}+ className="w-full px-3 py-2 rounded text-sm"+ style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ >+ <option value="">None (free text)</option>+ {OUTPUT_MODELS.map(m => (+ <option key={m.id} value={m.id}>{m.name}</option>+ ))}+ </select>+ </div>++ <div>+ <div className="text-xs font-medium mb-1" style={{ color: COLORS.GRAY }}>QUERY</div>+ <textarea+ value={testQuery}+ onChange={e => setTestQuery(e.target.value)}+ placeholder="Enter your query..."+ rows={3}+ className="w-full px-3 py-2 rounded text-sm"+ style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ />+ </div>++ <button+ onClick={runAgent}+ disabled={loading}+ className="w-full py-2 rounded font-medium flex items-center justify-center gap-2"+ style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE, opacity: loading ? 0.5 : 1 }}+ >+ {loading ? <Loader2 size={16} className="animate-spin" /> : <Play size={16} />}+ {useAutoRouting ? 'Run with Auto-Routing' : 'Run Agent'}+ </button>+ </div>++ {/* Result */}+ {testResult && (+ <div className="p-3 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>RESULT</div>+ <pre className="text-sm whitespace-pre-wrap" style={{ color: COLORS.WHITE }}>+ {typeof testResult === 'string' ? testResult : JSON.stringify(testResult, null, 2)}+ </pre></div>)}</div></>) : (- <div style={{- flex: 1,- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- color: FINCEPT.GRAY,- fontSize: '11px'- }}>- <div style={{ textAlign: 'center' }}>- <CategoryIcon size={48} style={{ margin: '0 auto 12px', opacity: 0.3 }} />- <div>Select an agent to view configuration</div>+ <div className="flex-1 flex items-center justify-center" style={{ color: COLORS.GRAY }}>+ <div className="text-center">+ <Bot size={48} className="mx-auto mb-4 opacity-50" />+ <p>Select an agent to view details</p>+ <p className="text-sm mt-2">or click Refresh to discover agents</p></div></div>)}@@ -925,735 +1029,825 @@ const AgentConfigTab: React.FC = () => {</div>);+ // =============================================================================+ // Render: Teams View+ // =============================================================================+const renderTeamsView = () => (- <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>- {/* Left - Team Builder */}- <div style={{- width: '300px',- borderRight: `1px solid ${FINCEPT.BORDER}`,- display: 'flex',- flexDirection: 'column',- backgroundColor: FINCEPT.PANEL_BG- }}>- <div style={{- padding: '12px',- borderBottom: `1px solid ${FINCEPT.BORDER}`,- backgroundColor: FINCEPT.HEADER_BG,- }}>- <div style={{ fontSize: '11px', fontWeight: 600, color: FINCEPT.CYAN, marginBottom: '8px' }}>- TEAM MEMBERS ({teamMembers.length})- </div>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '8px' }}>- Add agents from the Agents view to build a team+ <div className="p-4 space-y-4">+ <div className="flex items-center justify-between">+ <h2 className="text-lg font-semibold" style={{ color: COLORS.WHITE }}>Team Builder</h2>+ <select+ value={teamMode}+ onChange={e => setTeamMode(e.target.value as any)}+ className="px-3 py-1.5 rounded text-sm"+ style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ >+ <option value="coordinate">Coordinate (Sequential)</option>+ <option value="route">Route (Best Match)</option>+ <option value="collaborate">Collaborate (Parallel)</option>+ </select>+ </div>++ {/* Team Members */}+ <div className="p-3 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>TEAM MEMBERS ({teamMembers.length})</div>+ {teamMembers.length === 0 ? (+ <p className="text-sm" style={{ color: COLORS.GRAY }}>Add agents from the AGENTS tab</p>+ ) : (+ <div className="space-y-2">+ {teamMembers.map((agent, idx) => (+ <div key={agent.id} className="flex items-center justify-between p-2 rounded" style={{ backgroundColor: COLORS.BORDER }}>+ <div className="flex items-center gap-2">+ <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE }}>+ {idx + 1}+ </span>+ <div>+ <div className="text-sm font-medium" style={{ color: COLORS.WHITE }}>{agent.name}</div>+ <div className="text-xs" style={{ color: COLORS.GRAY }}>{agent.category}</div>+ </div>+ </div>+ <button onClick={() => removeFromTeam(agent.id)} style={{ color: COLORS.RED }}>+ <Trash2 size={14} />+ </button>+ </div>+ ))}</div>- <div style={{ display: 'flex', gap: '4px' }}>- {(['coordinate', 'route', 'collaborate'] as const).map(mode => (+ )}+ </div>++ {/* Available Agents to Add */}+ <div className="p-3 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>AVAILABLE AGENTS</div>+ <div className="max-h-48 overflow-y-auto space-y-1">+ {discoveredAgents+ .filter(a => !teamMembers.find(m => m.id === a.id))+ .map(agent => (<button- key={mode}- onClick={() => setTeamMode(mode)}- style={{- padding: '4px 8px',- backgroundColor: teamMode === mode ? FINCEPT.PURPLE : FINCEPT.DARK_BG,- border: `1px solid ${teamMode === mode ? FINCEPT.PURPLE : FINCEPT.BORDER}`,- color: teamMode === mode ? FINCEPT.WHITE : FINCEPT.GRAY,- cursor: 'pointer',- fontSize: '8px',- textTransform: 'uppercase',- }}+ key={agent.id}+ onClick={() => addToTeam(agent)}+ className="w-full flex items-center justify-between p-2 rounded text-sm hover:bg-[#1F1F1F]">- {mode}+ <span style={{ color: COLORS.WHITE }}>{agent.name}</span>+ <Plus size={14} style={{ color: COLORS.ORANGE }} /></button>))}- </div></div>+ </div>- <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>- {teamMembers.length === 0 ? (- <div style={{ textAlign: 'center', padding: '20px', color: FINCEPT.GRAY }}>- <Users size={24} style={{ margin: '0 auto 8px', opacity: 0.3 }} />- <div style={{ fontSize: '10px' }}>No team members yet</div>- <div style={{ fontSize: '9px', marginTop: '4px' }}>Go to Agents view to add members</div>- </div>- ) : (- teamMembers.map((member, idx) => (- <div- key={member.id}- style={{- padding: '10px',- marginBottom: '6px',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${FINCEPT.BORDER}`,- }}- >- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start' }}>- <div>- <div style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.CYAN }}>- {idx + 1}. {member.name}- </div>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginTop: '2px' }}>- {member.role?.substring(0, 50)}...- </div>- </div>- <button- onClick={() => removeFromTeam(member.id)}- style={{- background: 'none',- border: 'none',- color: FINCEPT.RED,- cursor: 'pointer',- padding: '2px',- }}- >- <Trash2 size={12} />- </button>- </div>- </div>- ))- )}- </div>+ {/* Query */}+ <div>+ <div className="text-xs font-medium mb-1" style={{ color: COLORS.GRAY }}>TEAM QUERY</div>+ <textarea+ value={testQuery}+ onChange={e => setTestQuery(e.target.value)}+ rows={3}+ className="w-full px-3 py-2 rounded text-sm"+ style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ /></div>- {/* Right - Team Execution */}- <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>- <div style={{- padding: '12px',- borderBottom: `1px solid ${FINCEPT.BORDER}`,- backgroundColor: FINCEPT.HEADER_BG,- }}>- <div style={{ fontSize: '14px', fontWeight: 600, color: FINCEPT.WHITE, marginBottom: '8px' }}>- Run Multi-Agent Team- </div>- <form onSubmit={(e) => { e.preventDefault(); runTeam(testQuery); }} style={{ display: 'flex', gap: '8px' }}>- <input- type="text"- value={testQuery}- onChange={(e) => setTestQuery(e.target.value)}- placeholder="Enter query for the team..."- style={{- flex: 1,- padding: '8px 12px',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${FINCEPT.BORDER}`,- color: FINCEPT.WHITE,- fontSize: '11px',- outline: 'none',- }}- />- <button- type="submit"- disabled={loading || teamMembers.length === 0 || !testQuery.trim()}- style={{- padding: '8px 16px',- backgroundColor: FINCEPT.PURPLE,- border: 'none',- color: FINCEPT.WHITE,- cursor: loading || teamMembers.length === 0 ? 'not-allowed' : 'pointer',- fontSize: '11px',- fontWeight: 600,- opacity: loading || teamMembers.length === 0 ? 0.5 : 1,- display: 'flex',- alignItems: 'center',- gap: '6px',- }}- >- <Users size={14} />- {loading ? 'Running...' : 'Run Team'}- </button>- </form>- </div>+ <button+ onClick={runTeam}+ disabled={loading || teamMembers.length === 0}+ className="w-full py-2 rounded font-medium flex items-center justify-center gap-2"+ style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE, opacity: (loading || teamMembers.length === 0) ? 0.5 : 1 }}+ >+ {loading ? <Loader2 size={16} className="animate-spin" /> : <Play size={16} />}+ Run Team+ </button>- <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>- {testResult && (- <div style={{- padding: '12px',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${testResult.success ? FINCEPT.GREEN : FINCEPT.RED}`,- }}>- <div style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.GRAY, marginBottom: '8px' }}>- TEAM RESULT- </div>- <pre style={{- margin: 0,- fontSize: '11px',- color: testResult.success ? FINCEPT.GREEN : FINCEPT.RED,- whiteSpace: 'pre-wrap',- fontFamily: 'monospace',- }}>- {testResult.response || testResult.error || JSON.stringify(testResult, null, 2)}- </pre>- </div>- )}+ {testResult && (+ <div className="p-3 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <pre className="text-sm whitespace-pre-wrap" style={{ color: COLORS.WHITE }}>+ {JSON.stringify(testResult, null, 2)}+ </pre></div>- </div>+ )}</div>);+ // =============================================================================+ // Render: Workflows View+ // =============================================================================+const renderWorkflowsView = () => (- <div style={{ flex: 1, padding: '16px', overflow: 'auto' }}>- <div style={{ fontSize: '14px', fontWeight: 600, color: FINCEPT.WHITE, marginBottom: '16px' }}>- Financial Workflows- </div>+ <div className="p-4 space-y-4">+ <h2 className="text-lg font-semibold" style={{ color: COLORS.WHITE }}>Financial Workflows</h2>++ <div className="grid grid-cols-1 md:grid-cols-3 gap-4">+ {/* Stock Analysis */}+ <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="flex items-center gap-2 mb-3">+ <TrendingUp size={20} style={{ color: COLORS.ORANGE }} />+ <h3 className="font-medium" style={{ color: COLORS.WHITE }}>Stock Analysis</h3>+ </div>+ <input+ type="text"+ value={workflowSymbol}+ onChange={e => setWorkflowSymbol(e.target.value.toUpperCase())}+ placeholder="Symbol (e.g., AAPL)"+ className="w-full px-3 py-2 rounded text-sm mb-3"+ style={{ backgroundColor: COLORS.DARK_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ />+ <button+ onClick={() => runWorkflow('stock_analysis')}+ disabled={loading}+ className="w-full py-2 rounded text-sm font-medium"+ style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE }}+ >+ Analyze+ </button>+ </div>- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px' }}>- {[- { id: 'stock_analysis', name: 'Stock Analysis', icon: TrendingUp, description: 'Comprehensive stock analysis pipeline', color: FINCEPT.GREEN },- { id: 'portfolio_rebal', name: 'Portfolio Rebalancing', icon: Database, description: 'Optimize portfolio allocation', color: FINCEPT.BLUE },- { id: 'risk_assessment', name: 'Risk Assessment', icon: Shield, description: 'Evaluate portfolio risks', color: FINCEPT.RED },- ].map(workflow => {- const Icon = workflow.icon;- return (- <div- key={workflow.id}- style={{- padding: '16px',- backgroundColor: FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- }}- >- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>- <Icon size={20} color={workflow.color} />- <span style={{ fontSize: '12px', fontWeight: 600, color: FINCEPT.WHITE }}>{workflow.name}</span>- </div>- <div style={{ fontSize: '10px', color: FINCEPT.GRAY, marginBottom: '12px' }}>- {workflow.description}- </div>- {workflow.id === 'stock_analysis' && (- <div style={{ display: 'flex', gap: '8px' }}>- <input- type="text"- placeholder="Symbol (e.g., AAPL)"- style={{- flex: 1,- padding: '6px 10px',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${FINCEPT.BORDER}`,- color: FINCEPT.WHITE,- fontSize: '10px',- outline: 'none',- }}- onKeyDown={(e) => {- if (e.key === 'Enter') {- runWorkflow('stock_analysis', { symbol: (e.target as HTMLInputElement).value });- }- }}- />- <button- onClick={() => {- const input = document.querySelector(`input[placeholder="Symbol (e.g., AAPL)"]`) as HTMLInputElement;- if (input?.value) runWorkflow('stock_analysis', { symbol: input.value });- }}- style={{- padding: '6px 12px',- backgroundColor: workflow.color,- border: 'none',- color: FINCEPT.WHITE,- cursor: 'pointer',- fontSize: '10px',- }}- >- Run- </button>- </div>- )}- </div>- );- })}+ {/* Portfolio Rebalancing */}+ <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="flex items-center gap-2 mb-3">+ <Brain size={20} style={{ color: COLORS.ORANGE }} />+ <h3 className="font-medium" style={{ color: COLORS.WHITE }}>Portfolio Rebalancing</h3>+ </div>+ <p className="text-xs mb-3" style={{ color: COLORS.GRAY }}>+ Optimize your portfolio allocation based on risk/return targets.+ </p>+ <button+ onClick={() => runWorkflow('portfolio_rebal')}+ disabled={loading}+ className="w-full py-2 rounded text-sm font-medium"+ style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE }}+ >+ Rebalance+ </button>+ </div>++ {/* Risk Assessment */}+ <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="flex items-center gap-2 mb-3">+ <AlertCircle size={20} style={{ color: COLORS.ORANGE }} />+ <h3 className="font-medium" style={{ color: COLORS.WHITE }}>Risk Assessment</h3>+ </div>+ <p className="text-xs mb-3" style={{ color: COLORS.GRAY }}>+ Analyze portfolio risk metrics and potential vulnerabilities.+ </p>+ <button+ onClick={() => runWorkflow('risk_assessment')}+ disabled={loading}+ className="w-full py-2 rounded text-sm font-medium"+ style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE }}+ >+ Assess Risk+ </button>+ </div></div>{testResult && (- <div style={{ marginTop: '16px' }}>- <div style={{ fontSize: '10px', fontWeight: 600, color: FINCEPT.GRAY, marginBottom: '8px' }}>- WORKFLOW RESULT- </div>- <div style={{- padding: '12px',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${testResult.success ? FINCEPT.GREEN : FINCEPT.RED}`,- maxHeight: '300px',- overflow: 'auto',- }}>- <pre style={{- margin: 0,- fontSize: '11px',- color: testResult.success ? FINCEPT.GREEN : FINCEPT.RED,- whiteSpace: 'pre-wrap',- }}>- {JSON.stringify(testResult, null, 2)}- </pre>- </div>+ <div className="p-3 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>WORKFLOW RESULT</div>+ <pre className="text-sm whitespace-pre-wrap" style={{ color: COLORS.WHITE }}>+ {JSON.stringify(testResult, null, 2)}+ </pre></div>)}</div>);- const renderToolsView = () => (- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>- {/* Search */}- <div style={{- padding: '12px',- borderBottom: `1px solid ${FINCEPT.BORDER}`,- backgroundColor: FINCEPT.HEADER_BG,- }}>- <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>- <Search size={14} color={FINCEPT.GRAY} />- <input- type="text"- value={toolSearch}- onChange={(e) => setToolSearch(e.target.value)}- placeholder="Search tools..."+ // =============================================================================+ // Render: Planner View (NEW)+ // =============================================================================++ const renderPlannerView = () => (+ <div className="p-4 space-y-4">+ <div className="flex items-center justify-between">+ <h2 className="text-lg font-semibold flex items-center gap-2" style={{ color: COLORS.WHITE }}>+ <ListTree size={20} style={{ color: COLORS.ORANGE }} />+ Execution Planner+ </h2>+ {currentPlan && (+ <span+ className="px-2 py-1 rounded text-xs"style={{- flex: 1,- padding: '6px 10px',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${FINCEPT.BORDER}`,- color: FINCEPT.WHITE,- fontSize: '11px',- outline: 'none',+ backgroundColor: currentPlan.is_complete ? COLORS.GREEN + '20' : currentPlan.has_failed ? COLORS.RED + '20' : COLORS.ORANGE + '20',+ color: currentPlan.is_complete ? COLORS.GREEN : currentPlan.has_failed ? COLORS.RED : COLORS.ORANGE,}}- />- <span style={{ fontSize: '10px', color: FINCEPT.GRAY }}>- {toolsInfo?.total_count || 0} tools available+ >+ {currentPlan.status}</span>+ )}+ </div>++ {/* Create Plan */}+ <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>CREATE EXECUTION PLAN</div>+ <div className="flex gap-2">+ <input+ type="text"+ value={workflowSymbol}+ onChange={e => setWorkflowSymbol(e.target.value.toUpperCase())}+ placeholder="Symbol (e.g., AAPL)"+ className="flex-1 px-3 py-2 rounded text-sm"+ style={{ backgroundColor: COLORS.DARK_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ />+ <button+ onClick={createPlan}+ disabled={loading}+ className="px-4 py-2 rounded text-sm font-medium flex items-center gap-2"+ style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE }}+ >+ {loading ? <Loader2 size={14} className="animate-spin" /> : <Target size={14} />}+ Create Plan+ </button></div>- {selectedTools.length > 0 && (- <div style={{ marginTop: '8px', display: 'flex', gap: '4px', flexWrap: 'wrap', alignItems: 'center' }}>- <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>Selected:</span>- {selectedTools.map(tool => (- <span- key={tool}+ </div>++ {/* Plan Visualization */}+ {currentPlan && (+ <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="flex items-center justify-between mb-4">+ <div>+ <div className="text-sm font-medium" style={{ color: COLORS.WHITE }}>{currentPlan.name}</div>+ <div className="text-xs" style={{ color: COLORS.GRAY }}>{currentPlan.description}</div>+ </div>+ <button+ onClick={executePlan}+ disabled={planExecuting || currentPlan.is_complete}+ className="px-4 py-2 rounded text-sm font-medium flex items-center gap-2"+ style={{+ backgroundColor: currentPlan.is_complete ? COLORS.GREEN : COLORS.ORANGE,+ color: COLORS.WHITE,+ opacity: planExecuting ? 0.5 : 1,+ }}+ >+ {planExecuting ? <Loader2 size={14} className="animate-spin" /> : <Play size={14} />}+ {currentPlan.is_complete ? 'Completed' : 'Execute Plan'}+ </button>+ </div>++ {/* Steps */}+ <div className="space-y-2">+ {currentPlan.steps.map((step, idx) => (+ <div+ key={step.id}+ className="flex items-center gap-3 p-3 rounded"style={{- padding: '2px 6px',- backgroundColor: FINCEPT.PURPLE + '30',- border: `1px solid ${FINCEPT.PURPLE}`,- color: FINCEPT.PURPLE,- fontSize: '8px',- display: 'flex',- alignItems: 'center',- gap: '4px',+ backgroundColor: COLORS.BORDER,+ borderLeft: `3px solid ${+ step.status === 'completed' ? COLORS.GREEN :+ step.status === 'failed' ? COLORS.RED :+ step.status === 'running' ? COLORS.ORANGE :+ COLORS.GRAY+ }`,}}>- {tool}- <button- onClick={() => toggleTool(tool)}- style={{ background: 'none', border: 'none', color: FINCEPT.PURPLE, cursor: 'pointer', padding: 0 }}+ <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: COLORS.DARK_BG, color: COLORS.GRAY }}>+ {idx + 1}+ </span>+ <div className="flex-1">+ <div className="text-sm font-medium" style={{ color: COLORS.WHITE }}>{step.name}</div>+ <div className="text-xs" style={{ color: COLORS.GRAY }}>+ Type: {step.step_type}+ {step.dependencies.length > 0 && ` • Depends on: ${step.dependencies.join(', ')}`}+ </div>+ </div>+ <span+ className="text-xs px-2 py-0.5 rounded"+ style={{+ backgroundColor: step.status === 'completed' ? COLORS.GREEN + '20' :+ step.status === 'failed' ? COLORS.RED + '20' :+ step.status === 'running' ? COLORS.ORANGE + '20' :+ COLORS.BORDER,+ color: step.status === 'completed' ? COLORS.GREEN :+ step.status === 'failed' ? COLORS.RED :+ step.status === 'running' ? COLORS.ORANGE :+ COLORS.GRAY,+ }}>- x- </button>- </span>+ {step.status}+ </span>+ </div>))}+ </div>++ {/* Results */}+ {currentPlan.is_complete && currentPlan.context && (+ <div className="mt-4 p-3 rounded" style={{ backgroundColor: COLORS.DARK_BG }}>+ <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>PLAN RESULTS</div>+ <pre className="text-xs whitespace-pre-wrap" style={{ color: COLORS.WHITE }}>+ {JSON.stringify(currentPlan.context, null, 2)}+ </pre>+ </div>+ )}+ </div>+ )}++ {/* Plan Templates */}+ <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="text-xs font-medium mb-3" style={{ color: COLORS.GRAY }}>PLAN TEMPLATES</div>+ <div className="grid grid-cols-2 gap-2">+ {[+ { id: 'stock_analysis', name: 'Stock Analysis', desc: 'Full fundamental + technical analysis' },+ { id: 'portfolio_rebalance', name: 'Portfolio Rebalance', desc: 'Analyze and rebalance portfolio' },+ { id: 'sector_rotation', name: 'Sector Rotation', desc: 'Identify sector opportunities' },+ { id: 'risk_audit', name: 'Risk Audit', desc: 'Comprehensive risk assessment' },+ ].map(template => (<button- onClick={() => setSelectedTools([])}- style={{- padding: '2px 6px',- backgroundColor: 'transparent',- border: `1px solid ${FINCEPT.RED}`,- color: FINCEPT.RED,- cursor: 'pointer',- fontSize: '8px',+ key={template.id}+ onClick={() => {+ setWorkflowSymbol('AAPL');+ createPlan();}}+ className="p-3 rounded text-left hover:bg-[#1F1F1F] transition-colors"+ style={{ backgroundColor: COLORS.BORDER }}>- Clear All+ <div className="text-sm font-medium" style={{ color: COLORS.WHITE }}>{template.name}</div>+ <div className="text-xs" style={{ color: COLORS.GRAY }}>{template.desc}</div></button>- </div>+ ))}+ </div>+ </div>+ </div>+ );++ // =============================================================================+ // Render: Tools View+ // =============================================================================++ const renderToolsView = () => (+ <div className="p-4 space-y-4">+ <div className="flex items-center gap-3">+ <h2 className="text-lg font-semibold" style={{ color: COLORS.WHITE }}>Available Tools</h2>+ {toolsInfo && (+ <span className="px-2 py-0.5 rounded text-xs" style={{ backgroundColor: COLORS.ORANGE + '20', color: COLORS.ORANGE }}>+ {toolsInfo.total_count} tools+ </span>)}</div>- {/* Tools List */}- <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>- {Object.entries(filteredTools).map(([category, tools]) => (- <div key={category} style={{ marginBottom: '8px' }}>- <button- onClick={() => toggleCategory(category)}- style={{- width: '100%',- padding: '8px 12px',- backgroundColor: FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- color: FINCEPT.CYAN,- cursor: 'pointer',- fontSize: '11px',- fontWeight: 600,- display: 'flex',- alignItems: 'center',- gap: '8px',- textAlign: 'left',- }}- >- {expandedCategories.has(category) ? <ChevronDown size={12} /> : <ChevronRight size={12} />}- {category.toUpperCase()}- <span style={{ color: FINCEPT.GRAY, fontWeight: 400 }}>({tools.length})</span>- </button>- {expandedCategories.has(category) && (- <div style={{- padding: '8px',- backgroundColor: FINCEPT.DARK_BG,- borderLeft: `1px solid ${FINCEPT.BORDER}`,- borderRight: `1px solid ${FINCEPT.BORDER}`,- borderBottom: `1px solid ${FINCEPT.BORDER}`,- display: 'flex',- gap: '6px',- flexWrap: 'wrap',- }}>- {tools.map(tool => (- <button- key={tool}- onClick={() => toggleTool(tool)}- style={{- padding: '4px 8px',- backgroundColor: selectedTools.includes(tool) ? FINCEPT.PURPLE + '40' : FINCEPT.PANEL_BG,- border: `1px solid ${selectedTools.includes(tool) ? FINCEPT.PURPLE : FINCEPT.BORDER}`,- color: selectedTools.includes(tool) ? FINCEPT.PURPLE : FINCEPT.GREEN,- cursor: 'pointer',- fontSize: '9px',- display: 'flex',- alignItems: 'center',- gap: '4px',- }}- >- {selectedTools.includes(tool) && <Check size={10} />}- {tool}- <button- onClick={(e) => { e.stopPropagation(); copyTool(tool); }}- style={{ background: 'none', border: 'none', color: FINCEPT.GRAY, cursor: 'pointer', padding: 0 }}- >- {copiedTool === tool ? <Check size={10} color={FINCEPT.GREEN} /> : <Copy size={10} />}- </button>- </button>- ))}- </div>- )}+ {/* Search */}+ <div className="relative">+ <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: COLORS.GRAY }} />+ <input+ type="text"+ value={toolSearch}+ onChange={e => setToolSearch(e.target.value)}+ placeholder="Search tools..."+ className="w-full pl-10 pr-3 py-2 rounded text-sm"+ style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ />+ </div>++ {/* Selected Tools */}+ {selectedTools.length > 0 && (+ <div className="p-3 rounded" style={{ backgroundColor: COLORS.ORANGE + '10', border: `1px solid ${COLORS.ORANGE}40` }}>+ <div className="text-xs font-medium mb-2" style={{ color: COLORS.ORANGE }}>SELECTED ({selectedTools.length})</div>+ <div className="flex flex-wrap gap-1">+ {selectedTools.map(tool => (+ <span+ key={tool}+ onClick={() => toggleToolSelection(tool)}+ className="px-2 py-0.5 rounded text-xs cursor-pointer"+ style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE }}+ >+ {tool} ×+ </span>+ ))}</div>- ))}+ </div>+ )}++ {/* Tool Categories */}+ <div className="space-y-2">+ {toolsInfo?.categories?.map(category => {+ const tools = toolsInfo.tools[category] || [];+ const filteredTools = toolSearch+ ? tools.filter(t => t.toLowerCase().includes(toolSearch.toLowerCase()))+ : tools;++ if (filteredTools.length === 0) return null;++ return (+ <div key={category} className="rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <button+ onClick={() => toggleToolCategory(category)}+ className="w-full flex items-center justify-between p-3"+ >+ <span className="font-medium text-sm" style={{ color: COLORS.WHITE }}>{category}</span>+ <div className="flex items-center gap-2">+ <span className="text-xs" style={{ color: COLORS.GRAY }}>{filteredTools.length}</span>+ {expandedCategories.has(category) ? <ChevronDown size={14} /> : <ChevronRight size={14} />}+ </div>+ </button>+ {expandedCategories.has(category) && (+ <div className="px-3 pb-3 flex flex-wrap gap-1">+ {filteredTools.map(tool => (+ <span+ key={tool}+ onClick={() => toggleToolSelection(tool)}+ className="px-2 py-1 rounded text-xs cursor-pointer flex items-center gap-1"+ style={{+ backgroundColor: selectedTools.includes(tool) ? COLORS.ORANGE : COLORS.BORDER,+ color: COLORS.WHITE,+ }}+ >+ {tool}+ <button onClick={e => { e.stopPropagation(); copyTool(tool); }}>+ {copiedTool === tool ? <Check size={10} /> : <Copy size={10} />}+ </button>+ </span>+ ))}+ </div>+ )}+ </div>+ );+ })}</div></div>);+ // =============================================================================+ // Render: Chat View+ // =============================================================================++ const handleChatSubmit = async () => {+ if (!chatInput.trim() || loading) return;++ const query = chatInput;+ setChatInput('');+ setTestQuery(query);++ // Add user message+ setChatMessages(prev => [...prev, { role: 'user', content: query, timestamp: new Date() }]);++ setLoading(true);+ try {+ const apiKeys = await getApiKeys();++ if (useAutoRouting) {+ // Route and execute+ const routingResult = await agentService.routeQuery(query, apiKeys);+ setLastRoutingResult(routingResult);++ setChatMessages(prev => [+ ...prev,+ {+ role: 'system',+ content: `🎯 Routed to: ${routingResult.agent_id} (${routingResult.intent})`,+ timestamp: new Date(),+ routingInfo: routingResult,+ },+ ]);++ const result = await agentService.executeRoutedQuery(query, apiKeys);+ setChatMessages(prev => [+ ...prev,+ {+ role: 'assistant',+ content: result.response || result.error || 'No response',+ timestamp: new Date(),+ agentName: routingResult.agent_id,+ },+ ]);+ } else {+ // Direct agent execution+ const config = agentService.buildAgentConfig(+ editedConfig.provider,+ editedConfig.model_id,+ editedConfig.instructions,+ {+ tools: selectedTools.length > 0 ? selectedTools : editedConfig.tools,+ temperature: editedConfig.temperature,+ maxTokens: editedConfig.max_tokens,+ memory: editedConfig.enable_memory,+ }+ );++ const result = await agentService.runAgent(query, config, apiKeys);+ setChatMessages(prev => [+ ...prev,+ {+ role: 'assistant',+ content: result.response || result.error || 'No response',+ timestamp: new Date(),+ agentName: selectedAgent?.name || 'Agent',+ },+ ]);+ }+ } catch (err: any) {+ setChatMessages(prev => [+ ...prev,+ { role: 'system', content: `Error: ${err.message}`, timestamp: new Date() },+ ]);+ } finally {+ setLoading(false);+ }+ };+const renderChatView = () => (- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>- {/* Chat Messages */}- <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>+ <div className="flex flex-col h-full">+ {/* Chat Header */}+ <div className="p-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>+ <div className="flex items-center gap-2">+ <MessageSquare size={16} style={{ color: COLORS.ORANGE }} />+ <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>Agent Chat</span>+ </div>+ <div className="flex items-center gap-2">+ <span className="text-xs" style={{ color: COLORS.GRAY }}>Auto-Route</span>+ <button+ onClick={() => setUseAutoRouting(!useAutoRouting)}+ style={{ color: useAutoRouting ? COLORS.GREEN : COLORS.GRAY }}+ >+ {useAutoRouting ? <ToggleRight size={20} /> : <ToggleLeft size={20} />}+ </button>+ </div>+ </div>++ {/* Messages */}+ <div className="flex-1 overflow-y-auto p-4 space-y-3">{chatMessages.length === 0 ? (- <div style={{ textAlign: 'center', padding: '40px', color: FINCEPT.GRAY }}>- <MessageSquare size={32} style={{ margin: '0 auto 12px', opacity: 0.3 }} />- <div style={{ fontSize: '11px' }}>No messages yet</div>- <div style={{ fontSize: '10px', marginTop: '4px' }}>Select an agent and start chatting</div>+ <div className="text-center py-8" style={{ color: COLORS.GRAY }}>+ <Sparkles size={32} className="mx-auto mb-2" />+ <p>Start a conversation</p>+ <p className="text-xs mt-1">+ {useAutoRouting ? 'Queries will be auto-routed to the best agent' : `Using: ${selectedAgent?.name || 'No agent selected'}`}+ </p></div>) : (- chatMessages.map((msg, idx) => (- <div- key={idx}- style={{- marginBottom: '12px',- padding: '10px',- backgroundColor: msg.role === 'user' ? FINCEPT.BLUE + '20' : FINCEPT.PANEL_BG,- borderLeft: `3px solid ${msg.role === 'user' ? FINCEPT.BLUE : FINCEPT.GREEN}`,- }}- >- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>- {msg.role === 'user' ? 'You' : msg.agentName || 'Agent'}- {msg.outputModel && <span style={{ color: FINCEPT.PURPLE }}> ({msg.outputModel})</span>}- <span style={{ marginLeft: '8px' }}>{msg.timestamp.toLocaleTimeString()}</span>- </div>- <div style={{ fontSize: '11px', color: FINCEPT.WHITE, whiteSpace: 'pre-wrap' }}>- {msg.content}+ chatMessages.map((msg, i) => (+ <div key={i} className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>+ <div+ className="max-w-[85%] p-3 rounded-lg"+ style={{+ backgroundColor: msg.role === 'user' ? COLORS.ORANGE :+ msg.role === 'system' ? COLORS.PURPLE + '20' : COLORS.PANEL_BG,+ color: COLORS.WHITE,+ border: msg.role === 'system' ? `1px solid ${COLORS.PURPLE}40` : 'none',+ }}+ >+ {msg.agentName && (+ <div className="text-xs mb-1 flex items-center gap-1" style={{ color: COLORS.ORANGE }}>+ <Bot size={12} />+ {msg.agentName}+ </div>+ )}+ <div className="text-sm whitespace-pre-wrap">{msg.content}</div>+ <div className="text-xs mt-1 opacity-60">+ {msg.timestamp.toLocaleTimeString()}+ </div></div></div>)))}+ <div ref={chatEndRef} /></div>- {/* Chat Input */}- <div style={{- padding: '12px',- borderTop: `1px solid ${FINCEPT.BORDER}`,- backgroundColor: FINCEPT.HEADER_BG,- }}>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '8px' }}>- Agent: {selectedAgent?.name || 'None selected'} | Team: {teamMembers.length} members- </div>- <form onSubmit={handleChatSubmit} style={{ display: 'flex', gap: '8px' }}>+ {/* Input */}+ <div className="p-4 border-t" style={{ borderColor: COLORS.BORDER }}>+ <div className="flex gap-2"><inputtype="text"value={chatInput}- onChange={(e) => setChatInput(e.target.value)}- placeholder="Type a message..."- style={{- flex: 1,- padding: '8px 12px',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${FINCEPT.BORDER}`,- color: FINCEPT.WHITE,- fontSize: '11px',- outline: 'none',+ onChange={e => setChatInput(e.target.value)}+ onKeyDown={e => {+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault();+ handleChatSubmit();+ }}}+ placeholder={useAutoRouting ? 'Ask anything - auto-routed to best agent...' : 'Type a message...'}+ className="flex-1 px-3 py-2 rounded text-sm"+ style={{ backgroundColor: COLORS.PANEL_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}/><button- type="submit"- disabled={loading || (!selectedAgent && teamMembers.length === 0)}- style={{- padding: '8px 16px',- backgroundColor: FINCEPT.BLUE,- border: 'none',- color: FINCEPT.WHITE,- cursor: loading ? 'not-allowed' : 'pointer',- fontSize: '11px',- fontWeight: 600,- opacity: loading ? 0.5 : 1,- }}+ onClick={handleChatSubmit}+ disabled={loading || !chatInput.trim()}+ className="px-4 py-2 rounded flex items-center gap-2"+ style={{ backgroundColor: COLORS.ORANGE, color: COLORS.WHITE, opacity: loading ? 0.5 : 1 }}>- {loading ? 'Sending...' : 'Send'}+ {loading ? <Loader2 size={16} className="animate-spin" /> : <Zap size={16} />}+ Send</button>- </form>+ </div></div></div>);+ // =============================================================================+ // Render: System View+ // =============================================================================+const renderSystemView = () => (- <div style={{ flex: 1, padding: '16px', overflow: 'auto' }}>+ <div className="p-4 space-y-4">+ <div className="flex items-center justify-between">+ <h2 className="text-lg font-semibold" style={{ color: COLORS.WHITE }}>System Capabilities</h2>+ <button+ onClick={() => loadSystemData()}+ className="p-2 rounded"+ style={{ backgroundColor: COLORS.BORDER }}+ >+ <RefreshCw size={14} style={{ color: COLORS.WHITE }} />+ </button>+ </div>+{systemInfo ? (- <div style={{ display: 'grid', gap: '16px' }}>- {/* Header */}- <div style={{- padding: '16px',- backgroundColor: FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.ORANGE}`,- }}>- <div style={{ fontSize: '18px', fontWeight: 700, color: FINCEPT.ORANGE, marginBottom: '8px' }}>- FinAgent Core v{systemInfo.version}- </div>- <div style={{ fontSize: '11px', color: FINCEPT.GRAY }}>- Powered by {systemInfo.framework} framework- </div>+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4">+ <div className="p-4 rounded text-center" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="text-2xl font-bold" style={{ color: COLORS.ORANGE }}>{systemInfo.capabilities.model_providers}</div>+ <div className="text-xs" style={{ color: COLORS.GRAY }}>Model Providers</div></div>-- {/* Capabilities */}- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px' }}>- <div style={{ padding: '12px', backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, textAlign: 'center' }}>- <div style={{ fontSize: '24px', fontWeight: 700, color: FINCEPT.CYAN }}>{systemInfo.capabilities.model_providers}</div>- <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>Model Providers</div>- </div>- <div style={{ padding: '12px', backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, textAlign: 'center' }}>- <div style={{ fontSize: '24px', fontWeight: 700, color: FINCEPT.GREEN }}>{systemInfo.capabilities.tools}</div>- <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>Tools Available</div>- </div>- <div style={{ padding: '12px', backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, textAlign: 'center' }}>- <div style={{ fontSize: '24px', fontWeight: 700, color: FINCEPT.PURPLE }}>{systemInfo.capabilities.vectordbs.length}</div>- <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>Vector DBs</div>- </div>- <div style={{ padding: '12px', backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, textAlign: 'center' }}>- <div style={{ fontSize: '24px', fontWeight: 700, color: FINCEPT.YELLOW }}>{systemInfo.capabilities.embedders.length}</div>- <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>Embedders</div>- </div>+ <div className="p-4 rounded text-center" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="text-2xl font-bold" style={{ color: COLORS.ORANGE }}>{systemInfo.capabilities.tools}</div>+ <div className="text-xs" style={{ color: COLORS.GRAY }}>Tools</div>+ </div>+ <div className="p-4 rounded text-center" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="text-2xl font-bold" style={{ color: COLORS.ORANGE }}>{discoveredAgents.length}</div>+ <div className="text-xs" style={{ color: COLORS.GRAY }}>Discovered Agents</div>+ </div>+ <div className="p-4 rounded text-center" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="text-2xl font-bold" style={{ color: COLORS.ORANGE }}>{configuredLLMs.length}</div>+ <div className="text-xs" style={{ color: COLORS.GRAY }}>Configured LLMs</div></div>+ </div>+ ) : (+ <div className="text-center py-8" style={{ color: COLORS.GRAY }}>Loading system info...</div>+ )}- {/* Features */}- <div>- <div style={{ fontSize: '12px', fontWeight: 600, color: FINCEPT.WHITE, marginBottom: '8px' }}>Features</div>- <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>- {systemInfo.features.map(feature => (- <span- key={feature}- style={{- padding: '4px 8px',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${FINCEPT.BORDER}`,- color: FINCEPT.GREEN,- fontSize: '9px',- }}+ {/* Configured LLMs from Settings */}+ <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="flex items-center justify-between mb-3">+ <div className="text-xs font-medium" style={{ color: COLORS.GRAY }}>CONFIGURED LLM PROVIDERS (from Settings)</div>+ <button+ onClick={() => loadLLMConfigs()}+ className="px-2 py-1 rounded text-xs"+ style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}+ >+ Refresh+ </button>+ </div>+ {configuredLLMs.length > 0 ? (+ <div className="space-y-2">+ {configuredLLMs.map((llm, idx) => {+ const hasKey = !!llm.api_key && llm.api_key.length > 0;+ return (+ <div+ key={idx}+ className="flex items-center justify-between p-2 rounded"+ style={{ backgroundColor: COLORS.BORDER }}>- {feature.replace(/_/g, ' ')}- </span>- ))}- </div>+ <div className="flex items-center gap-2">+ {llm.is_active && (+ <span className="px-1.5 py-0.5 rounded text-xs" style={{ backgroundColor: COLORS.GREEN + '30', color: COLORS.GREEN }}>+ Active+ </span>+ )}+ <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>+ {llm.provider.charAt(0).toUpperCase() + llm.provider.slice(1)}+ </span>+ <span className="text-xs" style={{ color: COLORS.GRAY }}>+ {llm.model}+ </span>+ </div>+ <div className="flex items-center gap-2">+ {hasKey ? (+ <span className="flex items-center gap-1 text-xs" style={{ color: COLORS.GREEN }}>+ <CheckCircle size={12} /> API Key Set+ </span>+ ) : (+ <span className="flex items-center gap-1 text-xs" style={{ color: COLORS.RED }}>+ <AlertCircle size={12} /> No API Key+ </span>+ )}+ </div>+ </div>+ );+ })}</div>+ ) : (+ <div className="text-center py-4" style={{ color: COLORS.GRAY }}>+ <AlertCircle size={24} className="mx-auto mb-2" />+ <p className="text-sm">No LLM providers configured</p>+ <p className="text-xs mt-1">Go to Settings → LLM Configuration to add providers</p>+ </div>+ )}+ {configuredLLMs.filter(l => !l.api_key || l.api_key.length === 0).length > 0 && (+ <div className="mt-3 p-2 rounded text-xs" style={{ backgroundColor: COLORS.RED + '10', color: COLORS.RED }}>+ {configuredLLMs.filter(l => !l.api_key || l.api_key.length === 0).length} provider(s) missing API keys. Go to Settings → LLM Configuration to add them.+ </div>+ )}+ </div>- {/* Output Models */}+ {/* Cache Stats */}+ <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="flex items-center justify-between mb-3">+ <div className="text-xs font-medium" style={{ color: COLORS.GRAY }}>CACHE STATISTICS</div>+ <button+ onClick={() => agentService.clearCache()}+ className="px-2 py-1 rounded text-xs"+ style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}+ >+ Clear Cache+ </button>+ </div>+ <div className="grid grid-cols-3 gap-4 text-sm"><div>- <div style={{ fontSize: '12px', fontWeight: 600, color: FINCEPT.WHITE, marginBottom: '8px' }}>Structured Output Models</div>- <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>- {systemInfo.capabilities.output_models.map(model => (- <span- key={model}- style={{- padding: '4px 8px',- backgroundColor: FINCEPT.PURPLE + '30',- border: `1px solid ${FINCEPT.PURPLE}`,- color: FINCEPT.PURPLE,- fontSize: '9px',- }}- >- {model.replace(/_/g, ' ')}- </span>- ))}- </div>+ <div style={{ color: COLORS.GRAY }}>Static Cache:</div>+ <div style={{ color: COLORS.WHITE }}>{agentService.getCacheStats().cacheSize} items</div></div>-- {/* Tool Categories */}<div>- <div style={{ fontSize: '12px', fontWeight: 600, color: FINCEPT.WHITE, marginBottom: '8px' }}>Tool Categories</div>- <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>- {systemInfo.capabilities.tool_categories.map(cat => (- <span- key={cat}- style={{- padding: '4px 8px',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${FINCEPT.BORDER}`,- color: FINCEPT.CYAN,- fontSize: '9px',- }}- >- {cat}- </span>- ))}- </div>+ <div style={{ color: COLORS.GRAY }}>Response Cache:</div>+ <div style={{ color: COLORS.WHITE }}>{agentService.getCacheStats().responseCacheSize} items</div>+ </div>+ <div>+ <div style={{ color: COLORS.GRAY }}>Max Size:</div>+ <div style={{ color: COLORS.WHITE }}>{agentService.getCacheStats().maxSize} items</div></div></div>- ) : (- <div style={{ textAlign: 'center', padding: '40px', color: FINCEPT.GRAY }}>- <RefreshCw size={24} className="animate-spin" style={{ margin: '0 auto 12px' }} />- <div>Loading system info...</div>+ </div>++ {systemInfo?.features && (+ <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>FEATURES</div>+ <div className="flex flex-wrap gap-2">+ {systemInfo.features.map(feature => (+ <span key={feature} className="px-2 py-1 rounded text-xs" style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}>+ {feature.replace(/_/g, ' ')}+ </span>+ ))}+ </div></div>)}++ <div className="p-4 rounded" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>VERSION INFO</div>+ <div className="grid grid-cols-2 gap-2 text-sm">+ <div style={{ color: COLORS.GRAY }}>Version:</div>+ <div style={{ color: COLORS.WHITE }}>{systemInfo?.version || 'N/A'}</div>+ <div style={{ color: COLORS.GRAY }}>Framework:</div>+ <div style={{ color: COLORS.WHITE }}>{systemInfo?.framework || 'N/A'}</div>+ </div>+ </div></div>);- return (- <div style={{- height: '100%',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- fontFamily: '"IBM Plex Mono", "Consolas", monospace',- overflow: 'hidden',- display: 'flex',- flexDirection: 'column'- }}>- <style>{`- *::-webkit-scrollbar { width: 6px; height: 6px; }- *::-webkit-scrollbar-track { background: ${FINCEPT.DARK_BG}; }- *::-webkit-scrollbar-thumb { background: ${FINCEPT.BORDER}; border-radius: 3px; }- *::-webkit-scrollbar-thumb:hover { background: ${FINCEPT.MUTED}; }- @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }- .animate-spin { animation: spin 1s linear infinite; }- `}</style>-- {/* TOP NAVIGATION BAR */}- <div style={{- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `2px solid ${FINCEPT.ORANGE}`,- padding: '6px 12px',- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- flexShrink: 0,- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <Bot size={18} color={FINCEPT.ORANGE} />- <span style={{ color: FINCEPT.ORANGE, fontWeight: 700, fontSize: '14px', letterSpacing: '0.5px' }}>- AGENT STUDIO- </span>- </div>-- <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />+ // =============================================================================+ // Main Render+ // =============================================================================- {/* View Mode Selector */}- <div style={{ display: 'flex', gap: '4px' }}>- {viewModes.map((mode) => {- const Icon = mode.icon;- return (- <button- key={mode.id}- onClick={() => setViewMode(mode.id)}- style={{- padding: '4px 10px',- backgroundColor: viewMode === mode.id ? FINCEPT.ORANGE : FINCEPT.PANEL_BG,- border: `1px solid ${viewMode === mode.id ? FINCEPT.ORANGE : FINCEPT.BORDER}`,- color: viewMode === mode.id ? FINCEPT.DARK_BG : FINCEPT.CYAN,- cursor: 'pointer',- fontSize: '9px',- fontWeight: 600,- letterSpacing: '0.5px',- display: 'flex',- alignItems: 'center',- gap: '4px',- }}- >- <Icon size={10} />- {mode.name}- </button>- );- })}- </div>+ return (+ <div className="flex flex-col h-full" style={{ backgroundColor: COLORS.DARK_BG }}>+ {/* Header */}+ <div className="flex items-center justify-between px-4 py-3 border-b" style={{ borderColor: COLORS.BORDER }}>+ <div className="flex items-center gap-3">+ <Bot size={20} style={{ color: COLORS.ORANGE }} />+ <h1 className="text-lg font-semibold" style={{ color: COLORS.WHITE }}>Agent Studio</h1>+ <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: COLORS.PURPLE + '20', color: COLORS.PURPLE }}>+ v2.1+ </span></div>- <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>- <button- onClick={() => { loadAgents(); loadSystemInfo(); loadToolsInfo(); }}- disabled={loading}- style={{- padding: '4px 10px',- backgroundColor: FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- color: FINCEPT.CYAN,- cursor: loading ? 'not-allowed' : 'pointer',- fontSize: '10px',- fontWeight: 600,- display: 'flex',- alignItems: 'center',- gap: '4px'- }}- >- <RefreshCw size={12} className={loading ? 'animate-spin' : ''} />- Refresh- </button>+ {/* View Mode Tabs */}+ <div className="flex gap-1">+ {VIEW_MODES.map(mode => (+ <button+ key={mode.id}+ onClick={() => setViewMode(mode.id)}+ className="px-3 py-1.5 rounded text-xs font-medium flex items-center gap-1.5 transition-colors"+ style={{+ backgroundColor: viewMode === mode.id ? COLORS.ORANGE : 'transparent',+ color: viewMode === mode.id ? COLORS.WHITE : COLORS.GRAY,+ }}+ >+ <mode.icon size={14} />+ {mode.name}+ </button>+ ))}</div></div>- {/* Status Messages */}- {(error || success) && (- <div style={{- padding: '8px 12px',- backgroundColor: error ? FINCEPT.RED + '20' : FINCEPT.GREEN + '20',- borderBottom: `1px solid ${error ? FINCEPT.RED : FINCEPT.GREEN}`,- display: 'flex',- alignItems: 'center',- gap: '8px',- fontSize: '10px'- }}>- {error ? <AlertCircle size={14} color={FINCEPT.RED} /> : <CheckCircle size={14} color={FINCEPT.GREEN} />}- <span style={{ color: error ? FINCEPT.RED : FINCEPT.GREEN, flex: 1 }}>- {error || success}- </span>- <button- onClick={() => { setError(null); setSuccess(null); }}- style={{ background: 'none', border: 'none', color: 'inherit', cursor: 'pointer', fontSize: '14px' }}- >- x- </button>+ {/* Notifications */}+ {error && (+ <div className="mx-4 mt-2 p-3 rounded flex items-center gap-2" style={{ backgroundColor: COLORS.RED + '20', color: COLORS.RED }}>+ <AlertCircle size={16} />+ <span className="text-sm flex-1">{error}</span>+ <button onClick={() => setError(null)}>×</button>+ </div>+ )}+ {success && (+ <div className="mx-4 mt-2 p-3 rounded flex items-center gap-2" style={{ backgroundColor: COLORS.GREEN + '20', color: COLORS.GREEN }}>+ <CheckCircle size={16} />+ <span className="text-sm">{success}</span></div>)}- {/* MAIN CONTENT */}- <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>+ {/* Content */}+ <div className="flex-1 overflow-hidden">{viewMode === 'agents' && renderAgentsView()}{viewMode === 'teams' && renderTeamsView()}{viewMode === 'workflows' && renderWorkflowsView()}+ {viewMode === 'planner' && renderPlannerView()}{viewMode === 'tools' && renderToolsView()}{viewMode === 'chat' && renderChatView()}{viewMode === 'system' && renderSystemView()}</div>- {/* Footer */}- <TabFooter- tabName="AGENT STUDIO"- leftInfo={[- { label: `${agents.length} agents`, color: FINCEPT.CYAN },- { label: `${teamMembers.length} in team`, color: FINCEPT.PURPLE },- { label: `${selectedTools.length} tools`, color: FINCEPT.GREEN },- ]}- statusInfo={systemInfo ? `v${systemInfo.version} | ${systemInfo.capabilities.tools} tools | ${systemInfo.capabilities.model_providers} providers` : 'Loading...'}- />+ <TabFooter tabName="Agent Studio v2.1" /></div>);};diff --git a/fincept-terminal-desktop/src/components/tabs/AlphaArenaTab.tsx b/fincept-terminal-desktop/src/components/tabs/AlphaArenaTab.tsxdeleted file mode 100644index 39aad015f..000000000--- a/fincept-terminal-desktop/src/components/tabs/AlphaArenaTab.tsx+++ /dev/null@@ -1,833 +0,0 @@-/**- * Alpha Arena Tab - Simplified Real-time UI- * Direct integration with backend Python service- */--import React, { useState, useEffect } from 'react';-import { Trophy, Play, Square, TrendingUp, TrendingDown, RefreshCw } from 'lucide-react';-import { invoke } from '@tauri-apps/api/core';-import { TabFooter } from '@/components/common/TabFooter';-import { useTranslation } from 'react-i18next';-import { useBrokerContext } from '@/contexts/BrokerContext';-import { alphaArenaBrokerBridge } from '@/services/trading/alphaArenaBrokerBridge';--// Fincept color palette-const COLORS = {- ORANGE: '#FF8800',- WHITE: '#FFFFFF',- RED: '#FF3B3B',- GREEN: '#00D66F',- GRAY: '#787878',- DARK_BG: '#000000',- PANEL_BG: '#0F0F0F',- HEADER_BG: '#1A1A1A',- BORDER: '#2A2A2A',-};--interface LeaderboardEntry {- model_name: string;- portfolio_value: number;- total_pnl: number;- return_pct: number;- trades_count: number;- cash: number;- positions_count: number;- rank: number;-}--interface ModelDecision {- competition_id: string;- model_name: string;- cycle_number: number;- action: string;- symbol: string;- quantity: number;- confidence: number;- reasoning: string;- trade_executed: string;- timestamp: string;-}--const AlphaArenaTab: React.FC = () => {- const { t } = useTranslation('alphaArena');-- // BrokerContext integration- const {- activeBroker,- availableBrokers,- setActiveBroker,- tradingMode,- setTradingMode,- paperPortfolio,- activeAdapter,- defaultSymbols,- } = useBrokerContext();-- const [competitionId, setCompetitionId] = useState<string>('');- const [isRunning, setIsRunning] = useState(false);- const [leaderboard, setLeaderboard] = useState<LeaderboardEntry[]>([]);- const [decisions, setDecisions] = useState<ModelDecision[]>([]);- const [cycleCount, setCycleCount] = useState(0);- const [error, setError] = useState<string | null>(null);- const [isLoading, setIsLoading] = useState(false);- const [showCreateForm, setShowCreateForm] = useState(false);-- // Form state- const [competitionName, setCompetitionName] = useState('Alpha Arena Competition');- const [symbol, setSymbol] = useState(defaultSymbols[0] || 'BTC/USD');- const [mode, setMode] = useState<'baseline' | 'monk' | 'situational' | 'max_leverage'>('baseline');- const [selectedModels, setSelectedModels] = useState<string[]>(['gpt-4o-mini', 'claude-3-5-sonnet']);- const [apiKeys, setApiKeys] = useState<Record<string, string>>({- 'gpt-4o-mini': '',- 'claude-3-5-sonnet': ''- });-- // Use paper trading by default (can switch to live)- const usePaperTrading = tradingMode === 'paper';-- // Refresh leaderboard and decisions- const refreshData = async () => {- if (!competitionId) return;-- try {- // Get leaderboard- const leaderboardResult = await invoke<{ success: boolean; leaderboard: LeaderboardEntry[] }>(- 'get_alpha_leaderboard',- { competitionId }- );-- if (leaderboardResult.success) {- setLeaderboard(leaderboardResult.leaderboard);- }-- // Get decisions- const decisionsResult = await invoke<{ success: boolean; decisions: ModelDecision[] }>(- 'get_alpha_model_decisions',- { competitionId, modelName: null }- );-- if (decisionsResult.success) {- setDecisions(decisionsResult.decisions);- }- } catch (err) {- console.error('[AlphaArena] Refresh failed:', err);- }- };-- // Auto-refresh when competition exists (regardless of running state)- useEffect(() => {- if (!competitionId) return;-- // Initial load- refreshData();-- // Refresh every 3 seconds for live updates- const interval = setInterval(refreshData, 3000);- return () => clearInterval(interval);- }, [competitionId]);-- // Available models- const availableModels = [- { id: 'gpt-4o-mini', name: 'GPT-4O Mini', provider: 'openai' },- { id: 'gpt-4o', name: 'GPT-4O', provider: 'openai' },- { id: 'claude-3-5-sonnet', name: 'Claude 3.5 Sonnet', provider: 'anthropic' },- { id: 'gemini-2.0-flash', name: 'Gemini 2.0 Flash', provider: 'google' },- { id: 'deepseek-chat', name: 'DeepSeek Chat', provider: 'deepseek' }- ];-- const competitionModes = [- { value: 'baseline', label: 'Baseline', description: 'Standard trading with full market data' },- { value: 'monk', label: 'Monk Mode', description: 'Conservative capital preservation' },- { value: 'situational', label: 'Situational Awareness', description: 'Competition-aware agents' },- { value: 'max_leverage', label: 'Max Leverage', description: 'Maximum capital efficiency' }- ];-- // Create competition- const handleCreate = async () => {- setIsLoading(true);- setError(null);-- try {- // Validate- if (selectedModels.length === 0) {- setError('Please select at least one model');- setIsLoading(false);- return;- }-- const modelsWithKeys = selectedModels.filter(modelId => apiKeys[modelId]?.trim());- if (modelsWithKeys.length === 0) {- setError('Please provide API keys for selected models');- setIsLoading(false);- return;- }-- const models = modelsWithKeys.map(modelId => {- const model = availableModels.find(m => m.id === modelId);- return {- name: model?.name || modelId,- provider: model?.provider || 'openai',- model_id: modelId,- api_key: apiKeys[modelId]- };- });-- const config = {- competition_id: `comp_${Date.now()}_${Math.random().toString(36).substring(7)}`,- competition_name: competitionName,- models,- symbols: [symbol],- initial_capital: 10000.0,- exchange_id: 'kraken'- };-- console.log('[AlphaArena] Creating competition with config:', config);-- const result = await invoke<{ success: boolean; competition_id?: string; error?: string }>(- 'create_alpha_competition',- { configJson: JSON.stringify(config) }- );-- console.log('[AlphaArena] Create result:', result);-- if (result.success && result.competition_id) {- setCompetitionId(result.competition_id);- setShowCreateForm(false);- await refreshData();- } else {- setError(result.error || 'Failed to create competition');- }- } catch (err) {- console.error('[AlphaArena] Create error:', err);- setError(err instanceof Error ? err.message : String(err));- } finally {- setIsLoading(false);- }- };-- const toggleModelSelection = (modelId: string) => {- setSelectedModels(prev =>- prev.includes(modelId)- ? prev.filter(id => id !== modelId)- : [...prev, modelId]- );- if (!apiKeys[modelId]) {- setApiKeys(prev => ({ ...prev, [modelId]: '' }));- }- };-- // Run single cycle- const handleRunCycle = async () => {- if (!competitionId) return;-- setIsLoading(true);- try {- const result = await invoke<{ success: boolean; cycle_number?: number; error?: string }>(- 'run_alpha_cycle',- { competitionId }- );-- if (result.success) {- setCycleCount(result.cycle_number || 0);- await refreshData();- } else {- setError(result.error || 'Cycle failed');- }- } catch (err) {- setError(err instanceof Error ? err.message : 'Unknown error');- } finally {- setIsLoading(false);- }- };-- // Toggle continuous running- const handleToggleRunning = () => {- setIsRunning(!isRunning);- };-- // Auto-run cycles when running- useEffect(() => {- if (!isRunning || !competitionId) {- console.log('[AlphaArena] Auto-run disabled. Running:', isRunning, 'CompID:', competitionId);- return;- }-- console.log('[AlphaArena] Starting auto-run cycles');-- let isCancelled = false;-- const runCycle = async () => {- if (isCancelled) return;-- console.log('[AlphaArena] Executing cycle...');- setIsLoading(true);-- try {- const result = await invoke<{ success: boolean; cycle_number?: number; error?: string }>(- 'run_alpha_cycle',- { competitionId }- );-- if (!isCancelled) {- if (result.success) {- console.log('[AlphaArena] Cycle completed:', result.cycle_number);- setCycleCount(result.cycle_number || 0);- await refreshData();- } else {- console.error('[AlphaArena] Cycle failed:', result.error);- setError(result.error || 'Cycle failed');- }- }- } catch (err) {- if (!isCancelled) {- console.error('[AlphaArena] Cycle error:', err);- setError(err instanceof Error ? err.message : 'Unknown error');- }- } finally {- if (!isCancelled) {- setIsLoading(false);- }- }- };-- // Run first cycle immediately- runCycle();-- // Then run every 60 seconds- const interval = setInterval(runCycle, 60000);-- return () => {- console.log('[AlphaArena] Stopping auto-run cycles');- isCancelled = true;- clearInterval(interval);- };- }, [isRunning, competitionId]);-- return (- <div style={{- height: '100%',- backgroundColor: COLORS.DARK_BG,- color: COLORS.WHITE,- fontFamily: '"IBM Plex Mono", monospace',- display: 'flex',- flexDirection: 'column'- }}>- {/* Header */}- <div style={{- padding: '16px',- backgroundColor: COLORS.HEADER_BG,- borderBottom: `2px solid ${COLORS.ORANGE}`,- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center'- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>- <Trophy size={24} color={COLORS.ORANGE} />- <div>- <div style={{ fontSize: '18px', fontWeight: 700, color: COLORS.ORANGE }}>- {t('title')}- </div>- <div style={{ fontSize: '10px', color: COLORS.GRAY }}>- {t('header.competition')}- </div>- </div>- </div>-- <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>- {!competitionId ? (- <button- onClick={() => setShowCreateForm(true)}- style={{- padding: '10px 20px',- backgroundColor: COLORS.ORANGE,- border: 'none',- color: COLORS.DARK_BG,- fontSize: '12px',- fontWeight: 700,- cursor: 'pointer'- }}- >- {t('buttons.create')}- </button>- ) : (- <>- <button- onClick={handleRunCycle}- disabled={isLoading || isRunning}- style={{- padding: '10px 20px',- backgroundColor: COLORS.ORANGE,- border: 'none',- color: COLORS.DARK_BG,- fontSize: '12px',- fontWeight: 700,- cursor: (isLoading || isRunning) ? 'not-allowed' : 'pointer',- opacity: (isLoading || isRunning) ? 0.6 : 1,- display: 'flex',- alignItems: 'center',- gap: '8px'- }}- >- <RefreshCw size={14} />- RUN CYCLE- </button>-- <button- onClick={() => {- console.log('[AlphaArena] Toggle button clicked. Current state:', isRunning);- setIsRunning(!isRunning);- }}- disabled={isLoading}- style={{- padding: '10px 20px',- backgroundColor: isRunning ? COLORS.RED : COLORS.GREEN,- border: 'none',- color: COLORS.WHITE,- fontSize: '12px',- fontWeight: 700,- cursor: isLoading ? 'not-allowed' : 'pointer',- opacity: isLoading ? 0.6 : 1,- display: 'flex',- alignItems: 'center',- gap: '8px'- }}- >- {isRunning ? (- <>- <Square size={14} />- STOP AUTO {isLoading && '(RUNNING...)'}- </>- ) : (- <>- <Play size={14} />- START AUTO- </>- )}- </button>- </>- )}- </div>- </div>-- {/* Status Bar */}- {competitionId && (- <div style={{- padding: '12px 16px',- backgroundColor: COLORS.PANEL_BG,- borderBottom: `1px solid ${COLORS.BORDER}`,- display: 'flex',- gap: '24px',- fontSize: '11px'- }}>- <div>- <span style={{ color: COLORS.GRAY }}>COMPETITION ID: </span>- <span style={{ color: COLORS.ORANGE, fontWeight: 600 }}>{competitionId}</span>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>CYCLE: </span>- <span style={{ color: COLORS.WHITE, fontWeight: 600 }}>{cycleCount}</span>- </div>- <div>- <span style={{ color: COLORS.GRAY }}>STATUS: </span>- <span style={{ color: isRunning ? COLORS.GREEN : COLORS.GRAY, fontWeight: 600 }}>- {isRunning ? 'RUNNING' : 'PAUSED'}- </span>- </div>- </div>- )}-- {/* Create Form Modal */}- {showCreateForm && (- <div style={{- position: 'fixed',- top: 0,- left: 0,- right: 0,- bottom: 0,- backgroundColor: 'rgba(0,0,0,0.8)',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- zIndex: 1000- }}>- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `2px solid ${COLORS.ORANGE}`,- padding: '24px',- maxWidth: '600px',- width: '90%',- maxHeight: '80vh',- overflow: 'auto'- }}>- <h2 style={{ fontSize: '16px', color: COLORS.ORANGE, marginBottom: '20px', fontWeight: 700 }}>- CREATE NEW COMPETITION- </h2>-- {/* Competition Name */}- <div style={{ marginBottom: '16px' }}>- <label style={{ display: 'block', fontSize: '10px', color: COLORS.GRAY, marginBottom: '6px', fontWeight: 600 }}>- COMPETITION NAME- </label>- <input- type="text"- value={competitionName}- onChange={(e) => setCompetitionName(e.target.value)}- style={{- width: '100%',- padding: '8px',- backgroundColor: COLORS.HEADER_BG,- border: `1px solid ${COLORS.BORDER}`,- color: COLORS.WHITE,- fontSize: '11px',- fontFamily: 'inherit'- }}- />- </div>-- {/* Symbol */}- <div style={{ marginBottom: '16px' }}>- <label style={{ display: 'block', fontSize: '10px', color: COLORS.GRAY, marginBottom: '6px', fontWeight: 600 }}>- TRADING SYMBOL- </label>- <input- type="text"- value={symbol}- onChange={(e) => setSymbol(e.target.value)}- style={{- width: '100%',- padding: '8px',- backgroundColor: COLORS.HEADER_BG,- border: `1px solid ${COLORS.BORDER}`,- color: COLORS.WHITE,- fontSize: '11px',- fontFamily: 'inherit'- }}- />- </div>-- {/* Mode */}- <div style={{ marginBottom: '16px' }}>- <label style={{ display: 'block', fontSize: '10px', color: COLORS.GRAY, marginBottom: '6px', fontWeight: 600 }}>- MODE- </label>- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>- {competitionModes.map(m => (- <button- key={m.value}- onClick={() => setMode(m.value as any)}- style={{- padding: '10px',- backgroundColor: mode === m.value ? COLORS.ORANGE : COLORS.HEADER_BG,- border: `1px solid ${mode === m.value ? COLORS.ORANGE : COLORS.BORDER}`,- color: mode === m.value ? COLORS.DARK_BG : COLORS.WHITE,- fontSize: '10px',- fontWeight: 600,- cursor: 'pointer',- textAlign: 'left'- }}- >- <div style={{ fontWeight: 700 }}>{m.label}</div>- <div style={{ fontSize: '8px', opacity: 0.8 }}>{m.description}</div>- </button>- ))}- </div>- </div>-- {/* Models */}- <div style={{ marginBottom: '16px' }}>- <label style={{ display: 'block', fontSize: '10px', color: COLORS.GRAY, marginBottom: '6px', fontWeight: 600 }}>- SELECT MODELS (AT LEAST 2)- </label>- {availableModels.map(model => (- <div key={model.id} style={{ marginBottom: '12px' }}>- <label style={{- display: 'flex',- alignItems: 'center',- gap: '8px',- padding: '8px',- backgroundColor: COLORS.HEADER_BG,- border: `1px solid ${selectedModels.includes(model.id) ? COLORS.ORANGE : COLORS.BORDER}`,- cursor: 'pointer'- }}>- <input- type="checkbox"- checked={selectedModels.includes(model.id)}- onChange={() => toggleModelSelection(model.id)}- style={{ accentColor: COLORS.ORANGE }}- />- <div style={{ flex: 1 }}>- <div style={{ fontSize: '11px', fontWeight: 600 }}>{model.name}</div>- <div style={{ fontSize: '9px', color: COLORS.GRAY }}>{model.provider}</div>- </div>- </label>- {selectedModels.includes(model.id) && (- <input- type="password"- placeholder={`${model.provider} API Key`}- value={apiKeys[model.id] || ''}- onChange={(e) => setApiKeys(prev => ({ ...prev, [model.id]: e.target.value }))}- style={{- width: '100%',- padding: '6px',- marginTop: '6px',- backgroundColor: COLORS.DARK_BG,- border: `1px solid ${COLORS.BORDER}`,- color: COLORS.WHITE,- fontSize: '10px',- fontFamily: 'inherit'- }}- />- )}- </div>- ))}- </div>-- {/* Error */}- {error && (- <div style={{- marginBottom: '16px',- padding: '10px',- backgroundColor: `${COLORS.RED}20`,- border: `1px solid ${COLORS.RED}`,- color: COLORS.RED,- fontSize: '10px'- }}>- {error}- </div>- )}-- {/* Actions */}- <div style={{ display: 'flex', gap: '12px' }}>- <button- onClick={handleCreate}- disabled={isLoading}- style={{- flex: 1,- padding: '10px',- backgroundColor: isLoading ? COLORS.GRAY : COLORS.ORANGE,- border: 'none',- color: isLoading ? COLORS.DARK_BG : COLORS.DARK_BG,- fontSize: '11px',- fontWeight: 700,- cursor: isLoading ? 'not-allowed' : 'pointer'- }}- >- {isLoading ? 'CREATING...' : 'CREATE'}- </button>- <button- onClick={() => { setShowCreateForm(false); setError(null); }}- disabled={isLoading}- style={{- padding: '10px 20px',- backgroundColor: COLORS.HEADER_BG,- border: `1px solid ${COLORS.BORDER}`,- color: COLORS.WHITE,- fontSize: '11px',- fontWeight: 700,- cursor: isLoading ? 'not-allowed' : 'pointer'- }}- >- CANCEL- </button>- </div>- </div>- </div>- )}-- {/* Main Content */}- <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>- {/* Leaderboard */}- <div style={{- flex: 1,- backgroundColor: COLORS.PANEL_BG,- borderRight: `1px solid ${COLORS.BORDER}`,- display: 'flex',- flexDirection: 'column'- }}>- <div style={{- padding: '12px 16px',- backgroundColor: COLORS.HEADER_BG,- borderBottom: `1px solid ${COLORS.BORDER}`,- fontSize: '12px',- fontWeight: 700,- color: COLORS.ORANGE- }}>- LEADERBOARD- </div>-- <div style={{ flex: 1, overflow: 'auto' }}>- {leaderboard.length === 0 ? (- <div style={{- padding: '40px',- textAlign: 'center',- color: COLORS.GRAY,- fontSize: '11px'- }}>- No data yet. Create competition and run cycles.- </div>- ) : (- <table style={{ width: '100%', fontSize: '11px', borderCollapse: 'collapse' }}>- <thead>- <tr style={{ backgroundColor: COLORS.HEADER_BG, fontSize: '9px', color: COLORS.GRAY }}>- <th style={{ padding: '10px', textAlign: 'left' }}>RANK</th>- <th style={{ padding: '10px', textAlign: 'left' }}>MODEL</th>- <th style={{ padding: '10px', textAlign: 'right' }}>VALUE</th>- <th style={{ padding: '10px', textAlign: 'right' }}>P&L</th>- <th style={{ padding: '10px', textAlign: 'right' }}>RETURN</th>- <th style={{ padding: '10px', textAlign: 'right' }}>TRADES</th>- </tr>- </thead>- <tbody>- {leaderboard.map((entry) => (- <tr key={entry.rank} style={{ borderBottom: `1px solid ${COLORS.BORDER}` }}>- <td style={{ padding: '10px', fontWeight: 700, color: COLORS.ORANGE }}>- #{entry.rank}- </td>- <td style={{ padding: '10px', fontWeight: 600 }}>{entry.model_name}</td>- <td style={{ padding: '10px', textAlign: 'right', fontWeight: 600 }}>- ${entry.portfolio_value.toFixed(2)}- </td>- <td style={{- padding: '10px',- textAlign: 'right',- fontWeight: 700,- color: entry.total_pnl >= 0 ? COLORS.GREEN : COLORS.RED- }}>- {entry.total_pnl >= 0 ? '+' : ''}{entry.total_pnl.toFixed(2)}- </td>- <td style={{- padding: '10px',- textAlign: 'right',- fontWeight: 700,- color: entry.return_pct >= 0 ? COLORS.GREEN : COLORS.RED- }}>- {entry.return_pct >= 0 ? '+' : ''}{entry.return_pct.toFixed(2)}%- </td>- <td style={{ padding: '10px', textAlign: 'right' }}>- {entry.trades_count}- </td>- </tr>- ))}- </tbody>- </table>- )}- </div>- </div>-- {/* Decisions Panel */}- <div style={{- width: '500px',- backgroundColor: COLORS.PANEL_BG,- display: 'flex',- flexDirection: 'column'- }}>- <div style={{- padding: '12px 16px',- backgroundColor: COLORS.HEADER_BG,- borderBottom: `1px solid ${COLORS.BORDER}`,- fontSize: '12px',- fontWeight: 700,- color: COLORS.ORANGE- }}>- RECENT DECISIONS ({decisions.length})- </div>-- <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>- {decisions.length === 0 ? (- <div style={{- padding: '40px 20px',- textAlign: 'center',- color: COLORS.GRAY,- fontSize: '11px'- }}>- No trading decisions yet- </div>- ) : (- <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>- {decisions.slice().reverse().map((decision, idx) => (- <div- key={idx}- style={{- backgroundColor: COLORS.HEADER_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '12px'- }}- >- <div style={{- display: 'flex',- justifyContent: 'space-between',- marginBottom: '8px',- alignItems: 'center'- }}>- <span style={{ fontSize: '11px', fontWeight: 700 }}>- {decision.model_name}- </span>- <span style={{- fontSize: '10px',- padding: '3px 8px',- backgroundColor: decision.action === 'BUY' ? `${COLORS.GREEN}30` : `${COLORS.RED}30`,- color: decision.action === 'BUY' ? COLORS.GREEN : COLORS.RED,- fontWeight: 700- }}>- {decision.action}- </span>- </div>-- <div style={{ fontSize: '10px', color: COLORS.GRAY, marginBottom: '6px' }}>- <span style={{ color: COLORS.ORANGE }}>{decision.symbol}</span>- {' × '}- <span>{decision.quantity}</span>- {' | Cycle '}- <span>{decision.cycle_number}</span>- </div>-- <div style={{ fontSize: '10px', marginBottom: '8px' }}>- <span style={{ color: COLORS.GRAY }}>Confidence: </span>- <span style={{ color: COLORS.WHITE, fontWeight: 600 }}>- {(decision.confidence * 100).toFixed(0)}%- </span>- </div>-- <div style={{- fontSize: '9px',- color: COLORS.GRAY,- lineHeight: '1.5',- maxHeight: '60px',- overflow: 'hidden'- }}>- {decision.reasoning}- </div>-- <div style={{- fontSize: '8px',- color: COLORS.GRAY,- marginTop: '8px',- paddingTop: '8px',- borderTop: `1px solid ${COLORS.BORDER}`- }}>- {new Date(parseInt(decision.timestamp)).toLocaleString()}- </div>- </div>- ))}- </div>- )}- </div>- </div>- </div>-- <TabFooter- tabName="ALPHA ARENA"- leftInfo={[- { label: `Competition: ${competitionId || 'None'}`, color: COLORS.GRAY },- { label: `Models: ${leaderboard.length}`, color: COLORS.GRAY },- { label: `Status: ${isRunning ? 'RUNNING' : 'STOPPED'}`, color: isRunning ? COLORS.GREEN : COLORS.RED },- ]}- statusInfo={`Cycle: ${cycleCount} | Decisions: ${decisions.length} | ${error || 'Ready'}`}- backgroundColor={COLORS.PANEL_BG}- borderColor={COLORS.BORDER}- />- </div>- );-};--export default AlphaArenaTab;diff --git a/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx b/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsxindex 91ca70576..efc1f64fd 100644--- a/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx@@ -1,3665 +1,17 @@-import React, { useState, useEffect, useRef } from 'react';-import { useTerminalTheme } from '@/contexts/ThemeContext';-import { invoke } from '@tauri-apps/api/core';-import { createChart, CandlestickSeries, HistogramSeries, LineSeries, BarSeries } from 'lightweight-charts';-import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, ComposedChart, Bar, Area } from 'recharts';-import { ProChartWithToolkit } from './trading/charts/ProChartWithToolkit';-import { FinancialAnalysisPanel } from './equity-research/components/FinancialAnalysisPanel';-import { PeerComparisonPanel } from './equity-research/components/PeerComparisonPanel';-import { TabFooter } from '@/components/common/TabFooter';-import { useTranslation } from 'react-i18next';-import { Search, TrendingUp, BarChart3, FileText, Users, Newspaper, RefreshCw, AlertCircle, Info } from 'lucide-react';-import { createEquityResearchTabTour } from './tours/equityResearchTabTour';--// Import Fincept styles-import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, LAYOUT, EFFECTS, COMMON_STYLES } from './portfolio-tab/finceptStyles';--const COLORS = {- ORANGE: FINCEPT.ORANGE,- WHITE: FINCEPT.WHITE,- RED: FINCEPT.RED,- GREEN: FINCEPT.GREEN,- YELLOW: FINCEPT.YELLOW,- GRAY: FINCEPT.GRAY,- BLUE: FINCEPT.BLUE,- CYAN: FINCEPT.CYAN,- DARK_BG: FINCEPT.DARK_BG,- PANEL_BG: FINCEPT.PANEL_BG,- BORDER: FINCEPT.BORDER,- MAGENTA: '#FF00FF',- PURPLE: FINCEPT.PURPLE,- HEADER_BG: FINCEPT.HEADER_BG,- HOVER: FINCEPT.HOVER,-};--interface StockInfo {- symbol: string;- company_name: string;- sector: string;- industry: string;- market_cap: number | null;- pe_ratio: number | null;- forward_pe: number | null;- dividend_yield: number | null;- beta: number | null;- fifty_two_week_high: number | null;- fifty_two_week_low: number | null;- average_volume: number | null;- description: string;- website: string;- country: string;- currency: string;- exchange: string;- employees: number | null;- current_price: number | null;- target_high_price: number | null;- target_low_price: number | null;- target_mean_price: number | null;- recommendation_mean: number | null;- recommendation_key: string | null;- number_of_analyst_opinions: number | null;- total_cash: number | null;- total_debt: number | null;- total_revenue: number | null;- revenue_per_share: number | null;- return_on_assets: number | null;- return_on_equity: number | null;- gross_profits: number | null;- free_cashflow: number | null;- operating_cashflow: number | null;- earnings_growth: number | null;- revenue_growth: number | null;- gross_margins: number | null;- operating_margins: number | null;- ebitda_margins: number | null;- profit_margins: number | null;- book_value: number | null;- price_to_book: number | null;- enterprise_value: number | null;- enterprise_to_revenue: number | null;- enterprise_to_ebitda: number | null;- shares_outstanding: number | null;- float_shares: number | null;- held_percent_insiders: number | null;- held_percent_institutions: number | null;- short_ratio: number | null;- short_percent_of_float: number | null;- peg_ratio: number | null;-}--interface HistoricalData {- symbol: string;- timestamp: number;- open: number;- high: number;- low: number;- close: number;- volume: number;-}--interface QuoteData {- symbol: string;- price: number;- change: number;- change_percent: number;- volume: number | null;- high: number | null;- low: number | null;- open: number | null;- previous_close: number | null;-}--interface FinancialsData {- symbol: string;- income_statement: Record<string, Record<string, number>>;- balance_sheet: Record<string, Record<string, number>>;- cash_flow: Record<string, Record<string, number>>;- timestamp: number;-}--// Lightweight Indicator Box Component with Parameter Controls-const IndicatorBox: React.FC<{- name: string;- latestValue: number;- min: number;- max: number;- avg: number;- values: number[];- priceData: any[];- color: string;- category: string;- onRecompute?: (params: any) => void;-}> = ({ name, latestValue, min, max, avg, values, priceData, color, category, onRecompute }) => {- const [showSettings, setShowSettings] = useState(false);- const [customThresholds, setCustomThresholds] = useState<{ upper: number; lower: number } | null>(null);- const [customParams, setCustomParams] = useState<any>(null);-- const formatValue = (val: number) => {- if (Math.abs(val) < 0.01) return val.toFixed(6);- if (Math.abs(val) < 1) return val.toFixed(4);- if (Math.abs(val) < 100) return val.toFixed(2);- return val.toFixed(0);- };-- // Only create indicator chart data (no price data for performance)- const chartData = values.map((value, i) => ({- index: i,- value: value || null,- }));-- // Get default parameters for this indicator- const getDefaultParams = (): any => {- const nameUpper = name.toUpperCase();-- // Moving Averages- if (nameUpper.includes('SMA_5')) return { period: 5 };- if (nameUpper.includes('SMA_10')) return { period: 10 };- if (nameUpper.includes('SMA_20')) return { period: 20 };- if (nameUpper.includes('SMA_50')) return { period: 50 };- if (nameUpper.includes('SMA_200')) return { period: 200 };- if (nameUpper.includes('EMA_9')) return { period: 9 };- if (nameUpper.includes('EMA_12')) return { period: 12 };- if (nameUpper.includes('EMA_21')) return { period: 21 };- if (nameUpper.includes('EMA_26')) return { period: 26 };- if (nameUpper.includes('EMA_50')) return { period: 50 };- if (nameUpper.includes('WMA')) return { period: 9 };-- // RSI- if (nameUpper.includes('RSI')) return { period: 14 };-- // MACD- if (nameUpper.includes('MACD')) return { fast: 12, slow: 26, signal: 9 };-- // Stochastic- if (nameUpper.includes('STOCH')) return { k_period: 14, d_period: 3 };-- // Bollinger Bands- if (nameUpper.includes('BB_')) return { period: 20, std: 2 };-- // ATR- if (nameUpper.includes('ATR')) return { period: 14 };-- // ADX- if (nameUpper.includes('ADX')) return { period: 14 };-- // CCI- if (nameUpper.includes('CCI')) return { period: 20 };-- // Williams %R- if (nameUpper.includes('WILLIAMS')) return { period: 14 };-- // ROC- if (nameUpper.includes('ROC')) return { period: 12 };-- // MFI- if (nameUpper === 'MFI') return { period: 14 };-- // Aroon- if (nameUpper.includes('AROON')) return { period: 25 };-- // Awesome Oscillator- if (nameUpper.includes('AWESOME') || nameUpper === 'AO') return { fast: 5, slow: 34 };-- // TSI- if (nameUpper === 'TSI') return { long: 25, short: 13 };-- // Ultimate Oscillator- if (nameUpper === 'UO' || nameUpper.includes('ULTIMATE')) return { period1: 7, period2: 14, period3: 28 };-- return null;- };-- // Get default thresholds for this indicator- const getDefaultThresholds = (): { upper: number; lower: number; label: string } => {- const nameUpper = name.toUpperCase();-- if (nameUpper.includes('RSI')) return { upper: 70, lower: 30, label: 'Overbought/Oversold' };- if (nameUpper.includes('STOCH')) return { upper: 80, lower: 20, label: 'Overbought/Oversold' };- if (nameUpper.includes('WILLIAMS')) return { upper: -20, lower: -80, label: 'Overbought/Oversold' };- if (nameUpper.includes('CCI')) return { upper: 100, lower: -100, label: 'Overbought/Oversold' };- if (nameUpper === 'TSI') return { upper: 25, lower: -25, label: 'Overbought/Oversold' };- if (nameUpper === 'UO' || nameUpper.includes('ULTIMATE')) return { upper: 70, lower: 30, label: 'Overbought/Oversold' };- if (nameUpper === 'MFI') return { upper: 80, lower: 20, label: 'Overbought/Oversold' };- if (nameUpper.includes('ROC')) return { upper: 5, lower: -5, label: 'Strength %' };- if (nameUpper.includes('ADX') && !nameUpper.includes('POS') && !nameUpper.includes('NEG')) return { upper: 25, lower: 20, label: 'Trend Strength' };- if (nameUpper.includes('AROON')) return { upper: 70, lower: 30, label: 'Trend Strength' };- if (nameUpper.includes('BB_PBAND') || nameUpper.includes('KC_PBAND') || nameUpper.includes('DC_PBAND')) return { upper: 0.8, lower: 0.2, label: 'Band Position' };- if (nameUpper.includes('CMF')) return { upper: 0.1, lower: -0.1, label: 'Money Flow' };-- return { upper: 0, lower: 0, label: 'Custom' };- };-- const defaultThresholds = getDefaultThresholds();- const activeThresholds = customThresholds || defaultThresholds;- const defaultParams = getDefaultParams();- const activeParams = customParams || defaultParams;-- // Comprehensive signal detection for ALL 80+ indicators- const getSignal = (): { signal: 'BUY' | 'SELL' | 'NEUTRAL'; reason: string } => {- const nameUpper = name.toUpperCase();- const prevValue = values[values.length - 2] || 0;-- // === MOMENTUM INDICATORS ===- if (nameUpper.includes('RSI')) {- if (latestValue <= activeThresholds.lower) return { signal: 'BUY', reason: `Oversold <${activeThresholds.lower}` };- if (latestValue >= activeThresholds.upper) return { signal: 'SELL', reason: `Overbought >${activeThresholds.upper}` };- return { signal: 'NEUTRAL', reason: `${activeThresholds.lower}-${activeThresholds.upper} range` };- }-- if (nameUpper.includes('STOCH') && !nameUpper.includes('RSI')) {- if (latestValue <= activeThresholds.lower) return { signal: 'BUY', reason: `Oversold <${activeThresholds.lower}` };- if (latestValue >= activeThresholds.upper) return { signal: 'SELL', reason: `Overbought >${activeThresholds.upper}` };- return { signal: 'NEUTRAL', reason: `${activeThresholds.lower}-${activeThresholds.upper} range` };- }-- if (nameUpper.includes('WILLIAMS')) {- if (latestValue <= -80) return { signal: 'BUY', reason: 'Oversold' };- if (latestValue >= -20) return { signal: 'SELL', reason: 'Overbought' };- return { signal: 'NEUTRAL', reason: '-20 to -80' };- }-- if (nameUpper === 'AO' || nameUpper.includes('AWESOME')) {- if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };- if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };- return { signal: 'NEUTRAL', reason: 'No crossover' };- }-- if (nameUpper.includes('ROC')) {- if (latestValue > 5) return { signal: 'BUY', reason: 'Strong >5%' };- if (latestValue < -5) return { signal: 'SELL', reason: 'Weak <-5%' };- return { signal: 'NEUTRAL', reason: '-5% to 5%' };- }-- if (nameUpper === 'TSI') {- if (latestValue < -25) return { signal: 'BUY', reason: 'Oversold' };- if (latestValue > 25) return { signal: 'SELL', reason: 'Overbought' };- return { signal: 'NEUTRAL', reason: '-25 to 25' };- }-- if (nameUpper === 'UO' || nameUpper.includes('ULTIMATE')) {- if (latestValue < 30) return { signal: 'BUY', reason: 'Oversold <30' };- if (latestValue > 70) return { signal: 'SELL', reason: 'Overbought >70' };- return { signal: 'NEUTRAL', reason: '30-70 range' };- }-- if (nameUpper.includes('PPO') && !nameUpper.includes('SIGNAL') && !nameUpper.includes('HIST')) {- if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };- if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };- return { signal: 'NEUTRAL', reason: 'No crossover' };- }-- // === TREND INDICATORS ===- if (nameUpper.includes('MACD') && !nameUpper.includes('SIGNAL') && !nameUpper.includes('DIFF')) {- if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Bullish crossover' };- if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Bearish crossover' };- return { signal: 'NEUTRAL', reason: 'No crossover' };- }-- if (nameUpper.includes('CCI')) {- if (latestValue <= -100) return { signal: 'BUY', reason: 'Oversold <-100' };- if (latestValue >= 100) return { signal: 'SELL', reason: 'Overbought >100' };- return { signal: 'NEUTRAL', reason: '-100 to 100' };- }-- if (nameUpper.includes('ADX') && !nameUpper.includes('POS') && !nameUpper.includes('NEG')) {- if (latestValue > 25) return { signal: 'BUY', reason: 'Strong trend >25' };- if (latestValue < 20) return { signal: 'NEUTRAL', reason: 'Weak trend <20' };- return { signal: 'NEUTRAL', reason: 'Moderate 20-25' };- }-- if (nameUpper.includes('AROON_UP')) {- if (latestValue > 70) return { signal: 'BUY', reason: 'Strong uptrend' };- return { signal: 'NEUTRAL', reason: 'Weak uptrend' };- }-- if (nameUpper.includes('AROON_DOWN')) {- if (latestValue > 70) return { signal: 'SELL', reason: 'Strong downtrend' };- return { signal: 'NEUTRAL', reason: 'Weak downtrend' };- }-- if (nameUpper.includes('AROON_INDICATOR')) {- if (latestValue > 50) return { signal: 'BUY', reason: 'Bullish' };- if (latestValue < -50) return { signal: 'SELL', reason: 'Bearish' };- return { signal: 'NEUTRAL', reason: '-50 to 50' };- }-- if (nameUpper.includes('PSAR_UP_INDICATOR')) {- if (latestValue === 1) return { signal: 'BUY', reason: 'Uptrend active' };- return { signal: 'NEUTRAL', reason: 'No uptrend' };- }-- if (nameUpper.includes('PSAR_DOWN_INDICATOR')) {- if (latestValue === 1) return { signal: 'SELL', reason: 'Downtrend active' };- return { signal: 'NEUTRAL', reason: 'No downtrend' };- }-- if (nameUpper.includes('TRIX')) {- if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };- if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };- return { signal: 'NEUTRAL', reason: 'No crossover' };- }-- if (nameUpper.includes('KST') && !nameUpper.includes('SIGNAL')) {- if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };- if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };- return { signal: 'NEUTRAL', reason: 'No crossover' };- }-- if (nameUpper.includes('VORTEX_POS')) {- if (latestValue > 1) return { signal: 'BUY', reason: 'Positive >1' };- return { signal: 'NEUTRAL', reason: 'Weak' };- }-- if (nameUpper.includes('VORTEX_NEG')) {- if (latestValue > 1) return { signal: 'SELL', reason: 'Negative >1' };- return { signal: 'NEUTRAL', reason: 'Weak' };- }-- // === VOLATILITY INDICATORS ===- if (nameUpper.includes('BB_PBAND') || nameUpper.includes('KC_PBAND') || nameUpper.includes('DC_PBAND')) {- if (latestValue < 0.2) return { signal: 'BUY', reason: 'Near lower band' };- if (latestValue > 0.8) return { signal: 'SELL', reason: 'Near upper band' };- return { signal: 'NEUTRAL', reason: 'Middle band' };- }-- if (nameUpper.includes('BB_HBAND_INDICATOR')) {- if (latestValue === 1) return { signal: 'SELL', reason: 'Above upper BB' };- return { signal: 'NEUTRAL', reason: 'Below upper BB' };- }-- if (nameUpper.includes('BB_LBAND_INDICATOR')) {- if (latestValue === 1) return { signal: 'BUY', reason: 'Below lower BB' };- return { signal: 'NEUTRAL', reason: 'Above lower BB' };- }-- if (nameUpper.includes('ATR')) {- if (latestValue > avg * 1.5) return { signal: 'NEUTRAL', reason: 'High volatility' };- if (latestValue < avg * 0.5) return { signal: 'NEUTRAL', reason: 'Low volatility' };- return { signal: 'NEUTRAL', reason: 'Normal volatility' };- }-- if (nameUpper.includes('UI') || nameUpper.includes('ULCER')) {- if (latestValue > avg * 1.5) return { signal: 'SELL', reason: 'High risk' };- return { signal: 'NEUTRAL', reason: 'Normal risk' };- }-- // === VOLUME INDICATORS ===- if (nameUpper === 'MFI') {- if (latestValue <= 20) return { signal: 'BUY', reason: 'Oversold <20' };- if (latestValue >= 80) return { signal: 'SELL', reason: 'Overbought >80' };- return { signal: 'NEUTRAL', reason: '20-80 range' };- }-- if (nameUpper.includes('CMF')) {- if (latestValue > 0.1) return { signal: 'BUY', reason: 'Positive flow' };- if (latestValue < -0.1) return { signal: 'SELL', reason: 'Negative flow' };- return { signal: 'NEUTRAL', reason: 'Neutral flow' };- }-- if (nameUpper === 'OBV' || nameUpper.includes('ADI') || nameUpper.includes('VPT')) {- if (latestValue > prevValue) return { signal: 'BUY', reason: 'Volume rising' };- if (latestValue < prevValue) return { signal: 'SELL', reason: 'Volume falling' };- return { signal: 'NEUTRAL', reason: 'Volume stable' };- }-- if (nameUpper.includes('EOM')) {- if (latestValue > 0) return { signal: 'BUY', reason: 'Ease of movement +' };- if (latestValue < 0) return { signal: 'SELL', reason: 'Ease of movement -' };- return { signal: 'NEUTRAL', reason: 'No movement' };- }-- if (nameUpper.includes('FI') && !nameUpper.includes('MFI')) {- if (latestValue > 0) return { signal: 'BUY', reason: 'Force positive' };- if (latestValue < 0) return { signal: 'SELL', reason: 'Force negative' };- return { signal: 'NEUTRAL', reason: 'No force' };- }-- // === OTHERS (RETURNS) ===- if (nameUpper.includes('RETURN')) {- if (latestValue > 2) return { signal: 'BUY', reason: 'Positive return' };- if (latestValue < -2) return { signal: 'SELL', reason: 'Negative return' };- return { signal: 'NEUTRAL', reason: 'Flat return' };- }-- // Default for moving averages and others- if (nameUpper.includes('SMA') || nameUpper.includes('EMA') || nameUpper.includes('WMA')) {- return { signal: 'NEUTRAL', reason: 'Compare to price' };- }-- return { signal: 'NEUTRAL', reason: 'Monitor indicator' };- };-- const { signal, reason } = getSignal();- const signalColor = signal === 'BUY' ? COLORS.GREEN : signal === 'SELL' ? COLORS.RED : COLORS.GRAY;-- return (- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- borderLeft: `3px solid ${color}`,- borderRadius: '6px',- padding: '12px',- display: 'flex',- flexDirection: 'column',- gap: '8px',- minHeight: showSettings ? '480px' : '320px',- height: 'auto',- boxShadow: '0 1px 3px rgba(0, 0, 0, 0.3)',- transition: 'all 0.2s ease',- }}- onMouseEnter={(e) => {- e.currentTarget.style.borderColor = color;- e.currentTarget.style.boxShadow = `0 4px 12px rgba(0, 0, 0, 0.5)`;- }}- onMouseLeave={(e) => {- e.currentTarget.style.borderColor = COLORS.BORDER;- e.currentTarget.style.boxShadow = '0 1px 3px rgba(0, 0, 0, 0.3)';- }}- >- {/* Header */}- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>- <div>- <div style={{ color: color, fontSize: '10px', fontWeight: 'bold', marginBottom: '2px' }}>- {category}- </div>- <div style={{ color: COLORS.WHITE, fontSize: '11px', fontWeight: 'bold' }}>- {name.toUpperCase().replace(/_/g, ' ')}- </div>- </div>- <div style={{ textAlign: 'right' }}>- <div style={{ color: COLORS.WHITE, fontSize: '16px', fontWeight: 'bold' }}>- {formatValue(latestValue)}- </div>- <div style={{ color: COLORS.GRAY, fontSize: '9px' }}>- Current- </div>- </div>- </div>-- {/* Lightweight Chart - ONLY indicator line */}- <div style={{ width: '100%', height: '80px', flex: '0 0 auto' }}>- <ResponsiveContainer width="100%" height="100%">- <LineChart data={chartData} margin={{ top: 5, right: 5, left: 5, bottom: 5 }}>- <CartesianGrid strokeDasharray="3 3" stroke={COLORS.BORDER} opacity={0.3} />- <XAxis dataKey="index" hide />- <YAxis domain={['auto', 'auto']} hide />- <Tooltip- contentStyle={{- backgroundColor: COLORS.DARK_BG,- border: `1px solid ${COLORS.BORDER}`,- borderRadius: '4px',- fontSize: '10px',- }}- formatter={(value: any) => formatValue(value)}- />- <Line- type="monotone"- dataKey="value"- stroke={color}- strokeWidth={2}- dot={false}- connectNulls- isAnimationActive={false}- />- </LineChart>- </ResponsiveContainer>- </div>-- {/* Signal Badge */}- <div style={{- display: 'flex',- justifyContent: 'center',- alignItems: 'center',- gap: '8px',- padding: '4px',- backgroundColor: `${signalColor}15`,- border: `1px solid ${signalColor}`,- borderRadius: '4px',- }}>- <span style={{ color: signalColor, fontSize: '11px', fontWeight: 'bold' }}>- {signal}- </span>- <span style={{ color: COLORS.GRAY, fontSize: '9px' }}>- {reason}- </span>- </div>-- {/* Settings Toggle & Parameters */}- <div style={{ flex: '0 0 auto' }}>- <button- onClick={() => setShowSettings(!showSettings)}- style={{- fontSize: '9px',- fontWeight: '500',- textAlign: 'center',- padding: '4px 8px',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- gap: '4px',- width: '100%',- userSelect: 'none',- backgroundColor: showSettings ? COLORS.DARK_BG : COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- borderRadius: '3px',- color: COLORS.GRAY,- transition: 'all 0.15s ease',- }}- onMouseEnter={(e) => {- e.currentTarget.style.borderColor = COLORS.ORANGE;- e.currentTarget.style.color = COLORS.ORANGE;- }}- onMouseLeave={(e) => {- e.currentTarget.style.borderColor = COLORS.BORDER;- e.currentTarget.style.color = COLORS.GRAY;- }}- >- <span style={{ fontSize: '10px' }}></span>- <span>{showSettings ? 'Hide' : 'Adjust'}</span>- </button>-- {showSettings && (- <div style={{- backgroundColor: COLORS.DARK_BG,- border: `1px solid ${COLORS.BORDER}`,- borderRadius: '4px',- padding: '10px',- marginTop: '8px',- fontSize: '10px',- }}>- {/* Indicator Parameters Section */}- {defaultParams && (- <div style={{ marginBottom: defaultThresholds.upper !== 0 ? '12px' : '0' }}>- <div style={{ color: COLORS.CYAN, fontWeight: 'bold', marginBottom: '8px', fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>- <span>📊</span>- <span>Indicator Parameters</span>- </div>-- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(100px, 1fr))', gap: '8px', marginBottom: '8px' }}>- {Object.keys(defaultParams).map((key) => (- <div key={key}>- <label style={{ color: COLORS.GRAY, display: 'block', marginBottom: '3px', fontSize: '9px', textTransform: 'capitalize' }}>- {key.replace(/_/g, ' ')}- </label>- <input- type="number"- step="1"- value={customParams?.[key] ?? defaultParams[key]}- onChange={(e) => setCustomParams({- ...defaultParams,- ...customParams,- [key]: parseInt(e.target.value) || 1- })}- style={{- width: '100%',- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- borderRadius: '3px',- color: COLORS.WHITE,- padding: '4px 6px',- fontSize: '10px',- }}- />- </div>- ))}- </div>-- {customParams && (- <button- onClick={() => {- // Call recompute with new parameters- if (onRecompute) {- onRecompute({ indicator: name, params: customParams });- }- }}- style={{- width: '100%',- backgroundColor: COLORS.CYAN,- border: 'none',- borderRadius: '3px',- color: COLORS.DARK_BG,- padding: '6px',- fontSize: '10px',- cursor: 'pointer',- fontWeight: 'bold',- marginBottom: '6px',- }}- >- 🔄 Recompute with New Parameters- </button>- )}- </div>- )}-- {/* Signal Thresholds Section */}- {defaultThresholds.upper !== 0 && (- <div>- <div style={{ color: COLORS.ORANGE, fontWeight: 'bold', marginBottom: '8px', fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>- <span>🎯</span>- <span>{defaultThresholds.label}</span>- </div>-- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '8px' }}>- <div>- <label style={{ color: COLORS.GRAY, display: 'block', marginBottom: '3px', fontSize: '9px' }}>- Upper Threshold- </label>- <input- type="number"- step="0.1"- value={customThresholds?.upper ?? defaultThresholds.upper}- onChange={(e) => setCustomThresholds({- upper: parseFloat(e.target.value),- lower: customThresholds?.lower ?? defaultThresholds.lower- })}- style={{- width: '100%',- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- borderRadius: '3px',- color: COLORS.WHITE,- padding: '4px 6px',- fontSize: '10px',- }}- />- </div>-- <div>- <label style={{ color: COLORS.GRAY, display: 'block', marginBottom: '3px', fontSize: '9px' }}>- Lower Threshold- </label>- <input- type="number"- step="0.1"- value={customThresholds?.lower ?? defaultThresholds.lower}- onChange={(e) => setCustomThresholds({- upper: customThresholds?.upper ?? defaultThresholds.upper,- lower: parseFloat(e.target.value)- })}- style={{- width: '100%',- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- borderRadius: '3px',- color: COLORS.WHITE,- padding: '4px 6px',- fontSize: '10px',- }}- />- </div>- </div>- </div>- )}-- {/* Reset Button */}- <button- onClick={() => {- setCustomThresholds(null);- setCustomParams(null);- }}- style={{- width: '100%',- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- borderRadius: '3px',- color: COLORS.GRAY,- padding: '5px',- fontSize: '9px',- cursor: 'pointer',- fontWeight: '600',- }}- >- Reset All to Defaults- </button>- </div>- )}- </div>-- {/* Stats */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px', fontSize: '9px' }}>- <div>- <div style={{ color: COLORS.GRAY }}>MIN</div>- <div style={{ color: COLORS.RED, fontWeight: 'bold' }}>{formatValue(min)}</div>- </div>- <div>- <div style={{ color: COLORS.GRAY }}>AVG</div>- <div style={{ color: COLORS.YELLOW, fontWeight: 'bold' }}>{formatValue(avg)}</div>- </div>- <div>- <div style={{ color: COLORS.GRAY }}>MAX</div>- <div style={{ color: COLORS.GREEN, fontWeight: 'bold' }}>{formatValue(max)}</div>- </div>- </div>-- {/* Data Points Count */}- <div style={{ color: COLORS.GRAY, fontSize: '9px', textAlign: 'center', borderTop: `1px solid ${COLORS.BORDER}`, paddingTop: '4px' }}>- {values.length} data points- </div>- </div>- );-};--const EquityResearchTab: React.FC = () => {- const { colors, fontSize: themeFontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();- const { t } = useTranslation('equityResearch');- const [searchSymbol, setSearchSymbol] = useState('');- const [currentSymbol, setCurrentSymbol] = useState('AAPL');- const [stockInfo, setStockInfo] = useState<StockInfo | null>(null);- const [quoteData, setQuoteData] = useState<QuoteData | null>(null);- const [historicalData, setHistoricalData] = useState<HistoricalData[]>([]);- const [financials, setFinancials] = useState<FinancialsData | null>(null);- 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' | 'technicals' | 'peers' | '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);-- // 3 Chart Metrics Selection- const [chart1Metrics, setChart1Metrics] = useState<string[]>(['Total Revenue', 'Gross Profit']);- 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);-- // Symbol Search State- const [searchResults, setSearchResults] = useState<Array<{ symbol: string; name: string; type: string }>>([]);- const [showSearchDropdown, setShowSearchDropdown] = useState(false);- const [searchLoading, setSearchLoading] = useState(false);- const searchDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const searchContainerRef = useRef<HTMLDivElement>(null);-- const chartContainerRef = useRef<HTMLDivElement>(null);- const chartRef = useRef<any>(null);- const candlestickSeriesRef = useRef<any>(null);- const volumeSeriesRef = useRef<any>(null);-- const financialChart1Ref = useRef<HTMLDivElement>(null);- const financialChart2Ref = useRef<HTMLDivElement>(null);- const financialChart3Ref = useRef<HTMLDivElement>(null);- const financialChart1InstanceRef = useRef<any>(null);- const financialChart2InstanceRef = useRef<any>(null);- const financialChart3InstanceRef = useRef<any>(null);-- // Data Cache: { symbol: { info, quote, historical: { period: data }, financials, timestamp } }- const dataCache = useRef<Record<string, {- stockInfo: StockInfo;- quoteData: QuoteData;- historicalData: Record<string, HistoricalData[]>;- financials: FinancialsData;- timestamp: number;- }>>({});-- useEffect(() => {- const timer = setInterval(() => setCurrentTime(new Date()), 1000);- return () => clearInterval(timer);- }, []);-- // HTTP Symbol Search function- const searchSymbolsHttp = async (query: string) => {- try {- const response = await fetch(`https://finceptbackend.share.zrok.io/search/symbols?query=${encodeURIComponent(query)}&limit=50`);- if (response.ok) {- const data = await response.json();- console.log('[Search] HTTP results:', data);- setSearchResults(data.results || []);- setSearchLoading(false);- if (data.results?.length > 0) {- setShowSearchDropdown(true);- }- } else {- console.error('[Search] HTTP error:', response.status);- setSearchLoading(false);- }- } catch (e) {- console.error('[Search] HTTP fetch error:', e);- setSearchLoading(false);- }- };-- // Cleanup debounce on unmount- useEffect(() => {- return () => {- if (searchDebounceRef.current) {- clearTimeout(searchDebounceRef.current);- }- };- }, []);-- // Debounced search function (non-blocking)- const handleSearchInput = (query: string) => {- if (searchDebounceRef.current) {- clearTimeout(searchDebounceRef.current);- }-- if (query.length < 2) {- setSearchResults([]);- setShowSearchDropdown(false);- setSearchLoading(false);- return;- }-- setSearchLoading(true);-- searchDebounceRef.current = setTimeout(() => {- searchSymbolsHttp(query);- }, 300);- };-- // Handle symbol selection from dropdown- const handleSelectSymbol = (symbol: string) => {- setSearchSymbol(symbol);- setCurrentSymbol(symbol);- setShowSearchDropdown(false);- setSearchResults([]);- };-- // Close dropdown when clicking outside- useEffect(() => {- const handleClickOutside = (e: MouseEvent) => {- if (searchContainerRef.current && !searchContainerRef.current.contains(e.target as Node)) {- setShowSearchDropdown(false);- }- };- document.addEventListener('mousedown', handleClickOutside);- return () => document.removeEventListener('mousedown', handleClickOutside);- }, []);-- const fetchStockData = async (symbol: string, forceRefresh = false) => {- setLoading(true);- console.log('Fetching data for:', symbol, '| Force refresh:', forceRefresh);-- try {- // Check cache first- const cached = dataCache.current[symbol];- const now = Date.now();- const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes-- if (cached && !forceRefresh && (now - cached.timestamp < CACHE_DURATION)) {- console.log('Using cached data for', symbol);- setStockInfo(cached.stockInfo);- setQuoteData(cached.quoteData);- setFinancials(cached.financials);-- // Check if we have historical data for this period- if (cached.historicalData[chartPeriod]) {- setHistoricalData(cached.historicalData[chartPeriod]);- setLoading(false);- return;- }- }-- // Fetch fresh data- console.log('Fetching fresh data for', symbol);-- // Fetch quote- const quoteResponse: any = await invoke('get_market_quote', { symbol });- let newQuote: QuoteData | null = null;- if (quoteResponse.success && quoteResponse.data) {- setQuoteData(quoteResponse.data);- newQuote = quoteResponse.data;- }-- // Fetch stock info- const infoResponse: any = await invoke('get_stock_info', { symbol });- let newInfo: StockInfo | null = null;- if (infoResponse.success && infoResponse.data) {- setStockInfo(infoResponse.data);- newInfo = infoResponse.data;- }-- // Fetch historical data- const endDate = new Date();- const startDate = new Date();- switch (chartPeriod) {- case '1M': startDate.setMonth(endDate.getMonth() - 1); break;- case '3M': startDate.setMonth(endDate.getMonth() - 3); break;- case '6M': startDate.setMonth(endDate.getMonth() - 6); break;- case '1Y': startDate.setFullYear(endDate.getFullYear() - 1); break;- case '5Y': startDate.setFullYear(endDate.getFullYear() - 5); break;- }-- const historicalResponse: any = await invoke('get_historical_data', {- symbol,- startDate: startDate.toISOString().split('T')[0],- endDate: endDate.toISOString().split('T')[0],- });- let newHistorical: HistoricalData[] = [];- if (historicalResponse.success && historicalResponse.data) {- setHistoricalData(historicalResponse.data);- newHistorical = historicalResponse.data;- }-- // Fetch financials- const financialsResponse: any = await invoke('get_financials', { symbol });- let newFinancials: FinancialsData | null = null;- if (financialsResponse.success && financialsResponse.data) {- setFinancials(financialsResponse.data);- newFinancials = financialsResponse.data;- }-- // Update cache- if (newInfo && newQuote && newFinancials) {- dataCache.current[symbol] = {- stockInfo: newInfo,- quoteData: newQuote,- historicalData: {- ...((cached?.historicalData) || {}),- [chartPeriod]: newHistorical,- },- financials: newFinancials,- timestamp: now,- };- }- } catch (error) {- console.error('Error fetching stock data:', error);- } finally {- setLoading(false);- }- };-- // Fetch company news- const fetchNews = async () => {- if (!currentSymbol) {- console.log('No symbol selected for news fetch');- return;- }-- setNewsLoading(true);- console.log('Fetching news for:', currentSymbol);-- try {- // Use company name if available, otherwise use symbol- const query = stockInfo?.company_name || currentSymbol;-- const response: any = await invoke('fetch_company_news', {- query: query,- maxResults: 20,- period: '7d',- language: 'en',- country: 'US'- });-- console.log('News response:', response);-- if (typeof response === 'string') {- const parsed = JSON.parse(response);- setNewsData(parsed);- } else {- setNewsData(response);- }- } catch (error) {- console.error('Error fetching news:', error);- setNewsData({- success: false,- error: String(error),- data: []- });- } finally {- setNewsLoading(false);- }- };-- // OLD CHART INITIALIZATION - NOW USING ProChartWithToolkit- // ProChartWithToolkit handles all chart creation and management- /* useEffect(() => {- if (chartContainerRef.current && !chartRef.current) {- const containerHeight = chartContainerRef.current.clientHeight;- const containerWidth = chartContainerRef.current.clientWidth;-- const chart = createChart(chartContainerRef.current, {- layout: {- background: { color: COLORS.DARK_BG },- textColor: COLORS.WHITE,- },- grid: {- vertLines: { color: COLORS.BORDER },- horzLines: { color: COLORS.BORDER },- },- width: containerWidth,- height: containerHeight > 0 ? containerHeight : 300,- timeScale: {- borderColor: COLORS.GRAY,- timeVisible: true,- },- rightPriceScale: {- borderColor: COLORS.GRAY,- },- });-- const candlestickSeries = chart.addSeries(CandlestickSeries, {- upColor: COLORS.GREEN,- downColor: COLORS.RED,- borderVisible: false,- wickUpColor: COLORS.GREEN,- wickDownColor: COLORS.RED,- });-- const volumeSeries = chart.addSeries(HistogramSeries, {- color: COLORS.BLUE,- priceFormat: {- type: 'volume',- },- priceScaleId: '',- });-- volumeSeries.priceScale().applyOptions({- scaleMargins: {- top: 0.8,- bottom: 0,- },- });-- chartRef.current = chart;- candlestickSeriesRef.current = candlestickSeries;- volumeSeriesRef.current = volumeSeries;-- const handleResize = () => {- if (chartContainerRef.current && chartRef.current) {- const newHeight = chartContainerRef.current.clientHeight;- const newWidth = chartContainerRef.current.clientWidth;- chartRef.current.applyOptions({- width: newWidth,- height: newHeight > 0 ? newHeight : 300,- });- }- };-- const resizeObserver = new ResizeObserver(handleResize);- if (chartContainerRef.current) {- resizeObserver.observe(chartContainerRef.current);- }-- window.addEventListener('resize', handleResize);- return () => {- window.removeEventListener('resize', handleResize);- resizeObserver.disconnect();- chart.remove();- chartRef.current = null;- candlestickSeriesRef.current = null;- volumeSeriesRef.current = null;- };- }- }, []); */-- // OLD CHART DATA UPDATE - NOW HANDLED BY ProChartWithToolkit- // Data is passed directly to ProChartWithToolkit component via props- /* useEffect(() => {- if (candlestickSeriesRef.current && volumeSeriesRef.current && historicalData.length > 0) {- const chartData = historicalData.map((d) => ({- time: Math.floor(d.timestamp) as any,- open: d.open,- high: d.high,- low: d.low,- close: d.close,- })).sort((a, b) => a.time - b.time);-- const volumeData = historicalData.map((d) => ({- time: Math.floor(d.timestamp) as any,- value: d.volume,- color: d.close >= d.open ? COLORS.GREEN + '80' : COLORS.RED + '80',- })).sort((a, b) => a.time - b.time);-- candlestickSeriesRef.current.setData(chartData);- volumeSeriesRef.current.setData(volumeData);-- if (chartRef.current) {- chartRef.current.timeScale().fitContent();- }- }- }, [historicalData]); */-- // Helper function to create a financial chart with dynamic metrics- const createFinancialChart = (- container: HTMLDivElement | null,- metrics: string[],- colors: string[]- ) => {- if (!container || !financials) return null;-- const chart = createChart(container, {- layout: {- background: { color: COLORS.DARK_BG },- textColor: COLORS.WHITE,- },- grid: {- vertLines: { color: COLORS.BORDER },- horzLines: { color: COLORS.BORDER },- },- width: container.clientWidth,- height: 250,- timeScale: {- borderColor: COLORS.GRAY,- timeVisible: true,- },- rightPriceScale: {- borderColor: COLORS.GRAY,- },- });-- const periods = Object.keys(financials.income_statement);- const seriesArray: any[] = [];-- metrics.forEach((metric, idx) => {- const color = colors[idx % colors.length];- const series = chart.addSeries(LineSeries, {- color,- lineWidth: 2,- title: metric,- });-- const data: any[] = [];- periods.forEach((period) => {- const timestamp = new Date(period).getTime() / 1000;- const statements = financials.income_statement[period];-- if (statements[metric] !== undefined && statements[metric] !== null) {- const value = metric.includes('EPS')- ? statements[metric]- : statements[metric] / 1e9; // Convert to billions- data.push({ time: timestamp, value });- }- });-- if (data.length > 0) {- series.setData(data.sort((a, b) => a.time - b.time));- }- seriesArray.push(series);- });-- chart.timeScale().fitContent();- return chart;- };-- // Update financial charts when data or metrics change- useEffect(() => {- if (activeTab === 'financials' && financials) {- // Cleanup existing charts with safety check- if (financialChart1InstanceRef.current) {- try {- financialChart1InstanceRef.current.remove();- } catch (e) {- // Chart already disposed, ignore error- }- financialChart1InstanceRef.current = null;- }- if (financialChart2InstanceRef.current) {- try {- financialChart2InstanceRef.current.remove();- } catch (e) {- // Chart already disposed, ignore error- }- financialChart2InstanceRef.current = null;- }- if (financialChart3InstanceRef.current) {- try {- financialChart3InstanceRef.current.remove();- } catch (e) {- // Chart already disposed, ignore error- }- financialChart3InstanceRef.current = null;- }-- // Create new charts- const chartColors = [COLORS.GREEN, COLORS.CYAN, COLORS.ORANGE, COLORS.YELLOW, COLORS.MAGENTA, COLORS.BLUE];-- if (financialChart1Ref.current && chart1Metrics.length > 0) {- financialChart1InstanceRef.current = createFinancialChart(- financialChart1Ref.current,- chart1Metrics,- chartColors- );- }-- if (financialChart2Ref.current && chart2Metrics.length > 0) {- financialChart2InstanceRef.current = createFinancialChart(- financialChart2Ref.current,- chart2Metrics,- chartColors- );- }-- if (financialChart3Ref.current && chart3Metrics.length > 0) {- financialChart3InstanceRef.current = createFinancialChart(- financialChart3Ref.current,- chart3Metrics,- chartColors- );- }-- // Handle window resize- const handleResize = () => {- if (financialChart1Ref.current && financialChart1InstanceRef.current) {- financialChart1InstanceRef.current.applyOptions({ width: financialChart1Ref.current.clientWidth });- }- if (financialChart2Ref.current && financialChart2InstanceRef.current) {- financialChart2InstanceRef.current.applyOptions({ width: financialChart2Ref.current.clientWidth });- }- if (financialChart3Ref.current && financialChart3InstanceRef.current) {- financialChart3InstanceRef.current.applyOptions({ width: financialChart3Ref.current.clientWidth });- }- };-- window.addEventListener('resize', handleResize);- return () => {- window.removeEventListener('resize', handleResize);- // Safe cleanup with try-catch to prevent disposal errors- if (financialChart1InstanceRef.current) {- try {- financialChart1InstanceRef.current.remove();- } catch (e) {- // Chart already disposed, ignore error- }- financialChart1InstanceRef.current = null;- }- if (financialChart2InstanceRef.current) {- try {- financialChart2InstanceRef.current.remove();- } catch (e) {- // Chart already disposed, ignore error- }- financialChart2InstanceRef.current = null;- }- if (financialChart3InstanceRef.current) {- try {- financialChart3InstanceRef.current.remove();- } catch (e) {- // Chart already disposed, ignore error- }- financialChart3InstanceRef.current = null;- }- };- }- }, [financials, activeTab, chart1Metrics, chart2Metrics, chart3Metrics]);-- // Compute technicals from historical data- const computeTechnicals = async (historical: HistoricalData[]) => {- setTechnicalsLoading(true);- try {- // Validate historical data- if (!historical || !Array.isArray(historical) || historical.length === 0) {- console.error('Invalid historical data for technicals computation');- setTechnicalsData(null);- return;- }-- // 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- })));-- console.log('Sending historical data for technicals computation:', historical.length, 'data points');-- const response: any = await invoke('compute_all_technicals', {- historicalData: historicalJson- });-- console.log('Technicals response:', response);- console.log('Response type:', typeof response);- console.log('Response keys:', response ? Object.keys(response) : 'null');-- if (typeof response === 'string') {- try {- const parsed = JSON.parse(response);- if (parsed.success && parsed.data && Array.isArray(parsed.data) && parsed.data.length > 0) {- setTechnicalsData(parsed);- } else {- console.error('Error computing technicals:', parsed.error || 'Invalid data structure');- setTechnicalsData(null);- }- } catch (parseError) {- console.error('Error parsing technicals response:', parseError);- setTechnicalsData(null);- }- } else if (response && response.success && response.data && Array.isArray(response.data) && response.data.length > 0) {- setTechnicalsData(response);- } else {- console.error('Invalid technicals response structure');- setTechnicalsData(null);- }- } catch (error) {- console.error('Error computing technicals:', error);- setTechnicalsData(null);- } finally {- setTechnicalsLoading(false);- }- };-- // Load initial data- useEffect(() => {- fetchStockData(currentSymbol);- }, [currentSymbol, chartPeriod]);-- // Compute technicals when historical data changes- useEffect(() => {- if (historicalData.length > 0) {- computeTechnicals(historicalData);- }- }, [historicalData]);-- // Fetch news when news tab is activated or symbol changes- useEffect(() => {- if (activeTab === 'news' && currentSymbol) {- fetchNews();- }- }, [activeTab, currentSymbol]);-- const handleSearch = () => {- if (searchSymbol.trim()) {- setCurrentSymbol(searchSymbol.trim().toUpperCase());- setSearchSymbol('');- }- };-- const formatNumber = (num: number | null | undefined, decimals = 2) => {- if (num === null || num === undefined) return 'N/A';- return num.toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });- };-- const formatLargeNumber = (num: number | null | undefined) => {- if (num === null || num === undefined) return 'N/A';- if (num >= 1e12) return `$${(num / 1e12).toFixed(2)}T`;- if (num >= 1e9) return `$${(num / 1e9).toFixed(2)}B`;- if (num >= 1e6) return `$${(num / 1e6).toFixed(2)}M`;- return `$${num.toFixed(2)}`;- };-- const formatPercent = (num: number | null | undefined) => {- if (num === null || num === undefined) return 'N/A';- return `${(num * 100).toFixed(2)}%`;- };-- const currentPrice = quoteData?.price || stockInfo?.current_price || 0;- const priceChange = quoteData?.change || 0;- const priceChangePercent = quoteData?.change_percent || 0;-- const getRecommendationColor = (key: string | null) => {- if (!key) return COLORS.GRAY;- if (key === 'buy' || key === 'strong_buy') return COLORS.GREEN;- if (key === 'sell' || key === 'strong_sell') return COLORS.RED;- return COLORS.YELLOW;- };-- const getRecommendationText = (key: string | null) => {- if (!key) return 'N/A';- return key.toUpperCase().replace('_', ' ');- };-- // Helper function to get year from period string- const getYearFromPeriod = (period: string) => {- return new Date(period).getFullYear();- };-- // Get all available metrics from income statement- const getAllMetrics = () => {- if (!financials || Object.keys(financials.income_statement).length === 0) return [];- const firstPeriod = Object.keys(financials.income_statement)[0];- return Object.keys(financials.income_statement[firstPeriod]);- };-- const toggleMetric = (metric: string) => {- setSelectedMetrics(prev =>- prev.includes(metric)- ? prev.filter(m => m !== metric)- : [...prev, metric]- );- };-- return (- <div style={{- ...COMMON_STYLES.container,- fontFamily: TYPOGRAPHY.MONO,- }}>- {/* Fincept-Style Header */}- <div style={{- ...COMMON_STYLES.header,- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- flexWrap: 'wrap',- gap: SPACING.MEDIUM,- }}>- {/* Left Section */}- <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.LARGE, flex: 1 }}>- {/* Title with Icon */}- <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>- <TrendingUp size={16} color={COLORS.ORANGE} />- <span style={{- color: COLORS.ORANGE,- fontWeight: TYPOGRAPHY.BOLD,- fontSize: TYPOGRAPHY.SUBHEADING,- letterSpacing: TYPOGRAPHY.WIDE,- textTransform: 'uppercase',- }}>- RESEARCH- </span>- </div>-- {/* Help Button */}- <button- onClick={() => {- const tour = createEquityResearchTabTour((tab: string) => setActiveTab(tab as any));- tour.drive();- }}- style={{- backgroundColor: COLORS.BLUE,- color: COLORS.DARK_BG,- border: 'none',- padding: '4px 8px',- fontSize: '10px',- fontWeight: 'bold',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '4px',- borderRadius: '0'- }}- title="Start interactive tour"- >- <Info size={12} />- HELP- </button>-- {/* Divider */}- <div style={COMMON_STYLES.verticalDivider} />-- {/* Symbol Search */}- <div id="research-search" style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>- <div ref={searchContainerRef} style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>- <Search size={14} style={{- position: 'absolute',- left: '8px',- pointerEvents: 'none',- color: COLORS.GRAY,- zIndex: 1- }} />- {searchLoading && (- <div style={{- position: 'absolute',- right: '8px',- width: '12px',- height: '12px',- border: `2px solid ${COLORS.BORDER}`,- borderTop: `2px solid ${COLORS.ORANGE}`,- borderRadius: '50%',- animation: 'spin 0.8s linear infinite',- zIndex: 1- }} />- )}- <input- type="text"- placeholder="SYMBOL..."- style={{- ...COMMON_STYLES.inputField,- paddingLeft: '28px',- paddingRight: searchLoading ? '28px' : '8px',- width: '160px',- height: '28px',- padding: `${SPACING.SMALL} ${SPACING.SMALL} ${SPACING.SMALL} 28px`,- fontSize: TYPOGRAPHY.BODY,- textTransform: 'uppercase',- }}- onInput={(e) => {- const val = (e.target as HTMLInputElement).value;- setSearchSymbol(val);- handleSearchInput(val);- }}- onKeyDown={(e) => {- if (e.key === 'Enter') {- handleSearch();- setShowSearchDropdown(false);- }- }}- onFocus={(e) => {- e.currentTarget.style.borderColor = COLORS.ORANGE;- if (searchResults.length > 0) setShowSearchDropdown(true);- }}- onBlur={(e) => e.currentTarget.style.borderColor = COLORS.BORDER}- />- {/* Search Results Dropdown */}- {showSearchDropdown && searchResults.length > 0 && (- <div style={{- position: 'absolute',- top: '100%',- left: 0,- width: '320px',- maxHeight: '300px',- overflowY: 'auto',- backgroundColor: COLORS.PANEL_BG,- border: BORDERS.STANDARD,- borderColor: COLORS.ORANGE,- zIndex: 1000,- marginTop: '2px',- }}>- {searchResults.map((result, idx) => (- <div- key={`${result.symbol}-${idx}`}- onMouseDown={() => handleSelectSymbol(result.symbol)}- style={{- padding: `${SPACING.SMALL} ${SPACING.DEFAULT}`,- cursor: 'pointer',- borderBottom: idx < searchResults.length - 1 ? BORDERS.STANDARD : 'none',- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center',- transition: EFFECTS.TRANSITION_FAST,- }}- onMouseEnter={(e) => e.currentTarget.style.backgroundColor = COLORS.HOVER}- onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}- >- <div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>- <span style={{ color: COLORS.ORANGE, fontWeight: TYPOGRAPHY.BOLD, fontSize: TYPOGRAPHY.BODY }}>- {result.symbol}- </span>- <span style={{ color: COLORS.GRAY, fontSize: TYPOGRAPHY.SMALL, maxWidth: '220px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>- {result.name}- </span>- </div>- <span style={{- color: COLORS.CYAN,- fontSize: '9px',- textTransform: 'uppercase',- padding: '2px 6px',- backgroundColor: `${COLORS.CYAN}20`,- borderRadius: '2px',- }}>- {result.type}- </span>- </div>- ))}- </div>- )}- </div>- <button- onClick={handleSearch}- style={{- ...COMMON_STYLES.buttonPrimary,- padding: `${SPACING.SMALL} ${SPACING.DEFAULT}`,- fontSize: TYPOGRAPHY.SMALL,- display: 'flex',- alignItems: 'center',- gap: SPACING.TINY,- }}- onMouseEnter={(e) => e.currentTarget.style.opacity = '0.85'}- onMouseLeave={(e) => e.currentTarget.style.opacity = '1'}- >- <Search size={12} />- GO- </button>- <button- onClick={() => fetchStockData(currentSymbol)}- style={{- ...COMMON_STYLES.buttonSecondary,- padding: `${SPACING.SMALL} ${SPACING.MEDIUM}`,- fontSize: TYPOGRAPHY.SMALL,- display: 'flex',- alignItems: 'center',- gap: SPACING.TINY,- }}- onMouseEnter={(e) => e.currentTarget.style.backgroundColor = COLORS.HOVER}- onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}- >- <RefreshCw size={12} />- REFRESH- </button>- </div>-- {/* Divider */}- <div style={COMMON_STYLES.verticalDivider} />-- {/* Tab Navigation Buttons */}- <div id="research-tabs" style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>- {[- { id: 'overview', label: 'OVERVIEW', icon: TrendingUp },- { id: 'financials', label: 'FINANCIALS', icon: BarChart3 },- { id: 'analysis', label: 'ANALYSIS', icon: FileText },- { id: 'technicals', label: 'TECHNICALS', icon: BarChart3 },- { id: 'peers', label: 'PEERS', icon: Users },- { id: 'news', label: 'NEWS', icon: Newspaper },- ].map((tab) => {- const Icon = tab.icon;- return (- <button- key={tab.id}- onClick={() => setActiveTab(tab.id as typeof activeTab)}- style={{- padding: `${SPACING.SMALL} ${SPACING.DEFAULT}`,- backgroundColor: activeTab === tab.id ? COLORS.ORANGE : 'transparent',- border: BORDERS.STANDARD,- borderColor: activeTab === tab.id ? COLORS.ORANGE : COLORS.BORDER,- color: activeTab === tab.id ? COLORS.DARK_BG : COLORS.GRAY,- fontSize: TYPOGRAPHY.SMALL,- fontWeight: TYPOGRAPHY.BOLD,- cursor: 'pointer',- textTransform: 'uppercase',- letterSpacing: TYPOGRAPHY.NORMAL,- transition: EFFECTS.TRANSITION_FAST,- display: 'flex',- alignItems: 'center',- gap: SPACING.SMALL,- }}- onMouseEnter={(e) => {- if (activeTab !== tab.id) {- e.currentTarget.style.backgroundColor = COLORS.HOVER;- e.currentTarget.style.borderColor = COLORS.ORANGE;- }- }}- onMouseLeave={(e) => {- if (activeTab !== tab.id) {- e.currentTarget.style.backgroundColor = 'transparent';- e.currentTarget.style.borderColor = COLORS.BORDER;- }- }}- title={tab.label}- >- <Icon size={12} />- <span>{tab.label}</span>- </button>- );- })}- </div>- </div>-- {/* Right Section - Status */}- <div style={{- display: 'flex',- alignItems: 'center',- gap: SPACING.DEFAULT,- fontSize: TYPOGRAPHY.BODY,- }}>- <span style={{ color: COLORS.GRAY, fontSize: TYPOGRAPHY.SMALL }}>- {currentTime.toLocaleTimeString()}- </span>- <div style={COMMON_STYLES.verticalDivider} />- <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.BOLD }}>- {currentSymbol}- </span>- <div style={{- display: 'flex',- alignItems: 'center',- gap: SPACING.TINY,- padding: `${SPACING.TINY} ${SPACING.SMALL}`,- backgroundColor: loading ? `${COLORS.YELLOW}15` : `${COLORS.GREEN}15`,- border: `1px solid ${loading ? COLORS.YELLOW : COLORS.GREEN}`,- }}>- <div style={{- width: '6px',- height: '6px',- borderRadius: '50%',- backgroundColor: loading ? COLORS.YELLOW : COLORS.GREEN,- animation: loading ? 'pulse 1.5s ease-in-out infinite' : 'none',- }} />- <span style={{- color: loading ? COLORS.YELLOW : COLORS.GREEN,- fontWeight: TYPOGRAPHY.BOLD,- fontSize: TYPOGRAPHY.SMALL,- }}>- {loading ? 'LOADING' : 'LIVE'}- </span>- </div>- </div>- </div>-- {/* Ticker Bar - Stock Price and Info */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- borderBottom: BORDERS.STANDARD,- padding: `${SPACING.MEDIUM} ${SPACING.DEFAULT}`,- flexShrink: 0,- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- }}>- {/* Left - Company Info */}- <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.LARGE }}>- <div>- <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.MEDIUM, marginBottom: SPACING.TINY }}>- <span style={{- color: COLORS.ORANGE,- fontSize: TYPOGRAPHY.LARGE,- fontWeight: TYPOGRAPHY.BOLD,- letterSpacing: TYPOGRAPHY.WIDE,- }}>- {currentSymbol}- </span>- <span style={{- color: COLORS.WHITE,- fontSize: TYPOGRAPHY.SUBHEADING,- fontWeight: TYPOGRAPHY.SEMIBOLD,- }}>- {stockInfo?.company_name || 'Loading...'}- </span>- {stockInfo?.sector && (- <span style={{- color: COLORS.BLUE,- fontSize: TYPOGRAPHY.SMALL,- padding: `${SPACING.TINY} ${SPACING.SMALL}`,- backgroundColor: `${COLORS.BLUE}15`,- border: `1px solid ${COLORS.BLUE}`,- fontWeight: TYPOGRAPHY.SEMIBOLD,- textTransform: 'uppercase',- letterSpacing: TYPOGRAPHY.NORMAL,- }}>- {stockInfo.sector}- </span>- )}- {stockInfo?.recommendation_key && (- <span style={{- color: getRecommendationColor(stockInfo.recommendation_key),- fontSize: TYPOGRAPHY.SMALL,- padding: `${SPACING.TINY} ${SPACING.SMALL}`,- backgroundColor: `${getRecommendationColor(stockInfo.recommendation_key)}20`,- border: `1px solid ${getRecommendationColor(stockInfo.recommendation_key)}`,- fontWeight: TYPOGRAPHY.BOLD,- textTransform: 'uppercase',- }}>- {getRecommendationText(stockInfo.recommendation_key)}- </span>- )}- </div>- <div style={{- fontSize: TYPOGRAPHY.SMALL,- color: COLORS.GRAY,- display: 'flex',- alignItems: 'center',- gap: SPACING.SMALL,- }}>- <span>{stockInfo?.exchange || 'N/A'}</span>- <span>•</span>- <span>{stockInfo?.industry || 'N/A'}</span>- <span>•</span>- <span>{stockInfo?.country || 'N/A'}</span>- </div>- </div>- </div>-- {/* Right - Price Info */}- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'flex-end',- gap: SPACING.TINY,- }}>- <div style={{- fontSize: '28px',- fontWeight: TYPOGRAPHY.BOLD,- color: COLORS.WHITE,- fontFamily: TYPOGRAPHY.MONO,- letterSpacing: TYPOGRAPHY.TIGHT,- }}>- ${formatNumber(currentPrice)}- </div>- <div style={{- fontSize: TYPOGRAPHY.SUBHEADING,- color: priceChange >= 0 ? COLORS.GREEN : COLORS.RED,- fontWeight: TYPOGRAPHY.BOLD,- display: 'flex',- alignItems: 'center',- gap: SPACING.TINY,- }}>- <span>{priceChange >= 0 ? '▲' : '▼'}</span>- <span>${Math.abs(priceChange).toFixed(2)}</span>- <span>({priceChangePercent.toFixed(2)}%)</span>- </div>- </div>- </div>-- {/* Main Content Area */}- <div style={{- flex: 1,- overflow: 'auto',- scrollbarColor: 'rgba(120, 120, 120, 0.3) transparent',- scrollbarWidth: 'thin',- minHeight: 0,- backgroundColor: COLORS.DARK_BG,- }} className="custom-scrollbar">-- {/* Overview Tab */}- {activeTab === 'overview' && (- <div id="research-overview" style={{- display: 'flex',- flexDirection: 'column',- gap: SPACING.MEDIUM,- padding: SPACING.DEFAULT,- height: '100%',- boxSizing: 'border-box',- }}>- {/* Top Data Grid - 4 Columns */}- <div style={{- display: 'grid',- gridTemplateColumns: 'repeat(4, 1fr)',- gap: SPACING.MEDIUM,- flex: '0 0 auto',- minHeight: '400px',- }}>- {/* Column 1 - Trading & Valuation */}- <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.MEDIUM }}>- {/* Today's Trading */}- <div id="overview-trading" style={{- ...COMMON_STYLES.panel,- padding: SPACING.MEDIUM,- }}>- <div style={{- ...COMMON_STYLES.sectionHeader,- fontSize: TYPOGRAPHY.BODY,- paddingBottom: SPACING.TINY,- marginBottom: SPACING.SMALL,- borderBottom: BORDERS.STANDARD,- }}>- TODAY'S TRADING- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, fontSize: TYPOGRAPHY.SMALL }}>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>OPEN</span>- <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(quoteData?.open)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>HIGH</span>- <span style={{ color: COLORS.GREEN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(quoteData?.high)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>LOW</span>- <span style={{ color: COLORS.RED, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(quoteData?.low)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>PREV CLOSE</span>- <span style={{ color: COLORS.WHITE, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(quoteData?.previous_close)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>VOLUME</span>- <span style={{ color: COLORS.YELLOW, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatNumber(quoteData?.volume || 0, 0)}</span>- </div>- </div>- </div>-- {/* Valuation Metrics */}- <div id="overview-valuation" style={{- ...COMMON_STYLES.panel,- padding: SPACING.MEDIUM,- }}>- <div style={{- color: COLORS.CYAN,- fontSize: TYPOGRAPHY.BODY,- fontWeight: TYPOGRAPHY.BOLD,- letterSpacing: TYPOGRAPHY.WIDE,- textTransform: 'uppercase',- paddingBottom: SPACING.TINY,- marginBottom: SPACING.SMALL,- borderBottom: BORDERS.STANDARD,- }}>- VALUATION- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, fontSize: TYPOGRAPHY.SMALL }}>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>MARKET CAP</span>- <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatLargeNumber(stockInfo?.market_cap)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>P/E RATIO</span>- <span style={{ color: COLORS.YELLOW, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatNumber(stockInfo?.pe_ratio)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>FWD P/E</span>- <span style={{ color: COLORS.YELLOW, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatNumber(stockInfo?.forward_pe)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>PEG RATIO</span>- <span style={{ color: COLORS.YELLOW, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatNumber(stockInfo?.peg_ratio)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>P/B RATIO</span>- <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatNumber(stockInfo?.price_to_book)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>DIV YIELD</span>- <span style={{ color: COLORS.GREEN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>- {formatPercent(stockInfo?.dividend_yield)}- </span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>BETA</span>- <span style={{ color: COLORS.WHITE, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatNumber(stockInfo?.beta)}</span>- </div>- </div>- </div>-- {/* Share Statistics */}- <div style={{- ...COMMON_STYLES.panel,- padding: SPACING.MEDIUM,- flex: 1,- }}>- <div style={{- color: COLORS.PURPLE,- fontSize: TYPOGRAPHY.BODY,- fontWeight: TYPOGRAPHY.BOLD,- letterSpacing: TYPOGRAPHY.WIDE,- textTransform: 'uppercase',- paddingBottom: SPACING.TINY,- marginBottom: SPACING.SMALL,- borderBottom: BORDERS.STANDARD,- }}>- SHARE STATS- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, fontSize: TYPOGRAPHY.SMALL }}>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>SHARES OUT</span>- <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatLargeNumber(stockInfo?.shares_outstanding)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>FLOAT</span>- <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatLargeNumber(stockInfo?.float_shares)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>INSIDERS</span>- <span style={{ color: COLORS.YELLOW, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatPercent(stockInfo?.held_percent_insiders)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>INSTITUTIONS</span>- <span style={{ color: COLORS.YELLOW, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatPercent(stockInfo?.held_percent_institutions)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>SHORT %</span>- <span style={{ color: COLORS.RED, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatPercent(stockInfo?.short_percent_of_float)}</span>- </div>- </div>- </div>- </div>-- {/* Column 2 - Price Chart */}- <div id="overview-price-chart" style={{- display: 'flex',- flexDirection: 'column',- gap: SPACING.MEDIUM,- gridColumn: 'span 2',- overflow: 'hidden',- minHeight: 0,- }}>- {/* Chart Period Selector */}- <div style={{- ...COMMON_STYLES.panel,- padding: SPACING.SMALL,- display: 'flex',- alignItems: 'center',- gap: SPACING.SMALL,- flexShrink: 0,- }}>- <span style={{- ...COMMON_STYLES.dataLabel,- marginRight: SPACING.TINY,- }}>- PERIOD- </span>- {(['1M', '3M', '6M', '1Y', '5Y'] as const).map((period) => (- <button- key={period}- onClick={() => setChartPeriod(period)}- style={{- padding: `${SPACING.TINY} ${SPACING.MEDIUM}`,- backgroundColor: chartPeriod === period ? COLORS.ORANGE : 'transparent',- border: BORDERS.STANDARD,- borderColor: chartPeriod === period ? COLORS.ORANGE : COLORS.BORDER,- color: chartPeriod === period ? COLORS.DARK_BG : COLORS.WHITE,- fontSize: TYPOGRAPHY.SMALL,- cursor: 'pointer',- fontWeight: TYPOGRAPHY.BOLD,- transition: EFFECTS.TRANSITION_FAST,- }}- onMouseEnter={(e) => {- if (chartPeriod !== period) {- e.currentTarget.style.backgroundColor = COLORS.HOVER;- e.currentTarget.style.borderColor = COLORS.ORANGE;- }- }}- onMouseLeave={(e) => {- if (chartPeriod !== period) {- e.currentTarget.style.backgroundColor = 'transparent';- e.currentTarget.style.borderColor = COLORS.BORDER;- }- }}- >- {period}- </button>- ))}- </div>-- {/* Chart with Volume - Full Trading Toolkit */}- <div style={{- ...COMMON_STYLES.panel,- padding: SPACING.NONE,- overflow: 'hidden',- flex: 1,- display: 'flex',- flexDirection: 'column',- minHeight: 0,- }}>- {historicalData && historicalData.length > 0 ? (- <ProChartWithToolkit- data={historicalData.map(h => ({- time: h.timestamp,- open: h.open,- high: h.high,- low: h.low,- close: h.close,- volume: h.volume,- }))}- symbol={`${currentSymbol} - ${chartPeriod}`}- height={400}- showVolume={true}- showToolbar={true}- onToolChange={(tool) => {- console.log('[EquityResearch] Active tool:', tool);- }}- />- ) : (- <div style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- height: '100%',- color: COLORS.GRAY,- fontSize: TYPOGRAPHY.DEFAULT,- flexDirection: 'column',- gap: SPACING.MEDIUM,- }}>- {loading ? (- <>- <div style={{- width: '40px',- height: '40px',- border: '3px solid #404040',- borderTop: '3px solid #ea580c',- borderRadius: '50%',- animation: 'spin 1s linear infinite'- }} />- <span>Loading chart data...</span>- </>- ) : (- <>- <AlertCircle size={32} color={COLORS.GRAY} />- <span>No chart data available</span>- </>- )}- </div>- )}- </div>- </div>-- {/* Column 3 - Analyst & Performance */}- <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.MEDIUM }}>- {/* Analyst Targets */}- <div id="research-analyst-ratings" style={{- ...COMMON_STYLES.panel,- padding: SPACING.MEDIUM,- }}>- <div style={{- color: COLORS.MAGENTA,- fontSize: TYPOGRAPHY.BODY,- fontWeight: TYPOGRAPHY.BOLD,- letterSpacing: TYPOGRAPHY.WIDE,- textTransform: 'uppercase',- paddingBottom: SPACING.TINY,- marginBottom: SPACING.SMALL,- borderBottom: BORDERS.STANDARD,- }}>- ANALYST TARGETS- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, fontSize: TYPOGRAPHY.SMALL }}>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>HIGH</span>- <span style={{ color: COLORS.GREEN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(stockInfo?.target_high_price)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>MEAN</span>- <span style={{ color: COLORS.YELLOW, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(stockInfo?.target_mean_price)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>LOW</span>- <span style={{ color: COLORS.RED, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(stockInfo?.target_low_price)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>ANALYSTS</span>- <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{stockInfo?.number_of_analyst_opinions || 'N/A'}</span>- </div>- </div>- </div>-- {/* 52 Week Range */}- <div style={{- ...COMMON_STYLES.panel,- padding: SPACING.MEDIUM,- }}>- <div style={{- color: COLORS.YELLOW,- fontSize: TYPOGRAPHY.BODY,- fontWeight: TYPOGRAPHY.BOLD,- letterSpacing: TYPOGRAPHY.WIDE,- textTransform: 'uppercase',- paddingBottom: SPACING.TINY,- marginBottom: SPACING.SMALL,- borderBottom: BORDERS.STANDARD,- }}>- 52 WEEK RANGE- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, fontSize: TYPOGRAPHY.SMALL }}>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>HIGH</span>- <span style={{ color: COLORS.GREEN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(stockInfo?.fifty_two_week_high)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>LOW</span>- <span style={{ color: COLORS.RED, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(stockInfo?.fifty_two_week_low)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>AVG VOL</span>- <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatNumber(stockInfo?.average_volume, 0)}</span>- </div>- </div>- </div>-- {/* Profitability */}- <div id="overview-profitability" style={{- ...COMMON_STYLES.panel,- padding: SPACING.MEDIUM,- flex: 1,- }}>- <div style={{- color: COLORS.GREEN,- fontSize: TYPOGRAPHY.BODY,- fontWeight: TYPOGRAPHY.BOLD,- letterSpacing: TYPOGRAPHY.WIDE,- textTransform: 'uppercase',- paddingBottom: SPACING.TINY,- marginBottom: SPACING.SMALL,- borderBottom: BORDERS.STANDARD,- }}>- PROFITABILITY- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, fontSize: TYPOGRAPHY.SMALL }}>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ ...COMMON_STYLES.dataLabel }}>GROSS MARGIN</span>- <span style={{ color: COLORS.GREEN }}>{formatPercent(stockInfo?.gross_margins)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: COLORS.GRAY }}>OPER. MARGIN:</span>- <span style={{ color: COLORS.GREEN }}>{formatPercent(stockInfo?.operating_margins)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: COLORS.GRAY }}>PROFIT MARGIN:</span>- <span style={{ color: COLORS.GREEN }}>{formatPercent(stockInfo?.profit_margins)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: COLORS.GRAY }}>ROA:</span>- <span style={{ color: COLORS.CYAN }}>{formatPercent(stockInfo?.return_on_assets)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: COLORS.GRAY }}>ROE:</span>- <span style={{ color: COLORS.CYAN }}>{formatPercent(stockInfo?.return_on_equity)}</span>- </div>- </div>- </div>-- {/* Growth */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '6px',- }}>- <div style={{ color: COLORS.BLUE, fontSize: '10px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '3px' }}>- GROWTH RATES- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: '9px' }}>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: COLORS.GRAY }}>REVENUE:</span>- <span style={{ color: COLORS.GREEN }}>{formatPercent(stockInfo?.revenue_growth)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: COLORS.GRAY }}>EARNINGS:</span>- <span style={{ color: COLORS.GREEN }}>{formatPercent(stockInfo?.earnings_growth)}</span>- </div>- </div>- </div>- </div>- </div>-- {/* Bottom Section - Company Overview & Key Info */}- <div style={{- display: 'grid',- gridTemplateColumns: '2fr 1fr',- gap: '6px',- flex: '0 0 auto',- minHeight: '120px',- }}>- {/* Company Description */}- {stockInfo?.description && stockInfo.description !== 'N/A' && (- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '6px',- display: 'flex',- flexDirection: 'column',- minHeight: 0,- }}>- <div style={{ color: COLORS.CYAN, fontSize: '10px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '3px', flexShrink: 0 }}>- COMPANY OVERVIEW- </div>- <div style={{- color: COLORS.WHITE,- fontSize: '9px',- lineHeight: '1.5',- overflow: 'auto',- flex: 1,- minHeight: 0,- }} className="custom-scrollbar">- {stockInfo.description}- </div>- </div>- )}-- {/* Company Info & Financial Health */}- <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>- {/* Company Info */}- {stockInfo && (- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '6px',- }}>- <div style={{ color: COLORS.WHITE, fontSize: '10px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '3px' }}>- COMPANY INFO- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '3px', fontSize: '9px' }}>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: COLORS.GRAY }}>EMPLOYEES:</span>- <span style={{ color: COLORS.CYAN }}>{formatNumber(stockInfo.employees, 0)}</span>- </div>- {stockInfo.website && stockInfo.website !== 'N/A' && (- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: COLORS.GRAY }}>WEBSITE:</span>- <span style={{ color: COLORS.BLUE, fontSize: '8px' }}>{stockInfo.website.substring(0, 25)}</span>- </div>- )}- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: COLORS.GRAY }}>CURRENCY:</span>- <span style={{ color: COLORS.CYAN }}>{stockInfo.currency || 'N/A'}</span>- </div>- </div>- </div>- )}-- {/* Key Financial Health */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '6px',- }}>- <div style={{ color: COLORS.ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '3px' }}>- FINANCIAL HEALTH- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '3px', fontSize: '9px' }}>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: COLORS.GRAY }}>CASH:</span>- <span style={{ color: COLORS.GREEN }}>{formatLargeNumber(stockInfo?.total_cash)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: COLORS.GRAY }}>DEBT:</span>- <span style={{ color: COLORS.RED }}>{formatLargeNumber(stockInfo?.total_debt)}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: COLORS.GRAY }}>FREE CF:</span>- <span style={{ color: COLORS.CYAN }}>{formatLargeNumber(stockInfo?.free_cashflow)}</span>- </div>- </div>- </div>- </div>- </div>- </div>- )}-- {/* Financials Tab */}- {activeTab === 'financials' && (- <div id="research-financials" style={{ padding: '8px' }}>- {!financials ? (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '400px',- gap: '16px',- }}>- {loading && (- <div style={{- width: '50px',- height: '50px',- border: '4px solid #404040',- borderTop: '4px solid #ea580c',- borderRadius: '50%',- animation: 'spin 1s linear infinite'- }} />- )}- <div style={{ color: COLORS.YELLOW, fontSize: '14px', fontWeight: 'bold' }}>- {loading ? ' LOADING FINANCIAL DATA...' : '[WARN]️ NO FINANCIAL DATA AVAILABLE'}- </div>- <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>- {loading ? 'Please wait while we fetch the data' : 'Financial statements are not available for this symbol'}- </div>- </div>- ) : (- <div style={{ padding: '0' }}>- {/* Controls Panel */}- <div id="financials-controls" style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '10px 12px',- marginBottom: '8px',- display: 'flex',- gap: '20px',- alignItems: 'center',- flexWrap: 'wrap',- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <span style={{ color: COLORS.GRAY, fontSize: `${fontSize}px` }}>FONT SIZE:</span>- <button- onClick={() => setFontSize(Math.max(10, fontSize - 1))}- style={{- backgroundColor: COLORS.DARK_BG,- border: `1px solid ${COLORS.BORDER}`,- color: COLORS.WHITE,- padding: '4px 8px',- fontSize: `${fontSize}px`,- cursor: 'pointer',- }}- >- -- </button>- <span style={{ color: COLORS.ORANGE, fontSize: `${fontSize}px`, fontWeight: 'bold', minWidth: '30px', textAlign: 'center' }}>{fontSize}px</span>- <button- onClick={() => setFontSize(Math.min(20, fontSize + 1))}- style={{- backgroundColor: COLORS.DARK_BG,- border: `1px solid ${COLORS.BORDER}`,- color: COLORS.WHITE,- padding: '4px 8px',- fontSize: `${fontSize}px`,- cursor: 'pointer',- }}- >- +- </button>- </div>-- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <span style={{ color: COLORS.GRAY, fontSize: `${fontSize}px` }}>SHOW YEARS:</span>- {[2, 3, 4, 5].map((count) => (- <button- key={count}- onClick={() => setShowYearsCount(count)}- style={{- backgroundColor: showYearsCount === count ? COLORS.ORANGE : COLORS.DARK_BG,- border: `1px solid ${COLORS.BORDER}`,- color: showYearsCount === count ? COLORS.DARK_BG : COLORS.WHITE,- padding: '4px 10px',- fontSize: `${fontSize - 1}px`,- cursor: 'pointer',- fontWeight: showYearsCount === count ? 'bold' : 'normal',- }}- >- {count}- </button>- ))}- </div>-- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <span style={{ color: COLORS.GRAY, fontSize: `${fontSize}px` }}>SELECT METRICS:</span>- <button- onClick={() => {- const allMetrics = getAllMetrics();- setSelectedMetrics(selectedMetrics.length === allMetrics.length ? [] : allMetrics);- }}- style={{- backgroundColor: COLORS.BLUE,- border: 'none',- color: COLORS.WHITE,- padding: '4px 10px',- fontSize: `${fontSize - 1}px`,- cursor: 'pointer',- fontWeight: 'bold',- }}- >- {selectedMetrics.length === getAllMetrics().length ? 'DESELECT ALL' : 'SELECT ALL'}- </button>- </div>- </div>-- {/* Metric Selector */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '12px',- marginBottom: '8px',- }}>- <div style={{ color: COLORS.CYAN, fontSize: `${fontSize + 2}px`, fontWeight: 'bold', marginBottom: '10px' }}>- SELECT METRICS TO COMPARE- </div>- <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>- {getAllMetrics().map((metric) => (- <button- key={metric}- onClick={() => toggleMetric(metric)}- style={{- backgroundColor: selectedMetrics.includes(metric) ? COLORS.GREEN : COLORS.DARK_BG,- border: `1px solid ${selectedMetrics.includes(metric) ? COLORS.GREEN : COLORS.BORDER}`,- color: selectedMetrics.includes(metric) ? COLORS.DARK_BG : COLORS.WHITE,- padding: '6px 12px',- fontSize: `${fontSize - 1}px`,- cursor: 'pointer',- fontWeight: selectedMetrics.includes(metric) ? 'bold' : 'normal',- borderRadius: '3px',- }}- >- {metric}- </button>- ))}- </div>- </div>-- {/* Financial Comparison Charts - 3 Charts in a Row */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '12px',- marginBottom: '8px',- }}>- <div style={{ color: COLORS.ORANGE, fontSize: `${fontSize + 3}px`, fontWeight: 'bold', marginBottom: '12px' }}>- FINANCIAL TRENDS COMPARISON (in Billions $)- </div>-- {/* Chart Controls */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px', marginBottom: '12px' }}>- {/* Chart 1 Selector */}- <div>- <div style={{ color: COLORS.CYAN, fontSize: `${fontSize}px`, fontWeight: 'bold', marginBottom: '6px' }}>- CHART 1 METRICS:- </div>- <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>- {getAllMetrics().slice(0, 8).map((metric) => (- <button- key={metric}- onClick={() => {- setChart1Metrics(prev =>- prev.includes(metric)- ? prev.filter(m => m !== metric)- : [...prev, metric]- );- }}- style={{- backgroundColor: chart1Metrics.includes(metric) ? COLORS.GREEN : COLORS.DARK_BG,- border: `1px solid ${chart1Metrics.includes(metric) ? COLORS.GREEN : COLORS.BORDER}`,- color: chart1Metrics.includes(metric) ? COLORS.DARK_BG : COLORS.WHITE,- padding: '3px 6px',- fontSize: `${fontSize - 3}px`,- cursor: 'pointer',- fontWeight: chart1Metrics.includes(metric) ? 'bold' : 'normal',- }}- >- {metric.substring(0, 15)}- </button>- ))}- </div>- </div>-- {/* Chart 2 Selector */}- <div>- <div style={{ color: COLORS.CYAN, fontSize: `${fontSize}px`, fontWeight: 'bold', marginBottom: '6px' }}>- CHART 2 METRICS:- </div>- <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>- {getAllMetrics().slice(0, 8).map((metric) => (- <button- key={metric}- onClick={() => {- setChart2Metrics(prev =>- prev.includes(metric)- ? prev.filter(m => m !== metric)- : [...prev, metric]- );- }}- style={{- backgroundColor: chart2Metrics.includes(metric) ? COLORS.ORANGE : COLORS.DARK_BG,- border: `1px solid ${chart2Metrics.includes(metric) ? COLORS.ORANGE : COLORS.BORDER}`,- color: chart2Metrics.includes(metric) ? COLORS.DARK_BG : COLORS.WHITE,- padding: '3px 6px',- fontSize: `${fontSize - 3}px`,- cursor: 'pointer',- fontWeight: chart2Metrics.includes(metric) ? 'bold' : 'normal',- }}- >- {metric.substring(0, 15)}- </button>- ))}- </div>- </div>-- {/* Chart 3 Selector */}- <div>- <div style={{ color: COLORS.CYAN, fontSize: `${fontSize}px`, fontWeight: 'bold', marginBottom: '6px' }}>- CHART 3 METRICS:- </div>- <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>- {getAllMetrics().slice(0, 8).map((metric) => (- <button- key={metric}- onClick={() => {- setChart3Metrics(prev =>- prev.includes(metric)- ? prev.filter(m => m !== metric)- : [...prev, metric]- );- }}- style={{- backgroundColor: chart3Metrics.includes(metric) ? COLORS.MAGENTA : COLORS.DARK_BG,- border: `1px solid ${chart3Metrics.includes(metric) ? COLORS.MAGENTA : COLORS.BORDER}`,- color: chart3Metrics.includes(metric) ? COLORS.DARK_BG : COLORS.WHITE,- padding: '3px 6px',- fontSize: `${fontSize - 3}px`,- cursor: 'pointer',- fontWeight: chart3Metrics.includes(metric) ? 'bold' : 'normal',- }}- >- {metric.substring(0, 15)}- </button>- ))}- </div>- </div>- </div>-- {/* 3 Charts Side by Side */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>- <div>- <div style={{ color: COLORS.GREEN, fontSize: `${fontSize}px`, fontWeight: 'bold', marginBottom: '6px', textAlign: 'center' }}>- {chart1Metrics.join(', ') || 'Select metrics'}- </div>- <div ref={financialChart1Ref} style={{ backgroundColor: COLORS.DARK_BG }} />- </div>- <div>- <div style={{ color: COLORS.ORANGE, fontSize: `${fontSize}px`, fontWeight: 'bold', marginBottom: '6px', textAlign: 'center' }}>- {chart2Metrics.join(', ') || 'Select metrics'}- </div>- <div ref={financialChart2Ref} style={{ backgroundColor: COLORS.DARK_BG }} />- </div>- <div>- <div style={{ color: COLORS.MAGENTA, fontSize: `${fontSize}px`, fontWeight: 'bold', marginBottom: '6px', textAlign: 'center' }}>- {chart3Metrics.join(', ') || 'Select metrics'}- </div>- <div ref={financialChart3Ref} style={{ backgroundColor: COLORS.DARK_BG }} />- </div>- </div>- </div>-- {/* Financial Comparison Table */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '12px',- marginBottom: '8px',- }}>- <div style={{ color: COLORS.CYAN, fontSize: `${fontSize + 3}px`, fontWeight: 'bold', marginBottom: '12px' }}>- YEAR-OVER-YEAR COMPARISON ({selectedMetrics.length} Metrics)- </div>-- {selectedMetrics.length === 0 ? (- <div style={{ color: COLORS.YELLOW, fontSize: `${fontSize + 1}px`, textAlign: 'center', padding: '20px' }}>- Please select at least one metric to compare- </div>- ) : (- <div style={{ overflowX: 'auto' }} className="custom-scrollbar">- <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: `${fontSize}px` }}>- <thead>- <tr style={{ borderBottom: `2px solid ${COLORS.BORDER}` }}>- <th style={{ textAlign: 'left', padding: '10px', color: COLORS.GRAY, fontSize: `${fontSize + 1}px` }}>METRIC</th>- {Object.keys(financials.income_statement).slice(0, showYearsCount).map((period) => (- <th key={period} style={{ textAlign: 'right', padding: '10px', color: COLORS.ORANGE, fontSize: `${fontSize + 1}px` }}>- {getYearFromPeriod(period)}- </th>- ))}- </tr>- </thead>- <tbody>- {selectedMetrics.map((metric, idx) => {- const periods = Object.keys(financials.income_statement).slice(0, showYearsCount);- return (- <tr key={metric} style={{ borderBottom: `1px solid ${COLORS.BORDER}20` }}>- <td style={{ padding: '10px', color: COLORS.WHITE, fontWeight: 'bold', fontSize: `${fontSize}px` }}>{metric}</td>- {periods.map((period) => {- const value = financials.income_statement[period][metric];- return (- <td key={period} style={{ textAlign: 'right', padding: '10px', color: COLORS.CYAN, fontSize: `${fontSize}px` }}>- {value ? (metric.includes('EPS') ? `$${formatNumber(value)}` : formatLargeNumber(value)) : 'N/A'}- </td>- );- })}- </tr>- );- })}- </tbody>- </table>- </div>- )}- </div>-- {/* Detailed Financial Statements */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>- {/* Income Statement */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '8px',- }}>- <div style={{ color: COLORS.GREEN, fontSize: `${fontSize + 2}px`, fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>- INCOME STATEMENT (Latest)- </div>- <div style={{ fontSize: `${fontSize}px`, maxHeight: '500px', overflow: 'auto' }} className="custom-scrollbar">- {Object.keys(financials.income_statement).length > 0 ? (- <>- {Object.entries(Object.values(financials.income_statement)[0] || {}).map(([metric, _], idx) => {- const latestPeriod = Object.keys(financials.income_statement)[0];- const value = financials.income_statement[latestPeriod][metric];- return (- <div key={idx} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px', paddingBottom: '6px', borderBottom: `1px solid rgba(255,255,255,0.05)` }}>- <span style={{ color: COLORS.GRAY, fontSize: `${fontSize - 1}px`, maxWidth: '60%' }}>{metric}:</span>- <span style={{ color: COLORS.CYAN, fontSize: `${fontSize}px` }}>{formatLargeNumber(value)}</span>- </div>- );- })}- </>- ) : (- <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '20px', fontSize: `${fontSize}px` }}>No data available</div>- )}- </div>- </div>-- {/* Balance Sheet */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '8px',- }}>- <div style={{ color: COLORS.YELLOW, fontSize: `${fontSize + 2}px`, fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>- BALANCE SHEET (Latest)- </div>- <div style={{ fontSize: `${fontSize}px`, maxHeight: '500px', overflow: 'auto' }} className="custom-scrollbar">- {Object.keys(financials.balance_sheet).length > 0 ? (- <>- {Object.entries(Object.values(financials.balance_sheet)[0] || {}).map(([metric, _], idx) => {- const latestPeriod = Object.keys(financials.balance_sheet)[0];- const value = financials.balance_sheet[latestPeriod][metric];- return (- <div key={idx} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px', paddingBottom: '6px', borderBottom: `1px solid rgba(255,255,255,0.05)` }}>- <span style={{ color: COLORS.GRAY, fontSize: `${fontSize - 1}px`, maxWidth: '60%' }}>{metric}:</span>- <span style={{ color: COLORS.CYAN, fontSize: `${fontSize}px` }}>{formatLargeNumber(value)}</span>- </div>- );- })}- </>- ) : (- <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '20px', fontSize: `${fontSize}px` }}>No data available</div>- )}- </div>- </div>-- {/* Cash Flow */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '8px',- }}>- <div style={{ color: COLORS.CYAN, fontSize: `${fontSize + 2}px`, fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>- CASH FLOW STATEMENT (Latest)- </div>- <div style={{ fontSize: `${fontSize}px`, maxHeight: '500px', overflow: 'auto' }} className="custom-scrollbar">- {Object.keys(financials.cash_flow).length > 0 ? (- <>- {Object.entries(Object.values(financials.cash_flow)[0] || {}).map(([metric, _], idx) => {- const latestPeriod = Object.keys(financials.cash_flow)[0];- const value = financials.cash_flow[latestPeriod][metric];- return (- <div key={idx} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px', paddingBottom: '6px', borderBottom: `1px solid rgba(255,255,255,0.05)` }}>- <span style={{ color: COLORS.GRAY, fontSize: `${fontSize - 1}px`, maxWidth: '60%' }}>{metric}:</span>- <span style={{ color: COLORS.CYAN, fontSize: `${fontSize}px` }}>{formatLargeNumber(value)}</span>- </div>- );- })}- </>- ) : (- <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '20px', fontSize: `${fontSize}px` }}>No data available</div>- )}- </div>- </div>- </div>- </div>- )}- </div>- )}-- {/* Analysis Tab */}- {activeTab === 'analysis' && (- <div id="analysis-tab-content" style={{ padding: SPACING.DEFAULT }}>- {/* Financial Analysis Panel - CFA-Compliant Analysis */}- <div id="analysis-cfa-panel" style={{ marginBottom: SPACING.MEDIUM }}>- <FinancialAnalysisPanel- ticker={currentSymbol}- companyName={stockInfo?.company_name || currentSymbol}- />- </div>-- {/* Financial Metrics Grid - 2x2 */}- <div id="analysis-metrics-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.MEDIUM }}>- {/* Financial Health */}- <div id="analysis-financial-health" style={{- ...COMMON_STYLES.panel,- padding: SPACING.LARGE,- }}>- <div style={{- ...COMMON_STYLES.sectionHeader,- fontSize: TYPOGRAPHY.SUBHEADING,- paddingBottom: SPACING.SMALL,- marginBottom: SPACING.LARGE,- borderBottom: BORDERS.ORANGE,- display: 'flex',- alignItems: 'center',- gap: SPACING.SMALL,- }}>- <div style={{- width: '4px',- height: '16px',- backgroundColor: COLORS.ORANGE,- }} />- FINANCIAL HEALTH- </div>- <div style={{- display: 'grid',- gridTemplateColumns: '1fr 1fr',- gap: SPACING.LARGE,- }}>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- TOTAL CASH- </div>- <div style={{- color: COLORS.GREEN,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatLargeNumber(stockInfo?.total_cash)}- </div>- </div>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- TOTAL DEBT- </div>- <div style={{- color: COLORS.RED,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatLargeNumber(stockInfo?.total_debt)}- </div>- </div>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- FREE CASHFLOW- </div>- <div style={{- color: COLORS.CYAN,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatLargeNumber(stockInfo?.free_cashflow)}- </div>- </div>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- OPERATING CF- </div>- <div style={{- color: COLORS.BLUE,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatLargeNumber(stockInfo?.operating_cashflow)}- </div>- </div>- </div>- </div>-- {/* Enterprise Value */}- <div style={{- ...COMMON_STYLES.panel,- padding: SPACING.LARGE,- }}>- <div style={{- color: COLORS.CYAN,- fontSize: TYPOGRAPHY.SUBHEADING,- fontWeight: TYPOGRAPHY.BOLD,- letterSpacing: TYPOGRAPHY.WIDE,- textTransform: 'uppercase',- paddingBottom: SPACING.SMALL,- marginBottom: SPACING.LARGE,- borderBottom: BORDERS.CYAN,- display: 'flex',- alignItems: 'center',- gap: SPACING.SMALL,- }}>- <div style={{- width: '4px',- height: '16px',- backgroundColor: COLORS.CYAN,- }} />- ENTERPRISE VALUE- </div>- <div style={{- display: 'grid',- gridTemplateColumns: '1fr 1fr',- gap: SPACING.LARGE,- }}>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- ENTERPRISE VALUE- </div>- <div style={{- color: COLORS.YELLOW,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatLargeNumber(stockInfo?.enterprise_value)}- </div>- </div>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- EV/REVENUE- </div>- <div style={{- color: COLORS.CYAN,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatNumber(stockInfo?.enterprise_to_revenue)}- </div>- </div>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- EV/EBITDA- </div>- <div style={{- color: COLORS.CYAN,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatNumber(stockInfo?.enterprise_to_ebitda)}- </div>- </div>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- BOOK VALUE- </div>- <div style={{- color: COLORS.WHITE,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- ${formatNumber(stockInfo?.book_value)}- </div>- </div>- </div>- </div>-- {/* Revenue & Profits */}- <div style={{- ...COMMON_STYLES.panel,- padding: SPACING.LARGE,- }}>- <div style={{- color: COLORS.GREEN,- fontSize: TYPOGRAPHY.SUBHEADING,- fontWeight: TYPOGRAPHY.BOLD,- letterSpacing: TYPOGRAPHY.WIDE,- textTransform: 'uppercase',- paddingBottom: SPACING.SMALL,- marginBottom: SPACING.LARGE,- borderBottom: BORDERS.GREEN,- display: 'flex',- alignItems: 'center',- gap: SPACING.SMALL,- }}>- <div style={{- width: '4px',- height: '16px',- backgroundColor: COLORS.GREEN,- }} />- REVENUE & PROFITS- </div>- <div style={{- display: 'grid',- gridTemplateColumns: '1fr 1fr',- gap: SPACING.LARGE,- }}>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- TOTAL REVENUE- </div>- <div style={{- color: COLORS.GREEN,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatLargeNumber(stockInfo?.total_revenue)}- </div>- </div>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- REVENUE/SHARE- </div>- <div style={{- color: COLORS.CYAN,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- ${formatNumber(stockInfo?.revenue_per_share)}- </div>- </div>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- GROSS PROFITS- </div>- <div style={{- color: COLORS.GREEN,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatLargeNumber(stockInfo?.gross_profits)}- </div>- </div>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- EBITDA MARGINS- </div>- <div style={{- color: COLORS.YELLOW,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatPercent(stockInfo?.ebitda_margins)}- </div>- </div>- </div>- </div>-- {/* Key Ratios Summary */}- <div style={{- ...COMMON_STYLES.panel,- padding: SPACING.LARGE,- }}>- <div style={{- color: COLORS.PURPLE,- fontSize: TYPOGRAPHY.SUBHEADING,- fontWeight: TYPOGRAPHY.BOLD,- letterSpacing: TYPOGRAPHY.WIDE,- textTransform: 'uppercase',- paddingBottom: SPACING.SMALL,- marginBottom: SPACING.LARGE,- borderBottom: `2px solid ${COLORS.PURPLE}`,- display: 'flex',- alignItems: 'center',- gap: SPACING.SMALL,- }}>- <div style={{- width: '4px',- height: '16px',- backgroundColor: COLORS.PURPLE,- }} />- KEY RATIOS- </div>- <div style={{- display: 'grid',- gridTemplateColumns: '1fr 1fr',- gap: SPACING.LARGE,- }}>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- P/E RATIO- </div>- <div style={{- color: COLORS.WHITE,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatNumber(stockInfo?.pe_ratio)}- </div>- </div>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- PEG RATIO- </div>- <div style={{- color: COLORS.WHITE,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatNumber(stockInfo?.peg_ratio)}- </div>- </div>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- ROE- </div>- <div style={{- color: COLORS.GREEN,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatPercent(stockInfo?.return_on_equity)}- </div>- </div>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- ROA- </div>- <div style={{- color: COLORS.GREEN,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatPercent(stockInfo?.return_on_assets)}- </div>- </div>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- BETA- </div>- <div style={{- color: COLORS.CYAN,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatNumber(stockInfo?.beta)}- </div>- </div>- <div>- <div style={{- ...COMMON_STYLES.dataLabel,- marginBottom: SPACING.TINY,- }}>- SHORT RATIO- </div>- <div style={{- color: COLORS.RED,- fontSize: TYPOGRAPHY.HEADING,- fontWeight: TYPOGRAPHY.BOLD,- fontFamily: TYPOGRAPHY.MONO,- }}>- {formatNumber(stockInfo?.short_ratio)}- </div>- </div>- </div>- </div>- </div>- </div>- )}-- {/* News Tab */}- {activeTab === 'news' && (- <div id="news-tab-content" style={{ padding: '8px', height: 'calc(100vh - 280px)', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>- {newsLoading ? (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '400px',- gap: '16px',- }}>- <div style={{- width: '50px',- height: '50px',- border: '4px solid #404040',- borderTop: '4px solid #ea580c',- borderRadius: '50%',- animation: 'spin 1s linear infinite'- }} />- <div style={{ color: COLORS.YELLOW, fontSize: '14px', fontWeight: 'bold' }}>- FETCHING LATEST NEWS...- </div>- <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>- Loading news for {currentSymbol}- </div>- </div>- ) : !newsData || !newsData.success ? (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '400px',- gap: '16px',- }}>- <div style={{ color: COLORS.RED, fontSize: '14px', fontWeight: 'bold' }}>- [WARN]️ NO NEWS AVAILABLE- </div>- <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>- {newsData?.error || 'Unable to fetch news at this time'}- </div>- <button- onClick={fetchNews}- style={{- backgroundColor: COLORS.ORANGE,- border: 'none',- color: COLORS.DARK_BG,- padding: '8px 16px',- fontSize: '10px',- cursor: 'pointer',- fontWeight: 'bold',- marginTop: '8px',- }}- >- RETRY- </button>- </div>- ) : newsData.data && newsData.data.length === 0 ? (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '400px',- gap: '16px',- }}>- <div style={{ color: COLORS.YELLOW, fontSize: '14px', fontWeight: 'bold' }}>- 📰 NO NEWS FOUND- </div>- <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>- No recent news articles found for {stockInfo?.company_name || currentSymbol}- </div>- </div>- ) : (- <>- {/* News Header */}- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '8px 12px',- marginBottom: '8px',- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center',- flexShrink: 0,- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>- <span style={{ color: COLORS.ORANGE, fontSize: '11px', fontWeight: 'bold' }}>- 📰 LATEST NEWS- </span>- <span style={{ color: COLORS.GRAY, fontSize: '9px' }}>- {newsData.count || 0} articles found- </span>- <span style={{ color: COLORS.CYAN, fontSize: '9px' }}>- {stockInfo?.company_name || currentSymbol}- </span>- </div>- <button- onClick={fetchNews}- style={{- backgroundColor: COLORS.DARK_BG,- border: `1px solid ${COLORS.BORDER}`,- color: COLORS.WHITE,- padding: '4px 12px',- fontSize: '9px',- cursor: 'pointer',- fontWeight: 'bold',- }}- >- 🔄 REFRESH- </button>- </div>-- {/* News Articles List */}- <div style={{- flex: 1,- overflow: 'auto',- display: 'flex',- flexDirection: 'column',- gap: '8px',- }} className="custom-scrollbar">- {newsData.data.map((article: any, index: number) => (- <div- key={index}- style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '12px',- cursor: 'pointer',- transition: 'all 0.2s',- }}- onMouseEnter={(e) => {- e.currentTarget.style.backgroundColor = '#252525';- e.currentTarget.style.borderColor = COLORS.ORANGE;- }}- onMouseLeave={(e) => {- e.currentTarget.style.backgroundColor = COLORS.PANEL_BG;- e.currentTarget.style.borderColor = COLORS.BORDER;- }}- onClick={() => {- if (article.url && article.url !== '#') {- window.open(article.url, '_blank');- }- }}- >- {/* Article Header */}- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>- <div style={{ flex: 1, marginRight: '12px' }}>- <h3 style={{- color: COLORS.WHITE,- fontSize: '12px',- fontWeight: 'bold',- margin: 0,- marginBottom: '6px',- lineHeight: '1.4',- }}>- {article.title}- </h3>- <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>- <span style={{- color: COLORS.CYAN,- fontSize: '9px',- fontWeight: 'bold',- }}>- {article.publisher || 'Unknown Source'}- </span>- <span style={{- color: COLORS.GRAY,- fontSize: '9px',- }}>- {article.published_date || 'Unknown Date'}- </span>- </div>- </div>- </div>-- {/* Article Description */}- {article.description && article.description !== 'N/A' && (- <div style={{- color: COLORS.GRAY,- fontSize: '10px',- lineHeight: '1.5',- marginBottom: '8px',- }}>- {article.description}- </div>- )}-- {/* Read More Link */}- {article.url && article.url !== '#' && (- <div style={{- color: COLORS.ORANGE,- fontSize: '9px',- fontWeight: 'bold',- display: 'flex',- alignItems: 'center',- gap: '4px',- }}>- READ FULL ARTICLE →- </div>- )}- </div>- ))}- </div>- </>- )}- </div>- )}-- {/* Peers Tab */}- {activeTab === 'peers' && (- <div id="research-peer-comparison" style={{ padding: '8px' }}>- <PeerComparisonPanel initialSymbol={currentSymbol} />- </div>- )}-- {/* Technicals Tab */}- {activeTab === 'technicals' && (- <div id="research-chart" style={{ padding: '8px' }}>- {technicalsLoading ? (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '400px',- gap: '16px',- }}>- <div style={{- width: '50px',- height: '50px',- border: '4px solid #404040',- borderTop: '4px solid #ea580c',- borderRadius: '50%',- animation: 'spin 1s linear infinite'- }} />- <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' }}>- [WARN]️ NO TECHNICAL DATA AVAILABLE- </div>- <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>- Please wait for historical data to load- </div>- </div>- ) : (- <div style={{ padding: '8px', overflow: 'auto', height: 'calc(100vh - 280px)' }} className="custom-scrollbar">- {/* Check if we have valid indicator data */}- {(!technicalsData.indicator_columns || !technicalsData.data || !Array.isArray(technicalsData.data) || technicalsData.data.length === 0) ? (- <div style={{- backgroundColor: COLORS.PANEL_BG,- border: `1px solid ${COLORS.BORDER}`,- padding: '16px',- textAlign: 'center',- color: COLORS.YELLOW,- }}>- <div style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>- [WARN]️ NO INDICATOR DATA- </div>- <div style={{ fontSize: '11px', color: COLORS.GRAY }}>- Technical indicators could not be computed. Please try again or select a different symbol.- </div>- </div>- ) : (- <>- {/* Render Individual Indicator Boxes */}- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(420px, 1fr))', gap: '16px' }}>- {/* Trend Indicators */}- {technicalsData.indicator_columns?.trend && Array.isArray(technicalsData.indicator_columns.trend) &&- technicalsData.indicator_columns.trend.map((indicator: string) => {- const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);- if (values.length === 0) return null;- const latestValue = values[values.length - 1];- const min = Math.min(...values);- const max = Math.max(...values);- const avg = values.reduce((a: number, b: number) => a + b, 0) / values.length;-- return (- <IndicatorBox- key={indicator}- name={indicator}- latestValue={latestValue}- min={min}- max={max}- avg={avg}- values={values}- priceData={historicalData}- color={COLORS.CYAN}- category="TREND"- />- );- })}-- {/* Momentum Indicators */}- {technicalsData.indicator_columns?.momentum && Array.isArray(technicalsData.indicator_columns.momentum) &&- technicalsData.indicator_columns.momentum.map((indicator: string) => {- const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);- if (values.length === 0) return null;- const latestValue = values[values.length - 1];- const min = Math.min(...values);- const max = Math.max(...values);- const avg = values.reduce((a: number, b: number) => a + b, 0) / values.length;-- return (- <IndicatorBox- key={indicator}- name={indicator}- latestValue={latestValue}- min={min}- max={max}- avg={avg}- values={values}- priceData={historicalData}- color={COLORS.GREEN}- category="MOMENTUM"- />- );- })}-- {/* Volatility Indicators */}- {technicalsData.indicator_columns?.volatility && Array.isArray(technicalsData.indicator_columns.volatility) &&- technicalsData.indicator_columns.volatility.map((indicator: string) => {- const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);- if (values.length === 0) return null;- const latestValue = values[values.length - 1];- const min = Math.min(...values);- const max = Math.max(...values);- const avg = values.reduce((a: number, b: number) => a + b, 0) / values.length;-- return (- <IndicatorBox- key={indicator}- name={indicator}- latestValue={latestValue}- min={min}- max={max}- avg={avg}- values={values}- priceData={historicalData}- color={COLORS.YELLOW}- category="VOLATILITY"- />- );- })}-- {/* Volume Indicators */}- {technicalsData.indicator_columns?.volume && Array.isArray(technicalsData.indicator_columns.volume) &&- technicalsData.indicator_columns.volume.map((indicator: string) => {- const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);- if (values.length === 0) return null;- const latestValue = values[values.length - 1];- const min = Math.min(...values);- const max = Math.max(...values);- const avg = values.reduce((a: number, b: number) => a + b, 0) / values.length;-- return (- <IndicatorBox- key={indicator}- name={indicator}- latestValue={latestValue}- min={min}- max={max}- avg={avg}- values={values}- priceData={historicalData}- color={COLORS.BLUE}- category="VOLUME"- />- );- })}-- {/* Others Indicators */}- {technicalsData.indicator_columns?.others && Array.isArray(technicalsData.indicator_columns.others) &&- technicalsData.indicator_columns.others.map((indicator: string) => {- const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);- if (values.length === 0) return null;- const latestValue = values[values.length - 1];- const min = Math.min(...values);- const max = Math.max(...values);- const avg = values.reduce((a: number, b: number) => a + b, 0) / values.length;-- return (- <IndicatorBox- key={indicator}- name={indicator}- latestValue={latestValue}- min={min}- max={max}- avg={avg}- values={values}- priceData={historicalData}- color={COLORS.MAGENTA}- category="RETURN"- />- );- })}- </div>- </>- )}- </div>- )}- </div>- )}- </div>-- {/* Footer / Status Bar */}- <TabFooter- tabName="EQUITY RESEARCH"- leftInfo={[- { label: 'Real-time data analysis and company fundamentals', color: COLORS.GRAY },- { label: 'Data Source: YFinance', color: COLORS.GRAY },- ]}- statusInfo={- <div style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>- <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, fontWeight: 'bold' }}>- {loading ? 'LOADING...' : 'READY'}- </span>- </div>- }- backgroundColor={COLORS.PANEL_BG}- borderColor={COLORS.BORDER}- />-- {/* Custom Scrollbar Styles */}- <style>{`- .custom-scrollbar::-webkit-scrollbar {- width: 4px;- height: 4px;- }- .custom-scrollbar::-webkit-scrollbar-track {- background: transparent;- }- .custom-scrollbar::-webkit-scrollbar-thumb {- background: rgba(120, 120, 120, 0.3);- border-radius: 2px;- }- .custom-scrollbar::-webkit-scrollbar-thumb:hover {- background: rgba(120, 120, 120, 0.6);- }- .custom-scrollbar::-webkit-scrollbar-corner {- background: transparent;- }- `}</style>- </div>- );-};--export default EquityResearchTab;+/**+ * EquityResearchTab - Re-export from modularized folder+ *+ * This file has been refactored into smaller components.+ * The implementation is now in the equity-research folder:+ *+ * - equity-research/+ * - EquityResearchTab.tsx - Main tab component+ * - types/index.ts - Type definitions+ * - hooks/ - Custom hooks (useStockData, useSymbolSearch, useNews)+ * - components/ - Reusable components (IndicatorBox, etc.)+ * - tabs/ - Tab content components (Overview, Financials, etc.)+ * - utils/ - Utility functions (formatters)+ * - index.ts - Main exports+ */++export { default } from './equity-research/EquityResearchTab';diff --git a/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx b/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsxindex f238dff00..642c25ba7 100644--- a/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx@@ -30,7 +30,28 @@ import {Sparkles,ChevronDown,MessageSquare,- Maximize2+ Maximize2,+ Palette,+ Wand2,+ BookmarkPlus,+ Quote,+ List,+ ListOrdered,+ Hash,+ Stamp,+ QrCode,+ PenTool,+ AlertTriangle,+ Activity,+ TrendingUp,+ Database,+ MessageCircle,+ History,+ Search,+ Undo2,+ Redo2,+ Keyboard,+ LayoutTemplate,} 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';@@ -47,6 +68,52 @@ import { sqliteService } from '@/services/core/sqliteService';import MarkdownRenderer from '../common/MarkdownRenderer';import { TabFooter } from '@/components/common/TabFooter';import { useTranslation } from 'react-i18next';+import { AdvancedStylingPanel } from './report-builder/AdvancedStylingPanel';+import { ExportDialog } from './report-builder/ExportDialog';+import {+ brandKitService,+ BrandKit,+ ComponentTemplate,+ HeaderFooterTemplate,+ ParagraphStyles,+} from '@/services/core/brandKitService';++// New feature imports+import {+ LiveDataTable,+ KPICardsRow,+ Sparkline,+ DynamicChart,+ FinancialMetricsWidget,+ ChartDataEditor,+} from './report-builder/DataComponents';+import {+ QuoteBox,+ ListComponent,+ FootnotesList,+ TableOfContents,+ Watermark,+ QRCodeComponent,+ SignatureBlock,+ DisclaimerSection,+ SectionHeader,+} from './report-builder/AdditionalComponents';+import { TemplateGallery } from './report-builder/TemplateGallery';+import {+ CommentsPanel,+ VersionHistoryPanel,+ RevisionMode,+ useCollaboration,+} from './report-builder/CollaborationFeatures';+import {+ useUndoRedo,+ useAutoSave,+ useKeyboardShortcuts,+ useFullscreen,+ FindReplaceDialog,+ ShortcutsDialog,+ ProductivityToolbar,+} from './report-builder/ProductivityFeatures';// Fincept color paletteconst FINCEPT_COLORS = {@@ -97,6 +164,16 @@ function SortableComponent({case 'image': return <ImageIcon size={14} />;case 'code': return <Code size={14} />;case 'divider': return <Minus size={14} />;+ case 'quote': return <Quote size={14} />;+ case 'list': return <List size={14} />;+ case 'toc': return <Hash size={14} />;+ case 'kpi': return <TrendingUp size={14} />;+ case 'sparkline': return <Activity size={14} />;+ case 'liveTable': return <Database size={14} />;+ case 'signature': return <PenTool size={14} />;+ case 'disclaimer': return <AlertTriangle size={14} />;+ case 'qrcode': return <QrCode size={14} />;+ case 'watermark': return <Stamp size={14} />;default: return <FileText size={14} />;}};@@ -175,6 +252,7 @@ const ReportBuilderTab: React.FC = () => {const [isSaving, setIsSaving] = useState(false);const [showSuccessDialog, setShowSuccessDialog] = useState(false);const [generatedPdfPath, setGeneratedPdfPath] = useState<string>('');+ const [showExportDialog, setShowExportDialog] = useState(false);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);@@ -192,8 +270,28 @@ const ReportBuilderTab: React.FC = () => {const [streamingContent, setStreamingContent] = useState('');const aiMessagesEndRef = useRef<HTMLDivElement>(null);- // Right panel view toggle: 'split' | 'properties' | 'chat'- const [rightPanelView, setRightPanelView] = useState<'split' | 'properties' | 'chat'>('split');+ // Right panel view toggle+ const [rightPanelView, setRightPanelView] = useState<'split' | 'properties' | 'chat' | 'styling' | 'comments' | 'history'>('split');++ // New feature states+ const [showTemplateGallery, setShowTemplateGallery] = useState(false);+ const [showFindReplace, setShowFindReplace] = useState(false);+ const [showShortcuts, setShowShortcuts] = useState(false);+ const [revisionModeEnabled, setRevisionModeEnabled] = useState(false);++ // Brand Kit and Advanced Styling state+ const [activeBrandKit, setActiveBrandKit] = useState<BrandKit | null>(null);+ const [advancedStyles, setAdvancedStyles] = useState<{+ customCSS: string;+ headerTemplate: HeaderFooterTemplate | null;+ footerTemplate: HeaderFooterTemplate | null;+ paragraphStyles: ParagraphStyles | null;+ }>({+ customCSS: '',+ headerTemplate: null,+ footerTemplate: null,+ paragraphStyles: null,+ });const sensors = useSensors(useSensor(PointerSensor),@@ -202,12 +300,81 @@ const ReportBuilderTab: React.FC = () => {}));+ // Undo/Redo hook+ const {+ state: templateHistory,+ set: setTemplateWithHistory,+ undo,+ redo,+ canUndo,+ canRedo,+ } = useUndoRedo(template);++ // Auto-save hook+ const { isSaving: isAutoSaving, lastSaved, forceSave } = useAutoSave(+ template,+ async (data) => {+ try {+ await reportService.saveTemplate(data);+ console.log('Auto-saved report');+ } catch (error) {+ console.error('Auto-save failed:', error);+ }+ },+ { interval: 60000, enabled: true }+ );++ // Collaboration hook+ const collaboration = useCollaboration(template);++ // Fullscreen hook+ const { isFullscreen, toggleFullscreen, fullscreenRef } = useFullscreen();++ // Keyboard shortcuts+ useKeyboardShortcuts({+ 'ctrl+z': () => undo(),+ 'ctrl+y': () => redo(),+ 'ctrl+shift+z': () => redo(),+ 'ctrl+s': () => { forceSave(); toast.success('Saved'); },+ 'ctrl+f': () => setShowFindReplace(true),+ 'ctrl+shift+/': () => setShowShortcuts(true),+ 'f11': () => toggleFullscreen(),+ });++ // Sync template with undo/redo history+ useEffect(() => {+ if (JSON.stringify(templateHistory) !== JSON.stringify(template)) {+ setTemplate(templateHistory);+ }+ }, [templateHistory]);+// Update timeReact.useEffect(() => {const timer = setInterval(() => setCurrentTime(new Date()), 1000);return () => clearInterval(timer);}, []);+ // Load active brand kit on mount+ useEffect(() => {+ const loadBrandKit = async () => {+ try {+ const kit = await brandKitService.getActiveBrandKit();+ if (kit) {+ setActiveBrandKit(kit);+ setAdvancedStyles({+ customCSS: kit.customCSS || '',+ headerTemplate: kit.headerTemplate || null,+ footerTemplate: kit.footerTemplate || null,+ paragraphStyles: kit.paragraphStyles || null,+ });+ }+ } catch (error) {+ console.error('Failed to load brand kit:', error);+ }+ };+ loadBrandKit();+ }, []);+// Load available AI modelsuseEffect(() => {const loadModels = async () => {@@ -248,7 +415,9 @@ const ReportBuilderTab: React.FC = () => {content: (type === 'divider' || type === 'pagebreak' || type === 'coverpage' || type === 'section' || type === 'columns') ? '' :type === 'heading' ? 'New Heading' :type === 'subheading' ? 'New Subheading' :- type === 'text' ? 'Enter text here...' : '',+ type === 'text' ? 'Enter text here...' :+ type === 'quote' ? 'Enter quote text here...' :+ type === 'disclaimer' ? 'This report is for informational purposes only.' : '',config: {fontSize: type === 'heading' ? '2xl' : type === 'subheading' ? 'xl' : 'base',fontWeight: type === 'heading' || type === 'subheading' ? 'bold' : 'normal',@@ -265,18 +434,74 @@ const ReportBuilderTab: React.FC = () => {subtitle: '',backgroundColor: '#0a0a0a',}),+ // New component configs+ ...(type === 'quote' && {+ quoteType: 'quote',+ author: '',+ }),+ ...(type === 'list' && {+ items: ['Item 1', 'Item 2', 'Item 3'],+ ordered: false,+ }),+ ...(type === 'toc' && {+ showPageNumbers: true,+ }),+ ...(type === 'kpi' && {+ kpis: [+ { label: 'Revenue', value: '$1.2M', change: 12.5, trend: 'up' },+ { label: 'Profit', value: '$340K', change: 8.2, trend: 'up' },+ { label: 'Margin', value: '28.3%', change: -2.1, trend: 'down' },+ ],+ }),+ ...(type === 'sparkline' && {+ data: [10, 25, 15, 30, 20, 35, 28],+ color: '#FFA500',+ }),+ ...(type === 'liveTable' && {+ dataSource: 'portfolio',+ columns: ['Symbol', 'Price', 'Change', 'Volume'],+ }),+ ...(type === 'dynamicChart' && {+ chartType: 'line',+ data: [+ { name: 'Jan', value: 100 },+ { name: 'Feb', value: 120 },+ { name: 'Mar', value: 115 },+ { name: 'Apr', value: 140 },+ ],+ }),+ ...(type === 'signature' && {+ name: 'John Doe',+ title: 'Analyst',+ showLine: true,+ }),+ ...(type === 'disclaimer' && {+ disclaimerType: 'standard',+ }),+ ...(type === 'qrcode' && {+ value: 'https://example.com',+ size: 100,+ label: 'Scan for more info',+ }),+ ...(type === 'watermark' && {+ text: 'CONFIDENTIAL',+ opacity: 0.1,+ rotation: -45,+ }),},...(type === 'columns' || type === 'section' ? { children: [] } : {}),};- setTemplate(prev => ({- ...prev,- components: [...prev.components, newComponent],- }));+ const newTemplate = {+ ...template,+ components: [...template.components, newComponent],+ };+ setTemplate(newTemplate);+ setTemplateWithHistory(newTemplate);setSelectedComponent(newComponent.id);toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} added`);- }, []);+ }, [template, setTemplateWithHistory]);// Update componentconst updateComponent = useCallback((id: string, updates: Partial<ReportComponent>) => {@@ -424,6 +649,92 @@ const ReportBuilderTab: React.FC = () => {}};+ // Handle brand kit change+ const handleBrandKitChange = useCallback((brandKit: BrandKit) => {+ setActiveBrandKit(brandKit);+ // Apply brand kit fonts+ const bodyFont = brandKit.fonts.find(f => f.usage === 'body');+ if (bodyFont) {+ setFontFamily(bodyFont.family);+ }+ // Update advanced styles+ setAdvancedStyles({+ customCSS: brandKit.customCSS || '',+ headerTemplate: brandKit.headerTemplate || null,+ footerTemplate: brandKit.footerTemplate || null,+ paragraphStyles: brandKit.paragraphStyles || null,+ });+ toast.success(`Applied brand kit: ${brandKit.name}`);+ }, []);++ // Handle component template selection+ const handleComponentTemplateSelect = useCallback((template: ComponentTemplate) => {+ const newComponent: ReportComponent = {+ id: `component-${Date.now()}`,+ type: template.component.type as ReportComponent['type'],+ content: template.component.content,+ config: template.component.config,+ children: template.component.children,+ };+ setTemplate(prev => ({+ ...prev,+ components: [...prev.components, newComponent],+ }));+ setSelectedComponent(newComponent.id);+ toast.success(`Added template: ${template.name}`);+ }, []);++ // Handle advanced styles change+ const handleStylesChange = useCallback((styles: {+ customCSS: string;+ headerTemplate: HeaderFooterTemplate;+ footerTemplate: HeaderFooterTemplate;+ paragraphStyles: ParagraphStyles;+ }) => {+ setAdvancedStyles(styles);+ }, []);++ // Save component as template+ const saveAsTemplate = useCallback(async () => {+ if (!selectedComp) return;+ const templateName = prompt('Enter template name:', `${selectedComp.type} Template`);+ if (!templateName) return;++ const newTemplate: ComponentTemplate = {+ id: `template-${Date.now()}`,+ name: templateName,+ description: `Custom ${selectedComp.type} template`,+ category: selectedComp.type === 'section' || selectedComp.type === 'columns' ? 'layout' :+ selectedComp.type === 'image' ? 'media' :+ selectedComp.type === 'chart' || selectedComp.type === 'table' ? 'data' : 'text',+ component: {+ type: selectedComp.type,+ content: selectedComp.content,+ config: selectedComp.config,+ children: selectedComp.children,+ },+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ };++ try {+ await brandKitService.saveComponentTemplate(newTemplate);+ toast.success('Component saved as template');+ } catch (error) {+ toast.error('Failed to save template');+ }+ }, [selectedComp]);++ // Generate TOC items from headings+ const tocItems = template.components+ .filter(c => c.type === 'heading' || c.type === 'subheading')+ .map((c, idx) => ({+ id: c.id,+ title: String(c.content || `Section ${idx + 1}`),+ level: c.type === 'heading' ? 1 : 2,+ page: Math.floor(idx / 3) + 1,+ }));+// AI Chat - Send messageconst handleAiSendMessage = async () => {if (!aiInput.trim()) return;@@ -597,11 +908,55 @@ const ReportBuilderTab: React.FC = () => {<FileText className="w-5 h-5" style={{ color: FINCEPT_COLORS.ORANGE }} /><span className="font-bold text-sm" style={{ color: FINCEPT_COLORS.ORANGE }}>{t('title')}</span></div>- <span className="text-xs" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>- {currentTime.toLocaleTimeString()}- </span>+ {/* Productivity Toolbar */}+ <div className="flex items-center gap-1 border-l border-[#333333] pl-3">+ <button+ onClick={undo}+ disabled={!canUndo}+ className="p-1.5 rounded hover:bg-[#2a2a2a] disabled:opacity-30"+ title="Undo (Ctrl+Z)"+ >+ <Undo2 size={14} />+ </button>+ <button+ onClick={redo}+ disabled={!canRedo}+ className="p-1.5 rounded hover:bg-[#2a2a2a] disabled:opacity-30"+ title="Redo (Ctrl+Y)"+ >+ <Redo2 size={14} />+ </button>+ <button+ onClick={() => setShowFindReplace(true)}+ className="p-1.5 rounded hover:bg-[#2a2a2a]"+ title="Find & Replace (Ctrl+F)"+ >+ <Search size={14} />+ </button>+ <button+ onClick={() => setShowShortcuts(true)}+ className="p-1.5 rounded hover:bg-[#2a2a2a]"+ title="Keyboard Shortcuts"+ >+ <Keyboard size={14} />+ </button>+ </div>+ {/* Auto-save status */}+ {lastSaved && (+ <span className="text-[10px]" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>+ {isAutoSaving ? 'Saving...' : `Saved ${lastSaved.toLocaleTimeString()}`}+ </span>+ )}</div><div className="flex items-center gap-2">+ <button+ onClick={() => setShowTemplateGallery(true)}+ className="px-3 py-1 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-1"+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}+ >+ <LayoutTemplate size={14} />+ Templates+ </button><buttononClick={loadTemplate}className="px-3 py-1 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-1"@@ -620,8 +975,8 @@ const ReportBuilderTab: React.FC = () => {{isSaving ? t('header.saving') : t('header.save')}</button><button- onClick={generatePdf}- disabled={isGenerating || template.components.length === 0}+ onClick={() => setShowExportDialog(true)}+ disabled={template.components.length === 0}className="px-3 py-1 text-xs rounded transition-colors flex items-center gap-1 disabled:opacity-50"style={{backgroundColor: FINCEPT_COLORS.ORANGE,@@ -630,7 +985,7 @@ const ReportBuilderTab: React.FC = () => {}}><Download size={14} />- {isGenerating ? t('header.generating') : t('header.exportPdf')}+ Export</button></div></div>@@ -700,6 +1055,108 @@ const ReportBuilderTab: React.FC = () => {<Minus size={14} />Divider</button>+ <button+ onClick={() => addComponent('quote' as any)}+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}+ >+ <Quote size={14} />+ Quote/Callout+ </button>+ <button+ onClick={() => addComponent('list' as any)}+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}+ >+ <List size={14} />+ List+ </button>+ </div>+ </div>++ {/* Data Components */}+ <div className="mb-4">+ <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>DATA</h3>+ <div className="grid grid-cols-2 gap-1">+ <button+ onClick={() => addComponent('kpi' as any)}+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}+ >+ <TrendingUp size={14} />+ <span className="text-[9px]">KPI</span>+ </button>+ <button+ onClick={() => addComponent('sparkline' as any)}+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}+ >+ <Activity size={14} />+ <span className="text-[9px]">Sparkline</span>+ </button>+ <button+ onClick={() => addComponent('liveTable' as any)}+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}+ >+ <Database size={14} />+ <span className="text-[9px]">Data Table</span>+ </button>+ <button+ onClick={() => addComponent('dynamicChart' as any)}+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}+ >+ <BarChart3 size={14} />+ <span className="text-[9px]">Chart</span>+ </button>+ </div>+ </div>++ {/* Document Components */}+ <div className="mb-4">+ <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>DOCUMENT</h3>+ <div className="grid grid-cols-2 gap-1">+ <button+ onClick={() => addComponent('toc' as any)}+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}+ >+ <Hash size={14} />+ <span className="text-[9px]">TOC</span>+ </button>+ <button+ onClick={() => addComponent('signature' as any)}+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}+ >+ <PenTool size={14} />+ <span className="text-[9px]">Signature</span>+ </button>+ <button+ onClick={() => addComponent('disclaimer' as any)}+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}+ >+ <AlertTriangle size={14} />+ <span className="text-[9px]">Disclaimer</span>+ </button>+ <button+ onClick={() => addComponent('qrcode' as any)}+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}+ >+ <QrCode size={14} />+ <span className="text-[9px]">QR Code</span>+ </button>+ <button+ onClick={() => addComponent('watermark' as any)}+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}+ >+ <Stamp size={14} />+ <span className="text-[9px]">Watermark</span>+ </button></div></div>@@ -1111,9 +1568,43 @@ const ReportBuilderTab: React.FC = () => {fontSize: `${defaultFontSize}pt`,fontWeight: isBold ? 'bold' : 'normal',fontStyle: isItalic ? 'italic' : 'normal',+ ...(advancedStyles.paragraphStyles && {+ lineHeight: advancedStyles.paragraphStyles.lineHeight,+ letterSpacing: `${advancedStyles.paragraphStyles.letterSpacing}px`,+ wordSpacing: `${advancedStyles.paragraphStyles.wordSpacing}px`,+ }),...getThemeBackground(),}}>+ {/* Header (if enabled) */}+ {advancedStyles.headerTemplate?.enabled && (+ <div+ className="mb-4 -mt-4 -mx-4 px-4"+ style={{+ backgroundColor: advancedStyles.headerTemplate.backgroundColor,+ color: advancedStyles.headerTemplate.textColor,+ fontSize: `${advancedStyles.headerTemplate.fontSize}pt`,+ minHeight: advancedStyles.headerTemplate.height,+ textAlign: advancedStyles.headerTemplate.alignment,+ borderBottom: advancedStyles.headerTemplate.borderBottom ? '1px solid #E0E0E0' : 'none',+ display: 'flex',+ alignItems: 'center',+ justifyContent: advancedStyles.headerTemplate.alignment === 'center' ? 'center' :+ advancedStyles.headerTemplate.alignment === 'right' ? 'flex-end' : 'space-between',+ padding: '8px 20px',+ }}+ >+ <span>+ {advancedStyles.headerTemplate.content+ .replace('{company}', template.metadata.company || 'Company')+ .replace('{title}', template.metadata.title || 'Report')+ .replace('{date}', template.metadata.date || new Date().toLocaleDateString())}+ </span>+ {advancedStyles.headerTemplate.showPageNumbers && (+ <span>Page 1</span>+ )}+ </div>+ )}{/* 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>@@ -1246,44 +1737,180 @@ const ReportBuilderTab: React.FC = () => {<span className="text-xs text-gray-400 bg-white px-3 py-1 rounded-full">Page Break</span></div>)}+ {/* New component types */}+ {component.type === 'quote' && (+ <QuoteBox+ content={String(component.content || '')}+ author={component.config.author}+ type={component.config.quoteType || 'quote'}+ />+ )}+ {component.type === 'list' && (+ <ListComponent+ items={component.config.items || ['Item 1', 'Item 2']}+ ordered={component.config.ordered}+ />+ )}+ {component.type === 'toc' && (+ <TableOfContents+ items={tocItems}+ showPageNumbers={component.config.showPageNumbers}+ />+ )}+ {component.type === 'kpi' && (+ <KPICardsRow+ cards={(component.config.kpis || []).map((k: any) => ({+ title: k.label,+ value: k.value,+ change: k.change,+ }))}+ />+ )}+ {component.type === 'sparkline' && (+ <div className="inline-block">+ <Sparkline+ config={{+ data: component.config.data as number[] || [10, 20, 15, 25],+ color: component.config.color || '#FFA500',+ height: 50,+ }}+ />+ </div>+ )}+ {component.type === 'liveTable' && (+ <LiveDataTable+ config={{+ source: component.config.dataSource as 'portfolio' | 'watchlist' || 'portfolio',+ columns: component.config.columns,+ }}+ />+ )}+ {component.type === 'dynamicChart' && (+ <DynamicChart+ config={{+ type: (component.config.chartType || 'line') as 'line' | 'bar' | 'area' | 'pie',+ data: component.config.data as Array<{ name: string; value: number }> || [],+ height: 250,+ }}+ />+ )}+ {component.type === 'signature' && (+ <SignatureBlock+ name={component.config.name || 'Name'}+ title={component.config.title}+ date={template.metadata.date}+ showLine={component.config.showLine}+ />+ )}+ {component.type === 'disclaimer' && (+ <DisclaimerSection+ content={String(component.content || '')}+ type={component.config.disclaimerType || 'standard'}+ />+ )}+ {component.type === 'qrcode' && (+ <QRCodeComponent+ value={component.config.value || 'https://example.com'}+ size={component.config.size || 100}+ label={component.config.label}+ />+ )}+ {component.type === 'watermark' && (+ <Watermark+ text={component.config.text || 'CONFIDENTIAL'}+ opacity={component.config.opacity || 0.1}+ rotation={component.config.rotation || -45}+ />+ )}</div>);})}</div>)}++ {/* Footer (if enabled) */}+ {advancedStyles.footerTemplate?.enabled && (+ <div+ className="mt-8 -mb-4 -mx-4 px-4"+ style={{+ backgroundColor: advancedStyles.footerTemplate.backgroundColor,+ color: advancedStyles.footerTemplate.textColor,+ fontSize: `${advancedStyles.footerTemplate.fontSize}pt`,+ minHeight: advancedStyles.footerTemplate.height,+ textAlign: advancedStyles.footerTemplate.alignment,+ borderTop: advancedStyles.footerTemplate.borderTop ? '1px solid #E0E0E0' : 'none',+ display: 'flex',+ alignItems: 'center',+ justifyContent: advancedStyles.footerTemplate.alignment === 'center' ? 'center' :+ advancedStyles.footerTemplate.alignment === 'right' ? 'flex-end' : 'space-between',+ padding: '8px 20px',+ }}+ >+ <span>+ {advancedStyles.footerTemplate.content+ .replace('{company}', template.metadata.company || 'Company')+ .replace('{title}', template.metadata.title || 'Report')+ .replace('{date}', template.metadata.date || new Date().toLocaleDateString())}+ </span>+ {advancedStyles.footerTemplate.showPageNumbers && advancedStyles.footerTemplate.pageNumberPosition !== advancedStyles.footerTemplate.alignment && (+ <span>Page 1</span>+ )}+ </div>+ )}</div></div>- {/* Right Panel - Properties and AI Chat */}+ {/* Right Panel - Properties, AI Chat, and Advanced Styling */}<div className="w-1/5 border-l flex flex-col min-h-0" style={{ borderColor: FINCEPT_COLORS.BORDER, backgroundColor: FINCEPT_COLORS.PANEL_BG }}>{/* Toggle Buttons */}- <div className="flex border-b" style={{ borderColor: FINCEPT_COLORS.BORDER }}>+ <div className="flex flex-wrap border-b" style={{ borderColor: FINCEPT_COLORS.BORDER }}><buttononClick={() => setRightPanelView('properties')}- className={`flex-1 px-3 py-2 text-xs font-semibold transition-colors flex items-center justify-center gap-1 ${rightPanelView === 'properties' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'+ className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${rightPanelView === 'properties' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'}`}style={{ color: rightPanelView === 'properties' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}+ title="Component Properties">- <SettingsIcon size={14} />- Properties+ <SettingsIcon size={12} />+ Props+ </button>+ <button+ onClick={() => setRightPanelView('styling')}+ className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${rightPanelView === 'styling' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'+ }`}+ style={{ color: rightPanelView === 'styling' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}+ title="Advanced Styling"+ >+ <Palette size={12} />+ Style</button><buttononClick={() => setRightPanelView('chat')}- className={`flex-1 px-3 py-2 text-xs font-semibold transition-colors flex items-center justify-center gap-1 ${rightPanelView === 'chat' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'+ className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${rightPanelView === 'chat' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'}`}style={{ color: rightPanelView === 'chat' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}+ title="AI Writing Assistant">- <MessageSquare size={14} />- AI Chat+ <Bot size={12} />+ AI</button><button- onClick={() => setRightPanelView('split')}- className={`px-3 py-2 text-xs font-semibold transition-colors flex items-center justify-center ${rightPanelView === 'split' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'+ onClick={() => setRightPanelView('comments')}+ className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${rightPanelView === 'comments' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'}`}- style={{ color: rightPanelView === 'split' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}- title="Split View"+ style={{ color: rightPanelView === 'comments' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}+ title="Comments">- <Maximize2 size={14} />+ <MessageCircle size={12} />+ </button>+ <button+ onClick={() => setRightPanelView('history')}+ className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${rightPanelView === 'history' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'+ }`}+ style={{ color: rightPanelView === 'history' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}+ title="Version History"+ >+ <History size={12} /></button></div>@@ -1465,7 +2092,7 @@ const ReportBuilderTab: React.FC = () => {{/* Actions */}<div className="pt-4 border-t" style={{ borderColor: FINCEPT_COLORS.BORDER }}>- <div className="flex gap-2">+ <div className="flex gap-2 mb-2"><buttononClick={() => 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"@@ -1481,6 +2108,14 @@ const ReportBuilderTab: React.FC = () => {Delete</button></div>+ <button+ onClick={saveAsTemplate}+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors flex items-center justify-center gap-2"+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}+ >+ <BookmarkPlus size={14} />+ Save as Template+ </button></div></div></div>@@ -1665,6 +2300,52 @@ const ReportBuilderTab: React.FC = () => {</div></div>)}++ {/* Advanced Styling Panel */}+ {rightPanelView === 'styling' && (+ <div className="flex-1 overflow-hidden">+ <AdvancedStylingPanel+ onBrandKitChange={handleBrandKitChange}+ onComponentTemplateSelect={handleComponentTemplateSelect}+ onStylesChange={handleStylesChange}+ />+ </div>+ )}++ {/* Comments Panel */}+ {rightPanelView === 'comments' && (+ <div className="flex-1 overflow-hidden">+ <CommentsPanel+ comments={collaboration.comments}+ onAddComment={(componentId: string, content: string) =>+ collaboration.addComment(componentId, content)+ }+ onResolveComment={collaboration.resolveComment}+ onDeleteComment={collaboration.deleteComment}+ onReplyComment={collaboration.replyToComment}+ selectedComponentId={selectedComponent}+ />+ </div>+ )}++ {/* Version History Panel */}+ {rightPanelView === 'history' && (+ <div className="flex-1 overflow-hidden">+ <VersionHistoryPanel+ history={collaboration.versionHistory}+ onPreview={(entry) => {+ toast.info(`Previewing version: ${entry.description}`);+ }}+ onRestore={(entry) => {+ if (entry.template) {+ setTemplate(entry.template);+ setTemplateWithHistory(entry.template);+ toast.success(`Restored version: ${entry.description}`);+ }+ }}+ />+ </div>+ )}</div></div>@@ -1702,13 +2383,50 @@ const ReportBuilderTab: React.FC = () => {</DialogContent></Dialog>+ {/* Export Dialog */}+ <ExportDialog+ open={showExportDialog}+ onClose={() => setShowExportDialog(false)}+ template={template}+ brandKit={activeBrandKit}+ />++ {/* Template Gallery Dialog */}+ <TemplateGallery+ open={showTemplateGallery}+ onClose={() => setShowTemplateGallery(false)}+ onSelectTemplate={(t) => {+ setTemplate(t);+ setTemplateWithHistory(t);+ toast.success(`Applied template: ${t.name}`);+ }}+ currentTemplate={template}+ />++ {/* Find & Replace Dialog */}+ <FindReplaceDialog+ open={showFindReplace}+ onClose={() => setShowFindReplace(false)}+ onReplace={(componentId, oldText, newText) => {+ updateComponent(componentId, { content: newText });+ }}+ components={template.components}+ />++ {/* Keyboard Shortcuts Dialog */}+ <ShortcutsDialog+ open={showShortcuts}+ onClose={() => setShowShortcuts(false)}+ />+<TabFootertabName="REPORT BUILDER"leftInfo={[{ label: `Components: ${template.components.length}`, color: FINCEPT_COLORS.TEXT_PRIMARY },{ label: `Theme: ${pageTheme.charAt(0).toUpperCase() + pageTheme.slice(1)}`, color: FINCEPT_COLORS.TEXT_PRIMARY },+ ...(activeBrandKit ? [{ label: `Brand: ${activeBrandKit.name}`, color: FINCEPT_COLORS.ORANGE }] : []),]}- statusInfo={`${currentTime.toLocaleTimeString()} | PDF Generator: Rust printpdf`}+ statusInfo={`${currentTime.toLocaleTimeString()} | Multi-format Export`}backgroundColor={FINCEPT_COLORS.PANEL_BG}borderColor={FINCEPT_COLORS.ORANGE}/>diff --git a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsxdeleted file mode 100644index e715069d1..000000000--- a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx+++ /dev/null@@ -1,2809 +0,0 @@-import React, { useState, useEffect } from 'react';-import { Save, RefreshCw, Lock, User, Settings as SettingsIcon, Database, Terminal, Bell, Bot, Edit3, Type, Palette, Wifi, WifiOff, Activity, Zap, Link, Globe, Check, Plus, Trash2, ToggleLeft, ToggleRight, Eye, EyeOff, TrendingUp, Key, X, Clock, Briefcase } from 'lucide-react';-import { sqliteService, type LLMConfig, type LLMGlobalSettings, type LLMModelConfig, PREDEFINED_API_KEYS, type ApiKeys, saveSetting, getSetting } from '@/services/core/sqliteService';-import { ollamaService } from '@/services/chat/ollamaService';-import { LLMModelsService, type ModelInfo } from '@/services/llmModelsService';-import { useTerminalTheme } from '@/contexts/ThemeContext';-import { terminalThemeService, FONT_FAMILIES, COLOR_THEMES, FontSettings } from '@/services/core/terminalThemeService';-import { getWebSocketManager, ConnectionStatus, getAvailableProviders } from '@/services/trading/websocketBridge';-import { DataSourcesPanel } from '@/components/settings/DataSourcesPanel';-import { BacktestingProvidersPanel } from '@/components/settings/BacktestingProvidersPanel';-import { LanguageSelector } from '@/components/settings/LanguageSelector';-import { TerminalConfigPanel } from '@/components/settings/TerminalConfigPanel';-import { PolymarketCredentialsPanel } from '@/components/settings/PolymarketCredentialsPanel';-import { MasterContractManager } from '@/components/tabs/equity-trading/components';-import { useTimezone, TIMEZONE_OPTIONS } from '@/contexts/TimezoneContext';-import { useTranslation } from 'react-i18next';-import { TabFooter } from '@/components/common/TabFooter';-import { useAuth } from '@/contexts/AuthContext';--export default function SettingsTab() {- const { t } = useTranslation('settings');- const { session } = useAuth();- const { theme, updateTheme, resetTheme, colors, fontSize: themeFontSize, fontFamily: themeFontFamily, fontWeight: themeFontWeight, fontStyle } = useTerminalTheme();- const { defaultTimezone, setDefaultTimezone, options: timezoneOptions } = useTimezone();- const [activeSection, setActiveSection] = useState<'credentials' | 'polymarket' | 'terminal' | 'terminalConfig' | 'llm' | 'dataConnections' | 'backtesting' | 'stockSymbols' | 'language'>('credentials');- const [apiKeys, setApiKeys] = useState<ApiKeys>({});- const [loading, setLoading] = useState(false);- const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);- const [dbInitialized, setDbInitialized] = useState(false);-- // WebSocket Data Connections State- // WebSocket manager removed - now using Rust backend- const [wsProviders, setWsProviders] = useState<Array<{- id: number;- provider_name: string;- enabled: boolean;- api_key: string | null;- api_secret: string | null;- endpoint: string | null;- config_data: string | null;- }>>([]);- const [selectedProvider, setSelectedProvider] = useState<string | null>(null);- const [providerForm, setProviderForm] = useState({- provider_name: '',- enabled: true,- api_key: '',- api_secret: '',- endpoint: '',- config_data: ''- });- const [expandedProvider, setExpandedProvider] = useState<string | null>(null);- const [programmaticProviders, setProgrammaticProviders] = useState<Set<string>>(new Set());-- // Terminal appearance states- const [fontFamily, setFontFamily] = useState(theme.font.family);- const [baseSize, setBaseSize] = useState(theme.font.baseSize);- const [fontWeight, setFontWeight] = useState(theme.font.weight);- const [fontItalic, setFontItalic] = useState(theme.font.italic);- const [selectedTheme, setSelectedTheme] = useState(terminalThemeService.getCurrentThemeKey());-- // Key mapping configuration- const DEFAULT_KEY_MAPPINGS = {- F1: 'dashboard',- F2: 'markets',- F3: 'news',- F4: 'portfolio',- F5: 'analytics',- F6: 'watchlist',- F7: 'equity-research',- F8: 'screener',- F9: 'trading',- F10: 'chat',- F11: 'fullscreen',- F12: 'profile'- };-- const [keyMappings, setKeyMappings] = useState<Record<string, string>>(DEFAULT_KEY_MAPPINGS);-- // LLM Configuration States- const [llmConfigs, setLlmConfigs] = useState<LLMConfig[]>([]);- const [llmGlobalSettings, setLlmGlobalSettings] = useState<LLMGlobalSettings>({- temperature: 0.7,- max_tokens: 2048,- system_prompt: ''- });- const [activeProvider, setActiveProvider] = useState<string>('ollama');-- // Ollama model selection- const [ollamaModels, setOllamaModels] = useState<string[]>([]);- const [ollamaLoading, setOllamaLoading] = useState(false);- const [ollamaError, setOllamaError] = useState<string | null>(null);- const [useManualEntry, setUseManualEntry] = useState(false);- const [showPasswords, setShowPasswords] = useState<Record<number, boolean>>({});-- // Provider models (auto-fetched from APIs)- const [providerModels, setProviderModels] = useState<ModelInfo[]>([]);- const [providerModelsLoading, setProviderModelsLoading] = useState(false);- const [providerModelsError, setProviderModelsError] = useState<string | null>(null);-- // Multi-model configuration state- const [modelConfigs, setModelConfigs] = useState<LLMModelConfig[]>([]);- const [showAddModel, setShowAddModel] = useState(false);- const [newModelConfig, setNewModelConfig] = useState<{- provider: string;- model_id: string;- display_name: string;- api_key: string;- base_url: string;- }>({- provider: 'openai',- model_id: '',- display_name: '',- api_key: '',- base_url: ''- });-- // Models for new model config dropdown- const [newModelConfigModels, setNewModelConfigModels] = useState<ModelInfo[]>([]);- const [showApiKeys, setShowApiKeys] = useState<Record<string, boolean>>({});---- useEffect(() => {- checkAndLoadData();- }, []);-- // Track programmatic providers that get initialized- // TODO: Re-implement with new Rust WebSocket backend- // useEffect(() => {- // const detectedProviders = new Set<string>([- // ...Array.from(statuses.keys()),- // ...manager.getSubscriptions().map(sub => sub.topic.split('.')[0])- // ]);-- // // Filter out database-configured providers- // detectedProviders.forEach(p => {- // if (wsProviders.find(wp => wp.provider_name === p)) {- // detectedProviders.delete(p);- // }- // });-- // if (detectedProviders.size > 0) {- // setProgrammaticProviders(prev => new Set([...prev, ...detectedProviders]));- // }- // }, [wsProviders]);-- const checkAndLoadData = async () => {- try {- setLoading(true);-- // Check if database is already initialized- const isReady = sqliteService.isReady();-- if (!isReady) {- // Database not initialized, initialize it now- console.log('[SettingsTab] Database not initialized, initializing now...');- await sqliteService.initialize();- }-- // Verify database health- const healthCheck = await sqliteService.healthCheck();- if (!healthCheck.healthy) {- throw new Error(healthCheck.message);- }-- setDbInitialized(true);-- // Load initial data- await loadApiKeys();- await loadLLMConfigs();- await loadWSProviders();-- console.log('[SettingsTab] Data loaded successfully');- } catch (error) {- console.error('[SettingsTab] Failed to load data:', error);- const errorMsg = error instanceof Error ? error.message : 'Unknown error';- showMessage('error', `Failed to load settings: ${errorMsg}`);- setDbInitialized(false);- } finally {- setLoading(false);- }- };-- const loadWSProviders = async () => {- try {- const providers = await sqliteService.getWSProviderConfigs();- setWsProviders(providers);-- // TODO: Re-implement auto-initialization with new Rust WebSocket backend- // const wsManager = getWebSocketManager();- // for (const provider of providers) {- // if (provider.enabled) {- // wsManager.setProviderConfig(provider.provider_name, {- // provider_name: provider.provider_name,- // enabled: provider.enabled,- // api_key: provider.api_key || undefined,- // api_secret: provider.api_secret || undefined,- // endpoint: provider.endpoint || undefined- // });- // console.log(`[Settings] Auto-initialized provider: ${provider.provider_name}`);- // }- // }- } catch (error) {- console.error('Failed to load WS providers:', error);- }- };-- const handleSaveWSProvider = async () => {- if (!providerForm.provider_name.trim()) {- showMessage('error', 'Provider name is required');- return;- }-- try {- setLoading(true);- const result = await sqliteService.saveWSProviderConfig(providerForm);-- if (result.success) {- showMessage('success', result.message);-- // TODO: Re-implement with new Rust WebSocket backend- // const manager = getWebSocketManager();- // manager.setProviderConfig(providerForm.provider_name, {- // provider_name: providerForm.provider_name,- // enabled: providerForm.enabled,- // api_key: providerForm.api_key || undefined,- // api_secret: providerForm.api_secret || undefined,- // endpoint: providerForm.endpoint || undefined- // });-- // Reset form- setProviderForm({- provider_name: '',- enabled: true,- api_key: '',- api_secret: '',- endpoint: '',- config_data: ''- });- setSelectedProvider(null);- await loadWSProviders();- } else {- showMessage('error', result.message);- }- } catch (error) {- showMessage('error', 'Failed to save provider configuration');- } finally {- setLoading(false);- }- };-- const handleToggleWSProvider = async (providerName: string) => {- try {- const result = await sqliteService.toggleWSProviderEnabled(providerName);- if (result.success) {- showMessage('success', result.message);- await loadWSProviders();-- // TODO: Re-implement with new Rust WebSocket backend- // const manager = getWebSocketManager();- // if (result.enabled) {- // const config = await sqliteService.getWSProviderConfig(providerName);- // if (config) {- // manager.setProviderConfig(providerName, config);- // }- // } else {- // await manager.disconnect(providerName);- // }- }- } catch (error) {- showMessage('error', 'Failed to toggle provider');- }- };-- const handleDeleteWSProvider = async (providerName: string) => {- if (!confirm(`Delete configuration for ${providerName}?`)) return;-- try {- setLoading(true);- const result = await sqliteService.deleteWSProviderConfig(providerName);-- if (result.success) {- showMessage('success', result.message);-- // Disconnect from WebSocket Manager- const manager = getWebSocketManager();- await manager.disconnect(providerName);-- await loadWSProviders();- }- } catch (error) {- showMessage('error', 'Failed to delete provider');- } finally {- setLoading(false);- }- };-- const handleConnectProvider = async (providerName: string) => {- try {- const manager = getWebSocketManager();-- // First try to get config from database- const config = await sqliteService.getWSProviderConfig(providerName);-- if (config) {- // TODO: Re-implement with new Rust WebSocket backend- // manager.setProviderConfig(providerName, config);- // const hasSubscriptions = manager.getProviderSubscriptions(providerName).length > 0;- // if (hasSubscriptions) {- // await manager.reconnect(providerName);- // } else {- await manager.connect(providerName);- // }-- showMessage('success', `Connected to ${providerName}`);- } else {- showMessage('error', `No configuration found for ${providerName}`);- }- } catch (error) {- showMessage('error', `Failed to connect to ${providerName}: ${error}`);- }- };-- const handleDisconnectProvider = async (providerName: string) => {- try {- const manager = getWebSocketManager();- await manager.disconnect(providerName);- showMessage('success', `Disconnected from ${providerName}`);- } catch (error) {- showMessage('error', `Failed to disconnect from ${providerName}`);- }- };-- const handleTestProvider = async (providerName: string) => {- try {- // TODO: Re-implement ping with new Rust WebSocket backend- // const manager = getWebSocketManager();- // const latency = await manager.ping(providerName);- // showMessage('success', `Ping: ${latency}ms`);- showMessage('success', `Test connection feature coming soon`);- } catch (error) {- showMessage('error', `Ping failed for ${providerName}`);- }- };-- const handleUnsubscribe = async (subscriptionId: string, topic: string) => {- try {- // TODO: Re-implement with new Rust WebSocket backend- // const manager = getWebSocketManager();- // const subscriptions = manager.getSubscriptions();- // const sub = subscriptions.find(s => s.id === subscriptionId);-- // if (sub) {- // sub.unsubscribe();- // showMessage('success', `Unsubscribed from ${topic}`);- // } else {- showMessage('error', 'Subscription management coming soon');- // }- } catch (error) {- showMessage('error', `Failed to unsubscribe from ${topic}`);- }- };-- const loadApiKeys = async () => {- try {- const keys = await sqliteService.getAllApiKeys();- setApiKeys(keys);- } catch (error) {- console.error('Failed to load API keys:', error);- }- };-- const handleSaveApiKeyField = async (keyName: string, value: string) => {- setLoading(true);- try {- await sqliteService.setApiKey(keyName, value);- setApiKeys({ ...apiKeys, [keyName]: value });- setMessage({ type: 'success', text: `${keyName} saved` });- } catch (error) {- setMessage({ type: 'error', text: 'Failed to save' });- } finally {- setLoading(false);- setTimeout(() => setMessage(null), 3000);- }- };-- const loadLLMConfigs = async () => {- try {- let configs = await sqliteService.getLLMConfigs();-- // Initialize Fincept LLM as default if no configs exist- if (configs.length === 0) {- // Try to get API key from session profile- const userApiKey = session?.api_key || '';-- const now = new Date().toISOString();- const finceptConfig = {- provider: 'fincept',- api_key: userApiKey,- base_url: 'https://finceptbackend.share.zrok.io/research/llm',- model: 'fincept-llm',- is_active: true,- created_at: now,- updated_at: now,- };- await sqliteService.saveLLMConfig(finceptConfig);- configs = await sqliteService.getLLMConfigs();- }-- setLlmConfigs(configs);-- const globalSettings = await sqliteService.getLLMGlobalSettings();- setLlmGlobalSettings(globalSettings);-- const activeConfig = configs.find(c => c.is_active);- if (activeConfig) {- setActiveProvider(activeConfig.provider);- }-- // Load model configs (multi-model support)- const modelCfgs = await sqliteService.getLLMModelConfigs();- setModelConfigs(modelCfgs);- } catch (error) {- console.error('Failed to load LLM configs:', error);- }- };-- // Add a new model configuration- const handleAddModelConfig = async () => {- if (!newModelConfig.model_id) {- showMessage('error', 'Model ID is required');- return;- }-- try {- setLoading(true);- const id = crypto.randomUUID();- const displayName = newModelConfig.display_name || `${newModelConfig.provider.toUpperCase()}: ${newModelConfig.model_id}`;-- const result = await sqliteService.saveLLMModelConfig({- id,- provider: newModelConfig.provider,- model_id: newModelConfig.model_id,- display_name: displayName,- api_key: newModelConfig.api_key || undefined,- base_url: newModelConfig.base_url || undefined,- is_enabled: true,- is_default: modelConfigs.filter(m => m.provider === newModelConfig.provider).length === 0- });-- if (result.success) {- showMessage('success', 'Model configuration added');- setNewModelConfig({- provider: 'openai',- model_id: '',- display_name: '',- api_key: '',- base_url: ''- });- setShowAddModel(false);- await loadLLMConfigs();- } else {- showMessage('error', result.message);- }- } catch (error) {- showMessage('error', 'Failed to add model configuration');- } finally {- setLoading(false);- }- };-- // Delete a model configuration- const handleDeleteModelConfig = async (id: string) => {- try {- setLoading(true);- const result = await sqliteService.deleteLLMModelConfig(id);- if (result.success) {- showMessage('success', 'Model configuration deleted');- await loadLLMConfigs();- } else {- showMessage('error', result.message);- }- } catch (error) {- showMessage('error', 'Failed to delete model configuration');- } finally {- setLoading(false);- }- };-- // Toggle model enabled state- const handleToggleModelEnabled = async (id: string) => {- try {- const result = await sqliteService.toggleLLMModelConfigEnabled(id);- if (result.success) {- await loadLLMConfigs();- }- } catch (error) {- showMessage('error', 'Failed to toggle model');- }- };--- const handleSaveLLMConfig = async () => {- try {- setLoading(true);-- // Check if a custom model from Model Library is selected- if (activeProvider.startsWith('model:')) {- const modelId = activeProvider.replace('model:', '');- const selectedModel = modelConfigs.find(m => m.id === modelId);-- if (selectedModel) {- // Get the provider's default base URL based on provider type- const getProviderBaseUrl = (provider: string): string => {- const providerUrls: Record<string, string> = {- 'openai': 'https://api.openai.com/v1',- 'anthropic': 'https://api.anthropic.com/v1',- 'google': 'https://generativelanguage.googleapis.com/v1beta',- 'gemini': 'https://generativelanguage.googleapis.com/v1beta',- 'groq': 'https://api.groq.com/openai/v1',- 'deepseek': 'https://api.deepseek.com/v1',- 'openrouter': 'https://openrouter.ai/api/v1'- };- return providerUrls[provider] || 'https://openrouter.ai/api/v1';- };-- // Create/update an LLM config based on the custom model- // Use the model's native provider (google, anthropic, etc.) instead of routing through OpenRouter- const modelLLMConfig: LLMConfig = {- provider: selectedModel.provider, // Use the actual provider- api_key: selectedModel.api_key || '',- base_url: selectedModel.base_url || getProviderBaseUrl(selectedModel.provider),- model: selectedModel.model_id.includes('/')- ? selectedModel.model_id.split('/').pop() || selectedModel.model_id // Extract model name from "provider/model" format- : selectedModel.model_id,- is_active: true,- created_at: new Date().toISOString(),- updated_at: new Date().toISOString()- };-- // Save the provider config with the custom model- await sqliteService.saveLLMConfig(modelLLMConfig);- await sqliteService.setActiveLLMProvider(selectedModel.provider);- }- } else {- // Save all provider configs- for (const config of llmConfigs) {- await sqliteService.saveLLMConfig(config);- }-- // Set active provider- await sqliteService.setActiveLLMProvider(activeProvider);- }-- // Save global settings- await sqliteService.saveLLMGlobalSettings(llmGlobalSettings);-- showMessage('success', 'LLM configuration saved successfully');- await loadLLMConfigs();- } catch (error) {- showMessage('error', 'Failed to save LLM configuration');- } finally {- setLoading(false);- }- };-- const updateLLMConfig = (provider: string, field: keyof LLMConfig, value: any) => {- setLlmConfigs(prev => prev.map(config =>- config.provider === provider ? { ...config, [field]: value } : config- ));- };-- const fetchOllamaModels = async () => {- setOllamaLoading(true);- setOllamaError(null);-- const currentConfig = getCurrentLLMConfig();- const baseUrl = currentConfig?.base_url || 'http://localhost:11434';-- const result = await ollamaService.listModels(baseUrl);-- if (result.success && result.models) {- setOllamaModels(result.models);- setOllamaError(null);- } else {- setOllamaModels([]);- setOllamaError(result.error || 'Failed to fetch models');- }-- setOllamaLoading(false);- };-- /**- * Fetch models from provider API- */- const fetchProviderModels = async (forceRefresh: boolean = false) => {- const currentConfig = getCurrentLLMConfig();- if (!currentConfig) return;-- const provider = currentConfig.provider;-- // Skip if provider is Ollama (handled separately) or Fincept (auto-configured)- if (provider === 'ollama' || provider === 'fincept') return;-- // Load fallback models immediately for instant display- if (!forceRefresh && providerModels.length === 0) {- const fallbackModels = LLMModelsService.getFallbackModels(provider);- setProviderModels(fallbackModels);- console.log(`[SettingsTab] Loaded ${fallbackModels.length} fallback models for ${provider}`);- }-- // Then fetch from API in background- setProviderModelsLoading(true);- setProviderModelsError(null);-- try {- const result = await LLMModelsService.getModels(- provider,- currentConfig.api_key || undefined,- currentConfig.base_url || undefined- );-- if (result.models && result.models.length > 0) {- setProviderModels(result.models);- setProviderModelsError(null);- console.log(`[SettingsTab] Loaded ${result.models.length} models from API for ${provider}`);- } else if (result.error) {- setProviderModelsError(result.error);- // Keep fallback models if API fails- if (providerModels.length === 0) {- setProviderModels(LLMModelsService.getFallbackModels(provider));- }- } else {- setProviderModels([]);- setProviderModelsError('No models available for this provider');- }- } catch (error) {- console.error(`[SettingsTab] Error fetching models for ${provider}:`, error);- setProviderModelsError(error instanceof Error ? error.message : 'Failed to fetch models');- // Keep fallback models on error- if (providerModels.length === 0) {- setProviderModels(LLMModelsService.getFallbackModels(provider));- }- } finally {- setProviderModelsLoading(false);- }- };-- // Fetch models when switching provider- useEffect(() => {- const loadModels = async () => {- if (activeSection !== 'llm') return;-- const currentConfig = getCurrentLLMConfig();- if (!currentConfig) return;-- const provider = currentConfig.provider;-- // Reset models when changing provider- setProviderModels([]);- setProviderModelsError(null);-- if (provider === 'ollama') {- fetchOllamaModels();- } else if (provider !== 'fincept') {- // Load fallback models immediately- const fallbackModels = LLMModelsService.getFallbackModels(provider);- setProviderModels(fallbackModels);- console.log(`[SettingsTab] Loaded ${fallbackModels.length} models for ${provider}`);-- // Then fetch from API- setProviderModelsLoading(true);- try {- const result = await LLMModelsService.getModels(- provider,- currentConfig.api_key || undefined,- currentConfig.base_url || undefined- );- if (result.models && result.models.length > 0) {- setProviderModels(result.models);- }- } catch (error) {- console.error('Error fetching models:', error);- } finally {- setProviderModelsLoading(false);- }- }- };-- loadModels();- }, [activeProvider, activeSection]);-- // Fetch models for new model config when provider changes- useEffect(() => {- const loadNewModelConfigModels = async () => {- if (!showAddModel) return;-- try {- // Use OpenRouter to get all models for the selected provider- const models = await LLMModelsService.getOpenRouterModelsByProvider(newModelConfig.provider);- if (models && models.length > 0) {- setNewModelConfigModels(models);- console.log(`[SettingsTab] Loaded ${models.length} ${newModelConfig.provider} models from OpenRouter`);- } else {- setNewModelConfigModels(LLMModelsService.getFallbackModels(newModelConfig.provider));- }- } catch (error) {- console.error('[SettingsTab] Failed to fetch models:', error);- setNewModelConfigModels(LLMModelsService.getFallbackModels(newModelConfig.provider));- }- };-- loadNewModelConfigModels();- }, [newModelConfig.provider, showAddModel]);-- const togglePasswordVisibility = (id: number) => {- setShowPasswords(prev => ({ ...prev, [id]: !prev[id] }));- };-- const showMessage = (type: 'success' | 'error', text: string) => {- setMessage({ type, text });- setTimeout(() => setMessage(null), 5000);- };-- const getCurrentLLMConfig = () => {- // Check if it's a custom model from Model Library- if (activeProvider.startsWith('model:')) {- const modelId = activeProvider.replace('model:', '');- const modelConfig = modelConfigs.find(m => m.id === modelId);- if (modelConfig) {- // Convert LLMModelConfig to LLMConfig format- return {- provider: modelConfig.provider,- api_key: modelConfig.api_key || '',- base_url: modelConfig.base_url || '',- model: modelConfig.model_id,- is_active: true,- created_at: modelConfig.created_at || new Date().toISOString(),- updated_at: modelConfig.updated_at || new Date().toISOString()- } as LLMConfig;- }- }- return llmConfigs.find(c => c.provider === activeProvider);- };-- // Get selected custom model (for display in UI)- const getSelectedModelConfig = () => {- if (activeProvider.startsWith('model:')) {- const modelId = activeProvider.replace('model:', '');- return modelConfigs.find(m => m.id === modelId);- }- return null;- };-- // Terminal appearance handlers- const handleSaveTerminalAppearance = async () => {- const newTheme = {- font: {- family: fontFamily,- baseSize: baseSize,- weight: fontWeight,- italic: fontItalic- },- colors: COLOR_THEMES[selectedTheme]- };- updateTheme(newTheme);-- // Save key mappings to storage- await saveSetting('fincept_key_mappings', JSON.stringify(keyMappings), 'settings');-- showMessage('success', 'Terminal appearance and key mappings saved successfully');- };-- const handleResetTerminalAppearance = async () => {- resetTheme();- const defaultTheme = terminalThemeService.getTheme();- setFontFamily(defaultTheme.font.family);- setBaseSize(defaultTheme.font.baseSize);- setFontWeight(defaultTheme.font.weight);- setFontItalic(defaultTheme.font.italic);- setSelectedTheme('fincept-classic');-- // Reset key mappings to defaults- setKeyMappings(DEFAULT_KEY_MAPPINGS);- await saveSetting('fincept_key_mappings', '', 'settings');-- showMessage('success', 'Reset to default appearance and key mappings');- };-- // Load saved key mappings on mount- useEffect(() => {- const loadKeyMappings = async () => {- const savedMappings = await getSetting('fincept_key_mappings');- if (savedMappings) {- try {- setKeyMappings(JSON.parse(savedMappings));- } catch (err) {- console.error('Failed to load key mappings:', err);- }- }- };- loadKeyMappings();- }, []);-- return (- <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: colors.background }}>- <style>{`- *::-webkit-scrollbar { width: 8px; height: 8px; }- *::-webkit-scrollbar-track { background: ${colors.panel}; }- *::-webkit-scrollbar-thumb { background: #2a2a2a; border-radius: 4px; }- *::-webkit-scrollbar-thumb:hover { background: #3a3a3a; }-- @keyframes pulse {- 0%, 100% { opacity: 1; }- 50% { opacity: 0.5; }- }-- @keyframes spin {- from { transform: rotate(0deg); }- to { transform: rotate(360deg); }- }-- @keyframes slideIn {- from { transform: translateX(-10px); opacity: 0; }- to { transform: translateX(0); opacity: 1; }- }- `}</style>-- {/* Header */}- <div style={{- borderBottom: `2px solid ${colors.primary}`,- padding: '12px 16px',- background: `linear-gradient(180deg, #1a1a1a 0%, ${colors.panel} 100%)`,- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center',- flexShrink: 0- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>- <SettingsIcon size={20} color={colors.primary} />- <span style={{ color: colors.primary, fontSize: '16px', fontWeight: 'bold', letterSpacing: '1px' }}>- {t('title')}- </span>- </div>- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>- <div style={{- padding: '4px 8px',- background: dbInitialized ? '#0a3a0a' : '#3a0a0a',- border: `1px solid ${dbInitialized ? '#00ff00' : '#ff0000'}`,- borderRadius: '3px'- }}>- <span style={{ color: dbInitialized ? '#00ff00' : '#ff0000', fontSize: '9px', fontWeight: 'bold' }}>- <Database size={10} style={{ display: 'inline', marginRight: '4px' }} />- SQLite: {dbInitialized ? t('llm.connected') : t('llm.disconnected')}- </span>- </div>- </div>- </div>-- {/* Message Banner */}- {message && (- <div style={{- padding: '8px 16px',- background: message.type === 'success' ? '#0a3a0a' : '#3a0a0a',- borderBottom: `1px solid ${message.type === 'success' ? '#00ff00' : '#ff0000'}`,- color: message.type === 'success' ? '#00ff00' : '#ff0000',- fontSize: '10px',- flexShrink: 0- }}>- {message.text}- </div>- )}-- {/* Main Layout */}- <div style={{ flex: 1, display: 'flex', minHeight: 0, overflow: 'hidden' }}>-- {/* Sidebar Navigation */}- <div style={{ width: '220px', borderRight: '1px solid #1a1a1a', background: colors.panel, flexShrink: 0 }}>- <div style={{ padding: '16px 0' }}>- {[- { id: 'credentials', icon: Lock, label: t('sidebar.credentials') },- { id: 'polymarket', icon: TrendingUp, label: t('sidebar.polymarket') },- { id: 'llm', icon: Bot, label: t('sidebar.llm') },- { id: 'dataConnections', icon: Database, label: t('sidebar.dataSources') },- { id: 'backtesting', icon: Activity, label: t('sidebar.backtesting') },- { id: 'stockSymbols', icon: Briefcase, label: 'Stock Symbols' },- { id: 'terminalConfig', icon: SettingsIcon, label: t('sidebar.tabLayout') },- { id: 'terminal', icon: Terminal, label: t('sidebar.appearance') },- { id: 'language', icon: Globe, label: t('sidebar.language') }- ].map((item) => (- <div- key={item.id}- onClick={() => setActiveSection(item.id as any)}- style={{- padding: '12px 16px',- cursor: 'pointer',- background: activeSection === item.id ? '#1a1a1a' : 'transparent',- borderLeft: activeSection === item.id ? `3px solid ${colors.primary}` : '3px solid transparent',- display: 'flex',- alignItems: 'center',- gap: '12px',- transition: 'all 0.2s'- }}- onMouseEnter={(e) => {- if (activeSection !== item.id) e.currentTarget.style.background = '#151515';- }}- onMouseLeave={(e) => {- if (activeSection !== item.id) e.currentTarget.style.background = 'transparent';- }}- >- <item.icon size={16} color={activeSection === item.id ? colors.primary : colors.text} />- <span style={{ color: colors.text, fontSize: '11px', fontWeight: activeSection === item.id ? 'bold' : 'normal' }}>- {item.label}- </span>- </div>- ))}- </div>- </div>-- {/* Main Content */}- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, overflow: 'hidden' }}>- <div style={{ flex: 1, overflowY: 'auto', padding: '20px', minHeight: 0 }}>-- {/* Credentials Section - Predefined API Keys */}- {activeSection === 'credentials' && (- <div>- <div style={{ marginBottom: '24px' }}>- <h2 style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>- {t('credentials.title')}- </h2>- <p style={{ color: colors.text, fontSize: '10px' }}>- {t('credentials.description')}- </p>- </div>-- {/* Predefined API Key Fields */}- <div style={{ display: 'grid', gap: '16px' }}>- {PREDEFINED_API_KEYS.map(({ key, label, description }) => (- <div- key={key}- style={{- background: colors.panel,- border: '1px solid #1a1a1a',- padding: '16px',- borderRadius: '4px'- }}- >- <h3 style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>- {label}- </h3>- <p style={{ color: colors.text, fontSize: '9px', marginBottom: '12px', opacity: 0.7 }}>- {description}- </p>-- <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '12px', alignItems: 'end' }}>- <div>- <label style={{ color: colors.text, fontSize: '9px', display: 'block', marginBottom: '4px' }}>- {t('credentials.apiKey')}- </label>- <input- type="password"- value={apiKeys[key] || ''}- onChange={(e) => setApiKeys({ ...apiKeys, [key]: e.target.value })}- placeholder={t('credentials.enterValue')}- style={{- width: '100%',- background: colors.background,- border: '1px solid #2a2a2a',- color: colors.text,- padding: '8px',- fontSize: '10px',- borderRadius: '3px',- fontFamily: 'monospace'- }}- />- </div>- <button- onClick={() => handleSaveApiKeyField(key, apiKeys[key] || '')}- disabled={loading || !apiKeys[key]}- style={{- background: apiKeys[key] ? colors.primary : '#333',- color: colors.text,- border: 'none',- padding: '8px 16px',- fontSize: '10px',- fontWeight: 'bold',- cursor: (loading || !apiKeys[key]) ? 'not-allowed' : 'pointer',- borderRadius: '3px',- display: 'flex',- alignItems: 'center',- gap: '6px',- opacity: (loading || !apiKeys[key]) ? 0.5 : 1,- whiteSpace: 'nowrap'- }}- >- <Save size={14} />- {t('buttons.save')}- </button>- </div>- </div>- ))}- </div>- </div>- )}-- {/* Polymarket API Section */}- {activeSection === 'polymarket' && (- <PolymarketCredentialsPanel />- )}-- {/* LLM Configuration Section - Fincept Style */}- {activeSection === 'llm' && (- <div style={{- fontFamily: '"IBM Plex Mono", "Consolas", monospace',- display: 'flex',- flexDirection: 'column',- gap: '20px'- }}>- {/* Header */}- <div style={{- borderBottom: `2px solid ${colors.primary}`,- padding: '16px 0',- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>- <Bot size={24} color={colors.primary} />- <div>- <div style={{- color: colors.primary,- fontWeight: 700,- fontSize: '16px',- letterSpacing: '0.5px',- }}>- LLM CONFIGURATION- </div>- <div style={{ color: '#888', fontSize: '12px', marginTop: '2px' }}>- Configure AI providers, models, and global settings- </div>- </div>- </div>- <button- onClick={handleSaveLLMConfig}- disabled={loading}- style={{- background: loading ? '#2A2A2A' : colors.primary,- color: loading ? '#666' : '#000',- border: 'none',- padding: '10px 20px',- fontSize: '12px',- fontWeight: 700,- letterSpacing: '0.5px',- cursor: loading ? 'not-allowed' : 'pointer',- display: 'flex',- alignItems: 'center',- gap: '8px'- }}- >- <Save size={14} />- {loading ? 'SAVING...' : 'SAVE ALL SETTINGS'}- </button>- </div>-- {/* Provider Selection */}- <div style={{- backgroundColor: '#0F0F0F',- border: `1px solid #2A2A2A`,- padding: '20px'- }}>- <div style={{- color: colors.primary,- fontSize: '13px',- fontWeight: 700,- marginBottom: '16px',- letterSpacing: '0.5px',- display: 'flex',- alignItems: 'center',- gap: '8px'- }}>- <Zap size={16} color={colors.primary} />- SELECT AI PROVIDER- </div>-- {/* Main Provider Buttons */}- <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap', marginBottom: '16px' }}>- {llmConfigs.map(config => (- <button- key={config.provider}- onClick={() => setActiveProvider(config.provider)}- style={{- padding: '12px 20px',- backgroundColor: activeProvider === config.provider ? colors.primary : '#1A1A1A',- border: `2px solid ${activeProvider === config.provider ? colors.primary : '#2A2A2A'}`,- color: activeProvider === config.provider ? '#000' : '#FFF',- cursor: 'pointer',- fontSize: '13px',- fontWeight: 700,- letterSpacing: '0.5px',- transition: 'all 0.2s',- display: 'flex',- alignItems: 'center',- gap: '8px'- }}- onMouseEnter={(e) => {- if (activeProvider !== config.provider) {- e.currentTarget.style.borderColor = colors.primary;- e.currentTarget.style.backgroundColor = '#252525';- }- }}- onMouseLeave={(e) => {- if (activeProvider !== config.provider) {- e.currentTarget.style.borderColor = '#2A2A2A';- e.currentTarget.style.backgroundColor = '#1A1A1A';- }- }}- >- {config.provider === 'fincept' && <span style={{ color: activeProvider === config.provider ? '#000' : colors.success }}>●</span>}- {config.provider.toUpperCase()}- </button>- ))}- </div>-- {/* Custom Models from Model Library */}- {modelConfigs.filter(m => m.is_enabled).length > 0 && (- <div>- <div style={{- color: '#888',- fontSize: '11px',- fontWeight: 600,- marginBottom: '10px',- letterSpacing: '0.5px',- display: 'flex',- alignItems: 'center',- gap: '8px'- }}>- <Bot size={14} color="#888" />- CUSTOM MODELS (from Model Library)- </div>- <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>- {modelConfigs.filter(m => m.is_enabled).map(model => {- const isSelected = activeProvider === `model:${model.id}`;- return (- <button- key={model.id}- onClick={() => setActiveProvider(`model:${model.id}`)}- style={{- padding: '10px 16px',- backgroundColor: isSelected ? colors.secondary : '#1A1A1A',- border: `2px solid ${isSelected ? colors.secondary : '#2A2A2A'}`,- color: isSelected ? '#000' : '#FFF',- cursor: 'pointer',- fontSize: '12px',- fontWeight: 600,- letterSpacing: '0.5px',- transition: 'all 0.2s',- display: 'flex',- alignItems: 'center',- gap: '8px'- }}- onMouseEnter={(e) => {- if (!isSelected) {- e.currentTarget.style.borderColor = colors.secondary;- e.currentTarget.style.backgroundColor = '#252525';- }- }}- onMouseLeave={(e) => {- if (!isSelected) {- e.currentTarget.style.borderColor = '#2A2A2A';- e.currentTarget.style.backgroundColor = '#1A1A1A';- }- }}- >- <span style={{- padding: '2px 6px',- background: colors.primary + '30',- border: `1px solid ${colors.primary}`,- fontSize: '9px',- fontWeight: 700,- color: colors.primary- }}>- {model.provider.toUpperCase()}- </span>- {model.display_name || model.model_id.split('/').pop()}- </button>- );- })}- </div>- </div>- )}- </div>-- {/* Main Content Grid */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>- {/* Left Column - Provider Config */}- <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>- {/* Fincept Auto-Configured */}- {getCurrentLLMConfig() && getCurrentLLMConfig()!.provider === 'fincept' && (- <div style={{- backgroundColor: '#0a2a0a',- border: `2px solid ${colors.success}`,- padding: '20px'- }}>- <div style={{- display: 'flex',- alignItems: 'center',- gap: '10px',- marginBottom: '12px'- }}>- <Check size={20} color={colors.success} />- <span style={{ color: colors.success, fontSize: '14px', fontWeight: 700 }}>- FINCEPT LLM - AUTO CONFIGURED- </span>- </div>- <div style={{ color: '#AAA', fontSize: '12px', lineHeight: 1.6 }}>- <div style={{ marginBottom: '8px' }}>- Your Fincept API is automatically configured and ready to use.- </div>- <div style={{- display: 'flex',- alignItems: 'center',- gap: '16px',- padding: '12px',- backgroundColor: '#000',- border: `1px solid #2A2A2A`- }}>- <div>- <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>API KEY</div>- <div style={{ color: colors.primary, fontSize: '12px', fontFamily: 'monospace' }}>- {session?.api_key?.substring(0, 12)}...- </div>- </div>- <div>- <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>COST</div>- <div style={{ color: '#FFF', fontSize: '12px' }}>5 credits/response</div>- </div>- <div>- <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>MODEL</div>- <div style={{ color: '#FFF', fontSize: '12px' }}>fincept-llm</div>- </div>- </div>- </div>- </div>- )}-- {/* Custom Model from Model Library */}- {getSelectedModelConfig() && (- <div style={{- backgroundColor: '#0a1a2a',- border: `2px solid ${colors.secondary}`,- padding: '20px'- }}>- <div style={{- display: 'flex',- alignItems: 'center',- gap: '10px',- marginBottom: '12px'- }}>- <Bot size={20} color={colors.secondary} />- <span style={{ color: colors.secondary, fontSize: '14px', fontWeight: 700 }}>- CUSTOM MODEL - {getSelectedModelConfig()!.display_name || getSelectedModelConfig()!.model_id}- </span>- </div>- <div style={{ color: '#AAA', fontSize: '12px', lineHeight: 1.6 }}>- <div style={{ marginBottom: '8px' }}>- This model uses the native <strong style={{ color: colors.primary }}>{getSelectedModelConfig()!.provider.toUpperCase()}</strong> API directly.- </div>- <div style={{- display: 'flex',- alignItems: 'center',- gap: '16px',- padding: '12px',- backgroundColor: '#000',- border: `1px solid #2A2A2A`,- flexWrap: 'wrap'- }}>- <div>- <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>PROVIDER</div>- <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 600 }}>- {getSelectedModelConfig()!.provider.toUpperCase()}- </div>- </div>- <div>- <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>MODEL</div>- <div style={{ color: '#FFF', fontSize: '12px', fontFamily: 'monospace' }}>- {getSelectedModelConfig()!.model_id.includes('/')- ? getSelectedModelConfig()!.model_id.split('/').pop()- : getSelectedModelConfig()!.model_id}- </div>- </div>- <div>- <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>API KEY</div>- <div style={{ color: getSelectedModelConfig()!.api_key ? colors.success : colors.alert, fontSize: '12px' }}>- {getSelectedModelConfig()!.api_key ? 'Custom key set' : 'No API key'}- </div>- </div>- </div>- {!getSelectedModelConfig()!.api_key && (- <div style={{- marginTop: '12px',- padding: '10px',- background: '#3a0a0a',- border: `1px solid ${colors.alert}`,- color: colors.alert,- fontSize: '11px'- }}>- ⚠️ No API key set for this model. Add your {getSelectedModelConfig()!.provider.toUpperCase()} API key in the Model Library or main provider config.- </div>- )}- </div>- </div>- )}-- {/* Provider Configuration */}- {getCurrentLLMConfig() && getCurrentLLMConfig()!.provider !== 'fincept' && !getSelectedModelConfig() && (- <div style={{- backgroundColor: '#0F0F0F',- border: `1px solid #2A2A2A`,- padding: '20px'- }}>- <div style={{- color: colors.primary,- fontSize: '13px',- fontWeight: 700,- marginBottom: '20px',- letterSpacing: '0.5px',- display: 'flex',- alignItems: 'center',- gap: '8px',- paddingBottom: '12px',- borderBottom: `1px solid #2A2A2A`- }}>- <Key size={16} color={colors.primary} />- {getCurrentLLMConfig()!.provider.toUpperCase()} CONFIGURATION- </div>-- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>- {/* API Key */}- {getCurrentLLMConfig()!.provider !== 'ollama' && (- <div>- <label style={{- color: '#FFF',- fontSize: '11px',- display: 'block',- marginBottom: '8px',- fontWeight: 600,- letterSpacing: '0.5px'- }}>- API KEY <span style={{ color: colors.alert }}>*</span>- </label>- <input- type="password"- value={getCurrentLLMConfig()!.api_key || ''}- onChange={(e) => updateLLMConfig(activeProvider, 'api_key', e.target.value)}- placeholder={`Enter your ${activeProvider} API key`}- style={{- width: '100%',- background: '#000',- border: `1px solid #2A2A2A`,- color: '#FFF',- padding: '12px 14px',- fontSize: '13px',- fontFamily: '"IBM Plex Mono", monospace',- outline: 'none'- }}- onFocus={(e) => { e.currentTarget.style.borderColor = colors.primary; }}- onBlur={(e) => { e.currentTarget.style.borderColor = '#2A2A2A'; }}- />- </div>- )}-- {/* Base URL */}- {(getCurrentLLMConfig()!.provider === 'ollama' || getCurrentLLMConfig()!.provider === 'deepseek' || getCurrentLLMConfig()!.provider === 'openrouter') && (- <div>- <label style={{- color: '#FFF',- fontSize: '11px',- display: 'block',- marginBottom: '8px',- fontWeight: 600,- letterSpacing: '0.5px'- }}>- BASE URL- </label>- <input- type="text"- value={getCurrentLLMConfig()!.base_url || ''}- onChange={(e) => updateLLMConfig(activeProvider, 'base_url', e.target.value)}- placeholder={getCurrentLLMConfig()!.provider === 'ollama' ? 'http://localhost:11434' : 'https://api.example.com'}- style={{- width: '100%',- background: '#000',- border: `1px solid #2A2A2A`,- color: '#FFF',- padding: '12px 14px',- fontSize: '13px',- fontFamily: '"IBM Plex Mono", monospace',- outline: 'none'- }}- onFocus={(e) => { e.currentTarget.style.borderColor = colors.primary; }}- onBlur={(e) => { e.currentTarget.style.borderColor = '#2A2A2A'; }}- />- </div>- )}-- {/* Model */}- <div>- <div style={{- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center',- marginBottom: '8px'- }}>- <label style={{- color: '#FFF',- fontSize: '11px',- fontWeight: 600,- letterSpacing: '0.5px'- }}>- MODEL- </label>- <div style={{ display: 'flex', gap: '8px' }}>- {getCurrentLLMConfig()!.provider === 'ollama' ? (- <button- onClick={fetchOllamaModels}- disabled={ollamaLoading}- style={{- background: '#1A1A1A',- border: `1px solid #2A2A2A`,- color: colors.primary,- padding: '6px 12px',- fontSize: '11px',- cursor: ollamaLoading ? 'not-allowed' : 'pointer',- display: 'flex',- alignItems: 'center',- gap: '6px',- fontWeight: 600- }}- >- <RefreshCw size={12} className={ollamaLoading ? 'animate-spin' : ''} />- {ollamaLoading ? 'LOADING...' : 'REFRESH MODELS'}- </button>- ) : getCurrentLLMConfig()!.provider !== 'fincept' && (- <button- onClick={() => fetchProviderModels(true)}- disabled={providerModelsLoading}- style={{- background: '#1A1A1A',- border: `1px solid #2A2A2A`,- color: colors.primary,- padding: '6px 12px',- fontSize: '11px',- cursor: providerModelsLoading ? 'not-allowed' : 'pointer',- display: 'flex',- alignItems: 'center',- gap: '6px',- fontWeight: 600- }}- >- <RefreshCw size={12} className={providerModelsLoading ? 'animate-spin' : ''} />- {providerModelsLoading ? 'LOADING...' : 'REFRESH MODELS'}- </button>- )}- <button- onClick={() => setUseManualEntry(!useManualEntry)}- style={{- background: useManualEntry ? colors.primary : '#1A1A1A',- border: `1px solid ${useManualEntry ? colors.primary : '#2A2A2A'}`,- color: useManualEntry ? '#000' : '#FFF',- padding: '6px 12px',- fontSize: '11px',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '6px',- fontWeight: 600- }}- >- <Edit3 size={12} />- {useManualEntry ? 'USE DROPDOWN' : 'MANUAL ENTRY'}- </button>- </div>- </div>-- {!useManualEntry ? (- <div>- <select- value={getCurrentLLMConfig()!.model}- onChange={(e) => updateLLMConfig(activeProvider, 'model', e.target.value)}- disabled={- (getCurrentLLMConfig()!.provider === 'ollama' && (ollamaLoading || ollamaModels.length === 0)) ||- (getCurrentLLMConfig()!.provider !== 'ollama' && getCurrentLLMConfig()!.provider !== 'fincept' && (providerModelsLoading || providerModels.length === 0))- }- style={{- width: '100%',- background: '#000',- border: `1px solid #2A2A2A`,- color: '#FFF',- padding: '12px 14px',- fontSize: '13px',- cursor: 'pointer'- }}- >- {getCurrentLLMConfig()!.provider === 'ollama' ? (- <>- {ollamaModels.length === 0 && !ollamaLoading && <option value="">No models found - Click REFRESH</option>}- {ollamaLoading && <option value="">Loading models...</option>}- {ollamaModels.map((model) => (- <option key={model} value={model}>{model}</option>- ))}- </>- ) : (- <>- {providerModels.length === 0 && !providerModelsLoading && <option value="">No models found - Click REFRESH</option>}- {providerModelsLoading && <option value="">Loading models...</option>}- {providerModels.map((model) => (- <option key={model.id} value={model.id}>- {model.name} {model.context_window ? `(${(model.context_window / 1000).toFixed(0)}K)` : ''}- </option>- ))}- </>- )}- </select>- {getCurrentLLMConfig()!.provider === 'ollama' && ollamaError && (- <div style={{- marginTop: '8px',- padding: '10px 12px',- background: '#3a0a0a',- border: `1px solid ${colors.alert}`,- fontSize: '12px',- color: colors.alert- }}>- {ollamaError}- </div>- )}- {getCurrentLLMConfig()!.provider !== 'ollama' && providerModelsError && (- <div style={{- marginTop: '8px',- padding: '10px 12px',- background: '#3a0a0a',- border: `1px solid ${colors.alert}`,- fontSize: '12px',- color: colors.alert- }}>- {providerModelsError}- </div>- )}- {getCurrentLLMConfig()!.provider === 'ollama' && ollamaModels.length > 0 && (- <div style={{- marginTop: '8px',- fontSize: '12px',- color: colors.success,- display: 'flex',- alignItems: 'center',- gap: '6px'- }}>- <Check size={14} />- {ollamaModels.length} model{ollamaModels.length !== 1 ? 's' : ''} available- </div>- )}- {getCurrentLLMConfig()!.provider !== 'ollama' && getCurrentLLMConfig()!.provider !== 'fincept' && providerModels.length > 0 && (- <div style={{- marginTop: '8px',- fontSize: '11px',- color: '#AAA',- display: 'flex',- flexDirection: 'column',- gap: '4px'- }}>- <div style={{- display: 'flex',- alignItems: 'center',- gap: '6px',- color: colors.success- }}>- <Check size={14} />- {providerModels.length} model{providerModels.length !== 1 ? 's' : ''} available- </div>- <div style={{ fontSize: '10px', color: '#666' }}>- Models fetched from {getCurrentLLMConfig()!.provider.toUpperCase()} API- {providerModelsLoading && ' (updating...)'}- </div>- </div>- )}- </div>- ) : (- <input- type="text"- value={getCurrentLLMConfig()!.model}- onChange={(e) => updateLLMConfig(activeProvider, 'model', e.target.value)}- placeholder="Enter model name (e.g., gpt-4, claude-3-sonnet)"- style={{- width: '100%',- background: '#000',- border: `1px solid #2A2A2A`,- color: '#FFF',- padding: '12px 14px',- fontSize: '13px',- outline: 'none'- }}- onFocus={(e) => { e.currentTarget.style.borderColor = colors.primary; }}- onBlur={(e) => { e.currentTarget.style.borderColor = '#2A2A2A'; }}- />- )}- </div>- </div>- </div>- )}-- {/* Global Settings */}- <div style={{- backgroundColor: '#0F0F0F',- border: `1px solid #2A2A2A`,- padding: '20px'- }}>- <div style={{- color: colors.primary,- fontSize: '13px',- fontWeight: 700,- marginBottom: '20px',- letterSpacing: '0.5px',- display: 'flex',- alignItems: 'center',- gap: '8px',- paddingBottom: '12px',- borderBottom: `1px solid #2A2A2A`- }}>- <SettingsIcon size={16} color={colors.primary} />- GLOBAL SETTINGS- </div>-- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>- {/* Temperature */}- <div>- <label style={{- color: '#FFF',- fontSize: '11px',- display: 'block',- marginBottom: '8px',- fontWeight: 600,- letterSpacing: '0.5px'- }}>- TEMPERATURE (Creativity)- </label>- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>- <input- type="range"- min="0"- max="2"- step="0.1"- value={llmGlobalSettings.temperature}- onChange={(e) => setLlmGlobalSettings({ ...llmGlobalSettings, temperature: parseFloat(e.target.value) })}- style={{ flex: 1, height: '6px', cursor: 'pointer' }}- />- <div style={{- minWidth: '50px',- padding: '8px 12px',- background: colors.primary + '20',- border: `1px solid ${colors.primary}`,- color: colors.primary,- fontSize: '13px',- fontWeight: 700,- textAlign: 'center'- }}>- {llmGlobalSettings.temperature.toFixed(1)}- </div>- </div>- <div style={{ color: '#666', fontSize: '10px', marginTop: '6px' }}>- Lower = More focused, Higher = More creative- </div>- </div>-- {/* Max Tokens */}- <div>- <label style={{- color: '#FFF',- fontSize: '11px',- display: 'block',- marginBottom: '8px',- fontWeight: 600,- letterSpacing: '0.5px'- }}>- MAX TOKENS (Response Length)- </label>- <input- type="number"- min="1"- max="32000"- value={llmGlobalSettings.max_tokens}- onChange={(e) => setLlmGlobalSettings({ ...llmGlobalSettings, max_tokens: parseInt(e.target.value) || 2048 })}- style={{- width: '100%',- background: '#000',- border: `1px solid #2A2A2A`,- color: '#FFF',- padding: '12px 14px',- fontSize: '13px',- outline: 'none'- }}- onFocus={(e) => { e.currentTarget.style.borderColor = colors.primary; }}- onBlur={(e) => { e.currentTarget.style.borderColor = '#2A2A2A'; }}- />- </div>-- {/* System Prompt */}- <div>- <label style={{- color: '#FFF',- fontSize: '11px',- display: 'block',- marginBottom: '8px',- fontWeight: 600,- letterSpacing: '0.5px'- }}>- SYSTEM PROMPT (Optional)- </label>- <textarea- value={llmGlobalSettings.system_prompt}- onChange={(e) => setLlmGlobalSettings({ ...llmGlobalSettings, system_prompt: e.target.value })}- rows={4}- placeholder="Custom instructions for the AI assistant..."- style={{- width: '100%',- background: '#000',- border: `1px solid #2A2A2A`,- color: '#FFF',- padding: '12px 14px',- fontSize: '12px',- resize: 'vertical',- fontFamily: '"IBM Plex Mono", monospace',- lineHeight: '1.5',- outline: 'none'- }}- onFocus={(e) => { e.currentTarget.style.borderColor = colors.primary; }}- onBlur={(e) => { e.currentTarget.style.borderColor = '#2A2A2A'; }}- />- </div>- </div>- </div>- </div>-- {/* Right Column - Model Library */}- <div style={{- backgroundColor: '#0F0F0F',- border: `1px solid #2A2A2A`,- padding: '20px',- display: 'flex',- flexDirection: 'column'- }}>- {/* Header */}- <div style={{- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center',- marginBottom: '20px',- paddingBottom: '12px',- borderBottom: `1px solid #2A2A2A`- }}>- <div>- <div style={{- color: colors.primary,- fontSize: '13px',- fontWeight: 700,- letterSpacing: '0.5px',- marginBottom: '4px',- display: 'flex',- alignItems: 'center',- gap: '8px'- }}>- <Bot size={16} color={colors.primary} />- MODEL LIBRARY- </div>- <div style={{ color: '#888', fontSize: '11px' }}>- Add custom models for different use cases- </div>- </div>- <button- onClick={() => setShowAddModel(!showAddModel)}- style={{- background: showAddModel ? '#3a0a0a' : colors.primary,- color: showAddModel ? colors.alert : '#000',- border: 'none',- padding: '8px 16px',- fontSize: '12px',- fontWeight: 700,- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '6px'- }}- >- {showAddModel ? <><X size={14} /> CANCEL</> : <><Plus size={14} /> ADD MODEL</>}- </button>- </div>-- {/* Add Model Form */}- {showAddModel && (- <div style={{- background: '#000',- border: `1px solid ${colors.primary}`,- padding: '16px',- marginBottom: '16px'- }}>- <div style={{- color: colors.primary,- fontSize: '12px',- fontWeight: 700,- marginBottom: '16px',- display: 'flex',- alignItems: 'center',- gap: '8px'- }}>- <Plus size={14} />- ADD NEW MODEL CONFIGURATION- </div>- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '12px' }}>- <div>- <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>- PROVIDER- </label>- <select- value={newModelConfig.provider}- onChange={(e) => setNewModelConfig({ ...newModelConfig, provider: e.target.value })}- style={{- width: '100%',- background: '#1A1A1A',- border: `1px solid #2A2A2A`,- color: '#FFF',- padding: '10px 12px',- fontSize: '12px',- cursor: 'pointer'- }}- >- <option value="openai">OpenAI</option>- <option value="anthropic">Anthropic</option>- <option value="google">Google</option>- <option value="meta-llama">Meta (Llama)</option>- <option value="mistralai">Mistral AI</option>- <option value="x-ai">xAI (Grok)</option>- <option value="cohere">Cohere</option>- <option value="deepseek">DeepSeek</option>- <option value="qwen">Qwen (Alibaba)</option>- <option value="nvidia">NVIDIA</option>- <option value="microsoft">Microsoft</option>- <option value="perplexity">Perplexity</option>- <option value="groq">Groq</option>- <option value="ai21">AI21 Labs</option>- <option value="nousresearch">Nous Research</option>- <option value="cognitivecomputations">Cognitive Computations</option>- </select>- </div>- <div>- <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>- MODEL ID <span style={{ color: colors.alert }}>*</span>- </label>- <div style={{ display: 'flex', gap: '8px', alignItems: 'stretch' }}>- <div style={{ flex: 1 }}>- {useManualEntry ? (- <input- type="text"- value={newModelConfig.model_id}- onChange={(e) => setNewModelConfig({ ...newModelConfig, model_id: e.target.value })}- placeholder="e.g. gpt-4o or openai/gpt-4o"- style={{- width: '100%',- background: '#1A1A1A',- border: `1px solid #2A2A2A`,- color: '#FFF',- padding: '10px 12px',- fontSize: '12px'- }}- />- ) : (- <select- value={newModelConfig.model_id}- onChange={(e) => setNewModelConfig({ ...newModelConfig, model_id: e.target.value })}- style={{- width: '100%',- background: '#1A1A1A',- border: `1px solid #2A2A2A`,- color: '#FFF',- padding: '10px 12px',- fontSize: '12px',- cursor: 'pointer'- }}- >- <option value="">Select a model...</option>- {newModelConfigModels.map((model) => (- <option key={model.id} value={model.id}>- {model.name} {model.context_window ? `(${(model.context_window / 1000).toFixed(0)}K)` : ''}- </option>- ))}- </select>- )}- </div>- <button- onClick={() => setUseManualEntry(!useManualEntry)}- style={{- background: useManualEntry ? colors.primary : '#1A1A1A',- border: `1px solid ${useManualEntry ? colors.primary : '#2A2A2A'}`,- color: useManualEntry ? '#000' : colors.primary,- padding: '10px 12px',- fontSize: '9px',- cursor: 'pointer',- fontWeight: 600,- whiteSpace: 'nowrap'- }}- >- {useManualEntry ? 'DROPDOWN' : 'MANUAL'}- </button>- </div>- </div>- </div>-- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '16px' }}>- <div>- <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>- DISPLAY NAME- </label>- <input- type="text"- value={newModelConfig.display_name}- onChange={(e) => setNewModelConfig({ ...newModelConfig, display_name: e.target.value })}- placeholder="e.g. GPT-4o Mini"- style={{- width: '100%',- background: '#1A1A1A',- border: `1px solid #2A2A2A`,- color: '#FFF',- padding: '10px 12px',- fontSize: '12px'- }}- />- </div>- <div>- <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>- API KEY (Optional)- </label>- <input- type="password"- value={newModelConfig.api_key}- onChange={(e) => setNewModelConfig({ ...newModelConfig, api_key: e.target.value })}- placeholder="Uses provider key if empty"- style={{- width: '100%',- background: '#1A1A1A',- border: `1px solid #2A2A2A`,- color: '#FFF',- padding: '10px 12px',- fontSize: '12px',- fontFamily: 'monospace'- }}- />- </div>- </div>-- <button- onClick={handleAddModelConfig}- disabled={loading || !newModelConfig.model_id}- style={{- background: loading || !newModelConfig.model_id ? '#2A2A2A' : colors.success,- color: loading || !newModelConfig.model_id ? '#666' : '#000',- border: 'none',- padding: '10px 20px',- fontSize: '12px',- fontWeight: 700,- cursor: loading || !newModelConfig.model_id ? 'not-allowed' : 'pointer',- display: 'flex',- alignItems: 'center',- gap: '8px'- }}- >- <Plus size={14} />- ADD MODEL- </button>- </div>- )}-- {/* Models List */}- <div style={{ flex: 1, overflowY: 'auto' }}>- {modelConfigs.length === 0 ? (- <div style={{- padding: '40px 20px',- textAlign: 'center',- color: '#666',- border: `1px dashed #2A2A2A`,- background: '#000'- }}>- <Bot size={40} color="#2A2A2A" style={{ marginBottom: '16px' }} />- <div style={{ fontSize: '13px', marginBottom: '8px', fontWeight: 600, color: '#888' }}>- No Custom Models Configured- </div>- <div style={{ fontSize: '11px', color: '#666' }}>- Click "ADD MODEL" to add custom model configurations- </div>- </div>- ) : (- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>- {modelConfigs.map((model) => (- <div- key={model.id}- style={{- display: 'flex',- alignItems: 'center',- gap: '12px',- padding: '12px 14px',- background: model.is_enabled ? '#1A1A1A' : '#0A0A0A',- border: `1px solid ${model.is_enabled ? '#2A2A2A' : '#1A1A1A'}`,- opacity: model.is_enabled ? 1 : 0.6- }}- >- <button- onClick={() => handleToggleModelEnabled(model.id)}- style={{- background: 'transparent',- border: 'none',- cursor: 'pointer',- padding: 0- }}- >- {model.is_enabled ? (- <ToggleRight size={24} color={colors.success} />- ) : (- <ToggleLeft size={24} color="#666" />- )}- </button>- <div style={{ flex: 1 }}>- <div style={{- fontSize: '13px',- fontWeight: 600,- color: model.is_enabled ? '#FFF' : '#666',- marginBottom: '4px'- }}>- {model.display_name || model.model_id}- </div>- <div style={{- fontSize: '11px',- color: '#888',- display: 'flex',- alignItems: 'center',- gap: '8px'- }}>- <span style={{- padding: '2px 8px',- background: colors.primary + '20',- border: `1px solid ${colors.primary}`,- color: colors.primary,- fontWeight: 600,- fontSize: '10px'- }}>- {model.provider.toUpperCase()}- </span>- <span style={{ fontFamily: 'monospace' }}>{model.model_id}</span>- {model.api_key && (- <span style={{- padding: '2px 8px',- background: colors.success + '20',- border: `1px solid ${colors.success}`,- color: colors.success,- fontWeight: 600,- fontSize: '10px'- }}>- HAS KEY- </span>- )}- </div>- </div>- <div style={{ display: 'flex', gap: '8px' }}>- {model.api_key && (- <button- onClick={() => setShowApiKeys(prev => ({ ...prev, [model.id]: !prev[model.id] }))}- style={{- background: '#1A1A1A',- border: `1px solid #2A2A2A`,- color: '#888',- padding: '6px 8px',- cursor: 'pointer'- }}- >- {showApiKeys[model.id] ? <EyeOff size={14} /> : <Eye size={14} />}- </button>- )}- <button- onClick={() => handleDeleteModelConfig(model.id)}- style={{- background: '#1A1A1A',- border: `1px solid #2A2A2A`,- color: colors.alert,- padding: '6px 12px',- fontSize: '11px',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '6px',- fontWeight: 600- }}- >- <Trash2 size={12} />- DELETE- </button>- </div>- </div>- ))}- </div>- )}- </div>-- {/* Summary */}- {modelConfigs.length > 0 && (- <div style={{- marginTop: '16px',- padding: '12px 14px',- background: '#0a2a0a',- border: `1px solid ${colors.success}`,- display: 'flex',- alignItems: 'center',- gap: '10px'- }}>- <Check size={16} color={colors.success} />- <div style={{ fontSize: '12px', color: colors.success, fontWeight: 600 }}>- {modelConfigs.filter(m => m.is_enabled).length} ENABLED · {modelConfigs.length} TOTAL MODELS- </div>- </div>- )}- </div>- </div>- </div>- )}-- {/* Terminal Tab Configuration Section */}- {activeSection === 'terminalConfig' && (- <TerminalConfigPanel />- )}-- {/* Terminal Appearance Section */}- {activeSection === 'terminal' && (- <div style={{ fontFamily: '"IBM Plex Mono", "Consolas", monospace' }}>- {/* Header */}- <div style={{- display: 'flex',- alignItems: 'center',- gap: '12px',- marginBottom: '24px',- paddingBottom: '12px',- borderBottom: `2px solid ${colors.primary}`- }}>- <Terminal size={20} color={colors.primary} style={{ filter: `drop-shadow(0 0 4px ${colors.primary})` }} />- <h2 style={{- color: colors.primary,- fontSize: '16px',- fontWeight: 700,- letterSpacing: '1px',- margin: 0,- textShadow: `0 0 10px ${colors.primary}40`- }}>- {t('terminal.title')}- </h2>- </div>-- {/* Description */}- <div style={{- marginBottom: '20px',- padding: '12px',- backgroundColor: '#1A1A1A',- border: '1px solid #2A2A2A',- borderLeft: `3px solid ${colors.secondary}`- }}>- <p style={{- color: colors.textMuted,- fontSize: '10px',- margin: 0,- lineHeight: '1.6'- }}>- {t('terminal.description')}- </p>- </div>-- {/* Font Settings */}- <div style={{- background: '#0F0F0F',- border: '1px solid #2A2A2A',- borderLeft: `3px solid ${colors.primary}`,- borderRadius: '4px',- padding: '16px',- marginBottom: '20px'- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>- <Type size={18} color={colors.primary} style={{ filter: `drop-shadow(0 0 2px ${colors.primary})` }} />- <span style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', letterSpacing: '0.5px' }}>{t('terminal.currentSettings')}</span>- </div>-- {/* Font Family */}- <div style={{ marginBottom: '16px' }}>- <label style={{ color: colors.text, fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600, letterSpacing: '0.5px' }}>{t('terminal.fontFamily')}</label>- <select value={fontFamily} onChange={(e) => setFontFamily(e.target.value)} style={{- width: '100%',- padding: '10px',- background: colors.background,- border: `1px solid #2A2A2A`,- color: colors.text,- borderRadius: '3px',- fontSize: '11px',- fontWeight: 500,- cursor: 'pointer',- appearance: 'none',- backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23FFA500' d='M6 9L1 4h10z'/%3E%3C/svg%3E")`,- backgroundRepeat: 'no-repeat',- backgroundPosition: 'right 10px center',- paddingRight: '32px'- }}>- {FONT_FAMILIES.map(f => <option key={f.value} value={f.value}>{f.label}</option>)}- </select>- </div>-- {/* Base Font Size */}- <div style={{ marginBottom: '16px' }}>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>- <label style={{ color: colors.text, fontSize: '10px', fontWeight: 600, letterSpacing: '0.5px' }}>BASE FONT SIZE</label>- <span style={{- color: colors.primary,- fontSize: '12px',- fontWeight: 'bold',- padding: '2px 8px',- background: `${colors.primary}20`,- borderRadius: '3px',- border: `1px solid ${colors.primary}40`- }}>{baseSize}px</span>- </div>- <input type="range" min="9" max="18" value={baseSize} onChange={(e) => setBaseSize(Number(e.target.value))} style={{- width: '100%',- height: '6px',- background: `linear-gradient(to right, ${colors.primary}40 0%, ${colors.primary}40 ${((baseSize - 9) / 9) * 100}%, #2A2A2A ${((baseSize - 9) / 9) * 100}%, #2A2A2A 100%)`,- borderRadius: '3px',- outline: 'none',- cursor: 'pointer'- }} />- <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '6px' }}>- <span style={{ color: colors.textMuted, fontSize: '9px', fontWeight: 500 }}>Small (9px)</span>- <span style={{ color: colors.textMuted, fontSize: '9px', fontWeight: 500 }}>Large (18px)</span>- </div>- </div>-- {/* Font Weight */}- <div style={{ marginBottom: '16px' }}>- <label style={{ color: colors.text, fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600, letterSpacing: '0.5px' }}>FONT WEIGHT</label>- <select value={fontWeight} onChange={(e) => setFontWeight(e.target.value as FontSettings['weight'])} style={{- width: '100%',- padding: '10px',- background: colors.background,- border: '1px solid #2A2A2A',- color: colors.text,- borderRadius: '3px',- fontSize: '11px',- fontWeight: 500,- cursor: 'pointer',- appearance: 'none',- backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23FFA500' d='M6 9L1 4h10z'/%3E%3C/svg%3E")`,- backgroundRepeat: 'no-repeat',- backgroundPosition: 'right 10px center',- paddingRight: '32px'- }}>- <option value="normal">Normal (400)</option>- <option value="semibold">Semi-Bold (600)</option>- <option value="bold">Bold (700)</option>- </select>- </div>-- {/* Font Style */}- <div>- <label style={{- display: 'flex',- alignItems: 'center',- gap: '10px',- cursor: 'pointer',- padding: '10px',- background: fontItalic ? `${colors.primary}10` : 'transparent',- border: `1px solid ${fontItalic ? colors.primary : '#2A2A2A'}`,- borderRadius: '3px',- transition: 'all 0.2s'- }}>- <input type="checkbox" checked={fontItalic} onChange={(e) => setFontItalic(e.target.checked)} style={{ width: '16px', height: '16px', cursor: 'pointer' }} />- <span style={{ color: colors.text, fontSize: '10px', fontWeight: 600, letterSpacing: '0.5px' }}>ENABLE ITALIC STYLE</span>- </label>- </div>- </div>-- {/* Color Theme */}- <div style={{- background: '#0F0F0F',- border: '1px solid #2A2A2A',- borderLeft: `3px solid ${colors.primary}`,- borderRadius: '4px',- padding: '16px',- marginBottom: '20px'- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>- <Palette size={18} color={colors.primary} style={{ filter: `drop-shadow(0 0 2px ${colors.primary})` }} />- <span style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', letterSpacing: '0.5px' }}>COLOR THEME</span>- </div>-- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '12px' }}>- {Object.entries(COLOR_THEMES).map(([key, themeObj]) => {- const isActive = selectedTheme === key;- return (- <button- key={key}- onClick={() => setSelectedTheme(key)}- style={{- display: 'flex',- alignItems: 'center',- gap: '12px',- padding: '12px',- background: isActive ? '#1A1A1A' : 'transparent',- border: `1px solid ${isActive ? colors.primary : '#2A2A2A'}`,- borderLeft: `3px solid ${isActive ? colors.primary : '#2A2A2A'}`,- borderRadius: '3px',- cursor: 'pointer',- transition: 'all 0.2s',- position: 'relative',- overflow: 'hidden'- }}- onMouseEnter={(e) => {- if (!isActive) {- e.currentTarget.style.background = '#151515';- e.currentTarget.style.borderColor = '#3A3A3A';- }- }}- onMouseLeave={(e) => {- if (!isActive) {- e.currentTarget.style.background = 'transparent';- e.currentTarget.style.borderColor = '#2A2A2A';- }- }}- >- {/* Color Swatches */}- <div style={{ display: 'flex', gap: '6px' }}>- <div style={{- width: '24px',- height: '24px',- background: themeObj.primary,- border: '1px solid #2A2A2A',- borderRadius: '3px',- boxShadow: isActive ? `0 0 8px ${themeObj.primary}60` : 'none'- }} title="Primary" />- <div style={{- width: '24px',- height: '24px',- background: themeObj.secondary,- border: '1px solid #2A2A2A',- borderRadius: '3px',- boxShadow: isActive ? `0 0 8px ${themeObj.secondary}60` : 'none'- }} title="Secondary" />- <div style={{- width: '24px',- height: '24px',- background: themeObj.alert,- border: '1px solid #2A2A2A',- borderRadius: '3px',- boxShadow: isActive ? `0 0 8px ${themeObj.alert}60` : 'none'- }} title="Alert" />- </div>-- <span style={{- color: isActive ? colors.primary : colors.text,- fontSize: '11px',- flex: 1,- fontWeight: isActive ? 700 : 500,- letterSpacing: '0.5px'- }}>{themeObj.name}</span>-- {isActive && (- <div style={{- display: 'flex',- alignItems: 'center',- gap: '4px'- }}>- <Check size={14} color={colors.success} />- <div style={{- width: '6px',- height: '6px',- borderRadius: '50%',- background: colors.success,- boxShadow: `0 0 6px ${colors.success}`- }} />- </div>- )}-- {isActive && (- <div style={{- position: 'absolute',- top: 0,- left: 0,- right: 0,- height: '1px',- background: `linear-gradient(90deg, transparent, ${colors.primary}, transparent)`,- opacity: 0.5- }} />- )}- </button>- );- })}- </div>- </div>-- {/* Default Timezone Selection */}- <div style={{- background: '#0F0F0F',- border: '1px solid #2A2A2A',- borderLeft: `3px solid ${colors.primary}`,- borderRadius: '4px',- padding: '16px',- marginBottom: '20px'- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>- <Clock size={18} color={colors.primary} style={{ filter: `drop-shadow(0 0 2px ${colors.primary})` }} />- <span style={{ color: colors.text, fontWeight: 'bold', fontSize: '12px' }}>- DEFAULT TIMEZONE- </span>- </div>- <p style={{ color: colors.textMuted, fontSize: '10px', marginBottom: '12px' }}>- Set the default timezone displayed in the navigation bar. Dashboard widgets can use their own timezone settings.- </p>- <div style={{- display: 'grid',- gridTemplateColumns: 'repeat(4, 1fr)',- gap: '8px',- maxHeight: '280px',- overflowY: 'auto',- paddingRight: '4px'- }}>- {timezoneOptions.map((tz) => (- <button- key={tz.id}- onClick={() => setDefaultTimezone(tz.id)}- style={{- background: defaultTimezone.id === tz.id ? `${colors.primary}20` : '#1A1A1A',- border: `1px solid ${defaultTimezone.id === tz.id ? colors.primary : '#2A2A2A'}`,- borderRadius: '4px',- padding: '12px 8px',- cursor: 'pointer',- textAlign: 'center',- transition: 'all 0.2s'- }}- onMouseEnter={(e) => {- if (defaultTimezone.id !== tz.id) {- e.currentTarget.style.borderColor = colors.primary;- e.currentTarget.style.background = '#2A2A2A';- }- }}- onMouseLeave={(e) => {- if (defaultTimezone.id !== tz.id) {- e.currentTarget.style.borderColor = '#2A2A2A';- e.currentTarget.style.background = '#1A1A1A';- }- }}- >- <div style={{- color: defaultTimezone.id === tz.id ? colors.primary : colors.text,- fontWeight: 'bold',- fontSize: '11px',- marginBottom: '4px'- }}>- {tz.shortLabel}- </div>- <div style={{- color: colors.textMuted,- fontSize: '9px'- }}>- {tz.label.split('(')[0].trim()}- </div>- </button>- ))}- </div>- </div>-- {/* Key Mapping Configuration */}- <div style={{- background: '#0F0F0F',- border: '1px solid #2A2A2A',- borderLeft: `3px solid ${colors.primary}`,- borderRadius: '4px',- padding: '16px',- marginBottom: '20px'- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>- <Terminal size={18} color={colors.primary} style={{ filter: `drop-shadow(0 0 2px ${colors.primary})` }} />- <span style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', letterSpacing: '0.5px' }}>FUNCTION KEY MAPPINGS</span>- </div>-- <div style={{- marginBottom: '12px',- padding: '10px',- backgroundColor: '#1A1A1A',- border: '1px solid #2A2A2A',- borderRadius: '3px'- }}>- <p style={{- color: colors.textMuted,- fontSize: '9px',- margin: 0,- lineHeight: '1.5'- }}>- Configure which tab or action each function key (F1-F12) should trigger. Changes will be reflected in the status bar and keyboard shortcuts.- </p>- </div>-- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: '12px' }}>- {Object.entries(keyMappings).map(([key, action]) => (- <div key={key} style={{- background: '#1A1A1A',- border: '1px solid #2A2A2A',- borderRadius: '3px',- padding: '12px'- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '8px' }}>- <span style={{- backgroundColor: colors.primary,- color: '#000',- padding: '4px 8px',- fontSize: '9px',- fontWeight: 'bold',- borderRadius: '2px',- minWidth: '40px',- textAlign: 'center'- }}>- {key}- </span>- <span style={{ color: colors.textMuted, fontSize: '10px' }}>→</span>- </div>- <select- value={action}- onChange={(e) => setKeyMappings({ ...keyMappings, [key]: e.target.value })}- style={{- width: '100%',- padding: '8px',- background: colors.background,- border: '1px solid #2A2A2A',- color: colors.text,- borderRadius: '3px',- fontSize: '10px',- fontWeight: 500,- cursor: 'pointer',- appearance: 'none',- backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23FFA500' d='M6 9L1 4h10z'/%3E%3C/svg%3E")`,- backgroundRepeat: 'no-repeat',- backgroundPosition: 'right 8px center',- paddingRight: '28px'- }}- >- <option value="dashboard">Dashboard</option>- <option value="markets">Markets</option>- <option value="news">News</option>- <option value="portfolio">Portfolio</option>- <option value="analytics">Analytics</option>- <option value="watchlist">Watchlist</option>- <option value="equity-research">Equity Research</option>- <option value="screener">Screener</option>- <option value="trading">Trading</option>- <option value="chat">AI Chat</option>- <option value="fullscreen">Toggle Fullscreen</option>- <option value="profile">Profile</option>- <option value="settings">Settings</option>- <option value="forum">Forum</option>- <option value="marketplace">Marketplace</option>- </select>- </div>- ))}- </div>- </div>-- {/* Live Preview Panel */}- <div style={{- background: theme.colors.background,- border: `2px solid ${theme.colors.primary}`,- borderRadius: '4px',- padding: '20px',- marginBottom: '20px',- position: 'relative',- overflow: 'hidden'- }}>- <div style={{- position: 'absolute',- top: 0,- left: 0,- right: 0,- height: '2px',- background: `linear-gradient(90deg, transparent, ${theme.colors.primary}, transparent)`,- opacity: 0.5- }} />-- <div style={{- color: theme.colors.textMuted,- fontSize: '9px',- fontWeight: 600,- letterSpacing: '1px',- marginBottom: '12px',- opacity: 0.7- }}>- LIVE PREVIEW- </div>-- <div style={{- color: theme.colors.primary,- fontSize: `${baseSize + 2}px`,- fontFamily: `${fontFamily}, monospace`,- fontWeight: fontWeight === 'normal' ? '400' : fontWeight === 'semibold' ? '600' : '700',- fontStyle: fontItalic ? 'italic' : 'normal',- marginBottom: '12px',- letterSpacing: '0.5px'- }}>- FINCEPT TERMINAL PREVIEW- </div>-- <div style={{- color: theme.colors.text,- fontSize: `${baseSize}px`,- fontFamily: `${fontFamily}, monospace`,- fontWeight: fontWeight === 'normal' ? '400' : fontWeight === 'semibold' ? '600' : '700',- fontStyle: fontItalic ? 'italic' : 'normal',- marginBottom: '8px',- lineHeight: '1.5'- }}>- Body Text: Real-time market analysis and portfolio tracking- </div>-- <div style={{- color: theme.colors.textMuted,- fontSize: `${baseSize - 1}px`,- fontFamily: `${fontFamily}, monospace`,- fontWeight: fontWeight === 'normal' ? '400' : fontWeight === 'semibold' ? '600' : '700',- fontStyle: fontItalic ? 'italic' : 'normal',- marginBottom: '12px',- lineHeight: '1.5'- }}>- Small Text: Market data, timestamps, and metadata- </div>-- <div style={{ display: 'flex', gap: '16px', marginTop: '12px', flexWrap: 'wrap' }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>- <div style={{- width: '8px',- height: '8px',- borderRadius: '50%',- background: theme.colors.success,- boxShadow: `0 0 8px ${theme.colors.success}`- }} />- <span style={{ color: theme.colors.success, fontSize: '10px', fontWeight: 600 }}>CONNECTED</span>- </div>- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>- <div style={{- width: '8px',- height: '8px',- borderRadius: '50%',- background: theme.colors.alert,- boxShadow: `0 0 8px ${theme.colors.alert}`- }} />- <span style={{ color: theme.colors.alert, fontSize: '10px', fontWeight: 600 }}>ALERT</span>- </div>- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>- <div style={{- width: '8px',- height: '8px',- borderRadius: '50%',- background: theme.colors.warning,- boxShadow: `0 0 8px ${theme.colors.warning}`- }} />- <span style={{ color: theme.colors.warning, fontSize: '10px', fontWeight: 600 }}>WARNING</span>- </div>- </div>- </div>-- {/* Action Buttons */}- <div style={{ display: 'flex', gap: '12px' }}>- <button onClick={handleSaveTerminalAppearance} style={{- flex: 1,- background: colors.primary,- color: '#000000',- border: 'none',- padding: '14px',- fontSize: '11px',- fontWeight: 'bold',- letterSpacing: '0.5px',- borderRadius: '4px',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- gap: '8px',- transition: 'all 0.2s',- boxShadow: `0 0 12px ${colors.primary}40`- }}- onMouseEnter={(e) => {- e.currentTarget.style.boxShadow = `0 0 20px ${colors.primary}60`;- e.currentTarget.style.transform = 'translateY(-1px)';- }}- onMouseLeave={(e) => {- e.currentTarget.style.boxShadow = `0 0 12px ${colors.primary}40`;- e.currentTarget.style.transform = 'translateY(0)';- }}>- <Save size={16} /> SAVE CONFIGURATION- </button>- <button onClick={handleResetTerminalAppearance} style={{- background: 'transparent',- color: colors.textMuted,- border: `1px solid #2A2A2A`,- padding: '14px 20px',- fontSize: '11px',- fontWeight: 'bold',- letterSpacing: '0.5px',- borderRadius: '4px',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '8px',- transition: 'all 0.2s'- }}- onMouseEnter={(e) => {- e.currentTarget.style.borderColor = colors.alert;- e.currentTarget.style.color = colors.alert;- }}- onMouseLeave={(e) => {- e.currentTarget.style.borderColor = '#2A2A2A';- e.currentTarget.style.color = colors.textMuted;- }}>- <RefreshCw size={16} /> RESET- </button>- </div>- </div>- )}-- {/* Data Sources Section (Unified WebSocket + REST API) */}- {activeSection === 'dataConnections' && (- <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- }} />- )}-- {/* Stock Symbols Section */}- {activeSection === 'stockSymbols' && (- <div style={{ maxWidth: '600px' }}>- <div style={{ marginBottom: '16px' }}>- <h2 style={{ fontSize: '16px', fontWeight: 700, color: colors.text, margin: 0 }}>- Stock Symbol Database- </h2>- <p style={{ fontSize: '11px', color: colors.textMuted, marginTop: '8px', lineHeight: 1.5 }}>- Download and manage broker symbol data for fast offline search.- Symbol data includes stocks, F&O, commodities, and currency derivatives.- Update regularly to get latest instruments and expiries.- </p>- </div>- <MasterContractManager- brokers={['angelone', 'fyers']}- onUpdate={(brokerId, result) => {- if (result.success) {- setMessage({- type: 'success',- text: `${brokerId.toUpperCase()}: Downloaded ${result.symbol_count.toLocaleString()} symbols`- });- } else {- setMessage({- type: 'error',- text: `${brokerId.toUpperCase()}: ${result.message}`- });- }- setTimeout(() => setMessage(null), 5000);- }}- />- </div>- )}-- {/* Language Section */}- {activeSection === 'language' && (- <div style={{ padding: '20px' }}>- <LanguageSelector />- </div>- )}-- {/* Other sections can be added here */}-- </div>- </div>- </div>-- {/* Footer */}- <TabFooter- tabName="SETTINGS"- leftInfo={[- { label: t('footer.database'), color: colors.text },- { label: t('footer.storage'), color: colors.text },- ]}- statusInfo={t('footer.secureStorage')}- backgroundColor={colors.panel}- borderColor={colors.primary}- />- </div>- );-}diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaChart.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaChart.tsxdeleted file mode 100644index cf9bf5c95..000000000--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaChart.tsx+++ /dev/null@@ -1,251 +0,0 @@-/**- * Alpha Arena Performance Chart- * Fincept-style portfolio value chart showing all models' performance over time- */--import React, { useMemo } from 'react';-import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';-import { AlphaPerformanceSnapshot } from '@/services/core/sqliteService';--interface AlphaArenaChartProps {- snapshots: AlphaPerformanceSnapshot[];- initialCapital?: number;-}--// Fincept color palette for models-const MODEL_COLORS = [- '#FF8800', // Orange (primary)- '#00D66F', // Green- '#0088FF', // Blue- '#9D4EDD', // Purple- '#FFD700', // Gold- '#00E5FF', // Cyan- '#FF3B3B', // Red- '#4ADE80', // Light Green- '#F59E0B', // Amber- '#EC4899', // Pink-];--const FINCEPT = {- DARK_BG: '#000000',- PANEL_BG: '#0F0F0F',- BORDER: '#2A2A2A',- GRAY: '#787878',- WHITE: '#FFFFFF',- ORANGE: '#FF8800',- GREEN: '#00D66F',-};--export const AlphaArenaChart: React.FC<AlphaArenaChartProps> = ({- snapshots,- initialCapital = 10000-}) => {- // Transform snapshots into chart data- const chartData = useMemo(() => {- if (!snapshots || snapshots.length === 0) return [];-- // Group by cycle number- const cycleMap = new Map<number, any>();-- snapshots.forEach(snap => {- const cycleNum = snap.cycle_number ?? 0;- if (!cycleMap.has(cycleNum)) {- cycleMap.set(cycleNum, {- cycle: cycleNum,- timestamp: snap.timestamp,- });- }-- const cycleData = cycleMap.get(cycleNum)!;- cycleData[snap.model_name] = snap.portfolio_value;- });-- // Convert to array and sort by cycle- const data = Array.from(cycleMap.values()).sort((a, b) => a.cycle - b.cycle);-- return data;- }, [snapshots]);-- // Get unique model names for lines- const modelNames = useMemo(() => {- const names = new Set<string>();- snapshots.forEach(snap => names.add(snap.model_name));- return Array.from(names);- }, [snapshots]);-- // Custom tooltip- const CustomTooltip = ({ active, payload, label }: any) => {- if (!active || !payload || payload.length === 0) return null;-- return (- <div style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- padding: '12px',- fontSize: '10px',- fontFamily: '"IBM Plex Mono", monospace',- }}>- <div style={{ color: FINCEPT.GRAY, marginBottom: '8px', fontSize: '9px' }}>- CYCLE #{label}- </div>- {payload.map((entry: any, index: number) => (- <div key={index} style={{- display: 'flex',- justifyContent: 'space-between',- gap: '16px',- marginBottom: '4px',- alignItems: 'center'- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>- <div style={{- width: '8px',- height: '8px',- backgroundColor: entry.color,- borderRadius: '50%',- }} />- <span style={{ color: FINCEPT.WHITE, fontWeight: 600 }}>- {entry.name}:- </span>- </div>- <span style={{- color: entry.value >= initialCapital ? FINCEPT.GREEN : FINCEPT.ORANGE,- fontWeight: 700,- fontFamily: '"IBM Plex Mono", monospace',- }}>- ${entry.value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}- </span>- </div>- ))}- </div>- );- };-- // Custom legend- const CustomLegend = ({ payload }: any) => {- return (- <div style={{- display: 'flex',- flexWrap: 'wrap',- gap: '16px',- justifyContent: 'center',- padding: '12px 0 0 0',- }}>- {payload.map((entry: any, index: number) => (- <div key={index} style={{- display: 'flex',- alignItems: 'center',- gap: '6px',- fontSize: '10px',- fontFamily: '"IBM Plex Mono", monospace',- }}>- <div style={{- width: '12px',- height: '3px',- backgroundColor: entry.color,- }} />- <span style={{ color: FINCEPT.WHITE, fontWeight: 600 }}>- {entry.value}- </span>- </div>- ))}- </div>- );- };-- if (chartData.length === 0) {- return (- <div style={{- height: '100%',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- color: FINCEPT.GRAY,- fontSize: '11px',- fontFamily: '"IBM Plex Mono", monospace',- }}>- No performance data yet. Start the competition to see the chart.- </div>- );- }-- return (- <ResponsiveContainer width="100%" height="100%">- <LineChart- data={chartData}- margin={{ top: 10, right: 30, left: 20, bottom: 10 }}- >- <CartesianGrid- strokeDasharray="3 3"- stroke={FINCEPT.BORDER}- vertical={false}- />- <XAxis- dataKey="cycle"- stroke={FINCEPT.GRAY}- tick={{ fill: FINCEPT.GRAY, fontSize: 10, fontFamily: '"IBM Plex Mono", monospace' }}- label={{- value: 'CYCLE',- position: 'insideBottom',- offset: -5,- fill: FINCEPT.GRAY,- fontSize: 10,- fontFamily: '"IBM Plex Mono", monospace',- }}- />- <YAxis- stroke={FINCEPT.GRAY}- tick={{ fill: FINCEPT.GRAY, fontSize: 10, fontFamily: '"IBM Plex Mono", monospace' }}- tickFormatter={(value) => `$${(value / 1000).toFixed(1)}k`}- domain={['dataMin - 500', 'dataMax + 500']}- label={{- value: 'PORTFOLIO VALUE',- angle: -90,- position: 'insideLeft',- fill: FINCEPT.GRAY,- fontSize: 10,- fontFamily: '"IBM Plex Mono", monospace',- }}- />- <Tooltip content={<CustomTooltip />} />- <Legend content={<CustomLegend />} />-- {/* Baseline reference line at initial capital */}- <Line- type="monotone"- dataKey={() => initialCapital}- stroke={FINCEPT.BORDER}- strokeWidth={1}- strokeDasharray="5 5"- dot={false}- activeDot={false}- name="Initial Capital"- />-- {/* Model performance lines */}- {modelNames.map((modelName, index) => (- <Line- key={modelName}- type="monotone"- dataKey={modelName}- stroke={MODEL_COLORS[index % MODEL_COLORS.length]}- strokeWidth={2}- dot={{- r: 3,- fill: MODEL_COLORS[index % MODEL_COLORS.length],- strokeWidth: 0,- }}- activeDot={{- r: 5,- fill: MODEL_COLORS[index % MODEL_COLORS.length],- stroke: FINCEPT.WHITE,- strokeWidth: 2,- }}- name={modelName}- />- ))}- </LineChart>- </ResponsiveContainer>- );-};--export default AlphaArenaChart;diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsxnew file mode 100644index 000000000..ecfe0212f--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsx@@ -0,0 +1,1423 @@+/**+ * Alpha Arena Tab - Fincept Terminal Design (v2.1)+ *+ * AI Trading Competition Platform with:+ * - LLM configuration from Settings+ * - Professional terminal-style UI+ * - Real-time leaderboard & performance charts+ * - Repository integration for trade decisions+ */++import React, { useState, useEffect, useCallback, useRef } from 'react';+import { listen, UnlistenFn } from '@tauri-apps/api/event';+import {+ Bot, Trophy, Play, Pause, RotateCcw, Plus, Settings, Key,+ TrendingUp, TrendingDown, Activity, Zap, AlertCircle, CheckCircle,+ ChevronRight, Loader2, BarChart3, Clock, Target, Brain,+ RefreshCw, Eye, Users, Sparkles, Check, Circle, History, Trash2, PlayCircle,+ StopCircle, XCircle,+} from 'lucide-react';+import { TabFooter } from '@/components/common/TabFooter';+import { sqliteService, type LLMModelConfig, type LLMConfig } from '@/services/core/sqliteService';+import alphaArenaService, { type StoredCompetition } from './services/alphaArenaService';+import { useAuth } from '@/contexts/AuthContext';++// Extended model type for Alpha Arena with API key+interface AlphaArenaModel {+ id: string;+ provider: string;+ model_id: string;+ display_name: string;+ api_key?: string;+ is_enabled: boolean;+}++// Progress event type from Rust backend+interface AlphaArenaProgress {+ event_type: 'step' | 'info' | 'warning' | 'error' | 'complete';+ step: number;+ total_steps: number;+ message: string;+ details?: unknown;+}+import type {+ CompetitionStatus,+ LeaderboardEntry,+ ModelDecision,+ PerformanceSnapshot,+ CompetitionMode,+} from './types';+import { formatCurrency, formatPercent, getModelColor } from './types';++// =============================================================================+// Design Constants - Fincept Terminal Style+// =============================================================================++const COLORS = {+ ORANGE: '#FF8800',+ ORANGE_HOVER: '#FF9900',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ BLUE: '#3B82F6',+ PURPLE: '#8B5CF6',+ YELLOW: '#EAB308',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ CARD_BG: '#0A0A0A',+ BORDER: '#2A2A2A',+ BORDER_LIGHT: '#3A3A3A',+ HOVER: '#1A1A1A',+ MUTED: '#4A4A4A',+};++const TRADING_SYMBOLS = [+ { value: 'BTC/USD', label: 'Bitcoin (BTC/USD)' },+ { value: 'ETH/USD', label: 'Ethereum (ETH/USD)' },+ { value: 'SOL/USD', label: 'Solana (SOL/USD)' },+ { value: 'XRP/USD', label: 'Ripple (XRP/USD)' },+ { value: 'DOGE/USD', label: 'Dogecoin (DOGE/USD)' },+];++const COMPETITION_MODES: { value: CompetitionMode; label: string; desc: string }[] = [+ { value: 'baseline', label: 'Baseline', desc: 'Standard trading with balanced risk' },+ { value: 'monk', label: 'Monk', desc: 'Conservative - capital preservation' },+ { value: 'situational', label: 'Situational', desc: 'Competitive - models aware of others' },+ { value: 'max_leverage', label: 'Max Leverage', desc: 'Aggressive - maximum positions' },+];++// =============================================================================+// Component+// =============================================================================++const AlphaArenaTab: React.FC = () => {+ // Auth context for Fincept API key+ const { session } = useAuth();++ // Competition state+ const [competitionId, setCompetitionId] = useState<string | null>(null);+ const [status, setStatus] = useState<CompetitionStatus | null>(null);+ const [cycleCount, setCycleCount] = useState(0);++ // Data state+ const [leaderboard, setLeaderboard] = useState<LeaderboardEntry[]>([]);+ const [decisions, setDecisions] = useState<ModelDecision[]>([]);+ const [snapshots, setSnapshots] = useState<PerformanceSnapshot[]>([]);++ // LLM state - from Settings+ const [configuredLLMs, setConfiguredLLMs] = useState<AlphaArenaModel[]>([]);+ const [selectedModels, setSelectedModels] = useState<AlphaArenaModel[]>([]);++ // UI state+ const [isLoading, setIsLoading] = useState(false);+ const [isAutoRunning, setIsAutoRunning] = useState(false);+ const [isCancelling, setIsCancelling] = useState(false);+ const [showCreatePanel, setShowCreatePanel] = useState(false);+ const [showPastCompetitions, setShowPastCompetitions] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [success, setSuccess] = useState<string | null>(null);++ // Abort controller for cancelling operations+ const abortControllerRef = useRef<AbortController | null>(null);++ // Past competitions state+ const [pastCompetitions, setPastCompetitions] = useState<StoredCompetition[]>([]);+ const [loadingPastCompetitions, setLoadingPastCompetitions] = useState(false);++ // Progress tracking state+ const [progressSteps, setProgressSteps] = useState<AlphaArenaProgress[]>([]);+ const [currentProgress, setCurrentProgress] = useState<AlphaArenaProgress | null>(null);+ const progressListenerRef = useRef<UnlistenFn | null>(null);++ // Form state+ const [competitionName, setCompetitionName] = useState('Alpha Arena Competition');+ const [symbol, setSymbol] = useState('BTC/USD');+ const [mode, setMode] = useState<CompetitionMode>('baseline');+ const [initialCapital, setInitialCapital] = useState(10000);+ const [cycleInterval, setCycleInterval] = useState(150);++ // Auto-run ref+ const autoRunIntervalRef = useRef<NodeJS.Timeout | null>(null);++ // =============================================================================+ // Load LLM Models from Settings (llm_model_configs table)+ // =============================================================================++ const loadLLMConfigs = useCallback(async () => {+ try {+ // Auto-fix any Google model IDs with incorrect format+ const fixResult = await sqliteService.fixGoogleModelIds();+ if (fixResult.success) {+ console.log('[AlphaArena] Google model IDs check:', fixResult.message);+ }++ // Load from llm_model_configs table (individual models configured in Settings)+ const modelConfigs = await sqliteService.getLLMModelConfigs();+ // Load provider configs for API key fallback and for fincept (which is auto-configured)+ const providerConfigs = await sqliteService.getLLMConfigs();++ console.log('[AlphaArena] Loaded model configs:', modelConfigs);+ console.log('[AlphaArena] Loaded provider configs:', providerConfigs);++ // Process models - filter and validate+ const validModels: AlphaArenaModel[] = [];++ // First, add fincept from provider configs (it's auto-configured, not in llm_model_configs)+ // Use session API key for fincept (the same key used for all Fincept backend APIs)+ const finceptProvider = providerConfigs.find(c => (c.provider || '').toLowerCase() === 'fincept');+ const finceptApiKey = session?.api_key || finceptProvider?.api_key;+ if (finceptProvider || finceptApiKey) {+ validModels.push({+ id: 'fincept-auto',+ provider: 'fincept',+ model_id: finceptProvider?.model || 'fincept-llm',+ display_name: 'Fincept LLM (Auto)',+ api_key: finceptApiKey || undefined,+ is_enabled: true,+ });+ console.log('[AlphaArena] Added Fincept LLM (auto-configured) with API key:', finceptApiKey ? 'present' : 'missing');+ }++ // Then process models from llm_model_configs table+ for (const model of modelConfigs) {+ // Skip disabled models+ if (!model.is_enabled) {+ console.log(`[AlphaArena] Skipping ${model.display_name} - disabled`);+ continue;+ }++ const providerLower = (model.provider || '').toLowerCase();++ // Get API key - try model config first, then provider config+ let apiKey = model.api_key;+ if (!apiKey || apiKey.trim() === '') {+ const providerConfig = providerConfigs.find(+ c => (c.provider || '').toLowerCase() === providerLower+ );+ if (providerConfig?.api_key && providerConfig.api_key.trim() !== '') {+ apiKey = providerConfig.api_key;+ console.log(`[AlphaArena] Using provider API key for ${model.display_name}`);+ }+ }++ // Skip if no API key (except ollama and fincept which may not need one in the same way)+ const noApiKeyRequired = providerLower === 'ollama' || providerLower === 'fincept';+ if ((!apiKey || apiKey.trim() === '') && !noApiKeyRequired) {+ console.log(`[AlphaArena] Skipping ${model.display_name} - no API key`);+ continue;+ }++ validModels.push({+ id: model.id,+ provider: model.provider,+ model_id: model.model_id,+ display_name: model.display_name || model.model_id,+ api_key: apiKey || undefined,+ is_enabled: model.is_enabled,+ });++ console.log(`[AlphaArena] Added model: ${model.display_name}`);+ }++ console.log(`[AlphaArena] Total valid models: ${validModels.length}`);+ setConfiguredLLMs(validModels);++ // Pre-select first 2 models+ if (validModels.length >= 2) {+ setSelectedModels(validModels.slice(0, 2));+ } else if (validModels.length === 1) {+ setSelectedModels([validModels[0]]);+ } else {+ setSelectedModels([]);+ }+ } catch (err) {+ console.error('[AlphaArena] Failed to load LLM configs:', err);+ }+ }, [session?.api_key]);++ useEffect(() => {+ loadLLMConfigs();+ }, [loadLLMConfigs]);++ // =============================================================================+ // Load Past Competitions from Database+ // =============================================================================++ const loadPastCompetitions = useCallback(async () => {+ setLoadingPastCompetitions(true);+ try {+ const result = await alphaArenaService.listCompetitions(20);+ if (result.success && result.competitions) {+ setPastCompetitions(result.competitions);+ }+ } catch (err) {+ console.error('[AlphaArena] Failed to load past competitions:', err);+ } finally {+ setLoadingPastCompetitions(false);+ }+ }, []);++ // Load past competitions on mount+ useEffect(() => {+ loadPastCompetitions();+ }, [loadPastCompetitions]);++ // Resume a past competition+ const handleResumeCompetition = async (comp: StoredCompetition) => {+ setIsLoading(true);+ setError(null);+ setProgressSteps([]);++ try {+ // Set the competition ID - the backend will restore from DB when we run a cycle+ setCompetitionId(comp.competition_id);+ setCycleCount(comp.cycle_count);+ setStatus(comp.status as CompetitionStatus);+ setShowPastCompetitions(false);+ setSuccess(`Loaded competition: ${comp.config.competition_name}`);+ setTimeout(() => setSuccess(null), 3000);++ // Fetch competition data - pass ID directly since state hasn't updated yet+ await fetchCompetitionData(comp.competition_id);+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Failed to resume competition');+ } finally {+ setIsLoading(false);+ }+ };++ // Delete a competition+ const handleDeleteCompetition = async (competitionId: string, e: React.MouseEvent) => {+ e.stopPropagation();++ if (!confirm('Are you sure you want to delete this competition? This cannot be undone.')) {+ return;+ }++ try {+ const result = await alphaArenaService.deleteCompetition(competitionId);+ if (result.success) {+ setPastCompetitions(prev => prev.filter(c => c.competition_id !== competitionId));+ setSuccess('Competition deleted');+ setTimeout(() => setSuccess(null), 3000);+ } else {+ setError(result.error || 'Failed to delete competition');+ }+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Failed to delete competition');+ }+ };++ // =============================================================================+ // Progress Event Listener+ // =============================================================================++ useEffect(() => {+ // Listen for progress events from Rust backend+ const setupListener = async () => {+ progressListenerRef.current = await listen<AlphaArenaProgress>(+ 'alpha-arena-progress',+ (event) => {+ const progress = event.payload;+ console.log('[AlphaArena] Progress:', progress);++ setCurrentProgress(progress);+ setProgressSteps(prev => {+ // Avoid duplicates+ if (prev.some(p => p.step === progress.step && p.message === progress.message)) {+ return prev;+ }+ return [...prev, progress];+ });++ // Handle completion+ if (progress.event_type === 'complete') {+ setTimeout(() => {+ setCurrentProgress(null);+ setProgressSteps([]);+ }, 2000);+ }++ // Handle errors+ if (progress.event_type === 'error') {+ setError(progress.message);+ }+ }+ );+ };++ setupListener();++ return () => {+ if (progressListenerRef.current) {+ progressListenerRef.current();+ }+ };+ }, []);++ // =============================================================================+ // Competition Data+ // =============================================================================++ const fetchCompetitionData = useCallback(async (overrideCompetitionId?: string) => {+ const targetCompetitionId = overrideCompetitionId || competitionId;+ if (!targetCompetitionId) return;++ try {+ console.log('[AlphaArena] Fetching competition data for:', targetCompetitionId);+ const [leaderboardResult, decisionsResult, snapshotsResult] = await Promise.all([+ alphaArenaService.getLeaderboard(targetCompetitionId),+ alphaArenaService.getDecisions(targetCompetitionId),+ alphaArenaService.getSnapshots(targetCompetitionId),+ ]);++ console.log('[AlphaArena] Leaderboard result:', leaderboardResult);+ console.log('[AlphaArena] Decisions result:', decisionsResult);+ console.log('[AlphaArena] Snapshots result:', snapshotsResult);++ if (leaderboardResult.success && leaderboardResult.leaderboard) {+ console.log('[AlphaArena] Setting leaderboard:', leaderboardResult.leaderboard.length, 'entries');+ setLeaderboard(leaderboardResult.leaderboard);+ } else {+ console.warn('[AlphaArena] Leaderboard not available:', leaderboardResult.error || 'no data');+ }+ if (decisionsResult.success && decisionsResult.decisions) {+ console.log('[AlphaArena] Setting decisions:', decisionsResult.decisions.length, 'entries');+ setDecisions(decisionsResult.decisions);+ } else {+ console.warn('[AlphaArena] Decisions not available:', decisionsResult.error || 'no data');+ }+ if (snapshotsResult.success && snapshotsResult.snapshots) {+ console.log('[AlphaArena] Setting snapshots:', snapshotsResult.snapshots.length, 'entries');+ setSnapshots(snapshotsResult.snapshots);+ } else {+ console.warn('[AlphaArena] Snapshots not available:', snapshotsResult.error || 'no data');+ }+ } catch (err) {+ console.error('[AlphaArena] Failed to fetch data:', err);+ }+ }, [competitionId]);++ useEffect(() => {+ if (!competitionId) return;+ fetchCompetitionData();+ const interval = setInterval(fetchCompetitionData, 5000);+ return () => clearInterval(interval);+ }, [competitionId, fetchCompetitionData]);++ // =============================================================================+ // Competition Actions+ // =============================================================================++ const handleCreateCompetition = async () => {+ if (selectedModels.length < 2) {+ setError('Select at least 2 AI models from your configured models in Settings');+ return;+ }++ setIsLoading(true);+ setError(null);+ setProgressSteps([]); // Reset progress+ setCurrentProgress(null);++ try {+ const result = await alphaArenaService.createCompetition({+ competition_name: competitionName,+ models: selectedModels.map(m => ({+ name: m.display_name,+ provider: m.provider,+ model_id: m.model_id,+ api_key: m.api_key, // Include API key from model config+ initial_capital: initialCapital,+ })),+ symbols: [symbol],+ initial_capital: initialCapital,+ mode,+ cycle_interval_seconds: cycleInterval,+ });++ if (result.success && result.competition_id) {+ setCompetitionId(result.competition_id);+ setStatus('created');+ setShowCreatePanel(false);+ setSuccess('Competition created successfully');+ setTimeout(() => setSuccess(null), 3000);+ } else {+ setError(result.error || 'Failed to create competition');+ }+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Unknown error');+ } finally {+ setIsLoading(false);+ }+ };++ const handleRunCycle = useCallback(async () => {+ if (!competitionId || isLoading) return;++ setIsLoading(true);+ setError(null);+ setProgressSteps([]); // Reset progress+ setCurrentProgress(null);++ try {+ const currentCompetitionId = competitionId; // Capture before async+ const result = await alphaArenaService.runCycle(currentCompetitionId);++ if (result.success) {+ setCycleCount(result.cycle_number || cycleCount + 1);+ setStatus('running');+ // Pass ID explicitly to avoid stale closure issues+ await fetchCompetitionData(currentCompetitionId);+ } else {+ setError(result.error || 'Cycle failed');+ }+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Unknown error');+ } finally {+ setIsLoading(false);+ }+ }, [competitionId, isLoading, cycleCount, fetchCompetitionData]);++ const handleToggleAutoRun = useCallback(() => {+ if (isAutoRunning) {+ if (autoRunIntervalRef.current) {+ clearInterval(autoRunIntervalRef.current);+ autoRunIntervalRef.current = null;+ }+ setIsAutoRunning(false);+ setStatus('paused');+ } else {+ setIsAutoRunning(true);+ setStatus('running');+ handleRunCycle();+ autoRunIntervalRef.current = setInterval(() => {+ handleRunCycle();+ }, cycleInterval * 1000);+ }+ }, [isAutoRunning, handleRunCycle, cycleInterval]);++ const handleReset = useCallback(() => {+ if (autoRunIntervalRef.current) {+ clearInterval(autoRunIntervalRef.current);+ autoRunIntervalRef.current = null;+ }+ // Cancel any ongoing operation+ if (abortControllerRef.current) {+ abortControllerRef.current.abort();+ abortControllerRef.current = null;+ }+ setCompetitionId(null);+ setStatus(null);+ setCycleCount(0);+ setLeaderboard([]);+ setDecisions([]);+ setSnapshots([]);+ setIsAutoRunning(false);+ setIsLoading(false);+ setIsCancelling(false);+ setError(null);+ setProgressSteps([]);+ setCurrentProgress(null);+ }, []);++ // Cancel ongoing operation+ const handleCancel = useCallback(() => {+ setIsCancelling(true);++ // Stop auto-run if active+ if (autoRunIntervalRef.current) {+ clearInterval(autoRunIntervalRef.current);+ autoRunIntervalRef.current = null;+ setIsAutoRunning(false);+ }++ // Abort any ongoing fetch/operation+ if (abortControllerRef.current) {+ abortControllerRef.current.abort();+ abortControllerRef.current = null;+ }++ // Reset loading states+ setIsLoading(false);+ setIsCancelling(false);+ setProgressSteps([]);+ setCurrentProgress(null);+ setStatus('paused');+ setSuccess('Operation cancelled');+ setTimeout(() => setSuccess(null), 2000);+ }, []);++ useEffect(() => {+ return () => {+ if (autoRunIntervalRef.current) {+ clearInterval(autoRunIntervalRef.current);+ }+ };+ }, []);++ const toggleModelSelection = (model: AlphaArenaModel) => {+ setSelectedModels(prev => {+ const isSelected = prev.some(m => m.id === model.id);+ if (isSelected) {+ return prev.filter(m => m.id !== model.id);+ }+ return [...prev, model];+ });+ };++ // =============================================================================+ // Render: Header+ // =============================================================================++ const renderHeader = () => (+ <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER, backgroundColor: COLORS.PANEL_BG }}>+ <div className="flex items-center gap-3">+ <Trophy size={20} style={{ color: COLORS.ORANGE }} />+ <h1 className="text-lg font-semibold" style={{ color: COLORS.WHITE }}>Alpha Arena</h1>+ <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: COLORS.PURPLE + '20', color: COLORS.PURPLE }}>+ AI Trading Competition+ </span>+ </div>++ <div className="flex items-center gap-2">+ {competitionId && (+ <div className="flex items-center gap-2 mr-4">+ <div className="flex items-center gap-1 px-2 py-1 rounded" style={{ backgroundColor: COLORS.BORDER }}>+ <Activity size={12} style={{ color: isAutoRunning ? COLORS.GREEN : COLORS.GRAY }} />+ <span className="text-xs" style={{ color: COLORS.WHITE }}>Cycle: {cycleCount}</span>+ </div>+ <div+ className="px-2 py-1 rounded text-xs"+ style={{+ backgroundColor: status === 'running' ? COLORS.GREEN + '20' : COLORS.GRAY + '20',+ color: status === 'running' ? COLORS.GREEN : COLORS.GRAY,+ }}+ >+ {isAutoRunning ? 'AUTO-RUNNING' : status?.toUpperCase() || 'IDLE'}+ </div>+ </div>+ )}+ <button+ onClick={() => loadLLMConfigs()}+ className="p-2 rounded transition-colors hover:bg-[#1A1A1A]"+ title="Refresh LLM configs"+ >+ <RefreshCw size={16} style={{ color: COLORS.GRAY }} />+ </button>+ </div>+ </div>+ );++ // =============================================================================+ // Render: Progress Panel (Real-time streaming updates)+ // =============================================================================++ const renderProgressPanel = () => {+ if (!isLoading && progressSteps.length === 0) return null;++ return (+ <div+ className="p-4 rounded-lg mb-4"+ style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.ORANGE}40`,+ boxShadow: `0 0 20px ${COLORS.ORANGE}10`+ }}+ >+ <div className="flex items-center justify-between mb-3">+ <div className="flex items-center gap-2">+ <Loader2 size={18} className="animate-spin" style={{ color: COLORS.ORANGE }} />+ <h3 className="font-medium" style={{ color: COLORS.WHITE }}>+ {currentProgress ? currentProgress.message : 'Processing...'}+ </h3>+ </div>+ {/* STOP button in progress panel */}+ <button+ onClick={handleCancel}+ disabled={isCancelling}+ className="px-3 py-1.5 rounded text-xs font-medium flex items-center gap-1.5 transition-colors"+ style={{+ backgroundColor: COLORS.RED,+ color: COLORS.WHITE,+ opacity: isCancelling ? 0.5 : 1,+ }}+ >+ {isCancelling ? <Loader2 size={12} className="animate-spin" /> : <XCircle size={12} />}+ {isCancelling ? 'Stopping...' : 'Cancel'}+ </button>+ </div>++ {/* Progress Bar */}+ {currentProgress && (+ <div className="mb-3">+ <div className="h-2 rounded-full overflow-hidden" style={{ backgroundColor: COLORS.BORDER }}>+ <div+ className="h-full transition-all duration-300 ease-out"+ style={{+ width: `${(currentProgress.step / currentProgress.total_steps) * 100}%`,+ backgroundColor: currentProgress.event_type === 'error' ? COLORS.RED :+ currentProgress.event_type === 'complete' ? COLORS.GREEN : COLORS.ORANGE+ }}+ />+ </div>+ <div className="flex justify-between mt-1">+ <span className="text-xs" style={{ color: COLORS.GRAY }}>+ Step {currentProgress.step} of {currentProgress.total_steps}+ </span>+ <span className="text-xs" style={{ color: COLORS.GRAY }}>+ {Math.round((currentProgress.step / currentProgress.total_steps) * 100)}%+ </span>+ </div>+ </div>+ )}++ {/* Steps Log */}+ <div className="space-y-1 max-h-40 overflow-y-auto">+ {progressSteps.map((step, idx) => (+ <div key={idx} className="flex items-center gap-2 text-xs">+ {step.event_type === 'complete' ? (+ <Check size={12} style={{ color: COLORS.GREEN }} />+ ) : step.event_type === 'error' ? (+ <AlertCircle size={12} style={{ color: COLORS.RED }} />+ ) : step.event_type === 'warning' ? (+ <AlertCircle size={12} style={{ color: COLORS.YELLOW }} />+ ) : step.event_type === 'step' ? (+ <Circle size={12} style={{ color: COLORS.ORANGE }} />+ ) : (+ <ChevronRight size={12} style={{ color: COLORS.GRAY }} />+ )}+ <span style={{+ color: step.event_type === 'error' ? COLORS.RED :+ step.event_type === 'complete' ? COLORS.GREEN :+ step.event_type === 'warning' ? COLORS.YELLOW : COLORS.GRAY+ }}>+ {step.message}+ </span>+ </div>+ ))}+ </div>+ </div>+ );+ };++ // =============================================================================+ // Render: Past Competitions Panel+ // =============================================================================++ const renderPastCompetitions = () => (+ <div className="p-4 rounded-lg" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="flex items-center justify-between mb-4">+ <div className="flex items-center gap-2">+ <History size={18} style={{ color: COLORS.ORANGE }} />+ <h2 className="font-semibold" style={{ color: COLORS.WHITE }}>Past Competitions</h2>+ <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: COLORS.BORDER, color: COLORS.GRAY }}>+ {pastCompetitions.length} saved+ </span>+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={() => loadPastCompetitions()}+ disabled={loadingPastCompetitions}+ className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"+ title="Refresh"+ >+ <RefreshCw size={14} className={loadingPastCompetitions ? 'animate-spin' : ''} style={{ color: COLORS.GRAY }} />+ </button>+ <button+ onClick={() => setShowPastCompetitions(false)}+ className="text-xs px-2 py-1 rounded"+ style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}+ >+ Close+ </button>+ </div>+ </div>++ {loadingPastCompetitions ? (+ <div className="flex items-center justify-center py-8">+ <Loader2 size={24} className="animate-spin" style={{ color: COLORS.ORANGE }} />+ </div>+ ) : pastCompetitions.length === 0 ? (+ <div className="text-center py-8">+ <History size={32} className="mx-auto mb-2" style={{ color: COLORS.GRAY, opacity: 0.5 }} />+ <p className="text-sm" style={{ color: COLORS.GRAY }}>No past competitions found</p>+ </div>+ ) : (+ <div className="space-y-2 max-h-[400px] overflow-y-auto">+ {pastCompetitions.map(comp => (+ <div+ key={comp.competition_id}+ onClick={() => handleResumeCompetition(comp)}+ className="p-3 rounded cursor-pointer transition-colors"+ style={{+ backgroundColor: COLORS.CARD_BG,+ border: `1px solid ${COLORS.BORDER}`,+ }}+ onMouseEnter={e => {+ (e.currentTarget as HTMLElement).style.backgroundColor = COLORS.HOVER;+ (e.currentTarget as HTMLElement).style.borderColor = COLORS.ORANGE + '40';+ }}+ onMouseLeave={e => {+ (e.currentTarget as HTMLElement).style.backgroundColor = COLORS.CARD_BG;+ (e.currentTarget as HTMLElement).style.borderColor = COLORS.BORDER;+ }}+ >+ <div className="flex items-center justify-between mb-2">+ <div className="flex items-center gap-2">+ <Trophy size={14} style={{ color: COLORS.ORANGE }} />+ <span className="font-medium text-sm" style={{ color: COLORS.WHITE }}>+ {comp.config.competition_name}+ </span>+ </div>+ <div className="flex items-center gap-2">+ <span+ className="text-xs px-2 py-0.5 rounded"+ style={{+ backgroundColor:+ comp.status === 'running' ? COLORS.GREEN + '20' :+ comp.status === 'completed' ? COLORS.BLUE + '20' :+ comp.status === 'failed' ? COLORS.RED + '20' :+ COLORS.GRAY + '20',+ color:+ comp.status === 'running' ? COLORS.GREEN :+ comp.status === 'completed' ? COLORS.BLUE :+ comp.status === 'failed' ? COLORS.RED :+ COLORS.GRAY,+ }}+ >+ {comp.status.toUpperCase()}+ </span>+ <button+ onClick={(e) => handleDeleteCompetition(comp.competition_id, e)}+ className="p-1 rounded transition-colors hover:bg-red-500/20"+ title="Delete competition"+ >+ <Trash2 size={12} style={{ color: COLORS.RED }} />+ </button>+ </div>+ </div>++ <div className="grid grid-cols-3 gap-2 text-xs">+ <div>+ <span style={{ color: COLORS.GRAY }}>Cycles: </span>+ <span style={{ color: COLORS.WHITE }}>{comp.cycle_count}</span>+ </div>+ <div>+ <span style={{ color: COLORS.GRAY }}>Models: </span>+ <span style={{ color: COLORS.WHITE }}>{comp.config.models.length}</span>+ </div>+ <div>+ <span style={{ color: COLORS.GRAY }}>Capital: </span>+ <span style={{ color: COLORS.WHITE }}>${comp.config.initial_capital.toLocaleString()}</span>+ </div>+ </div>++ <div className="flex items-center gap-2 mt-2">+ <span className="text-xs" style={{ color: COLORS.GRAY }}>+ {comp.config.symbols.join(', ')}+ </span>+ <span className="text-xs" style={{ color: COLORS.MUTED }}>•</span>+ <span className="text-xs" style={{ color: COLORS.GRAY }}>+ {new Date(comp.created_at).toLocaleDateString()}+ </span>+ </div>++ <div className="flex flex-wrap gap-1 mt-2">+ {comp.config.models.map((model, idx) => (+ <span+ key={idx}+ className="text-xs px-1.5 py-0.5 rounded"+ style={{ backgroundColor: COLORS.BORDER, color: COLORS.GRAY }}+ >+ {model.name}+ </span>+ ))}+ </div>++ <div className="flex items-center justify-end mt-2 pt-2 border-t" style={{ borderColor: COLORS.BORDER }}>+ <div className="flex items-center gap-1 text-xs" style={{ color: COLORS.ORANGE }}>+ <PlayCircle size={12} />+ <span>Click to resume</span>+ </div>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ );++ // =============================================================================+ // Render: Create Competition Panel+ // =============================================================================++ const renderCreatePanel = () => (+ <div className="p-4 rounded-lg" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="flex items-center gap-2 mb-4">+ <Plus size={18} style={{ color: COLORS.ORANGE }} />+ <h2 className="font-semibold" style={{ color: COLORS.WHITE }}>Create Competition</h2>+ </div>++ <div className="space-y-4">+ {/* Competition Name */}+ <div>+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Competition Name</label>+ <input+ type="text"+ value={competitionName}+ onChange={e => setCompetitionName(e.target.value)}+ className="w-full px-3 py-2 rounded text-sm"+ style={{ backgroundColor: COLORS.CARD_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ />+ </div>++ {/* Symbol & Mode */}+ <div className="grid grid-cols-2 gap-4">+ <div>+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Trading Symbol</label>+ <select+ value={symbol}+ onChange={e => setSymbol(e.target.value)}+ className="w-full px-3 py-2 rounded text-sm"+ style={{ backgroundColor: COLORS.CARD_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ >+ {TRADING_SYMBOLS.map(s => (+ <option key={s.value} value={s.value}>{s.label}</option>+ ))}+ </select>+ </div>+ <div>+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Competition Mode</label>+ <select+ value={mode}+ onChange={e => setMode(e.target.value as CompetitionMode)}+ className="w-full px-3 py-2 rounded text-sm"+ style={{ backgroundColor: COLORS.CARD_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ >+ {COMPETITION_MODES.map(m => (+ <option key={m.value} value={m.value}>{m.label}</option>+ ))}+ </select>+ </div>+ </div>++ {/* Capital & Interval */}+ <div className="grid grid-cols-2 gap-4">+ <div>+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Initial Capital (USD)</label>+ <input+ type="number"+ value={initialCapital}+ onChange={e => setInitialCapital(Number(e.target.value))}+ min={1000}+ step={1000}+ className="w-full px-3 py-2 rounded text-sm"+ style={{ backgroundColor: COLORS.CARD_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ />+ </div>+ <div>+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Cycle Interval (seconds)</label>+ <input+ type="number"+ value={cycleInterval}+ onChange={e => setCycleInterval(Number(e.target.value))}+ min={30}+ max={600}+ step={30}+ className="w-full px-3 py-2 rounded text-sm"+ style={{ backgroundColor: COLORS.CARD_BG, color: COLORS.WHITE, border: `1px solid ${COLORS.BORDER}` }}+ />+ </div>+ </div>++ {/* LLM Model Selection - FROM SETTINGS */}+ <div>+ <label className="text-xs mb-2 block flex items-center gap-2" style={{ color: COLORS.GRAY }}>+ <Brain size={12} />+ SELECT AI MODELS (from Settings - min 2 required)+ </label>++ {configuredLLMs.length === 0 ? (+ <div className="p-4 rounded text-center" style={{ backgroundColor: COLORS.CARD_BG, border: `1px solid ${COLORS.RED}40` }}>+ <AlertCircle size={24} className="mx-auto mb-2" style={{ color: COLORS.RED }} />+ <p className="text-sm" style={{ color: COLORS.RED }}>No AI models configured</p>+ <p className="text-xs mt-1" style={{ color: COLORS.GRAY }}>+ Go to Settings → LLM Config → My Model Library to add models with API keys+ </p>+ </div>+ ) : (+ <div className="grid grid-cols-2 gap-2">+ {configuredLLMs.map((model) => {+ const isSelected = selectedModels.some(m => m.id === model.id);+ return (+ <button+ key={model.id}+ type="button"+ onClick={() => toggleModelSelection(model)}+ className="flex items-center gap-2 p-3 rounded text-left transition-colors"+ style={{+ backgroundColor: isSelected ? COLORS.ORANGE + '15' : COLORS.CARD_BG,+ border: `1px solid ${isSelected ? COLORS.ORANGE : COLORS.BORDER}`,+ }}+ >+ <div+ className="w-5 h-5 rounded flex items-center justify-center"+ style={{+ backgroundColor: isSelected ? COLORS.ORANGE : COLORS.BORDER,+ border: `1px solid ${isSelected ? COLORS.ORANGE : COLORS.BORDER}`,+ }}+ >+ {isSelected && <CheckCircle size={12} style={{ color: COLORS.DARK_BG }} />}+ </div>+ <div className="flex-1 min-w-0">+ <div className="text-sm font-medium truncate" style={{ color: COLORS.WHITE }}>+ {model.display_name}+ </div>+ <div className="text-xs truncate" style={{ color: COLORS.GRAY }}>+ {model.provider} • {model.model_id}+ </div>+ </div>+ </button>+ );+ })}+ </div>+ )}+ <p className="text-xs mt-2" style={{ color: COLORS.GRAY }}>+ Selected: {selectedModels.length} model(s)+ </p>+ </div>++ {/* Actions */}+ <div className="flex gap-2 pt-2">+ <button+ onClick={() => setShowCreatePanel(false)}+ className="px-4 py-2 rounded text-sm"+ style={{ backgroundColor: COLORS.BORDER, color: COLORS.GRAY }}+ >+ Cancel+ </button>+ <button+ onClick={handleCreateCompetition}+ disabled={isLoading || selectedModels.length < 2 || configuredLLMs.length === 0}+ className="flex-1 py-2 rounded font-medium text-sm flex items-center justify-center gap-2"+ style={{+ backgroundColor: COLORS.ORANGE,+ color: COLORS.DARK_BG,+ opacity: (isLoading || selectedModels.length < 2) ? 0.5 : 1,+ }}+ >+ {isLoading ? <Loader2 size={16} className="animate-spin" /> : <Zap size={16} />}+ Create Competition+ </button>+ </div>+ </div>+ </div>+ );++ // =============================================================================+ // Render: Competition Controls+ // =============================================================================++ const renderControls = () => (+ <div className="flex items-center gap-2 p-3 rounded-lg" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ {/* Show STOP button when loading, otherwise show Run Cycle */}+ {isLoading ? (+ <button+ onClick={handleCancel}+ disabled={isCancelling}+ className="px-4 py-2 rounded text-sm font-medium flex items-center gap-2"+ style={{+ backgroundColor: COLORS.RED,+ color: COLORS.WHITE,+ opacity: isCancelling ? 0.5 : 1,+ }}+ >+ {isCancelling ? <Loader2 size={14} className="animate-spin" /> : <StopCircle size={14} />}+ {isCancelling ? 'Stopping...' : 'STOP'}+ </button>+ ) : (+ <button+ onClick={handleRunCycle}+ disabled={isAutoRunning}+ className="px-4 py-2 rounded text-sm font-medium flex items-center gap-2"+ style={{+ backgroundColor: COLORS.ORANGE,+ color: COLORS.DARK_BG,+ opacity: isAutoRunning ? 0.5 : 1,+ }}+ >+ <Play size={14} />+ Run Cycle+ </button>+ )}++ <button+ onClick={handleToggleAutoRun}+ disabled={isLoading}+ className="px-4 py-2 rounded text-sm font-medium flex items-center gap-2"+ style={{+ backgroundColor: isAutoRunning ? COLORS.RED + '20' : COLORS.GREEN + '20',+ color: isAutoRunning ? COLORS.RED : COLORS.GREEN,+ border: `1px solid ${isAutoRunning ? COLORS.RED + '40' : COLORS.GREEN + '40'}`,+ opacity: isLoading ? 0.5 : 1,+ }}+ >+ {isAutoRunning ? <Pause size={14} /> : <Zap size={14} />}+ {isAutoRunning ? 'Stop Auto' : 'Auto Run'}+ </button>++ <button+ onClick={handleReset}+ className="px-4 py-2 rounded text-sm flex items-center gap-2"+ style={{ backgroundColor: COLORS.BORDER, color: COLORS.GRAY }}+ >+ <RotateCcw size={14} />+ Reset+ </button>++ <div className="flex-1" />++ <div className="text-xs px-3 py-1 rounded" style={{ backgroundColor: COLORS.CARD_BG, color: COLORS.GRAY }}>+ <Clock size={12} className="inline mr-1" />+ Interval: {cycleInterval}s+ </div>+ </div>+ );++ // =============================================================================+ // Render: Leaderboard+ // =============================================================================++ const renderLeaderboard = () => {+ console.log('[AlphaArena] Rendering leaderboard, entries:', leaderboard.length, leaderboard);+ return (+ <div className="rounded-lg overflow-hidden" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>+ <div className="flex items-center gap-2">+ <Trophy size={16} style={{ color: COLORS.ORANGE }} />+ <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>Leaderboard</span>+ </div>+ <span className="text-xs" style={{ color: COLORS.GRAY }}>Cycle {cycleCount}</span>+ </div>++ {leaderboard.length === 0 ? (+ <div className="p-8 text-center" style={{ color: COLORS.GRAY }}>+ <Trophy size={32} className="mx-auto mb-2 opacity-30" />+ <p className="text-sm">No competition data yet</p>+ </div>+ ) : (+ <div className="divide-y" style={{ borderColor: COLORS.BORDER }}>+ {leaderboard.map(entry => {+ const isPositive = entry.total_pnl >= 0;+ const modelColor = getModelColor(entry.model_name);++ return (+ <div+ key={entry.model_name}+ className="flex items-center gap-3 px-4 py-3 hover:bg-[#1A1A1A] transition-colors"+ >+ {/* Rank */}+ <div+ className="w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold"+ style={{+ backgroundColor: entry.rank === 1 ? COLORS.YELLOW + '20' : entry.rank === 2 ? COLORS.GRAY + '20' : entry.rank === 3 ? COLORS.ORANGE + '20' : COLORS.BORDER,+ color: entry.rank === 1 ? COLORS.YELLOW : entry.rank === 2 ? COLORS.GRAY : entry.rank === 3 ? COLORS.ORANGE : COLORS.GRAY,+ }}+ >+ {entry.rank}+ </div>++ {/* Color indicator */}+ <div className="w-1 h-10 rounded-full" style={{ backgroundColor: modelColor }} />++ {/* Model info */}+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="font-medium truncate" style={{ color: COLORS.WHITE }}>+ {entry.model_name}+ </span>+ {entry.rank === 1 && <Trophy size={14} style={{ color: COLORS.YELLOW }} />}+ </div>+ <div className="flex items-center gap-3 text-xs" style={{ color: COLORS.GRAY }}>+ <span>{entry.trades_count} trades</span>+ <span>{entry.positions_count} positions</span>+ {entry.win_rate !== undefined && (+ <span>{(entry.win_rate * 100).toFixed(0)}% win</span>+ )}+ </div>+ </div>++ {/* P&L */}+ <div className="text-right">+ <div className="flex items-center justify-end gap-1">+ {isPositive ? (+ <TrendingUp size={14} style={{ color: COLORS.GREEN }} />+ ) : (+ <TrendingDown size={14} style={{ color: COLORS.RED }} />+ )}+ <span style={{ color: isPositive ? COLORS.GREEN : COLORS.RED }}>+ {formatPercent(entry.return_pct)}+ </span>+ </div>+ <span className="text-xs" style={{ color: COLORS.GRAY }}>+ {formatCurrency(entry.portfolio_value)}+ </span>+ </div>+ </div>+ );+ })}+ </div>+ )}+ </div>+ );+ };++ // =============================================================================+ // Render: Decisions Panel+ // =============================================================================++ const renderDecisions = () => {+ console.log('[AlphaArena] Rendering decisions, entries:', decisions.length, decisions);+ return (+ <div className="h-full flex flex-col" style={{ backgroundColor: COLORS.CARD_BG }}>+ <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>+ <div className="flex items-center gap-2">+ <Brain size={16} style={{ color: COLORS.PURPLE }} />+ <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>AI Decisions</span>+ </div>+ <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: COLORS.BORDER, color: COLORS.GRAY }}>+ {decisions.length}+ </span>+ </div>++ <div className="flex-1 overflow-y-auto">+ {decisions.length === 0 ? (+ <div className="p-8 text-center" style={{ color: COLORS.GRAY }}>+ <Sparkles size={32} className="mx-auto mb-2 opacity-30" />+ <p className="text-sm">No decisions yet</p>+ <p className="text-xs mt-1">Run a cycle to see AI trading decisions</p>+ </div>+ ) : (+ <div className="divide-y" style={{ borderColor: COLORS.BORDER }}>+ {decisions.slice(0, 50).map((decision, idx) => (+ <div key={idx} className="p-3 hover:bg-[#0F0F0F] transition-colors">+ <div className="flex items-center justify-between mb-1">+ <span className="text-xs font-medium" style={{ color: COLORS.WHITE }}>+ {decision.model_name}+ </span>+ <span className="text-xs" style={{ color: COLORS.GRAY }}>+ Cycle {decision.cycle_number}+ </span>+ </div>+ <div className="flex items-center gap-2">+ <span+ className="text-xs px-2 py-0.5 rounded font-medium"+ style={{+ backgroundColor: decision.action === 'buy' ? COLORS.GREEN + '20' :+ decision.action === 'sell' ? COLORS.RED + '20' :+ decision.action === 'short' ? COLORS.PURPLE + '20' :+ COLORS.GRAY + '20',+ color: decision.action === 'buy' ? COLORS.GREEN :+ decision.action === 'sell' ? COLORS.RED :+ decision.action === 'short' ? COLORS.PURPLE :+ COLORS.GRAY,+ }}+ >+ {decision.action.toUpperCase()}+ </span>+ <span className="text-xs" style={{ color: COLORS.GRAY }}>+ {decision.symbol}+ </span>+ <span className="text-xs" style={{ color: COLORS.GRAY }}>+ Qty: {decision.quantity.toFixed(4)}+ </span>+ </div>+ {decision.reasoning && (+ <p className="text-xs mt-1 line-clamp-2" style={{ color: COLORS.MUTED }}>+ {decision.reasoning}+ </p>+ )}+ <div className="flex items-center justify-between mt-1">+ <span className="text-xs" style={{ color: COLORS.GRAY }}>+ Confidence: {(decision.confidence * 100).toFixed(0)}%+ </span>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ );+ };++ // =============================================================================+ // Render: Performance Chart (Simple)+ // =============================================================================++ const renderPerformanceChart = () => (+ <div className="rounded-lg p-4" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <div className="flex items-center gap-2 mb-4">+ <BarChart3 size={16} style={{ color: COLORS.ORANGE }} />+ <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>Performance</span>+ </div>++ {snapshots.length === 0 ? (+ <div className="h-40 flex items-center justify-center" style={{ color: COLORS.GRAY }}>+ <div className="text-center">+ <BarChart3 size={32} className="mx-auto mb-2 opacity-30" />+ <p className="text-sm">No performance data yet</p>+ </div>+ </div>+ ) : (+ <div className="h-40 flex items-end gap-1">+ {/* Simple bar chart */}+ {leaderboard.map(entry => {+ const maxVal = Math.max(...leaderboard.map(e => Math.abs(e.return_pct)), 10);+ const height = Math.abs(entry.return_pct) / maxVal * 100;+ const isPositive = entry.return_pct >= 0;++ return (+ <div key={entry.model_name} className="flex-1 flex flex-col items-center">+ <div className="w-full flex-1 flex items-end justify-center">+ <div+ className="w-full max-w-8 rounded-t transition-all"+ style={{+ height: `${Math.max(height, 5)}%`,+ backgroundColor: isPositive ? COLORS.GREEN : COLORS.RED,+ opacity: 0.7,+ }}+ />+ </div>+ <span className="text-xs mt-1 truncate w-full text-center" style={{ color: COLORS.GRAY }}>+ {entry.model_name.split(' ')[0]}+ </span>+ </div>+ );+ })}+ </div>+ )}+ </div>+ );++ // =============================================================================+ // Main Render+ // =============================================================================++ return (+ <div className="h-full flex flex-col" style={{ backgroundColor: COLORS.DARK_BG, color: COLORS.WHITE }}>+ {/* Header */}+ {renderHeader()}++ {/* Notifications */}+ {error && (+ <div className="mx-4 mt-2 p-3 rounded flex items-center gap-2" style={{ backgroundColor: COLORS.RED + '20', color: COLORS.RED }}>+ <AlertCircle size={16} />+ <span className="text-sm flex-1">{error}</span>+ <button onClick={() => setError(null)}>×</button>+ </div>+ )}+ {success && (+ <div className="mx-4 mt-2 p-3 rounded flex items-center gap-2" style={{ backgroundColor: COLORS.GREEN + '20', color: COLORS.GREEN }}>+ <CheckCircle size={16} />+ <span className="text-sm">{success}</span>+ </div>+ )}++ {/* Main Content */}+ <div className="flex-1 flex overflow-hidden">+ {/* Left Panel */}+ <div className="flex-1 flex flex-col p-4 gap-4 overflow-y-auto">+ {/* No Competition State */}+ {!competitionId && !showCreatePanel && !showPastCompetitions && (+ <div className="p-8 rounded-lg text-center" style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}>+ <Trophy size={48} className="mx-auto mb-4" style={{ color: COLORS.ORANGE, opacity: 0.5 }} />+ <h3 className="text-lg font-semibold mb-2" style={{ color: COLORS.WHITE }}>No Active Competition</h3>+ <p className="text-sm mb-4" style={{ color: COLORS.GRAY }}>+ Create a new AI trading competition or resume a past competition.+ </p>+ <div className="flex justify-center gap-3">+ <button+ onClick={() => setShowCreatePanel(true)}+ className="flex items-center gap-2 px-4 py-2 rounded font-medium"+ style={{ backgroundColor: COLORS.ORANGE, color: COLORS.DARK_BG }}+ >+ <Plus size={16} />+ Create Competition+ </button>+ {pastCompetitions.length > 0 && (+ <button+ onClick={() => setShowPastCompetitions(true)}+ className="flex items-center gap-2 px-4 py-2 rounded font-medium transition-colors"+ style={{+ backgroundColor: COLORS.CARD_BG,+ color: COLORS.WHITE,+ border: `1px solid ${COLORS.BORDER}`,+ }}+ >+ <History size={16} />+ Past Competitions ({pastCompetitions.length})+ </button>+ )}+ </div>+ {configuredLLMs.length === 0 && (+ <p className="text-xs mt-4" style={{ color: COLORS.RED }}>+ No AI models configured. Go to Settings → LLM Config → My Model Library first.+ </p>+ )}+ </div>+ )}++ {/* Past Competitions Panel */}+ {!competitionId && showPastCompetitions && renderPastCompetitions()}++ {/* Progress Panel - Shows during loading */}+ {renderProgressPanel()}++ {/* Create Panel */}+ {showCreatePanel && renderCreatePanel()}++ {/* Competition Active */}+ {competitionId && (+ <>+ {renderControls()}+ {renderPerformanceChart()}+ {renderLeaderboard()}+ </>+ )}+ </div>++ {/* Right Panel - Decisions */}+ <div className="w-[380px] border-l" style={{ borderColor: COLORS.BORDER }}>+ {renderDecisions()}+ </div>+ </div>++ {/* Footer */}+ <TabFooter+ tabName="ALPHA ARENA"+ leftInfo={[+ {+ label: competitionId ? `ID: ${competitionId.slice(0, 8)}...` : 'No Competition',+ color: COLORS.GRAY,+ },+ {+ label: `Models: ${selectedModels.length}`,+ color: COLORS.GRAY,+ },+ {+ label: `AI Models: ${configuredLLMs.length} available`,+ color: COLORS.GRAY,+ },+ ]}+ statusInfo={`Cycle: ${cycleCount} | Decisions: ${decisions.length}`}+ backgroundColor={COLORS.PANEL_BG}+ borderColor={COLORS.BORDER}+ />+ </div>+ );+};++export default AlphaArenaTab;diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/CompetitionDashboard.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/CompetitionDashboard.tsxdeleted file mode 100644index 6d701cbe0..000000000--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/CompetitionDashboard.tsx+++ /dev/null@@ -1,351 +0,0 @@-/**- * Alpha Arena Competition Dashboard- * Shows all competitions (past and active) with management controls- */--import React, { useState, useEffect } from 'react';-import { Trophy, Play, Eye, Trash2, Plus, TrendingUp, Calendar, Clock } from 'lucide-react';-import { sqliteService, AlphaCompetition } from '@/services/core/sqliteService';--const FINCEPT = {- DARK_BG: '#000000',- PANEL_BG: '#0F0F0F',- HEADER_BG: '#1A1A1A',- BORDER: '#2A2A2A',- GRAY: '#787878',- MUTED: '#555555',- WHITE: '#FFFFFF',- ORANGE: '#FF8800',- GREEN: '#00D66F',- RED: '#FF3B3B',- CYAN: '#00E5FF',- YELLOW: '#FFD700',-};--interface CompetitionDashboardProps {- onCreateNew: () => void;- onViewCompetition: (competition: AlphaCompetition) => void;- currentCompetitionId?: string;-}--export const CompetitionDashboard: React.FC<CompetitionDashboardProps> = ({- onCreateNew,- onViewCompetition,- currentCompetitionId-}) => {- const [competitions, setCompetitions] = useState<AlphaCompetition[]>([]);- const [loading, setLoading] = useState(true);-- useEffect(() => {- loadCompetitions();- }, []);-- const loadCompetitions = async () => {- try {- setLoading(true);- const comps = await sqliteService.getAlphaCompetitions(50);- setCompetitions(comps);- } catch (err) {- console.error('[CompetitionDashboard] Failed to load competitions:', err);- } finally {- setLoading(false);- }- };-- const handleDelete = async (id: string, e: React.MouseEvent) => {- e.stopPropagation();- if (confirm('Are you sure you want to delete this competition? All data will be lost.')) {- try {- await sqliteService.deleteAlphaCompetition(id);- await loadCompetitions();- } catch (err) {- console.error('[CompetitionDashboard] Failed to delete competition:', err);- }- }- };-- const getStatusColor = (status: string) => {- switch (status) {- case 'running': return FINCEPT.GREEN;- case 'paused': return FINCEPT.YELLOW;- case 'completed': return FINCEPT.GRAY;- default: return FINCEPT.CYAN;- }- };-- const formatDate = (isoString: string) => {- const date = new Date(isoString);- return date.toLocaleDateString('en-US', {- month: 'short',- day: 'numeric',- year: 'numeric',- hour: '2-digit',- minute: '2-digit'- });- };-- if (loading) {- return (- <div style={{- flex: 1,- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- color: FINCEPT.GRAY,- fontSize: '11px',- fontFamily: '"IBM Plex Mono", monospace'- }}>- Loading competitions...- </div>- );- }-- if (competitions.length === 0) {- return (- <div style={{- flex: 1,- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- gap: '24px',- padding: '48px'- }}>- <Trophy size={64} color={FINCEPT.GRAY} strokeWidth={1.5} />- <div style={{- textAlign: 'center',- color: FINCEPT.GRAY,- fontFamily: '"IBM Plex Mono", monospace'- }}>- <div style={{ fontSize: '16px', fontWeight: 700, marginBottom: '8px', color: FINCEPT.WHITE }}>- NO COMPETITIONS YET- </div>- <div style={{ fontSize: '11px', maxWidth: '400px', lineHeight: '1.6' }}>- Create your first Alpha Arena competition to pit AI models against each other in live trading simulations.- </div>- </div>- <button- onClick={onCreateNew}- style={{- padding: '12px 32px',- backgroundColor: FINCEPT.ORANGE,- color: FINCEPT.DARK_BG,- border: 'none',- fontSize: '11px',- fontWeight: 700,- fontFamily: '"IBM Plex Mono", monospace',- cursor: 'pointer',- letterSpacing: '0.5px',- display: 'flex',- alignItems: 'center',- gap: '8px'- }}- onMouseOver={(e) => e.currentTarget.style.backgroundColor = '#FFA033'}- onMouseOut={(e) => e.currentTarget.style.backgroundColor = FINCEPT.ORANGE}- >- <Plus size={16} />- CREATE COMPETITION- </button>- </div>- );- }-- return (- <div style={{- flex: 1,- display: 'flex',- flexDirection: 'column',- overflow: 'hidden'- }}>- {/* Header */}- <div style={{- padding: '16px 20px',- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `1px solid ${FINCEPT.BORDER}`,- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center'- }}>- <div style={{- fontSize: '11px',- fontWeight: 700,- color: FINCEPT.ORANGE,- letterSpacing: '0.5px',- fontFamily: '"IBM Plex Mono", monospace'- }}>- COMPETITION HISTORY ({competitions.length})- </div>- <button- onClick={onCreateNew}- style={{- padding: '8px 16px',- backgroundColor: FINCEPT.ORANGE,- color: FINCEPT.DARK_BG,- border: 'none',- fontSize: '10px',- fontWeight: 700,- fontFamily: '"IBM Plex Mono", monospace',- cursor: 'pointer',- letterSpacing: '0.5px',- display: 'flex',- alignItems: 'center',- gap: '6px'- }}- onMouseOver={(e) => e.currentTarget.style.backgroundColor = '#FFA033'}- onMouseOut={(e) => e.currentTarget.style.backgroundColor = FINCEPT.ORANGE}- >- <Plus size={14} />- NEW- </button>- </div>-- {/* Competition List */}- <div style={{- flex: 1,- overflow: 'auto',- padding: '16px'- }}>- <div style={{- display: 'grid',- gridTemplateColumns: 'repeat(auto-fill, minmax(350px, 1fr))',- gap: '16px'- }}>- {competitions.map((comp) => (- <div- key={comp.id}- onClick={() => onViewCompetition(comp)}- style={{- backgroundColor: comp.id === currentCompetitionId ? FINCEPT.HEADER_BG : FINCEPT.PANEL_BG,- border: `1px solid ${comp.id === currentCompetitionId ? FINCEPT.ORANGE : FINCEPT.BORDER}`,- padding: '16px',- cursor: 'pointer',- transition: 'all 0.2s',- fontFamily: '"IBM Plex Mono", monospace'- }}- onMouseOver={(e) => {- if (comp.id !== currentCompetitionId) {- e.currentTarget.style.borderColor = FINCEPT.GRAY;- }- }}- onMouseOut={(e) => {- if (comp.id !== currentCompetitionId) {- e.currentTarget.style.borderColor = FINCEPT.BORDER;- }- }}- >- {/* Header */}- <div style={{- display: 'flex',- justifyContent: 'space-between',- alignItems: 'flex-start',- marginBottom: '12px'- }}>- <div style={{ flex: 1 }}>- <div style={{- fontSize: '12px',- fontWeight: 700,- color: FINCEPT.WHITE,- marginBottom: '4px'- }}>- {comp.name}- </div>- <div style={{- fontSize: '9px',- color: getStatusColor(comp.status),- fontWeight: 600,- letterSpacing: '0.5px'- }}>- ● {comp.status.toUpperCase()}- </div>- </div>- <div style={{ display: 'flex', gap: '8px' }}>- <button- onClick={(e) => {- e.stopPropagation();- onViewCompetition(comp);- }}- style={{- padding: '4px 8px',- backgroundColor: 'transparent',- border: `1px solid ${FINCEPT.CYAN}`,- color: FINCEPT.CYAN,- fontSize: '9px',- fontWeight: 600,- cursor: 'pointer',- fontFamily: '"IBM Plex Mono", monospace'- }}- title="View Details"- >- <Eye size={12} />- </button>- <button- onClick={(e) => handleDelete(comp.id, e)}- style={{- padding: '4px 8px',- backgroundColor: 'transparent',- border: `1px solid ${FINCEPT.RED}`,- color: FINCEPT.RED,- fontSize: '9px',- fontWeight: 600,- cursor: 'pointer',- fontFamily: '"IBM Plex Mono", monospace'- }}- title="Delete"- >- <Trash2 size={12} />- </button>- </div>- </div>-- {/* Details */}- <div style={{- display: 'grid',- gridTemplateColumns: '1fr 1fr',- gap: '8px',- marginBottom: '12px'- }}>- <div>- <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '2px' }}>SYMBOL</div>- <div style={{ fontSize: '10px', color: FINCEPT.CYAN, fontWeight: 600 }}>{comp.symbol}</div>- </div>- <div>- <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '2px' }}>MODE</div>- <div style={{ fontSize: '10px', color: FINCEPT.YELLOW, fontWeight: 600 }}>{comp.mode.toUpperCase()}</div>- </div>- <div>- <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '2px' }}>CYCLES</div>- <div style={{ fontSize: '10px', color: FINCEPT.WHITE, fontWeight: 600 }}>{comp.cycle_count}</div>- </div>- <div>- <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '2px' }}>CAPITAL</div>- <div style={{ fontSize: '10px', color: FINCEPT.GREEN, fontWeight: 600 }}>${comp.initial_capital.toLocaleString()}</div>- </div>- </div>-- {/* Timestamps */}- <div style={{- borderTop: `1px solid ${FINCEPT.BORDER}`,- paddingTop: '8px',- fontSize: '8px',- color: FINCEPT.MUTED- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '4px', marginBottom: '4px' }}>- <Calendar size={10} />- Created: {formatDate(comp.created_at || new Date().toISOString())}- </div>- {comp.started_at && (- <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>- <Clock size={10} />- Started: {formatDate(comp.started_at)}- </div>- )}- </div>- </div>- ))}- </div>- </div>- </div>- );-};--export default CompetitionDashboard;diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/TradeHistoryPanel.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/TradeHistoryPanel.tsxdeleted file mode 100644index 4f222d868..000000000--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/TradeHistoryPanel.tsx+++ /dev/null@@ -1,220 +0,0 @@-/**- * Trade History Panel - Shows executed trades with full details- */--import React from 'react';-import { TrendingUp, TrendingDown, Circle, CheckCircle, XCircle } from 'lucide-react';-import { AlphaDecisionLog } from '@/services/core/sqliteService';--interface TradeHistoryPanelProps {- decisions: AlphaDecisionLog[];-}--const FINCEPT = {- DARK_BG: '#000000',- PANEL_BG: '#0F0F0F',- HEADER_BG: '#1A1A1A',- BORDER: '#2A2A2A',- GRAY: '#787878',- MUTED: '#555555',- WHITE: '#FFFFFF',- ORANGE: '#FF8800',- GREEN: '#00D66F',- RED: '#FF3B3B',- CYAN: '#00E5FF',- YELLOW: '#FFD700',-};--export const TradeHistoryPanel: React.FC<TradeHistoryPanelProps> = ({ decisions }) => {- const formatTime = (timestamp: string) => {- const date = new Date(timestamp);- return date.toLocaleTimeString('en-US', {- hour: '2-digit',- minute: '2-digit',- second: '2-digit'- });- };-- const parseTradeExecuted = (trade: string | null) => {- if (!trade) return null;- try {- return JSON.parse(trade);- } catch {- return null;- }- };-- if (decisions.length === 0) {- return (- <div style={{- padding: '24px',- textAlign: 'center',- color: FINCEPT.GRAY,- fontSize: '10px',- fontFamily: '"IBM Plex Mono", monospace'- }}>- No trade history yet. Start the competition to see executed trades.- </div>- );- }-- return (- <div style={{- flex: 1,- overflow: 'auto',- fontFamily: '"IBM Plex Mono", monospace'- }}>- {/* Header */}- <div style={{- display: 'grid',- gridTemplateColumns: '100px 80px 120px 100px 100px 100px 1fr 80px',- padding: '8px 12px',- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `1px solid ${FINCEPT.BORDER}`,- fontSize: '8px',- fontWeight: 700,- color: FINCEPT.GRAY,- letterSpacing: '0.5px',- position: 'sticky',- top: 0- }}>- <div>TIME</div>- <div>CYCLE</div>- <div>MODEL</div>- <div>ACTION</div>- <div>QUANTITY</div>- <div>PRICE</div>- <div>REASON</div>- <div>STATUS</div>- </div>-- {/* Trade Rows */}- {decisions.map((decision, idx) => {- const tradeExecuted = parseTradeExecuted(decision.trade_executed);- const isExecuted = tradeExecuted?.status === 'executed';- const isRejected = tradeExecuted?.status === 'rejected';- const isHold = decision.action === 'hold';-- return (- <div- key={decision.id || idx}- style={{- display: 'grid',- gridTemplateColumns: '100px 80px 120px 100px 100px 100px 1fr 80px',- padding: '10px 12px',- borderBottom: `1px solid ${FINCEPT.BORDER}`,- fontSize: '9px',- color: FINCEPT.WHITE,- alignItems: 'center',- backgroundColor: idx % 2 === 0 ? FINCEPT.DARK_BG : FINCEPT.PANEL_BG- }}- >- {/* Time */}- <div style={{ color: FINCEPT.GRAY }}>- {formatTime(decision.timestamp)}- </div>-- {/* Cycle */}- <div style={{ color: FINCEPT.CYAN, fontWeight: 600 }}>- #{decision.cycle_number}- </div>-- {/* Model */}- <div style={{- color: FINCEPT.ORANGE,- fontSize: '8px',- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap'- }}>- {decision.model_name}- </div>-- {/* Action */}- <div style={{- display: 'flex',- alignItems: 'center',- gap: '4px',- fontWeight: 700- }}>- {decision.action === 'buy' && (- <>- <TrendingUp size={12} color={FINCEPT.GREEN} />- <span style={{ color: FINCEPT.GREEN }}>BUY</span>- </>- )}- {decision.action === 'sell' && (- <>- <TrendingDown size={12} color={FINCEPT.RED} />- <span style={{ color: FINCEPT.RED }}>SELL</span>- </>- )}- {decision.action === 'hold' && (- <>- <Circle size={12} color={FINCEPT.GRAY} />- <span style={{ color: FINCEPT.GRAY }}>HOLD</span>- </>- )}- </div>-- {/* Quantity */}- <div style={{ color: FINCEPT.WHITE, fontWeight: 600 }}>- {decision.quantity ? `×${decision.quantity.toFixed(3)}` : '-'}- </div>-- {/* Price */}- <div style={{ color: FINCEPT.CYAN }}>- {decision.price_at_decision- ? `$${decision.price_at_decision.toLocaleString('en-US', { minimumFractionDigits: 2 })}`- : '-'}- </div>-- {/* Reasoning */}- <div style={{- color: FINCEPT.GRAY,- fontSize: '8px',- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap'- }}>- {decision.reasoning || '-'}- </div>-- {/* Status */}- <div style={{- display: 'flex',- alignItems: 'center',- gap: '4px',- fontSize: '8px',- fontWeight: 600- }}>- {isExecuted && (- <>- <CheckCircle size={10} color={FINCEPT.GREEN} />- <span style={{ color: FINCEPT.GREEN }}>EXEC</span>- </>- )}- {isRejected && (- <>- <XCircle size={10} color={FINCEPT.RED} />- <span style={{ color: FINCEPT.RED }}>REJ</span>- </>- )}- {isHold && (- <>- <Circle size={10} color={FINCEPT.GRAY} />- <span style={{ color: FINCEPT.GRAY }}>HOLD</span>- </>- )}- {!isExecuted && !isRejected && !isHold && (- <span style={{ color: FINCEPT.YELLOW }}>PEND</span>- )}- </div>- </div>- );- })}- </div>- );-};--export default TradeHistoryPanel;diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/AlphaArenaHeader.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/AlphaArenaHeader.tsxnew file mode 100644index 000000000..8be5e3146--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/AlphaArenaHeader.tsx@@ -0,0 +1,98 @@+/**+ * Alpha Arena Header Component+ *+ * Displays the header with title and status indicators.+ */++import React from 'react';+import { Trophy, Settings, Info } from 'lucide-react';+import type { CompetitionStatus } from '../types';++interface AlphaArenaHeaderProps {+ competitionId?: string;+ status: CompetitionStatus | null;+ cycleCount: number;+ onSettingsClick?: () => void;+}++const AlphaArenaHeader: React.FC<AlphaArenaHeaderProps> = ({+ competitionId,+ status,+ cycleCount,+ onSettingsClick,+}) => {+ const getStatusBadge = (status: CompetitionStatus | null) => {+ if (!status) return null;++ const statusConfig = {+ created: { label: 'Ready', color: 'bg-blue-500/20 text-blue-400' },+ running: { label: 'Running', color: 'bg-green-500/20 text-green-400' },+ paused: { label: 'Paused', color: 'bg-yellow-500/20 text-yellow-400' },+ completed: { label: 'Completed', color: 'bg-gray-500/20 text-gray-400' },+ failed: { label: 'Failed', color: 'bg-red-500/20 text-red-400' },+ };++ const config = statusConfig[status] || statusConfig.created;++ return (+ <span className={`px-2 py-1 rounded text-xs font-medium ${config.color}`}>+ {config.label}+ </span>+ );+ };++ return (+ <div className="bg-[#1A1A1A] border-b border-[#2A2A2A] px-6 py-4">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-4">+ <div className="flex items-center gap-2">+ <Trophy className="w-6 h-6 text-[#FF8800]" />+ <h1 className="text-xl font-bold text-white">Alpha Arena</h1>+ </div>++ {competitionId && (+ <>+ <div className="h-6 w-px bg-[#2A2A2A]" />+ <div className="flex items-center gap-2">+ <span className="text-sm text-[#787878]">+ {competitionId.slice(0, 12)}...+ </span>+ {getStatusBadge(status)}+ </div>+ </>+ )}++ {cycleCount > 0 && (+ <div className="flex items-center gap-1 text-sm text-[#787878]">+ <span className="text-[#FF8800] font-mono">{cycleCount}</span>+ <span>cycles</span>+ </div>+ )}+ </div>++ <div className="flex items-center gap-2">+ <button+ onClick={onSettingsClick}+ className="p-2 rounded-lg hover:bg-[#2A2A2A] text-[#787878] hover:text-white transition-colors"+ title="Settings"+ >+ <Settings className="w-5 h-5" />+ </button>+ <button+ className="p-2 rounded-lg hover:bg-[#2A2A2A] text-[#787878] hover:text-white transition-colors"+ title="Info"+ >+ <Info className="w-5 h-5" />+ </button>+ </div>+ </div>++ {/* Subtitle */}+ <p className="text-sm text-[#787878] mt-1">+ AI Trading Competition - Multiple LLM models compete in real-time trading+ </p>+ </div>+ );+};++export default AlphaArenaHeader;diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/ApiKeysModal.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/ApiKeysModal.tsxnew file mode 100644index 000000000..56ec2b961--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/ApiKeysModal.tsx@@ -0,0 +1,246 @@+/**+ * API Keys Modal Component+ *+ * Modal for configuring LLM provider API keys.+ */++import React, { useState, useEffect } from 'react';+import { X, Key, Eye, EyeOff, Save, Loader2, AlertCircle } from 'lucide-react';+import alphaArenaService from '../services/alphaArenaService';++interface ApiKeysModalProps {+ isOpen: boolean;+ onClose: () => void;+}++interface ApiKeyConfig {+ provider: string;+ label: string;+ envVar: string;+ value: string;+ placeholder: string;+}++const DEFAULT_PROVIDERS: Omit<ApiKeyConfig, 'value'>[] = [+ {+ provider: 'openai',+ label: 'OpenAI',+ envVar: 'OPENAI_API_KEY',+ placeholder: 'sk-...',+ },+ {+ provider: 'anthropic',+ label: 'Anthropic',+ envVar: 'ANTHROPIC_API_KEY',+ placeholder: 'sk-ant-...',+ },+ {+ provider: 'google',+ label: 'Google AI',+ envVar: 'GOOGLE_API_KEY',+ placeholder: 'AIza...',+ },+ {+ provider: 'deepseek',+ label: 'DeepSeek',+ envVar: 'DEEPSEEK_API_KEY',+ placeholder: 'sk-...',+ },+ {+ provider: 'groq',+ label: 'Groq',+ envVar: 'GROQ_API_KEY',+ placeholder: 'gsk_...',+ },+];++const ApiKeysModal: React.FC<ApiKeysModalProps> = ({ isOpen, onClose }) => {+ const [apiKeys, setApiKeys] = useState<ApiKeyConfig[]>(+ DEFAULT_PROVIDERS.map((p) => ({ ...p, value: '' }))+ );+ const [visibleKeys, setVisibleKeys] = useState<Record<string, boolean>>({});+ const [isSaving, setIsSaving] = useState(false);+ const [isLoading, setIsLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);+ const [success, setSuccess] = useState(false);++ // Load existing keys on mount+ useEffect(() => {+ if (isOpen) {+ loadApiKeys();+ }+ }, [isOpen]);++ const loadApiKeys = async () => {+ setIsLoading(true);+ setError(null);++ try {+ const result = await alphaArenaService.getApiKeys();+ if (result.success && result.keys) {+ setApiKeys((prev) =>+ prev.map((key) => ({+ ...key,+ value: result.keys?.[key.provider] || '',+ }))+ );+ }+ } catch (err) {+ console.error('Failed to load API keys:', err);+ } finally {+ setIsLoading(false);+ }+ };++ const handleKeyChange = (provider: string, value: string) => {+ setApiKeys((prev) =>+ prev.map((key) => (key.provider === provider ? { ...key, value } : key))+ );+ setSuccess(false);+ };++ const toggleVisibility = (provider: string) => {+ setVisibleKeys((prev) => ({+ ...prev,+ [provider]: !prev[provider],+ }));+ };++ const handleSave = async () => {+ setIsSaving(true);+ setError(null);+ setSuccess(false);++ try {+ const keysToSave: Record<string, string> = {};+ apiKeys.forEach((key) => {+ if (key.value.trim()) {+ keysToSave[key.provider] = key.value.trim();+ }+ });++ const result = await alphaArenaService.saveApiKeys(keysToSave);+ if (result.success) {+ setSuccess(true);+ setTimeout(() => setSuccess(false), 3000);+ } else {+ setError(result.error || 'Failed to save API keys');+ }+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Unknown error');+ } finally {+ setIsSaving(false);+ }+ };++ if (!isOpen) return null;++ return (+ <div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50">+ <div className="bg-[#0F0F0F] rounded-lg border border-[#2A2A2A] w-full max-w-lg">+ {/* Header */}+ <div className="flex items-center justify-between px-6 py-4 border-b border-[#2A2A2A]">+ <div className="flex items-center gap-2">+ <Key className="w-5 h-5 text-[#FF8800]" />+ <h2 className="text-lg font-semibold text-white">API Keys</h2>+ </div>+ <button+ onClick={onClose}+ className="p-1 rounded hover:bg-[#2A2A2A] text-[#787878] hover:text-white"+ >+ <X className="w-5 h-5" />+ </button>+ </div>++ {/* Content */}+ <div className="p-6 space-y-4">+ {error && (+ <div className="flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg text-red-400 text-sm">+ <AlertCircle className="w-4 h-4 flex-shrink-0" />+ {error}+ </div>+ )}++ {success && (+ <div className="p-3 bg-green-500/10 border border-green-500/30 rounded-lg text-green-400 text-sm">+ API keys saved successfully+ </div>+ )}++ <p className="text-sm text-[#787878]">+ Configure API keys for LLM providers. Keys are stored securely and+ used for AI trading agents.+ </p>++ {isLoading ? (+ <div className="flex items-center justify-center py-8">+ <Loader2 className="w-6 h-6 animate-spin text-[#FF8800]" />+ </div>+ ) : (+ <div className="space-y-3">+ {apiKeys.map((key) => (+ <div key={key.provider}>+ <label className="block text-sm font-medium text-white mb-1">+ {key.label}+ </label>+ <div className="relative">+ <input+ type={visibleKeys[key.provider] ? 'text' : 'password'}+ value={key.value}+ onChange={(e) =>+ handleKeyChange(key.provider, e.target.value)+ }+ placeholder={key.placeholder}+ className="w-full px-3 py-2 pr-10 bg-[#1A1A1A] border border-[#2A2A2A] rounded-lg text-white placeholder-[#505050] focus:border-[#FF8800] focus:outline-none font-mono text-sm"+ />+ <button+ type="button"+ onClick={() => toggleVisibility(key.provider)}+ className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-[#787878] hover:text-white"+ >+ {visibleKeys[key.provider] ? (+ <EyeOff className="w-4 h-4" />+ ) : (+ <Eye className="w-4 h-4" />+ )}+ </button>+ </div>+ <p className="text-xs text-[#505050] mt-1">{key.envVar}</p>+ </div>+ ))}+ </div>+ )}+ </div>++ {/* Footer */}+ <div className="flex justify-end gap-3 px-6 py-4 border-t border-[#2A2A2A]">+ <button+ onClick={onClose}+ className="px-4 py-2 rounded-lg border border-[#2A2A2A] text-[#787878] hover:bg-[#1A1A1A]"+ >+ Cancel+ </button>+ <button+ onClick={handleSave}+ disabled={isSaving}+ className="px-4 py-2 rounded-lg bg-[#FF8800] text-black font-medium hover:bg-[#FF9900] disabled:opacity-50 flex items-center gap-2"+ >+ {isSaving ? (+ <>+ <Loader2 className="w-4 h-4 animate-spin" />+ Saving...+ </>+ ) : (+ <>+ <Save className="w-4 h-4" />+ Save Keys+ </>+ )}+ </button>+ </div>+ </div>+ </div>+ );+};++export default ApiKeysModal;diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/CompetitionControls.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/CompetitionControls.tsxnew file mode 100644index 000000000..bf21cd772--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/CompetitionControls.tsx@@ -0,0 +1,123 @@+/**+ * Competition Controls Component+ *+ * Controls for running competition cycles.+ */++import React from 'react';+import { Play, Square, RefreshCw, RotateCcw, Loader2 } from 'lucide-react';++interface CompetitionControlsProps {+ isRunning: boolean;+ isAutoRunning: boolean;+ isLoading: boolean;+ hasCompetition: boolean;+ onRunCycle: () => void;+ onToggleAutoRun: () => void;+ onReset?: () => void;+ cycleInterval?: number;+}++const CompetitionControls: React.FC<CompetitionControlsProps> = ({+ isRunning,+ isAutoRunning,+ isLoading,+ hasCompetition,+ onRunCycle,+ onToggleAutoRun,+ onReset,+ cycleInterval = 150,+}) => {+ return (+ <div className="bg-[#0F0F0F] rounded-lg p-4 border border-[#2A2A2A]">+ <div className="flex items-center justify-between">+ <h3 className="text-white font-semibold">Controls</h3>++ {isAutoRunning && (+ <span className="text-xs text-[#787878]">+ Auto-run every {cycleInterval}s+ </span>+ )}+ </div>++ <div className="flex items-center gap-3 mt-4">+ {/* Run Single Cycle */}+ <button+ onClick={onRunCycle}+ disabled={!hasCompetition || isLoading || isAutoRunning}+ className="flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-lg bg-[#FF8800] text-black font-medium hover:bg-[#FF9900] disabled:opacity-50 disabled:cursor-not-allowed transition-colors"+ >+ {isLoading ? (+ <>+ <Loader2 className="w-5 h-5 animate-spin" />+ Running...+ </>+ ) : (+ <>+ <Play className="w-5 h-5" />+ Run Cycle+ </>+ )}+ </button>++ {/* Auto Run Toggle */}+ <button+ onClick={onToggleAutoRun}+ disabled={!hasCompetition}+ className={`flex items-center justify-center gap-2 px-4 py-3 rounded-lg border font-medium transition-colors ${+ isAutoRunning+ ? 'bg-red-500/10 border-red-500 text-red-400 hover:bg-red-500/20'+ : 'bg-[#1A1A1A] border-[#2A2A2A] text-white hover:bg-[#2A2A2A]'+ }`}+ >+ {isAutoRunning ? (+ <>+ <Square className="w-5 h-5" />+ Stop Auto+ </>+ ) : (+ <>+ <RefreshCw className="w-5 h-5" />+ Auto Run+ </>+ )}+ </button>++ {/* Reset */}+ {onReset && (+ <button+ onClick={onReset}+ disabled={isLoading || isAutoRunning}+ className="p-3 rounded-lg border border-[#2A2A2A] text-[#787878] hover:bg-[#1A1A1A] hover:text-white transition-colors disabled:opacity-50"+ title="Reset Competition"+ >+ <RotateCcw className="w-5 h-5" />+ </button>+ )}+ </div>++ {/* Status indicators */}+ <div className="flex items-center gap-4 mt-4 text-sm">+ <div className="flex items-center gap-2">+ <div+ className={`w-2 h-2 rounded-full ${+ isRunning ? 'bg-green-500' : 'bg-[#787878]'+ }`}+ />+ <span className="text-[#787878]">+ {isRunning ? 'Competition Active' : 'Competition Idle'}+ </span>+ </div>++ {isAutoRunning && (+ <div className="flex items-center gap-2">+ <div className="w-2 h-2 rounded-full bg-blue-500 animate-pulse" />+ <span className="text-blue-400">Auto-running</span>+ </div>+ )}+ </div>+ </div>+ );+};++export default CompetitionControls;diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/DecisionsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/DecisionsPanel.tsxnew file mode 100644index 000000000..21baa21b2--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/DecisionsPanel.tsx@@ -0,0 +1,181 @@+/**+ * Decisions Panel Component+ *+ * Displays recent trading decisions from AI models.+ */++import React from 'react';+import { Brain, TrendingUp, TrendingDown, Pause, ArrowUpRight, ArrowDownRight } from 'lucide-react';+import type { ModelDecision } from '../types';+import { formatCurrency, getModelColor } from '../types';++interface DecisionsPanelProps {+ decisions: ModelDecision[];+ maxItems?: number;+ isLoading?: boolean;+}++const DecisionsPanel: React.FC<DecisionsPanelProps> = ({+ decisions,+ maxItems = 10,+ isLoading = false,+}) => {+ const displayDecisions = decisions.slice(0, maxItems);++ if (isLoading) {+ return (+ <div className="bg-[#0F0F0F] rounded-lg p-4 border border-[#2A2A2A]">+ <div className="flex items-center gap-2 mb-4">+ <Brain className="w-5 h-5 text-[#FF8800]" />+ <h3 className="text-white font-semibold">Recent Decisions</h3>+ </div>+ <div className="space-y-2">+ {[1, 2, 3].map((i) => (+ <div key={i} className="h-16 bg-[#1A1A1A] rounded animate-pulse" />+ ))}+ </div>+ </div>+ );+ }++ if (displayDecisions.length === 0) {+ return (+ <div className="bg-[#0F0F0F] rounded-lg p-4 border border-[#2A2A2A]">+ <div className="flex items-center gap-2 mb-4">+ <Brain className="w-5 h-5 text-[#FF8800]" />+ <h3 className="text-white font-semibold">Recent Decisions</h3>+ </div>+ <p className="text-[#787878] text-center py-8">+ No decisions yet. Run a cycle to see AI model decisions.+ </p>+ </div>+ );+ }++ return (+ <div className="bg-[#0F0F0F] rounded-lg p-4 border border-[#2A2A2A]">+ <div className="flex items-center justify-between mb-4">+ <div className="flex items-center gap-2">+ <Brain className="w-5 h-5 text-[#FF8800]" />+ <h3 className="text-white font-semibold">Recent Decisions</h3>+ </div>+ <span className="text-sm text-[#787878]">{decisions.length} total</span>+ </div>++ <div className="space-y-2 max-h-[400px] overflow-y-auto custom-scrollbar">+ {displayDecisions.map((decision, index) => (+ <DecisionCard key={`${decision.model_name}-${decision.cycle_number}-${index}`} decision={decision} />+ ))}+ </div>+ </div>+ );+};++interface DecisionCardProps {+ decision: ModelDecision;+}++const DecisionCard: React.FC<DecisionCardProps> = ({ decision }) => {+ const modelColor = getModelColor(decision.model_name);++ const getActionIcon = (action: string) => {+ switch (action.toLowerCase()) {+ case 'buy':+ return <TrendingUp className="w-4 h-4 text-[#00D66F]" />;+ case 'sell':+ return <TrendingDown className="w-4 h-4 text-[#FF3B3B]" />;+ case 'short':+ return <ArrowDownRight className="w-4 h-4 text-[#FF3B3B]" />;+ default:+ return <Pause className="w-4 h-4 text-[#787878]" />;+ }+ };++ const getActionColor = (action: string) => {+ switch (action.toLowerCase()) {+ case 'buy':+ return 'text-[#00D66F] bg-[#00D66F]/10';+ case 'sell':+ return 'text-[#FF3B3B] bg-[#FF3B3B]/10';+ case 'short':+ return 'text-[#FF3B3B] bg-[#FF3B3B]/10';+ default:+ return 'text-[#787878] bg-[#787878]/10';+ }+ };++ const confidenceColor = decision.confidence >= 0.7+ ? 'text-[#00D66F]'+ : decision.confidence >= 0.5+ ? 'text-[#FF8800]'+ : 'text-[#FF3B3B]';++ return (+ <div className="p-3 bg-[#1A1A1A] rounded-lg border border-[#2A2A2A] hover:border-[#3A3A3A] transition-colors">+ <div className="flex items-start gap-3">+ {/* Model indicator */}+ <div+ className="w-1 h-full min-h-[50px] rounded-full"+ style={{ backgroundColor: modelColor }}+ />++ <div className="flex-1 min-w-0">+ {/* Header */}+ <div className="flex items-center justify-between mb-2">+ <div className="flex items-center gap-2">+ <span className="text-white font-medium text-sm">+ {decision.model_name}+ </span>+ <span className="text-xs text-[#787878]">+ Cycle {decision.cycle_number}+ </span>+ </div>++ {/* Action badge */}+ <span className={`px-2 py-0.5 rounded text-xs font-medium uppercase flex items-center gap-1 ${getActionColor(decision.action)}`}>+ {getActionIcon(decision.action)}+ {decision.action}+ </span>+ </div>++ {/* Details */}+ <div className="flex items-center gap-4 text-xs text-[#787878] mb-2">+ <span>{decision.symbol}</span>+ {decision.quantity > 0 && (+ <span>Qty: {decision.quantity.toFixed(4)}</span>+ )}+ {decision.price_at_decision && (+ <span>@ {formatCurrency(decision.price_at_decision)}</span>+ )}+ <span className={confidenceColor}>+ {(decision.confidence * 100).toFixed(0)}% confidence+ </span>+ </div>++ {/* Reasoning */}+ {decision.reasoning && (+ <p className="text-xs text-[#A0A0A0] line-clamp-2">+ {decision.reasoning}+ </p>+ )}++ {/* Trade result */}+ {decision.trade_executed && (+ <div className="mt-2 pt-2 border-t border-[#2A2A2A]">+ <span className="text-xs text-[#787878]">+ Trade: {decision.trade_executed.status}+ {decision.trade_executed.pnl !== undefined && (+ <span className={decision.trade_executed.pnl >= 0 ? 'text-[#00D66F]' : 'text-[#FF3B3B]'}>+ {' '}({decision.trade_executed.pnl >= 0 ? '+' : ''}{formatCurrency(decision.trade_executed.pnl)})+ </span>+ )}+ </span>+ </div>+ )}+ </div>+ </div>+ </div>+ );+};++export default DecisionsPanel;diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/Leaderboard.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/Leaderboard.tsxnew file mode 100644index 000000000..910cc3f0b--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/Leaderboard.tsx@@ -0,0 +1,142 @@+/**+ * Leaderboard Component+ *+ * Displays the competition leaderboard with rankings and performance metrics.+ */++import React from 'react';+import { Trophy, TrendingUp, TrendingDown, Minus } from 'lucide-react';+import type { LeaderboardEntry } from '../types';+import { formatCurrency, formatPercent, getModelColor } from '../types';++interface LeaderboardProps {+ entries: LeaderboardEntry[];+ cycleNumber?: number;+ isLoading?: boolean;+}++const Leaderboard: React.FC<LeaderboardProps> = ({+ entries,+ cycleNumber = 0,+ isLoading = false,+}) => {+ if (isLoading) {+ return (+ <div className="bg-[#0F0F0F] rounded-lg p-4 border border-[#2A2A2A]">+ <div className="flex items-center gap-2 mb-4">+ <Trophy className="w-5 h-5 text-[#FF8800]" />+ <h3 className="text-white font-semibold">Leaderboard</h3>+ </div>+ <div className="space-y-2">+ {[1, 2, 3].map((i) => (+ <div key={i} className="h-12 bg-[#1A1A1A] rounded animate-pulse" />+ ))}+ </div>+ </div>+ );+ }++ if (entries.length === 0) {+ return (+ <div className="bg-[#0F0F0F] rounded-lg p-4 border border-[#2A2A2A]">+ <div className="flex items-center gap-2 mb-4">+ <Trophy className="w-5 h-5 text-[#FF8800]" />+ <h3 className="text-white font-semibold">Leaderboard</h3>+ </div>+ <p className="text-[#787878] text-center py-8">+ No competition data yet. Create and run a competition to see results.+ </p>+ </div>+ );+ }++ return (+ <div className="bg-[#0F0F0F] rounded-lg p-4 border border-[#2A2A2A]">+ <div className="flex items-center justify-between mb-4">+ <div className="flex items-center gap-2">+ <Trophy className="w-5 h-5 text-[#FF8800]" />+ <h3 className="text-white font-semibold">Leaderboard</h3>+ </div>+ <span className="text-sm text-[#787878]">Cycle {cycleNumber}</span>+ </div>++ <div className="space-y-2">+ {entries.map((entry) => (+ <LeaderboardRow key={entry.model_name} entry={entry} />+ ))}+ </div>+ </div>+ );+};++interface LeaderboardRowProps {+ entry: LeaderboardEntry;+}++const LeaderboardRow: React.FC<LeaderboardRowProps> = ({ entry }) => {+ const isPositive = entry.total_pnl >= 0;+ const modelColor = getModelColor(entry.model_name);++ // Rank badge styling+ const getRankBadge = (rank: number) => {+ if (rank === 1) return 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30';+ if (rank === 2) return 'bg-gray-400/20 text-gray-300 border-gray-400/30';+ if (rank === 3) return 'bg-orange-600/20 text-orange-400 border-orange-500/30';+ return 'bg-[#1A1A1A] text-[#787878] border-[#2A2A2A]';+ };++ return (+ <div className="flex items-center gap-3 p-3 bg-[#1A1A1A] rounded-lg hover:bg-[#222222] transition-colors">+ {/* Rank */}+ <div+ className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold border ${getRankBadge(entry.rank)}`}+ >+ {entry.rank}+ </div>++ {/* Model indicator */}+ <div+ className="w-1 h-10 rounded-full"+ style={{ backgroundColor: modelColor }}+ />++ {/* Model name and stats */}+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-white font-medium truncate">+ {entry.model_name}+ </span>+ {entry.rank === 1 && <Trophy className="w-4 h-4 text-yellow-400" />}+ </div>+ <div className="flex items-center gap-4 text-xs text-[#787878]">+ <span>{entry.trades_count} trades</span>+ <span>{entry.positions_count} positions</span>+ {entry.win_rate !== undefined && (+ <span>{(entry.win_rate * 100).toFixed(0)}% win rate</span>+ )}+ </div>+ </div>++ {/* P&L */}+ <div className="text-right">+ <div className="flex items-center gap-1">+ {isPositive ? (+ <TrendingUp className="w-4 h-4 text-[#00D66F]" />+ ) : entry.total_pnl === 0 ? (+ <Minus className="w-4 h-4 text-[#787878]" />+ ) : (+ <TrendingDown className="w-4 h-4 text-[#FF3B3B]" />+ )}+ <span className={isPositive ? 'text-[#00D66F]' : entry.total_pnl === 0 ? 'text-[#787878]' : 'text-[#FF3B3B]'}>+ {formatPercent(entry.return_pct)}+ </span>+ </div>+ <span className="text-xs text-[#787878]">+ {formatCurrency(entry.portfolio_value)}+ </span>+ </div>+ </div>+ );+};++export default Leaderboard;diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/PerformanceChart.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/PerformanceChart.tsxnew file mode 100644index 000000000..7ccbd0cc7--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/PerformanceChart.tsx@@ -0,0 +1,149 @@+/**+ * Performance Chart Component+ *+ * Displays portfolio value over time for all competing models.+ */++import React, { useMemo } from 'react';+import {+ LineChart,+ Line,+ XAxis,+ YAxis,+ Tooltip,+ Legend,+ ResponsiveContainer,+ CartesianGrid,+} from 'recharts';+import { TrendingUp } from 'lucide-react';+import type { PerformanceSnapshot, ChartData } from '../types';+import { formatCurrency, MODEL_COLORS } from '../types';++interface PerformanceChartProps {+ snapshots: PerformanceSnapshot[];+ height?: number;+ showLegend?: boolean;+}++const PerformanceChart: React.FC<PerformanceChartProps> = ({+ snapshots,+ height = 300,+ showLegend = true,+}) => {+ // Transform snapshots into chart data+ const { chartData, modelNames } = useMemo(() => {+ if (!snapshots.length) {+ return { chartData: [], modelNames: [] };+ }++ // Group by cycle+ const cycleData = new Map<number, ChartData[number]>();+ const models = new Set<string>();++ snapshots.forEach((snap) => {+ models.add(snap.model_name);++ if (!cycleData.has(snap.cycle_number)) {+ cycleData.set(snap.cycle_number, {+ cycle: snap.cycle_number,+ timestamp: snap.timestamp,+ });+ }++ const data = cycleData.get(snap.cycle_number)!;+ data[snap.model_name] = snap.portfolio_value;+ });++ // Sort by cycle and convert to array+ const sorted = Array.from(cycleData.entries())+ .sort((a, b) => a[0] - b[0])+ .map(([, data]) => data);++ return {+ chartData: sorted,+ modelNames: Array.from(models),+ };+ }, [snapshots]);++ if (chartData.length === 0) {+ return (+ <div className="bg-[#0F0F0F] rounded-lg p-4 border border-[#2A2A2A]">+ <div className="flex items-center gap-2 mb-4">+ <TrendingUp className="w-5 h-5 text-[#FF8800]" />+ <h3 className="text-white font-semibold">Performance Chart</h3>+ </div>+ <div+ className="flex items-center justify-center text-[#787878]"+ style={{ height }}+ >+ Run cycles to see performance data+ </div>+ </div>+ );+ }++ return (+ <div className="bg-[#0F0F0F] rounded-lg p-4 border border-[#2A2A2A]">+ <div className="flex items-center gap-2 mb-4">+ <TrendingUp className="w-5 h-5 text-[#FF8800]" />+ <h3 className="text-white font-semibold">Performance Chart</h3>+ </div>++ <ResponsiveContainer width="100%" height={height}>+ <LineChart+ data={chartData}+ margin={{ top: 5, right: 30, left: 20, bottom: 5 }}+ >+ <CartesianGrid strokeDasharray="3 3" stroke="#2A2A2A" />+ <XAxis+ dataKey="cycle"+ stroke="#787878"+ fontSize={12}+ tickFormatter={(value) => `#${value}`}+ />+ <YAxis+ stroke="#787878"+ fontSize={12}+ tickFormatter={(value) => `$${(value / 1000).toFixed(1)}k`}+ domain={['dataMin - 500', 'dataMax + 500']}+ />+ <Tooltip+ contentStyle={{+ backgroundColor: '#1A1A1A',+ border: '1px solid #2A2A2A',+ borderRadius: '8px',+ }}+ labelStyle={{ color: '#FFFFFF' }}+ formatter={(value: number, name: string) => [+ formatCurrency(value),+ name,+ ]}+ labelFormatter={(label) => `Cycle ${label}`}+ />+ {showLegend && (+ <Legend+ wrapperStyle={{ paddingTop: '10px' }}+ formatter={(value) => (+ <span style={{ color: '#FFFFFF' }}>{value}</span>+ )}+ />+ )}++ {modelNames.map((modelName) => (+ <Line+ key={modelName}+ type="monotone"+ dataKey={modelName}+ stroke={MODEL_COLORS[modelName] || '#6B7280'}+ strokeWidth={2}+ dot={{ fill: MODEL_COLORS[modelName] || '#6B7280', r: 3 }}+ activeDot={{ r: 5 }}+ />+ ))}+ </LineChart>+ </ResponsiveContainer>+ </div>+ );+};++export default PerformanceChart;diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/index.ts b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/index.tsnew file mode 100644index 000000000..e31ef32f6--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/index.ts@@ -0,0 +1,10 @@+/**+ * Alpha Arena Components Index+ */++export { default as AlphaArenaHeader } from './AlphaArenaHeader';+export { default as Leaderboard } from './Leaderboard';+export { default as DecisionsPanel } from './DecisionsPanel';+export { default as PerformanceChart } from './PerformanceChart';+export { default as CompetitionControls } from './CompetitionControls';+export { default as ApiKeysModal } from './ApiKeysModal';diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/index.ts b/fincept-terminal-desktop/src/components/tabs/alpha-arena/index.tsnew file mode 100644index 000000000..062913685--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/index.ts@@ -0,0 +1,17 @@+/**+ * Alpha Arena Tab Module+ *+ * AI Trading Competition where multiple LLM models compete in real-time trading.+ */++// Main Tab Component+export { default as AlphaArenaTab } from './AlphaArenaTab';++// Types+export * from './types';++// Services - export only the default to avoid duplicate type exports+export { default as alphaArenaService } from './services/alphaArenaService';++// Components+export * from './components';diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaService.ts b/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaService.tsnew file mode 100644index 000000000..d6432d40e--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaService.ts@@ -0,0 +1,669 @@+/**+ * Alpha Arena Service (v2.1)+ *+ * TypeScript service layer for interacting with the Alpha Arena Python backend+ * via Tauri Rust commands. Now integrated with the Repository pattern for+ * persistent trade decision storage.+ */++import { invoke } from '@tauri-apps/api/core';+import agentService, {+ type TradeDecision as AgentTradeDecision,+} from '@/services/agentService';+import type {+ CreateCompetitionRequest,+ CreateCompetitionResponse,+ RunCycleResponse,+ LeaderboardResponse,+ DecisionsResponse,+ SnapshotsResponse,+ ListAgentsResponse,+ ModelDecision,+} from '../types';++// =============================================================================+// API Key Management+// =============================================================================++interface ApiKeysResponse {+ success: boolean;+ keys?: Record<string, string>;+ error?: string;+}++/**+ * Get API keys (masked for display)+ */+export async function getApiKeys(): Promise<ApiKeysResponse> {+ try {+ const result = await invoke<ApiKeysResponse>('get_alpha_api_keys');+ return result;+ } catch (error) {+ console.error('Error getting API keys:', error);++ // Fallback to localStorage+ const stored = localStorage.getItem('alpha_arena_api_keys');+ if (stored) {+ return { success: true, keys: JSON.parse(stored) };+ }++ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++/**+ * Save API keys+ */+export async function saveApiKeys(+ keys: Record<string, string>+): Promise<{ success: boolean; error?: string }> {+ try {+ const result = await invoke<{ success: boolean; message?: string }>(+ 'save_alpha_api_keys',+ { keys }+ );++ // Also save to localStorage as backup+ localStorage.setItem('alpha_arena_api_keys', JSON.stringify(keys));++ return { success: result.success };+ } catch (error) {+ console.error('Error saving API keys:', error);++ // Fallback to localStorage only+ localStorage.setItem('alpha_arena_api_keys', JSON.stringify(keys));++ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++// =============================================================================+// Competition Management+// =============================================================================++/**+ * Create a new competition+ */+export async function createCompetition(+ request: CreateCompetitionRequest+): Promise<CreateCompetitionResponse> {+ try {+ const configJson = JSON.stringify(request);+ const result = await invoke<CreateCompetitionResponse>(+ 'create_alpha_competition',+ { configJson }+ );+ return result;+ } catch (error) {+ console.error('Error creating competition:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++/**+ * Start a competition+ */+export async function startCompetition(+ competitionId: string+): Promise<{ success: boolean; error?: string }> {+ try {+ const result = await invoke<{ success: boolean; error?: string }>(+ 'start_alpha_competition',+ { competitionId }+ );+ return result;+ } catch (error) {+ console.error('Error starting competition:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++/**+ * Run a single competition cycle+ * Now also saves decisions to the repository for persistence+ */+export async function runCycle(competitionId: string): Promise<RunCycleResponse> {+ try {+ const result = await invoke<RunCycleResponse>('run_alpha_cycle', {+ competitionId,+ });++ // If cycle was successful, save decisions to repository for persistence+ if (result.success && result.events) {+ const decisionEvents = result.events.filter(+ e => e.event === 'decision_completed' && e.metadata+ );++ for (const event of decisionEvents) {+ const meta = event.metadata as Record<string, unknown>;+ if (meta?.model_name && meta?.action && meta?.symbol) {+ try {+ await saveDecisionToRepository({+ competitionId,+ cycleNumber: result.cycle_number || 0,+ modelName: meta.model_name as string,+ action: meta.action as string,+ symbol: meta.symbol as string,+ quantity: (meta.quantity as number) || 0,+ price: meta.price as number | undefined,+ reasoning: (meta.reasoning as string) || '',+ confidence: (meta.confidence as number) || 0,+ });+ } catch (err) {+ console.warn('Failed to save decision to repository:', err);+ }+ }+ }+ }++ return result;+ } catch (error) {+ console.error('Error running cycle:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++/**+ * Stop a competition+ */+export async function stopCompetition(+ competitionId: string+): Promise<{ success: boolean; error?: string }> {+ try {+ const result = await invoke<{ success: boolean; error?: string }>(+ 'stop_alpha_competition',+ { competitionId }+ );+ return result;+ } catch (error) {+ console.error('Error stopping competition:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++// =============================================================================+// Data Retrieval+// =============================================================================++/**+ * Get current leaderboard+ */+export async function getLeaderboard(+ competitionId: string+): Promise<LeaderboardResponse> {+ try {+ console.log('[alphaArenaService] getLeaderboard called for:', competitionId);+ const rawResult = await invoke<unknown>('get_alpha_leaderboard', {+ competitionId,+ });+ console.log('[alphaArenaService] getLeaderboard raw result type:', typeof rawResult);+ console.log('[alphaArenaService] getLeaderboard raw result:', JSON.stringify(rawResult, null, 2));++ // Handle potential type issues - cast to expected type+ const result = rawResult as LeaderboardResponse;+ console.log('[alphaArenaService] getLeaderboard success:', result.success);+ console.log('[alphaArenaService] getLeaderboard leaderboard:', result.leaderboard);+ console.log('[alphaArenaService] getLeaderboard leaderboard length:', result.leaderboard?.length);++ return result;+ } catch (error) {+ console.error('[alphaArenaService] Error getting leaderboard:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++/**+ * Get model decisions - now uses repository for historical data+ */+export async function getDecisions(+ competitionId: string,+ modelName?: string+): Promise<DecisionsResponse> {+ try {+ console.log('[alphaArenaService] getDecisions called for:', competitionId, 'model:', modelName);+ // Try to get from Alpha Arena first+ const result = await invoke<DecisionsResponse>('get_alpha_model_decisions', {+ competitionId,+ modelName: modelName || null,+ });++ console.log('[alphaArenaService] getDecisions raw result:', result);+ console.log('[alphaArenaService] getDecisions success:', result.success);+ console.log('[alphaArenaService] getDecisions decisions:', result.decisions);+ console.log('[alphaArenaService] getDecisions decisions length:', result.decisions?.length);++ // Skip repository merging for now - just return the result+ return result;+ } catch (error) {+ console.error('[alphaArenaService] Error getting decisions:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++/**+ * Get performance snapshots for charting+ */+export async function getSnapshots(+ competitionId: string+): Promise<SnapshotsResponse> {+ try {+ console.log('[alphaArenaService] getSnapshots called for:', competitionId);+ const result = await invoke<SnapshotsResponse>('get_alpha_snapshots', {+ competitionId,+ });+ console.log('[alphaArenaService] getSnapshots raw result:', result);+ console.log('[alphaArenaService] getSnapshots success:', result.success);+ console.log('[alphaArenaService] getSnapshots snapshots:', result.snapshots);+ console.log('[alphaArenaService] getSnapshots snapshots length:', result.snapshots?.length);+ return result;+ } catch (error) {+ console.error('[alphaArenaService] Error getting snapshots:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++/**+ * List available agents+ */+export async function listAgents(): Promise<ListAgentsResponse> {+ try {+ const result = await invoke<ListAgentsResponse>('list_alpha_agents');+ return result;+ } catch (error) {+ console.error('Error listing agents:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++/**+ * Get evaluation metrics for a model+ */+export async function getEvaluation(+ competitionId: string,+ modelName: string+): Promise<{ success: boolean; metrics?: Record<string, number>; error?: string }> {+ try {+ const result = await invoke<{ success: boolean; metrics?: Record<string, number> }>(+ 'get_alpha_evaluation',+ { competitionId, modelName }+ );+ return result;+ } catch (error) {+ console.error('Error getting evaluation:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++// =============================================================================+// Repository Integration (NEW in v2.1)+// =============================================================================++interface SaveDecisionParams {+ competitionId: string;+ cycleNumber: number;+ modelName: string;+ action: string;+ symbol: string;+ quantity: number;+ price?: number;+ reasoning: string;+ confidence: number;+}++/**+ * Save a trade decision to the repository for persistence+ */+export async function saveDecisionToRepository(+ params: SaveDecisionParams+): Promise<{ success: boolean; decisionId?: string; error?: string }> {+ try {+ const result = await agentService.saveTradeDecision({+ competition_id: params.competitionId,+ model_name: params.modelName,+ cycle_number: params.cycleNumber,+ symbol: params.symbol,+ action: params.action,+ quantity: params.quantity,+ price: params.price,+ reasoning: params.reasoning,+ confidence: params.confidence,+ });++ return {+ success: result.success,+ decisionId: result.decision_id,+ error: result.error,+ };+ } catch (error) {+ console.error('Error saving decision to repository:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++/**+ * Get historical trade decisions from repository+ */+export async function getHistoricalDecisions(+ competitionId?: string,+ modelName?: string,+ limit: number = 100+): Promise<AgentTradeDecision[]> {+ try {+ return await agentService.getTradeDecisions({+ competition_id: competitionId,+ model_name: modelName,+ limit,+ });+ } catch (error) {+ console.error('Error getting historical decisions:', error);+ return [];+ }+}++/**+ * Get decisions for a specific cycle+ */+export async function getCycleDecisions(+ competitionId: string,+ cycleNumber: number+): Promise<AgentTradeDecision[]> {+ try {+ return await agentService.getTradeDecisions({+ competition_id: competitionId,+ cycle_number: cycleNumber,+ });+ } catch (error) {+ console.error('Error getting cycle decisions:', error);+ return [];+ }+}++/**+ * Get model performance summary from repository+ */+export async function getModelPerformanceSummary(+ competitionId: string,+ modelName: string+): Promise<{+ totalDecisions: number;+ buyCount: number;+ sellCount: number;+ holdCount: number;+ avgConfidence: number;+}> {+ try {+ const decisions = await agentService.getTradeDecisions({+ competition_id: competitionId,+ model_name: modelName,+ limit: 1000,+ });++ const summary = {+ totalDecisions: decisions.length,+ buyCount: 0,+ sellCount: 0,+ holdCount: 0,+ avgConfidence: 0,+ };++ let totalConfidence = 0;+ for (const d of decisions) {+ if (d.action === 'buy') summary.buyCount++;+ else if (d.action === 'sell') summary.sellCount++;+ else if (d.action === 'hold') summary.holdCount++;+ totalConfidence += d.confidence;+ }++ summary.avgConfidence = decisions.length > 0+ ? totalConfidence / decisions.length+ : 0;++ return summary;+ } catch (error) {+ console.error('Error getting model performance summary:', error);+ return {+ totalDecisions: 0,+ buyCount: 0,+ sellCount: 0,+ holdCount: 0,+ avgConfidence: 0,+ };+ }+}++// =============================================================================+// Competition Persistence & History+// =============================================================================++export interface StoredCompetition {+ competition_id: string;+ config: {+ competition_id: string;+ competition_name: string;+ models: Array<{+ name: string;+ provider: string;+ model_id: string;+ api_key?: string;+ initial_capital: number;+ }>;+ symbols: string[];+ initial_capital: number;+ mode: string;+ cycle_interval_seconds: number;+ exchange_id: string;+ };+ status: string;+ cycle_count: number;+ start_time: string | null;+ end_time: string | null;+ created_at: string;+}++export interface ListCompetitionsResponse {+ success: boolean;+ competitions?: StoredCompetition[];+ count?: number;+ error?: string;+}++export interface GetCompetitionResponse {+ success: boolean;+ competition?: StoredCompetition;+ error?: string;+}++/**+ * List all past competitions from the database+ */+export async function listCompetitions(limit: number = 50): Promise<ListCompetitionsResponse> {+ try {+ const result = await invoke<ListCompetitionsResponse>('list_alpha_competitions', {+ limit,+ });+ return result;+ } catch (error) {+ console.error('Error listing competitions:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++/**+ * Get a specific competition by ID+ */+export async function getCompetition(competitionId: string): Promise<GetCompetitionResponse> {+ try {+ const result = await invoke<GetCompetitionResponse>('get_alpha_competition', {+ competitionId,+ });+ return result;+ } catch (error) {+ console.error('Error getting competition:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++/**+ * Delete a competition+ */+export async function deleteCompetition(competitionId: string): Promise<{ success: boolean; error?: string }> {+ try {+ const result = await invoke<{ success: boolean; error?: string }>('delete_alpha_competition', {+ competitionId,+ });+ return result;+ } catch (error) {+ console.error('Error deleting competition:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++/**+ * Resume/reload a past competition+ * This loads the competition from the database and prepares it for running+ */+export async function resumeCompetition(competitionId: string): Promise<{+ success: boolean;+ competition?: StoredCompetition;+ error?: string;+}> {+ try {+ // First, get the competition data+ const compResult = await getCompetition(competitionId);+ if (!compResult.success || !compResult.competition) {+ return {+ success: false,+ error: compResult.error || 'Competition not found',+ };+ }++ // The backend will restore it from the database when we run the next cycle+ return {+ success: true,+ competition: compResult.competition,+ };+ } catch (error) {+ console.error('Error resuming competition:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Unknown error',+ };+ }+}++// =============================================================================+// Auto-Run Management+// =============================================================================++let autoRunInterval: ReturnType<typeof setInterval> | null = null;++export function startAutoRun(+ competitionId: string,+ intervalSeconds: number,+ onCycleComplete: (result: RunCycleResponse) => void+): void {+ stopAutoRun();++ autoRunInterval = setInterval(async () => {+ const result = await runCycle(competitionId);+ onCycleComplete(result);+ }, intervalSeconds * 1000);+}++export function stopAutoRun(): void {+ if (autoRunInterval) {+ clearInterval(autoRunInterval);+ autoRunInterval = null;+ }+}++export function isAutoRunning(): boolean {+ return autoRunInterval !== null;+}++// =============================================================================+// Export Service Object+// =============================================================================++export const alphaArenaService = {+ // API Keys+ getApiKeys,+ saveApiKeys,++ // Competition Management+ createCompetition,+ startCompetition,+ runCycle,+ stopCompetition,++ // Competition Persistence & History+ listCompetitions,+ getCompetition,+ deleteCompetition,+ resumeCompetition,++ // Data Retrieval+ getLeaderboard,+ getDecisions,+ getSnapshots,+ listAgents,+ getEvaluation,++ // Repository Integration (v2.1)+ saveDecisionToRepository,+ getHistoricalDecisions,+ getCycleDecisions,+ getModelPerformanceSummary,++ // Auto-Run+ startAutoRun,+ stopAutoRun,+ isAutoRunning,+};++export default alphaArenaService;diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/types/index.ts b/fincept-terminal-desktop/src/components/tabs/alpha-arena/types/index.tsnew file mode 100644index 000000000..9bb5dfabe--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/types/index.ts@@ -0,0 +1,368 @@+/**+ * Alpha Arena TypeScript Types+ *+ * Type definitions matching the Python Pydantic models.+ */++// Enums+export type CompetitionMode = 'baseline' | 'monk' | 'situational' | 'max_leverage';+export type CompetitionStatus = 'created' | 'running' | 'paused' | 'completed' | 'failed';+export type TradeAction = 'buy' | 'sell' | 'hold' | 'short';+export type ModelProvider = 'openai' | 'anthropic' | 'google' | 'deepseek' | 'groq' | 'openrouter' | 'ollama';++// Response Events+export type StreamResponseEvent =+ | 'message_chunk'+ | 'decision_started'+ | 'decision_completed'+ | 'trade_executed'+ | 'reasoning_started'+ | 'reasoning'+ | 'reasoning_completed'+ | 'market_data'+ | 'error';++export type SystemResponseEvent =+ | 'competition_started'+ | 'competition_paused'+ | 'competition_completed'+ | 'cycle_started'+ | 'cycle_completed'+ | 'system_failed'+ | 'done';++export type CommonResponseEvent =+ | 'component_generator'+ | 'leaderboard_update'+ | 'portfolio_update';++// Core Models+export interface AgentConfig {+ name: string;+ provider: ModelProvider;+ model_id: string;+ api_key?: string;+ temperature?: number;+ max_tokens?: number;+}++export interface CompetitionModel {+ name: string;+ provider: string;+ model_id: string;+ api_key?: string;+ initial_capital: number;+ capital?: number;+ total_pnl?: number;+}++export interface PositionInfo {+ symbol: string;+ quantity: number;+ entry_price: number;+ side: 'long' | 'short';+ margin_reserved?: number;+ unrealized_pnl?: number;+}++export interface PortfolioState {+ model_name: string;+ cash: number;+ portfolio_value: number;+ positions: Record<string, PositionInfo>;+ total_pnl: number;+ unrealized_pnl: number;+ trades_count: number;+}++export interface MarketData {+ symbol: string;+ price: number;+ bid: number;+ ask: number;+ high_24h: number;+ low_24h: number;+ volume_24h: number;+ timestamp: string;+}++export interface TradeResult {+ status: 'executed' | 'rejected' | 'partial';+ action: TradeAction;+ symbol: string;+ quantity: number;+ price: number;+ cost?: number;+ proceeds?: number;+ pnl?: number;+ margin_reserved?: number;+ reason?: string;+ timestamp: string;+}++export interface ModelDecision {+ competition_id: string;+ model_name: string;+ cycle_number: number;+ action: TradeAction;+ symbol: string;+ quantity: number;+ confidence: number;+ reasoning: string;+ trade_executed?: TradeResult;+ timestamp: string;+ price_at_decision?: number;+ portfolio_value_before?: number;+ portfolio_value_after?: number;+}++export interface LeaderboardEntry {+ rank: number;+ model_name: string;+ portfolio_value: number;+ total_pnl: number;+ return_pct: number;+ trades_count: number;+ cash: number;+ positions_count: number;+ win_rate?: number;+ sharpe_ratio?: number;+}++export interface CompetitionConfig {+ competition_id: string;+ competition_name: string;+ models: CompetitionModel[];+ symbols: string[];+ initial_capital: number;+ mode: CompetitionMode;+ cycle_interval_seconds: number;+ exchange_id: string;+ max_cycles?: number;+ custom_prompt?: string;+}++export interface Competition {+ config: CompetitionConfig;+ status: CompetitionStatus;+ cycle_count: number;+ start_time?: string;+ end_time?: string;+ portfolios: Record<string, PortfolioState>;+ leaderboard: LeaderboardEntry[];+}++export interface PerformanceSnapshot {+ id: string;+ competition_id: string;+ cycle_number: number;+ model_name: string;+ portfolio_value: number;+ cash: number;+ pnl: number;+ return_pct: number;+ positions_count: number;+ trades_count: number;+ timestamp: string;+}++// Streaming Responses+export interface StreamResponse {+ content?: string;+ event: StreamResponseEvent | SystemResponseEvent | CommonResponseEvent;+ metadata?: Record<string, unknown>;+}++export interface CycleEvent {+ event: string;+ content?: string;+ metadata?: Record<string, unknown>;+}++// Agent Card+export interface AgentCapabilities {+ streaming: boolean;+ trading: boolean;+ analysis: boolean;+ notifications: boolean;+ short_selling: boolean;+ leverage: boolean;+}++export interface AgentCard {+ name: string;+ description: string;+ version: string;+ provider: ModelProvider;+ model_id: string;+ agent_class?: string;+ url?: string;+ enabled: boolean;+ capabilities: AgentCapabilities;+ temperature: number;+ max_tokens?: number;+ default_mode: CompetitionMode;+ risk_level: 'low' | 'medium' | 'high';+ system_prompt?: string;+ instructions: string[];+ metadata: Record<string, unknown>;+}++// API Request/Response Types+export interface CreateCompetitionRequest {+ competition_name?: string;+ models: Array<{+ name: string;+ provider?: string;+ model_id?: string;+ initial_capital?: number;+ }>;+ symbols?: string[];+ initial_capital?: number;+ mode?: CompetitionMode;+ cycle_interval_seconds?: number;+ exchange_id?: string;+ max_cycles?: number;+}++export interface CreateCompetitionResponse {+ success: boolean;+ competition_id?: string;+ config?: CompetitionConfig;+ status?: string;+ error?: string;+}++export interface RunCycleResponse {+ success: boolean;+ competition_id?: string;+ cycle_number?: number;+ events?: CycleEvent[];+ leaderboard?: LeaderboardEntry[];+ error?: string;+}++export interface LeaderboardResponse {+ success: boolean;+ leaderboard?: LeaderboardEntry[];+ cycle_number?: number;+ error?: string;+}++export interface DecisionsResponse {+ success: boolean;+ decisions?: ModelDecision[];+ error?: string;+}++export interface SnapshotsResponse {+ success: boolean;+ snapshots?: PerformanceSnapshot[];+ error?: string;+}++export interface ListCompetitionsResponse {+ success: boolean;+ competitions?: Array<{+ competition_id: string;+ config: CompetitionConfig;+ status: CompetitionStatus;+ cycle_count: number;+ start_time?: string;+ end_time?: string;+ created_at: string;+ }>;+ count?: number;+ error?: string;+}++export interface ListAgentsResponse {+ success: boolean;+ agents?: Array<{+ name: string;+ provider: string;+ model_id: string;+ description: string;+ enabled: boolean;+ }>;+ count?: number;+ error?: string;+}++export interface SystemInfoResponse {+ success: boolean;+ version?: string;+ framework?: string;+ features?: string[];+ supported_providers?: string[];+ default_exchange?: string;+ error?: string;+}++// Evaluation Metrics+export interface ModelMetrics {+ model_name: string;+ total_decisions: number;+ correct_decisions: number;+ total_pnl: number;+ win_rate: number;+ avg_confidence: number;+ avg_return: number;+ confidence_accuracy_correlation: number;+ overconfidence_ratio: number;+ sharpe_ratio: number;+ max_drawdown: number;+ profit_factor: number;+ avg_trade_pnl: number;+ best_trade: number;+ worst_trade: number;+ consecutive_wins: number;+ consecutive_losses: number;+}++// Chart Data Types+export interface ChartDataPoint {+ cycle: number;+ timestamp: string;+ [modelName: string]: number | string;+}++export type ChartData = ChartDataPoint[];++// Color mapping for models+export const MODEL_COLORS: Record<string, string> = {+ 'GPT-4o Mini': '#10B981', // Emerald+ 'GPT-4o': '#3B82F6', // Blue+ 'Claude 3.5 Sonnet': '#F97316', // Orange+ 'Gemini 2.0 Flash': '#8B5CF6', // Purple+ 'DeepSeek Chat': '#EC4899', // Pink+ 'Llama 3.3 70B': '#14B8A6', // Teal+ 'Qwen 2.5 72B': '#F59E0B', // Amber+};++// Helper function to get color for model+export function getModelColor(modelName: string): string {+ return MODEL_COLORS[modelName] || '#6B7280'; // Default gray+}++// Format helpers+export function formatCurrency(value: number): string {+ return new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: 'USD',+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ }).format(value);+}++export function formatPercent(value: number): string {+ const sign = value >= 0 ? '+' : '';+ return `${sign}${value.toFixed(2)}%`;+}++export function formatNumber(value: number, decimals = 2): string {+ return value.toLocaleString('en-US', {+ minimumFractionDigits: decimals,+ maximumFractionDigits: decimals,+ });+}diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/EquityResearchTab.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/EquityResearchTab.tsxnew file mode 100644index 000000000..5adbbf362--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/EquityResearchTab.tsx@@ -0,0 +1,649 @@+import React, { useState, useEffect } from 'react';+import { Search, TrendingUp, BarChart3, FileText, Users, Newspaper, RefreshCw, Info } from 'lucide-react';+import { useTranslation } from 'react-i18next';++// Import hooks+import { useStockData } from './hooks/useStockData';+import { useSymbolSearch } from './hooks/useSymbolSearch';+import { useNews } from './hooks/useNews';++// Import tab components+import { OverviewTab } from './tabs/OverviewTab';+import { FinancialsTab } from './tabs/FinancialsTab';+import { AnalysisTab } from './tabs/AnalysisTab';+import { TechnicalsTab } from './tabs/TechnicalsTab';+import { NewsTab } from './tabs/NewsTab';++// Import existing components+import { PeerComparisonPanel } from './components/PeerComparisonPanel';+import { TabFooter } from '@/components/common/TabFooter';+import { createEquityResearchTabTour } from '../tours/equityResearchTabTour';++// Import types and utilities+import type { ChartPeriod, ActiveTab } from './types';+import { formatNumber, getRecommendationColor, getRecommendationText } from './utils/formatters';++// Import Fincept styles+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, EFFECTS, COMMON_STYLES } from '../portfolio-tab/finceptStyles';++const COLORS = {+ ORANGE: FINCEPT.ORANGE,+ WHITE: FINCEPT.WHITE,+ RED: FINCEPT.RED,+ GREEN: FINCEPT.GREEN,+ YELLOW: FINCEPT.YELLOW,+ GRAY: FINCEPT.GRAY,+ BLUE: FINCEPT.BLUE,+ CYAN: FINCEPT.CYAN,+ DARK_BG: FINCEPT.DARK_BG,+ PANEL_BG: FINCEPT.PANEL_BG,+ BORDER: FINCEPT.BORDER,+ HOVER: FINCEPT.HOVER,+};++const EquityResearchTab: React.FC = () => {+ const { t } = useTranslation('equityResearch');++ // State+ const [currentSymbol, setCurrentSymbol] = useState('AAPL');+ const [chartPeriod, setChartPeriod] = useState<ChartPeriod>('6M');+ const [currentTime, setCurrentTime] = useState(new Date());+ const [activeTab, setActiveTab] = useState<ActiveTab>('overview');++ // Custom hooks+ const {+ stockInfo,+ quoteData,+ historicalData,+ financials,+ technicalsData,+ loading,+ technicalsLoading,+ fetchStockData,+ computeTechnicals,+ } = useStockData();++ const {+ searchSymbol,+ setSearchSymbol,+ searchResults,+ showSearchDropdown,+ setShowSearchDropdown,+ searchLoading,+ handleSearchInput,+ handleSelectSymbol,+ searchContainerRef,+ } = useSymbolSearch();++ const {+ newsData,+ newsLoading,+ fetchNews,+ } = useNews();++ // Update time every second+ useEffect(() => {+ const timer = setInterval(() => setCurrentTime(new Date()), 1000);+ return () => clearInterval(timer);+ }, []);++ // Load initial data+ useEffect(() => {+ fetchStockData(currentSymbol, chartPeriod);+ }, [currentSymbol, chartPeriod, fetchStockData]);++ // Compute technicals when historical data changes+ useEffect(() => {+ if (historicalData.length > 0) {+ computeTechnicals(historicalData);+ }+ }, [historicalData, computeTechnicals]);++ // Fetch news when news tab is activated or symbol changes+ useEffect(() => {+ if (activeTab === 'news' && currentSymbol) {+ fetchNews(currentSymbol, stockInfo?.company_name);+ }+ }, [activeTab, currentSymbol, stockInfo?.company_name, fetchNews]);++ const handleSearch = () => {+ if (searchSymbol.trim()) {+ setCurrentSymbol(searchSymbol.trim().toUpperCase());+ setSearchSymbol('');+ }+ };++ const currentPrice = quoteData?.price || stockInfo?.current_price || 0;+ const priceChange = quoteData?.change || 0;+ const priceChangePercent = quoteData?.change_percent || 0;++ return (+ <div style={{+ ...COMMON_STYLES.container,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {/* Fincept-Style Header */}+ <div style={{+ ...COMMON_STYLES.header,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ flexWrap: 'wrap',+ gap: SPACING.MEDIUM,+ }}>+ {/* Left Section */}+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.LARGE, flex: 1 }}>+ {/* Title with Icon */}+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>+ <TrendingUp size={16} color={COLORS.ORANGE} />+ <span style={{+ color: COLORS.ORANGE,+ fontWeight: TYPOGRAPHY.BOLD,+ fontSize: TYPOGRAPHY.SUBHEADING,+ letterSpacing: TYPOGRAPHY.WIDE,+ textTransform: 'uppercase',+ }}>+ RESEARCH+ </span>+ </div>++ {/* Help Button */}+ <button+ onClick={() => {+ const tour = createEquityResearchTabTour((tab: string) => setActiveTab(tab as ActiveTab));+ tour.drive();+ }}+ style={{+ backgroundColor: COLORS.BLUE,+ color: COLORS.DARK_BG,+ border: 'none',+ padding: '4px 8px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ borderRadius: '0'+ }}+ title="Start interactive tour"+ >+ <Info size={12} />+ HELP+ </button>++ {/* Divider */}+ <div style={COMMON_STYLES.verticalDivider} />++ {/* Symbol Search */}+ <div id="research-search" style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>+ <div ref={searchContainerRef} style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>+ <Search size={14} style={{+ position: 'absolute',+ left: '8px',+ pointerEvents: 'none',+ color: COLORS.GRAY,+ zIndex: 1+ }} />+ {searchLoading && (+ <div style={{+ position: 'absolute',+ right: '8px',+ width: '12px',+ height: '12px',+ border: `2px solid ${COLORS.BORDER}`,+ borderTop: `2px solid ${COLORS.ORANGE}`,+ borderRadius: '50%',+ animation: 'spin 0.8s linear infinite',+ zIndex: 1+ }} />+ )}+ <input+ type="text"+ placeholder="SYMBOL..."+ value={searchSymbol}+ style={{+ ...COMMON_STYLES.inputField,+ paddingLeft: '28px',+ paddingRight: searchLoading ? '28px' : '8px',+ width: '160px',+ height: '28px',+ padding: `${SPACING.SMALL} ${SPACING.SMALL} ${SPACING.SMALL} 28px`,+ fontSize: TYPOGRAPHY.BODY,+ textTransform: 'uppercase',+ }}+ onInput={(e) => {+ const val = (e.target as HTMLInputElement).value;+ setSearchSymbol(val);+ handleSearchInput(val);+ }}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ handleSearch();+ setShowSearchDropdown(false);+ }+ }}+ onFocus={(e) => {+ e.currentTarget.style.borderColor = COLORS.ORANGE;+ if (searchResults.length > 0) setShowSearchDropdown(true);+ }}+ onBlur={(e) => e.currentTarget.style.borderColor = COLORS.BORDER}+ />+ {/* Search Results Dropdown */}+ {showSearchDropdown && searchResults.length > 0 && (+ <div style={{+ position: 'absolute',+ top: '100%',+ left: 0,+ width: '320px',+ maxHeight: '300px',+ overflowY: 'auto',+ backgroundColor: COLORS.PANEL_BG,+ border: BORDERS.STANDARD,+ borderColor: COLORS.ORANGE,+ zIndex: 1000,+ marginTop: '2px',+ }}>+ {searchResults.map((result, idx) => (+ <div+ key={`${result.symbol}-${idx}`}+ onMouseDown={() => handleSelectSymbol(result.symbol, setCurrentSymbol)}+ style={{+ padding: `${SPACING.SMALL} ${SPACING.DEFAULT}`,+ cursor: 'pointer',+ borderBottom: idx < searchResults.length - 1 ? BORDERS.STANDARD : 'none',+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ transition: EFFECTS.TRANSITION_FAST,+ }}+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = COLORS.HOVER}+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}+ >+ <div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>+ <span style={{ color: COLORS.ORANGE, fontWeight: TYPOGRAPHY.BOLD, fontSize: TYPOGRAPHY.BODY }}>+ {result.symbol}+ </span>+ <span style={{ color: COLORS.GRAY, fontSize: TYPOGRAPHY.SMALL, maxWidth: '220px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {result.name}+ </span>+ </div>+ <span style={{+ color: COLORS.CYAN,+ fontSize: '9px',+ textTransform: 'uppercase',+ padding: '2px 6px',+ backgroundColor: `${COLORS.CYAN}20`,+ borderRadius: '2px',+ }}>+ {result.type}+ </span>+ </div>+ ))}+ </div>+ )}+ </div>+ <button+ onClick={handleSearch}+ style={{+ ...COMMON_STYLES.buttonPrimary,+ padding: `${SPACING.SMALL} ${SPACING.DEFAULT}`,+ fontSize: TYPOGRAPHY.SMALL,+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.TINY,+ }}+ onMouseEnter={(e) => e.currentTarget.style.opacity = '0.85'}+ onMouseLeave={(e) => e.currentTarget.style.opacity = '1'}+ >+ <Search size={12} />+ GO+ </button>+ <button+ onClick={() => fetchStockData(currentSymbol, chartPeriod, true)}+ style={{+ ...COMMON_STYLES.buttonSecondary,+ padding: `${SPACING.SMALL} ${SPACING.MEDIUM}`,+ fontSize: TYPOGRAPHY.SMALL,+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.TINY,+ }}+ onMouseEnter={(e) => e.currentTarget.style.backgroundColor = COLORS.HOVER}+ onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}+ >+ <RefreshCw size={12} />+ REFRESH+ </button>+ </div>++ {/* Divider */}+ <div style={COMMON_STYLES.verticalDivider} />++ {/* Tab Navigation Buttons */}+ <div id="research-tabs" style={{ display: 'flex', alignItems: 'center', gap: SPACING.SMALL }}>+ {[+ { id: 'overview', label: 'OVERVIEW', icon: TrendingUp },+ { id: 'financials', label: 'FINANCIALS', icon: BarChart3 },+ { id: 'analysis', label: 'ANALYSIS', icon: FileText },+ { id: 'technicals', label: 'TECHNICALS', icon: BarChart3 },+ { id: 'peers', label: 'PEERS', icon: Users },+ { id: 'news', label: 'NEWS', icon: Newspaper },+ ].map((tab) => {+ const Icon = tab.icon;+ return (+ <button+ key={tab.id}+ onClick={() => setActiveTab(tab.id as ActiveTab)}+ style={{+ padding: `${SPACING.SMALL} ${SPACING.DEFAULT}`,+ backgroundColor: activeTab === tab.id ? COLORS.ORANGE : 'transparent',+ border: BORDERS.STANDARD,+ borderColor: activeTab === tab.id ? COLORS.ORANGE : COLORS.BORDER,+ color: activeTab === tab.id ? COLORS.DARK_BG : COLORS.GRAY,+ fontSize: TYPOGRAPHY.SMALL,+ fontWeight: TYPOGRAPHY.BOLD,+ cursor: 'pointer',+ textTransform: 'uppercase',+ letterSpacing: TYPOGRAPHY.NORMAL,+ transition: EFFECTS.TRANSITION_FAST,+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL,+ }}+ onMouseEnter={(e) => {+ if (activeTab !== tab.id) {+ e.currentTarget.style.backgroundColor = COLORS.HOVER;+ e.currentTarget.style.borderColor = COLORS.ORANGE;+ }+ }}+ onMouseLeave={(e) => {+ if (activeTab !== tab.id) {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.borderColor = COLORS.BORDER;+ }+ }}+ title={tab.label}+ >+ <Icon size={12} />+ <span>{tab.label}</span>+ </button>+ );+ })}+ </div>+ </div>++ {/* Right Section - Status */}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.DEFAULT,+ fontSize: TYPOGRAPHY.BODY,+ }}>+ <span style={{ color: COLORS.GRAY, fontSize: TYPOGRAPHY.SMALL }}>+ {currentTime.toLocaleTimeString()}+ </span>+ <div style={COMMON_STYLES.verticalDivider} />+ <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.BOLD }}>+ {currentSymbol}+ </span>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.TINY,+ padding: `${SPACING.TINY} ${SPACING.SMALL}`,+ backgroundColor: loading ? `${COLORS.YELLOW}15` : `${COLORS.GREEN}15`,+ border: `1px solid ${loading ? COLORS.YELLOW : COLORS.GREEN}`,+ }}>+ <div style={{+ width: '6px',+ height: '6px',+ borderRadius: '50%',+ backgroundColor: loading ? COLORS.YELLOW : COLORS.GREEN,+ animation: loading ? 'pulse 1.5s ease-in-out infinite' : 'none',+ }} />+ <span style={{+ color: loading ? COLORS.YELLOW : COLORS.GREEN,+ fontWeight: TYPOGRAPHY.BOLD,+ fontSize: TYPOGRAPHY.SMALL,+ }}>+ {loading ? 'LOADING' : 'LIVE'}+ </span>+ </div>+ </div>+ </div>++ {/* Ticker Bar - Stock Price and Info */}+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ borderBottom: BORDERS.STANDARD,+ padding: `${SPACING.MEDIUM} ${SPACING.DEFAULT}`,+ flexShrink: 0,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ {/* Left - Company Info */}+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.LARGE }}>+ <div>+ <div style={{ display: 'flex', alignItems: 'center', gap: SPACING.MEDIUM, marginBottom: SPACING.TINY }}>+ <span style={{+ color: COLORS.ORANGE,+ fontSize: TYPOGRAPHY.LARGE,+ fontWeight: TYPOGRAPHY.BOLD,+ letterSpacing: TYPOGRAPHY.WIDE,+ }}>+ {currentSymbol}+ </span>+ <span style={{+ color: COLORS.WHITE,+ fontSize: TYPOGRAPHY.SUBHEADING,+ fontWeight: TYPOGRAPHY.SEMIBOLD,+ }}>+ {stockInfo?.company_name || 'Loading...'}+ </span>+ {stockInfo?.sector && (+ <span style={{+ color: COLORS.BLUE,+ fontSize: TYPOGRAPHY.SMALL,+ padding: `${SPACING.TINY} ${SPACING.SMALL}`,+ backgroundColor: `${COLORS.BLUE}15`,+ border: `1px solid ${COLORS.BLUE}`,+ fontWeight: TYPOGRAPHY.SEMIBOLD,+ textTransform: 'uppercase',+ letterSpacing: TYPOGRAPHY.NORMAL,+ }}>+ {stockInfo.sector}+ </span>+ )}+ {stockInfo?.recommendation_key && (+ <span style={{+ color: getRecommendationColor(stockInfo.recommendation_key, COLORS),+ fontSize: TYPOGRAPHY.SMALL,+ padding: `${SPACING.TINY} ${SPACING.SMALL}`,+ backgroundColor: `${getRecommendationColor(stockInfo.recommendation_key, COLORS)}20`,+ border: `1px solid ${getRecommendationColor(stockInfo.recommendation_key, COLORS)}`,+ fontWeight: TYPOGRAPHY.BOLD,+ textTransform: 'uppercase',+ }}>+ {getRecommendationText(stockInfo.recommendation_key)}+ </span>+ )}+ </div>+ <div style={{+ fontSize: TYPOGRAPHY.SMALL,+ color: COLORS.GRAY,+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL,+ }}>+ <span>{stockInfo?.exchange || 'N/A'}</span>+ <span>•</span>+ <span>{stockInfo?.industry || 'N/A'}</span>+ <span>•</span>+ <span>{stockInfo?.country || 'N/A'}</span>+ </div>+ </div>+ </div>++ {/* Right - Price Info */}+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'flex-end',+ gap: SPACING.TINY,+ }}>+ <div style={{+ fontSize: '28px',+ fontWeight: TYPOGRAPHY.BOLD,+ color: COLORS.WHITE,+ fontFamily: TYPOGRAPHY.MONO,+ letterSpacing: TYPOGRAPHY.TIGHT,+ }}>+ ${formatNumber(currentPrice)}+ </div>+ <div style={{+ fontSize: TYPOGRAPHY.SUBHEADING,+ color: priceChange >= 0 ? COLORS.GREEN : COLORS.RED,+ fontWeight: TYPOGRAPHY.BOLD,+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.TINY,+ }}>+ <span>{priceChange >= 0 ? '▲' : '▼'}</span>+ <span>${Math.abs(priceChange).toFixed(2)}</span>+ <span>({priceChangePercent.toFixed(2)}%)</span>+ </div>+ </div>+ </div>++ {/* Main Content Area */}+ <div style={{+ flex: 1,+ overflow: 'auto',+ scrollbarColor: 'rgba(120, 120, 120, 0.3) transparent',+ scrollbarWidth: 'thin',+ minHeight: 0,+ backgroundColor: COLORS.DARK_BG,+ }} className="custom-scrollbar">++ {/* Overview Tab */}+ {activeTab === 'overview' && (+ <OverviewTab+ currentSymbol={currentSymbol}+ stockInfo={stockInfo}+ quoteData={quoteData}+ historicalData={historicalData}+ chartPeriod={chartPeriod}+ setChartPeriod={setChartPeriod}+ loading={loading}+ />+ )}++ {/* Financials Tab */}+ {activeTab === 'financials' && (+ <FinancialsTab+ financials={financials}+ loading={loading}+ />+ )}++ {/* Analysis Tab */}+ {activeTab === 'analysis' && (+ <AnalysisTab+ currentSymbol={currentSymbol}+ stockInfo={stockInfo}+ />+ )}++ {/* Technicals Tab */}+ {activeTab === 'technicals' && (+ <TechnicalsTab+ technicalsData={technicalsData}+ technicalsLoading={technicalsLoading}+ historicalData={historicalData}+ />+ )}++ {/* Peers Tab */}+ {activeTab === 'peers' && (+ <div id="research-peer-comparison" style={{ padding: '8px' }}>+ <PeerComparisonPanel initialSymbol={currentSymbol} />+ </div>+ )}++ {/* News Tab */}+ {activeTab === 'news' && (+ <NewsTab+ newsData={newsData}+ newsLoading={newsLoading}+ currentSymbol={currentSymbol}+ stockInfo={stockInfo}+ onRefresh={() => fetchNews(currentSymbol, stockInfo?.company_name)}+ />+ )}+ </div>++ {/* Footer / Status Bar */}+ <TabFooter+ tabName="EQUITY RESEARCH"+ leftInfo={[+ { label: 'Real-time data analysis and company fundamentals', color: COLORS.GRAY },+ { label: 'Data Source: YFinance', color: COLORS.GRAY },+ ]}+ statusInfo={+ <div style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>+ <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, fontWeight: 'bold' }}>+ {loading ? 'LOADING...' : 'READY'}+ </span>+ </div>+ }+ backgroundColor={COLORS.PANEL_BG}+ borderColor={COLORS.BORDER}+ />++ {/* Custom Scrollbar Styles */}+ <style>{`+ .custom-scrollbar::-webkit-scrollbar {+ width: 4px;+ height: 4px;+ }+ .custom-scrollbar::-webkit-scrollbar-track {+ background: transparent;+ }+ .custom-scrollbar::-webkit-scrollbar-thumb {+ background: rgba(120, 120, 120, 0.3);+ border-radius: 2px;+ }+ .custom-scrollbar::-webkit-scrollbar-thumb:hover {+ background: rgba(120, 120, 120, 0.6);+ }+ .custom-scrollbar::-webkit-scrollbar-corner {+ background: transparent;+ }+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ @keyframes pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.5; }+ }+ `}</style>+ </div>+ );+};++export default EquityResearchTab;diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/components/IndicatorBox.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/components/IndicatorBox.tsxnew file mode 100644index 000000000..a78e0b4a6--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/components/IndicatorBox.tsx@@ -0,0 +1,656 @@+import React, { useState } from 'react';+import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';+import { FINCEPT } from '../../portfolio-tab/finceptStyles';+import { formatIndicatorValue } from '../utils/formatters';++const COLORS = {+ ORANGE: FINCEPT.ORANGE,+ WHITE: FINCEPT.WHITE,+ RED: FINCEPT.RED,+ GREEN: FINCEPT.GREEN,+ YELLOW: FINCEPT.YELLOW,+ GRAY: FINCEPT.GRAY,+ CYAN: FINCEPT.CYAN,+ DARK_BG: FINCEPT.DARK_BG,+ PANEL_BG: FINCEPT.PANEL_BG,+ BORDER: FINCEPT.BORDER,+};++interface IndicatorBoxProps {+ name: string;+ latestValue: number;+ min: number;+ max: number;+ avg: number;+ values: number[];+ priceData: any[];+ color: string;+ category: string;+ onRecompute?: (params: any) => void;+}++/**+ * Get default parameters for a given indicator+ */+const getDefaultParams = (name: string): any => {+ const nameUpper = name.toUpperCase();++ // Moving Averages+ if (nameUpper.includes('SMA_5')) return { period: 5 };+ if (nameUpper.includes('SMA_10')) return { period: 10 };+ if (nameUpper.includes('SMA_20')) return { period: 20 };+ if (nameUpper.includes('SMA_50')) return { period: 50 };+ if (nameUpper.includes('SMA_200')) return { period: 200 };+ if (nameUpper.includes('EMA_9')) return { period: 9 };+ if (nameUpper.includes('EMA_12')) return { period: 12 };+ if (nameUpper.includes('EMA_21')) return { period: 21 };+ if (nameUpper.includes('EMA_26')) return { period: 26 };+ if (nameUpper.includes('EMA_50')) return { period: 50 };+ if (nameUpper.includes('WMA')) return { period: 9 };++ // RSI+ if (nameUpper.includes('RSI')) return { period: 14 };++ // MACD+ if (nameUpper.includes('MACD')) return { fast: 12, slow: 26, signal: 9 };++ // Stochastic+ if (nameUpper.includes('STOCH')) return { k_period: 14, d_period: 3 };++ // Bollinger Bands+ if (nameUpper.includes('BB_')) return { period: 20, std: 2 };++ // ATR+ if (nameUpper.includes('ATR')) return { period: 14 };++ // ADX+ if (nameUpper.includes('ADX')) return { period: 14 };++ // CCI+ if (nameUpper.includes('CCI')) return { period: 20 };++ // Williams %R+ if (nameUpper.includes('WILLIAMS')) return { period: 14 };++ // ROC+ if (nameUpper.includes('ROC')) return { period: 12 };++ // MFI+ if (nameUpper === 'MFI') return { period: 14 };++ // Aroon+ if (nameUpper.includes('AROON')) return { period: 25 };++ // Awesome Oscillator+ if (nameUpper.includes('AWESOME') || nameUpper === 'AO') return { fast: 5, slow: 34 };++ // TSI+ if (nameUpper === 'TSI') return { long: 25, short: 13 };++ // Ultimate Oscillator+ if (nameUpper === 'UO' || nameUpper.includes('ULTIMATE')) return { period1: 7, period2: 14, period3: 28 };++ return null;+};++/**+ * Get default thresholds for a given indicator+ */+const getDefaultThresholds = (name: string): { upper: number; lower: number; label: string } => {+ const nameUpper = name.toUpperCase();++ if (nameUpper.includes('RSI')) return { upper: 70, lower: 30, label: 'Overbought/Oversold' };+ if (nameUpper.includes('STOCH')) return { upper: 80, lower: 20, label: 'Overbought/Oversold' };+ if (nameUpper.includes('WILLIAMS')) return { upper: -20, lower: -80, label: 'Overbought/Oversold' };+ if (nameUpper.includes('CCI')) return { upper: 100, lower: -100, label: 'Overbought/Oversold' };+ if (nameUpper === 'TSI') return { upper: 25, lower: -25, label: 'Overbought/Oversold' };+ if (nameUpper === 'UO' || nameUpper.includes('ULTIMATE')) return { upper: 70, lower: 30, label: 'Overbought/Oversold' };+ if (nameUpper === 'MFI') return { upper: 80, lower: 20, label: 'Overbought/Oversold' };+ if (nameUpper.includes('ROC')) return { upper: 5, lower: -5, label: 'Strength %' };+ if (nameUpper.includes('ADX') && !nameUpper.includes('POS') && !nameUpper.includes('NEG')) return { upper: 25, lower: 20, label: 'Trend Strength' };+ if (nameUpper.includes('AROON')) return { upper: 70, lower: 30, label: 'Trend Strength' };+ if (nameUpper.includes('BB_PBAND') || nameUpper.includes('KC_PBAND') || nameUpper.includes('DC_PBAND')) return { upper: 0.8, lower: 0.2, label: 'Band Position' };+ if (nameUpper.includes('CMF')) return { upper: 0.1, lower: -0.1, label: 'Money Flow' };++ return { upper: 0, lower: 0, label: 'Custom' };+};++/**+ * Get trading signal based on indicator values+ */+const getSignal = (+ name: string,+ latestValue: number,+ prevValue: number,+ avg: number,+ activeThresholds: { upper: number; lower: number }+): { signal: 'BUY' | 'SELL' | 'NEUTRAL'; reason: string } => {+ const nameUpper = name.toUpperCase();++ // === MOMENTUM INDICATORS ===+ if (nameUpper.includes('RSI')) {+ if (latestValue <= activeThresholds.lower) return { signal: 'BUY', reason: `Oversold <${activeThresholds.lower}` };+ if (latestValue >= activeThresholds.upper) return { signal: 'SELL', reason: `Overbought >${activeThresholds.upper}` };+ return { signal: 'NEUTRAL', reason: `${activeThresholds.lower}-${activeThresholds.upper} range` };+ }++ if (nameUpper.includes('STOCH') && !nameUpper.includes('RSI')) {+ if (latestValue <= activeThresholds.lower) return { signal: 'BUY', reason: `Oversold <${activeThresholds.lower}` };+ if (latestValue >= activeThresholds.upper) return { signal: 'SELL', reason: `Overbought >${activeThresholds.upper}` };+ return { signal: 'NEUTRAL', reason: `${activeThresholds.lower}-${activeThresholds.upper} range` };+ }++ if (nameUpper.includes('WILLIAMS')) {+ if (latestValue <= -80) return { signal: 'BUY', reason: 'Oversold' };+ if (latestValue >= -20) return { signal: 'SELL', reason: 'Overbought' };+ return { signal: 'NEUTRAL', reason: '-20 to -80' };+ }++ if (nameUpper === 'AO' || nameUpper.includes('AWESOME')) {+ if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };+ if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };+ return { signal: 'NEUTRAL', reason: 'No crossover' };+ }++ if (nameUpper.includes('ROC')) {+ if (latestValue > 5) return { signal: 'BUY', reason: 'Strong >5%' };+ if (latestValue < -5) return { signal: 'SELL', reason: 'Weak <-5%' };+ return { signal: 'NEUTRAL', reason: '-5% to 5%' };+ }++ if (nameUpper === 'TSI') {+ if (latestValue < -25) return { signal: 'BUY', reason: 'Oversold' };+ if (latestValue > 25) return { signal: 'SELL', reason: 'Overbought' };+ return { signal: 'NEUTRAL', reason: '-25 to 25' };+ }++ if (nameUpper === 'UO' || nameUpper.includes('ULTIMATE')) {+ if (latestValue < 30) return { signal: 'BUY', reason: 'Oversold <30' };+ if (latestValue > 70) return { signal: 'SELL', reason: 'Overbought >70' };+ return { signal: 'NEUTRAL', reason: '30-70 range' };+ }++ if (nameUpper.includes('PPO') && !nameUpper.includes('SIGNAL') && !nameUpper.includes('HIST')) {+ if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };+ if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };+ return { signal: 'NEUTRAL', reason: 'No crossover' };+ }++ // === TREND INDICATORS ===+ if (nameUpper.includes('MACD') && !nameUpper.includes('SIGNAL') && !nameUpper.includes('DIFF')) {+ if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Bullish crossover' };+ if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Bearish crossover' };+ return { signal: 'NEUTRAL', reason: 'No crossover' };+ }++ if (nameUpper.includes('CCI')) {+ if (latestValue <= -100) return { signal: 'BUY', reason: 'Oversold <-100' };+ if (latestValue >= 100) return { signal: 'SELL', reason: 'Overbought >100' };+ return { signal: 'NEUTRAL', reason: '-100 to 100' };+ }++ if (nameUpper.includes('ADX') && !nameUpper.includes('POS') && !nameUpper.includes('NEG')) {+ if (latestValue > 25) return { signal: 'BUY', reason: 'Strong trend >25' };+ if (latestValue < 20) return { signal: 'NEUTRAL', reason: 'Weak trend <20' };+ return { signal: 'NEUTRAL', reason: 'Moderate 20-25' };+ }++ if (nameUpper.includes('AROON_UP')) {+ if (latestValue > 70) return { signal: 'BUY', reason: 'Strong uptrend' };+ return { signal: 'NEUTRAL', reason: 'Weak uptrend' };+ }++ if (nameUpper.includes('AROON_DOWN')) {+ if (latestValue > 70) return { signal: 'SELL', reason: 'Strong downtrend' };+ return { signal: 'NEUTRAL', reason: 'Weak downtrend' };+ }++ if (nameUpper.includes('AROON_INDICATOR')) {+ if (latestValue > 50) return { signal: 'BUY', reason: 'Bullish' };+ if (latestValue < -50) return { signal: 'SELL', reason: 'Bearish' };+ return { signal: 'NEUTRAL', reason: '-50 to 50' };+ }++ if (nameUpper.includes('PSAR_UP_INDICATOR')) {+ if (latestValue === 1) return { signal: 'BUY', reason: 'Uptrend active' };+ return { signal: 'NEUTRAL', reason: 'No uptrend' };+ }++ if (nameUpper.includes('PSAR_DOWN_INDICATOR')) {+ if (latestValue === 1) return { signal: 'SELL', reason: 'Downtrend active' };+ return { signal: 'NEUTRAL', reason: 'No downtrend' };+ }++ if (nameUpper.includes('TRIX')) {+ if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };+ if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };+ return { signal: 'NEUTRAL', reason: 'No crossover' };+ }++ if (nameUpper.includes('KST') && !nameUpper.includes('SIGNAL')) {+ if (prevValue < 0 && latestValue > 0) return { signal: 'BUY', reason: 'Zero cross up' };+ if (prevValue > 0 && latestValue < 0) return { signal: 'SELL', reason: 'Zero cross down' };+ return { signal: 'NEUTRAL', reason: 'No crossover' };+ }++ if (nameUpper.includes('VORTEX_POS')) {+ if (latestValue > 1) return { signal: 'BUY', reason: 'Positive >1' };+ return { signal: 'NEUTRAL', reason: 'Weak' };+ }++ if (nameUpper.includes('VORTEX_NEG')) {+ if (latestValue > 1) return { signal: 'SELL', reason: 'Negative >1' };+ return { signal: 'NEUTRAL', reason: 'Weak' };+ }++ // === VOLATILITY INDICATORS ===+ if (nameUpper.includes('BB_PBAND') || nameUpper.includes('KC_PBAND') || nameUpper.includes('DC_PBAND')) {+ if (latestValue < 0.2) return { signal: 'BUY', reason: 'Near lower band' };+ if (latestValue > 0.8) return { signal: 'SELL', reason: 'Near upper band' };+ return { signal: 'NEUTRAL', reason: 'Middle band' };+ }++ if (nameUpper.includes('BB_HBAND_INDICATOR')) {+ if (latestValue === 1) return { signal: 'SELL', reason: 'Above upper BB' };+ return { signal: 'NEUTRAL', reason: 'Below upper BB' };+ }++ if (nameUpper.includes('BB_LBAND_INDICATOR')) {+ if (latestValue === 1) return { signal: 'BUY', reason: 'Below lower BB' };+ return { signal: 'NEUTRAL', reason: 'Above lower BB' };+ }++ if (nameUpper.includes('ATR')) {+ if (latestValue > avg * 1.5) return { signal: 'NEUTRAL', reason: 'High volatility' };+ if (latestValue < avg * 0.5) return { signal: 'NEUTRAL', reason: 'Low volatility' };+ return { signal: 'NEUTRAL', reason: 'Normal volatility' };+ }++ if (nameUpper.includes('UI') || nameUpper.includes('ULCER')) {+ if (latestValue > avg * 1.5) return { signal: 'SELL', reason: 'High risk' };+ return { signal: 'NEUTRAL', reason: 'Normal risk' };+ }++ // === VOLUME INDICATORS ===+ if (nameUpper === 'MFI') {+ if (latestValue <= 20) return { signal: 'BUY', reason: 'Oversold <20' };+ if (latestValue >= 80) return { signal: 'SELL', reason: 'Overbought >80' };+ return { signal: 'NEUTRAL', reason: '20-80 range' };+ }++ if (nameUpper.includes('CMF')) {+ if (latestValue > 0.1) return { signal: 'BUY', reason: 'Positive flow' };+ if (latestValue < -0.1) return { signal: 'SELL', reason: 'Negative flow' };+ return { signal: 'NEUTRAL', reason: 'Neutral flow' };+ }++ if (nameUpper === 'OBV' || nameUpper.includes('ADI') || nameUpper.includes('VPT')) {+ if (latestValue > prevValue) return { signal: 'BUY', reason: 'Volume rising' };+ if (latestValue < prevValue) return { signal: 'SELL', reason: 'Volume falling' };+ return { signal: 'NEUTRAL', reason: 'Volume stable' };+ }++ if (nameUpper.includes('EOM')) {+ if (latestValue > 0) return { signal: 'BUY', reason: 'Ease of movement +' };+ if (latestValue < 0) return { signal: 'SELL', reason: 'Ease of movement -' };+ return { signal: 'NEUTRAL', reason: 'No movement' };+ }++ if (nameUpper.includes('FI') && !nameUpper.includes('MFI')) {+ if (latestValue > 0) return { signal: 'BUY', reason: 'Force positive' };+ if (latestValue < 0) return { signal: 'SELL', reason: 'Force negative' };+ return { signal: 'NEUTRAL', reason: 'No force' };+ }++ // === OTHERS (RETURNS) ===+ if (nameUpper.includes('RETURN')) {+ if (latestValue > 2) return { signal: 'BUY', reason: 'Positive return' };+ if (latestValue < -2) return { signal: 'SELL', reason: 'Negative return' };+ return { signal: 'NEUTRAL', reason: 'Flat return' };+ }++ // Default for moving averages and others+ if (nameUpper.includes('SMA') || nameUpper.includes('EMA') || nameUpper.includes('WMA')) {+ return { signal: 'NEUTRAL', reason: 'Compare to price' };+ }++ return { signal: 'NEUTRAL', reason: 'Monitor indicator' };+};++export const IndicatorBox: React.FC<IndicatorBoxProps> = ({+ name,+ latestValue,+ min,+ max,+ avg,+ values,+ priceData,+ color,+ category,+ onRecompute,+}) => {+ const [showSettings, setShowSettings] = useState(false);+ const [customThresholds, setCustomThresholds] = useState<{ upper: number; lower: number } | null>(null);+ const [customParams, setCustomParams] = useState<any>(null);++ // Only create indicator chart data (no price data for performance)+ const chartData = values.map((value, i) => ({+ index: i,+ value: value || null,+ }));++ const defaultThresholds = getDefaultThresholds(name);+ const activeThresholds = customThresholds || defaultThresholds;+ const defaultParams = getDefaultParams(name);+ const activeParams = customParams || defaultParams;++ const prevValue = values[values.length - 2] || 0;+ const { signal, reason } = getSignal(name, latestValue, prevValue, avg, activeThresholds);+ const signalColor = signal === 'BUY' ? COLORS.GREEN : signal === 'SELL' ? COLORS.RED : COLORS.GRAY;++ return (+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ borderLeft: `3px solid ${color}`,+ borderRadius: '6px',+ padding: '12px',+ display: 'flex',+ flexDirection: 'column',+ gap: '8px',+ minHeight: showSettings ? '480px' : '320px',+ height: 'auto',+ boxShadow: '0 1px 3px rgba(0, 0, 0, 0.3)',+ transition: 'all 0.2s ease',+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.borderColor = color;+ e.currentTarget.style.boxShadow = `0 4px 12px rgba(0, 0, 0, 0.5)`;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = COLORS.BORDER;+ e.currentTarget.style.boxShadow = '0 1px 3px rgba(0, 0, 0, 0.3)';+ }}+ >+ {/* Header */}+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <div>+ <div style={{ color: color, fontSize: '10px', fontWeight: 'bold', marginBottom: '2px' }}>+ {category}+ </div>+ <div style={{ color: COLORS.WHITE, fontSize: '11px', fontWeight: 'bold' }}>+ {name.toUpperCase().replace(/_/g, ' ')}+ </div>+ </div>+ <div style={{ textAlign: 'right' }}>+ <div style={{ color: COLORS.WHITE, fontSize: '16px', fontWeight: 'bold' }}>+ {formatIndicatorValue(latestValue)}+ </div>+ <div style={{ color: COLORS.GRAY, fontSize: '9px' }}>+ Current+ </div>+ </div>+ </div>++ {/* Lightweight Chart - ONLY indicator line */}+ <div style={{ width: '100%', height: '80px', flex: '0 0 auto' }}>+ <ResponsiveContainer width="100%" height="100%">+ <LineChart data={chartData} margin={{ top: 5, right: 5, left: 5, bottom: 5 }}>+ <CartesianGrid strokeDasharray="3 3" stroke={COLORS.BORDER} opacity={0.3} />+ <XAxis dataKey="index" hide />+ <YAxis domain={['auto', 'auto']} hide />+ <Tooltip+ contentStyle={{+ backgroundColor: COLORS.DARK_BG,+ border: `1px solid ${COLORS.BORDER}`,+ borderRadius: '4px',+ fontSize: '10px',+ }}+ formatter={(value: any) => formatIndicatorValue(value)}+ />+ <Line+ type="monotone"+ dataKey="value"+ stroke={color}+ strokeWidth={2}+ dot={false}+ connectNulls+ isAnimationActive={false}+ />+ </LineChart>+ </ResponsiveContainer>+ </div>++ {/* Signal Badge */}+ <div style={{+ display: 'flex',+ justifyContent: 'center',+ alignItems: 'center',+ gap: '8px',+ padding: '4px',+ backgroundColor: `${signalColor}15`,+ border: `1px solid ${signalColor}`,+ borderRadius: '4px',+ }}>+ <span style={{ color: signalColor, fontSize: '11px', fontWeight: 'bold' }}>+ {signal}+ </span>+ <span style={{ color: COLORS.GRAY, fontSize: '9px' }}>+ {reason}+ </span>+ </div>++ {/* Settings Toggle & Parameters */}+ <div style={{ flex: '0 0 auto' }}>+ <button+ onClick={() => setShowSettings(!showSettings)}+ style={{+ fontSize: '9px',+ fontWeight: '500',+ textAlign: 'center',+ padding: '4px 8px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '4px',+ width: '100%',+ userSelect: 'none',+ backgroundColor: showSettings ? COLORS.DARK_BG : COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ borderRadius: '3px',+ color: COLORS.GRAY,+ transition: 'all 0.15s ease',+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.borderColor = COLORS.ORANGE;+ e.currentTarget.style.color = COLORS.ORANGE;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.borderColor = COLORS.BORDER;+ e.currentTarget.style.color = COLORS.GRAY;+ }}+ >+ <span style={{ fontSize: '10px' }}></span>+ <span>{showSettings ? 'Hide' : 'Adjust'}</span>+ </button>++ {showSettings && (+ <div style={{+ backgroundColor: COLORS.DARK_BG,+ border: `1px solid ${COLORS.BORDER}`,+ borderRadius: '4px',+ padding: '10px',+ marginTop: '8px',+ fontSize: '10px',+ }}>+ {/* Indicator Parameters Section */}+ {defaultParams && (+ <div style={{ marginBottom: defaultThresholds.upper !== 0 ? '12px' : '0' }}>+ <div style={{ color: COLORS.CYAN, fontWeight: 'bold', marginBottom: '8px', fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span>Indicator Parameters</span>+ </div>++ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(100px, 1fr))', gap: '8px', marginBottom: '8px' }}>+ {Object.keys(defaultParams).map((key) => (+ <div key={key}>+ <label style={{ color: COLORS.GRAY, display: 'block', marginBottom: '3px', fontSize: '9px', textTransform: 'capitalize' }}>+ {key.replace(/_/g, ' ')}+ </label>+ <input+ type="number"+ step="1"+ value={customParams?.[key] ?? defaultParams[key]}+ onChange={(e) => setCustomParams({+ ...defaultParams,+ ...customParams,+ [key]: parseInt(e.target.value) || 1+ })}+ style={{+ width: '100%',+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ borderRadius: '3px',+ color: COLORS.WHITE,+ padding: '4px 6px',+ fontSize: '10px',+ }}+ />+ </div>+ ))}+ </div>++ {customParams && (+ <button+ onClick={() => {+ if (onRecompute) {+ onRecompute({ indicator: name, params: customParams });+ }+ }}+ style={{+ width: '100%',+ backgroundColor: COLORS.CYAN,+ border: 'none',+ borderRadius: '3px',+ color: COLORS.DARK_BG,+ padding: '6px',+ fontSize: '10px',+ cursor: 'pointer',+ fontWeight: 'bold',+ marginBottom: '6px',+ }}+ >+ Recompute with New Parameters+ </button>+ )}+ </div>+ )}++ {/* Signal Thresholds Section */}+ {defaultThresholds.upper !== 0 && (+ <div>+ <div style={{ color: COLORS.ORANGE, fontWeight: 'bold', marginBottom: '8px', fontSize: '10px', display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span>{defaultThresholds.label}</span>+ </div>++ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '8px' }}>+ <div>+ <label style={{ color: COLORS.GRAY, display: 'block', marginBottom: '3px', fontSize: '9px' }}>+ Upper Threshold+ </label>+ <input+ type="number"+ step="0.1"+ value={customThresholds?.upper ?? defaultThresholds.upper}+ onChange={(e) => setCustomThresholds({+ upper: parseFloat(e.target.value),+ lower: customThresholds?.lower ?? defaultThresholds.lower+ })}+ style={{+ width: '100%',+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ borderRadius: '3px',+ color: COLORS.WHITE,+ padding: '4px 6px',+ fontSize: '10px',+ }}+ />+ </div>++ <div>+ <label style={{ color: COLORS.GRAY, display: 'block', marginBottom: '3px', fontSize: '9px' }}>+ Lower Threshold+ </label>+ <input+ type="number"+ step="0.1"+ value={customThresholds?.lower ?? defaultThresholds.lower}+ onChange={(e) => setCustomThresholds({+ upper: customThresholds?.upper ?? defaultThresholds.upper,+ lower: parseFloat(e.target.value)+ })}+ style={{+ width: '100%',+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ borderRadius: '3px',+ color: COLORS.WHITE,+ padding: '4px 6px',+ fontSize: '10px',+ }}+ />+ </div>+ </div>+ </div>+ )}++ {/* Reset Button */}+ <button+ onClick={() => {+ setCustomThresholds(null);+ setCustomParams(null);+ }}+ style={{+ width: '100%',+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ borderRadius: '3px',+ color: COLORS.GRAY,+ padding: '5px',+ fontSize: '9px',+ cursor: 'pointer',+ fontWeight: '600',+ }}+ >+ Reset All to Defaults+ </button>+ </div>+ )}+ </div>++ {/* Stats */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px', fontSize: '9px' }}>+ <div>+ <div style={{ color: COLORS.GRAY }}>MIN</div>+ <div style={{ color: COLORS.RED, fontWeight: 'bold' }}>{formatIndicatorValue(min)}</div>+ </div>+ <div>+ <div style={{ color: COLORS.GRAY }}>AVG</div>+ <div style={{ color: COLORS.YELLOW, fontWeight: 'bold' }}>{formatIndicatorValue(avg)}</div>+ </div>+ <div>+ <div style={{ color: COLORS.GRAY }}>MAX</div>+ <div style={{ color: COLORS.GREEN, fontWeight: 'bold' }}>{formatIndicatorValue(max)}</div>+ </div>+ </div>++ {/* Data Points Count */}+ <div style={{ color: COLORS.GRAY, fontSize: '9px', textAlign: 'center', borderTop: `1px solid ${COLORS.BORDER}`, paddingTop: '4px' }}>+ {values.length} data points+ </div>+ </div>+ );+};++export default IndicatorBox;diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/index.tsnew file mode 100644index 000000000..9c9860b73--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/index.ts@@ -0,0 +1,3 @@+export { useStockData } from './useStockData';+export { useSymbolSearch } from './useSymbolSearch';+export { useNews } from './useNews';diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useNews.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useNews.tsnew file mode 100644index 000000000..f3b5729e7--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useNews.ts@@ -0,0 +1,63 @@+import { useState, useCallback } from 'react';+import { invoke } from '@tauri-apps/api/core';+import type { NewsData } from '../types';++interface UseNewsReturn {+ newsData: NewsData | null;+ newsLoading: boolean;+ fetchNews: (symbol: string, companyName?: string) => Promise<void>;+}++export function useNews(): UseNewsReturn {+ const [newsData, setNewsData] = useState<NewsData | null>(null);+ const [newsLoading, setNewsLoading] = useState(false);++ const fetchNews = useCallback(async (symbol: string, companyName?: string) => {+ if (!symbol) {+ console.log('No symbol selected for news fetch');+ return;+ }++ setNewsLoading(true);+ console.log('Fetching news for:', symbol);++ try {+ // Use company name if available, otherwise use symbol+ const query = companyName || symbol;++ const response: any = await invoke('fetch_company_news', {+ query: query,+ maxResults: 20,+ period: '7d',+ language: 'en',+ country: 'US'+ });++ console.log('News response:', response);++ if (typeof response === 'string') {+ const parsed = JSON.parse(response);+ setNewsData(parsed);+ } else {+ setNewsData(response);+ }+ } catch (error) {+ console.error('Error fetching news:', error);+ setNewsData({+ success: false,+ error: String(error),+ data: []+ });+ } finally {+ setNewsLoading(false);+ }+ }, []);++ return {+ newsData,+ newsLoading,+ fetchNews,+ };+}++export default useNews;diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useStockData.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useStockData.tsnew file mode 100644index 000000000..ab6c4563b--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useStockData.ts@@ -0,0 +1,198 @@+import { useState, useRef, useEffect, useCallback } from 'react';+import { invoke } from '@tauri-apps/api/core';+import type { StockInfo, HistoricalData, QuoteData, FinancialsData, ChartPeriod, TechnicalsData } from '../types';++interface DataCache {+ stockInfo: StockInfo;+ quoteData: QuoteData;+ historicalData: Record<string, HistoricalData[]>;+ financials: FinancialsData;+ timestamp: number;+}++interface UseStockDataReturn {+ stockInfo: StockInfo | null;+ quoteData: QuoteData | null;+ historicalData: HistoricalData[];+ financials: FinancialsData | null;+ technicalsData: TechnicalsData | null;+ loading: boolean;+ technicalsLoading: boolean;+ fetchStockData: (symbol: string, period: ChartPeriod, forceRefresh?: boolean) => Promise<void>;+ computeTechnicals: (historical: HistoricalData[]) => Promise<void>;+}++const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes++export function useStockData(): UseStockDataReturn {+ const [stockInfo, setStockInfo] = useState<StockInfo | null>(null);+ const [quoteData, setQuoteData] = useState<QuoteData | null>(null);+ const [historicalData, setHistoricalData] = useState<HistoricalData[]>([]);+ const [financials, setFinancials] = useState<FinancialsData | null>(null);+ const [technicalsData, setTechnicalsData] = useState<TechnicalsData | null>(null);+ const [loading, setLoading] = useState(false);+ const [technicalsLoading, setTechnicalsLoading] = useState(false);++ const dataCache = useRef<Record<string, DataCache>>({});++ const fetchStockData = useCallback(async (symbol: string, period: ChartPeriod, forceRefresh = false) => {+ setLoading(true);+ console.log('Fetching data for:', symbol, '| Force refresh:', forceRefresh);++ try {+ // Check cache first+ const cached = dataCache.current[symbol];+ const now = Date.now();++ if (cached && !forceRefresh && (now - cached.timestamp < CACHE_DURATION)) {+ console.log('Using cached data for', symbol);+ setStockInfo(cached.stockInfo);+ setQuoteData(cached.quoteData);+ setFinancials(cached.financials);++ // Check if we have historical data for this period+ if (cached.historicalData[period]) {+ setHistoricalData(cached.historicalData[period]);+ setLoading(false);+ return;+ }+ }++ // Fetch fresh data+ console.log('Fetching fresh data for', symbol);++ // Fetch quote+ const quoteResponse: any = await invoke('get_market_quote', { symbol });+ let newQuote: QuoteData | null = null;+ if (quoteResponse.success && quoteResponse.data) {+ setQuoteData(quoteResponse.data);+ newQuote = quoteResponse.data;+ }++ // Fetch stock info+ const infoResponse: any = await invoke('get_stock_info', { symbol });+ let newInfo: StockInfo | null = null;+ if (infoResponse.success && infoResponse.data) {+ setStockInfo(infoResponse.data);+ newInfo = infoResponse.data;+ }++ // Fetch historical data+ const endDate = new Date();+ const startDate = new Date();+ switch (period) {+ case '1M': startDate.setMonth(endDate.getMonth() - 1); break;+ case '3M': startDate.setMonth(endDate.getMonth() - 3); break;+ case '6M': startDate.setMonth(endDate.getMonth() - 6); break;+ case '1Y': startDate.setFullYear(endDate.getFullYear() - 1); break;+ case '5Y': startDate.setFullYear(endDate.getFullYear() - 5); break;+ }++ const historicalResponse: any = await invoke('get_historical_data', {+ symbol,+ startDate: startDate.toISOString().split('T')[0],+ endDate: endDate.toISOString().split('T')[0],+ });+ let newHistorical: HistoricalData[] = [];+ if (historicalResponse.success && historicalResponse.data) {+ setHistoricalData(historicalResponse.data);+ newHistorical = historicalResponse.data;+ }++ // Fetch financials+ const financialsResponse: any = await invoke('get_financials', { symbol });+ let newFinancials: FinancialsData | null = null;+ if (financialsResponse.success && financialsResponse.data) {+ setFinancials(financialsResponse.data);+ newFinancials = financialsResponse.data;+ }++ // Update cache+ if (newInfo && newQuote && newFinancials) {+ dataCache.current[symbol] = {+ stockInfo: newInfo,+ quoteData: newQuote,+ historicalData: {+ ...((cached?.historicalData) || {}),+ [period]: newHistorical,+ },+ financials: newFinancials,+ timestamp: now,+ };+ }+ } catch (error) {+ console.error('Error fetching stock data:', error);+ } finally {+ setLoading(false);+ }+ }, []);++ const computeTechnicals = useCallback(async (historical: HistoricalData[]) => {+ setTechnicalsLoading(true);+ try {+ // Validate historical data+ if (!historical || !Array.isArray(historical) || historical.length === 0) {+ console.error('Invalid historical data for technicals computation');+ setTechnicalsData(null);+ return;+ }++ // 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+ })));++ console.log('Sending historical data for technicals computation:', historical.length, 'data points');++ const response: any = await invoke('compute_all_technicals', {+ historicalData: historicalJson+ });++ console.log('Technicals response:', response);++ if (typeof response === 'string') {+ try {+ const parsed = JSON.parse(response);+ if (parsed.success && parsed.data && Array.isArray(parsed.data) && parsed.data.length > 0) {+ setTechnicalsData(parsed);+ } else {+ console.error('Error computing technicals:', parsed.error || 'Invalid data structure');+ setTechnicalsData(null);+ }+ } catch (parseError) {+ console.error('Error parsing technicals response:', parseError);+ setTechnicalsData(null);+ }+ } else if (response && response.success && response.data && Array.isArray(response.data) && response.data.length > 0) {+ setTechnicalsData(response);+ } else {+ console.error('Invalid technicals response structure');+ setTechnicalsData(null);+ }+ } catch (error) {+ console.error('Error computing technicals:', error);+ setTechnicalsData(null);+ } finally {+ setTechnicalsLoading(false);+ }+ }, []);++ return {+ stockInfo,+ quoteData,+ historicalData,+ financials,+ technicalsData,+ loading,+ technicalsLoading,+ fetchStockData,+ computeTechnicals,+ };+}++export default useStockData;diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useSymbolSearch.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useSymbolSearch.tsnew file mode 100644index 000000000..e88aeeafe--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/hooks/useSymbolSearch.ts@@ -0,0 +1,108 @@+import { useState, useRef, useEffect, useCallback } from 'react';+import type { SearchResult } from '../types';++interface UseSymbolSearchReturn {+ searchSymbol: string;+ setSearchSymbol: (value: string) => void;+ searchResults: SearchResult[];+ showSearchDropdown: boolean;+ setShowSearchDropdown: (value: boolean) => void;+ searchLoading: boolean;+ handleSearchInput: (query: string) => void;+ handleSelectSymbol: (symbol: string, onSelect: (symbol: string) => void) => void;+ searchContainerRef: React.RefObject<HTMLDivElement>;+}++export function useSymbolSearch(): UseSymbolSearchReturn {+ const [searchSymbol, setSearchSymbol] = useState('');+ const [searchResults, setSearchResults] = useState<SearchResult[]>([]);+ const [showSearchDropdown, setShowSearchDropdown] = useState(false);+ const [searchLoading, setSearchLoading] = useState(false);++ const searchDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const searchContainerRef = useRef<HTMLDivElement>(null);++ // HTTP Symbol Search function+ const searchSymbolsHttp = async (query: string) => {+ try {+ const response = await fetch(`https://finceptbackend.share.zrok.io/search/symbols?query=${encodeURIComponent(query)}&limit=50`);+ if (response.ok) {+ const data = await response.json();+ console.log('[Search] HTTP results:', data);+ setSearchResults(data.results || []);+ setSearchLoading(false);+ if (data.results?.length > 0) {+ setShowSearchDropdown(true);+ }+ } else {+ console.error('[Search] HTTP error:', response.status);+ setSearchLoading(false);+ }+ } catch (e) {+ console.error('[Search] HTTP fetch error:', e);+ setSearchLoading(false);+ }+ };++ // Cleanup debounce on unmount+ useEffect(() => {+ return () => {+ if (searchDebounceRef.current) {+ clearTimeout(searchDebounceRef.current);+ }+ };+ }, []);++ // Close dropdown when clicking outside+ useEffect(() => {+ const handleClickOutside = (e: MouseEvent) => {+ if (searchContainerRef.current && !searchContainerRef.current.contains(e.target as Node)) {+ setShowSearchDropdown(false);+ }+ };+ document.addEventListener('mousedown', handleClickOutside);+ return () => document.removeEventListener('mousedown', handleClickOutside);+ }, []);++ // Debounced search function (non-blocking)+ const handleSearchInput = useCallback((query: string) => {+ if (searchDebounceRef.current) {+ clearTimeout(searchDebounceRef.current);+ }++ if (query.length < 2) {+ setSearchResults([]);+ setShowSearchDropdown(false);+ setSearchLoading(false);+ return;+ }++ setSearchLoading(true);++ searchDebounceRef.current = setTimeout(() => {+ searchSymbolsHttp(query);+ }, 300);+ }, []);++ // Handle symbol selection from dropdown+ const handleSelectSymbol = useCallback((symbol: string, onSelect: (symbol: string) => void) => {+ setSearchSymbol(symbol);+ setShowSearchDropdown(false);+ setSearchResults([]);+ onSelect(symbol);+ }, []);++ return {+ searchSymbol,+ setSearchSymbol,+ searchResults,+ showSearchDropdown,+ setShowSearchDropdown,+ searchLoading,+ handleSearchInput,+ handleSelectSymbol,+ searchContainerRef: searchContainerRef as React.RefObject<HTMLDivElement>,+ };+}++export default useSymbolSearch;diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/index.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/index.tsnew file mode 100644index 000000000..770ebfa6a--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/index.ts@@ -0,0 +1,24 @@+// Main exports for Equity Research module++// Types+export * from './types';++// Hooks+export { useStockData } from './hooks/useStockData';+export { useSymbolSearch } from './hooks/useSymbolSearch';+export { useNews } from './hooks/useNews';++// Components+export { IndicatorBox } from './components/IndicatorBox';+export { FinancialAnalysisPanel } from './components/FinancialAnalysisPanel';+export { PeerComparisonPanel } from './components/PeerComparisonPanel';++// Tab Components+export { OverviewTab } from './tabs/OverviewTab';+export { FinancialsTab } from './tabs/FinancialsTab';+export { AnalysisTab } from './tabs/AnalysisTab';+export { TechnicalsTab } from './tabs/TechnicalsTab';+export { NewsTab } from './tabs/NewsTab';++// Utilities+export * from './utils/formatters';diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/AnalysisTab.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/AnalysisTab.tsxnew file mode 100644index 000000000..699aafc5b--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/AnalysisTab.tsx@@ -0,0 +1,464 @@+import React from 'react';+import { FinancialAnalysisPanel } from '../components/FinancialAnalysisPanel';+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';+import { formatNumber, formatLargeNumber, formatPercent } from '../utils/formatters';+import type { StockInfo } from '../types';++const COLORS = {+ ORANGE: FINCEPT.ORANGE,+ WHITE: FINCEPT.WHITE,+ RED: FINCEPT.RED,+ GREEN: FINCEPT.GREEN,+ YELLOW: FINCEPT.YELLOW,+ GRAY: FINCEPT.GRAY,+ BLUE: FINCEPT.BLUE,+ CYAN: FINCEPT.CYAN,+ DARK_BG: FINCEPT.DARK_BG,+ PANEL_BG: FINCEPT.PANEL_BG,+ BORDER: FINCEPT.BORDER,+ PURPLE: FINCEPT.PURPLE,+};++interface AnalysisTabProps {+ currentSymbol: string;+ stockInfo: StockInfo | null;+}++export const AnalysisTab: React.FC<AnalysisTabProps> = ({+ currentSymbol,+ stockInfo,+}) => {+ return (+ <div id="analysis-tab-content" style={{ padding: SPACING.DEFAULT }}>+ {/* Financial Analysis Panel - CFA-Compliant Analysis */}+ <div id="analysis-cfa-panel" style={{ marginBottom: SPACING.MEDIUM }}>+ <FinancialAnalysisPanel+ ticker={currentSymbol}+ companyName={stockInfo?.company_name || currentSymbol}+ />+ </div>++ {/* Financial Metrics Grid - 2x2 */}+ <div id="analysis-metrics-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: SPACING.MEDIUM }}>+ {/* Financial Health */}+ <div id="analysis-financial-health" style={{+ ...COMMON_STYLES.panel,+ padding: SPACING.LARGE,+ }}>+ <div style={{+ ...COMMON_STYLES.sectionHeader,+ fontSize: TYPOGRAPHY.SUBHEADING,+ paddingBottom: SPACING.SMALL,+ marginBottom: SPACING.LARGE,+ borderBottom: `2px solid ${COLORS.ORANGE}`,+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL,+ }}>+ <div style={{+ width: '4px',+ height: '16px',+ backgroundColor: COLORS.ORANGE,+ }} />+ FINANCIAL HEALTH+ </div>+ <div style={{+ display: 'grid',+ gridTemplateColumns: '1fr 1fr',+ gap: SPACING.LARGE,+ }}>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ TOTAL CASH+ </div>+ <div style={{+ color: COLORS.GREEN,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatLargeNumber(stockInfo?.total_cash)}+ </div>+ </div>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ TOTAL DEBT+ </div>+ <div style={{+ color: COLORS.RED,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatLargeNumber(stockInfo?.total_debt)}+ </div>+ </div>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ FREE CASHFLOW+ </div>+ <div style={{+ color: COLORS.CYAN,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatLargeNumber(stockInfo?.free_cashflow)}+ </div>+ </div>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ OPERATING CF+ </div>+ <div style={{+ color: COLORS.BLUE,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatLargeNumber(stockInfo?.operating_cashflow)}+ </div>+ </div>+ </div>+ </div>++ {/* Enterprise Value */}+ <div style={{+ ...COMMON_STYLES.panel,+ padding: SPACING.LARGE,+ }}>+ <div style={{+ color: COLORS.CYAN,+ fontSize: TYPOGRAPHY.SUBHEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ letterSpacing: TYPOGRAPHY.WIDE,+ textTransform: 'uppercase',+ paddingBottom: SPACING.SMALL,+ marginBottom: SPACING.LARGE,+ borderBottom: `2px solid ${COLORS.CYAN}`,+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL,+ }}>+ <div style={{+ width: '4px',+ height: '16px',+ backgroundColor: COLORS.CYAN,+ }} />+ ENTERPRISE VALUE+ </div>+ <div style={{+ display: 'grid',+ gridTemplateColumns: '1fr 1fr',+ gap: SPACING.LARGE,+ }}>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ ENTERPRISE VALUE+ </div>+ <div style={{+ color: COLORS.YELLOW,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatLargeNumber(stockInfo?.enterprise_value)}+ </div>+ </div>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ EV/REVENUE+ </div>+ <div style={{+ color: COLORS.CYAN,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatNumber(stockInfo?.enterprise_to_revenue)}+ </div>+ </div>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ EV/EBITDA+ </div>+ <div style={{+ color: COLORS.CYAN,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatNumber(stockInfo?.enterprise_to_ebitda)}+ </div>+ </div>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ BOOK VALUE+ </div>+ <div style={{+ color: COLORS.WHITE,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ ${formatNumber(stockInfo?.book_value)}+ </div>+ </div>+ </div>+ </div>++ {/* Revenue & Profits */}+ <div style={{+ ...COMMON_STYLES.panel,+ padding: SPACING.LARGE,+ }}>+ <div style={{+ color: COLORS.GREEN,+ fontSize: TYPOGRAPHY.SUBHEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ letterSpacing: TYPOGRAPHY.WIDE,+ textTransform: 'uppercase',+ paddingBottom: SPACING.SMALL,+ marginBottom: SPACING.LARGE,+ borderBottom: `2px solid ${COLORS.GREEN}`,+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL,+ }}>+ <div style={{+ width: '4px',+ height: '16px',+ backgroundColor: COLORS.GREEN,+ }} />+ REVENUE & PROFITS+ </div>+ <div style={{+ display: 'grid',+ gridTemplateColumns: '1fr 1fr',+ gap: SPACING.LARGE,+ }}>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ TOTAL REVENUE+ </div>+ <div style={{+ color: COLORS.GREEN,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatLargeNumber(stockInfo?.total_revenue)}+ </div>+ </div>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ REVENUE/SHARE+ </div>+ <div style={{+ color: COLORS.CYAN,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ ${formatNumber(stockInfo?.revenue_per_share)}+ </div>+ </div>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ GROSS PROFITS+ </div>+ <div style={{+ color: COLORS.GREEN,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatLargeNumber(stockInfo?.gross_profits)}+ </div>+ </div>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ EBITDA MARGINS+ </div>+ <div style={{+ color: COLORS.YELLOW,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatPercent(stockInfo?.ebitda_margins)}+ </div>+ </div>+ </div>+ </div>++ {/* Key Ratios Summary */}+ <div style={{+ ...COMMON_STYLES.panel,+ padding: SPACING.LARGE,+ }}>+ <div style={{+ color: COLORS.PURPLE,+ fontSize: TYPOGRAPHY.SUBHEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ letterSpacing: TYPOGRAPHY.WIDE,+ textTransform: 'uppercase',+ paddingBottom: SPACING.SMALL,+ marginBottom: SPACING.LARGE,+ borderBottom: `2px solid ${COLORS.PURPLE}`,+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL,+ }}>+ <div style={{+ width: '4px',+ height: '16px',+ backgroundColor: COLORS.PURPLE,+ }} />+ KEY RATIOS+ </div>+ <div style={{+ display: 'grid',+ gridTemplateColumns: '1fr 1fr',+ gap: SPACING.LARGE,+ }}>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ P/E RATIO+ </div>+ <div style={{+ color: COLORS.WHITE,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatNumber(stockInfo?.pe_ratio)}+ </div>+ </div>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ PEG RATIO+ </div>+ <div style={{+ color: COLORS.WHITE,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatNumber(stockInfo?.peg_ratio)}+ </div>+ </div>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ ROE+ </div>+ <div style={{+ color: COLORS.GREEN,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatPercent(stockInfo?.return_on_equity)}+ </div>+ </div>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ ROA+ </div>+ <div style={{+ color: COLORS.GREEN,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatPercent(stockInfo?.return_on_assets)}+ </div>+ </div>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ BETA+ </div>+ <div style={{+ color: COLORS.CYAN,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatNumber(stockInfo?.beta)}+ </div>+ </div>+ <div>+ <div style={{+ ...COMMON_STYLES.dataLabel,+ marginBottom: SPACING.TINY,+ }}>+ SHORT RATIO+ </div>+ <div style={{+ color: COLORS.RED,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ fontFamily: TYPOGRAPHY.MONO,+ }}>+ {formatNumber(stockInfo?.short_ratio)}+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ );+};++export default AnalysisTab;diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/FinancialsTab.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/FinancialsTab.tsxnew file mode 100644index 000000000..504fb3e20--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/FinancialsTab.tsx@@ -0,0 +1,541 @@+import React, { useState, useRef, useEffect } from 'react';+import { createChart, LineSeries } from 'lightweight-charts';+import { FINCEPT } from '../../portfolio-tab/finceptStyles';+import { formatNumber, formatLargeNumber, getYearFromPeriod } from '../utils/formatters';+import type { FinancialsData } from '../types';++const COLORS = {+ ORANGE: FINCEPT.ORANGE,+ WHITE: FINCEPT.WHITE,+ RED: FINCEPT.RED,+ GREEN: FINCEPT.GREEN,+ YELLOW: FINCEPT.YELLOW,+ GRAY: FINCEPT.GRAY,+ BLUE: FINCEPT.BLUE,+ CYAN: FINCEPT.CYAN,+ DARK_BG: FINCEPT.DARK_BG,+ PANEL_BG: FINCEPT.PANEL_BG,+ BORDER: FINCEPT.BORDER,+ MAGENTA: '#FF00FF',+};++interface FinancialsTabProps {+ financials: FinancialsData | null;+ loading: boolean;+}++export const FinancialsTab: React.FC<FinancialsTabProps> = ({+ financials,+ loading,+}) => {+ const [fontSize, setFontSize] = useState(12);+ const [showYearsCount, setShowYearsCount] = useState(4);+ const [selectedMetrics, setSelectedMetrics] = useState<string[]>(['Total Revenue', 'Gross Profit', 'Operating Income', 'Net Income', 'EBITDA', 'Basic EPS', 'Diluted EPS']);+ const [chart1Metrics, setChart1Metrics] = useState<string[]>(['Total Revenue', 'Gross Profit']);+ const [chart2Metrics, setChart2Metrics] = useState<string[]>(['Net Income', 'Operating Income']);+ const [chart3Metrics, setChart3Metrics] = useState<string[]>(['EBITDA']);++ const financialChart1Ref = useRef<HTMLDivElement>(null);+ const financialChart2Ref = useRef<HTMLDivElement>(null);+ const financialChart3Ref = useRef<HTMLDivElement>(null);+ const financialChart1InstanceRef = useRef<any>(null);+ const financialChart2InstanceRef = useRef<any>(null);+ const financialChart3InstanceRef = useRef<any>(null);++ // Get all available metrics from income statement+ const getAllMetrics = (): string[] => {+ if (!financials || Object.keys(financials.income_statement).length === 0) return [];+ const firstPeriod = Object.keys(financials.income_statement)[0];+ return Object.keys(financials.income_statement[firstPeriod]);+ };++ const toggleMetric = (metric: string) => {+ setSelectedMetrics(prev =>+ prev.includes(metric)+ ? prev.filter(m => m !== metric)+ : [...prev, metric]+ );+ };++ // Helper function to create a financial chart with dynamic metrics+ const createFinancialChart = (+ container: HTMLDivElement | null,+ metrics: string[],+ chartColors: string[]+ ) => {+ if (!container || !financials) return null;++ const chart = createChart(container, {+ layout: {+ background: { color: COLORS.DARK_BG },+ textColor: COLORS.WHITE,+ },+ grid: {+ vertLines: { color: COLORS.BORDER },+ horzLines: { color: COLORS.BORDER },+ },+ width: container.clientWidth,+ height: 250,+ timeScale: {+ borderColor: COLORS.GRAY,+ timeVisible: true,+ },+ rightPriceScale: {+ borderColor: COLORS.GRAY,+ },+ });++ const periods = Object.keys(financials.income_statement);++ metrics.forEach((metric, idx) => {+ const color = chartColors[idx % chartColors.length];+ const series = chart.addSeries(LineSeries, {+ color,+ lineWidth: 2,+ title: metric,+ });++ const data: any[] = [];+ periods.forEach((period) => {+ const timestamp = new Date(period).getTime() / 1000;+ const statements = financials.income_statement[period];++ if (statements[metric] !== undefined && statements[metric] !== null) {+ const value = metric.includes('EPS')+ ? statements[metric]+ : statements[metric] / 1e9; // Convert to billions+ data.push({ time: timestamp, value });+ }+ });++ if (data.length > 0) {+ series.setData(data.sort((a, b) => a.time - b.time));+ }+ });++ chart.timeScale().fitContent();+ return chart;+ };++ // Update financial charts when data or metrics change+ useEffect(() => {+ if (financials) {+ // Cleanup existing charts+ [financialChart1InstanceRef, financialChart2InstanceRef, financialChart3InstanceRef].forEach(ref => {+ if (ref.current) {+ try {+ ref.current.remove();+ } catch (e) {+ // Chart already disposed+ }+ ref.current = null;+ }+ });++ const chartColors = [COLORS.GREEN, COLORS.CYAN, COLORS.ORANGE, COLORS.YELLOW, COLORS.MAGENTA, COLORS.BLUE];++ if (financialChart1Ref.current && chart1Metrics.length > 0) {+ financialChart1InstanceRef.current = createFinancialChart(financialChart1Ref.current, chart1Metrics, chartColors);+ }++ if (financialChart2Ref.current && chart2Metrics.length > 0) {+ financialChart2InstanceRef.current = createFinancialChart(financialChart2Ref.current, chart2Metrics, chartColors);+ }++ if (financialChart3Ref.current && chart3Metrics.length > 0) {+ financialChart3InstanceRef.current = createFinancialChart(financialChart3Ref.current, chart3Metrics, chartColors);+ }++ // Handle resize+ const handleResize = () => {+ if (financialChart1Ref.current && financialChart1InstanceRef.current) {+ financialChart1InstanceRef.current.applyOptions({ width: financialChart1Ref.current.clientWidth });+ }+ if (financialChart2Ref.current && financialChart2InstanceRef.current) {+ financialChart2InstanceRef.current.applyOptions({ width: financialChart2Ref.current.clientWidth });+ }+ if (financialChart3Ref.current && financialChart3InstanceRef.current) {+ financialChart3InstanceRef.current.applyOptions({ width: financialChart3Ref.current.clientWidth });+ }+ };++ window.addEventListener('resize', handleResize);+ return () => {+ window.removeEventListener('resize', handleResize);+ [financialChart1InstanceRef, financialChart2InstanceRef, financialChart3InstanceRef].forEach(ref => {+ if (ref.current) {+ try {+ ref.current.remove();+ } catch (e) {+ // Chart already disposed+ }+ ref.current = null;+ }+ });+ };+ }+ }, [financials, chart1Metrics, chart2Metrics, chart3Metrics]);++ if (!financials) {+ return (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '400px',+ gap: '16px',+ }}>+ {loading && (+ <div style={{+ width: '50px',+ height: '50px',+ border: '4px solid #404040',+ borderTop: '4px solid #ea580c',+ borderRadius: '50%',+ animation: 'spin 1s linear infinite'+ }} />+ )}+ <div style={{ color: COLORS.YELLOW, fontSize: '14px', fontWeight: 'bold' }}>+ {loading ? 'LOADING FINANCIAL DATA...' : '[WARN] NO FINANCIAL DATA AVAILABLE'}+ </div>+ <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>+ {loading ? 'Please wait while we fetch the data' : 'Financial statements are not available for this symbol'}+ </div>+ </div>+ );+ }++ const allMetrics = getAllMetrics();++ return (+ <div id="research-financials" style={{ padding: '8px' }}>+ {/* Controls Panel */}+ <div id="financials-controls" style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '10px 12px',+ marginBottom: '8px',+ display: 'flex',+ gap: '20px',+ alignItems: 'center',+ flexWrap: 'wrap',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{ color: COLORS.GRAY, fontSize: `${fontSize}px` }}>FONT SIZE:</span>+ <button+ onClick={() => setFontSize(Math.max(10, fontSize - 1))}+ style={{+ backgroundColor: COLORS.DARK_BG,+ border: `1px solid ${COLORS.BORDER}`,+ color: COLORS.WHITE,+ padding: '4px 8px',+ fontSize: `${fontSize}px`,+ cursor: 'pointer',+ }}+ >+ -+ </button>+ <span style={{ color: COLORS.ORANGE, fontSize: `${fontSize}px`, fontWeight: 'bold', minWidth: '30px', textAlign: 'center' }}>{fontSize}px</span>+ <button+ onClick={() => setFontSize(Math.min(20, fontSize + 1))}+ style={{+ backgroundColor: COLORS.DARK_BG,+ border: `1px solid ${COLORS.BORDER}`,+ color: COLORS.WHITE,+ padding: '4px 8px',+ fontSize: `${fontSize}px`,+ cursor: 'pointer',+ }}+ >+ ++ </button>+ </div>++ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{ color: COLORS.GRAY, fontSize: `${fontSize}px` }}>SHOW YEARS:</span>+ {[2, 3, 4, 5].map((count) => (+ <button+ key={count}+ onClick={() => setShowYearsCount(count)}+ style={{+ backgroundColor: showYearsCount === count ? COLORS.ORANGE : COLORS.DARK_BG,+ border: `1px solid ${COLORS.BORDER}`,+ color: showYearsCount === count ? COLORS.DARK_BG : COLORS.WHITE,+ padding: '4px 10px',+ fontSize: `${fontSize - 1}px`,+ cursor: 'pointer',+ fontWeight: showYearsCount === count ? 'bold' : 'normal',+ }}+ >+ {count}+ </button>+ ))}+ </div>++ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span style={{ color: COLORS.GRAY, fontSize: `${fontSize}px` }}>SELECT METRICS:</span>+ <button+ onClick={() => {+ setSelectedMetrics(selectedMetrics.length === allMetrics.length ? [] : allMetrics);+ }}+ style={{+ backgroundColor: COLORS.BLUE,+ border: 'none',+ color: COLORS.WHITE,+ padding: '4px 10px',+ fontSize: `${fontSize - 1}px`,+ cursor: 'pointer',+ fontWeight: 'bold',+ }}+ >+ {selectedMetrics.length === allMetrics.length ? 'DESELECT ALL' : 'SELECT ALL'}+ </button>+ </div>+ </div>++ {/* Metric Selector */}+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '12px',+ marginBottom: '8px',+ }}>+ <div style={{ color: COLORS.CYAN, fontSize: `${fontSize + 2}px`, fontWeight: 'bold', marginBottom: '10px' }}>+ SELECT METRICS TO COMPARE+ </div>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>+ {allMetrics.map((metric) => (+ <button+ key={metric}+ onClick={() => toggleMetric(metric)}+ style={{+ backgroundColor: selectedMetrics.includes(metric) ? COLORS.GREEN : COLORS.DARK_BG,+ border: `1px solid ${selectedMetrics.includes(metric) ? COLORS.GREEN : COLORS.BORDER}`,+ color: selectedMetrics.includes(metric) ? COLORS.DARK_BG : COLORS.WHITE,+ padding: '6px 12px',+ fontSize: `${fontSize - 1}px`,+ cursor: 'pointer',+ fontWeight: selectedMetrics.includes(metric) ? 'bold' : 'normal',+ borderRadius: '3px',+ }}+ >+ {metric}+ </button>+ ))}+ </div>+ </div>++ {/* Financial Comparison Charts - 3 Charts in a Row */}+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '12px',+ marginBottom: '8px',+ }}>+ <div style={{ color: COLORS.ORANGE, fontSize: `${fontSize + 3}px`, fontWeight: 'bold', marginBottom: '12px' }}>+ FINANCIAL TRENDS COMPARISON (in Billions $)+ </div>++ {/* Chart Controls */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px', marginBottom: '12px' }}>+ {[+ { label: 'CHART 1 METRICS:', metrics: chart1Metrics, setMetrics: setChart1Metrics, color: COLORS.GREEN },+ { label: 'CHART 2 METRICS:', metrics: chart2Metrics, setMetrics: setChart2Metrics, color: COLORS.ORANGE },+ { label: 'CHART 3 METRICS:', metrics: chart3Metrics, setMetrics: setChart3Metrics, color: COLORS.MAGENTA },+ ].map(({ label, metrics, setMetrics, color }) => (+ <div key={label}>+ <div style={{ color: COLORS.CYAN, fontSize: `${fontSize}px`, fontWeight: 'bold', marginBottom: '6px' }}>+ {label}+ </div>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>+ {allMetrics.slice(0, 8).map((metric) => (+ <button+ key={metric}+ onClick={() => {+ setMetrics(prev =>+ prev.includes(metric)+ ? prev.filter(m => m !== metric)+ : [...prev, metric]+ );+ }}+ style={{+ backgroundColor: metrics.includes(metric) ? color : COLORS.DARK_BG,+ border: `1px solid ${metrics.includes(metric) ? color : COLORS.BORDER}`,+ color: metrics.includes(metric) ? COLORS.DARK_BG : COLORS.WHITE,+ padding: '3px 6px',+ fontSize: `${fontSize - 3}px`,+ cursor: 'pointer',+ fontWeight: metrics.includes(metric) ? 'bold' : 'normal',+ }}+ >+ {metric.substring(0, 15)}+ </button>+ ))}+ </div>+ </div>+ ))}+ </div>++ {/* 3 Charts Side by Side */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>+ <div>+ <div style={{ color: COLORS.GREEN, fontSize: `${fontSize}px`, fontWeight: 'bold', marginBottom: '6px', textAlign: 'center' }}>+ {chart1Metrics.join(', ') || 'Select metrics'}+ </div>+ <div ref={financialChart1Ref} style={{ backgroundColor: COLORS.DARK_BG }} />+ </div>+ <div>+ <div style={{ color: COLORS.ORANGE, fontSize: `${fontSize}px`, fontWeight: 'bold', marginBottom: '6px', textAlign: 'center' }}>+ {chart2Metrics.join(', ') || 'Select metrics'}+ </div>+ <div ref={financialChart2Ref} style={{ backgroundColor: COLORS.DARK_BG }} />+ </div>+ <div>+ <div style={{ color: COLORS.MAGENTA, fontSize: `${fontSize}px`, fontWeight: 'bold', marginBottom: '6px', textAlign: 'center' }}>+ {chart3Metrics.join(', ') || 'Select metrics'}+ </div>+ <div ref={financialChart3Ref} style={{ backgroundColor: COLORS.DARK_BG }} />+ </div>+ </div>+ </div>++ {/* Financial Comparison Table */}+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '12px',+ marginBottom: '8px',+ }}>+ <div style={{ color: COLORS.CYAN, fontSize: `${fontSize + 3}px`, fontWeight: 'bold', marginBottom: '12px' }}>+ YEAR-OVER-YEAR COMPARISON ({selectedMetrics.length} Metrics)+ </div>++ {selectedMetrics.length === 0 ? (+ <div style={{ color: COLORS.YELLOW, fontSize: `${fontSize + 1}px`, textAlign: 'center', padding: '20px' }}>+ Please select at least one metric to compare+ </div>+ ) : (+ <div style={{ overflowX: 'auto' }} className="custom-scrollbar">+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: `${fontSize}px` }}>+ <thead>+ <tr style={{ borderBottom: `2px solid ${COLORS.BORDER}` }}>+ <th style={{ textAlign: 'left', padding: '10px', color: COLORS.GRAY, fontSize: `${fontSize + 1}px` }}>METRIC</th>+ {Object.keys(financials.income_statement).slice(0, showYearsCount).map((period) => (+ <th key={period} style={{ textAlign: 'right', padding: '10px', color: COLORS.ORANGE, fontSize: `${fontSize + 1}px` }}>+ {getYearFromPeriod(period)}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {selectedMetrics.map((metric) => {+ const periods = Object.keys(financials.income_statement).slice(0, showYearsCount);+ return (+ <tr key={metric} style={{ borderBottom: `1px solid rgba(255,255,255,0.05)` }}>+ <td style={{ padding: '10px', color: COLORS.WHITE, fontWeight: 'bold', fontSize: `${fontSize}px` }}>{metric}</td>+ {periods.map((period) => {+ const value = financials.income_statement[period][metric];+ return (+ <td key={period} style={{ textAlign: 'right', padding: '10px', color: COLORS.CYAN, fontSize: `${fontSize}px` }}>+ {value ? (metric.includes('EPS') ? `$${formatNumber(value)}` : formatLargeNumber(value)) : 'N/A'}+ </td>+ );+ })}+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ )}+ </div>++ {/* Detailed Financial Statements */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>+ {/* Income Statement */}+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '8px',+ }}>+ <div style={{ color: COLORS.GREEN, fontSize: `${fontSize + 2}px`, fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ INCOME STATEMENT (Latest)+ </div>+ <div style={{ fontSize: `${fontSize}px`, maxHeight: '500px', overflow: 'auto' }} className="custom-scrollbar">+ {Object.keys(financials.income_statement).length > 0 ? (+ Object.entries(Object.values(financials.income_statement)[0] || {}).map(([metric, _], idx) => {+ const latestPeriod = Object.keys(financials.income_statement)[0];+ const value = financials.income_statement[latestPeriod][metric];+ return (+ <div key={idx} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px', paddingBottom: '6px', borderBottom: `1px solid rgba(255,255,255,0.05)` }}>+ <span style={{ color: COLORS.GRAY, fontSize: `${fontSize - 1}px`, maxWidth: '60%' }}>{metric}:</span>+ <span style={{ color: COLORS.CYAN, fontSize: `${fontSize}px` }}>{formatLargeNumber(value)}</span>+ </div>+ );+ })+ ) : (+ <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '20px', fontSize: `${fontSize}px` }}>No data available</div>+ )}+ </div>+ </div>++ {/* Balance Sheet */}+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '8px',+ }}>+ <div style={{ color: COLORS.YELLOW, fontSize: `${fontSize + 2}px`, fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ BALANCE SHEET (Latest)+ </div>+ <div style={{ fontSize: `${fontSize}px`, maxHeight: '500px', overflow: 'auto' }} className="custom-scrollbar">+ {Object.keys(financials.balance_sheet).length > 0 ? (+ Object.entries(Object.values(financials.balance_sheet)[0] || {}).map(([metric, _], idx) => {+ const latestPeriod = Object.keys(financials.balance_sheet)[0];+ const value = financials.balance_sheet[latestPeriod][metric];+ return (+ <div key={idx} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px', paddingBottom: '6px', borderBottom: `1px solid rgba(255,255,255,0.05)` }}>+ <span style={{ color: COLORS.GRAY, fontSize: `${fontSize - 1}px`, maxWidth: '60%' }}>{metric}:</span>+ <span style={{ color: COLORS.CYAN, fontSize: `${fontSize}px` }}>{formatLargeNumber(value)}</span>+ </div>+ );+ })+ ) : (+ <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '20px', fontSize: `${fontSize}px` }}>No data available</div>+ )}+ </div>+ </div>++ {/* Cash Flow */}+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '8px',+ }}>+ <div style={{ color: COLORS.CYAN, fontSize: `${fontSize + 2}px`, fontWeight: 'bold', marginBottom: '8px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '4px' }}>+ CASH FLOW STATEMENT (Latest)+ </div>+ <div style={{ fontSize: `${fontSize}px`, maxHeight: '500px', overflow: 'auto' }} className="custom-scrollbar">+ {Object.keys(financials.cash_flow).length > 0 ? (+ Object.entries(Object.values(financials.cash_flow)[0] || {}).map(([metric, _], idx) => {+ const latestPeriod = Object.keys(financials.cash_flow)[0];+ const value = financials.cash_flow[latestPeriod][metric];+ return (+ <div key={idx} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px', paddingBottom: '6px', borderBottom: `1px solid rgba(255,255,255,0.05)` }}>+ <span style={{ color: COLORS.GRAY, fontSize: `${fontSize - 1}px`, maxWidth: '60%' }}>{metric}:</span>+ <span style={{ color: COLORS.CYAN, fontSize: `${fontSize}px` }}>{formatLargeNumber(value)}</span>+ </div>+ );+ })+ ) : (+ <div style={{ color: COLORS.GRAY, textAlign: 'center', padding: '20px', fontSize: `${fontSize}px` }}>No data available</div>+ )}+ </div>+ </div>+ </div>+ </div>+ );+};++export default FinancialsTab;diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/NewsTab.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/NewsTab.tsxnew file mode 100644index 000000000..47795228a--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/NewsTab.tsx@@ -0,0 +1,251 @@+import React from 'react';+import { FINCEPT } from '../../portfolio-tab/finceptStyles';+import type { NewsData, StockInfo } from '../types';++const COLORS = {+ ORANGE: FINCEPT.ORANGE,+ WHITE: FINCEPT.WHITE,+ RED: FINCEPT.RED,+ GREEN: FINCEPT.GREEN,+ YELLOW: FINCEPT.YELLOW,+ GRAY: FINCEPT.GRAY,+ CYAN: FINCEPT.CYAN,+ DARK_BG: FINCEPT.DARK_BG,+ PANEL_BG: FINCEPT.PANEL_BG,+ BORDER: FINCEPT.BORDER,+};++interface NewsTabProps {+ newsData: NewsData | null;+ newsLoading: boolean;+ currentSymbol: string;+ stockInfo: StockInfo | null;+ onRefresh: () => void;+}++export const NewsTab: React.FC<NewsTabProps> = ({+ newsData,+ newsLoading,+ currentSymbol,+ stockInfo,+ onRefresh,+}) => {+ if (newsLoading) {+ return (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '400px',+ gap: '16px',+ }}>+ <div style={{+ width: '50px',+ height: '50px',+ border: '4px solid #404040',+ borderTop: '4px solid #ea580c',+ borderRadius: '50%',+ animation: 'spin 1s linear infinite'+ }} />+ <div style={{ color: COLORS.YELLOW, fontSize: '14px', fontWeight: 'bold' }}>+ FETCHING LATEST NEWS...+ </div>+ <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>+ Loading news for {currentSymbol}+ </div>+ </div>+ );+ }++ if (!newsData || !newsData.success) {+ return (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '400px',+ gap: '16px',+ }}>+ <div style={{ color: COLORS.RED, fontSize: '14px', fontWeight: 'bold' }}>+ [WARN] NO NEWS AVAILABLE+ </div>+ <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>+ {newsData?.error || 'Unable to fetch news at this time'}+ </div>+ <button+ onClick={onRefresh}+ style={{+ backgroundColor: COLORS.ORANGE,+ border: 'none',+ color: COLORS.DARK_BG,+ padding: '8px 16px',+ fontSize: '10px',+ cursor: 'pointer',+ fontWeight: 'bold',+ marginTop: '8px',+ }}+ >+ RETRY+ </button>+ </div>+ );+ }++ if (newsData.data && newsData.data.length === 0) {+ return (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '400px',+ gap: '16px',+ }}>+ <div style={{ color: COLORS.YELLOW, fontSize: '14px', fontWeight: 'bold' }}>+ NO NEWS FOUND+ </div>+ <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>+ No recent news articles found for {stockInfo?.company_name || currentSymbol}+ </div>+ </div>+ );+ }++ return (+ <div style={{ padding: '8px', height: 'calc(100vh - 280px)', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>+ {/* News Header */}+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '8px 12px',+ marginBottom: '8px',+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ flexShrink: 0,+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <span style={{ color: COLORS.ORANGE, fontSize: '11px', fontWeight: 'bold' }}>+ LATEST NEWS+ </span>+ <span style={{ color: COLORS.GRAY, fontSize: '9px' }}>+ {newsData.count || 0} articles found+ </span>+ <span style={{ color: COLORS.CYAN, fontSize: '9px' }}>+ {stockInfo?.company_name || currentSymbol}+ </span>+ </div>+ <button+ onClick={onRefresh}+ style={{+ backgroundColor: COLORS.DARK_BG,+ border: `1px solid ${COLORS.BORDER}`,+ color: COLORS.WHITE,+ padding: '4px 12px',+ fontSize: '9px',+ cursor: 'pointer',+ fontWeight: 'bold',+ }}+ >+ REFRESH+ </button>+ </div>++ {/* News Articles List */}+ <div style={{+ flex: 1,+ overflow: 'auto',+ display: 'flex',+ flexDirection: 'column',+ gap: '8px',+ }} className="custom-scrollbar">+ {newsData.data.map((article, index) => (+ <div+ key={index}+ style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '12px',+ cursor: 'pointer',+ transition: 'all 0.2s',+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = '#252525';+ e.currentTarget.style.borderColor = COLORS.ORANGE;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = COLORS.PANEL_BG;+ e.currentTarget.style.borderColor = COLORS.BORDER;+ }}+ onClick={() => {+ if (article.url && article.url !== '#') {+ window.open(article.url, '_blank');+ }+ }}+ >+ {/* Article Header */}+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>+ <div style={{ flex: 1, marginRight: '12px' }}>+ <h3 style={{+ color: COLORS.WHITE,+ fontSize: '12px',+ fontWeight: 'bold',+ margin: 0,+ marginBottom: '6px',+ lineHeight: '1.4',+ }}>+ {article.title}+ </h3>+ <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>+ <span style={{+ color: COLORS.CYAN,+ fontSize: '9px',+ fontWeight: 'bold',+ }}>+ {article.publisher || 'Unknown Source'}+ </span>+ <span style={{+ color: COLORS.GRAY,+ fontSize: '9px',+ }}>+ {article.published_date || 'Unknown Date'}+ </span>+ </div>+ </div>+ </div>++ {/* Article Description */}+ {article.description && article.description !== 'N/A' && (+ <div style={{+ color: COLORS.GRAY,+ fontSize: '10px',+ lineHeight: '1.5',+ marginBottom: '8px',+ }}>+ {article.description}+ </div>+ )}++ {/* Read More Link */}+ {article.url && article.url !== '#' && (+ <div style={{+ color: COLORS.ORANGE,+ fontSize: '9px',+ fontWeight: 'bold',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ }}>+ READ FULL ARTICLE+ </div>+ )}+ </div>+ ))}+ </div>+ </div>+ );+};++export default NewsTab;diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/OverviewTab.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/OverviewTab.tsxnew file mode 100644index 000000000..b862b2137--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/OverviewTab.tsx@@ -0,0 +1,545 @@+import React from 'react';+import { AlertCircle } from 'lucide-react';+import { ProChartWithToolkit } from '../../trading/charts/ProChartWithToolkit';+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES } from '../../portfolio-tab/finceptStyles';+import { formatNumber, formatLargeNumber, formatPercent, getRecommendationColor, getRecommendationText } from '../utils/formatters';+import type { StockInfo, QuoteData, HistoricalData, ChartPeriod } from '../types';++const COLORS = {+ ORANGE: FINCEPT.ORANGE,+ WHITE: FINCEPT.WHITE,+ RED: FINCEPT.RED,+ GREEN: FINCEPT.GREEN,+ YELLOW: FINCEPT.YELLOW,+ GRAY: FINCEPT.GRAY,+ BLUE: FINCEPT.BLUE,+ CYAN: FINCEPT.CYAN,+ DARK_BG: FINCEPT.DARK_BG,+ PANEL_BG: FINCEPT.PANEL_BG,+ BORDER: FINCEPT.BORDER,+ MAGENTA: '#FF00FF',+ PURPLE: FINCEPT.PURPLE,+};++interface OverviewTabProps {+ currentSymbol: string;+ stockInfo: StockInfo | null;+ quoteData: QuoteData | null;+ historicalData: HistoricalData[];+ chartPeriod: ChartPeriod;+ setChartPeriod: (period: ChartPeriod) => void;+ loading: boolean;+}++export const OverviewTab: React.FC<OverviewTabProps> = ({+ currentSymbol,+ stockInfo,+ quoteData,+ historicalData,+ chartPeriod,+ setChartPeriod,+ loading,+}) => {+ return (+ <div id="research-overview" style={{+ display: 'flex',+ flexDirection: 'column',+ gap: SPACING.MEDIUM,+ padding: SPACING.DEFAULT,+ height: '100%',+ boxSizing: 'border-box',+ }}>+ {/* Top Data Grid - 4 Columns */}+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(4, 1fr)',+ gap: SPACING.MEDIUM,+ flex: '0 0 auto',+ minHeight: '400px',+ }}>+ {/* Column 1 - Trading & Valuation */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.MEDIUM }}>+ {/* Today's Trading */}+ <div id="overview-trading" style={{+ ...COMMON_STYLES.panel,+ padding: SPACING.MEDIUM,+ }}>+ <div style={{+ ...COMMON_STYLES.sectionHeader,+ fontSize: TYPOGRAPHY.BODY,+ paddingBottom: SPACING.TINY,+ marginBottom: SPACING.SMALL,+ borderBottom: BORDERS.STANDARD,+ }}>+ TODAY'S TRADING+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, fontSize: TYPOGRAPHY.SMALL }}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>OPEN</span>+ <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(quoteData?.open)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>HIGH</span>+ <span style={{ color: COLORS.GREEN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(quoteData?.high)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>LOW</span>+ <span style={{ color: COLORS.RED, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(quoteData?.low)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>PREV CLOSE</span>+ <span style={{ color: COLORS.WHITE, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(quoteData?.previous_close)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>VOLUME</span>+ <span style={{ color: COLORS.YELLOW, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatNumber(quoteData?.volume || 0, 0)}</span>+ </div>+ </div>+ </div>++ {/* Valuation Metrics */}+ <div id="overview-valuation" style={{+ ...COMMON_STYLES.panel,+ padding: SPACING.MEDIUM,+ }}>+ <div style={{+ color: COLORS.CYAN,+ fontSize: TYPOGRAPHY.BODY,+ fontWeight: TYPOGRAPHY.BOLD,+ letterSpacing: TYPOGRAPHY.WIDE,+ textTransform: 'uppercase',+ paddingBottom: SPACING.TINY,+ marginBottom: SPACING.SMALL,+ borderBottom: BORDERS.STANDARD,+ }}>+ VALUATION+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, fontSize: TYPOGRAPHY.SMALL }}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>MARKET CAP</span>+ <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatLargeNumber(stockInfo?.market_cap)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>P/E RATIO</span>+ <span style={{ color: COLORS.YELLOW, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatNumber(stockInfo?.pe_ratio)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>FWD P/E</span>+ <span style={{ color: COLORS.YELLOW, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatNumber(stockInfo?.forward_pe)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>PEG RATIO</span>+ <span style={{ color: COLORS.YELLOW, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatNumber(stockInfo?.peg_ratio)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>P/B RATIO</span>+ <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatNumber(stockInfo?.price_to_book)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>DIV YIELD</span>+ <span style={{ color: COLORS.GREEN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>+ {formatPercent(stockInfo?.dividend_yield)}+ </span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>BETA</span>+ <span style={{ color: COLORS.WHITE, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatNumber(stockInfo?.beta)}</span>+ </div>+ </div>+ </div>++ {/* Share Statistics */}+ <div style={{+ ...COMMON_STYLES.panel,+ padding: SPACING.MEDIUM,+ flex: 1,+ }}>+ <div style={{+ color: COLORS.PURPLE,+ fontSize: TYPOGRAPHY.BODY,+ fontWeight: TYPOGRAPHY.BOLD,+ letterSpacing: TYPOGRAPHY.WIDE,+ textTransform: 'uppercase',+ paddingBottom: SPACING.TINY,+ marginBottom: SPACING.SMALL,+ borderBottom: BORDERS.STANDARD,+ }}>+ SHARE STATS+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, fontSize: TYPOGRAPHY.SMALL }}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>SHARES OUT</span>+ <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatLargeNumber(stockInfo?.shares_outstanding)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>FLOAT</span>+ <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatLargeNumber(stockInfo?.float_shares)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>INSIDERS</span>+ <span style={{ color: COLORS.YELLOW, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatPercent(stockInfo?.held_percent_insiders)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>INSTITUTIONS</span>+ <span style={{ color: COLORS.YELLOW, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatPercent(stockInfo?.held_percent_institutions)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>SHORT %</span>+ <span style={{ color: COLORS.RED, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatPercent(stockInfo?.short_percent_of_float)}</span>+ </div>+ </div>+ </div>+ </div>++ {/* Column 2 - Price Chart */}+ <div id="overview-price-chart" style={{+ display: 'flex',+ flexDirection: 'column',+ gap: SPACING.MEDIUM,+ gridColumn: 'span 2',+ overflow: 'hidden',+ minHeight: 0,+ }}>+ {/* Chart Period Selector */}+ <div style={{+ ...COMMON_STYLES.panel,+ padding: SPACING.SMALL,+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL,+ flexShrink: 0,+ }}>+ <span style={{+ ...COMMON_STYLES.dataLabel,+ marginRight: SPACING.TINY,+ }}>+ PERIOD+ </span>+ {(['1M', '3M', '6M', '1Y', '5Y'] as const).map((period) => (+ <button+ key={period}+ onClick={() => setChartPeriod(period)}+ style={{+ padding: `${SPACING.TINY} ${SPACING.MEDIUM}`,+ backgroundColor: chartPeriod === period ? COLORS.ORANGE : 'transparent',+ border: BORDERS.STANDARD,+ borderColor: chartPeriod === period ? COLORS.ORANGE : COLORS.BORDER,+ color: chartPeriod === period ? COLORS.DARK_BG : COLORS.WHITE,+ fontSize: TYPOGRAPHY.SMALL,+ cursor: 'pointer',+ fontWeight: TYPOGRAPHY.BOLD,+ transition: 'all 0.15s ease',+ }}+ onMouseEnter={(e) => {+ if (chartPeriod !== period) {+ e.currentTarget.style.backgroundColor = '#333';+ e.currentTarget.style.borderColor = COLORS.ORANGE;+ }+ }}+ onMouseLeave={(e) => {+ if (chartPeriod !== period) {+ e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.borderColor = COLORS.BORDER;+ }+ }}+ >+ {period}+ </button>+ ))}+ </div>++ {/* Chart with Volume */}+ <div style={{+ ...COMMON_STYLES.panel,+ padding: '0',+ overflow: 'hidden',+ flex: 1,+ display: 'flex',+ flexDirection: 'column',+ minHeight: 0,+ }}>+ {historicalData && historicalData.length > 0 ? (+ <ProChartWithToolkit+ data={historicalData.map(h => ({+ time: h.timestamp,+ open: h.open,+ high: h.high,+ low: h.low,+ close: h.close,+ volume: h.volume,+ }))}+ symbol={`${currentSymbol} - ${chartPeriod}`}+ height={400}+ showVolume={true}+ showToolbar={true}+ onToolChange={(tool) => {+ console.log('[EquityResearch] Active tool:', tool);+ }}+ />+ ) : (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ height: '100%',+ color: COLORS.GRAY,+ fontSize: TYPOGRAPHY.DEFAULT,+ flexDirection: 'column',+ gap: SPACING.MEDIUM,+ }}>+ {loading ? (+ <>+ <div style={{+ width: '40px',+ height: '40px',+ border: '3px solid #404040',+ borderTop: '3px solid #ea580c',+ borderRadius: '50%',+ animation: 'spin 1s linear infinite'+ }} />+ <span>Loading chart data...</span>+ </>+ ) : (+ <>+ <AlertCircle size={32} color={COLORS.GRAY} />+ <span>No chart data available</span>+ </>+ )}+ </div>+ )}+ </div>+ </div>++ {/* Column 3 - Analyst & Performance */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.MEDIUM }}>+ {/* Analyst Targets */}+ <div id="research-analyst-ratings" style={{+ ...COMMON_STYLES.panel,+ padding: SPACING.MEDIUM,+ }}>+ <div style={{+ color: COLORS.MAGENTA,+ fontSize: TYPOGRAPHY.BODY,+ fontWeight: TYPOGRAPHY.BOLD,+ letterSpacing: TYPOGRAPHY.WIDE,+ textTransform: 'uppercase',+ paddingBottom: SPACING.TINY,+ marginBottom: SPACING.SMALL,+ borderBottom: BORDERS.STANDARD,+ }}>+ ANALYST TARGETS+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, fontSize: TYPOGRAPHY.SMALL }}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>HIGH</span>+ <span style={{ color: COLORS.GREEN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(stockInfo?.target_high_price)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>MEAN</span>+ <span style={{ color: COLORS.YELLOW, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(stockInfo?.target_mean_price)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>LOW</span>+ <span style={{ color: COLORS.RED, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(stockInfo?.target_low_price)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>ANALYSTS</span>+ <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{stockInfo?.number_of_analyst_opinions || 'N/A'}</span>+ </div>+ </div>+ </div>++ {/* 52 Week Range */}+ <div style={{+ ...COMMON_STYLES.panel,+ padding: SPACING.MEDIUM,+ }}>+ <div style={{+ color: COLORS.YELLOW,+ fontSize: TYPOGRAPHY.BODY,+ fontWeight: TYPOGRAPHY.BOLD,+ letterSpacing: TYPOGRAPHY.WIDE,+ textTransform: 'uppercase',+ paddingBottom: SPACING.TINY,+ marginBottom: SPACING.SMALL,+ borderBottom: BORDERS.STANDARD,+ }}>+ 52 WEEK RANGE+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, fontSize: TYPOGRAPHY.SMALL }}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>HIGH</span>+ <span style={{ color: COLORS.GREEN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(stockInfo?.fifty_two_week_high)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>LOW</span>+ <span style={{ color: COLORS.RED, fontWeight: TYPOGRAPHY.SEMIBOLD }}>${formatNumber(stockInfo?.fifty_two_week_low)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>AVG VOL</span>+ <span style={{ color: COLORS.CYAN, fontWeight: TYPOGRAPHY.SEMIBOLD }}>{formatNumber(stockInfo?.average_volume, 0)}</span>+ </div>+ </div>+ </div>++ {/* Profitability */}+ <div id="overview-profitability" style={{+ ...COMMON_STYLES.panel,+ padding: SPACING.MEDIUM,+ flex: 1,+ }}>+ <div style={{+ color: COLORS.GREEN,+ fontSize: TYPOGRAPHY.BODY,+ fontWeight: TYPOGRAPHY.BOLD,+ letterSpacing: TYPOGRAPHY.WIDE,+ textTransform: 'uppercase',+ paddingBottom: SPACING.TINY,+ marginBottom: SPACING.SMALL,+ borderBottom: BORDERS.STANDARD,+ }}>+ PROFITABILITY+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: SPACING.SMALL, fontSize: TYPOGRAPHY.SMALL }}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ ...COMMON_STYLES.dataLabel }}>GROSS MARGIN</span>+ <span style={{ color: COLORS.GREEN }}>{formatPercent(stockInfo?.gross_margins)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: COLORS.GRAY }}>OPER. MARGIN:</span>+ <span style={{ color: COLORS.GREEN }}>{formatPercent(stockInfo?.operating_margins)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: COLORS.GRAY }}>PROFIT MARGIN:</span>+ <span style={{ color: COLORS.GREEN }}>{formatPercent(stockInfo?.profit_margins)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: COLORS.GRAY }}>ROA:</span>+ <span style={{ color: COLORS.CYAN }}>{formatPercent(stockInfo?.return_on_assets)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: COLORS.GRAY }}>ROE:</span>+ <span style={{ color: COLORS.CYAN }}>{formatPercent(stockInfo?.return_on_equity)}</span>+ </div>+ </div>+ </div>++ {/* Growth */}+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '6px',+ }}>+ <div style={{ color: COLORS.BLUE, fontSize: '10px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '3px' }}>+ GROWTH RATES+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', fontSize: '9px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: COLORS.GRAY }}>REVENUE:</span>+ <span style={{ color: COLORS.GREEN }}>{formatPercent(stockInfo?.revenue_growth)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: COLORS.GRAY }}>EARNINGS:</span>+ <span style={{ color: COLORS.GREEN }}>{formatPercent(stockInfo?.earnings_growth)}</span>+ </div>+ </div>+ </div>+ </div>+ </div>++ {/* Bottom Section - Company Overview & Key Info */}+ <div style={{+ display: 'grid',+ gridTemplateColumns: '2fr 1fr',+ gap: '6px',+ flex: '0 0 auto',+ minHeight: '120px',+ }}>+ {/* Company Description */}+ {stockInfo?.description && stockInfo.description !== 'N/A' && (+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '6px',+ display: 'flex',+ flexDirection: 'column',+ minHeight: 0,+ }}>+ <div style={{ color: COLORS.CYAN, fontSize: '10px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '3px', flexShrink: 0 }}>+ COMPANY OVERVIEW+ </div>+ <div style={{+ color: COLORS.WHITE,+ fontSize: '9px',+ lineHeight: '1.5',+ overflow: 'auto',+ flex: 1,+ minHeight: 0,+ }} className="custom-scrollbar">+ {stockInfo.description}+ </div>+ </div>+ )}++ {/* Company Info & Financial Health */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>+ {/* Company Info */}+ {stockInfo && (+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '6px',+ }}>+ <div style={{ color: COLORS.WHITE, fontSize: '10px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '3px' }}>+ COMPANY INFO+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '3px', fontSize: '9px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: COLORS.GRAY }}>EMPLOYEES:</span>+ <span style={{ color: COLORS.CYAN }}>{formatNumber(stockInfo.employees, 0)}</span>+ </div>+ {stockInfo.website && stockInfo.website !== 'N/A' && (+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: COLORS.GRAY }}>WEBSITE:</span>+ <span style={{ color: COLORS.BLUE, fontSize: '8px' }}>{stockInfo.website.substring(0, 25)}</span>+ </div>+ )}+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: COLORS.GRAY }}>CURRENCY:</span>+ <span style={{ color: COLORS.CYAN }}>{stockInfo.currency || 'N/A'}</span>+ </div>+ </div>+ </div>+ )}++ {/* Key Financial Health */}+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '6px',+ }}>+ <div style={{ color: COLORS.ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '6px', borderBottom: `1px solid ${COLORS.BORDER}`, paddingBottom: '3px' }}>+ FINANCIAL HEALTH+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '3px', fontSize: '9px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: COLORS.GRAY }}>CASH:</span>+ <span style={{ color: COLORS.GREEN }}>{formatLargeNumber(stockInfo?.total_cash)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: COLORS.GRAY }}>DEBT:</span>+ <span style={{ color: COLORS.RED }}>{formatLargeNumber(stockInfo?.total_debt)}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: COLORS.GRAY }}>FREE CF:</span>+ <span style={{ color: COLORS.CYAN }}>{formatLargeNumber(stockInfo?.free_cashflow)}</span>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ );+};++export default OverviewTab;diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/TechnicalsTab.tsx b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/TechnicalsTab.tsxnew file mode 100644index 000000000..cccf76592--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/TechnicalsTab.tsx@@ -0,0 +1,151 @@+import React from 'react';+import { IndicatorBox } from '../components/IndicatorBox';+import { FINCEPT } from '../../portfolio-tab/finceptStyles';+import type { HistoricalData, TechnicalsData } from '../types';++const COLORS = {+ ORANGE: FINCEPT.ORANGE,+ WHITE: FINCEPT.WHITE,+ RED: FINCEPT.RED,+ GREEN: FINCEPT.GREEN,+ YELLOW: FINCEPT.YELLOW,+ GRAY: FINCEPT.GRAY,+ BLUE: FINCEPT.BLUE,+ CYAN: FINCEPT.CYAN,+ DARK_BG: FINCEPT.DARK_BG,+ PANEL_BG: FINCEPT.PANEL_BG,+ BORDER: FINCEPT.BORDER,+ MAGENTA: '#FF00FF',+};++interface TechnicalsTabProps {+ technicalsData: TechnicalsData | null;+ technicalsLoading: boolean;+ historicalData: HistoricalData[];+}++export const TechnicalsTab: React.FC<TechnicalsTabProps> = ({+ technicalsData,+ technicalsLoading,+ historicalData,+}) => {+ if (technicalsLoading) {+ return (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '400px',+ gap: '16px',+ }}>+ <div style={{+ width: '50px',+ height: '50px',+ border: '4px solid #404040',+ borderTop: '4px solid #ea580c',+ borderRadius: '50%',+ animation: 'spin 1s linear infinite'+ }} />+ <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>+ );+ }++ if (!technicalsData) {+ return (+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '400px',+ gap: '16px',+ }}>+ <div style={{ color: COLORS.RED, fontSize: '14px', fontWeight: 'bold' }}>+ [WARN] NO TECHNICAL DATA AVAILABLE+ </div>+ <div style={{ color: COLORS.GRAY, fontSize: '11px' }}>+ Please wait for historical data to load+ </div>+ </div>+ );+ }++ // Check if we have valid indicator data+ if (!technicalsData.indicator_columns || !technicalsData.data || !Array.isArray(technicalsData.data) || technicalsData.data.length === 0) {+ return (+ <div style={{+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '16px',+ textAlign: 'center',+ color: COLORS.YELLOW,+ }}>+ <div style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>+ [WARN] NO INDICATOR DATA+ </div>+ <div style={{ fontSize: '11px', color: COLORS.GRAY }}>+ Technical indicators could not be computed. Please try again or select a different symbol.+ </div>+ </div>+ );+ }++ const renderIndicatorCategory = (indicators: string[] | undefined, color: string, category: string) => {+ if (!indicators || !Array.isArray(indicators)) return null;++ return indicators.map((indicator: string) => {+ const values = technicalsData.data.map((d: any) => d[indicator]).filter((v: any) => v != null);+ if (values.length === 0) return null;++ const latestValue = values[values.length - 1];+ const min = Math.min(...values);+ const max = Math.max(...values);+ const avg = values.reduce((a: number, b: number) => a + b, 0) / values.length;++ return (+ <IndicatorBox+ key={indicator}+ name={indicator}+ latestValue={latestValue}+ min={min}+ max={max}+ avg={avg}+ values={values}+ priceData={historicalData}+ color={color}+ category={category}+ />+ );+ });+ };++ return (+ <div style={{ padding: '8px', overflow: 'auto', height: 'calc(100vh - 280px)' }} className="custom-scrollbar">+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(420px, 1fr))', gap: '16px' }}>+ {/* Trend Indicators */}+ {renderIndicatorCategory(technicalsData.indicator_columns?.trend, COLORS.CYAN, 'TREND')}++ {/* Momentum Indicators */}+ {renderIndicatorCategory(technicalsData.indicator_columns?.momentum, COLORS.GREEN, 'MOMENTUM')}++ {/* Volatility Indicators */}+ {renderIndicatorCategory(technicalsData.indicator_columns?.volatility, COLORS.YELLOW, 'VOLATILITY')}++ {/* Volume Indicators */}+ {renderIndicatorCategory(technicalsData.indicator_columns?.volume, COLORS.BLUE, 'VOLUME')}++ {/* Others Indicators */}+ {renderIndicatorCategory(technicalsData.indicator_columns?.others, COLORS.MAGENTA, 'RETURN')}+ </div>+ </div>+ );+};++export default TechnicalsTab;diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/index.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/index.tsnew file mode 100644index 000000000..3369970e8--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/tabs/index.ts@@ -0,0 +1,5 @@+export { OverviewTab } from './OverviewTab';+export { FinancialsTab } from './FinancialsTab';+export { AnalysisTab } from './AnalysisTab';+export { TechnicalsTab } from './TechnicalsTab';+export { NewsTab } from './NewsTab';diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/types/index.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/types/index.tsindex 6a27dc967..6779a1d3c 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-research/types/index.ts+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/types/index.ts@@ -1,5 +1,130 @@// Type definitions for Equity Research module+// ===== Core Data Types =====++export interface StockInfo {+ symbol: string;+ company_name: string;+ sector: string;+ industry: string;+ market_cap: number | null;+ pe_ratio: number | null;+ forward_pe: number | null;+ dividend_yield: number | null;+ beta: number | null;+ fifty_two_week_high: number | null;+ fifty_two_week_low: number | null;+ average_volume: number | null;+ description: string;+ website: string;+ country: string;+ currency: string;+ exchange: string;+ employees: number | null;+ current_price: number | null;+ target_high_price: number | null;+ target_low_price: number | null;+ target_mean_price: number | null;+ recommendation_mean: number | null;+ recommendation_key: string | null;+ number_of_analyst_opinions: number | null;+ total_cash: number | null;+ total_debt: number | null;+ total_revenue: number | null;+ revenue_per_share: number | null;+ return_on_assets: number | null;+ return_on_equity: number | null;+ gross_profits: number | null;+ free_cashflow: number | null;+ operating_cashflow: number | null;+ earnings_growth: number | null;+ revenue_growth: number | null;+ gross_margins: number | null;+ operating_margins: number | null;+ ebitda_margins: number | null;+ profit_margins: number | null;+ book_value: number | null;+ price_to_book: number | null;+ enterprise_value: number | null;+ enterprise_to_revenue: number | null;+ enterprise_to_ebitda: number | null;+ shares_outstanding: number | null;+ float_shares: number | null;+ held_percent_insiders: number | null;+ held_percent_institutions: number | null;+ short_ratio: number | null;+ short_percent_of_float: number | null;+ peg_ratio: number | null;+}++export interface HistoricalData {+ symbol: string;+ timestamp: number;+ open: number;+ high: number;+ low: number;+ close: number;+ volume: number;+}++export interface QuoteData {+ symbol: string;+ price: number;+ change: number;+ change_percent: number;+ volume: number | null;+ high: number | null;+ low: number | null;+ open: number | null;+ previous_close: number | null;+}++export interface FinancialsData {+ symbol: string;+ income_statement: Record<string, Record<string, number>>;+ balance_sheet: Record<string, Record<string, number>>;+ cash_flow: Record<string, Record<string, number>>;+ timestamp: number;+}++export interface SearchResult {+ symbol: string;+ name: string;+ type: string;+}++export interface NewsArticle {+ title: string;+ description?: string;+ url: string;+ publisher?: string;+ published_date?: string;+}++export interface NewsData {+ success: boolean;+ error?: string;+ data: NewsArticle[];+ count?: number;+}++export interface TechnicalsData {+ success: boolean;+ data: Record<string, any>[];+ indicator_columns?: {+ trend?: string[];+ momentum?: string[];+ volatility?: string[];+ volume?: string[];+ others?: string[];+ };+}++export type ChartPeriod = '1M' | '3M' | '6M' | '1Y' | '5Y';+export type ActiveTab = 'overview' | 'financials' | 'analysis' | 'technicals' | 'peers' | 'news';++// ===== Indicator Types =====+export interface CandleData {time: number;open: number;diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/utils/formatters.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/utils/formatters.tsnew file mode 100644index 000000000..51965789b--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/utils/formatters.ts@@ -0,0 +1,63 @@+// Formatting utilities for Equity Research tab++/**+ * Format a number with specified decimal places+ */+export const formatNumber = (num: number | null | undefined, decimals = 2): string => {+ if (num === null || num === undefined) return 'N/A';+ return num.toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });+};++/**+ * Format a large number with currency prefix and abbreviations (T, B, M)+ */+export const formatLargeNumber = (num: number | null | undefined): string => {+ if (num === null || num === undefined) return 'N/A';+ if (num >= 1e12) return `$${(num / 1e12).toFixed(2)}T`;+ if (num >= 1e9) return `$${(num / 1e9).toFixed(2)}B`;+ if (num >= 1e6) return `$${(num / 1e6).toFixed(2)}M`;+ return `$${num.toFixed(2)}`;+};++/**+ * Format a decimal as a percentage+ */+export const formatPercent = (num: number | null | undefined): string => {+ if (num === null || num === undefined) return 'N/A';+ return `${(num * 100).toFixed(2)}%`;+};++/**+ * Format indicator value based on magnitude+ */+export const formatIndicatorValue = (val: number): string => {+ if (Math.abs(val) < 0.01) return val.toFixed(6);+ if (Math.abs(val) < 1) return val.toFixed(4);+ if (Math.abs(val) < 100) return val.toFixed(2);+ return val.toFixed(0);+};++/**+ * Get recommendation color based on recommendation key+ */+export const getRecommendationColor = (key: string | null, colors: { GREEN: string; RED: string; YELLOW: string; GRAY: string }): string => {+ if (!key) return colors.GRAY;+ if (key === 'buy' || key === 'strong_buy') return colors.GREEN;+ if (key === 'sell' || key === 'strong_sell') return colors.RED;+ return colors.YELLOW;+};++/**+ * Get recommendation text from key+ */+export const getRecommendationText = (key: string | null): string => {+ if (!key) return 'N/A';+ return key.toUpperCase().replace('_', ' ');+};++/**+ * Get year from period string (e.g., "2023-12-31" -> 2023)+ */+export const getYearFromPeriod = (period: string): number => {+ return new Date(period).getFullYear();+};diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/EquityTradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/EquityTradingTab.tsxindex 26af0e236..a93d7ed55 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-trading/EquityTradingTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/EquityTradingTab.tsx@@ -5,7 +5,7 @@* Supports multiple brokers across different regions with real-time market data.*/-import React, { useState, useEffect, useCallback, useMemo } from 'react';+import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';import {TrendingUp, TrendingDown, Activity, DollarSign, BarChart3,Settings as SettingsIcon, Globe, Wifi, WifiOff, Bell,@@ -18,7 +18,7 @@ import { useTranslation } from 'react-i18next';import { StockBrokerProvider, useStockBrokerContext, useStockTradingMode, useStockTradingData } from '@/contexts/StockBrokerContext';import {BrokerSelector,- BrokerSetupPanel,+ BrokersManagementPanel,StockOrderForm,PositionsPanel,HoldingsPanel,@@ -29,9 +29,13 @@ import {} from './components';import type { SymbolSearchResult, SupportedBroker } from '@/services/trading/masterContractService';-import type { StockExchange, Quote } from '@/brokers/stocks/types';+import type { StockExchange, Quote, MarketDepth } from '@/brokers/stocks/types';import { GridTradingPanel } from '../trading/grid-trading';+// Market hours and caching utilities+import { getMarketStatus, getPollingInterval, getCacheTTL, isMarketOpen, getMarketStatusMessage } from '@/services/markets/marketHoursService';+import cacheService from '@/services/cache/cacheService';+// Fincept Professional Color Paletteconst FINCEPT = {ORANGE: '#FF8800',@@ -51,14 +55,33 @@ const FINCEPT = {MUTED: '#4A4A4A'};-// Default Indian market watchlist+// NIFTY 50 Components - Full watchlist (current constituents as of Jan 2025)const DEFAULT_WATCHLIST = [- 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK',- 'HINDUNILVR', 'SBIN', 'BHARTIARTL', 'ITC', 'KOTAKBANK',- 'LT', 'AXISBANK', 'BAJFINANCE', 'MARUTI', 'ASIANPAINT',- 'HCLTECH', 'SUNPHARMA', 'TITAN', 'WIPRO', 'ULTRACEMCO',- 'NESTLEIND', 'M&M', 'TATASTEEL', 'POWERGRID', 'NTPC',- 'JSWSTEEL', 'TECHM', 'ADANIPORTS', 'DIVISLAB', 'DRREDDY'+ // Financials (Weight: ~35%)+ 'HDFCBANK', 'ICICIBANK', 'SBIN', 'KOTAKBANK', 'AXISBANK',+ 'BAJFINANCE', 'BAJAJFINSV', 'HDFCLIFE', 'SBILIFE', 'INDUSINDBK',++ // IT (Weight: ~13%)+ 'TCS', 'INFY', 'WIPRO', 'HCLTECH', 'TECHM', 'LTIM',++ // Oil & Gas / Energy (Weight: ~12%)+ 'RELIANCE', 'ONGC', 'NTPC', 'POWERGRID', 'ADANIPORTS', 'ADANIENT',++ // Auto (Weight: ~7%)+ 'MARUTI', 'TATAMOTORS', 'M&M', 'BAJAJ-AUTO', 'HEROMOTOCO', 'EICHERMOT',++ // FMCG (Weight: ~8%)+ 'HINDUNILVR', 'ITC', 'NESTLEIND', 'BRITANNIA', 'TATACONSUM',++ // Metals & Mining (Weight: ~4%)+ 'TATASTEEL', 'JSWSTEEL', 'HINDALCO', 'COALINDIA',++ // Pharma & Healthcare (Weight: ~4%)+ 'SUNPHARMA', 'DRREDDY', 'CIPLA', 'APOLLOHOSP', 'DIVISLAB',++ // Infrastructure & Others (Weight: ~17%)+ 'LT', 'BHARTIARTL', 'ULTRACEMCO', 'GRASIM', 'TITAN',+ 'ASIANPAINT', 'BPCL', 'SHRIRAMFIN', 'TRENT',];// Market indices@@ -69,7 +92,7 @@ const MARKET_INDICES = [{ symbol: 'NIFTYIT', exchange: 'NSE' as StockExchange },];-type BottomPanelTab = 'positions' | 'holdings' | 'orders' | 'history' | 'stats' | 'market' | 'grid-trading';+type BottomPanelTab = 'positions' | 'holdings' | 'orders' | 'history' | 'stats' | 'market' | 'grid-trading' | 'brokers';type LeftSidebarView = 'watchlist' | 'indices' | 'sectors';type CenterView = 'chart' | 'depth' | 'trades';type RightPanelView = 'orderbook' | 'marketdepth' | 'info';@@ -87,7 +110,7 @@ function EquityTradingContent() {isConnecting,} = useStockBrokerContext();const { mode: tradingMode, setMode: setTradingMode, isLive, isPaper } = useStockTradingMode();- const { positions, holdings, orders, funds, refreshAll, isRefreshing } = useStockTradingData();+ const { positions, holdings, orders, trades, funds, refreshAll, refreshTrades, isRefreshing } = useStockTradingData();// Time stateconst [currentTime, setCurrentTime] = useState(new Date());@@ -99,11 +122,17 @@ function EquityTradingContent() {// Quote dataconst [quote, setQuote] = useState<Quote | null>(null);+ const [marketDepth, setMarketDepth] = useState<MarketDepth | null>(null);const [wsError, setWsError] = useState<string | null>(null);+ const [isLoadingQuote, setIsLoadingQuote] = useState(false);// Watchlistconst [watchlist, setWatchlist] = useState<string[]>(DEFAULT_WATCHLIST);const [watchlistQuotes, setWatchlistQuotes] = useState<Record<string, Quote>>({});+ // Auto-set WebSocket based on market hours - ON during market hours, OFF when closed+ const [useWebSocketForWatchlist, setUseWebSocketForWatchlist] = useState<boolean>(() => {+ return isMarketOpen(selectedExchange || 'NSE');+ });// UI Stateconst [leftSidebarView, setLeftSidebarView] = useState<LeftSidebarView>('watchlist');@@ -113,8 +142,15 @@ function EquityTradingContent() {const [isBottomPanelMinimized, setIsBottomPanelMinimized] = useState(false);const [showSettings, setShowSettings] = useState(false);- // Recent trades for trades view- const [recentTrades, setRecentTrades] = useState<any[]>([]);+ // Filter trades for the selected symbol (memoized)+ const symbolTrades = useMemo(() => {+ if (!selectedSymbol || !trades || trades.length === 0) return [];+ // Filter trades for current symbol and sort by time (most recent first)+ return trades+ .filter(t => t.symbol === selectedSymbol)+ .sort((a, b) => new Date(b.tradedAt).getTime() - new Date(a.tradedAt).getTime())+ .slice(0, 50); // Keep last 50 trades+ }, [trades, selectedSymbol]);// Update clockuseEffect(() => {@@ -122,97 +158,449 @@ function EquityTradingContent() {return () => clearInterval(timer);}, []);+ // Auto-toggle WebSocket based on market hours+ // Check every minute and switch WS on when market opens, off when it closes+ useEffect(() => {+ const checkMarketStatus = () => {+ const marketOpen = isMarketOpen(selectedExchange);+ setUseWebSocketForWatchlist(prev => {+ if (prev !== marketOpen) {+ console.log(`[EquityTrading] Market ${marketOpen ? 'OPEN' : 'CLOSED'} - WebSocket ${marketOpen ? 'enabled' : 'disabled'}`);+ }+ return marketOpen;+ });+ };++ // Check immediately+ checkMarketStatus();++ // Check every minute+ const interval = setInterval(checkMarketStatus, 60 * 1000);+ return () => clearInterval(interval);+ }, [selectedExchange]);+// Set default symbol when broker changesuseEffect(() => {if (defaultSymbols.length > 0 && !selectedSymbol) {setSelectedSymbol(defaultSymbols[0]);}- // Update watchlist from broker defaults+ // Update watchlist - use broker defaults if available, otherwise use full Nifty 50if (defaultSymbols.length > 0) {- setWatchlist(defaultSymbols.slice(0, 30));+ // Use broker's default symbols (but not sliced - show all 50)+ setWatchlist(defaultSymbols.slice(0, 50));+ } else {+ // Fallback to our DEFAULT_WATCHLIST (full Nifty 50)+ setWatchlist(DEFAULT_WATCHLIST);}}, [defaultSymbols, selectedSymbol]);- // Subscribe to WebSocket for live prices+ // Subscribe to WebSocket for live prices and fetch initial datauseEffect(() => {if (!adapter || !isAuthenticated || !selectedSymbol) return;+ let isCancelled = false;+const subscribeToSymbol = async () => {try {console.log(`[EquityTrading] Subscribing to ${selectedSymbol} via WebSocket...`);+ setIsLoadingQuote(true);++ // Fetch initial quote immediately+ try {+ const initialQuote = await adapter.getQuote(selectedSymbol, selectedExchange);+ if (!isCancelled && initialQuote) {+ setQuote(initialQuote);+ console.log(`[EquityTrading] Initial quote loaded for ${selectedSymbol}:`, {+ lastPrice: initialQuote.lastPrice,+ bid: initialQuote.bid,+ ask: initialQuote.ask,+ });+ }+ } catch (quoteErr) {+ console.warn(`[EquityTrading] Failed to fetch initial quote:`, quoteErr);+ }- await adapter.subscribe(selectedSymbol, selectedExchange, 'quote');+ // Fetch initial market depth+ try {+ const initialDepth = await adapter.getMarketDepth(selectedSymbol, selectedExchange);+ if (!isCancelled && initialDepth) {+ setMarketDepth(initialDepth);+ console.log(`[EquityTrading] Initial depth loaded for ${selectedSymbol}:`, {+ bids: initialDepth.bids?.length || 0,+ asks: initialDepth.asks?.length || 0,+ });+ }+ } catch (depthErr) {+ console.warn(`[EquityTrading] Failed to fetch initial depth:`, depthErr);+ }++ setIsLoadingQuote(false);++ // Subscribe to WebSocket for live updates+ await adapter.subscribe(selectedSymbol, selectedExchange, 'full');const handleTick = (tick: any) => {- if (tick.symbol === selectedSymbol) {- setQuote({+ if (tick.symbol === selectedSymbol && !isCancelled) {+ // Update quote with tick data+ setQuote((prevQuote) => ({symbol: tick.symbol,exchange: tick.exchange,- lastPrice: tick.lastPrice || tick.price,- open: tick.open || tick.lastPrice,- high: tick.high || tick.lastPrice,- low: tick.low || tick.lastPrice,- close: tick.close || tick.lastPrice,- previousClose: tick.close || tick.lastPrice,- volume: tick.volume || 0,- change: tick.change || 0,- changePercent: tick.changePercent || 0,- bid: tick.bid || 0,- bidQty: tick.bidQty || 0,- ask: tick.ask || 0,- askQty: tick.askQty || 0,+ lastPrice: tick.lastPrice || tick.price || prevQuote?.lastPrice || 0,+ open: tick.open || prevQuote?.open || tick.lastPrice,+ high: tick.high || prevQuote?.high || tick.lastPrice,+ low: tick.low || prevQuote?.low || tick.lastPrice,+ close: tick.close || prevQuote?.close || tick.lastPrice,+ previousClose: tick.previousClose || prevQuote?.previousClose || tick.close || tick.lastPrice,+ volume: tick.volume ?? prevQuote?.volume ?? 0,+ change: tick.change ?? prevQuote?.change ?? 0,+ changePercent: tick.changePercent ?? prevQuote?.changePercent ?? 0,+ // Update bid/ask from tick or preserve previous values+ bid: tick.bid || prevQuote?.bid || 0,+ bidQty: tick.bidQty || prevQuote?.bidQty || 0,+ ask: tick.ask || prevQuote?.ask || 0,+ askQty: tick.askQty || prevQuote?.askQty || 0,timestamp: Date.now(),+ }));++ // Also update market depth if tick includes depth data+ if (tick.depth && (tick.depth.bids?.length > 0 || tick.depth.asks?.length > 0)) {+ setMarketDepth({+ bids: tick.depth.bids || [],+ asks: tick.depth.asks || [],+ });+ }+ }+ };++ const handleDepth = (depth: any) => {+ if (depth.symbol === selectedSymbol && !isCancelled) {+ setMarketDepth({+ bids: depth.bids || [],+ asks: depth.asks || [],});++ // Also update quote's bid/ask from depth data (best bid/ask)+ const bestBid = depth.bids?.[0];+ const bestAsk = depth.asks?.[0];+ if (bestBid || bestAsk) {+ setQuote((prevQuote) => {+ if (!prevQuote) return prevQuote;+ return {+ ...prevQuote,+ bid: bestBid?.price || prevQuote.bid,+ bidQty: bestBid?.quantity || prevQuote.bidQty,+ ask: bestAsk?.price || prevQuote.ask,+ askQty: bestAsk?.quantity || prevQuote.askQty,+ };+ });+ }}};adapter.onTick(handleTick);+ adapter.onDepth(handleDepth);setWsError(null);} catch (err: any) {console.error('[EquityTrading] WebSocket subscription failed:', err);setWsError(err.message);+ setIsLoadingQuote(false);}};subscribeToSymbol();return () => {+ isCancelled = true;if (adapter && selectedSymbol) {adapter.unsubscribe(selectedSymbol, selectedExchange).catch(console.error);}};}, [adapter, isAuthenticated, selectedSymbol, selectedExchange]);- // Fetch watchlist quotes periodically+ // Subscribe to watchlist via WebSocket for real-time updatesuseEffect(() => {- if (!adapter || !isAuthenticated) return;+ if (!adapter || !isAuthenticated || !useWebSocketForWatchlist) return;- const fetchWatchlistQuotes = async () => {- try {- const quotes: Record<string, Quote> = {};- // Batch fetch quotes for watchlist- for (const symbol of watchlist.slice(0, 15)) {- try {- const q = await adapter.getQuote(symbol, selectedExchange);- if (q) {- quotes[symbol] = q;+ let isCancelled = false;+ const subscribedSymbols: string[] = [];++ const subscribeWatchlist = async () => {+ console.log('[EquityTrading] Subscribing to watchlist via WebSocket...');++ // Handle incoming ticks for watchlist symbols+ const handleWatchlistTick = (tick: any) => {+ if (watchlist.includes(tick.symbol) && !isCancelled) {+ setWatchlistQuotes(prev => ({+ ...prev,+ [tick.symbol]: {+ symbol: tick.symbol,+ exchange: tick.exchange || selectedExchange,+ lastPrice: tick.lastPrice || tick.price,+ open: tick.open || prev[tick.symbol]?.open || 0,+ high: tick.high || prev[tick.symbol]?.high || tick.lastPrice,+ low: tick.low || prev[tick.symbol]?.low || tick.lastPrice,+ close: tick.close || prev[tick.symbol]?.close || tick.lastPrice,+ previousClose: tick.previousClose || prev[tick.symbol]?.previousClose || tick.close || tick.lastPrice,+ volume: tick.volume || prev[tick.symbol]?.volume || 0,+ change: tick.change || 0,+ changePercent: tick.changePercent || 0,+ bid: tick.bid || prev[tick.symbol]?.bid || 0,+ bidQty: tick.bidQty || prev[tick.symbol]?.bidQty || 0,+ ask: tick.ask || prev[tick.symbol]?.ask || 0,+ askQty: tick.askQty || prev[tick.symbol]?.askQty || 0,+ timestamp: tick.timestamp || Date.now(),}+ }));+ }+ };++ // Register tick handler+ adapter.onTick(handleWatchlistTick);++ // Subscribe to all watchlist symbols in batches+ const BATCH_SIZE = 10;+ const BATCH_DELAY = 500; // 500ms between subscription batches++ for (let i = 0; i < watchlist.length && !isCancelled; i += BATCH_SIZE) {+ const batch = watchlist.slice(i, i + BATCH_SIZE);++ for (const symbol of batch) {+ if (isCancelled) break;+ try {+ await adapter.subscribe(symbol, selectedExchange, 'quote');+ subscribedSymbols.push(symbol);} catch (err) {- // Skip individual quote errors+ console.warn(`[EquityTrading] Failed to subscribe to ${symbol}:`, err);}}- if (Object.keys(quotes).length > 0) {- setWatchlistQuotes(quotes);++ // Small delay between batches+ if (i + BATCH_SIZE < watchlist.length && !isCancelled) {+ await new Promise(resolve => setTimeout(resolve, BATCH_DELAY));+ }+ }++ console.log(`[EquityTrading] Subscribed to ${subscribedSymbols.length} watchlist symbols via WebSocket`);++ // Store the tick handler for cleanup+ return handleWatchlistTick;+ };++ let tickHandler: ((tick: any) => void) | undefined;++ subscribeWatchlist().then(handler => {+ tickHandler = handler;+ }).catch(err => {+ console.error('[EquityTrading] WebSocket watchlist subscription failed:', err);+ });++ return () => {+ isCancelled = true;++ // Unsubscribe from all watchlist symbols+ if (tickHandler) {+ adapter.offTick(tickHandler);+ }++ // Unsubscribe symbols (but not the selected symbol)+ for (const symbol of subscribedSymbols) {+ if (symbol !== selectedSymbol) {+ adapter.unsubscribe(symbol, selectedExchange).catch(() => {});+ }+ }+ };+ }, [adapter, isAuthenticated, watchlist, selectedExchange, useWebSocketForWatchlist, selectedSymbol]);++ // Fallback: Fetch watchlist quotes via REST if WebSocket is disabled+ // Uses smart polling based on market hours - polls frequently when open, uses cache when closed+ useEffect(() => {+ if (!adapter || !isAuthenticated || useWebSocketForWatchlist) return;++ let isCancelled = false;+ let isPolling = false;+ let pollingIntervalId: ReturnType<typeof setInterval> | null = null;+ let hasFetchedInitial = false;++ const fetchWatchlistQuotes = async (useCache = false) => {+ if (isCancelled || isPolling) return;++ const marketOpen = isMarketOpen(selectedExchange);+ const cacheKey = `watchlist:quotes:${selectedExchange}:${watchlist.slice(0, 5).join('-')}`;++ // If market is closed and we already fetched, skip polling (use cached data)+ if (!marketOpen && hasFetchedInitial && useCache) {+ console.log('[EquityTrading] Market closed, using cached watchlist data');+ return;+ }++ isPolling = true;++ try {+ // Try to get from cache first when market is closed+ if (!marketOpen) {+ const cached = await cacheService.get<Record<string, Quote>>(cacheKey);+ if (cached && !cached.isStale) {+ setWatchlistQuotes(prev => ({ ...prev, ...cached.data }));+ console.log('[EquityTrading] ✓ Loaded watchlist from cache (market closed)');+ hasFetchedInitial = true;+ return;+ }+ }++ console.log(`[EquityTrading] Fetching watchlist quotes (market ${marketOpen ? 'OPEN' : 'CLOSED'})...`);++ const quotes = await adapter.getQuotes(+ watchlist.map(s => ({ symbol: s, exchange: selectedExchange }))+ );++ if (quotes && quotes.length > 0 && !isCancelled) {+ const newQuotes: Record<string, Quote> = {};+ quotes.forEach(q => {+ newQuotes[q.symbol] = q;+ });+ setWatchlistQuotes(prev => ({ ...prev, ...newQuotes }));++ // Cache the quotes with TTL based on market status+ const ttl = getCacheTTL(selectedExchange);+ await cacheService.set(cacheKey, newQuotes, 'market-quotes', ttl);++ console.log(`[EquityTrading] ✓ Received ${quotes.length} watchlist quotes`);+ hasFetchedInitial = true;}} catch (err) {console.error('[EquityTrading] Failed to fetch watchlist quotes:', err);+ } finally {+ isPolling = false;}};- fetchWatchlistQuotes();- const interval = setInterval(fetchWatchlistQuotes, 30000);- return () => clearInterval(interval);- }, [adapter, isAuthenticated, watchlist, selectedExchange]);+ // Get polling interval based on market hours+ const interval = getPollingInterval(selectedExchange);+ const marketStatus = getMarketStatus(selectedExchange);++ console.log(`[EquityTrading] Watchlist poll interval: ${interval / 1000}s (${marketStatus.status})`);++ // Initial fetch after 3 seconds+ const initialTimeout = setTimeout(() => {+ fetchWatchlistQuotes(false);+ }, 3000);++ // Setup polling interval+ pollingIntervalId = setInterval(() => {+ fetchWatchlistQuotes(true);+ }, interval);++ return () => {+ isCancelled = true;+ clearTimeout(initialTimeout);+ if (pollingIntervalId) {+ clearInterval(pollingIntervalId);+ }+ };+ }, [adapter, isAuthenticated, watchlist, selectedExchange, useWebSocketForWatchlist]);++ // Smart polling for selected symbol's quote and depth data+ // Polls based on market hours - more frequently when open, uses cache when closed+ useEffect(() => {+ if (!adapter || !isAuthenticated || !selectedSymbol) return;++ let isCancelled = false;+ let isPolling = false;+ let pollingIntervalId: ReturnType<typeof setInterval> | null = null;+ let hasFetchedInitial = false;++ const fetchQuoteAndDepth = async (useCache = false) => {+ if (isCancelled || isPolling) return;++ const marketOpen = isMarketOpen(selectedExchange);+ const quoteCacheKey = `quote:${selectedExchange}:${selectedSymbol}`;+ const depthCacheKey = `depth:${selectedExchange}:${selectedSymbol}`;++ // If market is closed and we already fetched, skip polling+ if (!marketOpen && hasFetchedInitial && useCache) {+ console.log(`[EquityTrading] Market closed, skipping poll for ${selectedSymbol}`);+ return;+ }++ isPolling = true;++ try {+ // Try cache first when market is closed+ if (!marketOpen) {+ const [cachedQuote, cachedDepth] = await Promise.all([+ cacheService.get<Quote>(quoteCacheKey),+ cacheService.get<MarketDepth>(depthCacheKey),+ ]);++ if (cachedQuote && !cachedQuote.isStale) {+ setQuote(cachedQuote.data);+ console.log(`[EquityTrading] ✓ Loaded ${selectedSymbol} quote from cache`);+ }+ if (cachedDepth && !cachedDepth.isStale) {+ setMarketDepth(cachedDepth.data);+ console.log(`[EquityTrading] ✓ Loaded ${selectedSymbol} depth from cache`);+ }++ // If both are cached and fresh, skip fetch+ if (cachedQuote && !cachedQuote.isStale && cachedDepth && !cachedDepth.isStale) {+ hasFetchedInitial = true;+ return;+ }+ }++ console.log(`[EquityTrading] Polling ${selectedSymbol} (market ${marketOpen ? 'OPEN' : 'CLOSED'})...`);++ // Fetch quote and depth in parallel+ const [freshQuote, freshDepth] = await Promise.all([+ adapter.getQuote(selectedSymbol, selectedExchange).catch(() => null),+ adapter.getMarketDepth(selectedSymbol, selectedExchange).catch(() => null),+ ]);++ const ttl = getCacheTTL(selectedExchange);++ if (freshQuote && !isCancelled) {+ setQuote(freshQuote);+ await cacheService.set(quoteCacheKey, freshQuote, 'market-quotes', ttl);+ }++ if (freshDepth && !isCancelled) {+ setMarketDepth(freshDepth);+ await cacheService.set(depthCacheKey, freshDepth, 'market-quotes', ttl);+ console.log(`[EquityTrading] ✓ Depth updated: ${freshDepth.bids?.length || 0} bids, ${freshDepth.asks?.length || 0} asks`);+ }++ hasFetchedInitial = true;+ } catch (err) {+ console.error(`[EquityTrading] Failed to poll ${selectedSymbol}:`, err);+ } finally {+ isPolling = false;+ }+ };++ // Get polling interval based on market hours+ const interval = getPollingInterval(selectedExchange);+ const marketStatus = getMarketStatus(selectedExchange);++ console.log(`[EquityTrading] ${selectedSymbol} poll interval: ${interval / 1000}s (${marketStatus.status})`);++ // Initial fetch after a short delay (let WebSocket subscription settle first)+ const initialTimeout = setTimeout(() => {+ fetchQuoteAndDepth(false);+ }, 5000);++ // Setup polling interval+ pollingIntervalId = setInterval(() => {+ fetchQuoteAndDepth(true);+ }, interval);++ return () => {+ isCancelled = true;+ clearTimeout(initialTimeout);+ if (pollingIntervalId) {+ clearInterval(pollingIntervalId);+ }+ };+ }, [adapter, isAuthenticated, selectedSymbol, selectedExchange]);// Select symbol from search (supports both legacy search and master contract search)const handleSelectSymbol = (symbol: string, exchange: StockExchange, result?: SymbolSearchResult) => {@@ -234,8 +622,13 @@ function EquityTradingContent() {const currentPrice = quote?.lastPrice || 0;const priceChange = quote?.change || 0;const priceChangePercent = quote?.changePercent || 0;- const spread = quote ? (quote.ask - quote.bid) : 0;- const spreadPercent = quote && quote.bid > 0 ? (spread / quote.bid) * 100 : 0;+ // Spread = Ask - Bid (only calculate if both values are valid and positive)+ const spread = (quote?.ask && quote?.bid && quote.ask > 0 && quote.bid > 0)+ ? (quote.ask - quote.bid)+ : 0;+ const spreadPercent = (spread > 0 && quote?.bid && quote.bid > 0)+ ? (spread / quote.bid) * 100+ : 0;const dayRange = quote ? (quote.high - quote.low) : 0;const dayRangePercent = quote && quote.low > 0 ? (dayRange / quote.low) * 100 : 0;@@ -317,67 +710,51 @@ function EquityTradingContent() {<div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />- {/* Trading Mode Toggle - PROMINENT INDICATOR */}+ {/* Trading Mode Toggle */}<div style={{display: 'flex',alignItems: 'center',- gap: '8px',- padding: '4px 12px',- backgroundColor: isLive ? `${FINCEPT.RED}20` : `${FINCEPT.GREEN}20`,- border: `2px solid ${isLive ? FINCEPT.RED : FINCEPT.GREEN}`,- borderRadius: '4px'+ gap: '2px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ padding: '2px',}}>- {/* Mode Indicator */}- <div style={{- display: 'flex',- alignItems: 'center',- gap: '6px'- }}>- <div style={{- width: '8px',- height: '8px',- borderRadius: '50%',- backgroundColor: isLive ? FINCEPT.RED : FINCEPT.GREEN,- boxShadow: `0 0 8px ${isLive ? FINCEPT.RED : FINCEPT.GREEN}`,- animation: isLive ? 'pulse 1s infinite' : 'none'- }} />- <span style={{- fontSize: '11px',- fontWeight: 700,- color: isLive ? FINCEPT.RED : FINCEPT.GREEN,- letterSpacing: '1px'- }}>- {isLive ? '🔴 LIVE' : '⚪ PAPER'}- </span>- </div>-- <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />-<buttononClick={() => setTradingMode('paper')}style={{- padding: '4px 10px',- backgroundColor: isPaper ? FINCEPT.GREEN : FINCEPT.PANEL_BG,- border: `1px solid ${isPaper ? FINCEPT.GREEN : FINCEPT.BORDER}`,+ padding: '6px 14px',+ backgroundColor: isPaper ? FINCEPT.GREEN : 'transparent',+ border: 'none',color: isPaper ? FINCEPT.DARK_BG : FINCEPT.GRAY,cursor: 'pointer',fontSize: '10px',fontWeight: 700,- transition: 'all 0.2s'+ letterSpacing: '0.5px',+ transition: 'all 0.2s',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',}}>+ {isPaper && (+ <div style={{+ width: '6px',+ height: '6px',+ borderRadius: '50%',+ backgroundColor: FINCEPT.DARK_BG,+ }} />+ )}PAPER</button><buttononClick={() => {- // Require confirmation before switching to live modeif (!isLive) {const confirmed = window.confirm(- '⚠️ WARNING: SWITCHING TO LIVE TRADING ⚠️\n\n' ++ 'WARNING: SWITCHING TO LIVE TRADING\n\n' +'You are about to enable LIVE trading mode.\n\n' +- '• All orders will be placed with REAL funds\n' +- '• Trades will be executed on the actual exchange\n' +- '• You may lose money\n\n' ++ '- All orders will be placed with REAL funds\n' ++ '- Trades will be executed on the actual exchange\n' ++ '- You may lose money\n\n' +'Are you sure you want to continue?');if (confirmed) {@@ -386,16 +763,30 @@ function EquityTradingContent() {}}}style={{- padding: '4px 10px',- backgroundColor: isLive ? FINCEPT.RED : FINCEPT.PANEL_BG,- border: `1px solid ${isLive ? FINCEPT.RED : FINCEPT.BORDER}`,+ padding: '6px 14px',+ backgroundColor: isLive ? FINCEPT.RED : 'transparent',+ border: 'none',color: isLive ? FINCEPT.WHITE : FINCEPT.GRAY,cursor: 'pointer',fontSize: '10px',fontWeight: 700,- transition: 'all 0.2s'+ letterSpacing: '0.5px',+ transition: 'all 0.2s',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',}}>+ {isLive && (+ <div style={{+ width: '6px',+ height: '6px',+ borderRadius: '50%',+ backgroundColor: FINCEPT.WHITE,+ boxShadow: `0 0 6px ${FINCEPT.WHITE}`,+ animation: 'pulse 1s infinite',+ }} />+ )}LIVE</button></div>@@ -615,6 +1006,39 @@ function EquityTradingContent() {))}</div>+ {/* WebSocket Toggle for Watchlist */}+ {leftSidebarView === 'watchlist' && (+ <div style={{+ padding: '4px 8px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ {useWebSocketForWatchlist ? '⚡ REALTIME' : '🔄 POLLING'}+ </span>+ <button+ onClick={() => setUseWebSocketForWatchlist(!useWebSocketForWatchlist)}+ style={{+ padding: '3px 8px',+ backgroundColor: useWebSocketForWatchlist ? FINCEPT.GREEN : FINCEPT.MUTED,+ border: 'none',+ color: useWebSocketForWatchlist ? FINCEPT.DARK_BG : FINCEPT.WHITE,+ cursor: 'pointer',+ fontSize: '8px',+ fontWeight: 700,+ borderRadius: '2px',+ transition: 'all 0.2s',+ }}+ title={useWebSocketForWatchlist ? 'Switch to REST polling' : 'Switch to WebSocket real-time'}+ >+ {useWebSocketForWatchlist ? 'WS ON' : 'WS OFF'}+ </button>+ </div>+ )}+{/* Content */}<div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>{leftSidebarView === 'watchlist' && (@@ -672,7 +1096,7 @@ function EquityTradingContent() {{symbol}</div>- {q ? (+ {q && q.lastPrice != null ? (<div style={{display: 'flex',flexDirection: 'column',@@ -692,11 +1116,11 @@ function EquityTradingContent() {</div><div style={{fontSize: '9px',- color: q.changePercent >= 0 ? FINCEPT.GREEN : FINCEPT.RED,+ color: (q.changePercent ?? 0) >= 0 ? FINCEPT.GREEN : FINCEPT.RED,fontFamily: 'monospace',fontWeight: 700}}>- {q.changePercent >= 0 ? '▲' : '▼'} {Math.abs(q.changePercent).toFixed(2)}%+ {(q.changePercent ?? 0) >= 0 ? '▲' : '▼'} {Math.abs(q.changePercent ?? 0).toFixed(2)}%</div></div>) : (@@ -912,34 +1336,43 @@ function EquityTradingContent() {)}{centerView === 'trades' && (<div style={{ width: '100%', height: '100%', overflow: 'auto', padding: '8px' }}>- {recentTrades.length === 0 ? (+ {symbolTrades.length === 0 ? (<div style={{padding: '40px',textAlign: 'center',color: FINCEPT.GRAY,fontSize: '11px'}}>- No recent trades+ No recent trades for {selectedSymbol || 'selected symbol'}</div>) : (<table style={{ width: '100%', fontSize: '10px', borderCollapse: 'collapse' }}><thead><tr style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}><th style={{ padding: '6px', textAlign: 'left', color: FINCEPT.GRAY }}>TIME</th>+ <th style={{ padding: '6px', textAlign: 'left', color: FINCEPT.GRAY }}>SIDE</th><th style={{ padding: '6px', textAlign: 'right', color: FINCEPT.GRAY }}>PRICE</th><th style={{ padding: '6px', textAlign: 'right', color: FINCEPT.GRAY }}>QTY</th></tr></thead><tbody>- {recentTrades.slice(0, 20).map((trade, idx) => (- <tr key={idx} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}40` }}>+ {symbolTrades.slice(0, 20).map((trade, idx) => (+ <tr key={trade.tradeId || idx} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}40` }}><td style={{ padding: '4px 6px', color: FINCEPT.GRAY, fontSize: '9px' }}>- {new Date(trade.timestamp).toLocaleTimeString()}+ {new Date(trade.tradedAt).toLocaleTimeString()}+ </td>+ <td style={{+ padding: '4px 6px',+ color: trade.side === 'BUY' ? FINCEPT.GREEN : FINCEPT.RED,+ fontWeight: 600,+ fontSize: '9px'+ }}>+ {trade.side}</td><td style={{padding: '4px 6px',textAlign: 'right',- color: trade.side === 'buy' ? FINCEPT.GREEN : FINCEPT.RED+ color: trade.side === 'BUY' ? FINCEPT.GREEN : FINCEPT.RED}}>₹{trade.price?.toFixed(2)}</td>@@ -956,11 +1389,11 @@ function EquityTradingContent() {</div></div>- {/* Bottom Panel - Positions/Holdings/Orders - Compact by default */}+ {/* Bottom Panel - Positions/Holdings/Orders - Compact by default, larger for brokers */}<div style={{- flex: isBottomPanelMinimized ? '0 0 32px' : '0 0 200px',- minHeight: isBottomPanelMinimized ? '32px' : '150px',- maxHeight: isBottomPanelMinimized ? '32px' : '220px',+ flex: isBottomPanelMinimized ? '0 0 32px' : activeBottomTab === 'brokers' ? '0 0 350px' : '0 0 200px',+ minHeight: isBottomPanelMinimized ? '32px' : activeBottomTab === 'brokers' ? '300px' : '150px',+ maxHeight: isBottomPanelMinimized ? '32px' : activeBottomTab === 'brokers' ? '450px' : '220px',display: 'flex',flexDirection: 'column',overflow: 'hidden',@@ -983,6 +1416,7 @@ function EquityTradingContent() {{ id: 'history', label: 'HISTORY', count: null },{ id: 'stats', label: 'STATS', count: null },{ id: 'grid-trading', label: 'GRID BOT', count: null },+ { id: 'brokers', label: 'BROKERS', count: null },] as const).map((tab) => (<buttonkey={tab.id}@@ -1119,6 +1553,13 @@ function EquityTradingContent() {/></div>)}++ {/* Brokers Management Tab */}+ {activeBottomTab === 'brokers' && (+ <div style={{ height: '100%', overflow: 'hidden' }}>+ <BrokersManagementPanel />+ </div>+ )}</div>)}</div>@@ -1156,7 +1597,39 @@ function EquityTradingContent() {</div><div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>{!isAuthenticated ? (- <BrokerSetupPanel />+ <div style={{+ display: 'flex',+ flexDirection: 'column',+ alignItems: 'center',+ justifyContent: 'center',+ height: '100%',+ gap: '12px',+ textAlign: 'center',+ }}>+ <AlertCircle size={32} color={FINCEPT.ORANGE} />+ <div>+ <p style={{ color: FINCEPT.WHITE, fontSize: '12px', fontWeight: 600, margin: '0 0 4px 0' }}>+ No Broker Connected+ </p>+ <p style={{ color: FINCEPT.GRAY, fontSize: '10px', margin: 0 }}>+ Configure your broker in the BROKERS tab below+ </p>+ </div>+ <button+ onClick={() => setActiveBottomTab('brokers')}+ style={{+ padding: '8px 16px',+ backgroundColor: FINCEPT.ORANGE,+ border: 'none',+ color: FINCEPT.DARK_BG,+ fontSize: '10px',+ fontWeight: 700,+ cursor: 'pointer',+ }}+ >+ CONNECT BROKER+ </button>+ </div>) : (<StockOrderFormsymbol={selectedSymbol}@@ -1225,11 +1698,20 @@ function EquityTradingContent() {</tr></thead><tbody>- {[1, 2, 3, 4, 5].map((i) => (+ {(marketDepth?.bids && marketDepth.bids.length > 0+ ? marketDepth.bids.slice(0, 5)+ : [null, null, null, null, null]+ ).map((bid, i) => (<tr key={i} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}40` }}>- <td style={{ padding: '4px', color: FINCEPT.WHITE }}>--</td>- <td style={{ padding: '4px', textAlign: 'right', color: FINCEPT.GREEN }}>--</td>- <td style={{ padding: '4px', textAlign: 'right', color: FINCEPT.GRAY }}>--</td>+ <td style={{ padding: '4px', color: FINCEPT.WHITE }}>+ {bid?.quantity ? bid.quantity.toLocaleString('en-IN') : '--'}+ </td>+ <td style={{ padding: '4px', textAlign: 'right', color: FINCEPT.GREEN }}>+ {bid?.price ? `₹${bid.price.toFixed(2)}` : '--'}+ </td>+ <td style={{ padding: '4px', textAlign: 'right', color: FINCEPT.GRAY }}>+ {bid?.orders || '--'}+ </td></tr>))}</tbody>@@ -1264,11 +1746,20 @@ function EquityTradingContent() {</tr></thead><tbody>- {[1, 2, 3, 4, 5].map((i) => (+ {(marketDepth?.asks && marketDepth.asks.length > 0+ ? marketDepth.asks.slice(0, 5)+ : [null, null, null, null, null]+ ).map((ask, i) => (<tr key={i} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}40` }}>- <td style={{ padding: '4px', color: FINCEPT.RED }}>--</td>- <td style={{ padding: '4px', textAlign: 'right', color: FINCEPT.WHITE }}>--</td>- <td style={{ padding: '4px', textAlign: 'right', color: FINCEPT.GRAY }}>--</td>+ <td style={{ padding: '4px', color: FINCEPT.RED }}>+ {ask?.price ? `₹${ask.price.toFixed(2)}` : '--'}+ </td>+ <td style={{ padding: '4px', textAlign: 'right', color: FINCEPT.WHITE }}>+ {ask?.quantity ? ask.quantity.toLocaleString('en-IN') : '--'}+ </td>+ <td style={{ padding: '4px', textAlign: 'right', color: FINCEPT.GRAY }}>+ {ask?.orders || '--'}+ </td></tr>))}</tbody>@@ -1281,16 +1772,105 @@ function EquityTradingContent() {<div style={{height: '100%',display: 'flex',- alignItems: 'center',- justifyContent: 'center',flexDirection: 'column',- gap: '12px'+ gap: '8px'}}>- <Layers size={48} color={FINCEPT.GRAY} />- <span style={{ fontSize: '12px', color: FINCEPT.GRAY }}>Market Depth</span>- <span style={{ fontSize: '10px', color: FINCEPT.MUTED, textAlign: 'center' }}>- Connect to broker for<br />real-time depth visualization- </span>+ {marketDepth && (marketDepth.bids?.length > 0 || marketDepth.asks?.length > 0) ? (+ <>+ {/* Depth Chart Visualization */}+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: '4px' }}>+ {/* Bid depth bars */}+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', gap: '2px' }}>+ {marketDepth.bids?.slice(0, 5).reverse().map((bid, i) => {+ const maxQty = Math.max(+ ...marketDepth.bids.slice(0, 5).map(b => b.quantity),+ ...marketDepth.asks.slice(0, 5).map(a => a.quantity)+ );+ const widthPercent = (bid.quantity / maxQty) * 100;+ return (+ <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '4px', height: '20px' }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GREEN, width: '60px', textAlign: 'right' }}>+ ₹{bid.price.toFixed(2)}+ </span>+ <div style={{ flex: 1, height: '16px', backgroundColor: FINCEPT.PANEL_BG, position: 'relative' }}>+ <div style={{+ position: 'absolute',+ right: 0,+ height: '100%',+ width: `${widthPercent}%`,+ backgroundColor: `${FINCEPT.GREEN}40`,+ borderRight: `2px solid ${FINCEPT.GREEN}`,+ }} />+ </div>+ <span style={{ fontSize: '9px', color: FINCEPT.WHITE, width: '50px' }}>+ {bid.quantity.toLocaleString('en-IN')}+ </span>+ </div>+ );+ })}+ </div>++ {/* Spread line */}+ <div style={{+ padding: '4px 8px',+ backgroundColor: FINCEPT.HEADER_BG,+ textAlign: 'center',+ fontSize: '9px',+ color: FINCEPT.YELLOW,+ borderTop: `1px solid ${FINCEPT.BORDER}`,+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}>+ Spread: {spread > 0 ? `₹${spread.toFixed(2)}` : '--'}+ </div>++ {/* Ask depth bars */}+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: '2px' }}>+ {marketDepth.asks?.slice(0, 5).map((ask, i) => {+ const maxQty = Math.max(+ ...marketDepth.bids.slice(0, 5).map(b => b.quantity),+ ...marketDepth.asks.slice(0, 5).map(a => a.quantity)+ );+ const widthPercent = (ask.quantity / maxQty) * 100;+ return (+ <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '4px', height: '20px' }}>+ <span style={{ fontSize: '9px', color: FINCEPT.RED, width: '60px', textAlign: 'right' }}>+ ₹{ask.price.toFixed(2)}+ </span>+ <div style={{ flex: 1, height: '16px', backgroundColor: FINCEPT.PANEL_BG, position: 'relative' }}>+ <div style={{+ position: 'absolute',+ left: 0,+ height: '100%',+ width: `${widthPercent}%`,+ backgroundColor: `${FINCEPT.RED}40`,+ borderLeft: `2px solid ${FINCEPT.RED}`,+ }} />+ </div>+ <span style={{ fontSize: '9px', color: FINCEPT.WHITE, width: '50px' }}>+ {ask.quantity.toLocaleString('en-IN')}+ </span>+ </div>+ );+ })}+ </div>+ </div>+ </>+ ) : (+ <div style={{+ height: '100%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ flexDirection: 'column',+ gap: '12px'+ }}>+ <Layers size={48} color={FINCEPT.GRAY} />+ <span style={{ fontSize: '12px', color: FINCEPT.GRAY }}>Market Depth</span>+ <span style={{ fontSize: '10px', color: FINCEPT.MUTED, textAlign: 'center' }}>+ {isLoadingQuote ? 'Loading depth data...' : 'Select a symbol to view depth'}+ </span>+ </div>+ )}</div>)}diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokersManagementPanel.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokersManagementPanel.tsxnew file mode 100644index 000000000..94a46544a--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/BrokersManagementPanel.tsx@@ -0,0 +1,988 @@+/**+ * Brokers Management Panel+ *+ * A unified panel to manage stock broker connections:+ * - View all available brokers with connection status+ * - Configure API credentials+ * - Authenticate via OAuth+ * - Check token expiry and re-authenticate+ */++import React, { useState, useEffect, useMemo } from 'react';+import {+ Settings,+ CheckCircle2,+ XCircle,+ AlertTriangle,+ ExternalLink,+ Eye,+ EyeOff,+ Save,+ LogOut,+ RefreshCw,+ Loader2,+ Clock,+ Globe,+ Zap,+ ChevronRight,+ Search,+ Key,+} from 'lucide-react';+import { open } from '@tauri-apps/plugin-shell';+import {+ useStockBrokerContext,+ useStockBrokerSelection,+ useStockBrokerAuth,+} from '@/contexts/StockBrokerContext';+import { createStockBrokerAdapter } from '@/brokers/stocks';+import type { BrokerCredentials, StockBrokerMetadata, Region } from '@/brokers/stocks/types';++// Fincept color palette+const COLORS = {+ ORANGE: '#FF8800',+ GREEN: '#00D66F',+ RED: '#FF3B3B',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+ BLUE: '#0088FF',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ CARD_BG: '#141414',+ BORDER: '#2A2A2A',+ GRAY: '#787878',+ MUTED: '#4A4A4A',+ WHITE: '#FFFFFF',+};++type ConnectionStatus = 'connected' | 'expired' | 'configured' | 'not_configured';++interface BrokerStatus {+ brokerId: string;+ metadata: StockBrokerMetadata;+ status: ConnectionStatus;+ lastAuthTime?: Date;+ hasCredentials: boolean;+}++// API credential URLs for brokers+const API_KEYS_URLS: Record<string, string> = {+ zerodha: 'https://developers.kite.trade/',+ fyers: 'https://myapi.fyers.in/dashboard',+ angelone: 'https://smartapi.angelbroking.com/publisher-login',+ angel: 'https://smartapi.angelbroking.com/',+ dhan: 'https://dhanhq.co/api',+ upstox: 'https://upstox.com/developer/api/',+ kotak: 'https://napi.kotaksecurities.com/devportal/',+ saxobank: 'https://www.developer.saxo/openapi/appmanagement',+ alpaca: 'https://app.alpaca.markets/brokerage/new-account',+ ibkr: 'https://www.interactivebrokers.com/en/trading/ib-api.php',+ tradier: 'https://developer.tradier.com/',+};++// Region labels+const REGION_LABELS: Record<Region, string> = {+ india: 'India',+ us: 'United States',+ europe: 'Europe',+ uk: 'United Kingdom',+ asia: 'Asia Pacific',+ australia: 'Australia',+ canada: 'Canada',+};++export function BrokersManagementPanel() {+ const { availableBrokers, activeBroker, setActiveBroker, adapter, tradingMode } = useStockBrokerContext();+ const { isAuthenticated, authenticate, logout, getAuthUrl, isConnecting, error, clearError } = useStockBrokerAuth();++ // UI State+ const [selectedBrokerId, setSelectedBrokerId] = useState<string | null>(activeBroker);+ const [searchQuery, setSearchQuery] = useState('');+ const [selectedRegion, setSelectedRegion] = useState<Region | 'all'>('all');+ const [showConfigPanel, setShowConfigPanel] = useState(false);++ // Config State+ const [showSecret, setShowSecret] = useState(false);+ const [config, setConfig] = useState<BrokerCredentials>({ apiKey: '', apiSecret: '' });+ const [isSaving, setIsSaving] = useState(false);+ const [saveSuccess, setSaveSuccess] = useState(false);+ const [configError, setConfigError] = useState<string | null>(null);++ // Auth State+ const [callbackUrl, setCallbackUrl] = useState('');+ const [showCallbackInput, setShowCallbackInput] = useState(false);+ const [isCheckingToken, setIsCheckingToken] = useState(false);++ // Get broker statuses+ const [brokerStatuses, setBrokerStatuses] = useState<Map<string, BrokerStatus>>(new Map());++ // Selected broker metadata+ const selectedBroker = useMemo(() => {+ return availableBrokers.find(b => b.id === selectedBrokerId) || null;+ }, [availableBrokers, selectedBrokerId]);++ // Filter brokers+ const filteredBrokers = useMemo(() => {+ return availableBrokers.filter(broker => {+ const matchesSearch = !searchQuery ||+ broker.displayName.toLowerCase().includes(searchQuery.toLowerCase()) ||+ broker.id.toLowerCase().includes(searchQuery.toLowerCase());+ const matchesRegion = selectedRegion === 'all' || broker.region === selectedRegion;+ return matchesSearch && matchesRegion;+ });+ }, [availableBrokers, searchQuery, selectedRegion]);++ // Group brokers by region+ const brokersByRegion = useMemo(() => {+ const grouped = new Map<Region, StockBrokerMetadata[]>();+ filteredBrokers.forEach(broker => {+ const existing = grouped.get(broker.region) || [];+ existing.push(broker);+ grouped.set(broker.region, existing);+ });+ return grouped;+ }, [filteredBrokers]);++ // Get unique regions+ const availableRegions = useMemo(() => {+ const regions = new Set(availableBrokers.map(b => b.region));+ return Array.from(regions);+ }, [availableBrokers]);++ // Check broker statuses on mount - SEQUENTIAL with delay to avoid request spam+ useEffect(() => {+ let isCancelled = false;++ const checkBrokerStatuses = async () => {+ const statuses = new Map<string, BrokerStatus>();++ // Sequential check with delay between brokers+ for (const broker of availableBrokers) {+ if (isCancelled) break;++ try {+ const tempAdapter = createStockBrokerAdapter(broker.id);+ const storedCreds = await (tempAdapter as any).loadCredentials?.();++ let status: ConnectionStatus = 'not_configured';+ let hasCredentials = false;++ if (storedCreds?.apiKey) {+ hasCredentials = true;+ status = 'configured';++ if (storedCreds.accessToken) {+ // Has token - check if it's the active connected broker+ if (broker.id === activeBroker && isAuthenticated) {+ status = 'connected';+ } else {+ // Token exists but may be expired - mark as configured+ status = 'configured';+ }+ }+ }++ statuses.set(broker.id, {+ brokerId: broker.id,+ metadata: broker,+ status,+ hasCredentials,+ });++ // Update state incrementally+ setBrokerStatuses(new Map(statuses));+ } catch (err) {+ statuses.set(broker.id, {+ brokerId: broker.id,+ metadata: broker,+ status: 'not_configured',+ hasCredentials: false,+ });+ }++ // Small delay between broker checks (100ms) to avoid spamming+ if (!isCancelled) {+ await new Promise(resolve => setTimeout(resolve, 100));+ }+ }++ setBrokerStatuses(statuses);+ };++ checkBrokerStatuses();++ return () => {+ isCancelled = true;+ };+ }, [availableBrokers, activeBroker, isAuthenticated]);++ // Update selected broker when active broker changes+ useEffect(() => {+ if (activeBroker && !selectedBrokerId) {+ setSelectedBrokerId(activeBroker);+ }+ }, [activeBroker, selectedBrokerId]);++ // Load existing config when broker is selected+ useEffect(() => {+ const loadConfig = async () => {+ if (!selectedBrokerId) return;++ try {+ const tempAdapter = createStockBrokerAdapter(selectedBrokerId);+ const storedCreds = await (tempAdapter as any).loadCredentials?.();++ if (storedCreds) {+ setConfig({+ apiKey: storedCreds.apiKey || '',+ apiSecret: storedCreds.apiSecret || '',+ });+ } else {+ setConfig({ apiKey: '', apiSecret: '' });+ }+ } catch (err) {+ setConfig({ apiKey: '', apiSecret: '' });+ }+ };++ loadConfig();+ setShowCallbackInput(false);+ setCallbackUrl('');+ setConfigError(null);+ clearError();+ }, [selectedBrokerId, clearError]);++ // Handle broker selection+ const handleSelectBroker = async (brokerId: string) => {+ setSelectedBrokerId(brokerId);+ setShowConfigPanel(true);++ // Also set as active broker in context+ try {+ await setActiveBroker(brokerId);+ } catch (err) {+ console.error('Failed to set active broker:', err);+ }+ };++ // Save configuration+ const handleSaveConfig = async () => {+ if (!selectedBroker) return;++ setConfigError(null);+ setSaveSuccess(false);++ if (!config.apiKey?.trim()) {+ setConfigError('API Key is required');+ return;+ }++ if (selectedBroker.authType === 'oauth' && !config.apiSecret?.trim()) {+ setConfigError('API Secret is required for OAuth brokers');+ return;+ }++ setIsSaving(true);++ try {+ const tempAdapter = createStockBrokerAdapter(selectedBrokerId!);++ // Store credentials+ await (tempAdapter as any).storeCredentials({+ apiKey: config.apiKey,+ apiSecret: config.apiSecret || '',+ });++ // Set on adapter+ if (tempAdapter.setCredentials) {+ tempAdapter.setCredentials(config.apiKey, config.apiSecret || '');+ }++ // Update broker statuses+ setBrokerStatuses(prev => {+ const newMap = new Map(prev);+ const existing = newMap.get(selectedBrokerId!);+ if (existing) {+ newMap.set(selectedBrokerId!, { ...existing, status: 'configured', hasCredentials: true });+ }+ return newMap;+ });++ setSaveSuccess(true);+ setTimeout(() => setSaveSuccess(false), 3000);+ } catch (err) {+ setConfigError(err instanceof Error ? err.message : 'Failed to save configuration');+ } finally {+ setIsSaving(false);+ }+ };++ // Handle OAuth login+ const handleOAuthLogin = async () => {+ try {+ const authUrl = await getAuthUrl();+ if (authUrl) {+ await open(authUrl);+ setShowCallbackInput(true);+ }+ } catch (err) {+ console.error('Failed to get auth URL:', err);+ }+ };++ // Handle callback URL submission+ const handleCallbackSubmit = async () => {+ try {+ const url = new URL(callbackUrl);+ const requestToken = url.searchParams.get('request_token');+ const authCode = url.searchParams.get('auth_code');+ const code = url.searchParams.get('code');++ const token = requestToken || authCode || code;++ if (!token) {+ setConfigError('No auth code found in callback URL');+ return;+ }++ const authCredentials: BrokerCredentials = {+ apiKey: config.apiKey,+ apiSecret: config.apiSecret,+ };++ if (requestToken) {+ (authCredentials as any).requestToken = requestToken;+ } else if (authCode) {+ (authCredentials as any).authCode = authCode;+ } else {+ authCredentials.accessToken = token;+ }++ const response = await authenticate(authCredentials);++ if (response.success) {+ setShowCallbackInput(false);+ setCallbackUrl('');++ // Update broker status+ setBrokerStatuses(prev => {+ const newMap = new Map(prev);+ const existing = newMap.get(selectedBrokerId!);+ if (existing) {+ newMap.set(selectedBrokerId!, { ...existing, status: 'connected' });+ }+ return newMap;+ });+ }+ } catch (err) {+ setConfigError('Failed to process callback URL');+ }+ };++ // Handle logout/disconnect+ const handleDisconnect = async () => {+ await logout();++ // Update broker status+ setBrokerStatuses(prev => {+ const newMap = new Map(prev);+ const existing = newMap.get(selectedBrokerId!);+ if (existing) {+ newMap.set(selectedBrokerId!, { ...existing, status: existing.hasCredentials ? 'configured' : 'not_configured' });+ }+ return newMap;+ });+ };++ // Check token validity+ const handleCheckToken = async () => {+ if (!adapter) return;++ setIsCheckingToken(true);+ try {+ // Try to fetch funds - if it fails, token is expired+ await adapter.getFunds();++ // Update status to connected+ setBrokerStatuses(prev => {+ const newMap = new Map(prev);+ const existing = newMap.get(selectedBrokerId!);+ if (existing) {+ newMap.set(selectedBrokerId!, { ...existing, status: 'connected' });+ }+ return newMap;+ });+ } catch (err) {+ // Token expired+ setBrokerStatuses(prev => {+ const newMap = new Map(prev);+ const existing = newMap.get(selectedBrokerId!);+ if (existing) {+ newMap.set(selectedBrokerId!, { ...existing, status: 'expired' });+ }+ return newMap;+ });+ setConfigError('Session expired. Please re-authenticate.');+ } finally {+ setIsCheckingToken(false);+ }+ };++ // Get status badge+ const getStatusBadge = (status: ConnectionStatus) => {+ switch (status) {+ case 'connected':+ return (+ <span style={{ display: 'flex', alignItems: 'center', gap: '4px', color: COLORS.GREEN, fontSize: '10px' }}>+ <CheckCircle2 size={12} />+ CONNECTED+ </span>+ );+ case 'expired':+ return (+ <span style={{ display: 'flex', alignItems: 'center', gap: '4px', color: COLORS.YELLOW, fontSize: '10px' }}>+ <AlertTriangle size={12} />+ EXPIRED+ </span>+ );+ case 'configured':+ return (+ <span style={{ display: 'flex', alignItems: 'center', gap: '4px', color: COLORS.CYAN, fontSize: '10px' }}>+ <Key size={12} />+ CONFIGURED+ </span>+ );+ default:+ return (+ <span style={{ display: 'flex', alignItems: 'center', gap: '4px', color: COLORS.GRAY, fontSize: '10px' }}>+ <XCircle size={12} />+ NOT CONFIGURED+ </span>+ );+ }+ };++ return (+ <div style={{ display: 'flex', height: '100%', backgroundColor: COLORS.DARK_BG, fontFamily: '"IBM Plex Mono", monospace' }}>+ {/* Left Panel - Broker List */}+ <div style={{ width: '320px', borderRight: `1px solid ${COLORS.BORDER}`, display: 'flex', flexDirection: 'column' }}>+ {/* Search & Filter */}+ <div style={{ padding: '12px', borderBottom: `1px solid ${COLORS.BORDER}` }}>+ <div style={{ position: 'relative', marginBottom: '8px' }}>+ <Search size={14} color={COLORS.GRAY} style={{ position: 'absolute', left: '10px', top: '50%', transform: 'translateY(-50%)' }} />+ <input+ type="text"+ placeholder="Search brokers..."+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ style={{+ width: '100%',+ padding: '8px 8px 8px 32px',+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ color: COLORS.WHITE,+ fontSize: '11px',+ outline: 'none',+ boxSizing: 'border-box',+ }}+ />+ </div>++ <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>+ <button+ onClick={() => setSelectedRegion('all')}+ style={{+ padding: '4px 8px',+ fontSize: '9px',+ backgroundColor: selectedRegion === 'all' ? COLORS.ORANGE : COLORS.PANEL_BG,+ color: selectedRegion === 'all' ? COLORS.DARK_BG : COLORS.GRAY,+ border: `1px solid ${selectedRegion === 'all' ? COLORS.ORANGE : COLORS.BORDER}`,+ cursor: 'pointer',+ fontWeight: 600,+ }}+ >+ ALL+ </button>+ {availableRegions.map(region => (+ <button+ key={region}+ onClick={() => setSelectedRegion(region)}+ style={{+ padding: '4px 8px',+ fontSize: '9px',+ backgroundColor: selectedRegion === region ? COLORS.ORANGE : COLORS.PANEL_BG,+ color: selectedRegion === region ? COLORS.DARK_BG : COLORS.GRAY,+ border: `1px solid ${selectedRegion === region ? COLORS.ORANGE : COLORS.BORDER}`,+ cursor: 'pointer',+ fontWeight: 600,+ }}+ >+ {REGION_LABELS[region]?.toUpperCase() || region.toUpperCase()}+ </button>+ ))}+ </div>+ </div>++ {/* Broker List */}+ <div style={{ flex: 1, overflowY: 'auto', padding: '8px' }}>+ {Array.from(brokersByRegion.entries()).map(([region, brokers]) => (+ <div key={region} style={{ marginBottom: '16px' }}>+ <div style={{ padding: '4px 8px', color: COLORS.GRAY, fontSize: '9px', fontWeight: 600, letterSpacing: '1px' }}>+ {REGION_LABELS[region] || region}+ </div>+ {brokers.map(broker => {+ const status = brokerStatuses.get(broker.id);+ const isSelected = selectedBrokerId === broker.id;+ const isActive = activeBroker === broker.id && isAuthenticated;++ return (+ <div+ key={broker.id}+ onClick={() => handleSelectBroker(broker.id)}+ style={{+ padding: '10px 12px',+ backgroundColor: isSelected ? COLORS.HEADER_BG : 'transparent',+ border: `1px solid ${isSelected ? COLORS.ORANGE : 'transparent'}`,+ cursor: 'pointer',+ marginBottom: '4px',+ transition: 'all 0.15s ease',+ }}+ >+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <div>+ <div style={{ color: COLORS.WHITE, fontSize: '11px', fontWeight: 600 }}>+ {broker.displayName}+ {isActive && (+ <span style={{ marginLeft: '6px', padding: '2px 6px', backgroundColor: COLORS.GREEN, color: COLORS.DARK_BG, fontSize: '8px', fontWeight: 700 }}>+ ACTIVE+ </span>+ )}+ </div>+ <div style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '2px' }}>+ {broker.authType === 'oauth' ? 'OAuth' : broker.authType === 'totp' ? 'TOTP' : 'API Key'}+ </div>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ {getStatusBadge(status?.status || 'not_configured')}+ <ChevronRight size={14} color={COLORS.GRAY} />+ </div>+ </div>+ </div>+ );+ })}+ </div>+ ))}+ </div>+ </div>++ {/* Right Panel - Configuration */}+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>+ {selectedBroker ? (+ <>+ {/* Broker Header */}+ <div style={{ padding: '16px 20px', borderBottom: `1px solid ${COLORS.BORDER}`, backgroundColor: COLORS.HEADER_BG }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <div style={{+ width: '40px',+ height: '40px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: `${COLORS.ORANGE}20`,+ border: `1px solid ${COLORS.ORANGE}40`,+ }}>+ <Globe size={20} color={COLORS.ORANGE} />+ </div>+ <div>+ <h2 style={{ color: COLORS.WHITE, fontSize: '14px', fontWeight: 600, margin: 0 }}>+ {selectedBroker.displayName}+ </h2>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginTop: '4px' }}>+ {getStatusBadge(brokerStatuses.get(selectedBrokerId!)?.status || 'not_configured')}+ <span style={{ color: COLORS.MUTED, fontSize: '10px' }}>+ {selectedBroker.authType === 'oauth' ? 'OAuth 2.0' : selectedBroker.authType === 'totp' ? 'TOTP Auth' : 'API Key Auth'}+ </span>+ </div>+ </div>+ </div>++ <div style={{ display: 'flex', gap: '8px' }}>+ {API_KEYS_URLS[selectedBrokerId!] && (+ <a+ href={API_KEYS_URLS[selectedBrokerId!]}+ target="_blank"+ rel="noopener noreferrer"+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ padding: '8px 12px',+ backgroundColor: `${COLORS.ORANGE}10`,+ border: `1px solid ${COLORS.ORANGE}40`,+ color: COLORS.ORANGE,+ fontSize: '10px',+ textDecoration: 'none',+ fontWeight: 600,+ }}+ >+ GET API KEYS+ <ExternalLink size={12} />+ </a>+ )}++ {selectedBrokerId === activeBroker && isAuthenticated && (+ <button+ onClick={handleCheckToken}+ disabled={isCheckingToken}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ padding: '8px 12px',+ backgroundColor: `${COLORS.BLUE}10`,+ border: `1px solid ${COLORS.BLUE}40`,+ color: COLORS.BLUE,+ fontSize: '10px',+ cursor: 'pointer',+ fontWeight: 600,+ }}+ >+ {isCheckingToken ? <Loader2 size={12} className="animate-spin" /> : <RefreshCw size={12} />}+ CHECK TOKEN+ </button>+ )}+ </div>+ </div>+ </div>++ {/* Configuration Content */}+ <div style={{ flex: 1, overflow: 'auto', padding: '20px' }}>+ {/* Error Display */}+ {(error || configError) && (+ <div style={{+ marginBottom: '16px',+ padding: '12px',+ backgroundColor: `${COLORS.RED}15`,+ border: `1px solid ${COLORS.RED}40`,+ display: 'flex',+ alignItems: 'center',+ gap: '10px',+ }}>+ <AlertTriangle size={16} color={COLORS.RED} />+ <p style={{ color: COLORS.RED, fontSize: '11px', margin: 0 }}>{error || configError}</p>+ </div>+ )}++ {/* Success Display */}+ {saveSuccess && (+ <div style={{+ marginBottom: '16px',+ padding: '12px',+ backgroundColor: `${COLORS.GREEN}15`,+ border: `1px solid ${COLORS.GREEN}40`,+ display: 'flex',+ alignItems: 'center',+ gap: '10px',+ }}>+ <CheckCircle2 size={16} color={COLORS.GREEN} />+ <p style={{ color: COLORS.GREEN, fontSize: '11px', margin: 0 }}>Configuration saved successfully!</p>+ </div>+ )}++ {/* Connected State */}+ {selectedBrokerId === activeBroker && isAuthenticated ? (+ <div style={{ maxWidth: '500px' }}>+ <div style={{+ padding: '20px',+ backgroundColor: `${COLORS.GREEN}10`,+ border: `1px solid ${COLORS.GREEN}40`,+ marginBottom: '20px',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '12px' }}>+ <CheckCircle2 size={24} color={COLORS.GREEN} />+ <div>+ <h3 style={{ color: COLORS.WHITE, fontSize: '13px', fontWeight: 600, margin: 0 }}>+ Connected to {selectedBroker.displayName}+ </h3>+ <p style={{ color: COLORS.GREEN, fontSize: '10px', margin: '4px 0 0 0' }}>+ Trading mode: {tradingMode.toUpperCase()}+ </p>+ </div>+ </div>+ <p style={{ color: COLORS.GRAY, fontSize: '10px', margin: 0 }}>+ Your broker account is linked and ready for trading. Indian broker tokens expire at midnight IST.+ </p>+ </div>++ <button+ onClick={handleDisconnect}+ style={{+ width: '100%',+ padding: '12px 16px',+ backgroundColor: `${COLORS.RED}20`,+ border: `1px solid ${COLORS.RED}40`,+ color: COLORS.RED,+ fontSize: '11px',+ fontWeight: 600,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '8px',+ }}+ >+ <LogOut size={14} />+ DISCONNECT BROKER+ </button>+ </div>+ ) : (+ /* Configuration Form */+ <div style={{ maxWidth: '500px' }}>+ {/* Step 1: API Credentials */}+ <div style={{ marginBottom: '24px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>+ <div style={{+ width: '24px',+ height: '24px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: COLORS.ORANGE,+ color: COLORS.DARK_BG,+ fontSize: '12px',+ fontWeight: 700,+ }}>+ 1+ </div>+ <h3 style={{ color: COLORS.WHITE, fontSize: '12px', fontWeight: 600, margin: 0 }}>+ CONFIGURE API CREDENTIALS+ </h3>+ </div>++ {/* API Key */}+ <div style={{ marginBottom: '12px' }}>+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>+ API KEY / APP ID <span style={{ color: COLORS.RED }}>*</span>+ </label>+ <input+ type="text"+ value={config.apiKey}+ onChange={(e) => setConfig({ ...config, apiKey: e.target.value })}+ placeholder={`Enter your ${selectedBroker.displayName} API Key`}+ style={{+ width: '100%',+ padding: '10px 12px',+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ color: COLORS.WHITE,+ fontSize: '12px',+ fontFamily: 'monospace',+ outline: 'none',+ boxSizing: 'border-box',+ }}+ />+ </div>++ {/* API Secret (for OAuth) */}+ {selectedBroker.authType === 'oauth' && (+ <div style={{ marginBottom: '12px' }}>+ <label style={{ display: 'block', color: COLORS.GRAY, fontSize: '10px', fontWeight: 600, marginBottom: '6px' }}>+ API SECRET <span style={{ color: COLORS.RED }}>*</span>+ </label>+ <div style={{ position: 'relative' }}>+ <input+ type={showSecret ? 'text' : 'password'}+ value={config.apiSecret || ''}+ onChange={(e) => setConfig({ ...config, apiSecret: e.target.value })}+ placeholder="Enter your API Secret"+ style={{+ width: '100%',+ padding: '10px 40px 10px 12px',+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ color: COLORS.WHITE,+ fontSize: '12px',+ fontFamily: 'monospace',+ outline: 'none',+ boxSizing: 'border-box',+ }}+ />+ <button+ type="button"+ onClick={() => setShowSecret(!showSecret)}+ style={{+ position: 'absolute',+ right: '10px',+ top: '50%',+ transform: 'translateY(-50%)',+ background: 'none',+ border: 'none',+ color: COLORS.GRAY,+ cursor: 'pointer',+ }}+ >+ {showSecret ? <EyeOff size={16} /> : <Eye size={16} />}+ </button>+ </div>+ </div>+ )}++ <button+ onClick={handleSaveConfig}+ disabled={isSaving || !config.apiKey}+ style={{+ width: '100%',+ padding: '10px 16px',+ backgroundColor: isSaving || !config.apiKey ? COLORS.MUTED : COLORS.ORANGE,+ border: 'none',+ color: isSaving || !config.apiKey ? COLORS.GRAY : COLORS.DARK_BG,+ fontSize: '11px',+ fontWeight: 700,+ cursor: isSaving || !config.apiKey ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '8px',+ }}+ >+ {isSaving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}+ SAVE CONFIGURATION+ </button>+ </div>++ {/* Step 2: Authentication */}+ {selectedBroker.authType === 'oauth' && (+ <div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>+ <div style={{+ width: '24px',+ height: '24px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: brokerStatuses.get(selectedBrokerId!)?.hasCredentials ? COLORS.ORANGE : COLORS.MUTED,+ color: COLORS.DARK_BG,+ fontSize: '12px',+ fontWeight: 700,+ }}>+ 2+ </div>+ <h3 style={{ color: COLORS.WHITE, fontSize: '12px', fontWeight: 600, margin: 0 }}>+ AUTHENTICATE WITH {selectedBroker.displayName.toUpperCase()}+ </h3>+ </div>++ {!brokerStatuses.get(selectedBrokerId!)?.hasCredentials ? (+ <p style={{ color: COLORS.MUTED, fontSize: '10px', marginBottom: '12px' }}>+ Save your API credentials first to enable authentication.+ </p>+ ) : (+ <>+ <button+ onClick={handleOAuthLogin}+ disabled={isConnecting}+ style={{+ width: '100%',+ padding: '12px 16px',+ backgroundColor: isConnecting ? COLORS.MUTED : COLORS.ORANGE,+ border: 'none',+ color: isConnecting ? COLORS.GRAY : COLORS.DARK_BG,+ fontSize: '11px',+ fontWeight: 700,+ cursor: isConnecting ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '8px',+ marginBottom: '12px',+ }}+ >+ {isConnecting ? <Loader2 size={14} className="animate-spin" /> : <ExternalLink size={14} />}+ LOGIN WITH {selectedBroker.displayName.toUpperCase()}+ </button>++ {/* Callback URL Input */}+ {showCallbackInput && (+ <div style={{+ padding: '16px',+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ }}>+ <p style={{ color: COLORS.WHITE, fontSize: '11px', fontWeight: 600, marginBottom: '8px' }}>+ PASTE CALLBACK URL+ </p>+ <p style={{ color: COLORS.GRAY, fontSize: '9px', marginBottom: '12px' }}>+ After authorizing, copy the URL from your browser and paste it below.+ </p>+ <input+ type="text"+ value={callbackUrl}+ onChange={(e) => setCallbackUrl(e.target.value)}+ placeholder="https://127.0.0.1/?auth_code=..."+ style={{+ width: '100%',+ padding: '10px 12px',+ backgroundColor: COLORS.HEADER_BG,+ border: `1px solid ${COLORS.BORDER}`,+ color: COLORS.WHITE,+ fontSize: '11px',+ fontFamily: 'monospace',+ outline: 'none',+ boxSizing: 'border-box',+ marginBottom: '12px',+ }}+ />+ <button+ onClick={handleCallbackSubmit}+ disabled={!callbackUrl || isConnecting}+ style={{+ width: '100%',+ padding: '10px 16px',+ backgroundColor: !callbackUrl || isConnecting ? COLORS.MUTED : COLORS.GREEN,+ border: 'none',+ color: !callbackUrl || isConnecting ? COLORS.GRAY : COLORS.DARK_BG,+ fontSize: '11px',+ fontWeight: 700,+ cursor: !callbackUrl || isConnecting ? 'not-allowed' : 'pointer',+ }}+ >+ COMPLETE AUTHENTICATION+ </button>+ </div>+ )}+ </>+ )}+ </div>+ )}++ {/* Security Note */}+ <div style={{+ marginTop: '24px',+ padding: '12px',+ backgroundColor: COLORS.PANEL_BG,+ border: `1px solid ${COLORS.BORDER}`,+ }}>+ <p style={{ color: COLORS.MUTED, fontSize: '9px', margin: 0, lineHeight: 1.6 }}>+ <strong style={{ color: COLORS.GRAY }}>SECURITY:</strong> Your credentials are stored securely on your local device.+ They are never sent to our servers and only communicate directly with {selectedBroker.displayName}'s API.+ Indian broker tokens expire at midnight IST daily.+ </p>+ </div>+ </div>+ )}+ </div>+ </>+ ) : (+ /* No broker selected */+ <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>+ <div style={{ textAlign: 'center' }}>+ <Settings size={48} color={COLORS.MUTED} style={{ marginBottom: '16px' }} />+ <p style={{ color: COLORS.GRAY, fontSize: '12px' }}>Select a broker from the list to configure</p>+ </div>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsxindex b933b4092..058ef8adb 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/StockTradingChart.tsx@@ -17,6 +17,7 @@ interface StockTradingChartProps {exchange: StockExchange;interval?: TimeFrame;height?: number;+ timezone?: string; // e.g., 'Asia/Kolkata' for IST}// Available timeframes@@ -53,12 +54,36 @@ const timeframeToDays = (tf: TimeFrame): number => {}};+// Map exchange to timezone+const EXCHANGE_TIMEZONES: Record<string, string> = {+ // Indian exchanges - IST (UTC+5:30)+ NSE: 'Asia/Kolkata',+ BSE: 'Asia/Kolkata',+ MCX: 'Asia/Kolkata',+ NFO: 'Asia/Kolkata',+ BFO: 'Asia/Kolkata',+ CDS: 'Asia/Kolkata',+ // US exchanges - Eastern Time+ NYSE: 'America/New_York',+ NASDAQ: 'America/New_York',+ AMEX: 'America/New_York',+ // European exchanges+ LSE: 'Europe/London',+ XETRA: 'Europe/Berlin',+ EURONEXT: 'Europe/Paris',+ // Default+ DEFAULT: 'UTC',+};+export function StockTradingChart({symbol,exchange,interval: initialInterval = '5m',- height+ height,+ timezone: propTimezone}: StockTradingChartProps) {+ // Auto-detect timezone based on exchange if not provided+ const timezone = propTimezone || EXCHANGE_TIMEZONES[exchange] || EXCHANGE_TIMEZONES.DEFAULT;const [isLoading, setIsLoading] = useState(true);const [error, setError] = useState<string | null>(null);const [selectedInterval, setSelectedInterval] = useState<TimeFrame>(initialInterval);@@ -324,6 +349,7 @@ export function StockTradingChart({showVolume={true}showToolbar={true}showHeader={false}+ timezone={timezone}/></div>)}diff --git a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/index.ts b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/index.tsindex 7ede454cd..3565217f1 100644--- a/fincept-terminal-desktop/src/components/tabs/equity-trading/components/index.ts+++ b/fincept-terminal-desktop/src/components/tabs/equity-trading/components/index.ts@@ -8,6 +8,7 @@ export { BrokerSelector } from './BrokerSelector';export { BrokerAuthPanel } from './BrokerAuthPanel';export { BrokerConfigPanel } from './BrokerConfigPanel';export { BrokerSetupPanel } from './BrokerSetupPanel';+export { BrokersManagementPanel } from './BrokersManagementPanel';export { StockOrderForm } from './StockOrderForm';export { PositionsPanel } from './PositionsPanel';export { HoldingsPanel } from './HoldingsPanel';diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsxindex f2cb23e48..451618f3b 100644--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/PortfolioTab.tsx@@ -23,6 +23,7 @@ import PortfolioOptimizationView from './portfolio/PortfolioOptimizationView';import CreatePortfolioModal from './modals/CreatePortfolioModal';import AddAssetModal from './modals/AddAssetModal';import SellAssetModal from './modals/SellAssetModal';+import ConfirmDeleteModal from './modals/ConfirmDeleteModal';import { usePortfolioOperations } from './hooks/usePortfolioOperations';import { formatCurrency, formatPercent } from './portfolio/utils';import { TabFooter } from '@/components/common/TabFooter';@@ -38,6 +39,8 @@ const PortfolioTab: React.FC = () => {const [showCreatePortfolio, setShowCreatePortfolio] = useState(false);const [showAddAsset, setShowAddAsset] = useState(false);const [showSellAsset, setShowSellAsset] = useState(false);+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);+ const [portfolioToDelete, setPortfolioToDelete] = useState<string | null>(null);// Form statesconst [newPortfolioName, setNewPortfolioName] = useState('');@@ -119,17 +122,24 @@ const PortfolioTab: React.FC = () => {}};- // Handle delete portfolio- const handleDeletePortfolio = async (portfolioId: string) => {- if (!confirm('Are you sure you want to delete this portfolio? This action cannot be undone.')) {- return;- }+ // Handle delete portfolio - show confirmation modal+ const handleDeletePortfolio = (portfolioId: string) => {+ setPortfolioToDelete(portfolioId);+ setShowDeleteConfirm(true);+ };++ // Confirm delete portfolio+ const confirmDeletePortfolio = async () => {+ if (!portfolioToDelete) return;try {- await deletePortfolio(portfolioId);+ await deletePortfolio(portfolioToDelete);+ setShowDeleteConfirm(false);+ setPortfolioToDelete(null);} catch (error) {console.error('[PortfolioTab] Error deleting portfolio:', error);- alert('Failed to delete portfolio');+ setShowDeleteConfirm(false);+ setPortfolioToDelete(null);}};@@ -575,6 +585,16 @@ const PortfolioTab: React.FC = () => {onClose={() => setShowSellAsset(false)}onSell={handleSellAsset}/>++ <ConfirmDeleteModal+ show={showDeleteConfirm}+ portfolioName={portfolios.find(p => p.id === portfolioToDelete)?.name || ''}+ onClose={() => {+ setShowDeleteConfirm(false);+ setPortfolioToDelete(null);+ }}+ onConfirm={confirmDeletePortfolio}+ /></div>);};diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/hooks/usePortfolioOperations.ts b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/hooks/usePortfolioOperations.tsindex 81f298042..bed3b0251 100644--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/hooks/usePortfolioOperations.ts+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/hooks/usePortfolioOperations.ts@@ -20,7 +20,12 @@ export const usePortfolioOperations = () => {setLoading(true);try {await portfolioService.initialize();- await loadPortfolios();+ const result = await portfolioService.getPortfolios();+ setPortfolios(result);+ // Select first portfolio on initial load+ if (result.length > 0) {+ setSelectedPortfolio(result[0]);+ }} catch (error) {console.error('[usePortfolioOperations] Initialization error:', error);} finally {@@ -30,14 +35,46 @@ export const usePortfolioOperations = () => {initService();}, []);- // Auto-refresh portfolio data+ // Auto-refresh portfolio data only when tab is visibleuseEffect(() => {- if (selectedPortfolio) {- const refreshTimer = setInterval(() => {- refreshPortfolioData();- }, 60000); // Refresh every minute- return () => clearInterval(refreshTimer);+ if (!selectedPortfolio) return;++ let refreshTimer: ReturnType<typeof setInterval> | null = null;++ const startRefresh = () => {+ if (!refreshTimer) {+ refreshTimer = setInterval(() => {+ refreshPortfolioData();+ }, 60000);+ }+ };++ const stopRefresh = () => {+ if (refreshTimer) {+ clearInterval(refreshTimer);+ refreshTimer = null;+ }+ };++ const handleVisibilityChange = () => {+ if (document.hidden) {+ stopRefresh();+ } else {+ startRefresh();+ }+ };++ // Start refresh only if page is visible+ if (!document.hidden) {+ startRefresh();}++ document.addEventListener('visibilitychange', handleVisibilityChange);++ return () => {+ stopRefresh();+ document.removeEventListener('visibilitychange', handleVisibilityChange);+ };}, [selectedPortfolio]);// Load portfolio summary when selection changes@@ -52,13 +89,10 @@ export const usePortfolioOperations = () => {try {const result = await portfolioService.getPortfolios();setPortfolios(result);-- // Select first portfolio if none selected- if (result.length > 0 && !selectedPortfolio) {- setSelectedPortfolio(result[0]);- }+ return result;} catch (error) {console.error('[usePortfolioOperations] Error loading portfolios:', error);+ return [];}};@@ -132,10 +166,12 @@ export const usePortfolioOperations = () => {// Delete portfolioconst deletePortfolio = async (portfolioId: string) => {await portfolioService.deletePortfolio(portfolioId);- await loadPortfolios();+ const updatedPortfolios = await loadPortfolios();if (selectedPortfolio?.id === portfolioId) {- setSelectedPortfolio(portfolios.length > 1 ? portfolios[0] : null);+ // Use fresh list, exclude deleted portfolio+ const remaining = updatedPortfolios.filter(p => p.id !== portfolioId);+ setSelectedPortfolio(remaining.length > 0 ? remaining[0] : null);setPortfolioSummary(null);}};diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/ConfirmDeleteModal.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/ConfirmDeleteModal.tsxnew file mode 100644index 000000000..932410d91--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/modals/ConfirmDeleteModal.tsx@@ -0,0 +1,101 @@+import React from 'react';+import { AlertTriangle } from 'lucide-react';+import { FINCEPT, TYPOGRAPHY, SPACING, BORDERS, COMMON_STYLES } from '../finceptStyles';++interface ConfirmDeleteModalProps {+ show: boolean;+ portfolioName: string;+ onClose: () => void;+ onConfirm: () => void;+}++const ConfirmDeleteModal: React.FC<ConfirmDeleteModalProps> = ({+ show,+ portfolioName,+ onClose,+ onConfirm+}) => {+ if (!show) return null;++ return (+ <div style={COMMON_STYLES.modalOverlay}>+ <div style={{+ ...COMMON_STYLES.modalPanel,+ fontFamily: TYPOGRAPHY.MONO,+ maxWidth: '450px'+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.MEDIUM,+ marginBottom: SPACING.LARGE+ }}>+ <AlertTriangle size={24} color={FINCEPT.RED} />+ <div style={{+ color: FINCEPT.RED,+ fontSize: TYPOGRAPHY.HEADING,+ fontWeight: TYPOGRAPHY.BOLD,+ letterSpacing: TYPOGRAPHY.WIDE+ }}>+ DELETE PORTFOLIO+ </div>+ </div>++ <div style={{+ color: FINCEPT.WHITE,+ fontSize: TYPOGRAPHY.DEFAULT,+ marginBottom: SPACING.LARGE,+ lineHeight: 1.5+ }}>+ Are you sure you want to delete <span style={{ color: FINCEPT.ORANGE, fontWeight: TYPOGRAPHY.BOLD }}>"{portfolioName}"</span>?+ </div>++ <div style={{+ color: FINCEPT.GRAY,+ fontSize: TYPOGRAPHY.BODY,+ marginBottom: SPACING.LARGE,+ padding: SPACING.MEDIUM,+ backgroundColor: FINCEPT.DARK_BG,+ border: BORDERS.RED+ }}>+ This action cannot be undone. All positions, transactions, and history will be permanently deleted.+ </div>++ <div style={{ display: 'flex', gap: SPACING.MEDIUM, justifyContent: 'flex-end' }}>+ <button+ onClick={onClose}+ style={{+ ...COMMON_STYLES.buttonSecondary,+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.backgroundColor = 'transparent';+ }}+ >+ CANCEL+ </button>+ <button+ onClick={onConfirm}+ style={{+ ...COMMON_STYLES.buttonPrimary,+ backgroundColor: FINCEPT.RED,+ border: BORDERS.RED+ }}+ onMouseEnter={(e) => {+ e.currentTarget.style.opacity = '0.85';+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.opacity = '1';+ }}+ >+ DELETE+ </button>+ </div>+ </div>+ </div>+ );+};++export default ConfirmDeleteModal;diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PositionsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PositionsView.tsxindex 7338104e6..948923802 100644--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PositionsView.tsx+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/PositionsView.tsx@@ -68,7 +68,7 @@ const PositionsView: React.FC<PositionsViewProps> = ({ portfolioSummary }) => {) : (portfolioSummary.holdings.map((holding, index) => (<div- key={holding.id}+ key={holding.id || `${holding.symbol}-${index}`}style={{display: 'grid',gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr 1fr 1fr 1.2fr 1fr',diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/SectorsView.tsx b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/SectorsView.tsxindex 01c7c23a0..11686ffca 100644--- a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/SectorsView.tsx+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/portfolio/SectorsView.tsx@@ -1,4 +1,4 @@-import React, { useMemo } from 'react';+import React, { useMemo, useEffect, useState } from 'react';import { PortfolioSummary, PortfolioHolding } from '../../../../services/portfolio/portfolioService';import { formatCurrency, formatPercent } from './utils';import { sectorService } from '../../../../services/data-sources/sectorService';@@ -18,6 +18,8 @@ interface SectorAllocation {const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {const currency = portfolioSummary.portfolio.currency;+ const [sectorsLoaded, setSectorsLoaded] = useState(false);+ const [, forceUpdate] = useState(0);// Fincept color palette for sectorsconst sectorColors = [@@ -30,6 +32,18 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {FINCEPT.RED];+ // Prefetch sector data for all holdings+ useEffect(() => {+ const symbols = portfolioSummary.holdings.map(h => h.symbol);+ if (symbols.length > 0) {+ setSectorsLoaded(false);+ sectorService.prefetchSectors(symbols).then(() => {+ setSectorsLoaded(true);+ forceUpdate(n => n + 1); // Trigger re-render with updated cache+ });+ }+ }, [portfolioSummary.holdings]);+// Group holdings by sector using real sector classificationconst sectorAllocations = useMemo((): SectorAllocation[] => {const sectorMap = new Map<string, { value: number; holdings: PortfolioHolding[] }>();@@ -55,7 +69,7 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {color: sectorColors[index % sectorColors.length]})).sort((a, b) => b.weight - a.weight);- }, [portfolioSummary.holdings, portfolioSummary.total_market_value]);+ }, [portfolioSummary.holdings, portfolioSummary.total_market_value, sectorsLoaded]);// Calculate pie chart angleslet currentAngle = 0;@@ -107,6 +121,23 @@ const SectorsView: React.FC<SectorsViewProps> = ({ portfolioSummary }) => {SECTOR ALLOCATION</div>+ {!sectorsLoaded && portfolioSummary.holdings.length > 0 && (+ <div style={{+ padding: SPACING.MEDIUM,+ marginBottom: SPACING.MEDIUM,+ backgroundColor: FINCEPT.PANEL_BG,+ border: BORDERS.CYAN,+ color: FINCEPT.CYAN,+ fontSize: TYPOGRAPHY.BODY,+ display: 'flex',+ alignItems: 'center',+ gap: SPACING.SMALL+ }}>+ <span style={{ animation: 'pulse 1.5s infinite' }}>●</span>+ Loading sector data from API...+ </div>+ )}+{sectorAllocations.length === 0 ? (<div style={{padding: SPACING.XLARGE,diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/AdditionalComponents.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/AdditionalComponents.tsxnew file mode 100644index 000000000..0c7b5adca--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/AdditionalComponents.tsx@@ -0,0 +1,365 @@+import React, { useState } from 'react';+import {+ Quote,+ List,+ ListOrdered,+ FileText,+ Stamp,+ QrCode,+ PenTool,+ AlertTriangle,+ ChevronRight,+ Hash,+} from 'lucide-react';++// ============ Quote/Callout Box ============+interface QuoteBoxProps {+ content: string;+ author?: string;+ type?: 'quote' | 'info' | 'warning' | 'success' | 'error';+}++export const QuoteBox: React.FC<QuoteBoxProps> = ({ content, author, type = 'quote' }) => {+ const styles = {+ quote: { bg: '#f8f9fa', border: '#6c757d', icon: Quote },+ info: { bg: '#e7f3ff', border: '#0066cc', icon: FileText },+ warning: { bg: '#fff8e1', border: '#ffa500', icon: AlertTriangle },+ success: { bg: '#e8f5e9', border: '#4caf50', icon: FileText },+ error: { bg: '#ffebee', border: '#f44336', icon: AlertTriangle },+ };++ const style = styles[type];+ const Icon = style.icon;++ return (+ <div+ className="p-4 rounded-r-lg my-4"+ style={{ backgroundColor: style.bg, borderLeft: `4px solid ${style.border}` }}+ >+ <div className="flex gap-3">+ <Icon size={20} style={{ color: style.border }} className="flex-shrink-0 mt-0.5" />+ <div className="flex-1">+ <p className="text-sm text-gray-700 italic">{content}</p>+ {author && <p className="text-xs text-gray-500 mt-2">— {author}</p>}+ </div>+ </div>+ </div>+ );+};++// ============ Bullet/Numbered Lists ============+interface ListComponentProps {+ items: string[];+ ordered?: boolean;+ nested?: boolean;+}++export const ListComponent: React.FC<ListComponentProps> = ({ items, ordered, nested }) => {+ const Tag = ordered ? 'ol' : 'ul';++ return (+ <Tag className={`my-3 ${ordered ? 'list-decimal' : 'list-disc'} ${nested ? 'ml-6' : 'ml-4'}`}>+ {items.map((item, idx) => (+ <li key={idx} className="text-sm text-gray-800 py-1 pl-1">+ {item}+ </li>+ ))}+ </Tag>+ );+};++// ============ Footnotes/References ============+interface FootnoteProps {+ id: number;+ content: string;+ inline?: boolean;+}++export const Footnote: React.FC<FootnoteProps> = ({ id, content, inline }) => {+ if (inline) {+ return (+ <sup className="text-[#FFA500] cursor-pointer hover:underline text-xs font-semibold">+ [{id}]+ </sup>+ );+ }++ return (+ <div className="flex gap-2 py-1 text-xs text-gray-600 border-t border-gray-200">+ <span className="text-[#FFA500] font-semibold">[{id}]</span>+ <span>{content}</span>+ </div>+ );+};++interface FootnotesListProps {+ footnotes: { id: number; content: string }[];+}++export const FootnotesList: React.FC<FootnotesListProps> = ({ footnotes }) => (+ <div className="mt-8 pt-4 border-t-2 border-gray-300">+ <h4 className="text-xs font-bold text-gray-600 mb-2">REFERENCES</h4>+ {footnotes.map(fn => (+ <Footnote key={fn.id} id={fn.id} content={fn.content} />+ ))}+ </div>+);++// ============ Table of Contents ============+interface TOCItem {+ id: string;+ title: string;+ level: number;+ page?: number;+}++interface TableOfContentsProps {+ items: TOCItem[];+ showPageNumbers?: boolean;+}++export const TableOfContents: React.FC<TableOfContentsProps> = ({ items, showPageNumbers = true }) => (+ <div className="bg-gray-50 p-4 rounded border border-gray-200 my-4">+ <h3 className="text-sm font-bold text-gray-800 mb-3 pb-2 border-b">Table of Contents</h3>+ <nav>+ {items.map((item, idx) => (+ <div+ key={item.id}+ className="flex items-center justify-between py-1.5 hover:bg-gray-100 rounded px-2 cursor-pointer"+ style={{ paddingLeft: `${(item.level - 1) * 16 + 8}px` }}+ >+ <div className="flex items-center gap-2">+ {item.level === 1 && <ChevronRight size={12} className="text-[#FFA500]" />}+ <span className={`text-sm ${item.level === 1 ? 'font-semibold' : ''} text-gray-700`}>+ {item.title}+ </span>+ </div>+ {showPageNumbers && item.page && (+ <span className="text-xs text-gray-400">{item.page}</span>+ )}+ </div>+ ))}+ </nav>+ </div>+);++// ============ Watermark ============+interface WatermarkProps {+ text: string;+ opacity?: number;+ rotation?: number;+ color?: string;+}++export const Watermark: React.FC<WatermarkProps> = ({+ text,+ opacity = 0.1,+ rotation = -45,+ color = '#000000'+}) => (+ <div+ className="absolute inset-0 flex items-center justify-center pointer-events-none overflow-hidden"+ style={{ zIndex: 0 }}+ >+ <span+ className="text-6xl font-bold whitespace-nowrap select-none"+ style={{+ opacity,+ transform: `rotate(${rotation}deg)`,+ color,+ }}+ >+ {text}+ </span>+ </div>+);++// ============ QR Code (Simple SVG-based) ============+interface QRCodeProps {+ value: string;+ size?: number;+ label?: string;+}++export const QRCodeComponent: React.FC<QRCodeProps> = ({ value, size = 100, label }) => {+ // Simple placeholder - in production, use a QR library+ const generatePattern = (str: string) => {+ const pattern: boolean[][] = [];+ const gridSize = 21;+ for (let i = 0; i < gridSize; i++) {+ pattern[i] = [];+ for (let j = 0; j < gridSize; j++) {+ // Positioning patterns (corners)+ const isCorner = (i < 7 && j < 7) || (i < 7 && j >= gridSize - 7) || (i >= gridSize - 7 && j < 7);+ if (isCorner) {+ const inOuter = i === 0 || i === 6 || j === 0 || j === 6 ||+ (i >= gridSize - 7 && (i === gridSize - 7 || i === gridSize - 1)) ||+ (j >= gridSize - 7 && (j === gridSize - 7 || j === gridSize - 1));+ const inInner = (i >= 2 && i <= 4 && j >= 2 && j <= 4) ||+ (i >= 2 && i <= 4 && j >= gridSize - 5 && j <= gridSize - 3) ||+ (i >= gridSize - 5 && i <= gridSize - 3 && j >= 2 && j <= 4);+ pattern[i][j] = inOuter || inInner;+ } else {+ // Data pattern based on string hash+ const hash = (str.charCodeAt((i * gridSize + j) % str.length) + i + j) % 3;+ pattern[i][j] = hash === 0;+ }+ }+ }+ return pattern;+ };++ const pattern = generatePattern(value);+ const cellSize = size / 21;++ return (+ <div className="inline-flex flex-col items-center gap-2">+ <svg width={size} height={size} className="border border-gray-300 rounded">+ <rect width={size} height={size} fill="white" />+ {pattern.map((row, i) =>+ row.map((cell, j) =>+ cell && (+ <rect+ key={`${i}-${j}`}+ x={j * cellSize}+ y={i * cellSize}+ width={cellSize}+ height={cellSize}+ fill="black"+ />+ )+ )+ )}+ </svg>+ {label && <span className="text-xs text-gray-500">{label}</span>}+ </div>+ );+};++// ============ Signature Block ============+interface SignatureBlockProps {+ name: string;+ title?: string;+ date?: string;+ showLine?: boolean;+}++export const SignatureBlock: React.FC<SignatureBlockProps> = ({ name, title, date, showLine = true }) => (+ <div className="mt-8 inline-block min-w-[200px]">+ {showLine && <div className="border-b border-gray-400 h-8 mb-2" />}+ <p className="text-sm font-semibold text-gray-800">{name}</p>+ {title && <p className="text-xs text-gray-600">{title}</p>}+ {date && <p className="text-xs text-gray-500 mt-1">Date: {date}</p>}+ </div>+);++// ============ Disclaimer Section ============+interface DisclaimerProps {+ title?: string;+ content: string;+ type?: 'standard' | 'legal' | 'confidential';+}++export const DisclaimerSection: React.FC<DisclaimerProps> = ({+ title,+ content,+ type = 'standard'+}) => {+ const styles = {+ standard: { bg: '#f5f5f5', border: '#ddd' },+ legal: { bg: '#fff8e1', border: '#ffa500' },+ confidential: { bg: '#ffebee', border: '#f44336' },+ };++ const defaultTitles = {+ standard: 'Disclaimer',+ legal: 'Legal Notice',+ confidential: 'Confidential',+ };++ const style = styles[type];++ return (+ <div+ className="mt-8 p-4 rounded text-xs"+ style={{ backgroundColor: style.bg, border: `1px solid ${style.border}` }}+ >+ <h4 className="font-bold text-gray-700 mb-2 uppercase text-[10px]">+ {title || defaultTitles[type]}+ </h4>+ <p className="text-gray-600 leading-relaxed">{content}</p>+ </div>+ );+};++// ============ Section Header ============+interface SectionHeaderProps {+ number?: string;+ title: string;+ subtitle?: string;+}++export const SectionHeader: React.FC<SectionHeaderProps> = ({ number, title, subtitle }) => (+ <div className="mb-4 pb-2 border-b-2 border-[#FFA500]">+ <div className="flex items-baseline gap-3">+ {number && (+ <span className="text-2xl font-bold text-[#FFA500]">{number}</span>+ )}+ <h2 className="text-xl font-bold text-gray-800">{title}</h2>+ </div>+ {subtitle && <p className="text-sm text-gray-500 mt-1">{subtitle}</p>}+ </div>+);++// ============ Page Number ============+interface PageNumberProps {+ current: number;+ total?: number;+ format?: 'numeric' | 'roman';+ position?: 'left' | 'center' | 'right';+}++export const PageNumber: React.FC<PageNumberProps> = ({+ current,+ total,+ format = 'numeric',+ position = 'center'+}) => {+ const toRoman = (num: number): string => {+ const romanNumerals: [number, string][] = [+ [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'],+ [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'],+ [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I']+ ];+ let result = '';+ for (const [value, symbol] of romanNumerals) {+ while (num >= value) {+ result += symbol;+ num -= value;+ }+ }+ return result;+ };++ const formatNumber = (n: number) => format === 'roman' ? toRoman(n) : n.toString();++ return (+ <div className={`text-xs text-gray-500 text-${position}`}>+ {total ? `${formatNumber(current)} / ${formatNumber(total)}` : formatNumber(current)}+ </div>+ );+};++export default {+ QuoteBox,+ ListComponent,+ Footnote,+ FootnotesList,+ TableOfContents,+ Watermark,+ QRCodeComponent,+ SignatureBlock,+ DisclaimerSection,+ SectionHeader,+ PageNumber,+};diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/AdvancedStylingPanel.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/AdvancedStylingPanel.tsxnew file mode 100644index 000000000..22a87fe70--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/AdvancedStylingPanel.tsx@@ -0,0 +1,1434 @@+import React, { useState, useEffect, useCallback } from 'react';+import {+ Palette,+ Type,+ Image as ImageIcon,+ Code,+ FileText,+ Save,+ Trash2,+ Plus,+ ChevronDown,+ ChevronRight,+ Copy,+ Check,+ Edit2,+ X,+ AlignLeft,+ AlignCenter,+ AlignRight,+ AlignJustify,+ LayoutTemplate,+ Bookmark,+ Settings2,+ Layers,+ RefreshCw,+} from 'lucide-react';+import {+ brandKitService,+ BrandKit,+ BrandColor,+ BrandFont,+ BrandLogo,+ ComponentTemplate,+ HeaderFooterTemplate,+ ParagraphStyles,+} from '@/services/core/brandKitService';+import { open } from '@tauri-apps/plugin-dialog';+import { toast } from 'sonner';++// Fincept color palette+const FINCEPT_COLORS = {+ ORANGE: '#FFA500',+ WHITE: '#FFFFFF',+ BLACK: '#000000',+ DARK_BG: '#0a0a0a',+ PANEL_BG: '#1a1a1a',+ BORDER: '#333333',+ HOVER: '#2a2a2a',+ TEXT_PRIMARY: '#FFFFFF',+ TEXT_SECONDARY: '#999999',+};++interface AdvancedStylingPanelProps {+ onBrandKitChange?: (brandKit: BrandKit) => void;+ onComponentTemplateSelect?: (template: ComponentTemplate) => void;+ onStylesChange?: (styles: {+ customCSS: string;+ headerTemplate: HeaderFooterTemplate;+ footerTemplate: HeaderFooterTemplate;+ paragraphStyles: ParagraphStyles;+ }) => void;+}++type TabType = 'brandKit' | 'templates' | 'headerFooter' | 'typography' | 'customCSS';++export const AdvancedStylingPanel: React.FC<AdvancedStylingPanelProps> = ({+ onBrandKitChange,+ onComponentTemplateSelect,+ onStylesChange,+}) => {+ const [activeTab, setActiveTab] = useState<TabType>('brandKit');+ const [brandKits, setBrandKits] = useState<BrandKit[]>([]);+ const [activeBrandKit, setActiveBrandKit] = useState<BrandKit | null>(null);+ const [componentTemplates, setComponentTemplates] = useState<ComponentTemplate[]>([]);+ const [isEditing, setIsEditing] = useState(false);+ const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({+ colors: true,+ fonts: true,+ logos: false,+ });++ // Load data on mount+ useEffect(() => {+ loadData();+ }, []);++ const loadData = async () => {+ try {+ const kits = await brandKitService.getAllBrandKits();+ setBrandKits(kits);++ const active = await brandKitService.getActiveBrandKit();+ setActiveBrandKit(active);++ const templates = await brandKitService.getAllComponentTemplates();+ setComponentTemplates(templates);+ } catch (error) {+ console.error('Error loading styling data:', error);+ toast.error('Failed to load styling data');+ }+ };++ const handleSaveBrandKit = async () => {+ if (!activeBrandKit) return;+ try {+ await brandKitService.saveBrandKit(activeBrandKit);+ await brandKitService.setActiveBrandKit(activeBrandKit.id);+ toast.success('Brand kit saved');+ onBrandKitChange?.(activeBrandKit);+ loadData();+ } catch (error) {+ toast.error('Failed to save brand kit');+ }+ };++ const handleCreateNewBrandKit = async () => {+ const newKit = brandKitService.getDefaultBrandKit();+ newKit.name = `Brand Kit ${brandKits.length + 1}`;+ newKit.isDefault = false;+ setActiveBrandKit(newKit);+ setIsEditing(true);+ };++ const handleDeleteBrandKit = async (id: string) => {+ try {+ await brandKitService.deleteBrandKit(id);+ toast.success('Brand kit deleted');+ loadData();+ } catch (error) {+ toast.error('Failed to delete brand kit');+ }+ };++ const toggleSection = (section: string) => {+ setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));+ };++ const updateBrandKitColor = (colorId: string, updates: Partial<BrandColor>) => {+ if (!activeBrandKit) return;+ setActiveBrandKit({+ ...activeBrandKit,+ colors: activeBrandKit.colors.map(c =>+ c.id === colorId ? { ...c, ...updates } : c+ ),+ });+ };++ const updateBrandKitFont = (fontId: string, updates: Partial<BrandFont>) => {+ if (!activeBrandKit) return;+ setActiveBrandKit({+ ...activeBrandKit,+ fonts: activeBrandKit.fonts.map(f =>+ f.id === fontId ? { ...f, ...updates } : f+ ),+ });+ };++ const addColor = () => {+ if (!activeBrandKit) return;+ const newColor: BrandColor = {+ id: `color-${Date.now()}`,+ name: 'New Color',+ hex: '#888888',+ usage: 'custom',+ };+ setActiveBrandKit({+ ...activeBrandKit,+ colors: [...activeBrandKit.colors, newColor],+ });+ };++ const removeColor = (colorId: string) => {+ if (!activeBrandKit) return;+ setActiveBrandKit({+ ...activeBrandKit,+ colors: activeBrandKit.colors.filter(c => c.id !== colorId),+ });+ };++ const handleLogoUpload = async () => {+ try {+ const selected = await open({+ multiple: false,+ filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'svg'] }],+ });++ if (selected && typeof selected === 'string' && activeBrandKit) {+ const newLogo: BrandLogo = {+ id: `logo-${Date.now()}`,+ name: selected.split(/[/\\]/).pop() || 'Logo',+ path: selected,+ type: 'primary',+ };+ setActiveBrandKit({+ ...activeBrandKit,+ logos: [...activeBrandKit.logos, newLogo],+ });+ toast.success('Logo added');+ }+ } catch (error) {+ toast.error('Failed to upload logo');+ }+ };++ const renderTabButton = (tab: TabType, icon: React.ReactNode, label: string) => (+ <button+ onClick={() => setActiveTab(tab)}+ className={`flex items-center gap-2 px-3 py-2 text-xs rounded transition-colors ${+ activeTab === tab+ ? 'bg-[#FFA500] text-black font-semibold'+ : 'bg-transparent hover:bg-[#2a2a2a] text-gray-300'+ }`}+ >+ {icon}+ <span>{label}</span>+ </button>+ );++ return (+ <div className="h-full flex flex-col" style={{ backgroundColor: FINCEPT_COLORS.PANEL_BG }}>+ {/* Tab Navigation */}+ <div className="flex flex-wrap gap-1 p-2 border-b" style={{ borderColor: FINCEPT_COLORS.BORDER }}>+ {renderTabButton('brandKit', <Palette size={14} />, 'Brand Kit')}+ {renderTabButton('templates', <LayoutTemplate size={14} />, 'Templates')}+ {renderTabButton('headerFooter', <Layers size={14} />, 'Header/Footer')}+ {renderTabButton('typography', <Type size={14} />, 'Typography')}+ {renderTabButton('customCSS', <Code size={14} />, 'Custom CSS')}+ </div>++ {/* Content Area */}+ <div className="flex-1 overflow-y-auto p-3">+ {activeTab === 'brandKit' && (+ <BrandKitTab+ brandKits={brandKits}+ activeBrandKit={activeBrandKit}+ setActiveBrandKit={setActiveBrandKit}+ expandedSections={expandedSections}+ toggleSection={toggleSection}+ updateBrandKitColor={updateBrandKitColor}+ updateBrandKitFont={updateBrandKitFont}+ addColor={addColor}+ removeColor={removeColor}+ handleLogoUpload={handleLogoUpload}+ handleSaveBrandKit={handleSaveBrandKit}+ handleCreateNewBrandKit={handleCreateNewBrandKit}+ handleDeleteBrandKit={handleDeleteBrandKit}+ />+ )}++ {activeTab === 'templates' && (+ <ComponentTemplatesTab+ templates={componentTemplates}+ onSelect={onComponentTemplateSelect}+ onRefresh={loadData}+ />+ )}++ {activeTab === 'headerFooter' && (+ <HeaderFooterTab+ brandKit={activeBrandKit}+ onUpdate={(header, footer) => {+ if (activeBrandKit) {+ const updated = {+ ...activeBrandKit,+ headerTemplate: header,+ footerTemplate: footer,+ };+ setActiveBrandKit(updated);+ onStylesChange?.({+ customCSS: updated.customCSS || '',+ headerTemplate: header,+ footerTemplate: footer,+ paragraphStyles: updated.paragraphStyles,+ });+ }+ }}+ />+ )}++ {activeTab === 'typography' && (+ <TypographyTab+ brandKit={activeBrandKit}+ onUpdate={(paragraphStyles) => {+ if (activeBrandKit) {+ const updated = {+ ...activeBrandKit,+ paragraphStyles,+ };+ setActiveBrandKit(updated);+ onStylesChange?.({+ customCSS: updated.customCSS || '',+ headerTemplate: updated.headerTemplate!,+ footerTemplate: updated.footerTemplate!,+ paragraphStyles,+ });+ }+ }}+ />+ )}++ {activeTab === 'customCSS' && (+ <CustomCSSTab+ brandKit={activeBrandKit}+ onUpdate={(css) => {+ if (activeBrandKit) {+ const updated = { ...activeBrandKit, customCSS: css };+ setActiveBrandKit(updated);+ onStylesChange?.({+ customCSS: css,+ headerTemplate: updated.headerTemplate!,+ footerTemplate: updated.footerTemplate!,+ paragraphStyles: updated.paragraphStyles,+ });+ }+ }}+ />+ )}+ </div>+ </div>+ );+};++// ============ Brand Kit Tab ============+interface BrandKitTabProps {+ brandKits: BrandKit[];+ activeBrandKit: BrandKit | null;+ setActiveBrandKit: (kit: BrandKit) => void;+ expandedSections: Record<string, boolean>;+ toggleSection: (section: string) => void;+ updateBrandKitColor: (colorId: string, updates: Partial<BrandColor>) => void;+ updateBrandKitFont: (fontId: string, updates: Partial<BrandFont>) => void;+ addColor: () => void;+ removeColor: (colorId: string) => void;+ handleLogoUpload: () => void;+ handleSaveBrandKit: () => void;+ handleCreateNewBrandKit: () => void;+ handleDeleteBrandKit: (id: string) => void;+}++const BrandKitTab: React.FC<BrandKitTabProps> = ({+ brandKits,+ activeBrandKit,+ setActiveBrandKit,+ expandedSections,+ toggleSection,+ updateBrandKitColor,+ updateBrandKitFont,+ addColor,+ removeColor,+ handleLogoUpload,+ handleSaveBrandKit,+ handleCreateNewBrandKit,+ handleDeleteBrandKit,+}) => {+ const availableFonts = brandKitService.getAvailableFonts();+ const presetKits = brandKitService.getPresetBrandKits();++ return (+ <div className="space-y-4">+ {/* Brand Kit Selector */}+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <label className="text-xs font-semibold" style={{ color: FINCEPT_COLORS.ORANGE }}>+ SELECT BRAND KIT+ </label>+ <button+ onClick={handleCreateNewBrandKit}+ className="p-1 rounded hover:bg-[#2a2a2a] transition-colors"+ title="Create New"+ >+ <Plus size={14} style={{ color: FINCEPT_COLORS.ORANGE }} />+ </button>+ </div>+ <select+ value={activeBrandKit?.id || ''}+ onChange={(e) => {+ const kit = brandKits.find(k => k.id === e.target.value);+ if (kit) setActiveBrandKit(kit);+ }}+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none text-white"+ >+ {brandKits.map(kit => (+ <option key={kit.id} value={kit.id}>{kit.name}</option>+ ))}+ </select>+ </div>++ {/* Preset Brand Kits */}+ <div className="space-y-2">+ <label className="text-xs font-semibold" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>+ QUICK PRESETS+ </label>+ <div className="grid grid-cols-2 gap-2">+ {presetKits.map((preset, idx) => (+ <button+ key={idx}+ onClick={() => {+ if (activeBrandKit) {+ setActiveBrandKit({+ ...activeBrandKit,+ colors: preset.colors as BrandColor[],+ fonts: preset.fonts as BrandFont[],+ });+ }+ }}+ className="px-2 py-2 text-[10px] rounded border border-[#333333] hover:border-[#FFA500] transition-colors text-left"+ >+ <div className="flex gap-1 mb-1">+ {preset.colors?.slice(0, 4).map((c, i) => (+ <div+ key={i}+ className="w-3 h-3 rounded-full"+ style={{ backgroundColor: c.hex }}+ />+ ))}+ </div>+ <span className="text-gray-300">{preset.name}</span>+ </button>+ ))}+ </div>+ </div>++ {activeBrandKit && (+ <>+ {/* Brand Kit Name */}+ <div className="space-y-1">+ <label className="text-xs" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>+ Brand Kit Name+ </label>+ <input+ type="text"+ value={activeBrandKit.name}+ onChange={(e) => setActiveBrandKit({ ...activeBrandKit, name: e.target.value })}+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none text-white"+ />+ </div>++ {/* Colors Section */}+ <div className="border border-[#333333] rounded">+ <button+ onClick={() => toggleSection('colors')}+ className="w-full flex items-center justify-between p-3 hover:bg-[#2a2a2a] transition-colors"+ >+ <div className="flex items-center gap-2">+ <Palette size={14} style={{ color: FINCEPT_COLORS.ORANGE }} />+ <span className="text-xs font-semibold text-white">Colors</span>+ </div>+ {expandedSections.colors ? <ChevronDown size={14} /> : <ChevronRight size={14} />}+ </button>+ {expandedSections.colors && (+ <div className="p-3 pt-0 space-y-2">+ {activeBrandKit.colors.map((color) => (+ <div key={color.id} className="flex items-center gap-2">+ <input+ type="color"+ value={color.hex}+ onChange={(e) => updateBrandKitColor(color.id, { hex: e.target.value })}+ className="w-8 h-8 rounded cursor-pointer border-0"+ />+ <input+ type="text"+ value={color.name}+ onChange={(e) => updateBrandKitColor(color.id, { name: e.target.value })}+ className="flex-1 px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none text-white"+ />+ <select+ value={color.usage}+ onChange={(e) => updateBrandKitColor(color.id, { usage: e.target.value as any })}+ className="px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none text-white"+ >+ <option value="primary">Primary</option>+ <option value="secondary">Secondary</option>+ <option value="accent">Accent</option>+ <option value="background">Background</option>+ <option value="text">Text</option>+ <option value="custom">Custom</option>+ </select>+ <button+ onClick={() => removeColor(color.id)}+ className="p-1 hover:bg-[#333333] rounded text-red-500"+ >+ <X size={14} />+ </button>+ </div>+ ))}+ <button+ onClick={addColor}+ className="w-full py-2 text-xs rounded border border-dashed border-[#333333] hover:border-[#FFA500] transition-colors text-gray-400 hover:text-[#FFA500]"+ >+ + Add Color+ </button>+ </div>+ )}+ </div>++ {/* Fonts Section */}+ <div className="border border-[#333333] rounded">+ <button+ onClick={() => toggleSection('fonts')}+ className="w-full flex items-center justify-between p-3 hover:bg-[#2a2a2a] transition-colors"+ >+ <div className="flex items-center gap-2">+ <Type size={14} style={{ color: FINCEPT_COLORS.ORANGE }} />+ <span className="text-xs font-semibold text-white">Fonts</span>+ </div>+ {expandedSections.fonts ? <ChevronDown size={14} /> : <ChevronRight size={14} />}+ </button>+ {expandedSections.fonts && (+ <div className="p-3 pt-0 space-y-3">+ {activeBrandKit.fonts.map((font) => (+ <div key={font.id} className="space-y-1">+ <label className="text-[10px] text-gray-400 capitalize">{font.usage} Font</label>+ <div className="flex gap-2">+ <select+ value={font.family}+ onChange={(e) => updateBrandKitFont(font.id, { family: e.target.value })}+ className="flex-1 px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none text-white"+ >+ {availableFonts.map(f => (+ <option key={f.family} value={f.family}>{f.name}</option>+ ))}+ </select>+ <select+ value={font.weight}+ onChange={(e) => updateBrandKitFont(font.id, { weight: e.target.value })}+ className="w-24 px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none text-white"+ >+ <option value="300">Light</option>+ <option value="400">Regular</option>+ <option value="500">Medium</option>+ <option value="600">Semi-Bold</option>+ <option value="700">Bold</option>+ <option value="800">Extra Bold</option>+ </select>+ </div>+ <div+ className="p-2 bg-[#0a0a0a] rounded text-sm"+ style={{ fontFamily: font.family, fontWeight: font.weight }}+ >+ The quick brown fox jumps over the lazy dog+ </div>+ </div>+ ))}+ </div>+ )}+ </div>++ {/* Logos Section */}+ <div className="border border-[#333333] rounded">+ <button+ onClick={() => toggleSection('logos')}+ className="w-full flex items-center justify-between p-3 hover:bg-[#2a2a2a] transition-colors"+ >+ <div className="flex items-center gap-2">+ <ImageIcon size={14} style={{ color: FINCEPT_COLORS.ORANGE }} />+ <span className="text-xs font-semibold text-white">Logos</span>+ </div>+ {expandedSections.logos ? <ChevronDown size={14} /> : <ChevronRight size={14} />}+ </button>+ {expandedSections.logos && (+ <div className="p-3 pt-0 space-y-2">+ {activeBrandKit.logos.length === 0 ? (+ <p className="text-xs text-gray-500 text-center py-2">No logos added</p>+ ) : (+ activeBrandKit.logos.map((logo) => (+ <div key={logo.id} className="flex items-center gap-2 p-2 bg-[#0a0a0a] rounded">+ <ImageIcon size={16} className="text-gray-400" />+ <span className="flex-1 text-xs text-gray-300 truncate">{logo.name}</span>+ <span className="text-[10px] text-gray-500 capitalize">{logo.type}</span>+ </div>+ ))+ )}+ <button+ onClick={handleLogoUpload}+ className="w-full py-2 text-xs rounded border border-dashed border-[#333333] hover:border-[#FFA500] transition-colors text-gray-400 hover:text-[#FFA500]"+ >+ + Upload Logo+ </button>+ </div>+ )}+ </div>++ {/* Save Button */}+ <button+ onClick={handleSaveBrandKit}+ className="w-full py-2 text-xs font-semibold rounded transition-colors flex items-center justify-center gap-2"+ style={{ backgroundColor: FINCEPT_COLORS.ORANGE, color: FINCEPT_COLORS.BLACK }}+ >+ <Save size={14} />+ Save Brand Kit+ </button>+ </>+ )}+ </div>+ );+};++// ============ Component Templates Tab ============+interface ComponentTemplatesTabProps {+ templates: ComponentTemplate[];+ onSelect?: (template: ComponentTemplate) => void;+ onRefresh: () => void;+}++const ComponentTemplatesTab: React.FC<ComponentTemplatesTabProps> = ({+ templates,+ onSelect,+ onRefresh,+}) => {+ const [selectedCategory, setSelectedCategory] = useState<string>('all');++ const categories = ['all', 'text', 'layout', 'data', 'media', 'custom'];+ const filteredTemplates = selectedCategory === 'all'+ ? templates+ : templates.filter(t => t.category === selectedCategory);++ const handleSaveAsTemplate = async (template: ComponentTemplate) => {+ try {+ await brandKitService.saveComponentTemplate(template);+ toast.success('Template saved');+ onRefresh();+ } catch (error) {+ toast.error('Failed to save template');+ }+ };++ const handleDeleteTemplate = async (id: string) => {+ try {+ await brandKitService.deleteComponentTemplate(id);+ toast.success('Template deleted');+ onRefresh();+ } catch (error) {+ toast.error('Failed to delete template');+ }+ };++ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <label className="text-xs font-semibold" style={{ color: FINCEPT_COLORS.ORANGE }}>+ COMPONENT TEMPLATES+ </label>+ <button+ onClick={onRefresh}+ className="p-1 rounded hover:bg-[#2a2a2a] transition-colors"+ title="Refresh"+ >+ <RefreshCw size={14} className="text-gray-400" />+ </button>+ </div>++ {/* Category Filter */}+ <div className="flex flex-wrap gap-1">+ {categories.map(cat => (+ <button+ key={cat}+ onClick={() => setSelectedCategory(cat)}+ className={`px-2 py-1 text-[10px] rounded capitalize transition-colors ${+ selectedCategory === cat+ ? 'bg-[#FFA500] text-black'+ : 'bg-[#0a0a0a] text-gray-400 hover:bg-[#2a2a2a]'+ }`}+ >+ {cat}+ </button>+ ))}+ </div>++ {/* Templates Grid */}+ <div className="space-y-2">+ {filteredTemplates.length === 0 ? (+ <p className="text-xs text-gray-500 text-center py-4">No templates in this category</p>+ ) : (+ filteredTemplates.map(template => (+ <div+ key={template.id}+ className="p-3 bg-[#0a0a0a] rounded border border-[#333333] hover:border-[#FFA500] transition-colors cursor-pointer"+ onClick={() => onSelect?.(template)}+ >+ <div className="flex items-start justify-between mb-2">+ <div>+ <h4 className="text-xs font-semibold text-white">{template.name}</h4>+ <p className="text-[10px] text-gray-500">{template.description}</p>+ </div>+ <div className="flex gap-1">+ <button+ onClick={(e) => {+ e.stopPropagation();+ onSelect?.(template);+ }}+ className="p-1 rounded hover:bg-[#2a2a2a]"+ title="Use Template"+ >+ <Plus size={12} style={{ color: FINCEPT_COLORS.ORANGE }} />+ </button>+ <button+ onClick={(e) => {+ e.stopPropagation();+ handleDeleteTemplate(template.id);+ }}+ className="p-1 rounded hover:bg-[#2a2a2a]"+ title="Delete"+ >+ <Trash2 size={12} className="text-red-500" />+ </button>+ </div>+ </div>+ <div className="flex items-center gap-2">+ <span className="text-[9px] px-2 py-0.5 rounded bg-[#1a1a1a] text-gray-400 capitalize">+ {template.category}+ </span>+ <span className="text-[9px] px-2 py-0.5 rounded bg-[#1a1a1a] text-gray-400">+ {template.component.type}+ </span>+ </div>+ </div>+ ))+ )}+ </div>++ {/* Info */}+ <div className="p-3 bg-[#0a0a0a] rounded border border-[#333333]">+ <p className="text-[10px] text-gray-500">+ Click on a template to add it to your report. You can also save custom components as templates+ from the Properties panel.+ </p>+ </div>+ </div>+ );+};++// ============ Header/Footer Tab ============+interface HeaderFooterTabProps {+ brandKit: BrandKit | null;+ onUpdate: (header: HeaderFooterTemplate, footer: HeaderFooterTemplate) => void;+}++const HeaderFooterTab: React.FC<HeaderFooterTabProps> = ({ brandKit, onUpdate }) => {+ const [editingSection, setEditingSection] = useState<'header' | 'footer'>('header');++ if (!brandKit) {+ return (+ <div className="text-center py-8 text-gray-500 text-xs">+ Select a brand kit first+ </div>+ );+ }++ const template = editingSection === 'header' ? brandKit.headerTemplate : brandKit.footerTemplate;++ const updateTemplate = (updates: Partial<HeaderFooterTemplate>) => {+ const newHeader = editingSection === 'header'+ ? { ...brandKit.headerTemplate!, ...updates }+ : brandKit.headerTemplate!;+ const newFooter = editingSection === 'footer'+ ? { ...brandKit.footerTemplate!, ...updates }+ : brandKit.footerTemplate!;+ onUpdate(newHeader, newFooter);+ };++ return (+ <div className="space-y-4">+ <label className="text-xs font-semibold" style={{ color: FINCEPT_COLORS.ORANGE }}>+ HEADER & FOOTER+ </label>++ {/* Section Toggle */}+ <div className="flex gap-2">+ <button+ onClick={() => setEditingSection('header')}+ className={`flex-1 py-2 text-xs rounded transition-colors ${+ editingSection === 'header'+ ? 'bg-[#FFA500] text-black font-semibold'+ : 'bg-[#0a0a0a] text-gray-400'+ }`}+ >+ Header+ </button>+ <button+ onClick={() => setEditingSection('footer')}+ className={`flex-1 py-2 text-xs rounded transition-colors ${+ editingSection === 'footer'+ ? 'bg-[#FFA500] text-black font-semibold'+ : 'bg-[#0a0a0a] text-gray-400'+ }`}+ >+ Footer+ </button>+ </div>++ {template && (+ <div className="space-y-3">+ {/* Enable Toggle */}+ <div className="flex items-center justify-between">+ <label className="text-xs text-gray-300">Enable {editingSection}</label>+ <button+ onClick={() => updateTemplate({ enabled: !template.enabled })}+ className={`w-10 h-5 rounded-full transition-colors ${+ template.enabled ? 'bg-[#FFA500]' : 'bg-[#333333]'+ }`}+ >+ <div+ className={`w-4 h-4 rounded-full bg-white transition-transform ${+ template.enabled ? 'translate-x-5' : 'translate-x-0.5'+ }`}+ />+ </button>+ </div>++ {template.enabled && (+ <>+ {/* Content */}+ <div className="space-y-1">+ <label className="text-[10px] text-gray-500">+ Content (use {'{company}'}, {'{date}'}, {'{title}'})+ </label>+ <input+ type="text"+ value={template.content}+ onChange={(e) => updateTemplate({ content: e.target.value })}+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none text-white"+ placeholder="Enter content..."+ />+ </div>++ {/* Alignment */}+ <div className="space-y-1">+ <label className="text-[10px] text-gray-500">Text Alignment</label>+ <div className="flex gap-2">+ {(['left', 'center', 'right'] as const).map(align => (+ <button+ key={align}+ onClick={() => updateTemplate({ alignment: align })}+ className={`flex-1 py-2 rounded transition-colors ${+ template.alignment === align+ ? 'bg-[#FFA500] text-black'+ : 'bg-[#0a0a0a] text-gray-400'+ }`}+ >+ {align === 'left' && <AlignLeft size={14} className="mx-auto" />}+ {align === 'center' && <AlignCenter size={14} className="mx-auto" />}+ {align === 'right' && <AlignRight size={14} className="mx-auto" />}+ </button>+ ))}+ </div>+ </div>++ {/* Page Numbers */}+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <label className="text-xs text-gray-300">Show Page Numbers</label>+ <button+ onClick={() => updateTemplate({ showPageNumbers: !template.showPageNumbers })}+ className={`w-10 h-5 rounded-full transition-colors ${+ template.showPageNumbers ? 'bg-[#FFA500]' : 'bg-[#333333]'+ }`}+ >+ <div+ className={`w-4 h-4 rounded-full bg-white transition-transform ${+ template.showPageNumbers ? 'translate-x-5' : 'translate-x-0.5'+ }`}+ />+ </button>+ </div>++ {template.showPageNumbers && (+ <div className="grid grid-cols-2 gap-2">+ <div>+ <label className="text-[10px] text-gray-500">Format</label>+ <select+ value={template.pageNumberFormat}+ onChange={(e) => updateTemplate({ pageNumberFormat: 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 text-white"+ >+ <option value="numeric">1, 2, 3...</option>+ <option value="roman">I, II, III...</option>+ <option value="alphanumeric">A, B, C...</option>+ </select>+ </div>+ <div>+ <label className="text-[10px] text-gray-500">Position</label>+ <select+ value={template.pageNumberPosition}+ onChange={(e) => updateTemplate({ pageNumberPosition: 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 text-white"+ >+ <option value="left">Left</option>+ <option value="center">Center</option>+ <option value="right">Right</option>+ </select>+ </div>+ </div>+ )}+ </div>++ {/* Colors */}+ <div className="grid grid-cols-2 gap-2">+ <div className="space-y-1">+ <label className="text-[10px] text-gray-500">Background</label>+ <div className="flex gap-2">+ <input+ type="color"+ value={template.backgroundColor || '#FFFFFF'}+ onChange={(e) => updateTemplate({ backgroundColor: e.target.value })}+ className="w-8 h-8 rounded cursor-pointer"+ />+ <input+ type="text"+ value={template.backgroundColor || '#FFFFFF'}+ onChange={(e) => updateTemplate({ backgroundColor: e.target.value })}+ className="flex-1 px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none text-white"+ />+ </div>+ </div>+ <div className="space-y-1">+ <label className="text-[10px] text-gray-500">Text Color</label>+ <div className="flex gap-2">+ <input+ type="color"+ value={template.textColor || '#666666'}+ onChange={(e) => updateTemplate({ textColor: e.target.value })}+ className="w-8 h-8 rounded cursor-pointer"+ />+ <input+ type="text"+ value={template.textColor || '#666666'}+ onChange={(e) => updateTemplate({ textColor: e.target.value })}+ className="flex-1 px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none text-white"+ />+ </div>+ </div>+ </div>++ {/* Font Size & Height */}+ <div className="grid grid-cols-2 gap-2">+ <div className="space-y-1">+ <label className="text-[10px] text-gray-500">Font Size (pt)</label>+ <input+ type="number"+ value={template.fontSize || 10}+ onChange={(e) => updateTemplate({ fontSize: Number(e.target.value) })}+ min={6}+ max={16}+ className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none text-white"+ />+ </div>+ <div className="space-y-1">+ <label className="text-[10px] text-gray-500">Height (px)</label>+ <input+ type="number"+ value={template.height || 30}+ onChange={(e) => updateTemplate({ height: Number(e.target.value) })}+ min={20}+ max={100}+ className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none text-white"+ />+ </div>+ </div>++ {/* Border */}+ <div className="flex items-center justify-between">+ <label className="text-xs text-gray-300">+ {editingSection === 'header' ? 'Border Bottom' : 'Border Top'}+ </label>+ <button+ onClick={() => {+ if (editingSection === 'header') {+ updateTemplate({ borderBottom: !template.borderBottom });+ } else {+ updateTemplate({ borderTop: !template.borderTop });+ }+ }}+ className={`w-10 h-5 rounded-full transition-colors ${+ (editingSection === 'header' ? template.borderBottom : template.borderTop)+ ? 'bg-[#FFA500]'+ : 'bg-[#333333]'+ }`}+ >+ <div+ className={`w-4 h-4 rounded-full bg-white transition-transform ${+ (editingSection === 'header' ? template.borderBottom : template.borderTop)+ ? 'translate-x-5'+ : 'translate-x-0.5'+ }`}+ />+ </button>+ </div>++ {/* Show Date */}+ <div className="flex items-center justify-between">+ <label className="text-xs text-gray-300">Show Date</label>+ <button+ onClick={() => updateTemplate({ showDate: !template.showDate })}+ className={`w-10 h-5 rounded-full transition-colors ${+ template.showDate ? 'bg-[#FFA500]' : 'bg-[#333333]'+ }`}+ >+ <div+ className={`w-4 h-4 rounded-full bg-white transition-transform ${+ template.showDate ? 'translate-x-5' : 'translate-x-0.5'+ }`}+ />+ </button>+ </div>+ </>+ )}+ </div>+ )}++ {/* Preview */}+ <div className="space-y-2">+ <label className="text-[10px] text-gray-500">Preview</label>+ <div className="bg-white p-4 rounded">+ {brandKit.headerTemplate?.enabled && (+ <div+ className="mb-4 pb-2"+ style={{+ borderBottom: brandKit.headerTemplate.borderBottom ? '1px solid #E0E0E0' : 'none',+ fontSize: `${brandKit.headerTemplate.fontSize}pt`,+ color: brandKit.headerTemplate.textColor,+ backgroundColor: brandKit.headerTemplate.backgroundColor,+ textAlign: brandKit.headerTemplate.alignment,+ minHeight: brandKit.headerTemplate.height,+ display: 'flex',+ alignItems: 'center',+ justifyContent: brandKit.headerTemplate.alignment === 'center' ? 'center' :+ brandKit.headerTemplate.alignment === 'right' ? 'flex-end' : 'flex-start',+ }}+ >+ <span>{brandKit.headerTemplate.content.replace('{company}', 'Your Company')}</span>+ {brandKit.headerTemplate.showPageNumbers && brandKit.headerTemplate.pageNumberPosition !== brandKit.headerTemplate.alignment && (+ <span className="ml-auto">Page 1</span>+ )}+ </div>+ )}+ <div className="h-20 bg-gray-100 rounded flex items-center justify-center text-gray-400 text-xs">+ Report Content+ </div>+ {brandKit.footerTemplate?.enabled && (+ <div+ className="mt-4 pt-2"+ style={{+ borderTop: brandKit.footerTemplate.borderTop ? '1px solid #E0E0E0' : 'none',+ fontSize: `${brandKit.footerTemplate.fontSize}pt`,+ color: brandKit.footerTemplate.textColor,+ backgroundColor: brandKit.footerTemplate.backgroundColor,+ textAlign: brandKit.footerTemplate.alignment,+ minHeight: brandKit.footerTemplate.height,+ display: 'flex',+ alignItems: 'center',+ justifyContent: brandKit.footerTemplate.alignment === 'center' ? 'center' :+ brandKit.footerTemplate.alignment === 'right' ? 'flex-end' : 'flex-start',+ }}+ >+ <span>{brandKit.footerTemplate.content.replace('{company}', 'Your Company')}</span>+ {brandKit.footerTemplate.showPageNumbers && (+ <span className={brandKit.footerTemplate.pageNumberPosition === 'center' ? '' : 'ml-auto'}>+ {brandKit.footerTemplate.pageNumberPosition === 'center' ? ' - Page 1 -' : 'Page 1'}+ </span>+ )}+ </div>+ )}+ </div>+ </div>+ </div>+ );+};++// ============ Typography Tab ============+interface TypographyTabProps {+ brandKit: BrandKit | null;+ onUpdate: (styles: ParagraphStyles) => void;+}++const TypographyTab: React.FC<TypographyTabProps> = ({ brandKit, onUpdate }) => {+ if (!brandKit) {+ return (+ <div className="text-center py-8 text-gray-500 text-xs">+ Select a brand kit first+ </div>+ );+ }++ const styles = brandKit.paragraphStyles;++ const updateStyles = (updates: Partial<ParagraphStyles>) => {+ onUpdate({ ...styles, ...updates });+ };++ return (+ <div className="space-y-4">+ <label className="text-xs font-semibold" style={{ color: FINCEPT_COLORS.ORANGE }}>+ PARAGRAPH & LINE SPACING+ </label>++ {/* Line Height */}+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <label className="text-xs text-gray-300">Line Height</label>+ <span className="text-xs text-[#FFA500]">{styles.lineHeight.toFixed(2)}</span>+ </div>+ <input+ type="range"+ min="1"+ max="3"+ step="0.1"+ value={styles.lineHeight}+ onChange={(e) => updateStyles({ lineHeight: Number(e.target.value) })}+ className="w-full"+ style={{ accentColor: FINCEPT_COLORS.ORANGE }}+ />+ <div className="flex justify-between text-[10px] text-gray-500">+ <span>Tight (1.0)</span>+ <span>Normal (1.5)</span>+ <span>Loose (3.0)</span>+ </div>+ </div>++ {/* Paragraph Spacing */}+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <label className="text-xs text-gray-300">Paragraph Spacing</label>+ <span className="text-xs text-[#FFA500]">{styles.paragraphSpacing}px</span>+ </div>+ <input+ type="range"+ min="0"+ max="48"+ step="4"+ value={styles.paragraphSpacing}+ onChange={(e) => updateStyles({ paragraphSpacing: Number(e.target.value) })}+ className="w-full"+ style={{ accentColor: FINCEPT_COLORS.ORANGE }}+ />+ </div>++ {/* Text Indent */}+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <label className="text-xs text-gray-300">First Line Indent</label>+ <span className="text-xs text-[#FFA500]">{styles.textIndent}px</span>+ </div>+ <input+ type="range"+ min="0"+ max="50"+ step="5"+ value={styles.textIndent}+ onChange={(e) => updateStyles({ textIndent: Number(e.target.value) })}+ className="w-full"+ style={{ accentColor: FINCEPT_COLORS.ORANGE }}+ />+ </div>++ {/* Letter Spacing */}+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <label className="text-xs text-gray-300">Letter Spacing</label>+ <span className="text-xs text-[#FFA500]">{styles.letterSpacing}px</span>+ </div>+ <input+ type="range"+ min="-2"+ max="10"+ step="0.5"+ value={styles.letterSpacing}+ onChange={(e) => updateStyles({ letterSpacing: Number(e.target.value) })}+ className="w-full"+ style={{ accentColor: FINCEPT_COLORS.ORANGE }}+ />+ </div>++ {/* Word Spacing */}+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <label className="text-xs text-gray-300">Word Spacing</label>+ <span className="text-xs text-[#FFA500]">{styles.wordSpacing}px</span>+ </div>+ <input+ type="range"+ min="0"+ max="20"+ step="1"+ value={styles.wordSpacing}+ onChange={(e) => updateStyles({ wordSpacing: Number(e.target.value) })}+ className="w-full"+ style={{ accentColor: FINCEPT_COLORS.ORANGE }}+ />+ </div>++ {/* Text Alignment */}+ <div className="space-y-2">+ <label className="text-xs text-gray-300">Default Text Alignment</label>+ <div className="flex gap-2">+ {([+ { value: 'left', icon: AlignLeft },+ { value: 'center', icon: AlignCenter },+ { value: 'right', icon: AlignRight },+ { value: 'justify', icon: AlignJustify },+ ] as const).map(({ value, icon: Icon }) => (+ <button+ key={value}+ onClick={() => updateStyles({ textAlign: value })}+ className={`flex-1 py-2 rounded transition-colors ${+ styles.textAlign === value+ ? 'bg-[#FFA500] text-black'+ : 'bg-[#0a0a0a] text-gray-400 hover:bg-[#2a2a2a]'+ }`}+ title={value.charAt(0).toUpperCase() + value.slice(1)}+ >+ <Icon size={14} className="mx-auto" />+ </button>+ ))}+ </div>+ </div>++ {/* Preview */}+ <div className="space-y-2">+ <label className="text-[10px] text-gray-500">Preview</label>+ <div className="bg-white p-4 rounded text-black">+ <p style={{+ lineHeight: styles.lineHeight,+ marginBottom: `${styles.paragraphSpacing}px`,+ textIndent: `${styles.textIndent}px`,+ letterSpacing: `${styles.letterSpacing}px`,+ wordSpacing: `${styles.wordSpacing}px`,+ textAlign: styles.textAlign,+ }}>+ This is a sample paragraph demonstrating the typography settings. Notice how the line height,+ paragraph spacing, and text alignment affect the overall readability and appearance of the text.+ </p>+ <p style={{+ lineHeight: styles.lineHeight,+ marginBottom: `${styles.paragraphSpacing}px`,+ textIndent: `${styles.textIndent}px`,+ letterSpacing: `${styles.letterSpacing}px`,+ wordSpacing: `${styles.wordSpacing}px`,+ textAlign: styles.textAlign,+ }}>+ A second paragraph shows the spacing between paragraphs. Professional reports often use+ consistent typography to maintain visual coherence throughout the document.+ </p>+ </div>+ </div>++ {/* Presets */}+ <div className="space-y-2">+ <label className="text-xs text-gray-500">Quick Presets</label>+ <div className="grid grid-cols-2 gap-2">+ <button+ onClick={() => updateStyles({+ lineHeight: 1.5,+ paragraphSpacing: 12,+ textIndent: 0,+ letterSpacing: 0,+ wordSpacing: 0,+ textAlign: 'left',+ })}+ className="px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors text-gray-300"+ >+ Default+ </button>+ <button+ onClick={() => updateStyles({+ lineHeight: 2.0,+ paragraphSpacing: 16,+ textIndent: 20,+ letterSpacing: 0,+ wordSpacing: 0,+ textAlign: 'justify',+ })}+ className="px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors text-gray-300"+ >+ Academic+ </button>+ <button+ onClick={() => updateStyles({+ lineHeight: 1.4,+ paragraphSpacing: 8,+ textIndent: 0,+ letterSpacing: 0.5,+ wordSpacing: 0,+ textAlign: 'left',+ })}+ className="px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors text-gray-300"+ >+ Compact+ </button>+ <button+ onClick={() => updateStyles({+ lineHeight: 1.8,+ paragraphSpacing: 20,+ textIndent: 0,+ letterSpacing: 0,+ wordSpacing: 2,+ textAlign: 'left',+ })}+ className="px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors text-gray-300"+ >+ Relaxed+ </button>+ </div>+ </div>+ </div>+ );+};++// ============ Custom CSS Tab ============+interface CustomCSSTabProps {+ brandKit: BrandKit | null;+ onUpdate: (css: string) => void;+}++const CustomCSSTab: React.FC<CustomCSSTabProps> = ({ brandKit, onUpdate }) => {+ const [localCSS, setLocalCSS] = useState(brandKit?.customCSS || '');+ const [showGenerated, setShowGenerated] = useState(false);++ useEffect(() => {+ setLocalCSS(brandKit?.customCSS || '');+ }, [brandKit]);++ if (!brandKit) {+ return (+ <div className="text-center py-8 text-gray-500 text-xs">+ Select a brand kit first+ </div>+ );+ }++ const generatedCSS = brandKitService.generateCSSFromBrandKit(brandKit);++ const handleApply = () => {+ onUpdate(localCSS);+ toast.success('Custom CSS applied');+ };++ return (+ <div className="space-y-4">+ <div className="flex items-center justify-between">+ <label className="text-xs font-semibold" style={{ color: FINCEPT_COLORS.ORANGE }}>+ CUSTOM CSS+ </label>+ <button+ onClick={() => setShowGenerated(!showGenerated)}+ className="text-[10px] px-2 py-1 rounded bg-[#0a0a0a] hover:bg-[#2a2a2a] text-gray-400"+ >+ {showGenerated ? 'Hide Generated' : 'Show Generated'}+ </button>+ </div>++ {showGenerated && (+ <div className="space-y-2">+ <label className="text-[10px] text-gray-500">Generated from Brand Kit (read-only)</label>+ <pre className="p-3 text-[10px] rounded bg-[#0a0a0a] border border-[#333333] text-green-400 overflow-x-auto max-h-48 overflow-y-auto">+ {generatedCSS}+ </pre>+ <button+ onClick={() => {+ navigator.clipboard.writeText(generatedCSS);+ toast.success('CSS copied to clipboard');+ }}+ className="text-[10px] px-2 py-1 rounded bg-[#0a0a0a] hover:bg-[#2a2a2a] text-gray-400 flex items-center gap-1"+ >+ <Copy size={12} />+ Copy Generated CSS+ </button>+ </div>+ )}++ {/* Custom CSS Editor */}+ <div className="space-y-2">+ <label className="text-[10px] text-gray-500">Additional Custom CSS</label>+ <textarea+ value={localCSS}+ onChange={(e) => setLocalCSS(e.target.value)}+ className="w-full h-64 px-3 py-2 text-xs font-mono rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none text-green-400 resize-none"+ placeholder="/* Add your custom CSS here */ .report-title { color: #FFA500; font-weight: bold; }"+ spellCheck={false}+ />+ </div>++ {/* CSS Snippets */}+ <div className="space-y-2">+ <label className="text-[10px] text-gray-500">Quick Snippets</label>+ <div className="grid grid-cols-2 gap-2">+ <button+ onClick={() => setLocalCSS(prev => prev + '\n\n/* Highlight Box */\n.highlight {\n background: #FFF8E1;\n border-left: 4px solid #FFA500;\n padding: 15px;\n margin: 10px 0;\n}')}+ className="px-2 py-2 text-[10px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors text-gray-300"+ >+ Highlight Box+ </button>+ <button+ onClick={() => setLocalCSS(prev => prev + '\n\n/* Shadow Card */\n.shadow-card {\n box-shadow: 0 4px 6px rgba(0,0,0,0.1);\n border-radius: 8px;\n padding: 20px;\n}')}+ className="px-2 py-2 text-[10px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors text-gray-300"+ >+ Shadow Card+ </button>+ <button+ onClick={() => setLocalCSS(prev => prev + '\n\n/* Striped Table */\ntable tr:nth-child(even) {\n background-color: #f8f9fa;\n}')}+ className="px-2 py-2 text-[10px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors text-gray-300"+ >+ Striped Table+ </button>+ <button+ onClick={() => setLocalCSS(prev => prev + '\n\n/* Print Styles */\n@media print {\n .no-print { display: none; }\n body { font-size: 12pt; }\n}')}+ className="px-2 py-2 text-[10px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors text-gray-300"+ >+ Print Styles+ </button>+ </div>+ </div>++ {/* Apply Button */}+ <button+ onClick={handleApply}+ className="w-full py-2 text-xs font-semibold rounded transition-colors flex items-center justify-center gap-2"+ style={{ backgroundColor: FINCEPT_COLORS.ORANGE, color: FINCEPT_COLORS.BLACK }}+ >+ <Check size={14} />+ Apply Custom CSS+ </button>++ {/* Help Text */}+ <div className="p-3 bg-[#0a0a0a] rounded border border-[#333333]">+ <p className="text-[10px] text-gray-500">+ Custom CSS will be applied to the generated PDF. Use standard CSS properties.+ The generated CSS from your brand kit settings is automatically included.+ </p>+ </div>+ </div>+ );+};++export default AdvancedStylingPanel;diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/CollaborationFeatures.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/CollaborationFeatures.tsxnew file mode 100644index 000000000..0f8e4cab3--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/CollaborationFeatures.tsx@@ -0,0 +1,586 @@+import React, { useState, useEffect } from 'react';+import {+ MessageSquare,+ Clock,+ User,+ Plus,+ X,+ ChevronDown,+ ChevronRight,+ History,+ RotateCcw,+ Check,+ Edit3,+ Trash2,+ Eye,+ EyeOff,+} from 'lucide-react';+import { ReportTemplate, ReportComponent } from '@/services/core/reportService';++// ============ Types ============+export interface Comment {+ id: string;+ componentId: string;+ author: string;+ content: string;+ timestamp: string;+ resolved?: boolean;+ replies?: Comment[];+}++export interface VersionHistoryEntry {+ id: string;+ timestamp: string;+ author: string;+ description: string;+ template: ReportTemplate;+ changes: {+ type: 'add' | 'delete' | 'modify';+ componentId?: string;+ field?: string;+ oldValue?: any;+ newValue?: any;+ }[];+}++export interface TrackedChange {+ id: string;+ componentId: string;+ type: 'addition' | 'deletion' | 'modification';+ field?: string;+ oldValue?: any;+ newValue?: any;+ timestamp: string;+ author: string;+ accepted?: boolean;+}++// ============ Comments Panel ============+interface CommentsPanelProps {+ comments: Comment[];+ selectedComponentId: string | null;+ onAddComment: (componentId: string, content: string) => void;+ onResolveComment: (commentId: string) => void;+ onDeleteComment: (commentId: string) => void;+ onReplyComment: (commentId: string, content: string) => void;+}++export const CommentsPanel: React.FC<CommentsPanelProps> = ({+ comments,+ selectedComponentId,+ onAddComment,+ onResolveComment,+ onDeleteComment,+ onReplyComment,+}) => {+ const [newComment, setNewComment] = useState('');+ const [replyingTo, setReplyingTo] = useState<string | null>(null);+ const [replyContent, setReplyContent] = useState('');+ const [showResolved, setShowResolved] = useState(false);++ const filteredComments = comments.filter(c =>+ (selectedComponentId ? c.componentId === selectedComponentId : true) &&+ (showResolved || !c.resolved)+ );++ const handleAddComment = () => {+ if (!newComment.trim() || !selectedComponentId) return;+ onAddComment(selectedComponentId, newComment.trim());+ setNewComment('');+ };++ const handleReply = (commentId: string) => {+ if (!replyContent.trim()) return;+ onReplyComment(commentId, replyContent.trim());+ setReplyContent('');+ setReplyingTo(null);+ };++ return (+ <div className="flex flex-col h-full">+ <div className="flex items-center justify-between p-3 border-b border-[#333333]">+ <div className="flex items-center gap-2">+ <MessageSquare size={14} className="text-[#FFA500]" />+ <span className="text-xs font-semibold text-[#FFA500]">COMMENTS</span>+ <span className="text-[10px] text-gray-500">({filteredComments.length})</span>+ </div>+ <button+ onClick={() => setShowResolved(!showResolved)}+ className="text-[10px] text-gray-400 hover:text-white"+ >+ {showResolved ? 'Hide' : 'Show'} resolved+ </button>+ </div>++ {/* Comments List */}+ <div className="flex-1 overflow-y-auto p-3 space-y-3">+ {filteredComments.length === 0 ? (+ <p className="text-xs text-gray-500 text-center py-4">+ {selectedComponentId ? 'No comments on this component' : 'Select a component to view comments'}+ </p>+ ) : (+ filteredComments.map(comment => (+ <CommentItem+ key={comment.id}+ comment={comment}+ onResolve={() => onResolveComment(comment.id)}+ onDelete={() => onDeleteComment(comment.id)}+ onReply={() => setReplyingTo(comment.id)}+ isReplying={replyingTo === comment.id}+ replyContent={replyContent}+ setReplyContent={setReplyContent}+ handleReply={() => handleReply(comment.id)}+ cancelReply={() => setReplyingTo(null)}+ />+ ))+ )}+ </div>++ {/* Add Comment */}+ {selectedComponentId && (+ <div className="p-3 border-t border-[#333333]">+ <div className="flex gap-2">+ <input+ type="text"+ value={newComment}+ onChange={(e) => setNewComment(e.target.value)}+ placeholder="Add a comment..."+ className="flex-1 px-3 py-2 text-xs bg-[#0a0a0a] border border-[#333333] rounded text-white focus:border-[#FFA500] outline-none"+ onKeyPress={(e) => e.key === 'Enter' && handleAddComment()}+ />+ <button+ onClick={handleAddComment}+ disabled={!newComment.trim()}+ className="px-3 py-2 bg-[#FFA500] text-black rounded text-xs disabled:opacity-50"+ >+ <Plus size={14} />+ </button>+ </div>+ </div>+ )}+ </div>+ );+};++// Comment Item+interface CommentItemProps {+ comment: Comment;+ onResolve: () => void;+ onDelete: () => void;+ onReply: () => void;+ isReplying: boolean;+ replyContent: string;+ setReplyContent: (v: string) => void;+ handleReply: () => void;+ cancelReply: () => void;+}++const CommentItem: React.FC<CommentItemProps> = ({+ comment,+ onResolve,+ onDelete,+ onReply,+ isReplying,+ replyContent,+ setReplyContent,+ handleReply,+ cancelReply,+}) => (+ <div className={`p-3 rounded border ${comment.resolved ? 'bg-[#0a0a0a] border-[#222222] opacity-60' : 'bg-[#1a1a1a] border-[#333333]'}`}>+ <div className="flex items-start justify-between mb-2">+ <div className="flex items-center gap-2">+ <div className="w-6 h-6 rounded-full bg-[#FFA500]/20 flex items-center justify-center">+ <User size={12} className="text-[#FFA500]" />+ </div>+ <div>+ <p className="text-xs font-semibold text-white">{comment.author}</p>+ <p className="text-[10px] text-gray-500">{new Date(comment.timestamp).toLocaleString()}</p>+ </div>+ </div>+ <div className="flex gap-1">+ {!comment.resolved && (+ <button onClick={onResolve} className="p-1 hover:bg-[#2a2a2a] rounded" title="Resolve">+ <Check size={12} className="text-green-500" />+ </button>+ )}+ <button onClick={onDelete} className="p-1 hover:bg-[#2a2a2a] rounded" title="Delete">+ <Trash2 size={12} className="text-red-500" />+ </button>+ </div>+ </div>+ <p className="text-xs text-gray-300 mb-2">{comment.content}</p>++ {/* Replies */}+ {comment.replies && comment.replies.length > 0 && (+ <div className="ml-4 mt-2 space-y-2 border-l border-[#333333] pl-3">+ {comment.replies.map(reply => (+ <div key={reply.id} className="text-xs">+ <span className="font-semibold text-gray-400">{reply.author}: </span>+ <span className="text-gray-300">{reply.content}</span>+ </div>+ ))}+ </div>+ )}++ {/* Reply Input */}+ {isReplying ? (+ <div className="mt-2 flex gap-2">+ <input+ type="text"+ value={replyContent}+ onChange={(e) => setReplyContent(e.target.value)}+ placeholder="Reply..."+ className="flex-1 px-2 py-1 text-xs bg-[#0a0a0a] border border-[#333333] rounded text-white"+ autoFocus+ />+ <button onClick={handleReply} className="text-[#FFA500] text-xs">Send</button>+ <button onClick={cancelReply} className="text-gray-500 text-xs">Cancel</button>+ </div>+ ) : (+ <button onClick={onReply} className="text-xs text-gray-500 hover:text-[#FFA500] mt-1">+ Reply+ </button>+ )}+ </div>+);++// ============ Version History Panel ============+interface VersionHistoryPanelProps {+ history: VersionHistoryEntry[];+ onRestore: (entry: VersionHistoryEntry) => void;+ onPreview: (entry: VersionHistoryEntry) => void;+}++export const VersionHistoryPanel: React.FC<VersionHistoryPanelProps> = ({+ history,+ onRestore,+ onPreview,+}) => {+ const [expandedId, setExpandedId] = useState<string | null>(null);++ return (+ <div className="flex flex-col h-full">+ <div className="flex items-center gap-2 p-3 border-b border-[#333333]">+ <History size={14} className="text-[#FFA500]" />+ <span className="text-xs font-semibold text-[#FFA500]">VERSION HISTORY</span>+ </div>++ <div className="flex-1 overflow-y-auto">+ {history.length === 0 ? (+ <p className="text-xs text-gray-500 text-center py-8">No version history</p>+ ) : (+ <div className="divide-y divide-[#333333]">+ {history.map((entry, idx) => (+ <div key={entry.id} className="p-3">+ <div+ className="flex items-center justify-between cursor-pointer"+ onClick={() => setExpandedId(expandedId === entry.id ? null : entry.id)}+ >+ <div className="flex items-center gap-2">+ {expandedId === entry.id ? (+ <ChevronDown size={12} className="text-gray-500" />+ ) : (+ <ChevronRight size={12} className="text-gray-500" />+ )}+ <div>+ <p className="text-xs text-white">{entry.description}</p>+ <p className="text-[10px] text-gray-500">+ {entry.author} • {new Date(entry.timestamp).toLocaleString()}+ </p>+ </div>+ </div>+ {idx === 0 && (+ <span className="text-[10px] px-2 py-0.5 bg-[#FFA500]/20 text-[#FFA500] rounded">+ Current+ </span>+ )}+ </div>++ {expandedId === entry.id && (+ <div className="mt-3 ml-5 space-y-2">+ {/* Changes */}+ <div className="text-[10px] text-gray-500">+ {entry.changes.length} change(s)+ </div>+ {entry.changes.slice(0, 3).map((change, i) => (+ <div key={i} className="text-xs text-gray-400 flex items-center gap-2">+ <span className={`w-2 h-2 rounded-full ${+ change.type === 'add' ? 'bg-green-500' :+ change.type === 'delete' ? 'bg-red-500' : 'bg-yellow-500'+ }`} />+ <span className="capitalize">{change.type}</span>+ {change.field && <span>- {change.field}</span>}+ </div>+ ))}++ {/* Actions */}+ {idx !== 0 && (+ <div className="flex gap-2 mt-2">+ <button+ onClick={() => onPreview(entry)}+ className="text-xs px-2 py-1 bg-[#2a2a2a] text-gray-300 rounded hover:bg-[#3a3a3a]"+ >+ <Eye size={12} className="inline mr-1" />+ Preview+ </button>+ <button+ onClick={() => onRestore(entry)}+ className="text-xs px-2 py-1 bg-[#FFA500] text-black rounded hover:bg-[#ff8c00]"+ >+ <RotateCcw size={12} className="inline mr-1" />+ Restore+ </button>+ </div>+ )}+ </div>+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ );+};++// ============ Revision Mode (Track Changes) ============+interface RevisionModeProps {+ changes: TrackedChange[];+ enabled: boolean;+ onToggle: () => void;+ onAcceptChange: (changeId: string) => void;+ onRejectChange: (changeId: string) => void;+ onAcceptAll: () => void;+ onRejectAll: () => void;+}++export const RevisionMode: React.FC<RevisionModeProps> = ({+ changes,+ enabled,+ onToggle,+ onAcceptChange,+ onRejectChange,+ onAcceptAll,+ onRejectAll,+}) => {+ const pendingChanges = changes.filter(c => c.accepted === undefined);++ return (+ <div className="flex flex-col h-full">+ <div className="flex items-center justify-between p-3 border-b border-[#333333]">+ <div className="flex items-center gap-2">+ <Edit3 size={14} className="text-[#FFA500]" />+ <span className="text-xs font-semibold text-[#FFA500]">TRACK CHANGES</span>+ </div>+ <button+ onClick={onToggle}+ className={`px-2 py-1 text-xs rounded ${+ enabled ? 'bg-[#FFA500] text-black' : 'bg-[#333333] text-gray-400'+ }`}+ >+ {enabled ? 'ON' : 'OFF'}+ </button>+ </div>++ {enabled && (+ <>+ {/* Bulk Actions */}+ {pendingChanges.length > 0 && (+ <div className="flex gap-2 p-3 border-b border-[#333333]">+ <button+ onClick={onAcceptAll}+ className="flex-1 py-1.5 text-xs bg-green-600 text-white rounded hover:bg-green-700"+ >+ Accept All ({pendingChanges.length})+ </button>+ <button+ onClick={onRejectAll}+ className="flex-1 py-1.5 text-xs bg-red-600 text-white rounded hover:bg-red-700"+ >+ Reject All+ </button>+ </div>+ )}++ {/* Changes List */}+ <div className="flex-1 overflow-y-auto p-3 space-y-2">+ {changes.length === 0 ? (+ <p className="text-xs text-gray-500 text-center py-4">No tracked changes</p>+ ) : (+ changes.map(change => (+ <div+ key={change.id}+ className={`p-2 rounded border text-xs ${+ change.accepted === true ? 'bg-green-900/20 border-green-800' :+ change.accepted === false ? 'bg-red-900/20 border-red-800' :+ 'bg-[#1a1a1a] border-[#333333]'+ }`}+ >+ <div className="flex items-center justify-between mb-1">+ <div className="flex items-center gap-2">+ <span className={`w-2 h-2 rounded-full ${+ change.type === 'addition' ? 'bg-green-500' :+ change.type === 'deletion' ? 'bg-red-500' : 'bg-yellow-500'+ }`} />+ <span className="capitalize text-gray-300">{change.type}</span>+ </div>+ {change.accepted === undefined && (+ <div className="flex gap-1">+ <button+ onClick={() => onAcceptChange(change.id)}+ className="p-1 hover:bg-green-600/30 rounded"+ >+ <Check size={12} className="text-green-500" />+ </button>+ <button+ onClick={() => onRejectChange(change.id)}+ className="p-1 hover:bg-red-600/30 rounded"+ >+ <X size={12} className="text-red-500" />+ </button>+ </div>+ )}+ </div>+ {change.field && (+ <p className="text-gray-500 text-[10px]">Field: {change.field}</p>+ )}+ {change.type === 'modification' && (+ <div className="mt-1 text-[10px]">+ <p className="text-red-400 line-through">{String(change.oldValue).substring(0, 50)}</p>+ <p className="text-green-400">{String(change.newValue).substring(0, 50)}</p>+ </div>+ )}+ <p className="text-[10px] text-gray-600 mt-1">+ {change.author} • {new Date(change.timestamp).toLocaleString()}+ </p>+ </div>+ ))+ )}+ </div>+ </>+ )}+ </div>+ );+};++// ============ Hook for managing collaboration state ============+export const useCollaboration = (template: ReportTemplate) => {+ const [comments, setComments] = useState<Comment[]>([]);+ const [versionHistory, setVersionHistory] = useState<VersionHistoryEntry[]>([]);+ const [trackedChanges, setTrackedChanges] = useState<TrackedChange[]>([]);+ const [isTrackingEnabled, setIsTrackingEnabled] = useState(false);++ // Add comment+ const addComment = (componentId: string, content: string) => {+ const newComment: Comment = {+ id: `comment-${Date.now()}`,+ componentId,+ author: 'User',+ content,+ timestamp: new Date().toISOString(),+ replies: [],+ };+ setComments(prev => [...prev, newComment]);+ };++ // Resolve comment+ const resolveComment = (commentId: string) => {+ setComments(prev => prev.map(c =>+ c.id === commentId ? { ...c, resolved: true } : c+ ));+ };++ // Delete comment+ const deleteComment = (commentId: string) => {+ setComments(prev => prev.filter(c => c.id !== commentId));+ };++ // Reply to comment+ const replyToComment = (commentId: string, content: string) => {+ const reply: Comment = {+ id: `reply-${Date.now()}`,+ componentId: '',+ author: 'User',+ content,+ timestamp: new Date().toISOString(),+ };+ setComments(prev => prev.map(c =>+ c.id === commentId ? { ...c, replies: [...(c.replies || []), reply] } : c+ ));+ };++ // Save version+ const saveVersion = (description: string, changes: VersionHistoryEntry['changes']) => {+ const entry: VersionHistoryEntry = {+ id: `version-${Date.now()}`,+ timestamp: new Date().toISOString(),+ author: 'User',+ description,+ template: JSON.parse(JSON.stringify(template)),+ changes,+ };+ setVersionHistory(prev => [entry, ...prev]);+ };++ // Track change+ const trackChange = (change: Omit<TrackedChange, 'id' | 'timestamp' | 'author'>) => {+ if (!isTrackingEnabled) return;+ const tracked: TrackedChange = {+ ...change,+ id: `change-${Date.now()}`,+ timestamp: new Date().toISOString(),+ author: 'User',+ };+ setTrackedChanges(prev => [...prev, tracked]);+ };++ // Accept/Reject changes+ const acceptChange = (changeId: string) => {+ setTrackedChanges(prev => prev.map(c =>+ c.id === changeId ? { ...c, accepted: true } : c+ ));+ };++ const rejectChange = (changeId: string) => {+ setTrackedChanges(prev => prev.map(c =>+ c.id === changeId ? { ...c, accepted: false } : c+ ));+ };++ const acceptAllChanges = () => {+ setTrackedChanges(prev => prev.map(c =>+ c.accepted === undefined ? { ...c, accepted: true } : c+ ));+ };++ const rejectAllChanges = () => {+ setTrackedChanges(prev => prev.map(c =>+ c.accepted === undefined ? { ...c, accepted: false } : c+ ));+ };++ return {+ comments,+ versionHistory,+ trackedChanges,+ isTrackingEnabled,+ addComment,+ resolveComment,+ deleteComment,+ replyToComment,+ saveVersion,+ trackChange,+ acceptChange,+ rejectChange,+ acceptAllChanges,+ rejectAllChanges,+ setIsTrackingEnabled,+ };+};++export default {+ CommentsPanel,+ VersionHistoryPanel,+ RevisionMode,+ useCollaboration,+};diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/DataComponents.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/DataComponents.tsxnew file mode 100644index 000000000..a27c43f59--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/DataComponents.tsx@@ -0,0 +1,468 @@+import React, { useState, useEffect } from 'react';+import {+ TrendingUp,+ TrendingDown,+ Minus,+ Database,+ RefreshCw,+ Settings2,+} from 'lucide-react';+import {+ LineChart,+ Line,+ AreaChart,+ Area,+ BarChart,+ Bar,+ PieChart,+ Pie,+ Cell,+ XAxis,+ YAxis,+ Tooltip,+ ResponsiveContainer,+} from 'recharts';++// ============ Types ============+export interface LiveDataConfig {+ source: 'portfolio' | 'watchlist' | 'market' | 'custom';+ ticker?: string;+ columns?: string[];+ refreshInterval?: number;+}++export interface KPICardConfig {+ title: string;+ value: string | number;+ change?: number;+ changeType?: 'percent' | 'absolute';+ prefix?: string;+ suffix?: string;+ color?: string;+}++export interface SparklineConfig {+ data: number[];+ color?: string;+ height?: number;+ showArea?: boolean;+}++export interface DynamicChartConfig {+ type: 'line' | 'bar' | 'area' | 'pie' | 'candlestick';+ data: any[];+ xKey?: string;+ yKey?: string;+ colors?: string[];+ height?: number;+}++// ============ Sample Data ============+const SAMPLE_PORTFOLIO_DATA = [+ { symbol: 'AAPL', name: 'Apple Inc.', shares: 100, price: 178.50, change: 2.35, value: 17850 },+ { symbol: 'GOOGL', name: 'Alphabet Inc.', shares: 50, price: 141.20, change: -1.20, value: 7060 },+ { symbol: 'MSFT', name: 'Microsoft Corp.', shares: 75, price: 378.90, change: 4.50, value: 28417.50 },+ { symbol: 'AMZN', name: 'Amazon.com Inc.', shares: 30, price: 178.25, change: 1.85, value: 5347.50 },+ { symbol: 'NVDA', name: 'NVIDIA Corp.', shares: 40, price: 875.30, change: 15.20, value: 35012 },+];++const SAMPLE_CHART_DATA = [+ { date: 'Jan', value: 4000, volume: 2400 },+ { date: 'Feb', value: 3000, volume: 1398 },+ { date: 'Mar', value: 2000, volume: 9800 },+ { date: 'Apr', value: 2780, volume: 3908 },+ { date: 'May', value: 1890, volume: 4800 },+ { date: 'Jun', value: 2390, volume: 3800 },+ { date: 'Jul', value: 3490, volume: 4300 },+];++const COLORS = ['#FFA500', '#4A90D9', '#10B981', '#EF4444', '#8B5CF6', '#F59E0B'];++// ============ Live Data Table ============+interface LiveDataTableProps {+ config?: LiveDataConfig;+ isPreview?: boolean;+}++export const LiveDataTable: React.FC<LiveDataTableProps> = ({ config, isPreview }) => {+ const [data, setData] = useState(SAMPLE_PORTFOLIO_DATA);+ const [isLoading, setIsLoading] = useState(false);++ const columns = config?.columns || ['symbol', 'name', 'shares', 'price', 'change', 'value'];++ const formatValue = (key: string, val: any) => {+ if (key === 'price' || key === 'value') return `$${val.toLocaleString()}`;+ if (key === 'change') return (+ <span className={val >= 0 ? 'text-green-500' : 'text-red-500'}>+ {val >= 0 ? '+' : ''}{val.toFixed(2)}%+ </span>+ );+ return val;+ };++ return (+ <div className="border border-gray-300 rounded overflow-hidden bg-white">+ <div className="flex items-center justify-between px-3 py-2 bg-gray-50 border-b">+ <div className="flex items-center gap-2">+ <Database size={14} className="text-[#FFA500]" />+ <span className="text-xs font-semibold text-gray-700">+ {config?.source === 'portfolio' ? 'Portfolio Holdings' :+ config?.source === 'watchlist' ? 'Watchlist' : 'Market Data'}+ </span>+ </div>+ {!isPreview && (+ <button className="p-1 hover:bg-gray-200 rounded">+ <RefreshCw size={12} className="text-gray-500" />+ </button>+ )}+ </div>+ <table className="w-full text-xs">+ <thead className="bg-gray-100">+ <tr>+ {columns.map(col => (+ <th key={col} className="px-3 py-2 text-left font-semibold text-gray-600 capitalize">+ {col}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {data.map((row, idx) => (+ <tr key={idx} className="border-t border-gray-100 hover:bg-gray-50">+ {columns.map(col => (+ <td key={col} className="px-3 py-2 text-gray-800">+ {formatValue(col, (row as any)[col])}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+};++// ============ KPI Card ============+interface KPICardProps {+ config: KPICardConfig;+}++export const KPICard: React.FC<KPICardProps> = ({ config }) => {+ const { title, value, change, changeType = 'percent', prefix = '', suffix = '', color = '#FFA500' } = config;++ const isPositive = (change || 0) >= 0;+ const TrendIcon = change === 0 ? Minus : isPositive ? TrendingUp : TrendingDown;++ return (+ <div className="bg-white border border-gray-200 rounded-lg p-4 shadow-sm">+ <p className="text-xs text-gray-500 mb-1">{title}</p>+ <div className="flex items-end justify-between">+ <p className="text-2xl font-bold" style={{ color }}>+ {prefix}{typeof value === 'number' ? value.toLocaleString() : value}{suffix}+ </p>+ {change !== undefined && (+ <div className={`flex items-center gap-1 text-xs ${isPositive ? 'text-green-500' : 'text-red-500'}`}>+ <TrendIcon size={14} />+ <span>{isPositive ? '+' : ''}{change}{changeType === 'percent' ? '%' : ''}</span>+ </div>+ )}+ </div>+ </div>+ );+};++// ============ KPI Cards Row ============+interface KPICardsRowProps {+ cards?: KPICardConfig[];+}++export const KPICardsRow: React.FC<KPICardsRowProps> = ({ cards }) => {+ const defaultCards: KPICardConfig[] = cards || [+ { title: 'Total Value', value: 93687, change: 5.2, prefix: '$' },+ { title: 'Daily P&L', value: 1250, change: 1.35, prefix: '$', color: '#10B981' },+ { title: 'Total Return', value: '18.5%', change: 3.2 },+ { title: 'Positions', value: 12, change: 0 },+ ];++ return (+ <div className="grid grid-cols-4 gap-3">+ {defaultCards.map((card, idx) => (+ <KPICard key={idx} config={card} />+ ))}+ </div>+ );+};++// ============ Sparkline ============+interface SparklineProps {+ config?: SparklineConfig;+ inline?: boolean;+}++export const Sparkline: React.FC<SparklineProps> = ({ config, inline }) => {+ const data = (config?.data || [45, 52, 38, 45, 19, 23, 25, 30, 35, 40, 45, 50]).map((v, i) => ({ v }));+ const color = config?.color || '#FFA500';+ const height = config?.height || (inline ? 20 : 40);++ return (+ <div style={{ width: inline ? 80 : '100%', height }}>+ <ResponsiveContainer width="100%" height="100%">+ <AreaChart data={data} margin={{ top: 0, right: 0, left: 0, bottom: 0 }}>+ <defs>+ <linearGradient id={`sparkGrad-${color}`} x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor={color} stopOpacity={0.3} />+ <stop offset="95%" stopColor={color} stopOpacity={0} />+ </linearGradient>+ </defs>+ <Area+ type="monotone"+ dataKey="v"+ stroke={color}+ strokeWidth={1.5}+ fill={config?.showArea !== false ? `url(#sparkGrad-${color})` : 'none'}+ />+ </AreaChart>+ </ResponsiveContainer>+ </div>+ );+};++// ============ Dynamic Chart ============+interface DynamicChartProps {+ config?: DynamicChartConfig;+}++export const DynamicChart: React.FC<DynamicChartProps> = ({ config }) => {+ const type = config?.type || 'line';+ const data = config?.data || SAMPLE_CHART_DATA;+ const xKey = config?.xKey || 'date';+ const yKey = config?.yKey || 'value';+ const colors = config?.colors || COLORS;+ const height = config?.height || 200;++ const renderChart = () => {+ switch (type) {+ case 'bar':+ return (+ <BarChart data={data}>+ <XAxis dataKey={xKey} tick={{ fontSize: 10 }} />+ <YAxis tick={{ fontSize: 10 }} />+ <Tooltip />+ <Bar dataKey={yKey} fill={colors[0]} radius={[4, 4, 0, 0]} />+ </BarChart>+ );+ case 'area':+ return (+ <AreaChart data={data}>+ <defs>+ <linearGradient id="areaGrad" x1="0" y1="0" x2="0" y2="1">+ <stop offset="5%" stopColor={colors[0]} stopOpacity={0.3} />+ <stop offset="95%" stopColor={colors[0]} stopOpacity={0} />+ </linearGradient>+ </defs>+ <XAxis dataKey={xKey} tick={{ fontSize: 10 }} />+ <YAxis tick={{ fontSize: 10 }} />+ <Tooltip />+ <Area type="monotone" dataKey={yKey} stroke={colors[0]} fill="url(#areaGrad)" />+ </AreaChart>+ );+ case 'pie':+ return (+ <PieChart>+ <Pie+ data={data}+ dataKey={yKey}+ nameKey={xKey}+ cx="50%"+ cy="50%"+ outerRadius={60}+ label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}+ labelLine={false}+ >+ {data.map((_, idx) => (+ <Cell key={idx} fill={colors[idx % colors.length]} />+ ))}+ </Pie>+ <Tooltip />+ </PieChart>+ );+ case 'line':+ default:+ return (+ <LineChart data={data}>+ <XAxis dataKey={xKey} tick={{ fontSize: 10 }} />+ <YAxis tick={{ fontSize: 10 }} />+ <Tooltip />+ <Line type="monotone" dataKey={yKey} stroke={colors[0]} strokeWidth={2} dot={false} />+ </LineChart>+ );+ }+ };++ return (+ <div className="bg-white border border-gray-200 rounded p-4">+ <ResponsiveContainer width="100%" height={height}>+ {renderChart()}+ </ResponsiveContainer>+ </div>+ );+};++// ============ Financial Metrics Widget ============+interface FinancialMetricsProps {+ ticker?: string;+}++export const FinancialMetricsWidget: React.FC<FinancialMetricsProps> = ({ ticker = 'AAPL' }) => {+ const metrics = [+ { label: 'P/E Ratio', value: '28.5x' },+ { label: 'EPS', value: '$6.14' },+ { label: 'Market Cap', value: '$2.8T' },+ { label: 'Dividend Yield', value: '0.51%' },+ { label: 'Beta', value: '1.28' },+ { label: '52W High', value: '$199.62' },+ { label: '52W Low', value: '$124.17' },+ { label: 'Avg Volume', value: '58.2M' },+ ];++ return (+ <div className="bg-white border border-gray-200 rounded overflow-hidden">+ <div className="px-3 py-2 bg-gray-50 border-b flex items-center justify-between">+ <span className="text-xs font-semibold text-gray-700">{ticker} - Key Metrics</span>+ <span className="text-[10px] text-gray-500">Real-time</span>+ </div>+ <div className="grid grid-cols-4 gap-px bg-gray-200">+ {metrics.map((m, idx) => (+ <div key={idx} className="bg-white p-3 text-center">+ <p className="text-[10px] text-gray-500 mb-1">{m.label}</p>+ <p className="text-sm font-semibold text-gray-800">{m.value}</p>+ </div>+ ))}+ </div>+ </div>+ );+};++// ============ Chart Data Editor ============+interface ChartDataEditorProps {+ data: any[];+ onChange: (data: any[]) => void;+ columns: string[];+}++export const ChartDataEditor: React.FC<ChartDataEditorProps> = ({ data, onChange, columns }) => {+ const [csvInput, setCsvInput] = useState('');++ const handleCsvImport = () => {+ try {+ const lines = csvInput.trim().split('\n');+ const headers = lines[0].split(',').map(h => h.trim());+ const rows = lines.slice(1).map(line => {+ const values = line.split(',').map(v => v.trim());+ const row: any = {};+ headers.forEach((h, i) => {+ row[h] = isNaN(Number(values[i])) ? values[i] : Number(values[i]);+ });+ return row;+ });+ onChange(rows);+ setCsvInput('');+ } catch (e) {+ console.error('CSV parse error:', e);+ }+ };++ const addRow = () => {+ const newRow: any = {};+ columns.forEach(col => { newRow[col] = ''; });+ onChange([...data, newRow]);+ };++ const updateCell = (rowIdx: number, col: string, value: string) => {+ const newData = [...data];+ newData[rowIdx][col] = isNaN(Number(value)) ? value : Number(value);+ onChange(newData);+ };++ const deleteRow = (idx: number) => {+ onChange(data.filter((_, i) => i !== idx));+ };++ return (+ <div className="space-y-3">+ <div className="text-xs font-semibold text-gray-600">Chart Data</div>++ {/* Table Editor */}+ <div className="border border-gray-300 rounded overflow-hidden">+ <table className="w-full text-xs">+ <thead className="bg-gray-100">+ <tr>+ {columns.map(col => (+ <th key={col} className="px-2 py-1 text-left">{col}</th>+ ))}+ <th className="w-8"></th>+ </tr>+ </thead>+ <tbody>+ {data.map((row, rowIdx) => (+ <tr key={rowIdx} className="border-t">+ {columns.map(col => (+ <td key={col} className="px-1 py-1">+ <input+ type="text"+ value={row[col] || ''}+ onChange={(e) => updateCell(rowIdx, col, e.target.value)}+ className="w-full px-1 py-0.5 text-xs border border-gray-200 rounded"+ />+ </td>+ ))}+ <td className="px-1">+ <button+ onClick={() => deleteRow(rowIdx)}+ className="text-red-500 hover:text-red-700 text-xs"+ >+ ×+ </button>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>++ <button+ onClick={addRow}+ className="text-xs text-[#FFA500] hover:underline"+ >+ + Add Row+ </button>++ {/* CSV Import */}+ <div className="pt-2 border-t">+ <label className="text-[10px] text-gray-500 block mb-1">Import CSV</label>+ <textarea+ value={csvInput}+ onChange={(e) => setCsvInput(e.target.value)}+ placeholder="date,value Jan,100 Feb,150"+ className="w-full h-16 text-xs p-2 border border-gray-300 rounded resize-none"+ />+ <button+ onClick={handleCsvImport}+ className="mt-1 text-xs px-2 py-1 bg-[#FFA500] text-black rounded"+ >+ Import+ </button>+ </div>+ </div>+ );+};++export default {+ LiveDataTable,+ KPICard,+ KPICardsRow,+ Sparkline,+ DynamicChart,+ FinancialMetricsWidget,+ ChartDataEditor,+};diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/ExportDialog.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/ExportDialog.tsxnew file mode 100644index 000000000..68d5573da--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/ExportDialog.tsx@@ -0,0 +1,221 @@+import React, { useState } from 'react';+import {+ Download,+ FileText,+ Code,+ FileType,+ Printer,+ X,+ Check,+ Loader2,+ Eye,+ Package,+} from 'lucide-react';+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';+import { Button } from '@/components/ui/button';+import { ReportTemplate } from '@/services/core/reportService';+import { BrandKit } from '@/services/core/brandKitService';+import { reportExportService, ExportFormat } from '@/services/core/reportExportService';+import { toast } from 'sonner';++interface ExportDialogProps {+ open: boolean;+ onClose: () => void;+ template: ReportTemplate;+ brandKit: BrandKit | null;+}++const EXPORT_OPTIONS: { format: ExportFormat; label: string; icon: React.ReactNode; desc: string }[] = [+ { format: 'pdf', label: 'PDF', icon: <FileText size={20} />, desc: 'Best for sharing and printing' },+ { format: 'html', label: 'HTML', icon: <Code size={20} />, desc: 'For web publishing' },+ { format: 'docx', label: 'Word', icon: <FileType size={20} />, desc: 'For editing in Word' },+ { format: 'markdown', label: 'Markdown', icon: <FileText size={20} />, desc: 'For documentation' },+];++export const ExportDialog: React.FC<ExportDialogProps> = ({ open, onClose, template, brandKit }) => {+ const [selectedFormats, setSelectedFormats] = useState<ExportFormat[]>(['pdf']);+ const [isExporting, setIsExporting] = useState(false);+ const [showPreview, setShowPreview] = useState(false);+ const [previewHtml, setPreviewHtml] = useState('');++ const toggleFormat = (format: ExportFormat) => {+ setSelectedFormats(prev =>+ prev.includes(format) ? prev.filter(f => f !== format) : [...prev, format]+ );+ };++ const handleExport = async () => {+ if (selectedFormats.length === 0) {+ toast.error('Select at least one format');+ return;+ }++ setIsExporting(true);+ try {+ if (selectedFormats.length === 1) {+ const path = await reportExportService.exportToFile(template, selectedFormats[0], brandKit);+ if (path) toast.success(`Exported to ${path}`);+ } else {+ const results = await reportExportService.batchExport(template, selectedFormats, brandKit);+ const success = Object.values(results).filter(Boolean).length;+ toast.success(`Exported ${success}/${selectedFormats.length} formats`);+ }+ onClose();+ } catch (error) {+ toast.error('Export failed');+ } finally {+ setIsExporting(false);+ }+ };++ const handlePreview = () => {+ const html = reportExportService.getPrintPreviewHTML(template, brandKit);+ setPreviewHtml(html);+ setShowPreview(true);+ };++ const handlePrint = () => {+ const html = reportExportService.getPrintPreviewHTML(template, brandKit);+ const printWindow = window.open('', '_blank');+ if (printWindow) {+ printWindow.document.write(html);+ printWindow.document.close();+ printWindow.print();+ }+ };++ return (+ <>+ <Dialog open={open && !showPreview} onOpenChange={onClose}>+ <DialogContent className="bg-[#1a1a1a] border-[#333333] max-w-md">+ <DialogHeader>+ <DialogTitle className="text-[#FFA500] flex items-center gap-2">+ <Download size={20} />+ Export Report+ </DialogTitle>+ </DialogHeader>++ <div className="space-y-4 py-4">+ {/* Format Selection */}+ <div className="space-y-2">+ <label className="text-xs text-gray-400">Select Format(s)</label>+ <div className="grid grid-cols-2 gap-2">+ {EXPORT_OPTIONS.map(({ format, label, icon, desc }) => (+ <button+ key={format}+ onClick={() => toggleFormat(format)}+ className={`p-3 rounded border text-left transition-all ${+ selectedFormats.includes(format)+ ? 'border-[#FFA500] bg-[#FFA500]/10'+ : 'border-[#333333] hover:border-[#555555]'+ }`}+ >+ <div className="flex items-center gap-2 mb-1">+ <span className={selectedFormats.includes(format) ? 'text-[#FFA500]' : 'text-gray-400'}>+ {icon}+ </span>+ <span className="text-sm font-medium text-white">{label}</span>+ {selectedFormats.includes(format) && (+ <Check size={14} className="ml-auto text-[#FFA500]" />+ )}+ </div>+ <p className="text-[10px] text-gray-500">{desc}</p>+ </button>+ ))}+ </div>+ </div>++ {/* Batch Export Info */}+ {selectedFormats.length > 1 && (+ <div className="flex items-center gap-2 p-2 bg-[#0a0a0a] rounded text-xs text-gray-400">+ <Package size={14} className="text-[#FFA500]" />+ Batch export: {selectedFormats.length} formats selected+ </div>+ )}++ {/* Actions */}+ <div className="flex gap-2 pt-2">+ <Button+ variant="outline"+ onClick={handlePreview}+ className="flex-1 bg-transparent border-[#333333] text-white hover:bg-[#2a2a2a]"+ >+ <Eye size={16} className="mr-2" />+ Preview+ </Button>+ <Button+ variant="outline"+ onClick={handlePrint}+ className="flex-1 bg-transparent border-[#333333] text-white hover:bg-[#2a2a2a]"+ >+ <Printer size={16} className="mr-2" />+ </Button>+ </div>++ <Button+ onClick={handleExport}+ disabled={isExporting || selectedFormats.length === 0}+ className="w-full bg-[#FFA500] text-black hover:bg-[#ff8c00]"+ >+ {isExporting ? (+ <>+ <Loader2 size={16} className="mr-2 animate-spin" />+ Exporting...+ </>+ ) : (+ <>+ <Download size={16} className="mr-2" />+ Export {selectedFormats.length > 1 ? `(${selectedFormats.length})` : ''}+ </>+ )}+ </Button>+ </div>+ </DialogContent>+ </Dialog>++ {/* Print Preview Modal */}+ <Dialog open={showPreview} onOpenChange={() => setShowPreview(false)}>+ <DialogContent className="bg-[#1a1a1a] border-[#333333] max-w-4xl max-h-[90vh]">+ <DialogHeader>+ <DialogTitle className="text-[#FFA500] flex items-center justify-between">+ <span className="flex items-center gap-2">+ <Eye size={20} />+ Print Preview+ </span>+ <div className="flex gap-2">+ <Button+ size="sm"+ onClick={handlePrint}+ className="bg-[#FFA500] text-black hover:bg-[#ff8c00]"+ >+ <Printer size={14} className="mr-1" />+ </Button>+ <Button+ size="sm"+ variant="outline"+ onClick={() => setShowPreview(false)}+ className="bg-transparent border-[#333333] text-white"+ >+ <X size={14} />+ </Button>+ </div>+ </DialogTitle>+ </DialogHeader>++ <div className="overflow-auto max-h-[70vh] bg-gray-200 p-4 rounded">+ <iframe+ srcDoc={previewHtml}+ className="w-full bg-white shadow-lg"+ style={{ height: '800px', border: 'none' }}+ title="Print Preview"+ />+ </div>+ </DialogContent>+ </Dialog>+ </>+ );+};++export default ExportDialog;diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/ProductivityFeatures.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/ProductivityFeatures.tsxnew file mode 100644index 000000000..cc07aa721--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/ProductivityFeatures.tsx@@ -0,0 +1,578 @@+import React, { useState, useEffect, useCallback, useRef } from 'react';+import {+ Undo2,+ Redo2,+ Search,+ Replace,+ Maximize,+ Minimize,+ Save,+ Keyboard,+ X,+} from 'lucide-react';+import { ReportTemplate, ReportComponent } from '@/services/core/reportService';+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';+import { toast } from 'sonner';++// ============ Undo/Redo History Hook ============+interface HistoryState<T> {+ past: T[];+ present: T;+ future: T[];+}++export const useUndoRedo = <T,>(initialState: T, maxHistory: number = 50) => {+ const [history, setHistory] = useState<HistoryState<T>>({+ past: [],+ present: initialState,+ future: [],+ });++ const canUndo = history.past.length > 0;+ const canRedo = history.future.length > 0;++ const set = useCallback((newState: T | ((prev: T) => T)) => {+ setHistory(prev => {+ const nextState = typeof newState === 'function'+ ? (newState as (prev: T) => T)(prev.present)+ : newState;++ // Don't add to history if state hasn't changed+ if (JSON.stringify(nextState) === JSON.stringify(prev.present)) {+ return prev;+ }++ return {+ past: [...prev.past, prev.present].slice(-maxHistory),+ present: nextState,+ future: [],+ };+ });+ }, [maxHistory]);++ const undo = useCallback(() => {+ setHistory(prev => {+ if (prev.past.length === 0) return prev;+ const previous = prev.past[prev.past.length - 1];+ const newPast = prev.past.slice(0, -1);+ return {+ past: newPast,+ present: previous,+ future: [prev.present, ...prev.future],+ };+ });+ }, []);++ const redo = useCallback(() => {+ setHistory(prev => {+ if (prev.future.length === 0) return prev;+ const next = prev.future[0];+ const newFuture = prev.future.slice(1);+ return {+ past: [...prev.past, prev.present],+ present: next,+ future: newFuture,+ };+ });+ }, []);++ const reset = useCallback((newState: T) => {+ setHistory({+ past: [],+ present: newState,+ future: [],+ });+ }, []);++ return {+ state: history.present,+ set,+ undo,+ redo,+ reset,+ canUndo,+ canRedo,+ historyLength: history.past.length,+ };+};++// ============ Auto-Save Hook ============+interface AutoSaveConfig {+ interval?: number; // milliseconds+ enabled?: boolean;+}++export const useAutoSave = <T,>(+ data: T,+ onSave: (data: T) => Promise<void>,+ config: AutoSaveConfig = {}+) => {+ const { interval = 30000, enabled = true } = config;+ const [lastSaved, setLastSaved] = useState<Date | null>(null);+ const [isSaving, setIsSaving] = useState(false);+ const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);+ const lastDataRef = useRef<string>(JSON.stringify(data));+ const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ useEffect(() => {+ const currentData = JSON.stringify(data);+ if (currentData !== lastDataRef.current) {+ setHasUnsavedChanges(true);+ }+ }, [data]);++ useEffect(() => {+ if (!enabled || !hasUnsavedChanges) return;++ // Clear existing timeout+ if (timeoutRef.current) {+ clearTimeout(timeoutRef.current);+ }++ // Set new timeout+ timeoutRef.current = setTimeout(async () => {+ try {+ setIsSaving(true);+ await onSave(data);+ lastDataRef.current = JSON.stringify(data);+ setLastSaved(new Date());+ setHasUnsavedChanges(false);+ } catch (error) {+ console.error('Auto-save failed:', error);+ } finally {+ setIsSaving(false);+ }+ }, interval);++ return () => {+ if (timeoutRef.current) {+ clearTimeout(timeoutRef.current);+ }+ };+ }, [data, enabled, hasUnsavedChanges, interval, onSave]);++ const saveNow = useCallback(async () => {+ try {+ setIsSaving(true);+ await onSave(data);+ lastDataRef.current = JSON.stringify(data);+ setLastSaved(new Date());+ setHasUnsavedChanges(false);+ toast.success('Saved');+ } catch (error) {+ toast.error('Save failed');+ } finally {+ setIsSaving(false);+ }+ }, [data, onSave]);++ return {+ lastSaved,+ isSaving,+ hasUnsavedChanges,+ saveNow,+ forceSave: saveNow,+ };+};++// ============ Keyboard Shortcuts Hook ============+interface ShortcutAction {+ key: string;+ ctrl?: boolean;+ shift?: boolean;+ alt?: boolean;+ action: () => void;+ description: string;+}++type ShortcutMap = Record<string, () => void>;++// Parse shortcut string like 'ctrl+z' into components+const parseShortcut = (shortcutStr: string): { key: string; ctrl: boolean; shift: boolean; alt: boolean } => {+ const parts = shortcutStr.toLowerCase().split('+');+ return {+ key: parts[parts.length - 1],+ ctrl: parts.includes('ctrl'),+ shift: parts.includes('shift'),+ alt: parts.includes('alt'),+ };+};++export const useKeyboardShortcuts = (shortcuts: ShortcutMap, enabled: boolean = true) => {+ useEffect(() => {+ if (!enabled) return;++ const handleKeyDown = (e: KeyboardEvent) => {+ for (const [shortcutStr, action] of Object.entries(shortcuts)) {+ const { key, ctrl, shift, alt } = parseShortcut(shortcutStr);+ const keyMatch = e.key.toLowerCase() === key.toLowerCase();+ const ctrlMatch = ctrl ? (e.ctrlKey || e.metaKey) : !(e.ctrlKey || e.metaKey);+ const shiftMatch = shift ? e.shiftKey : !e.shiftKey;+ const altMatch = alt ? e.altKey : !e.altKey;++ if (keyMatch && ctrlMatch && shiftMatch && altMatch) {+ e.preventDefault();+ action();+ return;+ }+ }+ };++ window.addEventListener('keydown', handleKeyDown);+ return () => window.removeEventListener('keydown', handleKeyDown);+ }, [shortcuts, enabled]);+};++// ============ Find & Replace Dialog ============+interface FindReplaceDialogProps {+ open: boolean;+ onClose: () => void;+ components: ReportComponent[];+ onReplace: (componentId: string, oldText: string, newText: string) => void;+}++export const FindReplaceDialog: React.FC<FindReplaceDialogProps> = ({+ open,+ onClose,+ components,+ onReplace,+}) => {+ const [findText, setFindText] = useState('');+ const [replaceText, setReplaceText] = useState('');+ const [matches, setMatches] = useState<{ componentId: string; content: string; index: number }[]>([]);+ const [currentMatch, setCurrentMatch] = useState(0);+ const [caseSensitive, setCaseSensitive] = useState(false);++ useEffect(() => {+ if (!findText) {+ setMatches([]);+ return;+ }++ const found: typeof matches = [];+ const searchText = caseSensitive ? findText : findText.toLowerCase();++ components.forEach(comp => {+ if (typeof comp.content === 'string') {+ const content = caseSensitive ? comp.content : comp.content.toLowerCase();+ let index = content.indexOf(searchText);+ while (index !== -1) {+ found.push({ componentId: comp.id, content: comp.content, index });+ index = content.indexOf(searchText, index + 1);+ }+ }+ });++ setMatches(found);+ setCurrentMatch(0);+ }, [findText, components, caseSensitive]);++ const handleReplaceOne = () => {+ if (matches.length === 0) return;+ const match = matches[currentMatch];+ const comp = components.find(c => c.id === match.componentId);+ if (!comp || typeof comp.content !== 'string') return;++ const flags = caseSensitive ? '' : 'i';+ const regex = new RegExp(findText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), flags);+ const newContent = comp.content.replace(regex, replaceText);+ onReplace(match.componentId, comp.content, newContent);+ toast.success('Replaced 1 occurrence');+ };++ const handleReplaceAll = () => {+ if (matches.length === 0) return;++ const componentIds = [...new Set(matches.map(m => m.componentId))];+ componentIds.forEach(id => {+ const comp = components.find(c => c.id === id);+ if (!comp || typeof comp.content !== 'string') return;++ const flags = caseSensitive ? 'g' : 'gi';+ const regex = new RegExp(findText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), flags);+ const newContent = comp.content.replace(regex, replaceText);+ onReplace(id, comp.content, newContent);+ });++ toast.success(`Replaced ${matches.length} occurrences`);+ };++ return (+ <Dialog open={open} onOpenChange={onClose}>+ <DialogContent className="bg-[#1a1a1a] border-[#333333] max-w-md">+ <DialogHeader>+ <DialogTitle className="text-[#FFA500] flex items-center gap-2">+ <Search size={18} />+ Find & Replace+ </DialogTitle>+ </DialogHeader>++ <div className="space-y-4">+ {/* Find */}+ <div>+ <label className="text-xs text-gray-400 block mb-1">Find</label>+ <input+ type="text"+ value={findText}+ onChange={(e) => setFindText(e.target.value)}+ placeholder="Search text..."+ className="w-full px-3 py-2 text-sm bg-[#0a0a0a] border border-[#333333] rounded text-white focus:border-[#FFA500] outline-none"+ autoFocus+ />+ </div>++ {/* Replace */}+ <div>+ <label className="text-xs text-gray-400 block mb-1">Replace with</label>+ <input+ type="text"+ value={replaceText}+ onChange={(e) => setReplaceText(e.target.value)}+ placeholder="Replacement text..."+ className="w-full px-3 py-2 text-sm bg-[#0a0a0a] border border-[#333333] rounded text-white focus:border-[#FFA500] outline-none"+ />+ </div>++ {/* Options */}+ <label className="flex items-center gap-2 text-xs text-gray-400">+ <input+ type="checkbox"+ checked={caseSensitive}+ onChange={(e) => setCaseSensitive(e.target.checked)}+ className="rounded"+ />+ Case sensitive+ </label>++ {/* Results */}+ <div className="text-xs text-gray-500">+ {matches.length > 0 ? (+ <span>{matches.length} match(es) found</span>+ ) : findText ? (+ <span>No matches found</span>+ ) : null}+ </div>++ {/* Actions */}+ <div className="flex gap-2">+ <button+ onClick={handleReplaceOne}+ disabled={matches.length === 0}+ className="flex-1 py-2 text-xs bg-[#333333] text-white rounded hover:bg-[#444444] disabled:opacity-50"+ >+ Replace+ </button>+ <button+ onClick={handleReplaceAll}+ disabled={matches.length === 0}+ className="flex-1 py-2 text-xs bg-[#FFA500] text-black rounded hover:bg-[#ff8c00] disabled:opacity-50"+ >+ Replace All+ </button>+ </div>+ </div>+ </DialogContent>+ </Dialog>+ );+};++// ============ Keyboard Shortcuts Dialog ============+interface ShortcutsDialogProps {+ open: boolean;+ onClose: () => void;+}++const SHORTCUTS_LIST = [+ { keys: 'Ctrl + Z', action: 'Undo' },+ { keys: 'Ctrl + Shift + Z', action: 'Redo' },+ { keys: 'Ctrl + S', action: 'Save' },+ { keys: 'Ctrl + F', action: 'Find & Replace' },+ { keys: 'Ctrl + E', action: 'Export' },+ { keys: 'Ctrl + T', action: 'Template Gallery' },+ { keys: 'Ctrl + P', action: 'Print Preview' },+ { keys: 'F11', action: 'Toggle Fullscreen' },+ { keys: 'Escape', action: 'Deselect / Close' },+ { keys: 'Delete', action: 'Delete Selected' },+ { keys: 'Ctrl + D', action: 'Duplicate Selected' },+ { keys: 'Ctrl + 1', action: 'Add Heading' },+ { keys: 'Ctrl + 2', action: 'Add Text' },+ { keys: 'Ctrl + 3', action: 'Add Chart' },+ { keys: 'Ctrl + 4', action: 'Add Table' },+];++export const ShortcutsDialog: React.FC<ShortcutsDialogProps> = ({ open, onClose }) => (+ <Dialog open={open} onOpenChange={onClose}>+ <DialogContent className="bg-[#1a1a1a] border-[#333333] max-w-md">+ <DialogHeader>+ <DialogTitle className="text-[#FFA500] flex items-center gap-2">+ <Keyboard size={18} />+ Keyboard Shortcuts+ </DialogTitle>+ </DialogHeader>++ <div className="space-y-1 max-h-[400px] overflow-y-auto">+ {SHORTCUTS_LIST.map((shortcut, idx) => (+ <div+ key={idx}+ className="flex items-center justify-between py-2 px-2 hover:bg-[#2a2a2a] rounded"+ >+ <span className="text-xs text-gray-300">{shortcut.action}</span>+ <kbd className="px-2 py-1 text-[10px] bg-[#0a0a0a] border border-[#333333] rounded text-gray-400">+ {shortcut.keys}+ </kbd>+ </div>+ ))}+ </div>+ </DialogContent>+ </Dialog>+);++// ============ Fullscreen Mode Hook ============+export const useFullscreen = (externalRef?: React.RefObject<HTMLElement>) => {+ const internalRef = useRef<HTMLElement>(null);+ const elementRef = externalRef || internalRef;+ const [isFullscreen, setIsFullscreen] = useState(false);++ useEffect(() => {+ const handleChange = () => {+ setIsFullscreen(!!document.fullscreenElement);+ };++ document.addEventListener('fullscreenchange', handleChange);+ return () => document.removeEventListener('fullscreenchange', handleChange);+ }, []);++ const enterFullscreen = useCallback(() => {+ const element = elementRef.current || document.documentElement;+ element.requestFullscreen?.();+ }, [elementRef]);++ const exitFullscreen = useCallback(() => {+ document.exitFullscreen?.();+ }, []);++ const toggleFullscreen = useCallback(() => {+ if (isFullscreen) {+ exitFullscreen();+ } else {+ enterFullscreen();+ }+ }, [isFullscreen, enterFullscreen, exitFullscreen]);++ return { isFullscreen, enterFullscreen, exitFullscreen, toggleFullscreen, fullscreenRef: elementRef };+};++// ============ Toolbar Component ============+interface ProductivityToolbarProps {+ canUndo: boolean;+ canRedo: boolean;+ onUndo: () => void;+ onRedo: () => void;+ onSave: () => void;+ onFindReplace: () => void;+ onShortcuts: () => void;+ onFullscreen: () => void;+ isFullscreen: boolean;+ isSaving: boolean;+ hasUnsavedChanges: boolean;+ lastSaved: Date | null;+}++export const ProductivityToolbar: React.FC<ProductivityToolbarProps> = ({+ canUndo,+ canRedo,+ onUndo,+ onRedo,+ onSave,+ onFindReplace,+ onShortcuts,+ onFullscreen,+ isFullscreen,+ isSaving,+ hasUnsavedChanges,+ lastSaved,+}) => (+ <div className="flex items-center gap-1 px-2 py-1 bg-[#1a1a1a] border-b border-[#333333]">+ {/* Undo/Redo */}+ <button+ onClick={onUndo}+ disabled={!canUndo}+ className="p-1.5 rounded hover:bg-[#2a2a2a] disabled:opacity-30 disabled:hover:bg-transparent"+ title="Undo (Ctrl+Z)"+ >+ <Undo2 size={14} className="text-gray-400" />+ </button>+ <button+ onClick={onRedo}+ disabled={!canRedo}+ className="p-1.5 rounded hover:bg-[#2a2a2a] disabled:opacity-30 disabled:hover:bg-transparent"+ title="Redo (Ctrl+Shift+Z)"+ >+ <Redo2 size={14} className="text-gray-400" />+ </button>++ <div className="w-px h-4 bg-[#333333] mx-1" />++ {/* Save */}+ <button+ onClick={onSave}+ className="p-1.5 rounded hover:bg-[#2a2a2a] relative"+ title="Save (Ctrl+S)"+ >+ <Save size={14} className={hasUnsavedChanges ? 'text-[#FFA500]' : 'text-gray-400'} />+ {isSaving && (+ <span className="absolute -top-0.5 -right-0.5 w-2 h-2 bg-[#FFA500] rounded-full animate-pulse" />+ )}+ </button>++ {/* Find/Replace */}+ <button+ onClick={onFindReplace}+ className="p-1.5 rounded hover:bg-[#2a2a2a]"+ title="Find & Replace (Ctrl+F)"+ >+ <Search size={14} className="text-gray-400" />+ </button>++ <div className="w-px h-4 bg-[#333333] mx-1" />++ {/* Fullscreen */}+ <button+ onClick={onFullscreen}+ className="p-1.5 rounded hover:bg-[#2a2a2a]"+ title="Toggle Fullscreen (F11)"+ >+ {isFullscreen ? (+ <Minimize size={14} className="text-gray-400" />+ ) : (+ <Maximize size={14} className="text-gray-400" />+ )}+ </button>++ {/* Shortcuts */}+ <button+ onClick={onShortcuts}+ className="p-1.5 rounded hover:bg-[#2a2a2a]"+ title="Keyboard Shortcuts"+ >+ <Keyboard size={14} className="text-gray-400" />+ </button>++ {/* Auto-save indicator */}+ {lastSaved && (+ <span className="ml-auto text-[10px] text-gray-500">+ Saved {lastSaved.toLocaleTimeString()}+ </span>+ )}+ </div>+);++export default {+ useUndoRedo,+ useAutoSave,+ useKeyboardShortcuts,+ useFullscreen,+ FindReplaceDialog,+ ShortcutsDialog,+ ProductivityToolbar,+};diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/TemplateGallery.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/TemplateGallery.tsxnew file mode 100644index 000000000..8e466d9b0--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/TemplateGallery.tsx@@ -0,0 +1,441 @@+import React, { useState, useEffect } from 'react';+import {+ LayoutTemplate,+ FileText,+ Download,+ Upload,+ Plus,+ Search,+ X,+ Check,+ Eye,+ Trash2,+ Copy,+} from 'lucide-react';+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';+import { Button } from '@/components/ui/button';+import { ReportTemplate } from '@/services/core/reportService';+import { reportService } from '@/services/core/reportService';+import { save, open as openDialog } from '@tauri-apps/plugin-dialog';+import { writeTextFile, readTextFile } from '@tauri-apps/plugin-fs';+import { toast } from 'sonner';++// Export template type for external use+export type ReportTemplateType = Partial<ReportTemplate>;++// Pre-built Templates+const PRE_BUILT_TEMPLATES: ReportTemplateType[] = [+ {+ id: 'equity-research',+ name: 'Equity Research Report',+ description: 'Professional equity research with buy/sell recommendations',+ components: [+ { id: 'c1', type: 'coverpage', content: '', config: { subtitle: 'Equity Research', backgroundColor: '#0a0a0a' } },+ { id: 'c2', type: 'pagebreak', content: '', config: {} },+ { id: 'c3', type: 'heading', content: 'Executive Summary', config: { fontSize: '2xl' } },+ { id: 'c4', type: 'text', content: 'Investment thesis and key recommendations...', config: {} },+ { id: 'c5', type: 'divider', content: '', config: {} },+ { id: 'c6', type: 'heading', content: 'Financial Analysis', config: { fontSize: '2xl' } },+ { id: 'c7', type: 'table', content: '', config: { columns: ['Metric', 'FY23', 'FY24E', 'FY25E'] } },+ { id: 'c8', type: 'chart', content: '', config: { chartType: 'line' } },+ ],+ },+ {+ id: 'quarterly-report',+ name: 'Quarterly Report',+ description: 'Standard quarterly financial report template',+ components: [+ { id: 'c1', type: 'heading', content: 'Q4 2024 Financial Report', config: { fontSize: '3xl', alignment: 'center' } },+ { id: 'c2', type: 'divider', content: '', config: {} },+ { id: 'c3', type: 'heading', content: 'Financial Highlights', config: { fontSize: 'xl' } },+ { id: 'c4', type: 'columns', content: '', config: { columnCount: 3 }, children: [] },+ { id: 'c5', type: 'heading', content: 'Revenue Analysis', config: { fontSize: 'xl' } },+ { id: 'c6', type: 'chart', content: '', config: { chartType: 'bar' } },+ { id: 'c7', type: 'heading', content: 'Outlook', config: { fontSize: 'xl' } },+ { id: 'c8', type: 'text', content: 'Management guidance and forward-looking statements...', config: {} },+ ],+ },+ {+ id: 'investment-memo',+ name: 'Investment Memo',+ description: 'Concise investment memorandum for decision makers',+ components: [+ { id: 'c1', type: 'heading', content: 'Investment Memorandum', config: { fontSize: '2xl' } },+ { id: 'c2', type: 'section', content: '', config: { sectionTitle: 'RECOMMENDATION', borderColor: '#10B981', backgroundColor: '#E8F5E9' } },+ { id: 'c3', type: 'heading', content: 'Investment Thesis', config: { fontSize: 'xl' } },+ { id: 'c4', type: 'text', content: 'Core investment rationale...', config: {} },+ { id: 'c5', type: 'columns', content: '', config: { columnCount: 2 }, children: [] },+ { id: 'c6', type: 'heading', content: 'Risk Factors', config: { fontSize: 'xl' } },+ { id: 'c7', type: 'text', content: 'Key risks to monitor...', config: {} },+ ],+ },+ {+ id: 'due-diligence',+ name: 'Due Diligence Report',+ description: 'Comprehensive due diligence checklist and analysis',+ components: [+ { id: 'c1', type: 'coverpage', content: '', config: { subtitle: 'Due Diligence Report', backgroundColor: '#1a1a2e' } },+ { id: 'c2', type: 'pagebreak', content: '', config: {} },+ { id: 'c3', type: 'heading', content: 'Company Overview', config: { fontSize: '2xl' } },+ { id: 'c4', type: 'table', content: '', config: { columns: ['Item', 'Details', 'Status'] } },+ { id: 'c5', type: 'heading', content: 'Financial Review', config: { fontSize: '2xl' } },+ { id: 'c6', type: 'text', content: 'Detailed financial analysis...', config: {} },+ { id: 'c7', type: 'heading', content: 'Legal & Compliance', config: { fontSize: '2xl' } },+ { id: 'c8', type: 'text', content: 'Legal review findings...', config: {} },+ ],+ },+ {+ id: 'market-analysis',+ name: 'Market Analysis',+ description: 'Industry and market analysis report',+ components: [+ { id: 'c1', type: 'heading', content: 'Market Analysis Report', config: { fontSize: '2xl', alignment: 'center' } },+ { id: 'c2', type: 'text', content: 'Comprehensive market overview and trends...', config: { alignment: 'center' } },+ { id: 'c3', type: 'divider', content: '', config: {} },+ { id: 'c4', type: 'heading', content: 'Market Size & Growth', config: { fontSize: 'xl' } },+ { id: 'c5', type: 'chart', content: '', config: { chartType: 'area' } },+ { id: 'c6', type: 'heading', content: 'Competitive Landscape', config: { fontSize: 'xl' } },+ { id: 'c7', type: 'chart', content: '', config: { chartType: 'pie' } },+ ],+ },+ {+ id: 'portfolio-summary',+ name: 'Portfolio Summary',+ description: 'Portfolio holdings and performance summary',+ components: [+ { id: 'c1', type: 'heading', content: 'Portfolio Summary', config: { fontSize: '2xl' } },+ { id: 'c2', type: 'columns', content: '', config: { columnCount: 3 }, children: [] },+ { id: 'c3', type: 'heading', content: 'Holdings', config: { fontSize: 'xl' } },+ { id: 'c4', type: 'table', content: '', config: { columns: ['Symbol', 'Shares', 'Value', 'Weight', 'Return'] } },+ { id: 'c5', type: 'heading', content: 'Performance', config: { fontSize: 'xl' } },+ { id: 'c6', type: 'chart', content: '', config: { chartType: 'line' } },+ ],+ },+];++interface TemplateGalleryProps {+ open: boolean;+ onClose: () => void;+ onSelectTemplate: (template: ReportTemplate) => void;+ currentTemplate?: ReportTemplate;+}++export const TemplateGallery: React.FC<TemplateGalleryProps> = ({+ open,+ onClose,+ onSelectTemplate,+ currentTemplate,+}) => {+ const [searchQuery, setSearchQuery] = useState('');+ const [savedTemplates, setSavedTemplates] = useState<ReportTemplate[]>([]);+ const [selectedCategory, setSelectedCategory] = useState<'all' | 'prebuilt' | 'saved'>('all');+ const [previewTemplate, setPreviewTemplate] = useState<Partial<ReportTemplate> | null>(null);++ useEffect(() => {+ loadSavedTemplates();+ }, [open]);++ const loadSavedTemplates = async () => {+ try {+ const templates = await reportService.getTemplates();+ setSavedTemplates(templates);+ } catch (error) {+ console.error('Failed to load templates:', error);+ }+ };++ const handleUseTemplate = (template: Partial<ReportTemplate>) => {+ const fullTemplate: ReportTemplate = {+ id: `report-${Date.now()}`,+ name: template.name || 'New Report',+ description: template.description || '',+ components: template.components || [],+ metadata: {+ author: '',+ company: '',+ date: new Date().toISOString().split('T')[0],+ title: template.name || 'New Report',+ },+ styles: {+ pageSize: 'A4',+ orientation: 'portrait',+ margins: '20mm',+ headerFooter: true,+ },+ };+ onSelectTemplate(fullTemplate);+ onClose();+ toast.success(`Template "${template.name}" applied`);+ };++ const handleExportTemplate = async () => {+ if (!currentTemplate) return;+ try {+ const filePath = await save({+ filters: [{ name: 'JSON', extensions: ['json'] }],+ defaultPath: `${currentTemplate.name}.json`,+ });+ if (filePath) {+ await writeTextFile(filePath, JSON.stringify(currentTemplate, null, 2));+ toast.success('Template exported');+ }+ } catch (error) {+ toast.error('Export failed');+ }+ };++ const handleImportTemplate = async () => {+ try {+ const filePath = await openDialog({+ filters: [{ name: 'JSON', extensions: ['json'] }],+ multiple: false,+ });+ if (filePath && typeof filePath === 'string') {+ const content = await readTextFile(filePath);+ const template = JSON.parse(content) as ReportTemplate;+ template.id = `report-${Date.now()}`;+ onSelectTemplate(template);+ onClose();+ toast.success('Template imported');+ }+ } catch (error) {+ toast.error('Import failed');+ }+ };++ const handleDeleteSaved = async (id: string) => {+ try {+ await reportService.deleteTemplate(id);+ loadSavedTemplates();+ toast.success('Template deleted');+ } catch (error) {+ toast.error('Delete failed');+ }+ };++ const filteredPrebuilt = PRE_BUILT_TEMPLATES.filter(t =>+ t.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||+ t.description?.toLowerCase().includes(searchQuery.toLowerCase())+ );++ const filteredSaved = savedTemplates.filter(t =>+ t.name.toLowerCase().includes(searchQuery.toLowerCase())+ );++ const showPrebuilt = selectedCategory === 'all' || selectedCategory === 'prebuilt';+ const showSaved = selectedCategory === 'all' || selectedCategory === 'saved';++ return (+ <Dialog open={open} onOpenChange={onClose}>+ <DialogContent className="bg-[#1a1a1a] border-[#333333] max-w-4xl max-h-[85vh]">+ <DialogHeader>+ <DialogTitle className="text-[#FFA500] flex items-center gap-2">+ <LayoutTemplate size={20} />+ Template Gallery+ </DialogTitle>+ </DialogHeader>++ <div className="flex flex-col gap-4">+ {/* Top Bar */}+ <div className="flex items-center gap-3">+ {/* Search */}+ <div className="flex-1 relative">+ <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" />+ <input+ type="text"+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ placeholder="Search templates..."+ className="w-full pl-9 pr-3 py-2 text-xs bg-[#0a0a0a] border border-[#333333] rounded text-white focus:border-[#FFA500] outline-none"+ />+ </div>++ {/* Category Filter */}+ <div className="flex gap-1">+ {(['all', 'prebuilt', 'saved'] as const).map(cat => (+ <button+ key={cat}+ onClick={() => setSelectedCategory(cat)}+ className={`px-3 py-2 text-xs rounded capitalize ${+ selectedCategory === cat+ ? 'bg-[#FFA500] text-black'+ : 'bg-[#0a0a0a] text-gray-400 hover:bg-[#2a2a2a]'+ }`}+ >+ {cat}+ </button>+ ))}+ </div>++ {/* Import/Export */}+ <Button+ size="sm"+ variant="outline"+ onClick={handleImportTemplate}+ className="bg-transparent border-[#333333] text-white text-xs"+ >+ <Upload size={14} className="mr-1" />+ Import+ </Button>+ {currentTemplate && (+ <Button+ size="sm"+ variant="outline"+ onClick={handleExportTemplate}+ className="bg-transparent border-[#333333] text-white text-xs"+ >+ <Download size={14} className="mr-1" />+ Export+ </Button>+ )}+ </div>++ {/* Templates Grid */}+ <div className="overflow-y-auto max-h-[55vh] pr-2">+ {/* Pre-built Templates */}+ {showPrebuilt && filteredPrebuilt.length > 0 && (+ <div className="mb-6">+ <h3 className="text-xs font-semibold text-[#FFA500] mb-3">PRE-BUILT TEMPLATES</h3>+ <div className="grid grid-cols-3 gap-3">+ {filteredPrebuilt.map(template => (+ <TemplateCard+ key={template.id}+ template={template}+ onUse={() => handleUseTemplate(template)}+ onPreview={() => setPreviewTemplate(template)}+ />+ ))}+ </div>+ </div>+ )}++ {/* Saved Templates */}+ {showSaved && (+ <div>+ <h3 className="text-xs font-semibold text-[#FFA500] mb-3">SAVED TEMPLATES</h3>+ {filteredSaved.length === 0 ? (+ <p className="text-xs text-gray-500 text-center py-8">No saved templates</p>+ ) : (+ <div className="grid grid-cols-3 gap-3">+ {filteredSaved.map(template => (+ <TemplateCard+ key={template.id}+ template={template}+ onUse={() => handleUseTemplate(template)}+ onPreview={() => setPreviewTemplate(template)}+ onDelete={() => handleDeleteSaved(template.id)}+ isSaved+ />+ ))}+ </div>+ )}+ </div>+ )}+ </div>+ </div>++ {/* Preview Modal */}+ {previewTemplate && (+ <Dialog open={!!previewTemplate} onOpenChange={() => setPreviewTemplate(null)}>+ <DialogContent className="bg-[#1a1a1a] border-[#333333] max-w-2xl">+ <DialogHeader>+ <DialogTitle className="text-white">{previewTemplate.name}</DialogTitle>+ </DialogHeader>+ <div className="space-y-3">+ <p className="text-xs text-gray-400">{previewTemplate.description}</p>+ <div className="bg-[#0a0a0a] rounded p-4 max-h-[400px] overflow-y-auto">+ <p className="text-xs text-gray-500 mb-2">Components:</p>+ {previewTemplate.components?.map((comp, idx) => (+ <div key={idx} className="flex items-center gap-2 py-1 text-xs text-gray-300">+ <span className="w-4 h-4 rounded bg-[#FFA500]/20 text-[#FFA500] flex items-center justify-center text-[10px]">+ {idx + 1}+ </span>+ <span className="capitalize">{comp.type}</span>+ {comp.content && typeof comp.content === 'string' && (+ <span className="text-gray-500 truncate max-w-[200px]">- {comp.content}</span>+ )}+ </div>+ ))}+ </div>+ <div className="flex justify-end gap-2">+ <Button+ variant="outline"+ onClick={() => setPreviewTemplate(null)}+ className="bg-transparent border-[#333333] text-white"+ >+ Cancel+ </Button>+ <Button+ onClick={() => {+ handleUseTemplate(previewTemplate);+ setPreviewTemplate(null);+ }}+ className="bg-[#FFA500] text-black"+ >+ <Check size={14} className="mr-1" />+ Use Template+ </Button>+ </div>+ </div>+ </DialogContent>+ </Dialog>+ )}+ </DialogContent>+ </Dialog>+ );+};++// Template Card Component+interface TemplateCardProps {+ template: Partial<ReportTemplate>;+ onUse: () => void;+ onPreview: () => void;+ onDelete?: () => void;+ isSaved?: boolean;+}++const TemplateCard: React.FC<TemplateCardProps> = ({ template, onUse, onPreview, onDelete, isSaved }) => (+ <div className="bg-[#0a0a0a] border border-[#333333] rounded-lg p-3 hover:border-[#FFA500] transition-all group">+ {/* Preview Area */}+ <div className="h-24 bg-[#1a1a1a] rounded mb-3 flex items-center justify-center relative overflow-hidden">+ <FileText size={32} className="text-[#333333]" />+ <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">+ <button+ onClick={onPreview}+ className="p-2 bg-[#2a2a2a] rounded hover:bg-[#3a3a3a]"+ title="Preview"+ >+ <Eye size={14} className="text-white" />+ </button>+ <button+ onClick={onUse}+ className="p-2 bg-[#FFA500] rounded hover:bg-[#ff8c00]"+ title="Use Template"+ >+ <Check size={14} className="text-black" />+ </button>+ </div>+ </div>++ {/* Info */}+ <h4 className="text-sm font-semibold text-white mb-1 truncate">{template.name}</h4>+ <p className="text-[10px] text-gray-500 line-clamp-2 h-8">{template.description}</p>++ {/* Footer */}+ <div className="flex items-center justify-between mt-2 pt-2 border-t border-[#333333]">+ <span className="text-[10px] text-gray-500">+ {template.components?.length || 0} components+ </span>+ {isSaved && onDelete && (+ <button+ onClick={(e) => { e.stopPropagation(); onDelete(); }}+ className="p-1 text-gray-500 hover:text-red-500"+ >+ <Trash2 size={12} />+ </button>+ )}+ </div>+ </div>+);++export default TemplateGallery;diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/SettingsTab.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/SettingsTab.tsxnew file mode 100644index 000000000..df3372db9--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/SettingsTab.tsx@@ -0,0 +1,331 @@+import React, { useState, useEffect } from 'react';+import { Settings as SettingsIcon, Lock, Bot, Database, Terminal, Activity, Globe, TrendingUp, Briefcase, HardDrive } from 'lucide-react';+import { useTerminalTheme } from '@/contexts/ThemeContext';+import { useTimezone } from '@/contexts/TimezoneContext';+import { useTranslation } from 'react-i18next';+import { useAuth } from '@/contexts/AuthContext';+import { TabFooter } from '@/components/common/TabFooter';++// External panels from settings folder+import { DataSourcesPanel } from '@/components/settings/DataSourcesPanel';+import { BacktestingProvidersPanel } from '@/components/settings/BacktestingProvidersPanel';+import { LanguageSelector } from '@/components/settings/LanguageSelector';+import { TerminalConfigPanel } from '@/components/settings/TerminalConfigPanel';+import { PolymarketCredentialsPanel } from '@/components/settings/PolymarketCredentialsPanel';+import { MasterContractManager } from '@/components/tabs/equity-trading/components';++// Section components+import {+ CredentialsSection,+ LLMConfigSection,+ TerminalAppearanceSection,+ StorageCacheSection,+} from './sections';++// Hooks and types+import { useSettingsData } from './hooks';+import type { SettingsSection, SettingsColors } from './types';++export default function SettingsTab() {+ const { t } = useTranslation('settings');+ const { session } = useAuth();+ const { theme, updateTheme, resetTheme, colors } = useTerminalTheme();+ const { defaultTimezone, setDefaultTimezone, options: timezoneOptions } = useTimezone();+ const [activeSection, setActiveSection] = useState<SettingsSection>('credentials');++ const {+ apiKeys,+ setApiKeys,+ loading,+ setLoading,+ message,+ setMessage,+ showMessage,+ dbInitialized,+ llmConfigs,+ setLlmConfigs,+ llmGlobalSettings,+ setLlmGlobalSettings,+ modelConfigs,+ keyMappings,+ setKeyMappings,+ checkAndLoadData,+ loadLLMConfigs,+ } = useSettingsData();++ useEffect(() => {+ checkAndLoadData(session?.api_key ?? undefined);+ }, []);++ const settingsColors: SettingsColors = {+ background: colors.background,+ panel: colors.panel,+ primary: colors.primary,+ secondary: colors.secondary,+ text: colors.text,+ textMuted: colors.textMuted,+ success: colors.success,+ alert: colors.alert,+ warning: colors.warning,+ accent: colors.accent,+ };++ const sidebarItems = [+ { id: 'credentials' as SettingsSection, icon: Lock, label: t('sidebar.credentials') },+ { id: 'polymarket' as SettingsSection, icon: TrendingUp, label: t('sidebar.polymarket') },+ { id: 'llm' as SettingsSection, icon: Bot, label: t('sidebar.llm') },+ { id: 'dataConnections' as SettingsSection, icon: Database, label: t('sidebar.dataSources') },+ { id: 'backtesting' as SettingsSection, icon: Activity, label: t('sidebar.backtesting') },+ { id: 'stockSymbols' as SettingsSection, icon: Briefcase, label: 'Stock Symbols' },+ { id: 'terminalConfig' as SettingsSection, icon: SettingsIcon, label: t('sidebar.tabLayout') },+ { id: 'terminal' as SettingsSection, icon: Terminal, label: t('sidebar.appearance') },+ { id: 'language' as SettingsSection, icon: Globe, label: t('sidebar.language') },+ { id: 'storage' as SettingsSection, icon: HardDrive, label: 'Storage & Cache' },+ ];++ return (+ <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: colors.background }}>+ <style>{`+ *::-webkit-scrollbar { width: 8px; height: 8px; }+ *::-webkit-scrollbar-track { background: ${colors.panel}; }+ *::-webkit-scrollbar-thumb { background: #2a2a2a; border-radius: 4px; }+ *::-webkit-scrollbar-thumb:hover { background: #3a3a3a; }++ @keyframes pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.5; }+ }++ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }++ @keyframes slideIn {+ from { transform: translateX(-10px); opacity: 0; }+ to { transform: translateX(0); opacity: 1; }+ }+ `}</style>++ {/* Header */}+ <div style={{+ borderBottom: `2px solid ${colors.primary}`,+ padding: '12px 16px',+ background: `linear-gradient(180deg, #1a1a1a 0%, ${colors.panel} 100%)`,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ flexShrink: 0+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <SettingsIcon size={20} color={colors.primary} />+ <span style={{ color: colors.primary, fontSize: '16px', fontWeight: 'bold', letterSpacing: '1px' }}>+ {t('title')}+ </span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <div style={{+ padding: '4px 8px',+ background: dbInitialized ? '#0a3a0a' : '#3a0a0a',+ border: `1px solid ${dbInitialized ? '#00ff00' : '#ff0000'}`,+ borderRadius: '3px'+ }}>+ <span style={{ color: dbInitialized ? '#00ff00' : '#ff0000', fontSize: '9px', fontWeight: 'bold' }}>+ <Database size={10} style={{ display: 'inline', marginRight: '4px' }} />+ SQLite: {dbInitialized ? t('llm.connected') : t('llm.disconnected')}+ </span>+ </div>+ </div>+ </div>++ {/* Message Banner */}+ {message && (+ <div style={{+ padding: '8px 16px',+ background: message.type === 'success' ? '#0a3a0a' : '#3a0a0a',+ borderBottom: `1px solid ${message.type === 'success' ? '#00ff00' : '#ff0000'}`,+ color: message.type === 'success' ? '#00ff00' : '#ff0000',+ fontSize: '10px',+ flexShrink: 0+ }}>+ {message.text}+ </div>+ )}++ {/* Main Layout */}+ <div style={{ flex: 1, display: 'flex', minHeight: 0, overflow: 'hidden' }}>+ {/* Sidebar Navigation */}+ <div style={{ width: '220px', borderRight: '1px solid #1a1a1a', background: colors.panel, flexShrink: 0 }}>+ <div style={{ padding: '16px 0' }}>+ {sidebarItems.map((item) => (+ <div+ key={item.id}+ onClick={() => setActiveSection(item.id)}+ style={{+ padding: '12px 16px',+ cursor: 'pointer',+ background: activeSection === item.id ? '#1a1a1a' : 'transparent',+ borderLeft: activeSection === item.id ? `3px solid ${colors.primary}` : '3px solid transparent',+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ if (activeSection !== item.id) e.currentTarget.style.background = '#151515';+ }}+ onMouseLeave={(e) => {+ if (activeSection !== item.id) e.currentTarget.style.background = 'transparent';+ }}+ >+ <item.icon size={16} color={activeSection === item.id ? colors.primary : colors.text} />+ <span style={{ color: colors.text, fontSize: '11px', fontWeight: activeSection === item.id ? 'bold' : 'normal' }}>+ {item.label}+ </span>+ </div>+ ))}+ </div>+ </div>++ {/* Main Content */}+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, overflow: 'hidden' }}>+ <div style={{ flex: 1, overflowY: 'auto', padding: '20px', minHeight: 0 }}>+ {/* Credentials Section */}+ {activeSection === 'credentials' && (+ <CredentialsSection+ colors={settingsColors}+ apiKeys={apiKeys}+ setApiKeys={setApiKeys}+ loading={loading}+ setLoading={setLoading}+ showMessage={showMessage}+ />+ )}++ {/* Polymarket API Section */}+ {activeSection === 'polymarket' && (+ <PolymarketCredentialsPanel />+ )}++ {/* LLM Configuration Section */}+ {activeSection === 'llm' && (+ <LLMConfigSection+ colors={settingsColors}+ llmConfigs={llmConfigs}+ setLlmConfigs={setLlmConfigs}+ llmGlobalSettings={llmGlobalSettings}+ setLlmGlobalSettings={setLlmGlobalSettings}+ modelConfigs={modelConfigs}+ loading={loading}+ setLoading={setLoading}+ showMessage={showMessage}+ loadLLMConfigs={loadLLMConfigs}+ sessionApiKey={session?.api_key ?? undefined}+ />+ )}++ {/* Terminal Tab Configuration Section */}+ {activeSection === 'terminalConfig' && (+ <TerminalConfigPanel />+ )}++ {/* Terminal Appearance Section */}+ {activeSection === 'terminal' && (+ <TerminalAppearanceSection+ colors={settingsColors}+ theme={theme}+ updateTheme={updateTheme}+ resetTheme={resetTheme}+ showMessage={showMessage}+ keyMappings={keyMappings}+ setKeyMappings={setKeyMappings}+ defaultTimezone={defaultTimezone}+ setDefaultTimezone={setDefaultTimezone}+ timezoneOptions={timezoneOptions}+ />+ )}++ {/* Data Sources Section */}+ {activeSection === 'dataConnections' && (+ <DataSourcesPanel colors={settingsColors} />+ )}++ {/* 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+ }} />+ )}++ {/* Stock Symbols Section */}+ {activeSection === 'stockSymbols' && (+ <div style={{ maxWidth: '600px' }}>+ <div style={{ marginBottom: '16px' }}>+ <h2 style={{ fontSize: '16px', fontWeight: 700, color: colors.text, margin: 0 }}>+ Stock Symbol Database+ </h2>+ <p style={{ fontSize: '11px', color: colors.textMuted, marginTop: '8px', lineHeight: 1.5 }}>+ Download and manage broker symbol data for fast offline search.+ Symbol data includes stocks, F&O, commodities, and currency derivatives.+ Update regularly to get latest instruments and expiries.+ </p>+ </div>+ <MasterContractManager+ brokers={['angelone', 'fyers']}+ onUpdate={(brokerId, result) => {+ if (result.success) {+ setMessage({+ type: 'success',+ text: `${brokerId.toUpperCase()}: Downloaded ${result.symbol_count.toLocaleString()} symbols`+ });+ } else {+ setMessage({+ type: 'error',+ text: `${brokerId.toUpperCase()}: ${result.message}`+ });+ }+ setTimeout(() => setMessage(null), 5000);+ }}+ />+ </div>+ )}++ {/* Language Section */}+ {activeSection === 'language' && (+ <div style={{ padding: '20px' }}>+ <LanguageSelector />+ </div>+ )}++ {/* Storage & Cache Section */}+ {activeSection === 'storage' && (+ <StorageCacheSection+ colors={settingsColors}+ showMessage={showMessage}+ />+ )}+ </div>+ </div>+ </div>++ {/* Footer */}+ <TabFooter+ tabName="SETTINGS"+ leftInfo={[+ { label: t('footer.database'), color: colors.text },+ { label: t('footer.storage'), color: colors.text },+ ]}+ statusInfo={t('footer.secureStorage')}+ backgroundColor={colors.panel}+ borderColor={colors.primary}+ />+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/hooks/index.tsnew file mode 100644index 000000000..9753fc583--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/hooks/index.ts@@ -0,0 +1 @@+export { useSettingsData, DEFAULT_KEY_MAPPINGS } from './useSettingsData';diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/hooks/useSettingsData.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/hooks/useSettingsData.tsnew file mode 100644index 000000000..49965608a--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/hooks/useSettingsData.ts@@ -0,0 +1,162 @@+import { useState, useEffect } from 'react';+import { sqliteService, type LLMConfig, type LLMGlobalSettings, type LLMModelConfig, type ApiKeys } from '@/services/core/sqliteService';+import { getSetting } from '@/services/core/sqliteService';+import type { WSProviderConfig, SettingsMessage } from '../types';++export const DEFAULT_KEY_MAPPINGS = {+ F1: 'dashboard',+ F2: 'markets',+ F3: 'news',+ F4: 'portfolio',+ F5: 'analytics',+ F6: 'watchlist',+ F7: 'equity-research',+ F8: 'screener',+ F9: 'trading',+ F10: 'chat',+ F11: 'fullscreen',+ F12: 'profile'+};++export function useSettingsData() {+ const [apiKeys, setApiKeys] = useState<ApiKeys>({});+ const [loading, setLoading] = useState(false);+ const [message, setMessage] = useState<SettingsMessage | null>(null);+ const [dbInitialized, setDbInitialized] = useState(false);+ const [wsProviders, setWsProviders] = useState<WSProviderConfig[]>([]);+ const [llmConfigs, setLlmConfigs] = useState<LLMConfig[]>([]);+ const [llmGlobalSettings, setLlmGlobalSettings] = useState<LLMGlobalSettings>({+ temperature: 0.7,+ max_tokens: 2048,+ system_prompt: ''+ });+ const [modelConfigs, setModelConfigs] = useState<LLMModelConfig[]>([]);+ const [keyMappings, setKeyMappings] = useState<Record<string, string>>(DEFAULT_KEY_MAPPINGS);++ const showMessage = (type: 'success' | 'error', text: string) => {+ setMessage({ type, text });+ setTimeout(() => setMessage(null), 5000);+ };++ const loadApiKeys = async () => {+ try {+ const keys = await sqliteService.getAllApiKeys();+ setApiKeys(keys);+ } catch (error) {+ console.error('Failed to load API keys:', error);+ }+ };++ const loadWSProviders = async () => {+ try {+ const providers = await sqliteService.getWSProviderConfigs();+ setWsProviders(providers);+ } catch (error) {+ console.error('Failed to load WS providers:', error);+ }+ };++ const loadLLMConfigs = async (sessionApiKey?: string) => {+ try {+ let configs = await sqliteService.getLLMConfigs();++ if (configs.length === 0) {+ const userApiKey = sessionApiKey || '';+ const now = new Date().toISOString();+ const finceptConfig = {+ provider: 'fincept',+ api_key: userApiKey,+ base_url: 'https://finceptbackend.share.zrok.io/research/llm',+ model: 'fincept-llm',+ is_active: true,+ created_at: now,+ updated_at: now,+ };+ await sqliteService.saveLLMConfig(finceptConfig);+ configs = await sqliteService.getLLMConfigs();+ }++ setLlmConfigs(configs);++ const globalSettings = await sqliteService.getLLMGlobalSettings();+ setLlmGlobalSettings(globalSettings);++ const modelCfgs = await sqliteService.getLLMModelConfigs();+ setModelConfigs(modelCfgs);++ return { configs, modelCfgs };+ } catch (error) {+ console.error('Failed to load LLM configs:', error);+ return { configs: [], modelCfgs: [] };+ }+ };++ const loadKeyMappings = async () => {+ const savedMappings = await getSetting('fincept_key_mappings');+ if (savedMappings) {+ try {+ setKeyMappings(JSON.parse(savedMappings));+ } catch (err) {+ console.error('Failed to load key mappings:', err);+ }+ }+ };++ const checkAndLoadData = async (sessionApiKey?: string) => {+ try {+ setLoading(true);+ const isReady = sqliteService.isReady();++ if (!isReady) {+ console.log('[SettingsTab] Database not initialized, initializing now...');+ await sqliteService.initialize();+ }++ const healthCheck = await sqliteService.healthCheck();+ if (!healthCheck.healthy) {+ throw new Error(healthCheck.message);+ }++ setDbInitialized(true);++ await loadApiKeys();+ await loadLLMConfigs(sessionApiKey);+ await loadWSProviders();+ await loadKeyMappings();++ console.log('[SettingsTab] Data loaded successfully');+ } catch (error) {+ console.error('[SettingsTab] Failed to load data:', error);+ const errorMsg = error instanceof Error ? error.message : 'Unknown error';+ showMessage('error', `Failed to load settings: ${errorMsg}`);+ setDbInitialized(false);+ } finally {+ setLoading(false);+ }+ };++ return {+ apiKeys,+ setApiKeys,+ loading,+ setLoading,+ message,+ setMessage,+ showMessage,+ dbInitialized,+ wsProviders,+ setWsProviders,+ llmConfigs,+ setLlmConfigs,+ llmGlobalSettings,+ setLlmGlobalSettings,+ modelConfigs,+ setModelConfigs,+ keyMappings,+ setKeyMappings,+ loadApiKeys,+ loadWSProviders,+ loadLLMConfigs,+ checkAndLoadData,+ };+}diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/index.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/index.tsnew file mode 100644index 000000000..1b6c1a599--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/index.ts@@ -0,0 +1,5 @@+export { default } from './SettingsTab';+export { default as SettingsTab } from './SettingsTab';+export * from './types';+export * from './hooks';+export * from './sections';diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/CredentialsSection.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/CredentialsSection.tsxnew file mode 100644index 000000000..6fa207cf9--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/CredentialsSection.tsx@@ -0,0 +1,118 @@+import React from 'react';+import { Save } from 'lucide-react';+import { sqliteService, PREDEFINED_API_KEYS, type ApiKeys } from '@/services/core/sqliteService';+import { useTranslation } from 'react-i18next';+import type { SettingsColors } from '../types';++interface CredentialsSectionProps {+ colors: SettingsColors;+ apiKeys: ApiKeys;+ setApiKeys: (keys: ApiKeys) => void;+ loading: boolean;+ setLoading: (loading: boolean) => void;+ showMessage: (type: 'success' | 'error', text: string) => void;+}++export function CredentialsSection({+ colors,+ apiKeys,+ setApiKeys,+ loading,+ setLoading,+ showMessage,+}: CredentialsSectionProps) {+ const { t } = useTranslation('settings');++ const handleSaveApiKeyField = async (keyName: string, value: string) => {+ setLoading(true);+ try {+ await sqliteService.setApiKey(keyName, value);+ setApiKeys({ ...apiKeys, [keyName]: value });+ showMessage('success', `${keyName} saved`);+ } catch (error) {+ showMessage('error', 'Failed to save');+ } finally {+ setLoading(false);+ }+ };++ return (+ <div>+ <div style={{ marginBottom: '24px' }}>+ <h2 style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>+ {t('credentials.title')}+ </h2>+ <p style={{ color: colors.text, fontSize: '10px' }}>+ {t('credentials.description')}+ </p>+ </div>++ <div style={{ display: 'grid', gap: '16px' }}>+ {PREDEFINED_API_KEYS.map(({ key, label, description }) => (+ <div+ key={key}+ style={{+ background: colors.panel,+ border: '1px solid #1a1a1a',+ padding: '16px',+ borderRadius: '4px'+ }}+ >+ <h3 style={{ color: colors.primary, fontSize: '12px', fontWeight: 'bold', marginBottom: '4px' }}>+ {label}+ </h3>+ <p style={{ color: colors.text, fontSize: '9px', marginBottom: '12px', opacity: 0.7 }}>+ {description}+ </p>++ <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '12px', alignItems: 'end' }}>+ <div>+ <label style={{ color: colors.text, fontSize: '9px', display: 'block', marginBottom: '4px' }}>+ {t('credentials.apiKey')}+ </label>+ <input+ type="password"+ value={apiKeys[key] || ''}+ onChange={(e) => setApiKeys({ ...apiKeys, [key]: e.target.value })}+ placeholder={t('credentials.enterValue')}+ style={{+ width: '100%',+ background: colors.background,+ border: '1px solid #2a2a2a',+ color: colors.text,+ padding: '8px',+ fontSize: '10px',+ borderRadius: '3px',+ fontFamily: 'monospace'+ }}+ />+ </div>+ <button+ onClick={() => handleSaveApiKeyField(key, apiKeys[key] || '')}+ disabled={loading || !apiKeys[key]}+ style={{+ background: apiKeys[key] ? colors.primary : '#333',+ color: colors.text,+ border: 'none',+ padding: '8px 16px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: (loading || !apiKeys[key]) ? 'not-allowed' : 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ opacity: (loading || !apiKeys[key]) ? 0.5 : 1,+ whiteSpace: 'nowrap'+ }}+ >+ <Save size={14} />+ {t('buttons.save')}+ </button>+ </div>+ </div>+ ))}+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/LLMConfigSection.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/LLMConfigSection.tsxnew file mode 100644index 000000000..71a3512a9--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/LLMConfigSection.tsx@@ -0,0 +1,1454 @@+import React, { useState, useEffect } from 'react';+import { Save, RefreshCw, Bot, Edit3, Zap, Key, Check, Plus, X, Trash2, ToggleLeft, ToggleRight, Eye, EyeOff, Settings as SettingsIcon } from 'lucide-react';+import { sqliteService, type LLMConfig, type LLMGlobalSettings, type LLMModelConfig } from '@/services/core/sqliteService';+import { ollamaService } from '@/services/chat/ollamaService';+import { LLMModelsService, type ModelInfo } from '@/services/llmModelsService';+import type { SettingsColors } from '../types';++interface LLMConfigSectionProps {+ colors: SettingsColors;+ llmConfigs: LLMConfig[];+ setLlmConfigs: React.Dispatch<React.SetStateAction<LLMConfig[]>>;+ llmGlobalSettings: LLMGlobalSettings;+ setLlmGlobalSettings: React.Dispatch<React.SetStateAction<LLMGlobalSettings>>;+ modelConfigs: LLMModelConfig[];+ loading: boolean;+ setLoading: (loading: boolean) => void;+ showMessage: (type: 'success' | 'error', text: string) => void;+ loadLLMConfigs: () => Promise<{ configs: LLMConfig[]; modelCfgs: LLMModelConfig[] }>;+ sessionApiKey?: string;+}++export function LLMConfigSection({+ colors,+ llmConfigs,+ setLlmConfigs,+ llmGlobalSettings,+ setLlmGlobalSettings,+ modelConfigs: initialModelConfigs,+ loading,+ setLoading,+ showMessage,+ loadLLMConfigs,+ sessionApiKey,+}: LLMConfigSectionProps) {+ const [activeProvider, setActiveProvider] = useState<string>('fincept');+ const [ollamaModels, setOllamaModels] = useState<string[]>([]);+ const [ollamaLoading, setOllamaLoading] = useState(false);+ const [ollamaError, setOllamaError] = useState<string | null>(null);+ const [useManualEntry, setUseManualEntry] = useState(false);+ const [providerModels, setProviderModels] = useState<ModelInfo[]>([]);+ const [providerModelsLoading, setProviderModelsLoading] = useState(false);+ const [providerModelsError, setProviderModelsError] = useState<string | null>(null);+ const [modelConfigs, setModelConfigs] = useState<LLMModelConfig[]>(initialModelConfigs);+ const [showAddModel, setShowAddModel] = useState(false);+ const [newModelConfig, setNewModelConfig] = useState({+ provider: 'openai',+ model_id: '',+ display_name: '',+ api_key: '',+ base_url: ''+ });+ const [newModelConfigModels, setNewModelConfigModels] = useState<ModelInfo[]>([]);+ const [showApiKeys, setShowApiKeys] = useState<Record<string, boolean>>({});++ useEffect(() => {+ setModelConfigs(initialModelConfigs);+ }, [initialModelConfigs]);++ useEffect(() => {+ const activeConfig = llmConfigs.find(c => c.is_active);+ const specialProviders = ['fincept', 'ollama'];+ const providersWithModels = new Set(modelConfigs.filter(m => m.is_enabled).map(m => m.provider));++ const isProviderVisible = (provider: string, config?: LLMConfig) => {+ if (specialProviders.includes(provider)) return true;+ if (config?.api_key && config.api_key.trim() !== '') return true;+ if (providersWithModels.has(provider)) return true;+ return false;+ };++ if (activeConfig && isProviderVisible(activeConfig.provider, activeConfig)) {+ setActiveProvider(activeConfig.provider);+ } else {+ setActiveProvider('fincept');+ }+ }, [llmConfigs, modelConfigs]);++ const getCurrentLLMConfig = () => {+ if (activeProvider.startsWith('model:')) {+ const modelId = activeProvider.replace('model:', '');+ const modelConfig = modelConfigs.find(m => m.id === modelId);+ if (modelConfig) {+ return {+ provider: modelConfig.provider,+ api_key: modelConfig.api_key || '',+ base_url: modelConfig.base_url || '',+ model: modelConfig.model_id,+ is_active: true,+ created_at: modelConfig.created_at || new Date().toISOString(),+ updated_at: modelConfig.updated_at || new Date().toISOString()+ } as LLMConfig;+ }+ }+ return llmConfigs.find(c => c.provider === activeProvider);+ };++ const getSelectedModelConfig = () => {+ if (activeProvider.startsWith('model:')) {+ const modelId = activeProvider.replace('model:', '');+ return modelConfigs.find(m => m.id === modelId);+ }+ return null;+ };++ const getVisibleProviderConfigs = () => {+ const specialProviders = ['fincept', 'ollama'];+ const providersWithModels = new Set(modelConfigs.filter(m => m.is_enabled).map(m => m.provider));++ return llmConfigs.filter(config => {+ if (specialProviders.includes(config.provider)) return true;+ if (config.api_key && config.api_key.trim() !== '') return true;+ if (providersWithModels.has(config.provider)) return true;+ return false;+ });+ };++ const visibleProviderConfigs = getVisibleProviderConfigs();++ const updateLLMConfig = (provider: string, field: keyof LLMConfig, value: any) => {+ setLlmConfigs(prev => prev.map(config =>+ config.provider === provider ? { ...config, [field]: value } : config+ ));+ };++ const fetchOllamaModels = async () => {+ setOllamaLoading(true);+ setOllamaError(null);++ const currentConfig = getCurrentLLMConfig();+ const baseUrl = currentConfig?.base_url || 'http://localhost:11434';++ const result = await ollamaService.listModels(baseUrl);++ if (result.success && result.models) {+ setOllamaModels(result.models);+ setOllamaError(null);+ } else {+ setOllamaModels([]);+ setOllamaError(result.error || 'Failed to fetch models');+ }++ setOllamaLoading(false);+ };++ const fetchProviderModels = async (forceRefresh: boolean = false) => {+ const currentConfig = getCurrentLLMConfig();+ if (!currentConfig) return;++ const provider = currentConfig.provider;+ if (provider === 'ollama' || provider === 'fincept') return;++ setProviderModelsLoading(true);+ setProviderModelsError(null);++ try {+ const result = await LLMModelsService.getModels(+ provider,+ currentConfig.api_key || undefined,+ currentConfig.base_url || undefined+ );++ if (result.models && result.models.length > 0) {+ setProviderModels(result.models);+ setProviderModelsError(null);+ } else if (result.error) {+ setProviderModelsError(result.error);+ setProviderModels([]);+ } else {+ setProviderModels([]);+ setProviderModelsError('No models available for this provider');+ }+ } catch (error) {+ setProviderModelsError(error instanceof Error ? error.message : 'Failed to fetch models');+ setProviderModels([]);+ } finally {+ setProviderModelsLoading(false);+ }+ };++ useEffect(() => {+ const loadModels = async () => {+ const currentConfig = getCurrentLLMConfig();+ if (!currentConfig) return;++ const provider = currentConfig.provider;+ setProviderModels([]);+ setProviderModelsError(null);++ if (provider === 'ollama') {+ fetchOllamaModels();+ } else if (provider !== 'fincept') {+ setProviderModelsLoading(true);+ try {+ const result = await LLMModelsService.getModels(+ provider,+ currentConfig.api_key || undefined,+ currentConfig.base_url || undefined+ );+ if (result.models && result.models.length > 0) {+ setProviderModels(result.models);+ }+ } catch (error) {+ console.error('Error fetching models:', error);+ } finally {+ setProviderModelsLoading(false);+ }+ }+ };++ loadModels();+ }, [activeProvider]);++ useEffect(() => {+ const loadNewModelConfigModels = async () => {+ if (!showAddModel) return;++ try {+ const models = await LLMModelsService.getModelsByProvider(newModelConfig.provider);+ if (models && models.length > 0) {+ setNewModelConfigModels(models);+ } else {+ setNewModelConfigModels([]);+ }+ } catch (error) {+ setNewModelConfigModels([]);+ }+ };++ loadNewModelConfigModels();+ }, [newModelConfig.provider, showAddModel]);++ const handleSaveLLMConfig = async () => {+ try {+ setLoading(true);++ if (activeProvider.startsWith('model:')) {+ const modelId = activeProvider.replace('model:', '');+ const selectedModel = modelConfigs.find(m => m.id === modelId);++ if (selectedModel) {+ const modelLLMConfig: LLMConfig = {+ provider: selectedModel.provider,+ api_key: selectedModel.api_key || '',+ base_url: selectedModel.base_url || LLMModelsService.getProviderBaseUrl(selectedModel.provider),+ model: selectedModel.model_id.includes('/')+ ? selectedModel.model_id.split('/').pop() || selectedModel.model_id+ : selectedModel.model_id,+ is_active: true,+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString()+ };++ await sqliteService.saveLLMConfig(modelLLMConfig);+ await sqliteService.setActiveLLMProvider(selectedModel.provider);+ }+ } else {+ for (const config of llmConfigs) {+ await sqliteService.saveLLMConfig(config);+ }+ await sqliteService.setActiveLLMProvider(activeProvider);+ }++ await sqliteService.saveLLMGlobalSettings(llmGlobalSettings);+ showMessage('success', 'LLM configuration saved successfully');+ await loadLLMConfigs();+ } catch (error) {+ showMessage('error', 'Failed to save LLM configuration');+ } finally {+ setLoading(false);+ }+ };++ const handleAddModelConfig = async () => {+ if (!newModelConfig.model_id) {+ showMessage('error', 'Model ID is required');+ return;+ }++ try {+ setLoading(true);+ const id = crypto.randomUUID();+ const displayName = newModelConfig.display_name || `${newModelConfig.provider.toUpperCase()}: ${newModelConfig.model_id}`;++ const result = await sqliteService.saveLLMModelConfig({+ id,+ provider: newModelConfig.provider,+ model_id: newModelConfig.model_id,+ display_name: displayName,+ api_key: newModelConfig.api_key || undefined,+ base_url: newModelConfig.base_url || undefined,+ is_enabled: true,+ is_default: modelConfigs.filter(m => m.provider === newModelConfig.provider).length === 0+ });++ if (result.success) {+ showMessage('success', 'Model configuration added');+ setNewModelConfig({+ provider: 'openai',+ model_id: '',+ display_name: '',+ api_key: '',+ base_url: ''+ });+ setShowAddModel(false);+ await loadLLMConfigs();+ } else {+ showMessage('error', result.message);+ }+ } catch (error) {+ showMessage('error', 'Failed to add model configuration');+ } finally {+ setLoading(false);+ }+ };++ const handleDeleteModelConfig = async (id: string) => {+ try {+ setLoading(true);+ const modelToDelete = modelConfigs.find(m => m.id === id);+ const deletedProvider = modelToDelete?.provider;++ const result = await sqliteService.deleteLLMModelConfig(id);+ if (result.success) {+ showMessage('success', 'Model configuration deleted');++ if (activeProvider === `model:${id}`) {+ setActiveProvider('fincept');+ } else if (deletedProvider && activeProvider === deletedProvider) {+ const remainingModelsForProvider = modelConfigs.filter(+ m => m.id !== id && m.provider === deletedProvider && m.is_enabled+ );+ const providerConfig = llmConfigs.find(c => c.provider === deletedProvider);+ const hasApiKey = providerConfig?.api_key && providerConfig.api_key.trim() !== '';+ const isSpecial = ['fincept', 'ollama'].includes(deletedProvider);++ if (remainingModelsForProvider.length === 0 && !hasApiKey && !isSpecial) {+ setActiveProvider('fincept');+ }+ }++ await loadLLMConfigs();+ } else {+ showMessage('error', result.message);+ }+ } catch (error) {+ showMessage('error', 'Failed to delete model configuration');+ } finally {+ setLoading(false);+ }+ };++ const handleToggleModelEnabled = async (id: string) => {+ try {+ const modelToToggle = modelConfigs.find(m => m.id === id);++ const result = await sqliteService.toggleLLMModelConfigEnabled(id);+ if (result.success) {+ if (modelToToggle?.is_enabled && activeProvider === `model:${id}`) {+ const defaultProvider = llmConfigs.find(c => c.is_active)?.provider || 'fincept';+ setActiveProvider(defaultProvider);+ }++ await loadLLMConfigs();+ }+ } catch (error) {+ showMessage('error', 'Failed to toggle model');+ }+ };++ const currentConfig = getCurrentLLMConfig();++ return (+ <div style={{+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',+ display: 'flex',+ flexDirection: 'column',+ gap: '20px'+ }}>+ {/* Header */}+ <div style={{+ borderBottom: `2px solid ${colors.primary}`,+ padding: '16px 0',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <Bot size={24} color={colors.primary} />+ <div>+ <div style={{+ color: colors.primary,+ fontWeight: 700,+ fontSize: '16px',+ letterSpacing: '0.5px',+ }}>+ LLM CONFIGURATION+ </div>+ <div style={{ color: '#888', fontSize: '12px', marginTop: '2px' }}>+ Configure AI providers, models, and global settings+ </div>+ </div>+ </div>+ <button+ onClick={handleSaveLLMConfig}+ disabled={loading}+ style={{+ background: loading ? '#2A2A2A' : colors.primary,+ color: loading ? '#666' : '#000',+ border: 'none',+ padding: '10px 20px',+ fontSize: '12px',+ fontWeight: 700,+ letterSpacing: '0.5px',+ cursor: loading ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '8px'+ }}+ >+ <Save size={14} />+ {loading ? 'SAVING...' : 'SAVE ALL SETTINGS'}+ </button>+ </div>++ {/* Provider Selection */}+ <div style={{+ backgroundColor: '#0F0F0F',+ border: `1px solid #2A2A2A`,+ padding: '20px'+ }}>+ <div style={{+ color: colors.primary,+ fontSize: '13px',+ fontWeight: 700,+ marginBottom: '16px',+ letterSpacing: '0.5px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px'+ }}>+ <Zap size={16} color={colors.primary} />+ SELECT AI PROVIDER+ </div>++ <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap', marginBottom: '16px' }}>+ {visibleProviderConfigs.map(config => (+ <button+ key={config.provider}+ onClick={() => setActiveProvider(config.provider)}+ style={{+ padding: '12px 20px',+ backgroundColor: activeProvider === config.provider ? colors.primary : '#1A1A1A',+ border: `2px solid ${activeProvider === config.provider ? colors.primary : '#2A2A2A'}`,+ color: activeProvider === config.provider ? '#000' : '#FFF',+ cursor: 'pointer',+ fontSize: '13px',+ fontWeight: 700,+ letterSpacing: '0.5px',+ transition: 'all 0.2s',+ display: 'flex',+ alignItems: 'center',+ gap: '8px'+ }}+ >+ {config.provider === 'fincept' && <span style={{ color: activeProvider === config.provider ? '#000' : colors.success }}>●</span>}+ {config.provider.toUpperCase()}+ </button>+ ))}+ </div>++ {/* Custom Models from Model Library */}+ {modelConfigs.filter(m => m.is_enabled).length > 0 && (+ <div>+ <div style={{+ color: '#888',+ fontSize: '11px',+ fontWeight: 600,+ marginBottom: '10px',+ letterSpacing: '0.5px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px'+ }}>+ <Bot size={14} color="#888" />+ CUSTOM MODELS (from Model Library)+ </div>+ <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>+ {modelConfigs.filter(m => m.is_enabled).map(model => {+ const isSelected = activeProvider === `model:${model.id}`;+ return (+ <button+ key={model.id}+ onClick={() => setActiveProvider(`model:${model.id}`)}+ style={{+ padding: '10px 16px',+ backgroundColor: isSelected ? colors.secondary : '#1A1A1A',+ border: `2px solid ${isSelected ? colors.secondary : '#2A2A2A'}`,+ color: isSelected ? '#000' : '#FFF',+ cursor: 'pointer',+ fontSize: '12px',+ fontWeight: 600,+ letterSpacing: '0.5px',+ transition: 'all 0.2s',+ display: 'flex',+ alignItems: 'center',+ gap: '8px'+ }}+ >+ <span style={{+ padding: '2px 6px',+ background: colors.primary + '30',+ border: `1px solid ${colors.primary}`,+ fontSize: '9px',+ fontWeight: 700,+ color: colors.primary+ }}>+ {model.provider.toUpperCase()}+ </span>+ {model.display_name || model.model_id.split('/').pop()}+ </button>+ );+ })}+ </div>+ </div>+ )}+ </div>++ {/* Main Content Grid */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>+ {/* Left Column - Provider Config */}+ <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>+ {/* Fincept Auto-Configured */}+ {currentConfig && currentConfig.provider === 'fincept' && (+ <div style={{+ backgroundColor: '#0a2a0a',+ border: `2px solid ${colors.success}`,+ padding: '20px'+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '10px',+ marginBottom: '12px'+ }}>+ <Check size={20} color={colors.success} />+ <span style={{ color: colors.success, fontSize: '14px', fontWeight: 700 }}>+ FINCEPT LLM - AUTO CONFIGURED+ </span>+ </div>+ <div style={{ color: '#AAA', fontSize: '12px', lineHeight: 1.6 }}>+ <div style={{ marginBottom: '8px' }}>+ Your Fincept API is automatically configured and ready to use.+ </div>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '16px',+ padding: '12px',+ backgroundColor: '#000',+ border: `1px solid #2A2A2A`+ }}>+ <div>+ <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>API KEY</div>+ <div style={{ color: colors.primary, fontSize: '12px', fontFamily: 'monospace' }}>+ {sessionApiKey?.substring(0, 12)}...+ </div>+ </div>+ <div>+ <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>COST</div>+ <div style={{ color: '#FFF', fontSize: '12px' }}>5 credits/response</div>+ </div>+ <div>+ <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>MODEL</div>+ <div style={{ color: '#FFF', fontSize: '12px' }}>fincept-llm</div>+ </div>+ </div>+ </div>+ </div>+ )}++ {/* Custom Model from Model Library */}+ {getSelectedModelConfig() && (+ <div style={{+ backgroundColor: '#0a1a2a',+ border: `2px solid ${colors.secondary}`,+ padding: '20px'+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '10px',+ marginBottom: '12px'+ }}>+ <Bot size={20} color={colors.secondary} />+ <span style={{ color: colors.secondary, fontSize: '14px', fontWeight: 700 }}>+ CUSTOM MODEL - {getSelectedModelConfig()!.display_name || getSelectedModelConfig()!.model_id}+ </span>+ </div>+ <div style={{ color: '#AAA', fontSize: '12px', lineHeight: 1.6 }}>+ <div style={{ marginBottom: '8px' }}>+ This model uses the native <strong style={{ color: colors.primary }}>{getSelectedModelConfig()!.provider.toUpperCase()}</strong> API directly.+ </div>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '16px',+ padding: '12px',+ backgroundColor: '#000',+ border: `1px solid #2A2A2A`,+ flexWrap: 'wrap'+ }}>+ <div>+ <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>PROVIDER</div>+ <div style={{ color: colors.primary, fontSize: '12px', fontWeight: 600 }}>+ {getSelectedModelConfig()!.provider.toUpperCase()}+ </div>+ </div>+ <div>+ <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>MODEL</div>+ <div style={{ color: '#FFF', fontSize: '12px', fontFamily: 'monospace' }}>+ {getSelectedModelConfig()!.model_id.includes('/')+ ? getSelectedModelConfig()!.model_id.split('/').pop()+ : getSelectedModelConfig()!.model_id}+ </div>+ </div>+ <div>+ <div style={{ color: '#666', fontSize: '10px', marginBottom: '4px' }}>API KEY</div>+ <div style={{ color: getSelectedModelConfig()!.api_key ? colors.success : colors.alert, fontSize: '12px' }}>+ {getSelectedModelConfig()!.api_key ? 'Custom key set' : 'No API key'}+ </div>+ </div>+ </div>+ {!getSelectedModelConfig()!.api_key && (+ <div style={{+ marginTop: '12px',+ padding: '10px',+ background: '#3a0a0a',+ border: `1px solid ${colors.alert}`,+ color: colors.alert,+ fontSize: '11px'+ }}>+ Warning: No API key set for this model. Add your {getSelectedModelConfig()!.provider.toUpperCase()} API key in the Model Library or main provider config.+ </div>+ )}+ </div>+ </div>+ )}++ {/* Provider Configuration */}+ {currentConfig && currentConfig.provider !== 'fincept' && !getSelectedModelConfig() && (+ <div style={{+ backgroundColor: '#0F0F0F',+ border: `1px solid #2A2A2A`,+ padding: '20px'+ }}>+ <div style={{+ color: colors.primary,+ fontSize: '13px',+ fontWeight: 700,+ marginBottom: '20px',+ letterSpacing: '0.5px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ paddingBottom: '12px',+ borderBottom: `1px solid #2A2A2A`+ }}>+ <Key size={16} color={colors.primary} />+ {currentConfig.provider.toUpperCase()} CONFIGURATION+ </div>++ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>+ {/* API Key */}+ {currentConfig.provider !== 'ollama' && (+ <div>+ <label style={{+ color: '#FFF',+ fontSize: '11px',+ display: 'block',+ marginBottom: '8px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ API KEY <span style={{ color: colors.alert }}>*</span>+ </label>+ <input+ type="password"+ value={currentConfig.api_key || ''}+ onChange={(e) => updateLLMConfig(activeProvider, 'api_key', e.target.value)}+ placeholder={`Enter your ${activeProvider} API key`}+ style={{+ width: '100%',+ background: '#000',+ border: `1px solid #2A2A2A`,+ color: '#FFF',+ padding: '12px 14px',+ fontSize: '13px',+ fontFamily: '"IBM Plex Mono", monospace',+ outline: 'none'+ }}+ />+ </div>+ )}++ {/* Base URL */}+ {(currentConfig.provider === 'ollama' || currentConfig.provider === 'deepseek' || currentConfig.provider === 'openrouter') && (+ <div>+ <label style={{+ color: '#FFF',+ fontSize: '11px',+ display: 'block',+ marginBottom: '8px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ BASE URL+ </label>+ <input+ type="text"+ value={currentConfig.base_url || ''}+ onChange={(e) => updateLLMConfig(activeProvider, 'base_url', e.target.value)}+ placeholder={currentConfig.provider === 'ollama' ? 'http://localhost:11434' : 'https://api.example.com'}+ style={{+ width: '100%',+ background: '#000',+ border: `1px solid #2A2A2A`,+ color: '#FFF',+ padding: '12px 14px',+ fontSize: '13px',+ fontFamily: '"IBM Plex Mono", monospace',+ outline: 'none'+ }}+ />+ </div>+ )}++ {/* Model Selection */}+ <div>+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ marginBottom: '8px'+ }}>+ <label style={{+ color: '#FFF',+ fontSize: '11px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ MODEL+ </label>+ <div style={{ display: 'flex', gap: '8px' }}>+ {currentConfig.provider === 'ollama' ? (+ <button+ onClick={fetchOllamaModels}+ disabled={ollamaLoading}+ style={{+ background: '#1A1A1A',+ border: `1px solid #2A2A2A`,+ color: colors.primary,+ padding: '6px 12px',+ fontSize: '11px',+ cursor: ollamaLoading ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ fontWeight: 600+ }}+ >+ <RefreshCw size={12} className={ollamaLoading ? 'animate-spin' : ''} />+ {ollamaLoading ? 'LOADING...' : 'REFRESH MODELS'}+ </button>+ ) : currentConfig.provider !== 'fincept' && (+ <button+ onClick={() => fetchProviderModels(true)}+ disabled={providerModelsLoading}+ style={{+ background: '#1A1A1A',+ border: `1px solid #2A2A2A`,+ color: colors.primary,+ padding: '6px 12px',+ fontSize: '11px',+ cursor: providerModelsLoading ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ fontWeight: 600+ }}+ >+ <RefreshCw size={12} className={providerModelsLoading ? 'animate-spin' : ''} />+ {providerModelsLoading ? 'LOADING...' : 'REFRESH MODELS'}+ </button>+ )}+ <button+ onClick={() => setUseManualEntry(!useManualEntry)}+ style={{+ background: useManualEntry ? colors.primary : '#1A1A1A',+ border: `1px solid ${useManualEntry ? colors.primary : '#2A2A2A'}`,+ color: useManualEntry ? '#000' : '#FFF',+ padding: '6px 12px',+ fontSize: '11px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ fontWeight: 600+ }}+ >+ <Edit3 size={12} />+ {useManualEntry ? 'USE DROPDOWN' : 'MANUAL ENTRY'}+ </button>+ </div>+ </div>++ {!useManualEntry ? (+ <div>+ <select+ value={currentConfig.model}+ onChange={(e) => updateLLMConfig(activeProvider, 'model', e.target.value)}+ disabled={+ (currentConfig.provider === 'ollama' && (ollamaLoading || ollamaModels.length === 0)) ||+ (currentConfig.provider !== 'ollama' && currentConfig.provider !== 'fincept' && (providerModelsLoading || providerModels.length === 0))+ }+ style={{+ width: '100%',+ background: '#000',+ border: `1px solid #2A2A2A`,+ color: '#FFF',+ padding: '12px 14px',+ fontSize: '13px',+ cursor: 'pointer'+ }}+ >+ {currentConfig.provider === 'ollama' ? (+ <>+ {ollamaModels.length === 0 && !ollamaLoading && <option value="">No models found - Click REFRESH</option>}+ {ollamaLoading && <option value="">Loading models...</option>}+ {ollamaModels.map((model) => (+ <option key={model} value={model}>{model}</option>+ ))}+ </>+ ) : (+ <>+ {providerModels.length === 0 && !providerModelsLoading && <option value="">No models found - Click REFRESH</option>}+ {providerModelsLoading && <option value="">Loading models...</option>}+ {providerModels.map((model) => (+ <option key={model.id} value={model.id}>+ {model.name} {model.context_window ? `(${(model.context_window / 1000).toFixed(0)}K)` : ''}+ </option>+ ))}+ </>+ )}+ </select>+ {currentConfig.provider === 'ollama' && ollamaError && (+ <div style={{+ marginTop: '8px',+ padding: '10px 12px',+ background: '#3a0a0a',+ border: `1px solid ${colors.alert}`,+ fontSize: '12px',+ color: colors.alert+ }}>+ {ollamaError}+ </div>+ )}+ {currentConfig.provider !== 'ollama' && providerModelsError && (+ <div style={{+ marginTop: '8px',+ padding: '10px 12px',+ background: '#3a0a0a',+ border: `1px solid ${colors.alert}`,+ fontSize: '12px',+ color: colors.alert+ }}>+ {providerModelsError}+ </div>+ )}+ {currentConfig.provider === 'ollama' && ollamaModels.length > 0 && (+ <div style={{+ marginTop: '8px',+ fontSize: '12px',+ color: colors.success,+ display: 'flex',+ alignItems: 'center',+ gap: '6px'+ }}>+ <Check size={14} />+ {ollamaModels.length} model{ollamaModels.length !== 1 ? 's' : ''} available+ </div>+ )}+ {currentConfig.provider !== 'ollama' && currentConfig.provider !== 'fincept' && providerModels.length > 0 && (+ <div style={{+ marginTop: '8px',+ fontSize: '11px',+ color: '#AAA',+ display: 'flex',+ flexDirection: 'column',+ gap: '4px'+ }}>+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ color: colors.success+ }}>+ <Check size={14} />+ {providerModels.length} model{providerModels.length !== 1 ? 's' : ''} available+ </div>+ <div style={{ fontSize: '10px', color: '#666' }}>+ Models fetched from {currentConfig.provider.toUpperCase()} API+ {providerModelsLoading && ' (updating...)'}+ </div>+ </div>+ )}+ </div>+ ) : (+ <input+ type="text"+ value={currentConfig.model}+ onChange={(e) => updateLLMConfig(activeProvider, 'model', e.target.value)}+ placeholder="Enter model name (e.g., gpt-4, claude-3-sonnet)"+ style={{+ width: '100%',+ background: '#000',+ border: `1px solid #2A2A2A`,+ color: '#FFF',+ padding: '12px 14px',+ fontSize: '13px',+ outline: 'none'+ }}+ />+ )}+ </div>+ </div>+ </div>+ )}++ {/* Global Settings */}+ <div style={{+ backgroundColor: '#0F0F0F',+ border: `1px solid #2A2A2A`,+ padding: '20px'+ }}>+ <div style={{+ color: colors.primary,+ fontSize: '13px',+ fontWeight: 700,+ marginBottom: '20px',+ letterSpacing: '0.5px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ paddingBottom: '12px',+ borderBottom: `1px solid #2A2A2A`+ }}>+ <SettingsIcon size={16} color={colors.primary} />+ GLOBAL SETTINGS+ </div>++ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>+ {/* Temperature */}+ <div>+ <label style={{+ color: '#FFF',+ fontSize: '11px',+ display: 'block',+ marginBottom: '8px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ TEMPERATURE (Creativity)+ </label>+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <input+ type="range"+ min="0"+ max="2"+ step="0.1"+ value={llmGlobalSettings.temperature}+ onChange={(e) => setLlmGlobalSettings({ ...llmGlobalSettings, temperature: parseFloat(e.target.value) })}+ style={{ flex: 1, height: '6px', cursor: 'pointer' }}+ />+ <div style={{+ minWidth: '50px',+ padding: '8px 12px',+ background: colors.primary + '20',+ border: `1px solid ${colors.primary}`,+ color: colors.primary,+ fontSize: '13px',+ fontWeight: 700,+ textAlign: 'center'+ }}>+ {llmGlobalSettings.temperature.toFixed(1)}+ </div>+ </div>+ <div style={{ color: '#666', fontSize: '10px', marginTop: '6px' }}>+ Lower = More focused, Higher = More creative+ </div>+ </div>++ {/* Max Tokens */}+ <div>+ <label style={{+ color: '#FFF',+ fontSize: '11px',+ display: 'block',+ marginBottom: '8px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ MAX TOKENS (Response Length)+ </label>+ <input+ type="number"+ min="1"+ max="32000"+ value={llmGlobalSettings.max_tokens}+ onChange={(e) => setLlmGlobalSettings({ ...llmGlobalSettings, max_tokens: parseInt(e.target.value) || 2048 })}+ style={{+ width: '100%',+ background: '#000',+ border: `1px solid #2A2A2A`,+ color: '#FFF',+ padding: '12px 14px',+ fontSize: '13px',+ outline: 'none'+ }}+ />+ </div>++ {/* System Prompt */}+ <div>+ <label style={{+ color: '#FFF',+ fontSize: '11px',+ display: 'block',+ marginBottom: '8px',+ fontWeight: 600,+ letterSpacing: '0.5px'+ }}>+ SYSTEM PROMPT (Optional)+ </label>+ <textarea+ value={llmGlobalSettings.system_prompt}+ onChange={(e) => setLlmGlobalSettings({ ...llmGlobalSettings, system_prompt: e.target.value })}+ rows={4}+ placeholder="Custom instructions for the AI assistant..."+ style={{+ width: '100%',+ background: '#000',+ border: `1px solid #2A2A2A`,+ color: '#FFF',+ padding: '12px 14px',+ fontSize: '12px',+ resize: 'vertical',+ fontFamily: '"IBM Plex Mono", monospace',+ lineHeight: '1.5',+ outline: 'none'+ }}+ />+ </div>+ </div>+ </div>+ </div>++ {/* Right Column - Model Library */}+ <div style={{+ backgroundColor: '#0F0F0F',+ border: `1px solid #2A2A2A`,+ padding: '20px',+ display: 'flex',+ flexDirection: 'column'+ }}>+ {/* Header */}+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ marginBottom: '20px',+ paddingBottom: '12px',+ borderBottom: `1px solid #2A2A2A`+ }}>+ <div>+ <div style={{+ color: colors.primary,+ fontSize: '13px',+ fontWeight: 700,+ letterSpacing: '0.5px',+ marginBottom: '4px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px'+ }}>+ <Bot size={16} color={colors.primary} />+ MODEL LIBRARY+ </div>+ <div style={{ color: '#888', fontSize: '11px' }}>+ Add custom models for different use cases+ </div>+ </div>+ <button+ onClick={() => setShowAddModel(!showAddModel)}+ style={{+ background: showAddModel ? '#3a0a0a' : colors.primary,+ color: showAddModel ? colors.alert : '#000',+ border: 'none',+ padding: '8px 16px',+ fontSize: '12px',+ fontWeight: 700,+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px'+ }}+ >+ {showAddModel ? <><X size={14} /> CANCEL</> : <><Plus size={14} /> ADD MODEL</>}+ </button>+ </div>++ {/* Add Model Form */}+ {showAddModel && (+ <div style={{+ background: '#000',+ border: `1px solid ${colors.primary}`,+ padding: '16px',+ marginBottom: '16px'+ }}>+ <div style={{+ color: colors.primary,+ fontSize: '12px',+ fontWeight: 700,+ marginBottom: '16px',+ display: 'flex',+ alignItems: 'center',+ gap: '8px'+ }}>+ <Plus size={14} />+ ADD NEW MODEL CONFIGURATION+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '12px' }}>+ <div>+ <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>+ PROVIDER+ </label>+ <select+ value={newModelConfig.provider}+ onChange={(e) => setNewModelConfig({ ...newModelConfig, provider: e.target.value })}+ style={{+ width: '100%',+ background: '#1A1A1A',+ border: `1px solid #2A2A2A`,+ color: '#FFF',+ padding: '10px 12px',+ fontSize: '12px',+ cursor: 'pointer'+ }}+ >+ <option value="openai">OpenAI</option>+ <option value="anthropic">Anthropic</option>+ <option value="google">Google</option>+ <option value="meta-llama">Meta (Llama)</option>+ <option value="mistralai">Mistral AI</option>+ <option value="x-ai">xAI (Grok)</option>+ <option value="cohere">Cohere</option>+ <option value="deepseek">DeepSeek</option>+ <option value="qwen">Qwen (Alibaba)</option>+ <option value="nvidia">NVIDIA</option>+ <option value="microsoft">Microsoft</option>+ <option value="perplexity">Perplexity</option>+ <option value="groq">Groq</option>+ <option value="ai21">AI21 Labs</option>+ <option value="nousresearch">Nous Research</option>+ <option value="cognitivecomputations">Cognitive Computations</option>+ </select>+ </div>+ <div>+ <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>+ MODEL ID <span style={{ color: colors.alert }}>*</span>+ </label>+ <div style={{ display: 'flex', gap: '8px', alignItems: 'stretch' }}>+ <div style={{ flex: 1 }}>+ {useManualEntry ? (+ <input+ type="text"+ value={newModelConfig.model_id}+ onChange={(e) => setNewModelConfig({ ...newModelConfig, model_id: e.target.value })}+ placeholder="e.g. gpt-4o or openai/gpt-4o"+ style={{+ width: '100%',+ background: '#1A1A1A',+ border: `1px solid #2A2A2A`,+ color: '#FFF',+ padding: '10px 12px',+ fontSize: '12px'+ }}+ />+ ) : (+ <select+ value={newModelConfig.model_id}+ onChange={(e) => setNewModelConfig({ ...newModelConfig, model_id: e.target.value })}+ style={{+ width: '100%',+ background: '#1A1A1A',+ border: `1px solid #2A2A2A`,+ color: '#FFF',+ padding: '10px 12px',+ fontSize: '12px',+ cursor: 'pointer'+ }}+ >+ <option value="">Select a model...</option>+ {newModelConfigModels.map((model) => (+ <option key={model.id} value={model.id}>+ {model.name} {model.context_window ? `(${(model.context_window / 1000).toFixed(0)}K)` : ''}+ </option>+ ))}+ </select>+ )}+ </div>+ <button+ onClick={() => setUseManualEntry(!useManualEntry)}+ style={{+ background: useManualEntry ? colors.primary : '#1A1A1A',+ border: `1px solid ${useManualEntry ? colors.primary : '#2A2A2A'}`,+ color: useManualEntry ? '#000' : colors.primary,+ padding: '10px 12px',+ fontSize: '9px',+ cursor: 'pointer',+ fontWeight: 600,+ whiteSpace: 'nowrap'+ }}+ >+ {useManualEntry ? 'DROPDOWN' : 'MANUAL'}+ </button>+ </div>+ </div>+ </div>++ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '16px' }}>+ <div>+ <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>+ DISPLAY NAME+ </label>+ <input+ type="text"+ value={newModelConfig.display_name}+ onChange={(e) => setNewModelConfig({ ...newModelConfig, display_name: e.target.value })}+ placeholder="e.g. GPT-4o Mini"+ style={{+ width: '100%',+ background: '#1A1A1A',+ border: `1px solid #2A2A2A`,+ color: '#FFF',+ padding: '10px 12px',+ fontSize: '12px'+ }}+ />+ </div>+ <div>+ <label style={{ color: '#FFF', fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600 }}>+ API KEY (Optional)+ </label>+ <input+ type="password"+ value={newModelConfig.api_key}+ onChange={(e) => setNewModelConfig({ ...newModelConfig, api_key: e.target.value })}+ placeholder="Uses provider key if empty"+ style={{+ width: '100%',+ background: '#1A1A1A',+ border: `1px solid #2A2A2A`,+ color: '#FFF',+ padding: '10px 12px',+ fontSize: '12px',+ fontFamily: 'monospace'+ }}+ />+ </div>+ </div>++ <button+ onClick={handleAddModelConfig}+ disabled={loading || !newModelConfig.model_id}+ style={{+ background: loading || !newModelConfig.model_id ? '#2A2A2A' : colors.success,+ color: loading || !newModelConfig.model_id ? '#666' : '#000',+ border: 'none',+ padding: '10px 20px',+ fontSize: '12px',+ fontWeight: 700,+ cursor: loading || !newModelConfig.model_id ? 'not-allowed' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '8px'+ }}+ >+ <Plus size={14} />+ ADD MODEL+ </button>+ </div>+ )}++ {/* Models List */}+ <div style={{ flex: 1, overflowY: 'auto' }}>+ {modelConfigs.length === 0 ? (+ <div style={{+ padding: '40px 20px',+ textAlign: 'center',+ color: '#666',+ border: `1px dashed #2A2A2A`,+ background: '#000'+ }}>+ <Bot size={40} color="#2A2A2A" style={{ marginBottom: '16px' }} />+ <div style={{ fontSize: '13px', marginBottom: '8px', fontWeight: 600, color: '#888' }}>+ No Custom Models Configured+ </div>+ <div style={{ fontSize: '11px', color: '#666' }}>+ Click "ADD MODEL" to add custom model configurations+ </div>+ </div>+ ) : (+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>+ {modelConfigs.map((model) => (+ <div+ key={model.id}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ padding: '12px 14px',+ background: model.is_enabled ? '#1A1A1A' : '#0A0A0A',+ border: `1px solid ${model.is_enabled ? '#2A2A2A' : '#1A1A1A'}`,+ opacity: model.is_enabled ? 1 : 0.6+ }}+ >+ <button+ onClick={() => handleToggleModelEnabled(model.id)}+ style={{+ background: 'transparent',+ border: 'none',+ cursor: 'pointer',+ padding: 0+ }}+ >+ {model.is_enabled ? (+ <ToggleRight size={24} color={colors.success} />+ ) : (+ <ToggleLeft size={24} color="#666" />+ )}+ </button>+ <div style={{ flex: 1 }}>+ <div style={{+ fontSize: '13px',+ fontWeight: 600,+ color: model.is_enabled ? '#FFF' : '#666',+ marginBottom: '4px'+ }}>+ {model.display_name || model.model_id}+ </div>+ <div style={{+ fontSize: '11px',+ color: '#888',+ display: 'flex',+ alignItems: 'center',+ gap: '8px'+ }}>+ <span style={{+ padding: '2px 8px',+ background: colors.primary + '20',+ border: `1px solid ${colors.primary}`,+ color: colors.primary,+ fontWeight: 600,+ fontSize: '10px'+ }}>+ {model.provider.toUpperCase()}+ </span>+ <span style={{ fontFamily: 'monospace' }}>{model.model_id}</span>+ {model.api_key && (+ <span style={{+ padding: '2px 8px',+ background: colors.success + '20',+ border: `1px solid ${colors.success}`,+ color: colors.success,+ fontWeight: 600,+ fontSize: '10px'+ }}>+ HAS KEY+ </span>+ )}+ </div>+ </div>+ <div style={{ display: 'flex', gap: '8px' }}>+ {model.api_key && (+ <button+ onClick={() => setShowApiKeys(prev => ({ ...prev, [model.id]: !prev[model.id] }))}+ style={{+ background: '#1A1A1A',+ border: `1px solid #2A2A2A`,+ color: '#888',+ padding: '6px 8px',+ cursor: 'pointer'+ }}+ >+ {showApiKeys[model.id] ? <EyeOff size={14} /> : <Eye size={14} />}+ </button>+ )}+ <button+ onClick={() => handleDeleteModelConfig(model.id)}+ style={{+ background: '#1A1A1A',+ border: `1px solid #2A2A2A`,+ color: colors.alert,+ padding: '6px 12px',+ fontSize: '11px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ fontWeight: 600+ }}+ >+ <Trash2 size={12} />+ DELETE+ </button>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>++ {/* Summary */}+ {modelConfigs.length > 0 && (+ <div style={{+ marginTop: '16px',+ padding: '12px 14px',+ background: '#0a2a0a',+ border: `1px solid ${colors.success}`,+ display: 'flex',+ alignItems: 'center',+ gap: '10px'+ }}>+ <Check size={16} color={colors.success} />+ <div style={{ fontSize: '12px', color: colors.success, fontWeight: 600 }}>+ {modelConfigs.filter(m => m.is_enabled).length} ENABLED · {modelConfigs.length} TOTAL MODELS+ </div>+ </div>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/StorageCacheSection.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/StorageCacheSection.tsxnew file mode 100644index 000000000..46cad1aa7--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/StorageCacheSection.tsx@@ -0,0 +1,223 @@+import React, { useState } from 'react';+import { RefreshCw, Trash2 } from 'lucide-react';+import { cacheService, type CacheStats } from '@/services/cache/cacheService';+import { LLMModelsService } from '@/services/llmModelsService';+import type { SettingsColors } from '../types';++interface StorageCacheSectionProps {+ colors: SettingsColors;+ showMessage: (type: 'success' | 'error', text: string) => void;+}++export function StorageCacheSection({+ colors,+ showMessage,+}: StorageCacheSectionProps) {+ const [cacheStats, setCacheStats] = useState<CacheStats | null>(null);+ const [clearingCache, setClearingCache] = useState(false);++ const refreshStats = async () => {+ const stats = await cacheService.getStats();+ setCacheStats(stats);+ };++ const handleCleanup = async () => {+ setClearingCache(true);+ try {+ const removed = await cacheService.cleanup();+ showMessage('success', `Cleaned up ${removed} expired cache entries`);+ await refreshStats();+ } catch (error) {+ showMessage('error', 'Failed to cleanup cache');+ } finally {+ setClearingCache(false);+ }+ };++ const handleClearAll = async () => {+ if (!confirm('Are you sure you want to clear all cached data? This action cannot be undone.')) {+ return;+ }+ setClearingCache(true);+ try {+ const removed = await cacheService.clearAll();+ await LLMModelsService.clearCache();+ showMessage('success', `Cleared ${removed} cache entries successfully`);+ setCacheStats(null);+ await refreshStats();+ } catch (error) {+ showMessage('error', 'Failed to clear cache');+ } finally {+ setClearingCache(false);+ }+ };++ return (+ <div style={{ padding: '20px' }}>+ <div style={{ marginBottom: '24px' }}>+ <h3 style={{ fontSize: '16px', fontWeight: 600, color: colors.text, marginBottom: '8px' }}>+ Storage & Cache Management+ </h3>+ <p style={{ color: colors.textMuted, fontSize: '13px' }}>+ Manage application cache and storage. Clearing cache can help resolve issues and free up disk space.+ </p>+ </div>++ {/* Cache Statistics */}+ <div style={{+ background: '#1a1a1a',+ borderRadius: '8px',+ padding: '16px',+ marginBottom: '20px',+ border: '1px solid #2a2a2a'+ }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>+ <h4 style={{ fontSize: '14px', fontWeight: 500, color: colors.text }}>Cache Statistics</h4>+ <button+ onClick={refreshStats}+ style={{+ padding: '6px 12px',+ background: '#2a2a2a',+ border: '1px solid #3a3a3a',+ borderRadius: '4px',+ color: colors.text,+ fontSize: '12px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '6px'+ }}+ >+ <RefreshCw size={12} />+ Refresh+ </button>+ </div>++ {cacheStats ? (+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '16px' }}>+ <div style={{ background: '#252525', padding: '12px', borderRadius: '6px' }}>+ <div style={{ color: colors.textMuted, fontSize: '11px', marginBottom: '4px' }}>Total Entries</div>+ <div style={{ color: colors.text, fontSize: '18px', fontWeight: 600 }}>{cacheStats.total_entries.toLocaleString()}</div>+ </div>+ <div style={{ background: '#252525', padding: '12px', borderRadius: '6px' }}>+ <div style={{ color: colors.textMuted, fontSize: '11px', marginBottom: '4px' }}>Cache Size</div>+ <div style={{ color: colors.text, fontSize: '18px', fontWeight: 600 }}>+ {(cacheStats.total_size_bytes / 1024 / 1024).toFixed(2)} MB+ </div>+ </div>+ <div style={{ background: '#252525', padding: '12px', borderRadius: '6px' }}>+ <div style={{ color: colors.textMuted, fontSize: '11px', marginBottom: '4px' }}>Expired Entries</div>+ <div style={{ color: cacheStats.expired_entries > 0 ? '#f59e0b' : colors.text, fontSize: '18px', fontWeight: 600 }}>+ {cacheStats.expired_entries.toLocaleString()}+ </div>+ </div>+ </div>+ ) : (+ <div style={{ color: colors.textMuted, fontSize: '13px', textAlign: 'center', padding: '20px' }}>+ Click "Refresh" to load cache statistics+ </div>+ )}++ {cacheStats && cacheStats.categories && cacheStats.categories.length > 0 && (+ <div style={{ marginTop: '16px' }}>+ <div style={{ color: colors.textMuted, fontSize: '12px', marginBottom: '8px' }}>Categories</div>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>+ {cacheStats.categories.map(cat => (+ <div+ key={cat.category}+ style={{+ background: '#252525',+ padding: '6px 10px',+ borderRadius: '4px',+ fontSize: '11px',+ color: colors.text+ }}+ >+ <span style={{ color: colors.primary }}>{cat.category}</span>+ <span style={{ color: colors.textMuted, marginLeft: '8px' }}>+ {cat.entry_count} entries · {(cat.total_size / 1024).toFixed(1)} KB+ </span>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>++ {/* Cache Actions */}+ <div style={{+ background: '#1a1a1a',+ borderRadius: '8px',+ padding: '16px',+ border: '1px solid #2a2a2a'+ }}>+ <h4 style={{ fontSize: '14px', fontWeight: 500, color: colors.text, marginBottom: '16px' }}>Cache Actions</h4>++ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>+ {/* Clear Expired */}+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px', background: '#252525', borderRadius: '6px' }}>+ <div>+ <div style={{ color: colors.text, fontSize: '13px', fontWeight: 500 }}>Clear Expired Entries</div>+ <div style={{ color: colors.textMuted, fontSize: '11px' }}>Remove all expired cache entries to free up space</div>+ </div>+ <button+ onClick={handleCleanup}+ disabled={clearingCache}+ style={{+ padding: '8px 16px',+ background: '#3a3a3a',+ border: 'none',+ borderRadius: '4px',+ color: colors.text,+ fontSize: '12px',+ cursor: clearingCache ? 'not-allowed' : 'pointer',+ opacity: clearingCache ? 0.6 : 1+ }}+ >+ {clearingCache ? 'Cleaning...' : 'Clean Up'}+ </button>+ </div>++ {/* Clear All Cache */}+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px', background: '#252525', borderRadius: '6px', border: '1px solid #dc262640' }}>+ <div>+ <div style={{ color: colors.text, fontSize: '13px', fontWeight: 500 }}>Clear All Cache</div>+ <div style={{ color: colors.textMuted, fontSize: '11px' }}>Remove all cached data. This will not affect your settings or saved data.</div>+ </div>+ <button+ onClick={handleClearAll}+ disabled={clearingCache}+ style={{+ padding: '8px 16px',+ background: '#dc2626',+ border: 'none',+ borderRadius: '4px',+ color: 'white',+ fontSize: '12px',+ fontWeight: 500,+ cursor: clearingCache ? 'not-allowed' : 'pointer',+ opacity: clearingCache ? 0.6 : 1,+ display: 'flex',+ alignItems: 'center',+ gap: '6px'+ }}+ >+ <Trash2 size={14} />+ {clearingCache ? 'Clearing...' : 'Clear All'}+ </button>+ </div>+ </div>+ </div>++ {/* Info */}+ <div style={{ marginTop: '20px', padding: '12px', background: '#1a1a2e', borderRadius: '6px', border: '1px solid #2a2a4e' }}>+ <div style={{ color: '#8b8bff', fontSize: '12px', fontWeight: 500, marginBottom: '6px' }}>About Cache</div>+ <div style={{ color: colors.textMuted, fontSize: '11px', lineHeight: '1.5' }}>+ The cache stores temporary data like market quotes, news articles, and API responses to improve performance.+ Clearing the cache will not delete your settings, credentials, portfolios, or other saved data.+ The application will automatically rebuild the cache as you use it.+ </div>+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/TerminalAppearanceSection.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/TerminalAppearanceSection.tsxnew file mode 100644index 000000000..d87732578--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/TerminalAppearanceSection.tsx@@ -0,0 +1,624 @@+import React, { useState } from 'react';+import { Save, RefreshCw, Terminal, Type, Palette, Clock, Check } from 'lucide-react';+import { terminalThemeService, FONT_FAMILIES, COLOR_THEMES, FontSettings } from '@/services/core/terminalThemeService';+import { saveSetting } from '@/services/core/sqliteService';+import { useTranslation } from 'react-i18next';+import type { SettingsColors } from '../types';+import { DEFAULT_KEY_MAPPINGS } from '../hooks';++interface TerminalAppearanceSectionProps {+ colors: SettingsColors;+ theme: any;+ updateTheme: (theme: any) => void;+ resetTheme: () => void;+ showMessage: (type: 'success' | 'error', text: string) => void;+ keyMappings: Record<string, string>;+ setKeyMappings: (mappings: Record<string, string>) => void;+ defaultTimezone: { id: string; label: string; shortLabel: string };+ setDefaultTimezone: (id: string) => void;+ timezoneOptions: Array<{ id: string; label: string; shortLabel: string }>;+}++export function TerminalAppearanceSection({+ colors,+ theme,+ updateTheme,+ resetTheme,+ showMessage,+ keyMappings,+ setKeyMappings,+ defaultTimezone,+ setDefaultTimezone,+ timezoneOptions,+}: TerminalAppearanceSectionProps) {+ const { t } = useTranslation('settings');+ const [fontFamily, setFontFamily] = useState(theme.font.family);+ const [baseSize, setBaseSize] = useState(theme.font.baseSize);+ const [fontWeight, setFontWeight] = useState(theme.font.weight);+ const [fontItalic, setFontItalic] = useState(theme.font.italic);+ const [selectedTheme, setSelectedTheme] = useState(terminalThemeService.getCurrentThemeKey());++ const handleSaveTerminalAppearance = async () => {+ const newTheme = {+ font: {+ family: fontFamily,+ baseSize: baseSize,+ weight: fontWeight,+ italic: fontItalic+ },+ colors: COLOR_THEMES[selectedTheme]+ };+ updateTheme(newTheme);+ await saveSetting('fincept_key_mappings', JSON.stringify(keyMappings), 'settings');+ showMessage('success', 'Terminal appearance and key mappings saved successfully');+ };++ const handleResetTerminalAppearance = async () => {+ resetTheme();+ const defaultTheme = terminalThemeService.getTheme();+ setFontFamily(defaultTheme.font.family);+ setBaseSize(defaultTheme.font.baseSize);+ setFontWeight(defaultTheme.font.weight);+ setFontItalic(defaultTheme.font.italic);+ setSelectedTheme('fincept-classic');+ setKeyMappings(DEFAULT_KEY_MAPPINGS);+ await saveSetting('fincept_key_mappings', '', 'settings');+ showMessage('success', 'Reset to default appearance and key mappings');+ };++ return (+ <div style={{ fontFamily: '"IBM Plex Mono", "Consolas", monospace' }}>+ {/* Header */}+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ marginBottom: '24px',+ paddingBottom: '12px',+ borderBottom: `2px solid ${colors.primary}`+ }}>+ <Terminal size={20} color={colors.primary} style={{ filter: `drop-shadow(0 0 4px ${colors.primary})` }} />+ <h2 style={{+ color: colors.primary,+ fontSize: '16px',+ fontWeight: 700,+ letterSpacing: '1px',+ margin: 0,+ textShadow: `0 0 10px ${colors.primary}40`+ }}>+ {t('terminal.title')}+ </h2>+ </div>++ {/* Description */}+ <div style={{+ marginBottom: '20px',+ padding: '12px',+ backgroundColor: '#1A1A1A',+ border: '1px solid #2A2A2A',+ borderLeft: `3px solid ${colors.secondary}`+ }}>+ <p style={{+ color: colors.textMuted,+ fontSize: '10px',+ margin: 0,+ lineHeight: '1.6'+ }}>+ {t('terminal.description')}+ </p>+ </div>++ {/* Font Settings */}+ <div style={{+ background: '#0F0F0F',+ border: '1px solid #2A2A2A',+ borderLeft: `3px solid ${colors.primary}`,+ borderRadius: '4px',+ padding: '16px',+ marginBottom: '20px'+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>+ <Type size={18} color={colors.primary} style={{ filter: `drop-shadow(0 0 2px ${colors.primary})` }} />+ <span style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', letterSpacing: '0.5px' }}>{t('terminal.currentSettings')}</span>+ </div>++ {/* Font Family */}+ <div style={{ marginBottom: '16px' }}>+ <label style={{ color: colors.text, fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600, letterSpacing: '0.5px' }}>{t('terminal.fontFamily')}</label>+ <select value={fontFamily} onChange={(e) => setFontFamily(e.target.value)} style={{+ width: '100%',+ padding: '10px',+ background: colors.background,+ border: `1px solid #2A2A2A`,+ color: colors.text,+ borderRadius: '3px',+ fontSize: '11px',+ fontWeight: 500,+ cursor: 'pointer',+ appearance: 'none',+ backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23FFA500' d='M6 9L1 4h10z'/%3E%3C/svg%3E")`,+ backgroundRepeat: 'no-repeat',+ backgroundPosition: 'right 10px center',+ paddingRight: '32px'+ }}>+ {FONT_FAMILIES.map(f => <option key={f.value} value={f.value}>{f.label}</option>)}+ </select>+ </div>++ {/* Base Font Size */}+ <div style={{ marginBottom: '16px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>+ <label style={{ color: colors.text, fontSize: '10px', fontWeight: 600, letterSpacing: '0.5px' }}>BASE FONT SIZE</label>+ <span style={{+ color: colors.primary,+ fontSize: '12px',+ fontWeight: 'bold',+ padding: '2px 8px',+ background: `${colors.primary}20`,+ borderRadius: '3px',+ border: `1px solid ${colors.primary}40`+ }}>{baseSize}px</span>+ </div>+ <input type="range" min="9" max="18" value={baseSize} onChange={(e) => setBaseSize(Number(e.target.value))} style={{+ width: '100%',+ height: '6px',+ background: `linear-gradient(to right, ${colors.primary}40 0%, ${colors.primary}40 ${((baseSize - 9) / 9) * 100}%, #2A2A2A ${((baseSize - 9) / 9) * 100}%, #2A2A2A 100%)`,+ borderRadius: '3px',+ outline: 'none',+ cursor: 'pointer'+ }} />+ <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '6px' }}>+ <span style={{ color: colors.textMuted, fontSize: '9px', fontWeight: 500 }}>Small (9px)</span>+ <span style={{ color: colors.textMuted, fontSize: '9px', fontWeight: 500 }}>Large (18px)</span>+ </div>+ </div>++ {/* Font Weight */}+ <div style={{ marginBottom: '16px' }}>+ <label style={{ color: colors.text, fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600, letterSpacing: '0.5px' }}>FONT WEIGHT</label>+ <select value={fontWeight} onChange={(e) => setFontWeight(e.target.value as FontSettings['weight'])} style={{+ width: '100%',+ padding: '10px',+ background: colors.background,+ border: '1px solid #2A2A2A',+ color: colors.text,+ borderRadius: '3px',+ fontSize: '11px',+ fontWeight: 500,+ cursor: 'pointer',+ appearance: 'none',+ backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23FFA500' d='M6 9L1 4h10z'/%3E%3C/svg%3E")`,+ backgroundRepeat: 'no-repeat',+ backgroundPosition: 'right 10px center',+ paddingRight: '32px'+ }}>+ <option value="normal">Normal (400)</option>+ <option value="semibold">Semi-Bold (600)</option>+ <option value="bold">Bold (700)</option>+ </select>+ </div>++ {/* Font Style */}+ <div>+ <label style={{+ display: 'flex',+ alignItems: 'center',+ gap: '10px',+ cursor: 'pointer',+ padding: '10px',+ background: fontItalic ? `${colors.primary}10` : 'transparent',+ border: `1px solid ${fontItalic ? colors.primary : '#2A2A2A'}`,+ borderRadius: '3px',+ transition: 'all 0.2s'+ }}>+ <input type="checkbox" checked={fontItalic} onChange={(e) => setFontItalic(e.target.checked)} style={{ width: '16px', height: '16px', cursor: 'pointer' }} />+ <span style={{ color: colors.text, fontSize: '10px', fontWeight: 600, letterSpacing: '0.5px' }}>ENABLE ITALIC STYLE</span>+ </label>+ </div>+ </div>++ {/* Color Theme */}+ <div style={{+ background: '#0F0F0F',+ border: '1px solid #2A2A2A',+ borderLeft: `3px solid ${colors.primary}`,+ borderRadius: '4px',+ padding: '16px',+ marginBottom: '20px'+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>+ <Palette size={18} color={colors.primary} style={{ filter: `drop-shadow(0 0 2px ${colors.primary})` }} />+ <span style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', letterSpacing: '0.5px' }}>COLOR THEME</span>+ </div>++ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '12px' }}>+ {Object.entries(COLOR_THEMES).map(([key, themeObj]) => {+ const isActive = selectedTheme === key;+ return (+ <button+ key={key}+ onClick={() => setSelectedTheme(key)}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ padding: '12px',+ background: isActive ? '#1A1A1A' : 'transparent',+ border: `1px solid ${isActive ? colors.primary : '#2A2A2A'}`,+ borderLeft: `3px solid ${isActive ? colors.primary : '#2A2A2A'}`,+ borderRadius: '3px',+ cursor: 'pointer',+ transition: 'all 0.2s',+ position: 'relative',+ overflow: 'hidden'+ }}+ >+ {/* Color Swatches */}+ <div style={{ display: 'flex', gap: '6px' }}>+ <div style={{+ width: '24px',+ height: '24px',+ background: themeObj.primary,+ border: '1px solid #2A2A2A',+ borderRadius: '3px',+ boxShadow: isActive ? `0 0 8px ${themeObj.primary}60` : 'none'+ }} title="Primary" />+ <div style={{+ width: '24px',+ height: '24px',+ background: themeObj.secondary,+ border: '1px solid #2A2A2A',+ borderRadius: '3px',+ boxShadow: isActive ? `0 0 8px ${themeObj.secondary}60` : 'none'+ }} title="Secondary" />+ <div style={{+ width: '24px',+ height: '24px',+ background: themeObj.alert,+ border: '1px solid #2A2A2A',+ borderRadius: '3px',+ boxShadow: isActive ? `0 0 8px ${themeObj.alert}60` : 'none'+ }} title="Alert" />+ </div>++ <span style={{+ color: isActive ? colors.primary : colors.text,+ fontSize: '11px',+ flex: 1,+ fontWeight: isActive ? 700 : 500,+ letterSpacing: '0.5px',+ textAlign: 'left'+ }}>{themeObj.name}</span>++ {isActive && (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}>+ <Check size={14} color={colors.success} />+ <div style={{+ width: '6px',+ height: '6px',+ borderRadius: '50%',+ background: colors.success,+ boxShadow: `0 0 6px ${colors.success}`+ }} />+ </div>+ )}++ {isActive && (+ <div style={{+ position: 'absolute',+ top: 0,+ left: 0,+ right: 0,+ height: '1px',+ background: `linear-gradient(90deg, transparent, ${colors.primary}, transparent)`,+ opacity: 0.5+ }} />+ )}+ </button>+ );+ })}+ </div>+ </div>++ {/* Default Timezone Selection */}+ <div style={{+ background: '#0F0F0F',+ border: '1px solid #2A2A2A',+ borderLeft: `3px solid ${colors.primary}`,+ borderRadius: '4px',+ padding: '16px',+ marginBottom: '20px'+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>+ <Clock size={18} color={colors.primary} style={{ filter: `drop-shadow(0 0 2px ${colors.primary})` }} />+ <span style={{ color: colors.text, fontWeight: 'bold', fontSize: '12px' }}>+ DEFAULT TIMEZONE+ </span>+ </div>+ <p style={{ color: colors.textMuted, fontSize: '10px', marginBottom: '12px' }}>+ Set the default timezone displayed in the navigation bar. Dashboard widgets can use their own timezone settings.+ </p>+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(4, 1fr)',+ gap: '8px',+ maxHeight: '280px',+ overflowY: 'auto',+ paddingRight: '4px'+ }}>+ {timezoneOptions.map((tz) => (+ <button+ key={tz.id}+ onClick={() => setDefaultTimezone(tz.id)}+ style={{+ background: defaultTimezone.id === tz.id ? `${colors.primary}20` : '#1A1A1A',+ border: `1px solid ${defaultTimezone.id === tz.id ? colors.primary : '#2A2A2A'}`,+ borderRadius: '4px',+ padding: '12px 8px',+ cursor: 'pointer',+ textAlign: 'center',+ transition: 'all 0.2s'+ }}+ >+ <div style={{+ color: defaultTimezone.id === tz.id ? colors.primary : colors.text,+ fontWeight: 'bold',+ fontSize: '11px',+ marginBottom: '4px'+ }}>+ {tz.shortLabel}+ </div>+ <div style={{+ color: colors.textMuted,+ fontSize: '9px'+ }}>+ {tz.label.split('(')[0].trim()}+ </div>+ </button>+ ))}+ </div>+ </div>++ {/* Key Mapping Configuration */}+ <div style={{+ background: '#0F0F0F',+ border: '1px solid #2A2A2A',+ borderLeft: `3px solid ${colors.primary}`,+ borderRadius: '4px',+ padding: '16px',+ marginBottom: '20px'+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>+ <Terminal size={18} color={colors.primary} style={{ filter: `drop-shadow(0 0 2px ${colors.primary})` }} />+ <span style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', letterSpacing: '0.5px' }}>FUNCTION KEY MAPPINGS</span>+ </div>++ <div style={{+ marginBottom: '12px',+ padding: '10px',+ backgroundColor: '#1A1A1A',+ border: '1px solid #2A2A2A',+ borderRadius: '3px'+ }}>+ <p style={{+ color: colors.textMuted,+ fontSize: '9px',+ margin: 0,+ lineHeight: '1.5'+ }}>+ Configure which tab or action each function key (F1-F12) should trigger. Changes will be reflected in the status bar and keyboard shortcuts.+ </p>+ </div>++ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: '12px' }}>+ {Object.entries(keyMappings).map(([key, action]) => (+ <div key={key} style={{+ background: '#1A1A1A',+ border: '1px solid #2A2A2A',+ borderRadius: '3px',+ padding: '12px'+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '8px' }}>+ <span style={{+ backgroundColor: colors.primary,+ color: '#000',+ padding: '4px 8px',+ fontSize: '9px',+ fontWeight: 'bold',+ borderRadius: '2px',+ minWidth: '40px',+ textAlign: 'center'+ }}>+ {key}+ </span>+ <span style={{ color: colors.textMuted, fontSize: '10px' }}>→</span>+ </div>+ <select+ value={action}+ onChange={(e) => setKeyMappings({ ...keyMappings, [key]: e.target.value })}+ style={{+ width: '100%',+ padding: '8px',+ background: colors.background,+ border: '1px solid #2A2A2A',+ color: colors.text,+ borderRadius: '3px',+ fontSize: '10px',+ fontWeight: 500,+ cursor: 'pointer',+ appearance: 'none',+ backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23FFA500' d='M6 9L1 4h10z'/%3E%3C/svg%3E")`,+ backgroundRepeat: 'no-repeat',+ backgroundPosition: 'right 8px center',+ paddingRight: '28px'+ }}+ >+ <option value="dashboard">Dashboard</option>+ <option value="markets">Markets</option>+ <option value="news">News</option>+ <option value="portfolio">Portfolio</option>+ <option value="analytics">Analytics</option>+ <option value="watchlist">Watchlist</option>+ <option value="equity-research">Equity Research</option>+ <option value="screener">Screener</option>+ <option value="trading">Trading</option>+ <option value="chat">AI Chat</option>+ <option value="fullscreen">Toggle Fullscreen</option>+ <option value="profile">Profile</option>+ <option value="settings">Settings</option>+ <option value="forum">Forum</option>+ <option value="marketplace">Marketplace</option>+ </select>+ </div>+ ))}+ </div>+ </div>++ {/* Live Preview Panel */}+ <div style={{+ background: theme.colors.background,+ border: `2px solid ${theme.colors.primary}`,+ borderRadius: '4px',+ padding: '20px',+ marginBottom: '20px',+ position: 'relative',+ overflow: 'hidden'+ }}>+ <div style={{+ position: 'absolute',+ top: 0,+ left: 0,+ right: 0,+ height: '2px',+ background: `linear-gradient(90deg, transparent, ${theme.colors.primary}, transparent)`,+ opacity: 0.5+ }} />++ <div style={{+ color: theme.colors.textMuted,+ fontSize: '9px',+ fontWeight: 600,+ letterSpacing: '1px',+ marginBottom: '12px',+ opacity: 0.7+ }}>+ LIVE PREVIEW+ </div>++ <div style={{+ color: theme.colors.primary,+ fontSize: `${baseSize + 2}px`,+ fontFamily: `${fontFamily}, monospace`,+ fontWeight: fontWeight === 'normal' ? '400' : fontWeight === 'semibold' ? '600' : '700',+ fontStyle: fontItalic ? 'italic' : 'normal',+ marginBottom: '12px',+ letterSpacing: '0.5px'+ }}>+ FINCEPT TERMINAL PREVIEW+ </div>++ <div style={{+ color: theme.colors.text,+ fontSize: `${baseSize}px`,+ fontFamily: `${fontFamily}, monospace`,+ fontWeight: fontWeight === 'normal' ? '400' : fontWeight === 'semibold' ? '600' : '700',+ fontStyle: fontItalic ? 'italic' : 'normal',+ marginBottom: '8px',+ lineHeight: '1.5'+ }}>+ Body Text: Real-time market analysis and portfolio tracking+ </div>++ <div style={{+ color: theme.colors.textMuted,+ fontSize: `${baseSize - 1}px`,+ fontFamily: `${fontFamily}, monospace`,+ fontWeight: fontWeight === 'normal' ? '400' : fontWeight === 'semibold' ? '600' : '700',+ fontStyle: fontItalic ? 'italic' : 'normal',+ marginBottom: '12px',+ lineHeight: '1.5'+ }}>+ Small Text: Market data, timestamps, and metadata+ </div>++ <div style={{ display: 'flex', gap: '16px', marginTop: '12px', flexWrap: 'wrap' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <div style={{+ width: '8px',+ height: '8px',+ borderRadius: '50%',+ background: theme.colors.success,+ boxShadow: `0 0 8px ${theme.colors.success}`+ }} />+ <span style={{ color: theme.colors.success, fontSize: '10px', fontWeight: 600 }}>CONNECTED</span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <div style={{+ width: '8px',+ height: '8px',+ borderRadius: '50%',+ background: theme.colors.alert,+ boxShadow: `0 0 8px ${theme.colors.alert}`+ }} />+ <span style={{ color: theme.colors.alert, fontSize: '10px', fontWeight: 600 }}>ALERT</span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <div style={{+ width: '8px',+ height: '8px',+ borderRadius: '50%',+ background: theme.colors.warning,+ boxShadow: `0 0 8px ${theme.colors.warning}`+ }} />+ <span style={{ color: theme.colors.warning, fontSize: '10px', fontWeight: 600 }}>WARNING</span>+ </div>+ </div>+ </div>++ {/* Action Buttons */}+ <div style={{ display: 'flex', gap: '12px' }}>+ <button onClick={handleSaveTerminalAppearance} style={{+ flex: 1,+ background: colors.primary,+ color: '#000000',+ border: 'none',+ padding: '14px',+ fontSize: '11px',+ fontWeight: 'bold',+ letterSpacing: '0.5px',+ borderRadius: '4px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '8px',+ transition: 'all 0.2s',+ boxShadow: `0 0 12px ${colors.primary}40`+ }}>+ <Save size={16} /> SAVE CONFIGURATION+ </button>+ <button onClick={handleResetTerminalAppearance} style={{+ background: 'transparent',+ color: colors.textMuted,+ border: `1px solid #2A2A2A`,+ padding: '14px 20px',+ fontSize: '11px',+ fontWeight: 'bold',+ letterSpacing: '0.5px',+ borderRadius: '4px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ transition: 'all 0.2s'+ }}>+ <RefreshCw size={16} /> RESET+ </button>+ </div>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/index.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/index.tsnew file mode 100644index 000000000..9eb8ddf8a--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/index.ts@@ -0,0 +1,4 @@+export { CredentialsSection } from './CredentialsSection';+export { LLMConfigSection } from './LLMConfigSection';+export { TerminalAppearanceSection } from './TerminalAppearanceSection';+export { StorageCacheSection } from './StorageCacheSection';diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/types.ts b/fincept-terminal-desktop/src/components/tabs/settings-tab/types.tsnew file mode 100644index 000000000..98ca02e47--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/types.ts@@ -0,0 +1,41 @@+// Settings Tab Types++export type SettingsSection =+ | 'credentials'+ | 'polymarket'+ | 'terminal'+ | 'terminalConfig'+ | 'llm'+ | 'dataConnections'+ | 'backtesting'+ | 'stockSymbols'+ | 'language'+ | 'storage';++export interface SettingsMessage {+ type: 'success' | 'error';+ text: string;+}++export interface WSProviderConfig {+ id: number;+ provider_name: string;+ enabled: boolean;+ api_key: string | null;+ api_secret: string | null;+ endpoint: string | null;+ config_data: string | null;+}++export interface SettingsColors {+ background: string;+ panel: string;+ primary: string;+ secondary: string;+ text: string;+ textMuted: string;+ success: string;+ alert: string;+ warning: string;+ accent: string;+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx b/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsxindex d118a4fd3..51c8dcd8e 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx@@ -32,6 +32,7 @@ interface ProChartProps {showToolbar?: boolean;showHeader?: boolean; // Option to hide the symbol/OHLC headeronToolChange?: (tool: DrawingTool | null) => void;+ timezone?: string; // e.g., 'Asia/Kolkata' for IST, 'America/New_York' for EST}export function ProChartWithToolkit({@@ -42,6 +43,7 @@ export function ProChartWithToolkit({showToolbar = true,showHeader = true,onToolChange,+ timezone,}: ProChartProps) {const chartContainerRef = useRef<HTMLDivElement>(null);const chartRef = useRef<IChartApi | null>(null);@@ -61,6 +63,29 @@ export function ProChartWithToolkit({if (!chartContainerRef.current) return;const containerHeight = chartContainerRef.current.clientHeight || height;+ // Build localization options for timezone+ const localizationOptions = timezone ? {+ locale: 'en-IN', // Use Indian locale for IST, can be customized per timezone+ timeFormatter: (time: number) => {+ const date = new Date(time * 1000);+ return date.toLocaleTimeString('en-IN', {+ timeZone: timezone,+ hour: '2-digit',+ minute: '2-digit',+ hour12: false+ });+ },+ dateFormatter: (time: number) => {+ const date = new Date(time * 1000);+ return date.toLocaleDateString('en-IN', {+ timeZone: timezone,+ day: '2-digit',+ month: 'short',+ year: 'numeric'+ });+ },+ } : {};+const chart = createChart(chartContainerRef.current, {width: chartContainerRef.current.clientWidth,height: containerHeight,@@ -69,6 +94,7 @@ export function ProChartWithToolkit({textColor: '#d1d5db',fontSize: 11,},+ localization: localizationOptions,handleScroll: {vertTouchDrag: true,},@@ -245,7 +271,7 @@ export function ProChartWithToolkit({pluginManager.destroy();chart.remove();};- }, [height, showVolume]);+ }, [height, showVolume, timezone]);// Update chart datauseEffect(() => {diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/AdvancedOrders/AdvancedOrdersPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/AdvancedOrders/AdvancedOrdersPanel.tsxnew file mode 100644index 000000000..1ec319fb8--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/AdvancedOrders/AdvancedOrdersPanel.tsx@@ -0,0 +1,372 @@+/**+ * Advanced Orders Panel+ * Batch orders, cancel all orders, cancel after timeout+ */++import React, { useState } from 'react';+import { Layers, XCircle, Clock, AlertTriangle, Check, Loader2, Plus, Trash2 } from 'lucide-react';+import { useCancelAllOrders, useCancelAllOrdersAfter, useCloseAllPositions } from '../../hooks';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',+ PURPLE: '#9D4EDD',+};++interface AdvancedOrdersPanelProps {+ symbol?: string;+}++export function AdvancedOrdersPanel({ symbol }: AdvancedOrdersPanelProps) {+ const { tradingMode, activeBroker } = useBrokerContext();+ const { cancelAllOrders, isLoading: cancellingAll, isSupported: cancelAllSupported } = useCancelAllOrders();+ const { cancelAllOrdersAfter, isLoading: settingTimeout, scheduledTime, isSupported: timeoutSupported } = useCancelAllOrdersAfter();+ const { closeAllPositions, isLoading: closingAll, isSupported: closeAllSupported } = useCloseAllPositions();++ const [timeoutSeconds, setTimeoutSeconds] = useState(60);+ const [confirmCancel, setConfirmCancel] = useState(false);+ const [confirmClose, setConfirmClose] = useState(false);+ const [success, setSuccess] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);++ // Handle cancel all orders+ const handleCancelAll = async () => {+ if (!confirmCancel) {+ setConfirmCancel(true);+ return;+ }++ setError(null);+ const result = await cancelAllOrders(symbol);+ if (result) {+ setSuccess(`Cancelled ${result.length} orders`);+ setTimeout(() => setSuccess(null), 3000);+ }+ setConfirmCancel(false);+ };++ // Handle cancel after timeout+ const handleCancelAfter = async () => {+ setError(null);+ const result = await cancelAllOrdersAfter(timeoutSeconds);+ if (result) {+ setSuccess(`Orders will be cancelled at ${new Date(result.triggerTime).toLocaleTimeString()}`);+ setTimeout(() => setSuccess(null), 5000);+ }+ };++ // Handle close all positions+ const handleCloseAll = async () => {+ if (!confirmClose) {+ setConfirmClose(true);+ return;+ }++ setError(null);+ const result = await closeAllPositions(symbol ? { symbol } : undefined);+ if (result) {+ setSuccess(`Closed ${result.length} positions`);+ setTimeout(() => setSuccess(null), 3000);+ }+ setConfirmClose(false);+ };++ if (tradingMode === 'paper') {+ return (+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px' }}>+ <AlertTriangle size={32} color={FINCEPT.YELLOW} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '12px' }}>Advanced orders not available in paper trading</div>+ </div>+ );+ }++ const isLoading = cancellingAll || settingTimeout || closingAll;++ return (+ <div style={{ background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px', padding: '16px' }}>+ {/* Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px', paddingBottom: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Layers size={14} color={FINCEPT.ORANGE} />+ <span style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>Advanced Orders</span>+ </div>+ {symbol && (+ <span style={{ fontSize: '10px', color: FINCEPT.CYAN, fontFamily: '"IBM Plex Mono", monospace' }}>{symbol}</span>+ )}+ </div>++ {/* Success Message */}+ {success && (+ <div style={{ padding: '10px', backgroundColor: `${FINCEPT.GREEN}20`, borderRadius: '4px', marginBottom: '12px', display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Check size={14} color={FINCEPT.GREEN} />+ <span style={{ fontSize: '11px', color: FINCEPT.GREEN }}>{success}</span>+ </div>+ )}++ {/* Error Message */}+ {error && (+ <div style={{ padding: '10px', backgroundColor: `${FINCEPT.RED}20`, borderRadius: '4px', marginBottom: '12px', fontSize: '11px', color: FINCEPT.RED }}>+ {error}+ </div>+ )}++ {/* Cancel All Orders */}+ {cancelAllSupported && (+ <div style={{ marginBottom: '16px', padding: '12px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '10px' }}>+ <XCircle size={12} color={FINCEPT.RED} />+ <span style={{ fontSize: '10px', color: FINCEPT.WHITE, fontWeight: 600 }}>CANCEL ALL ORDERS</span>+ </div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '10px' }}>+ {symbol ? `Cancel all open orders for ${symbol}` : 'Cancel all open orders across all symbols'}+ </div>+ <button+ onClick={handleCancelAll}+ disabled={isLoading}+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: confirmCancel ? FINCEPT.RED : `${FINCEPT.RED}30`,+ border: `1px solid ${FINCEPT.RED}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '11px',+ fontWeight: 700,+ cursor: isLoading ? 'wait' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ }}+ >+ {cancellingAll ? (+ <>+ <Loader2 size={12} style={{ animation: 'spin 1s linear infinite' }} />+ CANCELLING...+ </>+ ) : confirmCancel ? (+ <>+ <AlertTriangle size={12} />+ CONFIRM CANCEL ALL+ </>+ ) : (+ <>+ <XCircle size={12} />+ CANCEL ALL ORDERS+ </>+ )}+ </button>+ {confirmCancel && (+ <button+ onClick={() => setConfirmCancel(false)}+ style={{+ width: '100%',+ marginTop: '6px',+ padding: '8px',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.GRAY,+ fontSize: '10px',+ cursor: 'pointer',+ }}+ >+ NEVERMIND+ </button>+ )}+ </div>+ )}++ {/* Cancel Orders After Timeout */}+ {timeoutSupported && (+ <div style={{ marginBottom: '16px', padding: '12px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '10px' }}>+ <Clock size={12} color={FINCEPT.YELLOW} />+ <span style={{ fontSize: '10px', color: FINCEPT.WHITE, fontWeight: 600 }}>DEAD MAN'S SWITCH</span>+ </div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '10px' }}>+ Automatically cancel all orders after a timeout+ </div>+ <div style={{ display: 'flex', gap: '8px', marginBottom: '10px' }}>+ <input+ type="number"+ value={timeoutSeconds}+ onChange={(e) => setTimeoutSeconds(parseInt(e.target.value) || 0)}+ min={10}+ max={3600}+ style={{+ flex: 1,+ padding: '8px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '12px',+ fontFamily: '"IBM Plex Mono", monospace',+ }}+ />+ <span style={{ display: 'flex', alignItems: 'center', fontSize: '10px', color: FINCEPT.GRAY }}>seconds</span>+ </div>+ {/* Quick Select */}+ <div style={{ display: 'flex', gap: '4px', marginBottom: '10px' }}>+ {[30, 60, 300, 600].map((sec) => (+ <button+ key={sec}+ onClick={() => setTimeoutSeconds(sec)}+ style={{+ flex: 1,+ padding: '6px',+ backgroundColor: timeoutSeconds === sec ? FINCEPT.YELLOW : 'transparent',+ border: `1px solid ${timeoutSeconds === sec ? FINCEPT.YELLOW : FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: timeoutSeconds === sec ? FINCEPT.DARK_BG : FINCEPT.GRAY,+ fontSize: '9px',+ fontWeight: 600,+ cursor: 'pointer',+ }}+ >+ {sec < 60 ? `${sec}s` : `${sec / 60}m`}+ </button>+ ))}+ </div>+ <button+ onClick={handleCancelAfter}+ disabled={isLoading || timeoutSeconds < 10}+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: `${FINCEPT.YELLOW}30`,+ border: `1px solid ${FINCEPT.YELLOW}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '11px',+ fontWeight: 700,+ cursor: isLoading ? 'wait' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ }}+ >+ {settingTimeout ? (+ <>+ <Loader2 size={12} style={{ animation: 'spin 1s linear infinite' }} />+ SETTING...+ </>+ ) : (+ <>+ <Clock size={12} />+ SET TIMEOUT+ </>+ )}+ </button>+ {scheduledTime && (+ <div style={{ marginTop: '8px', padding: '8px', backgroundColor: `${FINCEPT.YELLOW}15`, borderRadius: '4px', fontSize: '9px', color: FINCEPT.YELLOW }}>+ Orders will cancel at {new Date(scheduledTime).toLocaleTimeString()}+ </div>+ )}+ </div>+ )}++ {/* Close All Positions */}+ {closeAllSupported && (+ <div style={{ padding: '12px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '10px' }}>+ <Trash2 size={12} color={FINCEPT.PURPLE} />+ <span style={{ fontSize: '10px', color: FINCEPT.WHITE, fontWeight: 600 }}>CLOSE ALL POSITIONS</span>+ </div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '10px' }}>+ {symbol ? `Close all positions for ${symbol}` : 'Close all open positions across all symbols'}+ </div>+ <button+ onClick={handleCloseAll}+ disabled={isLoading}+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: confirmClose ? FINCEPT.PURPLE : `${FINCEPT.PURPLE}30`,+ border: `1px solid ${FINCEPT.PURPLE}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '11px',+ fontWeight: 700,+ cursor: isLoading ? 'wait' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ }}+ >+ {closingAll ? (+ <>+ <Loader2 size={12} style={{ animation: 'spin 1s linear infinite' }} />+ CLOSING...+ </>+ ) : confirmClose ? (+ <>+ <AlertTriangle size={12} />+ CONFIRM CLOSE ALL+ </>+ ) : (+ <>+ <Trash2 size={12} />+ CLOSE ALL POSITIONS+ </>+ )}+ </button>+ {confirmClose && (+ <button+ onClick={() => setConfirmClose(false)}+ style={{+ width: '100%',+ marginTop: '6px',+ padding: '8px',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.GRAY,+ fontSize: '10px',+ cursor: 'pointer',+ }}+ >+ NEVERMIND+ </button>+ )}+ </div>+ )}++ {/* No Features Available */}+ {!cancelAllSupported && !timeoutSupported && !closeAllSupported && (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ No advanced order features available for {activeBroker}+ </div>+ )}++ {/* Warning */}+ <div style={{ marginTop: '12px', padding: '10px', backgroundColor: `${FINCEPT.RED}10`, borderRadius: '4px', display: 'flex', gap: '8px', alignItems: 'flex-start' }}>+ <AlertTriangle size={14} color={FINCEPT.RED} style={{ flexShrink: 0, marginTop: '2px' }} />+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ <strong style={{ color: FINCEPT.RED }}>Warning:</strong> These actions are irreversible.+ Cancelled orders and closed positions cannot be restored.+ </div>+ </div>++ <style>{`+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `}</style>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/AdvancedOrders/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/core/AdvancedOrders/index.tsnew file mode 100644index 000000000..aba291040--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/AdvancedOrders/index.ts@@ -0,0 +1 @@+export { AdvancedOrdersPanel } from './AdvancedOrdersPanel';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/ConvertManager/ConvertPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/ConvertManager/ConvertPanel.tsxnew file mode 100644index 000000000..60ee19a86--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/ConvertManager/ConvertPanel.tsx@@ -0,0 +1,405 @@+/**+ * Convert Panel+ * Allows users to swap/convert between cryptocurrencies+ */++import React, { useState, useEffect } from 'react';+import { ArrowRightLeft, RefreshCw, AlertCircle, Check, Loader2, ArrowDownUp } from 'lucide-react';+import { useConvertCurrencies, useConvertQuote, useCreateConvertTrade } from '../../hooks/useConversions';+import { useBalance } from '../../hooks/useAccountInfo';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',+};++export function ConvertPanel() {+ const { tradingMode, activeBroker } = useBrokerContext();+ const { balances } = useBalance(false);+ const { currencies, isLoading: currenciesLoading, isSupported } = useConvertCurrencies();+ const { createTrade, isLoading: tradeLoading, error: tradeError, lastTrade } = useCreateConvertTrade();++ const [fromCurrency, setFromCurrency] = useState('');+ const [toCurrency, setToCurrency] = useState('');+ const [amount, setAmount] = useState('');+ const [showConfirm, setShowConfirm] = useState(false);+ const [success, setSuccess] = useState(false);++ // Get quote when currencies and amount are set+ const numericAmount = parseFloat(amount) || 0;+ const { quote, isLoading: quoteLoading, refresh: refreshQuote } = useConvertQuote(+ fromCurrency || undefined,+ toCurrency || undefined,+ numericAmount > 0 ? numericAmount : undefined+ );++ // Available currencies with balance+ const availableCurrencies = balances.filter((b) => b.free > 0).map((b) => b.currency);+ const fromBalance = balances.find((b) => b.currency === fromCurrency)?.free || 0;++ // Swap currencies+ const handleSwap = () => {+ const temp = fromCurrency;+ setFromCurrency(toCurrency);+ setToCurrency(temp);+ setAmount('');+ };++ // Handle amount change+ const handleAmountChange = (value: string) => {+ if (/^\d*\.?\d*$/.test(value)) {+ setAmount(value);+ }+ };++ // Set max amount+ const handleSetMax = () => {+ setAmount(fromBalance.toString());+ };++ // Execute conversion+ const handleConvert = async () => {+ if (!fromCurrency || !toCurrency || numericAmount <= 0) return;++ const result = await createTrade(fromCurrency, toCurrency, numericAmount, quote?.id);++ if (result) {+ setSuccess(true);+ setTimeout(() => {+ setAmount('');+ setShowConfirm(false);+ setSuccess(false);+ }, 3000);+ }+ };++ // Reset on currency change+ useEffect(() => {+ setShowConfirm(false);+ setSuccess(false);+ }, [fromCurrency, toCurrency]);++ if (tradingMode === 'paper') {+ return (+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px' }}>+ <AlertCircle size={32} color={FINCEPT.YELLOW} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '12px', marginBottom: '8px' }}>+ Currency conversion not available in paper trading mode+ </div>+ </div>+ );+ }++ if (!isSupported) {+ return (+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px' }}>+ <AlertCircle size={32} color={FINCEPT.GRAY} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '12px', marginBottom: '8px' }}>+ Currency conversion not supported by {activeBroker}+ </div>+ </div>+ );+ }++ return (+ <div style={{ background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px', padding: '16px' }}>+ {/* Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px', paddingBottom: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <ArrowRightLeft size={14} color={FINCEPT.CYAN} />+ <span style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>Convert Crypto</span>+ </div>+ </div>++ {/* Success Message */}+ {success && lastTrade && (+ <div style={{ padding: '16px', backgroundColor: `${FINCEPT.GREEN}20`, borderRadius: '4px', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '12px' }}>+ <Check size={20} color={FINCEPT.GREEN} />+ <div>+ <div style={{ fontSize: '12px', color: FINCEPT.GREEN, fontWeight: 600 }}>Conversion Successful!</div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>+ Converted {lastTrade.fromAmount} {lastTrade.fromCurrency} to {lastTrade.toAmount.toFixed(8)} {lastTrade.toCurrency}+ </div>+ </div>+ </div>+ )}++ {/* Error Message */}+ {tradeError && !success && (+ <div style={{ padding: '12px', backgroundColor: `${FINCEPT.RED}20`, borderRadius: '4px', marginBottom: '16px', fontSize: '11px', color: FINCEPT.RED }}>+ {tradeError.message}+ </div>+ )}++ {/* From Currency */}+ <div style={{ marginBottom: '8px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>+ <label style={{ fontSize: '9px', color: FINCEPT.GRAY }}>FROM</label>+ <span style={{ fontSize: '9px', color: FINCEPT.CYAN }}>+ Balance: {fromBalance.toFixed(8)} {fromCurrency || '--'}+ </span>+ </div>+ <div style={{ display: 'flex', gap: '8px' }}>+ <select+ value={fromCurrency}+ onChange={(e) => setFromCurrency(e.target.value)}+ style={{+ width: '120px',+ padding: '10px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '12px',+ }}+ >+ <option value="">Select</option>+ {availableCurrencies.map((c) => (+ <option key={c} value={c} disabled={c === toCurrency}>{c}</option>+ ))}+ </select>+ <div style={{ flex: 1, display: 'flex', gap: '4px' }}>+ <input+ type="text"+ value={amount}+ onChange={(e) => handleAmountChange(e.target.value)}+ placeholder="0.00"+ style={{+ flex: 1,+ padding: '10px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '14px',+ fontFamily: '"IBM Plex Mono", monospace',+ }}+ />+ <button+ onClick={handleSetMax}+ disabled={!fromCurrency}+ style={{+ padding: '10px 12px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.ORANGE,+ fontSize: '9px',+ fontWeight: 700,+ cursor: fromCurrency ? 'pointer' : 'not-allowed',+ }}+ >+ MAX+ </button>+ </div>+ </div>+ </div>++ {/* Swap Button */}+ <div style={{ display: 'flex', justifyContent: 'center', padding: '8px 0' }}>+ <button+ onClick={handleSwap}+ disabled={!fromCurrency && !toCurrency}+ style={{+ padding: '8px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '50%',+ cursor: 'pointer',+ }}+ >+ <ArrowDownUp size={16} color={FINCEPT.ORANGE} />+ </button>+ </div>++ {/* To Currency */}+ <div style={{ marginBottom: '16px' }}>+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '6px' }}>TO</label>+ <div style={{ display: 'flex', gap: '8px' }}>+ <select+ value={toCurrency}+ onChange={(e) => setToCurrency(e.target.value)}+ style={{+ width: '120px',+ padding: '10px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '12px',+ }}+ >+ <option value="">Select</option>+ {(currencies.length > 0 ? currencies : ['BTC', 'ETH', 'USDT', 'USDC', 'BNB']).map((c) => (+ <option key={c} value={c} disabled={c === fromCurrency}>{c}</option>+ ))}+ </select>+ <div+ style={{+ flex: 1,+ padding: '10px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.GREEN,+ fontSize: '14px',+ fontFamily: '"IBM Plex Mono", monospace',+ display: 'flex',+ alignItems: 'center',+ }}+ >+ {quoteLoading ? (+ <Loader2 size={14} color={FINCEPT.GRAY} style={{ animation: 'spin 1s linear infinite' }} />+ ) : quote ? (+ `~${quote.toAmount.toFixed(8)}`+ ) : (+ '--'+ )}+ </div>+ </div>+ </div>++ {/* Rate Display */}+ {quote && (+ <div style={{ padding: '12px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px', marginBottom: '16px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY }}>Rate</span>+ <span style={{ fontSize: '10px', color: FINCEPT.WHITE, fontFamily: '"IBM Plex Mono", monospace' }}>+ 1 {fromCurrency} = {quote.rate.toFixed(8)} {toCurrency}+ </span>+ </div>+ {quote.fee !== undefined && (+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY }}>Fee</span>+ <span style={{ fontSize: '10px', color: FINCEPT.ORANGE, fontFamily: '"IBM Plex Mono", monospace' }}>+ {quote.fee} {quote.feeCurrency || fromCurrency}+ </span>+ </div>+ )}+ <button+ onClick={refreshQuote}+ disabled={quoteLoading}+ style={{+ marginTop: '8px',+ width: '100%',+ padding: '6px',+ backgroundColor: 'transparent',+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.GRAY,+ fontSize: '9px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '4px',+ }}+ >+ <RefreshCw size={10} style={{ animation: quoteLoading ? 'spin 1s linear infinite' : 'none' }} />+ Refresh Quote+ </button>+ </div>+ )}++ {/* Convert Button */}+ {!showConfirm ? (+ <button+ onClick={() => setShowConfirm(true)}+ disabled={!fromCurrency || !toCurrency || numericAmount <= 0 || numericAmount > fromBalance || !quote}+ style={{+ width: '100%',+ padding: '14px',+ backgroundColor: (fromCurrency && toCurrency && numericAmount > 0 && numericAmount <= fromBalance && quote) ? FINCEPT.ORANGE : FINCEPT.BORDER,+ border: 'none',+ borderRadius: '4px',+ color: (fromCurrency && toCurrency && numericAmount > 0 && numericAmount <= fromBalance && quote) ? FINCEPT.WHITE : FINCEPT.GRAY,+ fontSize: '12px',+ fontWeight: 700,+ cursor: (fromCurrency && toCurrency && numericAmount > 0 && numericAmount <= fromBalance && quote) ? 'pointer' : 'not-allowed',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '8px',+ }}+ >+ <ArrowRightLeft size={14} />+ PREVIEW CONVERSION+ </button>+ ) : (+ <div>+ <div style={{ padding: '12px', backgroundColor: `${FINCEPT.CYAN}15`, border: `1px solid ${FINCEPT.CYAN}`, borderRadius: '4px', marginBottom: '12px', fontSize: '10px' }}>+ <div style={{ marginBottom: '4px', color: FINCEPT.CYAN, fontWeight: 600 }}>Confirm Conversion</div>+ <div style={{ color: FINCEPT.WHITE }}>+ Convert <strong>{amount} {fromCurrency}</strong> to approximately <strong>{quote?.toAmount.toFixed(8)} {toCurrency}</strong>+ </div>+ </div>+ <div style={{ display: 'flex', gap: '8px' }}>+ <button+ onClick={() => setShowConfirm(false)}+ style={{+ flex: 1,+ padding: '12px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.GRAY,+ fontSize: '11px',+ cursor: 'pointer',+ }}+ >+ CANCEL+ </button>+ <button+ onClick={handleConvert}+ disabled={tradeLoading}+ style={{+ flex: 2,+ padding: '12px',+ backgroundColor: FINCEPT.GREEN,+ border: 'none',+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '11px',+ fontWeight: 700,+ cursor: tradeLoading ? 'wait' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ }}+ >+ {tradeLoading ? (+ <>+ <Loader2 size={14} style={{ animation: 'spin 1s linear infinite' }} />+ CONVERTING...+ </>+ ) : (+ <>+ <Check size={14} />+ CONFIRM CONVERT+ </>+ )}+ </button>+ </div>+ </div>+ )}++ <style>{`+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `}</style>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/ConvertManager/TransferPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/ConvertManager/TransferPanel.tsxnew file mode 100644index 000000000..3c5ea5b1f--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/ConvertManager/TransferPanel.tsx@@ -0,0 +1,340 @@+/**+ * Transfer Panel+ * Allows users to transfer funds between accounts (spot, margin, futures, etc.)+ */++import React, { useState } from 'react';+import { ArrowRight, RefreshCw, AlertCircle, Check, Loader2 } from 'lucide-react';+import { useTransfer, useAvailableAccounts } from '../../hooks/useConversions';+import { useBalance } from '../../hooks/useAccountInfo';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',+ PURPLE: '#9D4EDD',+};++export function TransferPanel() {+ const { tradingMode, activeBroker } = useBrokerContext();+ const { balances } = useBalance(false);+ const accounts = useAvailableAccounts();+ const { transfer, isLoading, error, lastTransfer, isSupported } = useTransfer();++ const [currency, setCurrency] = useState('');+ const [amount, setAmount] = useState('');+ const [fromAccount, setFromAccount] = useState('');+ const [toAccount, setToAccount] = useState('');+ const [success, setSuccess] = useState(false);++ // Get balance for selected currency+ const selectedBalance = balances.find((b) => b.currency === currency)?.free || 0;++ // Handle amount change+ const handleAmountChange = (value: string) => {+ if (/^\d*\.?\d*$/.test(value)) {+ setAmount(value);+ }+ };++ // Set max amount+ const handleSetMax = () => {+ setAmount(selectedBalance.toString());+ };++ // Swap accounts+ const handleSwapAccounts = () => {+ const temp = fromAccount;+ setFromAccount(toAccount);+ setToAccount(temp);+ };++ // Execute transfer+ const handleTransfer = async () => {+ const numericAmount = parseFloat(amount);+ if (!currency || numericAmount <= 0 || !fromAccount || !toAccount) return;++ const result = await transfer(currency, numericAmount, fromAccount, toAccount);++ if (result) {+ setSuccess(true);+ setTimeout(() => {+ setAmount('');+ setSuccess(false);+ }, 3000);+ }+ };++ const isValidForm = () => {+ const numericAmount = parseFloat(amount) || 0;+ return (+ currency &&+ numericAmount > 0 &&+ numericAmount <= selectedBalance &&+ fromAccount &&+ toAccount &&+ fromAccount !== toAccount+ );+ };++ if (tradingMode === 'paper') {+ return (+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px' }}>+ <AlertCircle size={32} color={FINCEPT.YELLOW} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '12px', marginBottom: '8px' }}>+ Internal transfers not available in paper trading mode+ </div>+ </div>+ );+ }++ if (!isSupported) {+ return (+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px' }}>+ <AlertCircle size={32} color={FINCEPT.GRAY} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '12px', marginBottom: '8px' }}>+ Internal transfers not supported by {activeBroker}+ </div>+ </div>+ );+ }++ return (+ <div style={{ background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px', padding: '16px' }}>+ {/* Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px', paddingBottom: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <ArrowRight size={14} color={FINCEPT.PURPLE} />+ <span style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>Internal Transfer</span>+ </div>+ </div>++ {/* Success Message */}+ {success && lastTransfer && (+ <div style={{ padding: '16px', backgroundColor: `${FINCEPT.GREEN}20`, borderRadius: '4px', marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '12px' }}>+ <Check size={20} color={FINCEPT.GREEN} />+ <div>+ <div style={{ fontSize: '12px', color: FINCEPT.GREEN, fontWeight: 600 }}>Transfer Successful!</div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>+ Moved {lastTransfer.amount} {lastTransfer.currency} from {lastTransfer.fromAccount} to {lastTransfer.toAccount}+ </div>+ </div>+ </div>+ )}++ {/* Error Message */}+ {error && !success && (+ <div style={{ padding: '12px', backgroundColor: `${FINCEPT.RED}20`, borderRadius: '4px', marginBottom: '16px', fontSize: '11px', color: FINCEPT.RED }}>+ {error.message}+ </div>+ )}++ {/* Currency Selection */}+ <div style={{ marginBottom: '16px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>+ <label style={{ fontSize: '9px', color: FINCEPT.GRAY }}>CURRENCY</label>+ <span style={{ fontSize: '9px', color: FINCEPT.CYAN }}>+ Available: {selectedBalance.toFixed(8)} {currency || '--'}+ </span>+ </div>+ <select+ value={currency}+ onChange={(e) => setCurrency(e.target.value)}+ style={{+ width: '100%',+ padding: '10px 12px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '12px',+ }}+ >+ <option value="">Select currency</option>+ {balances.filter((b) => b.free > 0).map((b) => (+ <option key={b.currency} value={b.currency}>+ {b.currency} ({b.free.toFixed(8)} available)+ </option>+ ))}+ </select>+ </div>++ {/* Amount Input */}+ <div style={{ marginBottom: '16px' }}>+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '6px' }}>AMOUNT</label>+ <div style={{ display: 'flex', gap: '8px' }}>+ <input+ type="text"+ value={amount}+ onChange={(e) => handleAmountChange(e.target.value)}+ placeholder="0.00000000"+ style={{+ flex: 1,+ padding: '10px 12px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '14px',+ fontFamily: '"IBM Plex Mono", monospace',+ }}+ />+ <button+ onClick={handleSetMax}+ disabled={!currency}+ style={{+ padding: '10px 16px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.ORANGE,+ fontSize: '10px',+ fontWeight: 700,+ cursor: currency ? 'pointer' : 'not-allowed',+ }}+ >+ MAX+ </button>+ </div>+ </div>++ {/* Account Selection */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', gap: '8px', alignItems: 'end', marginBottom: '16px' }}>+ {/* From Account */}+ <div>+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '6px' }}>FROM</label>+ <select+ value={fromAccount}+ onChange={(e) => setFromAccount(e.target.value)}+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '11px',+ }}+ >+ <option value="">Select</option>+ {accounts.map((acc) => (+ <option key={acc.id} value={acc.id} disabled={acc.id === toAccount}>+ {acc.name}+ </option>+ ))}+ </select>+ </div>++ {/* Swap Button */}+ <button+ onClick={handleSwapAccounts}+ disabled={!fromAccount && !toAccount}+ style={{+ padding: '10px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ cursor: 'pointer',+ marginBottom: '0px',+ }}+ >+ <ArrowRight size={14} color={FINCEPT.PURPLE} />+ </button>++ {/* To Account */}+ <div>+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '6px' }}>TO</label>+ <select+ value={toAccount}+ onChange={(e) => setToAccount(e.target.value)}+ style={{+ width: '100%',+ padding: '10px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '11px',+ }}+ >+ <option value="">Select</option>+ {accounts.map((acc) => (+ <option key={acc.id} value={acc.id} disabled={acc.id === fromAccount}>+ {acc.name}+ </option>+ ))}+ </select>+ </div>+ </div>++ {/* Account Descriptions */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '16px' }}>+ {fromAccount && (+ <div style={{ padding: '8px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px', fontSize: '9px', color: FINCEPT.GRAY }}>+ <strong style={{ color: FINCEPT.WHITE }}>From:</strong> {accounts.find((a) => a.id === fromAccount)?.description}+ </div>+ )}+ {toAccount && (+ <div style={{ padding: '8px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px', fontSize: '9px', color: FINCEPT.GRAY }}>+ <strong style={{ color: FINCEPT.WHITE }}>To:</strong> {accounts.find((a) => a.id === toAccount)?.description}+ </div>+ )}+ </div>++ {/* Transfer Button */}+ <button+ onClick={handleTransfer}+ disabled={!isValidForm() || isLoading}+ style={{+ width: '100%',+ padding: '14px',+ backgroundColor: isValidForm() && !isLoading ? FINCEPT.PURPLE : FINCEPT.BORDER,+ border: 'none',+ borderRadius: '4px',+ color: isValidForm() && !isLoading ? FINCEPT.WHITE : FINCEPT.GRAY,+ fontSize: '12px',+ fontWeight: 700,+ cursor: isValidForm() && !isLoading ? 'pointer' : 'not-allowed',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '8px',+ }}+ >+ {isLoading ? (+ <>+ <Loader2 size={14} style={{ animation: 'spin 1s linear infinite' }} />+ TRANSFERRING...+ </>+ ) : (+ <>+ <ArrowRight size={14} />+ TRANSFER FUNDS+ </>+ )}+ </button>++ {/* Info */}+ <div style={{ marginTop: '12px', padding: '10px', backgroundColor: `${FINCEPT.PURPLE}15`, borderRadius: '4px', fontSize: '9px', color: FINCEPT.GRAY }}>+ <strong style={{ color: FINCEPT.PURPLE }}>Note:</strong> Internal transfers are instant and free.+ Move funds between your accounts to enable different trading features.+ </div>++ <style>{`+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `}</style>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/ConvertManager/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/core/ConvertManager/index.tsnew file mode 100644index 000000000..2f58a3753--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/ConvertManager/index.ts@@ -0,0 +1,2 @@+export { ConvertPanel } from './ConvertPanel';+export { TransferPanel } from './TransferPanel';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/DerivativesInfo/BorrowRatesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/DerivativesInfo/BorrowRatesPanel.tsxnew file mode 100644index 000000000..2220d0a2b--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/DerivativesInfo/BorrowRatesPanel.tsx@@ -0,0 +1,221 @@+/**+ * Borrow Rates Panel+ * Displays borrow rates for margin trading+ */++import React, { useState } from 'react';+import { Percent, RefreshCw, AlertCircle, Search } from 'lucide-react';+import { useBorrowRate, useBorrowRates } from '../../hooks/useDerivatives';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',+ BLUE: '#0088FF',+};++interface BorrowRatesPanelProps {+ currency?: string;+}++export function BorrowRatesPanel({ currency }: BorrowRatesPanelProps) {+ const { tradingMode } = useBrokerContext();+ const [searchTerm, setSearchTerm] = useState('');+ const [selectedCurrency, setSelectedCurrency] = useState(currency || '');++ const { borrowRate, isLoading: singleLoading, isSupported: singleSupported, refresh: refreshSingle } = useBorrowRate(selectedCurrency || undefined);+ const { borrowRates, isLoading: allLoading, isSupported: allSupported, refresh: refreshAll } = useBorrowRates();++ const formatRate = (rate: number) => {+ return `${(rate * 100).toFixed(4)}%`;+ };++ const formatDailyRate = (rate: number) => {+ // Assuming hourly rate, convert to daily+ const daily = rate * 24 * 100;+ return `${daily.toFixed(4)}%/day`;+ };++ const formatAnnualRate = (rate: number) => {+ // Assuming hourly rate, convert to annual+ const annual = rate * 24 * 365 * 100;+ return `${annual.toFixed(2)}% APY`;+ };++ const getRateColor = (rate: number) => {+ if (rate < 0.0001) return FINCEPT.GREEN; // Low rate+ if (rate < 0.001) return FINCEPT.YELLOW; // Medium rate+ return FINCEPT.RED; // High rate+ };++ // Filter rates by search term+ const filteredRates = borrowRates.filter((r) =>+ r.currency.toLowerCase().includes(searchTerm.toLowerCase())+ );++ if (tradingMode === 'paper') {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ <AlertCircle size={20} color={FINCEPT.YELLOW} style={{ marginBottom: '8px' }} />+ <div>Borrow rates not available in paper trading mode</div>+ </div>+ );+ }++ if (!singleSupported && !allSupported) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ Borrow rates not supported by this exchange+ </div>+ );+ }++ return (+ <div style={{ background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px', padding: '12px' }}>+ {/* Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Percent size={14} color={FINCEPT.BLUE} />+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>BORROW RATES</span>+ </div>+ <button+ onClick={refreshAll}+ disabled={allLoading}+ style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: '4px' }}+ >+ <RefreshCw size={12} color={FINCEPT.GRAY} style={{ animation: allLoading ? 'spin 1s linear infinite' : 'none' }} />+ </button>+ </div>++ {/* Search */}+ <div style={{ position: 'relative', marginBottom: '12px' }}>+ <Search size={12} color={FINCEPT.GRAY} style={{ position: 'absolute', left: '10px', top: '50%', transform: 'translateY(-50%)' }} />+ <input+ type="text"+ value={searchTerm}+ onChange={(e) => setSearchTerm(e.target.value)}+ placeholder="Search currency..."+ style={{+ width: '100%',+ padding: '8px 10px 8px 30px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '10px',+ }}+ />+ </div>++ {/* Selected Currency Detail */}+ {selectedCurrency && borrowRate && (+ <div style={{ padding: '12px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px', marginBottom: '12px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>+ <span style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>{selectedCurrency}</span>+ <button+ onClick={() => setSelectedCurrency('')}+ style={{ background: 'transparent', border: 'none', color: FINCEPT.GRAY, cursor: 'pointer', fontSize: '10px' }}+ >+ Clear+ </button>+ </div>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>+ <div>+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY }}>HOURLY</div>+ <div style={{ fontSize: '14px', fontWeight: 700, fontFamily: '"IBM Plex Mono", monospace', color: getRateColor(borrowRate.rate) }}>+ {formatRate(borrowRate.rate)}+ </div>+ </div>+ <div>+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY }}>DAILY</div>+ <div style={{ fontSize: '14px', fontWeight: 700, fontFamily: '"IBM Plex Mono", monospace', color: getRateColor(borrowRate.rate) }}>+ {formatDailyRate(borrowRate.rate)}+ </div>+ </div>+ <div>+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY }}>ANNUAL</div>+ <div style={{ fontSize: '14px', fontWeight: 700, fontFamily: '"IBM Plex Mono", monospace', color: getRateColor(borrowRate.rate) }}>+ {formatAnnualRate(borrowRate.rate)}+ </div>+ </div>+ </div>+ </div>+ )}++ {/* Rates Table */}+ <div style={{ maxHeight: '200px', overflowY: 'auto' }}>+ {allLoading && borrowRates.length === 0 ? (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '10px' }}>+ Loading borrow rates...+ </div>+ ) : filteredRates.length === 0 ? (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '10px' }}>+ {searchTerm ? 'No matching currencies' : 'No borrow rates available'}+ </div>+ ) : (+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>+ <thead>+ <tr style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <th style={{ padding: '6px', textAlign: 'left', color: FINCEPT.GRAY }}>CURRENCY</th>+ <th style={{ padding: '6px', textAlign: 'right', color: FINCEPT.GRAY }}>HOURLY</th>+ <th style={{ padding: '6px', textAlign: 'right', color: FINCEPT.GRAY }}>DAILY</th>+ <th style={{ padding: '6px', textAlign: 'right', color: FINCEPT.GRAY }}>APY</th>+ </tr>+ </thead>+ <tbody>+ {filteredRates.slice(0, 30).map((rate, idx) => (+ <tr+ key={rate.currency}+ onClick={() => setSelectedCurrency(rate.currency)}+ style={{+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ backgroundColor: selectedCurrency === rate.currency ? `${FINCEPT.ORANGE}20` : idx % 2 === 0 ? FINCEPT.DARK_BG : 'transparent',+ cursor: 'pointer',+ }}+ >+ <td style={{ padding: '6px', color: FINCEPT.WHITE, fontWeight: 600 }}>+ {rate.currency}+ </td>+ <td style={{ padding: '6px', textAlign: 'right', fontFamily: '"IBM Plex Mono", monospace', color: getRateColor(rate.rate) }}>+ {formatRate(rate.rate)}+ </td>+ <td style={{ padding: '6px', textAlign: 'right', fontFamily: '"IBM Plex Mono", monospace', color: getRateColor(rate.rate) }}>+ {formatDailyRate(rate.rate)}+ </td>+ <td style={{ padding: '6px', textAlign: 'right', fontFamily: '"IBM Plex Mono", monospace', color: getRateColor(rate.rate) }}>+ {formatAnnualRate(rate.rate)}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>++ {/* Info */}+ <div style={{ marginTop: '12px', padding: '10px', backgroundColor: `${FINCEPT.BLUE}15`, borderRadius: '4px', fontSize: '9px', color: FINCEPT.GRAY }}>+ <strong style={{ color: FINCEPT.BLUE }}>About Borrow Rates:</strong>+ <div style={{ marginTop: '4px' }}>+ Interest charged when borrowing assets for margin trading.+ Lower rates = cheaper to hold leveraged positions.+ </div>+ </div>++ <style>{`+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `}</style>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/DerivativesInfo/FundingRatesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/DerivativesInfo/FundingRatesPanel.tsxnew file mode 100644index 000000000..ae3659350--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/DerivativesInfo/FundingRatesPanel.tsx@@ -0,0 +1,226 @@+/**+ * Funding Rates Panel+ * Displays funding rates for perpetual contracts+ */++import React, { useState } from 'react';+import { TrendingUp, TrendingDown, RefreshCw, Clock, AlertCircle } from 'lucide-react';+import { useFundingRate, useFundingRates } from '../../hooks/useDerivatives';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',+};++interface FundingRatesPanelProps {+ symbol?: string;+ showAll?: boolean;+}++export function FundingRatesPanel({ symbol, showAll = false }: FundingRatesPanelProps) {+ const { tradingMode } = useBrokerContext();+ const { fundingRate, isLoading: singleLoading, isSupported: singleSupported, refresh: refreshSingle } = useFundingRate(symbol);+ const { fundingRates, isLoading: allLoading, isSupported: allSupported, refresh: refreshAll } = useFundingRates();++ const [viewMode, setViewMode] = useState<'single' | 'all'>(showAll ? 'all' : 'single');++ const formatRate = (rate: number) => {+ const percent = (rate * 100).toFixed(4);+ return `${rate >= 0 ? '+' : ''}${percent}%`;+ };++ const formatAnnualized = (rate: number) => {+ // 3 funding periods per day * 365 days+ const annualized = rate * 3 * 365 * 100;+ return `${annualized >= 0 ? '+' : ''}${annualized.toFixed(2)}% APR`;+ };++ const getRateColor = (rate: number) => {+ if (rate > 0.001) return FINCEPT.GREEN; // Longs pay shorts+ if (rate < -0.001) return FINCEPT.RED; // Shorts pay longs+ return FINCEPT.GRAY; // Neutral+ };++ const getNextFundingTime = (timestamp?: number) => {+ if (!timestamp) return '--';+ const now = Date.now();+ const diff = timestamp - now;+ if (diff <= 0) return 'Now';+ const hours = Math.floor(diff / 3600000);+ const minutes = Math.floor((diff % 3600000) / 60000);+ return `${hours}h ${minutes}m`;+ };++ if (tradingMode === 'paper') {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ <AlertCircle size={20} color={FINCEPT.YELLOW} style={{ marginBottom: '8px' }} />+ <div>Funding rates not available in paper trading mode</div>+ </div>+ );+ }++ if (!singleSupported && !allSupported) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ Funding rates not supported by this exchange+ </div>+ );+ }++ return (+ <div style={{ background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px', padding: '12px' }}>+ {/* Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <TrendingUp size={14} color={FINCEPT.ORANGE} />+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>FUNDING RATES</span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ {symbol && (+ <div style={{ display: 'flex', gap: '4px' }}>+ <button+ onClick={() => setViewMode('single')}+ style={{+ padding: '4px 8px',+ fontSize: '9px',+ backgroundColor: viewMode === 'single' ? FINCEPT.ORANGE : FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ color: viewMode === 'single' ? FINCEPT.WHITE : FINCEPT.GRAY,+ cursor: 'pointer',+ }}+ >+ {symbol}+ </button>+ <button+ onClick={() => setViewMode('all')}+ style={{+ padding: '4px 8px',+ fontSize: '9px',+ backgroundColor: viewMode === 'all' ? FINCEPT.ORANGE : FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ color: viewMode === 'all' ? FINCEPT.WHITE : FINCEPT.GRAY,+ cursor: 'pointer',+ }}+ >+ ALL+ </button>+ </div>+ )}+ <button+ onClick={viewMode === 'single' ? refreshSingle : refreshAll}+ disabled={singleLoading || allLoading}+ style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: '4px' }}+ >+ <RefreshCw size={12} color={FINCEPT.GRAY} style={{ animation: (singleLoading || allLoading) ? 'spin 1s linear infinite' : 'none' }} />+ </button>+ </div>+ </div>++ {/* Single Symbol View */}+ {viewMode === 'single' && fundingRate && (+ <div>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px', marginBottom: '8px' }}>+ <div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>CURRENT RATE</div>+ <div style={{ fontSize: '20px', fontWeight: 700, fontFamily: '"IBM Plex Mono", monospace', color: getRateColor(fundingRate.fundingRate) }}>+ {formatRate(fundingRate.fundingRate)}+ </div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>+ {formatAnnualized(fundingRate.fundingRate)}+ </div>+ </div>+ <div style={{ textAlign: 'right' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', marginBottom: '4px' }}>+ <Clock size={10} color={FINCEPT.CYAN} />+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>NEXT IN</span>+ </div>+ <div style={{ fontSize: '14px', fontWeight: 600, color: FINCEPT.CYAN, fontFamily: '"IBM Plex Mono", monospace' }}>+ {getNextFundingTime(fundingRate.nextFundingTimestamp)}+ </div>+ </div>+ </div>++ {fundingRate.nextFundingRate !== undefined && (+ <div style={{ padding: '10px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px' }}>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>PREDICTED NEXT</div>+ <div style={{ fontSize: '14px', fontWeight: 600, fontFamily: '"IBM Plex Mono", monospace', color: getRateColor(fundingRate.nextFundingRate) }}>+ {formatRate(fundingRate.nextFundingRate)}+ </div>+ </div>+ )}++ {/* Rate Interpretation */}+ <div style={{ marginTop: '12px', padding: '10px', backgroundColor: `${getRateColor(fundingRate.fundingRate)}15`, borderRadius: '4px', fontSize: '10px' }}>+ {fundingRate.fundingRate > 0 ? (+ <span style={{ color: FINCEPT.GREEN }}>+ <TrendingUp size={12} style={{ marginRight: '4px', verticalAlign: 'middle' }} />+ Longs pay shorts - Bullish sentiment+ </span>+ ) : fundingRate.fundingRate < 0 ? (+ <span style={{ color: FINCEPT.RED }}>+ <TrendingDown size={12} style={{ marginRight: '4px', verticalAlign: 'middle' }} />+ Shorts pay longs - Bearish sentiment+ </span>+ ) : (+ <span style={{ color: FINCEPT.GRAY }}>Neutral funding rate</span>+ )}+ </div>+ </div>+ )}++ {/* All Symbols View */}+ {viewMode === 'all' && (+ <div style={{ maxHeight: '300px', overflowY: 'auto' }}>+ {fundingRates.length === 0 ? (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '10px' }}>+ {allLoading ? 'Loading...' : 'No funding rates available'}+ </div>+ ) : (+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>+ <thead>+ <tr style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <th style={{ padding: '8px', textAlign: 'left', color: FINCEPT.GRAY }}>SYMBOL</th>+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY }}>RATE</th>+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY }}>APR</th>+ </tr>+ </thead>+ <tbody>+ {fundingRates.slice(0, 20).map((rate, idx) => (+ <tr key={rate.symbol} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}`, backgroundColor: idx % 2 === 0 ? FINCEPT.DARK_BG : 'transparent' }}>+ <td style={{ padding: '8px', color: FINCEPT.WHITE, fontWeight: 600 }}>{rate.symbol}</td>+ <td style={{ padding: '8px', textAlign: 'right', fontFamily: '"IBM Plex Mono", monospace', color: getRateColor(rate.fundingRate) }}>+ {formatRate(rate.fundingRate)}+ </td>+ <td style={{ padding: '8px', textAlign: 'right', fontFamily: '"IBM Plex Mono", monospace', color: getRateColor(rate.fundingRate) }}>+ {formatAnnualized(rate.fundingRate)}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </div>+ )}++ <style>{`+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `}</style>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/DerivativesInfo/LiquidationsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/DerivativesInfo/LiquidationsPanel.tsxnew file mode 100644index 000000000..a7de7079d--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/DerivativesInfo/LiquidationsPanel.tsx@@ -0,0 +1,228 @@+/**+ * Liquidations Panel+ * Displays market liquidations and personal liquidation history+ */++import React, { useState } from 'react';+import { Flame, RefreshCw, AlertCircle, AlertTriangle } from 'lucide-react';+import { useLiquidations, useMyLiquidations } from '../../hooks/useDerivatives';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';+import { formatCurrency, formatQuantity, formatDateTime } from '../../utils/formatters';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',+};++interface LiquidationsPanelProps {+ symbol?: string;+ showMyLiquidations?: boolean;+}++export function LiquidationsPanel({ symbol, showMyLiquidations = false }: LiquidationsPanelProps) {+ const { tradingMode } = useBrokerContext();+ const [viewMode, setViewMode] = useState<'market' | 'mine'>(showMyLiquidations ? 'mine' : 'market');++ const {+ liquidations: marketLiquidations,+ isLoading: marketLoading,+ isSupported: marketSupported,+ refresh: refreshMarket,+ } = useLiquidations(symbol);++ const {+ liquidations: myLiquidations,+ isLoading: myLoading,+ isSupported: mySupported,+ refresh: refreshMine,+ } = useMyLiquidations(symbol);++ const liquidations = viewMode === 'market' ? marketLiquidations : myLiquidations;+ const isLoading = viewMode === 'market' ? marketLoading : myLoading;+ const refresh = viewMode === 'market' ? refreshMarket : refreshMine;++ // Calculate totals+ const totalLiquidated = liquidations.reduce((sum, l) => sum + l.cost, 0);+ const longLiquidations = liquidations.filter((l) => l.side === 'sell'); // Liquidated longs become sells+ const shortLiquidations = liquidations.filter((l) => l.side === 'buy'); // Liquidated shorts become buys++ if (tradingMode === 'paper') {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ <AlertCircle size={20} color={FINCEPT.YELLOW} style={{ marginBottom: '8px' }} />+ <div>Liquidations not available in paper trading mode</div>+ </div>+ );+ }++ if (!marketSupported && !mySupported) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ Liquidation data not supported by this exchange+ </div>+ );+ }++ return (+ <div style={{ background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px', padding: '12px' }}>+ {/* Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Flame size={14} color={FINCEPT.RED} />+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>LIQUIDATIONS</span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <div style={{ display: 'flex', gap: '4px' }}>+ <button+ onClick={() => setViewMode('market')}+ style={{+ padding: '4px 8px',+ fontSize: '9px',+ backgroundColor: viewMode === 'market' ? FINCEPT.ORANGE : FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ color: viewMode === 'market' ? FINCEPT.WHITE : FINCEPT.GRAY,+ cursor: 'pointer',+ }}+ >+ MARKET+ </button>+ <button+ onClick={() => setViewMode('mine')}+ style={{+ padding: '4px 8px',+ fontSize: '9px',+ backgroundColor: viewMode === 'mine' ? FINCEPT.ORANGE : FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ color: viewMode === 'mine' ? FINCEPT.WHITE : FINCEPT.GRAY,+ cursor: 'pointer',+ }}+ >+ MY HISTORY+ </button>+ </div>+ <button+ onClick={refresh}+ disabled={isLoading}+ style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: '4px' }}+ >+ <RefreshCw size={12} color={FINCEPT.GRAY} style={{ animation: isLoading ? 'spin 1s linear infinite' : 'none' }} />+ </button>+ </div>+ </div>++ {/* Summary Stats */}+ {liquidations.length > 0 && viewMode === 'market' && (+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px', marginBottom: '12px' }}>+ <div style={{ padding: '10px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY }}>TOTAL</div>+ <div style={{ fontSize: '14px', fontWeight: 700, color: FINCEPT.RED, fontFamily: '"IBM Plex Mono", monospace' }}>+ {formatCurrency(totalLiquidated)}+ </div>+ </div>+ <div style={{ padding: '10px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY }}>LONGS REKT</div>+ <div style={{ fontSize: '14px', fontWeight: 700, color: FINCEPT.RED, fontFamily: '"IBM Plex Mono", monospace' }}>+ {longLiquidations.length}+ </div>+ </div>+ <div style={{ padding: '10px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY }}>SHORTS REKT</div>+ <div style={{ fontSize: '14px', fontWeight: 700, color: FINCEPT.GREEN, fontFamily: '"IBM Plex Mono", monospace' }}>+ {shortLiquidations.length}+ </div>+ </div>+ </div>+ )}++ {/* My Liquidations Warning */}+ {viewMode === 'mine' && myLiquidations.length > 0 && (+ <div style={{ padding: '10px', backgroundColor: `${FINCEPT.RED}20`, borderRadius: '4px', marginBottom: '12px', display: 'flex', alignItems: 'center', gap: '8px' }}>+ <AlertTriangle size={16} color={FINCEPT.RED} />+ <span style={{ fontSize: '10px', color: FINCEPT.RED }}>+ You have {myLiquidations.length} liquidation(s) in your history+ </span>+ </div>+ )}++ {/* Liquidations List */}+ <div style={{ maxHeight: '250px', overflowY: 'auto' }}>+ {isLoading && liquidations.length === 0 ? (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '10px' }}>+ Loading liquidations...+ </div>+ ) : liquidations.length === 0 ? (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '10px' }}>+ {viewMode === 'mine' ? 'No liquidations in your history' : 'No recent liquidations'}+ </div>+ ) : (+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '9px' }}>+ <thead>+ <tr style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <th style={{ padding: '6px', textAlign: 'left', color: FINCEPT.GRAY }}>TIME</th>+ <th style={{ padding: '6px', textAlign: 'left', color: FINCEPT.GRAY }}>SYMBOL</th>+ <th style={{ padding: '6px', textAlign: 'center', color: FINCEPT.GRAY }}>SIDE</th>+ <th style={{ padding: '6px', textAlign: 'right', color: FINCEPT.GRAY }}>PRICE</th>+ <th style={{ padding: '6px', textAlign: 'right', color: FINCEPT.GRAY }}>AMOUNT</th>+ <th style={{ padding: '6px', textAlign: 'right', color: FINCEPT.GRAY }}>VALUE</th>+ </tr>+ </thead>+ <tbody>+ {liquidations.slice(0, 20).map((liq, idx) => {+ const isLongLiq = liq.side === 'sell';+ return (+ <tr key={liq.id || idx} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}`, backgroundColor: idx % 2 === 0 ? FINCEPT.DARK_BG : 'transparent' }}>+ <td style={{ padding: '6px', color: FINCEPT.GRAY, fontSize: '8px' }}>+ {new Date(liq.timestamp).toLocaleTimeString()}+ </td>+ <td style={{ padding: '6px', color: FINCEPT.WHITE, fontWeight: 600 }}>+ {liq.symbol}+ </td>+ <td style={{ padding: '6px', textAlign: 'center' }}>+ <span style={{+ padding: '2px 6px',+ backgroundColor: isLongLiq ? `${FINCEPT.RED}20` : `${FINCEPT.GREEN}20`,+ color: isLongLiq ? FINCEPT.RED : FINCEPT.GREEN,+ fontSize: '8px',+ fontWeight: 700,+ borderRadius: '2px',+ }}>+ {isLongLiq ? 'LONG' : 'SHORT'}+ </span>+ </td>+ <td style={{ padding: '6px', textAlign: 'right', color: FINCEPT.WHITE, fontFamily: '"IBM Plex Mono", monospace' }}>+ {formatCurrency(liq.price)}+ </td>+ <td style={{ padding: '6px', textAlign: 'right', color: FINCEPT.WHITE, fontFamily: '"IBM Plex Mono", monospace' }}>+ {formatQuantity(liq.amount)}+ </td>+ <td style={{ padding: '6px', textAlign: 'right', color: FINCEPT.RED, fontFamily: '"IBM Plex Mono", monospace', fontWeight: 600 }}>+ {formatCurrency(liq.cost)}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ )}+ </div>++ <style>{`+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `}</style>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/DerivativesInfo/OpenInterestPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/DerivativesInfo/OpenInterestPanel.tsxnew file mode 100644index 000000000..cbebea855--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/DerivativesInfo/OpenInterestPanel.tsx@@ -0,0 +1,144 @@+/**+ * Open Interest Panel+ * Displays open interest data for futures/perpetuals+ */++import React from 'react';+import { Activity, RefreshCw, AlertCircle, TrendingUp, TrendingDown } from 'lucide-react';+import { useOpenInterest } from '../../hooks/useDerivatives';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';+import { formatVolume, formatCurrency } from '../../utils/formatters';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',+ PURPLE: '#9D4EDD',+};++interface OpenInterestPanelProps {+ symbol?: string;+}++export function OpenInterestPanel({ symbol }: OpenInterestPanelProps) {+ const { tradingMode } = useBrokerContext();+ const { openInterest, isLoading, error, isSupported, refresh } = useOpenInterest(symbol);++ if (tradingMode === 'paper') {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ <AlertCircle size={20} color={FINCEPT.YELLOW} style={{ marginBottom: '8px' }} />+ <div>Open interest not available in paper trading mode</div>+ </div>+ );+ }++ if (!isSupported) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ Open interest not supported by this exchange+ </div>+ );+ }++ if (!symbol) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ Select a symbol to view open interest+ </div>+ );+ }++ return (+ <div style={{ background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px', padding: '12px' }}>+ {/* Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Activity size={14} color={FINCEPT.PURPLE} />+ <span style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>OPEN INTEREST</span>+ </div>+ <button+ onClick={refresh}+ disabled={isLoading}+ style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: '4px' }}+ >+ <RefreshCw size={12} color={FINCEPT.GRAY} style={{ animation: isLoading ? 'spin 1s linear infinite' : 'none' }} />+ </button>+ </div>++ {error ? (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.RED, fontSize: '10px' }}>+ Failed to load open interest+ </div>+ ) : isLoading && !openInterest ? (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '10px' }}>+ Loading...+ </div>+ ) : openInterest ? (+ <div>+ {/* Main OI Display */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '12px' }}>+ {/* Amount */}+ <div style={{ padding: '12px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px' }}>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '6px' }}>+ OI AMOUNT+ </div>+ <div style={{ fontSize: '18px', fontWeight: 700, fontFamily: '"IBM Plex Mono", monospace', color: FINCEPT.PURPLE }}>+ {formatVolume(openInterest.openInterestAmount)}+ </div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ contracts+ </div>+ </div>++ {/* Value */}+ <div style={{ padding: '12px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px' }}>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '6px' }}>+ OI VALUE+ </div>+ <div style={{ fontSize: '18px', fontWeight: 700, fontFamily: '"IBM Plex Mono", monospace', color: FINCEPT.CYAN }}>+ {formatCurrency(openInterest.openInterestValue)}+ </div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ USD equivalent+ </div>+ </div>+ </div>++ {/* Last Updated */}+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, textAlign: 'center' }}>+ Last updated: {new Date(openInterest.timestamp).toLocaleTimeString()}+ </div>++ {/* OI Interpretation */}+ <div style={{ marginTop: '12px', padding: '10px', backgroundColor: `${FINCEPT.PURPLE}15`, borderRadius: '4px', fontSize: '10px', color: FINCEPT.GRAY }}>+ <strong style={{ color: FINCEPT.PURPLE }}>What is Open Interest?</strong>+ <div style={{ marginTop: '4px' }}>+ Total number of outstanding derivative contracts that have not been settled.+ Rising OI with price = Strong trend. Falling OI = Trend weakening.+ </div>+ </div>+ </div>+ ) : (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '10px' }}>+ No open interest data available+ </div>+ )}++ <style>{`+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `}</style>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/DerivativesInfo/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/core/DerivativesInfo/index.tsnew file mode 100644index 000000000..879db719a--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/DerivativesInfo/index.ts@@ -0,0 +1,4 @@+export { FundingRatesPanel } from './FundingRatesPanel';+export { OpenInterestPanel } from './OpenInterestPanel';+export { LiquidationsPanel } from './LiquidationsPanel';+export { BorrowRatesPanel } from './BorrowRatesPanel';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/ExchangeStatus/ExchangeStatusIndicator.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/ExchangeStatus/ExchangeStatusIndicator.tsxnew file mode 100644index 000000000..e41febf18--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/ExchangeStatus/ExchangeStatusIndicator.tsx@@ -0,0 +1,329 @@+/**+ * Exchange Status Indicator+ * Compact component showing exchange operational status+ * Uses fetchStatus and fetchTime for real-time monitoring+ */++import React from 'react';+import { Activity, AlertTriangle, XCircle, Clock, Wifi, RefreshCw } from 'lucide-react';+import { useExchangeStatus, useExchangeTime } from '../../hooks/useExchangeStatus';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',+};++interface ExchangeStatusIndicatorProps {+ compact?: boolean;+ showLatency?: boolean;+}++export function ExchangeStatusIndicator({ compact = false, showLatency = true }: ExchangeStatusIndicatorProps) {+ const { activeBroker, tradingMode } = useBrokerContext();+ const { status, isLoading, refresh } = useExchangeStatus(true, 30000);+ const { latency, serverTime } = useExchangeTime();++ const getStatusConfig = () => {+ if (!status) {+ return {+ color: FINCEPT.GRAY,+ bgColor: `${FINCEPT.GRAY}20`,+ icon: Activity,+ label: 'Unknown',+ pulse: false,+ };+ }++ switch (status.status) {+ case 'ok':+ return {+ color: FINCEPT.GREEN,+ bgColor: `${FINCEPT.GREEN}20`,+ icon: Activity,+ label: 'Operational',+ pulse: true,+ };+ case 'maintenance':+ return {+ color: FINCEPT.YELLOW,+ bgColor: `${FINCEPT.YELLOW}20`,+ icon: Clock,+ label: 'Maintenance',+ pulse: false,+ };+ case 'degraded':+ return {+ color: FINCEPT.ORANGE,+ bgColor: `${FINCEPT.ORANGE}20`,+ icon: AlertTriangle,+ label: 'Degraded',+ pulse: true,+ };+ case 'offline':+ return {+ color: FINCEPT.RED,+ bgColor: `${FINCEPT.RED}20`,+ icon: XCircle,+ label: 'Offline',+ pulse: false,+ };+ default:+ return {+ color: FINCEPT.GRAY,+ bgColor: `${FINCEPT.GRAY}20`,+ icon: Activity,+ label: 'Unknown',+ pulse: false,+ };+ }+ };++ const config = getStatusConfig();+ const Icon = config.icon;++ const formatLatency = (ms: number | null) => {+ if (ms === null) return '--';+ if (ms < 100) return `${ms}ms`;+ if (ms < 1000) return `${ms}ms`;+ return `${(ms / 1000).toFixed(1)}s`;+ };++ const getLatencyColor = (ms: number | null) => {+ if (ms === null) return FINCEPT.GRAY;+ if (ms < 100) return FINCEPT.GREEN;+ if (ms < 300) return FINCEPT.YELLOW;+ if (ms < 1000) return FINCEPT.ORANGE;+ return FINCEPT.RED;+ };++ const exchangeName = tradingMode === 'paper'+ ? 'Paper Trading'+ : (activeBroker || 'Exchange').charAt(0).toUpperCase() + (activeBroker || 'exchange').slice(1);++ if (compact) {+ return (+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ padding: '4px 8px',+ backgroundColor: config.bgColor,+ borderRadius: '4px',+ cursor: 'pointer',+ }}+ onClick={refresh}+ title={`${exchangeName}: ${config.label}${latency !== null ? ` | Latency: ${formatLatency(latency)}` : ''}`}+ >+ <div+ style={{+ width: '6px',+ height: '6px',+ borderRadius: '50%',+ backgroundColor: config.color,+ animation: config.pulse ? 'pulse 2s infinite' : 'none',+ }}+ />+ <span style={{ fontSize: '9px', color: config.color, fontWeight: 600 }}>+ {config.label.toUpperCase()}+ </span>+ {showLatency && latency !== null && (+ <span style={{ fontSize: '8px', color: getLatencyColor(latency), fontFamily: '"IBM Plex Mono", monospace' }}>+ {formatLatency(latency)}+ </span>+ )}+ </div>+ );+ }++ return (+ <div+ style={{+ background: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ padding: '12px',+ }}+ >+ {/* Header */}+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ marginBottom: '12px',+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Icon size={14} color={config.color} />+ <span style={{ fontSize: '11px', color: FINCEPT.WHITE, fontWeight: 600 }}>+ {exchangeName} Status+ </span>+ </div>+ <button+ onClick={refresh}+ disabled={isLoading}+ style={{+ background: 'transparent',+ border: 'none',+ cursor: isLoading ? 'wait' : 'pointer',+ padding: '4px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ }}+ title="Refresh status"+ >+ <RefreshCw+ size={12}+ color={FINCEPT.GRAY}+ style={{+ animation: isLoading ? 'spin 1s linear infinite' : 'none',+ }}+ />+ </button>+ </div>++ {/* Status Row */}+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ padding: '10px',+ backgroundColor: config.bgColor,+ borderRadius: '4px',+ marginBottom: '10px',+ }}+ >+ <div+ style={{+ width: '10px',+ height: '10px',+ borderRadius: '50%',+ backgroundColor: config.color,+ boxShadow: config.pulse ? `0 0 8px ${config.color}` : 'none',+ animation: config.pulse ? 'pulse 2s infinite' : 'none',+ }}+ />+ <div>+ <div style={{ fontSize: '12px', color: config.color, fontWeight: 700 }}>+ {config.label}+ </div>+ {status?.eta && (+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ ETA: {status.eta}+ </div>+ )}+ </div>+ </div>++ {/* Stats Row */}+ <div style={{ display: 'flex', gap: '12px' }}>+ {/* Latency */}+ {showLatency && (+ <div+ style={{+ flex: 1,+ background: FINCEPT.DARK_BG,+ borderRadius: '4px',+ padding: '8px',+ textAlign: 'center',+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px', marginBottom: '4px' }}>+ <Wifi size={10} color={FINCEPT.GRAY} />+ <span style={{ fontSize: '8px', color: FINCEPT.GRAY, fontWeight: 600 }}>LATENCY</span>+ </div>+ <div+ style={{+ fontSize: '14px',+ fontWeight: 700,+ fontFamily: '"IBM Plex Mono", monospace',+ color: getLatencyColor(latency),+ }}+ >+ {formatLatency(latency)}+ </div>+ </div>+ )}++ {/* Last Updated */}+ <div+ style={{+ flex: 1,+ background: FINCEPT.DARK_BG,+ borderRadius: '4px',+ padding: '8px',+ textAlign: 'center',+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px', marginBottom: '4px' }}>+ <Clock size={10} color={FINCEPT.GRAY} />+ <span style={{ fontSize: '8px', color: FINCEPT.GRAY, fontWeight: 600 }}>UPDATED</span>+ </div>+ <div+ style={{+ fontSize: '10px',+ fontWeight: 600,+ fontFamily: '"IBM Plex Mono", monospace',+ color: FINCEPT.WHITE,+ }}+ >+ {status?.updated ? new Date(status.updated).toLocaleTimeString() : '--'}+ </div>+ </div>++ {/* Server Time */}+ {serverTime && (+ <div+ style={{+ flex: 1,+ background: FINCEPT.DARK_BG,+ borderRadius: '4px',+ padding: '8px',+ textAlign: 'center',+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px', marginBottom: '4px' }}>+ <Activity size={10} color={FINCEPT.GRAY} />+ <span style={{ fontSize: '8px', color: FINCEPT.GRAY, fontWeight: 600 }}>SERVER</span>+ </div>+ <div+ style={{+ fontSize: '10px',+ fontWeight: 600,+ fontFamily: '"IBM Plex Mono", monospace',+ color: FINCEPT.CYAN,+ }}+ >+ {new Date(serverTime).toLocaleTimeString()}+ </div>+ </div>+ )}+ </div>++ {/* CSS for animations */}+ <style>{`+ @keyframes pulse {+ 0%, 100% { opacity: 1; }+ 50% { opacity: 0.5; }+ }+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `}</style>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/ExchangeStatus/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/core/ExchangeStatus/index.tsnew file mode 100644index 000000000..3d78804ea--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/ExchangeStatus/index.ts@@ -0,0 +1 @@+export { ExchangeStatusIndicator } from './ExchangeStatusIndicator';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/FundingManager/DepositPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/FundingManager/DepositPanel.tsxnew file mode 100644index 000000000..61a813950--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/FundingManager/DepositPanel.tsx@@ -0,0 +1,378 @@+/**+ * Deposit Panel+ * Shows deposit address and QR code for receiving crypto+ */++import React, { useState } from 'react';+import { Copy, Check, RefreshCw, AlertCircle, QrCode } from 'lucide-react';+import { useDepositAddress } from '../../hooks/useFunding';+import { useBalance } from '../../hooks/useAccountInfo';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',+};++// Common networks for deposits+const NETWORKS: Record<string, string[]> = {+ BTC: ['BTC', 'BEP20', 'BEP2'],+ ETH: ['ERC20', 'BEP20', 'ARBITRUM', 'OPTIMISM', 'POLYGON'],+ USDT: ['ERC20', 'TRC20', 'BEP20', 'SOL', 'POLYGON'],+ USDC: ['ERC20', 'SOL', 'BEP20', 'POLYGON', 'ARBITRUM'],+ SOL: ['SOL'],+ XRP: ['XRP'],+ DOGE: ['DOGE', 'BEP20'],+ ADA: ['ADA', 'BEP20'],+};++export function DepositPanel() {+ const { tradingMode, activeBroker } = useBrokerContext();+ const { balances } = useBalance(false);+ const [selectedCurrency, setSelectedCurrency] = useState<string>('');+ const [selectedNetwork, setSelectedNetwork] = useState<string>('');+ const [copied, setCopied] = useState<'address' | 'tag' | null>(null);++ const { address, isLoading, error, isSupported, refresh } = useDepositAddress(+ selectedCurrency || undefined,+ selectedNetwork || undefined+ );++ // Get unique currencies from balances+ const availableCurrencies = Array.from(new Set(balances.map((b) => b.currency))).sort();++ const handleCurrencyChange = (currency: string) => {+ setSelectedCurrency(currency);+ setSelectedNetwork(''); // Reset network when currency changes+ };++ const copyToClipboard = (text: string, type: 'address' | 'tag') => {+ navigator.clipboard.writeText(text);+ setCopied(type);+ setTimeout(() => setCopied(null), 2000);+ };++ if (tradingMode === 'paper') {+ return (+ <div+ style={{+ padding: '40px',+ textAlign: 'center',+ color: FINCEPT.GRAY,+ background: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ }}+ >+ <AlertCircle size={32} color={FINCEPT.YELLOW} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '12px', marginBottom: '8px' }}>+ Deposits not available in paper trading mode+ </div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>+ Connect a live exchange to deposit funds+ </div>+ </div>+ );+ }++ return (+ <div+ style={{+ background: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ padding: '16px',+ }}+ >+ {/* Header */}+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ marginBottom: '16px',+ paddingBottom: '12px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}+ >+ <div style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>+ Deposit to {activeBroker?.charAt(0).toUpperCase()}{activeBroker?.slice(1)}+ </div>+ </div>++ {/* Currency Selection */}+ <div style={{ marginBottom: '16px' }}>+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '6px' }}>+ SELECT CURRENCY+ </label>+ <select+ value={selectedCurrency}+ onChange={(e) => handleCurrencyChange(e.target.value)}+ style={{+ width: '100%',+ padding: '10px 12px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '12px',+ cursor: 'pointer',+ }}+ >+ <option value="">-- Select Currency --</option>+ {availableCurrencies.map((currency) => (+ <option key={currency} value={currency}>+ {currency}+ </option>+ ))}+ {/* Common currencies if not in balance */}+ {!availableCurrencies.includes('BTC') && <option value="BTC">BTC</option>}+ {!availableCurrencies.includes('ETH') && <option value="ETH">ETH</option>}+ {!availableCurrencies.includes('USDT') && <option value="USDT">USDT</option>}+ {!availableCurrencies.includes('USDC') && <option value="USDC">USDC</option>}+ </select>+ </div>++ {/* Network Selection */}+ {selectedCurrency && NETWORKS[selectedCurrency] && (+ <div style={{ marginBottom: '16px' }}>+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '6px' }}>+ SELECT NETWORK+ </label>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>+ {NETWORKS[selectedCurrency].map((network) => (+ <button+ key={network}+ onClick={() => setSelectedNetwork(network)}+ style={{+ padding: '6px 12px',+ backgroundColor: selectedNetwork === network ? FINCEPT.ORANGE : FINCEPT.DARK_BG,+ border: `1px solid ${selectedNetwork === network ? FINCEPT.ORANGE : FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: selectedNetwork === network ? FINCEPT.WHITE : FINCEPT.GRAY,+ fontSize: '10px',+ cursor: 'pointer',+ fontWeight: selectedNetwork === network ? 700 : 400,+ }}+ >+ {network}+ </button>+ ))}+ </div>+ </div>+ )}++ {/* Deposit Address Display */}+ {selectedCurrency && (+ <div style={{ marginTop: '20px' }}>+ {isLoading ? (+ <div+ style={{+ padding: '40px',+ textAlign: 'center',+ color: FINCEPT.GRAY,+ }}+ >+ <RefreshCw+ size={24}+ color={FINCEPT.ORANGE}+ style={{ animation: 'spin 1s linear infinite', marginBottom: '12px' }}+ />+ <div style={{ fontSize: '11px' }}>Loading deposit address...</div>+ </div>+ ) : error || !address ? (+ <div+ style={{+ padding: '30px',+ textAlign: 'center',+ backgroundColor: `${FINCEPT.RED}10`,+ borderRadius: '4px',+ }}+ >+ <AlertCircle size={24} color={FINCEPT.RED} style={{ marginBottom: '8px' }} />+ <div style={{ fontSize: '11px', color: FINCEPT.RED, marginBottom: '8px' }}>+ {error?.message || 'Failed to generate deposit address'}+ </div>+ <button+ onClick={refresh}+ style={{+ padding: '6px 12px',+ backgroundColor: FINCEPT.ORANGE,+ border: 'none',+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '10px',+ cursor: 'pointer',+ }}+ >+ Try Again+ </button>+ </div>+ ) : (+ <div>+ {/* Address Box */}+ <div+ style={{+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ padding: '16px',+ marginBottom: '12px',+ }}+ >+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '8px' }}>+ {selectedCurrency} DEPOSIT ADDRESS+ {address.network && ` (${address.network})`}+ </div>+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ }}+ >+ <div+ style={{+ flex: 1,+ padding: '12px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderRadius: '4px',+ fontFamily: '"IBM Plex Mono", monospace',+ fontSize: '11px',+ color: FINCEPT.CYAN,+ wordBreak: 'break-all',+ }}+ >+ {address.address}+ </div>+ <button+ onClick={() => copyToClipboard(address.address, 'address')}+ style={{+ padding: '12px',+ backgroundColor: copied === 'address' ? FINCEPT.GREEN : FINCEPT.ORANGE,+ border: 'none',+ borderRadius: '4px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ }}+ title="Copy address"+ >+ {copied === 'address' ? (+ <Check size={16} color={FINCEPT.WHITE} />+ ) : (+ <Copy size={16} color={FINCEPT.WHITE} />+ )}+ </button>+ </div>+ </div>++ {/* Tag/Memo (if applicable) */}+ {address.tag && (+ <div+ style={{+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.YELLOW}`,+ borderRadius: '4px',+ padding: '16px',+ marginBottom: '12px',+ }}+ >+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ marginBottom: '8px',+ }}+ >+ <AlertCircle size={12} color={FINCEPT.YELLOW} />+ <span style={{ fontSize: '9px', color: FINCEPT.YELLOW, fontWeight: 700 }}>+ MEMO/TAG REQUIRED+ </span>+ </div>+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ }}+ >+ <div+ style={{+ flex: 1,+ padding: '12px',+ backgroundColor: FINCEPT.PANEL_BG,+ borderRadius: '4px',+ fontFamily: '"IBM Plex Mono", monospace',+ fontSize: '11px',+ color: FINCEPT.YELLOW,+ }}+ >+ {address.tag}+ </div>+ <button+ onClick={() => copyToClipboard(address.tag!, 'tag')}+ style={{+ padding: '12px',+ backgroundColor: copied === 'tag' ? FINCEPT.GREEN : FINCEPT.YELLOW,+ border: 'none',+ borderRadius: '4px',+ cursor: 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ }}+ title="Copy memo/tag"+ >+ {copied === 'tag' ? (+ <Check size={16} color={FINCEPT.DARK_BG} />+ ) : (+ <Copy size={16} color={FINCEPT.DARK_BG} />+ )}+ </button>+ </div>+ <div style={{ fontSize: '9px', color: FINCEPT.YELLOW, marginTop: '8px' }}>+ Always include this memo/tag when depositing or your funds may be lost!+ </div>+ </div>+ )}++ {/* Warning */}+ <div+ style={{+ backgroundColor: `${FINCEPT.ORANGE}10`,+ borderRadius: '4px',+ padding: '12px',+ fontSize: '10px',+ color: FINCEPT.ORANGE,+ }}+ >+ <strong>Important:</strong> Only send {selectedCurrency}+ {address.network ? ` on the ${address.network} network` : ''} to this address. Sending+ other assets may result in permanent loss.+ </div>+ </div>+ )}+ </div>+ )}++ <style>{`+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `}</style>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/FundingManager/TransactionsTable.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/FundingManager/TransactionsTable.tsxnew file mode 100644index 000000000..b75a6ed88--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/FundingManager/TransactionsTable.tsx@@ -0,0 +1,316 @@+/**+ * Transactions Table+ * Displays deposit and withdrawal history+ */++import React, { useState } from 'react';+import { ArrowDownLeft, ArrowUpRight, ExternalLink, Copy, Check, RefreshCw } from 'lucide-react';+import { useTransactions } from '../../hooks/useFunding';+import { formatDateTime } from '../../utils/formatters';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',+ BLUE: '#0088FF',+};++interface TransactionsTableProps {+ currency?: string;+ limit?: number;+ type?: 'all' | 'deposits' | 'withdrawals';+}++export function TransactionsTable({ currency, limit = 50, type = 'all' }: TransactionsTableProps) {+ const { transactions, deposits, withdrawals, isLoading, error, isSupported, refresh } = useTransactions(currency, limit);+ const [copiedId, setCopiedId] = useState<string | null>(null);++ // Filter based on type+ const displayedTransactions = type === 'deposits' ? deposits : type === 'withdrawals' ? withdrawals : transactions;++ const copyToClipboard = (text: string, id: string) => {+ navigator.clipboard.writeText(text);+ setCopiedId(id);+ setTimeout(() => setCopiedId(null), 2000);+ };++ const getStatusConfig = (status: string) => {+ switch (status) {+ case 'ok':+ return { color: FINCEPT.GREEN, label: 'Completed' };+ case 'pending':+ return { color: FINCEPT.YELLOW, label: 'Pending' };+ case 'failed':+ return { color: FINCEPT.RED, label: 'Failed' };+ case 'canceled':+ return { color: FINCEPT.GRAY, label: 'Canceled' };+ default:+ return { color: FINCEPT.GRAY, label: status };+ }+ };++ if (!isSupported) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ Transaction history not available in paper trading mode+ </div>+ );+ }++ if (error) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.RED, fontSize: '11px' }}>+ Failed to load transactions+ <button+ onClick={refresh}+ style={{+ marginLeft: '10px',+ padding: '4px 8px',+ backgroundColor: FINCEPT.ORANGE,+ border: 'none',+ color: FINCEPT.WHITE,+ fontSize: '9px',+ cursor: 'pointer',+ }}+ >+ RETRY+ </button>+ </div>+ );+ }++ if (isLoading && displayedTransactions.length === 0) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ Loading transaction history...+ </div>+ );+ }++ if (displayedTransactions.length === 0) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ No transactions found+ </div>+ );+ }++ return (+ <div style={{ width: '100%', height: '100%', overflowX: 'auto', overflowY: 'auto' }}>+ {/* Refresh Button */}+ <div style={{ padding: '8px 12px', display: 'flex', justifyContent: 'flex-end' }}>+ <button+ onClick={refresh}+ disabled={isLoading}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ padding: '4px 8px',+ backgroundColor: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ color: FINCEPT.GRAY,+ fontSize: '9px',+ cursor: isLoading ? 'wait' : 'pointer',+ borderRadius: '2px',+ }}+ >+ <RefreshCw size={10} style={{ animation: isLoading ? 'spin 1s linear infinite' : 'none' }} />+ REFRESH+ </button>+ </div>++ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>+ <thead style={{ position: 'sticky', top: 0, zIndex: 1 }}>+ <tr style={{ backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: FINCEPT.GRAY, fontWeight: 700 }}>TYPE</th>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: FINCEPT.GRAY, fontWeight: 700 }}>TIME</th>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: FINCEPT.GRAY, fontWeight: 700 }}>CURRENCY</th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: FINCEPT.GRAY, fontWeight: 700 }}>AMOUNT</th>+ <th style={{ padding: '8px 10px', textAlign: 'center', color: FINCEPT.GRAY, fontWeight: 700 }}>STATUS</th>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: FINCEPT.GRAY, fontWeight: 700 }}>ADDRESS</th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: FINCEPT.GRAY, fontWeight: 700 }}>FEE</th>+ <th style={{ padding: '8px 10px', textAlign: 'center', color: FINCEPT.GRAY, fontWeight: 700 }}>TXID</th>+ </tr>+ </thead>+ <tbody>+ {displayedTransactions.map((tx, index) => {+ const statusConfig = getStatusConfig(tx.status);+ const isDeposit = tx.type === 'deposit';++ return (+ <tr+ key={tx.id}+ style={{+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ backgroundColor: index % 2 === 0 ? FINCEPT.DARK_BG : FINCEPT.PANEL_BG,+ }}+ >+ {/* Type */}+ <td style={{ padding: '10px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ {isDeposit ? (+ <ArrowDownLeft size={14} color={FINCEPT.GREEN} />+ ) : (+ <ArrowUpRight size={14} color={FINCEPT.RED} />+ )}+ <span+ style={{+ fontSize: '9px',+ fontWeight: 700,+ color: isDeposit ? FINCEPT.GREEN : FINCEPT.RED,+ }}+ >+ {tx.type.toUpperCase()}+ </span>+ </div>+ </td>++ {/* Time */}+ <td style={{ padding: '10px', color: FINCEPT.GRAY, fontSize: '9px' }}>+ {formatDateTime(tx.timestamp)}+ </td>++ {/* Currency */}+ <td style={{ padding: '10px', color: FINCEPT.WHITE, fontWeight: 600 }}>+ {tx.currency}+ {tx.network && (+ <span style={{ fontSize: '8px', color: FINCEPT.GRAY, marginLeft: '4px' }}>+ ({tx.network})+ </span>+ )}+ </td>++ {/* Amount */}+ <td+ style={{+ padding: '10px',+ textAlign: 'right',+ color: isDeposit ? FINCEPT.GREEN : FINCEPT.RED,+ fontFamily: '"IBM Plex Mono", monospace',+ fontWeight: 600,+ }}+ >+ {isDeposit ? '+' : '-'}+ {tx.amount.toFixed(8)}+ </td>++ {/* Status */}+ <td style={{ padding: '10px', textAlign: 'center' }}>+ <span+ style={{+ padding: '2px 8px',+ backgroundColor: `${statusConfig.color}20`,+ color: statusConfig.color,+ fontSize: '8px',+ fontWeight: 700,+ borderRadius: '2px',+ }}+ >+ {statusConfig.label.toUpperCase()}+ </span>+ </td>++ {/* Address */}+ <td style={{ padding: '10px' }}>+ {tx.address ? (+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span+ style={{+ fontSize: '9px',+ color: FINCEPT.CYAN,+ fontFamily: '"IBM Plex Mono", monospace',+ maxWidth: '120px',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}+ title={tx.address}+ >+ {tx.address.slice(0, 8)}...{tx.address.slice(-6)}+ </span>+ <button+ onClick={() => copyToClipboard(tx.address!, `addr-${tx.id}`)}+ style={{+ background: 'transparent',+ border: 'none',+ cursor: 'pointer',+ padding: '2px',+ }}+ title="Copy address"+ >+ {copiedId === `addr-${tx.id}` ? (+ <Check size={10} color={FINCEPT.GREEN} />+ ) : (+ <Copy size={10} color={FINCEPT.GRAY} />+ )}+ </button>+ </div>+ ) : (+ <span style={{ color: FINCEPT.GRAY }}>--</span>+ )}+ </td>++ {/* Fee */}+ <td style={{ padding: '10px', textAlign: 'right', color: FINCEPT.GRAY, fontSize: '9px' }}>+ {tx.fee ? `${tx.fee.cost.toFixed(8)} ${tx.fee.currency}` : '--'}+ </td>++ {/* TXID */}+ <td style={{ padding: '10px', textAlign: 'center' }}>+ {tx.txid ? (+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px' }}>+ <span+ style={{+ fontSize: '8px',+ color: FINCEPT.BLUE,+ fontFamily: '"IBM Plex Mono", monospace',+ }}+ title={tx.txid}+ >+ {tx.txid.slice(0, 6)}...+ </span>+ <button+ onClick={() => copyToClipboard(tx.txid!, `txid-${tx.id}`)}+ style={{+ background: 'transparent',+ border: 'none',+ cursor: 'pointer',+ padding: '2px',+ }}+ title="Copy transaction ID"+ >+ {copiedId === `txid-${tx.id}` ? (+ <Check size={10} color={FINCEPT.GREEN} />+ ) : (+ <Copy size={10} color={FINCEPT.GRAY} />+ )}+ </button>+ </div>+ ) : (+ <span style={{ color: FINCEPT.GRAY }}>--</span>+ )}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>++ <style>{`+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `}</style>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/FundingManager/WithdrawPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/FundingManager/WithdrawPanel.tsxnew file mode 100644index 000000000..919b6e4e2--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/FundingManager/WithdrawPanel.tsx@@ -0,0 +1,520 @@+/**+ * Withdraw Panel+ * Form for initiating crypto withdrawals+ */++import React, { useState, useEffect } from 'react';+import { Send, AlertCircle, AlertTriangle, Check, Loader2 } from 'lucide-react';+import { useWithdraw } from '../../hooks/useFunding';+import { useBalance } from '../../hooks/useAccountInfo';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',+};++// Common networks for withdrawals+const NETWORKS: Record<string, string[]> = {+ BTC: ['BTC', 'BEP20', 'BEP2'],+ ETH: ['ERC20', 'BEP20', 'ARBITRUM', 'OPTIMISM', 'POLYGON'],+ USDT: ['ERC20', 'TRC20', 'BEP20', 'SOL', 'POLYGON'],+ USDC: ['ERC20', 'SOL', 'BEP20', 'POLYGON', 'ARBITRUM'],+ SOL: ['SOL'],+ XRP: ['XRP'],+ DOGE: ['DOGE', 'BEP20'],+ ADA: ['ADA', 'BEP20'],+};++export function WithdrawPanel() {+ const { tradingMode, activeBroker } = useBrokerContext();+ const { balances } = useBalance(false);+ const { withdraw, isLoading, error, lastResult, isSupported } = useWithdraw();++ const [selectedCurrency, setSelectedCurrency] = useState<string>('');+ const [selectedNetwork, setSelectedNetwork] = useState<string>('');+ const [amount, setAmount] = useState<string>('');+ const [address, setAddress] = useState<string>('');+ const [tag, setTag] = useState<string>('');+ const [showConfirm, setShowConfirm] = useState(false);+ const [success, setSuccess] = useState(false);++ // Get balance for selected currency+ const selectedBalance = balances.find((b) => b.currency === selectedCurrency);+ const availableBalance = selectedBalance?.free || 0;++ // Reset form on currency change+ useEffect(() => {+ setSelectedNetwork('');+ setAmount('');+ setAddress('');+ setTag('');+ setShowConfirm(false);+ setSuccess(false);+ }, [selectedCurrency]);++ // Check if tag/memo is required+ const requiresTag = ['XRP', 'XLM', 'EOS', 'ATOM', 'BNB'].includes(selectedCurrency);++ const handleAmountChange = (value: string) => {+ // Only allow numbers and decimal+ if (/^\d*\.?\d*$/.test(value)) {+ setAmount(value);+ }+ };++ const handleSetMax = () => {+ setAmount(availableBalance.toString());+ };++ const handleSetPercent = (percent: number) => {+ setAmount((availableBalance * percent).toFixed(8));+ };++ const isValidForm = () => {+ if (!selectedCurrency) return false;+ if (!amount || parseFloat(amount) <= 0) return false;+ if (parseFloat(amount) > availableBalance) return false;+ if (!address || address.length < 10) return false;+ if (requiresTag && !tag) return false;+ return true;+ };++ const handleWithdraw = async () => {+ if (!isValidForm()) return;++ const result = await withdraw({+ code: selectedCurrency,+ amount: parseFloat(amount),+ address,+ tag: tag || undefined,+ network: selectedNetwork || undefined,+ });++ if (result) {+ setSuccess(true);+ // Reset form after successful withdrawal+ setTimeout(() => {+ setAmount('');+ setAddress('');+ setTag('');+ setShowConfirm(false);+ setSuccess(false);+ }, 3000);+ }+ };++ if (tradingMode === 'paper') {+ return (+ <div+ style={{+ padding: '40px',+ textAlign: 'center',+ color: FINCEPT.GRAY,+ background: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ }}+ >+ <AlertCircle size={32} color={FINCEPT.YELLOW} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '12px', marginBottom: '8px' }}>+ Withdrawals not available in paper trading mode+ </div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>+ Connect a live exchange to withdraw funds+ </div>+ </div>+ );+ }++ return (+ <div+ style={{+ background: FINCEPT.PANEL_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ padding: '16px',+ }}+ >+ {/* Header */}+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ marginBottom: '16px',+ paddingBottom: '12px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}+ >+ <div style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>+ Withdraw from {activeBroker?.charAt(0).toUpperCase()}{activeBroker?.slice(1)}+ </div>+ </div>++ {/* Success Message */}+ {success && (+ <div+ style={{+ padding: '16px',+ backgroundColor: `${FINCEPT.GREEN}20`,+ borderRadius: '4px',+ marginBottom: '16px',+ display: 'flex',+ alignItems: 'center',+ gap: '12px',+ }}+ >+ <Check size={20} color={FINCEPT.GREEN} />+ <div>+ <div style={{ fontSize: '12px', color: FINCEPT.GREEN, fontWeight: 600 }}>+ Withdrawal Submitted+ </div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>+ Your withdrawal is being processed+ </div>+ </div>+ </div>+ )}++ {/* Error Message */}+ {error && !success && (+ <div+ style={{+ padding: '12px',+ backgroundColor: `${FINCEPT.RED}20`,+ borderRadius: '4px',+ marginBottom: '16px',+ fontSize: '11px',+ color: FINCEPT.RED,+ }}+ >+ {error.message}+ </div>+ )}++ {/* Currency Selection */}+ <div style={{ marginBottom: '16px' }}>+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '6px' }}>+ SELECT CURRENCY+ </label>+ <select+ value={selectedCurrency}+ onChange={(e) => setSelectedCurrency(e.target.value)}+ style={{+ width: '100%',+ padding: '10px 12px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '12px',+ cursor: 'pointer',+ }}+ >+ <option value="">-- Select Currency --</option>+ {balances+ .filter((b) => b.free > 0)+ .map((b) => (+ <option key={b.currency} value={b.currency}>+ {b.currency} (Available: {b.free.toFixed(8)})+ </option>+ ))}+ </select>+ </div>++ {selectedCurrency && (+ <>+ {/* Network Selection */}+ {NETWORKS[selectedCurrency] && (+ <div style={{ marginBottom: '16px' }}>+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '6px' }}>+ SELECT NETWORK+ </label>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>+ {NETWORKS[selectedCurrency].map((network) => (+ <button+ key={network}+ onClick={() => setSelectedNetwork(network)}+ style={{+ padding: '6px 12px',+ backgroundColor: selectedNetwork === network ? FINCEPT.ORANGE : FINCEPT.DARK_BG,+ border: `1px solid ${selectedNetwork === network ? FINCEPT.ORANGE : FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: selectedNetwork === network ? FINCEPT.WHITE : FINCEPT.GRAY,+ fontSize: '10px',+ cursor: 'pointer',+ fontWeight: selectedNetwork === network ? 700 : 400,+ }}+ >+ {network}+ </button>+ ))}+ </div>+ </div>+ )}++ {/* Amount Input */}+ <div style={{ marginBottom: '16px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>+ <label style={{ fontSize: '9px', color: FINCEPT.GRAY }}>AMOUNT</label>+ <span style={{ fontSize: '9px', color: FINCEPT.CYAN }}>+ Available: {availableBalance.toFixed(8)} {selectedCurrency}+ </span>+ </div>+ <div style={{ display: 'flex', gap: '8px' }}>+ <input+ type="text"+ value={amount}+ onChange={(e) => handleAmountChange(e.target.value)}+ placeholder="0.00000000"+ style={{+ flex: 1,+ padding: '10px 12px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '14px',+ fontFamily: '"IBM Plex Mono", monospace',+ }}+ />+ <button+ onClick={handleSetMax}+ style={{+ padding: '10px 16px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.ORANGE,+ fontSize: '10px',+ fontWeight: 700,+ cursor: 'pointer',+ }}+ >+ MAX+ </button>+ </div>+ <div style={{ display: 'flex', gap: '8px', marginTop: '8px' }}>+ {[0.25, 0.5, 0.75].map((percent) => (+ <button+ key={percent}+ onClick={() => handleSetPercent(percent)}+ style={{+ padding: '4px 8px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '2px',+ color: FINCEPT.GRAY,+ fontSize: '9px',+ cursor: 'pointer',+ }}+ >+ {percent * 100}%+ </button>+ ))}+ </div>+ </div>++ {/* Address Input */}+ <div style={{ marginBottom: '16px' }}>+ <label style={{ display: 'block', fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '6px' }}>+ WITHDRAWAL ADDRESS+ </label>+ <input+ type="text"+ value={address}+ onChange={(e) => setAddress(e.target.value)}+ placeholder="Enter destination address"+ style={{+ width: '100%',+ padding: '10px 12px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '12px',+ fontFamily: '"IBM Plex Mono", monospace',+ }}+ />+ </div>++ {/* Tag/Memo Input (if required) */}+ {requiresTag && (+ <div style={{ marginBottom: '16px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>+ <AlertTriangle size={10} color={FINCEPT.YELLOW} />+ <label style={{ fontSize: '9px', color: FINCEPT.YELLOW }}>+ MEMO/TAG (REQUIRED)+ </label>+ </div>+ <input+ type="text"+ value={tag}+ onChange={(e) => setTag(e.target.value)}+ placeholder="Enter memo/tag"+ style={{+ width: '100%',+ padding: '10px 12px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.YELLOW}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '12px',+ fontFamily: '"IBM Plex Mono", monospace',+ }}+ />+ </div>+ )}++ {/* Confirmation Checkbox */}+ {!showConfirm ? (+ <button+ onClick={() => setShowConfirm(true)}+ disabled={!isValidForm()}+ style={{+ width: '100%',+ padding: '12px',+ backgroundColor: isValidForm() ? FINCEPT.ORANGE : FINCEPT.BORDER,+ border: 'none',+ borderRadius: '4px',+ color: isValidForm() ? FINCEPT.WHITE : FINCEPT.GRAY,+ fontSize: '12px',+ fontWeight: 700,+ cursor: isValidForm() ? 'pointer' : 'not-allowed',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '8px',+ }}+ >+ <Send size={14} />+ CONTINUE TO WITHDRAW+ </button>+ ) : (+ <div>+ {/* Confirmation Summary */}+ <div+ style={{+ backgroundColor: `${FINCEPT.YELLOW}10`,+ border: `1px solid ${FINCEPT.YELLOW}`,+ borderRadius: '4px',+ padding: '16px',+ marginBottom: '16px',+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>+ <AlertTriangle size={16} color={FINCEPT.YELLOW} />+ <span style={{ fontSize: '11px', color: FINCEPT.YELLOW, fontWeight: 700 }}>+ CONFIRM WITHDRAWAL+ </span>+ </div>++ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, marginBottom: '8px' }}>+ <strong>Amount:</strong>{' '}+ <span style={{ color: FINCEPT.WHITE }}>+ {amount} {selectedCurrency}+ </span>+ </div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, marginBottom: '8px' }}>+ <strong>To:</strong>{' '}+ <span style={{ color: FINCEPT.CYAN, wordBreak: 'break-all' }}>{address}</span>+ </div>+ {selectedNetwork && (+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, marginBottom: '8px' }}>+ <strong>Network:</strong> <span style={{ color: FINCEPT.WHITE }}>{selectedNetwork}</span>+ </div>+ )}+ {tag && (+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>+ <strong>Memo/Tag:</strong> <span style={{ color: FINCEPT.YELLOW }}>{tag}</span>+ </div>+ )}+ </div>++ <div style={{ display: 'flex', gap: '12px' }}>+ <button+ onClick={() => setShowConfirm(false)}+ style={{+ flex: 1,+ padding: '12px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.GRAY,+ fontSize: '11px',+ cursor: 'pointer',+ }}+ >+ CANCEL+ </button>+ <button+ onClick={handleWithdraw}+ disabled={isLoading}+ style={{+ flex: 2,+ padding: '12px',+ backgroundColor: FINCEPT.RED,+ border: 'none',+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '11px',+ fontWeight: 700,+ cursor: isLoading ? 'wait' : 'pointer',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '8px',+ }}+ >+ {isLoading ? (+ <>+ <Loader2 size={14} style={{ animation: 'spin 1s linear infinite' }} />+ PROCESSING...+ </>+ ) : (+ <>+ <Send size={14} />+ CONFIRM WITHDRAWAL+ </>+ )}+ </button>+ </div>+ </div>+ )}++ {/* Warning */}+ <div+ style={{+ marginTop: '16px',+ padding: '12px',+ backgroundColor: `${FINCEPT.RED}10`,+ borderRadius: '4px',+ fontSize: '9px',+ color: FINCEPT.RED,+ }}+ >+ <strong>Warning:</strong> Cryptocurrency transactions are irreversible. Please verify the+ address and network carefully before confirming.+ </div>+ </>+ )}++ <style>{`+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `}</style>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/FundingManager/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/core/FundingManager/index.tsnew file mode 100644index 000000000..970e3aa9b--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/FundingManager/index.ts@@ -0,0 +1,3 @@+export { TransactionsTable } from './TransactionsTable';+export { DepositPanel } from './DepositPanel';+export { WithdrawPanel } from './WithdrawPanel';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/LedgerManager/LedgerTable.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/LedgerManager/LedgerTable.tsxnew file mode 100644index 000000000..39cfb759c--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/LedgerManager/LedgerTable.tsx@@ -0,0 +1,267 @@+/**+ * Ledger Table+ * Displays account ledger entries (transactions, fees, funding, etc.)+ */++import React, { useState } from 'react';+import { Book, RefreshCw, AlertCircle, Info, ArrowUpRight, ArrowDownRight, Filter } from 'lucide-react';+import { useLedger } from '../../hooks/useLedger';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',+ PURPLE: '#9D4EDD',+};++const TYPE_COLORS: Record<string, string> = {+ trade: FINCEPT.CYAN,+ fee: FINCEPT.ORANGE,+ transfer: FINCEPT.PURPLE,+ deposit: FINCEPT.GREEN,+ withdrawal: FINCEPT.RED,+ funding: FINCEPT.YELLOW,+ rebate: FINCEPT.GREEN,+ cashback: FINCEPT.GREEN,+ referral: FINCEPT.PURPLE,+ default: FINCEPT.GRAY,+};++interface LedgerTableProps {+ currency?: string;+ limit?: number;+}++export function LedgerTable({ currency, limit = 100 }: LedgerTableProps) {+ const { tradingMode, activeBroker } = useBrokerContext();+ const { entries, isLoading, error, isSupported, refresh } = useLedger(currency, undefined, limit);+ const [filterType, setFilterType] = useState<string>('all');++ if (tradingMode === 'paper') {+ return (+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px' }}>+ <AlertCircle size={32} color={FINCEPT.YELLOW} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '12px' }}>Ledger not available in paper trading</div>+ </div>+ );+ }++ if (!isSupported) {+ return (+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px' }}>+ <Info size={32} color={FINCEPT.GRAY} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '12px' }}>Ledger not supported by {activeBroker}</div>+ </div>+ );+ }++ // Get unique types for filter+ const types = ['all', ...new Set(entries.map((e) => e.type))];++ // Filter entries+ const filteredEntries = entries.filter((e) => filterType === 'all' || e.type === filterType);++ // Calculate summary+ const totalIn = filteredEntries.filter((e) => e.amount > 0).reduce((sum, e) => sum + e.amount, 0);+ const totalOut = filteredEntries.filter((e) => e.amount < 0).reduce((sum, e) => sum + Math.abs(e.amount), 0);+ const totalFees = filteredEntries.filter((e) => e.fee).reduce((sum, e) => sum + (e.fee || 0), 0);++ return (+ <div style={{ background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px' }}>+ {/* Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Book size={14} color={FINCEPT.CYAN} />+ <span style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>Account Ledger</span>+ {currency && (+ <span style={{ fontSize: '10px', color: FINCEPT.CYAN, marginLeft: '8px' }}>({currency})</span>+ )}+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ {/* Type Filter */}+ <select+ value={filterType}+ onChange={(e) => setFilterType(e.target.value)}+ style={{+ padding: '4px 8px',+ backgroundColor: FINCEPT.DARK_BG,+ border: `1px solid ${FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: FINCEPT.WHITE,+ fontSize: '10px',+ }}+ >+ {types.map((type) => (+ <option key={type} value={type}>+ {type.charAt(0).toUpperCase() + type.slice(1)}+ </option>+ ))}+ </select>+ <button+ onClick={refresh}+ disabled={isLoading}+ style={{+ padding: '4px',+ backgroundColor: 'transparent',+ border: 'none',+ cursor: 'pointer',+ }}+ >+ <RefreshCw size={12} color={FINCEPT.GRAY} style={{ animation: isLoading ? 'spin 1s linear infinite' : 'none' }} />+ </button>+ </div>+ </div>++ {/* Summary Stats */}+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '1px', backgroundColor: FINCEPT.BORDER }}>+ <div style={{ padding: '12px', backgroundColor: FINCEPT.HEADER_BG, textAlign: 'center' }}>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>TOTAL IN</div>+ <div style={{ fontSize: '14px', fontFamily: '"IBM Plex Mono", monospace', color: FINCEPT.GREEN }}>+ +{totalIn.toFixed(4)}+ </div>+ </div>+ <div style={{ padding: '12px', backgroundColor: FINCEPT.HEADER_BG, textAlign: 'center' }}>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>TOTAL OUT</div>+ <div style={{ fontSize: '14px', fontFamily: '"IBM Plex Mono", monospace', color: FINCEPT.RED }}>+ -{totalOut.toFixed(4)}+ </div>+ </div>+ <div style={{ padding: '12px', backgroundColor: FINCEPT.HEADER_BG, textAlign: 'center' }}>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>TOTAL FEES</div>+ <div style={{ fontSize: '14px', fontFamily: '"IBM Plex Mono", monospace', color: FINCEPT.ORANGE }}>+ {totalFees.toFixed(4)}+ </div>+ </div>+ </div>++ {/* Error */}+ {error && (+ <div style={{ padding: '10px 16px', backgroundColor: `${FINCEPT.RED}20`, fontSize: '11px', color: FINCEPT.RED }}>+ {error.message}+ </div>+ )}++ {/* Table Header */}+ <div style={{ display: 'grid', gridTemplateColumns: '120px 80px 100px 100px 80px 80px', gap: '8px', padding: '10px 16px', backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>DATE/TIME</span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>TYPE</span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>CURRENCY</span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, textAlign: 'right' }}>AMOUNT</span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, textAlign: 'right' }}>FEE</span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, textAlign: 'right' }}>BALANCE</span>+ </div>++ {/* Table Body */}+ <div style={{ maxHeight: '400px', overflowY: 'auto' }}>+ {filteredEntries.map((entry, index) => {+ const typeColor = TYPE_COLORS[entry.type.toLowerCase()] || TYPE_COLORS.default;++ return (+ <div+ key={entry.id || index}+ style={{+ display: 'grid',+ gridTemplateColumns: '120px 80px 100px 100px 80px 80px',+ gap: '8px',+ padding: '10px 16px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ backgroundColor: index % 2 === 0 ? 'transparent' : `${FINCEPT.DARK_BG}50`,+ }}+ >+ {/* Date/Time */}+ <div>+ <div style={{ fontSize: '10px', color: FINCEPT.WHITE }}>+ {new Date(entry.timestamp).toLocaleDateString()}+ </div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ {new Date(entry.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}+ </div>+ </div>++ {/* Type */}+ <span+ style={{+ display: 'inline-flex',+ alignItems: 'center',+ padding: '2px 8px',+ backgroundColor: `${typeColor}20`,+ borderRadius: '4px',+ fontSize: '9px',+ fontWeight: 600,+ color: typeColor,+ textTransform: 'uppercase',+ height: 'fit-content',+ }}+ >+ {entry.type}+ </span>++ {/* Currency */}+ <span style={{ fontSize: '11px', color: FINCEPT.CYAN, fontFamily: '"IBM Plex Mono", monospace' }}>+ {entry.currency}+ </span>++ {/* Amount */}+ <div style={{ textAlign: 'right', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '4px' }}>+ {entry.amount > 0 ? (+ <ArrowUpRight size={10} color={FINCEPT.GREEN} />+ ) : (+ <ArrowDownRight size={10} color={FINCEPT.RED} />+ )}+ <span+ style={{+ fontSize: '11px',+ fontFamily: '"IBM Plex Mono", monospace',+ color: entry.amount > 0 ? FINCEPT.GREEN : FINCEPT.RED,+ }}+ >+ {entry.amount > 0 ? '+' : ''}{entry.amount.toFixed(6)}+ </span>+ </div>++ {/* Fee */}+ <span style={{ fontSize: '10px', color: FINCEPT.ORANGE, fontFamily: '"IBM Plex Mono", monospace', textAlign: 'right' }}>+ {entry.fee ? entry.fee.toFixed(6) : '--'}+ </span>++ {/* Balance After */}+ <span style={{ fontSize: '10px', color: FINCEPT.WHITE, fontFamily: '"IBM Plex Mono", monospace', textAlign: 'right' }}>+ {entry.after !== undefined ? entry.after.toFixed(4) : '--'}+ </span>+ </div>+ );+ })}+ </div>++ {/* Empty State */}+ {!isLoading && filteredEntries.length === 0 && !error && (+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ No ledger entries found+ </div>+ )}++ {/* Loading */}+ {isLoading && entries.length === 0 && (+ <div style={{ padding: '40px', textAlign: 'center' }}>+ <RefreshCw size={20} color={FINCEPT.GRAY} style={{ animation: 'spin 1s linear infinite' }} />+ </div>+ )}++ <style>{`+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `}</style>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/LedgerManager/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/core/LedgerManager/index.tsnew file mode 100644index 000000000..47685beb5--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/LedgerManager/index.ts@@ -0,0 +1 @@+export { LedgerTable } from './LedgerTable';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/LeverageManager/LeveragePanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/LeverageManager/LeveragePanel.tsxnew file mode 100644index 000000000..6d78f7923--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/LeverageManager/LeveragePanel.tsx@@ -0,0 +1,376 @@+/**+ * Leverage Panel+ * Control leverage settings, margin mode, and position mode+ */++import React, { useState, useEffect } from 'react';+import { Settings, AlertTriangle, Check, Loader2, Info, TrendingUp, Shield } from 'lucide-react';+import { useFetchLeverage, useSetLeverage, useLeverageTiers, useSetMarginMode, usePositionMode, useSetPositionMode } from '../../hooks/useLeverageManagement';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',+ PURPLE: '#9D4EDD',+};++interface LeveragePanelProps {+ symbol?: string;+}++export function LeveragePanel({ symbol }: LeveragePanelProps) {+ const { tradingMode, activeBroker } = useBrokerContext();+ const { leverage, isLoading: fetchingLeverage, isSupported: leverageSupported, refresh } = useFetchLeverage(symbol);+ const { setLeverage, isLoading: settingLeverage, error: setError, isSupported: setSupported } = useSetLeverage();+ const { tiers, isLoading: fetchingTiers, isSupported: tiersSupported } = useLeverageTiers(symbol);+ const { setMarginMode, isLoading: settingMargin, isSupported: marginSupported } = useSetMarginMode();+ const { positionMode, isSupported: positionModeSupported } = usePositionMode(symbol);+ const { setPositionMode, isLoading: settingPositionMode, isSupported: setPositionSupported } = useSetPositionMode();++ const [selectedLeverage, setSelectedLeverage] = useState(1);+ const [selectedMarginMode, setSelectedMarginMode] = useState<'cross' | 'isolated'>('cross');+ const [selectedPositionMode, setSelectedPositionMode] = useState<'one-way' | 'hedge'>('one-way');+ const [success, setSuccess] = useState<string | null>(null);++ // Sync with fetched values+ useEffect(() => {+ if (leverage) {+ setSelectedLeverage(leverage.leverage);+ if (leverage.marginMode) {+ setSelectedMarginMode(leverage.marginMode);+ }+ }+ }, [leverage]);++ useEffect(() => {+ if (positionMode) {+ setSelectedPositionMode(positionMode);+ }+ }, [positionMode]);++ // Calculate max leverage from tiers+ const maxLeverage = tiers.length > 0 ? Math.max(...tiers.map((t) => t.maxLeverage)) : leverage?.maxLeverage || 125;++ // Handle leverage change+ const handleLeverageChange = async () => {+ if (!symbol) return;+ const result = await setLeverage(selectedLeverage, symbol);+ if (result) {+ setSuccess('Leverage updated successfully');+ setTimeout(() => setSuccess(null), 3000);+ refresh();+ }+ };++ // Handle margin mode change+ const handleMarginModeChange = async (mode: 'cross' | 'isolated') => {+ if (!symbol) return;+ setSelectedMarginMode(mode);+ const result = await setMarginMode(mode, symbol);+ if (result) {+ setSuccess('Margin mode updated');+ setTimeout(() => setSuccess(null), 3000);+ }+ };++ // Handle position mode change+ const handlePositionModeChange = async (mode: 'one-way' | 'hedge') => {+ if (!symbol) return;+ setSelectedPositionMode(mode);+ const result = await setPositionMode(mode === 'hedge', symbol);+ if (result) {+ setSuccess('Position mode updated');+ setTimeout(() => setSuccess(null), 3000);+ }+ };++ if (tradingMode === 'paper') {+ return (+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px' }}>+ <AlertTriangle size={32} color={FINCEPT.YELLOW} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '12px' }}>Leverage settings not available in paper trading</div>+ </div>+ );+ }++ if (!leverageSupported) {+ return (+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px' }}>+ <Info size={32} color={FINCEPT.GRAY} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '12px' }}>Leverage not supported by {activeBroker}</div>+ </div>+ );+ }++ const isLoading = fetchingLeverage || settingLeverage || settingMargin || settingPositionMode;++ return (+ <div style={{ background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px', padding: '16px' }}>+ {/* Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px', paddingBottom: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Settings size={14} color={FINCEPT.ORANGE} />+ <span style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>Leverage Settings</span>+ </div>+ {symbol && (+ <span style={{ fontSize: '10px', color: FINCEPT.CYAN, fontFamily: '"IBM Plex Mono", monospace' }}>{symbol}</span>+ )}+ </div>++ {/* Success Message */}+ {success && (+ <div style={{ padding: '10px', backgroundColor: `${FINCEPT.GREEN}20`, borderRadius: '4px', marginBottom: '12px', display: 'flex', alignItems: 'center', gap: '8px' }}>+ <Check size={14} color={FINCEPT.GREEN} />+ <span style={{ fontSize: '11px', color: FINCEPT.GREEN }}>{success}</span>+ </div>+ )}++ {/* Error Message */}+ {setError && (+ <div style={{ padding: '10px', backgroundColor: `${FINCEPT.RED}20`, borderRadius: '4px', marginBottom: '12px', fontSize: '11px', color: FINCEPT.RED }}>+ {setError.message}+ </div>+ )}++ {/* Leverage Slider */}+ <div style={{ marginBottom: '20px' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>+ <label style={{ fontSize: '10px', color: FINCEPT.GRAY }}>LEVERAGE</label>+ <span style={{ fontSize: '14px', color: FINCEPT.ORANGE, fontWeight: 700, fontFamily: '"IBM Plex Mono", monospace' }}>+ {selectedLeverage}x+ </span>+ </div>++ <input+ type="range"+ min={1}+ max={maxLeverage}+ value={selectedLeverage}+ onChange={(e) => setSelectedLeverage(parseInt(e.target.value))}+ style={{+ width: '100%',+ height: '6px',+ borderRadius: '3px',+ appearance: 'none',+ background: `linear-gradient(to right, ${FINCEPT.ORANGE} 0%, ${FINCEPT.ORANGE} ${(selectedLeverage / maxLeverage) * 100}%, ${FINCEPT.BORDER} ${(selectedLeverage / maxLeverage) * 100}%, ${FINCEPT.BORDER} 100%)`,+ cursor: 'pointer',+ }}+ />++ <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '4px' }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>1x</span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>{maxLeverage}x</span>+ </div>++ {/* Quick Select Buttons */}+ <div style={{ display: 'flex', gap: '6px', marginTop: '12px', flexWrap: 'wrap' }}>+ {[1, 5, 10, 20, 50, 100].filter((v) => v <= maxLeverage).map((val) => (+ <button+ key={val}+ onClick={() => setSelectedLeverage(val)}+ style={{+ padding: '6px 12px',+ backgroundColor: selectedLeverage === val ? FINCEPT.ORANGE : FINCEPT.DARK_BG,+ border: `1px solid ${selectedLeverage === val ? FINCEPT.ORANGE : FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: selectedLeverage === val ? FINCEPT.WHITE : FINCEPT.GRAY,+ fontSize: '10px',+ fontWeight: 600,+ cursor: 'pointer',+ }}+ >+ {val}x+ </button>+ ))}+ </div>++ <button+ onClick={handleLeverageChange}+ disabled={isLoading || selectedLeverage === leverage?.leverage}+ style={{+ width: '100%',+ marginTop: '12px',+ padding: '10px',+ backgroundColor: selectedLeverage !== leverage?.leverage ? FINCEPT.ORANGE : FINCEPT.BORDER,+ border: 'none',+ borderRadius: '4px',+ color: selectedLeverage !== leverage?.leverage ? FINCEPT.WHITE : FINCEPT.GRAY,+ fontSize: '11px',+ fontWeight: 700,+ cursor: selectedLeverage !== leverage?.leverage ? 'pointer' : 'not-allowed',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '6px',+ }}+ >+ {settingLeverage ? (+ <>+ <Loader2 size={12} style={{ animation: 'spin 1s linear infinite' }} />+ UPDATING...+ </>+ ) : (+ <>+ <TrendingUp size={12} />+ APPLY LEVERAGE+ </>+ )}+ </button>+ </div>++ {/* Margin Mode */}+ {marginSupported && (+ <div style={{ marginBottom: '20px' }}>+ <label style={{ display: 'block', fontSize: '10px', color: FINCEPT.GRAY, marginBottom: '8px' }}>MARGIN MODE</label>+ <div style={{ display: 'flex', gap: '8px' }}>+ <button+ onClick={() => handleMarginModeChange('cross')}+ disabled={settingMargin}+ style={{+ flex: 1,+ padding: '10px',+ backgroundColor: selectedMarginMode === 'cross' ? `${FINCEPT.CYAN}20` : FINCEPT.DARK_BG,+ border: `1px solid ${selectedMarginMode === 'cross' ? FINCEPT.CYAN : FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: selectedMarginMode === 'cross' ? FINCEPT.CYAN : FINCEPT.GRAY,+ fontSize: '11px',+ fontWeight: 600,+ cursor: 'pointer',+ }}+ >+ <div>Cross</div>+ <div style={{ fontSize: '8px', marginTop: '2px', opacity: 0.7 }}>Shared margin</div>+ </button>+ <button+ onClick={() => handleMarginModeChange('isolated')}+ disabled={settingMargin}+ style={{+ flex: 1,+ padding: '10px',+ backgroundColor: selectedMarginMode === 'isolated' ? `${FINCEPT.PURPLE}20` : FINCEPT.DARK_BG,+ border: `1px solid ${selectedMarginMode === 'isolated' ? FINCEPT.PURPLE : FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: selectedMarginMode === 'isolated' ? FINCEPT.PURPLE : FINCEPT.GRAY,+ fontSize: '11px',+ fontWeight: 600,+ cursor: 'pointer',+ }}+ >+ <div>Isolated</div>+ <div style={{ fontSize: '8px', marginTop: '2px', opacity: 0.7 }}>Per-position</div>+ </button>+ </div>+ </div>+ )}++ {/* Position Mode */}+ {positionModeSupported && setPositionSupported && (+ <div style={{ marginBottom: '16px' }}>+ <label style={{ display: 'block', fontSize: '10px', color: FINCEPT.GRAY, marginBottom: '8px' }}>POSITION MODE</label>+ <div style={{ display: 'flex', gap: '8px' }}>+ <button+ onClick={() => handlePositionModeChange('one-way')}+ disabled={settingPositionMode}+ style={{+ flex: 1,+ padding: '10px',+ backgroundColor: selectedPositionMode === 'one-way' ? `${FINCEPT.GREEN}20` : FINCEPT.DARK_BG,+ border: `1px solid ${selectedPositionMode === 'one-way' ? FINCEPT.GREEN : FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: selectedPositionMode === 'one-way' ? FINCEPT.GREEN : FINCEPT.GRAY,+ fontSize: '11px',+ fontWeight: 600,+ cursor: 'pointer',+ }}+ >+ <div>One-way</div>+ <div style={{ fontSize: '8px', marginTop: '2px', opacity: 0.7 }}>Single direction</div>+ </button>+ <button+ onClick={() => handlePositionModeChange('hedge')}+ disabled={settingPositionMode}+ style={{+ flex: 1,+ padding: '10px',+ backgroundColor: selectedPositionMode === 'hedge' ? `${FINCEPT.YELLOW}20` : FINCEPT.DARK_BG,+ border: `1px solid ${selectedPositionMode === 'hedge' ? FINCEPT.YELLOW : FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: selectedPositionMode === 'hedge' ? FINCEPT.YELLOW : FINCEPT.GRAY,+ fontSize: '11px',+ fontWeight: 600,+ cursor: 'pointer',+ }}+ >+ <div>Hedge</div>+ <div style={{ fontSize: '8px', marginTop: '2px', opacity: 0.7 }}>Long & Short</div>+ </button>+ </div>+ </div>+ )}++ {/* Leverage Tiers Info */}+ {tiersSupported && tiers.length > 0 && (+ <div style={{ backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px', padding: '12px' }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '8px' }}>+ <Shield size={12} color={FINCEPT.CYAN} />+ <span style={{ fontSize: '10px', color: FINCEPT.CYAN, fontWeight: 600 }}>LEVERAGE TIERS</span>+ </div>+ <div style={{ maxHeight: '120px', overflowY: 'auto' }}>+ {tiers.slice(0, 5).map((tier) => (+ <div+ key={tier.tier}+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ padding: '6px 0',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ fontSize: '9px',+ }}+ >+ <span style={{ color: FINCEPT.GRAY }}>+ {tier.minNotional.toLocaleString()} - {tier.maxNotional === Infinity ? '...' : tier.maxNotional.toLocaleString()}+ </span>+ <span style={{ color: FINCEPT.WHITE }}>Max {tier.maxLeverage}x</span>+ <span style={{ color: FINCEPT.ORANGE }}>{(tier.maintenanceMarginRate * 100).toFixed(2)}% MMR</span>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Warning */}+ <div style={{ marginTop: '12px', padding: '10px', backgroundColor: `${FINCEPT.YELLOW}10`, borderRadius: '4px', display: 'flex', gap: '8px', alignItems: 'flex-start' }}>+ <AlertTriangle size={14} color={FINCEPT.YELLOW} style={{ flexShrink: 0, marginTop: '2px' }} />+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ <strong style={{ color: FINCEPT.YELLOW }}>Risk Warning:</strong> Higher leverage increases both potential profits and losses.+ You may lose more than your initial margin.+ </div>+ </div>++ <style>{`+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ input[type="range"]::-webkit-slider-thumb {+ appearance: none;+ width: 16px;+ height: 16px;+ border-radius: 50%;+ background: ${FINCEPT.ORANGE};+ cursor: pointer;+ border: 2px solid ${FINCEPT.WHITE};+ }+ `}</style>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/LeverageManager/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/core/LeverageManager/index.tsnew file mode 100644index 000000000..7c306e75b--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/LeverageManager/index.ts@@ -0,0 +1 @@+export { LeveragePanel } from './LeveragePanel';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/MarketSentiment/LongShortRatioPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/MarketSentiment/LongShortRatioPanel.tsxnew file mode 100644index 000000000..e161612dc--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/MarketSentiment/LongShortRatioPanel.tsx@@ -0,0 +1,257 @@+/**+ * Long/Short Ratio Panel+ * Displays market sentiment based on long/short ratio data+ */++import React from 'react';+import { TrendingUp, TrendingDown, BarChart2, RefreshCw, AlertCircle, Info } from 'lucide-react';+import { useLongShortRatioHistory } from '../../hooks/useAdvancedMarketData';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',+};++interface LongShortRatioPanelProps {+ symbol?: string;+ timeframe?: string;+ limit?: number;+}++export function LongShortRatioPanel({ symbol, timeframe = '1h', limit = 24 }: LongShortRatioPanelProps) {+ const { tradingMode, activeBroker } = useBrokerContext();+ const { history, isLoading, error, isSupported, refresh } = useLongShortRatioHistory(symbol, timeframe, undefined, limit);++ if (tradingMode === 'paper') {+ return (+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px' }}>+ <AlertCircle size={32} color={FINCEPT.YELLOW} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '12px' }}>Market sentiment not available in paper trading</div>+ </div>+ );+ }++ if (!isSupported) {+ return (+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px' }}>+ <Info size={32} color={FINCEPT.GRAY} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '12px' }}>Long/Short ratio not supported by {activeBroker}</div>+ </div>+ );+ }++ // Latest ratio+ const latest = history.length > 0 ? history[0] : null;+ const prevRatio = history.length > 1 ? history[1].longShortRatio : null;+ const ratioChange = latest && prevRatio ? ((latest.longShortRatio - prevRatio) / prevRatio) * 100 : 0;++ // Calculate percentages+ const longPercent = latest ? (latest.longShortRatio / (latest.longShortRatio + 1)) * 100 : 50;+ const shortPercent = 100 - longPercent;++ // Determine sentiment+ const sentiment = latest+ ? latest.longShortRatio > 1.5+ ? 'Extremely Bullish'+ : latest.longShortRatio > 1.1+ ? 'Bullish'+ : latest.longShortRatio > 0.9+ ? 'Neutral'+ : latest.longShortRatio > 0.67+ ? 'Bearish'+ : 'Extremely Bearish'+ : 'Unknown';++ const sentimentColor =+ sentiment === 'Extremely Bullish' || sentiment === 'Bullish'+ ? FINCEPT.GREEN+ : sentiment === 'Neutral'+ ? FINCEPT.YELLOW+ : FINCEPT.RED;++ return (+ <div style={{ background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px', padding: '16px' }}>+ {/* Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '16px', paddingBottom: '12px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <BarChart2 size={14} color={FINCEPT.CYAN} />+ <span style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>Long/Short Ratio</span>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ {symbol && (+ <span style={{ fontSize: '10px', color: FINCEPT.CYAN, fontFamily: '"IBM Plex Mono", monospace' }}>{symbol}</span>+ )}+ <button+ onClick={refresh}+ disabled={isLoading}+ style={{+ padding: '4px',+ backgroundColor: 'transparent',+ border: 'none',+ cursor: 'pointer',+ }}+ >+ <RefreshCw size={12} color={FINCEPT.GRAY} style={{ animation: isLoading ? 'spin 1s linear infinite' : 'none' }} />+ </button>+ </div>+ </div>++ {/* Error */}+ {error && (+ <div style={{ padding: '10px', backgroundColor: `${FINCEPT.RED}20`, borderRadius: '4px', marginBottom: '12px', fontSize: '11px', color: FINCEPT.RED }}>+ {error.message}+ </div>+ )}++ {/* Main Ratio Display */}+ {latest && (+ <div style={{ marginBottom: '20px' }}>+ {/* Big Ratio Number */}+ <div style={{ textAlign: 'center', marginBottom: '16px' }}>+ <div style={{ fontSize: '32px', fontWeight: 700, color: FINCEPT.WHITE, fontFamily: '"IBM Plex Mono", monospace' }}>+ {latest.longShortRatio.toFixed(3)}+ </div>+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px', marginTop: '4px' }}>+ {ratioChange > 0 ? (+ <TrendingUp size={12} color={FINCEPT.GREEN} />+ ) : ratioChange < 0 ? (+ <TrendingDown size={12} color={FINCEPT.RED} />+ ) : null}+ <span style={{ fontSize: '11px', color: ratioChange > 0 ? FINCEPT.GREEN : ratioChange < 0 ? FINCEPT.RED : FINCEPT.GRAY }}>+ {ratioChange > 0 ? '+' : ''}{ratioChange.toFixed(2)}%+ </span>+ </div>+ </div>++ {/* Sentiment Badge */}+ <div style={{ textAlign: 'center', marginBottom: '16px' }}>+ <span+ style={{+ display: 'inline-block',+ padding: '6px 16px',+ backgroundColor: `${sentimentColor}20`,+ border: `1px solid ${sentimentColor}`,+ borderRadius: '20px',+ fontSize: '11px',+ fontWeight: 600,+ color: sentimentColor,+ }}+ >+ {sentiment}+ </span>+ </div>++ {/* Long/Short Bar */}+ <div style={{ marginBottom: '12px' }}>+ <div style={{ display: 'flex', marginBottom: '6px' }}>+ <div style={{ flex: longPercent, textAlign: 'left' }}>+ <span style={{ fontSize: '10px', color: FINCEPT.GREEN, fontWeight: 600 }}>LONG {longPercent.toFixed(1)}%</span>+ </div>+ <div style={{ flex: shortPercent, textAlign: 'right' }}>+ <span style={{ fontSize: '10px', color: FINCEPT.RED, fontWeight: 600 }}>{shortPercent.toFixed(1)}% SHORT</span>+ </div>+ </div>+ <div style={{ display: 'flex', height: '8px', borderRadius: '4px', overflow: 'hidden' }}>+ <div style={{ width: `${longPercent}%`, backgroundColor: FINCEPT.GREEN }} />+ <div style={{ width: `${shortPercent}%`, backgroundColor: FINCEPT.RED }} />+ </div>+ </div>++ {/* Account Stats */}+ {(latest.longAccount !== undefined || latest.shortAccount !== undefined) && (+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>+ {latest.longAccount !== undefined && (+ <div style={{ padding: '10px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>LONG ACCOUNTS</div>+ <div style={{ fontSize: '14px', color: FINCEPT.GREEN, fontFamily: '"IBM Plex Mono", monospace' }}>+ {(latest.longAccount * 100).toFixed(2)}%+ </div>+ </div>+ )}+ {latest.shortAccount !== undefined && (+ <div style={{ padding: '10px', backgroundColor: FINCEPT.DARK_BG, borderRadius: '4px', textAlign: 'center' }}>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>SHORT ACCOUNTS</div>+ <div style={{ fontSize: '14px', color: FINCEPT.RED, fontFamily: '"IBM Plex Mono", monospace' }}>+ {(latest.shortAccount * 100).toFixed(2)}%+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ )}++ {/* Historical Data */}+ {history.length > 1 && (+ <div>+ <div style={{ fontSize: '10px', color: FINCEPT.GRAY, marginBottom: '8px' }}>HISTORICAL ({timeframe})</div>+ <div style={{ maxHeight: '150px', overflowY: 'auto' }}>+ {history.slice(0, 12).map((item, index) => (+ <div+ key={index}+ style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ padding: '6px 0',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ }}+ >+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>+ {new Date(item.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}+ </span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <span+ style={{+ fontSize: '11px',+ fontFamily: '"IBM Plex Mono", monospace',+ color: item.longShortRatio > 1 ? FINCEPT.GREEN : item.longShortRatio < 1 ? FINCEPT.RED : FINCEPT.WHITE,+ }}+ >+ {item.longShortRatio.toFixed(3)}+ </span>+ {/* Mini bar */}+ <div style={{ width: '40px', height: '4px', display: 'flex', borderRadius: '2px', overflow: 'hidden' }}>+ <div style={{ width: `${(item.longShortRatio / (item.longShortRatio + 1)) * 100}%`, backgroundColor: FINCEPT.GREEN }} />+ <div style={{ flex: 1, backgroundColor: FINCEPT.RED }} />+ </div>+ </div>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* No Data */}+ {!isLoading && history.length === 0 && !error && (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ No long/short ratio data available+ </div>+ )}++ {/* Loading */}+ {isLoading && history.length === 0 && (+ <div style={{ padding: '20px', textAlign: 'center' }}>+ <RefreshCw size={20} color={FINCEPT.GRAY} style={{ animation: 'spin 1s linear infinite' }} />+ </div>+ )}++ <style>{`+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `}</style>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/MarketSentiment/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/core/MarketSentiment/index.tsnew file mode 100644index 000000000..0b3ded6d7--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/MarketSentiment/index.ts@@ -0,0 +1 @@+export { LongShortRatioPanel } from './LongShortRatioPanel';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/PositionHistory/PositionHistoryTable.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/PositionHistory/PositionHistoryTable.tsxnew file mode 100644index 000000000..9739a1eca--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/PositionHistory/PositionHistoryTable.tsx@@ -0,0 +1,250 @@+/**+ * Position History Table+ * Displays closed position history with P&L+ */++import React, { useState } from 'react';+import { History, RefreshCw, AlertCircle, Info, TrendingUp, TrendingDown, Filter } from 'lucide-react';+import { usePositionHistory } from '../../hooks/useAdvancedMarketData';+import { useBrokerContext } from '../../../../../contexts/BrokerContext';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ YELLOW: '#FFD700',+ CYAN: '#00E5FF',+};++interface PositionHistoryTableProps {+ symbol?: string;+ limit?: number;+}++export function PositionHistoryTable({ symbol, limit = 50 }: PositionHistoryTableProps) {+ const { tradingMode, activeBroker } = useBrokerContext();+ const { history, isLoading, error, isSupported, refresh } = usePositionHistory(symbol, undefined, limit);+ const [filterSide, setFilterSide] = useState<'all' | 'long' | 'short'>('all');++ if (tradingMode === 'paper') {+ return (+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px' }}>+ <AlertCircle size={32} color={FINCEPT.YELLOW} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '12px' }}>Position history not available in paper trading</div>+ </div>+ );+ }++ if (!isSupported) {+ return (+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px' }}>+ <Info size={32} color={FINCEPT.GRAY} style={{ marginBottom: '12px' }} />+ <div style={{ fontSize: '12px' }}>Position history not supported by {activeBroker}</div>+ </div>+ );+ }++ // Filter positions+ const filteredHistory = history.filter((pos) => filterSide === 'all' || pos.side === filterSide);++ // Calculate totals+ const totalPnl = filteredHistory.reduce((sum, pos) => sum + pos.realizedPnl, 0);+ const winCount = filteredHistory.filter((pos) => pos.realizedPnl > 0).length;+ const lossCount = filteredHistory.filter((pos) => pos.realizedPnl < 0).length;+ const winRate = filteredHistory.length > 0 ? (winCount / filteredHistory.length) * 100 : 0;++ return (+ <div style={{ background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '4px' }}>+ {/* Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ <History size={14} color={FINCEPT.CYAN} />+ <span style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE }}>Position History</span>+ {symbol && (+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY, marginLeft: '8px' }}>({symbol})</span>+ )}+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ {/* Filter */}+ <div style={{ display: 'flex', gap: '4px' }}>+ {(['all', 'long', 'short'] as const).map((side) => (+ <button+ key={side}+ onClick={() => setFilterSide(side)}+ style={{+ padding: '4px 8px',+ backgroundColor: filterSide === side ? FINCEPT.ORANGE : 'transparent',+ border: `1px solid ${filterSide === side ? FINCEPT.ORANGE : FINCEPT.BORDER}`,+ borderRadius: '4px',+ color: filterSide === side ? FINCEPT.WHITE : FINCEPT.GRAY,+ fontSize: '9px',+ cursor: 'pointer',+ textTransform: 'uppercase',+ }}+ >+ {side}+ </button>+ ))}+ </div>+ <button+ onClick={refresh}+ disabled={isLoading}+ style={{+ padding: '4px',+ backgroundColor: 'transparent',+ border: 'none',+ cursor: 'pointer',+ }}+ >+ <RefreshCw size={12} color={FINCEPT.GRAY} style={{ animation: isLoading ? 'spin 1s linear infinite' : 'none' }} />+ </button>+ </div>+ </div>++ {/* Summary Stats */}+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '1px', backgroundColor: FINCEPT.BORDER }}>+ <div style={{ padding: '12px', backgroundColor: FINCEPT.HEADER_BG, textAlign: 'center' }}>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>TOTAL P&L</div>+ <div style={{ fontSize: '14px', fontFamily: '"IBM Plex Mono", monospace', color: totalPnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED }}>+ {totalPnl >= 0 ? '+' : ''}{totalPnl.toFixed(2)}+ </div>+ </div>+ <div style={{ padding: '12px', backgroundColor: FINCEPT.HEADER_BG, textAlign: 'center' }}>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>WIN RATE</div>+ <div style={{ fontSize: '14px', fontFamily: '"IBM Plex Mono", monospace', color: winRate >= 50 ? FINCEPT.GREEN : FINCEPT.RED }}>+ {winRate.toFixed(1)}%+ </div>+ </div>+ <div style={{ padding: '12px', backgroundColor: FINCEPT.HEADER_BG, textAlign: 'center' }}>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>WINS</div>+ <div style={{ fontSize: '14px', fontFamily: '"IBM Plex Mono", monospace', color: FINCEPT.GREEN }}>+ {winCount}+ </div>+ </div>+ <div style={{ padding: '12px', backgroundColor: FINCEPT.HEADER_BG, textAlign: 'center' }}>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>LOSSES</div>+ <div style={{ fontSize: '14px', fontFamily: '"IBM Plex Mono", monospace', color: FINCEPT.RED }}>+ {lossCount}+ </div>+ </div>+ </div>++ {/* Error */}+ {error && (+ <div style={{ padding: '10px 16px', backgroundColor: `${FINCEPT.RED}20`, fontSize: '11px', color: FINCEPT.RED }}>+ {error.message}+ </div>+ )}++ {/* Table Header */}+ <div style={{ display: 'grid', gridTemplateColumns: '100px 60px 80px 80px 80px 90px 80px', gap: '8px', padding: '10px 16px', backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>SYMBOL</span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>SIDE</span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, textAlign: 'right' }}>ENTRY</span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, textAlign: 'right' }}>EXIT</span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, textAlign: 'right' }}>SIZE</span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, textAlign: 'right' }}>P&L</span>+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, textAlign: 'right' }}>CLOSED</span>+ </div>++ {/* Table Body */}+ <div style={{ maxHeight: '400px', overflowY: 'auto' }}>+ {filteredHistory.map((position, index) => {+ const pnlPercent = position.entryPrice > 0 ? ((position.exitPrice || 0) - position.entryPrice) / position.entryPrice * 100 * (position.side === 'long' ? 1 : -1) : 0;++ return (+ <div+ key={index}+ style={{+ display: 'grid',+ gridTemplateColumns: '100px 60px 80px 80px 80px 90px 80px',+ gap: '8px',+ padding: '10px 16px',+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ backgroundColor: index % 2 === 0 ? 'transparent' : `${FINCEPT.DARK_BG}50`,+ }}+ >+ {/* Symbol */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <span style={{ fontSize: '11px', color: FINCEPT.WHITE, fontFamily: '"IBM Plex Mono", monospace' }}>+ {position.symbol.replace('/USDT', '').slice(0, 8)}+ </span>+ </div>++ {/* Side */}+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ {position.side === 'long' ? (+ <TrendingUp size={10} color={FINCEPT.GREEN} />+ ) : (+ <TrendingDown size={10} color={FINCEPT.RED} />+ )}+ <span style={{ fontSize: '10px', color: position.side === 'long' ? FINCEPT.GREEN : FINCEPT.RED, textTransform: 'uppercase' }}>+ {position.side}+ </span>+ </div>++ {/* Entry Price */}+ <span style={{ fontSize: '10px', color: FINCEPT.WHITE, fontFamily: '"IBM Plex Mono", monospace', textAlign: 'right' }}>+ {position.entryPrice.toFixed(position.entryPrice < 1 ? 6 : 2)}+ </span>++ {/* Exit Price */}+ <span style={{ fontSize: '10px', color: FINCEPT.WHITE, fontFamily: '"IBM Plex Mono", monospace', textAlign: 'right' }}>+ {position.exitPrice ? position.exitPrice.toFixed(position.exitPrice < 1 ? 6 : 2) : '--'}+ </span>++ {/* Size */}+ <span style={{ fontSize: '10px', color: FINCEPT.GRAY, fontFamily: '"IBM Plex Mono", monospace', textAlign: 'right' }}>+ {position.amount.toFixed(position.amount < 1 ? 6 : 2)}+ </span>++ {/* P&L */}+ <div style={{ textAlign: 'right' }}>+ <div style={{ fontSize: '10px', fontFamily: '"IBM Plex Mono", monospace', color: position.realizedPnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED }}>+ {position.realizedPnl >= 0 ? '+' : ''}{position.realizedPnl.toFixed(2)}+ </div>+ <div style={{ fontSize: '8px', color: position.realizedPnl >= 0 ? FINCEPT.GREEN : FINCEPT.RED, opacity: 0.7 }}>+ ({pnlPercent >= 0 ? '+' : ''}{pnlPercent.toFixed(2)}%)+ </div>+ </div>++ {/* Closed Time */}+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY, textAlign: 'right' }}>+ {position.closeTimestamp+ ? new Date(position.closeTimestamp).toLocaleDateString([], { month: 'short', day: 'numeric' })+ : '--'}+ </span>+ </div>+ );+ })}+ </div>++ {/* Empty State */}+ {!isLoading && filteredHistory.length === 0 && !error && (+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ No closed positions found+ </div>+ )}++ {/* Loading */}+ {isLoading && history.length === 0 && (+ <div style={{ padding: '40px', textAlign: 'center' }}>+ <RefreshCw size={20} color={FINCEPT.GRAY} style={{ animation: 'spin 1s linear infinite' }} />+ </div>+ )}++ <style>{`+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ `}</style>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/PositionHistory/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/core/PositionHistory/index.tsnew file mode 100644index 000000000..eab8c0cfa--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/PositionHistory/index.ts@@ -0,0 +1 @@+export { PositionHistoryTable } from './PositionHistoryTable';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/TradeManager/TradesTable.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/TradeManager/TradesTable.tsxnew file mode 100644index 000000000..504aa66fc--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/TradeManager/TradesTable.tsx@@ -0,0 +1,200 @@+/**+ * Trades Table+ * Displays user's trade history using fetchMyTrades+ * Universal component - works with ALL exchanges+ */++import React from 'react';+import { useTrades } from '../../hooks/useTrades';+import { formatCurrency, formatDateTime } from '../../utils/formatters';++const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+};++interface TradesTableProps {+ symbol?: string;+ limit?: number;+}++export function TradesTable({ symbol, limit = 50 }: TradesTableProps) {+ const { trades, isLoading, error, isSupported, refresh } = useTrades(symbol, limit, false);++ if (!isSupported) {+ return (+ <div+ style={{+ padding: '20px',+ textAlign: 'center',+ color: FINCEPT.GRAY,+ fontSize: '11px',+ }}+ >+ This exchange does not support trade history+ </div>+ );+ }++ if (error) {+ return (+ <div+ style={{+ padding: '20px',+ textAlign: 'center',+ color: FINCEPT.RED,+ fontSize: '11px',+ }}+ >+ Failed to load trade history+ <button+ onClick={refresh}+ style={{+ marginLeft: '10px',+ padding: '4px 8px',+ backgroundColor: FINCEPT.ORANGE,+ border: 'none',+ color: FINCEPT.WHITE,+ fontSize: '9px',+ cursor: 'pointer',+ }}+ >+ RETRY+ </button>+ </div>+ );+ }++ if (isLoading && trades.length === 0) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ Loading trade history...+ </div>+ );+ }++ if (trades.length === 0) {+ return (+ <div style={{ padding: '20px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>+ No trades found+ </div>+ );+ }++ return (+ <div style={{ width: '100%', height: '100%', overflowX: 'auto', overflowY: 'auto' }}>+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>+ <thead style={{ position: 'sticky', top: 0, zIndex: 1 }}>+ <tr style={{ backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.BORDER}` }}>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: FINCEPT.GRAY, fontWeight: 700 }}>+ TIME+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: FINCEPT.GRAY, fontWeight: 700 }}>+ SYMBOL+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'left', color: FINCEPT.GRAY, fontWeight: 700 }}>+ SIDE+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: FINCEPT.GRAY, fontWeight: 700 }}>+ PRICE+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: FINCEPT.GRAY, fontWeight: 700 }}>+ QTY+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: FINCEPT.GRAY, fontWeight: 700 }}>+ COST+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'right', color: FINCEPT.GRAY, fontWeight: 700 }}>+ FEE+ </th>+ <th style={{ padding: '8px 10px', textAlign: 'center', color: FINCEPT.GRAY, fontWeight: 700 }}>+ TYPE+ </th>+ </tr>+ </thead>+ <tbody>+ {trades.map((trade, index) => (+ <tr+ key={trade.id}+ style={{+ borderBottom: `1px solid ${FINCEPT.BORDER}`,+ backgroundColor: index % 2 === 0 ? FINCEPT.DARK_BG : FINCEPT.PANEL_BG,+ }}+ >+ {/* Time */}+ <td style={{ padding: '10px', color: FINCEPT.GRAY, fontSize: '9px' }}>+ {formatDateTime(trade.timestamp)}+ </td>++ {/* Symbol */}+ <td style={{ padding: '10px', color: FINCEPT.WHITE, fontWeight: 600 }}>+ {trade.symbol}+ </td>++ {/* Side */}+ <td style={{ padding: '10px' }}>+ <span+ style={{+ padding: '2px 6px',+ backgroundColor: trade.side === 'buy' ? `${FINCEPT.GREEN}20` : `${FINCEPT.RED}20`,+ color: trade.side === 'buy' ? FINCEPT.GREEN : FINCEPT.RED,+ fontSize: '9px',+ fontWeight: 700,+ borderRadius: '2px',+ }}+ >+ {trade.side.toUpperCase()}+ </span>+ </td>++ {/* Price */}+ <td style={{ padding: '10px', textAlign: 'right', color: FINCEPT.WHITE }}>+ {formatCurrency(trade.price)}+ </td>++ {/* Quantity */}+ <td style={{ padding: '10px', textAlign: 'right', color: FINCEPT.WHITE }}>+ {trade.quantity.toFixed(6)}+ </td>++ {/* Cost */}+ <td style={{ padding: '10px', textAlign: 'right', color: FINCEPT.ORANGE }}>+ {formatCurrency(trade.cost)}+ </td>++ {/* Fee */}+ <td style={{ padding: '10px', textAlign: 'right', color: FINCEPT.GRAY }}>+ {trade.fee ? `${trade.fee.cost.toFixed(4)} ${trade.fee.currency}` : '--'}+ </td>++ {/* Taker/Maker */}+ <td style={{ padding: '10px', textAlign: 'center' }}>+ {trade.takerOrMaker && (+ <span+ style={{+ padding: '2px 6px',+ backgroundColor: trade.takerOrMaker === 'maker' ? `${FINCEPT.GREEN}20` : `${FINCEPT.ORANGE}20`,+ color: trade.takerOrMaker === 'maker' ? FINCEPT.GREEN : FINCEPT.ORANGE,+ fontSize: '8px',+ fontWeight: 700,+ borderRadius: '2px',+ }}+ >+ {trade.takerOrMaker.toUpperCase()}+ </span>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ );+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/TradeManager/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/core/TradeManager/index.tsnew file mode 100644index 000000000..d60dc2448--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/TradeManager/index.ts@@ -0,0 +1 @@+export { TradesTable } from './TradesTable';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/core/index.tsnew file mode 100644index 000000000..3534ead07--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/index.ts@@ -0,0 +1,46 @@+/**+ * Trading Core Components Index+ * Re-exports all core trading UI components+ */++// Account & Balance+export { AccountStats, FeesDisplay } from './AccountInfo';++// Order Form+export { BasicOrderForm, AdvancedOrderForm, EnhancedOrderForm } from './OrderForm';++// Order Management+export { OrdersTable, ClosedOrders } from './OrderManager';++// Position Management+export { PositionsTable } from './PositionManager';++// Trade History+export { TradesTable } from './TradeManager';++// Funding (Deposit/Withdraw)+export { TransactionsTable, DepositPanel, WithdrawPanel } from './FundingManager';++// Exchange Status+export { ExchangeStatusIndicator } from './ExchangeStatus';++// Derivatives Info+export { FundingRatesPanel, OpenInterestPanel, LiquidationsPanel, BorrowRatesPanel } from './DerivativesInfo';++// Convert & Transfer+export { ConvertPanel, TransferPanel } from './ConvertManager';++// Leverage Management+export { LeveragePanel } from './LeverageManager';++// Market Sentiment+export { LongShortRatioPanel } from './MarketSentiment';++// Position History+export { PositionHistoryTable } from './PositionHistory';++// Ledger+export { LedgerTable } from './LedgerManager';++// Advanced Orders+export { AdvancedOrdersPanel } from './AdvancedOrders';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/index.tsindex 3bb53b762..6464a483d 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/hooks/index.ts+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/index.ts@@ -9,7 +9,132 @@ export { usePositions, useClosePosition } from './usePositions';export { useOrders, useCancelOrder, useClosedOrders } from './useOrders';export { useOHLCV, useOrderBook, useTicker, useVolumeProfile } from './useMarketData';export type { VolumeProfileLevel } from './useMarketData';-export { useBalance, useFees, useMarginInfo, useTradingStats } from './useAccountInfo';-export type { FeeStructure, MarginInfo } from './useAccountInfo';+export { useBalance, useFees, useMarginInfo, useLeverage, useTradingStats } from './useAccountInfo';+export type { FeeStructure, MarginInfo, LeverageInfo } from './useAccountInfo';export { useCrossExchangePortfolio, useArbitrageDetection, useCrossExchangePositions } from './useCrossExchange';export type { CrossExchangeBalance, AggregatedBalance, ArbitrageOpportunity, CrossExchangePosition } from './useCrossExchange';+export { useTrades, useOrderTrades } from './useTrades';+export type { UnifiedTrade } from './useTrades';+export { useExchangeStatus, useExchangeTime } from './useExchangeStatus';+export type { ExchangeStatus } from './useExchangeStatus';+export { useDeposits, useWithdrawals, useDepositAddress, useWithdraw, useTransactions } from './useFunding';+export type { UnifiedTransaction, DepositAddress, WithdrawParams } from './useFunding';++// Derivatives (Funding Rates, Mark Prices, Open Interest, Liquidations, Borrow Rates)+export {+ useFundingRate,+ useFundingRates,+ useFundingRateHistory,+ useMarkPrice,+ useMarkPrices,+ useOpenInterest,+ useOpenInterestHistory,+ useLiquidations,+ useMyLiquidations,+ useBorrowRate,+ useBorrowRates,+ useBorrowInterest,+} from './useDerivatives';+export type {+ FundingRateInfo,+ MarkPriceInfo,+ OpenInterestInfo,+ LiquidationInfo,+ BorrowRateInfo,+} from './useDerivatives';++// Options Trading+export {+ useGreeks,+ useOption,+ useOptionChain,+ useVolatilityHistory,+} from './useOptions';+export type {+ GreeksInfo,+ OptionContract,+ OptionChain,+ VolatilityData,+} from './useOptions';++// Conversions & Transfers+export {+ useConvertCurrencies,+ useConvertQuote,+ useCreateConvertTrade,+ useConvertTradeHistory,+ useTransfer,+ useAvailableAccounts,+} from './useConversions';+export type {+ ConvertQuote,+ ConvertTrade,+ TransferResult,+} from './useConversions';++// Leverage & Margin Management+export {+ useFetchLeverage,+ useSetLeverage,+ useLeverageTiers,+ useSetMarginMode,+ usePositionMode,+ useSetPositionMode,+ useCloseAllPositions,+} from './useLeverageManagement';+export type {+ LeverageSettings,+ LeverageTier,+ MarginModeInfo,+} from './useLeverageManagement';++// Advanced Market Data (OHLCV Variants, Sentiment, Settlements, Position History)+export {+ useMarkOHLCV,+ useIndexOHLCV,+ usePremiumIndexOHLCV,+ useLongShortRatioHistory,+ useSettlementHistory,+ useMySettlementHistory,+ usePositionHistory,+} from './useAdvancedMarketData';+export type {+ OHLCVCandle,+ LongShortRatio,+ SettlementInfo,+ MySettlementInfo,+ PositionHistoryItem,+} from './useAdvancedMarketData';++// Advanced Orders (Batch Orders, Market Orders with Cost, Cancel All)+export {+ useCreateOrders,+ useCreateMarketOrderWithCost,+ useCancelOrders,+ useCancelAllOrders,+ useCancelAllOrdersAfter,+ useEditOrder,+} from './useAdvancedOrders';+export type {+ OrderParams,+ BatchOrderResult,+ CancelOrderResult,+} from './useAdvancedOrders';++// Ledger & Transfer History+export {+ useLedger,+ useTransferHistory,+ useDepositWithdrawFees,+ useBorrowRateHistory,+ useFundingHistory,+ useIncomeHistory,+} from './useLedger';+export type {+ LedgerEntry,+ TransferEntry,+ DepositWithdrawFee,+ BorrowRateHistoryEntry,+ FundingHistoryEntry,+ IncomeEntry,+} from './useLedger';diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAccountInfo.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAccountInfo.tsindex 8064ff909..532944373 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAccountInfo.ts+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAccountInfo.ts@@ -228,6 +228,100 @@ export function useMarginInfo(autoRefresh: boolean = true) {};}+// ============================================================================+// LEVERAGE HOOK+// ============================================================================++export interface LeverageInfo {+ symbol: string;+ leverage: number;+ maxLeverage?: number;+ marginMode?: 'cross' | 'isolated';+}++export function useLeverage(symbol?: string) {+ const { activeAdapter, activeBroker } = useBrokerContext();+ const [leverageInfo, setLeverageInfo] = useState<LeverageInfo | null>(null);+ const [leverageTiers, setLeverageTiers] = useState<any[] | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchLeverage = useCallback(async () => {+ if (!activeAdapter || !activeAdapter.isConnected() || !symbol) {+ setLeverageInfo(null);+ return;+ }++ // Check if adapter supports fetchLeverage+ if (typeof (activeAdapter as any).fetchLeverage !== 'function') {+ setIsSupported(false);+ setLeverageInfo(null);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const rawLeverage = await (activeAdapter as any).fetchLeverage(symbol);++ setLeverageInfo({+ symbol,+ leverage: rawLeverage?.leverage || rawLeverage?.longLeverage || 1,+ maxLeverage: rawLeverage?.maxLeverage,+ marginMode: rawLeverage?.marginMode,+ });+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useLeverage] Failed to fetch leverage:', error);++ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ setError(error);+ setLeverageInfo(null);+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol]);++ const fetchTiers = useCallback(async () => {+ if (!activeAdapter || !activeAdapter.isConnected() || !symbol) {+ setLeverageTiers(null);+ return;+ }++ if (typeof (activeAdapter as any).fetchLeverageTiers !== 'function') {+ setLeverageTiers(null);+ return;+ }++ try {+ const tiers = await (activeAdapter as any).fetchLeverageTiers([symbol]);+ setLeverageTiers(tiers?.[symbol] || null);+ } catch (err) {+ console.error('[useLeverage] Failed to fetch leverage tiers:', err);+ setLeverageTiers(null);+ }+ }, [activeAdapter, symbol]);++ useEffect(() => {+ fetchLeverage();+ fetchTiers();+ }, [fetchLeverage, fetchTiers, activeBroker]);++ return {+ leverageInfo,+ leverageTiers,+ isLoading,+ error,+ isSupported,+ refresh: fetchLeverage,+ };+}+// ============================================================================// TRADING STATISTICS HOOK// ============================================================================diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAdvancedMarketData.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAdvancedMarketData.tsnew file mode 100644index 000000000..77fa650d7--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAdvancedMarketData.ts@@ -0,0 +1,527 @@+/**+ * Advanced Market Data Hooks+ * Mark OHLCV, Index OHLCV, Premium Index OHLCV, Long/Short Ratio+ */++import { useState, useEffect, useCallback } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';++// ============================================================================+// TYPES+// ============================================================================++export interface OHLCVCandle {+ timestamp: number;+ datetime: string;+ open: number;+ high: number;+ low: number;+ close: number;+ volume: number;+}++export interface LongShortRatio {+ symbol: string;+ longShortRatio: number;+ longAccount?: number;+ shortAccount?: number;+ timestamp: number;+ datetime: string;+ info?: any;+}++// ============================================================================+// MARK OHLCV HOOK+// ============================================================================++export function useMarkOHLCV(+ symbol?: string,+ timeframe: string = '1h',+ since?: number,+ limit: number = 100+) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [candles, setCandles] = useState<OHLCVCandle[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchMarkOHLCV = useCallback(async () => {+ if (tradingMode === 'paper' || !symbol) {+ setCandles([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setCandles([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchMarkOHLCV !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchMarkOHLCV(symbol, timeframe, since, limit);++ const normalized: OHLCVCandle[] = (raw || []).map((candle: any[]) => ({+ timestamp: candle[0],+ datetime: new Date(candle[0]).toISOString(),+ open: candle[1],+ high: candle[2],+ low: candle[3],+ close: candle[4],+ volume: candle[5] || 0,+ }));++ setCandles(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useMarkOHLCV] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, timeframe, since, limit, tradingMode]);++ useEffect(() => {+ fetchMarkOHLCV();+ }, [fetchMarkOHLCV]);++ return { candles, isLoading, error, isSupported, refresh: fetchMarkOHLCV };+}++// ============================================================================+// INDEX OHLCV HOOK+// ============================================================================++export function useIndexOHLCV(+ symbol?: string,+ timeframe: string = '1h',+ since?: number,+ limit: number = 100+) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [candles, setCandles] = useState<OHLCVCandle[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchIndexOHLCV = useCallback(async () => {+ if (tradingMode === 'paper' || !symbol) {+ setCandles([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setCandles([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchIndexOHLCV !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchIndexOHLCV(symbol, timeframe, since, limit);++ const normalized: OHLCVCandle[] = (raw || []).map((candle: any[]) => ({+ timestamp: candle[0],+ datetime: new Date(candle[0]).toISOString(),+ open: candle[1],+ high: candle[2],+ low: candle[3],+ close: candle[4],+ volume: candle[5] || 0,+ }));++ setCandles(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useIndexOHLCV] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, timeframe, since, limit, tradingMode]);++ useEffect(() => {+ fetchIndexOHLCV();+ }, [fetchIndexOHLCV]);++ return { candles, isLoading, error, isSupported, refresh: fetchIndexOHLCV };+}++// ============================================================================+// PREMIUM INDEX OHLCV HOOK+// ============================================================================++export function usePremiumIndexOHLCV(+ symbol?: string,+ timeframe: string = '1h',+ since?: number,+ limit: number = 100+) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [candles, setCandles] = useState<OHLCVCandle[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchPremiumIndexOHLCV = useCallback(async () => {+ if (tradingMode === 'paper' || !symbol) {+ setCandles([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setCandles([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchPremiumIndexOHLCV !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchPremiumIndexOHLCV(symbol, timeframe, since, limit);++ const normalized: OHLCVCandle[] = (raw || []).map((candle: any[]) => ({+ timestamp: candle[0],+ datetime: new Date(candle[0]).toISOString(),+ open: candle[1],+ high: candle[2],+ low: candle[3],+ close: candle[4],+ volume: candle[5] || 0,+ }));++ setCandles(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[usePremiumIndexOHLCV] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, timeframe, since, limit, tradingMode]);++ useEffect(() => {+ fetchPremiumIndexOHLCV();+ }, [fetchPremiumIndexOHLCV]);++ return { candles, isLoading, error, isSupported, refresh: fetchPremiumIndexOHLCV };+}++// ============================================================================+// LONG SHORT RATIO HISTORY HOOK+// ============================================================================++export function useLongShortRatioHistory(+ symbol?: string,+ timeframe: string = '1h',+ since?: number,+ limit: number = 100+) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [history, setHistory] = useState<LongShortRatio[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchHistory = useCallback(async () => {+ if (tradingMode === 'paper' || !symbol) {+ setHistory([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setHistory([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchLongShortRatioHistory !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchLongShortRatioHistory(symbol, timeframe, since, limit);++ const normalized: LongShortRatio[] = (raw || []).map((item: any) => ({+ symbol: item.symbol || symbol,+ longShortRatio: item.longShortRatio || item.ratio || 0,+ longAccount: item.longAccount || item.longPosition,+ shortAccount: item.shortAccount || item.shortPosition,+ timestamp: item.timestamp || Date.now(),+ datetime: item.datetime || new Date().toISOString(),+ info: item.info,+ }));++ setHistory(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useLongShortRatioHistory] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, timeframe, since, limit, tradingMode]);++ useEffect(() => {+ fetchHistory();+ }, [fetchHistory]);++ return { history, isLoading, error, isSupported, refresh: fetchHistory };+}++// ============================================================================+// SETTLEMENT HISTORY HOOK+// ============================================================================++export interface SettlementInfo {+ symbol: string;+ price: number;+ timestamp: number;+ datetime: string;+ info?: any;+}++export function useSettlementHistory(symbol?: string, since?: number, limit: number = 50) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [settlements, setSettlements] = useState<SettlementInfo[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchSettlements = useCallback(async () => {+ if (tradingMode === 'paper') {+ setSettlements([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setSettlements([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchSettlementHistory !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchSettlementHistory(symbol, since, limit);++ const normalized: SettlementInfo[] = (raw || []).map((item: any) => ({+ symbol: item.symbol,+ price: item.price || item.settlementPrice || 0,+ timestamp: item.timestamp || Date.now(),+ datetime: item.datetime || new Date().toISOString(),+ info: item.info,+ }));++ normalized.sort((a, b) => b.timestamp - a.timestamp);+ setSettlements(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useSettlementHistory] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, since, limit, tradingMode]);++ useEffect(() => {+ fetchSettlements();+ }, [fetchSettlements]);++ return { settlements, isLoading, error, isSupported, refresh: fetchSettlements };+}++// ============================================================================+// MY SETTLEMENT HISTORY HOOK+// ============================================================================++export interface MySettlementInfo extends SettlementInfo {+ amount: number;+ realizedPnl: number;+}++export function useMySettlementHistory(symbol?: string, since?: number, limit: number = 50) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [settlements, setSettlements] = useState<MySettlementInfo[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchMySettlements = useCallback(async () => {+ if (tradingMode === 'paper') {+ setSettlements([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setSettlements([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchMySettlementHistory !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchMySettlementHistory(symbol, since, limit);++ const normalized: MySettlementInfo[] = (raw || []).map((item: any) => ({+ symbol: item.symbol,+ price: item.price || item.settlementPrice || 0,+ amount: item.amount || item.quantity || 0,+ realizedPnl: item.realizedPnl || item.pnl || 0,+ timestamp: item.timestamp || Date.now(),+ datetime: item.datetime || new Date().toISOString(),+ info: item.info,+ }));++ normalized.sort((a, b) => b.timestamp - a.timestamp);+ setSettlements(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useMySettlementHistory] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, since, limit, tradingMode]);++ useEffect(() => {+ fetchMySettlements();+ }, [fetchMySettlements]);++ return { settlements, isLoading, error, isSupported, refresh: fetchMySettlements };+}++// ============================================================================+// POSITION HISTORY HOOK+// ============================================================================++export interface PositionHistoryItem {+ symbol: string;+ side: 'long' | 'short';+ entryPrice: number;+ exitPrice?: number;+ amount: number;+ realizedPnl: number;+ openTimestamp: number;+ closeTimestamp?: number;+ info?: any;+}++export function usePositionHistory(symbol?: string, since?: number, limit: number = 50) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [history, setHistory] = useState<PositionHistoryItem[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchHistory = useCallback(async () => {+ if (tradingMode === 'paper') {+ setHistory([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setHistory([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchPositionHistory !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchPositionHistory(symbol, since, limit);++ const normalized: PositionHistoryItem[] = (raw || []).map((item: any) => ({+ symbol: item.symbol,+ side: item.side === 'sell' || item.side === 'short' ? 'short' : 'long',+ entryPrice: item.entryPrice || item.avgEntryPrice || 0,+ exitPrice: item.exitPrice || item.avgExitPrice,+ amount: item.amount || item.contracts || 0,+ realizedPnl: item.realizedPnl || item.pnl || 0,+ openTimestamp: item.openTimestamp || item.createTime || Date.now(),+ closeTimestamp: item.closeTimestamp || item.updateTime,+ info: item.info,+ }));++ normalized.sort((a, b) => (b.closeTimestamp || b.openTimestamp) - (a.closeTimestamp || a.openTimestamp));+ setHistory(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[usePositionHistory] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, since, limit, tradingMode]);++ useEffect(() => {+ fetchHistory();+ }, [fetchHistory]);++ return { history, isLoading, error, isSupported, refresh: fetchHistory };+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAdvancedOrders.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAdvancedOrders.tsnew file mode 100644index 000000000..527427f36--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useAdvancedOrders.ts@@ -0,0 +1,500 @@+/**+ * Advanced Order Hooks+ * Batch orders, market orders with cost, cancel all orders+ */++import { useState, useCallback } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';++// ============================================================================+// TYPES+// ============================================================================++export interface OrderParams {+ symbol: string;+ type: 'market' | 'limit' | 'stop' | 'stopLimit';+ side: 'buy' | 'sell';+ amount: number;+ price?: number;+ stopPrice?: number;+ params?: Record<string, any>;+}++export interface BatchOrderResult {+ id: string;+ symbol: string;+ type: string;+ side: string;+ status: 'open' | 'closed' | 'canceled' | 'rejected';+ amount: number;+ price?: number;+ filled?: number;+ remaining?: number;+ error?: string;+ info?: any;+}++export interface CancelOrderResult {+ id: string;+ symbol: string;+ status: 'canceled' | 'failed';+ error?: string;+ info?: any;+}++// ============================================================================+// CREATE ORDERS (BATCH) HOOK+// ============================================================================++export function useCreateOrders() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [results, setResults] = useState<BatchOrderResult[]>([]);+ const [isSupported, setIsSupported] = useState(true);++ const createOrders = useCallback(+ async (orders: OrderParams[]) => {+ if (tradingMode === 'paper') {+ setError(new Error('Batch orders not available in paper trading mode'));+ return null;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setError(new Error('Not connected to exchange'));+ return null;+ }++ if (typeof (activeAdapter as any).createOrders !== 'function') {+ setIsSupported(false);+ setError(new Error('Batch orders not supported by this exchange'));+ return null;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).createOrders(orders);++ const normalized: BatchOrderResult[] = (raw || []).map((order: any) => ({+ id: order.id,+ symbol: order.symbol,+ type: order.type,+ side: order.side,+ status: order.status,+ amount: order.amount,+ price: order.price,+ filled: order.filled,+ remaining: order.remaining,+ error: order.error,+ info: order.info,+ }));++ setResults(normalized);+ setIsSupported(true);+ return normalized;+ } catch (err) {+ const error = err as Error;+ console.error('[useCreateOrders] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ return null;+ } finally {+ setIsLoading(false);+ }+ },+ [activeAdapter, tradingMode]+ );++ return { createOrders, isLoading, error, results, isSupported };+}++// ============================================================================+// CREATE MARKET ORDER WITH COST HOOK+// ============================================================================++export function useCreateMarketOrderWithCost() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [lastOrder, setLastOrder] = useState<BatchOrderResult | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const createMarketBuyWithCost = useCallback(+ async (symbol: string, cost: number, params?: Record<string, any>) => {+ if (tradingMode === 'paper') {+ setError(new Error('Not available in paper trading mode'));+ return null;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setError(new Error('Not connected to exchange'));+ return null;+ }++ if (typeof (activeAdapter as any).createMarketBuyOrderWithCost !== 'function') {+ setIsSupported(false);+ setError(new Error('Market order with cost not supported by this exchange'));+ return null;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).createMarketBuyOrderWithCost(symbol, cost, params);++ const order: BatchOrderResult = {+ id: raw.id,+ symbol: raw.symbol,+ type: raw.type,+ side: raw.side,+ status: raw.status,+ amount: raw.amount,+ price: raw.price || raw.average,+ filled: raw.filled,+ remaining: raw.remaining,+ info: raw.info,+ };++ setLastOrder(order);+ setIsSupported(true);+ return order;+ } catch (err) {+ const error = err as Error;+ console.error('[useCreateMarketOrderWithCost] Buy failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ return null;+ } finally {+ setIsLoading(false);+ }+ },+ [activeAdapter, tradingMode]+ );++ const createMarketSellWithCost = useCallback(+ async (symbol: string, cost: number, params?: Record<string, any>) => {+ if (tradingMode === 'paper') {+ setError(new Error('Not available in paper trading mode'));+ return null;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setError(new Error('Not connected to exchange'));+ return null;+ }++ if (typeof (activeAdapter as any).createMarketSellOrderWithCost !== 'function') {+ setIsSupported(false);+ setError(new Error('Market order with cost not supported by this exchange'));+ return null;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).createMarketSellOrderWithCost(symbol, cost, params);++ const order: BatchOrderResult = {+ id: raw.id,+ symbol: raw.symbol,+ type: raw.type,+ side: raw.side,+ status: raw.status,+ amount: raw.amount,+ price: raw.price || raw.average,+ filled: raw.filled,+ remaining: raw.remaining,+ info: raw.info,+ };++ setLastOrder(order);+ setIsSupported(true);+ return order;+ } catch (err) {+ const error = err as Error;+ console.error('[useCreateMarketOrderWithCost] Sell failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ return null;+ } finally {+ setIsLoading(false);+ }+ },+ [activeAdapter, tradingMode]+ );++ return { createMarketBuyWithCost, createMarketSellWithCost, isLoading, error, lastOrder, isSupported };+}++// ============================================================================+// CANCEL ORDERS (BATCH) HOOK+// ============================================================================++export function useCancelOrders() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [results, setResults] = useState<CancelOrderResult[]>([]);+ const [isSupported, setIsSupported] = useState(true);++ const cancelOrders = useCallback(+ async (orderIds: string[], symbol?: string) => {+ if (tradingMode === 'paper') {+ setError(new Error('Batch cancel not available in paper trading mode'));+ return null;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setError(new Error('Not connected to exchange'));+ return null;+ }++ if (typeof (activeAdapter as any).cancelOrders !== 'function') {+ setIsSupported(false);+ setError(new Error('Batch cancel not supported by this exchange'));+ return null;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).cancelOrders(orderIds, symbol);++ const normalized: CancelOrderResult[] = (raw || []).map((result: any, index: number) => ({+ id: result.id || orderIds[index],+ symbol: result.symbol || symbol,+ status: result.status === 'canceled' || result.success ? 'canceled' : 'failed',+ error: result.error,+ info: result.info,+ }));++ setResults(normalized);+ setIsSupported(true);+ return normalized;+ } catch (err) {+ const error = err as Error;+ console.error('[useCancelOrders] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ return null;+ } finally {+ setIsLoading(false);+ }+ },+ [activeAdapter, tradingMode]+ );++ return { cancelOrders, isLoading, error, results, isSupported };+}++// ============================================================================+// CANCEL ALL ORDERS HOOK+// ============================================================================++export function useCancelAllOrders() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [results, setResults] = useState<CancelOrderResult[]>([]);+ const [isSupported, setIsSupported] = useState(true);++ const cancelAllOrders = useCallback(+ async (symbol?: string, params?: { side?: 'buy' | 'sell' }) => {+ if (tradingMode === 'paper') {+ setError(new Error('Cancel all not available in paper trading mode'));+ return null;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setError(new Error('Not connected to exchange'));+ return null;+ }++ if (typeof (activeAdapter as any).cancelAllOrders !== 'function') {+ setIsSupported(false);+ setError(new Error('Cancel all orders not supported by this exchange'));+ return null;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).cancelAllOrders(symbol, params);++ const normalized: CancelOrderResult[] = Array.isArray(raw)+ ? raw.map((result: any) => ({+ id: result.id,+ symbol: result.symbol || symbol,+ status: 'canceled' as const,+ info: result.info,+ }))+ : [];++ setResults(normalized);+ setIsSupported(true);+ return normalized;+ } catch (err) {+ const error = err as Error;+ console.error('[useCancelAllOrders] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ return null;+ } finally {+ setIsLoading(false);+ }+ },+ [activeAdapter, tradingMode]+ );++ return { cancelAllOrders, isLoading, error, results, isSupported };+}++// ============================================================================+// CANCEL ALL ORDERS AFTER (TIMEOUT) HOOK+// ============================================================================++export function useCancelAllOrdersAfter() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);+ const [scheduledTime, setScheduledTime] = useState<number | null>(null);++ const cancelAllOrdersAfter = useCallback(+ async (timeout: number, params?: Record<string, any>) => {+ if (tradingMode === 'paper') {+ setError(new Error('Not available in paper trading mode'));+ return null;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setError(new Error('Not connected to exchange'));+ return null;+ }++ if (typeof (activeAdapter as any).cancelAllOrdersAfter !== 'function') {+ setIsSupported(false);+ setError(new Error('Cancel orders after timeout not supported by this exchange'));+ return null;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).cancelAllOrdersAfter(timeout, params);++ const cancelTime = raw?.triggerTime || Date.now() + timeout * 1000;+ setScheduledTime(cancelTime);+ setIsSupported(true);+ return { triggerTime: cancelTime, info: raw?.info };+ } catch (err) {+ const error = err as Error;+ console.error('[useCancelAllOrdersAfter] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ return null;+ } finally {+ setIsLoading(false);+ }+ },+ [activeAdapter, tradingMode]+ );++ return { cancelAllOrdersAfter, isLoading, error, scheduledTime, isSupported };+}++// ============================================================================+// EDIT ORDER HOOK+// ============================================================================++export function useEditOrder() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [lastResult, setLastResult] = useState<BatchOrderResult | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const editOrder = useCallback(+ async (+ orderId: string,+ symbol: string,+ type: string,+ side: 'buy' | 'sell',+ amount?: number,+ price?: number,+ params?: Record<string, any>+ ) => {+ if (tradingMode === 'paper') {+ setError(new Error('Edit order not available in paper trading mode'));+ return null;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setError(new Error('Not connected to exchange'));+ return null;+ }++ if (typeof (activeAdapter as any).editOrder !== 'function') {+ setIsSupported(false);+ setError(new Error('Edit order not supported by this exchange'));+ return null;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).editOrder(orderId, symbol, type, side, amount, price, params);++ const result: BatchOrderResult = {+ id: raw.id,+ symbol: raw.symbol,+ type: raw.type,+ side: raw.side,+ status: raw.status,+ amount: raw.amount,+ price: raw.price,+ filled: raw.filled,+ remaining: raw.remaining,+ info: raw.info,+ };++ setLastResult(result);+ setIsSupported(true);+ return result;+ } catch (err) {+ const error = err as Error;+ console.error('[useEditOrder] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ return null;+ } finally {+ setIsLoading(false);+ }+ },+ [activeAdapter, tradingMode]+ );++ return { editOrder, isLoading, error, lastResult, isSupported };+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useConversions.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useConversions.tsnew file mode 100644index 000000000..115523f72--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useConversions.ts@@ -0,0 +1,459 @@+/**+ * Conversion & Transfer Hooks+ * Crypto swap/convert, internal transfers between accounts+ */++import { useState, useEffect, useCallback } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';++// ============================================================================+// TYPES+// ============================================================================++export interface ConvertQuote {+ id?: string;+ fromCurrency: string;+ toCurrency: string;+ fromAmount: number;+ toAmount: number;+ rate: number;+ inverseRate: number;+ fee?: number;+ feeCurrency?: string;+ expireTime?: number;+ info?: any;+}++export interface ConvertTrade {+ id: string;+ fromCurrency: string;+ toCurrency: string;+ fromAmount: number;+ toAmount: number;+ rate: number;+ fee?: number;+ feeCurrency?: string;+ status: 'pending' | 'success' | 'failed';+ timestamp: number;+ datetime: string;+ info?: any;+}++export interface TransferResult {+ id: string;+ currency: string;+ amount: number;+ fromAccount: string;+ toAccount: string;+ status: 'pending' | 'success' | 'failed';+ timestamp: number;+ datetime: string;+ info?: any;+}++// ============================================================================+// CONVERT CURRENCIES HOOK+// ============================================================================++export function useConvertCurrencies() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [currencies, setCurrencies] = useState<string[]>([]);+ const [pairs, setPairs] = useState<{ from: string; to: string }[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchCurrencies = useCallback(async () => {+ if (tradingMode === 'paper') {+ setCurrencies([]);+ setPairs([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setCurrencies([]);+ setPairs([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchConvertCurrencies !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchConvertCurrencies();++ // Extract unique currencies and pairs+ const currencySet = new Set<string>();+ const pairList: { from: string; to: string }[] = [];++ if (Array.isArray(raw)) {+ for (const item of raw) {+ if (item.from) currencySet.add(item.from);+ if (item.to) currencySet.add(item.to);+ if (item.from && item.to) {+ pairList.push({ from: item.from, to: item.to });+ }+ }+ } else if (raw && typeof raw === 'object') {+ // Could be { BTC: ['USDT', 'ETH'], ... }+ for (const [from, toList] of Object.entries(raw)) {+ currencySet.add(from);+ if (Array.isArray(toList)) {+ for (const to of toList) {+ currencySet.add(to as string);+ pairList.push({ from, to: to as string });+ }+ }+ }+ }++ setCurrencies(Array.from(currencySet).sort());+ setPairs(pairList);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useConvertCurrencies] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, tradingMode]);++ useEffect(() => {+ fetchCurrencies();+ }, [fetchCurrencies]);++ return { currencies, pairs, isLoading, error, isSupported, refresh: fetchCurrencies };+}++// ============================================================================+// CONVERT QUOTE HOOK+// ============================================================================++export function useConvertQuote(fromCurrency?: string, toCurrency?: string, amount?: number) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [quote, setQuote] = useState<ConvertQuote | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchQuote = useCallback(async () => {+ if (tradingMode === 'paper' || !fromCurrency || !toCurrency || !amount || amount <= 0) {+ setQuote(null);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setQuote(null);+ return;+ }++ if (typeof (activeAdapter as any).fetchConvertQuote !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchConvertQuote(fromCurrency, toCurrency, amount);++ setQuote({+ id: raw.id,+ fromCurrency: raw.fromCurrency || fromCurrency,+ toCurrency: raw.toCurrency || toCurrency,+ fromAmount: raw.fromAmount || amount,+ toAmount: raw.toAmount || 0,+ rate: raw.rate || raw.price || 0,+ inverseRate: raw.inverseRate || (raw.rate ? 1 / raw.rate : 0),+ fee: raw.fee,+ feeCurrency: raw.feeCurrency,+ expireTime: raw.expireTime || raw.expires,+ info: raw.info,+ });+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useConvertQuote] Failed:', error);+ setError(error);+ setQuote(null);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, fromCurrency, toCurrency, amount, tradingMode]);++ useEffect(() => {+ fetchQuote();+ }, [fetchQuote]);++ return { quote, isLoading, error, isSupported, refresh: fetchQuote };+}++// ============================================================================+// CREATE CONVERT TRADE HOOK+// ============================================================================++export function useCreateConvertTrade() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [lastTrade, setLastTrade] = useState<ConvertTrade | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const createTrade = useCallback(+ async (fromCurrency: string, toCurrency: string, amount: number, quoteId?: string) => {+ if (tradingMode === 'paper') {+ setError(new Error('Conversions not available in paper trading mode'));+ return null;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setError(new Error('Not connected to exchange'));+ return null;+ }++ if (typeof (activeAdapter as any).createConvertTrade !== 'function') {+ setIsSupported(false);+ setError(new Error('Currency conversion not supported by this exchange'));+ return null;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).createConvertTrade(+ fromCurrency,+ toCurrency,+ amount,+ quoteId ? { quoteId } : undefined+ );++ const trade: ConvertTrade = {+ id: raw.id,+ fromCurrency: raw.fromCurrency || fromCurrency,+ toCurrency: raw.toCurrency || toCurrency,+ fromAmount: raw.fromAmount || amount,+ toAmount: raw.toAmount || 0,+ rate: raw.rate || raw.price || 0,+ fee: raw.fee,+ feeCurrency: raw.feeCurrency,+ status: raw.status === 'success' || raw.status === 'filled' ? 'success' : 'pending',+ timestamp: raw.timestamp || Date.now(),+ datetime: raw.datetime || new Date().toISOString(),+ info: raw.info,+ };++ setLastTrade(trade);+ setIsSupported(true);+ return trade;+ } catch (err) {+ const error = err as Error;+ console.error('[useCreateConvertTrade] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ return null;+ } finally {+ setIsLoading(false);+ }+ },+ [activeAdapter, tradingMode]+ );++ return { createTrade, isLoading, error, lastTrade, isSupported };+}++// ============================================================================+// CONVERT TRADE HISTORY HOOK+// ============================================================================++export function useConvertTradeHistory(code?: string, since?: number, limit: number = 50) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [history, setHistory] = useState<ConvertTrade[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchHistory = useCallback(async () => {+ if (tradingMode === 'paper') {+ setHistory([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setHistory([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchConvertTradeHistory !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchConvertTradeHistory(code, since, limit);++ const normalized: ConvertTrade[] = (raw || []).map((item: any) => ({+ id: item.id,+ fromCurrency: item.fromCurrency || item.from,+ toCurrency: item.toCurrency || item.to,+ fromAmount: item.fromAmount || 0,+ toAmount: item.toAmount || 0,+ rate: item.rate || item.price || 0,+ fee: item.fee,+ feeCurrency: item.feeCurrency,+ status: item.status === 'success' || item.status === 'filled' ? 'success' : item.status === 'failed' ? 'failed' : 'pending',+ timestamp: item.timestamp || Date.now(),+ datetime: item.datetime || new Date().toISOString(),+ info: item.info,+ }));++ normalized.sort((a, b) => b.timestamp - a.timestamp);+ setHistory(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useConvertTradeHistory] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, code, since, limit, tradingMode]);++ useEffect(() => {+ fetchHistory();+ }, [fetchHistory]);++ return { history, isLoading, error, isSupported, refresh: fetchHistory };+}++// ============================================================================+// TRANSFER HOOK+// ============================================================================++export function useTransfer() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [lastTransfer, setLastTransfer] = useState<TransferResult | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const transfer = useCallback(+ async (code: string, amount: number, fromAccount: string, toAccount: string) => {+ if (tradingMode === 'paper') {+ setError(new Error('Transfers not available in paper trading mode'));+ return null;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setError(new Error('Not connected to exchange'));+ return null;+ }++ if (typeof (activeAdapter as any).transfer !== 'function') {+ setIsSupported(false);+ setError(new Error('Internal transfers not supported by this exchange'));+ return null;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).transfer(code, amount, fromAccount, toAccount);++ const result: TransferResult = {+ id: raw.id,+ currency: raw.currency || code,+ amount: raw.amount || amount,+ fromAccount: raw.fromAccount || fromAccount,+ toAccount: raw.toAccount || toAccount,+ status: raw.status === 'ok' || raw.status === 'success' ? 'success' : 'pending',+ timestamp: raw.timestamp || Date.now(),+ datetime: raw.datetime || new Date().toISOString(),+ info: raw.info,+ };++ setLastTransfer(result);+ setIsSupported(true);+ return result;+ } catch (err) {+ const error = err as Error;+ console.error('[useTransfer] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ return null;+ } finally {+ setIsLoading(false);+ }+ },+ [activeAdapter, tradingMode]+ );++ return { transfer, isLoading, error, lastTransfer, isSupported };+}++// ============================================================================+// AVAILABLE ACCOUNTS HOOK (for transfer source/destination)+// ============================================================================++export function useAvailableAccounts() {+ const { activeBroker } = useBrokerContext();++ // Common account types across exchanges+ const commonAccounts = [+ { id: 'spot', name: 'Spot', description: 'Main trading account' },+ { id: 'margin', name: 'Margin', description: 'Cross margin account' },+ { id: 'futures', name: 'Futures', description: 'Futures/derivatives account' },+ { id: 'funding', name: 'Funding', description: 'Funding/wallet account' },+ ];++ // Exchange-specific accounts+ const exchangeAccounts: Record<string, typeof commonAccounts> = {+ binance: [+ ...commonAccounts,+ { id: 'isolated', name: 'Isolated Margin', description: 'Isolated margin account' },+ { id: 'coin_future', name: 'Coin-M Futures', description: 'Coin-margined futures' },+ ],+ bybit: [+ { id: 'SPOT', name: 'Spot', description: 'Spot trading account' },+ { id: 'CONTRACT', name: 'Derivatives', description: 'Derivatives account' },+ { id: 'FUND', name: 'Funding', description: 'Funding account' },+ { id: 'UNIFIED', name: 'Unified', description: 'Unified trading account' },+ ],+ okx: [+ { id: '18', name: 'Trading', description: 'Trading account' },+ { id: '6', name: 'Funding', description: 'Funding account' },+ ],+ kucoin: [+ { id: 'main', name: 'Main', description: 'Main account' },+ { id: 'trade', name: 'Trading', description: 'Trading account' },+ { id: 'margin', name: 'Margin', description: 'Margin account' },+ { id: 'contract', name: 'Futures', description: 'Futures account' },+ ],+ };++ return exchangeAccounts[activeBroker || ''] || commonAccounts;+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useDerivatives.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useDerivatives.tsnew file mode 100644index 000000000..ebc01153e--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useDerivatives.ts@@ -0,0 +1,809 @@+/**+ * Derivatives Hooks+ * Funding rates, mark prices, open interest, liquidations for futures/perpetuals+ */++import { useState, useEffect, useCallback } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';++// ============================================================================+// TYPES+// ============================================================================++export interface FundingRateInfo {+ symbol: string;+ fundingRate: number;+ fundingTimestamp?: number;+ fundingDatetime?: string;+ nextFundingRate?: number;+ nextFundingTimestamp?: number;+ nextFundingDatetime?: string;+ previousFundingRate?: number;+ previousFundingTimestamp?: number;+ info?: any;+}++export interface MarkPriceInfo {+ symbol: string;+ markPrice: number;+ indexPrice?: number;+ timestamp: number;+ datetime: string;+ info?: any;+}++export interface OpenInterestInfo {+ symbol: string;+ openInterestAmount: number;+ openInterestValue: number;+ timestamp: number;+ datetime: string;+ info?: any;+}++export interface LiquidationInfo {+ id: string;+ symbol: string;+ side: 'buy' | 'sell';+ type: string;+ price: number;+ amount: number;+ cost: number;+ timestamp: number;+ datetime: string;+ info?: any;+}++export interface BorrowRateInfo {+ currency: string;+ rate: number;+ period?: number; // In hours or days+ timestamp: number;+ datetime: string;+ info?: any;+}++// ============================================================================+// FUNDING RATE HOOKS+// ============================================================================++export function useFundingRate(symbol?: string) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [fundingRate, setFundingRate] = useState<FundingRateInfo | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchFundingRate = useCallback(async () => {+ if (tradingMode === 'paper' || !symbol) {+ setFundingRate(null);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setFundingRate(null);+ return;+ }++ if (typeof (activeAdapter as any).fetchFundingRate !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchFundingRate(symbol);++ setFundingRate({+ symbol: raw.symbol || symbol,+ fundingRate: raw.fundingRate || 0,+ fundingTimestamp: raw.fundingTimestamp,+ fundingDatetime: raw.fundingDatetime,+ nextFundingRate: raw.nextFundingRate,+ nextFundingTimestamp: raw.nextFundingTimestamp,+ nextFundingDatetime: raw.nextFundingDatetime,+ previousFundingRate: raw.previousFundingRate,+ previousFundingTimestamp: raw.previousFundingTimestamp,+ info: raw.info,+ });+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useFundingRate] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, tradingMode]);++ useEffect(() => {+ fetchFundingRate();+ const interval = setInterval(fetchFundingRate, 60000); // Update every minute+ return () => clearInterval(interval);+ }, [fetchFundingRate]);++ return { fundingRate, isLoading, error, isSupported, refresh: fetchFundingRate };+}++export function useFundingRates(symbols?: string[]) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [fundingRates, setFundingRates] = useState<FundingRateInfo[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchFundingRates = useCallback(async () => {+ if (tradingMode === 'paper') {+ setFundingRates([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setFundingRates([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchFundingRates !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchFundingRates(symbols);++ const normalized: FundingRateInfo[] = Object.entries(raw || {}).map(([sym, data]: [string, any]) => ({+ symbol: sym,+ fundingRate: data.fundingRate || 0,+ fundingTimestamp: data.fundingTimestamp,+ fundingDatetime: data.fundingDatetime,+ nextFundingRate: data.nextFundingRate,+ nextFundingTimestamp: data.nextFundingTimestamp,+ info: data.info,+ }));++ // Sort by absolute funding rate (highest first)+ normalized.sort((a, b) => Math.abs(b.fundingRate) - Math.abs(a.fundingRate));+ setFundingRates(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useFundingRates] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbols, tradingMode]);++ useEffect(() => {+ fetchFundingRates();+ const interval = setInterval(fetchFundingRates, 60000);+ return () => clearInterval(interval);+ }, [fetchFundingRates]);++ return { fundingRates, isLoading, error, isSupported, refresh: fetchFundingRates };+}++export function useFundingRateHistory(symbol?: string, since?: number, limit: number = 100) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [history, setHistory] = useState<FundingRateInfo[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchHistory = useCallback(async () => {+ if (tradingMode === 'paper' || !symbol) {+ setHistory([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setHistory([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchFundingRateHistory !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchFundingRateHistory(symbol, since, limit);++ const normalized: FundingRateInfo[] = (raw || []).map((item: any) => ({+ symbol: item.symbol || symbol,+ fundingRate: item.fundingRate || 0,+ fundingTimestamp: item.timestamp || item.fundingTimestamp,+ fundingDatetime: item.datetime || item.fundingDatetime,+ info: item.info,+ }));++ setHistory(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useFundingRateHistory] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, since, limit, tradingMode]);++ useEffect(() => {+ fetchHistory();+ }, [fetchHistory]);++ return { history, isLoading, error, isSupported, refresh: fetchHistory };+}++// ============================================================================+// MARK PRICE HOOKS+// ============================================================================++export function useMarkPrice(symbol?: string) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [markPrice, setMarkPrice] = useState<MarkPriceInfo | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchMarkPrice = useCallback(async () => {+ if (tradingMode === 'paper' || !symbol) {+ setMarkPrice(null);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setMarkPrice(null);+ return;+ }++ if (typeof (activeAdapter as any).fetchMarkPrice !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchMarkPrice(symbol);++ setMarkPrice({+ symbol: raw.symbol || symbol,+ markPrice: raw.markPrice || raw.mark || 0,+ indexPrice: raw.indexPrice || raw.index,+ timestamp: raw.timestamp || Date.now(),+ datetime: raw.datetime || new Date().toISOString(),+ info: raw.info,+ });+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useMarkPrice] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, tradingMode]);++ useEffect(() => {+ fetchMarkPrice();+ const interval = setInterval(fetchMarkPrice, 5000); // Update every 5s+ return () => clearInterval(interval);+ }, [fetchMarkPrice]);++ return { markPrice, isLoading, error, isSupported, refresh: fetchMarkPrice };+}++export function useMarkPrices(symbols?: string[]) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [markPrices, setMarkPrices] = useState<MarkPriceInfo[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchMarkPrices = useCallback(async () => {+ if (tradingMode === 'paper') {+ setMarkPrices([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setMarkPrices([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchMarkPrices !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchMarkPrices(symbols);++ const normalized: MarkPriceInfo[] = Object.entries(raw || {}).map(([sym, data]: [string, any]) => ({+ symbol: sym,+ markPrice: data.markPrice || data.mark || 0,+ indexPrice: data.indexPrice || data.index,+ timestamp: data.timestamp || Date.now(),+ datetime: data.datetime || new Date().toISOString(),+ info: data.info,+ }));++ setMarkPrices(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useMarkPrices] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbols, tradingMode]);++ useEffect(() => {+ fetchMarkPrices();+ const interval = setInterval(fetchMarkPrices, 5000);+ return () => clearInterval(interval);+ }, [fetchMarkPrices]);++ return { markPrices, isLoading, error, isSupported, refresh: fetchMarkPrices };+}++// ============================================================================+// OPEN INTEREST HOOKS+// ============================================================================++export function useOpenInterest(symbol?: string) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [openInterest, setOpenInterest] = useState<OpenInterestInfo | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchOpenInterest = useCallback(async () => {+ if (tradingMode === 'paper' || !symbol) {+ setOpenInterest(null);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setOpenInterest(null);+ return;+ }++ if (typeof (activeAdapter as any).fetchOpenInterest !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchOpenInterest(symbol);++ setOpenInterest({+ symbol: raw.symbol || symbol,+ openInterestAmount: raw.openInterestAmount || raw.openInterest || 0,+ openInterestValue: raw.openInterestValue || 0,+ timestamp: raw.timestamp || Date.now(),+ datetime: raw.datetime || new Date().toISOString(),+ info: raw.info,+ });+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useOpenInterest] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, tradingMode]);++ useEffect(() => {+ fetchOpenInterest();+ const interval = setInterval(fetchOpenInterest, 30000); // Update every 30s+ return () => clearInterval(interval);+ }, [fetchOpenInterest]);++ return { openInterest, isLoading, error, isSupported, refresh: fetchOpenInterest };+}++export function useOpenInterestHistory(symbol?: string, timeframe: string = '1h', since?: number, limit: number = 100) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [history, setHistory] = useState<OpenInterestInfo[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchHistory = useCallback(async () => {+ if (tradingMode === 'paper' || !symbol) {+ setHistory([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setHistory([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchOpenInterestHistory !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchOpenInterestHistory(symbol, timeframe, since, limit);++ const normalized: OpenInterestInfo[] = (raw || []).map((item: any) => ({+ symbol: item.symbol || symbol,+ openInterestAmount: item.openInterestAmount || item.openInterest || 0,+ openInterestValue: item.openInterestValue || 0,+ timestamp: item.timestamp || Date.now(),+ datetime: item.datetime || new Date().toISOString(),+ info: item.info,+ }));++ setHistory(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useOpenInterestHistory] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, timeframe, since, limit, tradingMode]);++ useEffect(() => {+ fetchHistory();+ }, [fetchHistory]);++ return { history, isLoading, error, isSupported, refresh: fetchHistory };+}++// ============================================================================+// LIQUIDATIONS HOOKS+// ============================================================================++export function useLiquidations(symbol?: string, since?: number, limit: number = 50) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [liquidations, setLiquidations] = useState<LiquidationInfo[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchLiquidations = useCallback(async () => {+ if (tradingMode === 'paper') {+ setLiquidations([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setLiquidations([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchLiquidations !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchLiquidations(symbol, since, limit);++ const normalized: LiquidationInfo[] = (raw || []).map((item: any) => ({+ id: item.id || `liq-${item.timestamp}`,+ symbol: item.symbol,+ side: item.side,+ type: item.type || 'liquidation',+ price: item.price || 0,+ amount: item.amount || 0,+ cost: item.cost || (item.price * item.amount) || 0,+ timestamp: item.timestamp || Date.now(),+ datetime: item.datetime || new Date().toISOString(),+ info: item.info,+ }));++ // Sort by timestamp descending+ normalized.sort((a, b) => b.timestamp - a.timestamp);+ setLiquidations(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useLiquidations] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, since, limit, tradingMode]);++ useEffect(() => {+ fetchLiquidations();+ const interval = setInterval(fetchLiquidations, 30000);+ return () => clearInterval(interval);+ }, [fetchLiquidations]);++ return { liquidations, isLoading, error, isSupported, refresh: fetchLiquidations };+}++export function useMyLiquidations(symbol?: string, since?: number, limit: number = 50) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [liquidations, setLiquidations] = useState<LiquidationInfo[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchMyLiquidations = useCallback(async () => {+ if (tradingMode === 'paper') {+ setLiquidations([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setLiquidations([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchMyLiquidations !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchMyLiquidations(symbol, since, limit);++ const normalized: LiquidationInfo[] = (raw || []).map((item: any) => ({+ id: item.id || `liq-${item.timestamp}`,+ symbol: item.symbol,+ side: item.side,+ type: item.type || 'liquidation',+ price: item.price || 0,+ amount: item.amount || 0,+ cost: item.cost || (item.price * item.amount) || 0,+ timestamp: item.timestamp || Date.now(),+ datetime: item.datetime || new Date().toISOString(),+ info: item.info,+ }));++ normalized.sort((a, b) => b.timestamp - a.timestamp);+ setLiquidations(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useMyLiquidations] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, since, limit, tradingMode]);++ useEffect(() => {+ fetchMyLiquidations();+ }, [fetchMyLiquidations]);++ return { liquidations, isLoading, error, isSupported, refresh: fetchMyLiquidations };+}++// ============================================================================+// BORROW RATE HOOKS+// ============================================================================++export function useBorrowRate(code?: string) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [borrowRate, setBorrowRate] = useState<BorrowRateInfo | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchBorrowRate = useCallback(async () => {+ if (tradingMode === 'paper' || !code) {+ setBorrowRate(null);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setBorrowRate(null);+ return;+ }++ if (typeof (activeAdapter as any).fetchBorrowRate !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchBorrowRate(code);++ setBorrowRate({+ currency: raw.currency || code,+ rate: raw.rate || 0,+ period: raw.period,+ timestamp: raw.timestamp || Date.now(),+ datetime: raw.datetime || new Date().toISOString(),+ info: raw.info,+ });+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useBorrowRate] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, code, tradingMode]);++ useEffect(() => {+ fetchBorrowRate();+ const interval = setInterval(fetchBorrowRate, 60000);+ return () => clearInterval(interval);+ }, [fetchBorrowRate]);++ return { borrowRate, isLoading, error, isSupported, refresh: fetchBorrowRate };+}++export function useBorrowRates() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [borrowRates, setBorrowRates] = useState<BorrowRateInfo[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchBorrowRates = useCallback(async () => {+ if (tradingMode === 'paper') {+ setBorrowRates([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setBorrowRates([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchBorrowRates !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchBorrowRates();++ const normalized: BorrowRateInfo[] = Object.entries(raw || {}).map(([currency, data]: [string, any]) => ({+ currency,+ rate: data.rate || 0,+ period: data.period,+ timestamp: data.timestamp || Date.now(),+ datetime: data.datetime || new Date().toISOString(),+ info: data.info,+ }));++ // Sort by rate descending+ normalized.sort((a, b) => b.rate - a.rate);+ setBorrowRates(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useBorrowRates] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, tradingMode]);++ useEffect(() => {+ fetchBorrowRates();+ const interval = setInterval(fetchBorrowRates, 60000);+ return () => clearInterval(interval);+ }, [fetchBorrowRates]);++ return { borrowRates, isLoading, error, isSupported, refresh: fetchBorrowRates };+}++export function useBorrowInterest(code?: string, symbol?: string, since?: number, limit: number = 50) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [interest, setInterest] = useState<any[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchBorrowInterest = useCallback(async () => {+ if (tradingMode === 'paper') {+ setInterest([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setInterest([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchBorrowInterest !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchBorrowInterest(code, symbol, since, limit);+ setInterest(raw || []);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useBorrowInterest] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, code, symbol, since, limit, tradingMode]);++ useEffect(() => {+ fetchBorrowInterest();+ }, [fetchBorrowInterest]);++ return { interest, isLoading, error, isSupported, refresh: fetchBorrowInterest };+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useExchangeStatus.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useExchangeStatus.tsnew file mode 100644index 000000000..97b73ba5d--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useExchangeStatus.ts@@ -0,0 +1,180 @@+/**+ * Exchange Status Hook+ * Fetches exchange operational status using fetchStatus+ */++import { useState, useEffect, useCallback } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';++export interface ExchangeStatus {+ status: 'ok' | 'maintenance' | 'degraded' | 'offline' | 'unknown';+ updated: number;+ eta?: string; // Estimated time for maintenance to end+ url?: string; // Status page URL+ info?: Record<string, any>;+}++export function useExchangeStatus(autoRefresh: boolean = true, refreshInterval: number = 30000) {+ const { activeAdapter, activeBroker, tradingMode } = useBrokerContext();+ const [status, setStatus] = useState<ExchangeStatus | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchStatus = useCallback(async () => {+ // For paper trading, always show as "ok"+ if (tradingMode === 'paper') {+ setStatus({+ status: 'ok',+ updated: Date.now(),+ });+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setStatus(null);+ return;+ }++ // Check if adapter supports fetchStatus+ if (typeof (activeAdapter as any).fetchStatus !== 'function') {+ setIsSupported(false);+ // Default to 'ok' if not supported but connected+ setStatus({+ status: 'ok',+ updated: Date.now(),+ });+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const rawStatus = await (activeAdapter as any).fetchStatus();++ // Normalize status response+ let normalizedStatus: 'ok' | 'maintenance' | 'degraded' | 'offline' | 'unknown' = 'unknown';++ if (rawStatus?.status) {+ const statusStr = String(rawStatus.status).toLowerCase();+ if (statusStr === 'ok' || statusStr === 'operational' || statusStr === 'online') {+ normalizedStatus = 'ok';+ } else if (statusStr === 'maintenance' || statusStr === 'scheduled') {+ normalizedStatus = 'maintenance';+ } else if (statusStr === 'degraded' || statusStr === 'partial' || statusStr === 'limited') {+ normalizedStatus = 'degraded';+ } else if (statusStr === 'offline' || statusStr === 'down' || statusStr === 'unavailable') {+ normalizedStatus = 'offline';+ }+ } else {+ // If we got a response but no status field, assume ok+ normalizedStatus = 'ok';+ }++ setStatus({+ status: normalizedStatus,+ updated: rawStatus?.updated || rawStatus?.timestamp || Date.now(),+ eta: rawStatus?.eta,+ url: rawStatus?.url,+ info: rawStatus?.info || rawStatus,+ });+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useExchangeStatus] Failed to fetch status:', error);+ setError(error);++ // If error, assume exchange might be having issues+ setStatus({+ status: 'unknown',+ updated: Date.now(),+ });++ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, tradingMode]);++ // Fetch on mount and when dependencies change+ useEffect(() => {+ fetchStatus();++ if (!autoRefresh) return;++ // Refresh status periodically+ const interval = setInterval(fetchStatus, refreshInterval);+ return () => clearInterval(interval);+ }, [fetchStatus, autoRefresh, refreshInterval, activeBroker]);++ return {+ status,+ isLoading,+ error,+ isSupported,+ refresh: fetchStatus,+ };+}++/**+ * Hook to get exchange server time+ */+export function useExchangeTime() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [serverTime, setServerTime] = useState<number | null>(null);+ const [latency, setLatency] = useState<number | null>(null);+ const [isLoading, setIsLoading] = useState(false);++ const fetchTime = useCallback(async () => {+ if (tradingMode === 'paper') {+ setServerTime(Date.now());+ setLatency(0);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setServerTime(null);+ setLatency(null);+ return;+ }++ if (typeof (activeAdapter as any).fetchTime !== 'function') {+ setServerTime(null);+ setLatency(null);+ return;+ }++ setIsLoading(true);++ try {+ const startTime = Date.now();+ const time = await (activeAdapter as any).fetchTime();+ const endTime = Date.now();++ setServerTime(time);+ setLatency(Math.round((endTime - startTime) / 2)); // Approximate one-way latency+ } catch (err) {+ console.error('[useExchangeTime] Failed to fetch time:', err);+ setServerTime(null);+ setLatency(null);+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, tradingMode]);++ useEffect(() => {+ fetchTime();+ const interval = setInterval(fetchTime, 10000); // Update every 10s+ return () => clearInterval(interval);+ }, [fetchTime]);++ return {+ serverTime,+ latency,+ isLoading,+ refresh: fetchTime,+ };+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useFunding.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useFunding.tsnew file mode 100644index 000000000..f20c3f8eb--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useFunding.ts@@ -0,0 +1,388 @@+/**+ * Funding Hooks+ * Handles deposits, withdrawals, and deposit addresses+ */++import { useState, useEffect, useCallback } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';++// ============================================================================+// TYPES+// ============================================================================++export interface UnifiedTransaction {+ id: string;+ txid?: string;+ type: 'deposit' | 'withdrawal';+ currency: string;+ amount: number;+ status: 'pending' | 'ok' | 'failed' | 'canceled';+ address?: string;+ tag?: string;+ fee?: {+ cost: number;+ currency: string;+ };+ timestamp: number;+ datetime: string;+ network?: string;+}++export interface DepositAddress {+ currency: string;+ address: string;+ tag?: string;+ network?: string;+ info?: any;+}++export interface WithdrawParams {+ code: string;+ amount: number;+ address: string;+ tag?: string;+ network?: string;+}++// ============================================================================+// DEPOSITS HOOK+// ============================================================================++export function useDeposits(currency?: string, limit: number = 50) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [deposits, setDeposits] = useState<UnifiedTransaction[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchDeposits = useCallback(async () => {+ if (tradingMode === 'paper') {+ setDeposits([]);+ setIsSupported(false);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setDeposits([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchDeposits !== 'function') {+ setIsSupported(false);+ setDeposits([]);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const rawDeposits = await (activeAdapter as any).fetchDeposits(currency, undefined, limit);++ const normalized: UnifiedTransaction[] = (rawDeposits || []).map((d: any) => ({+ id: d.id,+ txid: d.txid,+ type: 'deposit' as const,+ currency: d.currency,+ amount: d.amount || 0,+ status: normalizeStatus(d.status),+ address: d.address,+ tag: d.tag,+ fee: d.fee ? { cost: d.fee.cost || 0, currency: d.fee.currency || d.currency } : undefined,+ timestamp: d.timestamp || Date.now(),+ datetime: d.datetime || new Date().toISOString(),+ network: d.network,+ }));++ normalized.sort((a, b) => b.timestamp - a.timestamp);+ setDeposits(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useDeposits] Failed to fetch deposits:', error);+ setError(error);++ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, currency, limit, tradingMode]);++ useEffect(() => {+ fetchDeposits();+ }, [fetchDeposits]);++ return {+ deposits,+ isLoading,+ error,+ isSupported,+ refresh: fetchDeposits,+ };+}++// ============================================================================+// WITHDRAWALS HOOK+// ============================================================================++export function useWithdrawals(currency?: string, limit: number = 50) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [withdrawals, setWithdrawals] = useState<UnifiedTransaction[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchWithdrawals = useCallback(async () => {+ if (tradingMode === 'paper') {+ setWithdrawals([]);+ setIsSupported(false);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setWithdrawals([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchWithdrawals !== 'function') {+ setIsSupported(false);+ setWithdrawals([]);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const rawWithdrawals = await (activeAdapter as any).fetchWithdrawals(currency, undefined, limit);++ const normalized: UnifiedTransaction[] = (rawWithdrawals || []).map((w: any) => ({+ id: w.id,+ txid: w.txid,+ type: 'withdrawal' as const,+ currency: w.currency,+ amount: w.amount || 0,+ status: normalizeStatus(w.status),+ address: w.address,+ tag: w.tag,+ fee: w.fee ? { cost: w.fee.cost || 0, currency: w.fee.currency || w.currency } : undefined,+ timestamp: w.timestamp || Date.now(),+ datetime: w.datetime || new Date().toISOString(),+ network: w.network,+ }));++ normalized.sort((a, b) => b.timestamp - a.timestamp);+ setWithdrawals(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useWithdrawals] Failed to fetch withdrawals:', error);+ setError(error);++ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, currency, limit, tradingMode]);++ useEffect(() => {+ fetchWithdrawals();+ }, [fetchWithdrawals]);++ return {+ withdrawals,+ isLoading,+ error,+ isSupported,+ refresh: fetchWithdrawals,+ };+}++// ============================================================================+// DEPOSIT ADDRESS HOOK+// ============================================================================++export function useDepositAddress(currency?: string, network?: string) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [address, setAddress] = useState<DepositAddress | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchAddress = useCallback(async () => {+ if (tradingMode === 'paper' || !currency) {+ setAddress(null);+ setIsSupported(tradingMode !== 'paper');+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setAddress(null);+ return;+ }++ if (typeof (activeAdapter as any).fetchDepositAddress !== 'function') {+ setIsSupported(false);+ setAddress(null);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const params = network ? { network } : undefined;+ const rawAddress = await (activeAdapter as any).fetchDepositAddress(currency, params);++ setAddress({+ currency: rawAddress.currency || currency,+ address: rawAddress.address,+ tag: rawAddress.tag,+ network: rawAddress.network || network,+ info: rawAddress.info,+ });+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useDepositAddress] Failed to fetch address:', error);+ setError(error);+ setAddress(null);++ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, currency, network, tradingMode]);++ useEffect(() => {+ if (currency) {+ fetchAddress();+ }+ }, [fetchAddress, currency]);++ return {+ address,+ isLoading,+ error,+ isSupported,+ refresh: fetchAddress,+ };+}++// ============================================================================+// WITHDRAW HOOK+// ============================================================================++export function useWithdraw() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [lastResult, setLastResult] = useState<any | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const withdraw = useCallback(+ async ({ code, amount, address, tag, network }: WithdrawParams) => {+ if (tradingMode === 'paper') {+ setError(new Error('Withdrawals not available in paper trading mode'));+ return null;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setError(new Error('Not connected to exchange'));+ return null;+ }++ if (typeof (activeAdapter as any).withdraw !== 'function') {+ setIsSupported(false);+ setError(new Error('Withdrawals not supported by this exchange'));+ return null;+ }++ setIsLoading(true);+ setError(null);++ try {+ const params = network ? { network } : undefined;+ const result = await (activeAdapter as any).withdraw(code, amount, address, tag, params);+ setLastResult(result);+ setIsSupported(true);+ return result;+ } catch (err) {+ const error = err as Error;+ console.error('[useWithdraw] Withdrawal failed:', error);+ setError(error);++ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ return null;+ } finally {+ setIsLoading(false);+ }+ },+ [activeAdapter, tradingMode]+ );++ return {+ withdraw,+ isLoading,+ error,+ lastResult,+ isSupported,+ };+}++// ============================================================================+// COMBINED TRANSACTIONS HOOK+// ============================================================================++export function useTransactions(currency?: string, limit: number = 50) {+ const { deposits, isLoading: depositsLoading, error: depositsError, isSupported: depositsSupported, refresh: refreshDeposits } = useDeposits(currency, limit);+ const { withdrawals, isLoading: withdrawalsLoading, error: withdrawalsError, isSupported: withdrawalsSupported, refresh: refreshWithdrawals } = useWithdrawals(currency, limit);++ const transactions = [...deposits, ...withdrawals].sort((a, b) => b.timestamp - a.timestamp);++ const refresh = useCallback(() => {+ refreshDeposits();+ refreshWithdrawals();+ }, [refreshDeposits, refreshWithdrawals]);++ return {+ transactions,+ deposits,+ withdrawals,+ isLoading: depositsLoading || withdrawalsLoading,+ error: depositsError || withdrawalsError,+ isSupported: depositsSupported || withdrawalsSupported,+ refresh,+ };+}++// ============================================================================+// HELPERS+// ============================================================================++function normalizeStatus(status: string): 'pending' | 'ok' | 'failed' | 'canceled' {+ const statusLower = String(status || '').toLowerCase();++ if (statusLower === 'ok' || statusLower === 'success' || statusLower === 'completed' || statusLower === 'confirmed') {+ return 'ok';+ }+ if (statusLower === 'pending' || statusLower === 'processing' || statusLower === 'confirming') {+ return 'pending';+ }+ if (statusLower === 'failed' || statusLower === 'rejected' || statusLower === 'error') {+ return 'failed';+ }+ if (statusLower === 'canceled' || statusLower === 'cancelled') {+ return 'canceled';+ }++ return 'pending'; // Default to pending for unknown statuses+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useLedger.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useLedger.tsnew file mode 100644index 000000000..a99e4859e--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useLedger.ts@@ -0,0 +1,521 @@+/**+ * Ledger & Transfer History Hooks+ * Ledger entries, transfer history, deposit/withdraw fees+ */++import { useState, useEffect, useCallback } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';++// ============================================================================+// TYPES+// ============================================================================++export interface LedgerEntry {+ id: string;+ currency: string;+ account?: string;+ referenceAccount?: string;+ referenceId?: string;+ type: string;+ amount: number;+ before?: number;+ after?: number;+ fee?: number;+ timestamp: number;+ datetime: string;+ info?: any;+}++export interface TransferEntry {+ id: string;+ currency: string;+ amount: number;+ fromAccount: string;+ toAccount: string;+ status: string;+ timestamp: number;+ datetime: string;+ info?: any;+}++export interface DepositWithdrawFee {+ currency: string;+ network?: string;+ deposit?: {+ fee?: number;+ percentage?: boolean;+ };+ withdraw?: {+ fee?: number;+ percentage?: boolean;+ min?: number;+ max?: number;+ };+ info?: any;+}++// ============================================================================+// FETCH LEDGER HOOK+// ============================================================================++export function useLedger(+ code?: string,+ since?: number,+ limit: number = 100,+ params?: { type?: string }+) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [entries, setEntries] = useState<LedgerEntry[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchLedger = useCallback(async () => {+ if (tradingMode === 'paper') {+ setEntries([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setEntries([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchLedger !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchLedger(code, since, limit, params);++ const normalized: LedgerEntry[] = (raw || []).map((entry: any) => ({+ id: entry.id,+ currency: entry.currency,+ account: entry.account,+ referenceAccount: entry.referenceAccount,+ referenceId: entry.referenceId,+ type: entry.type,+ amount: entry.amount,+ before: entry.before,+ after: entry.after,+ fee: entry.fee?.cost || entry.fee,+ timestamp: entry.timestamp,+ datetime: entry.datetime || new Date(entry.timestamp).toISOString(),+ info: entry.info,+ }));++ normalized.sort((a, b) => b.timestamp - a.timestamp);+ setEntries(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useLedger] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, code, since, limit, params, tradingMode]);++ useEffect(() => {+ fetchLedger();+ }, [fetchLedger]);++ return { entries, isLoading, error, isSupported, refresh: fetchLedger };+}++// ============================================================================+// FETCH TRANSFERS HOOK+// ============================================================================++export function useTransferHistory(+ code?: string,+ since?: number,+ limit: number = 100+) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [transfers, setTransfers] = useState<TransferEntry[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchTransfers = useCallback(async () => {+ if (tradingMode === 'paper') {+ setTransfers([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setTransfers([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchTransfers !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchTransfers(code, since, limit);++ const normalized: TransferEntry[] = (raw || []).map((transfer: any) => ({+ id: transfer.id,+ currency: transfer.currency,+ amount: transfer.amount,+ fromAccount: transfer.fromAccount || transfer.from,+ toAccount: transfer.toAccount || transfer.to,+ status: transfer.status,+ timestamp: transfer.timestamp,+ datetime: transfer.datetime || new Date(transfer.timestamp).toISOString(),+ info: transfer.info,+ }));++ normalized.sort((a, b) => b.timestamp - a.timestamp);+ setTransfers(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useTransferHistory] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, code, since, limit, tradingMode]);++ useEffect(() => {+ fetchTransfers();+ }, [fetchTransfers]);++ return { transfers, isLoading, error, isSupported, refresh: fetchTransfers };+}++// ============================================================================+// FETCH DEPOSIT/WITHDRAW FEES HOOK+// ============================================================================++export function useDepositWithdrawFees(codes?: string[]) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [fees, setFees] = useState<Record<string, DepositWithdrawFee>>({});+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchFees = useCallback(async () => {+ if (tradingMode === 'paper') {+ setFees({});+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setFees({});+ return;+ }++ if (typeof (activeAdapter as any).fetchDepositWithdrawFees !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchDepositWithdrawFees(codes);++ const normalized: Record<string, DepositWithdrawFee> = {};++ for (const [currency, feeInfo] of Object.entries(raw || {})) {+ const info = feeInfo as any;+ normalized[currency] = {+ currency,+ network: info.network,+ deposit: info.deposit+ ? {+ fee: info.deposit.fee,+ percentage: info.deposit.percentage,+ }+ : undefined,+ withdraw: info.withdraw+ ? {+ fee: info.withdraw.fee,+ percentage: info.withdraw.percentage,+ min: info.withdraw.min,+ max: info.withdraw.max,+ }+ : undefined,+ info: info.info,+ };+ }++ setFees(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useDepositWithdrawFees] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, codes, tradingMode]);++ useEffect(() => {+ fetchFees();+ }, [fetchFees]);++ return { fees, isLoading, error, isSupported, refresh: fetchFees };+}++// ============================================================================+// FETCH BORROW RATE HISTORY HOOK+// ============================================================================++export interface BorrowRateHistoryEntry {+ currency: string;+ rate: number;+ timestamp: number;+ datetime: string;+ info?: any;+}++export function useBorrowRateHistory(+ code: string,+ since?: number,+ limit: number = 100+) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [history, setHistory] = useState<BorrowRateHistoryEntry[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchHistory = useCallback(async () => {+ if (tradingMode === 'paper' || !code) {+ setHistory([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setHistory([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchBorrowRateHistory !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchBorrowRateHistory(code, since, limit);++ const normalized: BorrowRateHistoryEntry[] = (raw || []).map((entry: any) => ({+ currency: entry.currency || code,+ rate: entry.rate || entry.borrowRate || 0,+ timestamp: entry.timestamp,+ datetime: entry.datetime || new Date(entry.timestamp).toISOString(),+ info: entry.info,+ }));++ normalized.sort((a, b) => b.timestamp - a.timestamp);+ setHistory(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useBorrowRateHistory] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, code, since, limit, tradingMode]);++ useEffect(() => {+ fetchHistory();+ }, [fetchHistory]);++ return { history, isLoading, error, isSupported, refresh: fetchHistory };+}++// ============================================================================+// FETCH FUNDING HISTORY HOOK+// ============================================================================++export interface FundingHistoryEntry {+ id: string;+ symbol: string;+ currency: string;+ amount: number;+ timestamp: number;+ datetime: string;+ info?: any;+}++export function useFundingHistory(+ symbol?: string,+ since?: number,+ limit: number = 100+) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [history, setHistory] = useState<FundingHistoryEntry[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchHistory = useCallback(async () => {+ if (tradingMode === 'paper') {+ setHistory([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setHistory([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchFundingHistory !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchFundingHistory(symbol, since, limit);++ const normalized: FundingHistoryEntry[] = (raw || []).map((entry: any) => ({+ id: entry.id,+ symbol: entry.symbol,+ currency: entry.currency,+ amount: entry.amount,+ timestamp: entry.timestamp,+ datetime: entry.datetime || new Date(entry.timestamp).toISOString(),+ info: entry.info,+ }));++ normalized.sort((a, b) => b.timestamp - a.timestamp);+ setHistory(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useFundingHistory] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, since, limit, tradingMode]);++ useEffect(() => {+ fetchHistory();+ }, [fetchHistory]);++ return { history, isLoading, error, isSupported, refresh: fetchHistory };+}++// ============================================================================+// FETCH INCOME HISTORY HOOK (Futures)+// ============================================================================++export interface IncomeEntry {+ id: string;+ symbol: string;+ incomeType: string;+ income: number;+ asset: string;+ timestamp: number;+ datetime: string;+ info?: any;+}++export function useIncomeHistory(+ incomeType?: string,+ symbol?: string,+ since?: number,+ limit: number = 100+) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [history, setHistory] = useState<IncomeEntry[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchHistory = useCallback(async () => {+ if (tradingMode === 'paper') {+ setHistory([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setHistory([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchIncomeHistory !== 'function') {+ // Try alternative method name+ if (typeof (activeAdapter as any).fetchIncome !== 'function') {+ setIsSupported(false);+ return;+ }+ }++ setIsLoading(true);+ setError(null);++ try {+ const method = (activeAdapter as any).fetchIncomeHistory || (activeAdapter as any).fetchIncome;+ const raw = await method(incomeType, symbol, since, limit);++ const normalized: IncomeEntry[] = (raw || []).map((entry: any) => ({+ id: entry.id,+ symbol: entry.symbol,+ incomeType: entry.incomeType || entry.type,+ income: entry.income || entry.amount,+ asset: entry.asset || entry.currency,+ timestamp: entry.timestamp || entry.time,+ datetime: entry.datetime || new Date(entry.timestamp || entry.time).toISOString(),+ info: entry.info,+ }));++ normalized.sort((a, b) => b.timestamp - a.timestamp);+ setHistory(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useIncomeHistory] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, incomeType, symbol, since, limit, tradingMode]);++ useEffect(() => {+ fetchHistory();+ }, [fetchHistory]);++ return { history, isLoading, error, isSupported, refresh: fetchHistory };+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useLeverageManagement.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useLeverageManagement.tsnew file mode 100644index 000000000..c21e92367--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useLeverageManagement.ts@@ -0,0 +1,453 @@+/**+ * Leverage Management Hooks+ * Set/fetch leverage, margin mode, leverage tiers+ */++import { useState, useEffect, useCallback } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';++// ============================================================================+// TYPES+// ============================================================================++export interface LeverageSettings {+ symbol: string;+ leverage: number;+ longLeverage?: number;+ shortLeverage?: number;+ maxLeverage?: number;+ marginMode?: 'cross' | 'isolated';+ info?: any;+}++export interface LeverageTier {+ tier: number;+ minNotional: number;+ maxNotional: number;+ maintenanceMarginRate: number;+ maxLeverage: number;+ info?: any;+}++export interface MarginModeInfo {+ symbol: string;+ marginMode: 'cross' | 'isolated';+ info?: any;+}++// ============================================================================+// FETCH LEVERAGE HOOK+// ============================================================================++export function useFetchLeverage(symbol?: string) {+ const { activeAdapter, tradingMode, activeBroker } = useBrokerContext();+ const [leverage, setLeverage] = useState<LeverageSettings | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchLeverage = useCallback(async () => {+ if (tradingMode === 'paper' || !symbol) {+ setLeverage(null);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setLeverage(null);+ return;+ }++ if (typeof (activeAdapter as any).fetchLeverage !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchLeverage(symbol);++ setLeverage({+ symbol: raw.symbol || symbol,+ leverage: raw.leverage || raw.longLeverage || 1,+ longLeverage: raw.longLeverage,+ shortLeverage: raw.shortLeverage,+ maxLeverage: raw.maxLeverage,+ marginMode: raw.marginMode,+ info: raw.info,+ });+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useFetchLeverage] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, tradingMode]);++ useEffect(() => {+ fetchLeverage();+ }, [fetchLeverage, activeBroker]);++ return { leverage, isLoading, error, isSupported, refresh: fetchLeverage };+}++// ============================================================================+// SET LEVERAGE HOOK+// ============================================================================++export function useSetLeverage() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [lastResult, setLastResult] = useState<LeverageSettings | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const setLeverage = useCallback(+ async (leverage: number, symbol: string, params?: { side?: 'long' | 'short' | 'both' }) => {+ if (tradingMode === 'paper') {+ setError(new Error('Cannot set leverage in paper trading mode'));+ return null;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setError(new Error('Not connected to exchange'));+ return null;+ }++ if (typeof (activeAdapter as any).setLeverage !== 'function') {+ setIsSupported(false);+ setError(new Error('Setting leverage not supported by this exchange'));+ return null;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).setLeverage(leverage, symbol, params);++ const result: LeverageSettings = {+ symbol,+ leverage: raw?.leverage || leverage,+ longLeverage: raw?.longLeverage,+ shortLeverage: raw?.shortLeverage,+ marginMode: raw?.marginMode,+ info: raw?.info,+ };++ setLastResult(result);+ setIsSupported(true);+ return result;+ } catch (err) {+ const error = err as Error;+ console.error('[useSetLeverage] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ return null;+ } finally {+ setIsLoading(false);+ }+ },+ [activeAdapter, tradingMode]+ );++ return { setLeverage, isLoading, error, lastResult, isSupported };+}++// ============================================================================+// FETCH LEVERAGE TIERS HOOK+// ============================================================================++export function useLeverageTiers(symbol?: string) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [tiers, setTiers] = useState<LeverageTier[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchTiers = useCallback(async () => {+ if (tradingMode === 'paper' || !symbol) {+ setTiers([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setTiers([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchLeverageTiers !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchLeverageTiers([symbol]);+ const symbolTiers = raw?.[symbol] || [];++ const normalized: LeverageTier[] = symbolTiers.map((tier: any, index: number) => ({+ tier: tier.tier || index + 1,+ minNotional: tier.minNotional || tier.notionalFloor || 0,+ maxNotional: tier.maxNotional || tier.notionalCap || Infinity,+ maintenanceMarginRate: tier.maintenanceMarginRate || tier.maintenanceMargin || 0,+ maxLeverage: tier.maxLeverage || 1,+ info: tier.info,+ }));++ setTiers(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useLeverageTiers] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, tradingMode]);++ useEffect(() => {+ fetchTiers();+ }, [fetchTiers]);++ return { tiers, isLoading, error, isSupported, refresh: fetchTiers };+}++// ============================================================================+// SET MARGIN MODE HOOK+// ============================================================================++export function useSetMarginMode() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [lastResult, setLastResult] = useState<MarginModeInfo | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const setMarginMode = useCallback(+ async (marginMode: 'cross' | 'isolated', symbol: string) => {+ if (tradingMode === 'paper') {+ setError(new Error('Cannot set margin mode in paper trading mode'));+ return null;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setError(new Error('Not connected to exchange'));+ return null;+ }++ if (typeof (activeAdapter as any).setMarginMode !== 'function') {+ setIsSupported(false);+ setError(new Error('Setting margin mode not supported by this exchange'));+ return null;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).setMarginMode(marginMode, symbol);++ const result: MarginModeInfo = {+ symbol,+ marginMode: raw?.marginMode || marginMode,+ info: raw?.info,+ };++ setLastResult(result);+ setIsSupported(true);+ return result;+ } catch (err) {+ const error = err as Error;+ console.error('[useSetMarginMode] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ return null;+ } finally {+ setIsLoading(false);+ }+ },+ [activeAdapter, tradingMode]+ );++ return { setMarginMode, isLoading, error, lastResult, isSupported };+}++// ============================================================================+// FETCH POSITION MODE HOOK+// ============================================================================++export function usePositionMode(symbol?: string) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [positionMode, setPositionMode] = useState<'one-way' | 'hedge' | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchPositionMode = useCallback(async () => {+ if (tradingMode === 'paper') {+ setPositionMode('one-way');+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setPositionMode(null);+ return;+ }++ if (typeof (activeAdapter as any).fetchPositionMode !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchPositionMode(symbol);++ // Normalize position mode+ const mode = raw?.hedged || raw?.dualSidePosition ? 'hedge' : 'one-way';+ setPositionMode(mode);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[usePositionMode] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, tradingMode]);++ useEffect(() => {+ fetchPositionMode();+ }, [fetchPositionMode]);++ return { positionMode, isLoading, error, isSupported, refresh: fetchPositionMode };+}++// ============================================================================+// SET POSITION MODE HOOK+// ============================================================================++export function useSetPositionMode() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const setPositionModeAction = useCallback(+ async (hedged: boolean, symbol?: string) => {+ if (tradingMode === 'paper') {+ setError(new Error('Cannot set position mode in paper trading mode'));+ return false;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setError(new Error('Not connected to exchange'));+ return false;+ }++ if (typeof (activeAdapter as any).setPositionMode !== 'function') {+ setIsSupported(false);+ setError(new Error('Setting position mode not supported by this exchange'));+ return false;+ }++ setIsLoading(true);+ setError(null);++ try {+ await (activeAdapter as any).setPositionMode(hedged, symbol);+ setIsSupported(true);+ return true;+ } catch (err) {+ const error = err as Error;+ console.error('[useSetPositionMode] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ return false;+ } finally {+ setIsLoading(false);+ }+ },+ [activeAdapter, tradingMode]+ );++ return { setPositionMode: setPositionModeAction, isLoading, error, isSupported };+}++// ============================================================================+// CLOSE ALL POSITIONS HOOK+// ============================================================================++export function useCloseAllPositions() {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [lastResult, setLastResult] = useState<any[] | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const closeAllPositions = useCallback(+ async (params?: { symbol?: string }) => {+ if (tradingMode === 'paper') {+ setError(new Error('Close all positions not available in paper trading mode'));+ return null;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setError(new Error('Not connected to exchange'));+ return null;+ }++ if (typeof (activeAdapter as any).closeAllPositions !== 'function') {+ setIsSupported(false);+ setError(new Error('Close all positions not supported by this exchange'));+ return null;+ }++ setIsLoading(true);+ setError(null);++ try {+ const result = await (activeAdapter as any).closeAllPositions(params);+ setLastResult(result);+ setIsSupported(true);+ return result;+ } catch (err) {+ const error = err as Error;+ console.error('[useCloseAllPositions] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ return null;+ } finally {+ setIsLoading(false);+ }+ },+ [activeAdapter, tradingMode]+ );++ return { closeAllPositions, isLoading, error, lastResult, isSupported };+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOptions.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOptions.tsnew file mode 100644index 000000000..3ef4c9576--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOptions.ts@@ -0,0 +1,349 @@+/**+ * Options Trading Hooks+ * Greeks, option chains, volatility for options trading+ */++import { useState, useEffect, useCallback } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';++// ============================================================================+// TYPES+// ============================================================================++export interface GreeksInfo {+ symbol: string;+ delta: number;+ gamma: number;+ theta: number;+ vega: number;+ rho?: number;+ impliedVolatility?: number;+ timestamp: number;+ info?: any;+}++export interface OptionContract {+ symbol: string;+ underlying: string;+ strike: number;+ expiry: number;+ expiryDatetime: string;+ optionType: 'call' | 'put';+ bid?: number;+ ask?: number;+ last?: number;+ volume?: number;+ openInterest?: number;+ greeks?: GreeksInfo;+ info?: any;+}++export interface OptionChain {+ underlying: string;+ expirations: number[];+ strikes: number[];+ calls: OptionContract[];+ puts: OptionContract[];+}++export interface VolatilityData {+ symbol: string;+ impliedVolatility: number;+ historicalVolatility?: number;+ timestamp: number;+ datetime: string;+}++// ============================================================================+// GREEKS HOOK+// ============================================================================++export function useGreeks(symbol?: string) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [greeks, setGreeks] = useState<GreeksInfo | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchGreeks = useCallback(async () => {+ if (tradingMode === 'paper' || !symbol) {+ setGreeks(null);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setGreeks(null);+ return;+ }++ if (typeof (activeAdapter as any).fetchGreeks !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchGreeks(symbol);++ setGreeks({+ symbol: raw.symbol || symbol,+ delta: raw.delta || 0,+ gamma: raw.gamma || 0,+ theta: raw.theta || 0,+ vega: raw.vega || 0,+ rho: raw.rho,+ impliedVolatility: raw.impliedVolatility || raw.iv,+ timestamp: raw.timestamp || Date.now(),+ info: raw.info,+ });+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useGreeks] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, tradingMode]);++ useEffect(() => {+ fetchGreeks();+ const interval = setInterval(fetchGreeks, 10000); // Update every 10s+ return () => clearInterval(interval);+ }, [fetchGreeks]);++ return { greeks, isLoading, error, isSupported, refresh: fetchGreeks };+}++// ============================================================================+// OPTION HOOK (Single Contract)+// ============================================================================++export function useOption(symbol?: string) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [option, setOption] = useState<OptionContract | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchOption = useCallback(async () => {+ if (tradingMode === 'paper' || !symbol) {+ setOption(null);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setOption(null);+ return;+ }++ if (typeof (activeAdapter as any).fetchOption !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchOption(symbol);++ setOption({+ symbol: raw.symbol || symbol,+ underlying: raw.underlying || raw.base,+ strike: raw.strike || 0,+ expiry: raw.expiry || raw.expiryTimestamp,+ expiryDatetime: raw.expiryDatetime || raw.expiry,+ optionType: raw.optionType || raw.type,+ bid: raw.bid,+ ask: raw.ask,+ last: raw.last || raw.lastPrice,+ volume: raw.volume,+ openInterest: raw.openInterest,+ greeks: raw.greeks,+ info: raw.info,+ });+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useOption] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, tradingMode]);++ useEffect(() => {+ fetchOption();+ const interval = setInterval(fetchOption, 5000);+ return () => clearInterval(interval);+ }, [fetchOption]);++ return { option, isLoading, error, isSupported, refresh: fetchOption };+}++// ============================================================================+// OPTION CHAIN HOOK+// ============================================================================++export function useOptionChain(underlyingSymbol?: string) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [chain, setChain] = useState<OptionChain | null>(null);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchOptionChain = useCallback(async () => {+ if (tradingMode === 'paper' || !underlyingSymbol) {+ setChain(null);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setChain(null);+ return;+ }++ if (typeof (activeAdapter as any).fetchOptionChain !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchOptionChain(underlyingSymbol);++ // Normalize option chain data+ const calls: OptionContract[] = [];+ const puts: OptionContract[] = [];+ const expirations = new Set<number>();+ const strikes = new Set<number>();++ // Process raw data - could be array or object+ const options = Array.isArray(raw) ? raw : Object.values(raw || {});++ for (const opt of options) {+ const contract: OptionContract = {+ symbol: opt.symbol,+ underlying: opt.underlying || opt.base || underlyingSymbol,+ strike: opt.strike || 0,+ expiry: opt.expiry || opt.expiryTimestamp || 0,+ expiryDatetime: opt.expiryDatetime || opt.expiry || '',+ optionType: opt.optionType || opt.type,+ bid: opt.bid,+ ask: opt.ask,+ last: opt.last || opt.lastPrice,+ volume: opt.volume,+ openInterest: opt.openInterest,+ greeks: opt.greeks,+ info: opt.info,+ };++ if (contract.expiry) expirations.add(contract.expiry);+ if (contract.strike) strikes.add(contract.strike);++ if (contract.optionType === 'call') {+ calls.push(contract);+ } else if (contract.optionType === 'put') {+ puts.push(contract);+ }+ }++ setChain({+ underlying: underlyingSymbol,+ expirations: Array.from(expirations).sort((a, b) => a - b),+ strikes: Array.from(strikes).sort((a, b) => a - b),+ calls: calls.sort((a, b) => a.strike - b.strike),+ puts: puts.sort((a, b) => a.strike - b.strike),+ });+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useOptionChain] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, underlyingSymbol, tradingMode]);++ useEffect(() => {+ fetchOptionChain();+ }, [fetchOptionChain]);++ return { chain, isLoading, error, isSupported, refresh: fetchOptionChain };+}++// ============================================================================+// VOLATILITY HISTORY HOOK+// ============================================================================++export function useVolatilityHistory(symbol?: string, timeframe: string = '1h', since?: number, limit: number = 100) {+ const { activeAdapter, tradingMode } = useBrokerContext();+ const [history, setHistory] = useState<VolatilityData[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchHistory = useCallback(async () => {+ if (tradingMode === 'paper' || !symbol) {+ setHistory([]);+ return;+ }++ if (!activeAdapter || !activeAdapter.isConnected()) {+ setHistory([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchVolatilityHistory !== 'function') {+ setIsSupported(false);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const raw = await (activeAdapter as any).fetchVolatilityHistory(symbol, timeframe, since, limit);++ const normalized: VolatilityData[] = (raw || []).map((item: any) => ({+ symbol: item.symbol || symbol,+ impliedVolatility: item.impliedVolatility || item.iv || 0,+ historicalVolatility: item.historicalVolatility || item.hv,+ timestamp: item.timestamp || Date.now(),+ datetime: item.datetime || new Date().toISOString(),+ }));++ setHistory(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useVolatilityHistory] Failed:', error);+ setError(error);+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, timeframe, since, limit, tradingMode]);++ useEffect(() => {+ fetchHistory();+ }, [fetchHistory]);++ return { history, isLoading, error, isSupported, refresh: fetchHistory };+}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useTrades.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useTrades.tsnew file mode 100644index 000000000..6dfc35ee2--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useTrades.ts@@ -0,0 +1,173 @@+/**+ * Trade History Hook+ * Fetches user's trade history using fetchMyTrades from the adapter+ */++import { useState, useEffect, useCallback } from 'react';+import { useBrokerContext } from '../../../../contexts/BrokerContext';++export interface UnifiedTrade {+ id: string;+ orderId?: string;+ symbol: string;+ side: 'buy' | 'sell';+ type?: string;+ price: number;+ quantity: number;+ cost: number;+ fee?: {+ cost: number;+ currency: string;+ };+ timestamp: number;+ datetime: string;+ takerOrMaker?: 'taker' | 'maker';+}++export function useTrades(symbol?: string, limit: number = 50, autoRefresh: boolean = false) {+ const { activeAdapter, activeBroker } = useBrokerContext();+ const [trades, setTrades] = useState<UnifiedTrade[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);+ const [isSupported, setIsSupported] = useState(true);++ const fetchTrades = useCallback(async () => {+ if (!activeAdapter || !activeAdapter.isConnected()) {+ setTrades([]);+ return;+ }++ // Check if exchange supports fetchMyTrades+ if (typeof (activeAdapter as any).fetchMyTrades !== 'function') {+ setIsSupported(false);+ setTrades([]);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const rawTrades = await (activeAdapter as any).fetchMyTrades(symbol, undefined, limit);++ const normalized: UnifiedTrade[] = (rawTrades || []).map((trade: any) => ({+ id: trade.id,+ orderId: trade.order,+ symbol: trade.symbol,+ side: trade.side,+ type: trade.type,+ price: trade.price || 0,+ quantity: trade.amount || 0,+ cost: trade.cost || (trade.price * trade.amount) || 0,+ fee: trade.fee ? {+ cost: trade.fee.cost || 0,+ currency: trade.fee.currency || 'USD',+ } : undefined,+ timestamp: trade.timestamp || Date.now(),+ datetime: trade.datetime || new Date().toISOString(),+ takerOrMaker: trade.takerOrMaker,+ }));++ // Sort by timestamp descending (newest first)+ normalized.sort((a, b) => b.timestamp - a.timestamp);+ setTrades(normalized);+ setIsSupported(true);+ } catch (err) {+ const error = err as Error;+ console.error('[useTrades] Failed to fetch trades:', error);+ setError(error);++ // Check if it's an "unsupported" error+ if (error.message?.includes('not supported')) {+ setIsSupported(false);+ }+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, symbol, limit]);++ // Fetch on mount and when dependencies change+ useEffect(() => {+ setTrades([]); // Clear trades when broker changes+ fetchTrades();++ if (!autoRefresh) return;++ const interval = setInterval(fetchTrades, 10000); // Refresh every 10s+ return () => clearInterval(interval);+ }, [fetchTrades, autoRefresh, activeBroker]);++ return {+ trades,+ isLoading,+ error,+ isSupported,+ refresh: fetchTrades,+ };+}++/**+ * Hook to fetch trades for a specific order+ */+export function useOrderTrades(orderId: string, symbol: string) {+ const { activeAdapter } = useBrokerContext();+ const [trades, setTrades] = useState<UnifiedTrade[]>([]);+ const [isLoading, setIsLoading] = useState(false);+ const [error, setError] = useState<Error | null>(null);++ const fetchOrderTrades = useCallback(async () => {+ if (!activeAdapter || !activeAdapter.isConnected() || !orderId || !symbol) {+ setTrades([]);+ return;+ }++ if (typeof (activeAdapter as any).fetchOrderTrades !== 'function') {+ setTrades([]);+ return;+ }++ setIsLoading(true);+ setError(null);++ try {+ const rawTrades = await (activeAdapter as any).fetchOrderTrades(orderId, symbol);++ const normalized: UnifiedTrade[] = (rawTrades || []).map((trade: any) => ({+ id: trade.id,+ orderId: trade.order,+ symbol: trade.symbol,+ side: trade.side,+ type: trade.type,+ price: trade.price || 0,+ quantity: trade.amount || 0,+ cost: trade.cost || 0,+ fee: trade.fee ? {+ cost: trade.fee.cost || 0,+ currency: trade.fee.currency || 'USD',+ } : undefined,+ timestamp: trade.timestamp || Date.now(),+ datetime: trade.datetime || new Date().toISOString(),+ takerOrMaker: trade.takerOrMaker,+ }));++ setTrades(normalized);+ } catch (err) {+ const error = err as Error;+ console.error('[useOrderTrades] Failed to fetch order trades:', error);+ setError(error);+ } finally {+ setIsLoading(false);+ }+ }, [activeAdapter, orderId, symbol]);++ useEffect(() => {+ fetchOrderTrades();+ }, [fetchOrderTrades]);++ return {+ trades,+ isLoading,+ error,+ refresh: fetchOrderTrades,+ };+}diff --git a/fincept-terminal-desktop/src/components/ui/tabs.tsx b/fincept-terminal-desktop/src/components/ui/tabs.tsxindex 497ba5ea3..7a7a34d8c 100644--- a/fincept-terminal-desktop/src/components/ui/tabs.tsx+++ b/fincept-terminal-desktop/src/components/ui/tabs.tsx@@ -52,12 +52,18 @@ function TabsTrigger({function TabsContent({className,+ forceMount,...props-}: React.ComponentProps<typeof TabsPrimitive.Content>) {+}: Omit<React.ComponentProps<typeof TabsPrimitive.Content>, 'forceMount'> & { forceMount?: boolean }) {return (<TabsPrimitive.Contentdata-slot="tabs-content"- className={cn("flex-1 outline-none", className)}+ forceMount={forceMount ? true : undefined}+ className={cn(+ "flex-1 outline-none",+ forceMount && "data-[state=inactive]:hidden",+ className+ )}{...props}/>)diff --git a/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx b/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsxindex 4ca2deadd..9a8b4a9c8 100644--- a/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx+++ b/fincept-terminal-desktop/src/contexts/StockBrokerContext.tsx@@ -26,6 +26,7 @@ import {stockBrokerSupportsTradingFeature,getStockBrokerDefaultSymbols,} from '../brokers/stocks';+import { BaseStockBrokerAdapter } from '../brokers/stocks/BaseStockBrokerAdapter';import type {IStockBrokerAdapter,@@ -265,19 +266,45 @@ export function StockBrokerProvider({ children }: StockBrokerProviderProps) {setIsLoading(true);try {- // Load saved broker preference- const savedBroker = await safeStorageGet(STORAGE_KEYS.ACTIVE_STOCK_BROKER);- if (savedBroker && STOCK_BROKER_REGISTRY[savedBroker]) {- setActiveBrokerState(savedBroker);- }-- // Load saved trading mode+ // Load saved trading mode firstconst savedModeStr = await safeStorageGet(STORAGE_KEYS.STOCK_TRADING_MODE);const savedMode = validateTradingMode(savedModeStr);if (savedMode) {setTradingModeState(savedMode);}+ // Load saved broker preference+ const savedBroker = await safeStorageGet(STORAGE_KEYS.ACTIVE_STOCK_BROKER);++ // If we have a saved broker, try to use it+ if (savedBroker && STOCK_BROKER_REGISTRY[savedBroker]) {+ console.log(`[StockBrokerContext] Found saved broker: ${savedBroker}`);+ setActiveBrokerState(savedBroker);+ } else {+ // No saved broker - scan all brokers to find one with valid session+ console.log('[StockBrokerContext] No saved broker, scanning for valid sessions...');+ const allBrokers = getAllStockBrokers();++ for (const broker of allBrokers) {+ try {+ const tempAdapter = createStockBrokerAdapter(broker.id);+ const creds = await (tempAdapter as any).loadCredentials?.();++ if (creds?.accessToken && creds?.tokenTimestamp) {+ // Check if token is valid for today (IST check for Indian brokers)+ const isValid = BaseStockBrokerAdapter.isTokenValidForTodayIST(creds.tokenTimestamp);+ if (isValid) {+ console.log(`[StockBrokerContext] Found valid session for: ${broker.id}`);+ setActiveBrokerState(broker.id);+ break;+ }+ }+ } catch (err) {+ // Skip broker if check fails+ }+ }+ }+console.log('[StockBrokerContext] Preferences loaded', {broker: savedBroker,mode: savedMode,diff --git a/fincept-terminal-desktop/src/services/agentService.ts b/fincept-terminal-desktop/src/services/agentService.tsnew file mode 100644index 000000000..f6b90f8dc--- /dev/null+++ b/fincept-terminal-desktop/src/services/agentService.ts@@ -0,0 +1,1182 @@+/**+ * Agent Service - High-Performance Centralized API for CoreAgent operations+ *+ * Features:+ * - Single entry point for all agent operations+ * - LRU caching with smart invalidation for static & response data+ * - Real-time streaming via Tauri events+ * - Parallel execution for batch operations+ * - Priority queue support for urgent queries+ * - Type-safe payload construction+ * - Error handling and retry logic+ */++import { invoke } from '@tauri-apps/api/core';+import { listen, UnlistenFn } from '@tauri-apps/api/event';++// =============================================================================+// Types+// =============================================================================++export interface AgentConfig {+ model: {+ provider: string;+ model_id: string;+ temperature?: number;+ max_tokens?: number;+ };+ instructions?: string;+ tools?: string[];+ name?: string;+ memory?: { enabled: boolean };+ reasoning?: boolean | { strategy: string };+ debug?: boolean;+}++export interface TeamConfig {+ name: string;+ mode: 'coordinate' | 'route' | 'collaborate';+ members: Array<{+ name: string;+ role?: string;+ model: AgentConfig['model'];+ tools?: string[];+ instructions?: string;+ }>;+}++export interface AgentPayload {+ action: string;+ api_keys?: Record<string, string>;+ user_id?: string;+ config?: AgentConfig;+ params?: Record<string, any>;+}++export interface AgentResponse<T = any> {+ success: boolean;+ error?: string;+ response?: string;+ data?: T;+ result?: any;+}++export interface SystemInfo {+ success: boolean;+ version: string;+ framework: string;+ capabilities: {+ model_providers: number;+ tools: number;+ tool_categories: string[];+ vectordbs: string[];+ embedders: string[];+ output_models: string[];+ };+ features: string[];+}++export interface ToolsInfo {+ success: boolean;+ tools: Record<string, string[]>;+ categories: string[];+ total_count: number;+}++export interface ModelsInfo {+ success: boolean;+ providers: string[];+ count: number;+}++// Streaming types+export interface StreamChunk {+ stream_id: string;+ chunk_type: 'token' | 'thinking' | 'tool_call' | 'tool_result' | 'done' | 'error' | 'agent_token' | 'agent_done';+ content: string;+ metadata?: Record<string, any>;+ sequence: number;+}++export interface StreamHandle {+ streamId: string;+ eventName: string;+ unlisten: UnlistenFn | null;+ cancel: () => Promise<void>;+}++export type StreamCallback = (chunk: StreamChunk) => void;++// Parallel execution types+export interface ParallelTask {+ action: string;+ config?: AgentConfig;+ params?: Record<string, any>;+}++export interface ParallelResult {+ task_id: string;+ success: boolean;+ result?: any;+ error?: string;+ execution_time_ms: number;+}++export interface BatchResponse {+ batch_id: string;+ results: ParallelResult[];+ total_time_ms: number;+ successful_count: number;+ failed_count: number;+}++// Priority levels+export enum AgentPriority {+ HIGH = 0,+ NORMAL = 1,+ LOW = 2,+}++// =============================================================================+// LRU Cache with Smart Invalidation+// =============================================================================++interface LRUEntry<T> {+ data: T;+ timestamp: number;+ ttl: number;+ accessCount: number;+ lastAccess: number;+}++class LRUCache {+ private cache = new Map<string, LRUEntry<any>>();+ private maxSize: number;+ private responseCache = new Map<string, LRUEntry<any>>(); // Separate cache for query responses++ constructor(maxSize = 100) {+ this.maxSize = maxSize;+ }++ set<T>(key: string, data: T, ttlMs: number = 5 * 60 * 1000): void {+ // Evict if at capacity+ if (this.cache.size >= this.maxSize) {+ this.evictLRU();+ }++ this.cache.set(key, {+ data,+ timestamp: Date.now(),+ ttl: ttlMs,+ accessCount: 1,+ lastAccess: Date.now(),+ });+ }++ get<T>(key: string): T | null {+ const entry = this.cache.get(key);+ if (!entry) return null;++ // Check TTL+ if (Date.now() - entry.timestamp > entry.ttl) {+ this.cache.delete(key);+ return null;+ }++ // Update access stats+ entry.accessCount++;+ entry.lastAccess = Date.now();++ return entry.data as T;+ }++ // Cache query responses with content-based key+ setResponse<T>(query: string, config: AgentConfig, data: T, ttlMs: number = 2 * 60 * 1000): void {+ const key = this.generateResponseKey(query, config);++ if (this.responseCache.size >= this.maxSize) {+ this.evictLRUResponse();+ }++ this.responseCache.set(key, {+ data,+ timestamp: Date.now(),+ ttl: ttlMs,+ accessCount: 1,+ lastAccess: Date.now(),+ });+ }++ getResponse<T>(query: string, config: AgentConfig): T | null {+ const key = this.generateResponseKey(query, config);+ const entry = this.responseCache.get(key);++ if (!entry) return null;++ if (Date.now() - entry.timestamp > entry.ttl) {+ this.responseCache.delete(key);+ return null;+ }++ entry.accessCount++;+ entry.lastAccess = Date.now();++ return entry.data as T;+ }++ private generateResponseKey(query: string, config: AgentConfig): string {+ // Create deterministic key from query and relevant config+ const configKey = `${config.model.provider}:${config.model.model_id}:${config.tools?.join(',') || ''}`;+ return `${query.slice(0, 100)}|${configKey}`;+ }++ private evictLRU(): void {+ let oldestKey: string | null = null;+ let oldestAccess = Infinity;++ for (const [key, entry] of this.cache) {+ if (entry.lastAccess < oldestAccess) {+ oldestAccess = entry.lastAccess;+ oldestKey = key;+ }+ }++ if (oldestKey) {+ this.cache.delete(oldestKey);+ }+ }++ private evictLRUResponse(): void {+ let oldestKey: string | null = null;+ let oldestAccess = Infinity;++ for (const [key, entry] of this.responseCache) {+ if (entry.lastAccess < oldestAccess) {+ oldestAccess = entry.lastAccess;+ oldestKey = key;+ }+ }++ if (oldestKey) {+ this.responseCache.delete(oldestKey);+ }+ }++ clear(): void {+ this.cache.clear();+ this.responseCache.clear();+ }++ invalidate(key: string): void {+ this.cache.delete(key);+ }++ invalidateResponses(): void {+ this.responseCache.clear();+ }++ getStats(): { cacheSize: number; responseCacheSize: number; maxSize: number } {+ return {+ cacheSize: this.cache.size,+ responseCacheSize: this.responseCache.size,+ maxSize: this.maxSize,+ };+ }+}++const cache = new LRUCache(100);++// =============================================================================+// Core Execution+// =============================================================================++/**+ * Execute a CoreAgent action with the given payload+ */+async function execute<T = any>(payload: AgentPayload): Promise<AgentResponse<T>> {+ try {+ const result = await invoke<string>('execute_core_agent', { payload });+ return JSON.parse(result) as AgentResponse<T>;+ } catch (error: any) {+ return {+ success: false,+ error: error?.message || String(error),+ };+ }+}++/**+ * Execute with priority (0=HIGH, 1=NORMAL, 2=LOW)+ */+async function executeWithPriority<T = any>(+ payload: AgentPayload,+ priority: AgentPriority = AgentPriority.NORMAL+): Promise<AgentResponse<T>> {+ try {+ const result = await invoke<string>('execute_agent_priority', { payload, priority });+ return JSON.parse(result) as AgentResponse<T>;+ } catch (error: any) {+ return {+ success: false,+ error: error?.message || String(error),+ };+ }+}++// =============================================================================+// Streaming Operations+// =============================================================================++/**+ * Run agent with real-time streaming+ * Returns a handle to control the stream+ */+export async function runAgentStreaming(+ query: string,+ config: AgentConfig,+ apiKeys: Record<string, string>,+ onChunk: StreamCallback,+ sessionId?: string+): Promise<StreamHandle> {+ const payload = {+ action: 'run',+ api_keys: apiKeys,+ config,+ params: { query, session_id: sessionId },+ };++ // Start streaming+ const result = await invoke<string>('execute_agent_streaming', { payload });+ const parsed = JSON.parse(result);++ if (!parsed.success) {+ throw new Error(parsed.error || 'Failed to start stream');+ }++ const streamId = parsed.stream_id;+ const eventName = parsed.event_name;++ // Subscribe to stream events+ const unlisten = await listen<StreamChunk>(eventName, (event) => {+ onChunk(event.payload);+ });++ return {+ streamId,+ eventName,+ unlisten,+ cancel: async () => {+ unlisten();+ await invoke('cancel_agent_stream', { streamId });+ },+ };+}++/**+ * Run team with streaming updates per agent+ */+export async function runTeamStreaming(+ query: string,+ teamConfig: TeamConfig,+ apiKeys: Record<string, string>,+ onChunk: StreamCallback,+ sessionId?: string+): Promise<StreamHandle> {+ const payload = {+ action: 'run_team',+ api_keys: apiKeys,+ params: { query, team_config: teamConfig, session_id: sessionId },+ };++ const result = await invoke<string>('execute_agent_streaming', { payload });+ const parsed = JSON.parse(result);++ if (!parsed.success) {+ throw new Error(parsed.error || 'Failed to start team stream');+ }++ const streamId = parsed.stream_id;+ const eventName = parsed.event_name;++ const unlisten = await listen<StreamChunk>(eventName, (event) => {+ onChunk(event.payload);+ });++ return {+ streamId,+ eventName,+ unlisten,+ cancel: async () => {+ unlisten();+ await invoke('cancel_agent_stream', { streamId });+ },+ };+}++/**+ * Get all active streams+ */+export async function getActiveStreams(): Promise<string[]> {+ const result = await invoke<string>('get_active_agent_streams');+ const parsed = JSON.parse(result);+ return parsed.active_streams || [];+}++// =============================================================================+// Parallel Execution+// =============================================================================++/**+ * Execute multiple agent tasks in parallel+ * Useful for batch analysis, multi-symbol research, etc.+ */+export async function runAgentsParallel(+ tasks: ParallelTask[],+ apiKeys: Record<string, string>,+ maxConcurrent: number = 4+): Promise<BatchResponse> {+ const payloads = tasks.map(task => ({+ action: task.action,+ api_keys: apiKeys,+ config: task.config,+ params: task.params,+ }));++ const result = await invoke<string>('execute_agents_parallel', {+ tasks: payloads,+ maxConcurrent,+ });++ return JSON.parse(result) as BatchResponse;+}++/**+ * Run stock analysis on multiple symbols in parallel+ */+export async function runBatchStockAnalysis(+ symbols: string[],+ apiKeys: Record<string, string>,+ config?: Partial<AgentConfig>,+ maxConcurrent: number = 4+): Promise<BatchResponse> {+ const tasks: ParallelTask[] = symbols.map(symbol => ({+ action: 'stock_analysis',+ config: config as AgentConfig,+ params: { symbol },+ }));++ return runAgentsParallel(tasks, apiKeys, maxConcurrent);+}++// =============================================================================+// Priority Execution+// =============================================================================++/**+ * Run agent with high priority (jumps the queue)+ */+export async function runAgentHighPriority(+ query: string,+ config: AgentConfig,+ apiKeys: Record<string, string>,+ sessionId?: string+): Promise<AgentResponse> {+ return executeWithPriority(+ {+ action: 'run',+ api_keys: apiKeys,+ config,+ params: { query, session_id: sessionId },+ },+ AgentPriority.HIGH+ );+}++/**+ * Run agent with low priority (background task)+ */+export async function runAgentLowPriority(+ query: string,+ config: AgentConfig,+ apiKeys: Record<string, string>,+ sessionId?: string+): Promise<AgentResponse> {+ return executeWithPriority(+ {+ action: 'run',+ api_keys: apiKeys,+ config,+ params: { query, session_id: sessionId },+ },+ AgentPriority.LOW+ );+}++// =============================================================================+// Cached Agent Operations+// =============================================================================++/**+ * Run agent with response caching+ * Identical queries with same config return cached results+ */+export async function runAgentCached(+ query: string,+ config: AgentConfig,+ apiKeys: Record<string, string>,+ sessionId?: string,+ cacheTtlMs: number = 2 * 60 * 1000+): Promise<AgentResponse> {+ // Check cache first+ const cached = cache.getResponse<AgentResponse>(query, config);+ if (cached) {+ return { ...cached, _cached: true } as AgentResponse & { _cached: boolean };+ }++ // Execute and cache+ const response = await execute({+ action: 'run',+ api_keys: apiKeys,+ config,+ params: { query, session_id: sessionId },+ });++ if (response.success) {+ cache.setResponse(query, config, response, cacheTtlMs);+ }++ return response;+}++// =============================================================================+// Standard Agent Operations+// =============================================================================++/**+ * Run a single agent query+ */+export async function runAgent(+ query: string,+ config: AgentConfig,+ apiKeys: Record<string, string>,+ sessionId?: string+): Promise<AgentResponse> {+ return execute({+ action: 'run',+ api_keys: apiKeys,+ config,+ params: { query, session_id: sessionId },+ });+}++/**+ * Run agent with structured output (Pydantic model)+ */+export async function runAgentStructured(+ query: string,+ config: AgentConfig,+ outputModel: string,+ apiKeys: Record<string, string>,+ sessionId?: string+): Promise<AgentResponse> {+ return execute({+ action: 'run_structured',+ api_keys: apiKeys,+ config,+ params: { query, output_model: outputModel, session_id: sessionId },+ });+}++/**+ * Run a multi-agent team+ */+export async function runTeam(+ query: string,+ teamConfig: TeamConfig,+ apiKeys: Record<string, string>,+ sessionId?: string+): Promise<AgentResponse> {+ return execute({+ action: 'run_team',+ api_keys: apiKeys,+ params: { query, team_config: teamConfig, session_id: sessionId },+ });+}++// =============================================================================+// Financial Workflows+// =============================================================================++/**+ * Run stock analysis workflow+ */+export async function runStockAnalysis(+ symbol: string,+ apiKeys: Record<string, string>,+ config?: Partial<AgentConfig>+): Promise<AgentResponse> {+ return execute({+ action: 'stock_analysis',+ api_keys: apiKeys,+ config: config as AgentConfig,+ params: { symbol },+ });+}++/**+ * Run portfolio rebalancing workflow+ */+export async function runPortfolioRebalancing(+ portfolioData: Record<string, any>,+ apiKeys: Record<string, string>,+ config?: Partial<AgentConfig>+): Promise<AgentResponse> {+ return execute({+ action: 'portfolio_rebal',+ api_keys: apiKeys,+ config: config as AgentConfig,+ params: { portfolio_data: portfolioData },+ });+}++/**+ * Run risk assessment workflow+ */+export async function runRiskAssessment(+ portfolioData: Record<string, any>,+ apiKeys: Record<string, string>,+ config?: Partial<AgentConfig>+): Promise<AgentResponse> {+ return execute({+ action: 'risk_assessment',+ api_keys: apiKeys,+ config: config as AgentConfig,+ params: { portfolio_data: portfolioData },+ });+}++// =============================================================================+// Memory & Knowledge+// =============================================================================++/**+ * Store a memory+ */+export async function storeMemory(+ content: string,+ memoryType: string = 'fact',+ metadata?: Record<string, any>+): Promise<AgentResponse<{ memory_id: number }>> {+ return execute({+ action: 'store_memory',+ params: { content, type: memoryType, metadata },+ });+}++/**+ * Recall memories+ */+export async function recallMemories(+ query?: string,+ memoryType?: string,+ limit: number = 5+): Promise<AgentResponse<{ memories: any[]; count: number }>> {+ return execute({+ action: 'recall_memories',+ params: { query, type: memoryType, limit },+ });+}++/**+ * Search knowledge base+ */+export async function searchKnowledge(+ query: string,+ limit: number = 5+): Promise<AgentResponse<{ results: any[]; count: number }>> {+ return execute({+ action: 'search',+ params: { query, limit },+ });+}++// =============================================================================+// Guardrails & Evaluation+// =============================================================================++/**+ * Check input against guardrails+ */+export async function checkGuardrails(+ text: string,+ context?: Record<string, any>+): Promise<AgentResponse<{ passed: boolean; violations: string[] }>> {+ return execute({+ action: 'check_guardrails',+ params: { text, context, check_type: 'input' },+ });+}++/**+ * Evaluate agent response+ */+export async function evaluateResponse(+ query: string,+ response: string,+ context?: Record<string, any>+): Promise<AgentResponse<{ passed: boolean; score: number; details: any }>> {+ return execute({+ action: 'evaluate',+ params: { query, response, context, type: 'response' },+ });+}++// =============================================================================+// System Information (Cached)+// =============================================================================++/**+ * Get system info (cached for 5 minutes)+ */+export async function getSystemInfo(forceRefresh = false): Promise<SystemInfo | null> {+ const cacheKey = 'system_info';++ if (!forceRefresh) {+ const cached = cache.get<SystemInfo>(cacheKey);+ if (cached) return cached;+ }++ const response = await execute<SystemInfo>({ action: 'system_info' });++ if (response.success) {+ const info = response as unknown as SystemInfo;+ cache.set(cacheKey, info, 5 * 60 * 1000); // 5 min TTL+ return info;+ }++ return null;+}++/**+ * Get available tools (cached for 10 minutes)+ */+export async function getTools(forceRefresh = false): Promise<ToolsInfo | null> {+ const cacheKey = 'tools_info';++ if (!forceRefresh) {+ const cached = cache.get<ToolsInfo>(cacheKey);+ if (cached) return cached;+ }++ const response = await execute<ToolsInfo>({ action: 'list_tools' });++ if (response.success) {+ const info = response as unknown as ToolsInfo;+ cache.set(cacheKey, info, 10 * 60 * 1000); // 10 min TTL+ return info;+ }++ return null;+}++/**+ * Get available models (cached for 10 minutes)+ */+export async function getModels(forceRefresh = false): Promise<ModelsInfo | null> {+ const cacheKey = 'models_info';++ if (!forceRefresh) {+ const cached = cache.get<ModelsInfo>(cacheKey);+ if (cached) return cached;+ }++ const response = await execute<ModelsInfo>({ action: 'list_models' });++ if (response.success) {+ const info = response as unknown as ModelsInfo;+ cache.set(cacheKey, info, 10 * 60 * 1000); // 10 min TTL+ return info;+ }++ return null;+}++/**+ * Get available output models (cached)+ */+export async function getOutputModels(forceRefresh = false): Promise<string[]> {+ const cacheKey = 'output_models';++ if (!forceRefresh) {+ const cached = cache.get<string[]>(cacheKey);+ if (cached) return cached;+ }++ const response = await execute<{ models: string[] }>({ action: 'list_outputs' });++ if (response.success && response.data?.models) {+ cache.set(cacheKey, response.data.models, 10 * 60 * 1000);+ return response.data.models;+ }++ // Default output models if API fails+ return [+ 'trade_signal',+ 'stock_analysis',+ 'portfolio_analysis',+ 'risk_assessment',+ 'market_analysis',+ 'research_report',+ ];+}++// =============================================================================+// Utility Functions+// =============================================================================++/**+ * Clear all caches+ */+export function clearCache(): void {+ cache.clear();+}++/**+ * Clear only response cache (keep static data)+ */+export function clearResponseCache(): void {+ cache.invalidateResponses();+}++/**+ * Get cache statistics+ */+export function getCacheStats(): { cacheSize: number; responseCacheSize: number; maxSize: number } {+ return cache.getStats();+}++/**+ * Pre-warm the agent system (call on app startup)+ */+export async function prewarmAgent(): Promise<void> {+ // Fetch and cache static data in parallel+ await Promise.all([+ getSystemInfo(),+ getTools(),+ getModels(),+ ]);+}++/**+ * Build agent config from UI state+ */+export function buildAgentConfig(+ provider: string,+ modelId: string,+ instructions: string,+ options?: {+ tools?: string[];+ temperature?: number;+ maxTokens?: number;+ reasoning?: boolean;+ memory?: boolean;+ }+): AgentConfig {+ return {+ model: {+ provider,+ model_id: modelId,+ temperature: options?.temperature ?? 0.7,+ max_tokens: options?.maxTokens ?? 4096,+ },+ instructions,+ tools: options?.tools ?? [],+ reasoning: options?.reasoning,+ memory: options?.memory ? { enabled: true } : undefined,+ };+}++/**+ * Build team config from UI state+ */+export function buildTeamConfig(+ name: string,+ mode: 'coordinate' | 'route' | 'collaborate',+ members: Array<{+ name: string;+ role?: string;+ provider: string;+ modelId: string;+ tools?: string[];+ instructions?: string;+ }>+): TeamConfig {+ return {+ name,+ mode,+ members: members.map(m => ({+ name: m.name,+ role: m.role,+ model: { provider: m.provider, model_id: m.modelId },+ tools: m.tools,+ instructions: m.instructions,+ })),+ };+}++// =============================================================================+// SuperAgent & Routing (v2.1)+// =============================================================================++export interface RoutingResult {+ success: boolean;+ intent: string;+ agent_id: string;+ confidence: number;+ matched_keywords: string[];+ matched_patterns: string[];+ config: Record<string, any>;+}++export interface AgentCard {+ id: string;+ name: string;+ description: string;+ category: string;+ version: string;+ provider: string;+ capabilities: string[];+ config: Record<string, any>;+}++/**+ * Route a query to the appropriate agent (SuperAgent)+ */+export async function routeQuery(+ query: string,+ apiKeys?: Record<string, string>+): Promise<RoutingResult> {+ try {+ const result = await invoke<string>('route_query', { query, apiKeys });+ return JSON.parse(result) as RoutingResult;+ } catch (error: any) {+ return {+ success: false,+ intent: 'general',+ agent_id: 'core_agent',+ confidence: 0,+ matched_keywords: [],+ matched_patterns: [],+ config: {},+ };+ }+}++/**+ * Execute query with automatic routing via SuperAgent+ */+export async function executeRoutedQuery(+ query: string,+ apiKeys?: Record<string, string>,+ sessionId?: string+): Promise<AgentResponse> {+ try {+ const result = await invoke<string>('execute_routed_query', {+ query,+ apiKeys,+ sessionId,+ });+ return JSON.parse(result) as AgentResponse;+ } catch (error: any) {+ return {+ success: false,+ error: error?.message || String(error),+ };+ }+}++/**+ * Discover all available agents+ */+export async function discoverAgents(): Promise<AgentCard[]> {+ try {+ const result = await invoke<string>('discover_agents');+ const parsed = JSON.parse(result);+ return parsed.agents || [];+ } catch {+ return [];+ }+}++// =============================================================================+// Execution Planner (v2.1)+// =============================================================================++export interface PlanStep {+ id: string;+ name: string;+ step_type: string;+ config: Record<string, any>;+ dependencies: string[];+ status: string;+ result?: any;+ error?: string;+}++export interface ExecutionPlan {+ id: string;+ name: string;+ description: string;+ steps: PlanStep[];+ context: Record<string, any>;+ status: string;+ is_complete: boolean;+ has_failed: boolean;+}++/**+ * Create a stock analysis execution plan+ */+export async function createStockAnalysisPlan(symbol: string): Promise<ExecutionPlan | null> {+ try {+ const result = await invoke<string>('create_stock_analysis_plan', { symbol });+ const parsed = JSON.parse(result);+ return parsed.plan || null;+ } catch {+ return null;+ }+}++/**+ * Execute an execution plan+ */+export async function executePlan(+ plan: ExecutionPlan,+ apiKeys?: Record<string, string>+): Promise<ExecutionPlan | null> {+ try {+ const result = await invoke<string>('execute_plan', { plan, apiKeys });+ return JSON.parse(result) as ExecutionPlan;+ } catch {+ return null;+ }+}++// =============================================================================+// Trade Decision Repository (v2.1)+// =============================================================================++export interface TradeDecision {+ id: string;+ competition_id: string;+ model_name: string;+ cycle_number: number;+ symbol: string;+ action: string;+ quantity: number;+ price?: number;+ reasoning: string;+ confidence: number;+}++/**+ * Save a trade decision to the repository+ */+export async function saveTradeDecision(+ decision: Omit<TradeDecision, 'id'>+): Promise<{ success: boolean; decision_id?: string; error?: string }> {+ try {+ const result = await invoke<string>('save_trade_decision', decision);+ return JSON.parse(result);+ } catch (error: any) {+ return { success: false, error: error?.message || String(error) };+ }+}++/**+ * Get trade decisions from repository+ */+export async function getTradeDecisions(filters?: {+ competition_id?: string;+ model_name?: string;+ cycle_number?: number;+ limit?: number;+}): Promise<TradeDecision[]> {+ try {+ const result = await invoke<string>('get_trade_decisions', filters || {});+ const parsed = JSON.parse(result);+ return parsed.decisions || [];+ } catch {+ return [];+ }+}++// =============================================================================+// Export default service object+// =============================================================================++export const agentService = {+ // Core+ runAgent,+ runAgentStructured,+ runTeam,++ // Streaming+ runAgentStreaming,+ runTeamStreaming,+ getActiveStreams,++ // Parallel Execution+ runAgentsParallel,+ runBatchStockAnalysis,++ // Priority Execution+ runAgentHighPriority,+ runAgentLowPriority,++ // Cached Execution+ runAgentCached,++ // Workflows+ runStockAnalysis,+ runPortfolioRebalancing,+ runRiskAssessment,++ // Memory+ storeMemory,+ recallMemories,+ searchKnowledge,++ // Guardrails+ checkGuardrails,+ evaluateResponse,++ // System (cached)+ getSystemInfo,+ getTools,+ getModels,+ getOutputModels,++ // SuperAgent & Routing (v2.1)+ routeQuery,+ executeRoutedQuery,+ discoverAgents,++ // Execution Planner (v2.1)+ createStockAnalysisPlan,+ executePlan,++ // Trade Decisions (v2.1)+ saveTradeDecision,+ getTradeDecisions,++ // Utils+ clearCache,+ clearResponseCache,+ getCacheStats,+ prewarmAgent,+ buildAgentConfig,+ buildTeamConfig,+};++export default agentService;diff --git a/fincept-terminal-desktop/src/services/core/brandKitService.ts b/fincept-terminal-desktop/src/services/core/brandKitService.tsnew file mode 100644index 000000000..274b08c39--- /dev/null+++ b/fincept-terminal-desktop/src/services/core/brandKitService.ts@@ -0,0 +1,636 @@+import { sqliteService, saveSetting, getSetting } from './sqliteService';++export interface BrandColor {+ id: string;+ name: string;+ hex: string;+ usage: 'primary' | 'secondary' | 'accent' | 'background' | 'text' | 'custom';+}++export interface BrandFont {+ id: string;+ name: string;+ family: string;+ weight: string;+ usage: 'heading' | 'body' | 'caption' | 'custom';+}++export interface BrandLogo {+ id: string;+ name: string;+ path: string;+ type: 'primary' | 'secondary' | 'icon' | 'watermark';+ width?: number;+ height?: number;+}++export interface BrandKit {+ id: string;+ name: string;+ description?: string;+ colors: BrandColor[];+ fonts: BrandFont[];+ logos: BrandLogo[];+ customCSS?: string;+ headerTemplate?: HeaderFooterTemplate;+ footerTemplate?: HeaderFooterTemplate;+ paragraphStyles: ParagraphStyles;+ created_at: string;+ updated_at: string;+ isDefault?: boolean;+}++export interface HeaderFooterTemplate {+ enabled: boolean;+ content: string;+ alignment: 'left' | 'center' | 'right';+ showPageNumbers: boolean;+ pageNumberFormat: 'numeric' | 'roman' | 'alphanumeric';+ pageNumberPosition: 'left' | 'center' | 'right';+ backgroundColor?: string;+ textColor?: string;+ fontSize?: number;+ height?: number;+ showLogo?: boolean;+ logoPosition?: 'left' | 'center' | 'right';+ showDate?: boolean;+ dateFormat?: string;+ borderBottom?: boolean;+ borderTop?: boolean;+}++export interface ParagraphStyles {+ lineHeight: number; // e.g., 1.5, 1.75, 2.0+ paragraphSpacing: number; // in px+ textIndent: number; // in px+ letterSpacing: number; // in px+ wordSpacing: number; // in px+ textAlign: 'left' | 'center' | 'right' | 'justify';+}++export interface ComponentTemplate {+ id: string;+ name: string;+ description?: string;+ category: 'text' | 'layout' | 'data' | 'media' | 'custom';+ component: {+ type: string;+ content: any;+ config: Record<string, any>;+ children?: any[];+ };+ styles?: string; // Custom CSS for this component+ thumbnail?: string;+ created_at: string;+ updated_at: string;+}++const BRAND_KITS_KEY = 'report_brand_kits';+const COMPONENT_TEMPLATES_KEY = 'report_component_templates';+const ACTIVE_BRAND_KIT_KEY = 'active_brand_kit_id';++class BrandKitService {+ private initialized = false;++ async initialize(): Promise<void> {+ if (this.initialized) return;+ await sqliteService.initialize();+ this.initialized = true;+ }++ // ============ Brand Kit Methods ============++ getDefaultBrandKit(): BrandKit {+ return {+ id: `brand-kit-${Date.now()}`,+ name: 'Default Brand Kit',+ description: 'Default styling for reports',+ colors: [+ { id: 'color-1', name: 'Primary', hex: '#FFA500', usage: 'primary' },+ { id: 'color-2', name: 'Secondary', hex: '#333333', usage: 'secondary' },+ { id: 'color-3', name: 'Accent', hex: '#4A90D9', usage: 'accent' },+ { id: 'color-4', name: 'Background', hex: '#FFFFFF', usage: 'background' },+ { id: 'color-5', name: 'Text', hex: '#1A1A1A', usage: 'text' },+ ],+ fonts: [+ { id: 'font-1', name: 'Heading Font', family: 'Georgia, serif', weight: '700', usage: 'heading' },+ { id: 'font-2', name: 'Body Font', family: 'Arial, sans-serif', weight: '400', usage: 'body' },+ { id: 'font-3', name: 'Caption Font', family: 'Arial, sans-serif', weight: '300', usage: 'caption' },+ ],+ logos: [],+ customCSS: '',+ headerTemplate: {+ enabled: true,+ content: '{company}',+ alignment: 'left',+ showPageNumbers: true,+ pageNumberFormat: 'numeric',+ pageNumberPosition: 'right',+ backgroundColor: '#FFFFFF',+ textColor: '#666666',+ fontSize: 10,+ height: 30,+ showLogo: false,+ showDate: true,+ dateFormat: 'MMMM DD, YYYY',+ borderBottom: true,+ },+ footerTemplate: {+ enabled: true,+ content: 'Confidential - {company}',+ alignment: 'center',+ showPageNumbers: true,+ pageNumberFormat: 'numeric',+ pageNumberPosition: 'center',+ backgroundColor: '#FFFFFF',+ textColor: '#999999',+ fontSize: 9,+ height: 25,+ showDate: false,+ borderTop: true,+ },+ paragraphStyles: {+ lineHeight: 1.6,+ paragraphSpacing: 12,+ textIndent: 0,+ letterSpacing: 0,+ wordSpacing: 0,+ textAlign: 'left',+ },+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ isDefault: true,+ };+ }++ async saveBrandKit(brandKit: BrandKit): Promise<void> {+ await this.initialize();+ const brandKits = await this.getAllBrandKits();+ const existingIndex = brandKits.findIndex(bk => bk.id === brandKit.id);++ brandKit.updated_at = new Date().toISOString();++ if (existingIndex >= 0) {+ brandKits[existingIndex] = brandKit;+ } else {+ brandKit.created_at = new Date().toISOString();+ brandKits.push(brandKit);+ }++ await saveSetting(BRAND_KITS_KEY, JSON.stringify(brandKits), 'reports');+ }++ async getAllBrandKits(): Promise<BrandKit[]> {+ await this.initialize();+ const stored = await getSetting(BRAND_KITS_KEY);+ if (!stored) {+ // Create default brand kit if none exists+ const defaultKit = this.getDefaultBrandKit();+ await this.saveBrandKit(defaultKit);+ return [defaultKit];+ }+ return JSON.parse(stored);+ }++ async getBrandKit(id: string): Promise<BrandKit | null> {+ const brandKits = await this.getAllBrandKits();+ return brandKits.find(bk => bk.id === id) || null;+ }++ async deleteBrandKit(id: string): Promise<void> {+ await this.initialize();+ const brandKits = await this.getAllBrandKits();+ const filtered = brandKits.filter(bk => bk.id !== id);+ await saveSetting(BRAND_KITS_KEY, JSON.stringify(filtered), 'reports');+ }++ async setActiveBrandKit(id: string): Promise<void> {+ await this.initialize();+ await saveSetting(ACTIVE_BRAND_KIT_KEY, id, 'reports');+ }++ async getActiveBrandKit(): Promise<BrandKit | null> {+ await this.initialize();+ const activeId = await getSetting(ACTIVE_BRAND_KIT_KEY);+ if (activeId) {+ return await this.getBrandKit(activeId);+ }+ // Return first brand kit or default+ const brandKits = await this.getAllBrandKits();+ return brandKits[0] || this.getDefaultBrandKit();+ }++ // ============ Component Template Methods ============++ async saveComponentTemplate(template: ComponentTemplate): Promise<void> {+ await this.initialize();+ const templates = await this.getAllComponentTemplates();+ const existingIndex = templates.findIndex(t => t.id === template.id);++ template.updated_at = new Date().toISOString();++ if (existingIndex >= 0) {+ templates[existingIndex] = template;+ } else {+ template.created_at = new Date().toISOString();+ templates.push(template);+ }++ await saveSetting(COMPONENT_TEMPLATES_KEY, JSON.stringify(templates), 'reports');+ }++ async getAllComponentTemplates(): Promise<ComponentTemplate[]> {+ await this.initialize();+ const stored = await getSetting(COMPONENT_TEMPLATES_KEY);+ if (!stored) {+ // Create default component templates+ const defaultTemplates = this.getDefaultComponentTemplates();+ for (const template of defaultTemplates) {+ await this.saveComponentTemplate(template);+ }+ return defaultTemplates;+ }+ return JSON.parse(stored);+ }++ async getComponentTemplate(id: string): Promise<ComponentTemplate | null> {+ const templates = await this.getAllComponentTemplates();+ return templates.find(t => t.id === id) || null;+ }++ async getComponentTemplatesByCategory(category: ComponentTemplate['category']): Promise<ComponentTemplate[]> {+ const templates = await this.getAllComponentTemplates();+ return templates.filter(t => t.category === category);+ }++ async deleteComponentTemplate(id: string): Promise<void> {+ await this.initialize();+ const templates = await this.getAllComponentTemplates();+ const filtered = templates.filter(t => t.id !== id);+ await saveSetting(COMPONENT_TEMPLATES_KEY, JSON.stringify(filtered), 'reports');+ }++ getDefaultComponentTemplates(): ComponentTemplate[] {+ return [+ {+ id: 'template-callout-info',+ name: 'Info Callout',+ description: 'Blue information callout box',+ category: 'text',+ component: {+ type: 'section',+ content: null,+ config: {+ sectionTitle: 'Note',+ sectionStyle: 'highlight',+ backgroundColor: '#EBF5FB',+ borderColor: '#3498DB',+ padding: '15px',+ },+ },+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ },+ {+ id: 'template-callout-warning',+ name: 'Warning Callout',+ description: 'Yellow warning callout box',+ category: 'text',+ component: {+ type: 'section',+ content: null,+ config: {+ sectionTitle: 'Warning',+ sectionStyle: 'highlight',+ backgroundColor: '#FEF9E7',+ borderColor: '#F1C40F',+ padding: '15px',+ },+ },+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ },+ {+ id: 'template-callout-success',+ name: 'Success Callout',+ description: 'Green success callout box',+ category: 'text',+ component: {+ type: 'section',+ content: null,+ config: {+ sectionTitle: 'Success',+ sectionStyle: 'highlight',+ backgroundColor: '#E8F8F5',+ borderColor: '#27AE60',+ padding: '15px',+ },+ },+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ },+ {+ id: 'template-callout-danger',+ name: 'Danger Callout',+ description: 'Red danger/error callout box',+ category: 'text',+ component: {+ type: 'section',+ content: null,+ config: {+ sectionTitle: 'Important',+ sectionStyle: 'highlight',+ backgroundColor: '#FDEDEC',+ borderColor: '#E74C3C',+ padding: '15px',+ },+ },+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ },+ {+ id: 'template-two-column-comparison',+ name: 'Two Column Comparison',+ description: 'Side by side comparison layout',+ category: 'layout',+ component: {+ type: 'columns',+ content: null,+ config: {+ columnCount: 2,+ padding: '20px',+ },+ children: [],+ },+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ },+ {+ id: 'template-three-column-metrics',+ name: 'Three Column Metrics',+ description: 'Three KPI metrics side by side',+ category: 'layout',+ component: {+ type: 'columns',+ content: null,+ config: {+ columnCount: 3,+ padding: '15px',+ },+ children: [],+ },+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ },+ {+ id: 'template-quote-block',+ name: 'Quote Block',+ description: 'Styled quote with attribution',+ category: 'text',+ component: {+ type: 'section',+ content: null,+ config: {+ sectionTitle: '',+ sectionStyle: 'sidebar',+ backgroundColor: '#F8F9FA',+ borderColor: '#6C757D',+ padding: '20px',+ },+ },+ styles: `+ font-style: italic;+ border-left: 4px solid #6C757D;+ margin: 20px 40px;+ `,+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ },+ {+ id: 'template-highlight-box',+ name: 'Highlight Box',+ description: 'Emphasized content box with orange accent',+ category: 'text',+ component: {+ type: 'section',+ content: null,+ config: {+ sectionTitle: 'Key Insight',+ sectionStyle: 'highlight',+ backgroundColor: '#FFF8E1',+ borderColor: '#FFA500',+ padding: '20px',+ },+ },+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ },+ ];+ }++ // ============ CSS Generation Methods ============++ generateCSSFromBrandKit(brandKit: BrandKit): string {+ const { colors, fonts, paragraphStyles, customCSS } = brandKit;++ let css = `/* Brand Kit: ${brandKit.name} */\n\n`;++ // CSS Variables for colors+ css += `:root {\n`;+ colors.forEach(color => {+ css += ` --brand-${color.usage}: ${color.hex};\n`;+ });+ css += `}\n\n`;++ // Typography+ const headingFont = fonts.find(f => f.usage === 'heading');+ const bodyFont = fonts.find(f => f.usage === 'body');+ const captionFont = fonts.find(f => f.usage === 'caption');++ if (headingFont) {+ css += `h1, h2, h3, h4, h5, h6, .heading {\n`;+ css += ` font-family: ${headingFont.family};\n`;+ css += ` font-weight: ${headingFont.weight};\n`;+ css += `}\n\n`;+ }++ if (bodyFont) {+ css += `body, p, .body-text {\n`;+ css += ` font-family: ${bodyFont.family};\n`;+ css += ` font-weight: ${bodyFont.weight};\n`;+ css += `}\n\n`;+ }++ if (captionFont) {+ css += `.caption, figcaption, .small-text {\n`;+ css += ` font-family: ${captionFont.family};\n`;+ css += ` font-weight: ${captionFont.weight};\n`;+ css += `}\n\n`;+ }++ // Paragraph styles+ css += `p, .paragraph {\n`;+ css += ` line-height: ${paragraphStyles.lineHeight};\n`;+ css += ` margin-bottom: ${paragraphStyles.paragraphSpacing}px;\n`;+ css += ` text-indent: ${paragraphStyles.textIndent}px;\n`;+ css += ` letter-spacing: ${paragraphStyles.letterSpacing}px;\n`;+ css += ` word-spacing: ${paragraphStyles.wordSpacing}px;\n`;+ css += ` text-align: ${paragraphStyles.textAlign};\n`;+ css += `}\n\n`;++ // Custom CSS+ if (customCSS) {+ css += `/* Custom CSS */\n${customCSS}\n`;+ }++ return css;+ }++ generateHeaderFooterCSS(template: HeaderFooterTemplate, type: 'header' | 'footer'): string {+ if (!template.enabled) return '';++ let css = `.report-${type} {\n`;+ css += ` background-color: ${template.backgroundColor || '#FFFFFF'};\n`;+ css += ` color: ${template.textColor || '#666666'};\n`;+ css += ` font-size: ${template.fontSize || 10}pt;\n`;+ css += ` height: ${template.height || 30}px;\n`;+ css += ` text-align: ${template.alignment};\n`;+ css += ` padding: 5px 20px;\n`;+ css += ` display: flex;\n`;+ css += ` align-items: center;\n`;+ css += ` justify-content: space-between;\n`;++ if (type === 'header' && template.borderBottom) {+ css += ` border-bottom: 1px solid #E0E0E0;\n`;+ }+ if (type === 'footer' && template.borderTop) {+ css += ` border-top: 1px solid #E0E0E0;\n`;+ }++ css += `}\n`;++ return css;+ }++ // ============ Utility Methods ============++ hexToRgb(hex: string): { r: number; g: number; b: number } | null {+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);+ return result ? {+ r: parseInt(result[1], 16),+ g: parseInt(result[2], 16),+ b: parseInt(result[3], 16)+ } : null;+ }++ rgbToHex(r: number, g: number, b: number): string {+ return '#' + [r, g, b].map(x => {+ const hex = x.toString(16);+ return hex.length === 1 ? '0' + hex : hex;+ }).join('');+ }++ // Common font families for selection+ getAvailableFonts(): { name: string; family: string }[] {+ return [+ { name: 'Arial', family: 'Arial, sans-serif' },+ { name: 'Helvetica', family: 'Helvetica, Arial, sans-serif' },+ { name: 'Times New Roman', family: '"Times New Roman", Times, serif' },+ { name: 'Georgia', family: 'Georgia, serif' },+ { name: 'Verdana', family: 'Verdana, sans-serif' },+ { name: 'Trebuchet MS', family: '"Trebuchet MS", sans-serif' },+ { name: 'Palatino', family: '"Palatino Linotype", Palatino, serif' },+ { name: 'Garamond', family: 'Garamond, serif' },+ { name: 'Courier New', family: '"Courier New", Courier, monospace' },+ { name: 'Lucida Console', family: '"Lucida Console", Monaco, monospace' },+ { name: 'Impact', family: 'Impact, sans-serif' },+ { name: 'Comic Sans MS', family: '"Comic Sans MS", cursive' },+ { name: 'Roboto', family: 'Roboto, sans-serif' },+ { name: 'Open Sans', family: '"Open Sans", sans-serif' },+ { name: 'Lato', family: 'Lato, sans-serif' },+ { name: 'Montserrat', family: 'Montserrat, sans-serif' },+ { name: 'Source Sans Pro', family: '"Source Sans Pro", sans-serif' },+ { name: 'Playfair Display', family: '"Playfair Display", serif' },+ { name: 'Merriweather', family: 'Merriweather, serif' },+ { name: 'Inter', family: 'Inter, sans-serif' },+ ];+ }++ // Preset brand kits for quick selection+ getPresetBrandKits(): Partial<BrandKit>[] {+ return [+ {+ name: 'Corporate Blue',+ colors: [+ { id: 'c1', name: 'Primary', hex: '#1E3A8A', usage: 'primary' },+ { id: 'c2', name: 'Secondary', hex: '#3B82F6', usage: 'secondary' },+ { id: 'c3', name: 'Accent', hex: '#FBBF24', usage: 'accent' },+ { id: 'c4', name: 'Background', hex: '#F8FAFC', usage: 'background' },+ { id: 'c5', name: 'Text', hex: '#1E293B', usage: 'text' },+ ],+ fonts: [+ { id: 'f1', name: 'Heading', family: '"Roboto", sans-serif', weight: '700', usage: 'heading' },+ { id: 'f2', name: 'Body', family: '"Open Sans", sans-serif', weight: '400', usage: 'body' },+ ],+ },+ {+ name: 'Modern Green',+ colors: [+ { id: 'c1', name: 'Primary', hex: '#059669', usage: 'primary' },+ { id: 'c2', name: 'Secondary', hex: '#10B981', usage: 'secondary' },+ { id: 'c3', name: 'Accent', hex: '#F59E0B', usage: 'accent' },+ { id: 'c4', name: 'Background', hex: '#ECFDF5', usage: 'background' },+ { id: 'c5', name: 'Text', hex: '#064E3B', usage: 'text' },+ ],+ fonts: [+ { id: 'f1', name: 'Heading', family: '"Montserrat", sans-serif', weight: '600', usage: 'heading' },+ { id: 'f2', name: 'Body', family: '"Lato", sans-serif', weight: '400', usage: 'body' },+ ],+ },+ {+ name: 'Classic Serif',+ colors: [+ { id: 'c1', name: 'Primary', hex: '#7C3AED', usage: 'primary' },+ { id: 'c2', name: 'Secondary', hex: '#A78BFA', usage: 'secondary' },+ { id: 'c3', name: 'Accent', hex: '#F472B6', usage: 'accent' },+ { id: 'c4', name: 'Background', hex: '#FFFBEB', usage: 'background' },+ { id: 'c5', name: 'Text', hex: '#44403C', usage: 'text' },+ ],+ fonts: [+ { id: 'f1', name: 'Heading', family: '"Playfair Display", serif', weight: '700', usage: 'heading' },+ { id: 'f2', name: 'Body', family: '"Merriweather", serif', weight: '400', usage: 'body' },+ ],+ },+ {+ name: 'Minimal Dark',+ colors: [+ { id: 'c1', name: 'Primary', hex: '#FFFFFF', usage: 'primary' },+ { id: 'c2', name: 'Secondary', hex: '#A3A3A3', usage: 'secondary' },+ { id: 'c3', name: 'Accent', hex: '#FFA500', usage: 'accent' },+ { id: 'c4', name: 'Background', hex: '#171717', usage: 'background' },+ { id: 'c5', name: 'Text', hex: '#FAFAFA', usage: 'text' },+ ],+ fonts: [+ { id: 'f1', name: 'Heading', family: '"Inter", sans-serif', weight: '600', usage: 'heading' },+ { id: 'f2', name: 'Body', family: '"Inter", sans-serif', weight: '400', usage: 'body' },+ ],+ },+ {+ name: 'Financial Pro',+ colors: [+ { id: 'c1', name: 'Primary', hex: '#0F172A', usage: 'primary' },+ { id: 'c2', name: 'Secondary', hex: '#334155', usage: 'secondary' },+ { id: 'c3', name: 'Accent', hex: '#22C55E', usage: 'accent' },+ { id: 'c4', name: 'Background', hex: '#FFFFFF', usage: 'background' },+ { id: 'c5', name: 'Text', hex: '#0F172A', usage: 'text' },+ ],+ fonts: [+ { id: 'f1', name: 'Heading', family: 'Georgia, serif', weight: '700', usage: 'heading' },+ { id: 'f2', name: 'Body', family: 'Arial, sans-serif', weight: '400', usage: 'body' },+ ],+ },+ ];+ }+}++export const brandKitService = new BrandKitService();diff --git a/fincept-terminal-desktop/src/services/core/reportExportService.ts b/fincept-terminal-desktop/src/services/core/reportExportService.tsnew file mode 100644index 000000000..2ada838a3--- /dev/null+++ b/fincept-terminal-desktop/src/services/core/reportExportService.ts@@ -0,0 +1,319 @@+import { invoke } from '@tauri-apps/api/core';+import { save } from '@tauri-apps/plugin-dialog';+import { writeTextFile } from '@tauri-apps/plugin-fs';+import { ReportTemplate, ReportComponent } from './reportService';+import { BrandKit } from './brandKitService';++export type ExportFormat = 'pdf' | 'html' | 'docx' | 'markdown';++export interface ExportOptions {+ format: ExportFormat;+ includeStyles?: boolean;+ includeHeader?: boolean;+ includeFooter?: boolean;+}++export interface BatchExportOptions {+ formats: ExportFormat[];+ basePath?: string;+}++class ReportExportService {+ // Generate HTML from template+ generateHTML(template: ReportTemplate, brandKit?: BrandKit | null): string {+ const styles = this.generateStyles(brandKit);+ const content = this.renderComponents(template.components, 'html');++ return `<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>${template.metadata.title || 'Report'}</title>+ <style>${styles}</style>+</head>+<body>+ <div class="report-container">+ <header class="report-header">+ <h1>${template.metadata.title || 'Report'}</h1>+ ${template.metadata.company ? `<p class="company">${template.metadata.company}</p>` : ''}+ ${template.metadata.author ? `<p class="author">By ${template.metadata.author}</p>` : ''}+ <p class="date">${template.metadata.date || new Date().toLocaleDateString()}</p>+ </header>+ <main class="report-content">+ ${content}+ </main>+ <footer class="report-footer">+ <p>© ${new Date().getFullYear()} ${template.metadata.company || ''}</p>+ </footer>+ </div>+</body>+</html>`;+ }++ // Generate Markdown from template+ generateMarkdown(template: ReportTemplate): string {+ let md = `# ${template.metadata.title || 'Report'}\n\n`;++ if (template.metadata.company) md += `**${template.metadata.company}**\n\n`;+ if (template.metadata.author) md += `*By ${template.metadata.author}*\n\n`;+ if (template.metadata.date) md += `Date: ${template.metadata.date}\n\n`;++ md += '---\n\n';+ md += this.renderComponents(template.components, 'markdown');++ return md;+ }++ // Generate DOCX XML structure+ generateDocxContent(template: ReportTemplate): string {+ const content = this.renderComponents(template.components, 'docx');++ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">+ <w:body>+ <w:p>+ <w:pPr><w:pStyle w:val="Title"/></w:pPr>+ <w:r><w:t>${template.metadata.title || 'Report'}</w:t></w:r>+ </w:p>+ ${template.metadata.company ? `<w:p><w:r><w:t>${template.metadata.company}</w:t></w:r></w:p>` : ''}+ ${template.metadata.author ? `<w:p><w:r><w:t>By ${template.metadata.author}</w:t></w:r></w:p>` : ''}+ <w:p><w:r><w:t>${template.metadata.date || ''}</w:t></w:r></w:p>+ ${content}+ </w:body>+</w:document>`;+ }++ // Render components to different formats+ private renderComponents(components: ReportComponent[], format: 'html' | 'markdown' | 'docx'): string {+ return components.map(comp => this.renderComponent(comp, format)).join('\n');+ }++ private renderComponent(comp: ReportComponent, format: 'html' | 'markdown' | 'docx'): string {+ const content = comp.content || '';++ switch (format) {+ case 'html':+ return this.renderComponentHTML(comp, content);+ case 'markdown':+ return this.renderComponentMarkdown(comp, content);+ case 'docx':+ return this.renderComponentDocx(comp, content);+ default:+ return '';+ }+ }++ private renderComponentHTML(comp: ReportComponent, content: string): string {+ switch (comp.type) {+ case 'heading':+ return `<h2 class="heading" style="text-align:${comp.config.alignment || 'left'}">${content}</h2>`;+ case 'subheading':+ return `<h3 class="subheading" style="text-align:${comp.config.alignment || 'left'}">${content}</h3>`;+ case 'text':+ return `<p style="text-align:${comp.config.alignment || 'left'}">${content}</p>`;+ case 'divider':+ return '<hr class="divider"/>';+ case 'code':+ return `<pre class="code-block"><code>${this.escapeHtml(content)}</code></pre>`;+ case 'table':+ return this.renderTableHTML(comp);+ case 'image':+ return comp.config.imageUrl ? `<img src="file://${comp.config.imageUrl}" alt="Report Image" class="report-image"/>` : '';+ case 'section':+ return `<section class="section" style="border-left:4px solid ${comp.config.borderColor || '#FFA500'};background:${comp.config.backgroundColor || '#f8f9fa'};padding:${comp.config.padding || '15px'}">+ <h4>${comp.config.sectionTitle || 'Section'}</h4>+ ${comp.children ? this.renderComponents(comp.children, 'html') : ''}+ </section>`;+ case 'columns':+ return `<div class="columns columns-${comp.config.columnCount || 2}">+ ${comp.children ? comp.children.map(c => `<div class="column">${this.renderComponent(c, 'html')}</div>`).join('') : ''}+ </div>`;+ case 'pagebreak':+ return '<div class="page-break"></div>';+ case 'coverpage':+ return `<div class="cover-page" style="background:${comp.config.backgroundColor || '#0a0a0a'};color:#FFA500;text-align:center;padding:100px 50px;">+ <h1>${content}</h1>+ ${comp.config.subtitle ? `<p class="subtitle">${comp.config.subtitle}</p>` : ''}+ </div>`;+ default:+ return `<div>${content}</div>`;+ }+ }++ private renderComponentMarkdown(comp: ReportComponent, content: string): string {+ switch (comp.type) {+ case 'heading':+ return `## ${content}\n\n`;+ case 'subheading':+ return `### ${content}\n\n`;+ case 'text':+ return `${content}\n\n`;+ case 'divider':+ return '---\n\n';+ case 'code':+ return `\`\`\`\n${content}\n\`\`\`\n\n`;+ case 'table':+ return this.renderTableMarkdown(comp);+ case 'image':+ return comp.config.imageUrl ? `\n\n` : '';+ case 'section':+ return `> **${comp.config.sectionTitle || 'Section'}**\n>\n> ${comp.children ? this.renderComponents(comp.children, 'markdown').replace(/\n/g, '\n> ') : ''}\n\n`;+ case 'pagebreak':+ return '\n---\n<div style="page-break-after: always;"></div>\n\n';+ case 'coverpage':+ return `# ${content}\n\n${comp.config.subtitle ? `*${comp.config.subtitle}*\n\n` : ''}---\n\n`;+ default:+ return `${content}\n\n`;+ }+ }++ private renderComponentDocx(comp: ReportComponent, content: string): string {+ const escaped = this.escapeXml(content);+ switch (comp.type) {+ case 'heading':+ return `<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>${escaped}</w:t></w:r></w:p>`;+ case 'subheading':+ return `<w:p><w:pPr><w:pStyle w:val="Heading2"/></w:pPr><w:r><w:t>${escaped}</w:t></w:r></w:p>`;+ case 'text':+ return `<w:p><w:r><w:t>${escaped}</w:t></w:r></w:p>`;+ case 'divider':+ return `<w:p><w:pPr><w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="auto"/></w:pBdr></w:pPr></w:p>`;+ case 'code':+ return `<w:p><w:pPr><w:pStyle w:val="Code"/></w:pPr><w:r><w:rPr><w:rFonts w:ascii="Courier New"/></w:rPr><w:t>${escaped}</w:t></w:r></w:p>`;+ default:+ return `<w:p><w:r><w:t>${escaped}</w:t></w:r></w:p>`;+ }+ }++ private renderTableHTML(comp: ReportComponent): string {+ const columns = comp.config.columns || ['Column 1', 'Column 2', 'Column 3'];+ const rows = (comp.content as any)?.rows || [columns.map(() => 'Sample data')];++ return `<table class="report-table">+ <thead><tr>${columns.map(c => `<th>${c}</th>`).join('')}</tr></thead>+ <tbody>${rows.map((row: string[]) => `<tr>${row.map(cell => `<td>${cell}</td>`).join('')}</tr>`).join('')}</tbody>+ </table>`;+ }++ private renderTableMarkdown(comp: ReportComponent): string {+ const columns = comp.config.columns || ['Column 1', 'Column 2', 'Column 3'];+ const rows = (comp.content as any)?.rows || [columns.map(() => 'Sample data')];++ let md = `| ${columns.join(' | ')} |\n`;+ md += `| ${columns.map(() => '---').join(' | ')} |\n`;+ rows.forEach((row: string[]) => {+ md += `| ${row.join(' | ')} |\n`;+ });+ return md + '\n';+ }++ private generateStyles(brandKit?: BrandKit | null): string {+ const primary = brandKit?.colors.find(c => c.usage === 'primary')?.hex || '#FFA500';+ const text = brandKit?.colors.find(c => c.usage === 'text')?.hex || '#1a1a1a';+ const bg = brandKit?.colors.find(c => c.usage === 'background')?.hex || '#ffffff';+ const bodyFont = brandKit?.fonts.find(f => f.usage === 'body')?.family || 'Arial, sans-serif';+ const headingFont = brandKit?.fonts.find(f => f.usage === 'heading')?.family || 'Georgia, serif';++ return `+ * { margin: 0; padding: 0; box-sizing: border-box; }+ body { font-family: ${bodyFont}; color: ${text}; background: ${bg}; line-height: 1.6; }+ .report-container { max-width: 210mm; margin: 0 auto; padding: 20mm; }+ .report-header { border-bottom: 2px solid ${primary}; padding-bottom: 20px; margin-bottom: 30px; }+ .report-header h1 { font-family: ${headingFont}; font-size: 28pt; color: ${text}; }+ .report-header .company { font-size: 14pt; color: #666; }+ .report-header .author, .report-header .date { font-size: 11pt; color: #888; }+ .heading { font-family: ${headingFont}; font-size: 18pt; margin: 20px 0 10px; color: ${text}; }+ .subheading { font-family: ${headingFont}; font-size: 14pt; margin: 15px 0 8px; color: ${text}; }+ p { margin-bottom: 12px; }+ .divider { border: none; border-top: 1px solid #ddd; margin: 20px 0; }+ .code-block { background: #1a1a1a; color: #00ff00; padding: 15px; border-radius: 4px; overflow-x: auto; font-family: monospace; }+ .report-table { width: 100%; border-collapse: collapse; margin: 15px 0; }+ .report-table th, .report-table td { border: 1px solid #ddd; padding: 10px; text-align: left; }+ .report-table th { background: #f5f5f5; font-weight: bold; }+ .report-image { max-width: 100%; height: auto; margin: 15px 0; }+ .section { margin: 20px 0; border-radius: 4px; }+ .columns { display: flex; gap: 20px; margin: 15px 0; }+ .columns-2 .column { flex: 1; }+ .columns-3 .column { flex: 1; }+ .page-break { page-break-after: always; height: 0; }+ .cover-page { min-height: 500px; display: flex; flex-direction: column; justify-content: center; align-items: center; }+ .cover-page h1 { font-size: 36pt; margin-bottom: 20px; }+ .cover-page .subtitle { font-size: 18pt; }+ .report-footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #ddd; text-align: center; color: #888; font-size: 10pt; }+ @media print { .page-break { page-break-after: always; } }+ ${brandKit?.customCSS || ''}+ `;+ }++ private escapeHtml(text: string): string {+ return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');+ }++ private escapeXml(text: string): string {+ return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');+ }++ // Export to file+ async exportToFile(template: ReportTemplate, format: ExportFormat, brandKit?: BrandKit | null): Promise<string | null> {+ const extensions: Record<ExportFormat, string> = {+ pdf: 'pdf', html: 'html', docx: 'docx', markdown: 'md'+ };++ const filePath = await save({+ filters: [{ name: format.toUpperCase(), extensions: [extensions[format]] }],+ defaultPath: `${template.metadata.title || 'report'}.${extensions[format]}`+ });++ if (!filePath) return null;++ switch (format) {+ case 'html':+ await writeTextFile(filePath, this.generateHTML(template, brandKit));+ break;+ case 'markdown':+ await writeTextFile(filePath, this.generateMarkdown(template));+ break;+ case 'docx':+ // For DOCX, we'll generate HTML and let Rust handle conversion+ await invoke('export_report_docx', {+ htmlContent: this.generateHTML(template, brandKit),+ outputPath: filePath+ });+ break;+ case 'pdf':+ await invoke('generate_report_pdf', {+ templateJson: JSON.stringify(template),+ outputPath: filePath+ });+ break;+ }++ return filePath;+ }++ // Batch export to multiple formats+ async batchExport(template: ReportTemplate, formats: ExportFormat[], brandKit?: BrandKit | null): Promise<Record<ExportFormat, string | null>> {+ const results: Record<ExportFormat, string | null> = {+ pdf: null, html: null, docx: null, markdown: null+ };++ for (const format of formats) {+ try {+ results[format] = await this.exportToFile(template, format, brandKit);+ } catch (error) {+ console.error(`Failed to export ${format}:`, error);+ results[format] = null;+ }+ }++ return results;+ }++ // Get print-ready HTML for preview+ getPrintPreviewHTML(template: ReportTemplate, brandKit?: BrandKit | null): string {+ return this.generateHTML(template, brandKit);+ }+}++export const reportExportService = new ReportExportService();diff --git a/fincept-terminal-desktop/src/services/core/reportService.ts b/fincept-terminal-desktop/src/services/core/reportService.tsindex 9970053a7..3e933f5ba 100644--- a/fincept-terminal-desktop/src/services/core/reportService.ts+++ b/fincept-terminal-desktop/src/services/core/reportService.ts@@ -5,7 +5,9 @@ import { reportLogger } from './loggerService';export interface ReportComponent {id: string;- type: 'text' | 'heading' | 'subheading' | 'chart' | 'table' | 'image' | 'divider' | 'code' | 'section' | 'columns' | 'coverpage' | 'pagebreak';+ type: 'text' | 'heading' | 'subheading' | 'chart' | 'table' | 'image' | 'divider' | 'code' | 'section' | 'columns' | 'coverpage' | 'pagebreak' |+ // New component types+ 'quote' | 'list' | 'toc' | 'kpi' | 'sparkline' | 'liveTable' | 'dynamicChart' | 'signature' | 'disclaimer' | 'qrcode' | 'watermark';content: any;config: {fontSize?: string;@@ -28,6 +30,34 @@ export interface ReportComponent {// Cover page configssubtitle?: string;logo?: string;+ // Quote/Callout configs+ quoteType?: 'quote' | 'info' | 'warning' | 'success' | 'error';+ author?: string;+ // List configs+ items?: string[];+ ordered?: boolean;+ // TOC configs+ showPageNumbers?: boolean;+ // KPI configs+ kpis?: Array<{ label: string; value: string; change: number; trend: 'up' | 'down' }>;+ // Sparkline configs+ data?: number[] | Array<{ name: string; value: number }>;+ // Signature configs+ name?: string;+ title?: string;+ showLine?: boolean;+ // Disclaimer configs+ disclaimerType?: 'standard' | 'legal' | 'confidential';+ // QR Code configs+ value?: string;+ size?: number;+ label?: string;+ // Watermark configs+ text?: string;+ opacity?: number;+ rotation?: number;+ // Data source configs+ dataSource?: string;};// For column and section types that contain other componentschildren?: ReportComponent[];diff --git a/fincept-terminal-desktop/src/services/core/sqliteService.ts b/fincept-terminal-desktop/src/services/core/sqliteService.tsindex 2bea21144..aee593849 100644--- a/fincept-terminal-desktop/src/services/core/sqliteService.ts+++ b/fincept-terminal-desktop/src/services/core/sqliteService.ts@@ -1203,6 +1203,24 @@ class SqliteService {}}+ async updateLLMModelId(id: string, newModelId: string): Promise<{ success: boolean; message: string }> {+ try {+ return await invoke<{ success: boolean; message: string }>('db_update_llm_model_id', { id, newModelId });+ } catch (error) {+ console.error('[SqliteService] Failed to update LLM model ID:', error);+ return { success: false, message: String(error) };+ }+ }++ async fixGoogleModelIds(): Promise<{ success: boolean; message: string }> {+ try {+ return await invoke<{ success: boolean; message: string }>('db_fix_google_model_ids');+ } catch (error) {+ console.error('[SqliteService] Failed to fix Google model IDs:', error);+ return { success: false, message: String(error) };+ }+ }+async setActiveLLMProvider(provider: string): Promise<void> {try {await invoke('db_set_active_llm_provider', { provider });diff --git a/fincept-terminal-desktop/src/services/data-sources/sectorService.ts b/fincept-terminal-desktop/src/services/data-sources/sectorService.tsindex 6d682bde9..68a73845f 100644--- a/fincept-terminal-desktop/src/services/data-sources/sectorService.ts+++ b/fincept-terminal-desktop/src/services/data-sources/sectorService.ts@@ -1,5 +1,8 @@// Sector Classification Service// Maps stock symbols to their sectors and industries+// Uses yfinance .info for real-time sector data - fully dynamic++import { invoke } from '@tauri-apps/api/core';export interface SectorInfo {sector: string;@@ -7,162 +10,140 @@ export interface SectorInfo {description?: string;}-// Common sector classifications (GICS sectors)-export const SECTORS = {- TECHNOLOGY: 'Technology',- HEALTHCARE: 'Healthcare',- FINANCIAL: 'Financial Services',- CONSUMER_CYCLICAL: 'Consumer Cyclical',- CONSUMER_DEFENSIVE: 'Consumer Defensive',- INDUSTRIALS: 'Industrials',- ENERGY: 'Energy',- UTILITIES: 'Utilities',- REAL_ESTATE: 'Real Estate',- MATERIALS: 'Basic Materials',- COMMUNICATION: 'Communication Services',- CRYPTO: 'Cryptocurrency',- OTHER: 'Other'-};--// Known symbol to sector mappings-const SYMBOL_SECTOR_MAP: Record<string, SectorInfo> = {- // Technology- 'AAPL': { sector: SECTORS.TECHNOLOGY, industry: 'Consumer Electronics' },- 'MSFT': { sector: SECTORS.TECHNOLOGY, industry: 'Software' },- 'GOOGL': { sector: SECTORS.COMMUNICATION, industry: 'Internet Content' },- 'GOOG': { sector: SECTORS.COMMUNICATION, industry: 'Internet Content' },- 'AMZN': { sector: SECTORS.CONSUMER_CYCLICAL, industry: 'Internet Retail' },- 'META': { sector: SECTORS.COMMUNICATION, industry: 'Social Media' },- 'NVDA': { sector: SECTORS.TECHNOLOGY, industry: 'Semiconductors' },- 'TSLA': { sector: SECTORS.CONSUMER_CYCLICAL, industry: 'Auto Manufacturers' },- 'AMD': { sector: SECTORS.TECHNOLOGY, industry: 'Semiconductors' },- 'INTC': { sector: SECTORS.TECHNOLOGY, industry: 'Semiconductors' },- 'CRM': { sector: SECTORS.TECHNOLOGY, industry: 'Software' },- 'ORCL': { sector: SECTORS.TECHNOLOGY, industry: 'Software' },- 'ADBE': { sector: SECTORS.TECHNOLOGY, industry: 'Software' },- 'CSCO': { sector: SECTORS.TECHNOLOGY, industry: 'Communication Equipment' },- 'IBM': { sector: SECTORS.TECHNOLOGY, industry: 'Information Technology Services' },-- // Healthcare- 'JNJ': { sector: SECTORS.HEALTHCARE, industry: 'Drug Manufacturers' },- 'UNH': { sector: SECTORS.HEALTHCARE, industry: 'Healthcare Plans' },- 'PFE': { sector: SECTORS.HEALTHCARE, industry: 'Drug Manufacturers' },- 'ABBV': { sector: SECTORS.HEALTHCARE, industry: 'Drug Manufacturers' },- 'TMO': { sector: SECTORS.HEALTHCARE, industry: 'Diagnostics & Research' },- 'ABT': { sector: SECTORS.HEALTHCARE, industry: 'Medical Devices' },- 'MRK': { sector: SECTORS.HEALTHCARE, industry: 'Drug Manufacturers' },-- // Financial- 'JPM': { sector: SECTORS.FINANCIAL, industry: 'Banks' },- 'BAC': { sector: SECTORS.FINANCIAL, industry: 'Banks' },- 'WFC': { sector: SECTORS.FINANCIAL, industry: 'Banks' },- 'GS': { sector: SECTORS.FINANCIAL, industry: 'Capital Markets' },- 'MS': { sector: SECTORS.FINANCIAL, industry: 'Capital Markets' },- 'V': { sector: SECTORS.FINANCIAL, industry: 'Credit Services' },- 'MA': { sector: SECTORS.FINANCIAL, industry: 'Credit Services' },- 'BRK.B': { sector: SECTORS.FINANCIAL, industry: 'Insurance' },-- // Consumer- 'WMT': { sector: SECTORS.CONSUMER_DEFENSIVE, industry: 'Discount Stores' },- 'PG': { sector: SECTORS.CONSUMER_DEFENSIVE, industry: 'Household Products' },- 'KO': { sector: SECTORS.CONSUMER_DEFENSIVE, industry: 'Beverages' },- 'PEP': { sector: SECTORS.CONSUMER_DEFENSIVE, industry: 'Beverages' },- 'COST': { sector: SECTORS.CONSUMER_DEFENSIVE, industry: 'Discount Stores' },- 'NKE': { sector: SECTORS.CONSUMER_CYCLICAL, industry: 'Footwear & Accessories' },- 'MCD': { sector: SECTORS.CONSUMER_CYCLICAL, industry: 'Restaurants' },- 'SBUX': { sector: SECTORS.CONSUMER_CYCLICAL, industry: 'Restaurants' },- 'DIS': { sector: SECTORS.COMMUNICATION, industry: 'Entertainment' },- 'NFLX': { sector: SECTORS.COMMUNICATION, industry: 'Entertainment' },-- // Energy- 'XOM': { sector: SECTORS.ENERGY, industry: 'Oil & Gas' },- 'CVX': { sector: SECTORS.ENERGY, industry: 'Oil & Gas' },- 'COP': { sector: SECTORS.ENERGY, industry: 'Oil & Gas' },-- // Industrials- 'BA': { sector: SECTORS.INDUSTRIALS, industry: 'Aerospace & Defense' },- 'HON': { sector: SECTORS.INDUSTRIALS, industry: 'Conglomerates' },- 'UPS': { sector: SECTORS.INDUSTRIALS, industry: 'Integrated Freight & Logistics' },- 'CAT': { sector: SECTORS.INDUSTRIALS, industry: 'Farm & Heavy Machinery' },-- // Indian Stocks- 'RELIANCE.NS': { sector: SECTORS.ENERGY, industry: 'Oil & Gas Refining' },- 'RELIANCE.BO': { sector: SECTORS.ENERGY, industry: 'Oil & Gas Refining' },- 'TCS.NS': { sector: SECTORS.TECHNOLOGY, industry: 'Information Technology Services' },- 'TCS.BO': { sector: SECTORS.TECHNOLOGY, industry: 'Information Technology Services' },- 'INFY.NS': { sector: SECTORS.TECHNOLOGY, industry: 'Information Technology Services' },- 'INFY.BO': { sector: SECTORS.TECHNOLOGY, industry: 'Information Technology Services' },- 'HDFCBANK.NS': { sector: SECTORS.FINANCIAL, industry: 'Banks' },- 'HDFCBANK.BO': { sector: SECTORS.FINANCIAL, industry: 'Banks' },- 'ITC.NS': { sector: SECTORS.CONSUMER_DEFENSIVE, industry: 'Tobacco' },- 'ITC.BO': { sector: SECTORS.CONSUMER_DEFENSIVE, industry: 'Tobacco' },-- // Cryptocurrency- 'BTC-USD': { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' },- 'ETH-USD': { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' },- 'USDT-USD': { sector: SECTORS.CRYPTO, industry: 'Stablecoin' },- 'BNB-USD': { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' },- 'XRP-USD': { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' },- 'SOL-USD': { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' },- 'ADA-USD': { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' },- 'DOGE-USD': { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' },-- // ETFs- 'SPY': { sector: SECTORS.OTHER, industry: 'Index ETF' },- 'QQQ': { sector: SECTORS.OTHER, industry: 'Index ETF' },- 'VOO': { sector: SECTORS.OTHER, industry: 'Index ETF' },- 'VTI': { sector: SECTORS.OTHER, industry: 'Index ETF' },- 'IWM': { sector: SECTORS.OTHER, industry: 'Index ETF' },-};+// Default sector for unknown/missing values+export const DEFAULT_SECTOR = 'Other';++// Crypto sector constant (for pattern matching)+export const CRYPTO_SECTOR = 'Cryptocurrency';++// Runtime cache for fetched sector data (fully dynamic)+const sectorCache: Record<string, SectorInfo> = {};++// Pending fetch promises to avoid duplicate requests+const pendingFetches: Record<string, Promise<SectorInfo>> = {};class SectorService {/**- * Get sector information for a symbol+ * Get sector information for a symbol (synchronous - uses cache)+ * Returns cached data or pattern-based fallback*/getSectorInfo(symbol: string): SectorInfo {- // Normalize symbol (uppercase, remove exchange suffix variations)const normalizedSymbol = symbol.toUpperCase().trim();- // Check direct mapping- if (SYMBOL_SECTOR_MAP[normalizedSymbol]) {- return SYMBOL_SECTOR_MAP[normalizedSymbol];+ // Check runtime cache first+ if (sectorCache[normalizedSymbol]) {+ return sectorCache[normalizedSymbol];}- // Check without exchange suffix (.NS, .BO, etc.)+ // Check without exchange suffixconst baseSymbol = normalizedSymbol.split('.')[0];- if (SYMBOL_SECTOR_MAP[baseSymbol]) {- return SYMBOL_SECTOR_MAP[baseSymbol];+ if (sectorCache[baseSymbol]) {+ return sectorCache[baseSymbol];}- // Heuristic classification based on symbol patterns+ // Return pattern-based fallback (async fetch will update cache)return this.classifyByPattern(normalizedSymbol);}/**- * Classify symbol by patterns (fallback)+ * Fetch sector info from yfinance API (async)*/- private classifyByPattern(symbol: string): SectorInfo {- // Crypto patterns- if (symbol.endsWith('-USD') || symbol.endsWith('USD') || symbol.endsWith('USDT')) {- return { sector: SECTORS.CRYPTO, industry: 'Cryptocurrency' };+ async fetchSectorInfo(symbol: string): Promise<SectorInfo> {+ const normalizedSymbol = symbol.toUpperCase().trim();++ // Check cache+ if (sectorCache[normalizedSymbol]) {+ return sectorCache[normalizedSymbol];+ }++ // Check if already fetching+ if (normalizedSymbol in pendingFetches) {+ return pendingFetches[normalizedSymbol];}- // ETF patterns- if (symbol.length === 3 && (symbol.startsWith('V') || symbol.startsWith('I') || symbol.startsWith('S'))) {- return { sector: SECTORS.OTHER, industry: 'Index ETF' };+ // Pattern-based symbols (crypto, etc.) - no API call needed+ const patternInfo = this.classifyByPattern(normalizedSymbol);+ if (patternInfo.sector !== DEFAULT_SECTOR || patternInfo.industry !== 'Unknown') {+ sectorCache[normalizedSymbol] = patternInfo;+ return patternInfo;}- // Indian stocks- if (symbol.endsWith('.NS') || symbol.endsWith('.BO')) {- return { sector: SECTORS.OTHER, industry: 'Indian Stock' };+ // Fetch from yfinance API+ const fetchPromise = this.fetchFromYfinance(normalizedSymbol);+ pendingFetches[normalizedSymbol] = fetchPromise;++ try {+ const result = await fetchPromise;+ sectorCache[normalizedSymbol] = result;+ return result;+ } finally {+ delete pendingFetches[normalizedSymbol];}+ }++ /**+ * Fetch sector data from yfinance API+ * Returns whatever sector/industry yfinance provides - fully dynamic+ */+ private async fetchFromYfinance(symbol: string): Promise<SectorInfo> {+ try {+ const response = await invoke<string>('execute_yfinance_command', {+ command: 'info',+ args: [symbol]+ });+ const data = JSON.parse(response);++ // Check for error response+ if (data.error) {+ console.warn(`[SectorService] yfinance error for ${symbol}:`, data.error);+ return { sector: DEFAULT_SECTOR, industry: 'Unknown' };+ }++ // Use sector/industry directly from yfinance - no normalization needed+ const sector = data.sector && data.sector !== 'N/A' ? data.sector : DEFAULT_SECTOR;+ const industry = data.industry && data.industry !== 'N/A' ? data.industry : undefined;+ const description = data.description && data.description !== 'N/A' ? data.description : undefined;- // Default fallback- return { sector: SECTORS.OTHER, industry: 'Unknown' };+ return { sector, industry, description };+ } catch (error) {+ console.warn(`[SectorService] Failed to fetch sector for ${symbol}:`, error);+ return { sector: DEFAULT_SECTOR, industry: 'Unknown' };+ }}/**- * Get all unique sectors from a list of symbols+ * Prefetch sector data for multiple symbols+ */+ async prefetchSectors(symbols: string[]): Promise<void> {+ const unknownSymbols = symbols.filter(s => {+ const normalized = s.toUpperCase().trim();+ return !sectorCache[normalized];+ });++ // Fetch in parallel (limit concurrency to avoid overwhelming API)+ const batchSize = 5;+ for (let i = 0; i < unknownSymbols.length; i += batchSize) {+ const batch = unknownSymbols.slice(i, i + batchSize);+ await Promise.all(batch.map(s => this.fetchSectorInfo(s)));+ }+ }++ /**+ * Classify symbol by patterns (fallback for crypto, ETFs, etc.)+ */+ private classifyByPattern(symbol: string): SectorInfo {+ // Crypto patterns+ if (symbol.endsWith('-USD') || symbol.endsWith('USDT') ||+ symbol.includes('BTC') || symbol.includes('ETH') || symbol.includes('USDC')) {+ return { sector: CRYPTO_SECTOR, industry: 'Cryptocurrency' };+ }++ // Default fallback - will be updated by async fetch+ return { sector: DEFAULT_SECTOR, industry: 'Unknown' };+ }++ /**+ * Get all unique sectors from a list of symbols (from cache)*/getUniqueSectors(symbols: string[]): string[] {const sectors = new Set<string>();@@ -174,7 +155,7 @@ class SectorService {}/**- * Group symbols by sector+ * Group symbols by sector (from cache)*/groupBySector(symbols: string[]): Record<string, string[]> {const grouped: Record<string, string[]> = {};@@ -191,17 +172,26 @@ class SectorService {}/**- * Add custom sector mapping+ * Manually add sector mapping to cache*/addSectorMapping(symbol: string, sectorInfo: SectorInfo): void {- SYMBOL_SECTOR_MAP[symbol.toUpperCase()] = sectorInfo;+ sectorCache[symbol.toUpperCase()] = sectorInfo;+ }++ /**+ * Get all sectors currently in cache+ */+ getCachedSectors(): string[] {+ const sectors = new Set<string>();+ Object.values(sectorCache).forEach(info => sectors.add(info.sector));+ return Array.from(sectors).sort();}/**- * Get all supported sectors+ * Clear cache (useful for refresh)*/- getAllSectors(): string[] {- return Object.values(SECTORS);+ clearCache(): void {+ Object.keys(sectorCache).forEach(key => delete sectorCache[key]);}}diff --git a/fincept-terminal-desktop/src/services/llmModelsService.ts b/fincept-terminal-desktop/src/services/llmModelsService.tsindex 8093f8cbd..72b1ff81e 100644--- a/fincept-terminal-desktop/src/services/llmModelsService.ts+++ b/fincept-terminal-desktop/src/services/llmModelsService.ts@@ -1,20 +1,30 @@/*** LLM Models Service- * Fetches available models from various LLM providers- * Uses official API endpoints to get real-time model listings+ * Fetches available models from LiteLLM library via Tauri commands+ * Supports 52+ providers and 1700+ models* CACHING: Uses unified cache system (cacheService)*/+import { invoke } from '@tauri-apps/api/core';import { cacheService } from './cache/cacheService';export interface ModelInfo {id: string;name: string;+ provider?: string;description?: string;context_window?: number;+ input_cost_per_token?: number;+ output_cost_per_token?: number;deprecated?: boolean;}+export interface ProviderInfo {+ id: string;+ name: string;+ model_count: number;+}+export interface ProviderModels {provider: string;models: ModelInfo[];@@ -22,320 +32,112 @@ export interface ProviderModels {error?: string;}-/**- * Static fallback model lists (minimal, used only if API fails)- */-const FALLBACK_MODELS: Record<string, ModelInfo[]> = {- openai: [- { id: 'gpt-4o', name: 'GPT-4o', description: 'Latest flagship', context_window: 128000 },- { id: 'gpt-4o-mini', name: 'GPT-4o Mini', description: 'Fast & affordable', context_window: 128000 },- { id: 'o1', name: 'o1', description: 'Reasoning model', context_window: 200000 },- ],- anthropic: [- { id: 'claude-opus-4-5-20251101', name: 'Claude Opus 4.5', description: 'Most capable', context_window: 200000 },- { id: 'claude-sonnet-4-5-20250929', name: 'Claude Sonnet 4.5', description: 'Balanced', context_window: 200000 },- { id: 'claude-haiku-4-5-20251031', name: 'Claude Haiku 4.5', description: 'Fastest', context_window: 200000 },- ],- google: [- { id: 'gemini-2.5-pro-latest', name: 'Gemini 2.5 Pro', description: 'Latest flagship', context_window: 1000000 },- { id: 'gemini-2.5-flash-latest', name: 'Gemini 2.5 Flash', description: 'Fast', context_window: 1000000 },- ],- groq: [- { id: 'llama-3.3-70b-versatile', name: 'Llama 3.3 70B', description: 'Meta Llama', context_window: 128000 },- { id: 'mixtral-8x7b-32768', name: 'Mixtral 8x7B', description: 'Mistral', context_window: 32768 },- ],- deepseek: [- { id: 'deepseek-chat', name: 'DeepSeek Chat', description: 'General chat', context_window: 64000 },- { id: 'deepseek-coder', name: 'DeepSeek Coder', description: 'Code generation', context_window: 64000 },- ],- openrouter: [],-};+export interface LLMStats {+ total_providers: number;+ total_models: number;+ top_providers: Array<{+ provider: string;+ model_count: number;+ }>;+}/**- * Fetch models from OpenAI API+ * Provider name mappings (UI name → LiteLLM provider name)+ * Some providers have different names in the UI vs LiteLLM data*/-async function fetchOpenAIModels(apiKey: string): Promise<ModelInfo[]> {- try {- const response = await fetch('https://api.openai.com/v1/models', {- headers: {- 'Authorization': `Bearer ${apiKey}`,- },- });-- if (!response.ok) {- throw new Error(`OpenAI API error: ${response.status}`);- }-- const data = await response.json();-- // Filter to only show GPT and o1 models- const models = data.data- .filter((m: any) => m.id.startsWith('gpt-') || m.id.startsWith('o1'))- .map((m: any) => ({- id: m.id,- name: m.id,- description: `OpenAI ${m.id}`,- }))- .sort((a: ModelInfo, b: ModelInfo) => b.id.localeCompare(a.id));-- return models.length > 0 ? models : FALLBACK_MODELS.openai;- } catch (error) {- console.error('[LLMModels] Failed to fetch OpenAI models:', error);- return FALLBACK_MODELS.openai;- }-}+const PROVIDER_MAPPINGS: Record<string, string> = {+ 'google': 'gemini', // UI uses 'google', LiteLLM uses 'gemini'+ 'azure_openai': 'azure', // UI might use 'azure_openai', LiteLLM uses 'azure'+};/**- * Fetch models from Anthropic API+ * Reverse mappings (LiteLLM name → UI name)*/-async function fetchAnthropicModels(apiKey: string): Promise<ModelInfo[]> {- try {- const response = await fetch('https://api.anthropic.com/v1/models', {- headers: {- 'x-api-key': apiKey,- 'anthropic-version': '2023-06-01',- },- });-- if (!response.ok) {- throw new Error(`Anthropic API error: ${response.status}`);- }-- const data = await response.json();-- const models = data.data.map((m: any) => ({- id: m.id,- name: m.display_name || m.id,- description: `Anthropic ${m.display_name || m.id}`,- context_window: m.max_tokens,- }));-- return models.length > 0 ? models : FALLBACK_MODELS.anthropic;- } catch (error) {- console.error('[LLMModels] Failed to fetch Anthropic models:', error);- return FALLBACK_MODELS.anthropic;- }-}+const REVERSE_PROVIDER_MAPPINGS: Record<string, string> = {+ 'gemini': 'google',+ 'azure': 'azure_openai',+};/**- * Fetch models from Google Gemini API+ * Get the LiteLLM provider name for a UI provider name*/-async function fetchGoogleModels(apiKey: string): Promise<ModelInfo[]> {- try {- const response = await fetch(- `https://generativelanguage.googleapis.com/v1beta/models?key=${apiKey}`- );-- if (!response.ok) {- throw new Error(`Google API error: ${response.status}`);- }-- const data = await response.json();-- // Filter to only Gemini models that support generateContent- const models = data.models- .filter((m: any) =>- m.name.includes('gemini') &&- m.supportedGenerationMethods?.includes('generateContent')- )- .map((m: any) => ({- id: m.name.replace('models/', ''),- name: m.displayName || m.name.replace('models/', ''),- description: m.description || `Google ${m.displayName}`,- context_window: m.inputTokenLimit,- }));-- return models.length > 0 ? models : FALLBACK_MODELS.google;- } catch (error) {- console.error('[LLMModels] Failed to fetch Google models:', error);- return FALLBACK_MODELS.google;- }+function getLiteLLMProviderName(uiProvider: string): string {+ return PROVIDER_MAPPINGS[uiProvider.toLowerCase()] || uiProvider;}/**- * Fetch all models from OpenRouter API (public, no auth required)- * Returns 400+ models from multiple providers, grouped and sorted+ * Main service class for LLM models+ * Uses LiteLLM library via Tauri Python commands*/-async function fetchOpenRouterModels(): Promise<ModelInfo[]> {- try {- const response = await fetch('https://openrouter.ai/api/v1/models');-- if (!response.ok) {- throw new Error(`OpenRouter API error: ${response.status}`);- }-- const data = await response.json();+export class LLMModelsService {+ /**+ * Get all available providers from LiteLLM+ */+ static async getProviders(): Promise<ProviderInfo[]> {+ const cacheKey = 'llm-providers:all';- if (!data.data || !Array.isArray(data.data)) {- throw new Error('Invalid response format');+ // Check cache first+ const cached = await cacheService.get<ProviderInfo[]>(cacheKey);+ if (cached) {+ console.log('[LLMModels] Serving providers from cache');+ return cached.data;}- // Group models by provider- const providerGroups: Record<string, ModelInfo[]> = {};-- data.data.forEach((m: any) => {- const provider = m.id.split('/')[0]; // e.g., "openai/gpt-4" -> "openai"- const modelName = m.id.split('/')[1] || m.id;-- if (!providerGroups[provider]) {- providerGroups[provider] = [];- }+ try {+ const providers = await invoke<ProviderInfo[]>('get_llm_providers');+ console.log(`[LLMModels] Loaded ${providers.length} providers from LiteLLM`);- providerGroups[provider].push({- id: m.id,- name: m.name || modelName,- description: m.description?.substring(0, 150) || modelName,- context_window: m.context_length || 0,- });- });-- // Sort providers and flatten models- const sortedModels: ModelInfo[] = [];- const providers = Object.keys(providerGroups).sort();-- console.log(`[LLMModels] OpenRouter providers found: ${providers.join(', ')}`);- console.log(`[LLMModels] Total models: ${data.data.length}`);-- providers.forEach(provider => {- // Sort models within each provider by name- const sortedProviderModels = providerGroups[provider].sort((a, b) =>- a.name.localeCompare(b.name)- );- sortedModels.push(...sortedProviderModels);- });-- return sortedModels;- } catch (error) {- console.error('[LLMModels] Failed to fetch OpenRouter models:', error);- return FALLBACK_MODELS.openrouter;- }-}+ // Cache for 24 hours (provider list rarely changes)+ await cacheService.set(cacheKey, providers, 'reference', '24h');-/**- * Fetch models from Groq API- */-async function fetchGroqModels(apiKey: string): Promise<ModelInfo[]> {- try {- const response = await fetch('https://api.groq.com/openai/v1/models', {- headers: {- 'Authorization': `Bearer ${apiKey}`,- },- });-- if (!response.ok) {- throw new Error(`Groq API error: ${response.status}`);+ return providers;+ } catch (error) {+ console.error('[LLMModels] Failed to fetch providers:', error);+ // Return empty list on error - all models come from LiteLLM data+ return [];}-- const data = await response.json();-- const models = data.data.map((m: any) => ({- id: m.id,- name: m.id,- description: `Groq ${m.id}`,- context_window: m.context_window,- }));-- return models.length > 0 ? models : FALLBACK_MODELS.groq;- } catch (error) {- console.error('[LLMModels] Failed to fetch Groq models:', error);- return FALLBACK_MODELS.groq;- }-}--/**- * Main service class for LLM models- */-export class LLMModelsService {- /**- * Get models from OpenRouter filtered by provider prefix- */- static async getOpenRouterModelsByProvider(providerPrefix: string): Promise<ModelInfo[]> {- const allModels = await fetchOpenRouterModels();- return allModels.filter(m => m.id.startsWith(`${providerPrefix}/`));}/**- * Get models for a specific provider+ * Get models for a specific provider from LiteLLM*/- static async getModels(provider: string, apiKey?: string, baseUrl?: string): Promise<ProviderModels> {- const cacheKey = `llm-models:${provider}:${apiKey?.substring(0, 10) || 'no-key'}`;+ static async getModelsByProvider(provider: string): Promise<ModelInfo[]> {+ // Map UI provider name to LiteLLM provider name+ const litellmProvider = getLiteLLMProviderName(provider);+ const cacheKey = `llm-models:${provider}`; // Use original provider for cache key- // Check unified cache first+ // Check cache firstconst cached = await cacheService.get<ModelInfo[]>(cacheKey);if (cached) {console.log(`[LLMModels] Serving ${provider} models from cache`);- return {- provider,- models: cached.data,- lastFetched: Date.now(),- };+ return cached.data;}try {- let models: ModelInfo[] = [];-- switch (provider.toLowerCase()) {- case 'openai':- if (!apiKey) {- models = FALLBACK_MODELS.openai;- } else {- models = await fetchOpenAIModels(apiKey);- }- break;-- case 'anthropic':- if (!apiKey) {- models = FALLBACK_MODELS.anthropic;- } else {- models = await fetchAnthropicModels(apiKey);- }- break;-- case 'google':- if (!apiKey) {- models = FALLBACK_MODELS.google;- } else {- models = await fetchGoogleModels(apiKey);- }- break;-- case 'groq':- if (!apiKey) {- models = FALLBACK_MODELS.groq;- } else {- models = await fetchGroqModels(apiKey);- }- break;-- case 'deepseek':- models = FALLBACK_MODELS.deepseek;- break;-- case 'openrouter':- models = await fetchOpenRouterModels();- break;-- case 'ollama':- // Ollama models are fetched separately via ollamaService- models = [];- break;-- case 'fincept':- // Fincept models - auto-configured- models = [- { id: 'fincept-ai', name: 'Fincept AI', description: 'Auto-configured Fincept model' },- ];- break;-- default:- models = [];- }+ // Use mapped provider name for the API call+ const models = await invoke<ModelInfo[]>('get_llm_models_by_provider', { provider: litellmProvider });+ console.log(`[LLMModels] Loaded ${models.length} models for ${provider} (litellm: ${litellmProvider})`);- // Cache the result using unified cache (1 hour TTL)+ // Cache for 6 hoursif (models.length > 0) {- await cacheService.set(cacheKey, models, 'reference', '1h');+ await cacheService.set(cacheKey, models, 'reference', '6h');}+ return models;+ } catch (error) {+ console.error(`[LLMModels] Failed to fetch models for ${provider}:`, error);+ // Return empty list on error - all models come from LiteLLM data+ return [];+ }+ }++ /**+ * Get models for a specific provider (alias for backward compatibility)+ */+ static async getModels(provider: string, _apiKey?: string, _baseUrl?: string): Promise<ProviderModels> {+ try {+ const models = await this.getModelsByProvider(provider);+return {provider,models,@@ -344,48 +146,168 @@ export class LLMModelsService {} catch (error) {console.error(`[LLMModels] Error fetching models for ${provider}:`, error);- // Return fallback models on error- const fallback = FALLBACK_MODELS[provider.toLowerCase()] || [];return {provider,- models: fallback,+ models: [],error: error instanceof Error ? error.message : 'Failed to fetch models',};}}/**- * Get fallback models (static list) for a provider+ * Search models by name or provider+ */+ static async searchModels(query: string): Promise<ModelInfo[]> {+ // Map provider names in query if needed+ let mappedQuery = query;+ for (const [uiName, litellmName] of Object.entries(PROVIDER_MAPPINGS)) {+ if (query.toLowerCase() === uiName) {+ mappedQuery = litellmName;+ break;+ }+ }++ const cacheKey = `llm-search:${query.toLowerCase()}`;++ // Check cache first+ const cached = await cacheService.get<ModelInfo[]>(cacheKey);+ if (cached) {+ return cached.data;+ }++ try {+ const models = await invoke<ModelInfo[]>('search_llm_models', { query: mappedQuery });+ console.log(`[LLMModels] Search '${query}' (mapped: ${mappedQuery}) returned ${models.length} models`);++ // Cache search results for 1 hour+ if (models.length > 0) {+ await cacheService.set(cacheKey, models, 'reference', '1h');+ }++ return models;+ } catch (error) {+ console.error(`[LLMModels] Search failed for '${query}':`, error);+ return [];+ }+ }++ /**+ * Get LLM statistics*/- static getFallbackModels(provider: string): ModelInfo[] {- return FALLBACK_MODELS[provider.toLowerCase()] || [];+ static async getStats(): Promise<LLMStats | null> {+ const cacheKey = 'llm-stats';++ const cached = await cacheService.get<LLMStats>(cacheKey);+ if (cached) {+ return cached.data;+ }++ try {+ const stats = await invoke<LLMStats>('get_llm_stats');+ console.log(`[LLMModels] Stats: ${stats.total_providers} providers, ${stats.total_models} models`);++ await cacheService.set(cacheKey, stats, 'reference', '24h');++ return stats;+ } catch (error) {+ console.error('[LLMModels] Failed to fetch stats:', error);+ return null;+ }}/**- * Clear the cache for a specific provider+ * Clear the cache for a specific provider or all*/static async clearCache(provider?: string): Promise<void> {if (provider) {- await cacheService.invalidatePattern(`llm-models:${provider}:%`);+ await cacheService.invalidatePattern(`llm-models:${provider}`);+ await cacheService.invalidatePattern(`llm-search:%`);} else {await cacheService.invalidatePattern('llm-models:%');+ await cacheService.invalidatePattern('llm-providers:%');+ await cacheService.invalidatePattern('llm-search:%');+ await cacheService.invalidatePattern('llm-stats');}console.log(`[LLMModels] Cache cleared${provider ? ` for ${provider}` : ''}`);}/**- * Get all supported providers+ * Get all supported providers from LiteLLM+ */+ static async getSupportedProviders(): Promise<string[]> {+ try {+ const providers = await this.getProviders();+ return providers.map(p => p.id);+ } catch {+ return [];+ }+ }++ /**+ * Get provider display name+ */+ static getProviderDisplayName(providerId: string): string {+ const displayNames: Record<string, string> = {+ 'openai': 'OpenAI',+ 'anthropic': 'Anthropic',+ 'google': 'Google AI',+ 'gemini': 'Google Gemini',+ 'groq': 'Groq',+ 'deepseek': 'DeepSeek',+ 'mistral': 'Mistral AI',+ 'openrouter': 'OpenRouter',+ 'ollama': 'Ollama (Local)',+ 'fincept': 'Fincept AI',+ 'azure': 'Azure OpenAI',+ 'azure_ai': 'Azure AI',+ 'bedrock': 'AWS Bedrock',+ 'vertex_ai': 'Google Vertex AI',+ 'fireworks_ai': 'Fireworks AI',+ 'together_ai': 'Together AI',+ 'perplexity': 'Perplexity',+ 'cohere': 'Cohere',+ 'replicate': 'Replicate',+ 'huggingface': 'Hugging Face',+ 'deepinfra': 'DeepInfra',+ 'anyscale': 'Anyscale',+ 'databricks': 'Databricks',+ 'xai': 'xAI (Grok)',+ 'cerebras': 'Cerebras',+ 'sambanova': 'SambaNova',+ 'novita': 'Novita AI',+ 'cloudflare': 'Cloudflare AI',+ 'nlp_cloud': 'NLP Cloud',+ 'ai21': 'AI21 Labs',+ 'aleph_alpha': 'Aleph Alpha',+ 'palm': 'Google PaLM',+ 'watsonx': 'IBM watsonx',+ };++ return displayNames[providerId.toLowerCase()] || providerId.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());+ }++ /**+ * Get provider base URL*/- static getSupportedProviders(): string[] {- return [- 'fincept',- 'openai',- 'anthropic',- 'google',- 'groq',- 'deepseek',- 'openrouter',- 'ollama',- ];+ static getProviderBaseUrl(provider: string): string {+ const urls: Record<string, string> = {+ 'openai': 'https://api.openai.com/v1',+ 'anthropic': 'https://api.anthropic.com/v1',+ 'google': 'https://generativelanguage.googleapis.com/v1beta',+ 'gemini': 'https://generativelanguage.googleapis.com/v1beta',+ 'groq': 'https://api.groq.com/openai/v1',+ 'deepseek': 'https://api.deepseek.com/v1',+ 'mistral': 'https://api.mistral.ai/v1',+ 'openrouter': 'https://openrouter.ai/api/v1',+ 'together_ai': 'https://api.together.xyz/v1',+ 'fireworks_ai': 'https://api.fireworks.ai/inference/v1',+ 'perplexity': 'https://api.perplexity.ai',+ 'cohere': 'https://api.cohere.ai/v1',+ 'anyscale': 'https://api.endpoints.anyscale.com/v1',+ 'deepinfra': 'https://api.deepinfra.com/v1/openai',+ 'xai': 'https://api.x.ai/v1',+ };++ return urls[provider.toLowerCase()] || '';}}diff --git a/fincept-terminal-desktop/src/services/markets/marketHoursService.ts b/fincept-terminal-desktop/src/services/markets/marketHoursService.tsnew file mode 100644index 000000000..71cf358dd--- /dev/null+++ b/fincept-terminal-desktop/src/services/markets/marketHoursService.ts@@ -0,0 +1,312 @@+/**+ * Market Hours Service+ *+ * Provides utilities for checking market hours across different exchanges.+ * Used to optimize polling strategies - poll frequently when market is open,+ * use cached data when market is closed.+ */++export type MarketStatus = 'PRE_OPEN' | 'OPEN' | 'CLOSED' | 'POST_MARKET' | 'HOLIDAY';++export interface MarketHoursConfig {+ open: { hour: number; minute: number };+ close: { hour: number; minute: number };+ preMarketOpen?: { hour: number; minute: number };+ preMarketClose?: { hour: number; minute: number };+ postMarketOpen?: { hour: number; minute: number };+ postMarketClose?: { hour: number; minute: number };+ timezone: string;+ tradingDays: number[]; // 0 = Sunday, 1 = Monday, ..., 6 = Saturday+}++export interface MarketStatusInfo {+ status: MarketStatus;+ isOpen: boolean;+ nextOpen?: Date;+ nextClose?: Date;+ currentTime: Date;+ exchangeTime: Date;+}++// Market hours configuration for different exchanges+const MARKET_HOURS: Record<string, MarketHoursConfig> = {+ // Indian Markets (NSE, BSE)+ NSE: {+ open: { hour: 9, minute: 15 },+ close: { hour: 15, minute: 30 },+ preMarketOpen: { hour: 9, minute: 0 },+ preMarketClose: { hour: 9, minute: 15 },+ postMarketOpen: { hour: 15, minute: 40 },+ postMarketClose: { hour: 16, minute: 0 },+ timezone: 'Asia/Kolkata',+ tradingDays: [1, 2, 3, 4, 5], // Monday to Friday+ },+ BSE: {+ open: { hour: 9, minute: 15 },+ close: { hour: 15, minute: 30 },+ preMarketOpen: { hour: 9, minute: 0 },+ preMarketClose: { hour: 9, minute: 15 },+ postMarketOpen: { hour: 15, minute: 40 },+ postMarketClose: { hour: 16, minute: 0 },+ timezone: 'Asia/Kolkata',+ tradingDays: [1, 2, 3, 4, 5],+ },+ // US Markets+ NYSE: {+ open: { hour: 9, minute: 30 },+ close: { hour: 16, minute: 0 },+ preMarketOpen: { hour: 4, minute: 0 },+ preMarketClose: { hour: 9, minute: 30 },+ postMarketOpen: { hour: 16, minute: 0 },+ postMarketClose: { hour: 20, minute: 0 },+ timezone: 'America/New_York',+ tradingDays: [1, 2, 3, 4, 5],+ },+ NASDAQ: {+ open: { hour: 9, minute: 30 },+ close: { hour: 16, minute: 0 },+ preMarketOpen: { hour: 4, minute: 0 },+ preMarketClose: { hour: 9, minute: 30 },+ postMarketOpen: { hour: 16, minute: 0 },+ postMarketClose: { hour: 20, minute: 0 },+ timezone: 'America/New_York',+ tradingDays: [1, 2, 3, 4, 5],+ },+ // Crypto Markets (24/7)+ CRYPTO: {+ open: { hour: 0, minute: 0 },+ close: { hour: 23, minute: 59 },+ timezone: 'UTC',+ tradingDays: [0, 1, 2, 3, 4, 5, 6], // All days+ },+};++/**+ * Get current time in a specific timezone+ */+function getTimeInTimezone(timezone: string): Date {+ const now = new Date();+ const options: Intl.DateTimeFormatOptions = {+ timeZone: timezone,+ year: 'numeric',+ month: '2-digit',+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ second: '2-digit',+ hour12: false,+ };++ const formatter = new Intl.DateTimeFormat('en-US', options);+ const parts = formatter.formatToParts(now);++ const getPart = (type: string) => parts.find(p => p.type === type)?.value || '0';++ return new Date(+ parseInt(getPart('year')),+ parseInt(getPart('month')) - 1,+ parseInt(getPart('day')),+ parseInt(getPart('hour')),+ parseInt(getPart('minute')),+ parseInt(getPart('second'))+ );+}++/**+ * Convert hours and minutes to total minutes since midnight+ */+function toMinutes(hour: number, minute: number): number {+ return hour * 60 + minute;+}++/**+ * Check if current time is within a time range+ */+function isWithinRange(+ currentMinutes: number,+ start: { hour: number; minute: number },+ end: { hour: number; minute: number }+): boolean {+ const startMinutes = toMinutes(start.hour, start.minute);+ const endMinutes = toMinutes(end.hour, end.minute);+ return currentMinutes >= startMinutes && currentMinutes < endMinutes;+}++/**+ * Get market status for a specific exchange+ */+export function getMarketStatus(exchange: string): MarketStatusInfo {+ const config = MARKET_HOURS[exchange.toUpperCase()] || MARKET_HOURS.NSE;+ const now = new Date();+ const exchangeTime = getTimeInTimezone(config.timezone);++ const dayOfWeek = exchangeTime.getDay();+ const currentMinutes = toMinutes(exchangeTime.getHours(), exchangeTime.getMinutes());++ // Check if it's a trading day+ if (!config.tradingDays.includes(dayOfWeek)) {+ return {+ status: 'CLOSED',+ isOpen: false,+ currentTime: now,+ exchangeTime,+ };+ }++ // Check pre-market+ if (config.preMarketOpen && config.preMarketClose) {+ if (isWithinRange(currentMinutes, config.preMarketOpen, config.preMarketClose)) {+ return {+ status: 'PRE_OPEN',+ isOpen: false,+ currentTime: now,+ exchangeTime,+ };+ }+ }++ // Check market hours+ if (isWithinRange(currentMinutes, config.open, config.close)) {+ return {+ status: 'OPEN',+ isOpen: true,+ currentTime: now,+ exchangeTime,+ };+ }++ // Check post-market+ if (config.postMarketOpen && config.postMarketClose) {+ if (isWithinRange(currentMinutes, config.postMarketOpen, config.postMarketClose)) {+ return {+ status: 'POST_MARKET',+ isOpen: false,+ currentTime: now,+ exchangeTime,+ };+ }+ }++ return {+ status: 'CLOSED',+ isOpen: false,+ currentTime: now,+ exchangeTime,+ };+}++/**+ * Check if market is currently open+ */+export function isMarketOpen(exchange: string): boolean {+ return getMarketStatus(exchange).isOpen;+}++/**+ * Check if market is in extended hours (pre-market or post-market)+ */+export function isExtendedHours(exchange: string): boolean {+ const status = getMarketStatus(exchange).status;+ return status === 'PRE_OPEN' || status === 'POST_MARKET';+}++/**+ * Get recommended polling interval based on market status+ * Returns interval in milliseconds+ */+export function getPollingInterval(exchange: string): number {+ const { status } = getMarketStatus(exchange);++ switch (status) {+ case 'OPEN':+ // Market is open - poll every 30 seconds+ return 30 * 1000;+ case 'PRE_OPEN':+ // Pre-market - poll every 2 minutes+ return 2 * 60 * 1000;+ case 'POST_MARKET':+ // Post-market - poll every 5 minutes+ return 5 * 60 * 1000;+ case 'CLOSED':+ case 'HOLIDAY':+ default:+ // Market closed - poll every 30 minutes (data won't change)+ return 30 * 60 * 1000;+ }+}++/**+ * Get recommended cache TTL based on market status+ * Returns TTL in seconds+ */+export function getCacheTTL(exchange: string): number {+ const { status } = getMarketStatus(exchange);++ switch (status) {+ case 'OPEN':+ // Market is open - cache for 1 minute+ return 60;+ case 'PRE_OPEN':+ // Pre-market - cache for 2 minutes+ return 2 * 60;+ case 'POST_MARKET':+ // Post-market - cache for 5 minutes+ return 5 * 60;+ case 'CLOSED':+ case 'HOLIDAY':+ default:+ // Market closed - cache for 30 minutes (data won't change)+ return 30 * 60;+ }+}++/**+ * Check if we should skip polling (market closed and have cached data)+ */+export function shouldSkipPolling(exchange: string, hasCachedData: boolean): boolean {+ const { status } = getMarketStatus(exchange);++ // If market is closed and we have cached data, skip polling+ if (status === 'CLOSED' && hasCachedData) {+ return true;+ }++ return false;+}++/**+ * Get human-readable market status message+ */+export function getMarketStatusMessage(exchange: string): string {+ const { status, exchangeTime } = getMarketStatus(exchange);+ const config = MARKET_HOURS[exchange.toUpperCase()] || MARKET_HOURS.NSE;++ const formatTime = (t: { hour: number; minute: number }) =>+ `${t.hour.toString().padStart(2, '0')}:${t.minute.toString().padStart(2, '0')}`;++ switch (status) {+ case 'OPEN':+ return `Market Open (closes at ${formatTime(config.close)})`;+ case 'PRE_OPEN':+ return `Pre-Market (opens at ${formatTime(config.open)})`;+ case 'POST_MARKET':+ return `Post-Market (closes at ${formatTime(config.postMarketClose!)})`;+ case 'CLOSED':+ return `Market Closed (opens at ${formatTime(config.open)})`;+ case 'HOLIDAY':+ return 'Market Holiday';+ default:+ return 'Unknown';+ }+}++// Export default instance for convenience+export default {+ getMarketStatus,+ isMarketOpen,+ isExtendedHours,+ getPollingInterval,+ getCacheTTL,+ shouldSkipPolling,+ getMarketStatusMessage,+};diff --git a/fincept-terminal-desktop/src/services/portfolio/activeManagementService.ts b/fincept-terminal-desktop/src/services/portfolio/activeManagementService.tsindex 9b209a625..89dbda7bb 100644--- a/fincept-terminal-desktop/src/services/portfolio/activeManagementService.ts+++ b/fincept-terminal-desktop/src/services/portfolio/activeManagementService.ts@@ -246,39 +246,82 @@ class ActiveManagementService {/*** Helper: Fetch benchmark returns (e.g., S&P 500)- * Uses marketDataService to get period returns and generates calibrated daily returns+ * Uses marketDataService to get historical prices and calculate actual daily returns*/async fetchBenchmarkReturns(benchmarkSymbol: string = 'SPY', days: number = 252): Promise<number[]> {try {// Import marketDataService dynamically to avoid circular depsconst { marketDataService } = await import('../markets/marketDataService');- // Try to get period returns from market data service+ // Try to get historical prices for the benchmark+ const historicalData = await (marketDataService as any).getHistoricalPrices?.(benchmarkSymbol, days + 1);++ if (historicalData && historicalData.length > 1) {+ // Calculate actual daily returns from historical prices+ const returns: number[] = [];+ for (let i = 1; i < historicalData.length; i++) {+ const prevPrice = historicalData[i - 1].close;+ const currPrice = historicalData[i].close;+ if (prevPrice > 0) {+ returns.push((currPrice - prevPrice) / prevPrice);+ }+ }++ if (returns.length > 0) {+ return returns;+ }+ }++ // Fallback: Try period returns for calibrationconst periodReturns = await marketDataService.getPeriodReturns(benchmarkSymbol);if (periodReturns) {- // Use actual returns to calibrate simulated daily returns- const dailyVolatility = Math.abs(periodReturns.seven_day / 100) / Math.sqrt(7);- const avgDailyReturn = periodReturns.thirty_day / 100 / 30;-- // Generate daily returns calibrated to actual benchmark performance- return Array.from({ length: days }, () =>- avgDailyReturn + (Math.random() - 0.5) * 2 * dailyVolatility- );+ // Use actual period returns to estimate characteristics+ // This is still an approximation but better than pure random+ const annualReturn = ((periodReturns as any).one_year || periodReturns.thirty_day * 12) / 100;+ const avgDailyReturn = annualReturn / 252;++ // Estimate volatility from shorter-term variance+ const weeklyReturn = (periodReturns.seven_day || 0) / 100;+ const monthlyReturn = (periodReturns.thirty_day || 0) / 100;+ const impliedDailyVol = Math.abs(weeklyReturn - monthlyReturn / 4) / Math.sqrt(7);+ const dailyVolatility = impliedDailyVol > 0 ? impliedDailyVol : 0.01; // ~16% annual++ // Generate returns using Box-Muller for proper normal distribution+ const returns: number[] = [];+ for (let i = 0; i < days; i++) {+ const u1 = Math.random();+ const u2 = Math.random();+ const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);+ returns.push(avgDailyReturn + z * dailyVolatility);+ }+ return returns;}- // Fallback: typical S&P 500 daily returns characteristics+ // Last resort: typical S&P 500 characteristics with proper distribution// ~10% annual return, ~16% annual volatilityconst avgDailyReturn = 0.10 / 252;const dailyVolatility = 0.16 / Math.sqrt(252);- return Array.from({ length: days }, () =>- avgDailyReturn + (Math.random() - 0.5) * 2 * dailyVolatility- );+ const returns: number[] = [];+ for (let i = 0; i < days; i++) {+ const u1 = Math.random();+ const u2 = Math.random();+ const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);+ returns.push(avgDailyReturn + z * dailyVolatility);+ }+ return returns;} catch (error) {console.error('[ActiveManagementService] Benchmark fetch error:', error);- // Fallback to simulated data- return Array.from({ length: days }, () => (Math.random() - 0.5) * 0.02);+ // Fallback with proper normal distribution+ const returns: number[] = [];+ for (let i = 0; i < days; i++) {+ const u1 = Math.random();+ const u2 = Math.random();+ const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);+ returns.push(0.0004 + z * 0.01); // ~10% annual, ~16% vol+ }+ return returns;}}}diff --git a/fincept-terminal-desktop/src/services/portfolio/portfolioService.ts b/fincept-terminal-desktop/src/services/portfolio/portfolioService.tsindex 961d5a9e4..e1f0bde49 100644--- a/fincept-terminal-desktop/src/services/portfolio/portfolioService.ts+++ b/fincept-terminal-desktop/src/services/portfolio/portfolioService.ts@@ -147,12 +147,22 @@ class PortfolioService {};}- async removeAsset(portfolioId: string, symbol: string): Promise<void> {+ async removeAsset(portfolioId: string, symbol: string, sellPrice?: number): Promise<void> {// Sell all quantityconst assets = await this.getPortfolioAssets(portfolioId);const asset = assets.find(a => a.symbol === symbol.toUpperCase());if (asset) {- await this.sellAsset(portfolioId, symbol, asset.quantity, 0);+ // Use provided price, or fetch current price, or fallback to avg buy price+ let price = sellPrice;+ if (price === undefined || price === null) {+ try {+ const quotes = await marketDataService.getQuotes([symbol]);+ price = quotes[0]?.price ?? asset.avg_buy_price;+ } catch {+ price = asset.avg_buy_price;+ }+ }+ await this.sellAsset(portfolioId, symbol, asset.quantity, price);}}@@ -224,9 +234,9 @@ class PortfolioService {const marketValue = currentPrice * asset.quantity;const costBasis = asset.avg_buy_price * asset.quantity;const unrealizedPnl = marketValue - costBasis;- const unrealizedPnlPercent = (unrealizedPnl / costBasis) * 100;+ const unrealizedPnlPercent = costBasis > 0 ? (unrealizedPnl / costBasis) * 100 : 0;const dayChange = (currentPrice - previousClose) * asset.quantity;- const dayChangePercent = ((currentPrice - previousClose) / previousClose) * 100;+ const dayChangePercent = previousClose > 0 ? ((currentPrice - previousClose) / previousClose) * 100 : 0;totalMarketValue += marketValue;totalCostBasis += costBasis;@@ -322,13 +332,92 @@ class PortfolioService {}async calculateAdvancedMetrics(portfolioId: string): Promise<any> {- // Advanced features not implemented yet- return {};+ portfolioLogger.info(`Calculating advanced metrics for portfolio: ${portfolioId}`);++ const summary = await this.getPortfolioSummary(portfolioId);+ const holdings = summary.holdings;++ if (holdings.length === 0) {+ return {+ sharpe_ratio: 0,+ portfolio_volatility: 0,+ value_at_risk_95: 0,+ max_drawdown: 0,+ portfolio_return: 0,+ };+ }++ // Calculate basic metrics from holdings data+ const weights = holdings.map(h => h.weight / 100);+ const returns = holdings.map(h => (h.unrealized_pnl_percent || 0) / 100);++ // Portfolio return (weighted average)+ const portfolioReturn = weights.reduce((sum, w, i) => sum + w * returns[i], 0);++ // Portfolio volatility estimate (simplified - using day change variance)+ const dayChanges = holdings.map(h => (h.day_change_percent || 0) / 100);+ const avgDayChange = dayChanges.reduce((sum, d) => sum + d, 0) / dayChanges.length;+ const variance = dayChanges.reduce((sum, d) => sum + Math.pow(d - avgDayChange, 2), 0) / dayChanges.length;+ const dailyVolatility = Math.sqrt(variance);+ const annualizedVolatility = dailyVolatility * Math.sqrt(252);++ // Sharpe ratio (assuming 4% risk-free rate)+ const riskFreeRate = 0.04;+ const excessReturn = portfolioReturn - riskFreeRate;+ const sharpeRatio = annualizedVolatility > 0 ? excessReturn / annualizedVolatility : 0;++ // VaR 95% (parametric)+ const var95 = avgDayChange - 1.645 * dailyVolatility;++ // Max drawdown estimate from unrealized losses+ const maxLoss = Math.min(...returns, 0);++ return {+ sharpe_ratio: sharpeRatio,+ portfolio_volatility: annualizedVolatility,+ value_at_risk_95: Math.abs(var95),+ max_drawdown: Math.abs(maxLoss),+ portfolio_return: portfolioReturn,+ };}- async optimizePortfolioWeights(portfolioId: string, constraints: any): Promise<any> {- // Advanced features not implemented yet- return {};+ async optimizePortfolioWeights(portfolioId: string, method: string = 'max_sharpe'): Promise<any> {+ portfolioLogger.info(`Optimizing portfolio weights: ${portfolioId}, method: ${method}`);++ const summary = await this.getPortfolioSummary(portfolioId);+ const holdings = summary.holdings;++ if (holdings.length === 0) {+ return {+ optimal_weights: [],+ sharpe_ratio: 0,+ expected_return: 0,+ volatility: 0,+ };+ }++ // Simple equal-weight optimization as fallback+ // In production, this would call the Python optimizer+ const n = holdings.length;+ const equalWeight = 1 / n;++ // Calculate metrics for equal-weight portfolio+ const returns = holdings.map(h => (h.unrealized_pnl_percent || 0) / 100);+ const expectedReturn = returns.reduce((sum, r) => sum + r * equalWeight, 0);++ const dayChanges = holdings.map(h => (h.day_change_percent || 0) / 100);+ const avgChange = dayChanges.reduce((sum, d) => sum + d, 0) / n;+ const variance = dayChanges.reduce((sum, d) => sum + Math.pow(d - avgChange, 2), 0) / n;+ const volatility = Math.sqrt(variance) * Math.sqrt(252);++ const sharpeRatio = volatility > 0 ? (expectedReturn - 0.04) / volatility : 0;++ return {+ optimal_weights: holdings.map(() => equalWeight),+ sharpe_ratio: sharpeRatio,+ expected_return: expectedReturn,+ volatility: volatility,+ };}async generateAssetAllocation(portfolioId: string, strategy: string): Promise<any> {diff --git a/fincept-terminal-desktop/src/services/trading/websocketBridge.ts b/fincept-terminal-desktop/src/services/trading/websocketBridge.tsindex 8a2d08250..a62a02be1 100644--- a/fincept-terminal-desktop/src/services/trading/websocketBridge.ts+++ b/fincept-terminal-desktop/src/services/trading/websocketBridge.ts@@ -293,7 +293,7 @@ export function getWebSocketManager() {* Get available providers*/export function getAvailableProviders(): string[] {- return ['kraken', 'binance', 'hyperliquid', 'okx', 'coinbase'];+ return ['kraken', 'binance', 'hyperliquid', 'okx', 'coinbase', 'bybit', 'kucoin', 'gateio'];}/**