Skip to content

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.

Agentic Trading added to Paper Trading

tilakpatel22039dfee35a7b
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/README.md b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/README.md
new file mode 100644
index 000000000..1f5588966
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/README.md
@@ -0,0 +1,425 @@
+# Agno Trading Agent System
+
+A comprehensive AI trading agent framework powered by **Agno** for Fincept Terminal.
+
+## Overview
+
+This system provides intelligent AI trading agents that can:
+- Analyze markets and generate insights
+- Develop and execute trading strategies
+- Manage portfolio risk
+- Provide real-time decision support
+- Learn from market patterns
+
+## Architecture
+
+```
+agno_trading/
+├── config/ # Configuration management
+│ ├── settings.py # Main configuration classes
+│ └── models.py # LLM model registry
+├── core/ # Core agent framework
+│ ├── agent_manager.py
+│ └── team_orchestrator.py
+├── agents/ # Specialized trading agents
+│ ├── market_analyst.py
+│ ├── trading_strategy.py
+│ ├── risk_manager.py
+│ └── portfolio_manager.py
+├── tools/ # Agent tools
+│ ├── market_data.py
+│ ├── technical_indicators.py
+│ └── order_execution.py
+├── knowledge/ # Knowledge base
+│ └── market_knowledge.py
+└── utils/ # Utilities
+ └── helpers.py
+```
+
+## Features
+
+### Supported LLM Providers
+
+- **OpenAI**: GPT-4, GPT-4 Turbo, GPT-4o, o1, o4
+- **Anthropic**: Claude 3 (Opus, Sonnet, Haiku), Claude Sonnet 4
+- **Google**: Gemini Pro, Gemini 1.5 Pro/Flash, Gemini 2.0 Flash
+- **Groq**: Llama 3.1, Mixtral
+- **DeepSeek**: DeepSeek Chat, DeepSeek Reasoner
+- **xAI**: Grok, Grok-2
+- **Ollama**: Local models (Llama, Mistral, Qwen, etc.)
+- **Cohere, Mistral, Together, Fireworks**
+
+### Agent Types
+
+1. **Market Analyst Agent**
+ - Analyzes market data and trends
+ - Provides technical and fundamental insights
+ - Monitors news and sentiment
+
+2. **Trading Strategy Agent**
+ - Develops trading strategies
+ - Generates buy/sell signals
+ - Optimizes entry/exit points
+
+3. **Risk Manager Agent**
+ - Monitors portfolio risk metrics
+ - Calculates VaR and drawdowns
+ - Provides risk mitigation recommendations
+
+4. **Portfolio Manager Agent**
+ - Manages asset allocation
+ - Rebalances portfolio
+ - Optimizes risk-adjusted returns
+
+5. **Sentiment Analyst Agent**
+ - Analyzes market sentiment
+ - Monitors social media and news
+ - Detects sentiment shifts
+
+### Configuration Options
+
+#### LLM Configuration
+```python
+{
+ "provider": "openai", # LLM provider
+ "model": "gpt-4", # Model name
+ "temperature": 0.7, # Creativity (0.0-1.0)
+ "max_tokens": 4096, # Max response length
+ "top_p": 1.0, # Nucleus sampling
+ "reasoning_effort": "medium", # For reasoning models
+ "stream": false # Enable streaming
+}
+```
+
+#### Trading Configuration
+```python
+{
+ "mode": "paper", # paper, live, backtest
+ "max_position_size": 0.1, # Max 10% of portfolio
+ "max_leverage": 1.0, # No leverage
+ "stop_loss_pct": 0.05, # 5% stop loss
+ "take_profit_pct": 0.15, # 15% take profit
+ "symbols": ["BTC/USD"], # Trading symbols
+ "exchange": "kraken" # Exchange name
+}
+```
+
+#### Knowledge Configuration
+```python
+{
+ "vector_db": "lancedb", # Vector database
+ "embedder_provider": "openai",
+ "embedder_model": "text-embedding-3-small",
+ "search_type": "hybrid", # vector, keyword, hybrid
+ "search_limit": 5
+}
+```
+
+#### Memory Configuration
+```python
+{
+ "enable_memory": true, # Persistent memory
+ "enable_sessions": true, # Session tracking
+ "memory_db": "sqlite", # Database backend
+ "max_session_history": 100 # Max messages per session
+}
+```
+
+## Installation
+
+### 1. Install Python Dependencies
+
+```bash
+cd src-tauri/resources/scripts/agno_trading
+pip install -r requirements.txt
+```
+
+### 2. Set API Keys
+
+Create a `.env` file or set environment variables:
+
+```bash
+# OpenAI
+export OPENAI_API_KEY="your-key"
+
+# Anthropic
+export ANTHROPIC_API_KEY="your-key"
+
+# Google
+export GOOGLE_API_KEY="your-key"
+
+# Groq
+export GROQ_API_KEY="your-key"
+
+# DeepSeek
+export DEEPSEEK_API_KEY="your-key"
+
+# xAI (Grok)
+export XAI_API_KEY="your-key"
+```
+
+## Usage from Rust/Tauri
+
+### List Available Models
+
+```rust
+use tauri::command;
+
+#[tauri::command]
+async fn list_models(app: tauri::AppHandle) -> Result<String, String> {
+ commands::agno_trading::agno_list_models(app, None).await
+}
+```
+
+### Recommend Model for Task
+
+```rust
+commands::agno_trading::agno_recommend_model(
+ app,
+ "trading".to_string(),
+ Some("medium".to_string()),
+ Some(false)
+).await
+```
+
+### Analyze Market
+
+```rust
+commands::agno_trading::agno_analyze_market(
+ app,
+ "BTC/USD".to_string(),
+ Some("anthropic:claude-sonnet-4".to_string()),
+ Some("comprehensive".to_string())
+).await
+```
+
+### Generate Trade Signal
+
+```rust
+commands::agno_trading::agno_generate_trade_signal(
+ app,
+ "ETH/USD".to_string(),
+ Some("momentum".to_string()),
+ Some("openai:gpt-4o".to_string()),
+ None
+).await
+```
+
+### Risk Management
+
+```rust
+let portfolio_data = json!({
+ "positions": [...],
+ "total_value": 100000.0
+}).to_string();
+
+commands::agno_trading::agno_manage_risk(
+ app,
+ portfolio_data,
+ Some("openai:gpt-4".to_string()),
+ Some("moderate".to_string())
+).await
+```
+
+## Usage from Frontend (TypeScript)
+
+```typescript
+import { invoke } from '@tauri-apps/api/core';
+
+// List available models
+const models = await invoke('agno_list_models', {
+ provider: 'openai'
+});
+
+// Analyze market
+const analysis = await invoke('agno_analyze_market', {
+ symbol: 'BTC/USD',
+ agentModel: 'anthropic:claude-sonnet-4',
+ analysisType: 'comprehensive'
+});
+
+// Generate trade signal
+const signal = await invoke('agno_generate_trade_signal', {
+ symbol: 'ETH/USD',
+ strategy: 'momentum',
+ agentModel: 'openai:gpt-4o-mini'
+});
+
+// Risk management
+const risk = await invoke('agno_manage_risk', {
+ portfolioData: JSON.stringify(portfolio),
+ agentModel: 'openai:gpt-4',
+ riskTolerance: 'moderate'
+});
+```
+
+## CLI Usage (Direct Python)
+
+```bash
+# List models
+python agno_trading_service.py list_models
+
+# Recommend model for task
+python agno_trading_service.py recommend_model trading medium false
+
+# Get configuration template
+python agno_trading_service.py get_config_template default
+
+# Analyze market
+python agno_trading_service.py analyze_market BTC/USD openai:gpt-4o-mini comprehensive
+```
+
+## Response Format
+
+All commands return JSON in this format:
+
+```json
+{
+ "success": true,
+ "data": {
+ ...
+ },
+ "error": null
+}
+```
+
+Error response:
+
+```json
+{
+ "success": false,
+ "data": null,
+ "error": "Error message here"
+}
+```
+
+## Advanced Features
+
+### Multi-Agent Teams
+
+Create teams of specialized agents that collaborate:
+
+```python
+team = Team(
+ name="TradingTeam",
+ members=[market_analyst, strategy_agent, risk_manager],
+ lead_agent=strategy_agent,
+ delegation_strategy="sequential"
+)
+```
+
+### Workflows
+
+Build deterministic trading workflows:
+
+```python
+workflow = Workflow(
+ name="TradingWorkflow",
+ steps=[
+ fetch_market_data,
+ analyze_market,
+ generate_signal,
+ check_risk,
+ execute_trade
+ ]
+)
+```
+
+### Knowledge Integration
+
+Agents can access:
+- Historical market data
+- Economic indicators
+- News and sentiment
+- Research reports
+- Company filings
+
+### Memory System
+
+Agents remember:
+- Past decisions and outcomes
+- User preferences
+- Market patterns
+- Strategy performance
+
+## Model Recommendations
+
+### For Trading (Fast decisions)
+- **High Budget**: `anthropic:claude-sonnet-4`
+- **Medium Budget**: `openai:gpt-4o-mini`
+- **Low Budget**: `groq:llama-3.1-70b`
+
+### For Analysis (Deep insights)
+- **High Budget**: `google:gemini-1.5-pro`
+- **Medium Budget**: `anthropic:claude-3-sonnet`
+- **Low Budget**: `groq:mixtral-8x7b`
+
+### For Risk Management (Conservative)
+- **High Budget**: `openai:gpt-4`
+- **Medium Budget**: `anthropic:claude-3-sonnet`
+- **Low Budget**: `deepseek:deepseek-chat`
+
+### For Reasoning (Complex analysis)
+- **High Budget**: `openai:o4`
+- **Medium Budget**: `openai:o1-mini`
+- **Low Budget**: `deepseek:deepseek-reasoner`
+
+## Troubleshooting
+
+### Missing API Keys
+Error: `API key not found`
+Solution: Set environment variables or configure in settings
+
+### Model Not Found
+Error: `Model 'xyz' not found for provider 'abc'`
+Solution: Use `list_models` command to see available models
+
+### Rate Limits
+Error: `Rate limit exceeded`
+Solution: Reduce request frequency or upgrade API plan
+
+### Python Dependencies
+Error: `Module not found`
+Solution: Run `pip install -r requirements.txt`
+
+## Performance Optimization
+
+1. **Use appropriate models**: Don't use GPT-4 for simple tasks
+2. **Enable caching**: Reduce redundant API calls
+3. **Batch requests**: Process multiple items together
+4. **Local models**: Use Ollama for development/testing
+5. **Streaming**: Enable streaming for long responses
+
+## Security
+
+- API keys stored in environment variables
+- Never log sensitive data
+- Validate all inputs
+- Rate limiting enabled
+- Secure database connections
+
+## Future Enhancements
+
+- [ ] Real-time market data integration
+- [ ] Backtesting framework
+- [ ] Strategy optimization
+- [ ] Multi-exchange support
+- [ ] Advanced risk models
+- [ ] Portfolio optimization
+- [ ] Social trading features
+- [ ] Performance analytics
+
+## Support
+
+For issues or questions:
+- Check the documentation
+- Review example code
+
+## License
+
+MIT License - Fincept Terminal
+
+## Version
+
+v1.0.0 - Initial Release
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/__init__.py
new file mode 100644
index 000000000..25f31860b
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/__init__.py
@@ -0,0 +1,41 @@
+"""
+Agno Trading Agent System
+==========================
+
+A comprehensive AI trading agent framework powered by Agno.
+Supports multiple LLM providers, trading strategies, and market analysis.
+
+Architecture:
+- core/: Base classes and agent management
+- agents/: Specialized trading agents (analyst, trader, risk manager, etc.)
+- tools/: Market data, technical analysis, order execution tools
+- knowledge/: Market research, historical data, documentation
+- utils/: Helper functions and utilities
+- config/: Configuration management
+
+Author: Fincept Terminal
+Version: 1.0.0
+"""
+
+__version__ = "1.0.0"
+__author__ = "Fincept Terminal"
+
+from .core.agent_manager import AgentManager
+from .core.team_orchestrator import TeamOrchestrator
+from .agents import (
+ MarketAnalystAgent,
+ TradingStrategyAgent,
+ RiskManagerAgent,
+ PortfolioManagerAgent,
+ SentimentAnalystAgent
+)
+
+__all__ = [
+ "AgentManager",
+ "TeamOrchestrator",
+ "MarketAnalystAgent",
+ "TradingStrategyAgent",
+ "RiskManagerAgent",
+ "PortfolioManagerAgent",
+ "SentimentAnalystAgent"
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/__init__.py
new file mode 100644
index 000000000..db95e4f05
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/__init__.py
@@ -0,0 +1,20 @@
+"""
+Specialized Trading Agents
+
+This module provides specialized AI agents for different trading tasks.
+Each agent has specific expertise and tools optimized for their role.
+"""
+
+from .market_analyst import MarketAnalystAgent
+from .trading_strategy import TradingStrategyAgent
+from .risk_manager import RiskManagerAgent
+from .portfolio_manager import PortfolioManagerAgent
+from .sentiment_analyst import SentimentAnalystAgent
+
+__all__ = [
+ 'MarketAnalystAgent',
+ 'TradingStrategyAgent',
+ 'RiskManagerAgent',
+ 'PortfolioManagerAgent',
+ 'SentimentAnalystAgent',
+]
diff --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.py
new file mode 100644
index 000000000..e7fe588a0
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/market_analyst.py
@@ -0,0 +1,283 @@
+"""
+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.py
new file mode 100644
index 000000000..fd1bd588f
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/portfolio_manager.py
@@ -0,0 +1,107 @@
+"""
+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.py
new file mode 100644
index 000000000..73d28e291
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/risk_manager.py
@@ -0,0 +1,151 @@
+"""
+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.py
new file mode 100644
index 000000000..857491119
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/sentiment_analyst.py
@@ -0,0 +1,101 @@
+"""
+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.py
new file mode 100644
index 000000000..24df81ee6
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/agents/trading_strategy.py
@@ -0,0 +1,172 @@
+"""
+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/config/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/config/__init__.py
new file mode 100644
index 000000000..bb834ac5a
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/config/__init__.py
@@ -0,0 +1,6 @@
+"""Configuration module for Agno trading agents"""
+
+from .settings import AgnoConfig, LLMConfig, TradingConfig
+from .models import get_model, list_available_models
+
+__all__ = ["AgnoConfig", "LLMConfig", "TradingConfig", "get_model", "list_available_models"]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/config/models.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/config/models.py
new file mode 100644
index 000000000..065c8e8e2
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/config/models.py
@@ -0,0 +1,395 @@
+"""
+LLM Model Registry and Factory
+===============================
+
+Centralized registry of all supported LLM models with their capabilities
+and factory functions to create Agno model instances.
+"""
+
+from typing import Dict, List, Any, Optional
+from dataclasses import dataclass
+from .settings import LLMProvider, LLMConfig
+
+
+@dataclass
+class ModelCapabilities:
+ """Model capabilities and specifications"""
+ max_tokens: int
+ supports_streaming: bool
+ supports_function_calling: bool
+ supports_vision: bool = False
+ supports_reasoning: bool = False
+ context_window: int = 0
+ cost_per_1k_input: float = 0.0
+ cost_per_1k_output: float = 0.0
+
+
+# Model Registry with capabilities
+MODEL_REGISTRY: Dict[str, Dict[str, ModelCapabilities]] = {
+ # OpenAI Models
+ "openai": {
+ "gpt-4": ModelCapabilities(
+ max_tokens=8192,
+ context_window=8192,
+ supports_streaming=True,
+ supports_function_calling=True,
+ supports_vision=False,
+ cost_per_1k_input=0.03,
+ cost_per_1k_output=0.06
+ ),
+ "gpt-4-turbo": ModelCapabilities(
+ max_tokens=4096,
+ context_window=128000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ supports_vision=True,
+ cost_per_1k_input=0.01,
+ cost_per_1k_output=0.03
+ ),
+ "gpt-4o": ModelCapabilities(
+ max_tokens=16384,
+ context_window=128000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ supports_vision=True,
+ cost_per_1k_input=0.005,
+ cost_per_1k_output=0.015
+ ),
+ "gpt-4o-mini": ModelCapabilities(
+ max_tokens=16384,
+ context_window=128000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ supports_vision=True,
+ cost_per_1k_input=0.00015,
+ cost_per_1k_output=0.0006
+ ),
+ "o1": ModelCapabilities(
+ max_tokens=100000,
+ context_window=200000,
+ supports_streaming=False,
+ supports_function_calling=False,
+ supports_reasoning=True,
+ cost_per_1k_input=0.015,
+ cost_per_1k_output=0.06
+ ),
+ "o1-mini": ModelCapabilities(
+ max_tokens=65536,
+ context_window=128000,
+ supports_streaming=False,
+ supports_function_calling=False,
+ supports_reasoning=True,
+ cost_per_1k_input=0.003,
+ cost_per_1k_output=0.012
+ ),
+ "o4": ModelCapabilities(
+ max_tokens=100000,
+ context_window=200000,
+ supports_streaming=False,
+ supports_function_calling=True,
+ supports_reasoning=True,
+ cost_per_1k_input=0.01,
+ cost_per_1k_output=0.04
+ ),
+ },
+ # Anthropic Models
+ "anthropic": {
+ "claude-3-opus": ModelCapabilities(
+ max_tokens=4096,
+ context_window=200000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ supports_vision=True,
+ cost_per_1k_input=0.015,
+ cost_per_1k_output=0.075
+ ),
+ "claude-3-sonnet": ModelCapabilities(
+ max_tokens=4096,
+ context_window=200000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ supports_vision=True,
+ cost_per_1k_input=0.003,
+ cost_per_1k_output=0.015
+ ),
+ "claude-3-haiku": ModelCapabilities(
+ max_tokens=4096,
+ context_window=200000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ supports_vision=True,
+ cost_per_1k_input=0.00025,
+ cost_per_1k_output=0.00125
+ ),
+ "claude-sonnet-4": ModelCapabilities(
+ max_tokens=8192,
+ context_window=200000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ supports_vision=True,
+ cost_per_1k_input=0.003,
+ cost_per_1k_output=0.015
+ ),
+ "claude-opus-4": ModelCapabilities(
+ max_tokens=8192,
+ context_window=200000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ supports_vision=True,
+ cost_per_1k_input=0.015,
+ cost_per_1k_output=0.075
+ ),
+ },
+ # Google Models
+ "google": {
+ "gemini-pro": ModelCapabilities(
+ max_tokens=8192,
+ context_window=32768,
+ supports_streaming=True,
+ supports_function_calling=True,
+ supports_vision=False,
+ cost_per_1k_input=0.0005,
+ cost_per_1k_output=0.0015
+ ),
+ "gemini-pro-vision": ModelCapabilities(
+ max_tokens=4096,
+ context_window=16384,
+ supports_streaming=True,
+ supports_function_calling=True,
+ supports_vision=True,
+ cost_per_1k_input=0.00025,
+ cost_per_1k_output=0.0005
+ ),
+ "gemini-1.5-pro": ModelCapabilities(
+ max_tokens=8192,
+ context_window=2000000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ supports_vision=True,
+ cost_per_1k_input=0.00125,
+ cost_per_1k_output=0.00375
+ ),
+ "gemini-1.5-flash": ModelCapabilities(
+ max_tokens=8192,
+ context_window=1000000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ supports_vision=True,
+ cost_per_1k_input=0.000075,
+ cost_per_1k_output=0.00030
+ ),
+ "gemini-2.0-flash": ModelCapabilities(
+ max_tokens=8192,
+ context_window=1000000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ supports_vision=True,
+ cost_per_1k_input=0.000075,
+ cost_per_1k_output=0.00030
+ ),
+ },
+ # Groq Models
+ "groq": {
+ "llama-3.1-8b": ModelCapabilities(
+ max_tokens=8000,
+ context_window=128000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ cost_per_1k_input=0.00005,
+ cost_per_1k_output=0.00008
+ ),
+ "llama-3.1-70b": ModelCapabilities(
+ max_tokens=8000,
+ context_window=128000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ cost_per_1k_input=0.00059,
+ cost_per_1k_output=0.00079
+ ),
+ "mixtral-8x7b": ModelCapabilities(
+ max_tokens=32768,
+ context_window=32768,
+ supports_streaming=True,
+ supports_function_calling=True,
+ cost_per_1k_input=0.00024,
+ cost_per_1k_output=0.00024
+ ),
+ },
+ # DeepSeek Models
+ "deepseek": {
+ "deepseek-chat": ModelCapabilities(
+ max_tokens=4096,
+ context_window=64000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ cost_per_1k_input=0.00014,
+ cost_per_1k_output=0.00028
+ ),
+ "deepseek-coder": ModelCapabilities(
+ max_tokens=4096,
+ context_window=16000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ cost_per_1k_input=0.00014,
+ cost_per_1k_output=0.00028
+ ),
+ "deepseek-reasoner": ModelCapabilities(
+ max_tokens=8000,
+ context_window=64000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ supports_reasoning=True,
+ cost_per_1k_input=0.00055,
+ cost_per_1k_output=0.0022
+ ),
+ },
+ # xAI Grok Models
+ "xai": {
+ "grok-beta": ModelCapabilities(
+ max_tokens=8192,
+ context_window=131072,
+ supports_streaming=True,
+ supports_function_calling=True,
+ cost_per_1k_input=0.005,
+ cost_per_1k_output=0.015
+ ),
+ "grok-2": ModelCapabilities(
+ max_tokens=8192,
+ context_window=131072,
+ supports_streaming=True,
+ supports_function_calling=True,
+ cost_per_1k_input=0.002,
+ cost_per_1k_output=0.01
+ ),
+ },
+ # Ollama Models (Local)
+ "ollama": {
+ "llama3.1": ModelCapabilities(
+ max_tokens=8192,
+ context_window=128000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ cost_per_1k_input=0.0,
+ cost_per_1k_output=0.0
+ ),
+ "mistral": ModelCapabilities(
+ max_tokens=8192,
+ context_window=32768,
+ supports_streaming=True,
+ supports_function_calling=True,
+ cost_per_1k_input=0.0,
+ cost_per_1k_output=0.0
+ ),
+ "qwen2.5": ModelCapabilities(
+ max_tokens=8192,
+ context_window=128000,
+ supports_streaming=True,
+ supports_function_calling=True,
+ cost_per_1k_input=0.0,
+ cost_per_1k_output=0.0
+ ),
+ },
+}
+
+
+def get_model(provider: str, model_name: str) -> Optional[ModelCapabilities]:
+ """Get model capabilities"""
+ return MODEL_REGISTRY.get(provider, {}).get(model_name)
+
+
+def list_available_models(provider: Optional[str] = None) -> Dict[str, List[str]]:
+ """List all available models, optionally filtered by provider"""
+ if provider:
+ return {provider: list(MODEL_REGISTRY.get(provider, {}).keys())}
+ return {prov: list(models.keys()) for prov, models in MODEL_REGISTRY.items()}
+
+
+def get_best_model_for_task(
+ task: str,
+ budget: str = "medium",
+ requires_reasoning: bool = False
+) -> tuple[str, str]:
+ """
+ Recommend best model for a specific task
+
+ Args:
+ task: Type of task (trading, analysis, risk_management, etc.)
+ budget: Budget level (low, medium, high)
+ requires_reasoning: Whether reasoning capabilities are needed
+
+ Returns:
+ Tuple of (provider, model_name)
+ """
+
+ if requires_reasoning:
+ if budget == "high":
+ return ("openai", "o4")
+ elif budget == "medium":
+ return ("openai", "o1-mini")
+ else:
+ return ("deepseek", "deepseek-reasoner")
+
+ if task == "trading":
+ # Fast, accurate, function calling
+ if budget == "high":
+ return ("anthropic", "claude-sonnet-4")
+ elif budget == "medium":
+ return ("openai", "gpt-4o-mini")
+ else:
+ return ("groq", "llama-3.1-70b")
+
+ elif task == "analysis":
+ # Deep understanding, large context
+ if budget == "high":
+ return ("google", "gemini-1.5-pro")
+ elif budget == "medium":
+ return ("anthropic", "claude-3-sonnet")
+ else:
+ return ("groq", "mixtral-8x7b")
+
+ elif task == "risk_management":
+ # Conservative, accurate
+ if budget == "high":
+ return ("openai", "gpt-4")
+ elif budget == "medium":
+ return ("anthropic", "claude-3-sonnet")
+ else:
+ return ("deepseek", "deepseek-chat")
+
+ # Default
+ return ("openai", "gpt-4o-mini")
+
+
+def validate_model_config(llm_config: LLMConfig) -> tuple[bool, Optional[str]]:
+ """
+ Validate LLM configuration
+
+ Returns:
+ Tuple of (is_valid, error_message)
+ """
+ provider = llm_config.provider.value
+ model = llm_config.model
+
+ # Check if model exists
+ if provider not in MODEL_REGISTRY:
+ return False, f"Provider '{provider}' not found in registry"
+
+ if model not in MODEL_REGISTRY[provider]:
+ available = ", ".join(MODEL_REGISTRY[provider].keys())
+ return False, f"Model '{model}' not found for provider '{provider}'. Available: {available}"
+
+ capabilities = MODEL_REGISTRY[provider][model]
+
+ # Check max_tokens
+ if llm_config.max_tokens and llm_config.max_tokens > capabilities.max_tokens:
+ return False, f"max_tokens ({llm_config.max_tokens}) exceeds model limit ({capabilities.max_tokens})"
+
+ # Check streaming support
+ if llm_config.stream and not capabilities.supports_streaming:
+ return False, f"Model '{model}' does not support streaming"
+
+ # Check reasoning
+ if llm_config.reasoning_effort and not capabilities.supports_reasoning:
+ return False, f"Model '{model}' does not support reasoning"
+
+ return True, None
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/config/settings.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/config/settings.py
new file mode 100644
index 000000000..3a85693b7
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/config/settings.py
@@ -0,0 +1,379 @@
+"""
+Configuration Settings for Agno Trading Agents
+===============================================
+
+Manages all configuration for LLM providers, trading parameters,
+knowledge bases, memory systems, and agent behaviors.
+"""
+
+import os
+from typing import Optional, Dict, Any, List
+from dataclasses import dataclass, field
+from enum import Enum
+
+
+class LLMProvider(str, Enum):
+ """Supported LLM providers"""
+ OPENAI = "openai"
+ ANTHROPIC = "anthropic"
+ GOOGLE = "google"
+ GROQ = "groq"
+ DEEPSEEK = "deepseek"
+ XAI = "xai" # Grok
+ OLLAMA = "ollama"
+ COHERE = "cohere"
+ MISTRAL = "mistral"
+ TOGETHER = "together"
+ FIREWORKS = "fireworks"
+
+
+class TradingMode(str, Enum):
+ """Trading execution modes"""
+ PAPER = "paper"
+ LIVE = "live"
+ BACKTEST = "backtest"
+ ANALYSIS_ONLY = "analysis_only"
+
+
+@dataclass
+class LLMConfig:
+ """LLM Provider Configuration"""
+
+ # Provider details
+ provider: LLMProvider = LLMProvider.OPENAI
+ model: str = "gpt-4"
+
+ # API Configuration
+ api_key: Optional[str] = None
+ api_base: Optional[str] = None
+ organization: Optional[str] = None
+
+ # Model parameters
+ temperature: float = 0.7
+ max_tokens: Optional[int] = 4096
+ top_p: float = 1.0
+ top_k: Optional[int] = None
+ frequency_penalty: float = 0.0
+ presence_penalty: float = 0.0
+
+ # Reasoning parameters (for reasoning models like o1)
+ reasoning_effort: Optional[str] = None # "low", "medium", "high"
+
+ # Streaming
+ stream: bool = False
+
+ # Timeout
+ timeout: int = 60
+
+ # Model-specific settings
+ model_kwargs: Dict[str, Any] = field(default_factory=dict)
+
+ def __post_init__(self):
+ """Load API key from environment if not provided"""
+ if not self.api_key:
+ env_var_map = {
+ LLMProvider.OPENAI: "OPENAI_API_KEY",
+ LLMProvider.ANTHROPIC: "ANTHROPIC_API_KEY",
+ LLMProvider.GOOGLE: "GOOGLE_API_KEY",
+ LLMProvider.GROQ: "GROQ_API_KEY",
+ LLMProvider.DEEPSEEK: "DEEPSEEK_API_KEY",
+ LLMProvider.XAI: "XAI_API_KEY",
+ LLMProvider.COHERE: "COHERE_API_KEY",
+ LLMProvider.MISTRAL: "MISTRAL_API_KEY",
+ }
+ env_var = env_var_map.get(self.provider)
+ if env_var:
+ self.api_key = os.getenv(env_var)
+
+ def to_agno_model_string(self) -> str:
+ """Convert to Agno model string format: provider:model"""
+ return f"{self.provider.value}:{self.model}"
+
+
+@dataclass
+class KnowledgeConfig:
+ """Knowledge base configuration"""
+
+ # Vector database settings
+ vector_db: str = "lancedb" # lancedb, chromadb, pgvector, etc.
+ vector_db_path: Optional[str] = None
+
+ # Embedder settings
+ embedder_provider: str = "openai"
+ embedder_model: str = "text-embedding-3-small"
+ embedder_api_key: Optional[str] = None
+ embedder_dimensions: int = 1536
+
+ # Search settings
+ search_type: str = "hybrid" # "vector", "keyword", "hybrid"
+ search_limit: int = 5
+
+ # Content sources
+ enable_market_news: bool = True
+ enable_economic_data: bool = True
+ enable_company_filings: bool = False
+ enable_research_reports: bool = False
+
+ # Chunking strategy
+ chunk_size: int = 1000
+ chunk_overlap: int = 200
+
+
+@dataclass
+class MemoryConfig:
+ """Memory system configuration"""
+
+ # Memory persistence
+ enable_memory: bool = True
+ memory_db: str = "sqlite" # sqlite, postgres, redis
+ memory_db_path: Optional[str] = None
+
+ # Session management
+ enable_sessions: bool = True
+ max_session_history: int = 100
+
+ # Memory optimization
+ enable_summarization: bool = True
+ summarization_threshold: int = 50 # messages
+
+ # User-specific memory
+ enable_user_memory: bool = True
+
+
+@dataclass
+class TradingConfig:
+ """Trading-specific configuration"""
+
+ # Trading mode
+ mode: TradingMode = TradingMode.PAPER
+
+ # Risk parameters
+ max_position_size: float = 0.1 # 10% of portfolio
+ max_leverage: float = 1.0 # No leverage by default
+ max_drawdown: float = 0.2 # 20% max drawdown
+ stop_loss_pct: float = 0.05 # 5% stop loss
+ take_profit_pct: float = 0.15 # 15% take profit
+
+ # Portfolio parameters
+ initial_capital: float = 10000.0
+ commission_rate: float = 0.001 # 0.1%
+ slippage_pct: float = 0.0005 # 0.05%
+
+ # Market data
+ market_data_provider: str = "ccxt" # ccxt, yfinance, polygon
+ exchange: str = "kraken" # For crypto
+ symbols: List[str] = field(default_factory=lambda: ["BTC/USD", "ETH/USD"])
+ timeframe: str = "1h"
+
+ # Order execution
+ order_type: str = "limit" # limit, market
+ time_in_force: str = "gtc" # gtc, ioc, fok
+
+ # Trading hours
+ trading_hours_start: str = "00:00"
+ trading_hours_end: str = "23:59"
+ timezone: str = "UTC"
+
+ # Backtesting
+ backtest_start_date: Optional[str] = None
+ backtest_end_date: Optional[str] = None
+
+
+@dataclass
+class AgentConfig:
+ """Individual agent configuration"""
+
+ # Agent identity
+ name: str = "TradingAgent"
+ role: str = "trader"
+ description: str = "An AI trading agent"
+
+ # Instructions
+ instructions: List[str] = field(default_factory=list)
+ system_prompt: Optional[str] = None
+
+ # Tools
+ tools: List[str] = field(default_factory=list)
+ enable_all_tools: bool = False
+
+ # Knowledge
+ enable_knowledge: bool = True
+
+ # Memory
+ enable_memory: bool = True
+
+ # Model
+ llm_config: Optional[LLMConfig] = None
+
+ # Execution
+ show_tool_calls: bool = True
+ markdown: bool = True
+ debug_mode: bool = False
+
+ # Output schema
+ structured_outputs: bool = False
+ output_model: Optional[str] = None
+
+
+@dataclass
+class TeamConfig:
+ """Team of agents configuration"""
+
+ # Team identity
+ name: str = "TradingTeam"
+ description: str = "A team of AI trading agents"
+
+ # Leader
+ lead_agent: Optional[str] = None
+
+ # Members
+ members: List[str] = field(default_factory=list)
+
+ # Delegation
+ delegation_strategy: str = "sequential" # sequential, parallel, all
+
+ # Model (inherited by all members if not specified)
+ llm_config: Optional[LLMConfig] = None
+
+ # Team memory
+ enable_shared_memory: bool = True
+
+ # Execution
+ show_tool_calls: bool = True
+ markdown: bool = True
+
+
+@dataclass
+class WorkflowConfig:
+ """Workflow configuration"""
+
+ # Workflow identity
+ name: str = "TradingWorkflow"
+ description: str = "AI trading workflow"
+
+ # Steps
+ steps: List[Dict[str, Any]] = field(default_factory=list)
+
+ # Execution
+ parallel_steps: bool = False
+ early_stop: bool = True
+
+ # Session
+ enable_session: bool = True
+
+ # Model
+ llm_config: Optional[LLMConfig] = None
+
+
+@dataclass
+class AgnoConfig:
+ """
+ Main configuration class for Agno trading system
+ Aggregates all sub-configurations
+ """
+
+ # Sub-configurations
+ llm: LLMConfig = field(default_factory=LLMConfig)
+ knowledge: KnowledgeConfig = field(default_factory=KnowledgeConfig)
+ memory: MemoryConfig = field(default_factory=MemoryConfig)
+ trading: TradingConfig = field(default_factory=TradingConfig)
+
+ # Global settings
+ debug: bool = False
+ log_level: str = "INFO"
+
+ # Database
+ db_url: Optional[str] = None # For AgentOS
+
+ # API Keys (loaded from environment)
+ api_keys: Dict[str, str] = field(default_factory=dict)
+
+ def __post_init__(self):
+ """Load environment variables"""
+ # Load API keys
+ api_key_vars = [
+ "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GOOGLE_API_KEY",
+ "GROQ_API_KEY", "DEEPSEEK_API_KEY", "XAI_API_KEY",
+ "COHERE_API_KEY", "MISTRAL_API_KEY"
+ ]
+ for var in api_key_vars:
+ value = os.getenv(var)
+ if value:
+ self.api_keys[var] = value
+
+ @classmethod
+ def from_dict(cls, config_dict: Dict[str, Any]) -> "AgnoConfig":
+ """Create configuration from dictionary"""
+ llm_config = LLMConfig(**config_dict.get("llm", {}))
+ knowledge_config = KnowledgeConfig(**config_dict.get("knowledge", {}))
+ memory_config = MemoryConfig(**config_dict.get("memory", {}))
+ trading_config = TradingConfig(**config_dict.get("trading", {}))
+
+ return cls(
+ llm=llm_config,
+ knowledge=knowledge_config,
+ memory=memory_config,
+ trading=trading_config,
+ debug=config_dict.get("debug", False),
+ log_level=config_dict.get("log_level", "INFO"),
+ db_url=config_dict.get("db_url")
+ )
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert configuration to dictionary"""
+ return {
+ "llm": {
+ "provider": self.llm.provider.value,
+ "model": self.llm.model,
+ "temperature": self.llm.temperature,
+ "max_tokens": self.llm.max_tokens,
+ "top_p": self.llm.top_p,
+ "reasoning_effort": self.llm.reasoning_effort,
+ "stream": self.llm.stream,
+ },
+ "knowledge": {
+ "vector_db": self.knowledge.vector_db,
+ "search_type": self.knowledge.search_type,
+ "search_limit": self.knowledge.search_limit,
+ },
+ "memory": {
+ "enable_memory": self.memory.enable_memory,
+ "enable_sessions": self.memory.enable_sessions,
+ "max_session_history": self.memory.max_session_history,
+ },
+ "trading": {
+ "mode": self.trading.mode.value,
+ "max_position_size": self.trading.max_position_size,
+ "max_leverage": self.trading.max_leverage,
+ "stop_loss_pct": self.trading.stop_loss_pct,
+ "symbols": self.trading.symbols,
+ },
+ "debug": self.debug,
+ "log_level": self.log_level,
+ }
+
+
+# Default configurations for different use cases
+DEFAULT_ANALYST_CONFIG = AgentConfig(
+ name="MarketAnalyst",
+ role="market_analyst",
+ description="Analyzes market data and provides insights",
+ tools=["get_market_data", "calculate_technical_indicators", "get_news"],
+ llm_config=LLMConfig(provider=LLMProvider.OPENAI, model="gpt-4", temperature=0.3)
+)
+
+DEFAULT_TRADER_CONFIG = AgentConfig(
+ name="TradingStrategy",
+ role="trader",
+ description="Develops and executes trading strategies",
+ tools=["get_market_data", "place_order", "get_positions", "calculate_technical_indicators"],
+ llm_config=LLMConfig(provider=LLMProvider.ANTHROPIC, model="claude-sonnet-4", temperature=0.5)
+)
+
+DEFAULT_RISK_MANAGER_CONFIG = AgentConfig(
+ name="RiskManager",
+ role="risk_manager",
+ description="Manages portfolio risk and monitors positions",
+ tools=["get_positions", "calculate_var", "get_portfolio_metrics"],
+ llm_config=LLMConfig(provider=LLMProvider.OPENAI, model="gpt-4", temperature=0.2)
+)
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/__init__.py
new file mode 100644
index 000000000..0d22d61b8
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/__init__.py
@@ -0,0 +1,18 @@
+"""
+Core Agno Trading Agent Framework
+
+This module provides the foundational classes for creating and managing
+AI trading agents using the Agno framework.
+"""
+
+from .base_agent import BaseAgent
+from .agent_manager import AgentManager
+from .team_orchestrator import TeamOrchestrator
+from .workflow_engine import WorkflowEngine
+
+__all__ = [
+ 'BaseAgent',
+ 'AgentManager',
+ 'TeamOrchestrator',
+ 'WorkflowEngine',
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/agent_manager.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/agent_manager.py
new file mode 100644
index 000000000..9ed3a369e
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/agent_manager.py
@@ -0,0 +1,375 @@
+"""
+Agent Manager
+
+This module manages the lifecycle of trading agents:
+- Creating and destroying agents
+- Tracking active agents
+- Managing agent resources
+- Agent performance monitoring
+"""
+
+import json
+from typing import Dict, List, Optional, Any
+from datetime import datetime
+from dataclasses import dataclass, asdict
+
+from .base_agent import BaseAgent, AgentConfig
+
+
+@dataclass
+class AgentMetrics:
+ """Performance metrics for an agent"""
+ total_runs: int = 0
+ successful_runs: int = 0
+ failed_runs: int = 0
+ total_tokens_used: int = 0
+ total_cost: float = 0.0
+ average_response_time: float = 0.0
+ last_run_at: Optional[str] = None
+
+
+class AgentManager:
+ """
+ Manages lifecycle and monitoring of trading agents
+
+ Features:
+ - Agent creation and destruction
+ - Agent registry and lookup
+ - Performance metrics tracking
+ - Resource management
+ - Agent health monitoring
+ """
+
+ def __init__(self):
+ """Initialize the agent manager"""
+ self.agents: Dict[str, BaseAgent] = {}
+ self.metrics: Dict[str, AgentMetrics] = {}
+ self.created_at = datetime.now()
+
+ def create_agent(self, config: AgentConfig) -> str:
+ """
+ Create a new trading agent
+
+ Args:
+ config: Agent configuration
+
+ Returns:
+ agent_id: Unique identifier for the created agent
+
+ Raises:
+ ValueError: If agent creation fails
+ """
+ try:
+ # Create agent instance
+ agent = BaseAgent(config)
+
+ # Register agent
+ agent_id = agent.agent_id
+ self.agents[agent_id] = agent
+ self.metrics[agent_id] = AgentMetrics()
+
+ return agent_id
+
+ except Exception as e:
+ raise ValueError(f"Failed to create agent: {str(e)}")
+
+ def get_agent(self, agent_id: str) -> Optional[BaseAgent]:
+ """
+ Get an agent by ID
+
+ Args:
+ agent_id: Agent identifier
+
+ Returns:
+ Agent instance or None if not found
+ """
+ return self.agents.get(agent_id)
+
+ def list_agents(self) -> List[Dict[str, Any]]:
+ """
+ List all active agents
+
+ Returns:
+ List of agent information dictionaries
+ """
+ return [
+ {
+ **agent.to_dict(),
+ "metrics": asdict(self.metrics.get(agent_id, AgentMetrics()))
+ }
+ for agent_id, agent in self.agents.items()
+ ]
+
+ def destroy_agent(self, agent_id: str) -> bool:
+ """
+ Destroy an agent and clean up resources
+
+ Args:
+ agent_id: Agent identifier
+
+ Returns:
+ True if agent was destroyed, False if not found
+ """
+ if agent_id in self.agents:
+ # Clean up agent resources
+ agent = self.agents[agent_id]
+ # Clear all sessions
+ for session_id in list(agent.sessions.keys()):
+ agent.clear_session(session_id)
+
+ # Remove from registry
+ del self.agents[agent_id]
+
+ # Keep metrics for historical tracking
+ # but mark as destroyed
+ if agent_id in self.metrics:
+ self.metrics[agent_id].last_run_at = datetime.now().isoformat()
+
+ return True
+
+ return False
+
+ def run_agent(
+ self,
+ agent_id: str,
+ prompt: str,
+ session_id: Optional[str] = None,
+ stream: bool = False,
+ **kwargs
+ ) -> Dict[str, Any]:
+ """
+ Run an agent with a prompt and track metrics
+
+ Args:
+ agent_id: Agent identifier
+ prompt: User prompt
+ session_id: Optional session ID
+ stream: Whether to stream response
+ **kwargs: Additional parameters
+
+ Returns:
+ Response dictionary with content and metadata
+
+ Raises:
+ ValueError: If agent not found or execution fails
+ """
+ # Get agent
+ agent = self.get_agent(agent_id)
+ if not agent:
+ raise ValueError(f"Agent not found: {agent_id}")
+
+ # Track metrics
+ metrics = self.metrics.get(agent_id, AgentMetrics())
+ start_time = datetime.now()
+
+ try:
+ # Run agent
+ response = agent.run(
+ prompt=prompt,
+ session_id=session_id,
+ stream=stream,
+ **kwargs
+ )
+
+ # Calculate response time
+ end_time = datetime.now()
+ response_time = (end_time - start_time).total_seconds()
+
+ # Update metrics
+ metrics.total_runs += 1
+ metrics.successful_runs += 1
+ metrics.last_run_at = end_time.isoformat()
+
+ # Update average response time
+ if metrics.average_response_time == 0:
+ metrics.average_response_time = response_time
+ else:
+ metrics.average_response_time = (
+ (metrics.average_response_time * (metrics.total_runs - 1) + response_time) /
+ metrics.total_runs
+ )
+
+ # Extract token usage and cost if available
+ if hasattr(response, 'metrics'):
+ if hasattr(response.metrics, 'input_tokens'):
+ metrics.total_tokens_used += response.metrics.input_tokens
+ if hasattr(response.metrics, 'output_tokens'):
+ metrics.total_tokens_used += response.metrics.output_tokens
+
+ self.metrics[agent_id] = metrics
+
+ # Format response
+ result = {
+ "agent_id": agent_id,
+ "session_id": session_id,
+ "content": agent._extract_response_content(response),
+ "response_time": response_time,
+ "timestamp": end_time.isoformat(),
+ "stream": stream,
+ }
+
+ # Add metrics if available
+ if hasattr(response, 'metrics'):
+ result["metrics"] = {
+ "input_tokens": getattr(response.metrics, 'input_tokens', 0),
+ "output_tokens": getattr(response.metrics, 'output_tokens', 0),
+ "total_tokens": getattr(response.metrics, 'total_tokens', 0),
+ }
+
+ return result
+
+ except Exception as e:
+ # Update failure metrics
+ metrics.total_runs += 1
+ metrics.failed_runs += 1
+ metrics.last_run_at = datetime.now().isoformat()
+ self.metrics[agent_id] = metrics
+
+ raise ValueError(f"Agent execution failed: {str(e)}")
+
+ def get_agent_metrics(self, agent_id: str) -> Optional[Dict[str, Any]]:
+ """
+ Get performance metrics for an agent
+
+ Args:
+ agent_id: Agent identifier
+
+ Returns:
+ Metrics dictionary or None if not found
+ """
+ metrics = self.metrics.get(agent_id)
+ if metrics:
+ return asdict(metrics)
+ return None
+
+ def get_session_history(
+ self,
+ agent_id: str,
+ session_id: str
+ ) -> List[Dict[str, Any]]:
+ """
+ Get conversation history for an agent session
+
+ Args:
+ agent_id: Agent identifier
+ session_id: Session identifier
+
+ Returns:
+ List of conversation messages
+ """
+ agent = self.get_agent(agent_id)
+ if agent:
+ return agent.get_session_history(session_id)
+ return []
+
+ def clear_session(self, agent_id: str, session_id: str) -> bool:
+ """
+ Clear a specific agent session
+
+ Args:
+ agent_id: Agent identifier
+ session_id: Session identifier
+
+ Returns:
+ True if session was cleared, False if not found
+ """
+ agent = self.get_agent(agent_id)
+ if agent:
+ agent.clear_session(session_id)
+ return True
+ return False
+
+ def get_manager_stats(self) -> Dict[str, Any]:
+ """
+ Get overall manager statistics
+
+ Returns:
+ Statistics dictionary
+ """
+ total_agents = len(self.agents)
+ total_runs = sum(m.total_runs for m in self.metrics.values())
+ total_successful = sum(m.successful_runs for m in self.metrics.values())
+ total_failed = sum(m.failed_runs for m in self.metrics.values())
+ total_tokens = sum(m.total_tokens_used for m in self.metrics.values())
+ total_cost = sum(m.total_cost for m in self.metrics.values())
+
+ return {
+ "manager_uptime": (datetime.now() - self.created_at).total_seconds(),
+ "total_agents": total_agents,
+ "active_agents": total_agents,
+ "total_runs": total_runs,
+ "successful_runs": total_successful,
+ "failed_runs": total_failed,
+ "success_rate": (total_successful / total_runs * 100) if total_runs > 0 else 0,
+ "total_tokens_used": total_tokens,
+ "total_cost": total_cost,
+ }
+
+ def health_check(self) -> Dict[str, Any]:
+ """
+ Perform health check on all agents
+
+ Returns:
+ Health status dictionary
+ """
+ healthy_agents = []
+ unhealthy_agents = []
+
+ for agent_id, agent in self.agents.items():
+ metrics = self.metrics.get(agent_id, AgentMetrics())
+
+ # Basic health criteria
+ is_healthy = True
+ health_issues = []
+
+ # Check failure rate
+ if metrics.total_runs > 0:
+ failure_rate = metrics.failed_runs / metrics.total_runs
+ if failure_rate > 0.5: # More than 50% failures
+ is_healthy = False
+ health_issues.append(f"High failure rate: {failure_rate:.1%}")
+
+ # Check if agent has been used recently
+ if metrics.last_run_at:
+ # Agent has been used, all good
+ pass
+ elif (datetime.now() - agent.created_at).total_seconds() > 3600:
+ # Agent created more than 1 hour ago but never used
+ health_issues.append("Agent never used")
+
+ agent_health = {
+ "agent_id": agent_id,
+ "name": agent.config.name,
+ "is_healthy": is_healthy,
+ "issues": health_issues,
+ "metrics": asdict(metrics)
+ }
+
+ if is_healthy:
+ healthy_agents.append(agent_health)
+ else:
+ unhealthy_agents.append(agent_health)
+
+ return {
+ "timestamp": datetime.now().isoformat(),
+ "total_agents": len(self.agents),
+ "healthy_count": len(healthy_agents),
+ "unhealthy_count": len(unhealthy_agents),
+ "healthy_agents": healthy_agents,
+ "unhealthy_agents": unhealthy_agents,
+ }
+
+ def __repr__(self) -> str:
+ return f"<AgentManager(agents={len(self.agents)}, uptime={(datetime.now() - self.created_at).total_seconds():.0f}s)>"
+
+
+# Global agent manager instance
+_agent_manager = None
+
+
+def get_agent_manager() -> AgentManager:
+ """Get the global agent manager instance"""
+ global _agent_manager
+ if _agent_manager is None:
+ _agent_manager = AgentManager()
+ return _agent_manager
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/auto_trader.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/auto_trader.py
new file mode 100644
index 000000000..24736a983
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/auto_trader.py
@@ -0,0 +1,408 @@
+"""
+Auto Trading Engine
+
+Implements automatic trading loop inspired by Alpha Arena.
+Executes trades based on AI agent recommendations with safety controls.
+"""
+
+import asyncio
+import json
+from typing import Dict, Any, Optional, List, Callable
+from datetime import datetime, timedelta
+from dataclasses import dataclass, field
+import time
+
+
+@dataclass
+class TradingSignal:
+ """Trading signal from AI agent"""
+ symbol: str
+ direction: str # 'long' or 'short'
+ entry_price: float
+ stop_loss: float
+ take_profit: float
+ position_size: float
+ leverage: float
+ confidence: float # 0.0 to 1.0
+ reasoning: str
+ timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
+
+
+@dataclass
+class SafetyLimits:
+ """Safety limits for auto-trading"""
+ max_position_size: float = 0.1 # 10% of portfolio
+ max_leverage: float = 1.0 # No leverage by default
+ max_drawdown: float = 0.15 # 15% max drawdown
+ max_daily_loss: float = 0.05 # 5% max daily loss
+ min_confidence: float = 0.6 # Minimum confidence to execute
+ max_open_positions: int = 5
+ require_stop_loss: bool = True
+ require_take_profit: bool = True
+
+
+@dataclass
+class TradingState:
+ """Current state of auto-trading"""
+ is_running: bool = False
+ total_trades: int = 0
+ winning_trades: int = 0
+ losing_trades: int = 0
+ total_pnl: float = 0.0
+ current_drawdown: float = 0.0
+ daily_pnl: float = 0.0
+ peak_equity: float = 0.0
+ last_trade_time: Optional[str] = None
+ start_time: Optional[str] = None
+ circuit_breaker_triggered: bool = False
+
+
+class AutoTrader:
+ """
+ Automatic trading engine that executes AI agent recommendations
+
+ Features:
+ - Configurable execution loop (2-3 min like Alpha Arena)
+ - Dynamic TP/SL based on volatility
+ - Position sizing with confidence weighting
+ - Safety limits and circuit breakers
+ - Emergency stop mechanism
+ """
+
+ def __init__(
+ self,
+ agent,
+ execution_interval: int = 180, # 3 minutes like Alpha Arena
+ safety_limits: Optional[SafetyLimits] = None,
+ initial_capital: float = 10000.0
+ ):
+ """
+ Initialize auto-trader
+
+ Args:
+ agent: Trading agent instance
+ execution_interval: Seconds between execution cycles (default 180 = 3 min)
+ safety_limits: Safety configuration
+ initial_capital: Starting capital
+ """
+ self.agent = agent
+ self.execution_interval = execution_interval
+ self.safety_limits = safety_limits or SafetyLimits()
+ self.initial_capital = initial_capital
+ self.current_capital = initial_capital
+
+ self.state = TradingState()
+ self.positions: Dict[str, Dict[str, Any]] = {}
+ self.trade_history: List[Dict[str, Any]] = []
+
+ self.callbacks: Dict[str, Callable] = {}
+ self._stop_requested = False
+
+ def register_callback(self, event: str, callback: Callable):
+ """Register callback for events (trade_executed, position_closed, etc.)"""
+ self.callbacks[event] = callback
+
+ async def start(self):
+ """Start auto-trading loop"""
+ if self.state.is_running:
+ return {"error": "Auto-trader already running"}
+
+ self.state.is_running = True
+ self.state.start_time = datetime.now().isoformat()
+ self.state.peak_equity = self.current_capital
+ self._stop_requested = False
+
+ print(f"[AutoTrader] Starting with ${self.current_capital:.2f} capital")
+ print(f"[AutoTrader] Execution interval: {self.execution_interval}s")
+
+ try:
+ while self.state.is_running and not self._stop_requested:
+ # Check safety limits
+ if self._check_circuit_breaker():
+ self._trigger_emergency_stop("Circuit breaker triggered")
+ break
+
+ # Execute trading cycle
+ await self._execute_cycle()
+
+ # Wait for next cycle
+ await asyncio.sleep(self.execution_interval)
+
+ except Exception as e:
+ print(f"[AutoTrader] Error in trading loop: {e}")
+ self.state.is_running = False
+
+ return {
+ "stopped": True,
+ "total_trades": self.state.total_trades,
+ "final_pnl": self.state.total_pnl
+ }
+
+ def stop(self):
+ """Stop auto-trading gracefully"""
+ print("[AutoTrader] Stop requested")
+ self._stop_requested = True
+ self.state.is_running = False
+
+ def emergency_stop(self):
+ """Emergency stop - close all positions immediately"""
+ print("[AutoTrader] EMERGENCY STOP - Closing all positions")
+ self._close_all_positions()
+ self.stop()
+
+ async def _execute_cycle(self):
+ """Execute one trading cycle (Alpha Arena style)"""
+ try:
+ # 1. Get market data and portfolio state
+ market_data = self._get_market_data()
+ portfolio_state = self._get_portfolio_state()
+
+ # 2. Get AI agent decision
+ prompt = self._build_trading_prompt(market_data, portfolio_state)
+ response = self.agent.run(prompt)
+
+ # 3. Parse signal
+ signal = self._parse_signal(response)
+
+ if not signal:
+ print("[AutoTrader] No signal from agent")
+ return
+
+ # 4. Validate signal against safety limits
+ if not self._validate_signal(signal):
+ print(f"[AutoTrader] Signal rejected by safety checks")
+ return
+
+ # 5. Calculate position size with confidence weighting
+ position_size = self._calculate_position_size(signal)
+
+ # 6. Execute trade
+ await self._execute_trade(signal, position_size)
+
+ # 7. Manage existing positions (check TP/SL)
+ self._manage_positions()
+
+ except Exception as e:
+ print(f"[AutoTrader] Error in cycle: {e}")
+
+ def _build_trading_prompt(self, market_data: Dict, portfolio: Dict) -> str:
+ """Build prompt for agent (Alpha Arena style)"""
+ return f"""
+ You are an autonomous trading agent. Analyze the market and provide a trading decision.
+
+ **Current Market Data:**
+ {json.dumps(market_data, indent=2)}
+
+ **Current Portfolio:**
+ - Capital: ${portfolio.get('capital', 0):.2f}
+ - Open Positions: {portfolio.get('position_count', 0)}
+ - Daily P&L: ${portfolio.get('daily_pnl', 0):.2f}
+ - Total P&L: ${portfolio.get('total_pnl', 0):.2f}
+
+ **Your Task:**
+ Decide whether to:
+ 1. Open a new position (LONG or SHORT)
+ 2. Close existing positions
+ 3. Hold current positions
+
+ **Required Response Format:**
+ {{
+ "action": "long" | "short" | "close" | "hold",
+ "symbol": "BTC/USD",
+ "entry_price": 50000.0,
+ "stop_loss": 48000.0,
+ "take_profit": 55000.0,
+ "position_size_pct": 0.1,
+ "leverage": 1.0,
+ "confidence": 0.75,
+ "reasoning": "Detailed explanation of your decision"
+ }}
+
+ **Important:**
+ - Confidence must be 0.0 to 1.0
+ - Always set stop_loss and take_profit
+ - Consider volatility for TP/SL placement
+ - Max position size: {self.safety_limits.max_position_size * 100}% of capital
+ """
+
+ def _parse_signal(self, response) -> Optional[TradingSignal]:
+ """Parse agent response into trading signal"""
+ try:
+ content = self.agent._extract_response_content(response)
+
+ # Try to extract JSON from response
+ import re
+ json_match = re.search(r'\{[^}]+\}', content, re.DOTALL)
+ if not json_match:
+ return None
+
+ data = json.loads(json_match.group())
+
+ if data.get('action') in ['hold', 'close']:
+ return None
+
+ return TradingSignal(
+ symbol=data.get('symbol', 'BTC/USD'),
+ direction=data['action'],
+ entry_price=data['entry_price'],
+ stop_loss=data['stop_loss'],
+ take_profit=data['take_profit'],
+ position_size=data.get('position_size_pct', 0.05),
+ leverage=data.get('leverage', 1.0),
+ confidence=data.get('confidence', 0.5),
+ reasoning=data.get('reasoning', '')
+ )
+ except Exception as e:
+ print(f"[AutoTrader] Failed to parse signal: {e}")
+ return None
+
+ def _validate_signal(self, signal: TradingSignal) -> bool:
+ """Validate signal against safety limits"""
+
+ # Check confidence
+ if signal.confidence < self.safety_limits.min_confidence:
+ print(f"[AutoTrader] Confidence too low: {signal.confidence}")
+ return False
+
+ # Check position size
+ if signal.position_size > self.safety_limits.max_position_size:
+ print(f"[AutoTrader] Position size too large: {signal.position_size}")
+ return False
+
+ # Check leverage
+ if signal.leverage > self.safety_limits.max_leverage:
+ print(f"[AutoTrader] Leverage too high: {signal.leverage}")
+ return False
+
+ # Check TP/SL required
+ if self.safety_limits.require_stop_loss and not signal.stop_loss:
+ print("[AutoTrader] Stop loss required but not provided")
+ return False
+
+ if self.safety_limits.require_take_profit and not signal.take_profit:
+ print("[AutoTrader] Take profit required but not provided")
+ return False
+
+ # Check max open positions
+ if len(self.positions) >= self.safety_limits.max_open_positions:
+ print("[AutoTrader] Max open positions reached")
+ return False
+
+ return True
+
+ def _calculate_position_size(self, signal: TradingSignal) -> float:
+ """Calculate position size with confidence weighting (Alpha Arena style)"""
+ # Base position size from signal
+ base_size = signal.position_size * self.current_capital
+
+ # Weight by confidence
+ confidence_weighted = base_size * signal.confidence
+
+ # Apply leverage
+ leveraged_size = confidence_weighted * signal.leverage
+
+ # Respect max limits
+ max_size = self.safety_limits.max_position_size * self.current_capital
+
+ return min(leveraged_size, max_size)
+
+ async def _execute_trade(self, signal: TradingSignal, position_size: float):
+ """Execute trade based on signal"""
+ print(f"[AutoTrader] Executing {signal.direction.upper()} on {signal.symbol}")
+ print(f"[AutoTrader] Size: ${position_size:.2f}, Confidence: {signal.confidence:.2f}")
+
+ # In production, this would call actual exchange API
+ # For now, simulate execution
+
+ trade = {
+ "id": f"trade_{self.state.total_trades + 1}",
+ "symbol": signal.symbol,
+ "direction": signal.direction,
+ "entry_price": signal.entry_price,
+ "size": position_size,
+ "stop_loss": signal.stop_loss,
+ "take_profit": signal.take_profit,
+ "confidence": signal.confidence,
+ "opened_at": datetime.now().isoformat(),
+ "status": "open"
+ }
+
+ self.positions[trade['id']] = trade
+ self.trade_history.append(trade)
+ self.state.total_trades += 1
+ self.state.last_trade_time = datetime.now().isoformat()
+
+ # Trigger callback
+ if 'trade_executed' in self.callbacks:
+ self.callbacks['trade_executed'](trade)
+
+ def _manage_positions(self):
+ """Check and manage open positions (TP/SL)"""
+ for trade_id, position in list(self.positions.items()):
+ # In production, get current price from market
+ # For now, simulate price movement
+
+ # Check if TP or SL hit
+ # self._check_exit_conditions(position)
+ pass
+
+ def _check_circuit_breaker(self) -> bool:
+ """Check if circuit breaker should trigger"""
+
+ # Check max drawdown
+ if self.state.current_drawdown >= self.safety_limits.max_drawdown:
+ print(f"[AutoTrader] Max drawdown reached: {self.state.current_drawdown:.2%}")
+ return True
+
+ # Check max daily loss
+ if abs(self.state.daily_pnl) >= self.safety_limits.max_daily_loss * self.initial_capital:
+ print(f"[AutoTrader] Max daily loss reached: ${self.state.daily_pnl:.2f}")
+ return True
+
+ return False
+
+ def _trigger_emergency_stop(self, reason: str):
+ """Trigger emergency stop"""
+ print(f"[AutoTrader] EMERGENCY STOP: {reason}")
+ self.state.circuit_breaker_triggered = True
+ self._close_all_positions()
+ self.stop()
+
+ def _close_all_positions(self):
+ """Close all open positions immediately"""
+ for trade_id in list(self.positions.keys()):
+ print(f"[AutoTrader] Closing position {trade_id}")
+ del self.positions[trade_id]
+
+ def _get_market_data(self) -> Dict:
+ """Get current market data"""
+ # In production, fetch from exchange
+ return {
+ "symbol": "BTC/USD",
+ "price": 50000.0,
+ "timestamp": datetime.now().isoformat()
+ }
+
+ def _get_portfolio_state(self) -> Dict:
+ """Get current portfolio state"""
+ return {
+ "capital": self.current_capital,
+ "position_count": len(self.positions),
+ "daily_pnl": self.state.daily_pnl,
+ "total_pnl": self.state.total_pnl
+ }
+
+ def get_state(self) -> Dict[str, Any]:
+ """Get current auto-trader state"""
+ return {
+ "is_running": self.state.is_running,
+ "total_trades": self.state.total_trades,
+ "winning_trades": self.state.winning_trades,
+ "losing_trades": self.state.losing_trades,
+ "win_rate": (self.state.winning_trades / self.state.total_trades * 100) if self.state.total_trades > 0 else 0,
+ "total_pnl": self.state.total_pnl,
+ "current_drawdown": self.state.current_drawdown,
+ "daily_pnl": self.state.daily_pnl,
+ "open_positions": len(self.positions),
+ "circuit_breaker": self.state.circuit_breaker_triggered
+ }
diff --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.py
new file mode 100644
index 000000000..24f9f74b1
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/base_agent.py
@@ -0,0 +1,354 @@
+"""
+Base Agent Class
+
+This module implements the base trading agent class using the Agno framework.
+All specialized trading agents inherit from this base class.
+"""
+
+import os
+import json
+from typing import List, Optional, Dict, Any, Union
+from datetime import datetime
+from dataclasses import dataclass, field
+
+try:
+ from agno.agent import Agent
+ from agno.models.response import ModelResponse
+ from agno.tools.toolkit import Toolkit
+ from agno.knowledge import Knowledge
+ from agno.memory import MemoryManager
+ AGNO_AVAILABLE = True
+except ImportError:
+ AGNO_AVAILABLE = False
+ # Fallback types for when Agno is not installed
+ Agent = None
+ ModelResponse = None
+ Toolkit = None
+ Knowledge = None
+ MemoryManager = None
+
+
+@dataclass
+class AgentConfig:
+ """Configuration for a trading agent"""
+ name: str
+ role: str
+ description: str
+ instructions: List[str] = field(default_factory=list)
+
+ # LLM Configuration
+ model_provider: str = "openai"
+ model_name: str = "gpt-4o-mini"
+ temperature: float = 0.7
+ max_tokens: Optional[int] = 4096
+
+ # Agent Capabilities
+ tools: List[str] = field(default_factory=list)
+ enable_knowledge: bool = False
+ enable_memory: bool = False
+
+ # Trading Configuration
+ symbols: List[str] = field(default_factory=lambda: ["BTC/USD"])
+ risk_tolerance: str = "moderate" # conservative, moderate, aggressive
+
+ # Behavior
+ show_tool_calls: bool = True
+ markdown: bool = True
+ stream: bool = False
+
+ # Advanced
+ reasoning_effort: Optional[str] = None # For o1/o3/o4 models
+ structured_outputs: bool = False
+ response_format: Optional[Dict[str, Any]] = None
+
+
+class BaseAgent:
+ """
+ Base Trading Agent using Agno framework
+
+ This class provides common functionality for all trading agents:
+ - Agent initialization with LLM configuration
+ - Tool registration and execution
+ - Knowledge base integration
+ - Memory management
+ - Session handling
+ - Response streaming
+ """
+
+ def __init__(self, config: AgentConfig):
+ """
+ Initialize the base trading agent
+
+ Args:
+ config: Agent configuration object
+ """
+ if not AGNO_AVAILABLE:
+ raise ImportError(
+ "Agno framework is not installed. "
+ "Install it with: pip install agno>=0.3.0"
+ )
+
+ self.config = config
+ self.agent_id = f"{config.name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
+ self.created_at = datetime.now()
+
+ # Initialize LLM model
+ self.model = self._initialize_model()
+
+ # Initialize tools
+ self.tools = self._initialize_tools()
+
+ # Initialize knowledge base
+ self.knowledge = self._initialize_knowledge() if config.enable_knowledge else None
+
+ # Initialize memory
+ self.memory = self._initialize_memory() if config.enable_memory else None
+
+ # Create Agno agent
+ self.agent = self._create_agent()
+
+ # Session tracking
+ self.sessions: Dict[str, List[Dict[str, Any]]] = {}
+
+ def _initialize_model(self) -> Any:
+ """Initialize the LLM model based on configuration"""
+ provider = self.config.model_provider.lower()
+ model_name = self.config.model_name
+
+ # Get API key from environment
+ api_key_map = {
+ "openai": os.getenv("OPENAI_API_KEY"),
+ "anthropic": os.getenv("ANTHROPIC_API_KEY"),
+ "google": os.getenv("GOOGLE_API_KEY"),
+ "groq": os.getenv("GROQ_API_KEY"),
+ "deepseek": os.getenv("DEEPSEEK_API_KEY"),
+ "xai": os.getenv("XAI_API_KEY"),
+ "cohere": os.getenv("COHERE_API_KEY"),
+ "mistral": os.getenv("MISTRAL_API_KEY"),
+ "together": os.getenv("TOGETHER_API_KEY"),
+ "fireworks": os.getenv("FIREWORKS_API_KEY"),
+ }
+
+ api_key = api_key_map.get(provider)
+
+ # Model configuration
+ model_config = {
+ "id": model_name,
+ "api_key": api_key,
+ }
+
+ # Add optional parameters
+ if self.config.reasoning_effort:
+ model_config["reasoning_effort"] = self.config.reasoning_effort
+
+ # Provider-specific model initialization
+ if provider == "openai":
+ from agno.models.openai import OpenAIChat
+ return OpenAIChat(**model_config)
+ elif provider == "anthropic":
+ from agno.models.anthropic import Claude
+ return Claude(**model_config)
+ elif provider == "google":
+ from agno.models.google import Gemini
+ return Gemini(**model_config)
+ elif provider == "groq":
+ from agno.models.groq import Groq
+ return Groq(**model_config)
+ elif provider == "deepseek":
+ from agno.models.openai import OpenAIChat
+ return OpenAIChat(
+ id=model_name,
+ api_key=api_key,
+ base_url="https://api.deepseek.com"
+ )
+ elif provider == "xai":
+ from agno.models.openai import OpenAIChat
+ return OpenAIChat(
+ id=model_name,
+ api_key=api_key,
+ base_url="https://api.x.ai/v1"
+ )
+ elif provider == "ollama":
+ from agno.models.ollama import Ollama
+ return Ollama(id=model_name)
+ else:
+ # Default to OpenAI-compatible
+ from agno.models.openai import OpenAIChat
+ return OpenAIChat(**model_config)
+
+ def _initialize_tools(self) -> List[Any]:
+ """Initialize agent tools based on configuration"""
+ tools = []
+
+ # Tool registry mapping
+ tool_registry = {
+ "market_data": self._get_market_data_tools,
+ "technical_analysis": self._get_technical_analysis_tools,
+ "order_execution": self._get_order_execution_tools,
+ "portfolio": self._get_portfolio_tools,
+ "news_sentiment": self._get_news_sentiment_tools,
+ }
+
+ # Load configured tools
+ for tool_name in self.config.tools:
+ if tool_name in tool_registry:
+ tool_fn = tool_registry[tool_name]
+ tools.extend(tool_fn())
+
+ return tools
+
+ def _get_market_data_tools(self) -> List[Any]:
+ """Get market data tools"""
+ # Placeholder - will be implemented in tools/market_data.py
+ return []
+
+ def _get_technical_analysis_tools(self) -> List[Any]:
+ """Get technical analysis tools"""
+ # Placeholder - will be implemented in tools/technical_indicators.py
+ return []
+
+ def _get_order_execution_tools(self) -> List[Any]:
+ """Get order execution tools"""
+ # Placeholder - will be implemented in tools/order_execution.py
+ return []
+
+ def _get_portfolio_tools(self) -> List[Any]:
+ """Get portfolio management tools"""
+ # Placeholder - will be implemented in tools/portfolio_tools.py
+ return []
+
+ def _get_news_sentiment_tools(self) -> List[Any]:
+ """Get news and sentiment tools"""
+ # Placeholder - will be implemented in tools/news_sentiment.py
+ return []
+
+ def _initialize_knowledge(self) -> Optional[Knowledge]:
+ """Initialize knowledge base for the agent"""
+ if not self.config.enable_knowledge:
+ return None
+
+ # Will be implemented with proper vector DB configuration
+ # from agno.knowledge.lancedb import LanceDBKnowledge
+ # return LanceDBKnowledge(...)
+ return None
+
+ def _initialize_memory(self) -> Optional[MemoryManager]:
+ """Initialize memory for the agent"""
+ if not self.config.enable_memory:
+ return None
+
+ # Will be implemented with proper database configuration
+ # from agno.memory.db.sqlite import SqliteMemory
+ # return SqliteMemory(...)
+ return None
+
+ def _create_agent(self) -> Agent:
+ """Create the Agno agent instance"""
+ agent_params = {
+ "name": self.config.name,
+ "role": self.config.role,
+ "model": self.model,
+ "description": self.config.description,
+ "instructions": self.config.instructions,
+ "tools": self.tools if self.tools else None,
+ "knowledge": self.knowledge,
+ "memory": self.memory,
+ "show_tool_calls": self.config.show_tool_calls,
+ "markdown": self.config.markdown,
+ }
+
+ # Add optional parameters
+ if self.config.structured_outputs:
+ agent_params["structured_outputs"] = True
+
+ if self.config.response_format:
+ agent_params["response_format"] = self.config.response_format
+
+ return Agent(**agent_params)
+
+ def run(
+ self,
+ prompt: str,
+ session_id: Optional[str] = None,
+ stream: bool = False,
+ **kwargs
+ ) -> Union[ModelResponse, Any]:
+ """
+ Run the agent with a prompt
+
+ Args:
+ prompt: User prompt/query
+ session_id: Optional session ID for conversation continuity
+ stream: Whether to stream the response
+ **kwargs: Additional parameters to pass to agent.run()
+
+ Returns:
+ ModelResponse object or streaming response
+ """
+ # Track in session
+ if session_id:
+ if session_id not in self.sessions:
+ self.sessions[session_id] = []
+ self.sessions[session_id].append({
+ "timestamp": datetime.now().isoformat(),
+ "prompt": prompt,
+ "type": "user"
+ })
+
+ # Run agent
+ run_params = {
+ "message": prompt,
+ "stream": stream or self.config.stream,
+ **kwargs
+ }
+
+ if session_id:
+ run_params["session_id"] = session_id
+
+ response = self.agent.run(**run_params)
+
+ # Track response in session
+ if session_id and not stream:
+ self.sessions[session_id].append({
+ "timestamp": datetime.now().isoformat(),
+ "response": self._extract_response_content(response),
+ "type": "assistant"
+ })
+
+ return response
+
+ def _extract_response_content(self, response: ModelResponse) -> str:
+ """Extract content from ModelResponse"""
+ if hasattr(response, 'content'):
+ return response.content
+ elif hasattr(response, 'message'):
+ return response.message
+ else:
+ return str(response)
+
+ def get_session_history(self, session_id: str) -> List[Dict[str, Any]]:
+ """Get conversation history for a session"""
+ return self.sessions.get(session_id, [])
+
+ def clear_session(self, session_id: str) -> None:
+ """Clear a specific session"""
+ if session_id in self.sessions:
+ del self.sessions[session_id]
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert agent to dictionary representation"""
+ return {
+ "agent_id": self.agent_id,
+ "name": self.config.name,
+ "role": self.config.role,
+ "description": self.config.description,
+ "model_provider": self.config.model_provider,
+ "model_name": self.config.model_name,
+ "tools": self.config.tools,
+ "symbols": self.config.symbols,
+ "created_at": self.created_at.isoformat(),
+ "active_sessions": len(self.sessions),
+ }
+
+ def __repr__(self) -> str:
+ return f"<BaseAgent(id={self.agent_id}, name={self.config.name}, role={self.config.role})>"
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.py
new file mode 100644
index 000000000..e9b1990cb
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/team_orchestrator.py
@@ -0,0 +1,316 @@
+"""
+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.0
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/workflow_engine.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/workflow_engine.py
new file mode 100644
index 000000000..1cf31e1ef
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/core/workflow_engine.py
@@ -0,0 +1,147 @@
+"""
+Workflow Engine
+
+This module manages deterministic trading workflows.
+"""
+
+from typing import List, Dict, Any, Optional, Callable
+from datetime import datetime
+from dataclasses import dataclass
+
+
+@dataclass
+class WorkflowStep:
+ """A single step in a workflow"""
+ name: str
+ function: Callable
+ inputs: Dict[str, Any]
+ outputs: List[str]
+ condition: Optional[Callable] = None
+
+
+class WorkflowEngine:
+ """
+ Executes deterministic trading workflows
+
+ Features:
+ - Sequential step execution
+ - Conditional branching
+ - Error handling and recovery
+ - State persistence
+ """
+
+ def __init__(self):
+ """Initialize workflow engine"""
+ self.workflows: Dict[str, List[WorkflowStep]] = {}
+ self.execution_history: List[Dict[str, Any]] = []
+ self.created_at = datetime.now()
+
+ def create_workflow(
+ self,
+ name: str,
+ steps: List[WorkflowStep]
+ ) -> str:
+ """
+ Create a new workflow
+
+ Args:
+ name: Workflow name
+ steps: List of workflow steps
+
+ Returns:
+ workflow_id: Unique workflow identifier
+ """
+ workflow_id = f"workflow_{name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
+ self.workflows[workflow_id] = steps
+ return workflow_id
+
+ def execute_workflow(
+ self,
+ workflow_id: str,
+ initial_inputs: Dict[str, Any] = None
+ ) -> Dict[str, Any]:
+ """
+ Execute a workflow
+
+ Args:
+ workflow_id: Workflow identifier
+ initial_inputs: Initial workflow inputs
+
+ Returns:
+ Workflow execution result
+ """
+ if workflow_id not in self.workflows:
+ raise ValueError(f"Workflow not found: {workflow_id}")
+
+ steps = self.workflows[workflow_id]
+ state = initial_inputs or {}
+ results = []
+
+ start_time = datetime.now()
+
+ try:
+ for step in steps:
+ # Check condition if exists
+ if step.condition and not step.condition(state):
+ continue
+
+ # Execute step
+ step_result = step.function(**{**step.inputs, **state})
+
+ # Update state with outputs
+ for output_key in step.outputs:
+ if output_key in step_result:
+ state[output_key] = step_result[output_key]
+
+ results.append({
+ "step": step.name,
+ "status": "completed",
+ "result": step_result
+ })
+
+ end_time = datetime.now()
+ execution_time = (end_time - start_time).total_seconds()
+
+ execution = {
+ "workflow_id": workflow_id,
+ "status": "completed",
+ "execution_time": execution_time,
+ "steps": results,
+ "final_state": state,
+ "timestamp": end_time.isoformat()
+ }
+
+ self.execution_history.append(execution)
+
+ return execution
+
+ except Exception as e:
+ return {
+ "workflow_id": workflow_id,
+ "status": "failed",
+ "error": str(e),
+ "steps": results,
+ "timestamp": datetime.now().isoformat()
+ }
+
+
+# Example workflow patterns for trading:
+# 1. Market Analysis Workflow:
+# - Fetch market data
+# - Calculate indicators
+# - Analyze patterns
+# - Generate insights
+#
+# 2. Signal Generation Workflow:
+# - Market analysis
+# - Strategy evaluation
+# - Signal generation
+# - Risk assessment
+# - Order preparation
+#
+# 3. Risk Management Workflow:
+# - Portfolio evaluation
+# - Position sizing
+# - Stop loss calculation
+# - Exposure analysis
+# - Rebalancing recommendations
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/requirements.txt b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/requirements.txt
new file mode 100644
index 000000000..ea1531e2f
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/requirements.txt
@@ -0,0 +1,31 @@
+# Agno Trading Agent Requirements
+# Install with: pip install -r requirements.txt
+
+# Core Agno Framework
+agno>=0.3.0
+
+# LLM Providers
+openai>=1.0.0
+anthropic>=0.21.0
+google-generativeai>=0.4.0
+groq>=0.4.0
+cohere>=5.0.0
+
+# Vector Databases & Embeddings
+lancedb>=0.6.0
+chromadb>=0.4.0
+sentence-transformers>=2.0.0
+
+# Data Processing
+pandas>=2.0.0
+numpy>=1.24.0
+pytz>=2023.0
+
+# Market Data & Trading
+ccxt>=4.0.0
+yfinance>=0.2.0
+
+# Utilities
+python-dotenv>=1.0.0
+pydantic>=2.0.0
+httpx>=0.24.0
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/__init__.py
new file mode 100644
index 000000000..856a1abc4
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/__init__.py
@@ -0,0 +1,20 @@
+"""
+Trading Tools
+
+This module provides tools that agents can use to interact with markets,
+execute trades, analyze data, and access information.
+"""
+
+from .market_data import get_market_data_tools
+from .technical_indicators import get_technical_analysis_tools
+from .order_execution import get_order_execution_tools
+from .portfolio_tools import get_portfolio_tools
+from .news_sentiment import get_news_sentiment_tools
+
+__all__ = [
+ 'get_market_data_tools',
+ 'get_technical_analysis_tools',
+ 'get_order_execution_tools',
+ 'get_portfolio_tools',
+ 'get_news_sentiment_tools',
+]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/market_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/market_data.py
new file mode 100644
index 000000000..f80aaecfe
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/market_data.py
@@ -0,0 +1,262 @@
+"""
+Market Data Tools
+
+Provides tools for agents to fetch real-time and historical market data.
+Integrates with existing Fincept Terminal data sources.
+"""
+
+import json
+from typing import List, Dict, Any, Optional
+from datetime import datetime, timedelta
+
+try:
+ import yfinance as yf
+ YFINANCE_AVAILABLE = True
+except ImportError:
+ YFINANCE_AVAILABLE = False
+
+try:
+ import ccxt
+ CCXT_AVAILABLE = True
+except ImportError:
+ CCXT_AVAILABLE = False
+
+
+def get_current_price(symbol: str, exchange: str = "binance") -> Dict[str, Any]:
+ """
+ Get current price for a symbol
+
+ Args:
+ symbol: Trading symbol (e.g., "BTC/USDT", "AAPL")
+ exchange: Exchange name (default: binance)
+
+ Returns:
+ Dictionary with price information
+ """
+ try:
+ # Try crypto first with CCXT
+ if CCXT_AVAILABLE and "/" in symbol:
+ exchange_obj = getattr(ccxt, exchange)()
+ ticker = exchange_obj.fetch_ticker(symbol)
+
+ return {
+ "symbol": symbol,
+ "exchange": exchange,
+ "price": ticker['last'],
+ "bid": ticker['bid'],
+ "ask": ticker['ask'],
+ "high_24h": ticker['high'],
+ "low_24h": ticker['low'],
+ "volume_24h": ticker['baseVolume'],
+ "timestamp": datetime.now().isoformat(),
+ "source": "ccxt"
+ }
+
+ # Try stock with yfinance
+ elif YFINANCE_AVAILABLE:
+ ticker = yf.Ticker(symbol)
+ info = ticker.info
+
+ return {
+ "symbol": symbol,
+ "price": info.get('currentPrice') or info.get('regularMarketPrice'),
+ "bid": info.get('bid'),
+ "ask": info.get('ask'),
+ "open": info.get('regularMarketOpen'),
+ "high": info.get('dayHigh'),
+ "low": info.get('dayLow'),
+ "volume": info.get('volume'),
+ "market_cap": info.get('marketCap'),
+ "timestamp": datetime.now().isoformat(),
+ "source": "yfinance"
+ }
+
+ else:
+ return {"error": "No market data library available. Install yfinance or ccxt."}
+
+ except Exception as e:
+ return {"error": f"Failed to fetch price: {str(e)}"}
+
+
+def get_historical_data(
+ symbol: str,
+ period: str = "1mo",
+ interval: str = "1d",
+ exchange: str = "binance"
+) -> Dict[str, Any]:
+ """
+ Get historical price data
+
+ Args:
+ symbol: Trading symbol
+ period: Time period (1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max)
+ interval: Data interval (1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo)
+ exchange: Exchange name for crypto
+
+ Returns:
+ Dictionary with historical data
+ """
+ try:
+ if YFINANCE_AVAILABLE:
+ ticker = yf.Ticker(symbol)
+ hist = ticker.history(period=period, interval=interval)
+
+ if hist.empty:
+ return {"error": "No historical data available"}
+
+ return {
+ "symbol": symbol,
+ "period": period,
+ "interval": interval,
+ "data": hist.to_dict('records'),
+ "count": len(hist),
+ "timestamp": datetime.now().isoformat(),
+ "source": "yfinance"
+ }
+
+ else:
+ return {"error": "yfinance not available. Install with: pip install yfinance"}
+
+ except Exception as e:
+ return {"error": f"Failed to fetch historical data: {str(e)}"}
+
+
+def get_market_summary(symbols: List[str]) -> Dict[str, Any]:
+ """
+ Get market summary for multiple symbols
+
+ Args:
+ symbols: List of symbols to fetch
+
+ Returns:
+ Dictionary with summary data for all symbols
+ """
+ summary = {
+ "timestamp": datetime.now().isoformat(),
+ "symbols": {},
+ "errors": []
+ }
+
+ for symbol in symbols:
+ try:
+ price_data = get_current_price(symbol)
+ if "error" not in price_data:
+ summary["symbols"][symbol] = price_data
+ else:
+ summary["errors"].append(f"{symbol}: {price_data['error']}")
+ except Exception as e:
+ summary["errors"].append(f"{symbol}: {str(e)}")
+
+ return summary
+
+
+def get_ohlcv_data(
+ symbol: str,
+ timeframe: str = "1d",
+ limit: int = 100,
+ exchange: str = "binance"
+) -> Dict[str, Any]:
+ """
+ Get OHLCV (Open, High, Low, Close, Volume) data
+
+ Args:
+ symbol: Trading symbol
+ timeframe: Timeframe (1m, 5m, 15m, 1h, 4h, 1d, 1w)
+ limit: Number of candles to fetch
+ exchange: Exchange name
+
+ Returns:
+ Dictionary with OHLCV data
+ """
+ try:
+ if CCXT_AVAILABLE and "/" in symbol:
+ exchange_obj = getattr(ccxt, exchange)()
+ ohlcv = exchange_obj.fetch_ohlcv(symbol, timeframe, limit=limit)
+
+ # Format data
+ formatted_data = []
+ for candle in ohlcv:
+ formatted_data.append({
+ "timestamp": candle[0],
+ "datetime": datetime.fromtimestamp(candle[0] / 1000).isoformat(),
+ "open": candle[1],
+ "high": candle[2],
+ "low": candle[3],
+ "close": candle[4],
+ "volume": candle[5]
+ })
+
+ return {
+ "symbol": symbol,
+ "timeframe": timeframe,
+ "exchange": exchange,
+ "data": formatted_data,
+ "count": len(formatted_data),
+ "source": "ccxt"
+ }
+
+ else:
+ return {"error": "CCXT not available or invalid symbol format"}
+
+ except Exception as e:
+ return {"error": f"Failed to fetch OHLCV data: {str(e)}"}
+
+
+def get_orderbook(symbol: str, exchange: str = "binance", limit: int = 20) -> Dict[str, Any]:
+ """
+ Get current order book
+
+ Args:
+ symbol: Trading symbol
+ exchange: Exchange name
+ limit: Number of orders to fetch per side
+
+ Returns:
+ Dictionary with orderbook data
+ """
+ try:
+ if CCXT_AVAILABLE:
+ exchange_obj = getattr(ccxt, exchange)()
+ orderbook = exchange_obj.fetch_order_book(symbol, limit=limit)
+
+ return {
+ "symbol": symbol,
+ "exchange": exchange,
+ "bids": orderbook['bids'][:limit],
+ "asks": orderbook['asks'][:limit],
+ "timestamp": orderbook.get('timestamp'),
+ "datetime": orderbook.get('datetime'),
+ "source": "ccxt"
+ }
+
+ else:
+ return {"error": "CCXT not available"}
+
+ except Exception as e:
+ return {"error": f"Failed to fetch orderbook: {str(e)}"}
+
+
+def get_market_data_tools() -> List[Any]:
+ """
+ Get list of market data tools for Agno agents
+
+ Returns:
+ List of tool functions
+ """
+ return [
+ get_current_price,
+ get_historical_data,
+ get_market_summary,
+ get_ohlcv_data,
+ get_orderbook,
+ ]
+
+
+# Tool descriptions for LLM
+TOOL_DESCRIPTIONS = {
+ "get_current_price": "Get the current market price for a symbol. Supports both crypto (BTC/USDT) and stocks (AAPL).",
+ "get_historical_data": "Fetch historical price data for analysis. Supports various time periods and intervals.",
+ "get_market_summary": "Get a quick summary of multiple symbols at once for market overview.",
+ "get_ohlcv_data": "Get OHLCV candlestick data for charting and technical analysis.",
+ "get_orderbook": "View the current order book to analyze market depth and liquidity.",
+}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/news_sentiment.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/news_sentiment.py
new file mode 100644
index 000000000..7d82eb1d7
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/news_sentiment.py
@@ -0,0 +1,96 @@
+"""
+News and Sentiment Analysis Tools
+
+Provides tools for fetching news and analyzing market sentiment.
+"""
+
+from typing import List, Dict, Any, Optional
+from datetime import datetime, timedelta
+
+
+def get_news(
+ symbol: str,
+ limit: int = 10,
+ source: str = "general"
+) -> Dict[str, Any]:
+ """
+ Get news articles for a symbol
+
+ Args:
+ symbol: Trading symbol
+ limit: Number of articles to fetch
+ source: News source
+
+ Returns:
+ News articles
+ """
+ # Placeholder - will integrate with actual news APIs
+ return {
+ "symbol": symbol,
+ "articles": [],
+ "count": 0,
+ "message": "News API integration pending. Will support NewsAPI, Benzinga, etc.",
+ "timestamp": datetime.now().isoformat()
+ }
+
+
+def analyze_sentiment(text: str) -> Dict[str, Any]:
+ """
+ Analyze sentiment of text
+
+ Args:
+ text: Text to analyze
+
+ Returns:
+ Sentiment analysis results
+ """
+ # Placeholder - will integrate with sentiment analysis
+ return {
+ "text_length": len(text),
+ "sentiment": "neutral",
+ "score": 0.0,
+ "confidence": 0.0,
+ "message": "Sentiment analysis integration pending. Will support TextBlob, VADER, or LLM-based analysis.",
+ "timestamp": datetime.now().isoformat()
+ }
+
+
+def get_market_sentiment(
+ symbol: str,
+ sources: List[str] = ["news", "social"]
+) -> Dict[str, Any]:
+ """
+ Get overall market sentiment for a symbol
+
+ Args:
+ symbol: Trading symbol
+ sources: List of sources to analyze
+
+ Returns:
+ Aggregated sentiment
+ """
+ return {
+ "symbol": symbol,
+ "sources": sources,
+ "overall_sentiment": "neutral",
+ "sentiment_score": 0.0,
+ "confidence": 0.0,
+ "message": "Market sentiment aggregation pending.",
+ "timestamp": datetime.now().isoformat()
+ }
+
+
+def get_news_sentiment_tools() -> List[Any]:
+ """Get news and sentiment tools"""
+ return [
+ get_news,
+ analyze_sentiment,
+ get_market_sentiment,
+ ]
+
+
+TOOL_DESCRIPTIONS = {
+ "get_news": "Fetch recent news articles for a symbol from various sources.",
+ "analyze_sentiment": "Analyze the sentiment (positive, negative, neutral) of a text.",
+ "get_market_sentiment": "Get aggregated market sentiment from news and social media sources.",
+}
diff --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.py
new file mode 100644
index 000000000..0dd03b074
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/order_execution.py
@@ -0,0 +1,111 @@
+"""
+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/tools/portfolio_tools.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/portfolio_tools.py
new file mode 100644
index 000000000..0ebfdd122
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/portfolio_tools.py
@@ -0,0 +1,184 @@
+"""
+Portfolio Management Tools
+
+Provides tools for portfolio analysis and management.
+"""
+
+from typing import List, Dict, Any, Optional
+from datetime import datetime
+import math
+
+
+def calculate_portfolio_metrics(
+ positions: List[Dict[str, Any]],
+ initial_capital: float = 10000.0
+) -> Dict[str, Any]:
+ """
+ Calculate portfolio performance metrics
+
+ Args:
+ positions: List of positions with symbol, quantity, entry_price, current_price
+ initial_capital: Initial portfolio capital
+
+ Returns:
+ Portfolio metrics including returns, sharpe ratio, etc.
+ """
+ try:
+ total_value = 0
+ total_pnl = 0
+ total_pnl_pct = 0
+
+ position_details = []
+
+ for pos in positions:
+ quantity = pos.get('quantity', 0)
+ entry_price = pos.get('entry_price', 0)
+ current_price = pos.get('current_price', 0)
+
+ position_value = quantity * current_price
+ position_cost = quantity * entry_price
+ position_pnl = position_value - position_cost
+ position_pnl_pct = (position_pnl / position_cost * 100) if position_cost > 0 else 0
+
+ total_value += position_value
+ total_pnl += position_pnl
+
+ position_details.append({
+ "symbol": pos.get('symbol'),
+ "quantity": quantity,
+ "entry_price": entry_price,
+ "current_price": current_price,
+ "value": position_value,
+ "cost": position_cost,
+ "pnl": position_pnl,
+ "pnl_pct": position_pnl_pct
+ })
+
+ total_return_pct = (total_pnl / initial_capital * 100) if initial_capital > 0 else 0
+
+ return {
+ "total_value": total_value,
+ "total_pnl": total_pnl,
+ "total_return_pct": total_return_pct,
+ "position_count": len(positions),
+ "positions": position_details,
+ "timestamp": datetime.now().isoformat()
+ }
+
+ except Exception as e:
+ return {"error": f"Portfolio metrics calculation failed: {str(e)}"}
+
+
+def calculate_position_size(
+ account_balance: float,
+ risk_per_trade: float,
+ entry_price: float,
+ stop_loss_price: float
+) -> Dict[str, Any]:
+ """
+ Calculate optimal position size based on risk management
+
+ Args:
+ account_balance: Total account balance
+ risk_per_trade: Risk percentage per trade (e.g., 0.02 for 2%)
+ entry_price: Planned entry price
+ stop_loss_price: Stop loss price
+
+ Returns:
+ Recommended position size
+ """
+ try:
+ risk_amount = account_balance * risk_per_trade
+ price_risk = abs(entry_price - stop_loss_price)
+
+ if price_risk == 0:
+ return {"error": "Entry price and stop loss cannot be the same"}
+
+ position_size = risk_amount / price_risk
+ position_value = position_size * entry_price
+ position_pct = (position_value / account_balance * 100) if account_balance > 0 else 0
+
+ return {
+ "position_size": position_size,
+ "position_value": position_value,
+ "position_pct": position_pct,
+ "risk_amount": risk_amount,
+ "risk_pct": risk_per_trade * 100,
+ "entry_price": entry_price,
+ "stop_loss_price": stop_loss_price,
+ "price_risk": price_risk
+ }
+
+ except Exception as e:
+ return {"error": f"Position size calculation failed: {str(e)}"}
+
+
+def analyze_portfolio_risk(
+ positions: List[Dict[str, Any]],
+ correlations: Optional[Dict[str, float]] = None
+) -> Dict[str, Any]:
+ """
+ Analyze portfolio risk and diversification
+
+ Args:
+ positions: List of positions
+ correlations: Optional correlation matrix
+
+ Returns:
+ Risk analysis
+ """
+ try:
+ total_value = sum(pos.get('value', 0) for pos in positions)
+
+ # Calculate concentration
+ concentrations = []
+ for pos in positions:
+ value = pos.get('value', 0)
+ concentration = (value / total_value * 100) if total_value > 0 else 0
+ concentrations.append({
+ "symbol": pos.get('symbol'),
+ "value": value,
+ "concentration_pct": concentration
+ })
+
+ # Find max concentration
+ max_concentration = max(concentrations, key=lambda x: x['concentration_pct']) if concentrations else None
+
+ # Assess diversification
+ diversification_score = 0
+ if len(positions) >= 10:
+ diversification_score = 100
+ elif len(positions) >= 5:
+ diversification_score = 75
+ elif len(positions) >= 3:
+ diversification_score = 50
+ else:
+ diversification_score = 25
+
+ return {
+ "total_value": total_value,
+ "position_count": len(positions),
+ "concentrations": concentrations,
+ "max_concentration": max_concentration,
+ "diversification_score": diversification_score,
+ "risk_level": "High" if (max_concentration and max_concentration['concentration_pct'] > 30) else "Medium" if (max_concentration and max_concentration['concentration_pct'] > 20) else "Low"
+ }
+
+ except Exception as e:
+ return {"error": f"Risk analysis failed: {str(e)}"}
+
+
+def get_portfolio_tools() -> List[Any]:
+ """Get portfolio management tools"""
+ return [
+ calculate_portfolio_metrics,
+ calculate_position_size,
+ analyze_portfolio_risk,
+ ]
+
+
+TOOL_DESCRIPTIONS = {
+ "calculate_portfolio_metrics": "Calculate comprehensive portfolio metrics including total value, P&L, and returns.",
+ "calculate_position_size": "Calculate optimal position size based on risk management rules and stop loss.",
+ "analyze_portfolio_risk": "Analyze portfolio risk, concentration, and diversification levels.",
+}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/technical_indicators.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/technical_indicators.py
new file mode 100644
index 000000000..c370b9643
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/tools/technical_indicators.py
@@ -0,0 +1,376 @@
+"""
+Technical Analysis Tools
+
+Provides technical indicators and analysis tools for trading agents.
+"""
+
+import json
+from typing import List, Dict, Any, Optional
+import math
+
+try:
+ import pandas as pd
+ import numpy as np
+ PANDAS_AVAILABLE = True
+except ImportError:
+ PANDAS_AVAILABLE = False
+
+try:
+ import talib
+ TALIB_AVAILABLE = True
+except ImportError:
+ TALIB_AVAILABLE = False
+
+
+def calculate_sma(prices: List[float], period: int = 20) -> Dict[str, Any]:
+ """
+ Calculate Simple Moving Average
+
+ Args:
+ prices: List of prices
+ period: Period for SMA calculation
+
+ Returns:
+ Dictionary with SMA values
+ """
+ try:
+ if not PANDAS_AVAILABLE:
+ # Manual calculation
+ if len(prices) < period:
+ return {"error": f"Not enough data. Need at least {period} prices."}
+
+ sma_values = []
+ for i in range(len(prices) - period + 1):
+ window = prices[i:i+period]
+ sma = sum(window) / period
+ sma_values.append(sma)
+
+ return {
+ "indicator": "SMA",
+ "period": period,
+ "values": sma_values,
+ "current": sma_values[-1] if sma_values else None,
+ "count": len(sma_values)
+ }
+
+ else:
+ # Use pandas
+ series = pd.Series(prices)
+ sma = series.rolling(window=period).mean()
+
+ return {
+ "indicator": "SMA",
+ "period": period,
+ "values": sma.dropna().tolist(),
+ "current": float(sma.iloc[-1]) if not pd.isna(sma.iloc[-1]) else None,
+ "count": len(sma.dropna())
+ }
+
+ except Exception as e:
+ return {"error": f"SMA calculation failed: {str(e)}"}
+
+
+def calculate_ema(prices: List[float], period: int = 20) -> Dict[str, Any]:
+ """
+ Calculate Exponential Moving Average
+
+ Args:
+ prices: List of prices
+ period: Period for EMA calculation
+
+ Returns:
+ Dictionary with EMA values
+ """
+ try:
+ if TALIB_AVAILABLE:
+ prices_array = np.array(prices)
+ ema = talib.EMA(prices_array, timeperiod=period)
+
+ return {
+ "indicator": "EMA",
+ "period": period,
+ "values": ema[~np.isnan(ema)].tolist(),
+ "current": float(ema[-1]) if not np.isnan(ema[-1]) else None,
+ "source": "talib"
+ }
+
+ elif PANDAS_AVAILABLE:
+ series = pd.Series(prices)
+ ema = series.ewm(span=period, adjust=False).mean()
+
+ return {
+ "indicator": "EMA",
+ "period": period,
+ "values": ema.tolist(),
+ "current": float(ema.iloc[-1]),
+ "source": "pandas"
+ }
+
+ else:
+ return {"error": "pandas or talib required for EMA calculation"}
+
+ except Exception as e:
+ return {"error": f"EMA calculation failed: {str(e)}"}
+
+
+def calculate_rsi(prices: List[float], period: int = 14) -> Dict[str, Any]:
+ """
+ Calculate Relative Strength Index
+
+ Args:
+ prices: List of prices
+ period: Period for RSI calculation
+
+ Returns:
+ Dictionary with RSI values and interpretation
+ """
+ try:
+ if TALIB_AVAILABLE:
+ prices_array = np.array(prices)
+ rsi = talib.RSI(prices_array, timeperiod=period)
+
+ current_rsi = float(rsi[-1]) if not np.isnan(rsi[-1]) else None
+
+ # Interpret RSI
+ interpretation = ""
+ if current_rsi:
+ if current_rsi > 70:
+ interpretation = "Overbought - Potential sell signal"
+ elif current_rsi < 30:
+ interpretation = "Oversold - Potential buy signal"
+ else:
+ interpretation = "Neutral"
+
+ return {
+ "indicator": "RSI",
+ "period": period,
+ "values": rsi[~np.isnan(rsi)].tolist(),
+ "current": current_rsi,
+ "interpretation": interpretation,
+ "source": "talib"
+ }
+
+ else:
+ return {"error": "talib required for RSI calculation. Install with: pip install TA-Lib"}
+
+ except Exception as e:
+ return {"error": f"RSI calculation failed: {str(e)}"}
+
+
+def calculate_macd(
+ prices: List[float],
+ fast_period: int = 12,
+ slow_period: int = 26,
+ signal_period: int = 9
+) -> Dict[str, Any]:
+ """
+ Calculate MACD (Moving Average Convergence Divergence)
+
+ Args:
+ prices: List of prices
+ fast_period: Fast EMA period
+ slow_period: Slow EMA period
+ signal_period: Signal line period
+
+ Returns:
+ Dictionary with MACD values
+ """
+ try:
+ if TALIB_AVAILABLE:
+ prices_array = np.array(prices)
+ macd, signal, histogram = talib.MACD(
+ prices_array,
+ fastperiod=fast_period,
+ slowperiod=slow_period,
+ signalperiod=signal_period
+ )
+
+ # Clean NaN values
+ valid_indices = ~(np.isnan(macd) | np.isnan(signal) | np.isnan(histogram))
+
+ current_macd = float(macd[-1]) if not np.isnan(macd[-1]) else None
+ current_signal = float(signal[-1]) if not np.isnan(signal[-1]) else None
+ current_histogram = float(histogram[-1]) if not np.isnan(histogram[-1]) else None
+
+ # Interpret MACD
+ interpretation = ""
+ if current_macd and current_signal:
+ if current_macd > current_signal:
+ interpretation = "Bullish - MACD above signal line"
+ else:
+ interpretation = "Bearish - MACD below signal line"
+
+ return {
+ "indicator": "MACD",
+ "fast_period": fast_period,
+ "slow_period": slow_period,
+ "signal_period": signal_period,
+ "macd": macd[valid_indices].tolist(),
+ "signal": signal[valid_indices].tolist(),
+ "histogram": histogram[valid_indices].tolist(),
+ "current_macd": current_macd,
+ "current_signal": current_signal,
+ "current_histogram": current_histogram,
+ "interpretation": interpretation,
+ "source": "talib"
+ }
+
+ else:
+ return {"error": "talib required for MACD calculation"}
+
+ except Exception as e:
+ return {"error": f"MACD calculation failed: {str(e)}"}
+
+
+def calculate_bollinger_bands(
+ prices: List[float],
+ period: int = 20,
+ std_dev: float = 2.0
+) -> Dict[str, Any]:
+ """
+ Calculate Bollinger Bands
+
+ Args:
+ prices: List of prices
+ period: Period for calculation
+ std_dev: Standard deviation multiplier
+
+ Returns:
+ Dictionary with Bollinger Bands
+ """
+ try:
+ if TALIB_AVAILABLE:
+ prices_array = np.array(prices)
+ upper, middle, lower = talib.BBANDS(
+ prices_array,
+ timeperiod=period,
+ nbdevup=std_dev,
+ nbdevdn=std_dev,
+ matype=0
+ )
+
+ current_price = prices[-1]
+ current_upper = float(upper[-1]) if not np.isnan(upper[-1]) else None
+ current_middle = float(middle[-1]) if not np.isnan(middle[-1]) else None
+ current_lower = float(lower[-1]) if not np.isnan(lower[-1]) else None
+
+ # Interpret position
+ interpretation = ""
+ if current_upper and current_lower:
+ if current_price > current_upper:
+ interpretation = "Price above upper band - Potentially overbought"
+ elif current_price < current_lower:
+ interpretation = "Price below lower band - Potentially oversold"
+ else:
+ interpretation = "Price within bands - Normal range"
+
+ return {
+ "indicator": "Bollinger Bands",
+ "period": period,
+ "std_dev": std_dev,
+ "upper_band": upper[~np.isnan(upper)].tolist(),
+ "middle_band": middle[~np.isnan(middle)].tolist(),
+ "lower_band": lower[~np.isnan(lower)].tolist(),
+ "current_upper": current_upper,
+ "current_middle": current_middle,
+ "current_lower": current_lower,
+ "current_price": current_price,
+ "interpretation": interpretation,
+ "source": "talib"
+ }
+
+ else:
+ return {"error": "talib required for Bollinger Bands calculation"}
+
+ except Exception as e:
+ return {"error": f"Bollinger Bands calculation failed: {str(e)}"}
+
+
+def detect_support_resistance(
+ prices: List[float],
+ window: int = 5,
+ threshold: float = 0.02
+) -> Dict[str, Any]:
+ """
+ Detect support and resistance levels
+
+ Args:
+ prices: List of prices
+ window: Window size for peak detection
+ threshold: Minimum price change threshold
+
+ Returns:
+ Dictionary with support and resistance levels
+ """
+ try:
+ if not PANDAS_AVAILABLE:
+ return {"error": "pandas required for support/resistance detection"}
+
+ series = pd.Series(prices)
+
+ # Find local maxima (resistance)
+ resistance_levels = []
+ for i in range(window, len(prices) - window):
+ if all(prices[i] >= prices[i-j] for j in range(1, window+1)) and \
+ all(prices[i] >= prices[i+j] for j in range(1, window+1)):
+ resistance_levels.append(prices[i])
+
+ # Find local minima (support)
+ support_levels = []
+ for i in range(window, len(prices) - window):
+ if all(prices[i] <= prices[i-j] for j in range(1, window+1)) and \
+ all(prices[i] <= prices[i+j] for j in range(1, window+1)):
+ support_levels.append(prices[i])
+
+ current_price = prices[-1]
+
+ # Find nearest levels
+ nearest_resistance = min(
+ [r for r in resistance_levels if r > current_price],
+ default=None
+ )
+ nearest_support = max(
+ [s for s in support_levels if s < current_price],
+ default=None
+ )
+
+ return {
+ "current_price": current_price,
+ "support_levels": sorted(set(support_levels)),
+ "resistance_levels": sorted(set(resistance_levels)),
+ "nearest_support": nearest_support,
+ "nearest_resistance": nearest_resistance,
+ "support_count": len(support_levels),
+ "resistance_count": len(resistance_levels)
+ }
+
+ except Exception as e:
+ return {"error": f"Support/Resistance detection failed: {str(e)}"}
+
+
+def get_technical_analysis_tools() -> List[Any]:
+ """
+ Get list of technical analysis tools for Agno agents
+
+ Returns:
+ List of tool functions
+ """
+ return [
+ calculate_sma,
+ calculate_ema,
+ calculate_rsi,
+ calculate_macd,
+ calculate_bollinger_bands,
+ detect_support_resistance,
+ ]
+
+
+# Tool descriptions for LLM
+TOOL_DESCRIPTIONS = {
+ "calculate_sma": "Calculate Simple Moving Average to identify trend direction and smooth out price action.",
+ "calculate_ema": "Calculate Exponential Moving Average which gives more weight to recent prices.",
+ "calculate_rsi": "Calculate Relative Strength Index to identify overbought/oversold conditions (>70 overbought, <30 oversold).",
+ "calculate_macd": "Calculate MACD indicator to identify trend changes and momentum shifts.",
+ "calculate_bollinger_bands": "Calculate Bollinger Bands to measure volatility and identify potential reversal points.",
+ "detect_support_resistance": "Detect support and resistance levels where price tends to reverse or consolidate.",
+}
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/utils/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/utils/__init__.py
new file mode 100644
index 000000000..8a53983c3
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/utils/__init__.py
@@ -0,0 +1,6 @@
+"""Utility modules"""
+
+from .tp_sl_calculator import TPSLCalculator
+from .confidence_scorer import ConfidenceScorer
+
+__all__ = ['TPSLCalculator', 'ConfidenceScorer']
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/utils/confidence_scorer.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/utils/confidence_scorer.py
new file mode 100644
index 000000000..3825d128f
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/utils/confidence_scorer.py
@@ -0,0 +1,245 @@
+"""
+Confidence Scorer
+
+Calculate confidence scores for trading signals based on multiple factors.
+Inspired by Alpha Arena's 0-1 confidence scoring system.
+"""
+
+from typing import Dict, List
+import math
+
+
+class ConfidenceScorer:
+ """
+ Calculate confidence scores (0.0 to 1.0) for trading signals
+
+ Factors considered:
+ - Technical indicator alignment
+ - Trend strength
+ - Volume confirmation
+ - Risk/reward ratio
+ - Market volatility
+ """
+
+ @staticmethod
+ def calculate_comprehensive_confidence(
+ indicator_alignment: float = 0.5,
+ trend_strength: float = 0.5,
+ volume_confirmation: float = 0.5,
+ risk_reward_ratio: float = 2.0,
+ volatility_factor: float = 0.5,
+ weights: Dict[str, float] = None
+ ) -> Dict[str, float]:
+ """
+ Calculate overall confidence score
+
+ Args:
+ indicator_alignment: 0-1, how many indicators agree
+ trend_strength: 0-1, strength of trend
+ volume_confirmation: 0-1, volume supports the move
+ risk_reward_ratio: Actual R:R ratio
+ volatility_factor: 0-1, volatility level (0=low, 1=high)
+ weights: Custom weights for each factor
+
+ Returns:
+ Dictionary with confidence score and breakdown
+ """
+
+ # Default weights
+ if weights is None:
+ weights = {
+ 'indicators': 0.30,
+ 'trend': 0.25,
+ 'volume': 0.20,
+ 'risk_reward': 0.15,
+ 'volatility': 0.10
+ }
+
+ # Normalize risk/reward to 0-1 scale (assuming 3:1 is excellent)
+ rr_normalized = min(risk_reward_ratio / 3.0, 1.0)
+
+ # Lower volatility = higher confidence
+ volatility_score = 1.0 - volatility_factor
+
+ # Calculate weighted score
+ confidence = (
+ indicator_alignment * weights['indicators'] +
+ trend_strength * weights['trend'] +
+ volume_confirmation * weights['volume'] +
+ rr_normalized * weights['risk_reward'] +
+ volatility_score * weights['volatility']
+ )
+
+ # Ensure 0-1 range
+ confidence = max(0.0, min(1.0, confidence))
+
+ return {
+ "confidence": round(confidence, 3),
+ "breakdown": {
+ "indicator_alignment": round(indicator_alignment, 2),
+ "trend_strength": round(trend_strength, 2),
+ "volume_confirmation": round(volume_confirmation, 2),
+ "risk_reward_score": round(rr_normalized, 2),
+ "volatility_score": round(volatility_score, 2)
+ },
+ "rating": ConfidenceScorer._get_confidence_rating(confidence)
+ }
+
+ @staticmethod
+ def calculate_indicator_alignment(
+ indicators: Dict[str, str]
+ ) -> float:
+ """
+ Calculate how well indicators align
+
+ Args:
+ indicators: Dict of indicator signals (e.g., {'RSI': 'buy', 'MACD': 'buy', 'EMA': 'sell'})
+
+ Returns:
+ Alignment score 0-1
+ """
+
+ if not indicators:
+ return 0.5
+
+ signals = list(indicators.values())
+ buy_count = signals.count('buy') + signals.count('bullish')
+ sell_count = signals.count('sell') + signals.count('bearish')
+ total = len(signals)
+
+ # If all agree, score is 1.0
+ alignment = max(buy_count, sell_count) / total if total > 0 else 0
+
+ return alignment
+
+ @staticmethod
+ def calculate_trend_strength(
+ current_price: float,
+ ma_20: float,
+ ma_50: float,
+ ma_200: float = None
+ ) -> float:
+ """
+ Calculate trend strength from moving averages
+
+ Args:
+ current_price: Current market price
+ ma_20: 20-period MA
+ ma_50: 50-period MA
+ ma_200: 200-period MA (optional)
+
+ Returns:
+ Trend strength 0-1
+ """
+
+ score = 0.0
+
+ # Check if price is trending
+ if current_price > ma_20 > ma_50:
+ score = 0.6 # Uptrend
+ elif current_price < ma_20 < ma_50:
+ score = 0.6 # Downtrend
+
+ # Bonus for 200 MA alignment
+ if ma_200:
+ if (current_price > ma_20 > ma_50 > ma_200) or \
+ (current_price < ma_20 < ma_50 < ma_200):
+ score = 1.0 # Strong trend
+
+ return score
+
+ @staticmethod
+ def calculate_volume_confirmation(
+ current_volume: float,
+ avg_volume: float,
+ volume_threshold: float = 1.2
+ ) -> float:
+ """
+ Calculate volume confirmation score
+
+ Args:
+ current_volume: Current volume
+ avg_volume: Average volume
+ volume_threshold: Multiplier for significant volume
+
+ Returns:
+ Volume confirmation 0-1
+ """
+
+ if avg_volume == 0:
+ return 0.5
+
+ volume_ratio = current_volume / avg_volume
+
+ if volume_ratio >= volume_threshold:
+ # High volume = strong confirmation
+ return min(volume_ratio / 2.0, 1.0)
+ else:
+ # Low volume = weak confirmation
+ return 0.3
+
+ @staticmethod
+ def adjust_for_market_conditions(
+ base_confidence: float,
+ market_condition: str
+ ) -> float:
+ """
+ Adjust confidence based on market conditions
+
+ Args:
+ base_confidence: Base confidence score
+ market_condition: 'trending', 'ranging', 'volatile', 'calm'
+
+ Returns:
+ Adjusted confidence
+ """
+
+ adjustments = {
+ 'trending': 1.1, # Boost in trending markets
+ 'ranging': 0.9, # Reduce in ranging markets
+ 'volatile': 0.85, # Reduce in volatile markets
+ 'calm': 1.0, # No change in calm markets
+ }
+
+ multiplier = adjustments.get(market_condition, 1.0)
+ adjusted = base_confidence * multiplier
+
+ return max(0.0, min(1.0, adjusted))
+
+ @staticmethod
+ def _get_confidence_rating(confidence: float) -> str:
+ """Get text rating for confidence score"""
+
+ if confidence >= 0.8:
+ return "Very High"
+ elif confidence >= 0.7:
+ return "High"
+ elif confidence >= 0.6:
+ return "Medium"
+ elif confidence >= 0.5:
+ return "Low"
+ else:
+ return "Very Low"
+
+ @staticmethod
+ def recommend_action(confidence: float, min_threshold: float = 0.6) -> str:
+ """
+ Recommend action based on confidence
+
+ Args:
+ confidence: Confidence score
+ min_threshold: Minimum confidence to trade
+
+ Returns:
+ Recommended action
+ """
+
+ if confidence >= min_threshold:
+ if confidence >= 0.8:
+ return "STRONG_EXECUTE"
+ elif confidence >= 0.7:
+ return "EXECUTE"
+ else:
+ return "EXECUTE_WITH_CAUTION"
+ else:
+ return "SKIP"
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/utils/tp_sl_calculator.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/utils/tp_sl_calculator.py
new file mode 100644
index 000000000..c9d4b12f4
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading/utils/tp_sl_calculator.py
@@ -0,0 +1,221 @@
+"""
+TP/SL Calculator
+
+Dynamic Take Profit and Stop Loss calculation based on volatility and market conditions.
+Inspired by Alpha Arena's adaptive TP/SL logic.
+"""
+
+from typing import Dict, Tuple
+import math
+
+
+class TPSLCalculator:
+ """
+ Calculate dynamic TP/SL levels based on:
+ - Current volatility (ATR)
+ - Risk/reward ratio
+ - Market conditions
+ """
+
+ @staticmethod
+ def calculate_dynamic_tp_sl(
+ entry_price: float,
+ direction: str,
+ volatility: float,
+ risk_reward_ratio: float = 2.0,
+ atr_multiplier: float = 2.0
+ ) -> Dict[str, float]:
+ """
+ Calculate TP/SL levels dynamically
+
+ Args:
+ entry_price: Entry price
+ direction: 'long' or 'short'
+ volatility: Current volatility (ATR or standard deviation)
+ risk_reward_ratio: Desired risk/reward ratio (default 2:1)
+ atr_multiplier: Multiplier for ATR to set SL distance
+
+ Returns:
+ Dictionary with stop_loss, take_profit, risk_amount, reward_amount
+ """
+
+ # Calculate stop loss distance based on volatility
+ sl_distance = volatility * atr_multiplier
+
+ if direction.lower() == 'long':
+ stop_loss = entry_price - sl_distance
+ take_profit = entry_price + (sl_distance * risk_reward_ratio)
+ else: # short
+ stop_loss = entry_price + sl_distance
+ take_profit = entry_price - (sl_distance * risk_reward_ratio)
+
+ return {
+ "stop_loss": round(stop_loss, 2),
+ "take_profit": round(take_profit, 2),
+ "sl_distance": round(sl_distance, 2),
+ "tp_distance": round(sl_distance * risk_reward_ratio, 2),
+ "risk_reward_ratio": risk_reward_ratio
+ }
+
+ @staticmethod
+ def calculate_from_percentage(
+ entry_price: float,
+ direction: str,
+ sl_percent: float = 2.0,
+ tp_percent: float = 5.0
+ ) -> Dict[str, float]:
+ """
+ Calculate TP/SL based on percentage
+
+ Args:
+ entry_price: Entry price
+ direction: 'long' or 'short'
+ sl_percent: Stop loss percentage (e.g., 2.0 for 2%)
+ tp_percent: Take profit percentage (e.g., 5.0 for 5%)
+
+ Returns:
+ Dictionary with stop_loss and take_profit
+ """
+
+ sl_amount = entry_price * (sl_percent / 100)
+ tp_amount = entry_price * (tp_percent / 100)
+
+ if direction.lower() == 'long':
+ stop_loss = entry_price - sl_amount
+ take_profit = entry_price + tp_amount
+ else: # short
+ stop_loss = entry_price + sl_amount
+ take_profit = entry_price - tp_amount
+
+ return {
+ "stop_loss": round(stop_loss, 2),
+ "take_profit": round(take_profit, 2),
+ "sl_percent": sl_percent,
+ "tp_percent": tp_percent,
+ "risk_reward_ratio": tp_percent / sl_percent
+ }
+
+ @staticmethod
+ def calculate_trailing_stop(
+ entry_price: float,
+ current_price: float,
+ direction: str,
+ trail_percent: float = 1.0
+ ) -> float:
+ """
+ Calculate trailing stop loss
+
+ Args:
+ entry_price: Original entry price
+ current_price: Current market price
+ direction: 'long' or 'short'
+ trail_percent: Trailing distance as percentage
+
+ Returns:
+ New stop loss level
+ """
+
+ if direction.lower() == 'long':
+ # For long, trail below current price
+ trailing_stop = current_price * (1 - trail_percent / 100)
+ # Never move stop down
+ original_stop = entry_price * (1 - trail_percent / 100)
+ return max(trailing_stop, original_stop)
+ else: # short
+ # For short, trail above current price
+ trailing_stop = current_price * (1 + trail_percent / 100)
+ # Never move stop up
+ original_stop = entry_price * (1 + trail_percent / 100)
+ return min(trailing_stop, original_stop)
+
+ @staticmethod
+ def estimate_volatility_from_price_history(
+ prices: list,
+ period: int = 14
+ ) -> float:
+ """
+ Estimate volatility from price history using ATR approximation
+
+ Args:
+ prices: List of recent prices
+ period: Period for calculation
+
+ Returns:
+ Estimated volatility
+ """
+
+ if len(prices) < period + 1:
+ # Use simple percentage of current price if not enough data
+ return prices[-1] * 0.02 if prices else 0
+
+ # Calculate simple volatility as average price range
+ ranges = []
+ for i in range(len(prices) - period, len(prices)):
+ if i > 0:
+ ranges.append(abs(prices[i] - prices[i-1]))
+
+ avg_range = sum(ranges) / len(ranges) if ranges else 0
+ return avg_range
+
+ @staticmethod
+ def validate_tp_sl(
+ entry_price: float,
+ stop_loss: float,
+ take_profit: float,
+ direction: str,
+ min_risk_reward: float = 1.5
+ ) -> Dict[str, any]:
+ """
+ Validate TP/SL levels
+
+ Args:
+ entry_price: Entry price
+ stop_loss: Stop loss level
+ take_profit: Take profit level
+ direction: 'long' or 'short'
+ min_risk_reward: Minimum acceptable risk/reward ratio
+
+ Returns:
+ Validation result with errors if any
+ """
+
+ errors = []
+ warnings = []
+
+ if direction.lower() == 'long':
+ # For long: SL < entry < TP
+ if stop_loss >= entry_price:
+ errors.append("Stop loss must be below entry price for long positions")
+
+ if take_profit <= entry_price:
+ errors.append("Take profit must be above entry price for long positions")
+
+ if stop_loss < entry_price and take_profit > entry_price:
+ risk = entry_price - stop_loss
+ reward = take_profit - entry_price
+ rr_ratio = reward / risk if risk > 0 else 0
+
+ if rr_ratio < min_risk_reward:
+ warnings.append(f"Risk/reward ratio {rr_ratio:.2f} is below minimum {min_risk_reward}")
+
+ else: # short
+ # For short: SL > entry > TP
+ if stop_loss <= entry_price:
+ errors.append("Stop loss must be above entry price for short positions")
+
+ if take_profit >= entry_price:
+ errors.append("Take profit must be below entry price for short positions")
+
+ if stop_loss > entry_price and take_profit < entry_price:
+ risk = stop_loss - entry_price
+ reward = entry_price - take_profit
+ rr_ratio = reward / risk if risk > 0 else 0
+
+ if rr_ratio < min_risk_reward:
+ warnings.append(f"Risk/reward ratio {rr_ratio:.2f} is below minimum {min_risk_reward}")
+
+ return {
+ "valid": len(errors) == 0,
+ "errors": errors,
+ "warnings": warnings
+ }
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.py
new file mode 100644
index 000000000..59aaedb31
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agno_trading_service.py
@@ -0,0 +1,432 @@
+#!/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
+from typing import Dict, Any, Optional, List
+
+# Add agno_trading to path
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'agno_trading'))
+
+# 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))
+
+
+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"
+) -> str:
+ """Analyze market for a given symbol"""
+ try:
+ # Parse model string
+ if ":" in agent_model:
+ model_provider, model_name = agent_model.split(":", 1)
+ else:
+ model_provider = "openai"
+ model_name = agent_model
+
+ # Create market analyst agent
+ analyst = MarketAnalystAgent(
+ model_provider=model_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
+) -> str:
+ """Generate trading signal"""
+ try:
+ # Parse model string
+ if ":" in agent_model:
+ model_provider, model_name = agent_model.split(":", 1)
+ else:
+ model_provider = "anthropic"
+ model_name = agent_model
+
+ # Create trading strategy agent
+ strategist = TradingStrategyAgent(
+ model_provider=model_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 manage_risk_command(
+ portfolio_data: str,
+ agent_model: str = "openai:gpt-4",
+ risk_tolerance: str = "moderate"
+) -> str:
+ """Run risk management analysis"""
+ try:
+ 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
+
+ # Create risk manager agent
+ risk_manager = RiskManagerAgent(
+ model_provider=model_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))
+
+
+def create_competition_command(
+ name: str,
+ models_json: str,
+ task_type: str = "trading"
+) -> 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
+ """
+ try:
+ import json
+ from agno_trading.core.team_orchestrator import TeamOrchestrator
+ from agno_trading.core.agent_manager import AgentManager
+
+ models = json.loads(models_json)
+ manager = AgentManager()
+ orchestrator = TeamOrchestrator()
+
+ # Create agents for each model
+ agents = []
+ for model_str in models:
+ agent_config = {
+ "name": f"Agent-{model_str}",
+ "role": "Market Analyst",
+ "agent_model": model_str
+ }
+ 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))
+
+
+def run_competition_command(team_id: str, symbol: str, task: str = "analyze") -> str:
+ """
+ Run multi-model competition
+
+ Args:
+ team_id: Competition ID
+ symbol: Trading symbol
+ task: Task type (analyze, signal)
+ """
+ try:
+ import asyncio
+ from agno_trading.core.team_orchestrator import TeamOrchestrator
+
+ 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)
+ )
+
+ 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))
+
+
+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))
+
+
+# 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,
+ "create_competition": create_competition_command,
+ "run_competition": run_competition_command,
+ "get_leaderboard": get_leaderboard_command,
+ "get_recent_decisions": get_recent_decisions_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/agno_trading.rs b/fincept-terminal-desktop/src-tauri/src/commands/agno_trading.rs
new file mode 100644
index 000000000..3b8612236
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/src/commands/agno_trading.rs
@@ -0,0 +1,242 @@
+// Agno Trading Agent Commands
+// Provides Rust/Tauri interface to Python-based Agno trading agents
+
+use crate::utils::python::execute_python_command;
+
+/// List available LLM models
+#[tauri::command]
+pub async fn agno_list_models(
+ app: tauri::AppHandle,
+ provider: Option<String>,
+) -> Result<String, String> {
+ let mut args = vec!["list_models".to_string()];
+
+ if let Some(p) = provider {
+ args.push(p);
+ }
+
+ execute_python_command(&app, "agno_trading_service.py", &args)
+}
+
+/// Recommend best model for a task
+#[tauri::command]
+pub async fn agno_recommend_model(
+ app: tauri::AppHandle,
+ task: String,
+ budget: Option<String>,
+ reasoning: Option<bool>,
+) -> Result<String, String> {
+ let mut args = vec!["recommend_model".to_string(), task];
+
+ if let Some(b) = budget {
+ args.push(b);
+ } else {
+ args.push("medium".to_string());
+ }
+
+ if let Some(r) = reasoning {
+ args.push(r.to_string());
+ } else {
+ args.push("false".to_string());
+ }
+
+ execute_python_command(&app, "agno_trading_service.py", &args)
+}
+
+/// Validate Agno configuration
+#[tauri::command]
+pub async fn agno_validate_config(
+ app: tauri::AppHandle,
+ config_json: String,
+) -> Result<String, String> {
+ let args = vec!["validate_config".to_string(), config_json];
+ execute_python_command(&app, "agno_trading_service.py", &args)
+}
+
+/// Create a new trading agent
+#[tauri::command]
+pub async fn agno_create_agent(
+ app: tauri::AppHandle,
+ agent_config_json: String,
+) -> Result<String, String> {
+ let args = vec!["create_agent".to_string(), agent_config_json];
+ execute_python_command(&app, "agno_trading_service.py", &args)
+}
+
+/// Run an agent with a prompt
+#[tauri::command]
+pub async fn agno_run_agent(
+ app: tauri::AppHandle,
+ agent_id: String,
+ prompt: String,
+ session_id: Option<String>,
+) -> Result<String, String> {
+ let mut args = vec!["run_agent".to_string(), agent_id, prompt];
+
+ if let Some(sid) = session_id {
+ args.push(sid);
+ }
+
+ execute_python_command(&app, "agno_trading_service.py", &args)
+}
+
+/// Analyze market for a given symbol
+#[tauri::command]
+pub async fn agno_analyze_market(
+ app: tauri::AppHandle,
+ symbol: String,
+ agent_model: Option<String>,
+ analysis_type: Option<String>,
+) -> Result<String, String> {
+ let mut args = vec!["analyze_market".to_string(), symbol];
+
+ if let Some(model) = agent_model {
+ args.push(model);
+ } else {
+ args.push("openai:gpt-4o-mini".to_string());
+ }
+
+ if let Some(atype) = analysis_type {
+ args.push(atype);
+ } else {
+ args.push("comprehensive".to_string());
+ }
+
+ execute_python_command(&app, "agno_trading_service.py", &args)
+}
+
+/// Generate trading signal
+#[tauri::command]
+pub async fn agno_generate_trade_signal(
+ app: tauri::AppHandle,
+ symbol: String,
+ strategy: Option<String>,
+ agent_model: Option<String>,
+ market_data: Option<String>,
+) -> Result<String, String> {
+ let mut args = vec!["generate_trade_signal".to_string(), symbol];
+
+ if let Some(strat) = strategy {
+ args.push(strat);
+ } else {
+ args.push("momentum".to_string());
+ }
+
+ if let Some(model) = agent_model {
+ args.push(model);
+ } else {
+ args.push("anthropic:claude-sonnet-4".to_string());
+ }
+
+ if let Some(data) = market_data {
+ args.push(data);
+ }
+
+ execute_python_command(&app, "agno_trading_service.py", &args)
+}
+
+/// Run risk management analysis
+#[tauri::command]
+pub async fn agno_manage_risk(
+ app: tauri::AppHandle,
+ portfolio_data: String,
+ agent_model: Option<String>,
+ risk_tolerance: Option<String>,
+) -> Result<String, String> {
+ let mut args = vec!["manage_risk".to_string(), portfolio_data];
+
+ if let Some(model) = agent_model {
+ args.push(model);
+ } else {
+ args.push("openai:gpt-4".to_string());
+ }
+
+ if let Some(tolerance) = risk_tolerance {
+ args.push(tolerance);
+ } else {
+ args.push("moderate".to_string());
+ }
+
+ execute_python_command(&app, "agno_trading_service.py", &args)
+}
+
+/// Get configuration template
+#[tauri::command]
+pub async fn agno_get_config_template(
+ app: tauri::AppHandle,
+ config_type: Option<String>,
+) -> Result<String, String> {
+ let mut args = vec!["get_config_template".to_string()];
+
+ if let Some(ctype) = config_type {
+ args.push(ctype);
+ } else {
+ args.push("default".to_string());
+ }
+
+ execute_python_command(&app, "agno_trading_service.py", &args)
+}
+
+/// Create multi-model competition
+#[tauri::command]
+pub async fn agno_create_competition(
+ app: tauri::AppHandle,
+ name: String,
+ models_json: String,
+ task_type: Option<String>,
+) -> Result<String, String> {
+ let mut args = vec!["create_competition".to_string(), name, models_json];
+
+ if let Some(task) = task_type {
+ args.push(task);
+ } else {
+ args.push("trading".to_string());
+ }
+
+ execute_python_command(&app, "agno_trading_service.py", &args)
+}
+
+/// Run multi-model competition
+#[tauri::command]
+pub async fn agno_run_competition(
+ app: tauri::AppHandle,
+ team_id: String,
+ symbol: String,
+ task: Option<String>,
+) -> Result<String, String> {
+ let mut args = vec!["run_competition".to_string(), team_id, symbol];
+
+ if let Some(t) = task {
+ args.push(t);
+ } else {
+ args.push("analyze".to_string());
+ }
+
+ execute_python_command(&app, "agno_trading_service.py", &args)
+}
+
+/// Get model performance leaderboard
+#[tauri::command]
+pub async fn agno_get_leaderboard(
+ app: tauri::AppHandle,
+) -> Result<String, String> {
+ let args = vec!["get_leaderboard".to_string()];
+ execute_python_command(&app, "agno_trading_service.py", &args)
+}
+
+/// Get recent model decisions
+#[tauri::command]
+pub async fn agno_get_recent_decisions(
+ app: tauri::AppHandle,
+ limit: Option<i32>,
+) -> Result<String, String> {
+ let mut args = vec!["get_recent_decisions".to_string()];
+
+ if let Some(l) = limit {
+ args.push(l.to_string());
+ } else {
+ args.push("50".to_string());
+ }
+
+ execute_python_command(&app, "agno_trading_service.py", &args)
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
index 246842de8..969ea8a1f 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/mod.rs
@@ -84,3 +84,6 @@ pub mod backtesting;
// Company News
pub mod company_news;
+
+// Agno Trading Agents
+pub mod agno_trading;
diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rs
index eb359c245..7524bf7b1 100644
--- a/fincept-terminal-desktop/src-tauri/src/lib.rs
+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs
@@ -125,7 +125,6 @@ fn spawn_mcp_server(
let (response_tx, response_rx): (Sender<String>, Receiver<String>) = channel();
// Spawn background thread to read stdout
- let server_id_clone = server_id.clone();
thread::spawn(move || {
let reader = BufReader::new(stdout);
@@ -1049,7 +1048,21 @@ pub fn run() {
commands::company_news::fetch_company_news,
commands::company_news::fetch_news_by_topic,
commands::company_news::get_full_article,
- commands::company_news::get_company_news_help
+ commands::company_news::get_company_news_help,
+ // Agno Trading Agents
+ commands::agno_trading::agno_list_models,
+ commands::agno_trading::agno_recommend_model,
+ commands::agno_trading::agno_validate_config,
+ commands::agno_trading::agno_create_agent,
+ commands::agno_trading::agno_run_agent,
+ commands::agno_trading::agno_analyze_market,
+ commands::agno_trading::agno_generate_trade_signal,
+ commands::agno_trading::agno_manage_risk,
+ commands::agno_trading::agno_get_config_template,
+ commands::agno_trading::agno_create_competition,
+ commands::agno_trading::agno_run_competition,
+ commands::agno_trading::agno_get_leaderboard,
+ commands::agno_trading::agno_get_recent_decisions
])
.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.rs
index 62671a653..ccf228064 100644
--- a/fincept-terminal-desktop/src-tauri/src/setup.rs
+++ b/fincept-terminal-desktop/src-tauri/src/setup.rs
@@ -4,6 +4,7 @@ use std::path::PathBuf;
use std::process::Command;
use tauri::{AppHandle, Emitter, Manager};
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SetupProgress {
pub step: String,
@@ -21,25 +22,17 @@ pub struct SetupStatus {
pub needs_setup: bool,
}
-// Python 3.12.7 download URLs
-const PYTHON_VERSION: &str = "3.12.7";
-const PYTHON_WINDOWS_URL: &str = "https://www.python.org/ftp/python/3.12.7/python-3.12.7-amd64.exe";
-const PYTHON_MACOS_URL: &str = "https://www.python.org/ftp/python/3.12.7/python-3.12.7-macos11.pkg";
-const PYTHON_LINUX_URL: &str = ""; // Linux uses package manager
-
-// Bun download URLs
+// Bun download URL
const BUN_WINDOWS_URL: &str = "https://github.com/oven-sh/bun/releases/latest/download/bun-windows-x64.zip";
-const BUN_MACOS_URL: &str = ""; // Bun install script
-const BUN_LINUX_URL: &str = ""; // Bun install script
/// Check if Python is installed (check app directory first, then system)
pub fn check_python_installed_in_app(app: &AppHandle) -> (bool, Option<String>) {
- // First check in app's resource directory
- if let Ok(resource_dir) = app.path().resource_dir() {
+ // Check in app's data directory (where Python is actually installed)
+ if let Ok(app_data_dir) = app.path().app_data_dir() {
let python_exe = if cfg!(target_os = "windows") {
- resource_dir.join("python").join("python.exe")
+ app_data_dir.join("python").join("python.exe")
} else {
- resource_dir.join("python").join("bin").join("python3")
+ app_data_dir.join("python").join("bin").join("python3")
};
if python_exe.exists() {
@@ -212,21 +205,60 @@ fn emit_progress(app: &AppHandle, step: &str, progress: u8, message: &str, is_er
let _ = app.emit("setup-progress", progress_data);
}
+/// Check if Microsoft Visual C++ Redistributable is installed (Windows only)
+#[cfg(target_os = "windows")]
+fn check_vcredist_installed() -> bool {
+ // Check for VC++ Redistributable by looking for vcruntime140.dll in System32
+ let system32 = std::env::var("SystemRoot")
+ .map(|root| PathBuf::from(root).join("System32"))
+ .unwrap_or_else(|_| PathBuf::from(r"C:\Windows\System32"));
+
+ let vcruntime_dll = system32.join("vcruntime140.dll");
+ let msvcp_dll = system32.join("msvcp140.dll");
+
+ vcruntime_dll.exists() && msvcp_dll.exists()
+}
+
/// Install Python on Windows in app directory (portable, no admin)
#[cfg(target_os = "windows")]
async fn install_python_windows(app: &AppHandle) -> Result<(), String> {
use std::env;
use std::fs;
- emit_progress(app, "python", 0, "Preparing Python installation...", false);
+ emit_progress(app, "python", 0, "Checking system requirements...", false);
+
+ // Check for VC++ Redistributable
+ if !check_vcredist_installed() {
+ emit_progress(
+ app,
+ "python",
+ 0,
+ "Warning: Microsoft Visual C++ Redistributable may not be installed",
+ false
+ );
+
+ // Return a warning but allow setup to continue
+ // The detailed error will be shown when Python fails to run
+ return Err(format!(
+ "Microsoft Visual C++ Redistributable 2015-2022 is required but may not be installed.\n\n\
+ Python 3.12 embedded requires this runtime to function.\n\n\
+ Please install it first from:\n\
+ https://aka.ms/vs/17/release/vc_redist.{}.exe\n\n\
+ After installing VC++ Redistributable, please restart the application and try again.",
+ if cfg!(target_arch = "x86_64") { "x64" } else { "x86" }
+ ));
+ }
+
+ emit_progress(app, "python", 5, "Preparing Python installation...", false);
- // Get app resource directory
- let resource_dir = app
+ // Use AppData for Python installation (writable without admin)
+ // resource_dir might be in Program Files which is read-only
+ let app_data_dir = app
.path()
- .resource_dir()
- .map_err(|e| format!("Failed to get resource dir: {}", e))?;
+ .app_data_dir()
+ .map_err(|e| format!("Failed to get app data dir: {}", e))?;
- let python_dir = resource_dir.join("python");
+ let python_dir = app_data_dir.join("python");
fs::create_dir_all(&python_dir)
.map_err(|e| format!("Failed to create python directory: {}", e))?;
@@ -234,8 +266,24 @@ async fn install_python_windows(app: &AppHandle) -> Result<(), String> {
let temp_dir = env::temp_dir();
let zip_path = temp_dir.join("python-embeddable.zip");
- // Use embeddable package instead of installer
- let embeddable_url = "https://www.python.org/ftp/python/3.12.7/python-3.12.7-embed-amd64.zip";
+ // Detect system architecture and select appropriate Python build
+ let embeddable_url = if cfg!(target_arch = "x86_64") {
+ // 64-bit Windows
+ "https://www.python.org/ftp/python/3.12.7/python-3.12.7-embed-amd64.zip"
+ } else if cfg!(target_arch = "x86") {
+ // 32-bit Windows
+ "https://www.python.org/ftp/python/3.12.7/python-3.12.7-embed-win32.zip"
+ } else if cfg!(target_arch = "aarch64") {
+ // ARM64 Windows
+ "https://www.python.org/ftp/python/3.12.7/python-3.12.7-embed-arm64.zip"
+ } else {
+ return Err(format!(
+ "Unsupported Windows architecture: {}. Please install Python 3.12 manually from python.org",
+ std::env::consts::ARCH
+ ));
+ };
+
+ emit_progress(app, "python", 10, &format!("Downloading Python for {} architecture...", std::env::consts::ARCH), false);
download_file(embeddable_url, &zip_path, app, "python").await?;
@@ -254,6 +302,43 @@ async fn install_python_windows(app: &AppHandle) -> Result<(), String> {
// Run get-pip.py
let python_exe = python_dir.join("python.exe");
+
+ // Test if Python executable can run (checks for VC++ Runtime and other dependencies)
+ emit_progress(app, "python", 70, "Testing Python installation...", false);
+ let test_output = Command::new(&python_exe)
+ .arg("--version")
+ .output();
+
+ match test_output {
+ Err(e) => {
+ return Err(format!(
+ "Python installation failed. The Python interpreter cannot run on this system.\n\n\
+ Common causes:\n\
+ 1. Missing Microsoft Visual C++ Redistributable 2015-2022\n\
+ 2. System incompatibility\n\n\
+ Error: {}\n\n\
+ Please install:\n\
+ - Microsoft Visual C++ Redistributable from: https://aka.ms/vs/17/release/vc_redist.x64.exe\n\
+ - Or install Python 3.12 manually from: https://www.python.org/downloads/",
+ e
+ ));
+ }
+ Ok(output) if !output.status.success() => {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ return Err(format!(
+ "Python installation test failed.\n\n\
+ Error: {}\n\n\
+ Please ensure Microsoft Visual C++ Redistributable 2015-2022 is installed.\n\
+ Download from: https://aka.ms/vs/17/release/vc_redist.x64.exe",
+ stderr
+ ));
+ }
+ Ok(_) => {
+ // Python exe works, continue with pip installation
+ }
+ }
+
+ emit_progress(app, "python", 75, "Installing pip package manager...", false);
let output = Command::new(&python_exe)
.arg(&get_pip_path)
.output()
diff --git a/fincept-terminal-desktop/src-tauri/src/utils/python.rs b/fincept-terminal-desktop/src-tauri/src/utils/python.rs
index 94b681048..a9cd8eb44 100644
--- a/fincept-terminal-desktop/src-tauri/src/utils/python.rs
+++ b/fincept-terminal-desktop/src-tauri/src/utils/python.rs
@@ -15,22 +15,23 @@ const CREATE_NO_WINDOW: u32 = 0x08000000;
/// In production: Uses installed Python from setup.rs
/// In development: Falls back to system Python if installed Python not found
pub fn get_python_path(app: &tauri::AppHandle) -> Result<PathBuf, String> {
- // Get the resource directory where Python was installed by setup.rs
- let resource_dir = app
+ // Get the app data directory where Python was installed by setup.rs
+ // Using app_data_dir instead of resource_dir to avoid admin permission issues
+ let app_data_dir = app
.path()
- .resource_dir()
- .map_err(|e| format!("Failed to get resource directory: {}", e))?;
+ .app_data_dir()
+ .map_err(|e| format!("Failed to get app data directory: {}", e))?;
// Platform-specific Python executable location
let python_exe = if cfg!(target_os = "windows") {
- // Windows: resources/python/python.exe
- resource_dir.join("python").join("python.exe")
+ // Windows: AppData/python/python.exe
+ app_data_dir.join("python").join("python.exe")
} else if cfg!(target_os = "linux") {
- // Linux: resources/python/bin/python3
- resource_dir.join("python").join("bin").join("python3")
+ // Linux: AppData/python/bin/python3
+ app_data_dir.join("python").join("bin").join("python3")
} else if cfg!(target_os = "macos") {
- // macOS: resources/python/bin/python3
- resource_dir.join("python").join("bin").join("python3")
+ // macOS: AppData/python/bin/python3
+ app_data_dir.join("python").join("bin").join("python3")
} else {
return Err("Unsupported platform".to_string());
};
@@ -69,7 +70,14 @@ pub fn get_python_path(app: &tauri::AppHandle) -> Result<PathBuf, String> {
// If we get here, Python is not available
Err(format!(
- "Python interpreter not found at: {}\n\nPlease run the setup process to install Python.",
+ "Python interpreter not found at: {}\n\n\
+ The Python runtime is required to run analytics and data processing features.\n\n\
+ Troubleshooting steps:\n\
+ 1. Run the setup wizard from the application to install Python\n\
+ 2. If setup fails, ensure Microsoft Visual C++ Redistributable is installed:\n\
+ Download from: https://aka.ms/vs/17/release/vc_redist.x64.exe\n\
+ 3. Alternatively, install Python 3.12 manually from: https://www.python.org/downloads/\n\
+ 4. Restart the application after installation",
python_exe.display()
))
}
diff --git a/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx b/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx
index 4cbf76ffb..a0208b81d 100644
--- a/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx
+++ b/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx
@@ -46,16 +46,26 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
} else {
console.log('Login failed:', result.error);
- // Check for specific error messages and provide helpful feedback
+ // Provide user-friendly error messages
const errorMessage = result.error || 'Login failed. Please check your credentials.';
- if (errorMessage.toLowerCase().includes('user not found') ||
+ // Check for specific error patterns
+ if (errorMessage.toLowerCase().includes('invalid email or password') ||
errorMessage.toLowerCase().includes('invalid credentials') ||
- errorMessage.toLowerCase().includes('user does not exist')) {
- setError(t('login.errors.accountNotFound'));
+ errorMessage.toLowerCase().includes('check your credentials')) {
+ setError('Invalid email or password. Please double-check your login information.');
+ } else if (errorMessage.toLowerCase().includes('account not found') ||
+ errorMessage.toLowerCase().includes('user not found') ||
+ errorMessage.toLowerCase().includes('user does not exist')) {
+ setError('No account found with this email. Please check your email or sign up for a new account.');
} else if (errorMessage.toLowerCase().includes('password')) {
- setError(t('login.errors.incorrectPassword'));
+ setError('Incorrect password. Please try again or use "Forgot Password" to reset it.');
+ } else if (errorMessage.toLowerCase().includes('server error')) {
+ setError('Server error. Please try again in a few moments.');
+ } else if (errorMessage.toLowerCase().includes('unable to connect')) {
+ setError('Unable to connect to server. Please check your internet connection and try again.');
} else {
+ // Display the error as-is if it's already user-friendly
setError(errorMessage);
}
}
@@ -138,7 +148,9 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
setPassword(e.target.value);
if (error) setError("");
}}
- className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 pr-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
+ className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 pr-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500 [&::-ms-reveal]:hidden [&::-ms-clear]:hidden"
+ style={{ WebkitTextSecurity: showPassword ? 'none' : undefined } as any}
+ autoComplete="current-password"
disabled={isLoading || isGuestLoading}
required
/>
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index 46119b84f..447dd13d8 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -21,7 +21,6 @@ import ChatTab from '@/components/tabs/ChatTab';
import ProfileTab from '@/components/tabs/ProfileTab';
import MarketplaceTab from '@/components/tabs/MarketplaceTab';
import PortfolioTab from '@/components/tabs/PortfolioTab';
-import AnalyticsTab from '@/components/tabs/AnalyticsTab';
import EquityResearchTab from '@/components/tabs/EquityResearchTab';
import ScreenerTab from '@/components/tabs/ScreenerTab';
import DBnomicsTab from '@/components/tabs/DBnomicsTab';
@@ -408,8 +407,8 @@ function FinxeptTerminalContent() {
break;
case 'F5':
event.preventDefault();
- setActiveTab('analytics');
- setStatusMessage('Navigated to Analytics (F5)');
+ setActiveTab('backtesting');
+ setStatusMessage('Navigated to Backtesting (F5)');
setTimeout(() => setStatusMessage(''), 2000);
break;
case 'F6':
@@ -486,9 +485,8 @@ function FinxeptTerminalContent() {
const tradingMenuItems = [
{ label: 'Trading Desk', shortcut: 'F9', action: () => setActiveTab('trading') },
{ label: 'Fyers Broker', action: () => setActiveTab('fyers') },
- { label: 'Backtesting', action: () => setActiveTab('backtesting'), separator: true },
{ label: 'Portfolio', shortcut: 'F4', action: () => setActiveTab('portfolio') },
- { label: 'Analytics', shortcut: 'F5', action: () => setActiveTab('analytics') },
+ { label: 'Backtesting', shortcut: 'F5', action: () => setActiveTab('backtesting') },
{ label: 'Watchlist', shortcut: 'F6', action: () => setActiveTab('watchlist') }
];
@@ -785,11 +783,11 @@ function FinxeptTerminalContent() {
Portfolio
</TabsTrigger>
<TabsTrigger
- value="analytics"
- style={activeTab === 'analytics' ? tabStyles.active : tabStyles.default}
- title="Analytics (F5)"
+ value="backtesting"
+ style={activeTab === 'backtesting' ? tabStyles.active : tabStyles.default}
+ title="Backtesting (F5)"
>
- Analytics
+ Backtesting
</TabsTrigger>
<TabsTrigger
value="watchlist"
@@ -847,61 +845,55 @@ function FinxeptTerminalContent() {
)}
{/* Command Bar - Hidden in Chat Mode */}
- {mode !== 'chat' && (
- <div style={{
- backgroundColor: '#2d2d2d',
- borderBottom: '1px solid #404040',
- padding: '4px 8px',
- height: '24px',
- display: 'flex',
- alignItems: 'center',
- gap: '12px',
- flexShrink: 0
- }}>
- <span style={{ backgroundColor: '#ea580c', color: 'white', padding: '2px 6px', fontSize: '9px', fontWeight: 'bold' }}>FINXEPT PROFESSIONAL</span>
- <span style={{ color: '#a3a3a3', fontSize: '10px' }}>Enter Command</span>
- <div style={{ width: '1px', height: '16px', backgroundColor: '#525252' }}></div>
- <span style={{ color: '#a3a3a3', fontSize: '10px' }}>Search</span>
- <div style={{ width: '1px', height: '16px', backgroundColor: '#525252' }}></div>
- <span style={{ color: '#a3a3a3', fontSize: '10px' }}>2025-09-26 14:00:49</span>
- <div style={{ width: '1px', height: '16px', backgroundColor: '#525252' }}></div>
- <span style={{ color: '#10b981', fontSize: '10px', fontWeight: 'bold' }}>v{APP_VERSION}</span>
- {isFullscreen && (
- <>
- <div style={{ width: '1px', height: '16px', backgroundColor: '#525252' }}></div>
- <span style={{ color: '#fbbf24', fontSize: '10px' }}>FULLSCREEN MODE</span>
- </>
- )}
- </div>
- )}
-
- {/* Function Keys Bar - Hidden in Chat Mode */}
+ {/* Merged Status & Function Keys Bar - Single Line */}
{mode !== 'chat' && (
<div style={{
backgroundColor: '#1a1a1a',
borderBottom: '1px solid #404040',
- padding: '2px 8px',
- height: '20px',
+ padding: '3px 8px',
+ height: '22px',
display: 'flex',
alignItems: 'center',
+ justifyContent: 'space-between',
gap: '12px',
flexShrink: 0,
- fontSize: '10px'
+ fontSize: '9px'
}}>
- <span style={{ color: '#fbbf24' }}>F1:DASH</span>
- <span style={{ color: '#fbbf24' }}>F2:MKTS</span>
- <span style={{ color: '#fbbf24' }}>F3:NEWS</span>
- <span style={{ color: '#fbbf24' }}>F4:PORT</span>
- <span style={{ color: '#fbbf24' }}>F5:ANLY</span>
- <span style={{ color: '#fbbf24' }}>F6:WATCH</span>
- <span style={{ color: '#fbbf24' }}>F7:RSRCH</span>
- <span style={{ color: '#fbbf24' }}>F8:SCRN</span>
- <span style={{ color: '#fbbf24' }}>F9:TRADE</span>
- <span style={{ color: '#fbbf24' }}>F10:AI</span>
- <span style={{ color: '#fbbf24' }}>F11:FULL</span>
- <span style={{ color: '#fbbf24' }}>F12:PROF</span>
- <span style={{ color: '#666', marginLeft: '8px' }}>|</span>
- <span style={{ color: '#10b981' }}>More tabs in toolbar menus</span>
+ {/* Left: Branding & Status Info */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
+ <span style={{ backgroundColor: '#ea580c', color: 'white', padding: '2px 5px', fontSize: '8px', fontWeight: 'bold' }}>FINXEPT PROFESSIONAL</span>
+ <span style={{ color: '#a3a3a3', fontSize: '9px' }}>Enter Command</span>
+ <div style={{ width: '1px', height: '14px', backgroundColor: '#525252' }}></div>
+ <span style={{ color: '#a3a3a3', fontSize: '9px' }}>Search</span>
+ <div style={{ width: '1px', height: '14px', backgroundColor: '#525252' }}></div>
+ <span style={{ color: '#a3a3a3', fontSize: '9px' }}>2025-09-26 14:00:49</span>
+ <div style={{ width: '1px', height: '14px', backgroundColor: '#525252' }}></div>
+ <span style={{ color: '#10b981', fontSize: '9px', fontWeight: 'bold' }}>v{APP_VERSION}</span>
+ {isFullscreen && (
+ <>
+ <div style={{ width: '1px', height: '14px', backgroundColor: '#525252' }}></div>
+ <span style={{ color: '#fbbf24', fontSize: '9px' }}>FULLSCREEN</span>
+ </>
+ )}
+ </div>
+
+ {/* Right: Function Keys */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: '#fbbf24', fontSize: '9px' }}>F1:DASH</span>
+ <span style={{ color: '#fbbf24', fontSize: '9px' }}>F2:MKTS</span>
+ <span style={{ color: '#fbbf24', fontSize: '9px' }}>F3:NEWS</span>
+ <span style={{ color: '#fbbf24', fontSize: '9px' }}>F4:PORT</span>
+ <span style={{ color: '#fbbf24', fontSize: '9px' }}>F5:BKTEST</span>
+ <span style={{ color: '#fbbf24', fontSize: '9px' }}>F6:WATCH</span>
+ <span style={{ color: '#fbbf24', fontSize: '9px' }}>F7:RSRCH</span>
+ <span style={{ color: '#fbbf24', fontSize: '9px' }}>F8:SCRN</span>
+ <span style={{ color: '#fbbf24', fontSize: '9px' }}>F9:TRADE</span>
+ <span style={{ color: '#fbbf24', fontSize: '9px' }}>F10:AI</span>
+ <span style={{ color: '#fbbf24', fontSize: '9px' }}>F11:FULL</span>
+ <span style={{ color: '#fbbf24', fontSize: '9px' }}>F12:PROF</span>
+ <span style={{ color: '#666', marginLeft: '4px' }}>|</span>
+ <span style={{ color: '#10b981', fontSize: '9px' }}>More tabs in toolbar menus</span>
+ </div>
</div>
)}
@@ -935,13 +927,16 @@ function FinxeptTerminalContent() {
<GeopoliticsTab />
</TabsContent>
<TabsContent value="chat" className="h-full m-0 p-0">
- <ChatTab onNavigateToSettings={() => setActiveTab('settings')} />
+ <ChatTab
+ onNavigateToSettings={() => setActiveTab('settings')}
+ onNavigateToTab={(tabName) => setActiveTab(tabName)}
+ />
</TabsContent>
<TabsContent value="fyers" className="h-full m-0 p-0">
<FyersTab />
</TabsContent>
<TabsContent value="mcp" className="h-full m-0 p-0">
- <MCPTab />
+ <MCPTab onNavigateToTab={(tabName) => setActiveTab(tabName)} />
</TabsContent>
<TabsContent value="profile" className="h-full m-0 p-0">
<ProfileTab />
@@ -952,9 +947,6 @@ function FinxeptTerminalContent() {
<TabsContent value="portfolio" className="h-full m-0 p-0">
<PortfolioTab />
</TabsContent>
- <TabsContent value="analytics" className="h-full m-0 p-0">
- <AnalyticsTab />
- </TabsContent>
<TabsContent value="backtesting" className="h-full m-0 p-0">
<BacktestingTab />
</TabsContent>
diff --git a/fincept-terminal-desktop/src/components/settings/BacktestingProvidersPanel.tsx b/fincept-terminal-desktop/src/components/settings/BacktestingProvidersPanel.tsx
index 2914dd5a9..aa20d743e 100644
--- a/fincept-terminal-desktop/src/components/settings/BacktestingProvidersPanel.tsx
+++ b/fincept-terminal-desktop/src/components/settings/BacktestingProvidersPanel.tsx
@@ -19,11 +19,29 @@ import {
Edit,
Trash2,
Plus,
+ Zap,
} from 'lucide-react';
import { sqliteService, type BacktestingProvider } from '@/services/sqliteService';
import { backtestingRegistry } from '@/services/backtesting/BacktestingProviderRegistry';
import { LeanAdapter } from '@/services/backtesting/adapters/lean';
+// Bloomberg Professional Color Palette
+const BLOOMBERG = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+ MUTED: '#4A4A4A'
+};
+
interface ProviderPanelProps {
colors: {
background: string;
@@ -136,7 +154,11 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {
// Initialize with config
const config = JSON.parse(provider.config);
- const initResult = await registeredProvider.initialize({ settings: config });
+ const initResult = await registeredProvider.initialize({
+ name: provider.name,
+ adapterType: provider.adapter_type,
+ settings: config
+ });
if (!initResult.success) {
throw new Error(initResult.error || 'Initialization failed');
@@ -192,7 +214,11 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {
// Initialize with config
const config = JSON.parse(dbProvider.config);
- const initResult = await registeredProvider.initialize({ settings: config });
+ const initResult = await registeredProvider.initialize({
+ name: dbProvider.name,
+ adapterType: dbProvider.adapter_type,
+ settings: config
+ });
if (!initResult.success) {
throw new Error(initResult.error || 'Initialization failed');
@@ -289,44 +315,80 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {
if (loading) {
return (
- <div style={{ padding: '20px', color: colors.text }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
- <Loader size={20} className="animate-spin" />
- <span>Loading providers...</span>
- </div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: '60px',
+ color: BLOOMBERG.GRAY
+ }}>
+ <Loader size={24} className="animate-spin" style={{ marginRight: '12px' }} />
+ <span style={{ fontSize: '12px', fontWeight: 600, letterSpacing: '0.5px' }}>LOADING PROVIDERS...</span>
</div>
);
}
return (
- <div style={{ padding: '20px' }}>
+ <div style={{ fontFamily: '"IBM Plex Mono", "Consolas", monospace' }}>
{/* Header */}
- <div style={{ marginBottom: '20px' }}>
- <h2 style={{ color: colors.text, fontSize: '1.5rem', marginBottom: '8px' }}>
- Backtesting Providers
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ marginBottom: '24px',
+ paddingBottom: '12px',
+ borderBottom: `2px solid ${BLOOMBERG.ORANGE}`
+ }}>
+ <Activity size={20} color={BLOOMBERG.ORANGE} style={{ filter: `drop-shadow(0 0 4px ${BLOOMBERG.ORANGE})` }} />
+ <h2 style={{
+ color: BLOOMBERG.ORANGE,
+ fontSize: '16px',
+ fontWeight: 700,
+ letterSpacing: '1px',
+ margin: 0,
+ textShadow: `0 0 10px ${BLOOMBERG.ORANGE}40`
+ }}>
+ BACKTESTING PROVIDERS
</h2>
- <p style={{ color: colors.textSecondary, fontSize: '0.9rem' }}>
+ </div>
+
+ {/* Description */}
+ <div style={{
+ marginBottom: '20px',
+ padding: '12px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderLeft: `3px solid ${BLOOMBERG.CYAN}`
+ }}>
+ <p style={{
+ color: BLOOMBERG.GRAY,
+ fontSize: '10px',
+ margin: 0,
+ lineHeight: '1.6'
+ }}>
Manage backtesting engines. Switch between Lean, Backtrader, and other providers seamlessly.
</p>
</div>
{/* Message Banner */}
{message && (
- <div
- style={{
- padding: '12px',
- marginBottom: '20px',
- borderRadius: '6px',
- backgroundColor: message.type === 'success' ? colors.success + '20' : colors.error + '20',
- border: `1px solid ${message.type === 'success' ? colors.success : colors.error}`,
- color: message.type === 'success' ? colors.success : colors.error,
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- }}
- >
- {message.type === 'success' ? <CheckCircle size={18} /> : <AlertCircle size={18} />}
- <span>{message.text}</span>
+ <div style={{
+ padding: '12px 16px',
+ marginBottom: '20px',
+ backgroundColor: message.type === 'success' ? `${BLOOMBERG.GREEN}15` : `${BLOOMBERG.RED}15`,
+ border: `1px solid ${message.type === 'success' ? BLOOMBERG.GREEN : BLOOMBERG.RED}`,
+ borderLeft: `3px solid ${message.type === 'success' ? BLOOMBERG.GREEN : BLOOMBERG.RED}`,
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ }}>
+ {message.type === 'success' ? <CheckCircle size={16} color={BLOOMBERG.GREEN} /> : <AlertCircle size={16} color={BLOOMBERG.RED} />}
+ <span style={{
+ color: message.type === 'success' ? BLOOMBERG.GREEN : BLOOMBERG.RED,
+ fontSize: '10px',
+ fontWeight: 600
+ }}>{message.text}</span>
</div>
)}
@@ -334,51 +396,83 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {
<button
onClick={() => setShowAddForm(!showAddForm)}
style={{
- padding: '10px 16px',
+ padding: '10px 20px',
marginBottom: '20px',
- backgroundColor: colors.accent,
- color: colors.background,
+ backgroundColor: BLOOMBERG.GREEN,
+ color: '#000000',
border: 'none',
- borderRadius: '6px',
+ borderRadius: '4px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '8px',
- fontWeight: '500',
+ fontWeight: 700,
+ fontSize: '11px',
+ letterSpacing: '0.5px',
+ boxShadow: `0 0 12px ${BLOOMBERG.GREEN}40`,
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.boxShadow = `0 0 20px ${BLOOMBERG.GREEN}60`;
+ e.currentTarget.style.transform = 'translateY(-1px)';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.boxShadow = `0 0 12px ${BLOOMBERG.GREEN}40`;
+ e.currentTarget.style.transform = 'translateY(0)';
}}
>
- <Plus size={18} />
- Add Provider
+ <Plus size={16} />
+ ADD PROVIDER
</button>
{/* Add Provider Form */}
{showAddForm && (
- <div
- style={{
- marginBottom: '20px',
- padding: '20px',
- backgroundColor: colors.surface,
- border: `1px solid ${colors.border}`,
- borderRadius: '8px',
- }}
- >
- <h3 style={{ color: colors.text, marginBottom: '16px' }}>Add New Provider</h3>
-
- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ <div style={{
+ marginBottom: '20px',
+ padding: '20px',
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderLeft: `3px solid ${BLOOMBERG.ORANGE}`,
+ borderRadius: '4px',
+ }}>
+ <h3 style={{
+ color: BLOOMBERG.ORANGE,
+ marginBottom: '16px',
+ fontSize: '13px',
+ fontWeight: 700,
+ letterSpacing: '0.5px'
+ }}>ADD NEW PROVIDER</h3>
+
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
<div>
- <label style={{ color: colors.text, display: 'block', marginBottom: '6px' }}>
- Provider Type
+ <label style={{
+ color: BLOOMBERG.WHITE,
+ display: 'block',
+ marginBottom: '6px',
+ fontSize: '10px',
+ fontWeight: 600,
+ letterSpacing: '0.5px'
+ }}>
+ PROVIDER TYPE
</label>
<select
value={newProviderForm.name}
onChange={(e) => setNewProviderForm({ ...newProviderForm, name: e.target.value })}
style={{
width: '100%',
- padding: '8px',
- backgroundColor: colors.background,
- color: colors.text,
- border: `1px solid ${colors.border}`,
- borderRadius: '4px',
+ padding: '10px',
+ backgroundColor: BLOOMBERG.DARK_BG,
+ color: BLOOMBERG.WHITE,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '3px',
+ fontSize: '11px',
+ fontWeight: 500,
+ cursor: 'pointer',
+ appearance: 'none',
+ backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23FF8800' d='M6 9L1 4h10z'/%3E%3C/svg%3E")`,
+ backgroundRepeat: 'no-repeat',
+ backgroundPosition: 'right 10px center',
+ paddingRight: '32px'
}}
>
<option value="QuantConnect Lean">QuantConnect Lean</option>
@@ -390,8 +484,15 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {
</div>
<div>
- <label style={{ color: colors.text, display: 'block', marginBottom: '6px' }}>
- Configuration (JSON)
+ <label style={{
+ color: BLOOMBERG.WHITE,
+ display: 'block',
+ marginBottom: '6px',
+ fontSize: '10px',
+ fontWeight: 600,
+ letterSpacing: '0.5px'
+ }}>
+ CONFIGURATION (JSON)
</label>
<textarea
value={newProviderForm.config}
@@ -399,43 +500,63 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {
rows={10}
style={{
width: '100%',
- padding: '8px',
- backgroundColor: colors.background,
- color: colors.text,
- border: `1px solid ${colors.border}`,
- borderRadius: '4px',
+ padding: '10px',
+ backgroundColor: BLOOMBERG.DARK_BG,
+ color: BLOOMBERG.WHITE,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '3px',
fontFamily: 'monospace',
- fontSize: '0.9rem',
+ fontSize: '10px',
+ lineHeight: '1.5',
+ resize: 'vertical'
}}
/>
</div>
- <div style={{ display: 'flex', gap: '10px' }}>
+ <div style={{ display: 'flex', gap: '12px' }}>
<button
onClick={saveNewProvider}
style={{
- padding: '8px 16px',
- backgroundColor: colors.success,
- color: 'white',
+ padding: '10px 20px',
+ backgroundColor: BLOOMBERG.GREEN,
+ color: '#000000',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
+ fontWeight: 700,
+ fontSize: '10px',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
}}
+ onMouseEnter={(e) => e.currentTarget.style.opacity = '0.8'}
+ onMouseLeave={(e) => e.currentTarget.style.opacity = '1'}
>
- Save
+ SAVE
</button>
<button
onClick={() => setShowAddForm(false)}
style={{
- padding: '8px 16px',
- backgroundColor: colors.surface,
- color: colors.text,
- border: `1px solid ${colors.border}`,
+ padding: '10px 20px',
+ backgroundColor: 'transparent',
+ color: BLOOMBERG.GRAY,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
borderRadius: '4px',
cursor: 'pointer',
+ fontWeight: 700,
+ fontSize: '10px',
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = BLOOMBERG.RED;
+ e.currentTarget.style.color = BLOOMBERG.RED;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;
+ e.currentTarget.style.color = BLOOMBERG.GRAY;
}}
>
- Cancel
+ CANCEL
</button>
</div>
</div>
@@ -443,89 +564,134 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {
)}
{/* Providers List */}
- <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(400px, 1fr))', gap: '16px', marginBottom: '20px' }}>
{providers.length === 0 ? (
- <div
- style={{
- padding: '40px',
- textAlign: 'center',
- color: colors.textSecondary,
- backgroundColor: colors.surface,
- border: `1px dashed ${colors.border}`,
- borderRadius: '8px',
- }}
- >
- <Activity size={48} style={{ margin: '0 auto 16px', opacity: 0.5 }} />
- <p>No providers configured</p>
- <p style={{ fontSize: '0.9rem', marginTop: '8px' }}>
- Click "Add Provider" to configure your first backtesting engine
+ <div style={{
+ gridColumn: '1 / -1',
+ padding: '60px 40px',
+ textAlign: 'center',
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ border: `1px dashed ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ }}>
+ <Activity size={48} style={{ margin: '0 auto 16px', opacity: 0.3, color: BLOOMBERG.ORANGE }} />
+ <p style={{ color: BLOOMBERG.WHITE, fontSize: '13px', fontWeight: 600, marginBottom: '8px' }}>
+ NO PROVIDERS CONFIGURED
+ </p>
+ <p style={{ color: BLOOMBERG.GRAY, fontSize: '10px' }}>
+ Click "ADD PROVIDER" to configure your first backtesting engine
</p>
</div>
) : (
providers.map((provider) => {
const status = statuses[provider.name] || { connected: false, testing: false };
const capabilities = getProviderCapabilities(provider.name);
+ const isActive = provider.is_active;
return (
<div
key={provider.id}
style={{
- padding: '20px',
- backgroundColor: colors.surface,
- border: `2px solid ${provider.is_active ? colors.accent : colors.border}`,
- borderRadius: '8px',
+ padding: '16px',
+ backgroundColor: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${isActive ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,
+ borderLeft: `3px solid ${isActive ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ transition: 'all 0.2s',
+ position: 'relative',
+ overflow: 'hidden'
+ }}
+ onMouseEnter={(e) => {
+ if (!isActive) {
+ e.currentTarget.style.backgroundColor = BLOOMBERG.HOVER;
+ e.currentTarget.style.borderColor = BLOOMBERG.MUTED;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (!isActive) {
+ e.currentTarget.style.backgroundColor = BLOOMBERG.PANEL_BG;
+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;
+ }
}}
>
+ {/* Active Glow */}
+ {isActive && (
+ <div style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ right: 0,
+ height: '1px',
+ background: `linear-gradient(90deg, transparent, ${BLOOMBERG.ORANGE}, transparent)`,
+ opacity: 0.5
+ }} />
+ )}
+
{/* Header */}
- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '12px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <Activity size={24} style={{ color: colors.accent }} />
+ <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: '12px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px', flex: 1 }}>
+ <Activity size={20} style={{ color: isActive ? BLOOMBERG.ORANGE : BLOOMBERG.GRAY }} />
<div>
- <h3 style={{ color: colors.text, margin: 0 }}>{provider.name}</h3>
- <p style={{ color: colors.textSecondary, fontSize: '0.85rem', margin: 0 }}>
+ <h3 style={{
+ color: isActive ? BLOOMBERG.ORANGE : BLOOMBERG.WHITE,
+ margin: 0,
+ fontSize: '12px',
+ fontWeight: 700,
+ letterSpacing: '0.5px'
+ }}>{provider.name}</h3>
+ <p style={{
+ color: BLOOMBERG.GRAY,
+ fontSize: '9px',
+ margin: 0,
+ fontWeight: 500
+ }}>
{provider.adapter_type}
</p>
</div>
</div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- {/* Active Badge */}
- {provider.is_active && (
- <span
- style={{
- padding: '4px 12px',
- backgroundColor: colors.success + '20',
- color: colors.success,
- borderRadius: '12px',
- fontSize: '0.85rem',
- fontWeight: '500',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- }}
- >
- <Check size={14} />
- Active
- </span>
+ {/* Status Badges */}
+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: '4px' }}>
+ {isActive && (
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ padding: '3px 8px',
+ backgroundColor: `${BLOOMBERG.GREEN}20`,
+ borderRadius: '3px'
+ }}>
+ <div style={{
+ width: '6px',
+ height: '6px',
+ borderRadius: '50%',
+ backgroundColor: BLOOMBERG.GREEN,
+ boxShadow: `0 0 6px ${BLOOMBERG.GREEN}`
+ }} />
+ <span style={{
+ color: BLOOMBERG.GREEN,
+ fontSize: '9px',
+ fontWeight: 700
+ }}>ACTIVE</span>
+ </div>
)}
- {/* Connection Status */}
{status.connected && (
- <span
- style={{
- padding: '4px 12px',
- backgroundColor: colors.success + '20',
- color: colors.success,
- borderRadius: '12px',
- fontSize: '0.85rem',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- }}
- >
- <CheckCircle size={14} />
- Connected
- </span>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ padding: '3px 8px',
+ backgroundColor: `${BLOOMBERG.CYAN}20`,
+ borderRadius: '3px'
+ }}>
+ <CheckCircle size={10} color={BLOOMBERG.CYAN} />
+ <span style={{
+ color: BLOOMBERG.CYAN,
+ fontSize: '9px',
+ fontWeight: 700
+ }}>CONNECTED</span>
+ </div>
)}
</div>
</div>
@@ -533,55 +699,88 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {
{/* Capabilities */}
{capabilities && (
<div style={{ marginBottom: '12px' }}>
- <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
{capabilities.backtesting && (
- <span style={{ ...capabilityBadgeStyle, color: colors.text }}>Backtesting</span>
+ <span style={{
+ padding: '3px 8px',
+ backgroundColor: `${BLOOMBERG.ORANGE}15`,
+ border: `1px solid ${BLOOMBERG.ORANGE}40`,
+ borderRadius: '3px',
+ color: BLOOMBERG.ORANGE,
+ fontSize: '8px',
+ fontWeight: 700,
+ letterSpacing: '0.5px'
+ }}>BACKTESTING</span>
)}
{capabilities.optimization && (
- <span style={{ ...capabilityBadgeStyle, color: colors.text }}>Optimization</span>
+ <span style={{
+ padding: '3px 8px',
+ backgroundColor: `${BLOOMBERG.CYAN}15`,
+ border: `1px solid ${BLOOMBERG.CYAN}40`,
+ borderRadius: '3px',
+ color: BLOOMBERG.CYAN,
+ fontSize: '8px',
+ fontWeight: 700,
+ letterSpacing: '0.5px'
+ }}>OPTIMIZATION</span>
)}
{capabilities.liveTrading && (
- <span style={{ ...capabilityBadgeStyle, color: colors.text }}>Live Trading</span>
+ <span style={{
+ padding: '3px 8px',
+ backgroundColor: `${BLOOMBERG.GREEN}15`,
+ border: `1px solid ${BLOOMBERG.GREEN}40`,
+ borderRadius: '3px',
+ color: BLOOMBERG.GREEN,
+ fontSize: '8px',
+ fontWeight: 700,
+ letterSpacing: '0.5px'
+ }}>LIVE</span>
)}
{capabilities.research && (
- <span style={{ ...capabilityBadgeStyle, color: colors.text }}>Research</span>
+ <span style={{
+ padding: '3px 8px',
+ backgroundColor: `${BLOOMBERG.YELLOW}15`,
+ border: `1px solid ${BLOOMBERG.YELLOW}40`,
+ borderRadius: '3px',
+ color: BLOOMBERG.YELLOW,
+ fontSize: '8px',
+ fontWeight: 700,
+ letterSpacing: '0.5px'
+ }}>RESEARCH</span>
)}
</div>
</div>
)}
- {/* Status Message */}
+ {/* Status/Error Messages */}
{status.message && (
- <div
- style={{
- padding: '8px 12px',
- marginBottom: '12px',
- backgroundColor: status.connected ? colors.success + '10' : colors.error + '10',
- borderRadius: '4px',
- fontSize: '0.9rem',
- color: status.connected ? colors.success : colors.error,
- }}
- >
+ <div style={{
+ padding: '8px 10px',
+ marginBottom: '12px',
+ backgroundColor: status.connected ? `${BLOOMBERG.GREEN}10` : `${BLOOMBERG.RED}10`,
+ border: `1px solid ${status.connected ? BLOOMBERG.GREEN : BLOOMBERG.RED}40`,
+ borderRadius: '3px',
+ fontSize: '9px',
+ color: status.connected ? BLOOMBERG.GREEN : BLOOMBERG.RED,
+ }}>
{status.message}
</div>
)}
- {/* Error Message */}
{status.error && (
- <div
- style={{
- padding: '8px 12px',
- marginBottom: '12px',
- backgroundColor: colors.error + '10',
- borderRadius: '4px',
- fontSize: '0.9rem',
- color: colors.error,
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- }}
- >
- <AlertCircle size={16} />
+ <div style={{
+ padding: '8px 10px',
+ marginBottom: '12px',
+ backgroundColor: `${BLOOMBERG.RED}10`,
+ border: `1px solid ${BLOOMBERG.RED}40`,
+ borderRadius: '3px',
+ fontSize: '9px',
+ color: BLOOMBERG.RED,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ }}>
+ <AlertCircle size={12} />
{status.error}
</div>
)}
@@ -592,67 +791,97 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {
onClick={() => testConnection(provider)}
disabled={status.testing}
style={{
- padding: '8px 16px',
- backgroundColor: colors.accent,
- color: colors.background,
+ flex: 1,
+ padding: '8px 12px',
+ backgroundColor: status.testing ? BLOOMBERG.MUTED : BLOOMBERG.ORANGE,
+ color: '#000000',
border: 'none',
- borderRadius: '4px',
+ borderRadius: '3px',
cursor: status.testing ? 'not-allowed' : 'pointer',
opacity: status.testing ? 0.6 : 1,
display: 'flex',
alignItems: 'center',
+ justifyContent: 'center',
gap: '6px',
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ if (!status.testing) e.currentTarget.style.opacity = '0.8';
+ }}
+ onMouseLeave={(e) => {
+ if (!status.testing) e.currentTarget.style.opacity = '1';
}}
>
{status.testing ? (
<>
- <Loader size={16} className="animate-spin" />
- Testing...
+ <Loader size={12} className="animate-spin" />
+ TESTING...
</>
) : (
<>
- <PlayCircle size={16} />
- Test Connection
+ <PlayCircle size={12} />
+ TEST
</>
)}
</button>
- {!provider.is_active && (
+ {!isActive && (
<button
onClick={() => activateProvider(provider.name)}
style={{
- padding: '8px 16px',
- backgroundColor: colors.success,
- color: 'white',
+ padding: '8px 12px',
+ backgroundColor: BLOOMBERG.GREEN,
+ color: '#000000',
border: 'none',
- borderRadius: '4px',
+ borderRadius: '3px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '6px',
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
}}
+ onMouseEnter={(e) => e.currentTarget.style.opacity = '0.8'}
+ onMouseLeave={(e) => e.currentTarget.style.opacity = '1'}
>
- <Check size={16} />
- Activate
+ <Zap size={12} />
+ ACTIVATE
</button>
)}
<button
onClick={() => deleteProvider(provider.name)}
style={{
- padding: '8px 16px',
- backgroundColor: colors.error,
- color: 'white',
- border: 'none',
- borderRadius: '4px',
+ padding: '8px 12px',
+ backgroundColor: 'transparent',
+ color: BLOOMBERG.GRAY,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '3px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '6px',
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = BLOOMBERG.RED;
+ e.currentTarget.style.color = BLOOMBERG.RED;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = BLOOMBERG.BORDER;
+ e.currentTarget.style.color = BLOOMBERG.GRAY;
}}
>
- <Trash2 size={16} />
- Delete
+ <Trash2 size={12} />
+ DELETE
</button>
</div>
</div>
@@ -661,33 +890,47 @@ export function BacktestingProvidersPanel({ colors }: ProviderPanelProps) {
)}
</div>
- {/* Registry Info */}
- <div
- style={{
- marginTop: '20px',
- padding: '16px',
- backgroundColor: colors.surface,
- border: `1px solid ${colors.border}`,
- borderRadius: '8px',
- }}
- >
- <h4 style={{ color: colors.text, marginBottom: '12px' }}>Provider Registry Status</h4>
- <div style={{ color: colors.textSecondary, fontSize: '0.9rem' }}>
- <p>
- Registered providers: {backtestingRegistry.listProviders().length}
- </p>
- <p>
- Active provider: {backtestingRegistry.getActiveProvider()?.name || 'None'}
- </p>
+ {/* Registry Status */}
+ <div style={{
+ padding: '16px',
+ backgroundColor: BLOOMBERG.HEADER_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderTop: `2px solid ${BLOOMBERG.CYAN}`,
+ borderRadius: '4px',
+ display: 'grid',
+ gridTemplateColumns: 'repeat(2, 1fr)',
+ gap: '16px'
+ }}>
+ <div>
+ <div style={{
+ color: BLOOMBERG.GRAY,
+ fontSize: '9px',
+ fontWeight: 600,
+ letterSpacing: '0.5px',
+ marginBottom: '6px'
+ }}>REGISTERED PROVIDERS</div>
+ <div style={{
+ color: BLOOMBERG.CYAN,
+ fontSize: '20px',
+ fontWeight: 700
+ }}>{backtestingRegistry.listProviders().length}</div>
+ </div>
+ <div>
+ <div style={{
+ color: BLOOMBERG.GRAY,
+ fontSize: '9px',
+ fontWeight: 600,
+ letterSpacing: '0.5px',
+ marginBottom: '6px'
+ }}>ACTIVE PROVIDER</div>
+ <div style={{
+ color: BLOOMBERG.GREEN,
+ fontSize: '12px',
+ fontWeight: 700,
+ letterSpacing: '0.5px'
+ }}>{backtestingRegistry.getActiveProvider()?.name || 'NONE'}</div>
</div>
</div>
</div>
);
}
-
-const capabilityBadgeStyle: React.CSSProperties = {
- padding: '4px 8px',
- backgroundColor: 'rgba(255, 255, 255, 0.1)',
- borderRadius: '4px',
- fontSize: '0.8rem',
-};
diff --git a/fincept-terminal-desktop/src/components/tabs/AnalyticsTab.tsx b/fincept-terminal-desktop/src/components/tabs/AnalyticsTab.tsx
deleted file mode 100644
index b7dfbb6a5..000000000
--- a/fincept-terminal-desktop/src/components/tabs/AnalyticsTab.tsx
+++ /dev/null
@@ -1,630 +0,0 @@
-import React, { useState, useEffect } from 'react';
-import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, AreaChart, Area, ScatterChart, Scatter, RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar, ComposedChart, ReferenceLine, Treemap, FunnelChart, Funnel, LabelList } from 'recharts';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-
-const AnalyticsTab: React.FC = () => {
- const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
- const [currentTime, setCurrentTime] = useState(new Date());
- const [dataUpdateCount, setDataUpdateCount] = useState(0);
- const [alertCount, setAlertCount] = useState(23);
-
- useEffect(() => {
- const timer = setInterval(() => {
- setCurrentTime(new Date());
- setDataUpdateCount(prev => prev + 1);
- if (Math.random() > 0.8) setAlertCount(prev => prev + 1);
- }, 2000);
- return () => clearInterval(timer);
- }, []);
-
- // Generate various chart data
- const priceData = Array.from({ length: 30 }, (_, i) => ({
- time: i + 1,
- price: 150 + Math.sin(i * 0.1) * 20 + Math.random() * 10,
- volume: Math.random() * 1000000 + 500000,
- high: 150 + Math.sin(i * 0.1) * 20 + Math.random() * 15 + 5,
- low: 150 + Math.sin(i * 0.1) * 20 + Math.random() * 15 - 5,
- volatility: Math.random() * 5 + 2
- }));
-
- const sectorData = [
- { sector: 'Technology', value: 28.5, growth: 12.4, pe: 24.8 },
- { sector: 'Healthcare', value: 15.2, growth: 8.7, pe: 18.9 },
- { sector: 'Finance', value: 18.9, growth: 6.3, pe: 14.2 },
- { sector: 'Energy', value: 12.1, growth: 15.8, pe: 12.5 },
- { sector: 'Consumer', value: 14.7, growth: 4.2, pe: 22.1 },
- { sector: 'Industrial', value: 10.6, growth: 7.9, pe: 16.7 }
- ];
-
- const correlationData = Array.from({ length: 20 }, (_, i) => ({
- x: Math.random() * 10,
- y: Math.random() * 10,
- size: Math.random() * 100 + 20
- }));
-
- const portfolioData = [
- { asset: 'Stocks', allocation: 65, returns: 14.2, risk: 18.5 },
- { asset: 'Bonds', allocation: 25, returns: 4.8, risk: 6.2 },
- { asset: 'Commodities', allocation: 7, returns: 8.9, risk: 22.1 },
- { asset: 'Cash', allocation: 3, returns: 2.1, risk: 0.5 }
- ];
-
- const riskMetrics = Array.from({ length: 90 }, (_, i) => ({
- day: i + 1,
- var: Math.random() * 5 + 2,
- sharpe: Math.random() * 2 + 0.5,
- beta: Math.random() * 1.5 + 0.5,
- alpha: Math.random() * 4 - 2,
- drawdown: Math.random() * 15
- }));
-
- const momentumData = Array.from({ length: 50 }, (_, i) => ({
- stock: i + 1,
- momentum: Math.random() * 100 - 50,
- rsi: Math.random() * 100,
- macd: Math.random() * 10 - 5
- }));
-
- const liquidityData = Array.from({ length: 24 }, (_, i) => ({
- hour: i,
- volume: Math.random() * 1000000 + 200000,
- spread: Math.random() * 0.5 + 0.1,
- depth: Math.random() * 50000 + 10000
- }));
-
- const technicalData = Array.from({ length: 30 }, (_, i) => ({
- period: i + 1,
- price: 100 + Math.sin(i * 0.2) * 15 + Math.random() * 5,
- sma20: 100 + Math.sin((i - 2) * 0.2) * 12,
- ema12: 100 + Math.sin((i - 1) * 0.2) * 13,
- bb_upper: 100 + Math.sin(i * 0.2) * 15 + 10,
- bb_lower: 100 + Math.sin(i * 0.2) * 15 - 10
- }));
-
- const fundamentalData = [
- { metric: 'P/E Ratio', value: 22.8, benchmark: 18.5 },
- { metric: 'EV/EBITDA', value: 14.2, benchmark: 12.1 },
- { metric: 'P/B Ratio', value: 3.4, benchmark: 2.8 },
- { metric: 'ROE', value: 18.7, benchmark: 15.2 },
- { metric: 'ROA', value: 8.9, benchmark: 7.1 },
- { metric: 'Debt/Equity', value: 0.65, benchmark: 0.8 }
- ];
-
- const optionsData = Array.from({ length: 10 }, (_, i) => ({
- strike: 140 + i * 5,
- calls: Math.random() * 1000 + 100,
- puts: Math.random() * 800 + 50,
- iv: Math.random() * 40 + 20,
- delta: 1 - (i / 10),
- gamma: Math.random() * 0.1,
- theta: -Math.random() * 0.5
- }));
-
- const volatilityData = Array.from({ length: 252 }, (_, i) => ({
- day: i + 1,
- realized: Math.random() * 40 + 10,
- implied: Math.random() * 45 + 15,
- historical: Math.random() * 35 + 12
- }));
-
- const economicData = [
- { indicator: 'GDP Growth', current: 6.7, forecast: 6.4, impact: 'High' },
- { indicator: 'Inflation', current: 4.2, forecast: 3.8, impact: 'Critical' },
- { indicator: 'Unemployment', current: 3.8, forecast: 4.1, impact: 'Medium' },
- { indicator: 'Interest Rate', current: 5.25, forecast: 5.5, impact: 'Critical' },
- { indicator: 'Oil Price', current: 82.45, forecast: 85.2, impact: 'High' }
- ];
-
- const sentimentData = Array.from({ length: 30 }, (_, i) => ({
- date: i + 1,
- bullish: Math.random() * 100,
- bearish: Math.random() * 100,
- neutral: Math.random() * 100,
- fear: Math.random() * 100,
- greed: Math.random() * 100
- }));
-
- const flowsData = Array.from({ length: 20 }, (_, i) => ({
- date: i + 1,
- inflows: Math.random() * 2000 - 1000,
- outflows: Math.random() * 1500 - 750,
- net: Math.random() * 1000 - 500
- }));
-
- const performanceData = [
- { period: '1D', return: 1.2, benchmark: 0.8 },
- { period: '1W', return: 3.4, benchmark: 2.1 },
- { period: '1M', return: 8.7, benchmark: 6.2 },
- { period: '3M', return: 15.2, benchmark: 12.8 },
- { period: '6M', return: 24.6, benchmark: 18.9 },
- { period: '1Y', return: 34.8, benchmark: 28.4 }
- ];
-
- const attribution = [
- { factor: 'Stock Selection', contribution: 4.8 },
- { factor: 'Sector Allocation', contribution: 2.3 },
- { factor: 'Market Timing', contribution: -1.2 },
- { factor: 'Currency', contribution: 0.8 },
- { factor: 'Other', contribution: 1.4 }
- ];
-
- const moneyFlowData = Array.from({ length: 30 }, (_, i) => ({
- day: i + 1,
- mfi: Math.random() * 100,
- obv: Math.random() * 1000000,
- adl: Math.random() * 50000 - 25000,
- cmf: Math.random() * 0.4 - 0.2
- }));
-
- const marketData = [
- { market: 'US', weight: 55.2, return: 12.4, volatility: 16.8 },
- { market: 'Europe', weight: 18.7, return: 8.9, volatility: 19.2 },
- { market: 'Asia', weight: 15.8, return: 15.6, volatility: 22.1 },
- { market: 'Emerging', weight: 10.3, return: 18.2, volatility: 28.4 }
- ];
-
- const bondData = Array.from({ length: 30 }, (_, i) => ({
- maturity: i / 2 + 0.25,
- yield: 3.5 + (i * 0.1) + Math.random() * 0.5,
- duration: i / 3 + 1,
- spread: Math.random() * 200 + 50
- }));
-
- const derivativesData = Array.from({ length: 15 }, (_, i) => ({
- type: ['Futures', 'Options', 'Swaps', 'Forwards'][i % 4],
- notional: Math.random() * 10000000 + 1000000,
- pnl: Math.random() * 100000 - 50000,
- risk: Math.random() * 50000 + 10000
- }));
-
- const stressData = [
- { scenario: 'Base Case', probability: 60, impact: 0 },
- { scenario: 'Recession', probability: 25, impact: -25 },
- { scenario: 'Market Crash', probability: 10, impact: -45 },
- { scenario: 'Black Swan', probability: 5, impact: -65 }
- ];
-
- // Chart component wrapper with Bloomberg styling
- const ChartBox = ({ title, children, width = "100%", height = "160px" }: {
- title: string,
- children: React.ReactNode,
- width?: string,
- height?: string
- }) => (
- <div style={{
- backgroundColor: colors.panel,
- border: `1px solid ${colors.textMuted}`,
- padding: '4px',
- height,
- width,
- overflow: 'hidden'
- }}>
- <div style={{
- color: colors.primary,
- fontSize: '10px',
- fontWeight: 'bold',
- marginBottom: '2px',
- textAlign: 'center',
- borderBottom: `1px solid ${colors.textMuted}`,
- paddingBottom: '2px'
- }}>
- {title}
- </div>
- <div style={{ height: 'calc(100% - 20px)' }}>
- {children}
- </div>
- </div>
- );
-
- return (
- <div style={{
- height: '100%',
- backgroundColor: colors.background,
- color: colors.text,
- fontFamily: 'Consolas, monospace',
- overflow: 'hidden',
- display: 'flex',
- flexDirection: 'column',
- fontSize: '12px'
- }}>
- {/* Header */}
- <div style={{
- backgroundColor: colors.panel,
- borderBottom: `1px solid ${colors.textMuted}`,
- padding: '4px 8px',
- flexShrink: 0
- }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', marginBottom: '2px' }}>
- <span style={{ color: colors.primary, fontWeight: 'bold' }}>FINANCIAL ANALYTICS DASHBOARD</span>
- <span style={{ color: colors.text }}>|</span>
- <span style={{ color: colors.secondary, fontWeight: 'bold' }}>PORTFOLIO VALUE: $2.45M</span>
- <span style={{ color: colors.text }}>|</span>
- <span style={{ color: colors.info }}>P&L TODAY: +$12,456 (+0.51%)</span>
- <span style={{ color: colors.text }}>|</span>
- <span style={{ color: colors.warning }}>ALERTS: {alertCount}</span>
- <span style={{ color: colors.text }}>|</span>
- <span style={{ color: colors.secondary }}>● LIVE DATA</span>
- <span style={{ color: colors.text }}>|</span>
- <span style={{ color: colors.text }}>{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC</span>
- </div>
-
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px' }}>
- <span style={{ color: colors.textMuted }}>ANALYTICS:</span>
- <span style={{ color: colors.secondary }}>RISK●</span>
- <span style={{ color: colors.secondary }}>PERFORMANCE●</span>
- <span style={{ color: colors.secondary }}>ATTRIBUTION●</span>
- <span style={{ color: colors.secondary }}>TECHNICAL●</span>
- <span style={{ color: colors.text }}>|</span>
- <span style={{ color: colors.textMuted }}>MODELS:</span>
- <span style={{ color: colors.info }}>VaR: $45K</span>
- <span style={{ color: colors.warning }}>Sharpe: 1.84</span>
- <span style={{ color: colors.purple }}>Beta: 0.97</span>
- <span style={{ color: colors.text }}>|</span>
- <span style={{ color: colors.textMuted }}>UPDATES:</span>
- <span style={{ color: colors.accent }}>{dataUpdateCount}</span>
- </div>
- </div>
-
- {/* Function Keys Bar */}
- <div style={{
- backgroundColor: colors.panel,
- borderBottom: `1px solid ${colors.textMuted}`,
- padding: '2px 4px',
- flexShrink: 0
- }}>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(10, 1fr)', gap: '2px' }}>
- {[
- { key: "F1", label: "RISK", status: "●" },
- { key: "F2", label: "PERF", status: "●" },
- { key: "F3", label: "TECH", status: "●" },
- { key: "F4", label: "FUND", status: "●" },
- { key: "F5", label: "OPTIONS", status: "●" },
- { key: "F6", label: "FLOWS", status: "●" },
- { key: "F7", label: "STRESS", status: "◐" },
- { key: "F8", label: "DERIV", status: "●" },
- { key: "F9", label: "MACRO", status: "●" },
- { key: "F10", label: "ALERT", status: "●" }
- ].map(item => (
- <button key={item.key} style={{
- backgroundColor: colors.background,
- border: `1px solid ${colors.textMuted}`,
- color: colors.text,
- padding: '2px 4px',
- fontSize: '9px',
- height: '16px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center'
- }}>
- <span style={{ color: colors.warning }}>{item.key}:</span>
- <span style={{ marginLeft: '2px' }}>{item.label}</span>
- <span style={{
- marginLeft: '2px',
- color: item.status === '●' ? colors.secondary : colors.warning
- }}>
- {item.status}
- </span>
- </button>
- ))}
- </div>
- </div>
-
- {/* Main Content - 4x5 Grid (20 charts) */}
- <div style={{ flex: 1, overflow: 'auto', padding: '2px', backgroundColor: '#050505' }}>
- <div style={{
- display: 'grid',
- gridTemplateColumns: 'repeat(5, 1fr)',
- gridTemplateRows: 'repeat(4, 1fr)',
- gap: '3px',
- height: '100%'
- }}>
- {/* Row 1 */}
- <ChartBox title="PRICE & VOLUME">
- <ResponsiveContainer width="100%" height="100%">
- <ComposedChart data={priceData.slice(0, 15)}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis dataKey="time" stroke={colors.text} fontSize={8} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Line type="monotone" dataKey="price" stroke={colors.info} strokeWidth={1} dot={false} />
- <Bar dataKey="volume" fill={colors.textMuted} opacity={0.3} />
- </ComposedChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="SECTOR ALLOCATION">
- <ResponsiveContainer width="100%" height="100%">
- <PieChart>
- <Pie
- data={sectorData}
- dataKey="value"
- nameKey="sector"
- cx="50%"
- cy="50%"
- outerRadius={50}
- fill={colors.info}
- >
- {sectorData.map((entry, index) => (
- <Cell key={`cell-${index}`} fill={[colors.info, colors.secondary, colors.warning, colors.alert, colors.purple, colors.accent][index % 6]} />
- ))}
- </Pie>
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- </PieChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="CORRELATION SCATTER">
- <ResponsiveContainer width="100%" height="100%">
- <ScatterChart data={correlationData}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis stroke={colors.text} fontSize={8} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Scatter dataKey="y" fill={colors.secondary} />
- </ScatterChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="PORTFOLIO COMPOSITION">
- <ResponsiveContainer width="100%" height="100%">
- <BarChart data={portfolioData}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis dataKey="asset" stroke={colors.text} fontSize={8} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Bar dataKey="allocation" fill={colors.primary} />
- </BarChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="RISK METRICS">
- <ResponsiveContainer width="100%" height="100%">
- <LineChart data={riskMetrics.slice(0, 20)}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis dataKey="day" stroke={colors.text} fontSize={8} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Line type="monotone" dataKey="var" stroke={colors.alert} strokeWidth={1} dot={false} />
- <Line type="monotone" dataKey="sharpe" stroke={colors.secondary} strokeWidth={1} dot={false} />
- </LineChart>
- </ResponsiveContainer>
- </ChartBox>
-
- {/* Row 2 */}
- <ChartBox title="MOMENTUM ANALYSIS">
- <ResponsiveContainer width="100%" height="100%">
- <BarChart data={momentumData.slice(0, 10)}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis dataKey="stock" stroke={colors.text} fontSize={8} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Bar dataKey="momentum" fill={colors.secondary} />
- </BarChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="INTRADAY LIQUIDITY">
- <ResponsiveContainer width="100%" height="100%">
- <AreaChart data={liquidityData}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis dataKey="hour" stroke={colors.text} fontSize={8} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Area type="monotone" dataKey="volume" stroke={colors.accent} fill={colors.accent} fillOpacity={0.3} />
- </AreaChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="TECHNICAL INDICATORS">
- <ResponsiveContainer width="100%" height="100%">
- <LineChart data={technicalData}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis dataKey="period" stroke={colors.text} fontSize={8} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Line type="monotone" dataKey="price" stroke={colors.text} strokeWidth={2} dot={false} />
- <Line type="monotone" dataKey="sma20" stroke={colors.warning} strokeWidth={1} dot={false} />
- <Line type="monotone" dataKey="ema12" stroke={colors.secondary} strokeWidth={1} dot={false} />
- </LineChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="FUNDAMENTAL RATIOS">
- <ResponsiveContainer width="100%" height="100%">
- <BarChart data={fundamentalData} layout="horizontal">
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis type="number" stroke={colors.text} fontSize={8} />
- <YAxis type="category" dataKey="metric" stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Bar dataKey="value" fill={colors.info} />
- <Bar dataKey="benchmark" fill={colors.textMuted} opacity={0.5} />
- </BarChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="OPTIONS FLOW">
- <ResponsiveContainer width="100%" height="100%">
- <ComposedChart data={optionsData}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis dataKey="strike" stroke={colors.text} fontSize={8} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Bar dataKey="calls" fill={colors.secondary} />
- <Bar dataKey="puts" fill={colors.alert} />
- <Line type="monotone" dataKey="iv" stroke={colors.warning} strokeWidth={1} />
- </ComposedChart>
- </ResponsiveContainer>
- </ChartBox>
-
- {/* Row 3 */}
- <ChartBox title="VOLATILITY SURFACE">
- <ResponsiveContainer width="100%" height="100%">
- <AreaChart data={volatilityData.slice(0, 30)}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis dataKey="day" stroke={colors.text} fontSize={8} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Area type="monotone" dataKey="realized" stackId="1" stroke={colors.secondary} fill={colors.secondary} fillOpacity={0.6} />
- <Area type="monotone" dataKey="implied" stackId="1" stroke={colors.warning} fill={colors.warning} fillOpacity={0.6} />
- </AreaChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="ECONOMIC INDICATORS">
- <ResponsiveContainer width="100%" height="100%">
- <BarChart data={economicData}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis dataKey="indicator" stroke={colors.text} fontSize={7} angle={-45} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Bar dataKey="current" fill={colors.info} />
- <Bar dataKey="forecast" fill={colors.primary} />
- </BarChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="MARKET SENTIMENT">
- <ResponsiveContainer width="100%" height="100%">
- <AreaChart data={sentimentData.slice(0, 15)}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis dataKey="date" stroke={colors.text} fontSize={8} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Area type="monotone" dataKey="bullish" stackId="1" stroke={colors.secondary} fill={colors.secondary} fillOpacity={0.4} />
- <Area type="monotone" dataKey="bearish" stackId="1" stroke={colors.alert} fill={colors.alert} fillOpacity={0.4} />
- </AreaChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="FUND FLOWS">
- <ResponsiveContainer width="100%" height="100%">
- <ComposedChart data={flowsData}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis dataKey="date" stroke={colors.text} fontSize={8} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Bar dataKey="inflows" fill={colors.secondary} />
- <Bar dataKey="outflows" fill={colors.alert} />
- <Line type="monotone" dataKey="net" stroke={colors.warning} strokeWidth={2} />
- </ComposedChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="PERFORMANCE ATTRIBUTION">
- <ResponsiveContainer width="100%" height="100%">
- <BarChart data={performanceData}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis dataKey="period" stroke={colors.text} fontSize={8} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Bar dataKey="return" fill={colors.secondary} />
- <Bar dataKey="benchmark" fill={colors.textMuted} opacity={0.5} />
- </BarChart>
- </ResponsiveContainer>
- </ChartBox>
-
- {/* Row 4 */}
- <ChartBox title="FACTOR ATTRIBUTION">
- <ResponsiveContainer width="100%" height="100%">
- <BarChart data={attribution} layout="horizontal">
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis type="number" stroke={colors.text} fontSize={8} />
- <YAxis type="category" dataKey="factor" stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Bar dataKey="contribution" fill={colors.secondary} />
- </BarChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="MONEY FLOW INDEX">
- <ResponsiveContainer width="100%" height="100%">
- <LineChart data={moneyFlowData}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis dataKey="day" stroke={colors.text} fontSize={8} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Line type="monotone" dataKey="mfi" stroke={colors.purple} strokeWidth={1} dot={false} />
- <ReferenceLine y={20} stroke={colors.alert} strokeDasharray="2 2" />
- <ReferenceLine y={80} stroke={colors.alert} strokeDasharray="2 2" />
- </LineChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="GLOBAL MARKETS">
- <ResponsiveContainer width="100%" height="100%">
- <RadarChart data={marketData}>
- <PolarGrid stroke={colors.textMuted} />
- <PolarAngleAxis dataKey="market" tick={{ fontSize: 9, fill: colors.text }} />
- <PolarRadiusAxis tick={{ fontSize: 8, fill: colors.textMuted }} />
- <Radar
- name="Return"
- dataKey="return"
- stroke={colors.secondary}
- fill={colors.secondary}
- fillOpacity={0.3}
- />
- <Radar
- name="Volatility"
- dataKey="volatility"
- stroke={colors.alert}
- fill={colors.alert}
- fillOpacity={0.2}
- />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- </RadarChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="YIELD CURVE">
- <ResponsiveContainer width="100%" height="100%">
- <AreaChart data={bondData}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis dataKey="maturity" stroke={colors.text} fontSize={8} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Area type="monotone" dataKey="yield" stroke={colors.warning} fill={colors.warning} fillOpacity={0.3} />
- </AreaChart>
- </ResponsiveContainer>
- </ChartBox>
-
- <ChartBox title="STRESS SCENARIOS">
- <ResponsiveContainer width="100%" height="100%">
- <ComposedChart data={stressData}>
- <CartesianGrid strokeDasharray="1 1" stroke={colors.textMuted} opacity={0.3} />
- <XAxis dataKey="scenario" stroke={colors.text} fontSize={7} angle={-45} />
- <YAxis stroke={colors.text} fontSize={8} />
- <Tooltip contentStyle={{ backgroundColor: colors.background, border: `1px solid ${colors.textMuted}`, fontSize: '9px' }} />
- <Bar dataKey="probability" fill={colors.info} />
- <Line type="monotone" dataKey="impact" stroke={colors.alert} strokeWidth={2} />
- </ComposedChart>
- </ResponsiveContainer>
- </ChartBox>
- </div>
- </div>
-
- {/* Status Bar */}
- <div style={{
- borderTop: `1px solid ${colors.textMuted}`,
- backgroundColor: colors.panel,
- padding: '2px 8px',
- fontSize: '10px',
- color: colors.textMuted,
- flexShrink: 0
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <div style={{ display: 'flex', gap: '16px' }}>
- <span>Financial Analytics System v2.8.1 | Real-time portfolio analysis</span>
- <span>Models: 47 Active | Data Sources: 23 | Processing: 1.2M ticks/min</span>
- </div>
- <div style={{ display: 'flex', gap: '16px' }}>
- <span>Risk: VaR $45K | Sharpe: 1.84 | Beta: 0.97</span>
- <span>Session: {currentTime.toTimeString().substring(0, 8)}</span>
- <span style={{ color: colors.secondary }}>SYSTEM: ACTIVE</span>
- </div>
- </div>
- </div>
- </div>
- );
-};
-
-export default AnalyticsTab;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/tabs/BacktestingTab.tsx b/fincept-terminal-desktop/src/components/tabs/BacktestingTab.tsx
index 9ef4f878b..9fa9221eb 100644
--- a/fincept-terminal-desktop/src/components/tabs/BacktestingTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/BacktestingTab.tsx
@@ -101,7 +101,11 @@ export default function BacktestingTab() {
// Initialize it
const config = JSON.parse(activeDbProvider.config);
- await registeredProvider.initialize({ settings: config });
+ await registeredProvider.initialize({
+ name: activeDbProvider.name,
+ adapterType: activeDbProvider.adapter_type,
+ settings: config
+ });
// Set as active
await backtestingRegistry.setActiveProvider(activeDbProvider.name);
diff --git a/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx b/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx
index e920481e6..a3ea2352a 100644
--- a/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx
@@ -12,9 +12,10 @@ import ContextSelector from '../common/ContextSelector';
interface ChatTabProps {
onNavigateToSettings?: () => void;
+ onNavigateToTab?: (tabName: string) => void;
}
-const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
+const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab }) => {
const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
const [currentTime, setCurrentTime] = useState(new Date());
const [currentSessionUuid, setCurrentSessionUuid] = useState<string | null>(null);
@@ -1136,10 +1137,28 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings }) => {
<div style={{
color: mcpToolsCount > 0 ? colors.secondary : colors.textMuted,
fontSize: '9px',
- marginBottom: '2px'
+ marginBottom: '6px'
}}>
MCP Tools: {mcpToolsCount > 0 ? `${mcpToolsCount} Available ✓` : 'None'}
</div>
+ <button
+ onClick={() => onNavigateToTab?.('mcp')}
+ style={{
+ width: '100%',
+ backgroundColor: colors.primary,
+ color: 'black',
+ border: 'none',
+ padding: '5px 8px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ marginBottom: '6px',
+ borderRadius: '2px'
+ }}
+ title="Configure MCP servers and tools"
+ >
+ 🔧 MCP INTEGRATION
+ </button>
{mcpToolsCount > 0 && !providerSupportsMCP() && (
<div style={{
color: colors.alert,
diff --git a/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx b/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx
index 7301bb964..eb7d96ee7 100644
--- a/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/EquityResearchTab.tsx
@@ -3,6 +3,7 @@ import { useTerminalTheme } from '@/contexts/ThemeContext';
import { invoke } from '@tauri-apps/api/core';
import { createChart, CandlestickSeries, HistogramSeries, LineSeries, BarSeries } from 'lightweight-charts';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, ComposedChart, Bar, Area } from 'recharts';
+import { ProChartWithToolkit } from './trading/charts/ProChartWithToolkit';
const COLORS = {
ORANGE: '#FFA500',
@@ -918,8 +919,9 @@ const EquityResearchTab: React.FC = () => {
}
};
- // Initialize price chart with volume
- useEffect(() => {
+ // OLD CHART INITIALIZATION - NOW USING ProChartWithToolkit
+ // ProChartWithToolkit handles all chart creation and management
+ /* useEffect(() => {
if (chartContainerRef.current && !chartRef.current) {
const containerHeight = chartContainerRef.current.clientHeight;
const containerWidth = chartContainerRef.current.clientWidth;
@@ -982,7 +984,6 @@ const EquityResearchTab: React.FC = () => {
}
};
- // Use ResizeObserver for better resize detection
const resizeObserver = new ResizeObserver(handleResize);
if (chartContainerRef.current) {
resizeObserver.observe(chartContainerRef.current);
@@ -998,10 +999,11 @@ const EquityResearchTab: React.FC = () => {
volumeSeriesRef.current = null;
};
}
- }, []);
+ }, []); */
- // Update price chart data
- useEffect(() => {
+ // OLD CHART DATA UPDATE - NOW HANDLED BY ProChartWithToolkit
+ // Data is passed directly to ProChartWithToolkit component via props
+ /* useEffect(() => {
if (candlestickSeriesRef.current && volumeSeriesRef.current && historicalData.length > 0) {
const chartData = historicalData.map((d) => ({
time: Math.floor(d.timestamp) as any,
@@ -1024,7 +1026,7 @@ const EquityResearchTab: React.FC = () => {
chartRef.current.timeScale().fitContent();
}
}
- }, [historicalData]);
+ }, [historicalData]); */
// Helper function to create a financial chart with dynamic metrics
const createFinancialChart = (
@@ -1618,27 +1620,46 @@ const EquityResearchTab: React.FC = () => {
))}
</div>
- {/* Chart with Volume */}
+ {/* Chart with Volume - NOW WITH FULL TRADING TOOLKIT! */}
<div style={{
backgroundColor: COLORS.PANEL_BG,
border: `1px solid ${COLORS.BORDER}`,
- padding: '6px',
overflow: 'hidden',
flex: 1,
display: 'flex',
flexDirection: 'column',
minHeight: 0,
}}>
- <div style={{ color: COLORS.ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '6px', flexShrink: 0 }}>
- PRICE CHART & VOLUME - {chartPeriod}
- </div>
- <div ref={chartContainerRef} style={{
- backgroundColor: COLORS.DARK_BG,
- flex: 1,
- width: '100%',
- overflow: 'hidden',
- minHeight: '280px',
- }} />
+ {historicalData && historicalData.length > 0 ? (
+ <ProChartWithToolkit
+ data={historicalData.map(h => ({
+ time: h.timestamp,
+ open: h.open,
+ high: h.high,
+ low: h.low,
+ close: h.close,
+ volume: h.volume,
+ }))}
+ symbol={`${currentSymbol} - ${chartPeriod}`}
+ height={400}
+ showVolume={true}
+ showToolbar={true}
+ onToolChange={(tool) => {
+ console.log('[EquityResearch] Active tool:', tool);
+ }}
+ />
+ ) : (
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ height: '100%',
+ color: COLORS.GRAY,
+ fontSize: '11px',
+ }}>
+ {loading ? 'Loading chart data...' : 'No chart data available'}
+ </div>
+ )}
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
index d313f7a41..dbf26e725 100644
--- a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
@@ -1,5 +1,5 @@
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 } from 'lucide-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 { ollamaService } from '@/services/ollamaService';
import { useTerminalTheme } from '@/contexts/ThemeContext';
@@ -12,7 +12,7 @@ import { LanguageSelector } from '@/components/settings/LanguageSelector';
export default function SettingsTab() {
const { theme, updateTheme, resetTheme, colors, fontSize: themeFontSize, fontFamily: themeFontFamily, fontWeight: themeFontWeight, fontStyle } = useTerminalTheme();
- const [activeSection, setActiveSection] = useState<'credentials' | 'profile' | 'terminal' | 'notifications' | 'llm' | 'dataConnections' | 'backtesting' | 'language'>('credentials');
+ const [activeSection, setActiveSection] = useState<'credentials' | 'terminal' | 'llm' | 'dataConnections' | 'backtesting' | 'language'>('credentials');
const [apiKeys, setApiKeys] = useState<ApiKeys>({});
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
@@ -48,6 +48,24 @@ export default function SettingsTab() {
const [fontItalic, setFontItalic] = useState(theme.font.italic);
const [selectedTheme, setSelectedTheme] = useState(terminalThemeService.getCurrentThemeKey());
+ // Key mapping configuration
+ const DEFAULT_KEY_MAPPINGS = {
+ F1: 'dashboard',
+ F2: 'markets',
+ F3: 'news',
+ F4: 'portfolio',
+ F5: 'analytics',
+ F6: 'watchlist',
+ F7: 'equity-research',
+ F8: 'screener',
+ F9: 'trading',
+ F10: 'chat',
+ F11: 'fullscreen',
+ F12: 'profile'
+ };
+
+ const [keyMappings, setKeyMappings] = useState<Record<string, string>>(DEFAULT_KEY_MAPPINGS);
+
// LLM Configuration States
const [llmConfigs, setLlmConfigs] = useState<LLMConfig[]>([]);
const [llmGlobalSettings, setLlmGlobalSettings] = useState<LLMGlobalSettings>({
@@ -428,7 +446,11 @@ export default function SettingsTab() {
colors: COLOR_THEMES[selectedTheme]
};
updateTheme(newTheme);
- showMessage('success', 'Terminal appearance saved successfully');
+
+ // Save key mappings to localStorage
+ localStorage.setItem('fincept_key_mappings', JSON.stringify(keyMappings));
+
+ showMessage('success', 'Terminal appearance and key mappings saved successfully');
};
const handleResetTerminalAppearance = () => {
@@ -439,9 +461,26 @@ export default function SettingsTab() {
setFontWeight(defaultTheme.font.weight);
setFontItalic(defaultTheme.font.italic);
setSelectedTheme('bloomberg-classic');
- showMessage('success', 'Reset to default appearance');
+
+ // Reset key mappings to defaults
+ setKeyMappings(DEFAULT_KEY_MAPPINGS);
+ localStorage.removeItem('fincept_key_mappings');
+
+ showMessage('success', 'Reset to default appearance and key mappings');
};
+ // Load saved key mappings on mount
+ useEffect(() => {
+ const savedMappings = localStorage.getItem('fincept_key_mappings');
+ if (savedMappings) {
+ try {
+ setKeyMappings(JSON.parse(savedMappings));
+ } catch (err) {
+ console.error('Failed to load key mappings:', err);
+ }
+ }
+ }, []);
+
return (
<div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: colors.background }}>
<style>{`
@@ -522,10 +561,8 @@ export default function SettingsTab() {
{ id: 'llm', icon: Bot, label: 'LLM Configuration' },
{ id: 'dataConnections', icon: Database, label: 'Data Sources' },
{ id: 'backtesting', icon: Activity, label: 'Backtesting Providers' },
- { id: 'profile', icon: User, label: 'User Profile' },
{ id: 'terminal', icon: Terminal, label: 'Terminal Config' },
- { id: 'language', icon: Globe, label: 'Language' },
- { id: 'notifications', icon: Bell, label: 'Notifications' }
+ { id: 'language', icon: Globe, label: 'Language' }
].map((item) => (
<div
key={item.id}
@@ -973,102 +1010,524 @@ export default function SettingsTab() {
{/* Terminal Appearance Section */}
{activeSection === 'terminal' && (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
+ <div style={{ fontFamily: '"IBM Plex Mono", "Consolas", monospace' }}>
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ marginBottom: '24px',
+ paddingBottom: '12px',
+ borderBottom: `2px solid ${colors.primary}`
+ }}>
+ <Terminal size={20} color={colors.primary} style={{ filter: `drop-shadow(0 0 4px ${colors.primary})` }} />
+ <h2 style={{
+ color: colors.primary,
+ fontSize: '16px',
+ fontWeight: 700,
+ letterSpacing: '1px',
+ margin: 0,
+ textShadow: `0 0 10px ${colors.primary}40`
+ }}>
+ TERMINAL CONFIGURATION
+ </h2>
+ </div>
+
+ {/* Description */}
+ <div style={{
+ marginBottom: '20px',
+ padding: '12px',
+ backgroundColor: '#1A1A1A',
+ border: '1px solid #2A2A2A',
+ borderLeft: `3px solid ${colors.secondary}`
+ }}>
+ <p style={{
+ color: colors.textMuted,
+ fontSize: '10px',
+ margin: 0,
+ lineHeight: '1.6'
+ }}>
+ Customize terminal appearance including fonts, colors, and themes. Changes apply across the entire application.
+ </p>
+ </div>
+
{/* Font Settings */}
- <div style={{ background: colors.panel, border: `1px solid ${colors.text}`, borderRadius: '4px', padding: '16px' }}>
+ <div style={{
+ background: '#0F0F0F',
+ border: '1px solid #2A2A2A',
+ borderLeft: `3px solid ${colors.primary}`,
+ borderRadius: '4px',
+ padding: '16px',
+ marginBottom: '20px'
+ }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>
- <Type size={18} color={colors.primary} />
- <span style={{ color: colors.text, fontSize: '14px', fontWeight: 'bold' }}>FONT SETTINGS</span>
+ <Type size={18} color={colors.primary} style={{ filter: `drop-shadow(0 0 2px ${colors.primary})` }} />
+ <span style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', letterSpacing: '0.5px' }}>FONT SETTINGS</span>
</div>
{/* Font Family */}
<div style={{ marginBottom: '16px' }}>
- <label style={{ color: colors.text, fontSize: '11px', display: 'block', marginBottom: '6px' }}>Font Family</label>
- <select value={fontFamily} onChange={(e) => setFontFamily(e.target.value)} style={{ width: '100%', padding: '8px', background: colors.background, border: '1px solid #444', color: colors.text, borderRadius: '3px' }}>
+ <label style={{ color: colors.text, fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600, letterSpacing: '0.5px' }}>FONT FAMILY</label>
+ <select value={fontFamily} onChange={(e) => setFontFamily(e.target.value)} style={{
+ width: '100%',
+ padding: '10px',
+ background: colors.background,
+ border: `1px solid #2A2A2A`,
+ color: colors.text,
+ borderRadius: '3px',
+ fontSize: '11px',
+ fontWeight: 500,
+ cursor: 'pointer',
+ appearance: 'none',
+ backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23FFA500' d='M6 9L1 4h10z'/%3E%3C/svg%3E")`,
+ backgroundRepeat: 'no-repeat',
+ backgroundPosition: 'right 10px center',
+ paddingRight: '32px'
+ }}>
{FONT_FAMILIES.map(f => <option key={f.value} value={f.value}>{f.label}</option>)}
</select>
</div>
{/* Base Font Size */}
<div style={{ marginBottom: '16px' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>
- <label style={{ color: colors.text, fontSize: '11px' }}>Base Font Size</label>
- <span style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold' }}>{baseSize}px</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
+ <label style={{ color: colors.text, fontSize: '10px', fontWeight: 600, letterSpacing: '0.5px' }}>BASE FONT SIZE</label>
+ <span style={{
+ color: colors.primary,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ padding: '2px 8px',
+ background: `${colors.primary}20`,
+ borderRadius: '3px',
+ border: `1px solid ${colors.primary}40`
+ }}>{baseSize}px</span>
</div>
- <input type="range" min="9" max="18" value={baseSize} onChange={(e) => setBaseSize(Number(e.target.value))} style={{ width: '100%' }} />
- <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '4px' }}>
- <span style={{ color: colors.text, fontSize: '9px' }}>Small (9px)</span>
- <span style={{ color: colors.text, fontSize: '9px' }}>Large (18px)</span>
+ <input type="range" min="9" max="18" value={baseSize} onChange={(e) => setBaseSize(Number(e.target.value))} style={{
+ width: '100%',
+ height: '6px',
+ background: `linear-gradient(to right, ${colors.primary}40 0%, ${colors.primary}40 ${((baseSize - 9) / 9) * 100}%, #2A2A2A ${((baseSize - 9) / 9) * 100}%, #2A2A2A 100%)`,
+ borderRadius: '3px',
+ outline: 'none',
+ cursor: 'pointer'
+ }} />
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '6px' }}>
+ <span style={{ color: colors.textMuted, fontSize: '9px', fontWeight: 500 }}>Small (9px)</span>
+ <span style={{ color: colors.textMuted, fontSize: '9px', fontWeight: 500 }}>Large (18px)</span>
</div>
</div>
{/* Font Weight */}
<div style={{ marginBottom: '16px' }}>
- <label style={{ color: colors.text, fontSize: '11px', display: 'block', marginBottom: '6px' }}>Font Weight</label>
- <select value={fontWeight} onChange={(e) => setFontWeight(e.target.value as FontSettings['weight'])} style={{ width: '100%', padding: '8px', background: colors.background, border: '1px solid #444', color: colors.text, borderRadius: '3px' }}>
- <option value="normal">Normal</option>
- <option value="semibold">Semi-Bold</option>
- <option value="bold">Bold</option>
+ <label style={{ color: colors.text, fontSize: '10px', display: 'block', marginBottom: '6px', fontWeight: 600, letterSpacing: '0.5px' }}>FONT WEIGHT</label>
+ <select value={fontWeight} onChange={(e) => setFontWeight(e.target.value as FontSettings['weight'])} style={{
+ width: '100%',
+ padding: '10px',
+ background: colors.background,
+ border: '1px solid #2A2A2A',
+ color: colors.text,
+ borderRadius: '3px',
+ fontSize: '11px',
+ fontWeight: 500,
+ cursor: 'pointer',
+ appearance: 'none',
+ backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23FFA500' d='M6 9L1 4h10z'/%3E%3C/svg%3E")`,
+ backgroundRepeat: 'no-repeat',
+ backgroundPosition: 'right 10px center',
+ paddingRight: '32px'
+ }}>
+ <option value="normal">Normal (400)</option>
+ <option value="semibold">Semi-Bold (600)</option>
+ <option value="bold">Bold (700)</option>
</select>
</div>
{/* Font Style */}
- <div style={{ marginBottom: '0' }}>
- <label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer' }}>
- <input type="checkbox" checked={fontItalic} onChange={(e) => setFontItalic(e.target.checked)} />
- <span style={{ color: colors.text, fontSize: '11px' }}>Enable Italic</span>
+ <div>
+ <label style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ cursor: 'pointer',
+ padding: '10px',
+ background: fontItalic ? `${colors.primary}10` : 'transparent',
+ border: `1px solid ${fontItalic ? colors.primary : '#2A2A2A'}`,
+ borderRadius: '3px',
+ transition: 'all 0.2s'
+ }}>
+ <input type="checkbox" checked={fontItalic} onChange={(e) => setFontItalic(e.target.checked)} style={{ width: '16px', height: '16px', cursor: 'pointer' }} />
+ <span style={{ color: colors.text, fontSize: '10px', fontWeight: 600, letterSpacing: '0.5px' }}>ENABLE ITALIC STYLE</span>
</label>
</div>
</div>
{/* Color Theme */}
- <div style={{ background: colors.panel, border: `1px solid ${colors.text}`, borderRadius: '4px', padding: '16px' }}>
+ <div style={{
+ background: '#0F0F0F',
+ border: '1px solid #2A2A2A',
+ borderLeft: `3px solid ${colors.primary}`,
+ borderRadius: '4px',
+ padding: '16px',
+ marginBottom: '20px'
+ }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>
- <Palette size={18} color={colors.primary} />
- <span style={{ color: colors.text, fontSize: '14px', fontWeight: 'bold' }}>COLOR THEME</span>
+ <Palette size={18} color={colors.primary} style={{ filter: `drop-shadow(0 0 2px ${colors.primary})` }} />
+ <span style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', letterSpacing: '0.5px' }}>COLOR THEME</span>
+ </div>
+
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '12px' }}>
+ {Object.entries(COLOR_THEMES).map(([key, themeObj]) => {
+ const isActive = selectedTheme === key;
+ return (
+ <button
+ key={key}
+ onClick={() => setSelectedTheme(key)}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ padding: '12px',
+ background: isActive ? '#1A1A1A' : 'transparent',
+ border: `1px solid ${isActive ? colors.primary : '#2A2A2A'}`,
+ borderLeft: `3px solid ${isActive ? colors.primary : '#2A2A2A'}`,
+ borderRadius: '3px',
+ cursor: 'pointer',
+ transition: 'all 0.2s',
+ position: 'relative',
+ overflow: 'hidden'
+ }}
+ onMouseEnter={(e) => {
+ if (!isActive) {
+ e.currentTarget.style.background = '#151515';
+ e.currentTarget.style.borderColor = '#3A3A3A';
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (!isActive) {
+ e.currentTarget.style.background = 'transparent';
+ e.currentTarget.style.borderColor = '#2A2A2A';
+ }
+ }}
+ >
+ {/* Color Swatches */}
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <div style={{
+ width: '24px',
+ height: '24px',
+ background: themeObj.primary,
+ border: '1px solid #2A2A2A',
+ borderRadius: '3px',
+ boxShadow: isActive ? `0 0 8px ${themeObj.primary}60` : 'none'
+ }} title="Primary" />
+ <div style={{
+ width: '24px',
+ height: '24px',
+ background: themeObj.secondary,
+ border: '1px solid #2A2A2A',
+ borderRadius: '3px',
+ boxShadow: isActive ? `0 0 8px ${themeObj.secondary}60` : 'none'
+ }} title="Secondary" />
+ <div style={{
+ width: '24px',
+ height: '24px',
+ background: themeObj.alert,
+ border: '1px solid #2A2A2A',
+ borderRadius: '3px',
+ boxShadow: isActive ? `0 0 8px ${themeObj.alert}60` : 'none'
+ }} title="Alert" />
+ </div>
+
+ <span style={{
+ color: isActive ? colors.primary : colors.text,
+ fontSize: '11px',
+ flex: 1,
+ fontWeight: isActive ? 700 : 500,
+ letterSpacing: '0.5px'
+ }}>{themeObj.name}</span>
+
+ {isActive && (
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}>
+ <Check size={14} color={colors.success} />
+ <div style={{
+ width: '6px',
+ height: '6px',
+ borderRadius: '50%',
+ background: colors.success,
+ boxShadow: `0 0 6px ${colors.success}`
+ }} />
+ </div>
+ )}
+
+ {isActive && (
+ <div style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ right: 0,
+ height: '1px',
+ background: `linear-gradient(90deg, transparent, ${colors.primary}, transparent)`,
+ opacity: 0.5
+ }} />
+ )}
+ </button>
+ );
+ })}
</div>
+ </div>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
- {Object.entries(COLOR_THEMES).map(([key, themeObj]) => (
- <label key={key} style={{ display: 'flex', alignItems: 'center', gap: '12px', padding: '10px', background: selectedTheme === key ? '#1a1a1a' : 'transparent', border: `1px solid ${selectedTheme === key ? colors.primary : colors.text}`, borderRadius: '4px', cursor: 'pointer' }}>
- <input type="radio" name="theme" value={key} checked={selectedTheme === key} onChange={() => setSelectedTheme(key)} />
- <div style={{ display: 'flex', gap: '6px' }}>
- <div style={{ width: '20px', height: '20px', background: themeObj.primary, border: '1px solid #444' }} title="Primary" />
- <div style={{ width: '20px', height: '20px', background: themeObj.secondary, border: '1px solid #444' }} title="Secondary" />
- <div style={{ width: '20px', height: '20px', background: themeObj.alert, border: '1px solid #444' }} title="Alert" />
+ {/* Key Mapping Configuration */}
+ <div style={{
+ background: '#0F0F0F',
+ border: '1px solid #2A2A2A',
+ borderLeft: `3px solid ${colors.primary}`,
+ borderRadius: '4px',
+ padding: '16px',
+ marginBottom: '20px'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px' }}>
+ <Terminal size={18} color={colors.primary} style={{ filter: `drop-shadow(0 0 2px ${colors.primary})` }} />
+ <span style={{ color: colors.primary, fontSize: '14px', fontWeight: 'bold', letterSpacing: '0.5px' }}>FUNCTION KEY MAPPINGS</span>
+ </div>
+
+ <div style={{
+ marginBottom: '12px',
+ padding: '10px',
+ backgroundColor: '#1A1A1A',
+ border: '1px solid #2A2A2A',
+ borderRadius: '3px'
+ }}>
+ <p style={{
+ color: colors.textMuted,
+ fontSize: '9px',
+ margin: 0,
+ lineHeight: '1.5'
+ }}>
+ Configure which tab or action each function key (F1-F12) should trigger. Changes will be reflected in the status bar and keyboard shortcuts.
+ </p>
+ </div>
+
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: '12px' }}>
+ {Object.entries(keyMappings).map(([key, action]) => (
+ <div key={key} style={{
+ background: '#1A1A1A',
+ border: '1px solid #2A2A2A',
+ borderRadius: '3px',
+ padding: '12px'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '8px' }}>
+ <span style={{
+ backgroundColor: colors.primary,
+ color: '#000',
+ padding: '4px 8px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ borderRadius: '2px',
+ minWidth: '40px',
+ textAlign: 'center'
+ }}>
+ {key}
+ </span>
+ <span style={{ color: colors.textMuted, fontSize: '10px' }}>→</span>
</div>
- <span style={{ color: colors.text, fontSize: '12px', flex: 1 }}>{themeObj.name}</span>
- {selectedTheme === key && <span style={{ color: colors.primary, fontSize: '10px', fontWeight: 'bold' }}>✓ ACTIVE</span>}
- </label>
+ <select
+ value={action}
+ onChange={(e) => setKeyMappings({ ...keyMappings, [key]: e.target.value })}
+ style={{
+ width: '100%',
+ padding: '8px',
+ background: colors.background,
+ border: '1px solid #2A2A2A',
+ color: colors.text,
+ borderRadius: '3px',
+ fontSize: '10px',
+ fontWeight: 500,
+ cursor: 'pointer',
+ appearance: 'none',
+ backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23FFA500' d='M6 9L1 4h10z'/%3E%3C/svg%3E")`,
+ backgroundRepeat: 'no-repeat',
+ backgroundPosition: 'right 8px center',
+ paddingRight: '28px'
+ }}
+ >
+ <option value="dashboard">Dashboard</option>
+ <option value="markets">Markets</option>
+ <option value="news">News</option>
+ <option value="portfolio">Portfolio</option>
+ <option value="analytics">Analytics</option>
+ <option value="watchlist">Watchlist</option>
+ <option value="equity-research">Equity Research</option>
+ <option value="screener">Screener</option>
+ <option value="trading">Trading</option>
+ <option value="chat">AI Chat</option>
+ <option value="fullscreen">Toggle Fullscreen</option>
+ <option value="profile">Profile</option>
+ <option value="settings">Settings</option>
+ <option value="forum">Forum</option>
+ <option value="marketplace">Marketplace</option>
+ </select>
+ </div>
))}
</div>
</div>
- {/* Preview Panel */}
- <div style={{ background: theme.colors.background, border: `2px solid ${theme.colors.primary}`, borderRadius: '4px', padding: '16px' }}>
- <div style={{ color: theme.colors.primary, fontSize: `${baseSize + 2}px`, fontFamily: `${fontFamily}, monospace`, fontWeight: fontWeight === 'normal' ? '400' : fontWeight === 'semibold' ? '600' : '700', fontStyle: fontItalic ? 'italic' : 'normal', marginBottom: '12px' }}>
+ {/* Live Preview Panel */}
+ <div style={{
+ background: theme.colors.background,
+ border: `2px solid ${theme.colors.primary}`,
+ borderRadius: '4px',
+ padding: '20px',
+ marginBottom: '20px',
+ position: 'relative',
+ overflow: 'hidden'
+ }}>
+ <div style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ right: 0,
+ height: '2px',
+ background: `linear-gradient(90deg, transparent, ${theme.colors.primary}, transparent)`,
+ opacity: 0.5
+ }} />
+
+ <div style={{
+ color: theme.colors.textMuted,
+ fontSize: '9px',
+ fontWeight: 600,
+ letterSpacing: '1px',
+ marginBottom: '12px',
+ opacity: 0.7
+ }}>
+ LIVE PREVIEW
+ </div>
+
+ <div style={{
+ color: theme.colors.primary,
+ fontSize: `${baseSize + 2}px`,
+ fontFamily: `${fontFamily}, monospace`,
+ fontWeight: fontWeight === 'normal' ? '400' : fontWeight === 'semibold' ? '600' : '700',
+ fontStyle: fontItalic ? 'italic' : 'normal',
+ marginBottom: '12px',
+ letterSpacing: '0.5px'
+ }}>
FINCEPT TERMINAL PREVIEW
</div>
- <div style={{ color: theme.colors.text, fontSize: `${baseSize}px`, fontFamily: `${fontFamily}, monospace`, fontWeight: fontWeight === 'normal' ? '400' : fontWeight === 'semibold' ? '600' : '700', fontStyle: fontItalic ? 'italic' : 'normal', marginBottom: '8px' }}>
- Body Text: Lorem ipsum dolor sit amet
+
+ <div style={{
+ color: theme.colors.text,
+ fontSize: `${baseSize}px`,
+ fontFamily: `${fontFamily}, monospace`,
+ fontWeight: fontWeight === 'normal' ? '400' : fontWeight === 'semibold' ? '600' : '700',
+ fontStyle: fontItalic ? 'italic' : 'normal',
+ marginBottom: '8px',
+ lineHeight: '1.5'
+ }}>
+ Body Text: Real-time market analysis and portfolio tracking
</div>
- <div style={{ color: theme.colors.text, fontSize: `${baseSize - 1}px`, fontFamily: `${fontFamily}, monospace`, fontWeight: fontWeight === 'normal' ? '400' : fontWeight === 'semibold' ? '600' : '700', fontStyle: fontItalic ? 'italic' : 'normal', marginBottom: '8px' }}>
- Small Text: Market data and timestamps
+
+ <div style={{
+ color: theme.colors.textMuted,
+ fontSize: `${baseSize - 1}px`,
+ fontFamily: `${fontFamily}, monospace`,
+ fontWeight: fontWeight === 'normal' ? '400' : fontWeight === 'semibold' ? '600' : '700',
+ fontStyle: fontItalic ? 'italic' : 'normal',
+ marginBottom: '12px',
+ lineHeight: '1.5'
+ }}>
+ Small Text: Market data, timestamps, and metadata
</div>
- <div style={{ display: 'flex', gap: '12px', marginTop: '12px' }}>
- <span style={{ color: theme.colors.secondary }}>● LIVE</span>
- <span style={{ color: theme.colors.alert }}>● ALERT</span>
- <span style={{ color: theme.colors.warning }}>● WARNING</span>
+
+ <div style={{ display: 'flex', gap: '16px', marginTop: '12px', flexWrap: 'wrap' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <div style={{
+ width: '8px',
+ height: '8px',
+ borderRadius: '50%',
+ background: theme.colors.success,
+ boxShadow: `0 0 8px ${theme.colors.success}`
+ }} />
+ <span style={{ color: theme.colors.success, fontSize: '10px', fontWeight: 600 }}>CONNECTED</span>
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <div style={{
+ width: '8px',
+ height: '8px',
+ borderRadius: '50%',
+ background: theme.colors.alert,
+ boxShadow: `0 0 8px ${theme.colors.alert}`
+ }} />
+ <span style={{ color: theme.colors.alert, fontSize: '10px', fontWeight: 600 }}>ALERT</span>
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <div style={{
+ width: '8px',
+ height: '8px',
+ borderRadius: '50%',
+ background: theme.colors.warning,
+ boxShadow: `0 0 8px ${theme.colors.warning}`
+ }} />
+ <span style={{ color: theme.colors.warning, fontSize: '10px', fontWeight: 600 }}>WARNING</span>
+ </div>
</div>
</div>
{/* Action Buttons */}
<div style={{ display: 'flex', gap: '12px' }}>
- <button onClick={handleSaveTerminalAppearance} style={{ flex: 1, background: colors.primary, color: colors.background, border: 'none', padding: '12px', fontSize: '12px', fontWeight: 'bold', borderRadius: '4px', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px' }}>
- <Save size={14} /> SAVE APPEARANCE
+ <button onClick={handleSaveTerminalAppearance} style={{
+ flex: 1,
+ background: colors.primary,
+ color: '#000000',
+ border: 'none',
+ padding: '14px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ letterSpacing: '0.5px',
+ borderRadius: '4px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px',
+ transition: 'all 0.2s',
+ boxShadow: `0 0 12px ${colors.primary}40`
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.boxShadow = `0 0 20px ${colors.primary}60`;
+ e.currentTarget.style.transform = 'translateY(-1px)';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.boxShadow = `0 0 12px ${colors.primary}40`;
+ e.currentTarget.style.transform = 'translateY(0)';
+ }}>
+ <Save size={16} /> SAVE CONFIGURATION
</button>
- <button onClick={handleResetTerminalAppearance} style={{ background: colors.text, color: colors.text, border: 'none', padding: '12px 16px', fontSize: '12px', fontWeight: 'bold', borderRadius: '4px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '6px' }}>
- <RefreshCw size={14} /> RESET
+ <button onClick={handleResetTerminalAppearance} style={{
+ background: 'transparent',
+ color: colors.textMuted,
+ border: `1px solid #2A2A2A`,
+ padding: '14px 20px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ letterSpacing: '0.5px',
+ borderRadius: '4px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = colors.alert;
+ e.currentTarget.style.color = colors.alert;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = '#2A2A2A';
+ e.currentTarget.style.color = colors.textMuted;
+ }}>
+ <RefreshCw size={16} /> RESET
</button>
</div>
</div>
@@ -1100,9 +1559,7 @@ export default function SettingsTab() {
</div>
)}
- {/* Other sections */}
- {activeSection === 'profile' && <div style={{ color: colors.text }}>User Profile section (implementation same as before)</div>}
- {activeSection === 'notifications' && <div style={{ color: colors.text }}>Notifications section (implementation same as before)</div>}
+ {/* Other sections can be added here */}
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
index 866515f3f..c43302db2 100644
--- a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
@@ -19,6 +19,9 @@ 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 {
@@ -104,7 +107,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'>('orderbook');
+ const [rightPanelView, setRightPanelView] = useState<'orderbook' | 'volume' | 'modelchat'>('orderbook');
+ const [leftSidebarView, setLeftSidebarView] = useState<'watchlist' | 'ai-agents' | 'leaderboard'>('watchlist');
// Paper trading state
const [positions, setPositions] = useState<Position[]>([]);
@@ -123,7 +127,18 @@ export function TradingTab() {
const [showSettings, setShowSettings] = useState(false);
// Watchlist
- const [watchlist, setWatchlist] = useState<string[]>(['BTC/USD', 'ETH/USD', 'SOL/USD']);
+ // Top 30 most traded crypto pairs
+ const [watchlist, setWatchlist] = useState<string[]>([
+ 'BTC/USD', 'ETH/USD', 'BNB/USD', 'SOL/USD', 'XRP/USD',
+ 'ADA/USD', 'DOGE/USD', 'AVAX/USD', 'DOT/USD', 'MATIC/USD',
+ 'LTC/USD', 'SHIB/USD', 'TRX/USD', 'LINK/USD', 'UNI/USD',
+ 'ATOM/USD', 'XLM/USD', 'ETC/USD', 'BCH/USD', 'NEAR/USD',
+ 'APT/USD', 'ARB/USD', 'OP/USD', 'LDO/USD', 'FIL/USD',
+ 'ICP/USD', 'INJ/USD', 'STX/USD', 'MKR/USD', 'AAVE/USD'
+ ]);
+
+ // Watchlist prices
+ const [watchlistPrices, setWatchlistPrices] = useState<Record<string, { price: number; change: number }>>({});
// Update time
useEffect(() => {
@@ -133,6 +148,93 @@ export function TradingTab() {
return () => clearInterval(timer);
}, []);
+ // Fetch watchlist prices - Using bulk API fetch (updated every 15 minutes)
+ useEffect(() => {
+ const fetchWatchlistPrices = async () => {
+ try {
+ // Approach 1: Try using exchange's bulk fetchTickers if available
+ if (activeAdapter && typeof activeAdapter.fetchTickers === 'function') {
+ try {
+ const tickers = await activeAdapter.fetchTickers(watchlist);
+ const prices: Record<string, { price: number; change: number }> = {};
+
+ let hasValidData = false;
+ watchlist.forEach(symbol => {
+ const ticker = tickers[symbol];
+ if (ticker && ticker.last && ticker.last > 0) {
+ prices[symbol] = {
+ price: ticker.last,
+ change: ticker.percentage || 0
+ };
+ hasValidData = true;
+ }
+ });
+
+ // Only update if we got valid data
+ if (hasValidData) {
+ setWatchlistPrices(prices);
+ console.log('[Watchlist] Successfully fetched prices from adapter');
+ return;
+ }
+ } catch (err) {
+ console.warn('[Watchlist] fetchTickers failed, trying fallback API:', err);
+ }
+ }
+
+ // Approach 2: Fallback to public Binance API for crypto prices
+ const symbols = watchlist.map(s => s.replace('/USD', 'USDT').replace('/', ''));
+ const response = await fetch('https://api.binance.com/api/v3/ticker/24hr');
+
+ if (!response.ok) {
+ throw new Error(`Binance API returned ${response.status}`);
+ }
+
+ const allTickers = await response.json();
+
+ if (!Array.isArray(allTickers)) {
+ throw new Error('Invalid response from Binance API');
+ }
+
+ const prices: Record<string, { price: number; change: number }> = {};
+ let hasValidData = false;
+
+ watchlist.forEach((symbol, idx) => {
+ const binanceSymbol = symbols[idx];
+ const ticker = allTickers.find((t: any) => t.symbol === binanceSymbol);
+
+ if (ticker && ticker.lastPrice) {
+ const price = parseFloat(ticker.lastPrice);
+ const change = parseFloat(ticker.priceChangePercent);
+
+ if (price > 0) {
+ prices[symbol] = { price, change };
+ hasValidData = true;
+ }
+ }
+ });
+
+ // Only update if we got valid data
+ if (hasValidData) {
+ setWatchlistPrices(prices);
+ console.log('[Watchlist] Successfully fetched prices from Binance');
+ } else {
+ console.warn('[Watchlist] No valid data received, keeping existing prices');
+ }
+ } catch (error) {
+ console.error('[Watchlist] Failed to fetch prices:', error);
+ // DON'T clear existing data on error - keep what we have
+ console.warn('[Watchlist] Keeping existing prices due to fetch error');
+ }
+ };
+
+ // Initial fetch
+ fetchWatchlistPrices();
+
+ // Update every 15 minutes (900000ms)
+ const interval = setInterval(fetchWatchlistPrices, 900000);
+ return () => clearInterval(interval);
+ }, [activeAdapter, watchlist]);
+
// Clear data when symbol changes
useEffect(() => {
setTickerData(null);
@@ -858,56 +960,199 @@ export function TradingTab() {
{/* ========== MAIN CONTENT ========== */}
<div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
- {/* LEFT SIDEBAR - Watchlist */}
+ {/* LEFT SIDEBAR - Watchlist / AI Agents Toggle */}
<div style={{
- width: '220px',
+ width: '320px',
backgroundColor: BLOOMBERG.PANEL_BG,
borderRight: `1px solid ${BLOOMBERG.BORDER}`,
display: 'flex',
flexDirection: 'column',
overflow: 'hidden'
}}>
+ {/* Toggle Header */}
<div style={{
- padding: '8px 12px',
+ padding: '6px',
backgroundColor: BLOOMBERG.HEADER_BG,
borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
- fontSize: '10px',
- fontWeight: 700,
- color: BLOOMBERG.ORANGE,
- letterSpacing: '0.5px'
+ display: 'flex',
+ gap: '4px'
}}>
- WATCHLIST
+ <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>
</div>
- <div style={{ flex: 1, overflow: 'auto' }}>
- {watchlist.map((symbol, idx) => (
- <div
- key={symbol}
- onClick={() => setSelectedSymbol(symbol)}
- style={{
- padding: '10px 12px',
- cursor: 'pointer',
- backgroundColor: selectedSymbol === symbol ? `${BLOOMBERG.ORANGE}15` : 'transparent',
- borderLeft: selectedSymbol === symbol ? `3px solid ${BLOOMBERG.ORANGE}` : '3px solid transparent',
- borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
- 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';
- }
- }}
- >
- <div style={{ fontSize: '11px', fontWeight: 600, color: selectedSymbol === symbol ? BLOOMBERG.ORANGE : BLOOMBERG.WHITE, marginBottom: '4px' }}>
- {symbol}
- </div>
- <div style={{ fontSize: '10px', color: BLOOMBERG.GREEN }}>+2.45%</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={{
+ 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',
+ 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>
+ )}
</div>
</div>
@@ -915,12 +1160,13 @@ export function TradingTab() {
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
{/* Chart Area */}
<div style={{
- height: '55%',
+ flex: isBottomPanelMinimized ? 1 : '0 0 55%',
backgroundColor: BLOOMBERG.PANEL_BG,
borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
display: 'flex',
flexDirection: 'column',
- overflow: 'hidden'
+ overflow: 'hidden',
+ transition: 'flex 0.3s ease'
}}>
<div style={{
padding: '8px 12px',
@@ -952,20 +1198,26 @@ export function TradingTab() {
<div style={{
flex: 1,
display: 'flex',
- alignItems: 'center',
+ alignItems: 'stretch',
justifyContent: 'center',
color: BLOOMBERG.GRAY,
fontSize: '12px',
- overflow: 'hidden'
+ overflow: 'visible',
+ minHeight: 0
}}>
{selectedView === 'chart' && (
- <div style={{ width: '100%', height: '100%' }}>
- <TradingChart symbol={selectedSymbol} height={isBottomPanelMinimized ? 650 : 450} showVolume={true} />
+ <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
+ <TradingChart
+ symbol={selectedSymbol}
+ showVolume={true}
+ />
</div>
)}
{selectedView === 'depth' && (
<div style={{ width: '100%', height: '100%', padding: '8px' }}>
- <DepthChart symbol={selectedSymbol} height={420} />
+ <DepthChart
+ symbol={selectedSymbol}
+ />
</div>
)}
{selectedView === 'trades' && (
@@ -1151,14 +1403,27 @@ export function TradingTab() {
{/* Stats Tab */}
{activeBottomTab === 'stats' && (
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: '12px' }}>
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 300px',
+ gap: '12px',
+ padding: '12px',
+ height: '100%',
+ overflow: 'hidden'
+ }}>
{/* Left: Account Statistics */}
- <div>
+ <div style={{ height: '100%', overflow: 'auto' }}>
<AccountStats />
</div>
{/* Right: Fees & Margin */}
- <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '12px',
+ height: '100%',
+ overflow: 'auto'
+ }}>
<FeesDisplay />
<MarginPanel />
</div>
@@ -1232,7 +1497,7 @@ export function TradingTab() {
{/* RIGHT SIDEBAR - Order Entry & Order Book */}
<div style={{
- width: '360px',
+ width: '300px',
backgroundColor: BLOOMBERG.PANEL_BG,
borderLeft: `1px solid ${BLOOMBERG.BORDER}`,
display: 'flex',
@@ -1320,7 +1585,7 @@ export function TradingTab() {
alignItems: 'center'
}}>
<div style={{ display: 'flex', gap: '8px' }}>
- {['orderbook', 'volume'].map((view) => (
+ {['orderbook', 'volume', 'modelchat'].map((view) => (
<button
key={view}
onClick={() => setRightPanelView(view as any)}
@@ -1448,6 +1713,10 @@ 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/mcp/index.tsx b/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx
index afc093319..ec19d77d9 100644
--- a/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/mcp/index.tsx
@@ -2,13 +2,17 @@
// Manage MCP servers and tools in Bloomberg-style interface
import React, { useState, useEffect } from 'react';
-import { Plus, RefreshCw, Search, Play, Square, Trash2, Settings, Zap, CheckCircle, XCircle, AlertCircle } from 'lucide-react';
+import { Plus, RefreshCw, Search, Play, Square, Trash2, Settings, Zap, CheckCircle, XCircle, AlertCircle, MessageSquare } from 'lucide-react';
import { mcpManager, MCPServerWithStats } from '../../../services/mcpManager';
import { sqliteService } from '../../../services/sqliteService';
import MCPMarketplace from './marketplace/MCPMarketplace';
import MCPAddServerModal from './MCPAddServerModal';
-const MCPTab: React.FC = () => {
+interface MCPTabProps {
+ onNavigateToTab?: (tabName: string) => void;
+}
+
+const MCPTab: React.FC<MCPTabProps> = ({ onNavigateToTab }) => {
const [view, setView] = useState<'marketplace' | 'installed'>('marketplace');
const [servers, setServers] = useState<MCPServerWithStats[]>([]);
const [tools, setTools] = useState<any[]>([]);
@@ -203,6 +207,27 @@ const MCPTab: React.FC = () => {
{/* View Switcher */}
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
+ <button
+ onClick={() => onNavigateToTab?.('chat')}
+ style={{
+ backgroundColor: 'transparent',
+ border: `1px solid ${ORANGE}`,
+ color: ORANGE,
+ padding: '6px 12px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ fontWeight: 'bold'
+ }}
+ title="Go back to AI Chat"
+ >
+ <MessageSquare size={12} />
+ AI CHAT
+ </button>
+
<button
onClick={handleRefresh}
disabled={isRefreshing}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/AIAgentsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/AIAgentsPanel.tsx
new file mode 100644
index 000000000..0969a5637
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/AIAgentsPanel.tsx
@@ -0,0 +1,1208 @@
+/**
+ * AI Agents Panel
+ *
+ * Main panel for Agno AI Trading Agents in the Trading tab.
+ * Provides interface for creating, configuring, and interacting with AI agents.
+ */
+
+import React, { useState, useEffect } from 'react';
+import {
+ Bot, Brain, TrendingUp, Shield, PieChart, MessageSquare,
+ Settings, Play, Loader2, AlertCircle, CheckCircle, Sparkles,
+ ChevronDown, ChevronUp, Zap, Target, Pause, Square, Activity,
+ TrendingDown
+} from 'lucide-react';
+import agnoTradingService, {
+ type AgentConfig,
+ type AgentInfo,
+ type MarketAnalysis,
+ type TradeSignal,
+ type RiskAnalysis
+} from '../../../../services/agnoTradingService';
+import { AgentConfigurationUI } from './AgentConfigurationUI';
+import { CompetitionPanel } from './CompetitionPanel';
+
+// Bloomberg color palette
+const BLOOMBERG = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ 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'
+};
+
+interface AIAgentsPanelProps {
+ selectedSymbol: string;
+ portfolioData?: {
+ positions: any[];
+ total_value: number;
+ };
+}
+
+export function AIAgentsPanel({ selectedSymbol, portfolioData }: AIAgentsPanelProps) {
+ const [activeView, setActiveView] = useState<'quick-actions' | 'create-agent' | 'manage-agents' | 'competition'>('quick-actions');
+ const [isLoading, setIsLoading] = useState(false);
+ const [result, setResult] = useState<any>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ // Quick Actions State
+ const [selectedModel, setSelectedModel] = useState('openai:gpt-4o-mini');
+ const [analysisType, setAnalysisType] = useState<'quick' | 'comprehensive' | 'deep'>('comprehensive');
+ const [strategy, setStrategy] = useState<'momentum' | 'breakout' | 'reversal' | 'trend_following'>('momentum');
+ const [hasConfiguredKeys, setHasConfiguredKeys] = useState(false);
+ const [availableModels, setAvailableModels] = useState<Array<{ value: string; label: string }>>([]);
+
+ // Agents State
+ const [agents, setAgents] = useState<AgentInfo[]>([]);
+ const [selectedAgent, setSelectedAgent] = useState<string | null>(null);
+
+ // ============================================================================
+ // Check for configured API keys on mount
+ // ============================================================================
+ useEffect(() => {
+ const checkAPIKeys = async () => {
+ try {
+ const { sqliteService } = await import('../../../../services/sqliteService');
+ const configs = await sqliteService.getLLMConfigs();
+
+ const configured = configs.filter(c => c.api_key && c.api_key.trim().length > 0);
+ setHasConfiguredKeys(configured.length > 0);
+
+ if (configured.length > 0) {
+ // Build available models list from configured providers
+ const models = configured.map(c => ({
+ value: `${c.provider}:${c.model}`,
+ label: `${c.provider.charAt(0).toUpperCase() + c.provider.slice(1)} - ${c.model}`
+ }));
+ setAvailableModels(models);
+
+ // Auto-select first configured model
+ setSelectedModel(models[0].value);
+ }
+ } catch (err) {
+ console.error('Failed to check API keys:', err);
+ }
+ };
+
+ checkAPIKeys();
+ }, []);
+
+ // ============================================================================
+ // Quick Actions
+ // ============================================================================
+
+ const handleAnalyzeMarket = async () => {
+ setIsLoading(true);
+ setError(null);
+ setResult(null);
+
+ try {
+ const response = await agnoTradingService.analyzeMarket(
+ selectedSymbol,
+ selectedModel,
+ analysisType
+ );
+
+ if (response.success && response.data) {
+ setResult({
+ type: 'market_analysis',
+ data: response.data
+ });
+ } else {
+ setError(response.error || 'Analysis failed');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error');
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleGenerateSignal = async () => {
+ setIsLoading(true);
+ setError(null);
+ setResult(null);
+
+ try {
+ const response = await agnoTradingService.generateTradeSignal(
+ selectedSymbol,
+ strategy,
+ selectedModel
+ );
+
+ if (response.success && response.data) {
+ setResult({
+ type: 'trade_signal',
+ data: response.data
+ });
+ } else {
+ setError(response.error || 'Signal generation failed');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error');
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleAssessRisk = async () => {
+ if (!portfolioData) {
+ setError('Portfolio data not available');
+ return;
+ }
+
+ setIsLoading(true);
+ setError(null);
+ setResult(null);
+
+ try {
+ const response = await agnoTradingService.manageRisk(
+ portfolioData,
+ selectedModel,
+ 'moderate'
+ );
+
+ if (response.success && response.data) {
+ setResult({
+ type: 'risk_analysis',
+ data: response.data
+ });
+ } else {
+ setError(response.error || 'Risk analysis failed');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error');
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleStartCompetition = async () => {
+ if (availableModels.length < 2) {
+ setError('Need at least 2 configured models to start a competition');
+ return;
+ }
+
+ setIsLoading(true);
+ setError(null);
+ setResult(null);
+
+ try {
+ // Create competition with all available models
+ const modelStrings = availableModels.map(m => m.value);
+ const createResponse = await agnoTradingService.createCompetition(
+ `${selectedSymbol}_${Date.now()}`,
+ modelStrings,
+ 'trading'
+ );
+
+ if (!createResponse.success || !createResponse.data) {
+ throw new Error(createResponse.error || 'Failed to create competition');
+ }
+
+ const teamId = createResponse.data.team_id;
+
+ // Run competition
+ const runResponse = await agnoTradingService.runCompetition(
+ teamId,
+ selectedSymbol,
+ 'analyze'
+ );
+
+ if (runResponse.success && runResponse.data) {
+ setResult({
+ type: 'competition',
+ data: runResponse.data
+ });
+ } else {
+ setError(runResponse.error || 'Competition failed');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error');
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ // ============================================================================
+ // Render
+ // ============================================================================
+
+ return (
+ <div
+ style={{
+ background: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ height: '100%',
+ display: 'flex',
+ flexDirection: 'column'
+ }}
+ >
+ {/* Header */}
+ <div
+ style={{
+ background: BLOOMBERG.HEADER_BG,
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '6px 8px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between'
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <Sparkles size={14} color={BLOOMBERG.ORANGE} />
+ <h3 style={{
+ color: BLOOMBERG.WHITE,
+ fontSize: '11px',
+ fontWeight: '600',
+ margin: 0,
+ letterSpacing: '0.5px'
+ }}>
+ AI AGENTS
+ </h3>
+ </div>
+
+ <div style={{ display: 'flex', gap: '3px' }}>
+ <button
+ onClick={() => setActiveView('quick-actions')}
+ style={{
+ background: activeView === 'quick-actions' ? BLOOMBERG.ORANGE : 'transparent',
+ color: activeView === 'quick-actions' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,
+ border: `1px solid ${activeView === 'quick-actions' ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,
+ padding: '4px 8px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'all 0.15s',
+ letterSpacing: '0.3px'
+ }}
+ >
+ QUICK
+ </button>
+
+ <button
+ onClick={() => setActiveView('create-agent')}
+ style={{
+ background: activeView === 'create-agent' ? BLOOMBERG.ORANGE : 'transparent',
+ color: activeView === 'create-agent' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,
+ border: `1px solid ${activeView === 'create-agent' ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,
+ padding: '4px 8px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'all 0.15s',
+ letterSpacing: '0.3px'
+ }}
+ >
+ CREATE
+ </button>
+
+ <button
+ onClick={() => setActiveView('manage-agents')}
+ style={{
+ background: activeView === 'manage-agents' ? BLOOMBERG.ORANGE : 'transparent',
+ color: activeView === 'manage-agents' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,
+ border: `1px solid ${activeView === 'manage-agents' ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,
+ padding: '4px 8px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'all 0.15s',
+ letterSpacing: '0.3px'
+ }}
+ >
+ MANAGE
+ </button>
+
+ <button
+ onClick={() => setActiveView('competition')}
+ style={{
+ background: activeView === 'competition' ? BLOOMBERG.ORANGE : 'transparent',
+ color: activeView === 'competition' ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,
+ border: `1px solid ${activeView === 'competition' ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,
+ padding: '4px 8px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: '600',
+ cursor: 'pointer',
+ transition: 'all 0.15s',
+ letterSpacing: '0.3px'
+ }}
+ >
+ COMPETE
+ </button>
+ </div>
+ </div>
+
+ {/* Content */}
+ <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
+ {activeView === 'quick-actions' && (
+ <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>
+ <QuickActionsView
+ selectedSymbol={selectedSymbol}
+ selectedModel={selectedModel}
+ setSelectedModel={setSelectedModel}
+ analysisType={analysisType}
+ setAnalysisType={setAnalysisType}
+ strategy={strategy}
+ setStrategy={setStrategy}
+ isLoading={isLoading}
+ result={result}
+ error={error}
+ hasConfiguredKeys={hasConfiguredKeys}
+ availableModels={availableModels}
+ onAnalyzeMarket={handleAnalyzeMarket}
+ onGenerateSignal={handleGenerateSignal}
+ onAssessRisk={handleAssessRisk}
+ onStartCompetition={handleStartCompetition}
+ />
+ </div>
+ )}
+
+ {activeView === 'create-agent' && (
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ <CreateAgentView
+ selectedSymbol={selectedSymbol}
+ onAgentCreated={(agent) => {
+ setAgents([...agents, agent]);
+ setActiveView('manage-agents');
+ }}
+ />
+ </div>
+ )}
+
+ {activeView === 'manage-agents' && (
+ <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>
+ <ManageAgentsView agents={agents} />
+ </div>
+ )}
+
+ {activeView === 'competition' && (
+ <div style={{ flex: 1, overflow: 'hidden' }}>
+ <CompetitionPanel selectedSymbol={selectedSymbol} />
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// ============================================================================
+// Quick Actions View
+// ============================================================================
+
+interface QuickActionsViewProps {
+ selectedSymbol: string;
+ selectedModel: string;
+ setSelectedModel: (model: string) => void;
+ analysisType: 'quick' | 'comprehensive' | 'deep';
+ setAnalysisType: (type: 'quick' | 'comprehensive' | 'deep') => void;
+ strategy: 'momentum' | 'breakout' | 'reversal' | 'trend_following';
+ setStrategy: (strategy: 'momentum' | 'breakout' | 'reversal' | 'trend_following') => void;
+ isLoading: boolean;
+ result: any;
+ error: string | null;
+ hasConfiguredKeys: boolean;
+ availableModels: Array<{ value: string; label: string }>;
+ onAnalyzeMarket: () => void;
+ onGenerateSignal: () => void;
+ onAssessRisk: () => void;
+ onStartCompetition: () => void;
+}
+
+function QuickActionsView({
+ selectedSymbol,
+ selectedModel,
+ setSelectedModel,
+ analysisType,
+ setAnalysisType,
+ strategy,
+ setStrategy,
+ isLoading,
+ result,
+ error,
+ hasConfiguredKeys,
+ availableModels,
+ onAnalyzeMarket,
+ onGenerateSignal,
+ onAssessRisk,
+ onStartCompetition
+}: QuickActionsViewProps) {
+ const models = availableModels.length > 0 ? availableModels : [
+ { value: 'openai:gpt-4o-mini', label: 'GPT-4o Mini (Configure in Settings)' },
+ { value: 'anthropic:claude-sonnet-4', label: 'Claude Sonnet 4 (Configure in Settings)' },
+ { value: 'google:gemini-2.0-flash-exp', label: 'Gemini 2.0 Flash (Configure in Settings)' },
+ ];
+
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ {/* Model Selection */}
+ <div>
+ <label style={{
+ color: BLOOMBERG.GRAY,
+ fontSize: '9px',
+ fontWeight: '600',
+ display: 'block',
+ marginBottom: '4px',
+ letterSpacing: '0.5px'
+ }}>
+ MODEL
+ </label>
+ <select
+ value={selectedModel}
+ onChange={(e) => setSelectedModel(e.target.value)}
+ disabled={!hasConfiguredKeys}
+ style={{
+ width: '100%',
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${hasConfiguredKeys ? BLOOMBERG.BORDER : BLOOMBERG.RED}`,
+ color: hasConfiguredKeys ? BLOOMBERG.WHITE : BLOOMBERG.GRAY,
+ padding: '5px 8px',
+ borderRadius: '2px',
+ fontSize: '10px',
+ cursor: hasConfiguredKeys ? 'pointer' : 'not-allowed',
+ fontFamily: '"IBM Plex Mono", monospace',
+ opacity: hasConfiguredKeys ? 1 : 0.6
+ }}
+ >
+ {models.map(m => (
+ <option key={m.value} value={m.value}>{m.label}</option>
+ ))}
+ </select>
+ {!hasConfiguredKeys && (
+ <div style={{ fontSize: '8px', color: BLOOMBERG.RED, marginTop: '3px' }}>
+ Configure API keys in Settings → LLM Config
+ </div>
+ )}
+ </div>
+
+ {/* Quick Action Buttons */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px' }}>
+ {/* Analyze Market */}
+ <div>
+ <button
+ onClick={onAnalyzeMarket}
+ disabled={isLoading || !hasConfiguredKeys}
+ style={{
+ width: '100%',
+ background: hasConfiguredKeys ? BLOOMBERG.BLUE : BLOOMBERG.GRAY,
+ border: `1px solid ${hasConfiguredKeys ? BLOOMBERG.BLUE : BLOOMBERG.GRAY}`,
+ color: BLOOMBERG.WHITE,
+ padding: '6px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: '600',
+ cursor: (isLoading || !hasConfiguredKeys) ? 'not-allowed' : 'pointer',
+ opacity: (isLoading || !hasConfiguredKeys) ? 0.5 : 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ letterSpacing: '0.3px'
+ }}
+ >
+ {isLoading ? <Loader2 size={12} className="animate-spin" /> : <Brain size={12} />}
+ ANALYZE
+ </button>
+ <select
+ value={analysisType}
+ onChange={(e) => setAnalysisType(e.target.value as any)}
+ style={{
+ width: '100%',
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ color: BLOOMBERG.GRAY,
+ padding: '4px 6px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ marginTop: '3px',
+ cursor: 'pointer'
+ }}
+ >
+ <option value="quick">Quick</option>
+ <option value="comprehensive">Comprehensive</option>
+ <option value="deep">Deep</option>
+ </select>
+ </div>
+
+ {/* Generate Signal */}
+ <div>
+ <button
+ onClick={onGenerateSignal}
+ disabled={isLoading || !hasConfiguredKeys}
+ style={{
+ width: '100%',
+ background: hasConfiguredKeys ? BLOOMBERG.GREEN : BLOOMBERG.GRAY,
+ border: `1px solid ${hasConfiguredKeys ? BLOOMBERG.GREEN : BLOOMBERG.GRAY}`,
+ color: BLOOMBERG.DARK_BG,
+ padding: '6px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: '600',
+ cursor: (isLoading || !hasConfiguredKeys) ? 'not-allowed' : 'pointer',
+ opacity: (isLoading || !hasConfiguredKeys) ? 0.5 : 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ letterSpacing: '0.3px'
+ }}
+ >
+ {isLoading ? <Loader2 size={12} className="animate-spin" /> : <Target size={12} />}
+ SIGNAL
+ </button>
+ <select
+ value={strategy}
+ onChange={(e) => setStrategy(e.target.value as any)}
+ style={{
+ width: '100%',
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ color: BLOOMBERG.GRAY,
+ padding: '4px 6px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ marginTop: '3px',
+ cursor: 'pointer'
+ }}
+ >
+ <option value="momentum">Momentum</option>
+ <option value="breakout">Breakout</option>
+ <option value="reversal">Reversal</option>
+ <option value="trend_following">Trend</option>
+ </select>
+ </div>
+
+ {/* Assess Risk */}
+ <button
+ onClick={onAssessRisk}
+ disabled={isLoading || !hasConfiguredKeys}
+ style={{
+ width: '100%',
+ background: hasConfiguredKeys ? BLOOMBERG.ORANGE : BLOOMBERG.GRAY,
+ border: `1px solid ${hasConfiguredKeys ? BLOOMBERG.ORANGE : BLOOMBERG.GRAY}`,
+ color: BLOOMBERG.DARK_BG,
+ padding: '6px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: '600',
+ cursor: (isLoading || !hasConfiguredKeys) ? 'not-allowed' : 'pointer',
+ opacity: (isLoading || !hasConfiguredKeys) ? 0.5 : 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ letterSpacing: '0.3px'
+ }}
+ >
+ {isLoading ? <Loader2 size={12} className="animate-spin" /> : <Shield size={12} />}
+ RISK
+ </button>
+
+ {/* Start Competition */}
+ <button
+ onClick={onStartCompetition}
+ disabled={isLoading || availableModels.length < 2}
+ style={{
+ width: '100%',
+ background: (availableModels.length >= 2) ? BLOOMBERG.PURPLE : BLOOMBERG.GRAY,
+ border: `1px solid ${(availableModels.length >= 2) ? BLOOMBERG.PURPLE : BLOOMBERG.GRAY}`,
+ color: BLOOMBERG.WHITE,
+ padding: '6px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: '600',
+ cursor: (isLoading || availableModels.length < 2) ? 'not-allowed' : 'pointer',
+ opacity: (isLoading || availableModels.length < 2) ? 0.5 : 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ letterSpacing: '0.3px'
+ }}
+ >
+ {isLoading ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
+ COMPETE
+ </button>
+ </div>
+
+ {!hasConfiguredKeys && (
+ <div style={{ fontSize: '8px', color: BLOOMBERG.RED, marginTop: '4px', textAlign: 'center' }}>
+ Configure API keys in Settings → LLM Config
+ </div>
+ )}
+
+ {hasConfiguredKeys && availableModels.length < 2 && (
+ <div style={{ fontSize: '8px', color: BLOOMBERG.YELLOW, marginTop: '4px', textAlign: 'center' }}>
+ Add 2+ models for multi-model competition
+ </div>
+ )}
+
+ {/* Error Display */}
+ {error && (
+ <div style={{
+ background: `${BLOOMBERG.RED}10`,
+ border: `1px solid ${BLOOMBERG.RED}`,
+ borderRadius: '2px',
+ padding: '6px 8px',
+ display: 'flex',
+ alignItems: 'flex-start',
+ gap: '6px'
+ }}>
+ <AlertCircle size={12} color={BLOOMBERG.RED} style={{ flexShrink: 0, marginTop: '1px' }} />
+ <div>
+ <div style={{ color: BLOOMBERG.RED, fontSize: '9px', fontWeight: '600', letterSpacing: '0.3px' }}>ERROR</div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginTop: '2px', lineHeight: '1.4' }}>{error}</div>
+ </div>
+ </div>
+ )}
+
+ {/* Result Display */}
+ {result && (
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '2px',
+ padding: '8px',
+ maxHeight: '300px',
+ overflow: 'auto'
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ marginBottom: '6px',
+ paddingBottom: '6px',
+ borderBottom: `1px solid ${BLOOMBERG.BORDER}`
+ }}>
+ <CheckCircle size={12} color={BLOOMBERG.GREEN} />
+ <span style={{ color: BLOOMBERG.GREEN, fontSize: '9px', fontWeight: '600', letterSpacing: '0.5px' }}>
+ {result.type === 'market_analysis' && 'MARKET ANALYSIS'}
+ {result.type === 'trade_signal' && 'TRADE SIGNAL'}
+ {result.type === 'risk_analysis' && 'RISK ASSESSMENT'}
+ {result.type === 'competition' && 'MULTI-MODEL COMPETITION'}
+ </span>
+ </div>
+
+ {result.type === 'competition' ? (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ {/* Consensus */}
+ <div>
+ <div style={{ color: BLOOMBERG.ORANGE, fontSize: '8px', fontWeight: '700', marginBottom: '4px' }}>
+ CONSENSUS ({result.data.consensus.total_models} MODELS)
+ </div>
+ <div style={{
+ background: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '2px',
+ padding: '6px',
+ fontSize: '9px',
+ color: BLOOMBERG.WHITE
+ }}>
+ Action: <span style={{ color: BLOOMBERG.CYAN, fontWeight: '700' }}>
+ {result.data.consensus.action.toUpperCase()}
+ </span>
+ {' • '}
+ Confidence: <span style={{ color: BLOOMBERG.YELLOW, fontWeight: '700' }}>
+ {(result.data.consensus.confidence * 100).toFixed(0)}%
+ </span>
+ {' • '}
+ Agreement: <span style={{ color: BLOOMBERG.GREEN, fontWeight: '700' }}>
+ {result.data.consensus.agreement}/{result.data.consensus.total_models}
+ </span>
+ </div>
+ </div>
+
+ {/* Model Results */}
+ <div>
+ <div style={{ color: BLOOMBERG.ORANGE, fontSize: '8px', fontWeight: '700', marginBottom: '4px' }}>
+ MODEL DECISIONS
+ </div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
+ {result.data.results.map((r: any, idx: number) => (
+ <div
+ key={idx}
+ style={{
+ background: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '2px',
+ padding: '4px 6px',
+ fontSize: '9px'
+ }}
+ >
+ <span style={{ color: BLOOMBERG.CYAN, fontWeight: '700' }}>
+ {r.model.split(':')[1] || r.model}:
+ </span>
+ {' '}
+ <span style={{ color: BLOOMBERG.WHITE }}>
+ {r.decision?.action?.toUpperCase() || 'ANALYZING...'}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ ) : (
+ <div style={{
+ color: BLOOMBERG.WHITE,
+ fontSize: '10px',
+ lineHeight: '1.5',
+ whiteSpace: 'pre-wrap',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {result.data.analysis || result.data.signal || result.data.risk_analysis}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+// ============================================================================
+// Create Agent View
+// ============================================================================
+
+function CreateAgentView({ selectedSymbol, onAgentCreated }: {
+ selectedSymbol: string;
+ onAgentCreated: (agent: AgentInfo) => void;
+}) {
+ return <AgentConfigurationUI onAgentCreated={onAgentCreated} />;
+}
+
+// ============================================================================
+// Manage Agents View
+// ============================================================================
+
+interface AgentStatus {
+ id: string;
+ name: string;
+ type: string;
+ status: 'running' | 'paused' | 'stopped';
+ autoTrading: boolean;
+ metrics: {
+ totalTrades: number;
+ winningTrades: number;
+ losingTrades: number;
+ totalPnL: number;
+ dailyPnL: number;
+ currentDrawdown: number;
+ confidence: number;
+ };
+ lastActivity?: string;
+}
+
+function ManageAgentsView({ agents }: { agents: AgentInfo[] }) {
+ const [agentStatuses, setAgentStatuses] = useState<AgentStatus[]>([]);
+ const [expandedAgent, setExpandedAgent] = useState<string | null>(null);
+
+ // Mock data for demonstration
+ useEffect(() => {
+ if (agents.length > 0) {
+ const mockStatuses: AgentStatus[] = agents.map((agent, idx) => ({
+ id: agent.agent_id,
+ name: agent.config.name,
+ type: agent.config.role,
+ status: idx === 0 ? 'running' : 'stopped',
+ autoTrading: idx === 0,
+ metrics: {
+ totalTrades: Math.floor(Math.random() * 50),
+ winningTrades: Math.floor(Math.random() * 30),
+ losingTrades: Math.floor(Math.random() * 20),
+ totalPnL: (Math.random() - 0.5) * 5000,
+ dailyPnL: (Math.random() - 0.5) * 500,
+ currentDrawdown: Math.random() * 0.15,
+ confidence: 0.6 + Math.random() * 0.3
+ },
+ lastActivity: new Date().toISOString()
+ }));
+ setAgentStatuses(mockStatuses);
+ }
+ }, [agents]);
+
+ const handleStart = (agentId: string) => {
+ setAgentStatuses(prev => prev.map(a =>
+ a.id === agentId ? { ...a, status: 'running' as const } : a
+ ));
+ };
+
+ const handlePause = (agentId: string) => {
+ setAgentStatuses(prev => prev.map(a =>
+ a.id === agentId ? { ...a, status: 'paused' as const } : a
+ ));
+ };
+
+ const handleStop = (agentId: string) => {
+ setAgentStatuses(prev => prev.map(a =>
+ a.id === agentId ? { ...a, status: 'stopped' as const, autoTrading: false } : a
+ ));
+ };
+
+ const handleEmergencyStop = () => {
+ setAgentStatuses(prev => prev.map(a => ({ ...a, status: 'stopped' as const, autoTrading: false })));
+ };
+
+ if (agents.length === 0) {
+ return (
+ <div style={{ color: BLOOMBERG.GRAY, textAlign: 'center', padding: '30px 12px' }}>
+ <Bot size={32} color={BLOOMBERG.GRAY} style={{ margin: '0 auto 10px' }} />
+ <div style={{ fontSize: '11px', fontWeight: '600', marginBottom: '4px', letterSpacing: '0.5px' }}>
+ NO AGENTS
+ </div>
+ <div style={{ fontSize: '9px', lineHeight: '1.4' }}>
+ Create your first AI agent
+ </div>
+ </div>
+ );
+ }
+
+ const runningAgents = agentStatuses.filter(a => a.status === 'running').length;
+ const totalPnL = agentStatuses.reduce((sum, a) => sum + a.metrics.totalPnL, 0);
+ const totalTrades = agentStatuses.reduce((sum, a) => sum + a.metrics.totalTrades, 0);
+
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ {/* Overview Stats */}
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '6px' }}>
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '2px',
+ padding: '6px 8px'
+ }}>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '8px', marginBottom: '3px', letterSpacing: '0.5px' }}>
+ ACTIVE
+ </div>
+ <div style={{ color: BLOOMBERG.WHITE, fontSize: '14px', fontWeight: '700', fontFamily: '"IBM Plex Mono", monospace' }}>
+ {runningAgents}/{agents.length}
+ </div>
+ </div>
+
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '2px',
+ padding: '6px 8px'
+ }}>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '8px', marginBottom: '3px', letterSpacing: '0.5px' }}>
+ P&L
+ </div>
+ <div style={{
+ color: totalPnL >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED,
+ fontSize: '14px',
+ fontWeight: '700',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ ${totalPnL.toFixed(0)}
+ </div>
+ </div>
+
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '2px',
+ padding: '6px 8px'
+ }}>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '8px', marginBottom: '3px', letterSpacing: '0.5px' }}>
+ TRADES
+ </div>
+ <div style={{ color: BLOOMBERG.WHITE, fontSize: '14px', fontWeight: '700', fontFamily: '"IBM Plex Mono", monospace' }}>
+ {totalTrades}
+ </div>
+ </div>
+
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '2px',
+ padding: '6px 8px'
+ }}>
+ <button
+ onClick={handleEmergencyStop}
+ disabled={runningAgents === 0}
+ style={{
+ width: '100%',
+ height: '100%',
+ background: runningAgents > 0 ? BLOOMBERG.RED : 'transparent',
+ border: `1px solid ${runningAgents > 0 ? BLOOMBERG.RED : BLOOMBERG.BORDER}`,
+ color: runningAgents > 0 ? BLOOMBERG.WHITE : BLOOMBERG.GRAY,
+ borderRadius: '2px',
+ fontSize: '8px',
+ fontWeight: '600',
+ cursor: runningAgents > 0 ? 'pointer' : 'not-allowed',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '3px',
+ letterSpacing: '0.3px'
+ }}
+ >
+ <Square size={10} />
+ STOP
+ </button>
+ </div>
+ </div>
+
+ {/* Agent List */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
+ {agentStatuses.map(agent => (
+ <AgentCard
+ key={agent.id}
+ agent={agent}
+ isExpanded={expandedAgent === agent.id}
+ onToggleExpand={() => setExpandedAgent(expandedAgent === agent.id ? null : agent.id)}
+ onStart={() => handleStart(agent.id)}
+ onPause={() => handlePause(agent.id)}
+ onStop={() => handleStop(agent.id)}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+// ============================================================================
+// Agent Card Component
+// ============================================================================
+
+interface AgentCardProps {
+ agent: AgentStatus;
+ isExpanded: boolean;
+ onToggleExpand: () => void;
+ onStart: () => void;
+ onPause: () => void;
+ onStop: () => void;
+}
+
+function AgentCard({ agent, isExpanded, onToggleExpand, onStart, onPause, onStop }: AgentCardProps) {
+ const winRate = agent.metrics.totalTrades > 0
+ ? (agent.metrics.winningTrades / agent.metrics.totalTrades) * 100
+ : 0;
+
+ const statusColor = {
+ running: BLOOMBERG.GREEN,
+ paused: BLOOMBERG.YELLOW,
+ stopped: BLOOMBERG.GRAY
+ }[agent.status];
+
+ return (
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${agent.status === 'running' ? BLOOMBERG.GREEN : BLOOMBERG.BORDER}`,
+ borderRadius: '2px',
+ overflow: 'hidden'
+ }}>
+ {/* Header */}
+ <div
+ onClick={onToggleExpand}
+ style={{
+ padding: '6px 8px',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ background: agent.status === 'running' ? `${BLOOMBERG.GREEN}08` : 'transparent'
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1 }}>
+ <div style={{
+ width: '6px',
+ height: '6px',
+ borderRadius: '50%',
+ background: statusColor,
+ boxShadow: agent.status === 'running' ? `0 0 6px ${statusColor}` : 'none'
+ }} />
+
+ <div style={{ flex: 1 }}>
+ <div style={{
+ color: BLOOMBERG.WHITE,
+ fontSize: '10px',
+ fontWeight: '600',
+ marginBottom: '1px'
+ }}>
+ {agent.name}
+ </div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '8px' }}>
+ {agent.type.replace(/_/g, ' ').toUpperCase()}
+ {agent.autoTrading && <span style={{ color: BLOOMBERG.ORANGE, marginLeft: '6px' }}>● AUTO</span>}
+ </div>
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
+ <div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '7px', letterSpacing: '0.5px' }}>P&L</div>
+ <div style={{
+ color: agent.metrics.totalPnL >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED,
+ fontSize: '10px',
+ fontWeight: '700',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ ${agent.metrics.totalPnL.toFixed(0)}
+ </div>
+ </div>
+
+ <div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '7px', letterSpacing: '0.5px' }}>WIN</div>
+ <div style={{ color: BLOOMBERG.WHITE, fontSize: '10px', fontWeight: '700', fontFamily: '"IBM Plex Mono", monospace' }}>
+ {winRate.toFixed(0)}%
+ </div>
+ </div>
+
+ <div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '7px', letterSpacing: '0.5px' }}>TRD</div>
+ <div style={{ color: BLOOMBERG.WHITE, fontSize: '10px', fontWeight: '700', fontFamily: '"IBM Plex Mono", monospace' }}>
+ {agent.metrics.totalTrades}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {isExpanded ? <ChevronUp size={12} color={BLOOMBERG.GRAY} /> : <ChevronDown size={12} color={BLOOMBERG.GRAY} />}
+ </div>
+
+ {/* Expanded Details */}
+ {isExpanded && (
+ <div style={{
+ borderTop: `1px solid ${BLOOMBERG.BORDER}`,
+ padding: '8px',
+ background: BLOOMBERG.PANEL_BG
+ }}>
+ {/* Metrics Grid */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(3, 1fr)',
+ gap: '6px',
+ marginBottom: '8px'
+ }}>
+ <MetricBox label="DAILY" value={`$${agent.metrics.dailyPnL.toFixed(0)}`}
+ color={agent.metrics.dailyPnL >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED} />
+ <MetricBox label="DD" value={`${(agent.metrics.currentDrawdown * 100).toFixed(1)}%`}
+ color={BLOOMBERG.ORANGE} />
+ <MetricBox label="CONF" value={`${(agent.metrics.confidence * 100).toFixed(0)}%`}
+ color={BLOOMBERG.CYAN} />
+ <MetricBox label="WIN" value={agent.metrics.winningTrades.toString()}
+ color={BLOOMBERG.GREEN} />
+ <MetricBox label="LOSS" value={agent.metrics.losingTrades.toString()}
+ color={BLOOMBERG.RED} />
+ <MetricBox label="STATE" value={agent.status.toUpperCase()}
+ color={statusColor} />
+ </div>
+
+ {/* Controls */}
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {agent.status !== 'running' && (
+ <button
+ onClick={onStart}
+ style={{
+ flex: 1,
+ background: BLOOMBERG.GREEN,
+ border: 'none',
+ color: BLOOMBERG.DARK_BG,
+ padding: '6px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: '600',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ letterSpacing: '0.3px'
+ }}
+ >
+ <Play size={10} />
+ START
+ </button>
+ )}
+
+ {agent.status === 'running' && (
+ <button
+ onClick={onPause}
+ style={{
+ flex: 1,
+ background: BLOOMBERG.YELLOW,
+ border: 'none',
+ color: BLOOMBERG.DARK_BG,
+ padding: '6px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: '600',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ letterSpacing: '0.3px'
+ }}
+ >
+ <Pause size={10} />
+ PAUSE
+ </button>
+ )}
+
+ {agent.status !== 'stopped' && (
+ <button
+ onClick={onStop}
+ style={{
+ flex: 1,
+ background: BLOOMBERG.RED,
+ border: 'none',
+ color: BLOOMBERG.WHITE,
+ padding: '6px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: '600',
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ letterSpacing: '0.3px'
+ }}
+ >
+ <Square size={10} />
+ STOP
+ </button>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+// ============================================================================
+// Metric Box Component
+// ============================================================================
+
+function MetricBox({ label, value, color }: { label: string; value: string; color: string }) {
+ return (
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '2px',
+ padding: '5px 6px'
+ }}>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '7px', marginBottom: '2px', letterSpacing: '0.5px' }}>
+ {label}
+ </div>
+ <div style={{ color, fontSize: '11px', fontWeight: '700', fontFamily: '"IBM Plex Mono", monospace' }}>
+ {value}
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/AgentConfigurationUI.tsx b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/AgentConfigurationUI.tsx
new file mode 100644
index 000000000..bfd73406c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/AgentConfigurationUI.tsx
@@ -0,0 +1,689 @@
+/**
+ * Agent Configuration UI
+ *
+ * Complete control panel for creating and configuring AI trading agents.
+ * Includes all Alpha Arena features: auto-trading, TP/SL, confidence, safety limits.
+ */
+
+import React, { useState } from 'react';
+import {
+ Bot, Brain, Shield, Target, Zap, Settings, AlertTriangle,
+ Clock, TrendingUp, Activity, BarChart3, Sliders, Play, Pause,
+ Power, Info, ChevronDown, ChevronUp, Save
+} from 'lucide-react';
+import agnoTradingService, { type AgentConfig } from '../../../../services/agnoTradingService';
+
+const BLOOMBERG = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ HEADER_BG: '#1A1A1A',
+ CYAN: '#00E5FF',
+ YELLOW: '#FFD700',
+ BLUE: '#0088FF',
+ BORDER: '#2A2A2A',
+ HOVER: '#1F1F1F',
+};
+
+interface AgentConfigUIProps {
+ onAgentCreated: (agent: any) => void;
+}
+
+export function AgentConfigurationUI({ onAgentCreated }: AgentConfigUIProps) {
+ // Basic Config
+ const [agentName, setAgentName] = useState('');
+ const [agentType, setAgentType] = useState('trading_strategy');
+ const [description, setDescription] = useState('');
+
+ // LLM Config
+ const [provider, setProvider] = useState('openai');
+ const [model, setModel] = useState('gpt-4o-mini');
+ const [temperature, setTemperature] = useState(0.7);
+
+ // Trading Config
+ const [symbols, setSymbols] = useState(['BTC/USD']);
+ const [autoTrading, setAutoTrading] = useState(false);
+ const [executionInterval, setExecutionInterval] = useState(180); // 3 minutes like Alpha Arena
+
+ // Safety Limits
+ const [maxPositionSize, setMaxPositionSize] = useState(0.1); // 10%
+ const [maxLeverage, setMaxLeverage] = useState(1.0);
+ const [maxDrawdown, setMaxDrawdown] = useState(0.15); // 15%
+ const [maxDailyLoss, setMaxDailyLoss] = useState(0.05); // 5%
+ const [minConfidence, setMinConfidence] = useState(0.6);
+ const [maxOpenPositions, setMaxOpenPositions] = useState(5);
+
+ // TP/SL Config
+ const [useDynamicTPSL, setUseDynamicTPSL] = useState(true);
+ const [riskRewardRatio, setRiskRewardRatio] = useState(2.0);
+ const [stopLossPercent, setStopLossPercent] = useState(2.0);
+ const [takeProfitPercent, setTakeProfitPercent] = useState(5.0);
+ const [useTrailingStop, setUseTrailingStop] = useState(false);
+ const [trailingPercent, setTrailingPercent] = useState(1.0);
+
+ // Advanced Config
+ const [enableMemory, setEnableMemory] = useState(true);
+ const [enableKnowledge, setEnableKnowledge] = useState(false);
+ const [customInstructions, setCustomInstructions] = useState('');
+
+ // UI State
+ const [expandedSections, setExpandedSections] = useState<Set<string>>(
+ new Set(['basic', 'llm', 'trading'])
+ );
+ const [isCreating, setIsCreating] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const toggleSection = (section: string) => {
+ const newExpanded = new Set(expandedSections);
+ if (newExpanded.has(section)) {
+ newExpanded.delete(section);
+ } else {
+ newExpanded.add(section);
+ }
+ setExpandedSections(newExpanded);
+ };
+
+ const handleCreateAgent = async () => {
+ setIsCreating(true);
+ setError(null);
+
+ try {
+ const config: AgentConfig = {
+ name: agentName || 'Trading Agent',
+ role: agentTypeToRole(agentType),
+ description: description || getDefaultDescription(agentType),
+ agent_model: `${provider}:${model}`,
+ temperature,
+ tools: getToolsForAgentType(agentType),
+ symbols,
+ enable_memory: enableMemory,
+ risk_tolerance: getRiskTolerance(),
+ instructions: customInstructions.split('\n').filter(i => i.trim())
+ };
+
+ const response = await agnoTradingService.createAgent(config);
+
+ if (response.success && response.data) {
+ onAgentCreated({
+ ...response.data,
+ autoTrading: {
+ enabled: autoTrading,
+ interval: executionInterval,
+ safety: {
+ maxPositionSize,
+ maxLeverage,
+ maxDrawdown,
+ maxDailyLoss,
+ minConfidence,
+ maxOpenPositions
+ },
+ tpsl: {
+ dynamic: useDynamicTPSL,
+ riskReward: riskRewardRatio,
+ slPercent: stopLossPercent,
+ tpPercent: takeProfitPercent,
+ trailing: useTrailingStop,
+ trailingPercent
+ }
+ }
+ });
+ } else {
+ setError(response.error || 'Failed to create agent');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error');
+ } finally {
+ setIsCreating(false);
+ }
+ };
+
+ const agentTypeToRole = (type: string): string => {
+ const roles: Record<string, string> = {
+ 'market_analyst': 'Market Analysis Specialist',
+ 'trading_strategy': 'Trading Strategy Expert',
+ 'risk_manager': 'Risk Management Specialist',
+ 'portfolio_manager': 'Portfolio Manager',
+ 'sentiment_analyst': 'Sentiment Analysis Expert'
+ };
+ return roles[type] || 'Trading Agent';
+ };
+
+ const getDefaultDescription = (type: string): string => {
+ const descriptions: Record<string, string> = {
+ 'market_analyst': 'Analyzes market data, technical indicators, and trends to provide insights',
+ 'trading_strategy': 'Generates trade signals with entry/exit points and risk management',
+ 'risk_manager': 'Monitors portfolio risk and ensures compliance with safety limits',
+ 'portfolio_manager': 'Manages asset allocation and portfolio optimization',
+ 'sentiment_analyst': 'Analyzes market sentiment from news and social media'
+ };
+ return descriptions[type] || 'AI-powered trading agent';
+ };
+
+ const getToolsForAgentType = (type: string): string[] => {
+ const toolMap: Record<string, string[]> = {
+ 'market_analyst': ['market_data', 'technical_analysis'],
+ 'trading_strategy': ['market_data', 'technical_analysis', 'order_execution'],
+ 'risk_manager': ['portfolio', 'market_data'],
+ 'portfolio_manager': ['portfolio', 'market_data'],
+ 'sentiment_analyst': ['news_sentiment', 'market_data']
+ };
+ return toolMap[type] || ['market_data'];
+ };
+
+ const getRiskTolerance = (): string => {
+ if (maxDrawdown <= 0.10) return 'conservative';
+ if (maxDrawdown >= 0.20) return 'aggressive';
+ return 'moderate';
+ };
+
+ return (
+ <div style={{ padding: '8px', height: '100%', overflow: 'auto' }}>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
+
+ {/* Basic Configuration */}
+ <ConfigSection
+ title="BASIC CONFIGURATION"
+ icon={<Bot size={14} />}
+ expanded={expandedSections.has('basic')}
+ onToggle={() => toggleSection('basic')}
+ >
+ <div style={{ display: 'grid', gap: '12px' }}>
+ <InputField label="Agent Name" value={agentName} onChange={setAgentName} placeholder="My Trading Agent" />
+
+ <SelectField
+ label="Agent Type"
+ value={agentType}
+ onChange={setAgentType}
+ options={[
+ { value: 'market_analyst', label: 'Market Analyst' },
+ { value: 'trading_strategy', label: 'Trading Strategy' },
+ { value: 'risk_manager', label: 'Risk Manager' },
+ { value: 'portfolio_manager', label: 'Portfolio Manager' },
+ { value: 'sentiment_analyst', label: 'Sentiment Analyst' }
+ ]}
+ />
+
+ <TextArea label="Description (Optional)" value={description} onChange={setDescription} rows={2} />
+ </div>
+ </ConfigSection>
+
+ {/* LLM Configuration */}
+ <ConfigSection
+ title="LLM CONFIGURATION"
+ icon={<Brain size={14} />}
+ expanded={expandedSections.has('llm')}
+ onToggle={() => toggleSection('llm')}
+ >
+ <div style={{ display: 'grid', gap: '12px' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ <SelectField
+ label="Provider"
+ value={provider}
+ onChange={setProvider}
+ options={[
+ { value: 'openai', label: 'OpenAI' },
+ { value: 'anthropic', label: 'Anthropic' },
+ { value: 'google', label: 'Google' },
+ { value: 'groq', label: 'Groq (Fast & Free)' },
+ { value: 'deepseek', label: 'DeepSeek' },
+ { value: 'xai', label: 'xAI (Grok)' },
+ { value: 'ollama', label: 'Ollama (Local)' }
+ ]}
+ />
+
+ <InputField label="Model" value={model} onChange={setModel} placeholder="gpt-4o-mini" />
+ </div>
+
+ <SliderField
+ label="Temperature"
+ value={temperature}
+ onChange={setTemperature}
+ min={0}
+ max={1}
+ step={0.1}
+ showValue
+ />
+ </div>
+ </ConfigSection>
+
+ {/* Trading Configuration */}
+ <ConfigSection
+ title="TRADING CONFIGURATION"
+ icon={<TrendingUp size={14} />}
+ expanded={expandedSections.has('trading')}
+ onToggle={() => toggleSection('trading')}
+ >
+ <div style={{ display: 'grid', gap: '12px' }}>
+ <InputField
+ label="Trading Symbols (comma-separated)"
+ value={symbols.join(', ')}
+ onChange={(val: string) => setSymbols(val.split(',').map((s: string) => s.trim()))}
+ placeholder="BTC/USD, ETH/USD"
+ />
+
+ <CheckboxField
+ label="Enable Auto-Trading (Alpha Arena Mode)"
+ checked={autoTrading}
+ onChange={setAutoTrading}
+ description="Agent will execute trades automatically every few minutes"
+ />
+
+ {autoTrading && (
+ <SliderField
+ label="Execution Interval (seconds)"
+ value={executionInterval}
+ onChange={setExecutionInterval}
+ min={60}
+ max={600}
+ step={30}
+ showValue
+ description="How often the agent makes trading decisions (Alpha Arena uses 180s)"
+ />
+ )}
+ </div>
+ </ConfigSection>
+
+ {/* Safety Limits */}
+ <ConfigSection
+ title="SAFETY LIMITS"
+ icon={<Shield size={14} />}
+ expanded={expandedSections.has('safety')}
+ onToggle={() => toggleSection('safety')}
+ >
+ <div style={{ display: 'grid', gap: '12px' }}>
+ <SliderField
+ label="Max Position Size (% of portfolio)"
+ value={maxPositionSize * 100}
+ onChange={(val: number) => setMaxPositionSize(val / 100)}
+ min={1}
+ max={50}
+ step={1}
+ showValue
+ suffix="%"
+ />
+
+ <SliderField
+ label="Max Leverage"
+ value={maxLeverage}
+ onChange={setMaxLeverage}
+ min={1}
+ max={10}
+ step={0.5}
+ showValue
+ suffix="x"
+ />
+
+ <SliderField
+ label="Max Drawdown (circuit breaker)"
+ value={maxDrawdown * 100}
+ onChange={(val: number) => setMaxDrawdown(val / 100)}
+ min={5}
+ max={50}
+ step={5}
+ showValue
+ suffix="%"
+ description="Auto-trading stops if drawdown exceeds this"
+ />
+
+ <SliderField
+ label="Max Daily Loss"
+ value={maxDailyLoss * 100}
+ onChange={(val: number) => setMaxDailyLoss(val / 100)}
+ min={1}
+ max={20}
+ step={1}
+ showValue
+ suffix="%"
+ />
+
+ <SliderField
+ label="Min Confidence to Execute"
+ value={minConfidence * 100}
+ onChange={(val: number) => setMinConfidence(val / 100)}
+ min={30}
+ max={90}
+ step={5}
+ showValue
+ suffix="%"
+ description="Only execute trades above this confidence"
+ />
+
+ <SliderField
+ label="Max Open Positions"
+ value={maxOpenPositions}
+ onChange={setMaxOpenPositions}
+ min={1}
+ max={20}
+ step={1}
+ showValue
+ />
+ </div>
+ </ConfigSection>
+
+ {/* TP/SL Configuration */}
+ <ConfigSection
+ title="TAKE PROFIT / STOP LOSS"
+ icon={<Target size={14} />}
+ expanded={expandedSections.has('tpsl')}
+ onToggle={() => toggleSection('tpsl')}
+ >
+ <div style={{ display: 'grid', gap: '12px' }}>
+ <CheckboxField
+ label="Dynamic TP/SL (based on volatility)"
+ checked={useDynamicTPSL}
+ onChange={setUseDynamicTPSL}
+ description="Alpha Arena style - adjusts TP/SL based on current market volatility"
+ />
+
+ {useDynamicTPSL ? (
+ <SliderField
+ label="Risk/Reward Ratio"
+ value={riskRewardRatio}
+ onChange={setRiskRewardRatio}
+ min={1}
+ max={5}
+ step={0.5}
+ showValue
+ suffix=":1"
+ />
+ ) : (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ <SliderField
+ label="Stop Loss %"
+ value={stopLossPercent}
+ onChange={setStopLossPercent}
+ min={0.5}
+ max={10}
+ step={0.5}
+ showValue
+ suffix="%"
+ />
+
+ <SliderField
+ label="Take Profit %"
+ value={takeProfitPercent}
+ onChange={setTakeProfitPercent}
+ min={1}
+ max={20}
+ step={0.5}
+ showValue
+ suffix="%"
+ />
+ </div>
+ )}
+
+ <CheckboxField
+ label="Trailing Stop Loss"
+ checked={useTrailingStop}
+ onChange={setUseTrailingStop}
+ description="Lock in profits as price moves favorably"
+ />
+
+ {useTrailingStop && (
+ <SliderField
+ label="Trailing Distance %"
+ value={trailingPercent}
+ onChange={setTrailingPercent}
+ min={0.5}
+ max={5}
+ step={0.5}
+ showValue
+ suffix="%"
+ />
+ )}
+ </div>
+ </ConfigSection>
+
+ {/* Advanced Configuration */}
+ <ConfigSection
+ title="ADVANCED OPTIONS"
+ icon={<Settings size={14} />}
+ expanded={expandedSections.has('advanced')}
+ onToggle={() => toggleSection('advanced')}
+ >
+ <div style={{ display: 'grid', gap: '12px' }}>
+ <CheckboxField
+ label="Enable Memory"
+ checked={enableMemory}
+ onChange={setEnableMemory}
+ description="Agent remembers past decisions and learns from them"
+ />
+
+ <CheckboxField
+ label="Enable Knowledge Base"
+ checked={enableKnowledge}
+ onChange={setEnableKnowledge}
+ description="Access to historical market data and patterns"
+ />
+
+ <TextArea
+ label="Custom Instructions (one per line)"
+ value={customInstructions}
+ onChange={setCustomInstructions}
+ rows={4}
+ placeholder="Always use risk management&#10;Never trade during low volume&#10;Focus on high confidence setups"
+ />
+ </div>
+ </ConfigSection>
+
+ {/* Error Display */}
+ {error && (
+ <div style={{
+ background: `${BLOOMBERG.RED}15`,
+ border: `1px solid ${BLOOMBERG.RED}`,
+ borderRadius: '4px',
+ padding: '12px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}>
+ <AlertTriangle size={16} color={BLOOMBERG.RED} />
+ <span style={{ color: BLOOMBERG.RED, fontSize: '11px' }}>{error}</span>
+ </div>
+ )}
+
+ {/* Create Button */}
+ <button
+ onClick={handleCreateAgent}
+ disabled={isCreating || !agentName}
+ style={{
+ background: `linear-gradient(135deg, ${BLOOMBERG.GREEN} 0%, #00B359 100%)`,
+ border: 'none',
+ color: BLOOMBERG.DARK_BG,
+ padding: '14px',
+ borderRadius: '4px',
+ fontSize: '12px',
+ fontWeight: '700',
+ cursor: isCreating || !agentName ? 'not-allowed' : 'pointer',
+ opacity: isCreating || !agentName ? 0.5 : 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px',
+ marginTop: '8px'
+ }}
+ >
+ <Save size={16} />
+ {isCreating ? 'CREATING AGENT...' : 'CREATE AGENT'}
+ </button>
+ </div>
+ </div>
+ );
+}
+
+// Helper Components
+
+function ConfigSection({ title, icon, expanded, onToggle, children }: any) {
+ return (
+ <div style={{
+ background: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ overflow: 'hidden'
+ }}>
+ <div
+ onClick={onToggle}
+ style={{
+ background: BLOOMBERG.HEADER_BG,
+ padding: '10px 12px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ cursor: 'pointer',
+ borderBottom: expanded ? `1px solid ${BLOOMBERG.BORDER}` : 'none'
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: BLOOMBERG.ORANGE }}>{icon}</span>
+ <span style={{ color: BLOOMBERG.WHITE, fontSize: '11px', fontWeight: '700' }}>{title}</span>
+ </div>
+ {expanded ? <ChevronUp size={14} color={BLOOMBERG.GRAY} /> : <ChevronDown size={14} color={BLOOMBERG.GRAY} />}
+ </div>
+ {expanded && (
+ <div style={{ padding: '12px' }}>
+ {children}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function InputField({ label, value, onChange, placeholder = '', type = 'text' }: any) {
+ return (
+ <div>
+ <label style={{ color: BLOOMBERG.GRAY, fontSize: '10px', fontWeight: '600', display: 'block', marginBottom: '4px' }}>
+ {label}
+ </label>
+ <input
+ type={type}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={placeholder}
+ style={{
+ width: '100%',
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ color: BLOOMBERG.WHITE,
+ padding: '8px',
+ borderRadius: '3px',
+ fontSize: '11px'
+ }}
+ />
+ </div>
+ );
+}
+
+function SelectField({ label, value, onChange, options }: any) {
+ return (
+ <div>
+ <label style={{ color: BLOOMBERG.GRAY, fontSize: '10px', fontWeight: '600', display: 'block', marginBottom: '4px' }}>
+ {label}
+ </label>
+ <select
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ style={{
+ width: '100%',
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ color: BLOOMBERG.WHITE,
+ padding: '8px',
+ borderRadius: '3px',
+ fontSize: '11px',
+ cursor: 'pointer'
+ }}
+ >
+ {options.map((opt: any) => (
+ <option key={opt.value} value={opt.value}>{opt.label}</option>
+ ))}
+ </select>
+ </div>
+ );
+}
+
+function TextArea({ label, value, onChange, rows = 3, placeholder = '' }: any) {
+ return (
+ <div>
+ <label style={{ color: BLOOMBERG.GRAY, fontSize: '10px', fontWeight: '600', display: 'block', marginBottom: '4px' }}>
+ {label}
+ </label>
+ <textarea
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ rows={rows}
+ placeholder={placeholder}
+ style={{
+ width: '100%',
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ color: BLOOMBERG.WHITE,
+ padding: '8px',
+ borderRadius: '3px',
+ fontSize: '11px',
+ resize: 'vertical',
+ fontFamily: 'inherit'
+ }}
+ />
+ </div>
+ );
+}
+
+function CheckboxField({ label, checked, onChange, description = '' }: any) {
+ return (
+ <div>
+ <label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer' }}>
+ <input
+ type="checkbox"
+ checked={checked}
+ onChange={(e) => onChange(e.target.checked)}
+ style={{ cursor: 'pointer' }}
+ />
+ <span style={{ color: BLOOMBERG.WHITE, fontSize: '11px', fontWeight: '600' }}>{label}</span>
+ </label>
+ {description && (
+ <p style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginTop: '4px', marginLeft: '24px' }}>
+ {description}
+ </p>
+ )}
+ </div>
+ );
+}
+
+function SliderField({ label, value, onChange, min, max, step, showValue, suffix = '', description = '' }: any) {
+ return (
+ <div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
+ <label style={{ color: BLOOMBERG.GRAY, fontSize: '10px', fontWeight: '600' }}>
+ {label}
+ </label>
+ {showValue && (
+ <span style={{ color: BLOOMBERG.CYAN, fontSize: '10px', fontWeight: '700' }}>
+ {value}{suffix}
+ </span>
+ )}
+ </div>
+ <input
+ type="range"
+ min={min}
+ max={max}
+ step={step}
+ value={value}
+ onChange={(e) => onChange(parseFloat(e.target.value))}
+ style={{
+ width: '100%',
+ cursor: 'pointer',
+ accentColor: BLOOMBERG.ORANGE
+ }}
+ />
+ {description && (
+ <p style={{ color: BLOOMBERG.GRAY, fontSize: '9px', marginTop: '4px' }}>
+ {description}
+ </p>
+ )}
+ </div>
+ );
+}
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.tsx
new file mode 100644
index 000000000..15339e2c0
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/CompetitionPanel.tsx
@@ -0,0 +1,618 @@
+/**
+ * Competition Panel
+ *
+ * Alpha Arena style AI trading competition
+ * - Create multi-model competitions
+ * - Start/stop competitions
+ * - Real-time decision streaming
+ * - Live leaderboard updates
+ */
+
+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';
+
+const BLOOMBERG = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ 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'
+};
+
+interface CompetitionPanelProps {
+ selectedSymbol: string;
+}
+
+export function CompetitionPanel({ selectedSymbol }: CompetitionPanelProps) {
+ const [teamId, setTeamId] = useState<string | null>(null);
+ const [isRunning, setIsRunning] = useState(false);
+ const [isLoading, setIsLoading] = useState(false);
+ 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[]>([
+ 'openai:gpt-4o-mini',
+ 'anthropic:claude-sonnet-4',
+ 'google:gemini-2.0-flash'
+ ]);
+ const [taskType, setTaskType] = useState<'analyze' | 'signal' | 'evaluate'>('analyze');
+ const [autoRefresh, setAutoRefresh] = useState(true);
+
+ // Available models
+ const availableModels = [
+ { value: 'openai:gpt-4o-mini', label: 'GPT-4o Mini', color: BLOOMBERG.GREEN },
+ { value: 'openai:gpt-4o', label: 'GPT-4o', color: BLOOMBERG.GREEN },
+ { value: 'anthropic:claude-sonnet-4', label: 'Claude Sonnet 4', color: BLOOMBERG.ORANGE },
+ { value: 'anthropic:claude-3-5-sonnet', label: 'Claude 3.5 Sonnet', color: BLOOMBERG.ORANGE },
+ { value: 'google:gemini-2.0-flash', label: 'Gemini 2.0 Flash', color: BLOOMBERG.BLUE },
+ { value: 'google:gemini-1.5-pro', label: 'Gemini 1.5 Pro', color: BLOOMBERG.BLUE },
+ { value: 'groq:llama-3.1-70b', label: 'Llama 3.1 70B', color: BLOOMBERG.PURPLE },
+ { value: 'groq:mixtral-8x7b', label: 'Mixtral 8x7B', color: BLOOMBERG.PURPLE },
+ { value: 'deepseek:deepseek-chat', label: 'DeepSeek Chat', color: BLOOMBERG.CYAN },
+ { value: 'xai:grok-2', label: 'Grok 2', color: BLOOMBERG.YELLOW }
+ ];
+
+ // Create competition
+ const handleCreateCompetition = async () => {
+ if (selectedModels.length < 2) {
+ setError('Select at least 2 models to compete');
+ return;
+ }
+
+ try {
+ setIsLoading(true);
+ setError(null);
+
+ const response = await agnoTradingService.createCompetition(
+ competitionName,
+ selectedModels,
+ 'trading'
+ );
+
+ if (response.success && response.data) {
+ setTeamId(response.data.team_id);
+ setShowSetup(false);
+ } else {
+ setError(response.error || 'Failed to create competition');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ // Run competition
+ const handleRunCompetition = async () => {
+ if (!teamId) return;
+
+ try {
+ setIsLoading(true);
+ setIsRunning(true);
+ setError(null);
+
+ const response = await agnoTradingService.runCompetition(
+ teamId,
+ selectedSymbol,
+ taskType
+ );
+
+ if (response.success && response.data) {
+ setResult(response.data);
+ } else {
+ setError(response.error || 'Competition failed');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setIsLoading(false);
+ setIsRunning(false);
+ }
+ };
+
+ // Stop competition
+ const handleStopCompetition = () => {
+ 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 =>
+ prev.includes(model)
+ ? prev.filter(m => m !== model)
+ : [...prev, model]
+ );
+ };
+
+ return (
+ <div style={{
+ height: '100%',
+ background: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '2px',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ {/* 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>
+ </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>
+
+ {/* Model Selection */}
+ <div>
+ <label style={{ color: BLOOMBERG.GRAY, fontSize: '9px', display: 'block', marginBottom: '6px' }}>
+ SELECT MODELS (min 2)
+ </label>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px' }}>
+ {availableModels.map((model: any) => (
+ <button
+ key={model.value}
+ onClick={() => toggleModel(model.value)}
+ style={{
+ background: selectedModels.includes(model.value) ? `${model.color}20` : BLOOMBERG.DARK_BG,
+ border: `1px solid ${selectedModels.includes(model.value) ? model.color : BLOOMBERG.BORDER}`,
+ color: selectedModels.includes(model.value) ? model.color : BLOOMBERG.GRAY,
+ padding: '6px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ fontWeight: selectedModels.includes(model.value) ? '700' : '400',
+ cursor: 'pointer',
+ transition: 'all 0.2s',
+ textAlign: 'left'
+ }}
+ >
+ {model.label}
+ </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>
+ </div>
+
+ {/* Create Button */}
+ <button
+ onClick={onCreateCompetition}
+ disabled={isLoading || selectedModels.length < 2}
+ style={{
+ background: BLOOMBERG.ORANGE,
+ border: 'none',
+ color: BLOOMBERG.DARK_BG,
+ padding: '10px',
+ borderRadius: '2px',
+ fontSize: '10px',
+ fontWeight: '700',
+ cursor: (isLoading || selectedModels.length < 2) ? 'not-allowed' : 'pointer',
+ opacity: (isLoading || selectedModels.length < 2) ? 0.5 : 1,
+ marginTop: '8px'
+ }}
+ >
+ {isLoading ? 'CREATING...' : 'CREATE 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 && (
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '2px',
+ padding: '10px'
+ }}>
+ <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>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/LeaderboardPanel.tsx b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/LeaderboardPanel.tsx
new file mode 100644
index 000000000..e072d3b56
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/LeaderboardPanel.tsx
@@ -0,0 +1,335 @@
+/**
+ * Leaderboard Panel
+ *
+ * Model performance tracking and leaderboard (Alpha Arena style)
+ * Shows win rate, P&L, trades, and rankings for all competing models
+ */
+
+import React, { useState, useEffect } from 'react';
+import { Trophy, TrendingUp, TrendingDown, Award, Target, Percent, DollarSign } from 'lucide-react';
+import type { ModelPerformance } from '../../../../services/agnoTradingService';
+
+const BLOOMBERG = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ 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'
+};
+
+interface LeaderboardPanelProps {
+ refreshInterval?: number;
+}
+
+export function LeaderboardPanel({ refreshInterval = 10000 }: LeaderboardPanelProps) {
+ const [leaderboard, setLeaderboard] = useState<ModelPerformance[]>([]);
+ const [isLoading, setIsLoading] = useState(false);
+ const [sortBy, setSortBy] = useState<'pnl' | 'winrate' | 'trades'>('pnl');
+
+ const fetchLeaderboard = async () => {
+ try {
+ setIsLoading(true);
+ const { invoke } = await import('@tauri-apps/api/core');
+ const response = await invoke('agno_get_leaderboard');
+ const data = JSON.parse(response as string);
+
+ if (data.success && data.data?.leaderboard) {
+ setLeaderboard(data.data.leaderboard);
+ }
+ } catch (err) {
+ console.error('Failed to fetch leaderboard:', err);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ useEffect(() => {
+ fetchLeaderboard();
+ const interval = setInterval(fetchLeaderboard, refreshInterval);
+ return () => clearInterval(interval);
+ }, [refreshInterval]);
+
+ const sortedLeaderboard = [...leaderboard].sort((a, b) => {
+ switch (sortBy) {
+ case 'pnl':
+ return b.total_pnl - a.total_pnl;
+ case 'winrate':
+ return b.win_rate - a.win_rate;
+ case 'trades':
+ return b.total_trades - a.total_trades;
+ default:
+ return 0;
+ }
+ });
+
+ const getRankColor = (rank: number) => {
+ switch (rank) {
+ case 1: return BLOOMBERG.YELLOW;
+ case 2: return BLOOMBERG.CYAN;
+ case 3: return BLOOMBERG.ORANGE;
+ default: return BLOOMBERG.GRAY;
+ }
+ };
+
+ const getModelColor = (model: string) => {
+ const colors = [BLOOMBERG.ORANGE, BLOOMBERG.CYAN, BLOOMBERG.GREEN, BLOOMBERG.PURPLE, BLOOMBERG.YELLOW];
+ const hash = model.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
+ return colors[hash % colors.length];
+ };
+
+ return (
+ <div style={{
+ height: '100%',
+ background: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '2px',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ {/* 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'
+ }}>
+ LEADERBOARD
+ </span>
+ {isLoading && (
+ <div style={{
+ width: '8px',
+ height: '8px',
+ borderRadius: '50%',
+ background: BLOOMBERG.ORANGE,
+ animation: 'pulse 2s infinite'
+ }} />
+ )}
+ </div>
+
+ {/* Sort Controls */}
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {[
+ { value: 'pnl' as const, label: 'P&L' },
+ { value: 'winrate' as const, label: 'WIN%' },
+ { value: 'trades' as const, label: 'TRADES' }
+ ].map(option => (
+ <button
+ key={option.value}
+ onClick={() => setSortBy(option.value)}
+ style={{
+ background: sortBy === option.value ? BLOOMBERG.ORANGE : 'transparent',
+ border: `1px solid ${sortBy === option.value ? BLOOMBERG.ORANGE : BLOOMBERG.BORDER}`,
+ color: sortBy === option.value ? BLOOMBERG.DARK_BG : BLOOMBERG.GRAY,
+ padding: '2px 6px',
+ borderRadius: '2px',
+ fontSize: '8px',
+ fontWeight: '700',
+ cursor: 'pointer',
+ transition: 'all 0.2s'
+ }}
+ >
+ {option.label}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Leaderboard Table */}
+ <div style={{
+ flex: 1,
+ overflow: 'auto',
+ padding: '10px'
+ }}>
+ {sortedLeaderboard.length === 0 ? (
+ <div style={{
+ textAlign: 'center',
+ color: BLOOMBERG.GRAY,
+ fontSize: '10px',
+ marginTop: '40px'
+ }}>
+ {isLoading ? 'Loading leaderboard...' : 'No models yet. Create a competition to start tracking.'}
+ </div>
+ ) : (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
+ {sortedLeaderboard.map((model, idx) => (
+ <ModelRankCard
+ key={model.model}
+ model={model}
+ rank={idx + 1}
+ rankColor={getRankColor(idx + 1)}
+ modelColor={getModelColor(model.model)}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+interface ModelRankCardProps {
+ model: ModelPerformance;
+ rank: number;
+ rankColor: string;
+ modelColor: string;
+}
+
+function ModelRankCard({ model, rank, rankColor, modelColor }: ModelRankCardProps) {
+ const isProfitable = model.total_pnl >= 0;
+
+ return (
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderLeft: `3px solid ${modelColor}`,
+ borderRadius: '2px',
+ padding: '8px 10px',
+ transition: 'all 0.2s'
+ }}>
+ {/* Header: Rank + Model Name */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: '8px'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <div style={{
+ width: '20px',
+ height: '20px',
+ borderRadius: '50%',
+ background: rank <= 3 ? `${rankColor}20` : 'transparent',
+ border: `2px solid ${rankColor}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: '10px',
+ fontWeight: '700',
+ color: rankColor
+ }}>
+ {rank}
+ </div>
+ <span style={{
+ color: modelColor,
+ fontSize: '10px',
+ fontWeight: '700',
+ fontFamily: '"IBM Plex Mono", monospace',
+ textTransform: 'uppercase'
+ }}>
+ {model.model.split(':')[1] || model.model}
+ </span>
+ </div>
+
+ {/* Total P&L Badge */}
+ <div style={{
+ background: isProfitable ? `${BLOOMBERG.GREEN}20` : `${BLOOMBERG.RED}20`,
+ border: `1px solid ${isProfitable ? BLOOMBERG.GREEN : BLOOMBERG.RED}`,
+ borderRadius: '2px',
+ padding: '2px 6px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '3px'
+ }}>
+ {isProfitable ? (
+ <TrendingUp size={10} color={BLOOMBERG.GREEN} />
+ ) : (
+ <TrendingDown size={10} color={BLOOMBERG.RED} />
+ )}
+ <span style={{
+ color: isProfitable ? BLOOMBERG.GREEN : BLOOMBERG.RED,
+ fontSize: '9px',
+ fontWeight: '700'
+ }}>
+ {isProfitable ? '+' : ''}{model.total_pnl.toFixed(2)}
+ </span>
+ </div>
+ </div>
+
+ {/* Stats Grid */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(3, 1fr)',
+ gap: '8px',
+ fontSize: '9px',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {/* Win Rate */}
+ <div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '7px', marginBottom: '2px' }}>WIN RATE</div>
+ <div style={{
+ color: model.win_rate >= 50 ? BLOOMBERG.GREEN : BLOOMBERG.RED,
+ fontWeight: '700',
+ fontSize: '10px'
+ }}>
+ {model.win_rate.toFixed(1)}%
+ </div>
+ </div>
+
+ {/* Total Trades */}
+ <div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '7px', marginBottom: '2px' }}>TRADES</div>
+ <div style={{ color: BLOOMBERG.CYAN, fontWeight: '700', fontSize: '10px' }}>
+ {model.total_trades}
+ </div>
+ </div>
+
+ {/* Daily P&L */}
+ <div>
+ <div style={{ color: BLOOMBERG.GRAY, fontSize: '7px', marginBottom: '2px' }}>TODAY</div>
+ <div style={{
+ color: model.daily_pnl >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED,
+ fontWeight: '700',
+ fontSize: '10px'
+ }}>
+ {model.daily_pnl >= 0 ? '+' : ''}{model.daily_pnl.toFixed(2)}
+ </div>
+ </div>
+ </div>
+
+ {/* Win/Loss Breakdown */}
+ <div style={{
+ marginTop: '8px',
+ paddingTop: '6px',
+ borderTop: `1px solid ${BLOOMBERG.BORDER}`,
+ display: 'flex',
+ justifyContent: 'space-between',
+ fontSize: '8px',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ <div style={{ display: 'flex', gap: '8px' }}>
+ <span style={{ color: BLOOMBERG.GRAY }}>W: </span>
+ <span style={{ color: BLOOMBERG.GREEN, fontWeight: '600' }}>{model.winning_trades}</span>
+ </div>
+ <div style={{ display: 'flex', gap: '8px' }}>
+ <span style={{ color: BLOOMBERG.GRAY }}>L: </span>
+ <span style={{ color: BLOOMBERG.RED, fontWeight: '600' }}>{model.losing_trades}</span>
+ </div>
+ <div style={{ display: 'flex', gap: '8px' }}>
+ <span style={{ color: BLOOMBERG.GRAY }}>POS: </span>
+ <span style={{ color: BLOOMBERG.YELLOW, fontWeight: '600' }}>{model.positions}</span>
+ </div>
+ </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.tsx
new file mode 100644
index 000000000..3b6f209e5
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/ai-agents/ModelChatPanel.tsx
@@ -0,0 +1,352 @@
+/**
+ * ModelChat Panel
+ *
+ * Real-time AI agent decision stream (Alpha Arena style)
+ * Shows what each model is thinking, deciding, and trading
+ */
+
+import React, { useState, useEffect, useRef } from 'react';
+import { Brain, TrendingUp, TrendingDown, Circle, Filter } from 'lucide-react';
+
+const BLOOMBERG = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ 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'
+};
+
+interface ModelDecision {
+ model: string;
+ timestamp: string;
+ content: string;
+ action?: 'long' | 'short' | 'hold' | 'close';
+ symbol?: string;
+ confidence?: number;
+ entry?: number;
+ target?: number;
+ stopLoss?: number;
+}
+
+interface ModelChatPanelProps {
+ teamId?: string;
+ refreshInterval?: number;
+}
+
+export function ModelChatPanel({ teamId, refreshInterval = 5000 }: ModelChatPanelProps) {
+ const [decisions, setDecisions] = useState<ModelDecision[]>([]);
+ const [selectedModel, setSelectedModel] = useState<string>('all');
+ const [isLoading, setIsLoading] = useState(false);
+ const [uniqueModels, setUniqueModels] = useState<string[]>([]);
+ const chatEndRef = useRef<HTMLDivElement>(null);
+
+ // Auto-scroll to bottom
+ const scrollToBottom = () => {
+ chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
+ };
+
+ useEffect(() => {
+ scrollToBottom();
+ }, [decisions]);
+
+ // Fetch recent decisions
+ const fetchDecisions = async () => {
+ try {
+ setIsLoading(true);
+ const { invoke } = await import('@tauri-apps/api/core');
+ const response = await invoke('agno_get_recent_decisions', { limit: 100 });
+ const data = JSON.parse(response as string);
+
+ if (data.success && data.data?.decisions) {
+ setDecisions(data.data.decisions);
+
+ // Extract unique models
+ const models = [...new Set(data.data.decisions.map((d: any) => d.model))];
+ setUniqueModels(models as string[]);
+ }
+ } catch (err) {
+ console.error('Failed to fetch decisions:', err);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ useEffect(() => {
+ fetchDecisions();
+
+ // Refresh periodically
+ const interval = setInterval(fetchDecisions, refreshInterval);
+ return () => clearInterval(interval);
+ }, [teamId, refreshInterval]);
+
+ // Filter decisions by model
+ const filteredDecisions = selectedModel === 'all'
+ ? decisions
+ : decisions.filter(d => d.model === selectedModel);
+
+ const getModelColor = (model: string) => {
+ const colors = [BLOOMBERG.ORANGE, BLOOMBERG.CYAN, BLOOMBERG.GREEN, BLOOMBERG.PURPLE, BLOOMBERG.YELLOW];
+ const hash = model.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
+ return colors[hash % colors.length];
+ };
+
+ const getActionColor = (action?: string) => {
+ switch (action) {
+ case 'long': return BLOOMBERG.GREEN;
+ case 'short': return BLOOMBERG.RED;
+ case 'close': return BLOOMBERG.ORANGE;
+ default: return BLOOMBERG.GRAY;
+ }
+ };
+
+ const formatTimestamp = (timestamp: string) => {
+ const date = new Date(timestamp);
+ const now = new Date();
+ const diffSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
+
+ if (diffSeconds < 60) return `${diffSeconds}s ago`;
+ if (diffSeconds < 3600) return `${Math.floor(diffSeconds / 60)}m ago`;
+ return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
+ };
+
+ return (
+ <div style={{
+ height: '100%',
+ background: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '2px',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ {/* 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' }}>
+ <Brain size={14} color={BLOOMBERG.ORANGE} />
+ <span style={{
+ color: BLOOMBERG.WHITE,
+ fontSize: '11px',
+ fontWeight: '600',
+ letterSpacing: '0.5px'
+ }}>
+ MODELCHAT
+ </span>
+ {isLoading && (
+ <Circle size={8} color={BLOOMBERG.ORANGE} style={{ animation: 'pulse 2s infinite' }} />
+ )}
+ </div>
+
+ {/* Model Filter */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <Filter size={12} color={BLOOMBERG.GRAY} />
+ <select
+ value={selectedModel}
+ onChange={(e) => setSelectedModel(e.target.value)}
+ style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ color: BLOOMBERG.WHITE,
+ padding: '3px 6px',
+ borderRadius: '2px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}
+ >
+ <option value="all">ALL MODELS</option>
+ {uniqueModels.map(model => (
+ <option key={model} value={model}>{model}</option>
+ ))}
+ </select>
+ </div>
+ </div>
+
+ {/* Chat Stream */}
+ <div style={{
+ flex: 1,
+ overflow: 'auto',
+ padding: '10px',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '8px'
+ }}>
+ {filteredDecisions.length === 0 ? (
+ <div style={{
+ textAlign: 'center',
+ color: BLOOMBERG.GRAY,
+ fontSize: '10px',
+ marginTop: '40px'
+ }}>
+ {isLoading ? 'Loading decisions...' : 'No decisions yet. Start a competition to see model reasoning.'}
+ </div>
+ ) : (
+ filteredDecisions.map((decision, idx) => (
+ <DecisionCard
+ key={`${decision.model}-${decision.timestamp}-${idx}`}
+ decision={decision}
+ modelColor={getModelColor(decision.model)}
+ actionColor={getActionColor(decision.action)}
+ formatTimestamp={formatTimestamp}
+ />
+ ))
+ )}
+ <div ref={chatEndRef} />
+ </div>
+ </div>
+ );
+}
+
+interface DecisionCardProps {
+ decision: ModelDecision;
+ modelColor: string;
+ actionColor: string;
+ formatTimestamp: (timestamp: string) => string;
+}
+
+function DecisionCard({ decision, modelColor, actionColor, formatTimestamp }: DecisionCardProps) {
+ return (
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderLeft: `3px solid ${modelColor}`,
+ borderRadius: '2px',
+ padding: '8px 10px'
+ }}>
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: '6px'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <div style={{
+ width: '6px',
+ height: '6px',
+ borderRadius: '50%',
+ background: modelColor
+ }} />
+ <span style={{
+ color: modelColor,
+ fontSize: '10px',
+ fontWeight: '700',
+ fontFamily: '"IBM Plex Mono", monospace',
+ textTransform: 'uppercase'
+ }}>
+ {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'
+ }}>
+ {decision.action.toUpperCase()}
+ </span>
+ </div>
+ )}
+
+ {decision.symbol && (
+ <span style={{
+ color: BLOOMBERG.GRAY,
+ fontSize: '8px',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {decision.symbol}
+ </span>
+ )}
+ </div>
+
+ <span style={{
+ color: BLOOMBERG.MUTED,
+ fontSize: '8px',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {formatTimestamp(decision.timestamp)}
+ </span>
+ </div>
+
+ {/* Content */}
+ <div style={{
+ color: BLOOMBERG.WHITE,
+ fontSize: '10px',
+ lineHeight: '1.5',
+ fontFamily: '"IBM Plex Mono", monospace',
+ whiteSpace: 'pre-wrap'
+ }}>
+ {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>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx b/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx
new file mode 100644
index 000000000..b51270938
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/ProChartWithToolkit.tsx
@@ -0,0 +1,553 @@
+/**
+ * Professional Chart with Complete Trading Toolkit
+ *
+ * Ready-to-use chart component with full TradingView-style functionality
+ */
+
+import React, { useEffect, useRef, useState, useCallback } from 'react';
+import { createChart, ColorType, CandlestickSeries, HistogramSeries } from 'lightweight-charts';
+import type { IChartApi, CandlestickData, Time, ISeriesApi, MouseEventParams } from 'lightweight-charts';
+import {
+ PluginManager,
+ TooltipPlugin,
+ TradingToolkitPlugin,
+ DrawingTool,
+ PositionType,
+ ChartPoint
+} from './plugins';
+import { ToolkitToolbar } from './ToolkitToolbar';
+
+interface ProChartProps {
+ data: Array<{
+ time: number;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ volume: number;
+ }>;
+ symbol?: string;
+ height?: number;
+ showVolume?: boolean;
+ showToolbar?: boolean;
+ showHeader?: boolean; // Option to hide the symbol/OHLC header
+ onToolChange?: (tool: DrawingTool | null) => void;
+}
+
+export function ProChartWithToolkit({
+ data,
+ symbol = 'CHART',
+ height = 600,
+ showVolume = true,
+ showToolbar = true,
+ showHeader = true,
+ onToolChange,
+}: ProChartProps) {
+ const chartContainerRef = useRef<HTMLDivElement>(null);
+ const chartRef = useRef<IChartApi | null>(null);
+ const candlestickSeriesRef = useRef<ISeriesApi<'Candlestick', Time> | null>(null);
+ const volumeSeriesRef = useRef<any>(null);
+ const pluginManagerRef = useRef<PluginManager | null>(null);
+ const toolkitRef = useRef<TradingToolkitPlugin | null>(null);
+ const activeToolRef = useRef<DrawingTool | null>(null); // Ref to avoid stale closures
+
+ const [activeTool, setActiveTool] = useState<DrawingTool | null>(null);
+ const [isReady, setIsReady] = useState(false);
+ const [cursorPosition, setCursorPosition] = useState<{ time: Time | null; price: number | null } | null>(null);
+ const [cursorStyle, setCursorStyle] = useState<string>('default');
+
+ // Initialize chart
+ useEffect(() => {
+ if (!chartContainerRef.current) return;
+
+ const chart = createChart(chartContainerRef.current, {
+ width: chartContainerRef.current.clientWidth,
+ height: height,
+ layout: {
+ background: { type: ColorType.Solid, color: '#0a0a0a' },
+ textColor: '#d1d5db',
+ fontSize: 11,
+ },
+ handleScroll: {
+ vertTouchDrag: true,
+ },
+ handleScale: {
+ axisPressedMouseMove: {
+ time: true,
+ price: true,
+ },
+ },
+ grid: {
+ vertLines: { color: '#1f1f1f' },
+ horzLines: { color: '#1f1f1f' },
+ },
+ crosshair: {
+ mode: 0, // Normal mode (0) allows free cursor movement, Magnet mode (1) snaps to candles
+ vertLine: {
+ width: 1,
+ color: '#758696',
+ style: 0,
+ },
+ horzLine: {
+ width: 1,
+ color: '#758696',
+ style: 0,
+ },
+ },
+ rightPriceScale: {
+ borderColor: '#2a2a2a',
+ scaleMargins: {
+ top: 0.1,
+ bottom: showVolume ? 0.25 : 0.1,
+ },
+ },
+ timeScale: {
+ borderColor: '#2a2a2a',
+ timeVisible: true,
+ secondsVisible: false,
+ },
+ });
+
+ chartRef.current = chart;
+
+ // Create candlestick series
+ const candlestickSeries = chart.addSeries(CandlestickSeries, {
+ upColor: '#10b981',
+ downColor: '#ef4444',
+ borderUpColor: '#10b981',
+ borderDownColor: '#ef4444',
+ wickUpColor: '#10b981',
+ wickDownColor: '#ef4444',
+ });
+
+ candlestickSeriesRef.current = candlestickSeries as any;
+
+ // Create volume series
+ if (showVolume) {
+ const volumeSeries = chart.addSeries(HistogramSeries, {
+ color: '#6b7280',
+ priceFormat: {
+ type: 'volume',
+ },
+ priceScaleId: '',
+ });
+
+ volumeSeries.priceScale().applyOptions({
+ scaleMargins: {
+ top: 0.8,
+ bottom: 0,
+ },
+ });
+
+ volumeSeriesRef.current = volumeSeries;
+ }
+
+ // Initialize plugin system
+ const pluginManager = new PluginManager(chart, candlestickSeries as any);
+ pluginManagerRef.current = pluginManager;
+
+ // Add tooltip
+ const tooltip = new TooltipPlugin({
+ showOHLC: true,
+ showVolume: showVolume,
+ });
+ pluginManager.register(tooltip);
+
+ // Add trading toolkit
+ const toolkit = new TradingToolkitPlugin();
+ pluginManager.register(toolkit);
+ toolkitRef.current = toolkit;
+
+ // Listen for tool deactivation from the plugin
+ toolkit.setOnToolDeactivated(() => {
+ setActiveTool(null);
+ activeToolRef.current = null;
+ onToolChange?.(null);
+ });
+
+ // Chart initialized with plugins
+
+ // Handle chart clicks for drawing
+ chart.subscribeClick((param: MouseEventParams) => {
+ handleChartClick(param);
+ });
+
+ // Handle mouse move for cursor tracking, hover, and dragging
+ chart.subscribeCrosshairMove((param: MouseEventParams) => {
+ handleMouseMove(param);
+ });
+
+ // Handle keyboard shortcuts
+ const handleKeyDown = (e: KeyboardEvent) => {
+ // Delete: Remove last drawing or selected drawing
+ if (e.key === 'Delete' || e.key === 'Backspace') {
+ if (toolkitRef.current && !activeTool) {
+ e.preventDefault();
+ const selectedId = toolkitRef.current.getSelectedDrawingId();
+ if (selectedId) {
+ // Delete selected drawing
+ const drawings = toolkitRef.current.getDrawings();
+ const drawing = drawings.find(d => d.id === selectedId);
+ if (drawing) {
+ toolkitRef.current.removeDrawing(selectedId);
+ toolkitRef.current.selectDrawing(null);
+ }
+ } else {
+ // Delete last drawing
+ toolkitRef.current.deleteLastDrawing();
+ }
+ }
+ }
+ // Escape: Deactivate current tool or deselect drawing
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ if (activeTool) {
+ handleToolSelect(null);
+ } else if (toolkitRef.current) {
+ toolkitRef.current.selectDrawing(null);
+ }
+ }
+ };
+
+ // Handle mouse up to end dragging
+ const handleMouseUp = () => {
+ if (toolkitRef.current) {
+ toolkitRef.current.handleMouseUp();
+ }
+ };
+
+ window.addEventListener('keydown', handleKeyDown);
+ window.addEventListener('mouseup', handleMouseUp);
+
+ // Handle resize
+ const handleResize = () => {
+ if (chartContainerRef.current && chartRef.current) {
+ chartRef.current.resize(chartContainerRef.current.clientWidth, height, true);
+ }
+ };
+
+ window.addEventListener('resize', handleResize);
+
+ const resizeObserver = new ResizeObserver(handleResize);
+ if (chartContainerRef.current) {
+ resizeObserver.observe(chartContainerRef.current);
+ }
+
+ setIsReady(true);
+
+ return () => {
+ window.removeEventListener('resize', handleResize);
+ window.removeEventListener('keydown', handleKeyDown);
+ window.removeEventListener('mouseup', handleMouseUp);
+ resizeObserver.disconnect();
+ pluginManager.destroy();
+ chart.remove();
+ };
+ }, [height, showVolume]);
+
+ // Update chart data
+ useEffect(() => {
+ if (!isReady || !candlestickSeriesRef.current || data.length === 0) return;
+
+ const candleData: CandlestickData[] = data.map((candle) => {
+ let timestamp = candle.time;
+ if (timestamp > 10000000000) {
+ timestamp = Math.floor(timestamp / 1000);
+ }
+
+ return {
+ time: timestamp as Time,
+ open: candle.open,
+ high: candle.high,
+ low: candle.low,
+ close: candle.close,
+ };
+ });
+
+ candlestickSeriesRef.current.setData(candleData);
+
+ if (showVolume && volumeSeriesRef.current) {
+ const volumeData = data.map((candle) => {
+ let timestamp = candle.time;
+ if (timestamp > 10000000000) {
+ timestamp = Math.floor(timestamp / 1000);
+ }
+
+ return {
+ time: timestamp as Time,
+ value: candle.volume,
+ color: candle.close >= candle.open ? '#10b98144' : '#ef444444',
+ };
+ });
+
+ volumeSeriesRef.current.setData(volumeData);
+ }
+
+ chartRef.current?.timeScale().fitContent();
+ }, [data, isReady, showVolume]);
+
+ // Handle mouse move for cursor tracking, hover, and dragging
+ const handleMouseMove = useCallback((param: MouseEventParams) => {
+ if (!candlestickSeriesRef.current || !toolkitRef.current) return;
+
+ // Update cursor position for UI display
+ if (param.time && param.point) {
+ const price = candlestickSeriesRef.current.coordinateToPrice(param.point.y);
+ if (price !== undefined && price !== null) {
+ setCursorPosition({ time: param.time as Time, price });
+
+ // Handle dragging and hover
+ const point: ChartPoint<Time> = {
+ time: param.time as Time,
+ price: price,
+ };
+ toolkitRef.current.handleMouseMove(point, param.point.x, param.point.y);
+
+ // Update cursor based on context
+ if (activeToolRef.current) {
+ setCursorStyle('crosshair');
+ } else {
+ // Check if hovering over a drawing
+ const hoveredDrawing = toolkitRef.current.getDrawings().find(d =>
+ toolkitRef.current!.findDrawingAtPoint &&
+ d.id === (toolkitRef.current as any)._hoveredDrawingId
+ );
+
+ if (hoveredDrawing) {
+ setCursorStyle('move');
+ } else {
+ setCursorStyle('default');
+ }
+ }
+ }
+ } else {
+ setCursorPosition(null);
+ }
+ }, []);
+
+ // Handle chart click for drawing and selection
+ const handleChartClick = useCallback(
+ (param: MouseEventParams) => {
+ if (!toolkitRef.current) return;
+
+ // Try to get coordinates from the click
+ let time: Time | null = null;
+ let price: number | null = null;
+ let pixelX = 0;
+ let pixelY = 0;
+
+ // Method 1: Use param.time and param.point if available
+ if (param.time && param.point) {
+ time = param.time as Time;
+ price = candlestickSeriesRef.current?.coordinateToPrice(param.point.y) ?? null;
+ pixelX = param.point.x;
+ pixelY = param.point.y;
+ }
+ // Method 2: Fallback - use logical coordinates directly from the chart
+ else if (param.point && chartRef.current && candlestickSeriesRef.current) {
+ time = chartRef.current.timeScale().coordinateToTime(param.point.x) as Time | null;
+ price = candlestickSeriesRef.current.coordinateToPrice(param.point.y);
+ pixelX = param.point.x;
+ pixelY = param.point.y;
+ }
+
+ if (time === null || price === null || price === undefined) {
+ return;
+ }
+
+ const point: ChartPoint<Time> = { time, price };
+ const currentActiveTool = activeToolRef.current;
+
+ // If a drawing tool is active, create drawing
+ if (currentActiveTool && toolkitRef.current.getCurrentTool()) {
+ toolkitRef.current.handleClick(point);
+
+ // Force chart update
+ if (chartRef.current) {
+ chartRef.current.timeScale().scrollToPosition(0, false);
+ }
+ } else {
+ // No tool active - handle selection/dragging
+ const handled = toolkitRef.current.handleMouseDown(point, pixelX, pixelY);
+
+ if (!handled) {
+ // Click on empty space - finish any drag operation
+ toolkitRef.current.handleMouseUp();
+ }
+ }
+ },
+ []
+ );
+
+ // Tool selection handler
+ const handleToolSelect = useCallback(
+ (tool: DrawingTool | null) => {
+ // Update both state and ref to avoid stale closures
+ setActiveTool(tool);
+ activeToolRef.current = tool;
+
+ if (tool && toolkitRef.current) {
+ toolkitRef.current.activateTool(tool);
+ } else if (!tool && toolkitRef.current) {
+ toolkitRef.current.deactivateTool();
+ }
+
+ onToolChange?.(tool);
+ },
+ [onToolChange, activeTool]
+ );
+
+ // Public API for adding positions programmatically
+ const addLongPosition = useCallback(
+ (entryTime: Time, entryPrice: number, label?: string) => {
+ if (toolkitRef.current) {
+ return toolkitRef.current.addLongPosition(entryTime, entryPrice, undefined, undefined, {
+ label,
+ });
+ }
+ return '';
+ },
+ []
+ );
+
+ const addShortPosition = useCallback(
+ (entryTime: Time, entryPrice: number, label?: string) => {
+ if (toolkitRef.current) {
+ return toolkitRef.current.addShortPosition(entryTime, entryPrice, undefined, undefined, {
+ label,
+ });
+ }
+ return '';
+ },
+ []
+ );
+
+ // TODO: Expose API via ref using forwardRef if needed
+ // For now, the component is self-contained with toolbar UI
+
+ return (
+ <div
+ style={{
+ display: 'flex',
+ flexDirection: 'column',
+ height: '100%',
+ width: '100%',
+ backgroundColor: '#0a0a0a',
+ position: 'relative',
+ }}
+ >
+ {/* Header with symbol and OHLC data - Bloomberg style */}
+ {showHeader && (
+ <div
+ style={{
+ padding: '4px 12px',
+ backgroundColor: '#000000',
+ borderBottom: '1px solid #2A2A2A',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ height: '28px',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
+ <span
+ style={{
+ fontSize: '11px',
+ fontWeight: 600,
+ color: '#FF8800',
+ fontFamily: 'monospace',
+ letterSpacing: '0.5px',
+ }}
+ >
+ {symbol}
+ </span>
+ {data.length > 0 && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', fontSize: '10px', fontFamily: 'monospace' }}>
+ <span style={{ color: '#787878' }}>O</span>
+ <span style={{ color: '#FFFFFF' }}>{data[data.length - 1].open.toFixed(2)}</span>
+ <span style={{ color: '#787878' }}>H</span>
+ <span style={{ color: '#FFFFFF' }}>{data[data.length - 1].high.toFixed(2)}</span>
+ <span style={{ color: '#787878' }}>L</span>
+ <span style={{ color: '#FFFFFF' }}>{data[data.length - 1].low.toFixed(2)}</span>
+ <span style={{ color: '#787878' }}>C</span>
+ <span
+ style={{
+ color:
+ data[data.length - 1].close >= data[data.length - 1].open
+ ? '#00D66F'
+ : '#FF3B3B',
+ fontWeight: 600,
+ }}
+ >
+ {data[data.length - 1].close.toFixed(2)}
+ </span>
+ </div>
+ )}
+ </div>
+
+ <div
+ style={{
+ fontSize: '9px',
+ color: '#787878',
+ fontFamily: 'monospace',
+ }}
+ >
+ {data.length} BARS
+ </div>
+ </div>
+ )}
+
+ {/* Toolbar */}
+ {showToolbar && (
+ <ToolkitToolbar
+ toolkit={toolkitRef.current}
+ onToolSelect={handleToolSelect}
+ activeTool={activeTool}
+ />
+ )}
+
+ {/* Chart container */}
+ <div
+ style={{
+ flex: 1,
+ position: 'relative',
+ minHeight: 0,
+ overflow: 'hidden',
+ }}
+ >
+ <div
+ ref={chartContainerRef}
+ style={{
+ width: '100%',
+ height: '100%',
+ position: 'relative',
+ cursor: cursorStyle,
+ }}
+ />
+
+ {/* Help text when tool is active */}
+ {activeTool && (
+ <div
+ style={{
+ position: 'absolute',
+ bottom: '10px',
+ left: '50%',
+ transform: 'translateX(-50%)',
+ backgroundColor: 'rgba(0, 0, 0, 0.95)',
+ border: '1px solid #2A2A2A',
+ borderRadius: '4px',
+ padding: '6px 14px',
+ fontSize: '10px',
+ color: '#FFFFFF',
+ zIndex: 100,
+ pointerEvents: 'none',
+ fontFamily: 'monospace',
+ }}
+ >
+ Click on the chart to draw {activeTool.replace(/_/g, ' ')}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/ToolkitToolbar.tsx b/fincept-terminal-desktop/src/components/tabs/trading/charts/ToolkitToolbar.tsx
new file mode 100644
index 000000000..7959d0ff7
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/ToolkitToolbar.tsx
@@ -0,0 +1,516 @@
+/**
+ * Trading Toolkit Toolbar
+ *
+ * Professional toolbar UI for accessing all drawing tools, similar to TradingView
+ */
+
+import React, { useState } from 'react';
+import {
+ TrendingUp,
+ Minus,
+ Circle,
+ Square,
+ Triangle,
+ Type,
+ ArrowUpRight,
+ GitBranch,
+ Maximize2,
+ Ruler,
+ Target,
+ ArrowUp,
+ ArrowDown,
+ StopCircle,
+ DollarSign,
+ Settings,
+ Trash2,
+ Undo2,
+ Lock,
+ Unlock,
+ Eye,
+ EyeOff,
+} from 'lucide-react';
+import { DrawingTool, PositionType, TradingToolkitPlugin } from './plugins';
+
+interface ToolkitToolbarProps {
+ toolkit: TradingToolkitPlugin | null;
+ onToolSelect?: (tool: DrawingTool) => void;
+ activeTool: DrawingTool | null;
+}
+
+interface ToolGroup {
+ name: string;
+ icon: React.ReactNode;
+ tools: ToolItem[];
+}
+
+interface ToolItem {
+ id: DrawingTool;
+ name: string;
+ icon: React.ReactNode;
+ shortcut?: string;
+}
+
+export function ToolkitToolbar({ toolkit, onToolSelect, activeTool }: ToolkitToolbarProps) {
+ const [activeGroup, setActiveGroup] = useState<string | null>(null);
+ const [showSettings, setShowSettings] = useState(false);
+
+ const toolGroups: ToolGroup[] = [
+ {
+ name: 'Lines',
+ icon: <TrendingUp size={16} />,
+ tools: [
+ {
+ id: DrawingTool.TREND_LINE,
+ name: 'Trend Line',
+ icon: <TrendingUp size={14} />,
+ shortcut: 'T',
+ },
+ {
+ id: DrawingTool.HORIZONTAL_LINE,
+ name: 'Horizontal Line',
+ icon: <Minus size={14} />,
+ shortcut: 'H',
+ },
+ {
+ id: DrawingTool.VERTICAL_LINE,
+ name: 'Vertical Line',
+ icon: <Minus size={14} style={{ transform: 'rotate(90deg)' }} />,
+ shortcut: 'V',
+ },
+ {
+ id: DrawingTool.RAY,
+ name: 'Ray',
+ icon: <ArrowUpRight size={14} />,
+ },
+ ],
+ },
+ {
+ name: 'Channels',
+ icon: <GitBranch size={16} style={{ transform: 'rotate(90deg)' }} />,
+ tools: [
+ {
+ id: DrawingTool.PARALLEL_CHANNEL,
+ name: 'Parallel Channel',
+ icon: <GitBranch size={14} style={{ transform: 'rotate(90deg)' }} />,
+ },
+ {
+ id: DrawingTool.REGRESSION_CHANNEL,
+ name: 'Regression Channel',
+ icon: <GitBranch size={14} />,
+ },
+ {
+ id: DrawingTool.PITCHFORK,
+ name: "Andrew's Pitchfork",
+ icon: <GitBranch size={14} />,
+ },
+ ],
+ },
+ {
+ name: 'Shapes',
+ icon: <Square size={16} />,
+ tools: [
+ {
+ id: DrawingTool.RECTANGLE,
+ name: 'Rectangle',
+ icon: <Square size={14} />,
+ shortcut: 'R',
+ },
+ {
+ id: DrawingTool.ELLIPSE,
+ name: 'Ellipse',
+ icon: <Circle size={14} />,
+ shortcut: 'E',
+ },
+ {
+ id: DrawingTool.TRIANGLE,
+ name: 'Triangle',
+ icon: <Triangle size={14} />,
+ },
+ ],
+ },
+ {
+ name: 'Fibonacci',
+ icon: <Ruler size={16} />,
+ tools: [
+ {
+ id: DrawingTool.FIBO_RETRACEMENT,
+ name: 'Fibonacci Retracement',
+ icon: <Ruler size={14} />,
+ shortcut: 'F',
+ },
+ {
+ id: DrawingTool.FIBO_EXTENSION,
+ name: 'Fibonacci Extension',
+ icon: <Ruler size={14} />,
+ },
+ {
+ id: DrawingTool.FIBO_FAN,
+ name: 'Fibonacci Fan',
+ icon: <Ruler size={14} />,
+ },
+ {
+ id: DrawingTool.FIBO_CIRCLE,
+ name: 'Fibonacci Circle',
+ icon: <Circle size={14} />,
+ },
+ ],
+ },
+ {
+ name: 'Positions',
+ icon: <Target size={16} />,
+ tools: [
+ {
+ id: DrawingTool.LONG_POSITION,
+ name: 'Long Position',
+ icon: <ArrowUp size={14} />,
+ shortcut: 'L',
+ },
+ {
+ id: DrawingTool.SHORT_POSITION,
+ name: 'Short Position',
+ icon: <ArrowDown size={14} />,
+ shortcut: 'S',
+ },
+ {
+ id: DrawingTool.STOP_LOSS,
+ name: 'Stop Loss',
+ icon: <StopCircle size={14} />,
+ },
+ {
+ id: DrawingTool.TAKE_PROFIT,
+ name: 'Take Profit',
+ icon: <DollarSign size={14} />,
+ },
+ ],
+ },
+ {
+ name: 'Annotations',
+ icon: <Type size={16} />,
+ tools: [
+ {
+ id: DrawingTool.TEXT,
+ name: 'Text',
+ icon: <Type size={14} />,
+ shortcut: 'A',
+ },
+ {
+ id: DrawingTool.ARROW,
+ name: 'Arrow',
+ icon: <ArrowUpRight size={14} />,
+ },
+ {
+ id: DrawingTool.CALLOUT,
+ name: 'Callout',
+ icon: <Type size={14} />,
+ },
+ ],
+ },
+ {
+ name: 'Measure',
+ icon: <Ruler size={16} />,
+ tools: [
+ {
+ id: DrawingTool.MEASURE,
+ name: 'Price & Date Range',
+ icon: <Ruler size={14} />,
+ },
+ {
+ id: DrawingTool.ANGLE,
+ name: 'Angle',
+ icon: <Ruler size={14} />,
+ },
+ ],
+ },
+ ];
+
+ const handleToolSelect = (tool: DrawingTool) => {
+ console.log('[ToolkitToolbar] Tool selected:', tool, 'hasToolkit:', !!toolkit);
+
+ if (toolkit) {
+ console.log('[ToolkitToolbar] Activating tool in toolkit plugin');
+ toolkit.activateTool(tool);
+ }
+
+ console.log('[ToolkitToolbar] Calling onToolSelect callback');
+ onToolSelect?.(tool);
+ setActiveGroup(null);
+ };
+
+ const handleClearAll = () => {
+ if (toolkit && confirm('Clear all drawings and positions?')) {
+ toolkit.clearAll();
+ }
+ };
+
+ const handleClearDrawings = () => {
+ if (toolkit && confirm('Clear all drawings?')) {
+ toolkit.clearDrawings();
+ }
+ };
+
+ const handleDeleteLast = () => {
+ if (toolkit) {
+ toolkit.deleteLastDrawing();
+ }
+ };
+
+ const stats = toolkit
+ ? {
+ drawings: toolkit.getDrawings().length,
+ positions: toolkit.getPositions().length,
+ }
+ : { drawings: 0, positions: 0 };
+
+ return (
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ padding: '4px 12px',
+ backgroundColor: '#000000',
+ borderBottom: '1px solid #2A2A2A',
+ fontSize: '10px',
+ position: 'relative',
+ height: '28px',
+ }}
+ >
+ {/* Tool Groups */}
+ {toolGroups.map((group) => (
+ <div key={group.name} style={{ position: 'relative' }}>
+ <button
+ onClick={() => setActiveGroup(activeGroup === group.name ? null : group.name)}
+ title={group.name}
+ style={{
+ padding: '6px 8px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ border: 'none',
+ borderRadius: '3px',
+ backgroundColor: activeGroup === group.name ? '#FF8800' : '#1A1A1A',
+ color: '#ffffff',
+ cursor: 'pointer',
+ transition: 'all 0.2s',
+ }}
+ onMouseEnter={(e) => {
+ if (activeGroup !== group.name) {
+ e.currentTarget.style.backgroundColor = '#2A2A2A';
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (activeGroup !== group.name) {
+ e.currentTarget.style.backgroundColor = '#1A1A1A';
+ }
+ }}
+ >
+ {group.icon}
+ <span style={{ fontSize: '10px' }}>{group.name}</span>
+ </button>
+
+ {/* Dropdown menu */}
+ {activeGroup === group.name && (
+ <div
+ style={{
+ position: 'absolute',
+ top: '100%',
+ left: 0,
+ marginTop: '4px',
+ backgroundColor: '#0F0F0F',
+ border: '1px solid #2A2A2A',
+ borderRadius: '4px',
+ padding: '4px',
+ minWidth: '200px',
+ zIndex: 1000,
+ boxShadow: '0 4px 12px rgba(0, 0, 0, 0.5)',
+ }}
+ >
+ {group.tools.map((tool) => (
+ <button
+ key={tool.id}
+ onClick={() => handleToolSelect(tool.id)}
+ style={{
+ width: '100%',
+ padding: '8px 10px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: '8px',
+ border: 'none',
+ borderRadius: '3px',
+ backgroundColor: activeTool === tool.id ? '#FF8800' : 'transparent',
+ color: '#ffffff',
+ cursor: 'pointer',
+ textAlign: 'left',
+ fontSize: '11px',
+ transition: 'all 0.15s',
+ }}
+ onMouseEnter={(e) => {
+ if (activeTool !== tool.id) {
+ e.currentTarget.style.backgroundColor = '#1A1A1A';
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (activeTool !== tool.id) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ }
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ {tool.icon}
+ <span>{tool.name}</span>
+ </div>
+ {tool.shortcut && (
+ <span
+ style={{
+ fontSize: '9px',
+ color: '#6b7280',
+ backgroundColor: '#0a0a0a',
+ padding: '2px 6px',
+ borderRadius: '2px',
+ }}
+ >
+ {tool.shortcut}
+ </span>
+ )}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ ))}
+
+ {/* Divider */}
+ <div
+ style={{
+ width: '1px',
+ height: '20px',
+ backgroundColor: '#2a2a2a',
+ margin: '0 4px',
+ }}
+ />
+
+ {/* Quick Actions */}
+ <button
+ onClick={handleDeleteLast}
+ title="Undo Last Drawing (Delete/Backspace)"
+ disabled={stats.drawings === 0}
+ style={{
+ padding: '6px 8px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ border: 'none',
+ borderRadius: '3px',
+ backgroundColor: stats.drawings === 0 ? '#0F0F0F' : '#1A1A1A',
+ color: stats.drawings === 0 ? '#4A4A4A' : '#ffffff',
+ cursor: stats.drawings === 0 ? 'not-allowed' : 'pointer',
+ transition: 'all 0.2s',
+ opacity: stats.drawings === 0 ? 0.5 : 1,
+ }}
+ onMouseEnter={(e) => {
+ if (stats.drawings > 0) {
+ e.currentTarget.style.backgroundColor = '#2A2A2A';
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (stats.drawings > 0) {
+ e.currentTarget.style.backgroundColor = '#1A1A1A';
+ }
+ }}
+ >
+ <Undo2 size={14} />
+ </button>
+
+ <button
+ onClick={handleClearDrawings}
+ title="Clear All Drawings"
+ disabled={stats.drawings === 0}
+ style={{
+ padding: '6px 8px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ border: 'none',
+ borderRadius: '3px',
+ backgroundColor: stats.drawings === 0 ? '#0F0F0F' : '#1A1A1A',
+ color: stats.drawings === 0 ? '#4A4A4A' : '#ffffff',
+ cursor: stats.drawings === 0 ? 'not-allowed' : 'pointer',
+ transition: 'all 0.2s',
+ opacity: stats.drawings === 0 ? 0.5 : 1,
+ }}
+ onMouseEnter={(e) => {
+ if (stats.drawings > 0) {
+ e.currentTarget.style.backgroundColor = '#2A2A2A';
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (stats.drawings > 0) {
+ e.currentTarget.style.backgroundColor = '#1A1A1A';
+ }
+ }}
+ >
+ <Trash2 size={14} />
+ </button>
+
+ {/* Stats */}
+ <div
+ style={{
+ marginLeft: 'auto',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ fontSize: '10px',
+ color: '#787878',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <TrendingUp size={12} />
+ <span>{stats.drawings} drawings</span>
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <Target size={12} />
+ <span>{stats.positions} positions</span>
+ </div>
+ </div>
+
+ {/* Active Tool Indicator */}
+ {activeTool && (
+ <div
+ style={{
+ padding: '4px 10px',
+ backgroundColor: '#FF8800',
+ color: '#000000',
+ borderRadius: '3px',
+ fontSize: '10px',
+ fontWeight: 600,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ }}
+ >
+ <span>Active:</span>
+ <span>{activeTool.replace(/_/g, ' ').toUpperCase()}</span>
+ <button
+ onClick={() => {
+ toolkit?.deactivateTool();
+ onToolSelect?.(null as any);
+ }}
+ style={{
+ background: 'none',
+ border: 'none',
+ color: '#000000',
+ cursor: 'pointer',
+ padding: 0,
+ marginLeft: '4px',
+ fontSize: '14px',
+ fontWeight: 700,
+ }}
+ >
+ ✕
+ </button>
+ </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.tsx
index f937f26bc..6659a6392 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChart.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChart.tsx
@@ -1,13 +1,12 @@
/**
- * TradingChart - TradingView-style candlestick chart
- * Uses lightweight-charts library for high-performance rendering
+ * TradingChart - TradingView-style candlestick chart with drawing tools
+ * Uses ProChartWithToolkit for professional drawing capabilities
*/
-import React, { useEffect, useRef, useState } from 'react';
-import { createChart, ColorType, CandlestickSeries, HistogramSeries } from 'lightweight-charts';
-import type { IChartApi, CandlestickData, Time } from 'lightweight-charts';
+import React, { useState } from 'react';
+import { ProChartWithToolkit } from './ProChartWithToolkit';
import { useOHLCV } from '../hooks/useMarketData';
-import type { Timeframe, OHLCV } from '../types';
+import type { Timeframe } from '../types';
interface TradingChartProps {
symbol: string;
@@ -22,177 +21,179 @@ export function TradingChart({
height = 500,
showVolume = true
}: TradingChartProps) {
- const chartContainerRef = useRef<HTMLDivElement>(null);
- const chartRef = useRef<IChartApi | null>(null);
- const candlestickSeriesRef = useRef<any>(null);
- const volumeSeriesRef = useRef<any>(null);
-
- const { ohlcv, isLoading, error } = useOHLCV(symbol, timeframe, 200);
const [selectedTimeframe, setSelectedTimeframe] = useState<Timeframe>(timeframe);
-
- // Initialize chart
- useEffect(() => {
- if (!chartContainerRef.current) return;
-
- const chart = createChart(chartContainerRef.current, {
- width: chartContainerRef.current.clientWidth,
- height,
- layout: {
- background: { type: ColorType.Solid, color: '#0a0a0a' },
- textColor: '#d1d5db',
- },
- grid: {
- vertLines: { color: '#1f1f1f' },
- horzLines: { color: '#1f1f1f' },
- },
- crosshair: {
- mode: 1,
- },
- rightPriceScale: {
- borderColor: '#2a2a2a',
- },
- timeScale: {
- borderColor: '#2a2a2a',
- timeVisible: true,
- secondsVisible: false,
- },
- });
-
- chartRef.current = chart;
-
- // Create candlestick series - v5 API: chart.addSeries(SeriesDefinition, options)
- const candlestickSeries = chart.addSeries(CandlestickSeries, {
- upColor: '#10b981',
- downColor: '#ef4444',
- borderUpColor: '#10b981',
- borderDownColor: '#ef4444',
- wickUpColor: '#10b981',
- wickDownColor: '#ef4444',
- });
-
- candlestickSeriesRef.current = candlestickSeries;
-
- // Create volume series
- if (showVolume) {
- const volumeSeries = chart.addSeries(HistogramSeries, {
- color: '#6b7280',
- priceFormat: {
- type: 'volume',
- },
- priceScaleId: '',
- });
-
- volumeSeries.priceScale().applyOptions({
- scaleMargins: {
- top: 0.8,
- bottom: 0,
- },
- });
-
- volumeSeriesRef.current = volumeSeries;
- }
-
- // Handle resize
- const handleResize = () => {
- if (chartContainerRef.current && chartRef.current) {
- chartRef.current.resize(
- chartContainerRef.current.clientWidth,
- height,
- true
- );
- }
- };
-
- window.addEventListener('resize', handleResize);
-
- return () => {
- window.removeEventListener('resize', handleResize);
- chart.remove();
- };
- }, [height, showVolume]);
-
- // Handle height changes
- useEffect(() => {
- if (chartRef.current && chartContainerRef.current) {
- chartRef.current.resize(
- chartContainerRef.current.clientWidth,
- height,
- true
- );
- }
- }, [height]);
-
- // Update chart data
- useEffect(() => {
- if (!ohlcv.length || !candlestickSeriesRef.current) return;
-
- // Convert OHLCV to candlestick data
- const candleData: CandlestickData[] = ohlcv.map((candle: OHLCV) => ({
- time: Math.floor(candle.timestamp / 1000) as any,
- open: candle.open,
- high: candle.high,
- low: candle.low,
- close: candle.close,
- }));
-
- candlestickSeriesRef.current.setData(candleData);
-
- // Update volume data
- if (showVolume && volumeSeriesRef.current) {
- const volumeData = ohlcv.map((candle: OHLCV) => ({
- time: Math.floor(candle.timestamp / 1000) as any,
- value: candle.volume,
- color: candle.close >= candle.open ? '#10b98144' : '#ef444444',
- }));
-
- volumeSeriesRef.current.setData(volumeData);
- }
-
- // Fit content
- chartRef.current?.timeScale().fitContent();
- }, [ohlcv, showVolume]);
+ const { ohlcv, isLoading, error } = useOHLCV(symbol, selectedTimeframe, 200);
const timeframes: Timeframe[] = ['1m', '5m', '15m', '1h', '4h', '1d'];
+ // Prepare data for ProChartWithToolkit
+ const chartData = ohlcv.map((candle) => ({
+ time: candle.timestamp > 10000000000 ? Math.floor(candle.timestamp / 1000) : candle.timestamp,
+ open: candle.open,
+ high: candle.high,
+ low: candle.low,
+ close: candle.close,
+ volume: candle.volume,
+ }));
+
return (
- <div className="flex flex-col gap-2">
- {/* Timeframe selector */}
- <div className="flex items-center gap-2 px-4">
- <span className="text-xs text-gray-400">TIMEFRAME:</span>
- <div className="flex gap-1">
- {timeframes.map((tf) => (
- <button
- key={tf}
- onClick={() => setSelectedTimeframe(tf)}
- className={`px-2 py-1 text-xs font-mono rounded transition-colors ${
- selectedTimeframe === tf
- ? 'bg-blue-600 text-white'
- : 'bg-gray-800 text-gray-400 hover:bg-gray-700'
- }`}
- >
- {tf}
- </button>
- ))}
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ height: '100%',
+ width: '100%',
+ position: 'relative'
+ }}>
+ {/* Timeframe selector with OHLC data - Bloomberg style */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '4px 12px',
+ flexShrink: 0,
+ backgroundColor: '#000000',
+ borderBottom: '1px solid #2A2A2A',
+ height: '28px'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <span style={{ fontSize: '10px', color: '#787878', fontWeight: 600, fontFamily: 'monospace' }}>TIMEFRAME:</span>
+ <div style={{ display: 'flex', gap: '3px' }}>
+ {timeframes.map((tf) => (
+ <button
+ key={tf}
+ onClick={() => setSelectedTimeframe(tf)}
+ style={{
+ padding: '3px 8px',
+ fontSize: '10px',
+ fontFamily: 'monospace',
+ borderRadius: '2px',
+ border: 'none',
+ cursor: 'pointer',
+ backgroundColor: selectedTimeframe === tf ? '#FF8800' : '#1A1A1A',
+ color: selectedTimeframe === tf ? '#000000' : '#787878',
+ fontWeight: selectedTimeframe === tf ? 600 : 400,
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ if (selectedTimeframe !== tf) {
+ e.currentTarget.style.backgroundColor = '#2A2A2A';
+ e.currentTarget.style.color = '#FFFFFF';
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (selectedTimeframe !== tf) {
+ e.currentTarget.style.backgroundColor = '#1A1A1A';
+ e.currentTarget.style.color = '#787878';
+ }
+ }}
+ >
+ {tf}
+ </button>
+ ))}
+ </div>
</div>
+
+ {/* OHLC Data */}
+ {!isLoading && !error && chartData.length > 0 && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '2px', fontSize: '10px', fontFamily: 'monospace' }}>
+ <span style={{ color: '#FF8800', fontWeight: 600, marginRight: '8px' }}>
+ {symbol} - {selectedTimeframe}
+ </span>
+ <span style={{ color: '#787878' }}>O</span>
+ <span style={{ color: '#FFFFFF', marginRight: '6px' }}>{chartData[chartData.length - 1].open.toFixed(2)}</span>
+ <span style={{ color: '#787878' }}>H</span>
+ <span style={{ color: '#FFFFFF', marginRight: '6px' }}>{chartData[chartData.length - 1].high.toFixed(2)}</span>
+ <span style={{ color: '#787878' }}>L</span>
+ <span style={{ color: '#FFFFFF', marginRight: '6px' }}>{chartData[chartData.length - 1].low.toFixed(2)}</span>
+ <span style={{ color: '#787878' }}>C</span>
+ <span
+ style={{
+ color: chartData[chartData.length - 1].close >= chartData[chartData.length - 1].open
+ ? '#00D66F'
+ : '#FF3B3B',
+ fontWeight: 600,
+ marginRight: '12px'
+ }}
+ >
+ {chartData[chartData.length - 1].close.toFixed(2)}
+ </span>
+ <span style={{ color: '#787878', fontSize: '9px' }}>{chartData.length} BARS</span>
+ </div>
+ </div>
+ )}
</div>
- {/* Chart container */}
- <div className="relative">
+ {/* Chart container with absolute positioning for perfect fit */}
+ <div style={{
+ flex: 1,
+ position: 'relative',
+ minHeight: 0,
+ overflow: 'hidden'
+ }}>
{isLoading && (
- <div className="absolute inset-0 flex items-center justify-center bg-black/50 z-10">
- <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
+ <div style={{
+ position: 'absolute',
+ inset: 0,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: 'rgba(0, 0, 0, 0.5)',
+ zIndex: 10
+ }}>
+ <div style={{
+ width: '32px',
+ height: '32px',
+ border: '2px solid transparent',
+ borderTopColor: '#3b82f6',
+ borderRadius: '50%',
+ animation: 'spin 1s linear infinite'
+ }} />
</div>
)}
{error && (
- <div className="absolute inset-0 flex items-center justify-center bg-black/50 z-10">
- <div className="text-red-500 text-sm">
+ <div style={{
+ position: 'absolute',
+ inset: 0,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: 'rgba(0, 0, 0, 0.5)',
+ zIndex: 10
+ }}>
+ <div style={{ color: '#ef4444', fontSize: '14px' }}>
Failed to load chart data: {error.message}
</div>
</div>
)}
- <div ref={chartContainerRef} className="w-full" />
+ {/* ProChartWithToolkit with drawing tools */}
+ {!isLoading && !error && chartData.length > 0 && (
+ <ProChartWithToolkit
+ data={chartData}
+ symbol={`${symbol} - ${selectedTimeframe}`}
+ height={height}
+ showVolume={showVolume}
+ showToolbar={true}
+ showHeader={false}
+ />
+ )}
+
+ {/* Empty state when no data */}
+ {!isLoading && !error && chartData.length === 0 && (
+ <div style={{
+ position: 'absolute',
+ inset: 0,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: '#6b7280',
+ fontSize: '12px'
+ }}>
+ No data available
+ </div>
+ )}
</div>
</div>
);
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChartWithPlugins.tsx b/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChartWithPlugins.tsx
new file mode 100644
index 000000000..de2f35b32
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/TradingChartWithPlugins.tsx
@@ -0,0 +1,471 @@
+/**
+ * TradingChartWithPlugins - Enhanced TradingChart with plugin system
+ * Extends the base TradingChart with support for lightweight-charts plugins
+ */
+
+import React, { useEffect, useRef, useState, useCallback } from 'react';
+import { createChart, ColorType, CandlestickSeries, HistogramSeries } from 'lightweight-charts';
+import type { IChartApi, CandlestickData, Time, ISeriesApi, SeriesType } from 'lightweight-charts';
+import { useOHLCV } from '../hooks/useMarketData';
+import type { Timeframe, OHLCV } from '../types';
+import { PluginManager, TooltipPlugin, TrendLinePlugin, VerticalLinePlugin, IChartPlugin, PluginCategory } from './plugins';
+import { Settings, TrendingUp, Minus, Maximize2 } from 'lucide-react';
+
+interface TradingChartWithPluginsProps {
+ symbol: string;
+ timeframe?: Timeframe;
+ height?: number;
+ showVolume?: boolean;
+ enablePlugins?: boolean;
+}
+
+export function TradingChartWithPlugins({
+ symbol,
+ timeframe = '1h',
+ height = 500,
+ showVolume = true,
+ enablePlugins = true
+}: TradingChartWithPluginsProps) {
+ const chartContainerRef = useRef<HTMLDivElement>(null);
+ const chartRef = useRef<IChartApi | null>(null);
+ const candlestickSeriesRef = useRef<ISeriesApi<'Candlestick', Time> | null>(null);
+ const volumeSeriesRef = useRef<any>(null);
+ const pluginManagerRef = useRef<PluginManager | null>(null);
+
+ const [selectedTimeframe, setSelectedTimeframe] = useState<Timeframe>(timeframe);
+ const [showPluginPanel, setShowPluginPanel] = useState(false);
+ const [activeDrawingTool, setActiveDrawingTool] = useState<string | null>(null);
+
+ const { ohlcv, isLoading, error } = useOHLCV(symbol, selectedTimeframe, 200);
+
+ // Initialize chart and plugins
+ useEffect(() => {
+ if (!chartContainerRef.current) return;
+
+ const containerHeight = chartContainerRef.current.clientHeight || 400;
+
+ const chart = createChart(chartContainerRef.current, {
+ width: chartContainerRef.current.clientWidth,
+ height: containerHeight,
+ layout: {
+ background: { type: ColorType.Solid, color: '#0a0a0a' },
+ textColor: '#d1d5db',
+ fontSize: 11,
+ },
+ handleScroll: {
+ vertTouchDrag: true,
+ },
+ handleScale: {
+ axisPressedMouseMove: {
+ time: true,
+ price: true,
+ },
+ },
+ grid: {
+ vertLines: { color: '#1f1f1f' },
+ horzLines: { color: '#1f1f1f' },
+ },
+ crosshair: {
+ mode: 1,
+ },
+ rightPriceScale: {
+ borderColor: '#2a2a2a',
+ scaleMargins: {
+ top: 0.1,
+ bottom: 0.1,
+ },
+ },
+ timeScale: {
+ borderColor: '#2a2a2a',
+ timeVisible: true,
+ secondsVisible: false,
+ visible: true,
+ borderVisible: true,
+ ticksVisible: true,
+ rightOffset: 5,
+ },
+ overlayPriceScales: {
+ scaleMargins: {
+ top: 0.7,
+ bottom: 0,
+ },
+ },
+ });
+
+ chartRef.current = chart;
+
+ // Create candlestick series
+ const candlestickSeries = chart.addSeries(CandlestickSeries, {
+ upColor: '#10b981',
+ downColor: '#ef4444',
+ borderUpColor: '#10b981',
+ borderDownColor: '#ef4444',
+ wickUpColor: '#10b981',
+ wickDownColor: '#ef4444',
+ });
+
+ candlestickSeriesRef.current = candlestickSeries as any;
+
+ // Create volume series
+ if (showVolume) {
+ const volumeSeries = chart.addSeries(HistogramSeries, {
+ color: '#6b7280',
+ priceFormat: {
+ type: 'volume',
+ },
+ priceScaleId: '',
+ });
+
+ volumeSeries.priceScale().applyOptions({
+ scaleMargins: {
+ top: 0.8,
+ bottom: 0,
+ },
+ });
+
+ volumeSeriesRef.current = volumeSeries;
+ }
+
+ // Initialize plugin system
+ if (enablePlugins) {
+ const pluginManager = new PluginManager(chart, candlestickSeries as any);
+ pluginManagerRef.current = pluginManager;
+
+ // Register default plugins
+ const tooltipPlugin = new TooltipPlugin();
+ const trendLinePlugin = new TrendLinePlugin();
+ const verticalLinePlugin = new VerticalLinePlugin();
+
+ pluginManager.register(tooltipPlugin);
+ pluginManager.register(trendLinePlugin);
+ pluginManager.register(verticalLinePlugin);
+
+ console.log('[TradingChart] Plugin system initialized:', pluginManager.getStats());
+ }
+
+ // Handle resize
+ const handleResize = () => {
+ if (chartContainerRef.current && chartRef.current) {
+ const containerHeight = chartContainerRef.current.clientHeight || 400;
+ chartRef.current.resize(
+ chartContainerRef.current.clientWidth,
+ containerHeight,
+ true
+ );
+ }
+ };
+
+ window.addEventListener('resize', handleResize);
+
+ const resizeObserver = new ResizeObserver(() => {
+ handleResize();
+ });
+
+ if (chartContainerRef.current) {
+ resizeObserver.observe(chartContainerRef.current);
+ }
+
+ return () => {
+ window.removeEventListener('resize', handleResize);
+ resizeObserver.disconnect();
+
+ // Cleanup plugins
+ if (pluginManagerRef.current) {
+ pluginManagerRef.current.destroy();
+ }
+
+ chart.remove();
+ };
+ }, [height, showVolume, enablePlugins]);
+
+ // Update chart data
+ useEffect(() => {
+ if (!ohlcv.length || !candlestickSeriesRef.current) return;
+
+ const candleData: CandlestickData[] = ohlcv.map((candle: OHLCV) => {
+ let timestamp = candle.timestamp;
+ if (timestamp > 10000000000) {
+ timestamp = Math.floor(timestamp / 1000);
+ }
+
+ return {
+ time: timestamp as Time,
+ open: candle.open,
+ high: candle.high,
+ low: candle.low,
+ close: candle.close,
+ };
+ });
+
+ candlestickSeriesRef.current.setData(candleData);
+
+ if (showVolume && volumeSeriesRef.current) {
+ const volumeData = ohlcv.map((candle: OHLCV) => {
+ let timestamp = candle.timestamp;
+ if (timestamp > 10000000000) {
+ timestamp = Math.floor(timestamp / 1000);
+ }
+
+ return {
+ time: timestamp as Time,
+ value: candle.volume,
+ color: candle.close >= candle.open ? '#10b98144' : '#ef444444',
+ };
+ });
+
+ volumeSeriesRef.current.setData(volumeData);
+ }
+
+ chartRef.current?.timeScale().fitContent();
+ }, [ohlcv, showVolume]);
+
+ // Plugin controls
+ const togglePlugin = useCallback((pluginId: string) => {
+ if (!pluginManagerRef.current) return;
+
+ const plugin = pluginManagerRef.current.getPlugin(pluginId);
+ if (plugin) {
+ pluginManagerRef.current.togglePlugin(pluginId, !plugin.metadata.enabled);
+ }
+ }, []);
+
+ const activateDrawingTool = useCallback((toolName: string) => {
+ if (!pluginManagerRef.current) return;
+
+ // Deactivate previous tool
+ if (activeDrawingTool) {
+ const prevTool = pluginManagerRef.current.getPlugin(activeDrawingTool);
+ if (prevTool && 'stopDrawing' in prevTool) {
+ (prevTool as any).stopDrawing();
+ }
+ }
+
+ // Activate new tool
+ if (toolName === activeDrawingTool) {
+ setActiveDrawingTool(null);
+ } else {
+ const tool = pluginManagerRef.current.getPlugin(toolName);
+ if (tool && 'startDrawing' in tool) {
+ (tool as any).startDrawing();
+ setActiveDrawingTool(toolName);
+ }
+ }
+ }, [activeDrawingTool]);
+
+ const timeframes: Timeframe[] = ['1m', '5m', '15m', '1h', '4h', '1d'];
+
+ return (
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ height: '100%',
+ width: '100%',
+ position: 'relative'
+ }}>
+ {/* Toolbar */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: '8px',
+ padding: '8px 16px',
+ flexShrink: 0,
+ backgroundColor: '#0a0a0a',
+ borderBottom: '1px solid #1f1f1f'
+ }}>
+ {/* Timeframe selector */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ fontSize: '11px', color: '#9ca3af', fontWeight: 600 }}>TIMEFRAME:</span>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {timeframes.map((tf) => (
+ <button
+ key={tf}
+ onClick={() => setSelectedTimeframe(tf)}
+ style={{
+ padding: '4px 8px',
+ fontSize: '11px',
+ fontFamily: 'monospace',
+ borderRadius: '2px',
+ border: 'none',
+ cursor: 'pointer',
+ backgroundColor: selectedTimeframe === tf ? '#2563eb' : '#1f2937',
+ color: selectedTimeframe === tf ? '#ffffff' : '#9ca3af',
+ transition: 'all 0.2s'
+ }}
+ >
+ {tf}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Plugin toolbar */}
+ {enablePlugins && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <button
+ onClick={() => activateDrawingTool('trendline')}
+ title="Trend Line"
+ style={{
+ padding: '6px 10px',
+ fontSize: '11px',
+ borderRadius: '3px',
+ border: 'none',
+ cursor: 'pointer',
+ backgroundColor: activeDrawingTool === 'trendline' ? '#10b981' : '#1f2937',
+ color: '#ffffff',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <TrendingUp size={14} />
+ <span>Trend</span>
+ </button>
+
+ <button
+ onClick={() => {
+ const plugin = pluginManagerRef.current?.getPlugin('verticalline');
+ if (plugin && 'markNow' in plugin) {
+ (plugin as any).markNow();
+ }
+ }}
+ title="Mark Current Time"
+ style={{
+ padding: '6px 10px',
+ fontSize: '11px',
+ borderRadius: '3px',
+ border: 'none',
+ cursor: 'pointer',
+ backgroundColor: '#1f2937',
+ color: '#ffffff',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Minus size={14} />
+ <span>Mark</span>
+ </button>
+
+ <button
+ onClick={() => setShowPluginPanel(!showPluginPanel)}
+ title="Plugin Settings"
+ style={{
+ padding: '6px 10px',
+ fontSize: '11px',
+ borderRadius: '3px',
+ border: 'none',
+ cursor: 'pointer',
+ backgroundColor: showPluginPanel ? '#2563eb' : '#1f2937',
+ color: '#ffffff',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Settings size={14} />
+ </button>
+ </div>
+ )}
+ </div>
+
+ {/* Plugin panel */}
+ {enablePlugins && showPluginPanel && (
+ <div style={{
+ padding: '12px 16px',
+ backgroundColor: '#0f0f0f',
+ borderBottom: '1px solid #1f1f1f',
+ fontSize: '11px'
+ }}>
+ <div style={{ color: '#9ca3af', marginBottom: '8px', fontWeight: 600 }}>PLUGINS</div>
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
+ {pluginManagerRef.current?.getPlugins().map((plugin) => (
+ <label
+ key={plugin.metadata.id}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ padding: '4px 8px',
+ backgroundColor: '#1f2937',
+ borderRadius: '3px',
+ cursor: 'pointer',
+ color: plugin.metadata.enabled ? '#ffffff' : '#6b7280'
+ }}
+ >
+ <input
+ type="checkbox"
+ checked={plugin.metadata.enabled}
+ onChange={() => togglePlugin(plugin.metadata.id)}
+ style={{ cursor: 'pointer' }}
+ />
+ <span>{plugin.metadata.name}</span>
+ <span style={{
+ fontSize: '9px',
+ color: '#6b7280',
+ textTransform: 'uppercase'
+ }}>
+ {plugin.metadata.category}
+ </span>
+ </label>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Chart container */}
+ <div style={{
+ flex: 1,
+ position: 'relative',
+ minHeight: 0,
+ overflow: 'hidden'
+ }}>
+ {isLoading && (
+ <div style={{
+ position: 'absolute',
+ inset: 0,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: 'rgba(0, 0, 0, 0.5)',
+ zIndex: 10
+ }}>
+ <div style={{
+ width: '32px',
+ height: '32px',
+ border: '2px solid transparent',
+ borderTopColor: '#3b82f6',
+ borderRadius: '50%',
+ animation: 'spin 1s linear infinite'
+ }} />
+ </div>
+ )}
+
+ {error && (
+ <div style={{
+ position: 'absolute',
+ inset: 0,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: 'rgba(0, 0, 0, 0.5)',
+ zIndex: 10
+ }}>
+ <div style={{ color: '#ef4444', fontSize: '14px' }}>
+ Failed to load chart data: {error.message}
+ </div>
+ </div>
+ )}
+
+ <div
+ ref={chartContainerRef}
+ style={{
+ width: '100%',
+ height: '100%',
+ position: 'relative'
+ }}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/BasePlugin.ts b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/BasePlugin.ts
new file mode 100644
index 000000000..c380566c2
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/BasePlugin.ts
@@ -0,0 +1,171 @@
+/**
+ * Base Plugin Class
+ *
+ * Abstract base class that provides common functionality for all chart plugins.
+ * Implements the IChartPlugin interface with shared utilities.
+ */
+
+import type {
+ ISeriesPrimitive,
+ Time,
+ SeriesType,
+ ISeriesApi,
+ IChartApi
+} from 'lightweight-charts';
+import {
+ IChartPlugin,
+ PluginMetadata,
+ PluginOptions,
+ PluginEventType,
+ PluginEvent,
+ PluginEventListener
+} from './types';
+
+export abstract class BasePlugin<HorzScaleItem = Time> implements IChartPlugin<HorzScaleItem> {
+ public metadata: PluginMetadata;
+ public options: PluginOptions;
+
+ protected chart: IChartApi | null = null;
+ protected series: ISeriesApi<SeriesType, HorzScaleItem> | null = null;
+ protected primitive: ISeriesPrimitive<HorzScaleItem> | null = null;
+ protected eventListeners: Map<PluginEventType, PluginEventListener[]> = new Map();
+
+ constructor(metadata: PluginMetadata, options: PluginOptions = {}) {
+ this.metadata = { ...metadata };
+ this.options = { ...this.getDefaultOptions(), ...options };
+ }
+
+ /**
+ * Get default options for the plugin (can be overridden)
+ */
+ protected getDefaultOptions(): PluginOptions {
+ return {
+ visible: true,
+ interactive: false,
+ color: '#2196F3',
+ lineWidth: 2,
+ lineStyle: 0, // Solid
+ };
+ }
+
+ /**
+ * Initialize the plugin with chart and series
+ */
+ public initialize(chart: IChartApi, series: ISeriesApi<SeriesType, HorzScaleItem>): void {
+ this.chart = chart;
+ this.series = series;
+
+ // Create and attach primitive
+ this.primitive = this.createPrimitive();
+ if (this.primitive && this.metadata.enabled) {
+ this.attachPrimitive();
+ }
+ }
+
+ /**
+ * Create the primitive (must be implemented by subclasses)
+ */
+ protected abstract createPrimitive(): ISeriesPrimitive<HorzScaleItem> | null;
+
+ /**
+ * Attach primitive to series
+ */
+ protected attachPrimitive(): void {
+ if (this.primitive && this.series) {
+ this.series.attachPrimitive(this.primitive);
+ }
+ }
+
+ /**
+ * Detach primitive from series
+ */
+ protected detachPrimitive(): void {
+ if (this.primitive && this.series) {
+ this.series.detachPrimitive(this.primitive);
+ }
+ }
+
+ /**
+ * Apply new options to the plugin
+ */
+ public applyOptions(newOptions: Partial<PluginOptions>): void {
+ this.options = { ...this.options, ...newOptions };
+ this.onOptionsChanged();
+ }
+
+ /**
+ * Called when options change (can be overridden)
+ */
+ protected onOptionsChanged(): void {
+ // Trigger re-render
+ if (this.chart) {
+ this.chart.timeScale().fitContent();
+ }
+ }
+
+ /**
+ * Get the primitive
+ */
+ public getPrimitive(): ISeriesPrimitive<HorzScaleItem> | null {
+ return this.primitive;
+ }
+
+ /**
+ * Enable/disable the plugin
+ */
+ public setEnabled(enabled: boolean): void {
+ if (this.metadata.enabled === enabled) return;
+
+ this.metadata.enabled = enabled;
+
+ if (enabled) {
+ this.attachPrimitive();
+ } else {
+ this.detachPrimitive();
+ }
+ }
+
+ /**
+ * Destroy the plugin and cleanup
+ */
+ public destroy(): void {
+ this.detachPrimitive();
+ this.eventListeners.clear();
+ this.chart = null;
+ this.series = null;
+ this.primitive = null;
+ }
+
+ /**
+ * Add event listener
+ */
+ public addEventListener(type: PluginEventType, listener: PluginEventListener): void {
+ if (!this.eventListeners.has(type)) {
+ this.eventListeners.set(type, []);
+ }
+ this.eventListeners.get(type)!.push(listener);
+ }
+
+ /**
+ * Remove event listener
+ */
+ public removeEventListener(type: PluginEventType, listener: PluginEventListener): void {
+ const listeners = this.eventListeners.get(type);
+ if (listeners) {
+ const index = listeners.indexOf(listener);
+ if (index > -1) {
+ listeners.splice(index, 1);
+ }
+ }
+ }
+
+ /**
+ * Emit event to listeners
+ */
+ protected emitEvent(event: PluginEvent): void {
+ const listeners = this.eventListeners.get(event.type);
+ if (listeners) {
+ listeners.forEach(listener => listener(event));
+ }
+ }
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/PluginManager.ts b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/PluginManager.ts
new file mode 100644
index 000000000..aec30e550
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/PluginManager.ts
@@ -0,0 +1,167 @@
+/**
+ * Plugin Manager
+ *
+ * Manages all chart plugins, including registration, lifecycle, and coordination.
+ */
+
+import type { IChartApi, ISeriesApi, SeriesType, Time } from 'lightweight-charts';
+import { IPluginManager, IChartPlugin, PluginCategory } from './types';
+
+export class PluginManager implements IPluginManager {
+ private plugins: Map<string, IChartPlugin> = new Map();
+ private chart: IChartApi | null = null;
+ private series: ISeriesApi<SeriesType, Time> | null = null;
+
+ constructor(chart?: IChartApi, series?: ISeriesApi<SeriesType, Time>) {
+ if (chart) this.chart = chart;
+ if (series) this.series = series;
+ }
+
+ /**
+ * Set the chart and series context
+ */
+ public setContext(chart: IChartApi, series: ISeriesApi<SeriesType, Time>): void {
+ this.chart = chart;
+ this.series = series;
+
+ // Initialize all existing plugins with new context
+ this.plugins.forEach(plugin => {
+ if (this.chart && this.series) {
+ plugin.initialize(this.chart, this.series);
+ }
+ });
+ }
+
+ /**
+ * Register a plugin
+ */
+ public register(plugin: IChartPlugin): void {
+ const pluginId = plugin.metadata.id;
+
+ if (this.plugins.has(pluginId)) {
+ console.warn(`Plugin with id "${pluginId}" is already registered. Skipping.`);
+ return;
+ }
+
+ // Initialize plugin if context is available
+ if (this.chart && this.series) {
+ plugin.initialize(this.chart, this.series);
+ }
+
+ this.plugins.set(pluginId, plugin);
+ console.log(`Plugin "${plugin.metadata.name}" registered successfully.`);
+ }
+
+ /**
+ * Unregister a plugin by id
+ */
+ public unregister(pluginId: string): void {
+ const plugin = this.plugins.get(pluginId);
+ if (!plugin) {
+ console.warn(`Plugin with id "${pluginId}" not found.`);
+ return;
+ }
+
+ plugin.destroy();
+ this.plugins.delete(pluginId);
+ console.log(`Plugin "${plugin.metadata.name}" unregistered.`);
+ }
+
+ /**
+ * Get all registered plugins
+ */
+ public getPlugins(): IChartPlugin[] {
+ return Array.from(this.plugins.values());
+ }
+
+ /**
+ * Get plugins by category
+ */
+ public getPluginsByCategory(category: PluginCategory): IChartPlugin[] {
+ return this.getPlugins().filter(
+ plugin => plugin.metadata.category === category
+ );
+ }
+
+ /**
+ * Toggle plugin enabled state
+ */
+ public togglePlugin(pluginId: string, enabled: boolean): void {
+ const plugin = this.plugins.get(pluginId);
+ if (!plugin) {
+ console.warn(`Plugin with id "${pluginId}" not found.`);
+ return;
+ }
+
+ plugin.setEnabled(enabled);
+ console.log(`Plugin "${plugin.metadata.name}" ${enabled ? 'enabled' : 'disabled'}.`);
+ }
+
+ /**
+ * Get plugin by id
+ */
+ public getPlugin(pluginId: string): IChartPlugin | undefined {
+ return this.plugins.get(pluginId);
+ }
+
+ /**
+ * Enable all plugins
+ */
+ public enableAll(): void {
+ this.plugins.forEach(plugin => plugin.setEnabled(true));
+ }
+
+ /**
+ * Disable all plugins
+ */
+ public disableAll(): void {
+ this.plugins.forEach(plugin => plugin.setEnabled(false));
+ }
+
+ /**
+ * Clear all plugins
+ */
+ public clear(): void {
+ this.plugins.forEach(plugin => plugin.destroy());
+ this.plugins.clear();
+ }
+
+ /**
+ * Get enabled plugins count
+ */
+ public getEnabledCount(): number {
+ return this.getPlugins().filter(p => p.metadata.enabled).length;
+ }
+
+ /**
+ * Get plugin statistics
+ */
+ public getStats(): {
+ total: number;
+ enabled: number;
+ byCategory: Record<string, number>;
+ } {
+ const plugins = this.getPlugins();
+ const byCategory: Record<string, number> = {};
+
+ plugins.forEach(plugin => {
+ const category = plugin.metadata.category;
+ byCategory[category] = (byCategory[category] || 0) + 1;
+ });
+
+ return {
+ total: plugins.length,
+ enabled: this.getEnabledCount(),
+ byCategory,
+ };
+ }
+
+ /**
+ * Destroy manager and all plugins
+ */
+ public destroy(): void {
+ this.clear();
+ this.chart = null;
+ this.series = null;
+ }
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/README.md b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/README.md
new file mode 100644
index 000000000..c89a175fc
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/README.md
@@ -0,0 +1,512 @@
+# Lightweight Charts Plugin System
+
+A comprehensive plugin architecture for extending lightweight-charts with custom primitives, drawing tools, indicators, and interactive features in the Fincept Terminal.
+
+## Table of Contents
+
+- [Overview](#overview)
+- [Architecture](#architecture)
+- [Built-in Plugins](#built-in-plugins)
+- [Usage](#usage)
+- [Creating Custom Plugins](#creating-custom-plugins)
+- [API Reference](#api-reference)
+- [Examples](#examples)
+
+## Overview
+
+The plugin system allows you to extend the lightweight-charts library with:
+
+- **Drawing Tools**: Interactive tools for technical analysis (trend lines, shapes, annotations)
+- **Indicators**: Custom technical indicators and overlays
+- **Annotations**: Text labels, vertical lines, markers
+- **Interactive Features**: Tooltips, crosshair enhancements, custom interactions
+- **Overlays**: Background shading, session highlighting, custom visualizations
+
+### Features
+
+✅ **Type-safe**: Full TypeScript support with comprehensive type definitions
+✅ **Modular**: Plugin-based architecture for easy extension
+✅ **Performance**: Built on lightweight-charts primitives for optimal rendering
+✅ **Interactive**: Support for mouse events and drawing interactions
+✅ **Customizable**: Extensive options for styling and behavior
+✅ **Production-ready**: Designed for professional financial terminal use
+
+## Architecture
+
+### Core Components
+
+```
+plugins/
+├── types.ts # Type definitions and interfaces
+├── BasePlugin.ts # Abstract base class for all plugins
+├── PluginManager.ts # Manages plugin lifecycle and coordination
+├── TooltipPlugin.ts # Interactive tooltip display
+├── TrendLinePlugin.ts # Trend line drawing tool
+├── VerticalLinePlugin.ts # Vertical time markers
+├── index.ts # Main export and plugin registry
+└── README.md # This file
+```
+
+### Plugin Lifecycle
+
+1. **Creation**: Plugin instance created with configuration options
+2. **Registration**: Plugin registered with PluginManager
+3. **Initialization**: Plugin receives chart and series context
+4. **Attachment**: Primitive attached to series for rendering
+5. **Updates**: Plugin responds to option changes and events
+6. **Destruction**: Cleanup when plugin is removed
+
+## Built-in Plugins
+
+### 1. TooltipPlugin
+
+Displays customizable tooltips with price and time information on hover.
+
+**Features**:
+- OHLC data display
+- Volume information
+- Custom formatting
+- Follow cursor mode
+- Configurable styling
+
+**Example**:
+```typescript
+import { TooltipPlugin } from './plugins';
+
+const tooltip = new TooltipPlugin({
+ showOHLC: true,
+ showVolume: true,
+ backgroundColor: 'rgba(0, 0, 0, 0.85)',
+ fontSize: 11,
+});
+```
+
+### 2. TrendLinePlugin
+
+Interactive trend line drawing tool for technical analysis.
+
+**Features**:
+- Two-point click drawing
+- Line extension (left/right)
+- Custom colors and styles
+- Multiple lines support
+- Edit and remove lines
+
+**Example**:
+```typescript
+import { TrendLinePlugin } from './plugins';
+
+const trendLine = new TrendLinePlugin({
+ color: '#2196F3',
+ lineWidth: 2,
+ extendRight: true,
+});
+
+// Activate drawing mode
+trendLine.startDrawing();
+
+// Add programmatically
+trendLine.addLine(
+ { time: 1234567890, price: 100 },
+ { time: 1234567900, price: 110 }
+);
+```
+
+### 3. VerticalLinePlugin
+
+Marks specific time points with vertical lines.
+
+**Features**:
+- Time-based markers
+- Optional labels
+- Customizable styling
+- Dashed/solid lines
+- Event marking
+
+**Example**:
+```typescript
+import { VerticalLinePlugin } from './plugins';
+
+const vLine = new VerticalLinePlugin({
+ showLabel: true,
+ dashArray: [5, 5],
+});
+
+// Mark current time
+vLine.markNow('Market Open');
+
+// Add custom marker
+vLine.addMarker(timestamp, 'Event', '#ff9800');
+```
+
+## Usage
+
+### Basic Setup
+
+```typescript
+import { PluginManager, TooltipPlugin, TrendLinePlugin } from './plugins';
+import { createChart, CandlestickSeries } from 'lightweight-charts';
+
+// Create chart and series
+const chart = createChart(container);
+const series = chart.addSeries(CandlestickSeries);
+
+// Initialize plugin manager
+const pluginManager = new PluginManager(chart, series);
+
+// Register plugins
+pluginManager.register(new TooltipPlugin());
+pluginManager.register(new TrendLinePlugin());
+
+// Get plugin statistics
+console.log(pluginManager.getStats());
+// { total: 2, enabled: 2, byCategory: { interactive: 1, drawing: 1 } }
+```
+
+### Using with TradingChartWithPlugins
+
+```typescript
+import { TradingChartWithPlugins } from './charts/TradingChartWithPlugins';
+
+function MyChart() {
+ return (
+ <TradingChartWithPlugins
+ symbol="BTC/USD"
+ timeframe="1h"
+ enablePlugins={true}
+ />
+ );
+}
+```
+
+### Managing Plugins
+
+```typescript
+// Enable/disable plugins
+pluginManager.togglePlugin('tooltip', false);
+
+// Get specific plugin
+const trendLine = pluginManager.getPlugin('trendline');
+
+// Get plugins by category
+const drawingTools = pluginManager.getPluginsByCategory(PluginCategory.DRAWING);
+
+// Clear all plugins
+pluginManager.clear();
+```
+
+## Creating Custom Plugins
+
+### Step 1: Define Plugin Class
+
+```typescript
+import { BasePlugin } from './BasePlugin';
+import { PluginCategory, PluginOptions } from './types';
+import type { ISeriesPrimitive, Time } from 'lightweight-charts';
+
+interface MyPluginOptions extends PluginOptions {
+ customOption?: string;
+}
+
+export class MyCustomPlugin extends BasePlugin<Time> {
+ constructor(options: Partial<MyPluginOptions> = {}) {
+ super(
+ {
+ id: 'my-plugin',
+ name: 'My Custom Plugin',
+ description: 'Does something awesome',
+ category: PluginCategory.INDICATOR,
+ version: '1.0.0',
+ enabled: true
+ },
+ options
+ );
+ }
+
+ protected createPrimitive(): ISeriesPrimitive<Time> | null {
+ // Create and return your primitive
+ return new MyCustomPrimitive(this.options);
+ }
+}
+```
+
+### Step 2: Implement Primitive
+
+```typescript
+import type {
+ ISeriesPrimitive,
+ ISeriesPrimitivePaneView,
+ SeriesAttachedParameter,
+ Time
+} from 'lightweight-charts';
+
+class MyCustomPrimitive implements ISeriesPrimitive<Time> {
+ private _paneViews: MyPaneView[];
+
+ constructor(options: any) {
+ this._paneViews = [new MyPaneView(options)];
+ }
+
+ attached(param: SeriesAttachedParameter<Time>): void {
+ // Called when primitive is attached
+ }
+
+ updateAllViews(param: SeriesAttachedParameter<Time>): void {
+ // Update all views with new data
+ this._paneViews.forEach(view => view.update(param));
+ }
+
+ paneViews(): readonly ISeriesPrimitivePaneView[] {
+ return this._paneViews;
+ }
+}
+```
+
+### Step 3: Implement Pane View
+
+```typescript
+import type {
+ ISeriesPrimitivePaneView,
+ SeriesAttachedParameter,
+ CanvasRenderingTarget2D,
+ Time
+} from 'lightweight-charts';
+
+class MyPaneView implements ISeriesPrimitivePaneView {
+ private _options: any;
+
+ constructor(options: any) {
+ this._options = options;
+ }
+
+ update(param: SeriesAttachedParameter<Time>): void {
+ // Update view data
+ }
+
+ renderer(): any {
+ return {
+ draw: (target: CanvasRenderingTarget2D) => {
+ const ctx = target.context;
+
+ // Your custom drawing code here
+ ctx.fillStyle = this._options.color;
+ ctx.fillRect(10, 10, 100, 100);
+ }
+ };
+ }
+}
+```
+
+### Step 4: Register Plugin
+
+```typescript
+import { PLUGIN_REGISTRY } from './index';
+import { MyCustomPlugin } from './MyCustomPlugin';
+
+// Add to registry
+PLUGIN_REGISTRY['my-plugin'] = () => new MyCustomPlugin();
+
+// Or register directly
+pluginManager.register(new MyCustomPlugin({
+ customOption: 'value'
+}));
+```
+
+## API Reference
+
+### PluginManager
+
+#### Methods
+
+- `register(plugin: IChartPlugin): void` - Register a plugin
+- `unregister(pluginId: string): void` - Unregister a plugin
+- `getPlugins(): IChartPlugin[]` - Get all plugins
+- `getPlugin(pluginId: string): IChartPlugin | undefined` - Get specific plugin
+- `getPluginsByCategory(category: PluginCategory): IChartPlugin[]` - Get plugins by category
+- `togglePlugin(pluginId: string, enabled: boolean): void` - Enable/disable plugin
+- `getStats()` - Get plugin statistics
+- `clear(): void` - Remove all plugins
+- `destroy(): void` - Cleanup manager
+
+### BasePlugin
+
+#### Properties
+
+- `metadata: PluginMetadata` - Plugin metadata
+- `options: PluginOptions` - Plugin options
+
+#### Methods
+
+- `initialize(chart, series): void` - Initialize plugin
+- `applyOptions(options): void` - Update options
+- `getPrimitive(): ISeriesPrimitive | null` - Get primitive
+- `setEnabled(enabled: boolean): void` - Enable/disable
+- `destroy(): void` - Cleanup
+
+#### Protected Methods (for subclasses)
+
+- `createPrimitive(): ISeriesPrimitive | null` - Create primitive
+- `getDefaultOptions(): PluginOptions` - Get defaults
+- `onOptionsChanged(): void` - Handle option changes
+- `attachPrimitive(): void` - Attach primitive to series
+- `detachPrimitive(): void` - Detach primitive
+
+### Plugin Types
+
+#### PluginCategory
+
+```typescript
+enum PluginCategory {
+ DRAWING = 'drawing',
+ INDICATOR = 'indicator',
+ ANNOTATION = 'annotation',
+ INTERACTIVE = 'interactive',
+ OVERLAY = 'overlay',
+}
+```
+
+#### PluginOptions
+
+```typescript
+interface PluginOptions {
+ color?: string;
+ lineWidth?: number;
+ lineStyle?: number;
+ visible?: boolean;
+ interactive?: boolean;
+ [key: string]: any;
+}
+```
+
+## Examples
+
+### Example 1: Multi-Plugin Setup
+
+```typescript
+const pluginManager = new PluginManager(chart, series);
+
+// Add tooltip
+const tooltip = new TooltipPlugin({
+ showOHLC: true,
+ showVolume: true,
+});
+pluginManager.register(tooltip);
+
+// Add trend lines
+const trendLine = new TrendLinePlugin({
+ color: '#2196F3',
+ extendRight: true,
+});
+pluginManager.register(trendLine);
+
+// Add vertical markers
+const vLine = new VerticalLinePlugin();
+pluginManager.register(vLine);
+
+// Mark important events
+vLine.addMarker(1234567890, 'Event A', '#ff9800');
+vLine.addMarker(1234567900, 'Event B', '#4caf50');
+```
+
+### Example 2: Interactive Drawing
+
+```typescript
+const trendLine = new TrendLinePlugin();
+pluginManager.register(trendLine);
+
+// Activate drawing mode
+function startDrawing() {
+ trendLine.startDrawing();
+ console.log('Click two points to draw a trend line');
+}
+
+// Handle chart clicks
+chartContainer.addEventListener('click', (event) => {
+ if (trendLine.isDrawing()) {
+ const point = getChartPoint(event); // Your coordinate conversion
+ trendLine.handleClick(point);
+ }
+});
+
+// Stop drawing
+function stopDrawing() {
+ trendLine.stopDrawing();
+}
+
+// Clear all lines
+function clearAll() {
+ trendLine.clear();
+}
+```
+
+### Example 3: Custom Plugin with Events
+
+```typescript
+class AlertPlugin extends BasePlugin<Time> {
+ private alerts: Map<string, Alert> = new Map();
+
+ addAlert(time: Time, price: number, message: string) {
+ const id = `alert-${Date.now()}`;
+ this.alerts.set(id, { time, price, message });
+
+ // Emit event
+ this.emitEvent({
+ type: PluginEventType.CUSTOM,
+ data: { id, time, price, message },
+ timestamp: Date.now()
+ });
+
+ return id;
+ }
+
+ protected createPrimitive(): ISeriesPrimitive<Time> {
+ return new AlertPrimitive(this.alerts);
+ }
+}
+
+// Usage with event listeners
+const alertPlugin = new AlertPlugin();
+alertPlugin.addEventListener(PluginEventType.CUSTOM, (event) => {
+ console.log('Alert added:', event.data);
+ // Trigger notification, sound, etc.
+});
+
+pluginManager.register(alertPlugin);
+```
+
+## Best Practices
+
+1. **Type Safety**: Always use TypeScript for type checking
+2. **Performance**: Minimize drawing operations, use memoization
+3. **Cleanup**: Always destroy plugins when done
+4. **Error Handling**: Handle edge cases and invalid data
+5. **Documentation**: Document custom plugins and options
+6. **Testing**: Test plugins with various data scenarios
+7. **Modularity**: Keep plugins focused on single responsibility
+
+## Resources
+
+- [Lightweight Charts Documentation](https://tradingview.github.io/lightweight-charts/)
+- [Plugin Examples](https://tradingview.github.io/lightweight-charts/plugin-examples/)
+- [API Reference](https://tradingview.github.io/lightweight-charts/docs/api)
+- [Primitives Guide](https://tradingview.github.io/lightweight-charts/docs/plugins/intro)
+
+## Contributing
+
+To add new plugins:
+
+1. Create plugin class extending `BasePlugin`
+2. Implement required methods
+3. Add to `PLUGIN_REGISTRY` in `index.ts`
+4. Add documentation and examples
+5. Test with `TradingChartWithPlugins`
+
+## License
+
+MIT - Part of Fincept Terminal
+
+---
+
+**Version**: 1.0.0
+**Last Updated**: 2025-01-14
+**Maintained By**: Fincept Corporation
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/TooltipPlugin.ts b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/TooltipPlugin.ts
new file mode 100644
index 000000000..2f9c1405b
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/TooltipPlugin.ts
@@ -0,0 +1,248 @@
+/**
+ * Tooltip Plugin
+ *
+ * Displays a customizable tooltip with price and time information when hovering over the chart.
+ * Based on https://tradingview.github.io/lightweight-charts/plugin-examples/tooltip
+ */
+
+import type {
+ ISeriesPrimitive,
+ Time,
+ IPrimitivePaneView
+} from 'lightweight-charts';
+import { BasePlugin } from './BasePlugin';
+import { PluginCategory, PluginOptions } from './types';
+
+interface TooltipOptions extends PluginOptions {
+ backgroundColor?: string;
+ textColor?: string;
+ borderColor?: string;
+ borderWidth?: number;
+ borderRadius?: number;
+ padding?: number;
+ fontSize?: number;
+ fontFamily?: string;
+ followCursor?: boolean;
+ offsetX?: number;
+ offsetY?: number;
+ showTime?: boolean;
+ showPrice?: boolean;
+ showOHLC?: boolean;
+ showVolume?: boolean;
+ customFormatter?: (data: any) => string;
+}
+
+class TooltipPaneView implements IPrimitivePaneView {
+ private _data: any = null;
+ private _options: TooltipOptions;
+
+ constructor(options: TooltipOptions) {
+ this._options = options;
+ }
+
+ update(data: any): void {
+ this._data = data;
+ }
+
+ renderer(): any {
+ return {
+ draw: (target: any) => {
+ if (!this._data || !this._data.visible) return;
+
+ target.useBitmapCoordinateSpace((scope: any) => {
+ const ctx = scope.context;
+ const x = this._data.x + (this._options.offsetX || 10);
+ const y = this._data.y + (this._options.offsetY || 10);
+
+ // Prepare text
+ const lines: string[] = [];
+
+ if (this._options.customFormatter) {
+ lines.push(this._options.customFormatter(this._data));
+ } else {
+ if (this._options.showTime && this._data.time) {
+ lines.push(`Time: ${this.formatTime(this._data.time)}`);
+ }
+
+ if (this._options.showOHLC && this._data.ohlc) {
+ lines.push(`O: ${this._data.ohlc.open.toFixed(2)}`);
+ lines.push(`H: ${this._data.ohlc.high.toFixed(2)}`);
+ lines.push(`L: ${this._data.ohlc.low.toFixed(2)}`);
+ lines.push(`C: ${this._data.ohlc.close.toFixed(2)}`);
+ } else if (this._options.showPrice && this._data.price !== undefined) {
+ lines.push(`Price: ${this._data.price.toFixed(2)}`);
+ }
+
+ if (this._options.showVolume && this._data.volume !== undefined) {
+ lines.push(`Vol: ${this.formatVolume(this._data.volume)}`);
+ }
+ }
+
+ if (lines.length === 0) return;
+
+ // Style
+ const fontSize = this._options.fontSize || 12;
+ const fontFamily = this._options.fontFamily || 'monospace';
+ const padding = this._options.padding || 8;
+ const lineHeight = fontSize * 1.4;
+
+ ctx.font = `${fontSize}px ${fontFamily}`;
+
+ // Measure text
+ const maxWidth = Math.max(...lines.map(line => ctx.measureText(line).width));
+ const tooltipWidth = maxWidth + padding * 2;
+ const tooltipHeight = lines.length * lineHeight + padding * 2;
+
+ // Draw background
+ ctx.fillStyle = this._options.backgroundColor || 'rgba(0, 0, 0, 0.8)';
+ ctx.strokeStyle = this._options.borderColor || 'rgba(255, 255, 255, 0.2)';
+ ctx.lineWidth = this._options.borderWidth || 1;
+
+ const radius = this._options.borderRadius || 4;
+ this.roundRect(ctx, x, y, tooltipWidth, tooltipHeight, radius);
+ ctx.fill();
+ ctx.stroke();
+
+ // Draw text
+ ctx.fillStyle = this._options.textColor || '#ffffff';
+ lines.forEach((line, index) => {
+ ctx.fillText(line, x + padding, y + padding + (index + 1) * lineHeight - 4);
+ });
+ });
+ }
+ };
+ }
+
+ private roundRect(
+ ctx: CanvasRenderingContext2D,
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ radius: number
+ ): void {
+ ctx.beginPath();
+ ctx.moveTo(x + radius, y);
+ ctx.lineTo(x + width - radius, y);
+ ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
+ ctx.lineTo(x + width, y + height - radius);
+ ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
+ ctx.lineTo(x + radius, y + height);
+ ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
+ ctx.lineTo(x, y + radius);
+ ctx.quadraticCurveTo(x, y, x + radius, y);
+ ctx.closePath();
+ }
+
+ private formatTime(time: Time): string {
+ if (typeof time === 'number') {
+ return new Date(time * 1000).toLocaleString();
+ }
+ if (typeof time === 'object' && 'year' in time) {
+ return `${time.year}-${String(time.month).padStart(2, '0')}-${String(time.day).padStart(2, '0')}`;
+ }
+ return String(time);
+ }
+
+ private formatVolume(volume: number): string {
+ if (volume >= 1e9) return (volume / 1e9).toFixed(2) + 'B';
+ if (volume >= 1e6) return (volume / 1e6).toFixed(2) + 'M';
+ if (volume >= 1e3) return (volume / 1e3).toFixed(2) + 'K';
+ return volume.toFixed(0);
+ }
+}
+
+class TooltipPrimitive implements ISeriesPrimitive<Time> {
+ private _paneViews: TooltipPaneView[];
+ private _options: TooltipOptions;
+
+ constructor(options: TooltipOptions) {
+ this._options = options;
+ this._paneViews = [new TooltipPaneView(options)];
+ }
+
+ updateAllViews(): void {
+ this._paneViews.forEach(view => view.update(null));
+ }
+
+ paneViews(): readonly IPrimitivePaneView[] {
+ return this._paneViews;
+ }
+
+ update(data: any): void {
+ this._paneViews[0].update(data);
+ }
+
+ updateOptions(options: TooltipOptions): void {
+ this._options = { ...this._options, ...options };
+ }
+}
+
+export class TooltipPlugin extends BasePlugin<Time> {
+ private tooltipPrimitive: TooltipPrimitive | null = null;
+
+ constructor(options: Partial<TooltipOptions> = {}) {
+ const defaultOptions: TooltipOptions = {
+ visible: true,
+ backgroundColor: 'rgba(0, 0, 0, 0.85)',
+ textColor: '#ffffff',
+ borderColor: 'rgba(255, 255, 255, 0.2)',
+ borderWidth: 1,
+ borderRadius: 6,
+ padding: 10,
+ fontSize: 11,
+ fontFamily: 'monospace',
+ followCursor: true,
+ offsetX: 15,
+ offsetY: 15,
+ showTime: true,
+ showPrice: false,
+ showOHLC: true,
+ showVolume: true,
+ ...options
+ };
+
+ super(
+ {
+ id: 'tooltip',
+ name: 'Tooltip',
+ description: 'Displays price and time information on hover',
+ category: PluginCategory.INTERACTIVE,
+ version: '1.0.0',
+ author: 'Fincept Terminal',
+ enabled: true
+ },
+ defaultOptions
+ );
+ }
+
+ protected getDefaultOptions(): PluginOptions {
+ return {
+ visible: true,
+ showTime: true,
+ showOHLC: true,
+ showVolume: true,
+ };
+ }
+
+ protected createPrimitive(): ISeriesPrimitive<Time> | null {
+ this.tooltipPrimitive = new TooltipPrimitive(this.options as TooltipOptions);
+ return this.tooltipPrimitive;
+ }
+
+ /**
+ * Update tooltip with crosshair data
+ */
+ public updateTooltip(data: any): void {
+ if (this.tooltipPrimitive) {
+ this.tooltipPrimitive.update(data);
+ }
+ }
+
+ protected onOptionsChanged(): void {
+ if (this.tooltipPrimitive) {
+ this.tooltipPrimitive.updateOptions(this.options as TooltipOptions);
+ }
+ super.onOptionsChanged();
+ }
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/TradingToolkitPlugin.ts b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/TradingToolkitPlugin.ts
new file mode 100644
index 000000000..ea5000ec3
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/TradingToolkitPlugin.ts
@@ -0,0 +1,1608 @@
+/**
+ * Trading Toolkit Plugin - All-in-One Professional Drawing & Analysis Tools
+ *
+ * A comprehensive plugin that replicates TradingView's complete toolkit including:
+ * - Drawing Tools: Trend lines, channels, patterns, rectangles, ellipses
+ * - Fibonacci Tools: Retracement, extension, fans, arcs, circles
+ * - Position Markers: Long/Short entries, exits, stop-loss, take-profit
+ * - Technical Patterns: Head & Shoulders, triangles, flags, wedges
+ * - Annotations: Text, arrows, labels, callouts
+ * - Measurement Tools: Price range, date range, angle measurements
+ */
+
+import type {
+ ISeriesPrimitive,
+ SeriesAttachedParameter,
+ Time,
+ IPrimitivePaneView,
+ Coordinate,
+ IChartApi,
+ ISeriesApi,
+ SeriesType
+} from 'lightweight-charts';
+import { BasePlugin } from './BasePlugin';
+import { PluginCategory, PluginOptions, ChartPoint } from './types';
+
+// ==================== TOOL TYPES ====================
+
+export enum DrawingTool {
+ // Basic Drawing
+ TREND_LINE = 'trendline',
+ HORIZONTAL_LINE = 'horizontal',
+ VERTICAL_LINE = 'vertical',
+ RAY = 'ray',
+ EXTENDED_LINE = 'extended',
+
+ // Channels & Patterns
+ PARALLEL_CHANNEL = 'channel',
+ REGRESSION_CHANNEL = 'regression',
+ PITCHFORK = 'pitchfork',
+
+ // Shapes
+ RECTANGLE = 'rectangle',
+ ELLIPSE = 'ellipse',
+ TRIANGLE = 'triangle',
+ ARROW = 'arrow',
+
+ // Fibonacci Tools
+ FIBO_RETRACEMENT = 'fibo_retracement',
+ FIBO_EXTENSION = 'fibo_extension',
+ FIBO_FAN = 'fibo_fan',
+ FIBO_CIRCLE = 'fibo_circle',
+ FIBO_SPIRAL = 'fibo_spiral',
+
+ // Gann Tools
+ GANN_FAN = 'gann_fan',
+ GANN_BOX = 'gann_box',
+
+ // Positions & Orders
+ LONG_POSITION = 'long_position',
+ SHORT_POSITION = 'short_position',
+ STOP_LOSS = 'stop_loss',
+ TAKE_PROFIT = 'take_profit',
+ ENTRY_ORDER = 'entry_order',
+
+ // Annotations
+ TEXT = 'text',
+ CALLOUT = 'callout',
+ LABEL = 'label',
+ PRICE_NOTE = 'price_note',
+
+ // Measurement
+ MEASURE = 'measure',
+ ANGLE = 'angle',
+}
+
+export enum PositionType {
+ LONG = 'long',
+ SHORT = 'short',
+}
+
+export enum OrderType {
+ ENTRY = 'entry',
+ EXIT = 'exit',
+ STOP_LOSS = 'stop_loss',
+ TAKE_PROFIT = 'take_profit',
+}
+
+// ==================== DATA STRUCTURES ====================
+
+interface DrawingObject {
+ id: string;
+ type: DrawingTool;
+ points: ChartPoint<Time>[];
+ style: DrawingStyle;
+ locked?: boolean;
+ visible?: boolean;
+ data?: any; // Additional tool-specific data
+}
+
+interface DrawingStyle {
+ color: string;
+ lineWidth: number;
+ lineStyle: 'solid' | 'dashed' | 'dotted';
+ fillColor?: string;
+ fillOpacity?: number;
+ textColor?: string;
+ fontSize?: number;
+ showLabels?: boolean;
+}
+
+interface FibonacciLevel {
+ level: number;
+ label: string;
+ color: string;
+ showLabel: boolean;
+}
+
+interface PositionMarker {
+ id: string;
+ type: PositionType;
+ orderType: OrderType;
+ time: Time;
+ price: number;
+ quantity?: number;
+ label?: string;
+ pnl?: number;
+ color: string;
+}
+
+interface ToolkitOptions extends PluginOptions {
+ // Default styles
+ defaultLineColor?: string;
+ defaultFillColor?: string;
+ defaultTextColor?: string;
+ defaultLineWidth?: number;
+
+ // Fibonacci levels
+ fibonacciLevels?: FibonacciLevel[];
+
+ // Position colors
+ longColor?: string;
+ shortColor?: string;
+ profitColor?: string;
+ lossColor?: string;
+
+ // Behavior
+ snapToPrice?: boolean;
+ snapToTime?: boolean;
+ showMagnetMode?: boolean;
+}
+
+// ==================== PANE VIEW ====================
+
+class ToolkitPaneView implements IPrimitivePaneView {
+ private _drawings: DrawingObject[] = [];
+ private _positions: PositionMarker[] = [];
+ private _options: ToolkitOptions;
+ private _chart: IChartApi | null = null;
+ private _series: ISeriesApi<SeriesType, Time> | null = null;
+ private _selectedDrawingId: string | null = null;
+ private _hoveredDrawingId: string | null = null;
+
+ constructor(options: ToolkitOptions) {
+ this._options = options;
+ }
+
+ public setSelectedDrawing(id: string | null): void {
+ this._selectedDrawingId = id;
+ }
+
+ public setHoveredDrawing(id: string | null): void {
+ this._hoveredDrawingId = id;
+ }
+
+ update(
+ drawings: DrawingObject[],
+ positions: PositionMarker[],
+ chart: IChartApi,
+ series: ISeriesApi<SeriesType, Time>
+ ): void {
+ this._drawings = drawings;
+ this._positions = positions;
+ this._chart = chart;
+ this._series = series;
+ }
+
+ renderer(): any {
+ return {
+ draw: (target: any) => {
+ if (!this._chart || !this._series) return;
+
+ // Removed rendering logs - they cause severe lag on every frame
+
+ target.useBitmapCoordinateSpace((scope: any) => {
+ const ctx = scope.context;
+
+ // Apply scaling for high DPI displays
+ const scaleX = scope.horizontalPixelRatio || 1;
+ const scaleY = scope.verticalPixelRatio || 1;
+
+ ctx.save();
+ ctx.scale(scaleX, scaleY);
+
+ // Calculate logical dimensions (unscaled)
+ const logicalWidth = scope.bitmapSize.width / scaleX;
+ const logicalHeight = scope.bitmapSize.height / scaleY;
+
+ // Draw all objects
+ this._drawings.forEach(drawing => {
+ if (drawing.visible !== false) {
+ this.drawObject(ctx, drawing, logicalWidth, logicalHeight);
+ }
+ });
+
+ // Draw position markers
+ this._positions.forEach(position => {
+ this.drawPosition(ctx, position);
+ });
+
+ ctx.restore();
+ });
+ }
+ };
+ }
+
+ private drawObject(
+ ctx: CanvasRenderingContext2D,
+ drawing: DrawingObject,
+ canvasWidth: number,
+ canvasHeight: number
+ ): void {
+ const coords = this.getCoordinates(drawing.points);
+ // Reduced logging - only log when coordinates are null (error case)
+
+ if (coords.some(c => c === null)) {
+ console.warn('[TradingToolkit] Skipping drawing - null coordinates:', { type: drawing.type, points: drawing.points });
+ return;
+ }
+
+ // Check if drawing is selected or hovered
+ const isSelected = drawing.id === this._selectedDrawingId;
+ const isHovered = drawing.id === this._hoveredDrawingId;
+
+ // Apply selection/hover styling
+ if (isSelected) {
+ this.applyStyle(ctx, {
+ ...drawing.style,
+ color: '#FF8800', // Bloomberg orange for selection
+ lineWidth: (drawing.style.lineWidth || 2) + 1, // Thicker when selected
+ });
+ } else if (isHovered) {
+ this.applyStyle(ctx, {
+ ...drawing.style,
+ color: '#00D66F', // Green for hover
+ });
+ } else {
+ this.applyStyle(ctx, drawing.style);
+ }
+
+ switch (drawing.type) {
+ case DrawingTool.TREND_LINE:
+ this.drawTrendLine(ctx, coords as Coordinate[][], drawing);
+ break;
+ case DrawingTool.HORIZONTAL_LINE:
+ this.drawHorizontalLine(ctx, coords as Coordinate[][], drawing, canvasWidth);
+ break;
+ case DrawingTool.VERTICAL_LINE:
+ this.drawVerticalLine(ctx, coords as Coordinate[][], drawing, canvasHeight);
+ break;
+ case DrawingTool.RAY:
+ this.drawRay(ctx, coords as Coordinate[][], drawing);
+ break;
+ case DrawingTool.PARALLEL_CHANNEL:
+ this.drawChannel(ctx, coords as Coordinate[][], drawing);
+ break;
+ case DrawingTool.REGRESSION_CHANNEL:
+ this.drawRegressionChannel(ctx, coords as Coordinate[][], drawing);
+ break;
+ case DrawingTool.PITCHFORK:
+ this.drawPitchfork(ctx, coords as Coordinate[][], drawing);
+ break;
+ case DrawingTool.RECTANGLE:
+ this.drawRectangle(ctx, coords as Coordinate[][], drawing);
+ break;
+ case DrawingTool.ELLIPSE:
+ this.drawEllipse(ctx, coords as Coordinate[][], drawing);
+ break;
+ case DrawingTool.TRIANGLE:
+ this.drawTriangle(ctx, coords as Coordinate[][], drawing);
+ break;
+ case DrawingTool.FIBO_RETRACEMENT:
+ this.drawFibonacci(ctx, coords as Coordinate[][], drawing);
+ break;
+ case DrawingTool.LONG_POSITION:
+ case DrawingTool.SHORT_POSITION:
+ this.drawPositionBox(ctx, coords as Coordinate[][], drawing);
+ break;
+ case DrawingTool.TEXT:
+ this.drawText(ctx, coords as Coordinate[][], drawing);
+ break;
+ case DrawingTool.CALLOUT:
+ this.drawCallout(ctx, coords as Coordinate[][], drawing);
+ break;
+ case DrawingTool.ARROW:
+ this.drawArrow(ctx, coords as Coordinate[][], drawing);
+ break;
+ default:
+ console.warn('[TradingToolkit] No renderer for tool type:', drawing.type);
+ }
+ }
+
+ private drawTrendLine(
+ ctx: CanvasRenderingContext2D,
+ coords: Coordinate[][],
+ drawing: DrawingObject
+ ): void {
+ if (coords.length < 2) return;
+
+ const [x1, y1] = coords[0];
+ const [x2, y2] = coords[1];
+
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(x2, y2);
+ ctx.stroke();
+
+ // Draw anchor points
+ this.drawAnchor(ctx, x1, y1, drawing.style.color);
+ this.drawAnchor(ctx, x2, y2, drawing.style.color);
+ }
+
+ private drawHorizontalLine(
+ ctx: CanvasRenderingContext2D,
+ coords: Coordinate[][],
+ drawing: DrawingObject,
+ canvasWidth: number
+ ): void {
+ if (coords.length < 1) return;
+
+ const [x, y] = coords[0];
+
+ // Draw line across entire chart width
+ ctx.beginPath();
+ ctx.moveTo(0, y);
+ ctx.lineTo(canvasWidth, y);
+ ctx.stroke();
+
+ // Draw anchor point
+ this.drawAnchor(ctx, x, y, drawing.style.color);
+ }
+
+ private drawVerticalLine(
+ ctx: CanvasRenderingContext2D,
+ coords: Coordinate[][],
+ drawing: DrawingObject,
+ canvasHeight: number
+ ): void {
+ if (coords.length < 1) return;
+
+ const [x, y] = coords[0];
+
+ // Draw line across entire chart height
+ ctx.beginPath();
+ ctx.moveTo(x, 0);
+ ctx.lineTo(x, canvasHeight);
+ ctx.stroke();
+
+ // Draw anchor point
+ this.drawAnchor(ctx, x, y, drawing.style.color);
+ }
+
+ private drawRay(
+ ctx: CanvasRenderingContext2D,
+ coords: Coordinate[][],
+ drawing: DrawingObject
+ ): void {
+ if (coords.length < 2) return;
+
+ const [x1, y1] = coords[0];
+ const [x2, y2] = coords[1];
+
+ // Calculate direction and extend the line to canvas edge
+ const dx = x2 - x1;
+ const dy = y2 - y1;
+ const angle = Math.atan2(dy, dx);
+
+ // Extend line to a very large distance in the direction
+ const extendDistance = 10000;
+ const x3 = x1 + Math.cos(angle) * extendDistance;
+ const y3 = y1 + Math.sin(angle) * extendDistance;
+
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(x3, y3);
+ ctx.stroke();
+
+ // Draw anchor points
+ this.drawAnchor(ctx, x1, y1, drawing.style.color);
+ this.drawAnchor(ctx, x2, y2, drawing.style.color);
+ }
+
+ private drawTriangle(
+ ctx: CanvasRenderingContext2D,
+ coords: Coordinate[][],
+ drawing: DrawingObject
+ ): void {
+ if (coords.length < 3) return;
+
+ const [x1, y1] = coords[0];
+ const [x2, y2] = coords[1];
+ const [x3, y3] = coords[2];
+
+ // Fill
+ if (drawing.style.fillColor) {
+ ctx.fillStyle = drawing.style.fillColor;
+ ctx.globalAlpha = drawing.style.fillOpacity || 0.2;
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(x2, y2);
+ ctx.lineTo(x3, y3);
+ ctx.closePath();
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ }
+
+ // Border
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(x2, y2);
+ ctx.lineTo(x3, y3);
+ ctx.closePath();
+ ctx.stroke();
+
+ // Anchors
+ this.drawAnchor(ctx, x1, y1, drawing.style.color);
+ this.drawAnchor(ctx, x2, y2, drawing.style.color);
+ this.drawAnchor(ctx, x3, y3, drawing.style.color);
+ }
+
+ private drawChannel(
+ ctx: CanvasRenderingContext2D,
+ coords: Coordinate[][],
+ drawing: DrawingObject
+ ): void {
+ if (coords.length < 3) return;
+
+ const [x1, y1] = coords[0];
+ const [x2, y2] = coords[1];
+ const [x3, y3] = coords[2];
+
+ // Calculate parallel offset
+ const dx = x2 - x1;
+ const dy = y2 - y1;
+ const offsetY = y3 - y1;
+
+ // Main trend line
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(x2, y2);
+ ctx.stroke();
+
+ // Parallel line
+ ctx.beginPath();
+ ctx.moveTo(x1, y1 + offsetY);
+ ctx.lineTo(x2, y2 + offsetY);
+ ctx.stroke();
+
+ // Fill channel if specified
+ if (drawing.style.fillColor) {
+ ctx.fillStyle = drawing.style.fillColor;
+ ctx.globalAlpha = drawing.style.fillOpacity || 0.1;
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(x2, y2);
+ ctx.lineTo(x2, y2 + offsetY);
+ ctx.lineTo(x1, y1 + offsetY);
+ ctx.closePath();
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ }
+
+ // Anchor points
+ this.drawAnchor(ctx, x1, y1, drawing.style.color);
+ this.drawAnchor(ctx, x2, y2, drawing.style.color);
+ this.drawAnchor(ctx, x3, y3, drawing.style.color);
+ }
+
+ private drawRegressionChannel(
+ ctx: CanvasRenderingContext2D,
+ coords: Coordinate[][],
+ drawing: DrawingObject
+ ): void {
+ if (coords.length < 3) return;
+
+ const [x1, y1] = coords[0];
+ const [x2, y2] = coords[1];
+ const [x3, y3] = coords[2];
+
+ // Calculate regression line (simplified - just uses two points)
+ const slope = (y2 - y1) / (x2 - x1);
+
+ // Calculate channel width based on third point
+ const channelWidth = Math.abs(y3 - y1);
+
+ // Draw center regression line
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(x2, y2);
+ ctx.stroke();
+
+ // Draw upper channel line
+ ctx.beginPath();
+ ctx.moveTo(x1, y1 - channelWidth);
+ ctx.lineTo(x2, y2 - channelWidth);
+ ctx.stroke();
+
+ // Draw lower channel line
+ ctx.beginPath();
+ ctx.moveTo(x1, y1 + channelWidth);
+ ctx.lineTo(x2, y2 + channelWidth);
+ ctx.stroke();
+
+ // Fill channel
+ if (drawing.style.fillColor) {
+ ctx.fillStyle = drawing.style.fillColor;
+ ctx.globalAlpha = drawing.style.fillOpacity || 0.1;
+
+ // Upper half
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(x2, y2);
+ ctx.lineTo(x2, y2 - channelWidth);
+ ctx.lineTo(x1, y1 - channelWidth);
+ ctx.closePath();
+ ctx.fill();
+
+ // Lower half
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(x2, y2);
+ ctx.lineTo(x2, y2 + channelWidth);
+ ctx.lineTo(x1, y1 + channelWidth);
+ ctx.closePath();
+ ctx.fill();
+
+ ctx.globalAlpha = 1;
+ }
+
+ // Anchor points
+ this.drawAnchor(ctx, x1, y1, drawing.style.color);
+ this.drawAnchor(ctx, x2, y2, drawing.style.color);
+ this.drawAnchor(ctx, x3, y3, drawing.style.color);
+ }
+
+ private drawPitchfork(
+ ctx: CanvasRenderingContext2D,
+ coords: Coordinate[][],
+ drawing: DrawingObject
+ ): void {
+ if (coords.length < 3) return;
+
+ // Andrew's Pitchfork: 3 points define the fork
+ // Point 1: Starting point (handle)
+ // Point 2: First prong end
+ // Point 3: Second prong end
+ const [x1, y1] = coords[0]; // Handle/pivot point
+ const [x2, y2] = coords[1]; // First peak/trough
+ const [x3, y3] = coords[2]; // Second peak/trough
+
+ // Calculate median line (from pivot to midpoint of peaks)
+ const midX = (x2 + x3) / 2;
+ const midY = (y2 + y3) / 2;
+
+ // Extend median line
+ const medianDx = midX - x1;
+ const medianDy = midY - y1;
+ const extendFactor = 2;
+ const medianEndX = x1 + medianDx * extendFactor;
+ const medianEndY = y1 + medianDy * extendFactor;
+
+ // Draw median line (center prong)
+ ctx.setLineDash([5, 5]); // Dashed for median
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(medianEndX, medianEndY);
+ ctx.stroke();
+ ctx.setLineDash([]); // Reset
+
+ // Draw upper prong (from pivot through first peak)
+ const upperDx = x2 - x1;
+ const upperDy = y2 - y1;
+ const upperEndX = x1 + upperDx * extendFactor;
+ const upperEndY = y1 + upperDy * extendFactor;
+
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(upperEndX, upperEndY);
+ ctx.stroke();
+
+ // Draw lower prong (from pivot through second peak)
+ const lowerDx = x3 - x1;
+ const lowerDy = y3 - y1;
+ const lowerEndX = x1 + lowerDx * extendFactor;
+ const lowerEndY = y1 + lowerDy * extendFactor;
+
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(lowerEndX, lowerEndY);
+ ctx.stroke();
+
+ // Fill the fork area
+ if (drawing.style.fillColor) {
+ ctx.fillStyle = drawing.style.fillColor;
+ ctx.globalAlpha = drawing.style.fillOpacity || 0.05;
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(upperEndX, upperEndY);
+ ctx.lineTo(lowerEndX, lowerEndY);
+ ctx.closePath();
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ }
+
+ // Anchor points
+ this.drawAnchor(ctx, x1, y1, drawing.style.color);
+ this.drawAnchor(ctx, x2, y2, drawing.style.color);
+ this.drawAnchor(ctx, x3, y3, drawing.style.color);
+ }
+
+ private drawRectangle(
+ ctx: CanvasRenderingContext2D,
+ coords: Coordinate[][],
+ drawing: DrawingObject
+ ): void {
+ if (coords.length < 2) return;
+
+ const [x1, y1] = coords[0];
+ const [x2, y2] = coords[1];
+
+ const x = Math.min(x1, x2);
+ const y = Math.min(y1, y2);
+ const width = Math.abs(x2 - x1);
+ const height = Math.abs(y2 - y1);
+
+ // Fill
+ if (drawing.style.fillColor) {
+ ctx.fillStyle = drawing.style.fillColor;
+ ctx.globalAlpha = drawing.style.fillOpacity || 0.2;
+ ctx.fillRect(x, y, width, height);
+ ctx.globalAlpha = 1;
+ }
+
+ // Border
+ ctx.strokeRect(x, y, width, height);
+
+ // Anchors
+ this.drawAnchor(ctx, x1, y1, drawing.style.color);
+ this.drawAnchor(ctx, x2, y2, drawing.style.color);
+ }
+
+ private drawEllipse(
+ ctx: CanvasRenderingContext2D,
+ coords: Coordinate[][],
+ drawing: DrawingObject
+ ): void {
+ if (coords.length < 2) return;
+
+ const [x1, y1] = coords[0];
+ const [x2, y2] = coords[1];
+
+ const centerX = (x1 + x2) / 2;
+ const centerY = (y1 + y2) / 2;
+ const radiusX = Math.abs(x2 - x1) / 2;
+ const radiusY = Math.abs(y2 - y1) / 2;
+
+ ctx.beginPath();
+ ctx.ellipse(centerX, centerY, radiusX, radiusY, 0, 0, 2 * Math.PI);
+
+ if (drawing.style.fillColor) {
+ ctx.fillStyle = drawing.style.fillColor;
+ ctx.globalAlpha = drawing.style.fillOpacity || 0.2;
+ ctx.fill();
+ ctx.globalAlpha = 1;
+ }
+
+ ctx.stroke();
+ }
+
+ private drawFibonacci(
+ ctx: CanvasRenderingContext2D,
+ coords: Coordinate[][],
+ drawing: DrawingObject
+ ): void {
+ if (coords.length < 2) return;
+
+ const [x1, y1] = coords[0];
+ const [x2, y2] = coords[1];
+
+ const levels = this._options.fibonacciLevels || [
+ { level: 0, label: '0%', color: '#787878', showLabel: true },
+ { level: 0.236, label: '23.6%', color: '#f23645', showLabel: true },
+ { level: 0.382, label: '38.2%', color: '#ff9800', showLabel: true },
+ { level: 0.5, label: '50%', color: '#fbbf24', showLabel: true },
+ { level: 0.618, label: '61.8%', color: '#4caf50', showLabel: true },
+ { level: 0.786, label: '78.6%', color: '#2196f3', showLabel: true },
+ { level: 1, label: '100%', color: '#787878', showLabel: true },
+ ];
+
+ const priceRange = Math.abs(y2 - y1);
+ const timeRange = Math.abs(x2 - x1);
+
+ levels.forEach(level => {
+ const y = y1 + (y2 - y1) * level.level;
+
+ // Line
+ ctx.strokeStyle = level.color;
+ ctx.setLineDash([5, 5]);
+ ctx.beginPath();
+ ctx.moveTo(x1, y);
+ ctx.lineTo(x2, y);
+ ctx.stroke();
+ ctx.setLineDash([]);
+
+ // Label
+ if (level.showLabel) {
+ ctx.fillStyle = level.color;
+ ctx.font = '11px monospace';
+ ctx.fillText(level.label, x2 + 5, y + 4);
+ }
+ });
+
+ // Main lines
+ ctx.strokeStyle = drawing.style.color;
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(x2, y1);
+ ctx.stroke();
+ ctx.beginPath();
+ ctx.moveTo(x1, y2);
+ ctx.lineTo(x2, y2);
+ ctx.stroke();
+ }
+
+ private drawPositionBox(
+ ctx: CanvasRenderingContext2D,
+ coords: Coordinate[][],
+ drawing: DrawingObject
+ ): void {
+ if (coords.length < 2) return;
+
+ const [x1, y1] = coords[0];
+ const [x2, y2] = coords[1];
+
+ const isLong = drawing.type === DrawingTool.LONG_POSITION;
+ const color = isLong ? (this._options.longColor || '#10b981') : (this._options.shortColor || '#ef4444');
+
+ // Position rectangle
+ ctx.fillStyle = color + '20';
+ ctx.strokeStyle = color;
+ ctx.lineWidth = 2;
+
+ const x = Math.min(x1, x2);
+ const y = Math.min(y1, y2);
+ const width = Math.abs(x2 - x1);
+ const height = Math.abs(y2 - y1);
+
+ ctx.fillRect(x, y, width, height);
+ ctx.strokeRect(x, y, width, height);
+
+ // Label
+ ctx.fillStyle = color;
+ ctx.font = 'bold 12px monospace';
+ ctx.fillText(isLong ? 'LONG' : 'SHORT', x + 5, y + 15);
+
+ // PnL if available
+ if (drawing.data?.pnl !== undefined) {
+ const pnlColor = drawing.data.pnl >= 0 ? this._options.profitColor || '#10b981' : this._options.lossColor || '#ef4444';
+ ctx.fillStyle = pnlColor;
+ ctx.fillText(`${drawing.data.pnl >= 0 ? '+' : ''}${drawing.data.pnl.toFixed(2)}%`, x + 5, y + 30);
+ }
+ }
+
+ private drawText(
+ ctx: CanvasRenderingContext2D,
+ coords: Coordinate[][],
+ drawing: DrawingObject
+ ): void {
+ if (coords.length < 1 || !drawing.data?.text) return;
+
+ const [x, y] = coords[0];
+
+ ctx.fillStyle = drawing.style.textColor || drawing.style.color;
+ ctx.font = `bold ${drawing.style.fontSize || 14}px monospace`;
+ ctx.fillText(drawing.data.text, x, y);
+
+ // Draw anchor point
+ this.drawAnchor(ctx, x, y, drawing.style.color);
+ }
+
+ private drawCallout(
+ ctx: CanvasRenderingContext2D,
+ coords: Coordinate[][],
+ drawing: DrawingObject
+ ): void {
+ if (coords.length < 1 || !drawing.data?.text) return;
+
+ const [x, y] = coords[0];
+ const text = drawing.data.text;
+
+ // Measure text
+ ctx.font = `${drawing.style.fontSize || 14}px monospace`;
+ const metrics = ctx.measureText(text);
+ const textWidth = metrics.width;
+ const textHeight = drawing.style.fontSize || 14;
+
+ // Callout box dimensions with padding
+ const padding = 8;
+ const boxWidth = textWidth + padding * 2;
+ const boxHeight = textHeight + padding * 2;
+
+ // Draw callout box background
+ ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
+ ctx.fillRect(x, y - boxHeight, boxWidth, boxHeight);
+
+ // Draw box border
+ ctx.strokeStyle = drawing.style.color;
+ ctx.lineWidth = 2;
+ ctx.strokeRect(x, y - boxHeight, boxWidth, boxHeight);
+
+ // Draw pointer line from box to anchor point
+ const pointerY = y + 15;
+ ctx.beginPath();
+ ctx.moveTo(x + boxWidth / 2, y);
+ ctx.lineTo(x + boxWidth / 2, pointerY);
+ ctx.stroke();
+
+ // Draw text inside box
+ ctx.fillStyle = drawing.style.textColor || '#FFFFFF';
+ ctx.fillText(text, x + padding, y - padding - 2);
+
+ // Draw anchor point at the bottom
+ this.drawAnchor(ctx, x + boxWidth / 2, pointerY, drawing.style.color);
+ }
+
+ private drawArrow(
+ ctx: CanvasRenderingContext2D,
+ coords: Coordinate[][],
+ drawing: DrawingObject
+ ): void {
+ if (coords.length < 2) return;
+
+ const [x1, y1] = coords[0];
+ const [x2, y2] = coords[1];
+
+ // Arrow line
+ ctx.beginPath();
+ ctx.moveTo(x1, y1);
+ ctx.lineTo(x2, y2);
+ ctx.stroke();
+
+ // Arrowhead
+ const angle = Math.atan2(y2 - y1, x2 - x1);
+ const headLength = 15;
+
+ ctx.beginPath();
+ ctx.moveTo(x2, y2);
+ ctx.lineTo(
+ x2 - headLength * Math.cos(angle - Math.PI / 6),
+ y2 - headLength * Math.sin(angle - Math.PI / 6)
+ );
+ ctx.moveTo(x2, y2);
+ ctx.lineTo(
+ x2 - headLength * Math.cos(angle + Math.PI / 6),
+ y2 - headLength * Math.sin(angle + Math.PI / 6)
+ );
+ ctx.stroke();
+ }
+
+ private drawPosition(
+ ctx: CanvasRenderingContext2D,
+ position: PositionMarker
+ ): void {
+ if (!this._chart || !this._series) return;
+
+ const x = this._chart.timeScale().timeToCoordinate(position.time);
+ const y = this._series.priceToCoordinate(position.price);
+
+ if (x === null || y === null) return;
+
+ const isLong = position.type === PositionType.LONG;
+ const size = 12;
+
+ // Triangle marker
+ ctx.fillStyle = position.color;
+ ctx.beginPath();
+
+ if (isLong) {
+ // Up triangle
+ ctx.moveTo(x, y - size);
+ ctx.lineTo(x - size / 2, y);
+ ctx.lineTo(x + size / 2, y);
+ } else {
+ // Down triangle
+ ctx.moveTo(x, y + size);
+ ctx.lineTo(x - size / 2, y);
+ ctx.lineTo(x + size / 2, y);
+ }
+
+ ctx.closePath();
+ ctx.fill();
+
+ // Border
+ ctx.strokeStyle = '#ffffff';
+ ctx.lineWidth = 1;
+ ctx.stroke();
+
+ // Label
+ if (position.label) {
+ ctx.fillStyle = '#ffffff';
+ ctx.font = '10px monospace';
+ ctx.fillText(position.label, x + 8, y + 4);
+ }
+ }
+
+ private getCoordinates(points: ChartPoint<Time>[]): (Coordinate[] | null)[] {
+ if (!this._chart || !this._series) return points.map(() => null);
+
+ return points.map(point => {
+ const x = this._chart!.timeScale().timeToCoordinate(point.time);
+ const y = this._series!.priceToCoordinate(point.price);
+ return x !== null && y !== null ? [x, y] : null;
+ });
+ }
+
+ private applyStyle(ctx: CanvasRenderingContext2D, style: DrawingStyle): void {
+ ctx.strokeStyle = style.color;
+ ctx.lineWidth = style.lineWidth;
+
+ switch (style.lineStyle) {
+ case 'dashed':
+ ctx.setLineDash([5, 5]);
+ break;
+ case 'dotted':
+ ctx.setLineDash([2, 2]);
+ break;
+ default:
+ ctx.setLineDash([]);
+ }
+ }
+
+ private drawAnchor(ctx: CanvasRenderingContext2D, x: number, y: number, color: string): void {
+ ctx.fillStyle = color;
+ ctx.strokeStyle = '#ffffff';
+ ctx.lineWidth = 2;
+
+ ctx.beginPath();
+ ctx.arc(x, y, 5, 0, 2 * Math.PI);
+ ctx.fill();
+ ctx.stroke();
+ }
+
+ // ==================== HIT DETECTION ====================
+
+ public findDrawingAtPoint(x: number, y: number): string | null {
+ const hitThreshold = 10; // Pixels
+
+ // Check drawings in reverse order (most recent on top)
+ for (let i = this._drawings.length - 1; i >= 0; i--) {
+ const drawing = this._drawings[i];
+ const coords = this.getCoordinates(drawing.points);
+
+ if (coords.some(c => c === null)) continue;
+
+ // Check based on drawing type
+ switch (drawing.type) {
+ case DrawingTool.TREND_LINE:
+ case DrawingTool.RAY:
+ case DrawingTool.HORIZONTAL_LINE:
+ case DrawingTool.VERTICAL_LINE:
+ if (this.hitTestLine(x, y, coords as Coordinate[][], hitThreshold)) {
+ return drawing.id;
+ }
+ break;
+
+ case DrawingTool.RECTANGLE:
+ case DrawingTool.PARALLEL_CHANNEL:
+ case DrawingTool.REGRESSION_CHANNEL:
+ if (this.hitTestRectangle(x, y, coords as Coordinate[][], hitThreshold)) {
+ return drawing.id;
+ }
+ break;
+
+ case DrawingTool.ELLIPSE:
+ if (this.hitTestEllipse(x, y, coords as Coordinate[][], hitThreshold)) {
+ return drawing.id;
+ }
+ break;
+
+ case DrawingTool.TEXT:
+ case DrawingTool.CALLOUT:
+ if (this.hitTestPoint(x, y, coords as Coordinate[][], hitThreshold)) {
+ return drawing.id;
+ }
+ break;
+
+ default:
+ // For other types, check if near any anchor point
+ if (this.hitTestAnyAnchor(x, y, coords as Coordinate[][], hitThreshold)) {
+ return drawing.id;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ public findAnchorAtPoint(drawingId: string, x: number, y: number): number {
+ const drawing = this._drawings.find(d => d.id === drawingId);
+ if (!drawing) return -1;
+
+ const coords = this.getCoordinates(drawing.points);
+ if (coords.some(c => c === null)) return -1;
+
+ const hitThreshold = 12; // Slightly larger for anchors
+
+ for (let i = 0; i < coords.length; i++) {
+ const [cx, cy] = coords[i];
+ const distance = Math.sqrt((x - cx) ** 2 + (y - cy) ** 2);
+ if (distance <= hitThreshold) {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+
+ private hitTestLine(x: number, y: number, coords: Coordinate[][], threshold: number): boolean {
+ if (coords.length < 2) return false;
+
+ const [x1, y1] = coords[0];
+ const [x2, y2] = coords[1];
+
+ // Calculate distance from point to line segment
+ const distance = this.pointToLineDistance(x, y, x1, y1, x2, y2);
+ return distance <= threshold;
+ }
+
+ private hitTestRectangle(x: number, y: number, coords: Coordinate[][], threshold: number): boolean {
+ if (coords.length < 2) return false;
+
+ const [x1, y1] = coords[0];
+ const [x2, y2] = coords[1];
+
+ const minX = Math.min(x1, x2);
+ const maxX = Math.max(x1, x2);
+ const minY = Math.min(y1, y2);
+ const maxY = Math.max(y1, y2);
+
+ // Check if point is inside or near the rectangle edges
+ if (x >= minX - threshold && x <= maxX + threshold &&
+ y >= minY - threshold && y <= maxY + threshold) {
+ // Inside bounding box
+ const nearLeft = Math.abs(x - minX) <= threshold;
+ const nearRight = Math.abs(x - maxX) <= threshold;
+ const nearTop = Math.abs(y - minY) <= threshold;
+ const nearBottom = Math.abs(y - maxY) <= threshold;
+
+ // On an edge or inside
+ return nearLeft || nearRight || nearTop || nearBottom ||
+ (x >= minX && x <= maxX && y >= minY && y <= maxY);
+ }
+
+ return false;
+ }
+
+ private hitTestEllipse(x: number, y: number, coords: Coordinate[][], threshold: number): boolean {
+ if (coords.length < 2) return false;
+
+ const [x1, y1] = coords[0];
+ const [x2, y2] = coords[1];
+
+ const centerX = (x1 + x2) / 2;
+ const centerY = (y1 + y2) / 2;
+ const radiusX = Math.abs(x2 - x1) / 2;
+ const radiusY = Math.abs(y2 - y1) / 2;
+
+ // Ellipse equation: ((x-cx)/rx)^2 + ((y-cy)/ry)^2 = 1
+ const normalized = ((x - centerX) / radiusX) ** 2 + ((y - centerY) / radiusY) ** 2;
+
+ // Check if on or near the ellipse boundary
+ return Math.abs(normalized - 1) * Math.min(radiusX, radiusY) <= threshold;
+ }
+
+ private hitTestPoint(x: number, y: number, coords: Coordinate[][], threshold: number): boolean {
+ if (coords.length < 1) return false;
+ const [cx, cy] = coords[0];
+ const distance = Math.sqrt((x - cx) ** 2 + (y - cy) ** 2);
+ return distance <= threshold * 2; // Larger hit area for text
+ }
+
+ private hitTestAnyAnchor(x: number, y: number, coords: Coordinate[][], threshold: number): boolean {
+ for (const [cx, cy] of coords) {
+ const distance = Math.sqrt((x - cx) ** 2 + (y - cy) ** 2);
+ if (distance <= threshold) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private pointToLineDistance(px: number, py: number, x1: number, y1: number, x2: number, y2: number): number {
+ const A = px - x1;
+ const B = py - y1;
+ const C = x2 - x1;
+ const D = y2 - y1;
+
+ const dot = A * C + B * D;
+ const lenSq = C * C + D * D;
+ let param = -1;
+
+ if (lenSq !== 0) {
+ param = dot / lenSq;
+ }
+
+ let xx, yy;
+
+ if (param < 0) {
+ xx = x1;
+ yy = y1;
+ } else if (param > 1) {
+ xx = x2;
+ yy = y2;
+ } else {
+ xx = x1 + param * C;
+ yy = y1 + param * D;
+ }
+
+ const dx = px - xx;
+ const dy = py - yy;
+ return Math.sqrt(dx * dx + dy * dy);
+ }
+}
+
+// ==================== PRIMITIVE ====================
+
+class ToolkitPrimitive implements ISeriesPrimitive<Time> {
+ private _paneViews: ToolkitPaneView[];
+ private _drawings: DrawingObject[] = [];
+ private _positions: PositionMarker[] = [];
+ private _options: ToolkitOptions;
+ private _param: SeriesAttachedParameter<Time> | null = null;
+
+ constructor(options: ToolkitOptions) {
+ this._options = options;
+ this._paneViews = [new ToolkitPaneView(options)];
+ }
+
+ attached(param: SeriesAttachedParameter<Time>): void {
+ this._param = param;
+ this.updateAllViews();
+ }
+
+ updateAllViews(): void {
+ if (!this._param) return;
+ this._paneViews.forEach(view =>
+ view.update(this._drawings, this._positions, this._param!.chart, this._param!.series)
+ );
+ this._param.requestUpdate();
+ }
+
+ paneViews(): readonly IPrimitivePaneView[] {
+ return this._paneViews;
+ }
+
+ addDrawing(drawing: DrawingObject): void {
+ this._drawings.push(drawing);
+ this.updateAllViews();
+ }
+
+ removeDrawing(id: string): void {
+ this._drawings = this._drawings.filter(d => d.id !== id);
+ this.updateAllViews();
+ }
+
+ addPosition(position: PositionMarker): void {
+ this._positions.push(position);
+ this.updateAllViews();
+ }
+
+ removePosition(id: string): void {
+ this._positions = this._positions.filter(p => p.id !== id);
+ this.updateAllViews();
+ }
+
+ getDrawings(): DrawingObject[] {
+ return [...this._drawings];
+ }
+
+ getPositions(): PositionMarker[] {
+ return [...this._positions];
+ }
+
+ clearAll(): void {
+ this._drawings = [];
+ this._positions = [];
+ this.updateAllViews();
+ }
+
+ // Selection methods
+ setSelectedDrawing(id: string | null): void {
+ this._paneViews.forEach(view => view.setSelectedDrawing(id));
+ this.updateAllViews();
+ }
+
+ setHoveredDrawing(id: string | null): void {
+ this._paneViews.forEach(view => view.setHoveredDrawing(id));
+ this.updateAllViews();
+ }
+
+ findDrawingAtPoint(x: number, y: number): string | null {
+ return this._paneViews[0]?.findDrawingAtPoint(x, y) || null;
+ }
+
+ findAnchorAtPoint(drawingId: string, x: number, y: number): number {
+ return this._paneViews[0]?.findAnchorAtPoint(drawingId, x, y) || -1;
+ }
+
+ // Update drawing coordinates (for dragging)
+ updateDrawingPoint(drawingId: string, pointIndex: number, newPoint: ChartPoint<Time>): void {
+ const drawing = this._drawings.find(d => d.id === drawingId);
+ if (drawing && pointIndex >= 0 && pointIndex < drawing.points.length) {
+ drawing.points[pointIndex] = newPoint;
+ this.updateAllViews();
+ }
+ }
+
+ // Move entire drawing
+ moveDrawing(drawingId: string, deltaTime: number, deltaPrice: number): void {
+ const drawing = this._drawings.find(d => d.id === drawingId);
+ if (drawing) {
+ drawing.points = drawing.points.map(point => ({
+ time: (point.time as number + deltaTime) as Time,
+ price: point.price + deltaPrice,
+ }));
+ this.updateAllViews();
+ }
+ }
+}
+
+// ==================== MAIN PLUGIN ====================
+
+export class TradingToolkitPlugin extends BasePlugin<Time> {
+ private toolkitPrimitive: ToolkitPrimitive | null = null;
+ private currentTool: DrawingTool | null = null;
+ private tempPoints: ChartPoint<Time>[] = [];
+ private drawingIdCounter: number = 0;
+ private positionIdCounter: number = 0;
+ private onToolDeactivated?: () => void;
+
+ // Selection and drag state
+ private selectedDrawingId: string | null = null;
+ private isDragging: boolean = false;
+ private draggedAnchorIndex: number = -1;
+ private dragStartPoint: ChartPoint<Time> | null = null;
+
+ constructor(options: Partial<ToolkitOptions> = {}) {
+ const defaultOptions: ToolkitOptions = {
+ visible: true,
+ interactive: true,
+ defaultLineColor: '#2196F3',
+ defaultFillColor: '#2196F320',
+ defaultTextColor: '#ffffff',
+ defaultLineWidth: 2,
+ longColor: '#10b981',
+ shortColor: '#ef4444',
+ profitColor: '#10b981',
+ lossColor: '#ef4444',
+ snapToPrice: true,
+ snapToTime: false,
+ showMagnetMode: true,
+ ...options
+ };
+
+ super(
+ {
+ id: 'trading-toolkit',
+ name: 'Trading Toolkit',
+ description: 'Complete TradingView-style drawing and analysis tools',
+ category: PluginCategory.DRAWING,
+ version: '1.0.0',
+ author: 'Fincept Terminal',
+ enabled: true
+ },
+ defaultOptions
+ );
+ }
+
+ protected createPrimitive(): ISeriesPrimitive<Time> | null {
+ this.toolkitPrimitive = new ToolkitPrimitive(this.options as ToolkitOptions);
+ return this.toolkitPrimitive;
+ }
+
+ // ==================== TOOL ACTIVATION ====================
+
+ public activateTool(tool: DrawingTool): void {
+ this.currentTool = tool;
+ this.tempPoints = [];
+ // Tool activated: ${tool}
+ }
+
+ public deactivateTool(): void {
+ this.currentTool = null;
+ this.tempPoints = [];
+
+ // Notify parent component that tool was deactivated
+ if (this.onToolDeactivated) {
+ this.onToolDeactivated();
+ }
+ }
+
+ public getCurrentTool(): DrawingTool | null {
+ return this.currentTool;
+ }
+
+ public setOnToolDeactivated(callback: () => void): void {
+ this.onToolDeactivated = callback;
+ }
+
+ // ==================== SELECTION & DRAGGING ====================
+
+ public handleMouseDown(point: ChartPoint<Time>, pixelX: number, pixelY: number): boolean {
+ if (!this.toolkitPrimitive) return false;
+
+ // If a drawing tool is active, let the normal click handler work
+ if (this.currentTool) return false;
+
+ // Check if clicking on an existing drawing
+ const hitDrawingId = this.toolkitPrimitive.findDrawingAtPoint(pixelX, pixelY);
+
+ if (hitDrawingId) {
+ this.selectedDrawingId = hitDrawingId;
+ this.toolkitPrimitive.setSelectedDrawing(hitDrawingId);
+
+ // Check if clicking on an anchor point
+ const anchorIndex = this.toolkitPrimitive.findAnchorAtPoint(hitDrawingId, pixelX, pixelY);
+
+ if (anchorIndex >= 0) {
+ // Start dragging anchor
+ this.isDragging = true;
+ this.draggedAnchorIndex = anchorIndex;
+ this.dragStartPoint = point;
+ return true; // Handled
+ } else {
+ // Start dragging entire drawing
+ this.isDragging = true;
+ this.draggedAnchorIndex = -1;
+ this.dragStartPoint = point;
+ return true; // Handled
+ }
+ } else {
+ // Clicked empty space - deselect
+ this.selectedDrawingId = null;
+ this.toolkitPrimitive.setSelectedDrawing(null);
+ }
+
+ return false;
+ }
+
+ public handleMouseMove(point: ChartPoint<Time>, pixelX: number, pixelY: number): void {
+ if (!this.toolkitPrimitive) return;
+
+ // Handle dragging
+ if (this.isDragging && this.dragStartPoint && this.selectedDrawingId) {
+ const deltaTime = (point.time as number) - (this.dragStartPoint.time as number);
+ const deltaPrice = point.price - this.dragStartPoint.price;
+
+ if (this.draggedAnchorIndex >= 0) {
+ // Dragging a specific anchor point
+ this.toolkitPrimitive.updateDrawingPoint(
+ this.selectedDrawingId,
+ this.draggedAnchorIndex,
+ point
+ );
+ } else {
+ // Dragging entire drawing
+ this.toolkitPrimitive.moveDrawing(this.selectedDrawingId, deltaTime, deltaPrice);
+ }
+
+ // Update drag start point for next move
+ this.dragStartPoint = point;
+ return;
+ }
+
+ // Handle hover (when not dragging and no tool active)
+ if (!this.currentTool && !this.isDragging) {
+ const hoveredDrawingId = this.toolkitPrimitive.findDrawingAtPoint(pixelX, pixelY);
+ this.toolkitPrimitive.setHoveredDrawing(hoveredDrawingId);
+ }
+ }
+
+ public handleMouseUp(): void {
+ this.isDragging = false;
+ this.draggedAnchorIndex = -1;
+ this.dragStartPoint = null;
+ }
+
+ public selectDrawing(id: string | null): void {
+ this.selectedDrawingId = id;
+ if (this.toolkitPrimitive) {
+ this.toolkitPrimitive.setSelectedDrawing(id);
+ }
+ }
+
+ public getSelectedDrawingId(): string | null {
+ return this.selectedDrawingId;
+ }
+
+ // ==================== DRAWING ====================
+
+ public handleClick(point: ChartPoint<Time>): void {
+ if (!this.currentTool || !this.toolkitPrimitive) return;
+
+ this.tempPoints.push(point);
+
+ const requiredPoints = this.getRequiredPoints(this.currentTool);
+
+ if (this.tempPoints.length >= requiredPoints) {
+ this.completeDrawing();
+ }
+ }
+
+ private completeDrawing(): void {
+ if (!this.currentTool || !this.toolkitPrimitive) return;
+
+ const drawing: DrawingObject = {
+ id: `drawing-${++this.drawingIdCounter}`,
+ type: this.currentTool,
+ points: [...this.tempPoints],
+ style: {
+ color: (this.options as ToolkitOptions).defaultLineColor || '#2196F3',
+ lineWidth: (this.options as ToolkitOptions).defaultLineWidth || 2,
+ lineStyle: 'solid',
+ fillColor: (this.options as ToolkitOptions).defaultFillColor,
+ fillOpacity: 0.2,
+ textColor: (this.options as ToolkitOptions).defaultTextColor || '#FFFFFF',
+ fontSize: 14,
+ showLabels: true,
+ },
+ visible: true,
+ locked: false,
+ };
+
+ // For text-based annotations, prompt for text input
+ if (this.currentTool === DrawingTool.TEXT || this.currentTool === DrawingTool.CALLOUT) {
+ const text = prompt('Enter annotation text:');
+ if (text) {
+ drawing.data = { text };
+ } else {
+ // User cancelled, don't create the drawing
+ this.tempPoints = [];
+ return;
+ }
+ }
+
+ // Drawing completed
+ this.toolkitPrimitive.addDrawing(drawing);
+ this.tempPoints = [];
+
+ // Auto-deselect tool after completing drawing (TradingView behavior)
+ this.deactivateTool();
+
+ // Force redraw
+ if (this.chart) {
+ this.chart.timeScale().scrollToPosition(0, false);
+ }
+ }
+
+ private getRequiredPoints(tool: DrawingTool): number {
+ switch (tool) {
+ case DrawingTool.HORIZONTAL_LINE:
+ case DrawingTool.VERTICAL_LINE:
+ case DrawingTool.TEXT:
+ case DrawingTool.CALLOUT:
+ return 1;
+ case DrawingTool.TREND_LINE:
+ case DrawingTool.RAY:
+ case DrawingTool.RECTANGLE:
+ case DrawingTool.ELLIPSE:
+ case DrawingTool.ARROW:
+ case DrawingTool.FIBO_RETRACEMENT:
+ case DrawingTool.FIBO_EXTENSION:
+ case DrawingTool.LONG_POSITION:
+ case DrawingTool.SHORT_POSITION:
+ return 2;
+ case DrawingTool.PARALLEL_CHANNEL:
+ case DrawingTool.REGRESSION_CHANNEL:
+ case DrawingTool.TRIANGLE:
+ case DrawingTool.PITCHFORK:
+ return 3;
+ default:
+ return 2;
+ }
+ }
+
+ // ==================== POSITIONS ====================
+
+ public addLongPosition(
+ entryTime: Time,
+ entryPrice: number,
+ exitTime?: Time,
+ exitPrice?: number,
+ options?: Partial<PositionMarker>
+ ): string {
+ return this.addPosition(PositionType.LONG, OrderType.ENTRY, entryTime, entryPrice, options);
+ }
+
+ public addShortPosition(
+ entryTime: Time,
+ entryPrice: number,
+ exitTime?: Time,
+ exitPrice?: number,
+ options?: Partial<PositionMarker>
+ ): string {
+ return this.addPosition(PositionType.SHORT, OrderType.ENTRY, entryTime, entryPrice, options);
+ }
+
+ public addPosition(
+ type: PositionType,
+ orderType: OrderType,
+ time: Time,
+ price: number,
+ options?: Partial<PositionMarker>
+ ): string {
+ if (!this.toolkitPrimitive) return '';
+
+ const color = type === PositionType.LONG
+ ? ((this.options as ToolkitOptions).longColor || '#10b981')
+ : ((this.options as ToolkitOptions).shortColor || '#ef4444');
+
+ const position: PositionMarker = {
+ id: `position-${++this.positionIdCounter}`,
+ type,
+ orderType,
+ time,
+ price,
+ color,
+ ...options,
+ };
+
+ this.toolkitPrimitive.addPosition(position);
+ this.chart?.timeScale().fitContent();
+
+ return position.id;
+ }
+
+ // ==================== MANAGEMENT ====================
+
+ public getDrawings(): DrawingObject[] {
+ return this.toolkitPrimitive?.getDrawings() || [];
+ }
+
+ public getPositions(): PositionMarker[] {
+ return this.toolkitPrimitive?.getPositions() || [];
+ }
+
+ public removeDrawing(id: string): void {
+ if (this.toolkitPrimitive) {
+ this.toolkitPrimitive.removeDrawing(id);
+ this.chart?.timeScale().fitContent();
+ }
+ }
+
+ public removePosition(id: string): void {
+ if (this.toolkitPrimitive) {
+ this.toolkitPrimitive.removePosition(id);
+ this.chart?.timeScale().fitContent();
+ }
+ }
+
+ public clearAll(): void {
+ if (this.toolkitPrimitive) {
+ this.toolkitPrimitive.clearAll();
+ this.chart?.timeScale().fitContent();
+ }
+ }
+
+ public clearDrawings(): void {
+ if (this.toolkitPrimitive) {
+ this.getDrawings().forEach(d => this.removeDrawing(d.id));
+ }
+ }
+
+ public deleteLastDrawing(): void {
+ const drawings = this.getDrawings();
+ if (drawings.length > 0) {
+ this.removeDrawing(drawings[drawings.length - 1].id);
+ }
+ }
+
+ public clearPositions(): void {
+ if (this.toolkitPrimitive) {
+ this.getPositions().forEach(p => this.removePosition(p.id));
+ }
+ }
+}
+
+// Export types
+export type { DrawingObject, DrawingStyle, PositionMarker, ToolkitOptions };
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/TrendLinePlugin.ts b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/TrendLinePlugin.ts
new file mode 100644
index 000000000..e7699108b
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/TrendLinePlugin.ts
@@ -0,0 +1,320 @@
+/**
+ * Trend Line Plugin
+ *
+ * Interactive trend line drawing tool for technical analysis.
+ * Users can draw trend lines by clicking two points on the chart.
+ * Based on https://tradingview.github.io/lightweight-charts/plugin-examples/trend-line
+ */
+
+import type {
+ ISeriesPrimitive,
+ SeriesAttachedParameter,
+ Time,
+ IPrimitivePaneView,
+ Coordinate,
+ IChartApi,
+ ISeriesApi,
+ SeriesType
+} from 'lightweight-charts';
+import { BasePlugin } from './BasePlugin';
+import { PluginCategory, PluginOptions, IDrawingPlugin, ChartPoint } from './types';
+
+interface TrendLineOptions extends PluginOptions {
+ extendLeft?: boolean;
+ extendRight?: boolean;
+ showPrice?: boolean;
+ dashArray?: number[];
+}
+
+interface TrendLine {
+ id: string;
+ point1: ChartPoint<Time>;
+ point2: ChartPoint<Time>;
+ color: string;
+ lineWidth: number;
+ extendLeft: boolean;
+ extendRight: boolean;
+}
+
+class TrendLinePaneView implements IPrimitivePaneView {
+ private _lines: TrendLine[] = [];
+ private _options: TrendLineOptions;
+ private _chart: IChartApi | null = null;
+ private _series: ISeriesApi<SeriesType, Time> | null = null;
+
+ constructor(options: TrendLineOptions) {
+ this._options = options;
+ }
+
+ update(lines: TrendLine[], chart: IChartApi, series: ISeriesApi<SeriesType, Time>): void {
+ this._lines = lines;
+ this._chart = chart;
+ this._series = series;
+ }
+
+ renderer(): any {
+ return {
+ draw: (target: any) => {
+ if (!this._chart || !this._series) return;
+
+ target.useBitmapCoordinateSpace((scope: any) => {
+ const ctx = scope.context;
+
+ this._lines.forEach(line => {
+ const x1 = this._chart!.timeScale().timeToCoordinate(line.point1.time);
+ const y1 = this._series!.priceToCoordinate(line.point1.price);
+ const x2 = this._chart!.timeScale().timeToCoordinate(line.point2.time);
+ const y2 = this._series!.priceToCoordinate(line.point2.price);
+
+ if (x1 === null || y1 === null || x2 === null || y2 === null) return;
+
+ // Calculate slope
+ const slope = (y2 - y1) / (x2 - x1);
+
+ // Determine start and end points (as numbers, not Coordinates)
+ let startX: number = x1 as number;
+ let startY: number = y1 as number;
+ let endX: number = x2 as number;
+ let endY: number = y2 as number;
+
+ if (line.extendLeft) {
+ startX = 0;
+ startY = (y1 as number) - slope * (x1 as number);
+ }
+
+ if (line.extendRight) {
+ endX = scope.bitmapSize.width;
+ endY = (y1 as number) + slope * (endX - (x1 as number));
+ }
+
+ // Draw line
+ ctx.strokeStyle = line.color;
+ ctx.lineWidth = line.lineWidth;
+
+ if (this._options.dashArray) {
+ ctx.setLineDash(this._options.dashArray);
+ } else {
+ ctx.setLineDash([]);
+ }
+
+ ctx.beginPath();
+ ctx.moveTo(startX, startY);
+ ctx.lineTo(endX, endY);
+ ctx.stroke();
+
+ // Draw anchor points
+ this.drawAnchor(ctx, x1, y1, line.color);
+ this.drawAnchor(ctx, x2, y2, line.color);
+ });
+ });
+ }
+ };
+ }
+
+ private drawAnchor(ctx: CanvasRenderingContext2D, x: number, y: number, color: string): void {
+ ctx.fillStyle = color;
+ ctx.strokeStyle = '#ffffff';
+ ctx.lineWidth = 2;
+
+ ctx.beginPath();
+ ctx.arc(x, y, 5, 0, 2 * Math.PI);
+ ctx.fill();
+ ctx.stroke();
+ }
+}
+
+class TrendLinePrimitive implements ISeriesPrimitive<Time> {
+ private _paneViews: TrendLinePaneView[];
+ private _lines: TrendLine[] = [];
+ private _options: TrendLineOptions;
+ private _param: SeriesAttachedParameter<Time> | null = null;
+
+ constructor(options: TrendLineOptions) {
+ this._options = options;
+ this._paneViews = [new TrendLinePaneView(options)];
+ }
+
+ attached(param: SeriesAttachedParameter<Time>): void {
+ this._param = param;
+ this.updateAllViews();
+ }
+
+ updateAllViews(): void {
+ if (!this._param) return;
+ this._paneViews.forEach(view => view.update(this._lines, this._param!.chart, this._param!.series));
+ this._param.requestUpdate();
+ }
+
+ paneViews(): readonly IPrimitivePaneView[] {
+ return this._paneViews;
+ }
+
+ addLine(line: TrendLine): void {
+ this._lines.push(line);
+ this.updateAllViews();
+ }
+
+ removeLine(lineId: string): void {
+ this._lines = this._lines.filter(l => l.id !== lineId);
+ this.updateAllViews();
+ }
+
+ getLines(): TrendLine[] {
+ return [...this._lines];
+ }
+
+ clearLines(): void {
+ this._lines = [];
+ this.updateAllViews();
+ }
+}
+
+export class TrendLinePlugin extends BasePlugin<Time> implements IDrawingPlugin<Time> {
+ private trendLinePrimitive: TrendLinePrimitive | null = null;
+ private isDrawingMode: boolean = false;
+ private tempPoint1: ChartPoint<Time> | null = null;
+ private lineIdCounter: number = 0;
+
+ constructor(options: Partial<TrendLineOptions> = {}) {
+ const defaultOptions: TrendLineOptions = {
+ visible: true,
+ interactive: true,
+ color: '#2196F3',
+ lineWidth: 2,
+ extendLeft: false,
+ extendRight: true,
+ showPrice: true,
+ dashArray: undefined,
+ ...options
+ };
+
+ super(
+ {
+ id: 'trendline',
+ name: 'Trend Line',
+ description: 'Draw trend lines for technical analysis',
+ category: PluginCategory.DRAWING,
+ version: '1.0.0',
+ author: 'Fincept Terminal',
+ enabled: true
+ },
+ defaultOptions
+ );
+ }
+
+ protected createPrimitive(): ISeriesPrimitive<Time> | null {
+ this.trendLinePrimitive = new TrendLinePrimitive(this.options as TrendLineOptions);
+ return this.trendLinePrimitive;
+ }
+
+ /**
+ * Start drawing mode
+ */
+ public startDrawing(): void {
+ this.isDrawingMode = true;
+ this.tempPoint1 = null;
+ console.log('Trend line drawing mode activated');
+ }
+
+ /**
+ * Stop drawing mode
+ */
+ public stopDrawing(): void {
+ this.isDrawingMode = false;
+ this.tempPoint1 = null;
+ console.log('Trend line drawing mode deactivated');
+ }
+
+ /**
+ * Check if in drawing mode
+ */
+ public isDrawing(): boolean {
+ return this.isDrawingMode;
+ }
+
+ /**
+ * Handle click to add point
+ */
+ public handleClick(point: ChartPoint<Time>): void {
+ if (!this.isDrawingMode || !this.trendLinePrimitive) return;
+
+ if (!this.tempPoint1) {
+ // First point
+ this.tempPoint1 = point;
+ console.log('First point set:', point);
+ } else {
+ // Second point - complete the line
+ this.addLine(this.tempPoint1, point);
+ this.tempPoint1 = null;
+
+ // Optionally stop drawing after one line (can be configured)
+ // this.stopDrawing();
+ }
+ }
+
+ /**
+ * Add a trend line
+ */
+ public addLine(point1: ChartPoint<Time>, point2: ChartPoint<Time>): void {
+ if (!this.trendLinePrimitive) return;
+
+ const line: TrendLine = {
+ id: `trendline-${++this.lineIdCounter}`,
+ point1,
+ point2,
+ color: this.options.color || '#2196F3',
+ lineWidth: this.options.lineWidth || 2,
+ extendLeft: (this.options as TrendLineOptions).extendLeft || false,
+ extendRight: (this.options as TrendLineOptions).extendRight || true,
+ };
+
+ this.trendLinePrimitive.addLine(line);
+
+ // Request update
+ if (this.series) {
+ this.chart?.timeScale().fitContent();
+ }
+
+ console.log('Trend line added:', line);
+ }
+
+ /**
+ * Remove a specific line
+ */
+ public removeLine(lineId: string): void {
+ if (this.trendLinePrimitive) {
+ this.trendLinePrimitive.removeLine(lineId);
+ this.chart?.timeScale().fitContent();
+ }
+ }
+
+ /**
+ * Get all lines
+ */
+ public getLines(): TrendLine[] {
+ return this.trendLinePrimitive?.getLines() || [];
+ }
+
+ /**
+ * Clear all lines
+ */
+ public clear(): void {
+ if (this.trendLinePrimitive) {
+ this.trendLinePrimitive.clearLines();
+ this.chart?.timeScale().fitContent();
+ console.log('All trend lines cleared');
+ }
+ }
+
+ protected onOptionsChanged(): void {
+ // Update existing lines with new options
+ if (this.trendLinePrimitive) {
+ const lines = this.trendLinePrimitive.getLines();
+ lines.forEach(line => {
+ line.color = this.options.color || line.color;
+ line.lineWidth = this.options.lineWidth || line.lineWidth;
+ });
+ }
+ super.onOptionsChanged();
+ }
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/VerticalLinePlugin.ts b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/VerticalLinePlugin.ts
new file mode 100644
index 000000000..fce726073
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/VerticalLinePlugin.ts
@@ -0,0 +1,258 @@
+/**
+ * Vertical Line Plugin
+ *
+ * Draws vertical lines at specific time points for marking important events.
+ * Based on https://tradingview.github.io/lightweight-charts/plugin-examples/vertical-line
+ */
+
+import type {
+ ISeriesPrimitive,
+ SeriesAttachedParameter,
+ Time,
+ IPrimitivePaneView,
+ Coordinate,
+ IChartApi
+} from 'lightweight-charts';
+import { BasePlugin } from './BasePlugin';
+import { PluginCategory, PluginOptions } from './types';
+
+interface VerticalLineOptions extends PluginOptions {
+ showLabel?: boolean;
+ labelBackgroundColor?: string;
+ labelTextColor?: string;
+ dashArray?: number[];
+}
+
+interface VerticalLineMarker {
+ id: string;
+ time: Time;
+ color: string;
+ lineWidth: number;
+ label?: string;
+ labelPosition?: 'top' | 'bottom';
+}
+
+class VerticalLinePaneView implements IPrimitivePaneView {
+ private _markers: VerticalLineMarker[] = [];
+ private _options: VerticalLineOptions;
+ private _chart: IChartApi | null = null;
+
+ constructor(options: VerticalLineOptions) {
+ this._options = options;
+ }
+
+ update(markers: VerticalLineMarker[], chart: IChartApi): void {
+ this._markers = markers;
+ this._chart = chart;
+ }
+
+ renderer(): any {
+ return {
+ draw: (target: any) => {
+ if (!this._chart) return;
+
+ target.useBitmapCoordinateSpace((scope: any) => {
+ const ctx = scope.context;
+ const height = scope.bitmapSize.height;
+
+ this._markers.forEach(marker => {
+ const x = this._chart!.timeScale().timeToCoordinate(marker.time);
+ if (x === null) return;
+
+ // Draw vertical line
+ ctx.strokeStyle = marker.color;
+ ctx.lineWidth = marker.lineWidth;
+
+ if (this._options.dashArray) {
+ ctx.setLineDash(this._options.dashArray);
+ } else {
+ ctx.setLineDash([]);
+ }
+
+ ctx.beginPath();
+ ctx.moveTo(x, 0);
+ ctx.lineTo(x, height);
+ ctx.stroke();
+
+ // Draw label if exists
+ if (marker.label && this._options.showLabel) {
+ this.drawLabel(ctx, x, marker, height);
+ }
+ });
+ });
+ }
+ };
+ }
+
+ private drawLabel(
+ ctx: CanvasRenderingContext2D,
+ x: number,
+ marker: VerticalLineMarker,
+ height: number
+ ): void {
+ const fontSize = 11;
+ const padding = 6;
+ const labelY = marker.labelPosition === 'bottom' ? height - 25 : 10;
+
+ ctx.font = `${fontSize}px monospace`;
+ const textWidth = ctx.measureText(marker.label!).width;
+
+ // Background
+ ctx.fillStyle = this._options.labelBackgroundColor || 'rgba(0, 0, 0, 0.8)';
+ ctx.fillRect(x - textWidth / 2 - padding, labelY, textWidth + padding * 2, fontSize + padding * 2);
+
+ // Border
+ ctx.strokeStyle = marker.color;
+ ctx.lineWidth = 1;
+ ctx.strokeRect(x - textWidth / 2 - padding, labelY, textWidth + padding * 2, fontSize + padding * 2);
+
+ // Text
+ ctx.fillStyle = this._options.labelTextColor || '#ffffff';
+ ctx.textAlign = 'center';
+ ctx.fillText(marker.label!, x, labelY + fontSize + padding - 2);
+ }
+}
+
+class VerticalLinePrimitive implements ISeriesPrimitive<Time> {
+ private _paneViews: VerticalLinePaneView[];
+ private _markers: VerticalLineMarker[] = [];
+ private _options: VerticalLineOptions;
+ private _param: SeriesAttachedParameter<Time> | null = null;
+
+ constructor(options: VerticalLineOptions) {
+ this._options = options;
+ this._paneViews = [new VerticalLinePaneView(options)];
+ }
+
+ attached(param: SeriesAttachedParameter<Time>): void {
+ this._param = param;
+ this.updateAllViews();
+ }
+
+ updateAllViews(): void {
+ if (!this._param) return;
+ this._paneViews.forEach(view => view.update(this._markers, this._param!.chart));
+ this._param.requestUpdate();
+ }
+
+ paneViews(): readonly IPrimitivePaneView[] {
+ return this._paneViews;
+ }
+
+ addMarker(marker: VerticalLineMarker): void {
+ this._markers.push(marker);
+ this.updateAllViews();
+ }
+
+ removeMarker(markerId: string): void {
+ this._markers = this._markers.filter(m => m.id !== markerId);
+ this.updateAllViews();
+ }
+
+ getMarkers(): VerticalLineMarker[] {
+ return [...this._markers];
+ }
+
+ clearMarkers(): void {
+ this._markers = [];
+ this.updateAllViews();
+ }
+}
+
+export class VerticalLinePlugin extends BasePlugin<Time> {
+ private verticalLinePrimitive: VerticalLinePrimitive | null = null;
+ private markerIdCounter: number = 0;
+
+ constructor(options: Partial<VerticalLineOptions> = {}) {
+ const defaultOptions: VerticalLineOptions = {
+ visible: true,
+ color: '#3f51b5',
+ lineWidth: 1,
+ showLabel: true,
+ labelBackgroundColor: 'rgba(0, 0, 0, 0.85)',
+ labelTextColor: '#ffffff',
+ dashArray: [5, 5],
+ ...options
+ };
+
+ super(
+ {
+ id: 'verticalline',
+ name: 'Vertical Line',
+ description: 'Mark specific time points with vertical lines',
+ category: PluginCategory.ANNOTATION,
+ version: '1.0.0',
+ author: 'Fincept Terminal',
+ enabled: true
+ },
+ defaultOptions
+ );
+ }
+
+ protected createPrimitive(): ISeriesPrimitive<Time> | null {
+ this.verticalLinePrimitive = new VerticalLinePrimitive(this.options as VerticalLineOptions);
+ return this.verticalLinePrimitive;
+ }
+
+ /**
+ * Add a vertical line marker at a specific time
+ */
+ public addMarker(
+ time: Time,
+ label?: string,
+ color?: string,
+ labelPosition?: 'top' | 'bottom'
+ ): string {
+ if (!this.verticalLinePrimitive) return '';
+
+ const markerId = `vline-${++this.markerIdCounter}`;
+ const marker: VerticalLineMarker = {
+ id: markerId,
+ time,
+ color: color || this.options.color || '#3f51b5',
+ lineWidth: this.options.lineWidth || 1,
+ label,
+ labelPosition: labelPosition || 'top',
+ };
+
+ this.verticalLinePrimitive.addMarker(marker);
+ this.chart?.timeScale().fitContent();
+
+ return markerId;
+ }
+
+ /**
+ * Remove a specific marker
+ */
+ public removeMarker(markerId: string): void {
+ if (this.verticalLinePrimitive) {
+ this.verticalLinePrimitive.removeMarker(markerId);
+ this.chart?.timeScale().fitContent();
+ }
+ }
+
+ /**
+ * Get all markers
+ */
+ public getMarkers(): VerticalLineMarker[] {
+ return this.verticalLinePrimitive?.getMarkers() || [];
+ }
+
+ /**
+ * Clear all markers
+ */
+ public clear(): void {
+ if (this.verticalLinePrimitive) {
+ this.verticalLinePrimitive.clearMarkers();
+ this.chart?.timeScale().fitContent();
+ }
+ }
+
+ /**
+ * Mark current time
+ */
+ public markNow(label: string = 'Now'): string {
+ const now = Math.floor(Date.now() / 1000) as Time;
+ return this.addMarker(now, label, '#ff9800');
+ }
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/index.ts b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/index.ts
new file mode 100644
index 000000000..0658ab74f
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/index.ts
@@ -0,0 +1,96 @@
+/**
+ * Lightweight Charts Plugin System
+ *
+ * Export all plugins and core plugin infrastructure
+ */
+
+// Core infrastructure
+export * from './types';
+export { BasePlugin } from './BasePlugin';
+export { PluginManager } from './PluginManager';
+
+// Built-in plugins
+export { TooltipPlugin } from './TooltipPlugin';
+export { TrendLinePlugin } from './TrendLinePlugin';
+export { VerticalLinePlugin } from './VerticalLinePlugin';
+export { TradingToolkitPlugin, DrawingTool, PositionType, OrderType } from './TradingToolkitPlugin';
+export type { DrawingObject, DrawingStyle, PositionMarker, ToolkitOptions } from './TradingToolkitPlugin';
+
+// Plugin factory for easy instantiation
+import { TooltipPlugin } from './TooltipPlugin';
+import { TrendLinePlugin } from './TrendLinePlugin';
+import { VerticalLinePlugin } from './VerticalLinePlugin';
+import { TradingToolkitPlugin } from './TradingToolkitPlugin';
+import { IChartPlugin, PluginCategory } from './types';
+
+export interface PluginRegistry {
+ [key: string]: () => IChartPlugin;
+}
+
+/**
+ * Registry of all available plugins
+ */
+export const PLUGIN_REGISTRY: PluginRegistry = {
+ tooltip: () => new TooltipPlugin(),
+ trendline: () => new TrendLinePlugin(),
+ verticalline: () => new VerticalLinePlugin(),
+ tradingtoolkit: () => new TradingToolkitPlugin(),
+};
+
+/**
+ * Create a plugin by name
+ */
+export function createPlugin(name: string, options?: any): IChartPlugin | null {
+ const factory = PLUGIN_REGISTRY[name.toLowerCase()];
+ if (!factory) {
+ console.warn(`Plugin "${name}" not found in registry`);
+ return null;
+ }
+ return factory();
+}
+
+/**
+ * Get all available plugin names
+ */
+export function getAvailablePlugins(): string[] {
+ return Object.keys(PLUGIN_REGISTRY);
+}
+
+/**
+ * Get plugin metadata by name
+ */
+export function getPluginInfo(name: string): { name: string; category: string; description: string } | null {
+ const plugin = createPlugin(name);
+ if (!plugin) return null;
+
+ const info = {
+ name: plugin.metadata.name,
+ category: plugin.metadata.category,
+ description: plugin.metadata.description,
+ };
+
+ plugin.destroy();
+ return info;
+}
+
+/**
+ * Get all plugins grouped by category
+ */
+export function getPluginsByCategory(): Record<PluginCategory, string[]> {
+ const grouped: Record<string, string[]> = {
+ [PluginCategory.DRAWING]: [],
+ [PluginCategory.INDICATOR]: [],
+ [PluginCategory.ANNOTATION]: [],
+ [PluginCategory.INTERACTIVE]: [],
+ [PluginCategory.OVERLAY]: [],
+ };
+
+ Object.keys(PLUGIN_REGISTRY).forEach(name => {
+ const info = getPluginInfo(name);
+ if (info) {
+ grouped[info.category].push(name);
+ }
+ });
+
+ return grouped as Record<PluginCategory, string[]>;
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/types.ts b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/types.ts
new file mode 100644
index 000000000..72119d6be
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trading/charts/plugins/types.ts
@@ -0,0 +1,193 @@
+/**
+ * Lightweight Charts Plugin System - Type Definitions
+ *
+ * This file defines the plugin architecture for extending lightweight-charts
+ * with custom primitives, drawing tools, indicators, and interactive features.
+ */
+
+import type {
+ ISeriesPrimitive,
+ SeriesAttachedParameter,
+ IPrimitivePaneView,
+ Time,
+ SeriesType,
+ ISeriesApi,
+ IChartApi
+} from 'lightweight-charts';
+
+/**
+ * Plugin categories for organization
+ */
+export enum PluginCategory {
+ DRAWING = 'drawing',
+ INDICATOR = 'indicator',
+ ANNOTATION = 'annotation',
+ INTERACTIVE = 'interactive',
+ OVERLAY = 'overlay',
+}
+
+/**
+ * Plugin metadata
+ */
+export interface PluginMetadata {
+ id: string;
+ name: string;
+ description: string;
+ category: PluginCategory;
+ version: string;
+ author?: string;
+ enabled: boolean;
+}
+
+/**
+ * Plugin configuration options
+ */
+export interface PluginOptions {
+ color?: string;
+ lineWidth?: number;
+ lineStyle?: number;
+ visible?: boolean;
+ interactive?: boolean;
+ [key: string]: any;
+}
+
+/**
+ * Base plugin interface that all plugins must implement
+ */
+export interface IChartPlugin<HorzScaleItem = Time> {
+ metadata: PluginMetadata;
+ options: PluginOptions;
+
+ /**
+ * Initialize the plugin with chart and series context
+ */
+ initialize(chart: IChartApi, series: ISeriesApi<SeriesType, HorzScaleItem>): void;
+
+ /**
+ * Update plugin options
+ */
+ applyOptions(options: Partial<PluginOptions>): void;
+
+ /**
+ * Get the primitive to attach to the series
+ */
+ getPrimitive(): ISeriesPrimitive<HorzScaleItem> | null;
+
+ /**
+ * Cleanup and remove the plugin
+ */
+ destroy(): void;
+
+ /**
+ * Enable/disable the plugin
+ */
+ setEnabled(enabled: boolean): void;
+}
+
+/**
+ * Drawing plugin interface for interactive drawing tools
+ */
+export interface IDrawingPlugin<HorzScaleItem = Time> extends IChartPlugin<HorzScaleItem> {
+ /**
+ * Start drawing mode
+ */
+ startDrawing(): void;
+
+ /**
+ * Stop drawing mode
+ */
+ stopDrawing(): void;
+
+ /**
+ * Check if currently in drawing mode
+ */
+ isDrawing(): boolean;
+
+ /**
+ * Clear all drawn objects
+ */
+ clear(): void;
+}
+
+/**
+ * Point in chart coordinates
+ */
+export interface ChartPoint<HorzScaleItem = Time> {
+ time: HorzScaleItem;
+ price: number;
+}
+
+/**
+ * Mouse event data for plugins
+ */
+export interface PluginMouseEvent {
+ x: number;
+ y: number;
+ time?: Time;
+ price?: number;
+ ctrlKey: boolean;
+ shiftKey: boolean;
+ altKey: boolean;
+}
+
+/**
+ * Plugin manager interface
+ */
+export interface IPluginManager {
+ /**
+ * Register a plugin
+ */
+ register(plugin: IChartPlugin): void;
+
+ /**
+ * Unregister a plugin by id
+ */
+ unregister(pluginId: string): void;
+
+ /**
+ * Get all registered plugins
+ */
+ getPlugins(): IChartPlugin[];
+
+ /**
+ * Get plugins by category
+ */
+ getPluginsByCategory(category: PluginCategory): IChartPlugin[];
+
+ /**
+ * Enable/disable a plugin
+ */
+ togglePlugin(pluginId: string, enabled: boolean): void;
+
+ /**
+ * Get plugin by id
+ */
+ getPlugin(pluginId: string): IChartPlugin | undefined;
+}
+
+/**
+ * Plugin event types
+ */
+export enum PluginEventType {
+ CLICK = 'click',
+ DOUBLE_CLICK = 'doubleClick',
+ MOUSE_DOWN = 'mouseDown',
+ MOUSE_UP = 'mouseUp',
+ MOUSE_MOVE = 'mouseMove',
+ DRAWING_COMPLETE = 'drawingComplete',
+ DRAWING_CANCEL = 'drawingCancel',
+}
+
+/**
+ * Plugin event
+ */
+export interface PluginEvent {
+ type: PluginEventType;
+ data: any;
+ timestamp: number;
+}
+
+/**
+ * Plugin event listener
+ */
+export type PluginEventListener = (event: PluginEvent) => void;
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/AccountStats.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/AccountStats.tsx
index c7a8f9f21..2d4b5f57a 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/AccountStats.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/AccountStats.tsx
@@ -7,19 +7,52 @@ import React from 'react';
import { TrendingUp, TrendingDown, Target, DollarSign } from 'lucide-react';
import { useTradingStats } from '../../hooks/useAccountInfo';
+// Bloomberg color palette
+const BLOOMBERG = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ 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'
+};
+
export function AccountStats() {
const { stats, isLoading } = useTradingStats();
if (isLoading || !stats) {
return (
- <div className="flex items-center justify-center p-8 bg-black border border-gray-800 rounded">
- <div className="text-gray-500 text-sm">
- {isLoading ? (
- <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
- ) : (
- 'No statistics available'
- )}
- </div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: '40px',
+ background: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ color: BLOOMBERG.GRAY,
+ fontSize: '12px'
+ }}>
+ {isLoading ? (
+ <div style={{
+ width: '24px',
+ height: '24px',
+ border: `2px solid ${BLOOMBERG.BORDER}`,
+ borderTopColor: BLOOMBERG.ORANGE,
+ borderRadius: '50%',
+ animation: 'spin 1s linear infinite'
+ }} />
+ ) : (
+ 'No statistics available'
+ )}
</div>
);
}
@@ -27,78 +60,107 @@ export function AccountStats() {
const statCards = [
{
label: 'Total P&L',
- value: `${stats.totalPnL >= 0 ? '+' : ''}$${stats.totalPnL.toFixed(2)}`,
- color: stats.totalPnL >= 0 ? 'text-green-500' : 'text-red-500',
+ value: `${stats.totalPnL >= 0 ? '+' : ''}$${(typeof stats.totalPnL === 'number' ? stats.totalPnL : 0).toFixed(2)}`,
+ color: stats.totalPnL >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED,
icon: stats.totalPnL >= 0 ? TrendingUp : TrendingDown,
- bgColor: stats.totalPnL >= 0 ? 'bg-green-500/10' : 'bg-red-500/10',
},
{
label: 'Return',
- value: `${stats.returnPercent >= 0 ? '+' : ''}${stats.returnPercent.toFixed(2)}%`,
- color: stats.returnPercent >= 0 ? 'text-green-500' : 'text-red-500',
+ value: `${stats.returnPercent >= 0 ? '+' : ''}${(typeof stats.returnPercent === 'number' ? stats.returnPercent : 0).toFixed(2)}%`,
+ color: stats.returnPercent >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED,
icon: Target,
- bgColor: stats.returnPercent >= 0 ? 'bg-green-500/10' : 'bg-red-500/10',
},
{
label: 'Win Rate',
- value: `${stats.winRate.toFixed(1)}%`,
- color: stats.winRate >= 50 ? 'text-green-500' : 'text-yellow-500',
+ value: `${(typeof stats.winRate === 'number' ? stats.winRate : 0).toFixed(1)}%`,
+ color: stats.winRate >= 50 ? BLOOMBERG.GREEN : BLOOMBERG.YELLOW,
icon: Target,
- bgColor: stats.winRate >= 50 ? 'bg-green-500/10' : 'bg-yellow-500/10',
},
{
label: 'Total Trades',
- value: stats.totalTrades.toString(),
- color: 'text-blue-500',
+ value: (stats.totalTrades || 0).toString(),
+ color: BLOOMBERG.BLUE,
icon: DollarSign,
- bgColor: 'bg-blue-500/10',
},
{
label: 'Winning Trades',
- value: stats.winningTrades.toString(),
- color: 'text-green-500',
+ value: (stats.winningTrades || 0).toString(),
+ color: BLOOMBERG.GREEN,
icon: TrendingUp,
- bgColor: 'bg-green-500/10',
},
{
label: 'Losing Trades',
- value: stats.losingTrades.toString(),
- color: 'text-red-500',
+ value: (stats.losingTrades || 0).toString(),
+ color: BLOOMBERG.RED,
icon: TrendingDown,
- bgColor: 'bg-red-500/10',
},
{
label: 'Realized P&L',
- value: `${stats.realizedPnL >= 0 ? '+' : ''}$${stats.realizedPnL.toFixed(2)}`,
- color: stats.realizedPnL >= 0 ? 'text-green-500' : 'text-red-500',
+ value: `${stats.realizedPnL >= 0 ? '+' : ''}$${(typeof stats.realizedPnL === 'number' ? stats.realizedPnL : 0).toFixed(2)}`,
+ color: stats.realizedPnL >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED,
icon: DollarSign,
- bgColor: 'bg-gray-800',
},
{
label: 'Unrealized P&L',
- value: `${stats.unrealizedPnL >= 0 ? '+' : ''}$${stats.unrealizedPnL.toFixed(2)}`,
- color: stats.unrealizedPnL >= 0 ? 'text-green-500' : 'text-red-500',
+ value: `${stats.unrealizedPnL >= 0 ? '+' : ''}$${(typeof stats.unrealizedPnL === 'number' ? stats.unrealizedPnL : 0).toFixed(2)}`,
+ color: stats.unrealizedPnL >= 0 ? BLOOMBERG.GREEN : BLOOMBERG.RED,
icon: DollarSign,
- bgColor: 'bg-gray-800',
},
];
return (
- <div className="space-y-4">
+ <div style={{
+ height: '100%',
+ overflow: 'auto',
+ padding: '12px',
+ background: BLOOMBERG.PANEL_BG
+ }}>
{/* Main Stats Grid */}
- <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, 1fr)',
+ gap: '12px',
+ marginBottom: '16px'
+ }}>
{statCards.map((stat, idx) => {
const Icon = stat.icon;
return (
<div
key={idx}
- className={`${stat.bgColor} border border-gray-800 rounded p-3 transition-all hover:border-gray-700`}
+ style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ padding: '12px',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => e.currentTarget.style.borderColor = BLOOMBERG.MUTED}
+ onMouseLeave={(e) => e.currentTarget.style.borderColor = BLOOMBERG.BORDER}
>
- <div className="flex items-center justify-between mb-2">
- <span className="text-xs text-gray-400 font-medium">{stat.label}</span>
- <Icon className={`w-4 h-4 ${stat.color}`} />
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: '8px'
+ }}>
+ <span style={{
+ fontSize: '9px',
+ color: BLOOMBERG.GRAY,
+ fontWeight: 600,
+ letterSpacing: '0.5px'
+ }}>
+ {stat.label.toUpperCase()}
+ </span>
+ <Icon size={14} color={stat.color} />
+ </div>
+ <div style={{
+ fontSize: '18px',
+ fontWeight: 700,
+ fontFamily: '"IBM Plex Mono", monospace',
+ color: stat.color
+ }}>
+ {stat.value}
</div>
- <div className={`text-lg font-bold font-mono ${stat.color}`}>{stat.value}</div>
</div>
);
})}
@@ -106,51 +168,109 @@ export function AccountStats() {
{/* Advanced Stats */}
{stats.averageWin !== undefined && (
- <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
- {stats.averageWin !== undefined && (
- <div className="bg-gray-900 border border-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Avg Win</div>
- <div className="text-sm font-mono text-green-500">${stats.averageWin.toFixed(2)}</div>
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(3, 1fr)',
+ gap: '12px',
+ marginBottom: '16px'
+ }}>
+ {stats.averageWin !== undefined && typeof stats.averageWin === 'number' && (
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ padding: '12px'
+ }}>
+ <div style={{ fontSize: '9px', color: BLOOMBERG.GRAY, marginBottom: '4px' }}>AVG WIN</div>
+ <div style={{ fontSize: '14px', fontFamily: '"IBM Plex Mono", monospace', color: BLOOMBERG.GREEN, fontWeight: 600 }}>
+ ${stats.averageWin.toFixed(2)}
+ </div>
</div>
)}
- {stats.averageLoss !== undefined && (
- <div className="bg-gray-900 border border-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Avg Loss</div>
- <div className="text-sm font-mono text-red-500">${stats.averageLoss.toFixed(2)}</div>
+ {stats.averageLoss !== undefined && typeof stats.averageLoss === 'number' && (
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ padding: '12px'
+ }}>
+ <div style={{ fontSize: '9px', color: BLOOMBERG.GRAY, marginBottom: '4px' }}>AVG LOSS</div>
+ <div style={{ fontSize: '14px', fontFamily: '"IBM Plex Mono", monospace', color: BLOOMBERG.RED, fontWeight: 600 }}>
+ ${stats.averageLoss.toFixed(2)}
+ </div>
</div>
)}
- {stats.profitFactor !== undefined && (
- <div className="bg-gray-900 border border-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Profit Factor</div>
- <div className="text-sm font-mono text-blue-500">{stats.profitFactor.toFixed(2)}</div>
+ {stats.profitFactor !== undefined && typeof stats.profitFactor === 'number' && (
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ padding: '12px'
+ }}>
+ <div style={{ fontSize: '9px', color: BLOOMBERG.GRAY, marginBottom: '4px' }}>PROFIT FACTOR</div>
+ <div style={{ fontSize: '14px', fontFamily: '"IBM Plex Mono", monospace', color: BLOOMBERG.BLUE, fontWeight: 600 }}>
+ {stats.profitFactor.toFixed(2)}
+ </div>
</div>
)}
- {stats.largestWin !== undefined && (
- <div className="bg-gray-900 border border-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Largest Win</div>
- <div className="text-sm font-mono text-green-500">${stats.largestWin.toFixed(2)}</div>
+ {stats.largestWin !== undefined && typeof stats.largestWin === 'number' && (
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ padding: '12px'
+ }}>
+ <div style={{ fontSize: '9px', color: BLOOMBERG.GRAY, marginBottom: '4px' }}>LARGEST WIN</div>
+ <div style={{ fontSize: '14px', fontFamily: '"IBM Plex Mono", monospace', color: BLOOMBERG.GREEN, fontWeight: 600 }}>
+ ${stats.largestWin.toFixed(2)}
+ </div>
</div>
)}
- {stats.largestLoss !== undefined && (
- <div className="bg-gray-900 border border-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Largest Loss</div>
- <div className="text-sm font-mono text-red-500">${stats.largestLoss.toFixed(2)}</div>
+ {stats.largestLoss !== undefined && typeof stats.largestLoss === 'number' && (
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ padding: '12px'
+ }}>
+ <div style={{ fontSize: '9px', color: BLOOMBERG.GRAY, marginBottom: '4px' }}>LARGEST LOSS</div>
+ <div style={{ fontSize: '14px', fontFamily: '"IBM Plex Mono", monospace', color: BLOOMBERG.RED, fontWeight: 600 }}>
+ ${stats.largestLoss.toFixed(2)}
+ </div>
</div>
)}
- {stats.sharpeRatio !== undefined && (
- <div className="bg-gray-900 border border-gray-800 rounded p-3">
- <div className="text-xs text-gray-400 mb-1">Sharpe Ratio</div>
- <div className="text-sm font-mono text-purple-500">{stats.sharpeRatio.toFixed(2)}</div>
+ {stats.sharpeRatio !== undefined && typeof stats.sharpeRatio === 'number' && (
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ padding: '12px'
+ }}>
+ <div style={{ fontSize: '9px', color: BLOOMBERG.GRAY, marginBottom: '4px' }}>SHARPE RATIO</div>
+ <div style={{ fontSize: '14px', fontFamily: '"IBM Plex Mono", monospace', color: BLOOMBERG.PURPLE, fontWeight: 600 }}>
+ {stats.sharpeRatio.toFixed(2)}
+ </div>
</div>
)}
</div>
)}
{/* Total Fees */}
- <div className="bg-gray-900 border border-gray-800 rounded p-3">
- <div className="flex items-center justify-between">
- <span className="text-xs text-gray-400">Total Fees Paid</span>
- <span className="text-sm font-mono text-orange-500">${stats.totalFees.toFixed(2)}</span>
+ <div style={{
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ padding: '12px'
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between'
+ }}>
+ <span style={{ fontSize: '9px', color: BLOOMBERG.GRAY, fontWeight: 600 }}>TOTAL FEES PAID</span>
+ <span style={{ fontSize: '14px', fontFamily: '"IBM Plex Mono", monospace', color: BLOOMBERG.ORANGE, fontWeight: 600 }}>
+ ${(typeof stats.totalFees === 'number' ? stats.totalFees : 0).toFixed(2)}
+ </span>
</div>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/FeesDisplay.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/FeesDisplay.tsx
index c672d8084..e9a0b7eb7 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/FeesDisplay.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/AccountInfo/FeesDisplay.tsx
@@ -7,89 +7,163 @@ import { DollarSign, Info } from 'lucide-react';
import { useFees } from '../../hooks/useAccountInfo';
import { useBrokerContext } from '../../../../../contexts/BrokerContext';
+// Bloomberg color palette
+const BLOOMBERG = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ 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'
+};
+
export function FeesDisplay() {
const { fees, isLoading } = useFees();
const { activeBroker } = useBrokerContext();
if (isLoading || !fees) {
return (
- <div className="bg-gray-900 border border-gray-800 rounded p-4">
- <div className="flex items-center gap-2 mb-3">
- <DollarSign className="w-4 h-4 text-orange-500" />
- <span className="text-sm font-medium text-gray-300">Trading Fees</span>
+ <div style={{
+ background: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ padding: '12px'
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '12px'
+ }}>
+ <DollarSign size={14} color={BLOOMBERG.ORANGE} />
+ <span style={{ fontSize: '11px', fontWeight: 600, color: BLOOMBERG.WHITE }}>TRADING FEES</span>
</div>
{isLoading ? (
- <div className="flex items-center justify-center py-4">
- <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-orange-500"></div>
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '16px' }}>
+ <div style={{
+ width: '20px',
+ height: '20px',
+ border: `2px solid ${BLOOMBERG.BORDER}`,
+ borderTopColor: BLOOMBERG.ORANGE,
+ borderRadius: '50%',
+ animation: 'spin 1s linear infinite'
+ }} />
</div>
) : (
- <div className="text-xs text-gray-500">No fee information available</div>
+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY }}>No fee information available</div>
)}
</div>
);
}
return (
- <div className="bg-gray-900 border border-gray-800 rounded p-4">
+ <div style={{
+ background: BLOOMBERG.PANEL_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '4px',
+ padding: '12px'
+ }}>
{/* Header */}
- <div className="flex items-center justify-between mb-3">
- <div className="flex items-center gap-2">
- <DollarSign className="w-4 h-4 text-orange-500" />
- <span className="text-sm font-medium text-gray-300">Trading Fees</span>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: '12px'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <DollarSign size={14} color={BLOOMBERG.ORANGE} />
+ <span style={{ fontSize: '11px', fontWeight: 600, color: BLOOMBERG.WHITE }}>TRADING FEES</span>
</div>
- <span className="text-xs text-gray-500 uppercase">{activeBroker}</span>
+ <span style={{ fontSize: '9px', color: BLOOMBERG.GRAY, fontWeight: 600 }}>{activeBroker?.toUpperCase()}</span>
</div>
{/* Fee Structure */}
- <div className="space-y-2">
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
{/* Maker Fee */}
- <div className="flex items-center justify-between p-2 bg-black/30 rounded">
- <div className="flex items-center gap-2">
- <div className="text-xs text-gray-400">Maker Fee</div>
- <div className="group relative">
- <Info className="w-3 h-3 text-gray-600 cursor-help" />
- <div className="hidden group-hover:block absolute bottom-full left-0 mb-2 w-48 p-2 bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 z-10">
- Fee for adding liquidity to the order book (limit orders that don't immediately execute)
- </div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '8px',
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '3px'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY }}>MAKER FEE</div>
+ <div style={{ position: 'relative', display: 'inline-block' }} title="Fee for adding liquidity to the order book">
+ <Info size={10} color={BLOOMBERG.MUTED} style={{ cursor: 'help' }} />
</div>
</div>
- <div className="text-sm font-mono text-green-500">{fees.makerPercent}</div>
+ <div style={{ fontSize: '11px', fontFamily: '"IBM Plex Mono", monospace', color: BLOOMBERG.GREEN, fontWeight: 600 }}>
+ {fees.makerPercent}
+ </div>
</div>
{/* Taker Fee */}
- <div className="flex items-center justify-between p-2 bg-black/30 rounded">
- <div className="flex items-center gap-2">
- <div className="text-xs text-gray-400">Taker Fee</div>
- <div className="group relative">
- <Info className="w-3 h-3 text-gray-600 cursor-help" />
- <div className="hidden group-hover:block absolute bottom-full left-0 mb-2 w-48 p-2 bg-gray-800 border border-gray-700 rounded text-xs text-gray-300 z-10">
- Fee for taking liquidity from the order book (market orders and limit orders that execute immediately)
- </div>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ padding: '8px',
+ background: BLOOMBERG.DARK_BG,
+ border: `1px solid ${BLOOMBERG.BORDER}`,
+ borderRadius: '3px'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <div style={{ fontSize: '10px', color: BLOOMBERG.GRAY }}>TAKER FEE</div>
+ <div style={{ position: 'relative', display: 'inline-block' }} title="Fee for taking liquidity from the order book">
+ <Info size={10} color={BLOOMBERG.MUTED} style={{ cursor: 'help' }} />
</div>
</div>
- <div className="text-sm font-mono text-orange-500">{fees.takerPercent}</div>
+ <div style={{ fontSize: '11px', fontFamily: '"IBM Plex Mono", monospace', color: BLOOMBERG.ORANGE, fontWeight: 600 }}>
+ {fees.takerPercent}
+ </div>
</div>
</div>
{/* Example Calculation */}
- <div className="mt-3 pt-3 border-t border-gray-800">
- <div className="text-xs text-gray-500 mb-2">Example: $10,000 trade</div>
- <div className="grid grid-cols-2 gap-2 text-xs">
- <div className="flex justify-between">
- <span className="text-gray-400">Maker:</span>
- <span className="text-green-500 font-mono">${(10000 * fees.maker).toFixed(2)}</span>
+ <div style={{
+ marginTop: '12px',
+ paddingTop: '12px',
+ borderTop: `1px solid ${BLOOMBERG.BORDER}`
+ }}>
+ <div style={{ fontSize: '9px', color: BLOOMBERG.GRAY, marginBottom: '8px' }}>EXAMPLE: $10,000 TRADE</div>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', fontSize: '10px' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: BLOOMBERG.GRAY }}>Maker:</span>
+ <span style={{ color: BLOOMBERG.GREEN, fontFamily: '"IBM Plex Mono", monospace', fontWeight: 600 }}>
+ ${(10000 * fees.maker).toFixed(2)}
+ </span>
</div>
- <div className="flex justify-between">
- <span className="text-gray-400">Taker:</span>
- <span className="text-orange-500 font-mono">${(10000 * fees.taker).toFixed(2)}</span>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: BLOOMBERG.GRAY }}>Taker:</span>
+ <span style={{ color: BLOOMBERG.ORANGE, fontFamily: '"IBM Plex Mono", monospace', fontWeight: 600 }}>
+ ${(10000 * fees.taker).toFixed(2)}
+ </span>
</div>
</div>
</div>
{/* Savings Tip */}
- <div className="mt-3 p-2 bg-blue-500/10 border border-blue-500/20 rounded">
- <div className="text-xs text-blue-400">
- 💡 Tip: Use limit orders to pay lower maker fees
+ <div style={{
+ marginTop: '12px',
+ padding: '8px',
+ background: `${BLOOMBERG.BLUE}15`,
+ border: `1px solid ${BLOOMBERG.BLUE}40`,
+ borderRadius: '3px'
+ }}>
+ <div style={{ fontSize: '9px', color: BLOOMBERG.CYAN }}>
+ 💡 TIP: Use limit orders to pay lower maker fees
</div>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/core/PositionManager/PositionsTable.tsx b/fincept-terminal-desktop/src/components/tabs/trading/core/PositionManager/PositionsTable.tsx
index 3af43d86c..1b0eb6eec 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/core/PositionManager/PositionsTable.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/trading/core/PositionManager/PositionsTable.tsx
@@ -35,10 +35,19 @@ export function PositionsTable() {
}
try {
+ console.log('[PositionsTable] Closing position:', position);
await closePosition(position);
+ console.log('[PositionsTable] Position closed, refreshing...');
+
+ // Force immediate refresh
await refresh();
+
+ // Additional refresh after 500ms to ensure DB sync
+ setTimeout(() => refresh(), 500);
+
alert(`✓ Position closed: ${position.symbol}`);
} catch (error) {
+ console.error('[PositionsTable] Close error:', error);
alert(`✗ Failed to close position: ${(error as Error).message}`);
}
};
diff --git a/fincept-terminal-desktop/src/components/tabs/trading/hooks/usePositions.ts b/fincept-terminal-desktop/src/components/tabs/trading/hooks/usePositions.ts
index 1e8d93699..1cb138763 100644
--- a/fincept-terminal-desktop/src/components/tabs/trading/hooks/usePositions.ts
+++ b/fincept-terminal-desktop/src/components/tabs/trading/hooks/usePositions.ts
@@ -10,21 +10,33 @@ import type { UnifiedPosition } from '../types';
export function usePositions(symbol?: string, autoRefresh: boolean = true, refreshInterval: number = 2000) {
const { activeAdapter, tradingMode } = useBrokerContext();
const [positions, setPositions] = useState<UnifiedPosition[]>([]);
+ // Start with loading false - only set true when actually fetching
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const fetchPositions = useCallback(async () => {
- if (!activeAdapter || !activeAdapter.isConnected()) {
+ // Quick early exit if no adapter - don't set loading state
+ if (!activeAdapter) {
setPositions([]);
+ setIsLoading(false);
return;
}
- setIsLoading(true);
+ // Set loading only if we don't have positions yet
+ if (positions.length === 0) {
+ setIsLoading(true);
+ }
setError(null);
try {
- // Fetch positions from adapter
- const rawPositions = await activeAdapter.fetchPositions(symbol ? [symbol] : undefined);
+ // 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[];
// Normalize to unified format
const normalized: UnifiedPosition[] = (rawPositions || []).map((pos: any) => ({
@@ -46,10 +58,15 @@ export function usePositions(symbol?: string, autoRefresh: boolean = true, refre
}));
setPositions(normalized);
+ setError(null); // Clear error on success
+ console.log('[usePositions] Successfully fetched', normalized.length, 'positions');
} catch (err) {
const error = err as Error;
console.error('[usePositions] Failed to fetch positions:', error);
setError(error);
+ // DON'T clear positions on error - keep existing data
+ // This prevents the "0 positions" flash when API fails temporarily
+ console.warn('[usePositions] Keeping existing positions due to fetch error');
} finally {
setIsLoading(false);
}
diff --git a/fincept-terminal-desktop/src/contexts/AuthContext.tsx b/fincept-terminal-desktop/src/contexts/AuthContext.tsx
index 03df9de2e..d538028de 100644
--- a/fincept-terminal-desktop/src/contexts/AuthContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/AuthContext.tsx
@@ -544,10 +544,10 @@ if (result.success && result.data && result.data.data && result.data.data.api_ke
console.log('AuthContext: Has subscription:', !!newSession.subscription?.has_subscription);
return { success: true };
} else {
- console.log('AuthContext: Login failed - success:', result.success, 'data:', result.data, 'api_key:', result.data?.api_key);
+ console.log('AuthContext: Login failed - success:', result.success, 'data:', result.data, 'error:', result.error);
return {
success: false,
- error: result.message || result.error || 'Login failed'
+ error: result.error || result.message || 'Login failed'
};
}
} catch (error) {
diff --git a/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts b/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts
index 6fbac2c9d..5485e2279 100644
--- a/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts
+++ b/fincept-terminal-desktop/src/paper-trading/OrderMatchingEngine.ts
@@ -504,7 +504,8 @@ export class OrderMatchingEngine {
price,
quantity,
leverage,
- marginMode
+ marginMode,
+ params?.reduceOnly
);
// Update portfolio balance (deduct fees)
diff --git a/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts b/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts
index 6b3338d97..8acac6016 100644
--- a/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts
+++ b/fincept-terminal-desktop/src/paper-trading/PaperTradingAdapter.ts
@@ -256,22 +256,25 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {
}
console.log('[PaperTradingAdapter] fetchPositions called');
- console.log('[PaperTradingAdapter] Portfolio ID:', this.paperConfig.portfolioId);
+ // FORCE FRESH DB READ - no caching
const positions = await paperTradingDatabase.getPortfolioPositions(this.paperConfig.portfolioId, 'open');
- console.log('[PaperTradingAdapter] Raw open positions from DB:', positions.length);
+ console.log('[PaperTradingAdapter] Open positions:', positions.length);
- // Also check ALL positions to see if there are closed ones
- const allPositions = await paperTradingDatabase.getPortfolioPositions(this.paperConfig.portfolioId);
- console.log('[PaperTradingAdapter] Total positions (open + closed):', allPositions.length);
- allPositions.forEach(p => {
- console.log(` Position: ${p.symbol} ${p.side} ${p.quantity} @ ${p.entryPrice} - Status: ${p.status}`);
+ positions.forEach(p => {
+ console.log(` ${p.symbol} ${p.side} ${p.quantity} @ ${p.entryPrice}`);
});
- // Update positions with current prices
- for (const p of positions) {
+ // Update positions with current prices - PARALLEL with timeout per position
+ const updatePromises = positions.map(async (p) => {
try {
- const ticker = await this.realAdapter.fetchTicker(p.symbol);
+ // Add timeout per ticker fetch (5 seconds max)
+ const tickerPromise = this.realAdapter.fetchTicker(p.symbol);
+ const timeoutPromise = new Promise((_, reject) =>
+ setTimeout(() => reject(new Error('Ticker timeout')), 5000)
+ );
+
+ const ticker = await Promise.race([tickerPromise, timeoutPromise]) as any;
const currentPrice = ticker.last || ticker.close || p.currentPrice || p.entryPrice;
const unrealizedPnl = p.side === 'long'
@@ -286,9 +289,20 @@ export class PaperTradingAdapter extends BaseExchangeAdapter {
p.currentPrice = currentPrice;
p.unrealizedPnl = unrealizedPnl;
} catch (err) {
- console.warn(`[PaperTradingAdapter] Failed to update price for ${p.symbol}`);
+ console.warn(`[PaperTradingAdapter] Skipping price update for ${p.symbol}:`, err);
+ // Keep existing price if fetch fails
+ p.currentPrice = p.currentPrice || p.entryPrice;
+ p.unrealizedPnl = p.unrealizedPnl || 0;
}
- }
+ });
+
+ // Wait for all updates with overall timeout
+ await Promise.race([
+ Promise.all(updatePromises),
+ new Promise((_, reject) => setTimeout(() => reject(new Error('All updates timeout')), 10000))
+ ]).catch(() => {
+ console.warn('[PaperTradingAdapter] Some price updates timed out, continuing...');
+ });
// Convert to CCXT Position format
const ccxtPositions: Position[] = positions
diff --git a/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts b/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts
index 418cac815..ffd811aca 100644
--- a/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts
+++ b/fincept-terminal-desktop/src/paper-trading/PaperTradingBalance.ts
@@ -122,44 +122,86 @@ export class PaperTradingBalance {
fillPrice: number,
fillQuantity: number,
leverage: number,
- marginMode: 'cross' | 'isolated'
+ 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';
- // Check for existing position WITH THE SAME SIDE (hedging mode)
- const existingPosition = await paperTradingDatabase.getPositionBySymbolAndSide(portfolioId, symbol, positionSide, 'open');
+ // Check for OPPOSITE position first (for closing)
+ const oppositePosition = await paperTradingDatabase.getPositionBySymbolAndSide(portfolioId, symbol, oppositePositionSide, 'open');
- if (!existingPosition) {
- // Create new position
- console.log(`[PaperTradingBalance] Creating new ${positionSide} position for ${symbol}`);
- const positionId = `pos_${Date.now()}_${Math.random().toString(36).substring(7)}`;
+ // If reduceOnly and no opposite position, reject
+ if (reduceOnly && !oppositePosition) {
+ throw new Error(`Cannot reduce position - no ${oppositePositionSide} position exists for ${symbol}`);
+ }
- const liquidationPrice = this.calculateLiquidationPrice(
- positionSide,
- fillPrice,
- leverage,
- fillQuantity
- );
+ // If reduceOnly OR opposite position exists, REDUCE/CLOSE that position
+ if (oppositePosition) {
+ console.log(`[PaperTradingBalance] Reducing/closing ${oppositePositionSide} position for ${symbol}`);
+ console.log(` Existing: ${oppositePosition.quantity} @ ${oppositePosition.entryPrice}`);
+ console.log(` Reducing by: ${fillQuantity} @ ${fillPrice}`);
- await paperTradingDatabase.createPosition({
- id: positionId,
- portfolioId,
- symbol,
- side: positionSide,
- entryPrice: fillPrice,
- quantity: fillQuantity,
- leverage,
- marginMode,
- });
+ // Validate reduceOnly doesn't exceed position
+ if (reduceOnly && fillQuantity > oppositePosition.quantity) {
+ throw new Error(`Reduce-only order quantity ${fillQuantity} exceeds position size ${oppositePosition.quantity}`);
+ }
+
+ const pnl = oppositePositionSide === 'long'
+ ? (fillPrice - oppositePosition.entryPrice) * fillQuantity
+ : (oppositePosition.entryPrice - fillPrice) * fillQuantity;
+
+ console.log(` Realized PnL: ${pnl.toFixed(2)}`);
+
+ // Update portfolio balance with realized PnL (done after fee calculation in executeTrade)
+ const portfolio = await paperTradingDatabase.getPortfolio(portfolioId);
+ if (portfolio) {
+ await paperTradingDatabase.updatePortfolioBalance(portfolioId, portfolio.currentBalance + pnl);
+ }
+
+ if (oppositePosition.quantity === fillQuantity) {
+ // FULLY CLOSE position
+ console.log(` Fully closing position`);
+ await paperTradingDatabase.updatePosition(oppositePosition.id, {
+ status: 'closed',
+ closedAt: new Date().toISOString(),
+ realizedPnl: pnl,
+ quantity: 0
+ });
+ } else if (oppositePosition.quantity > fillQuantity) {
+ // PARTIALLY CLOSE position
+ const remainingQty = oppositePosition.quantity - fillQuantity;
+ console.log(` Partially closing, remaining: ${remainingQty}`);
+ await paperTradingDatabase.updatePosition(oppositePosition.id, {
+ quantity: remainingQty,
+ realizedPnl: (oppositePosition.realizedPnl || 0) + pnl
+ });
+ } else {
+ // Fill exceeds position - close position and open opposite
+ console.log(` Fill exceeds position, closing and opening opposite`);
+ await paperTradingDatabase.updatePosition(oppositePosition.id, {
+ status: 'closed',
+ closedAt: new Date().toISOString(),
+ realizedPnl: pnl,
+ quantity: 0
+ });
+
+ const excessQuantity = fillQuantity - oppositePosition.quantity;
+ return await this.createNewPosition(portfolioId, symbol, positionSide, fillPrice, excessQuantity, leverage, marginMode);
+ }
- const position = await paperTradingDatabase.getPosition(positionId);
- if (!position) throw new Error('Failed to create position');
+ const updatedPosition = await paperTradingDatabase.getPosition(oppositePosition.id);
+ if (!updatedPosition) throw new Error('Failed to retrieve updated position');
+ return updatedPosition;
+ }
- // Update liquidation price
- await paperTradingDatabase.updatePosition(positionId, { liquidationPrice });
+ // Check for existing position WITH THE SAME SIDE (hedging mode)
+ const existingPosition = await paperTradingDatabase.getPositionBySymbolAndSide(portfolioId, symbol, positionSide, 'open');
- return position;
+ if (!existingPosition) {
+ // Create new position
+ return await this.createNewPosition(portfolioId, symbol, positionSide, 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}`);
@@ -193,6 +235,41 @@ export class PaperTradingBalance {
}
}
+ /**
+ * Helper to create new position
+ */
+ private async createNewPosition(
+ portfolioId: string,
+ symbol: string,
+ side: 'long' | 'short',
+ entryPrice: number,
+ quantity: number,
+ leverage: number,
+ marginMode: 'cross' | 'isolated'
+ ): Promise<PaperTradingPosition> {
+ console.log(`[PaperTradingBalance] Creating new ${side} position for ${symbol}`);
+ const positionId = `pos_${Date.now()}_${Math.random().toString(36).substring(7)}`;
+
+ const liquidationPrice = this.calculateLiquidationPrice(side, entryPrice, leverage, quantity);
+
+ await paperTradingDatabase.createPosition({
+ id: positionId,
+ portfolioId,
+ symbol,
+ side,
+ entryPrice,
+ quantity,
+ leverage,
+ marginMode,
+ });
+
+ const position = await paperTradingDatabase.getPosition(positionId);
+ if (!position) throw new Error('Failed to create position');
+
+ await paperTradingDatabase.updatePosition(positionId, { liquidationPrice });
+ return position;
+ }
+
/**
* Update position prices and unrealized P&L
*/
diff --git a/fincept-terminal-desktop/src/services/agnoTradingService.ts b/fincept-terminal-desktop/src/services/agnoTradingService.ts
new file mode 100644
index 000000000..653dc27f9
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/agnoTradingService.ts
@@ -0,0 +1,599 @@
+/**
+ * Agno Trading Service
+ *
+ * TypeScript wrapper for Agno AI Trading Agent system.
+ * Provides type-safe interface to Rust/Python Agno commands.
+ * Reads API keys from Settings tab LLM configuration.
+ */
+
+import { invoke } from '@tauri-apps/api/core';
+import { sqliteService } from './sqliteService';
+
+// ============================================================================
+// Types
+// ============================================================================
+
+export interface AgnoResponse<T = any> {
+ success: boolean;
+ data?: T;
+ error?: string;
+}
+
+export interface ModelInfo {
+ provider: string;
+ model: string;
+ max_tokens?: number;
+ supports_streaming?: boolean;
+ supports_reasoning?: boolean;
+ cost_per_1k_input?: number;
+ cost_per_1k_output?: number;
+}
+
+export interface ModelRecommendation {
+ provider: string;
+ model: string;
+ model_string: string;
+}
+
+export interface AgentConfig {
+ name: string;
+ role: string;
+ description?: string;
+ instructions?: string[];
+ agent_model?: string;
+ temperature?: number;
+ tools?: string[];
+ symbols?: string[];
+ enable_memory?: boolean;
+ risk_tolerance?: string;
+}
+
+export interface AgentInfo {
+ agent_id: string;
+ status: string;
+ config: {
+ name: string;
+ role: string;
+ model: string;
+ };
+}
+
+export interface AgentRunResult {
+ agent_id: string;
+ session_id?: string;
+ content: string;
+ response_time?: number;
+ timestamp: string;
+ metrics?: {
+ input_tokens: number;
+ output_tokens: number;
+ total_tokens: number;
+ };
+}
+
+export interface MarketAnalysis {
+ symbol: string;
+ analysis_type: string;
+ analysis: string;
+ agent: string;
+}
+
+export interface TradeSignal {
+ symbol: string;
+ strategy: string;
+ timeframe?: string;
+ signal: string;
+ agent: string;
+}
+
+export interface RiskAnalysis {
+ portfolio_value: number;
+ position_count: number;
+ risk_analysis: string;
+ agent: string;
+}
+
+export interface AgnoConfig {
+ llm?: {
+ provider: string;
+ model: string;
+ temperature?: number;
+ max_tokens?: number;
+ stream?: boolean;
+ reasoning_effort?: string;
+ };
+ trading?: {
+ mode: string;
+ max_position_size?: number;
+ max_leverage?: number;
+ stop_loss_pct?: number;
+ take_profit_pct?: number;
+ initial_capital?: number;
+ symbols?: string[];
+ exchange?: string;
+ };
+ knowledge?: any;
+ memory?: any;
+ agent?: any;
+ team?: any;
+ workflow?: any;
+}
+
+export interface CompetitionInfo {
+ team_id: string;
+ models: string[];
+ agent_count: number;
+}
+
+export interface ModelDecision {
+ model: string;
+ timestamp: string;
+ content: string;
+ action?: 'long' | 'short' | 'hold' | 'close';
+ symbol?: string;
+ confidence?: number;
+ entry?: number;
+ target?: number;
+ stopLoss?: number;
+}
+
+export interface ModelPerformance {
+ model: string;
+ total_trades: number;
+ winning_trades: number;
+ losing_trades: number;
+ win_rate: number;
+ total_pnl: number;
+ daily_pnl: number;
+ positions: number;
+ last_decision?: ModelDecision;
+}
+
+export interface CompetitionResult {
+ team_id: string;
+ results: Array<{
+ model: string;
+ decision: any;
+ response: string;
+ timestamp: string;
+ }>;
+ consensus: {
+ action: string;
+ votes: Record<string, number>;
+ confidence: number;
+ agreement: number;
+ total_models: number;
+ };
+ leaderboard: ModelPerformance[];
+ timestamp: string;
+}
+
+// ============================================================================
+// Service Class
+// ============================================================================
+
+class AgnoTradingService {
+
+ /**
+ * Sync API keys from Settings to environment
+ * Called before each API request
+ */
+ private async syncApiKeys(): Promise<void> {
+ try {
+ const configs = await sqliteService.getLLMConfigs();
+
+ // Map provider names to environment variable format
+ const keyMap: Record<string, string> = {
+ 'openai': 'OPENAI_API_KEY',
+ 'anthropic': 'ANTHROPIC_API_KEY',
+ 'google': 'GOOGLE_API_KEY',
+ 'groq': 'GROQ_API_KEY',
+ 'deepseek': 'DEEPSEEK_API_KEY',
+ 'xai': 'XAI_API_KEY',
+ 'cohere': 'COHERE_API_KEY',
+ 'mistral': 'MISTRAL_API_KEY',
+ 'together': 'TOGETHER_API_KEY',
+ 'fireworks': 'FIREWORKS_API_KEY'
+ };
+
+ // Send API keys to Rust backend
+ for (const config of configs) {
+ if (config.api_key && keyMap[config.provider]) {
+ await invoke('set_env_var', {
+ key: keyMap[config.provider],
+ value: config.api_key
+ }).catch(() => {
+ // Ignore errors - backend may not support this command
+ console.log(`Could not sync ${config.provider} API key to backend`);
+ });
+ }
+ }
+ } catch (error) {
+ console.warn('Failed to sync API keys:', error);
+ }
+ }
+
+ /**
+ * List available LLM models
+ */
+ async listModels(provider?: string): Promise<AgnoResponse<{ models: ModelInfo[] }>> {
+ await this.syncApiKeys();
+ try {
+ const response = await invoke<string>('agno_list_models', { provider });
+ return JSON.parse(response);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+ }
+
+ /**
+ * Recommend best model for a task
+ */
+ async recommendModel(
+ task: string,
+ budget: 'low' | 'medium' | 'high' = 'medium',
+ reasoning: boolean = false
+ ): Promise<AgnoResponse<ModelRecommendation>> {
+ try {
+ const response = await invoke<string>('agno_recommend_model', {
+ task,
+ budget,
+ reasoning
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+ }
+
+ /**
+ * Validate Agno configuration
+ */
+ async validateConfig(config: AgnoConfig): Promise<AgnoResponse<{ valid: boolean }>> {
+ try {
+ const response = await invoke<string>('agno_validate_config', {
+ configJson: JSON.stringify(config)
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+ }
+
+ /**
+ * Create a new trading agent
+ */
+ async createAgent(config: AgentConfig): Promise<AgnoResponse<AgentInfo>> {
+ try {
+ const response = await invoke<string>('agno_create_agent', {
+ agentConfigJson: JSON.stringify(config)
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+ }
+
+ /**
+ * Run an agent with a prompt
+ */
+ async runAgent(
+ agentId: string,
+ prompt: string,
+ sessionId?: string
+ ): Promise<AgnoResponse<AgentRunResult>> {
+ try {
+ const response = await invoke<string>('agno_run_agent', {
+ agentId,
+ prompt,
+ sessionId
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+ }
+
+ /**
+ * Analyze market for a symbol
+ */
+ async analyzeMarket(
+ symbol: string,
+ agentModel: string = 'openai:gpt-4o-mini',
+ analysisType: 'quick' | 'comprehensive' | 'deep' = 'comprehensive'
+ ): Promise<AgnoResponse<MarketAnalysis>> {
+ try {
+ const response = await invoke<string>('agno_analyze_market', {
+ symbol,
+ agentModel,
+ analysisType
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+ }
+
+ /**
+ * Generate trading signal
+ */
+ async generateTradeSignal(
+ symbol: string,
+ strategy: 'momentum' | 'breakout' | 'reversal' | 'trend_following' = 'momentum',
+ agentModel: string = 'anthropic:claude-sonnet-4',
+ marketData?: any
+ ): Promise<AgnoResponse<TradeSignal>> {
+ try {
+ const response = await invoke<string>('agno_generate_trade_signal', {
+ symbol,
+ strategy,
+ agentModel,
+ marketData: marketData ? JSON.stringify(marketData) : undefined
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+ }
+
+ /**
+ * Run risk management analysis
+ */
+ async manageRisk(
+ portfolioData: {
+ positions: any[];
+ total_value: number;
+ },
+ agentModel: string = 'openai:gpt-4',
+ riskTolerance: 'conservative' | 'moderate' | 'aggressive' = 'moderate'
+ ): Promise<AgnoResponse<RiskAnalysis>> {
+ try {
+ const response = await invoke<string>('agno_manage_risk', {
+ portfolioData: JSON.stringify(portfolioData),
+ agentModel,
+ riskTolerance
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+ }
+
+ /**
+ * Get configuration template
+ */
+ async getConfigTemplate(
+ configType: 'default' | 'conservative' | 'aggressive' = 'default'
+ ): Promise<AgnoResponse<{ config: AgnoConfig }>> {
+ try {
+ const response = await invoke<string>('agno_get_config_template', {
+ configType
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+ }
+
+ // ============================================================================
+ // Multi-Model Orchestration (Alpha Arena Style)
+ // ============================================================================
+
+ /**
+ * Create multi-model competition
+ */
+ async createCompetition(
+ name: string,
+ models: string[],
+ taskType: 'trading' | 'analysis' | 'research' = 'trading'
+ ): Promise<AgnoResponse<CompetitionInfo>> {
+ await this.syncApiKeys();
+ try {
+ const response = await invoke<string>('agno_create_competition', {
+ name,
+ modelsJson: JSON.stringify(models),
+ taskType
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+ }
+
+ /**
+ * Run multi-model competition
+ */
+ async runCompetition(
+ teamId: string,
+ symbol: string,
+ task: 'analyze' | 'signal' | 'evaluate' = 'analyze'
+ ): Promise<AgnoResponse<CompetitionResult>> {
+ await this.syncApiKeys();
+ try {
+ const response = await invoke<string>('agno_run_competition', {
+ teamId,
+ symbol,
+ task
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+ }
+
+ /**
+ * Get model performance leaderboard
+ */
+ async getLeaderboard(): Promise<AgnoResponse<{ leaderboard: ModelPerformance[] }>> {
+ try {
+ const response = await invoke<string>('agno_get_leaderboard');
+ return JSON.parse(response);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+ }
+
+ /**
+ * Get recent model decisions
+ */
+ async getRecentDecisions(limit: number = 50): Promise<AgnoResponse<{ decisions: ModelDecision[] }>> {
+ try {
+ const response = await invoke<string>('agno_get_recent_decisions', {
+ limit
+ });
+ return JSON.parse(response);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+ }
+
+ // ============================================================================
+ // Helper Methods
+ // ============================================================================
+
+ /**
+ * Get available LLM providers
+ */
+ getAvailableProviders(): string[] {
+ return [
+ 'openai',
+ 'anthropic',
+ 'google',
+ 'groq',
+ 'deepseek',
+ 'xai',
+ 'ollama',
+ 'cohere',
+ 'mistral',
+ 'together',
+ 'fireworks'
+ ];
+ }
+
+ /**
+ * Get available agent types
+ */
+ getAgentTypes(): Array<{ value: string; label: string; description: string }> {
+ return [
+ {
+ value: 'market_analyst',
+ label: 'Market Analyst',
+ description: 'Technical analysis and market insights'
+ },
+ {
+ value: 'trading_strategy',
+ label: 'Trading Strategy',
+ description: 'Signal generation and trade recommendations'
+ },
+ {
+ value: 'risk_manager',
+ label: 'Risk Manager',
+ description: 'Portfolio risk assessment and position sizing'
+ },
+ {
+ value: 'portfolio_manager',
+ label: 'Portfolio Manager',
+ description: 'Asset allocation and portfolio optimization'
+ },
+ {
+ value: 'sentiment_analyst',
+ label: 'Sentiment Analyst',
+ description: 'Market sentiment and news analysis'
+ },
+ {
+ value: 'custom',
+ label: 'Custom Agent',
+ description: 'Create your own custom agent'
+ }
+ ];
+ }
+
+ /**
+ * Get available trading strategies
+ */
+ getTradingStrategies(): Array<{ value: string; label: string; description: string }> {
+ return [
+ {
+ value: 'momentum',
+ label: 'Momentum',
+ description: 'Follow strong price trends with momentum indicators'
+ },
+ {
+ value: 'breakout',
+ label: 'Breakout',
+ description: 'Trade breakouts from consolidation zones'
+ },
+ {
+ value: 'reversal',
+ label: 'Reversal',
+ description: 'Identify trend reversals at key levels'
+ },
+ {
+ value: 'trend_following',
+ label: 'Trend Following',
+ description: 'Enter on pullbacks in established trends'
+ }
+ ];
+ }
+
+ /**
+ * Format model string
+ */
+ formatModelString(provider: string, model: string): string {
+ return `${provider}:${model}`;
+ }
+
+ /**
+ * Parse model string
+ */
+ parseModelString(modelString: string): { provider: string; model: string } {
+ const [provider, model] = modelString.split(':');
+ return { provider, model };
+ }
+}
+
+// ============================================================================
+// Export singleton instance
+// ============================================================================
+
+export const agnoTradingService = new AgnoTradingService();
+export default agnoTradingService;
diff --git a/fincept-terminal-desktop/src/services/authApi.tsx b/fincept-terminal-desktop/src/services/authApi.tsx
index 624910994..55d4fc5b3 100644
--- a/fincept-terminal-desktop/src/services/authApi.tsx
+++ b/fincept-terminal-desktop/src/services/authApi.tsx
@@ -161,18 +161,59 @@ const makeApiRequest = async <T = any>(
console.error('❌ Auth JSON parse failed:', parseError);
console.log('📄 Full auth response text:', responseText);
+ // Provide user-friendly error messages based on status code
+ let userFriendlyError = 'Unable to connect to server. Please try again later.';
+
+ if (response.status === 401 || response.status === 403) {
+ userFriendlyError = 'Invalid email or password. Please check your credentials and try again.';
+ } else if (response.status === 404) {
+ userFriendlyError = 'Account not found. Please check your email or sign up for a new account.';
+ } else if (response.status === 400) {
+ userFriendlyError = 'Invalid request. Please check your information and try again.';
+ } else if (response.status >= 500) {
+ userFriendlyError = 'Server error. Please try again later.';
+ } else if (!response.ok) {
+ userFriendlyError = 'An error occurred. Please try again.';
+ }
+
return {
success: false,
- error: `Invalid JSON response: ${responseText.substring(0, 100)}...`,
+ error: userFriendlyError,
status_code: response.status
};
}
+ // Generate user-friendly error message
+ let errorMessage: string | undefined;
+ if (!response.ok) {
+ const backendMessage = responseData.message || responseData.error || '';
+
+ // Map common backend error messages to user-friendly ones
+ if (response.status === 401 || response.status === 403) {
+ // Check if it's specifically about password or general authentication
+ if (backendMessage.toLowerCase().includes('password')) {
+ errorMessage = 'Incorrect password. Please try again.';
+ } else if (backendMessage.toLowerCase().includes('credential')) {
+ errorMessage = 'Invalid email or password. Please check your credentials and try again.';
+ } else {
+ errorMessage = 'Invalid email or password. Please check your credentials and try again.';
+ }
+ } else if (response.status === 404) {
+ errorMessage = 'Account not found. Please check your email or sign up for a new account.';
+ } else if (response.status === 400) {
+ errorMessage = backendMessage || 'Invalid request. Please check your information and try again.';
+ } else if (response.status >= 500) {
+ errorMessage = 'Server error. Please try again later.';
+ } else {
+ errorMessage = backendMessage || `HTTP ${response.status}`;
+ }
+ }
+
return {
success: response.ok,
data: responseData,
status_code: response.status,
- error: response.ok ? undefined : responseData.message || `HTTP ${response.status}`
+ error: errorMessage
};
} catch (error) {
diff --git a/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanAdapter.ts b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanAdapter.ts
index 83cc52905..4bebf0f27 100644
--- a/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanAdapter.ts
+++ b/fincept-terminal-desktop/src/services/backtesting/adapters/lean/LeanAdapter.ts
@@ -230,15 +230,38 @@ export class LeanAdapter extends BaseBacktestingAdapter {
totalReturn: 0,
annualizedReturn: 0,
sharpeRatio: 0,
+ sortinoRatio: 0,
maxDrawdown: 0,
winRate: 0,
+ lossRate: 0,
+ profitFactor: 0,
+ volatility: 0,
+ calmarRatio: 0,
totalTrades: 0,
+ winningTrades: 0,
+ losingTrades: 0,
+ averageWin: 0,
+ averageLoss: 0,
+ largestWin: 0,
+ largestLoss: 0,
+ averageTradeReturn: 0,
+ expectancy: 0,
},
statistics: {
+ startDate: request.startDate,
+ endDate: request.endDate,
initialCapital: request.initialCapital,
finalCapital: request.initialCapital,
totalFees: 0,
+ totalSlippage: 0,
totalTrades: 0,
+ winningDays: 0,
+ losingDays: 0,
+ averageDailyReturn: 0,
+ bestDay: 0,
+ worstDay: 0,
+ consecutiveWins: 0,
+ consecutiveLosses: 0,
},
trades: [],
equity: [],
diff --git a/fincept-terminal-desktop/src/services/sqliteService.ts b/fincept-terminal-desktop/src/services/sqliteService.ts
index 197f36282..75acc6b9d 100644
--- a/fincept-terminal-desktop/src/services/sqliteService.ts
+++ b/fincept-terminal-desktop/src/services/sqliteService.ts
@@ -476,9 +476,6 @@ class SQLiteService {
PRIMARY KEY (symbol, category)
)`,
- // Migration: Add position_value column if it doesn't exist
- `ALTER TABLE paper_trading_positions ADD COLUMN position_value REAL`,
-
// Data source connections table
`CREATE TABLE IF NOT EXISTS data_source_connections (
id TEXT PRIMARY KEY,
@@ -845,8 +842,15 @@ class SQLiteService {
const defaultConfigs = [
{ provider: 'ollama', model: 'llama3.2:3b', base_url: 'http://localhost:11434', is_active: true },
{ provider: 'openai', model: 'gpt-4o-mini', is_active: false },
- { provider: 'gemini', model: 'gemini-2.0-flash-exp', is_active: false },
+ { provider: 'anthropic', model: 'claude-sonnet-4', is_active: false },
+ { provider: 'google', model: 'gemini-2.0-flash-exp', is_active: false },
+ { provider: 'groq', model: 'llama-3.1-70b-versatile', is_active: false },
{ provider: 'deepseek', model: 'deepseek-chat', base_url: 'https://api.deepseek.com', is_active: false },
+ { provider: 'xai', model: 'grok-beta', is_active: false },
+ { provider: 'cohere', model: 'command-r-plus', is_active: false },
+ { provider: 'mistral', model: 'mistral-large-latest', is_active: false },
+ { provider: 'together', model: 'meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo', is_active: false },
+ { provider: 'fireworks', model: 'accounts/fireworks/models/llama-v3p1-70b-instruct', is_active: false },
{ provider: 'openrouter', model: 'meta-llama/llama-3.1-8b-instruct:free', base_url: 'https://openrouter.ai/api/v1', is_active: false },
];