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
installation correct linux/mac
tilakpatel22a303f16dc775
diff --git a/README.md b/README.mdindex cdcb2fa09..a4ee285e9 100644--- a/README.md+++ b/README.md@@ -170,9 +170,14 @@ Maritime Intelligence → Commodity Prices → Macro Strategies```bashgit clone https://github.com/Fincept-Corporation/FinceptTerminal.gitcd FinceptTerminal/fincept-terminal-desktop-npm install && npm run tauri dev+bun install && bun run tauri:dev```+**Requirements:**+- [Bun](https://bun.sh) 1.0++- [Rust](https://www.rust-lang.org/) (latest stable)+- Platform-specific dependencies (see [docs/GETTING_STARTED.md](docs/GETTING_STARTED.md))+---## 🛣️ What's Nextdiff --git a/fincept-terminal-desktop/src-tauri/.gitignore b/fincept-terminal-desktop/src-tauri/.gitignoreindex b21bd681d..3b2bae6a0 100644--- a/fincept-terminal-desktop/src-tauri/.gitignore+++ b/fincept-terminal-desktop/src-tauri/.gitignore@@ -5,3 +5,5 @@# Generated by Tauri# will have schema files for capabilities auto-completion/gen/schemas+**/__pycache__+**/*.pycdiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/market_analyst.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/market_analyst.pydeleted file mode 100644index e7fe588a0..000000000--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/market_analyst.py+++ /dev/null@@ -1,283 +0,0 @@-"""-Market Analyst Agent--Specialized agent for market analysis, technical analysis, and trend identification.-"""--from typing import Dict, Any, Optional-from core.base_agent import BaseAgent, AgentConfig-from tools.market_data import get_market_data_tools-from tools.technical_indicators import get_technical_analysis_tools---class MarketAnalystAgent(BaseAgent):- """- Market Analyst Agent-- Specializes in:- - Market data analysis- - Technical indicator interpretation- - Trend identification- - Price action analysis- - Support/resistance levels- - Chart pattern recognition- """-- def __init__(- self,- model_provider: str = "openai",- model_name: str = "gpt-4o-mini",- symbols: list = None,- temperature: float = 0.3 # Lower temperature for more analytical responses- ):- """- Initialize Market Analyst Agent-- Args:- model_provider: LLM provider (openai, anthropic, google, etc.)- model_name: Model name- symbols: List of symbols to analyze- temperature: Model temperature (lower = more analytical)- """- if symbols is None:- symbols = ["BTC/USD", "ETH/USD"]-- config = AgentConfig(- name="MarketAnalyst",- role="Market Analysis Specialist",- description=(- "Expert market analyst specializing in technical analysis, trend identification, "- "and price action interpretation. Provides data-driven insights using technical "- "indicators and chart patterns."- ),- instructions=[- "Analyze market data using technical indicators (SMA, EMA, RSI, MACD, Bollinger Bands)",- "Identify trends, support/resistance levels, and chart patterns",- "Provide objective, data-driven analysis without emotional bias",- "Use multiple timeframes for comprehensive analysis",- "Explain technical indicators in clear, understandable terms",- "Highlight key levels and potential turning points",- "Consider volume and momentum in your analysis",- "Always cite specific indicator values and price levels",- "Acknowledge limitations and uncertainties in market predictions"- ],- model_provider=model_provider,- model_name=model_name,- temperature=temperature,- tools=["market_data", "technical_analysis"],- symbols=symbols,- enable_memory=True,- show_tool_calls=True,- markdown=True- )-- super().__init__(config)-- def _initialize_tools(self):- """Initialize market analyst specific tools"""- tools = []- tools.extend(get_market_data_tools())- tools.extend(get_technical_analysis_tools())- return tools-- def analyze_market(- self,- symbol: str,- analysis_type: str = "comprehensive",- timeframe: str = "1d",- session_id: Optional[str] = None- ) -> Dict[str, Any]:- """- Perform market analysis for a symbol-- Args:- symbol: Trading symbol to analyze- analysis_type: Type of analysis (quick, comprehensive, deep)- timeframe: Timeframe for analysis- session_id: Optional session ID for context-- Returns:- Analysis response- """- # Construct analysis prompt based on type- if analysis_type == "quick":- prompt = f"""- Provide a quick market analysis for {symbol}:- 1. Current price and trend direction- 2. Key support and resistance levels- 3. RSI and MACD signals- 4. Brief outlook (bullish/bearish/neutral)-- Keep it concise and actionable.- """-- elif analysis_type == "comprehensive":- prompt = f"""- Provide a comprehensive market analysis for {symbol}:-- 1. **Current Market State**:- - Current price and 24h change- - Trend analysis (short-term and medium-term)-- 2. **Technical Indicators**:- - Moving averages (SMA 20, 50, 200)- - RSI (14) - identify overbought/oversold- - MACD - trend and momentum- - Bollinger Bands - volatility and price position-- 3. **Key Levels**:- - Major support levels- - Major resistance levels-- 4. **Market Structure**:- - Higher highs/lower lows analysis- - Volume analysis-- 5. **Outlook**:- - Overall bias (bullish/bearish/neutral)- - Key levels to watch- - Potential scenarios-- Use actual market data and technical indicators. Be specific with numbers.- """-- elif analysis_type == "deep":- prompt = f"""- Provide a deep technical analysis for {symbol}:-- 1. **Multi-Timeframe Analysis**:- - Daily, 4H, and 1H trends- - Alignment or divergence between timeframes-- 2. **Detailed Technical Indicators**:- - Multiple moving averages and their relationships- - RSI with divergence analysis- - MACD with histogram analysis- - Bollinger Bands with width analysis- - Volume profile-- 3. **Advanced Price Action**:- - Chart patterns (if any)- - Candlestick patterns- - Support/resistance confluence- - Fibonacci levels-- 4. **Market Dynamics**:- - Order book analysis (if available)- - Volume analysis across timeframes- - Momentum shifts-- 5. **Trading Implications**:- - Potential entry points- - Risk levels (stop loss areas)- - Target levels (take profit areas)- - Risk/reward analysis-- 6. **Outlook & Scenarios**:- - Base case scenario- - Bull case scenario- - Bear case scenario- - Probability assessment-- Be thorough and use all available technical tools.- """-- else:- prompt = f"Analyze the market for {symbol} on {timeframe} timeframe."-- # Run the analysis- response = self.run(prompt, session_id=session_id)-- return {- "symbol": symbol,- "analysis_type": analysis_type,- "timeframe": timeframe,- "analysis": self._extract_response_content(response),- "agent": "MarketAnalyst"- }-- def compare_symbols(- self,- symbols: list,- session_id: Optional[str] = None- ) -> Dict[str, Any]:- """- Compare multiple symbols-- Args:- symbols: List of symbols to compare- session_id: Optional session ID-- Returns:- Comparison analysis- """- symbols_str = ", ".join(symbols)-- prompt = f"""- Compare the following symbols: {symbols_str}-- For each symbol, provide:- 1. Current price and trend- 2. Technical strength (based on indicators)- 3. Momentum (bullish/bearish)- 4. Relative performance-- Then rank them by:- - Technical strength- - Risk/reward profile- - Short-term potential-- Provide a clear recommendation on which ones show the best technical setup.- """-- response = self.run(prompt, session_id=session_id)-- return {- "symbols": symbols,- "comparison": self._extract_response_content(response),- "agent": "MarketAnalyst"- }-- def identify_opportunities(- self,- symbols: list,- criteria: Dict[str, Any] = None,- session_id: Optional[str] = None- ) -> Dict[str, Any]:- """- Identify trading opportunities across symbols-- Args:- symbols: List of symbols to scan- criteria: Criteria for opportunities (e.g., {"rsi_below": 30, "trend": "bullish"})- session_id: Optional session ID-- Returns:- Identified opportunities- """- symbols_str = ", ".join(symbols)- criteria_str = str(criteria) if criteria else "default technical criteria"-- prompt = f"""- Scan the following symbols for trading opportunities: {symbols_str}-- Criteria: {criteria_str}-- For each symbol:- 1. Check if it meets the criteria- 2. Analyze technical setup- 3. Identify specific entry points- 4. Note risk levels-- List the best opportunities ranked by quality of setup and risk/reward.- Only include setups that have clear technical confirmation.- """-- response = self.run(prompt, session_id=session_id)-- return {- "symbols": symbols,- "criteria": criteria,- "opportunities": self._extract_response_content(response),- "agent": "MarketAnalyst"- }diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/portfolio_manager.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/portfolio_manager.pydeleted file mode 100644index fd1bd588f..000000000--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/portfolio_manager.py+++ /dev/null@@ -1,107 +0,0 @@-"""-Portfolio Manager Agent--Specialized agent for portfolio management and asset allocation.-"""--from typing import Dict, Any, Optional, List-from core.base_agent import BaseAgent, AgentConfig-from tools.portfolio_tools import get_portfolio_tools-from tools.market_data import get_market_data_tools---class PortfolioManagerAgent(BaseAgent):- """- Portfolio Manager Agent-- Specializes in:- - Asset allocation- - Portfolio optimization- - Rebalancing recommendations- - Performance tracking- - Capital deployment- """-- def __init__(- self,- model_provider: str = "anthropic",- model_name: str = "claude-3-sonnet",- temperature: float = 0.5- ):- """Initialize Portfolio Manager Agent"""-- config = AgentConfig(- name="PortfolioManager",- role="Portfolio Management Specialist",- description=(- "Expert portfolio manager focused on optimal asset allocation, portfolio construction, "- "and performance optimization. Balances growth with risk management."- ),- instructions=[- "Optimize portfolio for risk-adjusted returns",- "Maintain appropriate diversification",- "Recommend rebalancing when allocations drift significantly",- "Consider correlation between assets",- "Suggest capital deployment strategies",- "Monitor portfolio performance vs benchmarks",- "Adapt allocation based on market conditions",- "Provide clear rationale for allocation decisions"- ],- model_provider=model_provider,- model_name=model_name,- temperature=temperature,- tools=["portfolio", "market_data"],- enable_memory=True,- show_tool_calls=True,- markdown=True- )-- super().__init__(config)-- def _initialize_tools(self):- """Initialize portfolio management tools"""- tools = []- tools.extend(get_portfolio_tools())- tools.extend(get_market_data_tools())- return tools-- def optimize_portfolio(- self,- current_allocation: Dict[str, float],- available_cash: float,- session_id: Optional[str] = None- ) -> Dict[str, Any]:- """Optimize portfolio allocation"""-- allocation_str = "\n".join([- f"- {symbol}: ${amount:.2f} ({amount / sum(current_allocation.values()) * 100:.1f}%)"- for symbol, amount in current_allocation.items()- ])-- prompt = f"""- Optimize this portfolio allocation:-- **Current Allocation**:- {allocation_str}-- **Available Cash**: ${available_cash}- **Total Portfolio Value**: ${sum(current_allocation.values()) + available_cash}-- **Optimization Goals**:- 1. Propose optimal allocation across assets- 2. Ensure diversification (no single position >25%)- 3. Consider current market conditions- 4. Suggest rebalancing trades if needed- 5. Recommend how to deploy available cash-- Provide specific allocation percentages and reasoning.- """-- response = self.run(prompt, session_id=session_id)-- return {- "current_allocation": current_allocation,- "available_cash": available_cash,- "optimization": self._extract_response_content(response),- "agent": "PortfolioManager"- }diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/risk_manager.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/risk_manager.pydeleted file mode 100644index 73d28e291..000000000--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/risk_manager.py+++ /dev/null@@ -1,151 +0,0 @@-"""-Risk Manager Agent--Specialized agent for risk management and portfolio protection.-"""--from typing import Dict, Any, Optional, List-from core.base_agent import BaseAgent, AgentConfig-from tools.portfolio_tools import get_portfolio_tools---class RiskManagerAgent(BaseAgent):- """- Risk Manager Agent-- Specializes in:- - Portfolio risk assessment- - Position sizing- - Stop loss recommendations- - Drawdown management- - Risk/reward analysis- """-- def __init__(- self,- model_provider: str = "openai",- model_name: str = "gpt-4",- risk_tolerance: str = "moderate",- temperature: float = 0.2 # Very analytical- ):- """Initialize Risk Manager Agent"""-- config = AgentConfig(- name="RiskManager",- role="Risk Management Specialist",- description=(- "Expert risk manager focused on capital preservation and risk-adjusted returns. "- "Ensures all trades comply with risk management rules and portfolio safety."- ),- instructions=[- "Never risk more than 2% of portfolio on a single trade (conservative)",- "Ensure risk/reward ratio is at least 1:2",- "Monitor overall portfolio exposure and correlation",- "Recommend appropriate position sizes based on volatility",- "Identify when portfolio is overextended",- "Suggest protective measures during high volatility",- "Calculate and monitor maximum drawdown",- "Ensure diversification across uncorrelated assets",- "Be conservative - when in doubt, reduce risk"- ],- model_provider=model_provider,- model_name=model_name,- temperature=temperature,- tools=["portfolio"],- risk_tolerance=risk_tolerance,- enable_memory=True,- show_tool_calls=True,- markdown=True- )-- super().__init__(config)-- def _initialize_tools(self):- """Initialize risk management specific tools"""- return get_portfolio_tools()-- def assess_trade_risk(- self,- trade: Dict[str, Any],- portfolio_value: float,- session_id: Optional[str] = None- ) -> Dict[str, Any]:- """Assess risk for a proposed trade"""-- prompt = f"""- Assess the risk for this trade:-- **Trade Details**:- - Symbol: {trade.get('symbol')}- - Direction: {trade.get('direction')}- - Entry: ${trade.get('entry_price')}- - Stop Loss: ${trade.get('stop_loss')}- - Take Profit: ${trade.get('take_profit')}- - Proposed Position Size: {trade.get('position_size')} units-- **Portfolio**:- - Total Value: ${portfolio_value}-- **Analysis Required**:- 1. Calculate risk amount and % of portfolio- 2. Calculate risk/reward ratio- 3. Assess if within risk parameters (max 2% risk per trade)- 4. Recommend optimal position size if adjustment needed- 5. Evaluate stop loss placement- 6. Overall risk assessment: APPROVED, APPROVED_WITH_CHANGES, or REJECTED-- Provide clear recommendation with reasoning.- """-- response = self.run(prompt, session_id=session_id)-- return {- "trade": trade,- "portfolio_value": portfolio_value,- "assessment": self._extract_response_content(response),- "agent": "RiskManager"- }-- def analyze_portfolio_risk(- self,- positions: List[Dict[str, Any]],- portfolio_value: float,- session_id: Optional[str] = None- ) -> Dict[str, Any]:- """Analyze overall portfolio risk"""-- positions_summary = "\n".join([- f"- {p.get('symbol')}: {p.get('quantity')} units @ ${p.get('current_price')} "- f"(Value: ${p.get('quantity', 0) * p.get('current_price', 0):.2f})"- for p in positions- ])-- prompt = f"""- Analyze portfolio risk:-- **Portfolio Value**: ${portfolio_value}-- **Current Positions**:- {positions_summary}-- **Risk Analysis Required**:- 1. Position concentration (% of portfolio in each position)- 2. Overall exposure (long vs short)- 3. Diversification assessment- 4. Correlation risk (if positions are related)- 5. Maximum drawdown potential- 6. Recommendations for risk reduction if needed-- Risk Tolerance: {self.config.risk_tolerance}-- Provide actionable recommendations to optimize risk.- """-- response = self.run(prompt, session_id=session_id)-- return {- "portfolio_value": portfolio_value,- "position_count": len(positions),- "risk_analysis": self._extract_response_content(response),- "agent": "RiskManager"- }diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/sentiment_analyst.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/sentiment_analyst.pydeleted file mode 100644index 857491119..000000000--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/sentiment_analyst.py+++ /dev/null@@ -1,101 +0,0 @@-"""-Sentiment Analyst Agent--Specialized agent for market sentiment analysis.-"""--from typing import Dict, Any, Optional-from core.base_agent import BaseAgent, AgentConfig-from tools.news_sentiment import get_news_sentiment_tools---class SentimentAnalystAgent(BaseAgent):- """- Sentiment Analyst Agent-- Specializes in:- - News sentiment analysis- - Social media sentiment- - Market mood assessment- - Sentiment-based signals- """-- def __init__(- self,- model_provider: str = "google",- model_name: str = "gemini-1.5-pro",- temperature: float = 0.4- ):- """Initialize Sentiment Analyst Agent"""-- config = AgentConfig(- name="SentimentAnalyst",- role="Market Sentiment Specialist",- description=(- "Expert in analyzing market sentiment from news, social media, and market behavior. "- "Identifies sentiment shifts that may impact price action."- ),- instructions=[- "Analyze sentiment from multiple sources (news, social media, on-chain data)",- "Identify sentiment extremes (euphoria or panic)",- "Detect sentiment divergences from price action",- "Assess credibility and impact of news events",- "Track sentiment changes over time",- "Provide context: is current sentiment justified?",- "Warn of potential sentiment-driven volatility",- "Distinguish between noise and significant sentiment shifts"- ],- model_provider=model_provider,- model_name=model_name,- temperature=temperature,- tools=["news_sentiment"],- enable_memory=True,- show_tool_calls=True,- markdown=True- )-- super().__init__(config)-- def _initialize_tools(self):- """Initialize sentiment analysis tools"""- return get_news_sentiment_tools()-- def analyze_sentiment(- self,- symbol: str,- sources: list = None,- session_id: Optional[str] = None- ) -> Dict[str, Any]:- """Analyze market sentiment for a symbol"""-- if sources is None:- sources = ["news", "social"]-- prompt = f"""- Analyze market sentiment for {symbol}:-- **Sources to analyze**: {", ".join(sources)}-- **Sentiment Analysis**:- 1. Overall sentiment score (0-100, where 50 is neutral)- 2. Sentiment trend (improving, deteriorating, stable)- 3. Key themes in recent news/discussions- 4. Sentiment vs price divergence (if any)- 5. Credibility assessment of sentiment drivers-- **Trading Implications**:- - Does sentiment support current price?- - Potential sentiment-driven moves?- - Risk of sentiment reversal?-- Note: Sentiment integration is currently limited. This is a placeholder for future implementation.- """-- response = self.run(prompt, session_id=session_id)-- return {- "symbol": symbol,- "sources": sources,- "sentiment_analysis": self._extract_response_content(response),- "agent": "SentimentAnalyst"- }diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/trading_strategy.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/trading_strategy.pydeleted file mode 100644index 24df81ee6..000000000--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/trading_strategy.py+++ /dev/null@@ -1,172 +0,0 @@-"""-Trading Strategy Agent--Specialized agent for developing trading strategies and generating trade signals.-"""--from typing import Dict, Any, Optional-from core.base_agent import BaseAgent, AgentConfig-from tools.market_data import get_market_data_tools-from tools.technical_indicators import get_technical_analysis_tools---class TradingStrategyAgent(BaseAgent):- """- Trading Strategy Agent-- Specializes in:- - Strategy development- - Trade signal generation- - Entry/exit point identification- - Strategy optimization- - Backtesting recommendations- """-- def __init__(- self,- model_provider: str = "anthropic",- model_name: str = "claude-sonnet-4",- symbols: list = None,- temperature: float = 0.4- ):- """Initialize Trading Strategy Agent"""- if symbols is None:- symbols = ["BTC/USD", "ETH/USD"]-- config = AgentConfig(- name="TradingStrategy",- role="Trading Strategy Specialist",- description=(- "Expert trading strategist specializing in developing, optimizing, and executing "- "trading strategies. Generates high-quality trade signals based on technical analysis "- "and market conditions."- ),- instructions=[- "Develop clear, actionable trading strategies with specific entry/exit rules",- "Generate trade signals based on multiple technical confirmations",- "Always specify entry price, stop loss, and take profit levels",- "Consider risk/reward ratio (minimum 1:2 preferred)",- "Adapt strategies to current market conditions (trending vs ranging)",- "Provide clear reasoning for each trade signal",- "Include position sizing recommendations",- "Monitor and adjust strategies based on performance",- "Be conservative and prioritize capital preservation"- ],- model_provider=model_provider,- model_name=model_name,- temperature=temperature,- tools=["market_data", "technical_analysis"],- symbols=symbols,- enable_memory=True,- show_tool_calls=True,- markdown=True- )-- super().__init__(config)-- def _initialize_tools(self):- """Initialize trading strategy specific tools"""- tools = []- tools.extend(get_market_data_tools())- tools.extend(get_technical_analysis_tools())- return tools-- def generate_trade_signal(- self,- symbol: str,- strategy: str = "momentum",- timeframe: str = "1h",- session_id: Optional[str] = None- ) -> Dict[str, Any]:- """Generate a trade signal for a symbol"""-- strategy_prompts = {- "momentum": f"""- Generate a momentum trading signal for {symbol} on {timeframe} timeframe:-- 1. Analyze current momentum using:- - MACD- - RSI- - Moving average crossovers- - Volume confirmation-- 2. If a setup exists, provide:- - Direction: LONG or SHORT- - Entry price- - Stop loss level- - Take profit targets (TP1, TP2)- - Risk/reward ratio- - Position size recommendation (% of portfolio)-- 3. Trade rationale:- - Why this setup?- - What confirms it?- - What invalidates it?-- If no clear setup exists, state "NO SIGNAL" and explain why.- """,-- "breakout": f"""- Generate a breakout trading signal for {symbol}:-- 1. Identify key levels:- - Resistance levels for long breakout- - Support levels for short breakdown- - Consolidation zones-- 2. If breakout setup exists:- - Direction and breakout level- - Entry strategy (immediate or retest)- - Stop loss placement- - Target levels- - Volume confirmation needed-- 3. Provide clear entry rules and invalidation criteria.- """,-- "reversal": f"""- Generate a reversal trading signal for {symbol}:-- 1. Look for reversal signals:- - RSI divergence- - Support/resistance levels- - Candlestick patterns- - Oversold/overbought conditions-- 2. If reversal setup exists:- - Entry point- - Stop loss (tight, near invalidation)- - Target levels- - Confidence level-- 3. Note: Reversals are higher risk - require strong confirmation.- """,-- "trend_following": f"""- Generate a trend-following signal for {symbol}:-- 1. Confirm the trend:- - Moving average alignment- - Higher highs/higher lows (uptrend)- - Lower highs/lower lows (downtrend)-- 2. Find entry on pullback:- - Wait for retracement to support (uptrend)- - Entry near moving averages- - Stop loss below support-- 3. Ride the trend with trailing stop.- """- }-- prompt = strategy_prompts.get(strategy, f"Generate a {strategy} trading signal for {symbol}")-- response = self.run(prompt, session_id=session_id)-- return {- "symbol": symbol,- "strategy": strategy,- "timeframe": timeframe,- "signal": self._extract_response_content(response),- "agent": "TradingStrategy"- }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.pynew file mode 100644index 000000000..6608f018a--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/alpha_arena_competition.py@@ -0,0 +1,865 @@+"""+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/core/base_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/base_agent.pyindex 35cf3f8df..f78a6f1c8 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/base_agent.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/base_agent.py@@ -121,6 +121,7 @@ class BaseAgent:"openai": os.getenv("OPENAI_API_KEY"),"anthropic": os.getenv("ANTHROPIC_API_KEY"),"google": os.getenv("GOOGLE_API_KEY"),+ "gemini": os.getenv("GOOGLE_API_KEY"), # Gemini uses Google API key"groq": os.getenv("GROQ_API_KEY"),"deepseek": os.getenv("DEEPSEEK_API_KEY"),"xai": os.getenv("XAI_API_KEY"),@@ -149,8 +150,9 @@ class BaseAgent:elif provider == "anthropic":from agno.models.anthropic import Claudereturn Claude(**model_config)- elif provider == "google":+ elif provider == "google" or provider == "gemini":# Use OpenAI-compatible API for Google Gemini+ # Support both "google" and "gemini" as provider namesfrom agno.models.openai import OpenAIChatreturn OpenAIChat(id=model_name,diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/team_orchestrator.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/team_orchestrator.pydeleted file mode 100644index e9b1990cb..000000000--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/team_orchestrator.py+++ /dev/null@@ -1,316 +0,0 @@-"""-Team Orchestrator--Multi-model orchestration inspired by Alpha Arena.-Runs multiple LLM agents in parallel, tracks performance, aggregates decisions.-"""--from typing import List, Dict, Any, Optional, Callable-from datetime import datetime-import asyncio-import json-from collections import defaultdict--try:- from agno import Agent- AGNO_AVAILABLE = True-except ImportError:- AGNO_AVAILABLE = False- Agent = None---class ModelPerformance:- """Track performance metrics for each model"""-- def __init__(self, model_name: str):- self.model_name = model_name- self.total_trades = 0- self.winning_trades = 0- self.losing_trades = 0- self.total_pnl = 0.0- self.daily_pnl = 0.0- self.current_positions = []- self.decisions = []- self.start_time = datetime.now()-- def add_decision(self, decision: Dict[str, Any]):- """Log a model decision"""- self.decisions.append({- **decision,- "timestamp": datetime.now().isoformat(),- "model": self.model_name- })-- def update_trade(self, pnl: float, is_win: bool):- """Update trade statistics"""- self.total_trades += 1- self.total_pnl += pnl- self.daily_pnl += pnl- if is_win:- self.winning_trades += 1- else:- self.losing_trades += 1-- def get_metrics(self) -> Dict[str, Any]:- """Get current performance metrics"""- win_rate = (self.winning_trades / self.total_trades * 100) if self.total_trades > 0 else 0- return {- "model": self.model_name,- "total_trades": self.total_trades,- "winning_trades": self.winning_trades,- "losing_trades": self.losing_trades,- "win_rate": win_rate,- "total_pnl": self.total_pnl,- "daily_pnl": self.daily_pnl,- "positions": len(self.current_positions),- "last_decision": self.decisions[-1] if self.decisions else None- }---class TeamOrchestrator:- """- Multi-model orchestration for trading (Alpha Arena style)-- Features:- - Run multiple models simultaneously- - Track each model's performance- - Stream real-time decisions- - Aggregate signals with voting/consensus- - Leaderboard & competition mode- """-- def __init__(self):- """Initialize team orchestrator"""- self.teams: Dict[str, Dict] = {}- self.model_performances: Dict[str, ModelPerformance] = {}- self.decision_callbacks: List[Callable] = []- self.created_at = datetime.now()-- def register_decision_callback(self, callback: Callable):- """Register callback for real-time decision streaming"""- self.decision_callbacks.append(callback)-- def _notify_decision(self, model: str, decision: Dict[str, Any]):- """Notify all callbacks of new decision"""- for callback in self.decision_callbacks:- try:- callback(model, decision)- except Exception as e:- print(f"[Orchestrator] Callback error: {e}")-- def create_competition(- self,- name: str,- agents: List[Dict[str, Any]],- task_type: str = "trading",- mode: str = "parallel"- ) -> str:- """- Create a multi-model competition-- Args:- name: Competition name- agents: List of agent configs [{"model": "openai:gpt-4", "agent": agent_instance}]- task_type: Type of task (trading, analysis, etc.)- mode: Execution mode (parallel, sequential, voting)-- Returns:- team_id: Competition identifier- """- if not AGNO_AVAILABLE:- raise ImportError("Agno framework required for creating competitions")-- team_id = f"comp_{name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"-- # Initialize performance tracking for each model- for agent_config in agents:- model_name = agent_config["model"]- if model_name not in self.model_performances:- self.model_performances[model_name] = ModelPerformance(model_name)-- self.teams[team_id] = {- "name": name,- "agents": agents,- "task_type": task_type,- "mode": mode,- "created_at": datetime.now().isoformat(),- "is_running": False- }-- return team_id-- async def run_parallel(- self,- team_id: str,- prompt: str,- streaming: bool = True- ) -> Dict[str, Any]:- """- Run all models in parallel (Alpha Arena style)-- Args:- team_id: Team identifier- prompt: Prompt/task for agents- streaming: Enable real-time decision streaming-- Returns:- Aggregated results from all models- """- if team_id not in self.teams:- raise ValueError(f"Team not found: {team_id}")-- team = self.teams[team_id]- team["is_running"] = True-- # Run all agents concurrently- tasks = []- for agent_config in team["agents"]:- tasks.append(self._run_single_agent(- agent_config["model"],- agent_config["agent"],- prompt,- streaming- ))-- results = await asyncio.gather(*tasks, return_exceptions=True)-- # Aggregate results- successful_results = []- for i, result in enumerate(results):- if isinstance(result, Exception):- print(f"[Orchestrator] Agent {team['agents'][i]['model']} failed: {result}")- else:- successful_results.append(result)-- team["is_running"] = False-- return {- "team_id": team_id,- "results": successful_results,- "consensus": self._calculate_consensus(successful_results),- "leaderboard": self.get_leaderboard(),- "timestamp": datetime.now().isoformat()- }-- async def _run_single_agent(- self,- model_name: str,- agent: Any,- prompt: str,- streaming: bool- ) -> Dict[str, Any]:- """Run a single agent and track its decision"""- try:- # Execute agent- response = agent.run(prompt)-- # Extract decision- decision = self._parse_agent_response(response)-- # Track performance- perf = self.model_performances[model_name]- perf.add_decision(decision)-- # Stream decision to UI- if streaming:- self._notify_decision(model_name, decision)-- return {- "model": model_name,- "decision": decision,- "response": self._extract_response_content(response),- "timestamp": datetime.now().isoformat()- }-- except Exception as e:- return {- "model": model_name,- "error": str(e),- "timestamp": datetime.now().isoformat()- }-- def _parse_agent_response(self, response: Any) -> Dict[str, Any]:- """Parse agent response into structured decision"""- content = self._extract_response_content(response)-- # Try to extract JSON decision- try:- import re- json_match = re.search(r'\{[^}]+\}', content, re.DOTALL)- if json_match:- return json.loads(json_match.group())- except:- pass-- # Return text decision- return {- "type": "analysis",- "content": content,- "action": "hold"- }-- def _extract_response_content(self, response: Any) -> str:- """Extract text content from agent response"""- if hasattr(response, 'content'):- return response.content- elif isinstance(response, dict) and 'content' in response:- return response['content']- elif isinstance(response, str):- return response- return str(response)-- def _calculate_consensus(self, results: List[Dict]) -> Dict[str, Any]:- """Calculate consensus from multiple model decisions"""- if not results:- return {"action": "hold", "confidence": 0.0, "agreement": 0}-- actions = defaultdict(int)- for result in results:- decision = result.get("decision", {})- action = decision.get("action", "hold")- actions[action] += 1-- # Majority vote- consensus_action = max(actions.items(), key=lambda x: x[1])- total = len(results)-- return {- "action": consensus_action[0],- "votes": dict(actions),- "confidence": consensus_action[1] / total,- "agreement": consensus_action[1],- "total_models": total- }-- def get_leaderboard(self) -> List[Dict[str, Any]]:- """Get performance leaderboard of all models"""- leaderboard = []- for model_name, perf in self.model_performances.items():- leaderboard.append(perf.get_metrics())-- # Sort by total PnL- leaderboard.sort(key=lambda x: x["total_pnl"], reverse=True)-- return leaderboard-- def get_recent_decisions(self, limit: int = 50) -> List[Dict[str, Any]]:- """Get recent decisions from all models"""- all_decisions = []- for perf in self.model_performances.values():- all_decisions.extend(perf.decisions)-- # Sort by timestamp descending- all_decisions.sort(key=lambda x: x["timestamp"], reverse=True)-- return all_decisions[:limit]-- def update_trade_result(self, model: str, pnl: float):- """Update trade result for a model"""- if model in self.model_performances:- is_win = pnl > 0- self.model_performances[model].update_trade(pnl, is_win)-- def reset_daily_stats(self):- """Reset daily statistics for all models"""- for perf in self.model_performances.values():- perf.daily_pnl = 0.0diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/db/database_manager.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/db/database_manager.pyindex 07db98893..daef5c275 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/db/database_manager.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/db/database_manager.py@@ -14,8 +14,13 @@ class DatabaseManager:def __init__(self, db_path: Optional[str] = None):"""Initialize database manager"""if db_path is None:- # Default to agno_trading.db in same directory- db_path = os.path.join(os.path.dirname(__file__), 'agno_trading.db')+ # Use temp directory to avoid Tauri file watcher triggering rebuilds+ import tempfile+ temp_dir = tempfile.gettempdir()+ db_dir = os.path.join(temp_dir, 'fincept_alpha_arena')+ os.makedirs(db_dir, exist_ok=True)+ db_path = os.path.join(db_dir, 'agno_trading.db')+ print(f"[DatabaseManager] Using database at: {db_path}", file=sys.stderr)self.db_path = db_pathself.initialize_database()@@ -469,6 +474,248 @@ class DatabaseManager:return debates+ # ============================================================================+ # COMPETITION STATE MANAGEMENT+ # ============================================================================++ def save_competition_config(self, competition_id: str, name: str, models_json: str,+ symbol: str, mode: str, api_keys_json: str = "{}"):+ """Save competition configuration to database"""+ conn = self.get_connection()+ cursor = conn.cursor()++ cursor.execute("""+ INSERT OR REPLACE INTO competition_configs (+ competition_id, name, models_json, symbol, mode,+ api_keys_json, status, created_at+ ) VALUES (?, ?, ?, ?, ?, ?, 'created', ?)+ """, (+ competition_id, name, models_json, symbol, mode,+ api_keys_json, int(datetime.now().timestamp())+ ))++ conn.commit()+ conn.close()+ print(f"[DatabaseManager] Saved competition config: {competition_id}", file=sys.stderr)++ def get_competition_config(self, competition_id: str) -> Optional[Dict]:+ """Get competition configuration from database"""+ conn = self.get_connection()+ cursor = conn.cursor()++ cursor.execute("""+ SELECT * FROM competition_configs WHERE competition_id = ?+ """, (competition_id,))++ result = cursor.fetchone()+ conn.close()++ if result:+ return dict(result)+ return None++ def get_active_competition(self) -> Optional[Dict]:+ """Get the most recent active competition"""+ conn = self.get_connection()+ cursor = conn.cursor()++ cursor.execute("""+ SELECT * FROM competition_configs+ WHERE status IN ('created', 'running')+ ORDER BY created_at DESC LIMIT 1+ """)++ result = cursor.fetchone()+ conn.close()++ if result:+ return dict(result)+ return None++ def update_competition_status(self, competition_id: str, status: str):+ """Update competition status"""+ conn = self.get_connection()+ cursor = conn.cursor()++ cursor.execute("""+ UPDATE competition_configs SET status = ? WHERE competition_id = ?+ """, (status, competition_id))++ conn.commit()+ conn.close()++ def save_model_state(self, competition_id: str, model_name: str,+ capital: float, positions_json: str, trades_count: int,+ total_pnl: float = 0.0, portfolio_value: float = 0.0):+ """Save model state for competition"""+ conn = self.get_connection()+ cursor = conn.cursor()++ # Generate unique ID+ state_id = f"{competition_id}_{model_name}"++ cursor.execute("""+ INSERT OR REPLACE INTO alpha_model_states (+ id, competition_id, model_name, capital, positions_json,+ trades_count, total_pnl, portfolio_value, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)+ """, (+ state_id, competition_id, model_name, capital, positions_json,+ trades_count, total_pnl, portfolio_value, int(datetime.now().timestamp())+ ))++ conn.commit()+ conn.close()++ def get_model_states(self, competition_id: str) -> List[Dict]:+ """Get all model states for a competition"""+ conn = self.get_connection()+ cursor = conn.cursor()++ cursor.execute("""+ SELECT * FROM alpha_model_states WHERE competition_id = ?+ """, (competition_id,))++ results = [dict(row) for row in cursor.fetchall()]+ conn.close()++ return results++ def initialize_database(self):+ """Create tables if they don't exist"""+ schema_path = os.path.join(os.path.dirname(__file__), 'schema.sql')++ conn = self.get_connection()++ if os.path.exists(schema_path):+ with open(schema_path, 'r') as f:+ schema_sql = f.read()+ conn.executescript(schema_sql)++ # Also create competition config and model state tables (legacy table removed, using alpha_model_states from schema.sql)+ conn.executescript("""+ CREATE TABLE IF NOT EXISTS competition_configs (+ competition_id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ models_json TEXT NOT NULL,+ symbol TEXT NOT NULL,+ mode TEXT NOT NULL,+ api_keys_json TEXT,+ status TEXT DEFAULT 'created',+ created_at INTEGER+ );++ CREATE TABLE IF NOT EXISTS alpha_performance_snapshots (+ id TEXT PRIMARY KEY,+ competition_id TEXT NOT NULL,+ cycle_number INTEGER NOT NULL,+ model_name TEXT NOT NULL,+ portfolio_value REAL NOT NULL,+ cash REAL NOT NULL,+ pnl REAL NOT NULL,+ return_pct REAL NOT NULL,+ positions_count INTEGER NOT NULL,+ trades_count INTEGER NOT NULL,+ timestamp TEXT NOT NULL+ );++ CREATE TABLE IF NOT EXISTS alpha_decision_logs (+ id TEXT PRIMARY KEY,+ 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,+ confidence REAL NOT NULL,+ reasoning TEXT NOT NULL,+ trade_executed TEXT NOT NULL,+ price_at_decision REAL,+ portfolio_value_before REAL,+ portfolio_value_after REAL,+ timestamp TEXT NOT NULL+ );++ CREATE INDEX IF NOT EXISTS idx_competition_configs_status ON competition_configs(status);+ CREATE INDEX IF NOT EXISTS idx_alpha_snapshots_competition ON alpha_performance_snapshots(competition_id);+ CREATE INDEX IF NOT EXISTS idx_alpha_snapshots_cycle ON alpha_performance_snapshots(cycle_number);+ CREATE INDEX IF NOT EXISTS idx_alpha_decision_logs_competition ON alpha_decision_logs(competition_id);+ CREATE INDEX IF NOT EXISTS idx_alpha_decision_logs_model ON alpha_decision_logs(model_name);+ CREATE INDEX IF NOT EXISTS idx_alpha_decision_logs_cycle ON alpha_decision_logs(cycle_number);+ """)++ conn.commit()+ conn.close()+ def save_decision_log(self, competition_id: str, model_name: str, cycle_number: int,+ action: str, symbol: str, quantity: float, confidence: float,+ reasoning: str, trade_executed: bool, price_at_decision: float,+ portfolio_value_before: float, portfolio_value_after: float):+ """Save decision log to database"""+ conn = self.get_connection()+ cursor = conn.cursor()++ # Generate unique ID+ timestamp = int(datetime.now().timestamp() * 1000)+ decision_id = f"{competition_id}_{model_name}_{cycle_number}_{timestamp}"++ cursor.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """, (+ decision_id, competition_id, model_name, cycle_number, action, symbol, quantity,+ confidence, reasoning, trade_executed, price_at_decision,+ portfolio_value_before, portfolio_value_after, timestamp+ ))++ conn.commit()+ conn.close()++ def save_performance_snapshot(self, competition_id: str, cycle_number: int,+ model_name: str, portfolio_value: float, cash: float,+ pnl: float, return_pct: float, positions_count: int,+ trades_count: int):+ """Save performance snapshot to database"""+ conn = self.get_connection()+ cursor = conn.cursor()++ # Generate unique ID+ timestamp = int(datetime.now().timestamp() * 1000)+ snapshot_id = f"{competition_id}_{model_name}_{cycle_number}_{timestamp}"++ cursor.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, competition_id, cycle_number, model_name, portfolio_value, cash,+ pnl, return_pct, positions_count, trades_count, timestamp+ ))++ conn.commit()+ conn.close()++ def get_decision_logs(self, competition_id: str, limit: int = 50) -> List[Dict]:+ """Get recent decision logs for a competition"""+ conn = self.get_connection()+ cursor = conn.cursor()++ cursor.execute("""+ SELECT * FROM alpha_decision_logs+ WHERE competition_id = ?+ ORDER BY timestamp DESC+ LIMIT ?+ """, (competition_id, limit))++ results = [dict(row) for row in cursor.fetchall()]+ conn.close()++ return results++# Global instance_db_manager = Nonediff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/db/schema.sql b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/db/schema.sqlindex 83e772e7e..517da9dae 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/db/schema.sql+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/db/schema.sql@@ -117,6 +117,34 @@ CREATE TABLE IF NOT EXISTS debate_sessions (execution_time_ms INTEGER);+-- Alpha Arena Competition Configurations+CREATE TABLE IF NOT EXISTS competition_configs (+ competition_id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ models_json TEXT NOT NULL,+ symbol TEXT NOT NULL,+ mode TEXT NOT NULL,+ api_keys_json TEXT,+ status TEXT DEFAULT 'created',+ created_at INTEGER NOT NULL+);++-- Alpha Arena Model States+CREATE TABLE IF NOT EXISTS alpha_model_states (+ id TEXT PRIMARY KEY,+ competition_id TEXT NOT NULL,+ model_name TEXT NOT NULL,+ provider TEXT,+ model_id TEXT,+ capital REAL NOT NULL,+ positions_json TEXT,+ trades_count INTEGER DEFAULT 0,+ total_pnl REAL DEFAULT 0,+ portfolio_value REAL NOT NULL,+ created_at INTEGER DEFAULT (strftime('%s', 'now')),+ updated_at INTEGER DEFAULT (strftime('%s', 'now'))+);+-- Indexes for PerformanceCREATE INDEX IF NOT EXISTS idx_agent_trades_agent ON agent_trades(agent_id);CREATE INDEX IF NOT EXISTS idx_agent_trades_symbol ON agent_trades(symbol);@@ -125,3 +153,5 @@ CREATE INDEX IF NOT EXISTS idx_agent_trades_timestamp ON agent_trades(entry_timeCREATE INDEX IF NOT EXISTS idx_agent_decisions_agent ON agent_decisions(agent_id);CREATE INDEX IF NOT EXISTS idx_agent_decisions_timestamp ON agent_decisions(timestamp DESC);CREATE INDEX IF NOT EXISTS idx_competitions_status ON competitions(status);+CREATE INDEX IF NOT EXISTS idx_competition_configs_status ON competition_configs(status);+CREATE INDEX IF NOT EXISTS idx_alpha_model_states_comp ON alpha_model_states(competition_id);diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/__init__.pynew file mode 100644index 000000000..289af9076--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/__init__.py@@ -0,0 +1,71 @@+"""+Alpha Arena Trading Framework++A modular, extensible trading framework for multi-LLM competitions.+Based on ValueCell architecture with clean separation of concerns.+"""++from .types import (+ TradeInstruction,+ TxResult,+ PortfolioView,+ PositionSnapshot,+ ComposeContext,+ ComposeResult,+ DecisionCycleResult,+ FeaturesResult,+ FeatureVector,+ Candle,+ MarketSnapshot,+ TradeDigest,+ TradeDigestEntry,+ Side,+ TxStatus,+ TradingMode,+)++from .base_composer import BaseComposer+from .base_execution import BaseExecutionGateway+from .base_portfolio import BasePortfolioService+from .base_features import BaseFeaturesPipeline+from .portfolio_service import InMemoryPortfolioService+from .paper_execution import PaperExecutionGateway+from .market_data_source import CCXTMarketDataSource+from .features_pipeline import TechnicalFeaturesPipeline+from .llm_composer import LLMComposer, ModelConfig+from .decision_coordinator import DecisionCoordinator+from .competition_runtime import CompetitionRuntime++__all__ = [+ # Types+ "TradeInstruction",+ "TxResult",+ "PortfolioView",+ "PositionSnapshot",+ "ComposeContext",+ "ComposeResult",+ "DecisionCycleResult",+ "FeaturesResult",+ "FeatureVector",+ "Candle",+ "MarketSnapshot",+ "TradeDigest",+ "TradeDigestEntry",+ "Side",+ "TxStatus",+ "TradingMode",+ # Base Classes+ "BaseComposer",+ "BaseExecutionGateway",+ "BasePortfolioService",+ "BaseFeaturesPipeline",+ # Implementations+ "InMemoryPortfolioService",+ "PaperExecutionGateway",+ "CCXTMarketDataSource",+ "TechnicalFeaturesPipeline",+ "LLMComposer",+ "ModelConfig",+ "DecisionCoordinator",+ "CompetitionRuntime",+]diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/base_composer.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/base_composer.pynew file mode 100644index 000000000..8a5b41fc7--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/base_composer.py@@ -0,0 +1,40 @@+"""+Base interface for decision composers.+"""++from abc import ABC, abstractmethod+from .types import ComposeContext, ComposeResult+++class BaseComposer(ABC):+ """+ Base class for all composers.++ A composer takes market context and generates trade instructions.+ Different implementations can use:+ - LLM-based decisions (GPT-4, Claude, etc.)+ - Rule-based strategies (grid trading, momentum, mean reversion)+ - ML models (LSTM, transformers, reinforcement learning)+ """++ @abstractmethod+ async def compose(self, context: ComposeContext) -> ComposeResult:+ """+ Generate trading instructions based on context.++ Args:+ context: Market data, portfolio state, and historical performance++ Returns:+ ComposeResult with trade instructions+ """+ pass++ async def validate_instructions(self, result: ComposeResult) -> ComposeResult:+ """+ Optional validation hook for generated instructions.+ Can apply guardrails, risk limits, etc.++ Override in subclasses if needed.+ """+ return resultdiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/base_execution.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/base_execution.pynew file mode 100644index 000000000..166e78d5e--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/base_execution.py@@ -0,0 +1,51 @@+"""+Base interface for execution gateways.+"""++from abc import ABC, abstractmethod+from typing import List+from .types import TradeInstruction, TxResult, FeatureVector+++class BaseExecutionGateway(ABC):+ """+ Base class for all execution gateways.++ An execution gateway takes trade instructions and executes them,+ either in paper trading mode or against a live exchange.+ """++ @abstractmethod+ async def execute(+ self,+ instructions: List[TradeInstruction],+ market_features: List[FeatureVector]+ ) -> List[TxResult]:+ """+ Execute trade instructions.++ Args:+ instructions: List of trades to execute+ market_features: Current market data (for paper trading price reference)++ Returns:+ List of transaction results+ """+ pass++ @abstractmethod+ async def test_connection(self) -> bool:+ """+ Test connection to execution venue.++ Returns:+ True if connected, False otherwise+ """+ pass++ @abstractmethod+ async def close(self) -> None:+ """+ Close connection and clean up resources.+ """+ passdiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/base_features.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/base_features.pynew file mode 100644index 000000000..56e646d84--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/base_features.py@@ -0,0 +1,34 @@+"""+Base interface for features pipelines.+"""++from abc import ABC, abstractmethod+from .types import FeaturesResult+++class BaseFeaturesPipeline(ABC):+ """+ Base class for feature extraction pipelines.++ A features pipeline fetches market data and computes technical indicators.+ """++ @abstractmethod+ async def build(self) -> FeaturesResult:+ """+ Build feature vectors from market data.++ Returns:+ FeaturesResult with computed features+ """+ pass++ @abstractmethod+ async def update_symbols(self, symbols: list[str]) -> None:+ """+ Update the list of symbols to track.++ Args:+ symbols: List of trading symbols+ """+ passdiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/base_portfolio.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/base_portfolio.pynew file mode 100644index 000000000..d078a651a--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/base_portfolio.py@@ -0,0 +1,55 @@+"""+Base interface for portfolio services.+"""++from abc import ABC, abstractmethod+from typing import Dict+from .types import TxResult, PortfolioView+++class BasePortfolioService(ABC):+ """+ Base class for portfolio management.++ Tracks cash, positions, realized/unrealized P&L.+ """++ @abstractmethod+ async def apply_trade(self, tx: TxResult) -> None:+ """+ Apply a completed trade to the portfolio.++ Args:+ tx: Transaction result from execution gateway+ """+ pass++ @abstractmethod+ async def mark_to_market(self, prices: Dict[str, float]) -> None:+ """+ Update unrealized P&L based on current market prices.++ Args:+ prices: Dict of symbol -> current price+ """+ pass++ @abstractmethod+ async def get_portfolio_view(self) -> PortfolioView:+ """+ Get current portfolio snapshot.++ Returns:+ PortfolioView with cash, positions, and P&L+ """+ pass++ @abstractmethod+ async def reset(self, initial_capital: float) -> None:+ """+ Reset portfolio to initial state.++ Args:+ initial_capital: Starting cash balance+ """+ passdiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/competition_runtime.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/competition_runtime.pynew file mode 100644index 000000000..78abf9fc1--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/competition_runtime.py@@ -0,0 +1,178 @@+"""+Competition runtime for managing Alpha Arena competitions.+"""++import asyncio+from typing import List, Dict, Optional+from .decision_coordinator import DecisionCoordinator+from .llm_composer import LLMComposer, ModelConfig+from .paper_execution import PaperExecutionGateway+from .portfolio_service import InMemoryPortfolioService+from .market_data_source import CCXTMarketDataSource+from .features_pipeline import TechnicalFeaturesPipeline+from .types import DecisionCycleResult+++class CompetitionRuntime:+ """+ Runtime for managing a multi-model trading competition.++ Responsibilities:+ - Initialize all components (composer, execution, portfolios, etc.)+ - Run trading cycles at specified intervals+ - Persist state to database+ - Stream updates to UI+ """++ def __init__(+ self,+ competition_id: str,+ models: List[ModelConfig],+ symbols: List[str],+ initial_capital: float = 10000.0,+ exchange_id: str = "kraken",+ custom_prompt: Optional[str] = None+ ):+ """+ Initialize competition runtime.++ Args:+ competition_id: Unique competition ID+ models: List of competing LLM models+ symbols: List of trading symbols+ initial_capital: Starting capital per model+ exchange_id: Exchange for market data+ custom_prompt: Optional custom trading instructions+ """+ self.competition_id = competition_id+ self.models = models+ self.symbols = symbols+ self.initial_capital = initial_capital+ self.is_running = False++ # Create components+ self.market_data_source = CCXTMarketDataSource(+ exchange_id=exchange_id,+ testnet=False,+ rate_limit=True+ )++ self.features_pipeline = TechnicalFeaturesPipeline(+ market_data_source=self.market_data_source,+ symbols=symbols,+ interval="1h", # 1-hour candles for better technical analysis+ lookback=168 # 168 hours = 7 days of hourly data+ )++ self.execution_gateway = PaperExecutionGateway(+ fee_bps=10.0,+ default_slippage_bps=5.0+ )++ # Create portfolio for each model+ self.portfolios: Dict[str, InMemoryPortfolioService] = {}+ model_names = [model.name for model in models]++ for model_name in model_names:+ self.portfolios[model_name] = InMemoryPortfolioService(+ initial_capital=initial_capital+ )++ # Create composer+ self.composer = LLMComposer(+ models=models,+ custom_prompt=custom_prompt,+ max_positions=3,+ max_leverage=10.0+ )++ # Create coordinator+ self.coordinator = DecisionCoordinator(+ strategy_id=competition_id,+ composer=self.composer,+ execution_gateway=self.execution_gateway,+ features_pipeline=self.features_pipeline,+ portfolios=self.portfolios,+ model_names=model_names+ )++ async def run_cycle(self) -> DecisionCycleResult:+ """+ Run a single trading cycle.++ Returns:+ DecisionCycleResult with all decisions and executions+ """+ result = await self.coordinator.run_once()+ return result++ async def run_continuous(self, cycle_interval_seconds: int = 900):+ """+ Run continuous trading cycles.++ Args:+ cycle_interval_seconds: Seconds between cycles (default: 900 = 15 minutes)+ """+ self.is_running = True++ while self.is_running:+ try:+ # Run cycle+ result = await self.run_cycle()++ print(f"Cycle {result.cycle_number} complete", flush=True)++ # Wait for next cycle+ await asyncio.sleep(cycle_interval_seconds)++ except Exception as e:+ print(f"Error in trading cycle: {e}", flush=True)+ # Continue despite errors+ await asyncio.sleep(cycle_interval_seconds)++ def stop(self):+ """Stop the competition."""+ self.is_running = False++ async def get_leaderboard(self) -> List[Dict]:+ """+ Get current leaderboard.++ Returns:+ List of model rankings+ """+ leaderboard = []++ for model_name, portfolio in self.portfolios.items():+ view = await portfolio.get_portfolio_view()+ leaderboard.append({+ "model_name": model_name,+ "portfolio_value": view.total_value,+ "total_pnl": view.total_realized_pnl + view.total_unrealized_pnl,+ "return_pct": ((view.total_value - self.initial_capital) / self.initial_capital) * 100.0,+ "trades_count": view.trades_count,+ "cash": view.cash,+ "positions_count": len(view.positions)+ })++ # Sort by portfolio value+ leaderboard.sort(key=lambda x: x["portfolio_value"], reverse=True)++ # Add rank+ for i, entry in enumerate(leaderboard):+ entry["rank"] = i + 1++ return leaderboard++ async def get_portfolio_snapshot(self, model_name: str) -> Optional[Dict]:+ """Get portfolio snapshot for a specific model."""+ if model_name not in self.portfolios:+ return None++ view = await self.portfolios[model_name].get_portfolio_view()+ return view.to_dict()++ async def close(self):+ """Clean up resources."""+ await self.market_data_source.close()+ await self.execution_gateway.close()diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/decision_coordinator.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/decision_coordinator.pynew file mode 100644index 000000000..2eaf45282--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/decision_coordinator.py@@ -0,0 +1,168 @@+"""+Decision coordinator for orchestrating trading cycles.+"""++import time+import uuid+from typing import List, Dict+from .base_composer import BaseComposer+from .base_execution import BaseExecutionGateway+from .base_portfolio import BasePortfolioService+from .base_features import BaseFeaturesPipeline+from .types import (+ ComposeContext,+ DecisionCycleResult,+ PortfolioView,+ TradeDigest,+ ComposeResult+)+++class DecisionCoordinator:+ """+ Coordinates a single trading cycle.++ Flow:+ 1. Build features (market data + technical indicators)+ 2. Get portfolio state+ 3. Build performance digest+ 4. LLM decision via composer+ 5. Execute trades+ 6. Update portfolio+ 7. Return results+ """++ def __init__(+ self,+ strategy_id: str,+ composer: BaseComposer,+ execution_gateway: BaseExecutionGateway,+ features_pipeline: BaseFeaturesPipeline,+ portfolios: Dict[str, BasePortfolioService], # One per model+ model_names: List[str]+ ):+ """+ Initialize decision coordinator.++ Args:+ strategy_id: Competition/strategy ID+ composer: Decision composer (LLM-based)+ execution_gateway: Execution gateway (paper or live)+ features_pipeline: Features pipeline+ portfolios: Dict of model_name -> portfolio service+ model_names: List of competing model names+ """+ self.strategy_id = strategy_id+ self.composer = composer+ self.execution_gateway = execution_gateway+ self.features_pipeline = features_pipeline+ self.portfolios = portfolios+ self.model_names = model_names+ self.cycle_count = 0++ async def run_once(self) -> DecisionCycleResult:+ """+ Execute one trading cycle for all models.++ Returns:+ DecisionCycleResult with all decisions and executions+ """+ self.cycle_count += 1+ timestamp_ms = int(time.time() * 1000)+ cycle_id = f"cycle_{uuid.uuid4().hex[:8]}"++ # 1. Build features+ features_result = await self.features_pipeline.build()++ # 2. Get all decisions from competing models+ compose_results: List[ComposeResult] = []+ all_instructions = []++ for model_name in self.model_names:+ # Get portfolio for this model+ portfolio = self.portfolios[model_name]+ portfolio_view = await portfolio.get_portfolio_view()++ # Build digest (simplified - can be enhanced)+ digest = TradeDigest(+ total_trades=portfolio_view.trades_count,+ total_realized_pnl=portfolio_view.total_realized_pnl,+ overall_win_rate=0.0, # TODO: Calculate from trade history+ sharpe_ratio=0.0, # TODO: Calculate+ max_drawdown=0.0, # TODO: Calculate+ by_instrument={}+ )++ # Create context+ context = ComposeContext(+ ts=timestamp_ms,+ compose_id=f"{cycle_id}_{model_name}",+ strategy_id=self.strategy_id,+ model_name=model_name,+ features=features_result.features,+ portfolio=portfolio_view,+ digest=digest+ )++ # Get decision from LLM+ compose_result = await self.composer.compose(context)+ compose_results.append(compose_result)++ # Collect instructions+ all_instructions.extend(compose_result.instructions)++ # 3. Execute all trades+ tx_results = await self.execution_gateway.execute(+ all_instructions,+ features_result.features+ )++ # 4. Apply trades to respective portfolios+ for tx in tx_results:+ model_name = tx.instruction.model_name+ if model_name and model_name in self.portfolios:+ await self.portfolios[model_name].apply_trade(tx)++ # 5. Mark portfolios to market+ current_prices = {+ feat.symbol: feat.close+ for feat in features_result.features+ }++ for portfolio in self.portfolios.values():+ await portfolio.mark_to_market(current_prices)++ # 6. Get updated portfolio snapshots+ portfolio_snapshots = {}+ for model_name in self.model_names:+ portfolio_snapshots[model_name] = await self.portfolios[model_name].get_portfolio_view()++ # 7. Build leaderboard+ leaderboard = []+ for model_name in self.model_names:+ portfolio_view = portfolio_snapshots[model_name]+ leaderboard.append({+ "model_name": model_name,+ "portfolio_value": portfolio_view.total_value,+ "total_pnl": portfolio_view.total_realized_pnl + portfolio_view.total_unrealized_pnl,+ "trades_count": portfolio_view.trades_count,+ "cash": portfolio_view.cash+ })++ # Sort by portfolio value (descending)+ leaderboard.sort(key=lambda x: x["portfolio_value"], reverse=True)++ # Add rank+ for i, entry in enumerate(leaderboard):+ entry["rank"] = i + 1++ # 8. Return complete cycle result+ return DecisionCycleResult(+ cycle_id=cycle_id,+ cycle_number=self.cycle_count,+ timestamp_ms=timestamp_ms,+ compose_results=compose_results,+ tx_results=tx_results,+ portfolio_snapshots=portfolio_snapshots,+ leaderboard=leaderboard+ )diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/features_pipeline.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/features_pipeline.pynew file mode 100644index 000000000..380e463f6--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/features_pipeline.py@@ -0,0 +1,268 @@+"""+Features pipeline for computing technical indicators.+"""++import time+import numpy as np+from typing import List, Dict, Optional+from .base_features import BaseFeaturesPipeline+from .market_data_source import CCXTMarketDataSource+from .types import FeaturesResult, FeatureVector, Candle, MarketSnapshot+++class TechnicalFeaturesPipeline(BaseFeaturesPipeline):+ """+ Features pipeline that computes technical indicators.++ Indicators:+ - RSI (Relative Strength Index)+ - MACD (Moving Average Convergence Divergence)+ - Bollinger Bands+ - ATR (Average True Range)+ - Volatility+ """++ def __init__(+ self,+ market_data_source: CCXTMarketDataSource,+ symbols: List[str],+ interval: str = "1m",+ lookback: int = 100+ ):+ """+ Initialize features pipeline.++ Args:+ market_data_source: Market data source+ symbols: List of symbols to track+ interval: Candle interval+ lookback: Number of candles to fetch+ """+ self.market_data_source = market_data_source+ self.symbols = symbols+ self.interval = interval+ self.lookback = lookback++ async def build(self) -> FeaturesResult:+ """+ Build feature vectors with technical indicators.+ """+ timestamp_ms = int(time.time() * 1000)++ # Fetch candles+ candles_map = await self.market_data_source.get_recent_candles(+ self.symbols,+ self.interval,+ self.lookback+ )++ # Fetch market snapshots+ snapshots = await self.market_data_source.get_market_snapshot(self.symbols)+ snapshot_map = {snap.symbol: snap for snap in snapshots}++ # Compute features for each symbol+ features = []++ for symbol in self.symbols:+ candles = candles_map.get(symbol, [])+ snapshot = snapshot_map.get(symbol)++ if not candles or not snapshot:+ continue++ # Latest candle+ latest = candles[-1]++ # Compute technical indicators+ indicators = self._compute_indicators(candles)++ # Calculate spread in basis points+ spread_bps = 0.0+ if snapshot.ask > 0 and snapshot.bid > 0:+ spread_bps = ((snapshot.ask - snapshot.bid) / snapshot.bid) * 10000.0++ features.append(FeatureVector(+ symbol=symbol,+ timestamp_ms=timestamp_ms,+ close=latest.close,+ open=latest.open,+ high=latest.high,+ low=latest.low,+ volume=latest.volume,+ bid=snapshot.bid,+ ask=snapshot.ask,+ spread_bps=spread_bps,+ rsi_14=indicators.get('rsi_14'),+ macd=indicators.get('macd'),+ macd_signal=indicators.get('macd_signal'),+ macd_histogram=indicators.get('macd_histogram'),+ bb_upper=indicators.get('bb_upper'),+ bb_middle=indicators.get('bb_middle'),+ bb_lower=indicators.get('bb_lower'),+ atr_14=indicators.get('atr_14'),+ volatility_24h=indicators.get('volatility_24h'),+ ))++ return FeaturesResult(+ features=features,+ timestamp_ms=timestamp_ms,+ lookback_periods=self.lookback+ )++ def _compute_indicators(self, candles: List[Candle]) -> Dict[str, Optional[float]]:+ """+ Compute technical indicators from candles.+ """+ if len(candles) < 30:+ return {}++ closes = np.array([c.close for c in candles])+ highs = np.array([c.high for c in candles])+ lows = np.array([c.low for c in candles])++ indicators = {}++ try:+ # RSI (14-period)+ indicators['rsi_14'] = self._compute_rsi(closes, period=14)++ # MACD (12, 26, 9)+ macd_data = self._compute_macd(closes, fast=12, slow=26, signal=9)+ indicators.update(macd_data)++ # Bollinger Bands (20, 2)+ bb_data = self._compute_bollinger_bands(closes, period=20, std_dev=2.0)+ indicators.update(bb_data)++ # ATR (14-period)+ indicators['atr_14'] = self._compute_atr(highs, lows, closes, period=14)++ # Volatility (rolling standard deviation)+ indicators['volatility_24h'] = float(np.std(closes[-24:]) if len(closes) >= 24 else 0.0)++ except Exception as e:+ print(f"Error computing indicators: {e}", flush=True)++ return indicators++ def _compute_rsi(self, prices: np.ndarray, period: int = 14) -> Optional[float]:+ """Compute RSI (Relative Strength Index)."""+ if len(prices) < period + 1:+ return None++ deltas = np.diff(prices)+ gains = np.where(deltas > 0, deltas, 0)+ losses = np.where(deltas < 0, -deltas, 0)++ avg_gain = np.mean(gains[-period:])+ avg_loss = np.mean(losses[-period:])++ if avg_loss == 0:+ return 100.0++ rs = avg_gain / avg_loss+ rsi = 100.0 - (100.0 / (1.0 + rs))++ return float(rsi)++ def _compute_macd(+ self,+ prices: np.ndarray,+ fast: int = 12,+ slow: int = 26,+ signal: int = 9+ ) -> Dict[str, Optional[float]]:+ """Compute MACD (Moving Average Convergence Divergence)."""+ if len(prices) < slow + signal:+ return {+ 'macd': None,+ 'macd_signal': None,+ 'macd_histogram': None+ }++ # Exponential moving averages+ ema_fast = self._ema(prices, fast)+ ema_slow = self._ema(prices, slow)++ macd_line = ema_fast - ema_slow++ # Signal line (EMA of MACD)+ macd_values = []+ for i in range(len(prices) - slow + 1):+ macd_values.append(ema_fast - ema_slow)++ signal_line = self._ema(np.array(macd_values), signal)++ histogram = macd_line - signal_line++ return {+ 'macd': float(macd_line),+ 'macd_signal': float(signal_line),+ 'macd_histogram': float(histogram)+ }++ def _compute_bollinger_bands(+ self,+ prices: np.ndarray,+ period: int = 20,+ std_dev: float = 2.0+ ) -> Dict[str, Optional[float]]:+ """Compute Bollinger Bands."""+ if len(prices) < period:+ return {+ 'bb_upper': None,+ 'bb_middle': None,+ 'bb_lower': None+ }++ recent = prices[-period:]+ middle = float(np.mean(recent))+ std = float(np.std(recent))++ upper = middle + (std_dev * std)+ lower = middle - (std_dev * std)++ return {+ 'bb_upper': upper,+ 'bb_middle': middle,+ 'bb_lower': lower+ }++ def _compute_atr(+ self,+ highs: np.ndarray,+ lows: np.ndarray,+ closes: np.ndarray,+ period: int = 14+ ) -> Optional[float]:+ """Compute ATR (Average True Range)."""+ if len(highs) < period + 1:+ return None++ true_ranges = []+ for i in range(1, len(highs)):+ high_low = highs[i] - lows[i]+ high_close = abs(highs[i] - closes[i - 1])+ low_close = abs(lows[i] - closes[i - 1])+ true_range = max(high_low, high_close, low_close)+ true_ranges.append(true_range)++ atr = float(np.mean(true_ranges[-period:]))+ return atr++ def _ema(self, prices: np.ndarray, period: int) -> float:+ """Calculate Exponential Moving Average."""+ if len(prices) < period:+ return float(np.mean(prices))++ multiplier = 2.0 / (period + 1.0)+ ema = float(np.mean(prices[:period]))++ for price in prices[period:]:+ ema = (price * multiplier) + (ema * (1.0 - multiplier))++ return ema++ async def update_symbols(self, symbols: List[str]) -> None:+ """Update the list of symbols to track."""+ self.symbols = symbolsdiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/llm_composer.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/llm_composer.pynew file mode 100644index 000000000..79645bd2c--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/llm_composer.py@@ -0,0 +1,346 @@+"""+LLM-based composer for multi-model trading competitions.+"""++import json+import asyncio+import time+import sys+from typing import List, Dict, Optional+from dataclasses import dataclass++from agno.agent import Agent as AgnoAgent+from agno.models.openai import OpenAIChat++try:+ from agno.models.anthropic import Claude+except ImportError:+ Claude = None++try:+ from agno.models.google import Gemini+except ImportError:+ Gemini = None++from .base_composer import BaseComposer+from .types import ComposeContext, ComposeResult, TradeInstruction, Side+++@dataclass+class ModelConfig:+ """Configuration for a single LLM model."""+ name: str+ provider: str # openai, google, anthropic, openrouter, deepseek, groq+ model_id: str+ api_key: str+ temperature: float = 0.7+ max_tokens: int = 1000+ timeout_seconds: int = 30+++class LLMComposer(BaseComposer):+ """+ LLM-based composer for trading decisions.++ Supports multiple LLM providers and models competing simultaneously.+ """++ def __init__(+ self,+ models: List[ModelConfig],+ custom_prompt: Optional[str] = None,+ max_positions: int = 3,+ max_leverage: float = 10.0+ ):+ """+ Initialize LLM composer.++ Args:+ models: List of model configurations+ custom_prompt: Optional custom trading instructions+ max_positions: Maximum concurrent positions (guardrail)+ max_leverage: Maximum leverage allowed (guardrail)+ """+ self.models = models+ self.custom_prompt = custom_prompt+ self.max_positions = max_positions+ self.max_leverage = max_leverage+ self._agents: Dict[str, AgnoAgent] = {}++ def _create_agent(self, model_config: ModelConfig) -> AgnoAgent:+ """Create Agno agent for a model."""++ # Create model based on provider+ if model_config.provider == "openai":+ # o1/o4 models use max_completion_tokens and don't support custom temperature+ if model_config.model_id.startswith(('o1-', 'o4-')):+ model = OpenAIChat(+ id=model_config.model_id,+ api_key=model_config.api_key,+ max_completion_tokens=model_config.max_tokens+ # temperature not supported for o1/o4 models+ )+ else:+ model = OpenAIChat(+ id=model_config.model_id,+ api_key=model_config.api_key,+ temperature=model_config.temperature,+ max_tokens=model_config.max_tokens+ )+ elif model_config.provider == "google" and Gemini:+ model = Gemini(+ id=model_config.model_id,+ api_key=model_config.api_key+ )+ elif model_config.provider == "anthropic" and Claude:+ model = Claude(+ id=model_config.model_id,+ api_key=model_config.api_key+ )+ else:+ # Use OpenAI-compatible for other providers (OpenRouter, DeepSeek, Groq)+ base_url_map = {+ "openrouter": "https://openrouter.ai/api/v1",+ "deepseek": "https://api.deepseek.com/v1",+ "groq": "https://api.groq.com/openai/v1"+ }+ base_url = base_url_map.get(model_config.provider, "https://api.openai.com/v1")++ model = OpenAIChat(+ id=model_config.model_id,+ api_key=model_config.api_key,+ base_url=base_url,+ temperature=model_config.temperature,+ max_tokens=model_config.max_tokens+ )++ # Create agent with structured output+ agent = AgnoAgent(+ model=model,+ markdown=False+ )++ return agent++ def _build_prompt(self, context: ComposeContext) -> str:+ """+ Build trading prompt from context.+ """+ # Portfolio summary+ portfolio_summary = f"""+PORTFOLIO SUMMARY:+- Cash: ${context.portfolio.cash:.2f}+- Total Value: ${context.portfolio.total_value:.2f}+- Unrealized P&L: ${context.portfolio.total_unrealized_pnl:.2f}+- Realized P&L: ${context.portfolio.total_realized_pnl:.2f}+- Trades: {context.portfolio.trades_count}+"""++ # Current positions+ positions_str = ""+ if context.portfolio.positions:+ positions_str = "\nCURRENT POSITIONS:\n"+ for symbol, pos in context.portfolio.positions.items():+ pnl_pct = (pos.unrealized_pnl / (pos.avg_entry_price * abs(pos.quantity))) * 100 if pos.avg_entry_price > 0 else 0+ positions_str += f"- {symbol}: {pos.quantity:.4f} @ ${pos.avg_entry_price:.2f}, Current: ${pos.current_price:.2f}, P&L: ${pos.unrealized_pnl:.2f} ({pnl_pct:+.2f}%)\n"+ else:+ positions_str = "\nNo open positions.\n"++ # Market data+ market_data = "\nMARKET DATA:\n"+ for feat in context.features:+ market_data += f"\n{feat.symbol}:\n"+ market_data += f" Price: ${feat.close:.2f} (Bid: ${feat.bid:.2f}, Ask: ${feat.ask:.2f})\n"+ market_data += f" 24h Change: {((feat.close - feat.open) / feat.open * 100) if feat.open > 0 else 0:.2f}%\n"++ if feat.rsi_14:+ market_data += f" RSI(14): {feat.rsi_14:.2f}\n"+ if feat.macd:+ market_data += f" MACD: {feat.macd:.4f}, Signal: {feat.macd_signal:.4f}, Histogram: {feat.macd_histogram:.4f}\n"+ if feat.bb_upper:+ market_data += f" Bollinger Bands: Upper ${feat.bb_upper:.2f}, Middle ${feat.bb_middle:.2f}, Lower ${feat.bb_lower:.2f}\n"+ if feat.atr_14:+ market_data += f" ATR(14): ${feat.atr_14:.2f}\n"++ # Performance digest+ digest_str = ""+ if context.digest and context.digest.total_trades > 0:+ digest_str = f"""+PERFORMANCE HISTORY:+- Total Trades: {context.digest.total_trades}+- Total Realized P&L: ${context.digest.total_realized_pnl:.2f}+- Win Rate: {context.digest.overall_win_rate:.1f}%+- Sharpe Ratio: {context.digest.sharpe_ratio:.2f}+- Max Drawdown: {context.digest.max_drawdown:.2f}%+"""++ # Custom instructions+ custom_instructions = ""+ if self.custom_prompt:+ custom_instructions = f"\nCUSTOM TRADING INSTRUCTIONS:\n{self.custom_prompt}\n"++ # Combine into full prompt+ prompt = f"""You are an expert cryptocurrency trader. Analyze the market data and make a trading decision.++{portfolio_summary}+{positions_str}+{market_data}+{digest_str}+{custom_instructions}++RULES:+1. You can BUY, SELL, HOLD, or WAIT for each symbol+2. Consider technical indicators (RSI, MACD, Bollinger Bands, ATR)+3. Manage risk - don't over-leverage+4. Maximum {self.max_positions} positions at once+5. Maximum {self.max_leverage}x leverage+6. Provide clear reasoning for your decision++DECISION TYPES:+- BUY: Enter a long position or add to existing long+- SELL: Enter a short position or close/reduce long position+- HOLD: Maintain current positions (use when you have open positions but don't want to trade)+- WAIT: No action, waiting for better opportunity (use when you have NO positions)++Respond with a JSON object in this exact format:+{{+ "decision": "BUY" or "SELL" or "HOLD" or "WAIT",+ "symbol": "BTC/USD",+ "quantity": 0.01,+ "leverage": 1.0,+ "confidence": 0.75,+ "reasoning": "Detailed explanation of your decision"+}}++If you decide to HOLD or WAIT, set quantity to 0.+"""++ return prompt++ async def compose(self, context: ComposeContext) -> ComposeResult:+ """+ Generate trading instruction using LLM.++ Runs a single model specified in context.model_name.+ """+ model_config = next((m for m in self.models if m.name == context.model_name), None)++ if not model_config:+ # Return empty result if model not found+ return ComposeResult(+ instructions=[],+ compose_id=context.compose_id,+ model_name=context.model_name,+ rationale="Model not found",+ decision_type="WAIT"+ )++ # Get or create agent+ if model_config.name not in self._agents:+ self._agents[model_config.name] = self._create_agent(model_config)++ agent = self._agents[model_config.name]++ # Build prompt+ prompt = self._build_prompt(context)++ try:+ print(f"[LLMComposer] Calling {model_config.name} for trading decision...", flush=True, file=sys.stderr)++ # Call LLM (agent.run() is synchronous in Agno SDK)+ # Run it in executor to avoid blocking the event loop+ loop = asyncio.get_event_loop()+ response = await asyncio.wait_for(+ loop.run_in_executor(None, lambda: agent.run(prompt)),+ timeout=model_config.timeout_seconds+ )++ # Parse JSON response+ response_text = response.content if hasattr(response, 'content') else str(response)+ print(f"[LLMComposer] {model_config.name} response: {response_text[:200]}...", flush=True, file=sys.stderr)++ # Extract JSON from response+ decision_data = self._extract_json(response_text)+ print(f"[LLMComposer] {model_config.name} decision: {decision_data}", flush=True, file=sys.stderr)++ # Convert to TradeInstruction+ instructions = []+ decision_type = 'WAIT' # Default++ if decision_data:+ decision = decision_data.get('decision', 'WAIT').upper()+ decision_type = decision+ symbol = decision_data.get('symbol', context.features[0].symbol if context.features else 'BTC/USD')+ quantity = float(decision_data.get('quantity', 0))+ leverage = min(float(decision_data.get('leverage', 1.0)), self.max_leverage)+ confidence = float(decision_data.get('confidence', 0.5))+ reasoning = decision_data.get('reasoning', '')++ # Only create trade instructions for BUY/SELL with quantity > 0+ if decision in ['BUY', 'SELL'] and quantity > 0:+ instructions.append(TradeInstruction(+ symbol=symbol,+ side=Side.BUY if decision == 'BUY' else Side.SELL,+ quantity=quantity,+ leverage=leverage,+ max_slippage_bps=50,+ model_name=model_config.name,+ reasoning=reasoning,+ confidence=confidence+ ))++ return ComposeResult(+ instructions=instructions,+ compose_id=context.compose_id,+ model_name=model_config.name,+ rationale=decision_data.get('reasoning', '') if decision_data else '',+ decision_type=decision_type # Store the decision type (BUY/SELL/HOLD/WAIT)+ )++ except asyncio.TimeoutError:+ print(f"[LLMComposer] TIMEOUT for model {model_config.name} after {model_config.timeout_seconds}s", flush=True, file=sys.stderr)+ return ComposeResult(+ instructions=[],+ compose_id=context.compose_id,+ model_name=model_config.name,+ rationale="Model timed out",+ decision_type="WAIT"+ )+ except Exception as e:+ print(f"[LLMComposer] ERROR in {model_config.name}: {type(e).__name__}: {e}", flush=True, file=sys.stderr)+ import traceback+ traceback.print_exc(file=sys.stderr)+ return ComposeResult(+ instructions=[],+ compose_id=context.compose_id,+ model_name=model_config.name,+ rationale=f"Error: {str(e)}",+ decision_type="WAIT"+ )++ def _extract_json(self, text: str) -> Optional[Dict]:+ """Extract JSON object from text response."""+ try:+ # Try direct JSON parse+ return json.loads(text)+ except:+ pass++ # Try to find JSON block in markdown+ import re+ json_match = re.search(r'```json\s*(\{.*?\})\s*```', text, re.DOTALL)+ if json_match:+ try:+ return json.loads(json_match.group(1))+ except:+ pass++ # Try to find any JSON object+ json_match = re.search(r'\{.*?\}', text, re.DOTALL)+ if json_match:+ try:+ return json.loads(json_match.group(0))+ except:+ pass++ return Nonediff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/market_data_source.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/market_data_source.pynew file mode 100644index 000000000..bc3b74c95--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/market_data_source.py@@ -0,0 +1,193 @@+"""+Market data source using CCXT for fetching candles and snapshots.+"""++import ccxt+import time+import asyncio+from typing import List, Dict, Optional+from datetime import datetime+from .types import Candle, MarketSnapshot+++class CCXTMarketDataSource:+ """+ Market data source using CCXT library.++ Supports multiple exchanges (Binance, Kraken, Coinbase, etc.)+ """++ def __init__(+ self,+ exchange_id: str = "kraken",+ testnet: bool = False,+ rate_limit: bool = True+ ):+ """+ Initialize market data source.++ Args:+ exchange_id: Exchange name (binance, kraken, coinbase, etc.)+ testnet: Use testnet/sandbox (if available)+ rate_limit: Enable rate limiting+ """+ self.exchange_id = exchange_id+ self.testnet = testnet+ self.rate_limit = rate_limit+ self._exchange: Optional[ccxt.Exchange] = None+ self._last_request_time = 0.0+ self._min_request_interval = 1.0 # 1 second between requests++ def _get_exchange(self) -> ccxt.Exchange:+ """Get or create exchange instance."""+ if self._exchange is None:+ exchange_class = getattr(ccxt, self.exchange_id)+ config = {+ 'enableRateLimit': self.rate_limit,+ 'timeout': 10000,+ }++ if self.testnet:+ config['sandbox'] = True++ self._exchange = exchange_class(config)++ return self._exchange++ async def _rate_limit_delay(self) -> None:+ """Enforce rate limiting."""+ if not self.rate_limit:+ return++ now = time.time()+ time_since_last = now - self._last_request_time++ if time_since_last < self._min_request_interval:+ await asyncio.sleep(self._min_request_interval - time_since_last)++ self._last_request_time = time.time()++ async def get_recent_candles(+ self,+ symbols: List[str],+ interval: str = "1m",+ lookback: int = 100+ ) -> Dict[str, List[Candle]]:+ """+ Fetch recent OHLCV candles for multiple symbols.++ Args:+ symbols: List of trading pairs (e.g., ["BTC/USD", "ETH/USD"])+ interval: Timeframe (1m, 5m, 15m, 1h, 1d)+ lookback: Number of candles to fetch++ Returns:+ Dict mapping symbol -> list of candles+ """+ exchange = self._get_exchange()+ result = {}++ for symbol in symbols:+ try:+ await self._rate_limit_delay()++ # Fetch OHLCV data+ ohlcv = exchange.fetch_ohlcv(+ symbol=symbol,+ timeframe=interval,+ limit=lookback+ )++ # Convert to Candle objects+ candles = [+ Candle(+ timestamp=int(row[0]),+ open=float(row[1]),+ high=float(row[2]),+ low=float(row[3]),+ close=float(row[4]),+ volume=float(row[5])+ )+ for row in ohlcv+ ]++ result[symbol] = candles++ except Exception as e:+ print(f"Error fetching candles for {symbol}: {e}", flush=True)+ result[symbol] = []++ return result++ async def get_market_snapshot(+ self,+ symbols: List[str]+ ) -> List[MarketSnapshot]:+ """+ Get real-time market snapshots for multiple symbols.++ Args:+ symbols: List of trading pairs++ Returns:+ List of MarketSnapshot objects+ """+ exchange = self._get_exchange()+ snapshots = []+ timestamp_ms = int(time.time() * 1000)++ for symbol in symbols:+ try:+ await self._rate_limit_delay()++ # Fetch ticker+ ticker = exchange.fetch_ticker(symbol)++ # Extract data+ last_price = float(ticker.get('last', 0))+ bid = float(ticker.get('bid', last_price))+ ask = float(ticker.get('ask', last_price))+ volume_24h = float(ticker.get('quoteVolume', 0))+ high_24h = float(ticker.get('high', last_price))+ low_24h = float(ticker.get('low', last_price))++ # Calculate 24h change+ open_24h = float(ticker.get('open', last_price))+ change_24h_pct = 0.0+ if open_24h > 0:+ change_24h_pct = ((last_price - open_24h) / open_24h) * 100.0++ snapshots.append(MarketSnapshot(+ symbol=symbol,+ last_price=last_price,+ bid=bid,+ ask=ask,+ volume_24h=volume_24h,+ high_24h=high_24h,+ low_24h=low_24h,+ change_24h_pct=change_24h_pct,+ timestamp_ms=timestamp_ms+ ))++ except Exception as e:+ print(f"Error fetching snapshot for {symbol}: {e}", flush=True)+ # Create default snapshot on error+ snapshots.append(MarketSnapshot(+ symbol=symbol,+ last_price=0.0,+ bid=0.0,+ ask=0.0,+ volume_24h=0.0,+ high_24h=0.0,+ low_24h=0.0,+ change_24h_pct=0.0,+ timestamp_ms=timestamp_ms+ ))++ return snapshots++ async def close(self) -> None:+ """Close exchange connection."""+ if self._exchange is not None:+ await self._exchange.close()+ self._exchange = Nonediff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/paper_execution.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/paper_execution.pynew file mode 100644index 000000000..c08645cb1--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/paper_execution.py@@ -0,0 +1,106 @@+"""+Paper trading execution gateway.+Simulates order fills without connecting to a real exchange.+"""++import time+from typing import List+from .base_execution import BaseExecutionGateway+from .types import TradeInstruction, TxResult, FeatureVector, TxStatus, Side+++class PaperExecutionGateway(BaseExecutionGateway):+ """+ Paper trading execution gateway.++ Simulates instant fills at market price with configurable slippage and fees.+ """++ def __init__(self, fee_bps: float = 10.0, default_slippage_bps: float = 5.0):+ """+ Initialize paper trading gateway.++ Args:+ fee_bps: Trading fee in basis points (default 10 bps = 0.1%)+ default_slippage_bps: Default slippage in basis points (default 5 bps = 0.05%)+ """+ self.fee_bps = fee_bps+ self.default_slippage_bps = default_slippage_bps++ async def execute(+ self,+ instructions: List[TradeInstruction],+ market_features: List[FeatureVector]+ ) -> List[TxResult]:+ """+ Execute trade instructions in paper trading mode.++ Simulates fills at current market price ± slippage.+ """+ results = []++ # Build price map from features+ price_map = {+ feat.symbol: feat.close+ for feat in market_features+ }++ timestamp_ms = int(time.time() * 1000)++ for inst in instructions:+ # Skip HOLD instructions+ if inst.side == Side.HOLD:+ continue++ # Get reference price+ if inst.symbol not in price_map:+ # Reject if no price available+ results.append(TxResult(+ instruction=inst,+ status=TxStatus.REJECTED,+ error_message=f"No market price available for {inst.symbol}",+ timestamp_ms=timestamp_ms+ ))+ continue++ reference_price = price_map[inst.symbol]++ # Apply slippage+ slippage_bps = min(inst.max_slippage_bps, self.default_slippage_bps)+ slippage_factor = slippage_bps / 10000.0++ if inst.side == Side.BUY:+ # Buy at ask (higher price)+ fill_price = reference_price * (1 + slippage_factor)+ else: # SELL+ # Sell at bid (lower price)+ fill_price = reference_price * (1 - slippage_factor)++ # Calculate notional and fee+ notional = inst.quantity * fill_price+ fee = notional * (self.fee_bps / 10000.0)++ # Create successful fill+ results.append(TxResult(+ instruction=inst,+ status=TxStatus.FILLED,+ fill_price=fill_price,+ fill_quantity=inst.quantity,+ fee=fee,+ notional=notional,+ timestamp_ms=timestamp_ms+ ))++ return results++ async def test_connection(self) -> bool:+ """+ Paper trading always "connected".+ """+ return True++ async def close(self) -> None:+ """+ No cleanup needed for paper trading.+ """+ passdiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/portfolio_service.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/portfolio_service.pynew file mode 100644index 000000000..b2658af5c--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/portfolio_service.py@@ -0,0 +1,206 @@+"""+In-memory portfolio service for tracking trading state.+"""++import time+from typing import Dict+from .base_portfolio import BasePortfolioService+from .types import TxResult, PortfolioView, PositionSnapshot, Side, TxStatus+++class InMemoryPortfolioService(BasePortfolioService):+ """+ In-memory portfolio service.++ Tracks:+ - Cash balance+ - Open positions (long/short)+ - Realized P&L (from closed trades)+ - Unrealized P&L (mark-to-market)+ """++ def __init__(self, initial_capital: float = 10000.0):+ """+ Initialize portfolio.++ Args:+ initial_capital: Starting cash balance+ """+ self.initial_capital = initial_capital+ self.cash = initial_capital+ self.positions: Dict[str, PositionSnapshot] = {}+ self.total_realized_pnl = 0.0+ self.trades_count = 0++ async def apply_trade(self, tx: TxResult) -> None:+ """+ Apply a completed trade to the portfolio.++ Logic:+ - BUY: Deduct cash, increase/open long position+ - SELL: Add cash, reduce/close long or open short position+ """+ if tx.status != TxStatus.FILLED:+ return++ inst = tx.instruction+ symbol = inst.symbol+ side = inst.side+ quantity = tx.fill_quantity or 0.0+ price = tx.fill_price or 0.0+ fee = tx.fee++ # Update trade count+ self.trades_count += 1++ # Handle BUY+ if side == Side.BUY:+ cost = (quantity * price) + fee+ self.cash -= cost++ # Update or create position+ if symbol in self.positions:+ pos = self.positions[symbol]+ total_qty = pos.quantity + quantity+ total_cost = (pos.quantity * pos.avg_entry_price) + (quantity * price)+ new_avg_price = total_cost / total_qty if total_qty > 0 else price++ self.positions[symbol] = PositionSnapshot(+ symbol=symbol,+ quantity=total_qty,+ avg_entry_price=new_avg_price,+ current_price=price,+ unrealized_pnl=0.0, # Will be updated in mark_to_market+ leverage=inst.leverage,+ side=Side.BUY+ )+ else:+ self.positions[symbol] = PositionSnapshot(+ symbol=symbol,+ quantity=quantity,+ avg_entry_price=price,+ current_price=price,+ unrealized_pnl=0.0,+ leverage=inst.leverage,+ side=Side.BUY+ )++ # Handle SELL+ elif side == Side.SELL:+ proceeds = (quantity * price) - fee+ self.cash += proceeds++ if symbol in self.positions:+ pos = self.positions[symbol]++ if pos.quantity >= quantity:+ # Partial or full close of long position+ realized_pnl = (price - pos.avg_entry_price) * quantity+ self.total_realized_pnl += realized_pnl++ remaining_qty = pos.quantity - quantity+ if remaining_qty > 0.01: # Keep position open+ self.positions[symbol] = PositionSnapshot(+ symbol=symbol,+ quantity=remaining_qty,+ avg_entry_price=pos.avg_entry_price,+ current_price=price,+ unrealized_pnl=0.0,+ leverage=pos.leverage,+ side=Side.BUY+ )+ else:+ # Close position completely+ del self.positions[symbol]+ else:+ # Short position (sell more than we have)+ # First close existing long, then open short+ realized_pnl = (price - pos.avg_entry_price) * pos.quantity+ self.total_realized_pnl += realized_pnl++ short_qty = quantity - pos.quantity+ # For short, we need margin (assume 50% margin requirement)+ margin_required = (short_qty * price) * 0.5+ self.cash -= margin_required++ self.positions[symbol] = PositionSnapshot(+ symbol=symbol,+ quantity=-short_qty, # Negative for short+ avg_entry_price=price,+ current_price=price,+ unrealized_pnl=0.0,+ leverage=inst.leverage,+ side=Side.SELL+ )+ else:+ # Opening short position directly+ margin_required = (quantity * price) * 0.5+ self.cash -= margin_required++ self.positions[symbol] = PositionSnapshot(+ symbol=symbol,+ quantity=-quantity,+ avg_entry_price=price,+ current_price=price,+ unrealized_pnl=0.0,+ leverage=inst.leverage,+ side=Side.SELL+ )++ async def mark_to_market(self, prices: Dict[str, float]) -> None:+ """+ Update unrealized P&L based on current market prices.+ """+ for symbol, pos in self.positions.items():+ if symbol in prices:+ current_price = prices[symbol]+ pos.current_price = current_price++ if pos.quantity > 0:+ # Long position+ pos.unrealized_pnl = (current_price - pos.avg_entry_price) * pos.quantity+ else:+ # Short position+ pos.unrealized_pnl = (pos.avg_entry_price - current_price) * abs(pos.quantity)++ async def get_portfolio_view(self) -> PortfolioView:+ """+ Get current portfolio snapshot.+ """+ total_unrealized_pnl = sum(pos.unrealized_pnl for pos in self.positions.values())++ # Calculate exposures+ gross_exposure = 0.0+ net_exposure = 0.0++ for pos in self.positions.values():+ notional = abs(pos.quantity) * pos.current_price+ gross_exposure += notional++ if pos.quantity > 0:+ net_exposure += notional+ else:+ net_exposure -= notional++ total_value = self.cash + total_unrealized_pnl++ return PortfolioView(+ cash=self.cash,+ positions=self.positions.copy(),+ total_value=total_value,+ total_unrealized_pnl=total_unrealized_pnl,+ total_realized_pnl=self.total_realized_pnl,+ gross_exposure=gross_exposure,+ net_exposure=net_exposure,+ trades_count=self.trades_count+ )++ async def reset(self, initial_capital: float) -> None:+ """+ Reset portfolio to initial state.+ """+ self.initial_capital = initial_capital+ self.cash = initial_capital+ self.positions = {}+ self.total_realized_pnl = 0.0+ self.trades_count = 0diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/types.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/types.pynew file mode 100644index 000000000..cb2bd5afb--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/framework/types.py@@ -0,0 +1,355 @@+"""+Core types for the Alpha Arena trading framework.+"""++from dataclasses import dataclass, field+from typing import Dict, List, Optional, Literal+from enum import Enum+from datetime import datetime+++class Side(str, Enum):+ """Trade side."""+ BUY = "BUY"+ SELL = "SELL"+ HOLD = "HOLD"+++class TxStatus(str, Enum):+ """Transaction status."""+ FILLED = "FILLED"+ REJECTED = "REJECTED"+ PENDING = "PENDING"+ CANCELLED = "CANCELLED"+++class TradingMode(str, Enum):+ """Trading mode."""+ PAPER = "PAPER"+ LIVE = "LIVE"+++@dataclass+class TradeInstruction:+ """+ Instruction to execute a trade.+ Generated by composer, consumed by execution gateway.+ """+ symbol: str+ side: Side+ quantity: float+ leverage: float = 1.0+ max_slippage_bps: int = 50 # 0.5%+ model_name: Optional[str] = None # For multi-model competitions+ reasoning: Optional[str] = None+ confidence: Optional[float] = None+++@dataclass+class TxResult:+ """+ Result of a trade execution.+ Returned by execution gateway, consumed by portfolio service.+ """+ instruction: TradeInstruction+ status: TxStatus+ fill_price: Optional[float] = None+ fill_quantity: Optional[float] = None+ fee: float = 0.0+ notional: float = 0.0+ timestamp_ms: int = 0+ error_message: Optional[str] = None++ def to_dict(self) -> dict:+ return {+ "symbol": self.instruction.symbol,+ "side": self.instruction.side.value,+ "quantity": self.fill_quantity or 0.0,+ "price": self.fill_price or 0.0,+ "fee": self.fee,+ "notional": self.notional,+ "status": self.status.value,+ "model_name": self.instruction.model_name,+ "reasoning": self.instruction.reasoning,+ "confidence": self.instruction.confidence,+ "timestamp_ms": self.timestamp_ms,+ }+++@dataclass+class PositionSnapshot:+ """Snapshot of a single position."""+ symbol: str+ quantity: float+ avg_entry_price: float+ current_price: float+ unrealized_pnl: float+ leverage: float = 1.0+ side: Side = Side.BUY+++@dataclass+class PortfolioView:+ """+ Complete portfolio state at a point in time.+ Returned by portfolio service.+ """+ cash: float+ positions: Dict[str, PositionSnapshot]+ total_value: float+ total_unrealized_pnl: float+ total_realized_pnl: float+ gross_exposure: float+ net_exposure: float+ trades_count: int = 0++ def to_dict(self) -> dict:+ return {+ "cash": self.cash,+ "positions": {+ sym: {+ "symbol": pos.symbol,+ "quantity": pos.quantity,+ "avg_entry_price": pos.avg_entry_price,+ "current_price": pos.current_price,+ "unrealized_pnl": pos.unrealized_pnl,+ "leverage": pos.leverage,+ "side": pos.side.value,+ }+ for sym, pos in self.positions.items()+ },+ "total_value": self.total_value,+ "total_unrealized_pnl": self.total_unrealized_pnl,+ "total_realized_pnl": self.total_realized_pnl,+ "gross_exposure": self.gross_exposure,+ "net_exposure": self.net_exposure,+ "trades_count": self.trades_count,+ }+++@dataclass+class Candle:+ """OHLCV candle."""+ timestamp: int # Unix timestamp in milliseconds+ open: float+ high: float+ low: float+ close: float+ volume: float+++@dataclass+class MarketSnapshot:+ """Real-time market snapshot for a symbol."""+ symbol: str+ last_price: float+ bid: float+ ask: float+ volume_24h: float+ high_24h: float+ low_24h: float+ change_24h_pct: float+ timestamp_ms: int+++@dataclass+class FeatureVector:+ """+ Feature vector for a symbol at a point in time.+ Contains price data and technical indicators.+ """+ symbol: str+ timestamp_ms: int++ # Price data+ close: float+ open: float+ high: float+ low: float+ volume: float++ # Market snapshot+ bid: float+ ask: float+ spread_bps: float++ # Technical indicators+ rsi_14: Optional[float] = None+ macd: Optional[float] = None+ macd_signal: Optional[float] = None+ macd_histogram: Optional[float] = None+ bb_upper: Optional[float] = None+ bb_middle: Optional[float] = None+ bb_lower: Optional[float] = None+ atr_14: Optional[float] = None++ # Volatility+ volatility_24h: Optional[float] = None++ def to_dict(self) -> dict:+ return {+ "symbol": self.symbol,+ "timestamp_ms": self.timestamp_ms,+ "close": self.close,+ "open": self.open,+ "high": self.high,+ "low": self.low,+ "volume": self.volume,+ "bid": self.bid,+ "ask": self.ask,+ "spread_bps": self.spread_bps,+ "rsi_14": self.rsi_14,+ "macd": self.macd,+ "macd_signal": self.macd_signal,+ "macd_histogram": self.macd_histogram,+ "bb_upper": self.bb_upper,+ "bb_middle": self.bb_middle,+ "bb_lower": self.bb_lower,+ "atr_14": self.atr_14,+ "volatility_24h": self.volatility_24h,+ }+++@dataclass+class FeaturesResult:+ """Result from features pipeline."""+ features: List[FeatureVector]+ timestamp_ms: int+ lookback_periods: int+++@dataclass+class TradeDigestEntry:+ """Performance digest for a single symbol."""+ symbol: str+ trade_count: int+ realized_pnl: float+ win_rate: float+ avg_holding_ms: int+ last_trade_ts: int+++@dataclass+class TradeDigest:+ """+ Performance digest across all trading.+ Used to inform LLM of historical performance.+ """+ total_trades: int+ total_realized_pnl: float+ overall_win_rate: float+ sharpe_ratio: float+ max_drawdown: float+ by_instrument: Dict[str, TradeDigestEntry]++ def to_dict(self) -> dict:+ return {+ "total_trades": self.total_trades,+ "total_realized_pnl": self.total_realized_pnl,+ "overall_win_rate": self.overall_win_rate,+ "sharpe_ratio": self.sharpe_ratio,+ "max_drawdown": self.max_drawdown,+ "by_instrument": {+ sym: {+ "symbol": entry.symbol,+ "trade_count": entry.trade_count,+ "realized_pnl": entry.realized_pnl,+ "win_rate": entry.win_rate,+ "avg_holding_ms": entry.avg_holding_ms,+ }+ for sym, entry in self.by_instrument.items()+ },+ }+++@dataclass+class ComposeContext:+ """+ Context provided to composer for decision making.+ Contains all information needed to make a trading decision.+ """+ ts: int # Current timestamp in milliseconds+ compose_id: str # Unique ID for this decision cycle+ strategy_id: str # Competition/strategy ID+ model_name: str # Model making the decision++ # Market data+ features: List[FeatureVector]++ # Portfolio state+ portfolio: PortfolioView++ # Historical performance+ digest: Optional[TradeDigest] = None++ # Custom prompt/instructions+ custom_prompt: Optional[str] = None+++@dataclass+class ComposeResult:+ """+ Result from composer.+ Contains trade instructions to execute.+ """+ instructions: List[TradeInstruction]+ compose_id: str+ model_name: str+ rationale: Optional[str] = None+ decision_type: Optional[str] = None # BUY, SELL, HOLD, or WAIT+ metadata: Dict = field(default_factory=dict)+++@dataclass+class DecisionCycleResult:+ """+ Complete result of a decision cycle.+ Includes decisions, executions, and updated portfolio.+ """+ cycle_id: str+ cycle_number: int+ timestamp_ms: int++ # Decisions from all models+ compose_results: List[ComposeResult]++ # Execution results+ tx_results: List[TxResult]++ # Updated portfolio snapshots (per model)+ portfolio_snapshots: Dict[str, PortfolioView]++ # Performance metrics+ leaderboard: List[Dict] # Rankings by P&L++ def to_dict(self) -> dict:+ return {+ "cycle_id": self.cycle_id,+ "cycle_number": self.cycle_number,+ "timestamp_ms": self.timestamp_ms,+ "compose_results": [+ {+ "compose_id": cr.compose_id,+ "model_name": cr.model_name,+ "instructions": [+ {+ "symbol": inst.symbol,+ "side": inst.side.value,+ "quantity": inst.quantity,+ "leverage": inst.leverage,+ "reasoning": inst.reasoning,+ "confidence": inst.confidence,+ }+ for inst in cr.instructions+ ],+ "rationale": cr.rationale,+ }+ for cr in self.compose_results+ ],+ "tx_results": [tx.to_dict() for tx in self.tx_results],+ "portfolio_snapshots": {+ model: snapshot.to_dict()+ for model, snapshot in self.portfolio_snapshots.items()+ },+ "leaderboard": self.leaderboard,+ }diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/kraken_api.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/kraken_api.pynew file mode 100644index 000000000..75adb3e63--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/kraken_api.py@@ -0,0 +1,154 @@+"""+Kraken REST API Integration+Fetches market data from Kraken exchange (NO WebSocket - REST only)+"""++import requests+from typing import Dict, Any, List, Optional+from datetime import datetime+import time+++class KrakenAPI:+ """Kraken REST API client for market data"""++ BASE_URL = "https://api.kraken.com/0/public"++ def __init__(self):+ self.session = requests.Session()+ self.session.headers.update({+ 'User-Agent': 'Fincept-Terminal/1.0'+ })+ self.last_request_time = 0+ self.min_request_interval = 1.0 # 1 second between requests++ def _rate_limit(self):+ """Ensure we don't exceed rate limits"""+ elapsed = time.time() - self.last_request_time+ if elapsed < self.min_request_interval:+ time.sleep(self.min_request_interval - elapsed)+ self.last_request_time = time.time()++ def get_ticker(self, pair: str = "XBTUSD") -> Dict[str, Any]:+ """+ Get current ticker data++ Args:+ pair: Trading pair (e.g., XBTUSD for BTC/USD)++ Returns:+ Dict with current price, bid, ask, volume, etc.+ """+ self._rate_limit()++ try:+ response = self.session.get(+ f"{self.BASE_URL}/Ticker",+ params={"pair": pair},+ timeout=10+ )+ response.raise_for_status()+ data = response.json()++ if data.get('error') and len(data['error']) > 0:+ return {"error": f"Kraken API error: {data['error']}"}++ result = data.get('result', {})+ if not result or pair not in result:+ # Try alternate pair name+ alt_pair = list(result.keys())[0] if result else None+ if alt_pair:+ ticker = result[alt_pair]+ else:+ return {"error": "No ticker data returned"}+ else:+ ticker = result[pair]++ # Parse Kraken ticker format+ # [ask, bid, last_price, volume, vwap, trades, low, high, open]+ return {+ "symbol": pair,+ "price": float(ticker['c'][0]), # Last trade price+ "bid": float(ticker['b'][0]), # Best bid+ "ask": float(ticker['a'][0]), # Best ask+ "high_24h": float(ticker['h'][1]), # 24h high+ "low_24h": float(ticker['l'][1]), # 24h low+ "volume_24h": float(ticker['v'][1]), # 24h volume+ "vwap_24h": float(ticker['p'][1]), # 24h VWAP+ "open": float(ticker['o']), # Open price+ "timestamp": datetime.now().isoformat(),+ "source": "kraken_rest"+ }++ except Exception as e:+ return {"error": f"Failed to fetch ticker: {str(e)}"}++ def get_ohlc(self, pair: str = "XBTUSD", interval: int = 60) -> Dict[str, Any]:+ """+ Get OHLC (candlestick) data++ Args:+ pair: Trading pair+ interval: Time interval in minutes (1, 5, 15, 30, 60, 240, 1440)++ Returns:+ Dict with OHLC data+ """+ self._rate_limit()++ try:+ response = self.session.get(+ f"{self.BASE_URL}/OHLC",+ params={"pair": pair, "interval": interval},+ timeout=10+ )+ response.raise_for_status()+ data = response.json()++ if data.get('error') and len(data['error']) > 0:+ return {"error": f"Kraken API error: {data['error']}"}++ result = data.get('result', {})+ pair_data = None+ for key in result:+ if key != 'last':+ pair_data = result[key]+ break++ if not pair_data:+ return {"error": "No OHLC data returned"}++ # Get last 50 candles+ candles = []+ for candle in pair_data[-50:]:+ candles.append({+ "time": int(candle[0]),+ "open": float(candle[1]),+ "high": float(candle[2]),+ "low": float(candle[3]),+ "close": float(candle[4]),+ "volume": float(candle[6])+ })++ return {+ "symbol": pair,+ "interval": interval,+ "candles": candles,+ "count": len(candles),+ "timestamp": datetime.now().isoformat(),+ "source": "kraken_rest"+ }++ except Exception as e:+ return {"error": f"Failed to fetch OHLC: {str(e)}"}+++# Singleton instance+_kraken_api = None++def get_kraken_api() -> KrakenAPI:+ """Get singleton Kraken API instance"""+ global _kraken_api+ if _kraken_api is None:+ _kraken_api = KrakenAPI()+ return _kraken_apidiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/order_execution.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/order_execution.pydeleted file mode 100644index 0dd03b074..000000000--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/order_execution.py+++ /dev/null@@ -1,111 +0,0 @@-"""-Order Execution Tools--Provides tools for executing trades. Currently supports paper trading mode.-"""--from typing import List, Dict, Any, Optional-from datetime import datetime-import uuid---class PaperTradingEngine:- """Simple paper trading engine for testing"""-- def __init__(self, initial_capital: float = 10000.0):- self.initial_capital = initial_capital- self.cash = initial_capital- self.positions: Dict[str, Dict[str, Any]] = {}- self.orders: List[Dict[str, Any]] = []- self.trades: List[Dict[str, Any]] = []-- def get_portfolio_value(self, current_prices: Dict[str, float]) -> float:- """Calculate total portfolio value"""- portfolio_value = self.cash-- for symbol, position in self.positions.items():- if symbol in current_prices:- portfolio_value += position['quantity'] * current_prices[symbol]-- return portfolio_value---def place_order(- symbol: str,- side: str,- order_type: str,- quantity: float,- price: Optional[float] = None,- mode: str = "paper"-) -> Dict[str, Any]:- """- Place a trading order-- Args:- symbol: Trading symbol- side: 'buy' or 'sell'- order_type: 'market' or 'limit'- quantity: Order quantity- price: Limit price (for limit orders)- mode: 'paper' or 'live' (currently only paper supported)-- Returns:- Order confirmation- """- if mode != "paper":- return {"error": "Only paper trading mode is currently supported"}-- order_id = str(uuid.uuid4())-- order = {- "order_id": order_id,- "symbol": symbol,- "side": side.lower(),- "type": order_type.lower(),- "quantity": quantity,- "price": price,- "status": "submitted",- "timestamp": datetime.now().isoformat(),- "mode": mode- }-- return {- "success": True,- "order": order,- "message": f"Paper trading order placed: {side.upper()} {quantity} {symbol}"- }---def cancel_order(order_id: str, mode: str = "paper") -> Dict[str, Any]:- """Cancel an order"""- return {- "success": True,- "order_id": order_id,- "status": "cancelled",- "message": "Order cancelled (paper trading)"- }---def get_order_status(order_id: str, mode: str = "paper") -> Dict[str, Any]:- """Get order status"""- return {- "order_id": order_id,- "status": "filled",- "message": "Order status retrieved (paper trading)"- }---def get_order_execution_tools() -> List[Any]:- """Get order execution tools"""- return [- place_order,- cancel_order,- get_order_status,- ]---TOOL_DESCRIPTIONS = {- "place_order": "Place a buy or sell order for a symbol. Supports market and limit orders in paper trading mode.",- "cancel_order": "Cancel a pending order by order ID.",- "get_order_status": "Check the status of an order (pending, filled, cancelled).",-}diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading_service.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading_service.pyindex 08e7ec8bd..ce150acf8 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading_service.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading_service.py@@ -1,33 +1,28 @@#!/usr/bin/env python"""-Agno Trading Service - Main Entry Point-========================================+Alpha Arena Trading Service - New Framework+===========================================-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", ...])+Streamlined service using the modular trading framework.+Clean separation of concerns, extensible architecture.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+ - create_competition: Create a new multi-LLM competition+ - run_cycle: Execute a single trading cycle+ - start_competition: Start continuous trading+ - stop_competition: Stop the competition+ - get_leaderboard_alpha: Get current rankings+ - get_model_decisions_alpha: Get recent decisions"""import sysimport jsonimport os-import logging-from typing import Dict, Any, Optional, List+import asyncio+from typing import Dict, Any, Optional-# Configure logging to output to stderr only (stdout is reserved for JSON responses)+# Configure logging - stderr only+import logginglogging.basicConfig(level=logging.ERROR,format='%(levelname)s: %(message)s',@@ -35,730 +30,516 @@ logging.basicConfig(force=True)-# Suppress Agno library logs that go to stdout-# Agno uses loguru which outputs to stdout - we need to disable it+# Redirect stdout to stderr (preserve stdout for JSON)+class StdoutToStderr:+ def write(self, text):+ sys.stderr.write(text)+ def flush(self):+ sys.stderr.flush()++_original_stdout = sys.stdout++def _suppress_stdout():+ sys.stdout = StdoutToStderr()++def _restore_stdout():+ sys.stdout = _original_stdout++_suppress_stdout()++# Disable loguruos.environ['LOGURU_LEVEL'] = 'CRITICAL'os.environ['LOGURU_AUTOINIT'] = 'False'-# Add agno_trading to path+# Add to pathsys.path.insert(0, os.path.join(os.path.dirname(__file__), 'agno_trading'))-# Disable loguru after importtry:from loguru import logger- logger.remove() # Remove all default handlers- logger.add(sys.stderr, level="CRITICAL") # Only critical errors to stderr+ logger.remove()+ logger.add(sys.stderr, level="CRITICAL")except ImportError:pass-# Import after path is set-from config.settings import AgnoConfig, LLMConfig, LLMProvider, TradingConfig, TradingMode-from config.models import list_available_models, get_best_model_for_task, validate_model_config-from core.agent_manager import get_agent_manager, AgentConfig as CoreAgentConfig-from agents.market_analyst import MarketAnalystAgent-from agents.trading_strategy import TradingStrategyAgent-from agents.risk_manager import RiskManagerAgent-from agents.portfolio_manager import PortfolioManagerAgent---def create_response(success: bool, data: Any = None, error: str = None) -> str:- """Create standardized JSON response"""- return json.dumps({- "success": success,- "data": data,- "error": error- }, indent=2)---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))+# Import framework+from framework import CompetitionRuntime, ModelConfig+from db.database_manager import DatabaseManager+# Global competition instance+_active_competition: Optional[CompetitionRuntime] = None+_db_manager: Optional[DatabaseManager] = None-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 get_db_manager() -> DatabaseManager:+ """Get or create database manager."""+ global _db_manager+ if _db_manager is None:+ _db_manager = DatabaseManager()+ return _db_manager-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)- )+def create_competition_command(args: list) -> Dict[str, Any]:+ """+ Create a new Alpha Arena competition.- # 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}"+ Args:+ args[0]: JSON string with competition config+ {+ "competition_id": "comp_123",+ "competition_name": "My Competition",+ "models": [+ {+ "name": "GPT-4",+ "provider": "openai",+ "model_id": "gpt-4",+ "api_key": "sk-..."+ },+ ...+ ],+ "symbols": ["BTC/USD"],+ "initial_capital": 10000.0,+ "exchange_id": "kraken",+ "custom_prompt": "Optional strategy instructions"}- })- 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))-+ """+ global _active_competition-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]+ config = json.loads(args[0])++ competition_id = config["competition_id"]+ competition_name = config.get("competition_name", "Untitled")+ symbols = config.get("symbols", ["BTC/USD"])+ initial_capital = float(config.get("initial_capital", 10000.0))+ exchange_id = config.get("exchange_id", "kraken")+ custom_prompt = config.get("custom_prompt")++ # Parse model configs+ models = []+ for model_data in config["models"]:+ models.append(ModelConfig(+ name=model_data["name"],+ provider=model_data["provider"],+ model_id=model_data["model_id"],+ api_key=model_data["api_key"],+ temperature=float(model_data.get("temperature", 0.7)),+ max_tokens=int(model_data.get("max_tokens", 1000)),+ timeout_seconds=int(model_data.get("timeout_seconds", 30))+ ))++ # Create competition runtime+ _active_competition = CompetitionRuntime(+ competition_id=competition_id,+ models=models,+ symbols=symbols,+ initial_capital=initial_capital,+ exchange_id=exchange_id,+ custom_prompt=custom_prompt)- # 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]+ # Save to database+ db = get_db_manager()+ models_json = json.dumps([{+ "name": m.name,+ "provider": m.provider,+ "model_id": m.model_id+ } for m in models])++ db.save_competition_config(+ competition_id=competition_id,+ name=competition_name,+ models_json=models_json,+ symbol=symbols[0], # Primary symbol+ mode="baseline", # Default mode+ api_keys_json=json.dumps({m.name: m.api_key for m in models}))- # 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 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."+ # Save model states+ for model in models:+ db.save_model_state(+ competition_id=competition_id,+ model_name=model.name,+ capital=initial_capital,+ positions_json="{}",+ trades_count=0,+ total_pnl=0.0,+ portfolio_value=initial_capital)- # 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 {+ "success": True,+ "competition_id": competition_id,+ "models": [m.name for m in models],+ "symbols": symbols+ }- return create_response(True, result)except Exception as e:- return create_response(False, error=str(e))+ print(f"[ERROR] create_competition failed: {e}", file=sys.stderr)+ import traceback+ traceback.print_exc(file=sys.stderr)+ return {"success": 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))---def create_competition_command(- name: str,- models_json: str,- task_type: str = "trading",- api_keys_json: str = "{}"-) -> str:- """- Create multi-model competition-- Args:- name: Competition name- models_json: JSON array of models ["openai:gpt-4", "anthropic:claude-sonnet-4"]- task_type: Type of task- api_keys_json: JSON object of API keys (optional)- """+def load_competition_from_db(competition_id: str) -> Optional[CompetitionRuntime]:+ """Load competition from database."""try:- import json- from agno_trading.core.team_orchestrator import TeamOrchestrator- from agno_trading.core.agent_manager import AgentManager-- models = json.loads(models_json)- api_keys = json.loads(api_keys_json)-- # Set API keys in environment if provided- if api_keys:- import os- for key, value in api_keys.items():- os.environ[key] = value-- manager = AgentManager()- orchestrator = TeamOrchestrator()-- # Create agents for each model- from agno_trading.core.base_agent import AgentConfig-- agents = []- for model_str in models:- # Create proper AgentConfig object (not dict)- agent_config = AgentConfig(- name=f"Agent-{model_str.replace(':', '-')}",- role="Market Analyst",- agent_model=model_str,- instructions=["Analyze market data and provide trading insights."]- )- agent_id = manager.create_agent(agent_config)- agent = manager.get_agent(agent_id)-- agents.append({- "model": model_str,- "agent": agent- })-- team_id = orchestrator.create_competition(name, agents, task_type)-- return create_response(True, {- "team_id": team_id,- "models": models,- "agent_count": len(agents)- })- except Exception as e:- return create_response(False, error=str(e))+ db = get_db_manager()+ # Get competition config+ conn = db.get_connection()+ cursor = conn.cursor()+ cursor.execute("""+ SELECT name, models_json, symbol, api_keys_json+ FROM competition_configs+ WHERE competition_id = ?+ """, (competition_id,))++ row = cursor.fetchone()+ if not row:+ conn.close()+ print(f"[ERROR] Competition {competition_id} not found in database", file=sys.stderr)+ return None++ name, models_json, symbol, api_keys_json = row++ # Parse models+ models_data = json.loads(models_json)+ api_keys = json.loads(api_keys_json) if api_keys_json else {}++ models = []+ for model_data in models_data:+ model_name = model_data["name"]+ api_key = api_keys.get(model_name, "")++ models.append(ModelConfig(+ name=model_name,+ provider=model_data["provider"],+ model_id=model_data["model_id"],+ api_key=api_key,+ temperature=0.7,+ max_tokens=1000,+ timeout_seconds=30+ ))++ # Get model states to restore portfolios+ cursor.execute("""+ SELECT model_name, capital, positions_json, trades_count, total_pnl, portfolio_value+ FROM alpha_model_states+ WHERE competition_id = ?+ """, (competition_id,))++ model_states = {}+ for row in cursor.fetchall():+ model_name, capital, positions_json, trades_count, total_pnl, portfolio_value = row+ model_states[model_name] = {+ "capital": capital,+ "positions": json.loads(positions_json) if positions_json else {},+ "trades_count": trades_count,+ "total_pnl": total_pnl,+ "portfolio_value": portfolio_value+ }-def run_competition_command(- team_id: str,- symbol: str,- task: str = "analyze",- api_keys_json: str = "{}"-) -> str:- """- Run multi-model competition+ conn.close()- Args:- team_id: Competition ID- symbol: Trading symbol- task: Task type (analyze, signal)- api_keys_json: JSON object of API keys (optional)- """- try:- import asyncio- import json- from agno_trading.core.team_orchestrator import TeamOrchestrator-- # Set API keys in environment if provided- api_keys = json.loads(api_keys_json)- if api_keys:- import os- for key, value in api_keys.items():- os.environ[key] = value-- orchestrator = TeamOrchestrator()-- # Build prompt based on task- if task == "analyze":- prompt = f"Analyze {symbol} market conditions and provide trading insights."- elif task == "signal":- prompt = f"Generate a trade signal for {symbol} with entry/exit points."- else:- prompt = f"Evaluate {symbol} for trading opportunities."-- # Run parallel execution- loop = asyncio.get_event_loop()- result = loop.run_until_complete(- orchestrator.run_parallel(team_id, prompt, streaming=True)+ # Create competition+ competition = CompetitionRuntime(+ competition_id=competition_id,+ models=models,+ symbols=[symbol],+ initial_capital=10000.0, # Will restore from states+ exchange_id="kraken",+ custom_prompt=None)- return create_response(True, result)- except Exception as e:- return create_response(False, error=str(e))---def get_leaderboard_command() -> str:- """Get model performance leaderboard"""- try:- from agno_trading.core.team_orchestrator import TeamOrchestrator-- orchestrator = TeamOrchestrator()- leaderboard = orchestrator.get_leaderboard()-- return create_response(True, {"leaderboard": leaderboard})- except Exception as e:- return create_response(False, error=str(e))+ # Restore portfolio states+ for model_name, state in model_states.items():+ if model_name in competition.portfolios:+ portfolio = competition.portfolios[model_name]+ portfolio.cash = state["capital"]+ portfolio.trades_count = state["trades_count"]+ portfolio.total_realized_pnl = state["total_pnl"]+ # TODO: Restore positions from state["positions"]+ print(f"[INFO] Loaded competition {competition_id} from database", file=sys.stderr)+ return competition-def get_recent_decisions_command(limit: int = 50) -> str:- """Get recent model decisions"""- try:- from agno_trading.core.team_orchestrator import TeamOrchestrator-- orchestrator = TeamOrchestrator()- decisions = orchestrator.get_recent_decisions(int(limit))-- return create_response(True, {"decisions": decisions})except Exception as e:- return create_response(False, error=str(e))+ print(f"[ERROR] Failed to load competition: {e}", file=sys.stderr)+ import traceback+ traceback.print_exc(file=sys.stderr)+ return None-# ============================================================================-# NEW COMMANDS: Auto-Trading, Debate, Evolution-# ============================================================================+async def run_cycle_async(args: list) -> Dict[str, Any]:+ """Run a single trading cycle (async)."""+ global _active_competition-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)+ # Get competition ID from args+ competition_id = args[0] if args else None- # Set API keys- for key, value in api_keys.items():- os.environ[key] = value+ # If no active competition, try to load from database+ if _active_competition is None:+ if not competition_id:+ return {"success": False, "error": "No competition ID provided"}- executor = get_trade_executor()- result = executor.execute_trade(signal, portfolio, agent_id, model, paper_trading=True)+ print(f"[INFO] Loading competition {competition_id} from database", file=sys.stderr)+ _active_competition = load_competition_from_db(competition_id)- 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+ if _active_competition is None:+ return {"success": False, "error": "Failed to load competition from database"}- 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))+ # Verify competition ID matches if provided+ if competition_id and _active_competition.competition_id != competition_id:+ print(f"[INFO] Switching to competition {competition_id}", file=sys.stderr)+ _active_competition = load_competition_from_db(competition_id)+ if _active_competition is None:+ return {"success": False, "error": "Failed to load competition from database"}-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+ # Run cycle+ result = await _active_competition.run_cycle()+ # Save to databasedb = 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))+ competition_id = _active_competition.competition_id++ # Save ALL decisions (including HOLD/WAIT)+ for compose_result in result.compose_results:+ # Get portfolio value before+ portfolio_before = result.portfolio_snapshots.get(compose_result.model_name)+ portfolio_value_before = portfolio_before.total_value if portfolio_before else 0.0++ # Get the decision type (BUY/SELL/HOLD/WAIT)+ decision_type = compose_result.decision_type or 'WAIT'++ if compose_result.instructions:+ # BUY or SELL decision with trade execution+ for instruction in compose_result.instructions:+ db.save_decision_log(+ competition_id=competition_id,+ model_name=instruction.model_name or compose_result.model_name,+ cycle_number=result.cycle_number,+ action=instruction.side.value,+ symbol=instruction.symbol,+ quantity=instruction.quantity,+ confidence=instruction.confidence or 0.5,+ reasoning=instruction.reasoning or "",+ trade_executed=True,+ price_at_decision=0.0, # Will be updated with tx result+ portfolio_value_before=portfolio_value_before,+ portfolio_value_after=0.0 # Will be updated below+ )+ else:+ # HOLD or WAIT decision (no trade execution)+ # Get symbol from features or use competition default+ symbol = _active_competition.symbols[0] if _active_competition.symbols else 'BTC/USD'++ db.save_decision_log(+ competition_id=competition_id,+ model_name=compose_result.model_name,+ cycle_number=result.cycle_number,+ action=decision_type, # HOLD or WAIT+ symbol=symbol,+ quantity=0.0,+ confidence=0.5,+ reasoning=compose_result.rationale or "",+ trade_executed=False,+ price_at_decision=0.0,+ portfolio_value_before=portfolio_value_before,+ portfolio_value_after=portfolio_value_before # No change+ )+ # Save portfolio snapshots+ for model_name, portfolio_view in result.portfolio_snapshots.items():+ db.save_performance_snapshot(+ competition_id=competition_id,+ cycle_number=result.cycle_number,+ model_name=model_name,+ portfolio_value=portfolio_view.total_value,+ cash=portfolio_view.cash,+ pnl=portfolio_view.total_realized_pnl + portfolio_view.total_unrealized_pnl,+ return_pct=((portfolio_view.total_value - _active_competition.initial_capital) / _active_competition.initial_capital) * 100.0,+ positions_count=len(portfolio_view.positions),+ trades_count=portfolio_view.trades_count+ )-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+ # Update model state+ db.save_model_state(+ competition_id=competition_id,+ model_name=model_name,+ capital=portfolio_view.cash,+ positions_json=json.dumps(portfolio_view.to_dict()["positions"]),+ trades_count=portfolio_view.trades_count,+ total_pnl=portfolio_view.total_realized_pnl + portfolio_view.total_unrealized_pnl,+ portfolio_value=portfolio_view.total_value+ )- db = get_db_manager()- performance = db.get_agent_performance(agent_id)+ return {+ "success": True,+ "cycle_number": result.cycle_number,+ "leaderboard": result.leaderboard,+ "decisions_count": len(result.tx_results)+ }- 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))+ print(f"[ERROR] run_cycle failed: {e}", file=sys.stderr)+ import traceback+ traceback.print_exc(file=sys.stderr)+ return {"success": 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+def run_cycle_command(args: list) -> Dict[str, Any]:+ """Run a single trading cycle (sync wrapper)."""+ return asyncio.run(run_cycle_async(args))- 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 start_competition_command(args: list) -> Dict[str, Any]:+ """Start continuous trading (runs one cycle then returns)."""+ return run_cycle_command(args)++def stop_competition_command(args: list) -> Dict[str, Any]:+ """Stop the competition."""+ global _active_competition-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+ if _active_competition:+ _active_competition.stop()+ asyncio.run(_active_competition.close())+ _active_competition = None- db = get_db_manager()- decisions = db.get_recent_decisions(int(limit), agent_id)+ return {"success": True}- 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- )+ print(f"[ERROR] stop_competition failed: {e}", file=sys.stderr)+ return {"success": False, "error": str(e)}- return create_response(True, result)- except Exception as e:- return create_response(False, error=str(e))+async def get_leaderboard_async(args: list) -> Dict[str, Any]:+ """Get current leaderboard (async)."""+ global _active_competition-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))+ # Get competition ID from args+ competition_id = args[0] if args else None++ # If no active competition, try to load from database+ if _active_competition is None:+ if not competition_id:+ return {"success": False, "error": "No competition ID provided"}++ print(f"[INFO] Loading competition {competition_id} for leaderboard", file=sys.stderr)+ _active_competition = load_competition_from_db(competition_id)++ if _active_competition is None:+ return {"success": False, "error": "Failed to load competition from database"}++ # Verify competition ID matches if provided - but DON'T reload if match+ if competition_id and _active_competition.competition_id != competition_id:+ print(f"[INFO] Switching to competition {competition_id}", file=sys.stderr)+ _active_competition = load_competition_from_db(competition_id)++ if _active_competition is None:+ return {"success": False, "error": "Failed to load competition from database"}+ elif competition_id and _active_competition.competition_id == competition_id:+ # Competition matches - sync portfolio states from DB to ensure consistency+ db = get_db_manager()+ conn = db.get_connection()+ cursor = conn.cursor()+ cursor.execute("""+ SELECT model_name, capital, positions_json, trades_count, total_pnl, portfolio_value+ FROM alpha_model_states+ WHERE competition_id = ?+ """, (competition_id,))++ for row in cursor.fetchall():+ model_name, capital, positions_json, trades_count, total_pnl, portfolio_value = row+ if model_name in _active_competition.portfolios:+ portfolio = _active_competition.portfolios[model_name]+ portfolio.cash = capital+ portfolio.trades_count = trades_count+ portfolio.total_realized_pnl = total_pnl++ conn.close()++ leaderboard = await _active_competition.get_leaderboard()++ return {+ "success": True,+ "leaderboard": leaderboard+ }- return create_response(True, {"debates": debates})except Exception as e:- return create_response(False, error=str(e))+ print(f"[ERROR] get_leaderboard failed: {e}", file=sys.stderr)+ import traceback+ traceback.print_exc(file=sys.stderr)+ return {"success": 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 get_leaderboard_command(args: list) -> Dict[str, Any]:+ """Get current leaderboard (sync wrapper)."""+ return asyncio.run(get_leaderboard_async(args))-def check_evolution_command(agent_id: str) -> str:- """Check if agent should evolve"""+def get_model_decisions_command(args: list) -> Dict[str, Any]:+ """Get recent model decisions from database."""try:- from agno_trading.core.agent_evolution import get_agent_evolution- from agno_trading.db.database_manager import get_db_manager+ competition_id = args[0] if args else None+ if not competition_id:+ return {"success": False, "error": "competition_id required"}db = get_db_manager()- performance = db.get_agent_performance(agent_id)-- if not performance:- return create_response(False, error="Agent performance not found")+ decisions = db.get_decision_logs(competition_id, limit=50)- evolution = get_agent_evolution()- should_evolve, trigger = evolution.should_evolve(agent_id, performance)+ return {+ "success": True,+ "decisions": decisions+ }- return create_response(True, {- "should_evolve": should_evolve,- "trigger": trigger,- "performance": performance- })except Exception as e:- return create_response(False, error=str(e))+ print(f"[ERROR] get_model_decisions failed: {e}", file=sys.stderr)+ return {"success": 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))---# Command dispatcher+# Command registryCOMMANDS = {- "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,"create_competition": create_competition_command,- "run_competition": run_competition_command,- "get_leaderboard": get_leaderboard_command,- "get_recent_decisions": get_recent_decisions_command,- # New commands- "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,- "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,+ "run_cycle": run_cycle_command,+ "start_competition": start_competition_command,+ "stop_competition": stop_competition_command,+ "get_leaderboard_alpha": get_leaderboard_command,+ "get_model_decisions_alpha": get_model_decisions_command,}def main():- """Main entry point for CLI usage"""+ """Main entry point."""if len(sys.argv) < 2:- print(create_response(False, error="No command specified"))- sys.exit(1)+ _restore_stdout()+ print(json.dumps({+ "success": False,+ "error": "No command specified"+ }))+ returncommand = 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)+ _restore_stdout()+ print(json.dumps({+ "success": False,+ "error": f"Unknown command: {command}"+ }))+ return++ # Execute command+ result = COMMANDS[command](args)++ # Output JSON result+ _restore_stdout()+ print(json.dumps(result))if __name__ == "__main__":diff --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.backupnew file mode 100644index 000000000..88f0f6d65--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading_service_old.py.backup@@ -0,0 +1,1139 @@+#!/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/src/commands/alpha_arena.rs b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rsnew file mode 100644index 000000000..2bb7dbd92--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs@@ -0,0 +1,150 @@+/**+ * Alpha Arena Tauri Commands+ * Rust commands for NOF1-style AI trading competition+ */++use tauri::command;+use serde_json::Value;+use std::process::Command;++/// 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";++ // Try multiple possible paths for the script+ let possible_paths = vec![+ std::env::current_dir()+ .ok()+ .and_then(|d| Some(d.join("src-tauri").join("resources").join("scripts").join(python_script))),+ std::env::current_dir()+ .ok()+ .and_then(|d| Some(d.join("resources").join("scripts").join(python_script))),+ ];++ let script_path = possible_paths+ .into_iter()+ .flatten()+ .find(|p| p.exists())+ .ok_or_else(|| format!("Could not find Python script: {}", python_script))?;++ eprintln!("[Alpha Arena] Executing Python script: {:?}", script_path);+ eprintln!("[Alpha Arena] Args: {:?}", args);++ // Clone args for the blocking task+ let script_path_clone = script_path.clone();+ let args_owned: Vec<String> = args.iter().map(|s| s.to_string()).collect();++ // Execute in a blocking thread to avoid blocking the async runtime+ // This allows the UI to remain responsive during long-running operations+ let result = tokio::task::spawn_blocking(move || {+ Command::new("python")+ .env("PYTHONDONTWRITEBYTECODE", "1") // Prevent .pyc file creation+ .arg(&script_path_clone)+ .args(&args_owned)+ .output()+ })+ .await+ .map_err(|e| format!("Task join error: {}", e))?+ .map_err(|e| format!("Failed to execute Python: {}", e))?;++ // Always log stderr for debugging+ let stderr = String::from_utf8_lossy(&result.stderr);+ if !stderr.is_empty() {+ eprintln!("[Alpha Arena] Python stderr: {}", stderr);+ }++ if !result.status.success() {+ return Err(format!("Python error: {}", stderr));+ }++ let stdout = String::from_utf8_lossy(&result.stdout);+ eprintln!("[Alpha Arena] Python stdout length: {} chars", stdout.len());++ // 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);+ }++ serde_json::from_str(&stdout)+ .map_err(|e| format!("Failed to parse JSON: {}\nOutput: {}", e, stdout))+}++#[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());++ execute_python_alpha_command(&[+ "create_competition",+ &config_json+ ]).await+}++#[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);++ let id = competition_id.as_deref().unwrap_or("");+ execute_python_alpha_command(&[+ "start_competition",+ id+ ]).await+}++#[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);++ execute_python_alpha_command(&[+ "get_leaderboard_alpha",+ &competition_id+ ]).await+}++#[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);++ let model_name_str = model_name.as_deref().unwrap_or("");++ execute_python_alpha_command(&[+ "get_model_decisions_alpha",+ &competition_id,+ model_name_str+ ]).await+}++#[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);++ execute_python_alpha_command(&[+ "stop_competition",+ &competition_id+ ]).await+}++#[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+}diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rsindex 969ea8a1f..c0e754324 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs@@ -87,3 +87,4 @@ pub mod company_news;// Agno Trading Agentspub mod agno_trading;+pub mod alpha_arena;diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rsindex 58047bb7e..9df11a66a 100644--- a/fincept-terminal-desktop/src-tauri/src/lib.rs+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs@@ -1090,7 +1090,14 @@ pub fn run() {commands::agno_trading::agno_get_recent_debates,commands::agno_trading::agno_evolve_agent,commands::agno_trading::agno_check_evolution,- commands::agno_trading::agno_get_evolution_summary+ commands::agno_trading::agno_get_evolution_summary,+ // Alpha Arena Competition+ 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]).run(tauri::generate_context!()).expect("error while running tauri application");diff --git a/fincept-terminal-desktop/src-tauri/src/setup.rs b/fincept-terminal-desktop/src-tauri/src/setup.rsindex f3e09d1f5..4c9a29f20 100644--- a/fincept-terminal-desktop/src-tauri/src/setup.rs+++ b/fincept-terminal-desktop/src-tauri/src/setup.rs@@ -584,34 +584,99 @@ async fn install_python_macos(app: &AppHandle) -> Result<(), String> {emit_progress(app, "python", 50, "Extracting Python...", false);- // Extract tar.gz+ // Extract tar.gz with --strip-components=1 to flatten directory structurelet output = Command::new("tar")- .args(&["-xzf", tar_path.to_str().unwrap(), "-C", python_dir.to_str().unwrap()])+ .args(&[+ "-xzf",+ tar_path.to_str().unwrap(),+ "-C",+ python_dir.to_str().unwrap(),+ "--strip-components=1"+ ]).output()- .map_err(|e| format!("Failed to extract: {}", e))?;+ .map_err(|e| format!("Failed to extract tar.gz: {}", e))?;if !output.status.success() {- return Err("Failed to extract Python".to_string());+ let stderr = String::from_utf8_lossy(&output.stderr);+ let stdout = String::from_utf8_lossy(&output.stdout);+ return Err(format!(+ "Failed to extract Python archive.\n\nStderr: {}\nStdout: {}",+ stderr, stdout+ ));+ }++ emit_progress(app, "python", 60, "Checking extraction...", false);++ // Verify extraction succeeded by checking directory structure+ let python_exe = python_dir.join("bin").join("python3");+ if !python_exe.exists() {+ // List what was actually extracted for debugging+ let mut extracted_files = Vec::new();+ if let Ok(entries) = fs::read_dir(&python_dir) {+ for entry in entries.flatten() {+ extracted_files.push(entry.path().display().to_string());+ }+ }+ return Err(format!(+ "Python extraction failed: python3 not found at expected path.\n\n\+ Expected: {}\n\n\+ Extracted files in {}:\n{}\n\n\+ This may indicate archive structure mismatch.",+ python_exe.display(),+ python_dir.display(),+ extracted_files.join("\n")+ ));+ }++ emit_progress(app, "python", 70, "Making Python executable...", false);++ // Make Python executable (chmod +x)+ let chmod_output = Command::new("chmod")+ .args(&["+x", python_exe.to_str().unwrap()])+ .output()+ .map_err(|e| format!("Failed to chmod python3: {}", e))?;++ if !chmod_output.status.success() {+ eprintln!("[SETUP] Warning: chmod failed, but continuing...");}emit_progress(app, "python", 75, "Verifying Python installation...", false);// Verify Python and pip are working- let python_exe = python_dir.join("bin").join("python3");let test_output = Command::new(&python_exe).arg("--version").output();match test_output {Err(e) => {- return Err(format!("Python installation test failed: {}", e));+ return Err(format!(+ "Python installation test failed: {}\n\n\+ Python path: {}\n\+ Exists: {}\n\+ Executable: {:?}\n\n\+ Possible issues:\n\+ 1. Missing system dependencies\n\+ 2. Permission issues\n\+ 3. Incompatible architecture",+ e,+ python_exe.display(),+ python_exe.exists(),+ fs::metadata(&python_exe).ok()+ ));}Ok(output) if !output.status.success() => {let stderr = String::from_utf8_lossy(&output.stderr);- return Err(format!("Python installation test failed: {}", stderr));+ let stdout = String::from_utf8_lossy(&output.stdout);+ return Err(format!(+ "Python installation test failed.\n\n\+ Stderr: {}\n\+ Stdout: {}",+ stderr, stdout+ ));}- Ok(_) => {- // Python works, continue+ Ok(output) => {+ let version = String::from_utf8_lossy(&output.stdout);+ eprintln!("[SETUP] Python verified: {}", version.trim());}}@@ -653,34 +718,101 @@ async fn install_python_linux(app: &AppHandle) -> Result<(), String> {emit_progress(app, "python", 50, "Extracting Python...", false);- // Extract tar.gz+ // Extract tar.gz with --strip-components=1 to flatten directory structurelet output = Command::new("tar")- .args(&["-xzf", tar_path.to_str().unwrap(), "-C", python_dir.to_str().unwrap()])+ .args(&[+ "-xzf",+ tar_path.to_str().unwrap(),+ "-C",+ python_dir.to_str().unwrap(),+ "--strip-components=1"+ ]).output()- .map_err(|e| format!("Failed to extract: {}", e))?;+ .map_err(|e| format!("Failed to extract tar.gz: {}. Ensure 'tar' is installed.", e))?;if !output.status.success() {- return Err("Failed to extract Python".to_string());+ let stderr = String::from_utf8_lossy(&output.stderr);+ let stdout = String::from_utf8_lossy(&output.stdout);+ return Err(format!(+ "Failed to extract Python archive.\n\nStderr: {}\nStdout: {}\n\nEnsure 'tar' command is available.",+ stderr, stdout+ ));+ }++ emit_progress(app, "python", 60, "Checking extraction...", false);++ // Verify extraction succeeded by checking directory structure+ let python_exe = python_dir.join("bin").join("python3");+ if !python_exe.exists() {+ // List what was actually extracted for debugging+ let mut extracted_files = Vec::new();+ if let Ok(entries) = fs::read_dir(&python_dir) {+ for entry in entries.flatten() {+ extracted_files.push(entry.path().display().to_string());+ }+ }+ return Err(format!(+ "Python extraction failed: python3 not found at expected path.\n\n\+ Expected: {}\n\n\+ Extracted files in {}:\n{}\n\n\+ This may indicate archive structure mismatch.",+ python_exe.display(),+ python_dir.display(),+ extracted_files.join("\n")+ ));+ }++ emit_progress(app, "python", 70, "Making Python executable...", false);++ // Make Python executable (chmod +x)+ let chmod_output = Command::new("chmod")+ .args(&["+x", python_exe.to_str().unwrap()])+ .output()+ .map_err(|e| format!("Failed to chmod python3: {}", e))?;++ if !chmod_output.status.success() {+ eprintln!("[SETUP] Warning: chmod failed, but continuing...");}emit_progress(app, "python", 75, "Verifying Python installation...", false);// Verify Python and pip are working- let python_exe = python_dir.join("bin").join("python3");let test_output = Command::new(&python_exe).arg("--version").output();match test_output {Err(e) => {- return Err(format!("Python installation test failed: {}", e));+ return Err(format!(+ "Python installation test failed: {}\n\n\+ Python path: {}\n\+ Exists: {}\n\+ Executable: {:?}\n\n\+ Possible issues:\n\+ 1. Missing system dependencies (check with: ldd {})\n\+ 2. Permission issues\n\+ 3. Incompatible architecture",+ e,+ python_exe.display(),+ python_exe.exists(),+ fs::metadata(&python_exe).ok(),+ python_exe.display()+ ));}Ok(output) if !output.status.success() => {let stderr = String::from_utf8_lossy(&output.stderr);- return Err(format!("Python installation test failed: {}", stderr));+ let stdout = String::from_utf8_lossy(&output.stdout);+ return Err(format!(+ "Python installation test failed.\n\n\+ Stderr: {}\n\+ Stdout: {}\n\n\+ Run 'ldd {}' to check for missing dependencies.",+ stderr, stdout, python_exe.display()+ ));}- Ok(_) => {- // Python works, continue+ Ok(output) => {+ let version = String::from_utf8_lossy(&output.stdout);+ eprintln!("[SETUP] Python verified: {}", version.trim());}}@@ -842,12 +974,19 @@ async fn install_bun(app: &AppHandle) -> Result<(), String> {let output = Command::new("unzip").args(&["-q", zip_path.to_str().unwrap(), "-d", temp_extract_dir.to_str().unwrap()]).output()- .map_err(|e| format!("Failed to extract Bun: {}", e))?;+ .map_err(|e| format!("Failed to extract Bun: {}. Ensure 'unzip' is installed.", e))?;if !output.status.success() {- return Err("Failed to extract Bun".to_string());+ let stderr = String::from_utf8_lossy(&output.stderr);+ let stdout = String::from_utf8_lossy(&output.stdout);+ return Err(format!(+ "Failed to extract Bun archive.\n\nStderr: {}\nStdout: {}\n\nEnsure 'unzip' is installed.",+ stderr, stdout+ ));}+ emit_progress(app, "bun", 60, "Checking extraction...", false);+// Find the bun executable in extracted folder and move it directly to bun_dir// Bun zips contain a folder like "bun-darwin-aarch64/bun" or "bun-linux-x64/bun"let extracted_entries = fs::read_dir(&temp_extract_dir)@@ -864,11 +1003,17 @@ async fn install_bun(app: &AppHandle) -> Result<(), String> {fs::copy(&bun_exe_path, &target_bun).map_err(|e| format!("Failed to copy bun executable: {}", e))?;+ emit_progress(app, "bun", 70, "Making Bun executable...", false);+// Make executable- Command::new("chmod")+ let chmod_output = Command::new("chmod").args(&["+x", target_bun.to_str().unwrap()]).output()- .ok();+ .map_err(|e| format!("Failed to chmod bun: {}", e))?;++ if !chmod_output.status.success() {+ eprintln!("[SETUP] Warning: chmod failed on bun, but continuing...");+ }eprintln!("[SETUP] Bun copied to: {}", target_bun.display());bun_found = true;@@ -886,12 +1031,72 @@ async fn install_bun(app: &AppHandle) -> Result<(), String> {}}return Err(format!(- "Bun executable not found in extracted archive.\n\- Found:\n{}",+ "Bun executable not found in extracted archive.\n\n\+ Expected structure: bun-{}-{}/bun\n\+ Found in archive:\n{}\n\n\+ This may indicate a corrupted download.",+ if cfg!(target_os = "macos") { "darwin" } else { "linux" },+ if cfg!(target_arch = "aarch64") { "aarch64" } else { "x64" },found_files.join("\n")));}+ emit_progress(app, "bun", 75, "Verifying Bun installation...", false);++ // Verify Bun executable works+ let target_bun = bun_dir.join("bun");+ if !target_bun.exists() {+ return Err("Bun executable not found after copy".to_string());+ }++ // Check file size+ if let Ok(metadata) = fs::metadata(&target_bun) {+ if metadata.len() == 0 {+ return Err("Bun executable is empty (0 bytes). Download may be corrupted.".to_string());+ }+ eprintln!("[SETUP] Bun file size: {} bytes", metadata.len());+ }++ // Test Bun execution+ let test_output = Command::new(&target_bun)+ .arg("--version")+ .output();++ match test_output {+ Err(e) => {+ return Err(format!(+ "Bun installation test failed: {}\n\n\+ Bun path: {}\n\+ Exists: {}\n\+ Executable: {:?}\n\n\+ Possible issues:\n\+ 1. Missing system dependencies (check with: ldd {})\n\+ 2. Permission issues\n\+ 3. Incompatible architecture",+ e,+ target_bun.display(),+ target_bun.exists(),+ fs::metadata(&target_bun).ok(),+ target_bun.display()+ ));+ }+ Ok(output) if !output.status.success() => {+ let stderr = String::from_utf8_lossy(&output.stderr);+ let stdout = String::from_utf8_lossy(&output.stdout);+ return Err(format!(+ "Bun installation test failed.\n\n\+ Stderr: {}\n\+ Stdout: {}\n\n\+ Run 'ldd {}' to check for missing dependencies.",+ stderr, stdout, target_bun.display()+ ));+ }+ Ok(output) => {+ let version = String::from_utf8_lossy(&output.stdout);+ eprintln!("[SETUP] Bun verified: {}", version.trim());+ }+ }+emit_progress(app, "bun", 100, "Bun installed successfully", false);// Cleanupdiff --git a/fincept-terminal-desktop/src-tauri/src/utils/python.rs b/fincept-terminal-desktop/src-tauri/src/utils/python.rsindex 4779b4727..e7348f507 100644--- a/fincept-terminal-desktop/src-tauri/src/utils/python.rs+++ b/fincept-terminal-desktop/src-tauri/src/utils/python.rs@@ -50,7 +50,6 @@ pub fn get_python_path(app: &tauri::AppHandle) -> Result<PathBuf, String> {// Try system Python first in dev modeif let Ok(output) = Command::new(system_python).arg("--version").output() {if output.status.success() {- eprintln!("[DEV MODE] Using system Python");return Ok(PathBuf::from(system_python));}}@@ -114,7 +113,6 @@ pub fn get_bundled_bun_path(app: &tauri::AppHandle) -> Result<PathBuf, String> {// Try system Bun first in dev modeif let Ok(output) = Command::new(system_bun).arg("--version").output() {if output.status.success() {- eprintln!("[DEV MODE] Using system Bun");return Ok(PathBuf::from(system_bun));}}diff --git a/fincept-terminal-desktop/src/App.css b/fincept-terminal-desktop/src/App.cssindex 85feae9ae..30b7122a0 100644--- a/fincept-terminal-desktop/src/App.css+++ b/fincept-terminal-desktop/src/App.css@@ -3,6 +3,16 @@@custom-variant dark (&:is(.dark *));+/* Spinner animation for loading states */+@keyframes spin {+ from {+ transform: rotate(0deg);+ }+ to {+ transform: rotate(360deg);+ }+}+@theme inline {--radius-sm: calc(var(--radius) - 4px);--radius-md: calc(var(--radius) - 2px);diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsxindex b067ea08a..1fbdcf39c 100644--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx@@ -41,6 +41,7 @@ import ReportBuilderTab from '@/components/tabs/ReportBuilderTab';import BacktestingTab from '@/components/tabs/BacktestingTabNew';import RecordedContextsManager from '@/components/common/RecordedContextsManager';import AgentConfigTab from '@/components/tabs/AgentConfigTab';+import AlphaArenaTab from '@/components/tabs/AlphaArenaTab';// Dropdown Menu Componentconst DropdownMenu = ({ label, items, onItemClick }: { label: string; items: any[]; onItemClick: (item: any) => void }) => {@@ -485,6 +486,7 @@ function FinxeptTerminalContent() {const tradingMenuItems = [{ label: 'Trading Desk', shortcut: 'F9', action: () => setActiveTab('trading') },+ { label: 'Alpha Arena', action: () => setActiveTab('alpha-arena') },{ label: 'Fyers Broker', action: () => setActiveTab('fyers') },{ label: 'Portfolio', shortcut: 'F4', action: () => setActiveTab('portfolio') },{ label: 'Backtesting', shortcut: 'F5', action: () => setActiveTab('backtesting') },@@ -986,6 +988,9 @@ function FinxeptTerminalContent() {<TabsContent value="trading" className="h-full m-0 p-0"><TradingTab /></TabsContent>+ <TabsContent value="alpha-arena" className="h-full m-0 p-0">+ <AlphaArenaTab />+ </TabsContent><TabsContent value="settings" className="h-full m-0 p-0"><SettingsTab /></TabsContent>diff --git a/fincept-terminal-desktop/src/components/tabs/AlphaArenaTab.tsx b/fincept-terminal-desktop/src/components/tabs/AlphaArenaTab.tsxnew file mode 100644index 000000000..dabaeebc3--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/AlphaArenaTab.tsx@@ -0,0 +1,800 @@+/**+ * 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';++// Bloomberg 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 [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('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': ''+ });++ // 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 }}>+ ALPHA ARENA+ </div>+ <div style={{ fontSize: '10px', color: COLORS.GRAY }}>+ Live AI Trading 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'+ }}+ >+ NEW COMPETITION+ </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>+ </div>+ );+};++export default AlphaArenaTab;diff --git a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsxindex e489a759c..013e87031 100644--- a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx@@ -1,6 +1,6 @@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 } from 'lucide-react';-import { sqliteService, type LLMConfig, type LLMGlobalSettings, PREDEFINED_API_KEYS, type ApiKeys } from '@/services/sqliteService';+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 } from 'lucide-react';+import { sqliteService, type LLMConfig, type LLMGlobalSettings, type LLMModelConfig, PREDEFINED_API_KEYS, type ApiKeys } from '@/services/sqliteService';import { ollamaService } from '@/services/ollamaService';import { useTerminalTheme } from '@/contexts/ThemeContext';import { terminalThemeService, FONT_FAMILIES, COLOR_THEMES, FontSettings } from '@/services/terminalThemeService';@@ -86,6 +86,24 @@ export default function SettingsTab() {const [useManualEntry, setUseManualEntry] = useState(false);const [showPasswords, setShowPasswords] = useState<Record<number, boolean>>({});+ // 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: ''+ });+ const [showApiKeys, setShowApiKeys] = useState<Record<string, boolean>>({});+useEffect(() => {@@ -364,11 +382,89 @@ export default function SettingsTab() {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 {@@ -1010,6 +1106,290 @@ export default function SettingsTab() {<Save size={16} />{loading ? 'SAVING...' : 'SAVE LLM CONFIGURATION'}</button>++ {/* Multi-Model Configuration for Alpha Arena */}+ <div style={{+ background: colors.panel,+ border: '1px solid #1a1a1a',+ padding: '16px',+ marginTop: '20px',+ borderRadius: '4px'+ }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>+ <h3 style={{ color: colors.text, fontSize: '12px', fontWeight: 'bold' }}>+ Configured Models (Alpha Arena)+ </h3>+ <button+ onClick={() => setShowAddModel(!showAddModel)}+ style={{+ background: showAddModel ? '#3a0a0a' : colors.primary,+ color: colors.text,+ border: 'none',+ padding: '6px 12px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ {showAddModel ? <Trash2 size={12} /> : <Plus size={12} />}+ {showAddModel ? 'CANCEL' : 'ADD MODEL'}+ </button>+ </div>++ <p style={{ color: '#666', fontSize: '9px', marginBottom: '12px' }}>+ Configure multiple models with their own API keys for use in Alpha Arena AI trading competition.+ Each model can have its own API key or share the provider's key from above.+ </p>++ {/* Add Model Form */}+ {showAddModel && (+ <div style={{+ background: colors.background,+ border: '1px solid #2a2a2a',+ padding: '12px',+ marginBottom: '12px',+ borderRadius: '4px'+ }}>+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '12px' }}>+ <div>+ <label style={{ color: colors.text, fontSize: '9px', display: 'block', marginBottom: '4px' }}>+ PROVIDER+ </label>+ <select+ value={newModelConfig.provider}+ onChange={(e) => setNewModelConfig({ ...newModelConfig, provider: e.target.value })}+ style={{+ width: '100%',+ background: colors.background,+ border: '1px solid #2a2a2a',+ color: colors.text,+ padding: '8px',+ fontSize: '10px',+ borderRadius: '3px'+ }}+ >+ <option value="openai">OpenAI</option>+ <option value="google">Google (Gemini)</option>+ <option value="anthropic">Anthropic (Claude)</option>+ <option value="deepseek">DeepSeek</option>+ <option value="ollama">Ollama (Local)</option>+ <option value="openrouter">OpenRouter</option>+ <option value="groq">Groq</option>+ </select>+ </div>+ <div>+ <label style={{ color: colors.text, fontSize: '9px', display: 'block', marginBottom: '4px' }}>+ MODEL ID *+ </label>+ <input+ type="text"+ value={newModelConfig.model_id}+ onChange={(e) => setNewModelConfig({ ...newModelConfig, model_id: e.target.value })}+ placeholder="e.g. gpt-4o-mini, gemini-2.0-flash-exp"+ style={{+ width: '100%',+ background: colors.background,+ border: '1px solid #2a2a2a',+ color: colors.text,+ padding: '8px',+ fontSize: '10px',+ borderRadius: '3px'+ }}+ />+ </div>+ </div>++ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '12px' }}>+ <div>+ <label style={{ color: colors.text, fontSize: '9px', display: 'block', marginBottom: '4px' }}>+ DISPLAY NAME (Optional)+ </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: colors.background,+ border: '1px solid #2a2a2a',+ color: colors.text,+ padding: '8px',+ fontSize: '10px',+ borderRadius: '3px'+ }}+ />+ </div>+ <div>+ <label style={{ color: colors.text, fontSize: '9px', display: 'block', marginBottom: '4px' }}>+ API KEY (Optional - uses provider key if empty)+ </label>+ <input+ type="password"+ value={newModelConfig.api_key}+ onChange={(e) => setNewModelConfig({ ...newModelConfig, api_key: e.target.value })}+ placeholder="Leave empty to use provider API key"+ style={{+ width: '100%',+ background: colors.background,+ border: '1px solid #2a2a2a',+ color: colors.text,+ padding: '8px',+ fontSize: '10px',+ borderRadius: '3px'+ }}+ />+ </div>+ </div>++ <button+ onClick={handleAddModelConfig}+ disabled={loading || !newModelConfig.model_id}+ style={{+ background: colors.primary,+ color: colors.text,+ border: 'none',+ padding: '8px 16px',+ fontSize: '10px',+ fontWeight: 'bold',+ cursor: loading || !newModelConfig.model_id ? 'not-allowed' : 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ opacity: loading || !newModelConfig.model_id ? 0.5 : 1+ }}+ >+ <Plus size={12} />+ ADD MODEL+ </button>+ </div>+ )}++ {/* Configured Models List */}+ {modelConfigs.length === 0 ? (+ <div style={{+ padding: '20px',+ textAlign: 'center',+ color: '#666',+ fontSize: '10px',+ border: '1px dashed #2a2a2a',+ borderRadius: '4px'+ }}>+ No models configured yet. Click "ADD MODEL" to add models for Alpha Arena.+ <br />+ <span style={{ color: '#888', fontSize: '9px' }}>+ Note: Models from the legacy config above will also be available.+ </span>+ </div>+ ) : (+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>+ {modelConfigs.map((model) => (+ <div+ key={model.id}+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ padding: '10px 12px',+ background: model.is_enabled ? colors.background : '#1a1a1a',+ border: `1px solid ${model.is_enabled ? '#2a2a2a' : '#1a1a1a'}`,+ borderRadius: '4px',+ opacity: model.is_enabled ? 1 : 0.6+ }}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>+ <button+ onClick={() => handleToggleModelEnabled(model.id)}+ style={{+ background: 'transparent',+ border: 'none',+ cursor: 'pointer',+ padding: '2px'+ }}+ >+ {model.is_enabled ? (+ <ToggleRight size={20} color="#00ff00" />+ ) : (+ <ToggleLeft size={20} color="#666" />+ )}+ </button>+ <div>+ <div style={{+ fontSize: '11px',+ fontWeight: 600,+ color: model.is_enabled ? colors.text : '#666'+ }}>+ {model.display_name || model.model_id}+ </div>+ <div style={{ fontSize: '9px', color: '#666' }}>+ {model.provider.toUpperCase()} · {model.model_id}+ {model.api_key && ' · Has API Key'}+ </div>+ </div>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ {model.api_key && (+ <button+ onClick={() => setShowApiKeys(prev => ({ ...prev, [model.id]: !prev[model.id] }))}+ style={{+ background: 'transparent',+ border: '1px solid #2a2a2a',+ color: '#666',+ padding: '4px 8px',+ fontSize: '9px',+ cursor: 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ {showApiKeys[model.id] ? <EyeOff size={10} /> : <Eye size={10} />}+ </button>+ )}+ <button+ onClick={() => handleDeleteModelConfig(model.id)}+ style={{+ background: '#3a0a0a',+ border: 'none',+ color: '#ff4444',+ padding: '4px 8px',+ fontSize: '9px',+ cursor: 'pointer',+ borderRadius: '3px',+ display: 'flex',+ alignItems: 'center',+ gap: '4px'+ }}+ >+ <Trash2 size={10} />+ DELETE+ </button>+ </div>+ </div>+ ))}+ </div>+ )}++ {/* Summary of all available LLMs */}+ <div style={{+ marginTop: '12px',+ padding: '10px',+ background: '#0a1a0a',+ border: '1px solid #00ff00',+ borderRadius: '4px',+ fontSize: '9px',+ color: '#00ff00'+ }}>+ <strong>Available for Alpha Arena:</strong> {modelConfigs.filter(m => m.is_enabled).length} custom models+ + {llmConfigs.filter(c => c.api_key).length} provider defaults+ </div>+ </div></div>)}diff --git a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsxindex c43302db2..c71a027e3 100644--- a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx@@ -19,9 +19,6 @@ import { OrdersTable, ClosedOrders } from './trading/core/OrderManager';import { TradingChart, DepthChart, VolumeProfile } from './trading/charts';import { AccountStats, FeesDisplay, MarginPanel } from './trading/core/AccountInfo';import { PortfolioAggregator, ArbitrageDetector } from './trading/cross-exchange';-import { AIAgentsPanel } from './trading/ai-agents/AIAgentsPanel';-import { ModelChatPanel } from './trading/ai-agents/ModelChatPanel';-import { LeaderboardPanel } from './trading/ai-agents/LeaderboardPanel';import type { OrderRequest } from '../../types/trading';interface OrderBookLevel {@@ -107,8 +104,8 @@ export function TradingTab() {const [showSymbolDropdown, setShowSymbolDropdown] = useState(false);const [showBrokerDropdown, setShowBrokerDropdown] = useState(false);const [selectedView, setSelectedView] = useState<'chart' | 'depth' | 'trades'>('chart');- const [rightPanelView, setRightPanelView] = useState<'orderbook' | 'volume' | 'modelchat'>('orderbook');- const [leftSidebarView, setLeftSidebarView] = useState<'watchlist' | 'ai-agents' | 'leaderboard'>('watchlist');+ const [rightPanelView, setRightPanelView] = useState<'orderbook' | 'volume'>('orderbook');+ const [leftSidebarView, setLeftSidebarView] = useState<'watchlist'>('watchlist');// Paper trading stateconst [positions, setPositions] = useState<Position[]>([]);@@ -256,7 +253,7 @@ export function TradingTab() {activeBroker ? `${activeBroker}.trade.${selectedSymbol}` : null);- // Update ticker data+ // Update ticker data and position pricesuseEffect(() => {if (tickerMessage && tickerMessage.data) {const data = tickerMessage.data;@@ -271,6 +268,42 @@ export function TradingTab() {last: data.last,});}++ // Update position prices in real-time AND in database+ setPositions(prev => prev.map(p => {+ if (p.symbol === selectedSymbol && data.last) {+ const currentPrice = data.last;+ const unrealizedPnl = p.side === 'long'+ ? (currentPrice - p.entryPrice) * p.quantity+ : (p.entryPrice - currentPrice) * p.quantity;+ const pnlPercent = ((unrealizedPnl / (p.entryPrice * p.quantity)) * 100);++ // Update DB asynchronously+ (async () => {+ try {+ const db = (await import('../../paper-trading/PaperTradingDatabase')).paperTradingDatabase;+ const dbPositions = await db.getPortfolioPositions(+ (paperAdapter as any).paperConfig.portfolioId,+ 'open'+ );+ const dbPos = dbPositions.find(pos => pos.symbol === selectedSymbol);+ if (dbPos) {+ await db.updatePosition(dbPos.id, { currentPrice, unrealizedPnl });+ }+ } catch (err) {+ console.error('Failed to update position price in DB:', err);+ }+ })();++ return {+ ...p,+ currentPrice,+ unrealizedPnl,+ pnlPercent+ };+ }+ return p;+ }));}}}@@ -342,13 +375,18 @@ export function TradingTab() {if (tradingMode !== 'paper' || !paperAdapter) return;try {- const balanceData = await paperAdapter.fetchBalance();+ const [balanceData, positionsData, ordersData, tradesData] = await Promise.all([+ paperAdapter.fetchBalance(),+ paperAdapter.fetchPositions(),+ paperAdapter.fetchOpenOrders(),+ paperAdapter.fetchMyTrades(undefined, undefined, 50)+ ]);+const usdBalance = (balanceData.free as any)?.USD || 0;const totalEquity = (balanceData.total as any)?.USD || 0;setBalance(usdBalance);setEquity(totalEquity);- const positionsData = await paperAdapter.fetchPositions();const mappedPositions: Position[] = positionsData.map((p: any) => ({symbol: p.symbol,side: p.side,@@ -361,7 +399,6 @@ export function TradingTab() {}));setPositions(mappedPositions);- const ordersData = await paperAdapter.fetchOpenOrders();const mappedOrders: Order[] = ordersData.map((o: any) => ({id: o.id,symbol: o.symbol,@@ -374,7 +411,6 @@ export function TradingTab() {}));setOrders(mappedOrders);- const tradesData = await paperAdapter.fetchMyTrades(undefined, undefined, 50);setTrades(tradesData);if (typeof (paperAdapter as any).getStatistics === 'function') {@@ -387,7 +423,7 @@ export function TradingTab() {};loadPaperTradingData();- const interval = setInterval(loadPaperTradingData, 2000);+ const interval = setInterval(loadPaperTradingData, 500);return () => clearInterval(interval);}, [tradingMode, paperAdapter]);@@ -467,9 +503,15 @@ export function TradingTab() {// Handle order cancellationconst handleCancelOrder = useCallback(async (orderId: string, symbol: string) => {- if (!paperAdapter) return;+ if (!paperAdapter) {+ console.error('[TradingTab] Paper adapter not available for cancellation');+ return;+ }try {+ console.log(`[TradingTab] Canceling order ${orderId} for ${symbol}`);await paperAdapter.cancelOrder(orderId, symbol);++ // Refresh orders listconst ordersData = await paperAdapter.fetchOpenOrders();const mappedOrders: Order[] = ordersData.map((o: any) => ({id: o.id,@@ -482,8 +524,11 @@ export function TradingTab() {createdAt: o.datetime,}));setOrders(mappedOrders);++ console.log(`[TradingTab] Order ${orderId} canceled successfully`);} catch (error) {- console.error('Cancel failed:', error);+ console.error('[TradingTab] Cancel failed:', error);+ alert(`Failed to cancel order: ${(error as Error).message}`);}}, [paperAdapter]);@@ -969,190 +1014,111 @@ export function TradingTab() {flexDirection: 'column',overflow: 'hidden'}}>- {/* Toggle Header */}+ {/* Header */}<div style={{- padding: '6px',+ padding: '8px 12px',backgroundColor: BLOOMBERG.HEADER_BG,borderBottom: `1px solid ${BLOOMBERG.BORDER}`,- display: 'flex',- gap: '4px'+ fontSize: '10px',+ fontWeight: 700,+ color: BLOOMBERG.ORANGE,+ letterSpacing: '0.5px'}}>- <button- onClick={() => setLeftSidebarView('watchlist')}- style={{- flex: 1,- padding: '6px 8px',- backgroundColor: leftSidebarView === 'watchlist' ? BLOOMBERG.ORANGE : 'transparent',- border: 'none',- color: leftSidebarView === 'watchlist' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,- cursor: 'pointer',- fontSize: '9px',- fontWeight: 700,- letterSpacing: '0.5px',- transition: 'all 0.2s',- borderRadius: '2px'- }}- >- WATCH- </button>- <button- onClick={() => setLeftSidebarView('ai-agents')}- style={{- flex: 1,- padding: '6px 8px',- backgroundColor: leftSidebarView === 'ai-agents' ? BLOOMBERG.ORANGE : 'transparent',- border: 'none',- color: leftSidebarView === 'ai-agents' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,- cursor: 'pointer',- fontSize: '9px',- fontWeight: 700,- letterSpacing: '0.5px',- transition: 'all 0.2s',- borderRadius: '2px'- }}- >- AGENTS- </button>- <button- onClick={() => setLeftSidebarView('leaderboard')}- style={{- flex: 1,- padding: '6px 8px',- backgroundColor: leftSidebarView === 'leaderboard' ? BLOOMBERG.ORANGE : 'transparent',- border: 'none',- color: leftSidebarView === 'leaderboard' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,- cursor: 'pointer',- fontSize: '9px',- fontWeight: 700,- letterSpacing: '0.5px',- transition: 'all 0.2s',- borderRadius: '2px'- }}- >- LEADER- </button>+ WATCHLIST</div>{/* Content */}- <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>- {leftSidebarView === 'watchlist' && (- <div style={{- flex: 1,- overflow: 'auto',- display: 'grid',- gridTemplateColumns: '1fr 1fr',- gap: '0',- alignContent: 'start'- }}>- {watchlist.map((symbol, idx) => (- <div- key={symbol}- onClick={() => setSelectedSymbol(symbol)}- style={{- padding: '8px 10px',- cursor: 'pointer',- backgroundColor: selectedSymbol === symbol ? `${BLOOMBERG.ORANGE}15` : 'transparent',- borderLeft: selectedSymbol === symbol ? `2px solid ${BLOOMBERG.ORANGE}` : '2px solid transparent',- borderBottom: `1px solid ${BLOOMBERG.BORDER}`,- borderRight: idx % 2 === 0 ? `1px solid ${BLOOMBERG.BORDER}` : 'none',- transition: 'all 0.2s'- }}- onMouseEnter={(e) => {- if (selectedSymbol !== symbol) {- e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;- }- }}- onMouseLeave={(e) => {- if (selectedSymbol !== symbol) {- e.currentTarget.style.backgroundColor = 'transparent';- }- }}- >- {/* Flex container: Ticker on left, Price/Change on right */}+ <div style={{+ flex: 1,+ overflow: 'auto',+ display: 'grid',+ gridTemplateColumns: '1fr 1fr',+ gap: '0',+ alignContent: 'start'+ }}>+ {watchlist.map((symbol, idx) => (+ <div+ key={symbol}+ onClick={() => setSelectedSymbol(symbol)}+ style={{+ padding: '8px 10px',+ cursor: 'pointer',+ backgroundColor: selectedSymbol === symbol ? `${BLOOMBERG.ORANGE}15` : 'transparent',+ borderLeft: selectedSymbol === symbol ? `2px solid ${BLOOMBERG.ORANGE}` : '2px solid transparent',+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ borderRight: idx % 2 === 0 ? `1px solid ${BLOOMBERG.BORDER}` : 'none',+ transition: 'all 0.2s'+ }}+ onMouseEnter={(e) => {+ if (selectedSymbol !== symbol) {+ e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;+ }+ }}+ onMouseLeave={(e) => {+ if (selectedSymbol !== symbol) {+ e.currentTarget.style.backgroundColor = 'transparent';+ }+ }}+ >+ {/* Flex container: Ticker on left, Price/Change on right */}+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center',+ gap: '8px'+ }}>+ {/* Left side: Ticker symbol */}+ <div style={{+ fontSize: '11px',+ fontWeight: 700,+ color: selectedSymbol === symbol ? BLOOMBERG.ORANGE : BLOOMBERG.WHITE,+ whiteSpace: 'nowrap'+ }}>+ {symbol.replace('/USD', '')}+ </div>++ {/* Right side: Price and Change */}+ {watchlistPrices[symbol] ? (<div style={{display: 'flex',- justifyContent: 'space-between',- alignItems: 'center',- gap: '8px'+ flexDirection: 'column',+ alignItems: 'flex-end',+ gap: '2px'}}>- {/* Left side: Ticker symbol */}<div style={{- fontSize: '11px',- fontWeight: 700,- color: selectedSymbol === symbol ? BLOOMBERG.ORANGE : BLOOMBERG.WHITE,- whiteSpace: 'nowrap'+ fontSize: '10px',+ color: BLOOMBERG.WHITE,+ fontFamily: 'monospace',+ fontWeight: 600}}>- {symbol.replace('/USD', '')}+ ${watchlistPrices[symbol].price >= 1000+ ? watchlistPrices[symbol].price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })+ : watchlistPrices[symbol].price >= 1+ ? watchlistPrices[symbol].price.toFixed(2)+ : watchlistPrices[symbol].price.toFixed(4)+ }+ </div>+ <div style={{+ fontSize: '9px',+ color: watchlistPrices[symbol].change >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED,+ fontFamily: 'monospace',+ fontWeight: 700+ }}>+ {watchlistPrices[symbol].change >= 0 ? '▲' : '▼'} {Math.abs(watchlistPrices[symbol].change).toFixed(2)}%</div>-- {/* Right side: Price and Change */}- {watchlistPrices[symbol] ? (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'flex-end',- gap: '2px'- }}>- <div style={{- fontSize: '10px',- color: BLOOMBERG.WHITE,- fontFamily: 'monospace',- fontWeight: 600- }}>- ${watchlistPrices[symbol].price >= 1000- ? watchlistPrices[symbol].price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })- : watchlistPrices[symbol].price >= 1- ? watchlistPrices[symbol].price.toFixed(2)- : watchlistPrices[symbol].price.toFixed(4)- }- </div>- <div style={{- fontSize: '9px',- color: watchlistPrices[symbol].change >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED,- fontFamily: 'monospace',- fontWeight: 700- }}>- {watchlistPrices[symbol].change >= 0 ? '▲' : '▼'} {Math.abs(watchlistPrices[symbol].change).toFixed(2)}%- </div>- </div>- ) : (- <div style={{- fontSize: '9px',- color: BLOOMBERG.GRAY,- fontFamily: 'monospace'- }}>- ...- </div>- )}</div>- </div>- ))}- </div>- )}-- {leftSidebarView === 'ai-agents' && (- <div style={{ flex: 1, overflow: 'auto' }}>- <AIAgentsPanel- selectedSymbol={selectedSymbol}- portfolioData={{- positions: positions.map(p => ({- symbol: p.symbol,- quantity: p.quantity,- entry_price: p.entryPrice,- current_price: p.currentPrice,- value: p.positionValue- })),- total_value: equity- }}- />- </div>- )}-- {leftSidebarView === 'leaderboard' && (- <div style={{ flex: 1, overflow: 'hidden' }}>- <LeaderboardPanel refreshInterval={10000} />+ ) : (+ <div style={{+ fontSize: '9px',+ color: BLOOMBERG.GRAY,+ fontFamily: 'monospace'+ }}>+ ...+ </div>+ )}+ </div></div>- )}+ ))}</div></div>@@ -1585,7 +1551,7 @@ export function TradingTab() {alignItems: 'center'}}><div style={{ display: 'flex', gap: '8px' }}>- {['orderbook', 'volume', 'modelchat'].map((view) => (+ {['orderbook', 'volume'].map((view) => (<buttonkey={view}onClick={() => setRightPanelView(view as any)}@@ -1713,10 +1679,6 @@ export function TradingTab() {{rightPanelView === 'volume' && (<VolumeProfile symbol={selectedSymbol} height={550} />)}-- {rightPanelView === 'modelchat' && (- <ModelChatPanel refreshInterval={5000} />- )}</div><div style={{padding: '4px 8px',diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaChart.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaChart.tsxnew file mode 100644index 000000000..6797d03ef--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaChart.tsx@@ -0,0 +1,250 @@+/**+ * Alpha Arena Performance Chart+ * Bloomberg-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/sqliteService';++interface AlphaArenaChartProps {+ snapshots: AlphaPerformanceSnapshot[];+ initialCapital?: number;+}++// Bloomberg 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 BLOOMBERG = {+ 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 => {+ if (!cycleMap.has(snap.cycle_number)) {+ cycleMap.set(snap.cycle_number, {+ cycle: snap.cycle_number,+ timestamp: snap.timestamp,+ });+ }++ const cycleData = cycleMap.get(snap.cycle_number)!;+ 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: BLOOMBERG.PANEL_BG,+ border: `1px solid ${BLOOMBERG.BORDER}`,+ padding: '12px',+ fontSize: '10px',+ fontFamily: '"IBM Plex Mono", monospace',+ }}>+ <div style={{ color: BLOOMBERG.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: BLOOMBERG.WHITE, fontWeight: 600 }}>+ {entry.name}:+ </span>+ </div>+ <span style={{+ color: entry.value >= initialCapital ? BLOOMBERG.GREEN : BLOOMBERG.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: BLOOMBERG.WHITE, fontWeight: 600 }}>+ {entry.value}+ </span>+ </div>+ ))}+ </div>+ );+ };++ if (chartData.length === 0) {+ return (+ <div style={{+ height: '100%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: BLOOMBERG.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={BLOOMBERG.BORDER}+ vertical={false}+ />+ <XAxis+ dataKey="cycle"+ stroke={BLOOMBERG.GRAY}+ tick={{ fill: BLOOMBERG.GRAY, fontSize: 10, fontFamily: '"IBM Plex Mono", monospace' }}+ label={{+ value: 'CYCLE',+ position: 'insideBottom',+ offset: -5,+ fill: BLOOMBERG.GRAY,+ fontSize: 10,+ fontFamily: '"IBM Plex Mono", monospace',+ }}+ />+ <YAxis+ stroke={BLOOMBERG.GRAY}+ tick={{ fill: BLOOMBERG.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: BLOOMBERG.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={BLOOMBERG.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: BLOOMBERG.WHITE,+ strokeWidth: 2,+ }}+ name={modelName}+ />+ ))}+ </LineChart>+ </ResponsiveContainer>+ );+};++export default AlphaArenaChart;diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/CompetitionDashboard.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/CompetitionDashboard.tsxnew file mode 100644index 000000000..fb46a8dff--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/CompetitionDashboard.tsx@@ -0,0 +1,351 @@+/**+ * 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/sqliteService';++const BLOOMBERG = {+ 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 BLOOMBERG.GREEN;+ case 'paused': return BLOOMBERG.YELLOW;+ case 'completed': return BLOOMBERG.GRAY;+ default: return BLOOMBERG.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: BLOOMBERG.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={BLOOMBERG.GRAY} strokeWidth={1.5} />+ <div style={{+ textAlign: 'center',+ color: BLOOMBERG.GRAY,+ fontFamily: '"IBM Plex Mono", monospace'+ }}>+ <div style={{ fontSize: '16px', fontWeight: 700, marginBottom: '8px', color: BLOOMBERG.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: BLOOMBERG.ORANGE,+ color: BLOOMBERG.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 = BLOOMBERG.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: BLOOMBERG.HEADER_BG,+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ display: 'flex',+ justifyContent: 'space-between',+ alignItems: 'center'+ }}>+ <div style={{+ fontSize: '11px',+ fontWeight: 700,+ color: BLOOMBERG.ORANGE,+ letterSpacing: '0.5px',+ fontFamily: '"IBM Plex Mono", monospace'+ }}>+ COMPETITION HISTORY ({competitions.length})+ </div>+ <button+ onClick={onCreateNew}+ style={{+ padding: '8px 16px',+ backgroundColor: BLOOMBERG.ORANGE,+ color: BLOOMBERG.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 = BLOOMBERG.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 ? BLOOMBERG.HEADER_BG : BLOOMBERG.PANEL_BG,+ border: `1px solid ${comp.id === currentCompetitionId ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,+ padding: '16px',+ cursor: 'pointer',+ transition: 'all 0.2s',+ fontFamily: '"IBM Plex Mono", monospace'+ }}+ onMouseOver={(e) => {+ if (comp.id !== currentCompetitionId) {+ e.currentTarget.style.borderColor = BLOOMBERG.GRAY;+ }+ }}+ onMouseOut={(e) => {+ if (comp.id !== currentCompetitionId) {+ e.currentTarget.style.borderColor = BLOOMBERG.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: BLOOMBERG.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 ${BLOOMBERG.CYAN}`,+ color: BLOOMBERG.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 ${BLOOMBERG.RED}`,+ color: BLOOMBERG.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: BLOOMBERG.GRAY, marginBottom: '2px' }}>SYMBOL</div>+ <div style={{ fontSize: '10px', color: BLOOMBERG.CYAN, fontWeight: 600 }}>{comp.symbol}</div>+ </div>+ <div>+ <div style={{ fontSize: '8px', color: BLOOMBERG.GRAY, marginBottom: '2px' }}>MODE</div>+ <div style={{ fontSize: '10px', color: BLOOMBERG.YELLOW, fontWeight: 600 }}>{comp.mode.toUpperCase()}</div>+ </div>+ <div>+ <div style={{ fontSize: '8px', color: BLOOMBERG.GRAY, marginBottom: '2px' }}>CYCLES</div>+ <div style={{ fontSize: '10px', color: BLOOMBERG.WHITE, fontWeight: 600 }}>{comp.cycle_count}</div>+ </div>+ <div>+ <div style={{ fontSize: '8px', color: BLOOMBERG.GRAY, marginBottom: '2px' }}>CAPITAL</div>+ <div style={{ fontSize: '10px', color: BLOOMBERG.GREEN, fontWeight: 600 }}>${comp.initial_capital.toLocaleString()}</div>+ </div>+ </div>++ {/* Timestamps */}+ <div style={{+ borderTop: `1px solid ${BLOOMBERG.BORDER}`,+ paddingTop: '8px',+ fontSize: '8px',+ color: BLOOMBERG.MUTED+ }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', marginBottom: '4px' }}>+ <Calendar size={10} />+ Created: {formatDate(comp.created_at)}+ </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.tsxnew file mode 100644index 000000000..424459c05--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/TradeHistoryPanel.tsx@@ -0,0 +1,220 @@+/**+ * 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/sqliteService';++interface TradeHistoryPanelProps {+ decisions: AlphaDecisionLog[];+}++const BLOOMBERG = {+ 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: BLOOMBERG.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: BLOOMBERG.HEADER_BG,+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,+ fontSize: '8px',+ fontWeight: 700,+ color: BLOOMBERG.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 ${BLOOMBERG.BORDER}`,+ fontSize: '9px',+ color: BLOOMBERG.WHITE,+ alignItems: 'center',+ backgroundColor: idx % 2 === 0 ? BLOOMBERG.DARK_BG : BLOOMBERG.PANEL_BG+ }}+ >+ {/* Time */}+ <div style={{ color: BLOOMBERG.GRAY }}>+ {formatTime(decision.timestamp)}+ </div>++ {/* Cycle */}+ <div style={{ color: BLOOMBERG.CYAN, fontWeight: 600 }}>+ #{decision.cycle_number}+ </div>++ {/* Model */}+ <div style={{+ color: BLOOMBERG.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={BLOOMBERG.GREEN} />+ <span style={{ color: BLOOMBERG.GREEN }}>BUY</span>+ </>+ )}+ {decision.action === 'sell' && (+ <>+ <TrendingDown size={12} color={BLOOMBERG.RED} />+ <span style={{ color: BLOOMBERG.RED }}>SELL</span>+ </>+ )}+ {decision.action === 'hold' && (+ <>+ <Circle size={12} color={BLOOMBERG.GRAY} />+ <span style={{ color: BLOOMBERG.GRAY }}>HOLD</span>+ </>+ )}+ </div>++ {/* Quantity */}+ <div style={{ color: BLOOMBERG.WHITE, fontWeight: 600 }}>+ {decision.quantity ? `×${decision.quantity.toFixed(3)}` : '-'}+ </div>++ {/* Price */}+ <div style={{ color: BLOOMBERG.CYAN }}>+ {decision.price_at_decision+ ? `$${decision.price_at_decision.toLocaleString('en-US', { minimumFractionDigits: 2 })}`+ : '-'}+ </div>++ {/* Reasoning */}+ <div style={{+ color: BLOOMBERG.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={BLOOMBERG.GREEN} />+ <span style={{ color: BLOOMBERG.GREEN }}>EXEC</span>+ </>+ )}+ {isRejected && (+ <>+ <XCircle size={10} color={BLOOMBERG.RED} />+ <span style={{ color: BLOOMBERG.RED }}>REJ</span>+ </>+ )}+ {isHold && (+ <>+ <Circle size={10} color={BLOOMBERG.GRAY} />+ <span style={{ color: BLOOMBERG.GRAY }}>HOLD</span>+ </>+ )}+ {!isExecuted && !isRejected && !isHold && (+ <span style={{ color: BLOOMBERG.YELLOW }}>PEND</span>+ )}+ </div>+ </div>+ );+ })}+ </div>+ );+};++export default TradeHistoryPanel;diff --git a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/CompetitionPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/CompetitionPanel.tsxindex 956f749ca..cc27083c4 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/CompetitionPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/CompetitionPanel.tsx@@ -1,762 +1,212 @@/**- * Competition Panel- *- * Alpha Arena style AI trading competition- * - Create multi-model competitions- * - Start/stop competitions- * - Real-time decision streaming- * - Live leaderboard updates+ * Competition Panel - NOF1 Alpha Arena Style+ * Ultra-simple: Select models → Start → Watch them trade*/import React, { useState, useEffect } from 'react';-import { Play, Square, Trophy, Brain, TrendingUp, AlertCircle, Plus, X } from 'lucide-react';-import { agnoTradingService, type CompetitionResult, type ModelPerformance } from '../../../../services/agnoTradingService';+import { Play, Square } from 'lucide-react';+import { agnoTradingService } from '../../../../services/agnoTradingService';-const BLOOMBERG = {+const COLORS = {ORANGE: '#FF8800',- WHITE: '#FFFFFF',- RED: '#FF3B3B',GREEN: '#00D66F',+ RED: '#FF3B3B',+ WHITE: '#FFFFFF',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'+ BG: '#0F0F0F',+ BORDER: '#2A2A2A'};-interface CompetitionPanelProps {- selectedSymbol: string;+interface Model {+ value: string;+ label: string;}-export function CompetitionPanel({ selectedSymbol }: CompetitionPanelProps) {- const [teamId, setTeamId] = useState<string | null>(null);+export function CompetitionPanel({ selectedSymbol }: { selectedSymbol: string }) {+ const [models, setModels] = useState<Model[]>([]);+ const [selected, setSelected] = useState<string[]>([]);const [isRunning, setIsRunning] = useState(false);- const [isLoading, setIsLoading] = useState(false);+ const [teamId, setTeamId] = useState<string | null>(null);+ const [price, setPrice] = useState(67000);const [error, setError] = useState<string | null>(null);- const [result, setResult] = useState<CompetitionResult | null>(null);- const [showSetup, setShowSetup] = useState(false);- // Competition setup state- const [competitionName, setCompetitionName] = useState('AI Trading Competition');- const [selectedModels, setSelectedModels] = useState<string[]>([]);- const [taskType, setTaskType] = useState<'analyze' | 'signal' | 'evaluate'>('analyze');- const [autoRefresh, setAutoRefresh] = useState(true);- const [availableModels, setAvailableModels] = useState<Array<{ value: string; label: string; color: string }>>([]);-- // Color mapping for providers- const getProviderColor = (provider: string) => {- const colorMap: Record<string, string> = {- 'openai': BLOOMBERG.GREEN,- 'anthropic': BLOOMBERG.ORANGE,- 'google': BLOOMBERG.BLUE,- 'groq': BLOOMBERG.PURPLE,- 'deepseek': BLOOMBERG.CYAN,- 'xai': BLOOMBERG.YELLOW,- 'together': BLOOMBERG.PURPLE,- 'mistral': BLOOMBERG.BLUE,- 'cohere': BLOOMBERG.CYAN- };- return colorMap[provider.toLowerCase()] || BLOOMBERG.GRAY;- };-- // Load configured models from database+ // Load models from databaseuseEffect(() => {- const loadConfiguredModels = async () => {+ (async () => {try {- console.log('[CompetitionPanel] Loading configured models...');const { sqliteService } = await import('../../../../services/sqliteService');const configs = await sqliteService.getLLMConfigs();- console.log('[CompetitionPanel] Raw configs:', configs);-- // Filter to only models with API keys configured- const configuredModels = configs- .filter(c => c.api_key && c.api_key.trim().length > 0)+ const modelList = configs+ .filter(c => c.api_key?.trim()).map(c => ({value: `${c.provider}:${c.model}`,- label: `${c.provider.charAt(0).toUpperCase() + c.provider.slice(1)} - ${c.model}`,- color: getProviderColor(c.provider)+ label: `${c.provider} - ${c.model}`}));-- console.log('[CompetitionPanel] Configured models:', configuredModels);- setAvailableModels(configuredModels);-- // Auto-select first 3 models if available- if (configuredModels.length >= 3) {- const selected = configuredModels.slice(0, 3).map(m => m.value);- console.log('[CompetitionPanel] Auto-selecting first 3 models:', selected);- setSelectedModels(selected);- } else if (configuredModels.length >= 2) {- const selected = configuredModels.slice(0, 2).map(m => m.value);- console.log('[CompetitionPanel] Auto-selecting first 2 models:', selected);- setSelectedModels(selected);- } else {- console.warn('[CompetitionPanel] Not enough models configured for competition (need at least 2)');- }+ setModels(modelList);+ setSelected(modelList.slice(0, 2).map(m => m.value)); // Auto-select first 2} catch (err) {- console.error('[CompetitionPanel] Failed to load configured models:', err);- setError('Failed to load configured models. Please configure API keys in Settings → LLM Config');+ setError('Failed to load models. Configure API keys in Settings.');}- };-- loadConfiguredModels();+ })();}, []);- // Create competition- const handleCreateCompetition = async () => {- if (selectedModels.length < 2) {- const errorMsg = 'Select at least 2 models to compete';- console.error('[CompetitionPanel]', errorMsg);- setError(errorMsg);+ // Start competition+ const start = async () => {+ if (selected.length < 2) {+ setError('Select at least 2 models');return;}try {- setIsLoading(true);setError(null);- console.log('[CompetitionPanel] Creating competition:', {- name: competitionName,- models: selectedModels,- type: 'trading'- });-- const response = await agnoTradingService.createCompetition(- competitionName,- selectedModels,+ // Create team+ const res = await agnoTradingService.createCompetition(+ 'Competition',+ selected,'trading');- console.log('[CompetitionPanel] Create competition response:', response);-- if (response.success && response.data) {- console.log('[CompetitionPanel] Competition created successfully. Team ID:', response.data.team_id);- setTeamId(response.data.team_id);- setShowSetup(false);- } else {- const errorMsg = response.error || 'Failed to create competition';- console.error('[CompetitionPanel] Competition creation failed:', errorMsg);- setError(errorMsg);- }- } catch (err) {- console.error('[CompetitionPanel] Exception during competition creation:', err);- const errorMsg = err instanceof Error ? err.message : String(err);- setError(errorMsg);- } finally {- setIsLoading(false);- }- };-- // Run competition- const handleRunCompetition = async () => {- if (!teamId) {- console.error('[CompetitionPanel] No team ID available');- return;- }+ if (!res.success) throw new Error(res.error);- try {- setIsLoading(true);+ const tid = res.data!.team_id;+ setTeamId(tid);setIsRunning(true);- setError(null);- console.log('[CompetitionPanel] Running competition:', {- teamId,- symbol: selectedSymbol,- taskType- });+ // Start price feed+ const { krakenPriceFeed } = await import('../../../../services/krakenPriceFeed');+ await krakenPriceFeed.connect();- const response = await agnoTradingService.runCompetition(- teamId,- selectedSymbol,- taskType- );+ krakenPriceFeed.subscribe(selectedSymbol, async (p) => {+ if (!isRunning) return;+ setPrice(p);- console.log('[CompetitionPanel] Run competition response:', response);+ try {+ await agnoTradingService.runCompetition(tid, selectedSymbol, 'signal');+ } catch (e) {+ console.error('[Competition] Trade error:', e);+ }+ });- if (response.success && response.data) {- console.log('[CompetitionPanel] Competition completed successfully');- setResult(response.data);- } else {- const errorMsg = response.error || 'Competition failed';- console.error('[CompetitionPanel] Competition run failed:', errorMsg);- console.error('[CompetitionPanel] Full response:', JSON.stringify(response, null, 2));- setError(errorMsg);- }} catch (err) {- console.error('[CompetitionPanel] Exception during competition run:', err);- console.error('[CompetitionPanel] Error details:', {- message: err instanceof Error ? err.message : String(err),- stack: err instanceof Error ? err.stack : undefined,- raw: err- });- const errorMsg = err instanceof Error ? err.message : String(err);- setError(errorMsg);- } finally {- setIsLoading(false);+ setError(err instanceof Error ? err.message : String(err));setIsRunning(false);}};// Stop competition- const handleStopCompetition = () => {+ const stop = async () => {setIsRunning(false);- };-- // Reset competition- const handleResetCompetition = () => {- setTeamId(null);- setResult(null);- setError(null);- setShowSetup(true);- };-- // Auto-refresh leaderboard- useEffect(() => {- if (!autoRefresh || !teamId) return;-- const interval = setInterval(async () => {- try {- const response = await agnoTradingService.getLeaderboard();- if (response.success && response.data && result) {- setResult({- ...result,- leaderboard: response.data.leaderboard- });- }- } catch (err) {- console.error('Failed to refresh leaderboard:', err);- }- }, 5000);-- return () => clearInterval(interval);- }, [autoRefresh, teamId, result]);-- // Toggle model selection- const toggleModel = (model: string) => {- setSelectedModels(prev => {- const newSelection = prev.includes(model)- ? prev.filter(m => m !== model)- : [...prev, model];-- console.log('[CompetitionPanel] Model selection updated:', {- toggled: model,- wasPreviouslySelected: prev.includes(model),- previousSelection: prev,- newSelection: newSelection- });-- return newSelection;- });+ const { krakenPriceFeed } = await import('../../../../services/krakenPriceFeed');+ await krakenPriceFeed.disconnect();};return (<div style={{- height: '100%',- background: BLOOMBERG.PANEL_BG,- border: `1px solid ${BLOOMBERG.BORDER}`,- borderRadius: '2px',- display: 'flex',- flexDirection: 'column',- overflow: 'hidden'+ background: COLORS.BG,+ border: `1px solid ${COLORS.BORDER}`,+ padding: '20px',+ borderRadius: '4px',+ height: '100%'}}>{/* Header */}- <div style={{- background: BLOOMBERG.HEADER_BG,- borderBottom: `1px solid ${BLOOMBERG.BORDER}`,- padding: '8px 10px',- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between'- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>- <Trophy size={14} color={BLOOMBERG.YELLOW} />- <span style={{- color: BLOOMBERG.WHITE,- fontSize: '11px',- fontWeight: '600',- letterSpacing: '0.5px'- }}>- COMPETITION- </span>- {isRunning && (- <div style={{- width: '8px',- height: '8px',- borderRadius: '50%',- background: BLOOMBERG.GREEN,- animation: 'pulse 2s infinite'- }} />- )}- </div>-- {/* Controls */}- <div style={{ display: 'flex', gap: '4px' }}>- {!teamId && (- <button- onClick={() => setShowSetup(!showSetup)}- style={{- background: BLOOMBERG.ORANGE,- border: 'none',- color: BLOOMBERG.DARK_BG,- padding: '4px 8px',- borderRadius: '2px',- fontSize: '9px',- fontWeight: '700',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '4px'- }}- >- <Plus size={10} />- SETUP- </button>- )}-- {teamId && !isRunning && (- <button- onClick={handleRunCompetition}- disabled={isLoading}- style={{- background: BLOOMBERG.GREEN,- border: 'none',- color: BLOOMBERG.DARK_BG,- padding: '4px 8px',- borderRadius: '2px',- fontSize: '9px',- fontWeight: '700',- cursor: isLoading ? 'not-allowed' : 'pointer',- opacity: isLoading ? 0.5 : 1,- display: 'flex',- alignItems: 'center',- gap: '4px'- }}- >- <Play size={10} />- RUN- </button>- )}-- {isRunning && (- <button- onClick={handleStopCompetition}- style={{- background: BLOOMBERG.RED,- border: 'none',- color: BLOOMBERG.WHITE,- padding: '4px 8px',- borderRadius: '2px',- fontSize: '9px',- fontWeight: '700',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '4px'- }}- >- <Square size={10} />- STOP- </button>- )}-- {teamId && (- <button- onClick={handleResetCompetition}- style={{- background: 'transparent',- border: `1px solid ${BLOOMBERG.BORDER}`,- color: BLOOMBERG.GRAY,- padding: '4px 8px',- borderRadius: '2px',- fontSize: '9px',- fontWeight: '700',- cursor: 'pointer'- }}- >- RESET- </button>- )}+ <div style={{ marginBottom: '20px' }}>+ <h2 style={{ color: COLORS.ORANGE, fontSize: '16px', marginBottom: '8px' }}>+ AI TRADING COMPETITION+ </h2>+ <div style={{ color: COLORS.GRAY, fontSize: '12px' }}>+ {selectedSymbol} · ${price.toLocaleString()}</div></div>- {/* Content */}- <div style={{ flex: 1, overflow: 'auto', padding: '10px' }}>- {/* Setup View */}- {showSetup && !teamId && (- <SetupView- competitionName={competitionName}- setCompetitionName={setCompetitionName}- selectedModels={selectedModels}- toggleModel={toggleModel}- availableModels={availableModels}- taskType={taskType}- setTaskType={setTaskType}- onCreateCompetition={handleCreateCompetition}- isLoading={isLoading}- />- )}-- {/* Results View */}- {teamId && !showSetup && result && (- <ResultsView result={result} selectedSymbol={selectedSymbol} />- )}-- {/* Empty State */}- {!showSetup && !teamId && !result && (- <div style={{- textAlign: 'center',- color: BLOOMBERG.GRAY,- fontSize: '10px',- marginTop: '40px'- }}>- <Trophy size={40} color={BLOOMBERG.GRAY} style={{ marginBottom: '10px' }} />- <div>No active competition</div>- <div style={{ marginTop: '4px', fontSize: '9px' }}>Click SETUP to create one</div>- </div>- )}-- {/* Error Display */}- {error && (- <div style={{- background: `${BLOOMBERG.RED}15`,- border: `1px solid ${BLOOMBERG.RED}`,- borderRadius: '2px',- padding: '8px',- marginTop: '10px',- display: 'flex',- alignItems: 'center',- gap: '6px'- }}>- <AlertCircle size={14} color={BLOOMBERG.RED} />- <span style={{ color: BLOOMBERG.RED, fontSize: '10px' }}>{error}</span>- </div>- )}- </div>- </div>- );-}--// Setup View Component-function SetupView({- competitionName,- setCompetitionName,- selectedModels,- toggleModel,- availableModels,- taskType,- setTaskType,- onCreateCompetition,- isLoading-}: any) {- return (- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>- {/* Competition Name */}- <div>- <label style={{ color: BLOOMBERG.GRAY, fontSize: '9px', display: 'block', marginBottom: '4px' }}>- COMPETITION NAME- </label>- <input- type="text"- value={competitionName}- onChange={(e) => setCompetitionName(e.target.value)}- style={{- width: '100%',- background: BLOOMBERG.DARK_BG,- border: `1px solid ${BLOOMBERG.BORDER}`,- color: BLOOMBERG.WHITE,- padding: '6px 8px',- borderRadius: '2px',- fontSize: '10px',- fontFamily: '"IBM Plex Mono", monospace'- }}- />- </div>+ {error && (+ <div style={{+ background: '#FF3B3B20',+ border: `1px solid ${COLORS.RED}`,+ padding: '10px',+ borderRadius: '4px',+ color: COLORS.RED,+ fontSize: '12px',+ marginBottom: '20px'+ }}>+ {error}+ </div>+ )}{/* Model Selection */}- <div>- <label style={{ color: BLOOMBERG.GRAY, fontSize: '9px', display: 'block', marginBottom: '6px' }}>- SELECT MODELS (min 2) - {availableModels.length} Available- </label>-- {availableModels.length === 0 ? (- <div style={{- background: `${BLOOMBERG.YELLOW}15`,- border: `1px solid ${BLOOMBERG.YELLOW}`,- borderRadius: '2px',- padding: '8px',- fontSize: '9px',- color: BLOOMBERG.YELLOW,- textAlign: 'center'- }}>- No models configured. Go to Settings → LLM Config to add API keys.- </div>- ) : availableModels.length < 2 ? (- <div style={{- background: `${BLOOMBERG.ORANGE}15`,- border: `1px solid ${BLOOMBERG.ORANGE}`,- borderRadius: '2px',- padding: '8px',- fontSize: '9px',- color: BLOOMBERG.ORANGE,- textAlign: 'center'- }}>- Need at least 2 models for competition. Configure more in Settings → LLM Config.- </div>- ) : (- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px' }}>- {availableModels.map((model: any) => {- const isSelected = selectedModels.includes(model.value);- return (- <button- key={model.value}- onClick={() => {- console.log('[CompetitionPanel] Toggle model:', model.value, 'Currently selected:', isSelected);- toggleModel(model.value);- }}- style={{- background: isSelected ? `${model.color}30` : BLOOMBERG.DARK_BG,- border: `2px solid ${isSelected ? model.color : BLOOMBERG.BORDER}`,- color: isSelected ? model.color : BLOOMBERG.GRAY,- padding: '8px 10px',- borderRadius: '3px',- fontSize: '9px',- fontWeight: isSelected ? '700' : '500',- cursor: 'pointer',- transition: 'all 0.2s',- textAlign: 'left',- position: 'relative',- display: 'flex',- alignItems: 'center',- gap: '6px'- }}- onMouseEnter={(e) => {- if (!isSelected) {- e.currentTarget.style.background = BLOOMBERG.HOVER;- e.currentTarget.style.borderColor = model.color + '50';- }- }}- onMouseLeave={(e) => {- if (!isSelected) {- e.currentTarget.style.background = BLOOMBERG.DARK_BG;- e.currentTarget.style.borderColor = BLOOMBERG.BORDER;- }- }}- >- {/* Selection Indicator */}- <div style={{- width: '10px',- height: '10px',- borderRadius: '50%',- border: `2px solid ${isSelected ? model.color : BLOOMBERG.BORDER}`,- background: isSelected ? model.color : 'transparent',- flexShrink: 0,- transition: 'all 0.2s'- }} />- <span>{model.label}</span>- </button>- );- })}- </div>- )}- </div>-- {/* Task Type */}- <div>- <label style={{ color: BLOOMBERG.GRAY, fontSize: '9px', display: 'block', marginBottom: '4px' }}>- TASK TYPE- </label>- <div style={{ display: 'flex', gap: '4px' }}>- {['analyze', 'signal', 'evaluate'].map((task) => (- <button- key={task}- onClick={() => setTaskType(task)}- style={{- flex: 1,- background: taskType === task ? BLOOMBERG.ORANGE : 'transparent',- border: `1px solid ${taskType === task ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,- color: taskType === task ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,- padding: '6px',- borderRadius: '2px',- fontSize: '9px',- fontWeight: '700',- cursor: 'pointer',- transition: 'all 0.2s',- textTransform: 'uppercase'- }}- >- {task}- </button>+ <div style={{ marginBottom: '20px' }}>+ <div style={{ color: COLORS.WHITE, fontSize: '13px', marginBottom: '10px' }}>+ SELECT MODELS (minimum 2)+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>+ {models.map(m => (+ <label key={m.value} style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ padding: '8px',+ background: selected.includes(m.value) ? '#FF880020' : 'transparent',+ border: `1px solid ${selected.includes(m.value) ? COLORS.ORANGE : COLORS.BORDER}`,+ borderRadius: '4px',+ cursor: 'pointer',+ fontSize: '12px',+ color: COLORS.WHITE+ }}>+ <input+ type="checkbox"+ checked={selected.includes(m.value)}+ onChange={(e) => {+ if (e.target.checked) {+ setSelected([...selected, m.value]);+ } else {+ setSelected(selected.filter(s => s !== m.value));+ }+ }}+ disabled={isRunning}+ />+ {m.label}+ </label>))}</div></div>- {/* Create Button */}+ {/* Start/Stop Button */}<button- onClick={onCreateCompetition}- disabled={isLoading || selectedModels.length < 2}+ onClick={isRunning ? stop : start}+ disabled={!isRunning && selected.length < 2}style={{- background: BLOOMBERG.ORANGE,+ width: '100%',+ padding: '12px',+ background: isRunning ? COLORS.RED : COLORS.GREEN,+ color: '#000',border: 'none',- color: BLOOMBERG.DARK_BG,- padding: '10px',- borderRadius: '2px',- fontSize: '10px',+ borderRadius: '4px',+ fontSize: '14px',fontWeight: '700',- cursor: (isLoading || selectedModels.length < 2) ? 'not-allowed' : 'pointer',- opacity: (isLoading || selectedModels.length < 2) ? 0.5 : 1,- marginTop: '8px'+ cursor: selected.length >= 2 || isRunning ? 'pointer' : 'not-allowed',+ opacity: selected.length >= 2 || isRunning ? 1 : 0.5,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ gap: '8px'}}>- {isLoading ? 'CREATING...' : 'CREATE COMPETITION'}+ {isRunning ? <Square size={16} /> : <Play size={16} />}+ {isRunning ? 'STOP COMPETITION' : 'START COMPETITION'}</button>- </div>- );-}-// Results View Component-function ResultsView({ result, selectedSymbol }: { result: CompetitionResult; selectedSymbol: string }) {- return (- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>- {/* Consensus */}- {result.consensus && (+ {isRunning && (<div style={{- background: BLOOMBERG.DARK_BG,- border: `1px solid ${BLOOMBERG.BORDER}`,- borderRadius: '2px',- padding: '10px'+ marginTop: '20px',+ padding: '12px',+ background: '#00D66F20',+ border: `1px solid ${COLORS.GREEN}`,+ borderRadius: '4px',+ color: COLORS.GREEN,+ fontSize: '12px',+ textAlign: 'center'}}>- <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '6px' }}>- CONSENSUS- </div>- <div style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- marginBottom: '8px'- }}>- <span style={{- color: BLOOMBERG.WHITE,- fontSize: '14px',- fontWeight: '700',- textTransform: 'uppercase'- }}>- {result.consensus.action}- </span>- <span style={{- color: BLOOMBERG.ORANGE,- fontSize: '12px',- fontWeight: '700'- }}>- {(result.consensus.confidence * 100).toFixed(0)}% CONFIDENCE- </span>- </div>- <div style={{- display: 'flex',- gap: '12px',- fontSize: '9px',- color: BLOOMBERG.GRAY- }}>- <div>- AGREEMENT: <span style={{ color: BLOOMBERG.WHITE, fontWeight: '600' }}>- {result.consensus.agreement}/{result.consensus.total_models}- </span>- </div>- </div>- </div>- )}-- {/* Model Results */}- <div style={{- background: BLOOMBERG.DARK_BG,- border: `1px solid ${BLOOMBERG.BORDER}`,- borderRadius: '2px',- padding: '10px'- }}>- <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '8px' }}>- MODEL RESULTS- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>- {result.results.map((modelResult, idx) => (- <div- key={idx}- style={{- background: BLOOMBERG.PANEL_BG,- border: `1px solid ${BLOOMBERG.BORDER}`,- borderRadius: '2px',- padding: '8px'- }}- >- <div style={{- display: 'flex',- justifyContent: 'space-between',- marginBottom: '4px'- }}>- <span style={{ color: BLOOMBERG.ORANGE, fontSize: '10px', fontWeight: '700' }}>- {modelResult.model.split(':')[1] || modelResult.model}- </span>- <span style={{ color: BLOOMBERG.GRAY, fontSize: '8px' }}>- {new Date(modelResult.timestamp).toLocaleTimeString()}- </span>- </div>- <div style={{ color: BLOOMBERG.WHITE, fontSize: '9px', lineHeight: '1.4' }}>- {modelResult.response.substring(0, 150)}...- </div>- </div>- ))}- </div>- </div>-- {/* Leaderboard */}- {result.leaderboard && result.leaderboard.length > 0 && (- <div style={{- background: BLOOMBERG.DARK_BG,- border: `1px solid ${BLOOMBERG.BORDER}`,- borderRadius: '2px',- padding: '10px'- }}>- <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginBottom: '8px' }}>- LEADERBOARD- </div>- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>- {result.leaderboard.slice(0, 5).map((model, idx) => (- <div- key={model.model}- style={{- display: 'flex',- justifyContent: 'space-between',- padding: '6px',- background: BLOOMBERG.PANEL_BG,- border: `1px solid ${BLOOMBERG.BORDER}`,- borderRadius: '2px'- }}- >- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>- <span style={{- color: idx === 0 ? BLOOMBERG.YELLOW : BLOOMBERG.GRAY,- fontSize: '10px',- fontWeight: '700'- }}>- #{idx + 1}- </span>- <span style={{ color: BLOOMBERG.WHITE, fontSize: '10px' }}>- {model.model.split(':')[1]}- </span>- </div>- <span style={{- color: model.total_pnl >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED,- fontSize: '10px',- fontWeight: '700'- }}>- {model.total_pnl >= 0 ? '+' : ''}{model.total_pnl.toFixed(2)}- </span>- </div>- ))}- </div>+ LIVE · Models trading at ${price.toLocaleString()}</div>)}</div>diff --git a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/ModelChatPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/ModelChatPanel.tsxindex 3b6f209e5..c90b5e68f 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/ModelChatPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/ModelChatPanel.tsx@@ -30,12 +30,26 @@ interface ModelDecision {model: string;timestamp: string;content: string;- action?: 'long' | 'short' | 'hold' | 'close';+ type?: 'analyze' | 'evaluate' | 'signal';++ // For signal type+ direction?: 'long' | 'short' | 'hold';+ action?: 'long' | 'short' | 'hold';symbol?: string;confidence?: number;entry?: number;target?: number;stopLoss?: number;+ positionSize?: number;++ // For evaluate type+ riskScore?: number;+ recommendation?: 'increase' | 'reduce' | 'hold';++ // For analyze type+ sentiment?: 'bullish' | 'bearish' | 'neutral';+ support?: number;+ resistance?: number;}interface ModelChatPanelProps {@@ -100,12 +114,20 @@ export function ModelChatPanel({ teamId, refreshInterval = 5000 }: ModelChatPanereturn colors[hash % colors.length];};- const getActionColor = (action?: string) => {+ const getActionColor = (decision: ModelDecision) => {+ const action = decision.direction || decision.action;switch (action) {case 'long': return BLOOMBERG.GREEN;case 'short': return BLOOMBERG.RED;- case 'close': return BLOOMBERG.ORANGE;- default: return BLOOMBERG.GRAY;+ case 'hold': return BLOOMBERG.GRAY;+ default:+ // Check sentiment for analyze type+ if (decision.sentiment === 'bullish') return BLOOMBERG.GREEN;+ if (decision.sentiment === 'bearish') return BLOOMBERG.RED;+ // Check recommendation for evaluate type+ if (decision.recommendation === 'increase') return BLOOMBERG.GREEN;+ if (decision.recommendation === 'reduce') return BLOOMBERG.RED;+ return BLOOMBERG.GRAY;}};@@ -202,7 +224,7 @@ export function ModelChatPanel({ teamId, refreshInterval = 5000 }: ModelChatPanekey={`${decision.model}-${decision.timestamp}-${idx}`}decision={decision}modelColor={getModelColor(decision.model)}- actionColor={getActionColor(decision.action)}+ actionColor={getActionColor(decision)}formatTimestamp={formatTimestamp}/>))@@ -253,31 +275,49 @@ function DecisionCard({ decision, modelColor, actionColor, formatTimestamp }: De{decision.model.split(':')[1] || decision.model}</span>- {decision.action && (- <div style={{- background: `${actionColor}20`,- border: `1px solid ${actionColor}`,- borderRadius: '2px',- padding: '2px 6px',- display: 'flex',- alignItems: 'center',- gap: '3px'- }}>- {decision.action === 'long' ? (- <TrendingUp size={10} color={actionColor} />- ) : decision.action === 'short' ? (- <TrendingDown size={10} color={actionColor} />- ) : null}- <span style={{- color: actionColor,- fontSize: '8px',- fontWeight: '700',- letterSpacing: '0.5px'+ {/* Display action/sentiment/recommendation based on type */}+ {(() => {+ let label = '';+ let showIcon = true;++ if (decision.type === 'signal') {+ label = (decision.direction || decision.action || 'HOLD').toUpperCase();+ } else if (decision.type === 'analyze') {+ label = (decision.sentiment || 'NEUTRAL').toUpperCase();+ } else if (decision.type === 'evaluate') {+ label = (decision.recommendation || 'HOLD').toUpperCase();+ } else if (decision.action) {+ label = decision.action.toUpperCase();+ }++ if (!label) return null;++ return (+ <div style={{+ background: `${actionColor}20`,+ border: `1px solid ${actionColor}`,+ borderRadius: '2px',+ padding: '2px 6px',+ display: 'flex',+ alignItems: 'center',+ gap: '3px'}}>- {decision.action.toUpperCase()}- </span>- </div>- )}+ {(label === 'LONG' || label === 'BULLISH' || label === 'INCREASE') && showIcon ? (+ <TrendingUp size={10} color={actionColor} />+ ) : (label === 'SHORT' || label === 'BEARISH' || label === 'REDUCE') && showIcon ? (+ <TrendingDown size={10} color={actionColor} />+ ) : null}+ <span style={{+ color: actionColor,+ fontSize: '8px',+ fontWeight: '700',+ letterSpacing: '0.5px'+ }}>+ {label}+ </span>+ </div>+ );+ })()}{decision.symbol && (<span style={{@@ -310,43 +350,88 @@ function DecisionCard({ decision, modelColor, actionColor, formatTimestamp }: De{decision.content}</div>- {/* Trade Details */}- {(decision.entry || decision.target || decision.stopLoss) && (- <div style={{- marginTop: '6px',- paddingTop: '6px',- borderTop: `1px solid ${BLOOMBERG.BORDER}`,- display: 'flex',- gap: '12px',- fontSize: '9px',- fontFamily: '"IBM Plex Mono", monospace'- }}>- {decision.entry && (- <div>- <span style={{ color: BLOOMBERG.GRAY }}>ENTRY: </span>- <span style={{ color: BLOOMBERG.CYAN, fontWeight: '600' }}>${decision.entry}</span>- </div>- )}- {decision.target && (- <div>- <span style={{ color: BLOOMBERG.GRAY }}>TARGET: </span>- <span style={{ color: BLOOMBERG.GREEN, fontWeight: '600' }}>${decision.target}</span>- </div>- )}- {decision.stopLoss && (- <div>- <span style={{ color: BLOOMBERG.GRAY }}>STOP: </span>- <span style={{ color: BLOOMBERG.RED, fontWeight: '600' }}>${decision.stopLoss}</span>- </div>- )}- {decision.confidence && (- <div>- <span style={{ color: BLOOMBERG.GRAY }}>CONF: </span>- <span style={{ color: BLOOMBERG.YELLOW, fontWeight: '600' }}>{(decision.confidence * 100).toFixed(0)}%</span>- </div>- )}- </div>- )}+ {/* Decision Metadata */}+ {(() => {+ const hasSignalData = decision.entry || decision.target || decision.stopLoss || decision.confidence;+ const hasAnalysisData = decision.support || decision.resistance;+ const hasEvalData = decision.riskScore !== undefined;++ if (!hasSignalData && !hasAnalysisData && !hasEvalData) return null;++ return (+ <div style={{+ marginTop: '6px',+ paddingTop: '6px',+ borderTop: `1px solid ${BLOOMBERG.BORDER}`,+ display: 'flex',+ gap: '12px',+ fontSize: '9px',+ fontFamily: '"IBM Plex Mono", monospace',+ flexWrap: 'wrap'+ }}>+ {/* Signal type data */}+ {decision.entry && (+ <div>+ <span style={{ color: BLOOMBERG.GRAY }}>ENTRY: </span>+ <span style={{ color: BLOOMBERG.CYAN, fontWeight: '600' }}>${decision.entry.toLocaleString()}</span>+ </div>+ )}+ {decision.target && (+ <div>+ <span style={{ color: BLOOMBERG.GRAY }}>TARGET: </span>+ <span style={{ color: BLOOMBERG.GREEN, fontWeight: '600' }}>${decision.target.toLocaleString()}</span>+ </div>+ )}+ {decision.stopLoss && (+ <div>+ <span style={{ color: BLOOMBERG.GRAY }}>STOP: </span>+ <span style={{ color: BLOOMBERG.RED, fontWeight: '600' }}>${decision.stopLoss.toLocaleString()}</span>+ </div>+ )}+ {decision.positionSize && (+ <div>+ <span style={{ color: BLOOMBERG.GRAY }}>SIZE: </span>+ <span style={{ color: BLOOMBERG.PURPLE, fontWeight: '600' }}>{decision.positionSize.toFixed(1)}%</span>+ </div>+ )}++ {/* Analyze type data */}+ {decision.support && (+ <div>+ <span style={{ color: BLOOMBERG.GRAY }}>SUP: </span>+ <span style={{ color: BLOOMBERG.GREEN, fontWeight: '600' }}>${decision.support.toLocaleString()}</span>+ </div>+ )}+ {decision.resistance && (+ <div>+ <span style={{ color: BLOOMBERG.GRAY }}>RES: </span>+ <span style={{ color: BLOOMBERG.RED, fontWeight: '600' }}>${decision.resistance.toLocaleString()}</span>+ </div>+ )}++ {/* Evaluate type data */}+ {decision.riskScore !== undefined && (+ <div>+ <span style={{ color: BLOOMBERG.GRAY }}>RISK: </span>+ <span style={{+ color: decision.riskScore > 0.7 ? BLOOMBERG.RED : decision.riskScore < 0.3 ? BLOOMBERG.GREEN : BLOOMBERG.YELLOW,+ fontWeight: '600'+ }}>+ {(decision.riskScore * 10).toFixed(1)}/10+ </span>+ </div>+ )}++ {/* Confidence (all types) */}+ {decision.confidence && (+ <div>+ <span style={{ color: BLOOMBERG.GRAY }}>CONF: </span>+ <span style={{ color: BLOOMBERG.YELLOW, fontWeight: '600' }}>{(decision.confidence * 100).toFixed(0)}%</span>+ </div>+ )}+ </div>+ );+ })()}</div>);}diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChart.tsx b/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChart.tsxindex 6659a6392..228110814 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChart.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChart.tsx@@ -22,7 +22,7 @@ export function TradingChart({showVolume = true}: TradingChartProps) {const [selectedTimeframe, setSelectedTimeframe] = useState<Timeframe>(timeframe);- const { ohlcv, isLoading, error } = useOHLCV(symbol, selectedTimeframe, 200);+ const { ohlcv, isLoading, error } = useOHLCV(symbol, selectedTimeframe, 100); // Reduced from 200 to 100const timeframes: Timeframe[] = ['1m', '5m', '15m', '1h', '4h', '1d'];diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/VolumeProfile.tsx b/fincept-terminal-desktop/src/components/tabs/trading/charts/VolumeProfile.tsxindex 4a51fe73a..37b6f0716 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/charts/VolumeProfile.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/VolumeProfile.tsx@@ -19,7 +19,7 @@ export function VolumeProfile({symbol,timeframe = '1h',height = 400,- limit = 100+ limit = 500}: VolumeProfileProps) {const { volumeProfile, isLoading } = useVolumeProfile(symbol, timeframe, limit);@@ -43,53 +43,91 @@ export function VolumeProfile({current.volume > max.volume ? current : max);+ // Calculate total volume for display+ const totalVolume = volumeProfile.reduce((sum, p) => sum + p.volume, 0);++ // Format volume display+ const formatVolume = (vol: number) => {+ if (vol >= 1000000) return `${(vol / 1000000).toFixed(2)}M`;+ if (vol >= 1000) return `${(vol / 1000).toFixed(1)}K`;+ return vol.toFixed(0);+ };+return (- <div className="bg-black border border-gray-800 rounded p-2">- <div className="flex items-center justify-between mb-2 px-2">- <span className="text-xs text-gray-400">VOLUME PROFILE</span>- <span className="text-xs font-mono text-blue-400">- POC: ${poc.price.toFixed(2)}- </span>+ <div style={{ backgroundColor: '#000', border: '1px solid #2A2A2A', padding: '8px', height: '100%', display: 'flex', flexDirection: 'column', width: '100%', overflow: 'hidden' }}>+ {/* Header */}+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px', paddingBottom: '8px', borderBottom: '1px solid #2A2A2A', flexShrink: 0 }}>+ <span style={{ fontSize: '13px', color: '#FF8800', fontWeight: 700, fontFamily: 'monospace' }}>VOLUME BY PRICE</span>+ <div style={{ fontSize: '11px', color: '#FFF', fontFamily: 'monospace' }}>+ <span style={{ color: '#787878' }}>POC:</span> <span style={{ color: '#00E5FF', fontWeight: 700 }}>${poc.price.toLocaleString(undefined, { maximumFractionDigits: 2 })}</span>+ </div></div>- <ResponsiveContainer width="100%" height={height}>- <BarChart- data={volumeProfile}- layout="horizontal"- margin={{ top: 5, right: 5, left: 50, bottom: 20 }}- >- <XAxis- type="number"- stroke="#4b5563"- tick={{ fill: '#9ca3af', fontSize: 11 }}- tickFormatter={(value) => `${(value / 1000).toFixed(0)}K`}- />+ {/* Summary Stats */}+ <div style={{ display: 'flex', gap: '20px', marginBottom: '12px', fontSize: '12px', fontFamily: 'monospace', padding: '8px 12px', backgroundColor: '#0F0F0F', border: '1px solid #2A2A2A', flexShrink: 0 }}>+ <div style={{ flex: 1 }}>+ <div style={{ color: '#787878', fontSize: '9px', marginBottom: '2px' }}>TOTAL VOLUME</div>+ <div style={{ color: '#9D4EDD', fontWeight: 700, fontSize: '13px' }}>{formatVolume(totalVolume)}</div>+ </div>+ <div style={{ flex: 1 }}>+ <div style={{ color: '#787878', fontSize: '9px', marginBottom: '2px' }}>PRICE LEVELS</div>+ <div style={{ color: '#00E5FF', fontWeight: 700, fontSize: '13px' }}>{volumeProfile.length}</div>+ </div>+ <div style={{ flex: 1 }}>+ <div style={{ color: '#787878', fontSize: '9px', marginBottom: '2px' }}>TIMEFRAME</div>+ <div style={{ color: '#FFF', fontWeight: 700, fontSize: '13px' }}>{timeframe.toUpperCase()}</div>+ </div>+ </div>- <YAxis- type="number"- dataKey="price"- stroke="#4b5563"- tick={{ fill: '#9ca3af', fontSize: 11 }}- tickFormatter={(value) => `$${value.toFixed(0)}`}- domain={['auto', 'auto']}- />+ <div style={{ flex: 1, minHeight: 0 }}>+ <ResponsiveContainer width="100%" height="100%">+ <BarChart+ data={volumeProfile}+ layout="vertical"+ margin={{ top: 5, right: 5, left: 5, bottom: 5 }}+ barSize={12}+ barGap={2}+ >+ <XAxis+ type="number"+ stroke="#2A2A2A"+ tick={{ fill: '#FFFFFF', fontSize: 11, fontFamily: 'monospace' }}+ tickFormatter={(value) => {+ if (value >= 1000000) return `${(value / 1000000).toFixed(1)}M`;+ if (value >= 1000) return `${(value / 1000).toFixed(1)}K`;+ return value.toFixed(0);+ }}+ height={30}+ />++ <YAxis+ type="category"+ dataKey="price"+ stroke="#2A2A2A"+ orientation="right"+ tick={{ fill: '#FFFFFF', fontSize: 12, fontFamily: 'monospace' }}+ tickFormatter={(value) => `$${parseFloat(value).toLocaleString(undefined, { maximumFractionDigits: 0 })}`}+ width={90}+ /><TooltipcontentStyle={{- backgroundColor: '#1f2937',- border: '1px solid #374151',+ backgroundColor: '#0F0F0F',+ border: '2px solid #FF8800',borderRadius: '4px',- fontSize: '12px',+ fontSize: '13px',+ fontFamily: 'monospace',+ padding: '12px'}}- labelStyle={{ color: '#d1d5db' }}- itemStyle={{ color: '#d1d5db' }}+ labelStyle={{ color: '#FF8800', fontWeight: 700, fontSize: '14px' }}+ itemStyle={{ color: '#FFF', fontSize: '13px' }}formatter={(value: number, name: string) => {- if (name === 'buyVolume' || name === 'sellVolume') {- return value.toFixed(2);- }+ if (name === 'volume') return [value.toLocaleString(undefined, { maximumFractionDigits: 2 }), 'Volume'];+ if (name === 'buyVolume') return [value.toLocaleString(undefined, { maximumFractionDigits: 2 }), 'Buy Vol'];+ if (name === 'sellVolume') return [value.toLocaleString(undefined, { maximumFractionDigits: 2 }), 'Sell Vol'];return value.toFixed(2);}}- labelFormatter={(label) => `Price: $${label}`}+ labelFormatter={(label) => `Price: $${parseFloat(label).toLocaleString(undefined, { maximumFractionDigits: 2 })}`}/><Bar dataKey="volume" radius={[0, 2, 2, 0]}>@@ -111,26 +149,27 @@ export function VolumeProfile({return <Cell key={`cell-${index}`} fill={color} />;})}</Bar>- </BarChart>- </ResponsiveContainer>+ </BarChart>+ </ResponsiveContainer>+ </div>{/* Legend */}- <div className="flex items-center justify-center gap-4 mt-2 text-xs">- <div className="flex items-center gap-1">- <div className="w-3 h-3 bg-blue-500 rounded"></div>- <span className="text-gray-400">POC</span>+ <div style={{ display: 'flex', justifyContent: 'center', gap: '16px', marginTop: '12px', fontSize: '10px', fontFamily: 'monospace', paddingTop: '10px', borderTop: '1px solid #2A2A2A', flexShrink: 0 }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <div style={{ width: '10px', height: '10px', backgroundColor: '#3b82f6' }}></div>+ <span style={{ color: '#FFF', fontWeight: 600 }}>POC</span></div>- <div className="flex items-center gap-1">- <div className="w-3 h-3 bg-green-500 rounded"></div>- <span className="text-gray-400">Buy Heavy</span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <div style={{ width: '10px', height: '10px', backgroundColor: '#10b981' }}></div>+ <span style={{ color: '#FFF', fontWeight: 600 }}>BUY</span></div>- <div className="flex items-center gap-1">- <div className="w-3 h-3 bg-red-500 rounded"></div>- <span className="text-gray-400">Sell Heavy</span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <div style={{ width: '10px', height: '10px', backgroundColor: '#ef4444' }}></div>+ <span style={{ color: '#FFF', fontWeight: 600 }}>SELL</span></div>- <div className="flex items-center gap-1">- <div className="w-3 h-3 bg-gray-500 rounded"></div>- <span className="text-gray-400">Neutral</span>+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <div style={{ width: '10px', height: '10px', backgroundColor: '#6b7280' }}></div>+ <span style={{ color: '#FFF', fontWeight: 600 }}>NEUTRAL</span></div></div></div>diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/BasicOrderForm.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/BasicOrderForm.tsxindex 70210d832..1e8bc2692 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/BasicOrderForm.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/BasicOrderForm.tsx@@ -68,15 +68,18 @@ export function BasicOrderForm({// Handle quantity changeconst handleQuantityChange = (value: string) => {- // Allow only numbers and decimal point- if (/^\d*\.?\d*$/.test(value) || value === '') {+ // Allow empty string, numbers and decimal point+ // This allows users to clear the field and type new values freely+ if (value === '' || /^\d*\.?\d*$/.test(value)) {setQuantity(value);}};// Handle price changeconst handlePriceChange = (value: string) => {- if (/^\d*\.?\d*$/.test(value) || value === '') {+ // Allow empty string, numbers and decimal point+ // This allows users to clear the field and type new values freely+ if (value === '' || /^\d*\.?\d*$/.test(value)) {setPrice(value);}};diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/EnhancedOrderForm.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/EnhancedOrderForm.tsxindex 00365ed49..c9f19b439 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/EnhancedOrderForm.tsx+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/OrderForm/EnhancedOrderForm.tsx@@ -76,6 +76,17 @@ export function EnhancedOrderForm({ symbol, currentPrice, balance, onOrderPlacedreturn;}+ // Confirm before placing order+ const confirmMsg = `Place ${orderType.toUpperCase()} ${side.toUpperCase()} order?\n\n` ++ `Symbol: ${symbol}\n` ++ `Quantity: ${orderData.quantity}\n` ++ (orderType === 'limit' ? `Price: ${orderData.price}\n` : '') ++ `Total: ${((orderData.quantity || 0) * (orderData.price || currentPrice)).toFixed(2)} USD`;++ if (!confirm(confirmMsg)) {+ return; // User cancelled - don't call placeOrder+ }+try {await placeOrder(completeOrder);diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useMarketData.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useMarketData.tsindex 3424754ac..6529334b2 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useMarketData.ts+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useMarketData.ts@@ -11,6 +11,10 @@ import type { OHLCV, Timeframe, UnifiedOrderBook, UnifiedTicker } from '../types// OHLCV / CANDLESTICK DATA// ============================================================================+// Cache for OHLCV data+const ohlcvCache = new Map<string, { data: OHLCV[]; timestamp: number }>();+const OHLCV_CACHE_TTL = 30000; // 30 seconds+export function useOHLCV(symbol?: string, timeframe: Timeframe = '1h', limit: number = 100) {const { activeAdapter } = useBrokerContext();const [ohlcv, setOhlcv] = useState<OHLCV[]>([]);@@ -23,6 +27,15 @@ export function useOHLCV(symbol?: string, timeframe: Timeframe = '1h', limit: nureturn;}+ // Check cache+ const cacheKey = `${symbol}_${timeframe}_${limit}`;+ const cached = ohlcvCache.get(cacheKey);+ if (cached && Date.now() - cached.timestamp < OHLCV_CACHE_TTL) {+ setOhlcv(cached.data);+ setIsLoading(false);+ return;+ }+setIsLoading(true);setError(null);@@ -41,6 +54,9 @@ export function useOHLCV(symbol?: string, timeframe: Timeframe = '1h', limit: nu}));setOhlcv(normalized);++ // Update cache+ ohlcvCache.set(cacheKey, { data: normalized, timestamp: Date.now() });} catch (err) {const error = err as Error;console.error('[useOHLCV] Failed to fetch OHLCV:', error);diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrderExecution.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrderExecution.tsindex 8c0122b4f..5f8d41d24 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrderExecution.ts+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrderExecution.ts@@ -37,6 +37,12 @@ export function useOrderExecution(): UseOrderExecutionResult {setIsPlacing(true);setError(null);+ // Safety timeout - force reset after 10 seconds+ const timeoutId = setTimeout(() => {+ console.warn('[useOrderExecution] Force resetting isPlacing after timeout');+ setIsPlacing(false);+ }, 10000);+try {// Build CCXT-compatible paramsconst params: OrderParams = {};@@ -104,8 +110,10 @@ export function useOrderExecution(): UseOrderExecutionResult {);console.log('[useOrderExecution] Order placed:', result);+ clearTimeout(timeoutId);return result;} catch (err) {+ clearTimeout(timeoutId);const error = err as Error;console.error('[useOrderExecution] Order failed:', error);setError(error);diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrders.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrders.tsindex df7f45086..5b908b1e9 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrders.ts+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/useOrders.ts@@ -7,7 +7,7 @@ import { useState, useEffect, useCallback } from 'react';import { useBrokerContext } from '../../../../contexts/BrokerContext';import type { UnifiedOrder } from '../types';-export function useOrders(symbol?: string, autoRefresh: boolean = true, refreshInterval: number = 2000) {+export function useOrders(symbol?: string, autoRefresh: boolean = true, refreshInterval: number = 500) {const { activeAdapter } = useBrokerContext();const [openOrders, setOpenOrders] = useState<UnifiedOrder[]>([]);const [isLoading, setIsLoading] = useState(false);@@ -120,7 +120,7 @@ export function useCancelOrder() {}// Check if exchange supports cancel all- if (typeof (activeAdapter as any).cancelAllOrders !== 'function') {+ if (typeof activeAdapter.cancelAllOrders !== 'function') {throw new Error('This exchange does not support cancel all orders');}@@ -128,10 +128,11 @@ export function useCancelOrder() {setError(null);try {- await (activeAdapter as any).cancelAllOrders(symbol);+ await activeAdapter.cancelAllOrders(symbol);return true;} catch (err) {const error = err as Error;+ console.error('[useCancelOrder] Cancel all failed:', error);setError(error);throw error;} finally {diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/usePositions.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/usePositions.tsindex 89c7d3ee8..090c97b97 100644--- a/fincept-terminal-desktop/src/components/tabs/trading/hooks/usePositions.ts+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/usePositions.ts@@ -7,7 +7,7 @@ import { useState, useEffect, useCallback } from 'react';import { useBrokerContext } from '../../../../contexts/BrokerContext';import type { UnifiedPosition } from '../types';-export function usePositions(symbol?: string, autoRefresh: boolean = true, refreshInterval: number = 2000) {+export function usePositions(symbol?: string, autoRefresh: boolean = true, refreshInterval: number = 500) {const { activeAdapter, tradingMode } = useBrokerContext();const [positions, setPositions] = useState<UnifiedPosition[]>([]);// Start with loading false - only set true when actually fetching@@ -29,19 +29,13 @@ export function usePositions(symbol?: string, autoRefresh: boolean = true, refresetError(null);try {- // Fetch positions from adapter with reduced timeout- const timeoutPromise = new Promise((_, reject) =>- setTimeout(() => reject(new Error('Position fetch timeout after 15s')), 15000)- );-- const fetchPromise = activeAdapter.fetchPositions(symbol ? [symbol] : undefined);-- const rawPositions = await Promise.race([fetchPromise, timeoutPromise]) as any[];+ // Fetch positions from adapter (removed timeout - let it complete naturally)+ const rawPositions = await activeAdapter.fetchPositions(symbol ? [symbol] : undefined);// Normalize to unified formatconst normalized: UnifiedPosition[] = (rawPositions || []).map((pos: any) => ({symbol: pos.symbol,- side: pos.side === 'long' || pos.contracts > 0 ? 'long' : 'short',+ side: pos.side, // Use actual side from position, don't inferquantity: Math.abs(pos.contracts || pos.amount || 0),entryPrice: pos.entryPrice || pos.averagePrice || 0,currentPrice: pos.markPrice || pos.currentPrice || 0,@@ -107,6 +101,8 @@ export function useClosePosition() {setError(null);try {+ console.log(`[useClosePosition] Closing ${position.side} position: ${position.quantity} ${position.symbol}`);+// Create opposite order to close positionconst closeSide = position.side === 'long' ? 'sell' : 'buy';diff --git a/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts b/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.tsindex 5485e2279..cf2de09b0 100644--- a/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts+++ b/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts@@ -214,9 +214,12 @@ export class OrderMatchingEngine {const priceSnapshot = await this.fetchPriceSnapshot(symbol);// Check if order can be immediately filled+ // BUY limit: can fill if ask price is at or below limit price+ // SELL limit: can fill if bid price is at or above limit price+ // Also check last price for better fill opportunitiesconst canFillImmediately = side === 'buy'- ? priceSnapshot.ask <= limitPrice- : priceSnapshot.bid >= limitPrice;+ ? (priceSnapshot.ask <= limitPrice || priceSnapshot.last <= limitPrice)+ : (priceSnapshot.bid >= limitPrice || priceSnapshot.last >= limitPrice);// Handle Post-Onlyif (params?.postOnly && canFillImmediately) {@@ -235,10 +238,10 @@ export class OrderMatchingEngine {if (canFillImmediately) {return await this.executeLimitOrder(orderId, symbol, side, amount, limitPrice, params);} else {- await paperTradingDatabase.updateOrder(orderId, { status: 'canceled' });+ await paperTradingDatabase.updateOrder(orderId, { status: 'cancelled' });return {success: false,- order: this.createOrderObject(orderId, symbol, 'limit', side, amount, limitPrice, params, 'canceled'),+ order: this.createOrderObject(orderId, symbol, 'limit', side, amount, limitPrice, params, 'cancelled'),trades: [],balance: 0,error: 'IOC order could not be filled immediately',@@ -251,10 +254,10 @@ export class OrderMatchingEngine {if (canFillImmediately) {return await this.executeLimitOrder(orderId, symbol, side, amount, limitPrice, params);} else {- await paperTradingDatabase.updateOrder(orderId, { status: 'canceled' });+ await paperTradingDatabase.updateOrder(orderId, { status: 'cancelled' });return {success: false,- order: this.createOrderObject(orderId, symbol, 'limit', side, amount, limitPrice, params, 'canceled'),+ order: this.createOrderObject(orderId, symbol, 'limit', side, amount, limitPrice, params, 'cancelled'),trades: [],balance: 0,error: 'FOK order could not be fully filled',@@ -568,13 +571,18 @@ export class OrderMatchingEngine {// Check liquidations firstawait this.checkPositionLiquidations(order.symbol, priceSnapshot.last);- // Check limit orders+ // Check limit orders - IMPROVED LOGICif (order.type === 'limit' && order.status === 'pending') {+ // BUY limit: fills when ask price drops to or below limit price+ // SELL limit: fills when bid price rises to or above limit price+ // Also check last price as a fallback for better fill opportunities+ const limitPrice = order.price || 0;const canFill = order.side === 'buy'- ? priceSnapshot.ask <= (order.price || 0)- : priceSnapshot.bid >= (order.price || 0);+ ? (priceSnapshot.ask <= limitPrice || priceSnapshot.last <= limitPrice)+ : (priceSnapshot.bid >= limitPrice || priceSnapshot.last >= limitPrice);if (canFill) {+ console.log(`[OrderMatching] Limit order ${order.id} can fill - ${order.side} @ ${limitPrice}, market: bid=${priceSnapshot.bid}, ask=${priceSnapshot.ask}, last=${priceSnapshot.last}`);await this.executeLimitOrder(order.id, order.symbol, order.side as OrderSide, order.amount, order.price!, {leverage: order.leverage,marginMode: order.marginMode as any,@@ -622,6 +630,7 @@ export class OrderMatchingEngine {* Cancel an order*/async cancelOrder(orderId: string): Promise<PaperTradingOrder> {+ console.log(`[OrderMatching] Attempting to cancel order ${orderId}`);const order = await paperTradingDatabase.getOrder(orderId);if (!order) {throw new Error(`Order ${orderId} not found`);@@ -631,7 +640,13 @@ export class OrderMatchingEngine {throw new Error(`Cannot cancel filled order ${orderId}`);}- await paperTradingDatabase.updateOrder(orderId, { status: 'canceled' });+ if (order.status === 'cancelled') {+ console.warn(`[OrderMatching] Order ${orderId} already cancelled`);+ return order;+ }++ await paperTradingDatabase.updateOrder(orderId, { status: 'cancelled' });+ console.log(`[OrderMatching] Order ${orderId} cancelled successfully`);const updatedOrder = await paperTradingDatabase.getOrder(orderId);return updatedOrder!;@@ -647,14 +662,14 @@ export class OrderMatchingEngine {? pendingOrders.filter(o => o.symbol === symbol): pendingOrders;- const canceledOrders: PaperTradingOrder[] = [];+ const cancelledOrders: PaperTradingOrder[] = [];for (const order of ordersToCancel) {- await paperTradingDatabase.updateOrder(order.id, { status: 'canceled' });+ await paperTradingDatabase.updateOrder(order.id, { status: 'cancelled' });const updated = await paperTradingDatabase.getOrder(order.id);- if (updated) canceledOrders.push(updated);+ if (updated) cancelledOrders.push(updated);}- return canceledOrders;+ return cancelledOrders;}// ============================================================================diff --git a/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts b/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.tsindex e338eea7d..9f5ad9784 100644--- a/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts+++ b/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts@@ -25,6 +25,7 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {private balanceManager: PaperTradingBalance;private matchingEngine: OrderMatchingEngine;private initialized: boolean = false;+ // NO CACHING - Real-time data onlyconstructor(config: ExchangeConfig & { paperTradingConfig: PaperTradingConfig; realAdapter: IExchangeAdapter }) {// Initialize base with real exchange name (CCXT doesn't support "_paper" suffix)@@ -66,10 +67,11 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {await this.initializePortfolio();console.log('[PaperTradingAdapter] Portfolio initialized');- // Start order monitoring+ // Start order monitoring - INCREASED FREQUENCY for better limit order executionif (this.paperConfig.enableRealtimeUpdates !== false) {console.log('[PaperTradingAdapter] Starting order monitoring...');- this.matchingEngine.startMonitoring(this.paperConfig.priceUpdateInterval || 1000);+ // Reduced from 1000ms to 200ms for more responsive limit order fills+ this.matchingEngine.startMonitoring(this.paperConfig.priceUpdateInterval || 200);}this._isConnected = true;@@ -255,46 +257,18 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {throw new Error('Paper trading adapter not initialized. Call connect() first.');}- // FORCE FRESH DB READ - no cachingconst positions = await paperTradingDatabase.getPortfolioPositions(this.paperConfig.portfolioId, 'open');- // Update positions with current prices - PARALLEL with timeout per position- const updatePromises = positions.map(async (p) => {- try {- // Add timeout per ticker fetch (10 seconds max)- const tickerPromise = this.realAdapter.fetchTicker(p.symbol);- const timeoutPromise = new Promise((_, reject) =>- setTimeout(() => reject(new Error('Ticker timeout')), 10000)- );-- const ticker = await Promise.race([tickerPromise, timeoutPromise]) as any;- const currentPrice = ticker.last || ticker.close || p.currentPrice || p.entryPrice;-- const unrealizedPnl = p.side === 'long'- ? (currentPrice - p.entryPrice) * p.quantity- : (p.entryPrice - currentPrice) * p.quantity;-- await paperTradingDatabase.updatePosition(p.id, {- currentPrice,- unrealizedPnl,- });-- p.currentPrice = currentPrice;- p.unrealizedPnl = unrealizedPnl;- } catch (err) {- // Silently keep existing price if fetch fails- p.currentPrice = p.currentPrice || p.entryPrice;- p.unrealizedPnl = p.unrealizedPnl || 0;- }- });+ // Update PnL with current market prices+ for (const p of positions) {+ const currentPrice = p.currentPrice || p.entryPrice;+ const unrealizedPnl = p.side === 'long'+ ? (currentPrice - p.entryPrice) * p.quantity+ : (p.entryPrice - currentPrice) * p.quantity;- // Wait for all updates with overall timeout- await Promise.race([- Promise.all(updatePromises),- new Promise((_, reject) => setTimeout(() => reject(new Error('All updates timeout')), 20000))- ]).catch(() => {- // Silently continue if some updates timeout- });+ p.currentPrice = currentPrice;+ p.unrealizedPnl = unrealizedPnl;+ }// Convert to CCXT Position formatconst ccxtPositions: Position[] = positions@@ -493,14 +467,13 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {async fetchOpenOrders(symbol?: string): Promise<Order[]> {const orders = await paperTradingDatabase.getPortfolioOrders(this.paperConfig.portfolioId);-- const openOrders = orders.filter(o => ['pending', 'triggered', 'partial'].includes(o.status));+ const openOrders = orders.filter(o => ['pending', 'triggered', 'partial'].includes(o.status)) as Order[];if (symbol) {- return openOrders.filter(o => o.symbol === symbol) as Order[];+ return openOrders.filter(o => o.symbol === symbol);}- return openOrders as Order[];+ return openOrders;}async fetchClosedOrders(symbol?: string, limit?: number): Promise<Order[]> {diff --git a/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts b/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.tsindex ffd811aca..c36fe82c0 100644--- a/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts+++ b/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts@@ -114,6 +114,14 @@ export class PaperTradingBalance {/*** Create or update position after order fill+ *+ * Position Logic:+ * - BUY order creates/adds to LONG position OR closes SHORT position+ * - SELL order creates/adds to SHORT position OR closes LONG position+ *+ * When you already have a position:+ * - If you have a LONG position and SELL, it CLOSES the long (not creates short)+ * - If you have a SHORT position and BUY, it CLOSES the short (not creates long)*/async updatePositionAfterFill(portfolioId: string,@@ -125,11 +133,11 @@ export class PaperTradingBalance {marginMode: 'cross' | 'isolated',reduceOnly?: boolean): Promise<PaperTradingPosition> {- // Determine position side from order side- const positionSide = side === 'buy' ? 'long' : 'short';- const oppositePositionSide = positionSide === 'long' ? 'short' : 'long';+ console.log(`[PaperTradingBalance] Processing ${side.toUpperCase()} order for ${fillQuantity} ${symbol} @ ${fillPrice}`);- // Check for OPPOSITE position first (for closing)+ // CRITICAL FIX: Check for OPPOSITE positions to close+ // BUY closes SHORT, SELL closes LONG+ const oppositePositionSide = side === 'buy' ? 'short' : 'long';const oppositePosition = await paperTradingDatabase.getPositionBySymbolAndSide(portfolioId, symbol, oppositePositionSide, 'open');// If reduceOnly and no opposite position, reject@@ -187,8 +195,11 @@ export class PaperTradingBalance {quantity: 0});+ // The excess creates a NEW position in the ORIGINAL order directionconst excessQuantity = fillQuantity - oppositePosition.quantity;- return await this.createNewPosition(portfolioId, symbol, positionSide, fillPrice, excessQuantity, leverage, marginMode);+ const newPositionSide = side === 'buy' ? 'long' : 'short';+ console.log(`[PaperTradingBalance] Creating ${newPositionSide} position with excess quantity ${excessQuantity}`);+ return await this.createNewPosition(portfolioId, symbol, newPositionSide, fillPrice, excessQuantity, leverage, marginMode);}const updatedPosition = await paperTradingDatabase.getPosition(oppositePosition.id);@@ -196,15 +207,23 @@ export class PaperTradingBalance {return updatedPosition;}- // Check for existing position WITH THE SAME SIDE (hedging mode)- const existingPosition = await paperTradingDatabase.getPositionBySymbolAndSide(portfolioId, symbol, positionSide, 'open');+ // NO opposite position found - CREATE OR ADD to position with matching side+ // BUY order creates/adds to LONG position+ // SELL order creates/adds to SHORT position+ const newPositionSide = side === 'buy' ? 'long' : 'short';++ console.log(`[PaperTradingBalance] No opposite position found, checking for same-side position...`);++ // Check for existing position WITH THE SAME SIDE (for adding to existing position)+ const existingPosition = await paperTradingDatabase.getPositionBySymbolAndSide(portfolioId, symbol, newPositionSide, 'open');if (!existingPosition) {// Create new position- return await this.createNewPosition(portfolioId, symbol, positionSide, fillPrice, fillQuantity, leverage, marginMode);+ console.log(`[PaperTradingBalance] Creating new ${newPositionSide.toUpperCase()} position`);+ return await this.createNewPosition(portfolioId, symbol, newPositionSide, fillPrice, fillQuantity, leverage, marginMode);} else {// Position exists with same side - ADD to position (VWAP averaging)- console.log(`[PaperTradingBalance] Adding to existing ${positionSide} position for ${symbol}`);+ console.log(`[PaperTradingBalance] Adding to existing ${newPositionSide} position for ${symbol}`);console.log(` Existing: ${existingPosition.quantity} @ ${existingPosition.entryPrice}`);console.log(` Adding: ${fillQuantity} @ ${fillPrice}`);@@ -216,7 +235,7 @@ export class PaperTradingBalance {console.log(` New position: ${totalQuantity} @ ${newEntryPrice}`);const liquidationPrice = this.calculateLiquidationPrice(- positionSide,+ newPositionSide,newEntryPrice,leverage,totalQuantitydiff --git a/fincept-terminal-desktop/src/services/alphaArenaService.ts b/fincept-terminal-desktop/src/services/alphaArenaService.tsnew file mode 100644index 000000000..24d17a6e2--- /dev/null+++ b/fincept-terminal-desktop/src/services/alphaArenaService.ts@@ -0,0 +1,473 @@+/**+ * Alpha Arena Service+ * TypeScript service for NOF1-style AI trading competition+ */++import { invoke } from '@tauri-apps/api/core';+import { sqliteService } from './sqliteService';++export interface CompetitionModel {+ name: string;+ provider: string;+ model_id: string;+}++export interface LeaderboardEntry {+ model: string;+ pnl: number;+ return_pct: number;+ portfolio_value: number;+ cash: number;+ trades: number;+ positions: number;+}++export interface ModelDecision {+ model: string;+ timestamp: string;+ action: string;+ symbol: string;+ confidence: number;+ reasoning: string;+ quantity?: number;+ trade_executed?: any;+}++export interface CompetitionResult {+ success: boolean;+ data?: any;+ error?: string;+}++export interface ConfiguredLLM {+ id: string;+ provider: string;+ model_id: string;+ display_name: string;+ api_key_available: boolean;+}++export const alphaArenaService = {+ /**+ * Get all configured LLMs from database that can be used in Arena+ */+ async getConfiguredLLMs(): Promise<ConfiguredLLM[]> {+ try {+ console.log('[Service] getConfiguredLLMs called');++ const llmConfigs = await sqliteService.getLLMConfigs();+ const modelConfigs = await sqliteService.getLLMModelConfigs();+ const apiKeys = await sqliteService.getAllApiKeys();++ const result: ConfiguredLLM[] = [];++ // Add models from legacy llm_configs table+ for (const config of llmConfigs) {+ const hasApiKey = !!(config.api_key ||+ (config.provider === 'openai' && apiKeys['OPENAI_API_KEY']) ||+ (config.provider === 'google' && apiKeys['GOOGLE_API_KEY']));++ result.push({+ id: `legacy_${config.provider}`,+ provider: config.provider,+ model_id: config.model,+ display_name: `${config.provider.toUpperCase()}: ${config.model}`,+ api_key_available: hasApiKey+ });+ }++ // Add models from new llm_model_configs table+ for (const config of modelConfigs) {+ result.push({+ id: config.id,+ provider: config.provider,+ model_id: config.model_id,+ display_name: config.display_name || `${config.provider.toUpperCase()}: ${config.model_id}`,+ api_key_available: !!config.api_key+ });+ }++ console.log('[Service] Configured LLMs:', result);+ return result;+ } catch (error) {+ console.error('[Service] getConfiguredLLMs error:', error);+ return [];+ }+ },++ /**+ * Get API keys map for all configured providers+ */+ async getApiKeysMap(): Promise<Record<string, string>> {+ try {+ const apiKeys = await sqliteService.getAllApiKeys();+ const llmConfigs = await sqliteService.getLLMConfigs();+ const modelConfigs = await sqliteService.getLLMModelConfigs();++ const result: Record<string, string> = {};++ // From predefined API keys+ if (apiKeys['OPENAI_API_KEY']) {+ result['OPENAI_API_KEY'] = apiKeys['OPENAI_API_KEY'];+ }+ if (apiKeys['ANTHROPIC_API_KEY']) {+ result['ANTHROPIC_API_KEY'] = apiKeys['ANTHROPIC_API_KEY'];+ }++ // From legacy LLM configs+ for (const config of llmConfigs) {+ if (config.api_key) {+ const keyName = `${config.provider.toUpperCase()}_API_KEY`;+ if (!result[keyName]) {+ result[keyName] = config.api_key;+ }+ }+ }++ // From new model configs+ for (const config of modelConfigs) {+ if (config.api_key) {+ const keyName = `${config.provider.toUpperCase()}_API_KEY`;+ if (!result[keyName]) {+ result[keyName] = config.api_key;+ }+ }+ }++ return result;+ } catch (error) {+ console.error('[Service] getApiKeysMap error:', error);+ return {};+ }+ },++ /**+ * Create a new Alpha Arena competition+ */+ async createCompetition(+ name: string,+ models: CompetitionModel[],+ symbol: string = "BTC/USD",+ mode: string = "baseline",+ initialCapital: number = 10000,+ customPrompt?: string+ ): Promise<CompetitionResult> {+ try {+ console.log('[Service] createCompetition called with:', { name, models, symbol, mode });++ // Validate models+ if (!models || models.length === 0) {+ return {+ success: false,+ error: 'No models provided. Please select at least one AI model.'+ };+ }++ // Fetch API keys from all sources+ console.log('[Service] Fetching API keys from database...');+ const apiKeysMap = await this.getApiKeysMap();++ console.log('[Service] API keys prepared:', Object.keys(apiKeysMap));++ // Build models config with API keys+ const modelsWithKeys = [];+ const missingKeys: string[] = [];++ for (const model of models) {+ const provider = model.provider.toLowerCase();+ const possibleKeys = [+ `${provider}_API_KEY`.toUpperCase(),+ `${provider === 'gemini' ? 'GOOGLE' : provider}_API_KEY`.toUpperCase(),+ `${provider === 'google' ? 'GOOGLE' : provider}_API_KEY`.toUpperCase()+ ];++ let apiKey = '';+ for (const keyName of possibleKeys) {+ if (apiKeysMap[keyName] && apiKeysMap[keyName].trim() !== '') {+ apiKey = apiKeysMap[keyName];+ break;+ }+ }++ if (!apiKey) {+ missingKeys.push(`${model.provider} (for ${model.name})`);+ }++ modelsWithKeys.push({+ name: model.name,+ provider: provider,+ model_id: model.model_id,+ api_key: apiKey+ });+ }++ if (missingKeys.length > 0) {+ return {+ success: false,+ error: `Missing API keys for: ${missingKeys.join(', ')}. Please configure them in Settings → LLM Configuration.`+ };+ }++ console.log('[Service] All required API keys present. Creating competition...');++ // Generate competition ID+ const competitionId = `comp_${Date.now()}_${Math.random().toString(36).substring(7)}`;++ // Build config for new Python service+ const config = {+ competition_id: competitionId,+ competition_name: name,+ models: modelsWithKeys,+ symbols: [symbol],+ initial_capital: initialCapital,+ exchange_id: "kraken",+ custom_prompt: customPrompt || undefined+ };++ const configJson = JSON.stringify(config);+ console.log('[Service] Competition config:', configJson);++ // Add timeout to prevent indefinite hanging+ const CREATE_TIMEOUT = 60000; // 60 seconds+ const competitionPromise = invoke('create_alpha_competition', {+ configJson+ }) as Promise<any>;++ const timeoutPromise = new Promise<any>((_, reject) => {+ setTimeout(() => {+ reject(new Error('Competition creation timed out after 60 seconds. The AI models may be taking too long to initialize. Please try again with fewer models.'));+ }, CREATE_TIMEOUT);+ });++ const result = await Promise.race([competitionPromise, timeoutPromise]);++ console.log('[Service] create_alpha_competition response:', result);++ // If successful, persist to database+ if (result.success) {+ try {+ await sqliteService.createAlphaCompetition({+ id: competitionId,+ name,+ symbol,+ mode: mode as any,+ status: 'created',+ cycle_count: 0,+ cycle_interval_seconds: 150,+ initial_capital: initialCapital+ });++ // Initialize model states in database+ for (const model of models) {+ await sqliteService.saveAlphaModelState({+ id: `${competitionId}_${model.name}`,+ competition_id: competitionId,+ model_name: model.name,+ provider: model.provider,+ model_id: model.model_id,+ capital: initialCapital,+ positions_json: '{}',+ trades_count: 0,+ total_pnl: 0,+ portfolio_value: initialCapital+ });+ }++ console.log('[Service] Competition persisted to database');+ } catch (dbError) {+ console.error('[Service] Failed to persist to database:', dbError);+ }+ }++ return {+ success: result.success,+ data: { competition_id: competitionId, ...result },+ error: result.error+ };+ } catch (error) {+ console.error('[Service] createCompetition error:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error)+ };+ }+ },++ /**+ * Run a single competition cycle+ */+ async runCompetitionCycle(competitionId: string): Promise<CompetitionResult> {+ try {+ const result = await invoke('run_alpha_cycle', { competitionId }) as any;++ // Update cycle count in database if successful+ if (result.success && result.cycle_number) {+ await sqliteService.updateAlphaCompetition(competitionId, {+ cycle_count: result.cycle_number+ });+ }++ return {+ success: result.success,+ data: result,+ error: result.error+ };+ } catch (error) {+ console.error('[Service] runCompetitionCycle error:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error)+ };+ }+ },++ /**+ * Start competition (runs one cycle immediately)+ */+ async startCompetition(competitionId: string): Promise<CompetitionResult> {+ try {+ console.log('[Service] startCompetition called with ID:', competitionId);++ // Update status to running in database+ await sqliteService.updateAlphaCompetition(competitionId, {+ status: 'running',+ started_at: new Date().toISOString()+ });++ const result = await invoke('start_alpha_competition', { competitionId }) as CompetitionResult;+ console.log('[Service] start_alpha_competition response:', result);++ // Save performance snapshots if available+ if (result.success && result.data?.cycle_result) {+ const cycleNumber = result.data.cycle_result.cycle || 0;++ // Update cycle count+ await sqliteService.updateAlphaCompetition(competitionId, {+ cycle_count: cycleNumber+ });++ // TODO: Save performance snapshots from cycle result+ }++ return result as CompetitionResult;+ } catch (error) {+ console.error('[Service] startCompetition error:', error);+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error)+ };+ }+ },++ /**+ * Get current leaderboard+ */+ async getLeaderboard(competitionId: string): Promise<LeaderboardEntry[]> {+ try {+ const result: any = await invoke('get_alpha_leaderboard', { competitionId });+ if (result.success && result.leaderboard) {+ // Map backend format to frontend format+ return result.leaderboard.map((entry: any) => ({+ model: entry.model_name || entry.model,+ pnl: entry.total_pnl || 0,+ return_pct: entry.return_pct || 0,+ portfolio_value: entry.portfolio_value || 0,+ cash: entry.cash || 0,+ trades: entry.trades_count || 0,+ positions: entry.positions_count || 0+ }));+ }+ return [];+ } catch (error) {+ console.error('Failed to get leaderboard:', error);+ return [];+ }+ },++ /**+ * Get model decisions/chat feed+ */+ async getModelDecisions(competitionId: string, modelName?: string): Promise<ModelDecision[]> {+ try {+ const result: any = await invoke('get_alpha_model_decisions', {+ competitionId,+ modelName: modelName || null+ });+ if (result.success && result.decisions) {+ // Map backend format to frontend format+ return result.decisions.map((decision: any) => ({+ model: decision.model_name,+ timestamp: new Date(decision.timestamp).toISOString(),+ action: decision.action,+ symbol: decision.symbol,+ confidence: decision.confidence || 0,+ reasoning: decision.reasoning || '',+ quantity: decision.quantity,+ trade_executed: decision.trade_executed+ }));+ }+ return [];+ } catch (error) {+ console.error('Failed to get model decisions:', error);+ return [];+ }+ },++ /**+ * Stop active competition+ */+ async stopCompetition(competitionId: string): Promise<CompetitionResult> {+ try {+ // Update status to paused in database+ await sqliteService.updateAlphaCompetition(competitionId, {+ status: 'paused'+ });++ const result = await invoke('stop_alpha_competition', { competitionId }) as CompetitionResult;+ return result;+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : String(error)+ };+ }+ },++ /**+ * Parse text and remove markdown formatting (** bold, etc.)+ */+ cleanText(text: string): string {+ if (!text) return '';+ // Remove ** bold markers+ text = text.replace(/\*\*/g, '');+ // Remove * italic markers+ text = text.replace(/\*/g, '');+ // Remove ``` code blocks+ text = text.replace(/```[\s\S]*?```/g, '');+ return text.trim();+ },++ /**+ * Parse JSON response, handling markdown code blocks+ */+ parseJsonResponse(response: string): any {+ try {+ let cleaned = response.trim();++ // Remove markdown code blocks+ if (cleaned.startsWith('```')) {+ const parts = cleaned.split('```');+ cleaned = parts[1] || parts[0];+ if (cleaned.startsWith('json')) {+ cleaned = cleaned.substring(4);+ }+ cleaned = cleaned.trim();+ }++ return JSON.parse(cleaned);+ } catch (error) {+ console.error('Failed to parse JSON:', error, response);+ return null;+ }+ }+};diff --git a/fincept-terminal-desktop/src/services/krakenPriceFeed.ts b/fincept-terminal-desktop/src/services/krakenPriceFeed.tsnew file mode 100644index 000000000..b34659d64--- /dev/null+++ b/fincept-terminal-desktop/src/services/krakenPriceFeed.ts@@ -0,0 +1,101 @@+/**+ * Kraken WebSocket Price Feed+ * Simple real-time price updates for NOF1 Alpha Arena style trading+ */++import ccxt from 'ccxt';++class KrakenPriceFeed {+ private exchange: any = null;+ private subscribers: Map<string, Set<(price: number) => void>> = new Map();+ private currentPrices: Map<string, number> = new Map();+ private isConnected = false;++ async connect() {+ if (this.isConnected) return;++ try {+ // Use CCXT Pro for WebSocket+ const kraken = new (ccxt.pro as any).kraken();+ this.exchange = kraken;+ this.isConnected = true;+ console.log('[KrakenPriceFeed] Connected to Kraken WebSocket');+ } catch (error) {+ console.error('[KrakenPriceFeed] Failed to connect:', error);+ throw error;+ }+ }++ async subscribe(symbol: string, callback: (price: number) => void) {+ if (!this.isConnected) {+ await this.connect();+ }++ // Add subscriber+ if (!this.subscribers.has(symbol)) {+ this.subscribers.set(symbol, new Set());+ this.startWatching(symbol);+ }+ this.subscribers.get(symbol)!.add(callback);++ // Return current price immediately if available+ const currentPrice = this.currentPrices.get(symbol);+ if (currentPrice) {+ callback(currentPrice);+ }+ }++ unsubscribe(symbol: string, callback: (price: number) => void) {+ const subs = this.subscribers.get(symbol);+ if (subs) {+ subs.delete(callback);+ if (subs.size === 0) {+ this.subscribers.delete(symbol);+ }+ }+ }++ private async startWatching(symbol: string) {+ if (!this.exchange) return;++ const watch = async () => {+ while (this.subscribers.has(symbol)) {+ try {+ const ticker = await this.exchange.watchTicker(symbol);+ const price = ticker.last;++ if (price) {+ this.currentPrices.set(symbol, price);++ // Notify all subscribers+ const subs = this.subscribers.get(symbol);+ if (subs) {+ subs.forEach(callback => callback(price));+ }+ }+ } catch (error) {+ console.error(`[KrakenPriceFeed] Error watching ${symbol}:`, error);+ await new Promise(resolve => setTimeout(resolve, 5000)); // Retry after 5s+ }+ }+ };++ watch();+ }++ getCurrentPrice(symbol: string): number | null {+ return this.currentPrices.get(symbol) || null;+ }++ async disconnect() {+ if (this.exchange) {+ await this.exchange.close();+ this.isConnected = false;+ this.subscribers.clear();+ console.log('[KrakenPriceFeed] Disconnected');+ }+ }+}++// Singleton instance+export const krakenPriceFeed = new KrakenPriceFeed();diff --git a/fincept-terminal-desktop/src/services/sqliteService.ts b/fincept-terminal-desktop/src/services/sqliteService.tsindex 75acc6b9d..69d0cbee8 100644--- a/fincept-terminal-desktop/src/services/sqliteService.ts+++ b/fincept-terminal-desktop/src/services/sqliteService.ts@@ -59,6 +59,20 @@ export interface LLMConfig {updated_at?: string;}+// New interface for individual model configurations (multiple models per provider)+export interface LLMModelConfig {+ id: string;+ provider: string;+ model_id: string;+ display_name: string;+ api_key?: string;+ base_url?: string;+ is_enabled: boolean;+ is_default: boolean;+ created_at?: string;+ updated_at?: string;+}+export interface LLMGlobalSettings {temperature: number;max_tokens: number;@@ -212,6 +226,82 @@ export interface OptimizationRun {duration_seconds?: number;}+// ==================== ALPHA ARENA INTERFACES ====================++export interface AlphaCompetition {+ id: string;+ name: string;+ symbol: string;+ mode: 'baseline' | 'monk' | 'situational' | 'max_leverage';+ status: 'created' | 'running' | 'paused' | 'completed';+ cycle_count: number;+ cycle_interval_seconds: number;+ initial_capital: number;+ created_at: string;+ started_at?: string;+ ended_at?: string;+ updated_at: string;+}++export interface AlphaModelState {+ id: string;+ competition_id: string;+ model_name: string;+ provider: string;+ model_id: string;+ capital: number;+ positions_json: string;+ trades_count: number;+ total_pnl: number;+ portfolio_value: number;+ created_at: string;+ updated_at: string;+}++export interface AlphaPriceHistory {+ id: string;+ competition_id: string;+ symbol: string;+ price: number;+ bid?: number;+ ask?: number;+ volume_24h?: number;+ high_24h?: number;+ low_24h?: number;+ timestamp: string;+}++export interface AlphaDecisionLog {+ id: string;+ competition_id: string;+ model_name: string;+ cycle_number: number;+ action: 'buy' | 'sell' | 'hold';+ symbol: string;+ quantity?: number;+ confidence: number;+ reasoning: string;+ trade_executed: string;+ price_at_decision: number;+ portfolio_value_before: number;+ portfolio_value_after: number;+ timestamp: string;+}++export interface AlphaPerformanceSnapshot {+ 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;+}+class SQLiteService {private db: Database | null = null;private initPromise: Promise<void> | null = null;@@ -289,6 +379,23 @@ class SQLiteService {system_prompt TEXT DEFAULT '')`,+ // LLM model configurations table (supports multiple models per provider)+ `CREATE TABLE IF NOT EXISTS llm_model_configs (+ id TEXT PRIMARY KEY,+ provider TEXT NOT NULL,+ model_id TEXT NOT NULL,+ display_name TEXT NOT NULL,+ api_key TEXT,+ base_url TEXT,+ is_enabled INTEGER DEFAULT 1,+ is_default INTEGER DEFAULT 0,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ )`,++ `CREATE INDEX IF NOT EXISTS idx_llm_model_configs_provider ON llm_model_configs(provider)`,+ `CREATE INDEX IF NOT EXISTS idx_llm_model_configs_enabled ON llm_model_configs(is_enabled)`,+// Chat sessions table`CREATE TABLE IF NOT EXISTS chat_sessions (session_uuid TEXT PRIMARY KEY,@@ -638,6 +745,112 @@ class SQLiteService {`CREATE INDEX IF NOT EXISTS idx_optimization_runs_provider ON optimization_runs(provider_name)`,`CREATE INDEX IF NOT EXISTS idx_optimization_runs_status ON optimization_runs(status)`,+ // ==================== ALPHA ARENA TABLES ====================++ // Alpha Arena competitions table+ `CREATE TABLE IF NOT EXISTS alpha_competitions (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ symbol TEXT NOT NULL,+ mode TEXT NOT NULL CHECK (mode IN ('baseline', 'monk', 'situational', 'max_leverage')),+ status TEXT NOT NULL CHECK (status IN ('created', 'running', 'paused', 'completed')) DEFAULT 'created',+ cycle_count INTEGER DEFAULT 0,+ cycle_interval_seconds INTEGER DEFAULT 150,+ initial_capital REAL DEFAULT 10000,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ started_at TEXT,+ ended_at TEXT,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP+ )`,++ `CREATE INDEX IF NOT EXISTS idx_alpha_competitions_status ON alpha_competitions(status)`,+ `CREATE INDEX IF NOT EXISTS idx_alpha_competitions_created ON alpha_competitions(created_at DESC)`,++ // Alpha Arena model states table (persistent model portfolios)+ `CREATE TABLE IF NOT EXISTS alpha_model_states (+ id TEXT PRIMARY KEY,+ competition_id TEXT NOT NULL,+ model_name TEXT NOT NULL,+ provider TEXT NOT NULL,+ model_id TEXT NOT NULL,+ capital REAL NOT NULL,+ positions_json TEXT NOT NULL DEFAULT '{}',+ trades_count INTEGER DEFAULT 0,+ total_pnl REAL DEFAULT 0,+ portfolio_value REAL NOT NULL,+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY (competition_id) REFERENCES alpha_competitions(id) ON DELETE CASCADE,+ UNIQUE(competition_id, model_name)+ )`,++ `CREATE INDEX IF NOT EXISTS idx_alpha_model_states_competition ON alpha_model_states(competition_id)`,+ `CREATE INDEX IF NOT EXISTS idx_alpha_model_states_model ON alpha_model_states(model_name)`,++ // Alpha Arena price history table (for charting)+ `CREATE TABLE IF NOT EXISTS alpha_price_history (+ id TEXT PRIMARY KEY,+ competition_id TEXT NOT NULL,+ symbol TEXT NOT NULL,+ price REAL NOT NULL,+ bid REAL,+ ask REAL,+ volume_24h REAL,+ high_24h REAL,+ low_24h REAL,+ timestamp TEXT DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY (competition_id) REFERENCES alpha_competitions(id) ON DELETE CASCADE+ )`,++ `CREATE INDEX IF NOT EXISTS idx_alpha_price_history_competition ON alpha_price_history(competition_id)`,+ `CREATE INDEX IF NOT EXISTS idx_alpha_price_history_timestamp ON alpha_price_history(timestamp)`,+ `CREATE INDEX IF NOT EXISTS idx_alpha_price_history_symbol ON alpha_price_history(symbol)`,++ // Alpha Arena decision logs table (all model decisions and trades)+ `CREATE TABLE IF NOT EXISTS alpha_decision_logs (+ id TEXT PRIMARY KEY,+ competition_id TEXT NOT NULL,+ model_name TEXT NOT NULL,+ cycle_number INTEGER NOT NULL,+ action TEXT NOT NULL CHECK (action IN ('buy', 'sell', 'hold')),+ symbol TEXT NOT NULL,+ quantity REAL,+ confidence REAL NOT NULL,+ reasoning TEXT NOT NULL,+ trade_executed TEXT NOT NULL,+ price_at_decision REAL NOT NULL,+ portfolio_value_before REAL NOT NULL,+ portfolio_value_after REAL NOT NULL,+ timestamp TEXT DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY (competition_id) REFERENCES alpha_competitions(id) ON DELETE CASCADE+ )`,++ `CREATE INDEX IF NOT EXISTS idx_alpha_decision_logs_competition ON alpha_decision_logs(competition_id)`,+ `CREATE INDEX IF NOT EXISTS idx_alpha_decision_logs_model ON alpha_decision_logs(model_name)`,+ `CREATE INDEX IF NOT EXISTS idx_alpha_decision_logs_cycle ON alpha_decision_logs(cycle_number)`,+ `CREATE INDEX IF NOT EXISTS idx_alpha_decision_logs_timestamp ON alpha_decision_logs(timestamp DESC)`,++ // Alpha Arena performance snapshots table (portfolio value over time for charting)+ `CREATE TABLE IF NOT EXISTS alpha_performance_snapshots (+ id TEXT PRIMARY KEY,+ competition_id TEXT NOT NULL,+ cycle_number INTEGER NOT NULL,+ model_name TEXT 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 DEFAULT CURRENT_TIMESTAMP,+ FOREIGN KEY (competition_id) REFERENCES alpha_competitions(id) ON DELETE CASCADE+ )`,++ `CREATE INDEX IF NOT EXISTS idx_alpha_performance_competition ON alpha_performance_snapshots(competition_id)`,+ `CREATE INDEX IF NOT EXISTS idx_alpha_performance_model ON alpha_performance_snapshots(model_name)`,+ `CREATE INDEX IF NOT EXISTS idx_alpha_performance_cycle ON alpha_performance_snapshots(cycle_number)`,+ `CREATE INDEX IF NOT EXISTS idx_alpha_performance_timestamp ON alpha_performance_snapshots(timestamp)`,+// Insert default LLM global settings`INSERT OR IGNORE INTO llm_global_settings (id, temperature, max_tokens, system_prompt)VALUES (1, 0.7, 2000, 'You are a helpful AI assistant specialized in financial analysis and market data.')`,@@ -886,6 +1099,202 @@ class SQLiteService {);}+ // =========================+ // LLM MODEL CONFIG METHODS (Multiple models per provider)+ // =========================++ async saveLLMModelConfig(config: Omit<LLMModelConfig, 'created_at' | 'updated_at'>): Promise<{ success: boolean; message: string; id?: string }> {+ try {+ await this.ensureInitialized();++ const id = config.id || crypto.randomUUID();++ await this.db!.execute(+ `INSERT OR REPLACE INTO llm_model_configs+ (id, provider, model_id, display_name, api_key, base_url, is_enabled, is_default, updated_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, CURRENT_TIMESTAMP)`,+ [+ id,+ config.provider,+ config.model_id,+ config.display_name,+ config.api_key || null,+ config.base_url || null,+ config.is_enabled ? 1 : 0,+ config.is_default ? 1 : 0,+ ]+ );++ return { success: true, message: 'LLM model configuration saved', id };+ } catch (error) {+ console.error('[SQLite] Failed to save LLM model config:', error);+ return { success: false, message: 'Failed to save LLM model configuration' };+ }+ }++ async getLLMModelConfigs(): Promise<LLMModelConfig[]> {+ await this.ensureInitialized();+ return await this.db!.select<LLMModelConfig[]>(+ 'SELECT * FROM llm_model_configs ORDER BY provider, display_name'+ );+ }++ async getLLMModelConfigsByProvider(provider: string): Promise<LLMModelConfig[]> {+ await this.ensureInitialized();+ return await this.db!.select<LLMModelConfig[]>(+ 'SELECT * FROM llm_model_configs WHERE provider = $1 ORDER BY display_name',+ [provider]+ );+ }++ async getEnabledLLMModelConfigs(): Promise<LLMModelConfig[]> {+ await this.ensureInitialized();+ return await this.db!.select<LLMModelConfig[]>(+ 'SELECT * FROM llm_model_configs WHERE is_enabled = 1 ORDER BY provider, display_name'+ );+ }++ async getLLMModelConfig(id: string): Promise<LLMModelConfig | null> {+ await this.ensureInitialized();+ const results = await this.db!.select<LLMModelConfig[]>(+ 'SELECT * FROM llm_model_configs WHERE id = $1',+ [id]+ );+ return results[0] || null;+ }++ async deleteLLMModelConfig(id: string): Promise<{ success: boolean; message: string }> {+ try {+ await this.ensureInitialized();+ await this.db!.execute('DELETE FROM llm_model_configs WHERE id = $1', [id]);+ return { success: true, message: 'LLM model configuration deleted' };+ } catch (error) {+ console.error('[SQLite] Failed to delete LLM model config:', error);+ return { success: false, message: 'Failed to delete LLM model configuration' };+ }+ }++ async toggleLLMModelConfigEnabled(id: string): Promise<{ success: boolean; enabled: boolean }> {+ try {+ await this.ensureInitialized();++ const config = await this.getLLMModelConfig(id);+ if (!config) {+ return { success: false, enabled: false };+ }++ const newEnabled = !config.is_enabled;+ await this.db!.execute(+ 'UPDATE llm_model_configs SET is_enabled = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2',+ [newEnabled ? 1 : 0, id]+ );++ return { success: true, enabled: newEnabled };+ } catch (error) {+ console.error('[SQLite] Failed to toggle LLM model config:', error);+ return { success: false, enabled: false };+ }+ }++ async setDefaultLLMModelConfig(id: string, provider: string): Promise<{ success: boolean }> {+ try {+ await this.ensureInitialized();++ // Remove default from all models of this provider+ await this.db!.execute(+ 'UPDATE llm_model_configs SET is_default = 0 WHERE provider = $1',+ [provider]+ );++ // Set the new default+ await this.db!.execute(+ 'UPDATE llm_model_configs SET is_default = 1, updated_at = CURRENT_TIMESTAMP WHERE id = $1',+ [id]+ );++ return { success: true };+ } catch (error) {+ console.error('[SQLite] Failed to set default LLM model:', error);+ return { success: false };+ }+ }++ /**+ * Get all configured LLMs with their API keys for Alpha Arena+ * Returns models grouped by provider with API keys+ */+ async getConfiguredLLMsForArena(): Promise<{+ provider: string;+ api_key: string;+ models: { id: string; model_id: string; display_name: string }[];+ }[]> {+ await this.ensureInitialized();++ // First get from new model configs table+ const modelConfigs = await this.getEnabledLLMModelConfigs();++ // Also get from legacy llm_configs table+ const legacyConfigs = await this.getLLMConfigs();++ // Combine and group by provider+ const providerMap = new Map<string, {+ api_key: string;+ models: { id: string; model_id: string; display_name: string }[];+ }>();++ // Add from new model configs+ for (const config of modelConfigs) {+ if (!config.api_key) continue;++ if (!providerMap.has(config.provider)) {+ providerMap.set(config.provider, {+ api_key: config.api_key,+ models: []+ });+ }++ const entry = providerMap.get(config.provider)!;+ // Update API key if this one has it+ if (config.api_key) {+ entry.api_key = config.api_key;+ }+ entry.models.push({+ id: config.id,+ model_id: config.model_id,+ display_name: config.display_name+ });+ }++ // Add from legacy configs if not already present+ for (const config of legacyConfigs) {+ if (!config.api_key) continue;++ if (!providerMap.has(config.provider)) {+ providerMap.set(config.provider, {+ api_key: config.api_key,+ models: [{+ id: `legacy_${config.provider}`,+ model_id: config.model,+ display_name: config.model+ }]+ });+ } else if (providerMap.get(config.provider)!.models.length === 0) {+ // Add legacy model if no models from new table+ providerMap.get(config.provider)!.models.push({+ id: `legacy_${config.provider}`,+ model_id: config.model,+ display_name: config.model+ });+ }+ }++ // Convert to array+ return Array.from(providerMap.entries()).map(([provider, data]) => ({+ provider,+ ...data+ }));+ }+// =========================// CHAT METHODS// =========================@@ -2391,6 +2800,251 @@ class SQLiteService {}}+ // ==================== ALPHA ARENA METHODS ====================++ /**+ * Create a new Alpha Arena competition+ */+ async createAlphaCompetition(competition: Omit<AlphaCompetition, 'created_at' | 'updated_at'>): Promise<AlphaCompetition> {+ await this.ensureInitialized();++ const now = new Date().toISOString();+ const comp: AlphaCompetition = {+ ...competition,+ created_at: now,+ updated_at: now+ };++ await this.db!.execute(+ `INSERT INTO alpha_competitions+ (id, name, symbol, mode, status, cycle_count, cycle_interval_seconds, initial_capital, created_at, started_at, ended_at, updated_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,+ [comp.id, comp.name, comp.symbol, comp.mode, comp.status, comp.cycle_count, comp.cycle_interval_seconds, comp.initial_capital, comp.created_at, comp.started_at, comp.ended_at, comp.updated_at]+ );++ return comp;+ }++ /**+ * Get all competitions+ */+ async getAlphaCompetitions(limit?: number): Promise<AlphaCompetition[]> {+ await this.ensureInitialized();+ const sql = limit+ ? 'SELECT * FROM alpha_competitions ORDER BY created_at DESC LIMIT $1'+ : 'SELECT * FROM alpha_competitions ORDER BY created_at DESC';+ return limit ? await this.db!.select(sql, [limit]) : await this.db!.select(sql);+ }++ /**+ * Get a specific competition by ID+ */+ async getAlphaCompetition(id: string): Promise<AlphaCompetition | null> {+ await this.ensureInitialized();+ const results = await this.db!.select<AlphaCompetition[]>(+ 'SELECT * FROM alpha_competitions WHERE id = $1',+ [id]+ );+ return results[0] || null;+ }++ /**+ * Update competition status and metadata+ */+ async updateAlphaCompetition(id: string, updates: Partial<Omit<AlphaCompetition, 'id' | 'created_at'>>): Promise<void> {+ await this.ensureInitialized();++ const fields: string[] = [];+ const values: any[] = [];+ let paramIndex = 1;++ Object.entries(updates).forEach(([key, value]) => {+ fields.push(`${key} = $${paramIndex}`);+ values.push(value);+ paramIndex++;+ });++ fields.push(`updated_at = $${paramIndex}`);+ values.push(new Date().toISOString());+ values.push(id);++ await this.db!.execute(+ `UPDATE alpha_competitions SET ${fields.join(', ')} WHERE id = $${paramIndex + 1}`,+ values+ );+ }++ /**+ * Delete a competition and all related data+ */+ async deleteAlphaCompetition(id: string): Promise<void> {+ await this.ensureInitialized();++ // Delete from all related tables+ await this.db!.execute('DELETE FROM alpha_performance_snapshots WHERE competition_id = $1', [id]);+ await this.db!.execute('DELETE FROM alpha_model_states WHERE competition_id = $1', [id]);+ await this.db!.execute('DELETE FROM alpha_decision_logs WHERE competition_id = $1', [id]);+ await this.db!.execute('DELETE FROM alpha_price_history WHERE competition_id = $1', [id]);+ await this.db!.execute('DELETE FROM alpha_competitions WHERE id = $1', [id]);++ console.log(`[SQLite] Deleted competition ${id} and all related data`);+ }++ /**+ * Save/update model state+ */+ async saveAlphaModelState(state: Omit<AlphaModelState, 'created_at' | 'updated_at'>): Promise<void> {+ await this.ensureInitialized();++ const now = new Date().toISOString();++ await this.db!.execute(+ `INSERT OR REPLACE INTO alpha_model_states+ (id, competition_id, model_name, provider, model_id, capital, positions_json, trades_count, total_pnl, portfolio_value, created_at, updated_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, COALESCE((SELECT created_at FROM alpha_model_states WHERE id = $1), $11), $12)`,+ [state.id, state.competition_id, state.model_name, state.provider, state.model_id, state.capital, state.positions_json, state.trades_count, state.total_pnl, state.portfolio_value, now, now]+ );+ }++ /**+ * Get all model states for a competition+ */+ async getAlphaModelStates(competitionId: string): Promise<AlphaModelState[]> {+ await this.ensureInitialized();+ return await this.db!.select<AlphaModelState[]>(+ 'SELECT * FROM alpha_model_states WHERE competition_id = $1',+ [competitionId]+ );+ }++ /**+ * Get a specific model state+ */+ async getAlphaModelState(competitionId: string, modelName: string): Promise<AlphaModelState | null> {+ await this.ensureInitialized();+ const results = await this.db!.select<AlphaModelState[]>(+ 'SELECT * FROM alpha_model_states WHERE competition_id = $1 AND model_name = $2',+ [competitionId, modelName]+ );+ return results[0] || null;+ }++ /**+ * Log price data for charting+ */+ async logAlphaPrice(price: Omit<AlphaPriceHistory, 'timestamp'>): Promise<void> {+ await this.ensureInitialized();++ await this.db!.execute(+ `INSERT INTO alpha_price_history+ (id, competition_id, symbol, price, bid, ask, volume_24h, high_24h, low_24h, timestamp)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,+ [price.id, price.competition_id, price.symbol, price.price, price.bid, price.ask, price.volume_24h, price.high_24h, price.low_24h, new Date().toISOString()]+ );+ }++ /**+ * Get price history for a competition+ */+ async getAlphaPriceHistory(competitionId: string, limit?: number): Promise<AlphaPriceHistory[]> {+ await this.ensureInitialized();+ const sql = limit+ ? 'SELECT * FROM alpha_price_history WHERE competition_id = $1 ORDER BY timestamp DESC LIMIT $2'+ : 'SELECT * FROM alpha_price_history WHERE competition_id = $1 ORDER BY timestamp DESC';+ return limit ? await this.db!.select(sql, [competitionId, limit]) : await this.db!.select(sql, [competitionId]);+ }++ /**+ * Log a model decision+ */+ async logAlphaDecision(decision: Omit<AlphaDecisionLog, 'timestamp'>): Promise<void> {+ await this.ensureInitialized();++ await this.db!.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 ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)`,+ [decision.id, decision.competition_id, decision.model_name, decision.cycle_number, decision.action, decision.symbol, decision.quantity, decision.confidence, decision.reasoning, decision.trade_executed, decision.price_at_decision, decision.portfolio_value_before, decision.portfolio_value_after, new Date().toISOString()]+ );+ }++ /**+ * Get decision logs for a competition+ */+ async getAlphaDecisionLogs(competitionId: string, modelName?: string, limit?: number): Promise<AlphaDecisionLog[]> {+ await this.ensureInitialized();++ let sql = 'SELECT * FROM alpha_decision_logs WHERE competition_id = $1';+ const params: any[] = [competitionId];++ if (modelName) {+ sql += ' AND model_name = $2';+ params.push(modelName);+ }++ sql += ' ORDER BY timestamp DESC';++ if (limit) {+ sql += ` LIMIT $${params.length + 1}`;+ params.push(limit);+ }++ return await this.db!.select(sql, params);+ }++ /**+ * Save a performance snapshot+ */+ async saveAlphaPerformanceSnapshot(snapshot: Omit<AlphaPerformanceSnapshot, 'timestamp'>): Promise<void> {+ await this.ensureInitialized();++ await this.db!.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 ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,+ [snapshot.id, snapshot.competition_id, snapshot.cycle_number, snapshot.model_name, snapshot.portfolio_value, snapshot.cash, snapshot.pnl, snapshot.return_pct, snapshot.positions_count, snapshot.trades_count, new Date().toISOString()]+ );+ }++ /**+ * Get performance snapshots for charting+ */+ async getAlphaPerformanceSnapshots(competitionId: string, modelName?: string): Promise<AlphaPerformanceSnapshot[]> {+ await this.ensureInitialized();++ let sql = 'SELECT * FROM alpha_performance_snapshots WHERE competition_id = $1';+ const params: any[] = [competitionId];++ if (modelName) {+ sql += ' AND model_name = $2';+ params.push(modelName);+ }++ sql += ' ORDER BY cycle_number ASC';++ return await this.db!.select(sql, params);+ }++ /**+ * Get latest performance snapshot for each model in a competition (for leaderboard)+ */+ async getAlphaLatestPerformance(competitionId: string): Promise<AlphaPerformanceSnapshot[]> {+ await this.ensureInitialized();++ return await this.db!.select(+ `SELECT * FROM alpha_performance_snapshots+ WHERE competition_id = $1+ AND (model_name, cycle_number) IN (+ SELECT model_name, MAX(cycle_number)+ FROM alpha_performance_snapshots+ WHERE competition_id = $1+ GROUP BY model_name+ )+ ORDER BY pnl DESC`,+ [competitionId]+ );+ }+// =========================// UTILITY METHODS// =========================