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.

struct update

tilakpatel223a4032f897bc
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/config/agent_cards.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/config/agent_cards.py
index 08c6aa1e3..a7182b773 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/config/agent_cards.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/config/agent_cards.py
@@ -283,6 +283,7 @@ def create_agent_from_card(
card: AgentCard,
api_key: Optional[str] = None,
mode: str = "baseline",
+ trading_style: Optional[str] = None,
):
"""
Create an agent instance from an AgentCard.
@@ -291,6 +292,7 @@ def create_agent_from_card(
card: AgentCard configuration
api_key: Optional API key override
mode: Competition mode
+ trading_style: Optional trading style ID (e.g., "aggressive", "conservative")
Returns:
BaseTradingAgent instance
@@ -305,4 +307,82 @@ def create_agent_from_card(
temperature=card.temperature,
instructions=card.instructions if card.instructions else None,
mode=mode,
+ trading_style=trading_style,
)
+
+
+def create_styled_agents_from_provider(
+ provider: str,
+ model_id: str,
+ api_key: Optional[str] = None,
+ styles: Optional[List[str]] = None,
+ mode: str = "baseline",
+ base_capital: float = 10000.0,
+) -> List[Dict[str, Any]]:
+ """
+ Create multiple agents with different trading styles using the same provider.
+
+ This is useful for running competitions that test different strategies
+ using the same underlying LLM model.
+
+ Args:
+ provider: LLM provider (e.g., "openai", "anthropic")
+ model_id: Model identifier (e.g., "gpt-4o-mini")
+ api_key: API key for the provider
+ styles: List of style IDs to use (defaults to all styles)
+ mode: Competition mode
+ base_capital: Initial capital for each agent
+
+ Returns:
+ List of agent configurations ready for competition
+
+ Example:
+ >>> agents = create_styled_agents_from_provider(
+ ... provider="openai",
+ ... model_id="gpt-4o-mini",
+ ... api_key="sk-...",
+ ... styles=["aggressive", "conservative", "momentum"],
+ ... )
+ """
+ from alpha_arena.config.trading_styles import (
+ list_trading_styles,
+ get_trading_style,
+ TradingStyle,
+ )
+
+ # Get styles to use
+ if styles is None:
+ # Use a default set of contrasting styles
+ styles = ["aggressive", "conservative", "momentum", "contrarian", "neutral"]
+
+ agents = []
+ for style_id in styles:
+ style = get_trading_style(style_id)
+ if style is None:
+ logger.warning(f"Unknown trading style: {style_id}, skipping")
+ continue
+
+ # Create a descriptive name
+ model_short = model_id.split("/")[-1].split("-")[0].title()
+ agent_name = f"{model_short} ({style.name})"
+
+ agents.append({
+ "name": agent_name,
+ "provider": provider,
+ "model_id": model_id,
+ "api_key": api_key,
+ "initial_capital": base_capital,
+ "trading_style": style_id,
+ "mode": mode,
+ })
+
+ return agents
+
+
+def get_available_styles() -> List[Dict[str, Any]]:
+ """Get list of available trading styles for UI display."""
+ try:
+ from alpha_arena.config.trading_styles import list_trading_styles
+ return [style.to_dict() for style in list_trading_styles()]
+ except ImportError:
+ return []
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/config/trading_styles.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/config/trading_styles.py
new file mode 100644
index 000000000..7928711f0
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/config/trading_styles.py
@@ -0,0 +1,423 @@
+"""
+Trading Styles Configuration
+
+Defines different trading personalities/styles that can be applied to any LLM provider.
+This allows running competitions with the same model but different behavioral styles.
+"""
+
+from dataclasses import dataclass, field
+from typing import List, Dict, Any, Optional
+from enum import Enum
+
+
+class TradingStyleType(str, Enum):
+ """Types of trading styles."""
+ AGGRESSIVE = "aggressive"
+ CONSERVATIVE = "conservative"
+ MOMENTUM = "momentum"
+ CONTRARIAN = "contrarian"
+ VALUE = "value"
+ TECHNICAL = "technical"
+ FUNDAMENTAL = "fundamental"
+ SCALPER = "scalper"
+ SWING = "swing"
+ NEUTRAL = "neutral"
+
+
+@dataclass
+class TradingStyle:
+ """
+ Trading style configuration that modifies agent behavior.
+
+ Apply these styles to any LLM to get different trading personalities,
+ allowing comparison of styles using the same underlying model.
+ """
+ id: str
+ name: str
+ description: str
+ style_type: TradingStyleType
+
+ # Behavioral parameters
+ risk_tolerance: float = 0.5 # 0.0 = very low risk, 1.0 = very high risk
+ position_size_pct: float = 0.3 # Default position size as % of portfolio
+ hold_bias: float = 0.0 # -1.0 = sell bias, 0.0 = neutral, 1.0 = buy bias
+
+ # Decision parameters
+ confidence_threshold: float = 0.5 # Minimum confidence to trade
+ temperature_modifier: float = 0.0 # Add to base temperature
+
+ # Style-specific prompt
+ system_prompt: str = ""
+ instructions: List[str] = field(default_factory=list)
+
+ # Trading rules
+ max_trades_per_cycle: int = 3
+ stop_loss_pct: Optional[float] = None
+ take_profit_pct: Optional[float] = None
+
+ # Metadata
+ color: str = "#6B7280" # Display color for UI
+ icon: str = "trending-up"
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "id": self.id,
+ "name": self.name,
+ "description": self.description,
+ "style_type": self.style_type.value,
+ "risk_tolerance": self.risk_tolerance,
+ "position_size_pct": self.position_size_pct,
+ "hold_bias": self.hold_bias,
+ "confidence_threshold": self.confidence_threshold,
+ "temperature_modifier": self.temperature_modifier,
+ "system_prompt": self.system_prompt,
+ "instructions": self.instructions,
+ "max_trades_per_cycle": self.max_trades_per_cycle,
+ "stop_loss_pct": self.stop_loss_pct,
+ "take_profit_pct": self.take_profit_pct,
+ "color": self.color,
+ "icon": self.icon,
+ }
+
+
+# =============================================================================
+# PREDEFINED TRADING STYLES
+# =============================================================================
+
+TRADING_STYLES: Dict[str, TradingStyle] = {
+ "aggressive": TradingStyle(
+ id="aggressive",
+ name="Aggressive Trader",
+ description="High-risk, high-reward trader that seeks maximum gains",
+ style_type=TradingStyleType.AGGRESSIVE,
+ risk_tolerance=0.9,
+ position_size_pct=0.5,
+ hold_bias=0.2, # Slight buy bias
+ confidence_threshold=0.4,
+ temperature_modifier=0.1,
+ system_prompt="""You are an AGGRESSIVE crypto trader focused on maximizing gains.
+Your trading philosophy:
+- Take calculated risks for higher rewards
+- Enter positions quickly when you see opportunity
+- Don't be afraid to use larger position sizes
+- Momentum is your friend - ride the trends
+- Cut losses quickly but let winners run
+
+You prefer action over waiting. When in doubt, lean towards trading rather than holding.""",
+ instructions=[
+ "Be decisive and action-oriented",
+ "Look for strong momentum signals",
+ "Use larger position sizes (40-60% of capital)",
+ "Enter trades with conviction",
+ "Don't overthink - trust your analysis",
+ ],
+ max_trades_per_cycle=5,
+ stop_loss_pct=0.08,
+ take_profit_pct=0.15,
+ color="#EF4444", # Red
+ icon="zap",
+ ),
+
+ "conservative": TradingStyle(
+ id="conservative",
+ name="Conservative Trader",
+ description="Low-risk trader focused on capital preservation",
+ style_type=TradingStyleType.CONSERVATIVE,
+ risk_tolerance=0.2,
+ position_size_pct=0.15,
+ hold_bias=-0.1, # Slight hold/sell bias
+ confidence_threshold=0.7,
+ temperature_modifier=-0.1,
+ system_prompt="""You are a CONSERVATIVE crypto trader focused on capital preservation.
+Your trading philosophy:
+- Protect capital at all costs
+- Only trade with high conviction setups
+- Use small position sizes to limit risk
+- Prefer to miss opportunities than take bad trades
+- Cash is a position - being in fiat is fine
+
+You prefer patience over action. When in doubt, stay in cash or reduce exposure.""",
+ instructions=[
+ "Prioritize capital preservation",
+ "Only trade high-confidence setups (70%+)",
+ "Use small position sizes (10-20% of capital)",
+ "Set tight stop losses",
+ "Be patient - wait for the best opportunities",
+ ],
+ max_trades_per_cycle=2,
+ stop_loss_pct=0.03,
+ take_profit_pct=0.06,
+ color="#10B981", # Green
+ icon="shield",
+ ),
+
+ "momentum": TradingStyle(
+ id="momentum",
+ name="Momentum Trader",
+ description="Follows trends and rides momentum",
+ style_type=TradingStyleType.MOMENTUM,
+ risk_tolerance=0.6,
+ position_size_pct=0.35,
+ hold_bias=0.1,
+ confidence_threshold=0.5,
+ temperature_modifier=0.0,
+ system_prompt="""You are a MOMENTUM crypto trader who follows market trends.
+Your trading philosophy:
+- The trend is your friend
+- Buy what's going up, sell what's going down
+- Use price action and volume to confirm trends
+- Don't fight the market - go with the flow
+- Let winners run, cut losers quickly
+
+Look for strong directional moves with volume confirmation.""",
+ instructions=[
+ "Identify the current market trend",
+ "Buy assets showing upward momentum",
+ "Sell assets showing downward momentum",
+ "Use volume to confirm moves",
+ "Trail stops to protect profits",
+ ],
+ max_trades_per_cycle=3,
+ stop_loss_pct=0.05,
+ take_profit_pct=0.12,
+ color="#3B82F6", # Blue
+ icon="trending-up",
+ ),
+
+ "contrarian": TradingStyle(
+ id="contrarian",
+ name="Contrarian Trader",
+ description="Goes against the crowd, buys fear and sells greed",
+ style_type=TradingStyleType.CONTRARIAN,
+ risk_tolerance=0.5,
+ position_size_pct=0.25,
+ hold_bias=0.0,
+ confidence_threshold=0.6,
+ temperature_modifier=0.0,
+ system_prompt="""You are a CONTRARIAN crypto trader who goes against the crowd.
+Your trading philosophy:
+- Buy when others are fearful
+- Sell when others are greedy
+- Look for overextended moves to fade
+- Mean reversion is powerful in crypto
+- Patience pays - wait for extremes
+
+The crowd is usually wrong at extremes. Your job is to identify those extremes.""",
+ instructions=[
+ "Look for sentiment extremes",
+ "Buy during panic and fear",
+ "Sell during euphoria and greed",
+ "Fade overextended moves",
+ "Be patient for the best setups",
+ ],
+ max_trades_per_cycle=2,
+ stop_loss_pct=0.06,
+ take_profit_pct=0.10,
+ color="#8B5CF6", # Purple
+ icon="refresh-cw",
+ ),
+
+ "scalper": TradingStyle(
+ id="scalper",
+ name="Scalper",
+ description="Makes many small trades for quick profits",
+ style_type=TradingStyleType.SCALPER,
+ risk_tolerance=0.4,
+ position_size_pct=0.2,
+ hold_bias=0.0,
+ confidence_threshold=0.45,
+ temperature_modifier=0.15,
+ system_prompt="""You are a SCALPER crypto trader focused on quick, small profits.
+Your trading philosophy:
+- Many small gains add up to big profits
+- Get in and out quickly
+- Don't wait for home runs - take base hits
+- Tight stops, tight targets
+- Trade frequently when opportunities appear
+
+Speed and execution matter. Take profits quickly and move to the next trade.""",
+ instructions=[
+ "Take quick profits (2-5%)",
+ "Don't hold positions too long",
+ "Use tight stop losses",
+ "Trade frequently",
+ "Focus on liquid markets",
+ ],
+ max_trades_per_cycle=8,
+ stop_loss_pct=0.02,
+ take_profit_pct=0.04,
+ color="#F59E0B", # Amber
+ icon="activity",
+ ),
+
+ "swing": TradingStyle(
+ id="swing",
+ name="Swing Trader",
+ description="Holds positions for multiple cycles to capture larger moves",
+ style_type=TradingStyleType.SWING,
+ risk_tolerance=0.5,
+ position_size_pct=0.3,
+ hold_bias=0.3, # Bias towards holding
+ confidence_threshold=0.55,
+ temperature_modifier=-0.05,
+ system_prompt="""You are a SWING crypto trader who captures larger market moves.
+Your trading philosophy:
+- Patience is key - wait for the right setup
+- Hold positions to capture bigger moves
+- Don't get shaken out by small fluctuations
+- Trade less but make each trade count
+- Let profits run when you have a winner
+
+Think in terms of larger price swings, not tick-by-tick movements.""",
+ instructions=[
+ "Look for larger price swing setups",
+ "Be patient with winning positions",
+ "Don't overtrade - quality over quantity",
+ "Use wider stops to avoid whipsaws",
+ "Hold through minor pullbacks",
+ ],
+ max_trades_per_cycle=2,
+ stop_loss_pct=0.07,
+ take_profit_pct=0.18,
+ color="#14B8A6", # Teal
+ icon="maximize-2",
+ ),
+
+ "technical": TradingStyle(
+ id="technical",
+ name="Technical Analyst",
+ description="Trades based on chart patterns and technical indicators",
+ style_type=TradingStyleType.TECHNICAL,
+ risk_tolerance=0.5,
+ position_size_pct=0.25,
+ hold_bias=0.0,
+ confidence_threshold=0.55,
+ temperature_modifier=0.0,
+ system_prompt="""You are a TECHNICAL ANALYST crypto trader.
+Your trading philosophy:
+- Charts tell the whole story
+- Price action is the ultimate indicator
+- Support and resistance levels matter
+- Patterns repeat in markets
+- Let the technicals guide your decisions
+
+Focus on what the chart is telling you, not on news or fundamentals.""",
+ instructions=[
+ "Analyze price patterns and trends",
+ "Identify key support/resistance levels",
+ "Use price action signals",
+ "Look for chart pattern breakouts",
+ "Respect technical levels",
+ ],
+ max_trades_per_cycle=3,
+ stop_loss_pct=0.05,
+ take_profit_pct=0.10,
+ color="#EC4899", # Pink
+ icon="bar-chart-2",
+ ),
+
+ "fundamental": TradingStyle(
+ id="fundamental",
+ name="Fundamental Analyst",
+ description="Trades based on project fundamentals and value",
+ style_type=TradingStyleType.FUNDAMENTAL,
+ risk_tolerance=0.4,
+ position_size_pct=0.3,
+ hold_bias=0.2,
+ confidence_threshold=0.6,
+ temperature_modifier=-0.1,
+ system_prompt="""You are a FUNDAMENTAL ANALYST crypto trader.
+Your trading philosophy:
+- Understand what you're buying
+- Value matters in the long run
+- Quality projects outperform over time
+- News and developments drive value
+- Market cap and tokenomics matter
+
+Focus on the underlying value and fundamentals, not just price action.""",
+ instructions=[
+ "Evaluate project fundamentals",
+ "Consider market cap and valuation",
+ "Factor in news and developments",
+ "Think about long-term value",
+ "Buy quality, avoid hype",
+ ],
+ max_trades_per_cycle=2,
+ stop_loss_pct=0.06,
+ take_profit_pct=0.15,
+ color="#6366F1", # Indigo
+ icon="search",
+ ),
+
+ "neutral": TradingStyle(
+ id="neutral",
+ name="Balanced Trader",
+ description="Balanced approach with no specific bias",
+ style_type=TradingStyleType.NEUTRAL,
+ risk_tolerance=0.5,
+ position_size_pct=0.25,
+ hold_bias=0.0,
+ confidence_threshold=0.5,
+ temperature_modifier=0.0,
+ system_prompt="""You are a BALANCED crypto trader with no specific bias.
+Your trading philosophy:
+- Adapt to market conditions
+- Use a mix of technical and fundamental analysis
+- Balance risk and reward
+- Stay flexible in your approach
+- Let the market guide your decisions
+
+Be adaptable and respond to what the market is showing you.""",
+ instructions=[
+ "Use balanced analysis",
+ "Adapt to market conditions",
+ "Manage risk appropriately",
+ "Stay flexible in approach",
+ "Make well-reasoned decisions",
+ ],
+ max_trades_per_cycle=3,
+ stop_loss_pct=0.05,
+ take_profit_pct=0.10,
+ color="#6B7280", # Gray
+ icon="balance-scale",
+ ),
+}
+
+
+def get_trading_style(style_id: str) -> Optional[TradingStyle]:
+ """Get a trading style by ID."""
+ return TRADING_STYLES.get(style_id)
+
+
+def list_trading_styles() -> List[TradingStyle]:
+ """List all available trading styles."""
+ return list(TRADING_STYLES.values())
+
+
+def get_styles_by_type(style_type: TradingStyleType) -> List[TradingStyle]:
+ """Get styles by type."""
+ return [s for s in TRADING_STYLES.values() if s.style_type == style_type]
+
+
+def create_styled_agent_name(provider: str, model_id: str, style: TradingStyle) -> str:
+ """Create a display name for a styled agent."""
+ # Shorten model name for display
+ model_short = model_id.split("/")[-1].split("-")[0].title()
+ return f"{model_short} ({style.name})"
+
+
+def get_style_system_prompt(style: TradingStyle, base_prompt: str = "") -> str:
+ """Combine style prompt with base prompt."""
+ parts = []
+
+ if style.system_prompt:
+ parts.append(style.system_prompt)
+
+ if base_prompt:
+ parts.append(base_prompt)
+
+ if style.instructions:
+ instructions_text = "\n".join(f"- {i}" for i in style.instructions)
+ parts.append(f"\nKey Instructions:\n{instructions_text}")
+
+ return "\n\n".join(parts)
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/__init__.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/__init__.py
index 7fce59abd..c57e143e3 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/__init__.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/__init__.py
@@ -2,19 +2,158 @@
Alpha Arena Core Module
Contains the core components for the trading competition system.
+
+Components:
+- Base agents for trading (LLM-based and rule-based)
+- Features pipeline for technical analysis
+- Portfolio metrics with Sharpe ratio
+- Grid trading strategy
+- Research agent for SEC filings
+- Human-in-the-Loop approval system
"""
-from alpha_arena.core.base_agent import BaseAgent, BaseTradingAgent
+from alpha_arena.core.base_agent import BaseAgent, BaseTradingAgent, LLMTradingAgent
from alpha_arena.core.competition import AlphaArenaCompetition
-from alpha_arena.core.paper_trading import PaperTradingEngine
+from alpha_arena.core.paper_trading import PaperTradingEngine # Legacy, kept for compatibility
+from alpha_arena.core.paper_trading_bridge import (
+ PaperTradingBridge,
+ create_paper_trading_bridge,
+)
from alpha_arena.core.agent_manager import AgentManager
from alpha_arena.core.market_data import MarketDataProvider
+# New components
+from alpha_arena.core.features_pipeline import (
+ DefaultFeaturesPipeline,
+ MarketFeatures,
+ TechnicalFeatures,
+ SentimentFeatures,
+ get_features_pipeline,
+)
+from alpha_arena.core.portfolio_metrics import (
+ PortfolioAnalyzer,
+ PortfolioMetrics,
+ get_analyzer,
+)
+from alpha_arena.core.grid_agent import (
+ GridStrategyAgent,
+ GridConfig,
+ GridState,
+)
+from alpha_arena.core.hitl import (
+ HITLManager,
+ ApprovalRequest,
+ ApprovalStatus,
+ RiskLevel,
+ get_hitl_manager,
+ check_decision_approval,
+ approve_decision,
+ reject_decision,
+ get_pending_approvals,
+)
+from alpha_arena.core.research_agent import (
+ ResearchAgent,
+ ResearchReport,
+ get_research_agent,
+ get_research_context,
+)
+from alpha_arena.core.broker_adapter import (
+ BrokerAdapter,
+ BrokerInfo,
+ BrokerType,
+ BrokerRegion,
+ MultiExchangeDataProvider,
+ OrderRequest,
+ OrderResult,
+ get_supported_brokers,
+ get_broker_info,
+ get_brokers_by_type,
+ get_brokers_by_region,
+ create_broker_adapter,
+ get_multi_exchange_provider,
+)
+from alpha_arena.core.sentiment_agent import (
+ SentimentAgent,
+ SentimentResult,
+ SentimentLevel,
+ NewsArticle,
+ get_sentiment_agent,
+ get_sentiment_context,
+)
+from alpha_arena.core.memory_adapter import (
+ AgentMemory,
+ TradeMemory,
+ MarketInsight,
+ get_agent_memory,
+ clear_all_memories,
+)
+
__all__ = [
+ # Base agents
"BaseAgent",
"BaseTradingAgent",
+ "LLMTradingAgent",
+ # Competition
"AlphaArenaCompetition",
- "PaperTradingEngine",
+ "PaperTradingEngine", # Legacy, kept for compatibility
+ "PaperTradingBridge", # New database-backed bridge
+ "create_paper_trading_bridge",
"AgentManager",
"MarketDataProvider",
+ # Features pipeline
+ "DefaultFeaturesPipeline",
+ "MarketFeatures",
+ "TechnicalFeatures",
+ "SentimentFeatures",
+ "get_features_pipeline",
+ # Portfolio metrics
+ "PortfolioAnalyzer",
+ "PortfolioMetrics",
+ "get_analyzer",
+ # Grid trading
+ "GridStrategyAgent",
+ "GridConfig",
+ "GridState",
+ # HITL
+ "HITLManager",
+ "ApprovalRequest",
+ "ApprovalStatus",
+ "RiskLevel",
+ "get_hitl_manager",
+ "check_decision_approval",
+ "approve_decision",
+ "reject_decision",
+ "get_pending_approvals",
+ # Research
+ "ResearchAgent",
+ "ResearchReport",
+ "get_research_agent",
+ "get_research_context",
+ # Broker adapters
+ "BrokerAdapter",
+ "BrokerInfo",
+ "BrokerType",
+ "BrokerRegion",
+ "MultiExchangeDataProvider",
+ "OrderRequest",
+ "OrderResult",
+ "get_supported_brokers",
+ "get_broker_info",
+ "get_brokers_by_type",
+ "get_brokers_by_region",
+ "create_broker_adapter",
+ "get_multi_exchange_provider",
+ # Sentiment analysis
+ "SentimentAgent",
+ "SentimentResult",
+ "SentimentLevel",
+ "NewsArticle",
+ "get_sentiment_agent",
+ "get_sentiment_context",
+ # Memory adapter
+ "AgentMemory",
+ "TradeMemory",
+ "MarketInsight",
+ "get_agent_memory",
+ "clear_all_memories",
]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/agent_manager.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/agent_manager.py
index 61b6210c5..99f4bdef3 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/agent_manager.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/agent_manager.py
@@ -25,7 +25,12 @@ class AgentContext:
is_running: bool = False
api_key: Optional[str] = None
metadata: Dict[str, Any] = field(default_factory=dict)
- _lock: asyncio.Lock = field(default_factory=asyncio.Lock)
+ _lock: Optional[asyncio.Lock] = field(default=None, repr=False)
+
+ def __post_init__(self):
+ """Initialize the lock after instance creation."""
+ if self._lock is None:
+ self._lock = asyncio.Lock()
class AgentManager:
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/base_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/base_agent.py
index b617f9247..81dcb756a 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/base_agent.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/base_agent.py
@@ -2,9 +2,14 @@
Base Agent Abstract Class
Defines the interface for all trading agents in Alpha Arena.
-Inspired by ValueCell's BaseAgent architecture with stream/notify methods.
+Supports:
+- stream/notify pattern for user/agent-initiated actions
+- Features pipeline for technical analysis
+- Portfolio metrics tracking
+- Integration with finagent_core
"""
+import asyncio
from abc import ABC, abstractmethod
from typing import AsyncGenerator, Dict, List, Optional, Any
from datetime import datetime
@@ -22,6 +27,31 @@ from alpha_arena.utils.logging import get_logger
logger = get_logger("base_agent")
+# Import features pipeline (optional)
+try:
+ from alpha_arena.core.features_pipeline import (
+ DefaultFeaturesPipeline,
+ MarketFeatures,
+ get_features_pipeline,
+ )
+ FEATURES_AVAILABLE = True
+except ImportError:
+ FEATURES_AVAILABLE = False
+ logger.debug("Features pipeline not available")
+
+# Import portfolio metrics (optional)
+try:
+ from alpha_arena.core.portfolio_metrics import (
+ PortfolioAnalyzer,
+ PortfolioMetrics,
+ get_analyzer,
+ )
+ METRICS_AVAILABLE = True
+except ImportError:
+ METRICS_AVAILABLE = False
+ logger.debug("Portfolio metrics not available")
+
+
class BaseAgent(ABC):
"""
Abstract base class for all agents in Alpha Arena.
@@ -101,6 +131,8 @@ class BaseTradingAgent(BaseAgent):
- Processing market data
- Making trading decisions
- Managing portfolio state
+ - Features pipeline integration
+ - Portfolio metrics tracking
"""
def __init__(
@@ -111,6 +143,8 @@ class BaseTradingAgent(BaseAgent):
api_key: Optional[str] = None,
temperature: float = 0.7,
instructions: Optional[List[str]] = None,
+ enable_features: bool = True,
+ enable_metrics: bool = True,
):
super().__init__(name)
self.provider = provider
@@ -121,6 +155,14 @@ class BaseTradingAgent(BaseAgent):
self._agent = None
self._decisions: List[ModelDecision] = []
+ # Features pipeline
+ self.enable_features = enable_features and FEATURES_AVAILABLE
+ self._features_pipeline = get_features_pipeline() if self.enable_features else None
+
+ # Portfolio metrics
+ self.enable_metrics = enable_metrics and METRICS_AVAILABLE
+ self._portfolio_analyzer: Optional[PortfolioAnalyzer] = None
+
def _default_instructions(self) -> List[str]:
"""Default trading instructions."""
return [
@@ -130,6 +172,50 @@ class BaseTradingAgent(BaseAgent):
"Consider risk management and position sizing carefully.",
]
+ def initialize_metrics(self, initial_capital: float = 10000.0):
+ """Initialize portfolio metrics tracking"""
+ if self.enable_metrics:
+ self._portfolio_analyzer = get_analyzer(self.name, initial_capital)
+ logger.info(f"Portfolio metrics initialized for {self.name}")
+
+ def record_portfolio_value(self, value: float):
+ """Record portfolio value for metrics calculation"""
+ if self._portfolio_analyzer:
+ self._portfolio_analyzer.record_value(value)
+
+ def record_trade(self, pnl: float, entry_price: float, exit_price: float, quantity: float, side: str):
+ """Record a completed trade for metrics"""
+ if self._portfolio_analyzer:
+ self._portfolio_analyzer.record_trade(pnl, entry_price, exit_price, quantity, side)
+
+ def get_metrics(self) -> Optional[Dict[str, Any]]:
+ """Get current portfolio metrics"""
+ if self._portfolio_analyzer:
+ metrics = self._portfolio_analyzer.calculate_metrics()
+ return metrics.to_dict()
+ return None
+
+ def get_metrics_context(self) -> str:
+ """Get metrics as text for LLM context"""
+ if self._portfolio_analyzer:
+ metrics = self._portfolio_analyzer.calculate_metrics()
+ return metrics.to_prompt_context()
+ return ""
+
+ async def compute_features(self, market_data: MarketData) -> Optional[Dict[str, Any]]:
+ """Compute market features for decision making"""
+ if self._features_pipeline:
+ features = await self._features_pipeline.compute(market_data)
+ return features.to_dict()
+ return None
+
+ async def get_features_context(self, market_data: MarketData) -> str:
+ """Get features as text for LLM context"""
+ if self._features_pipeline:
+ features = await self._features_pipeline.compute(market_data)
+ return features.to_prompt_context()
+ return ""
+
@abstractmethod
async def make_decision(
self,
@@ -225,6 +311,7 @@ class LLMTradingAgent(BaseTradingAgent):
Trading agent powered by an LLM (OpenAI, Anthropic, etc.).
Uses the Agno library for LLM interactions when available.
+ Supports trading styles for behavioral customization.
"""
def __init__(
@@ -236,11 +323,43 @@ class LLMTradingAgent(BaseTradingAgent):
temperature: float = 0.7,
instructions: Optional[List[str]] = None,
mode: str = "baseline",
+ trading_style: Optional[str] = None, # Style ID (e.g., "aggressive", "conservative")
+ style_config: Optional[Dict[str, Any]] = None, # Full style configuration
):
super().__init__(name, provider, model_id, api_key, temperature, instructions)
self.mode = mode
self._llm = None
+ # Trading style support
+ self.trading_style_id = trading_style
+ self._style = None
+
+ # Load trading style if specified
+ if trading_style:
+ try:
+ from alpha_arena.config.trading_styles import get_trading_style
+ self._style = get_trading_style(trading_style)
+ if self._style:
+ # Apply style's temperature modifier
+ self.temperature = temperature + self._style.temperature_modifier
+ logger.info(f"Agent '{name}' using trading style: {self._style.name}")
+ except ImportError:
+ logger.warning("Trading styles module not available")
+ elif style_config:
+ # Use provided style config directly
+ from alpha_arena.config.trading_styles import TradingStyle, TradingStyleType
+ self._style = TradingStyle(
+ id=style_config.get("id", "custom"),
+ name=style_config.get("name", "Custom Style"),
+ description=style_config.get("description", ""),
+ style_type=TradingStyleType(style_config.get("style_type", "neutral")),
+ system_prompt=style_config.get("system_prompt", ""),
+ instructions=style_config.get("instructions", []),
+ risk_tolerance=style_config.get("risk_tolerance", 0.5),
+ position_size_pct=style_config.get("position_size_pct", 0.25),
+ confidence_threshold=style_config.get("confidence_threshold", 0.5),
+ )
+
async def initialize(self) -> bool:
"""Initialize the LLM agent."""
try:
@@ -280,9 +399,13 @@ class LLMTradingAgent(BaseTradingAgent):
elif self.provider == "google" or self.provider == "gemini":
# Google Gemini - use OpenAI-compatible endpoint directly (more reliable)
# Model IDs: gemini-2.0-flash, gemini-1.5-flash, gemini-1.5-pro, etc.
- logger.info(f"Using Google Gemini OpenAI-compatible endpoint for {self.model_id}")
+ # Strip "gemini/" prefix if present (LiteLLM format vs Google API format)
+ model_id = self.model_id
+ if model_id.startswith("gemini/"):
+ model_id = model_id[7:] # Remove "gemini/" prefix
+ logger.info(f"Using Google Gemini OpenAI-compatible endpoint for {model_id}")
model = OpenAIChat(
- id=self.model_id,
+ id=model_id,
api_key=self.api_key,
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
)
@@ -338,9 +461,24 @@ class LLMTradingAgent(BaseTradingAgent):
return None
def _get_mode_instructions(self) -> List[str]:
- """Get instructions based on competition mode."""
+ """Get instructions based on competition mode and trading style."""
base = self.instructions.copy()
+ # Add style-specific system prompt and instructions first (higher priority)
+ if self._style:
+ if self._style.system_prompt:
+ base.insert(0, self._style.system_prompt)
+ if self._style.instructions:
+ base.extend(self._style.instructions)
+
+ # Add style-specific trading parameters
+ base.extend([
+ f"Risk tolerance: {self._style.risk_tolerance:.0%} (0%=very conservative, 100%=very aggressive)",
+ f"Target position size: {self._style.position_size_pct:.0%} of available capital",
+ f"Minimum confidence threshold: {self._style.confidence_threshold:.0%}",
+ ])
+
+ # Add mode-specific instructions (lower priority than style)
if self.mode == "baseline":
base.extend([
"Use comprehensive analysis considering all market data.",
@@ -390,7 +528,10 @@ class LLMTradingAgent(BaseTradingAgent):
logger.info(f"Agent '{self.name}' requesting decision from {self.provider}:{self.model_id}...")
# Get response from LLM
- response = self._llm.run(prompt)
+ # Note: Agno's agent.run() is synchronous, so we run it in a thread pool
+ # to avoid blocking the async event loop
+ loop = asyncio.get_event_loop()
+ response = await loop.run_in_executor(None, self._llm.run, prompt)
# Detailed response logging for debugging
resp_type = type(response).__name__
@@ -460,13 +601,44 @@ class LLMTradingAgent(BaseTradingAgent):
price_at_decision=market_data.price,
)
+ async def _build_prompt_async(
+ self,
+ market_data: MarketData,
+ portfolio: PortfolioState,
+ cycle_number: int,
+ ) -> str:
+ """Build the trading prompt with features and metrics (async version)."""
+ # Get features context if available
+ features_context = ""
+ if self.enable_features and self._features_pipeline:
+ try:
+ features_context = await self.get_features_context(market_data)
+ except Exception as e:
+ logger.warning(f"Failed to compute features: {e}")
+
+ # Get metrics context if available
+ metrics_context = self.get_metrics_context()
+
+ return self._build_prompt_internal(market_data, portfolio, cycle_number, features_context, metrics_context)
+
def _build_prompt(
self,
market_data: MarketData,
portfolio: PortfolioState,
cycle_number: int,
) -> str:
- """Build the trading prompt."""
+ """Build the trading prompt (sync version, no features)."""
+ return self._build_prompt_internal(market_data, portfolio, cycle_number, "", "")
+
+ def _build_prompt_internal(
+ self,
+ market_data: MarketData,
+ portfolio: PortfolioState,
+ cycle_number: int,
+ features_context: str,
+ metrics_context: str,
+ ) -> str:
+ """Build the trading prompt with optional features and metrics."""
has_positions = len(portfolio.positions) > 0
num_trades = portfolio.trades_count
pnl = portfolio.portfolio_value - 10000 # Assuming 10k initial
@@ -492,6 +664,13 @@ You have open positions. Decide whether to:
- HOLD: Maintain current position
"""
+ # Build optional sections
+ optional_sections = ""
+ if features_context:
+ optional_sections += f"\n{features_context}\n"
+ if metrics_context:
+ optional_sections += f"\n{metrics_context}\n"
+
return f"""ALPHA ARENA TRADING DECISION - Cycle #{cycle_number}
MARKET DATA:
@@ -509,7 +688,7 @@ Portfolio Value: ${portfolio.portfolio_value:,.2f}
P&L: ${pnl:+,.2f} ({pnl_pct:+.2f}%)
Open Positions: {len(portfolio.positions)}
Total Trades Made: {num_trades}
-{action_guidance}
+{optional_sections}{action_guidance}
RESPONSE FORMAT (JSON ONLY - NO MARKDOWN, NO CODE BLOCKS):
{{
"action": "buy" or "sell" or "hold",
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/broker_adapter.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/broker_adapter.py
new file mode 100644
index 000000000..7781eb8a8
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/broker_adapter.py
@@ -0,0 +1,840 @@
+"""
+Broker Adapter for Alpha Arena
+
+Provides unified access to multiple exchange adapters via Tauri commands.
+Extends market data capabilities to support live trading when enabled.
+"""
+
+import asyncio
+from datetime import datetime
+from typing import Dict, List, Optional, Any
+from dataclasses import dataclass, field
+from enum import Enum
+
+try:
+ import httpx
+ HTTPX_AVAILABLE = True
+except ImportError:
+ HTTPX_AVAILABLE = False
+
+from alpha_arena.types.models import MarketData, TradeAction
+from alpha_arena.utils.logging import get_logger
+
+logger = get_logger("broker_adapter")
+
+
+class BrokerType(str, Enum):
+ """Supported broker types."""
+ CRYPTO = "crypto"
+ STOCKS = "stocks"
+ FOREX = "forex"
+
+
+class BrokerRegion(str, Enum):
+ """Broker region classification."""
+ GLOBAL = "global"
+ US = "us"
+ INDIA = "india"
+ EUROPE = "europe"
+ ASIA = "asia"
+
+
+@dataclass
+class BrokerInfo:
+ """Broker metadata."""
+ id: str
+ name: str
+ display_name: str
+ broker_type: BrokerType
+ region: BrokerRegion
+ supports_spot: bool = True
+ supports_margin: bool = False
+ supports_futures: bool = False
+ supports_options: bool = False
+ max_leverage: float = 1.0
+ default_symbols: List[str] = field(default_factory=list)
+ maker_fee: float = 0.001
+ taker_fee: float = 0.001
+ websocket_enabled: bool = False
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "id": self.id,
+ "name": self.name,
+ "display_name": self.display_name,
+ "broker_type": self.broker_type.value,
+ "region": self.region.value,
+ "supports_spot": self.supports_spot,
+ "supports_margin": self.supports_margin,
+ "supports_futures": self.supports_futures,
+ "supports_options": self.supports_options,
+ "max_leverage": self.max_leverage,
+ "default_symbols": self.default_symbols,
+ "maker_fee": self.maker_fee,
+ "taker_fee": self.taker_fee,
+ "websocket_enabled": self.websocket_enabled,
+ }
+
+
+@dataclass
+class OrderRequest:
+ """Order request for execution."""
+ symbol: str
+ side: TradeAction # BUY, SELL
+ quantity: float
+ order_type: str = "market" # market, limit, stop, stop_limit
+ price: Optional[float] = None # For limit orders
+ stop_price: Optional[float] = None # For stop orders
+ time_in_force: str = "gtc" # gtc, ioc, fok
+
+
+@dataclass
+class OrderResult:
+ """Order execution result."""
+ success: bool
+ order_id: Optional[str] = None
+ status: str = "" # open, filled, partial, cancelled, rejected
+ filled_quantity: float = 0.0
+ filled_price: float = 0.0
+ fee: float = 0.0
+ error: Optional[str] = None
+ timestamp: datetime = field(default_factory=datetime.now)
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "success": self.success,
+ "order_id": self.order_id,
+ "status": self.status,
+ "filled_quantity": self.filled_quantity,
+ "filled_price": self.filled_price,
+ "fee": self.fee,
+ "error": self.error,
+ "timestamp": self.timestamp.isoformat(),
+ }
+
+
+# =============================================================================
+# BROKER REGISTRY
+# =============================================================================
+
+SUPPORTED_BROKERS: Dict[str, BrokerInfo] = {
+ # Crypto exchanges
+ "kraken": BrokerInfo(
+ id="kraken",
+ name="kraken",
+ display_name="Kraken",
+ broker_type=BrokerType.CRYPTO,
+ region=BrokerRegion.GLOBAL,
+ supports_margin=True,
+ supports_futures=True,
+ max_leverage=5.0,
+ default_symbols=["BTC/USD", "ETH/USD", "SOL/USD", "XRP/USD"],
+ maker_fee=0.0016,
+ taker_fee=0.0026,
+ websocket_enabled=True,
+ ),
+ "binance": BrokerInfo(
+ id="binance",
+ name="binance",
+ display_name="Binance",
+ broker_type=BrokerType.CRYPTO,
+ region=BrokerRegion.GLOBAL,
+ supports_margin=True,
+ supports_futures=True,
+ supports_options=True,
+ max_leverage=125.0,
+ default_symbols=["BTC/USDT", "ETH/USDT", "BNB/USDT", "SOL/USDT"],
+ maker_fee=0.001,
+ taker_fee=0.001,
+ websocket_enabled=True,
+ ),
+ "okx": BrokerInfo(
+ id="okx",
+ name="okx",
+ display_name="OKX",
+ broker_type=BrokerType.CRYPTO,
+ region=BrokerRegion.GLOBAL,
+ supports_margin=True,
+ supports_futures=True,
+ supports_options=True,
+ max_leverage=125.0,
+ default_symbols=["BTC/USDT", "ETH/USDT", "SOL/USDT"],
+ maker_fee=0.0008,
+ taker_fee=0.001,
+ websocket_enabled=True,
+ ),
+ "coinbase": BrokerInfo(
+ id="coinbase",
+ name="coinbase",
+ display_name="Coinbase",
+ broker_type=BrokerType.CRYPTO,
+ region=BrokerRegion.US,
+ supports_margin=False,
+ max_leverage=1.0,
+ default_symbols=["BTC/USD", "ETH/USD", "SOL/USD"],
+ maker_fee=0.004,
+ taker_fee=0.006,
+ websocket_enabled=True,
+ ),
+ "bybit": BrokerInfo(
+ id="bybit",
+ name="bybit",
+ display_name="Bybit",
+ broker_type=BrokerType.CRYPTO,
+ region=BrokerRegion.GLOBAL,
+ supports_margin=True,
+ supports_futures=True,
+ supports_options=True,
+ max_leverage=100.0,
+ default_symbols=["BTC/USDT", "ETH/USDT", "SOL/USDT"],
+ maker_fee=0.001,
+ taker_fee=0.001,
+ websocket_enabled=True,
+ ),
+ "kucoin": BrokerInfo(
+ id="kucoin",
+ name="kucoin",
+ display_name="KuCoin",
+ broker_type=BrokerType.CRYPTO,
+ region=BrokerRegion.GLOBAL,
+ supports_margin=True,
+ supports_futures=True,
+ max_leverage=100.0,
+ default_symbols=["BTC/USDT", "ETH/USDT", "SOL/USDT"],
+ maker_fee=0.001,
+ taker_fee=0.001,
+ websocket_enabled=True,
+ ),
+ "gateio": BrokerInfo(
+ id="gateio",
+ name="gateio",
+ display_name="Gate.io",
+ broker_type=BrokerType.CRYPTO,
+ region=BrokerRegion.GLOBAL,
+ supports_margin=True,
+ supports_futures=True,
+ supports_options=True,
+ max_leverage=100.0,
+ default_symbols=["BTC/USDT", "ETH/USDT", "SOL/USDT"],
+ maker_fee=0.002,
+ taker_fee=0.002,
+ websocket_enabled=True,
+ ),
+ "hyperliquid": BrokerInfo(
+ id="hyperliquid",
+ name="hyperliquid",
+ display_name="HyperLiquid",
+ broker_type=BrokerType.CRYPTO,
+ region=BrokerRegion.GLOBAL,
+ supports_margin=False,
+ supports_futures=True,
+ max_leverage=50.0,
+ default_symbols=["BTC/USD", "ETH/USD", "SOL/USD"],
+ maker_fee=0.00015,
+ taker_fee=0.00035,
+ websocket_enabled=True,
+ ),
+
+ # Indian stock brokers
+ "zerodha": BrokerInfo(
+ id="zerodha",
+ name="zerodha",
+ display_name="Zerodha (Kite)",
+ broker_type=BrokerType.STOCKS,
+ region=BrokerRegion.INDIA,
+ supports_margin=True,
+ supports_futures=True,
+ supports_options=True,
+ max_leverage=5.0,
+ default_symbols=["RELIANCE", "TCS", "HDFCBANK", "INFY"],
+ maker_fee=0.0,
+ taker_fee=0.0003,
+ websocket_enabled=True,
+ ),
+ "fyers": BrokerInfo(
+ id="fyers",
+ name="fyers",
+ display_name="Fyers",
+ broker_type=BrokerType.STOCKS,
+ region=BrokerRegion.INDIA,
+ supports_margin=True,
+ supports_futures=True,
+ supports_options=True,
+ max_leverage=5.0,
+ default_symbols=["RELIANCE", "TCS", "HDFCBANK", "INFY"],
+ maker_fee=0.0,
+ taker_fee=0.0003,
+ websocket_enabled=True,
+ ),
+
+ # US stock brokers
+ "alpaca": BrokerInfo(
+ id="alpaca",
+ name="alpaca",
+ display_name="Alpaca",
+ broker_type=BrokerType.STOCKS,
+ region=BrokerRegion.US,
+ supports_margin=True,
+ supports_futures=False,
+ max_leverage=4.0,
+ default_symbols=["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"],
+ maker_fee=0.0,
+ taker_fee=0.0,
+ websocket_enabled=True,
+ ),
+ "ibkr": BrokerInfo(
+ id="ibkr",
+ name="ibkr",
+ display_name="Interactive Brokers",
+ broker_type=BrokerType.STOCKS,
+ region=BrokerRegion.GLOBAL,
+ supports_margin=True,
+ supports_futures=True,
+ supports_options=True,
+ max_leverage=4.0,
+ default_symbols=["AAPL", "MSFT", "GOOGL", "AMZN"],
+ maker_fee=0.0,
+ taker_fee=0.0005,
+ websocket_enabled=True,
+ ),
+ "tradier": BrokerInfo(
+ id="tradier",
+ name="tradier",
+ display_name="Tradier",
+ broker_type=BrokerType.STOCKS,
+ region=BrokerRegion.US,
+ supports_margin=True,
+ supports_options=True,
+ max_leverage=2.0,
+ default_symbols=["AAPL", "MSFT", "GOOGL", "AMZN"],
+ maker_fee=0.0,
+ taker_fee=0.0,
+ websocket_enabled=True,
+ ),
+}
+
+
+# =============================================================================
+# MULTI-EXCHANGE MARKET DATA
+# =============================================================================
+
+class MultiExchangeDataProvider:
+ """
+ Market data provider supporting multiple exchanges.
+
+ Extends Alpha Arena's market data capabilities.
+ """
+
+ def __init__(self, default_exchange: str = "kraken"):
+ self.default_exchange = default_exchange
+ self._client: Optional[Any] = None
+ self._cache: Dict[str, MarketData] = {}
+ self._cache_ttl = 5
+ self._initialized = False
+
+ async def initialize(self):
+ """Initialize HTTP client."""
+ if HTTPX_AVAILABLE:
+ self._client = httpx.AsyncClient(timeout=10.0)
+ self._initialized = True
+ logger.info(f"Multi-exchange provider initialized (default: {self.default_exchange})")
+
+ async def close(self):
+ """Close HTTP client."""
+ if self._client:
+ await self._client.aclose()
+ self._client = None
+
+ async def get_ticker(
+ self,
+ symbol: str,
+ exchange: Optional[str] = None,
+ ) -> MarketData:
+ """
+ Get ticker data from specified exchange.
+
+ Args:
+ symbol: Trading pair
+ exchange: Exchange ID (defaults to self.default_exchange)
+
+ Returns:
+ MarketData
+ """
+ exchange = exchange or self.default_exchange
+ cache_key = f"{exchange}:{symbol}"
+
+ # Check cache
+ if cache_key in self._cache:
+ cached = self._cache[cache_key]
+ age = (datetime.now() - cached.timestamp).total_seconds()
+ if age < self._cache_ttl:
+ return cached
+
+ # Fetch based on exchange
+ try:
+ if exchange == "kraken":
+ data = await self._fetch_kraken(symbol)
+ elif exchange == "binance":
+ data = await self._fetch_binance(symbol)
+ elif exchange == "okx":
+ data = await self._fetch_okx(symbol)
+ elif exchange == "coinbase":
+ data = await self._fetch_coinbase(symbol)
+ elif exchange == "bybit":
+ data = await self._fetch_bybit(symbol)
+ elif exchange == "kucoin":
+ data = await self._fetch_kucoin(symbol)
+ elif exchange == "gateio":
+ data = await self._fetch_gateio(symbol)
+ elif exchange == "hyperliquid":
+ data = await self._fetch_hyperliquid(symbol)
+ else:
+ # For stock brokers, use mock data (live would require Rust bridge)
+ logger.info(f"Using mock data for {exchange}:{symbol} (stock broker or unsupported)")
+ data = self._mock_data(symbol)
+
+ self._cache[cache_key] = data
+ return data
+
+ except Exception as e:
+ logger.error(f"Error fetching {symbol} from {exchange}: {e}")
+ return self._mock_data(symbol)
+
+ async def _fetch_kraken(self, symbol: str) -> MarketData:
+ """Fetch from Kraken API."""
+ pair = symbol.replace("/", "")
+ if pair.endswith("USD"):
+ pair = pair.replace("USD", "ZUSD")
+ if pair.startswith("BTC"):
+ pair = pair.replace("BTC", "XBT")
+
+ url = f"https://api.kraken.com/0/public/Ticker?pair={pair}"
+
+ if not self._client:
+ return self._mock_data(symbol)
+
+ response = await self._client.get(url)
+ data = response.json()
+
+ if data.get("error"):
+ return self._mock_data(symbol)
+
+ result = list(data.get("result", {}).values())[0]
+
+ return MarketData(
+ symbol=symbol,
+ price=float(result["c"][0]),
+ bid=float(result["b"][0]),
+ ask=float(result["a"][0]),
+ high_24h=float(result["h"][1]),
+ low_24h=float(result["l"][1]),
+ volume_24h=float(result["v"][1]),
+ timestamp=datetime.now(),
+ )
+
+ async def _fetch_binance(self, symbol: str) -> MarketData:
+ """Fetch from Binance API."""
+ pair = symbol.replace("/", "")
+ url = f"https://api.binance.com/api/v3/ticker/24hr?symbol={pair}"
+
+ if not self._client:
+ return self._mock_data(symbol)
+
+ response = await self._client.get(url)
+ data = response.json()
+
+ return MarketData(
+ symbol=symbol,
+ price=float(data["lastPrice"]),
+ bid=float(data["bidPrice"]),
+ ask=float(data["askPrice"]),
+ high_24h=float(data["highPrice"]),
+ low_24h=float(data["lowPrice"]),
+ volume_24h=float(data["volume"]),
+ timestamp=datetime.now(),
+ )
+
+ async def _fetch_okx(self, symbol: str) -> MarketData:
+ """Fetch from OKX API."""
+ pair = symbol.replace("/", "-")
+ url = f"https://www.okx.com/api/v5/market/ticker?instId={pair}"
+
+ if not self._client:
+ return self._mock_data(symbol)
+
+ response = await self._client.get(url)
+ data = response.json()
+
+ if data.get("code") != "0" or not data.get("data"):
+ return self._mock_data(symbol)
+
+ ticker = data["data"][0]
+
+ return MarketData(
+ symbol=symbol,
+ price=float(ticker["last"]),
+ bid=float(ticker["bidPx"]),
+ ask=float(ticker["askPx"]),
+ high_24h=float(ticker["high24h"]),
+ low_24h=float(ticker["low24h"]),
+ volume_24h=float(ticker["vol24h"]),
+ timestamp=datetime.now(),
+ )
+
+ async def _fetch_coinbase(self, symbol: str) -> MarketData:
+ """Fetch from Coinbase API."""
+ pair = symbol.replace("/", "-")
+ url = f"https://api.exchange.coinbase.com/products/{pair}/ticker"
+
+ if not self._client:
+ return self._mock_data(symbol)
+
+ response = await self._client.get(url)
+ data = response.json()
+
+ return MarketData(
+ symbol=symbol,
+ price=float(data.get("price", 0)),
+ bid=float(data.get("bid", 0)),
+ ask=float(data.get("ask", 0)),
+ high_24h=float(data.get("price", 0)) * 1.02,
+ low_24h=float(data.get("price", 0)) * 0.98,
+ volume_24h=float(data.get("volume", 0)),
+ timestamp=datetime.now(),
+ )
+
+ async def _fetch_bybit(self, symbol: str) -> MarketData:
+ """Fetch from Bybit API."""
+ pair = symbol.replace("/", "")
+ url = f"https://api.bybit.com/v5/market/tickers?category=spot&symbol={pair}"
+
+ if not self._client:
+ return self._mock_data(symbol)
+
+ response = await self._client.get(url)
+ data = response.json()
+
+ if data.get("retCode") != 0 or not data.get("result", {}).get("list"):
+ return self._mock_data(symbol)
+
+ ticker = data["result"]["list"][0]
+
+ return MarketData(
+ symbol=symbol,
+ price=float(ticker["lastPrice"]),
+ bid=float(ticker["bid1Price"]),
+ ask=float(ticker["ask1Price"]),
+ high_24h=float(ticker["highPrice24h"]),
+ low_24h=float(ticker["lowPrice24h"]),
+ volume_24h=float(ticker["volume24h"]),
+ timestamp=datetime.now(),
+ )
+
+ async def _fetch_kucoin(self, symbol: str) -> MarketData:
+ """Fetch from KuCoin API."""
+ pair = symbol.replace("/", "-")
+ url = f"https://api.kucoin.com/api/v1/market/stats?symbol={pair}"
+
+ if not self._client:
+ return self._mock_data(symbol)
+
+ response = await self._client.get(url)
+ data = response.json()
+
+ if data.get("code") != "200000" or not data.get("data"):
+ return self._mock_data(symbol)
+
+ ticker = data["data"]
+
+ return MarketData(
+ symbol=symbol,
+ price=float(ticker.get("last", 0)),
+ bid=float(ticker.get("buy", 0)),
+ ask=float(ticker.get("sell", 0)),
+ high_24h=float(ticker.get("high", 0)),
+ low_24h=float(ticker.get("low", 0)),
+ volume_24h=float(ticker.get("vol", 0)),
+ timestamp=datetime.now(),
+ )
+
+ async def _fetch_gateio(self, symbol: str) -> MarketData:
+ """Fetch from Gate.io API."""
+ pair = symbol.replace("/", "_")
+ url = f"https://api.gateio.ws/api/v4/spot/tickers?currency_pair={pair}"
+
+ if not self._client:
+ return self._mock_data(symbol)
+
+ try:
+ response = await self._client.get(url)
+ data = response.json()
+
+ if not data or len(data) == 0:
+ return self._mock_data(symbol)
+
+ ticker = data[0]
+
+ return MarketData(
+ symbol=symbol,
+ price=float(ticker.get("last", 0)),
+ bid=float(ticker.get("highest_bid", 0)),
+ ask=float(ticker.get("lowest_ask", 0)),
+ high_24h=float(ticker.get("high_24h", 0)),
+ low_24h=float(ticker.get("low_24h", 0)),
+ volume_24h=float(ticker.get("base_volume", 0)),
+ timestamp=datetime.now(),
+ )
+ except Exception as e:
+ logger.error(f"Gate.io fetch error: {e}")
+ return self._mock_data(symbol)
+
+ async def _fetch_hyperliquid(self, symbol: str) -> MarketData:
+ """Fetch from HyperLiquid API."""
+ # HyperLiquid uses a different symbol format (e.g., BTC for BTC/USD)
+ base_symbol = symbol.split("/")[0]
+ url = "https://api.hyperliquid.xyz/info"
+
+ if not self._client:
+ return self._mock_data(symbol)
+
+ try:
+ # HyperLiquid requires POST request with JSON body
+ payload = {
+ "type": "allMids"
+ }
+ response = await self._client.post(url, json=payload)
+ data = response.json()
+
+ if base_symbol not in data:
+ return self._mock_data(symbol)
+
+ mid_price = float(data[base_symbol])
+ spread = mid_price * 0.0001 # 0.01% spread estimate
+
+ return MarketData(
+ symbol=symbol,
+ price=mid_price,
+ bid=mid_price - spread,
+ ask=mid_price + spread,
+ high_24h=mid_price * 1.02,
+ low_24h=mid_price * 0.98,
+ volume_24h=0, # HyperLiquid doesn't provide volume in allMids
+ timestamp=datetime.now(),
+ )
+ except Exception as e:
+ logger.error(f"HyperLiquid fetch error: {e}")
+ return self._mock_data(symbol)
+
+ def _mock_data(self, symbol: str) -> MarketData:
+ """Generate mock data."""
+ import random
+
+ base_prices = {
+ "BTC/USD": 95000.0, "BTC/USDT": 95000.0,
+ "ETH/USD": 3500.0, "ETH/USDT": 3500.0,
+ "SOL/USD": 180.0, "SOL/USDT": 180.0,
+ "XRP/USD": 2.5, "XRP/USDT": 2.5,
+ }
+
+ base_price = base_prices.get(symbol, 100.0)
+ variation = base_price * 0.001
+ price = base_price + random.uniform(-variation, variation)
+ spread = price * 0.0005
+
+ return MarketData(
+ symbol=symbol,
+ price=price,
+ bid=price - spread,
+ ask=price + spread,
+ high_24h=price * 1.02,
+ low_24h=price * 0.98,
+ volume_24h=random.uniform(1000, 10000),
+ timestamp=datetime.now(),
+ )
+
+
+# =============================================================================
+# BROKER ADAPTER INTERFACE
+# =============================================================================
+
+class BrokerAdapter:
+ """
+ Base broker adapter for Alpha Arena.
+
+ Provides unified interface for live trading when enabled.
+ Paper trading uses simulated execution.
+ """
+
+ def __init__(
+ self,
+ broker_id: str,
+ api_key: Optional[str] = None,
+ api_secret: Optional[str] = None,
+ is_paper: bool = True,
+ ):
+ if broker_id not in SUPPORTED_BROKERS:
+ raise ValueError(f"Unsupported broker: {broker_id}")
+
+ self.broker_id = broker_id
+ self.info = SUPPORTED_BROKERS[broker_id]
+ self.api_key = api_key
+ self.api_secret = api_secret
+ self.is_paper = is_paper
+ self._data_provider: Optional[MultiExchangeDataProvider] = None
+ self._initialized = False
+
+ async def initialize(self) -> bool:
+ """Initialize the broker adapter."""
+ self._data_provider = MultiExchangeDataProvider(self.broker_id)
+ await self._data_provider.initialize()
+ self._initialized = True
+ logger.info(f"Broker adapter initialized: {self.broker_id} (paper={self.is_paper})")
+ return True
+
+ async def close(self):
+ """Close the broker adapter."""
+ if self._data_provider:
+ await self._data_provider.close()
+
+ async def get_ticker(self, symbol: str) -> MarketData:
+ """Get current market data."""
+ if not self._data_provider:
+ raise RuntimeError("Adapter not initialized")
+ return await self._data_provider.get_ticker(symbol, self.broker_id)
+
+ async def place_order(self, order: OrderRequest) -> OrderResult:
+ """
+ Place an order.
+
+ In paper mode, simulates execution.
+ In live mode, routes to actual exchange API.
+ """
+ if self.is_paper:
+ return await self._paper_execute(order)
+ else:
+ return await self._live_execute(order)
+
+ async def _paper_execute(self, order: OrderRequest) -> OrderResult:
+ """Simulate order execution for paper trading."""
+ # Get current market data
+ market = await self.get_ticker(order.symbol)
+
+ # Simulate execution
+ if order.order_type == "market":
+ fill_price = market.ask if order.side == TradeAction.BUY else market.bid
+ elif order.order_type == "limit" and order.price:
+ # Check if limit would fill
+ if order.side == TradeAction.BUY:
+ if order.price >= market.ask:
+ fill_price = market.ask
+ else:
+ return OrderResult(
+ success=True,
+ status="open",
+ error="Limit order placed (not filled)",
+ )
+ else:
+ if order.price <= market.bid:
+ fill_price = market.bid
+ else:
+ return OrderResult(
+ success=True,
+ status="open",
+ error="Limit order placed (not filled)",
+ )
+ else:
+ fill_price = market.price
+
+ # Calculate fee
+ fee = order.quantity * fill_price * self.info.taker_fee
+
+ return OrderResult(
+ success=True,
+ order_id=f"paper_{datetime.now().timestamp()}",
+ status="filled",
+ filled_quantity=order.quantity,
+ filled_price=fill_price,
+ fee=fee,
+ )
+
+ async def _live_execute(self, order: OrderRequest) -> OrderResult:
+ """
+ Execute order on live exchange.
+
+ NOTE: Live trading requires proper API integration.
+ This method would typically call Tauri commands that
+ route to the TypeScript broker adapters.
+ """
+ logger.warning(f"Live execution not implemented for {self.broker_id}")
+ return OrderResult(
+ success=False,
+ error="Live trading not yet implemented - use paper trading mode",
+ )
+
+
+# =============================================================================
+# FACTORY FUNCTIONS
+# =============================================================================
+
+def get_supported_brokers() -> List[BrokerInfo]:
+ """Get all supported brokers."""
+ return list(SUPPORTED_BROKERS.values())
+
+
+def get_broker_info(broker_id: str) -> Optional[BrokerInfo]:
+ """Get broker info by ID."""
+ return SUPPORTED_BROKERS.get(broker_id)
+
+
+def get_brokers_by_type(broker_type: BrokerType) -> List[BrokerInfo]:
+ """Get brokers by type."""
+ return [b for b in SUPPORTED_BROKERS.values() if b.broker_type == broker_type]
+
+
+def get_brokers_by_region(region: BrokerRegion) -> List[BrokerInfo]:
+ """Get brokers by region."""
+ return [b for b in SUPPORTED_BROKERS.values() if b.region == region]
+
+
+async def create_broker_adapter(
+ broker_id: str,
+ api_key: Optional[str] = None,
+ api_secret: Optional[str] = None,
+ is_paper: bool = True,
+) -> BrokerAdapter:
+ """Create and initialize a broker adapter."""
+ adapter = BrokerAdapter(broker_id, api_key, api_secret, is_paper)
+ await adapter.initialize()
+ return adapter
+
+
+# Singleton provider
+_multi_provider: Optional[MultiExchangeDataProvider] = None
+
+
+async def get_multi_exchange_provider(default_exchange: str = "kraken") -> MultiExchangeDataProvider:
+ """Get or create the multi-exchange data provider."""
+ global _multi_provider
+
+ if _multi_provider is None or _multi_provider.default_exchange != default_exchange:
+ if _multi_provider is not None:
+ try:
+ await _multi_provider.close()
+ except Exception as e:
+ logger.warning(f"Error closing previous multi-exchange provider: {e}")
+ _multi_provider = MultiExchangeDataProvider(default_exchange)
+ await _multi_provider.initialize()
+
+ return _multi_provider
+
+
+async def reset_multi_exchange_provider():
+ """Reset the multi-exchange provider singleton."""
+ global _multi_provider
+ if _multi_provider is not None:
+ try:
+ await _multi_provider.close()
+ except Exception as e:
+ logger.warning(f"Error closing multi-exchange provider: {e}")
+ _multi_provider = None
+ logger.info("Multi-exchange provider reset")
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/competition.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/competition.py
index 6944f7028..b9167d938 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/competition.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/competition.py
@@ -27,6 +27,7 @@ from alpha_arena.types.responses import (
decision_started,
decision_completed,
trade_executed,
+ portfolio_update,
reasoning,
market_data as market_data_response,
leaderboard_update,
@@ -36,7 +37,7 @@ from alpha_arena.types.responses import (
SystemResponseEvent,
)
from alpha_arena.core.base_agent import BaseTradingAgent, LLMTradingAgent
-from alpha_arena.core.paper_trading import PaperTradingEngine
+from alpha_arena.core.paper_trading_bridge import PaperTradingBridge, create_paper_trading_bridge
from alpha_arena.core.market_data import MarketDataProvider, get_market_data_provider
from alpha_arena.core.agent_manager import AgentManager, get_agent_manager
from alpha_arena.config.agent_cards import get_agent_card
@@ -66,9 +67,9 @@ class AlphaArenaCompetition:
self.start_time: Optional[datetime] = None
self.end_time: Optional[datetime] = None
- # Agents and trading engines
+ # Agents and trading engines (now using database-backed bridge)
self._agents: Dict[str, BaseTradingAgent] = {}
- self._engines: Dict[str, PaperTradingEngine] = {}
+ self._engines: Dict[str, PaperTradingBridge] = {}
self._market_provider: Optional[MarketDataProvider] = None
# Tracking
@@ -88,6 +89,11 @@ class AlphaArenaCompetition:
Returns:
True if initialization successful
"""
+ # Check if already initialized
+ if self._agents and self._engines:
+ logger.info(f"Competition {self.competition_id} already initialized with {len(self._agents)} agents")
+ return True
+
try:
logger.info(f"Initializing competition {self.competition_id}")
logger.info(f"API keys available for providers: {list(api_keys.keys())}")
@@ -125,7 +131,14 @@ class AlphaArenaCompetition:
if not api_key:
logger.warning(f"No API key found for provider '{provider}' - agent will use mock mode")
- # Create agent
+ # Get trading style if specified in model config
+ trading_style = None
+ if hasattr(model, 'trading_style'):
+ trading_style = model.trading_style
+ elif hasattr(model, 'metadata') and model.metadata:
+ trading_style = model.metadata.get('trading_style')
+
+ # Create agent with optional trading style
agent = LLMTradingAgent(
name=model.name,
provider=provider,
@@ -133,6 +146,7 @@ class AlphaArenaCompetition:
api_key=api_key,
temperature=0.7,
mode=self.config.mode.value if hasattr(self.config.mode, 'value') else self.config.mode,
+ trading_style=trading_style,
)
# Initialize with timeout
@@ -150,13 +164,15 @@ class AlphaArenaCompetition:
self._agents[model.name] = agent
- # Create trading engine
- engine = PaperTradingEngine(
+ # Create trading engine (database-backed bridge to main paper trading)
+ engine = create_paper_trading_bridge(
+ competition_id=self.competition_id,
model_name=model.name,
initial_capital=model.initial_capital or self.config.initial_capital,
+ fee_rate=0.001,
)
self._engines[model.name] = engine
- logger.info(f"Trading engine created for {model.name} with capital ${model.initial_capital or self.config.initial_capital}")
+ logger.info(f"Trading engine (DB-backed) created for {model.name} with capital ${model.initial_capital or self.config.initial_capital}")
self.status = CompetitionStatus.CREATED
logger.info(f"Competition {self.competition_id} initialized with {len(self._agents)} agents")
@@ -181,6 +197,14 @@ class AlphaArenaCompetition:
yield error("Competition is in failed state")
return
+ # Auto-transition to RUNNING if not already
+ if self.status in [CompetitionStatus.CREATED, CompetitionStatus.PAUSED]:
+ self.status = CompetitionStatus.RUNNING
+ self._is_running = True
+ if self.start_time is None:
+ self.start_time = datetime.now()
+ logger.info(f"Competition {self.competition_id} auto-transitioned to RUNNING state")
+
self.cycle_count += 1
cycle_number = self.cycle_count
cycle_start = time.time()
@@ -197,6 +221,12 @@ class AlphaArenaCompetition:
try:
# Fetch market data
symbol = self.config.symbols[0] if self.config.symbols else "BTC/USD"
+
+ # Ensure market provider is initialized
+ if self._market_provider is None:
+ logger.warning("Market provider not initialized, initializing now...")
+ self._market_provider = await get_market_data_provider(self.config.exchange_id)
+
market = await self._market_provider.get_ticker(symbol)
yield market_data_response(
@@ -263,6 +293,27 @@ class AlphaArenaCompetition:
pnl=trade_result.pnl,
)
+ # Emit real-time portfolio update after trade
+ yield portfolio_update(
+ model_name=model_name,
+ portfolio_value=new_portfolio.portfolio_value,
+ cash=new_portfolio.cash,
+ total_pnl=new_portfolio.total_pnl,
+ positions=[
+ {
+ "symbol": p.get("symbol", ""),
+ "side": p.get("side", ""),
+ "quantity": p.get("quantity", 0),
+ "entry_price": p.get("entry_price", 0),
+ "current_price": p.get("current_price", 0),
+ "unrealized_pnl": p.get("unrealized_pnl", 0),
+ }
+ for p in new_portfolio.positions
+ ] if isinstance(new_portfolio.positions, list) else [],
+ trades_count=new_portfolio.trades_count,
+ cycle_number=cycle_number,
+ )
+
except Exception as e:
error_msg = f"Error processing {model_name}: {str(e)}"
logger.exception(error_msg)
@@ -349,7 +400,8 @@ class AlphaArenaCompetition:
async def start(self, api_keys: Dict[str, str]) -> bool:
"""Start the competition."""
- if self.status not in [CompetitionStatus.CREATED, CompetitionStatus.PAUSED]:
+ # Allow restarting from RUNNING state (e.g., after browser refresh)
+ if self.status not in [CompetitionStatus.CREATED, CompetitionStatus.PAUSED, CompetitionStatus.RUNNING]:
logger.warning(f"Cannot start competition in state: {self.status}")
return False
@@ -357,11 +409,12 @@ class AlphaArenaCompetition:
return False
self.status = CompetitionStatus.RUNNING
- self.start_time = datetime.now()
+ if self.start_time is None:
+ self.start_time = datetime.now()
self._is_running = True
self._stop_requested = False
- logger.info(f"Competition {self.competition_id} started")
+ logger.info(f"Competition {self.competition_id} started (status: {self.status})")
return True
async def stop(self):
@@ -387,6 +440,10 @@ class AlphaArenaCompetition:
if self._cycle_results:
last_cycle = self._cycle_results[-1]
prices = {symbol: last_cycle.market_data.price}
+ else:
+ # No cycles run yet - use initial capital as portfolio value
+ # This allows showing a leaderboard even before the first cycle
+ prices = {symbol: 0.0} # Price doesn't matter for initial state
return self._calculate_leaderboard(prices)
def get_decisions(self, model_name: Optional[str] = None, limit: int = 50) -> List[ModelDecision]:
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/database.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/database.py
index 9ebb6ed8d..e6161afeb 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/database.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/database.py
@@ -6,6 +6,7 @@ SQLite-based persistence for competition state.
import json
import sqlite3
+import os
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Any
@@ -24,6 +25,24 @@ from alpha_arena.utils.logging import get_logger
logger = get_logger("database")
+def get_main_db_path() -> Optional[Path]:
+ """Get the path to the main Fincept Terminal database for paper trading integration."""
+ possible_paths = [
+ # Windows AppData
+ Path(os.environ.get("APPDATA", "")) / "fincept-terminal" / "fincept_terminal.db",
+ Path(os.environ.get("LOCALAPPDATA", "")) / "fincept-terminal" / "fincept_terminal.db",
+ # Linux/Mac
+ Path.home() / ".config" / "fincept-terminal" / "fincept_terminal.db",
+ Path.home() / ".local" / "share" / "fincept-terminal" / "fincept_terminal.db",
+ ]
+
+ for path in possible_paths:
+ if path.exists():
+ return path
+
+ return None
+
+
class AlphaArenaDatabase:
"""
SQLite database for Alpha Arena persistence.
@@ -260,7 +279,7 @@ class AlphaArenaDatabase:
# ==================== Decision Methods ====================
def save_decision(self, decision: ModelDecision) -> int:
- """Save a trading decision."""
+ """Save a trading decision to both local and main database."""
with self._get_connection() as conn:
cursor = conn.cursor()
@@ -290,7 +309,60 @@ class AlphaArenaDatabase:
decision.timestamp.isoformat(),
))
- return cursor.lastrowid
+ local_id = cursor.lastrowid
+
+ # Also save to main Fincept database for UI integration
+ self._save_decision_to_main_db(decision, trade_status, trade_pnl)
+
+ return local_id
+
+ def _save_decision_to_main_db(self, decision: ModelDecision, trade_status: Optional[str], trade_pnl: Optional[float]):
+ """Save decision to main Fincept Terminal database."""
+ main_db_path = get_main_db_path()
+ if not main_db_path:
+ logger.warning("Main database not found, skipping decision sync")
+ return
+
+ conn = None
+ try:
+ import uuid
+ conn = sqlite3.connect(str(main_db_path), timeout=10.0)
+ cursor = conn.cursor()
+
+ decision_id = str(uuid.uuid4())
+ action_value = decision.action.value if hasattr(decision.action, 'value') else str(decision.action)
+
+ cursor.execute("""
+ INSERT INTO alpha_arena_decisions
+ (id, competition_id, model_name, cycle_number, symbol, action, quantity,
+ confidence, reasoning, trade_executed, price_at_decision,
+ portfolio_value_before, portfolio_value_after, pnl, timestamp)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """, (
+ decision_id,
+ decision.competition_id,
+ decision.model_name,
+ decision.cycle_number,
+ decision.symbol,
+ action_value,
+ decision.quantity,
+ decision.confidence,
+ decision.reasoning,
+ 1 if trade_status == "executed" else 0,
+ decision.price_at_decision,
+ decision.portfolio_value_before,
+ decision.portfolio_value_after,
+ trade_pnl or 0,
+ decision.timestamp.isoformat(),
+ ))
+
+ conn.commit()
+ logger.debug(f"Decision synced to main database: {decision_id}")
+ except Exception as e:
+ logger.warning(f"Failed to sync decision to main database: {e}")
+ finally:
+ if conn:
+ conn.close()
def get_decisions(
self,
@@ -322,7 +394,7 @@ class AlphaArenaDatabase:
# ==================== Snapshot Methods ====================
def save_snapshot(self, snapshot: PerformanceSnapshot) -> bool:
- """Save a performance snapshot."""
+ """Save a performance snapshot to both local and main database."""
with self._get_connection() as conn:
cursor = conn.cursor()
@@ -345,8 +417,48 @@ class AlphaArenaDatabase:
snapshot.timestamp.isoformat(),
))
+ # Also save to main database
+ self._save_snapshot_to_main_db(snapshot)
+
return True
+ def _save_snapshot_to_main_db(self, snapshot: PerformanceSnapshot):
+ """Save snapshot to main Fincept Terminal database."""
+ main_db_path = get_main_db_path()
+ if not main_db_path:
+ return
+
+ conn = None
+ try:
+ conn = sqlite3.connect(str(main_db_path), timeout=10.0)
+ cursor = conn.cursor()
+
+ cursor.execute("""
+ INSERT OR REPLACE INTO alpha_arena_snapshots
+ (id, competition_id, model_name, cycle_number, portfolio_value,
+ cash, pnl, return_pct, positions_count, trades_count, timestamp)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """, (
+ snapshot.id,
+ snapshot.competition_id,
+ snapshot.model_name,
+ snapshot.cycle_number,
+ snapshot.portfolio_value,
+ snapshot.cash,
+ snapshot.pnl,
+ snapshot.return_pct,
+ snapshot.positions_count,
+ snapshot.trades_count,
+ snapshot.timestamp.isoformat(),
+ ))
+
+ conn.commit()
+ except Exception as e:
+ logger.warning(f"Failed to sync snapshot to main database: {e}")
+ finally:
+ if conn:
+ conn.close()
+
def get_snapshots(
self,
competition_id: str,
@@ -379,7 +491,11 @@ class AlphaArenaDatabase:
cycle_number: int,
leaderboard: List[LeaderboardEntry],
) -> bool:
- """Save leaderboard snapshot."""
+ """Save leaderboard snapshot to both local and main database."""
+ import uuid
+ leaderboard_json = json.dumps([e.model_dump() for e in leaderboard])
+ now = datetime.now().isoformat()
+
with self._get_connection() as conn:
cursor = conn.cursor()
@@ -390,12 +506,47 @@ class AlphaArenaDatabase:
""", (
competition_id,
cycle_number,
- json.dumps([e.model_dump() for e in leaderboard]),
- datetime.now().isoformat(),
+ leaderboard_json,
+ now,
))
+ # Also save to main database
+ self._save_leaderboard_to_main_db(competition_id, cycle_number, leaderboard_json, now)
+
return True
+ def _save_leaderboard_to_main_db(self, competition_id: str, cycle_number: int, leaderboard_json: str, timestamp: str):
+ """Save leaderboard to main Fincept Terminal database."""
+ main_db_path = get_main_db_path()
+ if not main_db_path:
+ return
+
+ conn = None
+ try:
+ import uuid
+ conn = sqlite3.connect(str(main_db_path), timeout=10.0)
+ cursor = conn.cursor()
+
+ leaderboard_id = str(uuid.uuid4())
+ cursor.execute("""
+ INSERT INTO alpha_arena_leaderboard
+ (id, competition_id, cycle_number, leaderboard_json, timestamp)
+ VALUES (?, ?, ?, ?, ?)
+ """, (
+ leaderboard_id,
+ competition_id,
+ cycle_number,
+ leaderboard_json,
+ timestamp,
+ ))
+
+ conn.commit()
+ except Exception as e:
+ logger.warning(f"Failed to sync leaderboard to main database: {e}")
+ finally:
+ if conn:
+ conn.close()
+
def get_latest_leaderboard(self, competition_id: str) -> Optional[List[Dict]]:
"""Get the latest leaderboard for a competition."""
with self._get_connection() as conn:
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/evaluation.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/evaluation.py
index 25e0fb6aa..5b878e126 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/evaluation.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/evaluation.py
@@ -139,9 +139,12 @@ class EvaluationModule:
continue
pred.price_after = current_price
- price_change = (current_price - pred.price_at_decision) / pred.price_at_decision
+ if pred.price_at_decision == 0:
+ price_change = 0.0
+ else:
+ price_change = (current_price - pred.price_at_decision) / pred.price_at_decision
- pred.actual_return = price_change
+ pred.actual_return = price_change if pred.price_at_decision != 0 else 0
# Determine if prediction was correct
if pred.action == "hold":
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/features_pipeline.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/features_pipeline.py
new file mode 100644
index 000000000..dff97181d
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/features_pipeline.py
@@ -0,0 +1,488 @@
+"""
+Features Pipeline for Alpha Arena
+
+Provides market features (technical indicators, sentiment, etc.) to trading agents.
+Integrates with existing technical indicators from agno_trading/tools.
+"""
+
+import sys
+from pathlib import Path
+from typing import Dict, List, Optional, Any
+from dataclasses import dataclass, field
+from datetime import datetime
+from abc import ABC, abstractmethod
+
+# Add parent paths for imports
+scripts_dir = Path(__file__).parent.parent.parent
+if str(scripts_dir) not in sys.path:
+ sys.path.insert(0, str(scripts_dir))
+
+from alpha_arena.types.models import MarketData
+from alpha_arena.utils.logging import get_logger
+
+logger = get_logger("features_pipeline")
+
+
+@dataclass
+class TechnicalFeatures:
+ """Technical analysis features"""
+ sma_20: Optional[float] = None
+ sma_50: Optional[float] = None
+ ema_12: Optional[float] = None
+ ema_26: Optional[float] = None
+ rsi_14: Optional[float] = None
+ rsi_interpretation: str = "neutral"
+ macd: Optional[float] = None
+ macd_signal: Optional[float] = None
+ macd_histogram: Optional[float] = None
+ macd_interpretation: str = "neutral"
+ bollinger_upper: Optional[float] = None
+ bollinger_middle: Optional[float] = None
+ bollinger_lower: Optional[float] = None
+ bollinger_interpretation: str = "neutral"
+ support_level: Optional[float] = None
+ resistance_level: Optional[float] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "sma_20": self.sma_20,
+ "sma_50": self.sma_50,
+ "ema_12": self.ema_12,
+ "ema_26": self.ema_26,
+ "rsi_14": self.rsi_14,
+ "rsi_interpretation": self.rsi_interpretation,
+ "macd": self.macd,
+ "macd_signal": self.macd_signal,
+ "macd_histogram": self.macd_histogram,
+ "macd_interpretation": self.macd_interpretation,
+ "bollinger_upper": self.bollinger_upper,
+ "bollinger_middle": self.bollinger_middle,
+ "bollinger_lower": self.bollinger_lower,
+ "bollinger_interpretation": self.bollinger_interpretation,
+ "support_level": self.support_level,
+ "resistance_level": self.resistance_level,
+ }
+
+ def to_prompt_context(self) -> str:
+ """Convert to text for LLM prompt"""
+ lines = ["TECHNICAL INDICATORS:"]
+
+ if self.sma_20:
+ lines.append(f" SMA(20): ${self.sma_20:,.2f}")
+ if self.sma_50:
+ lines.append(f" SMA(50): ${self.sma_50:,.2f}")
+ if self.ema_12:
+ lines.append(f" EMA(12): ${self.ema_12:,.2f}")
+ if self.ema_26:
+ lines.append(f" EMA(26): ${self.ema_26:,.2f}")
+ if self.rsi_14:
+ lines.append(f" RSI(14): {self.rsi_14:.1f} ({self.rsi_interpretation})")
+ if self.macd:
+ lines.append(f" MACD: {self.macd:.4f}, Signal: {self.macd_signal:.4f} ({self.macd_interpretation})")
+ if self.bollinger_upper:
+ lines.append(f" Bollinger Bands: Upper ${self.bollinger_upper:,.2f}, Middle ${self.bollinger_middle:,.2f}, Lower ${self.bollinger_lower:,.2f}")
+ lines.append(f" ({self.bollinger_interpretation})")
+ if self.support_level:
+ lines.append(f" Support: ${self.support_level:,.2f}")
+ if self.resistance_level:
+ lines.append(f" Resistance: ${self.resistance_level:,.2f}")
+
+ return "\n".join(lines)
+
+
+@dataclass
+class SentimentFeatures:
+ """News and sentiment features"""
+ overall_sentiment: str = "neutral" # bullish, bearish, neutral
+ sentiment_score: float = 0.0 # -1 to 1
+ news_count: int = 0
+ recent_headlines: List[str] = field(default_factory=list)
+ social_sentiment: Optional[float] = None
+ fear_greed_index: Optional[float] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "overall_sentiment": self.overall_sentiment,
+ "sentiment_score": self.sentiment_score,
+ "news_count": self.news_count,
+ "recent_headlines": self.recent_headlines,
+ "social_sentiment": self.social_sentiment,
+ "fear_greed_index": self.fear_greed_index,
+ }
+
+ def to_prompt_context(self) -> str:
+ """Convert to text for LLM prompt"""
+ lines = ["MARKET SENTIMENT:"]
+ lines.append(f" Overall: {self.overall_sentiment.upper()} (score: {self.sentiment_score:+.2f})")
+
+ if self.fear_greed_index is not None:
+ fg_label = "Extreme Fear" if self.fear_greed_index < 25 else \
+ "Fear" if self.fear_greed_index < 45 else \
+ "Neutral" if self.fear_greed_index < 55 else \
+ "Greed" if self.fear_greed_index < 75 else "Extreme Greed"
+ lines.append(f" Fear & Greed Index: {self.fear_greed_index:.0f} ({fg_label})")
+
+ if self.recent_headlines:
+ lines.append(f" Recent Headlines ({self.news_count} articles):")
+ for headline in self.recent_headlines[:3]:
+ lines.append(f" - {headline[:100]}")
+
+ return "\n".join(lines)
+
+
+@dataclass
+class MarketFeatures:
+ """Combined market features for decision making"""
+ timestamp: datetime = field(default_factory=datetime.now)
+ symbol: str = ""
+ current_price: float = 0.0
+ price_change_24h: float = 0.0
+ price_change_pct_24h: float = 0.0
+ volume_24h: float = 0.0
+ high_24h: float = 0.0
+ low_24h: float = 0.0
+
+ # Feature components
+ technical: TechnicalFeatures = field(default_factory=TechnicalFeatures)
+ sentiment: SentimentFeatures = field(default_factory=SentimentFeatures)
+
+ # Computed signals
+ trend_direction: str = "neutral" # bullish, bearish, neutral
+ trend_strength: float = 0.0 # 0 to 1
+ volatility_level: str = "normal" # low, normal, high, extreme
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "timestamp": self.timestamp.isoformat(),
+ "symbol": self.symbol,
+ "current_price": self.current_price,
+ "price_change_24h": self.price_change_24h,
+ "price_change_pct_24h": self.price_change_pct_24h,
+ "volume_24h": self.volume_24h,
+ "high_24h": self.high_24h,
+ "low_24h": self.low_24h,
+ "technical": self.technical.to_dict(),
+ "sentiment": self.sentiment.to_dict(),
+ "trend_direction": self.trend_direction,
+ "trend_strength": self.trend_strength,
+ "volatility_level": self.volatility_level,
+ }
+
+ def to_prompt_context(self) -> str:
+ """Convert to comprehensive text for LLM prompt"""
+ lines = [
+ f"MARKET OVERVIEW ({self.symbol}):",
+ f" Current Price: ${self.current_price:,.2f}",
+ f" 24h Change: ${self.price_change_24h:+,.2f} ({self.price_change_pct_24h:+.2f}%)",
+ f" 24h Range: ${self.low_24h:,.2f} - ${self.high_24h:,.2f}",
+ f" 24h Volume: {self.volume_24h:,.2f}",
+ f" Trend: {self.trend_direction.upper()} (strength: {self.trend_strength:.2f})",
+ f" Volatility: {self.volatility_level.upper()}",
+ "",
+ self.technical.to_prompt_context(),
+ "",
+ self.sentiment.to_prompt_context(),
+ ]
+ return "\n".join(lines)
+
+
+class FeaturesPipeline(ABC):
+ """Abstract base class for feature computation pipelines"""
+
+ @abstractmethod
+ async def compute(
+ self,
+ market_data: MarketData,
+ price_history: Optional[List[float]] = None,
+ ) -> MarketFeatures:
+ """Compute features from market data"""
+ raise NotImplementedError
+
+
+class DefaultFeaturesPipeline(FeaturesPipeline):
+ """
+ Default features pipeline using existing technical indicators.
+
+ Integrates with:
+ - agno_trading/tools/technical_indicators.py
+ - agno_trading/tools/news_sentiment.py
+ """
+
+ def __init__(
+ self,
+ enable_technical: bool = True,
+ enable_sentiment: bool = True,
+ price_history_length: int = 100,
+ ):
+ self.enable_technical = enable_technical
+ self.enable_sentiment = enable_sentiment
+ self.price_history_length = price_history_length
+ self._price_history: Dict[str, List[float]] = {}
+
+ def add_price(self, symbol: str, price: float):
+ """Add a price to history for technical analysis"""
+ if symbol not in self._price_history:
+ self._price_history[symbol] = []
+
+ self._price_history[symbol].append(price)
+
+ # Keep only recent history
+ if len(self._price_history[symbol]) > self.price_history_length:
+ self._price_history[symbol] = self._price_history[symbol][-self.price_history_length:]
+
+ def get_price_history(self, symbol: str) -> List[float]:
+ """Get price history for a symbol"""
+ return self._price_history.get(symbol, [])
+
+ async def compute(
+ self,
+ market_data: MarketData,
+ price_history: Optional[List[float]] = None,
+ ) -> MarketFeatures:
+ """Compute all features from market data"""
+
+ # Add current price to history
+ self.add_price(market_data.symbol, market_data.price)
+
+ # Use provided history or internal history
+ prices = price_history or self.get_price_history(market_data.symbol)
+
+ # Compute technical features
+ technical = await self._compute_technical(prices, market_data.price)
+
+ # Compute sentiment features (placeholder for now)
+ sentiment = await self._compute_sentiment(market_data.symbol)
+
+ # Compute trend and volatility
+ trend_direction, trend_strength = self._compute_trend(technical, prices)
+ volatility_level = self._compute_volatility(market_data, prices)
+
+ # Build features
+ return MarketFeatures(
+ timestamp=datetime.now(),
+ symbol=market_data.symbol,
+ current_price=market_data.price,
+ price_change_24h=market_data.price - (prices[0] if prices else market_data.price),
+ price_change_pct_24h=((market_data.price / prices[0]) - 1) * 100 if prices and prices[0] > 0 else 0,
+ volume_24h=market_data.volume_24h,
+ high_24h=market_data.high_24h,
+ low_24h=market_data.low_24h,
+ technical=technical,
+ sentiment=sentiment,
+ trend_direction=trend_direction,
+ trend_strength=trend_strength,
+ volatility_level=volatility_level,
+ )
+
+ async def _compute_technical(
+ self,
+ prices: List[float],
+ current_price: float,
+ ) -> TechnicalFeatures:
+ """Compute technical indicators using existing tools"""
+
+ if not self.enable_technical or len(prices) < 20:
+ return TechnicalFeatures()
+
+ features = TechnicalFeatures()
+
+ try:
+ # Import existing technical indicator tools
+ from agno_trading.tools.technical_indicators import (
+ calculate_sma,
+ calculate_ema,
+ calculate_rsi,
+ calculate_macd,
+ calculate_bollinger_bands,
+ detect_support_resistance,
+ )
+
+ # SMA
+ sma_20 = calculate_sma(prices, 20)
+ if "current" in sma_20 and sma_20["current"]:
+ features.sma_20 = sma_20["current"]
+
+ if len(prices) >= 50:
+ sma_50 = calculate_sma(prices, 50)
+ if "current" in sma_50 and sma_50["current"]:
+ features.sma_50 = sma_50["current"]
+
+ # EMA
+ ema_12 = calculate_ema(prices, 12)
+ if "current" in ema_12 and ema_12["current"]:
+ features.ema_12 = ema_12["current"]
+
+ ema_26 = calculate_ema(prices, 26)
+ if "current" in ema_26 and ema_26["current"]:
+ features.ema_26 = ema_26["current"]
+
+ # RSI
+ rsi = calculate_rsi(prices, 14)
+ if "current" in rsi and rsi["current"]:
+ features.rsi_14 = rsi["current"]
+ features.rsi_interpretation = rsi.get("interpretation", "neutral")
+
+ # MACD
+ macd = calculate_macd(prices)
+ if "current_macd" in macd and macd["current_macd"]:
+ features.macd = macd["current_macd"]
+ features.macd_signal = macd.get("current_signal")
+ features.macd_histogram = macd.get("current_histogram")
+ features.macd_interpretation = macd.get("interpretation", "neutral")
+
+ # Bollinger Bands
+ bb = calculate_bollinger_bands(prices)
+ if "current_upper" in bb and bb["current_upper"]:
+ features.bollinger_upper = bb["current_upper"]
+ features.bollinger_middle = bb.get("current_middle")
+ features.bollinger_lower = bb.get("current_lower")
+ features.bollinger_interpretation = bb.get("interpretation", "neutral")
+
+ # Support/Resistance
+ sr = detect_support_resistance(prices)
+ if "nearest_support" in sr:
+ features.support_level = sr.get("nearest_support")
+ features.resistance_level = sr.get("nearest_resistance")
+
+ except ImportError as e:
+ logger.warning(f"Technical indicators not available: {e}")
+ except Exception as e:
+ logger.warning(f"Error computing technical indicators: {e}")
+
+ return features
+
+ async def _compute_sentiment(self, symbol: str) -> SentimentFeatures:
+ """Compute sentiment features using sentiment agent"""
+
+ if not self.enable_sentiment:
+ return SentimentFeatures()
+
+ features = SentimentFeatures()
+
+ try:
+ # Try the new sentiment agent first
+ from alpha_arena.core.sentiment_agent import get_sentiment_agent
+
+ agent = await get_sentiment_agent()
+ result = await agent.analyze_sentiment(symbol, use_cache=True, max_articles=10)
+
+ features.overall_sentiment = result.overall_sentiment.value
+ features.sentiment_score = result.sentiment_score
+ features.news_count = result.articles_analyzed
+ features.recent_headlines = result.key_headlines[:3]
+
+ except ImportError:
+ # Fallback to basic sentiment tools
+ try:
+ from agno_trading.tools.news_sentiment import get_market_sentiment
+
+ sentiment = get_market_sentiment(symbol)
+ features.overall_sentiment = sentiment.get("overall_sentiment", "neutral")
+ features.sentiment_score = sentiment.get("sentiment_score", 0.0)
+
+ except ImportError:
+ logger.debug("Sentiment tools not available")
+ except Exception as e:
+ logger.warning(f"Error computing sentiment: {e}")
+
+ return features
+
+ def _compute_trend(
+ self,
+ technical: TechnicalFeatures,
+ prices: List[float],
+ ) -> tuple[str, float]:
+ """Compute trend direction and strength"""
+
+ signals = []
+
+ # SMA cross
+ if technical.sma_20 and technical.sma_50:
+ if technical.sma_20 > technical.sma_50:
+ signals.append(1) # bullish
+ else:
+ signals.append(-1) # bearish
+
+ # RSI
+ if technical.rsi_14:
+ if technical.rsi_14 > 60:
+ signals.append(1)
+ elif technical.rsi_14 < 40:
+ signals.append(-1)
+ else:
+ signals.append(0)
+
+ # MACD
+ if technical.macd and technical.macd_signal:
+ if technical.macd > technical.macd_signal:
+ signals.append(1)
+ else:
+ signals.append(-1)
+
+ # Price vs Bollinger
+ if technical.bollinger_upper and technical.bollinger_lower and prices:
+ current = prices[-1]
+ if current > technical.bollinger_upper:
+ signals.append(1)
+ elif current < technical.bollinger_lower:
+ signals.append(-1)
+ else:
+ signals.append(0)
+
+ if not signals:
+ return "neutral", 0.0
+
+ avg_signal = sum(signals) / len(signals)
+
+ if avg_signal > 0.3:
+ direction = "bullish"
+ elif avg_signal < -0.3:
+ direction = "bearish"
+ else:
+ direction = "neutral"
+
+ strength = abs(avg_signal)
+
+ return direction, min(strength, 1.0)
+
+ def _compute_volatility(
+ self,
+ market_data: MarketData,
+ prices: List[float],
+ ) -> str:
+ """Compute volatility level"""
+
+ if not prices or len(prices) < 10:
+ return "normal"
+
+ # Calculate recent price changes
+ changes = []
+ for i in range(1, min(20, len(prices))):
+ pct_change = abs((prices[i] - prices[i-1]) / prices[i-1]) * 100
+ changes.append(pct_change)
+
+ if not changes:
+ return "normal"
+
+ avg_change = sum(changes) / len(changes)
+
+ if avg_change < 0.5:
+ return "low"
+ elif avg_change < 2.0:
+ return "normal"
+ elif avg_change < 5.0:
+ return "high"
+ else:
+ return "extreme"
+
+
+# Singleton instance
+_default_pipeline: Optional[DefaultFeaturesPipeline] = None
+
+
+def get_features_pipeline() -> DefaultFeaturesPipeline:
+ """Get the default features pipeline instance"""
+ global _default_pipeline
+ if _default_pipeline is None:
+ _default_pipeline = DefaultFeaturesPipeline()
+ return _default_pipeline
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/grid_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/grid_agent.py
new file mode 100644
index 000000000..8c5ba9dde
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/grid_agent.py
@@ -0,0 +1,431 @@
+"""
+Grid Strategy Agent for Alpha Arena
+
+Implements rule-based grid trading strategy that doesn't require LLM.
+Uses the same grid calculation logic as the TypeScript GridEngine.
+"""
+
+from typing import Dict, List, Optional, Any, AsyncGenerator
+from dataclasses import dataclass, field
+from datetime import datetime
+from enum import Enum
+
+from alpha_arena.core.base_agent import BaseTradingAgent
+from alpha_arena.types.models import (
+ MarketData,
+ ModelDecision,
+ PortfolioState,
+ TradeAction,
+)
+from alpha_arena.types.responses import (
+ StreamResponse,
+ decision_started,
+ decision_completed,
+ reasoning,
+ done,
+)
+from alpha_arena.utils.logging import get_logger
+
+logger = get_logger("grid_agent")
+
+
+class GridType(Enum):
+ ARITHMETIC = "arithmetic" # Equal price gaps
+ GEOMETRIC = "geometric" # Equal percentage gaps
+
+
+class GridDirection(Enum):
+ NEUTRAL = "neutral" # Buy below, sell above
+ LONG = "long" # Bias towards buying
+ SHORT = "short" # Bias towards selling
+
+
+@dataclass
+class GridConfig:
+ """Grid strategy configuration"""
+ upper_price: float
+ lower_price: float
+ grid_levels: int = 10
+ grid_type: GridType = GridType.ARITHMETIC
+ direction: GridDirection = GridDirection.NEUTRAL
+ total_investment: float = 10000.0
+ quantity_per_grid: Optional[float] = None
+ stop_loss: Optional[float] = None
+ take_profit: Optional[float] = None
+
+
+@dataclass
+class GridLevel:
+ """A single grid level"""
+ index: int
+ price: float
+ side: str # "buy" or "sell"
+ quantity: float
+ status: str = "pending" # pending, triggered, filled
+ triggered_at: Optional[datetime] = None
+
+
+@dataclass
+class GridState:
+ """Current state of the grid strategy"""
+ config: GridConfig
+ levels: List[GridLevel]
+ current_price: float
+ position: float = 0.0
+ average_entry: float = 0.0
+ realized_pnl: float = 0.0
+ grid_profit: float = 0.0
+ total_buys: int = 0
+ total_sells: int = 0
+ last_triggered_index: Optional[int] = None
+
+
+class GridStrategyAgent(BaseTradingAgent):
+ """
+ Grid Trading Strategy Agent.
+
+ A rule-based agent that:
+ 1. Creates a grid of buy/sell levels
+ 2. Triggers orders when price crosses levels
+ 3. Profits from price oscillation within the range
+
+ This agent doesn't use LLM - it's purely algorithmic.
+ """
+
+ def __init__(
+ self,
+ name: str = "GridBot",
+ config: Optional[GridConfig] = None,
+ auto_adjust: bool = False,
+ ):
+ super().__init__(name=name, provider="rule_based", model_id="grid_v1")
+ self.config = config
+ self.state: Optional[GridState] = None
+ self.auto_adjust = auto_adjust
+ self._initialized = False
+
+ async def initialize(self) -> bool:
+ """Initialize the grid agent"""
+ self._initialized = True
+ logger.info(f"Grid agent '{self.name}' initialized")
+ return True
+
+ def configure(
+ self,
+ upper_price: float,
+ lower_price: float,
+ grid_levels: int = 10,
+ grid_type: str = "arithmetic",
+ direction: str = "neutral",
+ total_investment: float = 10000.0,
+ quantity_per_grid: Optional[float] = None,
+ stop_loss: Optional[float] = None,
+ take_profit: Optional[float] = None,
+ ):
+ """Configure the grid strategy"""
+ self.config = GridConfig(
+ upper_price=upper_price,
+ lower_price=lower_price,
+ grid_levels=grid_levels,
+ grid_type=GridType(grid_type),
+ direction=GridDirection(direction),
+ total_investment=total_investment,
+ quantity_per_grid=quantity_per_grid,
+ stop_loss=stop_loss,
+ take_profit=take_profit,
+ )
+ logger.info(f"Grid configured: {lower_price} - {upper_price}, {grid_levels} levels")
+
+ def auto_configure(
+ self,
+ current_price: float,
+ price_range_pct: float = 10.0,
+ grid_levels: int = 10,
+ total_investment: float = 10000.0,
+ ):
+ """Auto-configure grid based on current price"""
+ half_range = current_price * (price_range_pct / 100) / 2
+ self.configure(
+ upper_price=current_price + half_range,
+ lower_price=current_price - half_range,
+ grid_levels=grid_levels,
+ total_investment=total_investment,
+ )
+ logger.info(f"Grid auto-configured around ${current_price:,.2f}")
+
+ def _calculate_grid_levels(self, current_price: float) -> List[GridLevel]:
+ """Calculate grid price levels"""
+ if not self.config:
+ raise ValueError("Grid not configured")
+
+ cfg = self.config
+ levels = []
+
+ # Calculate price levels
+ if cfg.grid_type == GridType.ARITHMETIC:
+ step = (cfg.upper_price - cfg.lower_price) / (cfg.grid_levels - 1)
+ prices = [cfg.lower_price + step * i for i in range(cfg.grid_levels)]
+ else: # GEOMETRIC
+ ratio = (cfg.upper_price / cfg.lower_price) ** (1 / (cfg.grid_levels - 1))
+ prices = [cfg.lower_price * (ratio ** i) for i in range(cfg.grid_levels)]
+
+ # Calculate quantity per grid
+ avg_price = (cfg.upper_price + cfg.lower_price) / 2
+ qty = cfg.quantity_per_grid or (cfg.total_investment / cfg.grid_levels / avg_price)
+
+ # Create levels with buy/sell assignments
+ for i, price in enumerate(prices):
+ if cfg.direction == GridDirection.NEUTRAL:
+ side = "buy" if price < current_price else "sell"
+ elif cfg.direction == GridDirection.LONG:
+ side = "buy" if price <= current_price else "sell"
+ else: # SHORT
+ side = "sell" if price >= current_price else "buy"
+
+ levels.append(GridLevel(
+ index=i,
+ price=round(price, 8),
+ side=side,
+ quantity=round(qty, 8),
+ status="pending",
+ ))
+
+ return levels
+
+ def _initialize_state(self, current_price: float):
+ """Initialize grid state"""
+ levels = self._calculate_grid_levels(current_price)
+ self.state = GridState(
+ config=self.config,
+ levels=levels,
+ current_price=current_price,
+ )
+
+ def _check_triggered_levels(self, new_price: float) -> List[GridLevel]:
+ """Check which levels were triggered by price movement"""
+ if not self.state:
+ return []
+
+ triggered = []
+ old_price = self.state.current_price
+
+ for level in self.state.levels:
+ if level.status != "pending":
+ continue
+
+ # Check if price crossed this level
+ crossed = False
+ if old_price <= level.price <= new_price:
+ crossed = True
+ elif old_price >= level.price >= new_price:
+ crossed = True
+
+ if crossed:
+ level.status = "triggered"
+ level.triggered_at = datetime.now()
+ triggered.append(level)
+
+ return triggered
+
+ def _process_triggered_level(self, level: GridLevel, price: float):
+ """Process a triggered grid level"""
+ if level.side == "buy":
+ # Buying
+ cost = level.quantity * price
+ old_position = self.state.position
+ self.state.position += level.quantity
+ self.state.total_buys += 1
+
+ # Update average entry
+ if self.state.position > 0:
+ if old_position > 0:
+ old_value = old_position * self.state.average_entry
+ new_value = level.quantity * price
+ self.state.average_entry = (old_value + new_value) / self.state.position
+ else:
+ self.state.average_entry = price
+ else:
+ # Selling
+ if self.state.position > 0 and self.state.average_entry > 0:
+ # Realize profit
+ pnl = (price - self.state.average_entry) * level.quantity
+ self.state.realized_pnl += pnl
+ self.state.grid_profit += pnl
+
+ self.state.position -= level.quantity
+ self.state.total_sells += 1
+
+ level.status = "filled"
+ self.state.last_triggered_index = level.index
+
+ # Flip the level for next trigger
+ level.side = "sell" if level.side == "buy" else "buy"
+ level.status = "pending"
+
+ async def make_decision(
+ self,
+ market_data: MarketData,
+ portfolio: PortfolioState,
+ cycle_number: int,
+ ) -> ModelDecision:
+ """Make trading decision based on grid logic"""
+
+ price = market_data.price
+ symbol = market_data.symbol
+
+ # Auto-configure if not set
+ if not self.config:
+ self.auto_configure(price)
+
+ # Initialize state if needed
+ if not self.state:
+ self._initialize_state(price)
+
+ # Check stop conditions
+ if self.config.stop_loss and price <= self.config.stop_loss:
+ return ModelDecision(
+ competition_id="",
+ model_name=self.name,
+ cycle_number=cycle_number,
+ action=TradeAction.SELL,
+ symbol=symbol,
+ quantity=self.state.position if self.state.position > 0 else 0,
+ confidence=1.0,
+ reasoning="Stop loss triggered - closing all positions",
+ price_at_decision=price,
+ )
+
+ if self.config.take_profit and price >= self.config.take_profit:
+ return ModelDecision(
+ competition_id="",
+ model_name=self.name,
+ cycle_number=cycle_number,
+ action=TradeAction.SELL,
+ symbol=symbol,
+ quantity=self.state.position if self.state.position > 0 else 0,
+ confidence=1.0,
+ reasoning="Take profit triggered - closing all positions",
+ price_at_decision=price,
+ )
+
+ # Check for triggered levels
+ triggered = self._check_triggered_levels(price)
+ self.state.current_price = price
+
+ if not triggered:
+ # No levels triggered - hold
+ return ModelDecision(
+ competition_id="",
+ model_name=self.name,
+ cycle_number=cycle_number,
+ action=TradeAction.HOLD,
+ symbol=symbol,
+ quantity=0,
+ confidence=0.5,
+ reasoning=f"Price ${price:,.2f} - no grid levels triggered. Position: {self.state.position:.4f}",
+ price_at_decision=price,
+ )
+
+ # Process triggered levels
+ for level in triggered:
+ self._process_triggered_level(level, price)
+
+ # Determine aggregate action
+ net_buys = sum(1 for l in triggered if l.side == "sell") # Flipped, so original was buy
+ net_sells = sum(1 for l in triggered if l.side == "buy") # Flipped, so original was sell
+ total_qty = sum(l.quantity for l in triggered)
+
+ if net_buys > net_sells:
+ action = TradeAction.BUY
+ reasoning = f"Grid BUY: {net_buys} buy level(s) triggered at ${price:,.2f}"
+ elif net_sells > net_buys:
+ action = TradeAction.SELL
+ reasoning = f"Grid SELL: {net_sells} sell level(s) triggered at ${price:,.2f}"
+ else:
+ action = TradeAction.HOLD
+ reasoning = f"Grid: Equal buy/sell levels triggered at ${price:,.2f}"
+
+ reasoning += f" | Grid P&L: ${self.state.grid_profit:+,.2f} | Position: {self.state.position:.4f}"
+
+ return ModelDecision(
+ competition_id="",
+ model_name=self.name,
+ cycle_number=cycle_number,
+ action=action,
+ symbol=symbol,
+ quantity=total_qty,
+ confidence=0.9,
+ reasoning=reasoning,
+ price_at_decision=price,
+ )
+
+ async def stream(
+ self,
+ query: str,
+ competition_id: str,
+ cycle_number: int,
+ dependencies: Optional[Dict] = None,
+ ) -> AsyncGenerator[StreamResponse, None]:
+ """Stream decision process"""
+ dependencies = dependencies or {}
+ market_data = dependencies.get("market_data")
+ portfolio = dependencies.get("portfolio")
+
+ if not market_data or not portfolio:
+ yield StreamResponse(content="Missing market_data or portfolio", event="error")
+ return
+
+ yield decision_started(self.name, market_data.symbol)
+
+ decision = await self.make_decision(market_data, portfolio, cycle_number)
+
+ yield reasoning(self.name, decision.reasoning)
+
+ yield decision_completed(
+ model_name=self.name,
+ action=decision.action.value,
+ symbol=decision.symbol,
+ quantity=decision.quantity,
+ confidence=decision.confidence,
+ reasoning=decision.reasoning,
+ )
+
+ yield done()
+
+ def get_grid_status(self) -> Dict[str, Any]:
+ """Get current grid status for UI display"""
+ if not self.state:
+ return {"status": "not_initialized"}
+
+ return {
+ "status": "active",
+ "config": {
+ "upper_price": self.config.upper_price,
+ "lower_price": self.config.lower_price,
+ "grid_levels": self.config.grid_levels,
+ "grid_type": self.config.grid_type.value,
+ "direction": self.config.direction.value,
+ },
+ "current_price": self.state.current_price,
+ "position": self.state.position,
+ "average_entry": self.state.average_entry,
+ "realized_pnl": self.state.realized_pnl,
+ "grid_profit": self.state.grid_profit,
+ "total_buys": self.state.total_buys,
+ "total_sells": self.state.total_sells,
+ "levels": [
+ {
+ "index": l.index,
+ "price": l.price,
+ "side": l.side,
+ "quantity": l.quantity,
+ "status": l.status,
+ }
+ for l in self.state.levels
+ ],
+ }
+
+ def reset(self):
+ """Reset grid state"""
+ self.state = None
+ logger.info(f"Grid agent '{self.name}' reset")
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/hitl.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/hitl.py
new file mode 100644
index 000000000..6af7968fb
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/hitl.py
@@ -0,0 +1,431 @@
+"""
+Human-in-the-Loop (HITL) Approval System for Alpha Arena
+
+Provides approval mechanisms for:
+- Live trading decisions
+- High-risk actions
+- Large position sizes
+- Strategy changes
+
+Integrates with frontend via Tauri events.
+"""
+
+import asyncio
+from typing import Dict, List, Optional, Any, Callable
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta
+from enum import Enum
+import json
+
+from alpha_arena.types.models import ModelDecision, TradeAction
+from alpha_arena.utils.logging import get_logger
+
+logger = get_logger("hitl")
+
+
+class ApprovalStatus(Enum):
+ PENDING = "pending"
+ APPROVED = "approved"
+ REJECTED = "rejected"
+ TIMEOUT = "timeout"
+ AUTO_APPROVED = "auto_approved"
+
+
+class RiskLevel(Enum):
+ LOW = "low"
+ MEDIUM = "medium"
+ HIGH = "high"
+ CRITICAL = "critical"
+
+
+@dataclass
+class ApprovalRequest:
+ """A request for human approval"""
+ id: str
+ decision: ModelDecision
+ risk_level: RiskLevel
+ reason: str
+ created_at: datetime = field(default_factory=datetime.now)
+ expires_at: Optional[datetime] = None
+ status: ApprovalStatus = ApprovalStatus.PENDING
+ approved_by: Optional[str] = None
+ approval_time: Optional[datetime] = None
+ notes: Optional[str] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "id": self.id,
+ "decision": {
+ "model_name": self.decision.model_name,
+ "action": self.decision.action.value if hasattr(self.decision.action, 'value') else str(self.decision.action),
+ "symbol": self.decision.symbol,
+ "quantity": self.decision.quantity,
+ "confidence": self.decision.confidence,
+ "reasoning": self.decision.reasoning,
+ "price_at_decision": self.decision.price_at_decision,
+ },
+ "risk_level": self.risk_level.value,
+ "reason": self.reason,
+ "created_at": self.created_at.isoformat(),
+ "expires_at": self.expires_at.isoformat() if self.expires_at else None,
+ "status": self.status.value,
+ "approved_by": self.approved_by,
+ "approval_time": self.approval_time.isoformat() if self.approval_time else None,
+ "notes": self.notes,
+ }
+
+ def is_expired(self) -> bool:
+ if self.expires_at is None:
+ return False
+ return datetime.now() > self.expires_at
+
+
+@dataclass
+class ApprovalRule:
+ """A rule that determines when approval is required"""
+ name: str
+ description: str
+ condition: Callable[[ModelDecision, Dict[str, Any]], bool]
+ risk_level: RiskLevel
+ auto_approve_timeout: Optional[int] = None # Seconds after which to auto-approve
+ enabled: bool = True
+
+
+class HITLManager:
+ """
+ Human-in-the-Loop Manager
+
+ Manages approval requests and rules for trading decisions.
+ """
+
+ def __init__(
+ self,
+ default_timeout: int = 60,
+ auto_approve_low_risk: bool = True,
+ ):
+ self.default_timeout = default_timeout
+ self.auto_approve_low_risk = auto_approve_low_risk
+ self._rules: List[ApprovalRule] = []
+ self._pending_requests: Dict[str, ApprovalRequest] = {}
+ self._history: List[ApprovalRequest] = []
+ self._callbacks: Dict[str, Callable] = {}
+ self._request_counter = 0
+
+ # Setup default rules
+ self._setup_default_rules()
+
+ def _setup_default_rules(self):
+ """Setup default approval rules"""
+
+ # Rule 1: Large position size (>25% of portfolio)
+ self.add_rule(ApprovalRule(
+ name="large_position",
+ description="Position size exceeds 25% of portfolio",
+ condition=lambda d, ctx: self._check_large_position(d, ctx),
+ risk_level=RiskLevel.HIGH,
+ auto_approve_timeout=30,
+ ))
+
+ # Rule 2: Live trading mode
+ self.add_rule(ApprovalRule(
+ name="live_trading",
+ description="Live trading enabled (real money)",
+ condition=lambda d, ctx: ctx.get("is_live_trading", False),
+ risk_level=RiskLevel.CRITICAL,
+ auto_approve_timeout=None, # Never auto-approve
+ ))
+
+ # Rule 3: High volatility market
+ self.add_rule(ApprovalRule(
+ name="high_volatility",
+ description="Market volatility is extremely high",
+ condition=lambda d, ctx: ctx.get("volatility_level") == "extreme",
+ risk_level=RiskLevel.MEDIUM,
+ auto_approve_timeout=15,
+ ))
+
+ # Rule 4: Low confidence decision
+ self.add_rule(ApprovalRule(
+ name="low_confidence",
+ description="Agent confidence is below 50%",
+ condition=lambda d, ctx: d.confidence < 0.5 and d.action != TradeAction.HOLD,
+ risk_level=RiskLevel.MEDIUM,
+ auto_approve_timeout=20,
+ ))
+
+ # Rule 5: Consecutive losses
+ self.add_rule(ApprovalRule(
+ name="consecutive_losses",
+ description="3+ consecutive losing trades",
+ condition=lambda d, ctx: ctx.get("consecutive_losses", 0) >= 3,
+ risk_level=RiskLevel.HIGH,
+ auto_approve_timeout=45,
+ ))
+
+ # Rule 6: Max drawdown exceeded
+ self.add_rule(ApprovalRule(
+ name="max_drawdown",
+ description="Portfolio drawdown exceeds 20%",
+ condition=lambda d, ctx: ctx.get("current_drawdown_pct", 0) > 20,
+ risk_level=RiskLevel.HIGH,
+ auto_approve_timeout=None,
+ ))
+
+ def _check_large_position(self, decision: ModelDecision, context: Dict[str, Any]) -> bool:
+ """Check if position size is too large"""
+ portfolio_value = context.get("portfolio_value", 10000)
+ price = decision.price_at_decision or context.get("current_price", 1)
+ position_value = decision.quantity * price
+ position_pct = (position_value / portfolio_value) * 100
+ return position_pct > 25
+
+ def add_rule(self, rule: ApprovalRule):
+ """Add an approval rule"""
+ self._rules.append(rule)
+ logger.info(f"Added HITL rule: {rule.name}")
+
+ def remove_rule(self, name: str):
+ """Remove an approval rule by name"""
+ self._rules = [r for r in self._rules if r.name != name]
+
+ def set_rule_enabled(self, name: str, enabled: bool):
+ """Enable or disable a rule"""
+ for rule in self._rules:
+ if rule.name == name:
+ rule.enabled = enabled
+ break
+
+ def check_approval_required(
+ self,
+ decision: ModelDecision,
+ context: Dict[str, Any],
+ ) -> tuple[bool, List[ApprovalRule]]:
+ """
+ Check if approval is required for a decision.
+
+ Returns:
+ Tuple of (requires_approval, triggered_rules)
+ """
+ triggered = []
+
+ for rule in self._rules:
+ if not rule.enabled:
+ continue
+
+ try:
+ if rule.condition(decision, context):
+ triggered.append(rule)
+ except Exception as e:
+ logger.warning(f"Error checking rule {rule.name}: {e}")
+
+ return len(triggered) > 0, triggered
+
+ def create_approval_request(
+ self,
+ decision: ModelDecision,
+ triggered_rules: List[ApprovalRule],
+ context: Dict[str, Any],
+ ) -> ApprovalRequest:
+ """Create an approval request"""
+ self._request_counter += 1
+
+ # Determine highest risk level
+ risk_levels = [r.risk_level for r in triggered_rules]
+ highest_risk = max(risk_levels, key=lambda r: list(RiskLevel).index(r))
+
+ # Determine timeout
+ timeouts = [r.auto_approve_timeout for r in triggered_rules if r.auto_approve_timeout]
+ if timeouts:
+ timeout = max(timeouts) # Use longest timeout
+ elif highest_risk == RiskLevel.CRITICAL:
+ timeout = None # No auto-approve for critical
+ else:
+ timeout = self.default_timeout
+
+ # Build reason
+ reasons = [f"- {r.name}: {r.description}" for r in triggered_rules]
+ reason = "Approval required:\n" + "\n".join(reasons)
+
+ # Create request
+ request = ApprovalRequest(
+ id=f"hitl_{self._request_counter}_{datetime.now().strftime('%Y%m%d%H%M%S')}",
+ decision=decision,
+ risk_level=highest_risk,
+ reason=reason,
+ expires_at=datetime.now() + timedelta(seconds=timeout) if timeout else None,
+ )
+
+ self._pending_requests[request.id] = request
+ logger.info(f"Created approval request {request.id} (risk: {highest_risk.value})")
+
+ return request
+
+ async def wait_for_approval(
+ self,
+ request: ApprovalRequest,
+ poll_interval: float = 0.5,
+ ) -> ApprovalStatus:
+ """
+ Wait for approval of a request.
+
+ Returns the final status (approved, rejected, or timeout).
+ """
+ while request.status == ApprovalStatus.PENDING:
+ # Check expiration
+ if request.is_expired():
+ # Auto-approve low/medium risk, reject high/critical
+ if self.auto_approve_low_risk and request.risk_level in [RiskLevel.LOW, RiskLevel.MEDIUM]:
+ request.status = ApprovalStatus.AUTO_APPROVED
+ logger.info(f"Request {request.id} auto-approved (timeout)")
+ else:
+ request.status = ApprovalStatus.TIMEOUT
+ logger.info(f"Request {request.id} timed out")
+ break
+
+ await asyncio.sleep(poll_interval)
+
+ # Move to history
+ if request.id in self._pending_requests:
+ del self._pending_requests[request.id]
+ self._history.append(request)
+
+ return request.status
+
+ def approve(self, request_id: str, approved_by: str = "user", notes: str = ""):
+ """Approve a pending request"""
+ if request_id in self._pending_requests:
+ request = self._pending_requests[request_id]
+ request.status = ApprovalStatus.APPROVED
+ request.approved_by = approved_by
+ request.approval_time = datetime.now()
+ request.notes = notes
+ logger.info(f"Request {request_id} approved by {approved_by}")
+ return True
+ return False
+
+ def reject(self, request_id: str, rejected_by: str = "user", notes: str = ""):
+ """Reject a pending request"""
+ if request_id in self._pending_requests:
+ request = self._pending_requests[request_id]
+ request.status = ApprovalStatus.REJECTED
+ request.approved_by = rejected_by
+ request.approval_time = datetime.now()
+ request.notes = notes
+ logger.info(f"Request {request_id} rejected by {rejected_by}")
+ return True
+ return False
+
+ def get_pending_requests(self) -> List[ApprovalRequest]:
+ """Get all pending approval requests"""
+ return list(self._pending_requests.values())
+
+ def get_request(self, request_id: str) -> Optional[ApprovalRequest]:
+ """Get a specific request"""
+ return self._pending_requests.get(request_id)
+
+ def get_history(self, limit: int = 50) -> List[ApprovalRequest]:
+ """Get approval history"""
+ return self._history[-limit:]
+
+ def clear_pending(self):
+ """Clear all pending requests"""
+ for request in self._pending_requests.values():
+ request.status = ApprovalStatus.TIMEOUT
+ self._history.append(request)
+ self._pending_requests.clear()
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Get manager state as dict"""
+ return {
+ "rules": [
+ {
+ "name": r.name,
+ "description": r.description,
+ "risk_level": r.risk_level.value,
+ "auto_approve_timeout": r.auto_approve_timeout,
+ "enabled": r.enabled,
+ }
+ for r in self._rules
+ ],
+ "pending_count": len(self._pending_requests),
+ "pending": [r.to_dict() for r in self._pending_requests.values()],
+ "history_count": len(self._history),
+ }
+
+
+# Singleton instance
+_hitl_manager: Optional[HITLManager] = None
+
+
+def get_hitl_manager() -> HITLManager:
+ """Get the HITL manager singleton"""
+ global _hitl_manager
+ if _hitl_manager is None:
+ _hitl_manager = HITLManager()
+ return _hitl_manager
+
+
+def reset_hitl_manager():
+ """Reset the HITL manager"""
+ global _hitl_manager
+ _hitl_manager = None
+
+
+# Convenience functions for Tauri integration
+def check_decision_approval(
+ decision_dict: Dict[str, Any],
+ context: Dict[str, Any],
+) -> Dict[str, Any]:
+ """
+ Check if a decision requires approval.
+
+ Used by Tauri commands.
+ """
+ manager = get_hitl_manager()
+
+ # Reconstruct decision object
+ decision = ModelDecision(
+ competition_id=decision_dict.get("competition_id", ""),
+ model_name=decision_dict.get("model_name", ""),
+ cycle_number=decision_dict.get("cycle_number", 0),
+ action=TradeAction(decision_dict.get("action", "hold")),
+ symbol=decision_dict.get("symbol", ""),
+ quantity=decision_dict.get("quantity", 0),
+ confidence=decision_dict.get("confidence", 0),
+ reasoning=decision_dict.get("reasoning", ""),
+ price_at_decision=decision_dict.get("price_at_decision", 0),
+ )
+
+ requires, rules = manager.check_approval_required(decision, context)
+
+ if requires:
+ request = manager.create_approval_request(decision, rules, context)
+ return {
+ "requires_approval": True,
+ "request": request.to_dict(),
+ }
+
+ return {
+ "requires_approval": False,
+ "request": None,
+ }
+
+
+def approve_decision(request_id: str, approved_by: str = "user", notes: str = "") -> Dict[str, Any]:
+ """Approve a decision request"""
+ manager = get_hitl_manager()
+ success = manager.approve(request_id, approved_by, notes)
+ return {"success": success, "request_id": request_id, "action": "approved"}
+
+
+def reject_decision(request_id: str, rejected_by: str = "user", notes: str = "") -> Dict[str, Any]:
+ """Reject a decision request"""
+ manager = get_hitl_manager()
+ success = manager.reject(request_id, rejected_by, notes)
+ return {"success": success, "request_id": request_id, "action": "rejected"}
+
+
+def get_pending_approvals() -> List[Dict[str, Any]]:
+ """Get all pending approval requests"""
+ manager = get_hitl_manager()
+ return [r.to_dict() for r in manager.get_pending_requests()]
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/market_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/market_data.py
index 290c21e97..b467c62c0 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/market_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/market_data.py
@@ -254,8 +254,23 @@ async def get_market_data_provider(exchange_id: str = "kraken") -> MarketDataPro
if _provider is None or _provider.exchange_id != exchange_id:
if _provider:
- await _provider.close()
+ try:
+ await _provider.close()
+ except Exception as e:
+ logger.warning(f"Error closing previous market data provider: {e}")
_provider = CachedMarketDataProvider(exchange_id)
await _provider.initialize()
return _provider
+
+
+async def reset_market_data_provider():
+ """Reset the market data provider singleton (useful between competitions)."""
+ global _provider
+ if _provider:
+ try:
+ await _provider.close()
+ except Exception as e:
+ logger.warning(f"Error closing market data provider: {e}")
+ _provider = None
+ logger.info("Market data provider reset")
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/memory_adapter.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/memory_adapter.py
new file mode 100644
index 000000000..265162397
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/memory_adapter.py
@@ -0,0 +1,464 @@
+"""
+Memory Adapter for Alpha Arena
+
+Provides conversation/memory capabilities for trading agents using
+the existing session_module.py from finagent_core.
+"""
+
+import sys
+from pathlib import Path
+from typing import Dict, List, Optional, Any
+from dataclasses import dataclass, field
+from datetime import datetime
+
+# Add paths for imports
+scripts_dir = Path(__file__).parent.parent.parent
+if str(scripts_dir) not in sys.path:
+ sys.path.insert(0, str(scripts_dir))
+
+finagent_path = scripts_dir / "agents" / "finagent_core"
+if str(finagent_path) not in sys.path:
+ sys.path.insert(0, str(finagent_path))
+
+from alpha_arena.utils.logging import get_logger
+
+logger = get_logger("memory_adapter")
+
+
+@dataclass
+class TradeMemory:
+ """Memory of a trading decision and outcome."""
+ timestamp: datetime
+ symbol: str
+ action: str
+ quantity: float
+ price: float
+ reasoning: str
+ outcome: Optional[str] = None # "profit", "loss", "pending"
+ pnl: Optional[float] = None
+ lessons_learned: Optional[str] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "timestamp": self.timestamp.isoformat(),
+ "symbol": self.symbol,
+ "action": self.action,
+ "quantity": self.quantity,
+ "price": self.price,
+ "reasoning": self.reasoning,
+ "outcome": self.outcome,
+ "pnl": self.pnl,
+ "lessons_learned": self.lessons_learned,
+ }
+
+ def to_prompt_context(self) -> str:
+ """Format for LLM context."""
+ lines = [f"Trade on {self.timestamp.strftime('%Y-%m-%d %H:%M')}: {self.action} {self.quantity} {self.symbol} @ ${self.price:,.2f}"]
+ lines.append(f"Reasoning: {self.reasoning}")
+ if self.outcome:
+ lines.append(f"Outcome: {self.outcome} (P&L: ${self.pnl:,.2f})" if self.pnl else f"Outcome: {self.outcome}")
+ if self.lessons_learned:
+ lines.append(f"Lesson: {self.lessons_learned}")
+ return "\n".join(lines)
+
+
+@dataclass
+class MarketInsight:
+ """An insight about market conditions."""
+ timestamp: datetime
+ symbol: str
+ insight_type: str # "pattern", "correlation", "trend", "news"
+ content: str
+ confidence: float = 0.5
+ valid_until: Optional[datetime] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "timestamp": self.timestamp.isoformat(),
+ "symbol": self.symbol,
+ "insight_type": self.insight_type,
+ "content": self.content,
+ "confidence": self.confidence,
+ "valid_until": self.valid_until.isoformat() if self.valid_until else None,
+ }
+
+
+class AgentMemory:
+ """
+ Memory system for Alpha Arena agents.
+
+ Stores:
+ - Trade history with outcomes
+ - Market insights and patterns
+ - Conversation context
+ - Learning from successes/failures
+ """
+
+ def __init__(
+ self,
+ agent_name: str,
+ competition_id: str,
+ storage_path: Optional[str] = None,
+ max_trade_memory: int = 100,
+ max_insights: int = 50,
+ ):
+ self.agent_name = agent_name
+ self.competition_id = competition_id
+ self.storage_path = storage_path
+ self.max_trade_memory = max_trade_memory
+ self.max_insights = max_insights
+
+ self._trade_memories: List[TradeMemory] = []
+ self._insights: List[MarketInsight] = []
+ self._conversation_context: List[Dict[str, Any]] = []
+ self._session_module = None
+ self._session_id: Optional[str] = None
+
+ # Initialize session module
+ self._init_session()
+
+ def _init_session(self):
+ """Initialize session module from finagent_core."""
+ try:
+ from modules.session_module import SessionModule
+
+ self._session_module = SessionModule(
+ storage_path=self.storage_path or f"./alpha_arena_sessions/{self.competition_id}.db",
+ auto_save=True,
+ )
+
+ # Create or resume session for this agent
+ self._session_id = self._session_module.create_session(
+ session_id=f"{self.competition_id}_{self.agent_name}",
+ metadata={
+ "competition_id": self.competition_id,
+ "agent_name": self.agent_name,
+ "created_at": datetime.now().isoformat(),
+ }
+ )
+
+ logger.info(f"Session initialized for {self.agent_name}")
+
+ except ImportError:
+ logger.warning("SessionModule not available, using in-memory storage only")
+ except Exception as e:
+ logger.warning(f"Failed to initialize session: {e}")
+
+ def record_trade(
+ self,
+ symbol: str,
+ action: str,
+ quantity: float,
+ price: float,
+ reasoning: str,
+ ) -> TradeMemory:
+ """
+ Record a trading decision.
+
+ Args:
+ symbol: Trading symbol
+ action: Trade action (buy, sell, hold)
+ quantity: Trade quantity
+ price: Execution price
+ reasoning: Decision reasoning
+
+ Returns:
+ TradeMemory object
+ """
+ memory = TradeMemory(
+ timestamp=datetime.now(),
+ symbol=symbol,
+ action=action,
+ quantity=quantity,
+ price=price,
+ reasoning=reasoning,
+ )
+
+ self._trade_memories.append(memory)
+
+ # Trim to max
+ if len(self._trade_memories) > self.max_trade_memory:
+ self._trade_memories = self._trade_memories[-self.max_trade_memory:]
+
+ # Add to session conversation
+ if self._session_module and self._session_id:
+ self._session_module.add_message(
+ self._session_id,
+ role="assistant",
+ content=f"TRADE: {action} {quantity} {symbol} @ ${price:.2f}\nReason: {reasoning}",
+ trade_data=memory.to_dict(),
+ )
+
+ return memory
+
+ def update_trade_outcome(
+ self,
+ trade_index: int,
+ outcome: str,
+ pnl: float,
+ lessons_learned: Optional[str] = None,
+ ):
+ """
+ Update a trade with its outcome.
+
+ Args:
+ trade_index: Index of trade in memory
+ outcome: "profit", "loss", or "breakeven"
+ pnl: Profit/Loss amount
+ lessons_learned: Optional lessons from this trade
+ """
+ if 0 <= trade_index < len(self._trade_memories):
+ memory = self._trade_memories[trade_index]
+ memory.outcome = outcome
+ memory.pnl = pnl
+ memory.lessons_learned = lessons_learned
+
+ # Update session state
+ if self._session_module and self._session_id:
+ stats = self.get_performance_stats()
+ self._session_module.update_session_state(
+ self._session_id,
+ {"performance_stats": stats},
+ )
+
+ def add_insight(
+ self,
+ symbol: str,
+ insight_type: str,
+ content: str,
+ confidence: float = 0.5,
+ valid_hours: int = 24,
+ ) -> MarketInsight:
+ """
+ Add a market insight.
+
+ Args:
+ symbol: Related symbol
+ insight_type: Type of insight
+ content: Insight content
+ confidence: Confidence level (0-1)
+ valid_hours: Hours until insight expires
+
+ Returns:
+ MarketInsight object
+ """
+ from datetime import timedelta
+
+ insight = MarketInsight(
+ timestamp=datetime.now(),
+ symbol=symbol,
+ insight_type=insight_type,
+ content=content,
+ confidence=confidence,
+ valid_until=datetime.now() + timedelta(hours=valid_hours),
+ )
+
+ self._insights.append(insight)
+
+ # Trim to max
+ if len(self._insights) > self.max_insights:
+ self._insights = self._insights[-self.max_insights:]
+
+ return insight
+
+ def get_relevant_context(
+ self,
+ symbol: str,
+ max_trades: int = 5,
+ max_insights: int = 3,
+ ) -> str:
+ """
+ Get relevant context for a symbol.
+
+ Args:
+ symbol: Trading symbol
+ max_trades: Max recent trades to include
+ max_insights: Max insights to include
+
+ Returns:
+ Formatted context string for LLM
+ """
+ lines = [f"AGENT MEMORY FOR {symbol}:"]
+
+ # Recent trades for this symbol
+ symbol_trades = [t for t in self._trade_memories if t.symbol == symbol]
+ recent_trades = symbol_trades[-max_trades:] if symbol_trades else []
+
+ if recent_trades:
+ lines.append("\nRecent Trades:")
+ for trade in recent_trades:
+ lines.append(f" - {trade.to_prompt_context()}")
+
+ # Relevant insights
+ now = datetime.now()
+ valid_insights = [
+ i for i in self._insights
+ if (i.symbol == symbol or i.symbol == "MARKET")
+ and (i.valid_until is None or i.valid_until > now)
+ ]
+ recent_insights = valid_insights[-max_insights:] if valid_insights else []
+
+ if recent_insights:
+ lines.append("\nMarket Insights:")
+ for insight in recent_insights:
+ lines.append(f" - [{insight.insight_type}] {insight.content} (confidence: {insight.confidence:.0%})")
+
+ # Performance stats
+ stats = self.get_performance_stats()
+ if stats["total_trades"] > 0:
+ lines.append(f"\nPerformance: {stats['win_rate']:.0%} win rate, {stats['total_pnl']:.2f} total P&L")
+
+ return "\n".join(lines)
+
+ def get_performance_stats(self) -> Dict[str, Any]:
+ """Get performance statistics from memory."""
+ completed_trades = [t for t in self._trade_memories if t.outcome]
+
+ if not completed_trades:
+ return {
+ "total_trades": len(self._trade_memories),
+ "completed_trades": 0,
+ "wins": 0,
+ "losses": 0,
+ "win_rate": 0.0,
+ "total_pnl": 0.0,
+ "avg_pnl": 0.0,
+ }
+
+ wins = sum(1 for t in completed_trades if t.outcome == "profit")
+ losses = sum(1 for t in completed_trades if t.outcome == "loss")
+ total_pnl = sum(t.pnl or 0 for t in completed_trades)
+
+ return {
+ "total_trades": len(self._trade_memories),
+ "completed_trades": len(completed_trades),
+ "wins": wins,
+ "losses": losses,
+ "win_rate": wins / len(completed_trades) if completed_trades else 0.0,
+ "total_pnl": total_pnl,
+ "avg_pnl": total_pnl / len(completed_trades) if completed_trades else 0.0,
+ }
+
+ def get_lessons_learned(self, symbol: Optional[str] = None) -> List[str]:
+ """Get lessons learned from trades."""
+ if symbol:
+ trades = [t for t in self._trade_memories if t.symbol == symbol and t.lessons_learned]
+ else:
+ trades = [t for t in self._trade_memories if t.lessons_learned]
+
+ return [t.lessons_learned for t in trades]
+
+ def add_conversation(self, role: str, content: str):
+ """Add a conversation message to memory."""
+ self._conversation_context.append({
+ "role": role,
+ "content": content,
+ "timestamp": datetime.now().isoformat(),
+ })
+
+ # Also add to session module
+ if self._session_module and self._session_id:
+ self._session_module.add_message(self._session_id, role, content)
+
+ def get_conversation_history(self, limit: int = 10) -> List[Dict[str, Any]]:
+ """Get recent conversation history."""
+ if self._session_module and self._session_id:
+ return self._session_module.get_messages(self._session_id, limit=limit)
+ return self._conversation_context[-limit:]
+
+ def search_memory(self, query: str, limit: int = 5) -> List[Dict[str, Any]]:
+ """Search memory for relevant information."""
+ results = []
+ query_lower = query.lower()
+
+ # Search trade memories
+ for i, trade in enumerate(self._trade_memories):
+ if query_lower in trade.reasoning.lower() or query_lower in trade.symbol.lower():
+ results.append({
+ "type": "trade",
+ "index": i,
+ "data": trade.to_dict(),
+ })
+ if len(results) >= limit:
+ return results
+
+ # Search insights
+ for i, insight in enumerate(self._insights):
+ if query_lower in insight.content.lower() or query_lower in insight.symbol.lower():
+ results.append({
+ "type": "insight",
+ "index": i,
+ "data": insight.to_dict(),
+ })
+ if len(results) >= limit:
+ return results
+
+ # Search session history
+ if self._session_module and self._session_id:
+ session_results = self._session_module.search_history(query, self._session_id, limit=limit - len(results))
+ results.extend([{"type": "conversation", **r} for r in session_results])
+
+ return results[:limit]
+
+ def get_summary(self) -> str:
+ """Get a summary of agent memory."""
+ stats = self.get_performance_stats()
+ insights_count = len(self._insights)
+
+ return (
+ f"Agent: {self.agent_name} | Competition: {self.competition_id}\n"
+ f"Trades: {stats['total_trades']} ({stats['wins']}W/{stats['losses']}L)\n"
+ f"Win Rate: {stats['win_rate']:.0%} | Total P&L: ${stats['total_pnl']:.2f}\n"
+ f"Active Insights: {insights_count}"
+ )
+
+ def clear_memory(self, keep_lessons: bool = True):
+ """Clear memory, optionally keeping lessons learned."""
+ if keep_lessons:
+ lessons = self.get_lessons_learned()
+ else:
+ lessons = []
+
+ self._trade_memories.clear()
+ self._insights.clear()
+
+ # Re-add lessons as insights
+ for lesson in lessons:
+ self.add_insight("MARKET", "lesson", lesson, confidence=0.8, valid_hours=168)
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Export memory to dictionary."""
+ return {
+ "agent_name": self.agent_name,
+ "competition_id": self.competition_id,
+ "trades": [t.to_dict() for t in self._trade_memories],
+ "insights": [i.to_dict() for i in self._insights],
+ "stats": self.get_performance_stats(),
+ }
+
+
+# Factory function
+_agent_memories: Dict[str, AgentMemory] = {}
+
+
+def get_agent_memory(
+ agent_name: str,
+ competition_id: str,
+ storage_path: Optional[str] = None,
+) -> AgentMemory:
+ """Get or create memory for an agent."""
+ key = f"{competition_id}_{agent_name}"
+
+ if key not in _agent_memories:
+ _agent_memories[key] = AgentMemory(
+ agent_name=agent_name,
+ competition_id=competition_id,
+ storage_path=storage_path,
+ )
+
+ return _agent_memories[key]
+
+
+def clear_all_memories():
+ """Clear all agent memories."""
+ _agent_memories.clear()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/paper_trading_bridge.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/paper_trading_bridge.py
new file mode 100644
index 000000000..448ad8ddb
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/paper_trading_bridge.py
@@ -0,0 +1,983 @@
+"""
+Paper Trading Bridge for Alpha Arena
+
+This module bridges Alpha Arena's Python competition system with the main Rust paper trading module.
+It directly accesses the SQLite database used by Rust to ensure data persistence.
+"""
+
+import sqlite3
+import uuid
+from datetime import datetime
+from pathlib import Path
+from typing import Dict, List, Optional, Any
+from dataclasses import dataclass
+import os
+import json
+
+from alpha_arena.utils.logging import get_logger
+from alpha_arena.types.models import (
+ MarketData,
+ ModelDecision,
+ TradeAction,
+ TradeResult,
+)
+
+logger = get_logger("paper_trading_bridge")
+
+
+@dataclass
+class Portfolio:
+ """Paper trading portfolio."""
+ id: str
+ name: str
+ initial_balance: float
+ balance: float
+ currency: str
+ leverage: float
+ margin_mode: str
+ fee_rate: float
+ created_at: str
+
+
+@dataclass
+class Position:
+ """Paper trading position."""
+ id: str
+ portfolio_id: str
+ symbol: str
+ side: str # "long" | "short"
+ quantity: float
+ entry_price: float
+ current_price: float
+ unrealized_pnl: float
+ realized_pnl: float
+ leverage: float
+ liquidation_price: Optional[float]
+ opened_at: str
+
+
+@dataclass
+class Order:
+ """Paper trading order."""
+ id: str
+ portfolio_id: str
+ symbol: str
+ side: str # "buy" | "sell"
+ order_type: str # "market" | "limit" | "stop" | "stop_limit"
+ quantity: float
+ price: Optional[float]
+ stop_price: Optional[float]
+ filled_qty: float
+ avg_price: Optional[float]
+ status: str # "pending" | "filled" | "partial" | "cancelled"
+ reduce_only: bool
+ created_at: str
+ filled_at: Optional[str]
+
+
+@dataclass
+class Trade:
+ """Paper trading trade (execution)."""
+ id: str
+ portfolio_id: str
+ order_id: str
+ symbol: str
+ side: str
+ price: float
+ quantity: float
+ fee: float
+ pnl: float
+ timestamp: str
+
+
+@dataclass
+class BridgePortfolioState:
+ """Portfolio state with calculated values (bridge-specific format)."""
+ model_name: str
+ portfolio_value: float
+ cash: float
+ total_pnl: float
+ unrealized_pnl: float
+ trades_count: int
+ positions: List[Dict[str, Any]] # List format for easy serialization
+
+
+def get_db_path() -> Path:
+ """Get the path to the Fincept database."""
+ # Try different possible locations for the database
+ possible_paths = [
+ # Windows AppData
+ Path(os.environ.get("APPDATA", "")) / "fincept-terminal" / "fincept_terminal.db",
+ Path(os.environ.get("LOCALAPPDATA", "")) / "fincept-terminal" / "fincept_terminal.db",
+ # Development paths
+ Path(__file__).parent.parent.parent.parent.parent.parent / "fincept_terminal.db",
+ # Linux/Mac
+ Path.home() / ".config" / "fincept-terminal" / "fincept_terminal.db",
+ Path.home() / ".local" / "share" / "fincept-terminal" / "fincept_terminal.db",
+ ]
+
+ for path in possible_paths:
+ if path.exists():
+ logger.info(f"Found database at: {path}")
+ return path
+
+ # Default to Windows AppData
+ default_path = Path(os.environ.get("APPDATA", "C:/")) / "fincept-terminal" / "fincept_terminal.db"
+ logger.warning(f"Database not found, using default: {default_path}")
+ return default_path
+
+
+def get_connection() -> sqlite3.Connection:
+ """Get SQLite connection with proper settings."""
+ db_path = get_db_path()
+
+ # Ensure directory exists
+ db_path.parent.mkdir(parents=True, exist_ok=True)
+
+ conn = sqlite3.connect(str(db_path), timeout=30.0)
+ conn.row_factory = sqlite3.Row
+ # Enable foreign keys and WAL mode for better concurrency
+ conn.execute("PRAGMA foreign_keys = ON")
+ conn.execute("PRAGMA journal_mode = WAL")
+ return conn
+
+
+class ConnectionManager:
+ """Context manager for database connections."""
+
+ def __init__(self):
+ self.conn: Optional[sqlite3.Connection] = None
+
+ def __enter__(self) -> sqlite3.Connection:
+ self.conn = get_connection()
+ return self.conn
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ if self.conn:
+ if exc_type is None:
+ self.conn.commit()
+ else:
+ self.conn.rollback()
+ self.conn.close()
+ return False # Don't suppress exceptions
+
+
+class PaperTradingBridge:
+ """
+ Bridge to Rust paper trading module via SQLite.
+
+ This replaces the in-memory PaperTradingEngine with database-backed operations.
+ """
+
+ def __init__(
+ self,
+ competition_id: str,
+ model_name: str,
+ initial_capital: float = 10000.0,
+ fee_rate: float = 0.001,
+ currency: str = "USD",
+ ):
+ self.competition_id = competition_id
+ self.model_name = model_name
+ self.initial_capital = initial_capital
+ self.fee_rate = fee_rate
+ self.currency = currency
+ self.portfolio_id: Optional[str] = None
+
+ # Initialize on creation
+ self._ensure_tables()
+ self._initialize_portfolio()
+
+ def _ensure_tables(self):
+ """Ensure paper trading tables exist (they should be created by Rust)."""
+ conn = get_connection()
+ try:
+ # Check if pt_portfolios table exists
+ cursor = conn.execute(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='pt_portfolios'"
+ )
+ if not cursor.fetchone():
+ logger.warning("Paper trading tables not found, creating them...")
+ self._create_tables(conn)
+ conn.commit()
+ finally:
+ conn.close()
+
+ def _create_tables(self, conn: sqlite3.Connection):
+ """Create paper trading tables if they don't exist."""
+ conn.executescript("""
+ CREATE TABLE IF NOT EXISTS pt_portfolios (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ initial_balance REAL NOT NULL,
+ balance REAL NOT NULL,
+ currency TEXT DEFAULT 'USD',
+ leverage REAL DEFAULT 1.0,
+ margin_mode TEXT DEFAULT 'cross',
+ fee_rate REAL DEFAULT 0.001,
+ created_at TEXT NOT NULL
+ );
+
+ CREATE TABLE IF NOT EXISTS pt_orders (
+ id TEXT PRIMARY KEY,
+ portfolio_id TEXT NOT NULL,
+ symbol TEXT NOT NULL,
+ side TEXT NOT NULL,
+ order_type TEXT NOT NULL,
+ quantity REAL NOT NULL,
+ price REAL,
+ stop_price REAL,
+ filled_qty REAL DEFAULT 0,
+ avg_price REAL,
+ status TEXT DEFAULT 'pending',
+ reduce_only INTEGER DEFAULT 0,
+ created_at TEXT NOT NULL,
+ filled_at TEXT,
+ FOREIGN KEY (portfolio_id) REFERENCES pt_portfolios(id)
+ );
+
+ CREATE TABLE IF NOT EXISTS pt_positions (
+ id TEXT PRIMARY KEY,
+ portfolio_id TEXT NOT NULL,
+ symbol TEXT NOT NULL,
+ side TEXT NOT NULL,
+ quantity REAL NOT NULL,
+ entry_price REAL NOT NULL,
+ current_price REAL NOT NULL,
+ unrealized_pnl REAL DEFAULT 0,
+ realized_pnl REAL DEFAULT 0,
+ leverage REAL DEFAULT 1.0,
+ liquidation_price REAL,
+ opened_at TEXT NOT NULL,
+ FOREIGN KEY (portfolio_id) REFERENCES pt_portfolios(id),
+ UNIQUE(portfolio_id, symbol, side)
+ );
+
+ CREATE TABLE IF NOT EXISTS pt_trades (
+ id TEXT PRIMARY KEY,
+ portfolio_id TEXT NOT NULL,
+ order_id TEXT NOT NULL,
+ symbol TEXT NOT NULL,
+ side TEXT NOT NULL,
+ price REAL NOT NULL,
+ quantity REAL NOT NULL,
+ fee REAL NOT NULL,
+ pnl REAL DEFAULT 0,
+ timestamp TEXT NOT NULL,
+ FOREIGN KEY (portfolio_id) REFERENCES pt_portfolios(id),
+ FOREIGN KEY (order_id) REFERENCES pt_orders(id)
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_orders_portfolio ON pt_orders(portfolio_id);
+ CREATE INDEX IF NOT EXISTS idx_positions_portfolio ON pt_positions(portfolio_id);
+ CREATE INDEX IF NOT EXISTS idx_trades_portfolio ON pt_trades(portfolio_id);
+ """)
+
+ def _initialize_portfolio(self):
+ """Initialize or get existing portfolio for this competition/model."""
+ conn = get_connection()
+ try:
+ portfolio_name = f"alpha_arena_{self.competition_id}_{self.model_name}"
+
+ # Check for existing portfolio
+ cursor = conn.execute(
+ "SELECT id FROM pt_portfolios WHERE name = ?",
+ (portfolio_name,)
+ )
+ row = cursor.fetchone()
+
+ if row:
+ self.portfolio_id = row["id"]
+ logger.info(f"Using existing portfolio: {self.portfolio_id}")
+ else:
+ # Create new portfolio
+ self.portfolio_id = str(uuid.uuid4())
+ now = datetime.utcnow().isoformat() + "Z"
+
+ conn.execute(
+ """INSERT INTO pt_portfolios
+ (id, name, initial_balance, balance, currency, leverage, margin_mode, fee_rate, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ self.portfolio_id,
+ portfolio_name,
+ self.initial_capital,
+ self.initial_capital,
+ self.currency,
+ 1.0, # leverage
+ "cross", # margin_mode
+ self.fee_rate,
+ now,
+ )
+ )
+ conn.commit()
+ logger.info(f"Created new portfolio: {self.portfolio_id}")
+
+ # Also record in alpha_arena_model_portfolios for linking
+ self._link_model_portfolio(conn)
+ finally:
+ conn.close()
+
+ def _link_model_portfolio(self, conn: sqlite3.Connection):
+ """Link this portfolio to the Alpha Arena competition."""
+ try:
+ link_id = str(uuid.uuid4())
+ now = datetime.utcnow().isoformat() + "Z"
+
+ conn.execute(
+ """INSERT OR REPLACE INTO alpha_arena_model_portfolios
+ (id, competition_id, model_name, portfolio_id, initial_capital, created_at)
+ VALUES (?, ?, ?, ?, ?, ?)""",
+ (
+ link_id,
+ self.competition_id,
+ self.model_name,
+ self.portfolio_id,
+ self.initial_capital,
+ now,
+ )
+ )
+ conn.commit()
+ logger.info(f"Linked model {self.model_name} to portfolio {self.portfolio_id}")
+ except sqlite3.Error as e:
+ # Table might not exist yet, that's ok
+ logger.warning(f"Could not link model portfolio: {e}")
+
+ def get_portfolio(self) -> Optional[Portfolio]:
+ """Get current portfolio state."""
+ if not self.portfolio_id:
+ return None
+
+ conn = get_connection()
+ try:
+ cursor = conn.execute(
+ """SELECT id, name, initial_balance, balance, currency, leverage,
+ margin_mode, fee_rate, created_at
+ FROM pt_portfolios WHERE id = ?""",
+ (self.portfolio_id,)
+ )
+ row = cursor.fetchone()
+
+ if row:
+ return Portfolio(
+ id=row["id"],
+ name=row["name"],
+ initial_balance=row["initial_balance"],
+ balance=row["balance"],
+ currency=row["currency"],
+ leverage=row["leverage"],
+ margin_mode=row["margin_mode"],
+ fee_rate=row["fee_rate"],
+ created_at=row["created_at"],
+ )
+ return None
+ finally:
+ conn.close()
+
+ def get_positions(self) -> List[Position]:
+ """Get all open positions."""
+ if not self.portfolio_id:
+ return []
+
+ conn = get_connection()
+ try:
+ cursor = conn.execute(
+ """SELECT id, portfolio_id, symbol, side, quantity, entry_price,
+ current_price, unrealized_pnl, realized_pnl, leverage,
+ liquidation_price, opened_at
+ FROM pt_positions WHERE portfolio_id = ?""",
+ (self.portfolio_id,)
+ )
+
+ return [
+ Position(
+ id=row["id"],
+ portfolio_id=row["portfolio_id"],
+ symbol=row["symbol"],
+ side=row["side"],
+ quantity=row["quantity"],
+ entry_price=row["entry_price"],
+ current_price=row["current_price"],
+ unrealized_pnl=row["unrealized_pnl"],
+ realized_pnl=row["realized_pnl"],
+ leverage=row["leverage"],
+ liquidation_price=row["liquidation_price"],
+ opened_at=row["opened_at"],
+ )
+ for row in cursor.fetchall()
+ ]
+ finally:
+ conn.close()
+
+ def get_trades(self, limit: int = 100) -> List[Trade]:
+ """Get recent trades."""
+ if not self.portfolio_id:
+ return []
+
+ conn = get_connection()
+ try:
+ cursor = conn.execute(
+ """SELECT id, portfolio_id, order_id, symbol, side, price, quantity, fee, pnl, timestamp
+ FROM pt_trades
+ WHERE portfolio_id = ?
+ ORDER BY timestamp DESC
+ LIMIT ?""",
+ (self.portfolio_id, limit)
+ )
+
+ return [
+ Trade(
+ id=row["id"],
+ portfolio_id=row["portfolio_id"],
+ order_id=row["order_id"],
+ symbol=row["symbol"],
+ side=row["side"],
+ price=row["price"],
+ quantity=row["quantity"],
+ fee=row["fee"],
+ pnl=row["pnl"],
+ timestamp=row["timestamp"],
+ )
+ for row in cursor.fetchall()
+ ]
+ finally:
+ conn.close()
+
+ def place_order(
+ self,
+ symbol: str,
+ side: str,
+ order_type: str,
+ quantity: float,
+ price: Optional[float] = None,
+ reduce_only: bool = False,
+ ) -> Optional[Order]:
+ """Place a new order."""
+ if not self.portfolio_id:
+ logger.error("No portfolio initialized")
+ return None
+
+ conn = get_connection()
+ try:
+ # Validate
+ if quantity <= 0:
+ logger.error("Invalid quantity")
+ return None
+
+ if order_type == "limit" and price is None:
+ logger.error("Limit order requires price")
+ return None
+
+ # Check balance for new positions
+ if not reduce_only:
+ portfolio = self.get_portfolio()
+ if not portfolio:
+ return None
+
+ required_margin = quantity * (price or 0) / portfolio.leverage
+ if required_margin > portfolio.balance:
+ logger.error(f"Insufficient margin: need {required_margin}, have {portfolio.balance}")
+ return None
+
+ order_id = str(uuid.uuid4())
+ now = datetime.utcnow().isoformat() + "Z"
+
+ conn.execute(
+ """INSERT INTO pt_orders
+ (id, portfolio_id, symbol, side, order_type, quantity, price, filled_qty, status, reduce_only, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, 'pending', ?, ?)""",
+ (
+ order_id,
+ self.portfolio_id,
+ symbol,
+ side.lower(),
+ order_type,
+ quantity,
+ price,
+ 1 if reduce_only else 0,
+ now,
+ )
+ )
+ conn.commit()
+
+ return Order(
+ id=order_id,
+ portfolio_id=self.portfolio_id,
+ symbol=symbol,
+ side=side.lower(),
+ order_type=order_type,
+ quantity=quantity,
+ price=price,
+ stop_price=None,
+ filled_qty=0,
+ avg_price=None,
+ status="pending",
+ reduce_only=reduce_only,
+ created_at=now,
+ filled_at=None,
+ )
+ finally:
+ conn.close()
+
+ def fill_order(self, order_id: str, fill_price: float, fill_qty: Optional[float] = None) -> Optional[Trade]:
+ """Fill an order at the given price."""
+ conn = get_connection()
+ try:
+ # Get order
+ cursor = conn.execute(
+ """SELECT id, portfolio_id, symbol, side, order_type, quantity, price,
+ filled_qty, avg_price, status, reduce_only
+ FROM pt_orders WHERE id = ?""",
+ (order_id,)
+ )
+ order_row = cursor.fetchone()
+
+ if not order_row:
+ logger.error(f"Order not found: {order_id}")
+ return None
+
+ if order_row["status"] not in ("pending", "partial"):
+ logger.error(f"Order not fillable, status: {order_row['status']}")
+ return None
+
+ # Get portfolio
+ portfolio = self.get_portfolio()
+ if not portfolio:
+ return None
+
+ # Calculate fill quantity
+ qty = fill_qty or (order_row["quantity"] - order_row["filled_qty"])
+ fee = qty * fill_price * portfolio.fee_rate
+ now = datetime.utcnow().isoformat() + "Z"
+
+ # Determine position side
+ position_side = "long" if order_row["side"] == "buy" else "short"
+ opposite_side = "short" if order_row["side"] == "buy" else "long"
+ pnl = 0.0
+
+ # Check for closing opposite position
+ cursor = conn.execute(
+ """SELECT id, quantity, entry_price, realized_pnl
+ FROM pt_positions
+ WHERE portfolio_id = ? AND symbol = ? AND side = ?""",
+ (self.portfolio_id, order_row["symbol"], opposite_side)
+ )
+ opposite_pos = cursor.fetchone()
+
+ if opposite_pos:
+ # Closing/reducing existing position
+ close_qty = min(qty, opposite_pos["quantity"])
+
+ if opposite_side == "long":
+ pnl = (fill_price - opposite_pos["entry_price"]) * close_qty
+ else:
+ pnl = (opposite_pos["entry_price"] - fill_price) * close_qty
+
+ if close_qty >= opposite_pos["quantity"]:
+ # Close entire position
+ conn.execute("DELETE FROM pt_positions WHERE id = ?", (opposite_pos["id"],))
+ else:
+ # Reduce position
+ new_qty = opposite_pos["quantity"] - close_qty
+ new_realized = opposite_pos["realized_pnl"] + pnl
+ conn.execute(
+ "UPDATE pt_positions SET quantity = ?, realized_pnl = ? WHERE id = ?",
+ (new_qty, new_realized, opposite_pos["id"])
+ )
+
+ # Open remaining as new position
+ remaining_qty = qty - close_qty
+ if remaining_qty > 0:
+ self._create_or_add_position(
+ conn, order_row["symbol"], position_side, remaining_qty, fill_price
+ )
+ else:
+ # Check for same-side position to add to
+ cursor = conn.execute(
+ """SELECT id, quantity, entry_price
+ FROM pt_positions
+ WHERE portfolio_id = ? AND symbol = ? AND side = ?""",
+ (self.portfolio_id, order_row["symbol"], position_side)
+ )
+ same_pos = cursor.fetchone()
+
+ if same_pos:
+ # Average into existing position
+ new_qty = same_pos["quantity"] + qty
+ new_entry = (same_pos["entry_price"] * same_pos["quantity"] + fill_price * qty) / new_qty
+ conn.execute(
+ "UPDATE pt_positions SET quantity = ?, entry_price = ?, current_price = ? WHERE id = ?",
+ (new_qty, new_entry, fill_price, same_pos["id"])
+ )
+ else:
+ # New position
+ self._create_or_add_position(
+ conn, order_row["symbol"], position_side, qty, fill_price
+ )
+
+ # Update balance
+ balance_change = pnl - fee
+ conn.execute(
+ "UPDATE pt_portfolios SET balance = balance + ? WHERE id = ?",
+ (balance_change, self.portfolio_id)
+ )
+
+ # Update order
+ new_filled = order_row["filled_qty"] + qty
+ new_status = "filled" if new_filled >= order_row["quantity"] else "partial"
+ old_avg = order_row["avg_price"] or 0
+ new_avg = (old_avg * order_row["filled_qty"] + fill_price * qty) / new_filled if new_filled > 0 else fill_price
+
+ conn.execute(
+ """UPDATE pt_orders
+ SET filled_qty = ?, avg_price = ?, status = ?, filled_at = ?
+ WHERE id = ?""",
+ (new_filled, new_avg, new_status, now, order_id)
+ )
+
+ # Create trade record
+ trade_id = str(uuid.uuid4())
+ conn.execute(
+ """INSERT INTO pt_trades
+ (id, portfolio_id, order_id, symbol, side, price, quantity, fee, pnl, timestamp)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
+ (
+ trade_id,
+ self.portfolio_id,
+ order_id,
+ order_row["symbol"],
+ order_row["side"],
+ fill_price,
+ qty,
+ fee,
+ pnl,
+ now,
+ )
+ )
+
+ conn.commit()
+
+ return Trade(
+ id=trade_id,
+ portfolio_id=self.portfolio_id,
+ order_id=order_id,
+ symbol=order_row["symbol"],
+ side=order_row["side"],
+ price=fill_price,
+ quantity=qty,
+ fee=fee,
+ pnl=pnl,
+ timestamp=now,
+ )
+ finally:
+ conn.close()
+
+ def _create_or_add_position(
+ self,
+ conn: sqlite3.Connection,
+ symbol: str,
+ side: str,
+ quantity: float,
+ price: float,
+ ):
+ """Create a new position."""
+ pos_id = str(uuid.uuid4())
+ now = datetime.utcnow().isoformat() + "Z"
+
+ conn.execute(
+ """INSERT INTO pt_positions
+ (id, portfolio_id, symbol, side, quantity, entry_price, current_price,
+ unrealized_pnl, realized_pnl, leverage, opened_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, 0, 1.0, ?)""",
+ (
+ pos_id,
+ self.portfolio_id,
+ symbol,
+ side,
+ quantity,
+ price,
+ price,
+ now,
+ )
+ )
+
+ def update_position_price(self, symbol: str, price: float):
+ """Update position with current market price."""
+ if not self.portfolio_id:
+ return
+
+ conn = get_connection()
+ try:
+ conn.execute(
+ """UPDATE pt_positions
+ SET current_price = ?,
+ unrealized_pnl = CASE
+ WHEN side = 'long' THEN (? - entry_price) * quantity
+ ELSE (entry_price - ?) * quantity
+ END
+ WHERE portfolio_id = ? AND symbol = ?""",
+ (price, price, price, self.portfolio_id, symbol)
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+ def get_portfolio_state(self, prices: Dict[str, float]) -> BridgePortfolioState:
+ """Get current portfolio state with calculated values."""
+ portfolio = self.get_portfolio()
+ positions = self.get_positions()
+ trades = self.get_trades()
+
+ if not portfolio:
+ return BridgePortfolioState(
+ model_name=self.model_name,
+ portfolio_value=self.initial_capital,
+ cash=self.initial_capital,
+ total_pnl=0.0,
+ unrealized_pnl=0.0,
+ trades_count=0,
+ positions=[],
+ )
+
+ # Update position prices and calculate unrealized PnL
+ total_unrealized = 0.0
+ position_dicts = []
+
+ for pos in positions:
+ current_price = prices.get(pos.symbol, pos.current_price)
+
+ # Update price in database
+ self.update_position_price(pos.symbol, current_price)
+
+ # Calculate unrealized PnL
+ if pos.side == "long":
+ unrealized = (current_price - pos.entry_price) * pos.quantity
+ else:
+ unrealized = (pos.entry_price - current_price) * pos.quantity
+
+ total_unrealized += unrealized
+
+ position_dicts.append({
+ "symbol": pos.symbol,
+ "side": pos.side,
+ "quantity": pos.quantity,
+ "entry_price": pos.entry_price,
+ "current_price": current_price,
+ "unrealized_pnl": unrealized,
+ })
+
+ # Calculate total realized PnL from trades
+ total_realized = sum(t.pnl for t in trades)
+
+ # Portfolio value = cash + positions value
+ positions_value = sum(
+ p["quantity"] * p["current_price"] for p in position_dicts
+ )
+ portfolio_value = portfolio.balance + positions_value
+
+ return BridgePortfolioState(
+ model_name=self.model_name,
+ portfolio_value=portfolio_value,
+ cash=portfolio.balance,
+ total_pnl=total_realized + total_unrealized,
+ unrealized_pnl=total_unrealized,
+ trades_count=len(trades),
+ positions=position_dicts,
+ )
+
+ def reset(self):
+ """Reset portfolio to initial state."""
+ if not self.portfolio_id:
+ return
+
+ conn = get_connection()
+ try:
+ # Delete all positions, orders, trades
+ conn.execute("DELETE FROM pt_trades WHERE portfolio_id = ?", (self.portfolio_id,))
+ conn.execute("DELETE FROM pt_orders WHERE portfolio_id = ?", (self.portfolio_id,))
+ conn.execute("DELETE FROM pt_positions WHERE portfolio_id = ?", (self.portfolio_id,))
+
+ # Reset balance
+ conn.execute(
+ "UPDATE pt_portfolios SET balance = initial_balance WHERE id = ?",
+ (self.portfolio_id,)
+ )
+ conn.commit()
+ logger.info(f"Portfolio {self.portfolio_id} reset to initial state")
+ finally:
+ conn.close()
+
+ def execute_decision(
+ self,
+ decision: ModelDecision,
+ market_data: MarketData,
+ ) -> TradeResult:
+ """
+ Execute a trading decision using the database-backed paper trading.
+
+ This method provides the same interface as the old PaperTradingEngine.
+
+ Args:
+ decision: The trading decision to execute
+ market_data: Current market data
+
+ Returns:
+ TradeResult with execution details
+ """
+ symbol = decision.symbol
+ action = decision.action
+ requested_quantity = decision.quantity or 0
+
+ # Validate action
+ if isinstance(action, str):
+ try:
+ action = TradeAction(action.lower())
+ except ValueError:
+ return TradeResult(
+ status="rejected",
+ action=TradeAction.HOLD,
+ symbol=symbol,
+ quantity=0,
+ price=market_data.price,
+ reason=f"Invalid action: {action}",
+ )
+
+ # Handle HOLD
+ if action == TradeAction.HOLD:
+ return TradeResult(
+ status="executed",
+ action=TradeAction.HOLD,
+ symbol=symbol,
+ quantity=0,
+ price=market_data.price,
+ reason="Hold - no trade",
+ )
+
+ # Determine execution price (use ask for buys, bid for sells)
+ if action == TradeAction.BUY:
+ execution_price = market_data.ask
+ side = "buy"
+ elif action == TradeAction.SELL:
+ execution_price = market_data.bid
+ side = "sell"
+ elif action == TradeAction.SHORT:
+ execution_price = market_data.bid
+ side = "sell" # Short = sell to open
+ else:
+ return TradeResult(
+ status="rejected",
+ action=action,
+ symbol=symbol,
+ quantity=0,
+ price=market_data.price,
+ reason=f"Unknown action: {action}",
+ )
+
+ # Get current portfolio state
+ portfolio = self.get_portfolio()
+ if not portfolio:
+ return TradeResult(
+ status="rejected",
+ action=action,
+ symbol=symbol,
+ quantity=0,
+ price=execution_price,
+ reason="Portfolio not initialized",
+ )
+
+ # Adjust quantity based on available funds
+ if action == TradeAction.BUY:
+ max_cost = portfolio.balance * 0.9 # 90% max position
+ max_quantity = max_cost / (execution_price * (1 + self.fee_rate))
+ quantity = min(requested_quantity, max_quantity)
+ elif action in (TradeAction.SELL, TradeAction.SHORT):
+ # Check existing position
+ positions = self.get_positions()
+ long_position = next(
+ (p for p in positions if p.symbol == symbol and p.side == "long"),
+ None
+ )
+ if long_position:
+ quantity = min(requested_quantity, long_position.quantity)
+ else:
+ # For short, use margin
+ max_margin = portfolio.balance * 0.9 * 0.3 # 30% margin requirement
+ max_quantity = max_margin / (execution_price * 0.3)
+ quantity = min(requested_quantity, max_quantity)
+ else:
+ quantity = requested_quantity
+
+ if quantity <= 0:
+ return TradeResult(
+ status="rejected",
+ action=action,
+ symbol=symbol,
+ quantity=0,
+ price=execution_price,
+ reason="Insufficient funds or no position",
+ )
+
+ # Place order
+ order = self.place_order(
+ symbol=symbol,
+ side=side,
+ order_type="market",
+ quantity=quantity,
+ price=execution_price,
+ )
+
+ if not order:
+ return TradeResult(
+ status="rejected",
+ action=action,
+ symbol=symbol,
+ quantity=0,
+ price=execution_price,
+ reason="Failed to place order",
+ )
+
+ # Fill order immediately (market order)
+ trade = self.fill_order(order.id, execution_price)
+
+ if not trade:
+ return TradeResult(
+ status="rejected",
+ action=action,
+ symbol=symbol,
+ quantity=0,
+ price=execution_price,
+ reason="Failed to fill order",
+ )
+
+ # Return success result
+ logger.info(
+ f"{self.model_name}: {action.value.upper()} {quantity} {symbol} @ ${execution_price:.2f} "
+ f"(fee: ${trade.fee:.2f}, pnl: ${trade.pnl:+.2f})"
+ )
+
+ return TradeResult(
+ status="executed",
+ action=action,
+ symbol=symbol,
+ quantity=quantity,
+ price=execution_price,
+ cost=quantity * execution_price + trade.fee if action == TradeAction.BUY else None,
+ proceeds=quantity * execution_price - trade.fee if action == TradeAction.SELL else None,
+ pnl=trade.pnl,
+ )
+
+
+# Convenience function to create bridge for a model
+def create_paper_trading_bridge(
+ competition_id: str,
+ model_name: str,
+ initial_capital: float = 10000.0,
+ fee_rate: float = 0.001,
+) -> PaperTradingBridge:
+ """Create a paper trading bridge for a competition model."""
+ return PaperTradingBridge(
+ competition_id=competition_id,
+ model_name=model_name,
+ initial_capital=initial_capital,
+ fee_rate=fee_rate,
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/portfolio_metrics.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/portfolio_metrics.py
new file mode 100644
index 000000000..681ffe306
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/portfolio_metrics.py
@@ -0,0 +1,392 @@
+"""
+Portfolio Metrics for Alpha Arena
+
+Provides advanced portfolio analytics including:
+- Sharpe Ratio
+- Max Drawdown
+- Win Rate
+- Profit Factor
+- Risk-adjusted returns
+"""
+
+import math
+from typing import Dict, List, Optional, Any
+from dataclasses import dataclass, field
+from datetime import datetime
+
+from alpha_arena.types.models import PortfolioState, TradeResult
+from alpha_arena.utils.logging import get_logger
+
+logger = get_logger("portfolio_metrics")
+
+
+@dataclass
+class PortfolioMetrics:
+ """Comprehensive portfolio metrics"""
+
+ # Basic metrics
+ total_return: float = 0.0
+ total_return_pct: float = 0.0
+ total_pnl: float = 0.0
+
+ # Trade statistics
+ total_trades: int = 0
+ winning_trades: int = 0
+ losing_trades: int = 0
+ win_rate: float = 0.0
+
+ # P&L statistics
+ gross_profit: float = 0.0
+ gross_loss: float = 0.0
+ profit_factor: float = 0.0
+ average_win: float = 0.0
+ average_loss: float = 0.0
+ largest_win: float = 0.0
+ largest_loss: float = 0.0
+ expectancy: float = 0.0
+
+ # Risk metrics
+ sharpe_ratio: float = 0.0
+ sortino_ratio: float = 0.0
+ max_drawdown: float = 0.0
+ max_drawdown_pct: float = 0.0
+ current_drawdown: float = 0.0
+ current_drawdown_pct: float = 0.0
+
+ # Volatility
+ daily_volatility: float = 0.0
+ annualized_volatility: float = 0.0
+
+ # Time-based
+ avg_trade_duration: float = 0.0 # seconds
+ time_in_market_pct: float = 0.0
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "total_return": self.total_return,
+ "total_return_pct": self.total_return_pct,
+ "total_pnl": self.total_pnl,
+ "total_trades": self.total_trades,
+ "winning_trades": self.winning_trades,
+ "losing_trades": self.losing_trades,
+ "win_rate": self.win_rate,
+ "gross_profit": self.gross_profit,
+ "gross_loss": self.gross_loss,
+ "profit_factor": self.profit_factor,
+ "average_win": self.average_win,
+ "average_loss": self.average_loss,
+ "largest_win": self.largest_win,
+ "largest_loss": self.largest_loss,
+ "expectancy": self.expectancy,
+ "sharpe_ratio": self.sharpe_ratio,
+ "sortino_ratio": self.sortino_ratio,
+ "max_drawdown": self.max_drawdown,
+ "max_drawdown_pct": self.max_drawdown_pct,
+ "current_drawdown": self.current_drawdown,
+ "current_drawdown_pct": self.current_drawdown_pct,
+ "daily_volatility": self.daily_volatility,
+ "annualized_volatility": self.annualized_volatility,
+ }
+
+ def to_prompt_context(self) -> str:
+ """Convert to text for LLM context"""
+ lines = [
+ "PORTFOLIO PERFORMANCE:",
+ f" Total Return: ${self.total_return:+,.2f} ({self.total_return_pct:+.2f}%)",
+ f" Sharpe Ratio: {self.sharpe_ratio:.2f}",
+ f" Max Drawdown: {self.max_drawdown_pct:.2f}%",
+ f" Win Rate: {self.win_rate:.1f}% ({self.winning_trades}W / {self.losing_trades}L)",
+ f" Profit Factor: {self.profit_factor:.2f}",
+ f" Expectancy: ${self.expectancy:+,.2f}",
+ ]
+ return "\n".join(lines)
+
+ def get_risk_assessment(self) -> str:
+ """Get risk assessment based on metrics"""
+ if self.sharpe_ratio >= 2.0 and self.max_drawdown_pct < 10:
+ return "excellent"
+ elif self.sharpe_ratio >= 1.0 and self.max_drawdown_pct < 20:
+ return "good"
+ elif self.sharpe_ratio >= 0.5 and self.max_drawdown_pct < 30:
+ return "moderate"
+ elif self.sharpe_ratio >= 0 and self.max_drawdown_pct < 50:
+ return "risky"
+ else:
+ return "very_risky"
+
+
+class PortfolioAnalyzer:
+ """
+ Analyzes portfolio performance and calculates metrics.
+
+ Tracks:
+ - Portfolio value history for drawdown/volatility
+ - Trade history for win rate/profit factor
+ - Returns for Sharpe/Sortino ratios
+ """
+
+ def __init__(self, initial_capital: float = 10000.0, risk_free_rate: float = 0.05):
+ self.initial_capital = initial_capital
+ self.risk_free_rate = risk_free_rate # Annual risk-free rate
+
+ # History tracking
+ self._portfolio_values: List[float] = [initial_capital]
+ self._returns: List[float] = []
+ self._trades: List[Dict[str, Any]] = []
+ self._peak_value: float = initial_capital
+ self._timestamps: List[datetime] = [datetime.now()]
+
+ def record_value(self, value: float, timestamp: Optional[datetime] = None):
+ """Record a portfolio value snapshot"""
+ ts = timestamp or datetime.now()
+
+ if self._portfolio_values:
+ prev_value = self._portfolio_values[-1]
+ if prev_value > 0:
+ ret = (value - prev_value) / prev_value
+ self._returns.append(ret)
+
+ self._portfolio_values.append(value)
+ self._timestamps.append(ts)
+
+ # Update peak for drawdown
+ if value > self._peak_value:
+ self._peak_value = value
+
+ def record_trade(
+ self,
+ pnl: float,
+ entry_price: float,
+ exit_price: float,
+ quantity: float,
+ side: str,
+ entry_time: Optional[datetime] = None,
+ exit_time: Optional[datetime] = None,
+ ):
+ """Record a completed trade"""
+ self._trades.append({
+ "pnl": pnl,
+ "entry_price": entry_price,
+ "exit_price": exit_price,
+ "quantity": quantity,
+ "side": side,
+ "entry_time": entry_time or datetime.now(),
+ "exit_time": exit_time or datetime.now(),
+ })
+
+ def calculate_metrics(self) -> PortfolioMetrics:
+ """Calculate all portfolio metrics"""
+ metrics = PortfolioMetrics()
+
+ if not self._portfolio_values:
+ return metrics
+
+ current_value = self._portfolio_values[-1]
+
+ # Basic returns
+ metrics.total_return = current_value - self.initial_capital
+ metrics.total_return_pct = ((current_value / self.initial_capital) - 1) * 100
+ metrics.total_pnl = metrics.total_return
+
+ # Trade statistics
+ metrics.total_trades = len(self._trades)
+
+ if self._trades:
+ winning = [t for t in self._trades if t["pnl"] > 0]
+ losing = [t for t in self._trades if t["pnl"] < 0]
+
+ metrics.winning_trades = len(winning)
+ metrics.losing_trades = len(losing)
+ metrics.win_rate = (len(winning) / len(self._trades)) * 100 if self._trades else 0
+
+ # P&L statistics
+ metrics.gross_profit = sum(t["pnl"] for t in winning)
+ metrics.gross_loss = abs(sum(t["pnl"] for t in losing))
+ metrics.profit_factor = metrics.gross_profit / metrics.gross_loss if metrics.gross_loss > 0 else float('inf')
+
+ metrics.average_win = metrics.gross_profit / len(winning) if winning else 0
+ metrics.average_loss = metrics.gross_loss / len(losing) if losing else 0
+
+ metrics.largest_win = max((t["pnl"] for t in winning), default=0)
+ metrics.largest_loss = abs(min((t["pnl"] for t in losing), default=0))
+
+ # Expectancy = (Win% * Avg Win) - (Loss% * Avg Loss)
+ win_pct = metrics.win_rate / 100
+ loss_pct = 1 - win_pct
+ metrics.expectancy = (win_pct * metrics.average_win) - (loss_pct * metrics.average_loss)
+
+ # Volatility and risk metrics
+ if len(self._returns) >= 2:
+ metrics.daily_volatility = self._calculate_std(self._returns)
+ metrics.annualized_volatility = metrics.daily_volatility * math.sqrt(252)
+
+ # Sharpe Ratio
+ metrics.sharpe_ratio = self._calculate_sharpe_ratio()
+
+ # Sortino Ratio
+ metrics.sortino_ratio = self._calculate_sortino_ratio()
+
+ # Drawdown
+ dd, dd_pct = self._calculate_max_drawdown()
+ metrics.max_drawdown = dd
+ metrics.max_drawdown_pct = dd_pct
+
+ # Current drawdown
+ if self._peak_value > 0:
+ metrics.current_drawdown = self._peak_value - current_value
+ metrics.current_drawdown_pct = (metrics.current_drawdown / self._peak_value) * 100
+
+ return metrics
+
+ def _calculate_std(self, values: List[float]) -> float:
+ """Calculate standard deviation"""
+ if len(values) < 2:
+ return 0.0
+
+ mean = sum(values) / len(values)
+ variance = sum((x - mean) ** 2 for x in values) / (len(values) - 1)
+ return math.sqrt(variance)
+
+ def _calculate_sharpe_ratio(self) -> float:
+ """
+ Calculate Sharpe Ratio.
+
+ Sharpe = (Portfolio Return - Risk-Free Rate) / Portfolio Volatility
+ """
+ if len(self._returns) < 2:
+ return 0.0
+
+ # Annualized return
+ total_return = (self._portfolio_values[-1] / self.initial_capital) - 1
+ periods = len(self._returns)
+ annualized_return = ((1 + total_return) ** (252 / periods)) - 1 if periods > 0 else 0
+
+ # Daily risk-free rate
+ daily_rf = self.risk_free_rate / 252
+
+ # Excess returns
+ excess_returns = [r - daily_rf for r in self._returns]
+
+ # Average excess return (annualized)
+ avg_excess = sum(excess_returns) / len(excess_returns) if excess_returns else 0
+ avg_excess_annual = avg_excess * 252
+
+ # Volatility (annualized)
+ volatility = self._calculate_std(self._returns) * math.sqrt(252)
+
+ if volatility == 0:
+ return 0.0
+
+ return avg_excess_annual / volatility
+
+ def _calculate_sortino_ratio(self) -> float:
+ """
+ Calculate Sortino Ratio.
+
+ Similar to Sharpe but only uses downside volatility.
+ """
+ if len(self._returns) < 2:
+ return 0.0
+
+ daily_rf = self.risk_free_rate / 252
+
+ # Downside returns only (negative returns)
+ downside_returns = [r for r in self._returns if r < daily_rf]
+
+ if not downside_returns:
+ return float('inf') # No downside = infinite Sortino
+
+ # Downside deviation
+ downside_deviation = self._calculate_std(downside_returns) * math.sqrt(252)
+
+ if downside_deviation == 0:
+ return float('inf')
+
+ # Average excess return (annualized)
+ avg_return = sum(self._returns) / len(self._returns) * 252
+ excess_return = avg_return - self.risk_free_rate
+
+ return excess_return / downside_deviation
+
+ def _calculate_max_drawdown(self) -> tuple[float, float]:
+ """Calculate maximum drawdown in absolute and percentage terms"""
+ if len(self._portfolio_values) < 2:
+ return 0.0, 0.0
+
+ max_dd = 0.0
+ max_dd_pct = 0.0
+ peak = self._portfolio_values[0]
+
+ for value in self._portfolio_values:
+ if value > peak:
+ peak = value
+
+ dd = peak - value
+ dd_pct = (dd / peak) * 100 if peak > 0 else 0
+
+ if dd > max_dd:
+ max_dd = dd
+ max_dd_pct = dd_pct
+
+ return max_dd, max_dd_pct
+
+ def get_equity_curve(self) -> List[Dict[str, Any]]:
+ """Get equity curve data for charting"""
+ return [
+ {
+ "timestamp": ts.isoformat(),
+ "value": val,
+ "return_pct": ((val / self.initial_capital) - 1) * 100,
+ }
+ for ts, val in zip(self._timestamps, self._portfolio_values)
+ ]
+
+ def get_drawdown_curve(self) -> List[Dict[str, Any]]:
+ """Get drawdown curve data for charting"""
+ curve = []
+ peak = self._portfolio_values[0] if self._portfolio_values else 0
+
+ for ts, val in zip(self._timestamps, self._portfolio_values):
+ if val > peak:
+ peak = val
+
+ dd_pct = ((peak - val) / peak) * 100 if peak > 0 else 0
+ curve.append({
+ "timestamp": ts.isoformat(),
+ "drawdown_pct": dd_pct,
+ })
+
+ return curve
+
+ def reset(self, initial_capital: Optional[float] = None):
+ """Reset the analyzer"""
+ if initial_capital:
+ self.initial_capital = initial_capital
+
+ self._portfolio_values = [self.initial_capital]
+ self._returns = []
+ self._trades = []
+ self._peak_value = self.initial_capital
+ self._timestamps = [datetime.now()]
+
+
+# Per-model analyzers registry
+_analyzers: Dict[str, PortfolioAnalyzer] = {}
+
+
+def get_analyzer(model_name: str, initial_capital: float = 10000.0) -> PortfolioAnalyzer:
+ """Get or create a portfolio analyzer for a model"""
+ if model_name not in _analyzers:
+ _analyzers[model_name] = PortfolioAnalyzer(initial_capital=initial_capital)
+ return _analyzers[model_name]
+
+
+def reset_analyzer(model_name: str):
+ """Reset a model's analyzer"""
+ if model_name in _analyzers:
+ del _analyzers[model_name]
+
+
+def reset_all_analyzers():
+ """Reset all analyzers"""
+ _analyzers.clear()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/research_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/research_agent.py
new file mode 100644
index 000000000..e6c38ae12
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/research_agent.py
@@ -0,0 +1,427 @@
+"""
+Research Agent for Alpha Arena
+
+Provides research capabilities using:
+- SEC filings via edgar_tools.py
+- News analysis
+- Company fundamentals
+
+This agent doesn't trade but provides research context to trading agents.
+"""
+
+import sys
+from pathlib import Path
+from typing import Dict, List, Optional, Any, AsyncGenerator
+from dataclasses import dataclass, field
+from datetime import datetime
+
+# Add scripts directory to path for imports
+scripts_dir = Path(__file__).parent.parent.parent
+if str(scripts_dir) not in sys.path:
+ sys.path.insert(0, str(scripts_dir))
+
+from alpha_arena.core.base_agent import BaseAgent
+from alpha_arena.types.responses import StreamResponse, NotifyResponse
+from alpha_arena.utils.logging import get_logger
+
+logger = get_logger("research_agent")
+
+
+@dataclass
+class CompanyInfo:
+ """Company information from SEC"""
+ cik: str
+ name: str
+ ticker: Optional[str] = None
+ sic: Optional[str] = None
+ industry: Optional[str] = None
+ fiscal_year_end: Optional[str] = None
+ state: Optional[str] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "cik": self.cik,
+ "name": self.name,
+ "ticker": self.ticker,
+ "sic": self.sic,
+ "industry": self.industry,
+ "fiscal_year_end": self.fiscal_year_end,
+ "state": self.state,
+ }
+
+
+@dataclass
+class FilingSummary:
+ """Summary of an SEC filing"""
+ accession_number: str
+ form_type: str
+ filing_date: str
+ description: Optional[str] = None
+ primary_document: Optional[str] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "accession_number": self.accession_number,
+ "form_type": self.form_type,
+ "filing_date": self.filing_date,
+ "description": self.description,
+ "primary_document": self.primary_document,
+ }
+
+
+@dataclass
+class FinancialData:
+ """Financial data from SEC filings"""
+ period: str
+ revenue: Optional[float] = None
+ net_income: Optional[float] = None
+ total_assets: Optional[float] = None
+ total_liabilities: Optional[float] = None
+ total_equity: Optional[float] = None
+ eps: Optional[float] = None
+ cash_flow_operations: Optional[float] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "period": self.period,
+ "revenue": self.revenue,
+ "net_income": self.net_income,
+ "total_assets": self.total_assets,
+ "total_liabilities": self.total_liabilities,
+ "total_equity": self.total_equity,
+ "eps": self.eps,
+ "cash_flow_operations": self.cash_flow_operations,
+ }
+
+ def to_prompt_context(self) -> str:
+ """Format for LLM context"""
+ lines = [f"Financial Data ({self.period}):"]
+ if self.revenue:
+ lines.append(f" Revenue: ${self.revenue:,.0f}")
+ if self.net_income:
+ lines.append(f" Net Income: ${self.net_income:,.0f}")
+ if self.total_assets:
+ lines.append(f" Total Assets: ${self.total_assets:,.0f}")
+ if self.eps:
+ lines.append(f" EPS: ${self.eps:.2f}")
+ return "\n".join(lines)
+
+
+@dataclass
+class ResearchReport:
+ """A comprehensive research report"""
+ symbol: str
+ generated_at: datetime = field(default_factory=datetime.now)
+ company_info: Optional[CompanyInfo] = None
+ recent_filings: List[FilingSummary] = field(default_factory=list)
+ financials: List[FinancialData] = field(default_factory=list)
+ insider_activity: List[Dict[str, Any]] = field(default_factory=list)
+ summary: str = ""
+ risk_factors: List[str] = field(default_factory=list)
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "symbol": self.symbol,
+ "generated_at": self.generated_at.isoformat(),
+ "company_info": self.company_info.to_dict() if self.company_info else None,
+ "recent_filings": [f.to_dict() for f in self.recent_filings],
+ "financials": [f.to_dict() for f in self.financials],
+ "insider_activity": self.insider_activity,
+ "summary": self.summary,
+ "risk_factors": self.risk_factors,
+ }
+
+ def to_prompt_context(self) -> str:
+ """Format entire report for LLM context"""
+ lines = [f"RESEARCH REPORT: {self.symbol}"]
+ lines.append(f"Generated: {self.generated_at.strftime('%Y-%m-%d %H:%M')}")
+ lines.append("")
+
+ if self.company_info:
+ lines.append(f"Company: {self.company_info.name}")
+ if self.company_info.industry:
+ lines.append(f"Industry: {self.company_info.industry}")
+ lines.append("")
+
+ if self.financials:
+ lines.append("FINANCIALS:")
+ for fin in self.financials[:2]: # Last 2 periods
+ lines.append(fin.to_prompt_context())
+ lines.append("")
+
+ if self.recent_filings:
+ lines.append(f"RECENT FILINGS ({len(self.recent_filings)}):")
+ for filing in self.recent_filings[:5]:
+ lines.append(f" - {filing.form_type} ({filing.filing_date})")
+ lines.append("")
+
+ if self.insider_activity:
+ lines.append(f"INSIDER ACTIVITY: {len(self.insider_activity)} transactions")
+ lines.append("")
+
+ if self.risk_factors:
+ lines.append("KEY RISKS:")
+ for risk in self.risk_factors[:3]:
+ lines.append(f" - {risk[:100]}")
+ lines.append("")
+
+ if self.summary:
+ lines.append("SUMMARY:")
+ lines.append(self.summary)
+
+ return "\n".join(lines)
+
+
+class ResearchAgent(BaseAgent):
+ """
+ Research Agent for gathering and analyzing company information.
+
+ Uses edgar_tools.py for SEC filings data.
+ """
+
+ def __init__(self, name: str = "ResearchAgent"):
+ super().__init__(name)
+ self._edgar_available = False
+ self._cache: Dict[str, ResearchReport] = {}
+ self._cache_ttl = 3600 # 1 hour cache
+
+ async def initialize(self) -> bool:
+ """Initialize the research agent"""
+ try:
+ # Check if edgar_tools is available
+ import edgar_tools
+ self._edgar_available = True
+ logger.info("Edgar tools available for research")
+ except ImportError:
+ logger.warning("Edgar tools not available - research capabilities limited")
+ self._edgar_available = False
+
+ self._initialized = True
+ return True
+
+ async def stream(
+ self,
+ query: str,
+ competition_id: str,
+ cycle_number: int,
+ dependencies: Optional[Dict] = None,
+ ) -> AsyncGenerator[StreamResponse, None]:
+ """Stream research results"""
+ yield StreamResponse(content="Research agent stream not implemented", event="info")
+
+ async def get_company_info(self, ticker: str) -> Optional[CompanyInfo]:
+ """Get company information from SEC"""
+ if not self._edgar_available:
+ return None
+
+ try:
+ import edgar_tools
+ import json
+
+ # Call edgar_tools
+ result = edgar_tools.main(["company_info", ticker])
+ data = json.loads(result)
+
+ if data.get("success"):
+ info = data.get("data", {})
+ return CompanyInfo(
+ cik=info.get("cik", ""),
+ name=info.get("name", ""),
+ ticker=info.get("tickers", [ticker])[0] if info.get("tickers") else ticker,
+ sic=info.get("sic"),
+ industry=info.get("sic_description"),
+ fiscal_year_end=info.get("fiscal_year_end"),
+ state=info.get("state_of_incorporation"),
+ )
+ except Exception as e:
+ logger.error(f"Error getting company info: {e}")
+
+ return None
+
+ async def get_recent_filings(
+ self,
+ ticker: str,
+ form_types: Optional[List[str]] = None,
+ limit: int = 10,
+ ) -> List[FilingSummary]:
+ """Get recent SEC filings"""
+ if not self._edgar_available:
+ return []
+
+ try:
+ import edgar_tools
+ import json
+
+ # Call edgar_tools
+ args = ["get_filings", ticker, "--limit", str(limit)]
+ if form_types:
+ args.extend(["--form-type", ",".join(form_types)])
+
+ result = edgar_tools.main(args)
+ data = json.loads(result)
+
+ if data.get("success"):
+ filings = []
+ for f in data.get("data", {}).get("filings", []):
+ filings.append(FilingSummary(
+ accession_number=f.get("accession_number", ""),
+ form_type=f.get("form_type", ""),
+ filing_date=f.get("filing_date", ""),
+ description=f.get("description"),
+ primary_document=f.get("primary_document"),
+ ))
+ return filings
+ except Exception as e:
+ logger.error(f"Error getting filings: {e}")
+
+ return []
+
+ async def get_financials(self, ticker: str) -> List[FinancialData]:
+ """Get financial statements"""
+ if not self._edgar_available:
+ return []
+
+ try:
+ import edgar_tools
+ import json
+
+ # Get income statement
+ result = edgar_tools.main(["income_statement", ticker])
+ data = json.loads(result)
+
+ financials = []
+ if data.get("success"):
+ for period, values in data.get("data", {}).items():
+ if isinstance(values, dict):
+ financials.append(FinancialData(
+ period=period,
+ revenue=values.get("revenue") or values.get("total_revenue"),
+ net_income=values.get("net_income"),
+ eps=values.get("eps") or values.get("basic_eps"),
+ ))
+
+ return financials[:4] # Return last 4 periods
+ except Exception as e:
+ logger.error(f"Error getting financials: {e}")
+
+ return []
+
+ async def get_insider_transactions(self, ticker: str, limit: int = 10) -> List[Dict[str, Any]]:
+ """Get insider transactions"""
+ if not self._edgar_available:
+ return []
+
+ try:
+ import edgar_tools
+ import json
+
+ result = edgar_tools.main(["insider_transactions", ticker, "--limit", str(limit)])
+ data = json.loads(result)
+
+ if data.get("success"):
+ return data.get("data", {}).get("transactions", [])
+ except Exception as e:
+ logger.error(f"Error getting insider transactions: {e}")
+
+ return []
+
+ async def generate_report(self, ticker: str, use_cache: bool = True) -> ResearchReport:
+ """
+ Generate a comprehensive research report for a ticker.
+
+ Args:
+ ticker: Stock ticker symbol
+ use_cache: Whether to use cached report if available
+
+ Returns:
+ ResearchReport with all available data
+ """
+ # Check cache
+ if use_cache and ticker in self._cache:
+ cached = self._cache[ticker]
+ age = (datetime.now() - cached.generated_at).total_seconds()
+ if age < self._cache_ttl:
+ logger.info(f"Using cached research report for {ticker}")
+ return cached
+
+ logger.info(f"Generating research report for {ticker}")
+
+ report = ResearchReport(symbol=ticker)
+
+ # Gather data concurrently
+ company_info = await self.get_company_info(ticker)
+ if company_info:
+ report.company_info = company_info
+
+ filings = await self.get_recent_filings(ticker, limit=10)
+ report.recent_filings = filings
+
+ financials = await self.get_financials(ticker)
+ report.financials = financials
+
+ insider = await self.get_insider_transactions(ticker, limit=10)
+ report.insider_activity = insider
+
+ # Generate summary
+ report.summary = self._generate_summary(report)
+
+ # Cache the report
+ self._cache[ticker] = report
+
+ return report
+
+ def _generate_summary(self, report: ResearchReport) -> str:
+ """Generate a brief summary of the research"""
+ parts = []
+
+ if report.company_info:
+ parts.append(f"{report.company_info.name}")
+ if report.company_info.industry:
+ parts.append(f"operates in {report.company_info.industry}")
+
+ if report.financials:
+ latest = report.financials[0]
+ if latest.revenue:
+ parts.append(f"Revenue: ${latest.revenue:,.0f}")
+ if latest.net_income:
+ profit_status = "profitable" if latest.net_income > 0 else "reporting losses"
+ parts.append(f"Currently {profit_status}")
+
+ if report.recent_filings:
+ parts.append(f"{len(report.recent_filings)} recent SEC filings")
+
+ if report.insider_activity:
+ parts.append(f"{len(report.insider_activity)} insider transactions")
+
+ return ". ".join(parts) + "." if parts else "Limited data available."
+
+ def clear_cache(self, ticker: Optional[str] = None):
+ """Clear research cache"""
+ if ticker:
+ self._cache.pop(ticker, None)
+ else:
+ self._cache.clear()
+
+
+# Singleton instance
+_research_agent: Optional[ResearchAgent] = None
+
+
+async def get_research_agent() -> ResearchAgent:
+ """Get the research agent singleton"""
+ global _research_agent
+ if _research_agent is None:
+ _research_agent = ResearchAgent()
+ await _research_agent.initialize()
+ return _research_agent
+
+
+async def get_research_context(ticker: str) -> str:
+ """
+ Get research context for a ticker.
+
+ Convenience function for adding research to trading prompts.
+ """
+ agent = await get_research_agent()
+ report = await agent.generate_report(ticker)
+ return report.to_prompt_context()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/sentiment_agent.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/sentiment_agent.py
new file mode 100644
index 000000000..7d84e51b4
--- /dev/null
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/core/sentiment_agent.py
@@ -0,0 +1,411 @@
+"""
+Sentiment Analysis Agent for Alpha Arena
+
+Integrates with existing news fetching tools to provide
+sentiment analysis for trading decisions.
+"""
+
+import sys
+from pathlib import Path
+from typing import Dict, List, Optional, Any, AsyncGenerator
+from dataclasses import dataclass, field
+from datetime import datetime
+from enum import Enum
+
+# Add scripts directory to path for imports
+scripts_dir = Path(__file__).parent.parent.parent
+if str(scripts_dir) not in sys.path:
+ sys.path.insert(0, str(scripts_dir))
+
+from alpha_arena.core.base_agent import BaseAgent
+from alpha_arena.types.responses import StreamResponse
+from alpha_arena.utils.logging import get_logger
+
+logger = get_logger("sentiment_agent")
+
+
+class SentimentLevel(str, Enum):
+ """Sentiment classification levels."""
+ VERY_BEARISH = "very_bearish"
+ BEARISH = "bearish"
+ NEUTRAL = "neutral"
+ BULLISH = "bullish"
+ VERY_BULLISH = "very_bullish"
+
+
+@dataclass
+class NewsArticle:
+ """Represents a news article."""
+ title: str
+ description: str
+ url: str
+ publisher: str
+ published_date: str
+ sentiment_score: float = 0.0
+ sentiment_label: str = "neutral"
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "title": self.title,
+ "description": self.description,
+ "url": self.url,
+ "publisher": self.publisher,
+ "published_date": self.published_date,
+ "sentiment_score": self.sentiment_score,
+ "sentiment_label": self.sentiment_label,
+ }
+
+
+@dataclass
+class SentimentResult:
+ """Result of sentiment analysis."""
+ symbol: str
+ timestamp: datetime = field(default_factory=datetime.now)
+ articles_analyzed: int = 0
+ overall_sentiment: SentimentLevel = SentimentLevel.NEUTRAL
+ sentiment_score: float = 0.0 # -1.0 (bearish) to 1.0 (bullish)
+ confidence: float = 0.0
+ bullish_count: int = 0
+ bearish_count: int = 0
+ neutral_count: int = 0
+ key_headlines: List[str] = field(default_factory=list)
+ sources: List[str] = field(default_factory=list)
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {
+ "symbol": self.symbol,
+ "timestamp": self.timestamp.isoformat(),
+ "articles_analyzed": self.articles_analyzed,
+ "overall_sentiment": self.overall_sentiment.value,
+ "sentiment_score": self.sentiment_score,
+ "confidence": self.confidence,
+ "bullish_count": self.bullish_count,
+ "bearish_count": self.bearish_count,
+ "neutral_count": self.neutral_count,
+ "key_headlines": self.key_headlines,
+ "sources": self.sources,
+ }
+
+ def to_prompt_context(self) -> str:
+ """Format for LLM context."""
+ lines = [f"SENTIMENT ANALYSIS: {self.symbol}"]
+ lines.append(f"Overall: {self.overall_sentiment.value} (score: {self.sentiment_score:.2f})")
+ lines.append(f"Confidence: {self.confidence:.0%}")
+ lines.append(f"Articles: {self.articles_analyzed} ({self.bullish_count} bullish, {self.bearish_count} bearish, {self.neutral_count} neutral)")
+
+ if self.key_headlines:
+ lines.append("\nKey Headlines:")
+ for headline in self.key_headlines[:3]:
+ lines.append(f" - {headline[:100]}")
+
+ return "\n".join(lines)
+
+
+class SentimentAgent(BaseAgent):
+ """
+ Sentiment Analysis Agent using news and NLP.
+
+ Integrates with existing fetch_company_news.py for news data.
+ """
+
+ def __init__(self, name: str = "SentimentAgent"):
+ super().__init__(name)
+ self._news_available = False
+ self._cache: Dict[str, SentimentResult] = {}
+ self._cache_ttl = 1800 # 30 minutes
+
+ # Sentiment word lists for basic analysis
+ self._bullish_words = {
+ 'surge', 'soar', 'rally', 'gains', 'growth', 'profit', 'rise', 'high',
+ 'bullish', 'positive', 'up', 'gain', 'beat', 'exceeds', 'strong',
+ 'record', 'upgrade', 'buy', 'optimistic', 'opportunity', 'breakout',
+ 'momentum', 'breakthrough', 'outperform', 'boom', 'upside'
+ }
+ self._bearish_words = {
+ 'plunge', 'crash', 'fall', 'drop', 'loss', 'decline', 'slump', 'low',
+ 'bearish', 'negative', 'down', 'miss', 'below', 'weak', 'cut',
+ 'downgrade', 'sell', 'pessimistic', 'risk', 'warning', 'concern',
+ 'fear', 'underperform', 'recession', 'downside', 'tumble'
+ }
+
+ async def initialize(self) -> bool:
+ """Initialize the sentiment agent."""
+ try:
+ # Check if gnews is available
+ import gnews
+ self._news_available = True
+ logger.info("GNews available for sentiment analysis")
+ except ImportError:
+ logger.warning("GNews not available - using limited sentiment analysis")
+ self._news_available = False
+
+ self._initialized = True
+ return True
+
+ async def stream(
+ self,
+ query: str,
+ competition_id: str,
+ cycle_number: int,
+ dependencies: Optional[Dict] = None,
+ ) -> AsyncGenerator[StreamResponse, None]:
+ """Stream sentiment analysis results."""
+ yield StreamResponse(content="Sentiment agent stream not implemented", event="info")
+
+ def _analyze_text_sentiment(self, text: str) -> tuple[float, str]:
+ """
+ Analyze sentiment of text using word matching.
+
+ Returns:
+ Tuple of (score, label)
+ Score ranges from -1.0 (very bearish) to 1.0 (very bullish)
+ """
+ if not text:
+ return 0.0, "neutral"
+
+ text_lower = text.lower()
+ words = set(text_lower.split())
+
+ bullish_matches = len(words & self._bullish_words)
+ bearish_matches = len(words & self._bearish_words)
+
+ total_matches = bullish_matches + bearish_matches
+ if total_matches == 0:
+ return 0.0, "neutral"
+
+ # Calculate score
+ score = (bullish_matches - bearish_matches) / max(total_matches, 1)
+ score = max(-1.0, min(1.0, score))
+
+ # Determine label
+ if score > 0.5:
+ label = "very_bullish"
+ elif score > 0.15:
+ label = "bullish"
+ elif score < -0.5:
+ label = "very_bearish"
+ elif score < -0.15:
+ label = "bearish"
+ else:
+ label = "neutral"
+
+ return score, label
+
+ async def fetch_news(
+ self,
+ query: str,
+ max_results: int = 10,
+ period: str = "7d",
+ ) -> List[NewsArticle]:
+ """
+ Fetch news articles for analysis.
+
+ Args:
+ query: Search query (symbol, company name)
+ max_results: Maximum articles to fetch
+ period: Time period (7d, 1M, etc.)
+
+ Returns:
+ List of NewsArticle objects
+ """
+ if not self._news_available:
+ return []
+
+ try:
+ import json
+ # Import and use existing fetch_company_news
+ sys.path.insert(0, str(scripts_dir))
+ from fetch_company_news import fetch_company_news
+
+ result = fetch_company_news(query, max_results, period)
+ data = json.loads(result)
+
+ if not data.get("success"):
+ logger.warning(f"News fetch failed: {data.get('error')}")
+ return []
+
+ articles = []
+ for article_data in data.get("data", []):
+ # Analyze sentiment for each article
+ title = article_data.get("title", "")
+ desc = article_data.get("description", "")
+ combined_text = f"{title} {desc}"
+
+ score, label = self._analyze_text_sentiment(combined_text)
+
+ articles.append(NewsArticle(
+ title=title,
+ description=desc,
+ url=article_data.get("url", ""),
+ publisher=article_data.get("publisher", "Unknown"),
+ published_date=article_data.get("published_date", ""),
+ sentiment_score=score,
+ sentiment_label=label,
+ ))
+
+ return articles
+
+ except Exception as e:
+ logger.error(f"Error fetching news: {e}")
+ return []
+
+ async def analyze_sentiment(
+ self,
+ symbol: str,
+ use_cache: bool = True,
+ max_articles: int = 15,
+ ) -> SentimentResult:
+ """
+ Analyze market sentiment for a symbol.
+
+ Args:
+ symbol: Trading symbol (e.g., "AAPL", "BTC")
+ use_cache: Whether to use cached result
+ max_articles: Maximum articles to analyze
+
+ Returns:
+ SentimentResult with analysis
+ """
+ # Check cache
+ if use_cache and symbol in self._cache:
+ cached = self._cache[symbol]
+ age = (datetime.now() - cached.timestamp).total_seconds()
+ if age < self._cache_ttl:
+ logger.info(f"Using cached sentiment for {symbol}")
+ return cached
+
+ logger.info(f"Analyzing sentiment for {symbol}")
+
+ # Fetch and analyze news
+ articles = await self.fetch_news(symbol, max_results=max_articles)
+
+ if not articles:
+ # Return neutral result if no articles
+ result = SentimentResult(
+ symbol=symbol,
+ confidence=0.0,
+ )
+ return result
+
+ # Aggregate sentiment
+ total_score = 0.0
+ bullish = 0
+ bearish = 0
+ neutral = 0
+ headlines = []
+ sources = set()
+
+ for article in articles:
+ total_score += article.sentiment_score
+
+ if article.sentiment_label in ["bullish", "very_bullish"]:
+ bullish += 1
+ elif article.sentiment_label in ["bearish", "very_bearish"]:
+ bearish += 1
+ else:
+ neutral += 1
+
+ headlines.append(article.title)
+ sources.add(article.publisher)
+
+ # Calculate overall sentiment
+ avg_score = total_score / len(articles) if articles else 0.0
+
+ # Determine overall sentiment level
+ if avg_score > 0.4:
+ overall = SentimentLevel.VERY_BULLISH
+ elif avg_score > 0.15:
+ overall = SentimentLevel.BULLISH
+ elif avg_score < -0.4:
+ overall = SentimentLevel.VERY_BEARISH
+ elif avg_score < -0.15:
+ overall = SentimentLevel.BEARISH
+ else:
+ overall = SentimentLevel.NEUTRAL
+
+ # Calculate confidence based on agreement
+ max_count = max(bullish, bearish, neutral)
+ confidence = max_count / len(articles) if articles else 0.0
+
+ result = SentimentResult(
+ symbol=symbol,
+ articles_analyzed=len(articles),
+ overall_sentiment=overall,
+ sentiment_score=avg_score,
+ confidence=confidence,
+ bullish_count=bullish,
+ bearish_count=bearish,
+ neutral_count=neutral,
+ key_headlines=headlines[:5],
+ sources=list(sources),
+ )
+
+ # Cache result
+ self._cache[symbol] = result
+
+ return result
+
+ async def get_market_mood(self, symbols: List[str]) -> Dict[str, Any]:
+ """
+ Get overall market mood from multiple symbols.
+
+ Args:
+ symbols: List of symbols to analyze
+
+ Returns:
+ Aggregated market mood
+ """
+ results = {}
+ total_score = 0.0
+
+ for symbol in symbols:
+ sentiment = await self.analyze_sentiment(symbol)
+ results[symbol] = sentiment.to_dict()
+ total_score += sentiment.sentiment_score
+
+ avg_score = total_score / len(symbols) if symbols else 0.0
+
+ if avg_score > 0.3:
+ overall_mood = "risk_on"
+ elif avg_score < -0.3:
+ overall_mood = "risk_off"
+ else:
+ overall_mood = "mixed"
+
+ return {
+ "symbols_analyzed": len(symbols),
+ "overall_mood": overall_mood,
+ "average_sentiment": avg_score,
+ "individual_sentiments": results,
+ }
+
+ def clear_cache(self, symbol: Optional[str] = None):
+ """Clear sentiment cache."""
+ if symbol:
+ self._cache.pop(symbol, None)
+ else:
+ self._cache.clear()
+
+
+# Singleton instance
+_sentiment_agent: Optional[SentimentAgent] = None
+
+
+async def get_sentiment_agent() -> SentimentAgent:
+ """Get the sentiment agent singleton."""
+ global _sentiment_agent
+ if _sentiment_agent is None:
+ _sentiment_agent = SentimentAgent()
+ await _sentiment_agent.initialize()
+ return _sentiment_agent
+
+
+async def get_sentiment_context(symbol: str) -> str:
+ """
+ Get sentiment context for a symbol.
+
+ Convenience function for adding sentiment to trading prompts.
+ """
+ agent = await get_sentiment_agent()
+ result = await agent.analyze_sentiment(symbol)
+ return result.to_prompt_context()
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/main.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/main.py
index b8eb5563d..92cab99b6 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/main.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/main.py
@@ -112,6 +112,84 @@ async def handle_action(action: str, params: Dict, api_keys: Dict) -> Dict[str,
elif action == "system_info":
return get_system_info()
+ # HITL (Human-in-the-Loop) actions
+ elif action == "check_approval":
+ return await check_approval_handler(params)
+
+ elif action == "approve_decision":
+ return await approve_decision_handler(params)
+
+ elif action == "reject_decision":
+ return await reject_decision_handler(params)
+
+ elif action == "get_pending_approvals":
+ return await get_pending_approvals_handler(params)
+
+ elif action == "get_hitl_status":
+ return await get_hitl_status_handler(params)
+
+ elif action == "update_hitl_rule":
+ return await update_hitl_rule_handler(params)
+
+ # Portfolio metrics actions
+ elif action == "get_portfolio_metrics":
+ return await get_portfolio_metrics_handler(params)
+
+ elif action == "get_equity_curve":
+ return await get_equity_curve_handler(params)
+
+ # Grid strategy actions
+ elif action == "create_grid_agent":
+ return await create_grid_agent_handler(params)
+
+ elif action == "get_grid_status":
+ return await get_grid_status_handler(params)
+
+ # Research actions
+ elif action == "get_research":
+ return await get_research_handler(params)
+
+ elif action == "get_sec_filings":
+ return await get_sec_filings_handler(params)
+
+ # Features actions
+ elif action == "get_features":
+ return await get_features_handler(params)
+
+ # Trading styles actions
+ elif action == "list_trading_styles":
+ return await list_trading_styles_handler(params)
+
+ elif action == "create_styled_agents":
+ return await create_styled_agents_handler(params)
+
+ # Broker actions
+ elif action == "list_brokers":
+ return await list_brokers_handler(params)
+
+ elif action == "get_broker":
+ return await get_broker_handler(params)
+
+ elif action == "get_broker_ticker":
+ return await get_broker_ticker_handler(params)
+
+ # Sentiment actions
+ elif action == "get_sentiment":
+ return await get_sentiment_handler(params)
+
+ elif action == "get_market_mood":
+ return await get_market_mood_handler(params)
+
+ # Memory actions
+ elif action == "get_agent_context":
+ return await get_agent_context_handler(params)
+
+ elif action == "get_agent_memory_summary":
+ return await get_agent_memory_summary_handler(params)
+
+ elif action == "search_agent_memory":
+ return await search_agent_memory_handler(params)
+
else:
return {"success": False, "error": f"Unknown action: {action}"}
@@ -146,9 +224,12 @@ async def create_competition_handler(params: Dict, api_keys: Dict) -> Dict[str,
model_id=model_data.get("model_id") or (card.model_id if card else "gpt-4o-mini"),
api_key=model_data.get("api_key"),
initial_capital=model_data.get("initial_capital", params.get("initial_capital", 10000)),
+ trading_style=model_data.get("trading_style"), # Pass trading style if specified
+ metadata=model_data.get("metadata", {}), # Pass any additional metadata
)
models.append(model)
- logger.info(f"Configured model: {model.name} ({model.provider}/{model.model_id})")
+ style_info = f" [style: {model.trading_style}]" if model.trading_style else ""
+ logger.info(f"Configured model: {model.name} ({model.provider}/{model.model_id}){style_info}")
# Create config
config = CompetitionConfig(
@@ -538,9 +619,16 @@ async def get_agent_handler(params: Dict) -> Dict[str, Any]:
def get_system_info() -> Dict[str, Any]:
"""Get system information."""
+ # Get available trading styles
+ try:
+ from alpha_arena.config.trading_styles import list_trading_styles
+ styles = [s.id for s in list_trading_styles()]
+ except Exception:
+ styles = []
+
return {
"success": True,
- "version": "2.0.0",
+ "version": "2.1.0",
"framework": "alpha_arena",
"features": [
"multi_model_competition",
@@ -551,6 +639,13 @@ def get_system_info() -> Dict[str, Any]:
"evaluation_metrics",
"guardrails",
"database_persistence",
+ "hitl_approval",
+ "portfolio_metrics",
+ "grid_trading",
+ "research_agent",
+ "features_pipeline",
+ "trading_styles", # NEW: Single provider with multiple agent styles
+ "real_time_portfolio_updates", # NEW: Portfolio updates after trades
],
"supported_providers": [
"openai",
@@ -561,10 +656,762 @@ def get_system_info() -> Dict[str, Any]:
"openrouter",
"ollama",
],
+ "trading_styles": styles,
"default_exchange": "kraken",
}
+# =============================================================================
+# HITL (Human-in-the-Loop) Handlers
+# =============================================================================
+
+async def check_approval_handler(params: Dict) -> Dict[str, Any]:
+ """Check if a trading decision requires approval."""
+ try:
+ from alpha_arena.core.hitl import check_decision_approval
+
+ decision_dict = params.get("decision", {})
+ context = params.get("context", {})
+
+ if not decision_dict:
+ return {"success": False, "error": "Missing decision data"}
+
+ result = check_decision_approval(decision_dict, context)
+ return {
+ "success": True,
+ **result,
+ }
+ except Exception as e:
+ logger.exception(f"Error checking approval: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def approve_decision_handler(params: Dict) -> Dict[str, Any]:
+ """Approve a pending decision."""
+ try:
+ from alpha_arena.core.hitl import approve_decision
+
+ request_id = params.get("request_id")
+ approved_by = params.get("approved_by", "user")
+ notes = params.get("notes", "")
+
+ if not request_id:
+ return {"success": False, "error": "Missing request_id"}
+
+ result = approve_decision(request_id, approved_by, notes)
+ return {
+ "success": True,
+ **result,
+ }
+ except Exception as e:
+ logger.exception(f"Error approving decision: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def reject_decision_handler(params: Dict) -> Dict[str, Any]:
+ """Reject a pending decision."""
+ try:
+ from alpha_arena.core.hitl import reject_decision
+
+ request_id = params.get("request_id")
+ rejected_by = params.get("rejected_by", "user")
+ notes = params.get("notes", "")
+
+ if not request_id:
+ return {"success": False, "error": "Missing request_id"}
+
+ result = reject_decision(request_id, rejected_by, notes)
+ return {
+ "success": True,
+ **result,
+ }
+ except Exception as e:
+ logger.exception(f"Error rejecting decision: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def get_pending_approvals_handler(params: Dict) -> Dict[str, Any]:
+ """Get all pending approval requests."""
+ try:
+ from alpha_arena.core.hitl import get_pending_approvals
+
+ pending = get_pending_approvals()
+ return {
+ "success": True,
+ "pending_approvals": pending,
+ "count": len(pending),
+ }
+ except Exception as e:
+ logger.exception(f"Error getting pending approvals: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def get_hitl_status_handler(params: Dict) -> Dict[str, Any]:
+ """Get HITL manager status and configuration."""
+ try:
+ from alpha_arena.core.hitl import get_hitl_manager
+
+ manager = get_hitl_manager()
+ return {
+ "success": True,
+ "status": manager.to_dict(),
+ }
+ except Exception as e:
+ logger.exception(f"Error getting HITL status: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def update_hitl_rule_handler(params: Dict) -> Dict[str, Any]:
+ """Update a HITL rule configuration."""
+ try:
+ from alpha_arena.core.hitl import get_hitl_manager
+
+ rule_name = params.get("rule_name")
+ enabled = params.get("enabled")
+
+ if not rule_name:
+ return {"success": False, "error": "Missing rule_name"}
+
+ if enabled is None:
+ return {"success": False, "error": "Missing enabled flag"}
+
+ manager = get_hitl_manager()
+ manager.set_rule_enabled(rule_name, enabled)
+
+ return {
+ "success": True,
+ "rule_name": rule_name,
+ "enabled": enabled,
+ }
+ except Exception as e:
+ logger.exception(f"Error updating HITL rule: {e}")
+ return {"success": False, "error": str(e)}
+
+
+# =============================================================================
+# Portfolio Metrics Handlers
+# =============================================================================
+
+async def get_portfolio_metrics_handler(params: Dict) -> Dict[str, Any]:
+ """Get portfolio metrics for a competition or model."""
+ try:
+ from alpha_arena.core.portfolio_metrics import get_analyzer
+
+ competition_id = params.get("competition_id")
+ model_name = params.get("model_name")
+
+ if not competition_id:
+ return {"success": False, "error": "Missing competition_id"}
+
+ # Get competition to access portfolio data
+ competition = get_competition(competition_id)
+ if not competition:
+ # Try from database
+ db = get_database()
+ comp_data = db.get_competition(competition_id)
+ if not comp_data:
+ return {"success": False, "error": f"Competition not found: {competition_id}"}
+
+ # Get snapshots from database for metrics calculation
+ snapshots = db.get_snapshots(competition_id, model_name)
+ if not snapshots:
+ return {"success": False, "error": "No portfolio snapshots found"}
+
+ # Calculate metrics from historical snapshots
+ analyzer = get_analyzer()
+ for snapshot in snapshots:
+ analyzer.record(snapshot.get("portfolio_value", 10000))
+
+ metrics = analyzer.calculate_metrics()
+ return {
+ "success": True,
+ "metrics": metrics.to_dict(),
+ "from_database": True,
+ }
+
+ # Get metrics from live competition
+ if model_name:
+ # Get specific model's metrics
+ for agent in competition._agents:
+ if agent.name == model_name:
+ metrics = agent.get_metrics()
+ if metrics:
+ return {
+ "success": True,
+ "model_name": model_name,
+ "metrics": metrics.to_dict(),
+ }
+ break
+ return {"success": False, "error": f"Model not found or no metrics: {model_name}"}
+
+ # Get all models' metrics
+ all_metrics = {}
+ for agent in competition._agents:
+ metrics = agent.get_metrics()
+ if metrics:
+ all_metrics[agent.name] = metrics.to_dict()
+
+ return {
+ "success": True,
+ "metrics": all_metrics,
+ }
+ except Exception as e:
+ logger.exception(f"Error getting portfolio metrics: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def get_equity_curve_handler(params: Dict) -> Dict[str, Any]:
+ """Get equity curve data for charting."""
+ try:
+ from alpha_arena.core.portfolio_metrics import get_analyzer
+
+ competition_id = params.get("competition_id")
+ model_name = params.get("model_name")
+
+ if not competition_id:
+ return {"success": False, "error": "Missing competition_id"}
+
+ # Get from database snapshots
+ db = get_database()
+ snapshots = db.get_snapshots(competition_id, model_name)
+
+ if not snapshots:
+ return {"success": False, "error": "No snapshots found"}
+
+ # Build equity curve data
+ equity_curve = []
+ for snapshot in snapshots:
+ equity_curve.append({
+ "timestamp": snapshot.get("timestamp"),
+ "cycle": snapshot.get("cycle_number"),
+ "value": snapshot.get("portfolio_value"),
+ "model": snapshot.get("model_name"),
+ })
+
+ return {
+ "success": True,
+ "equity_curve": equity_curve,
+ "count": len(equity_curve),
+ }
+ except Exception as e:
+ logger.exception(f"Error getting equity curve: {e}")
+ return {"success": False, "error": str(e)}
+
+
+# =============================================================================
+# Grid Strategy Handlers
+# =============================================================================
+
+async def create_grid_agent_handler(params: Dict) -> Dict[str, Any]:
+ """Create a grid trading agent."""
+ try:
+ from alpha_arena.core.grid_agent import GridStrategyAgent, GridConfig
+
+ name = params.get("name", "GridAgent")
+ symbol = params.get("symbol", "BTC/USD")
+
+ # Grid configuration
+ grid_params = params.get("grid_config", {})
+ config = GridConfig(
+ symbol=symbol,
+ lower_price=grid_params.get("lower_price", 90000),
+ upper_price=grid_params.get("upper_price", 110000),
+ num_grids=grid_params.get("num_grids", 10),
+ quantity_per_grid=grid_params.get("quantity_per_grid", 0.001),
+ take_profit_pct=grid_params.get("take_profit_pct"),
+ stop_loss_pct=grid_params.get("stop_loss_pct"),
+ )
+
+ # Create agent
+ agent = GridStrategyAgent(name=name, grid_config=config)
+ await agent.initialize()
+
+ return {
+ "success": True,
+ "agent_name": name,
+ "grid_config": {
+ "symbol": config.symbol,
+ "lower_price": config.lower_price,
+ "upper_price": config.upper_price,
+ "num_grids": config.num_grids,
+ "quantity_per_grid": config.quantity_per_grid,
+ "grid_spacing": config.grid_spacing,
+ },
+ "grid_levels": agent.state.grid_levels,
+ }
+ except Exception as e:
+ logger.exception(f"Error creating grid agent: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def get_grid_status_handler(params: Dict) -> Dict[str, Any]:
+ """Get grid agent status."""
+ try:
+ competition_id = params.get("competition_id")
+ agent_name = params.get("agent_name")
+
+ if not competition_id:
+ return {"success": False, "error": "Missing competition_id"}
+
+ competition = get_competition(competition_id)
+ if not competition:
+ return {"success": False, "error": f"Competition not found: {competition_id}"}
+
+ # Find grid agent
+ for agent in competition._agents:
+ if hasattr(agent, 'state') and hasattr(agent.state, 'grid_levels'):
+ if agent_name and agent.name != agent_name:
+ continue
+
+ return {
+ "success": True,
+ "agent_name": agent.name,
+ "grid_status": {
+ "grid_levels": agent.state.grid_levels,
+ "triggered_levels": list(agent.state.triggered_levels),
+ "active_orders": agent.state.active_orders,
+ "total_profit": agent.state.total_profit,
+ "trades_executed": agent.state.trades_executed,
+ },
+ }
+
+ return {"success": False, "error": "No grid agent found"}
+ except Exception as e:
+ logger.exception(f"Error getting grid status: {e}")
+ return {"success": False, "error": str(e)}
+
+
+# =============================================================================
+# Research Handlers
+# =============================================================================
+
+async def get_research_handler(params: Dict) -> Dict[str, Any]:
+ """Get research report for a ticker."""
+ try:
+ from alpha_arena.core.research_agent import get_research_agent
+
+ ticker = params.get("ticker")
+ use_cache = params.get("use_cache", True)
+
+ if not ticker:
+ return {"success": False, "error": "Missing ticker"}
+
+ agent = await get_research_agent()
+ report = await agent.generate_report(ticker, use_cache=use_cache)
+
+ return {
+ "success": True,
+ "report": report.to_dict(),
+ "prompt_context": report.to_prompt_context(),
+ }
+ except Exception as e:
+ logger.exception(f"Error getting research: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def get_sec_filings_handler(params: Dict) -> Dict[str, Any]:
+ """Get SEC filings for a ticker."""
+ try:
+ from alpha_arena.core.research_agent import get_research_agent
+
+ ticker = params.get("ticker")
+ form_types = params.get("form_types") # e.g., ["10-K", "10-Q"]
+ limit = params.get("limit", 10)
+
+ if not ticker:
+ return {"success": False, "error": "Missing ticker"}
+
+ agent = await get_research_agent()
+ filings = await agent.get_recent_filings(ticker, form_types=form_types, limit=limit)
+
+ return {
+ "success": True,
+ "ticker": ticker,
+ "filings": [f.to_dict() for f in filings],
+ "count": len(filings),
+ }
+ except Exception as e:
+ logger.exception(f"Error getting SEC filings: {e}")
+ return {"success": False, "error": str(e)}
+
+
+# =============================================================================
+# Features Pipeline Handlers
+# =============================================================================
+
+async def get_features_handler(params: Dict) -> Dict[str, Any]:
+ """Get technical features for market analysis."""
+ try:
+ from alpha_arena.core.features_pipeline import get_features_pipeline
+ from alpha_arena.types.models import MarketData
+ from datetime import datetime
+
+ symbol = params.get("symbol", "BTC/USD")
+ price_history = params.get("price_history", [])
+ current_price = params.get("current_price", 100000)
+
+ # Build market data with required fields
+ market_data = MarketData(
+ symbol=symbol,
+ price=current_price,
+ bid=params.get("bid", current_price * 0.999),
+ ask=params.get("ask", current_price * 1.001),
+ high_24h=params.get("high_24h", current_price * 1.02),
+ low_24h=params.get("low_24h", current_price * 0.98),
+ volume_24h=params.get("volume_24h", 1000000),
+ timestamp=datetime.fromisoformat(params["timestamp"]) if params.get("timestamp") else datetime.now(),
+ )
+
+ pipeline = get_features_pipeline()
+ features = await pipeline.compute(market_data, price_history)
+
+ return {
+ "success": True,
+ "features": {
+ "technical": features.technical.to_dict() if features.technical else None,
+ "sentiment": features.sentiment.to_dict() if features.sentiment else None,
+ },
+ "prompt_context": features.to_prompt_context(),
+ }
+ except Exception as e:
+ logger.exception(f"Error computing features: {e}")
+ return {"success": False, "error": str(e)}
+
+
+# =============================================================================
+# Broker Handlers
+# =============================================================================
+
+async def list_brokers_handler(params: Dict) -> Dict[str, Any]:
+ """List all supported brokers."""
+ try:
+ from alpha_arena.core.broker_adapter import (
+ get_supported_brokers,
+ get_brokers_by_type,
+ get_brokers_by_region,
+ BrokerType,
+ BrokerRegion,
+ )
+
+ broker_type = params.get("type")
+ region = params.get("region")
+
+ if broker_type:
+ try:
+ bt = BrokerType(broker_type)
+ brokers = get_brokers_by_type(bt)
+ except ValueError:
+ return {"success": False, "error": f"Invalid broker type: {broker_type}"}
+ elif region:
+ try:
+ br = BrokerRegion(region)
+ brokers = get_brokers_by_region(br)
+ except ValueError:
+ return {"success": False, "error": f"Invalid region: {region}"}
+ else:
+ brokers = get_supported_brokers()
+
+ return {
+ "success": True,
+ "brokers": [b.to_dict() for b in brokers],
+ "count": len(brokers),
+ }
+ except Exception as e:
+ logger.exception(f"Error listing brokers: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def get_broker_handler(params: Dict) -> Dict[str, Any]:
+ """Get broker details by ID."""
+ try:
+ from alpha_arena.core.broker_adapter import get_broker_info
+
+ broker_id = params.get("broker_id")
+ if not broker_id:
+ return {"success": False, "error": "Missing broker_id"}
+
+ broker = get_broker_info(broker_id)
+ if broker:
+ return {
+ "success": True,
+ "broker": broker.to_dict(),
+ }
+
+ return {"success": False, "error": f"Broker not found: {broker_id}"}
+ except Exception as e:
+ logger.exception(f"Error getting broker: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def get_broker_ticker_handler(params: Dict) -> Dict[str, Any]:
+ """Get ticker data from specific broker."""
+ try:
+ from alpha_arena.core.broker_adapter import get_multi_exchange_provider
+
+ symbol = params.get("symbol")
+ broker_id = params.get("broker_id", "kraken")
+
+ if not symbol:
+ return {"success": False, "error": "Missing symbol"}
+
+ provider = await get_multi_exchange_provider(broker_id)
+ market_data = await provider.get_ticker(symbol, broker_id)
+
+ return {
+ "success": True,
+ "ticker": {
+ "symbol": market_data.symbol,
+ "price": market_data.price,
+ "bid": market_data.bid,
+ "ask": market_data.ask,
+ "high_24h": market_data.high_24h,
+ "low_24h": market_data.low_24h,
+ "volume_24h": market_data.volume_24h,
+ "timestamp": market_data.timestamp.isoformat(),
+ },
+ "broker_id": broker_id,
+ }
+ except Exception as e:
+ logger.exception(f"Error getting broker ticker: {e}")
+ return {"success": False, "error": str(e)}
+
+
+# =============================================================================
+# Sentiment Handlers
+# =============================================================================
+
+async def get_sentiment_handler(params: Dict) -> Dict[str, Any]:
+ """Get sentiment analysis for a symbol."""
+ try:
+ from alpha_arena.core.sentiment_agent import get_sentiment_agent
+
+ symbol = params.get("symbol")
+ use_cache = params.get("use_cache", True)
+ max_articles = params.get("max_articles", 15)
+
+ if not symbol:
+ return {"success": False, "error": "Missing symbol"}
+
+ agent = await get_sentiment_agent()
+ result = await agent.analyze_sentiment(symbol, use_cache, max_articles)
+
+ return {
+ "success": True,
+ "sentiment": result.to_dict(),
+ "prompt_context": result.to_prompt_context(),
+ }
+ except Exception as e:
+ logger.exception(f"Error getting sentiment: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def get_market_mood_handler(params: Dict) -> Dict[str, Any]:
+ """Get overall market mood from multiple symbols."""
+ try:
+ from alpha_arena.core.sentiment_agent import get_sentiment_agent
+
+ symbols = params.get("symbols", [])
+
+ if not symbols:
+ # Default to major market symbols
+ symbols = ["SPY", "QQQ", "BTC", "ETH"]
+
+ agent = await get_sentiment_agent()
+ result = await agent.get_market_mood(symbols)
+
+ return {
+ "success": True,
+ "market_mood": result,
+ }
+ except Exception as e:
+ logger.exception(f"Error getting market mood: {e}")
+ return {"success": False, "error": str(e)}
+
+
+# =============================================================================
+# Trading Styles Handlers
+# =============================================================================
+
+async def list_trading_styles_handler(params: Dict) -> Dict[str, Any]:
+ """List all available trading styles."""
+ try:
+ from alpha_arena.config.trading_styles import list_trading_styles
+
+ styles = list_trading_styles()
+
+ return {
+ "success": True,
+ "styles": [style.to_dict() for style in styles],
+ "count": len(styles),
+ }
+ except Exception as e:
+ logger.exception(f"Error listing trading styles: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def create_styled_agents_handler(params: Dict) -> Dict[str, Any]:
+ """
+ Create multiple agents with different trading styles using the same provider.
+
+ This allows running a competition with a single API key but different agent behaviors.
+
+ Params:
+ provider: LLM provider (openai, anthropic, etc.)
+ model_id: Model identifier (gpt-4o-mini, claude-3-5-sonnet, etc.)
+ api_key: API key for the provider (optional, can use env)
+ styles: List of style IDs to use (optional, defaults to all styles)
+ initial_capital: Starting capital per agent (default: 10000)
+ """
+ try:
+ from alpha_arena.config.trading_styles import (
+ list_trading_styles,
+ get_trading_style,
+ create_styled_agent_name,
+ )
+
+ provider = params.get("provider")
+ model_id = params.get("model_id")
+ api_key = params.get("api_key")
+ style_ids = params.get("styles")
+ initial_capital = params.get("initial_capital", 10000)
+
+ if not provider:
+ return {"success": False, "error": "Missing provider"}
+
+ if not model_id:
+ return {"success": False, "error": "Missing model_id"}
+
+ # Get styles to use
+ if style_ids:
+ styles = []
+ for style_id in style_ids:
+ style = get_trading_style(style_id)
+ if style:
+ styles.append(style)
+ else:
+ logger.warning(f"Unknown trading style: {style_id}, skipping")
+ else:
+ # Default to a diverse set of contrasting styles
+ default_style_ids = ["aggressive", "conservative", "momentum", "contrarian", "neutral"]
+ styles = [get_trading_style(sid) for sid in default_style_ids if get_trading_style(sid)]
+
+ if not styles:
+ return {"success": False, "error": "No valid styles specified"}
+
+ # Create agent configurations
+ agents = []
+ for style in styles:
+ agent_name = create_styled_agent_name(provider, model_id, style)
+
+ agents.append({
+ "name": agent_name,
+ "provider": provider,
+ "model_id": model_id,
+ "api_key": api_key,
+ "initial_capital": initial_capital,
+ "trading_style": style.id,
+ "metadata": {
+ "style_config": style.to_dict(),
+ },
+ })
+
+ return {
+ "success": True,
+ "agents": agents,
+ "count": len(agents),
+ "provider": provider,
+ "model_id": model_id,
+ "styles_used": [s.id for s in styles],
+ }
+ except Exception as e:
+ logger.exception(f"Error creating styled agents: {e}")
+ return {"success": False, "error": str(e)}
+
+
+# =============================================================================
+# Memory Handlers
+# =============================================================================
+
+async def get_agent_context_handler(params: Dict) -> Dict[str, Any]:
+ """Get agent memory context for a symbol."""
+ try:
+ from alpha_arena.core.memory_adapter import get_agent_memory
+
+ agent_name = params.get("agent_name")
+ competition_id = params.get("competition_id")
+ symbol = params.get("symbol")
+
+ if not agent_name or not competition_id:
+ return {"success": False, "error": "Missing agent_name or competition_id"}
+
+ if not symbol:
+ return {"success": False, "error": "Missing symbol"}
+
+ memory = get_agent_memory(agent_name, competition_id)
+ context = memory.get_relevant_context(symbol)
+
+ return {
+ "success": True,
+ "context": context,
+ "stats": memory.get_performance_stats(),
+ }
+ except Exception as e:
+ logger.exception(f"Error getting agent context: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def get_agent_memory_summary_handler(params: Dict) -> Dict[str, Any]:
+ """Get agent memory summary."""
+ try:
+ from alpha_arena.core.memory_adapter import get_agent_memory
+
+ agent_name = params.get("agent_name")
+ competition_id = params.get("competition_id")
+
+ if not agent_name or not competition_id:
+ return {"success": False, "error": "Missing agent_name or competition_id"}
+
+ memory = get_agent_memory(agent_name, competition_id)
+
+ return {
+ "success": True,
+ "summary": memory.get_summary(),
+ "data": memory.to_dict(),
+ }
+ except Exception as e:
+ logger.exception(f"Error getting agent memory summary: {e}")
+ return {"success": False, "error": str(e)}
+
+
+async def search_agent_memory_handler(params: Dict) -> Dict[str, Any]:
+ """Search agent memory."""
+ try:
+ from alpha_arena.core.memory_adapter import get_agent_memory
+
+ agent_name = params.get("agent_name")
+ competition_id = params.get("competition_id")
+ query = params.get("query")
+ limit = params.get("limit", 5)
+
+ if not agent_name or not competition_id:
+ return {"success": False, "error": "Missing agent_name or competition_id"}
+
+ if not query:
+ return {"success": False, "error": "Missing search query"}
+
+ memory = get_agent_memory(agent_name, competition_id)
+ results = memory.search_memory(query, limit=limit)
+
+ return {
+ "success": True,
+ "results": results,
+ "count": len(results),
+ }
+ except Exception as e:
+ logger.exception(f"Error searching agent memory: {e}")
+ return {"success": False, "error": str(e)}
+
+
def main(args=None):
"""
Main entry point - accepts single JSON payload from Rust/Tauri.
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/models.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/models.py
index 26e60c3d5..a2de575ff 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/models.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/models.py
@@ -70,6 +70,16 @@ class CompetitionModel(BaseModel):
api_key: Optional[str] = Field(None, description="API key for this model")
initial_capital: float = Field(10000.0, gt=0, description="Starting capital")
+ # Trading style (allows using same provider with different behaviors)
+ trading_style: Optional[str] = Field(
+ None,
+ description="Trading style ID (e.g., 'aggressive', 'conservative', 'momentum')"
+ )
+ metadata: Optional[Dict[str, Any]] = Field(
+ default_factory=dict,
+ description="Additional metadata including style configuration"
+ )
+
# Runtime state (populated during competition)
capital: Optional[float] = Field(None, description="Current cash balance")
total_pnl: float = Field(0.0, description="Total profit/loss")
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/responses.py b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/responses.py
index 378b67368..45dcb6ae3 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/responses.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/alpha_arena/types/responses.py
@@ -318,3 +318,29 @@ def done() -> StreamResponse:
content="",
event=SystemResponseEvent.DONE,
)
+
+
+def portfolio_update(
+ model_name: str,
+ portfolio_value: float,
+ cash: float,
+ total_pnl: float,
+ positions: list,
+ trades_count: int,
+ cycle_number: int,
+) -> StreamResponse:
+ """Create a real-time portfolio update response after trade execution."""
+ return StreamResponse(
+ content=f"{model_name}: Portfolio ${portfolio_value:,.2f} (P&L: ${total_pnl:+,.2f})",
+ event=CommonResponseEvent.PORTFOLIO_UPDATE,
+ metadata={
+ "model_name": model_name,
+ "portfolio_value": portfolio_value,
+ "cash": cash,
+ "total_pnl": total_pnl,
+ "positions": positions,
+ "trades_count": trades_count,
+ "cycle_number": cycle_number,
+ "timestamp": datetime.now().isoformat(),
+ },
+ )
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/fred_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/fred_data.py
index afa0ff095..cb088447e 100644
--- a/fincept-terminal-desktop/src-tauri/resources/scripts/fred_data.py
+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/fred_data.py
@@ -3,6 +3,8 @@ FRED Data Fetcher
Fetches economic data from Federal Reserve Economic Data (FRED)
Returns JSON output for Rust integration
Based on OpenBB FRED provider
+
+Optimized with concurrent fetching for multiple series
"""
import sys
@@ -11,12 +13,19 @@ import os
import requests
from datetime import datetime
from typing import Optional, List, Dict, Any
+from concurrent.futures import ThreadPoolExecutor, as_completed
FRED_API_BASE = "https://api.stlouisfed.org/fred"
FRED_API_KEY = os.environ.get('FRED_API_KEY', '') # API key from environment variable
+# Connection pool for better performance
+session = requests.Session()
+adapter = requests.adapters.HTTPAdapter(pool_connections=10, pool_maxsize=10, max_retries=3)
+session.mount('https://', adapter)
+
+
def make_fred_request(endpoint: str, params: Dict[str, Any]) -> Dict:
- """Make request to FRED API"""
+ """Make request to FRED API using connection pool"""
if not FRED_API_KEY:
return {"error": "FRED API key not configured"}
@@ -25,12 +34,13 @@ def make_fred_request(endpoint: str, params: Dict[str, Any]) -> Dict:
url = f"{FRED_API_BASE}/{endpoint}"
try:
- response = requests.get(url, params=params, timeout=10)
+ response = session.get(url, params=params, timeout=15)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return {"error": str(e)}
+
def get_series(series_id: str, start_date: Optional[str] = None, end_date: Optional[str] = None,
frequency: Optional[str] = None, transform: Optional[str] = None) -> Dict:
"""
@@ -90,6 +100,7 @@ def get_series(series_id: str, start_date: Optional[str] = None, end_date: Optio
except Exception as e:
return {"error": str(e), "series_id": series_id}
+
def search_series(search_text: str, limit: int = 10) -> Dict:
"""Search for FRED series"""
try:
@@ -125,6 +136,7 @@ def search_series(search_text: str, limit: int = 10) -> Dict:
except Exception as e:
return {"error": str(e), "search_text": search_text}
+
def get_categories(category_id: int = 0) -> Dict:
"""Get FRED categories"""
try:
@@ -149,6 +161,7 @@ def get_categories(category_id: int = 0) -> Dict:
except Exception as e:
return {"error": str(e), "category_id": category_id}
+
def get_category_series(category_id: int, limit: int = 50) -> Dict:
"""Get series in a category"""
try:
@@ -183,6 +196,7 @@ def get_category_series(category_id: int, limit: int = 50) -> Dict:
except Exception as e:
return {"error": str(e), "category_id": category_id}
+
def get_release_dates(release_id: int, limit: int = 10) -> Dict:
"""Get FRED release dates"""
try:
@@ -210,42 +224,67 @@ def get_release_dates(release_id: int, limit: int = 10) -> Dict:
except Exception as e:
return {"error": str(e), "release_id": release_id}
+
def get_multiple_series(series_ids: List[str], start_date: Optional[str] = None,
end_date: Optional[str] = None) -> List[Dict]:
- """Fetch multiple FRED series at once"""
+ """Fetch multiple FRED series concurrently for better performance"""
results = []
+
+ # Use ThreadPoolExecutor for concurrent fetching
+ # Limit to 5 concurrent requests to avoid rate limiting
+ max_workers = min(5, len(series_ids))
+
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
+ # Submit all tasks
+ future_to_series = {
+ executor.submit(get_series, series_id, start_date, end_date): series_id
+ for series_id in series_ids
+ }
+
+ # Collect results as they complete
+ results_dict = {}
+ for future in as_completed(future_to_series):
+ series_id = future_to_series[future]
+ try:
+ result = future.result()
+ results_dict[series_id] = result
+ except Exception as e:
+ results_dict[series_id] = {"error": str(e), "series_id": series_id}
+
+ # Return results in original order
for series_id in series_ids:
- result = get_series(series_id, start_date, end_date)
- results.append(result)
+ results.append(results_dict.get(series_id, {"error": "Unknown error", "series_id": series_id}))
+
return results
+
def main(args=None):
# Support both PyO3 (args parameter) and subprocess (sys.argv)
if args is None:
args = sys.argv[1:]
- if len(args) + 1 < 2:
+ if len(args) < 1:
print(json.dumps({"error": "Usage: python fred_data.py <command> <args>"}))
sys.exit(1)
command = args[0]
if command == "series":
- if len(args) + 1 < 3:
+ if len(args) < 2:
print(json.dumps({"error": "Usage: python fred_data.py series <series_id> [start_date] [end_date] [frequency] [transform]"}))
sys.exit(1)
series_id = args[1]
- start_date = args[2] if len(args) + 1 > 3 else None
- end_date = args[3] if len(args) + 1 > 4 else None
- frequency = sys.argv[5] if len(args) + 1 > 5 else None
- transform = sys.argv[6] if len(args) + 1 > 6 else None
+ start_date = args[2] if len(args) > 2 else None
+ end_date = args[3] if len(args) > 3 else None
+ frequency = args[4] if len(args) > 4 else None
+ transform = args[5] if len(args) > 5 else None
result = get_series(series_id, start_date, end_date, frequency, transform)
print(json.dumps(result, indent=2))
elif command == "multiple":
- if len(args) + 1 < 3:
+ if len(args) < 2:
print(json.dumps({"error": "Usage: python fred_data.py multiple <series_id1> <series_id2> ... [start_date] [end_date]"}))
sys.exit(1)
@@ -254,52 +293,53 @@ def main(args=None):
start_date = None
end_date = None
- for i in range(2, len(args) + 1):
- if '-' in sys.argv[i] and len(sys.argv[i]) == 10: # Date format YYYY-MM-DD
+ for i in range(1, len(args)):
+ arg = args[i]
+ if '-' in arg and len(arg) == 10: # Date format YYYY-MM-DD
if start_date is None:
- start_date = sys.argv[i]
+ start_date = arg
else:
- end_date = sys.argv[i]
+ end_date = arg
else:
- series_ids.append(sys.argv[i])
+ series_ids.append(arg)
result = get_multiple_series(series_ids, start_date, end_date)
print(json.dumps(result, indent=2))
elif command == "search":
- if len(args) + 1 < 3:
+ if len(args) < 2:
print(json.dumps({"error": "Usage: python fred_data.py search <search_text> [limit]"}))
sys.exit(1)
search_text = args[1]
- limit = int(args[2]) if len(args) + 1 > 3 else 10
+ limit = int(args[2]) if len(args) > 2 else 10
result = search_series(search_text, limit)
print(json.dumps(result, indent=2))
elif command == "categories":
- category_id = int(args[1]) if len(args) + 1 > 2 else 0
+ category_id = int(args[1]) if len(args) > 1 else 0
result = get_categories(category_id)
print(json.dumps(result, indent=2))
elif command == "category_series":
- if len(args) + 1 < 3:
+ if len(args) < 2:
print(json.dumps({"error": "Usage: python fred_data.py category_series <category_id> [limit]"}))
sys.exit(1)
category_id = int(args[1])
- limit = int(args[2]) if len(args) + 1 > 3 else 50
+ limit = int(args[2]) if len(args) > 2 else 50
result = get_category_series(category_id, limit)
print(json.dumps(result, indent=2))
elif command == "releases":
- if len(args) + 1 < 3:
+ if len(args) < 2:
print(json.dumps({"error": "Usage: python fred_data.py releases <release_id> [limit]"}))
sys.exit(1)
release_id = int(args[1])
- limit = int(args[2]) if len(args) + 1 > 3 else 10
+ limit = int(args[2]) if len(args) > 2 else 10
result = get_release_dates(release_id, limit)
print(json.dumps(result, indent=2))
@@ -308,5 +348,6 @@ def main(args=None):
print(json.dumps({"error": f"Unknown command: {command}"}))
sys.exit(1)
+
if __name__ == "__main__":
main()
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs
index 165ead72c..8898aa68a 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/alpha_arena.rs
@@ -574,3 +574,347 @@ pub async fn delete_alpha_competition(competition_id: String) -> Result<Value, S
execute_alpha_arena_action("delete_competition", params, None).await
}
+
+// ============================================================================
+// HITL (Human-in-the-Loop) Commands
+// ============================================================================
+
+/// Check if a decision requires approval
+#[command]
+pub async fn check_alpha_approval(
+ decision: Value,
+ context: Value
+) -> Result<Value, String> {
+ eprintln!("[Alpha Arena HITL] check_alpha_approval called");
+
+ let params = json!({
+ "decision": decision,
+ "context": context
+ });
+
+ execute_alpha_arena_action("check_approval", params, None).await
+}
+
+/// Approve a pending decision
+#[command]
+pub async fn approve_alpha_decision(
+ request_id: String,
+ approved_by: Option<String>,
+ notes: Option<String>
+) -> Result<Value, String> {
+ eprintln!("[Alpha Arena HITL] approve_alpha_decision called for: {}", request_id);
+
+ let params = json!({
+ "request_id": request_id,
+ "approved_by": approved_by.unwrap_or_else(|| "user".to_string()),
+ "notes": notes.unwrap_or_default()
+ });
+
+ execute_alpha_arena_action("approve_decision", params, None).await
+}
+
+/// Reject a pending decision
+#[command]
+pub async fn reject_alpha_decision(
+ request_id: String,
+ rejected_by: Option<String>,
+ notes: Option<String>
+) -> Result<Value, String> {
+ eprintln!("[Alpha Arena HITL] reject_alpha_decision called for: {}", request_id);
+
+ let params = json!({
+ "request_id": request_id,
+ "rejected_by": rejected_by.unwrap_or_else(|| "user".to_string()),
+ "notes": notes.unwrap_or_default()
+ });
+
+ execute_alpha_arena_action("reject_decision", params, None).await
+}
+
+/// Get all pending approval requests
+#[command]
+pub async fn get_alpha_pending_approvals() -> Result<Value, String> {
+ eprintln!("[Alpha Arena HITL] get_alpha_pending_approvals called");
+
+ execute_alpha_arena_action("get_pending_approvals", json!({}), None).await
+}
+
+/// Get HITL manager status and rules
+#[command]
+pub async fn get_alpha_hitl_status() -> Result<Value, String> {
+ eprintln!("[Alpha Arena HITL] get_alpha_hitl_status called");
+
+ execute_alpha_arena_action("get_hitl_status", json!({}), None).await
+}
+
+/// Update HITL rule settings
+#[command]
+pub async fn update_alpha_hitl_rule(
+ rule_name: String,
+ enabled: bool
+) -> Result<Value, String> {
+ eprintln!("[Alpha Arena HITL] update_alpha_hitl_rule called: {} = {}", rule_name, enabled);
+
+ let params = json!({
+ "rule_name": rule_name,
+ "enabled": enabled
+ });
+
+ execute_alpha_arena_action("update_hitl_rule", params, None).await
+}
+
+// ============================================================================
+// Portfolio Metrics Commands
+// ============================================================================
+
+/// Get portfolio metrics (Sharpe ratio, drawdown, etc.)
+#[command]
+pub async fn get_alpha_portfolio_metrics(
+ competition_id: String,
+ model_name: String
+) -> Result<Value, String> {
+ eprintln!("[Alpha Arena] get_alpha_portfolio_metrics called");
+
+ let params = json!({
+ "competition_id": competition_id,
+ "model_name": model_name
+ });
+
+ execute_alpha_arena_action("get_portfolio_metrics", params, None).await
+}
+
+/// Get equity curve data for charting
+#[command]
+pub async fn get_alpha_equity_curve(
+ competition_id: String,
+ model_name: String
+) -> Result<Value, String> {
+ eprintln!("[Alpha Arena] get_alpha_equity_curve called");
+
+ let params = json!({
+ "competition_id": competition_id,
+ "model_name": model_name
+ });
+
+ execute_alpha_arena_action("get_equity_curve", params, None).await
+}
+
+// ============================================================================
+// Grid Strategy Commands
+// ============================================================================
+
+/// Create a grid strategy agent
+#[command]
+pub async fn create_alpha_grid_agent(
+ name: String,
+ upper_price: f64,
+ lower_price: f64,
+ grid_levels: u32,
+ grid_type: Option<String>,
+ total_investment: Option<f64>
+) -> Result<Value, String> {
+ eprintln!("[Alpha Arena Grid] create_alpha_grid_agent called: {}", name);
+
+ let params = json!({
+ "name": name,
+ "upper_price": upper_price,
+ "lower_price": lower_price,
+ "grid_levels": grid_levels,
+ "grid_type": grid_type.unwrap_or_else(|| "arithmetic".to_string()),
+ "total_investment": total_investment.unwrap_or(10000.0)
+ });
+
+ execute_alpha_arena_action("create_grid_agent", params, None).await
+}
+
+/// Get grid agent status
+#[command]
+pub async fn get_alpha_grid_status(agent_name: String) -> Result<Value, String> {
+ eprintln!("[Alpha Arena Grid] get_alpha_grid_status called: {}", agent_name);
+
+ let params = json!({
+ "agent_name": agent_name
+ });
+
+ execute_alpha_arena_action("get_grid_status", params, None).await
+}
+
+// ============================================================================
+// Research Commands
+// ============================================================================
+
+/// Get research report for a ticker
+#[command]
+pub async fn get_alpha_research(ticker: String) -> Result<Value, String> {
+ eprintln!("[Alpha Arena Research] get_alpha_research called: {}", ticker);
+
+ let params = json!({
+ "ticker": ticker
+ });
+
+ execute_alpha_arena_action("get_research", params, None).await
+}
+
+/// Get SEC filings for a ticker
+#[command]
+pub async fn get_alpha_sec_filings(
+ ticker: String,
+ form_types: Option<Vec<String>>,
+ limit: Option<u32>
+) -> Result<Value, String> {
+ eprintln!("[Alpha Arena Research] get_alpha_sec_filings called: {}", ticker);
+
+ let params = json!({
+ "ticker": ticker,
+ "form_types": form_types,
+ "limit": limit.unwrap_or(10)
+ });
+
+ execute_alpha_arena_action("get_sec_filings", params, None).await
+}
+
+// ============================================================================
+// Features Pipeline Commands
+// ============================================================================
+
+/// Get technical features for a symbol
+#[command]
+pub async fn get_alpha_features(
+ symbol: String,
+ price: f64
+) -> Result<Value, String> {
+ eprintln!("[Alpha Arena Features] get_alpha_features called: {}", symbol);
+
+ let params = json!({
+ "symbol": symbol,
+ "price": price
+ });
+
+ execute_alpha_arena_action("get_features", params, None).await
+}
+
+// ============================================================================
+// Broker Commands
+// ============================================================================
+
+/// List all supported brokers
+#[command]
+pub async fn list_alpha_brokers(
+ broker_type: Option<String>,
+ region: Option<String>
+) -> Result<Value, String> {
+ eprintln!("[Alpha Arena Brokers] list_alpha_brokers called");
+
+ let params = json!({
+ "type": broker_type,
+ "region": region
+ });
+
+ execute_alpha_arena_action("list_brokers", params, None).await
+}
+
+/// Get broker details by ID
+#[command]
+pub async fn get_alpha_broker(broker_id: String) -> Result<Value, String> {
+ eprintln!("[Alpha Arena Brokers] get_alpha_broker called: {}", broker_id);
+
+ let params = json!({
+ "broker_id": broker_id
+ });
+
+ execute_alpha_arena_action("get_broker", params, None).await
+}
+
+/// Get ticker data from specific broker
+#[command]
+pub async fn get_alpha_broker_ticker(
+ symbol: String,
+ broker_id: Option<String>
+) -> Result<Value, String> {
+ eprintln!("[Alpha Arena Brokers] get_alpha_broker_ticker called: {} from {:?}", symbol, broker_id);
+
+ let params = json!({
+ "symbol": symbol,
+ "broker_id": broker_id.unwrap_or_else(|| "kraken".to_string())
+ });
+
+ execute_alpha_arena_action("get_broker_ticker", params, None).await
+}
+
+// ============================================================================
+// Sentiment Commands
+// ============================================================================
+
+/// Get sentiment analysis for a symbol
+#[command]
+pub async fn get_alpha_sentiment(
+ symbol: String,
+ max_articles: Option<u32>
+) -> Result<Value, String> {
+ eprintln!("[Alpha Arena Sentiment] get_alpha_sentiment called: {}", symbol);
+
+ let params = json!({
+ "symbol": symbol,
+ "max_articles": max_articles.unwrap_or(15)
+ });
+
+ execute_alpha_arena_action("get_sentiment", params, None).await
+}
+
+/// Get overall market mood from multiple symbols
+#[command]
+pub async fn get_alpha_market_mood(
+ symbols: Option<Vec<String>>
+) -> Result<Value, String> {
+ eprintln!("[Alpha Arena Sentiment] get_alpha_market_mood called");
+
+ let params = json!({
+ "symbols": symbols.unwrap_or_else(|| vec!["SPY".to_string(), "QQQ".to_string(), "BTC".to_string()])
+ });
+
+ execute_alpha_arena_action("get_market_mood", params, None).await
+}
+
+// ============================================================================
+// Trading Styles Commands (v2.2)
+// ============================================================================
+
+/// List all available trading styles
+#[command]
+pub async fn list_alpha_trading_styles() -> Result<Value, String> {
+ eprintln!("[Alpha Arena Styles] list_alpha_trading_styles called");
+
+ execute_alpha_arena_action("list_trading_styles", json!({}), None).await
+}
+
+/// Create multiple agents with different trading styles using the same provider
+#[command]
+pub async fn create_alpha_styled_agents(
+ provider: String,
+ model_id: String,
+ styles: Option<Vec<String>>,
+ initial_capital: Option<f64>
+) -> Result<Value, String> {
+ eprintln!("[Alpha Arena Styles] create_alpha_styled_agents called: {}:{}", provider, model_id);
+
+ let params = json!({
+ "provider": provider,
+ "model_id": model_id,
+ "styles": styles,
+ "initial_capital": initial_capital.unwrap_or(10000.0)
+ });
+
+ execute_alpha_arena_action("create_styled_agents", params, None).await
+}
+
+/// Generic action executor - allows calling any Alpha Arena action dynamically
+/// This is useful for new features that don't have dedicated commands yet
+#[command]
+pub async fn run_alpha_action(
+ action: String,
+ params: Value
+) -> Result<Value, String> {
+ eprintln!("[Alpha Arena Generic] run_alpha_action called: {}", action);
+
+ execute_alpha_arena_action(&action, params, None).await
+}
diff --git a/fincept-terminal-desktop/src-tauri/src/database/operations.rs b/fincept-terminal-desktop/src-tauri/src/database/operations.rs
index becd8147b..0e5decc7b 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/operations.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/operations.rs
@@ -378,22 +378,23 @@ pub fn fix_google_model_ids() -> Result<OperationResult> {
let pool = get_pool()?;
let conn = pool.get()?;
- // Fix model_ids that have incorrect prefixes like "google/" or "models/"
+ // Fix model_ids that have prefixes like "gemini/", "google/", or "models/"
+ // These come from LiteLLM format but Google's API needs just "gemini-xxx"
let rows_affected = conn.execute(
"UPDATE llm_model_configs
- SET model_id = REPLACE(REPLACE(model_id, 'google/', ''), 'models/', ''),
+ SET model_id = REPLACE(REPLACE(REPLACE(model_id, 'gemini/', ''), 'google/', ''), 'models/', ''),
updated_at = CURRENT_TIMESTAMP
- WHERE provider = 'google'
- AND (model_id LIKE 'google/%' OR model_id LIKE 'models/%')",
+ WHERE (provider = 'google' OR provider = 'gemini')
+ AND (model_id LIKE 'gemini/%' OR model_id LIKE 'google/%' OR model_id LIKE 'models/%')",
[],
)?;
- // Also ensure common model names are correct
+ // Also ensure common model names are correct - set default if model_id is invalid
conn.execute(
"UPDATE llm_model_configs
SET model_id = 'gemini-1.5-flash',
updated_at = CURRENT_TIMESTAMP
- WHERE provider = 'google'
+ WHERE (provider = 'google' OR provider = 'gemini')
AND model_id NOT LIKE 'gemini-%'
AND model_id != ''",
[],
diff --git a/fincept-terminal-desktop/src-tauri/src/database/schema.rs b/fincept-terminal-desktop/src-tauri/src/database/schema.rs
index 8f3200f27..be1f35122 100644
--- a/fincept-terminal-desktop/src-tauri/src/database/schema.rs
+++ b/fincept-terminal-desktop/src-tauri/src/database/schema.rs
@@ -683,7 +683,110 @@ pub fn create_schema(conn: &Connection) -> Result<()> {
enabled INTEGER DEFAULT 1,
deleted INTEGER DEFAULT 0,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
- )
+ );
+
+ -- =============================================================================
+ -- Alpha Arena Tables (Competition Paper Trading)
+ -- =============================================================================
+
+ -- Alpha Arena competitions table
+ CREATE TABLE IF NOT EXISTS alpha_arena_competitions (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ exchange_id TEXT DEFAULT 'kraken',
+ symbols TEXT NOT NULL,
+ initial_capital REAL NOT NULL DEFAULT 10000,
+ mode TEXT NOT NULL DEFAULT 'baseline',
+ cycle_interval_seconds INTEGER DEFAULT 150,
+ max_cycles INTEGER,
+ status TEXT NOT NULL DEFAULT 'created' CHECK (status IN ('created', 'running', 'paused', 'completed', 'failed')),
+ cycle_count INTEGER DEFAULT 0,
+ config_json TEXT,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ started_at TEXT,
+ completed_at TEXT,
+ updated_at TEXT DEFAULT CURRENT_TIMESTAMP
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_alpha_competitions_status ON alpha_arena_competitions(status);
+ CREATE INDEX IF NOT EXISTS idx_alpha_competitions_created ON alpha_arena_competitions(created_at DESC);
+
+ -- Alpha Arena model portfolios (links models to paper trading portfolios)
+ CREATE TABLE IF NOT EXISTS alpha_arena_model_portfolios (
+ id TEXT PRIMARY KEY,
+ competition_id TEXT NOT NULL,
+ model_name TEXT NOT NULL,
+ portfolio_id TEXT NOT NULL,
+ provider TEXT,
+ model_id TEXT,
+ initial_capital REAL NOT NULL,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (competition_id) REFERENCES alpha_arena_competitions(id) ON DELETE CASCADE,
+ FOREIGN KEY (portfolio_id) REFERENCES pt_portfolios(id) ON DELETE CASCADE,
+ UNIQUE(competition_id, model_name)
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_alpha_model_portfolios_competition ON alpha_arena_model_portfolios(competition_id);
+ CREATE INDEX IF NOT EXISTS idx_alpha_model_portfolios_model ON alpha_arena_model_portfolios(model_name);
+
+ -- Alpha Arena decision logs (AI trading decisions)
+ CREATE TABLE IF NOT EXISTS alpha_arena_decisions (
+ id TEXT PRIMARY KEY,
+ competition_id TEXT NOT NULL,
+ model_name TEXT NOT NULL,
+ cycle_number INTEGER NOT NULL,
+ symbol TEXT NOT NULL,
+ action TEXT NOT NULL CHECK (action IN ('buy', 'sell', 'hold', 'BUY', 'SELL', 'HOLD')),
+ quantity REAL,
+ confidence REAL,
+ reasoning TEXT,
+ trade_executed INTEGER DEFAULT 0,
+ price_at_decision REAL,
+ portfolio_value_before REAL,
+ portfolio_value_after REAL,
+ order_id TEXT,
+ pnl REAL DEFAULT 0,
+ timestamp TEXT DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (competition_id) REFERENCES alpha_arena_competitions(id) ON DELETE CASCADE
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_alpha_decisions_competition ON alpha_arena_decisions(competition_id);
+ CREATE INDEX IF NOT EXISTS idx_alpha_decisions_model ON alpha_arena_decisions(model_name);
+ CREATE INDEX IF NOT EXISTS idx_alpha_decisions_cycle ON alpha_arena_decisions(cycle_number);
+ CREATE INDEX IF NOT EXISTS idx_alpha_decisions_timestamp ON alpha_arena_decisions(timestamp DESC);
+
+ -- Alpha Arena performance snapshots (for charting)
+ CREATE TABLE IF NOT EXISTS alpha_arena_snapshots (
+ id TEXT PRIMARY KEY,
+ competition_id TEXT NOT NULL,
+ model_name TEXT NOT NULL,
+ cycle_number INTEGER NOT NULL,
+ portfolio_value REAL NOT NULL,
+ cash REAL NOT NULL,
+ pnl REAL DEFAULT 0,
+ return_pct REAL DEFAULT 0,
+ positions_count INTEGER DEFAULT 0,
+ trades_count INTEGER DEFAULT 0,
+ timestamp TEXT DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (competition_id) REFERENCES alpha_arena_competitions(id) ON DELETE CASCADE
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_alpha_snapshots_competition ON alpha_arena_snapshots(competition_id);
+ CREATE INDEX IF NOT EXISTS idx_alpha_snapshots_model ON alpha_arena_snapshots(model_name);
+ CREATE INDEX IF NOT EXISTS idx_alpha_snapshots_cycle ON alpha_arena_snapshots(cycle_number);
+
+ -- Alpha Arena leaderboard snapshots
+ CREATE TABLE IF NOT EXISTS alpha_arena_leaderboard (
+ id TEXT PRIMARY KEY,
+ competition_id TEXT NOT NULL,
+ cycle_number INTEGER NOT NULL,
+ leaderboard_json TEXT NOT NULL,
+ timestamp TEXT DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (competition_id) REFERENCES alpha_arena_competitions(id) ON DELETE CASCADE
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_alpha_leaderboard_competition ON alpha_arena_leaderboard(competition_id);
+ CREATE INDEX IF NOT EXISTS idx_alpha_leaderboard_cycle ON alpha_arena_leaderboard(cycle_number DESC)
",
)?;
diff --git a/fincept-terminal-desktop/src-tauri/src/lib.rs b/fincept-terminal-desktop/src-tauri/src/lib.rs
index fe51f6bb7..34e451e67 100644
--- a/fincept-terminal-desktop/src-tauri/src/lib.rs
+++ b/fincept-terminal-desktop/src-tauri/src/lib.rs
@@ -1648,6 +1648,10 @@ pub fn run() {
commands::alpha_arena::list_alpha_competitions,
commands::alpha_arena::get_alpha_competition,
commands::alpha_arena::delete_alpha_competition,
+ // Alpha Arena - Trading Styles (v2.2)
+ commands::alpha_arena::list_alpha_trading_styles,
+ commands::alpha_arena::create_alpha_styled_agents,
+ commands::alpha_arena::run_alpha_action,
// AI Quant Lab - Qlib
commands::ai_quant_lab::qlib_initialize,
commands::ai_quant_lab::qlib_check_status,
diff --git a/fincept-terminal-desktop/src/components/common/HeaderSupportButtons.tsx b/fincept-terminal-desktop/src/components/common/HeaderSupportButtons.tsx
new file mode 100644
index 000000000..fe50f7fa5
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/common/HeaderSupportButtons.tsx
@@ -0,0 +1,578 @@
+// Header Support Buttons - Feedback, Contact, Newsletter
+// Fincept-style modal forms for user engagement
+
+import React, { useState } from 'react';
+import { MessageSquarePlus, Mail, Newspaper, X, Star, Send, Check } from 'lucide-react';
+import {
+ submitContactForm,
+ submitFeedback,
+ subscribeToNewsletter,
+ type ContactFormData,
+ type FeedbackFormData,
+} from '@/services/support/supportApi';
+
+// Fincept color palette
+const COLORS = {
+ ORANGE: '#ea580c',
+ GREEN: '#10b981',
+ RED: '#ef4444',
+ YELLOW: '#fbbf24',
+ BLUE: '#3b82f6',
+ CYAN: '#06b6d4',
+ BG: '#0f0f0f',
+ PANEL: '#1a1a1a',
+ BORDER: '#404040',
+ TEXT: '#ffffff',
+ MUTED: '#a3a3a3',
+};
+
+// Modal wrapper component
+const Modal: React.FC<{
+ isOpen: boolean;
+ onClose: () => void;
+ title: string;
+ children: React.ReactNode;
+}> = ({ isOpen, onClose, title, children }) => {
+ if (!isOpen) return null;
+
+ return (
+ <div
+ style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0,0,0,0.85)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 9999,
+ }}
+ onClick={onClose}
+ >
+ <div
+ style={{
+ backgroundColor: COLORS.PANEL,
+ border: `2px solid ${COLORS.ORANGE}`,
+ borderRadius: '4px',
+ padding: '16px',
+ width: '450px',
+ maxHeight: '80vh',
+ overflow: 'auto',
+ fontFamily: 'Consolas, monospace',
+ }}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
+ <h3 style={{ color: COLORS.ORANGE, fontSize: '14px', fontWeight: 'bold', margin: 0 }}>{title}</h3>
+ <button
+ onClick={onClose}
+ style={{
+ background: 'transparent',
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.MUTED,
+ cursor: 'pointer',
+ padding: '2px 6px',
+ fontSize: '10px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ }}
+ >
+ <X size={12} /> CLOSE
+ </button>
+ </div>
+ <div style={{ borderBottom: `1px solid ${COLORS.BORDER}`, marginBottom: '12px' }}></div>
+ {children}
+ </div>
+ </div>
+ );
+};
+
+// Input field component
+const InputField: React.FC<{
+ label: string;
+ value: string;
+ onChange: (value: string) => void;
+ placeholder?: string;
+ type?: string;
+ required?: boolean;
+ multiline?: boolean;
+ rows?: number;
+}> = ({ label, value, onChange, placeholder, type = 'text', required, multiline, rows = 4 }) => (
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: COLORS.TEXT, fontSize: '11px', display: 'block', marginBottom: '4px' }}>
+ {label} {required && <span style={{ color: COLORS.RED }}>*</span>}
+ </label>
+ {multiline ? (
+ <textarea
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={placeholder}
+ rows={rows}
+ style={{
+ width: '100%',
+ backgroundColor: COLORS.BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.TEXT,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ resize: 'vertical',
+ borderRadius: '2px',
+ }}
+ />
+ ) : (
+ <input
+ type={type}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={placeholder}
+ style={{
+ width: '100%',
+ backgroundColor: COLORS.BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.TEXT,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ borderRadius: '2px',
+ }}
+ />
+ )}
+ </div>
+);
+
+// Star rating component
+const StarRating: React.FC<{
+ rating: number;
+ onChange: (rating: number) => void;
+}> = ({ rating, onChange }) => (
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: COLORS.TEXT, fontSize: '11px', display: 'block', marginBottom: '4px' }}>
+ Rating <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {[1, 2, 3, 4, 5].map((star) => (
+ <button
+ key={star}
+ onClick={() => onChange(star)}
+ style={{
+ background: 'transparent',
+ border: 'none',
+ cursor: 'pointer',
+ padding: '2px',
+ }}
+ >
+ <Star
+ size={24}
+ fill={star <= rating ? COLORS.YELLOW : 'transparent'}
+ color={star <= rating ? COLORS.YELLOW : COLORS.MUTED}
+ />
+ </button>
+ ))}
+ </div>
+ </div>
+);
+
+// Submit button component
+const SubmitButton: React.FC<{
+ onClick: () => void;
+ loading: boolean;
+ success: boolean;
+ text: string;
+}> = ({ onClick, loading, success, text }) => (
+ <button
+ onClick={onClick}
+ disabled={loading}
+ style={{
+ width: '100%',
+ backgroundColor: success ? COLORS.GREEN : COLORS.ORANGE,
+ color: COLORS.TEXT,
+ border: 'none',
+ padding: '10px 16px',
+ fontSize: '12px',
+ fontWeight: 'bold',
+ cursor: loading ? 'not-allowed' : 'pointer',
+ borderRadius: '2px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px',
+ opacity: loading ? 0.7 : 1,
+ }}
+ >
+ {loading ? (
+ 'SUBMITTING...'
+ ) : success ? (
+ <>
+ <Check size={14} /> SUBMITTED!
+ </>
+ ) : (
+ <>
+ <Send size={14} /> {text}
+ </>
+ )}
+ </button>
+);
+
+// Main component
+export const HeaderSupportButtons: React.FC = () => {
+ // Modal states
+ const [showFeedback, setShowFeedback] = useState(false);
+ const [showContact, setShowContact] = useState(false);
+ const [showNewsletter, setShowNewsletter] = useState(false);
+
+ // Feedback form state
+ const [feedbackName, setFeedbackName] = useState('');
+ const [feedbackEmail, setFeedbackEmail] = useState('');
+ const [feedbackRating, setFeedbackRating] = useState(0);
+ const [feedbackText, setFeedbackText] = useState('');
+ const [feedbackCategory, setFeedbackCategory] = useState('general');
+ const [feedbackLoading, setFeedbackLoading] = useState(false);
+ const [feedbackSuccess, setFeedbackSuccess] = useState(false);
+ const [feedbackError, setFeedbackError] = useState('');
+
+ // Contact form state
+ const [contactName, setContactName] = useState('');
+ const [contactEmail, setContactEmail] = useState('');
+ const [contactSubject, setContactSubject] = useState('');
+ const [contactMessage, setContactMessage] = useState('');
+ const [contactLoading, setContactLoading] = useState(false);
+ const [contactSuccess, setContactSuccess] = useState(false);
+ const [contactError, setContactError] = useState('');
+
+ // Newsletter state
+ const [newsletterEmail, setNewsletterEmail] = useState('');
+ const [newsletterLoading, setNewsletterLoading] = useState(false);
+ const [newsletterSuccess, setNewsletterSuccess] = useState(false);
+ const [newsletterError, setNewsletterError] = useState('');
+
+ // Reset functions
+ const resetFeedback = () => {
+ setFeedbackName('');
+ setFeedbackEmail('');
+ setFeedbackRating(0);
+ setFeedbackText('');
+ setFeedbackCategory('general');
+ setFeedbackSuccess(false);
+ setFeedbackError('');
+ };
+
+ const resetContact = () => {
+ setContactName('');
+ setContactEmail('');
+ setContactSubject('');
+ setContactMessage('');
+ setContactSuccess(false);
+ setContactError('');
+ };
+
+ const resetNewsletter = () => {
+ setNewsletterEmail('');
+ setNewsletterSuccess(false);
+ setNewsletterError('');
+ };
+
+ // Submit handlers
+ const handleFeedbackSubmit = async () => {
+ if (!feedbackRating || !feedbackText.trim()) {
+ setFeedbackError('Please provide a rating and feedback');
+ return;
+ }
+
+ setFeedbackLoading(true);
+ setFeedbackError('');
+
+ const data: FeedbackFormData = {
+ name: feedbackName || undefined,
+ email: feedbackEmail || undefined,
+ rating: feedbackRating,
+ feedback_text: feedbackText,
+ category: feedbackCategory,
+ };
+
+ const result = await submitFeedback(data);
+ setFeedbackLoading(false);
+
+ if (result.success) {
+ setFeedbackSuccess(true);
+ setTimeout(() => {
+ setShowFeedback(false);
+ resetFeedback();
+ }, 2000);
+ } else {
+ setFeedbackError(result.error || 'Failed to submit feedback');
+ }
+ };
+
+ const handleContactSubmit = async () => {
+ if (!contactName.trim() || !contactEmail.trim() || !contactSubject.trim() || !contactMessage.trim()) {
+ setContactError('Please fill in all required fields');
+ return;
+ }
+
+ setContactLoading(true);
+ setContactError('');
+
+ const data: ContactFormData = {
+ name: contactName,
+ email: contactEmail,
+ subject: contactSubject,
+ message: contactMessage,
+ };
+
+ const result = await submitContactForm(data);
+ setContactLoading(false);
+
+ if (result.success) {
+ setContactSuccess(true);
+ setTimeout(() => {
+ setShowContact(false);
+ resetContact();
+ }, 2000);
+ } else {
+ setContactError(result.error || 'Failed to submit contact form');
+ }
+ };
+
+ const handleNewsletterSubmit = async () => {
+ if (!newsletterEmail.trim()) {
+ setNewsletterError('Please enter your email');
+ return;
+ }
+
+ setNewsletterLoading(true);
+ setNewsletterError('');
+
+ const result = await subscribeToNewsletter({
+ email: newsletterEmail,
+ source: 'terminal_header',
+ });
+ setNewsletterLoading(false);
+
+ if (result.success) {
+ setNewsletterSuccess(true);
+ setTimeout(() => {
+ setShowNewsletter(false);
+ resetNewsletter();
+ }, 2000);
+ } else {
+ setNewsletterError(result.error || 'Failed to subscribe');
+ }
+ };
+
+ // Button style
+ const buttonStyle: React.CSSProperties = {
+ backgroundColor: 'transparent',
+ color: COLORS.MUTED,
+ border: `1px solid ${COLORS.BORDER}`,
+ padding: '3px 8px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ fontWeight: 'bold',
+ transition: 'all 0.2s',
+ };
+
+ return (
+ <>
+ {/* Header Buttons */}
+ <button
+ onClick={() => setShowFeedback(true)}
+ style={buttonStyle}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = COLORS.ORANGE;
+ e.currentTarget.style.borderColor = COLORS.ORANGE;
+ e.currentTarget.style.color = COLORS.TEXT;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.borderColor = COLORS.BORDER;
+ e.currentTarget.style.color = COLORS.MUTED;
+ }}
+ title="Send Feedback"
+ >
+ <MessageSquarePlus size={12} />
+ FEEDBACK
+ </button>
+
+ <button
+ onClick={() => setShowContact(true)}
+ style={buttonStyle}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = COLORS.BLUE;
+ e.currentTarget.style.borderColor = COLORS.BLUE;
+ e.currentTarget.style.color = COLORS.TEXT;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.borderColor = COLORS.BORDER;
+ e.currentTarget.style.color = COLORS.MUTED;
+ }}
+ title="Contact Us"
+ >
+ <Mail size={12} />
+ CONTACT
+ </button>
+
+ <button
+ onClick={() => setShowNewsletter(true)}
+ style={buttonStyle}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = COLORS.GREEN;
+ e.currentTarget.style.borderColor = COLORS.GREEN;
+ e.currentTarget.style.color = COLORS.TEXT;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.borderColor = COLORS.BORDER;
+ e.currentTarget.style.color = COLORS.MUTED;
+ }}
+ title="Subscribe to Newsletter"
+ >
+ <Newspaper size={12} />
+ NEWSLETTER
+ </button>
+
+ {/* Feedback Modal */}
+ <Modal isOpen={showFeedback} onClose={() => { setShowFeedback(false); resetFeedback(); }} title="SEND FEEDBACK">
+ <InputField
+ label="Name"
+ value={feedbackName}
+ onChange={setFeedbackName}
+ placeholder="Your name (optional)"
+ />
+ <InputField
+ label="Email"
+ value={feedbackEmail}
+ onChange={setFeedbackEmail}
+ placeholder="Your email (optional)"
+ type="email"
+ />
+ <StarRating rating={feedbackRating} onChange={setFeedbackRating} />
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: COLORS.TEXT, fontSize: '11px', display: 'block', marginBottom: '4px' }}>
+ Category
+ </label>
+ <select
+ value={feedbackCategory}
+ onChange={(e) => setFeedbackCategory(e.target.value)}
+ style={{
+ width: '100%',
+ backgroundColor: COLORS.BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.TEXT,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ borderRadius: '2px',
+ }}
+ >
+ <option value="general">General</option>
+ <option value="feature_request">Feature Request</option>
+ <option value="bug_report">Bug Report</option>
+ <option value="ui_ux">UI/UX</option>
+ <option value="performance">Performance</option>
+ <option value="data">Data Quality</option>
+ </select>
+ </div>
+ <InputField
+ label="Feedback"
+ value={feedbackText}
+ onChange={setFeedbackText}
+ placeholder="Tell us what you think..."
+ multiline
+ rows={4}
+ required
+ />
+ {feedbackError && (
+ <div style={{ color: COLORS.RED, fontSize: '10px', marginBottom: '12px' }}>{feedbackError}</div>
+ )}
+ <SubmitButton
+ onClick={handleFeedbackSubmit}
+ loading={feedbackLoading}
+ success={feedbackSuccess}
+ text="SUBMIT FEEDBACK"
+ />
+ </Modal>
+
+ {/* Contact Modal */}
+ <Modal isOpen={showContact} onClose={() => { setShowContact(false); resetContact(); }} title="CONTACT US">
+ <InputField
+ label="Name"
+ value={contactName}
+ onChange={setContactName}
+ placeholder="Your name"
+ required
+ />
+ <InputField
+ label="Email"
+ value={contactEmail}
+ onChange={setContactEmail}
+ placeholder="[email protected]"
+ type="email"
+ required
+ />
+ <InputField
+ label="Subject"
+ value={contactSubject}
+ onChange={setContactSubject}
+ placeholder="Subject of your message"
+ required
+ />
+ <InputField
+ label="Message"
+ value={contactMessage}
+ onChange={setContactMessage}
+ placeholder="Your message..."
+ multiline
+ rows={5}
+ required
+ />
+ {contactError && (
+ <div style={{ color: COLORS.RED, fontSize: '10px', marginBottom: '12px' }}>{contactError}</div>
+ )}
+ <SubmitButton
+ onClick={handleContactSubmit}
+ loading={contactLoading}
+ success={contactSuccess}
+ text="SEND MESSAGE"
+ />
+ </Modal>
+
+ {/* Newsletter Modal */}
+ <Modal isOpen={showNewsletter} onClose={() => { setShowNewsletter(false); resetNewsletter(); }} title="SUBSCRIBE TO NEWSLETTER">
+ <p style={{ color: COLORS.MUTED, fontSize: '11px', marginBottom: '16px', lineHeight: '1.5' }}>
+ Stay updated with the latest features, market insights, and Fincept news delivered to your inbox.
+ </p>
+ <InputField
+ label="Email Address"
+ value={newsletterEmail}
+ onChange={setNewsletterEmail}
+ placeholder="[email protected]"
+ type="email"
+ required
+ />
+ {newsletterError && (
+ <div style={{ color: COLORS.RED, fontSize: '10px', marginBottom: '12px' }}>{newsletterError}</div>
+ )}
+ <SubmitButton
+ onClick={handleNewsletterSubmit}
+ loading={newsletterLoading}
+ success={newsletterSuccess}
+ text="SUBSCRIBE"
+ />
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '12px', textAlign: 'center' }}>
+ You can unsubscribe at any time. We respect your privacy.
+ </p>
+ </Modal>
+ </>
+ );
+};
+
+export default HeaderSupportButtons;
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index 1a24d3531..a394cbcc4 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -15,51 +15,52 @@ import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { CommandBar } from '@/components/command-bar';
// Eagerly loaded tabs (needed immediately)
-import ForumTab from '@/components/tabs/ForumTab';
-import DashboardTab from '@/components/tabs/DashboardTab';
-import MarketsTab from '@/components/tabs/MarketsTab';
-import NewsTab from '@/components/tabs/NewsTab';
-import WatchlistTab from '@/components/tabs/WatchlistTab';
-import ChatTab from '@/components/tabs/ChatTab';
-import ProfileTab from '@/components/tabs/ProfileTab';
-import AboutTab from '@/components/tabs/AboutTab';
-import MarketplaceTab from '@/components/tabs/MarketplaceTab';
-import PortfolioTab from '@/components/tabs/portfolio-tab/PortfolioTab';
-import DocsTab from '@/components/tabs/docs/DocsTab';
+import ForumTab from '@/components/tabs/forum';
+import DashboardTab from '@/components/tabs/dashboard';
+import MarketsTab from '@/components/tabs/markets';
+import NewsTab from '@/components/tabs/news';
+import WatchlistTab from '@/components/tabs/watchlist';
+import ChatTab from '@/components/tabs/chat';
+import ProfileTab from '@/components/tabs/profile';
+import AboutTab from '@/components/tabs/about';
+import MarketplaceTab from '@/components/tabs/marketplace';
+import PortfolioTab from '@/components/tabs/portfolio-tab';
+import DocsTab from '@/components/tabs/docs';
import SettingsTab from '@/components/tabs/settings-tab';
-import DataSourcesTab from '@/components/tabs/data-sources/DataSourcesTab';
+import DataSourcesTab from '@/components/tabs/data-sources';
import MCPTab from '@/components/tabs/mcp';
-import SupportTicketTab from '@/components/tabs/SupportTicketTab';
+import SupportTicketTab from '@/components/tabs/support-ticket';
import RecordedContextsManager from '@/components/common/RecordedContextsManager';
-import AgentConfigTab from '@/components/tabs/AgentConfigTab';
-import RelationshipMapTab from '@/components/tabs/RelationshipMapTab';
-import MonitoringTab from '@/components/tabs/MonitoringTab';
+import { HeaderSupportButtons } from '@/components/common/HeaderSupportButtons';
+import AgentConfigTab from '@/components/tabs/agent-config';
+import RelationshipMapTab from '@/components/tabs/relationship-map';
+import MonitoringTab from '@/components/tabs/monitoring';
import { useTranslation } from 'react-i18next';
// Lazy loaded tabs (heavy/Python-dependent)
-const EquityResearchTab = React.lazy(() => import('@/components/tabs/EquityResearchTab'));
-const AsiaMarketsTab = React.lazy(() => import('@/components/tabs/AsiaMarketsTab'));
-const ScreenerTab = React.lazy(() => import('@/components/tabs/ScreenerTab'));
-const BacktestingTab = React.lazy(() => import('@/components/tabs/BacktestingTabNew'));
-const GeopoliticsTab = React.lazy(() => import('@/components/tabs/GeopoliticsTab'));
-const AIQuantLabTab = React.lazy(() => import('@/components/tabs/ai-quant-lab/AIQuantLabTab'));
-const CodeEditorTab = React.lazy(() => import('@/components/tabs/CodeEditorTab'));
-const NodeEditorTab = React.lazy(() => import('@/components/tabs/NodeEditorTab'));
-const PolygonEqTab = React.lazy(() => import('@/components/tabs/PolygonEqTab'));
-const DerivativesTab = React.lazy(() => import('@/components/tabs/DerivativesTab').then(m => ({ default: m.DerivativesTab })));
-const TradingTab = React.lazy(() => import('@/components/tabs/TradingTab').then(m => ({ default: m.TradingTab })));
-const EquityTradingTab = React.lazy(() => import('@/components/tabs/equity-trading/EquityTradingTab'));
-const DBnomicsTab = React.lazy(() => import('@/components/tabs/DBnomicsTab'));
-const AkShareDataTab = React.lazy(() => import('@/components/tabs/AkShareDataTab'));
-const EconomicsTab = React.lazy(() => import('@/components/tabs/EconomicsTab'));
-const MaritimeTab = React.lazy(() => import('@/components/tabs/MaritimeTabDeck'));
-const ReportBuilderTab = React.lazy(() => import('@/components/tabs/ReportBuilderTab'));
-const DataMappingTab = React.lazy(() => import('@/components/tabs/data-mapping/DataMappingTab'));
-const ExcelTab = React.lazy(() => import('@/components/tabs/ExcelTab'));
-const Visualization3DTab = React.lazy(() => import('@/components/tabs/Visualization3DTab'));
-const PolymarketTab = React.lazy(() => import('@/components/tabs/PolymarketTabEnhanced'));
-const TradeVisualizationTab = React.lazy(() => import('@/components/tabs/TradeVisualizationTab'));
-const AlphaArenaTab = React.lazy(() => import('@/components/tabs/alpha-arena/AlphaArenaTab'));
+const EquityResearchTab = React.lazy(() => import('@/components/tabs/equity-research'));
+const AsiaMarketsTab = React.lazy(() => import('@/components/tabs/asia-markets'));
+const ScreenerTab = React.lazy(() => import('@/components/tabs/screener'));
+const BacktestingTab = React.lazy(() => import('@/components/tabs/backtesting'));
+const GeopoliticsTab = React.lazy(() => import('@/components/tabs/geopolitics'));
+const AIQuantLabTab = React.lazy(() => import('@/components/tabs/ai-quant-lab'));
+const CodeEditorTab = React.lazy(() => import('@/components/tabs/code-editor'));
+const NodeEditorTab = React.lazy(() => import('@/components/tabs/node-editor'));
+const PolygonEqTab = React.lazy(() => import('@/components/tabs/polygon-eq'));
+const DerivativesTab = React.lazy(() => import('@/components/tabs/derivatives').then(m => ({ default: m.DerivativesTab })));
+const CryptoTradingTab = React.lazy(() => import('@/components/tabs/crypto-trading').then(m => ({ default: m.CryptoTradingTab })));
+const EquityTradingTab = React.lazy(() => import('@/components/tabs/equity-trading'));
+const DBnomicsTab = React.lazy(() => import('@/components/tabs/dbnomics'));
+const AkShareDataTab = React.lazy(() => import('@/components/tabs/akshare-data'));
+const EconomicsTab = React.lazy(() => import('@/components/tabs/economics'));
+const MaritimeTab = React.lazy(() => import('@/components/tabs/maritime'));
+const ReportBuilderTab = React.lazy(() => import('@/components/tabs/report-builder'));
+const DataMappingTab = React.lazy(() => import('@/components/tabs/data-mapping'));
+const ExcelTab = React.lazy(() => import('@/components/tabs/excel'));
+const Visualization3DTab = React.lazy(() => import('@/components/tabs/visualization-3d'));
+const PolymarketTab = React.lazy(() => import('@/components/tabs/polymarket'));
+const TradeVisualizationTab = React.lazy(() => import('@/components/tabs/trade-visualization'));
+const AlphaArenaTab = React.lazy(() => import('@/components/tabs/alpha-arena'));
// Loading fallback component for lazy-loaded tabs
const TabLoadingFallback = () => (
@@ -751,6 +752,7 @@ function FinxeptTerminalContent() {
)}
</button>
{getClickableSessionDisplay()}
+ <HeaderSupportButtons />
<button
onClick={async () => {
setStatusMessage("Logging out...");
@@ -1120,7 +1122,7 @@ function FinxeptTerminalContent() {
</TabsContent>
<TabsContent value="trading" className="h-full m-0 p-0" forceMount>
<React.Suspense fallback={<TabLoadingFallback />}>
- <TradingTab />
+ <CryptoTradingTab />
</React.Suspense>
</TabsContent>
<TabsContent value="equity-trading" className="h-full m-0 p-0" forceMount>
diff --git a/fincept-terminal-desktop/src/components/tabs/DBnomicsTab.tsx b/fincept-terminal-desktop/src/components/tabs/DBnomicsTab.tsx
deleted file mode 100644
index 8fc2837b0..000000000
--- a/fincept-terminal-desktop/src/components/tabs/DBnomicsTab.tsx
+++ /dev/null
@@ -1,829 +0,0 @@
-import React, { useState } from 'react';
-import { RefreshCw, Download, Plus, Minus, Trash2 } from 'lucide-react';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-import { TabFooter } from '@/components/common/TabFooter';
-import { useTranslation } from 'react-i18next';
-import { getSetting, saveSetting } from '@/services/core/sqliteService';
-
-interface Provider {
- code: string;
- name: string;
-}
-
-interface Dataset {
- code: string;
- name: string;
-}
-
-interface Series {
- code: string;
- name: string;
- full_id: string;
-}
-
-interface Observation {
- period: string;
- value: number;
-}
-
-interface DataPoint {
- series_id: string;
- series_name: string;
- observations: Observation[];
- color: string;
-}
-
-type ChartType = 'line' | 'bar' | 'area' | 'scatter' | 'candlestick';
-
-export default function DBnomicsTab() {
- const { t } = useTranslation('dbnomics');
- const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
- const BASE_URL = 'https://api.db.nomics.world/v22';
- const COLORS = [colors.primary, colors.info, colors.secondary, colors.warning, colors.purple, colors.purple, colors.accent, colors.primary];
-
- const [providers, setProviders] = useState<Provider[]>([]);
- const [datasets, setDatasets] = useState<Dataset[]>([]);
- const [seriesList, setSeriesList] = useState<Series[]>([]);
- const [currentData, setCurrentData] = useState<DataPoint | null>(null);
-
- const [selectedProvider, setSelectedProvider] = useState<string | null>(null);
- const [selectedDataset, setSelectedDataset] = useState<string | null>(null);
- const [selectedSeries, setSelectedSeries] = useState<string | null>(null);
-
- const [status, setStatus] = useState('Loading providers...');
- const [loading, setLoading] = useState(false);
-
- const [slots, setSlots] = useState<DataPoint[][]>([[]]); // Array of slot arrays (each slot can have multiple series)
- const [slotChartTypes, setSlotChartTypes] = useState<ChartType[]>(['line']);
- const [activeView, setActiveView] = useState<'single' | 'comparison'>('single');
- const [singleViewSeries, setSingleViewSeries] = useState<DataPoint[]>([]);
- const [singleChartType, setSingleChartType] = useState<ChartType>('line');
-
- // Load providers and restore cached state on mount
- React.useEffect(() => {
- loadProviders();
- restoreState();
- }, []);
-
- // Save state whenever important data changes
- React.useEffect(() => {
- saveState();
- }, [singleViewSeries, slots, slotChartTypes, singleChartType, activeView]);
-
- const saveState = async () => {
- try {
- const state = {
- singleViewSeries,
- slots,
- slotChartTypes,
- singleChartType,
- activeView,
- timestamp: Date.now()
- };
- await saveSetting('dbnomics_state', JSON.stringify(state), 'dbnomics_tab');
- console.log('[DBnomicsTab] State saved to SQLite');
- } catch (error) {
- console.error('[DBnomicsTab] Failed to save state to SQLite:', error);
- }
- };
-
- const restoreState = async () => {
- try {
- const saved = await getSetting('dbnomics_state');
- if (saved) {
- const state = JSON.parse(saved);
- // Only restore if saved within last 24 hours
- if (state.timestamp && Date.now() - state.timestamp < 24 * 60 * 60 * 1000) {
- if (state.singleViewSeries) setSingleViewSeries(state.singleViewSeries);
- if (state.slots) setSlots(state.slots);
- if (state.slotChartTypes) setSlotChartTypes(state.slotChartTypes);
- if (state.singleChartType) setSingleChartType(state.singleChartType);
- if (state.activeView) setActiveView(state.activeView);
- setStatus('Restored from SQLite');
- console.log('[DBnomicsTab] State restored from SQLite');
- } else {
- console.log('[DBnomicsTab] Cached state expired (>24h)');
- }
- } else {
- console.log('[DBnomicsTab] No cached state in SQLite');
- }
- } catch (error) {
- console.error('[DBnomicsTab] Failed to restore state from SQLite:', error);
- }
- };
-
- // API Functions
- const loadProviders = async () => {
- try {
- setLoading(true);
- setStatus('Loading providers...');
- const response = await fetch(`${BASE_URL}/providers`);
- if (response.ok) {
- const data = await response.json();
- const providerList: Provider[] = (data?.providers?.docs || []).map((p: any) => ({
- code: p.code || '',
- name: p.name || p.code || ''
- }));
- setProviders(providerList);
- setStatus(`Loaded ${providerList.length} providers`);
- } else {
- setStatus(`Error: ${response.status}`);
- }
- } catch (error) {
- setStatus(`Error: ${error}`);
- } finally {
- setLoading(false);
- }
- };
-
- const loadDatasets = async (providerCode: string) => {
- try {
- setLoading(true);
- setStatus(`Loading datasets...`);
- const response = await fetch(`${BASE_URL}/datasets/${providerCode}`);
- if (response.ok) {
- const data = await response.json();
- const datasetList: Dataset[] = (data?.datasets?.docs || []).map((d: any) => ({
- code: d.code || '',
- name: d.name || d.code || ''
- }));
- setDatasets(datasetList);
- setSeriesList([]);
- setStatus(`Loaded ${datasetList.length} datasets`);
- } else {
- setStatus(`Error: ${response.status}`);
- }
- } catch (error) {
- setStatus(`Error: ${error}`);
- } finally {
- setLoading(false);
- }
- };
-
- const loadSeries = async (providerCode: string, datasetCode: string) => {
- try {
- setLoading(true);
- setStatus(`Loading series...`);
- const response = await fetch(`${BASE_URL}/series/${providerCode}/${datasetCode}?limit=50&observations=false`);
- if (response.ok) {
- const data = await response.json();
- const seriesArray: Series[] = (data?.series?.docs || []).map((s: any) => ({
- code: s.series_code || '',
- name: s.series_name || s.series_code || '',
- full_id: `${providerCode}/${datasetCode}/${s.series_code}`
- }));
- setSeriesList(seriesArray);
- setStatus(`Loaded ${seriesArray.length} series`);
- } else {
- setStatus(`Error: ${response.status}`);
- }
- } catch (error) {
- setStatus(`Error: ${error}`);
- } finally {
- setLoading(false);
- }
- };
-
- const loadSeriesData = async (fullSeriesId: string, seriesName: string) => {
- try {
- setLoading(true);
- setStatus(`Loading data...`);
- const [providerCode, datasetCode, seriesCode] = fullSeriesId.split('/');
- const response = await fetch(`${BASE_URL}/series/${providerCode}/${datasetCode}/${seriesCode}?observations=1&format=json`);
- if (response.ok) {
- const data = await response.json();
- const seriesDocs = data?.series?.docs || [];
- if (seriesDocs.length > 0) {
- const firstSeries = seriesDocs[0];
- let observations: Observation[] = [];
- if (firstSeries.period && firstSeries.value) {
- for (let i = 0; i < Math.min(firstSeries.period.length, firstSeries.value.length); i++) {
- if (firstSeries.value[i] !== null) {
- observations.push({ period: firstSeries.period[i], value: firstSeries.value[i] });
- }
- }
- }
- if (observations.length > 0) {
- const colorIndex = (singleViewSeries.length + slots.flat().length) % COLORS.length;
- setCurrentData({ series_id: fullSeriesId, series_name: seriesName, observations, color: COLORS[colorIndex] });
- setStatus(`Loaded ${observations.length} points`);
- } else {
- setStatus('No data found');
- }
- } else {
- setStatus('No data found');
- }
- } else {
- setStatus(`Error: ${response.status}`);
- }
- } catch (error) {
- setStatus(`Error: ${error}`);
- } finally {
- setLoading(false);
- }
- };
-
- const handleProviderSelect = (providerCode: string) => {
- setSelectedProvider(providerCode);
- setSelectedDataset(null);
- setSelectedSeries(null);
- setDatasets([]);
- setSeriesList([]);
- loadDatasets(providerCode);
- };
-
- const handleDatasetSelect = (datasetCode: string) => {
- setSelectedDataset(datasetCode);
- setSelectedSeries(null);
- setSeriesList([]);
- if (selectedProvider) loadSeries(selectedProvider, datasetCode);
- };
-
- const handleSeriesSelect = (series: Series) => {
- setSelectedSeries(series.full_id);
- loadSeriesData(series.full_id, series.name);
- };
-
- // Slot Management
- const addSlot = () => {
- setSlots([...slots, []]);
- setSlotChartTypes([...slotChartTypes, 'line']);
- setStatus(`Added slot ${slots.length + 1}`);
- };
-
- const removeSlot = (index: number) => {
- if (slots.length > 1) {
- setSlots(slots.filter((_, i) => i !== index));
- setSlotChartTypes(slotChartTypes.filter((_, i) => i !== index));
- setStatus(`Removed slot ${index + 1}`);
- }
- };
-
- const addToSlot = (slotIndex: number) => {
- if (currentData && slotIndex >= 0 && slotIndex < slots.length) {
- const newSlots = [...slots];
- newSlots[slotIndex] = [...newSlots[slotIndex], currentData];
- setSlots(newSlots);
- setStatus(`Added to slot ${slotIndex + 1}`);
- }
- };
-
- const removeFromSlot = (slotIndex: number, seriesIndex: number) => {
- const newSlots = [...slots];
- newSlots[slotIndex] = newSlots[slotIndex].filter((_, i) => i !== seriesIndex);
- setSlots(newSlots);
- setStatus(`Removed from slot ${slotIndex + 1}`);
- };
-
- const addToSingleView = () => {
- if (currentData) {
- setSingleViewSeries([...singleViewSeries, currentData]);
- setActiveView('single'); // Switch to single view
- setStatus('Added to single view');
- }
- };
-
- const removeFromSingleView = (index: number) => {
- setSingleViewSeries(singleViewSeries.filter((_, i) => i !== index));
- };
-
- const clearAllSlots = async () => {
- setSlots([[]]);
- setSlotChartTypes(['line']);
- setSingleViewSeries([]);
- // PURE SQLite - Clear by saving empty state
- await saveSetting('dbnomics_state', '', 'dbnomics_tab');
- setStatus('Cleared all');
- console.log('[DBnomicsTab] State cleared from SQLite');
- };
-
- const exportData = () => {
- if (!currentData) return;
- const csv = ['Period,Value', ...currentData.observations.map(obs => `${obs.period},${obs.value}`)].join('\n');
- const blob = new Blob([csv], { type: 'text/csv' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = `dbnomics_${Date.now()}.csv`;
- a.click();
- URL.revokeObjectURL(url);
- setStatus('Exported');
- };
-
- // Chart Rendering
- const renderChart = (seriesArray: DataPoint[], chartType: ChartType, compact = false) => {
- if (seriesArray.length === 0) return null;
-
- const w = compact ? '100%' : 800;
- const h: number = compact ? 240 : 400;
- const ml = 60;
- const mr = 20;
- const mt = 20;
- const mb = 50;
-
- // For compact view, calculate width dynamically
- const actualWidth: number = compact ? 380 : 800;
- const pw = actualWidth - ml - mr;
- const ph = h - mt - mb;
-
- // Aggregate all observations
- const allValues = seriesArray.flatMap(s => s.observations.map(o => o.value));
- const yMin = Math.min(...allValues) * 0.9;
- const yMax = Math.max(...allValues) * 1.1;
- const yRange = yMax - yMin;
-
- return (
- <svg width={w} height={h} viewBox={`0 0 ${actualWidth} ${h}`} preserveAspectRatio="xMidYMid meet" style={{ backgroundColor: colors.panel, width: '100%', height: 'auto', maxHeight: compact ? '240px' : '400px' }}>
- {/* Axes */}
- <line x1={ml} y1={mt} x2={ml} y2={h - mb} stroke={colors.textMuted} strokeWidth="1" />
- <line x1={ml} y1={h - mb} x2={actualWidth - mr} y2={h - mb} stroke={colors.textMuted} strokeWidth="1" />
-
- {/* Y-axis grid and labels */}
- {[0, 1, 2, 3, 4].map(i => {
- const val = yMin + (yRange * i) / 4;
- const y = h - mb - (ph * i) / 4;
- return (
- <g key={i}>
- <line x1={ml} y1={y} x2={actualWidth - mr} y2={y} stroke="#1a1a1a" strokeDasharray="2,2" />
- <text x={ml - 8} y={y + 3} textAnchor="end" fill={colors.textMuted} fontSize="9" fontFamily="monospace">
- {val.toFixed(1)}
- </text>
- </g>
- );
- })}
-
- {/* Render each series */}
- {seriesArray.map((series, sIdx) => {
- const sorted = [...series.observations].sort((a, b) => new Date(a.period).getTime() - new Date(b.period).getTime());
-
- return (
- <g key={sIdx}>
- {sorted.map((obs, idx) => {
- const x = ml + (pw * idx) / (sorted.length - 1 || 1);
- const y = h - mb - (ph * ((Number(obs.value) - yMin) / yRange));
- const barWidth = pw / sorted.length * 0.8;
-
- if (chartType === 'line' || chartType === 'area') {
- return (
- <g key={idx}>
- {chartType === 'area' && idx === 0 && (
- <polygon
- points={(() => {
- const points = sorted.map((o, i) => {
- const xi = ml + (pw * i) / (sorted.length - 1 || 1);
- const oValue = typeof o.value === 'number' ? o.value : Number(o.value);
- const yi = h - mb - (ph * ((oValue - yMin) / yRange));
- return `${xi},${yi}`;
- }).join(' ');
- return `${points} ${actualWidth - mr},${h - mb} ${ml},${h - mb}`;
- })()}
- fill={series.color}
- opacity="0.2"
- />
- )}
- <circle cx={x} cy={y} r="2" fill={series.color} />
- {idx < sorted.length - 1 && (
- <line
- x1={x}
- y1={y}
- x2={ml + (pw * (idx + 1)) / (sorted.length - 1 || 1)}
- y2={h - mb - (ph * ((Number(sorted[idx + 1].value) - yMin) / yRange))}
- stroke={series.color}
- strokeWidth="1.5"
- />
- )}
- </g>
- );
- } else if (chartType === 'bar') {
- return (
- <rect
- key={idx}
- x={x - barWidth / 2 + (sIdx * barWidth / seriesArray.length)}
- y={y}
- width={barWidth / seriesArray.length}
- height={h - mb - y}
- fill={series.color}
- opacity="0.8"
- />
- );
- } else if (chartType === 'scatter') {
- return <circle key={idx} cx={x} cy={y} r="3" fill={series.color} opacity="0.7" />;
- } else if (chartType === 'candlestick') {
- const nextObs = sorted[idx + 1];
- const open = obs.value;
- const close = nextObs ? nextObs.value : obs.value;
- const high = Math.max(open, close);
- const low = Math.min(open, close);
- const yHigh = h - mb - (ph * ((high - yMin) / yRange));
- const yLow = h - mb - (ph * ((low - yMin) / yRange));
- const yOpen = h - mb - (ph * ((open - yMin) / yRange));
- const yClose = h - mb - (ph * ((close - yMin) / yRange));
-
- return (
- <g key={idx}>
- <line x1={x} y1={yHigh} x2={x} y2={yLow} stroke={series.color} strokeWidth="1" />
- <rect
- x={x - 3}
- y={Math.min(yOpen, yClose)}
- width={6}
- height={Math.abs(yClose - yOpen) || 1}
- fill={close >= open ? colors.secondary : colors.alert}
- />
- </g>
- );
- }
- return null;
- })}
- </g>
- );
- })}
-
- {/* X-axis labels */}
- {seriesArray[0] && seriesArray[0].observations.slice().sort((a, b) => new Date(a.period).getTime() - new Date(b.period).getTime()).map((obs, idx, arr) => {
- if (idx % Math.max(1, Math.floor(arr.length / 6)) !== 0 && idx !== arr.length - 1) return null;
- const x = ml + (pw * idx) / (arr.length - 1 || 1);
- return (
- <text key={idx} x={x} y={h - mb + 15} textAnchor="middle" fill={colors.textMuted} fontSize="8" fontFamily="monospace">
- {obs.period.substring(0, 7)}
- </text>
- );
- })}
-
- {/* Legend */}
- {seriesArray.map((series, idx) => (
- <g key={idx}>
- <rect x={ml + idx * 120} y={5} width={10} height={10} fill={series.color} />
- <text x={ml + idx * 120 + 15} y={13} fill={colors.text} fontSize="9" fontFamily="monospace">
- {series.series_name.substring(0, 12)}
- </text>
- </g>
- ))}
- </svg>
- );
- };
-
- return (
- <div style={{ width: '100%', height: '100%', backgroundColor: colors.background, color: colors.text, fontFamily: 'Consolas, monospace', fontSize: '11px', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
- <style>{`
- /* Custom scrollbar styles */
- *::-webkit-scrollbar {
- width: 8px;
- height: 8px;
- }
- *::-webkit-scrollbar-track {
- background: #1a1a1a;
- }
- *::-webkit-scrollbar-thumb {
- background: colors.textMuted;
- border-radius: 4px;
- }
- *::-webkit-scrollbar-thumb:hover {
- background: #525252;
- }
- `}</style>
- {/* Header */}
- <div style={{ padding: '8px 12px', borderBottom: '1px solid colors.textMuted', display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap' }}>
- <span style={{ color: colors.primary, fontWeight: 'bold' }}>{t('title')}</span>
- <span style={{ color: colors.secondary, fontSize: '10px' }}>● {status}</span>
- <span style={{ color: colors.warning, fontSize: '10px' }}>Providers: {providers.length}</span>
- <div style={{ flex: 1 }}></div>
- <button onClick={loadProviders} disabled={loading} style={{ padding: '3px 10px', backgroundColor: '#2a2a2a', color: colors.text, border: '1px solid colors.textMuted', cursor: loading ? 'not-allowed' : 'pointer', fontSize: '9px' }}>
- {t('toolbar.fetch')}
- </button>
- <button onClick={() => currentData && loadSeriesData(currentData.series_id, currentData.series_name)} disabled={!currentData} style={{ padding: '3px 10px', backgroundColor: '#2a2a2a', color: colors.text, border: '1px solid colors.textMuted', cursor: !currentData ? 'not-allowed' : 'pointer', fontSize: '9px' }}>
- <RefreshCw size={10} style={{ display: 'inline', marginRight: '4px' }} />{t('toolbar.refresh')}
- </button>
- <button onClick={exportData} disabled={!currentData} style={{ padding: '3px 10px', backgroundColor: '#2a2a2a', color: colors.text, border: '1px solid colors.textMuted', cursor: !currentData ? 'not-allowed' : 'pointer', fontSize: '9px' }}>
- <Download size={10} style={{ display: 'inline', marginRight: '4px' }} />{t('toolbar.export')}
- </button>
- </div>
-
- {/* Main Content */}
- <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
- {/* Left Panel */}
- <div style={{ width: '320px', borderRight: '1px solid colors.textMuted', display: 'flex', flexDirection: 'column', backgroundColor: colors.panel }}>
- <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', padding: '8px' }}>
- <div style={{ color: colors.primary, fontSize: '10px', marginBottom: '4px' }}>1. PROVIDER</div>
- <div
- style={{
- width: '100%',
- height: '140px',
- backgroundColor: '#1a1a1a',
- border: '1px solid colors.textMuted',
- marginBottom: '12px',
- overflowY: 'auto',
- overflowX: 'hidden',
- scrollbarWidth: 'thin',
- scrollbarColor: 'colors.textMuted #1a1a1a'
- }}
- >
- {providers.map(p => (
- <div
- key={p.code}
- onClick={() => handleProviderSelect(p.code)}
- style={{
- padding: '6px 8px',
- fontSize: '10px',
- color: selectedProvider === p.code ? '#fff' : colors.text,
- backgroundColor: selectedProvider === p.code ? colors.primary : 'transparent',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace',
- lineHeight: '1.4',
- wordWrap: 'break-word',
- whiteSpace: 'normal',
- borderBottom: '1px solid colors.panel'
- }}
- onMouseEnter={(e) => {
- if (selectedProvider !== p.code) {
- e.currentTarget.style.backgroundColor = '#2a2a2a';
- }
- }}
- onMouseLeave={(e) => {
- if (selectedProvider !== p.code) {
- e.currentTarget.style.backgroundColor = 'transparent';
- }
- }}
- >
- {p.code} - {p.name}
- </div>
- ))}
- </div>
-
- <div style={{ color: colors.primary, fontSize: '10px', marginBottom: '4px' }}>2. DATASET</div>
- <div
- style={{
- width: '100%',
- height: '140px',
- backgroundColor: '#1a1a1a',
- border: '1px solid colors.textMuted',
- marginBottom: '12px',
- overflowY: 'auto',
- overflowX: 'hidden',
- scrollbarWidth: 'thin',
- scrollbarColor: 'colors.textMuted #1a1a1a'
- }}
- >
- {datasets.map(d => (
- <div
- key={d.code}
- onClick={() => handleDatasetSelect(d.code)}
- style={{
- padding: '6px 8px',
- fontSize: '10px',
- color: selectedDataset === d.code ? '#fff' : colors.text,
- backgroundColor: selectedDataset === d.code ? colors.primary : 'transparent',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace',
- lineHeight: '1.4',
- wordWrap: 'break-word',
- whiteSpace: 'normal',
- borderBottom: '1px solid colors.panel'
- }}
- onMouseEnter={(e) => {
- if (selectedDataset !== d.code) {
- e.currentTarget.style.backgroundColor = '#2a2a2a';
- }
- }}
- onMouseLeave={(e) => {
- if (selectedDataset !== d.code) {
- e.currentTarget.style.backgroundColor = 'transparent';
- }
- }}
- >
- {d.code} - {d.name}
- </div>
- ))}
- </div>
-
- <div style={{ color: colors.primary, fontSize: '10px', marginBottom: '4px' }}>3. SERIES</div>
- <div
- style={{
- width: '100%',
- height: '140px',
- backgroundColor: '#1a1a1a',
- border: '1px solid colors.textMuted',
- marginBottom: '12px',
- overflowY: 'auto',
- overflowX: 'hidden',
- scrollbarWidth: 'thin',
- scrollbarColor: 'colors.textMuted #1a1a1a'
- }}
- >
- {seriesList.map(s => (
- <div
- key={s.full_id}
- onClick={() => handleSeriesSelect(s)}
- style={{
- padding: '6px 8px',
- fontSize: '10px',
- color: selectedSeries === s.full_id ? '#fff' : colors.text,
- backgroundColor: selectedSeries === s.full_id ? colors.primary : 'transparent',
- cursor: 'pointer',
- fontFamily: 'Consolas, monospace',
- lineHeight: '1.4',
- wordWrap: 'break-word',
- whiteSpace: 'normal',
- borderBottom: '1px solid colors.panel'
- }}
- onMouseEnter={(e) => {
- if (selectedSeries !== s.full_id) {
- e.currentTarget.style.backgroundColor = '#2a2a2a';
- }
- }}
- onMouseLeave={(e) => {
- if (selectedSeries !== s.full_id) {
- e.currentTarget.style.backgroundColor = 'transparent';
- }
- }}
- >
- {s.code} - {s.name}
- </div>
- ))}
- </div>
-
- <div style={{ height: '1px', backgroundColor: colors.textMuted, margin: '8px 0' }}></div>
-
- {/* Actions */}
- <div style={{ display: 'flex', gap: '4px', marginBottom: '8px' }}>
- <button onClick={addToSingleView} disabled={!currentData} style={{ flex: 1, padding: '4px', backgroundColor: '#1a1a1a', color: colors.text, border: '1px solid colors.textMuted', cursor: !currentData ? 'not-allowed' : 'pointer', fontSize: '9px' }}>
- ADD TO SINGLE
- </button>
- <button onClick={clearAllSlots} style={{ padding: '4px 8px', backgroundColor: '#1a1a1a', color: colors.alert, border: '1px solid colors.textMuted', cursor: 'pointer', fontSize: '9px' }}>
- <Trash2 size={10} />
- </button>
- </div>
-
- <div style={{ color: colors.primary, fontSize: '10px', marginBottom: '6px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <span>COMPARISON SLOTS</span>
- <button onClick={addSlot} style={{ padding: '2px 6px', backgroundColor: '#1a1a1a', color: colors.secondary, border: '1px solid colors.textMuted', cursor: 'pointer', fontSize: '9px' }}>
- <Plus size={10} />
- </button>
- </div>
-
- <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
- {slots.map((slot, idx) => (
- <div key={idx} style={{ marginBottom: '6px', padding: '6px', backgroundColor: '#1a1a1a', border: '1px solid colors.textMuted', borderRadius: '2px' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
- <span style={{ color: colors.warning, fontSize: '9px' }}>SLOT {idx + 1} ({slot.length})</span>
- <div style={{ display: 'flex', gap: '2px' }}>
- <button onClick={() => addToSlot(idx)} disabled={!currentData} style={{ padding: '2px 4px', backgroundColor: colors.panel, color: colors.secondary, border: '1px solid colors.textMuted', cursor: !currentData ? 'not-allowed' : 'pointer', fontSize: '8px' }}>
- <Plus size={8} />
- </button>
- {slots.length > 1 && (
- <button onClick={() => removeSlot(idx)} style={{ padding: '2px 4px', backgroundColor: colors.panel, color: colors.alert, border: '1px solid colors.textMuted', cursor: 'pointer', fontSize: '8px' }}>
- <Minus size={8} />
- </button>
- )}
- </div>
- </div>
- {slot.map((s, sIdx) => (
- <div key={sIdx} style={{ fontSize: '8px', color: colors.textMuted, display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '2px' }}>
- <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={s.series_name}>{s.series_name}</span>
- <button onClick={() => removeFromSlot(idx, sIdx)} style={{ padding: '1px 3px', backgroundColor: 'transparent', color: colors.alert, border: 'none', cursor: 'pointer', fontSize: '8px' }}>
- ×
- </button>
- </div>
- ))}
- {slot.length === 0 && <div style={{ fontSize: '8px', color: colors.textMuted, textAlign: 'center' }}>Empty</div>}
- </div>
- ))}
- </div>
- </div>
- </div>
-
- {/* Right Panel */}
- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
- {/* View Toggle */}
- <div style={{ padding: '8px 12px', borderBottom: '1px solid colors.textMuted', display: 'flex', gap: '8px', alignItems: 'center' }}>
- <button onClick={() => setActiveView('single')} style={{ padding: '4px 12px', backgroundColor: activeView === 'single' ? colors.primary : '#2a2a2a', color: '#fff', border: '1px solid colors.textMuted', cursor: 'pointer', fontSize: '10px' }}>
- SINGLE
- </button>
- <button onClick={() => setActiveView('comparison')} style={{ padding: '4px 12px', backgroundColor: activeView === 'comparison' ? colors.primary : '#2a2a2a', color: '#fff', border: '1px solid colors.textMuted', cursor: 'pointer', fontSize: '10px' }}>
- COMPARE
- </button>
-
- {activeView === 'single' ? (
- <>
- <div style={{ color: colors.textMuted, fontSize: '9px', marginLeft: '8px' }}>Chart Type:</div>
- {(['line', 'bar', 'area', 'scatter', 'candlestick'] as ChartType[]).map(type => (
- <button key={type} onClick={() => setSingleChartType(type)} style={{ padding: '3px 8px', backgroundColor: singleChartType === type ? colors.info : '#2a2a2a', color: '#fff', border: '1px solid colors.textMuted', cursor: 'pointer', fontSize: '9px', textTransform: 'uppercase' }}>
- {type}
- </button>
- ))}
- </>
- ) : null}
- </div>
-
- {/* Content Area */}
- <div style={{ flex: 1, overflowY: 'auto', padding: '12px' }}>
- {activeView === 'single' ? (
- <div>
- <div style={{ marginBottom: '12px' }}>
- <div style={{ color: colors.primary, fontSize: '11px', marginBottom: '6px' }}>SINGLE VIEW ({singleViewSeries.length} series)</div>
- {singleViewSeries.map((s, idx) => (
- <div key={idx} style={{ display: 'inline-flex', alignItems: 'center', gap: '4px', padding: '3px 6px', backgroundColor: '#1a1a1a', border: '1px solid colors.textMuted', borderRadius: '2px', marginRight: '4px', marginBottom: '4px', fontSize: '9px' }}>
- <div style={{ width: '8px', height: '8px', backgroundColor: s.color, borderRadius: '50%' }}></div>
- <span>{s.series_name.substring(0, 20)}</span>
- <button onClick={() => removeFromSingleView(idx)} style={{ padding: '0 4px', backgroundColor: 'transparent', color: colors.alert, border: 'none', cursor: 'pointer', fontSize: '10px' }}>×</button>
- </div>
- ))}
- </div>
-
- {singleViewSeries.length > 0 ? (
- <>
- {renderChart(singleViewSeries, singleChartType)}
-
- {/* Data Table */}
- <div style={{ marginTop: '24px' }}>
- <div style={{ color: colors.primary, fontSize: '11px', marginBottom: '8px' }}>DATA TABLE</div>
- <div style={{ overflowX: 'auto', overflowY: 'auto', maxHeight: '300px', border: '1px solid colors.textMuted', backgroundColor: colors.panel }}>
- <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>
- <thead style={{ position: 'sticky', top: 0, backgroundColor: '#1a1a1a', zIndex: 1 }}>
- <tr style={{ borderBottom: '2px solid colors.textMuted' }}>
- <th style={{ padding: '8px 12px', textAlign: 'left', color: colors.primary, fontWeight: 'bold', whiteSpace: 'nowrap' }}>Period</th>
- {singleViewSeries.map((series, idx) => (
- <th key={idx} style={{ padding: '8px 12px', textAlign: 'right', fontWeight: 'bold', whiteSpace: 'nowrap' }}>
- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '6px' }}>
- <div style={{ width: '8px', height: '8px', backgroundColor: series.color, borderRadius: '50%' }}></div>
- <span style={{ color: series.color }}>{series.series_name.substring(0, 25)}</span>
- </div>
- </th>
- ))}
- </tr>
- </thead>
- <tbody>
- {(() => {
- // Get all unique periods across all series
- const allPeriods = Array.from(
- new Set(singleViewSeries.flatMap(s => s.observations.map(o => o.period)))
- ).sort((a, b) => new Date(b).getTime() - new Date(a).getTime());
-
- return allPeriods.slice(0, 50).map((period, idx) => (
- <tr key={idx} style={{ borderBottom: '1px solid #1a1a1a' }}>
- <td style={{ padding: '6px 12px', color: colors.text, whiteSpace: 'nowrap', fontWeight: 'bold' }}>{period}</td>
- {singleViewSeries.map((series, sIdx) => {
- const obs = series.observations.find(o => o.period === period);
- const value = obs ? (typeof obs.value === 'number' ? obs.value : Number(obs.value)) : null;
- return (
- <td key={sIdx} style={{ padding: '6px 12px', textAlign: 'right', color: value !== null ? '#a3a3a3' : colors.textMuted, whiteSpace: 'nowrap' }}>
- {value !== null && !isNaN(value) ? value.toFixed(4) : '—'}
- </td>
- );
- })}
- </tr>
- ));
- })()}
- </tbody>
- </table>
- </div>
- <div style={{ color: colors.textMuted, fontSize: '9px', marginTop: '6px', textAlign: 'right' }}>
- Showing latest 50 periods
- </div>
- </div>
- </>
- ) : (
- <div style={{ color: colors.textMuted, textAlign: 'center', paddingTop: '40px' }}>Add series to view</div>
- )}
- </div>
- ) : (
- <div>
- <div style={{ color: colors.primary, marginBottom: '12px', fontSize: '11px' }}>COMPARISON DASHBOARD</div>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(380px, 1fr))', gap: '16px' }}>
- {slots.map((slot, idx) => (
- <div key={idx} style={{ border: '1px solid colors.textMuted', padding: '12px', backgroundColor: colors.panel, minHeight: '280px', display: 'flex', flexDirection: 'column' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
- <div style={{ color: colors.warning, fontSize: '10px' }}>SLOT {idx + 1}</div>
- <select value={slotChartTypes[idx]} onChange={(e) => { const newTypes = [...slotChartTypes]; newTypes[idx] = e.target.value as ChartType; setSlotChartTypes(newTypes); }} style={{ padding: '2px 4px', backgroundColor: '#1a1a1a', color: colors.text, border: '1px solid colors.textMuted', fontSize: '8px', fontFamily: 'Consolas, monospace' }}>
- <option value="line">LINE</option>
- <option value="bar">BAR</option>
- <option value="area">AREA</option>
- <option value="scatter">SCATTER</option>
- <option value="candlestick">CANDLE</option>
- </select>
- </div>
- <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '240px' }}>
- {slot.length > 0 ? renderChart(slot, slotChartTypes[idx], true) : <div style={{ color: colors.textMuted, textAlign: 'center', fontSize: '10px' }}>Empty Slot</div>}
- </div>
- </div>
- ))}
- </div>
- </div>
- )}
- </div>
- </div>
- </div>
-
- <TabFooter
- tabName="DBNOMICS ECONOMIC DATABASE"
- leftInfo={[
- { label: `Providers: ${providers.length}`, color: colors.textMuted },
- { label: `Datasets: ${datasets.length}`, color: colors.textMuted },
- { label: `Series: ${seriesList.length}`, color: colors.textMuted },
- ]}
- statusInfo={`${status} | Dataset: ${selectedDataset ? 'Selected' : 'None'}`}
- backgroundColor={colors.panel}
- borderColor={colors.textMuted}
- />
- </div>
- );
-}
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/tabs/ForumTab.tsx b/fincept-terminal-desktop/src/components/tabs/ForumTab.tsx
index cb5a20390..add28e421 100644
--- a/fincept-terminal-desktop/src/components/tabs/ForumTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ForumTab.tsx
@@ -1,1764 +1,7 @@
-import React, { useState, useEffect, useRef } from 'react';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-import { useAuth } from '../../contexts/AuthContext';
-import { ForumApiService, ForumPost as APIForumPost, ForumCategory, ForumStats, ForumComment as APIForumComment } from '../../services/forum/forumApi';
-import { sqliteService, getSetting, saveSetting } from '../../services/core/sqliteService';
-import { TabFooter } from '@/components/common/TabFooter';
-import { useTranslation } from 'react-i18next';
+// Forum Tab - Re-export from modular implementation
+// Original 1764 lines refactored into organized folder structure
+// See ./forum/ folder for implementation
-interface ForumPost {
- id: string;
- time: string;
- author: string;
- title: string;
- content: string;
- category: string;
- categoryId: number;
- tags: string[];
- views: number;
- replies: number;
- likes: number;
- dislikes: number;
- sentiment: 'BULLISH' | 'BEARISH' | 'NEUTRAL';
- priority: 'HOT' | 'TRENDING' | 'NORMAL';
- verified: boolean;
-}
-
-interface ForumComment {
- id: string;
- author: string;
- content: string;
- time: string;
- likes: number;
- dislikes: number;
-}
-
-interface ForumUser {
- username: string;
- reputation: number;
- posts: number;
- joined: string;
- status: 'ONLINE' | 'OFFLINE';
-}
-
-const ForumTab: React.FC = () => {
- const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
- const { t } = useTranslation('forum');
- const { session } = useAuth();
- const [currentTime, setCurrentTime] = useState(new Date());
- const [activeCategory, setActiveCategory] = useState('ALL');
- const [sortBy, setSortBy] = useState('latest');
- const [onlineUsers, setOnlineUsers] = useState(1247);
- const [isLoading, setIsLoading] = useState(false);
- const [lastRefreshTime, setLastRefreshTime] = useState<Date | null>(null);
- const [isRefreshing, setIsRefreshing] = useState(false);
-
- // Auto-refresh interval ref
- const autoRefreshIntervalRef = useRef<NodeJS.Timeout | null>(null);
-
- // Modal states
- const [showCreatePost, setShowCreatePost] = useState(false);
- const [showPostDetail, setShowPostDetail] = useState(false);
- const [showSearch, setShowSearch] = useState(false);
- const [showProfile, setShowProfile] = useState(false);
- const [showEditProfile, setShowEditProfile] = useState(false);
-
- // Selected data
- const [selectedPost, setSelectedPost] = useState<ForumPost | null>(null);
- const [postComments, setPostComments] = useState<ForumComment[]>([]);
- const [selectedUsername, setSelectedUsername] = useState<string>('');
-
- // Form states
- const [newPostTitle, setNewPostTitle] = useState('');
- const [newPostContent, setNewPostContent] = useState('');
- const [newComment, setNewComment] = useState('');
- const [searchQuery, setSearchQuery] = useState('');
- const [searchResults, setSearchResults] = useState<ForumPost[]>([]);
-
- // Profile states
- const [userProfile, setUserProfile] = useState<any>(null);
- const [profileEdit, setProfileEdit] = useState({
- display_name: '',
- bio: '',
- avatar_color: colors.primary,
- signature: ''
- });
-
- // API Data states
- const [categories, setCategories] = useState<Array<{ name: string; count: number; color: string; id: number }>>([]);
- const [forumPosts, setForumPosts] = useState<ForumPost[]>([]);
- const [forumStats, setForumStats] = useState<ForumStats | null>(null);
- const [trendingTopics, setTrendingTopics] = useState<Array<{ topic: string; mentions: number; sentiment: string; change: string }>>([]);
- const [recentActivity, setRecentActivity] = useState<Array<{ user: string; action: string; target: string; time: string }>>([]);
-
- // Fincept color scheme - use actual theme colors
- const FINCEPT_ORANGE = colors.primary;
- const FINCEPT_WHITE = colors.text;
- const FINCEPT_RED = colors.alert;
- const FINCEPT_GREEN = colors.secondary;
- const FINCEPT_YELLOW = colors.warning;
- const FINCEPT_GRAY = colors.textMuted;
- const FINCEPT_BLUE = colors.info;
- const FINCEPT_PURPLE = colors.purple;
- const FINCEPT_CYAN = colors.accent;
- const FINCEPT_DARK_BG = colors.background;
- const FINCEPT_PANEL_BG = colors.panel;
-
- // Top contributors - static for now
- const topContributors: ForumUser[] = [
- { username: 'QuantTrader_Pro', reputation: 8947, posts: 1234, joined: '2021-03-15', status: 'ONLINE' },
- { username: 'CryptoWhale_2024', reputation: 7823, posts: 892, joined: '2020-11-22', status: 'ONLINE' },
- { username: 'OptionsFlow_Alert', reputation: 7456, posts: 1567, joined: '2022-01-08', status: 'ONLINE' },
- { username: 'MacroHedgeFund', reputation: 6789, posts: 743, joined: '2021-07-19', status: 'OFFLINE' },
- { username: 'TechInvestor88', reputation: 6234, posts: 654, joined: '2022-05-12', status: 'ONLINE' },
- { username: 'EnergyAnalyst_TX', reputation: 5892, posts: 521, joined: '2021-09-30', status: 'ONLINE' }
- ];
-
- // Get API credentials
- const getApiCredentials = async () => {
- const apiKey = session?.api_key || await getSetting('fincept_api_key') || undefined;
- const deviceId = session?.device_id || await getSetting('fincept_device_id') || undefined;
- return { apiKey, deviceId };
- };
-
- // Convert API post to UI format
- const convertApiPostToUIFormat = (apiPost: APIForumPost): ForumPost => {
- const likes = apiPost.likes || 0;
- const dislikes = apiPost.dislikes || 0;
- const voteScore = likes - dislikes;
- const sentiment: 'BULLISH' | 'BEARISH' | 'NEUTRAL' = voteScore > 10 ? 'BULLISH' : voteScore < -5 ? 'BEARISH' : 'NEUTRAL';
- const priority: 'HOT' | 'TRENDING' | 'NORMAL' = likes > 300 ? 'HOT' : likes > 150 ? 'TRENDING' : 'NORMAL';
-
- const tagMatches = apiPost.content.match(/#\w+/g) || [];
- const tags = tagMatches.slice(0, 5).map(tag => tag.substring(1));
-
- return {
- id: apiPost.post_uuid,
- time: new Date(apiPost.created_at).toLocaleTimeString('en-US', { hour12: false }),
- author: apiPost.author_display_name || 'Anonymous',
- title: apiPost.title,
- content: apiPost.content,
- category: apiPost.category_name?.toUpperCase() || 'GENERAL',
- categoryId: apiPost.category_id || 0,
- tags: tags.length > 0 ? tags : ['DISCUSSION'],
- views: apiPost.views || 0,
- replies: apiPost.reply_count || 0,
- likes,
- dislikes,
- sentiment,
- priority,
- verified: likes > 100
- };
- };
-
- // Convert API comment to UI format
- const convertApiCommentToUIFormat = (apiComment: APIForumComment): ForumComment => {
- return {
- id: apiComment.comment_uuid,
- author: apiComment.author_display_name || 'Anonymous',
- content: apiComment.content,
- time: new Date(apiComment.created_at).toLocaleTimeString('en-US', { hour12: false }),
- likes: apiComment.likes || 0,
- dislikes: apiComment.dislikes || 0
- };
- };
-
- // ENDPOINT 1: Fetch forum categories (with caching)
- const fetchCategories = async (forceRefresh: boolean = false) => {
- try {
- // Try to load from cache first (unless forcing refresh)
- if (!forceRefresh) {
- const cachedCategories = await sqliteService.getCachedForumCategories(5);
- if (cachedCategories) {
- setCategories(cachedCategories);
- return;
- }
- }
-
- // Fetch from API
- const { apiKey, deviceId } = await getApiCredentials();
- const response = await ForumApiService.getCategories(apiKey, deviceId);
-
- if (response.success && response.data?.data?.categories) {
- const apiCategories = response.data.data.categories;
- const categoryColors = [
- FINCEPT_BLUE, FINCEPT_PURPLE, FINCEPT_CYAN, FINCEPT_YELLOW,
- FINCEPT_GREEN, FINCEPT_ORANGE, FINCEPT_RED, FINCEPT_PURPLE
- ];
-
- const formattedCategories = [
- { name: 'ALL', count: apiCategories.reduce((sum: number, cat: ForumCategory) => sum + cat.post_count, 0), color: FINCEPT_WHITE, id: 0 },
- ...apiCategories.map((cat: ForumCategory, index: number) => ({
- name: cat.name.toUpperCase(),
- count: cat.post_count,
- color: categoryColors[index % categoryColors.length],
- id: cat.id
- }))
- ];
-
- setCategories(formattedCategories);
-
- // Cache the formatted categories
- await sqliteService.cacheForumCategories(formattedCategories);
- }
- } catch (error) {
- // Silently fail - backend may not be available
- console.debug('Forum API not available (categories)');
- }
- };
-
- // ENDPOINT 2 & 6: Fetch forum posts (by category or trending) with caching
- const fetchPosts = async (forceRefresh: boolean = false) => {
- setIsLoading(true);
- try {
- const categoryId = activeCategory === 'ALL' ? null : categories.find(c => c.name === activeCategory)?.id || null;
-
- // Fetch from API
- const { apiKey, deviceId } = await getApiCredentials();
- let response;
-
- if (activeCategory === 'ALL') {
- // Fetch from all categories by getting from each
- const allPosts: any[] = [];
- for (const cat of categories.filter(c => c.id !== undefined)) {
- const catResponse = await ForumApiService.getPostsByCategory(cat.id, sortBy, 20, apiKey, deviceId);
- if (catResponse?.success && catResponse.data) {
- const posts = (catResponse.data as any).data?.posts || [];
- allPosts.push(...posts);
- }
- }
- // Create fake response structure
- response = {
- success: true,
- data: {
- data: {
- posts: allPosts
- }
- }
- };
- } else {
- if (categoryId) {
- response = await ForumApiService.getPostsByCategory(categoryId, sortBy, 20, apiKey, deviceId);
- }
- }
-
- if (response?.success && response.data) {
- const responseData = response.data as any;
- const posts = responseData.data?.posts || [];
-
- if (posts.length > 0) {
- const formattedPosts = posts.map(convertApiPostToUIFormat);
- setForumPosts(formattedPosts);
-
- // Cache the formatted posts
- await sqliteService.cacheForumPosts(categoryId, sortBy, formattedPosts);
- } else {
- setForumPosts([]);
- }
- }
- } catch (error) {
- // Silently fail - backend may not be available
- console.debug('Forum API not available (posts)');
- } finally {
- setIsLoading(false);
- }
- };
-
- // ENDPOINT 5: Fetch forum statistics (with caching)
- const fetchForumStats = async (forceRefresh: boolean = false) => {
- try {
- // Try to load from cache first (unless forcing refresh)
- if (!forceRefresh) {
- const cachedStats = await sqliteService.getCachedForumStats(5);
- if (cachedStats) {
- setForumStats(cachedStats);
- if (cachedStats.active_users) {
- setOnlineUsers(cachedStats.active_users);
- }
- return;
- }
- }
-
- // Fetch from API
- const { apiKey, deviceId } = await getApiCredentials();
- const response = await ForumApiService.getForumStats(apiKey, deviceId);
-
- if (response.success && response.data?.data) {
- setForumStats(response.data.data);
- if (response.data.data.active_users) {
- setOnlineUsers(response.data.data.active_users);
- }
-
- // Cache the stats
- await sqliteService.cacheForumStats(response.data.data);
- }
- } catch (error) {
- // Silently fail - backend may not be available
- console.debug('Forum API not available (stats)');
- }
- };
-
- // ENDPOINT 7: Create new post
- const handleCreatePost = async () => {
- // Validation
- if (!newPostTitle.trim()) {
- alert('Please enter a post title');
- return;
- }
- if (newPostTitle.trim().length < 5) {
- alert('Post title must be at least 5 characters long');
- return;
- }
- if (newPostTitle.trim().length > 500) {
- alert('Post title must be less than 500 characters');
- return;
- }
- if (!newPostContent.trim()) {
- alert('Please enter post content');
- return;
- }
- if (newPostContent.trim().length < 10) {
- alert('Post content must be at least 10 characters long');
- return;
- }
-
- const { apiKey, deviceId } = await getApiCredentials();
- if (!apiKey) {
- alert('You must be logged in to create posts');
- return;
- }
-
- const categoryId = categories.find(c => c.name === activeCategory)?.id || categories[1]?.id || 1;
-
- try {
- const response = await ForumApiService.createPost(
- categoryId,
- { title: newPostTitle.trim(), content: newPostContent.trim() },
- apiKey,
- deviceId
- );
-
- if (response.success) {
- alert('Post created successfully!');
- setShowCreatePost(false);
- setNewPostTitle('');
- setNewPostContent('');
- fetchPosts(true); // Refresh posts (force refresh to bypass cache)
- } else {
- alert(`Failed to create post: ${response.error || response.data?.message || 'Unknown error'}`);
- }
- } catch (error) {
- alert('Error creating post');
- }
- };
-
- // ENDPOINT 3 & 4: View post details with comments
- const handleViewPost = async (post: ForumPost) => {
- setSelectedPost(post);
- setShowPostDetail(true);
-
- const { apiKey, deviceId } = await getApiCredentials();
- try {
- const response = await ForumApiService.getPostDetails(post.id, apiKey, deviceId);
-
- if (response.success && response.data?.data) {
- const comments = response.data.data.comments || [];
- const formattedComments = comments.map(convertApiCommentToUIFormat);
- setPostComments(formattedComments);
- }
- } catch (error) {
- // Silently fail - backend may not be available
- console.debug('Forum API not available (post details)');
- }
- };
-
- // ENDPOINT 8: Add comment to post
- const handleAddComment = async () => {
- if (!newComment.trim() || !selectedPost) return;
-
- const { apiKey, deviceId } = await getApiCredentials();
- if (!apiKey) {
- alert('You must be logged in to comment');
- return;
- }
-
- try {
- const response = await ForumApiService.addComment(
- selectedPost.id,
- { content: newComment },
- apiKey,
- deviceId
- );
-
- if (response.success) {
- setNewComment('');
- // Refresh post details
- handleViewPost(selectedPost);
- } else {
- alert(`Failed to add comment: ${response.error || 'Unknown error'}`);
- }
- } catch (error) {
- alert('Error adding comment');
- }
- };
-
- // ENDPOINT 9: Vote on post
- const handleVotePost = async (postId: string, voteType: 'up' | 'down') => {
- const { apiKey, deviceId } = await getApiCredentials();
- if (!apiKey) {
- alert('You must be logged in to vote');
- return;
- }
-
- try {
- const response = await ForumApiService.voteOnPost(postId, voteType, apiKey, deviceId);
-
- if (response.success) {
- fetchPosts(true); // Refresh posts to show updated vote counts (force refresh)
- if (selectedPost && selectedPost.id === postId) {
- handleViewPost(selectedPost); // Refresh post detail if viewing
- }
- } else {
- alert(`Vote failed: ${response.error || 'Unknown error'}`);
- }
- } catch (error) {
- // Silently handle error
- }
- };
-
- // ENDPOINT 10: Vote on comment
- const handleVoteComment = async (commentId: string, voteType: 'up' | 'down') => {
- const { apiKey, deviceId } = await getApiCredentials();
- if (!apiKey) {
- alert('You must be logged in to vote');
- return;
- }
-
- try {
- const response = await ForumApiService.voteOnComment(commentId, voteType, apiKey, deviceId);
-
- if (response.success && selectedPost) {
- handleViewPost(selectedPost); // Refresh comments
- }
- } catch (error) {
- // Silently handle error
- }
- };
-
- // ENDPOINT 4: Search forum
- const handleSearch = async () => {
- if (!searchQuery.trim()) return;
-
- const { apiKey, deviceId } = await getApiCredentials();
- setIsLoading(true);
-
- try {
- const response = await ForumApiService.searchPosts(searchQuery, 'all', 20, apiKey, deviceId);
-
- if (response.success && response.data?.data?.results?.posts) {
- const posts = response.data.data.results.posts;
- const formattedPosts = posts.map(convertApiPostToUIFormat);
- setSearchResults(formattedPosts);
- }
- } catch (error) {
- // Silently handle error
- } finally {
- setIsLoading(false);
- }
- };
-
- // ENDPOINT 12: Get my profile
- const handleViewMyProfile = async () => {
- const { apiKey, deviceId } = await getApiCredentials();
- if (!apiKey) {
- alert('You must be logged in to view profile');
- return;
- }
-
- try {
- const response = await ForumApiService.getMyProfile(apiKey, deviceId);
-
- if (response.success && response.data?.data) {
- const profile = response.data.data;
- setUserProfile(profile);
- setProfileEdit({
- display_name: profile.display_name || '',
- bio: profile.bio || '',
- avatar_color: profile.avatar_color || colors.primary,
- signature: profile.signature || ''
- });
- setShowProfile(true);
- }
- } catch (error) {
- alert('Error loading profile');
- }
- };
-
- // ENDPOINT 11: Get user profile
- const handleViewUserProfile = async (username: string) => {
- const { apiKey, deviceId } = await getApiCredentials();
- if (!apiKey) {
- alert('You must be logged in to view profiles');
- return;
- }
-
- setSelectedUsername(username);
-
- try {
- const response = await ForumApiService.getUserProfile(username, apiKey, deviceId);
-
- if (response.success && response.data?.data) {
- setUserProfile(response.data.data);
- setShowProfile(true);
- }
- } catch (error) {
- alert('Error loading user profile');
- }
- };
-
- // ENDPOINT 13: Update profile
- const handleUpdateProfile = async () => {
- const { apiKey, deviceId } = await getApiCredentials();
- if (!apiKey) return;
-
- try {
- const response = await ForumApiService.updateProfile(profileEdit, apiKey, deviceId);
-
- if (response.success) {
- alert('Profile updated successfully!');
- setShowEditProfile(false);
- handleViewMyProfile(); // Refresh profile
- } else {
- alert(`Failed to update profile: ${response.error || 'Unknown error'}`);
- }
- } catch (error) {
- alert('Error updating profile');
- }
- };
-
- // Generate trending topics from posts
- const generateTrendingTopics = () => {
- const topicsMap: { [key: string]: { count: number; sentiment: string } } = {};
-
- forumPosts.forEach(post => {
- post.tags.forEach(tag => {
- const topic = `#${tag}`;
- if (!topicsMap[topic]) {
- topicsMap[topic] = { count: 0, sentiment: 'NEUTRAL' };
- }
- topicsMap[topic].count += 1;
- if (post.sentiment === 'BULLISH') topicsMap[topic].sentiment = 'BULLISH';
- });
- });
-
- const trending = Object.entries(topicsMap)
- .map(([topic, data]) => ({
- topic,
- mentions: data.count * 100,
- sentiment: data.sentiment,
- change: `+${Math.floor(Math.random() * 200 + 50)}%`
- }))
- .sort((a, b) => b.mentions - a.mentions)
- .slice(0, 6);
-
- setTrendingTopics(trending);
- };
-
- // Generate recent activity from posts
- const generateRecentActivity = () => {
- const activities = forumPosts.slice(0, 5).map((post, index) => ({
- user: post.author,
- action: index % 3 === 0 ? 'posted' : index % 3 === 1 ? 'replied to' : 'liked',
- target: post.title.substring(0, 30) + '...',
- time: `${(index + 1) * 3} min ago`
- }));
-
- setRecentActivity(activities);
- };
-
- // Manual refresh handler
- const handleRefresh = async () => {
- if (isRefreshing) return; // Prevent multiple simultaneous refreshes
-
- setIsRefreshing(true);
-
- try {
- // Force refresh all data (bypass cache)
- await Promise.all([
- fetchCategories(true),
- fetchForumStats(true),
- fetchPosts(true)
- ]);
-
- setLastRefreshTime(new Date());
- } catch (error) {
- // Silently handle error
- } finally {
- setIsRefreshing(false);
- }
- };
-
- // Initial load
- useEffect(() => {
- const initForum = async () => {
- fetchCategories();
- fetchForumStats();
-
- // Check if navigated from dashboard widget with post ID
- const selectedPostId = await getSetting('forum_selected_post_id');
- if (selectedPostId) {
- await saveSetting('forum_selected_post_id', '', 'forum');
- // Find and open the post
- setTimeout(async () => {
- const post = forumPosts.find(p => p.id === selectedPostId);
- if (post) {
- handleViewPost(post);
- } else {
- // Try to fetch the post details directly
- try {
- const { apiKey, deviceId } = await getApiCredentials();
- const response = await ForumApiService.getPostDetails(selectedPostId, apiKey, deviceId);
- if (response.success && response.data) {
- const apiPost = (response.data as any).data?.post || (response.data as any).post;
- const post = convertApiPostToUIFormat(apiPost);
- setSelectedPost(post);
- const comments = ((response.data as any).data?.comments || (response.data as any).comments || []).map(convertApiCommentToUIFormat);
- setPostComments(comments);
- setShowPostDetail(true);
- }
- } catch (err) {
- // Silently handle error
- }
- }
- }, 1000);
- }
- };
- initForum();
- }, []);
-
- // Fetch posts when category or sort changes
- useEffect(() => {
- if (categories.length > 0) {
- fetchPosts();
- }
- }, [activeCategory, sortBy, categories]);
-
- // Generate derived data
- useEffect(() => {
- if (forumPosts.length > 0) {
- generateTrendingTopics();
- generateRecentActivity();
- }
- }, [forumPosts]);
-
- // Update clock
- useEffect(() => {
- const timer = setInterval(() => {
- setCurrentTime(new Date());
- setOnlineUsers(prev => Math.max(1000, prev + Math.floor(Math.random() * 10) - 5));
- }, 5000);
- return () => clearInterval(timer);
- }, []);
-
- // Auto-refresh every 5 minutes
- useEffect(() => {
- const autoRefreshInterval = setInterval(() => {
- handleRefresh();
- }, 5 * 60 * 1000); // 5 minutes in milliseconds
-
- autoRefreshIntervalRef.current = autoRefreshInterval;
-
- // Cleanup on unmount
- return () => {
- if (autoRefreshIntervalRef.current) {
- clearInterval(autoRefreshIntervalRef.current);
- }
- };
- }, []); // Empty deps - set up once on mount
-
- const getPriorityColor = (priority: string) => {
- switch (priority) {
- case 'HOT': return FINCEPT_RED;
- case 'TRENDING': return FINCEPT_ORANGE;
- case 'NORMAL': return FINCEPT_GRAY;
- default: return FINCEPT_GRAY;
- }
- };
-
- const getSentimentColor = (sentiment: string) => {
- switch (sentiment) {
- case 'BULLISH': return FINCEPT_GREEN;
- case 'BEARISH': return FINCEPT_RED;
- case 'NEUTRAL': return FINCEPT_YELLOW;
- default: return FINCEPT_GRAY;
- }
- };
-
- const filteredPosts = activeCategory === 'ALL'
- ? forumPosts
- : forumPosts.filter(post => post.category === activeCategory);
-
- const totalPosts = forumStats?.total_posts || categories.find(c => c.name === 'ALL')?.count || 0;
- const postsToday = Math.floor(totalPosts * 0.003);
-
- // Modal components - useMemo to prevent re-creation and fix input focus
- const CreatePostModal = React.useMemo(() => {
- if (!showCreatePost) return null;
- return (
- <div style={{
- position: 'fixed',
- top: 0,
- left: 0,
- right: 0,
- bottom: 0,
- backgroundColor: 'rgba(0,0,0,0.85)',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- zIndex: 1000
- }}>
- <div style={{
- backgroundColor: FINCEPT_PANEL_BG,
- border: `2px solid ${FINCEPT_ORANGE}`,
- padding: '16px',
- width: '600px',
- maxHeight: '80vh',
- overflow: 'auto'
- }}>
- <div style={{ color: FINCEPT_ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>
- CREATE NEW POST
- </div>
- <div style={{ borderBottom: `1px solid ${FINCEPT_GRAY}`, marginBottom: '12px' }}></div>
-
- <div style={{ marginBottom: '12px' }}>
- <div style={{ color: FINCEPT_WHITE, fontSize: '11px', marginBottom: '4px' }}>
- Title: <span style={{ color: newPostTitle.length < 5 ? FINCEPT_RED : FINCEPT_GREEN }}>
- ({newPostTitle.length}/500 chars - min 5)
- </span>
- </div>
- <input
- type="text"
- value={newPostTitle}
- onChange={(e) => setNewPostTitle(e.target.value)}
- maxLength={500}
- style={{
- width: '100%',
- backgroundColor: FINCEPT_DARK_BG,
- border: `1px solid ${newPostTitle.length > 0 && newPostTitle.length < 5 ? FINCEPT_RED : FINCEPT_GRAY}`,
- color: FINCEPT_WHITE,
- padding: '6px',
- fontSize: '12px',
- fontFamily: 'Consolas, monospace'
- }}
- placeholder="Enter post title (minimum 5 characters)..."
- />
- </div>
-
- <div style={{ marginBottom: '12px' }}>
- <div style={{ color: FINCEPT_WHITE, fontSize: '11px', marginBottom: '4px' }}>
- Content: <span style={{ color: newPostContent.length < 10 ? FINCEPT_RED : FINCEPT_GREEN }}>
- ({newPostContent.length}/10000 chars - min 10)
- </span>
- </div>
- <textarea
- value={newPostContent}
- onChange={(e) => setNewPostContent(e.target.value)}
- maxLength={10000}
- rows={10}
- style={{
- width: '100%',
- backgroundColor: FINCEPT_DARK_BG,
- border: `1px solid ${newPostContent.length > 0 && newPostContent.length < 10 ? FINCEPT_RED : FINCEPT_GRAY}`,
- color: FINCEPT_WHITE,
- padding: '6px',
- fontSize: '11px',
- fontFamily: 'Consolas, monospace',
- resize: 'vertical'
- }}
- placeholder="Enter post content (minimum 10 characters)... Use #tags for topics"
- />
- </div>
-
- <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
- <button
- onClick={() => setShowCreatePost(false)}
- style={{
- backgroundColor: FINCEPT_GRAY,
- color: FINCEPT_DARK_BG,
- border: 'none',
- padding: '6px 16px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer'
- }}
- >
- CANCEL
- </button>
- <button
- onClick={handleCreatePost}
- style={{
- backgroundColor: FINCEPT_ORANGE,
- color: FINCEPT_DARK_BG,
- border: 'none',
- padding: '6px 16px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer'
- }}
- >
- CREATE POST
- </button>
- </div>
- </div>
- </div>
- );
- }, [showCreatePost, newPostTitle, newPostContent, handleCreatePost, FINCEPT_ORANGE, FINCEPT_GRAY, FINCEPT_DARK_BG, FINCEPT_WHITE, FINCEPT_RED, FINCEPT_GREEN, FINCEPT_PANEL_BG]);
-
- const PostDetailModal = React.useMemo(() => {
- if (!showPostDetail || !selectedPost) return null;
- return (
- <div style={{
- position: 'fixed',
- top: 0,
- left: 0,
- right: 0,
- bottom: 0,
- backgroundColor: 'rgba(0,0,0,0.85)',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- zIndex: 1000
- }}>
- <div style={{
- backgroundColor: FINCEPT_PANEL_BG,
- border: `2px solid ${FINCEPT_ORANGE}`,
- padding: '16px',
- width: '800px',
- maxHeight: '80vh',
- overflow: 'auto'
- }}>
- {selectedPost && (
- <>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
- <div style={{ color: FINCEPT_ORANGE, fontSize: '14px', fontWeight: 'bold' }}>
- POST DETAILS
- </div>
- <button
- onClick={() => setShowPostDetail(false)}
- style={{
- backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT_GRAY}`,
- color: FINCEPT_WHITE,
- padding: '2px 8px',
- fontSize: '10px',
- cursor: 'pointer'
- }}
- >
- CLOSE [X]
- </button>
- </div>
- <div style={{ borderBottom: `1px solid ${FINCEPT_GRAY}`, marginBottom: '12px' }}></div>
-
- {/* Post content */}
- <div style={{ marginBottom: '16px' }}>
- <div style={{ display: 'flex', gap: '4px', alignItems: 'center', marginBottom: '8px', fontSize: '10px' }}>
- <span style={{ color: FINCEPT_CYAN }}>@{selectedPost.author}</span>
- <span style={{ color: FINCEPT_GRAY }}>•</span>
- <span style={{ color: FINCEPT_BLUE }}>[{selectedPost.category}]</span>
- <span style={{ color: getSentimentColor(selectedPost.sentiment) }}>{selectedPost.sentiment}</span>
- </div>
-
- <div style={{ color: FINCEPT_WHITE, fontSize: '13px', fontWeight: 'bold', marginBottom: '8px' }}>
- {selectedPost.title}
- </div>
-
- <div style={{ color: FINCEPT_GRAY, fontSize: '11px', lineHeight: '1.5', marginBottom: '8px', whiteSpace: 'pre-wrap' }}>
- {selectedPost.content}
- </div>
-
- <div style={{ display: 'flex', gap: '12px', fontSize: '10px', marginBottom: '8px' }}>
- <button
- onClick={() => handleVotePost(selectedPost.id, 'up')}
- style={{
- backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT_GREEN}`,
- color: FINCEPT_GREEN,
- padding: '4px 12px',
- fontSize: '10px',
- cursor: 'pointer'
- }}
- >
- ▲ UPVOTE ({selectedPost.likes})
- </button>
- <button
- onClick={() => handleVotePost(selectedPost.id, 'down')}
- style={{
- backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT_RED}`,
- color: FINCEPT_RED,
- padding: '4px 12px',
- fontSize: '10px',
- cursor: 'pointer'
- }}
- >
- ▼ DOWNVOTE ({selectedPost.dislikes})
- </button>
- </div>
- </div>
-
- <div style={{ borderTop: `1px solid ${FINCEPT_GRAY}`, paddingTop: '12px', marginBottom: '12px' }}>
- <div style={{ color: FINCEPT_YELLOW, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
- COMMENTS ({postComments.length})
- </div>
-
- {/* Add comment form */}
- <div style={{ marginBottom: '12px' }}>
- <textarea
- value={newComment}
- onChange={(e) => setNewComment(e.target.value)}
- maxLength={2000}
- rows={3}
- style={{
- width: '100%',
- backgroundColor: FINCEPT_DARK_BG,
- border: `1px solid ${FINCEPT_GRAY}`,
- color: FINCEPT_WHITE,
- padding: '6px',
- fontSize: '11px',
- fontFamily: 'Consolas, monospace',
- marginBottom: '4px'
- }}
- placeholder="Add a comment..."
- />
- <button
- onClick={handleAddComment}
- style={{
- backgroundColor: FINCEPT_ORANGE,
- color: FINCEPT_DARK_BG,
- border: 'none',
- padding: '4px 12px',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: 'pointer'
- }}
- >
- POST COMMENT
- </button>
- </div>
-
- {/* Comments list */}
- {postComments.map((comment, index) => (
- <div key={comment.id} style={{
- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
- padding: '8px',
- marginBottom: '6px',
- borderLeft: `2px solid ${FINCEPT_BLUE}`
- }}>
- <div style={{ display: 'flex', gap: '4px', alignItems: 'center', marginBottom: '4px', fontSize: '9px' }}>
- <span style={{ color: FINCEPT_CYAN }}>@{comment.author}</span>
- <span style={{ color: FINCEPT_GRAY }}>•</span>
- <span style={{ color: FINCEPT_GRAY }}>{comment.time}</span>
- </div>
-
- <div style={{ color: FINCEPT_WHITE, fontSize: '10px', marginBottom: '4px', whiteSpace: 'pre-wrap' }}>
- {comment.content}
- </div>
-
- <div style={{ display: 'flex', gap: '8px', fontSize: '9px' }}>
- <button
- onClick={() => handleVoteComment(comment.id, 'up')}
- style={{
- backgroundColor: 'transparent',
- border: 'none',
- color: FINCEPT_GREEN,
- cursor: 'pointer',
- fontSize: '9px'
- }}
- >
- ▲ {comment.likes}
- </button>
- <button
- onClick={() => handleVoteComment(comment.id, 'down')}
- style={{
- backgroundColor: 'transparent',
- border: 'none',
- color: FINCEPT_RED,
- cursor: 'pointer',
- fontSize: '9px'
- }}
- >
- ▼ {comment.dislikes}
- </button>
- </div>
- </div>
- ))}
- </div>
- </>
- )}
- </div>
- </div>
- );
- }, [showPostDetail, selectedPost, postComments, newComment, handleAddComment, handleVotePost, handleVoteComment, getSentimentColor, FINCEPT_ORANGE, FINCEPT_GRAY, FINCEPT_WHITE, FINCEPT_DARK_BG, FINCEPT_PANEL_BG, FINCEPT_CYAN, FINCEPT_BLUE, FINCEPT_GREEN, FINCEPT_RED, FINCEPT_YELLOW]);
-
- const SearchModal = React.useMemo(() => {
- if (!showSearch) return null;
- return (
- <div style={{
- position: 'fixed',
- top: 0,
- left: 0,
- right: 0,
- bottom: 0,
- backgroundColor: 'rgba(0,0,0,0.85)',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- zIndex: 1000
- }}>
- <div style={{
- backgroundColor: FINCEPT_PANEL_BG,
- border: `2px solid ${FINCEPT_ORANGE}`,
- padding: '16px',
- width: '700px',
- maxHeight: '80vh',
- overflow: 'auto'
- }}>
- <div style={{ color: FINCEPT_ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>
- SEARCH FORUM
- </div>
- <div style={{ borderBottom: `1px solid ${FINCEPT_GRAY}`, marginBottom: '12px' }}></div>
-
- <div style={{ display: 'flex', gap: '8px', marginBottom: '16px' }}>
- <input
- type="text"
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
- style={{
- flex: 1,
- backgroundColor: FINCEPT_DARK_BG,
- border: `1px solid ${FINCEPT_GRAY}`,
- color: FINCEPT_WHITE,
- padding: '8px',
- fontSize: '12px',
- fontFamily: 'Consolas, monospace'
- }}
- placeholder="Search posts and comments..."
- />
- <button
- onClick={handleSearch}
- style={{
- backgroundColor: FINCEPT_ORANGE,
- color: FINCEPT_DARK_BG,
- border: 'none',
- padding: '8px 16px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer'
- }}
- >
- SEARCH
- </button>
- <button
- onClick={() => {
- setShowSearch(false);
- setSearchResults([]);
- setSearchQuery('');
- }}
- style={{
- backgroundColor: FINCEPT_GRAY,
- color: FINCEPT_DARK_BG,
- border: 'none',
- padding: '8px 16px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer'
- }}
- >
- CLOSE
- </button>
- </div>
-
- {isLoading && (
- <div style={{ color: FINCEPT_YELLOW, textAlign: 'center', padding: '20px' }}>
- SEARCHING...
- </div>
- )}
-
- {searchResults.length > 0 && (
- <div>
- <div style={{ color: FINCEPT_YELLOW, fontSize: '11px', marginBottom: '8px' }}>
- FOUND {searchResults.length} RESULTS
- </div>
- {searchResults.map((post, index) => (
- <div
- key={post.id}
- onClick={() => {
- setShowSearch(false);
- handleViewPost(post);
- }}
- style={{
- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
- padding: '8px',
- marginBottom: '6px',
- borderLeft: `3px solid ${getPriorityColor(post.priority)}`,
- cursor: 'pointer'
- }}
- >
- <div style={{ color: FINCEPT_WHITE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
- {post.title}
- </div>
- <div style={{ color: FINCEPT_GRAY, fontSize: '10px', marginBottom: '4px' }}>
- {post.content.substring(0, 150)}...
- </div>
- <div style={{ display: 'flex', gap: '8px', fontSize: '9px' }}>
- <span style={{ color: FINCEPT_CYAN }}>@{post.author}</span>
- <span style={{ color: FINCEPT_BLUE }}>[{post.category}]</span>
- <span style={{ color: FINCEPT_GREEN }}>👍 {post.likes}</span>
- </div>
- </div>
- ))}
- </div>
- )}
- </div>
- </div>
- );
- }, [showSearch, searchQuery, searchResults, isLoading, handleSearch, handleViewPost, getPriorityColor, FINCEPT_ORANGE, FINCEPT_GRAY, FINCEPT_DARK_BG, FINCEPT_WHITE, FINCEPT_PANEL_BG, FINCEPT_YELLOW, FINCEPT_CYAN, FINCEPT_BLUE, FINCEPT_GREEN]);
-
- const ProfileModal = React.useMemo(() => {
- if (!showProfile || !userProfile) return null;
- return (
- <div style={{
- position: 'fixed',
- top: 0,
- left: 0,
- right: 0,
- bottom: 0,
- backgroundColor: 'rgba(0,0,0,0.85)',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- zIndex: 1000
- }}>
- <div style={{
- backgroundColor: FINCEPT_PANEL_BG,
- border: `2px solid ${FINCEPT_ORANGE}`,
- padding: '16px',
- width: '600px',
- maxHeight: '80vh',
- overflow: 'auto'
- }}>
- {userProfile && (
- <>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
- <div style={{ color: FINCEPT_ORANGE, fontSize: '14px', fontWeight: 'bold' }}>
- FORUM PROFILE
- </div>
- <button
- onClick={() => {
- setShowProfile(false);
- setUserProfile(null);
- }}
- style={{
- backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT_GRAY}`,
- color: FINCEPT_WHITE,
- padding: '2px 8px',
- fontSize: '10px',
- cursor: 'pointer'
- }}
- >
- CLOSE [X]
- </button>
- </div>
- <div style={{ borderBottom: `1px solid ${FINCEPT_GRAY}`, marginBottom: '12px' }}></div>
-
- <div style={{ marginBottom: '12px' }}>
- <div style={{ color: FINCEPT_CYAN, fontSize: '16px', fontWeight: 'bold', marginBottom: '8px' }}>
- @{userProfile.username}
- </div>
- <div style={{ color: FINCEPT_WHITE, fontSize: '12px', marginBottom: '4px' }}>
- {userProfile.display_name || 'No display name set'}
- </div>
- <div style={{ color: FINCEPT_GRAY, fontSize: '11px', marginBottom: '12px', fontStyle: 'italic' }}>
- {userProfile.bio || 'No bio available'}
- </div>
-
- <div style={{ display: 'flex', gap: '16px', fontSize: '11px', marginBottom: '12px' }}>
- <div>
- <span style={{ color: FINCEPT_GRAY }}>Posts: </span>
- <span style={{ color: FINCEPT_WHITE }}>{userProfile.post_count || 0}</span>
- </div>
- <div>
- <span style={{ color: FINCEPT_GRAY }}>Comments: </span>
- <span style={{ color: FINCEPT_WHITE }}>{userProfile.comment_count || 0}</span>
- </div>
- <div>
- <span style={{ color: FINCEPT_GRAY }}>Reputation: </span>
- <span style={{ color: FINCEPT_GREEN }}>{userProfile.reputation || 0}</span>
- </div>
- </div>
-
- {userProfile.signature && (
- <div style={{
- backgroundColor: 'rgba(255,255,255,0.02)',
- padding: '8px',
- marginBottom: '12px',
- borderLeft: `2px solid ${FINCEPT_YELLOW}`
- }}>
- <div style={{ color: FINCEPT_YELLOW, fontSize: '10px', marginBottom: '4px' }}>SIGNATURE:</div>
- <div style={{ color: FINCEPT_GRAY, fontSize: '10px', fontStyle: 'italic' }}>
- {userProfile.signature}
- </div>
- </div>
- )}
-
- {!selectedUsername && (
- <button
- onClick={() => {
- setShowProfile(false);
- setShowEditProfile(true);
- }}
- style={{
- backgroundColor: FINCEPT_ORANGE,
- color: FINCEPT_DARK_BG,
- border: 'none',
- padding: '6px 16px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer'
- }}
- >
- EDIT PROFILE
- </button>
- )}
- </div>
- </>
- )}
- </div>
- </div>
- );
- }, [showProfile, userProfile, selectedUsername, FINCEPT_ORANGE, FINCEPT_GRAY, FINCEPT_WHITE, FINCEPT_DARK_BG, FINCEPT_PANEL_BG, FINCEPT_CYAN, FINCEPT_GREEN, FINCEPT_YELLOW]);
-
- const EditProfileModal = React.useMemo(() => {
- if (!showEditProfile) return null;
- return (
- <div style={{
- position: 'fixed',
- top: 0,
- left: 0,
- right: 0,
- bottom: 0,
- backgroundColor: 'rgba(0,0,0,0.85)',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- zIndex: 1000
- }}>
- <div style={{
- backgroundColor: FINCEPT_PANEL_BG,
- border: `2px solid ${FINCEPT_ORANGE}`,
- padding: '16px',
- width: '600px',
- maxHeight: '80vh',
- overflow: 'auto'
- }}>
- <div style={{ color: FINCEPT_ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>
- EDIT PROFILE
- </div>
- <div style={{ borderBottom: `1px solid ${FINCEPT_GRAY}`, marginBottom: '12px' }}></div>
-
- <div style={{ marginBottom: '12px' }}>
- <div style={{ color: FINCEPT_WHITE, fontSize: '11px', marginBottom: '4px' }}>Display Name:</div>
- <input
- type="text"
- value={profileEdit.display_name}
- onChange={(e) => setProfileEdit({ ...profileEdit, display_name: e.target.value })}
- style={{
- width: '100%',
- backgroundColor: FINCEPT_DARK_BG,
- border: `1px solid ${FINCEPT_GRAY}`,
- color: FINCEPT_WHITE,
- padding: '6px',
- fontSize: '12px',
- fontFamily: 'Consolas, monospace'
- }}
- />
- </div>
-
- <div style={{ marginBottom: '12px' }}>
- <div style={{ color: FINCEPT_WHITE, fontSize: '11px', marginBottom: '4px' }}>Bio:</div>
- <textarea
- value={profileEdit.bio}
- onChange={(e) => setProfileEdit({ ...profileEdit, bio: e.target.value })}
- rows={4}
- style={{
- width: '100%',
- backgroundColor: FINCEPT_DARK_BG,
- border: `1px solid ${FINCEPT_GRAY}`,
- color: FINCEPT_WHITE,
- padding: '6px',
- fontSize: '11px',
- fontFamily: 'Consolas, monospace'
- }}
- />
- </div>
-
- <div style={{ marginBottom: '12px' }}>
- <div style={{ color: FINCEPT_WHITE, fontSize: '11px', marginBottom: '4px' }}>Signature:</div>
- <input
- type="text"
- value={profileEdit.signature}
- onChange={(e) => setProfileEdit({ ...profileEdit, signature: e.target.value })}
- style={{
- width: '100%',
- backgroundColor: FINCEPT_DARK_BG,
- border: `1px solid ${FINCEPT_GRAY}`,
- color: FINCEPT_WHITE,
- padding: '6px',
- fontSize: '12px',
- fontFamily: 'Consolas, monospace'
- }}
- />
- </div>
-
- <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
- <button
- onClick={() => setShowEditProfile(false)}
- style={{
- backgroundColor: FINCEPT_GRAY,
- color: FINCEPT_DARK_BG,
- border: 'none',
- padding: '6px 16px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer'
- }}
- >
- CANCEL
- </button>
- <button
- onClick={handleUpdateProfile}
- style={{
- backgroundColor: FINCEPT_ORANGE,
- color: FINCEPT_DARK_BG,
- border: 'none',
- padding: '6px 16px',
- fontSize: '11px',
- fontWeight: 'bold',
- cursor: 'pointer'
- }}
- >
- SAVE CHANGES
- </button>
- </div>
- </div>
- </div>
- );
- }, [showEditProfile, profileEdit, handleUpdateProfile, FINCEPT_ORANGE, FINCEPT_GRAY, FINCEPT_DARK_BG, FINCEPT_WHITE, FINCEPT_PANEL_BG]);
-
- return (
- <div style={{
- height: '100%',
- backgroundColor: FINCEPT_DARK_BG,
- color: FINCEPT_WHITE,
- fontFamily: 'Consolas, monospace',
- overflow: 'hidden',
- display: 'flex',
- flexDirection: 'column',
- fontSize: '12px'
- }}>
- {/* Header */}
- <div style={{
- backgroundColor: FINCEPT_PANEL_BG,
- borderBottom: `1px solid ${FINCEPT_GRAY}`,
- padding: '4px 8px',
- flexShrink: 0
- }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', marginBottom: '2px', justifyContent: 'space-between' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <span style={{ color: FINCEPT_ORANGE, fontWeight: 'bold' }}>{t('title')}</span>
- <span style={{ color: FINCEPT_WHITE }}>|</span>
- <span style={{ color: FINCEPT_GREEN }}>● LIVE</span>
- <span style={{ color: FINCEPT_WHITE }}>|</span>
- <span style={{ color: FINCEPT_YELLOW }}>USERS ONLINE: {onlineUsers.toLocaleString()}</span>
- <span style={{ color: FINCEPT_WHITE }}>|</span>
- <span style={{ color: FINCEPT_CYAN }}>POSTS TODAY: {postsToday.toLocaleString()}</span>
- <span style={{ color: FINCEPT_WHITE }}>|</span>
- <span style={{ color: FINCEPT_WHITE }}>{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC</span>
- </div>
- <button
- onClick={handleRefresh}
- disabled={isRefreshing}
- style={{
- backgroundColor: isRefreshing ? FINCEPT_GRAY : FINCEPT_ORANGE,
- color: FINCEPT_DARK_BG,
- border: 'none',
- padding: '2px 8px',
- fontSize: '10px',
- fontWeight: 'bold',
- cursor: isRefreshing ? 'not-allowed' : 'pointer',
- opacity: isRefreshing ? 0.6 : 1
- }}
- title={lastRefreshTime ? `Last refreshed: ${lastRefreshTime.toLocaleTimeString()}` : 'Refresh forum data'}
- >
- {isRefreshing ? '⟳ REFRESHING...' : '⟳ REFRESH'}
- </button>
- </div>
-
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px' }}>
- <span style={{ color: FINCEPT_GRAY }}>{t('header.trending')}:</span>
- {trendingTopics.slice(0, 5).map((topic, i) => (
- <span key={i} style={{ color: i % 2 === 0 ? FINCEPT_RED : i % 3 === 0 ? FINCEPT_CYAN : FINCEPT_PURPLE }}>
- {topic.topic.replace('#', '').toUpperCase()}
- </span>
- ))}
- <span style={{ color: FINCEPT_WHITE }}>|</span>
- <span style={{ color: FINCEPT_GRAY }}>SENTIMENT:</span>
- <span style={{ color: FINCEPT_GREEN }}>BULLISH 68%</span>
- <span style={{ color: FINCEPT_RED }}>BEARISH 18%</span>
- <span style={{ color: FINCEPT_YELLOW }}>NEUTRAL 14%</span>
- </div>
- </div>
-
- {/* Function Keys */}
- <div style={{
- backgroundColor: FINCEPT_PANEL_BG,
- borderBottom: `1px solid ${FINCEPT_GRAY}`,
- padding: '2px 4px',
- flexShrink: 0
- }}>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: '2px' }}>
- {[
- { key: "F1", label: "ALL", action: () => setActiveCategory('ALL') },
- { key: "F2", label: categories[1]?.name || "MARKETS", action: () => setActiveCategory(categories[1]?.name || "MARKETS") },
- { key: "F3", label: categories[2]?.name || "TECH", action: () => setActiveCategory(categories[2]?.name || "TECH") },
- { key: "F4", label: categories[3]?.name || "CRYPTO", action: () => setActiveCategory(categories[3]?.name || "CRYPTO") },
- { key: "F5", label: categories[4]?.name || "OPTIONS", action: () => setActiveCategory(categories[4]?.name || "OPTIONS") },
- { key: "F6", label: categories[5]?.name || "BANKING", action: () => setActiveCategory(categories[5]?.name || "BANKING") },
- { key: "F7", label: categories[6]?.name || "ENERGY", action: () => setActiveCategory(categories[6]?.name || "ENERGY") },
- { key: "F8", label: categories[7]?.name || "MACRO", action: () => setActiveCategory(categories[7]?.name || "MACRO") },
- { key: "F9", label: "POST", action: () => setShowCreatePost(true) },
- { key: "F10", label: "SEARCH", action: () => setShowSearch(true) },
- { key: "F11", label: "PROFILE", action: () => handleViewMyProfile() },
- { key: "F12", label: "SETTINGS", action: () => setShowEditProfile(true) }
- ].map(item => (
- <button key={item.key}
- onClick={item.action}
- style={{
- backgroundColor: activeCategory === item.label ? FINCEPT_ORANGE : FINCEPT_DARK_BG,
- border: `1px solid ${FINCEPT_GRAY}`,
- color: activeCategory === item.label ? FINCEPT_DARK_BG : FINCEPT_WHITE,
- padding: '2px 4px',
- fontSize: '9px',
- height: '16px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- fontWeight: activeCategory === item.label ? 'bold' : 'normal',
- cursor: 'pointer'
- }}>
- <span style={{ color: FINCEPT_YELLOW }}>{item.key}:</span>
- <span style={{ marginLeft: '2px' }}>{item.label}</span>
- </button>
- ))}
- </div>
- </div>
-
- {/* Main Content */}
- <div style={{ flex: 1, overflow: 'auto', padding: '4px', backgroundColor: '#050505' }}>
- <div style={{ display: 'flex', gap: '4px', height: '100%' }}>
-
- {/* Left Panel - Categories & Stats */}
- <div style={{
- width: '280px',
- backgroundColor: FINCEPT_PANEL_BG,
- border: `1px solid ${FINCEPT_GRAY}`,
- padding: '4px',
- overflow: 'auto'
- }}>
- <div style={{ color: FINCEPT_ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
- FORUM CATEGORIES
- </div>
- <div style={{ borderBottom: `1px solid ${FINCEPT_GRAY}`, marginBottom: '4px' }}></div>
-
- {categories.map((cat, index) => (
- <button key={index}
- onClick={() => setActiveCategory(cat.name)}
- style={{
- width: '100%',
- display: 'flex',
- justifyContent: 'space-between',
- padding: '4px',
- marginBottom: '2px',
- backgroundColor: activeCategory === cat.name ? 'rgba(255,165,0,0.1)' : 'transparent',
- border: `1px solid ${activeCategory === cat.name ? FINCEPT_ORANGE : 'transparent'}`,
- color: cat.color,
- fontSize: '10px',
- cursor: 'pointer',
- textAlign: 'left'
- }}>
- <span>{cat.name}</span>
- <span style={{ color: FINCEPT_CYAN }}>{cat.count}</span>
- </button>
- ))}
-
- <div style={{ borderTop: `1px solid ${FINCEPT_GRAY}`, marginTop: '8px', paddingTop: '8px' }}>
- <div style={{ color: FINCEPT_YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
- TOP CONTRIBUTORS
- </div>
- {topContributors.map((user, index) => (
- <div key={index}
- onClick={() => handleViewUserProfile(user.username)}
- style={{
- padding: '3px',
- marginBottom: '2px',
- backgroundColor: 'rgba(255,255,255,0.02)',
- fontSize: '9px',
- cursor: 'pointer'
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: FINCEPT_WHITE }}>{user.username}</span>
- <span style={{ color: user.status === 'ONLINE' ? FINCEPT_GREEN : FINCEPT_GRAY }}>
- ●
- </span>
- </div>
- <div style={{ display: 'flex', gap: '6px', color: FINCEPT_GRAY }}>
- <span>REP: {user.reputation}</span>
- <span>POSTS: {user.posts}</span>
- </div>
- </div>
- ))}
- </div>
-
- <div style={{ borderTop: `1px solid ${FINCEPT_GRAY}`, marginTop: '8px', paddingTop: '8px' }}>
- <div style={{ color: FINCEPT_YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
- FORUM STATISTICS
- </div>
- <div style={{ fontSize: '9px', lineHeight: '1.4', color: FINCEPT_GRAY }}>
- <div>Total Posts: {totalPosts.toLocaleString()}</div>
- <div>Total Users: {(forumStats?.total_comments || 47832).toLocaleString()}</div>
- <div>Posts Today: {postsToday.toLocaleString()}</div>
- <div>Active Now: {onlineUsers}</div>
- <div style={{ color: FINCEPT_GREEN }}>Avg Response: 12 min</div>
- </div>
- </div>
- </div>
-
- {/* Center Panel - Forum Posts */}
- <div style={{
- flex: 1,
- backgroundColor: FINCEPT_PANEL_BG,
- border: `1px solid ${FINCEPT_GRAY}`,
- padding: '4px',
- overflow: 'auto'
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
- <div style={{ color: FINCEPT_ORANGE, fontSize: '11px', fontWeight: 'bold' }}>
- FORUM POSTS [{activeCategory}]
- {isLoading && <span style={{ color: FINCEPT_YELLOW, marginLeft: '8px' }}>LOADING...</span>}
- </div>
- <div style={{ display: 'flex', gap: '4px', fontSize: '9px' }}>
- <button onClick={() => setSortBy('latest')} style={{
- padding: '2px 6px',
- backgroundColor: sortBy === 'latest' ? FINCEPT_ORANGE : FINCEPT_DARK_BG,
- color: sortBy === 'latest' ? FINCEPT_DARK_BG : FINCEPT_WHITE,
- border: `1px solid ${FINCEPT_GRAY}`,
- cursor: 'pointer'
- }}>LATEST</button>
- <button onClick={() => setSortBy('popular')} style={{
- padding: '2px 6px',
- backgroundColor: sortBy === 'popular' ? FINCEPT_ORANGE : FINCEPT_DARK_BG,
- color: sortBy === 'popular' ? FINCEPT_DARK_BG : FINCEPT_WHITE,
- border: `1px solid ${FINCEPT_GRAY}`,
- cursor: 'pointer'
- }}>HOT</button>
- <button onClick={() => setSortBy('views')} style={{
- padding: '2px 6px',
- backgroundColor: sortBy === 'views' ? FINCEPT_ORANGE : FINCEPT_DARK_BG,
- color: sortBy === 'views' ? FINCEPT_DARK_BG : FINCEPT_WHITE,
- border: `1px solid ${FINCEPT_GRAY}`,
- cursor: 'pointer'
- }}>TOP</button>
- </div>
- </div>
- <div style={{ borderBottom: `1px solid ${FINCEPT_GRAY}`, marginBottom: '8px' }}></div>
-
- {filteredPosts.length === 0 && !isLoading && (
- <div style={{ color: FINCEPT_GRAY, textAlign: 'center', padding: '20px' }}>
- No posts available. Be the first to post!
- </div>
- )}
-
- {filteredPosts.map((post, index) => (
- <div key={post.id} style={{
- marginBottom: '6px',
- padding: '6px',
- backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
- borderLeft: `3px solid ${getPriorityColor(post.priority)}`,
- paddingLeft: '6px',
- cursor: 'pointer'
- }}
- onClick={() => handleViewPost(post)}
- >
- <div style={{ display: 'flex', gap: '4px', alignItems: 'center', marginBottom: '2px', fontSize: '8px' }}>
- <span style={{ color: FINCEPT_GRAY }}>{post.time}</span>
- <span style={{ color: getPriorityColor(post.priority), fontWeight: 'bold' }}>[{post.priority}]</span>
- <span style={{ color: FINCEPT_BLUE }}>[{post.category}]</span>
- <span style={{ color: getSentimentColor(post.sentiment) }}>{post.sentiment}</span>
- {post.verified && <span style={{ color: FINCEPT_CYAN }}>[OK] VERIFIED</span>}
- </div>
-
- <div style={{ display: 'flex', gap: '4px', alignItems: 'center', marginBottom: '2px', fontSize: '9px' }}>
- <span style={{ color: FINCEPT_CYAN }}>@{post.author}</span>
- <span style={{ color: FINCEPT_GRAY }}>•</span>
- <span style={{ color: FINCEPT_WHITE, fontWeight: 'bold' }}>{post.title}</span>
- </div>
-
- <div style={{ color: FINCEPT_GRAY, fontSize: '9px', lineHeight: '1.3', marginBottom: '3px' }}>
- {post.content.substring(0, 200)}{post.content.length > 200 ? '...' : ''}
- </div>
-
- <div style={{ display: 'flex', gap: '6px', fontSize: '8px', marginBottom: '2px' }}>
- {post.tags.map((tag, i) => (
- <span key={i} style={{
- color: FINCEPT_YELLOW,
- backgroundColor: 'rgba(255,255,0,0.1)',
- padding: '1px 4px',
- borderRadius: '2px'
- }}>#{tag}</span>
- ))}
- </div>
-
- <div style={{ display: 'flex', gap: '10px', fontSize: '8px' }}>
- <span style={{ color: FINCEPT_CYAN }}>👁️ {post.views.toLocaleString()}</span>
- <span style={{ color: FINCEPT_PURPLE }}>💬 {post.replies}</span>
- <span style={{ color: FINCEPT_GREEN }}>👍 {post.likes}</span>
- <span style={{ color: FINCEPT_RED }}>👎 {post.dislikes}</span>
- </div>
- </div>
- ))}
- </div>
-
- {/* Right Panel - Activity & Trending */}
- <div style={{
- width: '280px',
- backgroundColor: FINCEPT_PANEL_BG,
- border: `1px solid ${FINCEPT_GRAY}`,
- padding: '4px',
- overflow: 'auto'
- }}>
- <div style={{ color: FINCEPT_ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
- TRENDING TOPICS (1H)
- </div>
- <div style={{ borderBottom: `1px solid ${FINCEPT_GRAY}`, marginBottom: '8px' }}></div>
-
- {trendingTopics.map((item, index) => (
- <div key={index} style={{
- padding: '3px',
- marginBottom: '3px',
- backgroundColor: 'rgba(255,255,255,0.02)',
- fontSize: '9px'
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: FINCEPT_YELLOW }}>{item.topic}</span>
- <span style={{ color: FINCEPT_GREEN }}>{item.change}</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', color: FINCEPT_GRAY }}>
- <span>{item.mentions} mentions</span>
- <span style={{ color: getSentimentColor(item.sentiment) }}>{item.sentiment}</span>
- </div>
- </div>
- ))}
-
- <div style={{ borderTop: `1px solid ${FINCEPT_GRAY}`, marginTop: '12px', paddingTop: '8px' }}>
- <div style={{ color: FINCEPT_YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
- RECENT ACTIVITY
- </div>
- {recentActivity.map((activity, index) => (
- <div key={index} style={{
- padding: '2px',
- marginBottom: '2px',
- fontSize: '8px',
- color: FINCEPT_GRAY,
- lineHeight: '1.3'
- }}>
- <span style={{ color: FINCEPT_CYAN }}>@{activity.user}</span>
- {' '}<span>{activity.action}</span>{' '}
- <span style={{ color: FINCEPT_WHITE }}>{activity.target}</span>
- {' '}<span style={{ color: FINCEPT_YELLOW }}>• {activity.time}</span>
- </div>
- ))}
- </div>
-
- <div style={{ borderTop: `1px solid ${FINCEPT_GRAY}`, marginTop: '12px', paddingTop: '8px' }}>
- <div style={{ color: FINCEPT_YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
- SENTIMENT ANALYSIS
- </div>
- <div style={{ fontSize: '9px' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: FINCEPT_GRAY }}>Bullish Posts:</span>
- <span style={{ color: FINCEPT_GREEN }}>68%</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: FINCEPT_GRAY }}>Bearish Posts:</span>
- <span style={{ color: FINCEPT_RED }}>18%</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
- <span style={{ color: FINCEPT_GRAY }}>Neutral Posts:</span>
- <span style={{ color: FINCEPT_YELLOW }}>14%</span>
- </div>
- <div style={{ borderTop: `1px solid ${FINCEPT_GRAY}`, marginTop: '4px', paddingTop: '4px' }}>
- <span style={{ color: FINCEPT_CYAN }}>Overall Sentiment:</span>
- <span style={{ color: FINCEPT_GREEN, fontWeight: 'bold', marginLeft: '4px' }}>+0.62 BULLISH</span>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- {/* Status Bar */}
- <div style={{
- borderTop: `1px solid ${FINCEPT_GRAY}`,
- backgroundColor: FINCEPT_PANEL_BG,
- padding: '2px 8px',
- fontSize: '10px',
- color: FINCEPT_GRAY,
- flexShrink: 0
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <div style={{ display: 'flex', gap: '16px' }}>
- <span>Fincept Global Forum v2.4.1 | Professional trading community</span>
- <span>Posts: {totalPosts.toLocaleString()} | Users: {(forumStats?.total_comments || 47832).toLocaleString()} | Active: {onlineUsers}</span>
- </div>
- <div style={{ display: 'flex', gap: '16px' }}>
- <span>Category: {activeCategory}</span>
- <span>Sort: {sortBy}</span>
- <span style={{ color: FINCEPT_GREEN }}>STATUS: LIVE</span>
- </div>
- </div>
- </div>
-
- {/* Modals */}
- {CreatePostModal}
- {PostDetailModal}
- {SearchModal}
- {ProfileModal}
- {EditProfileModal}
-
- <TabFooter
- tabName="COMMUNITY FORUM"
- leftInfo={[
- { label: `Category: ${activeCategory || 'All'}`, color: colors.textMuted },
- { label: `Posts: ${forumStats?.total_posts || 0}`, color: colors.textMuted },
- ]}
- statusInfo={`Users: ${forumStats?.total_users || 0} | ${isLoading ? 'Loading...' : 'Ready'}`}
- backgroundColor={colors.panel}
- borderColor={colors.textMuted}
- />
- </div>
- );
-};
-
-export default ForumTab;
+export { default } from './forum';
+export { ForumTab } from './forum';
+export * from './forum/types';
diff --git a/fincept-terminal-desktop/src/components/tabs/MaritimeTab.tsx b/fincept-terminal-desktop/src/components/tabs/MaritimeTab.tsx
index 8df435f8c..09b340e99 100644
--- a/fincept-terminal-desktop/src/components/tabs/MaritimeTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/MaritimeTab.tsx
@@ -1,1966 +1,5 @@
-import React, { useState, useEffect, useRef } from 'react';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-import { TabFooter } from '@/components/common/TabFooter';
-import { useTranslation } from 'react-i18next';
-import { useAuth } from '@/contexts/AuthContext';
-import { MarineApiService, VesselData } from '@/services/maritime/marineApi';
+// Maritime Tab - Re-export from organized folder structure
+// This file maintains backward compatibility with existing imports
-interface MarkerData {
- lat: number;
- lng: number;
- title: string;
- type: 'Ship' | 'Port' | 'Industry' | 'Bank' | 'Exchange';
-}
-
-interface TradeRoute {
- name: string;
- value: string;
- status: 'active' | 'delayed' | 'critical';
- vessels: number;
- coordinates: [number, number][];
-}
-
-interface IntelligenceData {
- timestamp: string;
- threat_level: 'low' | 'medium' | 'high' | 'critical';
- active_vessels: number;
- monitored_routes: number;
- trade_volume: string;
-}
-
-interface RealVesselData {
- imo: string;
- name: string;
- lat: number;
- lng: number;
- speed: string;
- angle: string;
- from_port?: string;
- to_port?: string;
- route_progress?: number;
-}
-
-export default function MaritimeTab() {
- const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
- const { t } = useTranslation('maritime');
- const { session } = useAuth();
- const apiKey = session?.api_key || null;
- const [markers, setMarkers] = useState<MarkerData[]>([]);
- const [selectedRoute, setSelectedRoute] = useState<TradeRoute | null>(null);
- const [markerType, setMarkerType] = useState<MarkerData['type']>('Ship');
- const [showRoutes, setShowRoutes] = useState(true);
- const [showShips, setShowShips] = useState(true);
- const [showPlanes, setShowPlanes] = useState(true);
- const [showSatellites, setShowSatellites] = useState(true);
- const [isRotating, setIsRotating] = useState(true);
- const [realVessels, setRealVessels] = useState<RealVesselData[]>([]);
- const [isLoadingVessels, setIsLoadingVessels] = useState(false);
- const [vesselLoadError, setVesselLoadError] = useState<string | null>(null);
- const [searchImo, setSearchImo] = useState('');
- const [searchingVessel, setSearchingVessel] = useState(false);
- const [searchResult, setSearchResult] = useState<VesselData | null>(null);
- const [searchError, setSearchError] = useState<string | null>(null);
- const [mapMode, setMapMode] = useState<'3D' | '2D'>('3D');
- const [intelligence, setIntelligence] = useState<IntelligenceData>({
- timestamp: new Date().toISOString(),
- threat_level: 'low',
- active_vessels: 0,
- monitored_routes: 48,
- trade_volume: '$847.3B'
- });
- const mapRef = useRef<HTMLIFrameElement>(null);
-
- const tradeRoutes: TradeRoute[] = [
- { name: 'Mumbai → Rotterdam', value: '$45B', status: 'active', vessels: 23, coordinates: [[18.9388, 72.8354], [51.9553, 4.1392]] },
- { name: 'Mumbai → Shanghai', value: '$156B', status: 'active', vessels: 89, coordinates: [[18.9388, 72.8354], [31.3548, 121.6431]] },
- { name: 'Mumbai → Singapore', value: '$89B', status: 'active', vessels: 45, coordinates: [[18.9388, 72.8354], [1.2644, 103.8224]] },
- { name: 'Chennai → Tokyo', value: '$67B', status: 'delayed', vessels: 34, coordinates: [[13.0827, 80.2707], [35.4437, 139.6380]] },
- { name: 'Kolkata → Hong Kong', value: '$45B', status: 'active', vessels: 28, coordinates: [[22.5726, 88.3639], [22.2855, 114.1577]] },
- { name: 'Mumbai → Dubai', value: '$78B', status: 'critical', vessels: 12, coordinates: [[18.9388, 72.8354], [24.9857, 55.0272]] },
- { name: 'Mumbai → New York', value: '$123B', status: 'active', vessels: 56, coordinates: [[18.9388, 72.8354], [40.6655, -74.0781]] },
- { name: 'Chennai → Sydney', value: '$54B', status: 'active', vessels: 31, coordinates: [[13.0827, 80.2707], [-33.9544, 151.2093]] },
- { name: 'Cochin → Klang', value: '$34B', status: 'active', vessels: 19, coordinates: [[9.9667, 76.2667], [3.0048, 101.3975]] },
- { name: 'Mumbai → Cape Town', value: '$28B', status: 'delayed', vessels: 8, coordinates: [[18.9388, 72.8354], [-33.9055, 18.4232]] }
- ];
-
- const addMarker = (title: string, lat: number, lng: number) => {
- const newMarker: MarkerData = { lat, lng, title, type: markerType };
- setMarkers([...markers, newMarker]);
- };
-
- const clearMarkers = () => {
- setMarkers([]);
- };
-
- const presetLocations = [
- { name: 'Mumbai Port', lat: 18.9388, lng: 72.8354, type: 'Port' as const },
- { name: 'Shanghai Port', lat: 31.3548, lng: 121.6431, type: 'Port' as const },
- { name: 'Singapore Port', lat: 1.2644, lng: 103.8224, type: 'Port' as const },
- { name: 'Hong Kong Port', lat: 22.2855, lng: 114.1577, type: 'Port' as const },
- { name: 'Rotterdam Port', lat: 51.9553, lng: 4.1392, type: 'Port' as const },
- { name: 'Dubai Port', lat: 24.9857, lng: 55.0272, type: 'Port' as const },
- ];
-
- const addPreset = (preset: typeof presetLocations[0]) => {
- setMarkers([...markers, { ...preset, title: preset.name }]);
- };
-
- // Toggle between 2D and 3D map modes
- const toggleMapMode = () => {
- const newMode = mapMode === '3D' ? '2D' : '3D';
- setMapMode(newMode);
-
- if (mapRef.current?.contentWindow) {
- // Pass the current vessel data when switching to 2D
- if (newMode === '2D' && realVessels.length > 0) {
- console.log('Toggling to 2D with', realVessels.length, 'vessels from React state');
- (mapRef.current.contentWindow as any).switchMapMode?.(newMode, realVessels);
- } else {
- (mapRef.current.contentWindow as any).switchMapMode?.(newMode);
- }
- }
- };
-
- // Load real vessel data from API with performance optimization
- const loadRealVessels = async (limitCount: number = 500) => {
- if (!apiKey) {
- setVesselLoadError('No API key available');
- return;
- }
-
- setIsLoadingVessels(true);
- setVesselLoadError(null);
-
- try {
- // Search for vessels in focused Mumbai port area (smaller region for performance)
- const response = await MarineApiService.searchVesselsByArea(
- {
- min_lat: 18.5,
- max_lat: 19.5,
- min_lng: 72.0,
- max_lng: 73.5
- },
- apiKey
- );
-
- if (response.success && response.data) {
- // Filter and limit vessels for performance
- const allVessels = response.data.vessels
- .filter(v => v.last_pos_latitude && v.last_pos_longitude)
- .map(v => ({
- imo: v.imo,
- name: v.name,
- lat: parseFloat(v.last_pos_latitude),
- lng: parseFloat(v.last_pos_longitude),
- speed: v.last_pos_speed,
- angle: v.last_pos_angle,
- from_port: v.route_from_port_name || undefined,
- to_port: v.route_to_port_name || undefined,
- route_progress: v.route_progress ? parseFloat(v.route_progress) : undefined
- }));
-
- // Limit to prevent performance issues (take vessels with routes first, then others)
- const vesselsWithRoutes = allVessels.filter(v => v.from_port || v.to_port);
- const vesselsWithoutRoutes = allVessels.filter(v => !v.from_port && !v.to_port);
-
- const limitedVessels = [
- ...vesselsWithRoutes.slice(0, Math.floor(limitCount * 0.7)),
- ...vesselsWithoutRoutes.slice(0, Math.floor(limitCount * 0.3))
- ].slice(0, limitCount);
-
- console.log(`Loaded ${limitedVessels.length} vessels out of ${allVessels.length} total (limited for performance)`);
-
- setRealVessels(limitedVessels);
- setIntelligence(prev => ({
- ...prev,
- active_vessels: allVessels.length, // Show total count
- timestamp: new Date().toISOString()
- }));
-
- // Send vessel data to globe visualization
- if (mapRef.current?.contentWindow) {
- (mapRef.current.contentWindow as any).updateRealVessels?.(limitedVessels);
- }
- } else {
- setVesselLoadError(response.error || 'Failed to load vessel data');
- }
- } catch (error) {
- console.error('Error loading vessels:', error);
- setVesselLoadError(error instanceof Error ? error.message : 'Unknown error');
- } finally {
- setIsLoadingVessels(false);
- }
- };
-
- // Search for a specific vessel by IMO
- const searchVesselByImo = async () => {
- if (!apiKey) {
- setSearchError('No API key available');
- return;
- }
-
- if (!searchImo.trim()) {
- setSearchError('Please enter an IMO number');
- return;
- }
-
- setSearchingVessel(true);
- setSearchError(null);
- setSearchResult(null);
-
- try {
- const response = await MarineApiService.getVesselPosition(searchImo.trim(), apiKey);
-
- if (response.success && response.data) {
- const vessel = response.data.vessel;
- setSearchResult(vessel);
-
- // Zoom to vessel location on globe
- if (mapRef.current?.contentWindow && vessel.last_pos_latitude && vessel.last_pos_longitude) {
- const lat = parseFloat(vessel.last_pos_latitude);
- const lng = parseFloat(vessel.last_pos_longitude);
- (mapRef.current.contentWindow as any).world?.pointOfView?.({ lat, lng, altitude: 0.5 }, 1000);
- }
- } else {
- setSearchError(response.error || 'Vessel not found');
- }
- } catch (error) {
- console.error('Error searching vessel:', error);
- setSearchError(error instanceof Error ? error.message : 'Search failed');
- } finally {
- setSearchingVessel(false);
- }
- };
-
- // Load vessels on mount and every 5 minutes
- useEffect(() => {
- loadRealVessels();
- const interval = setInterval(loadRealVessels, 300000); // 5 minutes
- return () => clearInterval(interval);
- }, [apiKey]);
-
- // Update timestamp periodically
- useEffect(() => {
- const interval = setInterval(() => {
- setIntelligence(prev => ({
- ...prev,
- timestamp: new Date().toISOString()
- }));
- }, 5000);
- return () => clearInterval(interval);
- }, []);
-
- const mapHTML = `
-<!DOCTYPE html>
-<html>
-<head>
- <meta charset="utf-8" />
- <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
- <style>
- body { margin: 0; padding: 0; background: #000; overflow: hidden; }
- #globeViz { height: 100vh; width: 100vw; background: #000; position: absolute; top: 0; left: 0; }
- #mapViz { height: 100vh; width: 100vw; position: absolute; top: 0; left: 0; display: none; }
- #modeIndicator {
- position: absolute;
- top: 16px;
- right: 16px;
- background: rgba(0, 255, 255, 0.9);
- color: #000;
- padding: 8px 16px;
- border-radius: 4px;
- font-family: 'Consolas', monospace;
- font-size: 12px;
- font-weight: bold;
- z-index: 1000;
- box-shadow: 0 0 10px rgba(0, 255, 255, 0.5);
- }
- </style>
-</head>
-<body>
- <div id="modeIndicator">3D GLOBE MODE</div>
- <div id="globeViz"></div>
- <div id="mapViz"></div>
- <script src="https://unpkg.com/[email protected]/build/three.min.js"></script>
- <script src="https://unpkg.com/[email protected]/dist/globe.gl.min.js"></script>
- <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
- <script>
- console.log('Initializing Hybrid Globe/Map System...');
-
- // Wait for libraries to load
- setTimeout(() => {
- try {
- console.log('Creating globe...');
-
- // Create professional globe with natural appearance
- const world = Globe()
- (document.getElementById('globeViz'))
- .globeImageUrl('https://unpkg.com/[email protected]/example/img/earth-blue-marble.jpg')
- .bumpImageUrl('https://unpkg.com/[email protected]/example/img/earth-topology.png')
- .backgroundColor('#0a0a0a')
- .backgroundImageUrl('https://unpkg.com/three-globe/example/img/night-sky.png')
- .showAtmosphere(true)
- .atmosphereColor('#4a90e2')
- .atmosphereAltitude(0.12)
- .width(window.innerWidth)
- .height(window.innerHeight);
-
- console.log('Globe created successfully');
-
- // Initialize 2D Leaflet map for close zoom (lazy - will initialize when needed)
- let map2D = null;
-
- function initMap2D() {
- if (!map2D) {
- map2D = L.map('mapViz', {
- zoomControl: true,
- attributionControl: false,
- preferCanvas: true, // Better performance for many markers
- scrollWheelZoom: true, // Enable mousewheel/trackpad zoom
- doubleClickZoom: true, // Enable double-click zoom
- touchZoom: true, // Enable pinch zoom on touch devices
- boxZoom: true, // Enable shift+drag to zoom
- keyboard: true, // Enable keyboard navigation
- dragging: true, // Enable map dragging
- maxZoom: 18,
- minZoom: 3
- }).setView([19.0, 72.8], 11);
-
- // Add clean street map with maritime focus
- L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
- attribution: 'FINCEPT MARITIME INTELLIGENCE',
- maxZoom: 18,
- minZoom: 3
- }).addTo(map2D);
-
- // No auto-switching - user controls mode manually via button
-
- // Force map to resize and load tiles
- setTimeout(() => {
- map2D.invalidateSize();
- console.log('2D map resized and tiles loading');
- }, 100);
-
- console.log('2D map initialized');
- }
- }
-
- console.log('2D map setup ready');
-
- // Professional balanced lighting
- const scene = world.scene();
- const ambientLight = new THREE.AmbientLight(0x808080, 0.7); // Balanced ambient light
- const directionalLight = new THREE.DirectionalLight(0xaaaaaa, 0.6); // Natural directional light
- directionalLight.position.set(5, 3, 5);
- scene.add(ambientLight);
- scene.add(directionalLight);
-
- console.log('Professional lighting added');
-
- // Set initial point of view
- world.pointOfView({ lat: 20, lng: 75, altitude: 2.0 }, 1000);
-
- console.log('Camera positioned');
-
- // Hybrid mode state (disabled auto-switch to prevent white screen issues)
- let currentMode = '3D'; // '3D' or '2D'
- let lastGlobeView = { lat: 20, lng: 75, altitude: 2.0 };
- let targetCoords = { lat: 20, lng: 75 }; // Track where user is actually looking
- const ZOOM_THRESHOLD = 0.05; // Very close before switching (effectively disabled with minDistance=150)
-
- var markers = [];
- var allArcs = [];
- var allLabels = [];
- var planeLabels = [];
- var showRoutesFlag = true;
- var showShipsFlag = true;
- var showPlanesFlag = true;
-
- var oceanRoutes = [
- // Mumbai Port (18.9388° N, 72.8354° E) - actual port coordinates
- { name: "Mumbai → Rotterdam", start: {lat: 18.9388, lng: 72.8354}, end: {lat: 51.9553, lng: 4.1392}, value: "$45B", vessels: 23, color: 'rgba(100, 180, 255, 0.6)', width: 0.8 },
- { name: "Mumbai → Shanghai", start: {lat: 18.9388, lng: 72.8354}, end: {lat: 31.3548, lng: 121.6431}, value: "$156B", vessels: 89, color: 'rgba(120, 200, 255, 0.7)', width: 1.2 },
- { name: "Mumbai → Singapore", start: {lat: 18.9388, lng: 72.8354}, end: {lat: 1.2644, lng: 103.8224}, value: "$89B", vessels: 45, color: 'rgba(100, 180, 255, 0.65)', width: 1.0 },
- // Chennai Port (13.0827° N, 80.2707° E)
- { name: "Chennai → Tokyo", start: {lat: 13.0827, lng: 80.2707}, end: {lat: 35.4437, lng: 139.6380}, value: "$67B", vessels: 34, color: 'rgba(150, 220, 255, 0.6)', width: 0.9 },
- // Kolkata Port (22.5726° N, 88.3639° E)
- { name: "Kolkata → Hong Kong", start: {lat: 22.5726, lng: 88.3639}, end: {lat: 22.2855, lng: 114.1577}, value: "$45B", vessels: 28, color: 'rgba(100, 180, 255, 0.55)', width: 0.8 },
- // Mumbai → Dubai (Port Jebel Ali: 24.9857° N, 55.0272° E)
- { name: "Mumbai → Dubai", start: {lat: 18.9388, lng: 72.8354}, end: {lat: 24.9857, lng: 55.0272}, value: "$78B", vessels: 12, color: 'rgba(255, 160, 100, 0.6)', width: 0.9 },
- // Mumbai → New York (Port of NY/NJ: 40.6655° N, 74.0781° W)
- { name: "Mumbai → New York", start: {lat: 18.9388, lng: 72.8354}, end: {lat: 40.6655, lng: -74.0781}, value: "$123B", vessels: 56, color: 'rgba(120, 200, 255, 0.75)', width: 1.2 },
- // Chennai → Sydney (Port Botany: 33.9544° S, 151.2093° E)
- { name: "Chennai → Sydney", start: {lat: 13.0827, lng: 80.2707}, end: {lat: -33.9544, lng: 151.2093}, value: "$54B", vessels: 31, color: 'rgba(130, 190, 255, 0.6)', width: 0.9 },
- // Cochin Port (9.9667° N, 76.2667° E) → Port Klang, Malaysia (3.0048° N, 101.3975° E)
- { name: "Cochin → Klang", start: {lat: 9.9667, lng: 76.2667}, end: {lat: 3.0048, lng: 101.3975}, value: "$34B", vessels: 19, color: 'rgba(180, 200, 255, 0.5)', width: 0.7 },
- // Mumbai → Cape Town (33.9055° S, 18.4232° E)
- { name: "Mumbai → Cape Town", start: {lat: 18.9388, lng: 72.8354}, end: {lat: -33.9055, lng: 18.4232}, value: "$28B", vessels: 8, color: 'rgba(160, 180, 255, 0.5)', width: 0.7 }
- ];
-
- var airRoutes = [
- // Major international air cargo routes
- { name: "Mumbai → London", start: {lat: 19.0896, lng: 72.8656}, end: {lat: 51.4700, lng: -0.4543}, value: "$12B", flights: 45, color: 'rgba(255, 200, 100, 0.7)', width: 0.6 },
- { name: "Delhi → New York", start: {lat: 28.5562, lng: 77.1000}, end: {lat: 40.6413, lng: -73.7781}, value: "$18B", flights: 67, color: 'rgba(255, 200, 100, 0.75)', width: 0.8 },
- { name: "Mumbai → Dubai", start: {lat: 19.0896, lng: 72.8656}, end: {lat: 25.2532, lng: 55.3657}, value: "$22B", flights: 123, color: 'rgba(255, 200, 100, 0.8)', width: 0.9 },
- { name: "Bangalore → Singapore", start: {lat: 13.1979, lng: 77.7063}, end: {lat: 1.3644, lng: 103.9915}, value: "$8B", flights: 89, color: 'rgba(255, 200, 100, 0.65)', width: 0.6 },
- { name: "Delhi → Frankfurt", start: {lat: 28.5562, lng: 77.1000}, end: {lat: 50.0379, lng: 8.5622}, value: "$15B", flights: 56, color: 'rgba(255, 200, 100, 0.7)', width: 0.7 },
- { name: "Mumbai → Hong Kong", start: {lat: 19.0896, lng: 72.8656}, end: {lat: 22.3080, lng: 113.9185}, value: "$11B", flights: 78, color: 'rgba(255, 200, 100, 0.65)', width: 0.6 },
- { name: "Chennai → Tokyo", start: {lat: 12.9941, lng: 80.1709}, end: {lat: 35.7720, lng: 140.3929}, value: "$9B", flights: 34, color: 'rgba(255, 200, 100, 0.6)', width: 0.6 },
- { name: "Delhi → Sydney", start: {lat: 28.5562, lng: 77.1000}, end: {lat: -33.9399, lng: 151.1753}, value: "$7B", flights: 28, color: 'rgba(255, 200, 100, 0.6)', width: 0.5 }
- ];
-
- function createRoutes() {
- // Combine ocean and air routes
- const oceanArcsData = oceanRoutes.map(route => ({
- startLat: route.start.lat,
- startLng: route.start.lng,
- endLat: route.end.lat,
- endLng: route.end.lng,
- color: route.color,
- name: route.name,
- value: route.value,
- width: route.width || 0.5,
- type: 'ocean'
- }));
-
- const airArcsData = airRoutes.map(route => ({
- startLat: route.start.lat,
- startLng: route.start.lng,
- endLat: route.end.lat,
- endLng: route.end.lng,
- color: route.color,
- name: route.name,
- value: route.value,
- width: route.width || 0.5,
- type: 'air'
- }));
-
- const allArcsData = [...oceanArcsData, ...airArcsData];
- allArcs = allArcsData;
- world.arcsData(allArcsData)
- .arcColor('color')
- .arcStroke((d) => d.width) // Thin, professional lines
- .arcDashLength(1.0) // Full solid lines
- .arcDashGap(0) // No gaps - complete lines
- .arcDashInitialGap(0) // Start from beginning
- .arcDashAnimateTime(0) // No animation to avoid cutting
- .arcAltitude((d) => d.type === 'air' ? 0.15 : 0.1) // Higher for air, moderate for ocean
- .arcAltitudeAutoScale(0.5) // More curve for visibility
- .arcLabel((d) => \`
- <div style="background: rgba(10,10,10,0.92); padding: 6px 10px; border-left: 2px solid \${d.type === 'air' ? 'rgba(255, 200, 100, 0.8)' : 'rgba(100, 180, 255, 0.8)'}; font-family: 'Segoe UI', sans-serif; font-size: 11px; box-shadow: 0 2px 8px rgba(0,0,0,0.4);">
- <div style="color: #e0e0e0; font-weight: 500; margin-bottom: 2px;">\${d.type === 'air' ? '✈' : '🚢'} \${d.name}</div>
- <div style="color: #999; font-size: 9px;">\${d.value}</div>
- </div>
- \`);
-
- // Extract unique ports and airports
- const uniquePorts = new Map();
- oceanRoutes.forEach(route => {
- const startName = route.name.split(' → ')[0];
- const endName = route.name.split(' → ')[1];
-
- if (!uniquePorts.has(startName)) {
- uniquePorts.set(startName, { lat: route.start.lat, lng: route.start.lng, type: 'port' });
- }
- if (!uniquePorts.has(endName)) {
- uniquePorts.set(endName, { lat: route.end.lat, lng: route.end.lng, type: 'port' });
- }
- });
-
- const uniqueAirports = new Map();
- airRoutes.forEach(route => {
- const startName = route.name.split(' → ')[0];
- const endName = route.name.split(' → ')[1];
-
- if (!uniqueAirports.has(startName)) {
- uniqueAirports.set(startName, { lat: route.start.lat, lng: route.start.lng, type: 'airport' });
- }
- if (!uniqueAirports.has(endName)) {
- uniqueAirports.set(endName, { lat: route.end.lat, lng: route.end.lng, type: 'airport' });
- }
- });
-
- const portPoints = Array.from(uniquePorts.entries()).map(([name, data]) => ({
- lat: data.lat,
- lng: data.lng,
- size: 0.6,
- color: 'rgba(255, 180, 100, 0.85)', // Orange for ports
- label: name,
- type: 'port'
- }));
-
- const airportPoints = Array.from(uniqueAirports.entries()).map(([name, data]) => ({
- lat: data.lat,
- lng: data.lng,
- size: 0.5,
- color: 'rgba(180, 100, 255, 0.85)', // Purple for airports
- label: name,
- type: 'airport'
- }));
-
- const allPoints = [...portPoints, ...airportPoints];
-
- // Professional markers - ports (orange) and airports (purple)
- world.pointsData(allPoints)
- .pointAltitude(0.002)
- .pointRadius('size')
- .pointColor('color')
- .pointLabel((d) => \`
- <div style="background: rgba(10,10,10,0.92); padding: 5px 9px; border-left: 2px solid \${d.color}; font-family: 'Segoe UI', sans-serif; font-size: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.4);">
- <span style="color: #e0e0e0; font-weight: 500;">\${d.type === 'port' ? '⚓' : '✈'} \${d.label}</span>
- </div>
- \`);
- }
-
- function createShips() {
- // Professional ship visualization using proper globe coordinates
- const shipData = oceanRoutes.map((route, routeIdx) => ({
- routeIdx: routeIdx,
- progress: Math.random(),
- startLat: route.start.lat,
- startLng: route.start.lng,
- endLat: route.end.lat,
- endLng: route.end.lng,
- label: route.name,
- value: route.value,
- vessels: route.vessels
- }));
-
- // Calculate interpolated positions along great circle arc
- function interpolateArc(startLat, startLng, endLat, endLng, progress) {
- // Simple linear interpolation for latitude and longitude
- const lat = startLat + (endLat - startLat) * progress;
- const lng = startLng + (endLng - startLng) * progress;
- return { lat, lng };
- }
-
- // Generate ship positions
- function generateShipPoints(shipsData) {
- return shipsData.map(ship => {
- const pos = interpolateArc(
- ship.startLat,
- ship.startLng,
- ship.endLat,
- ship.endLng,
- ship.progress
- );
- return {
- lat: pos.lat,
- lng: pos.lng,
- size: 0.15,
- color: 'rgba(100, 180, 255, 0.95)',
- altitude: 0.003,
- label: ship.label,
- value: ship.value,
- vessels: ship.vessels
- };
- });
- }
-
- allLabels = shipData;
-
- // Use htmlElementsData for ships with ship icons (similar to planes)
- const initialShipPoints = generateShipPoints(shipData);
- world.customLayerData(initialShipPoints)
- .customThreeObject(d => {
- // Create HTML element for ship icon
- const el = document.createElement('div');
- el.innerHTML = '🚢';
- el.style.color = 'rgba(100, 180, 255, 0.95)';
- el.style.fontSize = '16px';
- el.style.cursor = 'pointer';
- el.style.filter = 'drop-shadow(0 0 4px rgba(100, 180, 255, 0.8))';
- el.title = \`\${d.label} - \${d.value} (\${d.vessels} vessels)\`;
-
- // Convert HTML to texture for THREE.js
- const canvas = document.createElement('canvas');
- canvas.width = 64;
- canvas.height = 64;
- const ctx = canvas.getContext('2d');
- ctx.font = '48px Arial';
- ctx.fillText('🚢', 8, 48);
-
- const texture = new THREE.CanvasTexture(canvas);
- const material = new THREE.SpriteMaterial({
- map: texture,
- transparent: true,
- opacity: 0.95
- });
- const sprite = new THREE.Sprite(material);
- sprite.scale.set(2, 2, 1);
-
- return sprite;
- })
- .customThreeObjectUpdate((obj, d) => {
- Object.assign(obj.position, world.getCoords(d.lat, d.lng, d.altitude));
- });
-
- // Animate ships along routes
- setInterval(() => {
- // Update progress for each ship
- shipData.forEach(ship => {
- ship.progress = (ship.progress + 0.0002) % 1.0;
- });
-
- // Regenerate ship positions
- const updatedShipPoints = generateShipPoints(shipData);
- world.customLayerData(updatedShipPoints);
- }, 200);
- }
-
- function createPlanes() {
- // Professional plane visualization using proper globe coordinates
- const planeData = airRoutes.map((route, routeIdx) => ({
- routeIdx: routeIdx,
- progress: Math.random(),
- startLat: route.start.lat,
- startLng: route.start.lng,
- endLat: route.end.lat,
- endLng: route.end.lng,
- label: route.name,
- value: route.value,
- flights: route.flights
- }));
-
- // Calculate interpolated positions along arc
- function interpolateArc(startLat, startLng, endLat, endLng, progress) {
- const lat = startLat + (endLat - startLat) * progress;
- const lng = startLng + (endLng - startLng) * progress;
- return { lat, lng };
- }
-
- // Generate plane positions
- function generatePlanePoints(planesData) {
- return planesData.map(plane => {
- const pos = interpolateArc(
- plane.startLat,
- plane.startLng,
- plane.endLat,
- plane.endLng,
- plane.progress
- );
- return {
- lat: pos.lat,
- lng: pos.lng,
- size: 0.15,
- color: 'rgba(255, 200, 100, 0.95)',
- altitude: 0.01, // Higher altitude for planes
- label: plane.label,
- value: plane.value,
- flights: plane.flights
- };
- });
- }
-
- planeLabels = planeData;
-
- // Use separate layer for planes
- const initialPlanePoints = generatePlanePoints(planeData);
- world.htmlElementsData(initialPlanePoints)
- .htmlElement(d => {
- const el = document.createElement('div');
- el.innerHTML = '✈';
- el.style.color = 'rgba(255, 200, 100, 0.95)';
- el.style.fontSize = '16px';
- el.style.cursor = 'pointer';
- el.style.filter = 'drop-shadow(0 0 4px rgba(255, 200, 100, 0.8))';
- el.style.transform = 'rotate(-45deg)';
- el.title = \`\${d.label} - \${d.value} (\${d.flights} flights/week)\`;
- return el;
- })
- .htmlAltitude(d => d.altitude);
-
- // Animate planes along routes (faster than ships)
- setInterval(() => {
- // Update progress for each plane
- planeData.forEach(plane => {
- plane.progress = (plane.progress + 0.0004) % 1.0; // Faster than ships
- });
-
- // Regenerate plane positions
- const updatedPlanePoints = generatePlanePoints(planeData);
- world.htmlElementsData(updatedPlanePoints);
- }, 200);
- }
-
- function createSatellites() {
- // Create satellite data in different orbits with unique orbital paths
- // Speeds reduced significantly for more realistic and pleasant viewing
- const satelliteOrbits = [
- // Low Earth Orbit satellites (LEO) - closer to Earth, faster orbits
- { name: 'GPS-1', inclination: 55, altitude: 0.35, speed: 0.0008, color: '#00ff00', orbitId: 'gps' },
- { name: 'GPS-2', inclination: 55, altitude: 0.35, speed: 0.0008, color: '#00ff00', phaseOffset: Math.PI, orbitId: 'gps' },
- { name: 'IRNSS-1', inclination: 29, altitude: 0.37, speed: 0.0007, color: '#ffd700', orbitId: 'irnss' },
- { name: 'IRNSS-2', inclination: 29, altitude: 0.37, speed: 0.0007, color: '#ffd700', phaseOffset: Math.PI / 2, orbitId: 'irnss' },
- { name: 'Starlink-1', inclination: 53, altitude: 0.32, speed: 0.0009, color: '#00ccff', orbitId: 'starlink' },
- { name: 'Starlink-2', inclination: 53, altitude: 0.32, speed: 0.0009, color: '#00ccff', phaseOffset: 2 * Math.PI / 3, orbitId: 'starlink' },
- { name: 'Starlink-3', inclination: 53, altitude: 0.32, speed: 0.0009, color: '#00ccff', phaseOffset: 4 * Math.PI / 3, orbitId: 'starlink' },
- // Medium Earth Orbit (MEO) - higher altitude, medium speed
- { name: 'GLONASS-1', inclination: 64.8, altitude: 0.42, speed: 0.0006, color: '#ff6b6b', orbitId: 'glonass' },
- { name: 'GLONASS-2', inclination: 64.8, altitude: 0.42, speed: 0.0006, color: '#ff6b6b', phaseOffset: Math.PI / 3, orbitId: 'glonass' },
- { name: 'Galileo-1', inclination: 56, altitude: 0.40, speed: 0.0007, color: '#9d4edd', orbitId: 'galileo' },
- { name: 'Galileo-2', inclination: 56, altitude: 0.40, speed: 0.0007, color: '#9d4edd', phaseOffset: Math.PI / 2, orbitId: 'galileo' },
- // Geostationary orbit representation (higher altitude, slowest)
- { name: 'INSAT-1', inclination: 0, altitude: 0.50, speed: 0.0004, color: '#ff9500', orbitId: 'insat' },
- { name: 'INSAT-2', inclination: 0, altitude: 0.50, speed: 0.0004, color: '#ff9500', phaseOffset: Math.PI, orbitId: 'insat' },
- ];
-
- const satellites = satelliteOrbits.map((orbit, idx) => ({
- id: idx,
- name: orbit.name,
- inclination: orbit.inclination,
- altitude: orbit.altitude,
- speed: orbit.speed,
- color: orbit.color,
- orbitId: orbit.orbitId,
- phase: orbit.phaseOffset || 0
- }));
-
- // Create orbital ring paths - draw complete circles for each unique orbit
- function createOrbitalPaths() {
- const uniqueOrbits = new Map();
-
- satelliteOrbits.forEach(orbit => {
- if (!uniqueOrbits.has(orbit.orbitId)) {
- uniqueOrbits.set(orbit.orbitId, {
- inclination: orbit.inclination,
- altitude: orbit.altitude,
- color: orbit.color,
- name: orbit.orbitId
- });
- }
- });
-
- const orbitalPaths = [];
- uniqueOrbits.forEach((orbit, orbitId) => {
- const numPoints = 100; // Number of points to draw the orbital ring
- const pathPoints = [];
-
- for (let i = 0; i <= numPoints; i++) {
- const angle = (i / numPoints) * 2 * Math.PI;
- const inclinationRad = (orbit.inclination * Math.PI) / 180;
-
- // Calculate position on orbit
- const x = Math.cos(angle);
- const y = Math.sin(angle) * Math.cos(inclinationRad);
- const z = Math.sin(angle) * Math.sin(inclinationRad);
-
- // Convert to lat/lng
- const lat = Math.asin(y) * (180 / Math.PI);
- const lng = Math.atan2(z, x) * (180 / Math.PI);
-
- pathPoints.push([lat, lng]);
- }
-
- orbitalPaths.push({
- id: orbitId,
- color: orbit.color,
- altitude: orbit.altitude,
- points: pathPoints
- });
- });
-
- return orbitalPaths;
- }
-
- const orbitalPaths = createOrbitalPaths();
-
- // Store orbital paths for toggling
- orbitalPathsData = orbitalPaths;
-
- // Draw orbital rings using pathsData
- world.pathsData(orbitalPaths)
- .pathPoints('points')
- .pathPointLat(p => p[0])
- .pathPointLng(p => p[1])
- .pathColor('color')
- .pathStroke(0.8)
- .pathDashLength(0.5)
- .pathDashGap(0.1)
- .pathDashAnimateTime(20000)
- .pathTransitionDuration(0)
- .pathPointAlt('altitude');
-
- // Function to calculate satellite position in orbit
- function calculateSatellitePosition(sat, time) {
- const angle = sat.phase + time * sat.speed;
-
- // Convert orbital elements to 3D position
- const inclinationRad = (sat.inclination * Math.PI) / 180;
-
- // Orbital position
- const x = Math.cos(angle);
- const y = Math.sin(angle) * Math.cos(inclinationRad);
- const z = Math.sin(angle) * Math.sin(inclinationRad);
-
- // Convert to lat/lng (approximate)
- const lat = Math.asin(y) * (180 / Math.PI);
- const lng = Math.atan2(z, x) * (180 / Math.PI);
-
- return { lat, lng, altitude: sat.altitude };
- }
-
- // Create satellite objects with animation
- const satelliteData = satellites.map((sat, idx) => ({
- ...sat,
- progress: (idx / satellites.length) // Distribute satellites evenly around orbit initially
- }));
-
- // Function to generate satellite HTML elements
- function generateSatellitePoints(satsData) {
- return satsData.map(sat => {
- const angle = sat.progress * 2 * Math.PI;
- const inclinationRad = (sat.inclination * Math.PI) / 180;
-
- // Calculate position on orbit
- const x = Math.cos(angle);
- const y = Math.sin(angle) * Math.cos(inclinationRad);
- const z = Math.sin(angle) * Math.sin(inclinationRad);
-
- // Convert to lat/lng
- const lat = Math.asin(y) * (180 / Math.PI);
- const lng = Math.atan2(z, x) * (180 / Math.PI);
-
- return {
- lat: lat,
- lng: lng,
- altitude: sat.altitude,
- name: sat.name,
- color: sat.color
- };
- });
- }
-
- // Initial satellite positions - use objectsData for satellites (separate from planes)
- const initialSatellitePoints = generateSatellitePoints(satelliteData);
-
- world.objectsData(initialSatellitePoints)
- .objectLat('lat')
- .objectLng('lng')
- .objectAltitude('altitude')
- .objectLabel(d => \`
- <div style="background: rgba(10,10,10,0.92); padding: 5px 9px; border-left: 2px solid \${d.color}; font-family: 'Segoe UI', sans-serif; font-size: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.4);">
- <span style="color: #e0e0e0; font-weight: 500;">🛰 \${d.name}</span>
- </div>
- \`)
- .objectThreeObject(d => {
- // Create satellite icon using canvas texture with better visibility
- const canvas = document.createElement('canvas');
- canvas.width = 128;
- canvas.height = 128;
- const ctx = canvas.getContext('2d');
-
- // Add colored background circle for visibility
- ctx.beginPath();
- ctx.arc(64, 64, 50, 0, 2 * Math.PI);
- ctx.fillStyle = d.color;
- ctx.globalAlpha = 0.4;
- ctx.fill();
- ctx.globalAlpha = 1.0;
-
- // Add bright border
- ctx.strokeStyle = d.color;
- ctx.lineWidth = 3;
- ctx.stroke();
-
- // Draw satellite emoji larger and centered
- ctx.font = 'bold 70px Arial';
- ctx.textAlign = 'center';
- ctx.textBaseline = 'middle';
- ctx.fillStyle = '#ffffff';
- ctx.fillText('🛰', 64, 64);
-
- const texture = new THREE.CanvasTexture(canvas);
- const material = new THREE.SpriteMaterial({
- map: texture,
- transparent: true,
- opacity: 1.0,
- sizeAttenuation: true
- });
- const sprite = new THREE.Sprite(material);
- sprite.scale.set(4, 4, 1);
-
- // Add pulsing glow ring around satellite
- const ringGeometry = new THREE.RingGeometry(1.5, 2.0, 16);
- const ringMaterial = new THREE.MeshBasicMaterial({
- color: d.color,
- transparent: true,
- opacity: 0.6,
- side: THREE.DoubleSide
- });
- const ring = new THREE.Mesh(ringGeometry, ringMaterial);
-
- const group = new THREE.Group();
- group.add(sprite);
- group.add(ring);
-
- return group;
- });
-
- // Animate satellites along their orbits at a gentle, realistic pace
- setInterval(() => {
- if (showSatellitesFlag) {
- // Update progress for each satellite with reduced multiplier
- satelliteData.forEach(sat => {
- sat.progress = (sat.progress + sat.speed * 0.15) % 1.0;
- });
-
- // Regenerate satellite positions
- const updatedSatellitePoints = generateSatellitePoints(satelliteData);
- world.objectsData(updatedSatellitePoints);
- }
- }, 100);
- }
-
- window.addMarker = function(lat, lng, title, type) {
- const icons = {
- 'Ship': '🚢',
- 'Port': '⚓',
- 'Industry': '🏭',
- 'Bank': '🏦',
- 'Exchange': '💱'
- };
-
- markers.push({ lat, lng, title, type, icon: icons[type] || icons['Ship'] });
-
- world.htmlElementsData([...allLabels, ...markers])
- .htmlElement(d => {
- const el = document.createElement('div');
- el.innerHTML = d.icon || d.label;
- el.style.color = d.color || '#ff8c00';
- el.style.fontSize = '20px';
- el.style.cursor = 'pointer';
- el.style.textShadow = '0 0 5px ' + (d.color || '#ff8c00');
- el.title = d.title || d.label || '';
- return el;
- });
- };
-
- window.clearMarkers = function() {
- markers = [];
- world.htmlElementsData(allLabels);
- };
-
- // Function to update with real vessel data from API (optimized for performance)
- var realVesselPoints = [];
- var vesselTexture = null; // Reuse texture for better performance
-
- // Create vessel texture once
- function createVesselTexture() {
- if (!vesselTexture) {
- const canvas = document.createElement('canvas');
- canvas.width = 64;
- canvas.height = 64;
- const ctx = canvas.getContext('2d');
- ctx.font = '48px Arial';
- ctx.fillText('🚢', 8, 48);
- vesselTexture = new THREE.CanvasTexture(canvas);
- }
- return vesselTexture;
- }
-
- window.updateRealVessels = function(vessels) {
- console.log('Updating real vessels:', vessels.length);
-
- if (!vessels || vessels.length === 0) {
- world.customLayerData([]);
- realVesselPoints = [];
- return;
- }
-
- // Convert API vessel data to globe points
- realVesselPoints = vessels.map(vessel => ({
- lat: vessel.lat,
- lng: vessel.lng,
- size: 0.15, // Slightly smaller for better performance
- color: 'rgba(0, 255, 255, 0.9)', // Cyan for real vessels
- altitude: 0.003,
- name: vessel.name,
- imo: vessel.imo,
- speed: vessel.speed,
- angle: vessel.angle,
- from_port: vessel.from_port,
- to_port: vessel.to_port,
- route_progress: vessel.route_progress
- }));
-
- // Update the custom layer with real vessels (optimized rendering)
- if (showShipsFlag) {
- const texture = createVesselTexture();
-
- world.customLayerData(realVesselPoints)
- .customThreeObject(d => {
- // Reuse the same texture for all vessels for better performance
- const material = new THREE.SpriteMaterial({
- map: texture,
- transparent: true,
- opacity: 0.9,
- sizeAttenuation: true
- });
- const sprite = new THREE.Sprite(material);
- sprite.scale.set(1.5, 1.5, 1);
-
- return sprite;
- })
- .customThreeObjectUpdate((obj, d) => {
- const coords = world.getCoords(d.lat, d.lng, d.altitude);
- if (coords && coords.x !== undefined && coords.y !== undefined && coords.z !== undefined) {
- Object.assign(obj.position, coords);
- }
- });
- }
- };
-
- // Manual mode switching between 3D Globe and 2D Map
- var vesselMarkers = []; // Store 2D map vessel markers
- window.switchMapMode = function(mode, vesselsFromReact) {
- console.log('Switching to mode:', mode, '| Vessel data from React:', vesselsFromReact ? vesselsFromReact.length : 0, '| realVesselPoints:', realVesselPoints ? realVesselPoints.length : 0);
-
- if (mode === '2D') {
- // Switch to 2D Map Mode - Clean, Only Real Vessels
- initMap2D();
-
- document.getElementById('globeViz').style.display = 'none';
- document.getElementById('mapViz').style.display = 'block';
- document.getElementById('modeIndicator').textContent = '2D MAP MODE - Real Vessels Only';
- document.getElementById('modeIndicator').style.background = 'rgba(255, 215, 0, 0.9)';
-
- // Center on Mumbai area and load vessels
- setTimeout(() => {
- if (map2D) {
- map2D.setView([19.0, 72.8], 11);
- map2D.invalidateSize();
-
- // Prefer vessels passed from React, fallback to realVesselPoints
- const vesselsToRender = vesselsFromReact || realVesselPoints;
-
- // Add real vessel markers to 2D map
- if (vesselsToRender && vesselsToRender.length > 0) {
- console.log('✅ Rendering vessels on 2D map:', vesselsToRender.length);
- updateVesselsOn2DMap(vesselsToRender);
- } else {
- console.warn('⚠️ No vessel data available! vesselsFromReact:', vesselsFromReact, 'realVesselPoints:', realVesselPoints);
- }
- }
- }, 200); // Increased timeout
-
- } else {
- // Switch to 3D Globe Mode
- document.getElementById('globeViz').style.display = 'block';
- document.getElementById('mapViz').style.display = 'none';
- document.getElementById('modeIndicator').textContent = '3D GLOBE MODE';
- document.getElementById('modeIndicator').style.background = 'rgba(0, 255, 255, 0.9)';
-
- // Clear 2D markers
- vesselMarkers.forEach(marker => marker.remove());
- vesselMarkers = [];
- }
- };
-
- // Function to update vessels on 2D map
- function updateVesselsOn2DMap(vessels) {
- console.log('updateVesselsOn2DMap called with', vessels ? vessels.length : 0, 'vessels');
- console.log('map2D exists:', !!map2D);
-
- if (!map2D) {
- console.error('❌ map2D is not initialized!');
- return;
- }
-
- if (!vessels || vessels.length === 0) {
- console.warn('⚠️ No vessels to display on 2D map');
- return;
- }
-
- // Clear existing markers
- vesselMarkers.forEach(marker => marker.remove());
- vesselMarkers = [];
-
- // Create custom ship icon
- const shipIcon = L.divIcon({
- className: 'vessel-marker',
- html: '<div style="font-size: 16px;">🚢</div>',
- iconSize: [20, 20],
- iconAnchor: [10, 10]
- });
-
- // Add vessel markers (limit to 500 for performance)
- const vesselsToDisplay = vessels.slice(0, 500);
- console.log('Displaying', vesselsToDisplay.length, 'vessels on 2D map');
-
- vesselsToDisplay.forEach(vessel => {
- const marker = L.marker([vessel.lat, vessel.lng], { icon: shipIcon })
- .bindPopup(\`
- <div style="font-family: 'Consolas', monospace; font-size: 11px;">
- <div style="font-weight: bold; color: #0ff; margin-bottom: 4px;">\${vessel.name}</div>
- <div style="font-size: 9px;">
- <div><strong>IMO:</strong> \${vessel.imo}</div>
- <div><strong>Position:</strong> \${vessel.lat.toFixed(4)}°, \${vessel.lng.toFixed(4)}°</div>
- <div><strong>Speed:</strong> \${vessel.speed} kts</div>
- \${vessel.from_port ? \`<div><strong>From:</strong> \${vessel.from_port}</div>\` : ''}
- \${vessel.to_port ? \`<div><strong>To:</strong> \${vessel.to_port}</div>\` : ''}
- </div>
- </div>
- \`)
- .addTo(map2D);
-
- vesselMarkers.push(marker);
- });
-
- console.log(\`Added \${vesselMarkers.length} vessel markers to 2D map\`);
- }
-
- // Update 2D map vessels when real vessels are updated
- var previousUpdateRealVessels = window.updateRealVessels;
- window.updateRealVessels = function(vessels) {
- previousUpdateRealVessels(vessels); // Update 3D globe
-
- // Also update 2D map if visible
- const mapViz = document.getElementById('mapViz');
- if (mapViz && mapViz.style.display === 'block' && map2D) {
- updateVesselsOn2DMap(vessels.map(v => ({
- lat: v.lat,
- lng: v.lng,
- name: v.name,
- imo: v.imo,
- speed: v.speed,
- from_port: v.from_port,
- to_port: v.to_port
- })));
- }
- };
-
- window.toggleRoutes = function() {
- if (showRoutesFlag) {
- world.arcsData([]);
- } else {
- createRoutes();
- }
- showRoutesFlag = !showRoutesFlag;
- };
-
- window.toggleShips = function() {
- if (showShipsFlag) {
- world.customLayerData([]);
- } else {
- // Show real vessels if available, otherwise show mock ships
- if (realVesselPoints.length > 0) {
- world.customLayerData(realVesselPoints)
- .customThreeObject(d => {
- const canvas = document.createElement('canvas');
- canvas.width = 64;
- canvas.height = 64;
- const ctx = canvas.getContext('2d');
- ctx.font = '48px Arial';
- ctx.fillText('🚢', 8, 48);
-
- const texture = new THREE.CanvasTexture(canvas);
- const material = new THREE.SpriteMaterial({
- map: texture,
- transparent: true,
- opacity: 0.95
- });
- const sprite = new THREE.Sprite(material);
- sprite.scale.set(2, 2, 1);
-
- return sprite;
- })
- .customThreeObjectUpdate((obj, d) => {
- Object.assign(obj.position, world.getCoords(d.lat, d.lng, d.altitude));
- });
- } else {
- // Fallback to mock ships
- function interpolateArc(startLat, startLng, endLat, endLng, progress) {
- const lat = startLat + (endLat - startLat) * progress;
- const lng = startLng + (endLng - startLng) * progress;
- return { lat, lng };
- }
-
- const shipPoints = allLabels.map(ship => {
- const pos = interpolateArc(ship.startLat, ship.startLng, ship.endLat, ship.endLng, ship.progress);
- return {
- lat: pos.lat,
- lng: pos.lng,
- size: 0.15,
- color: 'rgba(255, 255, 255, 0.95)',
- altitude: 0.003,
- label: ship.label,
- value: ship.value,
- vessels: ship.vessels
- };
- });
- world.customLayerData(shipPoints);
- }
- }
- showShipsFlag = !showShipsFlag;
- };
-
- window.togglePlanes = function() {
- if (showPlanesFlag) {
- world.htmlElementsData([]);
- } else {
- // Regenerate plane positions
- function interpolateArc(startLat, startLng, endLat, endLng, progress) {
- const lat = startLat + (endLat - startLat) * progress;
- const lng = startLng + (endLng - startLng) * progress;
- return { lat, lng };
- }
-
- const planePoints = planeLabels.map(plane => {
- const pos = interpolateArc(plane.startLat, plane.startLng, plane.endLat, plane.endLng, plane.progress);
- return {
- lat: pos.lat,
- lng: pos.lng,
- size: 0.15,
- color: 'rgba(255, 200, 100, 0.95)',
- altitude: 0.01,
- label: plane.label,
- value: plane.value,
- flights: plane.flights
- };
- });
- world.htmlElementsData(planePoints);
- }
- showPlanesFlag = !showPlanesFlag;
- };
-
- window.toggleRotation = function(shouldRotate) {
- userPausedRotation = !shouldRotate;
- world.controls().autoRotate = shouldRotate;
- console.log('Globe rotation:', shouldRotate ? 'enabled' : 'disabled');
- };
-
- var showSatellitesFlag = true;
- var orbitalPathsData = [];
-
- window.toggleSatellites = function() {
- showSatellitesFlag = !showSatellitesFlag;
-
- if (!showSatellitesFlag) {
- // Hide satellites and orbital paths
- world.objectsData([]);
- world.pathsData([]);
- } else {
- // Show orbital paths again
- world.pathsData(orbitalPathsData);
- // Satellites will be updated by the interval
- }
- };
-
- // Enable auto-rotation with enhanced zoom
- world.controls().autoRotate = true;
- world.controls().autoRotateSpeed = 0.2; // Slower, more professional rotation
- world.controls().enableDamping = true;
- world.controls().dampingFactor = 0.05;
-
- // Prevent extreme close zoom to avoid white screen issue
- world.controls().minDistance = 150; // Don't allow too close zoom (prevents white screen)
- world.controls().maxDistance = 800; // Very far zoom (space view)
- world.controls().zoomSpeed = 1.2; // Moderate zoom speed
- world.controls().enableZoom = true;
-
- console.log('Controls configured - minDistance:', 150, 'maxDistance:', 800);
-
- // Keep rotation state controlled by user toggle
- let userPausedRotation = false;
- let interactionTimeout;
- const resumeRotation = () => {
- clearTimeout(interactionTimeout);
- world.controls().autoRotate = false;
- interactionTimeout = setTimeout(() => {
- // Only resume if user hasn't manually paused
- if (!userPausedRotation) {
- world.controls().autoRotate = true;
- }
- }, 3000); // Resume after 3 seconds of inactivity (only if not manually paused)
- };
-
- // Function to switch between 3D and 2D modes
- function switchTo2D(lat, lng) {
- if (currentMode === '2D') return; // Prevent multiple switches
-
- // Use the most recent target coordinates (where user was actually looking)
- const finalLat = targetCoords.lat;
- const finalLng = targetCoords.lng;
-
- initMap2D(); // Initialize if needed
-
- document.getElementById('globeViz').style.display = 'none';
- document.getElementById('mapViz').style.display = 'block';
- document.getElementById('modeIndicator').textContent = '2D MAP MODE - Street Level';
- document.getElementById('modeIndicator').style.background = 'rgba(255, 215, 0, 0.9)';
-
- // Calculate zoom based on altitude (lower altitude = higher zoom)
- // More aggressive zoom calculation for better street detail
- const altitudeFactor = Math.max(0, 0.3 - lastGlobeView.altitude);
- const zoom2D = Math.max(14, Math.min(18, Math.floor(16 + altitudeFactor * 20)));
-
- // Set view and force map refresh
- setTimeout(() => {
- map2D.setView([finalLat, finalLng], zoom2D);
- map2D.invalidateSize();
-
- // Force tile refresh
- setTimeout(() => {
- map2D.eachLayer(function(layer) {
- if (layer instanceof L.TileLayer) {
- layer.redraw();
- }
- });
- console.log('2D map centered at:', finalLat.toFixed(6), finalLng.toFixed(6));
- }, 100);
- }, 50);
-
- currentMode = '2D';
- }
-
- function switchTo3D(lat, lng, altitude) {
- document.getElementById('globeViz').style.display = 'block';
- document.getElementById('mapViz').style.display = 'none';
- document.getElementById('modeIndicator').textContent = '3D GLOBE MODE';
- document.getElementById('modeIndicator').style.background = 'rgba(0, 255, 255, 0.9)';
-
- world.pointOfView({ lat, lng, altitude }, 500);
- currentMode = '3D';
- console.log('Switched to 3D mode at altitude:', altitude);
- }
-
- // Track zoom level (no auto-switching, manual control only)
- world.onZoom((view) => {
- lastGlobeView = view;
- targetCoords = { lat: view.lat, lng: view.lng };
- // Removed spam log: console.log('Globe zoom - altitude:', view.altitude, 'lat:', view.lat.toFixed(4), 'lng:', view.lng.toFixed(4));
- });
-
- // Listen for user interactions
- const container = document.getElementById('globeViz');
-
- // Track mouse position for accurate zoom targeting
- let mousePos = null;
- container.addEventListener('mousemove', (e) => {
- mousePos = { x: e.clientX, y: e.clientY };
- });
-
- // Get lat/lng from screen coordinates
- function getLatLngFromScreen(x, y) {
- try {
- const scene = world.scene();
- const camera = world.camera();
- const raycaster = new THREE.Raycaster();
- const mouse = new THREE.Vector2(
- (x / window.innerWidth) * 2 - 1,
- -(y / window.innerHeight) * 2 + 1
- );
-
- raycaster.setFromCamera(mouse, camera);
- const intersects = raycaster.intersectObject(scene.children.find(c => c.type === 'Mesh'), true);
-
- if (intersects.length > 0) {
- const point = intersects[0].point;
- const lat = Math.asin(point.y / Math.sqrt(point.x * point.x + point.y * point.y + point.z * point.z)) * 180 / Math.PI;
- const lng = Math.atan2(point.x, point.z) * 180 / Math.PI;
- return { lat, lng };
- }
- } catch (e) {
- console.log('Could not get exact coordinates, using view center');
- }
- return null;
- }
- container.addEventListener('mousedown', resumeRotation);
- container.addEventListener('wheel', (e) => {
- resumeRotation();
-
- // Update target coords based on mouse position
- if (mousePos) {
- const coords = getLatLngFromScreen(mousePos.x, mousePos.y);
- if (coords) {
- targetCoords = coords;
- console.log('Updated target from mouse:', targetCoords.lat.toFixed(4), targetCoords.lng.toFixed(4));
- }
- }
- });
- container.addEventListener('touchstart', resumeRotation);
-
- // Start with auto-rotation enabled
- world.controls().autoRotate = true;
-
- console.log('Event listeners added');
-
- createRoutes();
- createShips();
- createPlanes();
- createSatellites();
-
- // Handle window resize
- window.addEventListener('resize', () => {
- world.width(window.innerWidth).height(window.innerHeight);
- });
-
- console.log('3D Globe fully initialized');
- } catch (error) {
- console.error('Error initializing Globe:', error);
- document.body.innerHTML = '<div style="color: red; padding: 20px; font-family: monospace;">ERROR: Failed to load 3D Globe<br>Check console for details<br><br>' + error.message + '</div>';
- }
- }, 500); // Wait 500ms for libraries to load
- </script>
-</body>
-</html>
- `;
-
- return (
- <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: '#000' }}>
- <style>{`
- *::-webkit-scrollbar { width: 6px; height: 6px; }
- *::-webkit-scrollbar-track { background: #0a0a0a; }
- *::-webkit-scrollbar-thumb { background: #1a1a1a; border-radius: 3px; }
- *::-webkit-scrollbar-thumb:hover { background: #2a2a2a; }
- `}</style>
-
- {/* CIA-Style Header */}
- <div style={{
- borderBottom: '2px solid #00ff00',
- padding: '8px 16px',
- background: 'linear-gradient(180deg, #0a0a0a 0%, #000 100%)',
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- flexShrink: 0
- }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
- <span style={{ color: '#00ff00', fontSize: '14px', fontWeight: 'bold', letterSpacing: '2px' }}>
- ⚓ FINCEPT MARITIME INTELLIGENCE
- </span>
- <div style={{ width: '1px', height: '16px', background: '#00ff00' }} />
- <span style={{ color: '#0ff', fontSize: '10px' }}>CLASSIFIED // TRADE ROUTE ANALYSIS</span>
- </div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <button
- onClick={toggleMapMode}
- style={{
- background: mapMode === '2D' ? '#ffd700' : '#0a0a0a',
- color: mapMode === '2D' ? '#000' : '#ffd700',
- border: '1px solid #ffd700',
- padding: '4px 12px',
- fontSize: '9px',
- cursor: 'pointer',
- fontWeight: 'bold',
- fontFamily: 'Consolas, monospace',
- transition: 'all 0.2s'
- }}
- >
- {mapMode === '3D' ? '🌍 3D GLOBE' : '🗺️ 2D MAP'}
- </button>
- {mapMode === '3D' && (
- <button
- onClick={() => {
- const newRotating = !isRotating;
- setIsRotating(newRotating);
- if (mapRef.current?.contentWindow) {
- (mapRef.current.contentWindow as any).toggleRotation?.(newRotating);
- }
- }}
- style={{
- background: isRotating ? '#0a0a0a' : '#1a1a1a',
- color: isRotating ? '#00ff00' : '#888',
- border: `1px solid ${isRotating ? '#00ff00' : '#444'}`,
- padding: '4px 10px',
- fontSize: '9px',
- cursor: 'pointer',
- fontWeight: 'bold',
- fontFamily: 'Consolas, monospace',
- transition: 'all 0.2s'
- }}
- >
- {isRotating ? '● ROTATING' : '○ PAUSED'}
- </button>
- )}
- <span style={{ color: intelligence.threat_level === 'critical' ? '#ff0000' : intelligence.threat_level === 'high' ? '#ff8c00' : intelligence.threat_level === 'medium' ? '#ffd700' : '#00ff00', fontSize: '10px', fontWeight: 'bold' }}>
- THREAT: {intelligence.threat_level.toUpperCase()}
- </span>
- <span style={{ color: '#888', fontSize: '9px' }}>{new Date(intelligence.timestamp).toLocaleString()}</span>
- </div>
- </div>
-
- {/* Main Layout */}
- <div style={{ flex: 1, display: 'flex', minHeight: 0, overflow: 'hidden' }}>
-
- {/* Left Sidebar - Intelligence Panel */}
- <div style={{ width: '280px', borderRight: '1px solid #1a1a1a', display: 'flex', flexDirection: 'column', background: '#000', flexShrink: 0 }}>
-
- {/* Intelligence Stats */}
- <div style={{ padding: '12px', borderBottom: '1px solid #1a1a1a' }}>
- <div style={{ color: '#00ff00', fontSize: '10px', fontWeight: 'bold', marginBottom: '8px', letterSpacing: '1px' }}>GLOBAL INTEL</div>
- {isLoadingVessels && (
- <div style={{ background: 'rgba(0, 255, 255, 0.1)', border: '1px solid #0ff', padding: '6px', fontSize: '8px', color: '#0ff', marginBottom: '8px', textAlign: 'center' }}>
- ⏳ LOADING VESSELS...
- </div>
- )}
- {vesselLoadError && (
- <div style={{ background: 'rgba(255, 0, 0, 0.1)', border: '1px solid #ff0000', padding: '6px', fontSize: '8px', color: '#ff0000', marginBottom: '8px' }}>
- ⚠ {vesselLoadError}
- </div>
- )}
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
- <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '8px' }}>
- <div style={{ color: '#888', fontSize: '8px' }}>TOTAL VESSELS</div>
- <div style={{ color: '#0ff', fontSize: '16px', fontWeight: 'bold' }}>{intelligence.active_vessels}</div>
- </div>
- <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '8px' }}>
- <div style={{ color: '#888', fontSize: '8px' }}>DISPLAYED</div>
- <div style={{ color: '#00ff00', fontSize: '16px', fontWeight: 'bold' }}>{realVessels.length}</div>
- </div>
- <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '8px' }}>
- <div style={{ color: '#888', fontSize: '8px' }}>ROUTES</div>
- <div style={{ color: '#0ff', fontSize: '16px', fontWeight: 'bold' }}>{intelligence.monitored_routes}</div>
- </div>
- <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '8px' }}>
- <div style={{ color: '#888', fontSize: '8px' }}>AIRCRAFT</div>
- <div style={{ color: 'rgba(255, 200, 100, 0.95)', fontSize: '16px', fontWeight: 'bold' }}>342</div>
- </div>
- <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '8px' }}>
- <div style={{ color: '#888', fontSize: '8px' }}>SATELLITES</div>
- <div style={{ color: 'rgba(138, 43, 226, 0.9)', fontSize: '16px', fontWeight: 'bold' }}>13</div>
- </div>
- <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '8px', gridColumn: 'span 2' }}>
- <div style={{ color: '#888', fontSize: '8px' }}>TRADE VOLUME (24H)</div>
- <div style={{ color: '#00ff00', fontSize: '16px', fontWeight: 'bold' }}>{intelligence.trade_volume}</div>
- </div>
- <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '8px' }}>
- <div style={{ color: '#888', fontSize: '8px' }}>MAJOR PORTS</div>
- <div style={{ color: '#ffa500', fontSize: '14px', fontWeight: 'bold' }}>6</div>
- </div>
- <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '8px' }}>
- <div style={{ color: '#888', fontSize: '8px' }}>AIRPORTS</div>
- <div style={{ color: '#9d4edd', fontSize: '14px', fontWeight: 'bold' }}>8</div>
- </div>
- </div>
- </div>
-
- {/* Trade Routes List */}
- <div style={{ flex: 1, overflowY: 'auto', padding: '12px', minHeight: 0 }}>
- <div style={{ color: '#00ff00', fontSize: '10px', fontWeight: 'bold', marginBottom: '8px', letterSpacing: '1px' }}>TRADE CORRIDORS</div>
- {tradeRoutes.map((route, idx) => (
- <div
- key={idx}
- onClick={() => setSelectedRoute(route)}
- style={{
- background: selectedRoute?.name === route.name ? '#1a1a1a' : '#0a0a0a',
- border: `1px solid ${route.status === 'critical' ? '#ff0000' : route.status === 'delayed' ? '#ffd700' : '#1a1a1a'}`,
- padding: '8px',
- marginBottom: '6px',
- cursor: 'pointer',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => e.currentTarget.style.background = '#1a1a1a'}
- onMouseLeave={(e) => e.currentTarget.style.background = selectedRoute?.name === route.name ? '#1a1a1a' : '#0a0a0a'}
- >
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
- <span style={{ color: '#0ff', fontSize: '9px', fontWeight: 'bold' }}>{route.name}</span>
- <span style={{
- color: route.status === 'critical' ? '#ff0000' : route.status === 'delayed' ? '#ffd700' : '#00ff00',
- fontSize: '7px',
- padding: '2px 4px',
- background: '#000',
- border: `1px solid ${route.status === 'critical' ? '#ff0000' : route.status === 'delayed' ? '#ffd700' : '#00ff00'}`
- }}>
- {route.status.toUpperCase()}
- </span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: '#888', fontSize: '8px' }}>Value: {route.value}</span>
- <span style={{ color: '#888', fontSize: '8px' }}>Ships: {route.vessels}</span>
- </div>
- </div>
- ))}
- </div>
-
- {/* Map Controls */}
- <div style={{ padding: '12px', borderTop: '1px solid #1a1a1a' }}>
- <div style={{ color: '#00ff00', fontSize: '10px', fontWeight: 'bold', marginBottom: '8px', letterSpacing: '1px' }}>MAP CONTROLS</div>
- <div style={{ display: 'flex', gap: '6px', marginBottom: '6px' }}>
- <button
- onClick={() => {
- setShowRoutes(!showRoutes);
- if (mapRef.current?.contentWindow) {
- (mapRef.current.contentWindow as any).toggleRoutes?.();
- }
- }}
- style={{
- flex: 1,
- background: showRoutes ? '#0ff' : '#0a0a0a',
- color: showRoutes ? '#000' : '#0ff',
- border: '1px solid #0ff',
- padding: '6px',
- fontSize: '9px',
- cursor: 'pointer',
- fontWeight: 'bold'
- }}
- >
- ROUTES
- </button>
- <button
- onClick={() => {
- setShowShips(!showShips);
- if (mapRef.current?.contentWindow) {
- (mapRef.current.contentWindow as any).toggleShips?.();
- }
- }}
- style={{
- flex: 1,
- background: showShips ? '#0ff' : '#0a0a0a',
- color: showShips ? '#000' : '#0ff',
- border: '1px solid #0ff',
- padding: '6px',
- fontSize: '9px',
- cursor: 'pointer',
- fontWeight: 'bold'
- }}
- >
- VESSELS
- </button>
- </div>
- <div style={{ display: 'flex', gap: '6px', marginBottom: '6px' }}>
- <button
- onClick={() => {
- setShowPlanes(!showPlanes);
- if (mapRef.current?.contentWindow) {
- (mapRef.current.contentWindow as any).togglePlanes?.();
- }
- }}
- style={{
- flex: 1,
- background: showPlanes ? 'rgba(255, 200, 100, 0.9)' : '#0a0a0a',
- color: showPlanes ? '#000' : 'rgba(255, 200, 100, 0.9)',
- border: '1px solid rgba(255, 200, 100, 0.9)',
- padding: '6px',
- fontSize: '9px',
- cursor: 'pointer',
- fontWeight: 'bold'
- }}
- >
- AIRCRAFT
- </button>
- <button
- onClick={() => {
- setShowSatellites(!showSatellites);
- if (mapRef.current?.contentWindow) {
- (mapRef.current.contentWindow as any).toggleSatellites?.();
- }
- }}
- style={{
- flex: 1,
- background: showSatellites ? 'rgba(138, 43, 226, 0.9)' : '#0a0a0a',
- color: showSatellites ? '#fff' : 'rgba(138, 43, 226, 0.9)',
- border: '1px solid rgba(138, 43, 226, 0.9)',
- padding: '6px',
- fontSize: '9px',
- cursor: 'pointer',
- fontWeight: 'bold'
- }}
- >
- SATELLITES
- </button>
- </div>
- <button
- onClick={() => {
- clearMarkers();
- if (mapRef.current?.contentWindow) {
- (mapRef.current.contentWindow as any).clearMarkers?.();
- }
- }}
- style={{
- width: '100%',
- background: '#0a0a0a',
- color: '#ff0000',
- border: '1px solid #ff0000',
- padding: '6px',
- fontSize: '9px',
- cursor: 'pointer',
- fontWeight: 'bold'
- }}
- >
- CLEAR ALL MARKERS
- </button>
- </div>
- </div>
-
- {/* Center - Map */}
- <div style={{ flex: 1, position: 'relative', minWidth: 0, overflow: 'hidden' }}>
- <iframe
- ref={mapRef}
- srcDoc={mapHTML}
- style={{
- width: '100%',
- height: '100%',
- border: 'none',
- background: '#000'
- }}
- />
- {/* Map Overlay - Coordinates Display */}
- <div style={{
- position: 'absolute',
- bottom: '16px',
- left: '16px',
- background: 'rgba(0, 0, 0, 0.9)',
- border: '1px solid #0ff',
- padding: '8px 12px',
- color: '#0ff',
- fontSize: '9px',
- fontFamily: 'Consolas, monospace'
- }}>
- <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>HYBRID 3D/2D SYSTEM ACTIVE</div>
- <div>CENTER: 20.0000° N, 75.0000° E</div>
- <div>MODE: Globe.GL 3D → Auto-switches → Leaflet 2D</div>
- <div style={{ marginTop: '4px', color: '#ffd700' }}>🔍 ZOOM: Deep zoom auto-switches to street-level map!</div>
- </div>
- </div>
-
- {/* Right Sidebar - Marker Tools */}
- <div style={{ width: '280px', borderLeft: '1px solid #1a1a1a', display: 'flex', flexDirection: 'column', background: '#000', flexShrink: 0 }}>
-
- {/* Selected Route Details */}
- {selectedRoute && (
- <div style={{ padding: '12px', borderBottom: '1px solid #1a1a1a' }}>
- <div style={{ color: '#00ff00', fontSize: '10px', fontWeight: 'bold', marginBottom: '8px', letterSpacing: '1px' }}>ROUTE DETAILS</div>
- <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '10px' }}>
- <div style={{ color: '#0ff', fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>{selectedRoute.name}</div>
- <div style={{ display: 'grid', gap: '6px', fontSize: '9px' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: '#888' }}>Value:</span>
- <span style={{ color: '#fff' }}>{selectedRoute.value}</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: '#888' }}>Status:</span>
- <span style={{ color: selectedRoute.status === 'critical' ? '#ff0000' : selectedRoute.status === 'delayed' ? '#ffd700' : '#00ff00' }}>
- {selectedRoute.status.toUpperCase()}
- </span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: '#888' }}>Active Vessels:</span>
- <span style={{ color: '#fff' }}>{selectedRoute.vessels}</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: '#888' }}>Waypoints:</span>
- <span style={{ color: '#fff' }}>{selectedRoute.coordinates.length}</span>
- </div>
- </div>
- </div>
- </div>
- )}
-
- {/* Vessel Search by IMO */}
- <div style={{ padding: '12px', borderBottom: '1px solid #1a1a1a' }}>
- <div style={{ color: '#00ff00', fontSize: '10px', fontWeight: 'bold', marginBottom: '8px', letterSpacing: '1px' }}>VESSEL SEARCH</div>
-
- <div style={{ marginBottom: '8px' }}>
- <div style={{ color: '#888', fontSize: '8px', marginBottom: '4px' }}>IMO NUMBER</div>
- <div style={{ display: 'flex', gap: '4px' }}>
- <input
- type="text"
- value={searchImo}
- onChange={(e) => setSearchImo(e.target.value)}
- onKeyPress={(e) => e.key === 'Enter' && searchVesselByImo()}
- placeholder="e.g., 8020604"
- style={{
- flex: 1,
- background: '#0a0a0a',
- color: '#0ff',
- border: '1px solid #1a1a1a',
- padding: '6px',
- fontSize: '9px',
- outline: 'none'
- }}
- />
- <button
- onClick={searchVesselByImo}
- disabled={searchingVessel}
- style={{
- background: searchingVessel ? '#1a1a1a' : '#0ff',
- color: searchingVessel ? '#888' : '#000',
- border: '1px solid #0ff',
- padding: '6px 12px',
- fontSize: '9px',
- cursor: searchingVessel ? 'not-allowed' : 'pointer',
- fontWeight: 'bold'
- }}
- >
- {searchingVessel ? 'SEARCHING...' : 'TRACK'}
- </button>
- </div>
- </div>
-
- {searchError && (
- <div style={{ background: 'rgba(255, 0, 0, 0.1)', border: '1px solid #ff0000', padding: '6px', fontSize: '8px', color: '#ff0000', marginBottom: '8px' }}>
- ⚠ {searchError}
- </div>
- )}
-
- {searchResult && (
- <div style={{ background: '#0a0a0a', border: '1px solid #0ff', padding: '8px', fontSize: '9px', marginBottom: '8px' }}>
- <div style={{ color: '#0ff', fontWeight: 'bold', marginBottom: '6px' }}>{searchResult.name}</div>
- <div style={{ display: 'grid', gap: '4px', color: '#fff' }}>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: '#888' }}>IMO:</span>
- <span>{searchResult.imo}</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: '#888' }}>Position:</span>
- <span>{parseFloat(searchResult.last_pos_latitude).toFixed(4)}°, {parseFloat(searchResult.last_pos_longitude).toFixed(4)}°</span>
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: '#888' }}>Speed:</span>
- <span>{searchResult.last_pos_speed} kts</span>
- </div>
- {searchResult.route_from_port_name && (
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: '#888' }}>From:</span>
- <span>{searchResult.route_from_port_name}</span>
- </div>
- )}
- {searchResult.route_to_port_name && (
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: '#888' }}>To:</span>
- <span>{searchResult.route_to_port_name}</span>
- </div>
- )}
- </div>
- </div>
- )}
- </div>
-
- {/* Add Markers */}
- <div style={{ padding: '12px', borderBottom: '1px solid #1a1a1a' }}>
- <div style={{ color: '#00ff00', fontSize: '10px', fontWeight: 'bold', marginBottom: '8px', letterSpacing: '1px' }}>ADD TARGET</div>
-
- <div style={{ marginBottom: '8px' }}>
- <div style={{ color: '#888', fontSize: '8px', marginBottom: '4px' }}>MARKER TYPE</div>
- <select
- value={markerType}
- onChange={(e) => setMarkerType(e.target.value as MarkerData['type'])}
- style={{
- width: '100%',
- background: '#0a0a0a',
- color: '#0ff',
- border: '1px solid #1a1a1a',
- padding: '6px',
- fontSize: '9px'
- }}
- >
- <option value="Ship">🚢 Ship</option>
- <option value="Port">⚓ Port</option>
- <option value="Industry">🏭 Industry</option>
- <option value="Bank">🏦 Bank</option>
- <option value="Exchange">💱 Exchange</option>
- </select>
- </div>
-
- <div style={{ color: '#888', fontSize: '8px', marginBottom: '8px' }}>QUICK ADD PRESETS</div>
- <div style={{ display: 'grid', gap: '4px' }}>
- {presetLocations.map((preset, idx) => (
- <button
- key={idx}
- onClick={() => {
- addPreset(preset);
- if (mapRef.current?.contentWindow) {
- (mapRef.current.contentWindow as any).addMarker?.(preset.lat, preset.lng, preset.name, preset.type);
- }
- }}
- style={{
- background: '#0a0a0a',
- color: '#fff',
- border: '1px solid #1a1a1a',
- padding: '6px',
- fontSize: '9px',
- cursor: 'pointer',
- textAlign: 'left'
- }}
- onMouseEnter={(e) => e.currentTarget.style.borderColor = '#0ff'}
- onMouseLeave={(e) => e.currentTarget.style.borderColor = '#1a1a1a'}
- >
- {preset.name}
- </button>
- ))}
- </div>
- </div>
-
- {/* Markers List */}
- <div style={{ flex: 1, overflowY: 'auto', padding: '12px', minHeight: 0 }}>
- <div style={{ color: '#00ff00', fontSize: '10px', fontWeight: 'bold', marginBottom: '8px', letterSpacing: '1px' }}>
- TRACKED TARGETS ({markers.length})
- </div>
- {markers.length === 0 ? (
- <div style={{ color: '#444', fontSize: '9px', fontStyle: 'italic', padding: '8px' }}>
- No targets marked
- </div>
- ) : (
- markers.map((marker, idx) => (
- <div
- key={idx}
- style={{
- background: '#0a0a0a',
- border: '1px solid #1a1a1a',
- padding: '8px',
- marginBottom: '6px',
- fontSize: '9px'
- }}
- >
- <div style={{ color: '#0ff', fontWeight: 'bold', marginBottom: '4px' }}>{marker.title}</div>
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: '#888' }}>Type: {marker.type}</span>
- <span style={{ color: '#666', fontSize: '8px' }}>{marker.lat.toFixed(2)}°, {marker.lng.toFixed(2)}°</span>
- </div>
- </div>
- ))
- )}
- </div>
-
- {/* Info Panel */}
- <div style={{ padding: '12px', borderTop: '1px solid #1a1a1a', background: '#0a0a0a' }}>
- <div style={{ color: '#00ff00', fontSize: '9px', fontWeight: 'bold', marginBottom: '6px' }}>SYSTEM STATUS</div>
- <div style={{ fontSize: '8px', color: '#888', lineHeight: '1.4' }}>
- <div style={{ marginBottom: '4px' }}>
- <span style={{ color: '#0ff' }}>●</span> 3D Globe: ACTIVE
- </div>
- <div style={{ marginBottom: '4px' }}>
- <span style={{ color: '#0ff' }}>●</span> Satellite imagery: ONLINE
- </div>
- <div style={{ marginBottom: '4px' }}>
- <span style={{ color: '#0ff' }}>●</span> AIS transponders: STREAMING
- </div>
- <div style={{ marginBottom: '4px' }}>
- <span style={{ color: 'rgba(138, 43, 226, 0.9)' }}>●</span> Orbital tracking: 13 SATs
- </div>
- <div style={{ marginBottom: '4px' }}>
- <span style={{ color: 'rgba(255, 200, 100, 0.95)' }}>●</span> Air traffic: MONITORED
- </div>
- <div style={{ marginBottom: '4px' }}>
- <span style={{ color: '#0ff' }}>●</span> Maritime routes: {tradeRoutes.length} corridors
- </div>
- <div style={{ marginTop: '8px', padding: '6px', background: '#000', border: '1px solid #1a1a1a', color: '#ffd700' }}>
- [WARN] CLASSIFIED: For authorized personnel only
- </div>
- </div>
- </div>
- </div>
- </div>
-
- {/* Footer */}
- <TabFooter
- tabName="MARITIME INTELLIGENCE"
- leftInfo={[
- { label: 'AIS Feed: ACTIVE', color: '#0ff' },
- { label: 'Satellite Link: NOMINAL', color: '#0ff' },
- { label: 'Data Latency: 2.3ms', color: '#0ff' },
- ]}
- statusInfo={
- <>
- <span style={{ color: '#888' }}>Powered by Globe.GL 3D Visualization</span>
- <span style={{ color: '#888', marginLeft: '8px' }}>|</span>
- <span style={{ color: '#ffd700', marginLeft: '8px' }}>CLEARANCE: TOP SECRET // SCI</span>
- </>
- }
- backgroundColor="#0a0a0a"
- borderColor="#00ff00"
- />
- </div>
- );
-}
\ No newline at end of file
+export { default } from './maritime';
+export * from './maritime';
diff --git a/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx b/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx
index cfcc049df..9c9d72453 100644
--- a/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/NodeEditorTab.tsx
@@ -1,2907 +1,11 @@
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-import React, { useState, useCallback, useMemo, useEffect, useRef } from 'react';
-import { saveSetting, getSetting } from '@/services/core/sqliteService';
-import ReactFlow, {
- Node,
- Edge,
- addEdge,
- Background,
- Controls,
- MiniMap,
- Connection,
- useNodesState,
- useEdgesState,
- MarkerType,
- NodeTypes,
- Handle,
- Position,
- ReactFlowProvider,
- useReactFlow,
-} from 'reactflow';
-import 'reactflow/dist/style.css';
-import {
- Plus,
- Play,
- Save,
- Download,
- Upload,
- Trash2,
- Database,
- Zap,
- TrendingUp,
- BarChart3,
- Brain,
- FileText,
- Edit3,
- X,
- Monitor,
- Rocket,
- ChevronLeft,
- ChevronRight,
- Search,
- Settings2,
- Workflow,
- Filter,
- GitBranch,
- Code,
- Bell,
- Shield,
- BarChart2,
- Activity,
- RefreshCw,
- AlertCircle,
-} from 'lucide-react';
-import MCPToolNode from './node-editor/MCPToolNode';
-import { generateMCPNodeConfigs, MCPNodeConfig } from './node-editor/mcpNodeConfigs';
-import PythonAgentNode from './node-editor/PythonAgentNode';
-import ResultsDisplayNode from './node-editor/ResultsDisplayNode';
-import AgentMediatorNode from './node-editor/AgentMediatorNode';
-import DataSourceNode from './node-editor/DataSourceNode';
-import TechnicalIndicatorNode from './node-editor/TechnicalIndicatorNode';
-import BacktestNode from './node-editor/BacktestNode';
-import OptimizationNode from './node-editor/OptimizationNode';
-import { SystemNode } from './node-editor/SystemNode';
-import WorkflowManager from './node-editor/WorkflowManager';
-import ResultsModal from './node-editor/ResultsModal';
-import { NodeParameterInput } from './node-editor/NodeParameterInput';
-import type { INodeProperties, NodeParameterValue } from '@/services/nodeSystem';
-import { pythonAgentService, AgentMetadata } from '@/services/chat/pythonAgentService';
-import { workflowExecutor } from './node-editor/WorkflowExecutor';
-import { Workflow as WorkflowType, workflowService } from '@/services/core/workflowService';
-import { nodeExecutionManager } from '@/services/core/nodeExecutionManager';
-import { TabFooter } from '@/components/common/TabFooter';
-import { useTranslation } from 'react-i18next';
-import { NodeRegistry, INodeTypeDescription } from '@/services/nodeSystem';
-
-// Custom Node Component
-const CustomNode = ({ data, id, selected }: any) => {
- const [isEditing, setIsEditing] = useState(false);
- const [label, setLabel] = useState(data.label);
-
- const handleLabelSave = () => {
- data.onLabelChange(id, label);
- setIsEditing(false);
- };
-
- const getIcon = () => {
- switch (data.nodeType) {
- case 'data-source':
- return <Database size={16} />;
- case 'transformation':
- return <Zap size={16} />;
- case 'analysis':
- return <TrendingUp size={16} />;
- case 'visualization':
- return <BarChart3 size={16} />;
- case 'agent':
- return <Brain size={16} />;
- case 'output':
- return <FileText size={16} />;
- default:
- return <Database size={16} />;
- }
- };
-
- return (
- <div
- style={{
- background: selected ? '#2d2d2d' : '#1a1a1a',
- border: `2px solid ${selected ? data.color : `${data.color}80`}`,
- borderRadius: '6px',
- minWidth: '180px',
- boxShadow: selected
- ? `0 0 20px ${data.color}60, 0 4px 12px rgba(0,0,0,0.5)`
- : `0 2px 8px rgba(0,0,0,0.3)`,
- transition: 'all 0.2s',
- }}
- >
- {/* Input Handle */}
- {data.hasInput && (
- <Handle
- type="target"
- position={Position.Left}
- style={{
- background: data.color,
- width: 12,
- height: 12,
- border: '2px solid #1a1a1a',
- boxShadow: `0 0 8px ${data.color}`,
- }}
- />
- )}
-
- {/* Node Header */}
- <div
- style={{
- background: `${data.color}20`,
- borderBottom: `1px solid ${data.color}40`,
- padding: '8px 12px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- gap: '8px',
- color: data.color,
- borderTopLeftRadius: '4px',
- borderTopRightRadius: '4px',
- }}
- >
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- {getIcon()}
- {isEditing ? (
- <input
- type="text"
- value={label}
- onChange={(e) => setLabel(e.target.value)}
- onBlur={handleLabelSave}
- onKeyDown={(e) => {
- if (e.key === 'Enter') handleLabelSave();
- if (e.key === 'Escape') {
- setLabel(data.label);
- setIsEditing(false);
- }
- }}
- autoFocus
- style={{
- background: 'colors.panel',
- border: `1px solid ${data.color}`,
- color: data.color,
- fontSize: '11px',
- padding: '2px 6px',
- borderRadius: '3px',
- outline: 'none',
- fontWeight: 'bold',
- width: '120px',
- }}
- />
- ) : (
- <span
- style={{
- fontSize: '11px',
- fontWeight: 'bold',
- letterSpacing: '0.3px',
- }}
- >
- {data.label.toUpperCase()}
- </span>
- )}
- </div>
- {!isEditing && (
- <button
- onClick={() => setIsEditing(true)}
- style={{
- background: 'transparent',
- border: 'none',
- color: data.color,
- cursor: 'pointer',
- padding: '2px',
- display: 'flex',
- alignItems: 'center',
- }}
- title="Edit label"
- >
- <Edit3 size={12} />
- </button>
- )}
- </div>
-
- {/* Node Body */}
- <div
- style={{
- padding: '12px',
- display: 'flex',
- flexDirection: 'column',
- gap: '4px',
- color: '#a3a3a3',
- fontSize: '10px',
- }}
- >
- <div>Type: {data.nodeType}</div>
- <div>Status: {data.status || 'Ready'}</div>
- <div style={{ color: '#737373' }}>ID: {id.substring(0, 8)}</div>
- </div>
-
- {/* Output Handle */}
- {data.hasOutput && (
- <Handle
- type="source"
- position={Position.Right}
- style={{
- background: data.color,
- width: 12,
- height: 12,
- border: '2px solid #1a1a1a',
- boxShadow: `0 0 8px ${data.color}`,
- }}
- />
- )}
- </div>
- );
-};
-
-// Built-in UI node configs (these have custom React components)
-const BUILTIN_NODE_CONFIGS = [
- {
- type: 'data-source',
- label: 'Data Source',
- color: '#3b82f6',
- category: 'Input',
- hasInput: false,
- hasOutput: true,
- description: 'Connect to databases and fetch data',
- },
- {
- type: 'technical-indicator',
- label: 'Technical Indicators',
- color: '#10b981',
- category: 'Processing',
- hasInput: true,
- hasOutput: true,
- description: 'Calculate technical indicators on market data',
- },
- {
- type: 'agent-mediator',
- label: 'Agent Mediator',
- color: '#8b5cf6',
- category: 'AI',
- hasInput: true,
- hasOutput: true,
- description: 'AI-powered data analysis and decision making',
- },
- {
- type: 'results-display',
- label: 'Results Display',
- color: '#f59e0b',
- category: 'Output',
- hasInput: true,
- hasOutput: false,
- description: 'Display workflow results with formatting',
- },
- {
- type: 'backtest',
- label: 'Backtest',
- color: '#06b6d4',
- category: 'Analytics',
- hasInput: true,
- hasOutput: true,
- description: 'Run backtests on trading strategies',
- },
- {
- type: 'optimization',
- label: 'Optimization',
- color: '#a855f7',
- category: 'Analytics',
- hasInput: true,
- hasOutput: true,
- description: 'Optimize strategy parameters using grid/genetic algorithms',
- },
-];
-
-// Category icons and colors for the palette
-const CATEGORY_CONFIG: Record<string, { icon: React.ReactNode; color: string }> = {
- 'Core': { icon: <Workflow size={14} />, color: '#6b7280' },
- 'Input': { icon: <Database size={14} />, color: '#3b82f6' },
- 'Processing': { icon: <Zap size={14} />, color: '#10b981' },
- 'Output': { icon: <Monitor size={14} />, color: '#f59e0b' },
- 'AI': { icon: <Brain size={14} />, color: '#8b5cf6' },
- 'Analytics': { icon: <BarChart2 size={14} />, color: '#06b6d4' },
- 'Market Data': { icon: <Activity size={14} />, color: '#22c55e' },
- 'Control Flow': { icon: <GitBranch size={14} />, color: '#eab308' },
- 'Transform': { icon: <Filter size={14} />, color: '#ec4899' },
- 'Safety': { icon: <Shield size={14} />, color: '#ef4444' },
- 'Notifications': { icon: <Bell size={14} />, color: '#f97316' },
- 'Triggers': { icon: <Zap size={14} />, color: '#a855f7' },
- 'Trading': { icon: <TrendingUp size={14} />, color: '#14b8a6' },
- 'agents': { icon: <Brain size={14} />, color: '#8b5cf6' },
- 'marketData': { icon: <Activity size={14} />, color: '#22c55e' },
- 'trading': { icon: <TrendingUp size={14} />, color: '#14b8a6' },
- 'triggers': { icon: <Zap size={14} />, color: '#a855f7' },
- 'controlFlow': { icon: <GitBranch size={14} />, color: '#eab308' },
- 'transform': { icon: <Filter size={14} />, color: '#ec4899' },
- 'safety': { icon: <Shield size={14} />, color: '#ef4444' },
- 'notifications': { icon: <Bell size={14} />, color: '#f97316' },
- 'analytics': { icon: <BarChart2 size={14} />, color: '#06b6d4' },
-};
-
-// Integrated Node Palette Component
-interface NodePaletteProps {
- onNodeAdd: (nodeType: string, nodeData: any) => void;
- isCollapsed: boolean;
- onToggleCollapse: () => void;
- mcpNodeConfigs: MCPNodeConfig[];
- agentConfigs: AgentMetadata[];
-}
-
-const IntegratedNodePalette: React.FC<NodePaletteProps> = ({
- onNodeAdd,
- isCollapsed,
- onToggleCollapse,
- mcpNodeConfigs,
- agentConfigs,
-}) => {
- const [searchQuery, setSearchQuery] = useState('');
- const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set(['Input', 'Processing', 'Output']));
-
- // Get all registered nodes from NodeRegistry
- const registryNodes = useMemo(() => {
- try {
- return NodeRegistry.getAllNodes();
- } catch (e) {
- console.warn('[NodePalette] NodeRegistry not initialized yet');
- return [];
- }
- }, []);
-
- // Combine builtin nodes with registry nodes
- const allNodes = useMemo(() => {
- const nodes: Array<{
- id: string;
- type: string;
- label: string;
- category: string;
- color: string;
- description: string;
- source: 'builtin' | 'registry' | 'mcp' | 'agent';
- data?: any;
- }> = [];
-
- // Add builtin UI nodes
- BUILTIN_NODE_CONFIGS.forEach(config => {
- nodes.push({
- id: config.type,
- type: config.type,
- label: config.label,
- category: config.category,
- color: config.color,
- description: config.description,
- source: 'builtin',
- data: config,
- });
- });
-
- // Add registry nodes
- registryNodes.forEach((node: INodeTypeDescription) => {
- const category = node.group?.[0] || 'Core';
- const categoryConfig = CATEGORY_CONFIG[category] || CATEGORY_CONFIG['Core'];
- nodes.push({
- id: node.name,
- type: 'registry-node',
- label: node.displayName,
- category,
- color: node.defaults?.color || categoryConfig.color,
- description: node.description || '',
- source: 'registry',
- data: node,
- });
- });
-
- // Add MCP tool nodes
- mcpNodeConfigs.forEach(config => {
- nodes.push({
- id: config.id,
- type: 'mcp-tool',
- label: config.label,
- category: 'MCP Tools',
- color: '#ea580c',
- description: `MCP: ${config.serverId}`,
- source: 'mcp',
- data: config,
- });
- });
-
- // Add Python agent nodes
- agentConfigs.forEach(agent => {
- nodes.push({
- id: agent.id,
- type: 'python-agent',
- label: agent.name,
- category: 'Python Agents',
- color: agent.color || '#22c55e',
- description: agent.description,
- source: 'agent',
- data: agent,
- });
- });
-
- return nodes;
- }, [registryNodes, mcpNodeConfigs, agentConfigs]);
-
- // Group nodes by category
- const nodesByCategory = useMemo(() => {
- const grouped = new Map<string, typeof allNodes>();
-
- allNodes.forEach(node => {
- if (!grouped.has(node.category)) {
- grouped.set(node.category, []);
- }
- grouped.get(node.category)!.push(node);
- });
-
- // Sort each category alphabetically
- grouped.forEach((nodes, _) => {
- nodes.sort((a, b) => a.label.localeCompare(b.label));
- });
-
- return grouped;
- }, [allNodes]);
-
- // Filter by search
- const filteredCategories = useMemo(() => {
- if (!searchQuery.trim()) return nodesByCategory;
-
- const query = searchQuery.toLowerCase();
- const filtered = new Map<string, typeof allNodes>();
-
- nodesByCategory.forEach((nodes, category) => {
- const matching = nodes.filter(
- n => n.label.toLowerCase().includes(query) ||
- n.description.toLowerCase().includes(query) ||
- n.id.toLowerCase().includes(query)
- );
- if (matching.length > 0) {
- filtered.set(category, matching);
- }
- });
-
- return filtered;
- }, [nodesByCategory, searchQuery]);
-
- const toggleCategory = (category: string) => {
- const newExpanded = new Set(expandedCategories);
- if (newExpanded.has(category)) {
- newExpanded.delete(category);
- } else {
- newExpanded.add(category);
- }
- setExpandedCategories(newExpanded);
- };
-
- if (isCollapsed) {
- return (
- <div style={{
- width: '40px',
- backgroundColor: '#0a0a0a',
- borderRight: '1px solid #2d2d2d',
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- paddingTop: '8px',
- }}>
- <button
- onClick={onToggleCollapse}
- style={{
- backgroundColor: 'transparent',
- border: 'none',
- color: '#a3a3a3',
- cursor: 'pointer',
- padding: '8px',
- }}
- title="Expand palette"
- >
- <ChevronRight size={16} />
- </button>
- </div>
- );
- }
-
- return (
- <div style={{
- width: '280px',
- backgroundColor: '#0a0a0a',
- borderRight: '1px solid #2d2d2d',
- display: 'flex',
- flexDirection: 'column',
- height: '100%',
- }}>
- {/* Palette Header */}
- <div style={{
- padding: '12px',
- borderBottom: '1px solid #2d2d2d',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- }}>
- <div style={{
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- color: '#ea580c',
- fontSize: '12px',
- fontWeight: 'bold',
- }}>
- <Database size={14} />
- NODE PALETTE
- </div>
- <button
- onClick={onToggleCollapse}
- style={{
- backgroundColor: 'transparent',
- border: 'none',
- color: '#6b7280',
- cursor: 'pointer',
- padding: '4px',
- }}
- title="Collapse palette"
- >
- <ChevronLeft size={14} />
- </button>
- </div>
-
- {/* Search */}
- <div style={{ padding: '8px 12px', borderBottom: '1px solid #2d2d2d' }}>
- <div style={{ position: 'relative' }}>
- <Search size={14} style={{
- position: 'absolute',
- left: '10px',
- top: '50%',
- transform: 'translateY(-50%)',
- color: '#6b7280',
- }} />
- <input
- type="text"
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- placeholder="Search nodes..."
- style={{
- width: '100%',
- backgroundColor: '#1a1a1a',
- border: '1px solid #2d2d2d',
- borderRadius: '4px',
- padding: '8px 8px 8px 32px',
- color: '#fff',
- fontSize: '11px',
- outline: 'none',
- }}
- />
- </div>
- <div style={{ color: '#6b7280', fontSize: '10px', marginTop: '6px' }}>
- {allNodes.length} nodes available
- </div>
- </div>
-
- {/* Node Categories */}
- <div style={{ flex: 1, overflow: 'auto' }}>
- {Array.from(filteredCategories.entries()).map(([category, categoryNodes]) => {
- const catConfig = CATEGORY_CONFIG[category] || { icon: <Workflow size={14} />, color: '#6b7280' };
- const isExpanded = expandedCategories.has(category);
-
- return (
- <div key={category} style={{ borderBottom: '1px solid #1a1a1a' }}>
- {/* Category Header */}
- <button
- onClick={() => toggleCategory(category)}
- style={{
- width: '100%',
- padding: '10px 12px',
- backgroundColor: 'transparent',
- border: 'none',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- cursor: 'pointer',
- color: '#d4d4d4',
- }}
- >
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <span style={{ color: catConfig.color }}>{catConfig.icon}</span>
- <span style={{ fontSize: '11px', fontWeight: 'bold' }}>{category}</span>
- <span style={{ fontSize: '10px', color: '#6b7280' }}>({categoryNodes.length})</span>
- </div>
- {isExpanded ? <ChevronRight size={12} style={{ transform: 'rotate(90deg)' }} /> : <ChevronRight size={12} />}
- </button>
-
- {/* Category Nodes */}
- {isExpanded && (
- <div style={{ padding: '4px 8px 8px' }}>
- {categoryNodes.map(node => (
- <div
- key={node.id}
- onClick={() => onNodeAdd(node.type, node)}
- draggable
- onDragStart={(e) => {
- e.dataTransfer.setData('application/reactflow', JSON.stringify(node));
- e.dataTransfer.effectAllowed = 'move';
- }}
- style={{
- backgroundColor: '#1a1a1a',
- border: `1px solid ${node.color}30`,
- borderRadius: '4px',
- padding: '8px 10px',
- marginBottom: '4px',
- cursor: 'pointer',
- transition: 'all 0.15s',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = `${node.color}15`;
- e.currentTarget.style.borderColor = `${node.color}60`;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = '#1a1a1a';
- e.currentTarget.style.borderColor = `${node.color}30`;
- }}
- >
- <div style={{
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- }}>
- <div style={{
- width: '24px',
- height: '24px',
- borderRadius: '4px',
- backgroundColor: `${node.color}20`,
- border: `1px solid ${node.color}40`,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- color: node.color,
- fontSize: '10px',
- fontWeight: 'bold',
- }}>
- {node.label[0]}
- </div>
- <div style={{ flex: 1, minWidth: 0 }}>
- <div style={{
- color: node.color,
- fontSize: '11px',
- fontWeight: 'bold',
- whiteSpace: 'nowrap',
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- }}>
- {node.label}
- </div>
- {node.description && (
- <div style={{
- color: '#6b7280',
- fontSize: '9px',
- whiteSpace: 'nowrap',
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- }}>
- {node.description.substring(0, 40)}{node.description.length > 40 ? '...' : ''}
- </div>
- )}
- </div>
- </div>
- </div>
- ))}
- </div>
- )}
- </div>
- );
- })}
-
- {filteredCategories.size === 0 && (
- <div style={{
- padding: '24px',
- textAlign: 'center',
- color: '#6b7280',
- }}>
- <Search size={24} style={{ margin: '0 auto 8px', opacity: 0.5 }} />
- <div style={{ fontSize: '11px' }}>No nodes found</div>
- </div>
- )}
- </div>
-
- {/* Palette Footer */}
- <div style={{
- padding: '8px 12px',
- borderTop: '1px solid #2d2d2d',
- backgroundColor: '#0a0a0a',
- }}>
- <div style={{ color: '#6b7280', fontSize: '9px', textAlign: 'center' }}>
- Drag nodes to canvas or click to add
- </div>
- </div>
- </div>
- );
-};
-
-export default function NodeEditorTab() {
- const { t } = useTranslation('nodeEditor');
- const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
- const [mcpNodeConfigs, setMcpNodeConfigs] = useState<MCPNodeConfig[]>([]);
- const [agentConfigs, setAgentConfigs] = useState<AgentMetadata[]>([]);
-
- // Load saved workflow from storage or start with blank slate
- const loadSavedWorkflow = useCallback(async () => {
- try {
- const saved = await getSetting('nodeEditorWorkflow');
- if (saved) {
- const workflow = JSON.parse(saved);
- return workflow;
- }
- } catch (error) {
- console.error('[NodeEditor] Failed to load saved workflow:', error);
- }
- return { nodes: [], edges: [] };
- }, []);
-
- const [nodes, setNodes, onNodesChange] = useNodesState([]);
- const [edges, setEdges, onEdgesChange] = useEdgesState([]);
-
- // Load workflow on mount
- useEffect(() => {
- const initWorkflow = async () => {
- const workflow = await loadSavedWorkflow();
- setNodes(workflow.nodes);
- setEdges(workflow.edges);
- };
- initWorkflow();
- }, [loadSavedWorkflow]);
-
- // Auto-save workflow to storage whenever nodes or edges change
- useEffect(() => {
- const saveWorkflow = async () => {
- try {
- const workflow = { nodes, edges };
- await saveSetting('nodeEditorWorkflow', JSON.stringify(workflow), 'node_editor');
- } catch (error) {
- console.error('[NodeEditor] Failed to save workflow:', error);
- }
- };
-
- // Debounce saves to avoid too frequent writes
- const timeoutId = setTimeout(saveWorkflow, 500);
- return () => clearTimeout(timeoutId);
- }, [nodes, edges]);
-
- // Load MCP node configurations and Python agents on mount
- useEffect(() => {
- const loadMCPNodes = async () => {
- try {
- const configs = await generateMCPNodeConfigs();
- setMcpNodeConfigs(configs);
- } catch (error) {
- console.error('[NodeEditor] Failed to load MCP configs:', error);
- }
- };
-
- const loadAgents = async () => {
- try {
- const agents = await pythonAgentService.getAvailableAgents();
- setAgentConfigs(agents);
- } catch (error) {
- console.error('[NodeEditor] Failed to load agents:', error);
- }
- };
-
- loadMCPNodes();
- loadAgents();
- }, []);
-
- const [selectedNodes, setSelectedNodes] = useState<string[]>([]);
- const [showNodeMenu, setShowNodeMenu] = useState(false);
- const [activeView, setActiveView] = useState<'editor' | 'workflows'>('editor');
- const [isPaletteCollapsed, setIsPaletteCollapsed] = useState(false);
- const [showConfigPanel, setShowConfigPanel] = useState(false);
- const [selectedNodeForConfig, setSelectedNodeForConfig] = useState<Node | null>(null);
- const reactFlowWrapper = useRef<HTMLDivElement>(null);
- const [showDeployDialog, setShowDeployDialog] = useState(false);
- const [workflowName, setWorkflowName] = useState('');
- const [workflowDescription, setWorkflowDescription] = useState('');
- const [editingDraftId, setEditingDraftId] = useState<string | null>(null);
- const [isExecuting, setIsExecuting] = useState(false);
- const [workflowMode, setWorkflowMode] = useState<'new' | 'draft' | 'deployed'>('new');
- const [currentWorkflowId, setCurrentWorkflowId] = useState<string | null>(null);
- const [showResultsModal, setShowResultsModal] = useState(false);
- const [resultsData, setResultsData] = useState<any>(null);
- const [resultsWorkflowName, setResultsWorkflowName] = useState<string>('');
-
- const nodeTypes: NodeTypes = useMemo(() => ({
- custom: CustomNode,
- 'mcp-tool': MCPToolNode,
- 'python-agent': PythonAgentNode,
- 'results-display': ResultsDisplayNode,
- 'agent-mediator': AgentMediatorNode,
- 'data-source': DataSourceNode,
- 'technical-indicator': TechnicalIndicatorNode,
- 'backtest': BacktestNode,
- 'optimization': OptimizationNode,
- 'system': SystemNode,
- }), []);
-
- // Handle label change
- function handleLabelChange(nodeId: string, newLabel: string) {
- setNodes((nds) =>
- nds.map((node) => {
- if (node.id === nodeId) {
- return {
- ...node,
- data: {
- ...node.data,
- label: newLabel,
- },
- };
- }
- return node;
- })
- );
- }
-
- // Handle connection
- const onConnect = useCallback(
- (params: Connection) => {
- const newEdge = {
- ...params,
- animated: true,
- style: { stroke: '#ea580c', strokeWidth: 2 },
- markerEnd: { type: MarkerType.ArrowClosed, color: '#ea580c' },
- };
- setEdges((eds) => addEdge(newEdge, eds));
- },
- [setEdges]
- );
-
- // Handle node from palette (click or drag)
- const handlePaletteNodeAdd = useCallback((nodeType: string, nodeData: any) => {
-
- // Determine the actual node type for ReactFlow
- let reactFlowType = 'custom';
- if (nodeData.source === 'builtin') {
- reactFlowType = nodeData.data?.type || nodeType;
- } else if (nodeData.source === 'registry') {
- reactFlowType = 'custom'; // Registry nodes use custom component for now
- } else if (nodeData.source === 'mcp') {
- reactFlowType = 'mcp-tool';
- } else if (nodeData.source === 'agent') {
- reactFlowType = 'python-agent';
- }
-
- // Build the node based on type
- if (nodeData.source === 'builtin') {
- // Use existing addNode logic for builtin types
- addNode(nodeData.data);
- } else if (nodeData.source === 'mcp') {
- addNode(nodeData.data);
- } else if (nodeData.source === 'agent') {
- addNode({ ...nodeData.data, type: 'python-agent' });
- } else if (nodeData.source === 'registry') {
- // Create a new node from registry node description
- const registryNode = nodeData.data as INodeTypeDescription;
- const newNode: Node = {
- id: `node_${Date.now()}`,
- type: 'custom',
- position: { x: Math.random() * 400 + 100, y: Math.random() * 300 + 100 },
- data: {
- label: registryNode.displayName,
- nodeTypeName: registryNode.name,
- color: nodeData.color || '#6b7280',
- hasInput: (registryNode.inputs?.length || 0) > 0 || registryNode.name !== 'manualTrigger',
- hasOutput: (registryNode.outputs?.length || 0) > 0,
- status: 'idle',
- parameters: {},
- registryData: registryNode,
- onLabelChange: handleLabelChange,
- },
- };
- setNodes((nds) => [...nds, newNode]);
- }
-
- setShowNodeMenu(false);
- }, [setNodes]);
-
- // Handle drop from palette
- const onDrop = useCallback(
- (event: React.DragEvent) => {
- event.preventDefault();
-
- const data = event.dataTransfer.getData('application/reactflow');
- if (!data) return;
-
- const nodeData = JSON.parse(data);
-
- // Get position relative to the canvas
- const reactFlowBounds = reactFlowWrapper.current?.getBoundingClientRect();
- if (!reactFlowBounds) return;
-
- const position = {
- x: event.clientX - reactFlowBounds.left - 150,
- y: event.clientY - reactFlowBounds.top - 25,
- };
-
- // Add node at drop position
- if (nodeData.source === 'registry') {
- const registryNode = nodeData.data as INodeTypeDescription;
- const newNode: Node = {
- id: `node_${Date.now()}`,
- type: 'custom',
- position,
- data: {
- label: registryNode.displayName,
- nodeTypeName: registryNode.name,
- color: nodeData.color || '#6b7280',
- hasInput: (registryNode.inputs?.length || 0) > 0 || registryNode.name !== 'manualTrigger',
- hasOutput: (registryNode.outputs?.length || 0) > 0,
- status: 'idle',
- parameters: {},
- registryData: registryNode,
- onLabelChange: handleLabelChange,
- },
- };
- setNodes((nds) => [...nds, newNode]);
- } else {
- // Use existing logic for other node types
- handlePaletteNodeAdd(nodeData.type, nodeData);
- }
- },
- [setNodes, handlePaletteNodeAdd]
- );
-
- const onDragOver = useCallback((event: React.DragEvent) => {
- event.preventDefault();
- event.dataTransfer.dropEffect = 'move';
- }, []);
-
- // Add new node (handles regular nodes, MCP tool nodes, Python agent nodes, data source, technical indicators, and agent mediator)
- const addNode = (config: any) => {
- const isMCPNode = config.type === 'mcp-tool';
- const isPythonAgent = config.type === 'python-agent';
- const isResultsDisplay = config.type === 'results-display';
- const isAgentMediator = config.type === 'agent-mediator';
- const isDataSource = config.type === 'data-source';
- const isTechnicalIndicator = config.type === 'technical-indicator';
-
- const newNode: Node = {
- id: `node_${Date.now()}`,
- type: isPythonAgent ? 'python-agent' : (isMCPNode ? 'mcp-tool' : (isResultsDisplay ? 'results-display' : (isAgentMediator ? 'agent-mediator' : (isDataSource ? 'data-source' : (isTechnicalIndicator ? 'technical-indicator' : 'custom'))))),
- position: { x: Math.random() * 400 + 100, y: Math.random() * 300 + 100 },
- data: isPythonAgent ? {
- agentType: config.id, // Use 'id' field which contains agent_type like 'warren_buffett'
- agentCategory: config.category,
- label: config.name,
- icon: config.icon,
- color: config.color,
- parameters: config.parameters.reduce((acc: any, param: any) => {
- if (param.default_value !== null && param.default_value !== undefined) {
- acc[param.name] = param.default_value;
- }
- return acc;
- }, {}),
- selectedLLM: 'active', // Default to active provider
- status: 'idle',
- onExecute: async (nodeId: string) => {
- // Execute just this node
- try {
- setNodes((nds) =>
- nds.map((n) => n.id === nodeId ? { ...n, data: { ...n.data, status: 'running' } } : n)
- );
-
- const result = await pythonAgentService.executeAgent(
- config.id,
- config.parameters.reduce((acc: any, param: any) => {
- if (param.default_value !== null && param.default_value !== undefined) {
- acc[param.name] = param.default_value;
- }
- return acc;
- }, {}),
- {}
- );
-
- setNodes((nds) =>
- nds.map((n) =>
- n.id === nodeId
- ? {
- ...n,
- data: {
- ...n.data,
- status: result.success ? 'completed' : 'error',
- result: result.success ? result.data : undefined,
- error: result.success ? undefined : result.error,
- },
- }
- : n
- )
- );
- } catch (error: any) {
- setNodes((nds) =>
- nds.map((n) =>
- n.id === nodeId ? { ...n, data: { ...n.data, status: 'error', error: error.message } } : n
- )
- );
- }
- },
- onParameterChange: (_params: Record<string, any>) => {
- // Parameters updated
- },
- onLLMChange: (provider: string) => {
- setNodes((nds) =>
- nds.map((n) =>
- n.id === newNode.id
- ? {
- ...n,
- data: {
- ...n.data,
- selectedLLM: provider,
- },
- }
- : n
- )
- );
- },
- } : (isMCPNode ? {
- serverId: config.serverId,
- toolName: config.toolName,
- label: config.label,
- parameters: {},
- onParameterChange: (_params: Record<string, any>) => {
- // Parameters updated
- },
- onExecute: (_result: any) => {
- // Tool executed
- },
- } : (isResultsDisplay ? {
- label: config.label,
- color: config.color,
- inputData: undefined,
- } : (isAgentMediator ? {
- label: config.label,
- selectedProvider: undefined, // Will use active provider by default
- customPrompt: undefined,
- status: 'idle',
- result: undefined,
- error: undefined,
- inputData: undefined,
- onExecute: (_nodeId: string) => {
- // Workflow execution will handle this
- },
- onConfigChange: (newConfig: any) => {
- setNodes((nds) =>
- nds.map((n) =>
- n.id === newNode.id
- ? {
- ...n,
- data: {
- ...n.data,
- selectedProvider: newConfig.selectedProvider,
- customPrompt: newConfig.customPrompt,
- },
- }
- : n
- )
- );
- },
- } : (isDataSource ? {
- label: config.label,
- selectedConnectionId: undefined,
- query: '',
- status: 'idle',
- result: undefined,
- error: undefined,
- onConnectionChange: (connectionId: string) => {
- setNodes((nds) =>
- nds.map((n) =>
- n.id === newNode.id
- ? {
- ...n,
- data: {
- ...n.data,
- selectedConnectionId: connectionId,
- },
- }
- : n
- )
- );
- },
- onQueryChange: (query: string) => {
- setNodes((nds) =>
- nds.map((n) =>
- n.id === newNode.id
- ? {
- ...n,
- data: {
- ...n.data,
- query: query,
- },
- }
- : n
- )
- );
- },
- onExecute: async () => {
- // Will be handled by workflow execution
- },
- } : (isTechnicalIndicator ? {
- label: config.label,
- dataSource: 'yfinance',
- symbol: 'AAPL',
- period: '1y',
- csvPath: '',
- jsonData: '',
- categories: ['momentum', 'volume', 'volatility', 'trend', 'others'],
- status: 'idle',
- result: undefined,
- error: undefined,
- onExecute: (_nodeId: string) => {
- // Workflow execution will handle this
- },
- onParameterChange: (params: Record<string, any>) => {
- setNodes((nds) =>
- nds.map((n) =>
- n.id === newNode.id
- ? {
- ...n,
- data: {
- ...n.data,
- ...params,
- },
- }
- : n
- )
- );
- },
- } : {
- label: config.label,
- nodeType: config.type,
- color: config.color,
- hasInput: config.hasInput,
- hasOutput: config.hasOutput,
- onLabelChange: handleLabelChange,
- }))))),
- };
- setNodes((nds) => [...nds, newNode]);
- setShowNodeMenu(false);
- };
-
- // Delete selected nodes
- const deleteSelectedNodes = useCallback(() => {
- if (selectedNodes.length > 0) {
- setNodes((nds) => nds.filter((node) => !selectedNodes.includes(node.id)));
- setEdges((eds) =>
- eds.filter(
- (edge) =>
- !selectedNodes.includes(edge.source) &&
- !selectedNodes.includes(edge.target)
- )
- );
- setSelectedNodes([]);
- }
- }, [selectedNodes, setNodes, setEdges]);
-
- // Handle node selection
- const onSelectionChange = useCallback((params: any) => {
- setSelectedNodes(params.nodes.map((node: Node) => node.id));
- }, []);
-
- // Delete selected edges
- const deleteSelectedEdges = useCallback(() => {
- setEdges((eds) => eds.filter((edge) => !edge.selected));
- }, [setEdges]);
-
- // Handle keyboard shortcuts
- const handleKeyDown = useCallback(
- (event: KeyboardEvent) => {
- if (event.key === 'Delete' || event.key === 'Backspace') {
- deleteSelectedNodes();
- deleteSelectedEdges();
- }
- },
- [deleteSelectedNodes, deleteSelectedEdges]
- );
-
- React.useEffect(() => {
- window.addEventListener('keydown', handleKeyDown);
- return () => {
- window.removeEventListener('keydown', handleKeyDown);
- };
- }, [handleKeyDown]);
-
- // Save workflow manually
- const saveWorkflow = useCallback(async () => {
- try {
- const workflow = { nodes, edges };
- await saveSetting('nodeEditorWorkflow', JSON.stringify(workflow), 'node_editor');
- } catch (error) {
- console.error('[NodeEditor] Failed to save workflow:', error);
- }
- }, [nodes, edges]);
-
- // Export workflow to JSON file
- const exportWorkflow = useCallback(() => {
- const workflow = {
- nodes: nodes,
- edges: edges,
- };
- const dataStr = JSON.stringify(workflow, null, 2);
- const dataUri = `data:application/json;charset=utf-8,${encodeURIComponent(dataStr)}`;
- const exportFileDefaultName = `workflow_${Date.now()}.json`;
-
- const linkElement = document.createElement('a');
- linkElement.setAttribute('href', dataUri);
- linkElement.setAttribute('download', exportFileDefaultName);
- linkElement.click();
- }, [nodes, edges]);
-
- // Import workflow from JSON file
- const importWorkflow = useCallback(() => {
- const input = document.createElement('input');
- input.type = 'file';
- input.accept = '.json';
- input.onchange = (e: any) => {
- const file = e.target.files[0];
- if (file) {
- const reader = new FileReader();
- reader.onload = (event: any) => {
- try {
- const workflow = JSON.parse(event.target.result);
- setNodes(workflow.nodes || []);
- setEdges(workflow.edges || []);
- } catch (error) {
- console.error('[NodeEditor] Failed to import workflow:', error);
- }
- };
- reader.readAsText(file);
- }
- };
- input.click();
- }, [setNodes, setEdges]);
-
- // Clear workflow (start fresh)
- const clearWorkflow = useCallback(async () => {
- setNodes([]);
- setEdges([]);
- await saveSetting('nodeEditorWorkflow', '', 'node_editor');
- setWorkflowMode('new');
- setCurrentWorkflowId(null);
- setEditingDraftId(null);
- setWorkflowName('');
- setWorkflowDescription('');
- }, [setNodes, setEdges]);
-
- // Deploy workflow
- const deployWorkflow = useCallback(async () => {
- if (!workflowName.trim()) {
- alert('Please enter a workflow name');
- return;
- }
-
- if (isExecuting) {
- alert('A workflow is already executing. Please wait for it to complete.');
- return;
- }
-
- // Store values before closing dialog
- const name = workflowName;
- const description = workflowDescription;
- const currentNodes = nodes;
- const currentEdges = edges;
-
- // Close dialog IMMEDIATELY - don't wait for execution
- setShowDeployDialog(false);
- setWorkflowName('');
- setWorkflowDescription('');
- setEditingDraftId(null);
- setActiveView('editor'); // Stay in editor to see execution progress
-
- // Execute in background
- setIsExecuting(true);
-
- // Use setTimeout to ensure dialog closes before heavy execution starts
- setTimeout(async () => {
- try {
- const result = await workflowExecutor.executeAndSave(
- currentNodes,
- currentEdges,
- {
- name: name,
- description: description,
- saveAsDraft: false
- },
- (nodeId: string, status: string, result?: any) => {
- setNodes((nds) =>
- nds.map((node) => {
- if (node.id === nodeId) {
- if (node.type === 'results-display') {
- return {
- ...node,
- data: {
- ...node.data,
- inputData: status === 'completed' ? result : undefined,
- status,
- },
- };
- }
- return {
- ...node,
- data: {
- ...node.data,
- status,
- result: status === 'completed' ? result : undefined,
- error: status === 'error' ? result : undefined,
- },
- };
- }
- return node;
- })
- );
- }
- );
-
- if (result.success) {
- // Clear the canvas after successful deployment
- setNodes([]);
- setEdges([]);
- await saveSetting('nodeEditorWorkflow', '', 'node_editor');
-
- // Reset to new workflow mode
- setCurrentWorkflowId(null);
- setWorkflowMode('new');
- setEditingDraftId(null);
- } else {
- console.error('[NodeEditor] Deployment failed:', result.error);
- alert(`Deployment failed: ${result.error}`);
- }
- } catch (error: any) {
- console.error('[NodeEditor] Deploy failed:', error);
- alert(`Deployment failed: ${error.message}`);
- } finally {
- setIsExecuting(false);
- }
- }, 0);
- }, [nodes, edges, workflowName, workflowDescription, isExecuting, setNodes]);
-
- // Save as draft
- const saveDraft = useCallback(async () => {
- if (!workflowName.trim()) {
- alert('Please enter a workflow name');
- return;
- }
-
- try {
- let workflowId: string;
- if (editingDraftId) {
- // Update existing draft
- await workflowService.updateDraft(
- editingDraftId,
- workflowName,
- workflowDescription,
- nodes,
- edges
- );
- workflowId = editingDraftId;
- setEditingDraftId(null);
- } else {
- // Create new draft
- workflowId = await workflowExecutor.saveDraft(
- workflowName,
- workflowDescription,
- nodes,
- edges
- );
- }
- setCurrentWorkflowId(workflowId);
- setWorkflowMode('draft');
- setShowDeployDialog(false);
- setWorkflowName('');
- setWorkflowDescription('');
- setActiveView('workflows');
- } catch (error: any) {
- console.error('[NodeEditor] Save draft failed:', error);
- alert(`Save failed: ${error.message}`);
- }
- }, [nodes, edges, workflowName, workflowDescription, editingDraftId]);
-
- // Load workflow from manager (for play button on draft/completed workflows)
- const handleLoadWorkflow = useCallback((loadedNodes: Node[], loadedEdges: Edge[], workflowId: string, workflow: WorkflowType) => {
- setNodes(loadedNodes);
- setEdges(loadedEdges);
- setCurrentWorkflowId(workflowId);
- setWorkflowMode(workflow.status === 'draft' ? 'draft' : 'deployed');
- setActiveView('editor');
- }, [setNodes, setEdges]);
-
- // View workflow results
- const handleViewResults = useCallback((workflow: WorkflowType) => {
- // Ask user if they want to see in modal or navigate to workflow
- const choice = window.confirm(
- `View results for: ${workflow.name}\n\n` +
- `Click OK to view in modal window\n` +
- `Click Cancel to navigate to workflow editor with results`
- );
-
- if (choice) {
- // Show in modal
- setResultsData(workflow.results);
- setResultsWorkflowName(workflow.name);
- setShowResultsModal(true);
- } else {
- // Navigate to editor with results
- setNodes(workflow.nodes);
- setEdges(workflow.edges);
- setCurrentWorkflowId(workflow.id);
- setWorkflowMode('deployed');
- setActiveView('editor');
- }
- }, [setNodes, setEdges]);
-
- // Edit draft workflow
- const handleEditDraft = useCallback((workflow: WorkflowType) => {
- setNodes(workflow.nodes);
- setEdges(workflow.edges);
- setWorkflowName(workflow.name);
- setWorkflowDescription(workflow.description || '');
- setEditingDraftId(workflow.id);
- setCurrentWorkflowId(workflow.id);
- setWorkflowMode('draft');
- setShowDeployDialog(true);
- setActiveView('editor');
- }, [setNodes, setEdges]);
-
- return (
- <div
- style={{
- width: '100%',
- height: '100%',
- backgroundColor: 'colors.panel',
- display: 'flex',
- flexDirection: 'column',
- }}
- >
- {/* Toolbar */}
- <div
- style={{
- backgroundColor: '#1a1a1a',
- borderBottom: '1px solid #2d2d2d',
- padding: '8px 12px',
- display: 'flex',
- alignItems: 'center',
- gap: '12px',
- flexWrap: 'wrap',
- flexShrink: 0,
- }}
- >
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <span
- style={{
- color: '#ea580c',
- fontSize: '12px',
- fontWeight: 'bold',
- letterSpacing: '0.5px',
- }}
- >
- {t('title')}
- </span>
- <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }}></div>
-
- {/* Tab Switcher */}
- <button
- onClick={() => setActiveView('editor')}
- style={{
- backgroundColor: activeView === 'editor' ? '#ea580c' : 'transparent',
- color: activeView === 'editor' ? 'white' : '#a3a3a3',
- border: activeView === 'editor' ? 'none' : '1px solid #404040',
- padding: '4px 10px',
- fontSize: '10px',
- cursor: 'pointer',
- borderRadius: '3px',
- fontWeight: 'bold',
- }}
- >
- {t('tabs.editor')}
- </button>
- <button
- onClick={() => setActiveView('workflows')}
- style={{
- backgroundColor: activeView === 'workflows' ? '#ea580c' : 'transparent',
- color: activeView === 'workflows' ? 'white' : '#a3a3a3',
- border: activeView === 'workflows' ? 'none' : '1px solid #404040',
- padding: '4px 10px',
- fontSize: '10px',
- cursor: 'pointer',
- borderRadius: '3px',
- fontWeight: 'bold',
- }}
- >
- WORKFLOWS
- </button>
- </div>
-
- {/* Editor-specific buttons */}
- {activeView === 'editor' && (
- <>
- <button
- onClick={() => setShowNodeMenu(!showNodeMenu)}
- style={{
- backgroundColor: '#ea580c',
- color: 'white',
- border: 'none',
- padding: '6px 12px',
- fontSize: '11px',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- fontWeight: 'bold',
- }}
- onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = '#dc2626')}
- onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = '#ea580c')}
- >
- <Plus size={14} />
- ADD NODE
- </button>
-
- <button
- onClick={async () => {
- if (isExecuting) {
- alert('A workflow is already executing. Please wait for it to complete.');
- return;
- }
-
- try {
- setIsExecuting(true);
- await nodeExecutionManager.executeWorkflow(
- nodes,
- edges,
- (nodeId, status, result) => {
- // Update node status
- setNodes((nds) =>
- nds.map((node) => {
- if (node.id === nodeId) {
- // For results-display nodes, update inputData
- if (node.type === 'results-display') {
- // Force update to trigger re-render
- const currentData = node.data as any;
- return {
- ...node,
- data: {
- ...node.data,
- inputData: status === 'completed' ? result : (status === 'error' ? undefined : currentData.inputData),
- status,
- },
- };
- }
- // For other nodes, update status and result
- return {
- ...node,
- data: {
- ...node.data,
- status,
- result: status === 'completed' ? result : undefined,
- error: status === 'error' ? result : undefined,
- },
- };
- }
- return node;
- })
- );
- }
- );
- } catch (error: any) {
- console.error('[NodeEditor] Workflow execution failed:', error);
- // Don't use alert - just log the error
- } finally {
- setIsExecuting(false);
- }
- }}
- disabled={isExecuting}
- style={{
- backgroundColor: 'transparent',
- color: isExecuting ? '#737373' : '#10b981',
- border: `1px solid ${isExecuting ? '#737373' : '#10b981'}`,
- padding: '6px 12px',
- fontSize: '11px',
- cursor: isExecuting ? 'not-allowed' : 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- opacity: isExecuting ? 0.5 : 1,
- }}
- onMouseEnter={(e) => {
- if (!isExecuting) {
- e.currentTarget.style.backgroundColor = '#10b981';
- e.currentTarget.style.color = 'white';
- }
- }}
- onMouseLeave={(e) => {
- if (!isExecuting) {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = '#10b981';
- }
- }}
- >
- <Play size={14} />
- {isExecuting ? 'EXECUTING...' : 'EXECUTE'}
- </button>
-
- <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }}></div>
-
- {/* New Workflow Button */}
- <button
- onClick={() => {
- if (window.confirm('Start a new workflow? Current work will be cleared unless saved.')) {
- clearWorkflow();
- }
- }}
- style={{
- backgroundColor: 'transparent',
- color: '#3b82f6',
- border: '1px solid #3b82f6',
- padding: '6px 12px',
- fontSize: '11px',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- fontWeight: 'bold',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = '#3b82f6';
- e.currentTarget.style.color = 'white';
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = '#3b82f6';
- }}
- title="Start a new workflow"
- >
- <Plus size={14} />
- NEW
- </button>
-
- {/* Quick Save for Drafts */}
- {workflowMode === 'draft' && editingDraftId && (
- <button
- onClick={async () => {
- try {
- await workflowService.updateDraft(
- editingDraftId,
- workflowName || 'Untitled Draft',
- workflowDescription,
- nodes,
- edges
- );
- alert('Draft saved successfully!');
- } catch (error: any) {
- alert(`Save failed: ${error.message}`);
- }
- }}
- style={{
- backgroundColor: '#f59e0b',
- color: 'white',
- border: 'none',
- padding: '6px 12px',
- fontSize: '11px',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- fontWeight: 'bold',
- }}
- title="Quick save current draft"
- >
- <Save size={14} />
- SAVE DRAFT
- </button>
- )}
-
- <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }}></div>
-
- <button
- onClick={saveWorkflow}
- style={{
- backgroundColor: 'transparent',
- color: '#a3a3a3',
- border: '1px solid #404040',
- padding: '6px 12px',
- fontSize: '11px',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = '#2d2d2d';
- e.currentTarget.style.color = 'white';
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = '#a3a3a3';
- }}
- title="Save workflow to browser storage"
- >
- <Save size={14} />
- SAVE
- </button>
-
- <button
- onClick={importWorkflow}
- style={{
- backgroundColor: 'transparent',
- color: '#a3a3a3',
- border: '1px solid #404040',
- padding: '6px 12px',
- fontSize: '11px',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = '#2d2d2d';
- e.currentTarget.style.color = 'white';
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = '#a3a3a3';
- }}
- title="Import workflow from file"
- >
- <Upload size={14} />
- IMPORT
- </button>
-
- <button
- onClick={exportWorkflow}
- style={{
- backgroundColor: 'transparent',
- color: '#a3a3a3',
- border: '1px solid #404040',
- padding: '6px 12px',
- fontSize: '11px',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = '#2d2d2d';
- e.currentTarget.style.color = 'white';
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = '#a3a3a3';
- }}
- >
- <Download size={14} />
- EXPORT
- </button>
-
- <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }}></div>
-
- <button
- onClick={() => {
- if (window.confirm('Are you sure you want to clear all nodes? This cannot be undone.')) {
- clearWorkflow();
- }
- }}
- style={{
- backgroundColor: 'transparent',
- color: '#ef4444',
- border: '1px solid #ef4444',
- padding: '6px 12px',
- fontSize: '11px',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = '#ef4444';
- e.currentTarget.style.color = 'white';
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = '#ef4444';
- }}
- title="Clear all nodes and connections"
- >
- <Trash2 size={14} />
- CLEAR ALL
- </button>
-
- {selectedNodes.length > 0 && (
- <>
- <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }}></div>
- <button
- onClick={deleteSelectedNodes}
- style={{
- backgroundColor: 'transparent',
- color: '#ef4444',
- border: '1px solid #ef4444',
- padding: '6px 12px',
- fontSize: '11px',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = '#ef4444';
- e.currentTarget.style.color = 'white';
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = '#ef4444';
- }}
- >
- <Trash2 size={14} />
- DELETE ({selectedNodes.length})
- </button>
- </>
- )}
-
- <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }}></div>
-
- {/* DEPLOY Button */}
- <button
- onClick={() => setShowDeployDialog(true)}
- style={{
- backgroundColor: 'transparent',
- color: '#3b82f6',
- border: '1px solid #3b82f6',
- padding: '6px 12px',
- fontSize: '11px',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- fontWeight: 'bold',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = '#3b82f6';
- e.currentTarget.style.color = 'white';
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = '#3b82f6';
- }}
- title="Deploy workflow to database"
- >
- <Rocket size={14} />
- DEPLOY
- </button>
-
- <div
- style={{
- marginLeft: 'auto',
- display: 'flex',
- alignItems: 'center',
- gap: '12px',
- }}
- >
- <span style={{ color: '#737373', fontSize: '10px' }}>
- NODES: {nodes.length}
- </span>
- <span style={{ color: '#737373', fontSize: '10px' }}>
- CONNECTIONS: {edges.length}
- </span>
- </div>
- </>
- )}
- </div>
-
- {/* Node Menu */}
- {showNodeMenu && (
- <div
- style={{
- position: 'absolute',
- top: '60px',
- left: '12px',
- backgroundColor: '#1a1a1a',
- border: '1px solid #2d2d2d',
- borderRadius: '4px',
- padding: '12px',
- zIndex: 1000,
- minWidth: '250px',
- maxHeight: '400px',
- overflow: 'auto',
- boxShadow: '0 4px 12px rgba(0,0,0,0.5)',
- }}
- >
- <div
- style={{
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- marginBottom: '12px',
- }}
- >
- <div
- style={{
- color: '#a3a3a3',
- fontSize: '11px',
- fontWeight: 'bold',
- letterSpacing: '0.5px',
- }}
- >
- SELECT NODE TYPE
- </div>
- <button
- onClick={() => setShowNodeMenu(false)}
- style={{
- background: 'transparent',
- border: 'none',
- color: '#a3a3a3',
- cursor: 'pointer',
- padding: '2px',
- }}
- >
- <X size={16} />
- </button>
- </div>
-
- {['Input', 'Processing', 'Output'].map((category) => (
- <div key={category} style={{ marginBottom: '12px' }}>
- <div
- style={{
- color: '#737373',
- fontSize: '10px',
- marginBottom: '6px',
- textTransform: 'uppercase',
- letterSpacing: '0.5px',
- }}
- >
- {category}
- </div>
- {BUILTIN_NODE_CONFIGS.filter((t) => t.category === category).map((config) => (
- <button
- key={config.type}
- onClick={() => addNode(config)}
- style={{
- backgroundColor: 'colors.panel',
- color: config.color,
- border: `1px solid ${config.color}40`,
- padding: '8px 12px',
- fontSize: '11px',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- width: '100%',
- marginBottom: '6px',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = `${config.color}20`;
- e.currentTarget.style.borderColor = config.color;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'colors.panel';
- e.currentTarget.style.borderColor = `${config.color}40`;
- }}
- >
- {config.type === 'data-source' && <Database size={16} />}
- {config.type === 'transformation' && <Zap size={16} />}
- {config.type === 'analysis' && <TrendingUp size={16} />}
- {config.type === 'results-display' && <Monitor size={16} />}
- {config.type === 'visualization' && <BarChart3 size={16} />}
- {config.type === 'agent' && <Brain size={16} />}
- {config.type === 'output' && <FileText size={16} />}
- {config.label}
- </button>
- ))}
- </div>
- ))}
-
- {/* MCP Tools Section */}
- {mcpNodeConfigs.length > 0 && (
- <div style={{ marginBottom: '12px' }}>
- <div
- style={{
- color: 'colors.primary',
- fontSize: '10px',
- marginBottom: '6px',
- textTransform: 'uppercase',
- letterSpacing: '0.5px',
- fontWeight: 'bold',
- }}
- >
- MCP TOOLS ({mcpNodeConfigs.length})
- </div>
- {mcpNodeConfigs.map((config) => (
- <button
- key={config.id}
- onClick={() => addNode(config)}
- style={{
- backgroundColor: 'colors.panel',
- color: 'colors.primary',
- border: '1px solid colors.primary40',
- padding: '8px 12px',
- fontSize: '11px',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- width: '100%',
- marginBottom: '6px',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = 'colors.primary20';
- e.currentTarget.style.borderColor = 'colors.primary';
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'colors.panel';
- e.currentTarget.style.borderColor = 'colors.primary40';
- }}
- >
- <span style={{ fontSize: '14px' }}>{config.icon}</span>
- <div style={{ flex: 1, textAlign: 'left' }}>
- <div>{config.label}</div>
- <div style={{ fontSize: '9px', color: 'colors.textMuted' }}>
- {config.serverId}
- </div>
- </div>
- </button>
- ))}
- </div>
- )}
-
- </div>
- )}
-
- {/* Main Content - Conditional Rendering */}
- {activeView === 'editor' ? (
- <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
- {/* Left Sidebar - Node Palette */}
- <IntegratedNodePalette
- onNodeAdd={handlePaletteNodeAdd}
- isCollapsed={isPaletteCollapsed}
- onToggleCollapse={() => setIsPaletteCollapsed(!isPaletteCollapsed)}
- mcpNodeConfigs={mcpNodeConfigs}
- agentConfigs={agentConfigs}
- />
-
- {/* React Flow Canvas */}
- <div
- ref={reactFlowWrapper}
- style={{ flex: 1, position: 'relative' }}
- onDrop={onDrop}
- onDragOver={onDragOver}
- >
- <ReactFlow
- nodes={nodes}
- edges={edges}
- onNodesChange={onNodesChange}
- onEdgesChange={onEdgesChange}
- onConnect={onConnect}
- onSelectionChange={onSelectionChange}
- nodeTypes={nodeTypes}
- fitView
- style={{ background: '#0a0a0a' }}
- defaultEdgeOptions={{
- animated: true,
- style: { stroke: '#ea580c', strokeWidth: 2 },
- }}
- >
- <Background
- color="#2d2d2d"
- gap={20}
- size={1}
- style={{ backgroundColor: '#0a0a0a' }}
- />
- <Controls
- style={{
- backgroundColor: '#1a1a1a',
- border: '1px solid #2d2d2d',
- borderRadius: '4px',
- }}
- />
- <MiniMap
- style={{
- backgroundColor: '#1a1a1a',
- border: '1px solid #2d2d2d',
- }}
- nodeColor={(node) => {
- return node.data.color || '#3b82f6';
- }}
- />
- </ReactFlow>
-
- {/* Empty State Overlay */}
- {nodes.length === 0 && (
- <div style={{
- position: 'absolute',
- top: '50%',
- left: '50%',
- transform: 'translate(-50%, -50%)',
- textAlign: 'center',
- color: '#6b7280',
- pointerEvents: 'none',
- }}>
- <Workflow size={48} style={{ margin: '0 auto 16px', opacity: 0.3 }} />
- <div style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
- No nodes yet
- </div>
- <div style={{ fontSize: '12px', opacity: 0.7 }}>
- Drag nodes from the palette or click ADD NODE to get started
- </div>
- </div>
- )}
- </div>
-
- {/* Right Sidebar - Config Panel (Fincept Style) */}
- {selectedNodes.length === 1 && (() => {
- const selectedNode = nodes.find(n => n.id === selectedNodes[0]);
- if (!selectedNode) return null;
-
- // Get registry node type if this is a registry node
- const registryData = selectedNode.data.registryData;
- const nodeProperties: INodeProperties[] = registryData?.properties || [];
-
- // Handler for parameter changes
- const handleParameterChange = (paramName: string, value: NodeParameterValue) => {
- setNodes((nds) =>
- nds.map((node) => {
- if (node.id === selectedNode.id) {
- return {
- ...node,
- data: {
- ...node.data,
- parameters: {
- ...(node.data.parameters || {}),
- [paramName]: value,
- },
- },
- };
- }
- return node;
- })
- );
- };
-
- const nodeColor = selectedNode.data.color || '#FF8800';
-
- return (
- <div style={{
- width: '300px',
- backgroundColor: '#000000',
- borderLeft: '2px solid #FF8800',
- display: 'flex',
- flexDirection: 'column',
- overflow: 'hidden',
- fontFamily: '"IBM Plex Mono", "Consolas", monospace',
- }}>
- {/* Panel Header - Fincept Style */}
- <div style={{
- backgroundColor: '#1A1A1A',
- borderBottom: '1px solid #2A2A2A',
- padding: '8px 12px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Settings2 size={14} style={{ color: '#FF8800', filter: 'drop-shadow(0 0 4px #FF8800)' }} />
- <span style={{
- color: '#FF8800',
- fontSize: '11px',
- fontWeight: 700,
- letterSpacing: '0.5px',
- textTransform: 'uppercase',
- }}>
- NODE CONFIG
- </span>
- </div>
- <button
- onClick={() => setSelectedNodes([])}
- style={{
- backgroundColor: 'transparent',
- border: 'none',
- color: '#787878',
- cursor: 'pointer',
- padding: '2px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- }}
- >
- <X size={14} />
- </button>
- </div>
-
- {/* Node Type Badge */}
- <div style={{
- backgroundColor: '#0F0F0F',
- padding: '10px 12px',
- borderBottom: '1px solid #2A2A2A',
- display: 'flex',
- alignItems: 'center',
- gap: '10px',
- }}>
- <div style={{
- width: '28px',
- height: '28px',
- backgroundColor: `${nodeColor}20`,
- border: `1px solid ${nodeColor}`,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- fontSize: '12px',
- fontWeight: 700,
- color: nodeColor,
- }}>
- {(selectedNode.data.label || selectedNode.type || 'N')[0].toUpperCase()}
- </div>
- <div>
- <div style={{ color: '#FFFFFF', fontSize: '11px', fontWeight: 600 }}>
- {selectedNode.data.label || selectedNode.type}
- </div>
- <div style={{ color: '#787878', fontSize: '9px', textTransform: 'uppercase' }}>
- {selectedNode.type}
- </div>
- </div>
- </div>
-
- {/* Scrollable Content */}
- <div style={{ flex: 1, overflow: 'auto', backgroundColor: '#000000' }}>
- {/* Label Section */}
- <div style={{ padding: '12px', borderBottom: '1px solid #2A2A2A' }}>
- <label style={{
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- color: '#FF8800',
- fontSize: '9px',
- fontWeight: 700,
- marginBottom: '6px',
- textTransform: 'uppercase',
- letterSpacing: '0.5px',
- }}>
- <span>LABEL</span>
- <span style={{ color: '#4A4A4A', fontSize: '8px', fontWeight: 400 }}>REQUIRED</span>
- </label>
- <div style={{
- position: 'relative',
- display: 'flex',
- alignItems: 'stretch',
- }}>
- <div style={{
- backgroundColor: '#1A1A1A',
- borderTop: '1px solid #2A2A2A',
- borderLeft: '1px solid #2A2A2A',
- borderBottom: '1px solid #2A2A2A',
- padding: '0 8px',
- display: 'flex',
- alignItems: 'center',
- color: '#FF8800',
- fontSize: '10px',
- fontFamily: '"IBM Plex Mono", "Consolas", monospace',
- }}>
- <Edit3 size={10} />
- </div>
- <input
- type="text"
- value={selectedNode.data.label || ''}
- onChange={(e) => handleLabelChange(selectedNode.id, e.target.value)}
- placeholder="Enter node label..."
- style={{
- flex: 1,
- backgroundColor: '#0A0A0A',
- border: '1px solid #2A2A2A',
- borderLeft: 'none',
- padding: '10px 12px',
- color: '#FFFFFF',
- fontSize: '11px',
- fontFamily: '"IBM Plex Mono", "Consolas", monospace',
- outline: 'none',
- transition: 'all 0.15s ease',
- }}
- onFocus={(e) => {
- e.currentTarget.style.borderColor = '#FF8800';
- e.currentTarget.style.backgroundColor = '#0F0F0F';
- e.currentTarget.style.boxShadow = '0 0 8px #FF880030';
- const iconDiv = e.currentTarget.previousElementSibling as HTMLElement;
- if (iconDiv) iconDiv.style.borderColor = '#FF8800';
- }}
- onBlur={(e) => {
- e.currentTarget.style.borderColor = '#2A2A2A';
- e.currentTarget.style.backgroundColor = '#0A0A0A';
- e.currentTarget.style.boxShadow = 'none';
- const iconDiv = e.currentTarget.previousElementSibling as HTMLElement;
- if (iconDiv) iconDiv.style.borderColor = '#2A2A2A';
- }}
- />
- </div>
- <div style={{
- marginTop: '4px',
- fontSize: '8px',
- color: '#4A4A4A',
- fontFamily: '"IBM Plex Mono", "Consolas", monospace',
- }}>
- Display name for this node in the workflow
- </div>
- </div>
-
- {/* Registry Node Parameters */}
- {nodeProperties.length > 0 && (
- <div style={{
- padding: '14px',
- borderBottom: '1px solid #3A3A3A',
- backgroundColor: '#111111',
- }}>
- {/* Parameters Header */}
- <div style={{
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- marginBottom: '16px',
- paddingBottom: '10px',
- borderBottom: '1px solid #2A2A2A',
- }}>
- <div style={{
- display: 'flex',
- alignItems: 'center',
- gap: '10px',
- }}>
- <div style={{
- width: '4px',
- height: '18px',
- backgroundColor: '#FF8800',
- }} />
- <span style={{
- color: '#FF8800',
- fontSize: '13px',
- fontWeight: 700,
- textTransform: 'uppercase',
- letterSpacing: '1.5px',
- fontFamily: '"IBM Plex Mono", "Consolas", monospace',
- }}>
- PARAMETERS
- </span>
- </div>
- <div style={{
- backgroundColor: '#FF880030',
- border: '1px solid #FF8800',
- padding: '4px 10px',
- fontSize: '12px',
- fontWeight: 700,
- color: '#FF8800',
- fontFamily: '"IBM Plex Mono", "Consolas", monospace',
- }}>
- {nodeProperties.length}
- </div>
- </div>
-
- {/* Parameters List */}
- <div style={{
- display: 'flex',
- flexDirection: 'column',
- gap: '14px',
- }}>
- {nodeProperties.map((param, index) => (
- <div
- key={param.name}
- style={{
- padding: '14px',
- backgroundColor: '#1A1A1A',
- border: '1px solid #333333',
- position: 'relative',
- }}
- >
- {/* Parameter Index Badge */}
- <div style={{
- position: 'absolute',
- top: '-1px',
- left: '-1px',
- backgroundColor: '#2A2A2A',
- color: '#AAAAAA',
- fontSize: '11px',
- fontWeight: 700,
- padding: '4px 8px',
- fontFamily: '"IBM Plex Mono", "Consolas", monospace',
- borderRight: '1px solid #444444',
- borderBottom: '1px solid #444444',
- }}>
- {String(index + 1).padStart(2, '0')}
- </div>
-
- {/* Required Indicator */}
- {param.required && (
- <div style={{
- position: 'absolute',
- top: '0',
- right: '0',
- width: '0',
- height: '0',
- borderStyle: 'solid',
- borderWidth: '0 16px 16px 0',
- borderColor: 'transparent #FF3B3B transparent transparent',
- }} />
- )}
-
- <div style={{ paddingTop: '12px' }}>
- <NodeParameterInput
- parameter={param}
- value={selectedNode.data.parameters?.[param.name] ?? param.default}
- onChange={(value) => handleParameterChange(param.name, value)}
- />
- </div>
- </div>
- ))}
- </div>
-
- {/* Parameters Footer */}
- <div style={{
- marginTop: '14px',
- paddingTop: '10px',
- borderTop: '1px solid #2A2A2A',
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- }}>
- <div style={{
- width: '8px',
- height: '8px',
- backgroundColor: '#00D66F',
- borderRadius: '50%',
- boxShadow: '0 0 6px #00D66F80',
- }} />
- <span style={{
- color: '#AAAAAA',
- fontSize: '11px',
- fontWeight: 600,
- fontFamily: '"IBM Plex Mono", "Consolas", monospace',
- textTransform: 'uppercase',
- letterSpacing: '0.5px',
- }}>
- {nodeProperties.filter(p => p.required).length > 0
- ? `${nodeProperties.filter(p => p.required).length} REQUIRED`
- : 'ALL OPTIONAL'}
- </span>
- </div>
- </div>
- )}
-
- {/* Node Info Section */}
- <div style={{ padding: '12px', borderBottom: '1px solid #2A2A2A' }}>
- <div style={{
- color: '#FF8800',
- fontSize: '9px',
- fontWeight: 700,
- marginBottom: '10px',
- textTransform: 'uppercase',
- letterSpacing: '0.5px',
- }}>
- NODE INFO
- </div>
-
- <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
- {/* Node ID */}
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: '#787878', fontSize: '9px', textTransform: 'uppercase' }}>ID</span>
- <code style={{ color: '#FFFFFF', fontSize: '9px' }}>{selectedNode.id}</code>
- </div>
-
- {/* Position */}
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: '#787878', fontSize: '9px', textTransform: 'uppercase' }}>POS</span>
- <span style={{ color: '#FFFFFF', fontSize: '9px' }}>
- {Math.round(selectedNode.position.x)}, {Math.round(selectedNode.position.y)}
- </span>
- </div>
-
- {/* Registry Type */}
- {selectedNode.data.nodeTypeName && (
- <div style={{ display: 'flex', justifyContent: 'space-between' }}>
- <span style={{ color: '#787878', fontSize: '9px', textTransform: 'uppercase' }}>TYPE</span>
- <span style={{ color: '#FFFFFF', fontSize: '9px' }}>{selectedNode.data.nodeTypeName}</span>
- </div>
- )}
-
- {/* Status */}
- {selectedNode.data.status && (
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <span style={{ color: '#787878', fontSize: '9px', textTransform: 'uppercase' }}>STATUS</span>
- <span style={{
- fontSize: '9px',
- fontWeight: 700,
- padding: '2px 6px',
- backgroundColor: selectedNode.data.status === 'completed' ? '#00D66F20' :
- selectedNode.data.status === 'error' ? '#FF3B3B20' :
- selectedNode.data.status === 'running' ? '#0088FF20' : '#78787820',
- color: selectedNode.data.status === 'completed' ? '#00D66F' :
- selectedNode.data.status === 'error' ? '#FF3B3B' :
- selectedNode.data.status === 'running' ? '#0088FF' : '#787878',
- textTransform: 'uppercase',
- }}>
- {selectedNode.data.status}
- </span>
- </div>
- )}
- </div>
- </div>
-
- {/* Description (for registry nodes) */}
- {registryData?.description && (
- <div style={{ padding: '12px', borderBottom: '1px solid #2A2A2A' }}>
- <div style={{
- color: '#00E5FF',
- fontSize: '9px',
- fontWeight: 700,
- marginBottom: '6px',
- textTransform: 'uppercase',
- letterSpacing: '0.5px',
- }}>
- DESCRIPTION
- </div>
- <div style={{ color: '#FFFFFF', fontSize: '10px', lineHeight: '1.5' }}>
- {registryData.description}
- </div>
- </div>
- )}
-
- {/* Error Display */}
- {selectedNode.data.error && (
- <div style={{
- margin: '12px',
- backgroundColor: '#FF3B3B15',
- border: '1px solid #FF3B3B',
- padding: '10px',
- }}>
- <div style={{
- color: '#FF3B3B',
- fontSize: '9px',
- fontWeight: 700,
- marginBottom: '4px',
- textTransform: 'uppercase',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- }}>
- <AlertCircle size={10} />
- ERROR
- </div>
- <div style={{ color: '#FFFFFF', fontSize: '10px', lineHeight: '1.4' }}>
- {selectedNode.data.error}
- </div>
- </div>
- )}
-
- {/* Result Preview (for completed nodes) */}
- {selectedNode.data.result && selectedNode.data.status === 'completed' && (
- <div style={{
- margin: '12px',
- backgroundColor: '#00D66F15',
- border: '1px solid #00D66F',
- padding: '10px',
- }}>
- <div style={{
- color: '#00D66F',
- fontSize: '9px',
- fontWeight: 700,
- marginBottom: '6px',
- textTransform: 'uppercase',
- }}>
- OUTPUT PREVIEW
- </div>
- <pre style={{
- color: '#FFFFFF',
- fontSize: '9px',
- lineHeight: '1.4',
- overflow: 'auto',
- maxHeight: '80px',
- margin: 0,
- fontFamily: '"IBM Plex Mono", "Consolas", monospace',
- }}>
- {typeof selectedNode.data.result === 'string'
- ? selectedNode.data.result.substring(0, 200)
- : JSON.stringify(selectedNode.data.result, null, 2).substring(0, 200)}
- {(typeof selectedNode.data.result === 'string'
- ? selectedNode.data.result.length
- : JSON.stringify(selectedNode.data.result).length) > 200 && '...'}
- </pre>
- </div>
- )}
- </div>
-
- {/* Panel Footer with Actions - Fincept Style */}
- <div style={{
- padding: '10px 12px',
- backgroundColor: '#0F0F0F',
- borderTop: '1px solid #2A2A2A',
- display: 'flex',
- gap: '8px',
- }}>
- <button
- onClick={() => deleteSelectedNodes()}
- style={{
- flex: 1,
- backgroundColor: 'transparent',
- color: '#FF3B3B',
- border: '1px solid #FF3B3B',
- padding: '6px 8px',
- fontSize: '9px',
- fontWeight: 700,
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- gap: '4px',
- textTransform: 'uppercase',
- letterSpacing: '0.3px',
- fontFamily: '"IBM Plex Mono", "Consolas", monospace',
- transition: 'all 0.15s ease',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = '#FF3B3B';
- e.currentTarget.style.color = '#000000';
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.color = '#FF3B3B';
- }}
- >
- <Trash2 size={10} />
- DELETE
- </button>
- <button
- onClick={() => {
- // Duplicate node
- const newNode = {
- ...selectedNode,
- id: `node_${Date.now()}`,
- position: {
- x: selectedNode.position.x + 50,
- y: selectedNode.position.y + 50,
- },
- data: { ...selectedNode.data },
- };
- setNodes((nds) => [...nds, newNode]);
- }}
- style={{
- flex: 1,
- backgroundColor: '#FF8800',
- color: '#000000',
- border: '1px solid #FF8800',
- padding: '6px 8px',
- fontSize: '9px',
- fontWeight: 700,
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- gap: '4px',
- textTransform: 'uppercase',
- letterSpacing: '0.3px',
- fontFamily: '"IBM Plex Mono", "Consolas", monospace',
- transition: 'all 0.15s ease',
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = '#FFA033';
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = '#FF8800';
- }}
- >
- <Plus size={10} />
- DUPLICATE
- </button>
- </div>
- </div>
- );
- })()}
- </div>
- ) : (
- /* Workflow Manager View */
- <div style={{ flex: 1, overflow: 'hidden' }}>
- <WorkflowManager
- onLoadWorkflow={handleLoadWorkflow}
- onViewResults={handleViewResults}
- onEditDraft={handleEditDraft}
- />
- </div>
- )}
-
- {/* Bottom Info Bar */}
- {activeView === 'editor' && (
- <TabFooter
- tabName="NODE EDITOR"
- leftInfo={[
- { label: '💡 Drag nodes to move | Drag from handles to connect | Select & Delete to remove', color: '#737373' },
- ...(selectedNodes.length > 0 ? [{ label: `Selected: ${selectedNodes.length} node(s)`, color: '#ea580c' }] : [])
- ]}
- statusInfo="Scroll to zoom | Right-click drag to pan"
- backgroundColor="#1a1a1a"
- borderColor="#2d2d2d"
- />
- )}
-
- {/* Deploy Dialog */}
- {showDeployDialog && (
- <div
- style={{
- position: 'fixed',
- top: 0,
- left: 0,
- right: 0,
- bottom: 0,
- backgroundColor: 'rgba(0, 0, 0, 0.7)',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- zIndex: 2000,
- }}
- onClick={() => setShowDeployDialog(false)}
- >
- <div
- style={{
- backgroundColor: '#1a1a1a',
- border: '1px solid #2d2d2d',
- borderRadius: '6px',
- padding: '24px',
- minWidth: '400px',
- maxWidth: '500px',
- }}
- onClick={(e) => e.stopPropagation()}
- >
- <div
- style={{
- color: '#ea580c',
- fontSize: '14px',
- fontWeight: 'bold',
- marginBottom: '20px',
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- }}
- >
- <Rocket size={16} />
- DEPLOY WORKFLOW
- </div>
-
- <div style={{ marginBottom: '16px' }}>
- <label
- style={{
- display: 'block',
- color: '#a3a3a3',
- fontSize: '11px',
- marginBottom: '6px',
- fontWeight: 'bold',
- }}
- >
- WORKFLOW NAME *
- </label>
- <input
- type="text"
- value={workflowName}
- onChange={(e) => setWorkflowName(e.target.value)}
- placeholder="Enter workflow name..."
- autoFocus
- style={{
- width: '100%',
- backgroundColor: '#0a0a0a',
- border: '1px solid #2d2d2d',
- color: 'white',
- padding: '8px 12px',
- fontSize: '12px',
- borderRadius: '4px',
- outline: 'none',
- boxSizing: 'border-box',
- }}
- />
- </div>
-
- <div style={{ marginBottom: '20px' }}>
- <label
- style={{
- display: 'block',
- color: '#a3a3a3',
- fontSize: '11px',
- marginBottom: '6px',
- fontWeight: 'bold',
- }}
- >
- DESCRIPTION (OPTIONAL)
- </label>
- <textarea
- value={workflowDescription}
- onChange={(e) => setWorkflowDescription(e.target.value)}
- placeholder="Enter workflow description..."
- rows={3}
- style={{
- width: '100%',
- backgroundColor: '#0a0a0a',
- border: '1px solid #2d2d2d',
- color: 'white',
- padding: '8px 12px',
- fontSize: '12px',
- borderRadius: '4px',
- outline: 'none',
- resize: 'vertical',
- fontFamily: 'Consolas, monospace',
- boxSizing: 'border-box',
- }}
- />
- </div>
-
- <div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
- <button
- onClick={() => {
- setShowDeployDialog(false);
- setWorkflowName('');
- setWorkflowDescription('');
- }}
- style={{
- backgroundColor: 'transparent',
- color: '#a3a3a3',
- border: '1px solid #404040',
- padding: '8px 16px',
- fontSize: '11px',
- cursor: 'pointer',
- borderRadius: '4px',
- fontWeight: 'bold',
- }}
- >
- CANCEL
- </button>
- <button
- onClick={saveDraft}
- style={{
- backgroundColor: 'transparent',
- color: '#f59e0b',
- border: '1px solid #f59e0b',
- padding: '8px 16px',
- fontSize: '11px',
- cursor: 'pointer',
- borderRadius: '4px',
- fontWeight: 'bold',
- }}
- >
- SAVE AS DRAFT
- </button>
- <button
- onClick={deployWorkflow}
- style={{
- backgroundColor: '#3b82f6',
- color: 'white',
- border: 'none',
- padding: '8px 16px',
- fontSize: '11px',
- cursor: 'pointer',
- borderRadius: '4px',
- fontWeight: 'bold',
- }}
- >
- DEPLOY & EXECUTE
- </button>
- </div>
- </div>
- </div>
- )}
-
- {/* Results Modal */}
- {showResultsModal && (
- <ResultsModal
- data={resultsData}
- workflowName={resultsWorkflowName}
- onClose={() => {
- setShowResultsModal(false);
- setResultsData(null);
- setResultsWorkflowName('');
- }}
- />
- )}
- </div>
- );
-}
+/**
+ * NodeEditorTab
+ *
+ * Re-exports the NodeEditorTab component from ai-quant-lab folder.
+ * This file maintains backwards compatibility with existing imports.
+ *
+ * The actual implementation has been refactored into smaller, organized files
+ * under the ai-quant-lab directory for better maintainability.
+ */
+
+export { default } from './ai-quant-lab/NodeEditorTab';
diff --git a/fincept-terminal-desktop/src/components/tabs/NotesTab.tsx b/fincept-terminal-desktop/src/components/tabs/NotesTab.tsx
index 7902e6d60..d16453192 100644
--- a/fincept-terminal-desktop/src/components/tabs/NotesTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/NotesTab.tsx
@@ -1,1573 +1,2 @@
-// File: src/components/tabs/NotesTab.tsx
-// Professional Fincept Terminal-Grade Financial Note-Taking Interface
-
-import React, { useState, useEffect, useCallback } from 'react';
-import {
- FileText, Plus, Search, Star, Archive, Tag, Calendar, TrendingUp,
- TrendingDown, AlertCircle, Edit3, Trash2, Save, X, Clock, Filter,
- BookOpen, Briefcase, PieChart, DollarSign, Globe, ChevronDown,
- ChevronRight, Copy, Download, Upload, RefreshCw, Maximize2, Minimize2, Bell
-} from 'lucide-react';
-import { notesService, Note, NoteTemplate } from '../../services/core/notesService';
-import { noteReminderService } from '../../services/core/noteReminderService.tsx';
-import { toast } from 'sonner';
-import { TabFooter } from '@/components/common/TabFooter';
-import { useTranslation } from 'react-i18next';
-
-// Fincept Professional Color Palette
-const FINCEPT = {
- 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'
-};
-
-const CATEGORIES = [
- { id: 'ALL', label: 'ALL NOTES', icon: FileText },
- { id: 'TRADE_IDEA', label: 'TRADE IDEAS', icon: TrendingUp },
- { id: 'RESEARCH', label: 'RESEARCH', icon: BookOpen },
- { id: 'MARKET_ANALYSIS', label: 'MARKET ANALYSIS', icon: PieChart },
- { id: 'EARNINGS', label: 'EARNINGS', icon: DollarSign },
- { id: 'ECONOMIC', label: 'ECONOMIC', icon: Globe },
- { id: 'PORTFOLIO', label: 'PORTFOLIO', icon: Briefcase },
- { id: 'GENERAL', label: 'GENERAL', icon: FileText }
-];
-
-const PRIORITIES = ['HIGH', 'MEDIUM', 'LOW'];
-const SENTIMENTS = ['BULLISH', 'BEARISH', 'NEUTRAL'];
-const COLOR_CODES = ['#FF8800', '#00D66F', '#FF3B3B', '#00E5FF', '#FFD700', '#9D4EDD', '#0088FF'];
-
-export function NotesTab() {
- const { t } = useTranslation('notes');
- const [currentTime, setCurrentTime] = useState(new Date());
- const [notes, setNotes] = useState<Note[]>([]);
- const [filteredNotes, setFilteredNotes] = useState<Note[]>([]);
- const [templates, setTemplates] = useState<NoteTemplate[]>([]);
- const [selectedCategory, setSelectedCategory] = useState('ALL');
- const [selectedNote, setSelectedNote] = useState<Note | null>(null);
- const [isEditing, setIsEditing] = useState(false);
- const [isCreating, setIsCreating] = useState(false);
- const [searchQuery, setSearchQuery] = useState('');
- const [showTemplates, setShowTemplates] = useState(false);
- const [showFilters, setShowFilters] = useState(false);
- const [statistics, setStatistics] = useState<any>(null);
- const [upcomingReminders, setUpcomingReminders] = useState<Array<{ note: Note; hoursUntil: number }>>([]);
- const [showReminders, setShowReminders] = useState(false);
-
- // Editor state
- const [editTitle, setEditTitle] = useState('');
- const [editContent, setEditContent] = useState('');
- const [editCategory, setEditCategory] = useState('GENERAL');
- const [editPriority, setEditPriority] = useState('MEDIUM');
- const [editSentiment, setEditSentiment] = useState('NEUTRAL');
- const [editTags, setEditTags] = useState('');
- const [editTickers, setEditTickers] = useState('');
- const [editColorCode, setEditColorCode] = useState('#FF8800');
- const [editReminderDate, setEditReminderDate] = useState('');
-
- // Filters
- const [filterPriority, setFilterPriority] = useState<string | null>(null);
- const [filterSentiment, setFilterSentiment] = useState<string | null>(null);
- const [showFavorites, setShowFavorites] = useState(false);
- const [showArchived, setShowArchived] = useState(false);
-
- // UI State
- const [isRightPanelMinimized, setIsRightPanelMinimized] = useState(false);
-
- // Update time
- useEffect(() => {
- const timer = setInterval(() => setCurrentTime(new Date()), 1000);
- return () => clearInterval(timer);
- }, []);
-
- // Initialize reminder service
- useEffect(() => {
- noteReminderService.start();
- loadUpcomingReminders();
-
- // Listen for openNote events from reminder notifications
- const handleOpenNote = async (event: CustomEvent) => {
- const { noteId } = event.detail;
- const note = await notesService.getNoteById(noteId);
- if (note) {
- setSelectedNote(note);
- setIsEditing(false);
- setIsCreating(false);
- toast.success('Note opened from reminder');
- }
- };
-
- window.addEventListener('openNote', handleOpenNote as unknown as EventListener);
-
- return () => {
- window.removeEventListener('openNote', handleOpenNote as unknown as EventListener);
- };
- }, []);
-
- // Load upcoming reminders
- const loadUpcomingReminders = useCallback(async () => {
- try {
- const upcoming = await noteReminderService.getUpcomingReminders();
- setUpcomingReminders(upcoming);
- } catch (error) {
- console.error('[NotesTab] Failed to load upcoming reminders:', error);
- }
- }, []);
-
- // Load notes
- const loadNotes = useCallback(async () => {
- try {
- let loadedNotes: Note[];
- if (showFavorites) {
- loadedNotes = await notesService.getFavoriteNotes();
- } else if (selectedCategory === 'ALL') {
- loadedNotes = await notesService.getAllNotes(showArchived);
- } else {
- loadedNotes = await notesService.getNotesByCategory(selectedCategory, showArchived);
- }
- setNotes(loadedNotes);
- applyFilters(loadedNotes);
- } catch (error) {
- console.error('[NotesTab] Failed to load notes:', error);
- }
- }, [selectedCategory, showFavorites, showArchived]);
-
- // Load templates
- const loadTemplates = useCallback(async () => {
- try {
- const loadedTemplates = await notesService.getTemplates();
- setTemplates(loadedTemplates);
- } catch (error) {
- console.error('[NotesTab] Failed to load templates:', error);
- }
- }, []);
-
- // Load statistics
- const loadStatistics = useCallback(async () => {
- try {
- const stats = await notesService.getStatistics();
- setStatistics(stats);
- } catch (error) {
- console.error('[NotesTab] Failed to load statistics:', error);
- }
- }, []);
-
- // Apply filters
- const applyFilters = useCallback((notesToFilter: Note[]) => {
- let filtered = [...notesToFilter];
-
- if (searchQuery) {
- filtered = filtered.filter(note =>
- note.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
- note.content.toLowerCase().includes(searchQuery.toLowerCase()) ||
- note.tags?.toLowerCase().includes(searchQuery.toLowerCase()) ||
- note.tickers?.toLowerCase().includes(searchQuery.toLowerCase())
- );
- }
-
- if (filterPriority) {
- filtered = filtered.filter(note => note.priority === filterPriority);
- }
-
- if (filterSentiment) {
- filtered = filtered.filter(note => note.sentiment === filterSentiment);
- }
-
- setFilteredNotes(filtered);
- }, [searchQuery, filterPriority, filterSentiment]);
-
- useEffect(() => {
- loadNotes();
- loadTemplates();
- loadStatistics();
- }, [loadNotes, loadTemplates, loadStatistics]);
-
- useEffect(() => {
- applyFilters(notes);
- }, [notes, applyFilters]);
-
- // Create new note
- const handleCreateNote = async () => {
- if (!editTitle.trim()) {
- alert('Please enter a title');
- return;
- }
-
- try {
- const wordCount = editContent.trim().split(/\s+/).filter(w => w.length > 0).length;
- const newNote: Omit<Note, 'id'> = {
- title: editTitle,
- content: editContent,
- category: editCategory,
- priority: editPriority,
- tags: editTags,
- tickers: editTickers,
- sentiment: editSentiment,
- is_favorite: false,
- is_archived: false,
- color_code: editColorCode,
- attachments: '[]',
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString(),
- reminder_date: editReminderDate || null,
- word_count: wordCount
- };
-
- await notesService.createNote(newNote);
- await loadNotes();
- await loadStatistics();
- await loadUpcomingReminders();
- if (editReminderDate) {
- toast.success(`Note created with reminder set for ${new Date(editReminderDate).toLocaleString()}`);
- }
- resetEditor();
- setIsCreating(false);
- } catch (error) {
- console.error('[NotesTab] Failed to create note:', error);
- alert('Failed to create note');
- }
- };
-
- // Update note
- const handleUpdateNote = async () => {
- if (!selectedNote) return;
-
- try {
- const wordCount = editContent.trim().split(/\s+/).filter(w => w.length > 0).length;
- await notesService.updateNote(selectedNote.id!, {
- title: editTitle,
- content: editContent,
- category: editCategory,
- priority: editPriority,
- tags: editTags,
- tickers: editTickers,
- sentiment: editSentiment,
- color_code: editColorCode,
- reminder_date: editReminderDate || null,
- word_count: wordCount
- });
-
- await loadNotes();
- await loadStatistics();
- await loadUpcomingReminders();
- if (editReminderDate) {
- toast.success(`Reminder updated for ${new Date(editReminderDate).toLocaleString()}`);
- }
- setIsEditing(false);
-
- // Update selectedNote to reflect changes
- const updatedNote = await notesService.getNoteById(selectedNote.id!);
- setSelectedNote(updatedNote);
- } catch (error) {
- console.error('[NotesTab] Failed to update note:', error);
- alert('Failed to update note');
- }
- };
-
- // Delete note
- const handleDeleteNote = async (id: number) => {
- if (!confirm('Are you sure you want to delete this note?')) return;
-
- try {
- await notesService.deleteNote(id);
- await loadNotes();
- await loadStatistics();
- if (selectedNote?.id === id) {
- setSelectedNote(null);
- }
- } catch (error) {
- console.error('[NotesTab] Failed to delete note:', error);
- alert('Failed to delete note');
- }
- };
-
- // Toggle favorite
- const handleToggleFavorite = async (note: Note) => {
- try {
- await notesService.updateNote(note.id!, {
- is_favorite: !note.is_favorite
- });
- await loadNotes();
- } catch (error) {
- console.error('[NotesTab] Failed to toggle favorite:', error);
- }
- };
-
- // Toggle archive
- const handleToggleArchive = async (note: Note) => {
- try {
- await notesService.updateNote(note.id!, {
- is_archived: !note.is_archived
- });
- await loadNotes();
- await loadStatistics();
- if (selectedNote?.id === note.id) {
- setSelectedNote(null);
- }
- } catch (error) {
- console.error('[NotesTab] Failed to toggle archive:', error);
- }
- };
-
- // Start editing
- const startEditing = (note: Note) => {
- setSelectedNote(note);
- setEditTitle(note.title);
- setEditContent(note.content);
- setEditCategory(note.category);
- setEditPriority(note.priority);
- setEditSentiment(note.sentiment);
- setEditTags(note.tags || '');
- setEditTickers(note.tickers || '');
- setEditColorCode(note.color_code);
- setEditReminderDate(note.reminder_date || '');
- setIsEditing(true);
- };
-
- // Start creating from template
- const createFromTemplate = (template: NoteTemplate) => {
- setEditTitle(`New ${template.name}`);
- setEditContent(template.content);
- setEditCategory(template.category);
- setEditPriority('MEDIUM');
- setEditSentiment('NEUTRAL');
- setEditTags('');
- setEditTickers('');
- setEditColorCode('#FF8800');
- setEditReminderDate('');
- setIsCreating(true);
- setShowTemplates(false);
- };
-
- // Reset editor
- const resetEditor = () => {
- setEditTitle('');
- setEditContent('');
- setEditCategory('GENERAL');
- setEditPriority('MEDIUM');
- setEditSentiment('NEUTRAL');
- setEditTags('');
- setEditTickers('');
- setEditColorCode('#FF8800');
- setEditReminderDate('');
- };
-
- const getPriorityColor = (priority: string) => {
- switch (priority) {
- case 'HIGH': return FINCEPT.RED;
- case 'MEDIUM': return FINCEPT.YELLOW;
- case 'LOW': return FINCEPT.GREEN;
- default: return FINCEPT.GRAY;
- }
- };
-
- const getSentimentColor = (sentiment: string) => {
- switch (sentiment) {
- case 'BULLISH': return FINCEPT.GREEN;
- case 'BEARISH': return FINCEPT.RED;
- case 'NEUTRAL': return FINCEPT.YELLOW;
- default: return FINCEPT.GRAY;
- }
- };
-
- return (
- <div style={{
- height: '100%',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- fontFamily: '"IBM Plex Mono", "Consolas", monospace',
- overflow: 'hidden',
- display: 'flex',
- flexDirection: 'column'
- }}>
- <style>{`
- @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600;700&display=swap');
-
- *::-webkit-scrollbar { width: 6px; height: 6px; }
- *::-webkit-scrollbar-track { background: ${FINCEPT.DARK_BG}; }
- *::-webkit-scrollbar-thumb { background: ${FINCEPT.BORDER}; border-radius: 3px; }
- *::-webkit-scrollbar-thumb:hover { background: ${FINCEPT.MUTED}; }
-
- .terminal-glow {
- text-shadow: 0 0 10px ${FINCEPT.ORANGE}40;
- }
- `}</style>
-
- {/* ========== TOP NAVIGATION BAR ========== */}
- <div style={{
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `2px solid ${FINCEPT.ORANGE}`,
- padding: '6px 12px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- flexShrink: 0,
- boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20`
- }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <FileText size={18} color={FINCEPT.ORANGE} style={{ filter: 'drop-shadow(0 0 4px ' + FINCEPT.ORANGE + ')' }} />
- <span style={{
- color: FINCEPT.ORANGE,
- fontWeight: 700,
- fontSize: '14px',
- letterSpacing: '0.5px',
- textShadow: `0 0 10px ${FINCEPT.ORANGE}40`
- }}>
- {t('title')}
- </span>
- </div>
-
- <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
-
- {statistics && (
- <>
- <div style={{ fontSize: '10px', color: FINCEPT.CYAN }}>
- {t('header.total')}: <span style={{ fontWeight: 700 }}>{statistics.total}</span>
- </div>
- <div style={{ fontSize: '10px', color: FINCEPT.YELLOW }}>
- {t('header.favorites')}: <span style={{ fontWeight: 700 }}>{statistics.favorites}</span>
- </div>
- <div style={{ fontSize: '10px', color: FINCEPT.PURPLE }}>
- {t('header.words')}: <span style={{ fontWeight: 700 }}>{statistics.totalWords.toLocaleString()}</span>
- </div>
- </>
- )}
- </div>
-
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '10px', color: FINCEPT.CYAN }}>
- <Clock size={12} />
- {currentTime.toLocaleTimeString('en-US', { hour12: false })}
- </div>
-
- <button
- onClick={() => {
- loadNotes();
- loadUpcomingReminders();
- }}
- style={{
- padding: '4px 8px',
- backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.GRAY,
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- fontSize: '10px',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.ORANGE;
- e.currentTarget.style.color = FINCEPT.ORANGE;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
- e.currentTarget.style.color = FINCEPT.GRAY;
- }}
- >
- <RefreshCw size={12} />
- {t('header.refresh')}
- </button>
-
- <button
- onClick={() => setShowReminders(!showReminders)}
- style={{
- padding: '4px 8px',
- backgroundColor: showReminders ? FINCEPT.YELLOW : 'transparent',
- border: `1px solid ${upcomingReminders.length > 0 ? FINCEPT.YELLOW : FINCEPT.BORDER}`,
- color: showReminders ? FINCEPT.DARK_BG : upcomingReminders.length > 0 ? FINCEPT.YELLOW : FINCEPT.GRAY,
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- fontSize: '10px',
- fontWeight: 700,
- transition: 'all 0.2s'
- }}
- title="View upcoming reminders"
- >
- <Bell size={12} />
- {upcomingReminders.length > 0 && `(${upcomingReminders.length})`}
- </button>
- </div>
- </div>
-
- {/* ========== TOOLBAR ========== */}
- <div style={{
- backgroundColor: FINCEPT.PANEL_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- padding: '8px 12px',
- display: 'flex',
- alignItems: 'center',
- gap: '12px',
- flexShrink: 0
- }}>
- {/* Search */}
- <div style={{ position: 'relative', flex: 1, maxWidth: '400px' }}>
- <Search size={14} style={{ position: 'absolute', left: '8px', top: '50%', transform: 'translateY(-50%)', color: FINCEPT.GRAY }} />
- <input
- type="text"
- placeholder={t('toolbar.search')}
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- style={{
- width: '100%',
- padding: '6px 8px 6px 32px',
- backgroundColor: FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
- fontSize: '11px',
- outline: 'none'
- }}
- />
- </div>
-
- {/* Action Buttons */}
- <button
- onClick={() => {
- resetEditor();
- setIsCreating(true);
- }}
- style={{
- padding: '6px 12px',
- backgroundColor: FINCEPT.GREEN,
- border: 'none',
- color: FINCEPT.DARK_BG,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Plus size={14} />
- {t('toolbar.newNote')}
- </button>
-
- <button
- onClick={() => setShowTemplates(!showTemplates)}
- style={{
- padding: '6px 12px',
- backgroundColor: showTemplates ? FINCEPT.ORANGE : FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: showTemplates ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <BookOpen size={14} />
- {t('toolbar.templates')}
- </button>
-
- <button
- onClick={() => setShowFavorites(!showFavorites)}
- style={{
- padding: '6px 12px',
- backgroundColor: showFavorites ? FINCEPT.YELLOW : FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: showFavorites ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Star size={14} fill={showFavorites ? FINCEPT.DARK_BG : 'none'} />
- {t('toolbar.favorites')}
- </button>
-
- <button
- onClick={() => setShowFilters(!showFilters)}
- style={{
- padding: '6px 12px',
- backgroundColor: showFilters ? FINCEPT.CYAN : FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: showFilters ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Filter size={14} />
- {t('toolbar.filters')}
- </button>
-
- <button
- onClick={() => setShowArchived(!showArchived)}
- style={{
- padding: '6px 12px',
- backgroundColor: showArchived ? FINCEPT.PURPLE : FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: showArchived ? FINCEPT.WHITE : FINCEPT.GRAY,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Archive size={14} />
- {t('toolbar.archived')}
- </button>
- </div>
-
- {/* ========== FILTERS PANEL ========== */}
- {showFilters && (
- <div style={{
- backgroundColor: FINCEPT.PANEL_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- padding: '8px 12px',
- display: 'flex',
- alignItems: 'center',
- gap: '16px',
- flexShrink: 0,
- fontSize: '10px'
- }}>
- <span style={{ color: FINCEPT.ORANGE, fontWeight: 700 }}>FILTERS:</span>
-
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
- <span style={{ color: FINCEPT.GRAY }}>Priority:</span>
- {PRIORITIES.map(priority => (
- <button
- key={priority}
- onClick={() => setFilterPriority(filterPriority === priority ? null : priority)}
- style={{
- padding: '4px 8px',
- backgroundColor: filterPriority === priority ? getPriorityColor(priority) : FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: filterPriority === priority ? FINCEPT.DARK_BG : getPriorityColor(priority),
- cursor: 'pointer',
- fontSize: '9px',
- fontWeight: 700
- }}
- >
- {priority}
- </button>
- ))}
- </div>
-
- <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
-
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
- <span style={{ color: FINCEPT.GRAY }}>Sentiment:</span>
- {SENTIMENTS.map(sentiment => (
- <button
- key={sentiment}
- onClick={() => setFilterSentiment(filterSentiment === sentiment ? null : sentiment)}
- style={{
- padding: '4px 8px',
- backgroundColor: filterSentiment === sentiment ? getSentimentColor(sentiment) : FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: filterSentiment === sentiment ? FINCEPT.DARK_BG : getSentimentColor(sentiment),
- cursor: 'pointer',
- fontSize: '9px',
- fontWeight: 700
- }}
- >
- {sentiment}
- </button>
- ))}
- </div>
-
- <button
- onClick={() => {
- setFilterPriority(null);
- setFilterSentiment(null);
- }}
- style={{
- marginLeft: 'auto',
- padding: '4px 8px',
- backgroundColor: FINCEPT.RED,
- border: 'none',
- color: FINCEPT.WHITE,
- cursor: 'pointer',
- fontSize: '9px',
- fontWeight: 700
- }}
- >
- CLEAR FILTERS
- </button>
- </div>
- )}
-
- {/* ========== TEMPLATES PANEL ========== */}
- {showTemplates && (
- <div style={{
- backgroundColor: FINCEPT.PANEL_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- padding: '12px',
- flexShrink: 0
- }}>
- <div style={{ color: FINCEPT.ORANGE, fontSize: '11px', fontWeight: 700, marginBottom: '8px' }}>
- SELECT TEMPLATE
- </div>
- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '8px' }}>
- {templates.map(template => (
- <div
- key={template.id}
- onClick={() => createFromTemplate(template)}
- style={{
- padding: '12px',
- backgroundColor: FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- cursor: 'pointer',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.ORANGE;
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
- e.currentTarget.style.backgroundColor = FINCEPT.HEADER_BG;
- }}
- >
- <div style={{ color: FINCEPT.CYAN, fontSize: '11px', fontWeight: 700, marginBottom: '4px' }}>
- {template.name}
- </div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', lineHeight: '1.4' }}>
- {template.description}
- </div>
- </div>
- ))}
- </div>
- </div>
- )}
-
- {/* ========== UPCOMING REMINDERS PANEL ========== */}
- {showReminders && (
- <div style={{
- backgroundColor: FINCEPT.PANEL_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- padding: '12px',
- flexShrink: 0
- }}>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
- <div style={{ color: FINCEPT.YELLOW, fontSize: '11px', fontWeight: 700, display: 'flex', alignItems: 'center', gap: '6px' }}>
- <Bell size={14} />
- UPCOMING REMINDERS (24H)
- </div>
- <button
- onClick={async () => {
- await loadUpcomingReminders();
- toast.success('Reminders refreshed');
- }}
- style={{
- padding: '4px 8px',
- backgroundColor: FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.GRAY,
- cursor: 'pointer',
- fontSize: '9px',
- fontWeight: 700,
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <RefreshCw size={10} />
- REFRESH
- </button>
- </div>
- {upcomingReminders.length === 0 ? (
- <div style={{
- padding: '20px',
- textAlign: 'center',
- color: FINCEPT.GRAY,
- fontSize: '10px',
- backgroundColor: FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`
- }}>
- No upcoming reminders in the next 24 hours
- </div>
- ) : (
- <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
- {upcomingReminders.map(({ note, hoursUntil }) => {
- const isUrgent = hoursUntil < 1;
- const minutesUntil = Math.round(hoursUntil * 60);
- const timeText = hoursUntil < 1
- ? `${minutesUntil} minute${minutesUntil !== 1 ? 's' : ''}`
- : `${Math.round(hoursUntil)} hour${Math.round(hoursUntil) !== 1 ? 's' : ''}`;
-
- return (
- <div
- key={note.id}
- onClick={() => {
- setSelectedNote(note);
- setIsEditing(false);
- setIsCreating(false);
- setShowReminders(false);
- }}
- style={{
- padding: '10px',
- backgroundColor: isUrgent ? `${FINCEPT.RED}10` : FINCEPT.HEADER_BG,
- border: `1px solid ${isUrgent ? FINCEPT.RED : FINCEPT.BORDER}`,
- borderLeft: `4px solid ${note.color_code}`,
- cursor: 'pointer',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = isUrgent ? `${FINCEPT.RED}10` : FINCEPT.HEADER_BG;
- }}
- >
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
- <div style={{ color: FINCEPT.WHITE, fontSize: '11px', fontWeight: 700 }}>
- {note.title}
- </div>
- <div style={{
- padding: '2px 6px',
- backgroundColor: isUrgent ? FINCEPT.RED : FINCEPT.YELLOW,
- color: FINCEPT.DARK_BG,
- fontSize: '8px',
- fontWeight: 700
- }}>
- {isUrgent ? '🔴 URGENT' : ` ${timeText.toUpperCase()}`}
- </div>
- </div>
- <div style={{ display: 'flex', gap: '8px', fontSize: '9px', color: FINCEPT.GRAY }}>
- <span style={{ color: getPriorityColor(note.priority) }}>{note.priority}</span>
- <span>•</span>
- <span style={{ color: getSentimentColor(note.sentiment) }}>{note.sentiment}</span>
- <span>•</span>
- <span>{note.category}</span>
- {note.tickers && (
- <>
- <span>•</span>
- <span style={{ color: FINCEPT.CYAN }}>{note.tickers}</span>
- </>
- )}
- </div>
- <div style={{ fontSize: '8px', color: FINCEPT.MUTED, marginTop: '4px' }}>
- Due: {new Date(note.reminder_date!).toLocaleString()}
- </div>
- </div>
- );
- })}
- </div>
- )}
- </div>
- )}
-
- {/* ========== MAIN CONTENT ========== */}
- <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
- {/* LEFT SIDEBAR - Categories */}
- <div style={{
- width: '220px',
- backgroundColor: FINCEPT.PANEL_BG,
- borderRight: `1px solid ${FINCEPT.BORDER}`,
- display: 'flex',
- flexDirection: 'column',
- overflow: 'hidden'
- }}>
- <div style={{
- padding: '8px 12px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- fontSize: '10px',
- fontWeight: 700,
- color: FINCEPT.ORANGE,
- letterSpacing: '0.5px'
- }}>
- CATEGORIES
- </div>
-
- <div style={{ flex: 1, overflow: 'auto' }}>
- {CATEGORIES.map(category => {
- const Icon = category.icon;
- const count = statistics?.byCategory?.find((s: any) => s.category === category.id)?.count || 0;
-
- return (
- <div
- key={category.id}
- onClick={() => {
- setSelectedCategory(category.id);
- setShowFavorites(false);
- }}
- style={{
- padding: '10px 12px',
- cursor: 'pointer',
- backgroundColor: selectedCategory === category.id ? `${FINCEPT.ORANGE}20` : 'transparent',
- borderLeft: selectedCategory === category.id ? `3px solid ${FINCEPT.ORANGE}` : '3px solid transparent',
- transition: 'all 0.2s',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between'
- }}
- onMouseEnter={(e) => {
- if (selectedCategory !== category.id) {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- }
- }}
- onMouseLeave={(e) => {
- if (selectedCategory !== category.id) {
- e.currentTarget.style.backgroundColor = 'transparent';
- }
- }}
- >
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Icon size={14} color={selectedCategory === category.id ? FINCEPT.ORANGE : FINCEPT.GRAY} />
- <span style={{
- fontSize: '10px',
- fontWeight: 600,
- color: selectedCategory === category.id ? FINCEPT.ORANGE : FINCEPT.WHITE
- }}>
- {category.label}
- </span>
- </div>
- {category.id !== 'ALL' && (
- <span style={{
- fontSize: '9px',
- color: FINCEPT.CYAN,
- fontWeight: 700
- }}>
- {count}
- </span>
- )}
- </div>
- );
- })}
- </div>
- </div>
-
- {/* CENTER - Notes List */}
- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
- <div style={{
- padding: '8px 12px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- fontSize: '10px',
- fontWeight: 700,
- color: FINCEPT.ORANGE,
- letterSpacing: '0.5px',
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center'
- }}>
- <span>NOTES ({filteredNotes.length})</span>
- <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>
- SORTED BY: RECENTLY UPDATED
- </span>
- </div>
-
- <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>
- {filteredNotes.length === 0 ? (
- <div style={{
- padding: '40px',
- textAlign: 'center',
- color: FINCEPT.GRAY,
- fontSize: '11px'
- }}>
- {searchQuery ? 'No notes found matching your search' : 'No notes yet. Create your first note!'}
- </div>
- ) : (
- filteredNotes.map(note => (
- <div
- key={note.id}
- onClick={() => {
- setSelectedNote(note);
- setIsEditing(false);
- setIsCreating(false);
- }}
- style={{
- marginBottom: '8px',
- padding: '12px',
- backgroundColor: selectedNote?.id === note.id ? `${FINCEPT.ORANGE}15` : FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderLeft: `4px solid ${note.color_code}`,
- cursor: 'pointer',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- if (selectedNote?.id !== note.id) {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- }
- }}
- onMouseLeave={(e) => {
- if (selectedNote?.id !== note.id) {
- e.currentTarget.style.backgroundColor = FINCEPT.HEADER_BG;
- }
- }}
- >
- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flex: 1 }}>
- <span style={{ color: FINCEPT.WHITE, fontSize: '11px', fontWeight: 700 }}>
- {note.title}
- </span>
- {note.is_favorite && <Star size={12} fill={FINCEPT.YELLOW} color={FINCEPT.YELLOW} />}
- </div>
- <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
- <span style={{
- padding: '2px 6px',
- backgroundColor: getPriorityColor(note.priority),
- color: FINCEPT.DARK_BG,
- fontSize: '8px',
- fontWeight: 700
- }}>
- {note.priority}
- </span>
- <span style={{
- padding: '2px 6px',
- backgroundColor: getSentimentColor(note.sentiment),
- color: FINCEPT.DARK_BG,
- fontSize: '8px',
- fontWeight: 700
- }}>
- {note.sentiment}
- </span>
- </div>
- </div>
-
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', lineHeight: '1.4', marginBottom: '6px' }}>
- {note.content.substring(0, 120)}{note.content.length > 120 ? '...' : ''}
- </div>
-
- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: '8px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', color: FINCEPT.MUTED }}>
- <span>{new Date(note.updated_at).toLocaleDateString()}</span>
- {note.word_count > 0 && <span>{note.word_count} words</span>}
- {note.tickers && <span style={{ color: FINCEPT.CYAN }}>{note.tickers}</span>}
- </div>
- {note.tags && (
- <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
- <Tag size={10} color={FINCEPT.PURPLE} />
- <span style={{ color: FINCEPT.PURPLE }}>{note.tags.split(',').slice(0, 2).join(', ')}</span>
- </div>
- )}
- </div>
- </div>
- ))
- )}
- </div>
- </div>
-
- {/* RIGHT PANEL - Note Viewer/Editor */}
- {!isRightPanelMinimized && (
- <div style={{
- width: '500px',
- backgroundColor: FINCEPT.PANEL_BG,
- borderLeft: `1px solid ${FINCEPT.BORDER}`,
- display: 'flex',
- flexDirection: 'column',
- overflow: 'hidden'
- }}>
- {(isEditing || isCreating) ? (
- // EDITOR MODE
- <>
- <div style={{
- padding: '8px 12px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- fontSize: '10px',
- fontWeight: 700,
- color: FINCEPT.ORANGE,
- letterSpacing: '0.5px',
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center'
- }}>
- <span>{isCreating ? 'CREATE NOTE' : 'EDIT NOTE'}</span>
- <div style={{ display: 'flex', gap: '4px' }}>
- <button
- onClick={isCreating ? handleCreateNote : handleUpdateNote}
- style={{
- padding: '4px 8px',
- backgroundColor: FINCEPT.GREEN,
- border: 'none',
- color: FINCEPT.DARK_BG,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Save size={12} />
- SAVE
- </button>
- <button
- onClick={() => {
- setIsEditing(false);
- setIsCreating(false);
- resetEditor();
- }}
- style={{
- padding: '4px 8px',
- backgroundColor: FINCEPT.RED,
- border: 'none',
- color: FINCEPT.WHITE,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <X size={12} />
- CANCEL
- </button>
- </div>
- </div>
-
- <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
- {/* Title */}
- <div style={{ marginBottom: '12px' }}>
- <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
- TITLE *
- </label>
- <input
- type="text"
- value={editTitle}
- onChange={(e) => setEditTitle(e.target.value)}
- style={{
- width: '100%',
- padding: '8px',
- backgroundColor: FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
- fontSize: '12px',
- fontWeight: 700,
- outline: 'none'
- }}
- placeholder="Enter note title..."
- />
- </div>
-
- {/* Metadata Row 1 */}
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '12px' }}>
- <div>
- <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
- CATEGORY
- </label>
- <select
- value={editCategory}
- onChange={(e) => setEditCategory(e.target.value)}
- style={{
- width: '100%',
- padding: '6px',
- backgroundColor: FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
- fontSize: '10px',
- outline: 'none'
- }}
- >
- {CATEGORIES.filter(c => c.id !== 'ALL').map(cat => (
- <option key={cat.id} value={cat.id}>{cat.label}</option>
- ))}
- </select>
- </div>
-
- <div>
- <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
- PRIORITY
- </label>
- <select
- value={editPriority}
- onChange={(e) => setEditPriority(e.target.value)}
- style={{
- width: '100%',
- padding: '6px',
- backgroundColor: FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
- fontSize: '10px',
- outline: 'none'
- }}
- >
- {PRIORITIES.map(p => (
- <option key={p} value={p}>{p}</option>
- ))}
- </select>
- </div>
- </div>
-
- {/* Metadata Row 2 */}
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '12px' }}>
- <div>
- <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
- SENTIMENT
- </label>
- <select
- value={editSentiment}
- onChange={(e) => setEditSentiment(e.target.value)}
- style={{
- width: '100%',
- padding: '6px',
- backgroundColor: FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
- fontSize: '10px',
- outline: 'none'
- }}
- >
- {SENTIMENTS.map(s => (
- <option key={s} value={s}>{s}</option>
- ))}
- </select>
- </div>
-
- <div>
- <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
- COLOR
- </label>
- <div style={{ display: 'flex', gap: '4px' }}>
- {COLOR_CODES.map(color => (
- <div
- key={color}
- onClick={() => setEditColorCode(color)}
- style={{
- width: '24px',
- height: '24px',
- backgroundColor: color,
- border: editColorCode === color ? `2px solid ${FINCEPT.WHITE}` : `1px solid ${FINCEPT.BORDER}`,
- cursor: 'pointer'
- }}
- />
- ))}
- </div>
- </div>
- </div>
-
- {/* Tags & Tickers */}
- <div style={{ marginBottom: '12px' }}>
- <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
- TAGS (comma-separated)
- </label>
- <input
- type="text"
- value={editTags}
- onChange={(e) => setEditTags(e.target.value)}
- style={{
- width: '100%',
- padding: '6px',
- backgroundColor: FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
- fontSize: '10px',
- outline: 'none'
- }}
- placeholder="growth, tech, semiconductor"
- />
- </div>
-
- <div style={{ marginBottom: '12px' }}>
- <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
- TICKERS (comma-separated)
- </label>
- <input
- type="text"
- value={editTickers}
- onChange={(e) => setEditTickers(e.target.value)}
- style={{
- width: '100%',
- padding: '6px',
- backgroundColor: FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
- fontSize: '10px',
- outline: 'none'
- }}
- placeholder="AAPL, MSFT, NVDA"
- />
- </div>
-
- {/* Reminder Date */}
- <div style={{ marginBottom: '12px' }}>
- <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
- REMINDER DATE
- </label>
- <input
- type="datetime-local"
- value={editReminderDate}
- onChange={(e) => setEditReminderDate(e.target.value)}
- style={{
- width: '100%',
- padding: '6px',
- backgroundColor: FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
- fontSize: '10px',
- outline: 'none'
- }}
- />
- </div>
-
- {/* Content */}
- <div>
- <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
- CONTENT *
- </label>
- <textarea
- value={editContent}
- onChange={(e) => setEditContent(e.target.value)}
- style={{
- width: '100%',
- height: '400px',
- padding: '8px',
- backgroundColor: FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.WHITE,
- fontSize: '11px',
- lineHeight: '1.6',
- outline: 'none',
- resize: 'vertical',
- fontFamily: '"IBM Plex Mono", monospace'
- }}
- placeholder="Write your note content here... Supports Markdown formatting."
- />
- </div>
- </div>
- </>
- ) : selectedNote ? (
- // VIEWER MODE
- <>
- <div style={{
- padding: '8px 12px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- fontSize: '10px',
- fontWeight: 700,
- color: FINCEPT.ORANGE,
- letterSpacing: '0.5px',
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center'
- }}>
- <span>NOTE DETAILS</span>
- <div style={{ display: 'flex', gap: '4px' }}>
- <button
- onClick={() => handleToggleFavorite(selectedNote)}
- style={{
- padding: '4px 8px',
- backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.BORDER}`,
- color: selectedNote.is_favorite ? FINCEPT.YELLOW : FINCEPT.GRAY,
- cursor: 'pointer',
- fontSize: '10px',
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Star size={12} fill={selectedNote.is_favorite ? FINCEPT.YELLOW : 'none'} />
- </button>
- <button
- onClick={() => startEditing(selectedNote)}
- style={{
- padding: '4px 8px',
- backgroundColor: FINCEPT.BLUE,
- border: 'none',
- color: FINCEPT.WHITE,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Edit3 size={12} />
- EDIT
- </button>
- <button
- onClick={() => handleToggleArchive(selectedNote)}
- style={{
- padding: '4px 8px',
- backgroundColor: FINCEPT.PURPLE,
- border: 'none',
- color: FINCEPT.WHITE,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Archive size={12} />
- {selectedNote.is_archived ? 'UNARCHIVE' : 'ARCHIVE'}
- </button>
- <button
- onClick={() => handleDeleteNote(selectedNote.id!)}
- style={{
- padding: '4px 8px',
- backgroundColor: FINCEPT.RED,
- border: 'none',
- color: FINCEPT.WHITE,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <Trash2 size={12} />
- DELETE
- </button>
- </div>
- </div>
-
- <div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>
- {/* Title */}
- <div style={{
- color: FINCEPT.WHITE,
- fontSize: '16px',
- fontWeight: 700,
- marginBottom: '12px',
- paddingBottom: '12px',
- borderBottom: `2px solid ${selectedNote.color_code}`
- }}>
- {selectedNote.title}
- </div>
-
- {/* Metadata */}
- <div style={{
- display: 'grid',
- gridTemplateColumns: '1fr 1fr',
- gap: '8px',
- marginBottom: '16px',
- padding: '12px',
- backgroundColor: FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- fontSize: '9px'
- }}>
- <div>
- <span style={{ color: FINCEPT.GRAY }}>CATEGORY: </span>
- <span style={{ color: FINCEPT.CYAN, fontWeight: 700 }}>{selectedNote.category}</span>
- </div>
- <div>
- <span style={{ color: FINCEPT.GRAY }}>PRIORITY: </span>
- <span style={{ color: getPriorityColor(selectedNote.priority), fontWeight: 700 }}>{selectedNote.priority}</span>
- </div>
- <div>
- <span style={{ color: FINCEPT.GRAY }}>SENTIMENT: </span>
- <span style={{ color: getSentimentColor(selectedNote.sentiment), fontWeight: 700 }}>{selectedNote.sentiment}</span>
- </div>
- <div>
- <span style={{ color: FINCEPT.GRAY }}>WORDS: </span>
- <span style={{ color: FINCEPT.WHITE, fontWeight: 700 }}>{selectedNote.word_count}</span>
- </div>
- {selectedNote.tickers && (
- <div style={{ gridColumn: '1 / -1' }}>
- <span style={{ color: FINCEPT.GRAY }}>TICKERS: </span>
- <span style={{ color: FINCEPT.CYAN, fontWeight: 700 }}>{selectedNote.tickers}</span>
- </div>
- )}
- {selectedNote.tags && (
- <div style={{ gridColumn: '1 / -1' }}>
- <span style={{ color: FINCEPT.GRAY }}>TAGS: </span>
- <span style={{ color: FINCEPT.PURPLE, fontWeight: 700 }}>{selectedNote.tags}</span>
- </div>
- )}
- <div>
- <span style={{ color: FINCEPT.GRAY }}>CREATED: </span>
- <span style={{ color: FINCEPT.WHITE }}>{new Date(selectedNote.created_at).toLocaleString()}</span>
- </div>
- <div>
- <span style={{ color: FINCEPT.GRAY }}>UPDATED: </span>
- <span style={{ color: FINCEPT.WHITE }}>{new Date(selectedNote.updated_at).toLocaleString()}</span>
- </div>
- {selectedNote.reminder_date && (
- <div style={{ gridColumn: '1 / -1' }}>
- <span style={{ color: FINCEPT.GRAY }}>REMINDER: </span>
- <span style={{ color: FINCEPT.YELLOW, fontWeight: 700 }}>{new Date(selectedNote.reminder_date).toLocaleString()}</span>
- </div>
- )}
- </div>
-
- {/* Content */}
- <div style={{
- color: FINCEPT.WHITE,
- fontSize: '11px',
- lineHeight: '1.8',
- whiteSpace: 'pre-wrap',
- fontFamily: '"IBM Plex Mono", monospace'
- }}>
- {selectedNote.content}
- </div>
- </div>
- </>
- ) : (
- // NO SELECTION
- <div style={{
- flex: 1,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- color: FINCEPT.GRAY,
- fontSize: '11px',
- flexDirection: 'column',
- gap: '12px'
- }}>
- <FileText size={48} color={FINCEPT.MUTED} />
- <div>Select a note to view or create a new one</div>
- </div>
- )}
- </div>
- )}
-
- {/* Minimize/Maximize Toggle for Right Panel */}
- <div style={{
- width: '20px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderLeft: `1px solid ${FINCEPT.BORDER}`,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- cursor: 'pointer'
- }}
- onClick={() => setIsRightPanelMinimized(!isRightPanelMinimized)}
- >
- {isRightPanelMinimized ? <ChevronRight size={14} color={FINCEPT.GRAY} /> : <ChevronDown size={14} color={FINCEPT.GRAY} />}
- </div>
- </div>
-
- {/* ========== STATUS BAR ========== */}
- <TabFooter
- tabName="FINANCIAL NOTES"
- leftInfo={[
- { label: 'Professional Note-Taking', color: FINCEPT.GRAY },
- ]}
- statusInfo={
- <span>
- Notes: <span style={{ color: FINCEPT.ORANGE }}>{statistics?.total || 0}</span> |
- Category: <span style={{ color: FINCEPT.CYAN }}>{selectedCategory}</span> |
- Displayed: <span style={{ color: FINCEPT.YELLOW }}>{filteredNotes.length}</span>
- </span>
- }
- backgroundColor={FINCEPT.HEADER_BG}
- borderColor={FINCEPT.BORDER}
- />
- </div>
- );
-}
+// Re-export from refactored notes folder for backwards compatibility
+export { NotesTab } from './notes';
diff --git a/fincept-terminal-desktop/src/components/tabs/RelationshipMapTab.tsx b/fincept-terminal-desktop/src/components/tabs/RelationshipMapTab.tsx
deleted file mode 100644
index 2a3022633..000000000
--- a/fincept-terminal-desktop/src/components/tabs/RelationshipMapTab.tsx
+++ /dev/null
@@ -1,667 +0,0 @@
-import React, { useState, useCallback, useMemo, useEffect } from 'react';
-import { useTranslation } from 'react-i18next';
-import ReactFlow, {
- Node,
- Edge,
- Background,
- Controls,
- MiniMap,
- useNodesState,
- useEdgesState,
- Handle,
- Position,
- MarkerType,
-} from 'reactflow';
-import 'reactflow/dist/style.css';
-import { Search, Building2, Users, TrendingUp, Calendar, BarChart3, Globe, DollarSign, FileText, Award, Activity, Briefcase, PieChart, ExternalLink } from 'lucide-react';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-import { TabFooter } from '@/components/common/TabFooter';
-import { relationshipMapService } from '@/services/geopolitics/relationshipMapService';
-import { open } from '@tauri-apps/plugin-shell';
-
-// ============================================================================
-// CUSTOM NODE COMPONENTS
-// ============================================================================
-
-const CompanyNode = ({ data }: any) => {
- const { colors } = useTerminalTheme();
-
- const formatMarketCap = (val: number) => {
- if (!val) return 'N/A';
- if (val >= 1e12) return `$${(val/1e12).toFixed(2)}T`;
- if (val >= 1e9) return `$${(val/1e9).toFixed(2)}B`;
- if (val >= 1e6) return `$${(val/1e6).toFixed(2)}M`;
- return `$${val}`;
- };
-
- return (
- <div
- style={{
- background: 'linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%)',
- border: `3px solid ${colors.accent}`,
- borderRadius: '12px',
- padding: '24px',
- minWidth: '320px',
- maxWidth: '400px',
- boxShadow: `0 0 40px ${colors.accent}80, 0 10px 30px rgba(0,0,0,0.7)`,
- }}
- >
- <Handle type="target" position={Position.Top} style={{ opacity: 0 }} />
- <div className="flex flex-col items-center text-center">
- <Building2 className="w-12 h-12 mb-3" style={{ color: colors.accent }} />
- <h2 className="text-2xl font-bold mb-1" style={{ color: colors.text }}>{data.name}</h2>
- <div className="text-xl mb-2 font-mono" style={{ color: colors.accent }}>{data.ticker}</div>
- <div className="text-sm mb-1" style={{ color: colors.textMuted }}>
- {data.sector} • {data.industry}
- </div>
- <div className="text-sm font-semibold mt-2" style={{ color: colors.success }}>
- Market Cap: {formatMarketCap(data.market_cap)}
- </div>
- <div className="text-xs mt-2 opacity-60">
- CIK: {data.cik} | {data.exchange}
- </div>
- {data.employees && (
- <div className="text-xs mt-1" style={{ color: colors.textMuted }}>
- {data.employees.toLocaleString()} employees
- </div>
- )}
- </div>
- <Handle type="source" position={Position.Bottom} style={{ opacity: 0 }} />
- <Handle type="source" position={Position.Left} style={{ opacity: 0 }} />
- <Handle type="source" position={Position.Right} style={{ opacity: 0 }} />
- </div>
- );
-};
-
-const DataNode = ({ data }: any) => {
- const { colors } = useTerminalTheme();
- const [expanded, setExpanded] = useState(false);
-
- const getIcon = () => {
- switch (data.type) {
- case 'events': return <Activity className="w-5 h-5" />;
- case 'filings': return <Calendar className="w-5 h-5" />;
- case 'financials': return <DollarSign className="w-5 h-5" />;
- case 'balance': return <BarChart3 className="w-5 h-5" />;
- case 'analysts': return <Award className="w-5 h-5" />;
- case 'ownership': return <PieChart className="w-5 h-5" />;
- case 'valuation': return <TrendingUp className="w-5 h-5" />;
- case 'info': return <Briefcase className="w-5 h-5" />;
- case 'executives': return <Users className="w-5 h-5" />;
- default: return <FileText className="w-5 h-5" />;
- }
- };
-
- const getColor = () => {
- switch (data.type) {
- case 'events': return '#ef4444';
- case 'filings': return '#3b82f6';
- case 'financials': return '#10b981';
- case 'balance': return colors.accent;
- case 'analysts': return '#8b5cf6';
- case 'ownership': return '#f59e0b';
- case 'valuation': return '#ec4899';
- case 'info': return '#14b8a6';
- case 'executives': return '#10b981';
- default: return colors.textMuted;
- }
- };
-
- const displayItems = expanded ? data.items : data.items?.slice(0, 4);
- const hasClickableItems = data.type === 'events' || data.type === 'filings';
-
- const handleItemClick = async (e: React.MouseEvent, item: any) => {
- e.stopPropagation();
- if (hasClickableItems && item.url) {
- await open(item.url);
- }
- };
-
- return (
- <div
- style={{
- background: '#1a1a1a',
- border: `2px solid ${getColor()}`,
- borderRadius: '8px',
- padding: '14px 18px',
- minWidth: '260px',
- maxWidth: '320px',
- boxShadow: `0 0 20px ${getColor()}50, 0 4px 12px rgba(0,0,0,0.5)`,
- cursor: 'pointer',
- transition: 'all 0.2s',
- }}
- onClick={() => data.items?.length > 4 && setExpanded(!expanded)}
- onMouseEnter={(e) => {
- e.currentTarget.style.transform = 'scale(1.02)';
- e.currentTarget.style.boxShadow = `0 0 30px ${getColor()}70, 0 6px 16px rgba(0,0,0,0.6)`;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.transform = 'scale(1)';
- e.currentTarget.style.boxShadow = `0 0 20px ${getColor()}50, 0 4px 12px rgba(0,0,0,0.5)`;
- }}
- >
- <Handle type="target" position={Position.Top} style={{ background: getColor() }} />
-
- <div className="flex items-center gap-2 mb-3">
- <div style={{ color: getColor() }}>{getIcon()}</div>
- <h4 className="font-semibold text-sm" style={{ color: colors.text }}>{data.title}</h4>
- {data.items?.length > 4 && (
- <span className="text-xs ml-auto px-1.5 py-0.5 rounded" style={{
- backgroundColor: `${getColor()}20`,
- color: getColor()
- }}>
- {data.items.length}
- </span>
- )}
- </div>
-
- <div className="space-y-1.5 text-xs">
- {displayItems && displayItems.map((item: any, idx: number) => (
- <div
- key={idx}
- className="flex justify-between gap-3 hover:bg-white/5 rounded px-1 py-0.5 transition-colors"
- onClick={(e) => handleItemClick(e, item)}
- style={{ cursor: hasClickableItems && item.url ? 'pointer' : 'default' }}
- >
- <span className="truncate" style={{ color: colors.textMuted }}>{item.label}</span>
- <span className="font-medium text-right flex items-center gap-1" style={{ color: colors.text }}>
- {item.value}
- {hasClickableItems && item.url && <ExternalLink className="w-3 h-3 opacity-50" />}
- </span>
- </div>
- ))}
- {!expanded && data.items?.length > 4 && (
- <div className="text-center pt-1 text-xs font-semibold" style={{ color: getColor() }}>
- Click to see +{data.items.length - 4} more
- </div>
- )}
- </div>
-
- <Handle type="source" position={Position.Bottom} style={{ background: getColor(), opacity: 0 }} />
- </div>
- );
-};
-
-// ============================================================================
-// MAIN COMPONENT
-// ============================================================================
-
-// Define nodeTypes outside component to avoid re-creation on every render
-const nodeTypes = {
- company: CompanyNode,
- data: DataNode,
-};
-
-const RelationshipMapTab: React.FC = () => {
- const { t } = useTranslation('relationshipMap');
- const { colors, fontSize, fontFamily } = useTerminalTheme();
- const [searchQuery, setSearchQuery] = useState('');
- const [selectedSymbol, setSelectedSymbol] = useState('AAPL');
- const [isLoading, setIsLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- const [nodes, setNodes, onNodesChange] = useNodesState([]);
- const [edges, setEdges, onEdgesChange] = useEdgesState([]);
-
- useEffect(() => {
- fetchRelationshipData(selectedSymbol);
- }, []);
-
- const fetchRelationshipData = async (ticker: string) => {
- setIsLoading(true);
- setError(null);
- try {
- const data = await relationshipMapService.getRelationshipMap(ticker);
- updateGraph(data);
- } catch (err) {
- console.error('[UI] Error:', err);
- setError(`Failed to load data for ${ticker}`);
- } finally {
- setIsLoading(false);
- }
- };
-
- const updateGraph = (data: any) => {
- const formatMoney = (val: number) => {
- if (!val || val === 0) return '$0';
- if (val >= 1e9) return `$${(val/1e9).toFixed(2)}B`;
- if (val >= 1e6) return `$${(val/1e6).toFixed(2)}M`;
- if (val >= 1e3) return `$${(val/1e3).toFixed(2)}K`;
- return `$${val.toFixed(2)}`;
- };
-
- const formatPercent = (val: number) => {
- if (!val && val !== 0) return 'N/A';
- return `${(val * 100).toFixed(2)}%`;
- };
-
- const formatNumber = (val: number) => {
- if (!val && val !== 0) return 'N/A';
- if (val >= 1e9) return `${(val/1e9).toFixed(2)}B`;
- if (val >= 1e6) return `${(val/1e6).toFixed(2)}M`;
- return val.toFixed(2);
- };
-
- const newNodes: Node[] = [
- // Center: Company
- {
- id: 'company',
- type: 'company',
- position: { x: 600, y: 350 },
- data: {
- name: data.company.name,
- ticker: data.company.ticker,
- industry: data.company.industry,
- sector: data.company.sector,
- cik: data.company.cik,
- exchange: data.company.exchange,
- employees: data.company.employees,
- market_cap: data.company.market_cap,
- },
- },
- ];
-
- const newEdges: Edge[] = [];
-
- // 1. Corporate Events (Top-Left) - 8-K Filings with Major Announcements
- const corporateEventItems = data.corporate_events && data.corporate_events.length > 0
- ? data.corporate_events.map((e: any) => {
- const date = new Date(e.filing_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: '2-digit' });
- // Get the first item code or use "Event"
- const itemCode = e.items && e.items.length > 0 ? e.items[0] : 'Event';
- return {
- label: date,
- value: itemCode,
- description: e.description || 'Material corporate event filed with SEC',
- url: e.filing_url,
- allItems: e.items || []
- };
- })
- : [{ label: 'No events available', value: 'Loading...' }];
-
- newNodes.push({
- id: 'events',
- type: 'data',
- position: { x: 50, y: 50 },
- data: {
- type: 'events',
- title: 'Corporate Events',
- items: corporateEventItems,
- },
- });
- newEdges.push({
- id: 'e-events',
- source: 'company',
- target: 'events',
- type: 'smoothstep',
- animated: true,
- style: { stroke: '#ef4444', strokeWidth: 2 },
- markerEnd: { type: MarkerType.ArrowClosed, color: '#ef4444' },
- });
-
- // 2. Recent SEC Filings (Top-Left-Center)
- if (data.filings?.length > 0) {
- newNodes.push({
- id: 'filings',
- type: 'data',
- position: { x: 200, y: 80 },
- data: {
- type: 'filings',
- title: 'Recent SEC Filings',
- items: data.filings.map((f: any) => ({
- label: `${f.form} (${f.description})`,
- value: new Date(f.filing_date).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: '2-digit' }),
- })),
- },
- });
- newEdges.push({
- id: 'e-filings',
- source: 'company',
- target: 'filings',
- type: 'smoothstep',
- animated: true,
- style: { stroke: '#3b82f6', strokeWidth: 2 },
- markerEnd: { type: MarkerType.ArrowClosed, color: '#3b82f6' },
- });
- }
-
- // 3. Financials (Top-Center)
- if (data.financials) {
- newNodes.push({
- id: 'financials',
- type: 'data',
- position: { x: 500, y: 50 },
- data: {
- type: 'financials',
- title: 'Financial Metrics',
- items: [
- { label: 'Revenue', value: formatMoney(data.financials.revenue) },
- { label: 'Gross Profit', value: formatMoney(data.financials.gross_profit) },
- { label: 'Operating CF', value: formatMoney(data.financials.operating_cashflow) },
- { label: 'Free CF', value: formatMoney(data.financials.free_cashflow) },
- { label: 'EBITDA Margin', value: formatPercent(data.financials.ebitda_margins) },
- { label: 'Profit Margin', value: formatPercent(data.financials.profit_margins) },
- { label: 'Revenue Growth', value: formatPercent(data.financials.revenue_growth) },
- { label: 'Earnings Growth', value: formatPercent(data.financials.earnings_growth) },
- ],
- },
- });
- newEdges.push({
- id: 'e-financials',
- source: 'company',
- target: 'financials',
- type: 'smoothstep',
- animated: true,
- style: { stroke: '#10b981', strokeWidth: 2 },
- markerEnd: { type: MarkerType.ArrowClosed, color: '#10b981' },
- });
- }
-
- // 4. Balance Sheet (Top-Right)
- if (data.balance_sheet) {
- newNodes.push({
- id: 'balance',
- type: 'data',
- position: { x: 850, y: 80 },
- data: {
- type: 'balance',
- title: 'Balance Sheet',
- items: [
- { label: 'Total Assets', value: formatMoney(data.balance_sheet.total_assets) },
- { label: 'Total Liabilities', value: formatMoney(data.balance_sheet.total_liabilities) },
- { label: 'Equity', value: formatMoney(data.balance_sheet.stockholders_equity) },
- { label: 'Cash', value: formatMoney(data.balance_sheet.total_cash) },
- { label: 'Debt', value: formatMoney(data.balance_sheet.total_debt) },
- { label: 'Shares Out', value: formatNumber(data.balance_sheet.shares_outstanding) },
- ],
- },
- });
- newEdges.push({
- id: 'e-balance',
- source: 'company',
- target: 'balance',
- type: 'smoothstep',
- animated: true,
- style: { stroke: colors.accent, strokeWidth: 2 },
- markerEnd: { type: MarkerType.ArrowClosed, color: colors.accent },
- });
- }
-
- // 5. Analysts (Right)
- if (data.analysts) {
- newNodes.push({
- id: 'analysts',
- type: 'data',
- position: { x: 1100, y: 350 },
- data: {
- type: 'analysts',
- title: 'Analyst Coverage',
- items: [
- { label: 'Recommendation', value: data.analysts.recommendation.toUpperCase() },
- { label: 'Rating Score', value: data.analysts.recommendation_mean ? data.analysts.recommendation_mean.toFixed(2) : 'N/A' },
- { label: 'Target Price', value: formatMoney(data.analysts.target_price) },
- { label: 'Target High', value: formatMoney(data.analysts.target_high) },
- { label: 'Target Low', value: formatMoney(data.analysts.target_low) },
- { label: 'Analysts', value: String(data.analysts.analyst_count) },
- ],
- },
- });
- newEdges.push({
- id: 'e-analysts',
- source: 'company',
- target: 'analysts',
- type: 'smoothstep',
- animated: true,
- style: { stroke: '#8b5cf6', strokeWidth: 2 },
- markerEnd: { type: MarkerType.ArrowClosed, color: '#8b5cf6' },
- });
- }
-
- // 6. Ownership (Bottom-Right)
- if (data.ownership) {
- newNodes.push({
- id: 'ownership',
- type: 'data',
- position: { x: 850, y: 620 },
- data: {
- type: 'ownership',
- title: 'Ownership Structure',
- items: [
- { label: 'Insider %', value: `${data.ownership.insider_percent.toFixed(2)}%` },
- { label: 'Institutional %', value: `${data.ownership.institutional_percent.toFixed(2)}%` },
- { label: 'Float Shares', value: formatNumber(data.ownership.float_shares) },
- { label: 'Total Shares', value: formatNumber(data.ownership.shares_outstanding) },
- ],
- },
- });
- newEdges.push({
- id: 'e-ownership',
- source: 'company',
- target: 'ownership',
- type: 'smoothstep',
- animated: true,
- style: { stroke: '#f59e0b', strokeWidth: 2 },
- markerEnd: { type: MarkerType.ArrowClosed, color: '#f59e0b' },
- });
- }
-
- // 7. Valuation (Bottom-Center)
- if (data.valuation) {
- newNodes.push({
- id: 'valuation',
- type: 'data',
- position: { x: 450, y: 650 },
- data: {
- type: 'valuation',
- title: 'Valuation Metrics',
- items: [
- { label: 'P/E Ratio', value: data.valuation.pe_ratio.toFixed(2) },
- { label: 'Forward P/E', value: data.valuation.forward_pe.toFixed(2) },
- { label: 'Price/Book', value: data.valuation.price_to_book.toFixed(2) },
- { label: 'Enterprise Value', value: formatMoney(data.valuation.enterprise_value) },
- { label: 'EV/Revenue', value: data.valuation.enterprise_to_revenue.toFixed(2) },
- { label: 'PEG Ratio', value: data.valuation.peg_ratio.toFixed(2) },
- ],
- },
- });
- newEdges.push({
- id: 'e-valuation',
- source: 'company',
- target: 'valuation',
- type: 'smoothstep',
- animated: true,
- style: { stroke: '#ec4899', strokeWidth: 2 },
- markerEnd: { type: MarkerType.ArrowClosed, color: '#ec4899' },
- });
- }
-
- // 8. Company Info (Bottom-Left)
- newNodes.push({
- id: 'info',
- type: 'data',
- position: { x: 100, y: 620 },
- data: {
- type: 'info',
- title: 'Company Information',
- items: [
- { label: 'Exchange', value: data.company.exchange },
- { label: 'Sector', value: data.company.sector },
- { label: 'Industry', value: data.company.industry },
- { label: 'Employees', value: data.company.employees ? data.company.employees.toLocaleString() : 'N/A' },
- { label: 'SIC Code', value: data.company.sic },
- ],
- },
- });
- newEdges.push({
- id: 'e-info',
- source: 'company',
- target: 'info',
- type: 'smoothstep',
- animated: true,
- style: { stroke: '#14b8a6', strokeWidth: 2 },
- markerEnd: { type: MarkerType.ArrowClosed, color: '#14b8a6' },
- });
-
- // 9. Executives (Left) - if available
- if (data.executives?.length > 0) {
- newNodes.push({
- id: 'executives',
- type: 'data',
- position: { x: 50, y: 350 },
- data: {
- type: 'executives',
- title: 'Executives',
- items: data.executives.map((exec: any) => ({
- label: exec.name,
- value: exec.role,
- })),
- },
- });
- newEdges.push({
- id: 'e-executives',
- source: 'company',
- target: 'executives',
- type: 'smoothstep',
- animated: true,
- style: { stroke: '#10b981', strokeWidth: 2 },
- markerEnd: { type: MarkerType.ArrowClosed, color: '#10b981' },
- });
- }
-
- console.log('[UI] Generated nodes:', newNodes.length);
- console.log('[UI] Generated edges:', newEdges.length);
-
- setNodes(newNodes);
- setEdges(newEdges);
- };
-
- const handleSearch = async (e: React.FormEvent) => {
- e.preventDefault();
- if (!searchQuery.trim()) return;
-
- const ticker = searchQuery.toUpperCase().trim();
- setSelectedSymbol(ticker);
- await fetchRelationshipData(ticker);
- };
-
- return (
- <div
- className="h-full flex flex-col"
- style={{
- fontFamily,
- fontSize: `${fontSize}px`,
- backgroundColor: colors.background,
- color: colors.text,
- }}
- >
- {/* Header */}
- <div
- className="border-b px-4 py-3 flex items-center justify-between"
- style={{ borderColor: colors.textMuted }}
- >
- <div className="flex items-center gap-3">
- <Globe className="w-5 h-5" style={{ color: colors.accent }} />
- <h2 className="text-lg font-semibold">{t('title')}</h2>
- <span className="text-xs px-2 py-1 rounded font-mono" style={{
- backgroundColor: colors.panel,
- color: colors.accent,
- border: `1px solid ${colors.textMuted}`
- }}>
- {selectedSymbol}
- </span>
- </div>
-
- <form onSubmit={handleSearch} className="relative w-96">
- <Search
- className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4"
- style={{ color: colors.textMuted }}
- />
- <input
- type="text"
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- placeholder={t('search.placeholder')}
- className="w-full pl-10 pr-4 py-2 rounded border focus:outline-none focus:ring-1"
- style={{
- backgroundColor: colors.panel,
- borderColor: colors.textMuted,
- color: colors.text,
- }}
- />
- </form>
- </div>
-
- {/* Graph */}
- <div className="flex-1" style={{ background: '#0a0a0a' }}>
- {isLoading ? (
- <div className="flex items-center justify-center h-full">
- <div className="text-center">
- <div
- className="animate-spin rounded-full h-16 w-16 border-b-2 mx-auto mb-4"
- style={{ borderColor: colors.accent }}
- />
- <p className="text-lg font-semibold" style={{ color: colors.text }}>
- {t('loading.title')} {selectedSymbol}...
- </p>
- <p className="text-sm mt-2" style={{ color: colors.textMuted }}>
- {t('loading.subtitle')}
- </p>
- </div>
- </div>
- ) : error ? (
- <div className="flex items-center justify-center h-full">
- <div className="text-center p-8 rounded border" style={{
- backgroundColor: colors.panel,
- borderColor: colors.alert
- }}>
- <p className="text-lg font-semibold mb-2" style={{ color: colors.alert }}>{t('error.title')}</p>
- <p style={{ color: colors.textMuted }}>{error}</p>
- </div>
- </div>
- ) : (
- <ReactFlow
- nodes={nodes}
- edges={edges}
- onNodesChange={onNodesChange}
- onEdgesChange={onEdgesChange}
- nodeTypes={nodeTypes}
- fitView
- minZoom={0.3}
- maxZoom={2}
- defaultViewport={{ x: 0, y: 0, zoom: 0.75 }}
- style={{ background: '#0a0a0a' }}
- >
- <Background
- gap={20}
- size={1}
- style={{ background: '#0a0a0a' }}
- color="#1a1a1a"
- />
- <Controls
- style={{
- background: '#1a1a1a',
- border: `1px solid ${colors.textMuted}`,
- borderRadius: '4px',
- }}
- />
- <MiniMap
- style={{
- background: '#1a1a1a',
- border: `1px solid ${colors.textMuted}`,
- }}
- maskColor="#0a0a0a90"
- nodeColor={(node) => {
- if (node.id === 'company') return colors.accent;
- return colors.textMuted;
- }}
- />
- </ReactFlow>
- )}
- </div>
-
- <TabFooter tabName="Relationship Map" />
- </div>
- );
-};
-
-export default RelationshipMapTab;
diff --git a/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx b/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx
index 642c25ba7..f2fd96b2b 100644
--- a/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ReportBuilderTab.tsx
@@ -1,2437 +1,4 @@
-import React, { useState, useCallback, useEffect, useRef } from 'react';
-import {
- FileText,
- Download,
- Save,
- Type,
- BarChart3,
- Table,
- Image as ImageIcon,
- Trash2,
- Copy,
- AlignLeft,
- Code,
- Minus,
- FolderOpen,
- Plus,
- Edit2,
- Move,
- Settings as SettingsIcon,
- X,
- Columns as ColumnsIcon,
- Layout,
- BookOpen,
- FileX,
- Bold,
- Italic,
- Bot,
- Send,
- User,
- Sparkles,
- ChevronDown,
- MessageSquare,
- Maximize2,
- Palette,
- Wand2,
- BookmarkPlus,
- Quote,
- List,
- ListOrdered,
- Hash,
- Stamp,
- QrCode,
- PenTool,
- AlertTriangle,
- Activity,
- TrendingUp,
- Database,
- MessageCircle,
- History,
- Search,
- Undo2,
- Redo2,
- Keyboard,
- LayoutTemplate,
-} from 'lucide-react';
-import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragEndEvent } from '@dnd-kit/core';
-import { arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable';
-import { CSS } from '@dnd-kit/utilities';
-import { reportService, ReportTemplate, ReportComponent } from '@/services/core/reportService';
-import { save, open } from '@tauri-apps/plugin-dialog';
-import { invoke } from '@tauri-apps/api/core';
-import { toast } from 'sonner';
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
-import { Button } from '@/components/ui/button';
-import { llmApiService, ChatMessage as APIMessage } from '@/services/chat/llmApi';
-import { sqliteService } from '@/services/core/sqliteService';
-import MarkdownRenderer from '../common/MarkdownRenderer';
-import { TabFooter } from '@/components/common/TabFooter';
-import { useTranslation } from 'react-i18next';
-import { AdvancedStylingPanel } from './report-builder/AdvancedStylingPanel';
-import { ExportDialog } from './report-builder/ExportDialog';
-import {
- brandKitService,
- BrandKit,
- ComponentTemplate,
- HeaderFooterTemplate,
- ParagraphStyles,
-} from '@/services/core/brandKitService';
-
-// New feature imports
-import {
- LiveDataTable,
- KPICardsRow,
- Sparkline,
- DynamicChart,
- FinancialMetricsWidget,
- ChartDataEditor,
-} from './report-builder/DataComponents';
-import {
- QuoteBox,
- ListComponent,
- FootnotesList,
- TableOfContents,
- Watermark,
- QRCodeComponent,
- SignatureBlock,
- DisclaimerSection,
- SectionHeader,
-} from './report-builder/AdditionalComponents';
-import { TemplateGallery } from './report-builder/TemplateGallery';
-import {
- CommentsPanel,
- VersionHistoryPanel,
- RevisionMode,
- useCollaboration,
-} from './report-builder/CollaborationFeatures';
-import {
- useUndoRedo,
- useAutoSave,
- useKeyboardShortcuts,
- useFullscreen,
- FindReplaceDialog,
- ShortcutsDialog,
- ProductivityToolbar,
-} from './report-builder/ProductivityFeatures';
-
-// Fincept color palette
-const FINCEPT_COLORS = {
- ORANGE: '#FFA500',
- WHITE: '#FFFFFF',
- BLACK: '#000000',
- DARK_BG: '#0a0a0a',
- PANEL_BG: '#1a1a1a',
- BORDER: '#333333',
- HOVER: '#2a2a2a',
- TEXT_PRIMARY: '#FFFFFF',
- TEXT_SECONDARY: '#999999',
-};
-
-// Sortable component wrapper
-function SortableComponent({
- component,
- isSelected,
- onClick,
- onDelete,
- onDuplicate
-}: {
- component: ReportComponent;
- isSelected: boolean;
- onClick: () => void;
- onDelete: () => void;
- onDuplicate: () => void;
-}) {
- const {
- attributes,
- listeners,
- setNodeRef,
- transform,
- transition,
- } = useSortable({ id: component.id });
-
- const style = {
- transform: CSS.Transform.toString(transform),
- transition,
- };
-
- const getComponentIcon = () => {
- switch (component.type) {
- case 'heading': return <Type size={14} />;
- case 'text': return <AlignLeft size={14} />;
- case 'chart': return <BarChart3 size={14} />;
- case 'table': return <Table size={14} />;
- case 'image': return <ImageIcon size={14} />;
- case 'code': return <Code size={14} />;
- case 'divider': return <Minus size={14} />;
- case 'quote': return <Quote size={14} />;
- case 'list': return <List size={14} />;
- case 'toc': return <Hash size={14} />;
- case 'kpi': return <TrendingUp size={14} />;
- case 'sparkline': return <Activity size={14} />;
- case 'liveTable': return <Database size={14} />;
- case 'signature': return <PenTool size={14} />;
- case 'disclaimer': return <AlertTriangle size={14} />;
- case 'qrcode': return <QrCode size={14} />;
- case 'watermark': return <Stamp size={14} />;
- default: return <FileText size={14} />;
- }
- };
-
- const getPreviewText = () => {
- if (component.content) {
- return String(component.content).substring(0, 40);
- }
- return `${component.type.charAt(0).toUpperCase() + component.type.slice(1)} component`;
- };
-
- return (
- <div
- ref={setNodeRef}
- style={style}
- className={`flex items-center justify-between p-2 mb-1 cursor-pointer transition-colors border-l-2 ${isSelected
- ? 'bg-[#2a2a2a] border-l-[#FFA500]'
- : 'bg-transparent border-l-transparent hover:bg-[#1a1a1a]'
- }`}
- onClick={onClick}
- >
- <div className="flex items-center gap-2 flex-1 min-w-0">
- <div {...attributes} {...listeners} className="cursor-move text-gray-500 hover:text-[#FFA500]">
- <Move size={14} />
- </div>
- <div className="text-[#FFA500]">
- {getComponentIcon()}
- </div>
- <span className="text-xs text-gray-400 truncate">{getPreviewText()}</span>
- </div>
- <div className="flex gap-1">
- <button
- onClick={(e) => { e.stopPropagation(); onDuplicate(); }}
- className="p-1 hover:bg-[#333333] rounded text-gray-400 hover:text-[#FFA500]"
- title="Duplicate"
- >
- <Copy size={12} />
- </button>
- <button
- onClick={(e) => { e.stopPropagation(); onDelete(); }}
- className="p-1 hover:bg-[#333333] rounded text-gray-400 hover:text-red-500"
- title="Delete"
- >
- <Trash2 size={12} />
- </button>
- </div>
- </div>
- );
-}
-
-const ReportBuilderTab: React.FC = () => {
- const { t } = useTranslation('reportBuilder');
- const { colors } = useTerminalTheme();
- const [currentTime, setCurrentTime] = useState(new Date());
- const [template, setTemplate] = useState<ReportTemplate>({
- id: `report-${Date.now()}`,
- name: 'New Financial Report',
- description: 'Professional financial research report',
- components: [],
- metadata: {
- author: '',
- company: '',
- date: new Date().toISOString().split('T')[0],
- title: 'Financial Research Report',
- },
- styles: {
- pageSize: 'A4',
- orientation: 'portrait',
- margins: '20mm',
- headerFooter: true,
- },
- });
-
- const [selectedComponent, setSelectedComponent] = useState<string | null>(null);
- const [isGenerating, setIsGenerating] = useState(false);
- const [isSaving, setIsSaving] = useState(false);
- const [showSuccessDialog, setShowSuccessDialog] = useState(false);
- const [generatedPdfPath, setGeneratedPdfPath] = useState<string>('');
- const [showExportDialog, setShowExportDialog] = useState(false);
- const [pageTheme, setPageTheme] = useState<'classic' | 'modern' | 'geometric' | 'gradient' | 'minimal' | 'pattern'>('classic');
- const [fontFamily, setFontFamily] = useState<string>('Arial, sans-serif');
- const [defaultFontSize, setDefaultFontSize] = useState<number>(11);
- const [isBold, setIsBold] = useState<boolean>(false);
- const [isItalic, setIsItalic] = useState<boolean>(false);
- const [customBgColor, setCustomBgColor] = useState<string>('#ffffff');
- const [showColorPicker, setShowColorPicker] = useState<boolean>(false);
-
- // AI Chat state
- const [aiMessages, setAiMessages] = useState<{ role: string, content: string }[]>([]);
- const [aiInput, setAiInput] = useState('');
- const [isAiTyping, setIsAiTyping] = useState(false);
- const [currentProvider, setCurrentProvider] = useState('ollama');
- const [availableModels, setAvailableModels] = useState<{ id: string, name: string, provider: string }[]>([]);
- const [streamingContent, setStreamingContent] = useState('');
- const aiMessagesEndRef = useRef<HTMLDivElement>(null);
-
- // Right panel view toggle
- const [rightPanelView, setRightPanelView] = useState<'split' | 'properties' | 'chat' | 'styling' | 'comments' | 'history'>('split');
-
- // New feature states
- const [showTemplateGallery, setShowTemplateGallery] = useState(false);
- const [showFindReplace, setShowFindReplace] = useState(false);
- const [showShortcuts, setShowShortcuts] = useState(false);
- const [revisionModeEnabled, setRevisionModeEnabled] = useState(false);
-
- // Brand Kit and Advanced Styling state
- const [activeBrandKit, setActiveBrandKit] = useState<BrandKit | null>(null);
- const [advancedStyles, setAdvancedStyles] = useState<{
- customCSS: string;
- headerTemplate: HeaderFooterTemplate | null;
- footerTemplate: HeaderFooterTemplate | null;
- paragraphStyles: ParagraphStyles | null;
- }>({
- customCSS: '',
- headerTemplate: null,
- footerTemplate: null,
- paragraphStyles: null,
- });
-
- const sensors = useSensors(
- useSensor(PointerSensor),
- useSensor(KeyboardSensor, {
- coordinateGetter: sortableKeyboardCoordinates,
- })
- );
-
- // Undo/Redo hook
- const {
- state: templateHistory,
- set: setTemplateWithHistory,
- undo,
- redo,
- canUndo,
- canRedo,
- } = useUndoRedo(template);
-
- // Auto-save hook
- const { isSaving: isAutoSaving, lastSaved, forceSave } = useAutoSave(
- template,
- async (data) => {
- try {
- await reportService.saveTemplate(data);
- console.log('Auto-saved report');
- } catch (error) {
- console.error('Auto-save failed:', error);
- }
- },
- { interval: 60000, enabled: true }
- );
-
- // Collaboration hook
- const collaboration = useCollaboration(template);
-
- // Fullscreen hook
- const { isFullscreen, toggleFullscreen, fullscreenRef } = useFullscreen();
-
- // Keyboard shortcuts
- useKeyboardShortcuts({
- 'ctrl+z': () => undo(),
- 'ctrl+y': () => redo(),
- 'ctrl+shift+z': () => redo(),
- 'ctrl+s': () => { forceSave(); toast.success('Saved'); },
- 'ctrl+f': () => setShowFindReplace(true),
- 'ctrl+shift+/': () => setShowShortcuts(true),
- 'f11': () => toggleFullscreen(),
- });
-
- // Sync template with undo/redo history
- useEffect(() => {
- if (JSON.stringify(templateHistory) !== JSON.stringify(template)) {
- setTemplate(templateHistory);
- }
- }, [templateHistory]);
-
- // Update time
- React.useEffect(() => {
- const timer = setInterval(() => setCurrentTime(new Date()), 1000);
- return () => clearInterval(timer);
- }, []);
-
- // Load active brand kit on mount
- useEffect(() => {
- const loadBrandKit = async () => {
- try {
- const kit = await brandKitService.getActiveBrandKit();
- if (kit) {
- setActiveBrandKit(kit);
- setAdvancedStyles({
- customCSS: kit.customCSS || '',
- headerTemplate: kit.headerTemplate || null,
- footerTemplate: kit.footerTemplate || null,
- paragraphStyles: kit.paragraphStyles || null,
- });
- }
- } catch (error) {
- console.error('Failed to load brand kit:', error);
- }
- };
- loadBrandKit();
- }, []);
-
- // Load available AI models
- useEffect(() => {
- const loadModels = async () => {
- try {
- const configs = await sqliteService.getLLMConfigs();
- const models = configs.map((config: any) => ({
- id: config.config_name,
- name: config.model_name || config.config_name,
- provider: config.provider
- }));
- setAvailableModels(models);
-
- // Set active provider
- const activeConfig = await sqliteService.getActiveLLMConfig();
- if (activeConfig) {
- setCurrentProvider(activeConfig.provider);
- }
- } catch (error) {
- console.error('Failed to load models:', error);
- }
- };
- loadModels();
- }, []);
-
- // Auto-scroll AI chat
- useEffect(() => {
- aiMessagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
- }, [aiMessages, streamingContent]);
-
- // Get selected component data
- const selectedComp = template.components.find(c => c.id === selectedComponent);
-
- // Add component
- const addComponent = useCallback((type: ReportComponent['type']) => {
- const newComponent: ReportComponent = {
- id: `component-${Date.now()}`,
- type,
- content: (type === 'divider' || type === 'pagebreak' || type === 'coverpage' || type === 'section' || type === 'columns') ? '' :
- type === 'heading' ? 'New Heading' :
- type === 'subheading' ? 'New Subheading' :
- type === 'text' ? 'Enter text here...' :
- type === 'quote' ? 'Enter quote text here...' :
- type === 'disclaimer' ? 'This report is for informational purposes only.' : '',
- config: {
- fontSize: type === 'heading' ? '2xl' : type === 'subheading' ? 'xl' : 'base',
- fontWeight: type === 'heading' || type === 'subheading' ? 'bold' : 'normal',
- alignment: 'left',
- ...(type === 'columns' && { columnCount: 2 }),
- ...(type === 'section' && {
- sectionTitle: 'New Section',
- sectionStyle: 'default',
- backgroundColor: '#f8f9fa',
- borderColor: '#FFA500',
- padding: '15px'
- }),
- ...(type === 'coverpage' && {
- subtitle: '',
- backgroundColor: '#0a0a0a',
- }),
- // New component configs
- ...(type === 'quote' && {
- quoteType: 'quote',
- author: '',
- }),
- ...(type === 'list' && {
- items: ['Item 1', 'Item 2', 'Item 3'],
- ordered: false,
- }),
- ...(type === 'toc' && {
- showPageNumbers: true,
- }),
- ...(type === 'kpi' && {
- kpis: [
- { label: 'Revenue', value: '$1.2M', change: 12.5, trend: 'up' },
- { label: 'Profit', value: '$340K', change: 8.2, trend: 'up' },
- { label: 'Margin', value: '28.3%', change: -2.1, trend: 'down' },
- ],
- }),
- ...(type === 'sparkline' && {
- data: [10, 25, 15, 30, 20, 35, 28],
- color: '#FFA500',
- }),
- ...(type === 'liveTable' && {
- dataSource: 'portfolio',
- columns: ['Symbol', 'Price', 'Change', 'Volume'],
- }),
- ...(type === 'dynamicChart' && {
- chartType: 'line',
- data: [
- { name: 'Jan', value: 100 },
- { name: 'Feb', value: 120 },
- { name: 'Mar', value: 115 },
- { name: 'Apr', value: 140 },
- ],
- }),
- ...(type === 'signature' && {
- name: 'John Doe',
- title: 'Analyst',
- showLine: true,
- }),
- ...(type === 'disclaimer' && {
- disclaimerType: 'standard',
- }),
- ...(type === 'qrcode' && {
- value: 'https://example.com',
- size: 100,
- label: 'Scan for more info',
- }),
- ...(type === 'watermark' && {
- text: 'CONFIDENTIAL',
- opacity: 0.1,
- rotation: -45,
- }),
- },
- ...(type === 'columns' || type === 'section' ? { children: [] } : {}),
- };
-
- const newTemplate = {
- ...template,
- components: [...template.components, newComponent],
- };
- setTemplate(newTemplate);
- setTemplateWithHistory(newTemplate);
-
- setSelectedComponent(newComponent.id);
- toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} added`);
- }, [template, setTemplateWithHistory]);
-
- // Update component
- const updateComponent = useCallback((id: string, updates: Partial<ReportComponent>) => {
- setTemplate(prev => ({
- ...prev,
- components: prev.components.map(comp =>
- comp.id === id ? { ...comp, ...updates } : comp
- ),
- }));
- }, []);
-
- // Delete component
- const deleteComponent = useCallback((id: string) => {
- setTemplate(prev => ({
- ...prev,
- components: prev.components.filter(comp => comp.id !== id),
- }));
- if (selectedComponent === id) {
- setSelectedComponent(null);
- }
- toast.success('Component deleted');
- }, [selectedComponent]);
-
- // Duplicate component
- const duplicateComponent = useCallback((id: string) => {
- const component = template.components.find(c => c.id === id);
- if (component) {
- const newComponent = {
- ...component,
- id: `component-${Date.now()}`,
- };
- setTemplate(prev => ({
- ...prev,
- components: [...prev.components, newComponent],
- }));
- toast.success('Component duplicated');
- }
- }, [template.components]);
-
- // Handle drag end
- const handleDragEnd = (event: DragEndEvent) => {
- const { active, over } = event;
- if (over && active.id !== over.id) {
- setTemplate(prev => {
- const oldIndex = prev.components.findIndex(c => c.id === active.id);
- const newIndex = prev.components.findIndex(c => c.id === over.id);
- return {
- ...prev,
- components: arrayMove(prev.components, oldIndex, newIndex),
- };
- });
- }
- };
-
- // Save template
- const saveTemplate = async () => {
- try {
- setIsSaving(true);
- const filePath = await save({
- filters: [{
- name: 'JSON',
- extensions: ['json']
- }],
- defaultPath: `${template.name}.json`
- });
-
- if (filePath) {
- await reportService.saveTemplate(template);
- toast.success('Template saved successfully');
- }
- } catch (error) {
- console.error('Error saving template:', error);
- toast.error('Failed to save template');
- } finally {
- setIsSaving(false);
- }
- };
-
- // Load template
- const loadTemplate = async () => {
- try {
- const filePath = await open({
- filters: [{
- name: 'JSON',
- extensions: ['json']
- }],
- multiple: false
- });
-
- // Load from saved templates in SQLite
- // In the future, could add file system loading
- const templates = await reportService.getTemplates();
- if (templates.length > 0) {
- // Use the first template or show a selection dialog
- setTemplate(templates[0]);
- toast.success('Template loaded successfully');
- } else {
- toast.info('No saved templates found. Use a sample template instead.');
- }
- } catch (error) {
- console.error('Error loading template:', error);
- toast.error('Failed to load template');
- }
- };
-
- // Generate PDF
- const generatePdf = async () => {
- try {
- setIsGenerating(true);
-
- const filePath = await save({
- filters: [{
- name: 'PDF',
- extensions: ['pdf']
- }],
- defaultPath: `${template.metadata.title || 'report'}.pdf`
- });
-
- if (filePath) {
- await invoke('generate_report_pdf', {
- templateJson: JSON.stringify(template),
- outputPath: filePath
- });
-
- setGeneratedPdfPath(filePath);
- setShowSuccessDialog(true);
- }
- } catch (error) {
- console.error('Error generating PDF:', error);
- toast.error('Failed to generate PDF');
- } finally {
- setIsGenerating(false);
- }
- };
-
- // Handle show in folder
- const handleShowInFolder = async () => {
- try {
- const folderPath = generatedPdfPath.substring(0, generatedPdfPath.lastIndexOf('\\'));
- await invoke('open_folder', { path: folderPath });
- setShowSuccessDialog(false);
- } catch (error) {
- console.error('Error opening folder:', error);
- toast.error('Failed to open folder');
- }
- };
-
- // Handle brand kit change
- const handleBrandKitChange = useCallback((brandKit: BrandKit) => {
- setActiveBrandKit(brandKit);
- // Apply brand kit fonts
- const bodyFont = brandKit.fonts.find(f => f.usage === 'body');
- if (bodyFont) {
- setFontFamily(bodyFont.family);
- }
- // Update advanced styles
- setAdvancedStyles({
- customCSS: brandKit.customCSS || '',
- headerTemplate: brandKit.headerTemplate || null,
- footerTemplate: brandKit.footerTemplate || null,
- paragraphStyles: brandKit.paragraphStyles || null,
- });
- toast.success(`Applied brand kit: ${brandKit.name}`);
- }, []);
-
- // Handle component template selection
- const handleComponentTemplateSelect = useCallback((template: ComponentTemplate) => {
- const newComponent: ReportComponent = {
- id: `component-${Date.now()}`,
- type: template.component.type as ReportComponent['type'],
- content: template.component.content,
- config: template.component.config,
- children: template.component.children,
- };
- setTemplate(prev => ({
- ...prev,
- components: [...prev.components, newComponent],
- }));
- setSelectedComponent(newComponent.id);
- toast.success(`Added template: ${template.name}`);
- }, []);
-
- // Handle advanced styles change
- const handleStylesChange = useCallback((styles: {
- customCSS: string;
- headerTemplate: HeaderFooterTemplate;
- footerTemplate: HeaderFooterTemplate;
- paragraphStyles: ParagraphStyles;
- }) => {
- setAdvancedStyles(styles);
- }, []);
-
- // Save component as template
- const saveAsTemplate = useCallback(async () => {
- if (!selectedComp) return;
- const templateName = prompt('Enter template name:', `${selectedComp.type} Template`);
- if (!templateName) return;
-
- const newTemplate: ComponentTemplate = {
- id: `template-${Date.now()}`,
- name: templateName,
- description: `Custom ${selectedComp.type} template`,
- category: selectedComp.type === 'section' || selectedComp.type === 'columns' ? 'layout' :
- selectedComp.type === 'image' ? 'media' :
- selectedComp.type === 'chart' || selectedComp.type === 'table' ? 'data' : 'text',
- component: {
- type: selectedComp.type,
- content: selectedComp.content,
- config: selectedComp.config,
- children: selectedComp.children,
- },
- created_at: new Date().toISOString(),
- updated_at: new Date().toISOString(),
- };
-
- try {
- await brandKitService.saveComponentTemplate(newTemplate);
- toast.success('Component saved as template');
- } catch (error) {
- toast.error('Failed to save template');
- }
- }, [selectedComp]);
-
- // Generate TOC items from headings
- const tocItems = template.components
- .filter(c => c.type === 'heading' || c.type === 'subheading')
- .map((c, idx) => ({
- id: c.id,
- title: String(c.content || `Section ${idx + 1}`),
- level: c.type === 'heading' ? 1 : 2,
- page: Math.floor(idx / 3) + 1,
- }));
-
- // AI Chat - Send message
- const handleAiSendMessage = async () => {
- if (!aiInput.trim()) return;
-
- const userMessage = { role: 'user', content: aiInput.trim() };
- setAiMessages(prev => [...prev, userMessage]);
- setAiInput('');
- setIsAiTyping(true);
- setStreamingContent('');
-
- try {
- // Get active LLM config
- const activeConfig = await sqliteService.getActiveLLMConfig();
- if (!activeConfig) {
- setAiMessages(prev => [...prev, {
- role: 'assistant',
- content: 'Please configure your LLM settings first in the Chat tab or Settings.'
- }]);
- setIsAiTyping(false);
- return;
- }
-
- // Add context about the current report
- const contextMessage = `I'm working on a report titled "${template.metadata.title}". ${template.components.length > 0
- ? `It has ${template.components.length} components including ${template.components.map(c => c.type).join(', ')}.`
- : 'It\'s empty so far.'
- } The report uses ${fontFamily} font at ${defaultFontSize}pt with ${pageTheme} theme.`;
-
- const conversationHistory: APIMessage[] = [
- { role: 'system', content: `You are a professional writing assistant helping to create financial reports. ${contextMessage}` },
- ...aiMessages.map(msg => ({
- role: msg.role as 'user' | 'assistant',
- content: msg.content
- })),
- { role: 'user', content: userMessage.content }
- ];
-
- let fullResponse = '';
-
- const response = await llmApiService.chat(
- userMessage.content,
- conversationHistory,
- (chunk, done) => {
- if (!done) {
- fullResponse += chunk;
- setStreamingContent(fullResponse);
- }
- }
- );
-
- if (response.error) {
- throw new Error(response.error);
- }
-
- fullResponse = response.content;
-
- setAiMessages(prev => [...prev, {
- role: 'assistant',
- content: fullResponse
- }]);
- setStreamingContent('');
- } catch (error) {
- console.error('AI Error:', error);
- setAiMessages(prev => [...prev, {
- role: 'assistant',
- content: 'Sorry, I encountered an error. Please try again.'
- }]);
- } finally {
- setIsAiTyping(false);
- }
- };
-
- // AI Quick actions
- const handleAiQuickAction = (action: string) => {
- const prompts: Record<string, string> = {
- improve: 'Can you help me improve the content of this report? Suggest better wording and structure.',
- expand: 'Can you help me expand on the current content with more details and insights?',
- summarize: 'Can you help me create a concise executive summary for this report?',
- grammar: 'Can you check the grammar and suggest improvements for professional writing?'
- };
-
- setAiInput(prompts[action] || '');
- };
-
- // Get theme background style
- const getThemeBackground = () => {
- switch (pageTheme) {
- case 'modern':
- return {
- background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
- backgroundSize: 'cover',
- color: '#ffffff',
- };
- case 'geometric':
- return {
- backgroundColor: '#ffffff',
- backgroundImage: `
- linear-gradient(30deg, rgba(255,165,0,0.08) 12%, transparent 12.5%, transparent 87%, rgba(255,165,0,0.08) 87.5%, rgba(255,165,0,0.08)),
- linear-gradient(150deg, rgba(255,165,0,0.08) 12%, transparent 12.5%, transparent 87%, rgba(255,165,0,0.08) 87.5%, rgba(255,165,0,0.08)),
- linear-gradient(30deg, rgba(255,165,0,0.05) 12%, transparent 12.5%, transparent 87%, rgba(255,165,0,0.05) 87.5%, rgba(255,165,0,0.05)),
- linear-gradient(150deg, rgba(255,165,0,0.05) 12%, transparent 12.5%, transparent 87%, rgba(255,165,0,0.05) 87.5%, rgba(255,165,0,0.05))
- `,
- backgroundSize: '80px 140px',
- backgroundPosition: '0 0, 0 0, 40px 70px, 40px 70px',
- color: '#000000',
- };
- case 'gradient':
- return {
- background: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%)',
- color: '#ffffff',
- };
- case 'minimal':
- return {
- backgroundColor: '#ffffff',
- backgroundImage: `
- linear-gradient(rgba(200,200,200,0.3) 1px, transparent 1px),
- linear-gradient(90deg, rgba(200,200,200,0.3) 1px, transparent 1px)
- `,
- backgroundSize: '20px 20px',
- color: '#000000',
- };
- case 'pattern':
- return {
- backgroundColor: '#ffffff',
- backgroundImage: `
- repeating-linear-gradient(45deg, transparent, transparent 10px, rgba(255,165,0,0.02) 10px, rgba(255,165,0,0.02) 20px),
- repeating-linear-gradient(-45deg, transparent, transparent 10px, rgba(255,165,0,0.02) 10px, rgba(255,165,0,0.02) 20px),
- radial-gradient(circle at 10% 10%, rgba(255,165,0,0.03) 0%, transparent 50%),
- radial-gradient(circle at 90% 90%, rgba(255,165,0,0.03) 0%, transparent 50%)
- `,
- backgroundSize: 'cover',
- color: '#000000',
- };
- case 'classic':
- default:
- return {
- backgroundColor: customBgColor,
- color: '#000000',
- };
- }
- };
-
- // Handle image upload
- const handleImageUpload = async () => {
- try {
- const selected = await open({
- multiple: false,
- filters: [{
- name: 'Images',
- extensions: ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp']
- }]
- });
-
- if (selected && typeof selected === 'string' && selectedComp) {
- updateComponent(selectedComp.id, {
- config: { ...selectedComp.config, imageUrl: selected }
- });
- toast.success('Image uploaded');
- }
- } catch (error) {
- toast.error('Failed to upload image');
- }
- };
-
- return (
- <div className="h-full flex flex-col" style={{ backgroundColor: FINCEPT_COLORS.DARK_BG, color: FINCEPT_COLORS.TEXT_PRIMARY }}>
- {/* Header */}
- <div className="flex items-center justify-between px-4 py-2 border-b" style={{ borderColor: FINCEPT_COLORS.BORDER, backgroundColor: FINCEPT_COLORS.PANEL_BG }}>
- <div className="flex items-center gap-4">
- <div className="flex items-center gap-2">
- <FileText className="w-5 h-5" style={{ color: FINCEPT_COLORS.ORANGE }} />
- <span className="font-bold text-sm" style={{ color: FINCEPT_COLORS.ORANGE }}>{t('title')}</span>
- </div>
- {/* Productivity Toolbar */}
- <div className="flex items-center gap-1 border-l border-[#333333] pl-3">
- <button
- onClick={undo}
- disabled={!canUndo}
- className="p-1.5 rounded hover:bg-[#2a2a2a] disabled:opacity-30"
- title="Undo (Ctrl+Z)"
- >
- <Undo2 size={14} />
- </button>
- <button
- onClick={redo}
- disabled={!canRedo}
- className="p-1.5 rounded hover:bg-[#2a2a2a] disabled:opacity-30"
- title="Redo (Ctrl+Y)"
- >
- <Redo2 size={14} />
- </button>
- <button
- onClick={() => setShowFindReplace(true)}
- className="p-1.5 rounded hover:bg-[#2a2a2a]"
- title="Find & Replace (Ctrl+F)"
- >
- <Search size={14} />
- </button>
- <button
- onClick={() => setShowShortcuts(true)}
- className="p-1.5 rounded hover:bg-[#2a2a2a]"
- title="Keyboard Shortcuts"
- >
- <Keyboard size={14} />
- </button>
- </div>
- {/* Auto-save status */}
- {lastSaved && (
- <span className="text-[10px]" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- {isAutoSaving ? 'Saving...' : `Saved ${lastSaved.toLocaleTimeString()}`}
- </span>
- )}
- </div>
- <div className="flex items-center gap-2">
- <button
- onClick={() => setShowTemplateGallery(true)}
- className="px-3 py-1 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <LayoutTemplate size={14} />
- Templates
- </button>
- <button
- onClick={loadTemplate}
- className="px-3 py-1 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <FolderOpen size={14} />
- {t('header.load')}
- </button>
- <button
- onClick={saveTemplate}
- disabled={isSaving}
- className="px-3 py-1 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-1 disabled:opacity-50"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <Save size={14} />
- {isSaving ? t('header.saving') : t('header.save')}
- </button>
- <button
- onClick={() => setShowExportDialog(true)}
- disabled={template.components.length === 0}
- className="px-3 py-1 text-xs rounded transition-colors flex items-center gap-1 disabled:opacity-50"
- style={{
- backgroundColor: FINCEPT_COLORS.ORANGE,
- color: FINCEPT_COLORS.BLACK,
- fontWeight: 'bold'
- }}
- >
- <Download size={14} />
- Export
- </button>
- </div>
- </div>
-
- {/* Main Content */}
- <div className="flex-1 flex overflow-hidden">
- {/* Left Panel - Components */}
- <div className="w-1/5 border-r overflow-y-auto" style={{ borderColor: FINCEPT_COLORS.BORDER, backgroundColor: FINCEPT_COLORS.PANEL_BG }}>
- <div className="p-3">
- {/* Add Components */}
- <div className="mb-4">
- <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>{t('components.title')}</h3>
- <div className="space-y-1">
- <button
- onClick={() => addComponent('heading')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <Type size={14} />
- Heading
- </button>
- <button
- onClick={() => addComponent('text')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <AlignLeft size={14} />
- Text
- </button>
- <button
- onClick={() => addComponent('chart')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <BarChart3 size={14} />
- Chart
- </button>
- <button
- onClick={() => addComponent('table')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <Table size={14} />
- Table
- </button>
- <button
- onClick={() => addComponent('image')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <ImageIcon size={14} />
- Image
- </button>
- <button
- onClick={() => addComponent('code')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <Code size={14} />
- Code Block
- </button>
- <button
- onClick={() => addComponent('divider')}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <Minus size={14} />
- Divider
- </button>
- <button
- onClick={() => addComponent('quote' as any)}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <Quote size={14} />
- Quote/Callout
- </button>
- <button
- onClick={() => addComponent('list' as any)}
- className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <List size={14} />
- List
- </button>
- </div>
- </div>
-
- {/* Data Components */}
- <div className="mb-4">
- <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>DATA</h3>
- <div className="grid grid-cols-2 gap-1">
- <button
- onClick={() => addComponent('kpi' as any)}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <TrendingUp size={14} />
- <span className="text-[9px]">KPI</span>
- </button>
- <button
- onClick={() => addComponent('sparkline' as any)}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <Activity size={14} />
- <span className="text-[9px]">Sparkline</span>
- </button>
- <button
- onClick={() => addComponent('liveTable' as any)}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <Database size={14} />
- <span className="text-[9px]">Data Table</span>
- </button>
- <button
- onClick={() => addComponent('dynamicChart' as any)}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <BarChart3 size={14} />
- <span className="text-[9px]">Chart</span>
- </button>
- </div>
- </div>
-
- {/* Document Components */}
- <div className="mb-4">
- <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>DOCUMENT</h3>
- <div className="grid grid-cols-2 gap-1">
- <button
- onClick={() => addComponent('toc' as any)}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <Hash size={14} />
- <span className="text-[9px]">TOC</span>
- </button>
- <button
- onClick={() => addComponent('signature' as any)}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <PenTool size={14} />
- <span className="text-[9px]">Signature</span>
- </button>
- <button
- onClick={() => addComponent('disclaimer' as any)}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <AlertTriangle size={14} />
- <span className="text-[9px]">Disclaimer</span>
- </button>
- <button
- onClick={() => addComponent('qrcode' as any)}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <QrCode size={14} />
- <span className="text-[9px]">QR Code</span>
- </button>
- <button
- onClick={() => addComponent('watermark' as any)}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <Stamp size={14} />
- <span className="text-[9px]">Watermark</span>
- </button>
- </div>
- </div>
-
- {/* Layout Components */}
- <div className="mb-4">
- <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>{t('layout.title')}</h3>
- <div className="grid grid-cols-2 gap-1">
- <button
- onClick={() => addComponent('section')}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <Layout size={14} />
- <span className="text-[9px]">Section</span>
- </button>
- <button
- onClick={() => addComponent('columns')}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <ColumnsIcon size={14} />
- <span className="text-[9px]">Columns</span>
- </button>
- <button
- onClick={() => addComponent('coverpage')}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <BookOpen size={14} />
- <span className="text-[9px]">Cover</span>
- </button>
- <button
- onClick={() => addComponent('pagebreak')}
- className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <FileX size={14} />
- <span className="text-[9px]">Break</span>
- </button>
- </div>
- </div>
-
- {/* Settings */}
- <div className="mb-4">
- <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>{t('settings.title')}</h3>
- <div className="space-y-2">
- <div>
- <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Page Theme
- </label>
- <select
- value={pageTheme}
- onChange={(e) => setPageTheme(e.target.value as any)}
- className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <option value="classic">Classic White</option>
- <option value="minimal">Minimal Grid</option>
- <option value="geometric">Geometric Triangles</option>
- <option value="pattern">Diagonal Pattern</option>
- <option value="modern">Modern Gradient (Dark)</option>
- <option value="gradient">Professional Gradient (Dark)</option>
- </select>
- </div>
-
- {/* Color Picker for Classic Theme */}
- {pageTheme === 'classic' && (
- <div>
- <div className="flex items-center justify-between mb-1">
- <label className="text-[9px]" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Background Color
- </label>
- <button
- onClick={() => setShowColorPicker(!showColorPicker)}
- className="text-[9px] px-2 py-1 rounded hover:bg-[#2a2a2a]"
- style={{ color: FINCEPT_COLORS.ORANGE }}
- >
- {showColorPicker ? 'Hide Picker' : 'Show Picker'}
- </button>
- </div>
-
- {/* Current Color Display */}
- <div className="flex items-center gap-2 mb-2">
- <div
- className="w-8 h-8 rounded border-2 border-[#333333]"
- style={{ backgroundColor: customBgColor }}
- />
- <input
- type="text"
- value={customBgColor}
- onChange={(e) => setCustomBgColor(e.target.value)}
- className="flex-1 px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- placeholder="#ffffff"
- />
- </div>
-
- {/* Advanced Color Picker */}
- {showColorPicker && (
- <div className="p-3 rounded bg-[#0a0a0a] border border-[#333333] space-y-3">
- {/* Main Gradient Palette */}
- <div>
- <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Color Palette
- </label>
- <div
- className="w-full h-32 rounded cursor-crosshair border border-[#333333] relative"
- style={{
- background: `
- linear-gradient(to bottom, transparent, black),
- linear-gradient(to right, white, hsl(${customBgColor.startsWith('#') ? 0 : 120}, 100%, 50%))
- `
- }}
- onClick={(e) => {
- const rect = e.currentTarget.getBoundingClientRect();
- const x = e.clientX - rect.left;
- const y = e.clientY - rect.top;
- const percentX = x / rect.width;
- const percentY = y / rect.height;
-
- // Calculate color based on position
- const hue = percentX * 360;
- const saturation = 100;
- const lightness = 100 - (percentY * 50); // Top is white (100%), bottom is mid-dark (50%)
-
- const hslToHex = (h: number, s: number, l: number) => {
- l /= 100;
- const a = s * Math.min(l, 1 - l) / 100;
- const f = (n: number) => {
- const k = (n + h / 30) % 12;
- const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
- return Math.round(255 * color).toString(16).padStart(2, '0');
- };
- return `#${f(0)}${f(8)}${f(4)}`;
- };
-
- setCustomBgColor(hslToHex(hue, saturation, lightness));
- }}
- >
- {/* Current color indicator */}
- <div
- className="absolute w-3 h-3 border-2 border-white rounded-full shadow-lg pointer-events-none"
- style={{
- left: '50%',
- top: '10%',
- transform: 'translate(-50%, -50%)'
- }}
- />
- </div>
- </div>
-
- {/* Hue Slider */}
- <div>
- <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Hue
- </label>
- <div
- className="w-full h-6 rounded cursor-pointer border border-[#333333]"
- style={{
- background: 'linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)'
- }}
- onClick={(e) => {
- const rect = e.currentTarget.getBoundingClientRect();
- const x = e.clientX - rect.left;
- const percent = x / rect.width;
- const hue = Math.round(percent * 360);
-
- const hslToHex = (h: number, s: number, l: number) => {
- l /= 100;
- const a = s * Math.min(l, 1 - l) / 100;
- const f = (n: number) => {
- const k = (n + h / 30) % 12;
- const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
- return Math.round(255 * color).toString(16).padStart(2, '0');
- };
- return `#${f(0)}${f(8)}${f(4)}`;
- };
-
- setCustomBgColor(hslToHex(hue, 100, 50));
- }}
- />
- </div>
-
- {/* Lightness Slider */}
- <div>
- <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Lightness
- </label>
- <div
- className="w-full h-6 rounded cursor-pointer border border-[#333333]"
- style={{
- background: 'linear-gradient(to right, #000000, #808080, #ffffff)'
- }}
- onClick={(e) => {
- const rect = e.currentTarget.getBoundingClientRect();
- const x = e.clientX - rect.left;
- const percent = x / rect.width;
- const lightness = Math.round(percent * 100);
-
- const hslToHex = (h: number, s: number, l: number) => {
- l /= 100;
- const a = s * Math.min(l, 1 - l) / 100;
- const f = (n: number) => {
- const k = (n + h / 30) % 12;
- const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
- return Math.round(255 * color).toString(16).padStart(2, '0');
- };
- return `#${f(0)}${f(8)}${f(4)}`;
- };
-
- setCustomBgColor(hslToHex(120, 0, lightness));
- }}
- />
- </div>
-
- {/* Preset Colors */}
- <div>
- <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Preset Colors
- </label>
- <div className="grid grid-cols-8 gap-1">
- {[
- '#ffffff', '#f8f9fa', '#e9ecef', '#dee2e6', '#ced4da', '#adb5bd', '#6c757d', '#495057',
- '#fff3cd', '#d1ecf1', '#d4edda', '#f8d7da', '#e2e3e5', '#d6d8db', '#fef5e7', '#ebf5fb',
- '#ff0000', '#ff7f00', '#ffff00', '#00ff00', '#00ffff', '#0000ff', '#8b00ff', '#ff00ff',
- '#fff5f5', '#ffe6e6', '#ffd6cc', '#ffe5cc', '#fff4cc', '#ffffcc', '#f0fff4', '#f0f9ff'
- ].map(color => (
- <button
- key={color}
- onClick={() => setCustomBgColor(color)}
- className={`w-full aspect-square rounded border-2 transition-all hover:scale-110 ${customBgColor.toLowerCase() === color.toLowerCase()
- ? 'border-[#FFA500] ring-2 ring-[#FFA500]'
- : 'border-[#333333] hover:border-[#666]'
- }`}
- style={{ backgroundColor: color }}
- title={color}
- />
- ))}
- </div>
- </div>
- </div>
- )}
- </div>
- )}
- <div>
- <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Report Title
- </label>
- <input
- type="text"
- value={template.metadata.title}
- onChange={(e) => setTemplate(prev => ({
- ...prev,
- metadata: { ...prev.metadata, title: e.target.value }
- }))}
- className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- placeholder="Enter report title..."
- />
- </div>
- <div>
- <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Author
- </label>
- <input
- type="text"
- value={template.metadata.author}
- onChange={(e) => setTemplate(prev => ({
- ...prev,
- metadata: { ...prev.metadata, author: e.target.value }
- }))}
- className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- placeholder="Enter author name..."
- />
- </div>
- <div>
- <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Company
- </label>
- <input
- type="text"
- value={template.metadata.company}
- onChange={(e) => setTemplate(prev => ({
- ...prev,
- metadata: { ...prev.metadata, company: e.target.value }
- }))}
- className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- placeholder="Enter company name..."
- />
- </div>
- <div>
- <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Font Family
- </label>
- <select
- value={fontFamily}
- onChange={(e) => setFontFamily(e.target.value)}
- className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <option value="Arial, sans-serif">Arial</option>
- <option value="'Times New Roman', serif">Times New Roman</option>
- <option value="Georgia, serif">Georgia</option>
- <option value="'Courier New', monospace">Courier New</option>
- <option value="Verdana, sans-serif">Verdana</option>
- <option value="'Trebuchet MS', sans-serif">Trebuchet MS</option>
- <option value="'Palatino Linotype', serif">Palatino</option>
- <option value="Garamond, serif">Garamond</option>
- <option value="'Comic Sans MS', cursive">Comic Sans MS</option>
- <option value="'Lucida Console', monospace">Lucida Console</option>
- </select>
- </div>
- <div>
- <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Base Font Size
- </label>
- <div className="flex items-center gap-2">
- <input
- type="range"
- min="8"
- max="16"
- value={defaultFontSize}
- onChange={(e) => setDefaultFontSize(Number(e.target.value))}
- className="flex-1"
- style={{ accentColor: FINCEPT_COLORS.ORANGE }}
- />
- <span className="text-xs" style={{ color: FINCEPT_COLORS.TEXT_PRIMARY, minWidth: '30px' }}>
- {defaultFontSize}pt
- </span>
- </div>
- </div>
- <div>
- <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Text Style
- </label>
- <div className="flex gap-2">
- <button
- onClick={() => setIsBold(!isBold)}
- className={`flex-1 px-3 py-2 rounded border transition-all ${isBold
- ? 'bg-[#FFA500] border-[#FFA500] text-black'
- : 'bg-[#0a0a0a] border-[#333333] text-gray-400 hover:border-[#FFA500]'
- }`}
- title="Toggle Bold"
- >
- <Bold size={16} className="mx-auto" />
- </button>
- <button
- onClick={() => setIsItalic(!isItalic)}
- className={`flex-1 px-3 py-2 rounded border transition-all ${isItalic
- ? 'bg-[#FFA500] border-[#FFA500] text-black'
- : 'bg-[#0a0a0a] border-[#333333] text-gray-400 hover:border-[#FFA500]'
- }`}
- title="Toggle Italic"
- >
- <Italic size={16} className="mx-auto" />
- </button>
- </div>
- </div>
- </div>
- </div>
-
- {/* Document Structure */}
- <div>
- <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>DOCUMENT STRUCTURE</h3>
- <div className="space-y-0">
- {template.components.length === 0 ? (
- <p className="text-xs text-center py-4" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- No components yet
- </p>
- ) : (
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- onDragEnd={handleDragEnd}
- >
- <SortableContext
- items={template.components.map(c => c.id)}
- strategy={verticalListSortingStrategy}
- >
- {template.components.map((component) => (
- <SortableComponent
- key={component.id}
- component={component}
- isSelected={selectedComponent === component.id}
- onClick={() => setSelectedComponent(component.id)}
- onDelete={() => deleteComponent(component.id)}
- onDuplicate={() => duplicateComponent(component.id)}
- />
- ))}
- </SortableContext>
- </DndContext>
- )}
- </div>
- </div>
- </div>
- </div>
-
- {/* Center - Canvas */}
- <div className="w-3/5 overflow-y-auto p-6" style={{ backgroundColor: '#0f0f0f' }}>
- <div
- className="mx-auto shadow-lg"
- style={{
- width: '210mm',
- minHeight: '297mm',
- padding: '20mm',
- fontFamily: fontFamily,
- fontSize: `${defaultFontSize}pt`,
- fontWeight: isBold ? 'bold' : 'normal',
- fontStyle: isItalic ? 'italic' : 'normal',
- ...(advancedStyles.paragraphStyles && {
- lineHeight: advancedStyles.paragraphStyles.lineHeight,
- letterSpacing: `${advancedStyles.paragraphStyles.letterSpacing}px`,
- wordSpacing: `${advancedStyles.paragraphStyles.wordSpacing}px`,
- }),
- ...getThemeBackground(),
- }}
- >
- {/* Header (if enabled) */}
- {advancedStyles.headerTemplate?.enabled && (
- <div
- className="mb-4 -mt-4 -mx-4 px-4"
- style={{
- backgroundColor: advancedStyles.headerTemplate.backgroundColor,
- color: advancedStyles.headerTemplate.textColor,
- fontSize: `${advancedStyles.headerTemplate.fontSize}pt`,
- minHeight: advancedStyles.headerTemplate.height,
- textAlign: advancedStyles.headerTemplate.alignment,
- borderBottom: advancedStyles.headerTemplate.borderBottom ? '1px solid #E0E0E0' : 'none',
- display: 'flex',
- alignItems: 'center',
- justifyContent: advancedStyles.headerTemplate.alignment === 'center' ? 'center' :
- advancedStyles.headerTemplate.alignment === 'right' ? 'flex-end' : 'space-between',
- padding: '8px 20px',
- }}
- >
- <span>
- {advancedStyles.headerTemplate.content
- .replace('{company}', template.metadata.company || 'Company')
- .replace('{title}', template.metadata.title || 'Report')
- .replace('{date}', template.metadata.date || new Date().toLocaleDateString())}
- </span>
- {advancedStyles.headerTemplate.showPageNumbers && (
- <span>Page 1</span>
- )}
- </div>
- )}
- {/* Document Metadata */}
- <div className="mb-8 border-b border-gray-300 pb-4">
- <h1 className="text-3xl font-bold mb-2">{template.metadata.title}</h1>
- {template.metadata.company && (
- <p className="text-lg text-gray-600">{template.metadata.company}</p>
- )}
- {template.metadata.author && (
- <p className="text-sm text-gray-500">By {template.metadata.author}</p>
- )}
- <p className="text-sm text-gray-500">{template.metadata.date}</p>
- </div>
-
- {/* Components */}
- {template.components.length === 0 ? (
- <div className="text-center py-16 text-gray-400">
- <FileText className="w-16 h-16 mx-auto mb-4 opacity-30" />
- <p className="text-lg">Your report is empty</p>
- <p className="text-sm mt-2">Add components from the left panel to start building your report</p>
- </div>
- ) : (
- <div className="space-y-4">
- {template.components.map((component) => {
- const isSelected = selectedComponent === component.id;
- return (
- <div
- key={component.id}
- onClick={() => setSelectedComponent(component.id)}
- className={`cursor-pointer transition-all ${isSelected ? 'ring-2 ring-orange-500 ring-offset-2' : 'hover:ring-1 hover:ring-gray-300'
- }`}
- >
- {/* Render component based on type */}
- {component.type === 'heading' && (
- <h2 className={`font-bold text-2xl text-${component.config.alignment || 'left'}`}>
- {component.content || 'Heading'}
- </h2>
- )}
- {component.type === 'text' && (
- <p className={`text-${component.config.alignment || 'left'}`}>
- {component.content || 'Text content'}
- </p>
- )}
- {component.type === 'chart' && (
- <div className="border border-gray-300 rounded p-8 bg-gray-50 text-center">
- <BarChart3 className="w-16 h-16 mx-auto text-gray-400" />
- <p className="text-sm text-gray-500 mt-2">Chart Placeholder</p>
- </div>
- )}
- {component.type === 'table' && (
- <div className="border border-gray-300 rounded overflow-hidden">
- <table className="w-full">
- <thead className="bg-gray-100">
- <tr>
- {(component.config.columns || ['Column 1', 'Column 2', 'Column 3']).map((col, idx) => (
- <th key={idx} className="px-4 py-2 text-left text-sm font-semibold">{col}</th>
- ))}
- </tr>
- </thead>
- <tbody>
- <tr className="border-t border-gray-200">
- {(component.config.columns || ['Column 1', 'Column 2', 'Column 3']).map((_, idx) => (
- <td key={idx} className="px-4 py-2 text-sm">Sample data</td>
- ))}
- </tr>
- </tbody>
- </table>
- </div>
- )}
- {component.type === 'image' && (
- <div className="border border-gray-300 rounded p-4 bg-gray-50">
- {component.config.imageUrl ? (
- <img
- src={`file://${component.config.imageUrl}`}
- alt="Report Image"
- className="max-w-full h-auto"
- />
- ) : (
- <div className="text-center py-8 text-gray-400">
- <ImageIcon className="w-12 h-12 mx-auto mb-2" />
- <p className="text-sm">No image selected</p>
- </div>
- )}
- </div>
- )}
- {component.type === 'code' && (
- <pre className="bg-gray-900 text-green-400 p-4 rounded overflow-x-auto text-sm font-mono">
- <code>{component.content || '// Code block'}</code>
- </pre>
- )}
- {component.type === 'divider' && (
- <hr className="border-t-2 border-gray-300 my-4" />
- )}
- {component.type === 'section' && (
- <div className="border-l-4 p-4 my-4" style={{
- borderColor: component.config.borderColor || '#FFA500',
- backgroundColor: component.config.backgroundColor || '#f8f9fa'
- }}>
- <h3 className="font-bold text-lg mb-2" style={{ color: component.config.borderColor || '#FFA500' }}>
- {component.config.sectionTitle || 'SECTION'}
- </h3>
- <p className="text-sm text-gray-600">Section content area - add child components here</p>
- </div>
- )}
- {component.type === 'columns' && (
- <div className={`grid gap-4 my-4 ${component.config.columnCount === 3 ? 'grid-cols-3' : 'grid-cols-2'}`}>
- {Array.from({ length: component.config.columnCount || 2 }).map((_, idx) => (
- <div key={idx} className="border border-gray-300 rounded p-4 bg-gray-50">
- <p className="text-sm text-gray-500 text-center">Column {idx + 1}</p>
- </div>
- ))}
- </div>
- )}
- {component.type === 'coverpage' && (
- <div className="min-h-[400px] flex flex-col items-center justify-center text-center p-12" style={{
- backgroundColor: component.config.backgroundColor || '#0a0a0a',
- color: '#FFA500'
- }}>
- <h1 className="text-4xl font-bold mb-4">{template.metadata.title}</h1>
- {component.config.subtitle && (
- <p className="text-xl mb-8">{component.config.subtitle}</p>
- )}
- <div className="text-sm text-gray-400 mt-auto">
- {template.metadata.company}<br />
- {template.metadata.author}<br />
- {template.metadata.date}
- </div>
- </div>
- )}
- {component.type === 'pagebreak' && (
- <div className="my-8 py-4 border-t-2 border-dashed border-gray-400 text-center">
- <span className="text-xs text-gray-400 bg-white px-3 py-1 rounded-full">Page Break</span>
- </div>
- )}
- {/* New component types */}
- {component.type === 'quote' && (
- <QuoteBox
- content={String(component.content || '')}
- author={component.config.author}
- type={component.config.quoteType || 'quote'}
- />
- )}
- {component.type === 'list' && (
- <ListComponent
- items={component.config.items || ['Item 1', 'Item 2']}
- ordered={component.config.ordered}
- />
- )}
- {component.type === 'toc' && (
- <TableOfContents
- items={tocItems}
- showPageNumbers={component.config.showPageNumbers}
- />
- )}
- {component.type === 'kpi' && (
- <KPICardsRow
- cards={(component.config.kpis || []).map((k: any) => ({
- title: k.label,
- value: k.value,
- change: k.change,
- }))}
- />
- )}
- {component.type === 'sparkline' && (
- <div className="inline-block">
- <Sparkline
- config={{
- data: component.config.data as number[] || [10, 20, 15, 25],
- color: component.config.color || '#FFA500',
- height: 50,
- }}
- />
- </div>
- )}
- {component.type === 'liveTable' && (
- <LiveDataTable
- config={{
- source: component.config.dataSource as 'portfolio' | 'watchlist' || 'portfolio',
- columns: component.config.columns,
- }}
- />
- )}
- {component.type === 'dynamicChart' && (
- <DynamicChart
- config={{
- type: (component.config.chartType || 'line') as 'line' | 'bar' | 'area' | 'pie',
- data: component.config.data as Array<{ name: string; value: number }> || [],
- height: 250,
- }}
- />
- )}
- {component.type === 'signature' && (
- <SignatureBlock
- name={component.config.name || 'Name'}
- title={component.config.title}
- date={template.metadata.date}
- showLine={component.config.showLine}
- />
- )}
- {component.type === 'disclaimer' && (
- <DisclaimerSection
- content={String(component.content || '')}
- type={component.config.disclaimerType || 'standard'}
- />
- )}
- {component.type === 'qrcode' && (
- <QRCodeComponent
- value={component.config.value || 'https://example.com'}
- size={component.config.size || 100}
- label={component.config.label}
- />
- )}
- {component.type === 'watermark' && (
- <Watermark
- text={component.config.text || 'CONFIDENTIAL'}
- opacity={component.config.opacity || 0.1}
- rotation={component.config.rotation || -45}
- />
- )}
- </div>
- );
- })}
- </div>
- )}
-
- {/* Footer (if enabled) */}
- {advancedStyles.footerTemplate?.enabled && (
- <div
- className="mt-8 -mb-4 -mx-4 px-4"
- style={{
- backgroundColor: advancedStyles.footerTemplate.backgroundColor,
- color: advancedStyles.footerTemplate.textColor,
- fontSize: `${advancedStyles.footerTemplate.fontSize}pt`,
- minHeight: advancedStyles.footerTemplate.height,
- textAlign: advancedStyles.footerTemplate.alignment,
- borderTop: advancedStyles.footerTemplate.borderTop ? '1px solid #E0E0E0' : 'none',
- display: 'flex',
- alignItems: 'center',
- justifyContent: advancedStyles.footerTemplate.alignment === 'center' ? 'center' :
- advancedStyles.footerTemplate.alignment === 'right' ? 'flex-end' : 'space-between',
- padding: '8px 20px',
- }}
- >
- <span>
- {advancedStyles.footerTemplate.content
- .replace('{company}', template.metadata.company || 'Company')
- .replace('{title}', template.metadata.title || 'Report')
- .replace('{date}', template.metadata.date || new Date().toLocaleDateString())}
- </span>
- {advancedStyles.footerTemplate.showPageNumbers && advancedStyles.footerTemplate.pageNumberPosition !== advancedStyles.footerTemplate.alignment && (
- <span>Page 1</span>
- )}
- </div>
- )}
- </div>
- </div>
-
- {/* Right Panel - Properties, AI Chat, and Advanced Styling */}
- <div className="w-1/5 border-l flex flex-col min-h-0" style={{ borderColor: FINCEPT_COLORS.BORDER, backgroundColor: FINCEPT_COLORS.PANEL_BG }}>
- {/* Toggle Buttons */}
- <div className="flex flex-wrap border-b" style={{ borderColor: FINCEPT_COLORS.BORDER }}>
- <button
- onClick={() => setRightPanelView('properties')}
- className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${rightPanelView === 'properties' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'
- }`}
- style={{ color: rightPanelView === 'properties' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}
- title="Component Properties"
- >
- <SettingsIcon size={12} />
- Props
- </button>
- <button
- onClick={() => setRightPanelView('styling')}
- className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${rightPanelView === 'styling' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'
- }`}
- style={{ color: rightPanelView === 'styling' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}
- title="Advanced Styling"
- >
- <Palette size={12} />
- Style
- </button>
- <button
- onClick={() => setRightPanelView('chat')}
- className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${rightPanelView === 'chat' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'
- }`}
- style={{ color: rightPanelView === 'chat' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}
- title="AI Writing Assistant"
- >
- <Bot size={12} />
- AI
- </button>
- <button
- onClick={() => setRightPanelView('comments')}
- className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${rightPanelView === 'comments' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'
- }`}
- style={{ color: rightPanelView === 'comments' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}
- title="Comments"
- >
- <MessageCircle size={12} />
- </button>
- <button
- onClick={() => setRightPanelView('history')}
- className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${rightPanelView === 'history' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'
- }`}
- style={{ color: rightPanelView === 'history' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}
- title="Version History"
- >
- <History size={12} />
- </button>
- </div>
-
- {/* Properties Section */}
- {(rightPanelView === 'properties' || rightPanelView === 'split') && (
- <div className={`${rightPanelView === 'split' ? 'flex-1 border-b' : 'flex-1'} overflow-y-auto min-h-0`} style={{ borderColor: FINCEPT_COLORS.BORDER }}>
- {selectedComp ? (
- <div className="p-4">
- <div className="flex items-center justify-between mb-4">
- <h3 className="text-sm font-bold" style={{ color: FINCEPT_COLORS.ORANGE }}>PROPERTIES</h3>
- <button
- onClick={() => setSelectedComponent(null)}
- className="p-1 hover:bg-[#2a2a2a] rounded"
- style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}
- >
- <X size={16} />
- </button>
- </div>
-
- <div className="space-y-4">
- {/* Component Type */}
- <div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Type
- </label>
- <div className="px-3 py-2 text-xs rounded bg-[#0a0a0a] capitalize">
- {selectedComp.type}
- </div>
- </div>
-
- {/* Content Editor */}
- {(selectedComp.type === 'heading' || selectedComp.type === 'text' || selectedComp.type === 'code') && (
- <div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Content
- </label>
- <textarea
- value={selectedComp.content || ''}
- onChange={(e) => updateComponent(selectedComp.id, { content: e.target.value })}
- className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- rows={selectedComp.type === 'code' ? 10 : 4}
- placeholder="Enter content..."
- />
- </div>
- )}
-
- {/* Alignment */}
- {(selectedComp.type === 'heading' || selectedComp.type === 'text') && (
- <div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Alignment
- </label>
- <div className="flex gap-2">
- {['left', 'center', 'right'].map((align) => (
- <button
- key={align}
- onClick={() => updateComponent(selectedComp.id, {
- config: { ...selectedComp.config, alignment: align as any }
- })}
- className={`flex-1 px-3 py-2 text-xs rounded transition-colors capitalize ${selectedComp.config.alignment === align
- ? 'bg-[#FFA500] text-black'
- : 'bg-[#0a0a0a] hover:bg-[#2a2a2a]'
- }`}
- >
- {align}
- </button>
- ))}
- </div>
- </div>
- )}
-
- {/* Font Size */}
- {(selectedComp.type === 'heading' || selectedComp.type === 'text') && (
- <div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Font Size
- </label>
- <select
- value={selectedComp.config.fontSize || 'base'}
- onChange={(e) => updateComponent(selectedComp.id, {
- config: { ...selectedComp.config, fontSize: e.target.value }
- })}
- className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <option value="xs">Extra Small</option>
- <option value="sm">Small</option>
- <option value="base">Base</option>
- <option value="lg">Large</option>
- <option value="xl">Extra Large</option>
- <option value="2xl">2X Large</option>
- <option value="3xl">3X Large</option>
- </select>
- </div>
- )}
-
- {/* Image Upload */}
- {selectedComp.type === 'image' && (
- <div>
- <label className="text-xs font-semibold mb-2 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Image
- </label>
- {selectedComp.config.imageUrl ? (
- <div className="space-y-2">
- <div className="text-xs text-gray-400 break-all bg-[#0a0a0a] p-2 rounded">
- {selectedComp.config.imageUrl.split('\\').pop()}
- </div>
- <div className="flex gap-2">
- <button
- onClick={handleImageUpload}
- className="flex-1 px-3 py-2 text-xs rounded bg-blue-600 hover:bg-blue-700 transition-colors"
- >
- Change Image
- </button>
- <button
- onClick={() => updateComponent(selectedComp.id, {
- config: { ...selectedComp.config, imageUrl: undefined }
- })}
- className="flex-1 px-3 py-2 text-xs rounded bg-red-600 hover:bg-red-700 transition-colors"
- >
- Remove
- </button>
- </div>
- </div>
- ) : (
- <button
- onClick={handleImageUpload}
- className="w-full px-3 py-2 text-xs rounded transition-colors flex items-center justify-center gap-2"
- style={{ backgroundColor: FINCEPT_COLORS.ORANGE, color: FINCEPT_COLORS.BLACK }}
- >
- <Plus size={14} />
- Upload Image
- </button>
- )}
- </div>
- )}
-
- {/* Table Columns */}
- {selectedComp.type === 'table' && (
- <div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Columns (comma-separated)
- </label>
- <input
- type="text"
- value={(selectedComp.config.columns || []).join(', ')}
- onChange={(e) => updateComponent(selectedComp.id, {
- config: { ...selectedComp.config, columns: e.target.value.split(',').map(s => s.trim()) }
- })}
- className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- placeholder="Column 1, Column 2, Column 3"
- />
- </div>
- )}
-
- {/* Chart Type */}
- {selectedComp.type === 'chart' && (
- <div>
- <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Chart Type
- </label>
- <select
- value={selectedComp.config.chartType || 'bar'}
- onChange={(e) => updateComponent(selectedComp.id, {
- config: { ...selectedComp.config, chartType: e.target.value }
- })}
- className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <option value="bar">Bar Chart</option>
- <option value="line">Line Chart</option>
- <option value="pie">Pie Chart</option>
- <option value="area">Area Chart</option>
- </select>
- </div>
- )}
-
- {/* Actions */}
- <div className="pt-4 border-t" style={{ borderColor: FINCEPT_COLORS.BORDER }}>
- <div className="flex gap-2 mb-2">
- <button
- onClick={() => duplicateComponent(selectedComp.id)}
- className="flex-1 px-3 py-2 text-xs rounded bg-[#0a0a0a] hover:bg-[#2a2a2a] transition-colors flex items-center justify-center gap-2"
- >
- <Copy size={14} />
- Duplicate
- </button>
- <button
- onClick={() => deleteComponent(selectedComp.id)}
- className="flex-1 px-3 py-2 text-xs rounded bg-red-600 hover:bg-red-700 transition-colors flex items-center justify-center gap-2"
- >
- <Trash2 size={14} />
- Delete
- </button>
- </div>
- <button
- onClick={saveAsTemplate}
- className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors flex items-center justify-center gap-2"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- <BookmarkPlus size={14} />
- Save as Template
- </button>
- </div>
- </div>
- </div>
- ) : (
- <div className="p-4 text-center" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- <SettingsIcon size={32} className="mx-auto mb-2 opacity-30" />
- <p className="text-xs">Select a component to edit properties</p>
- </div>
- )}
- </div>
- )}
-
- {/* AI Writing Assistant Section */}
- {(rightPanelView === 'chat' || rightPanelView === 'split') && (
- <div className={`${rightPanelView === 'split' ? 'flex-1' : 'flex-1'} flex flex-col min-h-0`} style={{ backgroundColor: FINCEPT_COLORS.PANEL_BG }}>
- {/* AI Assistant Header */}
- <div className="p-4 border-b border-[#333333] flex-shrink-0">
- <div className="flex items-center justify-between mb-3">
- <div className="flex items-center gap-2">
- <Bot size={18} style={{ color: FINCEPT_COLORS.ORANGE }} />
- <h3 className="text-sm font-bold" style={{ color: FINCEPT_COLORS.ORANGE }}>
- AI WRITING ASSISTANT
- </h3>
- </div>
- <Sparkles size={16} style={{ color: FINCEPT_COLORS.ORANGE }} />
- </div>
-
- {/* Model Selector */}
- <div className="mb-3">
- <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- AI Model
- </label>
- <select
- value={currentProvider}
- onChange={(e) => setCurrentProvider(e.target.value)}
- className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- {availableModels.map(model => (
- <option key={model.id} value={model.provider}>
- {model.name} ({model.provider})
- </option>
- ))}
- {availableModels.length === 0 && (
- <option value="ollama">Configure in Settings</option>
- )}
- </select>
- </div>
-
- {/* Quick Actions */}
- <div className="grid grid-cols-2 gap-1">
- <button
- onClick={() => handleAiQuickAction('improve')}
- className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- ✨ Improve
- </button>
- <button
- onClick={() => handleAiQuickAction('expand')}
- className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- 📝 Expand
- </button>
- <button
- onClick={() => handleAiQuickAction('summarize')}
- className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- 📋 Summary
- </button>
- <button
- onClick={() => handleAiQuickAction('grammar')}
- className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- >
- [OK] Grammar
- </button>
- </div>
- </div>
-
- {/* AI Chat Messages */}
- <div className="flex-1 overflow-y-auto p-4 space-y-3 min-h-0">
- {aiMessages.length === 0 && (
- <div className="text-center py-8">
- <Bot size={32} className="mx-auto mb-3" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }} />
- <p className="text-xs" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Ask me to help you write better reports!
- </p>
- <p className="text-[9px] mt-2" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- Try: "Help me write an introduction"
- </p>
- </div>
- )}
-
- {aiMessages.map((msg, idx) => (
- <div key={idx} className={`flex gap-2 ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
- {msg.role === 'assistant' && (
- <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center" style={{ backgroundColor: FINCEPT_COLORS.ORANGE }}>
- <Bot size={14} style={{ color: '#000' }} />
- </div>
- )}
- <div
- className={`max-w-[85%] rounded-lg p-3 ${msg.role === 'user'
- ? 'bg-[#FFA500] text-black'
- : 'bg-[#1a1a1a] border border-[#333333]'
- }`}
- >
- <div className="text-xs break-words" style={{ color: msg.role === 'user' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}>
- {msg.role === 'assistant' ? (
- <MarkdownRenderer content={msg.content} />
- ) : (
- msg.content
- )}
- </div>
- </div>
- {msg.role === 'user' && (
- <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center bg-[#333333]">
- <User size={14} style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }} />
- </div>
- )}
- </div>
- ))}
-
- {isAiTyping && streamingContent && (
- <div className="flex gap-2 justify-start">
- <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center" style={{ backgroundColor: FINCEPT_COLORS.ORANGE }}>
- <Bot size={14} style={{ color: '#000' }} />
- </div>
- <div className="max-w-[85%] rounded-lg p-3 bg-[#1a1a1a] border border-[#333333]">
- <div className="text-xs break-words" style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}>
- <MarkdownRenderer content={streamingContent} />
- </div>
- </div>
- </div>
- )}
-
- {isAiTyping && !streamingContent && (
- <div className="flex gap-2 justify-start">
- <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center" style={{ backgroundColor: FINCEPT_COLORS.ORANGE }}>
- <Bot size={14} style={{ color: '#000' }} />
- </div>
- <div className="max-w-[85%] rounded-lg p-3 bg-[#1a1a1a] border border-[#333333]">
- <div className="text-xs flex gap-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
- <span className="animate-bounce">●</span>
- <span className="animate-bounce delay-100">●</span>
- <span className="animate-bounce delay-200">●</span>
- </div>
- </div>
- </div>
- )}
-
- <div ref={aiMessagesEndRef} />
- </div>
-
- {/* AI Input */}
- <div className="p-4 border-t border-[#333333] flex-shrink-0">
- <div className="flex gap-2">
- <input
- type="text"
- value={aiInput}
- onChange={(e) => setAiInput(e.target.value)}
- onKeyPress={(e) => e.key === 'Enter' && handleAiSendMessage()}
- placeholder="Ask AI to help with your report..."
- className="flex-1 px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
- style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
- disabled={isAiTyping}
- />
- <button
- onClick={handleAiSendMessage}
- disabled={isAiTyping || !aiInput.trim()}
- className="px-3 py-2 rounded transition-all disabled:opacity-50 disabled:cursor-not-allowed"
- style={{
- backgroundColor: FINCEPT_COLORS.ORANGE,
- color: '#000'
- }}
- >
- <Send size={16} />
- </button>
- </div>
- </div>
- </div>
- )}
-
- {/* Advanced Styling Panel */}
- {rightPanelView === 'styling' && (
- <div className="flex-1 overflow-hidden">
- <AdvancedStylingPanel
- onBrandKitChange={handleBrandKitChange}
- onComponentTemplateSelect={handleComponentTemplateSelect}
- onStylesChange={handleStylesChange}
- />
- </div>
- )}
-
- {/* Comments Panel */}
- {rightPanelView === 'comments' && (
- <div className="flex-1 overflow-hidden">
- <CommentsPanel
- comments={collaboration.comments}
- onAddComment={(componentId: string, content: string) =>
- collaboration.addComment(componentId, content)
- }
- onResolveComment={collaboration.resolveComment}
- onDeleteComment={collaboration.deleteComment}
- onReplyComment={collaboration.replyToComment}
- selectedComponentId={selectedComponent}
- />
- </div>
- )}
-
- {/* Version History Panel */}
- {rightPanelView === 'history' && (
- <div className="flex-1 overflow-hidden">
- <VersionHistoryPanel
- history={collaboration.versionHistory}
- onPreview={(entry) => {
- toast.info(`Previewing version: ${entry.description}`);
- }}
- onRestore={(entry) => {
- if (entry.template) {
- setTemplate(entry.template);
- setTemplateWithHistory(entry.template);
- toast.success(`Restored version: ${entry.description}`);
- }
- }}
- />
- </div>
- )}
- </div>
- </div>
-
- {/* Success Dialog */}
- <Dialog open={showSuccessDialog} onOpenChange={setShowSuccessDialog}>
- <DialogContent className="bg-[#1a1a1a] border-[#333333]">
- <DialogHeader>
- <DialogTitle className="text-[#FFA500]">PDF Generated Successfully!</DialogTitle>
- <DialogDescription className="text-gray-400">
- Your report has been generated and saved.
- </DialogDescription>
- </DialogHeader>
- <div className="py-4">
- <p className="text-sm text-gray-300 mb-2">File saved to:</p>
- <p className="text-xs text-gray-500 break-all bg-[#0a0a0a] p-2 rounded border border-[#333333]">
- {generatedPdfPath}
- </p>
- </div>
- <DialogFooter>
- <Button
- variant="outline"
- onClick={() => setShowSuccessDialog(false)}
- className="bg-transparent border-[#333333] text-white hover:bg-[#2a2a2a]"
- >
- Close
- </Button>
- <Button
- onClick={handleShowInFolder}
- className="bg-[#FFA500] text-black hover:bg-[#ff8c00]"
- >
- <FolderOpen className="w-4 h-4 mr-2" />
- Show in Folder
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
-
- {/* Export Dialog */}
- <ExportDialog
- open={showExportDialog}
- onClose={() => setShowExportDialog(false)}
- template={template}
- brandKit={activeBrandKit}
- />
-
- {/* Template Gallery Dialog */}
- <TemplateGallery
- open={showTemplateGallery}
- onClose={() => setShowTemplateGallery(false)}
- onSelectTemplate={(t) => {
- setTemplate(t);
- setTemplateWithHistory(t);
- toast.success(`Applied template: ${t.name}`);
- }}
- currentTemplate={template}
- />
-
- {/* Find & Replace Dialog */}
- <FindReplaceDialog
- open={showFindReplace}
- onClose={() => setShowFindReplace(false)}
- onReplace={(componentId, oldText, newText) => {
- updateComponent(componentId, { content: newText });
- }}
- components={template.components}
- />
-
- {/* Keyboard Shortcuts Dialog */}
- <ShortcutsDialog
- open={showShortcuts}
- onClose={() => setShowShortcuts(false)}
- />
-
- <TabFooter
- tabName="REPORT BUILDER"
- leftInfo={[
- { label: `Components: ${template.components.length}`, color: FINCEPT_COLORS.TEXT_PRIMARY },
- { label: `Theme: ${pageTheme.charAt(0).toUpperCase() + pageTheme.slice(1)}`, color: FINCEPT_COLORS.TEXT_PRIMARY },
- ...(activeBrandKit ? [{ label: `Brand: ${activeBrandKit.name}`, color: FINCEPT_COLORS.ORANGE }] : []),
- ]}
- statusInfo={`${currentTime.toLocaleTimeString()} | Multi-format Export`}
- backgroundColor={FINCEPT_COLORS.PANEL_BG}
- borderColor={FINCEPT_COLORS.ORANGE}
- />
- </div>
- );
-};
-
-export default ReportBuilderTab;
+// Re-export from the refactored report-builder folder
+// This file maintains backward compatibility with existing imports
+export { default } from './report-builder';
+export * from './report-builder';
diff --git a/fincept-terminal-desktop/src/components/tabs/ScreenerTab.tsx b/fincept-terminal-desktop/src/components/tabs/ScreenerTab.tsx
deleted file mode 100644
index 61e467521..000000000
--- a/fincept-terminal-desktop/src/components/tabs/ScreenerTab.tsx
+++ /dev/null
@@ -1,1418 +0,0 @@
-import { useTerminalTheme } from '@/contexts/ThemeContext';
-import React, { useState, useEffect, useMemo } from 'react';
-import { Search, Download, TrendingUp, BarChart3, Loader2, AlertCircle, FolderTree, X, Plus, ArrowLeft, ChevronRight } from 'lucide-react';
-import { LineChart, Line, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
-import { sqliteService } from '@/services/core/sqliteService';
-import { invoke } from '@tauri-apps/api/core';
-import { TabFooter } from '@/components/common/TabFooter';
-import { useTranslation } from 'react-i18next';
-
-interface SeriesData {
- date: string;
- value: number;
-}
-
-interface FREDSeries {
- series_id: string;
- title: string;
- units: string;
- frequency: string;
- seasonal_adjustment: string;
- last_updated: string;
- observations: SeriesData[];
- observation_count: number;
-}
-
-interface SearchResult {
- id: string;
- title: string;
- frequency: string;
- units: string;
- seasonal_adjustment: string;
- last_updated: string;
- popularity: number;
-}
-
-interface Category {
- id: number;
- name: string;
- parent_id: number;
-}
-
-const POPULAR_SERIES = [
- { id: 'GDP', name: 'Gross Domestic Product', cat: 'Economic' },
- { id: 'UNRATE', name: 'Unemployment Rate', cat: 'Labor' },
- { id: 'CPIAUCSL', name: 'Consumer Price Index', cat: 'Inflation' },
- { id: 'FEDFUNDS', name: 'Federal Funds Rate', cat: 'Interest Rates' },
- { id: 'DGS10', name: '10-Year Treasury Rate', cat: 'Bonds' },
- { id: 'DEXUSEU', name: 'USD/EUR Exchange Rate', cat: 'Forex' },
- { id: 'DCOILWTICO', name: 'WTI Crude Oil Price', cat: 'Commodities' },
- { id: 'GOLDAMGBD228NLBM', name: 'Gold Price', cat: 'Commodities' }
-];
-
-const POPULAR_CATEGORIES = [
- { id: 32991, name: '💰 Money, Banking, & Finance', desc: 'Money supply, interest rates, banking data' },
- { id: 10, name: '📊 Population, Employment, Labor', desc: 'Employment, unemployment, labor statistics' },
- { id: 32455, name: '💵 Prices', desc: 'Inflation, CPI, PPI, commodity prices' },
- { id: 1, name: '🏭 Production & Business', desc: 'Industrial production, capacity utilization' },
- { id: 32263, name: '🌍 International Data', desc: 'Trade, exchange rates, foreign markets' },
- { id: 33060, name: '🏛️ U.S. Regional Data', desc: 'State and metro area statistics' },
-];
-
-export default function ScreenerTab() {
- const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
- const { t } = useTranslation('screener');
- const [seriesIds, setSeriesIds] = useState('GDP');
- const [startDate, setStartDate] = useState('2000-01-01');
- const [endDate, setEndDate] = useState(new Date().toISOString().split('T')[0]);
- const [data, setData] = useState<FREDSeries[]>([]);
- const [loading, setLoading] = useState(false);
- const [loadingMessage, setLoadingMessage] = useState('');
- const [error, setError] = useState<string | null>(null);
- const [chartType, setChartType] = useState<'line' | 'area'>('line');
- const [apiKeyConfigured, setApiKeyConfigured] = useState<boolean>(false);
-
- // Series browser modal state
- const [showBrowser, setShowBrowser] = useState(false);
- const [searchQuery, setSearchQuery] = useState('');
- const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
- const [searchLoading, setSearchLoading] = useState(false);
- const [categories, setCategories] = useState<Category[]>([]);
- const [currentCategory, setCurrentCategory] = useState<number>(0);
- const [categoryPath, setCategoryPath] = useState<{ id: number, name: string }[]>([{ id: 0, name: 'All Categories' }]);
- const [categoryLoading, setCategoryLoading] = useState(false);
- const [categorySeriesResults, setCategorySeriesResults] = useState<SearchResult[]>([]);
- const [categorySeriesLoading, setCategorySeriesLoading] = useState(false);
- const [normalizeData, setNormalizeData] = useState(false);
-
- useEffect(() => {
- checkApiKey();
- // Auto-load GDP data on mount
- const autoLoadData = async () => {
- const apiKey = await sqliteService.getApiKey('FRED');
- if (apiKey) {
- fetchData();
- }
- };
- autoLoadData();
- }, []);
-
- const checkApiKey = async () => {
- try {
- const apiKey = await sqliteService.getApiKey('FRED');
- console.log('[ScreenerTab] FRED API key check:', apiKey ? `Found (length: ${apiKey.length})` : 'Not found');
- setApiKeyConfigured(!!apiKey);
-
- // Also check all API keys for debugging
- const allKeys = await sqliteService.getAllApiKeys();
- console.log('[ScreenerTab] All configured API keys:', Object.keys(allKeys));
- } catch (error) {
- console.error('[ScreenerTab] Failed to check FRED API key:', error);
- setApiKeyConfigured(false);
- }
- };
-
- // Search series
- const searchSeries = async (query: string) => {
- if (!query.trim()) {
- setSearchResults([]);
- return;
- }
-
- setSearchLoading(true);
- try {
- const apiKey = await sqliteService.getApiKey('FRED');
- if (!apiKey) return;
-
- const result = await invoke<string>('execute_python_script', {
- scriptName: 'fred_data.py',
- args: ['search', query, '50'],
- env: { FRED_API_KEY: apiKey }
- });
-
- const parsed = JSON.parse(result);
- if (!parsed.error && parsed.series) {
- setSearchResults(parsed.series);
- } else {
- setSearchResults([]);
- }
- } catch (err) {
- setSearchResults([]);
- } finally {
- setSearchLoading(false);
- }
- };
-
- // Load categories
- const loadCategories = async (categoryId: number = 0) => {
- setCategoryLoading(true);
- try {
- const apiKey = await sqliteService.getApiKey('FRED');
- if (!apiKey) return;
-
- const result = await invoke<string>('execute_python_script', {
- scriptName: 'fred_data.py',
- args: ['categories', categoryId.toString()],
- env: { FRED_API_KEY: apiKey }
- });
-
- const parsed = JSON.parse(result);
- if (!parsed.error && parsed.categories) {
- setCategories(parsed.categories);
- } else {
- setCategories([]);
- }
- } catch (err) {
- setCategories([]);
- } finally {
- setCategoryLoading(false);
- }
- };
-
- // Load series in a category
- const loadCategorySeries = async (categoryId: number) => {
- setCategorySeriesLoading(true);
- try {
- const apiKey = await sqliteService.getApiKey('FRED');
- if (!apiKey) {
- setCategorySeriesLoading(false);
- return;
- }
-
- const result = await invoke<string>('execute_python_script', {
- scriptName: 'fred_data.py',
- args: ['category_series', categoryId.toString(), '50'],
- env: { FRED_API_KEY: apiKey }
- });
-
- const parsed = JSON.parse(result);
- if (!parsed.error && parsed.series) {
- setCategorySeriesResults(parsed.series);
- } else {
- setCategorySeriesResults([]);
- }
- } catch (err) {
- setCategorySeriesResults([]);
- } finally {
- setCategorySeriesLoading(false);
- }
- };
-
- // Navigate to category
- const navigateToCategory = async (cat: { id: number, name: string }) => {
- setCurrentCategory(cat.id);
- setCategoryPath([...categoryPath, cat]);
- setSearchQuery('');
- setSearchResults([]);
- setCategorySeriesResults([]);
-
- // Load both subcategories and series
- await Promise.all([
- loadCategories(cat.id),
- loadCategorySeries(cat.id)
- ]);
- };
-
- // Navigate back
- const navigateBack = () => {
- if (categoryPath.length > 1) {
- const newPath = categoryPath.slice(0, -1);
- setCategoryPath(newPath);
- const parentId = newPath[newPath.length - 1].id;
- setCurrentCategory(parentId);
- loadCategories(parentId);
- }
- };
-
- // Open browser modal
- const openBrowser = () => {
- setShowBrowser(true);
- if (categories.length === 0) {
- loadCategories(0);
- }
- };
-
- // Add series from browser
- const addSeriesFromBrowser = async (id: string) => {
- if (!getCurrentSeriesIds().includes(id)) {
- const newIds = seriesIds ? `${seriesIds},${id}` : id;
- setSeriesIds(newIds);
-
- // Auto-fetch data after adding series
- setTimeout(async () => {
- try {
- setLoading(true);
- setError(null);
- setLoadingMessage('Initializing...');
-
- const apiKey = await sqliteService.getApiKey('FRED');
- if (!apiKey) {
- setError('FRED API key not configured. Please add it in Settings.');
- setLoading(false);
- setLoadingMessage('');
- return;
- }
-
- const ids = [...new Set(newIds.split(',').map(s => s.trim()).filter(Boolean))];
-
- if (ids.length === 0) {
- setError('Please enter at least one series ID');
- setLoading(false);
- setLoadingMessage('');
- return;
- }
-
- setLoadingMessage(`Fetching ${ids.length} series from FRED API...`);
- const args = ['multiple', ...ids, startDate, endDate];
-
- const result = await invoke<string>('execute_python_script', {
- scriptName: 'fred_data.py',
- args,
- env: { FRED_API_KEY: apiKey }
- });
-
- setLoadingMessage('Processing data...');
- const parsed = JSON.parse(result);
-
- if (parsed.error) {
- setError(`API Error: ${parsed.error}`);
- } else if (Array.isArray(parsed)) {
- const errorSeries = parsed.find(s => s.error);
- if (errorSeries) {
- setError(`Failed to fetch ${errorSeries.series_id}: ${errorSeries.error}`);
- } else {
- setData(parsed);
- setError(null);
- setLoadingMessage(`Successfully loaded ${parsed.length} series!`);
- setTimeout(() => setLoadingMessage(''), 2000);
- }
- } else {
- setData(parsed);
- }
- } catch (err: any) {
- setError(err.message || 'Failed to fetch data');
- } finally {
- setLoading(false);
- }
- }, 100);
- }
- };
-
- const fetchData = async () => {
- setLoading(true);
- setError(null);
- setLoadingMessage('Initializing...');
-
- try {
- const apiKey = await sqliteService.getApiKey('FRED');
- if (!apiKey) {
- setError('FRED API key not configured. Please add it in Settings > Credentials.');
- setApiKeyConfigured(false);
- setLoading(false);
- setLoadingMessage('');
- return;
- }
-
- // Remove duplicates and trim
- const ids = [...new Set(seriesIds.split(',').map(s => s.trim()).filter(Boolean))];
-
- if (ids.length === 0) {
- setError('Please enter at least one series ID');
- setLoading(false);
- setLoadingMessage('');
- return;
- }
-
- setLoadingMessage(`Fetching ${ids.length} series from FRED API...`);
- const args = ['multiple', ...ids, startDate, endDate];
-
- const result = await invoke<string>('execute_python_script', {
- scriptName: 'fred_data.py',
- args,
- env: { FRED_API_KEY: apiKey }
- });
-
- setLoadingMessage('Processing data...');
- const parsed = JSON.parse(result);
-
- if (parsed.error) {
- setError(`API Error: ${parsed.error}`);
- } else if (Array.isArray(parsed)) {
- // Check if any series has an error
- const errorSeries = parsed.find(s => s.error);
- if (errorSeries) {
- setError(`Failed to fetch ${errorSeries.series_id}: ${errorSeries.error}`);
- } else {
- setData(parsed);
- setError(null);
- setLoadingMessage(`Successfully loaded ${parsed.length} series!`);
- setTimeout(() => setLoadingMessage(''), 2000);
- }
- } else {
- setData(parsed);
- }
- } catch (err: any) {
- setError(err.message || 'Failed to fetch data');
- } finally {
- setLoading(false);
- }
- };
-
- // Helper to get current series IDs as array
- const getCurrentSeriesIds = () => {
- return seriesIds.split(',').map(s => s.trim()).filter(Boolean);
- };
-
- const addPopularSeries = (id: string) => {
- const currentIds = getCurrentSeriesIds();
- if (currentIds.includes(id)) {
- // Remove if already added
- const newIds = currentIds.filter(sid => sid !== id);
- setSeriesIds(newIds.join(','));
- } else {
- // Add if not present
- setSeriesIds(prev => prev ? `${prev},${id}` : id);
- }
- };
-
- const prepareChartData = () => {
- if (data.length === 0) return [];
-
- const allDates = new Set<string>();
- data.forEach(series => {
- series.observations.forEach(obs => allDates.add(obs.date));
- });
-
- const sortedDates = Array.from(allDates).sort();
-
- // First pass: collect all values
- const rawData = sortedDates.map(date => {
- const point: any = { date };
- data.forEach(series => {
- const obs = series.observations.find(o => o.date === date);
- point[series.series_id] = obs?.value || null;
- });
- return point;
- });
-
- // If normalization is enabled, normalize each series to 0-100 scale
- if (normalizeData && data.length > 1) {
- // Find min/max for each series
- const seriesStats: Record<string, { min: number, max: number }> = {};
-
- data.forEach(series => {
- const values = series.observations.map(obs => parseFloat(obs.value.toString())).filter(v => !isNaN(v) && v !== null);
- if (values.length > 0) {
- seriesStats[series.series_id] = {
- min: Math.min(...values),
- max: Math.max(...values)
- };
- }
- });
-
- // Normalize the data
- return rawData.map(point => {
- const normalizedPoint: any = { date: point.date };
- data.forEach(series => {
- const value = point[series.series_id];
- if (value !== null && value !== undefined && seriesStats[series.series_id]) {
- const { min, max } = seriesStats[series.series_id];
- const range = max - min;
- normalizedPoint[series.series_id] = range > 0 ? ((value - min) / range) * 100 : 50;
- } else {
- normalizedPoint[series.series_id] = null;
- }
- });
- return normalizedPoint;
- });
- }
-
- return rawData;
- };
-
- const exportToCSV = () => {
- const chartData = prepareChartData();
- const headers = ['Date', ...data.map(s => s.series_id)].join(',');
- const rows = chartData.map(row => {
- return [row.date, ...data.map(s => row[s.series_id] || '')].join(',');
- });
- const csv = [headers, ...rows].join('\n');
-
- const blob = new Blob([csv], { type: 'text/csv' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = `fred_data_${new Date().toISOString()}.csv`;
- a.click();
- };
-
- // Memoize current series IDs set for performance
- const currentSeriesIdsSet = useMemo(() => {
- return new Set(getCurrentSeriesIds());
- }, [seriesIds]);
-
- // Use effect for search debounce
- useEffect(() => {
- const timer = setTimeout(() => {
- if (searchQuery && showBrowser) {
- searchSeries(searchQuery);
- }
- }, 500);
- return () => clearTimeout(timer);
- }, [searchQuery, showBrowser]);
-
- return (
- <div style={{
- width: '100%',
- height: '100%',
- display: 'flex',
- flexDirection: 'column',
- backgroundColor: colors.background,
- color: colors.text,
- fontFamily: fontFamily,
- fontWeight: fontWeight,
- fontStyle: fontStyle,
- overflow: 'hidden',
- fontSize: fontSize.body
- }}>
- <style>{`
- *::-webkit-scrollbar { width: 6px; height: 6px; }
- *::-webkit-scrollbar-track { background: ${colors.background}; }
- *::-webkit-scrollbar-thumb { background: ${colors.panel}; border-radius: 3px; }
- *::-webkit-scrollbar-thumb:hover { background: ${colors.textMuted}; }
- `}</style>
-
- {/* Series Browser Modal */}
- {showBrowser && (
- <div style={{
- position: 'fixed',
- top: 0,
- left: 0,
- right: 0,
- bottom: 0,
- background: 'rgba(0,0,0,0.95)',
- zIndex: 1000,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- padding: '20px',
- backdropFilter: 'blur(4px)'
- }}>
- <div style={{
- background: colors.background,
- border: `1px solid ${colors.primary}`,
- borderRadius: '4px',
- width: '90%',
- maxWidth: '1200px',
- height: '85vh',
- display: 'flex',
- flexDirection: 'column',
- overflow: 'hidden',
- boxShadow: `0 8px 32px ${colors.primary}33`
- }}>
- {/* Modal Header */}
- <div style={{
- borderBottom: `1px solid ${colors.primary}`,
- padding: '12px 20px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- background: colors.panel
- }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
- <FolderTree size={16} color={colors.primary} />
- <span style={{ color: colors.primary, fontSize: fontSize.heading, fontWeight: 'bold', letterSpacing: '0.5px' }}>
- {t('title')}
- </span>
- </div>
- <button
- onClick={() => setShowBrowser(false)}
- style={{
- background: 'transparent',
- border: 'none',
- color: colors.textMuted,
- cursor: 'pointer',
- padding: '4px',
- display: 'flex',
- alignItems: 'center'
- }}
- >
- <X size={18} />
- </button>
- </div>
-
- {/* Search Bar */}
- <div style={{ padding: '12px 20px', borderBottom: `1px solid ${colors.panel}` }}>
- <div style={{ position: 'relative' }}>
- <Search size={14} color={colors.textMuted} style={{ position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)' }} />
- <input
- type="text"
- placeholder="Search FRED series by keyword (e.g., 'unemployment', 'inflation', 'GDP')..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- style={{
- width: '100%',
- background: colors.panel,
- border: `1px solid ${colors.textMuted}33`,
- color: colors.text,
- padding: '10px 40px 10px 40px',
- fontSize: fontSize.small,
- borderRadius: '3px',
- outline: 'none',
- transition: 'border-color 0.2s'
- }}
- onFocus={(e) => e.target.style.borderColor = colors.primary}
- onBlur={(e) => e.target.style.borderColor = `${colors.textMuted}33`}
- />
- {searchLoading && (
- <Loader2 size={14} className="animate-spin" style={{ position: 'absolute', right: '12px', top: '50%', transform: 'translateY(-50%)', color: colors.primary }} />
- )}
- </div>
- </div>
-
- {/* Content Area */}
- <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
- {/* Left Panel - Categories or Popular */}
- {!searchQuery && (
- <div style={{
- width: '350px',
- borderRight: '1px solid #1a1a1a',
- display: 'flex',
- flexDirection: 'column',
- background: '#050505'
- }}>
- {/* Breadcrumb */}
- <div style={{
- padding: '12px 16px',
- borderBottom: '1px solid #1a1a1a',
- display: 'flex',
- alignItems: 'center',
- gap: '8px'
- }}>
- {categoryPath.length > 1 && (
- <button
- onClick={navigateBack}
- style={{
- background: 'colors.panel',
- border: '1px solid #2a2a2a',
- color: '#ea580c',
- padding: '4px 8px',
- fontSize: '10px',
- cursor: 'pointer',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
- }}
- >
- <ArrowLeft size={12} />
- BACK
- </button>
- )}
- <span style={{ color: '#888', fontSize: '10px', flex: 1 }}>
- {categoryPath.map((p, i) => (
- <span key={`${p.id}-${i}`}>
- {i > 0 && ' > '}
- {p.name}
- </span>
- ))}
- </span>
- </div>
-
- {/* Popular Categories (only at root) */}
- {currentCategory === 0 && (
- <div style={{ padding: '12px', borderBottom: '1px solid #1a1a1a', maxHeight: '200px', overflowY: 'auto' }}>
- <h4 style={{ color: '#ea580c', fontSize: '10px', marginBottom: '8px', fontWeight: 'bold' }}>
- POPULAR CATEGORIES
- </h4>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
- {POPULAR_CATEGORIES.map((cat, idx) => (
- <button
- key={`pop-${cat.id}-${idx}`}
- onClick={() => navigateToCategory({ id: cat.id, name: cat.name.replace(/[^\w\s]/gi, '').trim() })}
- style={{
- background: 'colors.panel',
- border: '1px solid #2a2a2a',
- color: 'colors.text',
- padding: '6px 8px',
- fontSize: '9px',
- cursor: 'pointer',
- borderRadius: '3px',
- textAlign: 'left',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between'
- }}
- >
- <div style={{ flex: 1, minWidth: 0 }}>
- <div style={{ fontWeight: 'bold', marginBottom: '2px', fontSize: '9px' }}>{cat.name}</div>
- </div>
- <ChevronRight size={12} color="#666" />
- </button>
- ))}
- </div>
- </div>
- )}
-
- {/* Category List */}
- <div style={{ flex: 1, overflowY: 'auto', padding: '12px' }}>
- <h4 style={{ color: '#888', fontSize: '9px', marginBottom: '8px', fontWeight: 'bold' }}>
- {categoryLoading ? 'LOADING...' : `SUBCATEGORIES (${categories.length})`}
- </h4>
- {categories.length === 0 && !categoryLoading && currentCategory !== 0 && (
- <p style={{ color: '#666', fontSize: '10px' }}>No subcategories found</p>
- )}
- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
- {categories.map((cat, idx) => (
- <button
- key={`cat-${cat.id}-${idx}`}
- onClick={() => navigateToCategory(cat)}
- style={{
- background: 'colors.panel',
- border: '1px solid #2a2a2a',
- color: 'colors.text',
- padding: '8px 10px',
- fontSize: '10px',
- cursor: 'pointer',
- borderRadius: '3px',
- textAlign: 'left',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between'
- }}
- >
- <span>{cat.name}</span>
- <ChevronRight size={12} color="#666" />
- </button>
- ))}
- </div>
- </div>
- </div>
- )}
-
- {/* Right Panel - Search Results or Series in Category */}
- <div style={{ flex: 1, overflowY: 'auto', padding: '16px 20px' }}>
- {categorySeriesLoading && !searchQuery ? (
- // Loading Category Series
- <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: '16px' }}>
- <Loader2 size={32} color={colors.primary} className="animate-spin" />
- <p style={{ color: colors.textMuted, fontSize: fontSize.small }}>
- Loading series in category...
- </p>
- </div>
- ) : searchQuery ? (
- // Search Results
- <>
- <h3 style={{ color: '#ea580c', fontSize: '11px', marginBottom: '12px', fontWeight: 'bold' }}>
- SEARCH RESULTS ({searchResults.length})
- </h3>
- {searchResults.length === 0 && !searchLoading && (
- <p style={{ color: '#666', fontSize: '10px' }}>No results found</p>
- )}
- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
- {searchResults.map((result) => (
- <div
- key={result.id}
- style={{
- background: 'colors.panel',
- border: '1px solid #1a1a1a',
- borderRadius: '4px',
- padding: '12px',
- display: 'flex',
- alignItems: 'flex-start',
- justifyContent: 'space-between',
- gap: '12px'
- }}
- >
- <div style={{ flex: 1, minWidth: 0 }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
- <span style={{ color: '#ea580c', fontSize: '11px', fontWeight: 'bold', fontFamily: 'monospace' }}>
- {result.id}
- </span>
- <span style={{ color: '#666', fontSize: '9px' }}>
- Pop: {result.popularity}
- </span>
- </div>
- <p style={{ color: 'colors.text', fontSize: '10px', marginBottom: '4px' }}>
- {result.title}
- </p>
- <div style={{ display: 'flex', gap: '12px', fontSize: '9px', color: '#666' }}>
- <span>Freq: {result.frequency}</span>
- <span>Units: {result.units}</span>
- <span>Updated: {result.last_updated.split('T')[0]}</span>
- </div>
- </div>
- <button
- onClick={() => addSeriesFromBrowser(result.id)}
- disabled={currentSeriesIdsSet.has(result.id)}
- style={{
- background: currentSeriesIdsSet.has(result.id) ? '#1a3a1a' : '#ea580c',
- border: 'none',
- color: 'colors.text',
- padding: '6px 12px',
- fontSize: '10px',
- cursor: currentSeriesIdsSet.has(result.id) ? 'not-allowed' : 'pointer',
- borderRadius: '3px',
- fontWeight: 'bold',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- whiteSpace: 'nowrap',
- opacity: currentSeriesIdsSet.has(result.id) ? 0.5 : 1
- }}
- >
- <Plus size={12} />
- {currentSeriesIdsSet.has(result.id) ? 'ADDED' : 'ADD'}
- </button>
- </div>
- ))}
- </div>
- </>
- ) : categorySeriesResults.length > 0 ? (
- // Category Series Results
- <>
- <h3 style={{ color: '#ea580c', fontSize: '11px', marginBottom: '12px', fontWeight: 'bold' }}>
- SERIES IN THIS CATEGORY ({categorySeriesResults.length})
- </h3>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
- {categorySeriesResults.map((result) => (
- <div
- key={result.id}
- style={{
- background: 'colors.panel',
- border: '1px solid #1a1a1a',
- borderRadius: '4px',
- padding: '12px',
- display: 'flex',
- alignItems: 'flex-start',
- justifyContent: 'space-between',
- gap: '12px'
- }}
- >
- <div style={{ flex: 1, minWidth: 0 }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
- <span style={{ color: '#ea580c', fontSize: '11px', fontWeight: 'bold', fontFamily: 'monospace' }}>
- {result.id}
- </span>
- <span style={{ color: '#666', fontSize: '9px' }}>
- Pop: {result.popularity}
- </span>
- </div>
- <p style={{ color: 'colors.text', fontSize: '10px', marginBottom: '4px' }}>
- {result.title}
- </p>
- <div style={{ display: 'flex', gap: '12px', fontSize: '9px', color: '#666' }}>
- <span>Freq: {result.frequency}</span>
- <span>Units: {result.units}</span>
- <span>Updated: {result.last_updated.split('T')[0]}</span>
- </div>
- </div>
- <button
- onClick={() => addSeriesFromBrowser(result.id)}
- disabled={currentSeriesIdsSet.has(result.id)}
- style={{
- background: currentSeriesIdsSet.has(result.id) ? '#1a3a1a' : '#ea580c',
- border: 'none',
- color: 'colors.text',
- padding: '6px 12px',
- fontSize: '10px',
- cursor: currentSeriesIdsSet.has(result.id) ? 'not-allowed' : 'pointer',
- borderRadius: '3px',
- fontWeight: 'bold',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- whiteSpace: 'nowrap',
- opacity: currentSeriesIdsSet.has(result.id) ? 0.5 : 1
- }}
- >
- <Plus size={12} />
- {currentSeriesIdsSet.has(result.id) ? 'ADDED' : 'ADD'}
- </button>
- </div>
- ))}
- </div>
- </>
- ) : (
- // Instructions or Category Info
- <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: '16px' }}>
- <TrendingUp size={48} color="#333" />
- <div style={{ textAlign: 'center', maxWidth: '500px' }}>
- <p style={{ color: '#888', fontSize: '12px', marginBottom: '8px' }}>
- <strong>Search for any economic data series</strong>
- </p>
- <p style={{ color: '#666', fontSize: '10px', lineHeight: '1.5' }}>
- Try searching for terms like "unemployment", "inflation", "GDP", "interest rates", "housing", etc.
- Or browse through categories on the left to discover available data series.
- </p>
- </div>
- </div>
- )}
- </div>
- </div>
-
- {/* Modal Footer */}
- <div style={{
- borderTop: '1px solid #1a1a1a',
- padding: '12px 20px',
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- background: 'colors.panel'
- }}>
- <span style={{ color: '#666', fontSize: '9px' }}>
- Federal Reserve Economic Data (FRED) | 800,000+ series available
- </span>
- <button
- onClick={() => setShowBrowser(false)}
- style={{
- background: '#ea580c',
- border: 'none',
- color: 'colors.text',
- padding: '8px 16px',
- fontSize: '10px',
- cursor: 'pointer',
- borderRadius: '3px',
- fontWeight: 'bold'
- }}
- >
- DONE
- </button>
- </div>
- </div>
- </div>
- )}
-
- {/* Header */}
- <div style={{
- borderBottom: `1px solid ${colors.primary}`,
- padding: '10px 16px',
- background: colors.panel,
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- flexShrink: 0
- }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
- <BarChart3 size={16} color={colors.primary} />
- <span style={{ color: colors.primary, fontSize: fontSize.heading, fontWeight: 'bold', letterSpacing: '0.5px' }}>
- {t('header.title')}
- </span>
- </div>
- <div style={{ display: 'flex', gap: '6px' }}>
- <button
- onClick={() => setChartType(chartType === 'line' ? 'area' : 'line')}
- style={{
- background: colors.background,
- border: `1px solid ${colors.primary}33`,
- color: colors.primary,
- padding: '6px 12px',
- fontSize: fontSize.small,
- cursor: 'pointer',
- borderRadius: '3px',
- fontWeight: 'bold',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.background = colors.primary;
- e.currentTarget.style.color = colors.background;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.background = colors.background;
- e.currentTarget.style.color = colors.primary;
- }}
- >
- {chartType === 'line' ? 'AREA' : 'LINE'}
- </button>
- <button
- onClick={() => setNormalizeData(!normalizeData)}
- disabled={data.length <= 1}
- style={{
- background: normalizeData ? colors.primary : colors.background,
- border: `1px solid ${colors.primary}33`,
- color: normalizeData ? colors.background : colors.primary,
- padding: '6px 12px',
- fontSize: fontSize.small,
- cursor: data.length > 1 ? 'pointer' : 'not-allowed',
- borderRadius: '3px',
- fontWeight: 'bold',
- opacity: data.length > 1 ? 1 : 0.5,
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- if (data.length > 1 && !normalizeData) {
- e.currentTarget.style.background = colors.primary;
- e.currentTarget.style.color = colors.background;
- }
- }}
- onMouseLeave={(e) => {
- if (data.length > 1 && !normalizeData) {
- e.currentTarget.style.background = colors.background;
- e.currentTarget.style.color = colors.primary;
- }
- }}
- >
- NORMALIZE
- </button>
- <button
- onClick={exportToCSV}
- disabled={data.length === 0}
- style={{
- background: data.length > 0 ? colors.background : colors.panel,
- border: `1px solid ${data.length > 0 ? colors.success : colors.textMuted}33`,
- color: data.length > 0 ? colors.success : colors.textMuted,
- padding: '6px 12px',
- fontSize: fontSize.small,
- cursor: data.length > 0 ? 'pointer' : 'not-allowed',
- borderRadius: '3px',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- fontWeight: 'bold',
- opacity: data.length > 0 ? 1 : 0.5,
- transition: 'opacity 0.2s'
- }}
- onMouseEnter={(e) => {
- if (data.length > 0) {
- e.currentTarget.style.opacity = '0.7';
- }
- }}
- onMouseLeave={(e) => {
- if (data.length > 0) {
- e.currentTarget.style.opacity = '1';
- }
- }}
- >
- <Download size={12} />
- CSV
- </button>
- </div>
- </div>
-
- {/* API Key Warning */}
- {!apiKeyConfigured && (
- <div style={{
- background: `${colors.warning}11`,
- border: `1px solid ${colors.warning}`,
- padding: '12px 16px',
- display: 'flex',
- alignItems: 'flex-start',
- gap: '12px',
- flexShrink: 0
- }}>
- <AlertCircle size={20} color={colors.warning} style={{ flexShrink: 0, marginTop: '2px' }} />
- <div style={{ flex: 1 }}>
- <p style={{ color: colors.warning, fontSize: fontSize.body, fontWeight: 'bold', marginBottom: '6px' }}>
- {t('apiKey.required')}
- </p>
- <p style={{ color: colors.text, fontSize: fontSize.small, lineHeight: '1.5', marginBottom: '8px' }}>
- Configure your FRED API key in <strong>Settings → Credentials</strong> to access economic data.
- </p>
- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
- <p style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>
- <strong style={{ color: colors.warning }}>1.</strong> Get free API key at{' '}
- <a
- href="https://research.stlouisfed.org/useraccount/apikey"
- target="_blank"
- rel="noopener noreferrer"
- style={{ color: colors.info, textDecoration: 'underline' }}
- >
- research.stlouisfed.org
- </a>
- </p>
- <p style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>
- <strong style={{ color: colors.warning }}>2.</strong> Add to <strong>Settings → Credentials → FRED_API_KEY</strong>
- </p>
- <p style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>
- <strong style={{ color: colors.warning }}>3.</strong> Save and reload this tab
- </p>
- </div>
- </div>
- </div>
- )}
-
- {/* Query Panel */}
- <div style={{
- borderBottom: `1px solid ${colors.panel}`,
- padding: '12px 16px',
- background: colors.panel,
- flexShrink: 0
- }}>
- <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr auto', gap: '10px', marginBottom: '10px' }}>
- <div>
- <label style={{ color: colors.textMuted, fontSize: fontSize.tiny, display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
- {t('form.seriesIds')}
- </label>
- <input
- type="text"
- value={seriesIds}
- onChange={(e) => setSeriesIds(e.target.value)}
- placeholder="GDP,UNRATE,CPIAUCSL"
- style={{
- width: '100%',
- background: colors.background,
- border: `1px solid ${colors.textMuted}33`,
- color: colors.text,
- padding: '8px 10px',
- fontSize: fontSize.small,
- borderRadius: '3px',
- outline: 'none'
- }}
- onFocus={(e) => e.target.style.borderColor = colors.primary}
- onBlur={(e) => e.target.style.borderColor = `${colors.textMuted}33`}
- />
- </div>
- <div>
- <label style={{ color: colors.textMuted, fontSize: fontSize.tiny, display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
- START DATE
- </label>
- <input
- type="date"
- value={startDate}
- onChange={(e) => setStartDate(e.target.value)}
- style={{
- width: '100%',
- background: colors.background,
- border: `1px solid ${colors.textMuted}33`,
- color: colors.text,
- padding: '8px 10px',
- fontSize: fontSize.small,
- borderRadius: '3px',
- outline: 'none'
- }}
- onFocus={(e) => e.target.style.borderColor = colors.primary}
- onBlur={(e) => e.target.style.borderColor = `${colors.textMuted}33`}
- />
- </div>
- <div>
- <label style={{ color: colors.textMuted, fontSize: fontSize.tiny, display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
- END DATE
- </label>
- <input
- type="date"
- value={endDate}
- onChange={(e) => setEndDate(e.target.value)}
- style={{
- width: '100%',
- background: colors.background,
- border: `1px solid ${colors.textMuted}33`,
- color: colors.text,
- padding: '8px 10px',
- fontSize: fontSize.small,
- borderRadius: '3px',
- outline: 'none'
- }}
- onFocus={(e) => e.target.style.borderColor = colors.primary}
- onBlur={(e) => e.target.style.borderColor = `${colors.textMuted}33`}
- />
- </div>
- <button
- onClick={fetchData}
- disabled={loading}
- style={{
- background: loading ? colors.panel : colors.primary,
- border: 'none',
- color: colors.background,
- padding: '0 18px',
- fontSize: fontSize.small,
- cursor: loading ? 'not-allowed' : 'pointer',
- borderRadius: '3px',
- fontWeight: 'bold',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- alignSelf: 'end',
- opacity: loading ? 0.6 : 1,
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => !loading && (e.currentTarget.style.opacity = '0.8')}
- onMouseLeave={(e) => !loading && (e.currentTarget.style.opacity = '1')}
- >
- {loading ? <Loader2 size={12} className="animate-spin" /> : <Search size={12} />}
- {loading ? t('buttons.loading') : t('buttons.fetch')}
- </button>
- </div>
-
- {/* Popular Series Quick Add & Browse Button */}
- <div style={{ display: 'flex', alignItems: 'flex-end', gap: '10px' }}>
- <div style={{ flex: 1 }}>
- <label style={{ color: colors.textMuted, fontSize: fontSize.tiny, marginBottom: '6px', display: 'block', fontWeight: 'bold' }}>
- {t('form.quickAdd')}
- </label>
- <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
- {POPULAR_SERIES.map(series => (
- <button
- key={series.id}
- onClick={() => addPopularSeries(series.id)}
- style={{
- background: currentSeriesIdsSet.has(series.id) ? `${colors.success}22` : colors.background,
- border: `1px solid ${currentSeriesIdsSet.has(series.id) ? colors.success : colors.textMuted}44`,
- color: currentSeriesIdsSet.has(series.id) ? colors.success : colors.textMuted,
- padding: '4px 10px',
- fontSize: fontSize.tiny,
- cursor: 'pointer',
- borderRadius: '3px',
- fontWeight: currentSeriesIdsSet.has(series.id) ? 'bold' : 'normal',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- if (!currentSeriesIdsSet.has(series.id)) {
- e.currentTarget.style.borderColor = colors.primary;
- e.currentTarget.style.color = colors.primary;
- }
- }}
- onMouseLeave={(e) => {
- if (!currentSeriesIdsSet.has(series.id)) {
- e.currentTarget.style.borderColor = `${colors.textMuted}44`;
- e.currentTarget.style.color = colors.textMuted;
- }
- }}
- >
- {series.id}
- </button>
- ))}
- </div>
- </div>
- <button
- onClick={openBrowser}
- disabled={!apiKeyConfigured}
- style={{
- background: apiKeyConfigured ? colors.primary : colors.panel,
- border: `1px solid ${apiKeyConfigured ? colors.primary : colors.textMuted}44`,
- color: apiKeyConfigured ? colors.background : colors.textMuted,
- padding: '8px 14px',
- fontSize: fontSize.small,
- cursor: apiKeyConfigured ? 'pointer' : 'not-allowed',
- borderRadius: '3px',
- fontWeight: 'bold',
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- whiteSpace: 'nowrap',
- opacity: apiKeyConfigured ? 1 : 0.5,
- transition: 'opacity 0.2s'
- }}
- onMouseEnter={(e) => apiKeyConfigured && (e.currentTarget.style.opacity = '0.8')}
- onMouseLeave={(e) => apiKeyConfigured && (e.currentTarget.style.opacity = '1')}
- >
- <FolderTree size={12} />
- {t('buttons.browse')}
- </button>
- </div>
- </div>
-
- {/* Main Content */}
- <div style={{ flex: 1, display: 'flex', gap: '12px', padding: '12px 16px', overflow: 'hidden', minHeight: 0 }}>
-
- {/* Chart Section */}
- <div style={{ flex: 2, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
- <div style={{
- background: colors.panel,
- border: `1px solid ${colors.primary}33`,
- borderRadius: '4px',
- padding: '14px',
- height: '100%',
- display: 'flex',
- flexDirection: 'column'
- }}>
- <h3 style={{ color: colors.primary, fontSize: fontSize.body, fontWeight: 'bold', marginBottom: '10px', letterSpacing: '0.5px' }}>
- {t('chart.title')}
- </h3>
-
- {loading && (
- <div style={{
- flex: 1,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- flexDirection: 'column',
- gap: '16px'
- }}>
- <Loader2 size={48} color={colors.primary} className="animate-spin" />
- <div style={{ textAlign: 'center' }}>
- <p style={{ color: colors.primary, fontSize: fontSize.body, fontWeight: 'bold', marginBottom: '6px' }}>
- {loadingMessage}
- </p>
- <p style={{ color: colors.textMuted, fontSize: fontSize.small }}>
- Please wait while we fetch data from FRED...
- </p>
- </div>
- </div>
- )}
-
- {!loading && error && (
- <div style={{
- background: '#3a0a0a',
- border: '2px solid #ff0000',
- color: '#ff0000',
- padding: '16px',
- borderRadius: '4px',
- fontSize: '11px',
- marginBottom: '12px',
- display: 'flex',
- alignItems: 'flex-start',
- gap: '12px',
- boxShadow: '0 2px 8px rgba(255, 0, 0, 0.2)'
- }}>
- <AlertCircle size={20} style={{ flexShrink: 0, marginTop: '2px' }} />
- <div style={{ flex: 1 }}>
- <p style={{ fontWeight: 'bold', marginBottom: '4px' }}>Error Fetching Data</p>
- <p style={{ color: '#ffaaaa', fontSize: '10px' }}>{error}</p>
- {!apiKeyConfigured && (
- <p style={{ color: '#ffaaaa', fontSize: '10px', marginTop: '8px' }}>
- 💡 Tip: Make sure you've configured your FRED API key in Settings → Credentials
- </p>
- )}
- </div>
- </div>
- )}
-
- {data.length === 0 && !loading && !error && (
- <div style={{
- flex: 1,
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- color: colors.textMuted,
- fontSize: fontSize.body,
- flexDirection: 'column',
- gap: '10px'
- }}>
- <TrendingUp size={48} color={colors.textMuted} opacity={0.3} />
- <p style={{ color: colors.text }}>{t('chart.emptyState')}</p>
- <p style={{ fontSize: fontSize.small, color: colors.textMuted }}>{t('chart.trySuggestion')}</p>
- </div>
- )}
-
- {data.length > 0 && (
- <div style={{ flex: 1, minHeight: 0 }}>
- <ResponsiveContainer width="100%" height="100%">
- {chartType === 'line' ? (
- <LineChart data={prepareChartData()} margin={{ top: 5, right: 20, left: 10, bottom: 5 }}>
- <CartesianGrid strokeDasharray="3 3" stroke={`${colors.textMuted}22`} />
- <XAxis dataKey="date" stroke={colors.textMuted} style={{ fontSize: fontSize.tiny, fill: colors.textMuted }} />
- <YAxis
- stroke={colors.textMuted}
- style={{ fontSize: fontSize.tiny, fill: colors.textMuted }}
- label={normalizeData ? { value: 'Normalized (0-100)', angle: -90, position: 'insideLeft', style: { fontSize: fontSize.tiny, fill: colors.textMuted } } : undefined}
- />
- <Tooltip
- contentStyle={{ background: colors.background, border: `1px solid ${colors.primary}`, borderRadius: '3px', fontSize: fontSize.small }}
- labelStyle={{ color: colors.primary, fontSize: fontSize.tiny }}
- itemStyle={{ color: colors.text, fontSize: fontSize.tiny }}
- />
- <Legend wrapperStyle={{ fontSize: fontSize.tiny }} />
- {data.map((series, idx) => (
- <Line
- key={series.series_id}
- type="monotone"
- dataKey={series.series_id}
- stroke={[colors.primary, colors.success, colors.info, colors.warning, colors.alert][idx % 5]}
- strokeWidth={2}
- dot={false}
- />
- ))}
- </LineChart>
- ) : (
- <AreaChart data={prepareChartData()} margin={{ top: 5, right: 20, left: 10, bottom: 5 }}>
- <CartesianGrid strokeDasharray="3 3" stroke={`${colors.textMuted}22`} />
- <XAxis dataKey="date" stroke={colors.textMuted} style={{ fontSize: fontSize.tiny, fill: colors.textMuted }} />
- <YAxis
- stroke={colors.textMuted}
- style={{ fontSize: fontSize.tiny, fill: colors.textMuted }}
- label={normalizeData ? { value: 'Normalized (0-100)', angle: -90, position: 'insideLeft', style: { fontSize: fontSize.tiny, fill: colors.textMuted } } : undefined}
- />
- <Tooltip
- contentStyle={{ background: colors.background, border: `1px solid ${colors.primary}`, borderRadius: '3px', fontSize: fontSize.small }}
- labelStyle={{ color: colors.primary, fontSize: fontSize.tiny }}
- itemStyle={{ color: colors.text, fontSize: fontSize.tiny }}
- />
- <Legend wrapperStyle={{ fontSize: fontSize.tiny }} />
- {data.map((series, idx) => (
- <Area
- key={series.series_id}
- type="monotone"
- dataKey={series.series_id}
- stroke={[colors.primary, colors.success, colors.info, colors.warning, colors.alert][idx % 5]}
- fill={`${[colors.primary, colors.success, colors.info, colors.warning, colors.alert][idx % 5]}33`}
- />
- ))}
- </AreaChart>
- )}
- </ResponsiveContainer>
- </div>
- )}
- </div>
- </div>
-
- {/* Data Table */}
- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, overflowY: 'auto', gap: '10px' }}>
- {data.map(series => (
- <div
- key={series.series_id}
- style={{
- background: colors.panel,
- border: `1px solid ${colors.primary}33`,
- borderRadius: '4px',
- padding: '12px',
- flexShrink: 0
- }}
- >
- <div style={{ borderBottom: `1px solid ${colors.textMuted}33`, paddingBottom: '8px', marginBottom: '8px' }}>
- <h4 style={{ color: colors.primary, fontSize: fontSize.body, fontWeight: 'bold', marginBottom: '4px' }}>
- {series.series_id}
- </h4>
- <p style={{ color: colors.text, fontSize: fontSize.tiny, marginBottom: '6px' }}>{series.title}</p>
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px', fontSize: fontSize.tiny, color: colors.textMuted }}>
- <span>Units: {series.units}</span>
- <span>Freq: {series.frequency}</span>
- <span>Obs: {series.observation_count}</span>
- <span>Updated: {series.last_updated.split('T')[0]}</span>
- </div>
- </div>
-
- <div style={{ maxHeight: '200px', overflowY: 'auto' }}>
- <table style={{ width: '100%', fontSize: fontSize.tiny, borderCollapse: 'collapse' }}>
- <thead style={{ position: 'sticky', top: 0, background: colors.panel }}>
- <tr style={{ borderBottom: `1px solid ${colors.textMuted}33` }}>
- <th style={{ color: colors.textMuted, textAlign: 'left', padding: '6px 4px', fontWeight: 'bold' }}>Date</th>
- <th style={{ color: colors.textMuted, textAlign: 'right', padding: '6px 4px', fontWeight: 'bold' }}>Value</th>
- </tr>
- </thead>
- <tbody>
- {series.observations.slice(-20).reverse().map((obs, idx) => (
- <tr key={idx} style={{ borderBottom: `1px solid ${colors.background}` }}>
- <td style={{ color: colors.textMuted, padding: '4px' }}>{obs.date}</td>
- <td style={{ color: colors.text, textAlign: 'right', padding: '4px', fontFamily: 'monospace', fontSize: fontSize.tiny }}>
- {obs.value.toFixed(2)}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- </div>
- ))}
- </div>
- </div>
-
- {/* Footer */}
- <TabFooter
- tabName="ECONOMIC SCREENER"
- leftInfo={[
- { label: 'FRED Economic Data', color: colors.accent },
- { label: 'Federal Reserve Bank of St. Louis', color: colors.textMuted },
- ]}
- statusInfo={
- data.length > 0 && (
- <span style={{ color: colors.primary, fontWeight: 'bold' }}>
- {data.length} series | {data.reduce((acc, s) => acc + s.observation_count, 0)} observations
- </span>
- )
- }
- backgroundColor={colors.panel}
- borderColor={colors.primary}
- />
- </div>
- );
-}
diff --git a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
deleted file mode 100644
index c51c9df77..000000000
--- a/fincept-terminal-desktop/src/components/tabs/TradingTab.tsx
+++ /dev/null
@@ -1,2095 +0,0 @@
-// File: src/components/tabs/TradingTab.tsx
-// Professional Fincept Terminal-Grade Trading Interface
-
-import React, { useState, useEffect, useCallback, memo, useMemo } from 'react';
-import {
- TrendingUp, TrendingDown, Activity, DollarSign, BarChart3,
- Settings as SettingsIcon, Globe, Wifi, WifiOff, Bell,
- Zap, Target, AlertCircle, RefreshCw, Maximize2, ChevronDown,
- Clock, TrendingDown as ArrowDown, TrendingUp as ArrowUp, ChevronUp, Minimize2
-} from 'lucide-react';
-
-import { useBrokerContext } from '../../contexts/BrokerContext';
-import { useRustTicker, useRustOrderBook, useRustTrades } from '../../hooks/useRustWebSocket';
-import { invoke } from '@tauri-apps/api/core';
-import { getMarketDataService } from '../../services/trading/UnifiedMarketDataService';
-// Import new enhanced order form
-import { EnhancedOrderForm } from './trading/core/OrderForm';
-import { HyperLiquidVaultManager } from './trading/exchange-specific/hyperliquid';
-import { StakingPanel, FuturesPanel } from './trading/exchange-specific/kraken';
-import { PositionsTable } from './trading/core/PositionManager';
-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 { TimezoneSelector } from '../common/TimezoneSelector';
-import { AIAgentsPanel } from './trading/ai-agents/AIAgentsPanel';
-import { GridTradingPanel } from './trading/grid-trading';
-import { ModelChatPanel } from './trading/ai-agents/ModelChatPanel';
-import { LeaderboardPanel } from './trading/ai-agents/LeaderboardPanel';
-import type { OrderRequest } from '../../types/trading';
-import { useTranslation } from 'react-i18next';
-
-interface OrderBookLevel {
- price: number;
- size: number;
-}
-
-interface OrderBook {
- bids: OrderBookLevel[];
- asks: OrderBookLevel[];
- symbol: string;
- checksum?: number;
-}
-
-interface Position {
- symbol: string;
- side: 'long' | 'short';
- quantity: number;
- entryPrice: number;
- positionValue: number;
- currentPrice: number;
- unrealizedPnl: number;
- pnlPercent: number;
-}
-
-interface Order {
- id: string;
- symbol: string;
- side: 'buy' | 'sell';
- type: string;
- quantity: number;
- price?: number;
- status: string;
- createdAt: string;
-}
-
-// Fincept Professional Color Palette
-const FINCEPT = {
- 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 TradingTab() {
- const { t } = useTranslation('trading');
- const {
- activeBroker,
- availableBrokers,
- setActiveBroker,
- tradingMode,
- setTradingMode,
- paperPortfolioMode,
- setPaperPortfolioMode,
- activeAdapter,
- realAdapter,
- paperAdapter,
- defaultSymbols,
- isConnecting,
- isLoading,
- } = useBrokerContext();
-
- const [currentTime, setCurrentTime] = useState(new Date());
- const [selectedSymbol, setSelectedSymbol] = useState(defaultSymbols[0] || 'BTC/USD');
- const [tickerState, setTickerData] = useState<any>(null);
- const [orderBook, setOrderBook] = useState<OrderBook>({ bids: [], asks: [], symbol: '' });
- const [tradesState, setTradesData] = useState<any[]>([]);
- const [isPlacingOrder, setIsPlacingOrder] = useState(false);
- const [lastOrderBookUpdate, setLastOrderBookUpdate] = useState<number>(0);
-
- // UI State
- const [searchQuery, setSearchQuery] = useState('');
- const [availableSymbols, setAvailableSymbols] = useState<string[]>([]);
- const [isLoadingSymbols, setIsLoadingSymbols] = useState(false);
- const [showSymbolDropdown, setShowSymbolDropdown] = useState(false);
- const [showBrokerDropdown, setShowBrokerDropdown] = useState(false);
- const [selectedView, setSelectedView] = useState<'chart' | 'depth' | 'trades'>('chart');
- const [rightPanelView, setRightPanelView] = useState<'orderbook' | 'volume' | 'modelchat'>('orderbook');
- const [leftSidebarView, setLeftSidebarView] = useState<'watchlist' | 'ai-agents' | 'leaderboard'>('watchlist');
-
- // Paper trading state
- const [positions, setPositions] = useState<Position[]>([]);
- const [orders, setOrders] = useState<Order[]>([]);
- const [trades, setTrades] = useState<any[]>([]);
- const [balance, setBalance] = useState(0);
- const [equity, setEquity] = useState(0);
- const [stats, setStats] = useState<any>(null);
- const [activeBottomTab, setActiveBottomTab] = useState<'positions' | 'orders' | 'history' | 'trades' | 'stats' | 'features' | 'cross-exchange' | 'grid-trading'>('positions');
- const [isBottomPanelMinimized, setIsBottomPanelMinimized] = useState(false);
-
- // Trading settings
- const [slippage, setSlippage] = useState(0);
- const [makerFee, setMakerFee] = useState(0.0002);
- const [takerFee, setTakerFee] = useState(0.0005);
- const [showSettings, setShowSettings] = useState(false);
-
- // Watchlist
- // 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 }>>({});
-
- // Initialize WebSocket providers (Kraken & HyperLiquid)
- useEffect(() => {
- const initializeProviders = async () => {
- try {
- // Initialize Kraken
- await invoke('ws_set_config', {
- config: {
- name: 'kraken',
- url: 'wss://ws.kraken.com/v2',
- enabled: true,
- reconnect_delay_ms: 5000,
- max_reconnect_attempts: 10,
- heartbeat_interval_ms: 30000,
- }
- });
-
- // Initialize HyperLiquid
- await invoke('ws_set_config', {
- config: {
- name: 'hyperliquid',
- url: 'wss://api.hyperliquid.xyz/ws',
- enabled: true,
- reconnect_delay_ms: 5000,
- max_reconnect_attempts: 10,
- heartbeat_interval_ms: 30000,
- }
- });
- } catch (err) {
- // Ignore config errors
- }
- };
-
- initializeProviders();
- }, []);
-
- // Update time
- useEffect(() => {
- const timer = setInterval(() => {
- setCurrentTime(new Date());
- }, 1000);
- return () => clearInterval(timer);
- }, []);
-
- // Fetch watchlist prices - Use realAdapter for exchange data (works in both paper and live modes)
- // NOTE: This batches all requests into one API call for optimal performance
- useEffect(() => {
- const fetchWatchlistPrices = async () => {
- try {
- // Approach 1: Try using realAdapter's bulk fetchTickers (works in paper mode too)
- if (realAdapter?.isConnected() && typeof realAdapter.fetchTickers === 'function') {
- try {
- const tickers = await realAdapter.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 realAdapter');
- 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 30 seconds for more responsive watchlist
- const interval = setInterval(fetchWatchlistPrices, 30000);
- return () => clearInterval(interval);
- }, [realAdapter, watchlist]);
-
- // Clear data when symbol changes - but don't clear orderbook immediately
- useEffect(() => {
- setTickerData(null);
- setTradesData([]);
- // Don't clear orderbook - let WebSocket update it
- }, [selectedSymbol]);
-
- // Reset data when broker changes
- useEffect(() => {
- // Clear all market data when broker switches
- setTickerData(null);
- setOrderBook({ bids: [], asks: [], symbol: '' });
- setTradesData([]);
- setWatchlistPrices({});
- setLastOrderBookUpdate(0);
-
- // Reset symbol to default for new broker
- if (defaultSymbols.length > 0) {
- setSelectedSymbol(defaultSymbols[0]);
- }
- }, [activeBroker, defaultSymbols]);
-
- // Subscribe to Rust WebSocket feeds (10,000+ connections, minimal memory)
- const { data: tickerData, error: tickerError } = useRustTicker(
- activeBroker || '',
- selectedSymbol,
- !!activeBroker
- );
-
- // Use Rust WebSocket for orderbook (primary source of real-time data)
- const { data: orderbookData, error: orderbookError } = useRustOrderBook(
- activeBroker || '',
- selectedSymbol,
- 25,
- !!activeBroker
- );
-
- const { trades: tradesData, error: tradesError } = useRustTrades(
- activeBroker || '',
- selectedSymbol,
- 50,
- !!activeBroker
- );
-
- // Update ticker data from Rust WebSocket
- // Also feed into UnifiedMarketDataService for paper trading
- useEffect(() => {
- if (!tickerData) return;
-
- setTickerData({
- symbol: tickerData.symbol,
- price: tickerData.price,
- bid: tickerData.bid,
- ask: tickerData.ask,
- last: tickerData.price,
- volume: tickerData.volume,
- high: tickerData.high,
- low: tickerData.low,
- change: tickerData.change,
- changePercent: tickerData.change_percent,
- open: tickerData.open,
- });
-
- // Feed price into UnifiedMarketDataService for paper trading
- // This keeps positions updated and allows order matching
- if (activeBroker && tickerData.price > 0) {
- const marketDataService = getMarketDataService();
- marketDataService.updatePrice(activeBroker, selectedSymbol, {
- price: tickerData.price,
- bid: tickerData.bid,
- ask: tickerData.ask,
- volume: tickerData.volume,
- high: tickerData.high,
- low: tickerData.low,
- change: tickerData.change,
- change_percent: tickerData.change_percent,
- timestamp: tickerData.timestamp,
- });
- }
- }, [tickerData, activeBroker, selectedSymbol]);
-
- // Update orderbook from Rust WebSocket
- useEffect(() => {
- if (!orderbookData) return;
-
- setOrderBook({
- bids: orderbookData.bids.map(b => ({ price: b.price, size: b.quantity })),
- asks: orderbookData.asks.map(a => ({ price: a.price, size: a.quantity })),
- symbol: orderbookData.symbol,
- });
- setLastOrderBookUpdate(Date.now());
- }, [orderbookData]);
-
- // Update trades from Rust WebSocket (auto-maintains 50 trades)
- useEffect(() => {
- if (tradesData && tradesData.length > 0) {
- setTradesData(tradesData.map(t => ({
- symbol: t.symbol,
- price: t.price,
- quantity: t.quantity,
- side: t.side,
- timestamp: t.timestamp,
- })));
- }
- }, [tradesData]);
-
- // Load paper trading data
- useEffect(() => {
- const loadPaperTradingData = async () => {
- if (tradingMode !== 'paper' || !paperAdapter) return;
-
- try {
- const balanceData = await paperAdapter.fetchBalance();
- const usdBalance = (balanceData.free as any)?.USD || 0;
- const totalEquity = (balanceData.total as any)?.USD || 0;
- setBalance(usdBalance);
- setEquity(totalEquity);
-
- const positionsData = await paperAdapter.fetchPositions();
- const marketDataService = getMarketDataService();
-
- const mappedPositions: Position[] = positionsData.map((p: any) => {
- // Get live price from market data service
- const livePrice = marketDataService.getCurrentPrice(p.symbol, activeBroker || undefined);
- const currentPrice = livePrice?.last || p.markPrice || p.current_price || 0;
- const entryPrice = p.entryPrice || p.entry_price || 0;
- const quantity = p.contracts || p.quantity || 0;
-
- // Recalculate P&L with live price
- let unrealizedPnl = p.unrealizedPnl || p.unrealized_pnl || 0;
- let pnlPercent = p.percentage || 0;
-
- if (currentPrice > 0 && entryPrice > 0 && quantity > 0) {
- if (p.side === 'long') {
- unrealizedPnl = (currentPrice - entryPrice) * quantity;
- } else {
- unrealizedPnl = (entryPrice - currentPrice) * quantity;
- }
- pnlPercent = ((currentPrice - entryPrice) / entryPrice) * 100;
- if (p.side === 'short') pnlPercent = -pnlPercent;
- }
-
- return {
- symbol: p.symbol,
- side: p.side,
- quantity: quantity,
- entryPrice: entryPrice,
- positionValue: p.info?.positionValue || (currentPrice * quantity),
- currentPrice: currentPrice,
- unrealizedPnl: unrealizedPnl,
- pnlPercent: pnlPercent,
- };
- });
- setPositions(mappedPositions);
-
- const ordersData = await paperAdapter.fetchOpenOrders();
- const mappedOrders: Order[] = ordersData.map((o: any) => ({
- id: o.id,
- symbol: o.symbol,
- side: o.side,
- type: o.type,
- quantity: o.amount,
- price: o.price,
- status: o.status,
- createdAt: o.datetime,
- }));
- setOrders(mappedOrders);
-
- const tradesData = await paperAdapter.fetchMyTrades(undefined, undefined, 50);
- setTrades(tradesData);
-
- if (typeof (paperAdapter as any).getStatistics === 'function') {
- const statsData = await (paperAdapter as any).getStatistics();
- setStats(statsData);
- }
- } catch (error) {
- console.error('[TradingTab] Failed to load paper trading data:', error);
- }
- };
-
- loadPaperTradingData();
- // Refresh every 1 second for live position updates
- const intervalRef = { current: null as NodeJS.Timeout | null };
- intervalRef.current = setInterval(loadPaperTradingData, 1000);
- return () => {
- if (intervalRef.current) {
- clearInterval(intervalRef.current);
- }
- };
- }, [tradingMode, paperAdapter, activeBroker]);
-
- // Update slippage & fees - use proper adapter methods instead of direct mutation
- useEffect(() => {
- if (paperAdapter && 'paperConfig' in paperAdapter) {
- const config = (paperAdapter as any).paperConfig;
- if (config && config.slippage && config.fees) {
- config.slippage.market = slippage;
- config.fees.maker = makerFee;
- config.fees.taker = takerFee;
- }
- }
- }, [slippage, makerFee, takerFee, paperAdapter]);
-
- // Fetch markets - use realAdapter to get exchange symbols (works in both paper and live modes)
- useEffect(() => {
- const fetchMarkets = async () => {
- if (!realAdapter || !realAdapter.isConnected()) {
- setAvailableSymbols(defaultSymbols);
- return;
- }
- setIsLoadingSymbols(true);
- try {
- const markets = await realAdapter.fetchMarkets();
- const symbols = markets
- .filter((m: any) => m.active && m.spot && (m.quote === 'USD' || m.quote === 'USDT' || m.quote === 'USDC'))
- .map((m: any) => m.symbol)
- .sort();
- setAvailableSymbols(symbols.length > 0 ? symbols : defaultSymbols);
- } catch (error) {
- console.error('[TradingTab] Failed to fetch markets:', error);
- setAvailableSymbols(defaultSymbols);
- } finally {
- setIsLoadingSymbols(false);
- }
- };
- fetchMarkets();
- }, [realAdapter, defaultSymbols]);
-
- // Handle order placement - uses activeAdapter based on tradingMode
- const handlePlaceOrder = useCallback(async (orderRequest: OrderRequest) => {
- // Use the correct adapter based on trading mode
- const adapter = tradingMode === 'paper' ? paperAdapter : realAdapter;
-
- // Initial validation
- if (!adapter || !adapter.isConnected()) {
- alert(`${tradingMode === 'paper' ? 'Paper' : 'Live'} trading adapter not available`);
- throw new Error('Adapter not available');
- }
-
- // CRITICAL: Confirm before placing LIVE orders
- if (tradingMode === 'live') {
- const confirmed = window.confirm(
- `⚠️ LIVE TRADING WARNING ⚠️\n\n` +
- `You are about to place a REAL order:\n\n` +
- `${orderRequest.side.toUpperCase()} ${orderRequest.quantity} ${orderRequest.symbol}\n` +
- `Type: ${orderRequest.type}\n` +
- `${orderRequest.price ? `Price: $${orderRequest.price}` : 'Market Order'}\n\n` +
- `This will use REAL funds. Continue?`
- );
- if (!confirmed) {
- throw new Error('Order cancelled by user');
- }
- }
-
- setIsPlacingOrder(true);
- try {
- // Create order using the appropriate adapter
- const order = await adapter.createOrder(
- orderRequest.symbol,
- orderRequest.type,
- orderRequest.side,
- orderRequest.quantity,
- orderRequest.price,
- { stopPrice: orderRequest.stopPrice }
- );
-
- // Re-validate adapter is still connected after async operation
- if (!adapter || !adapter.isConnected()) {
- throw new Error('Adapter disconnected during order placement');
- }
-
- // Fetch updated orders (only for paper trading - live orders come from exchange)
- if (tradingMode === 'paper' && paperAdapter) {
- const ordersData = await paperAdapter.fetchOpenOrders();
- const mappedOrders: Order[] = ordersData.map((o: any) => ({
- id: o.id,
- symbol: o.symbol,
- side: o.side,
- type: o.type,
- quantity: o.amount,
- price: o.price,
- status: o.status,
- createdAt: o.datetime,
- }));
- setOrders(mappedOrders);
-
- // Fetch updated balance
- const balanceData = await paperAdapter.fetchBalance();
- const usdBalance = (balanceData.free as any)?.USD || 0;
- setBalance(usdBalance);
- }
-
- alert(`[OK] ${tradingMode.toUpperCase()} Order placed: ${order.id}`);
- } catch (error) {
- alert(`[FAIL] Order failed: ${(error as Error).message}`);
- throw error;
- } finally {
- setIsPlacingOrder(false);
- }
- }, [tradingMode, paperAdapter, realAdapter]);
-
- // Handle order cancellation - uses correct adapter based on mode
- const handleCancelOrder = useCallback(async (orderId: string, symbol: string) => {
- const adapter = tradingMode === 'paper' ? paperAdapter : realAdapter;
- if (!adapter) return;
-
- // Confirm for live orders
- if (tradingMode === 'live') {
- const confirmed = window.confirm(
- `Cancel LIVE order ${orderId}?\n\nThis will cancel a real order on the exchange.`
- );
- if (!confirmed) return;
- }
-
- try {
- await adapter.cancelOrder(orderId, symbol);
-
- // Refresh orders for paper trading
- if (tradingMode === 'paper' && paperAdapter) {
- const ordersData = await paperAdapter.fetchOpenOrders();
- const mappedOrders: Order[] = ordersData.map((o: any) => ({
- id: o.id,
- symbol: o.symbol,
- side: o.side,
- type: o.type,
- quantity: o.amount,
- price: o.price,
- status: o.status,
- createdAt: o.datetime,
- }));
- setOrders(mappedOrders);
- }
-
- alert(`[OK] Order ${orderId} cancelled`);
- } catch (error) {
- console.error('Cancel failed:', error);
- alert(`[FAIL] Cancel failed: ${(error as Error).message}`);
- }
- }, [tradingMode, paperAdapter, realAdapter]);
-
- // Handle broker change
- const handleBrokerChange = async (brokerId: string) => {
- setShowBrokerDropdown(false);
- await setActiveBroker(brokerId);
- };
-
- const currentPrice = tickerState?.last || tickerState?.price || orderBook.asks[0]?.price || 0;
-
- // Calculate price change and percentage - use 24h open price from watchlist as fallback
- let priceChange = 0;
- let priceChangePercent = 0;
-
- if (tickerState) {
- // Try direct fields first
- priceChange = tickerState.change || 0;
- priceChangePercent = tickerState.changePercent || tickerState.change_percent || 0;
-
- // If not available, calculate from open/last
- if (priceChange === 0 && priceChangePercent === 0) {
- const last = tickerState.last || tickerState.price || 0;
- const open = tickerState.open || 0;
-
- if (last > 0 && open > 0) {
- priceChange = last - open;
- priceChangePercent = (priceChange / open) * 100;
- }
- }
- }
-
- // Fallback: use watchlist data if ticker doesn't have change info
- if (priceChange === 0 && priceChangePercent === 0 && watchlistPrices[selectedSymbol]) {
- priceChangePercent = watchlistPrices[selectedSymbol].change;
- if (currentPrice > 0) {
- priceChange = (priceChangePercent / 100) * currentPrice / (1 + priceChangePercent / 100);
- }
- }
-
- // Calculate 24h price range (High - Low)
- const spread24h = (tickerState?.high && tickerState?.low) ? (tickerState.high - tickerState.low) : 0;
- const spread24hPercent = (spread24h > 0 && tickerState?.low && tickerState.low > 0)
- ? ((spread24h / tickerState.low) * 100)
- : 0;
-
- return (
- <div style={{
- height: '100%',
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- fontFamily: '"IBM Plex Mono", "Consolas", monospace',
- overflow: 'hidden',
- display: 'flex',
- flexDirection: 'column'
- }}>
- <style>{`
- @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600;700&display=swap');
-
- *::-webkit-scrollbar { width: 6px; height: 6px; }
- *::-webkit-scrollbar-track { background: ${FINCEPT.DARK_BG}; }
- *::-webkit-scrollbar-thumb { background: ${FINCEPT.BORDER}; border-radius: 3px; }
- *::-webkit-scrollbar-thumb:hover { background: ${FINCEPT.MUTED}; }
-
- .terminal-glow {
- text-shadow: 0 0 10px ${FINCEPT.ORANGE}40;
- }
-
- .price-flash {
- animation: flash 0.3s ease-out;
- }
-
- @keyframes flash {
- 0% { background-color: ${FINCEPT.YELLOW}40; }
- 100% { background-color: transparent; }
- }
-
- @keyframes pulse {
- 0%, 100% { opacity: 1; }
- 50% { opacity: 0.5; }
- }
- `}</style>
-
- {/* ========== TOP NAVIGATION BAR ========== */}
- <div style={{
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `2px solid ${FINCEPT.ORANGE}`,
- padding: '6px 12px',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- flexShrink: 0,
- boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20`
- }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
- <Activity size={18} color={FINCEPT.ORANGE} style={{ filter: 'drop-shadow(0 0 4px ' + FINCEPT.ORANGE + ')' }} />
- <span style={{
- color: FINCEPT.ORANGE,
- fontWeight: 700,
- fontSize: '14px',
- letterSpacing: '0.5px',
- textShadow: `0 0 10px ${FINCEPT.ORANGE}40`
- }}>
- {t('header.terminal')}
- </span>
- </div>
-
- <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
-
- {/* Broker Selector */}
- <div style={{ position: 'relative' }}>
- <button
- onClick={() => setShowBrokerDropdown(!showBrokerDropdown)}
- style={{
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- padding: '4px 10px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.CYAN,
- cursor: 'pointer',
- fontSize: '11px',
- fontWeight: 600,
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => e.currentTarget.style.borderColor = FINCEPT.CYAN}
- onMouseLeave={(e) => e.currentTarget.style.borderColor = FINCEPT.BORDER}
- >
- <Globe size={12} />
- {activeBroker?.toUpperCase() || t('header.selectBroker')}
- <ChevronDown size={10} />
- </button>
-
- {showBrokerDropdown && (
- <div style={{
- position: 'absolute',
- top: '100%',
- left: 0,
- marginTop: '4px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- minWidth: '200px',
- zIndex: 1000,
- boxShadow: `0 4px 16px ${FINCEPT.DARK_BG}80`
- }}>
- {availableBrokers.map((broker) => (
- <div
- key={broker.id}
- onClick={() => handleBrokerChange(broker.id)}
- style={{
- padding: '10px 12px',
- cursor: 'pointer',
- fontSize: '11px',
- backgroundColor: activeBroker === broker.id ? `${FINCEPT.ORANGE}20` : 'transparent',
- borderLeft: activeBroker === broker.id ? `3px solid ${FINCEPT.ORANGE}` : '3px solid transparent',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'space-between',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- if (activeBroker !== broker.id) {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- }
- }}
- onMouseLeave={(e) => {
- if (activeBroker !== broker.id) {
- e.currentTarget.style.backgroundColor = 'transparent';
- }
- }}
- >
- <div>
- <div style={{ color: FINCEPT.WHITE, fontWeight: 600 }}>{broker.name}</div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>{broker.type.toUpperCase()}</div>
- </div>
- {activeBroker === broker.id && (
- <div style={{
- width: '6px',
- height: '6px',
- borderRadius: '50%',
- backgroundColor: FINCEPT.GREEN,
- boxShadow: `0 0 6px ${FINCEPT.GREEN}`
- }} />
- )}
- </div>
- ))}
- </div>
- )}
- </div>
-
- <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
-
- {/* Trading Mode Toggle - PROMINENT INDICATOR */}
- <div style={{
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- padding: '4px 12px',
- backgroundColor: tradingMode === 'live' ? `${FINCEPT.RED}20` : `${FINCEPT.GREEN}20`,
- border: `2px solid ${tradingMode === 'live' ? FINCEPT.RED : FINCEPT.GREEN}`,
- borderRadius: '4px'
- }}>
- {/* Mode Indicator */}
- <div style={{
- display: 'flex',
- alignItems: 'center',
- gap: '6px'
- }}>
- <div style={{
- width: '8px',
- height: '8px',
- borderRadius: '50%',
- backgroundColor: tradingMode === 'live' ? FINCEPT.RED : FINCEPT.GREEN,
- boxShadow: `0 0 8px ${tradingMode === 'live' ? FINCEPT.RED : FINCEPT.GREEN}`,
- animation: tradingMode === 'live' ? 'pulse 1s infinite' : 'none'
- }} />
- <span style={{
- fontSize: '11px',
- fontWeight: 700,
- color: tradingMode === 'live' ? FINCEPT.RED : FINCEPT.GREEN,
- letterSpacing: '1px'
- }}>
- {tradingMode === 'live' ? '🔴 LIVE' : '⚪ PAPER'}
- </span>
- </div>
-
- <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
-
- <button
- onClick={() => setTradingMode('paper')}
- style={{
- padding: '4px 10px',
- backgroundColor: tradingMode === 'paper' ? FINCEPT.GREEN : FINCEPT.PANEL_BG,
- border: `1px solid ${tradingMode === 'paper' ? FINCEPT.GREEN : FINCEPT.BORDER}`,
- color: tradingMode === 'paper' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- transition: 'all 0.2s'
- }}
- >
- {t('header.paper')}
- </button>
- <button
- onClick={() => {
- // Require confirmation before switching to live mode
- if (tradingMode !== 'live') {
- const confirmed = window.confirm(
- '⚠️ WARNING: SWITCHING TO LIVE TRADING ⚠️\n\n' +
- 'You are about to enable LIVE trading mode.\n\n' +
- '• All orders will be placed with REAL funds\n' +
- '• Trades will be executed on the actual exchange\n' +
- '• You may lose money\n\n' +
- 'Are you sure you want to continue?'
- );
- if (confirmed) {
- setTradingMode('live');
- }
- }
- }}
- style={{
- padding: '4px 10px',
- backgroundColor: tradingMode === 'live' ? FINCEPT.RED : FINCEPT.PANEL_BG,
- border: `1px solid ${tradingMode === 'live' ? FINCEPT.RED : FINCEPT.BORDER}`,
- color: tradingMode === 'live' ? FINCEPT.WHITE : FINCEPT.GRAY,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- transition: 'all 0.2s'
- }}
- >
- {t('header.live')}
- </button>
- </div>
- </div>
-
- <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '10px' }}>
- {activeAdapter?.isConnected() ? (
- <>
- <Wifi size={12} color={FINCEPT.GREEN} />
- <span style={{ color: FINCEPT.GREEN }}>CONNECTED</span>
- </>
- ) : (
- <>
- <WifiOff size={12} color={FINCEPT.RED} />
- <span style={{ color: FINCEPT.RED }}>DISCONNECTED</span>
- </>
- )}
- </div>
-
- <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
-
- <TimezoneSelector compact />
-
- <button
- onClick={() => setShowSettings(!showSettings)}
- style={{
- padding: '4px 8px',
- backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.GRAY,
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- fontSize: '10px',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.ORANGE;
- e.currentTarget.style.color = FINCEPT.ORANGE;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
- e.currentTarget.style.color = FINCEPT.GRAY;
- }}
- >
- <SettingsIcon size={12} />
- </button>
- </div>
- </div>
-
- {/* ========== TICKER BAR ========== */}
- <div style={{
- backgroundColor: FINCEPT.PANEL_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- padding: '10px 12px',
- display: 'flex',
- alignItems: 'center',
- gap: '20px',
- flexShrink: 0
- }}>
- {/* Symbol Selector */}
- <div style={{ position: 'relative', minWidth: '180px' }} data-symbol-selector>
- <div
- onClick={() => setShowSymbolDropdown(!showSymbolDropdown)}
- style={{
- padding: '6px 12px',
- backgroundColor: FINCEPT.HEADER_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- cursor: 'pointer',
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center'
- }}
- >
- <span style={{ fontSize: '13px', fontWeight: 700, color: FINCEPT.ORANGE }}>{selectedSymbol}</span>
- <ChevronDown size={12} color={FINCEPT.GRAY} />
- </div>
-
- {showSymbolDropdown && (
- <div style={{
- position: 'absolute',
- top: '100%',
- left: 0,
- right: 0,
- marginTop: '4px',
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- maxHeight: '400px',
- overflow: 'hidden',
- zIndex: 1000,
- boxShadow: `0 4px 16px ${FINCEPT.DARK_BG}80`
- }}>
- <div style={{ padding: '8px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
- <input
- type="text"
- placeholder="Search symbols..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- autoFocus
- style={{
- width: '100%',
- padding: '6px 8px',
- backgroundColor: FINCEPT.HEADER_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`,
- fontSize: '11px',
- outline: 'none'
- }}
- />
- </div>
- <div style={{ maxHeight: '340px', overflowY: 'auto' }}>
- {availableSymbols
- .filter(symbol => symbol.toLowerCase().includes(searchQuery.toLowerCase()))
- .map(symbol => (
- <div
- key={symbol}
- onClick={() => {
- setSelectedSymbol(symbol);
- setShowSymbolDropdown(false);
- setSearchQuery('');
- }}
- style={{
- padding: '8px 12px',
- cursor: 'pointer',
- fontSize: '11px',
- backgroundColor: symbol === selectedSymbol ? `${FINCEPT.ORANGE}20` : 'transparent',
- color: symbol === selectedSymbol ? FINCEPT.ORANGE : FINCEPT.WHITE,
- borderLeft: symbol === selectedSymbol ? `3px solid ${FINCEPT.ORANGE}` : 'none'
- }}
- onMouseEnter={(e) => {
- if (symbol !== selectedSymbol) {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- }
- }}
- onMouseLeave={(e) => {
- if (symbol !== selectedSymbol) {
- e.currentTarget.style.backgroundColor = 'transparent';
- }
- }}
- >
- {symbol}
- </div>
- ))}
- </div>
- </div>
- )}
- </div>
-
- {/* Price Display */}
- <div style={{ display: 'flex', alignItems: 'baseline', gap: '8px' }}>
- <span style={{ fontSize: '24px', fontWeight: 700, color: FINCEPT.YELLOW, willChange: 'contents', transition: 'none' }}>
- {tickerState ? `$${(tickerState.last || tickerState.price)?.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) || '0.00'}` : '--'}
- </span>
- {tickerState && (priceChange !== 0 || priceChangePercent !== 0) && (
- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
- {priceChange >= 0 ? (
- <ArrowUp size={16} color={FINCEPT.GREEN} />
- ) : (
- <ArrowDown size={16} color={FINCEPT.RED} />
- )}
- <span style={{
- fontSize: '13px',
- fontWeight: 600,
- color: priceChange >= 0 ? FINCEPT.GREEN : FINCEPT.RED
- }}>
- {priceChange >= 0 ? '+' : ''}{priceChange.toFixed(2)} ({priceChangePercent >= 0 ? '+' : ''}{priceChangePercent.toFixed(2)}%)
- </span>
- </div>
- )}
- {tickerState && priceChange === 0 && priceChangePercent === 0 && (
- <div style={{ fontSize: '11px', color: FINCEPT.GRAY, fontStyle: 'italic' }}>
- No change data
- </div>
- )}
- </div>
-
- <div style={{ height: '24px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
-
- {/* Market Stats */}
- <div style={{ display: 'flex', alignItems: 'center', gap: '24px', fontSize: '11px', willChange: 'contents' }}>
- <div style={{ minWidth: '60px' }}>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>BID</div>
- <div style={{ color: FINCEPT.GREEN, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
- {tickerState?.bid ? `$${tickerState.bid.toFixed(2)}` : '--'}
- </div>
- </div>
- <div style={{ minWidth: '60px' }}>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>ASK</div>
- <div style={{ color: FINCEPT.RED, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
- {tickerState?.ask ? `$${tickerState.ask.toFixed(2)}` : '--'}
- </div>
- </div>
- <div style={{ minWidth: '120px' }}>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>24H RANGE</div>
- <div style={{ color: FINCEPT.CYAN, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
- {spread24h > 0 ? `$${spread24h.toFixed(2)} (${spread24hPercent.toFixed(2)}%)` : '--'}
- </div>
- </div>
- <div style={{ minWidth: '80px' }}>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>24H HIGH</div>
- <div style={{ color: FINCEPT.WHITE, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
- {tickerState?.high ? `$${tickerState.high.toFixed(2)}` : '--'}
- </div>
- </div>
- <div style={{ minWidth: '80px' }}>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>24H LOW</div>
- <div style={{ color: FINCEPT.WHITE, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
- {tickerState?.low ? `$${tickerState.low.toFixed(2)}` : '--'}
- </div>
- </div>
- <div style={{ minWidth: '100px' }}>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>24H VOLUME</div>
- <div style={{ color: FINCEPT.PURPLE, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
- {tickerState?.volume ? (
- tickerState.quoteVolume
- ? `$${tickerState.quoteVolume.toLocaleString(undefined, { maximumFractionDigits: 0 })}`
- : currentPrice > 0
- ? `$${(tickerState.volume * currentPrice).toLocaleString(undefined, { maximumFractionDigits: 0 })}`
- : `${tickerState.volume.toLocaleString(undefined, { maximumFractionDigits: 2 })} ${selectedSymbol.split('/')[0]}`
- ) : '--'}
- </div>
- </div>
- </div>
-
- {tradingMode === 'paper' && (
- <>
- <div style={{ height: '24px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
- <div style={{ display: 'flex', alignItems: 'center', gap: '16px', fontSize: '11px' }}>
- <div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>BALANCE</div>
- <div style={{ color: FINCEPT.CYAN, fontWeight: 600 }}>${balance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>
- </div>
- <div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>EQUITY</div>
- <div style={{ color: FINCEPT.YELLOW, fontWeight: 600 }}>${equity.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>
- </div>
- </div>
- </>
- )}
- </div>
-
- {/* ========== MAIN CONTENT ========== */}
- <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
- {/* LEFT SIDEBAR - Watchlist / AI Agents Toggle */}
- <div style={{
- width: '320px',
- backgroundColor: FINCEPT.PANEL_BG,
- borderRight: `1px solid ${FINCEPT.BORDER}`,
- display: 'flex',
- flexDirection: 'column',
- overflow: 'hidden'
- }}>
- {/* Toggle Header */}
- <div style={{
- padding: '6px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- display: 'flex',
- gap: '4px'
- }}>
- <button
- onClick={() => setLeftSidebarView('watchlist')}
- style={{
- flex: 1,
- padding: '6px 8px',
- backgroundColor: leftSidebarView === 'watchlist' ? FINCEPT.ORANGE : 'transparent',
- border: 'none',
- color: leftSidebarView === 'watchlist' ? FINCEPT.DARK_BG : FINCEPT.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' ? FINCEPT.ORANGE : 'transparent',
- border: 'none',
- color: leftSidebarView === 'ai-agents' ? FINCEPT.DARK_BG : FINCEPT.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' ? FINCEPT.ORANGE : 'transparent',
- border: 'none',
- color: leftSidebarView === 'leaderboard' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- cursor: 'pointer',
- fontSize: '9px',
- fontWeight: 700,
- letterSpacing: '0.5px',
- transition: 'all 0.2s',
- borderRadius: '2px'
- }}
- >
- LEADER
- </button>
- </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 ? `${FINCEPT.ORANGE}15` : 'transparent',
- borderLeft: selectedSymbol === symbol ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- borderRight: idx % 2 === 0 ? `1px solid ${FINCEPT.BORDER}` : 'none',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- if (selectedSymbol !== symbol) {
- e.currentTarget.style.backgroundColor = FINCEPT.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 ? FINCEPT.ORANGE : FINCEPT.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: FINCEPT.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 ? FINCEPT.GREEN : FINCEPT.RED,
- fontFamily: 'monospace',
- fontWeight: 700
- }}>
- {watchlistPrices[symbol].change >= 0 ? '▲' : '▼'} {Math.abs(watchlistPrices[symbol].change).toFixed(2)}%
- </div>
- </div>
- ) : (
- <div style={{
- fontSize: '9px',
- color: FINCEPT.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>
-
- {/* CENTER - Chart & Order Book */}
- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
- {/* Chart Area */}
- <div style={{
- flex: isBottomPanelMinimized ? 1 : '0 0 55%',
- backgroundColor: FINCEPT.PANEL_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- display: 'flex',
- flexDirection: 'column',
- overflow: 'hidden',
- transition: 'flex 0.3s ease'
- }}>
- <div style={{
- padding: '8px 12px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- display: 'flex',
- alignItems: 'center',
- gap: '8px'
- }}>
- {['CHART', 'DEPTH', 'TRADES'].map((view) => (
- <button
- key={view}
- onClick={() => setSelectedView(view.toLowerCase() as any)}
- style={{
- padding: '4px 12px',
- backgroundColor: selectedView === view.toLowerCase() ? FINCEPT.ORANGE : 'transparent',
- border: 'none',
- color: selectedView === view.toLowerCase() ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- transition: 'all 0.2s'
- }}
- >
- {view}
- </button>
- ))}
- </div>
- <div style={{
- flex: 1,
- display: 'flex',
- alignItems: 'stretch',
- justifyContent: 'center',
- color: FINCEPT.GRAY,
- fontSize: '12px',
- overflow: 'visible',
- minHeight: 0
- }}>
- {selectedView === 'chart' && (
- <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}
- />
- </div>
- )}
- {selectedView === 'trades' && (
- <div style={{ width: '100%', height: '100%', overflow: 'auto', padding: '8px' }}>
- <table style={{ width: '100%', fontSize: '10px', borderCollapse: 'collapse' }}>
- <thead>
- <tr style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
- <th style={{ padding: '6px', textAlign: 'left', color: FINCEPT.GRAY }}>TIME</th>
- <th style={{ padding: '6px', textAlign: 'right', color: FINCEPT.GRAY }}>PRICE</th>
- <th style={{ padding: '6px', textAlign: 'right', color: FINCEPT.GRAY }}>SIZE</th>
- </tr>
- </thead>
- <tbody>
- {tradesData.slice(0, 20).map((trade, idx) => (
- <tr key={idx} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}40` }}>
- <td style={{ padding: '4px 6px', color: FINCEPT.GRAY, fontSize: '9px' }}>
- {new Date(trade.timestamp).toLocaleTimeString()}
- </td>
- <td style={{
- padding: '4px 6px',
- textAlign: 'right',
- color: trade.side === 'buy' ? FINCEPT.GREEN : FINCEPT.RED
- }}>
- ${trade.price?.toFixed(2)}
- </td>
- <td style={{ padding: '4px 6px', textAlign: 'right', color: FINCEPT.WHITE }}>
- {trade.quantity?.toFixed(4)}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- )}
- </div>
- </div>
-
- {/* Bottom Panel - Positions/Orders/Trades */}
- <div style={{
- flex: isBottomPanelMinimized ? '0 0 40px' : 1,
- display: 'flex',
- flexDirection: 'column',
- overflow: 'hidden',
- transition: 'flex 0.3s ease'
- }}>
- <div style={{
- padding: '6px 12px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center'
- }}>
- <div style={{ display: 'flex', gap: '4px' }}>
- {(['positions', 'orders', 'history', 'trades', 'stats', 'features', 'cross-exchange', 'grid-trading'] as const).map((tab) => (
- <button
- key={tab}
- onClick={() => setActiveBottomTab(tab)}
- style={{
- padding: '6px 16px',
- backgroundColor: activeBottomTab === tab ? FINCEPT.ORANGE : 'transparent',
- border: 'none',
- color: activeBottomTab === tab ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- textTransform: 'uppercase',
- transition: 'all 0.2s'
- }}
- >
- {tab} {tab === 'positions' && `(${positions.length})`} {tab === 'orders' && `(${orders.length})`}
- </button>
- ))}
- </div>
-
- {/* Minimize/Maximize Button */}
- <button
- onClick={() => setIsBottomPanelMinimized(!isBottomPanelMinimized)}
- style={{
- padding: '4px 8px',
- backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.GRAY,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 600,
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- borderRadius: '2px',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
- e.currentTarget.style.borderColor = FINCEPT.GRAY;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.backgroundColor = 'transparent';
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
- }}
- title={isBottomPanelMinimized ? 'Maximize Panel' : 'Minimize Panel'}
- >
- {isBottomPanelMinimized ? (
- <>
- <ChevronUp size={14} />
- <span>MAXIMIZE</span>
- </>
- ) : (
- <>
- <ChevronDown size={14} />
- <span>MINIMIZE</span>
- </>
- )}
- </button>
- </div>
-
- {!isBottomPanelMinimized && (
- <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
- {/* Positions Tab */}
- {activeBottomTab === 'positions' && <PositionsTable />}
-
- {/* Orders Tab */}
- {activeBottomTab === 'orders' && <OrdersTable />}
-
- {/* History Tab (Closed Orders) */}
- {activeBottomTab === 'history' && <ClosedOrders />}
-
- {/* Trades Tab */}
- {activeBottomTab === 'trades' && (
- trades.length === 0 ? (
- <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>
- No trade history
- </div>
- ) : (
- <table style={{ width: '100%', fontSize: '10px', borderCollapse: 'collapse' }}>
- <thead>
- <tr style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
- <th style={{ padding: '8px', textAlign: 'left', color: FINCEPT.GRAY, fontWeight: 600 }}>TIME</th>
- <th style={{ padding: '8px', textAlign: 'left', color: FINCEPT.GRAY, fontWeight: 600 }}>SYMBOL</th>
- <th style={{ padding: '8px', textAlign: 'center', color: FINCEPT.GRAY, fontWeight: 600 }}>SIDE</th>
- <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, fontWeight: 600 }}>QTY</th>
- <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, fontWeight: 600 }}>PRICE</th>
- <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, fontWeight: 600 }}>VALUE</th>
- <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, fontWeight: 600 }}>FEE</th>
- </tr>
- </thead>
- <tbody>
- {trades.map((trade, idx) => (
- <tr key={idx} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}40` }}>
- <td style={{ padding: '8px', color: FINCEPT.GRAY, fontSize: '9px' }}>
- {new Date(trade.timestamp).toLocaleTimeString()}
- </td>
- <td style={{ padding: '8px', color: FINCEPT.WHITE }}>{trade.symbol}</td>
- <td style={{ padding: '8px', textAlign: 'center' }}>
- <span style={{
- padding: '2px 8px',
- backgroundColor: trade.side === 'buy' ? `${FINCEPT.GREEN}20` : `${FINCEPT.RED}20`,
- color: trade.side === 'buy' ? FINCEPT.GREEN : FINCEPT.RED,
- fontSize: '9px',
- fontWeight: 700
- }}>
- {trade.side.toUpperCase()}
- </span>
- </td>
- <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.WHITE }}>
- {trade.amount?.toFixed(4) || '0.0000'}
- </td>
- <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.YELLOW }}>
- ${trade.price?.toFixed(2) || '0.00'}
- </td>
- <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.CYAN }}>
- ${trade.cost?.toFixed(2) || '0.00'}
- </td>
- <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.RED }}>
- ${trade.fee?.cost?.toFixed(2) || '0.00'}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- )
- )}
-
- {/* Stats Tab */}
- {activeBottomTab === 'stats' && (
- <div style={{
- display: 'grid',
- gridTemplateColumns: '1fr 300px',
- gap: '12px',
- padding: '12px',
- height: '100%',
- overflow: 'hidden'
- }}>
- {/* Left: Account Statistics */}
- <div style={{ height: '100%', overflow: 'auto' }}>
- <AccountStats />
- </div>
-
- {/* Right: Fees & Margin */}
- <div style={{
- display: 'flex',
- flexDirection: 'column',
- gap: '12px',
- height: '100%',
- overflow: 'auto'
- }}>
- <FeesDisplay />
- <MarginPanel />
- </div>
- </div>
- )}
-
- {/* Features Tab - Exchange-Specific Features */}
- {activeBottomTab === 'features' && (
- <div style={{ padding: '16px', overflow: 'auto' }}>
- {/* Kraken-Specific Features */}
- {activeBroker === 'kraken' && (
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
- <StakingPanel />
- <FuturesPanel />
- </div>
- )}
-
- {/* HyperLiquid - Already shown in order form area */}
- {activeBroker === 'hyperliquid' && (
- <div style={{
- padding: '40px',
- textAlign: 'center',
- color: FINCEPT.GRAY,
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '4px'
- }}>
- <div style={{ fontSize: '14px', fontWeight: 600, marginBottom: '8px' }}>
- HyperLiquid Features
- </div>
- <div style={{ fontSize: '11px' }}>
- HyperLiquid-specific features (Vault Manager, Leverage Control) are available in the order form panel on the right.
- </div>
- </div>
- )}
-
- {/* No exchange-specific features */}
- {activeBroker !== 'kraken' && activeBroker !== 'hyperliquid' && (
- <div style={{
- padding: '40px',
- textAlign: 'center',
- color: FINCEPT.GRAY,
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: '4px'
- }}>
- <div style={{ fontSize: '14px', fontWeight: 600, marginBottom: '8px' }}>
- No Exchange-Specific Features
- </div>
- <div style={{ fontSize: '11px' }}>
- The selected exchange does not have additional features available in this panel.
- </div>
- </div>
- )}
- </div>
- )}
-
- {/* Cross-Exchange Tab - Multi-Exchange Portfolio & Arbitrage */}
- {activeBottomTab === 'cross-exchange' && (
- <div style={{ padding: '16px', overflow: 'auto' }}>
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
- <PortfolioAggregator />
- <ArbitrageDetector />
- </div>
- </div>
- )}
-
- {/* Grid Trading Tab */}
- {activeBottomTab === 'grid-trading' && (
- <div style={{ padding: '16px', overflow: 'auto', height: '100%' }}>
- <GridTradingPanel
- symbol={selectedSymbol}
- currentPrice={tickerState?.last || tickerState?.close || 0}
- brokerType="crypto"
- brokerId={activeBroker}
- cryptoAdapter={realAdapter || undefined}
- variant="full"
- />
- </div>
- )}
- </div>
- )}
- </div>
- </div>
-
- {/* RIGHT SIDEBAR - Order Entry & Order Book */}
- <div style={{
- width: '300px',
- backgroundColor: FINCEPT.PANEL_BG,
- borderLeft: `1px solid ${FINCEPT.BORDER}`,
- display: 'flex',
- flexDirection: 'column',
- overflow: 'hidden'
- }}>
- {/* Order Entry */}
- <div style={{
- height: '45%',
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- display: 'flex',
- flexDirection: 'column',
- overflow: 'hidden'
- }}>
- <div style={{
- padding: '8px 12px',
- backgroundColor: tradingMode === 'live' ? FINCEPT.RED : FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- fontSize: '10px',
- fontWeight: 700,
- color: tradingMode === 'live' ? FINCEPT.WHITE : FINCEPT.ORANGE,
- letterSpacing: '0.5px',
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center'
- }}>
- <span>ORDER ENTRY</span>
- <span style={{
- padding: '2px 8px',
- backgroundColor: tradingMode === 'live' ? FINCEPT.WHITE : FINCEPT.GREEN,
- color: tradingMode === 'live' ? FINCEPT.RED : FINCEPT.DARK_BG,
- fontSize: '9px',
- fontWeight: 700,
- borderRadius: '2px'
- }}>
- {tradingMode === 'live' ? '🔴 LIVE' : '⚪ PAPER'}
- </span>
- </div>
- <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
- {/* Loading State */}
- {isLoading ? (
- <div style={{
- padding: '20px',
- textAlign: 'center',
- border: `1px solid ${FINCEPT.CYAN}`,
- backgroundColor: `${FINCEPT.CYAN}10`
- }}>
- <div style={{ color: FINCEPT.CYAN, fontSize: '11px', fontWeight: 700, marginBottom: '8px' }}>
- ⏳ LOADING...
- </div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>
- Loading broker configurations...
- </div>
- </div>
- ) : tradingMode === 'paper' ? (
- /* PAPER TRADING MODE */
- !paperAdapter ? (
- <div style={{
- padding: '20px',
- textAlign: 'center',
- border: `1px solid ${FINCEPT.RED}`,
- backgroundColor: `${FINCEPT.RED}10`
- }}>
- <div style={{ color: FINCEPT.RED, fontSize: '12px', fontWeight: 700, marginBottom: '12px' }}>
- {isConnecting ? '⏳ CONNECTING...' : '❌ ADAPTER NOT READY'}
- </div>
- {!isConnecting && (
- <>
- <div style={{ color: FINCEPT.WHITE, fontSize: '10px', marginBottom: '12px', lineHeight: '1.5' }}>
- Paper trading adapter failed to initialize.
- </div>
- <button
- onClick={() => window.location.reload()}
- style={{
- padding: '6px 12px',
- backgroundColor: FINCEPT.ORANGE,
- border: 'none',
- color: FINCEPT.DARK_BG,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- borderRadius: '2px'
- }}
- >
- RELOAD APPLICATION
- </button>
- </>
- )}
- </div>
- ) : !paperAdapter.isConnected() ? (
- <div style={{
- padding: '20px',
- textAlign: 'center',
- border: `1px solid ${FINCEPT.YELLOW}`,
- backgroundColor: `${FINCEPT.YELLOW}10`
- }}>
- <div style={{ color: FINCEPT.YELLOW, fontSize: '11px', fontWeight: 700, marginBottom: '8px' }}>
- ⏳ CONNECTING...
- </div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>
- Establishing connection to {activeBroker}...
- </div>
- </div>
- ) : (
- <>
- {/* Paper Trading Banner */}
- <div style={{
- padding: '8px',
- marginBottom: '12px',
- backgroundColor: `${FINCEPT.GREEN}15`,
- border: `1px solid ${FINCEPT.GREEN}`,
- borderRadius: '4px',
- textAlign: 'center'
- }}>
- <div style={{ color: FINCEPT.GREEN, fontSize: '10px', fontWeight: 700 }}>
- ⚪ PAPER TRADING MODE
- </div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '2px' }}>
- Simulated orders • No real funds at risk
- </div>
- </div>
-
- <EnhancedOrderForm
- symbol={selectedSymbol}
- currentPrice={currentPrice}
- balance={balance}
- onOrderPlaced={() => {
- console.log('Paper order placed successfully');
- }}
- />
-
- {/* HyperLiquid Vault Manager */}
- <HyperLiquidVaultManager />
- </>
- )
- ) : (
- /* LIVE TRADING MODE */
- !realAdapter ? (
- <div style={{
- padding: '20px',
- textAlign: 'center',
- border: `1px solid ${FINCEPT.RED}`,
- backgroundColor: `${FINCEPT.RED}10`
- }}>
- <div style={{ color: FINCEPT.RED, fontSize: '12px', fontWeight: 700, marginBottom: '12px' }}>
- ❌ LIVE ADAPTER NOT CONFIGURED
- </div>
- <div style={{ color: FINCEPT.WHITE, fontSize: '10px', marginBottom: '12px' }}>
- Please configure API credentials for {activeBroker} to enable live trading.
- </div>
- <button
- onClick={() => setTradingMode('paper')}
- style={{
- padding: '6px 12px',
- backgroundColor: FINCEPT.GREEN,
- border: 'none',
- color: FINCEPT.DARK_BG,
- cursor: 'pointer',
- fontSize: '10px',
- fontWeight: 700,
- borderRadius: '2px'
- }}
- >
- SWITCH TO PAPER MODE
- </button>
- </div>
- ) : !realAdapter.isConnected() ? (
- <div style={{
- padding: '20px',
- textAlign: 'center',
- border: `1px solid ${FINCEPT.YELLOW}`,
- backgroundColor: `${FINCEPT.YELLOW}10`
- }}>
- <div style={{ color: FINCEPT.YELLOW, fontSize: '11px', fontWeight: 700, marginBottom: '8px' }}>
- ⏳ CONNECTING TO EXCHANGE...
- </div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>
- Authenticating with {activeBroker}...
- </div>
- </div>
- ) : (
- <>
- {/* LIVE TRADING WARNING BANNER */}
- <div style={{
- padding: '10px',
- marginBottom: '12px',
- backgroundColor: `${FINCEPT.RED}20`,
- border: `2px solid ${FINCEPT.RED}`,
- borderRadius: '4px',
- textAlign: 'center'
- }}>
- <div style={{ color: FINCEPT.RED, fontSize: '12px', fontWeight: 700 }}>
- 🔴 LIVE TRADING MODE
- </div>
- <div style={{ color: FINCEPT.WHITE, fontSize: '10px', marginTop: '4px', fontWeight: 600 }}>
- ⚠️ REAL FUNDS AT RISK ⚠️
- </div>
- <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '4px' }}>
- Orders will be executed on {activeBroker?.toUpperCase()}
- </div>
- </div>
-
- <EnhancedOrderForm
- symbol={selectedSymbol}
- currentPrice={currentPrice}
- balance={balance}
- onOrderPlaced={() => {
- console.log('LIVE order placed successfully');
- }}
- />
-
- {/* HyperLiquid Vault Manager */}
- <HyperLiquidVaultManager />
- </>
- )
- )}
- </div>
- </div>
-
- {/* Order Book / Volume Profile */}
- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
- <div style={{
- padding: '8px 12px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- fontSize: '10px',
- fontWeight: 700,
- color: FINCEPT.ORANGE,
- letterSpacing: '0.5px',
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center'
- }}>
- <div style={{ display: 'flex', gap: '8px' }}>
- {['orderbook', 'volume', 'modelchat'].map((view) => (
- <button
- key={view}
- onClick={() => setRightPanelView(view as any)}
- style={{
- padding: '4px 8px',
- backgroundColor: rightPanelView === view ? FINCEPT.ORANGE : 'transparent',
- border: 'none',
- color: rightPanelView === view ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- cursor: 'pointer',
- fontSize: '9px',
- fontWeight: 700,
- transition: 'all 0.2s'
- }}
- >
- {view.toUpperCase()}
- </button>
- ))}
- </div>
- {rightPanelView === 'orderbook' && (
- <span style={{ fontSize: '8px', color: FINCEPT.GRAY }}>
- {orderBook.asks.length + orderBook.bids.length} LEVELS
- </span>
- )}
- </div>
- <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>
- {rightPanelView === 'orderbook' && (
- <>
- <div style={{ marginBottom: '12px' }}>
- <div style={{ color: FINCEPT.RED, fontSize: '9px', fontWeight: 700, marginBottom: '4px' }}>
- ASKS ({orderBook.asks.length})
- </div>
- <table style={{ width: '100%', fontSize: '10px' }}>
- <tbody>
- {orderBook.asks.slice(0, 12).reverse().map((ask, idx) => {
- const depth = (ask.size / Math.max(...orderBook.asks.map(a => a.size))) * 100;
- return (
- <tr key={idx} style={{ position: 'relative' }}>
- <td style={{
- padding: '2px 4px',
- color: FINCEPT.RED,
- position: 'relative',
- zIndex: 1
- }}>
- <div style={{
- position: 'absolute',
- right: 0,
- top: 0,
- bottom: 0,
- width: `${depth}%`,
- backgroundColor: `${FINCEPT.RED}15`,
- zIndex: -1
- }} />
- ${ask.price.toFixed(2)}
- </td>
- <td style={{ padding: '2px 4px', textAlign: 'right', color: FINCEPT.GRAY }}>
- {ask.size.toFixed(4)}
- </td>
- </tr>
- );
- })}
- </tbody>
- </table>
- </div>
-
- <div style={{
- height: '1px',
- backgroundColor: FINCEPT.BORDER,
- margin: '8px 0',
- position: 'relative'
- }}>
- <div style={{
- position: 'absolute',
- left: '50%',
- top: '50%',
- transform: 'translate(-50%, -50%)',
- backgroundColor: FINCEPT.PANEL_BG,
- padding: '0 8px',
- fontSize: '11px',
- fontWeight: 700,
- color: FINCEPT.YELLOW
- }}>
- ${currentPrice.toFixed(2)}
- </div>
- </div>
-
- <div>
- <div style={{ color: FINCEPT.GREEN, fontSize: '9px', fontWeight: 700, marginBottom: '4px' }}>
- BIDS ({orderBook.bids.length})
- </div>
- <table style={{ width: '100%', fontSize: '10px' }}>
- <tbody>
- {orderBook.bids.slice(0, 12).map((bid, idx) => {
- const depth = (bid.size / Math.max(...orderBook.bids.map(b => b.size))) * 100;
- return (
- <tr key={idx} style={{ position: 'relative' }}>
- <td style={{
- padding: '2px 4px',
- color: FINCEPT.GREEN,
- position: 'relative',
- zIndex: 1
- }}>
- <div style={{
- position: 'absolute',
- right: 0,
- top: 0,
- bottom: 0,
- width: `${depth}%`,
- backgroundColor: `${FINCEPT.GREEN}15`,
- zIndex: -1
- }} />
- ${bid.price.toFixed(2)}
- </td>
- <td style={{ padding: '2px 4px', textAlign: 'right', color: FINCEPT.GRAY }}>
- {bid.size.toFixed(4)}
- </td>
- </tr>
- );
- })}
- </tbody>
- </table>
- </div>
- </>
- )}
-
- {rightPanelView === 'volume' && (
- <VolumeProfile symbol={selectedSymbol} height={550} />
- )}
-
- {rightPanelView === 'modelchat' && (
- <ModelChatPanel refreshInterval={5000} />
- )}
- </div>
- <div style={{
- padding: '4px 8px',
- backgroundColor: FINCEPT.HEADER_BG,
- borderTop: `1px solid ${FINCEPT.BORDER}`,
- fontSize: '8px',
- color: FINCEPT.GRAY
- }}>
- Updated: {lastOrderBookUpdate > 0 ? new Date(lastOrderBookUpdate).toLocaleTimeString() : 'Never'}
- </div>
- </div>
- </div>
- </div>
-
- {/* ========== STATUS BAR ========== */}
- <div style={{
- borderTop: `1px solid ${FINCEPT.BORDER}`,
- backgroundColor: FINCEPT.HEADER_BG,
- padding: '4px 12px',
- fontSize: '9px',
- color: FINCEPT.GRAY,
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- flexShrink: 0
- }}>
- <span>Fincept Terminal v3.1.4 | Professional Trading Platform</span>
- <span>
- Broker: <span style={{ color: FINCEPT.ORANGE }}>{activeBroker?.toUpperCase() || 'NONE'}</span> |
- Mode: <span style={{ color: tradingMode === 'paper' ? FINCEPT.GREEN : FINCEPT.RED }}>
- {tradingMode.toUpperCase()}
- </span> |
- Status: <span style={{ color: activeAdapter?.isConnected() ? FINCEPT.GREEN : FINCEPT.RED }}>
- {activeAdapter?.isConnected() ? 'CONNECTED' : 'DISCONNECTED'}
- </span>
- </span>
- </div>
- </div>
- );
-}
diff --git a/fincept-terminal-desktop/src/components/tabs/AboutTab.tsx b/fincept-terminal-desktop/src/components/tabs/about/AboutTab.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/AboutTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/about/AboutTab.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/about/index.ts b/fincept-terminal-desktop/src/components/tabs/about/index.ts
new file mode 100644
index 000000000..c063b3b1a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/about/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./AboutTab";
+export { default as AboutTab } from "./AboutTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/AgentConfigTab.tsx b/fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/AgentConfigTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/agent-config/AgentConfigTab.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/agent-config/index.ts b/fincept-terminal-desktop/src/components/tabs/agent-config/index.ts
new file mode 100644
index 000000000..e8089aabc
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/agent-config/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./AgentConfigTab";
+export { default as AgentConfigTab } from "./AgentConfigTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/CFAQuantPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/CFAQuantPanel.tsx
index 094832019..f359ac8cb 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/CFAQuantPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/CFAQuantPanel.tsx
@@ -1,3067 +1,16 @@
-import React, { useState, useEffect, useCallback, useMemo } from 'react';
-import {
- TrendingUp,
- Calculator,
- RefreshCw,
- AlertCircle,
- CheckCircle2,
- ChevronRight,
- ChevronLeft,
- Search,
- Play,
- Download,
- Database,
- Brain,
- Shuffle,
- Target,
- BarChart3,
- Info,
- Sparkles,
- ArrowUpRight,
- ArrowDownRight,
- Minus,
- Copy,
- HelpCircle,
- Zap,
- LineChart,
- Activity,
- TrendingDown,
- ZoomIn,
- ZoomOut,
- RotateCcw
-} from 'lucide-react';
-import {
- LineChart as RechartsLineChart,
- Line,
- XAxis,
- YAxis,
- CartesianGrid,
- Tooltip,
- ResponsiveContainer,
- Area,
- AreaChart,
- ReferenceLine,
- ComposedChart,
- Bar,
- Scatter,
- Brush,
- ReferenceArea
-} from 'recharts';
-import { quantAnalyticsService, type QuantAnalyticsResult } from '@/services/aiQuantLab/quantAnalyticsService';
-import { yfinanceService } from '@/services/markets/yfinanceService';
-
-// Fincept-style color palette
-const BB = {
- // Core Fincept colors
- black: '#000000',
- darkBg: '#0a0a0a',
- panelBg: '#121212',
- cardBg: '#1a1a1a',
- borderDark: '#2a2a2a',
- borderLight: '#3a3a3a',
-
- // Accent colors
- amber: '#FF8C00',
- amberLight: '#FFA500',
- amberDim: '#CC7000',
-
- // Status colors
- green: '#00C853',
- greenDim: '#00A040',
- red: '#FF3D00',
- redDim: '#CC3000',
-
- // Text colors
- textPrimary: '#FFFFFF',
- textSecondary: '#B0B0B0',
- textMuted: '#707070',
- textAmber: '#FF9500',
-
- // Chart colors
- chartLine: '#00D4FF',
- chartArea: 'rgba(0, 212, 255, 0.1)',
- chartGrid: '#1f1f1f',
-
- // Fincept blue
- blue: '#0066CC',
- blueLight: '#0088FF',
-};
-
-type Step = 'data' | 'analysis' | 'results';
-type DataSourceType = 'symbol' | 'manual';
-
-interface AnalysisConfig {
- id: string;
- name: string;
- shortName: string;
- description: string;
- icon: React.ElementType;
- category: 'time_series' | 'machine_learning' | 'sampling' | 'data_quality';
- color: string;
- minDataPoints: number;
- helpText: string;
-}
-
-const analysisConfigs: AnalysisConfig[] = [
- {
- id: 'trend_analysis',
- name: 'Trend Analysis',
- shortName: 'TREND',
- description: 'Detect upward/downward trends',
- icon: TrendingUp,
- category: 'time_series',
- color: BB.green,
- minDataPoints: 5,
- helpText: 'Linear regression to identify significant trends in price movements.'
- },
- {
- id: 'stationarity_test',
- name: 'Stationarity Test',
- shortName: 'ADF',
- description: 'Unit root test (ADF)',
- icon: BarChart3,
- category: 'time_series',
- color: BB.blue,
- minDataPoints: 20,
- helpText: 'Tests if time series has constant mean/variance. Important for ARIMA modeling.'
- },
- {
- id: 'arima_model',
- name: 'ARIMA Forecast',
- shortName: 'ARIMA',
- description: 'Time series prediction',
- icon: LineChart,
- category: 'time_series',
- color: BB.amber,
- minDataPoints: 20,
- helpText: 'AutoRegressive Integrated Moving Average for forecasting.'
- },
- {
- id: 'forecasting',
- name: 'Exp. Smoothing',
- shortName: 'ETS',
- description: 'Simple forecasting',
- icon: Sparkles,
- category: 'time_series',
- color: BB.amberLight,
- minDataPoints: 10,
- helpText: 'Exponential smoothing methods for quick predictions.'
- },
- {
- id: 'supervised_learning',
- name: 'ML Prediction',
- shortName: 'ML',
- description: 'Machine learning models',
- icon: Brain,
- category: 'machine_learning',
- color: BB.blueLight,
- minDataPoints: 30,
- helpText: 'Compare Ridge, Lasso, Random Forest for predictions.'
- },
- {
- id: 'unsupervised_learning',
- name: 'Pattern Discovery',
- shortName: 'PCA/K',
- description: 'PCA and clustering',
- icon: Target,
- category: 'machine_learning',
- color: BB.amber,
- minDataPoints: 20,
- helpText: 'Find hidden patterns with PCA and K-Means clustering.'
- },
- {
- id: 'resampling_methods',
- name: 'Bootstrap',
- shortName: 'BOOT',
- description: 'Confidence intervals',
- icon: Shuffle,
- category: 'sampling',
- color: BB.green,
- minDataPoints: 10,
- helpText: 'Bootstrap/jackknife for robust statistical inference.'
- },
- {
- id: 'validate_data',
- name: 'Data Quality',
- shortName: 'QA',
- description: 'Validate data quality',
- icon: CheckCircle2,
- category: 'data_quality',
- color: BB.greenDim,
- minDataPoints: 5,
- helpText: 'Check for missing values, outliers, and data issues.'
- },
-];
-
-export function CFAQuantPanel() {
- const [currentStep, setCurrentStep] = useState<Step>('data');
- const [isLoading, setIsLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [analysisResult, setAnalysisResult] = useState<QuantAnalyticsResult<Record<string, unknown>> | null>(null);
-
- const [dataSourceType, setDataSourceType] = useState<DataSourceType>('symbol');
- const [symbolInput, setSymbolInput] = useState('AAPL');
- const [historicalDays, setHistoricalDays] = useState(365);
- const [manualData, setManualData] = useState('');
- const [priceData, setPriceData] = useState<number[]>([]);
- const [priceDates, setPriceDates] = useState<string[]>([]);
- const [priceDataLoading, setPriceDataLoading] = useState(false);
- const [dataStats, setDataStats] = useState<{ min: number; max: number; mean: number; std: number; change: number; changePercent: number } | null>(null);
-
- const [selectedAnalysis, setSelectedAnalysis] = useState<string>('trend_analysis');
- const [showHelp, setShowHelp] = useState<string | null>(null);
-
- // Zoom state for charts
- const [dataChartZoom, setDataChartZoom] = useState<{ startIndex: number; endIndex: number } | null>(null);
- const [resultsChartZoom, setResultsChartZoom] = useState<{ startIndex: number; endIndex: number } | null>(null);
- const [refAreaLeft, setRefAreaLeft] = useState<number | null>(null);
- const [refAreaRight, setRefAreaRight] = useState<number | null>(null);
- const [isSelecting, setIsSelecting] = useState(false);
- const [activeChart, setActiveChart] = useState<'data' | 'results' | null>(null);
-
- // Zoom helper functions
- const handleZoomIn = useCallback((chartType: 'data' | 'results') => {
- const currentZoom = chartType === 'data' ? dataChartZoom : resultsChartZoom;
- const setZoom = chartType === 'data' ? setDataChartZoom : setResultsChartZoom;
- const dataLength = chartType === 'results' && analysisResult ?
- (getResultChartDataLength()) : priceData.length;
-
- if (dataLength <= 5) return;
-
- const currentStart = currentZoom?.startIndex ?? 0;
- const currentEnd = currentZoom?.endIndex ?? dataLength - 1;
- const range = currentEnd - currentStart;
- const center = Math.floor((currentStart + currentEnd) / 2);
- const newRange = Math.max(5, Math.floor(range * 0.7));
- const newStart = Math.max(0, center - Math.floor(newRange / 2));
- const newEnd = Math.min(dataLength - 1, newStart + newRange);
-
- setZoom({ startIndex: newStart, endIndex: newEnd });
- }, [priceData.length, dataChartZoom, resultsChartZoom, analysisResult]);
-
- const handleZoomOut = useCallback((chartType: 'data' | 'results') => {
- const currentZoom = chartType === 'data' ? dataChartZoom : resultsChartZoom;
- const setZoom = chartType === 'data' ? setDataChartZoom : setResultsChartZoom;
- const dataLength = chartType === 'results' && analysisResult ?
- (getResultChartDataLength()) : priceData.length;
-
- if (!currentZoom) return;
-
- const currentStart = currentZoom.startIndex;
- const currentEnd = currentZoom.endIndex;
- const range = currentEnd - currentStart;
- const center = Math.floor((currentStart + currentEnd) / 2);
- const newRange = Math.min(dataLength - 1, Math.floor(range * 1.5));
- const newStart = Math.max(0, center - Math.floor(newRange / 2));
- const newEnd = Math.min(dataLength - 1, newStart + newRange);
-
- if (newStart === 0 && newEnd === dataLength - 1) {
- setZoom(null);
- } else {
- setZoom({ startIndex: newStart, endIndex: newEnd });
- }
- }, [priceData.length, dataChartZoom, resultsChartZoom, analysisResult]);
-
- const handleResetZoom = useCallback((chartType: 'data' | 'results') => {
- const setZoom = chartType === 'data' ? setDataChartZoom : setResultsChartZoom;
- setZoom(null);
- }, []);
-
- // Pan navigation functions
- const handlePanLeft = useCallback((chartType: 'data' | 'results') => {
- const currentZoom = chartType === 'data' ? dataChartZoom : resultsChartZoom;
- const setZoom = chartType === 'data' ? setDataChartZoom : setResultsChartZoom;
-
- if (!currentZoom) return;
-
- const range = currentZoom.endIndex - currentZoom.startIndex;
- const step = Math.max(1, Math.floor(range * 0.2)); // Pan by 20% of visible range
- const newStart = Math.max(0, currentZoom.startIndex - step);
- const newEnd = newStart + range;
-
- setZoom({ startIndex: newStart, endIndex: newEnd });
- }, [dataChartZoom, resultsChartZoom]);
-
- const handlePanRight = useCallback((chartType: 'data' | 'results') => {
- const currentZoom = chartType === 'data' ? dataChartZoom : resultsChartZoom;
- const setZoom = chartType === 'data' ? setDataChartZoom : setResultsChartZoom;
- const dataLength = chartType === 'results' && analysisResult ?
- getResultChartDataLength() : priceData.length;
-
- if (!currentZoom) return;
-
- const range = currentZoom.endIndex - currentZoom.startIndex;
- const step = Math.max(1, Math.floor(range * 0.2)); // Pan by 20% of visible range
- const newEnd = Math.min(dataLength - 1, currentZoom.endIndex + step);
- const newStart = newEnd - range;
-
- setZoom({ startIndex: Math.max(0, newStart), endIndex: newEnd });
- }, [dataChartZoom, resultsChartZoom, priceData.length, analysisResult]);
-
- // Check if we can pan in each direction
- const canPanLeft = useCallback((chartType: 'data' | 'results') => {
- const currentZoom = chartType === 'data' ? dataChartZoom : resultsChartZoom;
- return currentZoom !== null && currentZoom.startIndex > 0;
- }, [dataChartZoom, resultsChartZoom]);
-
- const canPanRight = useCallback((chartType: 'data' | 'results') => {
- const currentZoom = chartType === 'data' ? dataChartZoom : resultsChartZoom;
- const dataLength = chartType === 'results' && analysisResult ?
- getResultChartDataLength() : priceData.length;
- return currentZoom !== null && currentZoom.endIndex < dataLength - 1;
- }, [dataChartZoom, resultsChartZoom, priceData.length, analysisResult]);
-
- const getResultChartDataLength = useCallback(() => {
- if (!analysisResult?.result) return priceData.length;
- if (selectedAnalysis === 'forecasting') {
- const forecasts = (analysisResult.result as Record<string, unknown>).value as number[];
- return priceData.length + (forecasts?.length || 0);
- }
- if (selectedAnalysis === 'trend_analysis') {
- // Account for 5-period projection
- return priceData.length + 5;
- }
- if (selectedAnalysis === 'arima_model') {
- // Account for forecast projection (5 periods default or actual forecasts length)
- const result = analysisResult.result as Record<string, unknown>;
- const value = result.value as Record<string, unknown>;
- const forecasts = value?.forecasts as number[];
- return priceData.length + (forecasts?.length || 5);
- }
- return priceData.length;
- }, [analysisResult, priceData.length, selectedAnalysis]);
-
- // Mouse selection handlers for drag zoom
- const handleMouseDown = useCallback((e: any, chartType: 'data' | 'results') => {
- const activeLabel = typeof e.activeLabel === 'string' ? parseInt(e.activeLabel, 10) : e.activeLabel;
- if (activeLabel !== undefined && !isNaN(activeLabel)) {
- setRefAreaLeft(activeLabel);
- setIsSelecting(true);
- setActiveChart(chartType);
- }
- }, []);
-
- const handleMouseMove = useCallback((e: any) => {
- const activeLabel = typeof e.activeLabel === 'string' ? parseInt(e.activeLabel, 10) : e.activeLabel;
- if (isSelecting && activeLabel !== undefined && !isNaN(activeLabel)) {
- setRefAreaRight(activeLabel);
- }
- }, [isSelecting]);
-
- const handleMouseUp = useCallback(() => {
- if (refAreaLeft !== null && refAreaRight !== null && activeChart) {
- const left = Math.min(refAreaLeft, refAreaRight);
- const right = Math.max(refAreaLeft, refAreaRight);
-
- if (right - left >= 2) {
- const setZoom = activeChart === 'data' ? setDataChartZoom : setResultsChartZoom;
- setZoom({ startIndex: left, endIndex: right });
- }
- }
- setRefAreaLeft(null);
- setRefAreaRight(null);
- setIsSelecting(false);
- setActiveChart(null);
- }, [refAreaLeft, refAreaRight, activeChart]);
-
- // Mouse wheel handler for zoom and horizontal scroll
- const handleWheel = useCallback((e: React.WheelEvent, chartType: 'data' | 'results') => {
- e.preventDefault();
-
- // Shift + wheel = horizontal pan
- if (e.shiftKey) {
- if (e.deltaY > 0) {
- handlePanRight(chartType);
- } else if (e.deltaY < 0) {
- handlePanLeft(chartType);
- }
- return;
- }
-
- // Ctrl + wheel = zoom in/out
- if (e.ctrlKey || e.metaKey) {
- if (e.deltaY < 0) {
- handleZoomIn(chartType);
- } else if (e.deltaY > 0) {
- handleZoomOut(chartType);
- }
- return;
- }
-
- // Plain wheel = horizontal pan (more intuitive for time series)
- if (e.deltaY > 0) {
- handlePanRight(chartType);
- } else if (e.deltaY < 0) {
- handlePanLeft(chartType);
- }
- }, [handlePanLeft, handlePanRight, handleZoomIn, handleZoomOut]);
-
- const calculateStats = useCallback((data: number[]) => {
- if (data.length === 0) return null;
- const mean = data.reduce((a, b) => a + b, 0) / data.length;
- const variance = data.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / data.length;
- const first = data[0];
- const last = data[data.length - 1];
- const change = last - first;
- const changePercent = (change / first) * 100;
- return {
- min: Math.min(...data),
- max: Math.max(...data),
- mean,
- std: Math.sqrt(variance),
- change,
- changePercent,
- };
- }, []);
-
- const chartData = useMemo(() => {
- return priceData.map((value, index) => ({
- index,
- value,
- date: priceDates[index] || `Day ${index + 1}`,
- }));
- }, [priceData, priceDates]);
-
- // Helper to get date for a given index
- const getDateForIndex = useCallback((index: number): string => {
- if (index >= 0 && index < priceDates.length) {
- return priceDates[index];
- }
- return `Day ${index + 1}`;
- }, [priceDates]);
-
- // Zoomed chart data for data step
- const zoomedChartData = useMemo(() => {
- if (!dataChartZoom) return chartData;
- return chartData.slice(dataChartZoom.startIndex, dataChartZoom.endIndex + 1);
- }, [chartData, dataChartZoom]);
-
- // Zoom controls component with navigation
- const ZoomControls = ({ chartType, isZoomed }: { chartType: 'data' | 'results'; isZoomed: boolean }) => {
- const canGoLeft = canPanLeft(chartType);
- const canGoRight = canPanRight(chartType);
-
- return (
- <div className="flex items-center gap-1">
- {/* Pan Left */}
- <button
- onClick={() => handlePanLeft(chartType)}
- disabled={!canGoLeft}
- className="p-1.5 transition-colors hover:opacity-80"
- style={{
- backgroundColor: BB.cardBg,
- border: `1px solid ${BB.borderDark}`,
- opacity: canGoLeft ? 1 : 0.4,
- cursor: canGoLeft ? 'pointer' : 'not-allowed'
- }}
- title="Pan Left"
- >
- <ChevronLeft size={14} style={{ color: canGoLeft ? BB.amber : BB.textSecondary }} />
- </button>
- {/* Zoom In */}
- <button
- onClick={() => handleZoomIn(chartType)}
- className="p-1.5 transition-colors hover:opacity-80"
- style={{ backgroundColor: BB.cardBg, border: `1px solid ${BB.borderDark}` }}
- title="Zoom In"
- >
- <ZoomIn size={14} style={{ color: BB.textSecondary }} />
- </button>
- {/* Zoom Out */}
- <button
- onClick={() => handleZoomOut(chartType)}
- disabled={!isZoomed}
- className="p-1.5 transition-colors hover:opacity-80"
- style={{
- backgroundColor: BB.cardBg,
- border: `1px solid ${BB.borderDark}`,
- opacity: isZoomed ? 1 : 0.4,
- cursor: isZoomed ? 'pointer' : 'not-allowed'
- }}
- title="Zoom Out"
- >
- <ZoomOut size={14} style={{ color: BB.textSecondary }} />
- </button>
- {/* Reset */}
- <button
- onClick={() => handleResetZoom(chartType)}
- disabled={!isZoomed}
- className="p-1.5 transition-colors hover:opacity-80"
- style={{
- backgroundColor: BB.cardBg,
- border: `1px solid ${BB.borderDark}`,
- opacity: isZoomed ? 1 : 0.4,
- cursor: isZoomed ? 'pointer' : 'not-allowed'
- }}
- title="Reset Zoom"
- >
- <RotateCcw size={14} style={{ color: BB.textSecondary }} />
- </button>
- {/* Pan Right */}
- <button
- onClick={() => handlePanRight(chartType)}
- disabled={!canGoRight}
- className="p-1.5 transition-colors hover:opacity-80"
- style={{
- backgroundColor: BB.cardBg,
- border: `1px solid ${BB.borderDark}`,
- opacity: canGoRight ? 1 : 0.4,
- cursor: canGoRight ? 'pointer' : 'not-allowed'
- }}
- title="Pan Right"
- >
- <ChevronRight size={14} style={{ color: canGoRight ? BB.amber : BB.textSecondary }} />
- </button>
- </div>
- );
- };
-
- const fetchSymbolData = useCallback(async () => {
- if (!symbolInput.trim()) return;
-
- setPriceDataLoading(true);
- setError(null);
-
- try {
- const endDate = new Date();
- const startDate = new Date();
- startDate.setDate(startDate.getDate() - historicalDays);
-
- const data = await yfinanceService.getHistoricalData(
- symbolInput.toUpperCase(),
- startDate.toISOString().split('T')[0],
- endDate.toISOString().split('T')[0]
- );
-
- if (data && data.length > 0) {
- const closes = data.map(d => d.close);
- const dates = data.map(d => {
- const date = new Date(d.timestamp);
- return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: '2-digit' });
- });
- setPriceData(closes);
- setPriceDates(dates);
- setDataStats(calculateStats(closes));
- setDataChartZoom(null); // Reset zoom when new data loads
- } else {
- setError('No data returned for symbol');
- }
- } catch (err) {
- setError(`Failed to fetch data: ${err}`);
- } finally {
- setPriceDataLoading(false);
- }
- }, [symbolInput, historicalDays, calculateStats]);
-
- useEffect(() => {
- if (dataSourceType === 'manual' && manualData) {
- const parsed = manualData.split(',').map(v => parseFloat(v.trim())).filter(v => !isNaN(v));
- setPriceData(parsed);
- setDataStats(calculateStats(parsed));
- }
- }, [manualData, dataSourceType, calculateStats]);
-
- const getDataArray = (): number[] => {
- if (dataSourceType === 'manual') {
- return manualData.split(',').map(v => parseFloat(v.trim())).filter(v => !isNaN(v));
- }
- return priceData;
- };
-
- const runAnalysis = async () => {
- setIsLoading(true);
- setError(null);
- setAnalysisResult(null);
-
- try {
- const data = getDataArray();
- const config = analysisConfigs.find(a => a.id === selectedAnalysis);
-
- if (data.length === 0) {
- setError('No data available');
- setIsLoading(false);
- return;
- }
-
- if (config && data.length < config.minDataPoints) {
- setError(`Need ${config.minDataPoints} data points (have ${data.length})`);
- setIsLoading(false);
- return;
- }
-
- const params: Record<string, unknown> = { data };
- const result = await quantAnalyticsService.executeCustomCommand(selectedAnalysis, params);
- setAnalysisResult(result as QuantAnalyticsResult<Record<string, unknown>>);
-
- if (result.success) {
- setCurrentStep('results');
- } else if (result.error) {
- setError(result.error);
- }
- } catch (err) {
- setError(`Analysis failed: ${err}`);
- } finally {
- setIsLoading(false);
- }
- };
-
- const exportResults = () => {
- if (!analysisResult) return;
- const content = JSON.stringify(analysisResult, null, 2);
- const blob = new Blob([content], { type: 'application/json' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.href = url;
- a.download = `${selectedAnalysis}_${symbolInput}_results.json`;
- a.click();
- URL.revokeObjectURL(url);
- };
-
- const copyToClipboard = (text: string) => {
- navigator.clipboard.writeText(text);
- };
-
- const formatNumber = (val: number, decimals = 4): string => {
- if (val === null || val === undefined || isNaN(val)) return '—';
- return val.toFixed(decimals);
- };
-
- const formatPrice = (val: number): string => {
- if (val === null || val === undefined || isNaN(val)) return '—';
- return val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
- };
-
- // Fincept-style header
- const renderHeader = () => (
- <div className="flex items-center justify-between px-4 py-2" style={{ backgroundColor: BB.black, borderBottom: `1px solid ${BB.borderDark}` }}>
- <div className="flex items-center gap-4">
- <div className="flex items-center gap-2">
- <Activity size={18} style={{ color: BB.amber }} />
- <span className="text-sm font-bold tracking-wider" style={{ color: BB.textAmber }}>CFA QUANT ANALYTICS</span>
- </div>
- <div className="h-4 w-px" style={{ backgroundColor: BB.borderLight }} />
- <div className="flex items-center gap-2">
- {(['data', 'analysis', 'results'] as Step[]).map((step, idx) => {
- const isActive = currentStep === step;
- const isPast = ['data', 'analysis', 'results'].indexOf(currentStep) > idx;
- const labels = { data: '1 DATA', analysis: '2 MODEL', results: '3 OUTPUT' };
- return (
- <React.Fragment key={step}>
- <button
- onClick={() => {
- if (step === 'results' && !analysisResult) return;
- setCurrentStep(step);
- }}
- className="px-3 py-1 text-xs font-mono transition-colors"
- style={{
- backgroundColor: isActive ? BB.amber : 'transparent',
- color: isActive ? BB.black : isPast ? BB.textAmber : BB.textMuted,
- cursor: step === 'results' && !analysisResult ? 'not-allowed' : 'pointer',
- }}
- >
- {labels[step]}
- </button>
- {idx < 2 && <span style={{ color: BB.textMuted }}>›</span>}
- </React.Fragment>
- );
- })}
- </div>
- </div>
- {dataSourceType === 'symbol' && symbolInput && (
- <div className="flex items-center gap-3">
- <span className="text-sm font-mono font-bold" style={{ color: BB.textPrimary }}>{symbolInput.toUpperCase()}</span>
- {dataStats && (
- <>
- <span className="text-sm font-mono" style={{ color: BB.textSecondary }}>{formatPrice(dataStats.mean)}</span>
- <span className="text-sm font-mono" style={{ color: dataStats.changePercent >= 0 ? BB.green : BB.red }}>
- {dataStats.changePercent >= 0 ? '▲' : '▼'} {Math.abs(dataStats.changePercent).toFixed(2)}%
- </span>
- </>
- )}
- </div>
- )}
- </div>
- );
-
- // Data Step - Fincept style
- const renderDataStep = () => (
- <div className="flex h-full">
- {/* Left Panel - Input Controls */}
- <div className="w-80 flex-shrink-0 p-4 overflow-y-auto" style={{ backgroundColor: BB.panelBg, borderRight: `1px solid ${BB.borderDark}` }}>
- <div className="mb-4">
- <div className="text-xs font-mono mb-2" style={{ color: BB.textAmber }}>DATA SOURCE</div>
- <div className="flex gap-2">
- <button
- onClick={() => setDataSourceType('symbol')}
- className="flex-1 px-3 py-2 text-xs font-mono transition-colors"
- style={{
- backgroundColor: dataSourceType === 'symbol' ? BB.amber : BB.cardBg,
- color: dataSourceType === 'symbol' ? BB.black : BB.textSecondary,
- border: `1px solid ${dataSourceType === 'symbol' ? BB.amber : BB.borderDark}`,
- }}
- >
- <Database size={14} className="inline mr-2" />
- MARKET
- </button>
- <button
- onClick={() => setDataSourceType('manual')}
- className="flex-1 px-3 py-2 text-xs font-mono transition-colors"
- style={{
- backgroundColor: dataSourceType === 'manual' ? BB.amber : BB.cardBg,
- color: dataSourceType === 'manual' ? BB.black : BB.textSecondary,
- border: `1px solid ${dataSourceType === 'manual' ? BB.amber : BB.borderDark}`,
- }}
- >
- <Calculator size={14} className="inline mr-2" />
- MANUAL
- </button>
- </div>
- </div>
-
- {dataSourceType === 'symbol' ? (
- <div className="space-y-4">
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: BB.textMuted }}>TICKER</label>
- <input
- type="text"
- value={symbolInput}
- onChange={(e) => setSymbolInput(e.target.value.toUpperCase())}
- placeholder="AAPL"
- className="w-full px-3 py-2 text-sm font-mono"
- style={{
- backgroundColor: BB.black,
- color: BB.textPrimary,
- border: `1px solid ${BB.borderLight}`,
- }}
- />
- </div>
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: BB.textMuted }}>LOOKBACK (DAYS)</label>
- <input
- type="number"
- value={historicalDays}
- onChange={(e) => setHistoricalDays(parseInt(e.target.value) || 365)}
- className="w-full px-3 py-2 text-sm font-mono"
- style={{
- backgroundColor: BB.black,
- color: BB.textPrimary,
- border: `1px solid ${BB.borderLight}`,
- }}
- />
- </div>
- <button
- onClick={fetchSymbolData}
- disabled={priceDataLoading}
- className="w-full py-2 text-sm font-mono font-bold flex items-center justify-center gap-2"
- style={{
- backgroundColor: BB.amber,
- color: BB.black,
- opacity: priceDataLoading ? 0.7 : 1,
- }}
- >
- {priceDataLoading ? (
- <>
- <RefreshCw size={14} className="animate-spin" />
- LOADING...
- </>
- ) : (
- <>
- <Search size={14} />
- FETCH DATA
- </>
- )}
- </button>
- </div>
- ) : (
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: BB.textMuted }}>VALUES (COMMA SEP)</label>
- <textarea
- value={manualData}
- onChange={(e) => setManualData(e.target.value)}
- placeholder="100, 102, 98, 105..."
- rows={8}
- className="w-full px-3 py-2 text-sm font-mono"
- style={{
- backgroundColor: BB.black,
- color: BB.textPrimary,
- border: `1px solid ${BB.borderLight}`,
- }}
- />
- </div>
- )}
-
- {/* Statistics Panel */}
- {priceData.length > 0 && dataStats && (
- <div className="mt-4 p-3" style={{ backgroundColor: BB.cardBg, border: `1px solid ${BB.borderDark}` }}>
- <div className="text-xs font-mono mb-3" style={{ color: BB.textAmber }}>STATISTICS</div>
- <div className="grid grid-cols-2 gap-2 text-xs font-mono">
- <div>
- <div style={{ color: BB.textMuted }}>COUNT</div>
- <div style={{ color: BB.textPrimary }}>{priceData.length}</div>
- </div>
- <div>
- <div style={{ color: BB.textMuted }}>MEAN</div>
- <div style={{ color: BB.textPrimary }}>{formatPrice(dataStats.mean)}</div>
- </div>
- <div>
- <div style={{ color: BB.textMuted }}>LOW</div>
- <div style={{ color: BB.red }}>{formatPrice(dataStats.min)}</div>
- </div>
- <div>
- <div style={{ color: BB.textMuted }}>HIGH</div>
- <div style={{ color: BB.green }}>{formatPrice(dataStats.max)}</div>
- </div>
- <div>
- <div style={{ color: BB.textMuted }}>STD DEV</div>
- <div style={{ color: BB.textPrimary }}>{formatNumber(dataStats.std, 2)}</div>
- </div>
- <div>
- <div style={{ color: BB.textMuted }}>CHANGE</div>
- <div style={{ color: dataStats.changePercent >= 0 ? BB.green : BB.red }}>
- {dataStats.changePercent >= 0 ? '+' : ''}{dataStats.changePercent.toFixed(2)}%
- </div>
- </div>
- </div>
- </div>
- )}
-
- {error && (
- <div className="mt-4 p-3 text-xs font-mono" style={{ backgroundColor: `${BB.red}20`, border: `1px solid ${BB.red}`, color: BB.red }}>
- <AlertCircle size={14} className="inline mr-2" />
- {error}
- </div>
- )}
-
- <button
- onClick={() => setCurrentStep('analysis')}
- disabled={priceData.length === 0}
- className="w-full mt-4 py-2 text-sm font-mono font-bold flex items-center justify-center gap-2"
- style={{
- backgroundColor: priceData.length > 0 ? BB.green : BB.cardBg,
- color: priceData.length > 0 ? BB.black : BB.textMuted,
- cursor: priceData.length > 0 ? 'pointer' : 'not-allowed',
- }}
- >
- CONTINUE <ChevronRight size={14} />
- </button>
- </div>
-
- {/* Right Panel - Chart */}
- <div className="flex-1 p-4" style={{ backgroundColor: BB.darkBg }}>
- {priceData.length > 0 ? (
- <div className="h-full flex flex-col">
- <div className="flex items-center justify-between mb-2">
- <div className="flex items-center gap-3">
- <div className="text-xs font-mono" style={{ color: BB.textAmber }}>PRICE CHART</div>
- {dataChartZoom && (
- <div className="text-xs font-mono px-2 py-0.5" style={{ backgroundColor: BB.amber + '20', color: BB.amber }}>
- {getDateForIndex(dataChartZoom.startIndex)} - {getDateForIndex(dataChartZoom.endIndex)}
- </div>
- )}
- </div>
- <div className="flex items-center gap-3">
- <ZoomControls chartType="data" isZoomed={dataChartZoom !== null} />
- <div className="text-xs font-mono" style={{ color: BB.textMuted }}>{priceData.length} POINTS</div>
- </div>
- </div>
- <div
- className="flex-1"
- style={{ minHeight: 300 }}
- onWheel={(e) => handleWheel(e, 'data')}
- >
- <ResponsiveContainer width="100%" height="100%">
- <AreaChart
- data={zoomedChartData}
- margin={{ top: 10, right: 10, left: 0, bottom: 30 }}
- onMouseDown={(e) => handleMouseDown(e, 'data')}
- onMouseMove={handleMouseMove}
- onMouseUp={handleMouseUp}
- onMouseLeave={handleMouseUp}
- >
- <defs>
- <linearGradient id="colorValue" x1="0" y1="0" x2="0" y2="1">
- <stop offset="5%" stopColor={dataStats && dataStats.changePercent >= 0 ? BB.green : BB.red} stopOpacity={0.3}/>
- <stop offset="95%" stopColor={dataStats && dataStats.changePercent >= 0 ? BB.green : BB.red} stopOpacity={0}/>
- </linearGradient>
- </defs>
- <CartesianGrid strokeDasharray="3 3" stroke={BB.chartGrid} />
- <XAxis
- dataKey="date"
- tick={{ fill: BB.textMuted, fontSize: 9 }}
- axisLine={{ stroke: BB.borderDark }}
- tickLine={{ stroke: BB.borderDark }}
- interval="preserveStartEnd"
- />
- <YAxis
- tick={{ fill: BB.textMuted, fontSize: 10 }}
- axisLine={{ stroke: BB.borderDark }}
- tickLine={{ stroke: BB.borderDark }}
- domain={['auto', 'auto']}
- tickFormatter={(val) => formatPrice(val)}
- />
- <Tooltip
- contentStyle={{
- backgroundColor: BB.cardBg,
- border: `1px solid ${BB.borderLight}`,
- borderRadius: 0,
- }}
- labelFormatter={(label) => `Date: ${label}`}
- labelStyle={{ color: BB.textAmber, fontSize: 11, fontWeight: 'bold' }}
- itemStyle={{ color: BB.textPrimary, fontSize: 12 }}
- formatter={(value: number) => [formatPrice(value), 'Price']}
- />
- <ReferenceLine y={dataStats?.mean} stroke={BB.amber} strokeDasharray="5 5" />
- <Area
- type="monotone"
- dataKey="value"
- stroke={dataStats && dataStats.changePercent >= 0 ? BB.green : BB.red}
- fillOpacity={1}
- fill="url(#colorValue)"
- strokeWidth={1.5}
- />
- {/* Brush for horizontal pan/zoom */}
- {!dataChartZoom && (
- <Brush
- dataKey="index"
- height={20}
- stroke={BB.amber}
- fill={BB.cardBg}
- tickFormatter={(val) => `${val}`}
- onChange={(e) => {
- if (e.startIndex !== undefined && e.endIndex !== undefined && e.startIndex !== e.endIndex) {
- setDataChartZoom({ startIndex: e.startIndex, endIndex: e.endIndex });
- }
- }}
- />
- )}
- {/* Selection area indicator */}
- {isSelecting && activeChart === 'data' && refAreaLeft !== null && refAreaRight !== null && (
- <ReferenceArea
- x1={refAreaLeft}
- x2={refAreaRight}
- strokeOpacity={0.3}
- fill={BB.amber}
- fillOpacity={0.2}
- />
- )}
- </AreaChart>
- </ResponsiveContainer>
- </div>
- <div className="text-xs font-mono mt-1 text-center" style={{ color: BB.textMuted }}>
- Scroll to pan | Ctrl+Scroll to zoom | Drag to select range
- </div>
- </div>
- ) : (
- <div className="h-full flex items-center justify-center">
- <div className="text-center">
- <Database size={48} style={{ color: BB.textMuted, margin: '0 auto 16px' }} />
- <div className="text-sm font-mono" style={{ color: BB.textMuted }}>NO DATA LOADED</div>
- <div className="text-xs font-mono mt-1" style={{ color: BB.textMuted }}>Fetch market data or enter values manually</div>
- </div>
- </div>
- )}
- </div>
- </div>
- );
-
- // Analysis Step - Fincept style
- const renderAnalysisStep = () => {
- const selectedConfig = analysisConfigs.find(a => a.id === selectedAnalysis);
- const canRun = priceData.length >= (selectedConfig?.minDataPoints || 0);
-
- return (
- <div className="flex h-full">
- {/* Left Panel - Analysis Selection */}
- <div className="w-80 flex-shrink-0 p-4 overflow-y-auto" style={{ backgroundColor: BB.panelBg, borderRight: `1px solid ${BB.borderDark}` }}>
- <div className="text-xs font-mono mb-3" style={{ color: BB.textAmber }}>SELECT MODEL</div>
-
- <div className="space-y-1">
- {analysisConfigs.map((config) => {
- const isSelected = selectedAnalysis === config.id;
- const hasEnoughData = priceData.length >= config.minDataPoints;
- const Icon = config.icon;
-
- return (
- <button
- key={config.id}
- onClick={() => hasEnoughData && setSelectedAnalysis(config.id)}
- className="w-full px-3 py-2 text-left flex items-center gap-3 transition-colors"
- style={{
- backgroundColor: isSelected ? BB.cardBg : 'transparent',
- borderLeft: `3px solid ${isSelected ? config.color : 'transparent'}`,
- opacity: hasEnoughData ? 1 : 0.4,
- cursor: hasEnoughData ? 'pointer' : 'not-allowed',
- }}
- >
- <Icon size={16} style={{ color: config.color }} />
- <div className="flex-1 min-w-0">
- <div className="text-xs font-mono font-bold" style={{ color: BB.textPrimary }}>{config.shortName}</div>
- <div className="text-xs font-mono truncate" style={{ color: BB.textMuted }}>{config.name}</div>
- </div>
- {!hasEnoughData && (
- <span className="text-xs font-mono" style={{ color: BB.red }}>
- {config.minDataPoints}+
- </span>
- )}
- </button>
- );
- })}
- </div>
-
- <div className="mt-4 flex gap-2">
- <button
- onClick={() => setCurrentStep('data')}
- className="flex-1 py-2 text-xs font-mono"
- style={{ backgroundColor: BB.cardBg, color: BB.textSecondary, border: `1px solid ${BB.borderDark}` }}
- >
- <ChevronLeft size={12} className="inline" /> BACK
- </button>
- <button
- onClick={runAnalysis}
- disabled={isLoading || !canRun}
- className="flex-1 py-2 text-xs font-mono font-bold"
- style={{
- backgroundColor: canRun ? BB.green : BB.cardBg,
- color: canRun ? BB.black : BB.textMuted,
- cursor: canRun ? 'pointer' : 'not-allowed',
- }}
- >
- {isLoading ? 'RUNNING...' : 'RUN'} <Zap size={12} className="inline ml-1" />
- </button>
- </div>
-
- {error && (
- <div className="mt-4 p-3 text-xs font-mono" style={{ backgroundColor: `${BB.red}20`, border: `1px solid ${BB.red}`, color: BB.red }}>
- {error}
- </div>
- )}
- </div>
-
- {/* Right Panel - Model Details */}
- <div className="flex-1 p-4" style={{ backgroundColor: BB.darkBg }}>
- {selectedConfig && (
- <div className="h-full flex flex-col">
- <div className="mb-4 p-4" style={{ backgroundColor: BB.cardBg, border: `1px solid ${BB.borderDark}` }}>
- <div className="flex items-center gap-3 mb-3">
- <div className="p-2" style={{ backgroundColor: `${selectedConfig.color}20` }}>
- <selectedConfig.icon size={24} style={{ color: selectedConfig.color }} />
- </div>
- <div>
- <div className="text-sm font-mono font-bold" style={{ color: BB.textPrimary }}>{selectedConfig.name}</div>
- <div className="text-xs font-mono" style={{ color: BB.textMuted }}>{selectedConfig.category.replace('_', ' ').toUpperCase()}</div>
- </div>
- </div>
- <div className="text-xs font-mono" style={{ color: BB.textSecondary }}>{selectedConfig.helpText}</div>
-
- <div className="mt-3 flex items-center gap-4 text-xs font-mono">
- <div>
- <span style={{ color: BB.textMuted }}>MIN POINTS: </span>
- <span style={{ color: priceData.length >= selectedConfig.minDataPoints ? BB.green : BB.red }}>
- {selectedConfig.minDataPoints}
- </span>
- </div>
- <div>
- <span style={{ color: BB.textMuted }}>YOUR DATA: </span>
- <span style={{ color: BB.textPrimary }}>{priceData.length}</span>
- </div>
- </div>
- </div>
-
- {/* Mini Chart Preview */}
- <div className="flex-1" style={{ minHeight: 200 }}>
- <div className="flex items-center justify-between mb-2">
- <div className="text-xs font-mono" style={{ color: BB.textAmber }}>DATA PREVIEW</div>
- {dataChartZoom && (
- <button
- onClick={() => setDataChartZoom(null)}
- className="text-xs font-mono px-2 py-0.5 flex items-center gap-1"
- style={{ backgroundColor: BB.cardBg, color: BB.textMuted, border: `1px solid ${BB.borderDark}` }}
- >
- <RotateCcw size={10} /> RESET ZOOM
- </button>
- )}
- </div>
- <ResponsiveContainer width="100%" height="100%">
- <RechartsLineChart data={zoomedChartData} margin={{ top: 5, right: 5, left: 0, bottom: 5 }}>
- <CartesianGrid strokeDasharray="3 3" stroke={BB.chartGrid} />
- <XAxis dataKey="index" hide />
- <YAxis hide domain={['auto', 'auto']} />
- <Line
- type="monotone"
- dataKey="value"
- stroke={selectedConfig.color}
- dot={false}
- strokeWidth={1.5}
- />
- </RechartsLineChart>
- </ResponsiveContainer>
- </div>
- </div>
- )}
- </div>
- </div>
- );
- };
-
- // Results Step - Fincept style
- const renderResultsStep = () => {
- if (!analysisResult?.result) return null;
-
- const config = analysisConfigs.find(a => a.id === selectedAnalysis);
- const result = analysisResult.result as Record<string, unknown>;
-
- // Extract key metrics based on analysis type
- const getKeyMetrics = () => {
- const metrics: { label: string; value: string; color: string; icon?: React.ElementType }[] = [];
-
- if (selectedAnalysis === 'trend_analysis' && result.metadata) {
- const meta = result.metadata as Record<string, unknown>;
- const value = result.value as Record<string, unknown>;
- const slope = value?.slope as number;
- const intercept = value?.intercept as number;
- const rSquared = meta?.r_squared as number;
- const significant = meta?.trend_significant as boolean;
- const direction = meta?.trend_direction as string;
- const pValue = meta?.slope_p_value as number;
- const tStat = meta?.slope_t_statistic as number;
-
- // Main result - direction with icon
- metrics.push({
- label: 'DIRECTION',
- value: direction === 'upward' ? 'UP' : direction === 'downward' ? 'DOWN' : 'FLAT',
- color: direction === 'upward' ? BB.green : direction === 'downward' ? BB.red : BB.textMuted,
- icon: direction === 'upward' ? ArrowUpRight : direction === 'downward' ? ArrowDownRight : Minus,
- });
-
- // Statistical significance
- metrics.push({
- label: 'SIGNIFICANT',
- value: significant ? 'YES' : 'NO',
- color: significant ? BB.green : BB.textMuted,
- icon: significant ? CheckCircle2 : undefined
- });
-
- // Model fit
- metrics.push({
- label: 'R-SQUARED',
- value: `${(rSquared * 100).toFixed(1)}%`,
- color: rSquared > 0.7 ? BB.green : rSquared > 0.4 ? BB.amber : BB.textMuted
- });
-
- // P-value with color coding
- if (pValue !== undefined && pValue !== null) {
- metrics.push({
- label: 'P-VALUE',
- value: pValue < 0.001 ? '<0.001' : formatNumber(pValue, 4),
- color: pValue < 0.01 ? BB.green : pValue < 0.05 ? BB.greenDim : pValue < 0.1 ? BB.amber : BB.red
- });
- }
-
- // T-statistic
- if (tStat !== undefined && tStat !== null) {
- metrics.push({
- label: 'T-STATISTIC',
- value: formatNumber(tStat, 2),
- color: Math.abs(tStat) > 2 ? BB.green : BB.textMuted
- });
- }
-
- // Regression parameters
- metrics.push({ label: 'SLOPE', value: formatNumber(slope, 6), color: BB.textPrimary });
- if (intercept !== undefined && intercept !== null) {
- metrics.push({ label: 'INTERCEPT', value: formatNumber(intercept, 2), color: BB.textSecondary });
- }
- } else if (selectedAnalysis === 'stationarity_test' && result.value) {
- const value = result.value as Record<string, unknown>;
- const meta = result.metadata as Record<string, unknown>;
- const isStationary = value?.is_stationary as boolean;
- const pValue = value?.p_value as number;
- const testStat = value?.test_statistic as number;
- const criticalValues = value?.critical_values as Record<string, number>;
- const nullHypothesis = value?.null_hypothesis as string;
-
- // Main result
- metrics.push({
- label: 'STATIONARY',
- value: isStationary ? 'YES' : 'NO',
- color: isStationary ? BB.green : BB.red,
- icon: isStationary ? CheckCircle2 : AlertCircle
- });
-
- // Test statistics
- metrics.push({ label: 'TEST STAT', value: formatNumber(testStat, 4), color: BB.textPrimary });
- metrics.push({
- label: 'P-VALUE',
- value: formatNumber(pValue, 4),
- color: pValue < 0.01 ? BB.green : pValue < 0.05 ? BB.greenDim : pValue < 0.1 ? BB.amber : BB.red
- });
-
- // Critical values comparison
- if (criticalValues) {
- const cv1 = criticalValues['1%'];
- const cv5 = criticalValues['5%'];
- const cv10 = criticalValues['10%'];
-
- if (cv1 !== undefined) {
- const beats1 = testStat < cv1;
- metrics.push({ label: 'CV 1%', value: `${formatNumber(cv1, 2)} ${beats1 ? 'PASS' : ''}`, color: beats1 ? BB.green : BB.textMuted });
- }
- if (cv5 !== undefined) {
- const beats5 = testStat < cv5;
- metrics.push({ label: 'CV 5%', value: `${formatNumber(cv5, 2)} ${beats5 ? 'PASS' : ''}`, color: beats5 ? BB.green : BB.textMuted });
- }
- if (cv10 !== undefined) {
- const beats10 = testStat < cv10;
- metrics.push({ label: 'CV 10%', value: `${formatNumber(cv10, 2)} ${beats10 ? 'PASS' : ''}`, color: beats10 ? BB.amber : BB.textMuted });
- }
- }
-
- // Metadata - stability measures
- if (meta) {
- const rollingMeanStability = meta.rolling_mean_stability as number;
- const rollingStdStability = meta.rolling_std_stability as number;
- const meanReversionStrength = meta.mean_reversion_strength as number;
-
- if (rollingMeanStability !== undefined) {
- metrics.push({
- label: 'MEAN STABILITY',
- value: formatNumber(rollingMeanStability, 2),
- color: rollingMeanStability < 1 ? BB.green : rollingMeanStability < 5 ? BB.amber : BB.red
- });
- }
- if (rollingStdStability !== undefined) {
- metrics.push({
- label: 'VOL STABILITY',
- value: formatNumber(rollingStdStability, 2),
- color: rollingStdStability < 0.5 ? BB.green : rollingStdStability < 2 ? BB.amber : BB.red
- });
- }
- if (meanReversionStrength !== undefined) {
- metrics.push({
- label: 'MEAN REVERSION',
- value: `${(meanReversionStrength * 100).toFixed(1)}%`,
- color: meanReversionStrength > 0.3 ? BB.green : meanReversionStrength > 0.1 ? BB.amber : BB.textMuted
- });
- }
- }
- } else if (selectedAnalysis === 'arima_model' && result.metadata) {
- const meta = result.metadata as Record<string, unknown>;
- const params = result.parameters as Record<string, unknown>;
- const value = result.value as Record<string, unknown>;
- const residuals = value?.residuals as number[];
-
- // Model order
- const order = params?.order as number[];
- if (order && order.length === 3) {
- metrics.push({
- label: 'MODEL ORDER',
- value: `(${order[0]},${order[1]},${order[2]})`,
- color: BB.amber
- });
- }
-
- // Seasonal order if present
- const seasonalOrder = params?.seasonal_order as number[];
- if (seasonalOrder && seasonalOrder.length === 4) {
- metrics.push({
- label: 'SEASONAL',
- value: `(${seasonalOrder[0]},${seasonalOrder[1]},${seasonalOrder[2]},${seasonalOrder[3]})`,
- color: BB.blueLight
- });
- }
-
- // Information criteria (lower is better)
- const aic = meta?.aic as number;
- const bic = meta?.bic as number;
- metrics.push({ label: 'AIC', value: formatNumber(aic, 2), color: BB.textPrimary });
- metrics.push({ label: 'BIC', value: formatNumber(bic, 2), color: BB.textPrimary });
-
- // Log-likelihood
- const logLik = meta?.log_likelihood as number;
- if (logLik !== undefined && logLik !== null) {
- metrics.push({ label: 'LOG-LIKELIHOOD', value: formatNumber(logLik, 2), color: BB.textSecondary });
- }
-
- // Ljung-Box test for residual autocorrelation
- const ljungBoxPValue = meta?.ljung_box_p_value as number;
- const residualsAutocorrelated = meta?.residuals_autocorrelated as boolean;
-
- metrics.push({
- label: 'RESIDUALS OK',
- value: !residualsAutocorrelated ? 'YES' : 'NO',
- color: !residualsAutocorrelated ? BB.green : BB.red,
- icon: !residualsAutocorrelated ? CheckCircle2 : AlertCircle
- });
-
- if (ljungBoxPValue !== undefined && ljungBoxPValue !== null) {
- metrics.push({
- label: 'LJUNG-BOX P',
- value: formatNumber(ljungBoxPValue, 4),
- color: ljungBoxPValue > 0.05 ? BB.green : ljungBoxPValue > 0.01 ? BB.amber : BB.red
- });
- }
-
- // Residual statistics
- if (residuals && residuals.length > 0) {
- const residMean = residuals.reduce((a, b) => a + b, 0) / residuals.length;
- const residStd = Math.sqrt(residuals.reduce((a, b) => a + Math.pow(b - residMean, 2), 0) / residuals.length);
- metrics.push({ label: 'RESID MEAN', value: formatNumber(residMean, 4), color: Math.abs(residMean) < 0.01 ? BB.green : BB.textMuted });
- metrics.push({ label: 'RESID STD', value: formatNumber(residStd, 4), color: BB.textSecondary });
- }
- } else if (selectedAnalysis === 'forecasting' && result.metadata) {
- const meta = result.metadata as Record<string, unknown>;
- const params = result.parameters as Record<string, unknown>;
- const forecasts = result.value as number[];
- const trainSize = meta?.train_data_size as number;
- const testSize = meta?.test_data_size as number;
- const horizon = meta?.forecast_horizon as number;
- const method = params?.method as string;
- const mae = meta?.mae as number;
- const rmse = meta?.rmse as number;
- const mape = meta?.mape as number;
-
- // Method with icon
- if (method) {
- const methodLabels: Record<string, string> = {
- 'simple_exponential': 'EXP SMOOTH',
- 'linear_trend': 'LINEAR TREND',
- 'moving_average': 'MOVING AVG'
- };
- const methodDescriptions: Record<string, string> = {
- 'simple_exponential': 'Level',
- 'linear_trend': 'Trend',
- 'moving_average': 'Average'
- };
- metrics.push({
- label: 'METHOD',
- value: methodLabels[method] || method.toUpperCase(),
- color: BB.amber,
- icon: method === 'linear_trend' ? TrendingUp : method === 'simple_exponential' ? Sparkles : Activity
- });
- metrics.push({ label: 'MODEL TYPE', value: methodDescriptions[method] || 'Custom', color: BB.textSecondary });
- }
-
- // Forecast accuracy rating based on MAPE
- if (mape !== undefined && mape !== null) {
- let accuracy = 'EXCELLENT';
- let accuracyColor = BB.green;
- if (mape > 30) { accuracy = 'POOR'; accuracyColor = BB.red; }
- else if (mape > 20) { accuracy = 'FAIR'; accuracyColor = BB.amber; }
- else if (mape > 10) { accuracy = 'GOOD'; accuracyColor = BB.greenDim; }
- metrics.push({ label: 'ACCURACY', value: accuracy, color: accuracyColor, icon: mape <= 10 ? CheckCircle2 : mape <= 20 ? AlertCircle : undefined });
- }
-
- // Forecast value info
- if (forecasts && forecasts.length > 0) {
- const forecastValue = forecasts[0];
- metrics.push({ label: 'FORECAST VALUE', value: formatPrice(forecastValue), color: BB.green });
-
- // If we have test data, show comparison
- if (testSize > 0 && priceData.length > 0) {
- const testStartIdx = trainSize;
- const lastActual = priceData[priceData.length - 1];
- const diff = forecastValue - lastActual;
- const diffPct = (diff / lastActual) * 100;
- metrics.push({
- label: 'VS LAST ACTUAL',
- value: `${diffPct >= 0 ? '+' : ''}${diffPct.toFixed(2)}%`,
- color: diffPct >= 0 ? BB.green : BB.red,
- icon: diffPct >= 0 ? ArrowUpRight : ArrowDownRight
- });
- }
- }
-
- // Data split info with visual representation
- if (trainSize && testSize) {
- const trainPct = ((trainSize / (trainSize + testSize)) * 100).toFixed(0);
- metrics.push({ label: 'TRAIN/TEST', value: `${trainPct}/${100 - parseInt(trainPct)}%`, color: BB.blueLight });
- }
- if (trainSize) metrics.push({ label: 'TRAIN SIZE', value: String(trainSize), color: BB.textSecondary });
- if (testSize) metrics.push({ label: 'TEST SIZE', value: String(testSize), color: BB.textSecondary });
- if (horizon) metrics.push({ label: 'HORIZON', value: `${horizon} periods`, color: BB.green });
-
- // Accuracy metrics with color coding
- if (mae !== undefined && mae !== null) {
- metrics.push({ label: 'MAE', value: formatNumber(mae, 2), color: BB.textPrimary });
- }
- if (rmse !== undefined && rmse !== null) {
- metrics.push({ label: 'RMSE', value: formatNumber(rmse, 2), color: BB.textPrimary });
- // RMSE to MAE ratio (closer to 1 means less outliers)
- if (mae !== undefined && mae !== null && mae > 0) {
- const rmseToMae = rmse / mae;
- metrics.push({
- label: 'RMSE/MAE',
- value: formatNumber(rmseToMae, 2),
- color: rmseToMae < 1.2 ? BB.green : rmseToMae < 1.5 ? BB.amber : BB.red
- });
- }
- }
- if (mape !== undefined && mape !== null) {
- metrics.push({
- label: 'MAPE',
- value: `${formatNumber(mape, 2)}%`,
- color: mape < 10 ? BB.green : mape < 20 ? BB.amber : BB.red
- });
- }
- } else if (selectedAnalysis === 'supervised_learning' && result.value) {
- const meta = result.metadata as Record<string, unknown>;
- const value = result.value as Record<string, Record<string, unknown>>;
- const bestAlgo = meta?.best_algorithm as string;
- const nFeatures = meta?.n_features as number;
- const yTest = meta?.y_test as number[];
-
- // Best model highlight
- if (bestAlgo) {
- metrics.push({ label: 'BEST MODEL', value: bestAlgo.toUpperCase().replace('_', ' '), color: BB.green, icon: CheckCircle2 });
- }
-
- // Best model detailed metrics
- if (bestAlgo && value[bestAlgo]) {
- const bestResult = value[bestAlgo];
- if (bestResult.r2_score !== undefined) {
- const r2 = bestResult.r2_score as number;
- const r2Quality = r2 > 0.8 ? 'Excellent' : r2 > 0.6 ? 'Good' : r2 > 0.4 ? 'Fair' : 'Poor';
- metrics.push({ label: 'R² SCORE', value: `${(r2 * 100).toFixed(1)}%`, color: r2 > 0.7 ? BB.green : r2 > 0.5 ? BB.amber : BB.red });
- metrics.push({ label: 'FIT QUALITY', value: r2Quality.toUpperCase(), color: r2 > 0.7 ? BB.green : r2 > 0.5 ? BB.amber : BB.red });
- }
- if (bestResult.rmse !== undefined) {
- metrics.push({ label: 'RMSE', value: formatNumber(bestResult.rmse as number, 4), color: BB.textPrimary });
- }
- if (bestResult.mse !== undefined) {
- metrics.push({ label: 'MSE', value: formatNumber(bestResult.mse as number, 4), color: BB.textSecondary });
- }
- }
-
- // Compare all algorithms
- const algoNames = Object.keys(value).filter(k => !value[k].error);
- if (algoNames.length > 1) {
- metrics.push({ label: 'MODELS TESTED', value: String(algoNames.length), color: BB.blueLight });
-
- // Show comparison of R² scores
- algoNames.forEach(algo => {
- if (algo !== bestAlgo && value[algo]?.r2_score !== undefined) {
- const r2 = value[algo].r2_score as number;
- metrics.push({
- label: algo.toUpperCase().replace('_', ' ').substring(0, 12),
- value: `R²: ${(r2 * 100).toFixed(1)}%`,
- color: BB.textMuted
- });
- }
- });
- }
-
- // Data split info
- if (meta?.train_size) {
- metrics.push({ label: 'TRAIN SIZE', value: String(meta.train_size), color: BB.textMuted });
- }
- if (meta?.test_size) {
- metrics.push({ label: 'TEST SIZE', value: String(meta.test_size), color: BB.textMuted });
- }
- if (nFeatures) {
- metrics.push({ label: 'FEATURES', value: String(nFeatures), color: BB.textMuted });
- }
-
- // Calculate prediction error statistics if y_test is available
- if (yTest && bestAlgo && value[bestAlgo]?.predictions) {
- const predictions = value[bestAlgo].predictions as number[];
- if (predictions.length === yTest.length) {
- const errors = yTest.map((actual, i) => actual - predictions[i]);
- const meanError = errors.reduce((a, b) => a + b, 0) / errors.length;
- const maxAbsError = Math.max(...errors.map(Math.abs));
-
- metrics.push({ label: 'MEAN ERROR', value: formatNumber(meanError, 4), color: Math.abs(meanError) < 0.01 ? BB.green : BB.textMuted });
- metrics.push({ label: 'MAX |ERROR|', value: formatNumber(maxAbsError, 4), color: BB.textSecondary });
- }
- }
- } else if (selectedAnalysis === 'unsupervised_learning' && result.value) {
- const value = result.value as Record<string, Record<string, unknown>>;
- const meta = result.metadata as Record<string, unknown>;
-
- if (value.pca) {
- const pca = value.pca;
- const explainedVariance = pca.explained_variance_ratio as number[];
- const componentsFor95 = pca.components_for_95_variance as number;
-
- if (explainedVariance && explainedVariance.length > 0) {
- const firstComponentVar = (explainedVariance[0] * 100).toFixed(1);
- const totalComponents = explainedVariance.length;
- metrics.push({ label: 'PC1 VARIANCE', value: `${firstComponentVar}%`, color: BB.green });
- metrics.push({ label: 'COMPONENTS (95%)', value: String(componentsFor95), color: BB.amber });
- metrics.push({ label: 'TOTAL PCs', value: String(totalComponents), color: BB.textSecondary });
- }
- }
-
- if (value.kmeans) {
- const kmeans = value.kmeans;
- const optimalK = kmeans.optimal_k as number;
- const silhouetteByK = kmeans.silhouette_by_k as [number, number][];
-
- metrics.push({ label: 'OPTIMAL K', value: String(optimalK), color: BB.green });
-
- if (silhouetteByK && silhouetteByK.length > 0) {
- const optimalSilhouette = silhouetteByK.find(([k]) => k === optimalK);
- if (optimalSilhouette) {
- const score = optimalSilhouette[1];
- const quality = score > 0.7 ? 'STRONG' : score > 0.5 ? 'GOOD' : score > 0.25 ? 'FAIR' : 'WEAK';
- metrics.push({ label: 'SILHOUETTE', value: formatNumber(score, 3), color: score > 0.5 ? BB.green : BB.amber });
- metrics.push({ label: 'CLUSTERING', value: quality, color: score > 0.5 ? BB.green : BB.amber });
- }
- }
-
- const clusterLabels = kmeans.cluster_labels as number[];
- if (clusterLabels) {
- metrics.push({ label: 'DATA POINTS', value: String(clusterLabels.length), color: BB.textSecondary });
- }
- }
-
- if (meta?.n_samples) {
- metrics.push({ label: 'SAMPLES', value: String(meta.n_samples), color: BB.textMuted });
- }
- if (meta?.n_features) {
- metrics.push({ label: 'FEATURES', value: String(meta.n_features), color: BB.textMuted });
- }
- } else if (selectedAnalysis === 'resampling_methods' && result.value) {
- const value = result.value as Record<string, Record<string, unknown>>;
- const meta = result.metadata as Record<string, unknown>;
-
- // Bootstrap metrics
- if (value.bootstrap) {
- const bootstrap = value.bootstrap;
- const mean = bootstrap.mean as number;
- const std = bootstrap.std as number;
- const bias = bootstrap.bias as number;
- const ci = bootstrap.confidence_interval as [number, number];
-
- metrics.push({ label: 'BOOT MEAN', value: formatNumber(mean, 4), color: BB.green });
- metrics.push({ label: 'BOOT STD', value: formatNumber(std, 4), color: BB.textPrimary });
- if (bias !== undefined && bias !== null) {
- metrics.push({ label: 'BIAS', value: formatNumber(bias, 6), color: Math.abs(bias) < 0.01 ? BB.green : BB.amber });
- }
- if (ci && ci.length === 2) {
- metrics.push({ label: '95% CI LOW', value: formatNumber(ci[0], 4), color: BB.textSecondary });
- metrics.push({ label: '95% CI HIGH', value: formatNumber(ci[1], 4), color: BB.textSecondary });
- }
- }
-
- // Jackknife metrics
- if (value.jackknife) {
- const jackknife = value.jackknife;
- const biasCorr = jackknife.bias_corrected_estimate as number;
- const stdErr = jackknife.std_error as number;
- const jackBias = jackknife.bias as number;
-
- if (biasCorr !== undefined) {
- metrics.push({ label: 'JACK ESTIMATE', value: formatNumber(biasCorr, 4), color: BB.amber });
- }
- if (stdErr !== undefined) {
- metrics.push({ label: 'STD ERROR', value: formatNumber(stdErr, 4), color: BB.textPrimary });
- }
- if (jackBias !== undefined) {
- metrics.push({ label: 'JACK BIAS', value: formatNumber(jackBias, 6), color: Math.abs(jackBias) < 0.01 ? BB.green : BB.amber });
- }
- }
-
- // Permutation test metrics
- if (value.permutation) {
- const perm = value.permutation;
- const pValue = perm.p_value as number;
- const significant = perm.significant as boolean;
-
- metrics.push({ label: 'P-VALUE', value: formatNumber(pValue, 4), color: pValue < 0.05 ? BB.green : BB.textMuted });
- metrics.push({ label: 'SIGNIFICANT', value: significant ? 'YES' : 'NO', color: significant ? BB.green : BB.textMuted });
- }
-
- // Metadata
- if (meta?.n_bootstrap) {
- metrics.push({ label: 'ITERATIONS', value: String(meta.n_bootstrap), color: BB.textMuted });
- }
- if (meta?.data_size) {
- metrics.push({ label: 'DATA SIZE', value: String(meta.data_size), color: BB.textMuted });
- }
- } else if (selectedAnalysis === 'validate_data' && result) {
- // Data Quality metrics
- const qualityScore = result.quality_score as number;
- const issues = result.issues as { type: string; severity: string; description: string }[];
- const warnings = result.warnings as { type: string; message: string }[];
- const statistics = result.statistics as Record<string, unknown>;
- const recommendations = result.recommendations as string[];
-
- // Quality Score with color coding
- if (qualityScore !== undefined && qualityScore !== null) {
- let scoreColor = BB.green;
- let scoreLabel = 'EXCELLENT';
- if (qualityScore < 50) { scoreColor = BB.red; scoreLabel = 'POOR'; }
- else if (qualityScore < 70) { scoreColor = BB.amber; scoreLabel = 'FAIR'; }
- else if (qualityScore < 90) { scoreColor = BB.green; scoreLabel = 'GOOD'; }
- metrics.push({ label: 'QUALITY SCORE', value: `${qualityScore.toFixed(0)}/100`, color: scoreColor });
- metrics.push({ label: 'STATUS', value: scoreLabel, color: scoreColor });
- }
-
- // Statistics
- if (statistics) {
- if (statistics.total_observations !== undefined) {
- metrics.push({ label: 'OBSERVATIONS', value: String(statistics.total_observations), color: BB.textPrimary });
- }
- if (statistics.missing_data_ratio !== undefined) {
- const missingRatio = statistics.missing_data_ratio as number;
- const missingPct = (missingRatio * 100).toFixed(1);
- metrics.push({
- label: 'MISSING DATA',
- value: `${missingPct}%`,
- color: missingRatio > 0.05 ? BB.red : missingRatio > 0.01 ? BB.amber : BB.green
- });
- }
- if (statistics.mean !== undefined) {
- metrics.push({ label: 'MEAN', value: formatNumber(statistics.mean as number, 2), color: BB.textSecondary });
- }
- if (statistics.std !== undefined) {
- metrics.push({ label: 'STD DEV', value: formatNumber(statistics.std as number, 2), color: BB.textSecondary });
- }
- }
-
- // Issues count by severity
- if (issues && issues.length > 0) {
- const criticalCount = issues.filter(i => i.severity === 'critical').length;
- const highCount = issues.filter(i => i.severity === 'high').length;
- const mediumCount = issues.filter(i => i.severity === 'medium').length;
- const totalIssues = issues.length;
-
- metrics.push({ label: 'TOTAL ISSUES', value: String(totalIssues), color: totalIssues > 0 ? BB.amber : BB.green });
- if (criticalCount > 0) {
- metrics.push({ label: 'CRITICAL', value: String(criticalCount), color: BB.red });
- }
- if (highCount > 0) {
- metrics.push({ label: 'HIGH SEV', value: String(highCount), color: BB.red });
- }
- } else {
- metrics.push({ label: 'ISSUES', value: 'NONE', color: BB.green });
- }
-
- // Warnings count
- if (warnings && warnings.length > 0) {
- metrics.push({ label: 'WARNINGS', value: String(warnings.length), color: BB.amber });
- }
-
- // Recommendations count
- if (recommendations && recommendations.length > 0) {
- metrics.push({ label: 'RECOMMENDATIONS', value: String(recommendations.length), color: BB.blueLight });
- }
- }
-
- return metrics;
- };
-
- // Build chart data for results
- const getResultChartData = () => {
- if (selectedAnalysis === 'trend_analysis') {
- const meta = result.metadata as Record<string, unknown>;
- const value = result.value as Record<string, unknown>;
- const fitted = meta?.fitted_values as number[];
- const residuals = meta?.residuals as number[];
- const slope = value?.slope as number;
- const intercept = value?.intercept as number;
-
- if (fitted && fitted.length > 0) {
- // Calculate standard error for confidence bands
- const n = priceData.length;
- const residualsArr = residuals || priceData.map((v, i) => v - fitted[i]);
- const mse = residualsArr.reduce((sum, r) => sum + r * r, 0) / (n - 2);
- const se = Math.sqrt(mse);
-
- // Mean of time index for confidence interval calculation
- const meanX = (n - 1) / 2;
- const sumXX = Array.from({ length: n }, (_, i) => Math.pow(i - meanX, 2)).reduce((a, b) => a + b, 0);
-
- // Build enhanced chart data with confidence bands
- const enhancedData = chartData.map((d, i) => {
- // Standard error of prediction at each point
- const sePred = se * Math.sqrt(1 + 1/n + Math.pow(i - meanX, 2) / sumXX);
- const ciWidth = 1.96 * sePred; // 95% confidence
-
- return {
- ...d,
- fitted: fitted[i],
- residual: residualsArr[i],
- upperBand: fitted[i] + ciWidth,
- lowerBand: fitted[i] - ciWidth,
- };
- });
-
- // Add future projection (5 periods)
- if (slope !== undefined && intercept !== undefined) {
- const projectionPeriods = 5;
- for (let i = 0; i < projectionPeriods; i++) {
- const futureIndex = n + i;
- const projectedValue = intercept + slope * futureIndex;
- const sePred = se * Math.sqrt(1 + 1/n + Math.pow(futureIndex - meanX, 2) / sumXX);
- const ciWidth = 1.96 * sePred;
-
- enhancedData.push({
- index: futureIndex,
- value: null as unknown as number,
- date: `+${i + 1}d`,
- fitted: null as unknown as number,
- residual: null as unknown as number,
- upperBand: null as unknown as number,
- lowerBand: null as unknown as number,
- projection: projectedValue,
- projectionUpper: projectedValue + ciWidth,
- projectionLower: projectedValue - ciWidth,
- } as any);
- }
- }
-
- return enhancedData;
- }
- } else if (selectedAnalysis === 'stationarity_test') {
- // Create rolling mean and rolling std visualization
- const windowSize = Math.min(20, Math.floor(priceData.length / 4));
- if (windowSize < 2) return chartData;
-
- // Calculate rolling statistics
- const rollingMean: (number | null)[] = [];
- const rollingStd: (number | null)[] = [];
- const upperBand: (number | null)[] = [];
- const lowerBand: (number | null)[] = [];
-
- for (let i = 0; i < priceData.length; i++) {
- if (i < windowSize - 1) {
- rollingMean.push(null);
- rollingStd.push(null);
- upperBand.push(null);
- lowerBand.push(null);
- } else {
- const windowData = priceData.slice(i - windowSize + 1, i + 1);
- const mean = windowData.reduce((a, b) => a + b, 0) / windowData.length;
- const variance = windowData.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / windowData.length;
- const std = Math.sqrt(variance);
-
- rollingMean.push(mean);
- rollingStd.push(std);
- upperBand.push(mean + 2 * std);
- lowerBand.push(mean - 2 * std);
- }
- }
-
- // Overall mean for reference
- const overallMean = priceData.reduce((a, b) => a + b, 0) / priceData.length;
-
- return chartData.map((d, i) => ({
- ...d,
- rollingMean: rollingMean[i],
- upperBand: upperBand[i],
- lowerBand: lowerBand[i],
- overallMean,
- }));
- } else if (selectedAnalysis === 'arima_model') {
- const value = result.value as Record<string, unknown>;
- const meta = result.metadata as Record<string, unknown>;
- const fitted = value?.fitted_values as number[];
- const residuals = value?.residuals as number[];
- const forecasts = value?.forecasts as number[];
- const forecastCI = value?.forecast_confidence_interval as { lower: number[]; upper: number[] };
-
- if (fitted && fitted.length > 0) {
- const n = priceData.length;
-
- // Calculate residual standard deviation for confidence bands
- const residualsArr = residuals || priceData.map((v, i) => v - (fitted[i] || v));
- const residMean = residualsArr.reduce((a, b) => a + b, 0) / residualsArr.length;
- const residStd = Math.sqrt(residualsArr.reduce((a, b) => a + Math.pow(b - residMean, 2), 0) / residualsArr.length);
-
- // Build enhanced chart data with fitted values, residuals, and confidence bands
- const enhancedData = chartData.map((d, i) => {
- const fittedVal = fitted[i];
- const residual = residualsArr[i];
- // 95% confidence band around fitted values
- const ciWidth = 1.96 * residStd;
-
- return {
- ...d,
- fitted: fittedVal,
- residual: residual,
- upperBand: fittedVal !== undefined ? fittedVal + ciWidth : null,
- lowerBand: fittedVal !== undefined ? fittedVal - ciWidth : null,
- // Residual bar height (scaled for visibility)
- residualBar: residual,
- };
- });
-
- // Add future forecast points if available
- if (forecasts && forecasts.length > 0) {
- forecasts.forEach((forecast, i) => {
- const ciLower = forecastCI?.lower?.[i];
- const ciUpper = forecastCI?.upper?.[i];
- // Default CI if not provided (widening uncertainty)
- const defaultCiWidth = 1.96 * residStd * Math.sqrt(1 + (i + 1) * 0.1);
-
- enhancedData.push({
- index: n + i,
- value: null as unknown as number,
- date: `+${i + 1}d`,
- fitted: null as unknown as number,
- residual: null as unknown as number,
- upperBand: null as unknown as number,
- lowerBand: null as unknown as number,
- residualBar: null as unknown as number,
- forecast: forecast,
- forecastUpper: ciUpper ?? (forecast + defaultCiWidth),
- forecastLower: ciLower ?? (forecast - defaultCiWidth),
- } as any);
- });
- } else {
- // Generate simple forecast projection if not provided by backend
- // Use last fitted value as base and project forward
- const lastFitted = fitted[fitted.length - 1];
- const forecastHorizon = 5;
-
- for (let i = 0; i < forecastHorizon; i++) {
- // Simple projection using last fitted value (ARIMA(0,1,0) like behavior)
- const forecastVal = lastFitted;
- const ciWidth = 1.96 * residStd * Math.sqrt(1 + (i + 1) * 0.2);
-
- enhancedData.push({
- index: n + i,
- value: null as unknown as number,
- date: `+${i + 1}d`,
- fitted: null as unknown as number,
- residual: null as unknown as number,
- upperBand: null as unknown as number,
- lowerBand: null as unknown as number,
- residualBar: null as unknown as number,
- forecast: forecastVal,
- forecastUpper: forecastVal + ciWidth,
- forecastLower: forecastVal - ciWidth,
- } as any);
- }
- }
-
- return enhancedData;
- }
- } else if (selectedAnalysis === 'forecasting') {
- const forecasts = result.value as number[];
- const meta = result.metadata as Record<string, unknown>;
- const params = result.parameters as Record<string, unknown>;
- const trainSize = (meta?.train_data_size as number) || Math.floor(chartData.length * 0.8);
- const testSize = (meta?.test_data_size as number) || chartData.length - trainSize;
- const horizon = (meta?.forecast_horizon as number) || forecasts?.length || 5;
- const rmse = meta?.rmse as number;
- const method = params?.method as string;
-
- if (forecasts && forecasts.length > 0) {
- // For ETS forecasting, show:
- // 1. Training data (gray line)
- // 2. Test actual data (amber line with dots)
- // 3. Forecast level through test period (dashed blue)
- // 4. Future forecast projection with confidence bands (green)
-
- const forecastValue = forecasts[0]; // For simple ETS, all forecasts are the same
-
- // Calculate standard deviation from training data for confidence bands
- const trainData = priceData.slice(0, trainSize);
- const trainMean = trainData.reduce((a, b) => a + b, 0) / trainData.length;
- const trainStd = Math.sqrt(trainData.reduce((a, b) => a + Math.pow(b - trainMean, 2), 0) / trainData.length);
-
- // Use RMSE if available, otherwise estimate from training std
- const errorStd = rmse || trainStd * 0.3;
-
- // Calculate test period errors for visualization
- const testData = priceData.slice(trainSize);
- const testErrors = testData.map(actual => actual - forecastValue);
- const meanTestError = testErrors.length > 0 ? testErrors.reduce((a, b) => a + b, 0) / testErrors.length : 0;
-
- const enhancedData = chartData.map((d, i) => {
- const isTrainData = i < trainSize;
- const isTestData = i >= trainSize;
- const testIdx = i - trainSize;
-
- // Calculate error for test points
- const error = isTestData && testIdx < testErrors.length ? testErrors[testIdx] : null;
- const absError = error !== null ? Math.abs(error) : null;
-
- return {
- ...d,
- trainValue: isTrainData ? d.value : null,
- testActual: isTestData ? d.value : null,
- // Show forecast level as a reference line through the test period
- forecastLevel: isTestData ? forecastValue : null,
- // Confidence bands in test period (95% CI)
- forecastUpper: isTestData ? forecastValue + 1.96 * errorStd : null,
- forecastLower: isTestData ? forecastValue - 1.96 * errorStd : null,
- // Error bar (absolute value for visualization)
- forecastError: error,
- absError: absError,
- };
- });
-
- // Add future forecast points beyond the historical data with widening confidence bands
- const futureForecasts = forecasts.map((v, i) => {
- // Confidence bands widen over time for future forecasts
- const ciWidth = 1.96 * errorStd * Math.sqrt(1 + (i + 1) * 0.15);
-
- return {
- index: chartData.length + i,
- value: null,
- trainValue: null,
- testActual: null,
- forecastLevel: null,
- forecastUpper: null,
- forecastLower: null,
- forecastError: null,
- absError: null,
- forecast: v,
- futureForecastUpper: v + ciWidth,
- futureForecastLower: v - ciWidth,
- date: `+${i + 1}d`,
- };
- });
-
- // Add a connecting point at the last training data point
- if (enhancedData.length > 0 && trainSize > 0) {
- const lastTrainIdx = trainSize - 1;
- enhancedData[lastTrainIdx] = {
- ...enhancedData[lastTrainIdx],
- forecastStart: enhancedData[lastTrainIdx].value,
- } as any;
- }
-
- return [...enhancedData, ...futureForecasts];
- }
- } else if (selectedAnalysis === 'supervised_learning') {
- const meta = result.metadata as Record<string, unknown>;
- const value = result.value as Record<string, Record<string, unknown>>;
- const bestAlgo = meta?.best_algorithm as string;
- if (bestAlgo && value[bestAlgo]) {
- const predictions = value[bestAlgo].predictions as number[];
- const yTest = meta?.y_test as number[];
- const rmse = value[bestAlgo].rmse as number;
-
- if (predictions && predictions.length > 0) {
- const nLags = 5;
- const totalSamples = chartData.length - nLags;
- const trainSize = (meta?.train_size as number) || Math.floor(totalSamples * 0.8);
- const testStartIndex = nLags + trainSize;
-
- // Calculate prediction standard error for confidence bands
- const predictionErrors = yTest ? yTest.map((actual, i) => actual - predictions[i]) : [];
- const predStd = rmse || (predictionErrors.length > 0 ?
- Math.sqrt(predictionErrors.reduce((sum, e) => sum + e * e, 0) / predictionErrors.length) : 0);
-
- return chartData.map((d, i) => {
- const testIdx = i - testStartIndex;
- const isTestPoint = testIdx >= 0 && testIdx < predictions.length;
- const isTrainPoint = i >= nLags && i < testStartIndex;
- const pred = isTestPoint ? predictions[testIdx] : null;
- const actual = isTestPoint && yTest ? yTest[testIdx] : null;
- const error = (pred !== null && actual !== null) ? actual - pred : null;
-
- // 95% confidence band (approximately ±2 * RMSE)
- const ciWidth = 1.96 * predStd;
-
- return {
- ...d,
- trainValue: isTrainPoint ? d.value : null,
- prediction: pred,
- testActual: actual,
- predictionError: error,
- upperBand: pred !== null ? pred + ciWidth : null,
- lowerBand: pred !== null ? pred - ciWidth : null,
- // Zero line for error reference
- zeroLine: isTestPoint ? 0 : null,
- };
- });
- }
- }
- } else if (selectedAnalysis === 'unsupervised_learning') {
- const value = result.value as Record<string, Record<string, unknown>>;
- if (value?.kmeans) {
- const clusterLabels = value.kmeans.cluster_labels as number[];
- if (clusterLabels && clusterLabels.length > 0) {
- return chartData.map((d, i) => ({
- ...d,
- cluster: i < clusterLabels.length ? clusterLabels[i] : 0,
- }));
- }
- }
- return chartData;
- } else if (selectedAnalysis === 'resampling_methods') {
- const value = result.value as Record<string, Record<string, unknown>>;
- if (value?.bootstrap) {
- const bootstrap = value.bootstrap;
- const resampledStats = bootstrap.resampled_statistics as number[];
- const mean = bootstrap.mean as number;
- const ci = bootstrap.confidence_interval as [number, number];
-
- if (resampledStats && resampledStats.length > 0) {
- // Create histogram data from resampled statistics
- const sortedStats = [...resampledStats].sort((a, b) => a - b);
- const min = sortedStats[0];
- const max = sortedStats[sortedStats.length - 1];
- const binCount = Math.min(30, Math.ceil(Math.sqrt(sortedStats.length)));
- const binWidth = (max - min) / binCount;
-
- // Find bin indices for mean and CI
- const findBinIndex = (val: number) => {
- const binIdx = Math.floor((val - min) / binWidth);
- return Math.max(0, Math.min(binCount - 1, binIdx));
- };
-
- const meanBinIdx = findBinIndex(mean);
- const ciLowIdx = ci ? findBinIndex(ci[0]) : 0;
- const ciHighIdx = ci ? findBinIndex(ci[1]) : binCount - 1;
-
- const bins: { binCenter: number; count: number; frequency: number; inCI: boolean; isMean: boolean }[] = [];
- for (let i = 0; i < binCount; i++) {
- const binStart = min + i * binWidth;
- const binEnd = binStart + binWidth;
- const binCenter = (binStart + binEnd) / 2;
- const count = sortedStats.filter(v => v >= binStart && (i === binCount - 1 ? v <= binEnd : v < binEnd)).length;
- const inCI = i >= ciLowIdx && i <= ciHighIdx;
- const isMean = i === meanBinIdx;
- bins.push({
- binCenter,
- count,
- frequency: count / sortedStats.length,
- inCI,
- isMean,
- });
- }
-
- return bins.map((bin, i) => ({
- index: i,
- value: bin.count,
- binCenter: bin.binCenter,
- frequency: bin.frequency,
- inCI: bin.inCI,
- isMean: bin.isMean,
- date: formatNumber(bin.binCenter, 2),
- meanBinIdx,
- ciLowIdx,
- ciHighIdx,
- }));
- }
- }
- // If no bootstrap data, show original data with jackknife leave-one-out visualization
- return chartData;
- } else if (selectedAnalysis === 'validate_data') {
- // Data Quality visualization: show data with outlier highlighting
- // Compute z-scores for outlier detection
- if (priceData.length < 3) return chartData;
-
- const mean = priceData.reduce((a, b) => a + b, 0) / priceData.length;
- const variance = priceData.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / priceData.length;
- const std = Math.sqrt(variance);
-
- const outlierThreshold = 3.0; // Z-score threshold for outliers
-
- return chartData.map((d, i) => {
- const zScore = std > 0 ? Math.abs((d.value - mean) / std) : 0;
- const isOutlier = zScore > outlierThreshold;
- const isSuspicious = zScore > 2.0 && zScore <= outlierThreshold;
-
- return {
- ...d,
- zScore,
- isOutlier,
- isSuspicious,
- normalValue: !isOutlier && !isSuspicious ? d.value : null,
- suspiciousValue: isSuspicious ? d.value : null,
- outlierValue: isOutlier ? d.value : null,
- mean,
- };
- });
- }
- return chartData;
- };
-
- const keyMetrics = getKeyMetrics();
- const resultChartData = getResultChartData();
-
- // Compute cluster boundary separately (not in chart data to avoid breaking the chart)
- let clusterBoundary: number | null = null;
- if (selectedAnalysis === 'unsupervised_learning' && analysisResult?.result) {
- const result = analysisResult.result as Record<string, unknown>;
- const value = result.value as Record<string, Record<string, unknown>>;
- if (value?.kmeans) {
- const clusterLabels = value.kmeans.cluster_labels as number[];
- if (clusterLabels && clusterLabels.length > 0 && priceData.length > 0) {
- const clusterSums: Record<number, { sum: number; count: number }> = {};
- priceData.forEach((price, i) => {
- const cluster = i < clusterLabels.length ? clusterLabels[i] : 0;
- if (!clusterSums[cluster]) clusterSums[cluster] = { sum: 0, count: 0 };
- clusterSums[cluster].sum += price;
- clusterSums[cluster].count += 1;
- });
- const means = Object.values(clusterSums).map(s => s.sum / s.count).sort((a, b) => a - b);
- if (means.length >= 2) {
- clusterBoundary = (means[0] + means[1]) / 2;
- }
- }
- }
- }
-
- // Compute Bootstrap reference values separately
- let bootstrapMean: number | null = null;
- let bootstrapCiLow: number | null = null;
- let bootstrapCiHigh: number | null = null;
- let bootstrapMeanIdx: number | null = null;
- let bootstrapCiLowIdx: number | null = null;
- let bootstrapCiHighIdx: number | null = null;
- if (selectedAnalysis === 'resampling_methods' && analysisResult?.result) {
- const result = analysisResult.result as Record<string, unknown>;
- const value = result.value as Record<string, Record<string, unknown>>;
- if (value?.bootstrap) {
- bootstrapMean = value.bootstrap.mean as number;
- const ci = value.bootstrap.confidence_interval as [number, number];
- if (ci && ci.length === 2) {
- bootstrapCiLow = ci[0];
- bootstrapCiHigh = ci[1];
- }
- // Get indices from chart data
- if (resultChartData.length > 0 && (resultChartData[0] as any)?.meanBinIdx !== undefined) {
- bootstrapMeanIdx = (resultChartData[0] as any).meanBinIdx as number;
- bootstrapCiLowIdx = (resultChartData[0] as any).ciLowIdx as number;
- bootstrapCiHighIdx = (resultChartData[0] as any).ciHighIdx as number;
- }
- }
- }
-
- return (
- <div className="flex h-full">
- {/* Left Panel - Metrics */}
- <div className="w-80 flex-shrink-0 p-4 overflow-y-auto" style={{ backgroundColor: BB.panelBg, borderRight: `1px solid ${BB.borderDark}` }}>
- <div className="flex items-center justify-between mb-3">
- <div className="text-xs font-mono" style={{ color: BB.textAmber }}>RESULTS</div>
- <div className="flex gap-2">
- <button onClick={() => copyToClipboard(JSON.stringify(analysisResult, null, 2))} className="p-1.5" style={{ backgroundColor: BB.cardBg }}>
- <Copy size={14} style={{ color: BB.textMuted }} />
- </button>
- <button onClick={exportResults} className="p-1.5" style={{ backgroundColor: BB.cardBg }}>
- <Download size={14} style={{ color: BB.textMuted }} />
- </button>
- </div>
- </div>
-
- {/* Status Banner */}
- <div className="p-3 mb-4" style={{ backgroundColor: `${BB.green}10`, border: `1px solid ${BB.green}` }}>
- <div className="flex items-center gap-2">
- <CheckCircle2 size={16} style={{ color: BB.green }} />
- <span className="text-xs font-mono font-bold" style={{ color: BB.green }}>COMPLETE</span>
- </div>
- <div className="text-xs font-mono mt-1" style={{ color: BB.textMuted }}>
- {config?.name} • {analysisResult.timestamp ? new Date(analysisResult.timestamp).toLocaleTimeString() : 'Just now'}
- </div>
- </div>
-
- {/* Key Metrics */}
- {keyMetrics.length > 0 && (
- <div className="space-y-2 mb-4">
- {keyMetrics.map((metric, i) => (
- <div key={i} className="flex items-center justify-between p-3" style={{ backgroundColor: BB.cardBg, border: `1px solid ${BB.borderDark}` }}>
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>{metric.label}</span>
- <div className="flex items-center gap-2">
- {metric.icon && <metric.icon size={14} style={{ color: metric.color }} />}
- <span className="text-sm font-mono font-bold" style={{ color: metric.color }}>{metric.value}</span>
- </div>
- </div>
- ))}
- </div>
- )}
-
- {/* Raw Data Section */}
- <div className="mb-4">
- <div className="text-xs font-mono mb-2" style={{ color: BB.textAmber }}>RAW OUTPUT</div>
- <div className="p-3 text-xs font-mono overflow-x-auto" style={{ backgroundColor: BB.black, border: `1px solid ${BB.borderDark}`, maxHeight: 200, overflowY: 'auto' }}>
- {Object.entries(result).map(([key, value]) => {
- if (key === 'model_summary' || (Array.isArray(value) && value.length > 20)) return null;
- return (
- <div key={key} className="flex gap-2 py-1" style={{ borderBottom: `1px solid ${BB.borderDark}` }}>
- <span style={{ color: BB.textMuted }}>{key}:</span>
- <span style={{ color: BB.textPrimary }} className="truncate">
- {typeof value === 'object' ? JSON.stringify(value).substring(0, 50) + '...' : String(value)}
- </span>
- </div>
- );
- })}
- </div>
- </div>
-
- <div className="flex gap-2">
- <button
- onClick={() => setCurrentStep('analysis')}
- className="flex-1 py-2 text-xs font-mono"
- style={{ backgroundColor: BB.cardBg, color: BB.textSecondary, border: `1px solid ${BB.borderDark}` }}
- >
- <ChevronLeft size={12} className="inline" /> MODELS
- </button>
- <button
- onClick={() => {
- setCurrentStep('data');
- setAnalysisResult(null);
- }}
- className="flex-1 py-2 text-xs font-mono font-bold"
- style={{ backgroundColor: BB.amber, color: BB.black }}
- >
- NEW <Play size={12} className="inline ml-1" />
- </button>
- </div>
- </div>
-
- {/* Right Panel - Chart with Results */}
- <div className="flex-1 p-4" style={{ backgroundColor: BB.darkBg }}>
- <div className="h-full flex flex-col">
- <div className="flex items-center justify-between mb-2">
- <div className="flex items-center gap-3">
- <div className="text-xs font-mono" style={{ color: BB.textAmber }}>{config?.shortName} OUTPUT</div>
- {resultsChartZoom && (
- <div className="text-xs font-mono px-2 py-0.5" style={{ backgroundColor: BB.amber + '20', color: BB.amber }}>
- {getDateForIndex(resultsChartZoom.startIndex)} - {getDateForIndex(resultsChartZoom.endIndex)}
- </div>
- )}
- </div>
- <div className="flex items-center gap-3">
- <ZoomControls chartType="results" isZoomed={resultsChartZoom !== null} />
- <div className="text-xs font-mono" style={{ color: BB.textMuted }}>{symbolInput.toUpperCase()}</div>
- </div>
- </div>
- <div
- className="flex-1"
- style={{ minHeight: 300 }}
- onWheel={(e) => handleWheel(e, 'results')}
- >
- <ResponsiveContainer width="100%" height="100%">
- <ComposedChart
- data={resultsChartZoom ? resultChartData.slice(resultsChartZoom.startIndex, resultsChartZoom.endIndex + 1) : resultChartData}
- margin={{ top: 10, right: 10, left: 0, bottom: 30 }}
- onMouseDown={(e) => handleMouseDown(e, 'results')}
- onMouseMove={handleMouseMove}
- onMouseUp={handleMouseUp}
- onMouseLeave={handleMouseUp}
- >
- <CartesianGrid strokeDasharray="3 3" stroke={BB.chartGrid} />
- <XAxis
- dataKey={selectedAnalysis === 'resampling_methods' ? 'index' : 'date'}
- tick={{ fill: BB.textMuted, fontSize: 9 }}
- axisLine={{ stroke: BB.borderDark }}
- interval={selectedAnalysis === 'resampling_methods' ? 'preserveStartEnd' : 'preserveStartEnd'}
- tickFormatter={(val) => {
- if (selectedAnalysis === 'resampling_methods' && (resultChartData[val] as any)?.binCenter !== undefined) {
- return formatNumber((resultChartData[val] as any).binCenter as number, 1);
- }
- return val;
- }}
- />
- <YAxis
- tick={{ fill: BB.textMuted, fontSize: 10 }}
- axisLine={{ stroke: BB.borderDark }}
- domain={['auto', 'auto']}
- tickFormatter={(val) => selectedAnalysis === 'resampling_methods' ? String(Math.round(val)) : formatPrice(val)}
- label={selectedAnalysis === 'resampling_methods' ? { value: 'COUNT', angle: -90, position: 'insideLeft', fill: BB.textMuted, fontSize: 9 } : undefined}
- />
- <Tooltip
- contentStyle={{
- backgroundColor: BB.cardBg,
- border: `1px solid ${BB.borderLight}`,
- borderRadius: 0,
- fontSize: 11,
- }}
- labelFormatter={(label) => selectedAnalysis === 'resampling_methods' ? `Value: ${label}` : `Date: ${label}`}
- labelStyle={{ color: BB.textAmber, fontWeight: 'bold' }}
- formatter={(value: number, name: string, props: { payload?: { frequency?: number; inCI?: boolean; binCenter?: number; zScore?: number; isOutlier?: boolean; isSuspicious?: boolean; value?: number } }) => {
- if (selectedAnalysis === 'resampling_methods' && props.payload) {
- const freq = props.payload.frequency;
- const inCI = props.payload.inCI;
- return [
- <span key="val">
- Count: <strong>{value}</strong> ({freq ? (freq * 100).toFixed(1) : 0}%)
- {inCI && <span style={{ color: BB.blueLight, marginLeft: 8 }}>In 95% CI</span>}
- </span>,
- ''
- ];
- }
- if (selectedAnalysis === 'validate_data' && props.payload) {
- const zScore = props.payload.zScore;
- const isOutlier = props.payload.isOutlier;
- const isSuspicious = props.payload.isSuspicious;
- const priceVal = props.payload.value;
- let status = 'Normal';
- let statusColor = BB.green;
- if (isOutlier) { status = 'OUTLIER'; statusColor = BB.red; }
- else if (isSuspicious) { status = 'Suspicious'; statusColor = BB.amber; }
- return [
- <span key="val">
- <span style={{ color: BB.textPrimary }}>Price: <strong>{priceVal !== undefined ? formatPrice(priceVal) : formatPrice(value)}</strong></span>
- <br />
- <span style={{ color: BB.textSecondary }}>Z-Score: {zScore !== undefined ? zScore.toFixed(2) : '—'}</span>
- <br />
- <span style={{ color: statusColor }}>Status: {status}</span>
- </span>,
- ''
- ];
- }
- return [value, name];
- }}
- />
- {/* Original data (for non-forecasting/non-unsupervised/non-bootstrap/non-validate/non-stationarity analyses) */}
- {selectedAnalysis !== 'forecasting' && selectedAnalysis !== 'unsupervised_learning' && selectedAnalysis !== 'resampling_methods' && selectedAnalysis !== 'validate_data' && selectedAnalysis !== 'stationarity_test' && (
- <Line
- type="monotone"
- dataKey="value"
- stroke={BB.textSecondary}
- strokeWidth={1}
- dot={false}
- name="Actual"
- />
- )}
- {/* Stationarity Test: Price line */}
- {selectedAnalysis === 'stationarity_test' && (
- <Line
- type="monotone"
- dataKey="value"
- stroke={BB.textSecondary}
- strokeWidth={1}
- dot={false}
- name="Price"
- />
- )}
- {/* Stationarity Test: Upper Bollinger Band */}
- {selectedAnalysis === 'stationarity_test' && (
- <Line
- type="monotone"
- dataKey="upperBand"
- stroke={BB.amber}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="Upper Band (+2σ)"
- connectNulls={false}
- />
- )}
- {/* Stationarity Test: Lower Bollinger Band */}
- {selectedAnalysis === 'stationarity_test' && (
- <Line
- type="monotone"
- dataKey="lowerBand"
- stroke={BB.amber}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="Lower Band (-2σ)"
- connectNulls={false}
- />
- )}
- {/* Stationarity Test: Rolling Mean */}
- {selectedAnalysis === 'stationarity_test' && (
- <Line
- type="monotone"
- dataKey="rollingMean"
- stroke={BB.green}
- strokeWidth={2}
- dot={false}
- name="Rolling Mean"
- connectNulls={false}
- />
- )}
- {/* Stationarity Test: Overall Mean Reference */}
- {selectedAnalysis === 'stationarity_test' && resultChartData.length > 0 && (resultChartData[0] as any).overallMean !== undefined && (
- <ReferenceLine
- y={(resultChartData[0] as any).overallMean}
- stroke={BB.blueLight}
- strokeWidth={2}
- strokeDasharray="5 5"
- label={{ value: 'OVERALL MEAN', fill: BB.blueLight, fontSize: 9, position: 'right' }}
- />
- )}
- {/* Data Quality: Normal data line */}
- {selectedAnalysis === 'validate_data' && (
- <Line
- type="monotone"
- dataKey="normalValue"
- stroke={BB.green}
- strokeWidth={1.5}
- dot={false}
- name="Normal"
- connectNulls={false}
- />
- )}
- {/* Data Quality: Suspicious data (2-3 std dev) */}
- {selectedAnalysis === 'validate_data' && (
- <Scatter
- dataKey="suspiciousValue"
- fill={BB.amber}
- name="Suspicious"
- shape={(props: any) => {
- if (!props.cx || !props.cy) return <g />;
- return (
- <circle
- cx={props.cx}
- cy={props.cy}
- r={5}
- fill={BB.amber}
- stroke={BB.black}
- strokeWidth={1}
- />
- );
- }}
- />
- )}
- {/* Data Quality: Outlier data (>3 std dev) */}
- {selectedAnalysis === 'validate_data' && (
- <Scatter
- dataKey="outlierValue"
- fill={BB.red}
- name="Outlier"
- shape={(props: any) => {
- if (!props.cx || !props.cy) return <g />;
- return (
- <g>
- <circle
- cx={props.cx}
- cy={props.cy}
- r={7}
- fill={BB.red}
- stroke={BB.black}
- strokeWidth={1}
- />
- <text
- x={props.cx}
- y={props.cy + 3}
- textAnchor="middle"
- fill={BB.textPrimary}
- fontSize={10}
- fontWeight="bold"
- >
- !
- </text>
- </g>
- );
- }}
- />
- )}
- {/* Data Quality: Mean reference line */}
- {selectedAnalysis === 'validate_data' && resultChartData.length > 0 && (resultChartData[0] as any).mean !== undefined && (
- <ReferenceLine
- y={(resultChartData[0] as any).mean}
- stroke={BB.blueLight}
- strokeWidth={2}
- strokeDasharray="5 5"
- label={{ value: 'MEAN', fill: BB.blueLight, fontSize: 10, position: 'right' }}
- />
- )}
- {/* Bootstrap: CI shaded area */}
- {selectedAnalysis === 'resampling_methods' && typeof bootstrapCiLowIdx === 'number' && typeof bootstrapCiHighIdx === 'number' && (
- <ReferenceArea
- x1={bootstrapCiLowIdx}
- x2={bootstrapCiHighIdx}
- fill={BB.blueLight}
- fillOpacity={0.15}
- stroke={BB.blueLight}
- strokeOpacity={0.3}
- />
- )}
- {/* Bootstrap: Histogram bars with conditional coloring */}
- {selectedAnalysis === 'resampling_methods' && (
- <Bar
- dataKey="value"
- name="Frequency"
- shape={(props: any) => {
- const { x, y, width, height, payload } = props;
- const inCI = payload?.inCI;
- const isMean = payload?.isMean;
- let fill = BB.green;
- let opacity = 0.5;
- if (inCI) {
- fill = BB.green;
- opacity = 0.8;
- }
- if (isMean) {
- fill = BB.amber;
- opacity = 1;
- }
- return (
- <rect
- x={x}
- y={y}
- width={width}
- height={height}
- fill={fill}
- fillOpacity={opacity}
- stroke={isMean ? BB.amber : 'none'}
- strokeWidth={isMean ? 2 : 0}
- />
- );
- }}
- />
- )}
- {/* Bootstrap: Mean reference line */}
- {selectedAnalysis === 'resampling_methods' && typeof bootstrapMeanIdx === 'number' && (
- <ReferenceLine
- x={bootstrapMeanIdx}
- stroke={BB.amber}
- strokeWidth={2}
- label={{ value: `MEAN: ${formatNumber(bootstrapMean || 0, 2)}`, fill: BB.amber, fontSize: 10, position: 'top' }}
- />
- )}
- {/* Unsupervised Learning: Cluster boundary line */}
- {selectedAnalysis === 'unsupervised_learning' && typeof clusterBoundary === 'number' && (
- <ReferenceLine
- y={clusterBoundary}
- stroke={BB.amber}
- strokeWidth={2}
- strokeDasharray="6 3"
- />
- )}
- {/* Unsupervised Learning: Price line with cluster colors */}
- {selectedAnalysis === 'unsupervised_learning' && (
- <Line
- type="monotone"
- dataKey="value"
- stroke={BB.textMuted}
- strokeWidth={1}
- strokeOpacity={0.5}
- dot={(props) => {
- const p = props as { cx: number; cy: number; payload: { cluster?: number } };
- if (!p.cx || !p.cy) return <g />;
- const colors = [BB.green, BB.amber, BB.blueLight, BB.red];
- const c = p.payload?.cluster ?? 0;
- return <circle cx={p.cx} cy={p.cy} r={4} fill={colors[c % colors.length]} />;
- }}
- name="Clustered Data"
- />
- )}
- {/* ETS/Forecasting: Training data */}
- <Line
- type="monotone"
- dataKey="trainValue"
- stroke={BB.textSecondary}
- dot={false}
- strokeWidth={1.5}
- name="Training Data"
- />
- {/* ETS/Forecasting: Test period actual values */}
- <Line
- type="monotone"
- dataKey="testActual"
- stroke={BB.amber}
- dot={{ fill: BB.amber, r: 2 }}
- strokeWidth={2}
- name="Actual (Test)"
- />
- {/* ETS/Forecasting: Forecast level line (shows expected value) */}
- <Line
- type="monotone"
- dataKey="forecastLevel"
- stroke={BB.blueLight}
- dot={false}
- strokeWidth={2}
- strokeDasharray="5 5"
- name="Forecast Level"
- />
- {/* ETS/Forecasting: Upper confidence band in test period */}
- {selectedAnalysis === 'forecasting' && (
- <Line
- type="monotone"
- dataKey="forecastUpper"
- stroke={BB.amber}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="95% CI Upper"
- connectNulls={false}
- />
- )}
- {/* ETS/Forecasting: Lower confidence band in test period */}
- {selectedAnalysis === 'forecasting' && (
- <Line
- type="monotone"
- dataKey="forecastLower"
- stroke={BB.amber}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="95% CI Lower"
- connectNulls={false}
- />
- )}
- {/* ETS/Forecasting: Future forecast upper band (widening) */}
- {selectedAnalysis === 'forecasting' && (
- <Line
- type="monotone"
- dataKey="futureForecastUpper"
- stroke={BB.greenDim}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="Forecast CI Upper"
- connectNulls={false}
- />
- )}
- {/* ETS/Forecasting: Future forecast lower band (widening) */}
- {selectedAnalysis === 'forecasting' && (
- <Line
- type="monotone"
- dataKey="futureForecastLower"
- stroke={BB.greenDim}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="Forecast CI Lower"
- connectNulls={false}
- />
- )}
- {/* Trend Analysis: Upper confidence band */}
- {selectedAnalysis === 'trend_analysis' && (
- <Line
- type="monotone"
- dataKey="upperBand"
- stroke={BB.amber}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="95% CI Upper"
- connectNulls={false}
- />
- )}
- {/* Trend Analysis: Lower confidence band */}
- {selectedAnalysis === 'trend_analysis' && (
- <Line
- type="monotone"
- dataKey="lowerBand"
- stroke={BB.amber}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="95% CI Lower"
- connectNulls={false}
- />
- )}
- {/* Fitted/trend line */}
- <Line
- type="monotone"
- dataKey="fitted"
- stroke={config?.color || BB.amber}
- dot={false}
- strokeWidth={2}
- strokeDasharray="5 5"
- name="Fitted"
- />
- {/* Trend Analysis: Future projection line */}
- {selectedAnalysis === 'trend_analysis' && (
- <Line
- type="monotone"
- dataKey="projection"
- stroke={BB.green}
- strokeWidth={2}
- dot={{ fill: BB.green, r: 4 }}
- name="Projection"
- connectNulls={false}
- />
- )}
- {/* Trend Analysis: Projection upper band */}
- {selectedAnalysis === 'trend_analysis' && (
- <Line
- type="monotone"
- dataKey="projectionUpper"
- stroke={BB.greenDim}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="Projection CI Upper"
- connectNulls={false}
- />
- )}
- {/* Trend Analysis: Projection lower band */}
- {selectedAnalysis === 'trend_analysis' && (
- <Line
- type="monotone"
- dataKey="projectionLower"
- stroke={BB.greenDim}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="Projection CI Lower"
- connectNulls={false}
- />
- )}
- {/* ARIMA: Upper confidence band */}
- {selectedAnalysis === 'arima_model' && (
- <Line
- type="monotone"
- dataKey="upperBand"
- stroke={BB.amber}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="95% CI Upper"
- connectNulls={false}
- />
- )}
- {/* ARIMA: Lower confidence band */}
- {selectedAnalysis === 'arima_model' && (
- <Line
- type="monotone"
- dataKey="lowerBand"
- stroke={BB.amber}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="95% CI Lower"
- connectNulls={false}
- />
- )}
- {/* ARIMA: Forecast projection line */}
- {selectedAnalysis === 'arima_model' && (
- <Line
- type="monotone"
- dataKey="forecast"
- stroke={BB.green}
- strokeWidth={2}
- dot={{ fill: BB.green, r: 4 }}
- name="ARIMA Forecast"
- connectNulls={false}
- />
- )}
- {/* ARIMA: Forecast upper band */}
- {selectedAnalysis === 'arima_model' && (
- <Line
- type="monotone"
- dataKey="forecastUpper"
- stroke={BB.greenDim}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="Forecast CI Upper"
- connectNulls={false}
- />
- )}
- {/* ARIMA: Forecast lower band */}
- {selectedAnalysis === 'arima_model' && (
- <Line
- type="monotone"
- dataKey="forecastLower"
- stroke={BB.greenDim}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="Forecast CI Lower"
- connectNulls={false}
- />
- )}
- {/* Future Forecast */}
- <Line
- type="monotone"
- dataKey="forecast"
- stroke={BB.green}
- dot={{ fill: BB.green, r: 4 }}
- strokeWidth={2}
- name="Forecast"
- />
- {/* ML Prediction: Training data line */}
- {selectedAnalysis === 'supervised_learning' && (
- <Line
- type="monotone"
- dataKey="trainValue"
- stroke={BB.textSecondary}
- strokeWidth={1}
- dot={false}
- name="Training Data"
- connectNulls={false}
- />
- )}
- {/* ML Prediction: Upper confidence band */}
- {selectedAnalysis === 'supervised_learning' && (
- <Line
- type="monotone"
- dataKey="upperBand"
- stroke={BB.amber}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="95% CI Upper"
- connectNulls={false}
- />
- )}
- {/* ML Prediction: Lower confidence band */}
- {selectedAnalysis === 'supervised_learning' && (
- <Line
- type="monotone"
- dataKey="lowerBand"
- stroke={BB.amber}
- strokeWidth={1}
- strokeDasharray="3 3"
- dot={false}
- name="95% CI Lower"
- connectNulls={false}
- />
- )}
- {/* ML Prediction: Test actual values */}
- {selectedAnalysis === 'supervised_learning' && (
- <Line
- type="monotone"
- dataKey="testActual"
- stroke={BB.green}
- strokeWidth={2}
- dot={{ fill: BB.green, r: 3 }}
- name="Test Actual"
- connectNulls={false}
- />
- )}
- {/* ML Prediction */}
- {selectedAnalysis === 'supervised_learning' && (
- <Line
- type="monotone"
- dataKey="prediction"
- stroke={BB.blueLight}
- dot={{ fill: BB.blueLight, r: 3 }}
- strokeWidth={2}
- name="ML Prediction"
- connectNulls={false}
- />
- )}
- {/* ML Prediction (for other analysis types that use it) */}
- {selectedAnalysis !== 'supervised_learning' && (
- <Line
- type="monotone"
- dataKey="prediction"
- stroke={BB.blueLight}
- dot={{ fill: BB.blueLight, r: 3 }}
- strokeWidth={2}
- name="ML Prediction"
- />
- )}
- {/* Brush for horizontal pan/zoom */}
- {!resultsChartZoom && (
- <Brush
- dataKey="index"
- height={20}
- stroke={BB.amber}
- fill={BB.cardBg}
- tickFormatter={(val) => `${val}`}
- onChange={(e) => {
- if (e.startIndex !== undefined && e.endIndex !== undefined && e.startIndex !== e.endIndex) {
- setResultsChartZoom({ startIndex: e.startIndex, endIndex: e.endIndex });
- }
- }}
- />
- )}
- {/* Selection area indicator */}
- {isSelecting && activeChart === 'results' && refAreaLeft !== null && refAreaRight !== null && (
- <ReferenceArea
- x1={refAreaLeft}
- x2={refAreaRight}
- strokeOpacity={0.3}
- fill={BB.amber}
- fillOpacity={0.2}
- />
- )}
- </ComposedChart>
- </ResponsiveContainer>
- </div>
-
- {/* Legend */}
- <div className="flex items-center justify-between mt-2 px-2">
- <div className="flex items-center gap-4 flex-wrap">
- {selectedAnalysis === 'forecasting' && (
- <>
- <div className="flex items-center gap-2">
- <div className="w-4 h-0.5" style={{ backgroundColor: BB.textSecondary }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>TRAIN DATA</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.amber }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>TEST ACTUAL</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 border-t-2 border-dashed" style={{ borderColor: BB.blueLight }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>ETS LEVEL</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 border-t border-dashed" style={{ borderColor: BB.amber }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>95% CI</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.green }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>FORECAST</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 border-t border-dashed" style={{ borderColor: BB.greenDim }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>FORECAST CI</span>
- </div>
- </>
- )}
- {selectedAnalysis === 'resampling_methods' && (
- <>
- <div className="flex items-center gap-2">
- <div className="w-3 h-3" style={{ backgroundColor: BB.green, opacity: 0.7 }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>DISTRIBUTION</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 h-0.5" style={{ backgroundColor: BB.amber }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>MEAN</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 h-3" style={{ backgroundColor: BB.blueLight, opacity: 0.2 }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>95% CI</span>
- </div>
- </>
- )}
- {selectedAnalysis === 'unsupervised_learning' && (
- <>
- <div className="flex items-center gap-2">
- <div className="w-4 h-0.5" style={{ backgroundColor: BB.textSecondary }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>PRICE</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 border-t-2 border-dashed" style={{ borderColor: BB.amber }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>BOUNDARY</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.green }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>CLUSTER 0</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.amber }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>CLUSTER 1</span>
- </div>
- </>
- )}
- {selectedAnalysis === 'supervised_learning' && (
- <>
- <div className="flex items-center gap-2">
- <div className="w-4 h-0.5" style={{ backgroundColor: BB.textSecondary }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>TRAIN DATA</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.green }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>TEST ACTUAL</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.blueLight }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>PREDICTION</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 border-t border-dashed" style={{ borderColor: BB.amber }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>95% CI</span>
- </div>
- </>
- )}
- {selectedAnalysis === 'validate_data' && (
- <>
- <div className="flex items-center gap-2">
- <div className="w-4 h-0.5" style={{ backgroundColor: BB.green }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>NORMAL DATA</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.amber }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>SUSPICIOUS (2-3σ)</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.red }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>OUTLIER (&gt;3σ)</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 border-t-2 border-dashed" style={{ borderColor: BB.blueLight }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>MEAN</span>
- </div>
- </>
- )}
- {selectedAnalysis === 'stationarity_test' && (
- <>
- <div className="flex items-center gap-2">
- <div className="w-4 h-0.5" style={{ backgroundColor: BB.textSecondary }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>PRICE</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 h-0.5" style={{ backgroundColor: BB.green }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>ROLLING MEAN</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 border-t-2 border-dashed" style={{ borderColor: BB.amber }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>±2σ BANDS</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 border-t-2 border-dashed" style={{ borderColor: BB.blueLight }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>OVERALL MEAN</span>
- </div>
- </>
- )}
- {selectedAnalysis === 'trend_analysis' && (
- <>
- <div className="flex items-center gap-2">
- <div className="w-4 h-0.5" style={{ backgroundColor: BB.textSecondary }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>ACTUAL</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 border-t-2 border-dashed" style={{ borderColor: config?.color || BB.amber }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>TREND</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 border-t border-dashed" style={{ borderColor: BB.amber }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>95% CI</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.green }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>PROJECTION</span>
- </div>
- </>
- )}
- {selectedAnalysis === 'arima_model' && (
- <>
- <div className="flex items-center gap-2">
- <div className="w-4 h-0.5" style={{ backgroundColor: BB.textSecondary }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>ACTUAL</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 border-t-2 border-dashed" style={{ borderColor: BB.amber }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>FITTED</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 border-t border-dashed" style={{ borderColor: BB.amber }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>95% CI</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.green }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>FORECAST</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 border-t border-dashed" style={{ borderColor: BB.greenDim }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>FORECAST CI</span>
- </div>
- </>
- )}
- {selectedAnalysis !== 'forecasting' && selectedAnalysis !== 'resampling_methods' && selectedAnalysis !== 'unsupervised_learning' && selectedAnalysis !== 'supervised_learning' && selectedAnalysis !== 'validate_data' && selectedAnalysis !== 'stationarity_test' && selectedAnalysis !== 'trend_analysis' && selectedAnalysis !== 'arima_model' && (
- <>
- <div className="flex items-center gap-2">
- <div className="w-4 h-0.5" style={{ backgroundColor: BB.textSecondary }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>ACTUAL</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-4 h-0.5" style={{ backgroundColor: config?.color, borderStyle: 'dashed', borderWidth: 1, borderColor: config?.color }} />
- <span className="text-xs font-mono" style={{ color: BB.textMuted }}>FITTED</span>
- </div>
- </>
- )}
- </div>
- <div className="text-xs font-mono" style={{ color: BB.textMuted }}>
- Scroll to pan | Ctrl+Scroll to zoom | Drag to select
- </div>
- </div>
- </div>
- </div>
- </div>
- );
- };
-
- return (
- <div className="h-full flex flex-col" style={{ backgroundColor: BB.black }}>
- {renderHeader()}
- <div className="flex-1 overflow-hidden">
- {currentStep === 'data' && renderDataStep()}
- {currentStep === 'analysis' && renderAnalysisStep()}
- {currentStep === 'results' && renderResultsStep()}
- </div>
- </div>
- );
-}
-
-export default CFAQuantPanel;
+/**
+ * CFA Quant Panel
+ *
+ * This file re-exports the CFAQuantPanel from its new modular location.
+ * The component has been refactored into smaller, maintainable pieces.
+ *
+ * See ./cfa-quant/ for:
+ * - CFAQuantPanel.tsx - Main component
+ * - components/ - UI components (Header, DataStep, AnalysisStep, ResultsStep, etc.)
+ * - hooks/ - Custom hooks (useChartZoom, usePriceData)
+ * - utils/ - Utility functions (formatters, calculations, metricsExtractor, chartDataBuilder)
+ * - constants.ts - Color palette (BB) and analysis configurations
+ * - types.ts - TypeScript interfaces
+ */
+
+export { CFAQuantPanel, default } from './cfa-quant';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FFNAnalyticsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FFNAnalyticsPanel.tsx
index 0ebc4ebfe..bff24ee8c 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FFNAnalyticsPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FFNAnalyticsPanel.tsx
@@ -1,1793 +1,6 @@
/**
- * FFN Analytics Panel - Portfolio Performance Analysis
- * Fincept Professional Design
- * Integrated with FFN library via PyO3
- *
- * Features:
- * - Multiple data sources (Manual, Portfolio, Symbol)
- * - Performance metrics analysis
- * - Drawdown analysis
- * - Risk metrics
- * - Monthly returns heatmap
- * - Rolling metrics charts
- * - Asset comparison with correlation matrix
- * - Portfolio optimization (ERC, Inv Vol, Mean-Var, Equal Weight)
- * - Benchmark comparison (Alpha, Beta, Tracking Error, Information Ratio, Capture Ratios)
+ * FFN Analytics Panel - Re-export
+ * This file re-exports from the refactored ffn-analytics folder
*/
-import React, { useState, useEffect, useCallback } from 'react';
-import {
- TrendingUp,
- TrendingDown,
- Activity,
- BarChart2,
- Calendar,
- RefreshCw,
- AlertCircle,
- CheckCircle2,
- ChevronDown,
- ChevronUp,
- LineChart,
- PieChart,
- Percent,
- DollarSign,
- Clock,
- Target,
- Database,
- Briefcase,
- Search,
- Grid,
- Table,
- Layers,
- Scale,
- Sliders,
- GitCompare
-} from 'lucide-react';
-import { ffnService, type PerformanceMetrics, type DrawdownInfo, type FFNConfig, type MonthlyReturnsResponse, type RollingMetricsResponse, type AssetComparisonResponse, type PortfolioOptimizationResponse, type BenchmarkComparisonResponse } from '@/services/aiQuantLab/ffnService';
-import { portfolioService, type Portfolio } from '@/services/portfolio/portfolioService';
-import { yfinanceService } from '@/services/markets/yfinanceService';
-
-// Fincept Professional Color Palette
-const FINCEPT = {
- 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'
-};
-
-// Sample data for demonstration
-const SAMPLE_PRICES = {
- '2023-01-03': 100.0,
- '2023-01-04': 101.2,
- '2023-01-05': 99.8,
- '2023-01-06': 102.5,
- '2023-01-09': 103.1,
- '2023-01-10': 104.0,
- '2023-01-11': 102.3,
- '2023-01-12': 105.2,
- '2023-01-13': 106.8,
- '2023-01-17': 105.5,
- '2023-01-18': 107.2,
- '2023-01-19': 106.0,
- '2023-01-20': 108.5,
- '2023-01-23': 109.3,
- '2023-01-24': 110.0,
- '2023-01-25': 108.7,
- '2023-01-26': 111.2,
- '2023-01-27': 112.5,
- '2023-01-30': 111.0,
- '2023-01-31': 113.8
-};
-
-// Data source types
-type DataSourceType = 'manual' | 'portfolio' | 'symbol';
-
-// Analysis mode types
-type AnalysisMode = 'performance' | 'comparison' | 'monthly' | 'rolling' | 'optimize' | 'benchmark';
-
-// Optimization method types
-type OptimizationMethod = 'erc' | 'inv_vol' | 'mean_var' | 'equal';
-
-interface AnalysisResult {
- performance?: PerformanceMetrics;
- drawdowns?: {
- max_drawdown: number;
- top_drawdowns: DrawdownInfo[];
- };
- riskMetrics?: {
- ulcer_index?: number;
- skewness?: number;
- kurtosis?: number;
- var_95?: number;
- cvar_95?: number;
- };
- monthlyReturns?: Record<string, Record<string, number | null>>;
- rollingMetrics?: {
- rolling_sharpe?: Record<string, number>;
- rolling_volatility?: Record<string, number>;
- };
- comparison?: AssetComparisonResponse;
- optimization?: PortfolioOptimizationResponse;
- benchmark?: BenchmarkComparisonResponse;
-}
-
-export function FFNAnalyticsPanel() {
- const [isFFNAvailable, setIsFFNAvailable] = useState<boolean | null>(null);
- const [isLoading, setIsLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [analysisResult, setAnalysisResult] = useState<AnalysisResult | null>(null);
- const [priceInput, setPriceInput] = useState(JSON.stringify(SAMPLE_PRICES, null, 2));
-
- // Data source configuration
- const [dataSourceType, setDataSourceType] = useState<DataSourceType>('manual');
- const [portfolios, setPortfolios] = useState<Portfolio[]>([]);
- const [selectedPortfolioId, setSelectedPortfolioId] = useState<string>('');
- const [symbolInput, setSymbolInput] = useState('AAPL');
- const [symbolsInput, setSymbolsInput] = useState('AAPL,MSFT,GOOGL'); // For comparison
- const [historicalDays, setHistoricalDays] = useState(365);
- const [priceDataLoading, setPriceDataLoading] = useState(false);
-
- // Analysis mode
- const [analysisMode, setAnalysisMode] = useState<AnalysisMode>('performance');
-
- // Portfolio optimization settings
- const [optimizationMethod, setOptimizationMethod] = useState<OptimizationMethod>('erc');
-
- // Benchmark comparison settings
- const [benchmarkSymbol, setBenchmarkSymbol] = useState('SPY');
-
- // Config
- const [config, setConfig] = useState<FFNConfig>({
- risk_free_rate: 0.02,
- annualization_factor: 252,
- drawdown_threshold: 0.05
- });
-
- const [expandedSections, setExpandedSections] = useState({
- performance: true,
- drawdowns: true,
- risk: true,
- monthly: true,
- rolling: true,
- comparison: true,
- optimization: true,
- benchmark: true,
- dataSource: true
- });
-
- // Check FFN availability and load portfolios on mount
- useEffect(() => {
- checkFFNStatus();
- loadPortfolios();
- }, []);
-
- const checkFFNStatus = async () => {
- try {
- const status = await ffnService.checkStatus();
- setIsFFNAvailable(status.available);
- if (!status.available) {
- setError('FFN library not installed. Run: pip install ffn');
- }
- } catch (err) {
- setIsFFNAvailable(false);
- setError('Failed to check FFN status');
- }
- };
-
- const loadPortfolios = async () => {
- try {
- const portfolioList = await portfolioService.getPortfolios();
- setPortfolios(portfolioList);
- if (portfolioList.length > 0) {
- setSelectedPortfolioId(portfolioList[0].id);
- }
- } catch (err) {
- console.error('Failed to load portfolios:', err);
- }
- };
-
- // Fetch data based on source type
- const fetchData = useCallback(async () => {
- setPriceDataLoading(true);
- setError(null);
-
- try {
- if (dataSourceType === 'portfolio' && selectedPortfolioId) {
- const summary = await portfolioService.getPortfolioSummary(selectedPortfolioId);
- if (!summary || !summary.holdings || summary.holdings.length === 0) {
- setError('Portfolio has no holdings');
- return;
- }
-
- // Fetch historical data for all holdings
- const priceData: Record<string, Record<string, number>> = {};
- const endDate = new Date();
- const startDate = new Date();
- startDate.setDate(startDate.getDate() - historicalDays);
-
- for (const holding of summary.holdings) {
- try {
- const data = await yfinanceService.getHistoricalData(
- holding.symbol,
- startDate.toISOString().split('T')[0],
- endDate.toISOString().split('T')[0]
- );
- if (data && data.length > 0) {
- priceData[holding.symbol] = {};
- data.forEach(point => {
- const dateStr = new Date(point.timestamp * 1000).toISOString().split('T')[0];
- priceData[holding.symbol][dateStr] = point.adj_close || point.close;
- });
- }
- } catch (err) {
- console.error(`Failed to fetch data for ${holding.symbol}:`, err);
- }
- }
-
- if (Object.keys(priceData).length > 0) {
- setPriceInput(JSON.stringify(priceData, null, 2));
- } else {
- setError('Failed to fetch historical data for portfolio');
- }
- } else if (dataSourceType === 'symbol') {
- // Handle single symbol or multiple symbols based on analysis mode
- const symbols = (analysisMode === 'comparison' || analysisMode === 'optimize')
- ? symbolsInput.split(',').map(s => s.trim()).filter(Boolean)
- : [symbolInput];
-
- const endDate = new Date();
- const startDate = new Date();
- startDate.setDate(startDate.getDate() - historicalDays);
-
- if (symbols.length === 1) {
- // Single symbol - simple format
- const data = await yfinanceService.getHistoricalData(
- symbols[0],
- startDate.toISOString().split('T')[0],
- endDate.toISOString().split('T')[0]
- );
-
- if (data && data.length > 0) {
- const priceData: Record<string, number> = {};
- data.forEach(point => {
- const dateStr = new Date(point.timestamp * 1000).toISOString().split('T')[0];
- priceData[dateStr] = point.adj_close || point.close;
- });
- setPriceInput(JSON.stringify(priceData, null, 2));
- } else {
- setError(`No data available for ${symbols[0]}`);
- }
- } else {
- // Multiple symbols - multi-asset format
- const priceData: Record<string, Record<string, number>> = {};
-
- for (const symbol of symbols) {
- try {
- const data = await yfinanceService.getHistoricalData(
- symbol,
- startDate.toISOString().split('T')[0],
- endDate.toISOString().split('T')[0]
- );
- if (data && data.length > 0) {
- priceData[symbol] = {};
- data.forEach(point => {
- const dateStr = new Date(point.timestamp * 1000).toISOString().split('T')[0];
- priceData[symbol][dateStr] = point.adj_close || point.close;
- });
- }
- } catch (err) {
- console.error(`Failed to fetch data for ${symbol}:`, err);
- }
- }
-
- if (Object.keys(priceData).length > 0) {
- setPriceInput(JSON.stringify(priceData, null, 2));
- } else {
- setError('Failed to fetch data for any symbols');
- }
- }
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Failed to load data');
- } finally {
- setPriceDataLoading(false);
- }
- }, [dataSourceType, selectedPortfolioId, symbolInput, symbolsInput, historicalDays, analysisMode]);
-
- const runAnalysis = async () => {
- setIsLoading(true);
- setError(null);
-
- try {
- const prices = JSON.parse(priceInput);
-
- if (analysisMode === 'performance') {
- // Run full analysis
- const result = await ffnService.fullAnalysis(prices, config);
- if (!result.success) {
- setError(result.error || 'Analysis failed');
- return;
- }
-
- // Get additional risk metrics
- const riskResult = await ffnService.riskMetrics(prices, config.risk_free_rate);
-
- setAnalysisResult({
- performance: result.performance as PerformanceMetrics,
- drawdowns: result.drawdowns,
- riskMetrics: riskResult.success ? {
- ulcer_index: riskResult.ulcer_index,
- skewness: riskResult.skewness,
- kurtosis: riskResult.kurtosis,
- var_95: riskResult.var_95,
- cvar_95: riskResult.cvar_95
- } : undefined
- });
- } else if (analysisMode === 'monthly') {
- // Monthly returns analysis
- const result = await ffnService.monthlyReturns(prices);
- if (!result.success) {
- setError(result.error || 'Monthly returns analysis failed');
- return;
- }
-
- setAnalysisResult({
- monthlyReturns: result.monthly_returns
- });
- } else if (analysisMode === 'rolling') {
- // Rolling metrics analysis
- const result = await ffnService.calculateRollingMetrics(prices, 63, ['sharpe', 'volatility']);
- if (!result.success) {
- setError(result.error || 'Rolling metrics analysis failed');
- return;
- }
-
- setAnalysisResult({
- rollingMetrics: result.metrics
- });
- } else if (analysisMode === 'comparison') {
- // Asset comparison
- const result = await ffnService.compareAssets(prices, undefined, config.risk_free_rate);
- if (!result.success) {
- setError(result.error || 'Asset comparison failed');
- return;
- }
-
- setAnalysisResult({
- comparison: result
- });
- } else if (analysisMode === 'optimize') {
- // Portfolio optimization
- const result = await ffnService.portfolioOptimization(
- prices,
- optimizationMethod,
- config.risk_free_rate,
- [0, 1]
- );
- if (!result.success) {
- setError(result.error || 'Portfolio optimization failed');
- return;
- }
-
- setAnalysisResult({
- optimization: result
- });
- } else if (analysisMode === 'benchmark') {
- // Benchmark comparison
- // Fetch benchmark data
- const endDate = new Date();
- const startDate = new Date();
- startDate.setDate(startDate.getDate() - historicalDays);
-
- const benchmarkData = await yfinanceService.getHistoricalData(
- benchmarkSymbol,
- startDate.toISOString().split('T')[0],
- endDate.toISOString().split('T')[0]
- );
-
- if (!benchmarkData || benchmarkData.length === 0) {
- setError(`No data available for benchmark ${benchmarkSymbol}`);
- return;
- }
-
- // Convert to price format
- const benchmarkPrices: Record<string, number> = {};
- benchmarkData.forEach(point => {
- const dateStr = new Date(point.timestamp * 1000).toISOString().split('T')[0];
- benchmarkPrices[dateStr] = point.adj_close || point.close;
- });
-
- const result = await ffnService.benchmarkComparison(
- prices,
- benchmarkPrices,
- benchmarkSymbol,
- config.risk_free_rate
- );
-
- if (!result.success) {
- setError(result.error || 'Benchmark comparison failed');
- return;
- }
-
- setAnalysisResult({
- benchmark: result
- });
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Analysis failed');
- } finally {
- setIsLoading(false);
- }
- };
-
- const toggleSection = (section: keyof typeof expandedSections) => {
- setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
- };
-
- const formatPercent = (value: number | null | undefined, decimals = 2): string => {
- if (value === null || value === undefined || isNaN(value)) return 'N/A';
- return `${(value * 100).toFixed(decimals)}%`;
- };
-
- const formatRatio = (value: number | null | undefined, decimals = 2): string => {
- if (value === null || value === undefined || isNaN(value)) return 'N/A';
- return value.toFixed(decimals);
- };
-
- const getValueColor = (value: number | null | undefined, inverse = false): string => {
- if (value === null || value === undefined) return FINCEPT.GRAY;
- if (inverse) return value < 0 ? FINCEPT.GREEN : value > 0 ? FINCEPT.RED : FINCEPT.WHITE;
- return value > 0 ? FINCEPT.GREEN : value < 0 ? FINCEPT.RED : FINCEPT.WHITE;
- };
-
- const getHeatmapColor = (value: number | null): string => {
- if (value === null || value === undefined) return FINCEPT.PANEL_BG;
- if (value > 0.05) return '#00D66F';
- if (value > 0.02) return '#00A050';
- if (value > 0) return '#006030';
- if (value > -0.02) return '#603000';
- if (value > -0.05) return '#A05000';
- return '#FF3B3B';
- };
-
- // Loading/Error states
- if (isFFNAvailable === null) {
- return (
- <div className="flex items-center justify-center h-full" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <RefreshCw size={32} color={FINCEPT.ORANGE} className="animate-spin" />
- </div>
- );
- }
-
- if (!isFFNAvailable) {
- return (
- <div className="flex items-center justify-center h-full p-8" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <div className="text-center max-w-md">
- <AlertCircle size={48} color={FINCEPT.RED} className="mx-auto mb-4" />
- <h3 className="text-lg font-bold uppercase mb-2" style={{ color: FINCEPT.WHITE }}>
- FFN Library Not Installed
- </h3>
- <code
- className="block p-4 rounded text-sm font-mono mt-4"
- style={{ backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.ORANGE }}
- >
- pip install ffn
- </code>
- <button
- onClick={checkFFNStatus}
- className="mt-6 px-6 py-2 rounded font-bold text-sm uppercase flex items-center gap-2 mx-auto"
- style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
- >
- <RefreshCw size={14} />
- Check Again
- </button>
- </div>
- </div>
- );
- }
-
- return (
- <div className="flex h-full" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- {/* Left Panel - Input */}
- <div
- className="w-80 flex flex-col border-r overflow-auto"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
- >
- {/* Data Source Section */}
- <div
- className="rounded overflow-hidden m-2"
- style={{ border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <button
- onClick={() => toggleSection('dataSource')}
- className="w-full px-3 py-2 flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <div className="flex items-center gap-2">
- <Database size={14} color={FINCEPT.CYAN} />
- <span className="text-xs font-bold uppercase" style={{ color: FINCEPT.WHITE }}>
- Data Source
- </span>
- </div>
- {expandedSections.dataSource ? (
- <ChevronUp size={14} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={14} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.dataSource && (
- <div className="p-3 space-y-3">
- {/* Data source type buttons */}
- <div className="flex gap-1">
- <button
- onClick={() => setDataSourceType('manual')}
- className="flex-1 px-2 py-1.5 rounded text-xs font-mono"
- style={{
- backgroundColor: dataSourceType === 'manual' ? FINCEPT.ORANGE : 'transparent',
- color: dataSourceType === 'manual' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- Manual
- </button>
- <button
- onClick={() => setDataSourceType('portfolio')}
- className="flex-1 px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"
- style={{
- backgroundColor: dataSourceType === 'portfolio' ? FINCEPT.ORANGE : 'transparent',
- color: dataSourceType === 'portfolio' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- <Briefcase size={12} />
- Portfolio
- </button>
- <button
- onClick={() => setDataSourceType('symbol')}
- className="flex-1 px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"
- style={{
- backgroundColor: dataSourceType === 'symbol' ? FINCEPT.ORANGE : 'transparent',
- color: dataSourceType === 'symbol' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- <Search size={12} />
- Symbol
- </button>
- </div>
-
- {/* Portfolio selector */}
- {dataSourceType === 'portfolio' && (
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- SELECT PORTFOLIO
- </label>
- <select
- value={selectedPortfolioId}
- onChange={(e) => setSelectedPortfolioId(e.target.value)}
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- {portfolios.map(p => (
- <option key={p.id} value={p.id}>{p.name}</option>
- ))}
- </select>
- </div>
- )}
-
- {/* Symbol input */}
- {dataSourceType === 'symbol' && (
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- {(analysisMode === 'comparison' || analysisMode === 'optimize') ? 'SYMBOLS (comma-separated)' : 'SYMBOL'}
- </label>
- <input
- type="text"
- value={(analysisMode === 'comparison' || analysisMode === 'optimize') ? symbolsInput : symbolInput}
- onChange={(e) => (analysisMode === 'comparison' || analysisMode === 'optimize')
- ? setSymbolsInput(e.target.value.toUpperCase())
- : setSymbolInput(e.target.value.toUpperCase())
- }
- placeholder={(analysisMode === 'comparison' || analysisMode === 'optimize') ? "AAPL,MSFT,GOOGL" : "AAPL"}
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- />
- </div>
- )}
-
- {/* Historical days */}
- {dataSourceType !== 'manual' && (
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- HISTORICAL DAYS
- </label>
- <input
- type="number"
- value={historicalDays}
- onChange={(e) => setHistoricalDays(parseInt(e.target.value) || 365)}
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- />
- </div>
- )}
-
- {/* Fetch data button */}
- {dataSourceType !== 'manual' && (
- <button
- onClick={fetchData}
- disabled={priceDataLoading}
- className="w-full py-2 rounded text-xs font-bold uppercase flex items-center justify-center gap-2"
- style={{
- backgroundColor: FINCEPT.CYAN,
- color: FINCEPT.DARK_BG,
- opacity: priceDataLoading ? 0.5 : 1
- }}
- >
- {priceDataLoading ? (
- <>
- <RefreshCw size={12} className="animate-spin" />
- Loading...
- </>
- ) : (
- <>
- <Database size={12} />
- Fetch Data
- </>
- )}
- </button>
- )}
- </div>
- )}
- </div>
-
- {/* Analysis Mode */}
- <div className="px-2 py-2">
- <label className="block text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
- ANALYSIS MODE
- </label>
- <div className="grid grid-cols-2 gap-1">
- <button
- onClick={() => setAnalysisMode('performance')}
- className="px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"
- style={{
- backgroundColor: analysisMode === 'performance' ? FINCEPT.ORANGE : 'transparent',
- color: analysisMode === 'performance' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- <Activity size={12} />
- Performance
- </button>
- <button
- onClick={() => setAnalysisMode('monthly')}
- className="px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"
- style={{
- backgroundColor: analysisMode === 'monthly' ? FINCEPT.ORANGE : 'transparent',
- color: analysisMode === 'monthly' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- <Calendar size={12} />
- Monthly
- </button>
- <button
- onClick={() => setAnalysisMode('rolling')}
- className="px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"
- style={{
- backgroundColor: analysisMode === 'rolling' ? FINCEPT.ORANGE : 'transparent',
- color: analysisMode === 'rolling' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- <LineChart size={12} />
- Rolling
- </button>
- <button
- onClick={() => setAnalysisMode('comparison')}
- className="px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"
- style={{
- backgroundColor: analysisMode === 'comparison' ? FINCEPT.ORANGE : 'transparent',
- color: analysisMode === 'comparison' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- <Layers size={12} />
- Compare
- </button>
- <button
- onClick={() => setAnalysisMode('optimize')}
- className="px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"
- style={{
- backgroundColor: analysisMode === 'optimize' ? FINCEPT.ORANGE : 'transparent',
- color: analysisMode === 'optimize' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- <Scale size={12} />
- Optimize
- </button>
- <button
- onClick={() => setAnalysisMode('benchmark')}
- className="px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"
- style={{
- backgroundColor: analysisMode === 'benchmark' ? FINCEPT.ORANGE : 'transparent',
- color: analysisMode === 'benchmark' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- <GitCompare size={12} />
- Benchmark
- </button>
- </div>
- </div>
-
- {/* Optimization Method Selector */}
- {analysisMode === 'optimize' && (
- <div className="px-2 py-2">
- <label className="block text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
- OPTIMIZATION METHOD
- </label>
- <div className="grid grid-cols-2 gap-1">
- <button
- onClick={() => setOptimizationMethod('erc')}
- className="px-2 py-1.5 rounded text-xs font-mono"
- style={{
- backgroundColor: optimizationMethod === 'erc' ? FINCEPT.CYAN : 'transparent',
- color: optimizationMethod === 'erc' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- ERC
- </button>
- <button
- onClick={() => setOptimizationMethod('inv_vol')}
- className="px-2 py-1.5 rounded text-xs font-mono"
- style={{
- backgroundColor: optimizationMethod === 'inv_vol' ? FINCEPT.CYAN : 'transparent',
- color: optimizationMethod === 'inv_vol' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- Inv Vol
- </button>
- <button
- onClick={() => setOptimizationMethod('mean_var')}
- className="px-2 py-1.5 rounded text-xs font-mono"
- style={{
- backgroundColor: optimizationMethod === 'mean_var' ? FINCEPT.CYAN : 'transparent',
- color: optimizationMethod === 'mean_var' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- Mean-Var
- </button>
- <button
- onClick={() => setOptimizationMethod('equal')}
- className="px-2 py-1.5 rounded text-xs font-mono"
- style={{
- backgroundColor: optimizationMethod === 'equal' ? FINCEPT.CYAN : 'transparent',
- color: optimizationMethod === 'equal' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- Equal Wt
- </button>
- </div>
- </div>
- )}
-
- {/* Benchmark Symbol Input */}
- {analysisMode === 'benchmark' && (
- <div className="px-2 py-2">
- <label className="block text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
- BENCHMARK SYMBOL
- </label>
- <input
- type="text"
- value={benchmarkSymbol}
- onChange={(e) => setBenchmarkSymbol(e.target.value.toUpperCase())}
- placeholder="SPY"
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- />
- <p className="text-xs font-mono mt-1" style={{ color: FINCEPT.MUTED }}>
- Common: SPY, QQQ, IWM, DIA
- </p>
- </div>
- )}
-
- {/* Price Input (for manual mode) */}
- {dataSourceType === 'manual' && (
- <div className="flex-1 p-2 overflow-auto">
- <label className="block text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
- PRICE DATA (JSON)
- </label>
- <textarea
- value={priceInput}
- onChange={(e) => setPriceInput(e.target.value)}
- className="w-full h-48 p-3 rounded text-xs font-mono resize-none"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- placeholder='{"2023-01-01": 100, "2023-01-02": 101, ...}'
- />
- </div>
- )}
-
- {/* Config Options */}
- <div className="p-2 space-y-3">
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- RISK-FREE RATE
- </label>
- <input
- type="number"
- step="0.01"
- value={config.risk_free_rate}
- onChange={(e) => setConfig({ ...config, risk_free_rate: parseFloat(e.target.value) || 0 })}
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- />
- </div>
-
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- DRAWDOWN THRESHOLD
- </label>
- <input
- type="number"
- step="0.01"
- value={config.drawdown_threshold}
- onChange={(e) => setConfig({ ...config, drawdown_threshold: parseFloat(e.target.value) || 0.05 })}
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- />
- </div>
- </div>
-
- {/* Run Button */}
- <div className="p-2 border-t" style={{ borderColor: FINCEPT.BORDER }}>
- <button
- onClick={runAnalysis}
- disabled={isLoading}
- className="w-full py-3 rounded font-bold text-sm uppercase flex items-center justify-center gap-2 disabled:opacity-50"
- style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
- >
- {isLoading ? (
- <>
- <RefreshCw size={16} className="animate-spin" />
- ANALYZING...
- </>
- ) : (
- <>
- <Activity size={16} />
- RUN ANALYSIS
- </>
- )}
- </button>
- </div>
- </div>
-
- {/* Right Panel - Results */}
- <div className="flex-1 overflow-auto p-4">
- {error && (
- <div
- className="mb-4 p-4 rounded flex items-center gap-3"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderLeft: `3px solid ${FINCEPT.RED}` }}
- >
- <AlertCircle size={20} color={FINCEPT.RED} />
- <span className="text-sm font-mono" style={{ color: FINCEPT.RED }}>{error}</span>
- </div>
- )}
-
- {!analysisResult && !error && (
- <div className="flex items-center justify-center h-full">
- <div className="text-center">
- <BarChart2 size={64} color={FINCEPT.MUTED} className="mx-auto mb-4" />
- <p className="text-sm font-mono" style={{ color: FINCEPT.GRAY }}>
- {analysisMode === 'performance' && 'Enter price data and click "Run Analysis" to see performance metrics'}
- {analysisMode === 'monthly' && 'Click "Run Analysis" to see monthly returns heatmap'}
- {analysisMode === 'rolling' && 'Click "Run Analysis" to see rolling performance metrics'}
- {analysisMode === 'comparison' && 'Enter multiple symbols and click "Run Analysis" to compare assets'}
- {analysisMode === 'optimize' && 'Enter multiple symbols and click "Run Analysis" to optimize portfolio weights'}
- {analysisMode === 'benchmark' && 'Enter portfolio data and benchmark symbol, then click "Run Analysis" to compare against benchmark'}
- </p>
- </div>
- </div>
- )}
-
- {analysisResult && (
- <div className="space-y-4">
- {/* Performance Metrics Section */}
- {analysisResult.performance && (
- <div
- className="rounded overflow-hidden"
- style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <button
- onClick={() => toggleSection('performance')}
- className="w-full px-4 py-3 flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <div className="flex items-center gap-2">
- <TrendingUp size={16} color={FINCEPT.GREEN} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- Performance Metrics
- </span>
- </div>
- {expandedSections.performance ? (
- <ChevronUp size={16} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={16} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.performance && (
- <div className="p-4 grid grid-cols-3 gap-4">
- <MetricCard
- label="Total Return"
- value={formatPercent(analysisResult.performance.total_return)}
- color={getValueColor(analysisResult.performance.total_return)}
- icon={<Percent size={14} />}
- />
- <MetricCard
- label="CAGR"
- value={formatPercent(analysisResult.performance.cagr)}
- color={getValueColor(analysisResult.performance.cagr)}
- icon={<TrendingUp size={14} />}
- />
- <MetricCard
- label="Sharpe Ratio"
- value={formatRatio(analysisResult.performance.sharpe_ratio)}
- color={getValueColor(analysisResult.performance.sharpe_ratio)}
- icon={<Target size={14} />}
- />
- <MetricCard
- label="Sortino Ratio"
- value={formatRatio(analysisResult.performance.sortino_ratio)}
- color={getValueColor(analysisResult.performance.sortino_ratio)}
- icon={<Target size={14} />}
- />
- <MetricCard
- label="Volatility"
- value={formatPercent(analysisResult.performance.volatility)}
- color={FINCEPT.YELLOW}
- icon={<Activity size={14} />}
- />
- <MetricCard
- label="Calmar Ratio"
- value={formatRatio(analysisResult.performance.calmar_ratio)}
- color={getValueColor(analysisResult.performance.calmar_ratio)}
- icon={<BarChart2 size={14} />}
- />
- <MetricCard
- label="Best Day"
- value={formatPercent(analysisResult.performance.best_day)}
- color={FINCEPT.GREEN}
- icon={<TrendingUp size={14} />}
- />
- <MetricCard
- label="Worst Day"
- value={formatPercent(analysisResult.performance.worst_day)}
- color={FINCEPT.RED}
- icon={<TrendingDown size={14} />}
- />
- <MetricCard
- label="Daily Mean"
- value={formatPercent(analysisResult.performance.daily_mean, 4)}
- color={getValueColor(analysisResult.performance.daily_mean)}
- icon={<LineChart size={14} />}
- />
- </div>
- )}
- </div>
- )}
-
- {/* Drawdowns Section */}
- {analysisResult.drawdowns && (
- <div
- className="rounded overflow-hidden"
- style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <button
- onClick={() => toggleSection('drawdowns')}
- className="w-full px-4 py-3 flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <div className="flex items-center gap-2">
- <TrendingDown size={16} color={FINCEPT.RED} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- Drawdown Analysis
- </span>
- </div>
- {expandedSections.drawdowns ? (
- <ChevronUp size={16} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={16} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.drawdowns && (
- <div className="p-4">
- <div className="mb-4">
- <MetricCard
- label="Max Drawdown"
- value={formatPercent(analysisResult.drawdowns.max_drawdown)}
- color={FINCEPT.RED}
- icon={<TrendingDown size={14} />}
- large
- />
- </div>
-
- {analysisResult.drawdowns.top_drawdowns && analysisResult.drawdowns.top_drawdowns.length > 0 && (
- <div>
- <h4 className="text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
- TOP DRAWDOWN PERIODS
- </h4>
- <div className="space-y-2">
- {analysisResult.drawdowns.top_drawdowns.map((dd, idx) => (
- <div
- key={idx}
- className="p-3 rounded flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.DARK_BG }}
- >
- <div className="flex items-center gap-3">
- <span
- className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold"
- style={{ backgroundColor: FINCEPT.RED, color: FINCEPT.WHITE }}
- >
- {idx + 1}
- </span>
- <div>
- <span className="text-xs font-mono" style={{ color: FINCEPT.WHITE }}>
- {dd.start} → {dd.end}
- </span>
- </div>
- </div>
- <span className="text-sm font-bold" style={{ color: FINCEPT.RED }}>
- {formatPercent(dd.drawdown)}
- </span>
- </div>
- ))}
- </div>
- </div>
- )}
- </div>
- )}
- </div>
- )}
-
- {/* Risk Metrics Section */}
- {analysisResult.riskMetrics && (
- <div
- className="rounded overflow-hidden"
- style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <button
- onClick={() => toggleSection('risk')}
- className="w-full px-4 py-3 flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <div className="flex items-center gap-2">
- <AlertCircle size={16} color={FINCEPT.YELLOW} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- Risk Metrics
- </span>
- </div>
- {expandedSections.risk ? (
- <ChevronUp size={16} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={16} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.risk && (
- <div className="p-4 grid grid-cols-3 gap-4">
- <MetricCard
- label="Ulcer Index"
- value={formatRatio(analysisResult.riskMetrics.ulcer_index, 4)}
- color={FINCEPT.YELLOW}
- icon={<Activity size={14} />}
- />
- <MetricCard
- label="Skewness"
- value={formatRatio(analysisResult.riskMetrics.skewness)}
- color={FINCEPT.CYAN}
- icon={<BarChart2 size={14} />}
- />
- <MetricCard
- label="Kurtosis"
- value={formatRatio(analysisResult.riskMetrics.kurtosis)}
- color={FINCEPT.CYAN}
- icon={<BarChart2 size={14} />}
- />
- <MetricCard
- label="VaR (95%)"
- value={formatPercent(analysisResult.riskMetrics.var_95)}
- color={FINCEPT.RED}
- icon={<TrendingDown size={14} />}
- />
- <MetricCard
- label="CVaR (95%)"
- value={formatPercent(analysisResult.riskMetrics.cvar_95)}
- color={FINCEPT.RED}
- icon={<TrendingDown size={14} />}
- />
- </div>
- )}
- </div>
- )}
-
- {/* Monthly Returns Heatmap */}
- {analysisResult.monthlyReturns && (
- <div
- className="rounded overflow-hidden"
- style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <button
- onClick={() => toggleSection('monthly')}
- className="w-full px-4 py-3 flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <div className="flex items-center gap-2">
- <Calendar size={16} color={FINCEPT.CYAN} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- Monthly Returns Heatmap
- </span>
- </div>
- {expandedSections.monthly ? (
- <ChevronUp size={16} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={16} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.monthly && (
- <div className="p-4 overflow-auto">
- <div className="min-w-[600px]">
- {/* Month headers */}
- <div className="flex">
- <div className="w-16 text-xs font-mono text-center" style={{ color: FINCEPT.GRAY }}>
- Year
- </div>
- {['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'].map(m => (
- <div key={m} className="flex-1 text-xs font-mono text-center" style={{ color: FINCEPT.GRAY }}>
- {m}
- </div>
- ))}
- </div>
- {/* Year rows */}
- {Object.entries(analysisResult.monthlyReturns).sort().map(([year, months]) => (
- <div key={year} className="flex mt-1">
- <div className="w-16 text-xs font-mono text-center py-2" style={{ color: FINCEPT.WHITE }}>
- {year}
- </div>
- {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map(m => {
- const value = months[String(m)] ?? null;
- return (
- <div
- key={m}
- className="flex-1 text-xs font-mono text-center py-2 mx-0.5 rounded"
- style={{
- backgroundColor: getHeatmapColor(value),
- color: FINCEPT.WHITE
- }}
- title={value !== null ? `${(value * 100).toFixed(2)}%` : 'N/A'}
- >
- {value !== null ? `${(value * 100).toFixed(1)}` : '-'}
- </div>
- );
- })}
- </div>
- ))}
- </div>
- </div>
- )}
- </div>
- )}
-
- {/* Rolling Metrics */}
- {analysisResult.rollingMetrics && (
- <div
- className="rounded overflow-hidden"
- style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <button
- onClick={() => toggleSection('rolling')}
- className="w-full px-4 py-3 flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <div className="flex items-center gap-2">
- <LineChart size={16} color={FINCEPT.PURPLE} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- Rolling Metrics (63-Day)
- </span>
- </div>
- {expandedSections.rolling ? (
- <ChevronUp size={16} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={16} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.rolling && (
- <div className="p-4">
- {analysisResult.rollingMetrics.rolling_sharpe && (
- <div className="mb-4">
- <h4 className="text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
- ROLLING SHARPE RATIO
- </h4>
- <div className="h-32 flex items-end gap-px">
- {Object.values(analysisResult.rollingMetrics.rolling_sharpe).slice(-50).map((value, idx) => {
- const height = Math.min(100, Math.max(10, ((value + 2) / 4) * 100));
- return (
- <div
- key={idx}
- className="flex-1 rounded-t"
- style={{
- height: `${height}%`,
- backgroundColor: value > 0 ? FINCEPT.GREEN : FINCEPT.RED
- }}
- />
- );
- })}
- </div>
- </div>
- )}
- {analysisResult.rollingMetrics.rolling_volatility && (
- <div>
- <h4 className="text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
- ROLLING VOLATILITY
- </h4>
- <div className="h-32 flex items-end gap-px">
- {Object.values(analysisResult.rollingMetrics.rolling_volatility).slice(-50).map((value, idx) => {
- const height = Math.min(100, Math.max(10, (value / 0.5) * 100));
- return (
- <div
- key={idx}
- className="flex-1 rounded-t"
- style={{
- height: `${height}%`,
- backgroundColor: FINCEPT.YELLOW
- }}
- />
- );
- })}
- </div>
- </div>
- )}
- </div>
- )}
- </div>
- )}
-
- {/* Asset Comparison */}
- {analysisResult.comparison && analysisResult.comparison.success && (
- <div
- className="rounded overflow-hidden"
- style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <button
- onClick={() => toggleSection('comparison')}
- className="w-full px-4 py-3 flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <div className="flex items-center gap-2">
- <Layers size={16} color={FINCEPT.BLUE} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- Asset Comparison
- </span>
- </div>
- {expandedSections.comparison ? (
- <ChevronUp size={16} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={16} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.comparison && (
- <div className="p-4 space-y-4">
- {/* Correlation Matrix */}
- {analysisResult.comparison.correlation_matrix && (
- <div>
- <h4 className="text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
- CORRELATION MATRIX
- </h4>
- <div className="overflow-auto">
- <table className="w-full text-xs font-mono">
- <thead>
- <tr>
- <th className="p-2" style={{ color: FINCEPT.GRAY }}></th>
- {Object.keys(analysisResult.comparison.correlation_matrix).map(symbol => (
- <th key={symbol} className="p-2" style={{ color: FINCEPT.WHITE }}>
- {symbol}
- </th>
- ))}
- </tr>
- </thead>
- <tbody>
- {Object.entries(analysisResult.comparison.correlation_matrix).map(([symbol, correlations]) => (
- <tr key={symbol}>
- <td className="p-2" style={{ color: FINCEPT.WHITE }}>{symbol}</td>
- {Object.entries(correlations).map(([otherSymbol, corr]) => (
- <td
- key={otherSymbol}
- className="p-2 text-center rounded"
- style={{
- backgroundColor: `rgba(0, 136, 255, ${Math.abs(corr)})`,
- color: FINCEPT.WHITE
- }}
- >
- {corr.toFixed(2)}
- </td>
- ))}
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- </div>
- )}
-
- {/* Asset Stats Comparison */}
- {analysisResult.comparison.asset_stats && (
- <div>
- <h4 className="text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
- PERFORMANCE COMPARISON
- </h4>
- <div className="overflow-auto">
- <table className="w-full text-xs font-mono">
- <thead>
- <tr>
- <th className="p-2 text-left" style={{ color: FINCEPT.GRAY }}>Asset</th>
- <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>Return</th>
- <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>Vol</th>
- <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>Sharpe</th>
- <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>MaxDD</th>
- </tr>
- </thead>
- <tbody>
- {Object.entries(analysisResult.comparison.asset_stats).map(([symbol, stats]) => (
- <tr key={symbol} className="border-t" style={{ borderColor: FINCEPT.BORDER }}>
- <td className="p-2" style={{ color: FINCEPT.WHITE }}>{symbol}</td>
- <td className="p-2 text-right" style={{ color: getValueColor(stats.total_return) }}>
- {formatPercent(stats.total_return)}
- </td>
- <td className="p-2 text-right" style={{ color: FINCEPT.YELLOW }}>
- {formatPercent(stats.volatility)}
- </td>
- <td className="p-2 text-right" style={{ color: getValueColor(stats.sharpe_ratio) }}>
- {formatRatio(stats.sharpe_ratio)}
- </td>
- <td className="p-2 text-right" style={{ color: FINCEPT.RED }}>
- {formatPercent(stats.max_drawdown)}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- </div>
- )}
- </div>
- )}
- </div>
- )}
-
- {/* Portfolio Optimization Results */}
- {analysisResult.optimization && analysisResult.optimization.success && (
- <div
- className="rounded overflow-hidden"
- style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <button
- onClick={() => toggleSection('optimization')}
- className="w-full px-4 py-3 flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <div className="flex items-center gap-2">
- <Scale size={16} color={FINCEPT.CYAN} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- Portfolio Optimization - {analysisResult.optimization.method}
- </span>
- </div>
- {expandedSections.optimization ? (
- <ChevronUp size={16} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={16} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.optimization && (
- <div className="p-4 space-y-4">
- {/* Optimal Weights */}
- {analysisResult.optimization.weights && (
- <div>
- <h4 className="text-xs font-mono mb-3" style={{ color: FINCEPT.GRAY }}>
- OPTIMAL WEIGHTS
- </h4>
- <div className="space-y-2">
- {Object.entries(analysisResult.optimization.weights)
- .sort(([, a], [, b]) => b - a)
- .map(([symbol, weight]) => (
- <div key={symbol} className="flex items-center gap-3">
- <span className="w-16 text-xs font-mono font-bold" style={{ color: FINCEPT.WHITE }}>
- {symbol}
- </span>
- <div className="flex-1 h-6 rounded overflow-hidden" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <div
- className="h-full rounded"
- style={{
- width: `${weight * 100}%`,
- backgroundColor: FINCEPT.CYAN
- }}
- />
- </div>
- <span className="w-16 text-right text-xs font-mono font-bold" style={{ color: FINCEPT.CYAN }}>
- {formatPercent(weight)}
- </span>
- </div>
- ))}
- </div>
- </div>
- )}
-
- {/* Portfolio Stats */}
- {analysisResult.optimization.portfolio_stats && (
- <div>
- <h4 className="text-xs font-mono mb-3" style={{ color: FINCEPT.GRAY }}>
- OPTIMIZED PORTFOLIO METRICS
- </h4>
- <div className="grid grid-cols-3 gap-3">
- <MetricCard
- label="Expected Return"
- value={formatPercent(analysisResult.optimization.portfolio_stats.total_return)}
- color={getValueColor(analysisResult.optimization.portfolio_stats.total_return)}
- icon={<TrendingUp size={14} />}
- />
- <MetricCard
- label="CAGR"
- value={formatPercent(analysisResult.optimization.portfolio_stats.cagr)}
- color={getValueColor(analysisResult.optimization.portfolio_stats.cagr)}
- icon={<TrendingUp size={14} />}
- />
- <MetricCard
- label="Volatility"
- value={formatPercent(analysisResult.optimization.portfolio_stats.volatility)}
- color={FINCEPT.YELLOW}
- icon={<Activity size={14} />}
- />
- <MetricCard
- label="Sharpe Ratio"
- value={formatRatio(analysisResult.optimization.portfolio_stats.sharpe_ratio)}
- color={getValueColor(analysisResult.optimization.portfolio_stats.sharpe_ratio)}
- icon={<Target size={14} />}
- />
- <MetricCard
- label="Sortino Ratio"
- value={formatRatio(analysisResult.optimization.portfolio_stats.sortino_ratio)}
- color={getValueColor(analysisResult.optimization.portfolio_stats.sortino_ratio)}
- icon={<Target size={14} />}
- />
- <MetricCard
- label="Max Drawdown"
- value={formatPercent(analysisResult.optimization.portfolio_stats.max_drawdown)}
- color={FINCEPT.RED}
- icon={<TrendingDown size={14} />}
- />
- </div>
- </div>
- )}
-
- {/* Asset Contributions */}
- {analysisResult.optimization.asset_contributions && (
- <div>
- <h4 className="text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
- ASSET CONTRIBUTIONS
- </h4>
- <div className="overflow-auto">
- <table className="w-full text-xs font-mono">
- <thead>
- <tr>
- <th className="p-2 text-left" style={{ color: FINCEPT.GRAY }}>Asset</th>
- <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>Weight</th>
- <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>Vol</th>
- <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>Return</th>
- <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>Risk Contrib</th>
- </tr>
- </thead>
- <tbody>
- {Object.entries(analysisResult.optimization.asset_contributions).map(([symbol, contrib]) => (
- <tr key={symbol} className="border-t" style={{ borderColor: FINCEPT.BORDER }}>
- <td className="p-2" style={{ color: FINCEPT.WHITE }}>{symbol}</td>
- <td className="p-2 text-right" style={{ color: FINCEPT.CYAN }}>
- {formatPercent(contrib.weight)}
- </td>
- <td className="p-2 text-right" style={{ color: FINCEPT.YELLOW }}>
- {formatPercent(contrib.volatility)}
- </td>
- <td className="p-2 text-right" style={{ color: getValueColor(contrib.return) }}>
- {formatPercent(contrib.return)}
- </td>
- <td className="p-2 text-right" style={{ color: FINCEPT.PURPLE }}>
- {formatPercent(contrib.risk_contribution)}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- </div>
- )}
- </div>
- )}
- </div>
- )}
-
- {/* Benchmark Comparison Results */}
- {analysisResult.benchmark && analysisResult.benchmark.success && (
- <div
- className="rounded overflow-hidden"
- style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <button
- onClick={() => toggleSection('benchmark')}
- className="w-full px-4 py-3 flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <div className="flex items-center gap-2">
- <GitCompare size={16} color={FINCEPT.PURPLE} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- Benchmark Comparison - {analysisResult.benchmark.benchmark_name || 'Benchmark'}
- </span>
- </div>
- {expandedSections.benchmark ? (
- <ChevronUp size={16} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={16} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.benchmark && (
- <div className="p-4 space-y-4">
- {/* Side by Side Performance Comparison */}
- <div className="grid grid-cols-2 gap-4">
- {/* Portfolio Stats */}
- <div>
- <h4 className="text-xs font-mono mb-3 flex items-center gap-2" style={{ color: FINCEPT.CYAN }}>
- <Briefcase size={14} />
- PORTFOLIO
- </h4>
- <div className="space-y-2">
- {analysisResult.benchmark.portfolio_stats && (
- <>
- <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Total Return</span>
- <span className="text-xs font-mono font-bold" style={{ color: getValueColor(analysisResult.benchmark.portfolio_stats.total_return) }}>
- {formatPercent(analysisResult.benchmark.portfolio_stats.total_return)}
- </span>
- </div>
- <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>CAGR</span>
- <span className="text-xs font-mono font-bold" style={{ color: getValueColor(analysisResult.benchmark.portfolio_stats.cagr) }}>
- {formatPercent(analysisResult.benchmark.portfolio_stats.cagr)}
- </span>
- </div>
- <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Volatility</span>
- <span className="text-xs font-mono font-bold" style={{ color: FINCEPT.YELLOW }}>
- {formatPercent(analysisResult.benchmark.portfolio_stats.volatility)}
- </span>
- </div>
- <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Sharpe Ratio</span>
- <span className="text-xs font-mono font-bold" style={{ color: getValueColor(analysisResult.benchmark.portfolio_stats.sharpe_ratio) }}>
- {formatRatio(analysisResult.benchmark.portfolio_stats.sharpe_ratio)}
- </span>
- </div>
- <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Max Drawdown</span>
- <span className="text-xs font-mono font-bold" style={{ color: FINCEPT.RED }}>
- {formatPercent(analysisResult.benchmark.portfolio_stats.max_drawdown)}
- </span>
- </div>
- </>
- )}
- </div>
- </div>
-
- {/* Benchmark Stats */}
- <div>
- <h4 className="text-xs font-mono mb-3 flex items-center gap-2" style={{ color: FINCEPT.ORANGE }}>
- <Target size={14} />
- {analysisResult.benchmark.benchmark_name || 'BENCHMARK'}
- </h4>
- <div className="space-y-2">
- {analysisResult.benchmark.benchmark_stats && (
- <>
- <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Total Return</span>
- <span className="text-xs font-mono font-bold" style={{ color: getValueColor(analysisResult.benchmark.benchmark_stats.total_return) }}>
- {formatPercent(analysisResult.benchmark.benchmark_stats.total_return)}
- </span>
- </div>
- <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>CAGR</span>
- <span className="text-xs font-mono font-bold" style={{ color: getValueColor(analysisResult.benchmark.benchmark_stats.cagr) }}>
- {formatPercent(analysisResult.benchmark.benchmark_stats.cagr)}
- </span>
- </div>
- <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Volatility</span>
- <span className="text-xs font-mono font-bold" style={{ color: FINCEPT.YELLOW }}>
- {formatPercent(analysisResult.benchmark.benchmark_stats.volatility)}
- </span>
- </div>
- <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Sharpe Ratio</span>
- <span className="text-xs font-mono font-bold" style={{ color: getValueColor(analysisResult.benchmark.benchmark_stats.sharpe_ratio) }}>
- {formatRatio(analysisResult.benchmark.benchmark_stats.sharpe_ratio)}
- </span>
- </div>
- <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Max Drawdown</span>
- <span className="text-xs font-mono font-bold" style={{ color: FINCEPT.RED }}>
- {formatPercent(analysisResult.benchmark.benchmark_stats.max_drawdown)}
- </span>
- </div>
- </>
- )}
- </div>
- </div>
- </div>
-
- {/* Relative Metrics */}
- {analysisResult.benchmark.relative_metrics && (
- <div>
- <h4 className="text-xs font-mono mb-3" style={{ color: FINCEPT.GRAY }}>
- RELATIVE METRICS
- </h4>
- <div className="grid grid-cols-4 gap-3">
- <MetricCard
- label="Alpha"
- value={formatPercent(analysisResult.benchmark.relative_metrics.alpha)}
- color={getValueColor(analysisResult.benchmark.relative_metrics.alpha)}
- icon={<TrendingUp size={14} />}
- />
- <MetricCard
- label="Beta"
- value={formatRatio(analysisResult.benchmark.relative_metrics.beta)}
- color={FINCEPT.CYAN}
- icon={<Activity size={14} />}
- />
- <MetricCard
- label="Correlation"
- value={formatRatio(analysisResult.benchmark.relative_metrics.correlation)}
- color={FINCEPT.BLUE}
- icon={<LineChart size={14} />}
- />
- <MetricCard
- label="Tracking Error"
- value={formatPercent(analysisResult.benchmark.relative_metrics.tracking_error)}
- color={FINCEPT.YELLOW}
- icon={<Target size={14} />}
- />
- <MetricCard
- label="Info Ratio"
- value={formatRatio(analysisResult.benchmark.relative_metrics.information_ratio)}
- color={getValueColor(analysisResult.benchmark.relative_metrics.information_ratio)}
- icon={<BarChart2 size={14} />}
- />
- <MetricCard
- label="Up Capture"
- value={formatPercent(analysisResult.benchmark.relative_metrics.up_capture)}
- color={FINCEPT.GREEN}
- icon={<TrendingUp size={14} />}
- />
- <MetricCard
- label="Down Capture"
- value={formatPercent(analysisResult.benchmark.relative_metrics.down_capture)}
- color={FINCEPT.RED}
- icon={<TrendingDown size={14} />}
- />
- </div>
- </div>
- )}
-
- {/* Date Range Info */}
- {analysisResult.benchmark.date_range && (
- <div className="flex items-center justify-between p-3 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <div className="flex items-center gap-2">
- <Calendar size={14} color={FINCEPT.GRAY} />
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- {analysisResult.benchmark.date_range.start} to {analysisResult.benchmark.date_range.end}
- </span>
- </div>
- <span className="text-xs font-mono" style={{ color: FINCEPT.MUTED }}>
- {analysisResult.benchmark.date_range.data_points} data points
- </span>
- </div>
- )}
- </div>
- )}
- </div>
- )}
- </div>
- )}
- </div>
- </div>
- );
-}
-
-// Metric Card Component
-function MetricCard({
- label,
- value,
- color,
- icon,
- large = false
-}: {
- label: string;
- value: string;
- color: string;
- icon: React.ReactNode;
- large?: boolean;
-}) {
- return (
- <div
- className={`p-3 rounded ${large ? 'col-span-3' : ''}`}
- style={{ backgroundColor: FINCEPT.DARK_BG }}
- >
- <div className="flex items-center gap-2 mb-1">
- <span style={{ color: FINCEPT.GRAY }}>{icon}</span>
- <span className="text-xs font-mono uppercase" style={{ color: FINCEPT.GRAY }}>
- {label}
- </span>
- </div>
- <span
- className={`font-bold font-mono ${large ? 'text-2xl' : 'text-lg'}`}
- style={{ color }}
- >
- {value}
- </span>
- </div>
- );
-}
+export { FFNAnalyticsPanel, default } from './ffn-analytics';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FortitudoPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FortitudoPanel.tsx
index d00c25233..7cf0ba2eb 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FortitudoPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FortitudoPanel.tsx
@@ -1,2032 +1,6 @@
/**
- * Fortitudo.tech Analytics Panel - Portfolio Risk Analytics
- * Fincept Professional Design
- * Integrated with fortitudo.tech library via PyO3
+ * FortitudoPanel
+ * This file re-exports the FortitudoPanel from its new modular location.
*/
-import React, { useState, useEffect, useMemo } from 'react';
-import {
- Shield,
- TrendingUp,
- TrendingDown,
- Activity,
- BarChart2,
- RefreshCw,
- AlertCircle,
- CheckCircle2,
- ChevronDown,
- ChevronUp,
- Play,
- Settings,
- Target,
- Percent,
- DollarSign,
- Layers,
- Grid,
- PieChart as PieChartIcon
-} from 'lucide-react';
-import {
- ScatterChart,
- Scatter,
- XAxis,
- YAxis,
- CartesianGrid,
- Tooltip,
- ResponsiveContainer,
- Line,
- ComposedChart,
- ReferenceLine,
- Cell,
- PieChart,
- Pie,
- Legend
-} from 'recharts';
-import {
- fortitudoService,
- type PortfolioMetrics,
- type FullAnalysisResponse,
- type OptionGreeksResponse,
- type OptimizationResult,
- type EfficientFrontierResponse,
- type OptimizationObjective
-} from '@/services/aiQuantLab/fortitudoService';
-import {
- portfolioFortitudoService,
- type PortfolioReturnsData
-} from '@/services/aiQuantLab/portfolioFortitudoService';
-import { type Portfolio, type PortfolioSummary } from '@/services/portfolio/portfolioService';
-import { Briefcase, Database } from 'lucide-react';
-
-// Fincept Professional Color Palette
-const FINCEPT = {
- 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'
-};
-
-// Sample portfolio data for demonstration
-const SAMPLE_RETURNS = {
- 'Stocks': Object.fromEntries(
- Array.from({ length: 200 }, (_, i) => [
- new Date(2024, 0, i + 1).toISOString().split('T')[0],
- 0.0003 + (Math.random() - 0.5) * 0.02
- ])
- ),
- 'Bonds': Object.fromEntries(
- Array.from({ length: 200 }, (_, i) => [
- new Date(2024, 0, i + 1).toISOString().split('T')[0],
- 0.0001 + (Math.random() - 0.5) * 0.005
- ])
- ),
- 'Commodities': Object.fromEntries(
- Array.from({ length: 200 }, (_, i) => [
- new Date(2024, 0, i + 1).toISOString().split('T')[0],
- 0.0002 + (Math.random() - 0.5) * 0.015
- ])
- ),
- 'Cash': Object.fromEntries(
- Array.from({ length: 200 }, (_, i) => [
- new Date(2024, 0, i + 1).toISOString().split('T')[0],
- 0.0001 + (Math.random() - 0.5) * 0.001
- ])
- )
-};
-
-const SAMPLE_WEIGHTS = [0.4, 0.3, 0.2, 0.1];
-
-type AnalysisMode = 'portfolio' | 'options' | 'entropy' | 'optimization';
-
-interface AnalysisResult {
- metrics_equal_weight?: PortfolioMetrics;
- metrics_exp_decay?: PortfolioMetrics;
- n_scenarios?: number;
- n_assets?: number;
- assets?: string[];
- half_life?: number;
- alpha?: number;
-}
-
-export function FortitudoPanel() {
- const [isFortitudoAvailable, setIsFortitudoAvailable] = useState<boolean | null>(null);
- const [isLoading, setIsLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [analysisResult, setAnalysisResult] = useState<AnalysisResult | null>(null);
- const [activeMode, setActiveMode] = useState<AnalysisMode>('portfolio');
-
- // Portfolio config
- const [weights, setWeights] = useState('[0.4, 0.3, 0.2, 0.1]');
- const [alpha, setAlpha] = useState(0.05);
- const [halfLife, setHalfLife] = useState(252);
-
- // Option pricing config
- const [spotPrice, setSpotPrice] = useState(100);
- const [strike, setStrike] = useState(100);
- const [volatility, setVolatility] = useState(0.25);
- const [riskFreeRate, setRiskFreeRate] = useState(0.05);
- const [dividendYield, setDividendYield] = useState(0.02);
- const [timeToMaturity, setTimeToMaturity] = useState(1.0);
- const [optionResult, setOptionResult] = useState<any>(null);
- const [greeksResult, setGreeksResult] = useState<OptionGreeksResponse | null>(null);
-
- // Entropy pooling config
- const [nScenarios, setNScenarios] = useState(100);
- const [maxProbability, setMaxProbability] = useState(0.05);
- const [entropyResult, setEntropyResult] = useState<any>(null);
-
- // Optimization config
- const [optimizationObjective, setOptimizationObjective] = useState<OptimizationObjective>('min_variance');
- const [optimizationType, setOptimizationType] = useState<'mv' | 'cvar'>('mv');
- const [optLongOnly, setOptLongOnly] = useState(true);
- const [optMaxWeight, setOptMaxWeight] = useState(0.5);
- const [optMinWeight, setOptMinWeight] = useState(0.0);
- const [optTargetReturn, setOptTargetReturn] = useState(0.08);
- const [optAlpha, setOptAlpha] = useState(0.05);
- const [optimizationResult, setOptimizationResult] = useState<OptimizationResult | null>(null);
- const [frontierResult, setFrontierResult] = useState<EfficientFrontierResponse | null>(null);
- const [nFrontierPoints, setNFrontierPoints] = useState(20);
- const [selectedFrontierIndex, setSelectedFrontierIndex] = useState<number | null>(null);
-
- const [expandedSections, setExpandedSections] = useState({
- config: true,
- metrics: true,
- comparison: true,
- matrix: false
- });
-
- // User portfolio integration
- const [userPortfolios, setUserPortfolios] = useState<Portfolio[]>([]);
- const [selectedPortfolioId, setSelectedPortfolioId] = useState<string | null>(null);
- const [selectedPortfolioSummary, setSelectedPortfolioSummary] = useState<PortfolioSummary | null>(null);
- const [portfolioReturnsData, setPortfolioReturnsData] = useState<PortfolioReturnsData | null>(null);
- const [dataSource, setDataSource] = useState<'sample' | 'portfolio'>('sample');
- const [isLoadingPortfolio, setIsLoadingPortfolio] = useState(false);
- const [historicalDays, setHistoricalDays] = useState(252);
-
- // Check fortitudo availability on mount
- useEffect(() => {
- checkFortitudoStatus();
- loadUserPortfolios();
- }, []);
-
- // Load portfolio summary and returns when selected
- useEffect(() => {
- if (selectedPortfolioId && dataSource === 'portfolio') {
- loadPortfolioData(selectedPortfolioId);
- }
- }, [selectedPortfolioId, dataSource]);
-
- const loadUserPortfolios = async () => {
- try {
- const portfolios = await portfolioFortitudoService.getAvailablePortfolios();
- setUserPortfolios(portfolios);
- } catch (err) {
- console.error('[FortitudoPanel] Failed to load portfolios:', err);
- }
- };
-
- const loadPortfolioData = async (portfolioId: string) => {
- setIsLoadingPortfolio(true);
- setError(null);
- try {
- const summary = await portfolioFortitudoService.getPortfolioSummary(portfolioId);
- setSelectedPortfolioSummary(summary);
-
- if (summary && summary.holdings.length > 0) {
- const returns = await portfolioFortitudoService.fetchHistoricalReturns(summary.holdings, historicalDays);
- setPortfolioReturnsData(returns);
-
- // Auto-update weights from portfolio
- if (returns) {
- setWeights(JSON.stringify(Object.values(returns.weights).map(w => Math.round(w * 1000) / 1000)));
- }
- }
- } catch (err) {
- setError(`Failed to load portfolio data: ${err}`);
- } finally {
- setIsLoadingPortfolio(false);
- }
- };
-
- const checkFortitudoStatus = async () => {
- try {
- const status = await fortitudoService.checkStatus();
- setIsFortitudoAvailable(status.available);
- if (!status.available) {
- setError('Fortitudo.tech library not installed. Run: pip install fortitudo.tech cvxopt');
- }
- } catch (err) {
- setIsFortitudoAvailable(false);
- setError('Failed to check fortitudo.tech status');
- }
- };
-
- const runPortfolioAnalysis = async () => {
- setIsLoading(true);
- setError(null);
-
- try {
- let returnsData: Record<string, Record<string, number>>;
- let weightsArray: number[];
-
- if (dataSource === 'portfolio' && portfolioReturnsData) {
- // Use user portfolio data
- returnsData = portfolioReturnsData.returns;
- weightsArray = Object.values(portfolioReturnsData.weights);
- } else {
- // Use sample data
- returnsData = SAMPLE_RETURNS;
- weightsArray = JSON.parse(weights);
- }
-
- const result = await fortitudoService.fullAnalysis(
- returnsData,
- weightsArray,
- alpha,
- halfLife
- );
-
- if (result.success && result.analysis) {
- // Add asset names from portfolio data if available
- if (dataSource === 'portfolio' && portfolioReturnsData) {
- result.analysis.assets = portfolioReturnsData.assets;
- }
- setAnalysisResult(result.analysis);
- } else {
- setError(result.error || 'Analysis failed');
- }
- } catch (err) {
- setError(String(err));
- } finally {
- setIsLoading(false);
- }
- };
-
- const runOptionPricing = async () => {
- setIsLoading(true);
- setError(null);
-
- try {
- const result = await fortitudoService.optionPricing(
- spotPrice,
- strike,
- volatility,
- riskFreeRate,
- dividendYield,
- timeToMaturity
- );
-
- if (result.success) {
- setOptionResult(result);
- } else {
- setError(result.error || 'Option pricing failed');
- }
- } catch (err) {
- setError(String(err));
- } finally {
- setIsLoading(false);
- }
- };
-
- const runOptionGreeks = async () => {
- setIsLoading(true);
- setError(null);
-
- try {
- const result = await fortitudoService.optionGreeks(
- spotPrice,
- strike,
- volatility,
- riskFreeRate,
- dividendYield,
- timeToMaturity
- );
-
- if (result.success) {
- setGreeksResult(result);
- } else {
- setError(result.error || 'Greeks calculation failed');
- }
- } catch (err) {
- setError(String(err));
- } finally {
- setIsLoading(false);
- }
- };
-
- const runEntropyPooling = async () => {
- setIsLoading(true);
- setError(null);
-
- try {
- const result = await fortitudoService.entropyPooling(nScenarios, maxProbability);
-
- if (result.success) {
- setEntropyResult(result);
- } else {
- setError(result.error || 'Entropy pooling failed');
- }
- } catch (err) {
- setError(String(err));
- } finally {
- setIsLoading(false);
- }
- };
-
- const runOptimization = async () => {
- setIsLoading(true);
- setError(null);
-
- try {
- // Use portfolio data if available, otherwise sample data
- const returnsData = (dataSource === 'portfolio' && portfolioReturnsData)
- ? portfolioReturnsData.returns
- : SAMPLE_RETURNS;
-
- let result: OptimizationResult;
-
- if (optimizationType === 'mv') {
- result = await fortitudoService.optimizeMeanVariance(
- returnsData,
- optimizationObjective,
- optLongOnly,
- optMaxWeight,
- optMinWeight,
- riskFreeRate,
- optimizationObjective === 'target_return' ? optTargetReturn : undefined
- );
- } else {
- result = await fortitudoService.optimizeMeanCVaR(
- returnsData,
- optimizationObjective === 'min_variance' ? 'min_cvar' : optimizationObjective,
- optAlpha,
- optLongOnly,
- optMaxWeight,
- optMinWeight,
- riskFreeRate,
- optimizationObjective === 'target_return' ? optTargetReturn : undefined
- );
- }
-
- // Add asset names from portfolio if available
- if (result.success && dataSource === 'portfolio' && portfolioReturnsData) {
- result.assets = portfolioReturnsData.assets;
- }
-
- if (result.success) {
- setOptimizationResult(result);
- } else {
- setError(result.error || 'Optimization failed');
- }
- } catch (err) {
- setError(String(err));
- } finally {
- setIsLoading(false);
- }
- };
-
- const runEfficientFrontier = async () => {
- setIsLoading(true);
- setError(null);
-
- try {
- // Use portfolio data if available, otherwise sample data
- const returnsData = (dataSource === 'portfolio' && portfolioReturnsData)
- ? portfolioReturnsData.returns
- : SAMPLE_RETURNS;
-
- let result: EfficientFrontierResponse;
-
- if (optimizationType === 'mv') {
- result = await fortitudoService.efficientFrontierMV(
- returnsData,
- nFrontierPoints,
- optLongOnly,
- optMaxWeight,
- riskFreeRate
- );
- } else {
- result = await fortitudoService.efficientFrontierCVaR(
- returnsData,
- nFrontierPoints,
- optAlpha,
- optLongOnly,
- optMaxWeight
- );
- }
-
- // Add asset names from portfolio if available
- if (result.success && dataSource === 'portfolio' && portfolioReturnsData) {
- result.assets = portfolioReturnsData.assets;
- }
-
- if (result.success) {
- setFrontierResult(result);
- setSelectedFrontierIndex(null); // Reset selection on new data
- } else {
- setError(result.error || 'Efficient frontier generation failed');
- }
- } catch (err) {
- setError(String(err));
- } finally {
- setIsLoading(false);
- }
- };
-
- const toggleSection = (section: keyof typeof expandedSections) => {
- setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
- };
-
- const formatPercent = (value: number | null | undefined) => {
- if (value === null || value === undefined || isNaN(value)) return 'N/A';
- return `${(value * 100).toFixed(2)}%`;
- };
-
- const formatRatio = (value: number | null | undefined) => {
- if (value === null || value === undefined || isNaN(value)) return 'N/A';
- return value.toFixed(3);
- };
-
- // Helper to normalize weights from object or array to array with asset names
- const normalizeWeights = (
- weights: number[] | Record<string, number> | undefined,
- assets: string[] | undefined
- ): { asset: string; weight: number }[] => {
- if (!weights) return [];
-
- if (Array.isArray(weights)) {
- return weights.map((w, idx) => ({
- asset: assets?.[idx] || `Asset ${idx + 1}`,
- weight: w
- }));
- } else {
- // weights is an object {assetName: weight}
- return Object.entries(weights).map(([asset, weight]) => ({
- asset,
- weight: weight as number
- }));
- }
- };
-
- // Render unavailable state
- if (isFortitudoAvailable === false) {
- return (
- <div className="flex items-center justify-center h-full p-8" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <div className="max-w-lg text-center">
- <AlertCircle size={64} color={FINCEPT.RED} className="mx-auto mb-6" />
- <h2 className="text-2xl font-bold uppercase tracking-wide mb-4" style={{ color: FINCEPT.WHITE }}>
- FORTITUDO.TECH NOT INSTALLED
- </h2>
- <p className="text-sm font-mono mb-6" style={{ color: FINCEPT.GRAY }}>
- Install the library to enable portfolio risk analytics:
- </p>
- <code
- className="block p-4 rounded text-sm font-mono mb-6"
- style={{ backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.ORANGE }}
- >
- pip install fortitudo.tech cvxopt
- </code>
- <button
- onClick={checkFortitudoStatus}
- className="px-6 py-2 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors inline-flex items-center gap-2"
- style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
- >
- <RefreshCw size={16} />
- RETRY
- </button>
- </div>
- </div>
- );
- }
-
- // Loading state
- if (isFortitudoAvailable === null) {
- return (
- <div className="flex items-center justify-center h-full" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <RefreshCw size={48} color={FINCEPT.ORANGE} className="animate-spin" />
- </div>
- );
- }
-
- return (
- <div className="h-full overflow-auto" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <div className="p-4 space-y-4">
- {/* Header */}
- <div
- className="flex items-center justify-between p-3 rounded border"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
- >
- <div className="flex items-center gap-3">
- <div className="p-2 rounded" style={{ backgroundColor: FINCEPT.ORANGE }}>
- <Shield size={20} color={FINCEPT.DARK_BG} />
- </div>
- <div>
- <h2 className="font-bold text-sm uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- FORTITUDO.TECH RISK ANALYTICS
- </h2>
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- VaR, CVaR, Option Pricing, Entropy Pooling
- </p>
- </div>
- </div>
- <div className="flex items-center gap-2">
- <CheckCircle2 size={16} color={FINCEPT.GREEN} />
- <span className="text-xs font-mono" style={{ color: FINCEPT.GREEN }}>READY</span>
- </div>
- </div>
-
- {/* Mode Selector */}
- <div
- className="flex rounded border overflow-hidden"
- style={{ borderColor: FINCEPT.BORDER }}
- >
- {[
- { id: 'portfolio', label: 'PORTFOLIO RISK', icon: Shield },
- { id: 'options', label: 'OPTION PRICING', icon: DollarSign },
- { id: 'optimization', label: 'OPTIMIZATION', icon: Target },
- { id: 'entropy', label: 'ENTROPY', icon: Layers }
- ].map(mode => (
- <button
- key={mode.id}
- onClick={() => setActiveMode(mode.id as AnalysisMode)}
- className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 text-xs font-semibold uppercase tracking-wide transition-all"
- style={{
- backgroundColor: activeMode === mode.id ? FINCEPT.ORANGE : FINCEPT.PANEL_BG,
- color: activeMode === mode.id ? FINCEPT.DARK_BG : FINCEPT.GRAY
- }}
- >
- <mode.icon size={14} />
- {mode.label}
- </button>
- ))}
- </div>
-
- {/* Data Source Selector */}
- <div
- className="p-3 rounded border"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
- >
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-3">
- <Database size={16} color={FINCEPT.CYAN} />
- <span className="text-xs font-bold uppercase" style={{ color: FINCEPT.WHITE }}>
- DATA SOURCE
- </span>
- </div>
- <div className="flex items-center gap-2">
- <div className="flex rounded border overflow-hidden" style={{ borderColor: FINCEPT.BORDER }}>
- <button
- onClick={() => setDataSource('sample')}
- className="px-3 py-1.5 text-xs font-bold uppercase transition-all"
- style={{
- backgroundColor: dataSource === 'sample' ? FINCEPT.ORANGE : FINCEPT.DARK_BG,
- color: dataSource === 'sample' ? FINCEPT.DARK_BG : FINCEPT.GRAY
- }}
- >
- SAMPLE DATA
- </button>
- <button
- onClick={() => setDataSource('portfolio')}
- className="px-3 py-1.5 text-xs font-bold uppercase transition-all flex items-center gap-1"
- style={{
- backgroundColor: dataSource === 'portfolio' ? FINCEPT.CYAN : FINCEPT.DARK_BG,
- color: dataSource === 'portfolio' ? FINCEPT.DARK_BG : FINCEPT.GRAY
- }}
- >
- <Briefcase size={12} />
- MY PORTFOLIOS
- </button>
- </div>
- </div>
- </div>
-
- {/* Portfolio Selector (shown when portfolio data source is selected) */}
- {dataSource === 'portfolio' && (
- <div className="mt-3 pt-3 border-t" style={{ borderColor: FINCEPT.BORDER }}>
- <div className="grid grid-cols-3 gap-4">
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- SELECT PORTFOLIO
- </label>
- <select
- value={selectedPortfolioId || ''}
- onChange={e => setSelectedPortfolioId(e.target.value || null)}
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- >
- <option value="">-- Select Portfolio --</option>
- {userPortfolios.map(p => (
- <option key={p.id} value={p.id}>{p.name}</option>
- ))}
- </select>
- </div>
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- HISTORICAL DAYS
- </label>
- <input
- type="number"
- value={historicalDays}
- onChange={e => setHistoricalDays(parseInt(e.target.value))}
- min="30"
- max="1000"
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- />
- </div>
- <div className="flex items-end">
- <button
- onClick={() => selectedPortfolioId && loadPortfolioData(selectedPortfolioId)}
- disabled={!selectedPortfolioId || isLoadingPortfolio}
- className="px-4 py-2 rounded font-bold uppercase tracking-wide text-xs hover:bg-opacity-90 transition-colors flex items-center gap-2 disabled:opacity-50"
- style={{ backgroundColor: FINCEPT.CYAN, color: FINCEPT.DARK_BG }}
- >
- {isLoadingPortfolio ? (
- <RefreshCw size={14} className="animate-spin" />
- ) : (
- <RefreshCw size={14} />
- )}
- LOAD DATA
- </button>
- </div>
- </div>
-
- {/* Portfolio Summary */}
- {selectedPortfolioSummary && portfolioReturnsData && (
- <div className="mt-3 p-3 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <div className="flex items-center gap-6 text-xs font-mono">
- <span style={{ color: FINCEPT.GRAY }}>
- Portfolio: <span style={{ color: FINCEPT.WHITE }}>{selectedPortfolioSummary.portfolio.name}</span>
- </span>
- <span style={{ color: FINCEPT.GRAY }}>
- Holdings: <span style={{ color: FINCEPT.CYAN }}>{selectedPortfolioSummary.holdings.length}</span>
- </span>
- <span style={{ color: FINCEPT.GRAY }}>
- Data Points: <span style={{ color: FINCEPT.CYAN }}>{portfolioReturnsData.nScenarios}</span>
- </span>
- <span style={{ color: FINCEPT.GRAY }}>
- Period: <span style={{ color: FINCEPT.WHITE }}>{portfolioReturnsData.startDate} to {portfolioReturnsData.endDate}</span>
- </span>
- </div>
- <div className="mt-2 flex flex-wrap gap-2">
- {portfolioReturnsData.assets.map((asset, idx) => (
- <span
- key={asset}
- className="px-2 py-0.5 rounded text-xs font-mono"
- style={{ backgroundColor: FINCEPT.BORDER, color: FINCEPT.WHITE }}
- >
- {asset}: {(portfolioReturnsData.weights[asset] * 100).toFixed(1)}%
- </span>
- ))}
- </div>
- </div>
- )}
-
- {/* No portfolios message */}
- {userPortfolios.length === 0 && (
- <div className="mt-3 p-3 rounded text-center" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- No portfolios found. Create a portfolio in the Portfolio tab first.
- </p>
- </div>
- )}
- </div>
- )}
- </div>
-
- {/* Error Display */}
- {error && (
- <div
- className="flex items-start gap-3 p-3 rounded border"
- style={{ backgroundColor: '#1a0000', borderColor: FINCEPT.RED }}
- >
- <AlertCircle size={18} color={FINCEPT.RED} className="flex-shrink-0 mt-0.5" />
- <div>
- <p className="text-sm font-bold" style={{ color: FINCEPT.RED }}>Error</p>
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>{error}</p>
- </div>
- </div>
- )}
-
- {/* Portfolio Risk Mode */}
- {activeMode === 'portfolio' && (
- <>
- {/* Configuration */}
- <div
- className="rounded border"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
- >
- <button
- onClick={() => toggleSection('config')}
- className="w-full flex items-center justify-between p-3"
- >
- <div className="flex items-center gap-2">
- <Settings size={16} color={FINCEPT.ORANGE} />
- <span className="text-sm font-bold uppercase" style={{ color: FINCEPT.WHITE }}>
- CONFIGURATION
- </span>
- </div>
- {expandedSections.config ? (
- <ChevronUp size={16} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={16} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.config && (
- <div className="p-4 border-t space-y-4" style={{ borderColor: FINCEPT.BORDER }}>
- <div className="grid grid-cols-3 gap-4">
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- PORTFOLIO WEIGHTS
- </label>
- <input
- type="text"
- value={weights}
- onChange={e => setWeights(e.target.value)}
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- />
- </div>
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- ALPHA (VaR/CVaR)
- </label>
- <input
- type="number"
- value={alpha}
- onChange={e => setAlpha(parseFloat(e.target.value))}
- step="0.01"
- min="0.01"
- max="0.50"
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- />
- </div>
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- HALF-LIFE (DAYS)
- </label>
- <input
- type="number"
- value={halfLife}
- onChange={e => setHalfLife(parseInt(e.target.value))}
- min="20"
- max="504"
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- />
- </div>
- </div>
-
- <button
- onClick={runPortfolioAnalysis}
- disabled={isLoading}
- className="w-full py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
- style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
- >
- {isLoading ? (
- <RefreshCw size={16} className="animate-spin" />
- ) : (
- <Play size={16} />
- )}
- RUN PORTFOLIO ANALYSIS
- </button>
- </div>
- )}
- </div>
-
- {/* Results */}
- {analysisResult && (
- <>
- {/* Metrics Comparison */}
- <div
- className="rounded border"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
- >
- <button
- onClick={() => toggleSection('metrics')}
- className="w-full flex items-center justify-between p-3"
- >
- <div className="flex items-center gap-2">
- <BarChart2 size={16} color={FINCEPT.CYAN} />
- <span className="text-sm font-bold uppercase" style={{ color: FINCEPT.WHITE }}>
- RISK METRICS
- </span>
- </div>
- {expandedSections.metrics ? (
- <ChevronUp size={16} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={16} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.metrics && (
- <div className="p-4 border-t" style={{ borderColor: FINCEPT.BORDER }}>
- <div className="grid grid-cols-2 gap-6">
- {/* Equal Weight Metrics */}
- <div>
- <h3 className="text-xs font-bold uppercase mb-3" style={{ color: FINCEPT.ORANGE }}>
- EQUAL WEIGHT SCENARIOS
- </h3>
- {analysisResult.metrics_equal_weight && (
- <div className="space-y-2">
- <MetricRow
- label="Expected Return"
- value={formatPercent(analysisResult.metrics_equal_weight.expected_return)}
- positive={analysisResult.metrics_equal_weight.expected_return > 0}
- />
- <MetricRow
- label="Volatility"
- value={formatPercent(analysisResult.metrics_equal_weight.volatility)}
- />
- <MetricRow
- label={`VaR (${(1 - alpha) * 100}%)`}
- value={formatPercent(analysisResult.metrics_equal_weight.var)}
- negative
- />
- <MetricRow
- label={`CVaR (${(1 - alpha) * 100}%)`}
- value={formatPercent(analysisResult.metrics_equal_weight.cvar)}
- negative
- />
- <MetricRow
- label="Sharpe Ratio"
- value={formatRatio(analysisResult.metrics_equal_weight.sharpe_ratio)}
- positive={analysisResult.metrics_equal_weight.sharpe_ratio > 0}
- />
- </div>
- )}
- </div>
-
- {/* Exp Decay Metrics */}
- <div>
- <h3 className="text-xs font-bold uppercase mb-3" style={{ color: FINCEPT.CYAN }}>
- EXP DECAY WEIGHTED ({halfLife}d)
- </h3>
- {analysisResult.metrics_exp_decay && (
- <div className="space-y-2">
- <MetricRow
- label="Expected Return"
- value={formatPercent(analysisResult.metrics_exp_decay.expected_return)}
- positive={analysisResult.metrics_exp_decay.expected_return > 0}
- />
- <MetricRow
- label="Volatility"
- value={formatPercent(analysisResult.metrics_exp_decay.volatility)}
- />
- <MetricRow
- label={`VaR (${(1 - alpha) * 100}%)`}
- value={formatPercent(analysisResult.metrics_exp_decay.var)}
- negative
- />
- <MetricRow
- label={`CVaR (${(1 - alpha) * 100}%)`}
- value={formatPercent(analysisResult.metrics_exp_decay.cvar)}
- negative
- />
- <MetricRow
- label="Sharpe Ratio"
- value={formatRatio(analysisResult.metrics_exp_decay.sharpe_ratio)}
- positive={analysisResult.metrics_exp_decay.sharpe_ratio > 0}
- />
- </div>
- )}
- </div>
- </div>
-
- {/* Summary */}
- <div
- className="mt-4 p-3 rounded"
- style={{ backgroundColor: FINCEPT.DARK_BG }}
- >
- <div className="flex items-center gap-6 text-xs font-mono">
- <span style={{ color: FINCEPT.GRAY }}>
- Scenarios: <span style={{ color: FINCEPT.WHITE }}>{analysisResult.n_scenarios}</span>
- </span>
- <span style={{ color: FINCEPT.GRAY }}>
- Assets: <span style={{ color: FINCEPT.WHITE }}>{analysisResult.n_assets}</span>
- </span>
- <span style={{ color: FINCEPT.GRAY }}>
- Alpha: <span style={{ color: FINCEPT.WHITE }}>{alpha}</span>
- </span>
- </div>
- </div>
- </div>
- )}
- </div>
- </>
- )}
- </>
- )}
-
- {/* Option Pricing Mode */}
- {activeMode === 'options' && (
- <div
- className="rounded border"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
- >
- <div className="p-4 space-y-4">
- <div className="grid grid-cols-6 gap-4">
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- SPOT PRICE
- </label>
- <input
- type="number"
- value={spotPrice}
- onChange={e => setSpotPrice(parseFloat(e.target.value))}
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- />
- </div>
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- STRIKE
- </label>
- <input
- type="number"
- value={strike}
- onChange={e => setStrike(parseFloat(e.target.value))}
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- />
- </div>
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- VOLATILITY
- </label>
- <input
- type="number"
- value={volatility}
- onChange={e => setVolatility(parseFloat(e.target.value))}
- step="0.01"
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- />
- </div>
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- RISK-FREE RATE
- </label>
- <input
- type="number"
- value={riskFreeRate}
- onChange={e => setRiskFreeRate(parseFloat(e.target.value))}
- step="0.01"
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- />
- </div>
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- DIV YIELD
- </label>
- <input
- type="number"
- value={dividendYield}
- onChange={e => setDividendYield(parseFloat(e.target.value))}
- step="0.01"
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- />
- </div>
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- TIME (YEARS)
- </label>
- <input
- type="number"
- value={timeToMaturity}
- onChange={e => setTimeToMaturity(parseFloat(e.target.value))}
- step="0.1"
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- />
- </div>
- </div>
-
- <div className="grid grid-cols-2 gap-4">
- <button
- onClick={runOptionPricing}
- disabled={isLoading}
- className="py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
- style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
- >
- {isLoading ? (
- <RefreshCw size={16} className="animate-spin" />
- ) : (
- <DollarSign size={16} />
- )}
- PRICE OPTIONS
- </button>
- <button
- onClick={runOptionGreeks}
- disabled={isLoading}
- className="py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
- style={{ backgroundColor: FINCEPT.CYAN, color: FINCEPT.DARK_BG }}
- >
- {isLoading ? (
- <RefreshCw size={16} className="animate-spin" />
- ) : (
- <Activity size={16} />
- )}
- CALCULATE GREEKS
- </button>
- </div>
-
- {/* Option Results */}
- {optionResult && optionResult.success && (
- <div className="grid grid-cols-4 gap-4 mt-4">
- <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>FORWARD</p>
- <p className="text-lg font-bold" style={{ color: FINCEPT.WHITE }}>
- ${optionResult.forward_price?.toFixed(2)}
- </p>
- </div>
- <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>CALL PRICE</p>
- <p className="text-lg font-bold" style={{ color: FINCEPT.GREEN }}>
- ${optionResult.call_price?.toFixed(4)}
- </p>
- </div>
- <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>PUT PRICE</p>
- <p className="text-lg font-bold" style={{ color: FINCEPT.RED }}>
- ${optionResult.put_price?.toFixed(4)}
- </p>
- </div>
- <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>STRADDLE</p>
- <p className="text-lg font-bold" style={{ color: FINCEPT.CYAN }}>
- ${optionResult.straddle?.straddle_price?.toFixed(4)}
- </p>
- </div>
- </div>
- )}
-
- {/* Greeks Results */}
- {greeksResult && greeksResult.success && (
- <div className="mt-4 p-4 rounded border" style={{ backgroundColor: FINCEPT.DARK_BG, borderColor: FINCEPT.BORDER }}>
- <h3 className="text-sm font-bold uppercase mb-4" style={{ color: FINCEPT.CYAN }}>
- OPTION GREEKS
- </h3>
- <div className="grid grid-cols-2 gap-6">
- {/* Call Greeks */}
- <div>
- <h4 className="text-xs font-bold uppercase mb-3" style={{ color: FINCEPT.GREEN }}>
- CALL OPTION
- </h4>
- <div className="space-y-2">
- <GreekRow label="Delta (Δ)" value={greeksResult.call?.delta} description="Price sensitivity" />
- <GreekRow label="Gamma (Γ)" value={greeksResult.call?.gamma} description="Delta sensitivity" />
- <GreekRow label="Vega (ν)" value={greeksResult.call?.vega} description="Volatility sensitivity" />
- <GreekRow label="Theta (Θ)" value={greeksResult.call?.theta} description="Time decay (daily)" />
- <GreekRow label="Rho (ρ)" value={greeksResult.call?.rho} description="Rate sensitivity" />
- </div>
- </div>
- {/* Put Greeks */}
- <div>
- <h4 className="text-xs font-bold uppercase mb-3" style={{ color: FINCEPT.RED }}>
- PUT OPTION
- </h4>
- <div className="space-y-2">
- <GreekRow label="Delta (Δ)" value={greeksResult.put?.delta} description="Price sensitivity" />
- <GreekRow label="Gamma (Γ)" value={greeksResult.put?.gamma} description="Delta sensitivity" />
- <GreekRow label="Vega (ν)" value={greeksResult.put?.vega} description="Volatility sensitivity" />
- <GreekRow label="Theta (Θ)" value={greeksResult.put?.theta} description="Time decay (daily)" />
- <GreekRow label="Rho (ρ)" value={greeksResult.put?.rho} description="Rate sensitivity" />
- </div>
- </div>
- </div>
- </div>
- )}
- </div>
- </div>
- )}
-
- {/* Portfolio Optimization Mode */}
- {activeMode === 'optimization' && (
- <div
- className="rounded border"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
- >
- <div className="p-4 space-y-4">
- {/* Optimization Type Toggle */}
- <div className="flex rounded border overflow-hidden" style={{ borderColor: FINCEPT.BORDER }}>
- <button
- onClick={() => setOptimizationType('mv')}
- className="flex-1 py-2 text-xs font-bold uppercase tracking-wide"
- style={{
- backgroundColor: optimizationType === 'mv' ? FINCEPT.ORANGE : FINCEPT.DARK_BG,
- color: optimizationType === 'mv' ? FINCEPT.DARK_BG : FINCEPT.GRAY
- }}
- >
- MEAN-VARIANCE
- </button>
- <button
- onClick={() => setOptimizationType('cvar')}
- className="flex-1 py-2 text-xs font-bold uppercase tracking-wide"
- style={{
- backgroundColor: optimizationType === 'cvar' ? FINCEPT.CYAN : FINCEPT.DARK_BG,
- color: optimizationType === 'cvar' ? FINCEPT.DARK_BG : FINCEPT.GRAY
- }}
- >
- MEAN-CVaR
- </button>
- </div>
-
- {/* Configuration */}
- <div className="grid grid-cols-4 gap-4">
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- OBJECTIVE
- </label>
- <select
- value={optimizationObjective}
- onChange={e => setOptimizationObjective(e.target.value as OptimizationObjective)}
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- >
- <option value="min_variance">{optimizationType === 'mv' ? 'Min Variance' : 'Min CVaR'}</option>
- <option value="max_sharpe">Max Sharpe</option>
- <option value="target_return">Target Return</option>
- </select>
- </div>
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- MAX WEIGHT
- </label>
- <input
- type="number"
- value={optMaxWeight}
- onChange={e => setOptMaxWeight(parseFloat(e.target.value))}
- step="0.05"
- min="0.1"
- max="1.0"
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- />
- </div>
- {optimizationObjective === 'target_return' && (
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- TARGET RETURN
- </label>
- <input
- type="number"
- value={optTargetReturn}
- onChange={e => setOptTargetReturn(parseFloat(e.target.value))}
- step="0.01"
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- />
- </div>
- )}
- {optimizationType === 'cvar' && (
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- CVaR ALPHA
- </label>
- <input
- type="number"
- value={optAlpha}
- onChange={e => setOptAlpha(parseFloat(e.target.value))}
- step="0.01"
- min="0.01"
- max="0.50"
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- />
- </div>
- )}
- <div className="flex items-end">
- <label className="flex items-center gap-2 cursor-pointer">
- <input
- type="checkbox"
- checked={optLongOnly}
- onChange={e => setOptLongOnly(e.target.checked)}
- className="w-4 h-4"
- />
- <span className="text-xs font-mono" style={{ color: FINCEPT.WHITE }}>LONG ONLY</span>
- </label>
- </div>
- </div>
-
- {/* Buttons */}
- <div className="grid grid-cols-2 gap-4">
- <button
- onClick={runOptimization}
- disabled={isLoading}
- className="py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
- style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
- >
- {isLoading ? (
- <RefreshCw size={16} className="animate-spin" />
- ) : (
- <Target size={16} />
- )}
- OPTIMIZE PORTFOLIO
- </button>
- <button
- onClick={runEfficientFrontier}
- disabled={isLoading}
- className="py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
- style={{ backgroundColor: FINCEPT.CYAN, color: FINCEPT.DARK_BG }}
- >
- {isLoading ? (
- <RefreshCw size={16} className="animate-spin" />
- ) : (
- <TrendingUp size={16} />
- )}
- EFFICIENT FRONTIER
- </button>
- </div>
-
- {/* Optimization Result */}
- {optimizationResult && optimizationResult.success && (() => {
- const normalizedWeights = normalizeWeights(optimizationResult.weights, optimizationResult.assets);
- const PIE_COLORS = [FINCEPT.ORANGE, FINCEPT.CYAN, FINCEPT.GREEN, FINCEPT.PURPLE, FINCEPT.YELLOW, FINCEPT.BLUE, FINCEPT.RED];
- return (
- <div className="p-4 rounded border" style={{ backgroundColor: FINCEPT.DARK_BG, borderColor: FINCEPT.BORDER }}>
- <h3 className="text-sm font-bold uppercase mb-4" style={{ color: FINCEPT.ORANGE }}>
- OPTIMAL PORTFOLIO
- </h3>
- <div className="grid grid-cols-3 gap-6">
- {/* Pie Chart */}
- <div>
- <h4 className="text-xs font-bold uppercase mb-3" style={{ color: FINCEPT.CYAN }}>
- ALLOCATION
- </h4>
- <div style={{ height: 180 }}>
- <ResponsiveContainer width="100%" height="100%">
- <PieChart>
- <Pie
- data={normalizedWeights
- .filter(item => item.weight > 0.001)
- .map((item, idx) => ({
- name: item.asset,
- value: Math.round(item.weight * 1000) / 10,
- weight: item.weight,
- fill: PIE_COLORS[idx % PIE_COLORS.length]
- }))}
- cx="50%"
- cy="50%"
- innerRadius={35}
- outerRadius={60}
- paddingAngle={2}
- dataKey="value"
- stroke={FINCEPT.DARK_BG}
- strokeWidth={2}
- >
- {normalizedWeights
- .filter(item => item.weight > 0.001)
- .map((_, idx) => (
- <Cell key={idx} fill={PIE_COLORS[idx % PIE_COLORS.length]} />
- ))}
- </Pie>
- <Tooltip
- contentStyle={{
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: 4,
- padding: '6px 10px'
- }}
- formatter={(value: number) => [`${value.toFixed(1)}%`, 'Weight']}
- labelStyle={{ color: FINCEPT.WHITE, fontWeight: 'bold', fontSize: 11 }}
- itemStyle={{ color: FINCEPT.GRAY, fontSize: 10 }}
- />
- </PieChart>
- </ResponsiveContainer>
- </div>
- {/* Pie Legend */}
- <div className="mt-2 space-y-1">
- {normalizedWeights
- .filter(item => item.weight > 0.001)
- .map((item, idx) => (
- <div key={idx} className="flex items-center gap-2">
- <div className="w-2 h-2 rounded-full" style={{ backgroundColor: PIE_COLORS[idx % PIE_COLORS.length] }} />
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>{item.asset}</span>
- <span className="text-xs font-mono font-bold ml-auto" style={{ color: FINCEPT.WHITE }}>
- {(item.weight * 100).toFixed(1)}%
- </span>
- </div>
- ))}
- </div>
- </div>
- {/* Weight Bars */}
- <div>
- <h4 className="text-xs font-bold uppercase mb-3" style={{ color: FINCEPT.CYAN }}>
- WEIGHTS
- </h4>
- <div className="space-y-2">
- {normalizedWeights.map((item, i) => (
- <div key={i} className="flex items-center justify-between">
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- {item.asset}
- </span>
- <div className="flex items-center gap-2">
- <div
- className="h-2 rounded"
- style={{
- width: `${Math.max(item.weight * 100, 5)}px`,
- backgroundColor: item.weight > 0 ? FINCEPT.GREEN : FINCEPT.RED
- }}
- />
- <span className="text-sm font-mono font-bold" style={{ color: FINCEPT.WHITE }}>
- {(item.weight * 100).toFixed(1)}%
- </span>
- </div>
- </div>
- ))}
- </div>
- </div>
- {/* Metrics */}
- <div>
- <h4 className="text-xs font-bold uppercase mb-3" style={{ color: FINCEPT.CYAN }}>
- METRICS
- </h4>
- <div className="space-y-2">
- <MetricRow
- label="Expected Return"
- value={formatPercent(optimizationResult.expected_return)}
- positive={(optimizationResult.expected_return ?? 0) > 0}
- />
- <MetricRow
- label="Volatility"
- value={formatPercent(optimizationResult.volatility)}
- />
- <MetricRow
- label="Sharpe Ratio"
- value={formatRatio(optimizationResult.sharpe_ratio)}
- positive={(optimizationResult.sharpe_ratio ?? 0) > 0}
- />
- {optimizationResult.cvar !== undefined && (
- <MetricRow
- label="CVaR"
- value={formatPercent(optimizationResult.cvar)}
- negative
- />
- )}
- </div>
- {/* Optimization Info */}
- <div className="mt-4 p-2 rounded" style={{ backgroundColor: FINCEPT.PANEL_BG }}>
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- Type: <span style={{ color: optimizationType === 'mv' ? FINCEPT.ORANGE : FINCEPT.CYAN }}>
- {optimizationType === 'mv' ? 'Mean-Variance' : 'Mean-CVaR'}
- </span>
- </p>
- <p className="text-xs font-mono mt-1" style={{ color: FINCEPT.GRAY }}>
- Objective: <span style={{ color: FINCEPT.WHITE }}>{optimizationObjective.replace('_', ' ').toUpperCase()}</span>
- </p>
- <p className="text-xs font-mono mt-1" style={{ color: FINCEPT.GRAY }}>
- Constraints: <span style={{ color: FINCEPT.WHITE }}>{optLongOnly ? 'Long Only' : 'Allow Short'}</span>
- </p>
- </div>
- </div>
- </div>
- </div>
- );
- })()}
-
- {/* Efficient Frontier Result */}
- {frontierResult && frontierResult.success && frontierResult.frontier && (
- <div className="p-4 rounded border" style={{ backgroundColor: FINCEPT.DARK_BG, borderColor: FINCEPT.BORDER }}>
- <h3 className="text-sm font-bold uppercase mb-4" style={{ color: FINCEPT.CYAN }}>
- EFFICIENT FRONTIER ({frontierResult.frontier.length} POINTS)
- </h3>
-
- {/* Chart Visualization */}
- <div className="mb-4" style={{ height: 300 }}>
- <ResponsiveContainer width="100%" height="100%">
- <ComposedChart
- margin={{ top: 20, right: 30, left: 20, bottom: 20 }}
- >
- <CartesianGrid
- strokeDasharray="3 3"
- stroke={FINCEPT.BORDER}
- vertical={true}
- />
- <XAxis
- type="number"
- dataKey="risk"
- name={optimizationType === 'mv' ? 'Volatility' : 'CVaR'}
- domain={['auto', 'auto']}
- tickFormatter={(value) => `${(value * 100).toFixed(1)}%`}
- stroke={FINCEPT.GRAY}
- tick={{ fill: FINCEPT.GRAY, fontSize: 10 }}
- label={{
- value: optimizationType === 'mv' ? 'VOLATILITY (%)' : 'CVaR (%)',
- position: 'bottom',
- fill: FINCEPT.GRAY,
- fontSize: 10,
- offset: 0
- }}
- />
- <YAxis
- type="number"
- dataKey="return"
- name="Expected Return"
- domain={['auto', 'auto']}
- tickFormatter={(value) => `${(value * 100).toFixed(1)}%`}
- stroke={FINCEPT.GRAY}
- tick={{ fill: FINCEPT.GRAY, fontSize: 10 }}
- label={{
- value: 'EXPECTED RETURN (%)',
- angle: -90,
- position: 'insideLeft',
- fill: FINCEPT.GRAY,
- fontSize: 10
- }}
- />
- <Tooltip
- contentStyle={{
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: 4,
- padding: '8px 12px'
- }}
- formatter={(value: number, name: string) => {
- if (name === 'return') return [`${(value * 100).toFixed(2)}%`, 'Return'];
- if (name === 'risk') return [`${(value * 100).toFixed(2)}%`, optimizationType === 'mv' ? 'Volatility' : 'CVaR'];
- if (name === 'sharpe') return [value.toFixed(3), 'Sharpe'];
- return [value, name];
- }}
- labelStyle={{ color: FINCEPT.WHITE }}
- itemStyle={{ color: FINCEPT.GRAY }}
- />
- {/* Frontier Line */}
- <Line
- data={frontierResult.frontier.map((point, idx) => ({
- risk: point.volatility ?? point.cvar ?? 0,
- return: point.expected_return,
- sharpe: point.sharpe_ratio ?? 0,
- index: idx
- }))}
- type="monotone"
- dataKey="return"
- stroke={FINCEPT.CYAN}
- strokeWidth={2}
- dot={false}
- />
- {/* Frontier Points */}
- <Scatter
- data={frontierResult.frontier.map((point, idx) => ({
- risk: point.volatility ?? point.cvar ?? 0,
- return: point.expected_return,
- sharpe: point.sharpe_ratio ?? 0,
- index: idx,
- isMaxSharpe: point.sharpe_ratio === Math.max(...frontierResult.frontier!.map(p => p.sharpe_ratio ?? 0))
- }))}
- fill={FINCEPT.ORANGE}
- onClick={(data: any) => {
- if (data && typeof data.index === 'number') {
- setSelectedFrontierIndex(data.index);
- }
- }}
- cursor="pointer"
- >
- {frontierResult.frontier.map((point, idx) => {
- const maxSharpe = Math.max(...frontierResult.frontier!.map(p => p.sharpe_ratio ?? 0));
- const isMaxSharpe = point.sharpe_ratio === maxSharpe;
- const isMinRisk = idx === 0;
- const isSelected = selectedFrontierIndex === idx;
- return (
- <Cell
- key={idx}
- fill={isSelected ? FINCEPT.YELLOW : isMaxSharpe ? FINCEPT.GREEN : isMinRisk ? FINCEPT.ORANGE : FINCEPT.CYAN}
- stroke={isSelected ? FINCEPT.WHITE : 'none'}
- strokeWidth={isSelected ? 2 : 0}
- r={isSelected ? 8 : isMaxSharpe || isMinRisk ? 6 : 4}
- />
- );
- })}
- </Scatter>
- </ComposedChart>
- </ResponsiveContainer>
- </div>
-
- {/* Legend */}
- <div className="flex items-center justify-center gap-6 mb-4">
- <div className="flex items-center gap-2">
- <div className="w-3 h-3 rounded-full" style={{ backgroundColor: FINCEPT.ORANGE }} />
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>MIN RISK</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-3 h-3 rounded-full" style={{ backgroundColor: FINCEPT.GREEN }} />
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>MAX SHARPE</span>
- </div>
- <div className="flex items-center gap-2">
- <div className="w-3 h-3 rounded-full" style={{ backgroundColor: FINCEPT.CYAN }} />
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>FRONTIER</span>
- </div>
- {selectedFrontierIndex !== null && (
- <div className="flex items-center gap-2">
- <div className="w-3 h-3 rounded-full border-2" style={{ backgroundColor: FINCEPT.YELLOW, borderColor: FINCEPT.WHITE }} />
- <span className="text-xs font-mono" style={{ color: FINCEPT.YELLOW }}>SELECTED</span>
- </div>
- )}
- </div>
-
- {/* Selected Portfolio Details */}
- {selectedFrontierIndex !== null && frontierResult.frontier[selectedFrontierIndex] && (
- <div
- className="mb-4 p-4 rounded border"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.YELLOW }}
- >
- <div className="flex items-center justify-between mb-3">
- <h4 className="text-sm font-bold uppercase" style={{ color: FINCEPT.YELLOW }}>
- SELECTED PORTFOLIO (#{selectedFrontierIndex + 1})
- </h4>
- <button
- onClick={() => setSelectedFrontierIndex(null)}
- className="text-xs font-mono px-2 py-1 rounded hover:bg-opacity-80"
- style={{ backgroundColor: FINCEPT.BORDER, color: FINCEPT.GRAY }}
- >
- CLEAR
- </button>
- </div>
- <div className="grid grid-cols-3 gap-6">
- {/* Pie Chart */}
- <div>
- <h5 className="text-xs font-bold uppercase mb-2" style={{ color: FINCEPT.CYAN }}>
- ALLOCATION
- </h5>
- <div style={{ height: 180 }}>
- <ResponsiveContainer width="100%" height="100%">
- <PieChart>
- <Pie
- data={(() => {
- const selectedPoint = frontierResult.frontier[selectedFrontierIndex];
- const weights = selectedPoint.weights;
- const PIE_COLORS = [FINCEPT.ORANGE, FINCEPT.CYAN, FINCEPT.GREEN, FINCEPT.PURPLE, FINCEPT.YELLOW, FINCEPT.BLUE, FINCEPT.RED];
- if (typeof weights === 'object' && !Array.isArray(weights)) {
- return Object.entries(weights)
- .filter(([_, w]) => (w as number) > 0.001)
- .map(([asset, weight], idx) => ({
- name: asset,
- value: Math.round((weight as number) * 1000) / 10,
- fill: PIE_COLORS[idx % PIE_COLORS.length]
- }));
- } else if (Array.isArray(weights)) {
- return weights
- .filter(w => w > 0.001)
- .map((w, idx) => ({
- name: `Asset ${idx + 1}`,
- value: Math.round(w * 1000) / 10,
- fill: PIE_COLORS[idx % PIE_COLORS.length]
- }));
- }
- return [];
- })()}
- cx="50%"
- cy="50%"
- innerRadius={35}
- outerRadius={60}
- paddingAngle={2}
- dataKey="value"
- stroke={FINCEPT.DARK_BG}
- strokeWidth={2}
- >
- {(() => {
- const selectedPoint = frontierResult.frontier[selectedFrontierIndex];
- const weights = selectedPoint.weights;
- const PIE_COLORS = [FINCEPT.ORANGE, FINCEPT.CYAN, FINCEPT.GREEN, FINCEPT.PURPLE, FINCEPT.YELLOW, FINCEPT.BLUE, FINCEPT.RED];
- if (typeof weights === 'object' && !Array.isArray(weights)) {
- return Object.entries(weights)
- .filter(([_, w]) => (w as number) > 0.001)
- .map(([asset, _], idx) => (
- <Cell key={asset} fill={PIE_COLORS[idx % PIE_COLORS.length]} />
- ));
- } else if (Array.isArray(weights)) {
- return weights
- .filter(w => w > 0.001)
- .map((_, idx) => (
- <Cell key={idx} fill={PIE_COLORS[idx % PIE_COLORS.length]} />
- ));
- }
- return null;
- })()}
- </Pie>
- <Tooltip
- contentStyle={{
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${FINCEPT.BORDER}`,
- borderRadius: 4,
- padding: '6px 10px'
- }}
- formatter={(value: number) => [`${value.toFixed(1)}%`, 'Weight']}
- labelStyle={{ color: FINCEPT.WHITE, fontWeight: 'bold', fontSize: 11 }}
- itemStyle={{ color: FINCEPT.GRAY, fontSize: 10 }}
- />
- </PieChart>
- </ResponsiveContainer>
- </div>
- {/* Pie Legend */}
- <div className="mt-2 space-y-1">
- {(() => {
- const selectedPoint = frontierResult.frontier[selectedFrontierIndex];
- const weights = selectedPoint.weights;
- const PIE_COLORS = [FINCEPT.ORANGE, FINCEPT.CYAN, FINCEPT.GREEN, FINCEPT.PURPLE, FINCEPT.YELLOW, FINCEPT.BLUE, FINCEPT.RED];
- if (typeof weights === 'object' && !Array.isArray(weights)) {
- return Object.entries(weights)
- .filter(([_, w]) => (w as number) > 0.001)
- .map(([asset, weight], idx) => (
- <div key={asset} className="flex items-center gap-2">
- <div className="w-2 h-2 rounded-full" style={{ backgroundColor: PIE_COLORS[idx % PIE_COLORS.length] }} />
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>{asset}</span>
- <span className="text-xs font-mono font-bold ml-auto" style={{ color: FINCEPT.WHITE }}>
- {((weight as number) * 100).toFixed(1)}%
- </span>
- </div>
- ));
- } else if (Array.isArray(weights)) {
- return weights
- .filter(w => w > 0.001)
- .map((w, idx) => (
- <div key={idx} className="flex items-center gap-2">
- <div className="w-2 h-2 rounded-full" style={{ backgroundColor: PIE_COLORS[idx % PIE_COLORS.length] }} />
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Asset {idx + 1}</span>
- <span className="text-xs font-mono font-bold ml-auto" style={{ color: FINCEPT.WHITE }}>
- {(w * 100).toFixed(1)}%
- </span>
- </div>
- ));
- }
- return null;
- })()}
- </div>
- </div>
- {/* Weight Bars */}
- <div>
- <h5 className="text-xs font-bold uppercase mb-2" style={{ color: FINCEPT.CYAN }}>
- WEIGHTS
- </h5>
- <div className="space-y-1">
- {(() => {
- const selectedPoint = frontierResult.frontier[selectedFrontierIndex];
- const weights = selectedPoint.weights;
- if (typeof weights === 'object' && !Array.isArray(weights)) {
- return Object.entries(weights).map(([asset, weight]) => (
- <div key={asset} className="flex items-center justify-between">
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- {asset}
- </span>
- <div className="flex items-center gap-2">
- <div
- className="h-2 rounded"
- style={{
- width: `${Math.max((weight as number) * 80, 3)}px`,
- backgroundColor: (weight as number) > 0 ? FINCEPT.GREEN : FINCEPT.RED
- }}
- />
- <span className="text-xs font-mono font-bold" style={{ color: FINCEPT.WHITE }}>
- {((weight as number) * 100).toFixed(1)}%
- </span>
- </div>
- </div>
- ));
- } else if (Array.isArray(weights)) {
- return weights.map((w, i) => (
- <div key={i} className="flex items-center justify-between">
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- Asset {i + 1}
- </span>
- <div className="flex items-center gap-2">
- <div
- className="h-2 rounded"
- style={{
- width: `${Math.max(w * 80, 3)}px`,
- backgroundColor: w > 0 ? FINCEPT.GREEN : FINCEPT.RED
- }}
- />
- <span className="text-xs font-mono font-bold" style={{ color: FINCEPT.WHITE }}>
- {(w * 100).toFixed(1)}%
- </span>
- </div>
- </div>
- ));
- }
- return null;
- })()}
- </div>
- </div>
- {/* Metrics */}
- <div>
- <h5 className="text-xs font-bold uppercase mb-2" style={{ color: FINCEPT.CYAN }}>
- METRICS
- </h5>
- <div className="space-y-1">
- <div className="flex items-center justify-between py-1 border-b" style={{ borderColor: FINCEPT.BORDER }}>
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Expected Return</span>
- <span className="text-sm font-mono font-bold" style={{ color: FINCEPT.GREEN }}>
- {(frontierResult.frontier[selectedFrontierIndex].expected_return * 100).toFixed(2)}%
- </span>
- </div>
- <div className="flex items-center justify-between py-1 border-b" style={{ borderColor: FINCEPT.BORDER }}>
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- {optimizationType === 'mv' ? 'Volatility' : 'CVaR'}
- </span>
- <span className="text-sm font-mono font-bold" style={{ color: FINCEPT.RED }}>
- {((frontierResult.frontier[selectedFrontierIndex].volatility ?? frontierResult.frontier[selectedFrontierIndex].cvar ?? 0) * 100).toFixed(2)}%
- </span>
- </div>
- <div className="flex items-center justify-between py-1">
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Sharpe Ratio</span>
- <span className="text-sm font-mono font-bold" style={{ color: FINCEPT.WHITE }}>
- {frontierResult.frontier[selectedFrontierIndex].sharpe_ratio?.toFixed(3) ?? 'N/A'}
- </span>
- </div>
- </div>
- {/* Position on Frontier */}
- <div className="mt-4 p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- Position: <span style={{ color: FINCEPT.YELLOW }}>{selectedFrontierIndex + 1}</span> of {frontierResult.frontier.length}
- </p>
- <p className="text-xs font-mono mt-1" style={{ color: FINCEPT.GRAY }}>
- {selectedFrontierIndex === 0 ? (
- <span style={{ color: FINCEPT.ORANGE }}>Minimum Risk Portfolio</span>
- ) : selectedFrontierIndex === frontierResult.frontier.length - 1 ? (
- <span style={{ color: FINCEPT.CYAN }}>Maximum Return Portfolio</span>
- ) : frontierResult.frontier[selectedFrontierIndex].sharpe_ratio === Math.max(...frontierResult.frontier.map(p => p.sharpe_ratio ?? 0)) ? (
- <span style={{ color: FINCEPT.GREEN }}>Maximum Sharpe Portfolio</span>
- ) : (
- <span style={{ color: FINCEPT.MUTED }}>Intermediate Portfolio</span>
- )}
- </p>
- </div>
- </div>
- </div>
- </div>
- )}
-
- {/* Summary Stats */}
- <div className="grid grid-cols-3 gap-4 p-3 rounded" style={{ backgroundColor: FINCEPT.PANEL_BG }}>
- <div className="text-center">
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>MIN RISK</p>
- <p className="text-sm font-bold" style={{ color: FINCEPT.ORANGE }}>
- {((frontierResult.frontier[0]?.volatility ?? frontierResult.frontier[0]?.cvar ?? 0) * 100).toFixed(2)}%
- </p>
- <p className="text-xs font-mono" style={{ color: FINCEPT.MUTED }}>
- Return: {(frontierResult.frontier[0]?.expected_return * 100).toFixed(2)}%
- </p>
- </div>
- <div className="text-center">
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>MAX SHARPE</p>
- {(() => {
- const maxSharpePoint = frontierResult.frontier.reduce((max, p) =>
- (p.sharpe_ratio ?? 0) > (max.sharpe_ratio ?? 0) ? p : max
- );
- return (
- <>
- <p className="text-sm font-bold" style={{ color: FINCEPT.GREEN }}>
- {maxSharpePoint.sharpe_ratio?.toFixed(3) ?? 'N/A'}
- </p>
- <p className="text-xs font-mono" style={{ color: FINCEPT.MUTED }}>
- Return: {(maxSharpePoint.expected_return * 100).toFixed(2)}%
- </p>
- </>
- );
- })()}
- </div>
- <div className="text-center">
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>MAX RETURN</p>
- <p className="text-sm font-bold" style={{ color: FINCEPT.CYAN }}>
- {(frontierResult.frontier[frontierResult.frontier.length - 1]?.expected_return * 100).toFixed(2)}%
- </p>
- <p className="text-xs font-mono" style={{ color: FINCEPT.MUTED }}>
- Risk: {((frontierResult.frontier[frontierResult.frontier.length - 1]?.volatility ?? frontierResult.frontier[frontierResult.frontier.length - 1]?.cvar ?? 0) * 100).toFixed(2)}%
- </p>
- </div>
- </div>
- </div>
- )}
- </div>
- </div>
- )}
-
- {/* Entropy Pooling Mode */}
- {activeMode === 'entropy' && (
- <div
- className="rounded border"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
- >
- <div className="p-4 space-y-4">
- <div className="grid grid-cols-2 gap-4">
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- NUMBER OF SCENARIOS
- </label>
- <input
- type="number"
- value={nScenarios}
- onChange={e => setNScenarios(parseInt(e.target.value))}
- min="10"
- max="10000"
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- />
- </div>
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- MAX PROBABILITY (%)
- </label>
- <input
- type="number"
- value={maxProbability * 100}
- onChange={e => setMaxProbability(parseFloat(e.target.value) / 100)}
- step="0.5"
- min="0.5"
- max="100"
- className="w-full px-3 py-2 rounded text-sm font-mono border"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- borderColor: FINCEPT.BORDER,
- color: FINCEPT.WHITE
- }}
- />
- </div>
- </div>
-
- <button
- onClick={runEntropyPooling}
- disabled={isLoading}
- className="w-full py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
- style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
- >
- {isLoading ? (
- <RefreshCw size={16} className="animate-spin" />
- ) : (
- <Layers size={16} />
- )}
- APPLY ENTROPY POOLING
- </button>
-
- {/* Entropy Results */}
- {entropyResult && entropyResult.success && (
- <div className="grid grid-cols-2 gap-4 mt-4">
- <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <p className="text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>PRIOR</p>
- <div className="space-y-1">
- <p className="text-xs font-mono" style={{ color: FINCEPT.WHITE }}>
- Effective Scenarios: {entropyResult.effective_scenarios_prior?.toFixed(1)}
- </p>
- </div>
- </div>
- <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <p className="text-xs font-mono mb-2" style={{ color: FINCEPT.CYAN }}>POSTERIOR</p>
- <div className="space-y-1">
- <p className="text-xs font-mono" style={{ color: FINCEPT.WHITE }}>
- Effective Scenarios: {entropyResult.effective_scenarios_posterior?.toFixed(1)}
- </p>
- <p className="text-xs font-mono" style={{ color: FINCEPT.WHITE }}>
- Max Prob: {(entropyResult.max_probability * 100).toFixed(2)}%
- </p>
- <p className="text-xs font-mono" style={{ color: FINCEPT.WHITE }}>
- Min Prob: {(entropyResult.min_probability * 100).toFixed(4)}%
- </p>
- </div>
- </div>
- </div>
- )}
- </div>
- </div>
- )}
- </div>
- </div>
- );
-}
-
-// Metric Row Component
-function MetricRow({
- label,
- value,
- positive,
- negative
-}: {
- label: string;
- value: string;
- positive?: boolean;
- negative?: boolean;
-}) {
- let valueColor = FINCEPT.WHITE;
- if (positive) valueColor = FINCEPT.GREEN;
- if (negative) valueColor = FINCEPT.RED;
-
- return (
- <div className="flex items-center justify-between py-1.5 border-b" style={{ borderColor: FINCEPT.BORDER }}>
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>{label}</span>
- <span className="text-sm font-mono font-semibold" style={{ color: valueColor }}>{value}</span>
- </div>
- );
-}
-
-// Greek Row Component for displaying option Greeks
-function GreekRow({
- label,
- value,
- description
-}: {
- label: string;
- value: number | undefined;
- description: string;
-}) {
- const formatGreek = (val: number | undefined) => {
- if (val === undefined || val === null || isNaN(val)) return 'N/A';
- return val.toFixed(4);
- };
-
- const getValueColor = (val: number | undefined) => {
- if (val === undefined || val === null || isNaN(val)) return FINCEPT.GRAY;
- if (val > 0) return FINCEPT.GREEN;
- if (val < 0) return FINCEPT.RED;
- return FINCEPT.WHITE;
- };
-
- return (
- <div className="flex items-center justify-between py-1.5 border-b" style={{ borderColor: FINCEPT.BORDER }}>
- <div>
- <span className="text-xs font-mono font-semibold" style={{ color: FINCEPT.WHITE }}>{label}</span>
- <span className="text-xs font-mono ml-2" style={{ color: FINCEPT.MUTED }}>{description}</span>
- </div>
- <span className="text-sm font-mono font-bold" style={{ color: getValueColor(value) }}>
- {formatGreek(value)}
- </span>
- </div>
- );
-}
+export { FortitudoPanel, default } from './fortitudo';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FunctimePanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FunctimePanel.tsx
index 5541858f3..103af8e1e 100644
--- a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FunctimePanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/FunctimePanel.tsx
@@ -1,1814 +1,6 @@
/**
- * Functime Analytics Panel - Time Series Forecasting
- * Fincept Professional Design
- * Integrated with functime library via PyO3
- * Enhanced with portfolio integration and yfinance data fetching
+ * FunctimePanel
+ * This file re-exports the FunctimePanel from its new modular location.
*/
-import React, { useState, useEffect, useMemo, useCallback } from 'react';
-import {
- TrendingUp,
- TrendingDown,
- Activity,
- BarChart2,
- Calendar,
- RefreshCw,
- AlertCircle,
- CheckCircle2,
- ChevronDown,
- ChevronUp,
- LineChart,
- Play,
- Settings,
- Zap,
- Target,
- Clock,
- Layers,
- GitBranch,
- Database,
- Briefcase,
- Search,
- AlertTriangle,
- Waves,
- BarChart3,
- History,
- Shuffle,
- Shield
-} from 'lucide-react';
-import {
- functimeService,
- type ForecastResult,
- type ForecastConfig,
- type PreprocessConfig,
- type FullPipelineResponse,
- type AnomalyDetectionConfig,
- type SeasonalityConfig,
- type ConfidenceIntervalsConfig,
- type BacktestConfig
-} from '@/services/aiQuantLab/functimeService';
-import {
- portfolioFunctimeService,
- type PortfolioPriceData,
- type PortfolioForecastResult,
- type PortfolioAnomalyResult,
- type PortfolioSeasonalityResult
-} from '@/services/aiQuantLab/portfolioFunctimeService';
-import { portfolioService, type Portfolio } from '@/services/portfolio/portfolioService';
-
-// Fincept Professional Color Palette
-const FINCEPT = {
- 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'
-};
-
-// Sample panel data for demonstration
-const SAMPLE_DATA = [
- { entity_id: 'AAPL', time: '2024-01-02', value: 185.64 },
- { entity_id: 'AAPL', time: '2024-01-03', value: 184.25 },
- { entity_id: 'AAPL', time: '2024-01-04', value: 181.91 },
- { entity_id: 'AAPL', time: '2024-01-05', value: 181.18 },
- { entity_id: 'AAPL', time: '2024-01-08', value: 185.56 },
- { entity_id: 'AAPL', time: '2024-01-09', value: 185.14 },
- { entity_id: 'AAPL', time: '2024-01-10', value: 186.19 },
- { entity_id: 'AAPL', time: '2024-01-11', value: 185.59 },
- { entity_id: 'AAPL', time: '2024-01-12', value: 185.92 },
- { entity_id: 'AAPL', time: '2024-01-16', value: 183.63 },
- { entity_id: 'AAPL', time: '2024-01-17', value: 182.68 },
- { entity_id: 'AAPL', time: '2024-01-18', value: 188.63 },
- { entity_id: 'AAPL', time: '2024-01-19', value: 191.56 },
- { entity_id: 'AAPL', time: '2024-01-22', value: 193.89 },
- { entity_id: 'AAPL', time: '2024-01-23', value: 195.18 },
- { entity_id: 'AAPL', time: '2024-01-24', value: 194.50 },
- { entity_id: 'AAPL', time: '2024-01-25', value: 194.17 },
- { entity_id: 'AAPL', time: '2024-01-26', value: 192.42 },
- { entity_id: 'AAPL', time: '2024-01-29', value: 191.73 },
- { entity_id: 'AAPL', time: '2024-01-30', value: 188.04 }
-];
-
-interface ForecastAnalysisResult {
- forecast?: ForecastResult[];
- model?: string;
- horizon?: number;
- frequency?: string;
- best_params?: Record<string, unknown>;
- evaluation_metrics?: {
- mae?: number;
- rmse?: number;
- smape?: number;
- };
- data_summary?: {
- total_rows: number;
- entities: number;
- train_size: number;
- test_size: number;
- };
-}
-
-// Data source types
-type DataSourceType = 'manual' | 'portfolio' | 'symbol';
-
-// Analysis mode types
-type AnalysisMode = 'forecast' | 'anomaly' | 'seasonality' | 'backtest';
-
-export function FunctimePanel() {
- const [isFunctimeAvailable, setIsFunctimeAvailable] = useState<boolean | null>(null);
- const [isLoading, setIsLoading] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [analysisResult, setAnalysisResult] = useState<ForecastAnalysisResult | null>(null);
- const [dataInput, setDataInput] = useState(JSON.stringify(SAMPLE_DATA, null, 2));
-
- // Data source configuration
- const [dataSourceType, setDataSourceType] = useState<DataSourceType>('manual');
- const [portfolios, setPortfolios] = useState<Portfolio[]>([]);
- const [selectedPortfolioId, setSelectedPortfolioId] = useState<string>('');
- const [symbolInput, setSymbolInput] = useState('AAPL');
- const [historicalDays, setHistoricalDays] = useState(365);
- const [priceDataLoading, setPriceDataLoading] = useState(false);
- const [priceData, setPriceData] = useState<PortfolioPriceData | null>(null);
-
- // Analysis mode
- const [analysisMode, setAnalysisMode] = useState<AnalysisMode>('forecast');
-
- // Forecast configuration
- const [selectedModel, setSelectedModel] = useState('linear');
- const [horizon, setHorizon] = useState(7);
- const [frequency, setFrequency] = useState('1d');
- const [alpha, setAlpha] = useState(1.0);
- const [testSize, setTestSize] = useState(5);
- const [preprocess, setPreprocess] = useState<'none' | 'scale' | 'difference'>('none');
-
- const [expandedSections, setExpandedSections] = useState({
- config: true,
- forecast: true,
- metrics: true,
- summary: true,
- chart: true,
- dataSource: true,
- anomaly: true,
- seasonality: true,
- backtest: true
- });
-
- // Anomaly detection state
- const [anomalyMethod, setAnomalyMethod] = useState<'zscore' | 'iqr' | 'isolation_forest'>('zscore');
- const [anomalyThreshold, setAnomalyThreshold] = useState(3.0);
- const [anomalyResult, setAnomalyResult] = useState<PortfolioAnomalyResult | null>(null);
-
- // Seasonality state
- const [seasonalityResult, setSeasonalityResult] = useState<PortfolioSeasonalityResult | null>(null);
-
- // Expandable table state
- const [forecastTableExpanded, setForecastTableExpanded] = useState(false);
- const INITIAL_ROWS = 10;
- const EXPANDED_ROWS = 50;
-
- // Advanced models
- const advancedModels = functimeService.getAdvancedModels();
- const anomalyMethods = functimeService.getAnomalyMethods();
-
- const models = functimeService.getAvailableModels();
- const frequencies = functimeService.getAvailableFrequencies();
-
- // Check functime availability on mount
- useEffect(() => {
- checkFunctimeStatus();
- loadPortfolios();
- }, []);
-
- const loadPortfolios = async () => {
- try {
- const portfolioList = await portfolioFunctimeService.getAvailablePortfolios();
- setPortfolios(portfolioList);
- if (portfolioList.length > 0 && !selectedPortfolioId) {
- setSelectedPortfolioId(portfolioList[0].id);
- }
- } catch (err) {
- console.error('Failed to load portfolios:', err);
- }
- };
-
- const checkFunctimeStatus = async () => {
- try {
- const status = await functimeService.checkStatus();
- setIsFunctimeAvailable(status.available);
- if (!status.available) {
- setError('Functime library not installed. Run: pip install functime polars');
- }
- } catch (err) {
- setIsFunctimeAvailable(false);
- setError('Failed to check functime status');
- }
- };
-
- // Load data based on source type
- const loadDataFromSource = useCallback(async () => {
- if (dataSourceType === 'manual') {
- return; // Data already in dataInput
- }
-
- setPriceDataLoading(true);
- setError(null);
-
- try {
- if (dataSourceType === 'portfolio' && selectedPortfolioId) {
- const summary = await portfolioFunctimeService.getPortfolioSummary(selectedPortfolioId);
- if (!summary || summary.holdings.length === 0) {
- setError('Portfolio has no holdings');
- return;
- }
-
- const data = await portfolioFunctimeService.fetchHistoricalPrices(
- summary.holdings,
- historicalDays
- );
-
- if (data) {
- setPriceData(data);
- setDataInput(JSON.stringify(data.panelData, null, 2));
- } else {
- setError('Failed to fetch historical data for portfolio');
- }
- } else if (dataSourceType === 'symbol' && symbolInput) {
- const data = await portfolioFunctimeService.fetchSymbolData(symbolInput, historicalDays);
- if (data) {
- setDataInput(JSON.stringify(data, null, 2));
- setPriceData({
- panelData: data,
- assets: [symbolInput],
- nDataPoints: data.length,
- startDate: data[0]?.time || '',
- endDate: data[data.length - 1]?.time || ''
- });
- } else {
- setError(`Failed to fetch data for ${symbolInput}`);
- }
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Failed to load data');
- } finally {
- setPriceDataLoading(false);
- }
- }, [dataSourceType, selectedPortfolioId, symbolInput, historicalDays]);
-
- // Run analysis based on mode
- const runAnalysis = async () => {
- setIsLoading(true);
- setError(null);
-
- try {
- const data = JSON.parse(dataInput);
-
- if (analysisMode === 'forecast') {
- await runForecast();
- } else if (analysisMode === 'anomaly') {
- await runAnomalyDetection(data);
- } else if (analysisMode === 'seasonality') {
- await runSeasonalityAnalysis(data);
- } else if (analysisMode === 'backtest') {
- // For backtest, we use the forecast function with more settings
- await runForecast();
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Analysis failed');
- } finally {
- setIsLoading(false);
- }
- };
-
- // Anomaly detection
- const runAnomalyDetection = async (data: any[]) => {
- const config: AnomalyDetectionConfig = {
- method: anomalyMethod,
- threshold: anomalyThreshold
- };
-
- const result = await functimeService.detectAnomalies(data, config);
-
- if (!result.success) {
- setError(result.error || 'Anomaly detection failed');
- return;
- }
-
- // Format result for portfolio view
- const anomalies: Record<string, any> = {};
- if (result.results) {
- Object.entries(result.results).forEach(([symbol, data]) => {
- const anomalyList = data.anomalies?.filter((a: any) => a.is_anomaly) || [];
- anomalies[symbol] = {
- count: data.n_anomalies,
- rate: data.anomaly_rate,
- dates: anomalyList.map((a: any) => a.time),
- values: anomalyList.map((a: any) => a.value)
- };
- });
- }
-
- setAnomalyResult({
- success: true,
- portfolio: portfolios.find(p => p.id === selectedPortfolioId) || {} as Portfolio,
- anomalies
- });
- };
-
- // Seasonality analysis
- const runSeasonalityAnalysis = async (data: any[]) => {
- const config: SeasonalityConfig = {
- operation: 'metrics'
- };
-
- const result = await functimeService.analyzeSeasonality(data, config);
-
- if (!result.success) {
- setError(result.error || 'Seasonality analysis failed');
- return;
- }
-
- // Format result
- const seasonality: Record<string, any> = {};
- if (result.metrics) {
- Object.entries(result.metrics).forEach(([symbol, metrics]) => {
- seasonality[symbol] = {
- period: metrics.detected_period || 0,
- strength: metrics.seasonal_strength,
- is_seasonal: metrics.is_seasonal,
- trend_strength: metrics.trend_strength
- };
- });
- }
-
- setSeasonalityResult({
- success: true,
- portfolio: portfolios.find(p => p.id === selectedPortfolioId) || {} as Portfolio,
- seasonality
- });
- };
-
- const runForecast = async () => {
- setIsLoading(true);
- setError(null);
-
- try {
- const data = JSON.parse(dataInput);
-
- // Run full pipeline
- const result = await functimeService.fullPipeline(
- data,
- selectedModel,
- horizon,
- frequency,
- testSize,
- preprocess === 'none' ? undefined : preprocess
- );
-
- if (!result.success) {
- setError(result.error || 'Forecast failed');
- return;
- }
-
- setAnalysisResult({
- forecast: result.forecast,
- model: result.model,
- horizon: result.horizon,
- frequency: result.frequency,
- best_params: result.best_params,
- evaluation_metrics: result.evaluation_metrics,
- data_summary: result.data_summary
- });
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Forecast failed');
- } finally {
- setIsLoading(false);
- }
- };
-
- const toggleSection = (section: keyof typeof expandedSections) => {
- setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
- };
-
- const formatMetric = (value: number | null | undefined, decimals = 4): string => {
- if (value === null || value === undefined || isNaN(value)) return 'N/A';
- return value.toFixed(decimals);
- };
-
- // Parse historical data from input for chart visualization
- const historicalData = useMemo(() => {
- try {
- const data = JSON.parse(dataInput);
- if (Array.isArray(data)) {
- return data.map(d => ({
- time: d.time,
- value: d.value
- }));
- }
- return [];
- } catch {
- return [];
- }
- }, [dataInput]);
-
- // Loading state
- if (isFunctimeAvailable === null) {
- return (
- <div className="flex items-center justify-center h-full" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <RefreshCw size={32} color={FINCEPT.ORANGE} className="animate-spin" />
- </div>
- );
- }
-
- // Not available state
- if (!isFunctimeAvailable) {
- return (
- <div className="flex items-center justify-center h-full p-8" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <div className="text-center max-w-md">
- <AlertCircle size={48} color={FINCEPT.RED} className="mx-auto mb-4" />
- <h3 className="text-lg font-bold uppercase mb-2" style={{ color: FINCEPT.WHITE }}>
- Functime Library Not Installed
- </h3>
- <p className="text-sm mb-4" style={{ color: FINCEPT.GRAY }}>
- Install functime and polars for ML time series forecasting
- </p>
- <code
- className="block p-4 rounded text-sm font-mono mt-4"
- style={{ backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.ORANGE }}
- >
- pip install functime polars
- </code>
- <button
- onClick={checkFunctimeStatus}
- className="mt-6 px-6 py-2 rounded font-bold text-sm uppercase flex items-center gap-2 mx-auto"
- style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
- >
- <RefreshCw size={14} />
- Check Again
- </button>
- </div>
- </div>
- );
- }
-
- return (
- <div className="flex h-full" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- {/* Left Panel - Configuration */}
- <div
- className="w-96 flex flex-col border-r"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
- >
- {/* Input Header */}
- <div
- className="px-4 py-3 border-b flex items-center gap-2"
- style={{ backgroundColor: FINCEPT.HEADER_BG, borderColor: FINCEPT.BORDER }}
- >
- <Zap size={16} color={FINCEPT.ORANGE} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- Time Series Forecasting
- </span>
- </div>
-
- {/* Scrollable Content */}
- <div className="flex-1 overflow-auto p-4 space-y-4">
- {/* Data Source Selection */}
- <div
- className="rounded overflow-hidden"
- style={{ border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <button
- onClick={() => toggleSection('dataSource')}
- className="w-full px-3 py-2 flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <div className="flex items-center gap-2">
- <Database size={14} color={FINCEPT.CYAN} />
- <span className="text-xs font-bold uppercase" style={{ color: FINCEPT.WHITE }}>
- Data Source
- </span>
- </div>
- {expandedSections.dataSource ? (
- <ChevronUp size={14} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={14} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.dataSource && (
- <div className="p-3 space-y-3">
- {/* Source Type Selection */}
- <div className="flex gap-2">
- <button
- onClick={() => setDataSourceType('manual')}
- className={`flex-1 px-2 py-1.5 rounded text-xs font-mono ${dataSourceType === 'manual' ? 'border-2' : ''}`}
- style={{
- backgroundColor: dataSourceType === 'manual' ? FINCEPT.HEADER_BG : FINCEPT.DARK_BG,
- borderColor: FINCEPT.ORANGE,
- color: dataSourceType === 'manual' ? FINCEPT.ORANGE : FINCEPT.GRAY
- }}
- >
- Manual
- </button>
- <button
- onClick={() => setDataSourceType('portfolio')}
- className={`flex-1 px-2 py-1.5 rounded text-xs font-mono ${dataSourceType === 'portfolio' ? 'border-2' : ''}`}
- style={{
- backgroundColor: dataSourceType === 'portfolio' ? FINCEPT.HEADER_BG : FINCEPT.DARK_BG,
- borderColor: FINCEPT.ORANGE,
- color: dataSourceType === 'portfolio' ? FINCEPT.ORANGE : FINCEPT.GRAY
- }}
- >
- <Briefcase size={12} className="inline mr-1" />
- Portfolio
- </button>
- <button
- onClick={() => setDataSourceType('symbol')}
- className={`flex-1 px-2 py-1.5 rounded text-xs font-mono ${dataSourceType === 'symbol' ? 'border-2' : ''}`}
- style={{
- backgroundColor: dataSourceType === 'symbol' ? FINCEPT.HEADER_BG : FINCEPT.DARK_BG,
- borderColor: FINCEPT.ORANGE,
- color: dataSourceType === 'symbol' ? FINCEPT.ORANGE : FINCEPT.GRAY
- }}
- >
- <Search size={12} className="inline mr-1" />
- Symbol
- </button>
- </div>
-
- {/* Portfolio Selection */}
- {dataSourceType === 'portfolio' && (
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- SELECT PORTFOLIO
- </label>
- <select
- value={selectedPortfolioId}
- onChange={(e) => setSelectedPortfolioId(e.target.value)}
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- {portfolios.length === 0 ? (
- <option value="">No portfolios found</option>
- ) : (
- portfolios.map((p) => (
- <option key={p.id} value={p.id}>
- {p.name}
- </option>
- ))
- )}
- </select>
- </div>
- )}
-
- {/* Symbol Input */}
- {dataSourceType === 'symbol' && (
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- TICKER SYMBOL
- </label>
- <input
- type="text"
- value={symbolInput}
- onChange={(e) => setSymbolInput(e.target.value.toUpperCase())}
- placeholder="AAPL"
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- />
- </div>
- )}
-
- {/* Historical Days */}
- {dataSourceType !== 'manual' && (
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- HISTORICAL DAYS
- </label>
- <input
- type="number"
- min={30}
- max={1825}
- value={historicalDays}
- onChange={(e) => setHistoricalDays(parseInt(e.target.value) || 365)}
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- />
- </div>
- )}
-
- {/* Load Data Button */}
- {dataSourceType !== 'manual' && (
- <button
- onClick={loadDataFromSource}
- disabled={priceDataLoading}
- className="w-full py-2 rounded font-bold text-xs uppercase flex items-center justify-center gap-2"
- style={{ backgroundColor: FINCEPT.CYAN, color: FINCEPT.DARK_BG }}
- >
- {priceDataLoading ? (
- <>
- <RefreshCw size={12} className="animate-spin" />
- Loading...
- </>
- ) : (
- <>
- <Database size={12} />
- Fetch Data
- </>
- )}
- </button>
- )}
-
- {/* Data Info */}
- {priceData && dataSourceType !== 'manual' && (
- <div className="p-2 rounded text-xs font-mono" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <div className="flex justify-between" style={{ color: FINCEPT.GRAY }}>
- <span>Assets:</span>
- <span style={{ color: FINCEPT.CYAN }}>{priceData.assets.length}</span>
- </div>
- <div className="flex justify-between" style={{ color: FINCEPT.GRAY }}>
- <span>Data Points:</span>
- <span style={{ color: FINCEPT.WHITE }}>{priceData.nDataPoints}</span>
- </div>
- <div className="flex justify-between" style={{ color: FINCEPT.GRAY }}>
- <span>Range:</span>
- <span style={{ color: FINCEPT.WHITE }}>{priceData.startDate} to {priceData.endDate}</span>
- </div>
- </div>
- )}
- </div>
- )}
- </div>
-
- {/* Analysis Mode Tabs */}
- <div className="flex gap-1 p-1 rounded" style={{ backgroundColor: FINCEPT.HEADER_BG }}>
- <button
- onClick={() => setAnalysisMode('forecast')}
- className={`flex-1 px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1`}
- style={{
- backgroundColor: analysisMode === 'forecast' ? FINCEPT.ORANGE : 'transparent',
- color: analysisMode === 'forecast' ? FINCEPT.DARK_BG : FINCEPT.GRAY
- }}
- >
- <TrendingUp size={12} />
- Forecast
- </button>
- <button
- onClick={() => setAnalysisMode('anomaly')}
- className={`flex-1 px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1`}
- style={{
- backgroundColor: analysisMode === 'anomaly' ? FINCEPT.ORANGE : 'transparent',
- color: analysisMode === 'anomaly' ? FINCEPT.DARK_BG : FINCEPT.GRAY
- }}
- >
- <AlertTriangle size={12} />
- Anomaly
- </button>
- <button
- onClick={() => setAnalysisMode('seasonality')}
- className={`flex-1 px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1`}
- style={{
- backgroundColor: analysisMode === 'seasonality' ? FINCEPT.ORANGE : 'transparent',
- color: analysisMode === 'seasonality' ? FINCEPT.DARK_BG : FINCEPT.GRAY
- }}
- >
- <Waves size={12} />
- Season
- </button>
- </div>
-
- {/* Data Input - Only for Manual */}
- {dataSourceType === 'manual' && (
- <div>
- <label className="block text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
- PANEL DATA (JSON)
- </label>
- <textarea
- value={dataInput}
- onChange={(e) => setDataInput(e.target.value)}
- className="w-full h-32 p-3 rounded text-xs font-mono resize-none"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- placeholder='[{"entity_id": "A", "time": "2024-01-01", "value": 100}, ...]'
- />
- </div>
- )}
-
- {/* Model Configuration - Shown for forecast mode */}
- {analysisMode === 'forecast' && (
- <div
- className="rounded overflow-hidden"
- style={{ border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <button
- onClick={() => toggleSection('config')}
- className="w-full px-3 py-2 flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <div className="flex items-center gap-2">
- <Settings size={14} color={FINCEPT.CYAN} />
- <span className="text-xs font-bold uppercase" style={{ color: FINCEPT.WHITE }}>
- Model Configuration
- </span>
- </div>
- {expandedSections.config ? (
- <ChevronUp size={14} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={14} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.config && (
- <div className="p-3 space-y-3">
- {/* Model Selection */}
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- FORECAST MODEL
- </label>
- <select
- value={selectedModel}
- onChange={(e) => setSelectedModel(e.target.value)}
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- {models.map((m) => (
- <option key={m.id} value={m.id}>
- {m.name}
- </option>
- ))}
- </select>
- </div>
-
- {/* Horizon */}
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- FORECAST HORIZON
- </label>
- <input
- type="number"
- min={1}
- max={365}
- value={horizon}
- onChange={(e) => setHorizon(parseInt(e.target.value) || 7)}
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- />
- </div>
-
- {/* Frequency */}
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- DATA FREQUENCY
- </label>
- <select
- value={frequency}
- onChange={(e) => setFrequency(e.target.value)}
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- {frequencies.map((f) => (
- <option key={f.id} value={f.id}>
- {f.name}
- </option>
- ))}
- </select>
- </div>
-
- {/* Alpha (for regularized models) */}
- {['lasso', 'ridge', 'elasticnet', 'auto_lasso', 'auto_ridge', 'auto_elasticnet'].includes(selectedModel) && (
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- ALPHA (REGULARIZATION)
- </label>
- <input
- type="number"
- step="0.1"
- min={0}
- value={alpha}
- onChange={(e) => setAlpha(parseFloat(e.target.value) || 1.0)}
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- />
- </div>
- )}
-
- {/* Test Size */}
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- TEST SIZE (FOR EVALUATION)
- </label>
- <input
- type="number"
- min={1}
- value={testSize}
- onChange={(e) => setTestSize(parseInt(e.target.value) || 5)}
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- />
- </div>
-
- {/* Preprocessing */}
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- PREPROCESSING
- </label>
- <select
- value={preprocess}
- onChange={(e) => setPreprocess(e.target.value as 'none' | 'scale' | 'difference')}
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- <option value="none">None</option>
- <option value="scale">Standard Scaling</option>
- <option value="difference">Differencing</option>
- </select>
- </div>
- </div>
- )}
- </div>
- )}
-
- {/* Anomaly Detection Configuration */}
- {analysisMode === 'anomaly' && (
- <div
- className="rounded overflow-hidden"
- style={{ border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <div
- className="px-3 py-2 flex items-center gap-2"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <AlertTriangle size={14} color={FINCEPT.YELLOW} />
- <span className="text-xs font-bold uppercase" style={{ color: FINCEPT.WHITE }}>
- Anomaly Detection Settings
- </span>
- </div>
- <div className="p-3 space-y-3">
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- DETECTION METHOD
- </label>
- <select
- value={anomalyMethod}
- onChange={(e) => setAnomalyMethod(e.target.value as 'zscore' | 'iqr' | 'isolation_forest')}
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- >
- <option value="zscore">Z-Score</option>
- <option value="iqr">IQR (Interquartile Range)</option>
- <option value="isolation_forest">Isolation Forest</option>
- </select>
- </div>
- <div>
- <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
- THRESHOLD
- </label>
- <input
- type="number"
- step="0.5"
- min={1}
- max={5}
- value={anomalyThreshold}
- onChange={(e) => setAnomalyThreshold(parseFloat(e.target.value) || 3.0)}
- className="w-full p-2 rounded text-xs font-mono"
- style={{
- backgroundColor: FINCEPT.DARK_BG,
- color: FINCEPT.WHITE,
- border: `1px solid ${FINCEPT.BORDER}`
- }}
- />
- </div>
- </div>
- </div>
- )}
-
- {/* Seasonality Analysis Configuration */}
- {analysisMode === 'seasonality' && (
- <div
- className="rounded overflow-hidden"
- style={{ border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <div
- className="px-3 py-2 flex items-center gap-2"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <Waves size={14} color={FINCEPT.CYAN} />
- <span className="text-xs font-bold uppercase" style={{ color: FINCEPT.WHITE }}>
- Seasonality Analysis
- </span>
- </div>
- <div className="p-3">
- <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- Analyzes time series for seasonal patterns, trend strength, and periodicity.
- Uses FFT and ACF for automatic period detection.
- </p>
- </div>
- </div>
- )}
- </div>
-
- {/* Run Button */}
- <div className="p-4 border-t" style={{ borderColor: FINCEPT.BORDER }}>
- <button
- onClick={runAnalysis}
- disabled={isLoading}
- className="w-full py-3 rounded font-bold text-sm uppercase flex items-center justify-center gap-2 disabled:opacity-50"
- style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
- >
- {isLoading ? (
- <>
- <RefreshCw size={16} className="animate-spin" />
- {analysisMode === 'forecast' ? 'FORECASTING...' :
- analysisMode === 'anomaly' ? 'DETECTING...' : 'ANALYZING...'}
- </>
- ) : (
- <>
- <Play size={16} />
- {analysisMode === 'forecast' ? 'RUN FORECAST' :
- analysisMode === 'anomaly' ? 'DETECT ANOMALIES' : 'ANALYZE SEASONALITY'}
- </>
- )}
- </button>
- </div>
- </div>
-
- {/* Right Panel - Results */}
- <div className="flex-1 overflow-auto p-4">
- {error && (
- <div
- className="mb-4 p-4 rounded flex items-center gap-3"
- style={{ backgroundColor: FINCEPT.PANEL_BG, borderLeft: `3px solid ${FINCEPT.RED}` }}
- >
- <AlertCircle size={20} color={FINCEPT.RED} />
- <span className="text-sm font-mono" style={{ color: FINCEPT.RED }}>{error}</span>
- </div>
- )}
-
- {!analysisResult && !anomalyResult && !seasonalityResult && !error && (
- <div className="flex items-center justify-center h-full">
- <div className="text-center">
- <LineChart size={64} color={FINCEPT.MUTED} className="mx-auto mb-4" />
- <p className="text-sm font-mono" style={{ color: FINCEPT.GRAY }}>
- {analysisMode === 'forecast'
- ? 'Configure model and click "Run Forecast" to see predictions'
- : analysisMode === 'anomaly'
- ? 'Click "Detect Anomalies" to find outliers in your data'
- : 'Click "Analyze Seasonality" to discover patterns'}
- </p>
- </div>
- </div>
- )}
-
- {/* Anomaly Detection Results */}
- {anomalyResult && anomalyResult.success && anomalyResult.anomalies && (
- <div className="space-y-4">
- <div
- className="rounded overflow-hidden"
- style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <div
- className="px-4 py-3 flex items-center gap-2"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <AlertTriangle size={16} color={FINCEPT.YELLOW} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- Anomaly Detection Results
- </span>
- </div>
- <div className="p-4">
- <div className="grid grid-cols-2 gap-4">
- {Object.entries(anomalyResult.anomalies).map(([symbol, data]) => (
- <div
- key={symbol}
- className="p-3 rounded"
- style={{ backgroundColor: FINCEPT.DARK_BG }}
- >
- <div className="flex justify-between items-center mb-2">
- <span className="text-sm font-bold" style={{ color: FINCEPT.CYAN }}>
- {symbol}
- </span>
- <span
- className="text-xs px-2 py-0.5 rounded"
- style={{
- backgroundColor: data.count > 0 ? FINCEPT.RED : FINCEPT.GREEN,
- color: FINCEPT.WHITE
- }}
- >
- {data.count} anomalies
- </span>
- </div>
- <div className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- <div>Rate: {(data.rate * 100).toFixed(2)}%</div>
- {data.dates?.length > 0 && (
- <div className="mt-1">
- Latest: {data.dates[data.dates.length - 1]}
- </div>
- )}
- </div>
- </div>
- ))}
- </div>
- </div>
- </div>
- </div>
- )}
-
- {/* Seasonality Results */}
- {seasonalityResult && seasonalityResult.success && seasonalityResult.seasonality && (
- <div className="space-y-4">
- <div
- className="rounded overflow-hidden"
- style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <div
- className="px-4 py-3 flex items-center gap-2"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <Waves size={16} color={FINCEPT.CYAN} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- Seasonality Analysis Results
- </span>
- </div>
- <div className="p-4">
- <div className="grid grid-cols-2 gap-4">
- {Object.entries(seasonalityResult.seasonality).map(([symbol, data]) => (
- <div
- key={symbol}
- className="p-3 rounded"
- style={{ backgroundColor: FINCEPT.DARK_BG }}
- >
- <div className="flex justify-between items-center mb-2">
- <span className="text-sm font-bold" style={{ color: FINCEPT.CYAN }}>
- {symbol}
- </span>
- <span
- className="text-xs px-2 py-0.5 rounded"
- style={{
- backgroundColor: data.is_seasonal ? FINCEPT.GREEN : FINCEPT.MUTED,
- color: FINCEPT.WHITE
- }}
- >
- {data.is_seasonal ? 'Seasonal' : 'Non-Seasonal'}
- </span>
- </div>
- <div className="text-xs font-mono space-y-1" style={{ color: FINCEPT.GRAY }}>
- <div className="flex justify-between">
- <span>Period:</span>
- <span style={{ color: FINCEPT.WHITE }}>{data.period} days</span>
- </div>
- <div className="flex justify-between">
- <span>Seasonal Strength:</span>
- <span style={{ color: FINCEPT.ORANGE }}>{(data.strength * 100).toFixed(1)}%</span>
- </div>
- {data.trend_strength !== undefined && (
- <div className="flex justify-between">
- <span>Trend Strength:</span>
- <span style={{ color: FINCEPT.GREEN }}>{(data.trend_strength * 100).toFixed(1)}%</span>
- </div>
- )}
- </div>
- </div>
- ))}
- </div>
- </div>
- </div>
- </div>
- )}
-
- {analysisResult && (
- <div className="space-y-4">
- {/* Data Summary Section */}
- {analysisResult.data_summary && (
- <div
- className="rounded overflow-hidden"
- style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <button
- onClick={() => toggleSection('summary')}
- className="w-full px-4 py-3 flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <div className="flex items-center gap-2">
- <Database size={16} color={FINCEPT.CYAN} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- Data Summary
- </span>
- </div>
- {expandedSections.summary ? (
- <ChevronUp size={16} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={16} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.summary && (
- <div className="p-4 grid grid-cols-4 gap-4">
- <MetricCard
- label="Total Rows"
- value={String(analysisResult.data_summary.total_rows)}
- color={FINCEPT.WHITE}
- icon={<Database size={14} />}
- />
- <MetricCard
- label="Entities"
- value={String(analysisResult.data_summary.entities)}
- color={FINCEPT.CYAN}
- icon={<Layers size={14} />}
- />
- <MetricCard
- label="Train Size"
- value={String(analysisResult.data_summary.train_size)}
- color={FINCEPT.GREEN}
- icon={<GitBranch size={14} />}
- />
- <MetricCard
- label="Test Size"
- value={String(analysisResult.data_summary.test_size)}
- color={FINCEPT.YELLOW}
- icon={<Target size={14} />}
- />
- </div>
- )}
- </div>
- )}
-
- {/* Evaluation Metrics Section */}
- {analysisResult.evaluation_metrics && (
- <div
- className="rounded overflow-hidden"
- style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <button
- onClick={() => toggleSection('metrics')}
- className="w-full px-4 py-3 flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <div className="flex items-center gap-2">
- <Target size={16} color={FINCEPT.GREEN} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- Evaluation Metrics
- </span>
- </div>
- {expandedSections.metrics ? (
- <ChevronUp size={16} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={16} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.metrics && (
- <div className="p-4 grid grid-cols-3 gap-4">
- <MetricCard
- label="MAE"
- value={formatMetric(analysisResult.evaluation_metrics.mae)}
- color={FINCEPT.CYAN}
- icon={<BarChart2 size={14} />}
- />
- <MetricCard
- label="RMSE"
- value={formatMetric(analysisResult.evaluation_metrics.rmse)}
- color={FINCEPT.YELLOW}
- icon={<Activity size={14} />}
- />
- <MetricCard
- label="SMAPE"
- value={formatMetric(analysisResult.evaluation_metrics.smape)}
- color={FINCEPT.PURPLE}
- icon={<TrendingUp size={14} />}
- />
- </div>
- )}
- </div>
- )}
-
- {/* Forecast Chart Visualization */}
- {analysisResult.forecast && analysisResult.forecast.length > 0 && (
- <div
- className="rounded overflow-hidden"
- style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <button
- onClick={() => toggleSection('chart')}
- className="w-full px-4 py-3 flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <div className="flex items-center gap-2">
- <LineChart size={16} color={FINCEPT.CYAN} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- Forecast Chart
- </span>
- </div>
- {expandedSections.chart ? (
- <ChevronUp size={16} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={16} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.chart && (
- <div className="p-4">
- <ForecastChart
- historicalData={historicalData}
- forecastData={analysisResult.forecast}
- height={350}
- />
- </div>
- )}
- </div>
- )}
-
- {/* Forecast Results Section */}
- <div
- className="rounded overflow-hidden"
- style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <button
- onClick={() => toggleSection('forecast')}
- className="w-full px-4 py-3 flex items-center justify-between"
- style={{ backgroundColor: FINCEPT.HEADER_BG }}
- >
- <div className="flex items-center gap-2">
- <TrendingUp size={16} color={FINCEPT.ORANGE} />
- <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
- Forecast Results
- </span>
- {analysisResult.model && (
- <span
- className="ml-2 px-2 py-0.5 rounded text-xs font-mono"
- style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
- >
- {analysisResult.model.toUpperCase()}
- </span>
- )}
- </div>
- {expandedSections.forecast ? (
- <ChevronUp size={16} color={FINCEPT.GRAY} />
- ) : (
- <ChevronDown size={16} color={FINCEPT.GRAY} />
- )}
- </button>
-
- {expandedSections.forecast && analysisResult.forecast && (
- <div className="p-4">
- {/* Forecast info */}
- <div className="mb-4 flex gap-4 text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- <span>Horizon: <span style={{ color: FINCEPT.WHITE }}>{analysisResult.horizon}</span></span>
- <span>Frequency: <span style={{ color: FINCEPT.WHITE }}>{analysisResult.frequency}</span></span>
- {analysisResult.best_params && (
- <span>Auto-tuned: <CheckCircle2 size={12} color={FINCEPT.GREEN} className="inline ml-1" /></span>
- )}
- </div>
-
- {/* Forecast table */}
- <div
- className="rounded overflow-hidden"
- style={{ border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <table className="w-full text-xs font-mono">
- <thead>
- <tr style={{ backgroundColor: FINCEPT.HEADER_BG }}>
- <th className="px-3 py-2 text-left" style={{ color: FINCEPT.GRAY }}>ENTITY</th>
- <th className="px-3 py-2 text-left" style={{ color: FINCEPT.GRAY }}>TIME</th>
- <th className="px-3 py-2 text-right" style={{ color: FINCEPT.GRAY }}>FORECAST</th>
- </tr>
- </thead>
- <tbody>
- {analysisResult.forecast.slice(0, forecastTableExpanded ? EXPANDED_ROWS : INITIAL_ROWS).map((row, idx) => (
- <tr
- key={idx}
- style={{
- backgroundColor: idx % 2 === 0 ? FINCEPT.DARK_BG : FINCEPT.PANEL_BG
- }}
- >
- <td className="px-3 py-2" style={{ color: FINCEPT.CYAN }}>
- {row.entity_id}
- </td>
- <td className="px-3 py-2" style={{ color: FINCEPT.WHITE }}>
- {row.time}
- </td>
- <td className="px-3 py-2 text-right" style={{ color: FINCEPT.GREEN }}>
- {typeof row.value === 'number' ? row.value.toFixed(2) : row.value}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- {analysisResult.forecast.length > INITIAL_ROWS && (
- <button
- onClick={() => setForecastTableExpanded(!forecastTableExpanded)}
- className="w-full px-3 py-2 text-xs font-mono text-center flex items-center justify-center gap-2 hover:opacity-80 transition-opacity"
- style={{ backgroundColor: FINCEPT.HEADER_BG, color: FINCEPT.ORANGE }}
- >
- {forecastTableExpanded ? (
- <>
- <ChevronUp size={12} />
- Show Less ({INITIAL_ROWS} rows)
- </>
- ) : (
- <>
- <ChevronDown size={12} />
- Show More ({Math.min(analysisResult.forecast.length, EXPANDED_ROWS)} of {analysisResult.forecast.length} rows)
- </>
- )}
- </button>
- )}
- </div>
- </div>
- )}
- </div>
-
- {/* Best Params (if auto-tuned) */}
- {analysisResult.best_params && Object.keys(analysisResult.best_params).length > 0 && (
- <div
- className="rounded p-4"
- style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- <div className="flex items-center gap-2 mb-3">
- <Zap size={16} color={FINCEPT.YELLOW} />
- <span className="text-xs font-bold uppercase" style={{ color: FINCEPT.WHITE }}>
- Best Parameters (Auto-tuned)
- </span>
- </div>
- <div className="grid grid-cols-3 gap-2">
- {Object.entries(analysisResult.best_params).map(([key, value]) => (
- <div key={key} className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
- <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>{key}</span>
- <span className="text-xs font-mono" style={{ color: FINCEPT.CYAN }}>
- {typeof value === 'number' ? value.toFixed(4) : String(value)}
- </span>
- </div>
- ))}
- </div>
- </div>
- )}
- </div>
- )}
- </div>
- </div>
- );
-}
-
-// Metric Card Component
-function MetricCard({
- label,
- value,
- color,
- icon,
- large = false
-}: {
- label: string;
- value: string;
- color: string;
- icon: React.ReactNode;
- large?: boolean;
-}) {
- return (
- <div
- className={`p-3 rounded ${large ? 'col-span-3' : ''}`}
- style={{ backgroundColor: FINCEPT.DARK_BG }}
- >
- <div className="flex items-center gap-2 mb-1">
- <span style={{ color: FINCEPT.GRAY }}>{icon}</span>
- <span className="text-xs font-mono uppercase" style={{ color: FINCEPT.GRAY }}>
- {label}
- </span>
- </div>
- <span
- className={`font-bold font-mono ${large ? 'text-2xl' : 'text-lg'}`}
- style={{ color }}
- >
- {value}
- </span>
- </div>
- );
-}
-
-// Forecast Chart Component - Interactive SVG-based line chart with tooltips
-interface ChartDataPoint {
- time: string;
- value: number;
- type: 'historical' | 'forecast';
- entity_id?: string;
-}
-
-interface TooltipState {
- visible: boolean;
- x: number;
- y: number;
- data: ChartDataPoint | null;
-}
-
-function ForecastChart({
- historicalData,
- forecastData,
- height = 300
-}: {
- historicalData: { time: string; value: number }[];
- forecastData: ForecastResult[];
- height?: number;
-}) {
- const [tooltip, setTooltip] = useState<TooltipState>({ visible: false, x: 0, y: 0, data: null });
- const [zoomLevel, setZoomLevel] = useState(1);
- const [panOffset, setPanOffset] = useState(0);
- const svgRef = React.useRef<SVGSVGElement>(null);
-
- const chartData = useMemo(() => {
- const historical: ChartDataPoint[] = historicalData.map(d => ({
- time: d.time,
- value: d.value,
- type: 'historical' as const
- }));
-
- const forecast: ChartDataPoint[] = forecastData.map(d => ({
- time: d.time,
- value: d.value,
- type: 'forecast' as const,
- entity_id: d.entity_id
- }));
-
- return [...historical, ...forecast];
- }, [historicalData, forecastData]);
-
- if (chartData.length === 0) {
- return (
- <div
- className="flex items-center justify-center"
- style={{ height, backgroundColor: FINCEPT.DARK_BG }}
- >
- <span className="text-sm font-mono" style={{ color: FINCEPT.GRAY }}>
- No data to display
- </span>
- </div>
- );
- }
-
- const baseWidth = 800;
- const width = baseWidth * zoomLevel;
- const padding = { top: 20, right: 60, bottom: 40, left: 60 };
- const chartWidth = width - padding.left - padding.right;
- const chartHeight = height - padding.top - padding.bottom;
-
- // Calculate scales
- const values = chartData.map(d => d.value);
- const minValue = Math.min(...values);
- const maxValue = Math.max(...values);
- const valueRange = maxValue - minValue || 1;
- const yMin = minValue - valueRange * 0.1;
- const yMax = maxValue + valueRange * 0.1;
-
- const xScale = (index: number) => padding.left + (index / (chartData.length - 1 || 1)) * chartWidth;
- const yScale = (value: number) => padding.top + chartHeight - ((value - yMin) / (yMax - yMin)) * chartHeight;
-
- // Find split point between historical and forecast
- const historicalEndIndex = historicalData.length - 1;
-
- // Generate path for historical data
- const historicalPath = historicalData
- .map((d, i) => {
- const x = xScale(i);
- const y = yScale(d.value);
- return `${i === 0 ? 'M' : 'L'} ${x} ${y}`;
- })
- .join(' ');
-
- // Generate path for forecast data (starts from last historical point)
- const forecastPath = forecastData.length > 0
- ? [
- historicalData.length > 0
- ? `M ${xScale(historicalEndIndex)} ${yScale(historicalData[historicalEndIndex]?.value ?? forecastData[0].value)}`
- : `M ${xScale(0)} ${yScale(forecastData[0].value)}`,
- ...forecastData.map((d, i) => {
- const x = xScale(historicalData.length + i);
- const y = yScale(d.value);
- return `L ${x} ${y}`;
- })
- ].join(' ')
- : '';
-
- // Y-axis ticks
- const yTicks = Array.from({ length: 5 }, (_, i) => {
- const value = yMin + (yMax - yMin) * (i / 4);
- return { value, y: yScale(value) };
- });
-
- // X-axis labels (show first, middle, last, and split point)
- const xLabels = [
- { index: 0, label: chartData[0]?.time.split('T')[0] || '' },
- { index: historicalEndIndex, label: chartData[historicalEndIndex]?.time.split('T')[0] || '' },
- { index: chartData.length - 1, label: chartData[chartData.length - 1]?.time.split('T')[0] || '' }
- ].filter((item, index, arr) =>
- arr.findIndex(t => t.index === item.index) === index && item.label
- );
-
- // Handle mouse events for interactive tooltips
- const handleMouseEnter = (data: ChartDataPoint, x: number, y: number) => {
- setTooltip({ visible: true, x, y, data });
- };
-
- const handleMouseLeave = () => {
- setTooltip({ visible: false, x: 0, y: 0, data: null });
- };
-
- // Zoom controls
- const handleZoomIn = () => setZoomLevel(prev => Math.min(prev + 0.5, 3));
- const handleZoomOut = () => setZoomLevel(prev => Math.max(prev - 0.5, 1));
- const handleResetZoom = () => { setZoomLevel(1); setPanOffset(0); };
-
- return (
- <div className="w-full">
- {/* Zoom Controls */}
- <div className="flex justify-end gap-2 mb-2">
- <button
- onClick={handleZoomOut}
- className="px-2 py-1 rounded text-xs font-mono"
- style={{ backgroundColor: FINCEPT.HEADER_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}` }}
- disabled={zoomLevel <= 1}
- >
- −
- </button>
- <span className="px-2 py-1 text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- {Math.round(zoomLevel * 100)}%
- </span>
- <button
- onClick={handleZoomIn}
- className="px-2 py-1 rounded text-xs font-mono"
- style={{ backgroundColor: FINCEPT.HEADER_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}` }}
- disabled={zoomLevel >= 3}
- >
- +
- </button>
- {zoomLevel !== 1 && (
- <button
- onClick={handleResetZoom}
- className="px-2 py-1 rounded text-xs font-mono"
- style={{ backgroundColor: FINCEPT.HEADER_BG, color: FINCEPT.ORANGE, border: `1px solid ${FINCEPT.BORDER}` }}
- >
- Reset
- </button>
- )}
- </div>
-
- {/* Chart Container with horizontal scroll */}
- <div className="overflow-x-auto" style={{ position: 'relative' }}>
- <svg
- ref={svgRef}
- width={width}
- height={height}
- viewBox={`0 0 ${width} ${height}`}
- style={{ backgroundColor: FINCEPT.DARK_BG, minWidth: baseWidth }}
- >
- {/* Grid lines */}
- {yTicks.map((tick, i) => (
- <line
- key={i}
- x1={padding.left}
- y1={tick.y}
- x2={width - padding.right}
- y2={tick.y}
- stroke={FINCEPT.BORDER}
- strokeWidth={1}
- strokeDasharray="4,4"
- />
- ))}
-
- {/* Forecast region background */}
- {forecastData.length > 0 && (
- <rect
- x={xScale(historicalEndIndex)}
- y={padding.top}
- width={chartWidth - xScale(historicalEndIndex) + padding.left}
- height={chartHeight}
- fill={FINCEPT.ORANGE}
- opacity={0.05}
- />
- )}
-
- {/* Vertical line at forecast start */}
- {forecastData.length > 0 && historicalData.length > 0 && (
- <line
- x1={xScale(historicalEndIndex)}
- y1={padding.top}
- x2={xScale(historicalEndIndex)}
- y2={height - padding.bottom}
- stroke={FINCEPT.ORANGE}
- strokeWidth={1}
- strokeDasharray="6,4"
- opacity={0.6}
- />
- )}
-
- {/* Historical line */}
- {historicalPath && (
- <path
- d={historicalPath}
- fill="none"
- stroke={FINCEPT.CYAN}
- strokeWidth={2}
- />
- )}
-
- {/* Forecast line */}
- {forecastPath && (
- <path
- d={forecastPath}
- fill="none"
- stroke={FINCEPT.ORANGE}
- strokeWidth={2}
- strokeDasharray="6,3"
- />
- )}
-
- {/* Historical data points - Interactive */}
- {historicalData.map((d, i) => {
- const cx = xScale(i);
- const cy = yScale(d.value);
- const dataPoint: ChartDataPoint = { time: d.time, value: d.value, type: 'historical' };
- return (
- <g key={`hist-${i}`}>
- {/* Larger invisible hit area */}
- <circle
- cx={cx}
- cy={cy}
- r={12}
- fill="transparent"
- style={{ cursor: 'pointer' }}
- onMouseEnter={() => handleMouseEnter(dataPoint, cx, cy)}
- onMouseLeave={handleMouseLeave}
- />
- {/* Visible point */}
- <circle
- cx={cx}
- cy={cy}
- r={tooltip.data?.time === d.time && tooltip.data?.type === 'historical' ? 6 : 3}
- fill={FINCEPT.CYAN}
- style={{ transition: 'r 0.15s ease', pointerEvents: 'none' }}
- />
- </g>
- );
- })}
-
- {/* Forecast data points - Interactive */}
- {forecastData.map((d, i) => {
- const cx = xScale(historicalData.length + i);
- const cy = yScale(d.value);
- const dataPoint: ChartDataPoint = { time: d.time, value: d.value, type: 'forecast', entity_id: d.entity_id };
- return (
- <g key={`forecast-${i}`}>
- {/* Larger invisible hit area */}
- <circle
- cx={cx}
- cy={cy}
- r={12}
- fill="transparent"
- style={{ cursor: 'pointer' }}
- onMouseEnter={() => handleMouseEnter(dataPoint, cx, cy)}
- onMouseLeave={handleMouseLeave}
- />
- {/* Visible point */}
- <circle
- cx={cx}
- cy={cy}
- r={tooltip.data?.time === d.time && tooltip.data?.type === 'forecast' ? 7 : 4}
- fill={FINCEPT.ORANGE}
- stroke={FINCEPT.DARK_BG}
- strokeWidth={1}
- style={{ transition: 'r 0.15s ease', pointerEvents: 'none' }}
- />
- </g>
- );
- })}
-
- {/* Y-axis labels */}
- {yTicks.map((tick, i) => (
- <text
- key={i}
- x={padding.left - 10}
- y={tick.y + 4}
- textAnchor="end"
- fontSize={10}
- fontFamily="monospace"
- fill={FINCEPT.GRAY}
- >
- {tick.value.toFixed(2)}
- </text>
- ))}
-
- {/* X-axis labels */}
- {xLabels.map((item, i) => (
- <text
- key={i}
- x={xScale(item.index)}
- y={height - padding.bottom + 20}
- textAnchor="middle"
- fontSize={10}
- fontFamily="monospace"
- fill={FINCEPT.GRAY}
- >
- {item.label}
- </text>
- ))}
-
- {/* Legend */}
- <g transform={`translate(${width - padding.right - 120}, ${padding.top})`}>
- <rect x={0} y={0} width={120} height={50} fill={FINCEPT.PANEL_BG} rx={4} />
- <line x1={10} y1={15} x2={35} y2={15} stroke={FINCEPT.CYAN} strokeWidth={2} />
- <text x={42} y={18} fontSize={10} fontFamily="monospace" fill={FINCEPT.WHITE}>Historical</text>
- <line x1={10} y1={35} x2={35} y2={35} stroke={FINCEPT.ORANGE} strokeWidth={2} strokeDasharray="6,3" />
- <text x={42} y={38} fontSize={10} fontFamily="monospace" fill={FINCEPT.WHITE}>Forecast</text>
- </g>
-
- {/* Forecast label */}
- {forecastData.length > 0 && historicalData.length > 0 && (
- <text
- x={xScale(historicalEndIndex) + 5}
- y={padding.top + 15}
- fontSize={10}
- fontFamily="monospace"
- fill={FINCEPT.ORANGE}
- >
- ▼ Forecast
- </text>
- )}
- </svg>
-
- {/* Tooltip */}
- {tooltip.visible && tooltip.data && (
- <div
- className="absolute pointer-events-none px-3 py-2 rounded shadow-lg z-50"
- style={{
- left: Math.min(tooltip.x + 10, width - 180),
- top: Math.max(tooltip.y - 60, 10),
- backgroundColor: FINCEPT.PANEL_BG,
- border: `1px solid ${tooltip.data.type === 'forecast' ? FINCEPT.ORANGE : FINCEPT.CYAN}`,
- minWidth: 160
- }}
- >
- <div className="text-xs font-mono font-bold mb-1" style={{ color: tooltip.data.type === 'forecast' ? FINCEPT.ORANGE : FINCEPT.CYAN }}>
- {tooltip.data.type === 'forecast' ? '📈 FORECAST' : '📊 HISTORICAL'}
- </div>
- <div className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- Date: <span style={{ color: FINCEPT.WHITE }}>{tooltip.data.time.split('T')[0]}</span>
- </div>
- <div className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- Value: <span style={{ color: FINCEPT.GREEN, fontWeight: 'bold' }}>{tooltip.data.value.toFixed(4)}</span>
- </div>
- {tooltip.data.entity_id && (
- <div className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
- Entity: <span style={{ color: FINCEPT.CYAN }}>{tooltip.data.entity_id}</span>
- </div>
- )}
- </div>
- )}
- </div>
- </div>
- );
-}
+export { FunctimePanel, default } from './functime';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/NodeEditorTab.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/NodeEditorTab.tsx
new file mode 100644
index 000000000..f5626fcda
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/NodeEditorTab.tsx
@@ -0,0 +1,1017 @@
+/**
+ * NodeEditorTab - Main Component
+ *
+ * Visual workflow editor for creating and executing financial analysis workflows.
+ * This is the main orchestrator component that composes all sub-components.
+ */
+
+import React, { useState, useCallback, useMemo, useEffect, useRef } from 'react';
+import ReactFlow, {
+ Node,
+ Edge,
+ addEdge,
+ Background,
+ Controls,
+ MiniMap,
+ Connection,
+ NodeTypes,
+ MarkerType,
+} from 'reactflow';
+import 'reactflow/dist/style.css';
+import {
+ Database,
+ Monitor,
+ Zap,
+ TrendingUp,
+ BarChart3,
+ Brain,
+ FileText,
+ X,
+ Workflow,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+// Local components
+import {
+ CustomNode,
+ NodePalette,
+ NodeEditorToolbar,
+ DeployDialog,
+ NodeConfigPanel,
+} from './components';
+
+// Local hooks
+import { useWorkflowManagement } from './hooks';
+
+// Node components
+import {
+ MCPToolNode,
+ PythonAgentNode,
+ ResultsDisplayNode,
+ AgentMediatorNode,
+ DataSourceNode,
+ TechnicalIndicatorNode,
+ BacktestNode,
+ OptimizationNode,
+ SystemNode,
+ WorkflowManager,
+ ResultsModal,
+ generateMCPNodeConfigs,
+ MCPNodeConfig,
+} from './nodes';
+
+// Constants
+import { BUILTIN_NODE_CONFIGS, DEFAULT_EDGE_OPTIONS, FLOW_BACKGROUND_CONFIG } from './constants';
+
+// Types
+import type { INodeTypeDescription, NodeParameterValue } from './types';
+
+// Services
+import { pythonAgentService, AgentMetadata } from '@/services/chat/pythonAgentService';
+import { workflowService } from '@/services/core/workflowService';
+import { nodeExecutionManager } from '@/services/core/nodeExecutionManager';
+import { NodeRegistry } from '@/services/nodeSystem';
+import { TabFooter } from '@/components/common/TabFooter';
+
+export default function NodeEditorTab() {
+ const { t } = useTranslation('nodeEditor');
+
+ // MCP and agent configurations
+ const [mcpNodeConfigs, setMcpNodeConfigs] = useState<MCPNodeConfig[]>([]);
+ const [agentConfigs, setAgentConfigs] = useState<AgentMetadata[]>([]);
+
+ // Workflow management hook
+ const {
+ nodes,
+ edges,
+ setNodes,
+ setEdges,
+ onNodesChange,
+ onEdgesChange,
+ selectedNodes,
+ setSelectedNodes,
+ isExecuting,
+ setIsExecuting,
+ workflowMode,
+ setWorkflowMode,
+ editingDraftId,
+ setEditingDraftId,
+ workflowName,
+ setWorkflowName,
+ workflowDescription,
+ setWorkflowDescription,
+ saveWorkflow,
+ exportWorkflow,
+ importWorkflow,
+ clearWorkflow,
+ deployWorkflow,
+ saveDraft,
+ handleLoadWorkflow,
+ handleViewResults,
+ handleEditDraft,
+ deleteSelectedNodes,
+ deleteSelectedEdges,
+ onSelectionChange,
+ } = useWorkflowManagement();
+
+ // UI state
+ const [showNodeMenu, setShowNodeMenu] = useState(false);
+ const [activeView, setActiveView] = useState<'editor' | 'workflows'>('editor');
+ const [isPaletteCollapsed, setIsPaletteCollapsed] = useState(false);
+ const [showDeployDialog, setShowDeployDialog] = useState(false);
+ const [showResultsModal, setShowResultsModal] = useState(false);
+ const [resultsData, setResultsData] = useState<any>(null);
+ const [resultsWorkflowName, setResultsWorkflowName] = useState<string>('');
+
+ const reactFlowWrapper = useRef<HTMLDivElement>(null);
+
+ // Load MCP node configurations and Python agents on mount
+ useEffect(() => {
+ const loadMCPNodes = async () => {
+ try {
+ const configs = await generateMCPNodeConfigs();
+ setMcpNodeConfigs(configs);
+ } catch (error) {
+ console.error('[NodeEditor] Failed to load MCP configs:', error);
+ }
+ };
+
+ const loadAgents = async () => {
+ try {
+ const agents = await pythonAgentService.getAvailableAgents();
+ setAgentConfigs(agents);
+ } catch (error) {
+ console.error('[NodeEditor] Failed to load agents:', error);
+ }
+ };
+
+ loadMCPNodes();
+ loadAgents();
+ }, []);
+
+ // Node types configuration
+ const nodeTypes: NodeTypes = useMemo(
+ () => ({
+ custom: CustomNode,
+ 'mcp-tool': MCPToolNode,
+ 'python-agent': PythonAgentNode,
+ 'results-display': ResultsDisplayNode,
+ 'agent-mediator': AgentMediatorNode,
+ 'data-source': DataSourceNode,
+ 'technical-indicator': TechnicalIndicatorNode,
+ backtest: BacktestNode,
+ optimization: OptimizationNode,
+ system: SystemNode,
+ }),
+ []
+ );
+
+ // Handle label change
+ const handleLabelChange = useCallback(
+ (nodeId: string, newLabel: string) => {
+ setNodes((nds) =>
+ nds.map((node) => {
+ if (node.id === nodeId) {
+ return {
+ ...node,
+ data: {
+ ...node.data,
+ label: newLabel,
+ },
+ };
+ }
+ return node;
+ })
+ );
+ },
+ [setNodes]
+ );
+
+ // Handle connection
+ const onConnect = useCallback(
+ (params: Connection) => {
+ const newEdge = {
+ ...params,
+ animated: true,
+ style: { stroke: '#ea580c', strokeWidth: 2 },
+ markerEnd: { type: MarkerType.ArrowClosed, color: '#ea580c' },
+ };
+ setEdges((eds) => addEdge(newEdge, eds));
+ },
+ [setEdges]
+ );
+
+ // Add new node
+ const addNode = useCallback(
+ (config: any) => {
+ const isMCPNode = config.type === 'mcp-tool';
+ const isPythonAgent = config.type === 'python-agent';
+ const isResultsDisplay = config.type === 'results-display';
+ const isAgentMediator = config.type === 'agent-mediator';
+ const isDataSource = config.type === 'data-source';
+ const isTechnicalIndicator = config.type === 'technical-indicator';
+
+ const nodeId = `node_${Date.now()}`;
+
+ const newNode: Node = {
+ id: nodeId,
+ type: isPythonAgent
+ ? 'python-agent'
+ : isMCPNode
+ ? 'mcp-tool'
+ : isResultsDisplay
+ ? 'results-display'
+ : isAgentMediator
+ ? 'agent-mediator'
+ : isDataSource
+ ? 'data-source'
+ : isTechnicalIndicator
+ ? 'technical-indicator'
+ : 'custom',
+ position: { x: Math.random() * 400 + 100, y: Math.random() * 300 + 100 },
+ data: isPythonAgent
+ ? {
+ agentType: config.id,
+ agentCategory: config.category,
+ label: config.name,
+ icon: config.icon,
+ color: config.color,
+ parameters: config.parameters?.reduce((acc: any, param: any) => {
+ if (param.default_value !== null && param.default_value !== undefined) {
+ acc[param.name] = param.default_value;
+ }
+ return acc;
+ }, {}) || {},
+ selectedLLM: 'active',
+ status: 'idle',
+ onExecute: async (nodeIdParam: string) => {
+ try {
+ setNodes((nds) =>
+ nds.map((n) =>
+ n.id === nodeIdParam ? { ...n, data: { ...n.data, status: 'running' } } : n
+ )
+ );
+
+ const result = await pythonAgentService.executeAgent(
+ config.id,
+ config.parameters?.reduce((acc: any, param: any) => {
+ if (param.default_value !== null && param.default_value !== undefined) {
+ acc[param.name] = param.default_value;
+ }
+ return acc;
+ }, {}) || {},
+ {}
+ );
+
+ setNodes((nds) =>
+ nds.map((n) =>
+ n.id === nodeIdParam
+ ? {
+ ...n,
+ data: {
+ ...n.data,
+ status: result.success ? 'completed' : 'error',
+ result: result.success ? result.data : undefined,
+ error: result.success ? undefined : result.error,
+ },
+ }
+ : n
+ )
+ );
+ } catch (error: any) {
+ setNodes((nds) =>
+ nds.map((n) =>
+ n.id === nodeIdParam
+ ? { ...n, data: { ...n.data, status: 'error', error: error.message } }
+ : n
+ )
+ );
+ }
+ },
+ onParameterChange: () => {},
+ onLLMChange: (provider: string) => {
+ setNodes((nds) =>
+ nds.map((n) =>
+ n.id === nodeId
+ ? { ...n, data: { ...n.data, selectedLLM: provider } }
+ : n
+ )
+ );
+ },
+ }
+ : isMCPNode
+ ? {
+ serverId: config.serverId,
+ toolName: config.toolName,
+ label: config.label,
+ parameters: {},
+ onParameterChange: () => {},
+ onExecute: () => {},
+ }
+ : isResultsDisplay
+ ? {
+ label: config.label,
+ color: config.color,
+ inputData: undefined,
+ }
+ : isAgentMediator
+ ? {
+ label: config.label,
+ selectedProvider: undefined,
+ customPrompt: undefined,
+ status: 'idle',
+ result: undefined,
+ error: undefined,
+ inputData: undefined,
+ onExecute: () => {},
+ onConfigChange: (newConfig: any) => {
+ setNodes((nds) =>
+ nds.map((n) =>
+ n.id === nodeId
+ ? {
+ ...n,
+ data: {
+ ...n.data,
+ selectedProvider: newConfig.selectedProvider,
+ customPrompt: newConfig.customPrompt,
+ },
+ }
+ : n
+ )
+ );
+ },
+ }
+ : isDataSource
+ ? {
+ label: config.label,
+ selectedConnectionId: undefined,
+ query: '',
+ status: 'idle',
+ result: undefined,
+ error: undefined,
+ onConnectionChange: (connectionId: string) => {
+ setNodes((nds) =>
+ nds.map((n) =>
+ n.id === nodeId
+ ? { ...n, data: { ...n.data, selectedConnectionId: connectionId } }
+ : n
+ )
+ );
+ },
+ onQueryChange: (query: string) => {
+ setNodes((nds) =>
+ nds.map((n) =>
+ n.id === nodeId ? { ...n, data: { ...n.data, query: query } } : n
+ )
+ );
+ },
+ onExecute: async () => {},
+ }
+ : isTechnicalIndicator
+ ? {
+ label: config.label,
+ dataSource: 'yfinance',
+ symbol: 'AAPL',
+ period: '1y',
+ csvPath: '',
+ jsonData: '',
+ categories: ['momentum', 'volume', 'volatility', 'trend', 'others'],
+ status: 'idle',
+ result: undefined,
+ error: undefined,
+ onExecute: () => {},
+ onParameterChange: (params: Record<string, any>) => {
+ setNodes((nds) =>
+ nds.map((n) =>
+ n.id === nodeId ? { ...n, data: { ...n.data, ...params } } : n
+ )
+ );
+ },
+ }
+ : {
+ label: config.label,
+ nodeType: config.type,
+ color: config.color,
+ hasInput: config.hasInput,
+ hasOutput: config.hasOutput,
+ onLabelChange: handleLabelChange,
+ },
+ };
+
+ setNodes((nds) => [...nds, newNode]);
+ setShowNodeMenu(false);
+ },
+ [setNodes, handleLabelChange]
+ );
+
+ // Handle node from palette
+ const handlePaletteNodeAdd = useCallback(
+ (nodeType: string, nodeData: any) => {
+ if (nodeData.source === 'builtin') {
+ addNode(nodeData.data);
+ } else if (nodeData.source === 'mcp') {
+ addNode(nodeData.data);
+ } else if (nodeData.source === 'agent') {
+ addNode({ ...nodeData.data, type: 'python-agent' });
+ } else if (nodeData.source === 'registry') {
+ const registryNode = nodeData.data as INodeTypeDescription;
+ const newNode: Node = {
+ id: `node_${Date.now()}`,
+ type: 'custom',
+ position: { x: Math.random() * 400 + 100, y: Math.random() * 300 + 100 },
+ data: {
+ label: registryNode.displayName,
+ nodeTypeName: registryNode.name,
+ color: nodeData.color || '#6b7280',
+ hasInput:
+ (registryNode.inputs?.length || 0) > 0 || registryNode.name !== 'manualTrigger',
+ hasOutput: (registryNode.outputs?.length || 0) > 0,
+ status: 'idle',
+ parameters: {},
+ registryData: registryNode,
+ onLabelChange: handleLabelChange,
+ },
+ };
+ setNodes((nds) => [...nds, newNode]);
+ }
+
+ setShowNodeMenu(false);
+ },
+ [addNode, setNodes, handleLabelChange]
+ );
+
+ // Handle drop from palette
+ const onDrop = useCallback(
+ (event: React.DragEvent) => {
+ event.preventDefault();
+
+ const data = event.dataTransfer.getData('application/reactflow');
+ if (!data) return;
+
+ const nodeData = JSON.parse(data);
+ const reactFlowBounds = reactFlowWrapper.current?.getBoundingClientRect();
+ if (!reactFlowBounds) return;
+
+ const position = {
+ x: event.clientX - reactFlowBounds.left - 150,
+ y: event.clientY - reactFlowBounds.top - 25,
+ };
+
+ if (nodeData.source === 'registry') {
+ const registryNode = nodeData.data as INodeTypeDescription;
+ const newNode: Node = {
+ id: `node_${Date.now()}`,
+ type: 'custom',
+ position,
+ data: {
+ label: registryNode.displayName,
+ nodeTypeName: registryNode.name,
+ color: nodeData.color || '#6b7280',
+ hasInput:
+ (registryNode.inputs?.length || 0) > 0 || registryNode.name !== 'manualTrigger',
+ hasOutput: (registryNode.outputs?.length || 0) > 0,
+ status: 'idle',
+ parameters: {},
+ registryData: registryNode,
+ onLabelChange: handleLabelChange,
+ },
+ };
+ setNodes((nds) => [...nds, newNode]);
+ } else {
+ handlePaletteNodeAdd(nodeData.type, nodeData);
+ }
+ },
+ [setNodes, handlePaletteNodeAdd, handleLabelChange]
+ );
+
+ const onDragOver = useCallback((event: React.DragEvent) => {
+ event.preventDefault();
+ event.dataTransfer.dropEffect = 'move';
+ }, []);
+
+ // Execute workflow
+ const handleExecute = useCallback(async () => {
+ if (isExecuting) {
+ alert('A workflow is already executing. Please wait for it to complete.');
+ return;
+ }
+
+ try {
+ setIsExecuting(true);
+ await nodeExecutionManager.executeWorkflow(nodes, edges, (nodeId, status, result) => {
+ setNodes((nds) =>
+ nds.map((node) => {
+ if (node.id === nodeId) {
+ if (node.type === 'results-display') {
+ return {
+ ...node,
+ data: {
+ ...node.data,
+ inputData: status === 'completed' ? result : undefined,
+ status,
+ },
+ };
+ }
+ return {
+ ...node,
+ data: {
+ ...node.data,
+ status,
+ result: status === 'completed' ? result : undefined,
+ error: status === 'error' ? result : undefined,
+ },
+ };
+ }
+ return node;
+ })
+ );
+ });
+ } catch (error: any) {
+ console.error('[NodeEditor] Workflow execution failed:', error);
+ } finally {
+ setIsExecuting(false);
+ }
+ }, [isExecuting, nodes, edges, setNodes, setIsExecuting]);
+
+ // Handle keyboard shortcuts
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key === 'Delete' || event.key === 'Backspace') {
+ deleteSelectedNodes();
+ deleteSelectedEdges();
+ }
+ };
+
+ window.addEventListener('keydown', handleKeyDown);
+ return () => window.removeEventListener('keydown', handleKeyDown);
+ }, [deleteSelectedNodes, deleteSelectedEdges]);
+
+ // Quick save draft handler
+ const handleQuickSaveDraft = useCallback(async () => {
+ if (editingDraftId) {
+ try {
+ await workflowService.updateDraft(
+ editingDraftId,
+ workflowName || 'Untitled Draft',
+ workflowDescription,
+ nodes,
+ edges
+ );
+ alert('Draft saved successfully!');
+ } catch (error: any) {
+ alert(`Save failed: ${error.message}`);
+ }
+ }
+ }, [editingDraftId, workflowName, workflowDescription, nodes, edges]);
+
+ // Handle deploy with status callback
+ const handleDeploy = useCallback(() => {
+ setShowDeployDialog(false);
+ setWorkflowName('');
+ setWorkflowDescription('');
+ setEditingDraftId(null);
+ setActiveView('editor');
+
+ deployWorkflow((nodeId, status, result) => {
+ setNodes((nds) =>
+ nds.map((node) => {
+ if (node.id === nodeId) {
+ if (node.type === 'results-display') {
+ return {
+ ...node,
+ data: {
+ ...node.data,
+ inputData: status === 'completed' ? result : undefined,
+ status,
+ },
+ };
+ }
+ return {
+ ...node,
+ data: {
+ ...node.data,
+ status,
+ result: status === 'completed' ? result : undefined,
+ error: status === 'error' ? result : undefined,
+ },
+ };
+ }
+ return node;
+ })
+ );
+ });
+ }, [deployWorkflow, setNodes, setWorkflowName, setWorkflowDescription, setEditingDraftId]);
+
+ // Handle save draft
+ const handleSaveDraft = useCallback(() => {
+ saveDraft();
+ setShowDeployDialog(false);
+ setWorkflowName('');
+ setWorkflowDescription('');
+ setActiveView('workflows');
+ }, [saveDraft]);
+
+ // Handle view results wrapper
+ const handleViewResultsWrapper = useCallback(
+ (workflow: any) => {
+ const result = handleViewResults(workflow);
+ if ('showModal' in result && result.showModal) {
+ setResultsData(result.data);
+ setResultsWorkflowName(result.name);
+ setShowResultsModal(true);
+ } else if ('navigate' in result && result.navigate) {
+ setActiveView('editor');
+ }
+ },
+ [handleViewResults]
+ );
+
+ // Handle edit draft wrapper
+ const handleEditDraftWrapper = useCallback(
+ (workflow: any) => {
+ handleEditDraft(workflow);
+ setShowDeployDialog(true);
+ setActiveView('editor');
+ },
+ [handleEditDraft]
+ );
+
+ // Handle parameter change for config panel
+ const handleParameterChange = useCallback(
+ (paramName: string, value: NodeParameterValue) => {
+ if (selectedNodes.length === 1) {
+ setNodes((nds) =>
+ nds.map((node) => {
+ if (node.id === selectedNodes[0]) {
+ return {
+ ...node,
+ data: {
+ ...node.data,
+ parameters: {
+ ...(node.data.parameters || {}),
+ [paramName]: value,
+ },
+ },
+ };
+ }
+ return node;
+ })
+ );
+ }
+ },
+ [selectedNodes, setNodes]
+ );
+
+ // Handle duplicate node
+ const handleDuplicateNode = useCallback(() => {
+ if (selectedNodes.length === 1) {
+ const selectedNode = nodes.find((n) => n.id === selectedNodes[0]);
+ if (selectedNode) {
+ const newNode = {
+ ...selectedNode,
+ id: `node_${Date.now()}`,
+ position: {
+ x: selectedNode.position.x + 50,
+ y: selectedNode.position.y + 50,
+ },
+ data: { ...selectedNode.data },
+ };
+ setNodes((nds) => [...nds, newNode]);
+ }
+ }
+ }, [selectedNodes, nodes, setNodes]);
+
+ // Get selected node for config panel
+ const selectedNode = selectedNodes.length === 1 ? nodes.find((n) => n.id === selectedNodes[0]) : null;
+
+ return (
+ <div
+ style={{
+ width: '100%',
+ height: '100%',
+ backgroundColor: '#0a0a0a',
+ display: 'flex',
+ flexDirection: 'column',
+ }}
+ >
+ {/* Toolbar */}
+ <NodeEditorToolbar
+ activeView={activeView}
+ setActiveView={setActiveView}
+ showNodeMenu={showNodeMenu}
+ setShowNodeMenu={setShowNodeMenu}
+ isExecuting={isExecuting}
+ nodes={nodes}
+ edges={edges}
+ selectedNodes={selectedNodes}
+ workflowMode={workflowMode}
+ editingDraftId={editingDraftId}
+ workflowName={workflowName}
+ workflowDescription={workflowDescription}
+ onExecute={handleExecute}
+ onClearWorkflow={clearWorkflow}
+ onSaveWorkflow={saveWorkflow}
+ onImportWorkflow={importWorkflow}
+ onExportWorkflow={exportWorkflow}
+ onDeleteSelectedNodes={deleteSelectedNodes}
+ onShowDeployDialog={() => setShowDeployDialog(true)}
+ onQuickSaveDraft={handleQuickSaveDraft}
+ />
+
+ {/* Node Menu */}
+ {showNodeMenu && (
+ <div
+ style={{
+ position: 'absolute',
+ top: '60px',
+ left: '12px',
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #2d2d2d',
+ borderRadius: '4px',
+ padding: '12px',
+ zIndex: 1000,
+ minWidth: '250px',
+ maxHeight: '400px',
+ overflow: 'auto',
+ boxShadow: '0 4px 12px rgba(0,0,0,0.5)',
+ }}
+ >
+ <div
+ style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '12px',
+ }}
+ >
+ <div
+ style={{
+ color: '#a3a3a3',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ letterSpacing: '0.5px',
+ }}
+ >
+ SELECT NODE TYPE
+ </div>
+ <button
+ onClick={() => setShowNodeMenu(false)}
+ style={{
+ background: 'transparent',
+ border: 'none',
+ color: '#a3a3a3',
+ cursor: 'pointer',
+ padding: '2px',
+ }}
+ >
+ <X size={16} />
+ </button>
+ </div>
+
+ {['Input', 'Processing', 'Output', 'AI', 'Analytics'].map((category) => (
+ <div key={category} style={{ marginBottom: '12px' }}>
+ <div
+ style={{
+ color: '#737373',
+ fontSize: '10px',
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}
+ >
+ {category}
+ </div>
+ {BUILTIN_NODE_CONFIGS.filter((t) => t.category === category).map((config) => (
+ <button
+ key={config.type}
+ onClick={() => addNode(config)}
+ style={{
+ backgroundColor: '#0a0a0a',
+ color: config.color,
+ border: `1px solid ${config.color}40`,
+ padding: '8px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ width: '100%',
+ marginBottom: '6px',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = `${config.color}20`;
+ e.currentTarget.style.borderColor = config.color;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = '#0a0a0a';
+ e.currentTarget.style.borderColor = `${config.color}40`;
+ }}
+ >
+ {config.type === 'data-source' && <Database size={16} />}
+ {config.type === 'technical-indicator' && <TrendingUp size={16} />}
+ {config.type === 'results-display' && <Monitor size={16} />}
+ {config.type === 'agent-mediator' && <Brain size={16} />}
+ {config.type === 'backtest' && <BarChart3 size={16} />}
+ {config.type === 'optimization' && <Zap size={16} />}
+ {config.label}
+ </button>
+ ))}
+ </div>
+ ))}
+
+ {/* MCP Tools Section */}
+ {mcpNodeConfigs.length > 0 && (
+ <div style={{ marginBottom: '12px' }}>
+ <div
+ style={{
+ color: '#ea580c',
+ fontSize: '10px',
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ fontWeight: 'bold',
+ }}
+ >
+ MCP TOOLS ({mcpNodeConfigs.length})
+ </div>
+ {mcpNodeConfigs.map((config) => (
+ <button
+ key={config.id}
+ onClick={() => addNode(config)}
+ style={{
+ backgroundColor: '#0a0a0a',
+ color: '#ea580c',
+ border: '1px solid #ea580c40',
+ padding: '8px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ width: '100%',
+ marginBottom: '6px',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#ea580c20';
+ e.currentTarget.style.borderColor = '#ea580c';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = '#0a0a0a';
+ e.currentTarget.style.borderColor = '#ea580c40';
+ }}
+ >
+ <span style={{ fontSize: '14px' }}>{config.icon}</span>
+ <div style={{ flex: 1, textAlign: 'left' }}>
+ <div>{config.label}</div>
+ <div style={{ fontSize: '9px', color: '#6b7280' }}>{config.serverId}</div>
+ </div>
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Main Content */}
+ {activeView === 'editor' ? (
+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
+ {/* Left Sidebar - Node Palette */}
+ <NodePalette
+ onNodeAdd={handlePaletteNodeAdd}
+ isCollapsed={isPaletteCollapsed}
+ onToggleCollapse={() => setIsPaletteCollapsed(!isPaletteCollapsed)}
+ mcpNodeConfigs={mcpNodeConfigs}
+ agentConfigs={agentConfigs}
+ />
+
+ {/* React Flow Canvas */}
+ <div
+ ref={reactFlowWrapper}
+ style={{ flex: 1, position: 'relative' }}
+ onDrop={onDrop}
+ onDragOver={onDragOver}
+ >
+ <ReactFlow
+ nodes={nodes}
+ edges={edges}
+ onNodesChange={onNodesChange}
+ onEdgesChange={onEdgesChange}
+ onConnect={onConnect}
+ onSelectionChange={onSelectionChange}
+ nodeTypes={nodeTypes}
+ fitView
+ style={{ background: '#0a0a0a' }}
+ defaultEdgeOptions={DEFAULT_EDGE_OPTIONS}
+ >
+ <Background {...FLOW_BACKGROUND_CONFIG} />
+ <Controls
+ style={{
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #2d2d2d',
+ borderRadius: '4px',
+ }}
+ />
+ <MiniMap
+ style={{
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #2d2d2d',
+ }}
+ nodeColor={(node) => node.data.color || '#3b82f6'}
+ />
+ </ReactFlow>
+
+ {/* Empty State Overlay */}
+ {nodes.length === 0 && (
+ <div
+ style={{
+ position: 'absolute',
+ top: '50%',
+ left: '50%',
+ transform: 'translate(-50%, -50%)',
+ textAlign: 'center',
+ color: '#6b7280',
+ pointerEvents: 'none',
+ }}
+ >
+ <Workflow size={48} style={{ margin: '0 auto 16px', opacity: 0.3 }} />
+ <div style={{ fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ No nodes yet
+ </div>
+ <div style={{ fontSize: '12px', opacity: 0.7 }}>
+ Drag nodes from the palette or click ADD NODE to get started
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Right Sidebar - Config Panel */}
+ {selectedNode && (
+ <NodeConfigPanel
+ selectedNode={selectedNode}
+ onLabelChange={handleLabelChange}
+ onParameterChange={handleParameterChange}
+ onClose={() => setSelectedNodes([])}
+ onDelete={deleteSelectedNodes}
+ onDuplicate={handleDuplicateNode}
+ />
+ )}
+ </div>
+ ) : (
+ /* Workflow Manager View */
+ <div style={{ flex: 1, overflow: 'hidden' }}>
+ <WorkflowManager
+ onLoadWorkflow={handleLoadWorkflow}
+ onViewResults={handleViewResultsWrapper}
+ onEditDraft={handleEditDraftWrapper}
+ />
+ </div>
+ )}
+
+ {/* Bottom Info Bar */}
+ {activeView === 'editor' && (
+ <TabFooter
+ tabName="NODE EDITOR"
+ leftInfo={[
+ {
+ label: 'Drag nodes to move | Drag from handles to connect | Select & Delete to remove',
+ color: '#737373',
+ },
+ ...(selectedNodes.length > 0
+ ? [{ label: `Selected: ${selectedNodes.length} node(s)`, color: '#ea580c' }]
+ : []),
+ ]}
+ statusInfo="Scroll to zoom | Right-click drag to pan"
+ backgroundColor="#1a1a1a"
+ borderColor="#2d2d2d"
+ />
+ )}
+
+ {/* Deploy Dialog */}
+ <DeployDialog
+ isOpen={showDeployDialog}
+ onClose={() => setShowDeployDialog(false)}
+ workflowName={workflowName}
+ setWorkflowName={setWorkflowName}
+ workflowDescription={workflowDescription}
+ setWorkflowDescription={setWorkflowDescription}
+ onDeploy={handleDeploy}
+ onSaveDraft={handleSaveDraft}
+ />
+
+ {/* Results Modal */}
+ {showResultsModal && (
+ <ResultsModal
+ data={resultsData}
+ workflowName={resultsWorkflowName}
+ onClose={() => {
+ setShowResultsModal(false);
+ setResultsData(null);
+ setResultsWorkflowName('');
+ }}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/CFAQuantPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/CFAQuantPanel.tsx
new file mode 100644
index 000000000..3708dc2bd
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/CFAQuantPanel.tsx
@@ -0,0 +1,214 @@
+/**
+ * CFA Quant Panel
+ * Main component for CFA-level quantitative analytics
+ *
+ * This component has been refactored into smaller, more maintainable pieces.
+ * See the cfa-quant folder for:
+ * - components/ - UI components (Header, DataStep, AnalysisStep, ResultsStep, etc.)
+ * - hooks/ - Custom hooks (useChartZoom, usePriceData)
+ * - utils/ - Utility functions (formatters, calculations, metricsExtractor, chartDataBuilder)
+ * - constants.ts - Color palette and analysis configurations
+ * - types.ts - TypeScript interfaces
+ */
+
+import React, { useState, useMemo, useCallback } from 'react';
+import { quantAnalyticsService, type QuantAnalyticsResult } from '@/services/aiQuantLab/quantAnalyticsService';
+import { BB, analysisConfigs } from './constants';
+import type { Step, DataSourceType } from './types';
+import { useChartZoom, usePriceData } from './hooks';
+import { Header, DataStep, AnalysisStep, ResultsStep } from './components';
+
+export function CFAQuantPanel() {
+ // Step navigation
+ const [currentStep, setCurrentStep] = useState<Step>('data');
+
+ // Loading and error states
+ const [isLoading, setIsLoading] = useState(false);
+ const [analysisResult, setAnalysisResult] = useState<QuantAnalyticsResult<Record<string, unknown>> | null>(null);
+
+ // Data input state
+ const [dataSourceType, setDataSourceType] = useState<DataSourceType>('symbol');
+ const [symbolInput, setSymbolInput] = useState('AAPL');
+ const [historicalDays, setHistoricalDays] = useState(365);
+ const [manualData, setManualData] = useState('');
+
+ // Analysis state
+ const [selectedAnalysis, setSelectedAnalysis] = useState<string>('trend_analysis');
+
+ // Price data hook
+ const {
+ priceData,
+ priceDates,
+ priceDataLoading,
+ dataStats,
+ chartData,
+ fetchSymbolData: fetchSymbolDataBase,
+ error,
+ setError,
+ getDataArray,
+ getDateForIndex,
+ } = usePriceData({ dataSourceType, manualData });
+
+ // Chart zoom hook
+ const {
+ dataChartZoom,
+ setDataChartZoom,
+ resultsChartZoom,
+ setResultsChartZoom,
+ refAreaLeft,
+ refAreaRight,
+ isSelecting,
+ activeChart,
+ handleZoomIn,
+ handleZoomOut,
+ handleResetZoom,
+ handlePanLeft,
+ handlePanRight,
+ canPanLeft,
+ canPanRight,
+ handleMouseDown,
+ handleMouseMove,
+ handleMouseUp,
+ handleWheel,
+ } = useChartZoom({
+ priceDataLength: priceData.length,
+ analysisResult,
+ selectedAnalysis,
+ });
+
+ // Fetch symbol data wrapper
+ const fetchSymbolData = useCallback(async () => {
+ await fetchSymbolDataBase(symbolInput, historicalDays);
+ setDataChartZoom(null);
+ }, [fetchSymbolDataBase, symbolInput, historicalDays, setDataChartZoom]);
+
+ // Zoomed chart data
+ const zoomedChartData = useMemo(() => {
+ if (!dataChartZoom) return chartData;
+ return chartData.slice(dataChartZoom.startIndex, dataChartZoom.endIndex + 1);
+ }, [chartData, dataChartZoom]);
+
+ // Run analysis
+ const runAnalysis = useCallback(async () => {
+ setIsLoading(true);
+ setError(null);
+ setAnalysisResult(null);
+
+ try {
+ const data = getDataArray(priceData, manualData, dataSourceType);
+ const config = analysisConfigs.find(a => a.id === selectedAnalysis);
+
+ if (data.length === 0) {
+ setError('No data available');
+ setIsLoading(false);
+ return;
+ }
+
+ if (config && data.length < config.minDataPoints) {
+ setError(`Need ${config.minDataPoints} data points (have ${data.length})`);
+ setIsLoading(false);
+ return;
+ }
+
+ const params: Record<string, unknown> = { data };
+ const result = await quantAnalyticsService.executeCustomCommand(selectedAnalysis, params);
+ setAnalysisResult(result as QuantAnalyticsResult<Record<string, unknown>>);
+
+ if (result.success) {
+ setCurrentStep('results');
+ } else if (result.error) {
+ setError(result.error);
+ }
+ } catch (err) {
+ setError(`Analysis failed: ${err}`);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [priceData, manualData, dataSourceType, selectedAnalysis, getDataArray, setError]);
+
+ return (
+ <div className="h-full flex flex-col" style={{ backgroundColor: BB.black }}>
+ <Header
+ currentStep={currentStep}
+ setCurrentStep={setCurrentStep}
+ analysisResult={analysisResult}
+ dataSourceType={dataSourceType}
+ symbolInput={symbolInput}
+ dataStats={dataStats}
+ />
+ <div className="flex-1 overflow-hidden">
+ {currentStep === 'data' && (
+ <DataStep
+ dataSourceType={dataSourceType}
+ setDataSourceType={setDataSourceType}
+ symbolInput={symbolInput}
+ setSymbolInput={setSymbolInput}
+ historicalDays={historicalDays}
+ setHistoricalDays={setHistoricalDays}
+ manualData={manualData}
+ setManualData={setManualData}
+ priceData={priceData}
+ priceDates={priceDates}
+ priceDataLoading={priceDataLoading}
+ dataStats={dataStats}
+ error={error}
+ chartData={chartData}
+ zoomedChartData={zoomedChartData}
+ dataChartZoom={dataChartZoom}
+ setDataChartZoom={setDataChartZoom}
+ fetchSymbolData={fetchSymbolData}
+ setCurrentStep={setCurrentStep}
+ getDateForIndex={getDateForIndex}
+ handleWheel={handleWheel}
+ handleMouseDown={handleMouseDown}
+ handleMouseMove={handleMouseMove}
+ handleMouseUp={handleMouseUp}
+ isSelecting={isSelecting}
+ activeChart={activeChart}
+ refAreaLeft={refAreaLeft}
+ refAreaRight={refAreaRight}
+ />
+ )}
+ {currentStep === 'analysis' && (
+ <AnalysisStep
+ selectedAnalysis={selectedAnalysis}
+ setSelectedAnalysis={setSelectedAnalysis}
+ priceData={priceData}
+ isLoading={isLoading}
+ error={error}
+ runAnalysis={runAnalysis}
+ setCurrentStep={setCurrentStep}
+ zoomedChartData={zoomedChartData}
+ dataChartZoom={dataChartZoom}
+ setDataChartZoom={setDataChartZoom}
+ />
+ )}
+ {currentStep === 'results' && (
+ <ResultsStep
+ analysisResult={analysisResult}
+ selectedAnalysis={selectedAnalysis}
+ symbolInput={symbolInput}
+ priceData={priceData}
+ priceDates={priceDates}
+ chartData={chartData}
+ setCurrentStep={setCurrentStep}
+ setAnalysisResult={setAnalysisResult}
+ resultsChartZoom={resultsChartZoom}
+ setResultsChartZoom={setResultsChartZoom}
+ getDateForIndex={getDateForIndex}
+ handleWheel={handleWheel}
+ handleMouseDown={handleMouseDown}
+ handleMouseMove={handleMouseMove}
+ handleMouseUp={handleMouseUp}
+ isSelecting={isSelecting}
+ activeChart={activeChart}
+ refAreaLeft={refAreaLeft}
+ refAreaRight={refAreaRight}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
+
+export default CFAQuantPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/AnalysisStep.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/AnalysisStep.tsx
new file mode 100644
index 000000000..0d3b84472
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/AnalysisStep.tsx
@@ -0,0 +1,172 @@
+/**
+ * Analysis Step Component
+ * Handles model selection and execution
+ */
+
+import React from 'react';
+import { ChevronLeft, Zap, RotateCcw } from 'lucide-react';
+import {
+ LineChart,
+ Line,
+ XAxis,
+ YAxis,
+ CartesianGrid,
+ ResponsiveContainer,
+} from 'recharts';
+import { BB, analysisConfigs } from '../constants';
+import type { AnalysisStepProps } from '../types';
+
+export function AnalysisStep({
+ selectedAnalysis,
+ setSelectedAnalysis,
+ priceData,
+ isLoading,
+ error,
+ runAnalysis,
+ setCurrentStep,
+ zoomedChartData,
+ dataChartZoom,
+ setDataChartZoom,
+}: AnalysisStepProps) {
+ const selectedConfig = analysisConfigs.find(a => a.id === selectedAnalysis);
+ const canRun = priceData.length >= (selectedConfig?.minDataPoints || 0);
+
+ return (
+ <div className="flex h-full">
+ {/* Left Panel - Analysis Selection */}
+ <div
+ className="w-80 flex-shrink-0 p-4 overflow-y-auto"
+ style={{ backgroundColor: BB.panelBg, borderRight: `1px solid ${BB.borderDark}` }}
+ >
+ <div className="text-xs font-mono mb-3" style={{ color: BB.textAmber }}>SELECT MODEL</div>
+
+ <div className="space-y-1">
+ {analysisConfigs.map((config) => {
+ const isSelected = selectedAnalysis === config.id;
+ const hasEnoughData = priceData.length >= config.minDataPoints;
+ const Icon = config.icon;
+
+ return (
+ <button
+ key={config.id}
+ onClick={() => hasEnoughData && setSelectedAnalysis(config.id)}
+ className="w-full px-3 py-2 text-left flex items-center gap-3 transition-colors"
+ style={{
+ backgroundColor: isSelected ? BB.cardBg : 'transparent',
+ borderLeft: `3px solid ${isSelected ? config.color : 'transparent'}`,
+ opacity: hasEnoughData ? 1 : 0.4,
+ cursor: hasEnoughData ? 'pointer' : 'not-allowed',
+ }}
+ >
+ <Icon size={16} style={{ color: config.color }} />
+ <div className="flex-1 min-w-0">
+ <div className="text-xs font-mono font-bold" style={{ color: BB.textPrimary }}>{config.shortName}</div>
+ <div className="text-xs font-mono truncate" style={{ color: BB.textMuted }}>{config.name}</div>
+ </div>
+ {!hasEnoughData && (
+ <span className="text-xs font-mono" style={{ color: BB.red }}>
+ {config.minDataPoints}+
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+
+ <div className="mt-4 flex gap-2">
+ <button
+ onClick={() => setCurrentStep('data')}
+ className="flex-1 py-2 text-xs font-mono"
+ style={{ backgroundColor: BB.cardBg, color: BB.textSecondary, border: `1px solid ${BB.borderDark}` }}
+ >
+ <ChevronLeft size={12} className="inline" /> BACK
+ </button>
+ <button
+ onClick={runAnalysis}
+ disabled={isLoading || !canRun}
+ className="flex-1 py-2 text-xs font-mono font-bold"
+ style={{
+ backgroundColor: canRun ? BB.green : BB.cardBg,
+ color: canRun ? BB.black : BB.textMuted,
+ cursor: canRun ? 'pointer' : 'not-allowed',
+ }}
+ >
+ {isLoading ? 'RUNNING...' : 'RUN'} <Zap size={12} className="inline ml-1" />
+ </button>
+ </div>
+
+ {error && (
+ <div
+ className="mt-4 p-3 text-xs font-mono"
+ style={{ backgroundColor: `${BB.red}20`, border: `1px solid ${BB.red}`, color: BB.red }}
+ >
+ {error}
+ </div>
+ )}
+ </div>
+
+ {/* Right Panel - Model Details */}
+ <div className="flex-1 p-4" style={{ backgroundColor: BB.darkBg }}>
+ {selectedConfig && (
+ <div className="h-full flex flex-col">
+ <div className="mb-4 p-4" style={{ backgroundColor: BB.cardBg, border: `1px solid ${BB.borderDark}` }}>
+ <div className="flex items-center gap-3 mb-3">
+ <div className="p-2" style={{ backgroundColor: `${selectedConfig.color}20` }}>
+ <selectedConfig.icon size={24} style={{ color: selectedConfig.color }} />
+ </div>
+ <div>
+ <div className="text-sm font-mono font-bold" style={{ color: BB.textPrimary }}>{selectedConfig.name}</div>
+ <div className="text-xs font-mono" style={{ color: BB.textMuted }}>{selectedConfig.category.replace('_', ' ').toUpperCase()}</div>
+ </div>
+ </div>
+ <div className="text-xs font-mono" style={{ color: BB.textSecondary }}>{selectedConfig.helpText}</div>
+
+ <div className="mt-3 flex items-center gap-4 text-xs font-mono">
+ <div>
+ <span style={{ color: BB.textMuted }}>MIN POINTS: </span>
+ <span style={{ color: priceData.length >= selectedConfig.minDataPoints ? BB.green : BB.red }}>
+ {selectedConfig.minDataPoints}
+ </span>
+ </div>
+ <div>
+ <span style={{ color: BB.textMuted }}>YOUR DATA: </span>
+ <span style={{ color: BB.textPrimary }}>{priceData.length}</span>
+ </div>
+ </div>
+ </div>
+
+ {/* Mini Chart Preview */}
+ <div className="flex-1" style={{ minHeight: 200 }}>
+ <div className="flex items-center justify-between mb-2">
+ <div className="text-xs font-mono" style={{ color: BB.textAmber }}>DATA PREVIEW</div>
+ {dataChartZoom && (
+ <button
+ onClick={() => setDataChartZoom(null)}
+ className="text-xs font-mono px-2 py-0.5 flex items-center gap-1"
+ style={{ backgroundColor: BB.cardBg, color: BB.textMuted, border: `1px solid ${BB.borderDark}` }}
+ >
+ <RotateCcw size={10} /> RESET ZOOM
+ </button>
+ )}
+ </div>
+ <ResponsiveContainer width="100%" height="100%">
+ <LineChart data={zoomedChartData} margin={{ top: 5, right: 5, left: 0, bottom: 5 }}>
+ <CartesianGrid strokeDasharray="3 3" stroke={BB.chartGrid} />
+ <XAxis dataKey="index" hide />
+ <YAxis hide domain={['auto', 'auto']} />
+ <Line
+ type="monotone"
+ dataKey="value"
+ stroke={selectedConfig.color}
+ dot={false}
+ strokeWidth={1.5}
+ />
+ </LineChart>
+ </ResponsiveContainer>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/ChartLegend.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/ChartLegend.tsx
new file mode 100644
index 000000000..9ddde45ae
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/ChartLegend.tsx
@@ -0,0 +1,221 @@
+/**
+ * Chart Legend Component
+ * Displays legend for different analysis types
+ */
+
+import React from 'react';
+import { BB, analysisConfigs } from '../constants';
+
+interface ChartLegendProps {
+ selectedAnalysis: string;
+}
+
+export function ChartLegend({ selectedAnalysis }: ChartLegendProps) {
+ const config = analysisConfigs.find(a => a.id === selectedAnalysis);
+
+ if (selectedAnalysis === 'forecasting') {
+ return (
+ <>
+ <div className="flex items-center gap-2">
+ <div className="w-4 h-0.5" style={{ backgroundColor: BB.textSecondary }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>TRAIN DATA</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.amber }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>TEST ACTUAL</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 border-t-2 border-dashed" style={{ borderColor: BB.blueLight }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>ETS LEVEL</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 border-t border-dashed" style={{ borderColor: BB.amber }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>95% CI</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.green }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>FORECAST</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 border-t border-dashed" style={{ borderColor: BB.greenDim }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>FORECAST CI</span>
+ </div>
+ </>
+ );
+ }
+
+ if (selectedAnalysis === 'resampling_methods') {
+ return (
+ <>
+ <div className="flex items-center gap-2">
+ <div className="w-3 h-3" style={{ backgroundColor: BB.green, opacity: 0.7 }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>DISTRIBUTION</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 h-0.5" style={{ backgroundColor: BB.amber }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>MEAN</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 h-3" style={{ backgroundColor: BB.blueLight, opacity: 0.2 }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>95% CI</span>
+ </div>
+ </>
+ );
+ }
+
+ if (selectedAnalysis === 'unsupervised_learning') {
+ return (
+ <>
+ <div className="flex items-center gap-2">
+ <div className="w-4 h-0.5" style={{ backgroundColor: BB.textSecondary }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>PRICE</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 border-t-2 border-dashed" style={{ borderColor: BB.amber }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>BOUNDARY</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.green }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>CLUSTER 0</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.amber }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>CLUSTER 1</span>
+ </div>
+ </>
+ );
+ }
+
+ if (selectedAnalysis === 'supervised_learning') {
+ return (
+ <>
+ <div className="flex items-center gap-2">
+ <div className="w-4 h-0.5" style={{ backgroundColor: BB.textSecondary }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>TRAIN DATA</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.green }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>TEST ACTUAL</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.blueLight }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>PREDICTION</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 border-t border-dashed" style={{ borderColor: BB.amber }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>95% CI</span>
+ </div>
+ </>
+ );
+ }
+
+ if (selectedAnalysis === 'validate_data') {
+ return (
+ <>
+ <div className="flex items-center gap-2">
+ <div className="w-4 h-0.5" style={{ backgroundColor: BB.green }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>NORMAL DATA</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.amber }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>SUSPICIOUS (2-3σ)</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.red }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>OUTLIER (&gt;3σ)</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 border-t-2 border-dashed" style={{ borderColor: BB.blueLight }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>MEAN</span>
+ </div>
+ </>
+ );
+ }
+
+ if (selectedAnalysis === 'stationarity_test') {
+ return (
+ <>
+ <div className="flex items-center gap-2">
+ <div className="w-4 h-0.5" style={{ backgroundColor: BB.textSecondary }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>PRICE</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 h-0.5" style={{ backgroundColor: BB.green }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>ROLLING MEAN</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 border-t-2 border-dashed" style={{ borderColor: BB.amber }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>±2σ BANDS</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 border-t-2 border-dashed" style={{ borderColor: BB.blueLight }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>OVERALL MEAN</span>
+ </div>
+ </>
+ );
+ }
+
+ if (selectedAnalysis === 'trend_analysis') {
+ return (
+ <>
+ <div className="flex items-center gap-2">
+ <div className="w-4 h-0.5" style={{ backgroundColor: BB.textSecondary }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>ACTUAL</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 border-t-2 border-dashed" style={{ borderColor: config?.color || BB.amber }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>TREND</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 border-t border-dashed" style={{ borderColor: BB.amber }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>95% CI</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.green }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>PROJECTION</span>
+ </div>
+ </>
+ );
+ }
+
+ if (selectedAnalysis === 'arima_model') {
+ return (
+ <>
+ <div className="flex items-center gap-2">
+ <div className="w-4 h-0.5" style={{ backgroundColor: BB.textSecondary }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>ACTUAL</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 border-t-2 border-dashed" style={{ borderColor: BB.amber }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>FITTED</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 border-t border-dashed" style={{ borderColor: BB.amber }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>95% CI</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-2 h-2 rounded-full" style={{ backgroundColor: BB.green }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>FORECAST</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 border-t border-dashed" style={{ borderColor: BB.greenDim }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>FORECAST CI</span>
+ </div>
+ </>
+ );
+ }
+
+ // Default legend
+ return (
+ <>
+ <div className="flex items-center gap-2">
+ <div className="w-4 h-0.5" style={{ backgroundColor: BB.textSecondary }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>ACTUAL</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="w-4 h-0.5" style={{ backgroundColor: config?.color, borderStyle: 'dashed', borderWidth: 1, borderColor: config?.color }} />
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>FITTED</span>
+ </div>
+ </>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/DataStep.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/DataStep.tsx
new file mode 100644
index 000000000..d10619163
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/DataStep.tsx
@@ -0,0 +1,353 @@
+/**
+ * Data Step Component
+ * Handles data input and visualization
+ */
+
+import React from 'react';
+import {
+ Database,
+ Calculator,
+ Search,
+ RefreshCw,
+ AlertCircle,
+ ChevronRight,
+} from 'lucide-react';
+import {
+ AreaChart,
+ Area,
+ XAxis,
+ YAxis,
+ CartesianGrid,
+ Tooltip,
+ ResponsiveContainer,
+ ReferenceLine,
+ Brush,
+ ReferenceArea,
+} from 'recharts';
+import { BB } from '../constants';
+import { formatPrice, formatNumber } from '../utils';
+import { ZoomControls } from './ZoomControls';
+import type { DataStepProps } from '../types';
+
+export function DataStep({
+ dataSourceType,
+ setDataSourceType,
+ symbolInput,
+ setSymbolInput,
+ historicalDays,
+ setHistoricalDays,
+ manualData,
+ setManualData,
+ priceData,
+ priceDataLoading,
+ dataStats,
+ error,
+ zoomedChartData,
+ dataChartZoom,
+ setDataChartZoom,
+ fetchSymbolData,
+ setCurrentStep,
+ getDateForIndex,
+ handleWheel,
+ handleMouseDown,
+ handleMouseMove,
+ handleMouseUp,
+ isSelecting,
+ activeChart,
+ refAreaLeft,
+ refAreaRight,
+}: DataStepProps) {
+ return (
+ <div className="flex h-full">
+ {/* Left Panel - Input Controls */}
+ <div
+ className="w-80 flex-shrink-0 p-4 overflow-y-auto"
+ style={{ backgroundColor: BB.panelBg, borderRight: `1px solid ${BB.borderDark}` }}
+ >
+ <div className="mb-4">
+ <div className="text-xs font-mono mb-2" style={{ color: BB.textAmber }}>DATA SOURCE</div>
+ <div className="flex gap-2">
+ <button
+ onClick={() => setDataSourceType('symbol')}
+ className="flex-1 px-3 py-2 text-xs font-mono transition-colors"
+ style={{
+ backgroundColor: dataSourceType === 'symbol' ? BB.amber : BB.cardBg,
+ color: dataSourceType === 'symbol' ? BB.black : BB.textSecondary,
+ border: `1px solid ${dataSourceType === 'symbol' ? BB.amber : BB.borderDark}`,
+ }}
+ >
+ <Database size={14} className="inline mr-2" />
+ MARKET
+ </button>
+ <button
+ onClick={() => setDataSourceType('manual')}
+ className="flex-1 px-3 py-2 text-xs font-mono transition-colors"
+ style={{
+ backgroundColor: dataSourceType === 'manual' ? BB.amber : BB.cardBg,
+ color: dataSourceType === 'manual' ? BB.black : BB.textSecondary,
+ border: `1px solid ${dataSourceType === 'manual' ? BB.amber : BB.borderDark}`,
+ }}
+ >
+ <Calculator size={14} className="inline mr-2" />
+ MANUAL
+ </button>
+ </div>
+ </div>
+
+ {dataSourceType === 'symbol' ? (
+ <div className="space-y-4">
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: BB.textMuted }}>TICKER</label>
+ <input
+ type="text"
+ value={symbolInput}
+ onChange={(e) => setSymbolInput(e.target.value.toUpperCase())}
+ placeholder="AAPL"
+ className="w-full px-3 py-2 text-sm font-mono"
+ style={{
+ backgroundColor: BB.black,
+ color: BB.textPrimary,
+ border: `1px solid ${BB.borderLight}`,
+ }}
+ />
+ </div>
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: BB.textMuted }}>LOOKBACK (DAYS)</label>
+ <input
+ type="number"
+ value={historicalDays}
+ onChange={(e) => setHistoricalDays(parseInt(e.target.value) || 365)}
+ className="w-full px-3 py-2 text-sm font-mono"
+ style={{
+ backgroundColor: BB.black,
+ color: BB.textPrimary,
+ border: `1px solid ${BB.borderLight}`,
+ }}
+ />
+ </div>
+ <button
+ onClick={fetchSymbolData}
+ disabled={priceDataLoading}
+ className="w-full py-2 text-sm font-mono font-bold flex items-center justify-center gap-2"
+ style={{
+ backgroundColor: BB.amber,
+ color: BB.black,
+ opacity: priceDataLoading ? 0.7 : 1,
+ }}
+ >
+ {priceDataLoading ? (
+ <>
+ <RefreshCw size={14} className="animate-spin" />
+ LOADING...
+ </>
+ ) : (
+ <>
+ <Search size={14} />
+ FETCH DATA
+ </>
+ )}
+ </button>
+ </div>
+ ) : (
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: BB.textMuted }}>VALUES (COMMA SEP)</label>
+ <textarea
+ value={manualData}
+ onChange={(e) => setManualData(e.target.value)}
+ placeholder="100, 102, 98, 105..."
+ rows={8}
+ className="w-full px-3 py-2 text-sm font-mono"
+ style={{
+ backgroundColor: BB.black,
+ color: BB.textPrimary,
+ border: `1px solid ${BB.borderLight}`,
+ }}
+ />
+ </div>
+ )}
+
+ {/* Statistics Panel */}
+ {priceData.length > 0 && dataStats && (
+ <div className="mt-4 p-3" style={{ backgroundColor: BB.cardBg, border: `1px solid ${BB.borderDark}` }}>
+ <div className="text-xs font-mono mb-3" style={{ color: BB.textAmber }}>STATISTICS</div>
+ <div className="grid grid-cols-2 gap-2 text-xs font-mono">
+ <div>
+ <div style={{ color: BB.textMuted }}>COUNT</div>
+ <div style={{ color: BB.textPrimary }}>{priceData.length}</div>
+ </div>
+ <div>
+ <div style={{ color: BB.textMuted }}>MEAN</div>
+ <div style={{ color: BB.textPrimary }}>{formatPrice(dataStats.mean)}</div>
+ </div>
+ <div>
+ <div style={{ color: BB.textMuted }}>LOW</div>
+ <div style={{ color: BB.red }}>{formatPrice(dataStats.min)}</div>
+ </div>
+ <div>
+ <div style={{ color: BB.textMuted }}>HIGH</div>
+ <div style={{ color: BB.green }}>{formatPrice(dataStats.max)}</div>
+ </div>
+ <div>
+ <div style={{ color: BB.textMuted }}>STD DEV</div>
+ <div style={{ color: BB.textPrimary }}>{formatNumber(dataStats.std, 2)}</div>
+ </div>
+ <div>
+ <div style={{ color: BB.textMuted }}>CHANGE</div>
+ <div style={{ color: dataStats.changePercent >= 0 ? BB.green : BB.red }}>
+ {dataStats.changePercent >= 0 ? '+' : ''}{dataStats.changePercent.toFixed(2)}%
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {error && (
+ <div
+ className="mt-4 p-3 text-xs font-mono"
+ style={{ backgroundColor: `${BB.red}20`, border: `1px solid ${BB.red}`, color: BB.red }}
+ >
+ <AlertCircle size={14} className="inline mr-2" />
+ {error}
+ </div>
+ )}
+
+ <button
+ onClick={() => setCurrentStep('analysis')}
+ disabled={priceData.length === 0}
+ className="w-full mt-4 py-2 text-sm font-mono font-bold flex items-center justify-center gap-2"
+ style={{
+ backgroundColor: priceData.length > 0 ? BB.green : BB.cardBg,
+ color: priceData.length > 0 ? BB.black : BB.textMuted,
+ cursor: priceData.length > 0 ? 'pointer' : 'not-allowed',
+ }}
+ >
+ CONTINUE <ChevronRight size={14} />
+ </button>
+ </div>
+
+ {/* Right Panel - Chart */}
+ <div className="flex-1 p-4" style={{ backgroundColor: BB.darkBg }}>
+ {priceData.length > 0 ? (
+ <div className="h-full flex flex-col">
+ <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center gap-3">
+ <div className="text-xs font-mono" style={{ color: BB.textAmber }}>PRICE CHART</div>
+ {dataChartZoom && (
+ <div className="text-xs font-mono px-2 py-0.5" style={{ backgroundColor: BB.amber + '20', color: BB.amber }}>
+ {getDateForIndex(dataChartZoom.startIndex)} - {getDateForIndex(dataChartZoom.endIndex)}
+ </div>
+ )}
+ </div>
+ <div className="flex items-center gap-3">
+ <ZoomControls
+ chartType="data"
+ isZoomed={dataChartZoom !== null}
+ onZoomIn={() => {}}
+ onZoomOut={() => {}}
+ onResetZoom={() => setDataChartZoom(null)}
+ onPanLeft={() => {}}
+ onPanRight={() => {}}
+ canPanLeft={dataChartZoom !== null && dataChartZoom.startIndex > 0}
+ canPanRight={dataChartZoom !== null && dataChartZoom.endIndex < priceData.length - 1}
+ />
+ <div className="text-xs font-mono" style={{ color: BB.textMuted }}>{priceData.length} POINTS</div>
+ </div>
+ </div>
+ <div
+ className="flex-1"
+ style={{ minHeight: 300 }}
+ onWheel={(e) => handleWheel(e, 'data')}
+ >
+ <ResponsiveContainer width="100%" height="100%">
+ <AreaChart
+ data={zoomedChartData}
+ margin={{ top: 10, right: 10, left: 0, bottom: 30 }}
+ onMouseDown={(e) => handleMouseDown(e, 'data')}
+ onMouseMove={handleMouseMove}
+ onMouseUp={handleMouseUp}
+ onMouseLeave={handleMouseUp}
+ >
+ <defs>
+ <linearGradient id="colorValue" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor={dataStats && dataStats.changePercent >= 0 ? BB.green : BB.red} stopOpacity={0.3}/>
+ <stop offset="95%" stopColor={dataStats && dataStats.changePercent >= 0 ? BB.green : BB.red} stopOpacity={0}/>
+ </linearGradient>
+ </defs>
+ <CartesianGrid strokeDasharray="3 3" stroke={BB.chartGrid} />
+ <XAxis
+ dataKey="date"
+ tick={{ fill: BB.textMuted, fontSize: 9 }}
+ axisLine={{ stroke: BB.borderDark }}
+ tickLine={{ stroke: BB.borderDark }}
+ interval="preserveStartEnd"
+ />
+ <YAxis
+ tick={{ fill: BB.textMuted, fontSize: 10 }}
+ axisLine={{ stroke: BB.borderDark }}
+ tickLine={{ stroke: BB.borderDark }}
+ domain={['auto', 'auto']}
+ tickFormatter={(val) => formatPrice(val)}
+ />
+ <Tooltip
+ contentStyle={{
+ backgroundColor: BB.cardBg,
+ border: `1px solid ${BB.borderLight}`,
+ borderRadius: 0,
+ }}
+ labelFormatter={(label) => `Date: ${label}`}
+ labelStyle={{ color: BB.textAmber, fontSize: 11, fontWeight: 'bold' }}
+ itemStyle={{ color: BB.textPrimary, fontSize: 12 }}
+ formatter={(value: number) => [formatPrice(value), 'Price']}
+ />
+ <ReferenceLine y={dataStats?.mean} stroke={BB.amber} strokeDasharray="5 5" />
+ <Area
+ type="monotone"
+ dataKey="value"
+ stroke={dataStats && dataStats.changePercent >= 0 ? BB.green : BB.red}
+ fillOpacity={1}
+ fill="url(#colorValue)"
+ strokeWidth={1.5}
+ />
+ {!dataChartZoom && (
+ <Brush
+ dataKey="index"
+ height={20}
+ stroke={BB.amber}
+ fill={BB.cardBg}
+ tickFormatter={(val) => `${val}`}
+ onChange={(e) => {
+ if (e.startIndex !== undefined && e.endIndex !== undefined && e.startIndex !== e.endIndex) {
+ setDataChartZoom({ startIndex: e.startIndex, endIndex: e.endIndex });
+ }
+ }}
+ />
+ )}
+ {isSelecting && activeChart === 'data' && refAreaLeft !== null && refAreaRight !== null && (
+ <ReferenceArea
+ x1={refAreaLeft}
+ x2={refAreaRight}
+ strokeOpacity={0.3}
+ fill={BB.amber}
+ fillOpacity={0.2}
+ />
+ )}
+ </AreaChart>
+ </ResponsiveContainer>
+ </div>
+ <div className="text-xs font-mono mt-1 text-center" style={{ color: BB.textMuted }}>
+ Scroll to pan | Ctrl+Scroll to zoom | Drag to select range
+ </div>
+ </div>
+ ) : (
+ <div className="h-full flex items-center justify-center">
+ <div className="text-center">
+ <Database size={48} style={{ color: BB.textMuted, margin: '0 auto 16px' }} />
+ <div className="text-sm font-mono" style={{ color: BB.textMuted }}>NO DATA LOADED</div>
+ <div className="text-xs font-mono mt-1" style={{ color: BB.textMuted }}>Fetch market data or enter values manually</div>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/Header.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/Header.tsx
new file mode 100644
index 000000000..61abcfb16
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/Header.tsx
@@ -0,0 +1,88 @@
+/**
+ * CFA Quant Header Component
+ * Step navigation and symbol info display
+ */
+
+import React from 'react';
+import { Activity } from 'lucide-react';
+import { BB } from '../constants';
+import { formatPrice } from '../utils';
+import type { HeaderProps, Step } from '../types';
+
+export function Header({
+ currentStep,
+ setCurrentStep,
+ analysisResult,
+ dataSourceType,
+ symbolInput,
+ dataStats,
+}: HeaderProps) {
+ const steps: Step[] = ['data', 'analysis', 'results'];
+ const labels: Record<Step, string> = {
+ data: '1 DATA',
+ analysis: '2 MODEL',
+ results: '3 OUTPUT'
+ };
+
+ return (
+ <div
+ className="flex items-center justify-between px-4 py-2"
+ style={{ backgroundColor: BB.black, borderBottom: `1px solid ${BB.borderDark}` }}
+ >
+ <div className="flex items-center gap-4">
+ <div className="flex items-center gap-2">
+ <Activity size={18} style={{ color: BB.amber }} />
+ <span className="text-sm font-bold tracking-wider" style={{ color: BB.textAmber }}>
+ CFA QUANT ANALYTICS
+ </span>
+ </div>
+ <div className="h-4 w-px" style={{ backgroundColor: BB.borderLight }} />
+ <div className="flex items-center gap-2">
+ {steps.map((step, idx) => {
+ const isActive = currentStep === step;
+ const isPast = steps.indexOf(currentStep) > idx;
+ return (
+ <React.Fragment key={step}>
+ <button
+ onClick={() => {
+ if (step === 'results' && !analysisResult) return;
+ setCurrentStep(step);
+ }}
+ className="px-3 py-1 text-xs font-mono transition-colors"
+ style={{
+ backgroundColor: isActive ? BB.amber : 'transparent',
+ color: isActive ? BB.black : isPast ? BB.textAmber : BB.textMuted,
+ cursor: step === 'results' && !analysisResult ? 'not-allowed' : 'pointer',
+ }}
+ >
+ {labels[step]}
+ </button>
+ {idx < 2 && <span style={{ color: BB.textMuted }}>›</span>}
+ </React.Fragment>
+ );
+ })}
+ </div>
+ </div>
+ {dataSourceType === 'symbol' && symbolInput && (
+ <div className="flex items-center gap-3">
+ <span className="text-sm font-mono font-bold" style={{ color: BB.textPrimary }}>
+ {symbolInput.toUpperCase()}
+ </span>
+ {dataStats && (
+ <>
+ <span className="text-sm font-mono" style={{ color: BB.textSecondary }}>
+ {formatPrice(dataStats.mean)}
+ </span>
+ <span
+ className="text-sm font-mono"
+ style={{ color: dataStats.changePercent >= 0 ? BB.green : BB.red }}
+ >
+ {dataStats.changePercent >= 0 ? '▲' : '▼'} {Math.abs(dataStats.changePercent).toFixed(2)}%
+ </span>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/ResultsStep.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/ResultsStep.tsx
new file mode 100644
index 000000000..75c86aa1b
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/ResultsStep.tsx
@@ -0,0 +1,440 @@
+/**
+ * Results Step Component
+ * Displays analysis results with charts and metrics
+ */
+
+import React, { useMemo } from 'react';
+import {
+ CheckCircle2,
+ ChevronLeft,
+ Play,
+ Copy,
+ Download,
+} from 'lucide-react';
+import {
+ ComposedChart,
+ Line,
+ Bar,
+ Scatter,
+ XAxis,
+ YAxis,
+ CartesianGrid,
+ Tooltip,
+ ResponsiveContainer,
+ ReferenceLine,
+ ReferenceArea,
+ Brush,
+} from 'recharts';
+import { BB, analysisConfigs } from '../constants';
+import { formatNumber, formatPrice, extractKeyMetrics, buildResultChartData } from '../utils';
+import { ZoomControls } from './ZoomControls';
+import { ChartLegend } from './ChartLegend';
+import type { ResultsStepProps } from '../types';
+
+export function ResultsStep({
+ analysisResult,
+ selectedAnalysis,
+ symbolInput,
+ priceData,
+ chartData,
+ setCurrentStep,
+ setAnalysisResult,
+ resultsChartZoom,
+ setResultsChartZoom,
+ getDateForIndex,
+ handleWheel,
+ handleMouseDown,
+ handleMouseMove,
+ handleMouseUp,
+ isSelecting,
+ activeChart,
+ refAreaLeft,
+ refAreaRight,
+}: ResultsStepProps) {
+ if (!analysisResult?.result) return null;
+
+ const config = analysisConfigs.find(a => a.id === selectedAnalysis);
+ const result = analysisResult.result as Record<string, unknown>;
+
+ const keyMetrics = useMemo(() =>
+ extractKeyMetrics(selectedAnalysis, result, priceData),
+ [selectedAnalysis, result, priceData]
+ );
+
+ const resultChartData = useMemo(() =>
+ buildResultChartData(selectedAnalysis, result, chartData, priceData),
+ [selectedAnalysis, result, chartData, priceData]
+ );
+
+ // Compute cluster boundary for unsupervised learning
+ const clusterBoundary = useMemo(() => {
+ if (selectedAnalysis !== 'unsupervised_learning') return null;
+ const value = result.value as Record<string, Record<string, unknown>>;
+ if (value?.kmeans) {
+ const clusterLabels = value.kmeans.cluster_labels as number[];
+ if (clusterLabels && clusterLabels.length > 0 && priceData.length > 0) {
+ const clusterSums: Record<number, { sum: number; count: number }> = {};
+ priceData.forEach((price, i) => {
+ const cluster = i < clusterLabels.length ? clusterLabels[i] : 0;
+ if (!clusterSums[cluster]) clusterSums[cluster] = { sum: 0, count: 0 };
+ clusterSums[cluster].sum += price;
+ clusterSums[cluster].count += 1;
+ });
+ const means = Object.values(clusterSums).map(s => s.sum / s.count).sort((a, b) => a - b);
+ if (means.length >= 2) {
+ return (means[0] + means[1]) / 2;
+ }
+ }
+ }
+ return null;
+ }, [selectedAnalysis, result, priceData]);
+
+ // Bootstrap reference values
+ const bootstrapRefs = useMemo(() => {
+ if (selectedAnalysis !== 'resampling_methods') return null;
+ const value = result.value as Record<string, Record<string, unknown>>;
+ if (value?.bootstrap) {
+ const mean = value.bootstrap.mean as number;
+ const ci = value.bootstrap.confidence_interval as [number, number];
+ if (resultChartData.length > 0 && (resultChartData[0] as any)?.meanBinIdx !== undefined) {
+ return {
+ mean,
+ ciLow: ci?.[0],
+ ciHigh: ci?.[1],
+ meanIdx: (resultChartData[0] as any).meanBinIdx as number,
+ ciLowIdx: (resultChartData[0] as any).ciLowIdx as number,
+ ciHighIdx: (resultChartData[0] as any).ciHighIdx as number,
+ };
+ }
+ }
+ return null;
+ }, [selectedAnalysis, result, resultChartData]);
+
+ const exportResults = () => {
+ if (!analysisResult) return;
+ const content = JSON.stringify(analysisResult, null, 2);
+ const blob = new Blob([content], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `${selectedAnalysis}_${symbolInput}_results.json`;
+ a.click();
+ URL.revokeObjectURL(url);
+ };
+
+ const copyToClipboard = (text: string) => {
+ navigator.clipboard.writeText(text);
+ };
+
+ return (
+ <div className="flex h-full">
+ {/* Left Panel - Metrics */}
+ <div
+ className="w-80 flex-shrink-0 p-4 overflow-y-auto"
+ style={{ backgroundColor: BB.panelBg, borderRight: `1px solid ${BB.borderDark}` }}
+ >
+ <div className="flex items-center justify-between mb-3">
+ <div className="text-xs font-mono" style={{ color: BB.textAmber }}>RESULTS</div>
+ <div className="flex gap-2">
+ <button
+ onClick={() => copyToClipboard(JSON.stringify(analysisResult, null, 2))}
+ className="p-1.5"
+ style={{ backgroundColor: BB.cardBg }}
+ >
+ <Copy size={14} style={{ color: BB.textMuted }} />
+ </button>
+ <button onClick={exportResults} className="p-1.5" style={{ backgroundColor: BB.cardBg }}>
+ <Download size={14} style={{ color: BB.textMuted }} />
+ </button>
+ </div>
+ </div>
+
+ {/* Status Banner */}
+ <div className="p-3 mb-4" style={{ backgroundColor: `${BB.green}10`, border: `1px solid ${BB.green}` }}>
+ <div className="flex items-center gap-2">
+ <CheckCircle2 size={16} style={{ color: BB.green }} />
+ <span className="text-xs font-mono font-bold" style={{ color: BB.green }}>COMPLETE</span>
+ </div>
+ <div className="text-xs font-mono mt-1" style={{ color: BB.textMuted }}>
+ {config?.name} • {analysisResult.timestamp ? new Date(analysisResult.timestamp).toLocaleTimeString() : 'Just now'}
+ </div>
+ </div>
+
+ {/* Key Metrics */}
+ {keyMetrics.length > 0 && (
+ <div className="space-y-2 mb-4">
+ {keyMetrics.map((metric, i) => (
+ <div
+ key={i}
+ className="flex items-center justify-between p-3"
+ style={{ backgroundColor: BB.cardBg, border: `1px solid ${BB.borderDark}` }}
+ >
+ <span className="text-xs font-mono" style={{ color: BB.textMuted }}>{metric.label}</span>
+ <div className="flex items-center gap-2">
+ {metric.icon && <metric.icon size={14} style={{ color: metric.color }} />}
+ <span className="text-sm font-mono font-bold" style={{ color: metric.color }}>{metric.value}</span>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* Raw Data Section */}
+ <div className="mb-4">
+ <div className="text-xs font-mono mb-2" style={{ color: BB.textAmber }}>RAW OUTPUT</div>
+ <div
+ className="p-3 text-xs font-mono overflow-x-auto"
+ style={{ backgroundColor: BB.black, border: `1px solid ${BB.borderDark}`, maxHeight: 200, overflowY: 'auto' }}
+ >
+ {Object.entries(result).map(([key, value]) => {
+ if (key === 'model_summary' || (Array.isArray(value) && value.length > 20)) return null;
+ return (
+ <div key={key} className="flex gap-2 py-1" style={{ borderBottom: `1px solid ${BB.borderDark}` }}>
+ <span style={{ color: BB.textMuted }}>{key}:</span>
+ <span style={{ color: BB.textPrimary }} className="truncate">
+ {typeof value === 'object' ? JSON.stringify(value).substring(0, 50) + '...' : String(value)}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+
+ <div className="flex gap-2">
+ <button
+ onClick={() => setCurrentStep('analysis')}
+ className="flex-1 py-2 text-xs font-mono"
+ style={{ backgroundColor: BB.cardBg, color: BB.textSecondary, border: `1px solid ${BB.borderDark}` }}
+ >
+ <ChevronLeft size={12} className="inline" /> MODELS
+ </button>
+ <button
+ onClick={() => {
+ setCurrentStep('data');
+ setAnalysisResult(null);
+ }}
+ className="flex-1 py-2 text-xs font-mono font-bold"
+ style={{ backgroundColor: BB.amber, color: BB.black }}
+ >
+ NEW <Play size={12} className="inline ml-1" />
+ </button>
+ </div>
+ </div>
+
+ {/* Right Panel - Chart with Results */}
+ <div className="flex-1 p-4" style={{ backgroundColor: BB.darkBg }}>
+ <div className="h-full flex flex-col">
+ <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center gap-3">
+ <div className="text-xs font-mono" style={{ color: BB.textAmber }}>{config?.shortName} OUTPUT</div>
+ {resultsChartZoom && (
+ <div className="text-xs font-mono px-2 py-0.5" style={{ backgroundColor: BB.amber + '20', color: BB.amber }}>
+ {getDateForIndex(resultsChartZoom.startIndex)} - {getDateForIndex(resultsChartZoom.endIndex)}
+ </div>
+ )}
+ </div>
+ <div className="flex items-center gap-3">
+ <ZoomControls
+ chartType="results"
+ isZoomed={resultsChartZoom !== null}
+ onZoomIn={() => {}}
+ onZoomOut={() => {}}
+ onResetZoom={() => setResultsChartZoom(null)}
+ onPanLeft={() => {}}
+ onPanRight={() => {}}
+ canPanLeft={resultsChartZoom !== null && resultsChartZoom.startIndex > 0}
+ canPanRight={resultsChartZoom !== null && resultsChartZoom.endIndex < resultChartData.length - 1}
+ />
+ <div className="text-xs font-mono" style={{ color: BB.textMuted }}>{symbolInput.toUpperCase()}</div>
+ </div>
+ </div>
+ <div
+ className="flex-1"
+ style={{ minHeight: 300 }}
+ onWheel={(e) => handleWheel(e, 'results')}
+ >
+ <ResponsiveContainer width="100%" height="100%">
+ <ComposedChart
+ data={resultsChartZoom ? resultChartData.slice(resultsChartZoom.startIndex, resultsChartZoom.endIndex + 1) : resultChartData}
+ margin={{ top: 10, right: 10, left: 0, bottom: 30 }}
+ onMouseDown={(e) => handleMouseDown(e, 'results')}
+ onMouseMove={handleMouseMove}
+ onMouseUp={handleMouseUp}
+ onMouseLeave={handleMouseUp}
+ >
+ <CartesianGrid strokeDasharray="3 3" stroke={BB.chartGrid} />
+ <XAxis
+ dataKey={selectedAnalysis === 'resampling_methods' ? 'index' : 'date'}
+ tick={{ fill: BB.textMuted, fontSize: 9 }}
+ axisLine={{ stroke: BB.borderDark }}
+ interval="preserveStartEnd"
+ tickFormatter={(val) => {
+ if (selectedAnalysis === 'resampling_methods' && (resultChartData[val] as any)?.binCenter !== undefined) {
+ return formatNumber((resultChartData[val] as any).binCenter as number, 1);
+ }
+ return val;
+ }}
+ />
+ <YAxis
+ tick={{ fill: BB.textMuted, fontSize: 10 }}
+ axisLine={{ stroke: BB.borderDark }}
+ domain={['auto', 'auto']}
+ tickFormatter={(val) => selectedAnalysis === 'resampling_methods' ? String(Math.round(val)) : formatPrice(val)}
+ label={selectedAnalysis === 'resampling_methods' ? { value: 'COUNT', angle: -90, position: 'insideLeft', fill: BB.textMuted, fontSize: 9 } : undefined}
+ />
+ <Tooltip
+ contentStyle={{
+ backgroundColor: BB.cardBg,
+ border: `1px solid ${BB.borderLight}`,
+ borderRadius: 0,
+ fontSize: 11,
+ }}
+ labelFormatter={(label) => selectedAnalysis === 'resampling_methods' ? `Value: ${label}` : `Date: ${label}`}
+ labelStyle={{ color: BB.textAmber, fontWeight: 'bold' }}
+ />
+
+ {/* Render lines based on analysis type */}
+ {selectedAnalysis !== 'forecasting' && selectedAnalysis !== 'unsupervised_learning' &&
+ selectedAnalysis !== 'resampling_methods' && selectedAnalysis !== 'validate_data' &&
+ selectedAnalysis !== 'stationarity_test' && (
+ <Line type="monotone" dataKey="value" stroke={BB.textSecondary} strokeWidth={1} dot={false} name="Actual" />
+ )}
+
+ {selectedAnalysis === 'stationarity_test' && (
+ <>
+ <Line type="monotone" dataKey="value" stroke={BB.textSecondary} strokeWidth={1} dot={false} name="Price" />
+ <Line type="monotone" dataKey="upperBand" stroke={BB.amber} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ <Line type="monotone" dataKey="lowerBand" stroke={BB.amber} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ <Line type="monotone" dataKey="rollingMean" stroke={BB.green} strokeWidth={2} dot={false} connectNulls={false} />
+ {resultChartData.length > 0 && (resultChartData[0] as any).overallMean !== undefined && (
+ <ReferenceLine y={(resultChartData[0] as any).overallMean} stroke={BB.blueLight} strokeWidth={2} strokeDasharray="5 5" />
+ )}
+ </>
+ )}
+
+ {selectedAnalysis === 'validate_data' && (
+ <>
+ <Line type="monotone" dataKey="normalValue" stroke={BB.green} strokeWidth={1.5} dot={false} connectNulls={false} />
+ <Scatter dataKey="suspiciousValue" fill={BB.amber} />
+ <Scatter dataKey="outlierValue" fill={BB.red} />
+ {resultChartData.length > 0 && (resultChartData[0] as any).mean !== undefined && (
+ <ReferenceLine y={(resultChartData[0] as any).mean} stroke={BB.blueLight} strokeWidth={2} strokeDasharray="5 5" />
+ )}
+ </>
+ )}
+
+ {selectedAnalysis === 'resampling_methods' && (
+ <>
+ {bootstrapRefs && (
+ <ReferenceArea x1={bootstrapRefs.ciLowIdx} x2={bootstrapRefs.ciHighIdx} fill={BB.blueLight} fillOpacity={0.15} />
+ )}
+ <Bar dataKey="value" name="Frequency" fill={BB.green} fillOpacity={0.7} />
+ {bootstrapRefs && (
+ <ReferenceLine x={bootstrapRefs.meanIdx} stroke={BB.amber} strokeWidth={2} />
+ )}
+ </>
+ )}
+
+ {selectedAnalysis === 'unsupervised_learning' && (
+ <>
+ {clusterBoundary !== null && (
+ <ReferenceLine y={clusterBoundary} stroke={BB.amber} strokeWidth={2} strokeDasharray="6 3" />
+ )}
+ <Line
+ type="monotone"
+ dataKey="value"
+ stroke={BB.textMuted}
+ strokeWidth={1}
+ strokeOpacity={0.5}
+ dot={(props) => {
+ const p = props as { cx: number; cy: number; payload: { cluster?: number } };
+ if (!p.cx || !p.cy) return <g />;
+ const colors = [BB.green, BB.amber, BB.blueLight, BB.red];
+ const c = p.payload?.cluster ?? 0;
+ return <circle cx={p.cx} cy={p.cy} r={4} fill={colors[c % colors.length]} />;
+ }}
+ />
+ </>
+ )}
+
+ <Line type="monotone" dataKey="trainValue" stroke={BB.textSecondary} dot={false} strokeWidth={1.5} />
+ <Line type="monotone" dataKey="testActual" stroke={BB.amber} dot={{ fill: BB.amber, r: 2 }} strokeWidth={2} />
+ <Line type="monotone" dataKey="forecastLevel" stroke={BB.blueLight} dot={false} strokeWidth={2} strokeDasharray="5 5" />
+
+ {selectedAnalysis === 'forecasting' && (
+ <>
+ <Line type="monotone" dataKey="forecastUpper" stroke={BB.amber} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ <Line type="monotone" dataKey="forecastLower" stroke={BB.amber} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ <Line type="monotone" dataKey="futureForecastUpper" stroke={BB.greenDim} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ <Line type="monotone" dataKey="futureForecastLower" stroke={BB.greenDim} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ </>
+ )}
+
+ {selectedAnalysis === 'trend_analysis' && (
+ <>
+ <Line type="monotone" dataKey="upperBand" stroke={BB.amber} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ <Line type="monotone" dataKey="lowerBand" stroke={BB.amber} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ <Line type="monotone" dataKey="projection" stroke={BB.green} strokeWidth={2} dot={{ fill: BB.green, r: 4 }} connectNulls={false} />
+ <Line type="monotone" dataKey="projectionUpper" stroke={BB.greenDim} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ <Line type="monotone" dataKey="projectionLower" stroke={BB.greenDim} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ </>
+ )}
+
+ <Line type="monotone" dataKey="fitted" stroke={config?.color || BB.amber} dot={false} strokeWidth={2} strokeDasharray="5 5" />
+
+ {selectedAnalysis === 'arima_model' && (
+ <>
+ <Line type="monotone" dataKey="upperBand" stroke={BB.amber} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ <Line type="monotone" dataKey="lowerBand" stroke={BB.amber} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ <Line type="monotone" dataKey="forecast" stroke={BB.green} strokeWidth={2} dot={{ fill: BB.green, r: 4 }} connectNulls={false} />
+ <Line type="monotone" dataKey="forecastUpper" stroke={BB.greenDim} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ <Line type="monotone" dataKey="forecastLower" stroke={BB.greenDim} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ </>
+ )}
+
+ <Line type="monotone" dataKey="forecast" stroke={BB.green} dot={{ fill: BB.green, r: 4 }} strokeWidth={2} />
+
+ {selectedAnalysis === 'supervised_learning' && (
+ <>
+ <Line type="monotone" dataKey="upperBand" stroke={BB.amber} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ <Line type="monotone" dataKey="lowerBand" stroke={BB.amber} strokeWidth={1} strokeDasharray="3 3" dot={false} connectNulls={false} />
+ <Line type="monotone" dataKey="testActual" stroke={BB.green} strokeWidth={2} dot={{ fill: BB.green, r: 3 }} connectNulls={false} />
+ <Line type="monotone" dataKey="prediction" stroke={BB.blueLight} dot={{ fill: BB.blueLight, r: 3 }} strokeWidth={2} connectNulls={false} />
+ </>
+ )}
+
+ {!resultsChartZoom && (
+ <Brush
+ dataKey="index"
+ height={20}
+ stroke={BB.amber}
+ fill={BB.cardBg}
+ onChange={(e) => {
+ if (e.startIndex !== undefined && e.endIndex !== undefined && e.startIndex !== e.endIndex) {
+ setResultsChartZoom({ startIndex: e.startIndex, endIndex: e.endIndex });
+ }
+ }}
+ />
+ )}
+
+ {isSelecting && activeChart === 'results' && refAreaLeft !== null && refAreaRight !== null && (
+ <ReferenceArea x1={refAreaLeft} x2={refAreaRight} strokeOpacity={0.3} fill={BB.amber} fillOpacity={0.2} />
+ )}
+ </ComposedChart>
+ </ResponsiveContainer>
+ </div>
+
+ {/* Legend */}
+ <div className="flex items-center justify-between mt-2 px-2">
+ <div className="flex items-center gap-4 flex-wrap">
+ <ChartLegend selectedAnalysis={selectedAnalysis} />
+ </div>
+ <div className="text-xs font-mono" style={{ color: BB.textMuted }}>
+ Scroll to pan | Ctrl+Scroll to zoom | Drag to select
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/ZoomControls.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/ZoomControls.tsx
new file mode 100644
index 000000000..065b7e14e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/ZoomControls.tsx
@@ -0,0 +1,95 @@
+/**
+ * Zoom Controls Component
+ * Provides zoom and pan controls for charts
+ */
+
+import React from 'react';
+import { ChevronLeft, ChevronRight, ZoomIn, ZoomOut, RotateCcw } from 'lucide-react';
+import { BB } from '../constants';
+import type { ZoomControlsProps } from '../types';
+
+export function ZoomControls({
+ chartType,
+ isZoomed,
+ onZoomIn,
+ onZoomOut,
+ onResetZoom,
+ onPanLeft,
+ onPanRight,
+ canPanLeft,
+ canPanRight,
+}: ZoomControlsProps) {
+ return (
+ <div className="flex items-center gap-1">
+ {/* Pan Left */}
+ <button
+ onClick={() => onPanLeft(chartType)}
+ disabled={!canPanLeft}
+ className="p-1.5 transition-colors hover:opacity-80"
+ style={{
+ backgroundColor: BB.cardBg,
+ border: `1px solid ${BB.borderDark}`,
+ opacity: canPanLeft ? 1 : 0.4,
+ cursor: canPanLeft ? 'pointer' : 'not-allowed'
+ }}
+ title="Pan Left"
+ >
+ <ChevronLeft size={14} style={{ color: canPanLeft ? BB.amber : BB.textSecondary }} />
+ </button>
+ {/* Zoom In */}
+ <button
+ onClick={() => onZoomIn(chartType)}
+ className="p-1.5 transition-colors hover:opacity-80"
+ style={{ backgroundColor: BB.cardBg, border: `1px solid ${BB.borderDark}` }}
+ title="Zoom In"
+ >
+ <ZoomIn size={14} style={{ color: BB.textSecondary }} />
+ </button>
+ {/* Zoom Out */}
+ <button
+ onClick={() => onZoomOut(chartType)}
+ disabled={!isZoomed}
+ className="p-1.5 transition-colors hover:opacity-80"
+ style={{
+ backgroundColor: BB.cardBg,
+ border: `1px solid ${BB.borderDark}`,
+ opacity: isZoomed ? 1 : 0.4,
+ cursor: isZoomed ? 'pointer' : 'not-allowed'
+ }}
+ title="Zoom Out"
+ >
+ <ZoomOut size={14} style={{ color: BB.textSecondary }} />
+ </button>
+ {/* Reset */}
+ <button
+ onClick={() => onResetZoom(chartType)}
+ disabled={!isZoomed}
+ className="p-1.5 transition-colors hover:opacity-80"
+ style={{
+ backgroundColor: BB.cardBg,
+ border: `1px solid ${BB.borderDark}`,
+ opacity: isZoomed ? 1 : 0.4,
+ cursor: isZoomed ? 'pointer' : 'not-allowed'
+ }}
+ title="Reset Zoom"
+ >
+ <RotateCcw size={14} style={{ color: BB.textSecondary }} />
+ </button>
+ {/* Pan Right */}
+ <button
+ onClick={() => onPanRight(chartType)}
+ disabled={!canPanRight}
+ className="p-1.5 transition-colors hover:opacity-80"
+ style={{
+ backgroundColor: BB.cardBg,
+ border: `1px solid ${BB.borderDark}`,
+ opacity: canPanRight ? 1 : 0.4,
+ cursor: canPanRight ? 'pointer' : 'not-allowed'
+ }}
+ title="Pan Right"
+ >
+ <ChevronRight size={14} style={{ color: canPanRight ? BB.amber : BB.textSecondary }} />
+ </button>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/index.ts
new file mode 100644
index 000000000..4a3157da0
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/components/index.ts
@@ -0,0 +1,10 @@
+/**
+ * CFA Quant Components - Barrel Export
+ */
+
+export { ZoomControls } from './ZoomControls';
+export { Header } from './Header';
+export { DataStep } from './DataStep';
+export { AnalysisStep } from './AnalysisStep';
+export { ResultsStep } from './ResultsStep';
+export { ChartLegend } from './ChartLegend';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/constants.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/constants.ts
new file mode 100644
index 000000000..7e6fba639
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/constants.ts
@@ -0,0 +1,144 @@
+/**
+ * CFA Quant Panel Constants
+ * Color palette and analysis configurations
+ */
+
+import {
+ TrendingUp,
+ BarChart3,
+ LineChart,
+ Sparkles,
+ Brain,
+ Target,
+ Shuffle,
+ CheckCircle2,
+} from 'lucide-react';
+import type { AnalysisConfig } from './types';
+
+// Fincept-style color palette
+export const BB = {
+ // Core Fincept colors
+ black: '#000000',
+ darkBg: '#0a0a0a',
+ panelBg: '#121212',
+ cardBg: '#1a1a1a',
+ borderDark: '#2a2a2a',
+ borderLight: '#3a3a3a',
+
+ // Accent colors
+ amber: '#FF8C00',
+ amberLight: '#FFA500',
+ amberDim: '#CC7000',
+
+ // Status colors
+ green: '#00C853',
+ greenDim: '#00A040',
+ red: '#FF3D00',
+ redDim: '#CC3000',
+
+ // Text colors
+ textPrimary: '#FFFFFF',
+ textSecondary: '#B0B0B0',
+ textMuted: '#707070',
+ textAmber: '#FF9500',
+
+ // Chart colors
+ chartLine: '#00D4FF',
+ chartArea: 'rgba(0, 212, 255, 0.1)',
+ chartGrid: '#1f1f1f',
+
+ // Fincept blue
+ blue: '#0066CC',
+ blueLight: '#0088FF',
+};
+
+export const analysisConfigs: AnalysisConfig[] = [
+ {
+ id: 'trend_analysis',
+ name: 'Trend Analysis',
+ shortName: 'TREND',
+ description: 'Detect upward/downward trends',
+ icon: TrendingUp,
+ category: 'time_series',
+ color: BB.green,
+ minDataPoints: 5,
+ helpText: 'Linear regression to identify significant trends in price movements.'
+ },
+ {
+ id: 'stationarity_test',
+ name: 'Stationarity Test',
+ shortName: 'ADF',
+ description: 'Unit root test (ADF)',
+ icon: BarChart3,
+ category: 'time_series',
+ color: BB.blue,
+ minDataPoints: 20,
+ helpText: 'Tests if time series has constant mean/variance. Important for ARIMA modeling.'
+ },
+ {
+ id: 'arima_model',
+ name: 'ARIMA Forecast',
+ shortName: 'ARIMA',
+ description: 'Time series prediction',
+ icon: LineChart,
+ category: 'time_series',
+ color: BB.amber,
+ minDataPoints: 20,
+ helpText: 'AutoRegressive Integrated Moving Average for forecasting.'
+ },
+ {
+ id: 'forecasting',
+ name: 'Exp. Smoothing',
+ shortName: 'ETS',
+ description: 'Simple forecasting',
+ icon: Sparkles,
+ category: 'time_series',
+ color: BB.amberLight,
+ minDataPoints: 10,
+ helpText: 'Exponential smoothing methods for quick predictions.'
+ },
+ {
+ id: 'supervised_learning',
+ name: 'ML Prediction',
+ shortName: 'ML',
+ description: 'Machine learning models',
+ icon: Brain,
+ category: 'machine_learning',
+ color: BB.blueLight,
+ minDataPoints: 30,
+ helpText: 'Compare Ridge, Lasso, Random Forest for predictions.'
+ },
+ {
+ id: 'unsupervised_learning',
+ name: 'Pattern Discovery',
+ shortName: 'PCA/K',
+ description: 'PCA and clustering',
+ icon: Target,
+ category: 'machine_learning',
+ color: BB.amber,
+ minDataPoints: 20,
+ helpText: 'Find hidden patterns with PCA and K-Means clustering.'
+ },
+ {
+ id: 'resampling_methods',
+ name: 'Bootstrap',
+ shortName: 'BOOT',
+ description: 'Confidence intervals',
+ icon: Shuffle,
+ category: 'sampling',
+ color: BB.green,
+ minDataPoints: 10,
+ helpText: 'Bootstrap/jackknife for robust statistical inference.'
+ },
+ {
+ id: 'validate_data',
+ name: 'Data Quality',
+ shortName: 'QA',
+ description: 'Validate data quality',
+ icon: CheckCircle2,
+ category: 'data_quality',
+ color: BB.greenDim,
+ minDataPoints: 5,
+ helpText: 'Check for missing values, outliers, and data issues.'
+ },
+];
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/hooks/index.ts
new file mode 100644
index 000000000..10a2dbbbc
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/hooks/index.ts
@@ -0,0 +1,6 @@
+/**
+ * CFA Quant Hooks - Barrel Export
+ */
+
+export { useChartZoom } from './useChartZoom';
+export { usePriceData } from './usePriceData';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/hooks/useChartZoom.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/hooks/useChartZoom.ts
new file mode 100644
index 000000000..a1f537bcd
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/hooks/useChartZoom.ts
@@ -0,0 +1,235 @@
+/**
+ * CFA Quant Chart Zoom Hook
+ * Handles zoom and pan functionality for charts
+ */
+
+import { useState, useCallback } from 'react';
+import type { ZoomState, QuantAnalyticsResult } from '../types';
+
+interface UseChartZoomProps {
+ priceDataLength: number;
+ analysisResult: QuantAnalyticsResult<Record<string, unknown>> | null;
+ selectedAnalysis: string;
+}
+
+interface UseChartZoomReturn {
+ dataChartZoom: ZoomState | null;
+ setDataChartZoom: (zoom: ZoomState | null) => void;
+ resultsChartZoom: ZoomState | null;
+ setResultsChartZoom: (zoom: ZoomState | null) => void;
+ refAreaLeft: number | null;
+ refAreaRight: number | null;
+ isSelecting: boolean;
+ activeChart: 'data' | 'results' | null;
+ handleZoomIn: (chartType: 'data' | 'results') => void;
+ handleZoomOut: (chartType: 'data' | 'results') => void;
+ handleResetZoom: (chartType: 'data' | 'results') => void;
+ handlePanLeft: (chartType: 'data' | 'results') => void;
+ handlePanRight: (chartType: 'data' | 'results') => void;
+ canPanLeft: (chartType: 'data' | 'results') => boolean;
+ canPanRight: (chartType: 'data' | 'results') => boolean;
+ handleMouseDown: (e: any, chartType: 'data' | 'results') => void;
+ handleMouseMove: (e: any) => void;
+ handleMouseUp: () => void;
+ handleWheel: (e: React.WheelEvent, chartType: 'data' | 'results') => void;
+ getResultChartDataLength: () => number;
+}
+
+export function useChartZoom({
+ priceDataLength,
+ analysisResult,
+ selectedAnalysis,
+}: UseChartZoomProps): UseChartZoomReturn {
+ const [dataChartZoom, setDataChartZoom] = useState<ZoomState | null>(null);
+ const [resultsChartZoom, setResultsChartZoom] = useState<ZoomState | null>(null);
+ const [refAreaLeft, setRefAreaLeft] = useState<number | null>(null);
+ const [refAreaRight, setRefAreaRight] = useState<number | null>(null);
+ const [isSelecting, setIsSelecting] = useState(false);
+ const [activeChart, setActiveChart] = useState<'data' | 'results' | null>(null);
+
+ const getResultChartDataLength = useCallback(() => {
+ if (!analysisResult?.result) return priceDataLength;
+ if (selectedAnalysis === 'forecasting') {
+ const forecasts = (analysisResult.result as Record<string, unknown>).value as number[];
+ return priceDataLength + (forecasts?.length || 0);
+ }
+ if (selectedAnalysis === 'trend_analysis') {
+ return priceDataLength + 5;
+ }
+ if (selectedAnalysis === 'arima_model') {
+ const result = analysisResult.result as Record<string, unknown>;
+ const value = result.value as Record<string, unknown>;
+ const forecasts = value?.forecasts as number[];
+ return priceDataLength + (forecasts?.length || 5);
+ }
+ return priceDataLength;
+ }, [analysisResult, priceDataLength, selectedAnalysis]);
+
+ const handleZoomIn = useCallback((chartType: 'data' | 'results') => {
+ const currentZoom = chartType === 'data' ? dataChartZoom : resultsChartZoom;
+ const setZoom = chartType === 'data' ? setDataChartZoom : setResultsChartZoom;
+ const dataLength = chartType === 'results' ? getResultChartDataLength() : priceDataLength;
+
+ if (dataLength <= 5) return;
+
+ const currentStart = currentZoom?.startIndex ?? 0;
+ const currentEnd = currentZoom?.endIndex ?? dataLength - 1;
+ const range = currentEnd - currentStart;
+ const center = Math.floor((currentStart + currentEnd) / 2);
+ const newRange = Math.max(5, Math.floor(range * 0.7));
+ const newStart = Math.max(0, center - Math.floor(newRange / 2));
+ const newEnd = Math.min(dataLength - 1, newStart + newRange);
+
+ setZoom({ startIndex: newStart, endIndex: newEnd });
+ }, [priceDataLength, dataChartZoom, resultsChartZoom, getResultChartDataLength]);
+
+ const handleZoomOut = useCallback((chartType: 'data' | 'results') => {
+ const currentZoom = chartType === 'data' ? dataChartZoom : resultsChartZoom;
+ const setZoom = chartType === 'data' ? setDataChartZoom : setResultsChartZoom;
+ const dataLength = chartType === 'results' ? getResultChartDataLength() : priceDataLength;
+
+ if (!currentZoom) return;
+
+ const currentStart = currentZoom.startIndex;
+ const currentEnd = currentZoom.endIndex;
+ const range = currentEnd - currentStart;
+ const center = Math.floor((currentStart + currentEnd) / 2);
+ const newRange = Math.min(dataLength - 1, Math.floor(range * 1.5));
+ const newStart = Math.max(0, center - Math.floor(newRange / 2));
+ const newEnd = Math.min(dataLength - 1, newStart + newRange);
+
+ if (newStart === 0 && newEnd === dataLength - 1) {
+ setZoom(null);
+ } else {
+ setZoom({ startIndex: newStart, endIndex: newEnd });
+ }
+ }, [priceDataLength, dataChartZoom, resultsChartZoom, getResultChartDataLength]);
+
+ const handleResetZoom = useCallback((chartType: 'data' | 'results') => {
+ const setZoom = chartType === 'data' ? setDataChartZoom : setResultsChartZoom;
+ setZoom(null);
+ }, []);
+
+ const handlePanLeft = useCallback((chartType: 'data' | 'results') => {
+ const currentZoom = chartType === 'data' ? dataChartZoom : resultsChartZoom;
+ const setZoom = chartType === 'data' ? setDataChartZoom : setResultsChartZoom;
+
+ if (!currentZoom) return;
+
+ const range = currentZoom.endIndex - currentZoom.startIndex;
+ const step = Math.max(1, Math.floor(range * 0.2));
+ const newStart = Math.max(0, currentZoom.startIndex - step);
+ const newEnd = newStart + range;
+
+ setZoom({ startIndex: newStart, endIndex: newEnd });
+ }, [dataChartZoom, resultsChartZoom]);
+
+ const handlePanRight = useCallback((chartType: 'data' | 'results') => {
+ const currentZoom = chartType === 'data' ? dataChartZoom : resultsChartZoom;
+ const setZoom = chartType === 'data' ? setDataChartZoom : setResultsChartZoom;
+ const dataLength = chartType === 'results' ? getResultChartDataLength() : priceDataLength;
+
+ if (!currentZoom) return;
+
+ const range = currentZoom.endIndex - currentZoom.startIndex;
+ const step = Math.max(1, Math.floor(range * 0.2));
+ const newEnd = Math.min(dataLength - 1, currentZoom.endIndex + step);
+ const newStart = newEnd - range;
+
+ setZoom({ startIndex: Math.max(0, newStart), endIndex: newEnd });
+ }, [dataChartZoom, resultsChartZoom, priceDataLength, getResultChartDataLength]);
+
+ const canPanLeft = useCallback((chartType: 'data' | 'results') => {
+ const currentZoom = chartType === 'data' ? dataChartZoom : resultsChartZoom;
+ return currentZoom !== null && currentZoom.startIndex > 0;
+ }, [dataChartZoom, resultsChartZoom]);
+
+ const canPanRight = useCallback((chartType: 'data' | 'results') => {
+ const currentZoom = chartType === 'data' ? dataChartZoom : resultsChartZoom;
+ const dataLength = chartType === 'results' ? getResultChartDataLength() : priceDataLength;
+ return currentZoom !== null && currentZoom.endIndex < dataLength - 1;
+ }, [dataChartZoom, resultsChartZoom, priceDataLength, getResultChartDataLength]);
+
+ const handleMouseDown = useCallback((e: any, chartType: 'data' | 'results') => {
+ const activeLabel = typeof e.activeLabel === 'string' ? parseInt(e.activeLabel, 10) : e.activeLabel;
+ if (activeLabel !== undefined && !isNaN(activeLabel)) {
+ setRefAreaLeft(activeLabel);
+ setIsSelecting(true);
+ setActiveChart(chartType);
+ }
+ }, []);
+
+ const handleMouseMove = useCallback((e: any) => {
+ const activeLabel = typeof e.activeLabel === 'string' ? parseInt(e.activeLabel, 10) : e.activeLabel;
+ if (isSelecting && activeLabel !== undefined && !isNaN(activeLabel)) {
+ setRefAreaRight(activeLabel);
+ }
+ }, [isSelecting]);
+
+ const handleMouseUp = useCallback(() => {
+ if (refAreaLeft !== null && refAreaRight !== null && activeChart) {
+ const left = Math.min(refAreaLeft, refAreaRight);
+ const right = Math.max(refAreaLeft, refAreaRight);
+
+ if (right - left >= 2) {
+ const setZoom = activeChart === 'data' ? setDataChartZoom : setResultsChartZoom;
+ setZoom({ startIndex: left, endIndex: right });
+ }
+ }
+ setRefAreaLeft(null);
+ setRefAreaRight(null);
+ setIsSelecting(false);
+ setActiveChart(null);
+ }, [refAreaLeft, refAreaRight, activeChart]);
+
+ const handleWheel = useCallback((e: React.WheelEvent, chartType: 'data' | 'results') => {
+ e.preventDefault();
+
+ if (e.shiftKey) {
+ if (e.deltaY > 0) {
+ handlePanRight(chartType);
+ } else if (e.deltaY < 0) {
+ handlePanLeft(chartType);
+ }
+ return;
+ }
+
+ if (e.ctrlKey || e.metaKey) {
+ if (e.deltaY < 0) {
+ handleZoomIn(chartType);
+ } else if (e.deltaY > 0) {
+ handleZoomOut(chartType);
+ }
+ return;
+ }
+
+ if (e.deltaY > 0) {
+ handlePanRight(chartType);
+ } else if (e.deltaY < 0) {
+ handlePanLeft(chartType);
+ }
+ }, [handlePanLeft, handlePanRight, handleZoomIn, handleZoomOut]);
+
+ return {
+ dataChartZoom,
+ setDataChartZoom,
+ resultsChartZoom,
+ setResultsChartZoom,
+ refAreaLeft,
+ refAreaRight,
+ isSelecting,
+ activeChart,
+ handleZoomIn,
+ handleZoomOut,
+ handleResetZoom,
+ handlePanLeft,
+ handlePanRight,
+ canPanLeft,
+ canPanRight,
+ handleMouseDown,
+ handleMouseMove,
+ handleMouseUp,
+ handleWheel,
+ getResultChartDataLength,
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/hooks/usePriceData.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/hooks/usePriceData.ts
new file mode 100644
index 000000000..c2fa5ffd8
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/hooks/usePriceData.ts
@@ -0,0 +1,128 @@
+/**
+ * CFA Quant Price Data Hook
+ * Handles fetching and managing price data
+ */
+
+import { useState, useCallback, useEffect, useMemo } from 'react';
+import { yfinanceService } from '@/services/markets/yfinanceService';
+import { calculateStats } from '../utils';
+import type { DataStats, DataSourceType, ChartDataPoint } from '../types';
+
+interface UsePriceDataProps {
+ dataSourceType: DataSourceType;
+ manualData: string;
+}
+
+interface UsePriceDataReturn {
+ priceData: number[];
+ setPriceData: (data: number[]) => void;
+ priceDates: string[];
+ setPriceDates: (dates: string[]) => void;
+ priceDataLoading: boolean;
+ dataStats: DataStats | null;
+ setDataStats: (stats: DataStats | null) => void;
+ chartData: ChartDataPoint[];
+ fetchSymbolData: (symbol: string, days: number) => Promise<void>;
+ error: string | null;
+ setError: (error: string | null) => void;
+ getDataArray: (symbolPriceData: number[], manualData: string, dataSourceType: DataSourceType) => number[];
+ getDateForIndex: (index: number) => string;
+}
+
+export function usePriceData({
+ dataSourceType,
+ manualData,
+}: UsePriceDataProps): UsePriceDataReturn {
+ const [priceData, setPriceData] = useState<number[]>([]);
+ const [priceDates, setPriceDates] = useState<string[]>([]);
+ const [priceDataLoading, setPriceDataLoading] = useState(false);
+ const [dataStats, setDataStats] = useState<DataStats | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const chartData = useMemo(() => {
+ return priceData.map((value, index) => ({
+ index,
+ value,
+ date: priceDates[index] || `Day ${index + 1}`,
+ }));
+ }, [priceData, priceDates]);
+
+ const fetchSymbolData = useCallback(async (symbol: string, days: number) => {
+ if (!symbol.trim()) return;
+
+ setPriceDataLoading(true);
+ setError(null);
+
+ try {
+ const endDate = new Date();
+ const startDate = new Date();
+ startDate.setDate(startDate.getDate() - days);
+
+ const data = await yfinanceService.getHistoricalData(
+ symbol.toUpperCase(),
+ startDate.toISOString().split('T')[0],
+ endDate.toISOString().split('T')[0]
+ );
+
+ if (data && data.length > 0) {
+ const closes = data.map(d => d.close);
+ const dates = data.map(d => {
+ const date = new Date(d.timestamp);
+ return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: '2-digit' });
+ });
+ setPriceData(closes);
+ setPriceDates(dates);
+ setDataStats(calculateStats(closes));
+ } else {
+ setError('No data returned for symbol');
+ }
+ } catch (err) {
+ setError(`Failed to fetch data: ${err}`);
+ } finally {
+ setPriceDataLoading(false);
+ }
+ }, []);
+
+ // Handle manual data parsing
+ useEffect(() => {
+ if (dataSourceType === 'manual' && manualData) {
+ const parsed = manualData.split(',').map(v => parseFloat(v.trim())).filter(v => !isNaN(v));
+ setPriceData(parsed);
+ setDataStats(calculateStats(parsed));
+ }
+ }, [manualData, dataSourceType]);
+
+ const getDataArray = useCallback((
+ symbolPriceData: number[],
+ manualDataStr: string,
+ sourceType: DataSourceType
+ ): number[] => {
+ if (sourceType === 'manual') {
+ return manualDataStr.split(',').map(v => parseFloat(v.trim())).filter(v => !isNaN(v));
+ }
+ return symbolPriceData;
+ }, []);
+
+ const getDateForIndex = useCallback((index: number): string => {
+ if (index >= 0 && index < priceDates.length) {
+ return priceDates[index];
+ }
+ return `Day ${index + 1}`;
+ }, [priceDates]);
+
+ return {
+ priceData,
+ setPriceData,
+ priceDates,
+ setPriceDates,
+ priceDataLoading,
+ dataStats,
+ setDataStats,
+ chartData,
+ fetchSymbolData,
+ error,
+ setError,
+ getDataArray,
+ getDateForIndex,
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/index.ts
new file mode 100644
index 000000000..bcc40a587
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/index.ts
@@ -0,0 +1,20 @@
+/**
+ * CFA Quant Panel - Barrel Export
+ *
+ * This module provides CFA-level quantitative analytics capabilities.
+ *
+ * The component has been refactored into smaller, maintainable pieces:
+ * - CFAQuantPanel.tsx - Main component
+ * - components/ - UI components
+ * - hooks/ - Custom React hooks
+ * - utils/ - Utility functions
+ * - constants.ts - Configuration and color palette
+ * - types.ts - TypeScript definitions
+ */
+
+export { CFAQuantPanel, default } from './CFAQuantPanel';
+export { BB, analysisConfigs } from './constants';
+export * from './types';
+export * from './hooks';
+export * from './utils';
+export * from './components';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/types.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/types.ts
new file mode 100644
index 000000000..c8aa89df1
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/types.ts
@@ -0,0 +1,139 @@
+/**
+ * CFA Quant Panel Types
+ * TypeScript interfaces and types
+ */
+
+import type { QuantAnalyticsResult } from '@/services/aiQuantLab/quantAnalyticsService';
+
+export type Step = 'data' | 'analysis' | 'results';
+export type DataSourceType = 'symbol' | 'manual';
+
+export interface AnalysisConfig {
+ id: string;
+ name: string;
+ shortName: string;
+ description: string;
+ icon: React.ElementType;
+ category: 'time_series' | 'machine_learning' | 'sampling' | 'data_quality';
+ color: string;
+ minDataPoints: number;
+ helpText: string;
+}
+
+export interface DataStats {
+ min: number;
+ max: number;
+ mean: number;
+ std: number;
+ change: number;
+ changePercent: number;
+}
+
+export interface ChartDataPoint {
+ index: number;
+ value: number;
+ date: string;
+}
+
+export interface ZoomState {
+ startIndex: number;
+ endIndex: number;
+}
+
+export interface KeyMetric {
+ label: string;
+ value: string;
+ color: string;
+ icon?: React.ElementType;
+}
+
+// Re-export from service
+export type { QuantAnalyticsResult };
+
+// Props interfaces for components
+export interface DataStepProps {
+ dataSourceType: DataSourceType;
+ setDataSourceType: (type: DataSourceType) => void;
+ symbolInput: string;
+ setSymbolInput: (value: string) => void;
+ historicalDays: number;
+ setHistoricalDays: (value: number) => void;
+ manualData: string;
+ setManualData: (value: string) => void;
+ priceData: number[];
+ priceDates: string[];
+ priceDataLoading: boolean;
+ dataStats: DataStats | null;
+ error: string | null;
+ chartData: ChartDataPoint[];
+ zoomedChartData: ChartDataPoint[];
+ dataChartZoom: ZoomState | null;
+ setDataChartZoom: (zoom: ZoomState | null) => void;
+ fetchSymbolData: () => Promise<void>;
+ setCurrentStep: (step: Step) => void;
+ getDateForIndex: (index: number) => string;
+ handleWheel: (e: React.WheelEvent, chartType: 'data' | 'results') => void;
+ handleMouseDown: (e: any, chartType: 'data' | 'results') => void;
+ handleMouseMove: (e: any) => void;
+ handleMouseUp: () => void;
+ isSelecting: boolean;
+ activeChart: 'data' | 'results' | null;
+ refAreaLeft: number | null;
+ refAreaRight: number | null;
+}
+
+export interface AnalysisStepProps {
+ selectedAnalysis: string;
+ setSelectedAnalysis: (id: string) => void;
+ priceData: number[];
+ isLoading: boolean;
+ error: string | null;
+ runAnalysis: () => Promise<void>;
+ setCurrentStep: (step: Step) => void;
+ zoomedChartData: ChartDataPoint[];
+ dataChartZoom: ZoomState | null;
+ setDataChartZoom: (zoom: ZoomState | null) => void;
+}
+
+export interface ResultsStepProps {
+ analysisResult: QuantAnalyticsResult<Record<string, unknown>> | null;
+ selectedAnalysis: string;
+ symbolInput: string;
+ priceData: number[];
+ priceDates: string[];
+ chartData: ChartDataPoint[];
+ setCurrentStep: (step: Step) => void;
+ setAnalysisResult: (result: QuantAnalyticsResult<Record<string, unknown>> | null) => void;
+ resultsChartZoom: ZoomState | null;
+ setResultsChartZoom: (zoom: ZoomState | null) => void;
+ getDateForIndex: (index: number) => string;
+ handleWheel: (e: React.WheelEvent, chartType: 'data' | 'results') => void;
+ handleMouseDown: (e: any, chartType: 'data' | 'results') => void;
+ handleMouseMove: (e: any) => void;
+ handleMouseUp: () => void;
+ isSelecting: boolean;
+ activeChart: 'data' | 'results' | null;
+ refAreaLeft: number | null;
+ refAreaRight: number | null;
+}
+
+export interface ZoomControlsProps {
+ chartType: 'data' | 'results';
+ isZoomed: boolean;
+ onZoomIn: (chartType: 'data' | 'results') => void;
+ onZoomOut: (chartType: 'data' | 'results') => void;
+ onResetZoom: (chartType: 'data' | 'results') => void;
+ onPanLeft: (chartType: 'data' | 'results') => void;
+ onPanRight: (chartType: 'data' | 'results') => void;
+ canPanLeft: boolean;
+ canPanRight: boolean;
+}
+
+export interface HeaderProps {
+ currentStep: Step;
+ setCurrentStep: (step: Step) => void;
+ analysisResult: QuantAnalyticsResult<Record<string, unknown>> | null;
+ dataSourceType: DataSourceType;
+ symbolInput: string;
+ dataStats: DataStats | null;
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/utils/calculations.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/utils/calculations.ts
new file mode 100644
index 000000000..1594636de
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/utils/calculations.ts
@@ -0,0 +1,104 @@
+/**
+ * CFA Quant Calculation Utilities
+ */
+
+import type { DataStats } from '../types';
+
+export const calculateStats = (data: number[]): DataStats | null => {
+ if (data.length === 0) return null;
+ const mean = data.reduce((a, b) => a + b, 0) / data.length;
+ const variance = data.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / data.length;
+ const first = data[0];
+ const last = data[data.length - 1];
+ const change = last - first;
+ const changePercent = (change / first) * 100;
+ return {
+ min: Math.min(...data),
+ max: Math.max(...data),
+ mean,
+ std: Math.sqrt(variance),
+ change,
+ changePercent,
+ };
+};
+
+export const calculateRollingStats = (
+ data: number[],
+ windowSize: number
+): {
+ rollingMean: (number | null)[];
+ rollingStd: (number | null)[];
+ upperBand: (number | null)[];
+ lowerBand: (number | null)[];
+} => {
+ const rollingMean: (number | null)[] = [];
+ const rollingStd: (number | null)[] = [];
+ const upperBand: (number | null)[] = [];
+ const lowerBand: (number | null)[] = [];
+
+ for (let i = 0; i < data.length; i++) {
+ if (i < windowSize - 1) {
+ rollingMean.push(null);
+ rollingStd.push(null);
+ upperBand.push(null);
+ lowerBand.push(null);
+ } else {
+ const windowData = data.slice(i - windowSize + 1, i + 1);
+ const mean = windowData.reduce((a, b) => a + b, 0) / windowData.length;
+ const variance = windowData.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / windowData.length;
+ const std = Math.sqrt(variance);
+
+ rollingMean.push(mean);
+ rollingStd.push(std);
+ upperBand.push(mean + 2 * std);
+ lowerBand.push(mean - 2 * std);
+ }
+ }
+
+ return { rollingMean, rollingStd, upperBand, lowerBand };
+};
+
+export const calculateZScores = (
+ data: number[]
+): { zScores: number[]; mean: number; std: number } => {
+ if (data.length < 3) return { zScores: [], mean: 0, std: 0 };
+
+ const mean = data.reduce((a, b) => a + b, 0) / data.length;
+ const variance = data.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / data.length;
+ const std = Math.sqrt(variance);
+
+ const zScores = data.map(value => std > 0 ? Math.abs((value - mean) / std) : 0);
+
+ return { zScores, mean, std };
+};
+
+export const createHistogramBins = (
+ data: number[],
+ binCount: number
+): { binCenter: number; count: number; frequency: number }[] => {
+ if (data.length === 0) return [];
+
+ const sortedData = [...data].sort((a, b) => a - b);
+ const min = sortedData[0];
+ const max = sortedData[sortedData.length - 1];
+ const binWidth = (max - min) / binCount;
+
+ const bins: { binCenter: number; count: number; frequency: number }[] = [];
+
+ for (let i = 0; i < binCount; i++) {
+ const binStart = min + i * binWidth;
+ const binEnd = binStart + binWidth;
+ const binCenter = (binStart + binEnd) / 2;
+ const count = sortedData.filter(v =>
+ v >= binStart && (i === binCount - 1 ? v <= binEnd : v < binEnd)
+ ).length;
+
+ bins.push({
+ binCenter,
+ count,
+ frequency: count / sortedData.length,
+ });
+ }
+
+ return bins;
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/utils/chartDataBuilder.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/utils/chartDataBuilder.ts
new file mode 100644
index 000000000..e5015e14a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/utils/chartDataBuilder.ts
@@ -0,0 +1,416 @@
+/**
+ * Chart Data Builder Utilities
+ * Builds chart data for different analysis types
+ */
+
+import type { ChartDataPoint } from '../types';
+import { calculateRollingStats, calculateZScores, createHistogramBins } from './calculations';
+import { formatNumber } from './formatters';
+
+export function buildResultChartData(
+ selectedAnalysis: string,
+ result: Record<string, unknown>,
+ chartData: ChartDataPoint[],
+ priceData: number[]
+): any[] {
+ if (selectedAnalysis === 'trend_analysis') {
+ return buildTrendAnalysisChartData(result, chartData, priceData);
+ } else if (selectedAnalysis === 'stationarity_test') {
+ return buildStationarityChartData(chartData, priceData);
+ } else if (selectedAnalysis === 'arima_model') {
+ return buildArimaChartData(result, chartData, priceData);
+ } else if (selectedAnalysis === 'forecasting') {
+ return buildForecastingChartData(result, chartData, priceData);
+ } else if (selectedAnalysis === 'supervised_learning') {
+ return buildSupervisedLearningChartData(result, chartData, priceData);
+ } else if (selectedAnalysis === 'unsupervised_learning') {
+ return buildUnsupervisedLearningChartData(result, chartData);
+ } else if (selectedAnalysis === 'resampling_methods') {
+ return buildResamplingChartData(result, chartData);
+ } else if (selectedAnalysis === 'validate_data') {
+ return buildValidateDataChartData(chartData, priceData);
+ }
+ return chartData;
+}
+
+function buildTrendAnalysisChartData(
+ result: Record<string, unknown>,
+ chartData: ChartDataPoint[],
+ priceData: number[]
+): any[] {
+ const meta = result.metadata as Record<string, unknown>;
+ const value = result.value as Record<string, unknown>;
+ const fitted = meta?.fitted_values as number[];
+ const residuals = meta?.residuals as number[];
+ const slope = value?.slope as number;
+ const intercept = value?.intercept as number;
+
+ if (fitted && fitted.length > 0) {
+ const n = priceData.length;
+ const residualsArr = residuals || priceData.map((v, i) => v - fitted[i]);
+ const mse = residualsArr.reduce((sum, r) => sum + r * r, 0) / (n - 2);
+ const se = Math.sqrt(mse);
+ const meanX = (n - 1) / 2;
+ const sumXX = Array.from({ length: n }, (_, i) => Math.pow(i - meanX, 2)).reduce((a, b) => a + b, 0);
+
+ const enhancedData = chartData.map((d, i) => {
+ const sePred = se * Math.sqrt(1 + 1/n + Math.pow(i - meanX, 2) / sumXX);
+ const ciWidth = 1.96 * sePred;
+
+ return {
+ ...d,
+ fitted: fitted[i],
+ residual: residualsArr[i],
+ upperBand: fitted[i] + ciWidth,
+ lowerBand: fitted[i] - ciWidth,
+ };
+ });
+
+ if (slope !== undefined && intercept !== undefined) {
+ const projectionPeriods = 5;
+ for (let i = 0; i < projectionPeriods; i++) {
+ const futureIndex = n + i;
+ const projectedValue = intercept + slope * futureIndex;
+ const sePred = se * Math.sqrt(1 + 1/n + Math.pow(futureIndex - meanX, 2) / sumXX);
+ const ciWidth = 1.96 * sePred;
+
+ enhancedData.push({
+ index: futureIndex,
+ value: null as unknown as number,
+ date: `+${i + 1}d`,
+ fitted: null as unknown as number,
+ residual: null as unknown as number,
+ upperBand: null as unknown as number,
+ lowerBand: null as unknown as number,
+ projection: projectedValue,
+ projectionUpper: projectedValue + ciWidth,
+ projectionLower: projectedValue - ciWidth,
+ } as any);
+ }
+ }
+
+ return enhancedData;
+ }
+ return chartData;
+}
+
+function buildStationarityChartData(
+ chartData: ChartDataPoint[],
+ priceData: number[]
+): any[] {
+ const windowSize = Math.min(20, Math.floor(priceData.length / 4));
+ if (windowSize < 2) return chartData;
+
+ const { rollingMean, upperBand, lowerBand } = calculateRollingStats(priceData, windowSize);
+ const overallMean = priceData.reduce((a, b) => a + b, 0) / priceData.length;
+
+ return chartData.map((d, i) => ({
+ ...d,
+ rollingMean: rollingMean[i],
+ upperBand: upperBand[i],
+ lowerBand: lowerBand[i],
+ overallMean,
+ }));
+}
+
+function buildArimaChartData(
+ result: Record<string, unknown>,
+ chartData: ChartDataPoint[],
+ priceData: number[]
+): any[] {
+ const value = result.value as Record<string, unknown>;
+ const fitted = value?.fitted_values as number[];
+ const residuals = value?.residuals as number[];
+ const forecasts = value?.forecasts as number[];
+ const forecastCI = value?.forecast_confidence_interval as { lower: number[]; upper: number[] };
+
+ if (fitted && fitted.length > 0) {
+ const n = priceData.length;
+ const residualsArr = residuals || priceData.map((v, i) => v - (fitted[i] || v));
+ const residMean = residualsArr.reduce((a, b) => a + b, 0) / residualsArr.length;
+ const residStd = Math.sqrt(residualsArr.reduce((a, b) => a + Math.pow(b - residMean, 2), 0) / residualsArr.length);
+
+ const enhancedData = chartData.map((d, i) => {
+ const fittedVal = fitted[i];
+ const residual = residualsArr[i];
+ const ciWidth = 1.96 * residStd;
+
+ return {
+ ...d,
+ fitted: fittedVal,
+ residual: residual,
+ upperBand: fittedVal !== undefined ? fittedVal + ciWidth : null,
+ lowerBand: fittedVal !== undefined ? fittedVal - ciWidth : null,
+ residualBar: residual,
+ };
+ });
+
+ if (forecasts && forecasts.length > 0) {
+ forecasts.forEach((forecast, i) => {
+ const ciLower = forecastCI?.lower?.[i];
+ const ciUpper = forecastCI?.upper?.[i];
+ const defaultCiWidth = 1.96 * residStd * Math.sqrt(1 + (i + 1) * 0.1);
+
+ enhancedData.push({
+ index: n + i,
+ value: null as unknown as number,
+ date: `+${i + 1}d`,
+ fitted: null as unknown as number,
+ residual: null as unknown as number,
+ upperBand: null as unknown as number,
+ lowerBand: null as unknown as number,
+ residualBar: null as unknown as number,
+ forecast: forecast,
+ forecastUpper: ciUpper ?? (forecast + defaultCiWidth),
+ forecastLower: ciLower ?? (forecast - defaultCiWidth),
+ } as any);
+ });
+ } else {
+ const lastFitted = fitted[fitted.length - 1];
+ const forecastHorizon = 5;
+
+ for (let i = 0; i < forecastHorizon; i++) {
+ const forecastVal = lastFitted;
+ const ciWidth = 1.96 * residStd * Math.sqrt(1 + (i + 1) * 0.2);
+
+ enhancedData.push({
+ index: n + i,
+ value: null as unknown as number,
+ date: `+${i + 1}d`,
+ fitted: null as unknown as number,
+ residual: null as unknown as number,
+ upperBand: null as unknown as number,
+ lowerBand: null as unknown as number,
+ residualBar: null as unknown as number,
+ forecast: forecastVal,
+ forecastUpper: forecastVal + ciWidth,
+ forecastLower: forecastVal - ciWidth,
+ } as any);
+ }
+ }
+
+ return enhancedData;
+ }
+ return chartData;
+}
+
+function buildForecastingChartData(
+ result: Record<string, unknown>,
+ chartData: ChartDataPoint[],
+ priceData: number[]
+): any[] {
+ const forecasts = result.value as number[];
+ const meta = result.metadata as Record<string, unknown>;
+ const trainSize = (meta?.train_data_size as number) || Math.floor(chartData.length * 0.8);
+ const rmse = meta?.rmse as number;
+
+ if (forecasts && forecasts.length > 0) {
+ const forecastValue = forecasts[0];
+ const trainData = priceData.slice(0, trainSize);
+ const trainMean = trainData.reduce((a, b) => a + b, 0) / trainData.length;
+ const trainStd = Math.sqrt(trainData.reduce((a, b) => a + Math.pow(b - trainMean, 2), 0) / trainData.length);
+ const errorStd = rmse || trainStd * 0.3;
+ const testData = priceData.slice(trainSize);
+ const testErrors = testData.map(actual => actual - forecastValue);
+
+ const enhancedData = chartData.map((d, i) => {
+ const isTrainData = i < trainSize;
+ const isTestData = i >= trainSize;
+ const testIdx = i - trainSize;
+ const error = isTestData && testIdx < testErrors.length ? testErrors[testIdx] : null;
+ const absError = error !== null ? Math.abs(error) : null;
+
+ return {
+ ...d,
+ trainValue: isTrainData ? d.value : null,
+ testActual: isTestData ? d.value : null,
+ forecastLevel: isTestData ? forecastValue : null,
+ forecastUpper: isTestData ? forecastValue + 1.96 * errorStd : null,
+ forecastLower: isTestData ? forecastValue - 1.96 * errorStd : null,
+ forecastError: error,
+ absError: absError,
+ };
+ });
+
+ const futureForecasts = forecasts.map((v, i) => {
+ const ciWidth = 1.96 * errorStd * Math.sqrt(1 + (i + 1) * 0.15);
+
+ return {
+ index: chartData.length + i,
+ value: null,
+ trainValue: null,
+ testActual: null,
+ forecastLevel: null,
+ forecastUpper: null,
+ forecastLower: null,
+ forecastError: null,
+ absError: null,
+ forecast: v,
+ futureForecastUpper: v + ciWidth,
+ futureForecastLower: v - ciWidth,
+ date: `+${i + 1}d`,
+ };
+ });
+
+ if (enhancedData.length > 0 && trainSize > 0) {
+ const lastTrainIdx = trainSize - 1;
+ enhancedData[lastTrainIdx] = {
+ ...enhancedData[lastTrainIdx],
+ forecastStart: enhancedData[lastTrainIdx].value,
+ } as any;
+ }
+
+ return [...enhancedData, ...futureForecasts];
+ }
+ return chartData;
+}
+
+function buildSupervisedLearningChartData(
+ result: Record<string, unknown>,
+ chartData: ChartDataPoint[],
+ priceData: number[]
+): any[] {
+ const meta = result.metadata as Record<string, unknown>;
+ const value = result.value as Record<string, Record<string, unknown>>;
+ const bestAlgo = meta?.best_algorithm as string;
+
+ if (bestAlgo && value[bestAlgo]) {
+ const predictions = value[bestAlgo].predictions as number[];
+ const yTest = meta?.y_test as number[];
+ const rmse = value[bestAlgo].rmse as number;
+
+ if (predictions && predictions.length > 0) {
+ const nLags = 5;
+ const totalSamples = chartData.length - nLags;
+ const trainSize = (meta?.train_size as number) || Math.floor(totalSamples * 0.8);
+ const testStartIndex = nLags + trainSize;
+
+ const predictionErrors = yTest ? yTest.map((actual, i) => actual - predictions[i]) : [];
+ const predStd = rmse || (predictionErrors.length > 0 ?
+ Math.sqrt(predictionErrors.reduce((sum, e) => sum + e * e, 0) / predictionErrors.length) : 0);
+
+ return chartData.map((d, i) => {
+ const testIdx = i - testStartIndex;
+ const isTestPoint = testIdx >= 0 && testIdx < predictions.length;
+ const isTrainPoint = i >= nLags && i < testStartIndex;
+ const pred = isTestPoint ? predictions[testIdx] : null;
+ const actual = isTestPoint && yTest ? yTest[testIdx] : null;
+ const error = (pred !== null && actual !== null) ? actual - pred : null;
+ const ciWidth = 1.96 * predStd;
+
+ return {
+ ...d,
+ trainValue: isTrainPoint ? d.value : null,
+ prediction: pred,
+ testActual: actual,
+ predictionError: error,
+ upperBand: pred !== null ? pred + ciWidth : null,
+ lowerBand: pred !== null ? pred - ciWidth : null,
+ zeroLine: isTestPoint ? 0 : null,
+ };
+ });
+ }
+ }
+ return chartData;
+}
+
+function buildUnsupervisedLearningChartData(
+ result: Record<string, unknown>,
+ chartData: ChartDataPoint[]
+): any[] {
+ const value = result.value as Record<string, Record<string, unknown>>;
+
+ if (value?.kmeans) {
+ const clusterLabels = value.kmeans.cluster_labels as number[];
+ if (clusterLabels && clusterLabels.length > 0) {
+ return chartData.map((d, i) => ({
+ ...d,
+ cluster: i < clusterLabels.length ? clusterLabels[i] : 0,
+ }));
+ }
+ }
+ return chartData;
+}
+
+function buildResamplingChartData(
+ result: Record<string, unknown>,
+ chartData: ChartDataPoint[]
+): any[] {
+ const value = result.value as Record<string, Record<string, unknown>>;
+
+ if (value?.bootstrap) {
+ const bootstrap = value.bootstrap;
+ const resampledStats = bootstrap.resampled_statistics as number[];
+ const mean = bootstrap.mean as number;
+ const ci = bootstrap.confidence_interval as [number, number];
+
+ if (resampledStats && resampledStats.length > 0) {
+ const sortedStats = [...resampledStats].sort((a, b) => a - b);
+ const min = sortedStats[0];
+ const max = sortedStats[sortedStats.length - 1];
+ const binCount = Math.min(30, Math.ceil(Math.sqrt(sortedStats.length)));
+ const binWidth = (max - min) / binCount;
+
+ const findBinIndex = (val: number) => {
+ const binIdx = Math.floor((val - min) / binWidth);
+ return Math.max(0, Math.min(binCount - 1, binIdx));
+ };
+
+ const meanBinIdx = findBinIndex(mean);
+ const ciLowIdx = ci ? findBinIndex(ci[0]) : 0;
+ const ciHighIdx = ci ? findBinIndex(ci[1]) : binCount - 1;
+
+ const bins: any[] = [];
+ for (let i = 0; i < binCount; i++) {
+ const binStart = min + i * binWidth;
+ const binEnd = binStart + binWidth;
+ const binCenter = (binStart + binEnd) / 2;
+ const count = sortedStats.filter(v => v >= binStart && (i === binCount - 1 ? v <= binEnd : v < binEnd)).length;
+ const inCI = i >= ciLowIdx && i <= ciHighIdx;
+ const isMean = i === meanBinIdx;
+ bins.push({
+ index: i,
+ value: count,
+ binCenter,
+ frequency: count / sortedStats.length,
+ inCI,
+ isMean,
+ date: formatNumber(binCenter, 2),
+ meanBinIdx,
+ ciLowIdx,
+ ciHighIdx,
+ });
+ }
+
+ return bins;
+ }
+ }
+ return chartData;
+}
+
+function buildValidateDataChartData(
+ chartData: ChartDataPoint[],
+ priceData: number[]
+): any[] {
+ if (priceData.length < 3) return chartData;
+
+ const { zScores, mean } = calculateZScores(priceData);
+ const outlierThreshold = 3.0;
+
+ return chartData.map((d, i) => {
+ const zScore = zScores[i] || 0;
+ const isOutlier = zScore > outlierThreshold;
+ const isSuspicious = zScore > 2.0 && zScore <= outlierThreshold;
+
+ return {
+ ...d,
+ zScore,
+ isOutlier,
+ isSuspicious,
+ normalValue: !isOutlier && !isSuspicious ? d.value : null,
+ suspiciousValue: isSuspicious ? d.value : null,
+ outlierValue: isOutlier ? d.value : null,
+ mean,
+ };
+ });
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/utils/formatters.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/utils/formatters.ts
new file mode 100644
index 000000000..4ef52749b
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/utils/formatters.ts
@@ -0,0 +1,23 @@
+/**
+ * CFA Quant Formatting Utilities
+ */
+
+export const formatNumber = (val: number, decimals = 4): string => {
+ if (val === null || val === undefined || isNaN(val)) return '—';
+ return val.toFixed(decimals);
+};
+
+export const formatPrice = (val: number): string => {
+ if (val === null || val === undefined || isNaN(val)) return '—';
+ return val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
+};
+
+export const formatPercentage = (val: number, decimals = 2): string => {
+ if (val === null || val === undefined || isNaN(val)) return '—';
+ return `${val >= 0 ? '+' : ''}${val.toFixed(decimals)}%`;
+};
+
+export const formatDate = (timestamp: number | string): string => {
+ const date = new Date(timestamp);
+ return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: '2-digit' });
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/utils/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/utils/index.ts
new file mode 100644
index 000000000..0d668fac1
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/utils/index.ts
@@ -0,0 +1,8 @@
+/**
+ * CFA Quant Utilities - Barrel Export
+ */
+
+export * from './formatters';
+export * from './calculations';
+export * from './metricsExtractor';
+export * from './chartDataBuilder';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/utils/metricsExtractor.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/utils/metricsExtractor.ts
new file mode 100644
index 000000000..044c4f71e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/cfa-quant/utils/metricsExtractor.ts
@@ -0,0 +1,501 @@
+/**
+ * Metrics Extraction Utilities
+ * Extracts key metrics from analysis results
+ */
+
+import { BB } from '../constants';
+import { formatNumber, formatPrice } from './formatters';
+import type { KeyMetric } from '../types';
+import {
+ ArrowUpRight,
+ ArrowDownRight,
+ Minus,
+ CheckCircle2,
+ AlertCircle,
+ TrendingUp,
+ Sparkles,
+ Activity,
+} from 'lucide-react';
+
+export function extractKeyMetrics(
+ selectedAnalysis: string,
+ result: Record<string, unknown>,
+ priceData: number[]
+): KeyMetric[] {
+ const metrics: KeyMetric[] = [];
+
+ if (selectedAnalysis === 'trend_analysis' && result.metadata) {
+ const meta = result.metadata as Record<string, unknown>;
+ const value = result.value as Record<string, unknown>;
+ const slope = value?.slope as number;
+ const intercept = value?.intercept as number;
+ const rSquared = meta?.r_squared as number;
+ const significant = meta?.trend_significant as boolean;
+ const direction = meta?.trend_direction as string;
+ const pValue = meta?.slope_p_value as number;
+ const tStat = meta?.slope_t_statistic as number;
+
+ metrics.push({
+ label: 'DIRECTION',
+ value: direction === 'upward' ? 'UP' : direction === 'downward' ? 'DOWN' : 'FLAT',
+ color: direction === 'upward' ? BB.green : direction === 'downward' ? BB.red : BB.textMuted,
+ icon: direction === 'upward' ? ArrowUpRight : direction === 'downward' ? ArrowDownRight : Minus,
+ });
+
+ metrics.push({
+ label: 'SIGNIFICANT',
+ value: significant ? 'YES' : 'NO',
+ color: significant ? BB.green : BB.textMuted,
+ icon: significant ? CheckCircle2 : undefined
+ });
+
+ metrics.push({
+ label: 'R-SQUARED',
+ value: `${(rSquared * 100).toFixed(1)}%`,
+ color: rSquared > 0.7 ? BB.green : rSquared > 0.4 ? BB.amber : BB.textMuted
+ });
+
+ if (pValue !== undefined && pValue !== null) {
+ metrics.push({
+ label: 'P-VALUE',
+ value: pValue < 0.001 ? '<0.001' : formatNumber(pValue, 4),
+ color: pValue < 0.01 ? BB.green : pValue < 0.05 ? BB.greenDim : pValue < 0.1 ? BB.amber : BB.red
+ });
+ }
+
+ if (tStat !== undefined && tStat !== null) {
+ metrics.push({
+ label: 'T-STATISTIC',
+ value: formatNumber(tStat, 2),
+ color: Math.abs(tStat) > 2 ? BB.green : BB.textMuted
+ });
+ }
+
+ metrics.push({ label: 'SLOPE', value: formatNumber(slope, 6), color: BB.textPrimary });
+ if (intercept !== undefined && intercept !== null) {
+ metrics.push({ label: 'INTERCEPT', value: formatNumber(intercept, 2), color: BB.textSecondary });
+ }
+ } else if (selectedAnalysis === 'stationarity_test' && result.value) {
+ const value = result.value as Record<string, unknown>;
+ const meta = result.metadata as Record<string, unknown>;
+ const isStationary = value?.is_stationary as boolean;
+ const pValue = value?.p_value as number;
+ const testStat = value?.test_statistic as number;
+ const criticalValues = value?.critical_values as Record<string, number>;
+
+ metrics.push({
+ label: 'STATIONARY',
+ value: isStationary ? 'YES' : 'NO',
+ color: isStationary ? BB.green : BB.red,
+ icon: isStationary ? CheckCircle2 : AlertCircle
+ });
+
+ metrics.push({ label: 'TEST STAT', value: formatNumber(testStat, 4), color: BB.textPrimary });
+ metrics.push({
+ label: 'P-VALUE',
+ value: formatNumber(pValue, 4),
+ color: pValue < 0.01 ? BB.green : pValue < 0.05 ? BB.greenDim : pValue < 0.1 ? BB.amber : BB.red
+ });
+
+ if (criticalValues) {
+ const cv1 = criticalValues['1%'];
+ const cv5 = criticalValues['5%'];
+ const cv10 = criticalValues['10%'];
+
+ if (cv1 !== undefined) {
+ const beats1 = testStat < cv1;
+ metrics.push({ label: 'CV 1%', value: `${formatNumber(cv1, 2)} ${beats1 ? 'PASS' : ''}`, color: beats1 ? BB.green : BB.textMuted });
+ }
+ if (cv5 !== undefined) {
+ const beats5 = testStat < cv5;
+ metrics.push({ label: 'CV 5%', value: `${formatNumber(cv5, 2)} ${beats5 ? 'PASS' : ''}`, color: beats5 ? BB.green : BB.textMuted });
+ }
+ if (cv10 !== undefined) {
+ const beats10 = testStat < cv10;
+ metrics.push({ label: 'CV 10%', value: `${formatNumber(cv10, 2)} ${beats10 ? 'PASS' : ''}`, color: beats10 ? BB.amber : BB.textMuted });
+ }
+ }
+
+ if (meta) {
+ const rollingMeanStability = meta.rolling_mean_stability as number;
+ const rollingStdStability = meta.rolling_std_stability as number;
+ const meanReversionStrength = meta.mean_reversion_strength as number;
+
+ if (rollingMeanStability !== undefined) {
+ metrics.push({
+ label: 'MEAN STABILITY',
+ value: formatNumber(rollingMeanStability, 2),
+ color: rollingMeanStability < 1 ? BB.green : rollingMeanStability < 5 ? BB.amber : BB.red
+ });
+ }
+ if (rollingStdStability !== undefined) {
+ metrics.push({
+ label: 'VOL STABILITY',
+ value: formatNumber(rollingStdStability, 2),
+ color: rollingStdStability < 0.5 ? BB.green : rollingStdStability < 2 ? BB.amber : BB.red
+ });
+ }
+ if (meanReversionStrength !== undefined) {
+ metrics.push({
+ label: 'MEAN REVERSION',
+ value: `${(meanReversionStrength * 100).toFixed(1)}%`,
+ color: meanReversionStrength > 0.3 ? BB.green : meanReversionStrength > 0.1 ? BB.amber : BB.textMuted
+ });
+ }
+ }
+ } else if (selectedAnalysis === 'arima_model' && result.metadata) {
+ const meta = result.metadata as Record<string, unknown>;
+ const params = result.parameters as Record<string, unknown>;
+ const value = result.value as Record<string, unknown>;
+ const residuals = value?.residuals as number[];
+
+ const order = params?.order as number[];
+ if (order && order.length === 3) {
+ metrics.push({
+ label: 'MODEL ORDER',
+ value: `(${order[0]},${order[1]},${order[2]})`,
+ color: BB.amber
+ });
+ }
+
+ const seasonalOrder = params?.seasonal_order as number[];
+ if (seasonalOrder && seasonalOrder.length === 4) {
+ metrics.push({
+ label: 'SEASONAL',
+ value: `(${seasonalOrder[0]},${seasonalOrder[1]},${seasonalOrder[2]},${seasonalOrder[3]})`,
+ color: BB.blueLight
+ });
+ }
+
+ const aic = meta?.aic as number;
+ const bic = meta?.bic as number;
+ metrics.push({ label: 'AIC', value: formatNumber(aic, 2), color: BB.textPrimary });
+ metrics.push({ label: 'BIC', value: formatNumber(bic, 2), color: BB.textPrimary });
+
+ const logLik = meta?.log_likelihood as number;
+ if (logLik !== undefined && logLik !== null) {
+ metrics.push({ label: 'LOG-LIKELIHOOD', value: formatNumber(logLik, 2), color: BB.textSecondary });
+ }
+
+ const ljungBoxPValue = meta?.ljung_box_p_value as number;
+ const residualsAutocorrelated = meta?.residuals_autocorrelated as boolean;
+
+ metrics.push({
+ label: 'RESIDUALS OK',
+ value: !residualsAutocorrelated ? 'YES' : 'NO',
+ color: !residualsAutocorrelated ? BB.green : BB.red,
+ icon: !residualsAutocorrelated ? CheckCircle2 : AlertCircle
+ });
+
+ if (ljungBoxPValue !== undefined && ljungBoxPValue !== null) {
+ metrics.push({
+ label: 'LJUNG-BOX P',
+ value: formatNumber(ljungBoxPValue, 4),
+ color: ljungBoxPValue > 0.05 ? BB.green : ljungBoxPValue > 0.01 ? BB.amber : BB.red
+ });
+ }
+
+ if (residuals && residuals.length > 0) {
+ const residMean = residuals.reduce((a, b) => a + b, 0) / residuals.length;
+ const residStd = Math.sqrt(residuals.reduce((a, b) => a + Math.pow(b - residMean, 2), 0) / residuals.length);
+ metrics.push({ label: 'RESID MEAN', value: formatNumber(residMean, 4), color: Math.abs(residMean) < 0.01 ? BB.green : BB.textMuted });
+ metrics.push({ label: 'RESID STD', value: formatNumber(residStd, 4), color: BB.textSecondary });
+ }
+ } else if (selectedAnalysis === 'forecasting' && result.metadata) {
+ const meta = result.metadata as Record<string, unknown>;
+ const params = result.parameters as Record<string, unknown>;
+ const forecasts = result.value as number[];
+ const trainSize = meta?.train_data_size as number;
+ const testSize = meta?.test_data_size as number;
+ const horizon = meta?.forecast_horizon as number;
+ const method = params?.method as string;
+ const mae = meta?.mae as number;
+ const rmse = meta?.rmse as number;
+ const mape = meta?.mape as number;
+
+ if (method) {
+ const methodLabels: Record<string, string> = {
+ 'simple_exponential': 'EXP SMOOTH',
+ 'linear_trend': 'LINEAR TREND',
+ 'moving_average': 'MOVING AVG'
+ };
+ metrics.push({
+ label: 'METHOD',
+ value: methodLabels[method] || method.toUpperCase(),
+ color: BB.amber,
+ icon: method === 'linear_trend' ? TrendingUp : method === 'simple_exponential' ? Sparkles : Activity
+ });
+ }
+
+ if (mape !== undefined && mape !== null) {
+ let accuracy = 'EXCELLENT';
+ let accuracyColor = BB.green;
+ if (mape > 30) { accuracy = 'POOR'; accuracyColor = BB.red; }
+ else if (mape > 20) { accuracy = 'FAIR'; accuracyColor = BB.amber; }
+ else if (mape > 10) { accuracy = 'GOOD'; accuracyColor = BB.greenDim; }
+ metrics.push({ label: 'ACCURACY', value: accuracy, color: accuracyColor, icon: mape <= 10 ? CheckCircle2 : mape <= 20 ? AlertCircle : undefined });
+ }
+
+ if (forecasts && forecasts.length > 0) {
+ const forecastValue = forecasts[0];
+ metrics.push({ label: 'FORECAST VALUE', value: formatPrice(forecastValue), color: BB.green });
+
+ if (testSize > 0 && priceData.length > 0) {
+ const lastActual = priceData[priceData.length - 1];
+ const diff = forecastValue - lastActual;
+ const diffPct = (diff / lastActual) * 100;
+ metrics.push({
+ label: 'VS LAST ACTUAL',
+ value: `${diffPct >= 0 ? '+' : ''}${diffPct.toFixed(2)}%`,
+ color: diffPct >= 0 ? BB.green : BB.red,
+ icon: diffPct >= 0 ? ArrowUpRight : ArrowDownRight
+ });
+ }
+ }
+
+ if (trainSize && testSize) {
+ const trainPct = ((trainSize / (trainSize + testSize)) * 100).toFixed(0);
+ metrics.push({ label: 'TRAIN/TEST', value: `${trainPct}/${100 - parseInt(trainPct)}%`, color: BB.blueLight });
+ }
+ if (trainSize) metrics.push({ label: 'TRAIN SIZE', value: String(trainSize), color: BB.textSecondary });
+ if (testSize) metrics.push({ label: 'TEST SIZE', value: String(testSize), color: BB.textSecondary });
+ if (horizon) metrics.push({ label: 'HORIZON', value: `${horizon} periods`, color: BB.green });
+
+ if (mae !== undefined && mae !== null) {
+ metrics.push({ label: 'MAE', value: formatNumber(mae, 2), color: BB.textPrimary });
+ }
+ if (rmse !== undefined && rmse !== null) {
+ metrics.push({ label: 'RMSE', value: formatNumber(rmse, 2), color: BB.textPrimary });
+ if (mae !== undefined && mae !== null && mae > 0) {
+ const rmseToMae = rmse / mae;
+ metrics.push({
+ label: 'RMSE/MAE',
+ value: formatNumber(rmseToMae, 2),
+ color: rmseToMae < 1.2 ? BB.green : rmseToMae < 1.5 ? BB.amber : BB.red
+ });
+ }
+ }
+ if (mape !== undefined && mape !== null) {
+ metrics.push({
+ label: 'MAPE',
+ value: `${formatNumber(mape, 2)}%`,
+ color: mape < 10 ? BB.green : mape < 20 ? BB.amber : BB.red
+ });
+ }
+ } else if (selectedAnalysis === 'supervised_learning' && result.value) {
+ const meta = result.metadata as Record<string, unknown>;
+ const value = result.value as Record<string, Record<string, unknown>>;
+ const bestAlgo = meta?.best_algorithm as string;
+ const nFeatures = meta?.n_features as number;
+
+ if (bestAlgo) {
+ metrics.push({ label: 'BEST MODEL', value: bestAlgo.toUpperCase().replace('_', ' '), color: BB.green, icon: CheckCircle2 });
+ }
+
+ if (bestAlgo && value[bestAlgo]) {
+ const bestResult = value[bestAlgo];
+ if (bestResult.r2_score !== undefined) {
+ const r2 = bestResult.r2_score as number;
+ const r2Quality = r2 > 0.8 ? 'Excellent' : r2 > 0.6 ? 'Good' : r2 > 0.4 ? 'Fair' : 'Poor';
+ metrics.push({ label: 'R² SCORE', value: `${(r2 * 100).toFixed(1)}%`, color: r2 > 0.7 ? BB.green : r2 > 0.5 ? BB.amber : BB.red });
+ metrics.push({ label: 'FIT QUALITY', value: r2Quality.toUpperCase(), color: r2 > 0.7 ? BB.green : r2 > 0.5 ? BB.amber : BB.red });
+ }
+ if (bestResult.rmse !== undefined) {
+ metrics.push({ label: 'RMSE', value: formatNumber(bestResult.rmse as number, 4), color: BB.textPrimary });
+ }
+ if (bestResult.mse !== undefined) {
+ metrics.push({ label: 'MSE', value: formatNumber(bestResult.mse as number, 4), color: BB.textSecondary });
+ }
+ }
+
+ const algoNames = Object.keys(value).filter(k => !value[k].error);
+ if (algoNames.length > 1) {
+ metrics.push({ label: 'MODELS TESTED', value: String(algoNames.length), color: BB.blueLight });
+
+ algoNames.forEach(algo => {
+ if (algo !== bestAlgo && value[algo]?.r2_score !== undefined) {
+ const r2 = value[algo].r2_score as number;
+ metrics.push({
+ label: algo.toUpperCase().replace('_', ' ').substring(0, 12),
+ value: `R²: ${(r2 * 100).toFixed(1)}%`,
+ color: BB.textMuted
+ });
+ }
+ });
+ }
+
+ if (meta?.train_size) {
+ metrics.push({ label: 'TRAIN SIZE', value: String(meta.train_size), color: BB.textMuted });
+ }
+ if (meta?.test_size) {
+ metrics.push({ label: 'TEST SIZE', value: String(meta.test_size), color: BB.textMuted });
+ }
+ if (nFeatures) {
+ metrics.push({ label: 'FEATURES', value: String(nFeatures), color: BB.textMuted });
+ }
+ } else if (selectedAnalysis === 'unsupervised_learning' && result.value) {
+ const value = result.value as Record<string, Record<string, unknown>>;
+ const meta = result.metadata as Record<string, unknown>;
+
+ if (value.pca) {
+ const pca = value.pca;
+ const explainedVariance = pca.explained_variance_ratio as number[];
+ const componentsFor95 = pca.components_for_95_variance as number;
+
+ if (explainedVariance && explainedVariance.length > 0) {
+ const firstComponentVar = (explainedVariance[0] * 100).toFixed(1);
+ const totalComponents = explainedVariance.length;
+ metrics.push({ label: 'PC1 VARIANCE', value: `${firstComponentVar}%`, color: BB.green });
+ metrics.push({ label: 'COMPONENTS (95%)', value: String(componentsFor95), color: BB.amber });
+ metrics.push({ label: 'TOTAL PCs', value: String(totalComponents), color: BB.textSecondary });
+ }
+ }
+
+ if (value.kmeans) {
+ const kmeans = value.kmeans;
+ const optimalK = kmeans.optimal_k as number;
+ const silhouetteByK = kmeans.silhouette_by_k as [number, number][];
+
+ metrics.push({ label: 'OPTIMAL K', value: String(optimalK), color: BB.green });
+
+ if (silhouetteByK && silhouetteByK.length > 0) {
+ const optimalSilhouette = silhouetteByK.find(([k]) => k === optimalK);
+ if (optimalSilhouette) {
+ const score = optimalSilhouette[1];
+ const quality = score > 0.7 ? 'STRONG' : score > 0.5 ? 'GOOD' : score > 0.25 ? 'FAIR' : 'WEAK';
+ metrics.push({ label: 'SILHOUETTE', value: formatNumber(score, 3), color: score > 0.5 ? BB.green : BB.amber });
+ metrics.push({ label: 'CLUSTERING', value: quality, color: score > 0.5 ? BB.green : BB.amber });
+ }
+ }
+
+ const clusterLabels = kmeans.cluster_labels as number[];
+ if (clusterLabels) {
+ metrics.push({ label: 'DATA POINTS', value: String(clusterLabels.length), color: BB.textSecondary });
+ }
+ }
+
+ if (meta?.n_samples) {
+ metrics.push({ label: 'SAMPLES', value: String(meta.n_samples), color: BB.textMuted });
+ }
+ if (meta?.n_features) {
+ metrics.push({ label: 'FEATURES', value: String(meta.n_features), color: BB.textMuted });
+ }
+ } else if (selectedAnalysis === 'resampling_methods' && result.value) {
+ const value = result.value as Record<string, Record<string, unknown>>;
+ const meta = result.metadata as Record<string, unknown>;
+
+ if (value.bootstrap) {
+ const bootstrap = value.bootstrap;
+ const mean = bootstrap.mean as number;
+ const std = bootstrap.std as number;
+ const bias = bootstrap.bias as number;
+ const ci = bootstrap.confidence_interval as [number, number];
+
+ metrics.push({ label: 'BOOT MEAN', value: formatNumber(mean, 4), color: BB.green });
+ metrics.push({ label: 'BOOT STD', value: formatNumber(std, 4), color: BB.textPrimary });
+ if (bias !== undefined && bias !== null) {
+ metrics.push({ label: 'BIAS', value: formatNumber(bias, 6), color: Math.abs(bias) < 0.01 ? BB.green : BB.amber });
+ }
+ if (ci && ci.length === 2) {
+ metrics.push({ label: '95% CI LOW', value: formatNumber(ci[0], 4), color: BB.textSecondary });
+ metrics.push({ label: '95% CI HIGH', value: formatNumber(ci[1], 4), color: BB.textSecondary });
+ }
+ }
+
+ if (value.jackknife) {
+ const jackknife = value.jackknife;
+ const biasCorr = jackknife.bias_corrected_estimate as number;
+ const stdErr = jackknife.std_error as number;
+ const jackBias = jackknife.bias as number;
+
+ if (biasCorr !== undefined) {
+ metrics.push({ label: 'JACK ESTIMATE', value: formatNumber(biasCorr, 4), color: BB.amber });
+ }
+ if (stdErr !== undefined) {
+ metrics.push({ label: 'STD ERROR', value: formatNumber(stdErr, 4), color: BB.textPrimary });
+ }
+ if (jackBias !== undefined) {
+ metrics.push({ label: 'JACK BIAS', value: formatNumber(jackBias, 6), color: Math.abs(jackBias) < 0.01 ? BB.green : BB.amber });
+ }
+ }
+
+ if (value.permutation) {
+ const perm = value.permutation;
+ const pValue = perm.p_value as number;
+ const significant = perm.significant as boolean;
+
+ metrics.push({ label: 'P-VALUE', value: formatNumber(pValue, 4), color: pValue < 0.05 ? BB.green : BB.textMuted });
+ metrics.push({ label: 'SIGNIFICANT', value: significant ? 'YES' : 'NO', color: significant ? BB.green : BB.textMuted });
+ }
+
+ if (meta?.n_bootstrap) {
+ metrics.push({ label: 'ITERATIONS', value: String(meta.n_bootstrap), color: BB.textMuted });
+ }
+ if (meta?.data_size) {
+ metrics.push({ label: 'DATA SIZE', value: String(meta.data_size), color: BB.textMuted });
+ }
+ } else if (selectedAnalysis === 'validate_data' && result) {
+ const qualityScore = result.quality_score as number;
+ const issues = result.issues as { type: string; severity: string; description: string }[];
+ const warnings = result.warnings as { type: string; message: string }[];
+ const statistics = result.statistics as Record<string, unknown>;
+ const recommendations = result.recommendations as string[];
+
+ if (qualityScore !== undefined && qualityScore !== null) {
+ let scoreColor = BB.green;
+ let scoreLabel = 'EXCELLENT';
+ if (qualityScore < 50) { scoreColor = BB.red; scoreLabel = 'POOR'; }
+ else if (qualityScore < 70) { scoreColor = BB.amber; scoreLabel = 'FAIR'; }
+ else if (qualityScore < 90) { scoreColor = BB.green; scoreLabel = 'GOOD'; }
+ metrics.push({ label: 'QUALITY SCORE', value: `${qualityScore.toFixed(0)}/100`, color: scoreColor });
+ metrics.push({ label: 'STATUS', value: scoreLabel, color: scoreColor });
+ }
+
+ if (statistics) {
+ if (statistics.total_observations !== undefined) {
+ metrics.push({ label: 'OBSERVATIONS', value: String(statistics.total_observations), color: BB.textPrimary });
+ }
+ if (statistics.missing_data_ratio !== undefined) {
+ const missingRatio = statistics.missing_data_ratio as number;
+ const missingPct = (missingRatio * 100).toFixed(1);
+ metrics.push({
+ label: 'MISSING DATA',
+ value: `${missingPct}%`,
+ color: missingRatio > 0.05 ? BB.red : missingRatio > 0.01 ? BB.amber : BB.green
+ });
+ }
+ if (statistics.mean !== undefined) {
+ metrics.push({ label: 'MEAN', value: formatNumber(statistics.mean as number, 2), color: BB.textSecondary });
+ }
+ if (statistics.std !== undefined) {
+ metrics.push({ label: 'STD DEV', value: formatNumber(statistics.std as number, 2), color: BB.textSecondary });
+ }
+ }
+
+ if (issues && issues.length > 0) {
+ const criticalCount = issues.filter(i => i.severity === 'critical').length;
+ const highCount = issues.filter(i => i.severity === 'high').length;
+ const totalIssues = issues.length;
+
+ metrics.push({ label: 'TOTAL ISSUES', value: String(totalIssues), color: totalIssues > 0 ? BB.amber : BB.green });
+ if (criticalCount > 0) {
+ metrics.push({ label: 'CRITICAL', value: String(criticalCount), color: BB.red });
+ }
+ if (highCount > 0) {
+ metrics.push({ label: 'HIGH SEV', value: String(highCount), color: BB.red });
+ }
+ } else {
+ metrics.push({ label: 'ISSUES', value: 'NONE', color: BB.green });
+ }
+
+ if (warnings && warnings.length > 0) {
+ metrics.push({ label: 'WARNINGS', value: String(warnings.length), color: BB.amber });
+ }
+
+ if (recommendations && recommendations.length > 0) {
+ metrics.push({ label: 'RECOMMENDATIONS', value: String(recommendations.length), color: BB.blueLight });
+ }
+ }
+
+ return metrics;
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/CustomNode.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/CustomNode.tsx
new file mode 100644
index 000000000..5e33d9f7e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/CustomNode.tsx
@@ -0,0 +1,191 @@
+/**
+ * CustomNode Component
+ *
+ * Generic custom node component for the workflow editor
+ * Handles rendering, editing labels, and displaying status
+ */
+
+import React, { useState } from 'react';
+import { Handle, Position } from 'reactflow';
+import {
+ Database,
+ Zap,
+ TrendingUp,
+ BarChart3,
+ Brain,
+ FileText,
+ Edit3,
+} from 'lucide-react';
+import type { CustomNodeData } from '../types';
+
+interface CustomNodeProps {
+ data: CustomNodeData;
+ id: string;
+ selected: boolean;
+}
+
+const CustomNode: React.FC<CustomNodeProps> = ({ data, id, selected }) => {
+ const [isEditing, setIsEditing] = useState(false);
+ const [label, setLabel] = useState(data.label);
+
+ const handleLabelSave = () => {
+ data.onLabelChange(id, label);
+ setIsEditing(false);
+ };
+
+ const getIcon = () => {
+ switch (data.nodeType) {
+ case 'data-source':
+ return <Database size={16} />;
+ case 'transformation':
+ return <Zap size={16} />;
+ case 'analysis':
+ return <TrendingUp size={16} />;
+ case 'visualization':
+ return <BarChart3 size={16} />;
+ case 'agent':
+ return <Brain size={16} />;
+ case 'output':
+ return <FileText size={16} />;
+ default:
+ return <Database size={16} />;
+ }
+ };
+
+ return (
+ <div
+ style={{
+ background: selected ? '#2d2d2d' : '#1a1a1a',
+ border: `2px solid ${selected ? data.color : `${data.color}80`}`,
+ borderRadius: '6px',
+ minWidth: '180px',
+ boxShadow: selected
+ ? `0 0 20px ${data.color}60, 0 4px 12px rgba(0,0,0,0.5)`
+ : `0 2px 8px rgba(0,0,0,0.3)`,
+ transition: 'all 0.2s',
+ }}
+ >
+ {/* Input Handle */}
+ {data.hasInput && (
+ <Handle
+ type="target"
+ position={Position.Left}
+ style={{
+ background: data.color,
+ width: 12,
+ height: 12,
+ border: '2px solid #1a1a1a',
+ boxShadow: `0 0 8px ${data.color}`,
+ }}
+ />
+ )}
+
+ {/* Node Header */}
+ <div
+ style={{
+ background: `${data.color}20`,
+ borderBottom: `1px solid ${data.color}40`,
+ padding: '8px 12px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: '8px',
+ color: data.color,
+ borderTopLeftRadius: '4px',
+ borderTopRightRadius: '4px',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ {getIcon()}
+ {isEditing ? (
+ <input
+ type="text"
+ value={label}
+ onChange={(e) => setLabel(e.target.value)}
+ onBlur={handleLabelSave}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') handleLabelSave();
+ if (e.key === 'Escape') {
+ setLabel(data.label);
+ setIsEditing(false);
+ }
+ }}
+ autoFocus
+ style={{
+ background: '#1a1a1a',
+ border: `1px solid ${data.color}`,
+ color: data.color,
+ fontSize: '11px',
+ padding: '2px 6px',
+ borderRadius: '3px',
+ outline: 'none',
+ fontWeight: 'bold',
+ width: '120px',
+ }}
+ />
+ ) : (
+ <span
+ style={{
+ fontSize: '11px',
+ fontWeight: 'bold',
+ letterSpacing: '0.3px',
+ }}
+ >
+ {data.label.toUpperCase()}
+ </span>
+ )}
+ </div>
+ {!isEditing && (
+ <button
+ onClick={() => setIsEditing(true)}
+ style={{
+ background: 'transparent',
+ border: 'none',
+ color: data.color,
+ cursor: 'pointer',
+ padding: '2px',
+ display: 'flex',
+ alignItems: 'center',
+ }}
+ title="Edit label"
+ >
+ <Edit3 size={12} />
+ </button>
+ )}
+ </div>
+
+ {/* Node Body */}
+ <div
+ style={{
+ padding: '12px',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '4px',
+ color: '#a3a3a3',
+ fontSize: '10px',
+ }}
+ >
+ <div>Type: {data.nodeType}</div>
+ <div>Status: {data.status || 'Ready'}</div>
+ <div style={{ color: '#737373' }}>ID: {id.substring(0, 8)}</div>
+ </div>
+
+ {/* Output Handle */}
+ {data.hasOutput && (
+ <Handle
+ type="source"
+ position={Position.Right}
+ style={{
+ background: data.color,
+ width: 12,
+ height: 12,
+ border: '2px solid #1a1a1a',
+ boxShadow: `0 0 8px ${data.color}`,
+ }}
+ />
+ )}
+ </div>
+ );
+};
+
+export default CustomNode;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/DeployDialog.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/DeployDialog.tsx
new file mode 100644
index 000000000..6170a0108
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/DeployDialog.tsx
@@ -0,0 +1,186 @@
+/**
+ * DeployDialog Component
+ *
+ * Modal dialog for deploying workflows with name and description
+ */
+
+import React from 'react';
+import { Rocket } from 'lucide-react';
+import type { DeployDialogProps } from '../types';
+
+const DeployDialog: React.FC<DeployDialogProps> = ({
+ isOpen,
+ onClose,
+ workflowName,
+ setWorkflowName,
+ workflowDescription,
+ setWorkflowDescription,
+ onDeploy,
+ onSaveDraft,
+}) => {
+ if (!isOpen) return null;
+
+ return (
+ <div
+ style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0, 0, 0, 0.7)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 2000,
+ }}
+ onClick={onClose}
+ >
+ <div
+ style={{
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #2d2d2d',
+ borderRadius: '6px',
+ padding: '24px',
+ minWidth: '400px',
+ maxWidth: '500px',
+ }}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div
+ style={{
+ color: '#ea580c',
+ fontSize: '14px',
+ fontWeight: 'bold',
+ marginBottom: '20px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ }}
+ >
+ <Rocket size={16} />
+ DEPLOY WORKFLOW
+ </div>
+
+ <div style={{ marginBottom: '16px' }}>
+ <label
+ style={{
+ display: 'block',
+ color: '#a3a3a3',
+ fontSize: '11px',
+ marginBottom: '6px',
+ fontWeight: 'bold',
+ }}
+ >
+ WORKFLOW NAME *
+ </label>
+ <input
+ type="text"
+ value={workflowName}
+ onChange={(e) => setWorkflowName(e.target.value)}
+ placeholder="Enter workflow name..."
+ autoFocus
+ style={{
+ width: '100%',
+ backgroundColor: '#0a0a0a',
+ border: '1px solid #2d2d2d',
+ color: 'white',
+ padding: '8px 12px',
+ fontSize: '12px',
+ borderRadius: '4px',
+ outline: 'none',
+ boxSizing: 'border-box',
+ }}
+ />
+ </div>
+
+ <div style={{ marginBottom: '20px' }}>
+ <label
+ style={{
+ display: 'block',
+ color: '#a3a3a3',
+ fontSize: '11px',
+ marginBottom: '6px',
+ fontWeight: 'bold',
+ }}
+ >
+ DESCRIPTION (OPTIONAL)
+ </label>
+ <textarea
+ value={workflowDescription}
+ onChange={(e) => setWorkflowDescription(e.target.value)}
+ placeholder="Enter workflow description..."
+ rows={3}
+ style={{
+ width: '100%',
+ backgroundColor: '#0a0a0a',
+ border: '1px solid #2d2d2d',
+ color: 'white',
+ padding: '8px 12px',
+ fontSize: '12px',
+ borderRadius: '4px',
+ outline: 'none',
+ resize: 'vertical',
+ fontFamily: 'Consolas, monospace',
+ boxSizing: 'border-box',
+ }}
+ />
+ </div>
+
+ <div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end' }}>
+ <button
+ onClick={() => {
+ onClose();
+ setWorkflowName('');
+ setWorkflowDescription('');
+ }}
+ style={{
+ backgroundColor: 'transparent',
+ color: '#a3a3a3',
+ border: '1px solid #404040',
+ padding: '8px 16px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '4px',
+ fontWeight: 'bold',
+ }}
+ >
+ CANCEL
+ </button>
+ <button
+ onClick={onSaveDraft}
+ style={{
+ backgroundColor: 'transparent',
+ color: '#f59e0b',
+ border: '1px solid #f59e0b',
+ padding: '8px 16px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '4px',
+ fontWeight: 'bold',
+ }}
+ >
+ SAVE AS DRAFT
+ </button>
+ <button
+ onClick={onDeploy}
+ style={{
+ backgroundColor: '#3b82f6',
+ color: 'white',
+ border: 'none',
+ padding: '8px 16px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '4px',
+ fontWeight: 'bold',
+ }}
+ >
+ DEPLOY & EXECUTE
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default DeployDialog;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/NodeConfigPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/NodeConfigPanel.tsx
new file mode 100644
index 000000000..829eef61e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/NodeConfigPanel.tsx
@@ -0,0 +1,630 @@
+/**
+ * NodeConfigPanel Component
+ *
+ * Right sidebar panel for configuring selected node properties
+ */
+
+import React from 'react';
+import { Node } from 'reactflow';
+import {
+ Settings2,
+ X,
+ Trash2,
+ Plus,
+ Edit3,
+ AlertCircle,
+} from 'lucide-react';
+import { NodeParameterInput } from '../nodes/NodeParameterInput';
+import type { INodeProperties, NodeParameterValue } from '@/services/nodeSystem';
+
+interface NodeConfigPanelProps {
+ selectedNode: Node;
+ onLabelChange: (nodeId: string, newLabel: string) => void;
+ onParameterChange: (paramName: string, value: NodeParameterValue) => void;
+ onClose: () => void;
+ onDelete: () => void;
+ onDuplicate: () => void;
+}
+
+const NodeConfigPanel: React.FC<NodeConfigPanelProps> = ({
+ selectedNode,
+ onLabelChange,
+ onParameterChange,
+ onClose,
+ onDelete,
+ onDuplicate,
+}) => {
+ const registryData = selectedNode.data.registryData;
+ const nodeProperties: INodeProperties[] = registryData?.properties || [];
+ const nodeColor = selectedNode.data.color || '#FF8800';
+
+ return (
+ <div
+ style={{
+ width: '300px',
+ backgroundColor: '#000000',
+ borderLeft: '2px solid #FF8800',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ }}
+ >
+ {/* Panel Header */}
+ <div
+ style={{
+ backgroundColor: '#1A1A1A',
+ borderBottom: '1px solid #2A2A2A',
+ padding: '8px 12px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Settings2
+ size={14}
+ style={{ color: '#FF8800', filter: 'drop-shadow(0 0 4px #FF8800)' }}
+ />
+ <span
+ style={{
+ color: '#FF8800',
+ fontSize: '11px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ textTransform: 'uppercase',
+ }}
+ >
+ NODE CONFIG
+ </span>
+ </div>
+ <button
+ onClick={onClose}
+ style={{
+ backgroundColor: 'transparent',
+ border: 'none',
+ color: '#787878',
+ cursor: 'pointer',
+ padding: '2px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ }}
+ >
+ <X size={14} />
+ </button>
+ </div>
+
+ {/* Node Type Badge */}
+ <div
+ style={{
+ backgroundColor: '#0F0F0F',
+ padding: '10px 12px',
+ borderBottom: '1px solid #2A2A2A',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ }}
+ >
+ <div
+ style={{
+ width: '28px',
+ height: '28px',
+ backgroundColor: `${nodeColor}20`,
+ border: `1px solid ${nodeColor}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: '12px',
+ fontWeight: 700,
+ color: nodeColor,
+ }}
+ >
+ {(selectedNode.data.label || selectedNode.type || 'N')[0].toUpperCase()}
+ </div>
+ <div>
+ <div style={{ color: '#FFFFFF', fontSize: '11px', fontWeight: 600 }}>
+ {selectedNode.data.label || selectedNode.type}
+ </div>
+ <div style={{ color: '#787878', fontSize: '9px', textTransform: 'uppercase' }}>
+ {selectedNode.type}
+ </div>
+ </div>
+ </div>
+
+ {/* Scrollable Content */}
+ <div style={{ flex: 1, overflow: 'auto', backgroundColor: '#000000' }}>
+ {/* Label Section */}
+ <div style={{ padding: '12px', borderBottom: '1px solid #2A2A2A' }}>
+ <label
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ color: '#FF8800',
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}
+ >
+ <span>LABEL</span>
+ <span style={{ color: '#4A4A4A', fontSize: '8px', fontWeight: 400 }}>REQUIRED</span>
+ </label>
+ <div
+ style={{
+ position: 'relative',
+ display: 'flex',
+ alignItems: 'stretch',
+ }}
+ >
+ <div
+ style={{
+ backgroundColor: '#1A1A1A',
+ borderTop: '1px solid #2A2A2A',
+ borderLeft: '1px solid #2A2A2A',
+ borderBottom: '1px solid #2A2A2A',
+ padding: '0 8px',
+ display: 'flex',
+ alignItems: 'center',
+ color: '#FF8800',
+ fontSize: '10px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ }}
+ >
+ <Edit3 size={10} />
+ </div>
+ <input
+ type="text"
+ value={selectedNode.data.label || ''}
+ onChange={(e) => onLabelChange(selectedNode.id, e.target.value)}
+ placeholder="Enter node label..."
+ style={{
+ flex: 1,
+ backgroundColor: '#0A0A0A',
+ border: '1px solid #2A2A2A',
+ borderLeft: 'none',
+ padding: '10px 12px',
+ color: '#FFFFFF',
+ fontSize: '11px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ outline: 'none',
+ transition: 'all 0.15s ease',
+ }}
+ />
+ </div>
+ <div
+ style={{
+ marginTop: '4px',
+ fontSize: '8px',
+ color: '#4A4A4A',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ }}
+ >
+ Display name for this node in the workflow
+ </div>
+ </div>
+
+ {/* Registry Node Parameters */}
+ {nodeProperties.length > 0 && (
+ <div
+ style={{
+ padding: '14px',
+ borderBottom: '1px solid #3A3A3A',
+ backgroundColor: '#111111',
+ }}
+ >
+ {/* Parameters Header */}
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: '16px',
+ paddingBottom: '10px',
+ borderBottom: '1px solid #2A2A2A',
+ }}
+ >
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ }}
+ >
+ <div
+ style={{
+ width: '4px',
+ height: '18px',
+ backgroundColor: '#FF8800',
+ }}
+ />
+ <span
+ style={{
+ color: '#FF8800',
+ fontSize: '13px',
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ letterSpacing: '1.5px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ }}
+ >
+ PARAMETERS
+ </span>
+ </div>
+ <div
+ style={{
+ backgroundColor: '#FF880030',
+ border: '1px solid #FF8800',
+ padding: '4px 10px',
+ fontSize: '12px',
+ fontWeight: 700,
+ color: '#FF8800',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ }}
+ >
+ {nodeProperties.length}
+ </div>
+ </div>
+
+ {/* Parameters List */}
+ <div
+ style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '14px',
+ }}
+ >
+ {nodeProperties.map((param, index) => (
+ <div
+ key={param.name}
+ style={{
+ padding: '14px',
+ backgroundColor: '#1A1A1A',
+ border: '1px solid #333333',
+ position: 'relative',
+ }}
+ >
+ {/* Parameter Index Badge */}
+ <div
+ style={{
+ position: 'absolute',
+ top: '-1px',
+ left: '-1px',
+ backgroundColor: '#2A2A2A',
+ color: '#AAAAAA',
+ fontSize: '11px',
+ fontWeight: 700,
+ padding: '4px 8px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ borderRight: '1px solid #444444',
+ borderBottom: '1px solid #444444',
+ }}
+ >
+ {String(index + 1).padStart(2, '0')}
+ </div>
+
+ {/* Required Indicator */}
+ {param.required && (
+ <div
+ style={{
+ position: 'absolute',
+ top: '0',
+ right: '0',
+ width: '0',
+ height: '0',
+ borderStyle: 'solid',
+ borderWidth: '0 16px 16px 0',
+ borderColor: 'transparent #FF3B3B transparent transparent',
+ }}
+ />
+ )}
+
+ <div style={{ paddingTop: '12px' }}>
+ <NodeParameterInput
+ parameter={param}
+ value={selectedNode.data.parameters?.[param.name] ?? param.default}
+ onChange={(value) => onParameterChange(param.name, value)}
+ />
+ </div>
+ </div>
+ ))}
+ </div>
+
+ {/* Parameters Footer */}
+ <div
+ style={{
+ marginTop: '14px',
+ paddingTop: '10px',
+ borderTop: '1px solid #2A2A2A',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ }}
+ >
+ <div
+ style={{
+ width: '8px',
+ height: '8px',
+ backgroundColor: '#00D66F',
+ borderRadius: '50%',
+ boxShadow: '0 0 6px #00D66F80',
+ }}
+ />
+ <span
+ style={{
+ color: '#AAAAAA',
+ fontSize: '11px',
+ fontWeight: 600,
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}
+ >
+ {nodeProperties.filter((p) => p.required).length > 0
+ ? `${nodeProperties.filter((p) => p.required).length} REQUIRED`
+ : 'ALL OPTIONAL'}
+ </span>
+ </div>
+ </div>
+ )}
+
+ {/* Node Info Section */}
+ <div style={{ padding: '12px', borderBottom: '1px solid #2A2A2A' }}>
+ <div
+ style={{
+ color: '#FF8800',
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '10px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}
+ >
+ NODE INFO
+ </div>
+
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
+ {/* Node ID */}
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: '#787878', fontSize: '9px', textTransform: 'uppercase' }}>
+ ID
+ </span>
+ <code style={{ color: '#FFFFFF', fontSize: '9px' }}>{selectedNode.id}</code>
+ </div>
+
+ {/* Position */}
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: '#787878', fontSize: '9px', textTransform: 'uppercase' }}>
+ POS
+ </span>
+ <span style={{ color: '#FFFFFF', fontSize: '9px' }}>
+ {Math.round(selectedNode.position.x)}, {Math.round(selectedNode.position.y)}
+ </span>
+ </div>
+
+ {/* Registry Type */}
+ {selectedNode.data.nodeTypeName && (
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: '#787878', fontSize: '9px', textTransform: 'uppercase' }}>
+ TYPE
+ </span>
+ <span style={{ color: '#FFFFFF', fontSize: '9px' }}>
+ {selectedNode.data.nodeTypeName}
+ </span>
+ </div>
+ )}
+
+ {/* Status */}
+ {selectedNode.data.status && (
+ <div
+ style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}
+ >
+ <span style={{ color: '#787878', fontSize: '9px', textTransform: 'uppercase' }}>
+ STATUS
+ </span>
+ <span
+ style={{
+ fontSize: '9px',
+ fontWeight: 700,
+ padding: '2px 6px',
+ backgroundColor:
+ selectedNode.data.status === 'completed'
+ ? '#00D66F20'
+ : selectedNode.data.status === 'error'
+ ? '#FF3B3B20'
+ : selectedNode.data.status === 'running'
+ ? '#0088FF20'
+ : '#78787820',
+ color:
+ selectedNode.data.status === 'completed'
+ ? '#00D66F'
+ : selectedNode.data.status === 'error'
+ ? '#FF3B3B'
+ : selectedNode.data.status === 'running'
+ ? '#0088FF'
+ : '#787878',
+ textTransform: 'uppercase',
+ }}
+ >
+ {selectedNode.data.status}
+ </span>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Description (for registry nodes) */}
+ {registryData?.description && (
+ <div style={{ padding: '12px', borderBottom: '1px solid #2A2A2A' }}>
+ <div
+ style={{
+ color: '#00E5FF',
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+ }}
+ >
+ DESCRIPTION
+ </div>
+ <div style={{ color: '#FFFFFF', fontSize: '10px', lineHeight: '1.5' }}>
+ {registryData.description}
+ </div>
+ </div>
+ )}
+
+ {/* Error Display */}
+ {selectedNode.data.error && (
+ <div
+ style={{
+ margin: '12px',
+ backgroundColor: '#FF3B3B15',
+ border: '1px solid #FF3B3B',
+ padding: '10px',
+ }}
+ >
+ <div
+ style={{
+ color: '#FF3B3B',
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '4px',
+ textTransform: 'uppercase',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ }}
+ >
+ <AlertCircle size={10} />
+ ERROR
+ </div>
+ <div style={{ color: '#FFFFFF', fontSize: '10px', lineHeight: '1.4' }}>
+ {selectedNode.data.error}
+ </div>
+ </div>
+ )}
+
+ {/* Result Preview */}
+ {selectedNode.data.result && selectedNode.data.status === 'completed' && (
+ <div
+ style={{
+ margin: '12px',
+ backgroundColor: '#00D66F15',
+ border: '1px solid #00D66F',
+ padding: '10px',
+ }}
+ >
+ <div
+ style={{
+ color: '#00D66F',
+ fontSize: '9px',
+ fontWeight: 700,
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ }}
+ >
+ OUTPUT PREVIEW
+ </div>
+ <pre
+ style={{
+ color: '#FFFFFF',
+ fontSize: '9px',
+ lineHeight: '1.4',
+ overflow: 'auto',
+ maxHeight: '80px',
+ margin: 0,
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ }}
+ >
+ {typeof selectedNode.data.result === 'string'
+ ? selectedNode.data.result.substring(0, 200)
+ : JSON.stringify(selectedNode.data.result, null, 2).substring(0, 200)}
+ {(typeof selectedNode.data.result === 'string'
+ ? selectedNode.data.result.length
+ : JSON.stringify(selectedNode.data.result).length) > 200 && '...'}
+ </pre>
+ </div>
+ )}
+ </div>
+
+ {/* Panel Footer with Actions */}
+ <div
+ style={{
+ padding: '10px 12px',
+ backgroundColor: '#0F0F0F',
+ borderTop: '1px solid #2A2A2A',
+ display: 'flex',
+ gap: '8px',
+ }}
+ >
+ <button
+ onClick={onDelete}
+ style={{
+ flex: 1,
+ backgroundColor: 'transparent',
+ color: '#FF3B3B',
+ border: '1px solid #FF3B3B',
+ padding: '6px 8px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.3px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ transition: 'all 0.15s ease',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#FF3B3B';
+ e.currentTarget.style.color = '#000000';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = '#FF3B3B';
+ }}
+ >
+ <Trash2 size={10} />
+ DELETE
+ </button>
+ <button
+ onClick={onDuplicate}
+ style={{
+ flex: 1,
+ backgroundColor: '#FF8800',
+ color: '#000000',
+ border: '1px solid #FF8800',
+ padding: '6px 8px',
+ fontSize: '9px',
+ fontWeight: 700,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.3px',
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ transition: 'all 0.15s ease',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#FFA033';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = '#FF8800';
+ }}
+ >
+ <Plus size={10} />
+ DUPLICATE
+ </button>
+ </div>
+ </div>
+ );
+};
+
+export default NodeConfigPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/NodeEditorToolbar.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/NodeEditorToolbar.tsx
new file mode 100644
index 000000000..5028347d8
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/NodeEditorToolbar.tsx
@@ -0,0 +1,419 @@
+/**
+ * NodeEditorToolbar Component
+ *
+ * Toolbar for the node editor with actions like execute, save, import/export, etc.
+ */
+
+import React from 'react';
+import {
+ Plus,
+ Play,
+ Save,
+ Download,
+ Upload,
+ Trash2,
+ Rocket,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import type { NodeEditorToolbarProps } from '../types';
+
+const NodeEditorToolbar: React.FC<NodeEditorToolbarProps> = ({
+ activeView,
+ setActiveView,
+ showNodeMenu,
+ setShowNodeMenu,
+ isExecuting,
+ nodes,
+ edges,
+ selectedNodes,
+ workflowMode,
+ editingDraftId,
+ onExecute,
+ onClearWorkflow,
+ onSaveWorkflow,
+ onImportWorkflow,
+ onExportWorkflow,
+ onDeleteSelectedNodes,
+ onShowDeployDialog,
+ onQuickSaveDraft,
+}) => {
+ const { t } = useTranslation('nodeEditor');
+
+ return (
+ <div
+ style={{
+ backgroundColor: '#1a1a1a',
+ borderBottom: '1px solid #2d2d2d',
+ padding: '8px 12px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ flexWrap: 'wrap',
+ flexShrink: 0,
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span
+ style={{
+ color: '#ea580c',
+ fontSize: '12px',
+ fontWeight: 'bold',
+ letterSpacing: '0.5px',
+ }}
+ >
+ {t('title')}
+ </span>
+ <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }} />
+
+ {/* Tab Switcher */}
+ <button
+ onClick={() => setActiveView('editor')}
+ style={{
+ backgroundColor: activeView === 'editor' ? '#ea580c' : 'transparent',
+ color: activeView === 'editor' ? 'white' : '#a3a3a3',
+ border: activeView === 'editor' ? 'none' : '1px solid #404040',
+ padding: '4px 10px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ fontWeight: 'bold',
+ }}
+ >
+ {t('tabs.editor')}
+ </button>
+ <button
+ onClick={() => setActiveView('workflows')}
+ style={{
+ backgroundColor: activeView === 'workflows' ? '#ea580c' : 'transparent',
+ color: activeView === 'workflows' ? 'white' : '#a3a3a3',
+ border: activeView === 'workflows' ? 'none' : '1px solid #404040',
+ padding: '4px 10px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ fontWeight: 'bold',
+ }}
+ >
+ WORKFLOWS
+ </button>
+ </div>
+
+ {/* Editor-specific buttons */}
+ {activeView === 'editor' && (
+ <>
+ <button
+ onClick={() => setShowNodeMenu(!showNodeMenu)}
+ style={{
+ backgroundColor: '#ea580c',
+ color: 'white',
+ border: 'none',
+ padding: '6px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ fontWeight: 'bold',
+ }}
+ onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = '#dc2626')}
+ onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = '#ea580c')}
+ >
+ <Plus size={14} />
+ ADD NODE
+ </button>
+
+ <button
+ onClick={onExecute}
+ disabled={isExecuting}
+ style={{
+ backgroundColor: 'transparent',
+ color: isExecuting ? '#737373' : '#10b981',
+ border: `1px solid ${isExecuting ? '#737373' : '#10b981'}`,
+ padding: '6px 12px',
+ fontSize: '11px',
+ cursor: isExecuting ? 'not-allowed' : 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ opacity: isExecuting ? 0.5 : 1,
+ }}
+ onMouseEnter={(e) => {
+ if (!isExecuting) {
+ e.currentTarget.style.backgroundColor = '#10b981';
+ e.currentTarget.style.color = 'white';
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (!isExecuting) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = '#10b981';
+ }
+ }}
+ >
+ <Play size={14} />
+ {isExecuting ? 'EXECUTING...' : 'EXECUTE'}
+ </button>
+
+ <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }} />
+
+ {/* New Workflow Button */}
+ <button
+ onClick={() => {
+ if (window.confirm('Start a new workflow? Current work will be cleared unless saved.')) {
+ onClearWorkflow();
+ }
+ }}
+ style={{
+ backgroundColor: 'transparent',
+ color: '#3b82f6',
+ border: '1px solid #3b82f6',
+ padding: '6px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ fontWeight: 'bold',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#3b82f6';
+ e.currentTarget.style.color = 'white';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = '#3b82f6';
+ }}
+ title="Start a new workflow"
+ >
+ <Plus size={14} />
+ NEW
+ </button>
+
+ {/* Quick Save for Drafts */}
+ {workflowMode === 'draft' && editingDraftId && (
+ <button
+ onClick={onQuickSaveDraft}
+ style={{
+ backgroundColor: '#f59e0b',
+ color: 'white',
+ border: 'none',
+ padding: '6px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ fontWeight: 'bold',
+ }}
+ title="Quick save current draft"
+ >
+ <Save size={14} />
+ SAVE DRAFT
+ </button>
+ )}
+
+ <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }} />
+
+ <button
+ onClick={onSaveWorkflow}
+ style={{
+ backgroundColor: 'transparent',
+ color: '#a3a3a3',
+ border: '1px solid #404040',
+ padding: '6px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#2d2d2d';
+ e.currentTarget.style.color = 'white';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = '#a3a3a3';
+ }}
+ title="Save workflow to browser storage"
+ >
+ <Save size={14} />
+ SAVE
+ </button>
+
+ <button
+ onClick={onImportWorkflow}
+ style={{
+ backgroundColor: 'transparent',
+ color: '#a3a3a3',
+ border: '1px solid #404040',
+ padding: '6px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#2d2d2d';
+ e.currentTarget.style.color = 'white';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = '#a3a3a3';
+ }}
+ title="Import workflow from file"
+ >
+ <Upload size={14} />
+ IMPORT
+ </button>
+
+ <button
+ onClick={onExportWorkflow}
+ style={{
+ backgroundColor: 'transparent',
+ color: '#a3a3a3',
+ border: '1px solid #404040',
+ padding: '6px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#2d2d2d';
+ e.currentTarget.style.color = 'white';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = '#a3a3a3';
+ }}
+ >
+ <Download size={14} />
+ EXPORT
+ </button>
+
+ <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }} />
+
+ <button
+ onClick={() => {
+ if (window.confirm('Are you sure you want to clear all nodes? This cannot be undone.')) {
+ onClearWorkflow();
+ }
+ }}
+ style={{
+ backgroundColor: 'transparent',
+ color: '#ef4444',
+ border: '1px solid #ef4444',
+ padding: '6px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#ef4444';
+ e.currentTarget.style.color = 'white';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = '#ef4444';
+ }}
+ title="Clear all nodes and connections"
+ >
+ <Trash2 size={14} />
+ CLEAR ALL
+ </button>
+
+ {selectedNodes.length > 0 && (
+ <>
+ <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }} />
+ <button
+ onClick={onDeleteSelectedNodes}
+ style={{
+ backgroundColor: 'transparent',
+ color: '#ef4444',
+ border: '1px solid #ef4444',
+ padding: '6px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#ef4444';
+ e.currentTarget.style.color = 'white';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = '#ef4444';
+ }}
+ >
+ <Trash2 size={14} />
+ DELETE ({selectedNodes.length})
+ </button>
+ </>
+ )}
+
+ <div style={{ width: '1px', height: '20px', backgroundColor: '#404040' }} />
+
+ {/* DEPLOY Button */}
+ <button
+ onClick={onShowDeployDialog}
+ style={{
+ backgroundColor: 'transparent',
+ color: '#3b82f6',
+ border: '1px solid #3b82f6',
+ padding: '6px 12px',
+ fontSize: '11px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ fontWeight: 'bold',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#3b82f6';
+ e.currentTarget.style.color = 'white';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = '#3b82f6';
+ }}
+ title="Deploy workflow to database"
+ >
+ <Rocket size={14} />
+ DEPLOY
+ </button>
+
+ <div
+ style={{
+ marginLeft: 'auto',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ }}
+ >
+ <span style={{ color: '#737373', fontSize: '10px' }}>NODES: {nodes.length}</span>
+ <span style={{ color: '#737373', fontSize: '10px' }}>CONNECTIONS: {edges.length}</span>
+ </div>
+ </>
+ )}
+ </div>
+ );
+};
+
+export default NodeEditorToolbar;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/NodePalette.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/NodePalette.tsx
new file mode 100644
index 000000000..1d82045b6
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/NodePalette.tsx
@@ -0,0 +1,427 @@
+/**
+ * NodePalette Component
+ *
+ * Sidebar component for browsing and adding nodes to the workflow canvas
+ * Supports search, categories, and drag-and-drop
+ */
+
+import React, { useState, useMemo } from 'react';
+import { Database, Search, ChevronLeft, ChevronRight, Workflow } from 'lucide-react';
+import { NodeRegistry, INodeTypeDescription } from '@/services/nodeSystem';
+import { BUILTIN_NODE_CONFIGS, CATEGORY_CONFIG } from '../constants';
+import type { NodePaletteProps, PaletteNodeItem } from '../types';
+
+const NodePalette: React.FC<NodePaletteProps> = ({
+ onNodeAdd,
+ isCollapsed,
+ onToggleCollapse,
+ mcpNodeConfigs,
+ agentConfigs,
+}) => {
+ const [searchQuery, setSearchQuery] = useState('');
+ const [expandedCategories, setExpandedCategories] = useState<Set<string>>(
+ new Set(['Input', 'Processing', 'Output'])
+ );
+
+ // Get all registered nodes from NodeRegistry
+ const registryNodes = useMemo(() => {
+ try {
+ return NodeRegistry.getAllNodes();
+ } catch (e) {
+ console.warn('[NodePalette] NodeRegistry not initialized yet');
+ return [];
+ }
+ }, []);
+
+ // Combine builtin nodes with registry nodes
+ const allNodes = useMemo(() => {
+ const nodes: PaletteNodeItem[] = [];
+
+ // Add builtin UI nodes
+ BUILTIN_NODE_CONFIGS.forEach((config) => {
+ nodes.push({
+ id: config.type,
+ type: config.type,
+ label: config.label,
+ category: config.category,
+ color: config.color,
+ description: config.description,
+ source: 'builtin',
+ data: config,
+ });
+ });
+
+ // Add registry nodes
+ registryNodes.forEach((node: INodeTypeDescription) => {
+ const category = node.group?.[0] || 'Core';
+ const categoryConfig = CATEGORY_CONFIG[category] || CATEGORY_CONFIG['Core'];
+ nodes.push({
+ id: node.name,
+ type: 'registry-node',
+ label: node.displayName,
+ category,
+ color: node.defaults?.color || categoryConfig.color,
+ description: node.description || '',
+ source: 'registry',
+ data: node,
+ });
+ });
+
+ // Add MCP tool nodes
+ mcpNodeConfigs.forEach((config) => {
+ nodes.push({
+ id: config.id,
+ type: 'mcp-tool',
+ label: config.label,
+ category: 'MCP Tools',
+ color: '#ea580c',
+ description: `MCP: ${config.serverId}`,
+ source: 'mcp',
+ data: config,
+ });
+ });
+
+ // Add Python agent nodes
+ agentConfigs.forEach((agent) => {
+ nodes.push({
+ id: agent.id,
+ type: 'python-agent',
+ label: agent.name,
+ category: 'Python Agents',
+ color: agent.color || '#22c55e',
+ description: agent.description,
+ source: 'agent',
+ data: agent,
+ });
+ });
+
+ return nodes;
+ }, [registryNodes, mcpNodeConfigs, agentConfigs]);
+
+ // Group nodes by category
+ const nodesByCategory = useMemo(() => {
+ const grouped = new Map<string, PaletteNodeItem[]>();
+
+ allNodes.forEach((node) => {
+ if (!grouped.has(node.category)) {
+ grouped.set(node.category, []);
+ }
+ grouped.get(node.category)!.push(node);
+ });
+
+ // Sort each category alphabetically
+ grouped.forEach((nodes) => {
+ nodes.sort((a, b) => a.label.localeCompare(b.label));
+ });
+
+ return grouped;
+ }, [allNodes]);
+
+ // Filter by search
+ const filteredCategories = useMemo(() => {
+ if (!searchQuery.trim()) return nodesByCategory;
+
+ const query = searchQuery.toLowerCase();
+ const filtered = new Map<string, PaletteNodeItem[]>();
+
+ nodesByCategory.forEach((nodes, category) => {
+ const matching = nodes.filter(
+ (n) =>
+ n.label.toLowerCase().includes(query) ||
+ n.description.toLowerCase().includes(query) ||
+ n.id.toLowerCase().includes(query)
+ );
+ if (matching.length > 0) {
+ filtered.set(category, matching);
+ }
+ });
+
+ return filtered;
+ }, [nodesByCategory, searchQuery]);
+
+ const toggleCategory = (category: string) => {
+ const newExpanded = new Set(expandedCategories);
+ if (newExpanded.has(category)) {
+ newExpanded.delete(category);
+ } else {
+ newExpanded.add(category);
+ }
+ setExpandedCategories(newExpanded);
+ };
+
+ if (isCollapsed) {
+ return (
+ <div
+ style={{
+ width: '40px',
+ backgroundColor: '#0a0a0a',
+ borderRight: '1px solid #2d2d2d',
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ paddingTop: '8px',
+ }}
+ >
+ <button
+ onClick={onToggleCollapse}
+ style={{
+ backgroundColor: 'transparent',
+ border: 'none',
+ color: '#a3a3a3',
+ cursor: 'pointer',
+ padding: '8px',
+ }}
+ title="Expand palette"
+ >
+ <ChevronRight size={16} />
+ </button>
+ </div>
+ );
+ }
+
+ return (
+ <div
+ style={{
+ width: '280px',
+ backgroundColor: '#0a0a0a',
+ borderRight: '1px solid #2d2d2d',
+ display: 'flex',
+ flexDirection: 'column',
+ height: '100%',
+ }}
+ >
+ {/* Palette Header */}
+ <div
+ style={{
+ padding: '12px',
+ borderBottom: '1px solid #2d2d2d',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ }}
+ >
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ color: '#ea580c',
+ fontSize: '12px',
+ fontWeight: 'bold',
+ }}
+ >
+ <Database size={14} />
+ NODE PALETTE
+ </div>
+ <button
+ onClick={onToggleCollapse}
+ style={{
+ backgroundColor: 'transparent',
+ border: 'none',
+ color: '#6b7280',
+ cursor: 'pointer',
+ padding: '4px',
+ }}
+ title="Collapse palette"
+ >
+ <ChevronLeft size={14} />
+ </button>
+ </div>
+
+ {/* Search */}
+ <div style={{ padding: '8px 12px', borderBottom: '1px solid #2d2d2d' }}>
+ <div style={{ position: 'relative' }}>
+ <Search
+ size={14}
+ style={{
+ position: 'absolute',
+ left: '10px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ color: '#6b7280',
+ }}
+ />
+ <input
+ type="text"
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ placeholder="Search nodes..."
+ style={{
+ width: '100%',
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #2d2d2d',
+ borderRadius: '4px',
+ padding: '8px 8px 8px 32px',
+ color: '#fff',
+ fontSize: '11px',
+ outline: 'none',
+ }}
+ />
+ </div>
+ <div style={{ color: '#6b7280', fontSize: '10px', marginTop: '6px' }}>
+ {allNodes.length} nodes available
+ </div>
+ </div>
+
+ {/* Node Categories */}
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ {Array.from(filteredCategories.entries()).map(([category, categoryNodes]) => {
+ const catConfig = CATEGORY_CONFIG[category] || {
+ icon: <Workflow size={14} />,
+ color: '#6b7280',
+ };
+ const isExpanded = expandedCategories.has(category);
+
+ return (
+ <div key={category} style={{ borderBottom: '1px solid #1a1a1a' }}>
+ {/* Category Header */}
+ <button
+ onClick={() => toggleCategory(category)}
+ style={{
+ width: '100%',
+ padding: '10px 12px',
+ backgroundColor: 'transparent',
+ border: 'none',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ cursor: 'pointer',
+ color: '#d4d4d4',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: catConfig.color }}>{catConfig.icon}</span>
+ <span style={{ fontSize: '11px', fontWeight: 'bold' }}>{category}</span>
+ <span style={{ fontSize: '10px', color: '#6b7280' }}>
+ ({categoryNodes.length})
+ </span>
+ </div>
+ {isExpanded ? (
+ <ChevronRight size={12} style={{ transform: 'rotate(90deg)' }} />
+ ) : (
+ <ChevronRight size={12} />
+ )}
+ </button>
+
+ {/* Category Nodes */}
+ {isExpanded && (
+ <div style={{ padding: '4px 8px 8px' }}>
+ {categoryNodes.map((node) => (
+ <div
+ key={node.id}
+ onClick={() => onNodeAdd(node.type, node)}
+ draggable
+ onDragStart={(e) => {
+ e.dataTransfer.setData('application/reactflow', JSON.stringify(node));
+ e.dataTransfer.effectAllowed = 'move';
+ }}
+ style={{
+ backgroundColor: '#1a1a1a',
+ border: `1px solid ${node.color}30`,
+ borderRadius: '4px',
+ padding: '8px 10px',
+ marginBottom: '4px',
+ cursor: 'pointer',
+ transition: 'all 0.15s',
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = `${node.color}15`;
+ e.currentTarget.style.borderColor = `${node.color}60`;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = '#1a1a1a';
+ e.currentTarget.style.borderColor = `${node.color}30`;
+ }}
+ >
+ <div
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ }}
+ >
+ <div
+ style={{
+ width: '24px',
+ height: '24px',
+ borderRadius: '4px',
+ backgroundColor: `${node.color}20`,
+ border: `1px solid ${node.color}40`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: node.color,
+ fontSize: '10px',
+ fontWeight: 'bold',
+ }}
+ >
+ {node.label[0]}
+ </div>
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <div
+ style={{
+ color: node.color,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ }}
+ >
+ {node.label}
+ </div>
+ {node.description && (
+ <div
+ style={{
+ color: '#6b7280',
+ fontSize: '9px',
+ whiteSpace: 'nowrap',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ }}
+ >
+ {node.description.substring(0, 40)}
+ {node.description.length > 40 ? '...' : ''}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+ })}
+
+ {filteredCategories.size === 0 && (
+ <div
+ style={{
+ padding: '24px',
+ textAlign: 'center',
+ color: '#6b7280',
+ }}
+ >
+ <Search size={24} style={{ margin: '0 auto 8px', opacity: 0.5 }} />
+ <div style={{ fontSize: '11px' }}>No nodes found</div>
+ </div>
+ )}
+ </div>
+
+ {/* Palette Footer */}
+ <div
+ style={{
+ padding: '8px 12px',
+ borderTop: '1px solid #2d2d2d',
+ backgroundColor: '#0a0a0a',
+ }}
+ >
+ <div style={{ color: '#6b7280', fontSize: '9px', textAlign: 'center' }}>
+ Drag nodes to canvas or click to add
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default NodePalette;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/index.ts
new file mode 100644
index 000000000..4ad5d6bd5
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/components/index.ts
@@ -0,0 +1,11 @@
+/**
+ * AI Quant Lab - Components Index
+ *
+ * Export all components from the components folder
+ */
+
+export { default as CustomNode } from './CustomNode';
+export { default as NodePalette } from './NodePalette';
+export { default as NodeEditorToolbar } from './NodeEditorToolbar';
+export { default as DeployDialog } from './DeployDialog';
+export { default as NodeConfigPanel } from './NodeConfigPanel';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/constants.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/constants.ts
new file mode 100644
index 000000000..35aab8283
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/constants.ts
@@ -0,0 +1,140 @@
+/**
+ * AI Quant Lab - Constants and Configurations
+ *
+ * Node configurations, category settings, and other constants
+ */
+
+import React from 'react';
+import {
+ Database,
+ Zap,
+ Monitor,
+ Brain,
+ BarChart2,
+ Activity,
+ GitBranch,
+ Filter,
+ Shield,
+ Bell,
+ TrendingUp,
+ Workflow,
+} from 'lucide-react';
+import type { NodeConfig, CategoryConfig } from './types';
+
+// Built-in UI node configs (these have custom React components)
+export const BUILTIN_NODE_CONFIGS: NodeConfig[] = [
+ {
+ type: 'data-source',
+ label: 'Data Source',
+ color: '#3b82f6',
+ category: 'Input',
+ hasInput: false,
+ hasOutput: true,
+ description: 'Connect to databases and fetch data',
+ },
+ {
+ type: 'technical-indicator',
+ label: 'Technical Indicators',
+ color: '#10b981',
+ category: 'Processing',
+ hasInput: true,
+ hasOutput: true,
+ description: 'Calculate technical indicators on market data',
+ },
+ {
+ type: 'agent-mediator',
+ label: 'Agent Mediator',
+ color: '#8b5cf6',
+ category: 'AI',
+ hasInput: true,
+ hasOutput: true,
+ description: 'AI-powered data analysis and decision making',
+ },
+ {
+ type: 'results-display',
+ label: 'Results Display',
+ color: '#f59e0b',
+ category: 'Output',
+ hasInput: true,
+ hasOutput: false,
+ description: 'Display workflow results with formatting',
+ },
+ {
+ type: 'backtest',
+ label: 'Backtest',
+ color: '#06b6d4',
+ category: 'Analytics',
+ hasInput: true,
+ hasOutput: true,
+ description: 'Run backtests on trading strategies',
+ },
+ {
+ type: 'optimization',
+ label: 'Optimization',
+ color: '#a855f7',
+ category: 'Analytics',
+ hasInput: true,
+ hasOutput: true,
+ description: 'Optimize strategy parameters using grid/genetic algorithms',
+ },
+];
+
+// Category icons and colors for the palette
+export const CATEGORY_CONFIG: Record<string, CategoryConfig> = {
+ 'Core': { icon: React.createElement(Workflow, { size: 14 }), color: '#6b7280' },
+ 'Input': { icon: React.createElement(Database, { size: 14 }), color: '#3b82f6' },
+ 'Processing': { icon: React.createElement(Zap, { size: 14 }), color: '#10b981' },
+ 'Output': { icon: React.createElement(Monitor, { size: 14 }), color: '#f59e0b' },
+ 'AI': { icon: React.createElement(Brain, { size: 14 }), color: '#8b5cf6' },
+ 'Analytics': { icon: React.createElement(BarChart2, { size: 14 }), color: '#06b6d4' },
+ 'Market Data': { icon: React.createElement(Activity, { size: 14 }), color: '#22c55e' },
+ 'Control Flow': { icon: React.createElement(GitBranch, { size: 14 }), color: '#eab308' },
+ 'Transform': { icon: React.createElement(Filter, { size: 14 }), color: '#ec4899' },
+ 'Safety': { icon: React.createElement(Shield, { size: 14 }), color: '#ef4444' },
+ 'Notifications': { icon: React.createElement(Bell, { size: 14 }), color: '#f97316' },
+ 'Triggers': { icon: React.createElement(Zap, { size: 14 }), color: '#a855f7' },
+ 'Trading': { icon: React.createElement(TrendingUp, { size: 14 }), color: '#14b8a6' },
+ 'MCP Tools': { icon: React.createElement(Zap, { size: 14 }), color: '#ea580c' },
+ 'Python Agents': { icon: React.createElement(Brain, { size: 14 }), color: '#22c55e' },
+ // Lowercase variants for registry nodes
+ 'agents': { icon: React.createElement(Brain, { size: 14 }), color: '#8b5cf6' },
+ 'marketData': { icon: React.createElement(Activity, { size: 14 }), color: '#22c55e' },
+ 'trading': { icon: React.createElement(TrendingUp, { size: 14 }), color: '#14b8a6' },
+ 'triggers': { icon: React.createElement(Zap, { size: 14 }), color: '#a855f7' },
+ 'controlFlow': { icon: React.createElement(GitBranch, { size: 14 }), color: '#eab308' },
+ 'transform': { icon: React.createElement(Filter, { size: 14 }), color: '#ec4899' },
+ 'safety': { icon: React.createElement(Shield, { size: 14 }), color: '#ef4444' },
+ 'notifications': { icon: React.createElement(Bell, { size: 14 }), color: '#f97316' },
+ 'analytics': { icon: React.createElement(BarChart2, { size: 14 }), color: '#06b6d4' },
+};
+
+// Fincept color palette
+export const FINCEPT_COLORS = {
+ primary: '#FF8800',
+ orange: '#FFA500',
+ white: '#FFFFFF',
+ gray: '#787878',
+ darkBg: '#0a0a0a',
+ panelBg: '#1a1a1a',
+ border: '#2d2d2d',
+ green: '#10b981',
+ red: '#ef4444',
+ blue: '#3b82f6',
+ purple: '#8b5cf6',
+ cyan: '#06b6d4',
+ yellow: '#f59e0b',
+};
+
+// Default edge options for ReactFlow
+export const DEFAULT_EDGE_OPTIONS = {
+ animated: true,
+ style: { stroke: '#ea580c', strokeWidth: 2 },
+};
+
+// ReactFlow background settings
+export const FLOW_BACKGROUND_CONFIG = {
+ color: '#2d2d2d',
+ gap: 20,
+ size: 1,
+ style: { backgroundColor: '#0a0a0a' },
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/FFNAnalyticsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/FFNAnalyticsPanel.tsx
new file mode 100644
index 000000000..a35ce7a6a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/FFNAnalyticsPanel.tsx
@@ -0,0 +1,214 @@
+/**
+ * FFNAnalyticsPanel - Main Component
+ * Portfolio Performance Analysis
+ * Integrated with FFN library via PyO3
+ */
+
+import React from 'react';
+import { FINCEPT } from './constants';
+import { useFFNState } from './hooks';
+import {
+ LoadingState,
+ UnavailableState,
+ ErrorDisplay,
+ EmptyState,
+ DataSourceSection,
+ AnalysisModeSelector,
+ OptimizationMethodSelector,
+ BenchmarkInput,
+ PriceInputSection,
+ ConfigSection,
+ RunButton
+} from './components';
+import {
+ PerformanceResults,
+ DrawdownResults,
+ RiskResults,
+ MonthlyResults,
+ RollingResults,
+ ComparisonResults,
+ OptimizationResults,
+ BenchmarkResults
+} from './results';
+
+export function FFNAnalyticsPanel() {
+ const state = useFFNState();
+
+ // Loading state
+ if (state.isFFNAvailable === null) {
+ return <LoadingState />;
+ }
+
+ // Not available state
+ if (!state.isFFNAvailable) {
+ return <UnavailableState onRetry={state.checkFFNStatus} />;
+ }
+
+ const hasResults = state.analysisResult && (
+ state.analysisResult.performance ||
+ state.analysisResult.monthlyReturns ||
+ state.analysisResult.rollingMetrics ||
+ state.analysisResult.comparison ||
+ state.analysisResult.optimization ||
+ state.analysisResult.benchmark
+ );
+
+ return (
+ <div className="flex h-full" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ {/* Left Panel - Input */}
+ <div
+ className="w-80 flex flex-col border-r overflow-auto"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ >
+ {/* Data Source Section */}
+ <DataSourceSection
+ dataSourceType={state.dataSourceType}
+ setDataSourceType={state.setDataSourceType}
+ portfolios={state.portfolios}
+ selectedPortfolioId={state.selectedPortfolioId}
+ setSelectedPortfolioId={state.setSelectedPortfolioId}
+ symbolInput={state.symbolInput}
+ setSymbolInput={state.setSymbolInput}
+ symbolsInput={state.symbolsInput}
+ setSymbolsInput={state.setSymbolsInput}
+ analysisMode={state.analysisMode}
+ historicalDays={state.historicalDays}
+ setHistoricalDays={state.setHistoricalDays}
+ priceDataLoading={state.priceDataLoading}
+ fetchData={state.fetchData}
+ expanded={state.expandedSections.dataSource}
+ toggleSection={() => state.toggleSection('dataSource')}
+ />
+
+ {/* Analysis Mode */}
+ <AnalysisModeSelector
+ analysisMode={state.analysisMode}
+ setAnalysisMode={state.setAnalysisMode}
+ />
+
+ {/* Optimization Method Selector */}
+ {state.analysisMode === 'optimize' && (
+ <OptimizationMethodSelector
+ optimizationMethod={state.optimizationMethod}
+ setOptimizationMethod={state.setOptimizationMethod}
+ />
+ )}
+
+ {/* Benchmark Symbol Input */}
+ {state.analysisMode === 'benchmark' && (
+ <BenchmarkInput
+ benchmarkSymbol={state.benchmarkSymbol}
+ setBenchmarkSymbol={state.setBenchmarkSymbol}
+ />
+ )}
+
+ {/* Price Input (for manual mode) */}
+ {state.dataSourceType === 'manual' && (
+ <PriceInputSection
+ priceInput={state.priceInput}
+ setPriceInput={state.setPriceInput}
+ />
+ )}
+
+ {/* Config Options */}
+ <ConfigSection
+ config={state.config}
+ setConfig={state.setConfig}
+ />
+
+ {/* Run Button */}
+ <RunButton
+ isLoading={state.isLoading}
+ onClick={state.runAnalysis}
+ />
+ </div>
+
+ {/* Right Panel - Results */}
+ <div className="flex-1 overflow-auto p-4">
+ {state.error && <ErrorDisplay error={state.error} />}
+
+ {!hasResults && !state.error && (
+ <EmptyState analysisMode={state.analysisMode} />
+ )}
+
+ {state.analysisResult && (
+ <div className="space-y-4">
+ {/* Performance Metrics Section */}
+ {state.analysisResult.performance && (
+ <PerformanceResults
+ performance={state.analysisResult.performance}
+ expanded={state.expandedSections.performance}
+ toggleSection={() => state.toggleSection('performance')}
+ />
+ )}
+
+ {/* Drawdowns Section */}
+ {state.analysisResult.drawdowns && (
+ <DrawdownResults
+ drawdowns={state.analysisResult.drawdowns}
+ expanded={state.expandedSections.drawdowns}
+ toggleSection={() => state.toggleSection('drawdowns')}
+ />
+ )}
+
+ {/* Risk Metrics Section */}
+ {state.analysisResult.riskMetrics && (
+ <RiskResults
+ riskMetrics={state.analysisResult.riskMetrics}
+ expanded={state.expandedSections.risk}
+ toggleSection={() => state.toggleSection('risk')}
+ />
+ )}
+
+ {/* Monthly Returns Heatmap */}
+ {state.analysisResult.monthlyReturns && (
+ <MonthlyResults
+ monthlyReturns={state.analysisResult.monthlyReturns}
+ expanded={state.expandedSections.monthly}
+ toggleSection={() => state.toggleSection('monthly')}
+ />
+ )}
+
+ {/* Rolling Metrics */}
+ {state.analysisResult.rollingMetrics && (
+ <RollingResults
+ rollingMetrics={state.analysisResult.rollingMetrics}
+ expanded={state.expandedSections.rolling}
+ toggleSection={() => state.toggleSection('rolling')}
+ />
+ )}
+
+ {/* Asset Comparison */}
+ {state.analysisResult.comparison && state.analysisResult.comparison.success && (
+ <ComparisonResults
+ comparison={state.analysisResult.comparison}
+ expanded={state.expandedSections.comparison}
+ toggleSection={() => state.toggleSection('comparison')}
+ />
+ )}
+
+ {/* Portfolio Optimization Results */}
+ {state.analysisResult.optimization && state.analysisResult.optimization.success && (
+ <OptimizationResults
+ optimization={state.analysisResult.optimization}
+ expanded={state.expandedSections.optimization}
+ toggleSection={() => state.toggleSection('optimization')}
+ />
+ )}
+
+ {/* Benchmark Comparison Results */}
+ {state.analysisResult.benchmark && state.analysisResult.benchmark.success && (
+ <BenchmarkResults
+ benchmark={state.analysisResult.benchmark}
+ expanded={state.expandedSections.benchmark}
+ toggleSection={() => state.toggleSection('benchmark')}
+ />
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+export default FFNAnalyticsPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/AnalysisModeSelector.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/AnalysisModeSelector.tsx
new file mode 100644
index 000000000..13d7eaa85
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/AnalysisModeSelector.tsx
@@ -0,0 +1,61 @@
+/**
+ * AnalysisModeSelector Component
+ * Grid of analysis mode buttons
+ */
+
+import React from 'react';
+import {
+ Activity,
+ Calendar,
+ LineChart,
+ Layers,
+ Scale,
+ GitCompare
+} from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { AnalysisModeSelectorProps, AnalysisMode } from '../types';
+
+interface ModeOption {
+ mode: AnalysisMode;
+ label: string;
+ icon: React.ReactNode;
+}
+
+const MODE_OPTIONS: ModeOption[] = [
+ { mode: 'performance', label: 'Performance', icon: <Activity size={12} /> },
+ { mode: 'monthly', label: 'Monthly', icon: <Calendar size={12} /> },
+ { mode: 'rolling', label: 'Rolling', icon: <LineChart size={12} /> },
+ { mode: 'comparison', label: 'Compare', icon: <Layers size={12} /> },
+ { mode: 'optimize', label: 'Optimize', icon: <Scale size={12} /> },
+ { mode: 'benchmark', label: 'Benchmark', icon: <GitCompare size={12} /> }
+];
+
+export function AnalysisModeSelector({
+ analysisMode,
+ setAnalysisMode
+}: AnalysisModeSelectorProps) {
+ return (
+ <div className="px-2 py-2">
+ <label className="block text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
+ ANALYSIS MODE
+ </label>
+ <div className="grid grid-cols-2 gap-1">
+ {MODE_OPTIONS.map(({ mode, label, icon }) => (
+ <button
+ key={mode}
+ onClick={() => setAnalysisMode(mode)}
+ className="px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"
+ style={{
+ backgroundColor: analysisMode === mode ? FINCEPT.ORANGE : 'transparent',
+ color: analysisMode === mode ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ >
+ {icon}
+ {label}
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/BenchmarkInput.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/BenchmarkInput.tsx
new file mode 100644
index 000000000..fdeecea36
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/BenchmarkInput.tsx
@@ -0,0 +1,36 @@
+/**
+ * BenchmarkInput Component
+ * Input for benchmark symbol
+ */
+
+import React from 'react';
+import { FINCEPT, COMMON_BENCHMARKS } from '../constants';
+import type { BenchmarkInputProps } from '../types';
+
+export function BenchmarkInput({
+ benchmarkSymbol,
+ setBenchmarkSymbol
+}: BenchmarkInputProps) {
+ return (
+ <div className="px-2 py-2">
+ <label className="block text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
+ BENCHMARK SYMBOL
+ </label>
+ <input
+ type="text"
+ value={benchmarkSymbol}
+ onChange={(e) => setBenchmarkSymbol(e.target.value.toUpperCase())}
+ placeholder="SPY"
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ />
+ <p className="text-xs font-mono mt-1" style={{ color: FINCEPT.MUTED }}>
+ Common: {COMMON_BENCHMARKS.join(', ')}
+ </p>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/ConfigSection.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/ConfigSection.tsx
new file mode 100644
index 000000000..70fed9f79
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/ConfigSection.tsx
@@ -0,0 +1,53 @@
+/**
+ * ConfigSection Component
+ * Risk-free rate and drawdown threshold inputs
+ */
+
+import React from 'react';
+import { FINCEPT } from '../constants';
+import type { ConfigSectionProps } from '../types';
+
+export function ConfigSection({
+ config,
+ setConfig
+}: ConfigSectionProps) {
+ return (
+ <div className="p-2 space-y-3">
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ RISK-FREE RATE
+ </label>
+ <input
+ type="number"
+ step="0.01"
+ value={config.risk_free_rate}
+ onChange={(e) => setConfig({ ...config, risk_free_rate: parseFloat(e.target.value) || 0 })}
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ />
+ </div>
+
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ DRAWDOWN THRESHOLD
+ </label>
+ <input
+ type="number"
+ step="0.01"
+ value={config.drawdown_threshold}
+ onChange={(e) => setConfig({ ...config, drawdown_threshold: parseFloat(e.target.value) || 0.05 })}
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/DataSourceSection.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/DataSourceSection.tsx
new file mode 100644
index 000000000..dbcb9ebb5
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/DataSourceSection.tsx
@@ -0,0 +1,198 @@
+/**
+ * DataSourceSection Component
+ * Data source selection and configuration
+ */
+
+import React from 'react';
+import {
+ Database,
+ Briefcase,
+ Search,
+ RefreshCw,
+ ChevronUp,
+ ChevronDown
+} from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { DataSourceSectionProps } from '../types';
+
+export function DataSourceSection({
+ dataSourceType,
+ setDataSourceType,
+ portfolios,
+ selectedPortfolioId,
+ setSelectedPortfolioId,
+ symbolInput,
+ setSymbolInput,
+ symbolsInput,
+ setSymbolsInput,
+ analysisMode,
+ historicalDays,
+ setHistoricalDays,
+ priceDataLoading,
+ fetchData,
+ expanded,
+ toggleSection
+}: DataSourceSectionProps) {
+ const isMultiSymbolMode = analysisMode === 'comparison' || analysisMode === 'optimize';
+
+ return (
+ <div
+ className="rounded overflow-hidden m-2"
+ style={{ border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <button
+ onClick={toggleSection}
+ className="w-full px-3 py-2 flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <Database size={14} color={FINCEPT.CYAN} />
+ <span className="text-xs font-bold uppercase" style={{ color: FINCEPT.WHITE }}>
+ Data Source
+ </span>
+ </div>
+ {expanded ? (
+ <ChevronUp size={14} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={14} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expanded && (
+ <div className="p-3 space-y-3">
+ {/* Data source type buttons */}
+ <div className="flex gap-1">
+ <button
+ onClick={() => setDataSourceType('manual')}
+ className="flex-1 px-2 py-1.5 rounded text-xs font-mono"
+ style={{
+ backgroundColor: dataSourceType === 'manual' ? FINCEPT.ORANGE : 'transparent',
+ color: dataSourceType === 'manual' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ >
+ Manual
+ </button>
+ <button
+ onClick={() => setDataSourceType('portfolio')}
+ className="flex-1 px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"
+ style={{
+ backgroundColor: dataSourceType === 'portfolio' ? FINCEPT.ORANGE : 'transparent',
+ color: dataSourceType === 'portfolio' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ >
+ <Briefcase size={12} />
+ Portfolio
+ </button>
+ <button
+ onClick={() => setDataSourceType('symbol')}
+ className="flex-1 px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"
+ style={{
+ backgroundColor: dataSourceType === 'symbol' ? FINCEPT.ORANGE : 'transparent',
+ color: dataSourceType === 'symbol' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ >
+ <Search size={12} />
+ Symbol
+ </button>
+ </div>
+
+ {/* Portfolio selector */}
+ {dataSourceType === 'portfolio' && (
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ SELECT PORTFOLIO
+ </label>
+ <select
+ value={selectedPortfolioId}
+ onChange={(e) => setSelectedPortfolioId(e.target.value)}
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ >
+ {portfolios.map(p => (
+ <option key={p.id} value={p.id}>{p.name}</option>
+ ))}
+ </select>
+ </div>
+ )}
+
+ {/* Symbol input */}
+ {dataSourceType === 'symbol' && (
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ {isMultiSymbolMode ? 'SYMBOLS (comma-separated)' : 'SYMBOL'}
+ </label>
+ <input
+ type="text"
+ value={isMultiSymbolMode ? symbolsInput : symbolInput}
+ onChange={(e) => isMultiSymbolMode
+ ? setSymbolsInput(e.target.value.toUpperCase())
+ : setSymbolInput(e.target.value.toUpperCase())
+ }
+ placeholder={isMultiSymbolMode ? 'AAPL,MSFT,GOOGL' : 'AAPL'}
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ />
+ </div>
+ )}
+
+ {/* Historical days */}
+ {dataSourceType !== 'manual' && (
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ HISTORICAL DAYS
+ </label>
+ <input
+ type="number"
+ value={historicalDays}
+ onChange={(e) => setHistoricalDays(parseInt(e.target.value) || 365)}
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ />
+ </div>
+ )}
+
+ {/* Fetch data button */}
+ {dataSourceType !== 'manual' && (
+ <button
+ onClick={fetchData}
+ disabled={priceDataLoading}
+ className="w-full py-2 rounded text-xs font-bold uppercase flex items-center justify-center gap-2"
+ style={{
+ backgroundColor: FINCEPT.CYAN,
+ color: FINCEPT.DARK_BG,
+ opacity: priceDataLoading ? 0.5 : 1
+ }}
+ >
+ {priceDataLoading ? (
+ <>
+ <RefreshCw size={12} className="animate-spin" />
+ Loading...
+ </>
+ ) : (
+ <>
+ <Database size={12} />
+ Fetch Data
+ </>
+ )}
+ </button>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/EmptyState.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/EmptyState.tsx
new file mode 100644
index 000000000..b2eae1880
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/EmptyState.tsx
@@ -0,0 +1,35 @@
+/**
+ * EmptyState Component
+ * Displays when no analysis results are available
+ */
+
+import React from 'react';
+import { BarChart2 } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { AnalysisMode } from '../types';
+
+interface EmptyStateProps {
+ analysisMode: AnalysisMode;
+}
+
+const EMPTY_STATE_MESSAGES: Record<AnalysisMode, string> = {
+ performance: 'Enter price data and click "Run Analysis" to see performance metrics',
+ monthly: 'Click "Run Analysis" to see monthly returns heatmap',
+ rolling: 'Click "Run Analysis" to see rolling performance metrics',
+ comparison: 'Enter multiple symbols and click "Run Analysis" to compare assets',
+ optimize: 'Enter multiple symbols and click "Run Analysis" to optimize portfolio weights',
+ benchmark: 'Enter portfolio data and benchmark symbol, then click "Run Analysis" to compare against benchmark'
+};
+
+export function EmptyState({ analysisMode }: EmptyStateProps) {
+ return (
+ <div className="flex items-center justify-center h-full">
+ <div className="text-center">
+ <BarChart2 size={64} color={FINCEPT.MUTED} className="mx-auto mb-4" />
+ <p className="text-sm font-mono" style={{ color: FINCEPT.GRAY }}>
+ {EMPTY_STATE_MESSAGES[analysisMode]}
+ </p>
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/ErrorDisplay.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/ErrorDisplay.tsx
new file mode 100644
index 000000000..7086eeed4
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/ErrorDisplay.tsx
@@ -0,0 +1,24 @@
+/**
+ * ErrorDisplay Component
+ * Displays error messages
+ */
+
+import React from 'react';
+import { AlertCircle } from 'lucide-react';
+import { FINCEPT } from '../constants';
+
+interface ErrorDisplayProps {
+ error: string;
+}
+
+export function ErrorDisplay({ error }: ErrorDisplayProps) {
+ return (
+ <div
+ className="mb-4 p-4 rounded flex items-center gap-3"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, borderLeft: `3px solid ${FINCEPT.RED}` }}
+ >
+ <AlertCircle size={20} color={FINCEPT.RED} />
+ <span className="text-sm font-mono" style={{ color: FINCEPT.RED }}>{error}</span>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/LoadingState.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/LoadingState.tsx
new file mode 100644
index 000000000..a03be804a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/LoadingState.tsx
@@ -0,0 +1,16 @@
+/**
+ * LoadingState Component
+ * Displays loading spinner while checking FFN availability
+ */
+
+import React from 'react';
+import { RefreshCw } from 'lucide-react';
+import { FINCEPT } from '../constants';
+
+export function LoadingState() {
+ return (
+ <div className="flex items-center justify-center h-full" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <RefreshCw size={32} color={FINCEPT.ORANGE} className="animate-spin" />
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/MetricCard.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/MetricCard.tsx
new file mode 100644
index 000000000..5fb5a1952
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/MetricCard.tsx
@@ -0,0 +1,36 @@
+/**
+ * MetricCard Component
+ * Displays a single metric with icon, label, and value
+ */
+
+import React from 'react';
+import { FINCEPT } from '../constants';
+import type { MetricCardProps } from '../types';
+
+export function MetricCard({
+ label,
+ value,
+ color,
+ icon,
+ large = false
+}: MetricCardProps) {
+ return (
+ <div
+ className={`p-3 rounded ${large ? 'col-span-3' : ''}`}
+ style={{ backgroundColor: FINCEPT.DARK_BG }}
+ >
+ <div className="flex items-center gap-2 mb-1">
+ <span style={{ color: FINCEPT.GRAY }}>{icon}</span>
+ <span className="text-xs font-mono uppercase" style={{ color: FINCEPT.GRAY }}>
+ {label}
+ </span>
+ </div>
+ <span
+ className={`font-bold font-mono ${large ? 'text-2xl' : 'text-lg'}`}
+ style={{ color }}
+ >
+ {value}
+ </span>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/OptimizationMethodSelector.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/OptimizationMethodSelector.tsx
new file mode 100644
index 000000000..2944329db
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/OptimizationMethodSelector.tsx
@@ -0,0 +1,49 @@
+/**
+ * OptimizationMethodSelector Component
+ * Grid of optimization method buttons
+ */
+
+import React from 'react';
+import { FINCEPT } from '../constants';
+import type { OptimizationMethodSelectorProps, OptimizationMethod } from '../types';
+
+interface MethodOption {
+ method: OptimizationMethod;
+ label: string;
+}
+
+const METHOD_OPTIONS: MethodOption[] = [
+ { method: 'erc', label: 'ERC' },
+ { method: 'inv_vol', label: 'Inv Vol' },
+ { method: 'mean_var', label: 'Mean-Var' },
+ { method: 'equal', label: 'Equal Wt' }
+];
+
+export function OptimizationMethodSelector({
+ optimizationMethod,
+ setOptimizationMethod
+}: OptimizationMethodSelectorProps) {
+ return (
+ <div className="px-2 py-2">
+ <label className="block text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
+ OPTIMIZATION METHOD
+ </label>
+ <div className="grid grid-cols-2 gap-1">
+ {METHOD_OPTIONS.map(({ method, label }) => (
+ <button
+ key={method}
+ onClick={() => setOptimizationMethod(method)}
+ className="px-2 py-1.5 rounded text-xs font-mono"
+ style={{
+ backgroundColor: optimizationMethod === method ? FINCEPT.CYAN : 'transparent',
+ color: optimizationMethod === method ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/PriceInputSection.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/PriceInputSection.tsx
new file mode 100644
index 000000000..9077c1c48
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/PriceInputSection.tsx
@@ -0,0 +1,32 @@
+/**
+ * PriceInputSection Component
+ * Manual price data input textarea
+ */
+
+import React from 'react';
+import { FINCEPT } from '../constants';
+import type { PriceInputSectionProps } from '../types';
+
+export function PriceInputSection({
+ priceInput,
+ setPriceInput
+}: PriceInputSectionProps) {
+ return (
+ <div className="flex-1 p-2 overflow-auto">
+ <label className="block text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
+ PRICE DATA (JSON)
+ </label>
+ <textarea
+ value={priceInput}
+ onChange={(e) => setPriceInput(e.target.value)}
+ className="w-full h-48 p-3 rounded text-xs font-mono resize-none"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ placeholder='{"2023-01-01": 100, "2023-01-02": 101, ...}'
+ />
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/RunButton.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/RunButton.tsx
new file mode 100644
index 000000000..946ef32d6
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/RunButton.tsx
@@ -0,0 +1,38 @@
+/**
+ * RunButton Component
+ * Analysis run button
+ */
+
+import React from 'react';
+import { Activity, RefreshCw } from 'lucide-react';
+import { FINCEPT } from '../constants';
+
+interface RunButtonProps {
+ isLoading: boolean;
+ onClick: () => void;
+}
+
+export function RunButton({ isLoading, onClick }: RunButtonProps) {
+ return (
+ <div className="p-2 border-t" style={{ borderColor: FINCEPT.BORDER }}>
+ <button
+ onClick={onClick}
+ disabled={isLoading}
+ className="w-full py-3 rounded font-bold text-sm uppercase flex items-center justify-center gap-2 disabled:opacity-50"
+ style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
+ >
+ {isLoading ? (
+ <>
+ <RefreshCw size={16} className="animate-spin" />
+ ANALYZING...
+ </>
+ ) : (
+ <>
+ <Activity size={16} />
+ RUN ANALYSIS
+ </>
+ )}
+ </button>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/UnavailableState.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/UnavailableState.tsx
new file mode 100644
index 000000000..3c124679a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/UnavailableState.tsx
@@ -0,0 +1,39 @@
+/**
+ * UnavailableState Component
+ * Displays when FFN library is not installed
+ */
+
+import React from 'react';
+import { AlertCircle, RefreshCw } from 'lucide-react';
+import { FINCEPT } from '../constants';
+
+interface UnavailableStateProps {
+ onRetry: () => void;
+}
+
+export function UnavailableState({ onRetry }: UnavailableStateProps) {
+ return (
+ <div className="flex items-center justify-center h-full p-8" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <div className="text-center max-w-md">
+ <AlertCircle size={48} color={FINCEPT.RED} className="mx-auto mb-4" />
+ <h3 className="text-lg font-bold uppercase mb-2" style={{ color: FINCEPT.WHITE }}>
+ FFN Library Not Installed
+ </h3>
+ <code
+ className="block p-4 rounded text-sm font-mono mt-4"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.ORANGE }}
+ >
+ pip install ffn
+ </code>
+ <button
+ onClick={onRetry}
+ className="mt-6 px-6 py-2 rounded font-bold text-sm uppercase flex items-center gap-2 mx-auto"
+ style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
+ >
+ <RefreshCw size={14} />
+ Check Again
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/index.ts
new file mode 100644
index 000000000..c2a94d2c2
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/components/index.ts
@@ -0,0 +1,16 @@
+/**
+ * FFN Analytics Components Barrel Export
+ */
+
+export { MetricCard } from './MetricCard';
+export { LoadingState } from './LoadingState';
+export { UnavailableState } from './UnavailableState';
+export { ErrorDisplay } from './ErrorDisplay';
+export { EmptyState } from './EmptyState';
+export { DataSourceSection } from './DataSourceSection';
+export { AnalysisModeSelector } from './AnalysisModeSelector';
+export { OptimizationMethodSelector } from './OptimizationMethodSelector';
+export { BenchmarkInput } from './BenchmarkInput';
+export { PriceInputSection } from './PriceInputSection';
+export { ConfigSection } from './ConfigSection';
+export { RunButton } from './RunButton';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/constants.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/constants.ts
new file mode 100644
index 000000000..799a5ab26
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/constants.ts
@@ -0,0 +1,66 @@
+/**
+ * FFN Analytics Constants
+ * Color palette and sample data
+ */
+
+// Fincept Professional Color Palette
+export const FINCEPT = {
+ 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'
+};
+
+// Sample price data for demonstration
+export const SAMPLE_PRICES: Record<string, number> = {
+ '2023-01-03': 100.0,
+ '2023-01-04': 101.2,
+ '2023-01-05': 99.8,
+ '2023-01-06': 102.5,
+ '2023-01-09': 103.1,
+ '2023-01-10': 104.0,
+ '2023-01-11': 102.3,
+ '2023-01-12': 105.2,
+ '2023-01-13': 106.8,
+ '2023-01-17': 105.5,
+ '2023-01-18': 107.2,
+ '2023-01-19': 106.0,
+ '2023-01-20': 108.5,
+ '2023-01-23': 109.3,
+ '2023-01-24': 110.0,
+ '2023-01-25': 108.7,
+ '2023-01-26': 111.2,
+ '2023-01-27': 112.5,
+ '2023-01-30': 111.0,
+ '2023-01-31': 113.8
+};
+
+// Default configuration values
+export const DEFAULT_CONFIG = {
+ risk_free_rate: 0.02,
+ annualization_factor: 252,
+ drawdown_threshold: 0.05
+};
+
+// Default historical days
+export const DEFAULT_HISTORICAL_DAYS = 365;
+
+// Default benchmark symbol
+export const DEFAULT_BENCHMARK_SYMBOL = 'SPY';
+
+// Common benchmark symbols for suggestions
+export const COMMON_BENCHMARKS = ['SPY', 'QQQ', 'IWM', 'DIA'];
+
+// Month names for heatmap
+export const MONTH_NAMES = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/hooks/index.ts
new file mode 100644
index 000000000..3ddcffe97
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/hooks/index.ts
@@ -0,0 +1,5 @@
+/**
+ * FFN Analytics Hooks Barrel Export
+ */
+
+export { useFFNState } from './useFFNState';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/hooks/useFFNState.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/hooks/useFFNState.ts
new file mode 100644
index 000000000..4691c13d5
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/hooks/useFFNState.ts
@@ -0,0 +1,384 @@
+/**
+ * useFFNState Hook
+ * Manages all state for the FFN Analytics Panel
+ */
+
+import { useState, useEffect, useCallback } from 'react';
+import {
+ ffnService,
+ type PerformanceMetrics,
+ type FFNConfig
+} from '@/services/aiQuantLab/ffnService';
+import { portfolioService, type Portfolio } from '@/services/portfolio/portfolioService';
+import { yfinanceService } from '@/services/markets/yfinanceService';
+import { SAMPLE_PRICES, DEFAULT_CONFIG, DEFAULT_HISTORICAL_DAYS, DEFAULT_BENCHMARK_SYMBOL } from '../constants';
+import type {
+ DataSourceType,
+ AnalysisMode,
+ OptimizationMethod,
+ AnalysisResult,
+ ExpandedSections,
+ FFNState
+} from '../types';
+
+export function useFFNState(): FFNState {
+ // Status
+ const [isFFNAvailable, setIsFFNAvailable] = useState<boolean | null>(null);
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [analysisResult, setAnalysisResult] = useState<AnalysisResult | null>(null);
+ const [priceInput, setPriceInput] = useState(JSON.stringify(SAMPLE_PRICES, null, 2));
+
+ // Data source configuration
+ const [dataSourceType, setDataSourceType] = useState<DataSourceType>('manual');
+ const [portfolios, setPortfolios] = useState<Portfolio[]>([]);
+ const [selectedPortfolioId, setSelectedPortfolioId] = useState<string>('');
+ const [symbolInput, setSymbolInput] = useState('AAPL');
+ const [symbolsInput, setSymbolsInput] = useState('AAPL,MSFT,GOOGL');
+ const [historicalDays, setHistoricalDays] = useState(DEFAULT_HISTORICAL_DAYS);
+ const [priceDataLoading, setPriceDataLoading] = useState(false);
+
+ // Analysis mode
+ const [analysisMode, setAnalysisMode] = useState<AnalysisMode>('performance');
+
+ // Portfolio optimization settings
+ const [optimizationMethod, setOptimizationMethod] = useState<OptimizationMethod>('erc');
+
+ // Benchmark comparison settings
+ const [benchmarkSymbol, setBenchmarkSymbol] = useState(DEFAULT_BENCHMARK_SYMBOL);
+
+ // Config
+ const [config, setConfig] = useState<FFNConfig>(DEFAULT_CONFIG);
+
+ const [expandedSections, setExpandedSections] = useState<ExpandedSections>({
+ performance: true,
+ drawdowns: true,
+ risk: true,
+ monthly: true,
+ rolling: true,
+ comparison: true,
+ optimization: true,
+ benchmark: true,
+ dataSource: true
+ });
+
+ // Check FFN availability and load portfolios on mount
+ useEffect(() => {
+ checkFFNStatus();
+ loadPortfolios();
+ }, []);
+
+ const checkFFNStatus = async () => {
+ try {
+ const status = await ffnService.checkStatus();
+ setIsFFNAvailable(status.available);
+ if (!status.available) {
+ setError('FFN library not installed. Run: pip install ffn');
+ }
+ } catch (err) {
+ setIsFFNAvailable(false);
+ setError('Failed to check FFN status');
+ }
+ };
+
+ const loadPortfolios = async () => {
+ try {
+ const portfolioList = await portfolioService.getPortfolios();
+ setPortfolios(portfolioList);
+ if (portfolioList.length > 0) {
+ setSelectedPortfolioId(portfolioList[0].id);
+ }
+ } catch (err) {
+ console.error('Failed to load portfolios:', err);
+ }
+ };
+
+ // Fetch data based on source type
+ const fetchData = useCallback(async () => {
+ setPriceDataLoading(true);
+ setError(null);
+
+ try {
+ if (dataSourceType === 'portfolio' && selectedPortfolioId) {
+ const summary = await portfolioService.getPortfolioSummary(selectedPortfolioId);
+ if (!summary || !summary.holdings || summary.holdings.length === 0) {
+ setError('Portfolio has no holdings');
+ return;
+ }
+
+ // Fetch historical data for all holdings
+ const priceData: Record<string, Record<string, number>> = {};
+ const endDate = new Date();
+ const startDate = new Date();
+ startDate.setDate(startDate.getDate() - historicalDays);
+
+ for (const holding of summary.holdings) {
+ try {
+ const data = await yfinanceService.getHistoricalData(
+ holding.symbol,
+ startDate.toISOString().split('T')[0],
+ endDate.toISOString().split('T')[0]
+ );
+ if (data && data.length > 0) {
+ priceData[holding.symbol] = {};
+ data.forEach(point => {
+ const dateStr = new Date(point.timestamp * 1000).toISOString().split('T')[0];
+ priceData[holding.symbol][dateStr] = point.adj_close || point.close;
+ });
+ }
+ } catch (err) {
+ console.error(`Failed to fetch data for ${holding.symbol}:`, err);
+ }
+ }
+
+ if (Object.keys(priceData).length > 0) {
+ setPriceInput(JSON.stringify(priceData, null, 2));
+ } else {
+ setError('Failed to fetch historical data for portfolio');
+ }
+ } else if (dataSourceType === 'symbol') {
+ // Handle single symbol or multiple symbols based on analysis mode
+ const symbols = (analysisMode === 'comparison' || analysisMode === 'optimize')
+ ? symbolsInput.split(',').map(s => s.trim()).filter(Boolean)
+ : [symbolInput];
+
+ const endDate = new Date();
+ const startDate = new Date();
+ startDate.setDate(startDate.getDate() - historicalDays);
+
+ if (symbols.length === 1) {
+ // Single symbol - simple format
+ const data = await yfinanceService.getHistoricalData(
+ symbols[0],
+ startDate.toISOString().split('T')[0],
+ endDate.toISOString().split('T')[0]
+ );
+
+ if (data && data.length > 0) {
+ const priceData: Record<string, number> = {};
+ data.forEach(point => {
+ const dateStr = new Date(point.timestamp * 1000).toISOString().split('T')[0];
+ priceData[dateStr] = point.adj_close || point.close;
+ });
+ setPriceInput(JSON.stringify(priceData, null, 2));
+ } else {
+ setError(`No data available for ${symbols[0]}`);
+ }
+ } else {
+ // Multiple symbols - multi-asset format
+ const priceData: Record<string, Record<string, number>> = {};
+
+ for (const symbol of symbols) {
+ try {
+ const data = await yfinanceService.getHistoricalData(
+ symbol,
+ startDate.toISOString().split('T')[0],
+ endDate.toISOString().split('T')[0]
+ );
+ if (data && data.length > 0) {
+ priceData[symbol] = {};
+ data.forEach(point => {
+ const dateStr = new Date(point.timestamp * 1000).toISOString().split('T')[0];
+ priceData[symbol][dateStr] = point.adj_close || point.close;
+ });
+ }
+ } catch (err) {
+ console.error(`Failed to fetch data for ${symbol}:`, err);
+ }
+ }
+
+ if (Object.keys(priceData).length > 0) {
+ setPriceInput(JSON.stringify(priceData, null, 2));
+ } else {
+ setError('Failed to fetch data for any symbols');
+ }
+ }
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load data');
+ } finally {
+ setPriceDataLoading(false);
+ }
+ }, [dataSourceType, selectedPortfolioId, symbolInput, symbolsInput, historicalDays, analysisMode]);
+
+ const runAnalysis = async () => {
+ setIsLoading(true);
+ setError(null);
+
+ try {
+ const prices = JSON.parse(priceInput);
+
+ if (analysisMode === 'performance') {
+ // Run full analysis
+ const result = await ffnService.fullAnalysis(prices, config);
+ if (!result.success) {
+ setError(result.error || 'Analysis failed');
+ return;
+ }
+
+ // Get additional risk metrics
+ const riskResult = await ffnService.riskMetrics(prices, config.risk_free_rate);
+
+ setAnalysisResult({
+ performance: result.performance as PerformanceMetrics,
+ drawdowns: result.drawdowns,
+ riskMetrics: riskResult.success ? {
+ ulcer_index: riskResult.ulcer_index,
+ skewness: riskResult.skewness,
+ kurtosis: riskResult.kurtosis,
+ var_95: riskResult.var_95,
+ cvar_95: riskResult.cvar_95
+ } : undefined
+ });
+ } else if (analysisMode === 'monthly') {
+ // Monthly returns analysis
+ const result = await ffnService.monthlyReturns(prices);
+ if (!result.success) {
+ setError(result.error || 'Monthly returns analysis failed');
+ return;
+ }
+
+ setAnalysisResult({
+ monthlyReturns: result.monthly_returns
+ });
+ } else if (analysisMode === 'rolling') {
+ // Rolling metrics analysis
+ const result = await ffnService.calculateRollingMetrics(prices, 63, ['sharpe', 'volatility']);
+ if (!result.success) {
+ setError(result.error || 'Rolling metrics analysis failed');
+ return;
+ }
+
+ setAnalysisResult({
+ rollingMetrics: result.metrics
+ });
+ } else if (analysisMode === 'comparison') {
+ // Asset comparison
+ const result = await ffnService.compareAssets(prices, undefined, config.risk_free_rate);
+ if (!result.success) {
+ setError(result.error || 'Asset comparison failed');
+ return;
+ }
+
+ setAnalysisResult({
+ comparison: result
+ });
+ } else if (analysisMode === 'optimize') {
+ // Portfolio optimization
+ const result = await ffnService.portfolioOptimization(
+ prices,
+ optimizationMethod,
+ config.risk_free_rate,
+ [0, 1]
+ );
+ if (!result.success) {
+ setError(result.error || 'Portfolio optimization failed');
+ return;
+ }
+
+ setAnalysisResult({
+ optimization: result
+ });
+ } else if (analysisMode === 'benchmark') {
+ // Benchmark comparison
+ // Fetch benchmark data
+ const endDate = new Date();
+ const startDate = new Date();
+ startDate.setDate(startDate.getDate() - historicalDays);
+
+ const benchmarkData = await yfinanceService.getHistoricalData(
+ benchmarkSymbol,
+ startDate.toISOString().split('T')[0],
+ endDate.toISOString().split('T')[0]
+ );
+
+ if (!benchmarkData || benchmarkData.length === 0) {
+ setError(`No data available for benchmark ${benchmarkSymbol}`);
+ return;
+ }
+
+ // Convert to price format
+ const benchmarkPrices: Record<string, number> = {};
+ benchmarkData.forEach(point => {
+ const dateStr = new Date(point.timestamp * 1000).toISOString().split('T')[0];
+ benchmarkPrices[dateStr] = point.adj_close || point.close;
+ });
+
+ const result = await ffnService.benchmarkComparison(
+ prices,
+ benchmarkPrices,
+ benchmarkSymbol,
+ config.risk_free_rate
+ );
+
+ if (!result.success) {
+ setError(result.error || 'Benchmark comparison failed');
+ return;
+ }
+
+ setAnalysisResult({
+ benchmark: result
+ });
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Analysis failed');
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const toggleSection = (section: keyof ExpandedSections) => {
+ setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
+ };
+
+ return {
+ // Status
+ isFFNAvailable,
+ isLoading,
+ error,
+
+ // Data
+ priceInput,
+ setPriceInput,
+ analysisResult,
+
+ // Data source
+ dataSourceType,
+ setDataSourceType,
+ portfolios,
+ selectedPortfolioId,
+ setSelectedPortfolioId,
+ symbolInput,
+ setSymbolInput,
+ symbolsInput,
+ setSymbolsInput,
+ historicalDays,
+ setHistoricalDays,
+ priceDataLoading,
+
+ // Analysis mode
+ analysisMode,
+ setAnalysisMode,
+
+ // Optimization
+ optimizationMethod,
+ setOptimizationMethod,
+
+ // Benchmark
+ benchmarkSymbol,
+ setBenchmarkSymbol,
+
+ // Config
+ config,
+ setConfig,
+
+ // UI state
+ expandedSections,
+ toggleSection,
+
+ // Actions
+ checkFFNStatus,
+ fetchData,
+ runAnalysis
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/index.ts
new file mode 100644
index 000000000..2172bdf09
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/index.ts
@@ -0,0 +1,26 @@
+/**
+ * FFN Analytics Panel - Main Barrel Export
+ *
+ * Export all components, hooks, types, and utilities
+ */
+
+// Main component
+export { FFNAnalyticsPanel, default } from './FFNAnalyticsPanel';
+
+// Components
+export * from './components';
+
+// Results
+export * from './results';
+
+// Hooks
+export * from './hooks';
+
+// Types
+export * from './types';
+
+// Constants
+export * from './constants';
+
+// Utils
+export * from './utils';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/BenchmarkResults.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/BenchmarkResults.tsx
new file mode 100644
index 000000000..64fa443f4
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/BenchmarkResults.tsx
@@ -0,0 +1,219 @@
+/**
+ * BenchmarkResults Component
+ * Displays benchmark comparison results section
+ */
+
+import React from 'react';
+import {
+ GitCompare,
+ TrendingUp,
+ TrendingDown,
+ Activity,
+ Target,
+ LineChart,
+ BarChart2,
+ Calendar,
+ Briefcase,
+ ChevronUp,
+ ChevronDown
+} from 'lucide-react';
+import { FINCEPT } from '../constants';
+import { formatPercent, formatRatio, getValueColor } from '../utils';
+import { MetricCard } from '../components/MetricCard';
+import type { BenchmarkResultsProps } from '../types';
+
+export function BenchmarkResults({
+ benchmark,
+ expanded,
+ toggleSection
+}: BenchmarkResultsProps) {
+ if (!benchmark.success) return null;
+
+ return (
+ <div
+ className="rounded overflow-hidden"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <button
+ onClick={toggleSection}
+ className="w-full px-4 py-3 flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <GitCompare size={16} color={FINCEPT.PURPLE} />
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ Benchmark Comparison - {benchmark.benchmark_name || 'Benchmark'}
+ </span>
+ </div>
+ {expanded ? (
+ <ChevronUp size={16} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={16} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expanded && (
+ <div className="p-4 space-y-4">
+ {/* Side by Side Performance Comparison */}
+ <div className="grid grid-cols-2 gap-4">
+ {/* Portfolio Stats */}
+ <div>
+ <h4 className="text-xs font-mono mb-3 flex items-center gap-2" style={{ color: FINCEPT.CYAN }}>
+ <Briefcase size={14} />
+ PORTFOLIO
+ </h4>
+ <div className="space-y-2">
+ {benchmark.portfolio_stats && (
+ <>
+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Total Return</span>
+ <span className="text-xs font-mono font-bold" style={{ color: getValueColor(benchmark.portfolio_stats.total_return) }}>
+ {formatPercent(benchmark.portfolio_stats.total_return)}
+ </span>
+ </div>
+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>CAGR</span>
+ <span className="text-xs font-mono font-bold" style={{ color: getValueColor(benchmark.portfolio_stats.cagr) }}>
+ {formatPercent(benchmark.portfolio_stats.cagr)}
+ </span>
+ </div>
+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Volatility</span>
+ <span className="text-xs font-mono font-bold" style={{ color: FINCEPT.YELLOW }}>
+ {formatPercent(benchmark.portfolio_stats.volatility)}
+ </span>
+ </div>
+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Sharpe Ratio</span>
+ <span className="text-xs font-mono font-bold" style={{ color: getValueColor(benchmark.portfolio_stats.sharpe_ratio) }}>
+ {formatRatio(benchmark.portfolio_stats.sharpe_ratio)}
+ </span>
+ </div>
+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Max Drawdown</span>
+ <span className="text-xs font-mono font-bold" style={{ color: FINCEPT.RED }}>
+ {formatPercent(benchmark.portfolio_stats.max_drawdown)}
+ </span>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+
+ {/* Benchmark Stats */}
+ <div>
+ <h4 className="text-xs font-mono mb-3 flex items-center gap-2" style={{ color: FINCEPT.ORANGE }}>
+ <Target size={14} />
+ {benchmark.benchmark_name || 'BENCHMARK'}
+ </h4>
+ <div className="space-y-2">
+ {benchmark.benchmark_stats && (
+ <>
+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Total Return</span>
+ <span className="text-xs font-mono font-bold" style={{ color: getValueColor(benchmark.benchmark_stats.total_return) }}>
+ {formatPercent(benchmark.benchmark_stats.total_return)}
+ </span>
+ </div>
+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>CAGR</span>
+ <span className="text-xs font-mono font-bold" style={{ color: getValueColor(benchmark.benchmark_stats.cagr) }}>
+ {formatPercent(benchmark.benchmark_stats.cagr)}
+ </span>
+ </div>
+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Volatility</span>
+ <span className="text-xs font-mono font-bold" style={{ color: FINCEPT.YELLOW }}>
+ {formatPercent(benchmark.benchmark_stats.volatility)}
+ </span>
+ </div>
+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Sharpe Ratio</span>
+ <span className="text-xs font-mono font-bold" style={{ color: getValueColor(benchmark.benchmark_stats.sharpe_ratio) }}>
+ {formatRatio(benchmark.benchmark_stats.sharpe_ratio)}
+ </span>
+ </div>
+ <div className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>Max Drawdown</span>
+ <span className="text-xs font-mono font-bold" style={{ color: FINCEPT.RED }}>
+ {formatPercent(benchmark.benchmark_stats.max_drawdown)}
+ </span>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Relative Metrics */}
+ {benchmark.relative_metrics && (
+ <div>
+ <h4 className="text-xs font-mono mb-3" style={{ color: FINCEPT.GRAY }}>
+ RELATIVE METRICS
+ </h4>
+ <div className="grid grid-cols-4 gap-3">
+ <MetricCard
+ label="Alpha"
+ value={formatPercent(benchmark.relative_metrics.alpha)}
+ color={getValueColor(benchmark.relative_metrics.alpha)}
+ icon={<TrendingUp size={14} />}
+ />
+ <MetricCard
+ label="Beta"
+ value={formatRatio(benchmark.relative_metrics.beta)}
+ color={FINCEPT.CYAN}
+ icon={<Activity size={14} />}
+ />
+ <MetricCard
+ label="Correlation"
+ value={formatRatio(benchmark.relative_metrics.correlation)}
+ color={FINCEPT.BLUE}
+ icon={<LineChart size={14} />}
+ />
+ <MetricCard
+ label="Tracking Error"
+ value={formatPercent(benchmark.relative_metrics.tracking_error)}
+ color={FINCEPT.YELLOW}
+ icon={<Target size={14} />}
+ />
+ <MetricCard
+ label="Info Ratio"
+ value={formatRatio(benchmark.relative_metrics.information_ratio)}
+ color={getValueColor(benchmark.relative_metrics.information_ratio)}
+ icon={<BarChart2 size={14} />}
+ />
+ <MetricCard
+ label="Up Capture"
+ value={formatPercent(benchmark.relative_metrics.up_capture)}
+ color={FINCEPT.GREEN}
+ icon={<TrendingUp size={14} />}
+ />
+ <MetricCard
+ label="Down Capture"
+ value={formatPercent(benchmark.relative_metrics.down_capture)}
+ color={FINCEPT.RED}
+ icon={<TrendingDown size={14} />}
+ />
+ </div>
+ </div>
+ )}
+
+ {/* Date Range Info */}
+ {benchmark.date_range && (
+ <div className="flex items-center justify-between p-3 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <div className="flex items-center gap-2">
+ <Calendar size={14} color={FINCEPT.GRAY} />
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ {benchmark.date_range.start} to {benchmark.date_range.end}
+ </span>
+ </div>
+ <span className="text-xs font-mono" style={{ color: FINCEPT.MUTED }}>
+ {benchmark.date_range.data_points} data points
+ </span>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/ComparisonResults.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/ComparisonResults.tsx
new file mode 100644
index 000000000..005997e3a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/ComparisonResults.tsx
@@ -0,0 +1,130 @@
+/**
+ * ComparisonResults Component
+ * Displays asset comparison section with correlation matrix
+ */
+
+import React from 'react';
+import { Layers, ChevronUp, ChevronDown } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import { formatPercent, formatRatio, getValueColor } from '../utils';
+import type { ComparisonResultsProps } from '../types';
+
+export function ComparisonResults({
+ comparison,
+ expanded,
+ toggleSection
+}: ComparisonResultsProps) {
+ if (!comparison.success) return null;
+
+ return (
+ <div
+ className="rounded overflow-hidden"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <button
+ onClick={toggleSection}
+ className="w-full px-4 py-3 flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <Layers size={16} color={FINCEPT.BLUE} />
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ Asset Comparison
+ </span>
+ </div>
+ {expanded ? (
+ <ChevronUp size={16} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={16} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expanded && (
+ <div className="p-4 space-y-4">
+ {/* Correlation Matrix */}
+ {comparison.correlation_matrix && (
+ <div>
+ <h4 className="text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
+ CORRELATION MATRIX
+ </h4>
+ <div className="overflow-auto">
+ <table className="w-full text-xs font-mono">
+ <thead>
+ <tr>
+ <th className="p-2" style={{ color: FINCEPT.GRAY }}></th>
+ {Object.keys(comparison.correlation_matrix).map(symbol => (
+ <th key={symbol} className="p-2" style={{ color: FINCEPT.WHITE }}>
+ {symbol}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {Object.entries(comparison.correlation_matrix).map(([symbol, correlations]) => (
+ <tr key={symbol}>
+ <td className="p-2" style={{ color: FINCEPT.WHITE }}>{symbol}</td>
+ {Object.entries(correlations).map(([otherSymbol, corr]) => (
+ <td
+ key={otherSymbol}
+ className="p-2 text-center rounded"
+ style={{
+ backgroundColor: `rgba(0, 136, 255, ${Math.abs(corr)})`,
+ color: FINCEPT.WHITE
+ }}
+ >
+ {corr.toFixed(2)}
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ )}
+
+ {/* Asset Stats Comparison */}
+ {comparison.asset_stats && (
+ <div>
+ <h4 className="text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
+ PERFORMANCE COMPARISON
+ </h4>
+ <div className="overflow-auto">
+ <table className="w-full text-xs font-mono">
+ <thead>
+ <tr>
+ <th className="p-2 text-left" style={{ color: FINCEPT.GRAY }}>Asset</th>
+ <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>Return</th>
+ <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>Vol</th>
+ <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>Sharpe</th>
+ <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>MaxDD</th>
+ </tr>
+ </thead>
+ <tbody>
+ {Object.entries(comparison.asset_stats).map(([symbol, stats]) => (
+ <tr key={symbol} className="border-t" style={{ borderColor: FINCEPT.BORDER }}>
+ <td className="p-2" style={{ color: FINCEPT.WHITE }}>{symbol}</td>
+ <td className="p-2 text-right" style={{ color: getValueColor(stats.total_return) }}>
+ {formatPercent(stats.total_return)}
+ </td>
+ <td className="p-2 text-right" style={{ color: FINCEPT.YELLOW }}>
+ {formatPercent(stats.volatility)}
+ </td>
+ <td className="p-2 text-right" style={{ color: getValueColor(stats.sharpe_ratio) }}>
+ {formatRatio(stats.sharpe_ratio)}
+ </td>
+ <td className="p-2 text-right" style={{ color: FINCEPT.RED }}>
+ {formatPercent(stats.max_drawdown)}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/DrawdownResults.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/DrawdownResults.tsx
new file mode 100644
index 000000000..a963c7d93
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/DrawdownResults.tsx
@@ -0,0 +1,90 @@
+/**
+ * DrawdownResults Component
+ * Displays drawdown analysis section
+ */
+
+import React from 'react';
+import { TrendingDown, ChevronUp, ChevronDown } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import { formatPercent } from '../utils';
+import { MetricCard } from '../components/MetricCard';
+import type { DrawdownResultsProps } from '../types';
+
+export function DrawdownResults({
+ drawdowns,
+ expanded,
+ toggleSection
+}: DrawdownResultsProps) {
+ return (
+ <div
+ className="rounded overflow-hidden"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <button
+ onClick={toggleSection}
+ className="w-full px-4 py-3 flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <TrendingDown size={16} color={FINCEPT.RED} />
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ Drawdown Analysis
+ </span>
+ </div>
+ {expanded ? (
+ <ChevronUp size={16} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={16} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expanded && (
+ <div className="p-4">
+ <div className="mb-4">
+ <MetricCard
+ label="Max Drawdown"
+ value={formatPercent(drawdowns.max_drawdown)}
+ color={FINCEPT.RED}
+ icon={<TrendingDown size={14} />}
+ large
+ />
+ </div>
+
+ {drawdowns.top_drawdowns && drawdowns.top_drawdowns.length > 0 && (
+ <div>
+ <h4 className="text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
+ TOP DRAWDOWN PERIODS
+ </h4>
+ <div className="space-y-2">
+ {drawdowns.top_drawdowns.map((dd, idx) => (
+ <div
+ key={idx}
+ className="p-3 rounded flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.DARK_BG }}
+ >
+ <div className="flex items-center gap-3">
+ <span
+ className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold"
+ style={{ backgroundColor: FINCEPT.RED, color: FINCEPT.WHITE }}
+ >
+ {idx + 1}
+ </span>
+ <div>
+ <span className="text-xs font-mono" style={{ color: FINCEPT.WHITE }}>
+ {dd.start} → {dd.end}
+ </span>
+ </div>
+ </div>
+ <span className="text-sm font-bold" style={{ color: FINCEPT.RED }}>
+ {formatPercent(dd.drawdown)}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/MonthlyResults.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/MonthlyResults.tsx
new file mode 100644
index 000000000..f10fbe302
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/MonthlyResults.tsx
@@ -0,0 +1,83 @@
+/**
+ * MonthlyResults Component
+ * Displays monthly returns heatmap section
+ */
+
+import React from 'react';
+import { Calendar, ChevronUp, ChevronDown } from 'lucide-react';
+import { FINCEPT, MONTH_NAMES } from '../constants';
+import { getHeatmapColor } from '../utils';
+import type { MonthlyResultsProps } from '../types';
+
+export function MonthlyResults({
+ monthlyReturns,
+ expanded,
+ toggleSection
+}: MonthlyResultsProps) {
+ return (
+ <div
+ className="rounded overflow-hidden"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <button
+ onClick={toggleSection}
+ className="w-full px-4 py-3 flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <Calendar size={16} color={FINCEPT.CYAN} />
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ Monthly Returns Heatmap
+ </span>
+ </div>
+ {expanded ? (
+ <ChevronUp size={16} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={16} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expanded && (
+ <div className="p-4 overflow-auto">
+ <div className="min-w-[600px]">
+ {/* Month headers */}
+ <div className="flex">
+ <div className="w-16 text-xs font-mono text-center" style={{ color: FINCEPT.GRAY }}>
+ Year
+ </div>
+ {MONTH_NAMES.map(m => (
+ <div key={m} className="flex-1 text-xs font-mono text-center" style={{ color: FINCEPT.GRAY }}>
+ {m}
+ </div>
+ ))}
+ </div>
+ {/* Year rows */}
+ {Object.entries(monthlyReturns).sort().map(([year, months]) => (
+ <div key={year} className="flex mt-1">
+ <div className="w-16 text-xs font-mono text-center py-2" style={{ color: FINCEPT.WHITE }}>
+ {year}
+ </div>
+ {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].map(m => {
+ const value = months[String(m)] ?? null;
+ return (
+ <div
+ key={m}
+ className="flex-1 text-xs font-mono text-center py-2 mx-0.5 rounded"
+ style={{
+ backgroundColor: getHeatmapColor(value),
+ color: FINCEPT.WHITE
+ }}
+ title={value !== null ? `${(value * 100).toFixed(2)}%` : 'N/A'}
+ >
+ {value !== null ? `${(value * 100).toFixed(1)}` : '-'}
+ </div>
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/OptimizationResults.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/OptimizationResults.tsx
new file mode 100644
index 000000000..31716c12c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/OptimizationResults.tsx
@@ -0,0 +1,176 @@
+/**
+ * OptimizationResults Component
+ * Displays portfolio optimization results section
+ */
+
+import React from 'react';
+import {
+ Scale,
+ TrendingUp,
+ TrendingDown,
+ Activity,
+ Target,
+ ChevronUp,
+ ChevronDown
+} from 'lucide-react';
+import { FINCEPT } from '../constants';
+import { formatPercent, formatRatio, getValueColor } from '../utils';
+import { MetricCard } from '../components/MetricCard';
+import type { OptimizationResultsProps } from '../types';
+
+export function OptimizationResults({
+ optimization,
+ expanded,
+ toggleSection
+}: OptimizationResultsProps) {
+ if (!optimization.success) return null;
+
+ return (
+ <div
+ className="rounded overflow-hidden"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <button
+ onClick={toggleSection}
+ className="w-full px-4 py-3 flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <Scale size={16} color={FINCEPT.CYAN} />
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ Portfolio Optimization - {optimization.method}
+ </span>
+ </div>
+ {expanded ? (
+ <ChevronUp size={16} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={16} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expanded && (
+ <div className="p-4 space-y-4">
+ {/* Optimal Weights */}
+ {optimization.weights && (
+ <div>
+ <h4 className="text-xs font-mono mb-3" style={{ color: FINCEPT.GRAY }}>
+ OPTIMAL WEIGHTS
+ </h4>
+ <div className="space-y-2">
+ {Object.entries(optimization.weights)
+ .sort(([, a], [, b]) => b - a)
+ .map(([symbol, weight]) => (
+ <div key={symbol} className="flex items-center gap-3">
+ <span className="w-16 text-xs font-mono font-bold" style={{ color: FINCEPT.WHITE }}>
+ {symbol}
+ </span>
+ <div className="flex-1 h-6 rounded overflow-hidden" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <div
+ className="h-full rounded"
+ style={{
+ width: `${weight * 100}%`,
+ backgroundColor: FINCEPT.CYAN
+ }}
+ />
+ </div>
+ <span className="w-16 text-right text-xs font-mono font-bold" style={{ color: FINCEPT.CYAN }}>
+ {formatPercent(weight)}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Portfolio Stats */}
+ {optimization.portfolio_stats && (
+ <div>
+ <h4 className="text-xs font-mono mb-3" style={{ color: FINCEPT.GRAY }}>
+ OPTIMIZED PORTFOLIO METRICS
+ </h4>
+ <div className="grid grid-cols-3 gap-3">
+ <MetricCard
+ label="Expected Return"
+ value={formatPercent(optimization.portfolio_stats.total_return)}
+ color={getValueColor(optimization.portfolio_stats.total_return)}
+ icon={<TrendingUp size={14} />}
+ />
+ <MetricCard
+ label="CAGR"
+ value={formatPercent(optimization.portfolio_stats.cagr)}
+ color={getValueColor(optimization.portfolio_stats.cagr)}
+ icon={<TrendingUp size={14} />}
+ />
+ <MetricCard
+ label="Volatility"
+ value={formatPercent(optimization.portfolio_stats.volatility)}
+ color={FINCEPT.YELLOW}
+ icon={<Activity size={14} />}
+ />
+ <MetricCard
+ label="Sharpe Ratio"
+ value={formatRatio(optimization.portfolio_stats.sharpe_ratio)}
+ color={getValueColor(optimization.portfolio_stats.sharpe_ratio)}
+ icon={<Target size={14} />}
+ />
+ <MetricCard
+ label="Sortino Ratio"
+ value={formatRatio(optimization.portfolio_stats.sortino_ratio)}
+ color={getValueColor(optimization.portfolio_stats.sortino_ratio)}
+ icon={<Target size={14} />}
+ />
+ <MetricCard
+ label="Max Drawdown"
+ value={formatPercent(optimization.portfolio_stats.max_drawdown)}
+ color={FINCEPT.RED}
+ icon={<TrendingDown size={14} />}
+ />
+ </div>
+ </div>
+ )}
+
+ {/* Asset Contributions */}
+ {optimization.asset_contributions && (
+ <div>
+ <h4 className="text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
+ ASSET CONTRIBUTIONS
+ </h4>
+ <div className="overflow-auto">
+ <table className="w-full text-xs font-mono">
+ <thead>
+ <tr>
+ <th className="p-2 text-left" style={{ color: FINCEPT.GRAY }}>Asset</th>
+ <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>Weight</th>
+ <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>Vol</th>
+ <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>Return</th>
+ <th className="p-2 text-right" style={{ color: FINCEPT.GRAY }}>Risk Contrib</th>
+ </tr>
+ </thead>
+ <tbody>
+ {Object.entries(optimization.asset_contributions).map(([symbol, contrib]) => (
+ <tr key={symbol} className="border-t" style={{ borderColor: FINCEPT.BORDER }}>
+ <td className="p-2" style={{ color: FINCEPT.WHITE }}>{symbol}</td>
+ <td className="p-2 text-right" style={{ color: FINCEPT.CYAN }}>
+ {formatPercent(contrib.weight)}
+ </td>
+ <td className="p-2 text-right" style={{ color: FINCEPT.YELLOW }}>
+ {formatPercent(contrib.volatility)}
+ </td>
+ <td className="p-2 text-right" style={{ color: getValueColor(contrib.return) }}>
+ {formatPercent(contrib.return)}
+ </td>
+ <td className="p-2 text-right" style={{ color: FINCEPT.PURPLE }}>
+ {formatPercent(contrib.risk_contribution)}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/PerformanceResults.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/PerformanceResults.tsx
new file mode 100644
index 000000000..dd3bb7aaf
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/PerformanceResults.tsx
@@ -0,0 +1,111 @@
+/**
+ * PerformanceResults Component
+ * Displays performance metrics section
+ */
+
+import React from 'react';
+import {
+ TrendingUp,
+ TrendingDown,
+ Activity,
+ BarChart2,
+ LineChart,
+ Percent,
+ Target,
+ ChevronUp,
+ ChevronDown
+} from 'lucide-react';
+import { FINCEPT } from '../constants';
+import { formatPercent, formatRatio, getValueColor } from '../utils';
+import { MetricCard } from '../components/MetricCard';
+import type { PerformanceResultsProps } from '../types';
+
+export function PerformanceResults({
+ performance,
+ expanded,
+ toggleSection
+}: PerformanceResultsProps) {
+ return (
+ <div
+ className="rounded overflow-hidden"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <button
+ onClick={toggleSection}
+ className="w-full px-4 py-3 flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <TrendingUp size={16} color={FINCEPT.GREEN} />
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ Performance Metrics
+ </span>
+ </div>
+ {expanded ? (
+ <ChevronUp size={16} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={16} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expanded && (
+ <div className="p-4 grid grid-cols-3 gap-4">
+ <MetricCard
+ label="Total Return"
+ value={formatPercent(performance.total_return)}
+ color={getValueColor(performance.total_return)}
+ icon={<Percent size={14} />}
+ />
+ <MetricCard
+ label="CAGR"
+ value={formatPercent(performance.cagr)}
+ color={getValueColor(performance.cagr)}
+ icon={<TrendingUp size={14} />}
+ />
+ <MetricCard
+ label="Sharpe Ratio"
+ value={formatRatio(performance.sharpe_ratio)}
+ color={getValueColor(performance.sharpe_ratio)}
+ icon={<Target size={14} />}
+ />
+ <MetricCard
+ label="Sortino Ratio"
+ value={formatRatio(performance.sortino_ratio)}
+ color={getValueColor(performance.sortino_ratio)}
+ icon={<Target size={14} />}
+ />
+ <MetricCard
+ label="Volatility"
+ value={formatPercent(performance.volatility)}
+ color={FINCEPT.YELLOW}
+ icon={<Activity size={14} />}
+ />
+ <MetricCard
+ label="Calmar Ratio"
+ value={formatRatio(performance.calmar_ratio)}
+ color={getValueColor(performance.calmar_ratio)}
+ icon={<BarChart2 size={14} />}
+ />
+ <MetricCard
+ label="Best Day"
+ value={formatPercent(performance.best_day)}
+ color={FINCEPT.GREEN}
+ icon={<TrendingUp size={14} />}
+ />
+ <MetricCard
+ label="Worst Day"
+ value={formatPercent(performance.worst_day)}
+ color={FINCEPT.RED}
+ icon={<TrendingDown size={14} />}
+ />
+ <MetricCard
+ label="Daily Mean"
+ value={formatPercent(performance.daily_mean, 4)}
+ color={getValueColor(performance.daily_mean)}
+ icon={<LineChart size={14} />}
+ />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/RiskResults.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/RiskResults.tsx
new file mode 100644
index 000000000..171cb1cc1
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/RiskResults.tsx
@@ -0,0 +1,84 @@
+/**
+ * RiskResults Component
+ * Displays risk metrics section
+ */
+
+import React from 'react';
+import {
+ AlertCircle,
+ Activity,
+ BarChart2,
+ TrendingDown,
+ ChevronUp,
+ ChevronDown
+} from 'lucide-react';
+import { FINCEPT } from '../constants';
+import { formatPercent, formatRatio } from '../utils';
+import { MetricCard } from '../components/MetricCard';
+import type { RiskResultsProps } from '../types';
+
+export function RiskResults({
+ riskMetrics,
+ expanded,
+ toggleSection
+}: RiskResultsProps) {
+ return (
+ <div
+ className="rounded overflow-hidden"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <button
+ onClick={toggleSection}
+ className="w-full px-4 py-3 flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <AlertCircle size={16} color={FINCEPT.YELLOW} />
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ Risk Metrics
+ </span>
+ </div>
+ {expanded ? (
+ <ChevronUp size={16} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={16} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expanded && (
+ <div className="p-4 grid grid-cols-3 gap-4">
+ <MetricCard
+ label="Ulcer Index"
+ value={formatRatio(riskMetrics.ulcer_index, 4)}
+ color={FINCEPT.YELLOW}
+ icon={<Activity size={14} />}
+ />
+ <MetricCard
+ label="Skewness"
+ value={formatRatio(riskMetrics.skewness)}
+ color={FINCEPT.CYAN}
+ icon={<BarChart2 size={14} />}
+ />
+ <MetricCard
+ label="Kurtosis"
+ value={formatRatio(riskMetrics.kurtosis)}
+ color={FINCEPT.CYAN}
+ icon={<BarChart2 size={14} />}
+ />
+ <MetricCard
+ label="VaR (95%)"
+ value={formatPercent(riskMetrics.var_95)}
+ color={FINCEPT.RED}
+ icon={<TrendingDown size={14} />}
+ />
+ <MetricCard
+ label="CVaR (95%)"
+ value={formatPercent(riskMetrics.cvar_95)}
+ color={FINCEPT.RED}
+ icon={<TrendingDown size={14} />}
+ />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/RollingResults.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/RollingResults.tsx
new file mode 100644
index 000000000..ed076335d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/RollingResults.tsx
@@ -0,0 +1,89 @@
+/**
+ * RollingResults Component
+ * Displays rolling metrics charts section
+ */
+
+import React from 'react';
+import { LineChart, ChevronUp, ChevronDown } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { RollingResultsProps } from '../types';
+
+export function RollingResults({
+ rollingMetrics,
+ expanded,
+ toggleSection
+}: RollingResultsProps) {
+ return (
+ <div
+ className="rounded overflow-hidden"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <button
+ onClick={toggleSection}
+ className="w-full px-4 py-3 flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <LineChart size={16} color={FINCEPT.PURPLE} />
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ Rolling Metrics (63-Day)
+ </span>
+ </div>
+ {expanded ? (
+ <ChevronUp size={16} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={16} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expanded && (
+ <div className="p-4">
+ {rollingMetrics.rolling_sharpe && (
+ <div className="mb-4">
+ <h4 className="text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
+ ROLLING SHARPE RATIO
+ </h4>
+ <div className="h-32 flex items-end gap-px">
+ {Object.values(rollingMetrics.rolling_sharpe).slice(-50).map((value, idx) => {
+ const height = Math.min(100, Math.max(10, ((value + 2) / 4) * 100));
+ return (
+ <div
+ key={idx}
+ className="flex-1 rounded-t"
+ style={{
+ height: `${height}%`,
+ backgroundColor: value > 0 ? FINCEPT.GREEN : FINCEPT.RED
+ }}
+ />
+ );
+ })}
+ </div>
+ </div>
+ )}
+ {rollingMetrics.rolling_volatility && (
+ <div>
+ <h4 className="text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
+ ROLLING VOLATILITY
+ </h4>
+ <div className="h-32 flex items-end gap-px">
+ {Object.values(rollingMetrics.rolling_volatility).slice(-50).map((value, idx) => {
+ const height = Math.min(100, Math.max(10, (value / 0.5) * 100));
+ return (
+ <div
+ key={idx}
+ className="flex-1 rounded-t"
+ style={{
+ height: `${height}%`,
+ backgroundColor: FINCEPT.YELLOW
+ }}
+ />
+ );
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/index.ts
new file mode 100644
index 000000000..d42e70830
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/results/index.ts
@@ -0,0 +1,12 @@
+/**
+ * FFN Analytics Results Barrel Export
+ */
+
+export { PerformanceResults } from './PerformanceResults';
+export { DrawdownResults } from './DrawdownResults';
+export { RiskResults } from './RiskResults';
+export { MonthlyResults } from './MonthlyResults';
+export { RollingResults } from './RollingResults';
+export { ComparisonResults } from './ComparisonResults';
+export { OptimizationResults } from './OptimizationResults';
+export { BenchmarkResults } from './BenchmarkResults';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/types.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/types.ts
new file mode 100644
index 000000000..ca5c87f41
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/types.ts
@@ -0,0 +1,235 @@
+/**
+ * FFN Analytics Types
+ * TypeScript interfaces and types
+ */
+
+import type {
+ PerformanceMetrics,
+ DrawdownInfo,
+ FFNConfig,
+ AssetComparisonResponse,
+ PortfolioOptimizationResponse,
+ BenchmarkComparisonResponse
+} from '@/services/aiQuantLab/ffnService';
+import type { Portfolio } from '@/services/portfolio/portfolioService';
+import type { ReactNode } from 'react';
+
+// Data source types
+export type DataSourceType = 'manual' | 'portfolio' | 'symbol';
+
+// Analysis mode types
+export type AnalysisMode = 'performance' | 'comparison' | 'monthly' | 'rolling' | 'optimize' | 'benchmark';
+
+// Optimization method types
+export type OptimizationMethod = 'erc' | 'inv_vol' | 'mean_var' | 'equal';
+
+// Risk metrics interface
+export interface RiskMetrics {
+ ulcer_index?: number;
+ skewness?: number;
+ kurtosis?: number;
+ var_95?: number;
+ cvar_95?: number;
+}
+
+// Rolling metrics interface
+export interface RollingMetrics {
+ rolling_sharpe?: Record<string, number>;
+ rolling_volatility?: Record<string, number>;
+}
+
+// Drawdowns result interface
+export interface DrawdownsResult {
+ max_drawdown: number;
+ top_drawdowns: DrawdownInfo[];
+}
+
+// Monthly returns type
+export type MonthlyReturns = Record<string, Record<string, number | null>>;
+
+// Main analysis result interface
+export interface AnalysisResult {
+ performance?: PerformanceMetrics;
+ drawdowns?: DrawdownsResult;
+ riskMetrics?: RiskMetrics;
+ monthlyReturns?: MonthlyReturns;
+ rollingMetrics?: RollingMetrics;
+ comparison?: AssetComparisonResponse;
+ optimization?: PortfolioOptimizationResponse;
+ benchmark?: BenchmarkComparisonResponse;
+}
+
+// Expanded sections state
+export interface ExpandedSections {
+ performance: boolean;
+ drawdowns: boolean;
+ risk: boolean;
+ monthly: boolean;
+ rolling: boolean;
+ comparison: boolean;
+ optimization: boolean;
+ benchmark: boolean;
+ dataSource: boolean;
+}
+
+// FFN State interface - returned by useFFFNState hook
+export interface FFNState {
+ // Status
+ isFFNAvailable: boolean | null;
+ isLoading: boolean;
+ error: string | null;
+
+ // Data
+ priceInput: string;
+ setPriceInput: (value: string) => void;
+ analysisResult: AnalysisResult | null;
+
+ // Data source
+ dataSourceType: DataSourceType;
+ setDataSourceType: (type: DataSourceType) => void;
+ portfolios: Portfolio[];
+ selectedPortfolioId: string;
+ setSelectedPortfolioId: (id: string) => void;
+ symbolInput: string;
+ setSymbolInput: (symbol: string) => void;
+ symbolsInput: string;
+ setSymbolsInput: (symbols: string) => void;
+ historicalDays: number;
+ setHistoricalDays: (days: number) => void;
+ priceDataLoading: boolean;
+
+ // Analysis mode
+ analysisMode: AnalysisMode;
+ setAnalysisMode: (mode: AnalysisMode) => void;
+
+ // Optimization
+ optimizationMethod: OptimizationMethod;
+ setOptimizationMethod: (method: OptimizationMethod) => void;
+
+ // Benchmark
+ benchmarkSymbol: string;
+ setBenchmarkSymbol: (symbol: string) => void;
+
+ // Config
+ config: FFNConfig;
+ setConfig: (config: FFNConfig) => void;
+
+ // UI state
+ expandedSections: ExpandedSections;
+ toggleSection: (section: keyof ExpandedSections) => void;
+
+ // Actions
+ checkFFNStatus: () => Promise<void>;
+ fetchData: () => Promise<void>;
+ runAnalysis: () => Promise<void>;
+}
+
+// Component Props
+
+// MetricCard props
+export interface MetricCardProps {
+ label: string;
+ value: string;
+ color: string;
+ icon: ReactNode;
+ large?: boolean;
+}
+
+// DataSourceSection props
+export interface DataSourceSectionProps {
+ dataSourceType: DataSourceType;
+ setDataSourceType: (type: DataSourceType) => void;
+ portfolios: Portfolio[];
+ selectedPortfolioId: string;
+ setSelectedPortfolioId: (id: string) => void;
+ symbolInput: string;
+ setSymbolInput: (symbol: string) => void;
+ symbolsInput: string;
+ setSymbolsInput: (symbols: string) => void;
+ analysisMode: AnalysisMode;
+ historicalDays: number;
+ setHistoricalDays: (days: number) => void;
+ priceDataLoading: boolean;
+ fetchData: () => void;
+ expanded: boolean;
+ toggleSection: () => void;
+}
+
+// AnalysisModeSelector props
+export interface AnalysisModeSelectorProps {
+ analysisMode: AnalysisMode;
+ setAnalysisMode: (mode: AnalysisMode) => void;
+}
+
+// OptimizationMethodSelector props
+export interface OptimizationMethodSelectorProps {
+ optimizationMethod: OptimizationMethod;
+ setOptimizationMethod: (method: OptimizationMethod) => void;
+}
+
+// BenchmarkInput props
+export interface BenchmarkInputProps {
+ benchmarkSymbol: string;
+ setBenchmarkSymbol: (symbol: string) => void;
+}
+
+// ConfigSection props
+export interface ConfigSectionProps {
+ config: FFNConfig;
+ setConfig: (config: FFNConfig) => void;
+}
+
+// PriceInputSection props
+export interface PriceInputSectionProps {
+ priceInput: string;
+ setPriceInput: (value: string) => void;
+}
+
+// Result section props
+export interface PerformanceResultsProps {
+ performance: PerformanceMetrics;
+ expanded: boolean;
+ toggleSection: () => void;
+}
+
+export interface DrawdownResultsProps {
+ drawdowns: DrawdownsResult;
+ expanded: boolean;
+ toggleSection: () => void;
+}
+
+export interface RiskResultsProps {
+ riskMetrics: RiskMetrics;
+ expanded: boolean;
+ toggleSection: () => void;
+}
+
+export interface MonthlyResultsProps {
+ monthlyReturns: MonthlyReturns;
+ expanded: boolean;
+ toggleSection: () => void;
+}
+
+export interface RollingResultsProps {
+ rollingMetrics: RollingMetrics;
+ expanded: boolean;
+ toggleSection: () => void;
+}
+
+export interface ComparisonResultsProps {
+ comparison: AssetComparisonResponse;
+ expanded: boolean;
+ toggleSection: () => void;
+}
+
+export interface OptimizationResultsProps {
+ optimization: PortfolioOptimizationResponse;
+ expanded: boolean;
+ toggleSection: () => void;
+}
+
+export interface BenchmarkResultsProps {
+ benchmark: BenchmarkComparisonResponse;
+ expanded: boolean;
+ toggleSection: () => void;
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/utils/formatters.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/utils/formatters.ts
new file mode 100644
index 000000000..352a5e3d2
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/utils/formatters.ts
@@ -0,0 +1,56 @@
+/**
+ * FFN Analytics Formatters
+ * Utility functions for formatting values
+ */
+
+import { FINCEPT } from '../constants';
+
+/**
+ * Format a number as percentage
+ */
+export function formatPercent(value: number | null | undefined, decimals = 2): string {
+ if (value === null || value === undefined || isNaN(value)) return 'N/A';
+ return `${(value * 100).toFixed(decimals)}%`;
+}
+
+/**
+ * Format a number as ratio
+ */
+export function formatRatio(value: number | null | undefined, decimals = 2): string {
+ if (value === null || value === undefined || isNaN(value)) return 'N/A';
+ return value.toFixed(decimals);
+}
+
+/**
+ * Get color based on value (positive = green, negative = red)
+ */
+export function getValueColor(value: number | null | undefined, inverse = false): string {
+ if (value === null || value === undefined) return FINCEPT.GRAY;
+ if (inverse) return value < 0 ? FINCEPT.GREEN : value > 0 ? FINCEPT.RED : FINCEPT.WHITE;
+ return value > 0 ? FINCEPT.GREEN : value < 0 ? FINCEPT.RED : FINCEPT.WHITE;
+}
+
+/**
+ * Get heatmap color based on return value
+ */
+export function getHeatmapColor(value: number | null): string {
+ if (value === null || value === undefined) return FINCEPT.PANEL_BG;
+ if (value > 0.05) return '#00D66F';
+ if (value > 0.02) return '#00A050';
+ if (value > 0) return '#006030';
+ if (value > -0.02) return '#603000';
+ if (value > -0.05) return '#A05000';
+ return '#FF3B3B';
+}
+
+/**
+ * Parse date string to formatted date
+ */
+export function formatDate(dateStr: string): string {
+ const date = new Date(dateStr);
+ return date.toLocaleDateString('en-US', {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric'
+ });
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/utils/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/utils/index.ts
new file mode 100644
index 000000000..3d5d0bf7e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/ffn-analytics/utils/index.ts
@@ -0,0 +1,5 @@
+/**
+ * FFN Analytics Utils Barrel Export
+ */
+
+export * from './formatters';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/FortitudoPanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/FortitudoPanel.tsx
new file mode 100644
index 000000000..cedd42de4
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/FortitudoPanel.tsx
@@ -0,0 +1,151 @@
+/**
+ * FortitudoPanel - Main Component
+ * Fortitudo.tech Analytics Panel - Portfolio Risk Analytics
+ * Integrated with fortitudo.tech library via PyO3
+ */
+
+import React from 'react';
+import { FINCEPT } from './constants';
+import { useFortitudoState } from './hooks';
+import {
+ Header,
+ ModeSelector,
+ DataSourceSelector,
+ ErrorDisplay,
+ LoadingState,
+ UnavailableState
+} from './components';
+import {
+ PortfolioRiskMode,
+ OptionPricingMode,
+ OptimizationMode,
+ EntropyPoolingMode
+} from './modes';
+
+export function FortitudoPanel() {
+ const state = useFortitudoState();
+
+ // Render unavailable state
+ if (state.isFortitudoAvailable === false) {
+ return <UnavailableState onRetry={state.checkFortitudoStatus} />;
+ }
+
+ // Loading state
+ if (state.isFortitudoAvailable === null) {
+ return <LoadingState />;
+ }
+
+ return (
+ <div className="h-full overflow-auto" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <div className="p-4 space-y-4">
+ {/* Header */}
+ <Header />
+
+ {/* Mode Selector */}
+ <ModeSelector
+ activeMode={state.activeMode}
+ setActiveMode={state.setActiveMode}
+ />
+
+ {/* Data Source Selector */}
+ <DataSourceSelector
+ dataSource={state.dataSource}
+ setDataSource={state.setDataSource}
+ userPortfolios={state.userPortfolios}
+ selectedPortfolioId={state.selectedPortfolioId}
+ setSelectedPortfolioId={state.setSelectedPortfolioId}
+ selectedPortfolioSummary={state.selectedPortfolioSummary}
+ portfolioReturnsData={state.portfolioReturnsData}
+ historicalDays={state.historicalDays}
+ setHistoricalDays={state.setHistoricalDays}
+ isLoadingPortfolio={state.isLoadingPortfolio}
+ loadPortfolioData={state.loadPortfolioData}
+ />
+
+ {/* Error Display */}
+ {state.error && <ErrorDisplay error={state.error} />}
+
+ {/* Portfolio Risk Mode */}
+ {state.activeMode === 'portfolio' && (
+ <PortfolioRiskMode
+ weights={state.weights}
+ setWeights={state.setWeights}
+ alpha={state.alpha}
+ setAlpha={state.setAlpha}
+ halfLife={state.halfLife}
+ setHalfLife={state.setHalfLife}
+ isLoading={state.isLoading}
+ analysisResult={state.analysisResult}
+ expandedSections={state.expandedSections}
+ toggleSection={state.toggleSection}
+ runPortfolioAnalysis={state.runPortfolioAnalysis}
+ />
+ )}
+
+ {/* Option Pricing Mode */}
+ {state.activeMode === 'options' && (
+ <OptionPricingMode
+ spotPrice={state.spotPrice}
+ setSpotPrice={state.setSpotPrice}
+ strike={state.strike}
+ setStrike={state.setStrike}
+ volatility={state.volatility}
+ setVolatility={state.setVolatility}
+ riskFreeRate={state.riskFreeRate}
+ setRiskFreeRate={state.setRiskFreeRate}
+ dividendYield={state.dividendYield}
+ setDividendYield={state.setDividendYield}
+ timeToMaturity={state.timeToMaturity}
+ setTimeToMaturity={state.setTimeToMaturity}
+ isLoading={state.isLoading}
+ optionResult={state.optionResult}
+ greeksResult={state.greeksResult}
+ runOptionPricing={state.runOptionPricing}
+ runOptionGreeks={state.runOptionGreeks}
+ />
+ )}
+
+ {/* Optimization Mode */}
+ {state.activeMode === 'optimization' && (
+ <OptimizationMode
+ optimizationType={state.optimizationType}
+ setOptimizationType={state.setOptimizationType}
+ optimizationObjective={state.optimizationObjective}
+ setOptimizationObjective={state.setOptimizationObjective}
+ optMaxWeight={state.optMaxWeight}
+ setOptMaxWeight={state.setOptMaxWeight}
+ optTargetReturn={state.optTargetReturn}
+ setOptTargetReturn={state.setOptTargetReturn}
+ optAlpha={state.optAlpha}
+ setOptAlpha={state.setOptAlpha}
+ optLongOnly={state.optLongOnly}
+ setOptLongOnly={state.setOptLongOnly}
+ riskFreeRate={state.riskFreeRate}
+ isLoading={state.isLoading}
+ optimizationResult={state.optimizationResult}
+ frontierResult={state.frontierResult}
+ selectedFrontierIndex={state.selectedFrontierIndex}
+ setSelectedFrontierIndex={state.setSelectedFrontierIndex}
+ runOptimization={state.runOptimization}
+ runEfficientFrontier={state.runEfficientFrontier}
+ />
+ )}
+
+ {/* Entropy Pooling Mode */}
+ {state.activeMode === 'entropy' && (
+ <EntropyPoolingMode
+ nScenarios={state.nScenarios}
+ setNScenarios={state.setNScenarios}
+ maxProbability={state.maxProbability}
+ setMaxProbability={state.setMaxProbability}
+ isLoading={state.isLoading}
+ entropyResult={state.entropyResult}
+ runEntropyPooling={state.runEntropyPooling}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
+
+export default FortitudoPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/DataSourceSelector.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/DataSourceSelector.tsx
new file mode 100644
index 000000000..8bf62db27
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/DataSourceSelector.tsx
@@ -0,0 +1,205 @@
+/**
+ * DataSourceSelector Component
+ * Selector for choosing between sample data and user portfolios
+ */
+
+import React from 'react';
+import { Database, Briefcase, RefreshCw } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { DataSourceSelectorProps } from '../types';
+
+export const DataSourceSelector: React.FC<DataSourceSelectorProps> = ({
+ dataSource,
+ setDataSource,
+ userPortfolios,
+ selectedPortfolioId,
+ setSelectedPortfolioId,
+ selectedPortfolioSummary,
+ portfolioReturnsData,
+ historicalDays,
+ setHistoricalDays,
+ isLoadingPortfolio,
+ loadPortfolioData
+}) => {
+ return (
+ <div
+ className="p-3 rounded border"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ >
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-3">
+ <Database size={16} color={FINCEPT.CYAN} />
+ <span
+ className="text-xs font-bold uppercase"
+ style={{ color: FINCEPT.WHITE }}
+ >
+ DATA SOURCE
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div
+ className="flex rounded border overflow-hidden"
+ style={{ borderColor: FINCEPT.BORDER }}
+ >
+ <button
+ onClick={() => setDataSource('sample')}
+ className="px-3 py-1.5 text-xs font-bold uppercase transition-all"
+ style={{
+ backgroundColor:
+ dataSource === 'sample' ? FINCEPT.ORANGE : FINCEPT.DARK_BG,
+ color: dataSource === 'sample' ? FINCEPT.DARK_BG : FINCEPT.GRAY
+ }}
+ >
+ SAMPLE DATA
+ </button>
+ <button
+ onClick={() => setDataSource('portfolio')}
+ className="px-3 py-1.5 text-xs font-bold uppercase transition-all flex items-center gap-1"
+ style={{
+ backgroundColor:
+ dataSource === 'portfolio' ? FINCEPT.CYAN : FINCEPT.DARK_BG,
+ color: dataSource === 'portfolio' ? FINCEPT.DARK_BG : FINCEPT.GRAY
+ }}
+ >
+ <Briefcase size={12} />
+ MY PORTFOLIOS
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {/* Portfolio Selector (shown when portfolio data source is selected) */}
+ {dataSource === 'portfolio' && (
+ <div className="mt-3 pt-3 border-t" style={{ borderColor: FINCEPT.BORDER }}>
+ <div className="grid grid-cols-3 gap-4">
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ SELECT PORTFOLIO
+ </label>
+ <select
+ value={selectedPortfolioId || ''}
+ onChange={(e) => setSelectedPortfolioId(e.target.value || null)}
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ >
+ <option value="">-- Select Portfolio --</option>
+ {userPortfolios.map((p) => (
+ <option key={p.id} value={p.id}>
+ {p.name}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ HISTORICAL DAYS
+ </label>
+ <input
+ type="number"
+ value={historicalDays}
+ onChange={(e) => setHistoricalDays(parseInt(e.target.value))}
+ min="30"
+ max="1000"
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ />
+ </div>
+ <div className="flex items-end">
+ <button
+ onClick={() =>
+ selectedPortfolioId && loadPortfolioData(selectedPortfolioId)
+ }
+ disabled={!selectedPortfolioId || isLoadingPortfolio}
+ className="px-4 py-2 rounded font-bold uppercase tracking-wide text-xs hover:bg-opacity-90 transition-colors flex items-center gap-2 disabled:opacity-50"
+ style={{ backgroundColor: FINCEPT.CYAN, color: FINCEPT.DARK_BG }}
+ >
+ {isLoadingPortfolio ? (
+ <RefreshCw size={14} className="animate-spin" />
+ ) : (
+ <RefreshCw size={14} />
+ )}
+ LOAD DATA
+ </button>
+ </div>
+ </div>
+
+ {/* Portfolio Summary */}
+ {selectedPortfolioSummary && portfolioReturnsData && (
+ <div
+ className="mt-3 p-3 rounded"
+ style={{ backgroundColor: FINCEPT.DARK_BG }}
+ >
+ <div className="flex items-center gap-6 text-xs font-mono">
+ <span style={{ color: FINCEPT.GRAY }}>
+ Portfolio:{' '}
+ <span style={{ color: FINCEPT.WHITE }}>
+ {selectedPortfolioSummary.portfolio.name}
+ </span>
+ </span>
+ <span style={{ color: FINCEPT.GRAY }}>
+ Holdings:{' '}
+ <span style={{ color: FINCEPT.CYAN }}>
+ {selectedPortfolioSummary.holdings.length}
+ </span>
+ </span>
+ <span style={{ color: FINCEPT.GRAY }}>
+ Data Points:{' '}
+ <span style={{ color: FINCEPT.CYAN }}>
+ {portfolioReturnsData.nScenarios}
+ </span>
+ </span>
+ <span style={{ color: FINCEPT.GRAY }}>
+ Period:{' '}
+ <span style={{ color: FINCEPT.WHITE }}>
+ {portfolioReturnsData.startDate} to{' '}
+ {portfolioReturnsData.endDate}
+ </span>
+ </span>
+ </div>
+ <div className="mt-2 flex flex-wrap gap-2">
+ {portfolioReturnsData.assets.map((asset) => (
+ <span
+ key={asset}
+ className="px-2 py-0.5 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ >
+ {asset}: {(portfolioReturnsData.weights[asset] * 100).toFixed(1)}%
+ </span>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* No portfolios message */}
+ {userPortfolios.length === 0 && (
+ <div
+ className="mt-3 p-3 rounded text-center"
+ style={{ backgroundColor: FINCEPT.DARK_BG }}
+ >
+ <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ No portfolios found. Create a portfolio in the Portfolio tab first.
+ </p>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/ErrorDisplay.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/ErrorDisplay.tsx
new file mode 100644
index 000000000..6913c95c6
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/ErrorDisplay.tsx
@@ -0,0 +1,35 @@
+/**
+ * ErrorDisplay Component
+ * Shows error messages with alert styling
+ */
+
+import React from 'react';
+import { AlertCircle } from 'lucide-react';
+import { FINCEPT } from '../constants';
+
+interface ErrorDisplayProps {
+ error: string;
+}
+
+export const ErrorDisplay: React.FC<ErrorDisplayProps> = ({ error }) => {
+ return (
+ <div
+ className="flex items-start gap-3 p-3 rounded border"
+ style={{ backgroundColor: '#1a0000', borderColor: FINCEPT.RED }}
+ >
+ <AlertCircle
+ size={18}
+ color={FINCEPT.RED}
+ className="flex-shrink-0 mt-0.5"
+ />
+ <div>
+ <p className="text-sm font-bold" style={{ color: FINCEPT.RED }}>
+ Error
+ </p>
+ <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ {error}
+ </p>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/GreekRow.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/GreekRow.tsx
new file mode 100644
index 000000000..259c78bd9
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/GreekRow.tsx
@@ -0,0 +1,43 @@
+/**
+ * GreekRow Component
+ * Displays option Greeks with label and description
+ */
+
+import React from 'react';
+import { FINCEPT } from '../constants';
+import { formatGreek, getGreekValueColor } from '../utils';
+import type { GreekRowProps } from '../types';
+
+export const GreekRow: React.FC<GreekRowProps> = ({
+ label,
+ value,
+ description
+}) => {
+ return (
+ <div
+ className="flex items-center justify-between py-1.5 border-b"
+ style={{ borderColor: FINCEPT.BORDER }}
+ >
+ <div>
+ <span
+ className="text-xs font-mono font-semibold"
+ style={{ color: FINCEPT.WHITE }}
+ >
+ {label}
+ </span>
+ <span
+ className="text-xs font-mono ml-2"
+ style={{ color: FINCEPT.MUTED }}
+ >
+ {description}
+ </span>
+ </div>
+ <span
+ className="text-sm font-mono font-bold"
+ style={{ color: getGreekValueColor(value) }}
+ >
+ {formatGreek(value)}
+ </span>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/Header.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/Header.tsx
new file mode 100644
index 000000000..eaed3776e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/Header.tsx
@@ -0,0 +1,40 @@
+/**
+ * Header Component
+ * Top header bar with title and status
+ */
+
+import React from 'react';
+import { Shield, CheckCircle2 } from 'lucide-react';
+import { FINCEPT } from '../constants';
+
+export const Header: React.FC = () => {
+ return (
+ <div
+ className="flex items-center justify-between p-3 rounded border"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ >
+ <div className="flex items-center gap-3">
+ <div className="p-2 rounded" style={{ backgroundColor: FINCEPT.ORANGE }}>
+ <Shield size={20} color={FINCEPT.DARK_BG} />
+ </div>
+ <div>
+ <h2
+ className="font-bold text-sm uppercase tracking-wide"
+ style={{ color: FINCEPT.WHITE }}
+ >
+ FORTITUDO.TECH RISK ANALYTICS
+ </h2>
+ <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ VaR, CVaR, Option Pricing, Entropy Pooling
+ </p>
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <CheckCircle2 size={16} color={FINCEPT.GREEN} />
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GREEN }}>
+ READY
+ </span>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/LoadingState.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/LoadingState.tsx
new file mode 100644
index 000000000..48f23f5eb
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/LoadingState.tsx
@@ -0,0 +1,19 @@
+/**
+ * LoadingState Component
+ * Full-screen loading spinner
+ */
+
+import React from 'react';
+import { RefreshCw } from 'lucide-react';
+import { FINCEPT } from '../constants';
+
+export const LoadingState: React.FC = () => {
+ return (
+ <div
+ className="flex items-center justify-center h-full"
+ style={{ backgroundColor: FINCEPT.DARK_BG }}
+ >
+ <RefreshCw size={48} color={FINCEPT.ORANGE} className="animate-spin" />
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/MetricRow.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/MetricRow.tsx
new file mode 100644
index 000000000..bb2528ca9
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/MetricRow.tsx
@@ -0,0 +1,36 @@
+/**
+ * MetricRow Component
+ * Displays a labeled metric with optional positive/negative coloring
+ */
+
+import React from 'react';
+import { FINCEPT } from '../constants';
+import type { MetricRowProps } from '../types';
+
+export const MetricRow: React.FC<MetricRowProps> = ({
+ label,
+ value,
+ positive,
+ negative
+}) => {
+ let valueColor = FINCEPT.WHITE;
+ if (positive) valueColor = FINCEPT.GREEN;
+ if (negative) valueColor = FINCEPT.RED;
+
+ return (
+ <div
+ className="flex items-center justify-between py-1.5 border-b"
+ style={{ borderColor: FINCEPT.BORDER }}
+ >
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ {label}
+ </span>
+ <span
+ className="text-sm font-mono font-semibold"
+ style={{ color: valueColor }}
+ >
+ {value}
+ </span>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/ModeSelector.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/ModeSelector.tsx
new file mode 100644
index 000000000..5af372dbd
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/ModeSelector.tsx
@@ -0,0 +1,48 @@
+/**
+ * ModeSelector Component
+ * Tab-style selector for switching between analysis modes
+ */
+
+import React from 'react';
+import { Shield, DollarSign, Target, Layers } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { AnalysisMode } from '../types';
+
+const MODE_CONFIG = [
+ { id: 'portfolio' as const, label: 'PORTFOLIO RISK', Icon: Shield },
+ { id: 'options' as const, label: 'OPTION PRICING', Icon: DollarSign },
+ { id: 'optimization' as const, label: 'OPTIMIZATION', Icon: Target },
+ { id: 'entropy' as const, label: 'ENTROPY', Icon: Layers }
+];
+
+interface ModeSelectorProps {
+ activeMode: AnalysisMode;
+ setActiveMode: (mode: AnalysisMode) => void;
+}
+
+export const ModeSelector: React.FC<ModeSelectorProps> = ({
+ activeMode,
+ setActiveMode
+}) => {
+ return (
+ <div
+ className="flex rounded border overflow-hidden"
+ style={{ borderColor: FINCEPT.BORDER }}
+ >
+ {MODE_CONFIG.map(({ id, label, Icon }) => (
+ <button
+ key={id}
+ onClick={() => setActiveMode(id)}
+ className="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 text-xs font-semibold uppercase tracking-wide transition-all"
+ style={{
+ backgroundColor: activeMode === id ? FINCEPT.ORANGE : FINCEPT.PANEL_BG,
+ color: activeMode === id ? FINCEPT.DARK_BG : FINCEPT.GRAY
+ }}
+ >
+ <Icon size={14} />
+ {label}
+ </button>
+ ))}
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/UnavailableState.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/UnavailableState.tsx
new file mode 100644
index 000000000..3e367306e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/UnavailableState.tsx
@@ -0,0 +1,48 @@
+/**
+ * UnavailableState Component
+ * Shown when fortitudo.tech library is not installed
+ */
+
+import React from 'react';
+import { AlertCircle, RefreshCw } from 'lucide-react';
+import { FINCEPT } from '../constants';
+
+interface UnavailableStateProps {
+ onRetry: () => void;
+}
+
+export const UnavailableState: React.FC<UnavailableStateProps> = ({ onRetry }) => {
+ return (
+ <div
+ className="flex items-center justify-center h-full p-8"
+ style={{ backgroundColor: FINCEPT.DARK_BG }}
+ >
+ <div className="max-w-lg text-center">
+ <AlertCircle size={64} color={FINCEPT.RED} className="mx-auto mb-6" />
+ <h2
+ className="text-2xl font-bold uppercase tracking-wide mb-4"
+ style={{ color: FINCEPT.WHITE }}
+ >
+ FORTITUDO.TECH NOT INSTALLED
+ </h2>
+ <p className="text-sm font-mono mb-6" style={{ color: FINCEPT.GRAY }}>
+ Install the library to enable portfolio risk analytics:
+ </p>
+ <code
+ className="block p-4 rounded text-sm font-mono mb-6"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.ORANGE }}
+ >
+ pip install fortitudo.tech cvxopt
+ </code>
+ <button
+ onClick={onRetry}
+ className="px-6 py-2 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors inline-flex items-center gap-2"
+ style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
+ >
+ <RefreshCw size={16} />
+ RETRY
+ </button>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/index.ts
new file mode 100644
index 000000000..b56c6fe44
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/components/index.ts
@@ -0,0 +1,12 @@
+/**
+ * Fortitudo Components Barrel Export
+ */
+
+export { MetricRow } from './MetricRow';
+export { GreekRow } from './GreekRow';
+export { Header } from './Header';
+export { ModeSelector } from './ModeSelector';
+export { DataSourceSelector } from './DataSourceSelector';
+export { ErrorDisplay } from './ErrorDisplay';
+export { LoadingState } from './LoadingState';
+export { UnavailableState } from './UnavailableState';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/constants.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/constants.ts
new file mode 100644
index 000000000..ec09e55f8
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/constants.ts
@@ -0,0 +1,72 @@
+/**
+ * Fortitudo Panel Constants
+ * Color palette, sample data, and configurations
+ */
+
+// Fincept Professional Color Palette
+export const FINCEPT = {
+ 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'
+};
+
+// Pie chart colors for allocations
+export const PIE_COLORS = [
+ FINCEPT.ORANGE,
+ FINCEPT.CYAN,
+ FINCEPT.GREEN,
+ FINCEPT.PURPLE,
+ FINCEPT.YELLOW,
+ FINCEPT.BLUE,
+ FINCEPT.RED
+];
+
+// Sample portfolio data for demonstration
+export const SAMPLE_RETURNS: Record<string, Record<string, number>> = {
+ 'Stocks': Object.fromEntries(
+ Array.from({ length: 200 }, (_, i) => [
+ new Date(2024, 0, i + 1).toISOString().split('T')[0],
+ 0.0003 + (Math.random() - 0.5) * 0.02
+ ])
+ ),
+ 'Bonds': Object.fromEntries(
+ Array.from({ length: 200 }, (_, i) => [
+ new Date(2024, 0, i + 1).toISOString().split('T')[0],
+ 0.0001 + (Math.random() - 0.5) * 0.005
+ ])
+ ),
+ 'Commodities': Object.fromEntries(
+ Array.from({ length: 200 }, (_, i) => [
+ new Date(2024, 0, i + 1).toISOString().split('T')[0],
+ 0.0002 + (Math.random() - 0.5) * 0.015
+ ])
+ ),
+ 'Cash': Object.fromEntries(
+ Array.from({ length: 200 }, (_, i) => [
+ new Date(2024, 0, i + 1).toISOString().split('T')[0],
+ 0.0001 + (Math.random() - 0.5) * 0.001
+ ])
+ )
+};
+
+export const SAMPLE_WEIGHTS = [0.4, 0.3, 0.2, 0.1];
+
+// Analysis modes available
+export const ANALYSIS_MODES = [
+ { id: 'portfolio', label: 'PORTFOLIO RISK', iconName: 'Shield' },
+ { id: 'options', label: 'OPTION PRICING', iconName: 'DollarSign' },
+ { id: 'optimization', label: 'OPTIMIZATION', iconName: 'Target' },
+ { id: 'entropy', label: 'ENTROPY', iconName: 'Layers' }
+] as const;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/hooks/index.ts
new file mode 100644
index 000000000..edbc5c18c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/hooks/index.ts
@@ -0,0 +1,5 @@
+/**
+ * Fortitudo Hooks Barrel Export
+ */
+
+export { useFortitudoState } from './useFortitudoState';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/hooks/useFortitudoState.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/hooks/useFortitudoState.ts
new file mode 100644
index 000000000..4b6e4a003
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/hooks/useFortitudoState.ts
@@ -0,0 +1,441 @@
+/**
+ * useFortitudoState Hook
+ * Manages all state for the Fortitudo Panel
+ */
+
+import { useState, useEffect } from 'react';
+import {
+ fortitudoService,
+ type OptionGreeksResponse,
+ type OptimizationResult,
+ type EfficientFrontierResponse,
+ type OptimizationObjective
+} from '@/services/aiQuantLab/fortitudoService';
+import {
+ portfolioFortitudoService,
+ type PortfolioReturnsData
+} from '@/services/aiQuantLab/portfolioFortitudoService';
+import type { Portfolio, PortfolioSummary } from '@/services/portfolio/portfolioService';
+import { SAMPLE_RETURNS } from '../constants';
+import type {
+ AnalysisMode,
+ DataSourceType,
+ OptimizationType,
+ AnalysisResult,
+ ExpandedSections
+} from '../types';
+
+export function useFortitudoState() {
+ // Status
+ const [isFortitudoAvailable, setIsFortitudoAvailable] = useState<boolean | null>(null);
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [activeMode, setActiveMode] = useState<AnalysisMode>('portfolio');
+
+ // Portfolio config
+ const [weights, setWeights] = useState('[0.4, 0.3, 0.2, 0.1]');
+ const [alpha, setAlpha] = useState(0.05);
+ const [halfLife, setHalfLife] = useState(252);
+ const [analysisResult, setAnalysisResult] = useState<AnalysisResult | null>(null);
+
+ // Option pricing config
+ const [spotPrice, setSpotPrice] = useState(100);
+ const [strike, setStrike] = useState(100);
+ const [volatility, setVolatility] = useState(0.25);
+ const [riskFreeRate, setRiskFreeRate] = useState(0.05);
+ const [dividendYield, setDividendYield] = useState(0.02);
+ const [timeToMaturity, setTimeToMaturity] = useState(1.0);
+ const [optionResult, setOptionResult] = useState<any>(null);
+ const [greeksResult, setGreeksResult] = useState<OptionGreeksResponse | null>(null);
+
+ // Entropy pooling config
+ const [nScenarios, setNScenarios] = useState(100);
+ const [maxProbability, setMaxProbability] = useState(0.05);
+ const [entropyResult, setEntropyResult] = useState<any>(null);
+
+ // Optimization config
+ const [optimizationObjective, setOptimizationObjective] = useState<OptimizationObjective>('min_variance');
+ const [optimizationType, setOptimizationType] = useState<OptimizationType>('mv');
+ const [optLongOnly, setOptLongOnly] = useState(true);
+ const [optMaxWeight, setOptMaxWeight] = useState(0.5);
+ const [optMinWeight, setOptMinWeight] = useState(0.0);
+ const [optTargetReturn, setOptTargetReturn] = useState(0.08);
+ const [optAlpha, setOptAlpha] = useState(0.05);
+ const [optimizationResult, setOptimizationResult] = useState<OptimizationResult | null>(null);
+ const [frontierResult, setFrontierResult] = useState<EfficientFrontierResponse | null>(null);
+ const [nFrontierPoints, setNFrontierPoints] = useState(20);
+ const [selectedFrontierIndex, setSelectedFrontierIndex] = useState<number | null>(null);
+
+ // User portfolio
+ const [userPortfolios, setUserPortfolios] = useState<Portfolio[]>([]);
+ const [selectedPortfolioId, setSelectedPortfolioId] = useState<string | null>(null);
+ const [selectedPortfolioSummary, setSelectedPortfolioSummary] = useState<PortfolioSummary | null>(null);
+ const [portfolioReturnsData, setPortfolioReturnsData] = useState<PortfolioReturnsData | null>(null);
+ const [dataSource, setDataSource] = useState<DataSourceType>('sample');
+ const [isLoadingPortfolio, setIsLoadingPortfolio] = useState(false);
+ const [historicalDays, setHistoricalDays] = useState(252);
+
+ // UI state
+ const [expandedSections, setExpandedSections] = useState<ExpandedSections>({
+ config: true,
+ metrics: true,
+ comparison: true,
+ matrix: false
+ });
+
+ // Check fortitudo availability on mount
+ useEffect(() => {
+ checkFortitudoStatus();
+ loadUserPortfolios();
+ }, []);
+
+ // Load portfolio summary and returns when selected
+ useEffect(() => {
+ if (selectedPortfolioId && dataSource === 'portfolio') {
+ loadPortfolioData(selectedPortfolioId);
+ }
+ }, [selectedPortfolioId, dataSource]);
+
+ const loadUserPortfolios = async () => {
+ try {
+ const portfolios = await portfolioFortitudoService.getAvailablePortfolios();
+ setUserPortfolios(portfolios);
+ } catch (err) {
+ console.error('[FortitudoPanel] Failed to load portfolios:', err);
+ }
+ };
+
+ const loadPortfolioData = async (portfolioId: string) => {
+ setIsLoadingPortfolio(true);
+ setError(null);
+ try {
+ const summary = await portfolioFortitudoService.getPortfolioSummary(portfolioId);
+ setSelectedPortfolioSummary(summary);
+
+ if (summary && summary.holdings.length > 0) {
+ const returns = await portfolioFortitudoService.fetchHistoricalReturns(summary.holdings, historicalDays);
+ setPortfolioReturnsData(returns);
+
+ // Auto-update weights from portfolio
+ if (returns) {
+ setWeights(JSON.stringify(Object.values(returns.weights).map(w => Math.round(w * 1000) / 1000)));
+ }
+ }
+ } catch (err) {
+ setError(`Failed to load portfolio data: ${err}`);
+ } finally {
+ setIsLoadingPortfolio(false);
+ }
+ };
+
+ const checkFortitudoStatus = async () => {
+ try {
+ const status = await fortitudoService.checkStatus();
+ setIsFortitudoAvailable(status.available);
+ if (!status.available) {
+ setError('Fortitudo.tech library not installed. Run: pip install fortitudo.tech cvxopt');
+ }
+ } catch (err) {
+ setIsFortitudoAvailable(false);
+ setError('Failed to check fortitudo.tech status');
+ }
+ };
+
+ const runPortfolioAnalysis = async () => {
+ setIsLoading(true);
+ setError(null);
+
+ try {
+ let returnsData: Record<string, Record<string, number>>;
+ let weightsArray: number[];
+
+ if (dataSource === 'portfolio' && portfolioReturnsData) {
+ returnsData = portfolioReturnsData.returns;
+ weightsArray = Object.values(portfolioReturnsData.weights);
+ } else {
+ returnsData = SAMPLE_RETURNS;
+ weightsArray = JSON.parse(weights);
+ }
+
+ const result = await fortitudoService.fullAnalysis(
+ returnsData,
+ weightsArray,
+ alpha,
+ halfLife
+ );
+
+ if (result.success && result.analysis) {
+ if (dataSource === 'portfolio' && portfolioReturnsData) {
+ result.analysis.assets = portfolioReturnsData.assets;
+ }
+ setAnalysisResult(result.analysis);
+ } else {
+ setError(result.error || 'Analysis failed');
+ }
+ } catch (err) {
+ setError(String(err));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const runOptionPricing = async () => {
+ setIsLoading(true);
+ setError(null);
+
+ try {
+ const result = await fortitudoService.optionPricing(
+ spotPrice,
+ strike,
+ volatility,
+ riskFreeRate,
+ dividendYield,
+ timeToMaturity
+ );
+
+ if (result.success) {
+ setOptionResult(result);
+ } else {
+ setError(result.error || 'Option pricing failed');
+ }
+ } catch (err) {
+ setError(String(err));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const runOptionGreeks = async () => {
+ setIsLoading(true);
+ setError(null);
+
+ try {
+ const result = await fortitudoService.optionGreeks(
+ spotPrice,
+ strike,
+ volatility,
+ riskFreeRate,
+ dividendYield,
+ timeToMaturity
+ );
+
+ if (result.success) {
+ setGreeksResult(result);
+ } else {
+ setError(result.error || 'Greeks calculation failed');
+ }
+ } catch (err) {
+ setError(String(err));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const runEntropyPooling = async () => {
+ setIsLoading(true);
+ setError(null);
+
+ try {
+ const result = await fortitudoService.entropyPooling(nScenarios, maxProbability);
+
+ if (result.success) {
+ setEntropyResult(result);
+ } else {
+ setError(result.error || 'Entropy pooling failed');
+ }
+ } catch (err) {
+ setError(String(err));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const runOptimization = async () => {
+ setIsLoading(true);
+ setError(null);
+
+ try {
+ const returnsData = (dataSource === 'portfolio' && portfolioReturnsData)
+ ? portfolioReturnsData.returns
+ : SAMPLE_RETURNS;
+
+ let result: OptimizationResult;
+
+ if (optimizationType === 'mv') {
+ result = await fortitudoService.optimizeMeanVariance(
+ returnsData,
+ optimizationObjective,
+ optLongOnly,
+ optMaxWeight,
+ optMinWeight,
+ riskFreeRate,
+ optimizationObjective === 'target_return' ? optTargetReturn : undefined
+ );
+ } else {
+ result = await fortitudoService.optimizeMeanCVaR(
+ returnsData,
+ optimizationObjective === 'min_variance' ? 'min_cvar' : optimizationObjective,
+ optAlpha,
+ optLongOnly,
+ optMaxWeight,
+ optMinWeight,
+ riskFreeRate,
+ optimizationObjective === 'target_return' ? optTargetReturn : undefined
+ );
+ }
+
+ if (result.success && dataSource === 'portfolio' && portfolioReturnsData) {
+ result.assets = portfolioReturnsData.assets;
+ }
+
+ if (result.success) {
+ setOptimizationResult(result);
+ } else {
+ setError(result.error || 'Optimization failed');
+ }
+ } catch (err) {
+ setError(String(err));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const runEfficientFrontier = async () => {
+ setIsLoading(true);
+ setError(null);
+
+ try {
+ const returnsData = (dataSource === 'portfolio' && portfolioReturnsData)
+ ? portfolioReturnsData.returns
+ : SAMPLE_RETURNS;
+
+ let result: EfficientFrontierResponse;
+
+ if (optimizationType === 'mv') {
+ result = await fortitudoService.efficientFrontierMV(
+ returnsData,
+ nFrontierPoints,
+ optLongOnly,
+ optMaxWeight,
+ riskFreeRate
+ );
+ } else {
+ result = await fortitudoService.efficientFrontierCVaR(
+ returnsData,
+ nFrontierPoints,
+ optAlpha,
+ optLongOnly,
+ optMaxWeight
+ );
+ }
+
+ if (result.success && dataSource === 'portfolio' && portfolioReturnsData) {
+ result.assets = portfolioReturnsData.assets;
+ }
+
+ if (result.success) {
+ setFrontierResult(result);
+ setSelectedFrontierIndex(null);
+ } else {
+ setError(result.error || 'Efficient frontier generation failed');
+ }
+ } catch (err) {
+ setError(String(err));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const toggleSection = (section: keyof ExpandedSections) => {
+ setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
+ };
+
+ return {
+ // Status
+ isFortitudoAvailable,
+ isLoading,
+ error,
+ activeMode,
+ setActiveMode,
+
+ // Portfolio risk
+ weights,
+ setWeights,
+ alpha,
+ setAlpha,
+ halfLife,
+ setHalfLife,
+ analysisResult,
+
+ // Option pricing
+ spotPrice,
+ setSpotPrice,
+ strike,
+ setStrike,
+ volatility,
+ setVolatility,
+ riskFreeRate,
+ setRiskFreeRate,
+ dividendYield,
+ setDividendYield,
+ timeToMaturity,
+ setTimeToMaturity,
+ optionResult,
+ greeksResult,
+
+ // Entropy pooling
+ nScenarios,
+ setNScenarios,
+ maxProbability,
+ setMaxProbability,
+ entropyResult,
+
+ // Optimization
+ optimizationObjective,
+ setOptimizationObjective,
+ optimizationType,
+ setOptimizationType,
+ optLongOnly,
+ setOptLongOnly,
+ optMaxWeight,
+ setOptMaxWeight,
+ optMinWeight,
+ setOptMinWeight,
+ optTargetReturn,
+ setOptTargetReturn,
+ optAlpha,
+ setOptAlpha,
+ optimizationResult,
+ frontierResult,
+ nFrontierPoints,
+ setNFrontierPoints,
+ selectedFrontierIndex,
+ setSelectedFrontierIndex,
+
+ // User portfolio
+ userPortfolios,
+ selectedPortfolioId,
+ setSelectedPortfolioId,
+ selectedPortfolioSummary,
+ portfolioReturnsData,
+ dataSource,
+ setDataSource,
+ isLoadingPortfolio,
+ historicalDays,
+ setHistoricalDays,
+ loadPortfolioData,
+
+ // UI state
+ expandedSections,
+ toggleSection,
+
+ // Actions
+ checkFortitudoStatus,
+ runPortfolioAnalysis,
+ runOptionPricing,
+ runOptionGreeks,
+ runEntropyPooling,
+ runOptimization,
+ runEfficientFrontier
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/index.ts
new file mode 100644
index 000000000..69221ae5b
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/index.ts
@@ -0,0 +1,26 @@
+/**
+ * Fortitudo Panel - Main Barrel Export
+ *
+ * Export all components, hooks, types, and utilities
+ */
+
+// Main component
+export { FortitudoPanel, default } from './FortitudoPanel';
+
+// Components
+export * from './components';
+
+// Modes
+export * from './modes';
+
+// Hooks
+export * from './hooks';
+
+// Types
+export * from './types';
+
+// Constants
+export * from './constants';
+
+// Utils
+export * from './utils';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/modes/EntropyPoolingMode.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/modes/EntropyPoolingMode.tsx
new file mode 100644
index 000000000..7bc44dbdb
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/modes/EntropyPoolingMode.tsx
@@ -0,0 +1,122 @@
+/**
+ * EntropyPoolingMode Component
+ * Entropy pooling configuration and results
+ */
+
+import React from 'react';
+import { Layers, RefreshCw } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { EntropyPoolingModeProps } from '../types';
+
+export const EntropyPoolingMode: React.FC<EntropyPoolingModeProps> = ({
+ nScenarios,
+ setNScenarios,
+ maxProbability,
+ setMaxProbability,
+ isLoading,
+ entropyResult,
+ runEntropyPooling
+}) => {
+ return (
+ <div
+ className="rounded border"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ >
+ <div className="p-4 space-y-4">
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ NUMBER OF SCENARIOS
+ </label>
+ <input
+ type="number"
+ value={nScenarios}
+ onChange={(e) => setNScenarios(parseInt(e.target.value))}
+ min="10"
+ max="10000"
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ />
+ </div>
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ MAX PROBABILITY (%)
+ </label>
+ <input
+ type="number"
+ value={maxProbability * 100}
+ onChange={(e) => setMaxProbability(parseFloat(e.target.value) / 100)}
+ step="0.5"
+ min="0.5"
+ max="100"
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ />
+ </div>
+ </div>
+
+ <button
+ onClick={runEntropyPooling}
+ disabled={isLoading}
+ className="w-full py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
+ style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
+ >
+ {isLoading ? (
+ <RefreshCw size={16} className="animate-spin" />
+ ) : (
+ <Layers size={16} />
+ )}
+ APPLY ENTROPY POOLING
+ </button>
+
+ {/* Entropy Results */}
+ {entropyResult && entropyResult.success && (
+ <div className="grid grid-cols-2 gap-4 mt-4">
+ <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <p className="text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
+ PRIOR
+ </p>
+ <div className="space-y-1">
+ <p className="text-xs font-mono" style={{ color: FINCEPT.WHITE }}>
+ Effective Scenarios:{' '}
+ {entropyResult.effective_scenarios_prior?.toFixed(1)}
+ </p>
+ </div>
+ </div>
+ <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <p className="text-xs font-mono mb-2" style={{ color: FINCEPT.CYAN }}>
+ POSTERIOR
+ </p>
+ <div className="space-y-1">
+ <p className="text-xs font-mono" style={{ color: FINCEPT.WHITE }}>
+ Effective Scenarios:{' '}
+ {entropyResult.effective_scenarios_posterior?.toFixed(1)}
+ </p>
+ <p className="text-xs font-mono" style={{ color: FINCEPT.WHITE }}>
+ Max Prob: {(entropyResult.max_probability * 100).toFixed(2)}%
+ </p>
+ <p className="text-xs font-mono" style={{ color: FINCEPT.WHITE }}>
+ Min Prob: {(entropyResult.min_probability * 100).toFixed(4)}%
+ </p>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/modes/OptimizationMode.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/modes/OptimizationMode.tsx
new file mode 100644
index 000000000..016f42cc6
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/modes/OptimizationMode.tsx
@@ -0,0 +1,1004 @@
+/**
+ * OptimizationMode Component
+ * Portfolio optimization and efficient frontier visualization
+ */
+
+import React from 'react';
+import { Target, TrendingUp, RefreshCw } from 'lucide-react';
+import {
+ ResponsiveContainer,
+ ComposedChart,
+ CartesianGrid,
+ XAxis,
+ YAxis,
+ Tooltip,
+ Line,
+ Scatter,
+ Cell,
+ PieChart,
+ Pie
+} from 'recharts';
+import { FINCEPT, PIE_COLORS } from '../constants';
+import { formatPercent, formatRatio, normalizeWeights } from '../utils';
+import { MetricRow } from '../components';
+import type { OptimizationModeProps, OptimizationObjective } from '../types';
+
+export const OptimizationMode: React.FC<OptimizationModeProps> = ({
+ optimizationType,
+ setOptimizationType,
+ optimizationObjective,
+ setOptimizationObjective,
+ optMaxWeight,
+ setOptMaxWeight,
+ optTargetReturn,
+ setOptTargetReturn,
+ optAlpha,
+ setOptAlpha,
+ optLongOnly,
+ setOptLongOnly,
+ riskFreeRate,
+ isLoading,
+ optimizationResult,
+ frontierResult,
+ selectedFrontierIndex,
+ setSelectedFrontierIndex,
+ runOptimization,
+ runEfficientFrontier
+}) => {
+ return (
+ <div
+ className="rounded border"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ >
+ <div className="p-4 space-y-4">
+ {/* Optimization Type Toggle */}
+ <div
+ className="flex rounded border overflow-hidden"
+ style={{ borderColor: FINCEPT.BORDER }}
+ >
+ <button
+ onClick={() => setOptimizationType('mv')}
+ className="flex-1 py-2 text-xs font-bold uppercase tracking-wide"
+ style={{
+ backgroundColor:
+ optimizationType === 'mv' ? FINCEPT.ORANGE : FINCEPT.DARK_BG,
+ color: optimizationType === 'mv' ? FINCEPT.DARK_BG : FINCEPT.GRAY
+ }}
+ >
+ MEAN-VARIANCE
+ </button>
+ <button
+ onClick={() => setOptimizationType('cvar')}
+ className="flex-1 py-2 text-xs font-bold uppercase tracking-wide"
+ style={{
+ backgroundColor:
+ optimizationType === 'cvar' ? FINCEPT.CYAN : FINCEPT.DARK_BG,
+ color: optimizationType === 'cvar' ? FINCEPT.DARK_BG : FINCEPT.GRAY
+ }}
+ >
+ MEAN-CVaR
+ </button>
+ </div>
+
+ {/* Configuration */}
+ <div className="grid grid-cols-4 gap-4">
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ OBJECTIVE
+ </label>
+ <select
+ value={optimizationObjective}
+ onChange={(e) =>
+ setOptimizationObjective(e.target.value as OptimizationObjective)
+ }
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ >
+ <option value="min_variance">
+ {optimizationType === 'mv' ? 'Min Variance' : 'Min CVaR'}
+ </option>
+ <option value="max_sharpe">Max Sharpe</option>
+ <option value="target_return">Target Return</option>
+ </select>
+ </div>
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ MAX WEIGHT
+ </label>
+ <input
+ type="number"
+ value={optMaxWeight}
+ onChange={(e) => setOptMaxWeight(parseFloat(e.target.value))}
+ step="0.05"
+ min="0.1"
+ max="1.0"
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ />
+ </div>
+ {optimizationObjective === 'target_return' && (
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ TARGET RETURN
+ </label>
+ <input
+ type="number"
+ value={optTargetReturn}
+ onChange={(e) => setOptTargetReturn(parseFloat(e.target.value))}
+ step="0.01"
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ />
+ </div>
+ )}
+ {optimizationType === 'cvar' && (
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ CVaR ALPHA
+ </label>
+ <input
+ type="number"
+ value={optAlpha}
+ onChange={(e) => setOptAlpha(parseFloat(e.target.value))}
+ step="0.01"
+ min="0.01"
+ max="0.50"
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ />
+ </div>
+ )}
+ <div className="flex items-end">
+ <label className="flex items-center gap-2 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={optLongOnly}
+ onChange={(e) => setOptLongOnly(e.target.checked)}
+ className="w-4 h-4"
+ />
+ <span className="text-xs font-mono" style={{ color: FINCEPT.WHITE }}>
+ LONG ONLY
+ </span>
+ </label>
+ </div>
+ </div>
+
+ {/* Buttons */}
+ <div className="grid grid-cols-2 gap-4">
+ <button
+ onClick={runOptimization}
+ disabled={isLoading}
+ className="py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
+ style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
+ >
+ {isLoading ? (
+ <RefreshCw size={16} className="animate-spin" />
+ ) : (
+ <Target size={16} />
+ )}
+ OPTIMIZE PORTFOLIO
+ </button>
+ <button
+ onClick={runEfficientFrontier}
+ disabled={isLoading}
+ className="py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
+ style={{ backgroundColor: FINCEPT.CYAN, color: FINCEPT.DARK_BG }}
+ >
+ {isLoading ? (
+ <RefreshCw size={16} className="animate-spin" />
+ ) : (
+ <TrendingUp size={16} />
+ )}
+ EFFICIENT FRONTIER
+ </button>
+ </div>
+
+ {/* Optimization Result */}
+ {optimizationResult && optimizationResult.success && (
+ <OptimalPortfolioDisplay
+ optimizationResult={optimizationResult}
+ optimizationType={optimizationType}
+ optimizationObjective={optimizationObjective}
+ optLongOnly={optLongOnly}
+ />
+ )}
+
+ {/* Efficient Frontier Result */}
+ {frontierResult && frontierResult.success && frontierResult.frontier && (
+ <EfficientFrontierDisplay
+ frontierResult={frontierResult}
+ optimizationType={optimizationType}
+ selectedFrontierIndex={selectedFrontierIndex}
+ setSelectedFrontierIndex={setSelectedFrontierIndex}
+ />
+ )}
+ </div>
+ </div>
+ );
+};
+
+// Sub-component for optimal portfolio display
+interface OptimalPortfolioDisplayProps {
+ optimizationResult: any;
+ optimizationType: 'mv' | 'cvar';
+ optimizationObjective: OptimizationObjective;
+ optLongOnly: boolean;
+}
+
+const OptimalPortfolioDisplay: React.FC<OptimalPortfolioDisplayProps> = ({
+ optimizationResult,
+ optimizationType,
+ optimizationObjective,
+ optLongOnly
+}) => {
+ const normalizedWeights = normalizeWeights(
+ optimizationResult.weights,
+ optimizationResult.assets
+ );
+
+ return (
+ <div
+ className="p-4 rounded border"
+ style={{ backgroundColor: FINCEPT.DARK_BG, borderColor: FINCEPT.BORDER }}
+ >
+ <h3
+ className="text-sm font-bold uppercase mb-4"
+ style={{ color: FINCEPT.ORANGE }}
+ >
+ OPTIMAL PORTFOLIO
+ </h3>
+ <div className="grid grid-cols-3 gap-6">
+ {/* Pie Chart */}
+ <div>
+ <h4
+ className="text-xs font-bold uppercase mb-3"
+ style={{ color: FINCEPT.CYAN }}
+ >
+ ALLOCATION
+ </h4>
+ <div style={{ height: 180 }}>
+ <ResponsiveContainer width="100%" height="100%">
+ <PieChart>
+ <Pie
+ data={normalizedWeights
+ .filter((item) => item.weight > 0.001)
+ .map((item, idx) => ({
+ name: item.asset,
+ value: Math.round(item.weight * 1000) / 10,
+ weight: item.weight,
+ fill: PIE_COLORS[idx % PIE_COLORS.length]
+ }))}
+ cx="50%"
+ cy="50%"
+ innerRadius={35}
+ outerRadius={60}
+ paddingAngle={2}
+ dataKey="value"
+ stroke={FINCEPT.DARK_BG}
+ strokeWidth={2}
+ >
+ {normalizedWeights
+ .filter((item) => item.weight > 0.001)
+ .map((_, idx) => (
+ <Cell key={idx} fill={PIE_COLORS[idx % PIE_COLORS.length]} />
+ ))}
+ </Pie>
+ <Tooltip
+ contentStyle={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: 4,
+ padding: '6px 10px'
+ }}
+ formatter={(value: number) => [`${value.toFixed(1)}%`, 'Weight']}
+ labelStyle={{
+ color: FINCEPT.WHITE,
+ fontWeight: 'bold',
+ fontSize: 11
+ }}
+ itemStyle={{ color: FINCEPT.GRAY, fontSize: 10 }}
+ />
+ </PieChart>
+ </ResponsiveContainer>
+ </div>
+ {/* Pie Legend */}
+ <div className="mt-2 space-y-1">
+ {normalizedWeights
+ .filter((item) => item.weight > 0.001)
+ .map((item, idx) => (
+ <div key={idx} className="flex items-center gap-2">
+ <div
+ className="w-2 h-2 rounded-full"
+ style={{ backgroundColor: PIE_COLORS[idx % PIE_COLORS.length] }}
+ />
+ <span
+ className="text-xs font-mono"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ {item.asset}
+ </span>
+ <span
+ className="text-xs font-mono font-bold ml-auto"
+ style={{ color: FINCEPT.WHITE }}
+ >
+ {(item.weight * 100).toFixed(1)}%
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Weight Bars */}
+ <div>
+ <h4
+ className="text-xs font-bold uppercase mb-3"
+ style={{ color: FINCEPT.CYAN }}
+ >
+ WEIGHTS
+ </h4>
+ <div className="space-y-2">
+ {normalizedWeights.map((item, i) => (
+ <div key={i} className="flex items-center justify-between">
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ {item.asset}
+ </span>
+ <div className="flex items-center gap-2">
+ <div
+ className="h-2 rounded"
+ style={{
+ width: `${Math.max(item.weight * 100, 5)}px`,
+ backgroundColor: item.weight > 0 ? FINCEPT.GREEN : FINCEPT.RED
+ }}
+ />
+ <span
+ className="text-sm font-mono font-bold"
+ style={{ color: FINCEPT.WHITE }}
+ >
+ {(item.weight * 100).toFixed(1)}%
+ </span>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Metrics */}
+ <div>
+ <h4
+ className="text-xs font-bold uppercase mb-3"
+ style={{ color: FINCEPT.CYAN }}
+ >
+ METRICS
+ </h4>
+ <div className="space-y-2">
+ <MetricRow
+ label="Expected Return"
+ value={formatPercent(optimizationResult.expected_return)}
+ positive={(optimizationResult.expected_return ?? 0) > 0}
+ />
+ <MetricRow
+ label="Volatility"
+ value={formatPercent(optimizationResult.volatility)}
+ />
+ <MetricRow
+ label="Sharpe Ratio"
+ value={formatRatio(optimizationResult.sharpe_ratio)}
+ positive={(optimizationResult.sharpe_ratio ?? 0) > 0}
+ />
+ {optimizationResult.cvar !== undefined && (
+ <MetricRow
+ label="CVaR"
+ value={formatPercent(optimizationResult.cvar)}
+ negative
+ />
+ )}
+ </div>
+ {/* Optimization Info */}
+ <div
+ className="mt-4 p-2 rounded"
+ style={{ backgroundColor: FINCEPT.PANEL_BG }}
+ >
+ <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ Type:{' '}
+ <span
+ style={{
+ color: optimizationType === 'mv' ? FINCEPT.ORANGE : FINCEPT.CYAN
+ }}
+ >
+ {optimizationType === 'mv' ? 'Mean-Variance' : 'Mean-CVaR'}
+ </span>
+ </p>
+ <p className="text-xs font-mono mt-1" style={{ color: FINCEPT.GRAY }}>
+ Objective:{' '}
+ <span style={{ color: FINCEPT.WHITE }}>
+ {optimizationObjective.replace('_', ' ').toUpperCase()}
+ </span>
+ </p>
+ <p className="text-xs font-mono mt-1" style={{ color: FINCEPT.GRAY }}>
+ Constraints:{' '}
+ <span style={{ color: FINCEPT.WHITE }}>
+ {optLongOnly ? 'Long Only' : 'Allow Short'}
+ </span>
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+// Sub-component for efficient frontier display
+interface EfficientFrontierDisplayProps {
+ frontierResult: any;
+ optimizationType: 'mv' | 'cvar';
+ selectedFrontierIndex: number | null;
+ setSelectedFrontierIndex: (value: number | null) => void;
+}
+
+const EfficientFrontierDisplay: React.FC<EfficientFrontierDisplayProps> = ({
+ frontierResult,
+ optimizationType,
+ selectedFrontierIndex,
+ setSelectedFrontierIndex
+}) => {
+ const frontier = frontierResult.frontier;
+
+ return (
+ <div
+ className="p-4 rounded border"
+ style={{ backgroundColor: FINCEPT.DARK_BG, borderColor: FINCEPT.BORDER }}
+ >
+ <h3
+ className="text-sm font-bold uppercase mb-4"
+ style={{ color: FINCEPT.CYAN }}
+ >
+ EFFICIENT FRONTIER ({frontier.length} POINTS)
+ </h3>
+
+ {/* Chart Visualization */}
+ <div className="mb-4" style={{ height: 300 }}>
+ <ResponsiveContainer width="100%" height="100%">
+ <ComposedChart margin={{ top: 20, right: 30, left: 20, bottom: 20 }}>
+ <CartesianGrid
+ strokeDasharray="3 3"
+ stroke={FINCEPT.BORDER}
+ vertical={true}
+ />
+ <XAxis
+ type="number"
+ dataKey="risk"
+ name={optimizationType === 'mv' ? 'Volatility' : 'CVaR'}
+ domain={['auto', 'auto']}
+ tickFormatter={(value) => `${(value * 100).toFixed(1)}%`}
+ stroke={FINCEPT.GRAY}
+ tick={{ fill: FINCEPT.GRAY, fontSize: 10 }}
+ label={{
+ value: optimizationType === 'mv' ? 'VOLATILITY (%)' : 'CVaR (%)',
+ position: 'bottom',
+ fill: FINCEPT.GRAY,
+ fontSize: 10,
+ offset: 0
+ }}
+ />
+ <YAxis
+ type="number"
+ dataKey="return"
+ name="Expected Return"
+ domain={['auto', 'auto']}
+ tickFormatter={(value) => `${(value * 100).toFixed(1)}%`}
+ stroke={FINCEPT.GRAY}
+ tick={{ fill: FINCEPT.GRAY, fontSize: 10 }}
+ label={{
+ value: 'EXPECTED RETURN (%)',
+ angle: -90,
+ position: 'insideLeft',
+ fill: FINCEPT.GRAY,
+ fontSize: 10
+ }}
+ />
+ <Tooltip
+ contentStyle={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: 4,
+ padding: '8px 12px'
+ }}
+ formatter={(value: number, name: string) => {
+ if (name === 'return') return [`${(value * 100).toFixed(2)}%`, 'Return'];
+ if (name === 'risk')
+ return [
+ `${(value * 100).toFixed(2)}%`,
+ optimizationType === 'mv' ? 'Volatility' : 'CVaR'
+ ];
+ if (name === 'sharpe') return [value.toFixed(3), 'Sharpe'];
+ return [value, name];
+ }}
+ labelStyle={{ color: FINCEPT.WHITE }}
+ itemStyle={{ color: FINCEPT.GRAY }}
+ />
+ {/* Frontier Line */}
+ <Line
+ data={frontier.map((point: any, idx: number) => ({
+ risk: point.volatility ?? point.cvar ?? 0,
+ return: point.expected_return,
+ sharpe: point.sharpe_ratio ?? 0,
+ index: idx
+ }))}
+ type="monotone"
+ dataKey="return"
+ stroke={FINCEPT.CYAN}
+ strokeWidth={2}
+ dot={false}
+ />
+ {/* Frontier Points */}
+ <Scatter
+ data={frontier.map((point: any, idx: number) => ({
+ risk: point.volatility ?? point.cvar ?? 0,
+ return: point.expected_return,
+ sharpe: point.sharpe_ratio ?? 0,
+ index: idx,
+ isMaxSharpe:
+ point.sharpe_ratio ===
+ Math.max(...frontier.map((p: any) => p.sharpe_ratio ?? 0))
+ }))}
+ fill={FINCEPT.ORANGE}
+ onClick={(data: any) => {
+ if (data && typeof data.index === 'number') {
+ setSelectedFrontierIndex(data.index);
+ }
+ }}
+ cursor="pointer"
+ >
+ {frontier.map((point: any, idx: number) => {
+ const maxSharpe = Math.max(
+ ...frontier.map((p: any) => p.sharpe_ratio ?? 0)
+ );
+ const isMaxSharpe = point.sharpe_ratio === maxSharpe;
+ const isMinRisk = idx === 0;
+ const isSelected = selectedFrontierIndex === idx;
+ return (
+ <Cell
+ key={idx}
+ fill={
+ isSelected
+ ? FINCEPT.YELLOW
+ : isMaxSharpe
+ ? FINCEPT.GREEN
+ : isMinRisk
+ ? FINCEPT.ORANGE
+ : FINCEPT.CYAN
+ }
+ stroke={isSelected ? FINCEPT.WHITE : 'none'}
+ strokeWidth={isSelected ? 2 : 0}
+ r={isSelected ? 8 : isMaxSharpe || isMinRisk ? 6 : 4}
+ />
+ );
+ })}
+ </Scatter>
+ </ComposedChart>
+ </ResponsiveContainer>
+ </div>
+
+ {/* Legend */}
+ <div className="flex items-center justify-center gap-6 mb-4">
+ <div className="flex items-center gap-2">
+ <div
+ className="w-3 h-3 rounded-full"
+ style={{ backgroundColor: FINCEPT.ORANGE }}
+ />
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ MIN RISK
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div
+ className="w-3 h-3 rounded-full"
+ style={{ backgroundColor: FINCEPT.GREEN }}
+ />
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ MAX SHARPE
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div
+ className="w-3 h-3 rounded-full"
+ style={{ backgroundColor: FINCEPT.CYAN }}
+ />
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ FRONTIER
+ </span>
+ </div>
+ {selectedFrontierIndex !== null && (
+ <div className="flex items-center gap-2">
+ <div
+ className="w-3 h-3 rounded-full border-2"
+ style={{
+ backgroundColor: FINCEPT.YELLOW,
+ borderColor: FINCEPT.WHITE
+ }}
+ />
+ <span className="text-xs font-mono" style={{ color: FINCEPT.YELLOW }}>
+ SELECTED
+ </span>
+ </div>
+ )}
+ </div>
+
+ {/* Selected Portfolio Details */}
+ {selectedFrontierIndex !== null && frontier[selectedFrontierIndex] && (
+ <SelectedPortfolioDetails
+ frontierResult={frontierResult}
+ selectedFrontierIndex={selectedFrontierIndex}
+ setSelectedFrontierIndex={setSelectedFrontierIndex}
+ optimizationType={optimizationType}
+ />
+ )}
+
+ {/* Summary Stats */}
+ <div
+ className="grid grid-cols-3 gap-4 p-3 rounded"
+ style={{ backgroundColor: FINCEPT.PANEL_BG }}
+ >
+ <div className="text-center">
+ <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ MIN RISK
+ </p>
+ <p className="text-sm font-bold" style={{ color: FINCEPT.ORANGE }}>
+ {(
+ (frontier[0]?.volatility ?? frontier[0]?.cvar ?? 0) * 100
+ ).toFixed(2)}
+ %
+ </p>
+ <p className="text-xs font-mono" style={{ color: FINCEPT.MUTED }}>
+ Return: {(frontier[0]?.expected_return * 100).toFixed(2)}%
+ </p>
+ </div>
+ <div className="text-center">
+ <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ MAX SHARPE
+ </p>
+ {(() => {
+ const maxSharpePoint = frontier.reduce(
+ (max: any, p: any) =>
+ (p.sharpe_ratio ?? 0) > (max.sharpe_ratio ?? 0) ? p : max,
+ frontier[0]
+ );
+ return (
+ <>
+ <p className="text-sm font-bold" style={{ color: FINCEPT.GREEN }}>
+ {maxSharpePoint.sharpe_ratio?.toFixed(3) ?? 'N/A'}
+ </p>
+ <p className="text-xs font-mono" style={{ color: FINCEPT.MUTED }}>
+ Return: {(maxSharpePoint.expected_return * 100).toFixed(2)}%
+ </p>
+ </>
+ );
+ })()}
+ </div>
+ <div className="text-center">
+ <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ MAX RETURN
+ </p>
+ <p className="text-sm font-bold" style={{ color: FINCEPT.CYAN }}>
+ {(frontier[frontier.length - 1]?.expected_return * 100).toFixed(2)}%
+ </p>
+ <p className="text-xs font-mono" style={{ color: FINCEPT.MUTED }}>
+ Risk:{' '}
+ {(
+ (frontier[frontier.length - 1]?.volatility ??
+ frontier[frontier.length - 1]?.cvar ??
+ 0) * 100
+ ).toFixed(2)}
+ %
+ </p>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+// Sub-component for selected portfolio details
+interface SelectedPortfolioDetailsProps {
+ frontierResult: any;
+ selectedFrontierIndex: number;
+ setSelectedFrontierIndex: (value: number | null) => void;
+ optimizationType: 'mv' | 'cvar';
+}
+
+const SelectedPortfolioDetails: React.FC<SelectedPortfolioDetailsProps> = ({
+ frontierResult,
+ selectedFrontierIndex,
+ setSelectedFrontierIndex,
+ optimizationType
+}) => {
+ const frontier = frontierResult.frontier;
+ const selectedPoint = frontier[selectedFrontierIndex];
+ const weights = selectedPoint.weights;
+
+ const getWeightsData = () => {
+ if (typeof weights === 'object' && !Array.isArray(weights)) {
+ return Object.entries(weights)
+ .filter(([_, w]) => (w as number) > 0.001)
+ .map(([asset, weight], idx) => ({
+ name: asset,
+ value: Math.round((weight as number) * 1000) / 10,
+ weight: weight as number,
+ fill: PIE_COLORS[idx % PIE_COLORS.length]
+ }));
+ } else if (Array.isArray(weights)) {
+ return weights
+ .filter((w) => w > 0.001)
+ .map((w, idx) => ({
+ name: `Asset ${idx + 1}`,
+ value: Math.round(w * 1000) / 10,
+ weight: w,
+ fill: PIE_COLORS[idx % PIE_COLORS.length]
+ }));
+ }
+ return [];
+ };
+
+ const weightsData = getWeightsData();
+
+ return (
+ <div
+ className="mb-4 p-4 rounded border"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.YELLOW }}
+ >
+ <div className="flex items-center justify-between mb-3">
+ <h4
+ className="text-sm font-bold uppercase"
+ style={{ color: FINCEPT.YELLOW }}
+ >
+ SELECTED PORTFOLIO (#{selectedFrontierIndex + 1})
+ </h4>
+ <button
+ onClick={() => setSelectedFrontierIndex(null)}
+ className="text-xs font-mono px-2 py-1 rounded hover:bg-opacity-80"
+ style={{ backgroundColor: FINCEPT.BORDER, color: FINCEPT.GRAY }}
+ >
+ CLEAR
+ </button>
+ </div>
+ <div className="grid grid-cols-3 gap-6">
+ {/* Pie Chart */}
+ <div>
+ <h5
+ className="text-xs font-bold uppercase mb-2"
+ style={{ color: FINCEPT.CYAN }}
+ >
+ ALLOCATION
+ </h5>
+ <div style={{ height: 180 }}>
+ <ResponsiveContainer width="100%" height="100%">
+ <PieChart>
+ <Pie
+ data={weightsData}
+ cx="50%"
+ cy="50%"
+ innerRadius={35}
+ outerRadius={60}
+ paddingAngle={2}
+ dataKey="value"
+ stroke={FINCEPT.DARK_BG}
+ strokeWidth={2}
+ >
+ {weightsData.map((_, idx) => (
+ <Cell key={idx} fill={PIE_COLORS[idx % PIE_COLORS.length]} />
+ ))}
+ </Pie>
+ <Tooltip
+ contentStyle={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: 4,
+ padding: '6px 10px'
+ }}
+ formatter={(value: number) => [`${value.toFixed(1)}%`, 'Weight']}
+ labelStyle={{
+ color: FINCEPT.WHITE,
+ fontWeight: 'bold',
+ fontSize: 11
+ }}
+ itemStyle={{ color: FINCEPT.GRAY, fontSize: 10 }}
+ />
+ </PieChart>
+ </ResponsiveContainer>
+ </div>
+ {/* Pie Legend */}
+ <div className="mt-2 space-y-1">
+ {weightsData.map((item, idx) => (
+ <div key={idx} className="flex items-center gap-2">
+ <div
+ className="w-2 h-2 rounded-full"
+ style={{ backgroundColor: PIE_COLORS[idx % PIE_COLORS.length] }}
+ />
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ {item.name}
+ </span>
+ <span
+ className="text-xs font-mono font-bold ml-auto"
+ style={{ color: FINCEPT.WHITE }}
+ >
+ {(item.weight * 100).toFixed(1)}%
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Weight Bars */}
+ <div>
+ <h5
+ className="text-xs font-bold uppercase mb-2"
+ style={{ color: FINCEPT.CYAN }}
+ >
+ WEIGHTS
+ </h5>
+ <div className="space-y-1">
+ {typeof weights === 'object' && !Array.isArray(weights)
+ ? Object.entries(weights).map(([asset, weight]) => (
+ <div key={asset} className="flex items-center justify-between">
+ <span
+ className="text-xs font-mono"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ {asset}
+ </span>
+ <div className="flex items-center gap-2">
+ <div
+ className="h-2 rounded"
+ style={{
+ width: `${Math.max((weight as number) * 80, 3)}px`,
+ backgroundColor:
+ (weight as number) > 0 ? FINCEPT.GREEN : FINCEPT.RED
+ }}
+ />
+ <span
+ className="text-xs font-mono font-bold"
+ style={{ color: FINCEPT.WHITE }}
+ >
+ {((weight as number) * 100).toFixed(1)}%
+ </span>
+ </div>
+ </div>
+ ))
+ : Array.isArray(weights) &&
+ weights.map((w, i) => (
+ <div key={i} className="flex items-center justify-between">
+ <span
+ className="text-xs font-mono"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ Asset {i + 1}
+ </span>
+ <div className="flex items-center gap-2">
+ <div
+ className="h-2 rounded"
+ style={{
+ width: `${Math.max(w * 80, 3)}px`,
+ backgroundColor: w > 0 ? FINCEPT.GREEN : FINCEPT.RED
+ }}
+ />
+ <span
+ className="text-xs font-mono font-bold"
+ style={{ color: FINCEPT.WHITE }}
+ >
+ {(w * 100).toFixed(1)}%
+ </span>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Metrics */}
+ <div>
+ <h5
+ className="text-xs font-bold uppercase mb-2"
+ style={{ color: FINCEPT.CYAN }}
+ >
+ METRICS
+ </h5>
+ <div className="space-y-1">
+ <div
+ className="flex items-center justify-between py-1 border-b"
+ style={{ borderColor: FINCEPT.BORDER }}
+ >
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ Expected Return
+ </span>
+ <span
+ className="text-sm font-mono font-bold"
+ style={{ color: FINCEPT.GREEN }}
+ >
+ {(selectedPoint.expected_return * 100).toFixed(2)}%
+ </span>
+ </div>
+ <div
+ className="flex items-center justify-between py-1 border-b"
+ style={{ borderColor: FINCEPT.BORDER }}
+ >
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ {optimizationType === 'mv' ? 'Volatility' : 'CVaR'}
+ </span>
+ <span
+ className="text-sm font-mono font-bold"
+ style={{ color: FINCEPT.RED }}
+ >
+ {(
+ (selectedPoint.volatility ?? selectedPoint.cvar ?? 0) * 100
+ ).toFixed(2)}
+ %
+ </span>
+ </div>
+ <div className="flex items-center justify-between py-1">
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ Sharpe Ratio
+ </span>
+ <span
+ className="text-sm font-mono font-bold"
+ style={{ color: FINCEPT.WHITE }}
+ >
+ {selectedPoint.sharpe_ratio?.toFixed(3) ?? 'N/A'}
+ </span>
+ </div>
+ </div>
+ {/* Position on Frontier */}
+ <div
+ className="mt-4 p-2 rounded"
+ style={{ backgroundColor: FINCEPT.DARK_BG }}
+ >
+ <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ Position:{' '}
+ <span style={{ color: FINCEPT.YELLOW }}>
+ {selectedFrontierIndex + 1}
+ </span>{' '}
+ of {frontier.length}
+ </p>
+ <p className="text-xs font-mono mt-1" style={{ color: FINCEPT.GRAY }}>
+ {selectedFrontierIndex === 0 ? (
+ <span style={{ color: FINCEPT.ORANGE }}>Minimum Risk Portfolio</span>
+ ) : selectedFrontierIndex === frontier.length - 1 ? (
+ <span style={{ color: FINCEPT.CYAN }}>Maximum Return Portfolio</span>
+ ) : selectedPoint.sharpe_ratio ===
+ Math.max(...frontier.map((p: any) => p.sharpe_ratio ?? 0)) ? (
+ <span style={{ color: FINCEPT.GREEN }}>Maximum Sharpe Portfolio</span>
+ ) : (
+ <span style={{ color: FINCEPT.MUTED }}>Intermediate Portfolio</span>
+ )}
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/modes/OptionPricingMode.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/modes/OptionPricingMode.tsx
new file mode 100644
index 000000000..9f4b77203
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/modes/OptionPricingMode.tsx
@@ -0,0 +1,316 @@
+/**
+ * OptionPricingMode Component
+ * Option pricing and Greeks calculation
+ */
+
+import React from 'react';
+import { DollarSign, Activity, RefreshCw } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import { GreekRow } from '../components';
+import type { OptionPricingModeProps } from '../types';
+
+export const OptionPricingMode: React.FC<OptionPricingModeProps> = ({
+ spotPrice,
+ setSpotPrice,
+ strike,
+ setStrike,
+ volatility,
+ setVolatility,
+ riskFreeRate,
+ setRiskFreeRate,
+ dividendYield,
+ setDividendYield,
+ timeToMaturity,
+ setTimeToMaturity,
+ isLoading,
+ optionResult,
+ greeksResult,
+ runOptionPricing,
+ runOptionGreeks
+}) => {
+ return (
+ <div
+ className="rounded border"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ >
+ <div className="p-4 space-y-4">
+ <div className="grid grid-cols-6 gap-4">
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ SPOT PRICE
+ </label>
+ <input
+ type="number"
+ value={spotPrice}
+ onChange={(e) => setSpotPrice(parseFloat(e.target.value))}
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ />
+ </div>
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ STRIKE
+ </label>
+ <input
+ type="number"
+ value={strike}
+ onChange={(e) => setStrike(parseFloat(e.target.value))}
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ />
+ </div>
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ VOLATILITY
+ </label>
+ <input
+ type="number"
+ value={volatility}
+ onChange={(e) => setVolatility(parseFloat(e.target.value))}
+ step="0.01"
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ />
+ </div>
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ RISK-FREE RATE
+ </label>
+ <input
+ type="number"
+ value={riskFreeRate}
+ onChange={(e) => setRiskFreeRate(parseFloat(e.target.value))}
+ step="0.01"
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ />
+ </div>
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ DIV YIELD
+ </label>
+ <input
+ type="number"
+ value={dividendYield}
+ onChange={(e) => setDividendYield(parseFloat(e.target.value))}
+ step="0.01"
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ />
+ </div>
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ TIME (YEARS)
+ </label>
+ <input
+ type="number"
+ value={timeToMaturity}
+ onChange={(e) => setTimeToMaturity(parseFloat(e.target.value))}
+ step="0.1"
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ />
+ </div>
+ </div>
+
+ <div className="grid grid-cols-2 gap-4">
+ <button
+ onClick={runOptionPricing}
+ disabled={isLoading}
+ className="py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
+ style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
+ >
+ {isLoading ? (
+ <RefreshCw size={16} className="animate-spin" />
+ ) : (
+ <DollarSign size={16} />
+ )}
+ PRICE OPTIONS
+ </button>
+ <button
+ onClick={runOptionGreeks}
+ disabled={isLoading}
+ className="py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
+ style={{ backgroundColor: FINCEPT.CYAN, color: FINCEPT.DARK_BG }}
+ >
+ {isLoading ? (
+ <RefreshCw size={16} className="animate-spin" />
+ ) : (
+ <Activity size={16} />
+ )}
+ CALCULATE GREEKS
+ </button>
+ </div>
+
+ {/* Option Results */}
+ {optionResult && optionResult.success && (
+ <div className="grid grid-cols-4 gap-4 mt-4">
+ <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ FORWARD
+ </p>
+ <p className="text-lg font-bold" style={{ color: FINCEPT.WHITE }}>
+ ${optionResult.forward_price?.toFixed(2)}
+ </p>
+ </div>
+ <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ CALL PRICE
+ </p>
+ <p className="text-lg font-bold" style={{ color: FINCEPT.GREEN }}>
+ ${optionResult.call_price?.toFixed(4)}
+ </p>
+ </div>
+ <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ PUT PRICE
+ </p>
+ <p className="text-lg font-bold" style={{ color: FINCEPT.RED }}>
+ ${optionResult.put_price?.toFixed(4)}
+ </p>
+ </div>
+ <div className="p-3 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ STRADDLE
+ </p>
+ <p className="text-lg font-bold" style={{ color: FINCEPT.CYAN }}>
+ ${optionResult.straddle?.straddle_price?.toFixed(4)}
+ </p>
+ </div>
+ </div>
+ )}
+
+ {/* Greeks Results */}
+ {greeksResult && greeksResult.success && (
+ <div
+ className="mt-4 p-4 rounded border"
+ style={{ backgroundColor: FINCEPT.DARK_BG, borderColor: FINCEPT.BORDER }}
+ >
+ <h3
+ className="text-sm font-bold uppercase mb-4"
+ style={{ color: FINCEPT.CYAN }}
+ >
+ OPTION GREEKS
+ </h3>
+ <div className="grid grid-cols-2 gap-6">
+ {/* Call Greeks */}
+ <div>
+ <h4
+ className="text-xs font-bold uppercase mb-3"
+ style={{ color: FINCEPT.GREEN }}
+ >
+ CALL OPTION
+ </h4>
+ <div className="space-y-2">
+ <GreekRow
+ label="Delta (Δ)"
+ value={greeksResult.call?.delta}
+ description="Price sensitivity"
+ />
+ <GreekRow
+ label="Gamma (Γ)"
+ value={greeksResult.call?.gamma}
+ description="Delta sensitivity"
+ />
+ <GreekRow
+ label="Vega (ν)"
+ value={greeksResult.call?.vega}
+ description="Volatility sensitivity"
+ />
+ <GreekRow
+ label="Theta (Θ)"
+ value={greeksResult.call?.theta}
+ description="Time decay (daily)"
+ />
+ <GreekRow
+ label="Rho (ρ)"
+ value={greeksResult.call?.rho}
+ description="Rate sensitivity"
+ />
+ </div>
+ </div>
+ {/* Put Greeks */}
+ <div>
+ <h4
+ className="text-xs font-bold uppercase mb-3"
+ style={{ color: FINCEPT.RED }}
+ >
+ PUT OPTION
+ </h4>
+ <div className="space-y-2">
+ <GreekRow
+ label="Delta (Δ)"
+ value={greeksResult.put?.delta}
+ description="Price sensitivity"
+ />
+ <GreekRow
+ label="Gamma (Γ)"
+ value={greeksResult.put?.gamma}
+ description="Delta sensitivity"
+ />
+ <GreekRow
+ label="Vega (ν)"
+ value={greeksResult.put?.vega}
+ description="Volatility sensitivity"
+ />
+ <GreekRow
+ label="Theta (Θ)"
+ value={greeksResult.put?.theta}
+ description="Time decay (daily)"
+ />
+ <GreekRow
+ label="Rho (ρ)"
+ value={greeksResult.put?.rho}
+ description="Rate sensitivity"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/modes/PortfolioRiskMode.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/modes/PortfolioRiskMode.tsx
new file mode 100644
index 000000000..ec8accf40
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/modes/PortfolioRiskMode.tsx
@@ -0,0 +1,301 @@
+/**
+ * PortfolioRiskMode Component
+ * Portfolio risk analysis configuration and results display
+ */
+
+import React from 'react';
+import {
+ Settings,
+ ChevronUp,
+ ChevronDown,
+ Play,
+ RefreshCw,
+ BarChart2
+} from 'lucide-react';
+import { FINCEPT } from '../constants';
+import { formatPercent, formatRatio } from '../utils';
+import { MetricRow } from '../components';
+import type { PortfolioRiskModeProps, ExpandedSections } from '../types';
+
+export const PortfolioRiskMode: React.FC<PortfolioRiskModeProps> = ({
+ weights,
+ setWeights,
+ alpha,
+ setAlpha,
+ halfLife,
+ setHalfLife,
+ isLoading,
+ analysisResult,
+ expandedSections,
+ toggleSection,
+ runPortfolioAnalysis
+}) => {
+ return (
+ <>
+ {/* Configuration */}
+ <div
+ className="rounded border"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ >
+ <button
+ onClick={() => toggleSection('config')}
+ className="w-full flex items-center justify-between p-3"
+ >
+ <div className="flex items-center gap-2">
+ <Settings size={16} color={FINCEPT.ORANGE} />
+ <span
+ className="text-sm font-bold uppercase"
+ style={{ color: FINCEPT.WHITE }}
+ >
+ CONFIGURATION
+ </span>
+ </div>
+ {expandedSections.config ? (
+ <ChevronUp size={16} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={16} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expandedSections.config && (
+ <div
+ className="p-4 border-t space-y-4"
+ style={{ borderColor: FINCEPT.BORDER }}
+ >
+ <div className="grid grid-cols-3 gap-4">
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ PORTFOLIO WEIGHTS
+ </label>
+ <input
+ type="text"
+ value={weights}
+ onChange={(e) => setWeights(e.target.value)}
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ />
+ </div>
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ ALPHA (VaR/CVaR)
+ </label>
+ <input
+ type="number"
+ value={alpha}
+ onChange={(e) => setAlpha(parseFloat(e.target.value))}
+ step="0.01"
+ min="0.01"
+ max="0.50"
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ />
+ </div>
+ <div>
+ <label
+ className="block text-xs font-mono mb-1"
+ style={{ color: FINCEPT.GRAY }}
+ >
+ HALF-LIFE (DAYS)
+ </label>
+ <input
+ type="number"
+ value={halfLife}
+ onChange={(e) => setHalfLife(parseInt(e.target.value))}
+ min="20"
+ max="504"
+ className="w-full px-3 py-2 rounded text-sm font-mono border"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ borderColor: FINCEPT.BORDER,
+ color: FINCEPT.WHITE
+ }}
+ />
+ </div>
+ </div>
+
+ <button
+ onClick={runPortfolioAnalysis}
+ disabled={isLoading}
+ className="w-full py-2.5 rounded font-bold uppercase tracking-wide text-sm hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 disabled:opacity-50"
+ style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
+ >
+ {isLoading ? (
+ <RefreshCw size={16} className="animate-spin" />
+ ) : (
+ <Play size={16} />
+ )}
+ RUN PORTFOLIO ANALYSIS
+ </button>
+ </div>
+ )}
+ </div>
+
+ {/* Results */}
+ {analysisResult && (
+ <div
+ className="rounded border"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ >
+ <button
+ onClick={() => toggleSection('metrics')}
+ className="w-full flex items-center justify-between p-3"
+ >
+ <div className="flex items-center gap-2">
+ <BarChart2 size={16} color={FINCEPT.CYAN} />
+ <span
+ className="text-sm font-bold uppercase"
+ style={{ color: FINCEPT.WHITE }}
+ >
+ RISK METRICS
+ </span>
+ </div>
+ {expandedSections.metrics ? (
+ <ChevronUp size={16} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={16} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expandedSections.metrics && (
+ <div className="p-4 border-t" style={{ borderColor: FINCEPT.BORDER }}>
+ <div className="grid grid-cols-2 gap-6">
+ {/* Equal Weight Metrics */}
+ <div>
+ <h3
+ className="text-xs font-bold uppercase mb-3"
+ style={{ color: FINCEPT.ORANGE }}
+ >
+ EQUAL WEIGHT SCENARIOS
+ </h3>
+ {analysisResult.metrics_equal_weight && (
+ <div className="space-y-2">
+ <MetricRow
+ label="Expected Return"
+ value={formatPercent(
+ analysisResult.metrics_equal_weight.expected_return
+ )}
+ positive={
+ analysisResult.metrics_equal_weight.expected_return > 0
+ }
+ />
+ <MetricRow
+ label="Volatility"
+ value={formatPercent(
+ analysisResult.metrics_equal_weight.volatility
+ )}
+ />
+ <MetricRow
+ label={`VaR (${(1 - alpha) * 100}%)`}
+ value={formatPercent(analysisResult.metrics_equal_weight.var)}
+ negative
+ />
+ <MetricRow
+ label={`CVaR (${(1 - alpha) * 100}%)`}
+ value={formatPercent(analysisResult.metrics_equal_weight.cvar)}
+ negative
+ />
+ <MetricRow
+ label="Sharpe Ratio"
+ value={formatRatio(
+ analysisResult.metrics_equal_weight.sharpe_ratio
+ )}
+ positive={
+ analysisResult.metrics_equal_weight.sharpe_ratio > 0
+ }
+ />
+ </div>
+ )}
+ </div>
+
+ {/* Exp Decay Metrics */}
+ <div>
+ <h3
+ className="text-xs font-bold uppercase mb-3"
+ style={{ color: FINCEPT.CYAN }}
+ >
+ EXP DECAY WEIGHTED ({halfLife}d)
+ </h3>
+ {analysisResult.metrics_exp_decay && (
+ <div className="space-y-2">
+ <MetricRow
+ label="Expected Return"
+ value={formatPercent(
+ analysisResult.metrics_exp_decay.expected_return
+ )}
+ positive={
+ analysisResult.metrics_exp_decay.expected_return > 0
+ }
+ />
+ <MetricRow
+ label="Volatility"
+ value={formatPercent(
+ analysisResult.metrics_exp_decay.volatility
+ )}
+ />
+ <MetricRow
+ label={`VaR (${(1 - alpha) * 100}%)`}
+ value={formatPercent(analysisResult.metrics_exp_decay.var)}
+ negative
+ />
+ <MetricRow
+ label={`CVaR (${(1 - alpha) * 100}%)`}
+ value={formatPercent(analysisResult.metrics_exp_decay.cvar)}
+ negative
+ />
+ <MetricRow
+ label="Sharpe Ratio"
+ value={formatRatio(
+ analysisResult.metrics_exp_decay.sharpe_ratio
+ )}
+ positive={analysisResult.metrics_exp_decay.sharpe_ratio > 0}
+ />
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Summary */}
+ <div
+ className="mt-4 p-3 rounded"
+ style={{ backgroundColor: FINCEPT.DARK_BG }}
+ >
+ <div className="flex items-center gap-6 text-xs font-mono">
+ <span style={{ color: FINCEPT.GRAY }}>
+ Scenarios:{' '}
+ <span style={{ color: FINCEPT.WHITE }}>
+ {analysisResult.n_scenarios}
+ </span>
+ </span>
+ <span style={{ color: FINCEPT.GRAY }}>
+ Assets:{' '}
+ <span style={{ color: FINCEPT.WHITE }}>
+ {analysisResult.n_assets}
+ </span>
+ </span>
+ <span style={{ color: FINCEPT.GRAY }}>
+ Alpha:{' '}
+ <span style={{ color: FINCEPT.WHITE }}>{alpha}</span>
+ </span>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/modes/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/modes/index.ts
new file mode 100644
index 000000000..7341148ff
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/modes/index.ts
@@ -0,0 +1,8 @@
+/**
+ * Fortitudo Modes Barrel Export
+ */
+
+export { PortfolioRiskMode } from './PortfolioRiskMode';
+export { OptionPricingMode } from './OptionPricingMode';
+export { OptimizationMode } from './OptimizationMode';
+export { EntropyPoolingMode } from './EntropyPoolingMode';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/types.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/types.ts
new file mode 100644
index 000000000..9bc7b380d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/types.ts
@@ -0,0 +1,204 @@
+/**
+ * Fortitudo Panel TypeScript Interfaces
+ */
+
+import type {
+ PortfolioMetrics,
+ OptionGreeksResponse,
+ OptimizationResult,
+ EfficientFrontierResponse,
+ OptimizationObjective
+} from '@/services/aiQuantLab/fortitudoService';
+import type { PortfolioReturnsData } from '@/services/aiQuantLab/portfolioFortitudoService';
+import type { Portfolio, PortfolioSummary } from '@/services/portfolio/portfolioService';
+
+// Analysis mode types
+export type AnalysisMode = 'portfolio' | 'options' | 'entropy' | 'optimization';
+export type DataSourceType = 'sample' | 'portfolio';
+export type OptimizationType = 'mv' | 'cvar';
+
+// Analysis result interface
+export interface AnalysisResult {
+ metrics_equal_weight?: PortfolioMetrics;
+ metrics_exp_decay?: PortfolioMetrics;
+ n_scenarios?: number;
+ n_assets?: number;
+ assets?: string[];
+ half_life?: number;
+ alpha?: number;
+}
+
+// Expandable sections state
+export interface ExpandedSections {
+ config: boolean;
+ metrics: boolean;
+ comparison: boolean;
+ matrix: boolean;
+}
+
+// Normalized weight item
+export interface NormalizedWeight {
+ asset: string;
+ weight: number;
+}
+
+// Main panel state
+export interface FortitudoPanelState {
+ // Status
+ isFortitudoAvailable: boolean | null;
+ isLoading: boolean;
+ error: string | null;
+ activeMode: AnalysisMode;
+
+ // Portfolio config
+ weights: string;
+ alpha: number;
+ halfLife: number;
+ analysisResult: AnalysisResult | null;
+
+ // Option pricing config
+ spotPrice: number;
+ strike: number;
+ volatility: number;
+ riskFreeRate: number;
+ dividendYield: number;
+ timeToMaturity: number;
+ optionResult: any;
+ greeksResult: OptionGreeksResponse | null;
+
+ // Entropy pooling config
+ nScenarios: number;
+ maxProbability: number;
+ entropyResult: any;
+
+ // Optimization config
+ optimizationObjective: OptimizationObjective;
+ optimizationType: OptimizationType;
+ optLongOnly: boolean;
+ optMaxWeight: number;
+ optMinWeight: number;
+ optTargetReturn: number;
+ optAlpha: number;
+ optimizationResult: OptimizationResult | null;
+ frontierResult: EfficientFrontierResponse | null;
+ nFrontierPoints: number;
+ selectedFrontierIndex: number | null;
+
+ // User portfolio
+ userPortfolios: Portfolio[];
+ selectedPortfolioId: string | null;
+ selectedPortfolioSummary: PortfolioSummary | null;
+ portfolioReturnsData: PortfolioReturnsData | null;
+ dataSource: DataSourceType;
+ isLoadingPortfolio: boolean;
+ historicalDays: number;
+
+ // UI state
+ expandedSections: ExpandedSections;
+}
+
+// Component props interfaces
+export interface MetricRowProps {
+ label: string;
+ value: string;
+ positive?: boolean;
+ negative?: boolean;
+}
+
+export interface GreekRowProps {
+ label: string;
+ value: number | undefined;
+ description: string;
+}
+
+export interface PortfolioRiskModeProps {
+ weights: string;
+ setWeights: (value: string) => void;
+ alpha: number;
+ setAlpha: (value: number) => void;
+ halfLife: number;
+ setHalfLife: (value: number) => void;
+ isLoading: boolean;
+ analysisResult: AnalysisResult | null;
+ expandedSections: ExpandedSections;
+ toggleSection: (section: keyof ExpandedSections) => void;
+ runPortfolioAnalysis: () => Promise<void>;
+}
+
+export interface OptionPricingModeProps {
+ spotPrice: number;
+ setSpotPrice: (value: number) => void;
+ strike: number;
+ setStrike: (value: number) => void;
+ volatility: number;
+ setVolatility: (value: number) => void;
+ riskFreeRate: number;
+ setRiskFreeRate: (value: number) => void;
+ dividendYield: number;
+ setDividendYield: (value: number) => void;
+ timeToMaturity: number;
+ setTimeToMaturity: (value: number) => void;
+ isLoading: boolean;
+ optionResult: any;
+ greeksResult: OptionGreeksResponse | null;
+ runOptionPricing: () => Promise<void>;
+ runOptionGreeks: () => Promise<void>;
+}
+
+export interface OptimizationModeProps {
+ optimizationType: OptimizationType;
+ setOptimizationType: (value: OptimizationType) => void;
+ optimizationObjective: OptimizationObjective;
+ setOptimizationObjective: (value: OptimizationObjective) => void;
+ optMaxWeight: number;
+ setOptMaxWeight: (value: number) => void;
+ optTargetReturn: number;
+ setOptTargetReturn: (value: number) => void;
+ optAlpha: number;
+ setOptAlpha: (value: number) => void;
+ optLongOnly: boolean;
+ setOptLongOnly: (value: boolean) => void;
+ riskFreeRate: number;
+ isLoading: boolean;
+ optimizationResult: OptimizationResult | null;
+ frontierResult: EfficientFrontierResponse | null;
+ selectedFrontierIndex: number | null;
+ setSelectedFrontierIndex: (value: number | null) => void;
+ runOptimization: () => Promise<void>;
+ runEfficientFrontier: () => Promise<void>;
+}
+
+export interface EntropyPoolingModeProps {
+ nScenarios: number;
+ setNScenarios: (value: number) => void;
+ maxProbability: number;
+ setMaxProbability: (value: number) => void;
+ isLoading: boolean;
+ entropyResult: any;
+ runEntropyPooling: () => Promise<void>;
+}
+
+export interface DataSourceSelectorProps {
+ dataSource: DataSourceType;
+ setDataSource: (value: DataSourceType) => void;
+ userPortfolios: Portfolio[];
+ selectedPortfolioId: string | null;
+ setSelectedPortfolioId: (value: string | null) => void;
+ selectedPortfolioSummary: PortfolioSummary | null;
+ portfolioReturnsData: PortfolioReturnsData | null;
+ historicalDays: number;
+ setHistoricalDays: (value: number) => void;
+ isLoadingPortfolio: boolean;
+ loadPortfolioData: (portfolioId: string) => Promise<void>;
+}
+
+// Re-export service types for convenience
+export type {
+ PortfolioMetrics,
+ OptionGreeksResponse,
+ OptimizationResult,
+ EfficientFrontierResponse,
+ OptimizationObjective
+};
+export type { PortfolioReturnsData };
+export type { Portfolio, PortfolioSummary };
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/utils/formatters.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/utils/formatters.ts
new file mode 100644
index 000000000..12cf8d103
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/utils/formatters.ts
@@ -0,0 +1,70 @@
+/**
+ * Fortitudo Panel Formatting Utilities
+ */
+
+import { FINCEPT } from '../constants';
+
+/**
+ * Format a number as a percentage string
+ */
+export function formatPercent(value: number | null | undefined): string {
+ if (value === null || value === undefined || isNaN(value)) return 'N/A';
+ return `${(value * 100).toFixed(2)}%`;
+}
+
+/**
+ * Format a number as a ratio with 3 decimal places
+ */
+export function formatRatio(value: number | null | undefined): string {
+ if (value === null || value === undefined || isNaN(value)) return 'N/A';
+ return value.toFixed(3);
+}
+
+/**
+ * Format a Greek value with 4 decimal places
+ */
+export function formatGreek(val: number | undefined): string {
+ if (val === undefined || val === null || isNaN(val)) return 'N/A';
+ return val.toFixed(4);
+}
+
+/**
+ * Get color for Greek value based on sign
+ */
+export function getGreekValueColor(val: number | undefined): string {
+ if (val === undefined || val === null || isNaN(val)) return FINCEPT.GRAY;
+ if (val > 0) return FINCEPT.GREEN;
+ if (val < 0) return FINCEPT.RED;
+ return FINCEPT.WHITE;
+}
+
+/**
+ * Normalize weights from object or array to array with asset names
+ */
+export function normalizeWeights(
+ weights: number[] | Record<string, number> | undefined,
+ assets: string[] | undefined
+): { asset: string; weight: number }[] {
+ if (!weights) return [];
+
+ if (Array.isArray(weights)) {
+ return weights.map((w, idx) => ({
+ asset: assets?.[idx] || `Asset ${idx + 1}`,
+ weight: w
+ }));
+ } else {
+ // weights is an object {assetName: weight}
+ return Object.entries(weights).map(([asset, weight]) => ({
+ asset,
+ weight: weight as number
+ }));
+ }
+}
+
+/**
+ * Format currency value
+ */
+export function formatCurrency(value: number | null | undefined, decimals: number = 2): string {
+ if (value === null || value === undefined || isNaN(value)) return 'N/A';
+ return `$${value.toFixed(decimals)}`;
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/utils/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/utils/index.ts
new file mode 100644
index 000000000..6ff6bbc9a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/fortitudo/utils/index.ts
@@ -0,0 +1,5 @@
+/**
+ * Fortitudo Utils Barrel Export
+ */
+
+export * from './formatters';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/FunctimePanel.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/FunctimePanel.tsx
new file mode 100644
index 000000000..568922167
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/FunctimePanel.tsx
@@ -0,0 +1,221 @@
+/**
+ * FunctimePanel - Main Component
+ * Functime Analytics Panel - Time Series Forecasting
+ * Integrated with functime library via PyO3
+ */
+
+import React from 'react';
+import {
+ Zap,
+ Play,
+ RefreshCw,
+ AlertCircle,
+ LineChart
+} from 'lucide-react';
+import { FINCEPT, SAMPLE_DATA } from './constants';
+import { useFunctimeState } from './hooks';
+import {
+ LoadingState,
+ UnavailableState,
+ DataSourceSection,
+ AnalysisModeSelector,
+ ForecastConfigSection,
+ AnomalyConfigSection,
+ SeasonalityConfigSection
+} from './components';
+import {
+ ForecastResults,
+ AnomalyResults,
+ SeasonalityResults
+} from './results';
+
+export function FunctimePanel() {
+ const state = useFunctimeState();
+
+ // Loading state
+ if (state.isFunctimeAvailable === null) {
+ return <LoadingState />;
+ }
+
+ // Not available state
+ if (!state.isFunctimeAvailable) {
+ return <UnavailableState onRetry={state.checkFunctimeStatus} />;
+ }
+
+ return (
+ <div className="flex h-full" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ {/* Left Panel - Configuration */}
+ <div
+ className="w-96 flex flex-col border-r"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, borderColor: FINCEPT.BORDER }}
+ >
+ {/* Input Header */}
+ <div
+ className="px-4 py-3 border-b flex items-center gap-2"
+ style={{ backgroundColor: FINCEPT.HEADER_BG, borderColor: FINCEPT.BORDER }}
+ >
+ <Zap size={16} color={FINCEPT.ORANGE} />
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ Time Series Forecasting
+ </span>
+ </div>
+
+ {/* Scrollable Content */}
+ <div className="flex-1 overflow-auto p-4 space-y-4">
+ {/* Data Source Selection */}
+ <DataSourceSection
+ dataSourceType={state.dataSourceType}
+ setDataSourceType={state.setDataSourceType}
+ portfolios={state.portfolios}
+ selectedPortfolioId={state.selectedPortfolioId}
+ setSelectedPortfolioId={state.setSelectedPortfolioId}
+ symbolInput={state.symbolInput}
+ setSymbolInput={state.setSymbolInput}
+ historicalDays={state.historicalDays}
+ setHistoricalDays={state.setHistoricalDays}
+ priceDataLoading={state.priceDataLoading}
+ priceData={state.priceData}
+ loadDataFromSource={state.loadDataFromSource}
+ expanded={state.expandedSections.dataSource}
+ toggleSection={() => state.toggleSection('dataSource')}
+ />
+
+ {/* Analysis Mode Tabs */}
+ <AnalysisModeSelector
+ analysisMode={state.analysisMode}
+ setAnalysisMode={state.setAnalysisMode}
+ />
+
+ {/* Data Input - Only for Manual */}
+ {state.dataSourceType === 'manual' && (
+ <div>
+ <label className="block text-xs font-mono mb-2" style={{ color: FINCEPT.GRAY }}>
+ PANEL DATA (JSON)
+ </label>
+ <textarea
+ value={state.dataInput}
+ onChange={(e) => state.setDataInput(e.target.value)}
+ className="w-full h-32 p-3 rounded text-xs font-mono resize-none"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ placeholder='[{"entity_id": "A", "time": "2024-01-01", "value": 100}, ...]'
+ />
+ </div>
+ )}
+
+ {/* Model Configuration - Shown for forecast mode */}
+ {state.analysisMode === 'forecast' && (
+ <ForecastConfigSection
+ selectedModel={state.selectedModel}
+ setSelectedModel={state.setSelectedModel}
+ horizon={state.horizon}
+ setHorizon={state.setHorizon}
+ frequency={state.frequency}
+ setFrequency={state.setFrequency}
+ alpha={state.alpha}
+ setAlpha={state.setAlpha}
+ testSize={state.testSize}
+ setTestSize={state.setTestSize}
+ preprocess={state.preprocess}
+ setPreprocess={state.setPreprocess}
+ expanded={state.expandedSections.config}
+ toggleSection={() => state.toggleSection('config')}
+ />
+ )}
+
+ {/* Anomaly Detection Configuration */}
+ {state.analysisMode === 'anomaly' && (
+ <AnomalyConfigSection
+ anomalyMethod={state.anomalyMethod}
+ setAnomalyMethod={state.setAnomalyMethod}
+ anomalyThreshold={state.anomalyThreshold}
+ setAnomalyThreshold={state.setAnomalyThreshold}
+ />
+ )}
+
+ {/* Seasonality Analysis Configuration */}
+ {state.analysisMode === 'seasonality' && (
+ <SeasonalityConfigSection />
+ )}
+ </div>
+
+ {/* Run Button */}
+ <div className="p-4 border-t" style={{ borderColor: FINCEPT.BORDER }}>
+ <button
+ onClick={state.runAnalysis}
+ disabled={state.isLoading}
+ className="w-full py-3 rounded font-bold text-sm uppercase flex items-center justify-center gap-2 disabled:opacity-50"
+ style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
+ >
+ {state.isLoading ? (
+ <>
+ <RefreshCw size={16} className="animate-spin" />
+ {state.analysisMode === 'forecast' ? 'FORECASTING...' :
+ state.analysisMode === 'anomaly' ? 'DETECTING...' : 'ANALYZING...'}
+ </>
+ ) : (
+ <>
+ <Play size={16} />
+ {state.analysisMode === 'forecast' ? 'RUN FORECAST' :
+ state.analysisMode === 'anomaly' ? 'DETECT ANOMALIES' : 'ANALYZE SEASONALITY'}
+ </>
+ )}
+ </button>
+ </div>
+ </div>
+
+ {/* Right Panel - Results */}
+ <div className="flex-1 overflow-auto p-4">
+ {state.error && (
+ <div
+ className="mb-4 p-4 rounded flex items-center gap-3"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, borderLeft: `3px solid ${FINCEPT.RED}` }}
+ >
+ <AlertCircle size={20} color={FINCEPT.RED} />
+ <span className="text-sm font-mono" style={{ color: FINCEPT.RED }}>{state.error}</span>
+ </div>
+ )}
+
+ {!state.analysisResult && !state.anomalyResult && !state.seasonalityResult && !state.error && (
+ <div className="flex items-center justify-center h-full">
+ <div className="text-center">
+ <LineChart size={64} color={FINCEPT.MUTED} className="mx-auto mb-4" />
+ <p className="text-sm font-mono" style={{ color: FINCEPT.GRAY }}>
+ {state.analysisMode === 'forecast'
+ ? 'Configure model and click "Run Forecast" to see predictions'
+ : state.analysisMode === 'anomaly'
+ ? 'Click "Detect Anomalies" to find outliers in your data'
+ : 'Click "Analyze Seasonality" to discover patterns'}
+ </p>
+ </div>
+ </div>
+ )}
+
+ {/* Anomaly Detection Results */}
+ {state.anomalyResult && state.anomalyResult.success && (
+ <AnomalyResults anomalyResult={state.anomalyResult} />
+ )}
+
+ {/* Seasonality Results */}
+ {state.seasonalityResult && state.seasonalityResult.success && (
+ <SeasonalityResults seasonalityResult={state.seasonalityResult} />
+ )}
+
+ {/* Forecast Results */}
+ {state.analysisResult && (
+ <ForecastResults
+ analysisResult={state.analysisResult}
+ expandedSections={state.expandedSections}
+ toggleSection={state.toggleSection}
+ historicalData={state.historicalData}
+ />
+ )}
+ </div>
+ </div>
+ );
+}
+
+export default FunctimePanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/AnalysisModeSelector.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/AnalysisModeSelector.tsx
new file mode 100644
index 000000000..0df132311
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/AnalysisModeSelector.tsx
@@ -0,0 +1,57 @@
+/**
+ * AnalysisModeSelector Component
+ * Tab-style selector for switching between analysis modes
+ */
+
+import React from 'react';
+import { TrendingUp, AlertTriangle, Waves } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { AnalysisMode } from '../types';
+
+interface AnalysisModeSelectorProps {
+ analysisMode: AnalysisMode;
+ setAnalysisMode: (mode: AnalysisMode) => void;
+}
+
+export const AnalysisModeSelector: React.FC<AnalysisModeSelectorProps> = ({
+ analysisMode,
+ setAnalysisMode
+}) => {
+ return (
+ <div className="flex gap-1 p-1 rounded" style={{ backgroundColor: FINCEPT.HEADER_BG }}>
+ <button
+ onClick={() => setAnalysisMode('forecast')}
+ className="flex-1 px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"
+ style={{
+ backgroundColor: analysisMode === 'forecast' ? FINCEPT.ORANGE : 'transparent',
+ color: analysisMode === 'forecast' ? FINCEPT.DARK_BG : FINCEPT.GRAY
+ }}
+ >
+ <TrendingUp size={12} />
+ Forecast
+ </button>
+ <button
+ onClick={() => setAnalysisMode('anomaly')}
+ className="flex-1 px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"
+ style={{
+ backgroundColor: analysisMode === 'anomaly' ? FINCEPT.ORANGE : 'transparent',
+ color: analysisMode === 'anomaly' ? FINCEPT.DARK_BG : FINCEPT.GRAY
+ }}
+ >
+ <AlertTriangle size={12} />
+ Anomaly
+ </button>
+ <button
+ onClick={() => setAnalysisMode('seasonality')}
+ className="flex-1 px-2 py-1.5 rounded text-xs font-mono flex items-center justify-center gap-1"
+ style={{
+ backgroundColor: analysisMode === 'seasonality' ? FINCEPT.ORANGE : 'transparent',
+ color: analysisMode === 'seasonality' ? FINCEPT.DARK_BG : FINCEPT.GRAY
+ }}
+ >
+ <Waves size={12} />
+ Season
+ </button>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/AnomalyConfigSection.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/AnomalyConfigSection.tsx
new file mode 100644
index 000000000..020f232fe
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/AnomalyConfigSection.tsx
@@ -0,0 +1,73 @@
+/**
+ * AnomalyConfigSection Component
+ * Configuration for anomaly detection
+ */
+
+import React from 'react';
+import { AlertTriangle } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { AnomalyConfigProps } from '../types';
+
+export const AnomalyConfigSection: React.FC<AnomalyConfigProps> = ({
+ anomalyMethod,
+ setAnomalyMethod,
+ anomalyThreshold,
+ setAnomalyThreshold
+}) => {
+ return (
+ <div
+ className="rounded overflow-hidden"
+ style={{ border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <div
+ className="px-3 py-2 flex items-center gap-2"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <AlertTriangle size={14} color={FINCEPT.YELLOW} />
+ <span className="text-xs font-bold uppercase" style={{ color: FINCEPT.WHITE }}>
+ Anomaly Detection Settings
+ </span>
+ </div>
+ <div className="p-3 space-y-3">
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ DETECTION METHOD
+ </label>
+ <select
+ value={anomalyMethod}
+ onChange={(e) => setAnomalyMethod(e.target.value as 'zscore' | 'iqr' | 'isolation_forest')}
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ >
+ <option value="zscore">Z-Score</option>
+ <option value="iqr">IQR (Interquartile Range)</option>
+ <option value="isolation_forest">Isolation Forest</option>
+ </select>
+ </div>
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ THRESHOLD
+ </label>
+ <input
+ type="number"
+ step="0.5"
+ min={1}
+ max={5}
+ value={anomalyThreshold}
+ onChange={(e) => setAnomalyThreshold(parseFloat(e.target.value) || 3.0)}
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/DataSourceSection.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/DataSourceSection.tsx
new file mode 100644
index 000000000..f89e17af6
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/DataSourceSection.tsx
@@ -0,0 +1,206 @@
+/**
+ * DataSourceSection Component
+ * Data source selection and configuration
+ */
+
+import React from 'react';
+import { Database, Briefcase, Search, ChevronUp, ChevronDown, RefreshCw } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { DataSourceSectionProps } from '../types';
+
+export const DataSourceSection: React.FC<DataSourceSectionProps> = ({
+ dataSourceType,
+ setDataSourceType,
+ portfolios,
+ selectedPortfolioId,
+ setSelectedPortfolioId,
+ symbolInput,
+ setSymbolInput,
+ historicalDays,
+ setHistoricalDays,
+ priceDataLoading,
+ priceData,
+ loadDataFromSource,
+ expanded,
+ toggleSection
+}) => {
+ return (
+ <div
+ className="rounded overflow-hidden"
+ style={{ border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <button
+ onClick={toggleSection}
+ className="w-full px-3 py-2 flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <Database size={14} color={FINCEPT.CYAN} />
+ <span className="text-xs font-bold uppercase" style={{ color: FINCEPT.WHITE }}>
+ Data Source
+ </span>
+ </div>
+ {expanded ? (
+ <ChevronUp size={14} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={14} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expanded && (
+ <div className="p-3 space-y-3">
+ {/* Source Type Selection */}
+ <div className="flex gap-2">
+ <button
+ onClick={() => setDataSourceType('manual')}
+ className={`flex-1 px-2 py-1.5 rounded text-xs font-mono ${dataSourceType === 'manual' ? 'border-2' : ''}`}
+ style={{
+ backgroundColor: dataSourceType === 'manual' ? FINCEPT.HEADER_BG : FINCEPT.DARK_BG,
+ borderColor: FINCEPT.ORANGE,
+ color: dataSourceType === 'manual' ? FINCEPT.ORANGE : FINCEPT.GRAY
+ }}
+ >
+ Manual
+ </button>
+ <button
+ onClick={() => setDataSourceType('portfolio')}
+ className={`flex-1 px-2 py-1.5 rounded text-xs font-mono ${dataSourceType === 'portfolio' ? 'border-2' : ''}`}
+ style={{
+ backgroundColor: dataSourceType === 'portfolio' ? FINCEPT.HEADER_BG : FINCEPT.DARK_BG,
+ borderColor: FINCEPT.ORANGE,
+ color: dataSourceType === 'portfolio' ? FINCEPT.ORANGE : FINCEPT.GRAY
+ }}
+ >
+ <Briefcase size={12} className="inline mr-1" />
+ Portfolio
+ </button>
+ <button
+ onClick={() => setDataSourceType('symbol')}
+ className={`flex-1 px-2 py-1.5 rounded text-xs font-mono ${dataSourceType === 'symbol' ? 'border-2' : ''}`}
+ style={{
+ backgroundColor: dataSourceType === 'symbol' ? FINCEPT.HEADER_BG : FINCEPT.DARK_BG,
+ borderColor: FINCEPT.ORANGE,
+ color: dataSourceType === 'symbol' ? FINCEPT.ORANGE : FINCEPT.GRAY
+ }}
+ >
+ <Search size={12} className="inline mr-1" />
+ Symbol
+ </button>
+ </div>
+
+ {/* Portfolio Selection */}
+ {dataSourceType === 'portfolio' && (
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ SELECT PORTFOLIO
+ </label>
+ <select
+ value={selectedPortfolioId}
+ onChange={(e) => setSelectedPortfolioId(e.target.value)}
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ >
+ {portfolios.length === 0 ? (
+ <option value="">No portfolios found</option>
+ ) : (
+ portfolios.map((p) => (
+ <option key={p.id} value={p.id}>
+ {p.name}
+ </option>
+ ))
+ )}
+ </select>
+ </div>
+ )}
+
+ {/* Symbol Input */}
+ {dataSourceType === 'symbol' && (
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ TICKER SYMBOL
+ </label>
+ <input
+ type="text"
+ value={symbolInput}
+ onChange={(e) => setSymbolInput(e.target.value.toUpperCase())}
+ placeholder="AAPL"
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ />
+ </div>
+ )}
+
+ {/* Historical Days */}
+ {dataSourceType !== 'manual' && (
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ HISTORICAL DAYS
+ </label>
+ <input
+ type="number"
+ min={30}
+ max={1825}
+ value={historicalDays}
+ onChange={(e) => setHistoricalDays(parseInt(e.target.value) || 365)}
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ />
+ </div>
+ )}
+
+ {/* Load Data Button */}
+ {dataSourceType !== 'manual' && (
+ <button
+ onClick={loadDataFromSource}
+ disabled={priceDataLoading}
+ className="w-full py-2 rounded font-bold text-xs uppercase flex items-center justify-center gap-2"
+ style={{ backgroundColor: FINCEPT.CYAN, color: FINCEPT.DARK_BG }}
+ >
+ {priceDataLoading ? (
+ <>
+ <RefreshCw size={12} className="animate-spin" />
+ Loading...
+ </>
+ ) : (
+ <>
+ <Database size={12} />
+ Fetch Data
+ </>
+ )}
+ </button>
+ )}
+
+ {/* Data Info */}
+ {priceData && dataSourceType !== 'manual' && (
+ <div className="p-2 rounded text-xs font-mono" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <div className="flex justify-between" style={{ color: FINCEPT.GRAY }}>
+ <span>Assets:</span>
+ <span style={{ color: FINCEPT.CYAN }}>{priceData.assets.length}</span>
+ </div>
+ <div className="flex justify-between" style={{ color: FINCEPT.GRAY }}>
+ <span>Data Points:</span>
+ <span style={{ color: FINCEPT.WHITE }}>{priceData.nDataPoints}</span>
+ </div>
+ <div className="flex justify-between" style={{ color: FINCEPT.GRAY }}>
+ <span>Range:</span>
+ <span style={{ color: FINCEPT.WHITE }}>{priceData.startDate} to {priceData.endDate}</span>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/ForecastChart.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/ForecastChart.tsx
new file mode 100644
index 000000000..3ed52711f
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/ForecastChart.tsx
@@ -0,0 +1,370 @@
+/**
+ * ForecastChart Component
+ * Interactive SVG-based line chart with tooltips for time series visualization
+ */
+
+import React, { useState, useMemo, useRef } from 'react';
+import { FINCEPT } from '../constants';
+import type { ForecastChartProps, ChartDataPoint, TooltipState } from '../types';
+
+export const ForecastChart: React.FC<ForecastChartProps> = ({
+ historicalData,
+ forecastData,
+ height = 300
+}) => {
+ const [tooltip, setTooltip] = useState<TooltipState>({ visible: false, x: 0, y: 0, data: null });
+ const [zoomLevel, setZoomLevel] = useState(1);
+ const [panOffset, setPanOffset] = useState(0);
+ const svgRef = useRef<SVGSVGElement>(null);
+
+ const chartData = useMemo(() => {
+ const historical: ChartDataPoint[] = historicalData.map(d => ({
+ time: d.time,
+ value: d.value,
+ type: 'historical' as const
+ }));
+
+ const forecast: ChartDataPoint[] = forecastData.map(d => ({
+ time: d.time,
+ value: d.value,
+ type: 'forecast' as const,
+ entity_id: d.entity_id
+ }));
+
+ return [...historical, ...forecast];
+ }, [historicalData, forecastData]);
+
+ if (chartData.length === 0) {
+ return (
+ <div
+ className="flex items-center justify-center"
+ style={{ height, backgroundColor: FINCEPT.DARK_BG }}
+ >
+ <span className="text-sm font-mono" style={{ color: FINCEPT.GRAY }}>
+ No data to display
+ </span>
+ </div>
+ );
+ }
+
+ const baseWidth = 800;
+ const width = baseWidth * zoomLevel;
+ const padding = { top: 20, right: 60, bottom: 40, left: 60 };
+ const chartWidth = width - padding.left - padding.right;
+ const chartHeight = height - padding.top - padding.bottom;
+
+ // Calculate scales
+ const values = chartData.map(d => d.value);
+ const minValue = Math.min(...values);
+ const maxValue = Math.max(...values);
+ const valueRange = maxValue - minValue || 1;
+ const yMin = minValue - valueRange * 0.1;
+ const yMax = maxValue + valueRange * 0.1;
+
+ const xScale = (index: number) => padding.left + (index / (chartData.length - 1 || 1)) * chartWidth;
+ const yScale = (value: number) => padding.top + chartHeight - ((value - yMin) / (yMax - yMin)) * chartHeight;
+
+ // Find split point between historical and forecast
+ const historicalEndIndex = historicalData.length - 1;
+
+ // Generate path for historical data
+ const historicalPath = historicalData
+ .map((d, i) => {
+ const x = xScale(i);
+ const y = yScale(d.value);
+ return `${i === 0 ? 'M' : 'L'} ${x} ${y}`;
+ })
+ .join(' ');
+
+ // Generate path for forecast data (starts from last historical point)
+ const forecastPath = forecastData.length > 0
+ ? [
+ historicalData.length > 0
+ ? `M ${xScale(historicalEndIndex)} ${yScale(historicalData[historicalEndIndex]?.value ?? forecastData[0].value)}`
+ : `M ${xScale(0)} ${yScale(forecastData[0].value)}`,
+ ...forecastData.map((d, i) => {
+ const x = xScale(historicalData.length + i);
+ const y = yScale(d.value);
+ return `L ${x} ${y}`;
+ })
+ ].join(' ')
+ : '';
+
+ // Y-axis ticks
+ const yTicks = Array.from({ length: 5 }, (_, i) => {
+ const value = yMin + (yMax - yMin) * (i / 4);
+ return { value, y: yScale(value) };
+ });
+
+ // X-axis labels (show first, middle, last, and split point)
+ const xLabels = [
+ { index: 0, label: chartData[0]?.time.split('T')[0] || '' },
+ { index: historicalEndIndex, label: chartData[historicalEndIndex]?.time.split('T')[0] || '' },
+ { index: chartData.length - 1, label: chartData[chartData.length - 1]?.time.split('T')[0] || '' }
+ ].filter((item, index, arr) =>
+ arr.findIndex(t => t.index === item.index) === index && item.label
+ );
+
+ // Handle mouse events for interactive tooltips
+ const handleMouseEnter = (data: ChartDataPoint, x: number, y: number) => {
+ setTooltip({ visible: true, x, y, data });
+ };
+
+ const handleMouseLeave = () => {
+ setTooltip({ visible: false, x: 0, y: 0, data: null });
+ };
+
+ // Zoom controls
+ const handleZoomIn = () => setZoomLevel(prev => Math.min(prev + 0.5, 3));
+ const handleZoomOut = () => setZoomLevel(prev => Math.max(prev - 0.5, 1));
+ const handleResetZoom = () => { setZoomLevel(1); setPanOffset(0); };
+
+ return (
+ <div className="w-full">
+ {/* Zoom Controls */}
+ <div className="flex justify-end gap-2 mb-2">
+ <button
+ onClick={handleZoomOut}
+ className="px-2 py-1 rounded text-xs font-mono"
+ style={{ backgroundColor: FINCEPT.HEADER_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}` }}
+ disabled={zoomLevel <= 1}
+ >
+ -
+ </button>
+ <span className="px-2 py-1 text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ {Math.round(zoomLevel * 100)}%
+ </span>
+ <button
+ onClick={handleZoomIn}
+ className="px-2 py-1 rounded text-xs font-mono"
+ style={{ backgroundColor: FINCEPT.HEADER_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}` }}
+ disabled={zoomLevel >= 3}
+ >
+ +
+ </button>
+ {zoomLevel !== 1 && (
+ <button
+ onClick={handleResetZoom}
+ className="px-2 py-1 rounded text-xs font-mono"
+ style={{ backgroundColor: FINCEPT.HEADER_BG, color: FINCEPT.ORANGE, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ Reset
+ </button>
+ )}
+ </div>
+
+ {/* Chart Container with horizontal scroll */}
+ <div className="overflow-x-auto" style={{ position: 'relative' }}>
+ <svg
+ ref={svgRef}
+ width={width}
+ height={height}
+ viewBox={`0 0 ${width} ${height}`}
+ style={{ backgroundColor: FINCEPT.DARK_BG, minWidth: baseWidth }}
+ >
+ {/* Grid lines */}
+ {yTicks.map((tick, i) => (
+ <line
+ key={i}
+ x1={padding.left}
+ y1={tick.y}
+ x2={width - padding.right}
+ y2={tick.y}
+ stroke={FINCEPT.BORDER}
+ strokeWidth={1}
+ strokeDasharray="4,4"
+ />
+ ))}
+
+ {/* Forecast region background */}
+ {forecastData.length > 0 && (
+ <rect
+ x={xScale(historicalEndIndex)}
+ y={padding.top}
+ width={chartWidth - xScale(historicalEndIndex) + padding.left}
+ height={chartHeight}
+ fill={FINCEPT.ORANGE}
+ opacity={0.05}
+ />
+ )}
+
+ {/* Vertical line at forecast start */}
+ {forecastData.length > 0 && historicalData.length > 0 && (
+ <line
+ x1={xScale(historicalEndIndex)}
+ y1={padding.top}
+ x2={xScale(historicalEndIndex)}
+ y2={height - padding.bottom}
+ stroke={FINCEPT.ORANGE}
+ strokeWidth={1}
+ strokeDasharray="6,4"
+ opacity={0.6}
+ />
+ )}
+
+ {/* Historical line */}
+ {historicalPath && (
+ <path
+ d={historicalPath}
+ fill="none"
+ stroke={FINCEPT.CYAN}
+ strokeWidth={2}
+ />
+ )}
+
+ {/* Forecast line */}
+ {forecastPath && (
+ <path
+ d={forecastPath}
+ fill="none"
+ stroke={FINCEPT.ORANGE}
+ strokeWidth={2}
+ strokeDasharray="6,3"
+ />
+ )}
+
+ {/* Historical data points - Interactive */}
+ {historicalData.map((d, i) => {
+ const cx = xScale(i);
+ const cy = yScale(d.value);
+ const dataPoint: ChartDataPoint = { time: d.time, value: d.value, type: 'historical' };
+ return (
+ <g key={`hist-${i}`}>
+ {/* Larger invisible hit area */}
+ <circle
+ cx={cx}
+ cy={cy}
+ r={12}
+ fill="transparent"
+ style={{ cursor: 'pointer' }}
+ onMouseEnter={() => handleMouseEnter(dataPoint, cx, cy)}
+ onMouseLeave={handleMouseLeave}
+ />
+ {/* Visible point */}
+ <circle
+ cx={cx}
+ cy={cy}
+ r={tooltip.data?.time === d.time && tooltip.data?.type === 'historical' ? 6 : 3}
+ fill={FINCEPT.CYAN}
+ style={{ transition: 'r 0.15s ease', pointerEvents: 'none' }}
+ />
+ </g>
+ );
+ })}
+
+ {/* Forecast data points - Interactive */}
+ {forecastData.map((d, i) => {
+ const cx = xScale(historicalData.length + i);
+ const cy = yScale(d.value);
+ const dataPoint: ChartDataPoint = { time: d.time, value: d.value, type: 'forecast', entity_id: d.entity_id };
+ return (
+ <g key={`forecast-${i}`}>
+ {/* Larger invisible hit area */}
+ <circle
+ cx={cx}
+ cy={cy}
+ r={12}
+ fill="transparent"
+ style={{ cursor: 'pointer' }}
+ onMouseEnter={() => handleMouseEnter(dataPoint, cx, cy)}
+ onMouseLeave={handleMouseLeave}
+ />
+ {/* Visible point */}
+ <circle
+ cx={cx}
+ cy={cy}
+ r={tooltip.data?.time === d.time && tooltip.data?.type === 'forecast' ? 7 : 4}
+ fill={FINCEPT.ORANGE}
+ stroke={FINCEPT.DARK_BG}
+ strokeWidth={1}
+ style={{ transition: 'r 0.15s ease', pointerEvents: 'none' }}
+ />
+ </g>
+ );
+ })}
+
+ {/* Y-axis labels */}
+ {yTicks.map((tick, i) => (
+ <text
+ key={i}
+ x={padding.left - 10}
+ y={tick.y + 4}
+ textAnchor="end"
+ fontSize={10}
+ fontFamily="monospace"
+ fill={FINCEPT.GRAY}
+ >
+ {tick.value.toFixed(2)}
+ </text>
+ ))}
+
+ {/* X-axis labels */}
+ {xLabels.map((item, i) => (
+ <text
+ key={i}
+ x={xScale(item.index)}
+ y={height - padding.bottom + 20}
+ textAnchor="middle"
+ fontSize={10}
+ fontFamily="monospace"
+ fill={FINCEPT.GRAY}
+ >
+ {item.label}
+ </text>
+ ))}
+
+ {/* Legend */}
+ <g transform={`translate(${width - padding.right - 120}, ${padding.top})`}>
+ <rect x={0} y={0} width={120} height={50} fill={FINCEPT.PANEL_BG} rx={4} />
+ <line x1={10} y1={15} x2={35} y2={15} stroke={FINCEPT.CYAN} strokeWidth={2} />
+ <text x={42} y={18} fontSize={10} fontFamily="monospace" fill={FINCEPT.WHITE}>Historical</text>
+ <line x1={10} y1={35} x2={35} y2={35} stroke={FINCEPT.ORANGE} strokeWidth={2} strokeDasharray="6,3" />
+ <text x={42} y={38} fontSize={10} fontFamily="monospace" fill={FINCEPT.WHITE}>Forecast</text>
+ </g>
+
+ {/* Forecast label */}
+ {forecastData.length > 0 && historicalData.length > 0 && (
+ <text
+ x={xScale(historicalEndIndex) + 5}
+ y={padding.top + 15}
+ fontSize={10}
+ fontFamily="monospace"
+ fill={FINCEPT.ORANGE}
+ >
+ Forecast
+ </text>
+ )}
+ </svg>
+
+ {/* Tooltip */}
+ {tooltip.visible && tooltip.data && (
+ <div
+ className="absolute pointer-events-none px-3 py-2 rounded shadow-lg z-50"
+ style={{
+ left: Math.min(tooltip.x + 10, width - 180),
+ top: Math.max(tooltip.y - 60, 10),
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${tooltip.data.type === 'forecast' ? FINCEPT.ORANGE : FINCEPT.CYAN}`,
+ minWidth: 160
+ }}
+ >
+ <div className="text-xs font-mono font-bold mb-1" style={{ color: tooltip.data.type === 'forecast' ? FINCEPT.ORANGE : FINCEPT.CYAN }}>
+ {tooltip.data.type === 'forecast' ? 'FORECAST' : 'HISTORICAL'}
+ </div>
+ <div className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ Date: <span style={{ color: FINCEPT.WHITE }}>{tooltip.data.time.split('T')[0]}</span>
+ </div>
+ <div className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ Value: <span style={{ color: FINCEPT.GREEN, fontWeight: 'bold' }}>{tooltip.data.value.toFixed(4)}</span>
+ </div>
+ {tooltip.data.entity_id && (
+ <div className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ Entity: <span style={{ color: FINCEPT.CYAN }}>{tooltip.data.entity_id}</span>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/ForecastConfigSection.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/ForecastConfigSection.tsx
new file mode 100644
index 000000000..85d1aa5c6
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/ForecastConfigSection.tsx
@@ -0,0 +1,189 @@
+/**
+ * ForecastConfigSection Component
+ * Model configuration for forecasting
+ */
+
+import React from 'react';
+import { Settings, ChevronUp, ChevronDown } from 'lucide-react';
+import { functimeService } from '@/services/aiQuantLab/functimeService';
+import { FINCEPT } from '../constants';
+import type { ForecastConfigProps } from '../types';
+
+export const ForecastConfigSection: React.FC<ForecastConfigProps> = ({
+ selectedModel,
+ setSelectedModel,
+ horizon,
+ setHorizon,
+ frequency,
+ setFrequency,
+ alpha,
+ setAlpha,
+ testSize,
+ setTestSize,
+ preprocess,
+ setPreprocess,
+ expanded,
+ toggleSection
+}) => {
+ const models = functimeService.getAvailableModels();
+ const frequencies = functimeService.getAvailableFrequencies();
+
+ const showAlpha = ['lasso', 'ridge', 'elasticnet', 'auto_lasso', 'auto_ridge', 'auto_elasticnet'].includes(selectedModel);
+
+ return (
+ <div
+ className="rounded overflow-hidden"
+ style={{ border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <button
+ onClick={toggleSection}
+ className="w-full px-3 py-2 flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <Settings size={14} color={FINCEPT.CYAN} />
+ <span className="text-xs font-bold uppercase" style={{ color: FINCEPT.WHITE }}>
+ Model Configuration
+ </span>
+ </div>
+ {expanded ? (
+ <ChevronUp size={14} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={14} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expanded && (
+ <div className="p-3 space-y-3">
+ {/* Model Selection */}
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ FORECAST MODEL
+ </label>
+ <select
+ value={selectedModel}
+ onChange={(e) => setSelectedModel(e.target.value)}
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ >
+ {models.map((m) => (
+ <option key={m.id} value={m.id}>
+ {m.name}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Horizon */}
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ FORECAST HORIZON
+ </label>
+ <input
+ type="number"
+ min={1}
+ max={365}
+ value={horizon}
+ onChange={(e) => setHorizon(parseInt(e.target.value) || 7)}
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ />
+ </div>
+
+ {/* Frequency */}
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ DATA FREQUENCY
+ </label>
+ <select
+ value={frequency}
+ onChange={(e) => setFrequency(e.target.value)}
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ >
+ {frequencies.map((f) => (
+ <option key={f.id} value={f.id}>
+ {f.name}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Alpha (for regularized models) */}
+ {showAlpha && (
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ ALPHA (REGULARIZATION)
+ </label>
+ <input
+ type="number"
+ step="0.1"
+ min={0}
+ value={alpha}
+ onChange={(e) => setAlpha(parseFloat(e.target.value) || 1.0)}
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ />
+ </div>
+ )}
+
+ {/* Test Size */}
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ TEST SIZE (FOR EVALUATION)
+ </label>
+ <input
+ type="number"
+ min={1}
+ value={testSize}
+ onChange={(e) => setTestSize(parseInt(e.target.value) || 5)}
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ />
+ </div>
+
+ {/* Preprocessing */}
+ <div>
+ <label className="block text-xs font-mono mb-1" style={{ color: FINCEPT.GRAY }}>
+ PREPROCESSING
+ </label>
+ <select
+ value={preprocess}
+ onChange={(e) => setPreprocess(e.target.value as 'none' | 'scale' | 'difference')}
+ className="w-full p-2 rounded text-xs font-mono"
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}
+ >
+ <option value="none">None</option>
+ <option value="scale">Standard Scaling</option>
+ <option value="difference">Differencing</option>
+ </select>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/LoadingState.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/LoadingState.tsx
new file mode 100644
index 000000000..3d7f93bc0
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/LoadingState.tsx
@@ -0,0 +1,19 @@
+/**
+ * LoadingState Component
+ * Full-screen loading spinner
+ */
+
+import React from 'react';
+import { RefreshCw } from 'lucide-react';
+import { FINCEPT } from '../constants';
+
+export const LoadingState: React.FC = () => {
+ return (
+ <div
+ className="flex items-center justify-center h-full"
+ style={{ backgroundColor: FINCEPT.DARK_BG }}
+ >
+ <RefreshCw size={32} color={FINCEPT.ORANGE} className="animate-spin" />
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/MetricCard.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/MetricCard.tsx
new file mode 100644
index 000000000..29498170c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/MetricCard.tsx
@@ -0,0 +1,36 @@
+/**
+ * MetricCard Component
+ * Displays a metric with label, value, and icon
+ */
+
+import React from 'react';
+import { FINCEPT } from '../constants';
+import type { MetricCardProps } from '../types';
+
+export const MetricCard: React.FC<MetricCardProps> = ({
+ label,
+ value,
+ color,
+ icon,
+ large = false
+}) => {
+ return (
+ <div
+ className={`p-3 rounded ${large ? 'col-span-3' : ''}`}
+ style={{ backgroundColor: FINCEPT.DARK_BG }}
+ >
+ <div className="flex items-center gap-2 mb-1">
+ <span style={{ color: FINCEPT.GRAY }}>{icon}</span>
+ <span className="text-xs font-mono uppercase" style={{ color: FINCEPT.GRAY }}>
+ {label}
+ </span>
+ </div>
+ <span
+ className={`font-bold font-mono ${large ? 'text-2xl' : 'text-lg'}`}
+ style={{ color }}
+ >
+ {value}
+ </span>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/SeasonalityConfigSection.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/SeasonalityConfigSection.tsx
new file mode 100644
index 000000000..c74c0a908
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/SeasonalityConfigSection.tsx
@@ -0,0 +1,33 @@
+/**
+ * SeasonalityConfigSection Component
+ * Configuration for seasonality analysis (informational)
+ */
+
+import React from 'react';
+import { Waves } from 'lucide-react';
+import { FINCEPT } from '../constants';
+
+export const SeasonalityConfigSection: React.FC = () => {
+ return (
+ <div
+ className="rounded overflow-hidden"
+ style={{ border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <div
+ className="px-3 py-2 flex items-center gap-2"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <Waves size={14} color={FINCEPT.CYAN} />
+ <span className="text-xs font-bold uppercase" style={{ color: FINCEPT.WHITE }}>
+ Seasonality Analysis
+ </span>
+ </div>
+ <div className="p-3">
+ <p className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ Analyzes time series for seasonal patterns, trend strength, and periodicity.
+ Uses FFT and ACF for automatic period detection.
+ </p>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/UnavailableState.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/UnavailableState.tsx
new file mode 100644
index 000000000..c1b01cafc
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/UnavailableState.tsx
@@ -0,0 +1,48 @@
+/**
+ * UnavailableState Component
+ * Shown when functime library is not installed
+ */
+
+import React from 'react';
+import { AlertCircle, RefreshCw } from 'lucide-react';
+import { FINCEPT } from '../constants';
+
+interface UnavailableStateProps {
+ onRetry: () => void;
+}
+
+export const UnavailableState: React.FC<UnavailableStateProps> = ({ onRetry }) => {
+ return (
+ <div
+ className="flex items-center justify-center h-full p-8"
+ style={{ backgroundColor: FINCEPT.DARK_BG }}
+ >
+ <div className="text-center max-w-md">
+ <AlertCircle size={48} color={FINCEPT.RED} className="mx-auto mb-4" />
+ <h3
+ className="text-lg font-bold uppercase mb-2"
+ style={{ color: FINCEPT.WHITE }}
+ >
+ Functime Library Not Installed
+ </h3>
+ <p className="text-sm mb-4" style={{ color: FINCEPT.GRAY }}>
+ Install functime and polars for ML time series forecasting
+ </p>
+ <code
+ className="block p-4 rounded text-sm font-mono mt-4"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, color: FINCEPT.ORANGE }}
+ >
+ pip install functime polars
+ </code>
+ <button
+ onClick={onRetry}
+ className="mt-6 px-6 py-2 rounded font-bold text-sm uppercase flex items-center gap-2 mx-auto"
+ style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
+ >
+ <RefreshCw size={14} />
+ Check Again
+ </button>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/index.ts
new file mode 100644
index 000000000..9a79eba1a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/components/index.ts
@@ -0,0 +1,13 @@
+/**
+ * Functime Components Barrel Export
+ */
+
+export { MetricCard } from './MetricCard';
+export { ForecastChart } from './ForecastChart';
+export { LoadingState } from './LoadingState';
+export { UnavailableState } from './UnavailableState';
+export { DataSourceSection } from './DataSourceSection';
+export { AnalysisModeSelector } from './AnalysisModeSelector';
+export { ForecastConfigSection } from './ForecastConfigSection';
+export { AnomalyConfigSection } from './AnomalyConfigSection';
+export { SeasonalityConfigSection } from './SeasonalityConfigSection';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/constants.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/constants.ts
new file mode 100644
index 000000000..8855647cb
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/constants.ts
@@ -0,0 +1,51 @@
+/**
+ * Functime Panel Constants
+ * Color palette, sample data, and configurations
+ */
+
+// Fincept Professional Color Palette
+export const FINCEPT = {
+ 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'
+};
+
+// Sample panel data for demonstration
+export const SAMPLE_DATA = [
+ { entity_id: 'AAPL', time: '2024-01-02', value: 185.64 },
+ { entity_id: 'AAPL', time: '2024-01-03', value: 184.25 },
+ { entity_id: 'AAPL', time: '2024-01-04', value: 181.91 },
+ { entity_id: 'AAPL', time: '2024-01-05', value: 181.18 },
+ { entity_id: 'AAPL', time: '2024-01-08', value: 185.56 },
+ { entity_id: 'AAPL', time: '2024-01-09', value: 185.14 },
+ { entity_id: 'AAPL', time: '2024-01-10', value: 186.19 },
+ { entity_id: 'AAPL', time: '2024-01-11', value: 185.59 },
+ { entity_id: 'AAPL', time: '2024-01-12', value: 185.92 },
+ { entity_id: 'AAPL', time: '2024-01-16', value: 183.63 },
+ { entity_id: 'AAPL', time: '2024-01-17', value: 182.68 },
+ { entity_id: 'AAPL', time: '2024-01-18', value: 188.63 },
+ { entity_id: 'AAPL', time: '2024-01-19', value: 191.56 },
+ { entity_id: 'AAPL', time: '2024-01-22', value: 193.89 },
+ { entity_id: 'AAPL', time: '2024-01-23', value: 195.18 },
+ { entity_id: 'AAPL', time: '2024-01-24', value: 194.50 },
+ { entity_id: 'AAPL', time: '2024-01-25', value: 194.17 },
+ { entity_id: 'AAPL', time: '2024-01-26', value: 192.42 },
+ { entity_id: 'AAPL', time: '2024-01-29', value: 191.73 },
+ { entity_id: 'AAPL', time: '2024-01-30', value: 188.04 }
+];
+
+// Table pagination constants
+export const INITIAL_ROWS = 10;
+export const EXPANDED_ROWS = 50;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/hooks/index.ts
new file mode 100644
index 000000000..5a380a54d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/hooks/index.ts
@@ -0,0 +1,5 @@
+/**
+ * Functime Hooks Barrel Export
+ */
+
+export { useFunctimeState } from './useFunctimeState';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/hooks/useFunctimeState.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/hooks/useFunctimeState.ts
new file mode 100644
index 000000000..4de83b3f4
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/hooks/useFunctimeState.ts
@@ -0,0 +1,361 @@
+/**
+ * useFunctimeState Hook
+ * Manages all state for the Functime Panel
+ */
+
+import { useState, useEffect, useMemo, useCallback } from 'react';
+import {
+ functimeService,
+ type AnomalyDetectionConfig,
+ type SeasonalityConfig
+} from '@/services/aiQuantLab/functimeService';
+import {
+ portfolioFunctimeService,
+ type PortfolioPriceData,
+ type PortfolioAnomalyResult,
+ type PortfolioSeasonalityResult
+} from '@/services/aiQuantLab/portfolioFunctimeService';
+import type { Portfolio } from '@/services/portfolio/portfolioService';
+import { SAMPLE_DATA } from '../constants';
+import { parseHistoricalData } from '../utils';
+import type {
+ DataSourceType,
+ AnalysisMode,
+ PreprocessType,
+ AnomalyMethod,
+ ForecastAnalysisResult,
+ ExpandedSections
+} from '../types';
+
+export function useFunctimeState() {
+ // Status
+ const [isFunctimeAvailable, setIsFunctimeAvailable] = useState<boolean | null>(null);
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [analysisResult, setAnalysisResult] = useState<ForecastAnalysisResult | null>(null);
+ const [dataInput, setDataInput] = useState(JSON.stringify(SAMPLE_DATA, null, 2));
+
+ // Data source configuration
+ const [dataSourceType, setDataSourceType] = useState<DataSourceType>('manual');
+ const [portfolios, setPortfolios] = useState<Portfolio[]>([]);
+ const [selectedPortfolioId, setSelectedPortfolioId] = useState<string>('');
+ const [symbolInput, setSymbolInput] = useState('AAPL');
+ const [historicalDays, setHistoricalDays] = useState(365);
+ const [priceDataLoading, setPriceDataLoading] = useState(false);
+ const [priceData, setPriceData] = useState<PortfolioPriceData | null>(null);
+
+ // Analysis mode
+ const [analysisMode, setAnalysisMode] = useState<AnalysisMode>('forecast');
+
+ // Forecast configuration
+ const [selectedModel, setSelectedModel] = useState('linear');
+ const [horizon, setHorizon] = useState(7);
+ const [frequency, setFrequency] = useState('1d');
+ const [alpha, setAlpha] = useState(1.0);
+ const [testSize, setTestSize] = useState(5);
+ const [preprocess, setPreprocess] = useState<PreprocessType>('none');
+
+ // Anomaly detection state
+ const [anomalyMethod, setAnomalyMethod] = useState<AnomalyMethod>('zscore');
+ const [anomalyThreshold, setAnomalyThreshold] = useState(3.0);
+ const [anomalyResult, setAnomalyResult] = useState<PortfolioAnomalyResult | null>(null);
+
+ // Seasonality state
+ const [seasonalityResult, setSeasonalityResult] = useState<PortfolioSeasonalityResult | null>(null);
+
+ // UI state
+ const [expandedSections, setExpandedSections] = useState<ExpandedSections>({
+ config: true,
+ forecast: true,
+ metrics: true,
+ summary: true,
+ chart: true,
+ dataSource: true,
+ anomaly: true,
+ seasonality: true,
+ backtest: true
+ });
+
+ // Check functime availability on mount
+ useEffect(() => {
+ checkFunctimeStatus();
+ loadPortfolios();
+ }, []);
+
+ const loadPortfolios = async () => {
+ try {
+ const portfolioList = await portfolioFunctimeService.getAvailablePortfolios();
+ setPortfolios(portfolioList);
+ if (portfolioList.length > 0 && !selectedPortfolioId) {
+ setSelectedPortfolioId(portfolioList[0].id);
+ }
+ } catch (err) {
+ console.error('Failed to load portfolios:', err);
+ }
+ };
+
+ const checkFunctimeStatus = async () => {
+ try {
+ const status = await functimeService.checkStatus();
+ setIsFunctimeAvailable(status.available);
+ if (!status.available) {
+ setError('Functime library not installed. Run: pip install functime polars');
+ }
+ } catch (err) {
+ setIsFunctimeAvailable(false);
+ setError('Failed to check functime status');
+ }
+ };
+
+ // Load data based on source type
+ const loadDataFromSource = useCallback(async () => {
+ if (dataSourceType === 'manual') {
+ return;
+ }
+
+ setPriceDataLoading(true);
+ setError(null);
+
+ try {
+ if (dataSourceType === 'portfolio' && selectedPortfolioId) {
+ const summary = await portfolioFunctimeService.getPortfolioSummary(selectedPortfolioId);
+ if (!summary || summary.holdings.length === 0) {
+ setError('Portfolio has no holdings');
+ return;
+ }
+
+ const data = await portfolioFunctimeService.fetchHistoricalPrices(
+ summary.holdings,
+ historicalDays
+ );
+
+ if (data) {
+ setPriceData(data);
+ setDataInput(JSON.stringify(data.panelData, null, 2));
+ } else {
+ setError('Failed to fetch historical data for portfolio');
+ }
+ } else if (dataSourceType === 'symbol' && symbolInput) {
+ const data = await portfolioFunctimeService.fetchSymbolData(symbolInput, historicalDays);
+ if (data) {
+ setDataInput(JSON.stringify(data, null, 2));
+ setPriceData({
+ panelData: data,
+ assets: [symbolInput],
+ nDataPoints: data.length,
+ startDate: data[0]?.time || '',
+ endDate: data[data.length - 1]?.time || ''
+ });
+ } else {
+ setError(`Failed to fetch data for ${symbolInput}`);
+ }
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to load data');
+ } finally {
+ setPriceDataLoading(false);
+ }
+ }, [dataSourceType, selectedPortfolioId, symbolInput, historicalDays]);
+
+ // Run analysis based on mode
+ const runAnalysis = async () => {
+ setIsLoading(true);
+ setError(null);
+
+ try {
+ const data = JSON.parse(dataInput);
+
+ if (analysisMode === 'forecast') {
+ await runForecast();
+ } else if (analysisMode === 'anomaly') {
+ await runAnomalyDetection(data);
+ } else if (analysisMode === 'seasonality') {
+ await runSeasonalityAnalysis(data);
+ } else if (analysisMode === 'backtest') {
+ await runForecast();
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Analysis failed');
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ // Anomaly detection
+ const runAnomalyDetection = async (data: any[]) => {
+ const config: AnomalyDetectionConfig = {
+ method: anomalyMethod,
+ threshold: anomalyThreshold
+ };
+
+ const result = await functimeService.detectAnomalies(data, config);
+
+ if (!result.success) {
+ setError(result.error || 'Anomaly detection failed');
+ return;
+ }
+
+ // Format result for portfolio view
+ const anomalies: Record<string, any> = {};
+ if (result.results) {
+ Object.entries(result.results).forEach(([symbol, data]) => {
+ const anomalyList = data.anomalies?.filter((a: any) => a.is_anomaly) || [];
+ anomalies[symbol] = {
+ count: data.n_anomalies,
+ rate: data.anomaly_rate,
+ dates: anomalyList.map((a: any) => a.time),
+ values: anomalyList.map((a: any) => a.value)
+ };
+ });
+ }
+
+ setAnomalyResult({
+ success: true,
+ portfolio: portfolios.find(p => p.id === selectedPortfolioId) || {} as Portfolio,
+ anomalies
+ });
+ };
+
+ // Seasonality analysis
+ const runSeasonalityAnalysis = async (data: any[]) => {
+ const config: SeasonalityConfig = {
+ operation: 'metrics'
+ };
+
+ const result = await functimeService.analyzeSeasonality(data, config);
+
+ if (!result.success) {
+ setError(result.error || 'Seasonality analysis failed');
+ return;
+ }
+
+ // Format result
+ const seasonality: Record<string, any> = {};
+ if (result.metrics) {
+ Object.entries(result.metrics).forEach(([symbol, metrics]) => {
+ seasonality[symbol] = {
+ period: metrics.detected_period || 0,
+ strength: metrics.seasonal_strength,
+ is_seasonal: metrics.is_seasonal,
+ trend_strength: metrics.trend_strength
+ };
+ });
+ }
+
+ setSeasonalityResult({
+ success: true,
+ portfolio: portfolios.find(p => p.id === selectedPortfolioId) || {} as Portfolio,
+ seasonality
+ });
+ };
+
+ const runForecast = async () => {
+ setIsLoading(true);
+ setError(null);
+
+ try {
+ const data = JSON.parse(dataInput);
+
+ // Run full pipeline
+ const result = await functimeService.fullPipeline(
+ data,
+ selectedModel,
+ horizon,
+ frequency,
+ testSize,
+ preprocess === 'none' ? undefined : preprocess
+ );
+
+ if (!result.success) {
+ setError(result.error || 'Forecast failed');
+ return;
+ }
+
+ setAnalysisResult({
+ forecast: result.forecast,
+ model: result.model,
+ horizon: result.horizon,
+ frequency: result.frequency,
+ best_params: result.best_params,
+ evaluation_metrics: result.evaluation_metrics,
+ data_summary: result.data_summary
+ });
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Forecast failed');
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const toggleSection = (section: keyof ExpandedSections) => {
+ setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
+ };
+
+ // Parse historical data from input for chart visualization
+ const historicalData = useMemo(() => {
+ return parseHistoricalData(dataInput);
+ }, [dataInput]);
+
+ return {
+ // Status
+ isFunctimeAvailable,
+ isLoading,
+ error,
+
+ // Data
+ dataInput,
+ setDataInput,
+ analysisResult,
+ historicalData,
+
+ // Data source
+ dataSourceType,
+ setDataSourceType,
+ portfolios,
+ selectedPortfolioId,
+ setSelectedPortfolioId,
+ symbolInput,
+ setSymbolInput,
+ historicalDays,
+ setHistoricalDays,
+ priceDataLoading,
+ priceData,
+ loadDataFromSource,
+
+ // Analysis mode
+ analysisMode,
+ setAnalysisMode,
+
+ // Forecast config
+ selectedModel,
+ setSelectedModel,
+ horizon,
+ setHorizon,
+ frequency,
+ setFrequency,
+ alpha,
+ setAlpha,
+ testSize,
+ setTestSize,
+ preprocess,
+ setPreprocess,
+
+ // Anomaly
+ anomalyMethod,
+ setAnomalyMethod,
+ anomalyThreshold,
+ setAnomalyThreshold,
+ anomalyResult,
+
+ // Seasonality
+ seasonalityResult,
+
+ // UI state
+ expandedSections,
+ toggleSection,
+
+ // Actions
+ checkFunctimeStatus,
+ runAnalysis
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/index.ts
new file mode 100644
index 000000000..eda7011d7
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/index.ts
@@ -0,0 +1,26 @@
+/**
+ * Functime Panel - Main Barrel Export
+ *
+ * Export all components, hooks, types, and utilities
+ */
+
+// Main component
+export { FunctimePanel, default } from './FunctimePanel';
+
+// Components
+export * from './components';
+
+// Results
+export * from './results';
+
+// Hooks
+export * from './hooks';
+
+// Types
+export * from './types';
+
+// Constants
+export * from './constants';
+
+// Utils
+export * from './utils';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/results/AnomalyResults.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/results/AnomalyResults.tsx
new file mode 100644
index 000000000..0180c753a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/results/AnomalyResults.tsx
@@ -0,0 +1,72 @@
+/**
+ * AnomalyResults Component
+ * Displays anomaly detection results
+ */
+
+import React from 'react';
+import { AlertTriangle } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { PortfolioAnomalyResult } from '../types';
+
+interface AnomalyResultsProps {
+ anomalyResult: PortfolioAnomalyResult;
+}
+
+export const AnomalyResults: React.FC<AnomalyResultsProps> = ({ anomalyResult }) => {
+ if (!anomalyResult.success || !anomalyResult.anomalies) {
+ return null;
+ }
+
+ return (
+ <div className="space-y-4">
+ <div
+ className="rounded overflow-hidden"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <div
+ className="px-4 py-3 flex items-center gap-2"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <AlertTriangle size={16} color={FINCEPT.YELLOW} />
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ Anomaly Detection Results
+ </span>
+ </div>
+ <div className="p-4">
+ <div className="grid grid-cols-2 gap-4">
+ {Object.entries(anomalyResult.anomalies).map(([symbol, data]) => (
+ <div
+ key={symbol}
+ className="p-3 rounded"
+ style={{ backgroundColor: FINCEPT.DARK_BG }}
+ >
+ <div className="flex justify-between items-center mb-2">
+ <span className="text-sm font-bold" style={{ color: FINCEPT.CYAN }}>
+ {symbol}
+ </span>
+ <span
+ className="text-xs px-2 py-0.5 rounded"
+ style={{
+ backgroundColor: data.count > 0 ? FINCEPT.RED : FINCEPT.GREEN,
+ color: FINCEPT.WHITE
+ }}
+ >
+ {data.count} anomalies
+ </span>
+ </div>
+ <div className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ <div>Rate: {(data.rate * 100).toFixed(2)}%</div>
+ {data.dates?.length > 0 && (
+ <div className="mt-1">
+ Latest: {data.dates[data.dates.length - 1]}
+ </div>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/results/ForecastResults.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/results/ForecastResults.tsx
new file mode 100644
index 000000000..d6f91e800
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/results/ForecastResults.tsx
@@ -0,0 +1,309 @@
+/**
+ * ForecastResults Component
+ * Displays forecast analysis results including summary, metrics, chart, and table
+ */
+
+import React, { useState } from 'react';
+import {
+ Database,
+ Layers,
+ GitBranch,
+ Target,
+ BarChart2,
+ Activity,
+ TrendingUp,
+ LineChart,
+ ChevronUp,
+ ChevronDown,
+ CheckCircle2,
+ Zap
+} from 'lucide-react';
+import { FINCEPT, INITIAL_ROWS, EXPANDED_ROWS } from '../constants';
+import { formatMetric } from '../utils';
+import { MetricCard, ForecastChart } from '../components';
+import type { ForecastAnalysisResult, ExpandedSections } from '../types';
+
+interface ForecastResultsProps {
+ analysisResult: ForecastAnalysisResult;
+ expandedSections: ExpandedSections;
+ toggleSection: (section: keyof ExpandedSections) => void;
+ historicalData: { time: string; value: number }[];
+}
+
+export const ForecastResults: React.FC<ForecastResultsProps> = ({
+ analysisResult,
+ expandedSections,
+ toggleSection,
+ historicalData
+}) => {
+ const [forecastTableExpanded, setForecastTableExpanded] = useState(false);
+
+ return (
+ <div className="space-y-4">
+ {/* Data Summary Section */}
+ {analysisResult.data_summary && (
+ <div
+ className="rounded overflow-hidden"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <button
+ onClick={() => toggleSection('summary')}
+ className="w-full px-4 py-3 flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <Database size={16} color={FINCEPT.CYAN} />
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ Data Summary
+ </span>
+ </div>
+ {expandedSections.summary ? (
+ <ChevronUp size={16} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={16} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expandedSections.summary && (
+ <div className="p-4 grid grid-cols-4 gap-4">
+ <MetricCard
+ label="Total Rows"
+ value={String(analysisResult.data_summary.total_rows)}
+ color={FINCEPT.WHITE}
+ icon={<Database size={14} />}
+ />
+ <MetricCard
+ label="Entities"
+ value={String(analysisResult.data_summary.entities)}
+ color={FINCEPT.CYAN}
+ icon={<Layers size={14} />}
+ />
+ <MetricCard
+ label="Train Size"
+ value={String(analysisResult.data_summary.train_size)}
+ color={FINCEPT.GREEN}
+ icon={<GitBranch size={14} />}
+ />
+ <MetricCard
+ label="Test Size"
+ value={String(analysisResult.data_summary.test_size)}
+ color={FINCEPT.YELLOW}
+ icon={<Target size={14} />}
+ />
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Evaluation Metrics Section */}
+ {analysisResult.evaluation_metrics && (
+ <div
+ className="rounded overflow-hidden"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <button
+ onClick={() => toggleSection('metrics')}
+ className="w-full px-4 py-3 flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <Target size={16} color={FINCEPT.GREEN} />
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ Evaluation Metrics
+ </span>
+ </div>
+ {expandedSections.metrics ? (
+ <ChevronUp size={16} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={16} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expandedSections.metrics && (
+ <div className="p-4 grid grid-cols-3 gap-4">
+ <MetricCard
+ label="MAE"
+ value={formatMetric(analysisResult.evaluation_metrics.mae)}
+ color={FINCEPT.CYAN}
+ icon={<BarChart2 size={14} />}
+ />
+ <MetricCard
+ label="RMSE"
+ value={formatMetric(analysisResult.evaluation_metrics.rmse)}
+ color={FINCEPT.YELLOW}
+ icon={<Activity size={14} />}
+ />
+ <MetricCard
+ label="SMAPE"
+ value={formatMetric(analysisResult.evaluation_metrics.smape)}
+ color={FINCEPT.PURPLE}
+ icon={<TrendingUp size={14} />}
+ />
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Forecast Chart Visualization */}
+ {analysisResult.forecast && analysisResult.forecast.length > 0 && (
+ <div
+ className="rounded overflow-hidden"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <button
+ onClick={() => toggleSection('chart')}
+ className="w-full px-4 py-3 flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <LineChart size={16} color={FINCEPT.CYAN} />
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ Forecast Chart
+ </span>
+ </div>
+ {expandedSections.chart ? (
+ <ChevronUp size={16} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={16} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expandedSections.chart && (
+ <div className="p-4">
+ <ForecastChart
+ historicalData={historicalData}
+ forecastData={analysisResult.forecast}
+ height={350}
+ />
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Forecast Results Section */}
+ <div
+ className="rounded overflow-hidden"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <button
+ onClick={() => toggleSection('forecast')}
+ className="w-full px-4 py-3 flex items-center justify-between"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <TrendingUp size={16} color={FINCEPT.ORANGE} />
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ Forecast Results
+ </span>
+ {analysisResult.model && (
+ <span
+ className="ml-2 px-2 py-0.5 rounded text-xs font-mono"
+ style={{ backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG }}
+ >
+ {analysisResult.model.toUpperCase()}
+ </span>
+ )}
+ </div>
+ {expandedSections.forecast ? (
+ <ChevronUp size={16} color={FINCEPT.GRAY} />
+ ) : (
+ <ChevronDown size={16} color={FINCEPT.GRAY} />
+ )}
+ </button>
+
+ {expandedSections.forecast && analysisResult.forecast && (
+ <div className="p-4">
+ {/* Forecast info */}
+ <div className="mb-4 flex gap-4 text-xs font-mono" style={{ color: FINCEPT.GRAY }}>
+ <span>Horizon: <span style={{ color: FINCEPT.WHITE }}>{analysisResult.horizon}</span></span>
+ <span>Frequency: <span style={{ color: FINCEPT.WHITE }}>{analysisResult.frequency}</span></span>
+ {analysisResult.best_params && (
+ <span>Auto-tuned: <CheckCircle2 size={12} color={FINCEPT.GREEN} className="inline ml-1" /></span>
+ )}
+ </div>
+
+ {/* Forecast table */}
+ <div
+ className="rounded overflow-hidden"
+ style={{ border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <table className="w-full text-xs font-mono">
+ <thead>
+ <tr style={{ backgroundColor: FINCEPT.HEADER_BG }}>
+ <th className="px-3 py-2 text-left" style={{ color: FINCEPT.GRAY }}>ENTITY</th>
+ <th className="px-3 py-2 text-left" style={{ color: FINCEPT.GRAY }}>TIME</th>
+ <th className="px-3 py-2 text-right" style={{ color: FINCEPT.GRAY }}>FORECAST</th>
+ </tr>
+ </thead>
+ <tbody>
+ {analysisResult.forecast.slice(0, forecastTableExpanded ? EXPANDED_ROWS : INITIAL_ROWS).map((row, idx) => (
+ <tr
+ key={idx}
+ style={{
+ backgroundColor: idx % 2 === 0 ? FINCEPT.DARK_BG : FINCEPT.PANEL_BG
+ }}
+ >
+ <td className="px-3 py-2" style={{ color: FINCEPT.CYAN }}>
+ {row.entity_id}
+ </td>
+ <td className="px-3 py-2" style={{ color: FINCEPT.WHITE }}>
+ {row.time}
+ </td>
+ <td className="px-3 py-2 text-right" style={{ color: FINCEPT.GREEN }}>
+ {typeof row.value === 'number' ? row.value.toFixed(2) : row.value}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {analysisResult.forecast.length > INITIAL_ROWS && (
+ <button
+ onClick={() => setForecastTableExpanded(!forecastTableExpanded)}
+ className="w-full px-3 py-2 text-xs font-mono text-center flex items-center justify-center gap-2 hover:opacity-80 transition-opacity"
+ style={{ backgroundColor: FINCEPT.HEADER_BG, color: FINCEPT.ORANGE }}
+ >
+ {forecastTableExpanded ? (
+ <>
+ <ChevronUp size={12} />
+ Show Less ({INITIAL_ROWS} rows)
+ </>
+ ) : (
+ <>
+ <ChevronDown size={12} />
+ Show More ({Math.min(analysisResult.forecast.length, EXPANDED_ROWS)} of {analysisResult.forecast.length} rows)
+ </>
+ )}
+ </button>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Best Params (if auto-tuned) */}
+ {analysisResult.best_params && Object.keys(analysisResult.best_params).length > 0 && (
+ <div
+ className="rounded p-4"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <div className="flex items-center gap-2 mb-3">
+ <Zap size={16} color={FINCEPT.YELLOW} />
+ <span className="text-xs font-bold uppercase" style={{ color: FINCEPT.WHITE }}>
+ Best Parameters (Auto-tuned)
+ </span>
+ </div>
+ <div className="grid grid-cols-3 gap-2">
+ {Object.entries(analysisResult.best_params).map(([key, value]) => (
+ <div key={key} className="flex justify-between p-2 rounded" style={{ backgroundColor: FINCEPT.DARK_BG }}>
+ <span className="text-xs font-mono" style={{ color: FINCEPT.GRAY }}>{key}</span>
+ <span className="text-xs font-mono" style={{ color: FINCEPT.CYAN }}>
+ {typeof value === 'number' ? value.toFixed(4) : String(value)}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/results/SeasonalityResults.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/results/SeasonalityResults.tsx
new file mode 100644
index 000000000..a0dad1069
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/results/SeasonalityResults.tsx
@@ -0,0 +1,80 @@
+/**
+ * SeasonalityResults Component
+ * Displays seasonality analysis results
+ */
+
+import React from 'react';
+import { Waves } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { PortfolioSeasonalityResult } from '../types';
+
+interface SeasonalityResultsProps {
+ seasonalityResult: PortfolioSeasonalityResult;
+}
+
+export const SeasonalityResults: React.FC<SeasonalityResultsProps> = ({ seasonalityResult }) => {
+ if (!seasonalityResult.success || !seasonalityResult.seasonality) {
+ return null;
+ }
+
+ return (
+ <div className="space-y-4">
+ <div
+ className="rounded overflow-hidden"
+ style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}
+ >
+ <div
+ className="px-4 py-3 flex items-center gap-2"
+ style={{ backgroundColor: FINCEPT.HEADER_BG }}
+ >
+ <Waves size={16} color={FINCEPT.CYAN} />
+ <span className="text-xs font-bold uppercase tracking-wide" style={{ color: FINCEPT.WHITE }}>
+ Seasonality Analysis Results
+ </span>
+ </div>
+ <div className="p-4">
+ <div className="grid grid-cols-2 gap-4">
+ {Object.entries(seasonalityResult.seasonality).map(([symbol, data]) => (
+ <div
+ key={symbol}
+ className="p-3 rounded"
+ style={{ backgroundColor: FINCEPT.DARK_BG }}
+ >
+ <div className="flex justify-between items-center mb-2">
+ <span className="text-sm font-bold" style={{ color: FINCEPT.CYAN }}>
+ {symbol}
+ </span>
+ <span
+ className="text-xs px-2 py-0.5 rounded"
+ style={{
+ backgroundColor: data.is_seasonal ? FINCEPT.GREEN : FINCEPT.MUTED,
+ color: FINCEPT.WHITE
+ }}
+ >
+ {data.is_seasonal ? 'Seasonal' : 'Non-Seasonal'}
+ </span>
+ </div>
+ <div className="text-xs font-mono space-y-1" style={{ color: FINCEPT.GRAY }}>
+ <div className="flex justify-between">
+ <span>Period:</span>
+ <span style={{ color: FINCEPT.WHITE }}>{data.period} days</span>
+ </div>
+ <div className="flex justify-between">
+ <span>Seasonal Strength:</span>
+ <span style={{ color: FINCEPT.ORANGE }}>{(data.strength * 100).toFixed(1)}%</span>
+ </div>
+ {data.trend_strength !== undefined && (
+ <div className="flex justify-between">
+ <span>Trend Strength:</span>
+ <span style={{ color: FINCEPT.GREEN }}>{(data.trend_strength * 100).toFixed(1)}%</span>
+ </div>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/results/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/results/index.ts
new file mode 100644
index 000000000..b6838114a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/results/index.ts
@@ -0,0 +1,7 @@
+/**
+ * Functime Results Barrel Export
+ */
+
+export { AnomalyResults } from './AnomalyResults';
+export { SeasonalityResults } from './SeasonalityResults';
+export { ForecastResults } from './ForecastResults';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/types.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/types.ts
new file mode 100644
index 000000000..dd3ba1f17
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/types.ts
@@ -0,0 +1,174 @@
+/**
+ * Functime Panel TypeScript Interfaces
+ */
+
+import type {
+ ForecastResult,
+ ForecastConfig,
+ PreprocessConfig,
+ FullPipelineResponse,
+ AnomalyDetectionConfig,
+ SeasonalityConfig,
+ ConfidenceIntervalsConfig,
+ BacktestConfig
+} from '@/services/aiQuantLab/functimeService';
+import type {
+ PortfolioPriceData,
+ PortfolioForecastResult,
+ PortfolioAnomalyResult,
+ PortfolioSeasonalityResult
+} from '@/services/aiQuantLab/portfolioFunctimeService';
+import type { Portfolio } from '@/services/portfolio/portfolioService';
+
+// Data source types
+export type DataSourceType = 'manual' | 'portfolio' | 'symbol';
+
+// Analysis mode types
+export type AnalysisMode = 'forecast' | 'anomaly' | 'seasonality' | 'backtest';
+
+// Preprocess type
+export type PreprocessType = 'none' | 'scale' | 'difference';
+
+// Anomaly method type
+export type AnomalyMethod = 'zscore' | 'iqr' | 'isolation_forest';
+
+// Forecast analysis result interface
+export interface ForecastAnalysisResult {
+ forecast?: ForecastResult[];
+ model?: string;
+ horizon?: number;
+ frequency?: string;
+ best_params?: Record<string, unknown>;
+ evaluation_metrics?: {
+ mae?: number;
+ rmse?: number;
+ smape?: number;
+ };
+ data_summary?: {
+ total_rows: number;
+ entities: number;
+ train_size: number;
+ test_size: number;
+ };
+}
+
+// Expandable sections state
+export interface ExpandedSections {
+ config: boolean;
+ forecast: boolean;
+ metrics: boolean;
+ summary: boolean;
+ chart: boolean;
+ dataSource: boolean;
+ anomaly: boolean;
+ seasonality: boolean;
+ backtest: boolean;
+}
+
+// Chart data point interface
+export interface ChartDataPoint {
+ time: string;
+ value: number;
+ type: 'historical' | 'forecast';
+ entity_id?: string;
+}
+
+// Tooltip state interface
+export interface TooltipState {
+ visible: boolean;
+ x: number;
+ y: number;
+ data: ChartDataPoint | null;
+}
+
+// Component props interfaces
+export interface DataSourceSectionProps {
+ dataSourceType: DataSourceType;
+ setDataSourceType: (type: DataSourceType) => void;
+ portfolios: Portfolio[];
+ selectedPortfolioId: string;
+ setSelectedPortfolioId: (id: string) => void;
+ symbolInput: string;
+ setSymbolInput: (symbol: string) => void;
+ historicalDays: number;
+ setHistoricalDays: (days: number) => void;
+ priceDataLoading: boolean;
+ priceData: PortfolioPriceData | null;
+ loadDataFromSource: () => Promise<void>;
+ expanded: boolean;
+ toggleSection: () => void;
+}
+
+export interface ForecastConfigProps {
+ selectedModel: string;
+ setSelectedModel: (model: string) => void;
+ horizon: number;
+ setHorizon: (horizon: number) => void;
+ frequency: string;
+ setFrequency: (freq: string) => void;
+ alpha: number;
+ setAlpha: (alpha: number) => void;
+ testSize: number;
+ setTestSize: (size: number) => void;
+ preprocess: PreprocessType;
+ setPreprocess: (preprocess: PreprocessType) => void;
+ expanded: boolean;
+ toggleSection: () => void;
+}
+
+export interface AnomalyConfigProps {
+ anomalyMethod: AnomalyMethod;
+ setAnomalyMethod: (method: AnomalyMethod) => void;
+ anomalyThreshold: number;
+ setAnomalyThreshold: (threshold: number) => void;
+}
+
+export interface SeasonalityConfigProps {
+ // Currently just informational panel, no configuration
+}
+
+export interface MetricCardProps {
+ label: string;
+ value: string;
+ color: string;
+ icon: React.ReactNode;
+ large?: boolean;
+}
+
+export interface ForecastChartProps {
+ historicalData: { time: string; value: number }[];
+ forecastData: ForecastResult[];
+ height?: number;
+}
+
+export interface AnomalyResultsProps {
+ anomalyResult: PortfolioAnomalyResult;
+}
+
+export interface SeasonalityResultsProps {
+ seasonalityResult: PortfolioSeasonalityResult;
+}
+
+export interface ForecastResultsProps {
+ analysisResult: ForecastAnalysisResult;
+ expandedSections: ExpandedSections;
+ toggleSection: (section: keyof ExpandedSections) => void;
+ historicalData: { time: string; value: number }[];
+}
+
+// Re-export service types for convenience
+export type {
+ ForecastResult,
+ ForecastConfig,
+ PreprocessConfig,
+ FullPipelineResponse,
+ AnomalyDetectionConfig,
+ SeasonalityConfig,
+ ConfidenceIntervalsConfig,
+ BacktestConfig,
+ PortfolioPriceData,
+ PortfolioForecastResult,
+ PortfolioAnomalyResult,
+ PortfolioSeasonalityResult,
+ Portfolio
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/utils/formatters.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/utils/formatters.ts
new file mode 100644
index 000000000..a9af3850e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/utils/formatters.ts
@@ -0,0 +1,44 @@
+/**
+ * Functime Panel Formatting Utilities
+ */
+
+/**
+ * Format a metric value with specified decimal places
+ */
+export function formatMetric(value: number | null | undefined, decimals = 4): string {
+ if (value === null || value === undefined || isNaN(value)) return 'N/A';
+ return value.toFixed(decimals);
+}
+
+/**
+ * Format a percentage value
+ */
+export function formatPercent(value: number | null | undefined, decimals = 2): string {
+ if (value === null || value === undefined || isNaN(value)) return 'N/A';
+ return `${(value * 100).toFixed(decimals)}%`;
+}
+
+/**
+ * Format a date string to display format
+ */
+export function formatDate(dateString: string): string {
+ return dateString.split('T')[0];
+}
+
+/**
+ * Parse historical data from JSON input
+ */
+export function parseHistoricalData(dataInput: string): { time: string; value: number }[] {
+ try {
+ const data = JSON.parse(dataInput);
+ if (Array.isArray(data)) {
+ return data.map(d => ({
+ time: d.time,
+ value: d.value
+ }));
+ }
+ return [];
+ } catch {
+ return [];
+ }
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/utils/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/utils/index.ts
new file mode 100644
index 000000000..46a2c668a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/functime/utils/index.ts
@@ -0,0 +1,5 @@
+/**
+ * Functime Utils Barrel Export
+ */
+
+export * from './formatters';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/hooks/index.ts
new file mode 100644
index 000000000..d2d4265dc
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/hooks/index.ts
@@ -0,0 +1,8 @@
+/**
+ * AI Quant Lab - Hooks Index
+ *
+ * Export all custom hooks
+ */
+
+export { useWorkflowManagement } from './useWorkflowManagement';
+export type { UseWorkflowManagementReturn } from './useWorkflowManagement';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/hooks/useWorkflowManagement.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/hooks/useWorkflowManagement.ts
new file mode 100644
index 000000000..917c8901e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/hooks/useWorkflowManagement.ts
@@ -0,0 +1,364 @@
+/**
+ * useWorkflowManagement Hook
+ *
+ * Custom hook for managing workflow state, persistence, and operations
+ */
+
+import { useState, useCallback, useEffect } from 'react';
+import { Node, Edge, useNodesState, useEdgesState } from 'reactflow';
+import { saveSetting, getSetting } from '@/services/core/sqliteService';
+import { workflowService, Workflow as WorkflowType } from '@/services/core/workflowService';
+import { workflowExecutor } from '../nodes/WorkflowExecutor';
+
+export interface UseWorkflowManagementReturn {
+ // Node and edge state
+ nodes: Node[];
+ edges: Edge[];
+ setNodes: React.Dispatch<React.SetStateAction<Node[]>>;
+ setEdges: React.Dispatch<React.SetStateAction<Edge[]>>;
+ onNodesChange: any;
+ onEdgesChange: any;
+
+ // Selection state
+ selectedNodes: string[];
+ setSelectedNodes: React.Dispatch<React.SetStateAction<string[]>>;
+
+ // Execution state
+ isExecuting: boolean;
+ setIsExecuting: React.Dispatch<React.SetStateAction<boolean>>;
+
+ // Workflow metadata
+ workflowMode: 'new' | 'draft' | 'deployed';
+ setWorkflowMode: React.Dispatch<React.SetStateAction<'new' | 'draft' | 'deployed'>>;
+ currentWorkflowId: string | null;
+ setCurrentWorkflowId: React.Dispatch<React.SetStateAction<string | null>>;
+ editingDraftId: string | null;
+ setEditingDraftId: React.Dispatch<React.SetStateAction<string | null>>;
+ workflowName: string;
+ setWorkflowName: React.Dispatch<React.SetStateAction<string>>;
+ workflowDescription: string;
+ setWorkflowDescription: React.Dispatch<React.SetStateAction<string>>;
+
+ // Operations
+ saveWorkflow: () => Promise<void>;
+ exportWorkflow: () => void;
+ importWorkflow: () => void;
+ clearWorkflow: () => Promise<void>;
+ deployWorkflow: (statusCallback: (nodeId: string, status: string, result?: any) => void) => Promise<void>;
+ saveDraft: () => Promise<void>;
+ handleLoadWorkflow: (loadedNodes: Node[], loadedEdges: Edge[], workflowId: string, workflow: WorkflowType) => void;
+ handleViewResults: (workflow: WorkflowType) => { showModal: boolean; data: any; name: string } | { navigate: boolean };
+ handleEditDraft: (workflow: WorkflowType) => void;
+ deleteSelectedNodes: () => void;
+ deleteSelectedEdges: () => void;
+ onSelectionChange: (params: any) => void;
+}
+
+export function useWorkflowManagement(): UseWorkflowManagementReturn {
+ // Node and edge state
+ const [nodes, setNodes, onNodesChange] = useNodesState([]);
+ const [edges, setEdges, onEdgesChange] = useEdgesState([]);
+
+ // Selection state
+ const [selectedNodes, setSelectedNodes] = useState<string[]>([]);
+
+ // Execution state
+ const [isExecuting, setIsExecuting] = useState(false);
+
+ // Workflow metadata
+ const [workflowMode, setWorkflowMode] = useState<'new' | 'draft' | 'deployed'>('new');
+ const [currentWorkflowId, setCurrentWorkflowId] = useState<string | null>(null);
+ const [editingDraftId, setEditingDraftId] = useState<string | null>(null);
+ const [workflowName, setWorkflowName] = useState('');
+ const [workflowDescription, setWorkflowDescription] = useState('');
+
+ // Load saved workflow from storage
+ const loadSavedWorkflow = useCallback(async () => {
+ try {
+ const saved = await getSetting('nodeEditorWorkflow');
+ if (saved) {
+ const workflow = JSON.parse(saved);
+ return workflow;
+ }
+ } catch (error) {
+ console.error('[useWorkflowManagement] Failed to load saved workflow:', error);
+ }
+ return { nodes: [], edges: [] };
+ }, []);
+
+ // Load workflow on mount
+ useEffect(() => {
+ const initWorkflow = async () => {
+ const workflow = await loadSavedWorkflow();
+ setNodes(workflow.nodes);
+ setEdges(workflow.edges);
+ };
+ initWorkflow();
+ }, [loadSavedWorkflow, setNodes, setEdges]);
+
+ // Auto-save workflow to storage whenever nodes or edges change
+ useEffect(() => {
+ const saveWorkflowAuto = async () => {
+ try {
+ const workflow = { nodes, edges };
+ await saveSetting('nodeEditorWorkflow', JSON.stringify(workflow), 'node_editor');
+ } catch (error) {
+ console.error('[useWorkflowManagement] Failed to auto-save workflow:', error);
+ }
+ };
+
+ // Debounce saves
+ const timeoutId = setTimeout(saveWorkflowAuto, 500);
+ return () => clearTimeout(timeoutId);
+ }, [nodes, edges]);
+
+ // Save workflow manually
+ const saveWorkflow = useCallback(async () => {
+ try {
+ const workflow = { nodes, edges };
+ await saveSetting('nodeEditorWorkflow', JSON.stringify(workflow), 'node_editor');
+ } catch (error) {
+ console.error('[useWorkflowManagement] Failed to save workflow:', error);
+ }
+ }, [nodes, edges]);
+
+ // Export workflow to JSON file
+ const exportWorkflow = useCallback(() => {
+ const workflow = {
+ nodes: nodes,
+ edges: edges,
+ };
+ const dataStr = JSON.stringify(workflow, null, 2);
+ const dataUri = `data:application/json;charset=utf-8,${encodeURIComponent(dataStr)}`;
+ const exportFileDefaultName = `workflow_${Date.now()}.json`;
+
+ const linkElement = document.createElement('a');
+ linkElement.setAttribute('href', dataUri);
+ linkElement.setAttribute('download', exportFileDefaultName);
+ linkElement.click();
+ }, [nodes, edges]);
+
+ // Import workflow from JSON file
+ const importWorkflow = useCallback(() => {
+ const input = document.createElement('input');
+ input.type = 'file';
+ input.accept = '.json';
+ input.onchange = (e: any) => {
+ const file = e.target.files[0];
+ if (file) {
+ const reader = new FileReader();
+ reader.onload = (event: any) => {
+ try {
+ const workflow = JSON.parse(event.target.result);
+ setNodes(workflow.nodes || []);
+ setEdges(workflow.edges || []);
+ } catch (error) {
+ console.error('[useWorkflowManagement] Failed to import workflow:', error);
+ }
+ };
+ reader.readAsText(file);
+ }
+ };
+ input.click();
+ }, [setNodes, setEdges]);
+
+ // Clear workflow
+ const clearWorkflow = useCallback(async () => {
+ setNodes([]);
+ setEdges([]);
+ await saveSetting('nodeEditorWorkflow', '', 'node_editor');
+ setWorkflowMode('new');
+ setCurrentWorkflowId(null);
+ setEditingDraftId(null);
+ setWorkflowName('');
+ setWorkflowDescription('');
+ }, [setNodes, setEdges]);
+
+ // Deploy workflow
+ const deployWorkflow = useCallback(
+ async (statusCallback: (nodeId: string, status: string, result?: any) => void) => {
+ if (!workflowName.trim()) {
+ alert('Please enter a workflow name');
+ return;
+ }
+
+ if (isExecuting) {
+ alert('A workflow is already executing. Please wait for it to complete.');
+ return;
+ }
+
+ const name = workflowName;
+ const description = workflowDescription;
+ const currentNodes = nodes;
+ const currentEdges = edges;
+
+ setIsExecuting(true);
+
+ try {
+ const result = await workflowExecutor.executeAndSave(
+ currentNodes,
+ currentEdges,
+ {
+ name: name,
+ description: description,
+ saveAsDraft: false,
+ },
+ statusCallback
+ );
+
+ if (result.success) {
+ setNodes([]);
+ setEdges([]);
+ await saveSetting('nodeEditorWorkflow', '', 'node_editor');
+ setCurrentWorkflowId(null);
+ setWorkflowMode('new');
+ setEditingDraftId(null);
+ } else {
+ console.error('[useWorkflowManagement] Deployment failed:', result.error);
+ alert(`Deployment failed: ${result.error}`);
+ }
+ } catch (error: any) {
+ console.error('[useWorkflowManagement] Deploy failed:', error);
+ alert(`Deployment failed: ${error.message}`);
+ } finally {
+ setIsExecuting(false);
+ }
+ },
+ [nodes, edges, workflowName, workflowDescription, isExecuting, setNodes, setEdges]
+ );
+
+ // Save as draft
+ const saveDraft = useCallback(async () => {
+ if (!workflowName.trim()) {
+ alert('Please enter a workflow name');
+ return;
+ }
+
+ try {
+ let workflowId: string;
+ if (editingDraftId) {
+ await workflowService.updateDraft(
+ editingDraftId,
+ workflowName,
+ workflowDescription,
+ nodes,
+ edges
+ );
+ workflowId = editingDraftId;
+ setEditingDraftId(null);
+ } else {
+ workflowId = await workflowExecutor.saveDraft(workflowName, workflowDescription, nodes, edges);
+ }
+ setCurrentWorkflowId(workflowId);
+ setWorkflowMode('draft');
+ } catch (error: any) {
+ console.error('[useWorkflowManagement] Save draft failed:', error);
+ alert(`Save failed: ${error.message}`);
+ }
+ }, [nodes, edges, workflowName, workflowDescription, editingDraftId]);
+
+ // Load workflow from manager
+ const handleLoadWorkflow = useCallback(
+ (loadedNodes: Node[], loadedEdges: Edge[], workflowId: string, workflow: WorkflowType) => {
+ setNodes(loadedNodes);
+ setEdges(loadedEdges);
+ setCurrentWorkflowId(workflowId);
+ setWorkflowMode(workflow.status === 'draft' ? 'draft' : 'deployed');
+ },
+ [setNodes, setEdges]
+ );
+
+ // View workflow results
+ const handleViewResults = useCallback(
+ (workflow: WorkflowType): { showModal: boolean; data: any; name: string } | { navigate: boolean } => {
+ const choice = window.confirm(
+ `View results for: ${workflow.name}\n\n` +
+ `Click OK to view in modal window\n` +
+ `Click Cancel to navigate to workflow editor with results`
+ );
+
+ if (choice) {
+ return { showModal: true, data: workflow.results, name: workflow.name };
+ } else {
+ setNodes(workflow.nodes);
+ setEdges(workflow.edges);
+ setCurrentWorkflowId(workflow.id);
+ setWorkflowMode('deployed');
+ return { navigate: true };
+ }
+ },
+ [setNodes, setEdges]
+ );
+
+ // Edit draft workflow
+ const handleEditDraft = useCallback(
+ (workflow: WorkflowType) => {
+ setNodes(workflow.nodes);
+ setEdges(workflow.edges);
+ setWorkflowName(workflow.name);
+ setWorkflowDescription(workflow.description || '');
+ setEditingDraftId(workflow.id);
+ setCurrentWorkflowId(workflow.id);
+ setWorkflowMode('draft');
+ },
+ [setNodes, setEdges]
+ );
+
+ // Delete selected nodes
+ const deleteSelectedNodes = useCallback(() => {
+ if (selectedNodes.length > 0) {
+ setNodes((nds) => nds.filter((node) => !selectedNodes.includes(node.id)));
+ setEdges((eds) =>
+ eds.filter(
+ (edge) => !selectedNodes.includes(edge.source) && !selectedNodes.includes(edge.target)
+ )
+ );
+ setSelectedNodes([]);
+ }
+ }, [selectedNodes, setNodes, setEdges]);
+
+ // Delete selected edges
+ const deleteSelectedEdges = useCallback(() => {
+ setEdges((eds) => eds.filter((edge) => !edge.selected));
+ }, [setEdges]);
+
+ // Handle selection change
+ const onSelectionChange = useCallback((params: any) => {
+ setSelectedNodes(params.nodes.map((node: Node) => node.id));
+ }, []);
+
+ return {
+ nodes,
+ edges,
+ setNodes,
+ setEdges,
+ onNodesChange,
+ onEdgesChange,
+ selectedNodes,
+ setSelectedNodes,
+ isExecuting,
+ setIsExecuting,
+ workflowMode,
+ setWorkflowMode,
+ currentWorkflowId,
+ setCurrentWorkflowId,
+ editingDraftId,
+ setEditingDraftId,
+ workflowName,
+ setWorkflowName,
+ workflowDescription,
+ setWorkflowDescription,
+ saveWorkflow,
+ exportWorkflow,
+ importWorkflow,
+ clearWorkflow,
+ deployWorkflow,
+ saveDraft,
+ handleLoadWorkflow,
+ handleViewResults,
+ handleEditDraft,
+ deleteSelectedNodes,
+ deleteSelectedEdges,
+ onSelectionChange,
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/index.ts
new file mode 100644
index 000000000..dd9df2b71
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/index.ts
@@ -0,0 +1,27 @@
+/**
+ * AI Quant Lab - Main Index
+ *
+ * Export all components, hooks, types, and utilities
+ */
+
+// Default export for lazy loading
+export { default } from './AIQuantLabTab';
+
+// Main component
+export { default as AIQuantLabTab } from './AIQuantLabTab';
+export { default as NodeEditorTab } from './NodeEditorTab';
+
+// Components
+export * from './components';
+
+// Hooks
+export * from './hooks';
+
+// Types
+export * from './types';
+
+// Constants
+export * from './constants';
+
+// Nodes
+export * from './nodes';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/AgentMediatorNode.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/AgentMediatorNode.tsx
new file mode 100644
index 000000000..3afe3a832
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/AgentMediatorNode.tsx
@@ -0,0 +1,506 @@
+// AgentMediatorNode.tsx - LLM-powered mediator between agents
+import React, { useState, useEffect } from 'react';
+import { Handle, Position } from 'reactflow';
+import { MessageSquare, Settings, CheckCircle, AlertCircle, Loader, Brain } from 'lucide-react';
+import { sqliteService, LLMConfig, LLMModelConfig } from '@/services/core/sqliteService';
+
+// Combined LLM option for display
+interface LLMOption {
+ id: string;
+ provider: string;
+ model: string;
+ displayName: string;
+ type: 'provider' | 'model' | 'fincept';
+ isActive?: boolean;
+}
+
+interface AgentMediatorNodeProps {
+ id: string;
+ data: {
+ label: string;
+ selectedProvider?: string; // Which LLM provider to use for mediation
+ customPrompt?: string; // Custom mediation prompt
+ status: 'idle' | 'running' | 'completed' | 'error';
+ result?: string; // Mediated context
+ error?: string;
+ inputData?: any; // Data from previous agent
+ onExecute?: (nodeId: string) => void;
+ onConfigChange?: (config: { selectedProvider?: string; customPrompt?: string }) => void;
+ };
+ selected: boolean;
+}
+
+const AgentMediatorNode: React.FC<AgentMediatorNodeProps> = ({ id, data, selected }) => {
+ const [showSettings, setShowSettings] = useState(false);
+ const [availableProviders, setAvailableProviders] = useState<LLMOption[]>([]);
+ const [localProvider, setLocalProvider] = useState(data.selectedProvider || 'active');
+ const [localPrompt, setLocalPrompt] = useState(data.customPrompt || '');
+
+ // Fincept colors
+ const ORANGE = '#FFA500';
+ const WHITE = '#FFFFFF';
+ const GRAY = '#787878';
+ const DARK_BG = '#0a0a0a';
+ const PANEL_BG = '#1a1a1a';
+ const BORDER = '#2d2d2d';
+ const GREEN = '#10b981';
+ const RED = '#ef4444';
+ const BLUE = '#3b82f6';
+
+ // Load available LLM providers (both LLMConfig and LLMModelConfig)
+ useEffect(() => {
+ const loadProviders = async () => {
+ try {
+ const options: LLMOption[] = [];
+
+ // Load provider-level configs (LLMConfig)
+ const providerConfigs = await sqliteService.getLLMConfigs();
+ for (const config of providerConfigs) {
+ // Fincept is special - always show it prominently
+ if (config.provider === 'fincept') {
+ options.unshift({
+ id: 'fincept',
+ provider: 'fincept',
+ model: config.model || 'fincept-llm',
+ displayName: 'FINCEPT (Pre-configured)',
+ type: 'fincept',
+ isActive: config.is_active
+ });
+ } else {
+ options.push({
+ id: config.provider,
+ provider: config.provider,
+ model: config.model,
+ displayName: `${config.provider.toUpperCase()} - ${config.model}`,
+ type: 'provider',
+ isActive: config.is_active
+ });
+ }
+ }
+
+ // Load custom model configs (LLMModelConfig) from Settings
+ const modelConfigs = await sqliteService.getLLMModelConfigs();
+ for (const model of modelConfigs) {
+ if (model.is_enabled) {
+ options.push({
+ id: model.id,
+ provider: model.provider,
+ model: model.model_id,
+ displayName: `${model.display_name} (${model.provider.toUpperCase()})`,
+ type: 'model',
+ isActive: model.is_default
+ });
+ }
+ }
+
+ // If Fincept wasn't in provider configs, add it as default
+ if (!options.find(o => o.provider === 'fincept')) {
+ options.unshift({
+ id: 'fincept',
+ provider: 'fincept',
+ model: 'fincept-llm',
+ displayName: 'FINCEPT (Pre-configured)',
+ type: 'fincept',
+ isActive: true
+ });
+ }
+
+ setAvailableProviders(options);
+ } catch (error) {
+ console.error('Failed to load LLM providers:', error);
+ // Default to Fincept if loading fails
+ setAvailableProviders([{
+ id: 'fincept',
+ provider: 'fincept',
+ model: 'fincept-llm',
+ displayName: 'FINCEPT (Pre-configured)',
+ type: 'fincept',
+ isActive: true
+ }]);
+ }
+ };
+ loadProviders();
+ }, []);
+
+ const getStatusColor = () => {
+ switch (data.status) {
+ case 'running': return BLUE;
+ case 'completed': return GREEN;
+ case 'error': return RED;
+ default: return ORANGE;
+ }
+ };
+
+ const getStatusIcon = () => {
+ switch (data.status) {
+ case 'running': return <Loader size={14} className="animate-spin" color={BLUE} />;
+ case 'completed': return <CheckCircle size={14} color={GREEN} />;
+ case 'error': return <AlertCircle size={14} color={RED} />;
+ default: return <Brain size={14} color={ORANGE} />;
+ }
+ };
+
+ const handleSaveConfig = () => {
+ data.onConfigChange?.({
+ selectedProvider: localProvider === 'active' ? undefined : localProvider,
+ customPrompt: localPrompt || undefined
+ });
+ setShowSettings(false);
+ };
+
+ const getProviderLabel = () => {
+ if (!data.selectedProvider || data.selectedProvider === 'active') {
+ return 'Active Provider';
+ }
+ const provider = availableProviders.find(p => p.id === data.selectedProvider);
+ return provider ? provider.displayName : data.selectedProvider;
+ };
+
+ return (
+ <div style={{
+ backgroundColor: PANEL_BG,
+ border: `2px solid ${selected ? ORANGE : getStatusColor()}`,
+ borderRadius: '8px',
+ padding: '12px',
+ minWidth: '280px',
+ maxWidth: '350px',
+ fontFamily: 'Consolas, monospace',
+ boxShadow: selected ? `0 0 16px ${ORANGE}60` : `0 2px 8px rgba(0,0,0,0.3)`
+ }}>
+ {/* Input Handle */}
+ <Handle
+ type="target"
+ position={Position.Left}
+ style={{
+ background: BLUE,
+ width: '12px',
+ height: '12px',
+ border: `2px solid ${DARK_BG}`,
+ left: '-6px'
+ }}
+ />
+
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '10px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${BORDER}`
+ }}>
+ <MessageSquare size={20} color={BLUE} />
+ <div style={{ flex: 1 }}>
+ <div style={{
+ color: WHITE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ marginBottom: '2px'
+ }}>
+ {data.label}
+ </div>
+ <div style={{
+ color: GRAY,
+ fontSize: '9px',
+ textTransform: 'uppercase'
+ }}>
+ LLM MEDIATOR
+ </div>
+ </div>
+ {getStatusIcon()}
+ </div>
+
+ {/* LLM Provider Display */}
+ <div style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${BORDER}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: BLUE,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ LLM PROVIDER
+ </div>
+ <div style={{
+ color: WHITE,
+ fontSize: '8px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}>
+ <Brain size={10} color={BLUE} />
+ {getProviderLabel()}
+ </div>
+ </div>
+
+ {/* Input Data Preview */}
+ {data.inputData && (
+ <div style={{
+ backgroundColor: `${GRAY}15`,
+ border: `1px solid ${GRAY}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: GRAY,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ INPUT DATA
+ </div>
+ <div style={{
+ color: WHITE,
+ fontSize: '8px',
+ fontFamily: 'monospace',
+ maxHeight: '50px',
+ overflow: 'auto'
+ }}>
+ {JSON.stringify(data.inputData, null, 2).substring(0, 80)}...
+ </div>
+ </div>
+ )}
+
+ {/* Mediated Result */}
+ {data.status === 'completed' && data.result && (
+ <div style={{
+ backgroundColor: `${GREEN}15`,
+ border: `1px solid ${GREEN}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: GREEN,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}>
+ <CheckCircle size={10} />
+ MEDIATED CONTEXT
+ </div>
+ <div style={{
+ color: WHITE,
+ fontSize: '8px',
+ maxHeight: '80px',
+ overflow: 'auto',
+ lineHeight: '1.4'
+ }}>
+ {typeof data.result === 'string'
+ ? data.result.substring(0, 150)
+ : JSON.stringify(data.result, null, 2).substring(0, 150)
+ }...
+ </div>
+ </div>
+ )}
+
+ {/* Error Display */}
+ {data.status === 'error' && data.error && (
+ <div style={{
+ backgroundColor: `${RED}15`,
+ border: `1px solid ${RED}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: RED,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}>
+ <AlertCircle size={10} />
+ ERROR
+ </div>
+ <div style={{
+ color: RED,
+ fontSize: '8px',
+ wordBreak: 'break-word'
+ }}>
+ {data.error}
+ </div>
+ </div>
+ )}
+
+ {/* Settings Panel */}
+ {showSettings && (
+ <div style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${ORANGE}`,
+ borderRadius: '4px',
+ padding: '8px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '10px',
+ fontWeight: 'bold',
+ marginBottom: '8px'
+ }}>
+ MEDIATOR SETTINGS
+ </div>
+
+ {/* Provider Selection */}
+ <div style={{ marginBottom: '8px' }}>
+ <label style={{
+ color: GRAY,
+ fontSize: '8px',
+ display: 'block',
+ marginBottom: '4px'
+ }}>
+ LLM Provider
+ </label>
+ <select
+ value={localProvider}
+ onChange={(e) => setLocalProvider(e.target.value)}
+ style={{
+ width: '100%',
+ backgroundColor: PANEL_BG,
+ border: `1px solid ${BORDER}`,
+ color: WHITE,
+ padding: '6px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ >
+ <option value="active">Use Active Provider (from Settings)</option>
+ {availableProviders.map(provider => (
+ <option key={provider.id} value={provider.id} style={{
+ backgroundColor: provider.type === 'fincept' ? '#1a3a1a' : undefined
+ }}>
+ {provider.displayName}{provider.isActive ? ' ✓' : ''}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Custom Prompt */}
+ <div style={{ marginBottom: '8px' }}>
+ <label style={{
+ color: GRAY,
+ fontSize: '8px',
+ display: 'block',
+ marginBottom: '4px'
+ }}>
+ Custom Mediation Prompt (optional)
+ </label>
+ <textarea
+ value={localPrompt}
+ onChange={(e) => setLocalPrompt(e.target.value)}
+ placeholder="Leave empty for default prompt"
+ rows={3}
+ style={{
+ width: '100%',
+ backgroundColor: PANEL_BG,
+ border: `1px solid ${BORDER}`,
+ color: WHITE,
+ padding: '4px',
+ fontSize: '8px',
+ borderRadius: '3px',
+ resize: 'vertical',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ <button
+ onClick={handleSaveConfig}
+ style={{
+ width: '100%',
+ backgroundColor: BLUE,
+ color: 'white',
+ border: 'none',
+ padding: '6px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '3px'
+ }}
+ >
+ SAVE CONFIG
+ </button>
+ </div>
+ )}
+
+ {/* Action Buttons */}
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <button
+ onClick={() => data.onExecute?.(id)}
+ disabled={data.status === 'running'}
+ style={{
+ flex: 1,
+ backgroundColor: data.status === 'running' ? GRAY : BLUE,
+ color: 'white',
+ border: 'none',
+ padding: '8px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: data.status === 'running' ? 'not-allowed' : 'pointer',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ opacity: data.status === 'running' ? 0.6 : 1
+ }}
+ >
+ {data.status === 'running' ? (
+ <>
+ <Loader size={12} className="animate-spin" />
+ MEDIATING...
+ </>
+ ) : (
+ <>
+ <Brain size={12} />
+ MEDIATE
+ </>
+ )}
+ </button>
+ <button
+ onClick={() => setShowSettings(!showSettings)}
+ style={{
+ backgroundColor: showSettings ? BLUE : DARK_BG,
+ border: `1px solid ${BORDER}`,
+ color: showSettings ? WHITE : GRAY,
+ padding: '8px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center'
+ }}
+ >
+ <Settings size={14} />
+ </button>
+ </div>
+
+ {/* Output Handle */}
+ <Handle
+ type="source"
+ position={Position.Right}
+ style={{
+ background: data.status === 'completed' ? GREEN : BLUE,
+ width: '12px',
+ height: '12px',
+ border: `2px solid ${DARK_BG}`,
+ right: '-6px'
+ }}
+ />
+ </div>
+ );
+};
+
+export default AgentMediatorNode;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/BacktestNode.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/BacktestNode.tsx
new file mode 100644
index 000000000..d96c0a4b7
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/BacktestNode.tsx
@@ -0,0 +1,369 @@
+/**
+ * Backtest Node
+ *
+ * ReactFlow node for running backtests in the workflow editor.
+ * Connects to strategy inputs and outputs backtest results.
+ */
+
+import React, { useState } from 'react';
+import { Handle, Position } from 'reactflow';
+import { Activity, Play, Settings, Check, AlertCircle, TrendingUp, Loader } from 'lucide-react';
+import { backtestingService } from '@/services/backtesting/BacktestingService';
+import { BacktestRequest, BacktestResult } from '@/services/backtesting/interfaces/types';
+
+interface BacktestNodeProps {
+ data: {
+ label: string;
+ strategyCode?: string;
+ startDate?: string;
+ endDate?: string;
+ initialCapital?: number;
+ status: 'idle' | 'running' | 'completed' | 'error';
+ result?: BacktestResult;
+ error?: string;
+ onStrategyChange?: (code: string) => void;
+ onConfigChange?: (config: any) => void;
+ onExecute?: () => Promise<void>;
+ };
+ selected: boolean;
+}
+
+const BacktestNode: React.FC<BacktestNodeProps> = ({ data, selected }) => {
+ const [showSettings, setShowSettings] = useState(false);
+ const [localConfig, setLocalConfig] = useState({
+ startDate: data.startDate || new Date(Date.now() - 365 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
+ endDate: data.endDate || new Date().toISOString().split('T')[0],
+ initialCapital: data.initialCapital || 100000,
+ });
+
+ const handleSaveSettings = () => {
+ if (data.onConfigChange) {
+ data.onConfigChange(localConfig);
+ }
+ setShowSettings(false);
+ };
+
+ const handleRunBacktest = async () => {
+ if (data.onExecute) {
+ await data.onExecute();
+ }
+ };
+
+ const getStatusColor = () => {
+ switch (data.status) {
+ case 'running': return '#3b82f6';
+ case 'completed': return '#10b981';
+ case 'error': return '#ef4444';
+ default: return '#6b7280';
+ }
+ };
+
+ const getStatusIcon = () => {
+ switch (data.status) {
+ case 'running': return <Loader size={14} className="animate-spin" color="#3b82f6" />;
+ case 'completed': return <Check size={14} color="#10b981" />;
+ case 'error': return <AlertCircle size={14} color="#ef4444" />;
+ default: return <Activity size={14} color="#6b7280" />;
+ }
+ };
+
+ const formatPerformance = () => {
+ if (!data.result) return null;
+ const perf = data.result.performance;
+ return {
+ totalReturn: (perf.totalReturn * 100).toFixed(2) + '%',
+ sharpe: perf.sharpeRatio.toFixed(2),
+ maxDD: (perf.maxDrawdown * 100).toFixed(2) + '%',
+ trades: perf.totalTrades,
+ };
+ };
+
+ const performance = formatPerformance();
+
+ return (
+ <div style={{
+ background: selected ? '#252525' : '#1a1a1a',
+ border: `2px solid ${selected ? '#3b82f6' : getStatusColor()}`,
+ borderRadius: '8px',
+ minWidth: '300px',
+ maxWidth: '400px',
+ fontFamily: 'Consolas, monospace',
+ boxShadow: selected ? `0 0 16px #3b82f660` : '0 2px 8px rgba(0,0,0,0.3)',
+ position: 'relative'
+ }}>
+ {/* Input Handle - Strategy */}
+ <Handle
+ type="target"
+ position={Position.Left}
+ id="strategy"
+ style={{
+ background: '#8b5cf6',
+ width: '12px',
+ height: '12px',
+ border: '2px solid #1a1a1a',
+ top: '30%'
+ }}
+ />
+
+ {/* Output Handle - Results */}
+ <Handle
+ type="source"
+ position={Position.Right}
+ id="results"
+ style={{
+ background: '#10b981',
+ width: '12px',
+ height: '12px',
+ border: '2px solid #1a1a1a',
+ }}
+ />
+
+ {/* Header */}
+ <div style={{
+ padding: '12px',
+ borderBottom: '1px solid #2a2a2a',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ background: '#1f1f1f'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Activity size={16} color={getStatusColor()} />
+ <span style={{ color: '#e5e7eb', fontSize: '12px', fontWeight: 'bold' }}>
+ {data.label}
+ </span>
+ </div>
+ <div style={{ display: 'flex', gap: '6px' }}>
+ {getStatusIcon()}
+ <Settings
+ size={14}
+ color="#9ca3af"
+ style={{ cursor: 'pointer' }}
+ onClick={() => setShowSettings(!showSettings)}
+ />
+ </div>
+ </div>
+
+ {/* Settings Panel */}
+ {showSettings && (
+ <div style={{
+ padding: '12px',
+ borderBottom: '1px solid #2a2a2a',
+ background: '#1a1a1a'
+ }}>
+ <div style={{ marginBottom: '8px' }}>
+ <label style={{ color: '#9ca3af', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ Start Date
+ </label>
+ <input
+ type="date"
+ value={localConfig.startDate}
+ onChange={(e) => setLocalConfig({ ...localConfig, startDate: e.target.value })}
+ style={{
+ width: '100%',
+ padding: '6px',
+ background: '#252525',
+ border: '1px solid #3a3a3a',
+ borderRadius: '4px',
+ color: '#e5e7eb',
+ fontSize: '10px'
+ }}
+ />
+ </div>
+
+ <div style={{ marginBottom: '8px' }}>
+ <label style={{ color: '#9ca3af', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ End Date
+ </label>
+ <input
+ type="date"
+ value={localConfig.endDate}
+ onChange={(e) => setLocalConfig({ ...localConfig, endDate: e.target.value })}
+ style={{
+ width: '100%',
+ padding: '6px',
+ background: '#252525',
+ border: '1px solid #3a3a3a',
+ borderRadius: '4px',
+ color: '#e5e7eb',
+ fontSize: '10px'
+ }}
+ />
+ </div>
+
+ <div style={{ marginBottom: '8px' }}>
+ <label style={{ color: '#9ca3af', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ Initial Capital ($)
+ </label>
+ <input
+ type="number"
+ value={localConfig.initialCapital}
+ onChange={(e) => setLocalConfig({ ...localConfig, initialCapital: Number(e.target.value) })}
+ style={{
+ width: '100%',
+ padding: '6px',
+ background: '#252525',
+ border: '1px solid #3a3a3a',
+ borderRadius: '4px',
+ color: '#e5e7eb',
+ fontSize: '10px'
+ }}
+ />
+ </div>
+
+ <button
+ onClick={handleSaveSettings}
+ style={{
+ width: '100%',
+ padding: '6px',
+ background: '#3b82f6',
+ color: 'white',
+ border: 'none',
+ borderRadius: '4px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ fontWeight: 'bold'
+ }}
+ >
+ Save Configuration
+ </button>
+ </div>
+ )}
+
+ {/* Content */}
+ <div style={{ padding: '12px' }}>
+ {/* Configuration Display */}
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ fontSize: '10px', color: '#9ca3af', marginBottom: '6px' }}>
+ Configuration:
+ </div>
+ <div style={{ fontSize: '9px', color: '#d1d5db', fontFamily: 'monospace' }}>
+ {localConfig.startDate} → {localConfig.endDate}
+ </div>
+ <div style={{ fontSize: '9px', color: '#d1d5db', fontFamily: 'monospace' }}>
+ Capital: ${localConfig.initialCapital.toLocaleString()}
+ </div>
+ </div>
+
+ {/* Results Display */}
+ {performance && data.status === 'completed' && (
+ <div style={{
+ padding: '8px',
+ background: '#1f1f1f',
+ borderRadius: '4px',
+ marginBottom: '8px'
+ }}>
+ <div style={{ fontSize: '10px', color: '#9ca3af', marginBottom: '6px', display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <TrendingUp size={12} />
+ Results:
+ </div>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px', fontSize: '9px' }}>
+ <div>
+ <div style={{ color: '#6b7280' }}>Total Return</div>
+ <div style={{ color: performance.totalReturn.startsWith('-') ? '#ef4444' : '#10b981', fontWeight: 'bold' }}>
+ {performance.totalReturn}
+ </div>
+ </div>
+ <div>
+ <div style={{ color: '#6b7280' }}>Sharpe Ratio</div>
+ <div style={{ color: '#e5e7eb', fontWeight: 'bold' }}>
+ {performance.sharpe}
+ </div>
+ </div>
+ <div>
+ <div style={{ color: '#6b7280' }}>Max DD</div>
+ <div style={{ color: '#ef4444', fontWeight: 'bold' }}>
+ {performance.maxDD}
+ </div>
+ </div>
+ <div>
+ <div style={{ color: '#6b7280' }}>Trades</div>
+ <div style={{ color: '#e5e7eb', fontWeight: 'bold' }}>
+ {performance.trades}
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Error Display */}
+ {data.error && data.status === 'error' && (
+ <div style={{
+ padding: '8px',
+ background: '#3a0a0a',
+ border: '1px solid #ef4444',
+ borderRadius: '4px',
+ marginBottom: '8px'
+ }}>
+ <div style={{ fontSize: '10px', color: '#ef4444', marginBottom: '4px' }}>
+ Error:
+ </div>
+ <div style={{ fontSize: '9px', color: '#fca5a5' }}>
+ {data.error}
+ </div>
+ </div>
+ )}
+
+ {/* Run Button */}
+ <button
+ onClick={handleRunBacktest}
+ disabled={data.status === 'running' || !data.strategyCode}
+ style={{
+ width: '100%',
+ padding: '8px',
+ background: data.status === 'running' ? '#6b7280' : '#3b82f6',
+ color: 'white',
+ border: 'none',
+ borderRadius: '4px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: data.status === 'running' || !data.strategyCode ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '6px',
+ opacity: data.status === 'running' || !data.strategyCode ? 0.6 : 1
+ }}
+ >
+ {data.status === 'running' ? (
+ <>
+ <Loader size={14} className="animate-spin" />
+ Running Backtest...
+ </>
+ ) : (
+ <>
+ <Play size={14} />
+ Run Backtest
+ </>
+ )}
+ </button>
+ </div>
+
+ {/* Handle Labels */}
+ <div style={{
+ position: 'absolute',
+ left: '-60px',
+ top: '30%',
+ transform: 'translateY(-50%)',
+ fontSize: '9px',
+ color: '#6b7280',
+ whiteSpace: 'nowrap'
+ }}>
+ Strategy
+ </div>
+ <div style={{
+ position: 'absolute',
+ right: '-50px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ fontSize: '9px',
+ color: '#6b7280',
+ whiteSpace: 'nowrap'
+ }}>
+ Results
+ </div>
+ </div>
+ );
+};
+
+export default BacktestNode;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/DataSourceNode.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/DataSourceNode.tsx
new file mode 100644
index 000000000..910a35e5d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/DataSourceNode.tsx
@@ -0,0 +1,432 @@
+import React, { useState } from 'react';
+import { Handle, Position } from 'reactflow';
+import { Database, Play, Settings, Check, AlertCircle } from 'lucide-react';
+
+interface DataSourceNodeProps {
+ data: {
+ label: string;
+ selectedConnectionId?: string;
+ query: string;
+ status: 'idle' | 'running' | 'completed' | 'error';
+ result?: any;
+ error?: string;
+ onConnectionChange: (connectionId: string) => void;
+ onQueryChange: (query: string) => void;
+ onExecute: () => void;
+ };
+ selected: boolean;
+}
+
+// Mock available database connections (in real app, fetch from settings/database)
+const MOCK_CONNECTIONS = [
+ { id: 'postgres_1', name: 'PostgreSQL - Production', type: 'PostgreSQL' },
+ { id: 'mysql_1', name: 'MySQL - Analytics', type: 'MySQL' },
+ { id: 'mongodb_1', name: 'MongoDB - Orders', type: 'MongoDB' },
+ { id: 'sqlite_1', name: 'SQLite - Local', type: 'SQLite' },
+];
+
+const DataSourceNode: React.FC<DataSourceNodeProps> = ({ data, selected }) => {
+ const [showSettings, setShowSettings] = useState(false);
+ const [localQuery, setLocalQuery] = useState(data.query || '');
+ const [localConnection, setLocalConnection] = useState(data.selectedConnectionId || '');
+
+ const handleSaveSettings = () => {
+ if (localConnection) {
+ data.onConnectionChange(localConnection);
+ }
+ if (localQuery) {
+ data.onQueryChange(localQuery);
+ }
+ setShowSettings(false);
+ };
+
+ const getStatusColor = () => {
+ switch (data.status) {
+ case 'running': return '#3b82f6';
+ case 'completed': return '#10b981';
+ case 'error': return '#ef4444';
+ default: return '#6b7280';
+ }
+ };
+
+ const getStatusIcon = () => {
+ switch (data.status) {
+ case 'running': return '🔄';
+ case 'completed': return <Check size={14} color="#10b981" />;
+ case 'error': return <AlertCircle size={14} color="#ef4444" />;
+ default: return <Database size={14} color="#6b7280" />;
+ }
+ };
+
+ const selectedConnection = MOCK_CONNECTIONS.find(c => c.id === (localConnection || data.selectedConnectionId));
+ const isConfigured = data.selectedConnectionId && data.query;
+
+ return (
+ <div style={{
+ background: selected ? '#252525' : '#1a1a1a',
+ border: `2px solid ${selected ? '#3b82f6' : getStatusColor()}`,
+ borderRadius: '8px',
+ minWidth: '280px',
+ maxWidth: '400px',
+ fontFamily: 'Consolas, monospace',
+ boxShadow: selected ? `0 0 16px #3b82f660` : '0 2px 8px rgba(0,0,0,0.3)',
+ position: 'relative'
+ }}>
+ {/* Output Handle */}
+ <Handle
+ type="source"
+ position={Position.Right}
+ style={{
+ background: '#3b82f6',
+ width: '12px',
+ height: '12px',
+ border: '2px solid #0a0a0a',
+ right: '-6px'
+ }}
+ />
+
+ {/* Header */}
+ <div style={{
+ backgroundColor: '#0f0f0f',
+ padding: '10px 12px',
+ borderTopLeftRadius: '6px',
+ borderTopRightRadius: '6px',
+ borderBottom: '1px solid #2d2d2d',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between'
+ }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}>
+ <Database size={16} color="#3b82f6" />
+ <span style={{
+ color: '#fff',
+ fontSize: '12px',
+ fontWeight: 'bold'
+ }}>
+ {data.label}
+ </span>
+ </div>
+ <div style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>
+ {getStatusIcon()}
+ <button
+ onClick={() => setShowSettings(!showSettings)}
+ style={{
+ backgroundColor: showSettings ? '#3b82f6' : 'transparent',
+ border: `1px solid ${showSettings ? '#3b82f6' : '#404040'}`,
+ color: showSettings ? '#fff' : '#6b7280',
+ padding: '4px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ transition: 'all 0.2s'
+ }}
+ title="Configure data source"
+ >
+ <Settings size={12} />
+ </button>
+ </div>
+ </div>
+
+ {/* Configuration Panel */}
+ {showSettings ? (
+ <div style={{
+ padding: '12px',
+ backgroundColor: '#0a0a0a'
+ }}>
+ {/* Connection Selector */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: '#a3a3a3',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px'
+ }}>
+ Database Connection
+ </label>
+ <select
+ value={localConnection}
+ onChange={(e) => setLocalConnection(e.target.value)}
+ style={{
+ width: '100%',
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #404040',
+ color: '#fff',
+ padding: '8px',
+ fontSize: '11px',
+ borderRadius: '4px',
+ cursor: 'pointer',
+ fontFamily: 'Consolas, monospace'
+ }}
+ >
+ <option value="">-- Select Connection --</option>
+ {MOCK_CONNECTIONS.map(conn => (
+ <option key={conn.id} value={conn.id}>
+ {conn.name} ({conn.type})
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Query Editor */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{
+ display: 'block',
+ color: '#a3a3a3',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ marginBottom: '6px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px'
+ }}>
+ SQL Query
+ </label>
+ <textarea
+ value={localQuery}
+ onChange={(e) => setLocalQuery(e.target.value)}
+ placeholder="SELECT * FROM table WHERE condition"
+ style={{
+ width: '100%',
+ height: '100px',
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #404040',
+ color: '#fff',
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '4px',
+ resize: 'vertical',
+ fontFamily: 'Consolas, monospace',
+ lineHeight: '1.5'
+ }}
+ />
+ </div>
+
+ {/* Action Buttons */}
+ <div style={{
+ display: 'flex',
+ gap: '8px'
+ }}>
+ <button
+ onClick={handleSaveSettings}
+ disabled={!localConnection || !localQuery.trim()}
+ style={{
+ flex: 1,
+ backgroundColor: (!localConnection || !localQuery.trim()) ? '#404040' : '#10b981',
+ color: '#fff',
+ border: 'none',
+ padding: '8px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: (!localConnection || !localQuery.trim()) ? 'not-allowed' : 'pointer',
+ borderRadius: '4px',
+ opacity: (!localConnection || !localQuery.trim()) ? 0.5 : 1
+ }}
+ >
+ SAVE CONFIG
+ </button>
+ <button
+ onClick={() => setShowSettings(false)}
+ style={{
+ backgroundColor: 'transparent',
+ color: '#6b7280',
+ border: '1px solid #404040',
+ padding: '8px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '4px'
+ }}
+ >
+ CANCEL
+ </button>
+ </div>
+ </div>
+ ) : (
+ /* Summary View */
+ <div style={{ padding: '12px' }}>
+ {/* Connection Info */}
+ {selectedConnection ? (
+ <div style={{
+ backgroundColor: '#0f0f0f',
+ border: '1px solid #2d2d2d',
+ borderRadius: '4px',
+ padding: '8px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: '#3b82f6',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px'
+ }}>
+ Connection
+ </div>
+ <div style={{
+ color: '#fff',
+ fontSize: '11px',
+ marginBottom: '2px'
+ }}>
+ {selectedConnection.name}
+ </div>
+ <div style={{
+ color: '#6b7280',
+ fontSize: '9px'
+ }}>
+ {selectedConnection.type}
+ </div>
+ </div>
+ ) : (
+ <div style={{
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #404040',
+ borderRadius: '4px',
+ padding: '8px',
+ marginBottom: '8px',
+ textAlign: 'center',
+ color: '#6b7280',
+ fontSize: '10px'
+ }}>
+ No connection selected
+ </div>
+ )}
+
+ {/* Query Preview */}
+ {data.query ? (
+ <div style={{
+ backgroundColor: '#0f0f0f',
+ border: '1px solid #2d2d2d',
+ borderRadius: '4px',
+ padding: '8px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: '#3b82f6',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px'
+ }}>
+ Query
+ </div>
+ <div style={{
+ color: '#d4d4d4',
+ fontSize: '9px',
+ fontFamily: 'Consolas, monospace',
+ lineHeight: '1.4',
+ maxHeight: '60px',
+ overflow: 'auto',
+ whiteSpace: 'pre-wrap',
+ wordBreak: 'break-word'
+ }}>
+ {data.query}
+ </div>
+ </div>
+ ) : (
+ <div style={{
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #404040',
+ borderRadius: '4px',
+ padding: '8px',
+ marginBottom: '8px',
+ textAlign: 'center',
+ color: '#6b7280',
+ fontSize: '10px'
+ }}>
+ No query defined
+ </div>
+ )}
+
+ {/* Execute Button */}
+ <button
+ onClick={data.onExecute}
+ disabled={!isConfigured || data.status === 'running'}
+ style={{
+ width: '100%',
+ backgroundColor: (!isConfigured || data.status === 'running') ? '#404040' : '#3b82f6',
+ color: '#fff',
+ border: 'none',
+ padding: '8px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: (!isConfigured || data.status === 'running') ? 'not-allowed' : 'pointer',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '6px',
+ opacity: (!isConfigured || data.status === 'running') ? 0.5 : 1
+ }}
+ >
+ <Play size={12} />
+ {data.status === 'running' ? 'EXECUTING...' : 'EXECUTE QUERY'}
+ </button>
+
+ {/* Result/Error Display */}
+ {data.status === 'completed' && data.result && (
+ <div style={{
+ marginTop: '8px',
+ backgroundColor: '#0f0f0f',
+ border: '1px solid #10b981',
+ borderRadius: '4px',
+ padding: '8px'
+ }}>
+ <div style={{
+ color: '#10b981',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ [OK] Query Successful
+ </div>
+ <div style={{
+ color: '#6b7280',
+ fontSize: '9px'
+ }}>
+ {data.result.rowCount || 0} rows returned
+ </div>
+ </div>
+ )}
+
+ {data.status === 'error' && data.error && (
+ <div style={{
+ marginTop: '8px',
+ backgroundColor: '#1a0a0a',
+ border: '1px solid #ef4444',
+ borderRadius: '4px',
+ padding: '8px'
+ }}>
+ <div style={{
+ color: '#ef4444',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ [FAIL] Error
+ </div>
+ <div style={{
+ color: '#d4d4d4',
+ fontSize: '9px',
+ lineHeight: '1.4',
+ wordBreak: 'break-word'
+ }}>
+ {data.error}
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default DataSourceNode;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/MCPToolNode.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/MCPToolNode.tsx
new file mode 100644
index 000000000..6e022c64c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/MCPToolNode.tsx
@@ -0,0 +1,361 @@
+// MCP Tool Node - Generic node component for MCP tools in Node Editor
+// Dynamically renders based on tool schema
+
+import React, { useState, useEffect } from 'react';
+import { Handle, Position } from 'reactflow';
+import { Zap, AlertCircle, CheckCircle, Loader } from 'lucide-react';
+import { mcpToolService, MCPTool } from '@/services/mcp/mcpToolService';
+
+interface MCPToolNodeProps {
+ data: {
+ serverId: string;
+ toolName: string;
+ label: string;
+ parameters?: Record<string, any>;
+ onParameterChange?: (params: Record<string, any>) => void;
+ onExecute?: (result: any) => void;
+ inputs?: Record<string, any>; // Inputs from connected nodes
+ };
+ selected: boolean;
+}
+
+const MCPToolNode: React.FC<MCPToolNodeProps> = ({ data, selected }) => {
+ const [parameters, setParameters] = useState<Record<string, any>>(data.parameters || {});
+ const [tool, setTool] = useState<MCPTool | null>(null);
+ const [isExecuting, setIsExecuting] = useState(false);
+ const [lastResult, setLastResult] = useState<any>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ // Fincept colors
+ const ORANGE = '#FFA500';
+ const WHITE = '#FFFFFF';
+ const GRAY = '#787878';
+ const DARK_BG = '#0a0a0a';
+ const PANEL_BG = '#1a1a1a';
+ const BORDER = '#2d2d2d';
+ const GREEN = '#10b981';
+ const RED = '#ef4444';
+ const YELLOW = '#FFFF00';
+
+ // Load tool schema on mount
+ useEffect(() => {
+ const loadTool = async () => {
+ try {
+ const toolData = await mcpToolService.getTool(data.serverId, data.toolName);
+ setTool(toolData);
+ } catch (err) {
+ console.error('[MCPToolNode] Failed to load tool:', err);
+ setError('Failed to load tool schema');
+ }
+ };
+ loadTool();
+ }, [data.serverId, data.toolName]);
+
+ // Merge inputs from connected nodes with manual parameters
+ const getMergedParameters = (): Record<string, any> => {
+ return {
+ ...parameters,
+ ...(data.inputs || {})
+ };
+ };
+
+ // Execute the tool
+ const executeTool = async () => {
+ if (!tool) return;
+
+ setIsExecuting(true);
+ setError(null);
+
+ try {
+ const mergedParams = getMergedParameters();
+ const result = await mcpToolService.executeToolDirect(
+ data.serverId,
+ data.toolName,
+ mergedParams
+ );
+
+ if (result.success) {
+ setLastResult(result.data);
+ data.onExecute?.(result.data);
+ } else {
+ setError(result.error || 'Unknown error');
+ }
+ } catch (err: any) {
+ setError(err.message || 'Execution failed');
+ } finally {
+ setIsExecuting(false);
+ }
+ };
+
+ // Handle parameter change
+ const handleParameterChange = (key: string, value: any) => {
+ const newParams = { ...parameters, [key]: value };
+ setParameters(newParams);
+ data.onParameterChange?.(newParams);
+ };
+
+ // Get required parameters from schema
+ const getRequiredParams = (): string[] => {
+ if (!tool?.inputSchema?.required) return [];
+ return tool.inputSchema.required;
+ };
+
+ // Render parameter input based on type
+ const renderParameterInput = (key: string, propSchema: any) => {
+ const isRequired = getRequiredParams().includes(key);
+ const value = parameters[key] || '';
+ const type = propSchema.type || 'string';
+
+ // Check if parameter is provided by connected node
+ const isProvidedByConnection = data.inputs && key in data.inputs;
+
+ return (
+ <div key={key} style={{ marginBottom: '8px' }}>
+ <label style={{
+ color: isRequired ? YELLOW : GRAY,
+ fontSize: '9px',
+ display: 'block',
+ marginBottom: '2px',
+ fontWeight: isRequired ? 'bold' : 'normal'
+ }}>
+ {key}{isRequired ? ' *' : ''}
+ {isProvidedByConnection && (
+ <span style={{ color: GREEN, marginLeft: '4px' }}>
+ [Connected]
+ </span>
+ )}
+ </label>
+ {type === 'boolean' ? (
+ <input
+ type="checkbox"
+ checked={value || false}
+ onChange={(e) => handleParameterChange(key, e.target.checked)}
+ disabled={isProvidedByConnection}
+ style={{
+ cursor: isProvidedByConnection ? 'not-allowed' : 'pointer',
+ opacity: isProvidedByConnection ? 0.5 : 1
+ }}
+ />
+ ) : type === 'number' ? (
+ <input
+ type="number"
+ value={value}
+ onChange={(e) => handleParameterChange(key, parseFloat(e.target.value))}
+ disabled={isProvidedByConnection}
+ style={{
+ width: '100%',
+ backgroundColor: DARK_BG,
+ border: `1px solid ${BORDER}`,
+ color: WHITE,
+ padding: '4px',
+ fontSize: '9px',
+ fontFamily: 'monospace',
+ opacity: isProvidedByConnection ? 0.5 : 1,
+ cursor: isProvidedByConnection ? 'not-allowed' : 'text'
+ }}
+ />
+ ) : (
+ <textarea
+ value={value}
+ onChange={(e) => handleParameterChange(key, e.target.value)}
+ disabled={isProvidedByConnection}
+ placeholder={propSchema.description || ''}
+ style={{
+ width: '100%',
+ backgroundColor: DARK_BG,
+ border: `1px solid ${BORDER}`,
+ color: WHITE,
+ padding: '4px',
+ fontSize: '9px',
+ fontFamily: 'monospace',
+ resize: 'vertical',
+ minHeight: '40px',
+ opacity: isProvidedByConnection ? 0.5 : 1,
+ cursor: isProvidedByConnection ? 'not-allowed' : 'text'
+ }}
+ />
+ )}
+ </div>
+ );
+ };
+
+ // Check if tool is ready to execute
+ const isReadyToExecute = (): boolean => {
+ if (!tool) return false;
+ const mergedParams = getMergedParameters();
+ const validation = mcpToolService.validateToolParams(tool, mergedParams);
+ return validation.valid;
+ };
+
+ return (
+ <div style={{
+ backgroundColor: PANEL_BG,
+ border: `2px solid ${selected ? ORANGE : BORDER}`,
+ borderRadius: '6px',
+ padding: '12px',
+ minWidth: '280px',
+ maxWidth: '350px',
+ fontFamily: 'Consolas, monospace',
+ boxShadow: selected ? `0 0 12px ${ORANGE}80` : 'none'
+ }}>
+ {/* Input handles - dynamically generated from schema */}
+ {tool?.inputSchema?.properties && Object.keys(tool.inputSchema.properties).map((key, index) => (
+ <Handle
+ key={`input-${key}`}
+ type="target"
+ position={Position.Left}
+ id={key}
+ style={{
+ top: `${30 + (index * 20)}px`,
+ background: ORANGE,
+ width: '10px',
+ height: '10px',
+ border: `2px solid ${DARK_BG}`
+ }}
+ />
+ ))}
+
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '12px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${BORDER}`
+ }}>
+ <Zap size={16} color={ORANGE} />
+ <div style={{ flex: 1 }}>
+ <div style={{
+ color: WHITE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginBottom: '2px'
+ }}>
+ {data.label}
+ </div>
+ <div style={{
+ color: GRAY,
+ fontSize: '8px'
+ }}>
+ {data.serverId} • {data.toolName}
+ </div>
+ </div>
+ </div>
+
+ {/* Tool Description */}
+ {tool?.description && (
+ <div style={{
+ color: GRAY,
+ fontSize: '9px',
+ marginBottom: '12px',
+ lineHeight: '1.4'
+ }}>
+ {tool.description}
+ </div>
+ )}
+
+ {/* Parameters */}
+ {tool?.inputSchema?.properties && (
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{
+ color: YELLOW,
+ fontSize: '10px',
+ fontWeight: 'bold',
+ marginBottom: '8px'
+ }}>
+ PARAMETERS
+ </div>
+ {Object.entries(tool.inputSchema.properties).map(([key, propSchema]: [string, any]) =>
+ renderParameterInput(key, propSchema)
+ )}
+ </div>
+ )}
+
+ {/* Execute Button */}
+ <button
+ onClick={executeTool}
+ disabled={!isReadyToExecute() || isExecuting}
+ style={{
+ width: '100%',
+ backgroundColor: isReadyToExecute() && !isExecuting ? GREEN : GRAY,
+ color: 'black',
+ border: 'none',
+ padding: '8px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: isReadyToExecute() && !isExecuting ? 'pointer' : 'not-allowed',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '6px',
+ marginBottom: '8px'
+ }}
+ >
+ {isExecuting ? (
+ <>
+ <Loader size={12} className="animate-spin" />
+ EXECUTING...
+ </>
+ ) : (
+ <>
+ <Zap size={12} />
+ EXECUTE TOOL
+ </>
+ )}
+ </button>
+
+ {/* Status */}
+ {error && (
+ <div style={{
+ backgroundColor: `${RED}20`,
+ border: `1px solid ${RED}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px'
+ }}>
+ <AlertCircle size={12} color={RED} />
+ <div style={{ color: RED, fontSize: '9px', flex: 1 }}>
+ {error}
+ </div>
+ </div>
+ )}
+
+ {lastResult && !error && (
+ <div style={{
+ backgroundColor: `${GREEN}20`,
+ border: `1px solid ${GREEN}`,
+ borderRadius: '4px',
+ padding: '6px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px'
+ }}>
+ <CheckCircle size={12} color={GREEN} />
+ <div style={{ color: GREEN, fontSize: '9px', flex: 1 }}>
+ Executed successfully
+ </div>
+ </div>
+ )}
+
+ {/* Output handle */}
+ <Handle
+ type="source"
+ position={Position.Right}
+ id="output"
+ style={{
+ background: GREEN,
+ width: '10px',
+ height: '10px',
+ border: `2px solid ${DARK_BG}`
+ }}
+ />
+ </div>
+ );
+};
+
+export default MCPToolNode;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/NodeParameterInput.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/NodeParameterInput.tsx
new file mode 100644
index 000000000..a1c84e8df
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/NodeParameterInput.tsx
@@ -0,0 +1,659 @@
+/**
+ * Node Parameter Input Component - Fincept Terminal Style
+ *
+ * Universal parameter input component that renders the appropriate UI control
+ * based on the parameter type from the node system.
+ *
+ * Supports all n8n parameter types:
+ * - String, Number, Boolean
+ * - Options, MultiOptions
+ * - Collection, FixedCollection
+ * - Color, DateTime
+ * - ResourceLocator
+ * - Code editor
+ * - Expression support
+ */
+
+import React, { useState, useCallback } from 'react';
+import type {
+ INodeProperties,
+ NodeParameterValue,
+ NodePropertyType,
+ INodePropertyOptions,
+} from '@/services/nodeSystem';
+import { isExpression } from '@/services/nodeSystem';
+import { Check, Code2, Calendar, Hash, Type, List, Settings2, Palette, ChevronDown } from 'lucide-react';
+
+// Fincept Terminal Style Constants
+const FINCEPT = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ YELLOW: '#FFD700',
+ CYAN: '#00E5FF',
+ GRAY: '#BBBBBB',
+ MUTED: '#888888',
+ DARK_BG: '#000000',
+ PANEL_BG: '#141414',
+ INPUT_BG: '#1A1A1A',
+ BORDER: '#3A3A3A',
+ FONT: '"IBM Plex Mono", "Consolas", monospace',
+};
+
+const inputBaseStyle: React.CSSProperties = {
+ width: '100%',
+ backgroundColor: FINCEPT.INPUT_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ padding: '10px 12px',
+ color: FINCEPT.WHITE,
+ fontSize: '13px',
+ fontFamily: FINCEPT.FONT,
+ outline: 'none',
+ transition: 'all 0.15s ease',
+};
+
+const labelStyle: React.CSSProperties = {
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ color: FINCEPT.GRAY,
+ fontSize: '12px',
+ fontWeight: 600,
+ marginBottom: '8px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px',
+};
+
+interface NodeParameterInputProps {
+ parameter: INodeProperties;
+ value: NodeParameterValue;
+ onChange: (value: NodeParameterValue) => void;
+ onExpressionChange?: (isExpression: boolean) => void;
+ disabled?: boolean;
+ itemIndex?: number;
+ expressionContext?: any;
+}
+
+export const NodeParameterInput: React.FC<NodeParameterInputProps> = ({
+ parameter,
+ value,
+ onChange,
+ onExpressionChange,
+ disabled = false,
+}) => {
+ const [isExpressionMode, setIsExpressionMode] = useState(
+ typeof value === 'string' && isExpression(value)
+ );
+ const [isFocused, setIsFocused] = useState(false);
+
+ const handleToggleExpression = useCallback(() => {
+ const newMode = !isExpressionMode;
+ setIsExpressionMode(newMode);
+ onExpressionChange?.(newMode);
+
+ if (newMode) {
+ onChange(`={{${value}}}`);
+ } else {
+ const strValue = String(value);
+ if (strValue.startsWith('={{') && strValue.endsWith('}}')) {
+ onChange(strValue.slice(3, -2));
+ }
+ }
+ }, [isExpressionMode, value, onChange, onExpressionChange]);
+
+ const getFocusStyle = (): React.CSSProperties => ({
+ borderColor: isFocused ? FINCEPT.ORANGE : FINCEPT.BORDER,
+ boxShadow: isFocused ? `0 0 8px ${FINCEPT.ORANGE}30` : 'none',
+ backgroundColor: isFocused ? FINCEPT.PANEL_BG : FINCEPT.INPUT_BG,
+ });
+
+ const renderInput = () => {
+ if (isExpressionMode) {
+ return (
+ <textarea
+ value={String(value)}
+ onChange={(e) => onChange(e.target.value)}
+ disabled={disabled}
+ placeholder="={{$json.field}}"
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ color: FINCEPT.YELLOW,
+ minHeight: '60px',
+ resize: 'vertical',
+ }}
+ />
+ );
+ }
+
+ switch (parameter.type) {
+ case 'string' as NodePropertyType:
+ return renderStringInput();
+ case 'number' as NodePropertyType:
+ return renderNumberInput();
+ case 'boolean' as NodePropertyType:
+ return renderBooleanInput();
+ case 'options' as NodePropertyType:
+ return renderOptionsInput();
+ case 'multiOptions' as NodePropertyType:
+ return renderMultiOptionsInput();
+ case 'color' as NodePropertyType:
+ return renderColorInput();
+ case 'dateTime' as NodePropertyType:
+ return renderDateTimeInput();
+ case 'json' as NodePropertyType:
+ case 'code' as NodePropertyType:
+ return renderCodeInput();
+ case 'collection' as NodePropertyType:
+ return renderCollectionInput();
+ case 'fixedCollection' as NodePropertyType:
+ return renderFixedCollectionInput();
+ case 'resourceLocator' as NodePropertyType:
+ return renderResourceLocatorInput();
+ default:
+ return renderStringInput();
+ }
+ };
+
+ const renderStringInput = () => (
+ <input
+ type="text"
+ value={String(value || '')}
+ onChange={(e) => onChange(e.target.value)}
+ disabled={disabled}
+ placeholder={parameter.placeholder || 'Enter value...'}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ }}
+ />
+ );
+
+ const renderNumberInput = () => (
+ <div style={{ display: 'flex', alignItems: 'stretch' }}>
+ <div style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${isFocused ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ borderRight: 'none',
+ padding: '0 10px',
+ display: 'flex',
+ alignItems: 'center',
+ color: FINCEPT.ORANGE,
+ fontSize: '13px',
+ transition: 'all 0.15s ease',
+ }}>
+ <Hash size={14} />
+ </div>
+ <input
+ type="number"
+ value={Number(value || 0)}
+ onChange={(e) => onChange(Number(e.target.value))}
+ disabled={disabled}
+ placeholder={parameter.placeholder}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ borderLeft: 'none',
+ flex: 1,
+ }}
+ />
+ </div>
+ );
+
+ const renderBooleanInput = () => (
+ <div
+ onClick={() => !disabled && onChange(!Boolean(value))}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '10px',
+ padding: '8px 10px',
+ backgroundColor: FINCEPT.INPUT_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ cursor: disabled ? 'not-allowed' : 'pointer',
+ transition: 'all 0.15s ease',
+ }}
+ onMouseEnter={(e) => {
+ if (!disabled) e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ }}
+ >
+ <div style={{
+ width: '32px',
+ height: '16px',
+ backgroundColor: Boolean(value) ? FINCEPT.GREEN : FINCEPT.MUTED,
+ borderRadius: '8px',
+ position: 'relative',
+ transition: 'all 0.15s ease',
+ }}>
+ <div style={{
+ position: 'absolute',
+ top: '2px',
+ left: Boolean(value) ? '16px' : '2px',
+ width: '12px',
+ height: '12px',
+ backgroundColor: FINCEPT.WHITE,
+ borderRadius: '50%',
+ transition: 'all 0.15s ease',
+ }} />
+ </div>
+ <span style={{
+ color: Boolean(value) ? FINCEPT.GREEN : FINCEPT.GRAY,
+ fontSize: '13px',
+ fontFamily: FINCEPT.FONT,
+ fontWeight: 600,
+ textTransform: 'uppercase',
+ }}>
+ {Boolean(value) ? 'ENABLED' : 'DISABLED'}
+ </span>
+ </div>
+ );
+
+ const renderOptionsInput = () => {
+ const options = parameter.options as INodePropertyOptions[] | undefined;
+
+ return (
+ <div style={{ position: 'relative' }}>
+ <select
+ value={String(value || parameter.default || '')}
+ onChange={(e) => onChange(e.target.value)}
+ disabled={disabled}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ appearance: 'none',
+ paddingRight: '28px',
+ cursor: 'pointer',
+ }}
+ >
+ {options?.map((option) => (
+ <option
+ key={String(option.value)}
+ value={String(option.value)}
+ style={{
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ }}
+ >
+ {option.name}
+ </option>
+ ))}
+ </select>
+ <ChevronDown
+ size={16}
+ style={{
+ position: 'absolute',
+ right: '12px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ color: FINCEPT.ORANGE,
+ pointerEvents: 'none',
+ }}
+ />
+ </div>
+ );
+ };
+
+ const renderMultiOptionsInput = () => {
+ const options = parameter.options as INodePropertyOptions[] | undefined;
+ const selectedValues = Array.isArray(value) ? value : [];
+
+ return (
+ <div style={{
+ backgroundColor: FINCEPT.INPUT_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ padding: '8px',
+ }}>
+ {options?.map((option) => (
+ <div
+ key={String(option.value)}
+ onClick={() => {
+ if (disabled) return;
+ const newValues = selectedValues.includes(option.value)
+ ? selectedValues.filter((v) => v !== option.value)
+ : [...selectedValues, option.value];
+ onChange(newValues);
+ }}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ padding: '6px 8px',
+ cursor: disabled ? 'not-allowed' : 'pointer',
+ backgroundColor: selectedValues.includes(option.value) ? `${FINCEPT.ORANGE}15` : 'transparent',
+ marginBottom: '4px',
+ transition: 'all 0.15s ease',
+ }}
+ >
+ <div style={{
+ width: '18px',
+ height: '18px',
+ border: `2px solid ${selectedValues.includes(option.value) ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ backgroundColor: selectedValues.includes(option.value) ? FINCEPT.ORANGE : 'transparent',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ }}>
+ {selectedValues.includes(option.value) && (
+ <Check size={14} style={{ color: FINCEPT.DARK_BG }} />
+ )}
+ </div>
+ <span style={{
+ color: selectedValues.includes(option.value) ? FINCEPT.WHITE : FINCEPT.GRAY,
+ fontSize: '13px',
+ fontFamily: FINCEPT.FONT,
+ }}>
+ {option.name}
+ </span>
+ </div>
+ ))}
+ </div>
+ );
+ };
+
+ const renderColorInput = () => (
+ <div style={{ display: 'flex', alignItems: 'stretch', gap: '8px' }}>
+ <input
+ type="color"
+ value={String(value || '#FF8800')}
+ onChange={(e) => onChange(e.target.value)}
+ disabled={disabled}
+ style={{
+ width: '40px',
+ height: '32px',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: FINCEPT.INPUT_BG,
+ cursor: 'pointer',
+ padding: '2px',
+ }}
+ />
+ <input
+ type="text"
+ value={String(value || '#FF8800')}
+ onChange={(e) => onChange(e.target.value)}
+ disabled={disabled}
+ placeholder="#FF8800"
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ flex: 1,
+ textTransform: 'uppercase',
+ }}
+ />
+ </div>
+ );
+
+ const renderDateTimeInput = () => (
+ <div style={{ display: 'flex', alignItems: 'stretch' }}>
+ <div style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${isFocused ? FINCEPT.ORANGE : FINCEPT.BORDER}`,
+ borderRight: 'none',
+ padding: '0 10px',
+ display: 'flex',
+ alignItems: 'center',
+ color: FINCEPT.ORANGE,
+ transition: 'all 0.15s ease',
+ }}>
+ <Calendar size={14} />
+ </div>
+ <input
+ type="datetime-local"
+ value={value ? new Date(value as string | number).toISOString().slice(0, 16) : ''}
+ onChange={(e) => onChange(new Date(e.target.value).toISOString())}
+ disabled={disabled}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ borderLeft: 'none',
+ flex: 1,
+ }}
+ />
+ </div>
+ );
+
+ const renderCodeInput = () => (
+ <textarea
+ value={String(value || '')}
+ onChange={(e) => onChange(e.target.value)}
+ disabled={disabled}
+ placeholder={parameter.placeholder || '// Enter code here'}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ color: FINCEPT.GREEN,
+ minHeight: '100px',
+ resize: 'vertical',
+ lineHeight: '1.5',
+ }}
+ />
+ );
+
+ const renderCollectionInput = () => (
+ <div style={{
+ backgroundColor: FINCEPT.INPUT_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ padding: '12px',
+ }}>
+ <div style={{
+ color: FINCEPT.CYAN,
+ fontSize: '12px',
+ fontWeight: 700,
+ marginBottom: '10px',
+ textTransform: 'uppercase',
+ }}>
+ COLLECTION (JSON)
+ </div>
+ <textarea
+ value={JSON.stringify(value, null, 2)}
+ onChange={(e) => {
+ try {
+ onChange(JSON.parse(e.target.value));
+ } catch {
+ // Invalid JSON
+ }
+ }}
+ disabled={disabled}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ minHeight: '80px',
+ resize: 'vertical',
+ fontSize: '12px',
+ }}
+ />
+ </div>
+ );
+
+ const renderFixedCollectionInput = () => (
+ <div style={{
+ backgroundColor: FINCEPT.INPUT_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ padding: '14px',
+ textAlign: 'center',
+ }}>
+ <Settings2 size={20} style={{ color: FINCEPT.MUTED, margin: '0 auto 10px' }} />
+ <div style={{
+ color: FINCEPT.GRAY,
+ fontSize: '12px',
+ textTransform: 'uppercase',
+ }}>
+ ADVANCED CONFIGURATION
+ </div>
+ <div style={{ color: FINCEPT.MUTED, fontSize: '11px', marginTop: '6px' }}>
+ Configure in advanced editor
+ </div>
+ </div>
+ );
+
+ const renderResourceLocatorInput = () => {
+ const resourceValue = (value as any) || { mode: 'id', value: '' };
+
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ <div style={{ position: 'relative' }}>
+ <select
+ value={resourceValue.mode || 'id'}
+ onChange={(e) => onChange({ ...resourceValue, mode: e.target.value })}
+ disabled={disabled}
+ style={{
+ ...inputBaseStyle,
+ appearance: 'none',
+ paddingRight: '28px',
+ cursor: 'pointer',
+ }}
+ >
+ <option value="id" style={{ backgroundColor: FINCEPT.DARK_BG }}>BY ID</option>
+ <option value="url" style={{ backgroundColor: FINCEPT.DARK_BG }}>BY URL</option>
+ <option value="list" style={{ backgroundColor: FINCEPT.DARK_BG }}>FROM LIST</option>
+ </select>
+ <ChevronDown
+ size={16}
+ style={{
+ position: 'absolute',
+ right: '12px',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ color: FINCEPT.ORANGE,
+ pointerEvents: 'none',
+ }}
+ />
+ </div>
+ <input
+ type="text"
+ value={resourceValue.value || ''}
+ onChange={(e) => onChange({ ...resourceValue, value: e.target.value })}
+ disabled={disabled}
+ placeholder={`Enter ${resourceValue.mode || 'ID'}...`}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => setIsFocused(false)}
+ style={{
+ ...inputBaseStyle,
+ ...getFocusStyle(),
+ }}
+ />
+ </div>
+ );
+ };
+
+ const getParameterIcon = () => {
+ const iconStyle = { color: FINCEPT.ORANGE };
+ switch (parameter.type) {
+ case 'string' as NodePropertyType:
+ return <Type size={14} style={iconStyle} />;
+ case 'number' as NodePropertyType:
+ return <Hash size={14} style={iconStyle} />;
+ case 'boolean' as NodePropertyType:
+ return <Check size={14} style={iconStyle} />;
+ case 'options' as NodePropertyType:
+ case 'multiOptions' as NodePropertyType:
+ return <List size={14} style={iconStyle} />;
+ case 'color' as NodePropertyType:
+ return <Palette size={14} style={iconStyle} />;
+ case 'dateTime' as NodePropertyType:
+ return <Calendar size={14} style={iconStyle} />;
+ case 'json' as NodePropertyType:
+ case 'code' as NodePropertyType:
+ return <Code2 size={14} style={iconStyle} />;
+ case 'collection' as NodePropertyType:
+ case 'fixedCollection' as NodePropertyType:
+ return <Settings2 size={14} style={iconStyle} />;
+ default:
+ return <Type size={14} style={iconStyle} />;
+ }
+ };
+
+ return (
+ <div style={{ marginBottom: '4px' }}>
+ {/* Parameter Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: '6px',
+ }}>
+ <div style={labelStyle}>
+ {getParameterIcon()}
+ <span>{parameter.displayName}</span>
+ {parameter.required && (
+ <span style={{ color: FINCEPT.RED, marginLeft: '2px' }}>*</span>
+ )}
+ </div>
+
+ {/* Expression Toggle */}
+ {parameter.noDataExpression !== true && (
+ <button
+ onClick={handleToggleExpression}
+ disabled={disabled}
+ style={{
+ padding: '4px 8px',
+ fontSize: '10px',
+ fontFamily: FINCEPT.FONT,
+ fontWeight: 600,
+ border: `1px solid ${isExpressionMode ? FINCEPT.YELLOW : FINCEPT.BORDER}`,
+ backgroundColor: isExpressionMode ? `${FINCEPT.YELLOW}20` : 'transparent',
+ color: isExpressionMode ? FINCEPT.YELLOW : FINCEPT.GRAY,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ textTransform: 'uppercase',
+ transition: 'all 0.15s ease',
+ }}
+ >
+ <Code2 size={12} />
+ {isExpressionMode ? 'EXPR' : 'FIXED'}
+ </button>
+ )}
+ </div>
+
+ {/* Parameter Description */}
+ {parameter.description && (
+ <div style={{
+ fontSize: '11px',
+ color: FINCEPT.MUTED,
+ marginBottom: '8px',
+ lineHeight: '1.5',
+ }}>
+ {parameter.description}
+ </div>
+ )}
+
+ {/* Parameter Input */}
+ {renderInput()}
+
+ {/* Expression Hint */}
+ {isExpressionMode && (
+ <div style={{
+ fontSize: '8px',
+ color: `${FINCEPT.YELLOW}90`,
+ marginTop: '4px',
+ fontFamily: FINCEPT.FONT,
+ }}>
+ SYNTAX: <code style={{ backgroundColor: FINCEPT.PANEL_BG, padding: '1px 4px' }}>{'{{$json.field}}'}</code>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default NodeParameterInput;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/OptimizationNode.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/OptimizationNode.tsx
new file mode 100644
index 000000000..29c128810
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/OptimizationNode.tsx
@@ -0,0 +1,501 @@
+/**
+ * Optimization Node
+ *
+ * ReactFlow node for running parameter optimization in workflows.
+ * Supports grid search and genetic algorithms.
+ */
+
+import React, { useState } from 'react';
+import { Handle, Position } from 'reactflow';
+import { Zap, Play, Settings, Check, AlertCircle, Loader, TrendingUp } from 'lucide-react';
+import { backtestingService } from '@/services/backtesting/BacktestingService';
+import { OptimizationRequest, OptimizationResult } from '@/services/backtesting/interfaces/types';
+
+interface OptimizationNodeProps {
+ data: {
+ label: string;
+ strategyCode?: string;
+ optimizationTarget: 'sharpe_ratio' | 'total_return' | 'sortino_ratio';
+ parameterRanges?: Record<string, { min: number; max: number; step: number }>;
+ method: 'grid' | 'genetic';
+ status: 'idle' | 'running' | 'completed' | 'error';
+ result?: OptimizationResult;
+ error?: string;
+ onConfigChange?: (config: any) => void;
+ onExecute?: () => Promise<void>;
+ };
+ selected: boolean;
+}
+
+const OptimizationNode: React.FC<OptimizationNodeProps> = ({ data, selected }) => {
+ const [showSettings, setShowSettings] = useState(false);
+ const [localConfig, setLocalConfig] = useState({
+ target: data.optimizationTarget || 'sharpe_ratio',
+ method: data.method || 'grid',
+ maxIterations: 100,
+ });
+
+ const [paramRanges, setParamRanges] = useState<Record<string, { min: number; max: number; step: number }>>(
+ data.parameterRanges || {
+ fast_period: { min: 10, max: 50, step: 5 },
+ slow_period: { min: 100, max: 200, step: 10 },
+ }
+ );
+
+ const handleSaveSettings = () => {
+ if (data.onConfigChange) {
+ data.onConfigChange({ ...localConfig, parameterRanges: paramRanges });
+ }
+ setShowSettings(false);
+ };
+
+ const handleRunOptimization = async () => {
+ if (data.onExecute) {
+ await data.onExecute();
+ }
+ };
+
+ const getStatusColor = () => {
+ switch (data.status) {
+ case 'running': return '#f59e0b';
+ case 'completed': return '#10b981';
+ case 'error': return '#ef4444';
+ default: return '#6b7280';
+ }
+ };
+
+ const getStatusIcon = () => {
+ switch (data.status) {
+ case 'running': return <Loader size={14} className="animate-spin" color="#f59e0b" />;
+ case 'completed': return <Check size={14} color="#10b981" />;
+ case 'error': return <AlertCircle size={14} color="#ef4444" />;
+ default: return <Zap size={14} color="#6b7280" />;
+ }
+ };
+
+ const formatBestParams = () => {
+ if (!data.result || !data.result.bestParameters) return null;
+ return Object.entries(data.result.bestParameters)
+ .map(([key, value]) => `${key}: ${value}`)
+ .join(', ');
+ };
+
+ const addParameterRange = () => {
+ const paramName = prompt('Parameter name:');
+ if (paramName) {
+ setParamRanges({
+ ...paramRanges,
+ [paramName]: { min: 0, max: 100, step: 1 },
+ });
+ }
+ };
+
+ return (
+ <div style={{
+ background: selected ? '#252525' : '#1a1a1a',
+ border: `2px solid ${selected ? '#f59e0b' : getStatusColor()}`,
+ borderRadius: '8px',
+ minWidth: '320px',
+ maxWidth: '450px',
+ fontFamily: 'Consolas, monospace',
+ boxShadow: selected ? `0 0 16px #f59e0b60` : '0 2px 8px rgba(0,0,0,0.3)',
+ position: 'relative'
+ }}>
+ {/* Input Handle - Strategy */}
+ <Handle
+ type="target"
+ position={Position.Left}
+ id="strategy"
+ style={{
+ background: '#8b5cf6',
+ width: '12px',
+ height: '12px',
+ border: '2px solid #1a1a1a',
+ top: '30%'
+ }}
+ />
+
+ {/* Output Handle - Best Parameters */}
+ <Handle
+ type="source"
+ position={Position.Right}
+ id="best_params"
+ style={{
+ background: '#f59e0b',
+ width: '12px',
+ height: '12px',
+ border: '2px solid #1a1a1a',
+ top: '30%'
+ }}
+ />
+
+ {/* Output Handle - All Results */}
+ <Handle
+ type="source"
+ position={Position.Right}
+ id="all_results"
+ style={{
+ background: '#10b981',
+ width: '12px',
+ height: '12px',
+ border: '2px solid #1a1a1a',
+ top: '60%'
+ }}
+ />
+
+ {/* Header */}
+ <div style={{
+ padding: '12px',
+ borderBottom: '1px solid #2a2a2a',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ background: 'linear-gradient(135deg, #1f1f1f 0%, #2a1f0f 100%)'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Zap size={16} color={getStatusColor()} />
+ <span style={{ color: '#e5e7eb', fontSize: '12px', fontWeight: 'bold' }}>
+ {data.label}
+ </span>
+ </div>
+ <div style={{ display: 'flex', gap: '6px' }}>
+ {getStatusIcon()}
+ <Settings
+ size={14}
+ color="#9ca3af"
+ style={{ cursor: 'pointer' }}
+ onClick={() => setShowSettings(!showSettings)}
+ />
+ </div>
+ </div>
+
+ {/* Settings Panel */}
+ {showSettings && (
+ <div style={{
+ padding: '12px',
+ borderBottom: '1px solid #2a2a2a',
+ background: '#1a1a1a',
+ maxHeight: '400px',
+ overflowY: 'auto'
+ }}>
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: '#9ca3af', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ Optimization Target
+ </label>
+ <select
+ value={localConfig.target}
+ onChange={(e) => setLocalConfig({ ...localConfig, target: e.target.value as any })}
+ style={{
+ width: '100%',
+ padding: '6px',
+ background: '#252525',
+ border: '1px solid #3a3a3a',
+ borderRadius: '4px',
+ color: '#e5e7eb',
+ fontSize: '10px'
+ }}
+ >
+ <option value="sharpe_ratio">Sharpe Ratio</option>
+ <option value="total_return">Total Return</option>
+ <option value="sortino_ratio">Sortino Ratio</option>
+ <option value="calmar_ratio">Calmar Ratio</option>
+ <option value="profit_factor">Profit Factor</option>
+ </select>
+ </div>
+
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: '#9ca3af', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ Method
+ </label>
+ <select
+ value={localConfig.method}
+ onChange={(e) => setLocalConfig({ ...localConfig, method: e.target.value as any })}
+ style={{
+ width: '100%',
+ padding: '6px',
+ background: '#252525',
+ border: '1px solid #3a3a3a',
+ borderRadius: '4px',
+ color: '#e5e7eb',
+ fontSize: '10px'
+ }}
+ >
+ <option value="grid">Grid Search</option>
+ <option value="genetic">Genetic Algorithm</option>
+ <option value="bayesian">Bayesian Optimization</option>
+ </select>
+ </div>
+
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: '#9ca3af', fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ Max Iterations
+ </label>
+ <input
+ type="number"
+ value={localConfig.maxIterations}
+ onChange={(e) => setLocalConfig({ ...localConfig, maxIterations: Number(e.target.value) })}
+ style={{
+ width: '100%',
+ padding: '6px',
+ background: '#252525',
+ border: '1px solid #3a3a3a',
+ borderRadius: '4px',
+ color: '#e5e7eb',
+ fontSize: '10px'
+ }}
+ />
+ </div>
+
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
+ <label style={{ color: '#9ca3af', fontSize: '10px' }}>
+ Parameter Ranges
+ </label>
+ <button
+ onClick={addParameterRange}
+ style={{
+ padding: '2px 6px',
+ background: '#3b82f6',
+ color: 'white',
+ border: 'none',
+ borderRadius: '3px',
+ fontSize: '9px',
+ cursor: 'pointer'
+ }}
+ >
+ + Add
+ </button>
+ </div>
+
+ {Object.entries(paramRanges).map(([param, range]) => (
+ <div key={param} style={{ marginBottom: '8px', padding: '8px', background: '#252525', borderRadius: '4px' }}>
+ <div style={{ fontSize: '10px', color: '#e5e7eb', marginBottom: '4px', fontWeight: 'bold' }}>
+ {param}
+ </div>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '4px' }}>
+ <div>
+ <label style={{ fontSize: '8px', color: '#6b7280' }}>Min</label>
+ <input
+ type="number"
+ value={range.min}
+ onChange={(e) => setParamRanges({
+ ...paramRanges,
+ [param]: { ...range, min: Number(e.target.value) }
+ })}
+ style={{
+ width: '100%',
+ padding: '4px',
+ background: '#1a1a1a',
+ border: '1px solid #3a3a3a',
+ borderRadius: '3px',
+ color: '#e5e7eb',
+ fontSize: '9px'
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ fontSize: '8px', color: '#6b7280' }}>Max</label>
+ <input
+ type="number"
+ value={range.max}
+ onChange={(e) => setParamRanges({
+ ...paramRanges,
+ [param]: { ...range, max: Number(e.target.value) }
+ })}
+ style={{
+ width: '100%',
+ padding: '4px',
+ background: '#1a1a1a',
+ border: '1px solid #3a3a3a',
+ borderRadius: '3px',
+ color: '#e5e7eb',
+ fontSize: '9px'
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ fontSize: '8px', color: '#6b7280' }}>Step</label>
+ <input
+ type="number"
+ value={range.step}
+ onChange={(e) => setParamRanges({
+ ...paramRanges,
+ [param]: { ...range, step: Number(e.target.value) }
+ })}
+ style={{
+ width: '100%',
+ padding: '4px',
+ background: '#1a1a1a',
+ border: '1px solid #3a3a3a',
+ borderRadius: '3px',
+ color: '#e5e7eb',
+ fontSize: '9px'
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+
+ <button
+ onClick={handleSaveSettings}
+ style={{
+ width: '100%',
+ padding: '6px',
+ background: '#f59e0b',
+ color: 'white',
+ border: 'none',
+ borderRadius: '4px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ fontWeight: 'bold'
+ }}
+ >
+ Save Configuration
+ </button>
+ </div>
+ )}
+
+ {/* Content */}
+ <div style={{ padding: '12px' }}>
+ {/* Configuration Display */}
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ fontSize: '10px', color: '#9ca3af', marginBottom: '6px' }}>
+ Configuration:
+ </div>
+ <div style={{ fontSize: '9px', color: '#d1d5db', fontFamily: 'monospace' }}>
+ Target: {localConfig.target.replace('_', ' ')}
+ </div>
+ <div style={{ fontSize: '9px', color: '#d1d5db', fontFamily: 'monospace' }}>
+ Method: {localConfig.method}
+ </div>
+ <div style={{ fontSize: '9px', color: '#d1d5db', fontFamily: 'monospace' }}>
+ Parameters: {Object.keys(paramRanges).length}
+ </div>
+ </div>
+
+ {/* Results Display */}
+ {data.result && data.status === 'completed' && (
+ <div style={{
+ padding: '8px',
+ background: '#1f1f1f',
+ borderRadius: '4px',
+ marginBottom: '8px'
+ }}>
+ <div style={{ fontSize: '10px', color: '#9ca3af', marginBottom: '6px', display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <TrendingUp size={12} />
+ Best Parameters:
+ </div>
+ <div style={{ fontSize: '9px', color: '#10b981', fontFamily: 'monospace', marginBottom: '6px' }}>
+ {formatBestParams()}
+ </div>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px', fontSize: '9px' }}>
+ <div>
+ <div style={{ color: '#6b7280' }}>Iterations</div>
+ <div style={{ color: '#e5e7eb', fontWeight: 'bold' }}>
+ {data.result.iterations}
+ </div>
+ </div>
+ <div>
+ <div style={{ color: '#6b7280' }}>Duration</div>
+ <div style={{ color: '#e5e7eb', fontWeight: 'bold' }}>
+ {Math.round(data.result.duration / 1000)}s
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Error Display */}
+ {data.error && data.status === 'error' && (
+ <div style={{
+ padding: '8px',
+ background: '#3a0a0a',
+ border: '1px solid #ef4444',
+ borderRadius: '4px',
+ marginBottom: '8px'
+ }}>
+ <div style={{ fontSize: '10px', color: '#ef4444', marginBottom: '4px' }}>
+ Error:
+ </div>
+ <div style={{ fontSize: '9px', color: '#fca5a5' }}>
+ {data.error}
+ </div>
+ </div>
+ )}
+
+ {/* Run Button */}
+ <button
+ onClick={handleRunOptimization}
+ disabled={data.status === 'running' || !data.strategyCode}
+ style={{
+ width: '100%',
+ padding: '8px',
+ background: data.status === 'running' ? '#6b7280' : '#f59e0b',
+ color: 'white',
+ border: 'none',
+ borderRadius: '4px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: data.status === 'running' || !data.strategyCode ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '6px',
+ opacity: data.status === 'running' || !data.strategyCode ? 0.6 : 1
+ }}
+ >
+ {data.status === 'running' ? (
+ <>
+ <Loader size={14} className="animate-spin" />
+ Optimizing... ({data.result?.iterations || 0}/{localConfig.maxIterations})
+ </>
+ ) : (
+ <>
+ <Play size={14} />
+ Run Optimization
+ </>
+ )}
+ </button>
+ </div>
+
+ {/* Handle Labels */}
+ <div style={{
+ position: 'absolute',
+ left: '-60px',
+ top: '30%',
+ transform: 'translateY(-50%)',
+ fontSize: '9px',
+ color: '#6b7280',
+ whiteSpace: 'nowrap'
+ }}>
+ Strategy
+ </div>
+ <div style={{
+ position: 'absolute',
+ right: '-80px',
+ top: '30%',
+ transform: 'translateY(-50%)',
+ fontSize: '9px',
+ color: '#6b7280',
+ whiteSpace: 'nowrap'
+ }}>
+ Best Params
+ </div>
+ <div style={{
+ position: 'absolute',
+ right: '-70px',
+ top: '60%',
+ transform: 'translateY(-50%)',
+ fontSize: '9px',
+ color: '#6b7280',
+ whiteSpace: 'nowrap'
+ }}>
+ All Results
+ </div>
+ </div>
+ );
+};
+
+export default OptimizationNode;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/PythonAgentNode.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/PythonAgentNode.tsx
new file mode 100644
index 000000000..e7308907d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/PythonAgentNode.tsx
@@ -0,0 +1,487 @@
+// PythonAgentNode.tsx - Visual node for Python agents in Node Editor
+import React, { useState, useEffect } from 'react';
+import { Handle, Position } from 'reactflow';
+import { Play, Settings, CheckCircle, AlertCircle, Loader, TrendingUp, Brain } from 'lucide-react';
+import { sqliteService, LLMConfig, LLMModelConfig } from '@/services/core/sqliteService';
+
+// Combined LLM option for display
+interface LLMOption {
+ id: string;
+ provider: string;
+ model: string;
+ displayName: string;
+ type: 'provider' | 'model' | 'fincept';
+ isActive?: boolean;
+}
+
+interface PythonAgentNodeProps {
+ id: string;
+ data: {
+ agentType: string;
+ agentCategory: string;
+ label: string;
+ icon: string;
+ color: string;
+ parameters: Record<string, any>;
+ selectedLLM?: string; // Which LLM provider to use for this agent
+ status: 'idle' | 'running' | 'completed' | 'error';
+ result?: any;
+ error?: string;
+ onExecute?: (nodeId: string) => void;
+ onParameterChange?: (params: Record<string, any>) => void;
+ onLLMChange?: (provider: string) => void;
+ };
+ selected: boolean;
+}
+
+const PythonAgentNode: React.FC<PythonAgentNodeProps> = ({ id, data, selected }) => {
+ const [showSettings, setShowSettings] = useState(false);
+ const [availableLLMs, setAvailableLLMs] = useState<LLMOption[]>([]);
+ const [selectedLLM, setSelectedLLM] = useState(data.selectedLLM || 'active');
+
+ // Load available LLM providers from Settings (both LLMConfig and LLMModelConfig)
+ useEffect(() => {
+ const loadLLMs = async () => {
+ try {
+ const options: LLMOption[] = [];
+
+ // Load provider-level configs (LLMConfig)
+ const providerConfigs = await sqliteService.getLLMConfigs();
+ for (const config of providerConfigs) {
+ // Fincept is special - always show it prominently
+ if (config.provider === 'fincept') {
+ options.unshift({
+ id: 'fincept',
+ provider: 'fincept',
+ model: config.model || 'fincept-llm',
+ displayName: 'FINCEPT (Pre-configured)',
+ type: 'fincept',
+ isActive: config.is_active
+ });
+ } else {
+ options.push({
+ id: config.provider,
+ provider: config.provider,
+ model: config.model,
+ displayName: `${config.provider.toUpperCase()} - ${config.model}`,
+ type: 'provider',
+ isActive: config.is_active
+ });
+ }
+ }
+
+ // Load custom model configs (LLMModelConfig) from Settings
+ const modelConfigs = await sqliteService.getLLMModelConfigs();
+ for (const model of modelConfigs) {
+ if (model.is_enabled) {
+ options.push({
+ id: model.id,
+ provider: model.provider,
+ model: model.model_id,
+ displayName: `${model.display_name} (${model.provider.toUpperCase()})`,
+ type: 'model',
+ isActive: model.is_default
+ });
+ }
+ }
+
+ // If Fincept wasn't in provider configs, add it as default
+ if (!options.find(o => o.provider === 'fincept')) {
+ options.unshift({
+ id: 'fincept',
+ provider: 'fincept',
+ model: 'fincept-llm',
+ displayName: 'FINCEPT (Pre-configured)',
+ type: 'fincept',
+ isActive: true
+ });
+ }
+
+ setAvailableLLMs(options);
+ } catch (error) {
+ console.error('Failed to load LLM configs:', error);
+ // Default to Fincept if loading fails
+ setAvailableLLMs([{
+ id: 'fincept',
+ provider: 'fincept',
+ model: 'fincept-llm',
+ displayName: 'FINCEPT (Pre-configured)',
+ type: 'fincept',
+ isActive: true
+ }]);
+ }
+ };
+ loadLLMs();
+ }, []);
+
+ // Fincept colors
+ const ORANGE = '#FFA500';
+ const WHITE = '#FFFFFF';
+ const GRAY = '#787878';
+ const DARK_BG = '#0a0a0a';
+ const PANEL_BG = '#1a1a1a';
+ const BORDER = '#2d2d2d';
+ const GREEN = '#10b981';
+ const RED = '#ef4444';
+
+ const getStatusColor = () => {
+ switch (data.status) {
+ case 'running': return ORANGE;
+ case 'completed': return GREEN;
+ case 'error': return RED;
+ default: return GRAY;
+ }
+ };
+
+ const getStatusIcon = () => {
+ switch (data.status) {
+ case 'running': return <Loader size={14} className="animate-spin" color={ORANGE} />;
+ case 'completed': return <CheckCircle size={14} color={GREEN} />;
+ case 'error': return <AlertCircle size={14} color={RED} />;
+ default: return <TrendingUp size={14} color={GRAY} />;
+ }
+ };
+
+ return (
+ <div style={{
+ backgroundColor: PANEL_BG,
+ border: `2px solid ${selected ? ORANGE : getStatusColor()}`,
+ borderRadius: '8px',
+ padding: '12px',
+ minWidth: '250px',
+ maxWidth: '320px',
+ fontFamily: 'Consolas, monospace',
+ boxShadow: selected ? `0 0 16px ${ORANGE}60` : `0 2px 8px rgba(0,0,0,0.3)`
+ }}>
+ {/* Input Handle */}
+ <Handle
+ type="target"
+ position={Position.Left}
+ style={{
+ background: data.color,
+ width: '12px',
+ height: '12px',
+ border: `2px solid ${DARK_BG}`,
+ left: '-6px'
+ }}
+ />
+
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '10px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${BORDER}`
+ }}>
+ <span style={{ fontSize: '20px' }}>{data.icon}</span>
+ <div style={{ flex: 1 }}>
+ <div style={{
+ color: WHITE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ marginBottom: '2px'
+ }}>
+ {data.label}
+ </div>
+ <div style={{
+ color: GRAY,
+ fontSize: '9px',
+ textTransform: 'uppercase'
+ }}>
+ {data.agentCategory}
+ </div>
+ </div>
+ {getStatusIcon()}
+ </div>
+
+ {/* Parameters Summary */}
+ {Object.keys(data.parameters).length > 0 && (
+ <div style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${BORDER}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ PARAMETERS
+ </div>
+ {Object.entries(data.parameters).slice(0, 2).map(([key, value]) => (
+ <div key={key} style={{
+ color: GRAY,
+ fontSize: '8px',
+ marginBottom: '2px',
+ display: 'flex',
+ justifyContent: 'space-between'
+ }}>
+ <span>{key}:</span>
+ <span style={{ color: WHITE }}>
+ {Array.isArray(value) ? value.join(', ') : String(value).substring(0, 20)}
+ </span>
+ </div>
+ ))}
+ {Object.keys(data.parameters).length > 2 && (
+ <div style={{ color: GRAY, fontSize: '8px', fontStyle: 'italic' }}>
+ +{Object.keys(data.parameters).length - 2} more...
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Result Preview */}
+ {data.status === 'completed' && data.result && (
+ <div style={{
+ backgroundColor: `${GREEN}15`,
+ border: `1px solid ${GREEN}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: GREEN,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}>
+ <CheckCircle size={10} />
+ RESULT
+ </div>
+ <div style={{
+ color: WHITE,
+ fontSize: '8px',
+ fontFamily: 'monospace',
+ maxHeight: '60px',
+ overflow: 'auto'
+ }}>
+ {JSON.stringify(data.result, null, 2).substring(0, 100)}...
+ </div>
+ </div>
+ )}
+
+ {/* Error Display */}
+ {data.status === 'error' && data.error && (
+ <div style={{
+ backgroundColor: `${RED}15`,
+ border: `1px solid ${RED}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: RED,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}>
+ <AlertCircle size={10} />
+ ERROR
+ </div>
+ <div style={{
+ color: RED,
+ fontSize: '8px',
+ wordBreak: 'break-word'
+ }}>
+ {data.error}
+ </div>
+ </div>
+ )}
+
+ {/* LLM Display - Always visible, clickable to configure */}
+ <div
+ onClick={() => setShowSettings(!showSettings)}
+ style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${showSettings ? ORANGE : BORDER}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px',
+ cursor: 'pointer',
+ transition: 'border-color 0.2s'
+ }}
+ >
+ <div style={{
+ color: GRAY,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: '4px'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <Brain size={10} />
+ LLM
+ </div>
+ <Settings size={10} color={showSettings ? ORANGE : GRAY} />
+ </div>
+ <div style={{
+ color: WHITE,
+ fontSize: '8px'
+ }}>
+ {selectedLLM === 'active'
+ ? 'Active Provider'
+ : (availableLLMs.find(l => l.id === selectedLLM)?.displayName || selectedLLM.toUpperCase())
+ }
+ </div>
+ </div>
+
+ {/* LLM Selection Panel */}
+ {showSettings && (
+ <div style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${ORANGE}`,
+ borderRadius: '4px',
+ padding: '8px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '10px',
+ fontWeight: 'bold',
+ marginBottom: '8px'
+ }}>
+ LLM CONFIGURATION
+ </div>
+
+ <div style={{ marginBottom: '8px' }}>
+ <label style={{
+ color: GRAY,
+ fontSize: '8px',
+ display: 'block',
+ marginBottom: '4px'
+ }}>
+ LLM Provider for Analysis
+ </label>
+ <select
+ value={selectedLLM}
+ onChange={(e) => {
+ setSelectedLLM(e.target.value);
+ data.onLLMChange?.(e.target.value);
+ }}
+ style={{
+ width: '100%',
+ backgroundColor: PANEL_BG,
+ border: `1px solid ${BORDER}`,
+ color: WHITE,
+ padding: '6px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ >
+ <option value="active">Use Active Provider (from Settings)</option>
+ {availableLLMs.map(llm => (
+ <option key={llm.id} value={llm.id} style={{
+ backgroundColor: llm.type === 'fincept' ? '#1a3a1a' : undefined
+ }}>
+ {llm.displayName}{llm.isActive ? ' ✓' : ''}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowSettings(false);
+ }}
+ style={{
+ width: '100%',
+ backgroundColor: ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '6px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '3px'
+ }}
+ >
+ CLOSE
+ </button>
+ </div>
+ )}
+
+ {/* Action Buttons */}
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <button
+ onClick={() => data.onExecute?.(id)}
+ disabled={data.status === 'running'}
+ style={{
+ flex: 1,
+ backgroundColor: data.status === 'running' ? GRAY : data.color,
+ color: 'black',
+ border: 'none',
+ padding: '8px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: data.status === 'running' ? 'not-allowed' : 'pointer',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ opacity: data.status === 'running' ? 0.6 : 1
+ }}
+ >
+ {data.status === 'running' ? (
+ <>
+ <Loader size={12} className="animate-spin" />
+ RUNNING...
+ </>
+ ) : (
+ <>
+ <Play size={12} />
+ EXECUTE
+ </>
+ )}
+ </button>
+ <button
+ onClick={() => setShowSettings(!showSettings)}
+ style={{
+ backgroundColor: showSettings ? ORANGE : DARK_BG,
+ border: `1px solid ${BORDER}`,
+ color: showSettings ? 'black' : GRAY,
+ padding: '8px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center'
+ }}
+ >
+ <Settings size={14} />
+ </button>
+ </div>
+
+ {/* Output Handle */}
+ <Handle
+ type="source"
+ position={Position.Right}
+ style={{
+ background: data.status === 'completed' ? GREEN : data.color,
+ width: '12px',
+ height: '12px',
+ border: `2px solid ${DARK_BG}`,
+ right: '-6px'
+ }}
+ />
+ </div>
+ );
+};
+
+export default PythonAgentNode;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/ResultsDisplayNode.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/ResultsDisplayNode.tsx
new file mode 100644
index 000000000..3ba333dff
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/ResultsDisplayNode.tsx
@@ -0,0 +1,465 @@
+// ResultsDisplayNode.tsx - Display results from previous nodes
+import React, { useState } from 'react';
+import { Handle, Position } from 'reactflow';
+import { Eye, EyeOff, Copy, Check } from 'lucide-react';
+
+interface ResultsDisplayNodeProps {
+ data: {
+ label: string;
+ inputData?: any;
+ color: string;
+ };
+ selected: boolean;
+}
+
+const ResultsDisplayNode: React.FC<ResultsDisplayNodeProps> = ({ data, selected }) => {
+ const [expanded, setExpanded] = useState(true);
+ const [copied, setCopied] = useState(false);
+ const [width, setWidth] = useState(500);
+ const [height, setHeight] = useState(400);
+
+ // Debug logging
+ console.log('[ResultsDisplayNode] Rendering with data:', data);
+ console.log('[ResultsDisplayNode] inputData present:', !!data.inputData);
+ console.log('[ResultsDisplayNode] inputData value:', data.inputData);
+
+ // Fincept colors
+ const ORANGE = '#FFA500';
+ const WHITE = '#FFFFFF';
+ const GRAY = '#787878';
+ const DARK_BG = '#0a0a0a';
+ const PANEL_BG = '#1a1a1a';
+ const BORDER = '#2d2d2d';
+
+ const handleCopy = () => {
+ if (data.inputData) {
+ navigator.clipboard.writeText(JSON.stringify(data.inputData, null, 2));
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ }
+ };
+
+ const formatValue = (value: any): string => {
+ if (value === null || value === undefined) return 'null';
+ if (typeof value === 'object') {
+ return JSON.stringify(value, null, 2);
+ }
+ return String(value);
+ };
+
+ const renderMarkdown = (text: string) => {
+ const lines = text.split('\n');
+ const elements: React.ReactElement[] = [];
+ let inTable = false;
+
+ lines.forEach((line, i) => {
+ let style: React.CSSProperties = {
+ color: WHITE,
+ fontSize: '10px',
+ lineHeight: '1.7',
+ marginBottom: '3px',
+ fontFamily: 'Consolas, monospace'
+ };
+
+ // Skip markdown separators
+ if (line.trim() === '---' || line.trim() === '***' || /^-{3,}$/.test(line.trim())) {
+ elements.push(
+ <div key={i} style={{
+ borderTop: `1px solid ${BORDER}`,
+ margin: '12px 0',
+ opacity: 0.5
+ }} />
+ );
+ return;
+ }
+
+ // Headers
+ if (line.startsWith('###')) {
+ style = {
+ color: '#10b981',
+ fontWeight: 'bold',
+ fontSize: '11px',
+ marginTop: '12px',
+ marginBottom: '6px',
+ borderBottom: `1px solid ${BORDER}`,
+ paddingBottom: '4px'
+ };
+ line = line.replace(/^###\s*/, '');
+ } else if (line.startsWith('##')) {
+ style = {
+ color: ORANGE,
+ fontWeight: 'bold',
+ fontSize: '13px',
+ marginTop: '16px',
+ marginBottom: '8px',
+ borderBottom: `2px solid ${ORANGE}40`,
+ paddingBottom: '6px'
+ };
+ line = line.replace(/^##\s*/, '');
+ } else if (line.startsWith('#')) {
+ style = {
+ color: ORANGE,
+ fontWeight: 'bold',
+ fontSize: '14px',
+ marginTop: '16px',
+ marginBottom: '8px'
+ };
+ line = line.replace(/^#\s*/, '');
+ }
+ // Table detection
+ else if (line.startsWith('|')) {
+ inTable = true;
+ const cells = line.split('|').map(c => c.trim()).filter(c => c);
+
+ // Check if it's a separator row
+ if (cells.every(c => /^[-:]+$/.test(c))) {
+ return; // Skip separator rows
+ }
+
+ // Render table row
+ elements.push(
+ <div key={i} style={{
+ display: 'flex',
+ gap: '8px',
+ padding: '4px 0',
+ borderBottom: `1px solid ${BORDER}30`,
+ fontFamily: 'Consolas, monospace',
+ fontSize: '9px'
+ }}>
+ {cells.map((cell, cellIdx) => (
+ <div
+ key={cellIdx}
+ style={{
+ flex: cellIdx === 0 ? '0 0 150px' : '1',
+ color: cellIdx === 0 ? ORANGE : '#d4d4d4',
+ fontWeight: cellIdx === 0 ? 'bold' : 'normal',
+ padding: '2px 6px',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis'
+ }}
+ >
+ {cell.replace(/\*\*/g, '')}
+ </div>
+ ))}
+ </div>
+ );
+ return;
+ }
+ // Bullet points
+ else if (line.startsWith('- ') || line.startsWith('• ')) {
+ style = {
+ ...style,
+ marginLeft: '16px',
+ color: '#d4d4d4',
+ display: 'flex',
+ alignItems: 'flex-start'
+ };
+ const content = line.replace(/^[-•]\s*/, '');
+ elements.push(
+ <div key={i} style={style}>
+ <span style={{ color: '#10b981', marginRight: '8px' }}>•</span>
+ <span>{content.replace(/\*\*/g, '')}</span>
+ </div>
+ );
+ return;
+ }
+ // Numbered lists
+ else if (/^\d+\.\s/.test(line)) {
+ style = {
+ ...style,
+ marginLeft: '16px',
+ color: '#d4d4d4'
+ };
+ line = line.replace(/\*\*/g, '');
+ }
+ // Bold text inline
+ else if (line.includes('**')) {
+ const parts = line.split(/\*\*([^*]+)\*\*/g);
+ elements.push(
+ <div key={i} style={style}>
+ {parts.map((part, idx) =>
+ idx % 2 === 1 ? (
+ <span key={idx} style={{ color: '#10b981', fontWeight: 'bold' }}>
+ {part}
+ </span>
+ ) : (
+ <span key={idx}>{part}</span>
+ )
+ )}
+ </div>
+ );
+ return;
+ }
+ // Italic text in parentheses
+ else if (line.startsWith('*(') || line.startsWith('*')) {
+ style = { ...style, color: GRAY, fontStyle: 'italic', fontSize: '9px' };
+ line = line.replace(/^\*\(/, '(').replace(/\)$/, ')').replace(/^\*/, '').replace(/\*$/, '');
+ }
+ // Empty lines
+ else if (line.trim() === '') {
+ elements.push(<div key={i} style={{ height: '8px' }} />);
+ return;
+ }
+
+ elements.push(<div key={i} style={style}>{line || '\u00A0'}</div>);
+ });
+
+ return <>{elements}</>;
+ };
+
+ const renderData = (obj: any, depth = 0) => {
+ if (!obj || typeof obj !== 'object') {
+ const strValue = formatValue(obj);
+ // Check if it looks like markdown text (has headers, tables, etc)
+ if (typeof obj === 'string' && (obj.includes('##') || obj.includes('|') || obj.length > 200)) {
+ return (
+ <div style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${BORDER}`,
+ borderRadius: '4px',
+ padding: '8px',
+ marginTop: '4px'
+ }}>
+ {renderMarkdown(obj)}
+ </div>
+ );
+ }
+ return (
+ <div style={{ color: WHITE, fontSize: '10px', fontFamily: 'monospace', whiteSpace: 'pre-wrap' }}>
+ {strValue}
+ </div>
+ );
+ }
+
+ return (
+ <div style={{ marginLeft: depth > 0 ? '12px' : '0' }}>
+ {Object.entries(obj).map(([key, value]) => (
+ <div key={key} style={{ marginBottom: '8px' }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '10px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ textTransform: 'uppercase',
+ letterSpacing: '0.5px'
+ }}>
+ {key.replace(/_/g, ' ')}:
+ </div>
+ {typeof value === 'object' && value !== null ? (
+ Array.isArray(value) ? (
+ <div style={{
+ color: '#10b981',
+ fontSize: '9px',
+ marginLeft: '8px',
+ fontFamily: 'monospace'
+ }}>
+ {value.map((item, i) => (
+ <div key={i} style={{ marginBottom: '2px' }}>• {item}</div>
+ ))}
+ </div>
+ ) : (
+ renderData(value, depth + 1)
+ )
+ ) : (
+ typeof value === 'string' && (value.includes('##') || value.includes('|') || value.length > 200) ? (
+ <div style={{
+ backgroundColor: '#0f0f0f',
+ border: `1px solid ${BORDER}`,
+ borderRadius: '4px',
+ padding: '8px',
+ marginLeft: '8px',
+ marginTop: '4px'
+ }}>
+ {renderMarkdown(value)}
+ </div>
+ ) : (
+ <div style={{
+ color: WHITE,
+ fontSize: '10px',
+ fontFamily: 'monospace',
+ marginLeft: '8px',
+ whiteSpace: 'pre-wrap',
+ wordBreak: 'break-word'
+ }}>
+ {formatValue(value)}
+ </div>
+ )
+ )}
+ </div>
+ ))}
+ </div>
+ );
+ };
+
+ return (
+ <div style={{
+ backgroundColor: PANEL_BG,
+ border: `2px solid ${selected ? ORANGE : data.color}`,
+ borderRadius: '8px',
+ padding: '12px',
+ width: `${width}px`,
+ fontFamily: 'Consolas, monospace',
+ boxShadow: selected ? `0 0 16px ${ORANGE}60` : `0 2px 8px rgba(0,0,0,0.3)`,
+ position: 'relative'
+ }}>
+ {/* Input Handle */}
+ <Handle
+ type="target"
+ position={Position.Left}
+ style={{
+ background: data.color,
+ width: '12px',
+ height: '12px',
+ border: `2px solid ${DARK_BG}`,
+ left: '-6px'
+ }}
+ />
+
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ marginBottom: '10px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${BORDER}`
+ }}>
+ <div style={{
+ color: WHITE,
+ fontSize: '12px',
+ fontWeight: 'bold'
+ }}>
+ 📊 {data.label}
+ </div>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ <button
+ onClick={() => setExpanded(!expanded)}
+ style={{
+ backgroundColor: 'transparent',
+ border: `1px solid ${BORDER}`,
+ color: GRAY,
+ padding: '4px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center'
+ }}
+ title={expanded ? 'Collapse' : 'Expand'}
+ >
+ {expanded ? <EyeOff size={12} /> : <Eye size={12} />}
+ </button>
+ <button
+ onClick={handleCopy}
+ disabled={!data.inputData}
+ style={{
+ backgroundColor: 'transparent',
+ border: `1px solid ${BORDER}`,
+ color: copied ? '#10b981' : GRAY,
+ padding: '4px',
+ cursor: data.inputData ? 'pointer' : 'not-allowed',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ opacity: data.inputData ? 1 : 0.5
+ }}
+ title="Copy to clipboard"
+ >
+ {copied ? <Check size={12} /> : <Copy size={12} />}
+ </button>
+ </div>
+ </div>
+
+ {/* Results Display */}
+ {expanded && (
+ <div
+ onWheel={(e) => e.stopPropagation()}
+ onMouseDown={(e) => e.stopPropagation()}
+ style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${BORDER}`,
+ borderRadius: '4px',
+ padding: '10px',
+ maxHeight: `${height}px`,
+ overflow: 'auto'
+ }}>
+ {data.inputData ? (
+ renderData(data.inputData)
+ ) : (
+ <div style={{
+ color: GRAY,
+ fontSize: '10px',
+ fontStyle: 'italic',
+ textAlign: 'center',
+ padding: '20px'
+ }}>
+ No data received yet.
+ <br />
+ Connect this node to an output to see results.
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Resize Handle */}
+ <div
+ onMouseDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const startWidth = width;
+ const startHeight = height;
+
+ const handleMouseMove = (moveEvent: MouseEvent) => {
+ moveEvent.preventDefault();
+ const deltaX = moveEvent.clientX - startX;
+ const deltaY = moveEvent.clientY - startY;
+ setWidth(Math.max(300, startWidth + deltaX));
+ setHeight(Math.max(200, startHeight + deltaY));
+ };
+
+ const handleMouseUp = () => {
+ document.removeEventListener('mousemove', handleMouseMove);
+ document.removeEventListener('mouseup', handleMouseUp);
+ };
+
+ document.addEventListener('mousemove', handleMouseMove);
+ document.addEventListener('mouseup', handleMouseUp);
+ }}
+ style={{
+ position: 'absolute',
+ bottom: '4px',
+ right: '4px',
+ width: '24px',
+ height: '24px',
+ cursor: 'nwse-resize',
+ backgroundColor: DARK_BG,
+ border: `2px solid ${BORDER}`,
+ borderBottomRightRadius: '6px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontSize: '16px',
+ color: GRAY,
+ transition: 'all 0.2s',
+ zIndex: 10
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = ORANGE;
+ e.currentTarget.style.color = 'white';
+ e.currentTarget.style.borderColor = ORANGE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = DARK_BG;
+ e.currentTarget.style.color = GRAY;
+ e.currentTarget.style.borderColor = BORDER;
+ }}
+ title="Drag to resize"
+ >
+ ⇲
+ </div>
+ </div>
+ );
+};
+
+export default ResultsDisplayNode;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/ResultsModal.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/ResultsModal.tsx
new file mode 100644
index 000000000..60c2aec5c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/ResultsModal.tsx
@@ -0,0 +1,63 @@
+import React from 'react';
+import { X } from 'lucide-react';
+
+interface ResultsModalProps {
+ data: any;
+ workflowName: string;
+ onClose: () => void;
+}
+
+const ResultsModal: React.FC<ResultsModalProps> = ({ data, workflowName, onClose }) => {
+ return (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0, 0, 0, 0.8)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 9999
+ }} onClick={onClose}>
+ <div style={{
+ background: '#1a1a1a',
+ border: '1px solid #2d2d2d',
+ borderRadius: '8px',
+ padding: '20px',
+ maxWidth: '600px',
+ width: '90%'
+ }} onClick={(e) => e.stopPropagation()}>
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '16px'
+ }}>
+ <h3 style={{ color: '#ea580c' }}>{workflowName} - Results</h3>
+ <button onClick={onClose} style={{
+ background: 'transparent',
+ border: 'none',
+ color: '#a3a3a3',
+ cursor: 'pointer'
+ }}>
+ <X size={20} />
+ </button>
+ </div>
+ <pre style={{
+ background: '#0a0a0a',
+ padding: '12px',
+ borderRadius: '4px',
+ overflow: 'auto',
+ maxHeight: '400px',
+ color: '#a3a3a3'
+ }}>
+ {JSON.stringify(data, null, 2)}
+ </pre>
+ </div>
+ </div>
+ );
+};
+
+export default ResultsModal;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/SystemNode.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/SystemNode.tsx
new file mode 100644
index 000000000..c17680cb9
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/SystemNode.tsx
@@ -0,0 +1,227 @@
+/**
+ * System Node Component for ReactFlow
+ *
+ * React component for rendering nodes from the n8n-inspired node system.
+ * Works with the NodeRegistry and displays nodes with their properties.
+ *
+ * Features:
+ * - Dynamic styling based on node type
+ * - Execution status indicators
+ * - Error display
+ * - Disabled state visualization
+ * - Input/output handles
+ * - Node configuration on click
+ */
+
+import React, { useMemo } from 'react';
+import { Handle, Position, NodeProps } from 'reactflow';
+import type { INode, INodeType } from '@/services/nodeSystem';
+import { NodeRegistry } from '@/services/nodeSystem';
+import {
+ Settings,
+ Play,
+ CheckCircle,
+ XCircle,
+ Clock,
+ AlertCircle,
+ Zap,
+} from 'lucide-react';
+
+export interface SystemNodeData {
+ node: INode;
+ onConfigure?: (node: INode) => void;
+ onExecute?: (node: INode) => void;
+ executionStatus?: 'idle' | 'running' | 'success' | 'error';
+ executionTime?: number;
+ error?: string;
+}
+
+export const SystemNode: React.FC<NodeProps<SystemNodeData>> = ({
+ data,
+ selected,
+}) => {
+ const node = data.node;
+
+ // Get node type definition
+ const nodeType = useMemo<INodeType | null>(() => {
+ try {
+ return NodeRegistry.getNodeType(node.type, node.typeVersion);
+ } catch (error) {
+ console.error('Failed to get node type:', error);
+ return null;
+ }
+ }, [node.type, node.typeVersion]);
+
+ // Node color
+ const nodeColor = nodeType?.description?.defaults?.color || '#888888';
+
+ // Execution status icon
+ const getStatusIcon = () => {
+ switch (data.executionStatus) {
+ case 'running':
+ return <Clock size={14} className="text-blue-400 animate-pulse" />;
+ case 'success':
+ return <CheckCircle size={14} className="text-green-400" />;
+ case 'error':
+ return <XCircle size={14} className="text-red-400" />;
+ default:
+ return null;
+ }
+ };
+
+ // Node icon or first letter
+ const getNodeIcon = () => {
+ if (nodeType?.description?.icon) {
+ // In a real implementation, you'd load the actual icon
+ return <Zap size={16} style={{ color: nodeColor }} />;
+ }
+
+ const displayName = nodeType?.description?.displayName || node.type;
+ return (
+ <div
+ className="w-6 h-6 rounded flex items-center justify-center text-xs font-bold"
+ style={{
+ background: `${nodeColor}30`,
+ color: nodeColor,
+ }}
+ >
+ {displayName[0].toUpperCase()}
+ </div>
+ );
+ };
+
+ if (!nodeType) {
+ return (
+ <div className="px-4 py-3 bg-red-900/20 border-2 border-red-500 rounded-lg min-w-[200px]">
+ <div className="flex items-center gap-2 text-red-400">
+ <AlertCircle size={16} />
+ <span className="text-sm font-medium">Unknown Node Type</span>
+ </div>
+ <div className="text-xs text-red-400/70 mt-1">{node.type}</div>
+ </div>
+ );
+ }
+
+ return (
+ <div
+ className={`relative bg-gray-900 rounded-lg min-w-[220px] transition-all ${
+ selected ? 'ring-2 ring-blue-500 shadow-lg shadow-blue-500/20' : 'shadow-md'
+ } ${node.disabled ? 'opacity-50' : ''}`}
+ style={{
+ borderLeft: `4px solid ${nodeColor}`,
+ }}
+ >
+ {/* Input Handle */}
+ <Handle
+ type="target"
+ position={Position.Left}
+ className="w-3 h-3 !bg-gray-700 !border-2 !border-gray-900"
+ style={{
+ left: -6,
+ }}
+ />
+
+ {/* Node Header */}
+ <div
+ className="px-3 py-2 border-b border-gray-800 flex items-center justify-between gap-2"
+ style={{
+ background: `${nodeColor}10`,
+ }}
+ >
+ <div className="flex items-center gap-2 flex-1 min-w-0">
+ {getNodeIcon()}
+ <div className="flex-1 min-w-0">
+ <div className="text-sm font-medium text-gray-200 truncate">
+ {nodeType.description.displayName}
+ </div>
+ {node.name !== nodeType.description.displayName && (
+ <div className="text-xs text-gray-500 truncate">{node.name}</div>
+ )}
+ </div>
+ </div>
+
+ {/* Status Icon */}
+ {getStatusIcon()}
+ </div>
+
+ {/* Node Body */}
+ <div className="px-3 py-2 space-y-1">
+ {/* Execution Time */}
+ {data.executionTime !== undefined && (
+ <div className="text-xs text-gray-500 flex items-center gap-1">
+ <Clock size={12} />
+ <span>{data.executionTime}ms</span>
+ </div>
+ )}
+
+ {/* Error Message */}
+ {data.error && (
+ <div className="text-xs text-red-400 flex items-start gap-1 bg-red-900/20 px-2 py-1 rounded">
+ <XCircle size={12} className="mt-0.5 flex-shrink-0" />
+ <span className="break-words">{data.error}</span>
+ </div>
+ )}
+
+ {/* Node Type */}
+ <div className="text-xs text-gray-600">
+ {node.type} v{node.typeVersion || 1}
+ </div>
+
+ {/* Disabled Badge */}
+ {node.disabled && (
+ <div className="inline-flex items-center gap-1 px-2 py-0.5 bg-yellow-900/30 border border-yellow-700/30 rounded text-xs text-yellow-500">
+ <AlertCircle size={10} />
+ Disabled
+ </div>
+ )}
+ </div>
+
+ {/* Node Footer - Actions */}
+ <div className="px-3 py-2 border-t border-gray-800 flex items-center gap-2">
+ <button
+ onClick={() => data.onConfigure?.(node)}
+ className="flex-1 px-2 py-1 bg-gray-800 hover:bg-gray-700 rounded text-xs text-gray-300 flex items-center justify-center gap-1 transition-colors"
+ title="Configure node"
+ >
+ <Settings size={12} />
+ Configure
+ </button>
+
+ {data.onExecute && (
+ <button
+ onClick={() => data.onExecute?.(node)}
+ disabled={node.disabled || data.executionStatus === 'running'}
+ className="px-2 py-1 bg-blue-600 hover:bg-blue-500 disabled:bg-gray-700 disabled:text-gray-500 rounded text-xs text-white flex items-center gap-1 transition-colors"
+ title="Execute node"
+ >
+ <Play size={12} />
+ </button>
+ )}
+ </div>
+
+ {/* Output Handle */}
+ <Handle
+ type="source"
+ position={Position.Right}
+ className="w-3 h-3 !bg-gray-700 !border-2 !border-gray-900"
+ style={{
+ right: -6,
+ }}
+ />
+
+ {/* Execution Indicator Overlay */}
+ {data.executionStatus === 'running' && (
+ <div
+ className="absolute inset-0 rounded-lg pointer-events-none"
+ style={{
+ background: `linear-gradient(90deg, transparent 0%, ${nodeColor}20 50%, transparent 100%)`,
+ backgroundSize: '200% 100%',
+ animation: 'shimmer 2s infinite',
+ }}
+ />
+ )}
+ </div>
+ );
+};
+
+export default SystemNode;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/TechnicalIndicatorNode.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/TechnicalIndicatorNode.tsx
new file mode 100644
index 000000000..e7970bb21
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/TechnicalIndicatorNode.tsx
@@ -0,0 +1,573 @@
+// TechnicalIndicatorNode.tsx - Node for calculating technical indicators
+import React, { useState } from 'react';
+import { Handle, Position } from 'reactflow';
+import { Play, Settings, CheckCircle, AlertCircle, Loader, TrendingUp } from 'lucide-react';
+
+interface TechnicalIndicatorNodeProps {
+ id: string;
+ data: {
+ label: string;
+ dataSource: 'yfinance' | 'csv' | 'json' | 'input';
+ symbol?: string;
+ period?: string;
+ csvPath?: string;
+ jsonData?: string;
+ categories: string[]; // ['momentum', 'volume', 'volatility', 'trend', 'others']
+ status: 'idle' | 'running' | 'completed' | 'error';
+ result?: any;
+ error?: string;
+ onExecute?: (nodeId: string) => void;
+ onParameterChange?: (params: Record<string, any>) => void;
+ };
+ selected: boolean;
+}
+
+const TechnicalIndicatorNode: React.FC<TechnicalIndicatorNodeProps> = ({ id, data, selected }) => {
+ const [showSettings, setShowSettings] = useState(false);
+ const [localParams, setLocalParams] = useState({
+ dataSource: data.dataSource || 'yfinance',
+ symbol: data.symbol || 'AAPL',
+ period: data.period || '1y',
+ csvPath: data.csvPath || '',
+ jsonData: data.jsonData || '',
+ categories: data.categories || ['momentum', 'volume', 'volatility', 'trend', 'others']
+ });
+
+ // Fincept colors
+ const ORANGE = '#FFA500';
+ const WHITE = '#FFFFFF';
+ const GRAY = '#787878';
+ const DARK_BG = '#0a0a0a';
+ const PANEL_BG = '#1a1a1a';
+ const BORDER = '#2d2d2d';
+ const GREEN = '#10b981';
+ const RED = '#ef4444';
+
+ const getStatusColor = () => {
+ switch (data.status) {
+ case 'running': return ORANGE;
+ case 'completed': return GREEN;
+ case 'error': return RED;
+ default: return GRAY;
+ }
+ };
+
+ const getStatusIcon = () => {
+ switch (data.status) {
+ case 'running': return <Loader size={14} className="animate-spin" color={ORANGE} />;
+ case 'completed': return <CheckCircle size={14} color={GREEN} />;
+ case 'error': return <AlertCircle size={14} color={RED} />;
+ default: return <TrendingUp size={14} color={GRAY} />;
+ }
+ };
+
+ const handleParamChange = (key: string, value: any) => {
+ const newParams = { ...localParams, [key]: value };
+ setLocalParams(newParams);
+ data.onParameterChange?.(newParams);
+ };
+
+ const handleCategoryToggle = (category: string) => {
+ const newCategories = localParams.categories.includes(category)
+ ? localParams.categories.filter(c => c !== category)
+ : [...localParams.categories, category];
+ handleParamChange('categories', newCategories);
+ };
+
+ const availableCategories = ['momentum', 'volume', 'volatility', 'trend', 'others'];
+
+ return (
+ <div style={{
+ backgroundColor: PANEL_BG,
+ border: `2px solid ${selected ? ORANGE : getStatusColor()}`,
+ borderRadius: '8px',
+ padding: '12px',
+ minWidth: '280px',
+ maxWidth: '350px',
+ fontFamily: 'Consolas, monospace',
+ boxShadow: selected ? `0 0 16px ${ORANGE}60` : `0 2px 8px rgba(0,0,0,0.3)`
+ }}>
+ {/* Input Handle - Can receive data from upstream nodes */}
+ <Handle
+ type="target"
+ position={Position.Left}
+ style={{
+ background: ORANGE,
+ width: '12px',
+ height: '12px',
+ border: `2px solid ${DARK_BG}`,
+ left: '-6px'
+ }}
+ />
+
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '10px',
+ paddingBottom: '8px',
+ borderBottom: `1px solid ${BORDER}`
+ }}>
+ <span style={{ fontSize: '20px' }}>📊</span>
+ <div style={{ flex: 1 }}>
+ <div style={{
+ color: WHITE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ marginBottom: '2px'
+ }}>
+ {data.label}
+ </div>
+ <div style={{
+ color: GRAY,
+ fontSize: '9px',
+ textTransform: 'uppercase'
+ }}>
+ TECHNICAL ANALYSIS
+ </div>
+ </div>
+ {getStatusIcon()}
+ </div>
+
+ {/* Data Source Summary */}
+ <div style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${BORDER}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ DATA SOURCE
+ </div>
+ <div style={{
+ color: GRAY,
+ fontSize: '8px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ marginBottom: '2px'
+ }}>
+ <span>Type:</span>
+ <span style={{ color: WHITE }}>{localParams.dataSource.toUpperCase()}</span>
+ </div>
+ {localParams.dataSource === 'yfinance' && (
+ <>
+ <div style={{
+ color: GRAY,
+ fontSize: '8px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ marginBottom: '2px'
+ }}>
+ <span>Symbol:</span>
+ <span style={{ color: WHITE }}>{localParams.symbol}</span>
+ </div>
+ <div style={{
+ color: GRAY,
+ fontSize: '8px',
+ display: 'flex',
+ justifyContent: 'space-between'
+ }}>
+ <span>Period:</span>
+ <span style={{ color: WHITE }}>{localParams.period}</span>
+ </div>
+ </>
+ )}
+ {localParams.dataSource === 'csv' && (
+ <div style={{
+ color: GRAY,
+ fontSize: '8px',
+ display: 'flex',
+ justifyContent: 'space-between'
+ }}>
+ <span>File:</span>
+ <span style={{ color: WHITE, maxWidth: '150px', overflow: 'hidden', textOverflow: 'ellipsis' }}>
+ {localParams.csvPath || 'Not set'}
+ </span>
+ </div>
+ )}
+ {localParams.dataSource === 'input' && (
+ <div style={{
+ color: GRAY,
+ fontSize: '8px'
+ }}>
+ Waiting for upstream data...
+ </div>
+ )}
+ </div>
+
+ {/* Categories Summary */}
+ <div style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${BORDER}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px'
+ }}>
+ INDICATORS ({localParams.categories.length}/5)
+ </div>
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
+ {localParams.categories.map(cat => (
+ <span key={cat} style={{
+ backgroundColor: `${ORANGE}30`,
+ border: `1px solid ${ORANGE}`,
+ color: ORANGE,
+ fontSize: '7px',
+ padding: '2px 6px',
+ borderRadius: '3px',
+ textTransform: 'uppercase'
+ }}>
+ {cat}
+ </span>
+ ))}
+ </div>
+ </div>
+
+ {/* Result Preview */}
+ {data.status === 'completed' && data.result && (
+ <div style={{
+ backgroundColor: `${GREEN}15`,
+ border: `1px solid ${GREEN}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: GREEN,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}>
+ <CheckCircle size={10} />
+ RESULT
+ </div>
+ <div style={{
+ color: WHITE,
+ fontSize: '8px',
+ fontFamily: 'monospace'
+ }}>
+ {Array.isArray(data.result)
+ ? `${data.result.length} data points calculated`
+ : 'Analysis complete'}
+ </div>
+ </div>
+ )}
+
+ {/* Error Display */}
+ {data.status === 'error' && data.error && (
+ <div style={{
+ backgroundColor: `${RED}15`,
+ border: `1px solid ${RED}`,
+ borderRadius: '4px',
+ padding: '6px',
+ marginBottom: '8px'
+ }}>
+ <div style={{
+ color: RED,
+ fontSize: '9px',
+ fontWeight: 'bold',
+ marginBottom: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}>
+ <AlertCircle size={10} />
+ ERROR
+ </div>
+ <div style={{
+ color: RED,
+ fontSize: '8px',
+ wordBreak: 'break-word'
+ }}>
+ {data.error}
+ </div>
+ </div>
+ )}
+
+ {/* Settings Panel */}
+ {showSettings && (
+ <div style={{
+ backgroundColor: DARK_BG,
+ border: `1px solid ${ORANGE}`,
+ borderRadius: '4px',
+ padding: '8px',
+ marginBottom: '8px',
+ maxHeight: '300px',
+ overflowY: 'auto'
+ }}>
+ <div style={{
+ color: ORANGE,
+ fontSize: '10px',
+ fontWeight: 'bold',
+ marginBottom: '8px'
+ }}>
+ CONFIGURATION
+ </div>
+
+ {/* Data Source Selection */}
+ <div style={{ marginBottom: '8px' }}>
+ <label style={{
+ color: GRAY,
+ fontSize: '8px',
+ display: 'block',
+ marginBottom: '4px'
+ }}>
+ Data Source
+ </label>
+ <select
+ value={localParams.dataSource}
+ onChange={(e) => handleParamChange('dataSource', e.target.value)}
+ style={{
+ width: '100%',
+ backgroundColor: PANEL_BG,
+ border: `1px solid ${BORDER}`,
+ color: WHITE,
+ padding: '4px',
+ fontSize: '8px',
+ borderRadius: '3px'
+ }}
+ >
+ <option value="yfinance">Yahoo Finance</option>
+ <option value="csv">CSV File</option>
+ <option value="json">JSON Data</option>
+ <option value="input">Upstream Input</option>
+ </select>
+ </div>
+
+ {/* YFinance Params */}
+ {localParams.dataSource === 'yfinance' && (
+ <>
+ <div style={{ marginBottom: '8px' }}>
+ <label style={{
+ color: GRAY,
+ fontSize: '8px',
+ display: 'block',
+ marginBottom: '4px'
+ }}>
+ Symbol
+ </label>
+ <input
+ type="text"
+ value={localParams.symbol}
+ onChange={(e) => handleParamChange('symbol', e.target.value)}
+ placeholder="AAPL"
+ style={{
+ width: '100%',
+ backgroundColor: PANEL_BG,
+ border: `1px solid ${BORDER}`,
+ color: WHITE,
+ padding: '4px',
+ fontSize: '8px',
+ borderRadius: '3px'
+ }}
+ />
+ </div>
+ <div style={{ marginBottom: '8px' }}>
+ <label style={{
+ color: GRAY,
+ fontSize: '8px',
+ display: 'block',
+ marginBottom: '4px'
+ }}>
+ Period
+ </label>
+ <select
+ value={localParams.period}
+ onChange={(e) => handleParamChange('period', e.target.value)}
+ style={{
+ width: '100%',
+ backgroundColor: PANEL_BG,
+ border: `1px solid ${BORDER}`,
+ color: WHITE,
+ padding: '4px',
+ fontSize: '8px',
+ borderRadius: '3px'
+ }}
+ >
+ <option value="1d">1 Day</option>
+ <option value="5d">5 Days</option>
+ <option value="1mo">1 Month</option>
+ <option value="3mo">3 Months</option>
+ <option value="6mo">6 Months</option>
+ <option value="1y">1 Year</option>
+ <option value="2y">2 Years</option>
+ <option value="5y">5 Years</option>
+ <option value="max">Max</option>
+ </select>
+ </div>
+ </>
+ )}
+
+ {/* CSV Path */}
+ {localParams.dataSource === 'csv' && (
+ <div style={{ marginBottom: '8px' }}>
+ <label style={{
+ color: GRAY,
+ fontSize: '8px',
+ display: 'block',
+ marginBottom: '4px'
+ }}>
+ CSV File Path
+ </label>
+ <input
+ type="text"
+ value={localParams.csvPath}
+ onChange={(e) => handleParamChange('csvPath', e.target.value)}
+ placeholder="/path/to/data.csv"
+ style={{
+ width: '100%',
+ backgroundColor: PANEL_BG,
+ border: `1px solid ${BORDER}`,
+ color: WHITE,
+ padding: '4px',
+ fontSize: '8px',
+ borderRadius: '3px'
+ }}
+ />
+ </div>
+ )}
+
+ {/* Categories Selection */}
+ <div style={{ marginBottom: '8px' }}>
+ <label style={{
+ color: GRAY,
+ fontSize: '8px',
+ display: 'block',
+ marginBottom: '6px'
+ }}>
+ Indicator Categories
+ </label>
+ {availableCategories.map(category => (
+ <label key={category} style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ marginBottom: '6px',
+ cursor: 'pointer'
+ }}>
+ <input
+ type="checkbox"
+ checked={localParams.categories.includes(category)}
+ onChange={() => handleCategoryToggle(category)}
+ style={{
+ accentColor: ORANGE
+ }}
+ />
+ <span style={{
+ color: WHITE,
+ fontSize: '8px',
+ textTransform: 'capitalize'
+ }}>
+ {category}
+ </span>
+ </label>
+ ))}
+ </div>
+
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ setShowSettings(false);
+ }}
+ style={{
+ width: '100%',
+ backgroundColor: ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '6px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '3px'
+ }}
+ >
+ CLOSE
+ </button>
+ </div>
+ )}
+
+ {/* Action Buttons */}
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <button
+ onClick={() => data.onExecute?.(id)}
+ disabled={data.status === 'running'}
+ style={{
+ flex: 1,
+ backgroundColor: data.status === 'running' ? GRAY : ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '8px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: data.status === 'running' ? 'not-allowed' : 'pointer',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px',
+ opacity: data.status === 'running' ? 0.6 : 1
+ }}
+ >
+ {data.status === 'running' ? (
+ <>
+ <Loader size={12} className="animate-spin" />
+ RUNNING...
+ </>
+ ) : (
+ <>
+ <Play size={12} />
+ CALCULATE
+ </>
+ )}
+ </button>
+ <button
+ onClick={() => setShowSettings(!showSettings)}
+ style={{
+ backgroundColor: showSettings ? ORANGE : DARK_BG,
+ border: `1px solid ${BORDER}`,
+ color: showSettings ? 'black' : GRAY,
+ padding: '8px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center'
+ }}
+ >
+ <Settings size={14} />
+ </button>
+ </div>
+
+ {/* Output Handle */}
+ <Handle
+ type="source"
+ position={Position.Right}
+ style={{
+ background: data.status === 'completed' ? GREEN : ORANGE,
+ width: '12px',
+ height: '12px',
+ border: `2px solid ${DARK_BG}`,
+ right: '-6px'
+ }}
+ />
+ </div>
+ );
+};
+
+export default TechnicalIndicatorNode;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/WorkflowExecutor.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/WorkflowExecutor.ts
new file mode 100644
index 000000000..a2ae02da9
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/WorkflowExecutor.ts
@@ -0,0 +1,249 @@
+import { Node, Edge } from 'reactflow';
+import { workflowService } from '@/services/core/workflowService';
+import { invoke } from '@tauri-apps/api/core';
+
+interface ExecuteOptions {
+ name: string;
+ description: string;
+ saveAsDraft: boolean;
+}
+
+type StatusCallback = (nodeId: string, status: string, result?: any) => void;
+
+class WorkflowExecutor {
+ async executeAndSave(
+ nodes: Node[],
+ edges: Edge[],
+ options: ExecuteOptions,
+ statusCallback: StatusCallback
+ ): Promise<{ success: boolean; workflowId?: string; error?: string }> {
+ console.log('[WorkflowExecutor] Executing workflow:', options.name);
+
+ try {
+ // Execute workflow nodes
+ const results = new Map<string, any>();
+
+ for (const node of nodes) {
+ statusCallback(node.id, 'running');
+
+ try {
+ let result: any;
+
+ // Execute based on node type
+ switch (node.type) {
+ case 'technical-indicator':
+ result = await this.executeTechnicalIndicatorNode(node, results);
+ break;
+
+ case 'python-agent':
+ result = await this.executePythonAgentNode(node, results);
+ break;
+
+ case 'data-source':
+ result = await this.executeDataSourceNode(node, results);
+ break;
+
+ default:
+ // For other node types, simulate execution
+ await new Promise(resolve => setTimeout(resolve, 500));
+ result = { message: 'Node executed successfully' };
+ }
+
+ results.set(node.id, result);
+ statusCallback(node.id, 'completed', result);
+ } catch (error) {
+ console.error(`[WorkflowExecutor] Error executing node ${node.id}:`, error);
+ statusCallback(node.id, 'error', { error: String(error) });
+ throw error;
+ }
+ }
+
+ return {
+ success: true,
+ workflowId: `workflow_${Date.now()}`
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error: String(error)
+ };
+ }
+ }
+
+ private async executeTechnicalIndicatorNode(node: Node, previousResults: Map<string, any>): Promise<any> {
+ console.log('[WorkflowExecutor] Executing technical indicator node:', node.id);
+
+ const { dataSource, symbol, period, csvPath, jsonData, categories } = node.data;
+
+ try {
+ let result: string;
+
+ // Build categories string
+ const categoriesStr = categories && categories.length > 0 ? categories.join(',') : undefined;
+
+ // Execute based on data source
+ switch (dataSource) {
+ case 'yfinance':
+ result = await invoke('calculate_indicators_yfinance', {
+ symbol: symbol || 'AAPL',
+ period: period || '1y',
+ categories: categoriesStr
+ });
+ break;
+
+ case 'csv':
+ if (!csvPath) {
+ throw new Error('CSV file path is required');
+ }
+ result = await invoke('calculate_indicators_csv', {
+ filepath: csvPath,
+ categories: categoriesStr
+ });
+ break;
+
+ case 'json':
+ if (!jsonData) {
+ throw new Error('JSON data is required');
+ }
+ result = await invoke('calculate_indicators_json', {
+ jsonData: jsonData,
+ categories: categoriesStr
+ });
+ break;
+
+ case 'input':
+ // Get data from previous node
+ const inputEdges = node.data.inputEdges || [];
+ if (inputEdges.length === 0) {
+ throw new Error('No input connection found');
+ }
+
+ const sourceNodeId = inputEdges[0].source;
+ const sourceData = previousResults.get(sourceNodeId);
+
+ if (!sourceData) {
+ throw new Error('No data available from input node');
+ }
+
+ // Use the data from previous node as JSON input
+ result = await invoke('calculate_indicators_json', {
+ jsonData: JSON.stringify(sourceData),
+ categories: categoriesStr
+ });
+ break;
+
+ default:
+ throw new Error(`Unknown data source: ${dataSource}`);
+ }
+
+ // Parse result
+ const parsedResult = JSON.parse(result);
+
+ // Check for errors
+ if (parsedResult.error) {
+ throw new Error(parsedResult.error);
+ }
+
+ console.log('[WorkflowExecutor] Technical indicator node completed:', parsedResult);
+ return parsedResult;
+
+ } catch (error) {
+ console.error('[WorkflowExecutor] Technical indicator node failed:', error);
+ throw error;
+ }
+ }
+
+ private async executePythonAgentNode(node: Node, previousResults: Map<string, any>): Promise<any> {
+ console.log('[WorkflowExecutor] Executing Python agent node:', node.id);
+
+ try {
+ const { pythonAgentService } = await import('@/services/chat/pythonAgentService');
+ const { agentId, parameters } = node.data;
+
+ if (!agentId) {
+ throw new Error('No agent ID specified in node');
+ }
+
+ // Get input data from previous results if connected
+ const inputData = previousResults.size > 0
+ ? Object.fromEntries(previousResults)
+ : parameters || {};
+
+ // Execute the Python agent
+ const result = await pythonAgentService.executeAgent(
+ agentId,
+ parameters || {},
+ inputData
+ );
+
+ console.log('[WorkflowExecutor] Python agent completed:', result);
+ return result;
+ } catch (error) {
+ console.error('[WorkflowExecutor] Python agent failed:', error);
+ throw error;
+ }
+ }
+
+ private async executeDataSourceNode(node: Node, previousResults: Map<string, any>): Promise<any> {
+ console.log('[WorkflowExecutor] Executing data source node:', node.id);
+
+ try {
+ const { createAdapter, hasAdapter } = await import('@/components/tabs/data-sources/adapters');
+ const { sourceType, connectionConfig, query } = node.data;
+
+ if (!sourceType) {
+ throw new Error('No source type specified');
+ }
+
+ if (!hasAdapter(sourceType)) {
+ throw new Error(`No adapter available for: ${sourceType}`);
+ }
+
+ // Create connection from node config
+ const connection = {
+ id: node.id,
+ name: node.data.label || 'Data Source',
+ type: sourceType,
+ category: node.data.category || 'database',
+ config: connectionConfig || {},
+ status: 'connected' as const,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ };
+
+ const adapter = createAdapter(connection);
+ if (!adapter) {
+ throw new Error(`Failed to create adapter for: ${sourceType}`);
+ }
+
+ const result = await adapter.query(query || {});
+ console.log('[WorkflowExecutor] Data source completed:', result);
+ return result;
+ } catch (error) {
+ console.error('[WorkflowExecutor] Data source failed:', error);
+ throw error;
+ }
+ }
+
+ async saveDraft(
+ name: string,
+ description: string,
+ nodes: Node[],
+ edges: Edge[]
+ ): Promise<string> {
+ console.log('[WorkflowExecutor] Saving draft:', name);
+
+ // Actually save the draft to workflowService
+ const workflowId = await workflowService.saveDraft(
+ name,
+ description,
+ nodes,
+ edges
+ );
+
+ console.log('[WorkflowExecutor] Draft saved with ID:', workflowId);
+ return workflowId;
+ }
+}
+
+export const workflowExecutor = new WorkflowExecutor();
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/WorkflowManager.tsx b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/WorkflowManager.tsx
new file mode 100644
index 000000000..29520d91e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/WorkflowManager.tsx
@@ -0,0 +1,392 @@
+import React, { useState, useEffect } from 'react';
+import { Node, Edge } from 'reactflow';
+import { Workflow, workflowService } from '@/services/core/workflowService';
+import { Play, Trash2, Edit3, Eye, FileText, Clock, CheckCircle, AlertCircle } from 'lucide-react';
+
+interface WorkflowManagerProps {
+ onLoadWorkflow: (nodes: Node[], edges: Edge[], workflowId: string, workflow: Workflow) => void;
+ onViewResults: (workflow: Workflow) => void;
+ onEditDraft: (workflow: Workflow) => void;
+}
+
+const WorkflowManager: React.FC<WorkflowManagerProps> = ({ onLoadWorkflow, onViewResults, onEditDraft }) => {
+ const [workflows, setWorkflows] = useState<Workflow[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [filter, setFilter] = useState<'all' | 'draft' | 'completed'>('all');
+
+ // Load workflows on mount
+ useEffect(() => {
+ loadWorkflows();
+ }, []);
+
+ const loadWorkflows = async () => {
+ setLoading(true);
+ try {
+ const allWorkflows = await workflowService.listWorkflows();
+ setWorkflows(allWorkflows);
+ } catch (error) {
+ console.error('[WorkflowManager] Failed to load workflows:', error);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleDelete = async (workflowId: string) => {
+ if (!confirm('Are you sure you want to delete this workflow?')) {
+ return;
+ }
+
+ try {
+ await workflowService.deleteWorkflow(workflowId);
+ setWorkflows(prev => prev.filter(wf => wf.id !== workflowId));
+ } catch (error) {
+ console.error('[WorkflowManager] Failed to delete workflow:', error);
+ alert('Failed to delete workflow');
+ }
+ };
+
+ const handlePlay = (workflow: Workflow) => {
+ onLoadWorkflow(workflow.nodes, workflow.edges, workflow.id, workflow);
+ };
+
+ const handleEdit = (workflow: Workflow) => {
+ if (workflow.status === 'draft') {
+ onEditDraft(workflow);
+ } else {
+ onLoadWorkflow(workflow.nodes, workflow.edges, workflow.id, workflow);
+ }
+ };
+
+ const handleViewResults = (workflow: Workflow) => {
+ onViewResults(workflow);
+ };
+
+ // Filter workflows
+ const filteredWorkflows = workflows.filter(wf => {
+ if (filter === 'all') return true;
+ if (filter === 'draft') return wf.status === 'draft';
+ if (filter === 'completed') return wf.status === 'completed';
+ return true;
+ });
+
+ const getStatusIcon = (status: string) => {
+ switch (status) {
+ case 'completed': return <CheckCircle size={14} color="#10b981" />;
+ case 'draft': return <FileText size={14} color="#f59e0b" />;
+ case 'error': return <AlertCircle size={14} color="#ef4444" />;
+ case 'running': return <Clock size={14} color="#3b82f6" />;
+ default: return <FileText size={14} color="#6b7280" />;
+ }
+ };
+
+ const getStatusColor = (status: string) => {
+ switch (status) {
+ case 'completed': return '#10b981';
+ case 'draft': return '#f59e0b';
+ case 'error': return '#ef4444';
+ case 'running': return '#3b82f6';
+ default: return '#6b7280';
+ }
+ };
+
+ return (
+ <div style={{
+ padding: '20px',
+ color: '#a3a3a3',
+ height: '100%',
+ overflow: 'auto'
+ }}>
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '20px',
+ paddingBottom: '12px',
+ borderBottom: '2px solid #404040'
+ }}>
+ <h2 style={{
+ margin: 0,
+ fontSize: '20px',
+ color: '#fff',
+ fontWeight: 'bold'
+ }}>
+ 📋 Workflow Manager
+ </h2>
+ <button
+ onClick={loadWorkflows}
+ style={{
+ backgroundColor: '#3b82f6',
+ color: '#fff',
+ border: 'none',
+ padding: '6px 12px',
+ fontSize: '12px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '4px'
+ }}
+ >
+ 🔄 REFRESH
+ </button>
+ </div>
+
+ {/* Filter Tabs */}
+ <div style={{
+ display: 'flex',
+ gap: '8px',
+ marginBottom: '16px',
+ borderBottom: '1px solid #404040',
+ paddingBottom: '8px'
+ }}>
+ {['all', 'draft', 'completed'].map(f => (
+ <button
+ key={f}
+ onClick={() => setFilter(f as any)}
+ style={{
+ backgroundColor: filter === f ? '#3b82f6' : 'transparent',
+ color: filter === f ? '#fff' : '#a3a3a3',
+ border: `1px solid ${filter === f ? '#3b82f6' : '#404040'}`,
+ padding: '6px 16px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '4px',
+ textTransform: 'uppercase'
+ }}
+ >
+ {f} ({workflows.filter(wf => f === 'all' || wf.status === f).length})
+ </button>
+ ))}
+ </div>
+
+ {/* Loading State */}
+ {loading && (
+ <div style={{
+ textAlign: 'center',
+ padding: '40px',
+ color: '#6b7280'
+ }}>
+ Loading workflows...
+ </div>
+ )}
+
+ {/* Empty State */}
+ {!loading && filteredWorkflows.length === 0 && (
+ <div style={{
+ textAlign: 'center',
+ padding: '40px',
+ color: '#6b7280'
+ }}>
+ <FileText size={48} style={{ margin: '0 auto 16px', opacity: 0.5 }} />
+ <p style={{ fontSize: '14px', marginBottom: '8px' }}>
+ No {filter !== 'all' ? filter : ''} workflows found
+ </p>
+ <p style={{ fontSize: '12px', opacity: 0.7 }}>
+ Create a new workflow in the Editor tab
+ </p>
+ </div>
+ )}
+
+ {/* Workflow List */}
+ {!loading && filteredWorkflows.length > 0 && (
+ <div style={{
+ display: 'grid',
+ gap: '12px'
+ }}>
+ {filteredWorkflows.map(workflow => (
+ <div
+ key={workflow.id}
+ style={{
+ backgroundColor: '#1a1a1a',
+ border: '1px solid #404040',
+ borderRadius: '6px',
+ padding: '16px',
+ transition: 'all 0.2s',
+ cursor: 'pointer'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = '#3b82f6';
+ e.currentTarget.style.backgroundColor = '#252525';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = '#404040';
+ e.currentTarget.style.backgroundColor = '#1a1a1a';
+ }}
+ >
+ {/* Workflow Header */}
+ <div style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'flex-start',
+ marginBottom: '12px'
+ }}>
+ <div style={{ flex: 1 }}>
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ marginBottom: '4px'
+ }}>
+ {getStatusIcon(workflow.status)}
+ <h3 style={{
+ margin: 0,
+ fontSize: '14px',
+ color: '#fff',
+ fontWeight: 'bold'
+ }}>
+ {workflow.name}
+ </h3>
+ <span style={{
+ backgroundColor: getStatusColor(workflow.status),
+ color: '#000',
+ padding: '2px 8px',
+ fontSize: '9px',
+ fontWeight: 'bold',
+ borderRadius: '3px',
+ textTransform: 'uppercase'
+ }}>
+ {workflow.status}
+ </span>
+ </div>
+ {workflow.description && (
+ <p style={{
+ margin: '4px 0 0 0',
+ fontSize: '11px',
+ color: '#6b7280',
+ lineHeight: '1.4'
+ }}>
+ {workflow.description}
+ </p>
+ )}
+ </div>
+ </div>
+
+ {/* Workflow Info */}
+ <div style={{
+ display: 'flex',
+ gap: '16px',
+ marginBottom: '12px',
+ fontSize: '11px',
+ color: '#6b7280'
+ }}>
+ <span>📦 {workflow.nodes?.length || 0} nodes</span>
+ <span>🔗 {workflow.edges?.length || 0} connections</span>
+ <span style={{ marginLeft: 'auto', fontSize: '10px' }}>
+ ID: {workflow.id.substring(0, 12)}...
+ </span>
+ </div>
+
+ {/* Action Buttons */}
+ <div style={{
+ display: 'flex',
+ gap: '8px',
+ paddingTop: '12px',
+ borderTop: '1px solid #404040'
+ }}>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ handlePlay(workflow);
+ }}
+ style={{
+ flex: 1,
+ backgroundColor: '#10b981',
+ color: '#fff',
+ border: 'none',
+ padding: '6px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px'
+ }}
+ >
+ <Play size={12} />
+ LOAD & RUN
+ </button>
+
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ handleEdit(workflow);
+ }}
+ style={{
+ flex: 1,
+ backgroundColor: '#3b82f6',
+ color: '#fff',
+ border: 'none',
+ padding: '6px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px'
+ }}
+ >
+ <Edit3 size={12} />
+ EDIT
+ </button>
+
+ {workflow.results && (
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ handleViewResults(workflow);
+ }}
+ style={{
+ backgroundColor: '#f59e0b',
+ color: '#000',
+ border: 'none',
+ padding: '6px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '4px'
+ }}
+ >
+ <Eye size={12} />
+ RESULTS
+ </button>
+ )}
+
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ handleDelete(workflow.id);
+ }}
+ style={{
+ backgroundColor: '#ef4444',
+ color: '#fff',
+ border: 'none',
+ padding: '6px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '4px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center'
+ }}
+ >
+ <Trash2 size={12} />
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default WorkflowManager;
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/index.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/index.ts
new file mode 100644
index 000000000..5e26a3d6d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/index.ts
@@ -0,0 +1,24 @@
+/**
+ * AI Quant Lab - Nodes Index
+ *
+ * Export all node components and utilities
+ */
+
+// Node Components
+export { default as MCPToolNode } from './MCPToolNode';
+export { default as PythonAgentNode } from './PythonAgentNode';
+export { default as ResultsDisplayNode } from './ResultsDisplayNode';
+export { default as AgentMediatorNode } from './AgentMediatorNode';
+export { default as DataSourceNode } from './DataSourceNode';
+export { default as TechnicalIndicatorNode } from './TechnicalIndicatorNode';
+export { default as BacktestNode } from './BacktestNode';
+export { default as OptimizationNode } from './OptimizationNode';
+export { SystemNode } from './SystemNode';
+export { default as WorkflowManager } from './WorkflowManager';
+export { default as ResultsModal } from './ResultsModal';
+
+// Utilities
+export { NodeParameterInput } from './NodeParameterInput';
+export { generateMCPNodeConfigs } from './mcpNodeConfigs';
+export type { MCPNodeConfig } from './mcpNodeConfigs';
+export { workflowExecutor } from './WorkflowExecutor';
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/mcpNodeConfigs.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/mcpNodeConfigs.ts
new file mode 100644
index 000000000..975de74e4
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/nodes/mcpNodeConfigs.ts
@@ -0,0 +1,134 @@
+// MCP Node Configurations
+// Dynamically generates node configs from available MCP servers
+
+import { mcpToolService, MCPTool } from '@/services/mcp/mcpToolService';
+
+export interface MCPNodeConfig {
+ id: string;
+ type: 'mcp-tool';
+ label: string;
+ category: 'MCP Tools';
+ icon: string;
+ serverId: string;
+ toolName: string;
+ description: string;
+ inputs: string[];
+ outputs: string[];
+}
+
+/**
+ * Generate node configurations from available MCP tools
+ * This function is called when Node Editor initializes
+ */
+export async function generateMCPNodeConfigs(): Promise<MCPNodeConfig[]> {
+ try {
+ const tools = await mcpToolService.getAllTools();
+
+ return tools.map((tool: MCPTool) => {
+ // Extract inputs from tool schema
+ const inputs = tool.inputSchema?.properties
+ ? Object.keys(tool.inputSchema.properties)
+ : [];
+
+ return {
+ id: `mcp-${tool.serverId}-${tool.name}`,
+ type: 'mcp-tool' as const,
+ label: tool.name.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()),
+ category: 'MCP Tools' as const,
+ icon: getIconForTool(tool),
+ serverId: tool.serverId,
+ toolName: tool.name,
+ description: tool.description || `${tool.name} from ${tool.serverId}`,
+ inputs,
+ outputs: ['output'] // All MCP tools have output
+ };
+ });
+ } catch (error) {
+ console.error('[MCPNodeConfigs] Failed to generate configs:', error);
+ return [];
+ }
+}
+
+/**
+ * Get icon emoji for tool based on server and tool name
+ */
+function getIconForTool(tool: MCPTool): string {
+ const serverId = tool.serverId.toLowerCase();
+ const toolName = tool.name.toLowerCase();
+
+ // Database tools
+ if (serverId.includes('postgres')) return '🐘';
+ if (serverId.includes('questdb')) return '';
+ if (serverId.includes('sqlite')) return '💾';
+ if (serverId.includes('mysql')) return '🐬';
+
+ // Web tools
+ if (serverId.includes('wikipedia')) return '📚';
+ if (serverId.includes('search') || serverId.includes('brave')) return '🔍';
+ if (serverId.includes('fetch') || toolName.includes('fetch')) return '🌐';
+
+ // File tools
+ if (serverId.includes('filesystem') || serverId.includes('file')) return '📁';
+
+ // API tools
+ if (serverId.includes('api') || serverId.includes('http')) return '🔌';
+
+ // Productivity tools
+ if (serverId.includes('slack')) return '💬';
+ if (serverId.includes('email')) return '📧';
+ if (serverId.includes('calendar')) return '📅';
+
+ // Default
+ return '';
+}
+
+/**
+ * Get MCP tool categories for filtering in Node Editor
+ */
+export function getMCPToolCategories(tools: MCPNodeConfig[]): string[] {
+ const categories = new Set<string>();
+
+ tools.forEach(tool => {
+ const category = categorizeMCPTool(tool);
+ categories.add(category);
+ });
+
+ return Array.from(categories);
+}
+
+/**
+ * Categorize MCP tool for grouping in UI
+ */
+function categorizeMCPTool(tool: MCPNodeConfig): string {
+ const serverId = tool.serverId.toLowerCase();
+
+ if (serverId.includes('postgres') || serverId.includes('questdb') ||
+ serverId.includes('sqlite') || serverId.includes('mysql')) {
+ return 'Database';
+ }
+
+ if (serverId.includes('wikipedia') || serverId.includes('search') ||
+ serverId.includes('fetch')) {
+ return 'Web';
+ }
+
+ if (serverId.includes('file')) {
+ return 'File System';
+ }
+
+ if (serverId.includes('api') || serverId.includes('http')) {
+ return 'API';
+ }
+
+ return 'Other';
+}
+
+/**
+ * Refresh MCP node configurations
+ * Call this when new MCP servers are installed
+ */
+export async function refreshMCPNodeConfigs(): Promise<MCPNodeConfig[]> {
+ // Clear cache to get fresh tool list
+ mcpToolService.clearCache();
+ return generateMCPNodeConfigs();
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/types.ts b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/types.ts
new file mode 100644
index 000000000..d14f48fe2
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ai-quant-lab/types.ts
@@ -0,0 +1,138 @@
+/**
+ * AI Quant Lab - Type Definitions
+ *
+ * Shared types and interfaces for the Node Editor and workflow system
+ */
+
+import { Node, Edge } from 'reactflow';
+import type { INodeProperties, NodeParameterValue, INodeTypeDescription } from '@/services/nodeSystem';
+import { Workflow as WorkflowType } from '@/services/core/workflowService';
+import { MCPNodeConfig } from './nodes/mcpNodeConfigs';
+import { AgentMetadata } from '@/services/chat/pythonAgentService';
+
+// Node configuration for builtin nodes
+export interface NodeConfig {
+ type: string;
+ label: string;
+ color: string;
+ category: string;
+ hasInput: boolean;
+ hasOutput: boolean;
+ description: string;
+}
+
+// Node palette item representation
+export interface PaletteNodeItem {
+ id: string;
+ type: string;
+ label: string;
+ category: string;
+ color: string;
+ description: string;
+ source: 'builtin' | 'registry' | 'mcp' | 'agent';
+ data?: any;
+}
+
+// Node palette props
+export interface NodePaletteProps {
+ onNodeAdd: (nodeType: string, nodeData: any) => void;
+ isCollapsed: boolean;
+ onToggleCollapse: () => void;
+ mcpNodeConfigs: MCPNodeConfig[];
+ agentConfigs: AgentMetadata[];
+}
+
+// Toolbar props
+export interface NodeEditorToolbarProps {
+ activeView: 'editor' | 'workflows';
+ setActiveView: (view: 'editor' | 'workflows') => void;
+ showNodeMenu: boolean;
+ setShowNodeMenu: (show: boolean) => void;
+ isExecuting: boolean;
+ nodes: Node[];
+ edges: Edge[];
+ selectedNodes: string[];
+ workflowMode: 'new' | 'draft' | 'deployed';
+ editingDraftId: string | null;
+ workflowName: string;
+ workflowDescription: string;
+ onExecute: () => Promise<void>;
+ onClearWorkflow: () => void;
+ onSaveWorkflow: () => void;
+ onImportWorkflow: () => void;
+ onExportWorkflow: () => void;
+ onDeleteSelectedNodes: () => void;
+ onShowDeployDialog: () => void;
+ onQuickSaveDraft: () => Promise<void>;
+}
+
+// Deploy dialog props
+export interface DeployDialogProps {
+ isOpen: boolean;
+ onClose: () => void;
+ workflowName: string;
+ setWorkflowName: (name: string) => void;
+ workflowDescription: string;
+ setWorkflowDescription: (description: string) => void;
+ onDeploy: () => void;
+ onSaveDraft: () => void;
+}
+
+// Node config panel props
+export interface NodeConfigPanelProps {
+ selectedNode: Node;
+ onLabelChange: (nodeId: string, newLabel: string) => void;
+ onParameterChange: (paramName: string, value: NodeParameterValue) => void;
+ onClose: () => void;
+ onDelete: () => void;
+ onDuplicate: () => void;
+ setNodes: React.Dispatch<React.SetStateAction<Node[]>>;
+}
+
+// Custom node data
+export interface CustomNodeData {
+ label: string;
+ nodeType?: string;
+ color: string;
+ hasInput: boolean;
+ hasOutput: boolean;
+ status?: 'idle' | 'running' | 'completed' | 'error';
+ result?: any;
+ error?: string;
+ parameters?: Record<string, any>;
+ registryData?: INodeTypeDescription;
+ nodeTypeName?: string;
+ onLabelChange: (nodeId: string, newLabel: string) => void;
+}
+
+// Workflow management hook return type
+export interface WorkflowManagementState {
+ nodes: Node[];
+ edges: Edge[];
+ setNodes: React.Dispatch<React.SetStateAction<Node[]>>;
+ setEdges: React.Dispatch<React.SetStateAction<Edge[]>>;
+ onNodesChange: any;
+ onEdgesChange: any;
+ selectedNodes: string[];
+ setSelectedNodes: React.Dispatch<React.SetStateAction<string[]>>;
+ isExecuting: boolean;
+ setIsExecuting: React.Dispatch<React.SetStateAction<boolean>>;
+ workflowMode: 'new' | 'draft' | 'deployed';
+ setWorkflowMode: React.Dispatch<React.SetStateAction<'new' | 'draft' | 'deployed'>>;
+ currentWorkflowId: string | null;
+ setCurrentWorkflowId: React.Dispatch<React.SetStateAction<string | null>>;
+ editingDraftId: string | null;
+ setEditingDraftId: React.Dispatch<React.SetStateAction<string | null>>;
+ workflowName: string;
+ setWorkflowName: React.Dispatch<React.SetStateAction<string>>;
+ workflowDescription: string;
+ setWorkflowDescription: React.Dispatch<React.SetStateAction<string>>;
+}
+
+// Category configuration
+export interface CategoryConfig {
+ icon: React.ReactNode;
+ color: string;
+}
+
+export type { WorkflowType, MCPNodeConfig, AgentMetadata, INodeProperties, NodeParameterValue, INodeTypeDescription };
diff --git a/fincept-terminal-desktop/src/components/tabs/AkShareDataTab.tsx b/fincept-terminal-desktop/src/components/tabs/akshare-data/AkShareDataTab.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/AkShareDataTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/akshare-data/AkShareDataTab.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/akshare-data/index.ts b/fincept-terminal-desktop/src/components/tabs/akshare-data/index.ts
new file mode 100644
index 000000000..32377662a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/akshare-data/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./AkShareDataTab";
+export { default as AkShareDataTab } from "./AkShareDataTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsx
index ecfe0212f..59b62e5bc 100644
--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/AlphaArenaTab.tsx
@@ -15,13 +15,23 @@ import {
TrendingUp, TrendingDown, Activity, Zap, AlertCircle, CheckCircle,
ChevronRight, Loader2, BarChart3, Clock, Target, Brain,
RefreshCw, Eye, Users, Sparkles, Check, Circle, History, Trash2, PlayCircle,
- StopCircle, XCircle,
+ StopCircle, XCircle, Shield, Newspaper, Grid3X3, FileSearch, Building,
} from 'lucide-react';
import { TabFooter } from '@/components/common/TabFooter';
import { sqliteService, type LLMModelConfig, type LLMConfig } from '@/services/core/sqliteService';
import alphaArenaService, { type StoredCompetition } from './services/alphaArenaService';
import { useAuth } from '@/contexts/AuthContext';
+// Enhanced Components
+import {
+ HITLApprovalPanel,
+ SentimentPanel,
+ PortfolioMetricsPanel,
+ GridStrategyPanel,
+ ResearchPanel,
+ BrokerSelector,
+} from './components';
+
// Extended model type for Alpha Arena with API key
interface AlphaArenaModel {
id: string;
@@ -118,6 +128,11 @@ const AlphaArenaTab: React.FC = () => {
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
+ // Enhanced features state
+ type RightPanelTab = 'decisions' | 'hitl' | 'sentiment' | 'metrics' | 'grid' | 'research' | 'broker';
+ const [rightPanelTab, setRightPanelTab] = useState<RightPanelTab>('decisions');
+ const [selectedBroker, setSelectedBroker] = useState<string | null>(null);
+
// Abort controller for cancelling operations
const abortControllerRef = useRef<AbortController | null>(null);
@@ -140,6 +155,9 @@ const AlphaArenaTab: React.FC = () => {
// Auto-run ref
const autoRunIntervalRef = useRef<NodeJS.Timeout | null>(null);
+ // Track if a cycle is currently running (to prevent overlapping cycles)
+ const cycleInProgressRef = useRef(false);
+
// =============================================================================
// Load LLM Models from Settings (llm_model_configs table)
// =============================================================================
@@ -454,8 +472,15 @@ const AlphaArenaTab: React.FC = () => {
};
const handleRunCycle = useCallback(async () => {
- if (!competitionId || isLoading) return;
+ if (!competitionId) return;
+ // Prevent overlapping cycles - use ref to allow auto-run to continue
+ if (cycleInProgressRef.current) {
+ console.log('[AlphaArena] Cycle already in progress, skipping...');
+ return;
+ }
+
+ cycleInProgressRef.current = true;
setIsLoading(true);
setError(null);
setProgressSteps([]); // Reset progress
@@ -463,25 +488,32 @@ const AlphaArenaTab: React.FC = () => {
try {
const currentCompetitionId = competitionId; // Capture before async
+ console.log('[AlphaArena] Running cycle for competition:', currentCompetitionId);
const result = await alphaArenaService.runCycle(currentCompetitionId);
if (result.success) {
+ console.log('[AlphaArena] Cycle completed successfully, cycle_number:', result.cycle_number);
setCycleCount(result.cycle_number || cycleCount + 1);
setStatus('running');
// Pass ID explicitly to avoid stale closure issues
await fetchCompetitionData(currentCompetitionId);
} else {
+ console.error('[AlphaArena] Cycle failed:', result.error);
setError(result.error || 'Cycle failed');
}
} catch (err) {
+ console.error('[AlphaArena] Cycle error:', err);
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
+ cycleInProgressRef.current = false;
setIsLoading(false);
}
- }, [competitionId, isLoading, cycleCount, fetchCompetitionData]);
+ }, [competitionId, cycleCount, fetchCompetitionData]);
const handleToggleAutoRun = useCallback(() => {
if (isAutoRunning) {
+ // Stop auto-run
+ console.log('[AlphaArena] Stopping auto-run');
if (autoRunIntervalRef.current) {
clearInterval(autoRunIntervalRef.current);
autoRunIntervalRef.current = null;
@@ -489,10 +521,19 @@ const AlphaArenaTab: React.FC = () => {
setIsAutoRunning(false);
setStatus('paused');
} else {
+ // Start auto-run
+ console.log('[AlphaArena] Starting auto-run with interval:', cycleInterval, 'seconds');
setIsAutoRunning(true);
setStatus('running');
+
+ // Run first cycle immediately
handleRunCycle();
+
+ // Then schedule subsequent cycles
+ // The interval will call handleRunCycle which checks cycleInProgressRef
+ // to prevent overlapping cycles
autoRunIntervalRef.current = setInterval(() => {
+ console.log('[AlphaArena] Auto-run interval triggered');
handleRunCycle();
}, cycleInterval * 1000);
}
@@ -508,6 +549,8 @@ const AlphaArenaTab: React.FC = () => {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
+ // Reset cycle in progress flag
+ cycleInProgressRef.current = false;
setCompetitionId(null);
setStatus(null);
setCycleCount(0);
@@ -539,6 +582,9 @@ const AlphaArenaTab: React.FC = () => {
abortControllerRef.current = null;
}
+ // Reset cycle in progress flag
+ cycleInProgressRef.current = false;
+
// Reset loading states
setIsLoading(false);
setIsCancelling(false);
@@ -1389,9 +1435,89 @@ const AlphaArenaTab: React.FC = () => {
)}
</div>
- {/* Right Panel - Decisions */}
- <div className="w-[380px] border-l" style={{ borderColor: COLORS.BORDER }}>
- {renderDecisions()}
+ {/* Right Panel - Enhanced Features */}
+ <div className="w-[400px] border-l flex flex-col" style={{ borderColor: COLORS.BORDER }}>
+ {/* Right Panel Tabs */}
+ <div className="flex border-b overflow-x-auto" style={{ borderColor: COLORS.BORDER }}>
+ {[
+ { key: 'decisions', icon: Brain, label: 'Decisions' },
+ { key: 'hitl', icon: Shield, label: 'HITL' },
+ { key: 'sentiment', icon: Newspaper, label: 'Sentiment' },
+ { key: 'metrics', icon: BarChart3, label: 'Metrics' },
+ { key: 'grid', icon: Grid3X3, label: 'Grid' },
+ { key: 'research', icon: FileSearch, label: 'Research' },
+ { key: 'broker', icon: Building, label: 'Broker' },
+ ].map(({ key, icon: Icon, label }) => (
+ <button
+ key={key}
+ onClick={() => setRightPanelTab(key as RightPanelTab)}
+ className="px-3 py-2 text-xs font-medium whitespace-nowrap flex items-center gap-1 transition-colors"
+ style={{
+ backgroundColor: rightPanelTab === key ? COLORS.CARD_BG : 'transparent',
+ color: rightPanelTab === key ? COLORS.ORANGE : COLORS.GRAY,
+ borderBottom: rightPanelTab === key ? `2px solid ${COLORS.ORANGE}` : '2px solid transparent',
+ }}
+ >
+ <Icon size={12} />
+ {label}
+ </button>
+ ))}
+ </div>
+
+ {/* Right Panel Content */}
+ <div className="flex-1 overflow-y-auto">
+ {rightPanelTab === 'decisions' && renderDecisions()}
+ {rightPanelTab === 'hitl' && (
+ <div className="p-3">
+ <HITLApprovalPanel
+ competitionId={competitionId || undefined}
+ onApprovalChange={() => fetchCompetitionData()}
+ />
+ </div>
+ )}
+ {rightPanelTab === 'sentiment' && (
+ <div className="p-3">
+ <SentimentPanel
+ symbol={symbol.split('/')[0]}
+ showMarketMood={true}
+ />
+ </div>
+ )}
+ {rightPanelTab === 'metrics' && competitionId && (
+ <div className="p-3">
+ <PortfolioMetricsPanel
+ competitionId={competitionId}
+ />
+ </div>
+ )}
+ {rightPanelTab === 'metrics' && !competitionId && (
+ <div className="p-8 text-center" style={{ color: COLORS.GRAY }}>
+ <BarChart3 size={32} className="mx-auto mb-2 opacity-30" />
+ <p className="text-sm">Start a competition to view metrics</p>
+ </div>
+ )}
+ {rightPanelTab === 'grid' && (
+ <div className="p-3">
+ <GridStrategyPanel
+ symbol={symbol.split('/')[0]}
+ currentPrice={50000} // This would come from real price data
+ />
+ </div>
+ )}
+ {rightPanelTab === 'research' && (
+ <div className="p-3">
+ <ResearchPanel />
+ </div>
+ )}
+ {rightPanelTab === 'broker' && (
+ <div className="p-3">
+ <BrokerSelector
+ selectedBrokerId={selectedBroker || undefined}
+ onBrokerSelect={(broker) => setSelectedBroker(broker.id)}
+ />
+ </div>
+ )}
+ </div>
</div>
</div>
@@ -1411,8 +1537,12 @@ const AlphaArenaTab: React.FC = () => {
label: `AI Models: ${configuredLLMs.length} available`,
color: COLORS.GRAY,
},
+ ...(selectedBroker ? [{
+ label: `Broker: ${selectedBroker}`,
+ color: COLORS.ORANGE,
+ }] : []),
]}
- statusInfo={`Cycle: ${cycleCount} | Decisions: ${decisions.length}`}
+ statusInfo={`Cycle: ${cycleCount} | Decisions: ${decisions.length} | Panel: ${rightPanelTab.toUpperCase()}`}
backgroundColor={COLORS.PANEL_BG}
borderColor={COLORS.BORDER}
/>
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/BrokerSelector.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/BrokerSelector.tsx
new file mode 100644
index 000000000..fd7bf2277
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/BrokerSelector.tsx
@@ -0,0 +1,453 @@
+/**
+ * Broker Selector Component
+ *
+ * Allows users to select and configure brokers/exchanges for
+ * trading in Alpha Arena. Supports multiple broker types.
+ */
+
+import React, { useState, useEffect, useCallback } from 'react';
+import {
+ Building, RefreshCw, Check, AlertTriangle, Loader2,
+ Globe, DollarSign, Percent, Zap, Settings, ChevronDown,
+ ChevronRight, Search, Star, StarOff,
+} from 'lucide-react';
+import {
+ alphaArenaEnhancedService,
+ type BrokerInfo,
+ type TickerData,
+} from '../services/alphaArenaEnhancedService';
+
+const COLORS = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ BLUE: '#3B82F6',
+ YELLOW: '#EAB308',
+ PURPLE: '#8B5CF6',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ CARD_BG: '#0A0A0A',
+ BORDER: '#2A2A2A',
+};
+
+const BROKER_TYPE_COLORS: Record<string, string> = {
+ crypto: COLORS.ORANGE,
+ stocks: COLORS.BLUE,
+ forex: COLORS.GREEN,
+};
+
+const REGION_FLAGS: Record<string, string> = {
+ global: '🌍',
+ us: '🇺🇸',
+ india: '🇮🇳',
+ europe: '🇪🇺',
+ asia: '🌏',
+};
+
+interface BrokerSelectorProps {
+ selectedBrokerId?: string;
+ onBrokerSelect?: (broker: BrokerInfo) => void;
+ filterType?: 'crypto' | 'stocks' | 'forex';
+ filterRegion?: 'global' | 'us' | 'india' | 'europe' | 'asia';
+}
+
+const BrokerSelector: React.FC<BrokerSelectorProps> = ({
+ selectedBrokerId,
+ onBrokerSelect,
+ filterType,
+ filterRegion,
+}) => {
+ const [brokers, setBrokers] = useState<BrokerInfo[]>([]);
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [searchQuery, setSearchQuery] = useState('');
+ const [selectedBroker, setSelectedBroker] = useState<BrokerInfo | null>(null);
+ const [tickerData, setTickerData] = useState<TickerData | null>(null);
+ const [isLoadingTicker, setIsLoadingTicker] = useState(false);
+ const [expandedBroker, setExpandedBroker] = useState<string | null>(null);
+ const [favorites, setFavorites] = useState<string[]>(() => {
+ const saved = localStorage.getItem('alpha-arena-favorite-brokers');
+ return saved ? JSON.parse(saved) : [];
+ });
+ const [typeFilter, setTypeFilter] = useState<'crypto' | 'stocks' | 'forex' | null>(filterType || null);
+ const [regionFilter, setRegionFilter] = useState<string | null>(filterRegion || null);
+
+ const fetchBrokers = useCallback(async () => {
+ setIsLoading(true);
+ setError(null);
+ try {
+ const result = await alphaArenaEnhancedService.listBrokers(
+ typeFilter || undefined,
+ regionFilter as 'global' | 'us' | 'india' | 'europe' | 'asia' | undefined
+ );
+
+ if (result.success && result.brokers) {
+ setBrokers(result.brokers);
+
+ // Auto-select if selectedBrokerId is provided
+ if (selectedBrokerId) {
+ const broker = result.brokers.find(b => b.id === selectedBrokerId);
+ if (broker) {
+ setSelectedBroker(broker);
+ }
+ }
+ } else {
+ setError(result.error || 'Failed to fetch brokers');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to fetch brokers');
+ } finally {
+ setIsLoading(false);
+ }
+ }, [typeFilter, regionFilter, selectedBrokerId]);
+
+ useEffect(() => {
+ fetchBrokers();
+ }, [fetchBrokers]);
+
+ useEffect(() => {
+ localStorage.setItem('alpha-arena-favorite-brokers', JSON.stringify(favorites));
+ }, [favorites]);
+
+ const handleBrokerSelect = async (broker: BrokerInfo) => {
+ setSelectedBroker(broker);
+ onBrokerSelect?.(broker);
+
+ // Fetch sample ticker data
+ if (broker.default_symbols.length > 0) {
+ setIsLoadingTicker(true);
+ try {
+ const result = await alphaArenaEnhancedService.getBrokerTicker(
+ broker.default_symbols[0],
+ broker.id
+ );
+ if (result.success && result.ticker) {
+ setTickerData(result.ticker);
+ }
+ } catch (err) {
+ console.error('Error fetching ticker:', err);
+ } finally {
+ setIsLoadingTicker(false);
+ }
+ }
+ };
+
+ const toggleFavorite = (brokerId: string, e: React.MouseEvent) => {
+ e.stopPropagation();
+ setFavorites(prev =>
+ prev.includes(brokerId)
+ ? prev.filter(id => id !== brokerId)
+ : [...prev, brokerId]
+ );
+ };
+
+ const filteredBrokers = brokers.filter(broker => {
+ const matchesSearch = broker.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
+ broker.display_name.toLowerCase().includes(searchQuery.toLowerCase());
+ return matchesSearch;
+ });
+
+ const sortedBrokers = [...filteredBrokers].sort((a, b) => {
+ const aFav = favorites.includes(a.id) ? -1 : 0;
+ const bFav = favorites.includes(b.id) ? -1 : 0;
+ if (aFav !== bFav) return aFav - bFav;
+ return a.display_name.localeCompare(b.display_name);
+ });
+
+ const renderBrokerFeatures = (broker: BrokerInfo) => (
+ <div className="flex flex-wrap gap-1 mt-2">
+ {broker.supports_spot && (
+ <span className="text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: COLORS.GREEN + '20', color: COLORS.GREEN }}>
+ Spot
+ </span>
+ )}
+ {broker.supports_margin && (
+ <span className="text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: COLORS.YELLOW + '20', color: COLORS.YELLOW }}>
+ Margin
+ </span>
+ )}
+ {broker.supports_futures && (
+ <span className="text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: COLORS.PURPLE + '20', color: COLORS.PURPLE }}>
+ Futures
+ </span>
+ )}
+ {broker.supports_options && (
+ <span className="text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: COLORS.BLUE + '20', color: COLORS.BLUE }}>
+ Options
+ </span>
+ )}
+ {broker.websocket_enabled && (
+ <span className="text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: COLORS.ORANGE + '20', color: COLORS.ORANGE }}>
+ <Zap size={10} className="inline" /> WS
+ </span>
+ )}
+ </div>
+ );
+
+ return (
+ <div
+ className="rounded-lg overflow-hidden"
+ style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}
+ >
+ {/* Header */}
+ <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>
+ <div className="flex items-center gap-2">
+ <Building size={16} style={{ color: COLORS.ORANGE }} />
+ <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>
+ Broker Selection
+ </span>
+ {selectedBroker && (
+ <span
+ className="px-2 py-0.5 rounded text-xs"
+ style={{ backgroundColor: COLORS.GREEN + '20', color: COLORS.GREEN }}
+ >
+ {selectedBroker.display_name}
+ </span>
+ )}
+ </div>
+ <button
+ onClick={fetchBrokers}
+ disabled={isLoading}
+ className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"
+ >
+ <RefreshCw
+ size={14}
+ className={isLoading ? 'animate-spin' : ''}
+ style={{ color: COLORS.GRAY }}
+ />
+ </button>
+ </div>
+
+ {/* Search and Filters */}
+ <div className="px-4 py-3 border-b space-y-2" style={{ borderColor: COLORS.BORDER }}>
+ <div className="relative">
+ <Search size={14} className="absolute left-2 top-1/2 -translate-y-1/2" style={{ color: COLORS.GRAY }} />
+ <input
+ type="text"
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ placeholder="Search brokers..."
+ className="w-full pl-8 pr-3 py-1.5 rounded text-sm"
+ style={{
+ backgroundColor: COLORS.CARD_BG,
+ color: COLORS.WHITE,
+ border: `1px solid ${COLORS.BORDER}`,
+ }}
+ />
+ </div>
+ <div className="flex gap-2">
+ {/* Type Filter */}
+ <select
+ value={typeFilter || ''}
+ onChange={(e) => setTypeFilter(e.target.value as 'crypto' | 'stocks' | 'forex' || null)}
+ className="flex-1 px-2 py-1 rounded text-xs"
+ style={{
+ backgroundColor: COLORS.CARD_BG,
+ color: COLORS.WHITE,
+ border: `1px solid ${COLORS.BORDER}`,
+ }}
+ >
+ <option value="">All Types</option>
+ <option value="crypto">Crypto</option>
+ <option value="stocks">Stocks</option>
+ <option value="forex">Forex</option>
+ </select>
+ {/* Region Filter */}
+ <select
+ value={regionFilter || ''}
+ onChange={(e) => setRegionFilter(e.target.value || null)}
+ className="flex-1 px-2 py-1 rounded text-xs"
+ style={{
+ backgroundColor: COLORS.CARD_BG,
+ color: COLORS.WHITE,
+ border: `1px solid ${COLORS.BORDER}`,
+ }}
+ >
+ <option value="">All Regions</option>
+ <option value="global">Global</option>
+ <option value="us">United States</option>
+ <option value="india">India</option>
+ <option value="europe">Europe</option>
+ <option value="asia">Asia</option>
+ </select>
+ </div>
+ </div>
+
+ {/* Error */}
+ {error && (
+ <div className="px-4 py-2 flex items-center gap-2" style={{ backgroundColor: COLORS.RED + '10' }}>
+ <AlertTriangle size={14} style={{ color: COLORS.RED }} />
+ <span className="text-xs" style={{ color: COLORS.RED }}>{error}</span>
+ </div>
+ )}
+
+ {/* Broker List */}
+ <div className="max-h-64 overflow-y-auto">
+ {isLoading ? (
+ <div className="flex items-center justify-center py-8">
+ <Loader2 size={24} className="animate-spin" style={{ color: COLORS.ORANGE }} />
+ </div>
+ ) : sortedBrokers.length === 0 ? (
+ <div className="p-8 text-center">
+ <Building size={32} className="mx-auto mb-2 opacity-30" style={{ color: COLORS.GRAY }} />
+ <p className="text-sm" style={{ color: COLORS.GRAY }}>No brokers found</p>
+ <p className="text-xs mt-1" style={{ color: COLORS.GRAY }}>
+ Try adjusting your filters
+ </p>
+ </div>
+ ) : (
+ <div className="divide-y" style={{ borderColor: COLORS.BORDER }}>
+ {sortedBrokers.map((broker) => (
+ <div key={broker.id} className="p-3">
+ <button
+ onClick={() => handleBrokerSelect(broker)}
+ className={`w-full text-left ${selectedBroker?.id === broker.id ? 'ring-1' : ''}`}
+ style={{
+ outlineColor: selectedBroker?.id === broker.id ? COLORS.ORANGE : 'transparent',
+ }}
+ >
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <span className="text-lg">{REGION_FLAGS[broker.region] || '🌐'}</span>
+ <div>
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>
+ {broker.display_name}
+ </span>
+ <span
+ className="text-xs px-1.5 py-0.5 rounded"
+ style={{
+ backgroundColor: BROKER_TYPE_COLORS[broker.broker_type] + '20',
+ color: BROKER_TYPE_COLORS[broker.broker_type],
+ }}
+ >
+ {broker.broker_type}
+ </span>
+ {selectedBroker?.id === broker.id && (
+ <Check size={14} style={{ color: COLORS.GREEN }} />
+ )}
+ </div>
+ <div className="text-xs mt-0.5" style={{ color: COLORS.GRAY }}>
+ Fees: {(broker.maker_fee * 100).toFixed(2)}% / {(broker.taker_fee * 100).toFixed(2)}%
+ {broker.max_leverage > 1 && ` • ${broker.max_leverage}x leverage`}
+ </div>
+ </div>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={(e) => toggleFavorite(broker.id, e)}
+ className="p-1 rounded hover:bg-[#1A1A1A]"
+ >
+ {favorites.includes(broker.id) ? (
+ <Star size={14} style={{ color: COLORS.YELLOW }} fill={COLORS.YELLOW} />
+ ) : (
+ <StarOff size={14} style={{ color: COLORS.GRAY }} />
+ )}
+ </button>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ setExpandedBroker(expandedBroker === broker.id ? null : broker.id);
+ }}
+ className="p-1 rounded hover:bg-[#1A1A1A]"
+ >
+ {expandedBroker === broker.id ? (
+ <ChevronDown size={14} style={{ color: COLORS.GRAY }} />
+ ) : (
+ <ChevronRight size={14} style={{ color: COLORS.GRAY }} />
+ )}
+ </button>
+ </div>
+ </div>
+
+ {/* Features Tags */}
+ {renderBrokerFeatures(broker)}
+ </button>
+
+ {/* Expanded Details */}
+ {expandedBroker === broker.id && (
+ <div className="mt-3 pt-3 border-t" style={{ borderColor: COLORS.BORDER }}>
+ <div className="grid grid-cols-2 gap-2 text-xs">
+ <div>
+ <span style={{ color: COLORS.GRAY }}>Region: </span>
+ <span style={{ color: COLORS.WHITE }}>
+ {REGION_FLAGS[broker.region]} {broker.region.charAt(0).toUpperCase() + broker.region.slice(1)}
+ </span>
+ </div>
+ <div>
+ <span style={{ color: COLORS.GRAY }}>Max Leverage: </span>
+ <span style={{ color: COLORS.WHITE }}>{broker.max_leverage}x</span>
+ </div>
+ </div>
+ <div className="mt-2">
+ <span className="text-xs" style={{ color: COLORS.GRAY }}>Default Symbols:</span>
+ <div className="flex flex-wrap gap-1 mt-1">
+ {broker.default_symbols.slice(0, 5).map((symbol) => (
+ <span
+ key={symbol}
+ className="text-xs px-1.5 py-0.5 rounded"
+ style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}
+ >
+ {symbol}
+ </span>
+ ))}
+ {broker.default_symbols.length > 5 && (
+ <span className="text-xs" style={{ color: COLORS.GRAY }}>
+ +{broker.default_symbols.length - 5} more
+ </span>
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {/* Selected Broker Ticker Preview */}
+ {selectedBroker && tickerData && (
+ <div className="px-4 py-3 border-t" style={{ borderColor: COLORS.BORDER, backgroundColor: COLORS.CARD_BG }}>
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <span className="text-xs" style={{ color: COLORS.GRAY }}>Sample Price:</span>
+ <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>
+ {tickerData.symbol}
+ </span>
+ </div>
+ {isLoadingTicker ? (
+ <Loader2 size={14} className="animate-spin" style={{ color: COLORS.GRAY }} />
+ ) : (
+ <div className="text-right">
+ <div className="text-sm font-bold" style={{ color: COLORS.WHITE }}>
+ ${tickerData.price.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
+ </div>
+ <div className="text-xs" style={{ color: COLORS.GRAY }}>
+ 24h Vol: {tickerData.volume_24h.toLocaleString()}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* Footer */}
+ <div className="px-4 py-2 border-t text-xs flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>
+ <span style={{ color: COLORS.GRAY }}>
+ {sortedBrokers.length} broker{sortedBrokers.length !== 1 ? 's' : ''} available
+ </span>
+ {favorites.length > 0 && (
+ <span style={{ color: COLORS.YELLOW }}>
+ <Star size={10} className="inline mr-1" fill={COLORS.YELLOW} />
+ {favorites.length} favorite{favorites.length !== 1 ? 's' : ''}
+ </span>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default BrokerSelector;
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/GridStrategyPanel.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/GridStrategyPanel.tsx
new file mode 100644
index 000000000..f80337709
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/GridStrategyPanel.tsx
@@ -0,0 +1,493 @@
+/**
+ * Grid Strategy Configuration Panel
+ *
+ * Allows users to create and manage grid trading strategies.
+ * Grid trading places buy/sell orders at regular price intervals.
+ */
+
+import React, { useState, useEffect, useCallback } from 'react';
+import {
+ Grid3X3, Settings, RefreshCw, Play, Pause, AlertTriangle,
+ TrendingUp, TrendingDown, DollarSign, Loader2, Info,
+ ChevronDown, ChevronUp, Plus, Trash2, Check,
+} from 'lucide-react';
+import {
+ alphaArenaEnhancedService,
+ type GridConfig,
+} from '../services/alphaArenaEnhancedService';
+
+const COLORS = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ BLUE: '#3B82F6',
+ YELLOW: '#EAB308',
+ PURPLE: '#8B5CF6',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ CARD_BG: '#0A0A0A',
+ BORDER: '#2A2A2A',
+};
+
+interface GridStrategyPanelProps {
+ symbol?: string;
+ currentPrice?: number;
+ onGridCreated?: (name: string) => void;
+}
+
+interface GridAgentStatus {
+ name: string;
+ symbol: string;
+ gridLevels: number[];
+ triggeredLevels: number[];
+ activeOrders: number;
+ totalProfit: number;
+ tradesExecuted: number;
+ isActive: boolean;
+}
+
+const GridStrategyPanel: React.FC<GridStrategyPanelProps> = ({
+ symbol = 'BTC',
+ currentPrice = 50000,
+ onGridCreated,
+}) => {
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [success, setSuccess] = useState<string | null>(null);
+ const [activeGrids, setActiveGrids] = useState<GridAgentStatus[]>([]);
+ const [showCreateForm, setShowCreateForm] = useState(false);
+ const [expandedGrid, setExpandedGrid] = useState<string | null>(null);
+
+ // Form state
+ const [gridConfig, setGridConfig] = useState<GridConfig>({
+ symbol: symbol,
+ lower_price: currentPrice * 0.9,
+ upper_price: currentPrice * 1.1,
+ num_grids: 10,
+ quantity_per_grid: 0.001,
+ take_profit_pct: 2.0,
+ stop_loss_pct: 5.0,
+ });
+ const [gridName, setGridName] = useState('');
+
+ useEffect(() => {
+ setGridConfig(prev => ({
+ ...prev,
+ symbol,
+ lower_price: currentPrice * 0.9,
+ upper_price: currentPrice * 1.1,
+ }));
+ }, [symbol, currentPrice]);
+
+ const calculateGridSpacing = () => {
+ const range = gridConfig.upper_price - gridConfig.lower_price;
+ return range / (gridConfig.num_grids - 1);
+ };
+
+ const calculateTotalInvestment = () => {
+ return gridConfig.quantity_per_grid * gridConfig.num_grids * gridConfig.lower_price;
+ };
+
+ const generateGridLevels = () => {
+ const levels: number[] = [];
+ const spacing = calculateGridSpacing();
+ for (let i = 0; i < gridConfig.num_grids; i++) {
+ levels.push(gridConfig.lower_price + (spacing * i));
+ }
+ return levels;
+ };
+
+ const handleCreateGrid = async () => {
+ if (!gridName.trim()) {
+ setError('Please enter a name for the grid strategy');
+ return;
+ }
+
+ setIsLoading(true);
+ setError(null);
+ setSuccess(null);
+
+ try {
+ const result = await alphaArenaEnhancedService.createGridAgent(gridName, gridConfig);
+
+ if (result.success) {
+ setSuccess(`Grid strategy "${gridName}" created successfully!`);
+ setShowCreateForm(false);
+ setGridName('');
+ onGridCreated?.(gridName);
+
+ // Add to active grids
+ setActiveGrids(prev => [...prev, {
+ name: gridName,
+ symbol: gridConfig.symbol,
+ gridLevels: result.grid_levels || generateGridLevels(),
+ triggeredLevels: [],
+ activeOrders: 0,
+ totalProfit: 0,
+ tradesExecuted: 0,
+ isActive: true,
+ }]);
+ } else {
+ setError(result.error || 'Failed to create grid strategy');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to create grid strategy');
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const fetchGridStatus = async (name: string) => {
+ try {
+ const result = await alphaArenaEnhancedService.getGridStatus(name);
+ if (result.success && result.grid_status) {
+ setActiveGrids(prev => prev.map(grid =>
+ grid.name === name
+ ? {
+ ...grid,
+ gridLevels: result.grid_status!.grid_levels,
+ triggeredLevels: result.grid_status!.triggered_levels,
+ activeOrders: result.grid_status!.active_orders,
+ totalProfit: result.grid_status!.total_profit,
+ tradesExecuted: result.grid_status!.trades_executed,
+ }
+ : grid
+ ));
+ }
+ } catch (err) {
+ console.error('Error fetching grid status:', err);
+ }
+ };
+
+ const renderGridVisualization = (levels: number[], triggeredLevels: number[]) => {
+ const maxPrice = Math.max(...levels);
+ const minPrice = Math.min(...levels);
+ const range = maxPrice - minPrice;
+
+ return (
+ <div className="relative h-32 my-2">
+ {levels.map((level, idx) => {
+ const position = ((maxPrice - level) / range) * 100;
+ const isTriggered = triggeredLevels.includes(level);
+ const isCurrentPrice = Math.abs(level - currentPrice) < range * 0.05;
+
+ return (
+ <div
+ key={idx}
+ className="absolute left-0 right-0 flex items-center"
+ style={{ top: `${position}%` }}
+ >
+ <div
+ className="h-0.5 flex-1"
+ style={{
+ backgroundColor: isTriggered ? COLORS.GREEN : isCurrentPrice ? COLORS.ORANGE : COLORS.BORDER,
+ }}
+ />
+ <span
+ className="text-xs ml-2 w-16 text-right"
+ style={{
+ color: isTriggered ? COLORS.GREEN : isCurrentPrice ? COLORS.ORANGE : COLORS.GRAY,
+ }}
+ >
+ ${level.toFixed(0)}
+ </span>
+ </div>
+ );
+ })}
+ {/* Current price indicator */}
+ <div
+ className="absolute left-0 flex items-center"
+ style={{
+ top: `${((maxPrice - currentPrice) / range) * 100}%`,
+ transform: 'translateY(-50%)',
+ }}
+ >
+ <div
+ className="w-2 h-2 rounded-full"
+ style={{ backgroundColor: COLORS.ORANGE }}
+ />
+ <span className="text-xs ml-1" style={{ color: COLORS.ORANGE }}>
+ Current
+ </span>
+ </div>
+ </div>
+ );
+ };
+
+ return (
+ <div
+ className="rounded-lg overflow-hidden"
+ style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}
+ >
+ {/* Header */}
+ <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>
+ <div className="flex items-center gap-2">
+ <Grid3X3 size={16} style={{ color: COLORS.BLUE }} />
+ <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>
+ Grid Trading
+ </span>
+ {activeGrids.length > 0 && (
+ <span
+ className="px-2 py-0.5 rounded-full text-xs"
+ style={{ backgroundColor: COLORS.BLUE + '20', color: COLORS.BLUE }}
+ >
+ {activeGrids.length} active
+ </span>
+ )}
+ </div>
+ <button
+ onClick={() => setShowCreateForm(!showCreateForm)}
+ className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"
+ >
+ <Plus size={14} style={{ color: COLORS.GRAY }} />
+ </button>
+ </div>
+
+ {/* Messages */}
+ {error && (
+ <div className="px-4 py-2 flex items-center gap-2" style={{ backgroundColor: COLORS.RED + '10' }}>
+ <AlertTriangle size={14} style={{ color: COLORS.RED }} />
+ <span className="text-xs" style={{ color: COLORS.RED }}>{error}</span>
+ </div>
+ )}
+ {success && (
+ <div className="px-4 py-2 flex items-center gap-2" style={{ backgroundColor: COLORS.GREEN + '10' }}>
+ <Check size={14} style={{ color: COLORS.GREEN }} />
+ <span className="text-xs" style={{ color: COLORS.GREEN }}>{success}</span>
+ </div>
+ )}
+
+ {/* Create Form */}
+ {showCreateForm && (
+ <div className="px-4 py-3 border-b" style={{ borderColor: COLORS.BORDER, backgroundColor: COLORS.CARD_BG }}>
+ <h4 className="text-xs font-medium mb-3" style={{ color: COLORS.WHITE }}>Create Grid Strategy</h4>
+
+ {/* Name Input */}
+ <div className="mb-3">
+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Strategy Name</label>
+ <input
+ type="text"
+ value={gridName}
+ onChange={(e) => setGridName(e.target.value)}
+ placeholder="My Grid Strategy"
+ className="w-full px-2 py-1.5 rounded text-xs"
+ style={{
+ backgroundColor: COLORS.DARK_BG,
+ color: COLORS.WHITE,
+ border: `1px solid ${COLORS.BORDER}`,
+ }}
+ />
+ </div>
+
+ {/* Price Range */}
+ <div className="grid grid-cols-2 gap-2 mb-3">
+ <div>
+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Lower Price</label>
+ <input
+ type="number"
+ value={gridConfig.lower_price}
+ onChange={(e) => setGridConfig(prev => ({ ...prev, lower_price: parseFloat(e.target.value) || 0 }))}
+ className="w-full px-2 py-1.5 rounded text-xs"
+ style={{
+ backgroundColor: COLORS.DARK_BG,
+ color: COLORS.WHITE,
+ border: `1px solid ${COLORS.BORDER}`,
+ }}
+ />
+ </div>
+ <div>
+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Upper Price</label>
+ <input
+ type="number"
+ value={gridConfig.upper_price}
+ onChange={(e) => setGridConfig(prev => ({ ...prev, upper_price: parseFloat(e.target.value) || 0 }))}
+ className="w-full px-2 py-1.5 rounded text-xs"
+ style={{
+ backgroundColor: COLORS.DARK_BG,
+ color: COLORS.WHITE,
+ border: `1px solid ${COLORS.BORDER}`,
+ }}
+ />
+ </div>
+ </div>
+
+ {/* Grid Settings */}
+ <div className="grid grid-cols-2 gap-2 mb-3">
+ <div>
+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Number of Grids</label>
+ <input
+ type="number"
+ value={gridConfig.num_grids}
+ onChange={(e) => setGridConfig(prev => ({ ...prev, num_grids: parseInt(e.target.value) || 5 }))}
+ min={3}
+ max={50}
+ className="w-full px-2 py-1.5 rounded text-xs"
+ style={{
+ backgroundColor: COLORS.DARK_BG,
+ color: COLORS.WHITE,
+ border: `1px solid ${COLORS.BORDER}`,
+ }}
+ />
+ </div>
+ <div>
+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Qty per Grid</label>
+ <input
+ type="number"
+ value={gridConfig.quantity_per_grid}
+ onChange={(e) => setGridConfig(prev => ({ ...prev, quantity_per_grid: parseFloat(e.target.value) || 0.001 }))}
+ step={0.001}
+ className="w-full px-2 py-1.5 rounded text-xs"
+ style={{
+ backgroundColor: COLORS.DARK_BG,
+ color: COLORS.WHITE,
+ border: `1px solid ${COLORS.BORDER}`,
+ }}
+ />
+ </div>
+ </div>
+
+ {/* Summary */}
+ <div className="p-2 rounded mb-3" style={{ backgroundColor: COLORS.DARK_BG }}>
+ <div className="grid grid-cols-2 gap-2 text-xs">
+ <div>
+ <span style={{ color: COLORS.GRAY }}>Grid Spacing: </span>
+ <span style={{ color: COLORS.WHITE }}>${calculateGridSpacing().toFixed(2)}</span>
+ </div>
+ <div>
+ <span style={{ color: COLORS.GRAY }}>Est. Investment: </span>
+ <span style={{ color: COLORS.WHITE }}>${calculateTotalInvestment().toFixed(2)}</span>
+ </div>
+ </div>
+ </div>
+
+ {/* Preview */}
+ <div className="mb-3">
+ <label className="text-xs mb-1 block" style={{ color: COLORS.GRAY }}>Grid Preview</label>
+ {renderGridVisualization(generateGridLevels(), [])}
+ </div>
+
+ {/* Actions */}
+ <div className="flex gap-2">
+ <button
+ onClick={() => setShowCreateForm(false)}
+ className="flex-1 py-1.5 rounded text-xs font-medium"
+ style={{
+ backgroundColor: COLORS.BORDER,
+ color: COLORS.WHITE,
+ }}
+ >
+ Cancel
+ </button>
+ <button
+ onClick={handleCreateGrid}
+ disabled={isLoading}
+ className="flex-1 py-1.5 rounded text-xs font-medium flex items-center justify-center gap-1"
+ style={{
+ backgroundColor: COLORS.BLUE,
+ color: COLORS.WHITE,
+ opacity: isLoading ? 0.5 : 1,
+ }}
+ >
+ {isLoading ? (
+ <Loader2 size={12} className="animate-spin" />
+ ) : (
+ <Play size={12} />
+ )}
+ Create Grid
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Active Grids */}
+ <div className="max-h-64 overflow-y-auto">
+ {activeGrids.length === 0 ? (
+ <div className="p-8 text-center">
+ <Grid3X3 size={32} className="mx-auto mb-2 opacity-30" style={{ color: COLORS.GRAY }} />
+ <p className="text-sm" style={{ color: COLORS.GRAY }}>No active grid strategies</p>
+ <p className="text-xs mt-1" style={{ color: COLORS.GRAY }}>
+ Create a grid to start automated trading
+ </p>
+ </div>
+ ) : (
+ <div className="divide-y" style={{ borderColor: COLORS.BORDER }}>
+ {activeGrids.map((grid) => (
+ <div key={grid.name} className="p-3">
+ <div className="flex items-center justify-between mb-2">
+ <button
+ onClick={() => setExpandedGrid(expandedGrid === grid.name ? null : grid.name)}
+ className="flex items-center gap-2"
+ >
+ {expandedGrid === grid.name ? (
+ <ChevronUp size={12} style={{ color: COLORS.GRAY }} />
+ ) : (
+ <ChevronDown size={12} style={{ color: COLORS.GRAY }} />
+ )}
+ <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>{grid.name}</span>
+ <span
+ className="px-1.5 py-0.5 rounded text-xs"
+ style={{
+ backgroundColor: grid.isActive ? COLORS.GREEN + '20' : COLORS.GRAY + '20',
+ color: grid.isActive ? COLORS.GREEN : COLORS.GRAY,
+ }}
+ >
+ {grid.isActive ? 'Active' : 'Paused'}
+ </span>
+ </button>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => fetchGridStatus(grid.name)}
+ className="p-1 rounded hover:bg-[#1A1A1A]"
+ >
+ <RefreshCw size={12} style={{ color: COLORS.GRAY }} />
+ </button>
+ </div>
+ </div>
+
+ {/* Quick Stats */}
+ <div className="grid grid-cols-3 gap-2 text-xs">
+ <div>
+ <span style={{ color: COLORS.GRAY }}>Trades: </span>
+ <span style={{ color: COLORS.WHITE }}>{grid.tradesExecuted}</span>
+ </div>
+ <div>
+ <span style={{ color: COLORS.GRAY }}>Profit: </span>
+ <span style={{ color: grid.totalProfit >= 0 ? COLORS.GREEN : COLORS.RED }}>
+ ${grid.totalProfit.toFixed(2)}
+ </span>
+ </div>
+ <div>
+ <span style={{ color: COLORS.GRAY }}>Active: </span>
+ <span style={{ color: COLORS.WHITE }}>{grid.activeOrders}</span>
+ </div>
+ </div>
+
+ {/* Expanded View */}
+ {expandedGrid === grid.name && (
+ <div className="mt-3 pt-3 border-t" style={{ borderColor: COLORS.BORDER }}>
+ <div className="text-xs mb-2" style={{ color: COLORS.GRAY }}>Grid Levels</div>
+ {renderGridVisualization(grid.gridLevels, grid.triggeredLevels)}
+ <div className="text-xs mt-2" style={{ color: COLORS.GRAY }}>
+ <Info size={10} className="inline mr-1" />
+ {grid.triggeredLevels.length} of {grid.gridLevels.length} levels triggered
+ </div>
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {/* Footer */}
+ <div className="px-4 py-2 border-t text-xs" style={{ borderColor: COLORS.BORDER, color: COLORS.GRAY }}>
+ <Info size={10} className="inline mr-1" />
+ Grid strategies execute automatically based on price levels
+ </div>
+ </div>
+ );
+};
+
+export default GridStrategyPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/HITLApprovalPanel.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/HITLApprovalPanel.tsx
new file mode 100644
index 000000000..6b40881cb
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/HITLApprovalPanel.tsx
@@ -0,0 +1,374 @@
+/**
+ * HITL Approval Panel - Human-in-the-Loop Trading Approval
+ *
+ * Allows users to review and approve/reject AI trading decisions
+ * before execution. Shows pending approvals with risk levels.
+ */
+
+import React, { useState, useEffect, useCallback } from 'react';
+import {
+ Shield, AlertTriangle, Check, X, Clock, RefreshCw,
+ Settings, ChevronDown, ChevronUp, Loader2,
+ AlertCircle, CheckCircle, Info,
+} from 'lucide-react';
+import {
+ alphaArenaEnhancedService,
+ type ApprovalRequest,
+ type HITLStatus,
+} from '../services/alphaArenaEnhancedService';
+
+const COLORS = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ BLUE: '#3B82F6',
+ YELLOW: '#EAB308',
+ PURPLE: '#8B5CF6',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ CARD_BG: '#0A0A0A',
+ BORDER: '#2A2A2A',
+};
+
+const RISK_COLORS: Record<string, string> = {
+ low: COLORS.GREEN,
+ medium: COLORS.YELLOW,
+ high: COLORS.ORANGE,
+ critical: COLORS.RED,
+};
+
+interface HITLApprovalPanelProps {
+ competitionId?: string;
+ onApprovalChange?: () => void;
+}
+
+const HITLApprovalPanel: React.FC<HITLApprovalPanelProps> = ({
+ competitionId,
+ onApprovalChange,
+}) => {
+ const [hitlStatus, setHitlStatus] = useState<HITLStatus | null>(null);
+ const [pendingApprovals, setPendingApprovals] = useState<ApprovalRequest[]>([]);
+ const [isLoading, setIsLoading] = useState(false);
+ const [isProcessing, setIsProcessing] = useState<string | null>(null);
+ const [showSettings, setShowSettings] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [expandedApproval, setExpandedApproval] = useState<string | null>(null);
+
+ const fetchStatus = useCallback(async () => {
+ setIsLoading(true);
+ setError(null);
+ try {
+ const [statusResult, pendingResult] = await Promise.all([
+ alphaArenaEnhancedService.getHITLStatus(),
+ alphaArenaEnhancedService.getPendingApprovals(),
+ ]);
+
+ if (statusResult.success && statusResult.status) {
+ setHitlStatus(statusResult.status);
+ }
+ if (pendingResult.success && pendingResult.pending_approvals) {
+ setPendingApprovals(pendingResult.pending_approvals);
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to fetch HITL status');
+ } finally {
+ setIsLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ fetchStatus();
+ const interval = setInterval(fetchStatus, 5000);
+ return () => clearInterval(interval);
+ }, [fetchStatus]);
+
+ const handleApprove = async (requestId: string) => {
+ setIsProcessing(requestId);
+ try {
+ const result = await alphaArenaEnhancedService.approveDecision(requestId);
+ if (result.success) {
+ setPendingApprovals(prev => prev.filter(a => a.id !== requestId));
+ onApprovalChange?.();
+ } else {
+ setError(result.error || 'Failed to approve');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to approve');
+ } finally {
+ setIsProcessing(null);
+ }
+ };
+
+ const handleReject = async (requestId: string) => {
+ setIsProcessing(requestId);
+ try {
+ const result = await alphaArenaEnhancedService.rejectDecision(requestId);
+ if (result.success) {
+ setPendingApprovals(prev => prev.filter(a => a.id !== requestId));
+ onApprovalChange?.();
+ } else {
+ setError(result.error || 'Failed to reject');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to reject');
+ } finally {
+ setIsProcessing(null);
+ }
+ };
+
+ const handleToggleRule = async (ruleName: string, currentEnabled: boolean) => {
+ try {
+ const result = await alphaArenaEnhancedService.updateHITLRule(ruleName, !currentEnabled);
+ if (result.success) {
+ fetchStatus();
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to update rule');
+ }
+ };
+
+ const getTimeRemaining = (expiresAt: string | null): string => {
+ if (!expiresAt) return 'No expiry';
+ const remaining = new Date(expiresAt).getTime() - Date.now();
+ if (remaining <= 0) return 'Expired';
+ const seconds = Math.floor(remaining / 1000);
+ if (seconds < 60) return `${seconds}s`;
+ const minutes = Math.floor(seconds / 60);
+ return `${minutes}m ${seconds % 60}s`;
+ };
+
+ return (
+ <div
+ className="rounded-lg overflow-hidden"
+ style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}
+ >
+ {/* Header */}
+ <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>
+ <div className="flex items-center gap-2">
+ <Shield size={16} style={{ color: COLORS.ORANGE }} />
+ <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>
+ HITL Approval
+ </span>
+ {pendingApprovals.length > 0 && (
+ <span
+ className="px-2 py-0.5 rounded-full text-xs font-medium"
+ style={{ backgroundColor: COLORS.RED + '20', color: COLORS.RED }}
+ >
+ {pendingApprovals.length} pending
+ </span>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => setShowSettings(!showSettings)}
+ className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"
+ title="Settings"
+ >
+ <Settings size={14} style={{ color: COLORS.GRAY }} />
+ </button>
+ <button
+ onClick={fetchStatus}
+ disabled={isLoading}
+ className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"
+ title="Refresh"
+ >
+ <RefreshCw
+ size={14}
+ className={isLoading ? 'animate-spin' : ''}
+ style={{ color: COLORS.GRAY }}
+ />
+ </button>
+ </div>
+ </div>
+
+ {/* Error */}
+ {error && (
+ <div className="px-4 py-2 flex items-center gap-2" style={{ backgroundColor: COLORS.RED + '10' }}>
+ <AlertCircle size={14} style={{ color: COLORS.RED }} />
+ <span className="text-xs" style={{ color: COLORS.RED }}>{error}</span>
+ <button onClick={() => setError(null)} className="ml-auto">
+ <X size={12} style={{ color: COLORS.RED }} />
+ </button>
+ </div>
+ )}
+
+ {/* Settings Panel */}
+ {showSettings && hitlStatus && (
+ <div className="px-4 py-3 border-b" style={{ borderColor: COLORS.BORDER, backgroundColor: COLORS.CARD_BG }}>
+ <h4 className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>Approval Rules</h4>
+ <div className="space-y-2">
+ {hitlStatus.rules.map(rule => (
+ <div key={rule.name} className="flex items-center justify-between">
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ <span className="text-xs" style={{ color: COLORS.WHITE }}>{rule.name}</span>
+ <span
+ className="text-xs px-1.5 py-0.5 rounded"
+ style={{ backgroundColor: RISK_COLORS[rule.risk_level] + '20', color: RISK_COLORS[rule.risk_level] }}
+ >
+ {rule.risk_level}
+ </span>
+ </div>
+ <p className="text-xs truncate" style={{ color: COLORS.GRAY }}>{rule.description}</p>
+ </div>
+ <button
+ onClick={() => handleToggleRule(rule.name, rule.enabled)}
+ className={`w-10 h-5 rounded-full transition-colors relative ${rule.enabled ? 'bg-green-500' : 'bg-gray-600'}`}
+ >
+ <div
+ className={`w-4 h-4 rounded-full bg-white absolute top-0.5 transition-transform ${rule.enabled ? 'translate-x-5' : 'translate-x-0.5'}`}
+ />
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Pending Approvals */}
+ <div className="max-h-80 overflow-y-auto">
+ {pendingApprovals.length === 0 ? (
+ <div className="p-8 text-center">
+ <CheckCircle size={32} className="mx-auto mb-2" style={{ color: COLORS.GREEN, opacity: 0.5 }} />
+ <p className="text-sm" style={{ color: COLORS.GRAY }}>No pending approvals</p>
+ <p className="text-xs mt-1" style={{ color: COLORS.GRAY }}>All trading decisions approved or auto-approved</p>
+ </div>
+ ) : (
+ <div className="divide-y" style={{ borderColor: COLORS.BORDER }}>
+ {pendingApprovals.map(approval => (
+ <div key={approval.id} className="p-3">
+ {/* Header */}
+ <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center gap-2">
+ <AlertTriangle
+ size={14}
+ style={{ color: RISK_COLORS[approval.risk_level] }}
+ />
+ <span className="text-xs font-medium" style={{ color: COLORS.WHITE }}>
+ {approval.decision.model_name}
+ </span>
+ <span
+ className="text-xs px-1.5 py-0.5 rounded font-medium"
+ style={{
+ backgroundColor: approval.decision.action === 'buy' ? COLORS.GREEN + '20' :
+ approval.decision.action === 'sell' ? COLORS.RED + '20' : COLORS.GRAY + '20',
+ color: approval.decision.action === 'buy' ? COLORS.GREEN :
+ approval.decision.action === 'sell' ? COLORS.RED : COLORS.GRAY,
+ }}
+ >
+ {approval.decision.action.toUpperCase()}
+ </span>
+ </div>
+ <div className="flex items-center gap-1 text-xs" style={{ color: COLORS.GRAY }}>
+ <Clock size={10} />
+ {getTimeRemaining(approval.expires_at)}
+ </div>
+ </div>
+
+ {/* Trade Details */}
+ <div className="grid grid-cols-3 gap-2 mb-2 text-xs">
+ <div>
+ <span style={{ color: COLORS.GRAY }}>Symbol: </span>
+ <span style={{ color: COLORS.WHITE }}>{approval.decision.symbol}</span>
+ </div>
+ <div>
+ <span style={{ color: COLORS.GRAY }}>Qty: </span>
+ <span style={{ color: COLORS.WHITE }}>{approval.decision.quantity.toFixed(4)}</span>
+ </div>
+ <div>
+ <span style={{ color: COLORS.GRAY }}>Conf: </span>
+ <span style={{ color: COLORS.WHITE }}>{(approval.decision.confidence * 100).toFixed(0)}%</span>
+ </div>
+ </div>
+
+ {/* Risk Level */}
+ <div
+ className="text-xs px-2 py-1 rounded mb-2"
+ style={{
+ backgroundColor: RISK_COLORS[approval.risk_level] + '10',
+ color: RISK_COLORS[approval.risk_level],
+ }}
+ >
+ {approval.reason.split('\n').slice(0, 2).join(' • ')}
+ </div>
+
+ {/* Expandable Reasoning */}
+ <button
+ onClick={() => setExpandedApproval(expandedApproval === approval.id ? null : approval.id)}
+ className="flex items-center gap-1 text-xs mb-2"
+ style={{ color: COLORS.GRAY }}
+ >
+ {expandedApproval === approval.id ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
+ {expandedApproval === approval.id ? 'Hide' : 'Show'} reasoning
+ </button>
+
+ {expandedApproval === approval.id && (
+ <div
+ className="text-xs p-2 rounded mb-2"
+ style={{ backgroundColor: COLORS.CARD_BG, color: COLORS.GRAY }}
+ >
+ {approval.decision.reasoning || 'No reasoning provided'}
+ </div>
+ )}
+
+ {/* Actions */}
+ <div className="flex gap-2">
+ <button
+ onClick={() => handleApprove(approval.id)}
+ disabled={isProcessing === approval.id}
+ className="flex-1 py-1.5 rounded text-xs font-medium flex items-center justify-center gap-1"
+ style={{
+ backgroundColor: COLORS.GREEN,
+ color: COLORS.DARK_BG,
+ opacity: isProcessing === approval.id ? 0.5 : 1,
+ }}
+ >
+ {isProcessing === approval.id ? (
+ <Loader2 size={12} className="animate-spin" />
+ ) : (
+ <Check size={12} />
+ )}
+ Approve
+ </button>
+ <button
+ onClick={() => handleReject(approval.id)}
+ disabled={isProcessing === approval.id}
+ className="flex-1 py-1.5 rounded text-xs font-medium flex items-center justify-center gap-1"
+ style={{
+ backgroundColor: COLORS.RED,
+ color: COLORS.WHITE,
+ opacity: isProcessing === approval.id ? 0.5 : 1,
+ }}
+ >
+ {isProcessing === approval.id ? (
+ <Loader2 size={12} className="animate-spin" />
+ ) : (
+ <X size={12} />
+ )}
+ Reject
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {/* Footer Stats */}
+ {hitlStatus && (
+ <div className="px-4 py-2 border-t flex items-center justify-between text-xs" style={{ borderColor: COLORS.BORDER }}>
+ <span style={{ color: COLORS.GRAY }}>
+ Rules: {hitlStatus.rules.filter(r => r.enabled).length}/{hitlStatus.rules.length} active
+ </span>
+ <span style={{ color: COLORS.GRAY }}>
+ History: {hitlStatus.history_count} decisions
+ </span>
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default HITLApprovalPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/PortfolioMetricsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/PortfolioMetricsPanel.tsx
new file mode 100644
index 000000000..6d4324b2e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/PortfolioMetricsPanel.tsx
@@ -0,0 +1,425 @@
+/**
+ * Portfolio Metrics Panel
+ *
+ * Displays comprehensive portfolio analytics including returns,
+ * risk metrics (Sharpe, Sortino), and performance statistics.
+ */
+
+import React, { useState, useEffect, useCallback } from 'react';
+import {
+ TrendingUp, TrendingDown, BarChart3, RefreshCw,
+ Target, AlertTriangle, Award, Percent, Loader2,
+ ChevronDown, ChevronUp, Info,
+} from 'lucide-react';
+import {
+ alphaArenaEnhancedService,
+ type PortfolioMetrics,
+} from '../services/alphaArenaEnhancedService';
+
+const COLORS = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ BLUE: '#3B82F6',
+ YELLOW: '#EAB308',
+ PURPLE: '#8B5CF6',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ CARD_BG: '#0A0A0A',
+ BORDER: '#2A2A2A',
+};
+
+interface PortfolioMetricsPanelProps {
+ competitionId: string;
+ modelName?: string;
+ onModelSelect?: (model: string) => void;
+}
+
+interface MetricCardProps {
+ label: string;
+ value: string | number;
+ icon: React.ReactNode;
+ color?: string;
+ tooltip?: string;
+ isPercentage?: boolean;
+}
+
+const MetricCard: React.FC<MetricCardProps> = ({
+ label,
+ value,
+ icon,
+ color = COLORS.WHITE,
+ tooltip,
+ isPercentage = false,
+}) => {
+ const [showTooltip, setShowTooltip] = useState(false);
+
+ const displayValue = typeof value === 'number'
+ ? isPercentage
+ ? `${(value * 100).toFixed(2)}%`
+ : value.toFixed(2)
+ : value;
+
+ return (
+ <div
+ className="p-3 rounded-lg relative"
+ style={{ backgroundColor: COLORS.CARD_BG }}
+ onMouseEnter={() => setShowTooltip(true)}
+ onMouseLeave={() => setShowTooltip(false)}
+ >
+ <div className="flex items-center justify-between mb-1">
+ <span className="text-xs" style={{ color: COLORS.GRAY }}>{label}</span>
+ <div style={{ color }}>{icon}</div>
+ </div>
+ <div className="text-lg font-bold" style={{ color }}>
+ {displayValue}
+ </div>
+ {tooltip && showTooltip && (
+ <div
+ className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-2 py-1 rounded text-xs whitespace-nowrap z-10"
+ style={{ backgroundColor: COLORS.BORDER, color: COLORS.WHITE }}
+ >
+ {tooltip}
+ </div>
+ )}
+ </div>
+ );
+};
+
+const PortfolioMetricsPanel: React.FC<PortfolioMetricsPanelProps> = ({
+ competitionId,
+ modelName,
+ onModelSelect,
+}) => {
+ const [metrics, setMetrics] = useState<PortfolioMetrics | null>(null);
+ const [allMetrics, setAllMetrics] = useState<Record<string, PortfolioMetrics> | null>(null);
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [selectedModel, setSelectedModel] = useState<string | null>(modelName || null);
+ const [expandedSection, setExpandedSection] = useState<string | null>('returns');
+
+ const fetchMetrics = useCallback(async () => {
+ if (!competitionId) return;
+
+ setIsLoading(true);
+ setError(null);
+ try {
+ const result = await alphaArenaEnhancedService.getPortfolioMetrics(
+ competitionId,
+ selectedModel || undefined
+ );
+
+ if (result.success && result.metrics) {
+ if (selectedModel) {
+ setMetrics(result.metrics as PortfolioMetrics);
+ setAllMetrics(null);
+ } else {
+ setAllMetrics(result.metrics as Record<string, PortfolioMetrics>);
+ setMetrics(null);
+ }
+ } else {
+ setError(result.error || 'Failed to fetch metrics');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to fetch metrics');
+ } finally {
+ setIsLoading(false);
+ }
+ }, [competitionId, selectedModel]);
+
+ useEffect(() => {
+ fetchMetrics();
+ }, [fetchMetrics]);
+
+ const handleModelChange = (model: string | null) => {
+ setSelectedModel(model);
+ onModelSelect?.(model || '');
+ };
+
+ const toggleSection = (section: string) => {
+ setExpandedSection(expandedSection === section ? null : section);
+ };
+
+ const getReturnColor = (value: number) => {
+ if (value > 0) return COLORS.GREEN;
+ if (value < 0) return COLORS.RED;
+ return COLORS.GRAY;
+ };
+
+ const renderMetricsSection = (metricsData: PortfolioMetrics) => (
+ <>
+ {/* Returns Section */}
+ <div className="border-b" style={{ borderColor: COLORS.BORDER }}>
+ <button
+ onClick={() => toggleSection('returns')}
+ className="w-full px-4 py-2 flex items-center justify-between"
+ >
+ <div className="flex items-center gap-2">
+ <TrendingUp size={14} style={{ color: COLORS.GREEN }} />
+ <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>Returns</span>
+ </div>
+ {expandedSection === 'returns' ? (
+ <ChevronUp size={14} style={{ color: COLORS.GRAY }} />
+ ) : (
+ <ChevronDown size={14} style={{ color: COLORS.GRAY }} />
+ )}
+ </button>
+ {expandedSection === 'returns' && (
+ <div className="px-4 pb-3 grid grid-cols-2 gap-2">
+ <MetricCard
+ label="Total Return"
+ value={metricsData.total_return}
+ icon={<Percent size={14} />}
+ color={getReturnColor(metricsData.total_return)}
+ isPercentage
+ tooltip="Overall portfolio return"
+ />
+ <MetricCard
+ label="Win Rate"
+ value={metricsData.win_rate}
+ icon={<Target size={14} />}
+ color={metricsData.win_rate > 0.5 ? COLORS.GREEN : COLORS.RED}
+ isPercentage
+ tooltip="Percentage of winning trades"
+ />
+ <MetricCard
+ label="Profit Factor"
+ value={metricsData.profit_factor}
+ icon={<Award size={14} />}
+ color={metricsData.profit_factor > 1 ? COLORS.GREEN : COLORS.RED}
+ tooltip="Gross profit / Gross loss"
+ />
+ <MetricCard
+ label="Expectancy"
+ value={`$${metricsData.expectancy.toFixed(2)}`}
+ icon={<BarChart3 size={14} />}
+ color={metricsData.expectancy > 0 ? COLORS.GREEN : COLORS.RED}
+ tooltip="Expected profit per trade"
+ />
+ </div>
+ )}
+ </div>
+
+ {/* Risk Metrics Section */}
+ <div className="border-b" style={{ borderColor: COLORS.BORDER }}>
+ <button
+ onClick={() => toggleSection('risk')}
+ className="w-full px-4 py-2 flex items-center justify-between"
+ >
+ <div className="flex items-center gap-2">
+ <AlertTriangle size={14} style={{ color: COLORS.YELLOW }} />
+ <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>Risk Metrics</span>
+ </div>
+ {expandedSection === 'risk' ? (
+ <ChevronUp size={14} style={{ color: COLORS.GRAY }} />
+ ) : (
+ <ChevronDown size={14} style={{ color: COLORS.GRAY }} />
+ )}
+ </button>
+ {expandedSection === 'risk' && (
+ <div className="px-4 pb-3 grid grid-cols-2 gap-2">
+ <MetricCard
+ label="Sharpe Ratio"
+ value={metricsData.sharpe_ratio}
+ icon={<BarChart3 size={14} />}
+ color={metricsData.sharpe_ratio > 1 ? COLORS.GREEN : metricsData.sharpe_ratio > 0 ? COLORS.YELLOW : COLORS.RED}
+ tooltip="Risk-adjusted return (> 1 is good)"
+ />
+ <MetricCard
+ label="Sortino Ratio"
+ value={metricsData.sortino_ratio}
+ icon={<BarChart3 size={14} />}
+ color={metricsData.sortino_ratio > 1 ? COLORS.GREEN : metricsData.sortino_ratio > 0 ? COLORS.YELLOW : COLORS.RED}
+ tooltip="Downside risk-adjusted return"
+ />
+ <MetricCard
+ label="Max Drawdown"
+ value={metricsData.max_drawdown_pct}
+ icon={<TrendingDown size={14} />}
+ color={COLORS.RED}
+ isPercentage
+ tooltip="Largest peak-to-trough decline"
+ />
+ <MetricCard
+ label="Volatility"
+ value={metricsData.volatility}
+ icon={<AlertTriangle size={14} />}
+ color={metricsData.volatility > 0.3 ? COLORS.RED : COLORS.YELLOW}
+ isPercentage
+ tooltip="Standard deviation of returns"
+ />
+ </div>
+ )}
+ </div>
+
+ {/* Trade Statistics Section */}
+ <div>
+ <button
+ onClick={() => toggleSection('trades')}
+ className="w-full px-4 py-2 flex items-center justify-between"
+ >
+ <div className="flex items-center gap-2">
+ <BarChart3 size={14} style={{ color: COLORS.BLUE }} />
+ <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>Trade Statistics</span>
+ </div>
+ {expandedSection === 'trades' ? (
+ <ChevronUp size={14} style={{ color: COLORS.GRAY }} />
+ ) : (
+ <ChevronDown size={14} style={{ color: COLORS.GRAY }} />
+ )}
+ </button>
+ {expandedSection === 'trades' && (
+ <div className="px-4 pb-3">
+ <div className="grid grid-cols-3 gap-2 mb-3">
+ <div className="text-center p-2 rounded" style={{ backgroundColor: COLORS.CARD_BG }}>
+ <div className="text-lg font-bold" style={{ color: COLORS.WHITE }}>
+ {metricsData.total_trades}
+ </div>
+ <div className="text-xs" style={{ color: COLORS.GRAY }}>Total</div>
+ </div>
+ <div className="text-center p-2 rounded" style={{ backgroundColor: COLORS.GREEN + '10' }}>
+ <div className="text-lg font-bold" style={{ color: COLORS.GREEN }}>
+ {metricsData.winning_trades}
+ </div>
+ <div className="text-xs" style={{ color: COLORS.GRAY }}>Wins</div>
+ </div>
+ <div className="text-center p-2 rounded" style={{ backgroundColor: COLORS.RED + '10' }}>
+ <div className="text-lg font-bold" style={{ color: COLORS.RED }}>
+ {metricsData.losing_trades}
+ </div>
+ <div className="text-xs" style={{ color: COLORS.GRAY }}>Losses</div>
+ </div>
+ </div>
+ <div className="grid grid-cols-2 gap-2">
+ <MetricCard
+ label="Avg Win"
+ value={`$${metricsData.avg_win.toFixed(2)}`}
+ icon={<TrendingUp size={14} />}
+ color={COLORS.GREEN}
+ tooltip="Average winning trade"
+ />
+ <MetricCard
+ label="Avg Loss"
+ value={`$${Math.abs(metricsData.avg_loss).toFixed(2)}`}
+ icon={<TrendingDown size={14} />}
+ color={COLORS.RED}
+ tooltip="Average losing trade"
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ </>
+ );
+
+ return (
+ <div
+ className="rounded-lg overflow-hidden"
+ style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}
+ >
+ {/* Header */}
+ <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>
+ <div className="flex items-center gap-2">
+ <BarChart3 size={16} style={{ color: COLORS.PURPLE }} />
+ <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>
+ Portfolio Metrics
+ </span>
+ </div>
+ <button
+ onClick={fetchMetrics}
+ disabled={isLoading}
+ className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"
+ >
+ <RefreshCw
+ size={14}
+ className={isLoading ? 'animate-spin' : ''}
+ style={{ color: COLORS.GRAY }}
+ />
+ </button>
+ </div>
+
+ {/* Model Selector */}
+ {allMetrics && Object.keys(allMetrics).length > 0 && (
+ <div className="px-4 py-2 border-b" style={{ borderColor: COLORS.BORDER }}>
+ <select
+ value={selectedModel || ''}
+ onChange={(e) => handleModelChange(e.target.value || null)}
+ className="w-full px-2 py-1.5 rounded text-xs"
+ style={{
+ backgroundColor: COLORS.CARD_BG,
+ color: COLORS.WHITE,
+ border: `1px solid ${COLORS.BORDER}`,
+ }}
+ >
+ <option value="">All Models</option>
+ {Object.keys(allMetrics).map((model) => (
+ <option key={model} value={model}>{model}</option>
+ ))}
+ </select>
+ </div>
+ )}
+
+ {/* Content */}
+ <div className="max-h-96 overflow-y-auto">
+ {error && (
+ <div className="px-4 py-3 flex items-center gap-2" style={{ backgroundColor: COLORS.RED + '10' }}>
+ <AlertTriangle size={14} style={{ color: COLORS.RED }} />
+ <span className="text-xs" style={{ color: COLORS.RED }}>{error}</span>
+ </div>
+ )}
+
+ {isLoading ? (
+ <div className="flex items-center justify-center py-8">
+ <Loader2 size={24} className="animate-spin" style={{ color: COLORS.ORANGE }} />
+ </div>
+ ) : metrics ? (
+ renderMetricsSection(metrics)
+ ) : allMetrics && Object.keys(allMetrics).length > 0 ? (
+ <div className="p-4">
+ <div className="text-xs mb-3" style={{ color: COLORS.GRAY }}>
+ <Info size={12} className="inline mr-1" />
+ Showing overview for {Object.keys(allMetrics).length} models
+ </div>
+ <div className="space-y-2">
+ {Object.entries(allMetrics).map(([model, modelMetrics]) => (
+ <button
+ key={model}
+ onClick={() => handleModelChange(model)}
+ className="w-full p-3 rounded flex items-center justify-between transition-colors hover:bg-[#1A1A1A]"
+ style={{ backgroundColor: COLORS.CARD_BG }}
+ >
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>{model}</span>
+ </div>
+ <div className="flex items-center gap-4 text-xs">
+ <span style={{ color: getReturnColor(modelMetrics.total_return) }}>
+ {(modelMetrics.total_return * 100).toFixed(1)}%
+ </span>
+ <span style={{ color: COLORS.GRAY }}>
+ {modelMetrics.total_trades} trades
+ </span>
+ <span style={{ color: modelMetrics.sharpe_ratio > 1 ? COLORS.GREEN : COLORS.GRAY }}>
+ SR: {modelMetrics.sharpe_ratio.toFixed(2)}
+ </span>
+ </div>
+ </button>
+ ))}
+ </div>
+ </div>
+ ) : (
+ <div className="p-8 text-center">
+ <BarChart3 size={32} className="mx-auto mb-2 opacity-30" style={{ color: COLORS.GRAY }} />
+ <p className="text-sm" style={{ color: COLORS.GRAY }}>No metrics available</p>
+ <p className="text-xs mt-1" style={{ color: COLORS.GRAY }}>
+ Start a competition to see portfolio metrics
+ </p>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default PortfolioMetricsPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/ResearchPanel.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/ResearchPanel.tsx
new file mode 100644
index 000000000..20928b7c6
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/ResearchPanel.tsx
@@ -0,0 +1,453 @@
+/**
+ * Research Panel - SEC Filings and Company Research
+ *
+ * Displays company research including SEC filings, financials,
+ * risk factors, and AI-generated summaries.
+ */
+
+import React, { useState, useCallback } from 'react';
+import {
+ FileText, Search, RefreshCw, AlertTriangle, ExternalLink,
+ Building2, DollarSign, TrendingUp, Loader2, ChevronDown,
+ ChevronUp, Calendar, FileSearch, Shield, BarChart3,
+} from 'lucide-react';
+import {
+ alphaArenaEnhancedService,
+ type ResearchReport,
+} from '../services/alphaArenaEnhancedService';
+
+const COLORS = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ BLUE: '#3B82F6',
+ YELLOW: '#EAB308',
+ PURPLE: '#8B5CF6',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ CARD_BG: '#0A0A0A',
+ BORDER: '#2A2A2A',
+};
+
+interface ResearchPanelProps {
+ initialTicker?: string;
+ onResearchLoaded?: (ticker: string) => void;
+}
+
+const FORM_TYPE_COLORS: Record<string, string> = {
+ '10-K': COLORS.BLUE,
+ '10-Q': COLORS.PURPLE,
+ '8-K': COLORS.ORANGE,
+ '4': COLORS.GREEN,
+ 'DEF 14A': COLORS.YELLOW,
+};
+
+const ResearchPanel: React.FC<ResearchPanelProps> = ({
+ initialTicker = '',
+ onResearchLoaded,
+}) => {
+ const [ticker, setTicker] = useState(initialTicker);
+ const [searchTicker, setSearchTicker] = useState(initialTicker);
+ const [report, setReport] = useState<ResearchReport | null>(null);
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [expandedSection, setExpandedSection] = useState<string | null>('filings');
+ const [selectedFormTypes, setSelectedFormTypes] = useState<string[]>([]);
+
+ const fetchResearch = useCallback(async (tickerToFetch: string) => {
+ if (!tickerToFetch.trim()) {
+ setError('Please enter a ticker symbol');
+ return;
+ }
+
+ setIsLoading(true);
+ setError(null);
+ setTicker(tickerToFetch.toUpperCase());
+
+ try {
+ const result = await alphaArenaEnhancedService.getResearch(tickerToFetch);
+
+ if (result.success && result.report) {
+ setReport(result.report);
+ onResearchLoaded?.(tickerToFetch);
+ } else {
+ setError(result.error || 'Failed to fetch research');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to fetch research');
+ } finally {
+ setIsLoading(false);
+ }
+ }, [onResearchLoaded]);
+
+ const handleSearch = (e: React.FormEvent) => {
+ e.preventDefault();
+ fetchResearch(searchTicker);
+ };
+
+ const toggleSection = (section: string) => {
+ setExpandedSection(expandedSection === section ? null : section);
+ };
+
+ const formatDate = (dateStr: string) => {
+ try {
+ return new Date(dateStr).toLocaleDateString();
+ } catch {
+ return dateStr;
+ }
+ };
+
+ const formatCurrency = (value: number | null) => {
+ if (value === null) return 'N/A';
+ if (Math.abs(value) >= 1e9) return `$${(value / 1e9).toFixed(2)}B`;
+ if (Math.abs(value) >= 1e6) return `$${(value / 1e6).toFixed(2)}M`;
+ return `$${value.toLocaleString()}`;
+ };
+
+ const filterFilings = (filings: ResearchReport['recent_filings']) => {
+ if (selectedFormTypes.length === 0) return filings;
+ return filings.filter(f => selectedFormTypes.includes(f.form_type));
+ };
+
+ return (
+ <div
+ className="rounded-lg overflow-hidden"
+ style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}
+ >
+ {/* Header */}
+ <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>
+ <div className="flex items-center gap-2">
+ <FileSearch size={16} style={{ color: COLORS.YELLOW }} />
+ <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>
+ Research & SEC Filings
+ </span>
+ </div>
+ {report && (
+ <button
+ onClick={() => fetchResearch(ticker)}
+ disabled={isLoading}
+ className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"
+ >
+ <RefreshCw
+ size={14}
+ className={isLoading ? 'animate-spin' : ''}
+ style={{ color: COLORS.GRAY }}
+ />
+ </button>
+ )}
+ </div>
+
+ {/* Search Bar */}
+ <form onSubmit={handleSearch} className="px-4 py-3 border-b" style={{ borderColor: COLORS.BORDER }}>
+ <div className="flex gap-2">
+ <input
+ type="text"
+ value={searchTicker}
+ onChange={(e) => setSearchTicker(e.target.value.toUpperCase())}
+ placeholder="Enter ticker (e.g., AAPL)"
+ className="flex-1 px-3 py-1.5 rounded text-sm"
+ style={{
+ backgroundColor: COLORS.CARD_BG,
+ color: COLORS.WHITE,
+ border: `1px solid ${COLORS.BORDER}`,
+ }}
+ />
+ <button
+ type="submit"
+ disabled={isLoading}
+ className="px-4 py-1.5 rounded text-sm font-medium flex items-center gap-1"
+ style={{
+ backgroundColor: COLORS.ORANGE,
+ color: COLORS.DARK_BG,
+ opacity: isLoading ? 0.5 : 1,
+ }}
+ >
+ {isLoading ? (
+ <Loader2 size={14} className="animate-spin" />
+ ) : (
+ <Search size={14} />
+ )}
+ Search
+ </button>
+ </div>
+ </form>
+
+ {/* Error */}
+ {error && (
+ <div className="px-4 py-2 flex items-center gap-2" style={{ backgroundColor: COLORS.RED + '10' }}>
+ <AlertTriangle size={14} style={{ color: COLORS.RED }} />
+ <span className="text-xs" style={{ color: COLORS.RED }}>{error}</span>
+ </div>
+ )}
+
+ {/* Content */}
+ <div className="max-h-96 overflow-y-auto">
+ {isLoading ? (
+ <div className="flex items-center justify-center py-8">
+ <Loader2 size={24} className="animate-spin" style={{ color: COLORS.ORANGE }} />
+ </div>
+ ) : report ? (
+ <>
+ {/* Company Info */}
+ {report.company_info && (
+ <div className="px-4 py-3 border-b" style={{ borderColor: COLORS.BORDER }}>
+ <div className="flex items-center gap-2 mb-2">
+ <Building2 size={14} style={{ color: COLORS.BLUE }} />
+ <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>
+ {report.company_info.name}
+ </span>
+ <span className="text-xs px-2 py-0.5 rounded" style={{ backgroundColor: COLORS.BORDER, color: COLORS.GRAY }}>
+ {report.company_info.ticker}
+ </span>
+ </div>
+ <div className="grid grid-cols-2 gap-2 text-xs">
+ <div>
+ <span style={{ color: COLORS.GRAY }}>Industry: </span>
+ <span style={{ color: COLORS.WHITE }}>{report.company_info.industry || 'N/A'}</span>
+ </div>
+ <div>
+ <span style={{ color: COLORS.GRAY }}>CIK: </span>
+ <span style={{ color: COLORS.WHITE }}>{report.company_info.cik}</span>
+ </div>
+ <div>
+ <span style={{ color: COLORS.GRAY }}>State: </span>
+ <span style={{ color: COLORS.WHITE }}>{report.company_info.state || 'N/A'}</span>
+ </div>
+ <div>
+ <span style={{ color: COLORS.GRAY }}>Fiscal Year End: </span>
+ <span style={{ color: COLORS.WHITE }}>{report.company_info.fiscal_year_end || 'N/A'}</span>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Summary */}
+ {report.summary && (
+ <div className="px-4 py-3 border-b" style={{ borderColor: COLORS.BORDER }}>
+ <p className="text-xs leading-relaxed" style={{ color: COLORS.GRAY }}>
+ {report.summary}
+ </p>
+ </div>
+ )}
+
+ {/* SEC Filings Section */}
+ <div className="border-b" style={{ borderColor: COLORS.BORDER }}>
+ <button
+ onClick={() => toggleSection('filings')}
+ className="w-full px-4 py-2 flex items-center justify-between"
+ >
+ <div className="flex items-center gap-2">
+ <FileText size={14} style={{ color: COLORS.ORANGE }} />
+ <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>
+ SEC Filings ({report.recent_filings.length})
+ </span>
+ </div>
+ {expandedSection === 'filings' ? (
+ <ChevronUp size={14} style={{ color: COLORS.GRAY }} />
+ ) : (
+ <ChevronDown size={14} style={{ color: COLORS.GRAY }} />
+ )}
+ </button>
+ {expandedSection === 'filings' && (
+ <div className="px-4 pb-3">
+ {/* Form Type Filters */}
+ <div className="flex flex-wrap gap-1 mb-2">
+ {['10-K', '10-Q', '8-K', '4', 'DEF 14A'].map((formType) => (
+ <button
+ key={formType}
+ onClick={() => {
+ setSelectedFormTypes(prev =>
+ prev.includes(formType)
+ ? prev.filter(t => t !== formType)
+ : [...prev, formType]
+ );
+ }}
+ className="px-2 py-0.5 rounded text-xs"
+ style={{
+ backgroundColor: selectedFormTypes.includes(formType)
+ ? (FORM_TYPE_COLORS[formType] || COLORS.GRAY) + '30'
+ : COLORS.CARD_BG,
+ color: selectedFormTypes.includes(formType)
+ ? FORM_TYPE_COLORS[formType] || COLORS.GRAY
+ : COLORS.GRAY,
+ border: `1px solid ${selectedFormTypes.includes(formType) ? FORM_TYPE_COLORS[formType] || COLORS.GRAY : COLORS.BORDER}`,
+ }}
+ >
+ {formType}
+ </button>
+ ))}
+ {selectedFormTypes.length > 0 && (
+ <button
+ onClick={() => setSelectedFormTypes([])}
+ className="px-2 py-0.5 rounded text-xs"
+ style={{ color: COLORS.RED }}
+ >
+ Clear
+ </button>
+ )}
+ </div>
+ {/* Filings List */}
+ <div className="space-y-2 max-h-48 overflow-y-auto">
+ {filterFilings(report.recent_filings).map((filing, idx) => (
+ <div
+ key={idx}
+ className="p-2 rounded flex items-start justify-between"
+ style={{ backgroundColor: COLORS.CARD_BG }}
+ >
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 mb-1">
+ <span
+ className="text-xs px-1.5 py-0.5 rounded font-medium"
+ style={{
+ backgroundColor: (FORM_TYPE_COLORS[filing.form_type] || COLORS.GRAY) + '20',
+ color: FORM_TYPE_COLORS[filing.form_type] || COLORS.GRAY,
+ }}
+ >
+ {filing.form_type}
+ </span>
+ <span className="text-xs" style={{ color: COLORS.GRAY }}>
+ <Calendar size={10} className="inline mr-1" />
+ {formatDate(filing.filing_date)}
+ </span>
+ </div>
+ <p className="text-xs truncate" style={{ color: COLORS.WHITE }}>
+ {filing.description || `Filing ${filing.accession_number}`}
+ </p>
+ </div>
+ <a
+ href={`https://www.sec.gov/Archives/edgar/data/${report.company_info?.cik}/${filing.accession_number.replace(/-/g, '')}/${filing.primary_document}`}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="p-1 rounded hover:bg-[#1A1A1A]"
+ >
+ <ExternalLink size={12} style={{ color: COLORS.GRAY }} />
+ </a>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Financials Section */}
+ {report.financials.length > 0 && (
+ <div className="border-b" style={{ borderColor: COLORS.BORDER }}>
+ <button
+ onClick={() => toggleSection('financials')}
+ className="w-full px-4 py-2 flex items-center justify-between"
+ >
+ <div className="flex items-center gap-2">
+ <BarChart3 size={14} style={{ color: COLORS.GREEN }} />
+ <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>
+ Financials
+ </span>
+ </div>
+ {expandedSection === 'financials' ? (
+ <ChevronUp size={14} style={{ color: COLORS.GRAY }} />
+ ) : (
+ <ChevronDown size={14} style={{ color: COLORS.GRAY }} />
+ )}
+ </button>
+ {expandedSection === 'financials' && (
+ <div className="px-4 pb-3">
+ <table className="w-full text-xs">
+ <thead>
+ <tr style={{ color: COLORS.GRAY }}>
+ <th className="text-left py-1">Period</th>
+ <th className="text-right py-1">Revenue</th>
+ <th className="text-right py-1">Net Income</th>
+ <th className="text-right py-1">EPS</th>
+ </tr>
+ </thead>
+ <tbody>
+ {report.financials.slice(0, 5).map((fin, idx) => (
+ <tr key={idx} className="border-t" style={{ borderColor: COLORS.BORDER }}>
+ <td className="py-1.5" style={{ color: COLORS.WHITE }}>{fin.period}</td>
+ <td className="text-right py-1.5" style={{ color: COLORS.WHITE }}>
+ {formatCurrency(fin.revenue)}
+ </td>
+ <td
+ className="text-right py-1.5"
+ style={{
+ color: fin.net_income && fin.net_income > 0 ? COLORS.GREEN : COLORS.RED,
+ }}
+ >
+ {formatCurrency(fin.net_income)}
+ </td>
+ <td className="text-right py-1.5" style={{ color: COLORS.WHITE }}>
+ {fin.eps !== null ? `$${fin.eps.toFixed(2)}` : 'N/A'}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Risk Factors Section */}
+ {report.risk_factors.length > 0 && (
+ <div>
+ <button
+ onClick={() => toggleSection('risks')}
+ className="w-full px-4 py-2 flex items-center justify-between"
+ >
+ <div className="flex items-center gap-2">
+ <Shield size={14} style={{ color: COLORS.RED }} />
+ <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>
+ Risk Factors ({report.risk_factors.length})
+ </span>
+ </div>
+ {expandedSection === 'risks' ? (
+ <ChevronUp size={14} style={{ color: COLORS.GRAY }} />
+ ) : (
+ <ChevronDown size={14} style={{ color: COLORS.GRAY }} />
+ )}
+ </button>
+ {expandedSection === 'risks' && (
+ <div className="px-4 pb-3">
+ <ul className="space-y-1">
+ {report.risk_factors.map((risk, idx) => (
+ <li
+ key={idx}
+ className="text-xs pl-3 relative"
+ style={{ color: COLORS.GRAY }}
+ >
+ <span
+ className="absolute left-0 top-1.5 w-1.5 h-1.5 rounded-full"
+ style={{ backgroundColor: COLORS.RED }}
+ />
+ {risk}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </div>
+ )}
+ </>
+ ) : (
+ <div className="p-8 text-center">
+ <FileSearch size={32} className="mx-auto mb-2 opacity-30" style={{ color: COLORS.GRAY }} />
+ <p className="text-sm" style={{ color: COLORS.GRAY }}>Search for a company</p>
+ <p className="text-xs mt-1" style={{ color: COLORS.GRAY }}>
+ Enter a ticker to view SEC filings and research
+ </p>
+ </div>
+ )}
+ </div>
+
+ {/* Footer */}
+ {report && (
+ <div className="px-4 py-2 border-t text-xs" style={{ borderColor: COLORS.BORDER, color: COLORS.GRAY }}>
+ Generated: {formatDate(report.generated_at)} • Data from SEC EDGAR
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default ResearchPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/SentimentPanel.tsx b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/SentimentPanel.tsx
new file mode 100644
index 000000000..5aba44008
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/SentimentPanel.tsx
@@ -0,0 +1,376 @@
+/**
+ * Sentiment Analysis Panel
+ *
+ * Displays market sentiment analysis from news and social sources.
+ * Shows sentiment scores, headlines, and market mood indicators.
+ */
+
+import React, { useState, useEffect, useCallback } from 'react';
+import {
+ Newspaper, TrendingUp, TrendingDown, Minus, RefreshCw,
+ Globe, AlertCircle, ChevronRight, ExternalLink, Loader2,
+} from 'lucide-react';
+import {
+ alphaArenaEnhancedService,
+ type SentimentResult,
+ type MarketMood,
+} from '../services/alphaArenaEnhancedService';
+
+const COLORS = {
+ ORANGE: '#FF8800',
+ WHITE: '#FFFFFF',
+ RED: '#FF3B3B',
+ GREEN: '#00D66F',
+ BLUE: '#3B82F6',
+ YELLOW: '#EAB308',
+ PURPLE: '#8B5CF6',
+ GRAY: '#787878',
+ DARK_BG: '#000000',
+ PANEL_BG: '#0F0F0F',
+ CARD_BG: '#0A0A0A',
+ BORDER: '#2A2A2A',
+};
+
+const SENTIMENT_COLORS: Record<string, string> = {
+ very_bearish: COLORS.RED,
+ bearish: '#FF6B6B',
+ neutral: COLORS.GRAY,
+ bullish: '#4ADE80',
+ very_bullish: COLORS.GREEN,
+};
+
+const SENTIMENT_LABELS: Record<string, string> = {
+ very_bearish: 'Very Bearish',
+ bearish: 'Bearish',
+ neutral: 'Neutral',
+ bullish: 'Bullish',
+ very_bullish: 'Very Bullish',
+};
+
+interface SentimentPanelProps {
+ symbol?: string;
+ showMarketMood?: boolean;
+}
+
+const SentimentPanel: React.FC<SentimentPanelProps> = ({
+ symbol = 'BTC',
+ showMarketMood = true,
+}) => {
+ const [sentiment, setSentiment] = useState<SentimentResult | null>(null);
+ const [marketMood, setMarketMood] = useState<MarketMood | null>(null);
+ const [isLoading, setIsLoading] = useState(false);
+ const [activeTab, setActiveTab] = useState<'symbol' | 'market'>('symbol');
+ const [error, setError] = useState<string | null>(null);
+
+ const fetchSentiment = useCallback(async () => {
+ setIsLoading(true);
+ setError(null);
+ try {
+ const result = await alphaArenaEnhancedService.getSentiment(symbol);
+ if (result.success && result.sentiment) {
+ setSentiment(result.sentiment);
+ } else {
+ setError(result.error || 'Failed to fetch sentiment');
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Failed to fetch sentiment');
+ } finally {
+ setIsLoading(false);
+ }
+ }, [symbol]);
+
+ const fetchMarketMood = useCallback(async () => {
+ setIsLoading(true);
+ setError(null);
+ try {
+ const result = await alphaArenaEnhancedService.getMarketMood();
+ if (result.success && result.market_mood) {
+ setMarketMood(result.market_mood);
+ }
+ } catch (err) {
+ console.error('Error fetching market mood:', err);
+ } finally {
+ setIsLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ if (activeTab === 'symbol') {
+ fetchSentiment();
+ } else {
+ fetchMarketMood();
+ }
+ }, [activeTab, fetchSentiment, fetchMarketMood]);
+
+ const getSentimentIcon = (sentimentLevel: string) => {
+ if (sentimentLevel.includes('bullish')) {
+ return <TrendingUp size={16} style={{ color: SENTIMENT_COLORS[sentimentLevel] }} />;
+ } else if (sentimentLevel.includes('bearish')) {
+ return <TrendingDown size={16} style={{ color: SENTIMENT_COLORS[sentimentLevel] }} />;
+ }
+ return <Minus size={16} style={{ color: COLORS.GRAY }} />;
+ };
+
+ const renderSentimentMeter = (score: number) => {
+ // Score ranges from -1 (bearish) to 1 (bullish)
+ const percentage = ((score + 1) / 2) * 100;
+
+ return (
+ <div className="relative h-2 rounded-full overflow-hidden" style={{ backgroundColor: COLORS.BORDER }}>
+ {/* Background gradient */}
+ <div
+ className="absolute inset-0"
+ style={{
+ background: `linear-gradient(to right, ${COLORS.RED}, ${COLORS.GRAY}, ${COLORS.GREEN})`,
+ }}
+ />
+ {/* Indicator */}
+ <div
+ className="absolute w-3 h-3 rounded-full bg-white -top-0.5 transform -translate-x-1/2"
+ style={{
+ left: `${percentage}%`,
+ boxShadow: '0 0 4px rgba(0,0,0,0.5)',
+ }}
+ />
+ </div>
+ );
+ };
+
+ return (
+ <div
+ className="rounded-lg overflow-hidden"
+ style={{ backgroundColor: COLORS.PANEL_BG, border: `1px solid ${COLORS.BORDER}` }}
+ >
+ {/* Header */}
+ <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: COLORS.BORDER }}>
+ <div className="flex items-center gap-2">
+ <Newspaper size={16} style={{ color: COLORS.BLUE }} />
+ <span className="font-semibold text-sm" style={{ color: COLORS.WHITE }}>
+ Sentiment Analysis
+ </span>
+ </div>
+ <button
+ onClick={activeTab === 'symbol' ? fetchSentiment : fetchMarketMood}
+ disabled={isLoading}
+ className="p-1.5 rounded transition-colors hover:bg-[#1A1A1A]"
+ >
+ <RefreshCw
+ size={14}
+ className={isLoading ? 'animate-spin' : ''}
+ style={{ color: COLORS.GRAY }}
+ />
+ </button>
+ </div>
+
+ {/* Tabs */}
+ {showMarketMood && (
+ <div className="flex border-b" style={{ borderColor: COLORS.BORDER }}>
+ <button
+ onClick={() => setActiveTab('symbol')}
+ className="flex-1 px-4 py-2 text-xs font-medium transition-colors"
+ style={{
+ backgroundColor: activeTab === 'symbol' ? COLORS.CARD_BG : 'transparent',
+ color: activeTab === 'symbol' ? COLORS.ORANGE : COLORS.GRAY,
+ borderBottom: activeTab === 'symbol' ? `2px solid ${COLORS.ORANGE}` : 'none',
+ }}
+ >
+ {symbol} Sentiment
+ </button>
+ <button
+ onClick={() => setActiveTab('market')}
+ className="flex-1 px-4 py-2 text-xs font-medium transition-colors"
+ style={{
+ backgroundColor: activeTab === 'market' ? COLORS.CARD_BG : 'transparent',
+ color: activeTab === 'market' ? COLORS.ORANGE : COLORS.GRAY,
+ borderBottom: activeTab === 'market' ? `2px solid ${COLORS.ORANGE}` : 'none',
+ }}
+ >
+ <Globe size={12} className="inline mr-1" />
+ Market Mood
+ </button>
+ </div>
+ )}
+
+ {/* Content */}
+ <div className="p-4">
+ {error && (
+ <div className="flex items-center gap-2 p-2 rounded mb-3" style={{ backgroundColor: COLORS.RED + '10' }}>
+ <AlertCircle size={14} style={{ color: COLORS.RED }} />
+ <span className="text-xs" style={{ color: COLORS.RED }}>{error}</span>
+ </div>
+ )}
+
+ {isLoading ? (
+ <div className="flex items-center justify-center py-8">
+ <Loader2 size={24} className="animate-spin" style={{ color: COLORS.ORANGE }} />
+ </div>
+ ) : activeTab === 'symbol' && sentiment ? (
+ <>
+ {/* Main Sentiment Display */}
+ <div className="text-center mb-4">
+ <div className="flex items-center justify-center gap-2 mb-2">
+ {getSentimentIcon(sentiment.overall_sentiment)}
+ <span
+ className="text-lg font-bold"
+ style={{ color: SENTIMENT_COLORS[sentiment.overall_sentiment] }}
+ >
+ {SENTIMENT_LABELS[sentiment.overall_sentiment]}
+ </span>
+ </div>
+ <div className="text-2xl font-bold mb-1" style={{ color: COLORS.WHITE }}>
+ {sentiment.sentiment_score >= 0 ? '+' : ''}{(sentiment.sentiment_score * 100).toFixed(0)}%
+ </div>
+ <div className="text-xs" style={{ color: COLORS.GRAY }}>
+ Confidence: {(sentiment.confidence * 100).toFixed(0)}%
+ </div>
+ </div>
+
+ {/* Sentiment Meter */}
+ <div className="mb-4">
+ {renderSentimentMeter(sentiment.sentiment_score)}
+ <div className="flex justify-between text-xs mt-1" style={{ color: COLORS.GRAY }}>
+ <span>Bearish</span>
+ <span>Neutral</span>
+ <span>Bullish</span>
+ </div>
+ </div>
+
+ {/* Article Breakdown */}
+ <div className="grid grid-cols-3 gap-2 mb-4">
+ <div className="p-2 rounded text-center" style={{ backgroundColor: COLORS.GREEN + '10' }}>
+ <div className="text-lg font-bold" style={{ color: COLORS.GREEN }}>
+ {sentiment.bullish_count}
+ </div>
+ <div className="text-xs" style={{ color: COLORS.GRAY }}>Bullish</div>
+ </div>
+ <div className="p-2 rounded text-center" style={{ backgroundColor: COLORS.GRAY + '10' }}>
+ <div className="text-lg font-bold" style={{ color: COLORS.GRAY }}>
+ {sentiment.neutral_count}
+ </div>
+ <div className="text-xs" style={{ color: COLORS.GRAY }}>Neutral</div>
+ </div>
+ <div className="p-2 rounded text-center" style={{ backgroundColor: COLORS.RED + '10' }}>
+ <div className="text-lg font-bold" style={{ color: COLORS.RED }}>
+ {sentiment.bearish_count}
+ </div>
+ <div className="text-xs" style={{ color: COLORS.GRAY }}>Bearish</div>
+ </div>
+ </div>
+
+ {/* Key Headlines */}
+ {sentiment.key_headlines.length > 0 && (
+ <div>
+ <h4 className="text-xs font-medium mb-2" style={{ color: COLORS.GRAY }}>Key Headlines</h4>
+ <div className="space-y-2">
+ {sentiment.key_headlines.slice(0, 4).map((headline, idx) => (
+ <div
+ key={idx}
+ className="flex items-start gap-2 p-2 rounded"
+ style={{ backgroundColor: COLORS.CARD_BG }}
+ >
+ <ChevronRight size={12} style={{ color: COLORS.GRAY, marginTop: 2 }} />
+ <span className="text-xs line-clamp-2" style={{ color: COLORS.WHITE }}>
+ {headline}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Sources */}
+ {sentiment.sources.length > 0 && (
+ <div className="mt-3 pt-3 border-t" style={{ borderColor: COLORS.BORDER }}>
+ <div className="flex flex-wrap gap-1">
+ {sentiment.sources.slice(0, 5).map((source, idx) => (
+ <span
+ key={idx}
+ className="text-xs px-2 py-0.5 rounded"
+ style={{ backgroundColor: COLORS.BORDER, color: COLORS.GRAY }}
+ >
+ {source}
+ </span>
+ ))}
+ </div>
+ </div>
+ )}
+ </>
+ ) : activeTab === 'market' && marketMood ? (
+ <>
+ {/* Market Mood Overview */}
+ <div className="text-center mb-4">
+ <div
+ className="inline-flex items-center gap-2 px-4 py-2 rounded-full mb-2"
+ style={{
+ backgroundColor: marketMood.overall_mood === 'risk_on' ? COLORS.GREEN + '20' :
+ marketMood.overall_mood === 'risk_off' ? COLORS.RED + '20' : COLORS.GRAY + '20',
+ }}
+ >
+ <Globe size={16} style={{
+ color: marketMood.overall_mood === 'risk_on' ? COLORS.GREEN :
+ marketMood.overall_mood === 'risk_off' ? COLORS.RED : COLORS.GRAY,
+ }} />
+ <span
+ className="text-sm font-bold"
+ style={{
+ color: marketMood.overall_mood === 'risk_on' ? COLORS.GREEN :
+ marketMood.overall_mood === 'risk_off' ? COLORS.RED : COLORS.GRAY,
+ }}
+ >
+ {marketMood.overall_mood === 'risk_on' ? 'RISK ON' :
+ marketMood.overall_mood === 'risk_off' ? 'RISK OFF' : 'MIXED'}
+ </span>
+ </div>
+ <div className="text-xs" style={{ color: COLORS.GRAY }}>
+ Avg Sentiment: {(marketMood.average_sentiment * 100).toFixed(0)}% • {marketMood.symbols_analyzed} symbols
+ </div>
+ </div>
+
+ {/* Individual Sentiments */}
+ <div className="space-y-2">
+ {Object.entries(marketMood.individual_sentiments).map(([sym, data]) => (
+ <div
+ key={sym}
+ className="flex items-center justify-between p-2 rounded"
+ style={{ backgroundColor: COLORS.CARD_BG }}
+ >
+ <div className="flex items-center gap-2">
+ {getSentimentIcon(data.overall_sentiment)}
+ <span className="text-sm font-medium" style={{ color: COLORS.WHITE }}>{sym}</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <span
+ className="text-xs"
+ style={{ color: SENTIMENT_COLORS[data.overall_sentiment] }}
+ >
+ {(data.sentiment_score * 100).toFixed(0)}%
+ </span>
+ <span className="text-xs" style={{ color: COLORS.GRAY }}>
+ ({data.articles_analyzed} articles)
+ </span>
+ </div>
+ </div>
+ ))}
+ </div>
+ </>
+ ) : (
+ <div className="text-center py-8" style={{ color: COLORS.GRAY }}>
+ <Newspaper size={32} className="mx-auto mb-2 opacity-30" />
+ <p className="text-sm">No sentiment data available</p>
+ </div>
+ )}
+ </div>
+
+ {/* Footer */}
+ <div className="px-4 py-2 border-t text-xs" style={{ borderColor: COLORS.BORDER, color: COLORS.GRAY }}>
+ {sentiment && (
+ <span>
+ Analyzed {sentiment.articles_analyzed} articles • Updated {new Date(sentiment.timestamp).toLocaleTimeString()}
+ </span>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default SentimentPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/index.ts b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/index.ts
index e31ef32f6..7905a7f5d 100644
--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/components/index.ts
@@ -8,3 +8,11 @@ export { default as DecisionsPanel } from './DecisionsPanel';
export { default as PerformanceChart } from './PerformanceChart';
export { default as CompetitionControls } from './CompetitionControls';
export { default as ApiKeysModal } from './ApiKeysModal';
+
+// Enhanced Alpha Arena Components
+export { default as HITLApprovalPanel } from './HITLApprovalPanel';
+export { default as SentimentPanel } from './SentimentPanel';
+export { default as PortfolioMetricsPanel } from './PortfolioMetricsPanel';
+export { default as GridStrategyPanel } from './GridStrategyPanel';
+export { default as ResearchPanel } from './ResearchPanel';
+export { default as BrokerSelector } from './BrokerSelector';
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/index.ts b/fincept-terminal-desktop/src/components/tabs/alpha-arena/index.ts
index 062913685..d816e7dd5 100644
--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/index.ts
@@ -4,6 +4,9 @@
* AI Trading Competition where multiple LLM models compete in real-time trading.
*/
+// Default export for lazy loading
+export { default } from './AlphaArenaTab';
+
// Main Tab Component
export { default as AlphaArenaTab } from './AlphaArenaTab';
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaEnhancedService.ts b/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaEnhancedService.ts
new file mode 100644
index 000000000..f70b7a165
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaEnhancedService.ts
@@ -0,0 +1,658 @@
+/**
+ * Alpha Arena Enhanced Service
+ *
+ * Additional service methods for new Alpha Arena features:
+ * - HITL (Human-in-the-Loop) approval
+ * - Sentiment analysis
+ * - Portfolio metrics
+ * - Grid trading
+ * - Multi-broker support
+ * - Research/SEC filings
+ */
+
+import { invoke } from '@tauri-apps/api/core';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export interface ApprovalRequest {
+ id: string;
+ decision: {
+ model_name: string;
+ action: string;
+ symbol: string;
+ quantity: number;
+ confidence: number;
+ reasoning: string;
+ price_at_decision: number;
+ };
+ risk_level: 'low' | 'medium' | 'high' | 'critical';
+ reason: string;
+ created_at: string;
+ expires_at: string | null;
+ status: 'pending' | 'approved' | 'rejected' | 'timeout' | 'auto_approved';
+}
+
+export interface HITLStatus {
+ rules: Array<{
+ name: string;
+ description: string;
+ risk_level: string;
+ auto_approve_timeout: number | null;
+ enabled: boolean;
+ }>;
+ pending_count: number;
+ pending: ApprovalRequest[];
+ history_count: number;
+}
+
+export interface SentimentResult {
+ symbol: string;
+ timestamp: string;
+ articles_analyzed: number;
+ overall_sentiment: 'very_bearish' | 'bearish' | 'neutral' | 'bullish' | 'very_bullish';
+ sentiment_score: number;
+ confidence: number;
+ bullish_count: number;
+ bearish_count: number;
+ neutral_count: number;
+ key_headlines: string[];
+ sources: string[];
+}
+
+export interface MarketMood {
+ symbols_analyzed: number;
+ overall_mood: 'risk_on' | 'risk_off' | 'mixed';
+ average_sentiment: number;
+ individual_sentiments: Record<string, SentimentResult>;
+}
+
+export interface PortfolioMetrics {
+ total_return: number;
+ sharpe_ratio: number;
+ sortino_ratio: number;
+ max_drawdown_pct: number;
+ max_drawdown_value: number;
+ win_rate: number;
+ profit_factor: number;
+ expectancy: number;
+ total_trades: number;
+ winning_trades: number;
+ losing_trades: number;
+ avg_win: number;
+ avg_loss: number;
+ volatility: number;
+}
+
+export interface GridConfig {
+ symbol: string;
+ lower_price: number;
+ upper_price: number;
+ num_grids: number;
+ quantity_per_grid: number;
+ take_profit_pct?: number;
+ stop_loss_pct?: number;
+}
+
+export interface GridStatus {
+ agent_name: string;
+ grid_status: {
+ grid_levels: number[];
+ triggered_levels: number[];
+ active_orders: number;
+ total_profit: number;
+ trades_executed: number;
+ };
+}
+
+export interface BrokerInfo {
+ id: string;
+ name: string;
+ display_name: string;
+ broker_type: 'crypto' | 'stocks' | 'forex';
+ region: 'global' | 'us' | 'india' | 'europe' | 'asia';
+ supports_spot: boolean;
+ supports_margin: boolean;
+ supports_futures: boolean;
+ supports_options: boolean;
+ max_leverage: number;
+ default_symbols: string[];
+ maker_fee: number;
+ taker_fee: number;
+ websocket_enabled: boolean;
+}
+
+export interface TickerData {
+ symbol: string;
+ price: number;
+ bid: number;
+ ask: number;
+ high_24h: number;
+ low_24h: number;
+ volume_24h: number;
+ timestamp: string;
+}
+
+export interface ResearchReport {
+ symbol: string;
+ generated_at: string;
+ company_info: {
+ cik: string;
+ name: string;
+ ticker: string;
+ sic: string;
+ industry: string;
+ fiscal_year_end: string;
+ state: string;
+ } | null;
+ recent_filings: Array<{
+ accession_number: string;
+ form_type: string;
+ filing_date: string;
+ description: string;
+ primary_document: string;
+ }>;
+ financials: Array<{
+ period: string;
+ revenue: number | null;
+ net_income: number | null;
+ total_assets: number | null;
+ eps: number | null;
+ }>;
+ insider_activity: unknown[];
+ summary: string;
+ risk_factors: string[];
+}
+
+export interface TechnicalFeatures {
+ sma_20: number | null;
+ sma_50: number | null;
+ ema_12: number | null;
+ ema_26: number | null;
+ rsi_14: number | null;
+ rsi_interpretation: string;
+ macd: number | null;
+ macd_signal: number | null;
+ macd_interpretation: string;
+ bollinger_upper: number | null;
+ bollinger_middle: number | null;
+ bollinger_lower: number | null;
+ bollinger_interpretation: string;
+ support_level: number | null;
+ resistance_level: number | null;
+}
+
+// =============================================================================
+// HITL (Human-in-the-Loop) Functions
+// =============================================================================
+
+export async function getHITLStatus(): Promise<{
+ success: boolean;
+ status?: HITLStatus;
+ error?: string;
+}> {
+ try {
+ const result = await invoke<{ success: boolean; status: HITLStatus }>('get_alpha_hitl_status');
+ return result;
+ } catch (error) {
+ console.error('Error getting HITL status:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+export async function getPendingApprovals(): Promise<{
+ success: boolean;
+ pending_approvals?: ApprovalRequest[];
+ count?: number;
+ error?: string;
+}> {
+ try {
+ const result = await invoke<{
+ success: boolean;
+ pending_approvals: ApprovalRequest[];
+ count: number;
+ }>('get_alpha_pending_approvals');
+ return result;
+ } catch (error) {
+ console.error('Error getting pending approvals:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+export async function approveDecision(
+ requestId: string,
+ notes?: string
+): Promise<{ success: boolean; error?: string }> {
+ try {
+ const result = await invoke<{ success: boolean; action: string }>('approve_alpha_decision', {
+ requestId,
+ approvedBy: 'user',
+ notes: notes || '',
+ });
+ return { success: result.success };
+ } catch (error) {
+ console.error('Error approving decision:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+export async function rejectDecision(
+ requestId: string,
+ notes?: string
+): Promise<{ success: boolean; error?: string }> {
+ try {
+ const result = await invoke<{ success: boolean; action: string }>('reject_alpha_decision', {
+ requestId,
+ rejectedBy: 'user',
+ notes: notes || '',
+ });
+ return { success: result.success };
+ } catch (error) {
+ console.error('Error rejecting decision:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+export async function updateHITLRule(
+ ruleName: string,
+ enabled: boolean
+): Promise<{ success: boolean; error?: string }> {
+ try {
+ const result = await invoke<{ success: boolean }>('update_alpha_hitl_rule', {
+ ruleName,
+ enabled,
+ });
+ return { success: result.success };
+ } catch (error) {
+ console.error('Error updating HITL rule:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+// =============================================================================
+// Sentiment Analysis Functions
+// =============================================================================
+
+export async function getSentiment(
+ symbol: string,
+ maxArticles?: number
+): Promise<{
+ success: boolean;
+ sentiment?: SentimentResult;
+ prompt_context?: string;
+ error?: string;
+}> {
+ try {
+ const result = await invoke<{
+ success: boolean;
+ sentiment: SentimentResult;
+ prompt_context: string;
+ }>('get_alpha_sentiment', {
+ symbol,
+ maxArticles: maxArticles || 15,
+ });
+ return result;
+ } catch (error) {
+ console.error('Error getting sentiment:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+export async function getMarketMood(
+ symbols?: string[]
+): Promise<{
+ success: boolean;
+ market_mood?: MarketMood;
+ error?: string;
+}> {
+ try {
+ const result = await invoke<{ success: boolean; market_mood: MarketMood }>(
+ 'get_alpha_market_mood',
+ { symbols }
+ );
+ return result;
+ } catch (error) {
+ console.error('Error getting market mood:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+// =============================================================================
+// Portfolio Metrics Functions
+// =============================================================================
+
+export async function getPortfolioMetrics(
+ competitionId: string,
+ modelName?: string
+): Promise<{
+ success: boolean;
+ metrics?: PortfolioMetrics | Record<string, PortfolioMetrics>;
+ error?: string;
+}> {
+ try {
+ const result = await invoke<{
+ success: boolean;
+ metrics: PortfolioMetrics | Record<string, PortfolioMetrics>;
+ }>('get_alpha_portfolio_metrics', {
+ competitionId,
+ modelName: modelName || null,
+ });
+ return result;
+ } catch (error) {
+ console.error('Error getting portfolio metrics:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+export async function getEquityCurve(
+ competitionId: string,
+ modelName?: string
+): Promise<{
+ success: boolean;
+ equity_curve?: Array<{
+ timestamp: string;
+ cycle: number;
+ value: number;
+ model: string;
+ }>;
+ error?: string;
+}> {
+ try {
+ const result = await invoke<{
+ success: boolean;
+ equity_curve: Array<{
+ timestamp: string;
+ cycle: number;
+ value: number;
+ model: string;
+ }>;
+ }>('get_alpha_equity_curve', {
+ competitionId,
+ modelName: modelName || null,
+ });
+ return result;
+ } catch (error) {
+ console.error('Error getting equity curve:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+// =============================================================================
+// Grid Trading Functions
+// =============================================================================
+
+export async function createGridAgent(
+ name: string,
+ gridConfig: GridConfig
+): Promise<{
+ success: boolean;
+ agent_name?: string;
+ grid_config?: GridConfig & { grid_spacing: number };
+ grid_levels?: number[];
+ error?: string;
+}> {
+ try {
+ const result = await invoke<{
+ success: boolean;
+ agent_name: string;
+ grid_config: GridConfig & { grid_spacing: number };
+ grid_levels: number[];
+ }>('create_alpha_grid_agent', {
+ name,
+ upperPrice: gridConfig.upper_price,
+ lowerPrice: gridConfig.lower_price,
+ gridLevels: gridConfig.num_grids,
+ gridType: 'arithmetic',
+ totalInvestment: gridConfig.quantity_per_grid * gridConfig.num_grids * gridConfig.lower_price,
+ });
+ return result;
+ } catch (error) {
+ console.error('Error creating grid agent:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+export async function getGridStatus(
+ agentName: string
+): Promise<{
+ success: boolean;
+ grid_status?: GridStatus['grid_status'];
+ error?: string;
+}> {
+ try {
+ const result = await invoke<GridStatus>('get_alpha_grid_status', { agentName });
+ return {
+ success: true,
+ grid_status: result.grid_status,
+ };
+ } catch (error) {
+ console.error('Error getting grid status:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+// =============================================================================
+// Broker Functions
+// =============================================================================
+
+export async function listBrokers(
+ brokerType?: 'crypto' | 'stocks' | 'forex',
+ region?: 'global' | 'us' | 'india' | 'europe' | 'asia'
+): Promise<{
+ success: boolean;
+ brokers?: BrokerInfo[];
+ count?: number;
+ error?: string;
+}> {
+ try {
+ const result = await invoke<{
+ success: boolean;
+ brokers: BrokerInfo[];
+ count: number;
+ }>('list_alpha_brokers', {
+ brokerType: brokerType || null,
+ region: region || null,
+ });
+ return result;
+ } catch (error) {
+ console.error('Error listing brokers:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+export async function getBrokerTicker(
+ symbol: string,
+ brokerId?: string
+): Promise<{
+ success: boolean;
+ ticker?: TickerData;
+ broker_id?: string;
+ error?: string;
+}> {
+ try {
+ const result = await invoke<{
+ success: boolean;
+ ticker: TickerData;
+ broker_id: string;
+ }>('get_alpha_broker_ticker', {
+ symbol,
+ brokerId: brokerId || null,
+ });
+ return result;
+ } catch (error) {
+ console.error('Error getting broker ticker:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+// =============================================================================
+// Research Functions
+// =============================================================================
+
+export async function getResearch(
+ ticker: string
+): Promise<{
+ success: boolean;
+ report?: ResearchReport;
+ prompt_context?: string;
+ error?: string;
+}> {
+ try {
+ const result = await invoke<{
+ success: boolean;
+ report: ResearchReport;
+ prompt_context: string;
+ }>('get_alpha_research', { ticker });
+ return result;
+ } catch (error) {
+ console.error('Error getting research:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+export async function getSecFilings(
+ ticker: string,
+ formTypes?: string[],
+ limit?: number
+): Promise<{
+ success: boolean;
+ filings?: ResearchReport['recent_filings'];
+ count?: number;
+ error?: string;
+}> {
+ try {
+ const result = await invoke<{
+ success: boolean;
+ ticker: string;
+ filings: ResearchReport['recent_filings'];
+ count: number;
+ }>('get_alpha_sec_filings', {
+ ticker,
+ formTypes: formTypes || null,
+ limit: limit || 10,
+ });
+ return result;
+ } catch (error) {
+ console.error('Error getting SEC filings:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+// =============================================================================
+// Technical Features Functions
+// =============================================================================
+
+export async function getTechnicalFeatures(
+ symbol: string,
+ price: number
+): Promise<{
+ success: boolean;
+ features?: {
+ technical: TechnicalFeatures | null;
+ sentiment: SentimentResult | null;
+ };
+ prompt_context?: string;
+ error?: string;
+}> {
+ try {
+ const result = await invoke<{
+ success: boolean;
+ features: {
+ technical: TechnicalFeatures | null;
+ sentiment: SentimentResult | null;
+ };
+ prompt_context: string;
+ }>('get_alpha_features', { symbol, price });
+ return result;
+ } catch (error) {
+ console.error('Error getting technical features:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+// =============================================================================
+// Export Service Object
+// =============================================================================
+
+export const alphaArenaEnhancedService = {
+ // HITL
+ getHITLStatus,
+ getPendingApprovals,
+ approveDecision,
+ rejectDecision,
+ updateHITLRule,
+
+ // Sentiment
+ getSentiment,
+ getMarketMood,
+
+ // Portfolio Metrics
+ getPortfolioMetrics,
+ getEquityCurve,
+
+ // Grid Trading
+ createGridAgent,
+ getGridStatus,
+
+ // Brokers
+ listBrokers,
+ getBrokerTicker,
+
+ // Research
+ getResearch,
+ getSecFilings,
+
+ // Technical Features
+ getTechnicalFeatures,
+};
+
+export default alphaArenaEnhancedService;
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaService.ts b/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaService.ts
index d6432d40e..fda8eb5be 100644
--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaService.ts
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/services/alphaArenaService.ts
@@ -130,9 +130,42 @@ export async function startCompetition(
}
}
+// Portfolio update callback type
+export type PortfolioUpdateCallback = (update: {
+ modelName: string;
+ portfolioValue: number;
+ cash: number;
+ totalPnl: number;
+ positions: Array<{
+ symbol: string;
+ side: string;
+ quantity: number;
+ entry_price: number;
+ current_price: number;
+ unrealized_pnl: number;
+ }>;
+ tradesCount: number;
+ cycleNumber: number;
+ timestamp: string;
+}) => void;
+
+// Store for real-time portfolio update callbacks
+let portfolioUpdateCallbacks: PortfolioUpdateCallback[] = [];
+
+/**
+ * Subscribe to real-time portfolio updates during cycle execution
+ */
+export function onPortfolioUpdate(callback: PortfolioUpdateCallback): () => void {
+ portfolioUpdateCallbacks.push(callback);
+ return () => {
+ portfolioUpdateCallbacks = portfolioUpdateCallbacks.filter(cb => cb !== callback);
+ };
+}
+
/**
* Run a single competition cycle
* Now also saves decisions to the repository for persistence
+ * AND emits real-time portfolio updates
*/
export async function runCycle(competitionId: string): Promise<RunCycleResponse> {
try {
@@ -140,8 +173,46 @@ export async function runCycle(competitionId: string): Promise<RunCycleResponse>
competitionId,
});
- // If cycle was successful, save decisions to repository for persistence
+ // If cycle was successful, process events
if (result.success && result.events) {
+ // Process portfolio update events for real-time updates
+ const portfolioEvents = result.events.filter(
+ e => e.event === 'portfolio_update' && e.metadata
+ );
+
+ for (const event of portfolioEvents) {
+ const meta = event.metadata as Record<string, unknown>;
+ if (meta?.model_name) {
+ const update = {
+ modelName: meta.model_name as string,
+ portfolioValue: (meta.portfolio_value as number) || 0,
+ cash: (meta.cash as number) || 0,
+ totalPnl: (meta.total_pnl as number) || 0,
+ positions: (meta.positions as Array<{
+ symbol: string;
+ side: string;
+ quantity: number;
+ entry_price: number;
+ current_price: number;
+ unrealized_pnl: number;
+ }>) || [],
+ tradesCount: (meta.trades_count as number) || 0,
+ cycleNumber: (meta.cycle_number as number) || 0,
+ timestamp: (meta.timestamp as string) || new Date().toISOString(),
+ };
+
+ // Notify all subscribers immediately
+ for (const callback of portfolioUpdateCallbacks) {
+ try {
+ callback(update);
+ } catch (err) {
+ console.warn('Portfolio update callback error:', err);
+ }
+ }
+ }
+ }
+
+ // Save decisions to repository for persistence
const decisionEvents = result.events.filter(
e => e.event === 'decision_completed' && e.metadata
);
@@ -596,6 +667,165 @@ export async function resumeCompetition(competitionId: string): Promise<{
}
}
+// =============================================================================
+// Trading Styles (v2.2)
+// =============================================================================
+
+export interface TradingStyle {
+ id: string;
+ name: string;
+ description: string;
+ style_type: string;
+ risk_tolerance: number;
+ position_size_pct: number;
+ hold_bias: number;
+ confidence_threshold: number;
+ temperature_modifier: number;
+ system_prompt: string;
+ instructions: string[];
+ max_trades_per_cycle: number;
+ stop_loss_pct: number | null;
+ take_profit_pct: number | null;
+ color: string;
+ icon: string;
+}
+
+export interface ListTradingStylesResponse {
+ success: boolean;
+ styles?: TradingStyle[];
+ count?: number;
+ error?: string;
+}
+
+export interface StyledAgent {
+ name: string;
+ provider: string;
+ model_id: string;
+ api_key?: string;
+ initial_capital: number;
+ trading_style: string;
+ metadata?: {
+ style_config?: TradingStyle;
+ };
+}
+
+export interface CreateStyledAgentsResponse {
+ success: boolean;
+ agents?: StyledAgent[];
+ count?: number;
+ provider?: string;
+ model_id?: string;
+ styles_used?: string[];
+ error?: string;
+}
+
+/**
+ * List all available trading styles
+ * Trading styles allow running the same LLM provider with different behavioral personalities
+ */
+export async function listTradingStyles(): Promise<ListTradingStylesResponse> {
+ try {
+ const result = await invoke<ListTradingStylesResponse>('list_alpha_trading_styles');
+ return result;
+ } catch (error) {
+ console.error('Error listing trading styles:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+/**
+ * Create multiple agents with different trading styles using a single provider
+ * This is useful for testing how the same model behaves with different strategies
+ *
+ * @param provider - LLM provider (openai, anthropic, google, deepseek, groq, etc.)
+ * @param modelId - Model identifier (gpt-4o-mini, claude-3-5-sonnet, etc.)
+ * @param styles - Optional list of style IDs to use (defaults to diverse set)
+ * @param initialCapital - Starting capital per agent (default: 10000)
+ */
+export async function createStyledAgents(
+ provider: string,
+ modelId: string,
+ styles?: string[],
+ initialCapital: number = 10000
+): Promise<CreateStyledAgentsResponse> {
+ try {
+ const result = await invoke<CreateStyledAgentsResponse>('create_alpha_styled_agents', {
+ provider,
+ modelId,
+ styles,
+ initialCapital,
+ });
+ return result;
+ } catch (error) {
+ console.error('Error creating styled agents:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
+/**
+ * Create a competition with styled agents using a single provider
+ * Convenience function that combines createStyledAgents and createCompetition
+ */
+export async function createStyledCompetition(params: {
+ name: string;
+ provider: string;
+ modelId: string;
+ styles?: string[];
+ symbol?: string;
+ initialCapital?: number;
+ cycleInterval?: number;
+ exchangeId?: string;
+}): Promise<CreateCompetitionResponse> {
+ try {
+ // First, create the styled agents
+ const agentsResult = await createStyledAgents(
+ params.provider,
+ params.modelId,
+ params.styles,
+ params.initialCapital || 10000
+ );
+
+ if (!agentsResult.success || !agentsResult.agents) {
+ return {
+ success: false,
+ error: agentsResult.error || 'Failed to create styled agents',
+ };
+ }
+
+ // Now create the competition with these agents
+ const competitionRequest: CreateCompetitionRequest = {
+ competition_name: params.name,
+ models: agentsResult.agents.map(agent => ({
+ name: agent.name,
+ provider: agent.provider,
+ model_id: agent.model_id,
+ initial_capital: agent.initial_capital,
+ trading_style: agent.trading_style,
+ metadata: agent.metadata,
+ })),
+ symbols: [params.symbol || 'BTC/USD'],
+ initial_capital: params.initialCapital || 10000,
+ mode: 'baseline',
+ cycle_interval_seconds: params.cycleInterval || 150,
+ exchange_id: params.exchangeId || 'kraken',
+ };
+
+ return await createCompetition(competitionRequest);
+ } catch (error) {
+ console.error('Error creating styled competition:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ };
+ }
+}
+
// =============================================================================
// Auto-Run Management
// =============================================================================
@@ -660,6 +890,14 @@ export const alphaArenaService = {
getCycleDecisions,
getModelPerformanceSummary,
+ // Real-time Portfolio Updates
+ onPortfolioUpdate,
+
+ // Trading Styles (v2.2) - Single provider with multiple agent personalities
+ listTradingStyles,
+ createStyledAgents,
+ createStyledCompetition,
+
// Auto-Run
startAutoRun,
stopAutoRun,
diff --git a/fincept-terminal-desktop/src/components/tabs/alpha-arena/types/index.ts b/fincept-terminal-desktop/src/components/tabs/alpha-arena/types/index.ts
index 9bb5dfabe..4e509b205 100644
--- a/fincept-terminal-desktop/src/components/tabs/alpha-arena/types/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/alpha-arena/types/index.ts
@@ -52,6 +52,8 @@ export interface CompetitionModel {
model_id: string;
api_key?: string;
initial_capital: number;
+ trading_style?: string; // Trading style ID (e.g., 'aggressive', 'conservative')
+ metadata?: Record<string, unknown>; // Additional metadata including style config
capital?: number;
total_pnl?: number;
}
@@ -216,6 +218,8 @@ export interface CreateCompetitionRequest {
provider?: string;
model_id?: string;
initial_capital?: number;
+ trading_style?: string; // Trading style ID (e.g., 'aggressive', 'conservative')
+ metadata?: Record<string, unknown>; // Additional metadata including style config
}>;
symbols?: string[];
initial_capital?: number;
diff --git a/fincept-terminal-desktop/src/components/tabs/AsiaMarketsTab.tsx b/fincept-terminal-desktop/src/components/tabs/asia-markets/AsiaMarketsTab.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/AsiaMarketsTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/asia-markets/AsiaMarketsTab.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/asia-markets/index.ts b/fincept-terminal-desktop/src/components/tabs/asia-markets/index.ts
new file mode 100644
index 000000000..9672102c6
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/asia-markets/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./AsiaMarketsTab";
+export { default as AsiaMarketsTab } from "./AsiaMarketsTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/BacktestingTabNew.tsx b/fincept-terminal-desktop/src/components/tabs/backtesting/BacktestingTabNew.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/BacktestingTabNew.tsx
rename to fincept-terminal-desktop/src/components/tabs/backtesting/BacktestingTabNew.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/backtesting/index.ts b/fincept-terminal-desktop/src/components/tabs/backtesting/index.ts
new file mode 100644
index 000000000..9543a5d88
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/backtesting/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./BacktestingTabNew";
+export { default as BacktestingTabNew } from "./BacktestingTabNew";
diff --git a/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx b/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx
similarity index 98%
rename from fincept-terminal-desktop/src/components/tabs/ChatTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx
index e5a5391b7..75a5663b6 100644
--- a/fincept-terminal-desktop/src/components/tabs/ChatTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/chat/ChatTab.tsx
@@ -4,11 +4,11 @@ import { Settings, Trash2, Bot, User, Clock, Send, Plus, Search, Edit2, Check, X
import { useTerminalTheme } from '@/contexts/ThemeContext';
import { useAuth } from '@/contexts/AuthContext';
import { useTranslation } from 'react-i18next';
-import { llmApiService, ChatMessage as APIMessage } from '../../services/chat/llmApi';
-import { sqliteService, ChatSession, ChatMessage, RecordedContext, LLMConfig, LLMGlobalSettings, ChatStatistics } from '../../services/core/sqliteService';
-import { contextRecorderService } from '../../services/data-sources/contextRecorderService';
-import MarkdownRenderer from '../common/MarkdownRenderer';
-import ContextSelector from '../common/ContextSelector';
+import { llmApiService, ChatMessage as APIMessage } from '@/services/chat/llmApi';
+import { sqliteService, ChatSession, ChatMessage, RecordedContext, LLMConfig, LLMGlobalSettings, ChatStatistics } from '@/services/core/sqliteService';
+import { contextRecorderService } from '@/services/data-sources/contextRecorderService';
+import MarkdownRenderer from '@/components/common/MarkdownRenderer';
+import ContextSelector from '@/components/common/ContextSelector';
import { TabFooter } from '@/components/common/TabFooter';
interface ChatTabProps {
@@ -184,7 +184,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
const loadMCPToolsCount = async (retryCount = 0, maxRetries = MCP_MAX_RETRIES) => {
try {
- const { mcpToolService } = await import('../../services/mcp/mcpToolService');
+ const { mcpToolService } = await import('@/services/mcp/mcpToolService');
const tools = await mcpToolService.getAllTools();
setMcpToolsCount(tools.length);
@@ -393,7 +393,7 @@ const ChatTab: React.FC<ChatTabProps> = ({ onNavigateToSettings, onNavigateToTab
const getMCPTools = async (): Promise<any[]> => {
try {
- const { mcpToolService } = await import('../../services/mcp/mcpToolService');
+ const { mcpToolService } = await import('@/services/mcp/mcpToolService');
return await mcpToolService.getAllTools();
} catch (error) {
return [];
diff --git a/fincept-terminal-desktop/src/components/tabs/chat/index.ts b/fincept-terminal-desktop/src/components/tabs/chat/index.ts
new file mode 100644
index 000000000..c517a9f15
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/chat/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./ChatTab";
+export { default as ChatTab } from "./ChatTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/CodeEditorTab.tsx b/fincept-terminal-desktop/src/components/tabs/code-editor/CodeEditorTab.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/CodeEditorTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/code-editor/CodeEditorTab.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/code-editor/index.ts b/fincept-terminal-desktop/src/components/tabs/code-editor/index.ts
new file mode 100644
index 000000000..73e3abf29
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/code-editor/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./CodeEditorTab";
+export { default as CodeEditorTab } from "./CodeEditorTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx
new file mode 100644
index 000000000..ac9006c9a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/CryptoTradingTab.tsx
@@ -0,0 +1,599 @@
+// CryptoTradingTab.tsx - Professional Fincept Terminal-Grade Crypto Trading Interface
+import React, { useState, useEffect, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+import { invoke } from '@tauri-apps/api/core';
+
+import { useBrokerContext } from '@/contexts/BrokerContext';
+import { useRustTicker, useRustOrderBook, useRustTrades } from '@/hooks/useRustWebSocket';
+import { getMarketDataService } from '@/services/trading/UnifiedMarketDataService';
+
+// Import sub-components
+import {
+ CryptoTopNav,
+ CryptoTickerBar,
+ CryptoWatchlist,
+ CryptoOrderBook,
+ CryptoOrderEntry,
+ CryptoChartArea,
+ CryptoBottomPanel,
+ CryptoStatusBar,
+} from './components';
+
+// Import constants and types
+import { FINCEPT, DEFAULT_CRYPTO_WATCHLIST, CRYPTO_TERMINAL_STYLES } from './constants';
+import type {
+ OrderBook,
+ Position,
+ Order,
+ TickerData,
+ TradeData,
+ WatchlistPrice,
+ CenterViewType,
+ RightPanelViewType,
+ LeftSidebarViewType,
+ BottomPanelTabType,
+} from './types';
+
+import type { OrderRequest } from '@/types/trading';
+
+export function CryptoTradingTab() {
+ const { t } = useTranslation('trading');
+ const {
+ activeBroker,
+ availableBrokers,
+ setActiveBroker,
+ tradingMode,
+ setTradingMode,
+ paperPortfolioMode,
+ setPaperPortfolioMode,
+ activeAdapter,
+ realAdapter,
+ paperAdapter,
+ defaultSymbols,
+ isConnecting,
+ isLoading,
+ } = useBrokerContext();
+
+ const [currentTime, setCurrentTime] = useState(new Date());
+ const [selectedSymbol, setSelectedSymbol] = useState(defaultSymbols[0] || 'BTC/USD');
+ const [tickerState, setTickerData] = useState<TickerData | null>(null);
+ const [orderBook, setOrderBook] = useState<OrderBook>({ bids: [], asks: [], symbol: '' });
+ const [tradesState, setTradesData] = useState<TradeData[]>([]);
+ const [isPlacingOrder, setIsPlacingOrder] = useState(false);
+ const [lastOrderBookUpdate, setLastOrderBookUpdate] = useState<number>(0);
+
+ // UI State
+ const [searchQuery, setSearchQuery] = useState('');
+ const [availableSymbols, setAvailableSymbols] = useState<string[]>([]);
+ const [isLoadingSymbols, setIsLoadingSymbols] = useState(false);
+ const [showSymbolDropdown, setShowSymbolDropdown] = useState(false);
+ const [showBrokerDropdown, setShowBrokerDropdown] = useState(false);
+ const [selectedView, setSelectedView] = useState<CenterViewType>('chart');
+ const [rightPanelView, setRightPanelView] = useState<RightPanelViewType>('orderbook');
+ const [leftSidebarView, setLeftSidebarView] = useState<LeftSidebarViewType>('watchlist');
+
+ // Paper trading state
+ const [positions, setPositions] = useState<Position[]>([]);
+ const [orders, setOrders] = useState<Order[]>([]);
+ const [trades, setTrades] = useState<any[]>([]);
+ const [balance, setBalance] = useState(0);
+ const [equity, setEquity] = useState(0);
+ const [stats, setStats] = useState<any>(null);
+ const [activeBottomTab, setActiveBottomTab] = useState<BottomPanelTabType>('positions');
+ const [isBottomPanelMinimized, setIsBottomPanelMinimized] = useState(false);
+
+ // Trading settings
+ const [slippage, setSlippage] = useState(0);
+ const [makerFee, setMakerFee] = useState(0.0002);
+ const [takerFee, setTakerFee] = useState(0.0005);
+ const [showSettings, setShowSettings] = useState(false);
+
+ // Watchlist
+ const [watchlist, setWatchlist] = useState<string[]>(DEFAULT_CRYPTO_WATCHLIST);
+ const [watchlistPrices, setWatchlistPrices] = useState<Record<string, WatchlistPrice>>({});
+
+ // Initialize WebSocket providers (Kraken & HyperLiquid)
+ useEffect(() => {
+ const initializeProviders = async () => {
+ try {
+ await invoke('ws_set_config', {
+ config: {
+ name: 'kraken',
+ url: 'wss://ws.kraken.com/v2',
+ enabled: true,
+ reconnect_delay_ms: 5000,
+ max_reconnect_attempts: 10,
+ heartbeat_interval_ms: 30000,
+ }
+ });
+
+ await invoke('ws_set_config', {
+ config: {
+ name: 'hyperliquid',
+ url: 'wss://api.hyperliquid.xyz/ws',
+ enabled: true,
+ reconnect_delay_ms: 5000,
+ max_reconnect_attempts: 10,
+ heartbeat_interval_ms: 30000,
+ }
+ });
+ } catch (err) {
+ // Ignore config errors
+ }
+ };
+
+ initializeProviders();
+ }, []);
+
+ // Update time
+ useEffect(() => {
+ const timer = setInterval(() => {
+ setCurrentTime(new Date());
+ }, 1000);
+ return () => clearInterval(timer);
+ }, []);
+
+ // Fetch watchlist prices
+ useEffect(() => {
+ const fetchWatchlistPrices = async () => {
+ try {
+ if (realAdapter?.isConnected() && typeof realAdapter.fetchTickers === 'function') {
+ try {
+ const tickers = await realAdapter.fetchTickers(watchlist);
+ const prices: Record<string, WatchlistPrice> = {};
+
+ 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;
+ }
+ });
+
+ if (hasValidData) {
+ setWatchlistPrices(prices);
+ return;
+ }
+ } catch (err) {
+ console.warn('[CryptoTrading] fetchTickers failed, trying fallback API:', err);
+ }
+ }
+
+ // Fallback to public Binance API
+ 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, WatchlistPrice> = {};
+ 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;
+ }
+ }
+ });
+
+ if (hasValidData) {
+ setWatchlistPrices(prices);
+ }
+ } catch (error) {
+ console.error('[CryptoTrading] Failed to fetch prices:', error);
+ }
+ };
+
+ fetchWatchlistPrices();
+ const interval = setInterval(fetchWatchlistPrices, 30000);
+ return () => clearInterval(interval);
+ }, [realAdapter, watchlist]);
+
+ // Clear data when symbol changes
+ useEffect(() => {
+ setTickerData(null);
+ setTradesData([]);
+ }, [selectedSymbol]);
+
+ // Reset data when broker changes
+ useEffect(() => {
+ setTickerData(null);
+ setOrderBook({ bids: [], asks: [], symbol: '' });
+ setTradesData([]);
+ setWatchlistPrices({});
+ setLastOrderBookUpdate(0);
+
+ if (defaultSymbols.length > 0) {
+ setSelectedSymbol(defaultSymbols[0]);
+ }
+ }, [activeBroker, defaultSymbols]);
+
+ // Subscribe to Rust WebSocket feeds
+ const { data: tickerData, error: tickerError } = useRustTicker(
+ activeBroker || '',
+ selectedSymbol,
+ !!activeBroker
+ );
+
+ const { data: orderbookData, error: orderbookError } = useRustOrderBook(
+ activeBroker || '',
+ selectedSymbol,
+ 25,
+ !!activeBroker
+ );
+
+ const { trades: tradesData, error: tradesError } = useRustTrades(
+ activeBroker || '',
+ selectedSymbol,
+ 50,
+ !!activeBroker
+ );
+
+ // Update ticker data from Rust WebSocket
+ useEffect(() => {
+ if (!tickerData) return;
+
+ setTickerData({
+ symbol: tickerData.symbol,
+ price: tickerData.price,
+ bid: tickerData.bid,
+ ask: tickerData.ask,
+ last: tickerData.price,
+ volume: tickerData.volume,
+ high: tickerData.high,
+ low: tickerData.low,
+ change: tickerData.change,
+ changePercent: tickerData.change_percent,
+ open: tickerData.open,
+ });
+
+ if (activeBroker && tickerData.price > 0) {
+ const marketDataService = getMarketDataService();
+ marketDataService.updatePrice(activeBroker, selectedSymbol, {
+ price: tickerData.price,
+ bid: tickerData.bid,
+ ask: tickerData.ask,
+ volume: tickerData.volume,
+ high: tickerData.high,
+ low: tickerData.low,
+ change: tickerData.change,
+ change_percent: tickerData.change_percent,
+ timestamp: tickerData.timestamp,
+ });
+ }
+ }, [tickerData, activeBroker, selectedSymbol]);
+
+ // Update orderbook from Rust WebSocket
+ useEffect(() => {
+ if (!orderbookData) return;
+
+ setOrderBook({
+ bids: orderbookData.bids.map(b => ({ price: b.price, size: b.quantity })),
+ asks: orderbookData.asks.map(a => ({ price: a.price, size: a.quantity })),
+ symbol: orderbookData.symbol,
+ });
+ setLastOrderBookUpdate(Date.now());
+ }, [orderbookData]);
+
+ // Update trades from Rust WebSocket
+ useEffect(() => {
+ if (tradesData && tradesData.length > 0) {
+ setTradesData(tradesData.map(t => ({
+ symbol: t.symbol,
+ price: t.price,
+ quantity: t.quantity,
+ side: t.side,
+ timestamp: t.timestamp,
+ })));
+ }
+ }, [tradesData]);
+
+ // Load paper trading data
+ useEffect(() => {
+ const loadPaperTradingData = async () => {
+ if (tradingMode !== 'paper' || !paperAdapter) return;
+
+ try {
+ const balanceData = await paperAdapter.fetchBalance();
+ const usdBalance = (balanceData.free as any)?.USD || 0;
+ const totalEquity = (balanceData.total as any)?.USD || 0;
+ setBalance(usdBalance);
+ setEquity(totalEquity);
+
+ const positionsData = await paperAdapter.fetchPositions();
+ const marketDataService = getMarketDataService();
+
+ const mappedPositions: Position[] = positionsData.map((p: any) => {
+ const livePrice = marketDataService.getCurrentPrice(p.symbol, activeBroker || undefined);
+ const currentPrice = livePrice?.last || p.markPrice || p.current_price || 0;
+ const entryPrice = p.entryPrice || p.entry_price || 0;
+ const quantity = p.contracts || p.quantity || 0;
+
+ let unrealizedPnl = p.unrealizedPnl || p.unrealized_pnl || 0;
+ let pnlPercent = p.percentage || 0;
+
+ if (currentPrice > 0 && entryPrice > 0 && quantity > 0) {
+ if (p.side === 'long') {
+ unrealizedPnl = (currentPrice - entryPrice) * quantity;
+ } else {
+ unrealizedPnl = (entryPrice - currentPrice) * quantity;
+ }
+ pnlPercent = ((currentPrice - entryPrice) / entryPrice) * 100;
+ if (p.side === 'short') pnlPercent = -pnlPercent;
+ }
+
+ return {
+ symbol: p.symbol,
+ side: p.side,
+ quantity: quantity,
+ entryPrice: entryPrice,
+ positionValue: p.info?.positionValue || (currentPrice * quantity),
+ currentPrice: currentPrice,
+ unrealizedPnl: unrealizedPnl,
+ pnlPercent: pnlPercent,
+ };
+ });
+ setPositions(mappedPositions);
+
+ const ordersData = await paperAdapter.fetchOpenOrders();
+ const mappedOrders: Order[] = ordersData.map((o: any) => ({
+ id: o.id,
+ symbol: o.symbol,
+ side: o.side,
+ type: o.type,
+ quantity: o.amount,
+ price: o.price,
+ status: o.status,
+ createdAt: o.datetime,
+ }));
+ setOrders(mappedOrders);
+
+ const tradesData = await paperAdapter.fetchMyTrades(undefined, undefined, 50);
+ setTrades(tradesData);
+
+ if (typeof (paperAdapter as any).getStatistics === 'function') {
+ const statsData = await (paperAdapter as any).getStatistics();
+ setStats(statsData);
+ }
+ } catch (error) {
+ console.error('[CryptoTrading] Failed to load paper trading data:', error);
+ }
+ };
+
+ loadPaperTradingData();
+ const intervalRef = { current: null as NodeJS.Timeout | null };
+ intervalRef.current = setInterval(loadPaperTradingData, 1000);
+ return () => {
+ if (intervalRef.current) {
+ clearInterval(intervalRef.current);
+ }
+ };
+ }, [tradingMode, paperAdapter, activeBroker]);
+
+ // Update slippage & fees
+ useEffect(() => {
+ if (paperAdapter && 'paperConfig' in paperAdapter) {
+ const config = (paperAdapter as any).paperConfig;
+ if (config && config.slippage && config.fees) {
+ config.slippage.market = slippage;
+ config.fees.maker = makerFee;
+ config.fees.taker = takerFee;
+ }
+ }
+ }, [slippage, makerFee, takerFee, paperAdapter]);
+
+ // Fetch markets
+ useEffect(() => {
+ const fetchMarkets = async () => {
+ if (!realAdapter || !realAdapter.isConnected()) {
+ setAvailableSymbols(defaultSymbols);
+ return;
+ }
+ setIsLoadingSymbols(true);
+ try {
+ const markets = await realAdapter.fetchMarkets();
+ const symbols = markets
+ .filter((m: any) => m.active && m.spot && (m.quote === 'USD' || m.quote === 'USDT' || m.quote === 'USDC'))
+ .map((m: any) => m.symbol)
+ .sort();
+ setAvailableSymbols(symbols.length > 0 ? symbols : defaultSymbols);
+ } catch (error) {
+ console.error('[CryptoTrading] Failed to fetch markets:', error);
+ setAvailableSymbols(defaultSymbols);
+ } finally {
+ setIsLoadingSymbols(false);
+ }
+ };
+ fetchMarkets();
+ }, [realAdapter, defaultSymbols]);
+
+ // Handle broker change
+ const handleBrokerChange = async (brokerId: string) => {
+ setShowBrokerDropdown(false);
+ await setActiveBroker(brokerId);
+ };
+
+ // Handle symbol selection
+ const handleSymbolSelect = (symbol: string) => {
+ setSelectedSymbol(symbol);
+ setShowSymbolDropdown(false);
+ };
+
+ const currentPrice = tickerState?.last || tickerState?.price || orderBook.asks[0]?.price || 0;
+
+ // Calculate price change and percentage
+ let priceChange = 0;
+ let priceChangePercent = 0;
+
+ if (tickerState) {
+ priceChange = tickerState.change || 0;
+ priceChangePercent = tickerState.changePercent || 0;
+
+ if (priceChange === 0 && priceChangePercent === 0) {
+ const last = tickerState.last || tickerState.price || 0;
+ const open = tickerState.open || 0;
+
+ if (last > 0 && open > 0) {
+ priceChange = last - open;
+ priceChangePercent = (priceChange / open) * 100;
+ }
+ }
+ }
+
+ // Fallback: use watchlist data
+ if (priceChange === 0 && priceChangePercent === 0 && watchlistPrices[selectedSymbol]) {
+ priceChangePercent = watchlistPrices[selectedSymbol].change;
+ if (currentPrice > 0) {
+ priceChange = (priceChangePercent / 100) * currentPrice / (1 + priceChangePercent / 100);
+ }
+ }
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ overflow: 'hidden',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ <style>{CRYPTO_TERMINAL_STYLES}</style>
+
+ {/* Top Navigation Bar */}
+ <CryptoTopNav
+ activeBroker={activeBroker}
+ availableBrokers={availableBrokers}
+ tradingMode={tradingMode}
+ isConnected={activeAdapter?.isConnected() || false}
+ showBrokerDropdown={showBrokerDropdown}
+ showSettings={showSettings}
+ onBrokerDropdownToggle={() => setShowBrokerDropdown(!showBrokerDropdown)}
+ onBrokerChange={handleBrokerChange}
+ onTradingModeChange={setTradingMode}
+ onSettingsToggle={() => setShowSettings(!showSettings)}
+ />
+
+ {/* Ticker Bar */}
+ <CryptoTickerBar
+ selectedSymbol={selectedSymbol}
+ tickerData={tickerState}
+ availableSymbols={availableSymbols}
+ searchQuery={searchQuery}
+ showSymbolDropdown={showSymbolDropdown}
+ balance={balance}
+ equity={equity}
+ tradingMode={tradingMode}
+ priceChange={priceChange}
+ priceChangePercent={priceChangePercent}
+ onSymbolSelect={handleSymbolSelect}
+ onSearchQueryChange={setSearchQuery}
+ onSymbolDropdownToggle={() => setShowSymbolDropdown(!showSymbolDropdown)}
+ />
+
+ {/* Main Content */}
+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
+ {/* Left Sidebar - Watchlist */}
+ <CryptoWatchlist
+ watchlist={watchlist}
+ watchlistPrices={watchlistPrices}
+ selectedSymbol={selectedSymbol}
+ leftSidebarView={leftSidebarView}
+ positions={positions}
+ equity={equity}
+ onSymbolSelect={handleSymbolSelect}
+ onViewChange={setLeftSidebarView}
+ />
+
+ {/* Center - Chart & Bottom Panel */}
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
+ {/* Chart Area */}
+ <CryptoChartArea
+ selectedSymbol={selectedSymbol}
+ selectedView={selectedView}
+ tradesData={tradesState}
+ isBottomPanelMinimized={isBottomPanelMinimized}
+ onViewChange={setSelectedView}
+ />
+
+ {/* Bottom Panel */}
+ <CryptoBottomPanel
+ activeTab={activeBottomTab}
+ positions={positions}
+ orders={orders}
+ trades={trades}
+ isMinimized={isBottomPanelMinimized}
+ activeBroker={activeBroker}
+ selectedSymbol={selectedSymbol}
+ tickerData={tickerState}
+ realAdapter={realAdapter}
+ onTabChange={setActiveBottomTab}
+ onMinimizeToggle={() => setIsBottomPanelMinimized(!isBottomPanelMinimized)}
+ />
+ </div>
+
+ {/* Right Sidebar - Order Entry & Order Book */}
+ <div style={{
+ width: '300px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderLeft: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ {/* Order Entry */}
+ <CryptoOrderEntry
+ selectedSymbol={selectedSymbol}
+ currentPrice={currentPrice}
+ balance={balance}
+ tradingMode={tradingMode}
+ activeBroker={activeBroker}
+ isLoading={isLoading}
+ isConnecting={isConnecting}
+ paperAdapter={paperAdapter}
+ realAdapter={realAdapter}
+ onTradingModeChange={setTradingMode}
+ />
+
+ {/* Order Book */}
+ <CryptoOrderBook
+ orderBook={orderBook}
+ currentPrice={currentPrice}
+ selectedSymbol={selectedSymbol}
+ rightPanelView={rightPanelView}
+ lastOrderBookUpdate={lastOrderBookUpdate}
+ onViewChange={setRightPanelView}
+ />
+ </div>
+ </div>
+
+ {/* Status Bar */}
+ <CryptoStatusBar
+ activeBroker={activeBroker}
+ tradingMode={tradingMode}
+ isConnected={activeAdapter?.isConnected() || false}
+ />
+ </div>
+ );
+}
+
+export default CryptoTradingTab;
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoBottomPanel.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoBottomPanel.tsx
new file mode 100644
index 000000000..8b208e713
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoBottomPanel.tsx
@@ -0,0 +1,295 @@
+// CryptoBottomPanel.tsx - Bottom Panel with Tabs for Crypto Trading
+import React from 'react';
+import { ChevronDown, ChevronUp } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { BottomPanelTabType, Position } from '../types';
+import { PositionsTable } from '../../trading/core/PositionManager';
+import { OrdersTable, ClosedOrders } from '../../trading/core/OrderManager';
+import { AccountStats, FeesDisplay, MarginPanel } from '../../trading/core/AccountInfo';
+import { StakingPanel, FuturesPanel } from '../../trading/exchange-specific/kraken';
+import { PortfolioAggregator, ArbitrageDetector } from '../../trading/cross-exchange';
+import { GridTradingPanel } from '../../trading/grid-trading';
+
+interface CryptoBottomPanelProps {
+ activeTab: BottomPanelTabType;
+ positions: Position[];
+ orders: any[];
+ trades: any[];
+ isMinimized: boolean;
+ activeBroker: string | null;
+ selectedSymbol: string;
+ tickerData: any;
+ realAdapter: any;
+ onTabChange: (tab: BottomPanelTabType) => void;
+ onMinimizeToggle: () => void;
+}
+
+export function CryptoBottomPanel({
+ activeTab,
+ positions,
+ orders,
+ trades,
+ isMinimized,
+ activeBroker,
+ selectedSymbol,
+ tickerData,
+ realAdapter,
+ onTabChange,
+ onMinimizeToggle,
+}: CryptoBottomPanelProps) {
+ return (
+ <div style={{
+ flex: isMinimized ? '0 0 40px' : 1,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ transition: 'flex 0.3s ease'
+ }}>
+ <div style={{
+ padding: '6px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {(['positions', 'orders', 'history', 'trades', 'stats', 'features', 'cross-exchange', 'grid-trading'] as BottomPanelTabType[]).map((tab) => (
+ <button
+ key={tab}
+ onClick={() => onTabChange(tab)}
+ style={{
+ padding: '6px 16px',
+ backgroundColor: activeTab === tab ? FINCEPT.ORANGE : 'transparent',
+ border: 'none',
+ color: activeTab === tab ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ textTransform: 'uppercase',
+ transition: 'all 0.2s'
+ }}
+ >
+ {tab} {tab === 'positions' && `(${positions.length})`} {tab === 'orders' && `(${orders.length})`}
+ </button>
+ ))}
+ </div>
+
+ {/* Minimize/Maximize Button */}
+ <button
+ onClick={onMinimizeToggle}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 600,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ borderRadius: '2px',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ e.currentTarget.style.borderColor = FINCEPT.GRAY;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ }}
+ title={isMinimized ? 'Maximize Panel' : 'Minimize Panel'}
+ >
+ {isMinimized ? (
+ <>
+ <ChevronUp size={14} />
+ <span>MAXIMIZE</span>
+ </>
+ ) : (
+ <>
+ <ChevronDown size={14} />
+ <span>MINIMIZE</span>
+ </>
+ )}
+ </button>
+ </div>
+
+ {!isMinimized && (
+ <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
+ {/* Positions Tab */}
+ {activeTab === 'positions' && <PositionsTable />}
+
+ {/* Orders Tab */}
+ {activeTab === 'orders' && <OrdersTable />}
+
+ {/* History Tab (Closed Orders) */}
+ {activeTab === 'history' && <ClosedOrders />}
+
+ {/* Trades Tab */}
+ {activeTab === 'trades' && (
+ trades.length === 0 ? (
+ <div style={{ padding: '40px', textAlign: 'center', color: FINCEPT.GRAY, fontSize: '11px' }}>
+ No trade history
+ </div>
+ ) : (
+ <table style={{ width: '100%', fontSize: '10px', borderCollapse: 'collapse' }}>
+ <thead>
+ <tr style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <th style={{ padding: '8px', textAlign: 'left', color: FINCEPT.GRAY, fontWeight: 600 }}>TIME</th>
+ <th style={{ padding: '8px', textAlign: 'left', color: FINCEPT.GRAY, fontWeight: 600 }}>SYMBOL</th>
+ <th style={{ padding: '8px', textAlign: 'center', color: FINCEPT.GRAY, fontWeight: 600 }}>SIDE</th>
+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, fontWeight: 600 }}>QTY</th>
+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, fontWeight: 600 }}>PRICE</th>
+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, fontWeight: 600 }}>VALUE</th>
+ <th style={{ padding: '8px', textAlign: 'right', color: FINCEPT.GRAY, fontWeight: 600 }}>FEE</th>
+ </tr>
+ </thead>
+ <tbody>
+ {trades.map((trade, idx) => (
+ <tr key={idx} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}40` }}>
+ <td style={{ padding: '8px', color: FINCEPT.GRAY, fontSize: '9px' }}>
+ {new Date(trade.timestamp).toLocaleTimeString()}
+ </td>
+ <td style={{ padding: '8px', color: FINCEPT.WHITE }}>{trade.symbol}</td>
+ <td style={{ padding: '8px', textAlign: 'center' }}>
+ <span style={{
+ padding: '2px 8px',
+ backgroundColor: trade.side === 'buy' ? `${FINCEPT.GREEN}20` : `${FINCEPT.RED}20`,
+ color: trade.side === 'buy' ? FINCEPT.GREEN : FINCEPT.RED,
+ fontSize: '9px',
+ fontWeight: 700
+ }}>
+ {trade.side.toUpperCase()}
+ </span>
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.WHITE }}>
+ {trade.amount?.toFixed(4) || '0.0000'}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.YELLOW }}>
+ ${trade.price?.toFixed(2) || '0.00'}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.CYAN }}>
+ ${trade.cost?.toFixed(2) || '0.00'}
+ </td>
+ <td style={{ padding: '8px', textAlign: 'right', color: FINCEPT.RED }}>
+ ${trade.fee?.cost?.toFixed(2) || '0.00'}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )
+ )}
+
+ {/* Stats Tab */}
+ {activeTab === 'stats' && (
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 300px',
+ gap: '12px',
+ padding: '12px',
+ height: '100%',
+ overflow: 'hidden'
+ }}>
+ {/* Left: Account Statistics */}
+ <div style={{ height: '100%', overflow: 'auto' }}>
+ <AccountStats />
+ </div>
+
+ {/* Right: Fees & Margin */}
+ <div style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '12px',
+ height: '100%',
+ overflow: 'auto'
+ }}>
+ <FeesDisplay />
+ <MarginPanel />
+ </div>
+ </div>
+ )}
+
+ {/* Features Tab - Exchange-Specific Features */}
+ {activeTab === 'features' && (
+ <div style={{ padding: '16px', overflow: 'auto' }}>
+ {/* Kraken-Specific Features */}
+ {activeBroker === 'kraken' && (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
+ <StakingPanel />
+ <FuturesPanel />
+ </div>
+ )}
+
+ {/* HyperLiquid - Already shown in order form area */}
+ {activeBroker === 'hyperliquid' && (
+ <div style={{
+ padding: '40px',
+ textAlign: 'center',
+ color: FINCEPT.GRAY,
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ fontSize: '14px', fontWeight: 600, marginBottom: '8px' }}>
+ HyperLiquid Features
+ </div>
+ <div style={{ fontSize: '11px' }}>
+ HyperLiquid-specific features (Vault Manager, Leverage Control) are available in the order form panel on the right.
+ </div>
+ </div>
+ )}
+
+ {/* No exchange-specific features */}
+ {activeBroker !== 'kraken' && activeBroker !== 'hyperliquid' && (
+ <div style={{
+ padding: '40px',
+ textAlign: 'center',
+ color: FINCEPT.GRAY,
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderRadius: '4px'
+ }}>
+ <div style={{ fontSize: '14px', fontWeight: 600, marginBottom: '8px' }}>
+ No Exchange-Specific Features
+ </div>
+ <div style={{ fontSize: '11px' }}>
+ The selected exchange does not have additional features available in this panel.
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Cross-Exchange Tab - Multi-Exchange Portfolio & Arbitrage */}
+ {activeTab === 'cross-exchange' && (
+ <div style={{ padding: '16px', overflow: 'auto' }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
+ <PortfolioAggregator />
+ <ArbitrageDetector />
+ </div>
+ </div>
+ )}
+
+ {/* Grid Trading Tab */}
+ {activeTab === 'grid-trading' && (
+ <div style={{ padding: '16px', overflow: 'auto', height: '100%' }}>
+ <GridTradingPanel
+ symbol={selectedSymbol}
+ currentPrice={tickerData?.last || tickerData?.close || 0}
+ brokerType="crypto"
+ brokerId={activeBroker || ''}
+ cryptoAdapter={realAdapter || undefined}
+ variant="full"
+ />
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+export default CryptoBottomPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoChartArea.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoChartArea.tsx
new file mode 100644
index 000000000..65554d59d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoChartArea.tsx
@@ -0,0 +1,121 @@
+// CryptoChartArea.tsx - Center Chart Area for Crypto Trading
+import React from 'react';
+import { FINCEPT } from '../constants';
+import type { CenterViewType, TradeData } from '../types';
+import { TradingChart, DepthChart } from '../../trading/charts';
+
+interface CryptoChartAreaProps {
+ selectedSymbol: string;
+ selectedView: CenterViewType;
+ tradesData: TradeData[];
+ isBottomPanelMinimized: boolean;
+ onViewChange: (view: CenterViewType) => void;
+}
+
+export function CryptoChartArea({
+ selectedSymbol,
+ selectedView,
+ tradesData,
+ isBottomPanelMinimized,
+ onViewChange,
+}: CryptoChartAreaProps) {
+ return (
+ <div style={{
+ flex: isBottomPanelMinimized ? 1 : '0 0 55%',
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ transition: 'flex 0.3s ease'
+ }}>
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}>
+ {(['CHART', 'DEPTH', 'TRADES'] as const).map((view) => (
+ <button
+ key={view}
+ onClick={() => onViewChange(view.toLowerCase() as CenterViewType)}
+ style={{
+ padding: '4px 12px',
+ backgroundColor: selectedView === view.toLowerCase() ? FINCEPT.ORANGE : 'transparent',
+ border: 'none',
+ color: selectedView === view.toLowerCase() ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ transition: 'all 0.2s'
+ }}
+ >
+ {view}
+ </button>
+ ))}
+ </div>
+ <div style={{
+ flex: 1,
+ display: 'flex',
+ alignItems: 'stretch',
+ justifyContent: 'center',
+ color: FINCEPT.GRAY,
+ fontSize: '12px',
+ overflow: 'visible',
+ minHeight: 0
+ }}>
+ {selectedView === 'chart' && (
+ <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}
+ />
+ </div>
+ )}
+ {selectedView === 'trades' && (
+ <div style={{ width: '100%', height: '100%', overflow: 'auto', padding: '8px' }}>
+ <table style={{ width: '100%', fontSize: '10px', borderCollapse: 'collapse' }}>
+ <thead>
+ <tr style={{ borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <th style={{ padding: '6px', textAlign: 'left', color: FINCEPT.GRAY }}>TIME</th>
+ <th style={{ padding: '6px', textAlign: 'right', color: FINCEPT.GRAY }}>PRICE</th>
+ <th style={{ padding: '6px', textAlign: 'right', color: FINCEPT.GRAY }}>SIZE</th>
+ </tr>
+ </thead>
+ <tbody>
+ {tradesData.slice(0, 20).map((trade, idx) => (
+ <tr key={idx} style={{ borderBottom: `1px solid ${FINCEPT.BORDER}40` }}>
+ <td style={{ padding: '4px 6px', color: FINCEPT.GRAY, fontSize: '9px' }}>
+ {new Date(trade.timestamp).toLocaleTimeString()}
+ </td>
+ <td style={{
+ padding: '4px 6px',
+ textAlign: 'right',
+ color: trade.side === 'buy' ? FINCEPT.GREEN : FINCEPT.RED
+ }}>
+ ${trade.price?.toFixed(2)}
+ </td>
+ <td style={{ padding: '4px 6px', textAlign: 'right', color: FINCEPT.WHITE }}>
+ {trade.quantity?.toFixed(4)}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+export default CryptoChartArea;
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderBook.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderBook.tsx
new file mode 100644
index 000000000..ffc2f049d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderBook.tsx
@@ -0,0 +1,186 @@
+// CryptoOrderBook.tsx - Right Sidebar Order Book for Crypto Trading
+import React from 'react';
+import { FINCEPT } from '../constants';
+import type { OrderBook, RightPanelViewType } from '../types';
+import { VolumeProfile } from '../../trading/charts';
+import { ModelChatPanel } from '../../trading/ai-agents/ModelChatPanel';
+
+interface CryptoOrderBookProps {
+ orderBook: OrderBook;
+ currentPrice: number;
+ selectedSymbol: string;
+ rightPanelView: RightPanelViewType;
+ lastOrderBookUpdate: number;
+ onViewChange: (view: RightPanelViewType) => void;
+}
+
+export function CryptoOrderBook({
+ orderBook,
+ currentPrice,
+ selectedSymbol,
+ rightPanelView,
+ lastOrderBookUpdate,
+ onViewChange,
+}: CryptoOrderBookProps) {
+ return (
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '10px',
+ fontWeight: 700,
+ color: FINCEPT.ORANGE,
+ letterSpacing: '0.5px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}>
+ <div style={{ display: 'flex', gap: '8px' }}>
+ {(['orderbook', 'volume', 'modelchat'] as RightPanelViewType[]).map((view) => (
+ <button
+ key={view}
+ onClick={() => onViewChange(view)}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: rightPanelView === view ? FINCEPT.ORANGE : 'transparent',
+ border: 'none',
+ color: rightPanelView === view ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '9px',
+ fontWeight: 700,
+ transition: 'all 0.2s'
+ }}
+ >
+ {view.toUpperCase()}
+ </button>
+ ))}
+ </div>
+ {rightPanelView === 'orderbook' && (
+ <span style={{ fontSize: '8px', color: FINCEPT.GRAY }}>
+ {orderBook.asks.length + orderBook.bids.length} LEVELS
+ </span>
+ )}
+ </div>
+ <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>
+ {rightPanelView === 'orderbook' && (
+ <>
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ color: FINCEPT.RED, fontSize: '9px', fontWeight: 700, marginBottom: '4px' }}>
+ ASKS ({orderBook.asks.length})
+ </div>
+ <table style={{ width: '100%', fontSize: '10px' }}>
+ <tbody>
+ {orderBook.asks.slice(0, 12).reverse().map((ask, idx) => {
+ const depth = (ask.size / Math.max(...orderBook.asks.map(a => a.size))) * 100;
+ return (
+ <tr key={idx} style={{ position: 'relative' }}>
+ <td style={{
+ padding: '2px 4px',
+ color: FINCEPT.RED,
+ position: 'relative',
+ zIndex: 1
+ }}>
+ <div style={{
+ position: 'absolute',
+ right: 0,
+ top: 0,
+ bottom: 0,
+ width: `${depth}%`,
+ backgroundColor: `${FINCEPT.RED}15`,
+ zIndex: -1
+ }} />
+ ${ask.price.toFixed(2)}
+ </td>
+ <td style={{ padding: '2px 4px', textAlign: 'right', color: FINCEPT.GRAY }}>
+ {ask.size.toFixed(4)}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+
+ <div style={{
+ height: '1px',
+ backgroundColor: FINCEPT.BORDER,
+ margin: '8px 0',
+ position: 'relative'
+ }}>
+ <div style={{
+ position: 'absolute',
+ left: '50%',
+ top: '50%',
+ transform: 'translate(-50%, -50%)',
+ backgroundColor: FINCEPT.PANEL_BG,
+ padding: '0 8px',
+ fontSize: '11px',
+ fontWeight: 700,
+ color: FINCEPT.YELLOW
+ }}>
+ ${currentPrice.toFixed(2)}
+ </div>
+ </div>
+
+ <div>
+ <div style={{ color: FINCEPT.GREEN, fontSize: '9px', fontWeight: 700, marginBottom: '4px' }}>
+ BIDS ({orderBook.bids.length})
+ </div>
+ <table style={{ width: '100%', fontSize: '10px' }}>
+ <tbody>
+ {orderBook.bids.slice(0, 12).map((bid, idx) => {
+ const depth = (bid.size / Math.max(...orderBook.bids.map(b => b.size))) * 100;
+ return (
+ <tr key={idx} style={{ position: 'relative' }}>
+ <td style={{
+ padding: '2px 4px',
+ color: FINCEPT.GREEN,
+ position: 'relative',
+ zIndex: 1
+ }}>
+ <div style={{
+ position: 'absolute',
+ right: 0,
+ top: 0,
+ bottom: 0,
+ width: `${depth}%`,
+ backgroundColor: `${FINCEPT.GREEN}15`,
+ zIndex: -1
+ }} />
+ ${bid.price.toFixed(2)}
+ </td>
+ <td style={{ padding: '2px 4px', textAlign: 'right', color: FINCEPT.GRAY }}>
+ {bid.size.toFixed(4)}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </div>
+ </>
+ )}
+
+ {rightPanelView === 'volume' && (
+ <VolumeProfile symbol={selectedSymbol} height={550} />
+ )}
+
+ {rightPanelView === 'modelchat' && (
+ <ModelChatPanel refreshInterval={5000} />
+ )}
+ </div>
+ <div style={{
+ padding: '4px 8px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '8px',
+ color: FINCEPT.GRAY
+ }}>
+ Updated: {lastOrderBookUpdate > 0 ? new Date(lastOrderBookUpdate).toLocaleTimeString() : 'Never'}
+ </div>
+ </div>
+ );
+}
+
+export default CryptoOrderBook;
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderEntry.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderEntry.tsx
new file mode 100644
index 000000000..e7d643202
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoOrderEntry.tsx
@@ -0,0 +1,247 @@
+// CryptoOrderEntry.tsx - Order Entry Panel for Crypto Trading
+import React from 'react';
+import { FINCEPT } from '../constants';
+import { EnhancedOrderForm } from '../../trading/core/OrderForm';
+import { HyperLiquidVaultManager } from '../../trading/exchange-specific/hyperliquid';
+
+interface CryptoOrderEntryProps {
+ selectedSymbol: string;
+ currentPrice: number;
+ balance: number;
+ tradingMode: 'paper' | 'live';
+ activeBroker: string | null;
+ isLoading: boolean;
+ isConnecting: boolean;
+ paperAdapter: any;
+ realAdapter: any;
+ onTradingModeChange: (mode: 'paper' | 'live') => void;
+}
+
+export function CryptoOrderEntry({
+ selectedSymbol,
+ currentPrice,
+ balance,
+ tradingMode,
+ activeBroker,
+ isLoading,
+ isConnecting,
+ paperAdapter,
+ realAdapter,
+ onTradingModeChange,
+}: CryptoOrderEntryProps) {
+ return (
+ <div style={{
+ height: '45%',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: tradingMode === 'live' ? FINCEPT.RED : FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '10px',
+ fontWeight: 700,
+ color: tradingMode === 'live' ? FINCEPT.WHITE : FINCEPT.ORANGE,
+ letterSpacing: '0.5px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}>
+ <span>ORDER ENTRY</span>
+ <span style={{
+ padding: '2px 8px',
+ backgroundColor: tradingMode === 'live' ? FINCEPT.WHITE : FINCEPT.GREEN,
+ color: tradingMode === 'live' ? FINCEPT.RED : FINCEPT.DARK_BG,
+ fontSize: '9px',
+ fontWeight: 700,
+ borderRadius: '2px'
+ }}>
+ {tradingMode === 'live' ? '🔴 LIVE' : '⚪ PAPER'}
+ </span>
+ </div>
+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
+ {/* Loading State */}
+ {isLoading ? (
+ <div style={{
+ padding: '20px',
+ textAlign: 'center',
+ border: `1px solid ${FINCEPT.CYAN}`,
+ backgroundColor: `${FINCEPT.CYAN}10`
+ }}>
+ <div style={{ color: FINCEPT.CYAN, fontSize: '11px', fontWeight: 700, marginBottom: '8px' }}>
+ ⏳ LOADING...
+ </div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>
+ Loading broker configurations...
+ </div>
+ </div>
+ ) : tradingMode === 'paper' ? (
+ /* PAPER TRADING MODE */
+ !paperAdapter ? (
+ <div style={{
+ padding: '20px',
+ textAlign: 'center',
+ border: `1px solid ${FINCEPT.RED}`,
+ backgroundColor: `${FINCEPT.RED}10`
+ }}>
+ <div style={{ color: FINCEPT.RED, fontSize: '12px', fontWeight: 700, marginBottom: '12px' }}>
+ {isConnecting ? '⏳ CONNECTING...' : '❌ ADAPTER NOT READY'}
+ </div>
+ {!isConnecting && (
+ <>
+ <div style={{ color: FINCEPT.WHITE, fontSize: '10px', marginBottom: '12px', lineHeight: '1.5' }}>
+ Paper trading adapter failed to initialize.
+ </div>
+ <button
+ onClick={() => window.location.reload()}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: FINCEPT.ORANGE,
+ border: 'none',
+ color: FINCEPT.DARK_BG,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ borderRadius: '2px'
+ }}
+ >
+ RELOAD APPLICATION
+ </button>
+ </>
+ )}
+ </div>
+ ) : !paperAdapter.isConnected() ? (
+ <div style={{
+ padding: '20px',
+ textAlign: 'center',
+ border: `1px solid ${FINCEPT.YELLOW}`,
+ backgroundColor: `${FINCEPT.YELLOW}10`
+ }}>
+ <div style={{ color: FINCEPT.YELLOW, fontSize: '11px', fontWeight: 700, marginBottom: '8px' }}>
+ ⏳ CONNECTING...
+ </div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>
+ Establishing connection to {activeBroker}...
+ </div>
+ </div>
+ ) : (
+ <>
+ {/* Paper Trading Banner */}
+ <div style={{
+ padding: '8px',
+ marginBottom: '12px',
+ backgroundColor: `${FINCEPT.GREEN}15`,
+ border: `1px solid ${FINCEPT.GREEN}`,
+ borderRadius: '4px',
+ textAlign: 'center'
+ }}>
+ <div style={{ color: FINCEPT.GREEN, fontSize: '10px', fontWeight: 700 }}>
+ ⚪ PAPER TRADING MODE
+ </div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '2px' }}>
+ Simulated orders • No real funds at risk
+ </div>
+ </div>
+
+ <EnhancedOrderForm
+ symbol={selectedSymbol}
+ currentPrice={currentPrice}
+ balance={balance}
+ onOrderPlaced={() => {
+ console.log('Paper order placed successfully');
+ }}
+ />
+
+ {/* HyperLiquid Vault Manager */}
+ <HyperLiquidVaultManager />
+ </>
+ )
+ ) : (
+ /* LIVE TRADING MODE */
+ !realAdapter ? (
+ <div style={{
+ padding: '20px',
+ textAlign: 'center',
+ border: `1px solid ${FINCEPT.RED}`,
+ backgroundColor: `${FINCEPT.RED}10`
+ }}>
+ <div style={{ color: FINCEPT.RED, fontSize: '12px', fontWeight: 700, marginBottom: '12px' }}>
+ ❌ LIVE ADAPTER NOT CONFIGURED
+ </div>
+ <div style={{ color: FINCEPT.WHITE, fontSize: '10px', marginBottom: '12px' }}>
+ Please configure API credentials for {activeBroker} to enable live trading.
+ </div>
+ <button
+ onClick={() => onTradingModeChange('paper')}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: FINCEPT.GREEN,
+ border: 'none',
+ color: FINCEPT.DARK_BG,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ borderRadius: '2px'
+ }}
+ >
+ SWITCH TO PAPER MODE
+ </button>
+ </div>
+ ) : !realAdapter.isConnected() ? (
+ <div style={{
+ padding: '20px',
+ textAlign: 'center',
+ border: `1px solid ${FINCEPT.YELLOW}`,
+ backgroundColor: `${FINCEPT.YELLOW}10`
+ }}>
+ <div style={{ color: FINCEPT.YELLOW, fontSize: '11px', fontWeight: 700, marginBottom: '8px' }}>
+ ⏳ CONNECTING TO EXCHANGE...
+ </div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '10px' }}>
+ Authenticating with {activeBroker}...
+ </div>
+ </div>
+ ) : (
+ <>
+ {/* LIVE TRADING WARNING BANNER */}
+ <div style={{
+ padding: '10px',
+ marginBottom: '12px',
+ backgroundColor: `${FINCEPT.RED}20`,
+ border: `2px solid ${FINCEPT.RED}`,
+ borderRadius: '4px',
+ textAlign: 'center'
+ }}>
+ <div style={{ color: FINCEPT.RED, fontSize: '12px', fontWeight: 700 }}>
+ 🔴 LIVE TRADING MODE
+ </div>
+ <div style={{ color: FINCEPT.WHITE, fontSize: '10px', marginTop: '4px', fontWeight: 600 }}>
+ ⚠️ REAL FUNDS AT RISK ⚠️
+ </div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginTop: '4px' }}>
+ Orders will be executed on {activeBroker?.toUpperCase()}
+ </div>
+ </div>
+
+ <EnhancedOrderForm
+ symbol={selectedSymbol}
+ currentPrice={currentPrice}
+ balance={balance}
+ onOrderPlaced={() => {
+ console.log('LIVE order placed successfully');
+ }}
+ />
+
+ {/* HyperLiquid Vault Manager */}
+ <HyperLiquidVaultManager />
+ </>
+ )
+ )}
+ </div>
+ </div>
+ );
+}
+
+export default CryptoOrderEntry;
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoStatusBar.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoStatusBar.tsx
new file mode 100644
index 000000000..0a42c6d07
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoStatusBar.tsx
@@ -0,0 +1,42 @@
+// CryptoStatusBar.tsx - Bottom Status Bar for Crypto Trading
+import React from 'react';
+import { FINCEPT } from '../constants';
+
+interface CryptoStatusBarProps {
+ activeBroker: string | null;
+ tradingMode: 'paper' | 'live';
+ isConnected: boolean;
+}
+
+export function CryptoStatusBar({
+ activeBroker,
+ tradingMode,
+ isConnected,
+}: CryptoStatusBarProps) {
+ return (
+ <div style={{
+ borderTop: `1px solid ${FINCEPT.BORDER}`,
+ backgroundColor: FINCEPT.HEADER_BG,
+ padding: '4px 12px',
+ fontSize: '9px',
+ color: FINCEPT.GRAY,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ flexShrink: 0
+ }}>
+ <span>Fincept Terminal v3.1.4 | Professional Crypto Trading Platform</span>
+ <span>
+ Broker: <span style={{ color: FINCEPT.ORANGE }}>{activeBroker?.toUpperCase() || 'NONE'}</span> |
+ Mode: <span style={{ color: tradingMode === 'paper' ? FINCEPT.GREEN : FINCEPT.RED }}>
+ {tradingMode.toUpperCase()}
+ </span> |
+ Status: <span style={{ color: isConnected ? FINCEPT.GREEN : FINCEPT.RED }}>
+ {isConnected ? 'CONNECTED' : 'DISCONNECTED'}
+ </span>
+ </span>
+ </div>
+ );
+}
+
+export default CryptoStatusBar;
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTickerBar.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTickerBar.tsx
new file mode 100644
index 000000000..1d327f229
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTickerBar.tsx
@@ -0,0 +1,238 @@
+// CryptoTickerBar.tsx - Ticker/Price Bar for Crypto Trading
+import React from 'react';
+import { TrendingUp as ArrowUp, TrendingDown as ArrowDown, ChevronDown } from 'lucide-react';
+import { FINCEPT } from '../constants';
+import type { TickerData } from '../types';
+
+interface CryptoTickerBarProps {
+ selectedSymbol: string;
+ tickerData: TickerData | null;
+ availableSymbols: string[];
+ searchQuery: string;
+ showSymbolDropdown: boolean;
+ balance: number;
+ equity: number;
+ tradingMode: 'paper' | 'live';
+ priceChange: number;
+ priceChangePercent: number;
+ onSymbolSelect: (symbol: string) => void;
+ onSearchQueryChange: (query: string) => void;
+ onSymbolDropdownToggle: () => void;
+}
+
+export function CryptoTickerBar({
+ selectedSymbol,
+ tickerData,
+ availableSymbols,
+ searchQuery,
+ showSymbolDropdown,
+ balance,
+ equity,
+ tradingMode,
+ priceChange,
+ priceChangePercent,
+ onSymbolSelect,
+ onSearchQueryChange,
+ onSymbolDropdownToggle,
+}: CryptoTickerBarProps) {
+ const currentPrice = tickerData?.last || tickerData?.price || 0;
+
+ // Calculate 24h price range (High - Low)
+ const spread24h = (tickerData?.high && tickerData?.low) ? (tickerData.high - tickerData.low) : 0;
+ const spread24hPercent = (spread24h > 0 && tickerData?.low && tickerData.low > 0)
+ ? ((spread24h / tickerData.low) * 100)
+ : 0;
+
+ return (
+ <div style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ padding: '10px 12px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '20px',
+ flexShrink: 0
+ }}>
+ {/* Symbol Selector */}
+ <div style={{ position: 'relative', minWidth: '180px' }} data-symbol-selector>
+ <div
+ onClick={onSymbolDropdownToggle}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ cursor: 'pointer',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}
+ >
+ <span style={{ fontSize: '13px', fontWeight: 700, color: FINCEPT.ORANGE }}>{selectedSymbol}</span>
+ <ChevronDown size={12} color={FINCEPT.GRAY} />
+ </div>
+
+ {showSymbolDropdown && (
+ <div style={{
+ position: 'absolute',
+ top: '100%',
+ left: 0,
+ right: 0,
+ marginTop: '4px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ maxHeight: '400px',
+ overflow: 'hidden',
+ zIndex: 1000,
+ boxShadow: `0 4px 16px ${FINCEPT.DARK_BG}80`
+ }}>
+ <div style={{ padding: '8px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>
+ <input
+ type="text"
+ placeholder="Search symbols..."
+ value={searchQuery}
+ onChange={(e) => onSearchQueryChange(e.target.value)}
+ autoFocus
+ style={{
+ width: '100%',
+ padding: '6px 8px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ color: FINCEPT.WHITE,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '11px',
+ outline: 'none'
+ }}
+ />
+ </div>
+ <div style={{ maxHeight: '340px', overflowY: 'auto' }}>
+ {availableSymbols
+ .filter(symbol => symbol.toLowerCase().includes(searchQuery.toLowerCase()))
+ .map(symbol => (
+ <div
+ key={symbol}
+ onClick={() => {
+ onSymbolSelect(symbol);
+ onSearchQueryChange('');
+ }}
+ style={{
+ padding: '8px 12px',
+ cursor: 'pointer',
+ fontSize: '11px',
+ backgroundColor: symbol === selectedSymbol ? `${FINCEPT.ORANGE}20` : 'transparent',
+ color: symbol === selectedSymbol ? FINCEPT.ORANGE : FINCEPT.WHITE,
+ borderLeft: symbol === selectedSymbol ? `3px solid ${FINCEPT.ORANGE}` : 'none'
+ }}
+ onMouseEnter={(e) => {
+ if (symbol !== selectedSymbol) {
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (symbol !== selectedSymbol) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ }
+ }}
+ >
+ {symbol}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Price Display */}
+ <div style={{ display: 'flex', alignItems: 'baseline', gap: '8px' }}>
+ <span style={{ fontSize: '24px', fontWeight: 700, color: FINCEPT.YELLOW, willChange: 'contents', transition: 'none' }}>
+ {tickerData ? `$${currentPrice?.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) || '0.00'}` : '--'}
+ </span>
+ {tickerData && (priceChange !== 0 || priceChangePercent !== 0) && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ {priceChange >= 0 ? (
+ <ArrowUp size={16} color={FINCEPT.GREEN} />
+ ) : (
+ <ArrowDown size={16} color={FINCEPT.RED} />
+ )}
+ <span style={{
+ fontSize: '13px',
+ fontWeight: 600,
+ color: priceChange >= 0 ? FINCEPT.GREEN : FINCEPT.RED
+ }}>
+ {priceChange >= 0 ? '+' : ''}{priceChange.toFixed(2)} ({priceChangePercent >= 0 ? '+' : ''}{priceChangePercent.toFixed(2)}%)
+ </span>
+ </div>
+ )}
+ {tickerData && priceChange === 0 && priceChangePercent === 0 && (
+ <div style={{ fontSize: '11px', color: FINCEPT.GRAY, fontStyle: 'italic' }}>
+ No change data
+ </div>
+ )}
+ </div>
+
+ <div style={{ height: '24px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
+
+ {/* Market Stats */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '24px', fontSize: '11px', willChange: 'contents' }}>
+ <div style={{ minWidth: '60px' }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>BID</div>
+ <div style={{ color: FINCEPT.GREEN, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
+ {tickerData?.bid ? `$${tickerData.bid.toFixed(2)}` : '--'}
+ </div>
+ </div>
+ <div style={{ minWidth: '60px' }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>ASK</div>
+ <div style={{ color: FINCEPT.RED, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
+ {tickerData?.ask ? `$${tickerData.ask.toFixed(2)}` : '--'}
+ </div>
+ </div>
+ <div style={{ minWidth: '120px' }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>24H RANGE</div>
+ <div style={{ color: FINCEPT.CYAN, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
+ {spread24h > 0 ? `$${spread24h.toFixed(2)} (${spread24hPercent.toFixed(2)}%)` : '--'}
+ </div>
+ </div>
+ <div style={{ minWidth: '80px' }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>24H HIGH</div>
+ <div style={{ color: FINCEPT.WHITE, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
+ {tickerData?.high ? `$${tickerData.high.toFixed(2)}` : '--'}
+ </div>
+ </div>
+ <div style={{ minWidth: '80px' }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>24H LOW</div>
+ <div style={{ color: FINCEPT.WHITE, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
+ {tickerData?.low ? `$${tickerData.low.toFixed(2)}` : '--'}
+ </div>
+ </div>
+ <div style={{ minWidth: '100px' }}>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>24H VOLUME</div>
+ <div style={{ color: FINCEPT.PURPLE, fontWeight: 600, willChange: 'contents', transition: 'none' }}>
+ {tickerData?.volume ? (
+ tickerData.quoteVolume
+ ? `$${tickerData.quoteVolume.toLocaleString(undefined, { maximumFractionDigits: 0 })}`
+ : currentPrice > 0
+ ? `$${(tickerData.volume * currentPrice).toLocaleString(undefined, { maximumFractionDigits: 0 })}`
+ : `${tickerData.volume.toLocaleString(undefined, { maximumFractionDigits: 2 })} ${selectedSymbol.split('/')[0]}`
+ ) : '--'}
+ </div>
+ </div>
+ </div>
+
+ {tradingMode === 'paper' && (
+ <>
+ <div style={{ height: '24px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px', fontSize: '11px' }}>
+ <div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>BALANCE</div>
+ <div style={{ color: FINCEPT.CYAN, fontWeight: 600 }}>${balance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>
+ </div>
+ <div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', marginBottom: '2px' }}>EQUITY</div>
+ <div style={{ color: FINCEPT.YELLOW, fontWeight: 600 }}>${equity.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</div>
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
+
+export default CryptoTickerBar;
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTopNav.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTopNav.tsx
new file mode 100644
index 000000000..303263875
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoTopNav.tsx
@@ -0,0 +1,291 @@
+// CryptoTopNav.tsx - Top Navigation Bar for Crypto Trading
+import React from 'react';
+import {
+ Activity, Globe, Wifi, WifiOff, ChevronDown,
+ Settings as SettingsIcon
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { TimezoneSelector } from '@/components/common/TimezoneSelector';
+import { FINCEPT } from '../constants';
+
+interface BrokerInfo {
+ id: string;
+ name: string;
+ type: string;
+}
+
+interface CryptoTopNavProps {
+ activeBroker: string | null;
+ availableBrokers: BrokerInfo[];
+ tradingMode: 'paper' | 'live';
+ isConnected: boolean;
+ showBrokerDropdown: boolean;
+ showSettings: boolean;
+ onBrokerDropdownToggle: () => void;
+ onBrokerChange: (brokerId: string) => void;
+ onTradingModeChange: (mode: 'paper' | 'live') => void;
+ onSettingsToggle: () => void;
+}
+
+export function CryptoTopNav({
+ activeBroker,
+ availableBrokers,
+ tradingMode,
+ isConnected,
+ showBrokerDropdown,
+ showSettings,
+ onBrokerDropdownToggle,
+ onBrokerChange,
+ onTradingModeChange,
+ onSettingsToggle,
+}: CryptoTopNavProps) {
+ const { t } = useTranslation('trading');
+
+ const handleLiveModeClick = () => {
+ if (tradingMode !== 'live') {
+ const confirmed = window.confirm(
+ '⚠️ WARNING: SWITCHING TO LIVE TRADING ⚠️\n\n' +
+ 'You are about to enable LIVE trading mode.\n\n' +
+ '• All orders will be placed with REAL funds\n' +
+ '• Trades will be executed on the actual exchange\n' +
+ '• You may lose money\n\n' +
+ 'Are you sure you want to continue?'
+ );
+ if (confirmed) {
+ onTradingModeChange('live');
+ }
+ }
+ };
+
+ return (
+ <div style={{
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `2px solid ${FINCEPT.ORANGE}`,
+ padding: '6px 12px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ flexShrink: 0,
+ boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20`
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
+ {/* Terminal Branding */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Activity size={18} color={FINCEPT.ORANGE} style={{ filter: 'drop-shadow(0 0 4px ' + FINCEPT.ORANGE + ')' }} />
+ <span style={{
+ color: FINCEPT.ORANGE,
+ fontWeight: 700,
+ fontSize: '14px',
+ letterSpacing: '0.5px',
+ textShadow: `0 0 10px ${FINCEPT.ORANGE}40`
+ }}>
+ {t('header.terminal')}
+ </span>
+ </div>
+
+ <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
+
+ {/* Broker Selector */}
+ <div style={{ position: 'relative' }}>
+ <button
+ onClick={onBrokerDropdownToggle}
+ style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ padding: '4px 10px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.CYAN,
+ cursor: 'pointer',
+ fontSize: '11px',
+ fontWeight: 600,
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => e.currentTarget.style.borderColor = FINCEPT.CYAN}
+ onMouseLeave={(e) => e.currentTarget.style.borderColor = FINCEPT.BORDER}
+ >
+ <Globe size={12} />
+ {activeBroker?.toUpperCase() || t('header.selectBroker')}
+ <ChevronDown size={10} />
+ </button>
+
+ {showBrokerDropdown && (
+ <div style={{
+ position: 'absolute',
+ top: '100%',
+ left: 0,
+ marginTop: '4px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ minWidth: '200px',
+ zIndex: 1000,
+ boxShadow: `0 4px 16px ${FINCEPT.DARK_BG}80`
+ }}>
+ {availableBrokers.map((broker) => (
+ <div
+ key={broker.id}
+ onClick={() => onBrokerChange(broker.id)}
+ style={{
+ padding: '10px 12px',
+ cursor: 'pointer',
+ fontSize: '11px',
+ backgroundColor: activeBroker === broker.id ? `${FINCEPT.ORANGE}20` : 'transparent',
+ borderLeft: activeBroker === broker.id ? `3px solid ${FINCEPT.ORANGE}` : '3px solid transparent',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ if (activeBroker !== broker.id) {
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (activeBroker !== broker.id) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ }
+ }}
+ >
+ <div>
+ <div style={{ color: FINCEPT.WHITE, fontWeight: 600 }}>{broker.name}</div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px' }}>{broker.type.toUpperCase()}</div>
+ </div>
+ {activeBroker === broker.id && (
+ <div style={{
+ width: '6px',
+ height: '6px',
+ borderRadius: '50%',
+ backgroundColor: FINCEPT.GREEN,
+ boxShadow: `0 0 6px ${FINCEPT.GREEN}`
+ }} />
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
+
+ {/* Trading Mode Toggle */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ padding: '4px 12px',
+ backgroundColor: tradingMode === 'live' ? `${FINCEPT.RED}20` : `${FINCEPT.GREEN}20`,
+ border: `2px solid ${tradingMode === 'live' ? FINCEPT.RED : FINCEPT.GREEN}`,
+ borderRadius: '4px'
+ }}>
+ {/* Mode Indicator */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px'
+ }}>
+ <div style={{
+ width: '8px',
+ height: '8px',
+ borderRadius: '50%',
+ backgroundColor: tradingMode === 'live' ? FINCEPT.RED : FINCEPT.GREEN,
+ boxShadow: `0 0 8px ${tradingMode === 'live' ? FINCEPT.RED : FINCEPT.GREEN}`,
+ animation: tradingMode === 'live' ? 'pulse 1s infinite' : 'none'
+ }} />
+ <span style={{
+ fontSize: '11px',
+ fontWeight: 700,
+ color: tradingMode === 'live' ? FINCEPT.RED : FINCEPT.GREEN,
+ letterSpacing: '1px'
+ }}>
+ {tradingMode === 'live' ? '🔴 LIVE' : '⚪ PAPER'}
+ </span>
+ </div>
+
+ <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
+
+ <button
+ onClick={() => onTradingModeChange('paper')}
+ style={{
+ padding: '4px 10px',
+ backgroundColor: tradingMode === 'paper' ? FINCEPT.GREEN : FINCEPT.PANEL_BG,
+ border: `1px solid ${tradingMode === 'paper' ? FINCEPT.GREEN : FINCEPT.BORDER}`,
+ color: tradingMode === 'paper' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ transition: 'all 0.2s'
+ }}
+ >
+ {t('header.paper')}
+ </button>
+ <button
+ onClick={handleLiveModeClick}
+ style={{
+ padding: '4px 10px',
+ backgroundColor: tradingMode === 'live' ? FINCEPT.RED : FINCEPT.PANEL_BG,
+ border: `1px solid ${tradingMode === 'live' ? FINCEPT.RED : FINCEPT.BORDER}`,
+ color: tradingMode === 'live' ? FINCEPT.WHITE : FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ transition: 'all 0.2s'
+ }}
+ >
+ {t('header.live')}
+ </button>
+ </div>
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ {/* Connection Status */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '10px' }}>
+ {isConnected ? (
+ <>
+ <Wifi size={12} color={FINCEPT.GREEN} />
+ <span style={{ color: FINCEPT.GREEN }}>CONNECTED</span>
+ </>
+ ) : (
+ <>
+ <WifiOff size={12} color={FINCEPT.RED} />
+ <span style={{ color: FINCEPT.RED }}>DISCONNECTED</span>
+ </>
+ )}
+ </div>
+
+ <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
+
+ <TimezoneSelector compact />
+
+ <button
+ onClick={onSettingsToggle}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ fontSize: '10px',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ e.currentTarget.style.color = FINCEPT.ORANGE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.color = FINCEPT.GRAY;
+ }}
+ >
+ <SettingsIcon size={12} />
+ </button>
+ </div>
+ </div>
+ );
+}
+
+export default CryptoTopNav;
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoWatchlist.tsx b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoWatchlist.tsx
new file mode 100644
index 000000000..0a6822103
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/CryptoWatchlist.tsx
@@ -0,0 +1,228 @@
+// CryptoWatchlist.tsx - Left Sidebar Watchlist for Crypto Trading
+import React from 'react';
+import { FINCEPT } from '../constants';
+import type { WatchlistPrice, LeftSidebarViewType } from '../types';
+import { AIAgentsPanel } from '../../trading/ai-agents/AIAgentsPanel';
+import { LeaderboardPanel } from '../../trading/ai-agents/LeaderboardPanel';
+import type { Position } from '../types';
+
+interface CryptoWatchlistProps {
+ watchlist: string[];
+ watchlistPrices: Record<string, WatchlistPrice>;
+ selectedSymbol: string;
+ leftSidebarView: LeftSidebarViewType;
+ positions: Position[];
+ equity: number;
+ onSymbolSelect: (symbol: string) => void;
+ onViewChange: (view: LeftSidebarViewType) => void;
+}
+
+export function CryptoWatchlist({
+ watchlist,
+ watchlistPrices,
+ selectedSymbol,
+ leftSidebarView,
+ positions,
+ equity,
+ onSymbolSelect,
+ onViewChange,
+}: CryptoWatchlistProps) {
+ return (
+ <div style={{
+ width: '320px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ {/* Toggle Header */}
+ <div style={{
+ padding: '6px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ gap: '4px'
+ }}>
+ <button
+ onClick={() => onViewChange('watchlist')}
+ style={{
+ flex: 1,
+ padding: '6px 8px',
+ backgroundColor: leftSidebarView === 'watchlist' ? FINCEPT.ORANGE : 'transparent',
+ border: 'none',
+ color: leftSidebarView === 'watchlist' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s',
+ borderRadius: '2px'
+ }}
+ >
+ WATCH
+ </button>
+ <button
+ onClick={() => onViewChange('ai-agents')}
+ style={{
+ flex: 1,
+ padding: '6px 8px',
+ backgroundColor: leftSidebarView === 'ai-agents' ? FINCEPT.ORANGE : 'transparent',
+ border: 'none',
+ color: leftSidebarView === 'ai-agents' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s',
+ borderRadius: '2px'
+ }}
+ >
+ AGENTS
+ </button>
+ <button
+ onClick={() => onViewChange('leaderboard')}
+ style={{
+ flex: 1,
+ padding: '6px 8px',
+ backgroundColor: leftSidebarView === 'leaderboard' ? FINCEPT.ORANGE : 'transparent',
+ border: 'none',
+ color: leftSidebarView === 'leaderboard' ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '9px',
+ fontWeight: 700,
+ letterSpacing: '0.5px',
+ transition: 'all 0.2s',
+ borderRadius: '2px'
+ }}
+ >
+ LEADER
+ </button>
+ </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={() => onSymbolSelect(symbol)}
+ style={{
+ padding: '8px 10px',
+ cursor: 'pointer',
+ backgroundColor: selectedSymbol === symbol ? `${FINCEPT.ORANGE}15` : 'transparent',
+ borderLeft: selectedSymbol === symbol ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ borderRight: idx % 2 === 0 ? `1px solid ${FINCEPT.BORDER}` : 'none',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ if (selectedSymbol !== symbol) {
+ e.currentTarget.style.backgroundColor = FINCEPT.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 ? FINCEPT.ORANGE : FINCEPT.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: FINCEPT.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 ? FINCEPT.GREEN : FINCEPT.RED,
+ fontFamily: 'monospace',
+ fontWeight: 700
+ }}>
+ {watchlistPrices[symbol].change >= 0 ? '▲' : '▼'} {Math.abs(watchlistPrices[symbol].change).toFixed(2)}%
+ </div>
+ </div>
+ ) : (
+ <div style={{
+ fontSize: '9px',
+ color: FINCEPT.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>
+ );
+}
+
+export default CryptoWatchlist;
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/index.ts b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/index.ts
new file mode 100644
index 000000000..eff56ac17
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/components/index.ts
@@ -0,0 +1,9 @@
+// Export all crypto trading components
+export { CryptoTopNav } from './CryptoTopNav';
+export { CryptoTickerBar } from './CryptoTickerBar';
+export { CryptoWatchlist } from './CryptoWatchlist';
+export { CryptoOrderBook } from './CryptoOrderBook';
+export { CryptoOrderEntry } from './CryptoOrderEntry';
+export { CryptoChartArea } from './CryptoChartArea';
+export { CryptoBottomPanel } from './CryptoBottomPanel';
+export { CryptoStatusBar } from './CryptoStatusBar';
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/constants.ts b/fincept-terminal-desktop/src/components/tabs/crypto-trading/constants.ts
new file mode 100644
index 000000000..026dc2f02
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/constants.ts
@@ -0,0 +1,56 @@
+// Fincept Professional Color Palette for Crypto Trading
+export const FINCEPT = {
+ 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'
+} as const;
+
+// Top 30 most traded crypto pairs
+export const DEFAULT_CRYPTO_WATCHLIST = [
+ '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'
+];
+
+// CSS styles for the crypto trading terminal
+export const CRYPTO_TERMINAL_STYLES = `
+ @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600;700&display=swap');
+
+ *::-webkit-scrollbar { width: 6px; height: 6px; }
+ *::-webkit-scrollbar-track { background: ${FINCEPT.DARK_BG}; }
+ *::-webkit-scrollbar-thumb { background: ${FINCEPT.BORDER}; border-radius: 3px; }
+ *::-webkit-scrollbar-thumb:hover { background: ${FINCEPT.MUTED}; }
+
+ .terminal-glow {
+ text-shadow: 0 0 10px ${FINCEPT.ORANGE}40;
+ }
+
+ .price-flash {
+ animation: flash 0.3s ease-out;
+ }
+
+ @keyframes flash {
+ 0% { background-color: ${FINCEPT.YELLOW}40; }
+ 100% { background-color: transparent; }
+ }
+
+ @keyframes pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.5; }
+ }
+`;
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/index.ts b/fincept-terminal-desktop/src/components/tabs/crypto-trading/index.ts
new file mode 100644
index 000000000..60fc7cef4
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/index.ts
@@ -0,0 +1,24 @@
+// Crypto Trading Tab - Main exports
+export { CryptoTradingTab } from './CryptoTradingTab';
+export { default } from './CryptoTradingTab';
+
+// Re-export types
+export type {
+ OrderBook,
+ OrderBookLevel,
+ Position,
+ Order,
+ TickerData,
+ TradeData,
+ WatchlistPrice,
+ CenterViewType,
+ RightPanelViewType,
+ LeftSidebarViewType,
+ BottomPanelTabType,
+} from './types';
+
+// Re-export constants
+export { FINCEPT, DEFAULT_CRYPTO_WATCHLIST, CRYPTO_TERMINAL_STYLES } from './constants';
+
+// Re-export components
+export * from './components';
diff --git a/fincept-terminal-desktop/src/components/tabs/crypto-trading/types.ts b/fincept-terminal-desktop/src/components/tabs/crypto-trading/types.ts
new file mode 100644
index 000000000..8bfd07963
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/crypto-trading/types.ts
@@ -0,0 +1,69 @@
+// Types for Crypto Trading Tab
+
+export interface OrderBookLevel {
+ price: number;
+ size: number;
+}
+
+export interface OrderBook {
+ bids: OrderBookLevel[];
+ asks: OrderBookLevel[];
+ symbol: string;
+ checksum?: number;
+}
+
+export interface Position {
+ symbol: string;
+ side: 'long' | 'short';
+ quantity: number;
+ entryPrice: number;
+ positionValue: number;
+ currentPrice: number;
+ unrealizedPnl: number;
+ pnlPercent: number;
+}
+
+export interface Order {
+ id: string;
+ symbol: string;
+ side: 'buy' | 'sell';
+ type: string;
+ quantity: number;
+ price?: number;
+ status: string;
+ createdAt: string;
+}
+
+export interface TickerData {
+ symbol: string;
+ price: number;
+ bid?: number;
+ ask?: number;
+ last?: number;
+ volume?: number;
+ high?: number;
+ low?: number;
+ change?: number;
+ changePercent?: number;
+ open?: number;
+ quoteVolume?: number;
+}
+
+export interface TradeData {
+ symbol: string;
+ price: number;
+ quantity: number;
+ side: 'buy' | 'sell' | 'unknown';
+ timestamp: number;
+}
+
+export interface WatchlistPrice {
+ price: number;
+ change: number;
+}
+
+// UI State Types
+export type CenterViewType = 'chart' | 'depth' | 'trades';
+export type RightPanelViewType = 'orderbook' | 'volume' | 'modelchat';
+export type LeftSidebarViewType = 'watchlist' | 'ai-agents' | 'leaderboard';
+export type BottomPanelTabType = 'positions' | 'orders' | 'history' | 'trades' | 'stats' | 'features' | 'cross-exchange' | 'grid-trading';
diff --git a/fincept-terminal-desktop/src/components/tabs/DashboardTab.tsx b/fincept-terminal-desktop/src/components/tabs/dashboard/DashboardTab.tsx
similarity index 98%
rename from fincept-terminal-desktop/src/components/tabs/DashboardTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/dashboard/DashboardTab.tsx
index 3754bdd2d..5f90fc674 100644
--- a/fincept-terminal-desktop/src/components/tabs/DashboardTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/DashboardTab.tsx
@@ -1,10 +1,10 @@
import React, { useState, useEffect } from 'react';
import GridLayout, { Layout } from 'react-grid-layout';
import { Plus, RotateCcw, Save, Info } from 'lucide-react';
-import { createDashboardTabTour } from './tours/dashboardTabTour';
+import { createDashboardTabTour } from '@/components/tabs/tours/dashboardTabTour';
import { useTerminalTheme } from '@/contexts/ThemeContext';
import { useTranslation } from 'react-i18next';
-import { sqliteService, saveSetting, getSetting } from '../../services/core/sqliteService';
+import { sqliteService, saveSetting, getSetting } from '@/services/core/sqliteService';
import { TabFooter } from '@/components/common/TabFooter';
import {
NewsWidget,
@@ -27,8 +27,8 @@ import {
PerformanceWidget,
WidgetType,
WidgetConfig
-} from './dashboard/widgets';
-import { AddWidgetModal } from './dashboard/AddWidgetModal';
+} from './widgets';
+import { AddWidgetModal } from './AddWidgetModal';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';
diff --git a/fincept-terminal-desktop/src/components/tabs/dashboard/index.ts b/fincept-terminal-desktop/src/components/tabs/dashboard/index.ts
new file mode 100644
index 000000000..9993942e9
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/dashboard/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./DashboardTab";
+export { default as DashboardTab } from "./DashboardTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/data-mapping/index.ts b/fincept-terminal-desktop/src/components/tabs/data-mapping/index.ts
index 3fd8393d0..4b85ffd33 100644
--- a/fincept-terminal-desktop/src/components/tabs/data-mapping/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/data-mapping/index.ts
@@ -1,5 +1,8 @@
// Data Mapping System - Main exports
+// Default export for lazy loading
+export { default } from './DataMappingTab';
+
// Main component
export { default as DataMappingTab } from './DataMappingTab';
diff --git a/fincept-terminal-desktop/src/components/tabs/data-sources/index.ts b/fincept-terminal-desktop/src/components/tabs/data-sources/index.ts
new file mode 100644
index 000000000..af467f98a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/data-sources/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./DataSourcesTab";
+export { default as DataSourcesTab } from "./DataSourcesTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/dbnomics/DBnomicsTab.tsx b/fincept-terminal-desktop/src/components/tabs/dbnomics/DBnomicsTab.tsx
new file mode 100644
index 000000000..73e0f5fd9
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/dbnomics/DBnomicsTab.tsx
@@ -0,0 +1,439 @@
+import React, { memo, useMemo, useCallback } from 'react';
+import { RefreshCw, Download } from 'lucide-react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
+import { TabFooter } from '@/components/common/TabFooter';
+import { useTranslation } from 'react-i18next';
+
+import { useDBnomicsData } from './hooks';
+import { SelectionPanel, DBnomicsChart, DataTable } from './components';
+import { CHART_TYPES } from './constants';
+import type { ChartType } from './types';
+
+// Memoized series tag component
+const SeriesTag = memo(({
+ series,
+ index,
+ onRemove,
+ colors,
+}: {
+ series: { series_name: string; color: string };
+ index: number;
+ onRemove: (index: number) => void;
+ colors: any;
+}) => (
+ <div
+ style={{
+ display: 'inline-flex',
+ alignItems: 'center',
+ gap: '4px',
+ padding: '3px 6px',
+ backgroundColor: '#1a1a1a',
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: '2px',
+ marginRight: '4px',
+ marginBottom: '4px',
+ fontSize: '9px',
+ }}
+ >
+ <div style={{ width: '8px', height: '8px', backgroundColor: series.color, borderRadius: '50%' }} />
+ <span>{series.series_name.substring(0, 20)}</span>
+ <button
+ onClick={() => onRemove(index)}
+ style={{
+ padding: '0 4px',
+ backgroundColor: 'transparent',
+ color: colors.alert,
+ border: 'none',
+ cursor: 'pointer',
+ fontSize: '10px',
+ }}
+ >
+ ×
+ </button>
+ </div>
+));
+
+SeriesTag.displayName = 'SeriesTag';
+
+// Memoized chart type button
+const ChartTypeButton = memo(({
+ type,
+ isActive,
+ onClick,
+ colors,
+}: {
+ type: ChartType;
+ isActive: boolean;
+ onClick: () => void;
+ colors: any;
+}) => (
+ <button
+ onClick={onClick}
+ style={{
+ padding: '3px 8px',
+ backgroundColor: isActive ? colors.info : '#2a2a2a',
+ color: '#fff',
+ border: `1px solid ${colors.textMuted}`,
+ cursor: 'pointer',
+ fontSize: '9px',
+ textTransform: 'uppercase',
+ }}
+ >
+ {type}
+ </button>
+));
+
+ChartTypeButton.displayName = 'ChartTypeButton';
+
+// Memoized comparison slot component
+const ComparisonSlot = memo(({
+ slot,
+ slotIndex,
+ chartType,
+ onChartTypeChange,
+ colors,
+}: {
+ slot: any[];
+ slotIndex: number;
+ chartType: ChartType;
+ onChartTypeChange: (type: ChartType) => void;
+ colors: any;
+}) => (
+ <div
+ style={{
+ border: `1px solid ${colors.textMuted}`,
+ padding: '12px',
+ backgroundColor: colors.panel,
+ minHeight: '280px',
+ display: 'flex',
+ flexDirection: 'column',
+ }}
+ >
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
+ <div style={{ color: colors.warning, fontSize: '10px' }}>SLOT {slotIndex + 1}</div>
+ <select
+ value={chartType}
+ onChange={(e) => onChartTypeChange(e.target.value as ChartType)}
+ style={{
+ padding: '2px 4px',
+ backgroundColor: '#1a1a1a',
+ color: colors.text,
+ border: `1px solid ${colors.textMuted}`,
+ fontSize: '8px',
+ fontFamily: 'Consolas, monospace',
+ }}
+ >
+ <option value="line">LINE</option>
+ <option value="bar">BAR</option>
+ <option value="area">AREA</option>
+ <option value="scatter">SCATTER</option>
+ <option value="candlestick">CANDLE</option>
+ </select>
+ </div>
+ <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '240px' }}>
+ {slot.length > 0 ? (
+ <DBnomicsChart seriesArray={slot} chartType={chartType} compact colors={colors} />
+ ) : (
+ <div style={{ color: colors.textMuted, textAlign: 'center', fontSize: '10px' }}>Empty Slot</div>
+ )}
+ </div>
+ </div>
+));
+
+ComparisonSlot.displayName = 'ComparisonSlot';
+
+function DBnomicsTab() {
+ const { t } = useTranslation('dbnomics');
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
+
+ // Build chart colors from theme
+ const chartColors = useMemo(
+ () => [colors.primary, colors.info, colors.secondary, colors.warning, colors.purple, colors.accent],
+ [colors]
+ );
+
+ // Use the data hook
+ const {
+ providers,
+ datasets,
+ seriesList,
+ currentData,
+ selectedProvider,
+ selectedDataset,
+ selectedSeries,
+ slots,
+ slotChartTypes,
+ singleViewSeries,
+ singleChartType,
+ activeView,
+ loading,
+ status,
+ loadProviders,
+ selectProvider,
+ selectDataset,
+ selectSeries,
+ refreshCurrentSeries,
+ addSlot,
+ removeSlot,
+ addToSlot,
+ removeFromSlot,
+ setSlotChartType,
+ addToSingleView,
+ removeFromSingleView,
+ setSingleChartType,
+ setActiveView,
+ clearAll,
+ exportData,
+ } = useDBnomicsData(chartColors);
+
+ // Memoized handlers
+ const handleViewChange = useCallback((view: 'single' | 'comparison') => {
+ setActiveView(view);
+ }, [setActiveView]);
+
+ const handleChartTypeChange = useCallback((type: ChartType) => {
+ setSingleChartType(type);
+ }, [setSingleChartType]);
+
+ // Memoized styles
+ const containerStyle = useMemo(
+ () => ({
+ width: '100%',
+ height: '100%',
+ backgroundColor: colors.background,
+ color: colors.text,
+ fontFamily: 'Consolas, monospace',
+ fontSize: '11px',
+ overflow: 'hidden',
+ display: 'flex',
+ flexDirection: 'column' as const,
+ }),
+ [colors.background, colors.text]
+ );
+
+ const scrollbarStyle = useMemo(
+ () => `
+ *::-webkit-scrollbar { width: 8px; height: 8px; }
+ *::-webkit-scrollbar-track { background: #1a1a1a; }
+ *::-webkit-scrollbar-thumb { background: ${colors.textMuted}; border-radius: 4px; }
+ *::-webkit-scrollbar-thumb:hover { background: #525252; }
+ `,
+ [colors.textMuted]
+ );
+
+ const headerStyle = useMemo(
+ () => ({
+ padding: '8px 12px',
+ borderBottom: `1px solid ${colors.textMuted}`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ flexWrap: 'wrap' as const,
+ }),
+ [colors.textMuted]
+ );
+
+ return (
+ <div style={containerStyle}>
+ <style>{scrollbarStyle}</style>
+
+ {/* Header */}
+ <div style={headerStyle}>
+ <span style={{ color: colors.primary, fontWeight: 'bold' }}>{t('title', 'DBNOMICS ECONOMIC DATABASE')}</span>
+ <span style={{ color: colors.secondary, fontSize: '10px' }}>● {status}</span>
+ <span style={{ color: colors.warning, fontSize: '10px' }}>Providers: {providers.length}</span>
+ <div style={{ flex: 1 }} />
+ <button
+ onClick={loadProviders}
+ disabled={loading}
+ style={{
+ padding: '3px 10px',
+ backgroundColor: '#2a2a2a',
+ color: colors.text,
+ border: `1px solid ${colors.textMuted}`,
+ cursor: loading ? 'not-allowed' : 'pointer',
+ fontSize: '9px',
+ }}
+ >
+ {t('toolbar.fetch', 'FETCH')}
+ </button>
+ <button
+ onClick={refreshCurrentSeries}
+ disabled={!currentData}
+ style={{
+ padding: '3px 10px',
+ backgroundColor: '#2a2a2a',
+ color: colors.text,
+ border: `1px solid ${colors.textMuted}`,
+ cursor: !currentData ? 'not-allowed' : 'pointer',
+ fontSize: '9px',
+ }}
+ >
+ <RefreshCw size={10} style={{ display: 'inline', marginRight: '4px' }} />
+ {t('toolbar.refresh', 'REFRESH')}
+ </button>
+ <button
+ onClick={exportData}
+ disabled={!currentData}
+ style={{
+ padding: '3px 10px',
+ backgroundColor: '#2a2a2a',
+ color: colors.text,
+ border: `1px solid ${colors.textMuted}`,
+ cursor: !currentData ? 'not-allowed' : 'pointer',
+ fontSize: '9px',
+ }}
+ >
+ <Download size={10} style={{ display: 'inline', marginRight: '4px' }} />
+ {t('toolbar.export', 'EXPORT')}
+ </button>
+ </div>
+
+ {/* Main Content */}
+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
+ {/* Left Panel - Selection */}
+ <SelectionPanel
+ providers={providers}
+ datasets={datasets}
+ seriesList={seriesList}
+ selectedProvider={selectedProvider}
+ selectedDataset={selectedDataset}
+ selectedSeries={selectedSeries}
+ currentData={currentData}
+ slots={slots}
+ onSelectProvider={selectProvider}
+ onSelectDataset={selectDataset}
+ onSelectSeries={selectSeries}
+ onAddToSingleView={addToSingleView}
+ onClearAll={clearAll}
+ onAddSlot={addSlot}
+ onRemoveSlot={removeSlot}
+ onAddToSlot={addToSlot}
+ onRemoveFromSlot={removeFromSlot}
+ colors={colors}
+ />
+
+ {/* Right Panel - Charts */}
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
+ {/* View Toggle */}
+ <div
+ style={{
+ padding: '8px 12px',
+ borderBottom: `1px solid ${colors.textMuted}`,
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'center',
+ }}
+ >
+ <button
+ onClick={() => handleViewChange('single')}
+ style={{
+ padding: '4px 12px',
+ backgroundColor: activeView === 'single' ? colors.primary : '#2a2a2a',
+ color: '#fff',
+ border: `1px solid ${colors.textMuted}`,
+ cursor: 'pointer',
+ fontSize: '10px',
+ }}
+ >
+ SINGLE
+ </button>
+ <button
+ onClick={() => handleViewChange('comparison')}
+ style={{
+ padding: '4px 12px',
+ backgroundColor: activeView === 'comparison' ? colors.primary : '#2a2a2a',
+ color: '#fff',
+ border: `1px solid ${colors.textMuted}`,
+ cursor: 'pointer',
+ fontSize: '10px',
+ }}
+ >
+ COMPARE
+ </button>
+
+ {activeView === 'single' && (
+ <>
+ <div style={{ color: colors.textMuted, fontSize: '9px', marginLeft: '8px' }}>Chart Type:</div>
+ {CHART_TYPES.map((type) => (
+ <ChartTypeButton
+ key={type}
+ type={type}
+ isActive={singleChartType === type}
+ onClick={() => handleChartTypeChange(type)}
+ colors={colors}
+ />
+ ))}
+ </>
+ )}
+ </div>
+
+ {/* Content Area */}
+ <div style={{ flex: 1, overflowY: 'auto', padding: '12px' }}>
+ {activeView === 'single' ? (
+ <div>
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ color: colors.primary, fontSize: '11px', marginBottom: '6px' }}>
+ SINGLE VIEW ({singleViewSeries.length} series)
+ </div>
+ {singleViewSeries.map((s, idx) => (
+ <SeriesTag key={idx} series={s} index={idx} onRemove={removeFromSingleView} colors={colors} />
+ ))}
+ </div>
+
+ {singleViewSeries.length > 0 ? (
+ <>
+ <DBnomicsChart seriesArray={singleViewSeries} chartType={singleChartType} colors={colors} />
+ <DataTable seriesArray={singleViewSeries} colors={colors} />
+ </>
+ ) : (
+ <div style={{ color: colors.textMuted, textAlign: 'center', paddingTop: '40px' }}>
+ Add series to view
+ </div>
+ )}
+ </div>
+ ) : (
+ <div>
+ <div style={{ color: colors.primary, marginBottom: '12px', fontSize: '11px' }}>
+ COMPARISON DASHBOARD
+ </div>
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fit, minmax(380px, 1fr))',
+ gap: '16px',
+ }}
+ >
+ {slots.map((slot, idx) => (
+ <ComparisonSlot
+ key={idx}
+ slot={slot}
+ slotIndex={idx}
+ chartType={slotChartTypes[idx]}
+ onChartTypeChange={(type) => setSlotChartType(idx, type)}
+ colors={colors}
+ />
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+
+ <TabFooter
+ tabName="DBNOMICS ECONOMIC DATABASE"
+ leftInfo={[
+ { label: `Providers: ${providers.length}`, color: colors.textMuted },
+ { label: `Datasets: ${datasets.length}`, color: colors.textMuted },
+ { label: `Series: ${seriesList.length}`, color: colors.textMuted },
+ ]}
+ statusInfo={`${status} | Dataset: ${selectedDataset ? 'Selected' : 'None'}`}
+ backgroundColor={colors.panel}
+ borderColor={colors.textMuted}
+ />
+ </div>
+ );
+}
+
+export default memo(DBnomicsTab);
diff --git a/fincept-terminal-desktop/src/components/tabs/dbnomics/components/DBnomicsChart.tsx b/fincept-terminal-desktop/src/components/tabs/dbnomics/components/DBnomicsChart.tsx
new file mode 100644
index 000000000..7129d7413
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/dbnomics/components/DBnomicsChart.tsx
@@ -0,0 +1,233 @@
+import React, { memo, useMemo } from 'react';
+import type { DataPoint, ChartType } from '../types';
+
+interface DBnomicsChartProps {
+ seriesArray: DataPoint[];
+ chartType: ChartType;
+ compact?: boolean;
+ colors: any;
+}
+
+function DBnomicsChart({ seriesArray, chartType, compact = false, colors }: DBnomicsChartProps) {
+ // Memoize all chart calculations
+ const chartData = useMemo(() => {
+ if (seriesArray.length === 0) return null;
+
+ const h = compact ? 240 : 400;
+ const ml = 60;
+ const mr = 20;
+ const mt = 20;
+ const mb = 50;
+ const actualWidth = compact ? 380 : 800;
+ const pw = actualWidth - ml - mr;
+ const ph = h - mt - mb;
+
+ // Aggregate all observations
+ const allValues = seriesArray.flatMap(s => s.observations.map(o => o.value));
+ const yMin = Math.min(...allValues) * 0.9;
+ const yMax = Math.max(...allValues) * 1.1;
+ const yRange = yMax - yMin || 1;
+
+ // Pre-sort observations for each series
+ const sortedSeries = seriesArray.map(series => ({
+ ...series,
+ sortedObs: [...series.observations].sort(
+ (a, b) => new Date(a.period).getTime() - new Date(b.period).getTime()
+ ),
+ }));
+
+ return {
+ h,
+ ml,
+ mr,
+ mt,
+ mb,
+ actualWidth,
+ pw,
+ ph,
+ yMin,
+ yMax,
+ yRange,
+ sortedSeries,
+ };
+ }, [seriesArray, compact]);
+
+ // Memoize Y-axis grid data
+ const yAxisData = useMemo(() => {
+ if (!chartData) return [];
+ const { yMin, yRange, h, mb, ph } = chartData;
+ return [0, 1, 2, 3, 4].map(i => ({
+ val: yMin + (yRange * i) / 4,
+ y: h - mb - (ph * i) / 4,
+ }));
+ }, [chartData]);
+
+ // Memoize X-axis labels
+ const xAxisLabels = useMemo(() => {
+ if (!chartData || chartData.sortedSeries.length === 0) return [];
+ const { sortedSeries, ml, pw, h, mb } = chartData;
+ const firstSortedObs = sortedSeries[0].sortedObs;
+
+ return firstSortedObs
+ .map((obs, idx, arr) => {
+ if (idx % Math.max(1, Math.floor(arr.length / 6)) !== 0 && idx !== arr.length - 1) {
+ return null;
+ }
+ const x = ml + (pw * idx) / (arr.length - 1 || 1);
+ return { x, y: h - mb + 15, label: obs.period.substring(0, 7) };
+ })
+ .filter(Boolean);
+ }, [chartData]);
+
+ if (!chartData || seriesArray.length === 0) return null;
+
+ const { h, ml, mr, mt, mb, actualWidth, pw, ph, yMin, yRange, sortedSeries } = chartData;
+
+ return (
+ <svg
+ width={compact ? '100%' : 800}
+ height={h}
+ viewBox={`0 0 ${actualWidth} ${h}`}
+ preserveAspectRatio="xMidYMid meet"
+ style={{
+ backgroundColor: colors.panel,
+ width: '100%',
+ height: 'auto',
+ maxHeight: compact ? '240px' : '400px',
+ }}
+ >
+ {/* Axes */}
+ <line x1={ml} y1={mt} x2={ml} y2={h - mb} stroke={colors.textMuted} strokeWidth="1" />
+ <line x1={ml} y1={h - mb} x2={actualWidth - mr} y2={h - mb} stroke={colors.textMuted} strokeWidth="1" />
+
+ {/* Y-axis grid and labels */}
+ {yAxisData.map((item, i) => (
+ <g key={i}>
+ <line x1={ml} y1={item.y} x2={actualWidth - mr} y2={item.y} stroke="#1a1a1a" strokeDasharray="2,2" />
+ <text x={ml - 8} y={item.y + 3} textAnchor="end" fill={colors.textMuted} fontSize="9" fontFamily="monospace">
+ {item.val.toFixed(1)}
+ </text>
+ </g>
+ ))}
+
+ {/* Render each series */}
+ {sortedSeries.map((series, sIdx) => {
+ const sorted = series.sortedObs;
+
+ return (
+ <g key={sIdx}>
+ {/* Area fill for area chart */}
+ {chartType === 'area' && (
+ <polygon
+ points={(() => {
+ const points = sorted
+ .map((o, i) => {
+ const xi = ml + (pw * i) / (sorted.length - 1 || 1);
+ const oValue = typeof o.value === 'number' ? o.value : Number(o.value);
+ const yi = h - mb - (ph * ((oValue - yMin) / yRange));
+ return `${xi},${yi}`;
+ })
+ .join(' ');
+ return `${points} ${actualWidth - mr},${h - mb} ${ml},${h - mb}`;
+ })()}
+ fill={series.color}
+ opacity="0.2"
+ />
+ )}
+
+ {sorted.map((obs, idx) => {
+ const x = ml + (pw * idx) / (sorted.length - 1 || 1);
+ const y = h - mb - (ph * ((Number(obs.value) - yMin) / yRange));
+ const barWidth = (pw / sorted.length) * 0.8;
+
+ if (chartType === 'line' || chartType === 'area') {
+ return (
+ <g key={idx}>
+ <circle cx={x} cy={y} r="2" fill={series.color} />
+ {idx < sorted.length - 1 && (
+ <line
+ x1={x}
+ y1={y}
+ x2={ml + (pw * (idx + 1)) / (sorted.length - 1 || 1)}
+ y2={h - mb - (ph * ((Number(sorted[idx + 1].value) - yMin) / yRange))}
+ stroke={series.color}
+ strokeWidth="1.5"
+ />
+ )}
+ </g>
+ );
+ } else if (chartType === 'bar') {
+ return (
+ <rect
+ key={idx}
+ x={x - barWidth / 2 + (sIdx * barWidth) / seriesArray.length}
+ y={y}
+ width={barWidth / seriesArray.length}
+ height={h - mb - y}
+ fill={series.color}
+ opacity="0.8"
+ />
+ );
+ } else if (chartType === 'scatter') {
+ return <circle key={idx} cx={x} cy={y} r="3" fill={series.color} opacity="0.7" />;
+ } else if (chartType === 'candlestick') {
+ const nextObs = sorted[idx + 1];
+ const open = obs.value;
+ const close = nextObs ? nextObs.value : obs.value;
+ const high = Math.max(open, close);
+ const low = Math.min(open, close);
+ const yHigh = h - mb - (ph * ((high - yMin) / yRange));
+ const yLow = h - mb - (ph * ((low - yMin) / yRange));
+ const yOpen = h - mb - (ph * ((open - yMin) / yRange));
+ const yClose = h - mb - (ph * ((close - yMin) / yRange));
+
+ return (
+ <g key={idx}>
+ <line x1={x} y1={yHigh} x2={x} y2={yLow} stroke={series.color} strokeWidth="1" />
+ <rect
+ x={x - 3}
+ y={Math.min(yOpen, yClose)}
+ width={6}
+ height={Math.abs(yClose - yOpen) || 1}
+ fill={close >= open ? colors.secondary : colors.alert}
+ />
+ </g>
+ );
+ }
+ return null;
+ })}
+ </g>
+ );
+ })}
+
+ {/* X-axis labels */}
+ {xAxisLabels.map((item, idx) =>
+ item ? (
+ <text
+ key={idx}
+ x={item.x}
+ y={item.y}
+ textAnchor="middle"
+ fill={colors.textMuted}
+ fontSize="8"
+ fontFamily="monospace"
+ >
+ {item.label}
+ </text>
+ ) : null
+ )}
+
+ {/* Legend */}
+ {sortedSeries.map((series, idx) => (
+ <g key={idx}>
+ <rect x={ml + idx * 120} y={5} width={10} height={10} fill={series.color} />
+ <text x={ml + idx * 120 + 15} y={13} fill={colors.text} fontSize="9" fontFamily="monospace">
+ {series.series_name.substring(0, 12)}
+ </text>
+ </g>
+ ))}
+ </svg>
+ );
+}
+
+export default memo(DBnomicsChart);
diff --git a/fincept-terminal-desktop/src/components/tabs/dbnomics/components/DataTable.tsx b/fincept-terminal-desktop/src/components/tabs/dbnomics/components/DataTable.tsx
new file mode 100644
index 000000000..52c9bbadb
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/dbnomics/components/DataTable.tsx
@@ -0,0 +1,111 @@
+import React, { memo, useMemo } from 'react';
+import type { DataPoint } from '../types';
+
+interface DataTableProps {
+ seriesArray: DataPoint[];
+ colors: any;
+}
+
+function DataTable({ seriesArray, colors }: DataTableProps) {
+ // Memoize unique periods across all series
+ const allPeriods = useMemo(() => {
+ return Array.from(
+ new Set(seriesArray.flatMap(s => s.observations.map(o => o.period)))
+ ).sort((a, b) => new Date(b).getTime() - new Date(a).getTime());
+ }, [seriesArray]);
+
+ // Memoize table rows (limited to 50)
+ const tableRows = useMemo(() => {
+ return allPeriods.slice(0, 50).map(period => {
+ const values = seriesArray.map(series => {
+ const obs = series.observations.find(o => o.period === period);
+ return obs ? (typeof obs.value === 'number' ? obs.value : Number(obs.value)) : null;
+ });
+ return { period, values };
+ });
+ }, [allPeriods, seriesArray]);
+
+ const containerStyle = useMemo(() => ({
+ overflowX: 'auto' as const,
+ overflowY: 'auto' as const,
+ maxHeight: '300px',
+ border: `1px solid ${colors.textMuted}`,
+ backgroundColor: colors.panel,
+ }), [colors.textMuted, colors.panel]);
+
+ return (
+ <div style={{ marginTop: '24px' }}>
+ <div style={{ color: colors.primary, fontSize: '11px', marginBottom: '8px' }}>DATA TABLE</div>
+ <div style={containerStyle}>
+ <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: '10px' }}>
+ <thead style={{ position: 'sticky', top: 0, backgroundColor: '#1a1a1a', zIndex: 1 }}>
+ <tr style={{ borderBottom: `2px solid ${colors.textMuted}` }}>
+ <th style={{
+ padding: '8px 12px',
+ textAlign: 'left',
+ color: colors.primary,
+ fontWeight: 'bold',
+ whiteSpace: 'nowrap',
+ }}>
+ Period
+ </th>
+ {seriesArray.map((series, idx) => (
+ <th
+ key={idx}
+ style={{
+ padding: '8px 12px',
+ textAlign: 'right',
+ fontWeight: 'bold',
+ whiteSpace: 'nowrap',
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: '6px' }}>
+ <div style={{
+ width: '8px',
+ height: '8px',
+ backgroundColor: series.color,
+ borderRadius: '50%',
+ }} />
+ <span style={{ color: series.color }}>{series.series_name.substring(0, 25)}</span>
+ </div>
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {tableRows.map((row, idx) => (
+ <tr key={idx} style={{ borderBottom: '1px solid #1a1a1a' }}>
+ <td style={{
+ padding: '6px 12px',
+ color: colors.text,
+ whiteSpace: 'nowrap',
+ fontWeight: 'bold',
+ }}>
+ {row.period}
+ </td>
+ {row.values.map((value, sIdx) => (
+ <td
+ key={sIdx}
+ style={{
+ padding: '6px 12px',
+ textAlign: 'right',
+ color: value !== null ? '#a3a3a3' : colors.textMuted,
+ whiteSpace: 'nowrap',
+ }}
+ >
+ {value !== null && !isNaN(value) ? value.toFixed(4) : '—'}
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ <div style={{ color: colors.textMuted, fontSize: '9px', marginTop: '6px', textAlign: 'right' }}>
+ Showing latest 50 periods
+ </div>
+ </div>
+ );
+}
+
+export default memo(DataTable);
diff --git a/fincept-terminal-desktop/src/components/tabs/dbnomics/components/SelectionPanel.tsx b/fincept-terminal-desktop/src/components/tabs/dbnomics/components/SelectionPanel.tsx
new file mode 100644
index 000000000..5d6219190
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/dbnomics/components/SelectionPanel.tsx
@@ -0,0 +1,355 @@
+import React, { memo, useCallback, useMemo } from 'react';
+import { Plus, Minus, Trash2 } from 'lucide-react';
+import type { Provider, Dataset, Series, DataPoint } from '../types';
+
+interface ListItemProps {
+ code: string;
+ name: string;
+ isSelected: boolean;
+ onClick: () => void;
+ colors: any;
+}
+
+const ListItem = memo(({ code, name, isSelected, onClick, colors }: ListItemProps) => {
+ const style = useMemo(() => ({
+ padding: '6px 8px',
+ fontSize: '10px',
+ color: isSelected ? '#fff' : colors.text,
+ backgroundColor: isSelected ? colors.primary : 'transparent',
+ cursor: 'pointer',
+ fontFamily: 'Consolas, monospace',
+ lineHeight: '1.4',
+ wordWrap: 'break-word' as const,
+ whiteSpace: 'normal' as const,
+ borderBottom: `1px solid ${colors.panel}`,
+ }), [isSelected, colors]);
+
+ return (
+ <div
+ onClick={onClick}
+ style={style}
+ onMouseEnter={(e) => {
+ if (!isSelected) e.currentTarget.style.backgroundColor = '#2a2a2a';
+ }}
+ onMouseLeave={(e) => {
+ if (!isSelected) e.currentTarget.style.backgroundColor = 'transparent';
+ }}
+ >
+ {code} - {name}
+ </div>
+ );
+});
+
+ListItem.displayName = 'ListItem';
+
+interface SelectionListProps {
+ title: string;
+ items: Array<{ code: string; name: string; full_id?: string }>;
+ selectedId: string | null;
+ onSelect: (item: any) => void;
+ idKey?: 'code' | 'full_id';
+ colors: any;
+}
+
+const SelectionList = memo(({ title, items, selectedId, onSelect, idKey = 'code', colors }: SelectionListProps) => {
+ const containerStyle = useMemo(() => ({
+ width: '100%',
+ height: '140px',
+ backgroundColor: '#1a1a1a',
+ border: `1px solid ${colors.textMuted}`,
+ marginBottom: '12px',
+ overflowY: 'auto' as const,
+ overflowX: 'hidden' as const,
+ }), [colors.textMuted]);
+
+ return (
+ <>
+ <div style={{ color: colors.primary, fontSize: '10px', marginBottom: '4px' }}>{title}</div>
+ <div style={containerStyle}>
+ {items.map((item) => {
+ const itemId = idKey === 'full_id' ? (item as Series).full_id : item.code;
+ return (
+ <ListItem
+ key={itemId}
+ code={item.code}
+ name={item.name}
+ isSelected={selectedId === itemId}
+ onClick={() => onSelect(item)}
+ colors={colors}
+ />
+ );
+ })}
+ </div>
+ </>
+ );
+});
+
+SelectionList.displayName = 'SelectionList';
+
+interface SlotItemProps {
+ slot: DataPoint[];
+ slotIndex: number;
+ currentData: DataPoint | null;
+ onAddToSlot: (index: number) => void;
+ onRemoveSlot: (index: number) => void;
+ onRemoveFromSlot: (slotIndex: number, seriesIndex: number) => void;
+ canRemove: boolean;
+ colors: any;
+}
+
+const SlotItem = memo(({
+ slot,
+ slotIndex,
+ currentData,
+ onAddToSlot,
+ onRemoveSlot,
+ onRemoveFromSlot,
+ canRemove,
+ colors,
+}: SlotItemProps) => (
+ <div style={{
+ marginBottom: '6px',
+ padding: '6px',
+ backgroundColor: '#1a1a1a',
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: '2px',
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
+ <span style={{ color: colors.warning, fontSize: '9px' }}>SLOT {slotIndex + 1} ({slot.length})</span>
+ <div style={{ display: 'flex', gap: '2px' }}>
+ <button
+ onClick={() => onAddToSlot(slotIndex)}
+ disabled={!currentData}
+ style={{
+ padding: '2px 4px',
+ backgroundColor: colors.panel,
+ color: colors.secondary,
+ border: `1px solid ${colors.textMuted}`,
+ cursor: !currentData ? 'not-allowed' : 'pointer',
+ fontSize: '8px',
+ }}
+ >
+ <Plus size={8} />
+ </button>
+ {canRemove && (
+ <button
+ onClick={() => onRemoveSlot(slotIndex)}
+ style={{
+ padding: '2px 4px',
+ backgroundColor: colors.panel,
+ color: colors.alert,
+ border: `1px solid ${colors.textMuted}`,
+ cursor: 'pointer',
+ fontSize: '8px',
+ }}
+ >
+ <Minus size={8} />
+ </button>
+ )}
+ </div>
+ </div>
+ {slot.map((s, sIdx) => (
+ <div
+ key={sIdx}
+ style={{
+ fontSize: '8px',
+ color: colors.textMuted,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '2px',
+ }}
+ >
+ <span
+ style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
+ title={s.series_name}
+ >
+ {s.series_name}
+ </span>
+ <button
+ onClick={() => onRemoveFromSlot(slotIndex, sIdx)}
+ style={{
+ padding: '1px 3px',
+ backgroundColor: 'transparent',
+ color: colors.alert,
+ border: 'none',
+ cursor: 'pointer',
+ fontSize: '8px',
+ }}
+ >
+ ×
+ </button>
+ </div>
+ ))}
+ {slot.length === 0 && (
+ <div style={{ fontSize: '8px', color: colors.textMuted, textAlign: 'center' }}>Empty</div>
+ )}
+ </div>
+));
+
+SlotItem.displayName = 'SlotItem';
+
+interface SelectionPanelProps {
+ providers: Provider[];
+ datasets: Dataset[];
+ seriesList: Series[];
+ selectedProvider: string | null;
+ selectedDataset: string | null;
+ selectedSeries: string | null;
+ currentData: DataPoint | null;
+ slots: DataPoint[][];
+ onSelectProvider: (code: string) => void;
+ onSelectDataset: (code: string) => void;
+ onSelectSeries: (series: Series) => void;
+ onAddToSingleView: () => void;
+ onClearAll: () => void;
+ onAddSlot: () => void;
+ onRemoveSlot: (index: number) => void;
+ onAddToSlot: (index: number) => void;
+ onRemoveFromSlot: (slotIndex: number, seriesIndex: number) => void;
+ colors: any;
+}
+
+function SelectionPanel({
+ providers,
+ datasets,
+ seriesList,
+ selectedProvider,
+ selectedDataset,
+ selectedSeries,
+ currentData,
+ slots,
+ onSelectProvider,
+ onSelectDataset,
+ onSelectSeries,
+ onAddToSingleView,
+ onClearAll,
+ onAddSlot,
+ onRemoveSlot,
+ onAddToSlot,
+ onRemoveFromSlot,
+ colors,
+}: SelectionPanelProps) {
+ const handleProviderSelect = useCallback((provider: Provider) => {
+ onSelectProvider(provider.code);
+ }, [onSelectProvider]);
+
+ const handleDatasetSelect = useCallback((dataset: Dataset) => {
+ onSelectDataset(dataset.code);
+ }, [onSelectDataset]);
+
+ const containerStyle = useMemo(() => ({
+ width: '320px',
+ borderRight: `1px solid ${colors.textMuted}`,
+ display: 'flex',
+ flexDirection: 'column' as const,
+ backgroundColor: colors.panel,
+ }), [colors.textMuted, colors.panel]);
+
+ return (
+ <div style={containerStyle}>
+ <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', padding: '8px' }}>
+ <SelectionList
+ title="1. PROVIDER"
+ items={providers}
+ selectedId={selectedProvider}
+ onSelect={handleProviderSelect}
+ colors={colors}
+ />
+
+ <SelectionList
+ title="2. DATASET"
+ items={datasets}
+ selectedId={selectedDataset}
+ onSelect={handleDatasetSelect}
+ colors={colors}
+ />
+
+ <SelectionList
+ title="3. SERIES"
+ items={seriesList}
+ selectedId={selectedSeries}
+ onSelect={onSelectSeries}
+ idKey="full_id"
+ colors={colors}
+ />
+
+ <div style={{ height: '1px', backgroundColor: colors.textMuted, margin: '8px 0' }} />
+
+ {/* Actions */}
+ <div style={{ display: 'flex', gap: '4px', marginBottom: '8px' }}>
+ <button
+ onClick={onAddToSingleView}
+ disabled={!currentData}
+ style={{
+ flex: 1,
+ padding: '4px',
+ backgroundColor: '#1a1a1a',
+ color: colors.text,
+ border: `1px solid ${colors.textMuted}`,
+ cursor: !currentData ? 'not-allowed' : 'pointer',
+ fontSize: '9px',
+ }}
+ >
+ ADD TO SINGLE
+ </button>
+ <button
+ onClick={onClearAll}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: '#1a1a1a',
+ color: colors.alert,
+ border: `1px solid ${colors.textMuted}`,
+ cursor: 'pointer',
+ fontSize: '9px',
+ }}
+ >
+ <Trash2 size={10} />
+ </button>
+ </div>
+
+ <div style={{
+ color: colors.primary,
+ fontSize: '10px',
+ marginBottom: '6px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ }}>
+ <span>COMPARISON SLOTS</span>
+ <button
+ onClick={onAddSlot}
+ style={{
+ padding: '2px 6px',
+ backgroundColor: '#1a1a1a',
+ color: colors.secondary,
+ border: `1px solid ${colors.textMuted}`,
+ cursor: 'pointer',
+ fontSize: '9px',
+ }}
+ >
+ <Plus size={10} />
+ </button>
+ </div>
+
+ <div style={{ maxHeight: '300px', overflowY: 'auto' }}>
+ {slots.map((slot, idx) => (
+ <SlotItem
+ key={idx}
+ slot={slot}
+ slotIndex={idx}
+ currentData={currentData}
+ onAddToSlot={onAddToSlot}
+ onRemoveSlot={onRemoveSlot}
+ onRemoveFromSlot={onRemoveFromSlot}
+ canRemove={slots.length > 1}
+ colors={colors}
+ />
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default memo(SelectionPanel);
diff --git a/fincept-terminal-desktop/src/components/tabs/dbnomics/components/index.ts b/fincept-terminal-desktop/src/components/tabs/dbnomics/components/index.ts
new file mode 100644
index 000000000..a7e3b8651
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/dbnomics/components/index.ts
@@ -0,0 +1,3 @@
+export { default as SelectionPanel } from './SelectionPanel';
+export { default as DBnomicsChart } from './DBnomicsChart';
+export { default as DataTable } from './DataTable';
diff --git a/fincept-terminal-desktop/src/components/tabs/dbnomics/constants.ts b/fincept-terminal-desktop/src/components/tabs/dbnomics/constants.ts
new file mode 100644
index 000000000..a583dbf82
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/dbnomics/constants.ts
@@ -0,0 +1,29 @@
+import type { ChartType } from './types';
+
+export const DBNOMICS_API_BASE = 'https://api.db.nomics.world/v22';
+
+// Cache duration in milliseconds (10 minutes for providers, 5 minutes for datasets/series)
+export const PROVIDERS_CACHE_DURATION = 10 * 60 * 1000;
+export const DATASETS_CACHE_DURATION = 5 * 60 * 1000;
+export const SERIES_CACHE_DURATION = 5 * 60 * 1000;
+
+// State persistence duration (24 hours)
+export const STATE_CACHE_DURATION = 24 * 60 * 60 * 1000;
+
+// Debounce delay for state saving
+export const STATE_SAVE_DEBOUNCE_MS = 1000;
+
+// Chart types
+export const CHART_TYPES: ChartType[] = ['line', 'bar', 'area', 'scatter', 'candlestick'];
+
+// Default chart colors (will be overridden by theme)
+export const DEFAULT_CHART_COLORS = [
+ '#ea580c', // primary/orange
+ '#3b82f6', // info/blue
+ '#22c55e', // secondary/green
+ '#eab308', // warning/yellow
+ '#a855f7', // purple
+ '#ec4899', // pink
+ '#06b6d4', // cyan
+ '#f97316', // orange variant
+];
diff --git a/fincept-terminal-desktop/src/components/tabs/dbnomics/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/dbnomics/hooks/index.ts
new file mode 100644
index 000000000..5a191623d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/dbnomics/hooks/index.ts
@@ -0,0 +1 @@
+export { useDBnomicsData } from './useDBnomicsData';
diff --git a/fincept-terminal-desktop/src/components/tabs/dbnomics/hooks/useDBnomicsData.ts b/fincept-terminal-desktop/src/components/tabs/dbnomics/hooks/useDBnomicsData.ts
new file mode 100644
index 000000000..949aec857
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/dbnomics/hooks/useDBnomicsData.ts
@@ -0,0 +1,478 @@
+import { useState, useCallback, useRef, useEffect } from 'react';
+import { getSetting, saveSetting } from '@/services/core/sqliteService';
+import type {
+ Provider,
+ Dataset,
+ Series,
+ DataPoint,
+ Observation,
+ ChartType,
+ DBnomicsState,
+ ProvidersCache,
+ DatasetsCache,
+ SeriesCache,
+} from '../types';
+import {
+ DBNOMICS_API_BASE,
+ PROVIDERS_CACHE_DURATION,
+ DATASETS_CACHE_DURATION,
+ SERIES_CACHE_DURATION,
+ STATE_CACHE_DURATION,
+ STATE_SAVE_DEBOUNCE_MS,
+ DEFAULT_CHART_COLORS,
+} from '../constants';
+
+interface UseDBnomicsDataReturn {
+ // Data
+ providers: Provider[];
+ datasets: Dataset[];
+ seriesList: Series[];
+ currentData: DataPoint | null;
+
+ // Selection state
+ selectedProvider: string | null;
+ selectedDataset: string | null;
+ selectedSeries: string | null;
+
+ // View state
+ slots: DataPoint[][];
+ slotChartTypes: ChartType[];
+ singleViewSeries: DataPoint[];
+ singleChartType: ChartType;
+ activeView: 'single' | 'comparison';
+
+ // Loading states
+ loading: boolean;
+ status: string;
+
+ // Colors for charts
+ chartColors: string[];
+
+ // Actions
+ loadProviders: () => Promise<void>;
+ selectProvider: (providerCode: string) => void;
+ selectDataset: (datasetCode: string) => void;
+ selectSeries: (series: Series) => void;
+ refreshCurrentSeries: () => void;
+
+ // Slot management
+ addSlot: () => void;
+ removeSlot: (index: number) => void;
+ addToSlot: (slotIndex: number) => void;
+ removeFromSlot: (slotIndex: number, seriesIndex: number) => void;
+ setSlotChartType: (slotIndex: number, chartType: ChartType) => void;
+
+ // Single view management
+ addToSingleView: () => void;
+ removeFromSingleView: (index: number) => void;
+ setSingleChartType: (chartType: ChartType) => void;
+ setActiveView: (view: 'single' | 'comparison') => void;
+
+ // Actions
+ clearAll: () => Promise<void>;
+ exportData: () => void;
+}
+
+export function useDBnomicsData(themeColors?: string[]): UseDBnomicsDataReturn {
+ // Chart colors from theme or defaults
+ const chartColors = themeColors || DEFAULT_CHART_COLORS;
+
+ // Data state
+ const [providers, setProviders] = useState<Provider[]>([]);
+ const [datasets, setDatasets] = useState<Dataset[]>([]);
+ const [seriesList, setSeriesList] = useState<Series[]>([]);
+ const [currentData, setCurrentData] = useState<DataPoint | null>(null);
+
+ // Selection state
+ const [selectedProvider, setSelectedProvider] = useState<string | null>(null);
+ const [selectedDataset, setSelectedDataset] = useState<string | null>(null);
+ const [selectedSeries, setSelectedSeries] = useState<string | null>(null);
+
+ // View state
+ const [slots, setSlots] = useState<DataPoint[][]>([[]]);
+ const [slotChartTypes, setSlotChartTypes] = useState<ChartType[]>(['line']);
+ const [singleViewSeries, setSingleViewSeries] = useState<DataPoint[]>([]);
+ const [singleChartType, setSingleChartTypeState] = useState<ChartType>('line');
+ const [activeView, setActiveViewState] = useState<'single' | 'comparison'>('single');
+
+ // Loading state
+ const [loading, setLoading] = useState(false);
+ const [status, setStatus] = useState('Loading providers...');
+
+ // Caches
+ const providersCache = useRef<ProvidersCache | null>(null);
+ const datasetsCache = useRef<DatasetsCache>(new Map());
+ const seriesCache = useRef<SeriesCache>(new Map());
+
+ // Debounced state saving
+ const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
+
+ const isCacheValid = useCallback((timestamp: number, duration: number): boolean => {
+ return Date.now() - timestamp < duration;
+ }, []);
+
+ // Save state with debouncing
+ const saveState = useCallback(async () => {
+ if (saveTimeoutRef.current) {
+ clearTimeout(saveTimeoutRef.current);
+ }
+
+ saveTimeoutRef.current = setTimeout(async () => {
+ try {
+ const state: DBnomicsState = {
+ singleViewSeries,
+ slots,
+ slotChartTypes,
+ singleChartType,
+ activeView,
+ timestamp: Date.now(),
+ };
+ await saveSetting('dbnomics_state', JSON.stringify(state), 'dbnomics_tab');
+ } catch (error) {
+ console.error('[DBnomics] Failed to save state:', error);
+ }
+ }, STATE_SAVE_DEBOUNCE_MS);
+ }, [singleViewSeries, slots, slotChartTypes, singleChartType, activeView]);
+
+ // Auto-save state when it changes
+ useEffect(() => {
+ if (singleViewSeries.length > 0 || slots.some(s => s.length > 0)) {
+ saveState();
+ }
+ }, [singleViewSeries, slots, slotChartTypes, singleChartType, activeView, saveState]);
+
+ // Restore state on mount
+ const restoreState = useCallback(async () => {
+ try {
+ const saved = await getSetting('dbnomics_state');
+ if (saved) {
+ const state: DBnomicsState = JSON.parse(saved);
+ if (state.timestamp && isCacheValid(state.timestamp, STATE_CACHE_DURATION)) {
+ if (state.singleViewSeries) setSingleViewSeries(state.singleViewSeries);
+ if (state.slots) setSlots(state.slots);
+ if (state.slotChartTypes) setSlotChartTypes(state.slotChartTypes);
+ if (state.singleChartType) setSingleChartTypeState(state.singleChartType);
+ if (state.activeView) setActiveViewState(state.activeView);
+ setStatus('Restored from cache');
+ }
+ }
+ } catch (error) {
+ console.error('[DBnomics] Failed to restore state:', error);
+ }
+ }, [isCacheValid]);
+
+ // Load providers
+ const loadProviders = useCallback(async () => {
+ // Check cache first
+ if (providersCache.current && isCacheValid(providersCache.current.timestamp, PROVIDERS_CACHE_DURATION)) {
+ setProviders(providersCache.current.data);
+ setStatus(`Loaded ${providersCache.current.data.length} providers (cached)`);
+ return;
+ }
+
+ try {
+ setLoading(true);
+ setStatus('Loading providers...');
+ const response = await fetch(`${DBNOMICS_API_BASE}/providers`);
+ if (response.ok) {
+ const data = await response.json();
+ const providerList: Provider[] = (data?.providers?.docs || []).map((p: any) => ({
+ code: p.code || '',
+ name: p.name || p.code || '',
+ }));
+
+ // Cache the results
+ providersCache.current = { data: providerList, timestamp: Date.now() };
+ setProviders(providerList);
+ setStatus(`Loaded ${providerList.length} providers`);
+ } else {
+ setStatus(`Error: ${response.status}`);
+ }
+ } catch (error) {
+ setStatus(`Error: ${error}`);
+ } finally {
+ setLoading(false);
+ }
+ }, [isCacheValid]);
+
+ // Load datasets for a provider
+ const loadDatasets = useCallback(async (providerCode: string) => {
+ // Check cache
+ const cached = datasetsCache.current.get(providerCode);
+ if (cached && isCacheValid(cached.timestamp, DATASETS_CACHE_DURATION)) {
+ setDatasets(cached.data);
+ setSeriesList([]);
+ setStatus(`Loaded ${cached.data.length} datasets (cached)`);
+ return;
+ }
+
+ try {
+ setLoading(true);
+ setStatus('Loading datasets...');
+ const response = await fetch(`${DBNOMICS_API_BASE}/datasets/${providerCode}`);
+ if (response.ok) {
+ const data = await response.json();
+ const datasetList: Dataset[] = (data?.datasets?.docs || []).map((d: any) => ({
+ code: d.code || '',
+ name: d.name || d.code || '',
+ }));
+
+ // Cache the results
+ datasetsCache.current.set(providerCode, { data: datasetList, timestamp: Date.now() });
+ setDatasets(datasetList);
+ setSeriesList([]);
+ setStatus(`Loaded ${datasetList.length} datasets`);
+ } else {
+ setStatus(`Error: ${response.status}`);
+ }
+ } catch (error) {
+ setStatus(`Error: ${error}`);
+ } finally {
+ setLoading(false);
+ }
+ }, [isCacheValid]);
+
+ // Load series for a dataset
+ const loadSeries = useCallback(async (providerCode: string, datasetCode: string) => {
+ const cacheKey = `${providerCode}/${datasetCode}`;
+
+ // Check cache
+ const cached = seriesCache.current.get(cacheKey);
+ if (cached && isCacheValid(cached.timestamp, SERIES_CACHE_DURATION)) {
+ setSeriesList(cached.data);
+ setStatus(`Loaded ${cached.data.length} series (cached)`);
+ return;
+ }
+
+ try {
+ setLoading(true);
+ setStatus('Loading series...');
+ const response = await fetch(
+ `${DBNOMICS_API_BASE}/series/${providerCode}/${datasetCode}?limit=50&observations=false`
+ );
+ if (response.ok) {
+ const data = await response.json();
+ const seriesArray: Series[] = (data?.series?.docs || []).map((s: any) => ({
+ code: s.series_code || '',
+ name: s.series_name || s.series_code || '',
+ full_id: `${providerCode}/${datasetCode}/${s.series_code}`,
+ }));
+
+ // Cache the results
+ seriesCache.current.set(cacheKey, { data: seriesArray, timestamp: Date.now() });
+ setSeriesList(seriesArray);
+ setStatus(`Loaded ${seriesArray.length} series`);
+ } else {
+ setStatus(`Error: ${response.status}`);
+ }
+ } catch (error) {
+ setStatus(`Error: ${error}`);
+ } finally {
+ setLoading(false);
+ }
+ }, [isCacheValid]);
+
+ // Load series data
+ const loadSeriesData = useCallback(async (fullSeriesId: string, seriesName: string) => {
+ try {
+ setLoading(true);
+ setStatus('Loading data...');
+ const [providerCode, datasetCode, seriesCode] = fullSeriesId.split('/');
+ const response = await fetch(
+ `${DBNOMICS_API_BASE}/series/${providerCode}/${datasetCode}/${seriesCode}?observations=1&format=json`
+ );
+ if (response.ok) {
+ const data = await response.json();
+ const seriesDocs = data?.series?.docs || [];
+ if (seriesDocs.length > 0) {
+ const firstSeries = seriesDocs[0];
+ const observations: Observation[] = [];
+ if (firstSeries.period && firstSeries.value) {
+ for (let i = 0; i < Math.min(firstSeries.period.length, firstSeries.value.length); i++) {
+ if (firstSeries.value[i] !== null) {
+ observations.push({ period: firstSeries.period[i], value: firstSeries.value[i] });
+ }
+ }
+ }
+ if (observations.length > 0) {
+ const colorIndex = (singleViewSeries.length + slots.flat().length) % chartColors.length;
+ setCurrentData({
+ series_id: fullSeriesId,
+ series_name: seriesName,
+ observations,
+ color: chartColors[colorIndex],
+ });
+ setStatus(`Loaded ${observations.length} points`);
+ } else {
+ setStatus('No data found');
+ }
+ } else {
+ setStatus('No data found');
+ }
+ } else {
+ setStatus(`Error: ${response.status}`);
+ }
+ } catch (error) {
+ setStatus(`Error: ${error}`);
+ } finally {
+ setLoading(false);
+ }
+ }, [singleViewSeries.length, slots, chartColors]);
+
+ // Selection handlers
+ const selectProvider = useCallback((providerCode: string) => {
+ setSelectedProvider(providerCode);
+ setSelectedDataset(null);
+ setSelectedSeries(null);
+ setDatasets([]);
+ setSeriesList([]);
+ loadDatasets(providerCode);
+ }, [loadDatasets]);
+
+ const selectDataset = useCallback((datasetCode: string) => {
+ setSelectedDataset(datasetCode);
+ setSelectedSeries(null);
+ setSeriesList([]);
+ if (selectedProvider) {
+ loadSeries(selectedProvider, datasetCode);
+ }
+ }, [selectedProvider, loadSeries]);
+
+ const selectSeries = useCallback((series: Series) => {
+ setSelectedSeries(series.full_id);
+ loadSeriesData(series.full_id, series.name);
+ }, [loadSeriesData]);
+
+ const refreshCurrentSeries = useCallback(() => {
+ if (currentData) {
+ loadSeriesData(currentData.series_id, currentData.series_name);
+ }
+ }, [currentData, loadSeriesData]);
+
+ // Slot management
+ const addSlot = useCallback(() => {
+ setSlots(prev => [...prev, []]);
+ setSlotChartTypes(prev => [...prev, 'line']);
+ setStatus(`Added slot ${slots.length + 1}`);
+ }, [slots.length]);
+
+ const removeSlot = useCallback((index: number) => {
+ if (slots.length > 1) {
+ setSlots(prev => prev.filter((_, i) => i !== index));
+ setSlotChartTypes(prev => prev.filter((_, i) => i !== index));
+ setStatus(`Removed slot ${index + 1}`);
+ }
+ }, [slots.length]);
+
+ const addToSlot = useCallback((slotIndex: number) => {
+ if (currentData && slotIndex >= 0 && slotIndex < slots.length) {
+ setSlots(prev => {
+ const newSlots = [...prev];
+ newSlots[slotIndex] = [...newSlots[slotIndex], currentData];
+ return newSlots;
+ });
+ setStatus(`Added to slot ${slotIndex + 1}`);
+ }
+ }, [currentData, slots.length]);
+
+ const removeFromSlot = useCallback((slotIndex: number, seriesIndex: number) => {
+ setSlots(prev => {
+ const newSlots = [...prev];
+ newSlots[slotIndex] = newSlots[slotIndex].filter((_, i) => i !== seriesIndex);
+ return newSlots;
+ });
+ setStatus(`Removed from slot ${slotIndex + 1}`);
+ }, []);
+
+ const setSlotChartType = useCallback((slotIndex: number, chartType: ChartType) => {
+ setSlotChartTypes(prev => {
+ const newTypes = [...prev];
+ newTypes[slotIndex] = chartType;
+ return newTypes;
+ });
+ }, []);
+
+ // Single view management
+ const addToSingleView = useCallback(() => {
+ if (currentData) {
+ setSingleViewSeries(prev => [...prev, currentData]);
+ setActiveViewState('single');
+ setStatus('Added to single view');
+ }
+ }, [currentData]);
+
+ const removeFromSingleView = useCallback((index: number) => {
+ setSingleViewSeries(prev => prev.filter((_, i) => i !== index));
+ }, []);
+
+ const setSingleChartType = useCallback((chartType: ChartType) => {
+ setSingleChartTypeState(chartType);
+ }, []);
+
+ const setActiveView = useCallback((view: 'single' | 'comparison') => {
+ setActiveViewState(view);
+ }, []);
+
+ // Clear all
+ const clearAll = useCallback(async () => {
+ setSlots([[]]);
+ setSlotChartTypes(['line']);
+ setSingleViewSeries([]);
+ await saveSetting('dbnomics_state', '', 'dbnomics_tab');
+ setStatus('Cleared all');
+ }, []);
+
+ // Export data
+ const exportData = useCallback(() => {
+ if (!currentData) return;
+ const csv = ['Period,Value', ...currentData.observations.map(obs => `${obs.period},${obs.value}`)].join('\n');
+ const blob = new Blob([csv], { type: 'text/csv' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `dbnomics_${Date.now()}.csv`;
+ a.click();
+ URL.revokeObjectURL(url);
+ setStatus('Exported');
+ }, [currentData]);
+
+ // Initialize on mount
+ useEffect(() => {
+ loadProviders();
+ restoreState();
+ }, []);
+
+ return {
+ providers,
+ datasets,
+ seriesList,
+ currentData,
+ selectedProvider,
+ selectedDataset,
+ selectedSeries,
+ slots,
+ slotChartTypes,
+ singleViewSeries,
+ singleChartType,
+ activeView,
+ loading,
+ status,
+ chartColors,
+ loadProviders,
+ selectProvider,
+ selectDataset,
+ selectSeries,
+ refreshCurrentSeries,
+ addSlot,
+ removeSlot,
+ addToSlot,
+ removeFromSlot,
+ setSlotChartType,
+ addToSingleView,
+ removeFromSingleView,
+ setSingleChartType,
+ setActiveView,
+ clearAll,
+ exportData,
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/dbnomics/index.ts b/fincept-terminal-desktop/src/components/tabs/dbnomics/index.ts
new file mode 100644
index 000000000..e41479bf3
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/dbnomics/index.ts
@@ -0,0 +1,4 @@
+export { default } from './DBnomicsTab';
+export { default as DBnomicsTab } from './DBnomicsTab';
+export * from './types';
+export * from './constants';
diff --git a/fincept-terminal-desktop/src/components/tabs/dbnomics/types.ts b/fincept-terminal-desktop/src/components/tabs/dbnomics/types.ts
new file mode 100644
index 000000000..e5fc73beb
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/dbnomics/types.ts
@@ -0,0 +1,50 @@
+// Types for DBnomics Tab
+
+export interface Provider {
+ code: string;
+ name: string;
+}
+
+export interface Dataset {
+ code: string;
+ name: string;
+}
+
+export interface Series {
+ code: string;
+ name: string;
+ full_id: string;
+}
+
+export interface Observation {
+ period: string;
+ value: number;
+}
+
+export interface DataPoint {
+ series_id: string;
+ series_name: string;
+ observations: Observation[];
+ color: string;
+}
+
+export type ChartType = 'line' | 'bar' | 'area' | 'scatter' | 'candlestick';
+
+export interface DBnomicsState {
+ singleViewSeries: DataPoint[];
+ slots: DataPoint[][];
+ slotChartTypes: ChartType[];
+ singleChartType: ChartType;
+ activeView: 'single' | 'comparison';
+ timestamp: number;
+}
+
+// Cache types
+export interface CachedData<T> {
+ data: T;
+ timestamp: number;
+}
+
+export type ProvidersCache = CachedData<Provider[]>;
+export type DatasetsCache = Map<string, CachedData<Dataset[]>>;
+export type SeriesCache = Map<string, CachedData<Series[]>>;
diff --git a/fincept-terminal-desktop/src/components/tabs/DerivativesTab.tsx b/fincept-terminal-desktop/src/components/tabs/derivatives/DerivativesTab.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/DerivativesTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/derivatives/DerivativesTab.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/derivatives/index.ts b/fincept-terminal-desktop/src/components/tabs/derivatives/index.ts
new file mode 100644
index 000000000..aea0359eb
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/derivatives/index.ts
@@ -0,0 +1,2 @@
+export { DerivativesTab } from './DerivativesTab';
+export { DerivativesTab as default } from './DerivativesTab';
diff --git a/fincept-terminal-desktop/src/components/tabs/docs/index.ts b/fincept-terminal-desktop/src/components/tabs/docs/index.ts
new file mode 100644
index 000000000..dd8a7129e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/docs/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./DocsTab";
+export { default as DocsTab } from "./DocsTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/EconomicsTab.tsx b/fincept-terminal-desktop/src/components/tabs/economics/EconomicsTab.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/EconomicsTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/economics/EconomicsTab.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/economics/index.ts b/fincept-terminal-desktop/src/components/tabs/economics/index.ts
new file mode 100644
index 000000000..4c452dbb7
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/economics/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./EconomicsTab";
+export { default as EconomicsTab } from "./EconomicsTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/equity-research/index.ts b/fincept-terminal-desktop/src/components/tabs/equity-research/index.ts
index 770ebfa6a..658a6bf54 100644
--- a/fincept-terminal-desktop/src/components/tabs/equity-research/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/equity-research/index.ts
@@ -1,5 +1,9 @@
// Main exports for Equity Research module
+// Default export
+export { default } from './EquityResearchTab';
+export { default as EquityResearchTab } from './EquityResearchTab';
+
// Types
export * from './types';
diff --git a/fincept-terminal-desktop/src/components/tabs/ExcelTab.tsx b/fincept-terminal-desktop/src/components/tabs/excel/ExcelTab.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/ExcelTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/excel/ExcelTab.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/excel/index.ts b/fincept-terminal-desktop/src/components/tabs/excel/index.ts
new file mode 100644
index 000000000..e6e39e791
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/excel/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./ExcelTab";
+export { default as ExcelTab } from "./ExcelTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/ForumTab.tsx b/fincept-terminal-desktop/src/components/tabs/forum/ForumTab.tsx
new file mode 100644
index 000000000..260efd9ae
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/ForumTab.tsx
@@ -0,0 +1,266 @@
+// Forum Tab - Main Component
+// Refactored from 1764-line monolith into modular components
+
+import React, { useState, useEffect, useMemo } from 'react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
+import { TabFooter } from '@/components/common/TabFooter';
+
+// Local imports
+import { getForumColors } from './constants';
+import { useForum } from './hooks/useForum';
+import { useForumModals } from './hooks/useForumModals';
+import {
+ Header,
+ FunctionBar,
+ LeftPanel,
+ CenterPanel,
+ RightPanel,
+ CreatePostModal,
+ PostDetailModal,
+ SearchModal,
+ ProfileModal
+} from './components';
+
+const ForumTab: React.FC = () => {
+ const { colors } = useTerminalTheme();
+ const [currentTime, setCurrentTime] = useState(new Date());
+
+ // Get forum-specific colors
+ const forumColors = useMemo(() => getForumColors(colors), [colors]);
+
+ // Forum data and actions
+ const forum = useForum({ colors: forumColors });
+
+ // Modal states
+ const modals = useForumModals({ colors: forumColors });
+
+ // Update time every second
+ useEffect(() => {
+ const interval = setInterval(() => setCurrentTime(new Date()), 1000);
+ return () => clearInterval(interval);
+ }, []);
+
+ // Handlers that bridge modals and forum actions
+ const handleCreatePost = async () => {
+ if (!modals.newPostTitle.trim() || !modals.newPostContent.trim()) return;
+ const success = await forum.handleCreatePost(modals.newPostTitle, modals.newPostContent);
+ if (success) {
+ modals.resetCreatePostForm();
+ modals.setShowCreatePost(false);
+ }
+ };
+
+ const handleViewPost = async (post: typeof forum.selectedPost) => {
+ if (post) {
+ await forum.handleViewPost(post);
+ modals.setShowPostDetail(true);
+ }
+ };
+
+ const handleAddComment = async () => {
+ if (!modals.newComment.trim()) return;
+ const success = await forum.handleAddComment(modals.newComment);
+ if (success) {
+ modals.setNewComment('');
+ }
+ };
+
+ const handleSearch = async () => {
+ if (!modals.searchQuery.trim()) return;
+ await forum.handleSearch(modals.searchQuery);
+ // Search results are stored in forum.searchResults
+ };
+
+ const handleViewProfile = async () => {
+ await forum.handleViewMyProfile();
+ if (forum.userProfile) {
+ modals.initProfileEdit(forum.userProfile);
+ }
+ modals.setShowProfile(true);
+ };
+
+ const handleViewUserProfile = async (username: string) => {
+ await forum.handleViewUserProfile(username);
+ modals.setShowProfile(true);
+ };
+
+ const handleOpenEditProfile = () => {
+ modals.setShowProfile(false);
+ modals.setShowEditProfile(true);
+ };
+
+ const handleSaveProfile = async () => {
+ const success = await forum.handleUpdateProfile(modals.profileEdit);
+ if (success) {
+ modals.setShowEditProfile(false);
+ modals.setShowProfile(true);
+ }
+ };
+
+ const handleCloseSearch = () => {
+ modals.setShowSearch(false);
+ modals.resetSearchForm();
+ };
+
+ const handleCloseProfile = () => {
+ modals.setShowProfile(false);
+ forum.setSelectedUsername('');
+ };
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: forumColors.DARK_BG,
+ color: forumColors.WHITE,
+ fontFamily: 'Consolas, monospace',
+ overflow: 'hidden',
+ display: 'flex',
+ flexDirection: 'column',
+ fontSize: '12px'
+ }}>
+ {/* Header */}
+ <Header
+ colors={forumColors}
+ currentTime={currentTime}
+ onlineUsers={forum.onlineUsers}
+ postsToday={forum.postsToday}
+ trendingTopics={forum.trendingTopics}
+ isRefreshing={forum.isRefreshing}
+ lastRefreshTime={forum.lastRefreshTime}
+ onRefresh={forum.handleRefresh}
+ />
+
+ {/* Function Bar */}
+ <FunctionBar
+ colors={forumColors}
+ activeCategory={forum.activeCategory}
+ categories={forum.categories}
+ onCategoryChange={forum.setActiveCategory}
+ onCreatePost={() => modals.setShowCreatePost(true)}
+ onSearch={() => modals.setShowSearch(true)}
+ onViewProfile={handleViewProfile}
+ onEditProfile={() => modals.setShowEditProfile(true)}
+ />
+
+ {/* Main Content Area */}
+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden', padding: '4px', gap: '4px' }}>
+ {/* Left Panel - Categories & Stats */}
+ <LeftPanel
+ colors={forumColors}
+ categories={forum.categories}
+ activeCategory={forum.activeCategory}
+ onCategoryChange={forum.setActiveCategory}
+ onViewUserProfile={handleViewUserProfile}
+ forumStats={forum.forumStats}
+ totalPosts={forum.totalPosts}
+ postsToday={forum.postsToday}
+ onlineUsers={forum.onlineUsers}
+ />
+
+ {/* Center Panel - Posts List */}
+ <CenterPanel
+ colors={forumColors}
+ activeCategory={forum.activeCategory}
+ sortBy={forum.sortBy}
+ onSortChange={forum.setSortBy}
+ filteredPosts={forum.filteredPosts}
+ isLoading={forum.isLoading}
+ onViewPost={handleViewPost}
+ />
+
+ {/* Right Panel - Trending & Activity */}
+ <RightPanel
+ colors={forumColors}
+ trendingTopics={forum.trendingTopics}
+ recentActivity={forum.recentActivity}
+ />
+ </div>
+
+ {/* Status Bar */}
+ <div style={{
+ borderTop: `1px solid ${forumColors.GRAY}`,
+ backgroundColor: forumColors.PANEL_BG,
+ padding: '2px 8px',
+ fontSize: '10px',
+ color: forumColors.GRAY,
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div style={{ display: 'flex', gap: '16px' }}>
+ <span>Fincept Global Forum v2.4.1 | Professional trading community</span>
+ <span>Posts: {forum.totalPosts.toLocaleString()} | Users: {(forum.forumStats?.total_comments || 47832).toLocaleString()} | Active: {forum.onlineUsers}</span>
+ </div>
+ <div style={{ display: 'flex', gap: '16px' }}>
+ <span>Category: {forum.activeCategory}</span>
+ <span>Sort: {forum.sortBy}</span>
+ <span style={{ color: forumColors.GREEN }}>STATUS: LIVE</span>
+ </div>
+ </div>
+ </div>
+
+ {/* Modals */}
+ <CreatePostModal
+ colors={forumColors}
+ show={modals.showCreatePost}
+ newPostTitle={modals.newPostTitle}
+ newPostContent={modals.newPostContent}
+ onTitleChange={modals.setNewPostTitle}
+ onContentChange={modals.setNewPostContent}
+ onClose={() => modals.setShowCreatePost(false)}
+ onSubmit={handleCreatePost}
+ />
+
+ <PostDetailModal
+ colors={forumColors}
+ show={modals.showPostDetail}
+ selectedPost={forum.selectedPost}
+ postComments={forum.postComments}
+ newComment={modals.newComment}
+ onCommentChange={modals.setNewComment}
+ onClose={() => modals.setShowPostDetail(false)}
+ onAddComment={handleAddComment}
+ onVotePost={(postId, voteType) => forum.handleVotePost(postId, voteType)}
+ onVoteComment={(commentId, voteType) => forum.handleVoteComment(commentId, voteType)}
+ />
+
+ <SearchModal
+ colors={forumColors}
+ show={modals.showSearch}
+ searchQuery={modals.searchQuery}
+ searchResults={forum.searchResults}
+ isLoading={forum.isLoading}
+ onQueryChange={modals.setSearchQuery}
+ onSearch={handleSearch}
+ onClose={handleCloseSearch}
+ onViewPost={handleViewPost}
+ />
+
+ <ProfileModal
+ colors={forumColors}
+ showProfile={modals.showProfile}
+ showEditProfile={modals.showEditProfile}
+ userProfile={forum.userProfile}
+ profileEdit={modals.profileEdit}
+ isOwnProfile={!forum.selectedUsername}
+ onProfileEditChange={modals.setProfileEdit}
+ onCloseProfile={handleCloseProfile}
+ onCloseEditProfile={() => modals.setShowEditProfile(false)}
+ onOpenEditProfile={handleOpenEditProfile}
+ onSaveProfile={handleSaveProfile}
+ />
+
+ <TabFooter
+ tabName="COMMUNITY FORUM"
+ leftInfo={[
+ { label: `Category: ${forum.activeCategory || 'All'}`, color: colors.textMuted },
+ { label: `Posts: ${forum.forumStats?.total_posts || 0}`, color: colors.textMuted },
+ ]}
+ statusInfo={`Users: ${forum.forumStats?.total_users || 0} | ${forum.isLoading ? 'Loading...' : 'Ready'}`}
+ backgroundColor={colors.panel}
+ borderColor={colors.textMuted}
+ />
+ </div>
+ );
+};
+
+export default ForumTab;
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/components/CenterPanel.tsx b/fincept-terminal-desktop/src/components/tabs/forum/components/CenterPanel.tsx
new file mode 100644
index 000000000..efaca327d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/components/CenterPanel.tsx
@@ -0,0 +1,143 @@
+// Forum Tab Center Panel Component (Posts List)
+
+import React from 'react';
+import type { ForumColors, ForumPost } from '../types';
+import { getPriorityColor, getSentimentColor } from '../constants';
+
+interface CenterPanelProps {
+ colors: ForumColors;
+ activeCategory: string;
+ sortBy: string;
+ onSortChange: (sort: string) => void;
+ filteredPosts: ForumPost[];
+ isLoading: boolean;
+ onViewPost: (post: ForumPost) => void;
+}
+
+export const CenterPanel: React.FC<CenterPanelProps> = ({
+ colors,
+ activeCategory,
+ sortBy,
+ onSortChange,
+ filteredPosts,
+ isLoading,
+ onViewPost
+}) => {
+ return (
+ <div style={{
+ flex: 1,
+ backgroundColor: colors.PANEL_BG,
+ border: `1px solid ${colors.GRAY}`,
+ padding: '4px',
+ overflow: 'auto'
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
+ <div style={{ color: colors.ORANGE, fontSize: '11px', fontWeight: 'bold' }}>
+ FORUM POSTS [{activeCategory}]
+ {isLoading && <span style={{ color: colors.YELLOW, marginLeft: '8px' }}>LOADING...</span>}
+ </div>
+ <div style={{ display: 'flex', gap: '4px', fontSize: '9px' }}>
+ <button
+ onClick={() => onSortChange('latest')}
+ style={{
+ padding: '2px 6px',
+ backgroundColor: sortBy === 'latest' ? colors.ORANGE : colors.DARK_BG,
+ color: sortBy === 'latest' ? colors.DARK_BG : colors.WHITE,
+ border: `1px solid ${colors.GRAY}`,
+ cursor: 'pointer'
+ }}
+ >
+ LATEST
+ </button>
+ <button
+ onClick={() => onSortChange('popular')}
+ style={{
+ padding: '2px 6px',
+ backgroundColor: sortBy === 'popular' ? colors.ORANGE : colors.DARK_BG,
+ color: sortBy === 'popular' ? colors.DARK_BG : colors.WHITE,
+ border: `1px solid ${colors.GRAY}`,
+ cursor: 'pointer'
+ }}
+ >
+ HOT
+ </button>
+ <button
+ onClick={() => onSortChange('views')}
+ style={{
+ padding: '2px 6px',
+ backgroundColor: sortBy === 'views' ? colors.ORANGE : colors.DARK_BG,
+ color: sortBy === 'views' ? colors.DARK_BG : colors.WHITE,
+ border: `1px solid ${colors.GRAY}`,
+ cursor: 'pointer'
+ }}
+ >
+ TOP
+ </button>
+ </div>
+ </div>
+ <div style={{ borderBottom: `1px solid ${colors.GRAY}`, marginBottom: '8px' }}></div>
+
+ {filteredPosts.length === 0 && !isLoading && (
+ <div style={{ color: colors.GRAY, textAlign: 'center', padding: '20px' }}>
+ No posts available. Be the first to post!
+ </div>
+ )}
+
+ {filteredPosts.map((post, index) => (
+ <div
+ key={post.id}
+ style={{
+ marginBottom: '6px',
+ padding: '6px',
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
+ borderLeft: `3px solid ${getPriorityColor(post.priority, colors)}`,
+ paddingLeft: '6px',
+ cursor: 'pointer'
+ }}
+ onClick={() => onViewPost(post)}
+ >
+ <div style={{ display: 'flex', gap: '4px', alignItems: 'center', marginBottom: '2px', fontSize: '8px' }}>
+ <span style={{ color: colors.GRAY }}>{post.time}</span>
+ <span style={{ color: getPriorityColor(post.priority, colors), fontWeight: 'bold' }}>[{post.priority}]</span>
+ <span style={{ color: colors.BLUE }}>[{post.category}]</span>
+ <span style={{ color: getSentimentColor(post.sentiment, colors) }}>{post.sentiment}</span>
+ {post.verified && <span style={{ color: colors.CYAN }}>[OK] VERIFIED</span>}
+ </div>
+
+ <div style={{ display: 'flex', gap: '4px', alignItems: 'center', marginBottom: '2px', fontSize: '9px' }}>
+ <span style={{ color: colors.CYAN }}>@{post.author}</span>
+ <span style={{ color: colors.GRAY }}>•</span>
+ <span style={{ color: colors.WHITE, fontWeight: 'bold' }}>{post.title}</span>
+ </div>
+
+ <div style={{ color: colors.GRAY, fontSize: '9px', lineHeight: '1.3', marginBottom: '3px' }}>
+ {post.content.substring(0, 200)}{post.content.length > 200 ? '...' : ''}
+ </div>
+
+ <div style={{ display: 'flex', gap: '6px', fontSize: '8px', marginBottom: '2px' }}>
+ {post.tags.map((tag, i) => (
+ <span
+ key={i}
+ style={{
+ color: colors.YELLOW,
+ backgroundColor: 'rgba(255,255,0,0.1)',
+ padding: '1px 4px',
+ borderRadius: '2px'
+ }}
+ >
+ #{tag}
+ </span>
+ ))}
+ </div>
+
+ <div style={{ display: 'flex', gap: '10px', fontSize: '8px' }}>
+ <span style={{ color: colors.CYAN }}>👁️ {post.views.toLocaleString()}</span>
+ <span style={{ color: colors.PURPLE }}>💬 {post.replies}</span>
+ <span style={{ color: colors.GREEN }}>👍 {post.likes}</span>
+ <span style={{ color: colors.RED }}>👎 {post.dislikes}</span>
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/components/FunctionBar.tsx b/fincept-terminal-desktop/src/components/tabs/forum/components/FunctionBar.tsx
new file mode 100644
index 000000000..da22bdde0
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/components/FunctionBar.tsx
@@ -0,0 +1,75 @@
+// Forum Tab Function Bar Component
+
+import React from 'react';
+import type { ForumColors, ForumCategoryUI } from '../types';
+
+interface FunctionBarProps {
+ colors: ForumColors;
+ activeCategory: string;
+ categories: ForumCategoryUI[];
+ onCategoryChange: (category: string) => void;
+ onCreatePost: () => void;
+ onSearch: () => void;
+ onViewProfile: () => void;
+ onEditProfile: () => void;
+}
+
+export const FunctionBar: React.FC<FunctionBarProps> = ({
+ colors,
+ activeCategory,
+ categories,
+ onCategoryChange,
+ onCreatePost,
+ onSearch,
+ onViewProfile,
+ onEditProfile
+}) => {
+ const functionKeys = [
+ { key: "F1", label: "ALL", action: () => onCategoryChange('ALL') },
+ { key: "F2", label: categories[1]?.name || "MARKETS", action: () => onCategoryChange(categories[1]?.name || "MARKETS") },
+ { key: "F3", label: categories[2]?.name || "TECH", action: () => onCategoryChange(categories[2]?.name || "TECH") },
+ { key: "F4", label: categories[3]?.name || "CRYPTO", action: () => onCategoryChange(categories[3]?.name || "CRYPTO") },
+ { key: "F5", label: categories[4]?.name || "OPTIONS", action: () => onCategoryChange(categories[4]?.name || "OPTIONS") },
+ { key: "F6", label: categories[5]?.name || "BANKING", action: () => onCategoryChange(categories[5]?.name || "BANKING") },
+ { key: "F7", label: categories[6]?.name || "ENERGY", action: () => onCategoryChange(categories[6]?.name || "ENERGY") },
+ { key: "F8", label: categories[7]?.name || "MACRO", action: () => onCategoryChange(categories[7]?.name || "MACRO") },
+ { key: "F9", label: "POST", action: onCreatePost },
+ { key: "F10", label: "SEARCH", action: onSearch },
+ { key: "F11", label: "PROFILE", action: onViewProfile },
+ { key: "F12", label: "SETTINGS", action: onEditProfile }
+ ];
+
+ return (
+ <div style={{
+ backgroundColor: colors.PANEL_BG,
+ borderBottom: `1px solid ${colors.GRAY}`,
+ padding: '2px 4px',
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: '2px' }}>
+ {functionKeys.map(item => (
+ <button
+ key={item.key}
+ onClick={item.action}
+ style={{
+ backgroundColor: activeCategory === item.label ? colors.ORANGE : colors.DARK_BG,
+ border: `1px solid ${colors.GRAY}`,
+ color: activeCategory === item.label ? colors.DARK_BG : colors.WHITE,
+ padding: '2px 4px',
+ fontSize: '9px',
+ height: '16px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ fontWeight: activeCategory === item.label ? 'bold' : 'normal',
+ cursor: 'pointer'
+ }}
+ >
+ <span style={{ color: colors.YELLOW }}>{item.key}:</span>
+ <span style={{ marginLeft: '2px' }}>{item.label}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/components/Header.tsx b/fincept-terminal-desktop/src/components/tabs/forum/components/Header.tsx
new file mode 100644
index 000000000..f0d1ebc77
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/components/Header.tsx
@@ -0,0 +1,83 @@
+// Forum Tab Header Component
+
+import React from 'react';
+import { useTranslation } from 'react-i18next';
+import type { ForumColors, TrendingTopic } from '../types';
+
+interface HeaderProps {
+ colors: ForumColors;
+ currentTime: Date;
+ onlineUsers: number;
+ postsToday: number;
+ trendingTopics: TrendingTopic[];
+ isRefreshing: boolean;
+ lastRefreshTime: Date | null;
+ onRefresh: () => void;
+}
+
+export const Header: React.FC<HeaderProps> = ({
+ colors,
+ currentTime,
+ onlineUsers,
+ postsToday,
+ trendingTopics,
+ isRefreshing,
+ lastRefreshTime,
+ onRefresh
+}) => {
+ const { t } = useTranslation('forum');
+
+ return (
+ <div style={{
+ backgroundColor: colors.PANEL_BG,
+ borderBottom: `1px solid ${colors.GRAY}`,
+ padding: '4px 8px',
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', marginBottom: '2px', justifyContent: 'space-between' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: colors.ORANGE, fontWeight: 'bold' }}>{t('title')}</span>
+ <span style={{ color: colors.WHITE }}>|</span>
+ <span style={{ color: colors.GREEN }}>● LIVE</span>
+ <span style={{ color: colors.WHITE }}>|</span>
+ <span style={{ color: colors.YELLOW }}>USERS ONLINE: {onlineUsers.toLocaleString()}</span>
+ <span style={{ color: colors.WHITE }}>|</span>
+ <span style={{ color: colors.CYAN }}>POSTS TODAY: {postsToday.toLocaleString()}</span>
+ <span style={{ color: colors.WHITE }}>|</span>
+ <span style={{ color: colors.WHITE }}>{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC</span>
+ </div>
+ <button
+ onClick={onRefresh}
+ disabled={isRefreshing}
+ style={{
+ backgroundColor: isRefreshing ? colors.GRAY : colors.ORANGE,
+ color: colors.DARK_BG,
+ border: 'none',
+ padding: '2px 8px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: isRefreshing ? 'not-allowed' : 'pointer',
+ opacity: isRefreshing ? 0.6 : 1
+ }}
+ title={lastRefreshTime ? `Last refreshed: ${lastRefreshTime.toLocaleTimeString()}` : 'Refresh forum data'}
+ >
+ {isRefreshing ? '⟳ REFRESHING...' : '⟳ REFRESH'}
+ </button>
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px' }}>
+ <span style={{ color: colors.GRAY }}>{t('header.trending')}:</span>
+ {trendingTopics.slice(0, 5).map((topic, i) => (
+ <span key={i} style={{ color: i % 2 === 0 ? colors.RED : i % 3 === 0 ? colors.CYAN : colors.PURPLE }}>
+ {topic.topic.replace('#', '').toUpperCase()}
+ </span>
+ ))}
+ <span style={{ color: colors.WHITE }}>|</span>
+ <span style={{ color: colors.GRAY }}>SENTIMENT:</span>
+ <span style={{ color: colors.GREEN }}>BULLISH 68%</span>
+ <span style={{ color: colors.RED }}>BEARISH 18%</span>
+ <span style={{ color: colors.YELLOW }}>NEUTRAL 14%</span>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/components/LeftPanel.tsx b/fincept-terminal-desktop/src/components/tabs/forum/components/LeftPanel.tsx
new file mode 100644
index 000000000..b819a47d0
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/components/LeftPanel.tsx
@@ -0,0 +1,111 @@
+// Forum Tab Left Panel Component (Categories & Stats)
+
+import React from 'react';
+import type { ForumColors, ForumCategoryUI, ForumUser } from '../types';
+import { ForumStats } from '@/services/forum/forumApi';
+import { TOP_CONTRIBUTORS } from '../constants';
+
+interface LeftPanelProps {
+ colors: ForumColors;
+ categories: ForumCategoryUI[];
+ activeCategory: string;
+ onCategoryChange: (category: string) => void;
+ onViewUserProfile: (username: string) => void;
+ forumStats: ForumStats | null;
+ totalPosts: number;
+ postsToday: number;
+ onlineUsers: number;
+}
+
+export const LeftPanel: React.FC<LeftPanelProps> = ({
+ colors,
+ categories,
+ activeCategory,
+ onCategoryChange,
+ onViewUserProfile,
+ forumStats,
+ totalPosts,
+ postsToday,
+ onlineUsers
+}) => {
+ return (
+ <div style={{
+ width: '280px',
+ backgroundColor: colors.PANEL_BG,
+ border: `1px solid ${colors.GRAY}`,
+ padding: '4px',
+ overflow: 'auto'
+ }}>
+ <div style={{ color: colors.ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
+ FORUM CATEGORIES
+ </div>
+ <div style={{ borderBottom: `1px solid ${colors.GRAY}`, marginBottom: '4px' }}></div>
+
+ {categories.map((cat, index) => (
+ <button
+ key={index}
+ onClick={() => onCategoryChange(cat.name)}
+ style={{
+ width: '100%',
+ display: 'flex',
+ justifyContent: 'space-between',
+ padding: '4px',
+ marginBottom: '2px',
+ backgroundColor: activeCategory === cat.name ? 'rgba(255,165,0,0.1)' : 'transparent',
+ border: `1px solid ${activeCategory === cat.name ? colors.ORANGE : 'transparent'}`,
+ color: cat.color,
+ fontSize: '10px',
+ cursor: 'pointer',
+ textAlign: 'left'
+ }}
+ >
+ <span>{cat.name}</span>
+ <span style={{ color: colors.CYAN }}>{cat.count}</span>
+ </button>
+ ))}
+
+ <div style={{ borderTop: `1px solid ${colors.GRAY}`, marginTop: '8px', paddingTop: '8px' }}>
+ <div style={{ color: colors.YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ TOP CONTRIBUTORS
+ </div>
+ {TOP_CONTRIBUTORS.map((user, index) => (
+ <div
+ key={index}
+ onClick={() => onViewUserProfile(user.username)}
+ style={{
+ padding: '3px',
+ marginBottom: '2px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ fontSize: '9px',
+ cursor: 'pointer'
+ }}
+ >
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
+ <span style={{ color: colors.WHITE }}>{user.username}</span>
+ <span style={{ color: user.status === 'ONLINE' ? colors.GREEN : colors.GRAY }}>
+ ●
+ </span>
+ </div>
+ <div style={{ display: 'flex', gap: '6px', color: colors.GRAY }}>
+ <span>REP: {user.reputation}</span>
+ <span>POSTS: {user.posts}</span>
+ </div>
+ </div>
+ ))}
+ </div>
+
+ <div style={{ borderTop: `1px solid ${colors.GRAY}`, marginTop: '8px', paddingTop: '8px' }}>
+ <div style={{ color: colors.YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ FORUM STATISTICS
+ </div>
+ <div style={{ fontSize: '9px', lineHeight: '1.4', color: colors.GRAY }}>
+ <div>Total Posts: {totalPosts.toLocaleString()}</div>
+ <div>Total Users: {(forumStats?.total_comments || 47832).toLocaleString()}</div>
+ <div>Posts Today: {postsToday.toLocaleString()}</div>
+ <div>Active Now: {onlineUsers}</div>
+ <div style={{ color: colors.GREEN }}>Avg Response: 12 min</div>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/components/RightPanel.tsx b/fincept-terminal-desktop/src/components/tabs/forum/components/RightPanel.tsx
new file mode 100644
index 000000000..eb8b3c319
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/components/RightPanel.tsx
@@ -0,0 +1,97 @@
+// Forum Tab Right Panel Component (Trending, Activity, Sentiment)
+
+import React from 'react';
+import type { ForumColors, TrendingTopic, RecentActivity } from '../types';
+import { getSentimentColor } from '../constants';
+
+interface RightPanelProps {
+ colors: ForumColors;
+ trendingTopics: TrendingTopic[];
+ recentActivity: RecentActivity[];
+}
+
+export const RightPanel: React.FC<RightPanelProps> = ({
+ colors,
+ trendingTopics,
+ recentActivity
+}) => {
+ return (
+ <div style={{
+ width: '280px',
+ backgroundColor: colors.PANEL_BG,
+ border: `1px solid ${colors.GRAY}`,
+ padding: '4px',
+ overflow: 'auto'
+ }}>
+ {/* Trending Topics Section */}
+ <div style={{ color: colors.ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
+ TRENDING TOPICS (1H)
+ </div>
+ <div style={{ borderBottom: `1px solid ${colors.GRAY}`, marginBottom: '8px' }}></div>
+
+ {trendingTopics.map((item, index) => (
+ <div key={index} style={{
+ padding: '3px',
+ marginBottom: '3px',
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ fontSize: '9px'
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
+ <span style={{ color: colors.YELLOW }}>{item.topic}</span>
+ <span style={{ color: colors.GREEN }}>{item.change}</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', color: colors.GRAY }}>
+ <span>{item.mentions} mentions</span>
+ <span style={{ color: getSentimentColor(item.sentiment, colors) }}>{item.sentiment}</span>
+ </div>
+ </div>
+ ))}
+
+ {/* Recent Activity Section */}
+ <div style={{ borderTop: `1px solid ${colors.GRAY}`, marginTop: '12px', paddingTop: '8px' }}>
+ <div style={{ color: colors.YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ RECENT ACTIVITY
+ </div>
+ {recentActivity.map((activity, index) => (
+ <div key={index} style={{
+ padding: '2px',
+ marginBottom: '2px',
+ fontSize: '8px',
+ color: colors.GRAY,
+ lineHeight: '1.3'
+ }}>
+ <span style={{ color: colors.CYAN }}>@{activity.user}</span>
+ {' '}<span>{activity.action}</span>{' '}
+ <span style={{ color: colors.WHITE }}>{activity.target}</span>
+ {' '}<span style={{ color: colors.YELLOW }}>• {activity.time}</span>
+ </div>
+ ))}
+ </div>
+
+ {/* Sentiment Analysis Section */}
+ <div style={{ borderTop: `1px solid ${colors.GRAY}`, marginTop: '12px', paddingTop: '8px' }}>
+ <div style={{ color: colors.YELLOW, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ SENTIMENT ANALYSIS
+ </div>
+ <div style={{ fontSize: '9px' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
+ <span style={{ color: colors.GRAY }}>Bullish Posts:</span>
+ <span style={{ color: colors.GREEN }}>68%</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
+ <span style={{ color: colors.GRAY }}>Bearish Posts:</span>
+ <span style={{ color: colors.RED }}>18%</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
+ <span style={{ color: colors.GRAY }}>Neutral Posts:</span>
+ <span style={{ color: colors.YELLOW }}>14%</span>
+ </div>
+ <div style={{ borderTop: `1px solid ${colors.GRAY}`, marginTop: '4px', paddingTop: '4px' }}>
+ <span style={{ color: colors.CYAN }}>Overall Sentiment:</span>
+ <span style={{ color: colors.GREEN, fontWeight: 'bold', marginLeft: '4px' }}>+0.62 BULLISH</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/components/index.ts b/fincept-terminal-desktop/src/components/tabs/forum/components/index.ts
new file mode 100644
index 000000000..3fe7a1730
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/components/index.ts
@@ -0,0 +1,8 @@
+// Forum components barrel export
+
+export { Header } from './Header';
+export { FunctionBar } from './FunctionBar';
+export { LeftPanel } from './LeftPanel';
+export { CenterPanel } from './CenterPanel';
+export { RightPanel } from './RightPanel';
+export * from './modals';
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/components/modals/CreatePostModal.tsx b/fincept-terminal-desktop/src/components/tabs/forum/components/modals/CreatePostModal.tsx
new file mode 100644
index 000000000..77d0f579d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/components/modals/CreatePostModal.tsx
@@ -0,0 +1,137 @@
+// Forum Tab Create Post Modal Component
+
+import React from 'react';
+import type { ForumColors } from '../../types';
+
+interface CreatePostModalProps {
+ colors: ForumColors;
+ show: boolean;
+ newPostTitle: string;
+ newPostContent: string;
+ onTitleChange: (title: string) => void;
+ onContentChange: (content: string) => void;
+ onClose: () => void;
+ onSubmit: () => void;
+}
+
+export const CreatePostModal: React.FC<CreatePostModalProps> = ({
+ colors,
+ show,
+ newPostTitle,
+ newPostContent,
+ onTitleChange,
+ onContentChange,
+ onClose,
+ onSubmit
+}) => {
+ if (!show) return null;
+
+ return (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0,0,0,0.85)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 1000
+ }}>
+ <div style={{
+ backgroundColor: colors.PANEL_BG,
+ border: `2px solid ${colors.ORANGE}`,
+ padding: '16px',
+ width: '600px',
+ maxHeight: '80vh',
+ overflow: 'auto'
+ }}>
+ <div style={{ color: colors.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>
+ CREATE NEW POST
+ </div>
+ <div style={{ borderBottom: `1px solid ${colors.GRAY}`, marginBottom: '12px' }}></div>
+
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ color: colors.WHITE, fontSize: '11px', marginBottom: '4px' }}>
+ Title: <span style={{ color: newPostTitle.length < 5 ? colors.RED : colors.GREEN }}>
+ ({newPostTitle.length}/500 chars - min 5)
+ </span>
+ </div>
+ <input
+ type="text"
+ value={newPostTitle}
+ onChange={(e) => onTitleChange(e.target.value)}
+ maxLength={500}
+ style={{
+ width: '100%',
+ backgroundColor: colors.DARK_BG,
+ border: `1px solid ${newPostTitle.length > 0 && newPostTitle.length < 5 ? colors.RED : colors.GRAY}`,
+ color: colors.WHITE,
+ padding: '6px',
+ fontSize: '12px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ placeholder="Enter post title (minimum 5 characters)..."
+ />
+ </div>
+
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ color: colors.WHITE, fontSize: '11px', marginBottom: '4px' }}>
+ Content: <span style={{ color: newPostContent.length < 10 ? colors.RED : colors.GREEN }}>
+ ({newPostContent.length}/10000 chars - min 10)
+ </span>
+ </div>
+ <textarea
+ value={newPostContent}
+ onChange={(e) => onContentChange(e.target.value)}
+ maxLength={10000}
+ rows={10}
+ style={{
+ width: '100%',
+ backgroundColor: colors.DARK_BG,
+ border: `1px solid ${newPostContent.length > 0 && newPostContent.length < 10 ? colors.RED : colors.GRAY}`,
+ color: colors.WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ resize: 'vertical'
+ }}
+ placeholder="Enter post content (minimum 10 characters)... Use #tags for topics"
+ />
+ </div>
+
+ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
+ <button
+ onClick={onClose}
+ style={{
+ backgroundColor: colors.GRAY,
+ color: colors.DARK_BG,
+ border: 'none',
+ padding: '6px 16px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ CANCEL
+ </button>
+ <button
+ onClick={onSubmit}
+ style={{
+ backgroundColor: colors.ORANGE,
+ color: colors.DARK_BG,
+ border: 'none',
+ padding: '6px 16px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ CREATE POST
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/components/modals/PostDetailModal.tsx b/fincept-terminal-desktop/src/components/tabs/forum/components/modals/PostDetailModal.tsx
new file mode 100644
index 000000000..79bf3305d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/components/modals/PostDetailModal.tsx
@@ -0,0 +1,214 @@
+// Forum Tab Post Detail Modal Component
+
+import React from 'react';
+import type { ForumColors, ForumPost, ForumComment } from '../../types';
+import { getSentimentColor } from '../../constants';
+
+interface PostDetailModalProps {
+ colors: ForumColors;
+ show: boolean;
+ selectedPost: ForumPost | null;
+ postComments: ForumComment[];
+ newComment: string;
+ onCommentChange: (comment: string) => void;
+ onClose: () => void;
+ onAddComment: () => void;
+ onVotePost: (postId: string, voteType: 'up' | 'down') => void;
+ onVoteComment: (commentId: string, voteType: 'up' | 'down') => void;
+}
+
+export const PostDetailModal: React.FC<PostDetailModalProps> = ({
+ colors,
+ show,
+ selectedPost,
+ postComments,
+ newComment,
+ onCommentChange,
+ onClose,
+ onAddComment,
+ onVotePost,
+ onVoteComment
+}) => {
+ if (!show || !selectedPost) return null;
+
+ return (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0,0,0,0.85)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 1000
+ }}>
+ <div style={{
+ backgroundColor: colors.PANEL_BG,
+ border: `2px solid ${colors.ORANGE}`,
+ padding: '16px',
+ width: '800px',
+ maxHeight: '80vh',
+ overflow: 'auto'
+ }}>
+ <>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
+ <div style={{ color: colors.ORANGE, fontSize: '14px', fontWeight: 'bold' }}>
+ POST DETAILS
+ </div>
+ <button
+ onClick={onClose}
+ style={{
+ backgroundColor: 'transparent',
+ border: `1px solid ${colors.GRAY}`,
+ color: colors.WHITE,
+ padding: '2px 8px',
+ fontSize: '10px',
+ cursor: 'pointer'
+ }}
+ >
+ CLOSE [X]
+ </button>
+ </div>
+ <div style={{ borderBottom: `1px solid ${colors.GRAY}`, marginBottom: '12px' }}></div>
+
+ {/* Post content */}
+ <div style={{ marginBottom: '16px' }}>
+ <div style={{ display: 'flex', gap: '4px', alignItems: 'center', marginBottom: '8px', fontSize: '10px' }}>
+ <span style={{ color: colors.CYAN }}>@{selectedPost.author}</span>
+ <span style={{ color: colors.GRAY }}>•</span>
+ <span style={{ color: colors.BLUE }}>[{selectedPost.category}]</span>
+ <span style={{ color: getSentimentColor(selectedPost.sentiment, colors) }}>{selectedPost.sentiment}</span>
+ </div>
+
+ <div style={{ color: colors.WHITE, fontSize: '13px', fontWeight: 'bold', marginBottom: '8px' }}>
+ {selectedPost.title}
+ </div>
+
+ <div style={{ color: colors.GRAY, fontSize: '11px', lineHeight: '1.5', marginBottom: '8px', whiteSpace: 'pre-wrap' }}>
+ {selectedPost.content}
+ </div>
+
+ <div style={{ display: 'flex', gap: '12px', fontSize: '10px', marginBottom: '8px' }}>
+ <button
+ onClick={() => onVotePost(selectedPost.id, 'up')}
+ style={{
+ backgroundColor: 'transparent',
+ border: `1px solid ${colors.GREEN}`,
+ color: colors.GREEN,
+ padding: '4px 12px',
+ fontSize: '10px',
+ cursor: 'pointer'
+ }}
+ >
+ ▲ UPVOTE ({selectedPost.likes})
+ </button>
+ <button
+ onClick={() => onVotePost(selectedPost.id, 'down')}
+ style={{
+ backgroundColor: 'transparent',
+ border: `1px solid ${colors.RED}`,
+ color: colors.RED,
+ padding: '4px 12px',
+ fontSize: '10px',
+ cursor: 'pointer'
+ }}
+ >
+ ▼ DOWNVOTE ({selectedPost.dislikes})
+ </button>
+ </div>
+ </div>
+
+ <div style={{ borderTop: `1px solid ${colors.GRAY}`, paddingTop: '12px', marginBottom: '12px' }}>
+ <div style={{ color: colors.YELLOW, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
+ COMMENTS ({postComments.length})
+ </div>
+
+ {/* Add comment form */}
+ <div style={{ marginBottom: '12px' }}>
+ <textarea
+ value={newComment}
+ onChange={(e) => onCommentChange(e.target.value)}
+ maxLength={2000}
+ rows={3}
+ style={{
+ width: '100%',
+ backgroundColor: colors.DARK_BG,
+ border: `1px solid ${colors.GRAY}`,
+ color: colors.WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ marginBottom: '4px'
+ }}
+ placeholder="Add a comment..."
+ />
+ <button
+ onClick={onAddComment}
+ style={{
+ backgroundColor: colors.ORANGE,
+ color: colors.DARK_BG,
+ border: 'none',
+ padding: '4px 12px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ POST COMMENT
+ </button>
+ </div>
+
+ {/* Comments list */}
+ {postComments.map((comment, index) => (
+ <div key={comment.id} style={{
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
+ padding: '8px',
+ marginBottom: '6px',
+ borderLeft: `2px solid ${colors.BLUE}`
+ }}>
+ <div style={{ display: 'flex', gap: '4px', alignItems: 'center', marginBottom: '4px', fontSize: '9px' }}>
+ <span style={{ color: colors.CYAN }}>@{comment.author}</span>
+ <span style={{ color: colors.GRAY }}>•</span>
+ <span style={{ color: colors.GRAY }}>{comment.time}</span>
+ </div>
+
+ <div style={{ color: colors.WHITE, fontSize: '10px', marginBottom: '4px', whiteSpace: 'pre-wrap' }}>
+ {comment.content}
+ </div>
+
+ <div style={{ display: 'flex', gap: '8px', fontSize: '9px' }}>
+ <button
+ onClick={() => onVoteComment(comment.id, 'up')}
+ style={{
+ backgroundColor: 'transparent',
+ border: 'none',
+ color: colors.GREEN,
+ cursor: 'pointer',
+ fontSize: '9px'
+ }}
+ >
+ ▲ {comment.likes}
+ </button>
+ <button
+ onClick={() => onVoteComment(comment.id, 'down')}
+ style={{
+ backgroundColor: 'transparent',
+ border: 'none',
+ color: colors.RED,
+ cursor: 'pointer',
+ fontSize: '9px'
+ }}
+ >
+ ▼ {comment.dislikes}
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+ </>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/components/modals/ProfileModal.tsx b/fincept-terminal-desktop/src/components/tabs/forum/components/modals/ProfileModal.tsx
new file mode 100644
index 000000000..3aa6b5982
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/components/modals/ProfileModal.tsx
@@ -0,0 +1,256 @@
+// Forum Tab Profile Modal Component (View and Edit modes)
+
+import React from 'react';
+import type { ForumColors, ForumUser, ProfileEdit } from '../../types';
+
+interface ProfileModalProps {
+ colors: ForumColors;
+ showProfile: boolean;
+ showEditProfile: boolean;
+ userProfile: ForumUser | null;
+ profileEdit: ProfileEdit;
+ isOwnProfile: boolean;
+ onProfileEditChange: (edit: ProfileEdit) => void;
+ onCloseProfile: () => void;
+ onCloseEditProfile: () => void;
+ onOpenEditProfile: () => void;
+ onSaveProfile: () => void;
+}
+
+export const ProfileModal: React.FC<ProfileModalProps> = ({
+ colors,
+ showProfile,
+ showEditProfile,
+ userProfile,
+ profileEdit,
+ isOwnProfile,
+ onProfileEditChange,
+ onCloseProfile,
+ onCloseEditProfile,
+ onOpenEditProfile,
+ onSaveProfile
+}) => {
+ // Profile View Modal
+ if (showProfile && userProfile) {
+ return (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0,0,0,0.85)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 1000
+ }}>
+ <div style={{
+ backgroundColor: colors.PANEL_BG,
+ border: `2px solid ${colors.ORANGE}`,
+ padding: '16px',
+ width: '600px',
+ maxHeight: '80vh',
+ overflow: 'auto'
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
+ <div style={{ color: colors.ORANGE, fontSize: '14px', fontWeight: 'bold' }}>
+ FORUM PROFILE
+ </div>
+ <button
+ onClick={onCloseProfile}
+ style={{
+ backgroundColor: 'transparent',
+ border: `1px solid ${colors.GRAY}`,
+ color: colors.WHITE,
+ padding: '2px 8px',
+ fontSize: '10px',
+ cursor: 'pointer'
+ }}
+ >
+ CLOSE [X]
+ </button>
+ </div>
+ <div style={{ borderBottom: `1px solid ${colors.GRAY}`, marginBottom: '12px' }}></div>
+
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ color: colors.CYAN, fontSize: '16px', fontWeight: 'bold', marginBottom: '8px' }}>
+ @{userProfile.username}
+ </div>
+ <div style={{ color: colors.WHITE, fontSize: '12px', marginBottom: '4px' }}>
+ {userProfile.display_name || 'No display name set'}
+ </div>
+ <div style={{ color: colors.GRAY, fontSize: '11px', marginBottom: '12px', fontStyle: 'italic' }}>
+ {userProfile.bio || 'No bio available'}
+ </div>
+
+ <div style={{ display: 'flex', gap: '16px', fontSize: '11px', marginBottom: '12px' }}>
+ <div>
+ <span style={{ color: colors.GRAY }}>Posts: </span>
+ <span style={{ color: colors.WHITE }}>{userProfile.post_count || 0}</span>
+ </div>
+ <div>
+ <span style={{ color: colors.GRAY }}>Comments: </span>
+ <span style={{ color: colors.WHITE }}>{userProfile.comment_count || 0}</span>
+ </div>
+ <div>
+ <span style={{ color: colors.GRAY }}>Reputation: </span>
+ <span style={{ color: colors.GREEN }}>{userProfile.reputation || 0}</span>
+ </div>
+ </div>
+
+ {userProfile.signature && (
+ <div style={{
+ backgroundColor: 'rgba(255,255,255,0.02)',
+ padding: '8px',
+ marginBottom: '12px',
+ borderLeft: `2px solid ${colors.YELLOW}`
+ }}>
+ <div style={{ color: colors.YELLOW, fontSize: '10px', marginBottom: '4px' }}>SIGNATURE:</div>
+ <div style={{ color: colors.GRAY, fontSize: '10px', fontStyle: 'italic' }}>
+ {userProfile.signature}
+ </div>
+ </div>
+ )}
+
+ {isOwnProfile && (
+ <button
+ onClick={onOpenEditProfile}
+ style={{
+ backgroundColor: colors.ORANGE,
+ color: colors.DARK_BG,
+ border: 'none',
+ padding: '6px 16px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ EDIT PROFILE
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ // Edit Profile Modal
+ if (showEditProfile) {
+ return (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0,0,0,0.85)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 1000
+ }}>
+ <div style={{
+ backgroundColor: colors.PANEL_BG,
+ border: `2px solid ${colors.ORANGE}`,
+ padding: '16px',
+ width: '600px',
+ maxHeight: '80vh',
+ overflow: 'auto'
+ }}>
+ <div style={{ color: colors.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>
+ EDIT PROFILE
+ </div>
+ <div style={{ borderBottom: `1px solid ${colors.GRAY}`, marginBottom: '12px' }}></div>
+
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ color: colors.WHITE, fontSize: '11px', marginBottom: '4px' }}>Display Name:</div>
+ <input
+ type="text"
+ value={profileEdit.display_name}
+ onChange={(e) => onProfileEditChange({ ...profileEdit, display_name: e.target.value })}
+ style={{
+ width: '100%',
+ backgroundColor: colors.DARK_BG,
+ border: `1px solid ${colors.GRAY}`,
+ color: colors.WHITE,
+ padding: '6px',
+ fontSize: '12px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ color: colors.WHITE, fontSize: '11px', marginBottom: '4px' }}>Bio:</div>
+ <textarea
+ value={profileEdit.bio}
+ onChange={(e) => onProfileEditChange({ ...profileEdit, bio: e.target.value })}
+ rows={4}
+ style={{
+ width: '100%',
+ backgroundColor: colors.DARK_BG,
+ border: `1px solid ${colors.GRAY}`,
+ color: colors.WHITE,
+ padding: '6px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ color: colors.WHITE, fontSize: '11px', marginBottom: '4px' }}>Signature:</div>
+ <input
+ type="text"
+ value={profileEdit.signature}
+ onChange={(e) => onProfileEditChange({ ...profileEdit, signature: e.target.value })}
+ style={{
+ width: '100%',
+ backgroundColor: colors.DARK_BG,
+ border: `1px solid ${colors.GRAY}`,
+ color: colors.WHITE,
+ padding: '6px',
+ fontSize: '12px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ />
+ </div>
+
+ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
+ <button
+ onClick={onCloseEditProfile}
+ style={{
+ backgroundColor: colors.GRAY,
+ color: colors.DARK_BG,
+ border: 'none',
+ padding: '6px 16px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ CANCEL
+ </button>
+ <button
+ onClick={onSaveProfile}
+ style={{
+ backgroundColor: colors.ORANGE,
+ color: colors.DARK_BG,
+ border: 'none',
+ padding: '6px 16px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ SAVE CHANGES
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ return null;
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/components/modals/SearchModal.tsx b/fincept-terminal-desktop/src/components/tabs/forum/components/modals/SearchModal.tsx
new file mode 100644
index 000000000..cdf57b8f8
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/components/modals/SearchModal.tsx
@@ -0,0 +1,161 @@
+// Forum Tab Search Modal Component
+
+import React from 'react';
+import type { ForumColors, ForumPost } from '../../types';
+import { getPriorityColor } from '../../constants';
+
+interface SearchModalProps {
+ colors: ForumColors;
+ show: boolean;
+ searchQuery: string;
+ searchResults: ForumPost[];
+ isLoading: boolean;
+ onQueryChange: (query: string) => void;
+ onSearch: () => void;
+ onClose: () => void;
+ onViewPost: (post: ForumPost) => void;
+}
+
+export const SearchModal: React.FC<SearchModalProps> = ({
+ colors,
+ show,
+ searchQuery,
+ searchResults,
+ isLoading,
+ onQueryChange,
+ onSearch,
+ onClose,
+ onViewPost
+}) => {
+ if (!show) return null;
+
+ const handleKeyPress = (e: React.KeyboardEvent) => {
+ if (e.key === 'Enter') {
+ onSearch();
+ }
+ };
+
+ const handleClose = () => {
+ onClose();
+ };
+
+ const handlePostClick = (post: ForumPost) => {
+ onClose();
+ onViewPost(post);
+ };
+
+ return (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: 'rgba(0,0,0,0.85)',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 1000
+ }}>
+ <div style={{
+ backgroundColor: colors.PANEL_BG,
+ border: `2px solid ${colors.ORANGE}`,
+ padding: '16px',
+ width: '700px',
+ maxHeight: '80vh',
+ overflow: 'auto'
+ }}>
+ <div style={{ color: colors.ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '12px' }}>
+ SEARCH FORUM
+ </div>
+ <div style={{ borderBottom: `1px solid ${colors.GRAY}`, marginBottom: '12px' }}></div>
+
+ <div style={{ display: 'flex', gap: '8px', marginBottom: '16px' }}>
+ <input
+ type="text"
+ value={searchQuery}
+ onChange={(e) => onQueryChange(e.target.value)}
+ onKeyPress={handleKeyPress}
+ style={{
+ flex: 1,
+ backgroundColor: colors.DARK_BG,
+ border: `1px solid ${colors.GRAY}`,
+ color: colors.WHITE,
+ padding: '8px',
+ fontSize: '12px',
+ fontFamily: 'Consolas, monospace'
+ }}
+ placeholder="Search posts and comments..."
+ />
+ <button
+ onClick={onSearch}
+ style={{
+ backgroundColor: colors.ORANGE,
+ color: colors.DARK_BG,
+ border: 'none',
+ padding: '8px 16px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ SEARCH
+ </button>
+ <button
+ onClick={handleClose}
+ style={{
+ backgroundColor: colors.GRAY,
+ color: colors.DARK_BG,
+ border: 'none',
+ padding: '8px 16px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ cursor: 'pointer'
+ }}
+ >
+ CLOSE
+ </button>
+ </div>
+
+ {isLoading && (
+ <div style={{ color: colors.YELLOW, textAlign: 'center', padding: '20px' }}>
+ SEARCHING...
+ </div>
+ )}
+
+ {searchResults.length > 0 && (
+ <div>
+ <div style={{ color: colors.YELLOW, fontSize: '11px', marginBottom: '8px' }}>
+ FOUND {searchResults.length} RESULTS
+ </div>
+ {searchResults.map((post, index) => (
+ <div
+ key={post.id}
+ onClick={() => handlePostClick(post)}
+ style={{
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.02)' : 'transparent',
+ padding: '8px',
+ marginBottom: '6px',
+ borderLeft: `3px solid ${getPriorityColor(post.priority, colors)}`,
+ cursor: 'pointer'
+ }}
+ >
+ <div style={{ color: colors.WHITE, fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
+ {post.title}
+ </div>
+ <div style={{ color: colors.GRAY, fontSize: '10px', marginBottom: '4px' }}>
+ {post.content.substring(0, 150)}...
+ </div>
+ <div style={{ display: 'flex', gap: '8px', fontSize: '9px' }}>
+ <span style={{ color: colors.CYAN }}>@{post.author}</span>
+ <span style={{ color: colors.BLUE }}>[{post.category}]</span>
+ <span style={{ color: colors.GREEN }}>👍 {post.likes}</span>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/components/modals/index.ts b/fincept-terminal-desktop/src/components/tabs/forum/components/modals/index.ts
new file mode 100644
index 000000000..f8c6ec24b
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/components/modals/index.ts
@@ -0,0 +1,6 @@
+// Forum modals barrel export
+
+export { CreatePostModal } from './CreatePostModal';
+export { PostDetailModal } from './PostDetailModal';
+export { SearchModal } from './SearchModal';
+export { ProfileModal } from './ProfileModal';
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/constants.ts b/fincept-terminal-desktop/src/components/tabs/forum/constants.ts
new file mode 100644
index 000000000..d3d592f59
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/constants.ts
@@ -0,0 +1,53 @@
+// Forum Tab Constants
+
+import type { ForumUser, ForumColors } from './types';
+
+// Helper function to get forum colors from theme
+export const getForumColors = (colors: any): ForumColors => ({
+ ORANGE: colors.primary,
+ WHITE: colors.text,
+ RED: colors.alert,
+ GREEN: colors.secondary,
+ YELLOW: colors.warning,
+ GRAY: colors.textMuted,
+ BLUE: colors.info,
+ PURPLE: colors.purple,
+ CYAN: colors.accent,
+ DARK_BG: colors.background,
+ PANEL_BG: colors.panel
+});
+
+// Top contributors - static data
+export const TOP_CONTRIBUTORS: ForumUser[] = [
+ { username: 'QuantTrader_Pro', reputation: 8947, posts: 1234, joined: '2021-03-15', status: 'ONLINE' },
+ { username: 'CryptoWhale_2024', reputation: 7823, posts: 892, joined: '2020-11-22', status: 'ONLINE' },
+ { username: 'OptionsFlow_Alert', reputation: 7456, posts: 1567, joined: '2022-01-08', status: 'ONLINE' },
+ { username: 'MacroHedgeFund', reputation: 6789, posts: 743, joined: '2021-07-19', status: 'OFFLINE' },
+ { username: 'TechInvestor88', reputation: 6234, posts: 654, joined: '2022-05-12', status: 'ONLINE' },
+ { username: 'EnergyAnalyst_TX', reputation: 5892, posts: 521, joined: '2021-09-30', status: 'ONLINE' }
+];
+
+// Category colors for mapping
+export const CATEGORY_COLORS = (colors: ForumColors) => [
+ colors.BLUE, colors.PURPLE, colors.CYAN, colors.YELLOW,
+ colors.GREEN, colors.ORANGE, colors.RED, colors.PURPLE
+];
+
+// Helper functions for priority and sentiment colors
+export const getPriorityColor = (priority: string, colors: ForumColors): string => {
+ switch (priority) {
+ case 'HOT': return colors.RED;
+ case 'TRENDING': return colors.ORANGE;
+ case 'NORMAL': return colors.GRAY;
+ default: return colors.GRAY;
+ }
+};
+
+export const getSentimentColor = (sentiment: string, colors: ForumColors): string => {
+ switch (sentiment) {
+ case 'BULLISH': return colors.GREEN;
+ case 'BEARISH': return colors.RED;
+ case 'NEUTRAL': return colors.YELLOW;
+ default: return colors.GRAY;
+ }
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/forum/hooks/index.ts
new file mode 100644
index 000000000..a94fd967a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/hooks/index.ts
@@ -0,0 +1,6 @@
+// Forum hooks barrel export
+
+export { useForum } from './useForum';
+export { useForumModals } from './useForumModals';
+export type { UseForumReturn } from './useForum';
+export type { UseForumModalsReturn } from './useForumModals';
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/hooks/useForum.ts b/fincept-terminal-desktop/src/components/tabs/forum/hooks/useForum.ts
new file mode 100644
index 000000000..30b9411c3
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/hooks/useForum.ts
@@ -0,0 +1,646 @@
+// Hook for managing forum data and API calls
+
+import { useState, useEffect, useCallback, useRef } from 'react';
+import { useAuth } from '@/contexts/AuthContext';
+import { ForumApiService, ForumPost as APIForumPost, ForumCategory, ForumStats, ForumComment as APIForumComment } from '@/services/forum/forumApi';
+import { sqliteService, getSetting, saveSetting } from '@/services/core/sqliteService';
+import type { ForumPost, ForumComment, ForumCategoryUI, TrendingTopic, RecentActivity, ForumColors } from '../types';
+import { CATEGORY_COLORS } from '../constants';
+
+interface UseForumProps {
+ colors: ForumColors;
+}
+
+export interface UseForumReturn {
+ // Data states
+ categories: ForumCategoryUI[];
+ forumPosts: ForumPost[];
+ filteredPosts: ForumPost[];
+ forumStats: ForumStats | null;
+ trendingTopics: TrendingTopic[];
+ recentActivity: RecentActivity[];
+ postComments: ForumComment[];
+ searchResults: ForumPost[];
+ userProfile: any;
+
+ // UI states
+ activeCategory: string;
+ setActiveCategory: (category: string) => void;
+ sortBy: string;
+ setSortBy: (sort: string) => void;
+ onlineUsers: number;
+ isLoading: boolean;
+ isRefreshing: boolean;
+ lastRefreshTime: Date | null;
+
+ // Selected data
+ selectedPost: ForumPost | null;
+ setSelectedPost: (post: ForumPost | null) => void;
+ setPostComments: (comments: ForumComment[]) => void;
+ selectedUsername: string;
+ setSelectedUsername: (username: string) => void;
+
+ // Actions
+ fetchCategories: (forceRefresh?: boolean) => Promise<void>;
+ fetchPosts: (forceRefresh?: boolean) => Promise<void>;
+ fetchForumStats: (forceRefresh?: boolean) => Promise<void>;
+ handleCreatePost: (title: string, content: string) => Promise<boolean>;
+ handleViewPost: (post: ForumPost) => Promise<void>;
+ handleAddComment: (comment: string) => Promise<boolean>;
+ handleVotePost: (postId: string, voteType: 'up' | 'down') => Promise<void>;
+ handleVoteComment: (commentId: string, voteType: 'up' | 'down') => Promise<void>;
+ handleSearch: (query: string) => Promise<void>;
+ handleViewMyProfile: () => Promise<void>;
+ handleViewUserProfile: (username: string) => Promise<void>;
+ handleUpdateProfile: (profileEdit: any) => Promise<boolean>;
+ handleRefresh: () => Promise<void>;
+
+ // Computed values
+ totalPosts: number;
+ postsToday: number;
+}
+
+export function useForum({ colors }: UseForumProps): UseForumReturn {
+ const { session } = useAuth();
+
+ // Data states
+ const [categories, setCategories] = useState<ForumCategoryUI[]>([]);
+ const [forumPosts, setForumPosts] = useState<ForumPost[]>([]);
+ const [forumStats, setForumStats] = useState<ForumStats | null>(null);
+ const [trendingTopics, setTrendingTopics] = useState<TrendingTopic[]>([]);
+ const [recentActivity, setRecentActivity] = useState<RecentActivity[]>([]);
+ const [postComments, setPostComments] = useState<ForumComment[]>([]);
+ const [searchResults, setSearchResults] = useState<ForumPost[]>([]);
+ const [userProfile, setUserProfile] = useState<any>(null);
+
+ // UI states
+ const [activeCategory, setActiveCategory] = useState('ALL');
+ const [sortBy, setSortBy] = useState('latest');
+ const [onlineUsers, setOnlineUsers] = useState(1247);
+ const [isLoading, setIsLoading] = useState(false);
+ const [isRefreshing, setIsRefreshing] = useState(false);
+ const [lastRefreshTime, setLastRefreshTime] = useState<Date | null>(null);
+
+ // Selected data
+ const [selectedPost, setSelectedPost] = useState<ForumPost | null>(null);
+ const [selectedUsername, setSelectedUsername] = useState('');
+
+ // Auto-refresh interval ref
+ const autoRefreshIntervalRef = useRef<NodeJS.Timeout | null>(null);
+
+ // Get API credentials
+ const getApiCredentials = useCallback(async () => {
+ const apiKey = session?.api_key || await getSetting('fincept_api_key') || undefined;
+ const deviceId = session?.device_id || await getSetting('fincept_device_id') || undefined;
+ return { apiKey, deviceId };
+ }, [session]);
+
+ // Convert API post to UI format
+ const convertApiPostToUIFormat = useCallback((apiPost: APIForumPost): ForumPost => {
+ const likes = apiPost.likes || 0;
+ const dislikes = apiPost.dislikes || 0;
+ const voteScore = likes - dislikes;
+ const sentiment: 'BULLISH' | 'BEARISH' | 'NEUTRAL' = voteScore > 10 ? 'BULLISH' : voteScore < -5 ? 'BEARISH' : 'NEUTRAL';
+ const priority: 'HOT' | 'TRENDING' | 'NORMAL' = likes > 300 ? 'HOT' : likes > 150 ? 'TRENDING' : 'NORMAL';
+
+ const tagMatches = apiPost.content.match(/#\w+/g) || [];
+ const tags = tagMatches.slice(0, 5).map(tag => tag.substring(1));
+
+ return {
+ id: apiPost.post_uuid,
+ time: new Date(apiPost.created_at).toLocaleTimeString('en-US', { hour12: false }),
+ author: apiPost.author_display_name || 'Anonymous',
+ title: apiPost.title,
+ content: apiPost.content,
+ category: apiPost.category_name?.toUpperCase() || 'GENERAL',
+ categoryId: apiPost.category_id || 0,
+ tags: tags.length > 0 ? tags : ['DISCUSSION'],
+ views: apiPost.views || 0,
+ replies: apiPost.reply_count || 0,
+ likes,
+ dislikes,
+ sentiment,
+ priority,
+ verified: likes > 100
+ };
+ }, []);
+
+ // Convert API comment to UI format
+ const convertApiCommentToUIFormat = useCallback((apiComment: APIForumComment): ForumComment => {
+ return {
+ id: apiComment.comment_uuid,
+ author: apiComment.author_display_name || 'Anonymous',
+ content: apiComment.content,
+ time: new Date(apiComment.created_at).toLocaleTimeString('en-US', { hour12: false }),
+ likes: apiComment.likes || 0,
+ dislikes: apiComment.dislikes || 0
+ };
+ }, []);
+
+ // Fetch forum categories
+ const fetchCategories = useCallback(async (forceRefresh: boolean = false) => {
+ try {
+ if (!forceRefresh) {
+ const cachedCategories = await sqliteService.getCachedForumCategories(5);
+ if (cachedCategories) {
+ setCategories(cachedCategories);
+ return;
+ }
+ }
+
+ const { apiKey, deviceId } = await getApiCredentials();
+ const response = await ForumApiService.getCategories(apiKey, deviceId);
+
+ if (response.success && response.data?.data?.categories) {
+ const apiCategories = response.data.data.categories;
+ const categoryColors = CATEGORY_COLORS(colors);
+
+ const formattedCategories = [
+ { name: 'ALL', count: apiCategories.reduce((sum: number, cat: ForumCategory) => sum + cat.post_count, 0), color: colors.WHITE, id: 0 },
+ ...apiCategories.map((cat: ForumCategory, index: number) => ({
+ name: cat.name.toUpperCase(),
+ count: cat.post_count,
+ color: categoryColors[index % categoryColors.length],
+ id: cat.id
+ }))
+ ];
+
+ setCategories(formattedCategories);
+ await sqliteService.cacheForumCategories(formattedCategories);
+ }
+ } catch (error) {
+ console.debug('Forum API not available (categories)');
+ }
+ }, [getApiCredentials, colors]);
+
+ // Fetch forum posts
+ const fetchPosts = useCallback(async (forceRefresh: boolean = false) => {
+ setIsLoading(true);
+ try {
+ const categoryId = activeCategory === 'ALL' ? null : categories.find(c => c.name === activeCategory)?.id || null;
+ const { apiKey, deviceId } = await getApiCredentials();
+ let response;
+
+ if (activeCategory === 'ALL') {
+ const allPosts: any[] = [];
+ for (const cat of categories.filter(c => c.id !== undefined)) {
+ const catResponse = await ForumApiService.getPostsByCategory(cat.id, sortBy, 20, apiKey, deviceId);
+ if (catResponse?.success && catResponse.data) {
+ const posts = (catResponse.data as any).data?.posts || [];
+ allPosts.push(...posts);
+ }
+ }
+ response = { success: true, data: { data: { posts: allPosts } } };
+ } else {
+ if (categoryId) {
+ response = await ForumApiService.getPostsByCategory(categoryId, sortBy, 20, apiKey, deviceId);
+ }
+ }
+
+ if (response?.success && response.data) {
+ const responseData = response.data as any;
+ const posts = responseData.data?.posts || [];
+
+ if (posts.length > 0) {
+ const formattedPosts = posts.map(convertApiPostToUIFormat);
+ setForumPosts(formattedPosts);
+ await sqliteService.cacheForumPosts(categoryId, sortBy, formattedPosts);
+ } else {
+ setForumPosts([]);
+ }
+ }
+ } catch (error) {
+ console.debug('Forum API not available (posts)');
+ } finally {
+ setIsLoading(false);
+ }
+ }, [activeCategory, sortBy, categories, getApiCredentials, convertApiPostToUIFormat]);
+
+ // Fetch forum statistics
+ const fetchForumStats = useCallback(async (forceRefresh: boolean = false) => {
+ try {
+ if (!forceRefresh) {
+ const cachedStats = await sqliteService.getCachedForumStats(5);
+ if (cachedStats) {
+ setForumStats(cachedStats);
+ if (cachedStats.active_users) {
+ setOnlineUsers(cachedStats.active_users);
+ }
+ return;
+ }
+ }
+
+ const { apiKey, deviceId } = await getApiCredentials();
+ const response = await ForumApiService.getForumStats(apiKey, deviceId);
+
+ if (response.success && response.data?.data) {
+ setForumStats(response.data.data);
+ if (response.data.data.active_users) {
+ setOnlineUsers(response.data.data.active_users);
+ }
+ await sqliteService.cacheForumStats(response.data.data);
+ }
+ } catch (error) {
+ console.debug('Forum API not available (stats)');
+ }
+ }, [getApiCredentials]);
+
+ // Create new post
+ const handleCreatePost = useCallback(async (title: string, content: string): Promise<boolean> => {
+ if (!title.trim() || title.trim().length < 5 || title.trim().length > 500) {
+ alert('Post title must be between 5 and 500 characters');
+ return false;
+ }
+ if (!content.trim() || content.trim().length < 10) {
+ alert('Post content must be at least 10 characters long');
+ return false;
+ }
+
+ const { apiKey, deviceId } = await getApiCredentials();
+ if (!apiKey) {
+ alert('You must be logged in to create posts');
+ return false;
+ }
+
+ const categoryId = categories.find(c => c.name === activeCategory)?.id || categories[1]?.id || 1;
+
+ try {
+ const response = await ForumApiService.createPost(
+ categoryId,
+ { title: title.trim(), content: content.trim() },
+ apiKey,
+ deviceId
+ );
+
+ if (response.success) {
+ alert('Post created successfully!');
+ fetchPosts(true);
+ return true;
+ } else {
+ alert(`Failed to create post: ${response.error || response.data?.message || 'Unknown error'}`);
+ return false;
+ }
+ } catch (error) {
+ alert('Error creating post');
+ return false;
+ }
+ }, [getApiCredentials, categories, activeCategory, fetchPosts]);
+
+ // View post details with comments
+ const handleViewPost = useCallback(async (post: ForumPost) => {
+ setSelectedPost(post);
+
+ const { apiKey, deviceId } = await getApiCredentials();
+ try {
+ const response = await ForumApiService.getPostDetails(post.id, apiKey, deviceId);
+
+ if (response.success && response.data?.data) {
+ const comments = response.data.data.comments || [];
+ const formattedComments = comments.map(convertApiCommentToUIFormat);
+ setPostComments(formattedComments);
+ }
+ } catch (error) {
+ console.debug('Forum API not available (post details)');
+ }
+ }, [getApiCredentials, convertApiCommentToUIFormat]);
+
+ // Add comment to post
+ const handleAddComment = useCallback(async (comment: string): Promise<boolean> => {
+ if (!comment.trim() || !selectedPost) return false;
+
+ const { apiKey, deviceId } = await getApiCredentials();
+ if (!apiKey) {
+ alert('You must be logged in to comment');
+ return false;
+ }
+
+ try {
+ const response = await ForumApiService.addComment(
+ selectedPost.id,
+ { content: comment },
+ apiKey,
+ deviceId
+ );
+
+ if (response.success) {
+ handleViewPost(selectedPost);
+ return true;
+ } else {
+ alert(`Failed to add comment: ${response.error || 'Unknown error'}`);
+ return false;
+ }
+ } catch (error) {
+ alert('Error adding comment');
+ return false;
+ }
+ }, [getApiCredentials, selectedPost, handleViewPost]);
+
+ // Vote on post
+ const handleVotePost = useCallback(async (postId: string, voteType: 'up' | 'down') => {
+ const { apiKey, deviceId } = await getApiCredentials();
+ if (!apiKey) {
+ alert('You must be logged in to vote');
+ return;
+ }
+
+ try {
+ const response = await ForumApiService.voteOnPost(postId, voteType, apiKey, deviceId);
+
+ if (response.success) {
+ fetchPosts(true);
+ if (selectedPost && selectedPost.id === postId) {
+ handleViewPost(selectedPost);
+ }
+ } else {
+ alert(`Vote failed: ${response.error || 'Unknown error'}`);
+ }
+ } catch (error) {
+ // Silently handle error
+ }
+ }, [getApiCredentials, fetchPosts, selectedPost, handleViewPost]);
+
+ // Vote on comment
+ const handleVoteComment = useCallback(async (commentId: string, voteType: 'up' | 'down') => {
+ const { apiKey, deviceId } = await getApiCredentials();
+ if (!apiKey) {
+ alert('You must be logged in to vote');
+ return;
+ }
+
+ try {
+ const response = await ForumApiService.voteOnComment(commentId, voteType, apiKey, deviceId);
+
+ if (response.success && selectedPost) {
+ handleViewPost(selectedPost);
+ }
+ } catch (error) {
+ // Silently handle error
+ }
+ }, [getApiCredentials, selectedPost, handleViewPost]);
+
+ // Search forum
+ const handleSearch = useCallback(async (query: string) => {
+ if (!query.trim()) return;
+
+ const { apiKey, deviceId } = await getApiCredentials();
+ setIsLoading(true);
+
+ try {
+ const response = await ForumApiService.searchPosts(query, 'all', 20, apiKey, deviceId);
+
+ if (response.success && response.data?.data?.results?.posts) {
+ const posts = response.data.data.results.posts;
+ const formattedPosts = posts.map(convertApiPostToUIFormat);
+ setSearchResults(formattedPosts);
+ }
+ } catch (error) {
+ // Silently handle error
+ } finally {
+ setIsLoading(false);
+ }
+ }, [getApiCredentials, convertApiPostToUIFormat]);
+
+ // View my profile
+ const handleViewMyProfile = useCallback(async () => {
+ const { apiKey, deviceId } = await getApiCredentials();
+ if (!apiKey) {
+ alert('You must be logged in to view profile');
+ return;
+ }
+
+ try {
+ const response = await ForumApiService.getMyProfile(apiKey, deviceId);
+
+ if (response.success && response.data?.data) {
+ setUserProfile(response.data.data);
+ setSelectedUsername('');
+ }
+ } catch (error) {
+ alert('Error loading profile');
+ }
+ }, [getApiCredentials]);
+
+ // View user profile
+ const handleViewUserProfile = useCallback(async (username: string) => {
+ const { apiKey, deviceId } = await getApiCredentials();
+ if (!apiKey) {
+ alert('You must be logged in to view profiles');
+ return;
+ }
+
+ setSelectedUsername(username);
+
+ try {
+ const response = await ForumApiService.getUserProfile(username, apiKey, deviceId);
+
+ if (response.success && response.data?.data) {
+ setUserProfile(response.data.data);
+ }
+ } catch (error) {
+ alert('Error loading user profile');
+ }
+ }, [getApiCredentials]);
+
+ // Update profile
+ const handleUpdateProfile = useCallback(async (profileEdit: any): Promise<boolean> => {
+ const { apiKey, deviceId } = await getApiCredentials();
+ if (!apiKey) return false;
+
+ try {
+ const response = await ForumApiService.updateProfile(profileEdit, apiKey, deviceId);
+
+ if (response.success) {
+ alert('Profile updated successfully!');
+ handleViewMyProfile();
+ return true;
+ } else {
+ alert(`Failed to update profile: ${response.error || 'Unknown error'}`);
+ return false;
+ }
+ } catch (error) {
+ alert('Error updating profile');
+ return false;
+ }
+ }, [getApiCredentials, handleViewMyProfile]);
+
+ // Manual refresh
+ const handleRefresh = useCallback(async () => {
+ if (isRefreshing) return;
+
+ setIsRefreshing(true);
+
+ try {
+ await Promise.all([
+ fetchCategories(true),
+ fetchForumStats(true),
+ fetchPosts(true)
+ ]);
+
+ setLastRefreshTime(new Date());
+ } catch (error) {
+ // Silently handle error
+ } finally {
+ setIsRefreshing(false);
+ }
+ }, [isRefreshing, fetchCategories, fetchForumStats, fetchPosts]);
+
+ // Generate trending topics from posts
+ const generateTrendingTopics = useCallback(() => {
+ const topicsMap: { [key: string]: { count: number; sentiment: string } } = {};
+
+ forumPosts.forEach(post => {
+ post.tags.forEach(tag => {
+ const topic = `#${tag}`;
+ if (!topicsMap[topic]) {
+ topicsMap[topic] = { count: 0, sentiment: 'NEUTRAL' };
+ }
+ topicsMap[topic].count += 1;
+ if (post.sentiment === 'BULLISH') topicsMap[topic].sentiment = 'BULLISH';
+ });
+ });
+
+ const trending = Object.entries(topicsMap)
+ .map(([topic, data]) => ({
+ topic,
+ mentions: data.count * 100,
+ sentiment: data.sentiment,
+ change: `+${Math.floor(Math.random() * 200 + 50)}%`
+ }))
+ .sort((a, b) => b.mentions - a.mentions)
+ .slice(0, 6);
+
+ setTrendingTopics(trending);
+ }, [forumPosts]);
+
+ // Generate recent activity from posts
+ const generateRecentActivity = useCallback(() => {
+ const activities = forumPosts.slice(0, 5).map((post, index) => ({
+ user: post.author,
+ action: index % 3 === 0 ? 'posted' : index % 3 === 1 ? 'replied to' : 'liked',
+ target: post.title.substring(0, 30) + '...',
+ time: `${(index + 1) * 3} min ago`
+ }));
+
+ setRecentActivity(activities);
+ }, [forumPosts]);
+
+ // Initial load
+ useEffect(() => {
+ const initForum = async () => {
+ fetchCategories();
+ fetchForumStats();
+
+ const selectedPostId = await getSetting('forum_selected_post_id');
+ if (selectedPostId) {
+ await saveSetting('forum_selected_post_id', '', 'forum');
+ setTimeout(async () => {
+ const post = forumPosts.find(p => p.id === selectedPostId);
+ if (post) {
+ handleViewPost(post);
+ } else {
+ try {
+ const { apiKey, deviceId } = await getApiCredentials();
+ const response = await ForumApiService.getPostDetails(selectedPostId, apiKey, deviceId);
+ if (response.success && response.data) {
+ const apiPost = (response.data as any).data?.post || (response.data as any).post;
+ const post = convertApiPostToUIFormat(apiPost);
+ setSelectedPost(post);
+ const comments = ((response.data as any).data?.comments || (response.data as any).comments || []).map(convertApiCommentToUIFormat);
+ setPostComments(comments);
+ }
+ } catch (err) {
+ // Silently handle error
+ }
+ }
+ }, 1000);
+ }
+ };
+ initForum();
+ }, []);
+
+ // Fetch posts when category or sort changes
+ useEffect(() => {
+ if (categories.length > 0) {
+ fetchPosts();
+ }
+ }, [activeCategory, sortBy, categories, fetchPosts]);
+
+ // Generate derived data
+ useEffect(() => {
+ if (forumPosts.length > 0) {
+ generateTrendingTopics();
+ generateRecentActivity();
+ }
+ }, [forumPosts, generateTrendingTopics, generateRecentActivity]);
+
+ // Update online users periodically
+ useEffect(() => {
+ const timer = setInterval(() => {
+ setOnlineUsers(prev => Math.max(1000, prev + Math.floor(Math.random() * 10) - 5));
+ }, 5000);
+ return () => clearInterval(timer);
+ }, []);
+
+ // Auto-refresh every 5 minutes
+ useEffect(() => {
+ const autoRefreshInterval = setInterval(() => {
+ handleRefresh();
+ }, 5 * 60 * 1000);
+
+ autoRefreshIntervalRef.current = autoRefreshInterval;
+
+ return () => {
+ if (autoRefreshIntervalRef.current) {
+ clearInterval(autoRefreshIntervalRef.current);
+ }
+ };
+ }, [handleRefresh]);
+
+ // Computed values
+ const filteredPosts = activeCategory === 'ALL'
+ ? forumPosts
+ : forumPosts.filter(post => post.category === activeCategory);
+
+ const totalPosts = forumStats?.total_posts || categories.find(c => c.name === 'ALL')?.count || 0;
+ const postsToday = Math.floor(totalPosts * 0.003);
+
+ return {
+ categories,
+ forumPosts,
+ filteredPosts,
+ forumStats,
+ trendingTopics,
+ recentActivity,
+ postComments,
+ searchResults,
+ userProfile,
+ activeCategory,
+ setActiveCategory,
+ sortBy,
+ setSortBy,
+ onlineUsers,
+ isLoading,
+ isRefreshing,
+ lastRefreshTime,
+ selectedPost,
+ setSelectedPost,
+ setPostComments,
+ selectedUsername,
+ setSelectedUsername,
+ fetchCategories,
+ fetchPosts,
+ fetchForumStats,
+ handleCreatePost,
+ handleViewPost,
+ handleAddComment,
+ handleVotePost,
+ handleVoteComment,
+ handleSearch,
+ handleViewMyProfile,
+ handleViewUserProfile,
+ handleUpdateProfile,
+ handleRefresh,
+ totalPosts,
+ postsToday
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/hooks/useForumModals.ts b/fincept-terminal-desktop/src/components/tabs/forum/hooks/useForumModals.ts
new file mode 100644
index 000000000..5f33f55a1
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/hooks/useForumModals.ts
@@ -0,0 +1,107 @@
+// Hook for managing forum modal states
+
+import { useState, useCallback } from 'react';
+import type { ProfileEdit, ForumColors } from '../types';
+
+interface UseForumModalsProps {
+ colors: ForumColors;
+}
+
+export interface UseForumModalsReturn {
+ // Modal visibility states
+ showCreatePost: boolean;
+ showPostDetail: boolean;
+ showSearch: boolean;
+ showProfile: boolean;
+ showEditProfile: boolean;
+
+ // Form states
+ newPostTitle: string;
+ newPostContent: string;
+ newComment: string;
+ searchQuery: string;
+ profileEdit: ProfileEdit;
+
+ // Actions
+ setShowCreatePost: (show: boolean) => void;
+ setShowPostDetail: (show: boolean) => void;
+ setShowSearch: (show: boolean) => void;
+ setShowProfile: (show: boolean) => void;
+ setShowEditProfile: (show: boolean) => void;
+ setNewPostTitle: (title: string) => void;
+ setNewPostContent: (content: string) => void;
+ setNewComment: (comment: string) => void;
+ setSearchQuery: (query: string) => void;
+ setProfileEdit: (edit: ProfileEdit) => void;
+ resetCreatePostForm: () => void;
+ resetSearchForm: () => void;
+ initProfileEdit: (profile: any) => void;
+}
+
+export function useForumModals({ colors }: UseForumModalsProps): UseForumModalsReturn {
+ // Modal visibility states
+ const [showCreatePost, setShowCreatePost] = useState(false);
+ const [showPostDetail, setShowPostDetail] = useState(false);
+ const [showSearch, setShowSearch] = useState(false);
+ const [showProfile, setShowProfile] = useState(false);
+ const [showEditProfile, setShowEditProfile] = useState(false);
+
+ // Form states
+ const [newPostTitle, setNewPostTitle] = useState('');
+ const [newPostContent, setNewPostContent] = useState('');
+ const [newComment, setNewComment] = useState('');
+ const [searchQuery, setSearchQuery] = useState('');
+ const [profileEdit, setProfileEdit] = useState<ProfileEdit>({
+ display_name: '',
+ bio: '',
+ avatar_color: colors.ORANGE,
+ signature: ''
+ });
+
+ // Reset create post form
+ const resetCreatePostForm = useCallback(() => {
+ setNewPostTitle('');
+ setNewPostContent('');
+ }, []);
+
+ // Reset search form
+ const resetSearchForm = useCallback(() => {
+ setSearchQuery('');
+ }, []);
+
+ // Initialize profile edit from profile data
+ const initProfileEdit = useCallback((profile: any) => {
+ setProfileEdit({
+ display_name: profile?.display_name || '',
+ bio: profile?.bio || '',
+ avatar_color: profile?.avatar_color || colors.ORANGE,
+ signature: profile?.signature || ''
+ });
+ }, [colors.ORANGE]);
+
+ return {
+ showCreatePost,
+ showPostDetail,
+ showSearch,
+ showProfile,
+ showEditProfile,
+ newPostTitle,
+ newPostContent,
+ newComment,
+ searchQuery,
+ profileEdit,
+ setShowCreatePost,
+ setShowPostDetail,
+ setShowSearch,
+ setShowProfile,
+ setShowEditProfile,
+ setNewPostTitle,
+ setNewPostContent,
+ setNewComment,
+ setSearchQuery,
+ setProfileEdit,
+ resetCreatePostForm,
+ resetSearchForm,
+ initProfileEdit
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/index.ts b/fincept-terminal-desktop/src/components/tabs/forum/index.ts
new file mode 100644
index 000000000..556c7f1fe
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/index.ts
@@ -0,0 +1,16 @@
+// Forum Tab Barrel Export
+
+export { default as ForumTab } from './ForumTab';
+export { default } from './ForumTab';
+
+// Export types
+export * from './types';
+
+// Export constants
+export * from './constants';
+
+// Export hooks
+export * from './hooks';
+
+// Export components
+export * from './components';
diff --git a/fincept-terminal-desktop/src/components/tabs/forum/types.ts b/fincept-terminal-desktop/src/components/tabs/forum/types.ts
new file mode 100644
index 000000000..2464c5954
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/forum/types.ts
@@ -0,0 +1,89 @@
+// Forum Tab Types
+
+import type { ForumPost as APIForumPost, ForumCategory, ForumStats, ForumComment as APIForumComment } from '@/services/forum/forumApi';
+
+// Re-export API types
+export type { APIForumPost, ForumCategory, ForumStats, APIForumComment };
+
+export interface ForumPost {
+ id: string;
+ time: string;
+ author: string;
+ title: string;
+ content: string;
+ category: string;
+ categoryId: number;
+ tags: string[];
+ views: number;
+ replies: number;
+ likes: number;
+ dislikes: number;
+ sentiment: 'BULLISH' | 'BEARISH' | 'NEUTRAL';
+ priority: 'HOT' | 'TRENDING' | 'NORMAL';
+ verified: boolean;
+}
+
+export interface ForumComment {
+ id: string;
+ author: string;
+ content: string;
+ time: string;
+ likes: number;
+ dislikes: number;
+}
+
+export interface ForumUser {
+ username: string;
+ reputation: number;
+ posts: number;
+ joined: string;
+ status: 'ONLINE' | 'OFFLINE';
+ // Profile fields (from API)
+ display_name?: string;
+ bio?: string;
+ signature?: string;
+ post_count?: number;
+ comment_count?: number;
+}
+
+export interface ForumCategoryUI {
+ name: string;
+ count: number;
+ color: string;
+ id: number;
+}
+
+export interface TrendingTopic {
+ topic: string;
+ mentions: number;
+ sentiment: string;
+ change: string;
+}
+
+export interface RecentActivity {
+ user: string;
+ action: string;
+ target: string;
+ time: string;
+}
+
+export interface ProfileEdit {
+ display_name: string;
+ bio: string;
+ avatar_color: string;
+ signature: string;
+}
+
+export interface ForumColors {
+ ORANGE: string;
+ WHITE: string;
+ RED: string;
+ GREEN: string;
+ YELLOW: string;
+ GRAY: string;
+ BLUE: string;
+ PURPLE: string;
+ CYAN: string;
+ DARK_BG: string;
+ PANEL_BG: string;
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/GeopoliticsHDXPanel.tsx b/fincept-terminal-desktop/src/components/tabs/geopolitics-hdx/GeopoliticsHDXPanel.tsx
similarity index 99%
rename from fincept-terminal-desktop/src/components/tabs/GeopoliticsHDXPanel.tsx
rename to fincept-terminal-desktop/src/components/tabs/geopolitics-hdx/GeopoliticsHDXPanel.tsx
index e9aa85d64..54e8a2088 100644
--- a/fincept-terminal-desktop/src/components/tabs/GeopoliticsHDXPanel.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/geopolitics-hdx/GeopoliticsHDXPanel.tsx
@@ -9,7 +9,7 @@ import {
HDXConflictResult,
HDXQueries
} from '@/services/data-sources/hdxService';
-import GeopoliticsRelationshipMap from './GeopoliticsRelationshipMap';
+import GeopoliticsRelationshipMap from '@/components/tabs/geopolitics-relationship-map';
interface HDXPanelProps {
selectedRegion?: string;
diff --git a/fincept-terminal-desktop/src/components/tabs/geopolitics-hdx/index.ts b/fincept-terminal-desktop/src/components/tabs/geopolitics-hdx/index.ts
new file mode 100644
index 000000000..fa9633a2d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/geopolitics-hdx/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./GeopoliticsHDXPanel";
+export { default as GeopoliticsHDXPanel } from "./GeopoliticsHDXPanel";
diff --git a/fincept-terminal-desktop/src/components/tabs/GeopoliticsRelationshipMap.tsx b/fincept-terminal-desktop/src/components/tabs/geopolitics-relationship-map/GeopoliticsRelationshipMap.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/GeopoliticsRelationshipMap.tsx
rename to fincept-terminal-desktop/src/components/tabs/geopolitics-relationship-map/GeopoliticsRelationshipMap.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/geopolitics-relationship-map/index.ts b/fincept-terminal-desktop/src/components/tabs/geopolitics-relationship-map/index.ts
new file mode 100644
index 000000000..1e54e44ee
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/geopolitics-relationship-map/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./GeopoliticsRelationshipMap";
+export { default as GeopoliticsRelationshipMap } from "./GeopoliticsRelationshipMap";
diff --git a/fincept-terminal-desktop/src/components/tabs/GeopoliticsTab.tsx b/fincept-terminal-desktop/src/components/tabs/geopolitics/GeopoliticsTab.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/GeopoliticsTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/geopolitics/GeopoliticsTab.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/geopolitics/index.ts b/fincept-terminal-desktop/src/components/tabs/geopolitics/index.ts
new file mode 100644
index 000000000..9185839e9
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/geopolitics/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./GeopoliticsTab";
+export { default as GeopoliticsTab } from "./GeopoliticsTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/LoginAuditDashboard.tsx b/fincept-terminal-desktop/src/components/tabs/login-audit/LoginAuditDashboard.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/LoginAuditDashboard.tsx
rename to fincept-terminal-desktop/src/components/tabs/login-audit/LoginAuditDashboard.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/login-audit/index.ts b/fincept-terminal-desktop/src/components/tabs/login-audit/index.ts
new file mode 100644
index 000000000..22a584f67
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/login-audit/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./LoginAuditDashboard";
+export { default as LoginAuditDashboard } from "./LoginAuditDashboard";
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTab.tsx b/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTab.tsx
new file mode 100644
index 000000000..ba1460240
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTab.tsx
@@ -0,0 +1,135 @@
+// Maritime Tab - Main Component
+// A comprehensive maritime intelligence dashboard with 3D globe visualization
+
+import React, { useRef, useCallback } from 'react';
+import { useAuth } from '@/contexts/AuthContext';
+import { TabFooter } from '@/components/common/TabFooter';
+
+// Local imports
+import { Header, LeftPanel, RightPanel, GlobeMap } from './components';
+import { useMaritimeData, useMapControls } from './hooks';
+import { TRADE_ROUTES, PRESET_LOCATIONS } from './constants';
+
+// Styles
+const scrollbarStyles = `
+ *::-webkit-scrollbar { width: 6px; height: 6px; }
+ *::-webkit-scrollbar-track { background: #0a0a0a; }
+ *::-webkit-scrollbar-thumb { background: #1a1a1a; border-radius: 3px; }
+ *::-webkit-scrollbar-thumb:hover { background: #2a2a2a; }
+`;
+
+export default function MaritimeTab() {
+ const { session } = useAuth();
+ const apiKey = session?.api_key || null;
+ const mapRef = useRef<HTMLIFrameElement>(null);
+
+ // Custom hooks for data and controls
+ const mapControls = useMapControls({ mapRef });
+
+ const handleVesselsUpdate = useCallback((vessels: any[]) => {
+ mapControls.updateRealVessels(vessels);
+ }, [mapControls]);
+
+ const maritimeData = useMaritimeData({
+ apiKey,
+ onVesselsUpdate: handleVesselsUpdate
+ });
+
+ // Handle vessel search result - zoom to location
+ const handleSearchVessel = useCallback(async () => {
+ await maritimeData.searchVesselByImo();
+ if (maritimeData.searchResult) {
+ const lat = parseFloat(maritimeData.searchResult.last_pos_latitude);
+ const lng = parseFloat(maritimeData.searchResult.last_pos_longitude);
+ mapControls.zoomToVessel(lat, lng);
+ }
+ }, [maritimeData, mapControls]);
+
+ // Handle map mode toggle
+ const handleToggleMapMode = useCallback(() => {
+ mapControls.toggleMapMode(maritimeData.realVessels);
+ }, [mapControls, maritimeData.realVessels]);
+
+ return (
+ <div style={{
+ width: '100%',
+ height: '100%',
+ display: 'flex',
+ flexDirection: 'column',
+ backgroundColor: '#000'
+ }}>
+ <style>{scrollbarStyles}</style>
+
+ {/* Header */}
+ <Header
+ intelligence={maritimeData.intelligence}
+ mapMode={mapControls.mapMode}
+ isRotating={mapControls.isRotating}
+ onToggleMapMode={handleToggleMapMode}
+ onToggleRotation={mapControls.toggleRotation}
+ />
+
+ {/* Main Layout */}
+ <div style={{ flex: 1, display: 'flex', minHeight: 0, overflow: 'hidden' }}>
+ {/* Left Panel - Intelligence & Controls */}
+ <LeftPanel
+ intelligence={maritimeData.intelligence}
+ realVesselsCount={maritimeData.realVessels.length}
+ isLoadingVessels={maritimeData.isLoadingVessels}
+ vesselLoadError={maritimeData.vesselLoadError}
+ tradeRoutes={TRADE_ROUTES}
+ selectedRoute={mapControls.selectedRoute}
+ onSelectRoute={mapControls.setSelectedRoute}
+ showRoutes={mapControls.showRoutes}
+ showShips={mapControls.showShips}
+ showPlanes={mapControls.showPlanes}
+ showSatellites={mapControls.showSatellites}
+ onToggleRoutes={mapControls.toggleRoutes}
+ onToggleShips={mapControls.toggleShips}
+ onTogglePlanes={mapControls.togglePlanes}
+ onToggleSatellites={mapControls.toggleSatellites}
+ onClearMarkers={mapControls.clearMarkers}
+ />
+
+ {/* Center - Globe/Map */}
+ <GlobeMap ref={mapRef} />
+
+ {/* Right Panel - Search & Markers */}
+ <RightPanel
+ selectedRoute={mapControls.selectedRoute}
+ searchImo={maritimeData.searchImo}
+ onSearchImoChange={maritimeData.setSearchImo}
+ onSearchVessel={handleSearchVessel}
+ searchingVessel={maritimeData.searchingVessel}
+ searchResult={maritimeData.searchResult}
+ searchError={maritimeData.searchError}
+ markerType={mapControls.markerType}
+ onMarkerTypeChange={mapControls.setMarkerType}
+ presetLocations={PRESET_LOCATIONS}
+ onAddPreset={mapControls.addPreset}
+ markers={mapControls.markers}
+ tradeRoutesCount={TRADE_ROUTES.length}
+ />
+ </div>
+
+ {/* Footer */}
+ <TabFooter
+ tabName="MARITIME INTELLIGENCE"
+ leftInfo={[
+ { label: 'AIS Feed: ACTIVE', color: '#0ff' },
+ { label: 'Satellite Link: NOMINAL', color: '#0ff' },
+ { label: 'Data Latency: 2.3ms', color: '#0ff' },
+ ]}
+ statusInfo={
+ <>
+ <span style={{ color: '#888' }}>Powered by Globe.GL 3D Visualization</span>
+ <span style={{ color: '#888', marginLeft: '8px' }}>|</span>
+ <span style={{ color: '#ffd700', marginLeft: '8px' }}>CLEARANCE: TOP SECRET // SCI</span>
+ </>
+ }
+ backgroundColor="#0a0a0a"
+ borderColor="#00ff00"
+ />
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/MaritimeTabDeck.backup.tsx b/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTabDeck.backup.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/MaritimeTabDeck.backup.tsx
rename to fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTabDeck.backup.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/MaritimeTabDeck.tsx b/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTabDeck.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/MaritimeTabDeck.tsx
rename to fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTabDeck.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/MaritimeTabKepler.tsx b/fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTabKepler.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/MaritimeTabKepler.tsx
rename to fincept-terminal-desktop/src/components/tabs/maritime/MaritimeTabKepler.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/components/GlobeMap.tsx b/fincept-terminal-desktop/src/components/tabs/maritime/components/GlobeMap.tsx
new file mode 100644
index 000000000..d6838e442
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/components/GlobeMap.tsx
@@ -0,0 +1,48 @@
+// Maritime Tab Globe/Map Component
+
+import React, { forwardRef } from 'react';
+import { generateMapHTML } from '../utils';
+
+interface GlobeMapProps {
+ // The iframe ref is passed from parent to allow control communication
+}
+
+export const GlobeMap = forwardRef<HTMLIFrameElement | null, GlobeMapProps>((_, ref) => {
+ const mapHTML = generateMapHTML();
+
+ return (
+ <div style={{ flex: 1, position: 'relative', minWidth: 0, overflow: 'hidden' }}>
+ <iframe
+ ref={ref}
+ srcDoc={mapHTML}
+ style={{
+ width: '100%',
+ height: '100%',
+ border: 'none',
+ background: '#000'
+ }}
+ />
+ {/* Map Overlay - Coordinates Display */}
+ <div style={{
+ position: 'absolute',
+ bottom: '16px',
+ left: '16px',
+ background: 'rgba(0, 0, 0, 0.9)',
+ border: '1px solid #0ff',
+ padding: '8px 12px',
+ color: '#0ff',
+ fontSize: '9px',
+ fontFamily: 'Consolas, monospace'
+ }}>
+ <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>HYBRID 3D/2D SYSTEM ACTIVE</div>
+ <div>CENTER: 20.0000° N, 75.0000° E</div>
+ <div>MODE: Globe.GL 3D → Auto-switches → Leaflet 2D</div>
+ <div style={{ marginTop: '4px', color: '#ffd700' }}>
+ 🔍 ZOOM: Deep zoom auto-switches to street-level map!
+ </div>
+ </div>
+ </div>
+ );
+});
+
+GlobeMap.displayName = 'GlobeMap';
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/components/Header.tsx b/fincept-terminal-desktop/src/components/tabs/maritime/components/Header.tsx
new file mode 100644
index 000000000..0b057736f
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/components/Header.tsx
@@ -0,0 +1,95 @@
+// Maritime Tab Header Component
+
+import React from 'react';
+import type { IntelligenceData, MapMode } from '../types';
+
+interface HeaderProps {
+ intelligence: IntelligenceData;
+ mapMode: MapMode;
+ isRotating: boolean;
+ onToggleMapMode: () => void;
+ onToggleRotation: () => void;
+}
+
+export const Header: React.FC<HeaderProps> = ({
+ intelligence,
+ mapMode,
+ isRotating,
+ onToggleMapMode,
+ onToggleRotation
+}) => {
+ const getThreatColor = (level: IntelligenceData['threat_level']) => {
+ switch (level) {
+ case 'critical': return '#ff0000';
+ case 'high': return '#ff8c00';
+ case 'medium': return '#ffd700';
+ default: return '#00ff00';
+ }
+ };
+
+ return (
+ <div style={{
+ borderBottom: '2px solid #00ff00',
+ padding: '8px 16px',
+ background: 'linear-gradient(180deg, #0a0a0a 0%, #000 100%)',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
+ <span style={{ color: '#00ff00', fontSize: '14px', fontWeight: 'bold', letterSpacing: '2px' }}>
+ ⚓ FINCEPT MARITIME INTELLIGENCE
+ </span>
+ <div style={{ width: '1px', height: '16px', background: '#00ff00' }} />
+ <span style={{ color: '#0ff', fontSize: '10px' }}>CLASSIFIED // TRADE ROUTE ANALYSIS</span>
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <button
+ onClick={onToggleMapMode}
+ style={{
+ background: mapMode === '2D' ? '#ffd700' : '#0a0a0a',
+ color: mapMode === '2D' ? '#000' : '#ffd700',
+ border: '1px solid #ffd700',
+ padding: '4px 12px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ fontWeight: 'bold',
+ fontFamily: 'Consolas, monospace',
+ transition: 'all 0.2s'
+ }}
+ >
+ {mapMode === '3D' ? '🌍 3D GLOBE' : '🗺️ 2D MAP'}
+ </button>
+ {mapMode === '3D' && (
+ <button
+ onClick={onToggleRotation}
+ style={{
+ background: isRotating ? '#0a0a0a' : '#1a1a1a',
+ color: isRotating ? '#00ff00' : '#888',
+ border: `1px solid ${isRotating ? '#00ff00' : '#444'}`,
+ padding: '4px 10px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ fontWeight: 'bold',
+ fontFamily: 'Consolas, monospace',
+ transition: 'all 0.2s'
+ }}
+ >
+ {isRotating ? '● ROTATING' : '○ PAUSED'}
+ </button>
+ )}
+ <span style={{
+ color: getThreatColor(intelligence.threat_level),
+ fontSize: '10px',
+ fontWeight: 'bold'
+ }}>
+ THREAT: {intelligence.threat_level.toUpperCase()}
+ </span>
+ <span style={{ color: '#888', fontSize: '9px' }}>
+ {new Date(intelligence.timestamp).toLocaleString()}
+ </span>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/components/LeftPanel.tsx b/fincept-terminal-desktop/src/components/tabs/maritime/components/LeftPanel.tsx
new file mode 100644
index 000000000..32a526786
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/components/LeftPanel.tsx
@@ -0,0 +1,245 @@
+// Maritime Tab Left Panel - Intelligence Stats, Trade Routes, Map Controls
+
+import React from 'react';
+import type { IntelligenceData, TradeRoute } from '../types';
+
+interface LeftPanelProps {
+ intelligence: IntelligenceData;
+ realVesselsCount: number;
+ isLoadingVessels: boolean;
+ vesselLoadError: string | null;
+ tradeRoutes: TradeRoute[];
+ selectedRoute: TradeRoute | null;
+ onSelectRoute: (route: TradeRoute | null) => void;
+ showRoutes: boolean;
+ showShips: boolean;
+ showPlanes: boolean;
+ showSatellites: boolean;
+ onToggleRoutes: () => void;
+ onToggleShips: () => void;
+ onTogglePlanes: () => void;
+ onToggleSatellites: () => void;
+ onClearMarkers: () => void;
+}
+
+export const LeftPanel: React.FC<LeftPanelProps> = ({
+ intelligence,
+ realVesselsCount,
+ isLoadingVessels,
+ vesselLoadError,
+ tradeRoutes,
+ selectedRoute,
+ onSelectRoute,
+ showRoutes,
+ showShips,
+ showPlanes,
+ showSatellites,
+ onToggleRoutes,
+ onToggleShips,
+ onTogglePlanes,
+ onToggleSatellites,
+ onClearMarkers
+}) => {
+ return (
+ <div style={{
+ width: '280px',
+ borderRight: '1px solid #1a1a1a',
+ display: 'flex',
+ flexDirection: 'column',
+ background: '#000',
+ flexShrink: 0
+ }}>
+ {/* Intelligence Stats */}
+ <div style={{ padding: '12px', borderBottom: '1px solid #1a1a1a' }}>
+ <div style={{ color: '#00ff00', fontSize: '10px', fontWeight: 'bold', marginBottom: '8px', letterSpacing: '1px' }}>
+ GLOBAL INTEL
+ </div>
+
+ {isLoadingVessels && (
+ <div style={{
+ background: 'rgba(0, 255, 255, 0.1)',
+ border: '1px solid #0ff',
+ padding: '6px',
+ fontSize: '8px',
+ color: '#0ff',
+ marginBottom: '8px',
+ textAlign: 'center'
+ }}>
+ ⏳ LOADING VESSELS...
+ </div>
+ )}
+
+ {vesselLoadError && (
+ <div style={{
+ background: 'rgba(255, 0, 0, 0.1)',
+ border: '1px solid #ff0000',
+ padding: '6px',
+ fontSize: '8px',
+ color: '#ff0000',
+ marginBottom: '8px'
+ }}>
+ ⚠ {vesselLoadError}
+ </div>
+ )}
+
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
+ <StatBox label="TOTAL VESSELS" value={intelligence.active_vessels} color="#0ff" />
+ <StatBox label="DISPLAYED" value={realVesselsCount} color="#00ff00" />
+ <StatBox label="ROUTES" value={intelligence.monitored_routes} color="#0ff" />
+ <StatBox label="AIRCRAFT" value={342} color="rgba(255, 200, 100, 0.95)" />
+ <StatBox label="SATELLITES" value={13} color="rgba(138, 43, 226, 0.9)" />
+ <div style={{
+ background: '#0a0a0a',
+ border: '1px solid #1a1a1a',
+ padding: '8px',
+ gridColumn: 'span 2'
+ }}>
+ <div style={{ color: '#888', fontSize: '8px' }}>TRADE VOLUME (24H)</div>
+ <div style={{ color: '#00ff00', fontSize: '16px', fontWeight: 'bold' }}>
+ {intelligence.trade_volume}
+ </div>
+ </div>
+ <StatBox label="MAJOR PORTS" value={6} color="#ffa500" fontSize="14px" />
+ <StatBox label="AIRPORTS" value={8} color="#9d4edd" fontSize="14px" />
+ </div>
+ </div>
+
+ {/* Trade Routes List */}
+ <div style={{ flex: 1, overflowY: 'auto', padding: '12px', minHeight: 0 }}>
+ <div style={{ color: '#00ff00', fontSize: '10px', fontWeight: 'bold', marginBottom: '8px', letterSpacing: '1px' }}>
+ TRADE CORRIDORS
+ </div>
+ {tradeRoutes.map((route, idx) => (
+ <RouteItem
+ key={idx}
+ route={route}
+ isSelected={selectedRoute?.name === route.name}
+ onClick={() => onSelectRoute(route)}
+ />
+ ))}
+ </div>
+
+ {/* Map Controls */}
+ <div style={{ padding: '12px', borderTop: '1px solid #1a1a1a' }}>
+ <div style={{ color: '#00ff00', fontSize: '10px', fontWeight: 'bold', marginBottom: '8px', letterSpacing: '1px' }}>
+ MAP CONTROLS
+ </div>
+ <div style={{ display: 'flex', gap: '6px', marginBottom: '6px' }}>
+ <ToggleButton label="ROUTES" active={showRoutes} onClick={onToggleRoutes} color="#0ff" />
+ <ToggleButton label="VESSELS" active={showShips} onClick={onToggleShips} color="#0ff" />
+ </div>
+ <div style={{ display: 'flex', gap: '6px', marginBottom: '6px' }}>
+ <ToggleButton label="AIRCRAFT" active={showPlanes} onClick={onTogglePlanes} color="rgba(255, 200, 100, 0.9)" />
+ <ToggleButton label="SATELLITES" active={showSatellites} onClick={onToggleSatellites} color="rgba(138, 43, 226, 0.9)" textColor={showSatellites ? '#fff' : undefined} />
+ </div>
+ <button
+ onClick={onClearMarkers}
+ style={{
+ width: '100%',
+ background: '#0a0a0a',
+ color: '#ff0000',
+ border: '1px solid #ff0000',
+ padding: '6px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ fontWeight: 'bold'
+ }}
+ >
+ CLEAR ALL MARKERS
+ </button>
+ </div>
+ </div>
+ );
+};
+
+// Sub-components
+interface StatBoxProps {
+ label: string;
+ value: number | string;
+ color: string;
+ fontSize?: string;
+}
+
+const StatBox: React.FC<StatBoxProps> = ({ label, value, color, fontSize = '16px' }) => (
+ <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '8px' }}>
+ <div style={{ color: '#888', fontSize: '8px' }}>{label}</div>
+ <div style={{ color, fontSize, fontWeight: 'bold' }}>{value}</div>
+ </div>
+);
+
+interface RouteItemProps {
+ route: TradeRoute;
+ isSelected: boolean;
+ onClick: () => void;
+}
+
+const RouteItem: React.FC<RouteItemProps> = ({ route, isSelected, onClick }) => {
+ const getStatusColor = (status: TradeRoute['status']) => {
+ switch (status) {
+ case 'critical': return '#ff0000';
+ case 'delayed': return '#ffd700';
+ default: return '#00ff00';
+ }
+ };
+
+ const statusColor = getStatusColor(route.status);
+
+ return (
+ <div
+ onClick={onClick}
+ style={{
+ background: isSelected ? '#1a1a1a' : '#0a0a0a',
+ border: `1px solid ${route.status === 'critical' ? '#ff0000' : route.status === 'delayed' ? '#ffd700' : '#1a1a1a'}`,
+ padding: '8px',
+ marginBottom: '6px',
+ cursor: 'pointer',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => (e.currentTarget.style.background = '#1a1a1a')}
+ onMouseLeave={(e) => (e.currentTarget.style.background = isSelected ? '#1a1a1a' : '#0a0a0a')}
+ >
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
+ <span style={{ color: '#0ff', fontSize: '9px', fontWeight: 'bold' }}>{route.name}</span>
+ <span style={{
+ color: statusColor,
+ fontSize: '7px',
+ padding: '2px 4px',
+ background: '#000',
+ border: `1px solid ${statusColor}`
+ }}>
+ {route.status.toUpperCase()}
+ </span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: '#888', fontSize: '8px' }}>Value: {route.value}</span>
+ <span style={{ color: '#888', fontSize: '8px' }}>Ships: {route.vessels}</span>
+ </div>
+ </div>
+ );
+};
+
+interface ToggleButtonProps {
+ label: string;
+ active: boolean;
+ onClick: () => void;
+ color: string;
+ textColor?: string;
+}
+
+const ToggleButton: React.FC<ToggleButtonProps> = ({ label, active, onClick, color, textColor }) => (
+ <button
+ onClick={onClick}
+ style={{
+ flex: 1,
+ background: active ? color : '#0a0a0a',
+ color: active ? (textColor || '#000') : color,
+ border: `1px solid ${color}`,
+ padding: '6px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ fontWeight: 'bold'
+ }}
+ >
+ {label}
+ </button>
+);
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/components/RightPanel.tsx b/fincept-terminal-desktop/src/components/tabs/maritime/components/RightPanel.tsx
new file mode 100644
index 000000000..e415345b2
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/components/RightPanel.tsx
@@ -0,0 +1,373 @@
+// Maritime Tab Right Panel - Route Details, Vessel Search, Markers
+
+import React from 'react';
+import type { VesselData } from '@/services/maritime/marineApi';
+import type { TradeRoute, MarkerData, PresetLocation } from '../types';
+
+interface RightPanelProps {
+ selectedRoute: TradeRoute | null;
+ // Vessel Search
+ searchImo: string;
+ onSearchImoChange: (imo: string) => void;
+ onSearchVessel: () => void;
+ searchingVessel: boolean;
+ searchResult: VesselData | null;
+ searchError: string | null;
+ // Markers
+ markerType: MarkerData['type'];
+ onMarkerTypeChange: (type: MarkerData['type']) => void;
+ presetLocations: PresetLocation[];
+ onAddPreset: (preset: PresetLocation) => void;
+ markers: MarkerData[];
+ tradeRoutesCount: number;
+}
+
+export const RightPanel: React.FC<RightPanelProps> = ({
+ selectedRoute,
+ searchImo,
+ onSearchImoChange,
+ onSearchVessel,
+ searchingVessel,
+ searchResult,
+ searchError,
+ markerType,
+ onMarkerTypeChange,
+ presetLocations,
+ onAddPreset,
+ markers,
+ tradeRoutesCount
+}) => {
+ return (
+ <div style={{
+ width: '280px',
+ borderLeft: '1px solid #1a1a1a',
+ display: 'flex',
+ flexDirection: 'column',
+ background: '#000',
+ flexShrink: 0
+ }}>
+ {/* Selected Route Details */}
+ {selectedRoute && (
+ <RouteDetails route={selectedRoute} />
+ )}
+
+ {/* Vessel Search by IMO */}
+ <VesselSearch
+ searchImo={searchImo}
+ onSearchImoChange={onSearchImoChange}
+ onSearch={onSearchVessel}
+ searching={searchingVessel}
+ result={searchResult}
+ error={searchError}
+ />
+
+ {/* Add Markers */}
+ <MarkerControls
+ markerType={markerType}
+ onMarkerTypeChange={onMarkerTypeChange}
+ presetLocations={presetLocations}
+ onAddPreset={onAddPreset}
+ />
+
+ {/* Markers List */}
+ <MarkersList markers={markers} />
+
+ {/* System Status */}
+ <SystemStatus tradeRoutesCount={tradeRoutesCount} />
+ </div>
+ );
+};
+
+// Sub-components
+interface RouteDetailsProps {
+ route: TradeRoute;
+}
+
+const RouteDetails: React.FC<RouteDetailsProps> = ({ route }) => {
+ const getStatusColor = (status: TradeRoute['status']) => {
+ switch (status) {
+ case 'critical': return '#ff0000';
+ case 'delayed': return '#ffd700';
+ default: return '#00ff00';
+ }
+ };
+
+ return (
+ <div style={{ padding: '12px', borderBottom: '1px solid #1a1a1a' }}>
+ <div style={{ color: '#00ff00', fontSize: '10px', fontWeight: 'bold', marginBottom: '8px', letterSpacing: '1px' }}>
+ ROUTE DETAILS
+ </div>
+ <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '10px' }}>
+ <div style={{ color: '#0ff', fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>
+ {route.name}
+ </div>
+ <div style={{ display: 'grid', gap: '6px', fontSize: '9px' }}>
+ <DetailRow label="Value:" value={route.value} />
+ <DetailRow
+ label="Status:"
+ value={route.status.toUpperCase()}
+ valueColor={getStatusColor(route.status)}
+ />
+ <DetailRow label="Active Vessels:" value={route.vessels.toString()} />
+ <DetailRow label="Waypoints:" value={route.coordinates.length.toString()} />
+ </div>
+ </div>
+ </div>
+ );
+};
+
+interface DetailRowProps {
+ label: string;
+ value: string;
+ valueColor?: string;
+}
+
+const DetailRow: React.FC<DetailRowProps> = ({ label, value, valueColor = '#fff' }) => (
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: '#888' }}>{label}</span>
+ <span style={{ color: valueColor }}>{value}</span>
+ </div>
+);
+
+interface VesselSearchProps {
+ searchImo: string;
+ onSearchImoChange: (imo: string) => void;
+ onSearch: () => void;
+ searching: boolean;
+ result: VesselData | null;
+ error: string | null;
+}
+
+const VesselSearch: React.FC<VesselSearchProps> = ({
+ searchImo,
+ onSearchImoChange,
+ onSearch,
+ searching,
+ result,
+ error
+}) => (
+ <div style={{ padding: '12px', borderBottom: '1px solid #1a1a1a' }}>
+ <div style={{ color: '#00ff00', fontSize: '10px', fontWeight: 'bold', marginBottom: '8px', letterSpacing: '1px' }}>
+ VESSEL SEARCH
+ </div>
+
+ <div style={{ marginBottom: '8px' }}>
+ <div style={{ color: '#888', fontSize: '8px', marginBottom: '4px' }}>IMO NUMBER</div>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ <input
+ type="text"
+ value={searchImo}
+ onChange={(e) => onSearchImoChange(e.target.value)}
+ onKeyPress={(e) => e.key === 'Enter' && onSearch()}
+ placeholder="e.g., 8020604"
+ style={{
+ flex: 1,
+ background: '#0a0a0a',
+ color: '#0ff',
+ border: '1px solid #1a1a1a',
+ padding: '6px',
+ fontSize: '9px',
+ outline: 'none'
+ }}
+ />
+ <button
+ onClick={onSearch}
+ disabled={searching}
+ style={{
+ background: searching ? '#1a1a1a' : '#0ff',
+ color: searching ? '#888' : '#000',
+ border: '1px solid #0ff',
+ padding: '6px 12px',
+ fontSize: '9px',
+ cursor: searching ? 'not-allowed' : 'pointer',
+ fontWeight: 'bold'
+ }}
+ >
+ {searching ? 'SEARCHING...' : 'TRACK'}
+ </button>
+ </div>
+ </div>
+
+ {error && (
+ <div style={{
+ background: 'rgba(255, 0, 0, 0.1)',
+ border: '1px solid #ff0000',
+ padding: '6px',
+ fontSize: '8px',
+ color: '#ff0000',
+ marginBottom: '8px'
+ }}>
+ ⚠ {error}
+ </div>
+ )}
+
+ {result && (
+ <div style={{
+ background: '#0a0a0a',
+ border: '1px solid #0ff',
+ padding: '8px',
+ fontSize: '9px',
+ marginBottom: '8px'
+ }}>
+ <div style={{ color: '#0ff', fontWeight: 'bold', marginBottom: '6px' }}>{result.name}</div>
+ <div style={{ display: 'grid', gap: '4px', color: '#fff' }}>
+ <DetailRow label="IMO:" value={result.imo} />
+ <DetailRow
+ label="Position:"
+ value={`${parseFloat(result.last_pos_latitude).toFixed(4)}°, ${parseFloat(result.last_pos_longitude).toFixed(4)}°`}
+ />
+ <DetailRow label="Speed:" value={`${result.last_pos_speed} kts`} />
+ {result.route_from_port_name && (
+ <DetailRow label="From:" value={result.route_from_port_name} />
+ )}
+ {result.route_to_port_name && (
+ <DetailRow label="To:" value={result.route_to_port_name} />
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+);
+
+interface MarkerControlsProps {
+ markerType: MarkerData['type'];
+ onMarkerTypeChange: (type: MarkerData['type']) => void;
+ presetLocations: PresetLocation[];
+ onAddPreset: (preset: PresetLocation) => void;
+}
+
+const MarkerControls: React.FC<MarkerControlsProps> = ({
+ markerType,
+ onMarkerTypeChange,
+ presetLocations,
+ onAddPreset
+}) => (
+ <div style={{ padding: '12px', borderBottom: '1px solid #1a1a1a' }}>
+ <div style={{ color: '#00ff00', fontSize: '10px', fontWeight: 'bold', marginBottom: '8px', letterSpacing: '1px' }}>
+ ADD TARGET
+ </div>
+
+ <div style={{ marginBottom: '8px' }}>
+ <div style={{ color: '#888', fontSize: '8px', marginBottom: '4px' }}>MARKER TYPE</div>
+ <select
+ value={markerType}
+ onChange={(e) => onMarkerTypeChange(e.target.value as MarkerData['type'])}
+ style={{
+ width: '100%',
+ background: '#0a0a0a',
+ color: '#0ff',
+ border: '1px solid #1a1a1a',
+ padding: '6px',
+ fontSize: '9px'
+ }}
+ >
+ <option value="Ship">🚢 Ship</option>
+ <option value="Port">⚓ Port</option>
+ <option value="Industry">🏭 Industry</option>
+ <option value="Bank">🏦 Bank</option>
+ <option value="Exchange">💱 Exchange</option>
+ </select>
+ </div>
+
+ <div style={{ color: '#888', fontSize: '8px', marginBottom: '8px' }}>QUICK ADD PRESETS</div>
+ <div style={{ display: 'grid', gap: '4px' }}>
+ {presetLocations.map((preset, idx) => (
+ <button
+ key={idx}
+ onClick={() => onAddPreset(preset)}
+ style={{
+ background: '#0a0a0a',
+ color: '#fff',
+ border: '1px solid #1a1a1a',
+ padding: '6px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ textAlign: 'left'
+ }}
+ onMouseEnter={(e) => (e.currentTarget.style.borderColor = '#0ff')}
+ onMouseLeave={(e) => (e.currentTarget.style.borderColor = '#1a1a1a')}
+ >
+ {preset.name}
+ </button>
+ ))}
+ </div>
+ </div>
+);
+
+interface MarkersListProps {
+ markers: MarkerData[];
+}
+
+const MarkersList: React.FC<MarkersListProps> = ({ markers }) => (
+ <div style={{ flex: 1, overflowY: 'auto', padding: '12px', minHeight: 0 }}>
+ <div style={{ color: '#00ff00', fontSize: '10px', fontWeight: 'bold', marginBottom: '8px', letterSpacing: '1px' }}>
+ TRACKED TARGETS ({markers.length})
+ </div>
+ {markers.length === 0 ? (
+ <div style={{ color: '#444', fontSize: '9px', fontStyle: 'italic', padding: '8px' }}>
+ No targets marked
+ </div>
+ ) : (
+ markers.map((marker, idx) => (
+ <div
+ key={idx}
+ style={{
+ background: '#0a0a0a',
+ border: '1px solid #1a1a1a',
+ padding: '8px',
+ marginBottom: '6px',
+ fontSize: '9px'
+ }}
+ >
+ <div style={{ color: '#0ff', fontWeight: 'bold', marginBottom: '4px' }}>{marker.title}</div>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: '#888' }}>Type: {marker.type}</span>
+ <span style={{ color: '#666', fontSize: '8px' }}>
+ {marker.lat.toFixed(2)}°, {marker.lng.toFixed(2)}°
+ </span>
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+);
+
+interface SystemStatusProps {
+ tradeRoutesCount: number;
+}
+
+const SystemStatus: React.FC<SystemStatusProps> = ({ tradeRoutesCount }) => (
+ <div style={{ padding: '12px', borderTop: '1px solid #1a1a1a', background: '#0a0a0a' }}>
+ <div style={{ color: '#00ff00', fontSize: '9px', fontWeight: 'bold', marginBottom: '6px' }}>
+ SYSTEM STATUS
+ </div>
+ <div style={{ fontSize: '8px', color: '#888', lineHeight: '1.4' }}>
+ <StatusLine color="#0ff" text="3D Globe: ACTIVE" />
+ <StatusLine color="#0ff" text="Satellite imagery: ONLINE" />
+ <StatusLine color="#0ff" text="AIS transponders: STREAMING" />
+ <StatusLine color="rgba(138, 43, 226, 0.9)" text="Orbital tracking: 13 SATs" />
+ <StatusLine color="rgba(255, 200, 100, 0.95)" text="Air traffic: MONITORED" />
+ <StatusLine color="#0ff" text={`Maritime routes: ${tradeRoutesCount} corridors`} />
+ <div style={{
+ marginTop: '8px',
+ padding: '6px',
+ background: '#000',
+ border: '1px solid #1a1a1a',
+ color: '#ffd700'
+ }}>
+ [WARN] CLASSIFIED: For authorized personnel only
+ </div>
+ </div>
+ </div>
+);
+
+interface StatusLineProps {
+ color: string;
+ text: string;
+}
+
+const StatusLine: React.FC<StatusLineProps> = ({ color, text }) => (
+ <div style={{ marginBottom: '4px' }}>
+ <span style={{ color }}>●</span> {text}
+ </div>
+);
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/components/index.ts b/fincept-terminal-desktop/src/components/tabs/maritime/components/index.ts
new file mode 100644
index 000000000..b3d3bc8fb
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/components/index.ts
@@ -0,0 +1,6 @@
+// Maritime components barrel export
+
+export { Header } from './Header';
+export { LeftPanel } from './LeftPanel';
+export { RightPanel } from './RightPanel';
+export { GlobeMap } from './GlobeMap';
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/constants.ts b/fincept-terminal-desktop/src/components/tabs/maritime/constants.ts
new file mode 100644
index 000000000..5a806fbe7
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/constants.ts
@@ -0,0 +1,88 @@
+// Maritime Tab Constants
+
+import type { TradeRoute, PresetLocation, OceanRoute, AirRoute } from './types';
+
+// Trade Routes for display in the sidebar
+export const TRADE_ROUTES: TradeRoute[] = [
+ { name: 'Mumbai → Rotterdam', value: '$45B', status: 'active', vessels: 23, coordinates: [[18.9388, 72.8354], [51.9553, 4.1392]] },
+ { name: 'Mumbai → Shanghai', value: '$156B', status: 'active', vessels: 89, coordinates: [[18.9388, 72.8354], [31.3548, 121.6431]] },
+ { name: 'Mumbai → Singapore', value: '$89B', status: 'active', vessels: 45, coordinates: [[18.9388, 72.8354], [1.2644, 103.8224]] },
+ { name: 'Chennai → Tokyo', value: '$67B', status: 'delayed', vessels: 34, coordinates: [[13.0827, 80.2707], [35.4437, 139.6380]] },
+ { name: 'Kolkata → Hong Kong', value: '$45B', status: 'active', vessels: 28, coordinates: [[22.5726, 88.3639], [22.2855, 114.1577]] },
+ { name: 'Mumbai → Dubai', value: '$78B', status: 'critical', vessels: 12, coordinates: [[18.9388, 72.8354], [24.9857, 55.0272]] },
+ { name: 'Mumbai → New York', value: '$123B', status: 'active', vessels: 56, coordinates: [[18.9388, 72.8354], [40.6655, -74.0781]] },
+ { name: 'Chennai → Sydney', value: '$54B', status: 'active', vessels: 31, coordinates: [[13.0827, 80.2707], [-33.9544, 151.2093]] },
+ { name: 'Cochin → Klang', value: '$34B', status: 'active', vessels: 19, coordinates: [[9.9667, 76.2667], [3.0048, 101.3975]] },
+ { name: 'Mumbai → Cape Town', value: '$28B', status: 'delayed', vessels: 8, coordinates: [[18.9388, 72.8354], [-33.9055, 18.4232]] }
+];
+
+// Preset locations for quick marker addition
+export const PRESET_LOCATIONS: PresetLocation[] = [
+ { name: 'Mumbai Port', lat: 18.9388, lng: 72.8354, type: 'Port' },
+ { name: 'Shanghai Port', lat: 31.3548, lng: 121.6431, type: 'Port' },
+ { name: 'Singapore Port', lat: 1.2644, lng: 103.8224, type: 'Port' },
+ { name: 'Hong Kong Port', lat: 22.2855, lng: 114.1577, type: 'Port' },
+ { name: 'Rotterdam Port', lat: 51.9553, lng: 4.1392, type: 'Port' },
+ { name: 'Dubai Port', lat: 24.9857, lng: 55.0272, type: 'Port' },
+];
+
+// Ocean routes for 3D globe visualization
+export const OCEAN_ROUTES: OceanRoute[] = [
+ { name: "Mumbai → Rotterdam", start: {lat: 18.9388, lng: 72.8354}, end: {lat: 51.9553, lng: 4.1392}, value: "$45B", vessels: 23, color: 'rgba(100, 180, 255, 0.6)', width: 0.8 },
+ { name: "Mumbai → Shanghai", start: {lat: 18.9388, lng: 72.8354}, end: {lat: 31.3548, lng: 121.6431}, value: "$156B", vessels: 89, color: 'rgba(120, 200, 255, 0.7)', width: 1.2 },
+ { name: "Mumbai → Singapore", start: {lat: 18.9388, lng: 72.8354}, end: {lat: 1.2644, lng: 103.8224}, value: "$89B", vessels: 45, color: 'rgba(100, 180, 255, 0.65)', width: 1.0 },
+ { name: "Chennai → Tokyo", start: {lat: 13.0827, lng: 80.2707}, end: {lat: 35.4437, lng: 139.6380}, value: "$67B", vessels: 34, color: 'rgba(150, 220, 255, 0.6)', width: 0.9 },
+ { name: "Kolkata → Hong Kong", start: {lat: 22.5726, lng: 88.3639}, end: {lat: 22.2855, lng: 114.1577}, value: "$45B", vessels: 28, color: 'rgba(100, 180, 255, 0.55)', width: 0.8 },
+ { name: "Mumbai → Dubai", start: {lat: 18.9388, lng: 72.8354}, end: {lat: 24.9857, lng: 55.0272}, value: "$78B", vessels: 12, color: 'rgba(255, 160, 100, 0.6)', width: 0.9 },
+ { name: "Mumbai → New York", start: {lat: 18.9388, lng: 72.8354}, end: {lat: 40.6655, lng: -74.0781}, value: "$123B", vessels: 56, color: 'rgba(120, 200, 255, 0.75)', width: 1.2 },
+ { name: "Chennai → Sydney", start: {lat: 13.0827, lng: 80.2707}, end: {lat: -33.9544, lng: 151.2093}, value: "$54B", vessels: 31, color: 'rgba(130, 190, 255, 0.6)', width: 0.9 },
+ { name: "Cochin → Klang", start: {lat: 9.9667, lng: 76.2667}, end: {lat: 3.0048, lng: 101.3975}, value: "$34B", vessels: 19, color: 'rgba(180, 200, 255, 0.5)', width: 0.7 },
+ { name: "Mumbai → Cape Town", start: {lat: 18.9388, lng: 72.8354}, end: {lat: -33.9055, lng: 18.4232}, value: "$28B", vessels: 8, color: 'rgba(160, 180, 255, 0.5)', width: 0.7 }
+];
+
+// Air routes for 3D globe visualization
+export const AIR_ROUTES: AirRoute[] = [
+ { name: "Mumbai → London", start: {lat: 19.0896, lng: 72.8656}, end: {lat: 51.4700, lng: -0.4543}, value: "$12B", flights: 45, color: 'rgba(255, 200, 100, 0.7)', width: 0.6 },
+ { name: "Delhi → New York", start: {lat: 28.5562, lng: 77.1000}, end: {lat: 40.6413, lng: -73.7781}, value: "$18B", flights: 67, color: 'rgba(255, 200, 100, 0.75)', width: 0.8 },
+ { name: "Mumbai → Dubai", start: {lat: 19.0896, lng: 72.8656}, end: {lat: 25.2532, lng: 55.3657}, value: "$22B", flights: 123, color: 'rgba(255, 200, 100, 0.8)', width: 0.9 },
+ { name: "Bangalore → Singapore", start: {lat: 13.1979, lng: 77.7063}, end: {lat: 1.3644, lng: 103.9915}, value: "$8B", flights: 89, color: 'rgba(255, 200, 100, 0.65)', width: 0.6 },
+ { name: "Delhi → Frankfurt", start: {lat: 28.5562, lng: 77.1000}, end: {lat: 50.0379, lng: 8.5622}, value: "$15B", flights: 56, color: 'rgba(255, 200, 100, 0.7)', width: 0.7 },
+ { name: "Mumbai → Hong Kong", start: {lat: 19.0896, lng: 72.8656}, end: {lat: 22.3080, lng: 113.9185}, value: "$11B", flights: 78, color: 'rgba(255, 200, 100, 0.65)', width: 0.6 },
+ { name: "Chennai → Tokyo", start: {lat: 12.9941, lng: 80.1709}, end: {lat: 35.7720, lng: 140.3929}, value: "$9B", flights: 34, color: 'rgba(255, 200, 100, 0.6)', width: 0.6 },
+ { name: "Delhi → Sydney", start: {lat: 28.5562, lng: 77.1000}, end: {lat: -33.9399, lng: 151.1753}, value: "$7B", flights: 28, color: 'rgba(255, 200, 100, 0.6)', width: 0.5 }
+];
+
+// Default intelligence data
+export const DEFAULT_INTELLIGENCE = {
+ timestamp: new Date().toISOString(),
+ threat_level: 'low' as const,
+ active_vessels: 0,
+ monitored_routes: 48,
+ trade_volume: '$847.3B'
+};
+
+// API search area (Mumbai port region)
+export const MUMBAI_SEARCH_AREA = {
+ min_lat: 18.5,
+ max_lat: 19.5,
+ min_lng: 72.0,
+ max_lng: 73.5
+};
+
+// Refresh interval for vessel data (5 minutes)
+export const VESSEL_REFRESH_INTERVAL = 300000;
+
+// Timestamp update interval (5 seconds)
+export const TIMESTAMP_UPDATE_INTERVAL = 5000;
+
+// Maximum vessels to display for performance
+export const MAX_VESSELS_DISPLAY = 500;
+
+// Marker type icons
+export const MARKER_ICONS: Record<string, string> = {
+ 'Ship': '🚢',
+ 'Port': '⚓',
+ 'Industry': '🏭',
+ 'Bank': '🏦',
+ 'Exchange': '💱'
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/maritime/hooks/index.ts
new file mode 100644
index 000000000..d4facef2c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/hooks/index.ts
@@ -0,0 +1,4 @@
+// Maritime hooks barrel export
+
+export { useMaritimeData } from './useMaritimeData';
+export { useMapControls } from './useMapControls';
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/hooks/useMapControls.ts b/fincept-terminal-desktop/src/components/tabs/maritime/hooks/useMapControls.ts
new file mode 100644
index 000000000..a8b338184
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/hooks/useMapControls.ts
@@ -0,0 +1,143 @@
+// Hook for managing map controls and state
+
+import { useState, useCallback, RefObject } from 'react';
+import type { MarkerData, MapMode, RealVesselData } from '../types';
+import type { PresetLocation } from '../types';
+
+interface UseMapControlsProps {
+ mapRef: RefObject<HTMLIFrameElement | null>;
+}
+
+interface UseMapControlsReturn {
+ markers: MarkerData[];
+ selectedRoute: any | null;
+ setSelectedRoute: (route: any | null) => void;
+ markerType: MarkerData['type'];
+ setMarkerType: (type: MarkerData['type']) => void;
+ showRoutes: boolean;
+ showShips: boolean;
+ showPlanes: boolean;
+ showSatellites: boolean;
+ isRotating: boolean;
+ mapMode: MapMode;
+ addMarker: (title: string, lat: number, lng: number) => void;
+ addPreset: (preset: PresetLocation) => void;
+ clearMarkers: () => void;
+ toggleRoutes: () => void;
+ toggleShips: () => void;
+ togglePlanes: () => void;
+ toggleSatellites: () => void;
+ toggleRotation: () => void;
+ toggleMapMode: (vessels?: RealVesselData[]) => void;
+ zoomToVessel: (lat: number, lng: number) => void;
+ updateRealVessels: (vessels: RealVesselData[]) => void;
+}
+
+export function useMapControls({ mapRef }: UseMapControlsProps): UseMapControlsReturn {
+ const [markers, setMarkers] = useState<MarkerData[]>([]);
+ const [selectedRoute, setSelectedRoute] = useState<any | null>(null);
+ const [markerType, setMarkerType] = useState<MarkerData['type']>('Ship');
+ const [showRoutes, setShowRoutes] = useState(true);
+ const [showShips, setShowShips] = useState(true);
+ const [showPlanes, setShowPlanes] = useState(true);
+ const [showSatellites, setShowSatellites] = useState(true);
+ const [isRotating, setIsRotating] = useState(true);
+ const [mapMode, setMapMode] = useState<MapMode>('3D');
+
+ const getIframeWindow = useCallback(() => {
+ return mapRef.current?.contentWindow as any;
+ }, [mapRef]);
+
+ const addMarker = useCallback((title: string, lat: number, lng: number) => {
+ const newMarker: MarkerData = { lat, lng, title, type: markerType };
+ setMarkers(prev => [...prev, newMarker]);
+ getIframeWindow()?.addMarker?.(lat, lng, title, markerType);
+ }, [markerType, getIframeWindow]);
+
+ const addPreset = useCallback((preset: PresetLocation) => {
+ const newMarker: MarkerData = {
+ lat: preset.lat,
+ lng: preset.lng,
+ title: preset.name,
+ type: preset.type
+ };
+ setMarkers(prev => [...prev, newMarker]);
+ getIframeWindow()?.addMarker?.(preset.lat, preset.lng, preset.name, preset.type);
+ }, [getIframeWindow]);
+
+ const clearMarkers = useCallback(() => {
+ setMarkers([]);
+ getIframeWindow()?.clearMarkers?.();
+ }, [getIframeWindow]);
+
+ const toggleRoutes = useCallback(() => {
+ setShowRoutes(prev => !prev);
+ getIframeWindow()?.toggleRoutes?.();
+ }, [getIframeWindow]);
+
+ const toggleShips = useCallback(() => {
+ setShowShips(prev => !prev);
+ getIframeWindow()?.toggleShips?.();
+ }, [getIframeWindow]);
+
+ const togglePlanes = useCallback(() => {
+ setShowPlanes(prev => !prev);
+ getIframeWindow()?.togglePlanes?.();
+ }, [getIframeWindow]);
+
+ const toggleSatellites = useCallback(() => {
+ setShowSatellites(prev => !prev);
+ getIframeWindow()?.toggleSatellites?.();
+ }, [getIframeWindow]);
+
+ const toggleRotation = useCallback(() => {
+ const newRotating = !isRotating;
+ setIsRotating(newRotating);
+ getIframeWindow()?.toggleRotation?.(newRotating);
+ }, [isRotating, getIframeWindow]);
+
+ const toggleMapMode = useCallback((vessels?: RealVesselData[]) => {
+ const newMode = mapMode === '3D' ? '2D' : '3D';
+ setMapMode(newMode);
+
+ if (newMode === '2D' && vessels && vessels.length > 0) {
+ console.log('Toggling to 2D with', vessels.length, 'vessels');
+ getIframeWindow()?.switchMapMode?.(newMode, vessels);
+ } else {
+ getIframeWindow()?.switchMapMode?.(newMode);
+ }
+ }, [mapMode, getIframeWindow]);
+
+ const zoomToVessel = useCallback((lat: number, lng: number) => {
+ getIframeWindow()?.world?.pointOfView?.({ lat, lng, altitude: 0.5 }, 1000);
+ }, [getIframeWindow]);
+
+ const updateRealVessels = useCallback((vessels: RealVesselData[]) => {
+ getIframeWindow()?.updateRealVessels?.(vessels);
+ }, [getIframeWindow]);
+
+ return {
+ markers,
+ selectedRoute,
+ setSelectedRoute,
+ markerType,
+ setMarkerType,
+ showRoutes,
+ showShips,
+ showPlanes,
+ showSatellites,
+ isRotating,
+ mapMode,
+ addMarker,
+ addPreset,
+ clearMarkers,
+ toggleRoutes,
+ toggleShips,
+ togglePlanes,
+ toggleSatellites,
+ toggleRotation,
+ toggleMapMode,
+ zoomToVessel,
+ updateRealVessels
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/hooks/useMaritimeData.ts b/fincept-terminal-desktop/src/components/tabs/maritime/hooks/useMaritimeData.ts
new file mode 100644
index 000000000..71bab17e4
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/hooks/useMaritimeData.ts
@@ -0,0 +1,164 @@
+// Hook for managing maritime vessel data
+
+import { useState, useEffect, useCallback } from 'react';
+import { MarineApiService, VesselData } from '@/services/maritime/marineApi';
+import type { RealVesselData, IntelligenceData } from '../types';
+import {
+ DEFAULT_INTELLIGENCE,
+ MUMBAI_SEARCH_AREA,
+ VESSEL_REFRESH_INTERVAL,
+ TIMESTAMP_UPDATE_INTERVAL,
+ MAX_VESSELS_DISPLAY
+} from '../constants';
+
+interface UseMaritimeDataProps {
+ apiKey: string | null;
+ onVesselsUpdate?: (vessels: RealVesselData[]) => void;
+}
+
+interface UseMaritimeDataReturn {
+ realVessels: RealVesselData[];
+ intelligence: IntelligenceData;
+ isLoadingVessels: boolean;
+ vesselLoadError: string | null;
+ searchImo: string;
+ setSearchImo: (imo: string) => void;
+ searchingVessel: boolean;
+ searchResult: VesselData | null;
+ searchError: string | null;
+ loadRealVessels: (limitCount?: number) => Promise<void>;
+ searchVesselByImo: () => Promise<void>;
+}
+
+export function useMaritimeData({ apiKey, onVesselsUpdate }: UseMaritimeDataProps): UseMaritimeDataReturn {
+ const [realVessels, setRealVessels] = useState<RealVesselData[]>([]);
+ const [isLoadingVessels, setIsLoadingVessels] = useState(false);
+ const [vesselLoadError, setVesselLoadError] = useState<string | null>(null);
+ const [searchImo, setSearchImo] = useState('');
+ const [searchingVessel, setSearchingVessel] = useState(false);
+ const [searchResult, setSearchResult] = useState<VesselData | null>(null);
+ const [searchError, setSearchError] = useState<string | null>(null);
+ const [intelligence, setIntelligence] = useState<IntelligenceData>(DEFAULT_INTELLIGENCE);
+
+ // Load real vessel data from API with performance optimization
+ const loadRealVessels = useCallback(async (limitCount: number = MAX_VESSELS_DISPLAY) => {
+ if (!apiKey) {
+ setVesselLoadError('No API key available');
+ return;
+ }
+
+ setIsLoadingVessels(true);
+ setVesselLoadError(null);
+
+ try {
+ const response = await MarineApiService.searchVesselsByArea(MUMBAI_SEARCH_AREA, apiKey);
+
+ if (response.success && response.data) {
+ const allVessels = response.data.vessels
+ .filter(v => v.last_pos_latitude && v.last_pos_longitude)
+ .map(v => ({
+ imo: v.imo,
+ name: v.name,
+ lat: parseFloat(v.last_pos_latitude),
+ lng: parseFloat(v.last_pos_longitude),
+ speed: v.last_pos_speed,
+ angle: v.last_pos_angle,
+ from_port: v.route_from_port_name || undefined,
+ to_port: v.route_to_port_name || undefined,
+ route_progress: v.route_progress ? parseFloat(v.route_progress) : undefined
+ }));
+
+ // Prioritize vessels with routes for better visualization
+ const vesselsWithRoutes = allVessels.filter(v => v.from_port || v.to_port);
+ const vesselsWithoutRoutes = allVessels.filter(v => !v.from_port && !v.to_port);
+
+ const limitedVessels = [
+ ...vesselsWithRoutes.slice(0, Math.floor(limitCount * 0.7)),
+ ...vesselsWithoutRoutes.slice(0, Math.floor(limitCount * 0.3))
+ ].slice(0, limitCount);
+
+ console.log(`Loaded ${limitedVessels.length} vessels out of ${allVessels.length} total`);
+
+ setRealVessels(limitedVessels);
+ setIntelligence(prev => ({
+ ...prev,
+ active_vessels: allVessels.length,
+ timestamp: new Date().toISOString()
+ }));
+
+ onVesselsUpdate?.(limitedVessels);
+ } else {
+ setVesselLoadError(response.error || 'Failed to load vessel data');
+ }
+ } catch (error) {
+ console.error('Error loading vessels:', error);
+ setVesselLoadError(error instanceof Error ? error.message : 'Unknown error');
+ } finally {
+ setIsLoadingVessels(false);
+ }
+ }, [apiKey, onVesselsUpdate]);
+
+ // Search for a specific vessel by IMO
+ const searchVesselByImo = useCallback(async () => {
+ if (!apiKey) {
+ setSearchError('No API key available');
+ return;
+ }
+
+ if (!searchImo.trim()) {
+ setSearchError('Please enter an IMO number');
+ return;
+ }
+
+ setSearchingVessel(true);
+ setSearchError(null);
+ setSearchResult(null);
+
+ try {
+ const response = await MarineApiService.getVesselPosition(searchImo.trim(), apiKey);
+
+ if (response.success && response.data) {
+ setSearchResult(response.data.vessel);
+ } else {
+ setSearchError(response.error || 'Vessel not found');
+ }
+ } catch (error) {
+ console.error('Error searching vessel:', error);
+ setSearchError(error instanceof Error ? error.message : 'Search failed');
+ } finally {
+ setSearchingVessel(false);
+ }
+ }, [apiKey, searchImo]);
+
+ // Load vessels on mount and refresh periodically
+ useEffect(() => {
+ loadRealVessels();
+ const interval = setInterval(loadRealVessels, VESSEL_REFRESH_INTERVAL);
+ return () => clearInterval(interval);
+ }, [loadRealVessels]);
+
+ // Update timestamp periodically
+ useEffect(() => {
+ const interval = setInterval(() => {
+ setIntelligence(prev => ({
+ ...prev,
+ timestamp: new Date().toISOString()
+ }));
+ }, TIMESTAMP_UPDATE_INTERVAL);
+ return () => clearInterval(interval);
+ }, []);
+
+ return {
+ realVessels,
+ intelligence,
+ isLoadingVessels,
+ vesselLoadError,
+ searchImo,
+ setSearchImo,
+ searchingVessel,
+ searchResult,
+ searchError,
+ loadRealVessels,
+ searchVesselByImo
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/index.ts b/fincept-terminal-desktop/src/components/tabs/maritime/index.ts
new file mode 100644
index 000000000..793e9b8d8
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/index.ts
@@ -0,0 +1,20 @@
+// Maritime Tab - Barrel Export
+
+// Main component
+export { default as MaritimeTab } from './MaritimeTab';
+export { default } from './MaritimeTab';
+
+// Types
+export * from './types';
+
+// Constants
+export * from './constants';
+
+// Hooks
+export * from './hooks';
+
+// Components
+export * from './components';
+
+// Utils
+export * from './utils';
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/types.ts b/fincept-terminal-desktop/src/components/tabs/maritime/types.ts
new file mode 100644
index 000000000..ab0d2e601
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/types.ts
@@ -0,0 +1,65 @@
+// Maritime Tab Types
+
+export interface MarkerData {
+ lat: number;
+ lng: number;
+ title: string;
+ type: 'Ship' | 'Port' | 'Industry' | 'Bank' | 'Exchange';
+}
+
+export interface TradeRoute {
+ name: string;
+ value: string;
+ status: 'active' | 'delayed' | 'critical';
+ vessels: number;
+ coordinates: [number, number][];
+}
+
+export interface IntelligenceData {
+ timestamp: string;
+ threat_level: 'low' | 'medium' | 'high' | 'critical';
+ active_vessels: number;
+ monitored_routes: number;
+ trade_volume: string;
+}
+
+export interface RealVesselData {
+ imo: string;
+ name: string;
+ lat: number;
+ lng: number;
+ speed: string;
+ angle: string;
+ from_port?: string;
+ to_port?: string;
+ route_progress?: number;
+}
+
+export interface PresetLocation {
+ name: string;
+ lat: number;
+ lng: number;
+ type: 'Port' | 'Ship' | 'Industry' | 'Bank' | 'Exchange';
+}
+
+export interface OceanRoute {
+ name: string;
+ start: { lat: number; lng: number };
+ end: { lat: number; lng: number };
+ value: string;
+ vessels: number;
+ color: string;
+ width: number;
+}
+
+export interface AirRoute {
+ name: string;
+ start: { lat: number; lng: number };
+ end: { lat: number; lng: number };
+ value: string;
+ flights: number;
+ color: string;
+ width: number;
+}
+
+export type MapMode = '3D' | '2D';
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/utils/index.ts b/fincept-terminal-desktop/src/components/tabs/maritime/utils/index.ts
new file mode 100644
index 000000000..b4d7b4e63
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/utils/index.ts
@@ -0,0 +1,3 @@
+// Maritime utils barrel export
+
+export { generateMapHTML } from './mapHtmlGenerator';
diff --git a/fincept-terminal-desktop/src/components/tabs/maritime/utils/mapHtmlGenerator.ts b/fincept-terminal-desktop/src/components/tabs/maritime/utils/mapHtmlGenerator.ts
new file mode 100644
index 000000000..6742f34c9
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/maritime/utils/mapHtmlGenerator.ts
@@ -0,0 +1,821 @@
+// Generates the HTML content for the 3D Globe / 2D Map visualization
+
+import { OCEAN_ROUTES, AIR_ROUTES } from '../constants';
+
+export function generateMapHTML(): string {
+ // Serialize routes for injection into the HTML
+ const oceanRoutesJson = JSON.stringify(OCEAN_ROUTES);
+ const airRoutesJson = JSON.stringify(AIR_ROUTES);
+
+ return `
+<!DOCTYPE html>
+<html>
+<head>
+ <meta charset="utf-8" />
+ <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
+ <style>
+ body { margin: 0; padding: 0; background: #000; overflow: hidden; }
+ #globeViz { height: 100vh; width: 100vw; background: #000; position: absolute; top: 0; left: 0; }
+ #mapViz { height: 100vh; width: 100vw; position: absolute; top: 0; left: 0; display: none; }
+ #modeIndicator {
+ position: absolute;
+ top: 16px;
+ right: 16px;
+ background: rgba(0, 255, 255, 0.9);
+ color: #000;
+ padding: 8px 16px;
+ border-radius: 4px;
+ font-family: 'Consolas', monospace;
+ font-size: 12px;
+ font-weight: bold;
+ z-index: 1000;
+ box-shadow: 0 0 10px rgba(0, 255, 255, 0.5);
+ }
+ </style>
+</head>
+<body>
+ <div id="modeIndicator">3D GLOBE MODE</div>
+ <div id="globeViz"></div>
+ <div id="mapViz"></div>
+ <script src="https://unpkg.com/[email protected]/build/three.min.js"></script>
+ <script src="https://unpkg.com/[email protected]/dist/globe.gl.min.js"></script>
+ <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
+ <script>
+ console.log('Initializing Hybrid Globe/Map System...');
+
+ // Route data injected from React
+ var oceanRoutes = ${oceanRoutesJson};
+ var airRoutes = ${airRoutesJson};
+
+ // Wait for libraries to load
+ setTimeout(() => {
+ try {
+ console.log('Creating globe...');
+
+ // Create professional globe with natural appearance
+ const world = Globe()
+ (document.getElementById('globeViz'))
+ .globeImageUrl('https://unpkg.com/[email protected]/example/img/earth-blue-marble.jpg')
+ .bumpImageUrl('https://unpkg.com/[email protected]/example/img/earth-topology.png')
+ .backgroundColor('#0a0a0a')
+ .backgroundImageUrl('https://unpkg.com/three-globe/example/img/night-sky.png')
+ .showAtmosphere(true)
+ .atmosphereColor('#4a90e2')
+ .atmosphereAltitude(0.12)
+ .width(window.innerWidth)
+ .height(window.innerHeight);
+
+ console.log('Globe created successfully');
+
+ // Initialize 2D Leaflet map (lazy)
+ let map2D = null;
+
+ function initMap2D() {
+ if (!map2D) {
+ map2D = L.map('mapViz', {
+ zoomControl: true,
+ attributionControl: false,
+ preferCanvas: true,
+ scrollWheelZoom: true,
+ doubleClickZoom: true,
+ touchZoom: true,
+ boxZoom: true,
+ keyboard: true,
+ dragging: true,
+ maxZoom: 18,
+ minZoom: 3
+ }).setView([19.0, 72.8], 11);
+
+ L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
+ attribution: 'FINCEPT MARITIME INTELLIGENCE',
+ maxZoom: 18,
+ minZoom: 3
+ }).addTo(map2D);
+
+ setTimeout(() => {
+ map2D.invalidateSize();
+ console.log('2D map resized and tiles loading');
+ }, 100);
+
+ console.log('2D map initialized');
+ }
+ }
+
+ // Professional balanced lighting
+ const scene = world.scene();
+ const ambientLight = new THREE.AmbientLight(0x808080, 0.7);
+ const directionalLight = new THREE.DirectionalLight(0xaaaaaa, 0.6);
+ directionalLight.position.set(5, 3, 5);
+ scene.add(ambientLight);
+ scene.add(directionalLight);
+
+ // Set initial point of view
+ world.pointOfView({ lat: 20, lng: 75, altitude: 2.0 }, 1000);
+
+ // State variables
+ let currentMode = '3D';
+ let lastGlobeView = { lat: 20, lng: 75, altitude: 2.0 };
+ let targetCoords = { lat: 20, lng: 75 };
+
+ var markers = [];
+ var allArcs = [];
+ var allLabels = [];
+ var planeLabels = [];
+ var showRoutesFlag = true;
+ var showShipsFlag = true;
+ var showPlanesFlag = true;
+ var showSatellitesFlag = true;
+ var orbitalPathsData = [];
+
+ function createRoutes() {
+ const oceanArcsData = oceanRoutes.map(route => ({
+ startLat: route.start.lat,
+ startLng: route.start.lng,
+ endLat: route.end.lat,
+ endLng: route.end.lng,
+ color: route.color,
+ name: route.name,
+ value: route.value,
+ width: route.width || 0.5,
+ type: 'ocean'
+ }));
+
+ const airArcsData = airRoutes.map(route => ({
+ startLat: route.start.lat,
+ startLng: route.start.lng,
+ endLat: route.end.lat,
+ endLng: route.end.lng,
+ color: route.color,
+ name: route.name,
+ value: route.value,
+ width: route.width || 0.5,
+ type: 'air'
+ }));
+
+ const allArcsData = [...oceanArcsData, ...airArcsData];
+ allArcs = allArcsData;
+ world.arcsData(allArcsData)
+ .arcColor('color')
+ .arcStroke((d) => d.width)
+ .arcDashLength(1.0)
+ .arcDashGap(0)
+ .arcDashInitialGap(0)
+ .arcDashAnimateTime(0)
+ .arcAltitude((d) => d.type === 'air' ? 0.15 : 0.1)
+ .arcAltitudeAutoScale(0.5)
+ .arcLabel((d) => \`
+ <div style="background: rgba(10,10,10,0.92); padding: 6px 10px; border-left: 2px solid \${d.type === 'air' ? 'rgba(255, 200, 100, 0.8)' : 'rgba(100, 180, 255, 0.8)'}; font-family: 'Segoe UI', sans-serif; font-size: 11px; box-shadow: 0 2px 8px rgba(0,0,0,0.4);">
+ <div style="color: #e0e0e0; font-weight: 500; margin-bottom: 2px;">\${d.type === 'air' ? '✈' : '🚢'} \${d.name}</div>
+ <div style="color: #999; font-size: 9px;">\${d.value}</div>
+ </div>
+ \`);
+
+ // Extract unique ports and airports
+ const uniquePorts = new Map();
+ oceanRoutes.forEach(route => {
+ const startName = route.name.split(' → ')[0];
+ const endName = route.name.split(' → ')[1];
+ if (!uniquePorts.has(startName)) {
+ uniquePorts.set(startName, { lat: route.start.lat, lng: route.start.lng, type: 'port' });
+ }
+ if (!uniquePorts.has(endName)) {
+ uniquePorts.set(endName, { lat: route.end.lat, lng: route.end.lng, type: 'port' });
+ }
+ });
+
+ const uniqueAirports = new Map();
+ airRoutes.forEach(route => {
+ const startName = route.name.split(' → ')[0];
+ const endName = route.name.split(' → ')[1];
+ if (!uniqueAirports.has(startName)) {
+ uniqueAirports.set(startName, { lat: route.start.lat, lng: route.start.lng, type: 'airport' });
+ }
+ if (!uniqueAirports.has(endName)) {
+ uniqueAirports.set(endName, { lat: route.end.lat, lng: route.end.lng, type: 'airport' });
+ }
+ });
+
+ const portPoints = Array.from(uniquePorts.entries()).map(([name, data]) => ({
+ lat: data.lat,
+ lng: data.lng,
+ size: 0.6,
+ color: 'rgba(255, 180, 100, 0.85)',
+ label: name,
+ type: 'port'
+ }));
+
+ const airportPoints = Array.from(uniqueAirports.entries()).map(([name, data]) => ({
+ lat: data.lat,
+ lng: data.lng,
+ size: 0.5,
+ color: 'rgba(180, 100, 255, 0.85)',
+ label: name,
+ type: 'airport'
+ }));
+
+ const allPoints = [...portPoints, ...airportPoints];
+
+ world.pointsData(allPoints)
+ .pointAltitude(0.002)
+ .pointRadius('size')
+ .pointColor('color')
+ .pointLabel((d) => \`
+ <div style="background: rgba(10,10,10,0.92); padding: 5px 9px; border-left: 2px solid \${d.color}; font-family: 'Segoe UI', sans-serif; font-size: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.4);">
+ <span style="color: #e0e0e0; font-weight: 500;">\${d.type === 'port' ? '⚓' : '✈'} \${d.label}</span>
+ </div>
+ \`);
+ }
+
+ function createShips() {
+ const shipData = oceanRoutes.map((route, routeIdx) => ({
+ routeIdx: routeIdx,
+ progress: Math.random(),
+ startLat: route.start.lat,
+ startLng: route.start.lng,
+ endLat: route.end.lat,
+ endLng: route.end.lng,
+ label: route.name,
+ value: route.value,
+ vessels: route.vessels
+ }));
+
+ function interpolateArc(startLat, startLng, endLat, endLng, progress) {
+ const lat = startLat + (endLat - startLat) * progress;
+ const lng = startLng + (endLng - startLng) * progress;
+ return { lat, lng };
+ }
+
+ function generateShipPoints(shipsData) {
+ return shipsData.map(ship => {
+ const pos = interpolateArc(ship.startLat, ship.startLng, ship.endLat, ship.endLng, ship.progress);
+ return {
+ lat: pos.lat,
+ lng: pos.lng,
+ size: 0.15,
+ color: 'rgba(100, 180, 255, 0.95)',
+ altitude: 0.003,
+ label: ship.label,
+ value: ship.value,
+ vessels: ship.vessels
+ };
+ });
+ }
+
+ allLabels = shipData;
+
+ const initialShipPoints = generateShipPoints(shipData);
+ world.customLayerData(initialShipPoints)
+ .customThreeObject(d => {
+ const canvas = document.createElement('canvas');
+ canvas.width = 64;
+ canvas.height = 64;
+ const ctx = canvas.getContext('2d');
+ ctx.font = '48px Arial';
+ ctx.fillText('🚢', 8, 48);
+
+ const texture = new THREE.CanvasTexture(canvas);
+ const material = new THREE.SpriteMaterial({
+ map: texture,
+ transparent: true,
+ opacity: 0.95
+ });
+ const sprite = new THREE.Sprite(material);
+ sprite.scale.set(2, 2, 1);
+
+ return sprite;
+ })
+ .customThreeObjectUpdate((obj, d) => {
+ Object.assign(obj.position, world.getCoords(d.lat, d.lng, d.altitude));
+ });
+
+ setInterval(() => {
+ shipData.forEach(ship => {
+ ship.progress = (ship.progress + 0.0002) % 1.0;
+ });
+ const updatedShipPoints = generateShipPoints(shipData);
+ world.customLayerData(updatedShipPoints);
+ }, 200);
+ }
+
+ function createPlanes() {
+ const planeData = airRoutes.map((route, routeIdx) => ({
+ routeIdx: routeIdx,
+ progress: Math.random(),
+ startLat: route.start.lat,
+ startLng: route.start.lng,
+ endLat: route.end.lat,
+ endLng: route.end.lng,
+ label: route.name,
+ value: route.value,
+ flights: route.flights
+ }));
+
+ function interpolateArc(startLat, startLng, endLat, endLng, progress) {
+ const lat = startLat + (endLat - startLat) * progress;
+ const lng = startLng + (endLng - startLng) * progress;
+ return { lat, lng };
+ }
+
+ function generatePlanePoints(planesData) {
+ return planesData.map(plane => {
+ const pos = interpolateArc(plane.startLat, plane.startLng, plane.endLat, plane.endLng, plane.progress);
+ return {
+ lat: pos.lat,
+ lng: pos.lng,
+ size: 0.15,
+ color: 'rgba(255, 200, 100, 0.95)',
+ altitude: 0.01,
+ label: plane.label,
+ value: plane.value,
+ flights: plane.flights
+ };
+ });
+ }
+
+ planeLabels = planeData;
+
+ const initialPlanePoints = generatePlanePoints(planeData);
+ world.htmlElementsData(initialPlanePoints)
+ .htmlElement(d => {
+ const el = document.createElement('div');
+ el.innerHTML = '✈';
+ el.style.color = 'rgba(255, 200, 100, 0.95)';
+ el.style.fontSize = '16px';
+ el.style.cursor = 'pointer';
+ el.style.filter = 'drop-shadow(0 0 4px rgba(255, 200, 100, 0.8))';
+ el.style.transform = 'rotate(-45deg)';
+ el.title = \`\${d.label} - \${d.value} (\${d.flights} flights/week)\`;
+ return el;
+ })
+ .htmlAltitude(d => d.altitude);
+
+ setInterval(() => {
+ planeData.forEach(plane => {
+ plane.progress = (plane.progress + 0.0004) % 1.0;
+ });
+ const updatedPlanePoints = generatePlanePoints(planeData);
+ world.htmlElementsData(updatedPlanePoints);
+ }, 200);
+ }
+
+ function createSatellites() {
+ const satelliteOrbits = [
+ { name: 'GPS-1', inclination: 55, altitude: 0.35, speed: 0.0008, color: '#00ff00', orbitId: 'gps' },
+ { name: 'GPS-2', inclination: 55, altitude: 0.35, speed: 0.0008, color: '#00ff00', phaseOffset: Math.PI, orbitId: 'gps' },
+ { name: 'IRNSS-1', inclination: 29, altitude: 0.37, speed: 0.0007, color: '#ffd700', orbitId: 'irnss' },
+ { name: 'IRNSS-2', inclination: 29, altitude: 0.37, speed: 0.0007, color: '#ffd700', phaseOffset: Math.PI / 2, orbitId: 'irnss' },
+ { name: 'Starlink-1', inclination: 53, altitude: 0.32, speed: 0.0009, color: '#00ccff', orbitId: 'starlink' },
+ { name: 'Starlink-2', inclination: 53, altitude: 0.32, speed: 0.0009, color: '#00ccff', phaseOffset: 2 * Math.PI / 3, orbitId: 'starlink' },
+ { name: 'Starlink-3', inclination: 53, altitude: 0.32, speed: 0.0009, color: '#00ccff', phaseOffset: 4 * Math.PI / 3, orbitId: 'starlink' },
+ { name: 'GLONASS-1', inclination: 64.8, altitude: 0.42, speed: 0.0006, color: '#ff6b6b', orbitId: 'glonass' },
+ { name: 'GLONASS-2', inclination: 64.8, altitude: 0.42, speed: 0.0006, color: '#ff6b6b', phaseOffset: Math.PI / 3, orbitId: 'glonass' },
+ { name: 'Galileo-1', inclination: 56, altitude: 0.40, speed: 0.0007, color: '#9d4edd', orbitId: 'galileo' },
+ { name: 'Galileo-2', inclination: 56, altitude: 0.40, speed: 0.0007, color: '#9d4edd', phaseOffset: Math.PI / 2, orbitId: 'galileo' },
+ { name: 'INSAT-1', inclination: 0, altitude: 0.50, speed: 0.0004, color: '#ff9500', orbitId: 'insat' },
+ { name: 'INSAT-2', inclination: 0, altitude: 0.50, speed: 0.0004, color: '#ff9500', phaseOffset: Math.PI, orbitId: 'insat' },
+ ];
+
+ const satellites = satelliteOrbits.map((orbit, idx) => ({
+ id: idx,
+ name: orbit.name,
+ inclination: orbit.inclination,
+ altitude: orbit.altitude,
+ speed: orbit.speed,
+ color: orbit.color,
+ orbitId: orbit.orbitId,
+ phase: orbit.phaseOffset || 0
+ }));
+
+ function createOrbitalPaths() {
+ const uniqueOrbits = new Map();
+ satelliteOrbits.forEach(orbit => {
+ if (!uniqueOrbits.has(orbit.orbitId)) {
+ uniqueOrbits.set(orbit.orbitId, {
+ inclination: orbit.inclination,
+ altitude: orbit.altitude,
+ color: orbit.color,
+ name: orbit.orbitId
+ });
+ }
+ });
+
+ const orbitalPaths = [];
+ uniqueOrbits.forEach((orbit, orbitId) => {
+ const numPoints = 100;
+ const pathPoints = [];
+
+ for (let i = 0; i <= numPoints; i++) {
+ const angle = (i / numPoints) * 2 * Math.PI;
+ const inclinationRad = (orbit.inclination * Math.PI) / 180;
+
+ const x = Math.cos(angle);
+ const y = Math.sin(angle) * Math.cos(inclinationRad);
+ const z = Math.sin(angle) * Math.sin(inclinationRad);
+
+ const lat = Math.asin(y) * (180 / Math.PI);
+ const lng = Math.atan2(z, x) * (180 / Math.PI);
+
+ pathPoints.push([lat, lng]);
+ }
+
+ orbitalPaths.push({
+ id: orbitId,
+ color: orbit.color,
+ altitude: orbit.altitude,
+ points: pathPoints
+ });
+ });
+
+ return orbitalPaths;
+ }
+
+ const orbitalPaths = createOrbitalPaths();
+ orbitalPathsData = orbitalPaths;
+
+ world.pathsData(orbitalPaths)
+ .pathPoints('points')
+ .pathPointLat(p => p[0])
+ .pathPointLng(p => p[1])
+ .pathColor('color')
+ .pathStroke(0.8)
+ .pathDashLength(0.5)
+ .pathDashGap(0.1)
+ .pathDashAnimateTime(20000)
+ .pathTransitionDuration(0)
+ .pathPointAlt('altitude');
+
+ const satelliteData = satellites.map((sat, idx) => ({
+ ...sat,
+ progress: (idx / satellites.length)
+ }));
+
+ function generateSatellitePoints(satsData) {
+ return satsData.map(sat => {
+ const angle = sat.progress * 2 * Math.PI;
+ const inclinationRad = (sat.inclination * Math.PI) / 180;
+
+ const x = Math.cos(angle);
+ const y = Math.sin(angle) * Math.cos(inclinationRad);
+ const z = Math.sin(angle) * Math.sin(inclinationRad);
+
+ const lat = Math.asin(y) * (180 / Math.PI);
+ const lng = Math.atan2(z, x) * (180 / Math.PI);
+
+ return {
+ lat: lat,
+ lng: lng,
+ altitude: sat.altitude,
+ name: sat.name,
+ color: sat.color
+ };
+ });
+ }
+
+ const initialSatellitePoints = generateSatellitePoints(satelliteData);
+
+ world.objectsData(initialSatellitePoints)
+ .objectLat('lat')
+ .objectLng('lng')
+ .objectAltitude('altitude')
+ .objectLabel(d => \`
+ <div style="background: rgba(10,10,10,0.92); padding: 5px 9px; border-left: 2px solid \${d.color}; font-family: 'Segoe UI', sans-serif; font-size: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.4);">
+ <span style="color: #e0e0e0; font-weight: 500;">🛰 \${d.name}</span>
+ </div>
+ \`)
+ .objectThreeObject(d => {
+ const canvas = document.createElement('canvas');
+ canvas.width = 128;
+ canvas.height = 128;
+ const ctx = canvas.getContext('2d');
+
+ ctx.beginPath();
+ ctx.arc(64, 64, 50, 0, 2 * Math.PI);
+ ctx.fillStyle = d.color;
+ ctx.globalAlpha = 0.4;
+ ctx.fill();
+ ctx.globalAlpha = 1.0;
+
+ ctx.strokeStyle = d.color;
+ ctx.lineWidth = 3;
+ ctx.stroke();
+
+ ctx.font = 'bold 70px Arial';
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.fillStyle = '#ffffff';
+ ctx.fillText('🛰', 64, 64);
+
+ const texture = new THREE.CanvasTexture(canvas);
+ const material = new THREE.SpriteMaterial({
+ map: texture,
+ transparent: true,
+ opacity: 1.0,
+ sizeAttenuation: true
+ });
+ const sprite = new THREE.Sprite(material);
+ sprite.scale.set(4, 4, 1);
+
+ const ringGeometry = new THREE.RingGeometry(1.5, 2.0, 16);
+ const ringMaterial = new THREE.MeshBasicMaterial({
+ color: d.color,
+ transparent: true,
+ opacity: 0.6,
+ side: THREE.DoubleSide
+ });
+ const ring = new THREE.Mesh(ringGeometry, ringMaterial);
+
+ const group = new THREE.Group();
+ group.add(sprite);
+ group.add(ring);
+
+ return group;
+ });
+
+ setInterval(() => {
+ if (showSatellitesFlag) {
+ satelliteData.forEach(sat => {
+ sat.progress = (sat.progress + sat.speed * 0.15) % 1.0;
+ });
+ const updatedSatellitePoints = generateSatellitePoints(satelliteData);
+ world.objectsData(updatedSatellitePoints);
+ }
+ }, 100);
+ }
+
+ window.addMarker = function(lat, lng, title, type) {
+ const icons = { 'Ship': '🚢', 'Port': '⚓', 'Industry': '🏭', 'Bank': '🏦', 'Exchange': '💱' };
+ markers.push({ lat, lng, title, type, icon: icons[type] || icons['Ship'] });
+
+ world.htmlElementsData([...allLabels, ...markers])
+ .htmlElement(d => {
+ const el = document.createElement('div');
+ el.innerHTML = d.icon || d.label;
+ el.style.color = d.color || '#ff8c00';
+ el.style.fontSize = '20px';
+ el.style.cursor = 'pointer';
+ el.style.textShadow = '0 0 5px ' + (d.color || '#ff8c00');
+ el.title = d.title || d.label || '';
+ return el;
+ });
+ };
+
+ window.clearMarkers = function() {
+ markers = [];
+ world.htmlElementsData(allLabels);
+ };
+
+ // Real vessel data handling
+ var realVesselPoints = [];
+ var vesselTexture = null;
+
+ function createVesselTexture() {
+ if (!vesselTexture) {
+ const canvas = document.createElement('canvas');
+ canvas.width = 64;
+ canvas.height = 64;
+ const ctx = canvas.getContext('2d');
+ ctx.font = '48px Arial';
+ ctx.fillText('🚢', 8, 48);
+ vesselTexture = new THREE.CanvasTexture(canvas);
+ }
+ return vesselTexture;
+ }
+
+ window.updateRealVessels = function(vessels) {
+ console.log('Updating real vessels:', vessels.length);
+
+ if (!vessels || vessels.length === 0) {
+ world.customLayerData([]);
+ realVesselPoints = [];
+ return;
+ }
+
+ realVesselPoints = vessels.map(vessel => ({
+ lat: vessel.lat,
+ lng: vessel.lng,
+ size: 0.15,
+ color: 'rgba(0, 255, 255, 0.9)',
+ altitude: 0.003,
+ name: vessel.name,
+ imo: vessel.imo,
+ speed: vessel.speed,
+ angle: vessel.angle,
+ from_port: vessel.from_port,
+ to_port: vessel.to_port,
+ route_progress: vessel.route_progress
+ }));
+
+ if (showShipsFlag) {
+ const texture = createVesselTexture();
+
+ world.customLayerData(realVesselPoints)
+ .customThreeObject(d => {
+ const material = new THREE.SpriteMaterial({
+ map: texture,
+ transparent: true,
+ opacity: 0.9,
+ sizeAttenuation: true
+ });
+ const sprite = new THREE.Sprite(material);
+ sprite.scale.set(1.5, 1.5, 1);
+ return sprite;
+ })
+ .customThreeObjectUpdate((obj, d) => {
+ const coords = world.getCoords(d.lat, d.lng, d.altitude);
+ if (coords && coords.x !== undefined && coords.y !== undefined && coords.z !== undefined) {
+ Object.assign(obj.position, coords);
+ }
+ });
+ }
+ };
+
+ // Mode switching
+ var vesselMarkers = [];
+ window.switchMapMode = function(mode, vesselsFromReact) {
+ console.log('Switching to mode:', mode);
+
+ if (mode === '2D') {
+ initMap2D();
+
+ document.getElementById('globeViz').style.display = 'none';
+ document.getElementById('mapViz').style.display = 'block';
+ document.getElementById('modeIndicator').textContent = '2D MAP MODE - Real Vessels Only';
+ document.getElementById('modeIndicator').style.background = 'rgba(255, 215, 0, 0.9)';
+
+ setTimeout(() => {
+ if (map2D) {
+ map2D.setView([19.0, 72.8], 11);
+ map2D.invalidateSize();
+
+ const vesselsToRender = vesselsFromReact || realVesselPoints;
+ if (vesselsToRender && vesselsToRender.length > 0) {
+ updateVesselsOn2DMap(vesselsToRender);
+ }
+ }
+ }, 200);
+
+ } else {
+ document.getElementById('globeViz').style.display = 'block';
+ document.getElementById('mapViz').style.display = 'none';
+ document.getElementById('modeIndicator').textContent = '3D GLOBE MODE';
+ document.getElementById('modeIndicator').style.background = 'rgba(0, 255, 255, 0.9)';
+
+ vesselMarkers.forEach(marker => marker.remove());
+ vesselMarkers = [];
+ }
+ };
+
+ function updateVesselsOn2DMap(vessels) {
+ if (!map2D || !vessels || vessels.length === 0) return;
+
+ vesselMarkers.forEach(marker => marker.remove());
+ vesselMarkers = [];
+
+ const shipIcon = L.divIcon({
+ className: 'vessel-marker',
+ html: '<div style="font-size: 16px;">🚢</div>',
+ iconSize: [20, 20],
+ iconAnchor: [10, 10]
+ });
+
+ const vesselsToDisplay = vessels.slice(0, 500);
+
+ vesselsToDisplay.forEach(vessel => {
+ const marker = L.marker([vessel.lat, vessel.lng], { icon: shipIcon })
+ .bindPopup(\`
+ <div style="font-family: 'Consolas', monospace; font-size: 11px;">
+ <div style="font-weight: bold; color: #0ff; margin-bottom: 4px;">\${vessel.name}</div>
+ <div style="font-size: 9px;">
+ <div><strong>IMO:</strong> \${vessel.imo}</div>
+ <div><strong>Position:</strong> \${vessel.lat.toFixed(4)}°, \${vessel.lng.toFixed(4)}°</div>
+ <div><strong>Speed:</strong> \${vessel.speed} kts</div>
+ \${vessel.from_port ? \`<div><strong>From:</strong> \${vessel.from_port}</div>\` : ''}
+ \${vessel.to_port ? \`<div><strong>To:</strong> \${vessel.to_port}</div>\` : ''}
+ </div>
+ </div>
+ \`)
+ .addTo(map2D);
+
+ vesselMarkers.push(marker);
+ });
+ }
+
+ // Toggle functions
+ window.toggleRoutes = function() {
+ if (showRoutesFlag) {
+ world.arcsData([]);
+ } else {
+ createRoutes();
+ }
+ showRoutesFlag = !showRoutesFlag;
+ };
+
+ window.toggleShips = function() {
+ if (showShipsFlag) {
+ world.customLayerData([]);
+ } else {
+ if (realVesselPoints.length > 0) {
+ window.updateRealVessels(realVesselPoints.map(p => ({
+ lat: p.lat, lng: p.lng, name: p.name, imo: p.imo,
+ speed: p.speed, angle: p.angle, from_port: p.from_port, to_port: p.to_port
+ })));
+ }
+ }
+ showShipsFlag = !showShipsFlag;
+ };
+
+ window.togglePlanes = function() {
+ if (showPlanesFlag) {
+ world.htmlElementsData([]);
+ } else {
+ function interpolateArc(startLat, startLng, endLat, endLng, progress) {
+ const lat = startLat + (endLat - startLat) * progress;
+ const lng = startLng + (endLng - startLng) * progress;
+ return { lat, lng };
+ }
+
+ const planePoints = planeLabels.map(plane => {
+ const pos = interpolateArc(plane.startLat, plane.startLng, plane.endLat, plane.endLng, plane.progress);
+ return {
+ lat: pos.lat, lng: pos.lng, size: 0.15,
+ color: 'rgba(255, 200, 100, 0.95)', altitude: 0.01,
+ label: plane.label, value: plane.value, flights: plane.flights
+ };
+ });
+ world.htmlElementsData(planePoints);
+ }
+ showPlanesFlag = !showPlanesFlag;
+ };
+
+ let userPausedRotation = false;
+
+ window.toggleRotation = function(shouldRotate) {
+ userPausedRotation = !shouldRotate;
+ world.controls().autoRotate = shouldRotate;
+ console.log('Globe rotation:', shouldRotate ? 'enabled' : 'disabled');
+ };
+
+ window.toggleSatellites = function() {
+ showSatellitesFlag = !showSatellitesFlag;
+ if (!showSatellitesFlag) {
+ world.objectsData([]);
+ world.pathsData([]);
+ } else {
+ world.pathsData(orbitalPathsData);
+ }
+ };
+
+ // Configure controls
+ world.controls().autoRotate = true;
+ world.controls().autoRotateSpeed = 0.2;
+ world.controls().enableDamping = true;
+ world.controls().dampingFactor = 0.05;
+ world.controls().minDistance = 150;
+ world.controls().maxDistance = 800;
+ world.controls().zoomSpeed = 1.2;
+ world.controls().enableZoom = true;
+
+ let interactionTimeout;
+ const resumeRotation = () => {
+ clearTimeout(interactionTimeout);
+ world.controls().autoRotate = false;
+ interactionTimeout = setTimeout(() => {
+ if (!userPausedRotation) {
+ world.controls().autoRotate = true;
+ }
+ }, 3000);
+ };
+
+ world.onZoom((view) => {
+ lastGlobeView = view;
+ targetCoords = { lat: view.lat, lng: view.lng };
+ });
+
+ const container = document.getElementById('globeViz');
+ container.addEventListener('mousedown', resumeRotation);
+ container.addEventListener('wheel', resumeRotation);
+ container.addEventListener('touchstart', resumeRotation);
+
+ world.controls().autoRotate = true;
+
+ // Initialize visualizations
+ createRoutes();
+ createShips();
+ createPlanes();
+ createSatellites();
+
+ window.addEventListener('resize', () => {
+ world.width(window.innerWidth).height(window.innerHeight);
+ });
+
+ console.log('3D Globe fully initialized');
+ } catch (error) {
+ console.error('Error initializing Globe:', error);
+ document.body.innerHTML = '<div style="color: red; padding: 20px; font-family: monospace;">ERROR: Failed to load 3D Globe<br>Check console for details<br><br>' + error.message + '</div>';
+ }
+ }, 500);
+ </script>
+</body>
+</html>
+ `;
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/MarketplaceTab.tsx b/fincept-terminal-desktop/src/components/tabs/marketplace/MarketplaceTab.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/MarketplaceTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/marketplace/MarketplaceTab.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/marketplace/index.ts b/fincept-terminal-desktop/src/components/tabs/marketplace/index.ts
new file mode 100644
index 000000000..e367d6534
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/marketplace/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./MarketplaceTab";
+export { default as MarketplaceTab } from "./MarketplaceTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx b/fincept-terminal-desktop/src/components/tabs/markets/MarketsTab.tsx
similarity index 98%
rename from fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/markets/MarketsTab.tsx
index 3538764f3..215f42849 100644
--- a/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/markets/MarketsTab.tsx
@@ -1,16 +1,16 @@
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { Edit2, Info, RefreshCw } from 'lucide-react';
import { useTerminalTheme } from '@/contexts/ThemeContext';
-import { marketDataService, QuoteData } from '../../services/markets/marketDataService';
-import { tickerStorage, UserMarketPreferences } from '../../services/core/tickerStorageService';
-import { sqliteService } from '../../services/core/sqliteService';
-import { contextRecorderService } from '../../services/data-sources/contextRecorderService';
-import { useCache } from '../../hooks/useCache';
-import TickerEditModal from './TickerEditModal';
-import RecordingControlPanel from '../common/RecordingControlPanel';
+import { marketDataService, QuoteData } from '@/services/markets/marketDataService';
+import { tickerStorage, UserMarketPreferences } from '@/services/core/tickerStorageService';
+import { sqliteService } from '@/services/core/sqliteService';
+import { contextRecorderService } from '@/services/data-sources/contextRecorderService';
+import { useCache } from '@/hooks/useCache';
+import TickerEditModal from '@/components/tabs/ticker-edit-modal';
+import RecordingControlPanel from '@/components/common/RecordingControlPanel';
import { TabFooter } from '@/components/common/TabFooter';
import { useTranslation } from 'react-i18next';
-import { createMarketsTabTour } from './tours/marketsTabTour';
+import { createMarketsTabTour } from '@/components/tabs/tours/marketsTabTour';
// Hook to fetch market data for a category
// Cache key includes ticker count and first/last ticker to detect changes
diff --git a/fincept-terminal-desktop/src/components/tabs/markets/index.ts b/fincept-terminal-desktop/src/components/tabs/markets/index.ts
new file mode 100644
index 000000000..1c96cebe1
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/markets/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./MarketsTab";
+export { default as MarketsTab } from "./MarketsTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/MonitoringTab.tsx b/fincept-terminal-desktop/src/components/tabs/monitoring/MonitoringTab.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/MonitoringTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/monitoring/MonitoringTab.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/monitoring/index.ts b/fincept-terminal-desktop/src/components/tabs/monitoring/index.ts
new file mode 100644
index 000000000..2dd0e8232
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/monitoring/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./MonitoringTab";
+export { default as MonitoringTab } from "./MonitoringTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx b/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx
similarity index 99%
rename from fincept-terminal-desktop/src/components/tabs/NewsTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx
index 3af5a1ce2..7ca5ba75e 100644
--- a/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/news/NewsTab.tsx
@@ -1,14 +1,14 @@
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Info, Settings } from 'lucide-react';
import { useTerminalTheme } from '@/contexts/ThemeContext';
-import { fetchAllNews, type NewsArticle, getRSSFeedCount, getActiveSources, isUsingMockData, setNewsCacheTTL, invalidateNewsCache } from '../../services/news/newsService';
-import { contextRecorderService } from '../../services/data-sources/contextRecorderService';
-import RecordingControlPanel from '../common/RecordingControlPanel';
-import { TimezoneSelector } from '../common/TimezoneSelector';
+import { fetchAllNews, type NewsArticle, getRSSFeedCount, getActiveSources, isUsingMockData, setNewsCacheTTL, invalidateNewsCache } from '@/services/news/newsService';
+import { contextRecorderService } from '@/services/data-sources/contextRecorderService';
+import RecordingControlPanel from '@/components/common/RecordingControlPanel';
+import { TimezoneSelector } from '@/components/common/TimezoneSelector';
import { useTranslation } from 'react-i18next';
-import { analyzeNewsArticle, type NewsAnalysisData, getSentimentColor, getUrgencyColor, getRiskColor } from '../../services/news/newsAnalysisService';
-import { createNewsTabTour } from './tours/newsTabTour';
-import RSSFeedSettingsModal from './news/RSSFeedSettingsModal';
+import { analyzeNewsArticle, type NewsAnalysisData, getSentimentColor, getUrgencyColor, getRiskColor } from '@/services/news/newsAnalysisService';
+import { createNewsTabTour } from '@/components/tabs/tours/newsTabTour';
+import RSSFeedSettingsModal from './RSSFeedSettingsModal';
// Extend Window interface for Tauri
declare global {
diff --git a/fincept-terminal-desktop/src/components/tabs/news/index.ts b/fincept-terminal-desktop/src/components/tabs/news/index.ts
new file mode 100644
index 000000000..950c48886
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/news/index.ts
@@ -0,0 +1,3 @@
+export { default } from "./NewsTab";
+export { default as NewsTab } from "./NewsTab";
+export { default as RSSFeedSettingsModal } from "./RSSFeedSettingsModal";
diff --git a/fincept-terminal-desktop/src/components/tabs/node-editor/index.ts b/fincept-terminal-desktop/src/components/tabs/node-editor/index.ts
new file mode 100644
index 000000000..c12aaab59
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/node-editor/index.ts
@@ -0,0 +1 @@
+export { default } from "../ai-quant-lab/NodeEditorTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/NotesTab.tsx b/fincept-terminal-desktop/src/components/tabs/notes/NotesTab.tsx
new file mode 100644
index 000000000..ba8d8d2fa
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/NotesTab.tsx
@@ -0,0 +1,290 @@
+// Notes Tab - Main Component
+// Professional Fincept Terminal-Grade Financial Note-Taking Interface
+
+import React, { useState, useEffect, useCallback } from 'react';
+import { ChevronRight, ChevronDown } from 'lucide-react';
+import { notesService, Note, NoteTemplate } from '../../../services/core/notesService';
+import { noteReminderService } from '../../../services/core/noteReminderService.tsx';
+import { toast } from 'sonner';
+import { TabFooter } from '@/components/common/TabFooter';
+import { useTranslation } from 'react-i18next';
+
+import { FINCEPT } from './constants';
+import type { NoteStatistics, UpcomingReminder, EditorState, FilterState } from './types';
+import { useNotes } from './hooks/useNotes';
+import { useNoteEditor } from './hooks/useNoteEditor';
+import {
+ Header,
+ Toolbar,
+ FiltersPanel,
+ TemplatesPanel,
+ RemindersPanel,
+ CategorySidebar,
+ NotesList,
+ NoteEditor,
+ NoteViewer
+} from './components';
+
+export function NotesTab() {
+ const { t } = useTranslation('notes');
+ const [currentTime, setCurrentTime] = useState(new Date());
+
+ // UI State
+ const [showTemplates, setShowTemplates] = useState(false);
+ const [showFilters, setShowFilters] = useState(false);
+ const [showReminders, setShowReminders] = useState(false);
+ const [isRightPanelMinimized, setIsRightPanelMinimized] = useState(false);
+
+ // Use custom hooks
+ const {
+ notes,
+ filteredNotes,
+ templates,
+ statistics,
+ selectedCategory,
+ selectedNote,
+ setSelectedNote,
+ upcomingReminders,
+ filters,
+ setFilters,
+ searchQuery,
+ setSearchQuery,
+ loadNotes,
+ loadUpcomingReminders,
+ loadStatistics,
+ handleDeleteNote,
+ handleToggleFavorite,
+ handleToggleArchive,
+ setSelectedCategory
+ } = useNotes();
+
+ const {
+ isEditing,
+ isCreating,
+ editorState,
+ updateField,
+ startEditing,
+ startCreating,
+ createFromTemplate,
+ handleSave,
+ handleCancel
+ } = useNoteEditor({
+ selectedNote,
+ setSelectedNote,
+ loadNotes,
+ loadUpcomingReminders,
+ loadStatistics
+ });
+
+ // Update time
+ useEffect(() => {
+ const timer = setInterval(() => setCurrentTime(new Date()), 1000);
+ return () => clearInterval(timer);
+ }, []);
+
+ // Initialize reminder service
+ useEffect(() => {
+ noteReminderService.start();
+ loadUpcomingReminders();
+
+ const handleOpenNote = async (event: CustomEvent) => {
+ const { noteId } = event.detail;
+ const note = await notesService.getNoteById(noteId);
+ if (note) {
+ setSelectedNote(note);
+ toast.success('Note opened from reminder');
+ }
+ };
+
+ window.addEventListener('openNote', handleOpenNote as unknown as EventListener);
+ return () => {
+ window.removeEventListener('openNote', handleOpenNote as unknown as EventListener);
+ };
+ }, []);
+
+ const handleRefresh = useCallback(() => {
+ loadNotes();
+ loadUpcomingReminders();
+ }, [loadNotes, loadUpcomingReminders]);
+
+ const handleTemplateSelect = (template: NoteTemplate) => {
+ createFromTemplate(template);
+ setShowTemplates(false);
+ };
+
+ const handleStartEditing = (note: Note) => {
+ startEditing(note);
+ };
+
+ const handleStartCreating = () => {
+ startCreating();
+ };
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: FINCEPT.DARK_BG,
+ color: FINCEPT.WHITE,
+ fontFamily: '"IBM Plex Mono", "Consolas", monospace',
+ overflow: 'hidden',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ <style>{`
+ @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600;700&display=swap');
+
+ *::-webkit-scrollbar { width: 6px; height: 6px; }
+ *::-webkit-scrollbar-track { background: ${FINCEPT.DARK_BG}; }
+ *::-webkit-scrollbar-thumb { background: ${FINCEPT.BORDER}; border-radius: 3px; }
+ *::-webkit-scrollbar-thumb:hover { background: ${FINCEPT.MUTED}; }
+
+ .terminal-glow {
+ text-shadow: 0 0 10px ${FINCEPT.ORANGE}40;
+ }
+ `}</style>
+
+ {/* Header */}
+ <Header
+ statistics={statistics}
+ currentTime={currentTime}
+ upcomingReminders={upcomingReminders}
+ showReminders={showReminders}
+ onRefresh={handleRefresh}
+ onToggleReminders={() => setShowReminders(!showReminders)}
+ />
+
+ {/* Toolbar */}
+ <Toolbar
+ searchQuery={searchQuery}
+ showFavorites={filters.showFavorites}
+ showArchived={filters.showArchived}
+ showFilters={showFilters}
+ onSearchChange={setSearchQuery}
+ onToggleFavorites={() => setFilters({ ...filters, showFavorites: !filters.showFavorites })}
+ onToggleArchived={() => setFilters({ ...filters, showArchived: !filters.showArchived })}
+ onToggleFilters={() => setShowFilters(!showFilters)}
+ onShowTemplates={() => setShowTemplates(!showTemplates)}
+ onCreateNew={handleStartCreating}
+ />
+
+ {/* Filters Panel */}
+ {showFilters && (
+ <FiltersPanel
+ filterPriority={filters.filterPriority}
+ filterSentiment={filters.filterSentiment}
+ onPriorityChange={(priority: string | null) => setFilters({ ...filters, filterPriority: priority })}
+ onSentimentChange={(sentiment: string | null) => setFilters({ ...filters, filterSentiment: sentiment })}
+ onClearFilters={() => setFilters({ ...filters, filterPriority: null, filterSentiment: null })}
+ />
+ )}
+
+ {/* Templates Panel */}
+ {showTemplates && (
+ <TemplatesPanel
+ templates={templates}
+ onSelectTemplate={handleTemplateSelect}
+ />
+ )}
+
+ {/* Reminders Panel */}
+ {showReminders && (
+ <RemindersPanel
+ upcomingReminders={upcomingReminders}
+ onRefresh={loadUpcomingReminders}
+ onSelectNote={(note) => {
+ setSelectedNote(note);
+ setShowReminders(false);
+ }}
+ onClose={() => setShowReminders(false)}
+ />
+ )}
+
+ {/* Main Content */}
+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
+ {/* Category Sidebar */}
+ <CategorySidebar
+ selectedCategory={selectedCategory}
+ statistics={statistics}
+ onSelectCategory={setSelectedCategory}
+ />
+
+ {/* Notes List */}
+ <div style={{
+ width: '320px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ <NotesList
+ notes={filteredNotes}
+ selectedNote={selectedNote}
+ onSelectNote={setSelectedNote}
+ />
+ </div>
+
+ {/* Right Panel - Note Content Area */}
+ {!isRightPanelMinimized && (
+ <div style={{
+ flex: 1,
+ backgroundColor: FINCEPT.PANEL_BG,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ {isCreating || isEditing ? (
+ <NoteEditor
+ isCreating={isCreating}
+ editorState={editorState}
+ onUpdateField={updateField}
+ onSave={handleSave}
+ onCancel={handleCancel}
+ />
+ ) : (
+ <NoteViewer
+ selectedNote={selectedNote}
+ onToggleFavorite={handleToggleFavorite}
+ onStartEditing={handleStartEditing}
+ onToggleArchive={handleToggleArchive}
+ onDelete={handleDeleteNote}
+ />
+ )}
+ </div>
+ )}
+
+ {/* Minimize/Maximize Toggle for Right Panel */}
+ <div style={{
+ width: '20px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderLeft: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ cursor: 'pointer'
+ }}
+ onClick={() => setIsRightPanelMinimized(!isRightPanelMinimized)}
+ >
+ {isRightPanelMinimized ? <ChevronRight size={14} color={FINCEPT.GRAY} /> : <ChevronDown size={14} color={FINCEPT.GRAY} />}
+ </div>
+ </div>
+
+ {/* Status Bar */}
+ <TabFooter
+ tabName="FINANCIAL NOTES"
+ leftInfo={[
+ { label: 'Professional Note-Taking', color: FINCEPT.GRAY },
+ ]}
+ statusInfo={
+ <span>
+ Notes: <span style={{ color: FINCEPT.ORANGE }}>{statistics?.total || 0}</span> |
+ Category: <span style={{ color: FINCEPT.CYAN }}>{selectedCategory}</span> |
+ Displayed: <span style={{ color: FINCEPT.YELLOW }}>{filteredNotes.length}</span>
+ </span>
+ }
+ backgroundColor={FINCEPT.HEADER_BG}
+ borderColor={FINCEPT.BORDER}
+ />
+ </div>
+ );
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/components/CategorySidebar.tsx b/fincept-terminal-desktop/src/components/tabs/notes/components/CategorySidebar.tsx
new file mode 100644
index 000000000..f0442eadf
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/components/CategorySidebar.tsx
@@ -0,0 +1,95 @@
+// Notes Tab Category Sidebar Component
+
+import React from 'react';
+import { FINCEPT, CATEGORIES } from '../constants';
+import type { NoteStatistics } from '../types';
+
+interface CategorySidebarProps {
+ selectedCategory: string;
+ statistics: NoteStatistics | null;
+ onSelectCategory: (categoryId: string) => void;
+}
+
+export const CategorySidebar: React.FC<CategorySidebarProps> = ({
+ selectedCategory,
+ statistics,
+ onSelectCategory
+}) => {
+ return (
+ <div style={{
+ width: '220px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderRight: `1px solid ${FINCEPT.BORDER}`,
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden'
+ }}>
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '10px',
+ fontWeight: 700,
+ color: FINCEPT.ORANGE,
+ letterSpacing: '0.5px'
+ }}>
+ CATEGORIES
+ </div>
+
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ {CATEGORIES.map(category => {
+ const Icon = category.icon;
+ const count = statistics?.byCategory?.find((s: any) => s.category === category.id)?.count || 0;
+ const isSelected = selectedCategory === category.id;
+
+ return (
+ <div
+ key={category.id}
+ onClick={() => onSelectCategory(category.id)}
+ style={{
+ padding: '10px 12px',
+ cursor: 'pointer',
+ backgroundColor: isSelected ? `${FINCEPT.ORANGE}20` : 'transparent',
+ borderLeft: isSelected ? `3px solid ${FINCEPT.ORANGE}` : '3px solid transparent',
+ transition: 'all 0.2s',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between'
+ }}
+ onMouseEnter={(e) => {
+ if (!isSelected) {
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (!isSelected) {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ }
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Icon size={14} color={isSelected ? FINCEPT.ORANGE : FINCEPT.GRAY} />
+ <span style={{
+ fontSize: '10px',
+ fontWeight: 600,
+ color: isSelected ? FINCEPT.ORANGE : FINCEPT.WHITE
+ }}>
+ {category.label}
+ </span>
+ </div>
+ {category.id !== 'ALL' && (
+ <span style={{
+ fontSize: '9px',
+ color: FINCEPT.CYAN,
+ fontWeight: 700
+ }}>
+ {count}
+ </span>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/components/FiltersPanel.tsx b/fincept-terminal-desktop/src/components/tabs/notes/components/FiltersPanel.tsx
new file mode 100644
index 000000000..ebd3a8310
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/components/FiltersPanel.tsx
@@ -0,0 +1,95 @@
+// Notes Tab Filters Panel Component
+
+import React from 'react';
+import { FINCEPT, PRIORITIES, SENTIMENTS, getPriorityColor, getSentimentColor } from '../constants';
+
+interface FiltersPanelProps {
+ filterPriority: string | null;
+ filterSentiment: string | null;
+ onPriorityChange: (priority: string | null) => void;
+ onSentimentChange: (sentiment: string | null) => void;
+ onClearFilters: () => void;
+}
+
+export const FiltersPanel: React.FC<FiltersPanelProps> = ({
+ filterPriority,
+ filterSentiment,
+ onPriorityChange,
+ onSentimentChange,
+ onClearFilters
+}) => {
+ return (
+ <div style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ padding: '8px 12px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '16px',
+ flexShrink: 0,
+ fontSize: '10px'
+ }}>
+ <span style={{ color: FINCEPT.ORANGE, fontWeight: 700 }}>FILTERS:</span>
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <span style={{ color: FINCEPT.GRAY }}>Priority:</span>
+ {PRIORITIES.map(priority => (
+ <button
+ key={priority}
+ onClick={() => onPriorityChange(filterPriority === priority ? null : priority)}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: filterPriority === priority ? getPriorityColor(priority) : FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: filterPriority === priority ? FINCEPT.DARK_BG : getPriorityColor(priority),
+ cursor: 'pointer',
+ fontSize: '9px',
+ fontWeight: 700
+ }}
+ >
+ {priority}
+ </button>
+ ))}
+ </div>
+
+ <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <span style={{ color: FINCEPT.GRAY }}>Sentiment:</span>
+ {SENTIMENTS.map(sentiment => (
+ <button
+ key={sentiment}
+ onClick={() => onSentimentChange(filterSentiment === sentiment ? null : sentiment)}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: filterSentiment === sentiment ? getSentimentColor(sentiment) : FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: filterSentiment === sentiment ? FINCEPT.DARK_BG : getSentimentColor(sentiment),
+ cursor: 'pointer',
+ fontSize: '9px',
+ fontWeight: 700
+ }}
+ >
+ {sentiment}
+ </button>
+ ))}
+ </div>
+
+ <button
+ onClick={onClearFilters}
+ style={{
+ marginLeft: 'auto',
+ padding: '4px 8px',
+ backgroundColor: FINCEPT.RED,
+ border: 'none',
+ color: FINCEPT.WHITE,
+ cursor: 'pointer',
+ fontSize: '9px',
+ fontWeight: 700
+ }}
+ >
+ CLEAR FILTERS
+ </button>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/components/Header.tsx b/fincept-terminal-desktop/src/components/tabs/notes/components/Header.tsx
new file mode 100644
index 000000000..4d1b86b48
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/components/Header.tsx
@@ -0,0 +1,127 @@
+// Notes Tab Header Component
+
+import React from 'react';
+import { FileText, Clock, RefreshCw, Bell } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { FINCEPT } from '../constants';
+import type { NoteStatistics } from '../types';
+
+interface HeaderProps {
+ statistics: NoteStatistics | null;
+ currentTime: Date;
+ upcomingReminders: Array<{ note: any; hoursUntil: number }>;
+ showReminders: boolean;
+ onRefresh: () => void;
+ onToggleReminders: () => void;
+}
+
+export const Header: React.FC<HeaderProps> = ({
+ statistics,
+ currentTime,
+ upcomingReminders,
+ showReminders,
+ onRefresh,
+ onToggleReminders
+}) => {
+ const upcomingRemindersCount = upcomingReminders.length;
+ const { t } = useTranslation('notes');
+
+ return (
+ <div style={{
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `2px solid ${FINCEPT.ORANGE}`,
+ padding: '6px 12px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ flexShrink: 0,
+ boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20`
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <FileText size={18} color={FINCEPT.ORANGE} style={{ filter: `drop-shadow(0 0 4px ${FINCEPT.ORANGE})` }} />
+ <span style={{
+ color: FINCEPT.ORANGE,
+ fontWeight: 700,
+ fontSize: '14px',
+ letterSpacing: '0.5px',
+ textShadow: `0 0 10px ${FINCEPT.ORANGE}40`
+ }}>
+ {t('title')}
+ </span>
+ </div>
+
+ <div style={{ height: '16px', width: '1px', backgroundColor: FINCEPT.BORDER }} />
+
+ {statistics && (
+ <>
+ <div style={{ fontSize: '10px', color: FINCEPT.CYAN }}>
+ {t('header.total')}: <span style={{ fontWeight: 700 }}>{statistics.total}</span>
+ </div>
+ <div style={{ fontSize: '10px', color: FINCEPT.YELLOW }}>
+ {t('header.favorites')}: <span style={{ fontWeight: 700 }}>{statistics.favorites}</span>
+ </div>
+ <div style={{ fontSize: '10px', color: FINCEPT.PURPLE }}>
+ {t('header.words')}: <span style={{ fontWeight: 700 }}>{statistics.totalWords.toLocaleString()}</span>
+ </div>
+ </>
+ )}
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '10px', color: FINCEPT.CYAN }}>
+ <Clock size={12} />
+ {currentTime.toLocaleTimeString('en-US', { hour12: false })}
+ </div>
+
+ <button
+ onClick={onRefresh}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ fontSize: '10px',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ e.currentTarget.style.color = FINCEPT.ORANGE;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.color = FINCEPT.GRAY;
+ }}
+ >
+ <RefreshCw size={12} />
+ {t('header.refresh')}
+ </button>
+
+ <button
+ onClick={onToggleReminders}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: showReminders ? FINCEPT.YELLOW : 'transparent',
+ border: `1px solid ${upcomingRemindersCount > 0 ? FINCEPT.YELLOW : FINCEPT.BORDER}`,
+ color: showReminders ? FINCEPT.DARK_BG : upcomingRemindersCount > 0 ? FINCEPT.YELLOW : FINCEPT.GRAY,
+ cursor: 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ fontSize: '10px',
+ fontWeight: 700,
+ transition: 'all 0.2s'
+ }}
+ title="View upcoming reminders"
+ >
+ <Bell size={12} />
+ {upcomingRemindersCount > 0 && `(${upcomingRemindersCount})`}
+ </button>
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/components/NoteEditor.tsx b/fincept-terminal-desktop/src/components/tabs/notes/components/NoteEditor.tsx
new file mode 100644
index 000000000..a49f4e86f
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/components/NoteEditor.tsx
@@ -0,0 +1,290 @@
+// Notes Tab Note Editor Component
+
+import React from 'react';
+import { Save, X } from 'lucide-react';
+import { FINCEPT, CATEGORIES, PRIORITIES, SENTIMENTS, COLOR_CODES } from '../constants';
+import type { EditorState } from '../types';
+
+interface NoteEditorProps {
+ isCreating: boolean;
+ editorState: EditorState;
+ onUpdateField: <K extends keyof EditorState>(field: K, value: EditorState[K]) => void;
+ onSave: () => void;
+ onCancel: () => void;
+}
+
+export const NoteEditor: React.FC<NoteEditorProps> = ({
+ isCreating,
+ editorState,
+ onUpdateField,
+ onSave,
+ onCancel
+}) => {
+ return (
+ <>
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '10px',
+ fontWeight: 700,
+ color: FINCEPT.ORANGE,
+ letterSpacing: '0.5px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}>
+ <span>{isCreating ? 'CREATE NOTE' : 'EDIT NOTE'}</span>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ <button
+ onClick={onSave}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: FINCEPT.GREEN,
+ border: 'none',
+ color: FINCEPT.DARK_BG,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Save size={12} />
+ SAVE
+ </button>
+ <button
+ onClick={onCancel}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: FINCEPT.RED,
+ border: 'none',
+ color: FINCEPT.WHITE,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <X size={12} />
+ CANCEL
+ </button>
+ </div>
+ </div>
+
+ <div style={{ flex: 1, overflow: 'auto', padding: '12px' }}>
+ {/* Title */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
+ TITLE *
+ </label>
+ <input
+ type="text"
+ value={editorState.title}
+ onChange={(e) => onUpdateField('title', e.target.value)}
+ style={{
+ width: '100%',
+ padding: '8px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ fontSize: '12px',
+ fontWeight: 700,
+ outline: 'none'
+ }}
+ placeholder="Enter note title..."
+ />
+ </div>
+
+ {/* Metadata Row 1 */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '12px' }}>
+ <div>
+ <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
+ CATEGORY
+ </label>
+ <select
+ value={editorState.category}
+ onChange={(e) => onUpdateField('category', e.target.value)}
+ style={{
+ width: '100%',
+ padding: '6px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ fontSize: '10px',
+ outline: 'none'
+ }}
+ >
+ {CATEGORIES.filter(c => c.id !== 'ALL').map(cat => (
+ <option key={cat.id} value={cat.id}>{cat.label}</option>
+ ))}
+ </select>
+ </div>
+
+ <div>
+ <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
+ PRIORITY
+ </label>
+ <select
+ value={editorState.priority}
+ onChange={(e) => onUpdateField('priority', e.target.value)}
+ style={{
+ width: '100%',
+ padding: '6px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ fontSize: '10px',
+ outline: 'none'
+ }}
+ >
+ {PRIORITIES.map(p => (
+ <option key={p} value={p}>{p}</option>
+ ))}
+ </select>
+ </div>
+ </div>
+
+ {/* Metadata Row 2 */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '12px' }}>
+ <div>
+ <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
+ SENTIMENT
+ </label>
+ <select
+ value={editorState.sentiment}
+ onChange={(e) => onUpdateField('sentiment', e.target.value)}
+ style={{
+ width: '100%',
+ padding: '6px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ fontSize: '10px',
+ outline: 'none'
+ }}
+ >
+ {SENTIMENTS.map(s => (
+ <option key={s} value={s}>{s}</option>
+ ))}
+ </select>
+ </div>
+
+ <div>
+ <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
+ COLOR
+ </label>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {COLOR_CODES.map(color => (
+ <div
+ key={color}
+ onClick={() => onUpdateField('colorCode', color)}
+ style={{
+ width: '24px',
+ height: '24px',
+ backgroundColor: color,
+ border: editorState.colorCode === color ? `2px solid ${FINCEPT.WHITE}` : `1px solid ${FINCEPT.BORDER}`,
+ cursor: 'pointer'
+ }}
+ />
+ ))}
+ </div>
+ </div>
+ </div>
+
+ {/* Tags */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
+ TAGS (comma-separated)
+ </label>
+ <input
+ type="text"
+ value={editorState.tags}
+ onChange={(e) => onUpdateField('tags', e.target.value)}
+ style={{
+ width: '100%',
+ padding: '6px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ fontSize: '10px',
+ outline: 'none'
+ }}
+ placeholder="growth, tech, semiconductor"
+ />
+ </div>
+
+ {/* Tickers */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
+ TICKERS (comma-separated)
+ </label>
+ <input
+ type="text"
+ value={editorState.tickers}
+ onChange={(e) => onUpdateField('tickers', e.target.value)}
+ style={{
+ width: '100%',
+ padding: '6px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ fontSize: '10px',
+ outline: 'none'
+ }}
+ placeholder="AAPL, MSFT, NVDA"
+ />
+ </div>
+
+ {/* Reminder Date */}
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
+ REMINDER DATE
+ </label>
+ <input
+ type="datetime-local"
+ value={editorState.reminderDate}
+ onChange={(e) => onUpdateField('reminderDate', e.target.value)}
+ style={{
+ width: '100%',
+ padding: '6px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ fontSize: '10px',
+ outline: 'none'
+ }}
+ />
+ </div>
+
+ {/* Content */}
+ <div>
+ <label style={{ color: FINCEPT.GRAY, fontSize: '9px', fontWeight: 700, marginBottom: '4px', display: 'block' }}>
+ CONTENT *
+ </label>
+ <textarea
+ value={editorState.content}
+ onChange={(e) => onUpdateField('content', e.target.value)}
+ style={{
+ width: '100%',
+ height: '400px',
+ padding: '8px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ fontSize: '11px',
+ lineHeight: '1.6',
+ outline: 'none',
+ resize: 'vertical',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}
+ placeholder="Write your note content here... Supports Markdown formatting."
+ />
+ </div>
+ </div>
+ </>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/components/NoteViewer.tsx b/fincept-terminal-desktop/src/components/tabs/notes/components/NoteViewer.tsx
new file mode 100644
index 000000000..795f86052
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/components/NoteViewer.tsx
@@ -0,0 +1,211 @@
+// Notes Tab Note Viewer Component
+
+import React from 'react';
+import { Star, Edit3, Archive, Trash2, FileText } from 'lucide-react';
+import { FINCEPT, getPriorityColor, getSentimentColor } from '../constants';
+import type { Note } from '../types';
+
+interface NoteViewerProps {
+ selectedNote: Note | null;
+ onToggleFavorite: (note: Note) => void;
+ onStartEditing: (note: Note) => void;
+ onToggleArchive: (note: Note) => void;
+ onDelete: (noteId: number) => void;
+}
+
+export const NoteViewer: React.FC<NoteViewerProps> = ({
+ selectedNote,
+ onToggleFavorite,
+ onStartEditing,
+ onToggleArchive,
+ onDelete
+}) => {
+ if (!selectedNote) {
+ return (
+ <div style={{
+ flex: 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: FINCEPT.GRAY,
+ fontSize: '11px',
+ flexDirection: 'column',
+ gap: '12px'
+ }}>
+ <FileText size={48} color={FINCEPT.MUTED} />
+ <div>Select a note to view or create a new one</div>
+ </div>
+ );
+ }
+
+ return (
+ <>
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '10px',
+ fontWeight: 700,
+ color: FINCEPT.ORANGE,
+ letterSpacing: '0.5px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}>
+ <span>NOTE DETAILS</span>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ <button
+ onClick={() => onToggleFavorite(selectedNote)}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: selectedNote.is_favorite ? FINCEPT.YELLOW : FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '10px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Star size={12} fill={selectedNote.is_favorite ? FINCEPT.YELLOW : 'none'} />
+ </button>
+ <button
+ onClick={() => onStartEditing(selectedNote)}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: FINCEPT.BLUE,
+ border: 'none',
+ color: FINCEPT.WHITE,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Edit3 size={12} />
+ EDIT
+ </button>
+ <button
+ onClick={() => onToggleArchive(selectedNote)}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: FINCEPT.PURPLE,
+ border: 'none',
+ color: FINCEPT.WHITE,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Archive size={12} />
+ {selectedNote.is_archived ? 'UNARCHIVE' : 'ARCHIVE'}
+ </button>
+ <button
+ onClick={() => onDelete(selectedNote.id!)}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: FINCEPT.RED,
+ border: 'none',
+ color: FINCEPT.WHITE,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Trash2 size={12} />
+ DELETE
+ </button>
+ </div>
+ </div>
+
+ <div style={{ flex: 1, overflow: 'auto', padding: '16px' }}>
+ {/* Title */}
+ <div style={{
+ color: FINCEPT.WHITE,
+ fontSize: '16px',
+ fontWeight: 700,
+ marginBottom: '12px',
+ paddingBottom: '12px',
+ borderBottom: `2px solid ${selectedNote.color_code}`
+ }}>
+ {selectedNote.title}
+ </div>
+
+ {/* Metadata */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr',
+ gap: '8px',
+ marginBottom: '16px',
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '9px'
+ }}>
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>CATEGORY: </span>
+ <span style={{ color: FINCEPT.CYAN, fontWeight: 700 }}>{selectedNote.category}</span>
+ </div>
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>PRIORITY: </span>
+ <span style={{ color: getPriorityColor(selectedNote.priority), fontWeight: 700 }}>{selectedNote.priority}</span>
+ </div>
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>SENTIMENT: </span>
+ <span style={{ color: getSentimentColor(selectedNote.sentiment), fontWeight: 700 }}>{selectedNote.sentiment}</span>
+ </div>
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>WORDS: </span>
+ <span style={{ color: FINCEPT.WHITE, fontWeight: 700 }}>{selectedNote.word_count}</span>
+ </div>
+ {selectedNote.tickers && (
+ <div style={{ gridColumn: '1 / -1' }}>
+ <span style={{ color: FINCEPT.GRAY }}>TICKERS: </span>
+ <span style={{ color: FINCEPT.CYAN, fontWeight: 700 }}>{selectedNote.tickers}</span>
+ </div>
+ )}
+ {selectedNote.tags && (
+ <div style={{ gridColumn: '1 / -1' }}>
+ <span style={{ color: FINCEPT.GRAY }}>TAGS: </span>
+ <span style={{ color: FINCEPT.PURPLE, fontWeight: 700 }}>{selectedNote.tags}</span>
+ </div>
+ )}
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>CREATED: </span>
+ <span style={{ color: FINCEPT.WHITE }}>{new Date(selectedNote.created_at).toLocaleString()}</span>
+ </div>
+ <div>
+ <span style={{ color: FINCEPT.GRAY }}>UPDATED: </span>
+ <span style={{ color: FINCEPT.WHITE }}>{new Date(selectedNote.updated_at).toLocaleString()}</span>
+ </div>
+ {selectedNote.reminder_date && (
+ <div style={{ gridColumn: '1 / -1' }}>
+ <span style={{ color: FINCEPT.GRAY }}>REMINDER: </span>
+ <span style={{ color: FINCEPT.YELLOW, fontWeight: 700 }}>{new Date(selectedNote.reminder_date).toLocaleString()}</span>
+ </div>
+ )}
+ </div>
+
+ {/* Content */}
+ <div style={{
+ color: FINCEPT.WHITE,
+ fontSize: '11px',
+ lineHeight: '1.8',
+ whiteSpace: 'pre-wrap',
+ fontFamily: '"IBM Plex Mono", monospace'
+ }}>
+ {selectedNote.content}
+ </div>
+ </div>
+ </>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/components/NotesList.tsx b/fincept-terminal-desktop/src/components/tabs/notes/components/NotesList.tsx
new file mode 100644
index 000000000..2e473cfb9
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/components/NotesList.tsx
@@ -0,0 +1,142 @@
+// Notes Tab Notes List Component
+
+import React from 'react';
+import { Star, Tag } from 'lucide-react';
+import { FINCEPT, getPriorityColor, getSentimentColor } from '../constants';
+import type { Note } from '../types';
+
+interface NotesListProps {
+ notes: Note[];
+ selectedNote: Note | null;
+ onSelectNote: (note: Note) => void;
+}
+
+export const NotesList: React.FC<NotesListProps> = ({
+ notes,
+ selectedNote,
+ onSelectNote
+}) => {
+ return (
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
+ <div style={{
+ padding: '8px 12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ fontSize: '10px',
+ fontWeight: 700,
+ color: FINCEPT.ORANGE,
+ letterSpacing: '0.5px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center'
+ }}>
+ <span>NOTES ({notes.length})</span>
+ <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>
+ SORTED BY: RECENTLY UPDATED
+ </span>
+ </div>
+
+ <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>
+ {notes.length === 0 ? (
+ <div style={{
+ padding: '40px',
+ textAlign: 'center',
+ color: FINCEPT.GRAY,
+ fontSize: '11px'
+ }}>
+ No notes found. Create your first note!
+ </div>
+ ) : (
+ notes.map(note => (
+ <NoteItem
+ key={note.id}
+ note={note}
+ isSelected={selectedNote?.id === note.id}
+ onSelect={() => onSelectNote(note)}
+ />
+ ))
+ )}
+ </div>
+ </div>
+ );
+};
+
+interface NoteItemProps {
+ note: Note;
+ isSelected: boolean;
+ onSelect: () => void;
+}
+
+const NoteItem: React.FC<NoteItemProps> = ({ note, isSelected, onSelect }) => {
+ return (
+ <div
+ onClick={onSelect}
+ style={{
+ marginBottom: '8px',
+ padding: '12px',
+ backgroundColor: isSelected ? `${FINCEPT.ORANGE}15` : FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ borderLeft: `4px solid ${note.color_code}`,
+ cursor: 'pointer',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ if (!isSelected) {
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ }
+ }}
+ onMouseLeave={(e) => {
+ if (!isSelected) {
+ e.currentTarget.style.backgroundColor = FINCEPT.HEADER_BG;
+ }
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', flex: 1 }}>
+ <span style={{ color: FINCEPT.WHITE, fontSize: '11px', fontWeight: 700 }}>
+ {note.title}
+ </span>
+ {note.is_favorite && <Star size={12} fill={FINCEPT.YELLOW} color={FINCEPT.YELLOW} />}
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <span style={{
+ padding: '2px 6px',
+ backgroundColor: getPriorityColor(note.priority),
+ color: FINCEPT.DARK_BG,
+ fontSize: '8px',
+ fontWeight: 700
+ }}>
+ {note.priority}
+ </span>
+ <span style={{
+ padding: '2px 6px',
+ backgroundColor: getSentimentColor(note.sentiment),
+ color: FINCEPT.DARK_BG,
+ fontSize: '8px',
+ fontWeight: 700
+ }}>
+ {note.sentiment}
+ </span>
+ </div>
+ </div>
+
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', lineHeight: '1.4', marginBottom: '6px' }}>
+ {note.content.substring(0, 120)}{note.content.length > 120 ? '...' : ''}
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: '8px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', color: FINCEPT.MUTED }}>
+ <span>{new Date(note.updated_at).toLocaleDateString()}</span>
+ {note.word_count > 0 && <span>{note.word_count} words</span>}
+ {note.tickers && <span style={{ color: FINCEPT.CYAN }}>{note.tickers}</span>}
+ </div>
+ {note.tags && (
+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
+ <Tag size={10} color={FINCEPT.PURPLE} />
+ <span style={{ color: FINCEPT.PURPLE }}>{note.tags.split(',').slice(0, 2).join(', ')}</span>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/components/RemindersPanel.tsx b/fincept-terminal-desktop/src/components/tabs/notes/components/RemindersPanel.tsx
new file mode 100644
index 000000000..fee8d0b65
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/components/RemindersPanel.tsx
@@ -0,0 +1,138 @@
+// Notes Tab Reminders Panel Component
+
+import React from 'react';
+import { Bell, RefreshCw } from 'lucide-react';
+import { toast } from 'sonner';
+import { FINCEPT, getPriorityColor, getSentimentColor } from '../constants';
+import type { UpcomingReminder, Note } from '../types';
+
+interface RemindersPanelProps {
+ upcomingReminders: UpcomingReminder[];
+ onRefresh: () => Promise<void>;
+ onSelectNote: (note: Note) => void;
+ onClose: () => void;
+}
+
+export const RemindersPanel: React.FC<RemindersPanelProps> = ({
+ upcomingReminders,
+ onRefresh,
+ onSelectNote,
+ onClose
+}) => {
+ const handleRefresh = async () => {
+ await onRefresh();
+ toast.success('Reminders refreshed');
+ };
+
+ return (
+ <div style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ padding: '12px',
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
+ <div style={{ color: FINCEPT.YELLOW, fontSize: '11px', fontWeight: 700, display: 'flex', alignItems: 'center', gap: '6px' }}>
+ <Bell size={14} />
+ UPCOMING REMINDERS (24H)
+ </div>
+ <button
+ onClick={handleRefresh}
+ style={{
+ padding: '4px 8px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '9px',
+ fontWeight: 700,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <RefreshCw size={10} />
+ REFRESH
+ </button>
+ </div>
+
+ {upcomingReminders.length === 0 ? (
+ <div style={{
+ padding: '20px',
+ textAlign: 'center',
+ color: FINCEPT.GRAY,
+ fontSize: '10px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`
+ }}>
+ No upcoming reminders in the next 24 hours
+ </div>
+ ) : (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
+ {upcomingReminders.map(({ note, hoursUntil }) => {
+ const isUrgent = hoursUntil < 1;
+ const minutesUntil = Math.round(hoursUntil * 60);
+ const timeText = hoursUntil < 1
+ ? `${minutesUntil} minute${minutesUntil !== 1 ? 's' : ''}`
+ : `${Math.round(hoursUntil)} hour${Math.round(hoursUntil) !== 1 ? 's' : ''}`;
+
+ return (
+ <div
+ key={note.id}
+ onClick={() => {
+ onSelectNote(note);
+ onClose();
+ }}
+ style={{
+ padding: '10px',
+ backgroundColor: isUrgent ? `${FINCEPT.RED}10` : FINCEPT.HEADER_BG,
+ border: `1px solid ${isUrgent ? FINCEPT.RED : FINCEPT.BORDER}`,
+ borderLeft: `4px solid ${note.color_code}`,
+ cursor: 'pointer',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = isUrgent ? `${FINCEPT.RED}10` : FINCEPT.HEADER_BG;
+ }}
+ >
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
+ <div style={{ color: FINCEPT.WHITE, fontSize: '11px', fontWeight: 700 }}>
+ {note.title}
+ </div>
+ <div style={{
+ padding: '2px 6px',
+ backgroundColor: isUrgent ? FINCEPT.RED : FINCEPT.YELLOW,
+ color: FINCEPT.DARK_BG,
+ fontSize: '8px',
+ fontWeight: 700
+ }}>
+ {isUrgent ? '🔴 URGENT' : ` ${timeText.toUpperCase()}`}
+ </div>
+ </div>
+ <div style={{ display: 'flex', gap: '8px', fontSize: '9px', color: FINCEPT.GRAY }}>
+ <span style={{ color: getPriorityColor(note.priority) }}>{note.priority}</span>
+ <span>•</span>
+ <span style={{ color: getSentimentColor(note.sentiment) }}>{note.sentiment}</span>
+ <span>•</span>
+ <span>{note.category}</span>
+ {note.tickers && (
+ <>
+ <span>•</span>
+ <span style={{ color: FINCEPT.CYAN }}>{note.tickers}</span>
+ </>
+ )}
+ </div>
+ <div style={{ fontSize: '8px', color: FINCEPT.MUTED, marginTop: '4px' }}>
+ Due: {new Date(note.reminder_date!).toLocaleString()}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/components/TemplatesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/notes/components/TemplatesPanel.tsx
new file mode 100644
index 000000000..d079c89bf
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/components/TemplatesPanel.tsx
@@ -0,0 +1,58 @@
+// Notes Tab Templates Panel Component
+
+import React from 'react';
+import { FINCEPT } from '../constants';
+import type { NoteTemplate } from '../types';
+
+interface TemplatesPanelProps {
+ templates: NoteTemplate[];
+ onSelectTemplate: (template: NoteTemplate) => void;
+}
+
+export const TemplatesPanel: React.FC<TemplatesPanelProps> = ({
+ templates,
+ onSelectTemplate
+}) => {
+ return (
+ <div style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ padding: '12px',
+ flexShrink: 0
+ }}>
+ <div style={{ color: FINCEPT.ORANGE, fontSize: '11px', fontWeight: 700, marginBottom: '8px' }}>
+ SELECT TEMPLATE
+ </div>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: '8px' }}>
+ {templates.map(template => (
+ <div
+ key={template.id}
+ onClick={() => onSelectTemplate(template)}
+ style={{
+ padding: '12px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ cursor: 'pointer',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.ORANGE;
+ e.currentTarget.style.backgroundColor = FINCEPT.HOVER;
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.borderColor = FINCEPT.BORDER;
+ e.currentTarget.style.backgroundColor = FINCEPT.HEADER_BG;
+ }}
+ >
+ <div style={{ color: FINCEPT.CYAN, fontSize: '11px', fontWeight: 700, marginBottom: '4px' }}>
+ {template.name}
+ </div>
+ <div style={{ color: FINCEPT.GRAY, fontSize: '9px', lineHeight: '1.4' }}>
+ {template.description}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/components/Toolbar.tsx b/fincept-terminal-desktop/src/components/tabs/notes/components/Toolbar.tsx
new file mode 100644
index 000000000..4415eab7d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/components/Toolbar.tsx
@@ -0,0 +1,162 @@
+// Notes Tab Toolbar Component
+
+import React from 'react';
+import { Search, Plus, BookOpen, Star, Filter, Archive } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { FINCEPT } from '../constants';
+
+interface ToolbarProps {
+ searchQuery: string;
+ showFavorites: boolean;
+ showArchived: boolean;
+ showFilters: boolean;
+ onSearchChange: (query: string) => void;
+ onToggleFavorites: () => void;
+ onToggleArchived: () => void;
+ onToggleFilters: () => void;
+ onShowTemplates: () => void;
+ onCreateNew: () => void;
+}
+
+export const Toolbar: React.FC<ToolbarProps> = ({
+ searchQuery,
+ showFavorites,
+ showArchived,
+ showFilters,
+ onSearchChange,
+ onToggleFavorites,
+ onToggleArchived,
+ onToggleFilters,
+ onShowTemplates,
+ onCreateNew
+}) => {
+ const { t } = useTranslation('notes');
+
+ return (
+ <div style={{
+ backgroundColor: FINCEPT.PANEL_BG,
+ borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ padding: '8px 12px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ flexShrink: 0
+ }}>
+ {/* Search */}
+ <div style={{ position: 'relative', flex: 1, maxWidth: '400px' }}>
+ <Search size={14} style={{ position: 'absolute', left: '8px', top: '50%', transform: 'translateY(-50%)', color: FINCEPT.GRAY }} />
+ <input
+ type="text"
+ placeholder={t('toolbar.search')}
+ value={searchQuery}
+ onChange={(e) => onSearchChange(e.target.value)}
+ style={{
+ width: '100%',
+ padding: '6px 8px 6px 32px',
+ backgroundColor: FINCEPT.HEADER_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.WHITE,
+ fontSize: '11px',
+ outline: 'none'
+ }}
+ />
+ </div>
+
+ {/* Action Buttons */}
+ <button
+ onClick={onCreateNew}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: FINCEPT.GREEN,
+ border: 'none',
+ color: FINCEPT.DARK_BG,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Plus size={14} />
+ {t('toolbar.newNote')}
+ </button>
+
+ <button
+ onClick={onShowTemplates}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <BookOpen size={14} />
+ {t('toolbar.templates')}
+ </button>
+
+ <button
+ onClick={onToggleFavorites}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: showFavorites ? FINCEPT.YELLOW : FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: showFavorites ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Star size={14} fill={showFavorites ? FINCEPT.DARK_BG : 'none'} />
+ {t('toolbar.favorites')}
+ </button>
+
+ <button
+ onClick={onToggleFilters}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: showFilters ? FINCEPT.CYAN : FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: showFilters ? FINCEPT.DARK_BG : FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Filter size={14} />
+ {t('toolbar.filters')}
+ </button>
+
+ <button
+ onClick={onToggleArchived}
+ style={{
+ padding: '6px 12px',
+ backgroundColor: showArchived ? FINCEPT.PURPLE : FINCEPT.PANEL_BG,
+ border: `1px solid ${FINCEPT.BORDER}`,
+ color: showArchived ? FINCEPT.WHITE : FINCEPT.GRAY,
+ cursor: 'pointer',
+ fontSize: '10px',
+ fontWeight: 700,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Archive size={14} />
+ {t('toolbar.archived')}
+ </button>
+ </div>
+ );
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/components/index.ts b/fincept-terminal-desktop/src/components/tabs/notes/components/index.ts
new file mode 100644
index 000000000..d2f76223d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/components/index.ts
@@ -0,0 +1,11 @@
+// Notes Tab Components barrel export
+
+export { Header } from './Header';
+export { Toolbar } from './Toolbar';
+export { FiltersPanel } from './FiltersPanel';
+export { TemplatesPanel } from './TemplatesPanel';
+export { RemindersPanel } from './RemindersPanel';
+export { CategorySidebar } from './CategorySidebar';
+export { NotesList } from './NotesList';
+export { NoteEditor } from './NoteEditor';
+export { NoteViewer } from './NoteViewer';
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/constants.ts b/fincept-terminal-desktop/src/components/tabs/notes/constants.ts
new file mode 100644
index 000000000..0749ec665
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/constants.ts
@@ -0,0 +1,87 @@
+// Notes Tab Constants
+
+import {
+ FileText, TrendingUp, BookOpen, PieChart,
+ DollarSign, Globe, Briefcase
+} from 'lucide-react';
+import type { Category } from './types';
+
+// Fincept Professional Color Palette
+export const FINCEPT = {
+ 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'
+} as const;
+
+export const CATEGORIES: Category[] = [
+ { id: 'ALL', label: 'ALL NOTES', icon: FileText },
+ { id: 'TRADE_IDEA', label: 'TRADE IDEAS', icon: TrendingUp },
+ { id: 'RESEARCH', label: 'RESEARCH', icon: BookOpen },
+ { id: 'MARKET_ANALYSIS', label: 'MARKET ANALYSIS', icon: PieChart },
+ { id: 'EARNINGS', label: 'EARNINGS', icon: DollarSign },
+ { id: 'ECONOMIC', label: 'ECONOMIC', icon: Globe },
+ { id: 'PORTFOLIO', label: 'PORTFOLIO', icon: Briefcase },
+ { id: 'GENERAL', label: 'GENERAL', icon: FileText }
+];
+
+export const PRIORITIES = ['HIGH', 'MEDIUM', 'LOW'] as const;
+export const SENTIMENTS = ['BULLISH', 'BEARISH', 'NEUTRAL'] as const;
+export const COLOR_CODES = ['#FF8800', '#00D66F', '#FF3B3B', '#00E5FF', '#FFD700', '#9D4EDD', '#0088FF'] as const;
+
+// Default editor values
+export const DEFAULT_EDITOR_STATE = {
+ title: '',
+ content: '',
+ category: 'GENERAL',
+ priority: 'MEDIUM',
+ sentiment: 'NEUTRAL',
+ tags: '',
+ tickers: '',
+ colorCode: '#FF8800',
+ reminderDate: ''
+};
+
+// Scrollbar styles
+export const SCROLLBAR_STYLES = `
+ @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600;700&display=swap');
+
+ *::-webkit-scrollbar { width: 6px; height: 6px; }
+ *::-webkit-scrollbar-track { background: ${FINCEPT.DARK_BG}; }
+ *::-webkit-scrollbar-thumb { background: ${FINCEPT.BORDER}; border-radius: 3px; }
+ *::-webkit-scrollbar-thumb:hover { background: ${FINCEPT.MUTED}; }
+
+ .terminal-glow {
+ text-shadow: 0 0 10px ${FINCEPT.ORANGE}40;
+ }
+`;
+
+// Helper functions
+export const getPriorityColor = (priority: string): string => {
+ switch (priority) {
+ case 'HIGH': return FINCEPT.RED;
+ case 'MEDIUM': return FINCEPT.YELLOW;
+ case 'LOW': return FINCEPT.GREEN;
+ default: return FINCEPT.GRAY;
+ }
+};
+
+export const getSentimentColor = (sentiment: string): string => {
+ switch (sentiment) {
+ case 'BULLISH': return FINCEPT.GREEN;
+ case 'BEARISH': return FINCEPT.RED;
+ case 'NEUTRAL': return FINCEPT.YELLOW;
+ default: return FINCEPT.GRAY;
+ }
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/notes/hooks/index.ts
new file mode 100644
index 000000000..af707c46e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/hooks/index.ts
@@ -0,0 +1,4 @@
+// Notes hooks barrel export
+
+export { useNotes } from './useNotes';
+export { useNoteEditor } from './useNoteEditor';
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/hooks/useNoteEditor.ts b/fincept-terminal-desktop/src/components/tabs/notes/hooks/useNoteEditor.ts
new file mode 100644
index 000000000..57177d8e1
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/hooks/useNoteEditor.ts
@@ -0,0 +1,220 @@
+// Hook for managing note editor state
+
+import { useState, useCallback } from 'react';
+import { notesService, Note, NoteTemplate } from '@/services/core/notesService';
+import { noteReminderService } from '@/services/core/noteReminderService.tsx';
+import { toast } from 'sonner';
+import type { EditorState } from '../types';
+import { DEFAULT_EDITOR_STATE } from '../constants';
+
+interface UseNoteEditorProps {
+ selectedNote: Note | null;
+ setSelectedNote: (note: Note | null) => void;
+ loadNotes: () => Promise<void>;
+ loadUpcomingReminders: () => Promise<void>;
+ loadStatistics: () => Promise<void>;
+}
+
+export interface UseNoteEditorReturn {
+ editorState: EditorState;
+ isEditing: boolean;
+ isCreating: boolean;
+ setEditorState: React.Dispatch<React.SetStateAction<EditorState>>;
+ setIsEditing: (editing: boolean) => void;
+ setIsCreating: (creating: boolean) => void;
+ updateField: <K extends keyof EditorState>(field: K, value: EditorState[K]) => void;
+ startEditing: (note: Note) => void;
+ startCreating: () => void;
+ createFromTemplate: (template: NoteTemplate) => void;
+ resetEditor: () => void;
+ handleSave: () => Promise<void>;
+ handleCancel: () => void;
+ buildNoteFromEditor: () => Omit<Note, 'id'>;
+}
+
+export function useNoteEditor({
+ selectedNote,
+ setSelectedNote,
+ loadNotes,
+ loadUpcomingReminders,
+ loadStatistics
+}: UseNoteEditorProps): UseNoteEditorReturn {
+ const [editorState, setEditorState] = useState<EditorState>(DEFAULT_EDITOR_STATE);
+ const [isEditing, setIsEditing] = useState(false);
+ const [isCreating, setIsCreating] = useState(false);
+
+ // Update a single field
+ const updateField = useCallback(<K extends keyof EditorState>(field: K, value: EditorState[K]) => {
+ setEditorState(prev => ({ ...prev, [field]: value }));
+ }, []);
+
+ // Reset editor to default state
+ const resetEditor = useCallback(() => {
+ setEditorState(DEFAULT_EDITOR_STATE);
+ }, []);
+
+ // Start editing an existing note
+ const startEditing = useCallback((note: Note) => {
+ setEditorState({
+ title: note.title,
+ content: note.content,
+ category: note.category,
+ priority: note.priority,
+ sentiment: note.sentiment,
+ tags: note.tags || '',
+ tickers: note.tickers || '',
+ colorCode: note.color_code,
+ reminderDate: note.reminder_date || ''
+ });
+ setSelectedNote(note);
+ setIsEditing(true);
+ setIsCreating(false);
+ }, [setSelectedNote]);
+
+ // Start creating a new note
+ const startCreating = useCallback(() => {
+ resetEditor();
+ setIsCreating(true);
+ setIsEditing(false);
+ }, [resetEditor]);
+
+ // Create from template
+ const createFromTemplate = useCallback((template: NoteTemplate) => {
+ setEditorState({
+ title: `New ${template.name}`,
+ content: template.content,
+ category: template.category,
+ priority: 'MEDIUM',
+ sentiment: 'NEUTRAL',
+ tags: '',
+ tickers: '',
+ colorCode: '#FF8800',
+ reminderDate: ''
+ });
+ setIsCreating(true);
+ setIsEditing(false);
+ }, []);
+
+ // Build note object from editor state
+ const buildNoteFromEditor = useCallback((): Omit<Note, 'id'> => {
+ const wordCount = editorState.content.trim().split(/\s+/).filter(w => w.length > 0).length;
+
+ return {
+ title: editorState.title,
+ content: editorState.content,
+ category: editorState.category,
+ priority: editorState.priority,
+ tags: editorState.tags,
+ tickers: editorState.tickers,
+ sentiment: editorState.sentiment,
+ is_favorite: false,
+ is_archived: false,
+ color_code: editorState.colorCode,
+ attachments: '[]',
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ reminder_date: editorState.reminderDate || null,
+ word_count: wordCount
+ };
+ }, [editorState]);
+
+ // Handle save - create or update note
+ const handleSave = useCallback(async () => {
+ if (!editorState.title.trim()) {
+ alert('Please enter a title');
+ return;
+ }
+
+ try {
+ const wordCount = editorState.content.trim().split(/\s+/).filter(w => w.length > 0).length;
+
+ if (isCreating) {
+ // Create new note
+ const newNote: Omit<Note, 'id'> = {
+ title: editorState.title,
+ content: editorState.content,
+ category: editorState.category,
+ priority: editorState.priority,
+ tags: editorState.tags,
+ tickers: editorState.tickers,
+ sentiment: editorState.sentiment,
+ is_favorite: false,
+ is_archived: false,
+ color_code: editorState.colorCode,
+ attachments: '[]',
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ reminder_date: editorState.reminderDate || null,
+ word_count: wordCount
+ };
+
+ await notesService.createNote(newNote);
+ await loadNotes();
+ await loadStatistics();
+ await loadUpcomingReminders();
+
+ if (editorState.reminderDate) {
+ toast.success(`Note created with reminder set for ${new Date(editorState.reminderDate).toLocaleString()}`);
+ }
+
+ resetEditor();
+ setIsCreating(false);
+ } else if (isEditing && selectedNote) {
+ // Update existing note
+ await notesService.updateNote(selectedNote.id!, {
+ title: editorState.title,
+ content: editorState.content,
+ category: editorState.category,
+ priority: editorState.priority,
+ tags: editorState.tags,
+ tickers: editorState.tickers,
+ sentiment: editorState.sentiment,
+ color_code: editorState.colorCode,
+ reminder_date: editorState.reminderDate || null,
+ word_count: wordCount
+ });
+
+ await loadNotes();
+ await loadStatistics();
+ await loadUpcomingReminders();
+
+ if (editorState.reminderDate) {
+ toast.success(`Reminder updated for ${new Date(editorState.reminderDate).toLocaleString()}`);
+ }
+
+ setIsEditing(false);
+
+ // Update selectedNote to reflect changes
+ const updatedNote = await notesService.getNoteById(selectedNote.id!);
+ setSelectedNote(updatedNote);
+ }
+ } catch (error) {
+ console.error('[useNoteEditor] Failed to save note:', error);
+ alert('Failed to save note');
+ }
+ }, [editorState, isCreating, isEditing, selectedNote, loadNotes, loadStatistics, loadUpcomingReminders, resetEditor, setSelectedNote]);
+
+ // Handle cancel
+ const handleCancel = useCallback(() => {
+ setIsEditing(false);
+ setIsCreating(false);
+ resetEditor();
+ }, [resetEditor]);
+
+ return {
+ editorState,
+ isEditing,
+ isCreating,
+ setEditorState,
+ setIsEditing,
+ setIsCreating,
+ updateField,
+ startEditing,
+ startCreating,
+ createFromTemplate,
+ resetEditor,
+ handleSave,
+ handleCancel,
+ buildNoteFromEditor
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/hooks/useNotes.ts b/fincept-terminal-desktop/src/components/tabs/notes/hooks/useNotes.ts
new file mode 100644
index 000000000..a8b5899ed
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/hooks/useNotes.ts
@@ -0,0 +1,253 @@
+// Hook for managing notes data
+
+import { useState, useEffect, useCallback } from 'react';
+import { notesService, Note, NoteTemplate } from '@/services/core/notesService';
+import { noteReminderService } from '@/services/core/noteReminderService.tsx';
+import { toast } from 'sonner';
+import type { NoteStatistics, UpcomingReminder, FilterState } from '../types';
+
+export interface UseNotesReturn {
+ notes: Note[];
+ filteredNotes: Note[];
+ templates: NoteTemplate[];
+ statistics: NoteStatistics | null;
+ upcomingReminders: UpcomingReminder[];
+ selectedNote: Note | null;
+ setSelectedNote: (note: Note | null) => void;
+ selectedCategory: string;
+ setSelectedCategory: (category: string) => void;
+ filters: FilterState;
+ setFilters: (filters: FilterState) => void;
+ searchQuery: string;
+ setSearchQuery: (query: string) => void;
+ loadNotes: () => Promise<void>;
+ loadTemplates: () => Promise<void>;
+ loadStatistics: () => Promise<void>;
+ loadUpcomingReminders: () => Promise<void>;
+ createNote: (note: Omit<Note, 'id'>) => Promise<void>;
+ updateNote: (id: number, updates: Partial<Note>) => Promise<void>;
+ handleDeleteNote: (id: number) => Promise<void>;
+ handleToggleFavorite: (note: Note) => Promise<void>;
+ handleToggleArchive: (note: Note) => Promise<void>;
+}
+
+export function useNotes(): UseNotesReturn {
+ const [notes, setNotes] = useState<Note[]>([]);
+ const [filteredNotes, setFilteredNotes] = useState<Note[]>([]);
+ const [templates, setTemplates] = useState<NoteTemplate[]>([]);
+ const [statistics, setStatistics] = useState<NoteStatistics | null>(null);
+ const [upcomingReminders, setUpcomingReminders] = useState<UpcomingReminder[]>([]);
+ const [selectedNote, setSelectedNote] = useState<Note | null>(null);
+ const [selectedCategory, setSelectedCategory] = useState('ALL');
+ const [searchQuery, setSearchQuery] = useState('');
+ const [filters, setFilters] = useState<FilterState>({
+ filterPriority: null,
+ filterSentiment: null,
+ showFavorites: false,
+ showArchived: false
+ });
+
+ // Apply filters to notes
+ const applyFilters = useCallback((notesToFilter: Note[]) => {
+ let filtered = [...notesToFilter];
+
+ if (searchQuery) {
+ filtered = filtered.filter(note =>
+ note.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
+ note.content.toLowerCase().includes(searchQuery.toLowerCase()) ||
+ note.tags?.toLowerCase().includes(searchQuery.toLowerCase()) ||
+ note.tickers?.toLowerCase().includes(searchQuery.toLowerCase())
+ );
+ }
+
+ if (filters.filterPriority) {
+ filtered = filtered.filter(note => note.priority === filters.filterPriority);
+ }
+
+ if (filters.filterSentiment) {
+ filtered = filtered.filter(note => note.sentiment === filters.filterSentiment);
+ }
+
+ setFilteredNotes(filtered);
+ }, [searchQuery, filters.filterPriority, filters.filterSentiment]);
+
+ // Load notes
+ const loadNotes = useCallback(async () => {
+ try {
+ let loadedNotes: Note[];
+ if (filters.showFavorites) {
+ loadedNotes = await notesService.getFavoriteNotes();
+ } else if (selectedCategory === 'ALL') {
+ loadedNotes = await notesService.getAllNotes(filters.showArchived);
+ } else {
+ loadedNotes = await notesService.getNotesByCategory(selectedCategory, filters.showArchived);
+ }
+ setNotes(loadedNotes);
+ applyFilters(loadedNotes);
+ } catch (error) {
+ console.error('[useNotes] Failed to load notes:', error);
+ }
+ }, [selectedCategory, filters.showFavorites, filters.showArchived, applyFilters]);
+
+ // Load templates
+ const loadTemplates = useCallback(async () => {
+ try {
+ const loadedTemplates = await notesService.getTemplates();
+ setTemplates(loadedTemplates);
+ } catch (error) {
+ console.error('[useNotes] Failed to load templates:', error);
+ }
+ }, []);
+
+ // Load statistics
+ const loadStatistics = useCallback(async () => {
+ try {
+ const stats = await notesService.getStatistics();
+ // Load all notes to calculate total words
+ const allNotes = await notesService.getAllNotes(false);
+ const totalWords = allNotes.reduce((sum, note) => sum + (note.word_count || 0), 0);
+
+ // Transform byCategory from Record<string, number> to Array<{ category: string; count: number }>
+ const byCategoryArray = Object.entries(stats.byCategory || {}).map(([category, count]) => ({
+ category,
+ count: count as number
+ }));
+
+ setStatistics({
+ total: stats.total || 0,
+ favorites: stats.favorites || 0,
+ totalWords,
+ byCategory: byCategoryArray
+ });
+ } catch (error) {
+ console.error('[useNotes] Failed to load statistics:', error);
+ }
+ }, []);
+
+ // Load upcoming reminders
+ const loadUpcomingReminders = useCallback(async () => {
+ try {
+ const upcoming = await noteReminderService.getUpcomingReminders();
+ setUpcomingReminders(upcoming);
+ } catch (error) {
+ console.error('[useNotes] Failed to load upcoming reminders:', error);
+ }
+ }, []);
+
+ // Create note
+ const createNote = useCallback(async (note: Omit<Note, 'id'>) => {
+ try {
+ await notesService.createNote(note);
+ await loadNotes();
+ await loadStatistics();
+ await loadUpcomingReminders();
+ if (note.reminder_date) {
+ toast.success(`Note created with reminder set for ${new Date(note.reminder_date).toLocaleString()}`);
+ }
+ } catch (error) {
+ console.error('[useNotes] Failed to create note:', error);
+ throw error;
+ }
+ }, [loadNotes, loadStatistics, loadUpcomingReminders]);
+
+ // Update note
+ const updateNote = useCallback(async (id: number, updates: Partial<Note>) => {
+ try {
+ await notesService.updateNote(id, updates);
+ await loadNotes();
+ await loadStatistics();
+ await loadUpcomingReminders();
+
+ // Update selectedNote if it's the one being updated
+ if (selectedNote?.id === id) {
+ const updatedNote = await notesService.getNoteById(id);
+ setSelectedNote(updatedNote);
+ }
+
+ if (updates.reminder_date) {
+ toast.success(`Reminder updated for ${new Date(updates.reminder_date).toLocaleString()}`);
+ }
+ } catch (error) {
+ console.error('[useNotes] Failed to update note:', error);
+ throw error;
+ }
+ }, [loadNotes, loadStatistics, loadUpcomingReminders, selectedNote]);
+
+ // Delete note
+ const handleDeleteNote = useCallback(async (id: number) => {
+ if (!confirm('Are you sure you want to delete this note?')) return;
+
+ try {
+ await notesService.deleteNote(id);
+ await loadNotes();
+ await loadStatistics();
+ if (selectedNote?.id === id) {
+ setSelectedNote(null);
+ }
+ } catch (error) {
+ console.error('[useNotes] Failed to delete note:', error);
+ alert('Failed to delete note');
+ }
+ }, [loadNotes, loadStatistics, selectedNote]);
+
+ // Toggle favorite
+ const handleToggleFavorite = useCallback(async (note: Note) => {
+ try {
+ await notesService.updateNote(note.id!, { is_favorite: !note.is_favorite });
+ await loadNotes();
+ } catch (error) {
+ console.error('[useNotes] Failed to toggle favorite:', error);
+ }
+ }, [loadNotes]);
+
+ // Toggle archive
+ const handleToggleArchive = useCallback(async (note: Note) => {
+ try {
+ await notesService.updateNote(note.id!, { is_archived: !note.is_archived });
+ await loadNotes();
+ await loadStatistics();
+ if (selectedNote?.id === note.id) {
+ setSelectedNote(null);
+ }
+ } catch (error) {
+ console.error('[useNotes] Failed to toggle archive:', error);
+ }
+ }, [loadNotes, loadStatistics, selectedNote]);
+
+ // Load data on mount and when dependencies change
+ useEffect(() => {
+ loadNotes();
+ loadTemplates();
+ loadStatistics();
+ }, [loadNotes, loadTemplates, loadStatistics]);
+
+ // Apply filters when notes change
+ useEffect(() => {
+ applyFilters(notes);
+ }, [notes, applyFilters]);
+
+ return {
+ notes,
+ filteredNotes,
+ templates,
+ statistics,
+ upcomingReminders,
+ selectedNote,
+ setSelectedNote,
+ selectedCategory,
+ setSelectedCategory,
+ filters,
+ setFilters,
+ searchQuery,
+ setSearchQuery,
+ loadNotes,
+ loadTemplates,
+ loadStatistics,
+ loadUpcomingReminders,
+ createNote,
+ updateNote,
+ handleDeleteNote,
+ handleToggleFavorite,
+ handleToggleArchive
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/index.ts b/fincept-terminal-desktop/src/components/tabs/notes/index.ts
new file mode 100644
index 000000000..a9fe82e97
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/index.ts
@@ -0,0 +1,5 @@
+// Notes Tab barrel export
+
+export { NotesTab } from './NotesTab';
+export * from './types';
+export * from './constants';
diff --git a/fincept-terminal-desktop/src/components/tabs/notes/types.ts b/fincept-terminal-desktop/src/components/tabs/notes/types.ts
new file mode 100644
index 000000000..f48c77a07
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/notes/types.ts
@@ -0,0 +1,43 @@
+// Notes Tab Types
+
+import type { Note, NoteTemplate } from '@/services/core/notesService';
+
+// Re-export service types
+export type { Note, NoteTemplate };
+
+export interface NoteStatistics {
+ total: number;
+ favorites: number;
+ totalWords: number;
+ byCategory: Array<{ category: string; count: number }>;
+}
+
+export interface UpcomingReminder {
+ note: Note;
+ hoursUntil: number;
+}
+
+export interface EditorState {
+ title: string;
+ content: string;
+ category: string;
+ priority: string;
+ sentiment: string;
+ tags: string;
+ tickers: string;
+ colorCode: string;
+ reminderDate: string;
+}
+
+export interface FilterState {
+ filterPriority: string | null;
+ filterSentiment: string | null;
+ showFavorites: boolean;
+ showArchived: boolean;
+}
+
+export type Category = {
+ id: string;
+ label: string;
+ icon: React.ComponentType<{ size?: number; color?: string }>;
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/PolygonEqTab.tsx b/fincept-terminal-desktop/src/components/tabs/polygon-eq/PolygonEqTab.tsx
similarity index 99%
rename from fincept-terminal-desktop/src/components/tabs/PolygonEqTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/polygon-eq/PolygonEqTab.tsx
index 048512a0c..a7ff5efa5 100644
--- a/fincept-terminal-desktop/src/components/tabs/PolygonEqTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/polygon-eq/PolygonEqTab.tsx
@@ -1,8 +1,8 @@
import React, { useState, useEffect } from 'react';
-import { polygonService } from '../../services/data-sources/polygonService';
+import { polygonService } from '@/services/data-sources/polygonService';
import { useTerminalTheme } from '@/contexts/ThemeContext';
-import { yfinanceService, HistoricalDataPoint } from '../../services/markets/yfinanceService';
-import CandlestickChart, { CandlestickDataPoint } from '../charts/CandlestickChart';
+import { yfinanceService, HistoricalDataPoint } from '@/services/markets/yfinanceService';
+import CandlestickChart, { CandlestickDataPoint } from '@/components/charts/CandlestickChart';
import { TabFooter } from '@/components/common/TabFooter';
const PolygonEqTab: React.FC = () => {
diff --git a/fincept-terminal-desktop/src/components/tabs/polygon-eq/index.ts b/fincept-terminal-desktop/src/components/tabs/polygon-eq/index.ts
new file mode 100644
index 000000000..22aaf29f8
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/polygon-eq/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./PolygonEqTab";
+export { default as PolygonEqTab } from "./PolygonEqTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/PolymarketTabEnhanced.tsx b/fincept-terminal-desktop/src/components/tabs/polymarket/PolymarketTabEnhanced.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/PolymarketTabEnhanced.tsx
rename to fincept-terminal-desktop/src/components/tabs/polymarket/PolymarketTabEnhanced.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/polymarket/index.ts b/fincept-terminal-desktop/src/components/tabs/polymarket/index.ts
new file mode 100644
index 000000000..a6399dc09
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/polymarket/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./PolymarketTabEnhanced";
+export { default as PolymarketTabEnhanced } from "./PolymarketTabEnhanced";
diff --git a/fincept-terminal-desktop/src/components/tabs/portfolio-tab/index.ts b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/index.ts
new file mode 100644
index 000000000..1fdd59943
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/portfolio-tab/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./PortfolioTab";
+export { default as PortfolioTab } from "./PortfolioTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx b/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx
similarity index 70%
rename from fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx
index 8f67f89a8..25e39cdac 100644
--- a/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx
@@ -9,8 +9,16 @@ import { TabFooter } from '@/components/common/TabFooter';
import { useTranslation } from 'react-i18next';
import {
User, CreditCard, Activity, Shield, Key, RefreshCw,
- LogOut, Crown, Zap, FileText, CheckCircle, AlertCircle, Eye, EyeOff, BarChart
+ LogOut, Crown, Zap, FileText, CheckCircle, AlertCircle, Eye, EyeOff, BarChart,
+ MessageSquarePlus, Mail, Newspaper, Star, Send, Check, HeadphonesIcon
} from 'lucide-react';
+import {
+ submitContactForm,
+ submitFeedback,
+ subscribeToNewsletter,
+ type ContactFormData,
+ type FeedbackFormData,
+} from '@/services/support/supportApi';
// Fincept Professional Color Palette
const COLORS = {
@@ -28,7 +36,7 @@ const COLORS = {
MUTED: '#737373'
};
-type Section = 'overview' | 'usage' | 'security' | 'billing';
+type Section = 'overview' | 'usage' | 'security' | 'billing' | 'support';
const ProfileTab: React.FC = () => {
const { t } = useTranslation('profile');
@@ -172,6 +180,7 @@ const ProfileTab: React.FC = () => {
{ id: 'usage', label: 'USAGE & CREDITS', icon: Activity },
{ id: 'security', label: 'SECURITY', icon: Shield },
{ id: 'billing', label: 'BILLING', icon: CreditCard },
+ { id: 'support', label: 'SUPPORT', icon: HeadphonesIcon },
].map(section => (
<button
key={section.id}
@@ -219,6 +228,7 @@ const ProfileTab: React.FC = () => {
/>
)}
{activeSection === 'billing' && <BillingSection paymentHistory={paymentHistory} loading={loading} />}
+ {activeSection === 'support' && <SupportSection />}
</div>
<TabFooter
@@ -826,6 +836,432 @@ const BillingSection: React.FC<{ paymentHistory: any[]; loading: boolean }> = ({
);
};
+// Support Section - Feedback, Contact, Newsletter
+const SupportSection: React.FC = () => {
+ // Feedback form state
+ const [feedbackName, setFeedbackName] = useState('');
+ const [feedbackEmail, setFeedbackEmail] = useState('');
+ const [feedbackRating, setFeedbackRating] = useState(0);
+ const [feedbackText, setFeedbackText] = useState('');
+ const [feedbackCategory, setFeedbackCategory] = useState('general');
+ const [feedbackLoading, setFeedbackLoading] = useState(false);
+ const [feedbackSuccess, setFeedbackSuccess] = useState(false);
+ const [feedbackError, setFeedbackError] = useState('');
+
+ // Contact form state
+ const [contactName, setContactName] = useState('');
+ const [contactEmail, setContactEmail] = useState('');
+ const [contactSubject, setContactSubject] = useState('');
+ const [contactMessage, setContactMessage] = useState('');
+ const [contactLoading, setContactLoading] = useState(false);
+ const [contactSuccess, setContactSuccess] = useState(false);
+ const [contactError, setContactError] = useState('');
+
+ // Newsletter state
+ const [newsletterEmail, setNewsletterEmail] = useState('');
+ const [newsletterLoading, setNewsletterLoading] = useState(false);
+ const [newsletterSuccess, setNewsletterSuccess] = useState(false);
+ const [newsletterError, setNewsletterError] = useState('');
+
+ // Reset functions
+ const resetFeedback = () => {
+ setFeedbackName('');
+ setFeedbackEmail('');
+ setFeedbackRating(0);
+ setFeedbackText('');
+ setFeedbackCategory('general');
+ setFeedbackSuccess(false);
+ setFeedbackError('');
+ };
+
+ const resetContact = () => {
+ setContactName('');
+ setContactEmail('');
+ setContactSubject('');
+ setContactMessage('');
+ setContactSuccess(false);
+ setContactError('');
+ };
+
+ const resetNewsletter = () => {
+ setNewsletterEmail('');
+ setNewsletterSuccess(false);
+ setNewsletterError('');
+ };
+
+ // Submit handlers
+ const handleFeedbackSubmit = async () => {
+ if (!feedbackRating || !feedbackText.trim()) {
+ setFeedbackError('Please provide a rating and feedback');
+ return;
+ }
+
+ setFeedbackLoading(true);
+ setFeedbackError('');
+
+ const data: FeedbackFormData = {
+ name: feedbackName || undefined,
+ email: feedbackEmail || undefined,
+ rating: feedbackRating,
+ feedback_text: feedbackText,
+ category: feedbackCategory,
+ };
+
+ const result = await submitFeedback(data);
+ setFeedbackLoading(false);
+
+ if (result.success) {
+ setFeedbackSuccess(true);
+ setTimeout(() => resetFeedback(), 3000);
+ } else {
+ setFeedbackError(result.error || 'Failed to submit feedback');
+ }
+ };
+
+ const handleContactSubmit = async () => {
+ if (!contactName.trim() || !contactEmail.trim() || !contactSubject.trim() || !contactMessage.trim()) {
+ setContactError('Please fill in all required fields');
+ return;
+ }
+
+ setContactLoading(true);
+ setContactError('');
+
+ const data: ContactFormData = {
+ name: contactName,
+ email: contactEmail,
+ subject: contactSubject,
+ message: contactMessage,
+ };
+
+ const result = await submitContactForm(data);
+ setContactLoading(false);
+
+ if (result.success) {
+ setContactSuccess(true);
+ setTimeout(() => resetContact(), 3000);
+ } else {
+ setContactError(result.error || 'Failed to submit contact form');
+ }
+ };
+
+ const handleNewsletterSubmit = async () => {
+ if (!newsletterEmail.trim()) {
+ setNewsletterError('Please enter your email');
+ return;
+ }
+
+ setNewsletterLoading(true);
+ setNewsletterError('');
+
+ const result = await subscribeToNewsletter({
+ email: newsletterEmail,
+ source: 'profile_tab',
+ });
+ setNewsletterLoading(false);
+
+ if (result.success) {
+ setNewsletterSuccess(true);
+ setTimeout(() => resetNewsletter(), 3000);
+ } else {
+ setNewsletterError(result.error || 'Failed to subscribe');
+ }
+ };
+
+ // Input field component
+ const InputField: React.FC<{
+ label: string;
+ value: string;
+ onChange: (value: string) => void;
+ placeholder?: string;
+ type?: string;
+ required?: boolean;
+ multiline?: boolean;
+ rows?: number;
+ }> = ({ label, value, onChange, placeholder, type = 'text', required, multiline, rows = 4 }) => (
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: COLORS.WHITE, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ {label} {required && <span style={{ color: COLORS.RED }}>*</span>}
+ </label>
+ {multiline ? (
+ <textarea
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={placeholder}
+ rows={rows}
+ style={{
+ width: '100%',
+ backgroundColor: COLORS.HEADER_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ resize: 'vertical',
+ }}
+ />
+ ) : (
+ <input
+ type={type}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={placeholder}
+ style={{
+ width: '100%',
+ backgroundColor: COLORS.HEADER_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ }}
+ />
+ )}
+ </div>
+ );
+
+ // Star rating component
+ const StarRating: React.FC<{ rating: number; onChange: (rating: number) => void }> = ({ rating, onChange }) => (
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: COLORS.WHITE, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ Rating <span style={{ color: COLORS.RED }}>*</span>
+ </label>
+ <div style={{ display: 'flex', gap: '4px' }}>
+ {[1, 2, 3, 4, 5].map((star) => (
+ <button
+ key={star}
+ onClick={() => onChange(star)}
+ style={{
+ background: 'transparent',
+ border: 'none',
+ cursor: 'pointer',
+ padding: '2px',
+ }}
+ >
+ <Star
+ size={20}
+ fill={star <= rating ? COLORS.YELLOW : 'transparent'}
+ color={star <= rating ? COLORS.YELLOW : COLORS.MUTED}
+ />
+ </button>
+ ))}
+ </div>
+ </div>
+ );
+
+ // Submit button component
+ const SubmitButton: React.FC<{
+ onClick: () => void;
+ loading: boolean;
+ success: boolean;
+ text: string;
+ color?: string;
+ }> = ({ onClick, loading, success, text, color = COLORS.ORANGE }) => (
+ <button
+ onClick={onClick}
+ disabled={loading}
+ style={{
+ width: '100%',
+ backgroundColor: success ? COLORS.GREEN : color,
+ color: COLORS.WHITE,
+ border: 'none',
+ padding: '10px 16px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ fontFamily: 'monospace',
+ cursor: loading ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ gap: '8px',
+ opacity: loading ? 0.7 : 1,
+ }}
+ >
+ {loading ? (
+ 'SUBMITTING...'
+ ) : success ? (
+ <>
+ <Check size={14} /> SUCCESS!
+ </>
+ ) : (
+ <>
+ <Send size={14} /> {text}
+ </>
+ )}
+ </button>
+ );
+
+ return (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
+ {/* Feedback Form */}
+ <DataPanel title="SEND FEEDBACK" icon={<MessageSquarePlus size={16} />}>
+ <InputField
+ label="Name"
+ value={feedbackName}
+ onChange={setFeedbackName}
+ placeholder="Your name (optional)"
+ />
+ <InputField
+ label="Email"
+ value={feedbackEmail}
+ onChange={setFeedbackEmail}
+ placeholder="Your email (optional)"
+ type="email"
+ />
+ <StarRating rating={feedbackRating} onChange={setFeedbackRating} />
+ <div style={{ marginBottom: '12px' }}>
+ <label style={{ color: COLORS.WHITE, fontSize: '10px', display: 'block', marginBottom: '4px' }}>
+ Category
+ </label>
+ <select
+ value={feedbackCategory}
+ onChange={(e) => setFeedbackCategory(e.target.value)}
+ style={{
+ width: '100%',
+ backgroundColor: COLORS.HEADER_BG,
+ border: `1px solid ${COLORS.BORDER}`,
+ color: COLORS.WHITE,
+ padding: '8px',
+ fontSize: '11px',
+ fontFamily: 'Consolas, monospace',
+ }}
+ >
+ <option value="general">General</option>
+ <option value="feature_request">Feature Request</option>
+ <option value="bug_report">Bug Report</option>
+ <option value="ui_ux">UI/UX</option>
+ <option value="performance">Performance</option>
+ <option value="data">Data Quality</option>
+ </select>
+ </div>
+ <InputField
+ label="Feedback"
+ value={feedbackText}
+ onChange={setFeedbackText}
+ placeholder="Tell us what you think..."
+ multiline
+ rows={3}
+ required
+ />
+ {feedbackError && (
+ <div style={{ color: COLORS.RED, fontSize: '10px', marginBottom: '12px' }}>{feedbackError}</div>
+ )}
+ <SubmitButton
+ onClick={handleFeedbackSubmit}
+ loading={feedbackLoading}
+ success={feedbackSuccess}
+ text="SUBMIT FEEDBACK"
+ />
+ </DataPanel>
+
+ {/* Contact Form */}
+ <DataPanel title="CONTACT US" icon={<Mail size={16} />}>
+ <InputField
+ label="Name"
+ value={contactName}
+ onChange={setContactName}
+ placeholder="Your name"
+ required
+ />
+ <InputField
+ label="Email"
+ value={contactEmail}
+ onChange={setContactEmail}
+ placeholder="[email protected]"
+ type="email"
+ required
+ />
+ <InputField
+ label="Subject"
+ value={contactSubject}
+ onChange={setContactSubject}
+ placeholder="Subject of your message"
+ required
+ />
+ <InputField
+ label="Message"
+ value={contactMessage}
+ onChange={setContactMessage}
+ placeholder="Your message..."
+ multiline
+ rows={3}
+ required
+ />
+ {contactError && (
+ <div style={{ color: COLORS.RED, fontSize: '10px', marginBottom: '12px' }}>{contactError}</div>
+ )}
+ <SubmitButton
+ onClick={handleContactSubmit}
+ loading={contactLoading}
+ success={contactSuccess}
+ text="SEND MESSAGE"
+ color="#3b82f6"
+ />
+ </DataPanel>
+
+ {/* Newsletter Subscription */}
+ <div style={{ gridColumn: '1 / -1' }}>
+ <DataPanel title="NEWSLETTER SUBSCRIPTION" icon={<Newspaper size={16} />}>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '12px', alignItems: 'flex-end' }}>
+ <div>
+ <p style={{ color: COLORS.MUTED, fontSize: '10px', marginBottom: '12px', lineHeight: '1.5' }}>
+ Stay updated with the latest features, market insights, and Fincept news delivered to your inbox.
+ </p>
+ <InputField
+ label="Email Address"
+ value={newsletterEmail}
+ onChange={setNewsletterEmail}
+ placeholder="[email protected]"
+ type="email"
+ required
+ />
+ {newsletterError && (
+ <div style={{ color: COLORS.RED, fontSize: '10px', marginBottom: '8px' }}>{newsletterError}</div>
+ )}
+ </div>
+ <div style={{ paddingBottom: newsletterError ? '28px' : '0' }}>
+ <button
+ onClick={handleNewsletterSubmit}
+ disabled={newsletterLoading}
+ style={{
+ backgroundColor: newsletterSuccess ? COLORS.GREEN : '#10b981',
+ color: COLORS.WHITE,
+ border: 'none',
+ padding: '10px 24px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ fontFamily: 'monospace',
+ cursor: newsletterLoading ? 'not-allowed' : 'pointer',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ opacity: newsletterLoading ? 0.7 : 1,
+ whiteSpace: 'nowrap',
+ }}
+ >
+ {newsletterLoading ? (
+ 'SUBSCRIBING...'
+ ) : newsletterSuccess ? (
+ <>
+ <Check size={14} /> SUBSCRIBED!
+ </>
+ ) : (
+ <>
+ <Newspaper size={14} /> SUBSCRIBE
+ </>
+ )}
+ </button>
+ </div>
+ </div>
+ <p style={{ color: COLORS.MUTED, fontSize: '9px', marginTop: '8px' }}>
+ You can unsubscribe at any time. We respect your privacy.
+ </p>
+ </DataPanel>
+ </div>
+ </div>
+ );
+};
+
// Helper Components
const DataPanel: React.FC<{ title: string; icon: React.ReactNode; children: React.ReactNode }> = ({ title, icon, children }) => (
<div style={{
diff --git a/fincept-terminal-desktop/src/components/tabs/profile/index.ts b/fincept-terminal-desktop/src/components/tabs/profile/index.ts
new file mode 100644
index 000000000..4c538d024
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/profile/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./ProfileTab";
+export { default as ProfileTab } from "./ProfileTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/RelationshipMapTab.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/RelationshipMapTab.tsx
new file mode 100644
index 000000000..cefc6455e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/RelationshipMapTab.tsx
@@ -0,0 +1,445 @@
+import React, { useState, useCallback, useMemo, useEffect, memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import ReactFlow, {
+ Node,
+ Edge,
+ Background,
+ Controls,
+ MiniMap,
+ useNodesState,
+ useEdgesState,
+ MarkerType,
+} from 'reactflow';
+import 'reactflow/dist/style.css';
+import { Search, Globe } from 'lucide-react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
+import { TabFooter } from '@/components/common/TabFooter';
+import { relationshipMapService } from '@/services/geopolitics/relationshipMapService';
+
+import { CompanyNode, DataNode } from './components';
+import { NODE_POSITIONS, EDGE_CONFIG, FLOW_CONFIG, BACKGROUND_CONFIG, DEFAULT_TICKER } from './constants';
+import { formatMoney, formatPercent, formatNumber, formatDate } from './utils';
+import type { NodeColors, GraphData } from './types';
+
+// Define nodeTypes outside component to prevent recreation
+const nodeTypes = {
+ company: CompanyNode,
+ data: DataNode,
+};
+
+// Build graph nodes and edges from data
+const buildGraph = (data: GraphData, colors: NodeColors) => {
+ const newNodes: Node[] = [];
+ const newEdges: Edge[] = [];
+
+ // Center: Company node
+ newNodes.push({
+ id: 'company',
+ type: 'company',
+ position: NODE_POSITIONS.company,
+ data: {
+ ...data.company,
+ colors,
+ },
+ });
+
+ // Helper to add a data node with edge
+ const addDataNode = (
+ id: string,
+ type: string,
+ title: string,
+ items: { label: string; value: string; url?: string }[],
+ edgeColor: string
+ ) => {
+ const position = NODE_POSITIONS[id as keyof typeof NODE_POSITIONS];
+ if (!position) return;
+
+ newNodes.push({
+ id,
+ type: 'data',
+ position,
+ data: {
+ type,
+ title,
+ items,
+ colors,
+ },
+ });
+
+ newEdges.push({
+ id: `e-${id}`,
+ source: 'company',
+ target: id,
+ type: EDGE_CONFIG.type,
+ animated: EDGE_CONFIG.animated,
+ style: { stroke: edgeColor, strokeWidth: EDGE_CONFIG.strokeWidth },
+ markerEnd: { type: MarkerType.ArrowClosed, color: edgeColor },
+ });
+ };
+
+ // 1. Corporate Events
+ const eventItems =
+ data.corporate_events && data.corporate_events.length > 0
+ ? data.corporate_events.map((e) => ({
+ label: formatDate(e.filing_date),
+ value: e.items?.[0] || 'Event',
+ url: e.filing_url,
+ }))
+ : [{ label: 'No events available', value: 'Loading...' }];
+
+ addDataNode('events', 'events', 'Corporate Events', eventItems, '#ef4444');
+
+ // 2. Recent SEC Filings
+ if (data.filings && data.filings.length > 0) {
+ addDataNode(
+ 'filings',
+ 'filings',
+ 'Recent SEC Filings',
+ data.filings.map((f) => ({
+ label: `${f.form} (${f.description || ''})`,
+ value: formatDate(f.filing_date),
+ })),
+ '#3b82f6'
+ );
+ }
+
+ // 3. Financials
+ if (data.financials) {
+ addDataNode(
+ 'financials',
+ 'financials',
+ 'Financial Metrics',
+ [
+ { label: 'Revenue', value: formatMoney(data.financials.revenue) },
+ { label: 'Gross Profit', value: formatMoney(data.financials.gross_profit) },
+ { label: 'Operating CF', value: formatMoney(data.financials.operating_cashflow) },
+ { label: 'Free CF', value: formatMoney(data.financials.free_cashflow) },
+ { label: 'EBITDA Margin', value: formatPercent(data.financials.ebitda_margins) },
+ { label: 'Profit Margin', value: formatPercent(data.financials.profit_margins) },
+ { label: 'Revenue Growth', value: formatPercent(data.financials.revenue_growth) },
+ { label: 'Earnings Growth', value: formatPercent(data.financials.earnings_growth) },
+ ],
+ '#10b981'
+ );
+ }
+
+ // 4. Balance Sheet
+ if (data.balance_sheet) {
+ addDataNode(
+ 'balance',
+ 'balance',
+ 'Balance Sheet',
+ [
+ { label: 'Total Assets', value: formatMoney(data.balance_sheet.total_assets) },
+ { label: 'Total Liabilities', value: formatMoney(data.balance_sheet.total_liabilities) },
+ { label: 'Equity', value: formatMoney(data.balance_sheet.stockholders_equity) },
+ { label: 'Cash', value: formatMoney(data.balance_sheet.total_cash) },
+ { label: 'Debt', value: formatMoney(data.balance_sheet.total_debt) },
+ { label: 'Shares Out', value: formatNumber(data.balance_sheet.shares_outstanding) },
+ ],
+ colors.accent
+ );
+ }
+
+ // 5. Analysts
+ if (data.analysts) {
+ addDataNode(
+ 'analysts',
+ 'analysts',
+ 'Analyst Coverage',
+ [
+ { label: 'Recommendation', value: data.analysts.recommendation.toUpperCase() },
+ {
+ label: 'Rating Score',
+ value: data.analysts.recommendation_mean ? data.analysts.recommendation_mean.toFixed(2) : 'N/A',
+ },
+ { label: 'Target Price', value: formatMoney(data.analysts.target_price) },
+ { label: 'Target High', value: formatMoney(data.analysts.target_high) },
+ { label: 'Target Low', value: formatMoney(data.analysts.target_low) },
+ { label: 'Analysts', value: String(data.analysts.analyst_count) },
+ ],
+ '#8b5cf6'
+ );
+ }
+
+ // 6. Ownership
+ if (data.ownership) {
+ addDataNode(
+ 'ownership',
+ 'ownership',
+ 'Ownership Structure',
+ [
+ { label: 'Insider %', value: `${data.ownership.insider_percent.toFixed(2)}%` },
+ { label: 'Institutional %', value: `${data.ownership.institutional_percent.toFixed(2)}%` },
+ { label: 'Float Shares', value: formatNumber(data.ownership.float_shares) },
+ { label: 'Total Shares', value: formatNumber(data.ownership.shares_outstanding) },
+ ],
+ '#f59e0b'
+ );
+ }
+
+ // 7. Valuation
+ if (data.valuation) {
+ addDataNode(
+ 'valuation',
+ 'valuation',
+ 'Valuation Metrics',
+ [
+ { label: 'P/E Ratio', value: data.valuation.pe_ratio.toFixed(2) },
+ { label: 'Forward P/E', value: data.valuation.forward_pe.toFixed(2) },
+ { label: 'Price/Book', value: data.valuation.price_to_book.toFixed(2) },
+ { label: 'Enterprise Value', value: formatMoney(data.valuation.enterprise_value) },
+ { label: 'EV/Revenue', value: data.valuation.enterprise_to_revenue.toFixed(2) },
+ { label: 'PEG Ratio', value: data.valuation.peg_ratio.toFixed(2) },
+ ],
+ '#ec4899'
+ );
+ }
+
+ // 8. Company Info
+ addDataNode(
+ 'info',
+ 'info',
+ 'Company Information',
+ [
+ { label: 'Exchange', value: data.company.exchange },
+ { label: 'Sector', value: data.company.sector },
+ { label: 'Industry', value: data.company.industry },
+ { label: 'Employees', value: data.company.employees ? data.company.employees.toLocaleString() : 'N/A' },
+ { label: 'CIK', value: data.company.cik },
+ ],
+ '#14b8a6'
+ );
+
+ // 9. Executives
+ if (data.executives && data.executives.length > 0) {
+ addDataNode(
+ 'executives',
+ 'executives',
+ 'Executives',
+ data.executives.map((exec) => ({
+ label: exec.name,
+ value: exec.role,
+ })),
+ '#10b981'
+ );
+ }
+
+ return { nodes: newNodes, edges: newEdges };
+};
+
+const RelationshipMapTab: React.FC = () => {
+ const { t } = useTranslation('relationshipMap');
+ const { colors, fontSize, fontFamily } = useTerminalTheme();
+ const [searchQuery, setSearchQuery] = useState('');
+ const [selectedSymbol, setSelectedSymbol] = useState(DEFAULT_TICKER);
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const [nodes, setNodes, onNodesChange] = useNodesState([]);
+ const [edges, setEdges, onEdgesChange] = useEdgesState([]);
+
+ // Memoize node colors to pass to child components
+ const nodeColors: NodeColors = useMemo(
+ () => ({
+ accent: colors.accent,
+ text: colors.text,
+ textMuted: colors.textMuted,
+ success: colors.success,
+ alert: colors.alert,
+ panel: colors.panel,
+ }),
+ [colors.accent, colors.text, colors.textMuted, colors.success, colors.alert, colors.panel]
+ );
+
+ const fetchRelationshipData = useCallback(
+ async (ticker: string) => {
+ setIsLoading(true);
+ setError(null);
+ try {
+ const data = await relationshipMapService.getRelationshipMap(ticker);
+ const { nodes: newNodes, edges: newEdges } = buildGraph(data as unknown as GraphData, nodeColors);
+ setNodes(newNodes);
+ setEdges(newEdges);
+ } catch (err) {
+ console.error('[UI] Error:', err);
+ setError(`Failed to load data for ${ticker}`);
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [nodeColors, setNodes, setEdges]
+ );
+
+ useEffect(() => {
+ fetchRelationshipData(selectedSymbol);
+ }, []);
+
+ const handleSearch = useCallback(
+ async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!searchQuery.trim()) return;
+
+ const ticker = searchQuery.toUpperCase().trim();
+ setSelectedSymbol(ticker);
+ await fetchRelationshipData(ticker);
+ },
+ [searchQuery, fetchRelationshipData]
+ );
+
+ // Memoize container style
+ const containerStyle = useMemo(
+ () => ({
+ fontFamily,
+ fontSize: `${fontSize}px`,
+ backgroundColor: colors.background,
+ color: colors.text,
+ }),
+ [fontFamily, fontSize, colors.background, colors.text]
+ );
+
+ // Memoize header border style
+ const headerStyle = useMemo(
+ () => ({ borderColor: colors.textMuted }),
+ [colors.textMuted]
+ );
+
+ // Memoize ticker badge style
+ const badgeStyle = useMemo(
+ () => ({
+ backgroundColor: colors.panel,
+ color: colors.accent,
+ border: `1px solid ${colors.textMuted}`,
+ }),
+ [colors.panel, colors.accent, colors.textMuted]
+ );
+
+ // Memoize input style
+ const inputStyle = useMemo(
+ () => ({
+ backgroundColor: colors.panel,
+ borderColor: colors.textMuted,
+ color: colors.text,
+ }),
+ [colors.panel, colors.textMuted, colors.text]
+ );
+
+ // Memoize minimap node color function
+ const minimapNodeColor = useCallback(
+ (node: Node) => {
+ if (node.id === 'company') return colors.accent;
+ return colors.textMuted;
+ },
+ [colors.accent, colors.textMuted]
+ );
+
+ // Memoize controls style
+ const controlsStyle = useMemo(
+ () => ({
+ background: '#1a1a1a',
+ border: `1px solid ${colors.textMuted}`,
+ borderRadius: '4px',
+ }),
+ [colors.textMuted]
+ );
+
+ // Memoize minimap style
+ const minimapStyle = useMemo(
+ () => ({
+ background: '#1a1a1a',
+ border: `1px solid ${colors.textMuted}`,
+ }),
+ [colors.textMuted]
+ );
+
+ return (
+ <div className="h-full flex flex-col" style={containerStyle}>
+ {/* Header */}
+ <div className="border-b px-4 py-3 flex items-center justify-between" style={headerStyle}>
+ <div className="flex items-center gap-3">
+ <Globe className="w-5 h-5" style={{ color: colors.accent }} />
+ <h2 className="text-lg font-semibold">{t('title')}</h2>
+ <span className="text-xs px-2 py-1 rounded font-mono" style={badgeStyle}>
+ {selectedSymbol}
+ </span>
+ </div>
+
+ <form onSubmit={handleSearch} className="relative w-96">
+ <Search
+ className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4"
+ style={{ color: colors.textMuted }}
+ />
+ <input
+ type="text"
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ placeholder={t('search.placeholder')}
+ className="w-full pl-10 pr-4 py-2 rounded border focus:outline-none focus:ring-1"
+ style={inputStyle}
+ />
+ </form>
+ </div>
+
+ {/* Graph */}
+ <div className="flex-1" style={{ background: '#0a0a0a' }}>
+ {isLoading ? (
+ <div className="flex items-center justify-center h-full">
+ <div className="text-center">
+ <div
+ className="animate-spin rounded-full h-16 w-16 border-b-2 mx-auto mb-4"
+ style={{ borderColor: colors.accent }}
+ />
+ <p className="text-lg font-semibold" style={{ color: colors.text }}>
+ {t('loading.title')} {selectedSymbol}...
+ </p>
+ <p className="text-sm mt-2" style={{ color: colors.textMuted }}>
+ {t('loading.subtitle')}
+ </p>
+ </div>
+ </div>
+ ) : error ? (
+ <div className="flex items-center justify-center h-full">
+ <div
+ className="text-center p-8 rounded border"
+ style={{
+ backgroundColor: colors.panel,
+ borderColor: colors.alert,
+ }}
+ >
+ <p className="text-lg font-semibold mb-2" style={{ color: colors.alert }}>
+ {t('error.title')}
+ </p>
+ <p style={{ color: colors.textMuted }}>{error}</p>
+ </div>
+ </div>
+ ) : (
+ <ReactFlow
+ nodes={nodes}
+ edges={edges}
+ onNodesChange={onNodesChange}
+ onEdgesChange={onEdgesChange}
+ nodeTypes={nodeTypes}
+ fitView={FLOW_CONFIG.fitView}
+ minZoom={FLOW_CONFIG.minZoom}
+ maxZoom={FLOW_CONFIG.maxZoom}
+ defaultViewport={FLOW_CONFIG.defaultViewport}
+ style={BACKGROUND_CONFIG.style}
+ >
+ <Background
+ gap={BACKGROUND_CONFIG.gap}
+ size={BACKGROUND_CONFIG.size}
+ style={BACKGROUND_CONFIG.style}
+ color={BACKGROUND_CONFIG.color}
+ />
+ <Controls style={controlsStyle} />
+ <MiniMap style={minimapStyle} maskColor="#0a0a0a90" nodeColor={minimapNodeColor} />
+ </ReactFlow>
+ )}
+ </div>
+
+ <TabFooter tabName="Relationship Map" />
+ </div>
+ );
+};
+
+export default memo(RelationshipMapTab);
diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/CompanyNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/CompanyNode.tsx
new file mode 100644
index 000000000..0733a9914
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/CompanyNode.tsx
@@ -0,0 +1,61 @@
+import React, { memo, useMemo } from 'react';
+import { Handle, Position } from 'reactflow';
+import { Building2 } from 'lucide-react';
+import { formatMarketCap } from '../utils';
+import type { CompanyNodeProps } from '../types';
+
+const CompanyNode = memo(({ data }: CompanyNodeProps) => {
+ const { colors } = data;
+
+ // Memoize styles to prevent recreation on each render
+ const containerStyle = useMemo(
+ () => ({
+ background: 'linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%)',
+ border: `3px solid ${colors.accent}`,
+ borderRadius: '12px',
+ padding: '24px',
+ minWidth: '320px',
+ maxWidth: '400px',
+ boxShadow: `0 0 40px ${colors.accent}80, 0 10px 30px rgba(0,0,0,0.7)`,
+ }),
+ [colors.accent]
+ );
+
+ const handleStyle = useMemo(() => ({ opacity: 0 }), []);
+
+ return (
+ <div style={containerStyle}>
+ <Handle type="target" position={Position.Top} style={handleStyle} />
+ <div className="flex flex-col items-center text-center">
+ <Building2 className="w-12 h-12 mb-3" style={{ color: colors.accent }} />
+ <h2 className="text-2xl font-bold mb-1" style={{ color: colors.text }}>
+ {data.name}
+ </h2>
+ <div className="text-xl mb-2 font-mono" style={{ color: colors.accent }}>
+ {data.ticker}
+ </div>
+ <div className="text-sm mb-1" style={{ color: colors.textMuted }}>
+ {data.sector} • {data.industry}
+ </div>
+ <div className="text-sm font-semibold mt-2" style={{ color: colors.success }}>
+ Market Cap: {formatMarketCap(data.market_cap || 0)}
+ </div>
+ <div className="text-xs mt-2 opacity-60">
+ CIK: {data.cik} | {data.exchange}
+ </div>
+ {data.employees && (
+ <div className="text-xs mt-1" style={{ color: colors.textMuted }}>
+ {data.employees.toLocaleString()} employees
+ </div>
+ )}
+ </div>
+ <Handle type="source" position={Position.Bottom} style={handleStyle} />
+ <Handle type="source" position={Position.Left} style={handleStyle} />
+ <Handle type="source" position={Position.Right} style={handleStyle} />
+ </div>
+ );
+});
+
+CompanyNode.displayName = 'CompanyNode';
+
+export default CompanyNode;
diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/DataNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/DataNode.tsx
new file mode 100644
index 000000000..b106e9711
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/DataNode.tsx
@@ -0,0 +1,202 @@
+import React, { memo, useMemo, useCallback, useState } from 'react';
+import { Handle, Position } from 'reactflow';
+import {
+ Activity,
+ Calendar,
+ DollarSign,
+ BarChart3,
+ Award,
+ PieChart,
+ TrendingUp,
+ Briefcase,
+ Users,
+ FileText,
+ ExternalLink,
+} from 'lucide-react';
+import { open } from '@tauri-apps/plugin-shell';
+import { NODE_TYPE_COLORS } from '../constants';
+import type { DataNodeProps, DataNodeType, DataNodeItem } from '../types';
+
+// Memoized icon getter - returns the icon component
+const getIconComponent = (type: DataNodeType) => {
+ switch (type) {
+ case 'events':
+ return Activity;
+ case 'filings':
+ return Calendar;
+ case 'financials':
+ return DollarSign;
+ case 'balance':
+ return BarChart3;
+ case 'analysts':
+ return Award;
+ case 'ownership':
+ return PieChart;
+ case 'valuation':
+ return TrendingUp;
+ case 'info':
+ return Briefcase;
+ case 'executives':
+ return Users;
+ default:
+ return FileText;
+ }
+};
+
+// Get node color based on type
+const getNodeColor = (type: DataNodeType, accentColor: string): string => {
+ if (type === 'balance') return accentColor;
+ return NODE_TYPE_COLORS[type] || '#6b7280';
+};
+
+// Memoized data item row
+const DataItemRow = memo(
+ ({
+ item,
+ isClickable,
+ textMutedColor,
+ textColor,
+ onClick,
+ }: {
+ item: DataNodeItem;
+ isClickable: boolean;
+ textMutedColor: string;
+ textColor: string;
+ onClick: (e: React.MouseEvent) => void;
+ }) => (
+ <div
+ className="flex justify-between gap-3 hover:bg-white/5 rounded px-1 py-0.5 transition-colors"
+ onClick={onClick}
+ style={{ cursor: isClickable && item.url ? 'pointer' : 'default' }}
+ >
+ <span className="truncate" style={{ color: textMutedColor }}>
+ {item.label}
+ </span>
+ <span className="font-medium text-right flex items-center gap-1" style={{ color: textColor }}>
+ {item.value}
+ {isClickable && item.url && <ExternalLink className="w-3 h-3 opacity-50" />}
+ </span>
+ </div>
+ )
+);
+
+DataItemRow.displayName = 'DataItemRow';
+
+const DataNode = memo(({ data }: DataNodeProps) => {
+ const { colors, type, title, items } = data;
+ const [expanded, setExpanded] = useState(false);
+
+ const nodeColor = useMemo(() => getNodeColor(type, colors.accent), [type, colors.accent]);
+ const IconComponent = useMemo(() => getIconComponent(type), [type]);
+ const hasClickableItems = type === 'events' || type === 'filings';
+ const displayItems = expanded ? items : items?.slice(0, 4);
+ const hasMoreItems = items?.length > 4;
+
+ // Memoize styles
+ const containerStyle = useMemo(
+ () => ({
+ background: '#1a1a1a',
+ border: `2px solid ${nodeColor}`,
+ borderRadius: '8px',
+ padding: '14px 18px',
+ minWidth: '260px',
+ maxWidth: '320px',
+ boxShadow: `0 0 20px ${nodeColor}50, 0 4px 12px rgba(0,0,0,0.5)`,
+ cursor: hasMoreItems ? 'pointer' : 'default',
+ transition: 'all 0.2s',
+ }),
+ [nodeColor, hasMoreItems]
+ );
+
+ const handleStyle = useMemo(() => ({ background: nodeColor }), [nodeColor]);
+ const handleStyleHidden = useMemo(() => ({ background: nodeColor, opacity: 0 }), [nodeColor]);
+
+ const badgeStyle = useMemo(
+ () => ({
+ backgroundColor: `${nodeColor}20`,
+ color: nodeColor,
+ }),
+ [nodeColor]
+ );
+
+ const handleContainerClick = useCallback(() => {
+ if (hasMoreItems) {
+ setExpanded((prev) => !prev);
+ }
+ }, [hasMoreItems]);
+
+ const handleItemClick = useCallback(
+ async (e: React.MouseEvent, item: DataNodeItem) => {
+ e.stopPropagation();
+ if (hasClickableItems && item.url) {
+ await open(item.url);
+ }
+ },
+ [hasClickableItems]
+ );
+
+ const handleMouseEnter = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>) => {
+ e.currentTarget.style.transform = 'scale(1.02)';
+ e.currentTarget.style.boxShadow = `0 0 30px ${nodeColor}70, 0 6px 16px rgba(0,0,0,0.6)`;
+ },
+ [nodeColor]
+ );
+
+ const handleMouseLeave = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>) => {
+ e.currentTarget.style.transform = 'scale(1)';
+ e.currentTarget.style.boxShadow = `0 0 20px ${nodeColor}50, 0 4px 12px rgba(0,0,0,0.5)`;
+ },
+ [nodeColor]
+ );
+
+ return (
+ <div
+ style={containerStyle}
+ onClick={handleContainerClick}
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ >
+ <Handle type="target" position={Position.Top} style={handleStyle} />
+
+ <div className="flex items-center gap-2 mb-3">
+ <div style={{ color: nodeColor }}>
+ <IconComponent className="w-5 h-5" />
+ </div>
+ <h4 className="font-semibold text-sm" style={{ color: colors.text }}>
+ {title}
+ </h4>
+ {hasMoreItems && (
+ <span className="text-xs ml-auto px-1.5 py-0.5 rounded" style={badgeStyle}>
+ {items.length}
+ </span>
+ )}
+ </div>
+
+ <div className="space-y-1.5 text-xs">
+ {displayItems?.map((item, idx) => (
+ <DataItemRow
+ key={idx}
+ item={item}
+ isClickable={hasClickableItems}
+ textMutedColor={colors.textMuted}
+ textColor={colors.text}
+ onClick={(e) => handleItemClick(e, item)}
+ />
+ ))}
+ {!expanded && hasMoreItems && (
+ <div className="text-center pt-1 text-xs font-semibold" style={{ color: nodeColor }}>
+ Click to see +{items.length - 4} more
+ </div>
+ )}
+ </div>
+
+ <Handle type="source" position={Position.Bottom} style={handleStyleHidden} />
+ </div>
+ );
+});
+
+DataNode.displayName = 'DataNode';
+
+export default DataNode;
diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/index.ts b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/index.ts
new file mode 100644
index 000000000..c3e6a6c95
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/index.ts
@@ -0,0 +1,2 @@
+export { default as CompanyNode } from './CompanyNode';
+export { default as DataNode } from './DataNode';
diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/constants.ts b/fincept-terminal-desktop/src/components/tabs/relationship-map/constants.ts
new file mode 100644
index 000000000..7bbe2d3ce
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/constants.ts
@@ -0,0 +1,60 @@
+// Constants for RelationshipMapTab
+import { MarkerType } from 'reactflow';
+import type { DataNodeType } from './types';
+
+// Node type colors
+export const NODE_TYPE_COLORS: Record<DataNodeType, string> = {
+ events: '#ef4444',
+ filings: '#3b82f6',
+ financials: '#10b981',
+ balance: '#f97316', // Will be overridden by theme accent
+ analysts: '#8b5cf6',
+ ownership: '#f59e0b',
+ valuation: '#ec4899',
+ info: '#14b8a6',
+ executives: '#10b981',
+};
+
+// Node positions for the graph layout
+export const NODE_POSITIONS = {
+ company: { x: 600, y: 350 },
+ events: { x: 50, y: 50 },
+ filings: { x: 200, y: 80 },
+ financials: { x: 500, y: 50 },
+ balance: { x: 850, y: 80 },
+ analysts: { x: 1100, y: 350 },
+ ownership: { x: 850, y: 620 },
+ valuation: { x: 450, y: 650 },
+ info: { x: 100, y: 620 },
+ executives: { x: 50, y: 350 },
+} as const;
+
+// Edge configuration
+export const EDGE_CONFIG = {
+ type: 'smoothstep' as const,
+ animated: true,
+ strokeWidth: 2,
+ markerType: MarkerType.ArrowClosed,
+};
+
+// Cache duration in milliseconds (5 minutes)
+export const CACHE_DURATION = 5 * 60 * 1000;
+
+// Default ticker
+export const DEFAULT_TICKER = 'AAPL';
+
+// ReactFlow configuration
+export const FLOW_CONFIG = {
+ minZoom: 0.3,
+ maxZoom: 2,
+ defaultViewport: { x: 0, y: 0, zoom: 0.75 },
+ fitView: true,
+};
+
+// Background configuration
+export const BACKGROUND_CONFIG = {
+ gap: 20,
+ size: 1,
+ color: '#1a1a1a',
+ style: { background: '#0a0a0a' },
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/index.ts b/fincept-terminal-desktop/src/components/tabs/relationship-map/index.ts
new file mode 100644
index 000000000..0cd1e3ef5
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/index.ts
@@ -0,0 +1,5 @@
+export { default } from './RelationshipMapTab';
+export { default as RelationshipMapTab } from './RelationshipMapTab';
+export * from './types';
+export * from './constants';
+export * from './utils';
diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/types.ts b/fincept-terminal-desktop/src/components/tabs/relationship-map/types.ts
new file mode 100644
index 000000000..08b811526
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/types.ts
@@ -0,0 +1,131 @@
+// Type definitions for RelationshipMapTab
+
+export interface NodeColors {
+ accent: string;
+ text: string;
+ textMuted: string;
+ success: string;
+ alert: string;
+ panel: string;
+}
+
+export interface CompanyNodeData {
+ name: string;
+ ticker: string;
+ industry: string;
+ sector: string;
+ cik: string;
+ exchange: string;
+ employees?: number;
+ market_cap?: number;
+}
+
+export interface DataNodeItem {
+ label: string;
+ value: string;
+ description?: string;
+ url?: string;
+ allItems?: string[];
+}
+
+export type DataNodeType =
+ | 'events'
+ | 'filings'
+ | 'financials'
+ | 'balance'
+ | 'analysts'
+ | 'ownership'
+ | 'valuation'
+ | 'info'
+ | 'executives';
+
+export interface DataNodeData {
+ type: DataNodeType;
+ title: string;
+ items: DataNodeItem[];
+ colors: NodeColors;
+}
+
+export interface CompanyNodeProps {
+ data: CompanyNodeData & { colors: NodeColors };
+}
+
+export interface DataNodeProps {
+ data: DataNodeData;
+}
+
+// Graph builder types
+export interface GraphData {
+ company: CompanyNodeData;
+ corporate_events?: CorporateEventData[];
+ filings?: FilingData[];
+ financials?: FinancialsData;
+ balance_sheet?: BalanceSheetData;
+ analysts?: AnalystsData;
+ ownership?: OwnershipData;
+ valuation?: ValuationData;
+ executives?: ExecutiveData[];
+}
+
+export interface CorporateEventData {
+ filing_date: string;
+ items?: string[];
+ description?: string;
+ filing_url?: string;
+}
+
+export interface FilingData {
+ form: string;
+ description?: string;
+ filing_date: string;
+}
+
+export interface FinancialsData {
+ revenue: number;
+ gross_profit: number;
+ operating_cashflow: number;
+ free_cashflow: number;
+ ebitda_margins: number;
+ profit_margins: number;
+ revenue_growth: number;
+ earnings_growth: number;
+}
+
+export interface BalanceSheetData {
+ total_assets: number;
+ total_liabilities: number;
+ stockholders_equity: number;
+ total_cash: number;
+ total_debt: number;
+ shares_outstanding: number;
+}
+
+export interface AnalystsData {
+ recommendation: string;
+ recommendation_mean?: number;
+ target_price: number;
+ target_high: number;
+ target_low: number;
+ analyst_count: number;
+}
+
+export interface OwnershipData {
+ insider_percent: number;
+ institutional_percent: number;
+ float_shares: number;
+ shares_outstanding: number;
+}
+
+export interface ValuationData {
+ pe_ratio: number;
+ forward_pe: number;
+ price_to_book: number;
+ enterprise_value: number;
+ enterprise_to_revenue: number;
+ peg_ratio: number;
+}
+
+export interface ExecutiveData {
+ name: string;
+ role: string;
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/utils.ts b/fincept-terminal-desktop/src/components/tabs/relationship-map/utils.ts
new file mode 100644
index 000000000..2725091d4
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/utils.ts
@@ -0,0 +1,53 @@
+// Utility functions for RelationshipMapTab
+
+/**
+ * Format monetary values with appropriate suffixes
+ */
+export const formatMoney = (val: number): string => {
+ if (!val || val === 0) return '$0';
+ if (val >= 1e12) return `$${(val / 1e12).toFixed(2)}T`;
+ if (val >= 1e9) return `$${(val / 1e9).toFixed(2)}B`;
+ if (val >= 1e6) return `$${(val / 1e6).toFixed(2)}M`;
+ if (val >= 1e3) return `$${(val / 1e3).toFixed(2)}K`;
+ return `$${val.toFixed(2)}`;
+};
+
+/**
+ * Format market cap with appropriate suffixes (same as formatMoney but for display)
+ */
+export const formatMarketCap = (val: number): string => {
+ if (!val) return 'N/A';
+ if (val >= 1e12) return `$${(val / 1e12).toFixed(2)}T`;
+ if (val >= 1e9) return `$${(val / 1e9).toFixed(2)}B`;
+ if (val >= 1e6) return `$${(val / 1e6).toFixed(2)}M`;
+ return `$${val}`;
+};
+
+/**
+ * Format percentage values
+ */
+export const formatPercent = (val: number): string => {
+ if (!val && val !== 0) return 'N/A';
+ return `${(val * 100).toFixed(2)}%`;
+};
+
+/**
+ * Format large numbers with appropriate suffixes
+ */
+export const formatNumber = (val: number): string => {
+ if (!val && val !== 0) return 'N/A';
+ if (val >= 1e9) return `${(val / 1e9).toFixed(2)}B`;
+ if (val >= 1e6) return `${(val / 1e6).toFixed(2)}M`;
+ return val.toFixed(2);
+};
+
+/**
+ * Format date for display
+ */
+export const formatDate = (dateStr: string): string => {
+ return new Date(dateStr).toLocaleDateString('en-US', {
+ month: 'short',
+ day: 'numeric',
+ year: '2-digit',
+ });
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/AIChatPanel.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/AIChatPanel.tsx
new file mode 100644
index 000000000..127ec26d8
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/AIChatPanel.tsx
@@ -0,0 +1,214 @@
+import React, { useRef, useEffect } from 'react';
+import {
+ Bot,
+ Send,
+ User,
+ Sparkles,
+} from 'lucide-react';
+import { AIChatPanelProps } from './types';
+import { FINCEPT_COLORS } from './constants';
+import MarkdownRenderer from '../../common/MarkdownRenderer';
+
+export const AIChatPanel: React.FC<AIChatPanelProps> = ({
+ messages,
+ input,
+ onInputChange,
+ onSendMessage,
+ onQuickAction,
+ isTyping,
+ streamingContent,
+ currentProvider,
+ onProviderChange,
+ availableModels,
+}) => {
+ const messagesEndRef = useRef<HTMLDivElement>(null);
+
+ // Auto-scroll to bottom when messages change
+ useEffect(() => {
+ messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
+ }, [messages, streamingContent]);
+
+ const handleKeyPress = (e: React.KeyboardEvent) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ onSendMessage();
+ }
+ };
+
+ return (
+ <div className="flex flex-col h-full min-h-0" style={{ backgroundColor: FINCEPT_COLORS.PANEL_BG }}>
+ {/* AI Assistant Header */}
+ <div className="p-4 border-b border-[#333333] flex-shrink-0">
+ <div className="flex items-center justify-between mb-3">
+ <div className="flex items-center gap-2">
+ <Bot size={18} style={{ color: FINCEPT_COLORS.ORANGE }} />
+ <h3 className="text-sm font-bold" style={{ color: FINCEPT_COLORS.ORANGE }}>
+ AI WRITING ASSISTANT
+ </h3>
+ </div>
+ <Sparkles size={16} style={{ color: FINCEPT_COLORS.ORANGE }} />
+ </div>
+
+ {/* Model Selector */}
+ <div className="mb-3">
+ <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ AI Model
+ </label>
+ <select
+ value={currentProvider}
+ onChange={(e) => onProviderChange(e.target.value)}
+ className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ {availableModels.map(model => (
+ <option key={model.id} value={model.provider}>
+ {model.name} ({model.provider})
+ </option>
+ ))}
+ {availableModels.length === 0 && (
+ <option value="ollama">Configure in Settings</option>
+ )}
+ </select>
+ </div>
+
+ {/* Quick Actions */}
+ <div className="grid grid-cols-2 gap-1">
+ <button
+ onClick={() => onQuickAction('improve')}
+ className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ ✨ Improve
+ </button>
+ <button
+ onClick={() => onQuickAction('expand')}
+ className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ 📝 Expand
+ </button>
+ <button
+ onClick={() => onQuickAction('summarize')}
+ className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ 📋 Summary
+ </button>
+ <button
+ onClick={() => onQuickAction('grammar')}
+ className="px-2 py-1 text-[9px] rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ [OK] Grammar
+ </button>
+ </div>
+ </div>
+
+ {/* AI Chat Messages */}
+ <div className="flex-1 overflow-y-auto p-4 space-y-3 min-h-0">
+ {messages.length === 0 && (
+ <div className="text-center py-8">
+ <Bot size={32} className="mx-auto mb-3" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }} />
+ <p className="text-xs" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Ask me to help you write better reports!
+ </p>
+ <p className="text-[9px] mt-2" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Try: "Help me write an introduction"
+ </p>
+ </div>
+ )}
+
+ {messages.map((msg, idx) => (
+ <div key={idx} className={`flex gap-2 ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
+ {msg.role === 'assistant' && (
+ <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center" style={{ backgroundColor: FINCEPT_COLORS.ORANGE }}>
+ <Bot size={14} style={{ color: '#000' }} />
+ </div>
+ )}
+ <div
+ className={`max-w-[85%] rounded-lg p-3 ${
+ msg.role === 'user'
+ ? 'bg-[#FFA500] text-black'
+ : 'bg-[#1a1a1a] border border-[#333333]'
+ }`}
+ >
+ <div className="text-xs break-words" style={{ color: msg.role === 'user' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}>
+ {msg.role === 'assistant' ? (
+ <MarkdownRenderer content={msg.content} />
+ ) : (
+ msg.content
+ )}
+ </div>
+ </div>
+ {msg.role === 'user' && (
+ <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center bg-[#333333]">
+ <User size={14} style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }} />
+ </div>
+ )}
+ </div>
+ ))}
+
+ {/* Streaming content */}
+ {isTyping && streamingContent && (
+ <div className="flex gap-2 justify-start">
+ <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center" style={{ backgroundColor: FINCEPT_COLORS.ORANGE }}>
+ <Bot size={14} style={{ color: '#000' }} />
+ </div>
+ <div className="max-w-[85%] rounded-lg p-3 bg-[#1a1a1a] border border-[#333333]">
+ <div className="text-xs break-words" style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}>
+ <MarkdownRenderer content={streamingContent} />
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Typing indicator */}
+ {isTyping && !streamingContent && (
+ <div className="flex gap-2 justify-start">
+ <div className="flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center" style={{ backgroundColor: FINCEPT_COLORS.ORANGE }}>
+ <Bot size={14} style={{ color: '#000' }} />
+ </div>
+ <div className="max-w-[85%] rounded-lg p-3 bg-[#1a1a1a] border border-[#333333]">
+ <div className="text-xs flex gap-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <span className="animate-bounce">●</span>
+ <span className="animate-bounce delay-100">●</span>
+ <span className="animate-bounce delay-200">●</span>
+ </div>
+ </div>
+ </div>
+ )}
+
+ <div ref={messagesEndRef} />
+ </div>
+
+ {/* AI Input */}
+ <div className="p-4 border-t border-[#333333] flex-shrink-0">
+ <div className="flex gap-2">
+ <input
+ type="text"
+ value={input}
+ onChange={(e) => onInputChange(e.target.value)}
+ onKeyPress={handleKeyPress}
+ placeholder="Ask AI to help with your report..."
+ className="flex-1 px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ disabled={isTyping}
+ />
+ <button
+ onClick={onSendMessage}
+ disabled={isTyping || !input.trim()}
+ className="px-3 py-2 rounded transition-all disabled:opacity-50 disabled:cursor-not-allowed"
+ style={{
+ backgroundColor: FINCEPT_COLORS.ORANGE,
+ color: '#000'
+ }}
+ >
+ <Send size={16} />
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default AIChatPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/ComponentToolbar.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/ComponentToolbar.tsx
new file mode 100644
index 000000000..14dcf77e1
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/ComponentToolbar.tsx
@@ -0,0 +1,561 @@
+import React from 'react';
+import {
+ Type,
+ AlignLeft,
+ BarChart3,
+ Table,
+ Image as ImageIcon,
+ Code,
+ Minus,
+ Quote,
+ List,
+ Hash,
+ TrendingUp,
+ Activity,
+ Database,
+ PenTool,
+ AlertTriangle,
+ QrCode,
+ Stamp,
+ Layout,
+ Columns as ColumnsIcon,
+ BookOpen,
+ FileX,
+ Bold,
+ Italic,
+} from 'lucide-react';
+import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors, DragEndEvent } from '@dnd-kit/core';
+import { SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy } from '@dnd-kit/sortable';
+import { useTranslation } from 'react-i18next';
+import { SortableComponent } from './SortableComponent';
+import { ComponentToolbarProps } from './types';
+import { FINCEPT_COLORS, PAGE_THEMES, FONT_FAMILIES, PRESET_COLORS } from './constants';
+
+export const ComponentToolbar: React.FC<ComponentToolbarProps> = ({
+ onAddComponent,
+ template,
+ selectedComponent,
+ onSelectComponent,
+ onDeleteComponent,
+ onDuplicateComponent,
+ onDragEnd,
+ pageTheme,
+ onPageThemeChange,
+ customBgColor,
+ onCustomBgColorChange,
+ showColorPicker,
+ onShowColorPickerChange,
+ fontFamily,
+ onFontFamilyChange,
+ defaultFontSize,
+ onDefaultFontSizeChange,
+ isBold,
+ onIsBoldChange,
+ isItalic,
+ onIsItalicChange,
+}) => {
+ const { t } = useTranslation('reportBuilder');
+
+ const sensors = useSensors(
+ useSensor(PointerSensor),
+ useSensor(KeyboardSensor, {
+ coordinateGetter: sortableKeyboardCoordinates,
+ })
+ );
+
+ // HSL to Hex conversion helper
+ const hslToHex = (h: number, s: number, l: number) => {
+ l /= 100;
+ const a = s * Math.min(l, 1 - l) / 100;
+ const f = (n: number) => {
+ const k = (n + h / 30) % 12;
+ const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
+ return Math.round(255 * color).toString(16).padStart(2, '0');
+ };
+ return `#${f(0)}${f(8)}${f(4)}`;
+ };
+
+ return (
+ <div className="w-1/5 border-r overflow-y-auto" style={{ borderColor: FINCEPT_COLORS.BORDER, backgroundColor: FINCEPT_COLORS.PANEL_BG }}>
+ <div className="p-3">
+ {/* Add Components */}
+ <div className="mb-4">
+ <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>{t('components.title')}</h3>
+ <div className="space-y-1">
+ <button
+ onClick={() => onAddComponent('heading')}
+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <Type size={14} />
+ Heading
+ </button>
+ <button
+ onClick={() => onAddComponent('text')}
+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <AlignLeft size={14} />
+ Text
+ </button>
+ <button
+ onClick={() => onAddComponent('chart')}
+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <BarChart3 size={14} />
+ Chart
+ </button>
+ <button
+ onClick={() => onAddComponent('table')}
+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <Table size={14} />
+ Table
+ </button>
+ <button
+ onClick={() => onAddComponent('image')}
+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <ImageIcon size={14} />
+ Image
+ </button>
+ <button
+ onClick={() => onAddComponent('code')}
+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <Code size={14} />
+ Code Block
+ </button>
+ <button
+ onClick={() => onAddComponent('divider')}
+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <Minus size={14} />
+ Divider
+ </button>
+ <button
+ onClick={() => onAddComponent('quote' as any)}
+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <Quote size={14} />
+ Quote/Callout
+ </button>
+ <button
+ onClick={() => onAddComponent('list' as any)}
+ className="w-full px-3 py-2 text-xs text-left rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-2"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <List size={14} />
+ List
+ </button>
+ </div>
+ </div>
+
+ {/* Data Components */}
+ <div className="mb-4">
+ <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>DATA</h3>
+ <div className="grid grid-cols-2 gap-1">
+ <button
+ onClick={() => onAddComponent('kpi' as any)}
+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <TrendingUp size={14} />
+ <span className="text-[9px]">KPI</span>
+ </button>
+ <button
+ onClick={() => onAddComponent('sparkline' as any)}
+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <Activity size={14} />
+ <span className="text-[9px]">Sparkline</span>
+ </button>
+ <button
+ onClick={() => onAddComponent('liveTable' as any)}
+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <Database size={14} />
+ <span className="text-[9px]">Data Table</span>
+ </button>
+ <button
+ onClick={() => onAddComponent('dynamicChart' as any)}
+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <BarChart3 size={14} />
+ <span className="text-[9px]">Chart</span>
+ </button>
+ </div>
+ </div>
+
+ {/* Document Components */}
+ <div className="mb-4">
+ <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>DOCUMENT</h3>
+ <div className="grid grid-cols-2 gap-1">
+ <button
+ onClick={() => onAddComponent('toc' as any)}
+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <Hash size={14} />
+ <span className="text-[9px]">TOC</span>
+ </button>
+ <button
+ onClick={() => onAddComponent('signature' as any)}
+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <PenTool size={14} />
+ <span className="text-[9px]">Signature</span>
+ </button>
+ <button
+ onClick={() => onAddComponent('disclaimer' as any)}
+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <AlertTriangle size={14} />
+ <span className="text-[9px]">Disclaimer</span>
+ </button>
+ <button
+ onClick={() => onAddComponent('qrcode' as any)}
+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <QrCode size={14} />
+ <span className="text-[9px]">QR Code</span>
+ </button>
+ <button
+ onClick={() => onAddComponent('watermark' as any)}
+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <Stamp size={14} />
+ <span className="text-[9px]">Watermark</span>
+ </button>
+ </div>
+ </div>
+
+ {/* Layout Components */}
+ <div className="mb-4">
+ <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>{t('layout.title')}</h3>
+ <div className="grid grid-cols-2 gap-1">
+ <button
+ onClick={() => onAddComponent('section')}
+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <Layout size={14} />
+ <span className="text-[9px]">Section</span>
+ </button>
+ <button
+ onClick={() => onAddComponent('columns')}
+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <ColumnsIcon size={14} />
+ <span className="text-[9px]">Columns</span>
+ </button>
+ <button
+ onClick={() => onAddComponent('coverpage')}
+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <BookOpen size={14} />
+ <span className="text-[9px]">Cover</span>
+ </button>
+ <button
+ onClick={() => onAddComponent('pagebreak')}
+ className="px-2 py-2 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex flex-col items-center gap-1"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <FileX size={14} />
+ <span className="text-[9px]">Break</span>
+ </button>
+ </div>
+ </div>
+
+ {/* Settings */}
+ <div className="mb-4">
+ <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>{t('settings.title')}</h3>
+ <div className="space-y-2">
+ <div>
+ <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Page Theme
+ </label>
+ <select
+ value={pageTheme}
+ onChange={(e) => onPageThemeChange(e.target.value as any)}
+ className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ {Object.entries(PAGE_THEMES).map(([value, label]) => (
+ <option key={value} value={value}>{label}</option>
+ ))}
+ </select>
+ </div>
+
+ {/* Color Picker for Classic Theme */}
+ {pageTheme === 'classic' && (
+ <div>
+ <div className="flex items-center justify-between mb-1">
+ <label className="text-[9px]" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Background Color
+ </label>
+ <button
+ onClick={() => onShowColorPickerChange(!showColorPicker)}
+ className="text-[9px] px-2 py-1 rounded hover:bg-[#2a2a2a]"
+ style={{ color: FINCEPT_COLORS.ORANGE }}
+ >
+ {showColorPicker ? 'Hide Picker' : 'Show Picker'}
+ </button>
+ </div>
+
+ {/* Current Color Display */}
+ <div className="flex items-center gap-2 mb-2">
+ <div
+ className="w-8 h-8 rounded border-2 border-[#333333]"
+ style={{ backgroundColor: customBgColor }}
+ />
+ <input
+ type="text"
+ value={customBgColor}
+ onChange={(e) => onCustomBgColorChange(e.target.value)}
+ className="flex-1 px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ placeholder="#ffffff"
+ />
+ </div>
+
+ {/* Advanced Color Picker */}
+ {showColorPicker && (
+ <div className="p-3 rounded bg-[#0a0a0a] border border-[#333333] space-y-3">
+ {/* Main Gradient Palette */}
+ <div>
+ <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Color Palette
+ </label>
+ <div
+ className="w-full h-32 rounded cursor-crosshair border border-[#333333] relative"
+ style={{
+ background: `
+ linear-gradient(to bottom, transparent, black),
+ linear-gradient(to right, white, hsl(${customBgColor.startsWith('#') ? 0 : 120}, 100%, 50%))
+ `
+ }}
+ onClick={(e) => {
+ const rect = e.currentTarget.getBoundingClientRect();
+ const x = e.clientX - rect.left;
+ const y = e.clientY - rect.top;
+ const percentX = x / rect.width;
+ const percentY = y / rect.height;
+ const hue = percentX * 360;
+ const lightness = 100 - (percentY * 50);
+ onCustomBgColorChange(hslToHex(hue, 100, lightness));
+ }}
+ >
+ <div
+ className="absolute w-3 h-3 border-2 border-white rounded-full shadow-lg pointer-events-none"
+ style={{
+ left: '50%',
+ top: '10%',
+ transform: 'translate(-50%, -50%)'
+ }}
+ />
+ </div>
+ </div>
+
+ {/* Hue Slider */}
+ <div>
+ <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Hue
+ </label>
+ <div
+ className="w-full h-6 rounded cursor-pointer border border-[#333333]"
+ style={{
+ background: 'linear-gradient(to right, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000)'
+ }}
+ onClick={(e) => {
+ const rect = e.currentTarget.getBoundingClientRect();
+ const x = e.clientX - rect.left;
+ const percent = x / rect.width;
+ const hue = Math.round(percent * 360);
+ onCustomBgColorChange(hslToHex(hue, 100, 50));
+ }}
+ />
+ </div>
+
+ {/* Lightness Slider */}
+ <div>
+ <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Lightness
+ </label>
+ <div
+ className="w-full h-6 rounded cursor-pointer border border-[#333333]"
+ style={{
+ background: 'linear-gradient(to right, #000000, #808080, #ffffff)'
+ }}
+ onClick={(e) => {
+ const rect = e.currentTarget.getBoundingClientRect();
+ const x = e.clientX - rect.left;
+ const percent = x / rect.width;
+ const lightness = Math.round(percent * 100);
+ onCustomBgColorChange(hslToHex(120, 0, lightness));
+ }}
+ />
+ </div>
+
+ {/* Preset Colors */}
+ <div>
+ <label className="text-[9px] mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Preset Colors
+ </label>
+ <div className="grid grid-cols-8 gap-1">
+ {PRESET_COLORS.map(color => (
+ <button
+ key={color}
+ onClick={() => onCustomBgColorChange(color)}
+ className={`w-full aspect-square rounded border-2 transition-all hover:scale-110 ${
+ customBgColor.toLowerCase() === color.toLowerCase()
+ ? 'border-[#FFA500] ring-2 ring-[#FFA500]'
+ : 'border-[#333333] hover:border-[#666]'
+ }`}
+ style={{ backgroundColor: color }}
+ title={color}
+ />
+ ))}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+
+ <div>
+ <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Report Title
+ </label>
+ <input
+ type="text"
+ value={template.metadata.title}
+ readOnly
+ className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] outline-none opacity-60"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ placeholder="Edit in Properties panel..."
+ />
+ </div>
+
+ <div>
+ <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Font Family
+ </label>
+ <select
+ value={fontFamily}
+ onChange={(e) => onFontFamilyChange(e.target.value)}
+ className="w-full px-2 py-1 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ {FONT_FAMILIES.map(font => (
+ <option key={font.value} value={font.value}>{font.label}</option>
+ ))}
+ </select>
+ </div>
+
+ <div>
+ <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Base Font Size
+ </label>
+ <div className="flex items-center gap-2">
+ <input
+ type="range"
+ min="8"
+ max="16"
+ value={defaultFontSize}
+ onChange={(e) => onDefaultFontSizeChange(Number(e.target.value))}
+ className="flex-1"
+ style={{ accentColor: FINCEPT_COLORS.ORANGE }}
+ />
+ <span className="text-xs" style={{ color: FINCEPT_COLORS.TEXT_PRIMARY, minWidth: '30px' }}>
+ {defaultFontSize}pt
+ </span>
+ </div>
+ </div>
+
+ <div>
+ <label className="text-[9px] block mb-1" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Text Style
+ </label>
+ <div className="flex gap-2">
+ <button
+ onClick={() => onIsBoldChange(!isBold)}
+ className={`flex-1 px-3 py-2 rounded border transition-all ${
+ isBold
+ ? 'bg-[#FFA500] border-[#FFA500] text-black'
+ : 'bg-[#0a0a0a] border-[#333333] text-gray-400 hover:border-[#FFA500]'
+ }`}
+ title="Toggle Bold"
+ >
+ <Bold size={16} className="mx-auto" />
+ </button>
+ <button
+ onClick={() => onIsItalicChange(!isItalic)}
+ className={`flex-1 px-3 py-2 rounded border transition-all ${
+ isItalic
+ ? 'bg-[#FFA500] border-[#FFA500] text-black'
+ : 'bg-[#0a0a0a] border-[#333333] text-gray-400 hover:border-[#FFA500]'
+ }`}
+ title="Toggle Italic"
+ >
+ <Italic size={16} className="mx-auto" />
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Document Structure */}
+ <div>
+ <h3 className="text-xs font-bold mb-2" style={{ color: FINCEPT_COLORS.ORANGE }}>DOCUMENT STRUCTURE</h3>
+ <div className="space-y-0">
+ {template.components.length === 0 ? (
+ <p className="text-xs text-center py-4" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ No components yet
+ </p>
+ ) : (
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragEnd={onDragEnd}
+ >
+ <SortableContext
+ items={template.components.map(c => c.id)}
+ strategy={verticalListSortingStrategy}
+ >
+ {template.components.map((component) => (
+ <SortableComponent
+ key={component.id}
+ component={component}
+ isSelected={selectedComponent === component.id}
+ onClick={() => onSelectComponent(component.id)}
+ onDelete={() => onDeleteComponent(component.id)}
+ onDuplicate={() => onDuplicateComponent(component.id)}
+ />
+ ))}
+ </SortableContext>
+ </DndContext>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default ComponentToolbar;
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/DocumentCanvas.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/DocumentCanvas.tsx
new file mode 100644
index 000000000..db3bcd0bf
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/DocumentCanvas.tsx
@@ -0,0 +1,421 @@
+import React from 'react';
+import {
+ FileText,
+ BarChart3,
+ Image as ImageIcon,
+} from 'lucide-react';
+import { ReportComponent } from '@/services/core/reportService';
+import { DocumentCanvasProps, PageTheme, ThemeBackgroundStyle } from './types';
+import {
+ LiveDataTable,
+ KPICardsRow,
+ Sparkline,
+ DynamicChart,
+} from './DataComponents';
+import {
+ QuoteBox,
+ ListComponent,
+ TableOfContents,
+ SignatureBlock,
+ DisclaimerSection,
+ QRCodeComponent,
+ Watermark,
+} from './AdditionalComponents';
+
+// Get theme background style
+export const getThemeBackground = (pageTheme: PageTheme, customBgColor: string): ThemeBackgroundStyle => {
+ switch (pageTheme) {
+ case 'modern':
+ return {
+ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
+ backgroundSize: 'cover',
+ color: '#ffffff',
+ };
+ case 'geometric':
+ return {
+ backgroundColor: '#ffffff',
+ backgroundImage: `
+ linear-gradient(30deg, rgba(255,165,0,0.08) 12%, transparent 12.5%, transparent 87%, rgba(255,165,0,0.08) 87.5%, rgba(255,165,0,0.08)),
+ linear-gradient(150deg, rgba(255,165,0,0.08) 12%, transparent 12.5%, transparent 87%, rgba(255,165,0,0.08) 87.5%, rgba(255,165,0,0.08)),
+ linear-gradient(30deg, rgba(255,165,0,0.05) 12%, transparent 12.5%, transparent 87%, rgba(255,165,0,0.05) 87.5%, rgba(255,165,0,0.05)),
+ linear-gradient(150deg, rgba(255,165,0,0.05) 12%, transparent 12.5%, transparent 87%, rgba(255,165,0,0.05) 87.5%, rgba(255,165,0,0.05))
+ `,
+ backgroundSize: '80px 140px',
+ backgroundPosition: '0 0, 0 0, 40px 70px, 40px 70px',
+ color: '#000000',
+ };
+ case 'gradient':
+ return {
+ background: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%)',
+ color: '#ffffff',
+ };
+ case 'minimal':
+ return {
+ backgroundColor: '#ffffff',
+ backgroundImage: `
+ linear-gradient(rgba(200,200,200,0.3) 1px, transparent 1px),
+ linear-gradient(90deg, rgba(200,200,200,0.3) 1px, transparent 1px)
+ `,
+ backgroundSize: '20px 20px',
+ color: '#000000',
+ };
+ case 'pattern':
+ return {
+ backgroundColor: '#ffffff',
+ backgroundImage: `
+ repeating-linear-gradient(45deg, transparent, transparent 10px, rgba(255,165,0,0.02) 10px, rgba(255,165,0,0.02) 20px),
+ repeating-linear-gradient(-45deg, transparent, transparent 10px, rgba(255,165,0,0.02) 10px, rgba(255,165,0,0.02) 20px),
+ radial-gradient(circle at 10% 10%, rgba(255,165,0,0.03) 0%, transparent 50%),
+ radial-gradient(circle at 90% 90%, rgba(255,165,0,0.03) 0%, transparent 50%)
+ `,
+ backgroundSize: 'cover',
+ color: '#000000',
+ };
+ case 'classic':
+ default:
+ return {
+ backgroundColor: customBgColor,
+ color: '#000000',
+ };
+ }
+};
+
+// Render individual component based on type
+const RenderComponent: React.FC<{
+ component: ReportComponent;
+ isSelected: boolean;
+ onClick: () => void;
+ template: any;
+ tocItems: any[];
+}> = ({ component, isSelected, onClick, template, tocItems }) => {
+ return (
+ <div
+ onClick={onClick}
+ className={`cursor-pointer transition-all ${
+ isSelected ? 'ring-2 ring-orange-500 ring-offset-2' : 'hover:ring-1 hover:ring-gray-300'
+ }`}
+ >
+ {component.type === 'heading' && (
+ <h2 className={`font-bold text-2xl text-${component.config.alignment || 'left'}`}>
+ {component.content || 'Heading'}
+ </h2>
+ )}
+ {component.type === 'text' && (
+ <p className={`text-${component.config.alignment || 'left'}`}>
+ {component.content || 'Text content'}
+ </p>
+ )}
+ {component.type === 'chart' && (
+ <div className="border border-gray-300 rounded p-8 bg-gray-50 text-center">
+ <BarChart3 className="w-16 h-16 mx-auto text-gray-400" />
+ <p className="text-sm text-gray-500 mt-2">Chart Placeholder</p>
+ </div>
+ )}
+ {component.type === 'table' && (
+ <div className="border border-gray-300 rounded overflow-hidden">
+ <table className="w-full">
+ <thead className="bg-gray-100">
+ <tr>
+ {(component.config.columns || ['Column 1', 'Column 2', 'Column 3']).map((col: string, idx: number) => (
+ <th key={idx} className="px-4 py-2 text-left text-sm font-semibold">{col}</th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ <tr className="border-t border-gray-200">
+ {(component.config.columns || ['Column 1', 'Column 2', 'Column 3']).map((_: any, idx: number) => (
+ <td key={idx} className="px-4 py-2 text-sm">Sample data</td>
+ ))}
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ )}
+ {component.type === 'image' && (
+ <div className="border border-gray-300 rounded p-4 bg-gray-50">
+ {component.config.imageUrl ? (
+ <img
+ src={`file://${component.config.imageUrl}`}
+ alt="Report Image"
+ className="max-w-full h-auto"
+ />
+ ) : (
+ <div className="text-center py-8 text-gray-400">
+ <ImageIcon className="w-12 h-12 mx-auto mb-2" />
+ <p className="text-sm">No image selected</p>
+ </div>
+ )}
+ </div>
+ )}
+ {component.type === 'code' && (
+ <pre className="bg-gray-900 text-green-400 p-4 rounded overflow-x-auto text-sm font-mono">
+ <code>{component.content || '// Code block'}</code>
+ </pre>
+ )}
+ {component.type === 'divider' && (
+ <hr className="border-t-2 border-gray-300 my-4" />
+ )}
+ {component.type === 'section' && (
+ <div className="border-l-4 p-4 my-4" style={{
+ borderColor: component.config.borderColor || '#FFA500',
+ backgroundColor: component.config.backgroundColor || '#f8f9fa'
+ }}>
+ <h3 className="font-bold text-lg mb-2" style={{ color: component.config.borderColor || '#FFA500' }}>
+ {component.config.sectionTitle || 'SECTION'}
+ </h3>
+ <p className="text-sm text-gray-600">Section content area - add child components here</p>
+ </div>
+ )}
+ {component.type === 'columns' && (
+ <div className={`grid gap-4 my-4 ${component.config.columnCount === 3 ? 'grid-cols-3' : 'grid-cols-2'}`}>
+ {Array.from({ length: component.config.columnCount || 2 }).map((_, idx) => (
+ <div key={idx} className="border border-gray-300 rounded p-4 bg-gray-50">
+ <p className="text-sm text-gray-500 text-center">Column {idx + 1}</p>
+ </div>
+ ))}
+ </div>
+ )}
+ {component.type === 'coverpage' && (
+ <div className="min-h-[400px] flex flex-col items-center justify-center text-center p-12" style={{
+ backgroundColor: component.config.backgroundColor || '#0a0a0a',
+ color: '#FFA500'
+ }}>
+ <h1 className="text-4xl font-bold mb-4">{template.metadata.title}</h1>
+ {component.config.subtitle && (
+ <p className="text-xl mb-8">{component.config.subtitle}</p>
+ )}
+ <div className="text-sm text-gray-400 mt-auto">
+ {template.metadata.company}<br />
+ {template.metadata.author}<br />
+ {template.metadata.date}
+ </div>
+ </div>
+ )}
+ {component.type === 'pagebreak' && (
+ <div className="my-8 py-4 border-t-2 border-dashed border-gray-400 text-center">
+ <span className="text-xs text-gray-400 bg-white px-3 py-1 rounded-full">Page Break</span>
+ </div>
+ )}
+ {/* New component types */}
+ {component.type === 'quote' && (
+ <QuoteBox
+ content={String(component.content || '')}
+ author={component.config.author}
+ type={component.config.quoteType || 'quote'}
+ />
+ )}
+ {component.type === 'list' && (
+ <ListComponent
+ items={component.config.items || ['Item 1', 'Item 2']}
+ ordered={component.config.ordered}
+ />
+ )}
+ {component.type === 'toc' && (
+ <TableOfContents
+ items={tocItems}
+ showPageNumbers={component.config.showPageNumbers}
+ />
+ )}
+ {component.type === 'kpi' && (
+ <KPICardsRow
+ cards={(component.config.kpis || []).map((k: any) => ({
+ title: k.label,
+ value: k.value,
+ change: k.change,
+ }))}
+ />
+ )}
+ {component.type === 'sparkline' && (
+ <div className="inline-block">
+ <Sparkline
+ config={{
+ data: component.config.data as number[] || [10, 20, 15, 25],
+ color: component.config.color || '#FFA500',
+ height: 50,
+ }}
+ />
+ </div>
+ )}
+ {component.type === 'liveTable' && (
+ <LiveDataTable
+ config={{
+ source: component.config.dataSource as 'portfolio' | 'watchlist' || 'portfolio',
+ columns: component.config.columns,
+ }}
+ />
+ )}
+ {component.type === 'dynamicChart' && (
+ <DynamicChart
+ config={{
+ type: (component.config.chartType || 'line') as 'line' | 'bar' | 'area' | 'pie',
+ data: component.config.data as Array<{ name: string; value: number }> || [],
+ height: 250,
+ }}
+ />
+ )}
+ {component.type === 'signature' && (
+ <SignatureBlock
+ name={component.config.name || 'Name'}
+ title={component.config.title}
+ date={template.metadata.date}
+ showLine={component.config.showLine}
+ />
+ )}
+ {component.type === 'disclaimer' && (
+ <DisclaimerSection
+ content={String(component.content || '')}
+ type={component.config.disclaimerType || 'standard'}
+ />
+ )}
+ {component.type === 'qrcode' && (
+ <QRCodeComponent
+ value={component.config.value || 'https://example.com'}
+ size={component.config.size || 100}
+ label={component.config.label}
+ />
+ )}
+ {component.type === 'watermark' && (
+ <Watermark
+ text={component.config.text || 'CONFIDENTIAL'}
+ opacity={component.config.opacity || 0.1}
+ rotation={component.config.rotation || -45}
+ />
+ )}
+ </div>
+ );
+};
+
+export const DocumentCanvas: React.FC<DocumentCanvasProps> = ({
+ template,
+ selectedComponent,
+ onSelectComponent,
+ pageTheme,
+ customBgColor,
+ fontFamily,
+ defaultFontSize,
+ isBold,
+ isItalic,
+ advancedStyles,
+ tocItems,
+}) => {
+ const themeBackground = getThemeBackground(pageTheme, customBgColor);
+
+ return (
+ <div className="w-3/5 overflow-y-auto p-6" style={{ backgroundColor: '#0f0f0f' }}>
+ <div
+ className="mx-auto shadow-lg"
+ style={{
+ width: '210mm',
+ minHeight: '297mm',
+ padding: '20mm',
+ fontFamily: fontFamily,
+ fontSize: `${defaultFontSize}pt`,
+ fontWeight: isBold ? 'bold' : 'normal',
+ fontStyle: isItalic ? 'italic' : 'normal',
+ ...(advancedStyles.paragraphStyles && {
+ lineHeight: advancedStyles.paragraphStyles.lineHeight,
+ letterSpacing: `${advancedStyles.paragraphStyles.letterSpacing}px`,
+ wordSpacing: `${advancedStyles.paragraphStyles.wordSpacing}px`,
+ }),
+ ...themeBackground,
+ }}
+ >
+ {/* Header (if enabled) */}
+ {advancedStyles.headerTemplate?.enabled && (
+ <div
+ className="mb-4 -mt-4 -mx-4 px-4"
+ style={{
+ backgroundColor: advancedStyles.headerTemplate.backgroundColor,
+ color: advancedStyles.headerTemplate.textColor,
+ fontSize: `${advancedStyles.headerTemplate.fontSize}pt`,
+ minHeight: advancedStyles.headerTemplate.height,
+ textAlign: advancedStyles.headerTemplate.alignment,
+ borderBottom: advancedStyles.headerTemplate.borderBottom ? '1px solid #E0E0E0' : 'none',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: advancedStyles.headerTemplate.alignment === 'center' ? 'center' :
+ advancedStyles.headerTemplate.alignment === 'right' ? 'flex-end' : 'space-between',
+ padding: '8px 20px',
+ }}
+ >
+ <span>
+ {advancedStyles.headerTemplate.content
+ .replace('{company}', template.metadata.company || 'Company')
+ .replace('{title}', template.metadata.title || 'Report')
+ .replace('{date}', template.metadata.date || new Date().toLocaleDateString())}
+ </span>
+ {advancedStyles.headerTemplate.showPageNumbers && (
+ <span>Page 1</span>
+ )}
+ </div>
+ )}
+
+ {/* Document Metadata */}
+ <div className="mb-8 border-b border-gray-300 pb-4">
+ <h1 className="text-3xl font-bold mb-2">{template.metadata.title}</h1>
+ {template.metadata.company && (
+ <p className="text-lg text-gray-600">{template.metadata.company}</p>
+ )}
+ {template.metadata.author && (
+ <p className="text-sm text-gray-500">By {template.metadata.author}</p>
+ )}
+ <p className="text-sm text-gray-500">{template.metadata.date}</p>
+ </div>
+
+ {/* Components */}
+ {template.components.length === 0 ? (
+ <div className="text-center py-16 text-gray-400">
+ <FileText className="w-16 h-16 mx-auto mb-4 opacity-30" />
+ <p className="text-lg">Your report is empty</p>
+ <p className="text-sm mt-2">Add components from the left panel to start building your report</p>
+ </div>
+ ) : (
+ <div className="space-y-4">
+ {template.components.map((component) => (
+ <RenderComponent
+ key={component.id}
+ component={component}
+ isSelected={selectedComponent === component.id}
+ onClick={() => onSelectComponent(component.id)}
+ template={template}
+ tocItems={tocItems}
+ />
+ ))}
+ </div>
+ )}
+
+ {/* Footer (if enabled) */}
+ {advancedStyles.footerTemplate?.enabled && (
+ <div
+ className="mt-8 -mb-4 -mx-4 px-4"
+ style={{
+ backgroundColor: advancedStyles.footerTemplate.backgroundColor,
+ color: advancedStyles.footerTemplate.textColor,
+ fontSize: `${advancedStyles.footerTemplate.fontSize}pt`,
+ minHeight: advancedStyles.footerTemplate.height,
+ textAlign: advancedStyles.footerTemplate.alignment,
+ borderTop: advancedStyles.footerTemplate.borderTop ? '1px solid #E0E0E0' : 'none',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: advancedStyles.footerTemplate.alignment === 'center' ? 'center' :
+ advancedStyles.footerTemplate.alignment === 'right' ? 'flex-end' : 'space-between',
+ padding: '8px 20px',
+ }}
+ >
+ <span>
+ {advancedStyles.footerTemplate.content
+ .replace('{company}', template.metadata.company || 'Company')
+ .replace('{title}', template.metadata.title || 'Report')
+ .replace('{date}', template.metadata.date || new Date().toLocaleDateString())}
+ </span>
+ {advancedStyles.footerTemplate.showPageNumbers && advancedStyles.footerTemplate.pageNumberPosition !== advancedStyles.footerTemplate.alignment && (
+ <span>Page 1</span>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default DocumentCanvas;
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/PropertiesPanel.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/PropertiesPanel.tsx
new file mode 100644
index 000000000..dbbe69dad
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/PropertiesPanel.tsx
@@ -0,0 +1,447 @@
+import React from 'react';
+import {
+ Settings as SettingsIcon,
+ X,
+ Plus,
+ Copy,
+ Trash2,
+ BookmarkPlus,
+} from 'lucide-react';
+import { PropertiesPanelProps } from './types';
+import { FINCEPT_COLORS, FONT_SIZES, CHART_TYPES } from './constants';
+
+export const PropertiesPanel: React.FC<PropertiesPanelProps> = ({
+ selectedComponent,
+ onUpdateComponent,
+ onDeleteComponent,
+ onDuplicateComponent,
+ onClearSelection,
+ onSaveAsTemplate,
+ onImageUpload,
+}) => {
+ if (!selectedComponent) {
+ return (
+ <div className="p-4 text-center" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ <SettingsIcon size={32} className="mx-auto mb-2 opacity-30" />
+ <p className="text-xs">Select a component to edit properties</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="p-4">
+ <div className="flex items-center justify-between mb-4">
+ <h3 className="text-sm font-bold" style={{ color: FINCEPT_COLORS.ORANGE }}>PROPERTIES</h3>
+ <button
+ onClick={onClearSelection}
+ className="p-1 hover:bg-[#2a2a2a] rounded"
+ style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}
+ >
+ <X size={16} />
+ </button>
+ </div>
+
+ <div className="space-y-4">
+ {/* Component Type */}
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Type
+ </label>
+ <div className="px-3 py-2 text-xs rounded bg-[#0a0a0a] capitalize">
+ {selectedComponent.type}
+ </div>
+ </div>
+
+ {/* Content Editor */}
+ {(selectedComponent.type === 'heading' || selectedComponent.type === 'text' || selectedComponent.type === 'code') && (
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Content
+ </label>
+ <textarea
+ value={selectedComponent.content || ''}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, { content: e.target.value })}
+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ rows={selectedComponent.type === 'code' ? 10 : 4}
+ placeholder="Enter content..."
+ />
+ </div>
+ )}
+
+ {/* Quote Content */}
+ {selectedComponent.type === 'quote' && (
+ <>
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Quote Text
+ </label>
+ <textarea
+ value={selectedComponent.content || ''}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, { content: e.target.value })}
+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ rows={3}
+ placeholder="Enter quote text..."
+ />
+ </div>
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Author
+ </label>
+ <input
+ type="text"
+ value={selectedComponent.config.author || ''}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, {
+ config: { ...selectedComponent.config, author: e.target.value }
+ })}
+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ placeholder="Enter author name..."
+ />
+ </div>
+ </>
+ )}
+
+ {/* Disclaimer Content */}
+ {selectedComponent.type === 'disclaimer' && (
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Disclaimer Text
+ </label>
+ <textarea
+ value={selectedComponent.content || ''}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, { content: e.target.value })}
+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ rows={4}
+ placeholder="Enter disclaimer text..."
+ />
+ </div>
+ )}
+
+ {/* Alignment */}
+ {(selectedComponent.type === 'heading' || selectedComponent.type === 'text') && (
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Alignment
+ </label>
+ <div className="flex gap-2">
+ {['left', 'center', 'right'].map((align) => (
+ <button
+ key={align}
+ onClick={() => onUpdateComponent(selectedComponent.id, {
+ config: { ...selectedComponent.config, alignment: align as any }
+ })}
+ className={`flex-1 px-3 py-2 text-xs rounded transition-colors capitalize ${
+ selectedComponent.config.alignment === align
+ ? 'bg-[#FFA500] text-black'
+ : 'bg-[#0a0a0a] hover:bg-[#2a2a2a]'
+ }`}
+ >
+ {align}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Font Size */}
+ {(selectedComponent.type === 'heading' || selectedComponent.type === 'text') && (
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Font Size
+ </label>
+ <select
+ value={selectedComponent.config.fontSize || 'base'}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, {
+ config: { ...selectedComponent.config, fontSize: e.target.value }
+ })}
+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ {FONT_SIZES.map(size => (
+ <option key={size.value} value={size.value}>{size.label}</option>
+ ))}
+ </select>
+ </div>
+ )}
+
+ {/* Image Upload */}
+ {selectedComponent.type === 'image' && (
+ <div>
+ <label className="text-xs font-semibold mb-2 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Image
+ </label>
+ {selectedComponent.config.imageUrl ? (
+ <div className="space-y-2">
+ <div className="text-xs text-gray-400 break-all bg-[#0a0a0a] p-2 rounded">
+ {selectedComponent.config.imageUrl.split('\\').pop()}
+ </div>
+ <div className="flex gap-2">
+ <button
+ onClick={onImageUpload}
+ className="flex-1 px-3 py-2 text-xs rounded bg-blue-600 hover:bg-blue-700 transition-colors"
+ >
+ Change Image
+ </button>
+ <button
+ onClick={() => onUpdateComponent(selectedComponent.id, {
+ config: { ...selectedComponent.config, imageUrl: undefined }
+ })}
+ className="flex-1 px-3 py-2 text-xs rounded bg-red-600 hover:bg-red-700 transition-colors"
+ >
+ Remove
+ </button>
+ </div>
+ </div>
+ ) : (
+ <button
+ onClick={onImageUpload}
+ className="w-full px-3 py-2 text-xs rounded transition-colors flex items-center justify-center gap-2"
+ style={{ backgroundColor: FINCEPT_COLORS.ORANGE, color: FINCEPT_COLORS.BLACK }}
+ >
+ <Plus size={14} />
+ Upload Image
+ </button>
+ )}
+ </div>
+ )}
+
+ {/* Table Columns */}
+ {selectedComponent.type === 'table' && (
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Columns (comma-separated)
+ </label>
+ <input
+ type="text"
+ value={(selectedComponent.config.columns || []).join(', ')}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, {
+ config: { ...selectedComponent.config, columns: e.target.value.split(',').map(s => s.trim()) }
+ })}
+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ placeholder="Column 1, Column 2, Column 3"
+ />
+ </div>
+ )}
+
+ {/* Chart Type */}
+ {selectedComponent.type === 'chart' && (
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Chart Type
+ </label>
+ <select
+ value={selectedComponent.config.chartType || 'bar'}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, {
+ config: { ...selectedComponent.config, chartType: e.target.value }
+ })}
+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ {CHART_TYPES.map(chart => (
+ <option key={chart.value} value={chart.value}>{chart.label}</option>
+ ))}
+ </select>
+ </div>
+ )}
+
+ {/* Section Settings */}
+ {selectedComponent.type === 'section' && (
+ <>
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Section Title
+ </label>
+ <input
+ type="text"
+ value={selectedComponent.config.sectionTitle || ''}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, {
+ config: { ...selectedComponent.config, sectionTitle: e.target.value }
+ })}
+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ placeholder="Enter section title..."
+ />
+ </div>
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Border Color
+ </label>
+ <input
+ type="color"
+ value={selectedComponent.config.borderColor || '#FFA500'}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, {
+ config: { ...selectedComponent.config, borderColor: e.target.value }
+ })}
+ className="w-full h-8 rounded cursor-pointer"
+ />
+ </div>
+ </>
+ )}
+
+ {/* Columns Count */}
+ {selectedComponent.type === 'columns' && (
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Number of Columns
+ </label>
+ <select
+ value={selectedComponent.config.columnCount || 2}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, {
+ config: { ...selectedComponent.config, columnCount: Number(e.target.value) as 2 | 3 }
+ })}
+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <option value={2}>2 Columns</option>
+ <option value={3}>3 Columns</option>
+ </select>
+ </div>
+ )}
+
+ {/* Signature Settings */}
+ {selectedComponent.type === 'signature' && (
+ <>
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Name
+ </label>
+ <input
+ type="text"
+ value={selectedComponent.config.name || ''}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, {
+ config: { ...selectedComponent.config, name: e.target.value }
+ })}
+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ placeholder="Enter name..."
+ />
+ </div>
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Title
+ </label>
+ <input
+ type="text"
+ value={selectedComponent.config.title || ''}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, {
+ config: { ...selectedComponent.config, title: e.target.value }
+ })}
+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ placeholder="Enter title..."
+ />
+ </div>
+ </>
+ )}
+
+ {/* QR Code Settings */}
+ {selectedComponent.type === 'qrcode' && (
+ <>
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ URL/Value
+ </label>
+ <input
+ type="text"
+ value={selectedComponent.config.value || ''}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, {
+ config: { ...selectedComponent.config, value: e.target.value }
+ })}
+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ placeholder="Enter URL..."
+ />
+ </div>
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Label
+ </label>
+ <input
+ type="text"
+ value={selectedComponent.config.label || ''}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, {
+ config: { ...selectedComponent.config, label: e.target.value }
+ })}
+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ placeholder="Enter label..."
+ />
+ </div>
+ </>
+ )}
+
+ {/* Watermark Settings */}
+ {selectedComponent.type === 'watermark' && (
+ <>
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Text
+ </label>
+ <input
+ type="text"
+ value={selectedComponent.config.text || ''}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, {
+ config: { ...selectedComponent.config, text: e.target.value }
+ })}
+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] focus:border-[#FFA500] outline-none"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ placeholder="Enter watermark text..."
+ />
+ </div>
+ <div>
+ <label className="text-xs font-semibold mb-1 block" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ Opacity
+ </label>
+ <input
+ type="range"
+ min="0.05"
+ max="0.3"
+ step="0.05"
+ value={selectedComponent.config.opacity || 0.1}
+ onChange={(e) => onUpdateComponent(selectedComponent.id, {
+ config: { ...selectedComponent.config, opacity: Number(e.target.value) }
+ })}
+ className="w-full"
+ style={{ accentColor: FINCEPT_COLORS.ORANGE }}
+ />
+ </div>
+ </>
+ )}
+
+ {/* Actions */}
+ <div className="pt-4 border-t" style={{ borderColor: FINCEPT_COLORS.BORDER }}>
+ <div className="flex gap-2 mb-2">
+ <button
+ onClick={() => onDuplicateComponent(selectedComponent.id)}
+ className="flex-1 px-3 py-2 text-xs rounded bg-[#0a0a0a] hover:bg-[#2a2a2a] transition-colors flex items-center justify-center gap-2"
+ >
+ <Copy size={14} />
+ Duplicate
+ </button>
+ <button
+ onClick={() => onDeleteComponent(selectedComponent.id)}
+ className="flex-1 px-3 py-2 text-xs rounded bg-red-600 hover:bg-red-700 transition-colors flex items-center justify-center gap-2"
+ >
+ <Trash2 size={14} />
+ Delete
+ </button>
+ </div>
+ <button
+ onClick={onSaveAsTemplate}
+ className="w-full px-3 py-2 text-xs rounded bg-[#0a0a0a] border border-[#333333] hover:border-[#FFA500] transition-colors flex items-center justify-center gap-2"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <BookmarkPlus size={14} />
+ Save as Template
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default PropertiesPanel;
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/ReportBuilderTab.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/ReportBuilderTab.tsx
new file mode 100644
index 000000000..57d704949
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/ReportBuilderTab.tsx
@@ -0,0 +1,524 @@
+import React, { useState, useCallback, useEffect } from 'react';
+import {
+ FolderOpen,
+ Settings as SettingsIcon,
+ Palette,
+ Bot,
+ MessageCircle,
+ History,
+} from 'lucide-react';
+import { toast } from 'sonner';
+import { useTranslation } from 'react-i18next';
+import { ReportComponent } from '@/services/core/reportService';
+import { ComponentTemplate, brandKitService, BrandKit, HeaderFooterTemplate, ParagraphStyles } from '@/services/core/brandKitService';
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
+import { Button } from '@/components/ui/button';
+import { TabFooter } from '@/components/common/TabFooter';
+
+// Import sub-components
+import { ReportHeader } from './ReportHeader';
+import { ComponentToolbar } from './ComponentToolbar';
+import { DocumentCanvas } from './DocumentCanvas';
+import { PropertiesPanel } from './PropertiesPanel';
+import { AIChatPanel } from './AIChatPanel';
+import { AdvancedStylingPanel } from './AdvancedStylingPanel';
+import { ExportDialog } from './ExportDialog';
+import { TemplateGallery } from './TemplateGallery';
+import {
+ CommentsPanel,
+ VersionHistoryPanel,
+ useCollaboration,
+} from './CollaborationFeatures';
+import {
+ useUndoRedo,
+ useAutoSave,
+ useKeyboardShortcuts,
+ FindReplaceDialog,
+ ShortcutsDialog,
+} from './ProductivityFeatures';
+
+// Import hooks
+import {
+ useReportTemplate,
+ useFileOperations,
+ useAIChat,
+ useBrandKit,
+ useImageUpload,
+} from './hooks';
+
+// Import types and constants
+import { PageTheme, RightPanelView } from './types';
+import { FINCEPT_COLORS } from './constants';
+
+const ReportBuilderTab: React.FC = () => {
+ const { t } = useTranslation('reportBuilder');
+ const [currentTime, setCurrentTime] = useState(new Date());
+
+ // Template management hook
+ const {
+ template,
+ setTemplate,
+ selectedComponent,
+ setSelectedComponent,
+ selectedComp,
+ addComponent,
+ updateComponent,
+ deleteComponent,
+ duplicateComponent,
+ handleDragEnd,
+ updateMetadata,
+ tocItems,
+ } = useReportTemplate();
+
+ // Style states
+ const [pageTheme, setPageTheme] = useState<PageTheme>('classic');
+ const [fontFamily, setFontFamily] = useState<string>('Arial, sans-serif');
+ const [defaultFontSize, setDefaultFontSize] = useState<number>(11);
+ const [isBold, setIsBold] = useState<boolean>(false);
+ const [isItalic, setIsItalic] = useState<boolean>(false);
+ const [customBgColor, setCustomBgColor] = useState<string>('#ffffff');
+ const [showColorPicker, setShowColorPicker] = useState<boolean>(false);
+
+ // UI states
+ const [rightPanelView, setRightPanelView] = useState<RightPanelView>('split');
+ const [showTemplateGallery, setShowTemplateGallery] = useState(false);
+ const [showFindReplace, setShowFindReplace] = useState(false);
+ const [showShortcuts, setShowShortcuts] = useState(false);
+ const [showExportDialog, setShowExportDialog] = useState(false);
+
+ // File operations hook
+ const {
+ isSaving,
+ showSuccessDialog,
+ setShowSuccessDialog,
+ generatedPdfPath,
+ saveTemplate,
+ loadTemplate,
+ handleShowInFolder,
+ } = useFileOperations(template, setTemplate);
+
+ // AI chat hook
+ const aiChat = useAIChat(template, fontFamily, defaultFontSize, pageTheme);
+
+ // Brand kit hook
+ const {
+ activeBrandKit,
+ advancedStyles,
+ setAdvancedStyles,
+ handleBrandKitChange: onBrandKitChange,
+ } = useBrandKit();
+
+ // Image upload hook
+ const { handleImageUpload } = useImageUpload(selectedComp, updateComponent);
+
+ // Undo/Redo hook
+ const {
+ state: templateHistory,
+ set: setTemplateWithHistory,
+ undo,
+ redo,
+ canUndo,
+ canRedo,
+ } = useUndoRedo(template);
+
+ // Auto-save hook
+ const { isSaving: isAutoSaving, lastSaved, forceSave } = useAutoSave(
+ template,
+ async (data) => {
+ try {
+ const { reportService } = await import('@/services/core/reportService');
+ await reportService.saveTemplate(data);
+ console.log('Auto-saved report');
+ } catch (error) {
+ console.error('Auto-save failed:', error);
+ }
+ },
+ { interval: 60000, enabled: true }
+ );
+
+ // Collaboration hook
+ const collaboration = useCollaboration(template);
+
+ // Keyboard shortcuts
+ useKeyboardShortcuts({
+ 'ctrl+z': () => undo(),
+ 'ctrl+y': () => redo(),
+ 'ctrl+shift+z': () => redo(),
+ 'ctrl+s': () => { forceSave(); toast.success('Saved'); },
+ 'ctrl+f': () => setShowFindReplace(true),
+ 'ctrl+shift+/': () => setShowShortcuts(true),
+ });
+
+ // Sync template with undo/redo history
+ useEffect(() => {
+ if (JSON.stringify(templateHistory) !== JSON.stringify(template)) {
+ setTemplate(templateHistory);
+ }
+ }, [templateHistory, template, setTemplate]);
+
+ // Update time
+ useEffect(() => {
+ const timer = setInterval(() => setCurrentTime(new Date()), 1000);
+ return () => clearInterval(timer);
+ }, []);
+
+ // Handle brand kit change (with font update)
+ const handleBrandKitChange = useCallback((brandKit: BrandKit) => {
+ const bodyFontFamily = onBrandKitChange(brandKit);
+ if (bodyFontFamily) {
+ setFontFamily(bodyFontFamily);
+ }
+ }, [onBrandKitChange]);
+
+ // Handle component template selection
+ const handleComponentTemplateSelect = useCallback((componentTemplate: ComponentTemplate) => {
+ const newComponent: ReportComponent = {
+ id: `component-${Date.now()}`,
+ type: componentTemplate.component.type as ReportComponent['type'],
+ content: componentTemplate.component.content,
+ config: componentTemplate.component.config,
+ children: componentTemplate.component.children,
+ };
+ setTemplate(prev => ({
+ ...prev,
+ components: [...prev.components, newComponent],
+ }));
+ setSelectedComponent(newComponent.id);
+ toast.success(`Added template: ${componentTemplate.name}`);
+ }, [setTemplate, setSelectedComponent]);
+
+ // Handle advanced styles change
+ const handleStylesChange = useCallback((styles: {
+ customCSS: string;
+ headerTemplate: HeaderFooterTemplate;
+ footerTemplate: HeaderFooterTemplate;
+ paragraphStyles: ParagraphStyles;
+ }) => {
+ setAdvancedStyles(styles);
+ }, [setAdvancedStyles]);
+
+ // Save component as template
+ const saveAsTemplate = useCallback(async () => {
+ if (!selectedComp) return;
+ const templateName = prompt('Enter template name:', `${selectedComp.type} Template`);
+ if (!templateName) return;
+
+ const newTemplate: ComponentTemplate = {
+ id: `template-${Date.now()}`,
+ name: templateName,
+ description: `Custom ${selectedComp.type} template`,
+ category: selectedComp.type === 'section' || selectedComp.type === 'columns' ? 'layout' :
+ selectedComp.type === 'image' ? 'media' :
+ selectedComp.type === 'chart' || selectedComp.type === 'table' ? 'data' : 'text',
+ component: {
+ type: selectedComp.type,
+ content: selectedComp.content,
+ config: selectedComp.config,
+ children: selectedComp.children,
+ },
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ };
+
+ try {
+ await brandKitService.saveComponentTemplate(newTemplate);
+ toast.success('Component saved as template');
+ } catch (error) {
+ toast.error('Failed to save template');
+ }
+ }, [selectedComp]);
+
+ // Handle add component with history
+ const handleAddComponent = useCallback((type: ReportComponent['type']) => {
+ addComponent(type);
+ setTemplateWithHistory(template);
+ }, [addComponent, template, setTemplateWithHistory]);
+
+ return (
+ <div className="h-full flex flex-col" style={{ backgroundColor: FINCEPT_COLORS.DARK_BG, color: FINCEPT_COLORS.TEXT_PRIMARY }}>
+ {/* Header */}
+ <ReportHeader
+ canUndo={canUndo}
+ canRedo={canRedo}
+ onUndo={undo}
+ onRedo={redo}
+ onFindReplace={() => setShowFindReplace(true)}
+ onShortcuts={() => setShowShortcuts(true)}
+ onTemplateGallery={() => setShowTemplateGallery(true)}
+ onLoad={loadTemplate}
+ onSave={saveTemplate}
+ onExport={() => setShowExportDialog(true)}
+ isSaving={isSaving}
+ isAutoSaving={isAutoSaving}
+ lastSaved={lastSaved}
+ hasComponents={template.components.length > 0}
+ />
+
+ {/* Main Content */}
+ <div className="flex-1 flex overflow-hidden">
+ {/* Left Panel - Components */}
+ <ComponentToolbar
+ onAddComponent={handleAddComponent}
+ template={template}
+ selectedComponent={selectedComponent}
+ onSelectComponent={setSelectedComponent}
+ onDeleteComponent={deleteComponent}
+ onDuplicateComponent={duplicateComponent}
+ onDragEnd={handleDragEnd}
+ pageTheme={pageTheme}
+ onPageThemeChange={setPageTheme}
+ customBgColor={customBgColor}
+ onCustomBgColorChange={setCustomBgColor}
+ showColorPicker={showColorPicker}
+ onShowColorPickerChange={setShowColorPicker}
+ fontFamily={fontFamily}
+ onFontFamilyChange={setFontFamily}
+ defaultFontSize={defaultFontSize}
+ onDefaultFontSizeChange={setDefaultFontSize}
+ isBold={isBold}
+ onIsBoldChange={setIsBold}
+ isItalic={isItalic}
+ onIsItalicChange={setIsItalic}
+ />
+
+ {/* Center - Canvas */}
+ <DocumentCanvas
+ template={template}
+ selectedComponent={selectedComponent}
+ onSelectComponent={setSelectedComponent}
+ pageTheme={pageTheme}
+ customBgColor={customBgColor}
+ fontFamily={fontFamily}
+ defaultFontSize={defaultFontSize}
+ isBold={isBold}
+ isItalic={isItalic}
+ advancedStyles={advancedStyles}
+ tocItems={tocItems}
+ />
+
+ {/* Right Panel - Properties, AI Chat, and Advanced Styling */}
+ <div className="w-1/5 border-l flex flex-col min-h-0" style={{ borderColor: FINCEPT_COLORS.BORDER, backgroundColor: FINCEPT_COLORS.PANEL_BG }}>
+ {/* Toggle Buttons */}
+ <div className="flex flex-wrap border-b" style={{ borderColor: FINCEPT_COLORS.BORDER }}>
+ <button
+ onClick={() => setRightPanelView('properties')}
+ className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${
+ rightPanelView === 'properties' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'
+ }`}
+ style={{ color: rightPanelView === 'properties' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}
+ title="Component Properties"
+ >
+ <SettingsIcon size={12} />
+ Props
+ </button>
+ <button
+ onClick={() => setRightPanelView('styling')}
+ className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${
+ rightPanelView === 'styling' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'
+ }`}
+ style={{ color: rightPanelView === 'styling' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}
+ title="Advanced Styling"
+ >
+ <Palette size={12} />
+ Style
+ </button>
+ <button
+ onClick={() => setRightPanelView('chat')}
+ className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${
+ rightPanelView === 'chat' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'
+ }`}
+ style={{ color: rightPanelView === 'chat' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}
+ title="AI Writing Assistant"
+ >
+ <Bot size={12} />
+ AI
+ </button>
+ <button
+ onClick={() => setRightPanelView('comments')}
+ className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${
+ rightPanelView === 'comments' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'
+ }`}
+ style={{ color: rightPanelView === 'comments' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}
+ title="Comments"
+ >
+ <MessageCircle size={12} />
+ </button>
+ <button
+ onClick={() => setRightPanelView('history')}
+ className={`flex-1 px-2 py-2 text-[10px] font-semibold transition-colors flex items-center justify-center gap-1 ${
+ rightPanelView === 'history' ? 'bg-[#FFA500] text-black' : 'bg-transparent hover:bg-[#2a2a2a]'
+ }`}
+ style={{ color: rightPanelView === 'history' ? '#000' : FINCEPT_COLORS.TEXT_PRIMARY }}
+ title="Version History"
+ >
+ <History size={12} />
+ </button>
+ </div>
+
+ {/* Properties Section */}
+ {(rightPanelView === 'properties' || rightPanelView === 'split') && (
+ <div className={`${rightPanelView === 'split' ? 'flex-1 border-b' : 'flex-1'} overflow-y-auto min-h-0`} style={{ borderColor: FINCEPT_COLORS.BORDER }}>
+ <PropertiesPanel
+ selectedComponent={selectedComp}
+ onUpdateComponent={updateComponent}
+ onDeleteComponent={deleteComponent}
+ onDuplicateComponent={duplicateComponent}
+ onClearSelection={() => setSelectedComponent(null)}
+ onSaveAsTemplate={saveAsTemplate}
+ onImageUpload={handleImageUpload}
+ />
+ </div>
+ )}
+
+ {/* AI Writing Assistant Section */}
+ {(rightPanelView === 'chat' || rightPanelView === 'split') && (
+ <div className={`${rightPanelView === 'split' ? 'flex-1' : 'flex-1'} flex flex-col min-h-0`}>
+ <AIChatPanel
+ messages={aiChat.messages}
+ input={aiChat.input}
+ onInputChange={aiChat.setInput}
+ onSendMessage={aiChat.sendMessage}
+ onQuickAction={aiChat.handleQuickAction}
+ isTyping={aiChat.isTyping}
+ streamingContent={aiChat.streamingContent}
+ currentProvider={aiChat.currentProvider}
+ onProviderChange={aiChat.setCurrentProvider}
+ availableModels={aiChat.availableModels}
+ />
+ </div>
+ )}
+
+ {/* Advanced Styling Panel */}
+ {rightPanelView === 'styling' && (
+ <div className="flex-1 overflow-hidden">
+ <AdvancedStylingPanel
+ onBrandKitChange={handleBrandKitChange}
+ onComponentTemplateSelect={handleComponentTemplateSelect}
+ onStylesChange={handleStylesChange}
+ />
+ </div>
+ )}
+
+ {/* Comments Panel */}
+ {rightPanelView === 'comments' && (
+ <div className="flex-1 overflow-hidden">
+ <CommentsPanel
+ comments={collaboration.comments}
+ onAddComment={(componentId: string, content: string) =>
+ collaboration.addComment(componentId, content)
+ }
+ onResolveComment={collaboration.resolveComment}
+ onDeleteComment={collaboration.deleteComment}
+ onReplyComment={collaboration.replyToComment}
+ selectedComponentId={selectedComponent}
+ />
+ </div>
+ )}
+
+ {/* Version History Panel */}
+ {rightPanelView === 'history' && (
+ <div className="flex-1 overflow-hidden">
+ <VersionHistoryPanel
+ history={collaboration.versionHistory}
+ onPreview={(entry) => {
+ toast.info(`Previewing version: ${entry.description}`);
+ }}
+ onRestore={(entry) => {
+ if (entry.template) {
+ setTemplate(entry.template);
+ setTemplateWithHistory(entry.template);
+ toast.success(`Restored version: ${entry.description}`);
+ }
+ }}
+ />
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Success Dialog */}
+ <Dialog open={showSuccessDialog} onOpenChange={setShowSuccessDialog}>
+ <DialogContent className="bg-[#1a1a1a] border-[#333333]">
+ <DialogHeader>
+ <DialogTitle className="text-[#FFA500]">PDF Generated Successfully!</DialogTitle>
+ <DialogDescription className="text-gray-400">
+ Your report has been generated and saved.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="py-4">
+ <p className="text-sm text-gray-300 mb-2">File saved to:</p>
+ <p className="text-xs text-gray-500 break-all bg-[#0a0a0a] p-2 rounded border border-[#333333]">
+ {generatedPdfPath}
+ </p>
+ </div>
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={() => setShowSuccessDialog(false)}
+ className="bg-transparent border-[#333333] text-white hover:bg-[#2a2a2a]"
+ >
+ Close
+ </Button>
+ <Button
+ onClick={handleShowInFolder}
+ className="bg-[#FFA500] text-black hover:bg-[#ff8c00]"
+ >
+ <FolderOpen className="w-4 h-4 mr-2" />
+ Show in Folder
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ {/* Export Dialog */}
+ <ExportDialog
+ open={showExportDialog}
+ onClose={() => setShowExportDialog(false)}
+ template={template}
+ brandKit={activeBrandKit}
+ />
+
+ {/* Template Gallery Dialog */}
+ <TemplateGallery
+ open={showTemplateGallery}
+ onClose={() => setShowTemplateGallery(false)}
+ onSelectTemplate={(t) => {
+ setTemplate(t);
+ setTemplateWithHistory(t);
+ toast.success(`Applied template: ${t.name}`);
+ }}
+ currentTemplate={template}
+ />
+
+ {/* Find & Replace Dialog */}
+ <FindReplaceDialog
+ open={showFindReplace}
+ onClose={() => setShowFindReplace(false)}
+ onReplace={(componentId, oldText, newText) => {
+ updateComponent(componentId, { content: newText });
+ }}
+ components={template.components}
+ />
+
+ {/* Keyboard Shortcuts Dialog */}
+ <ShortcutsDialog
+ open={showShortcuts}
+ onClose={() => setShowShortcuts(false)}
+ />
+
+ <TabFooter
+ tabName="REPORT BUILDER"
+ leftInfo={[
+ { label: `Components: ${template.components.length}`, color: FINCEPT_COLORS.TEXT_PRIMARY },
+ { label: `Theme: ${pageTheme.charAt(0).toUpperCase() + pageTheme.slice(1)}`, color: FINCEPT_COLORS.TEXT_PRIMARY },
+ ...(activeBrandKit ? [{ label: `Brand: ${activeBrandKit.name}`, color: FINCEPT_COLORS.ORANGE }] : []),
+ ]}
+ statusInfo={`${currentTime.toLocaleTimeString()} | Multi-format Export`}
+ backgroundColor={FINCEPT_COLORS.PANEL_BG}
+ borderColor={FINCEPT_COLORS.ORANGE}
+ />
+ </div>
+ );
+};
+
+export default ReportBuilderTab;
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/ReportHeader.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/ReportHeader.tsx
new file mode 100644
index 000000000..3fda3188b
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/ReportHeader.tsx
@@ -0,0 +1,134 @@
+import React from 'react';
+import {
+ FileText,
+ Download,
+ Save,
+ FolderOpen,
+ Undo2,
+ Redo2,
+ Search,
+ Keyboard,
+ LayoutTemplate,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { ReportHeaderProps } from './types';
+import { FINCEPT_COLORS } from './constants';
+
+export const ReportHeader: React.FC<ReportHeaderProps> = ({
+ canUndo,
+ canRedo,
+ onUndo,
+ onRedo,
+ onFindReplace,
+ onShortcuts,
+ onTemplateGallery,
+ onLoad,
+ onSave,
+ onExport,
+ isSaving,
+ isAutoSaving,
+ lastSaved,
+ hasComponents,
+}) => {
+ const { t } = useTranslation('reportBuilder');
+
+ return (
+ <div
+ className="flex items-center justify-between px-4 py-2 border-b"
+ style={{ borderColor: FINCEPT_COLORS.BORDER, backgroundColor: FINCEPT_COLORS.PANEL_BG }}
+ >
+ <div className="flex items-center gap-4">
+ <div className="flex items-center gap-2">
+ <FileText className="w-5 h-5" style={{ color: FINCEPT_COLORS.ORANGE }} />
+ <span className="font-bold text-sm" style={{ color: FINCEPT_COLORS.ORANGE }}>
+ {t('title')}
+ </span>
+ </div>
+
+ {/* Productivity Toolbar */}
+ <div className="flex items-center gap-1 border-l border-[#333333] pl-3">
+ <button
+ onClick={onUndo}
+ disabled={!canUndo}
+ className="p-1.5 rounded hover:bg-[#2a2a2a] disabled:opacity-30"
+ title="Undo (Ctrl+Z)"
+ >
+ <Undo2 size={14} />
+ </button>
+ <button
+ onClick={onRedo}
+ disabled={!canRedo}
+ className="p-1.5 rounded hover:bg-[#2a2a2a] disabled:opacity-30"
+ title="Redo (Ctrl+Y)"
+ >
+ <Redo2 size={14} />
+ </button>
+ <button
+ onClick={onFindReplace}
+ className="p-1.5 rounded hover:bg-[#2a2a2a]"
+ title="Find & Replace (Ctrl+F)"
+ >
+ <Search size={14} />
+ </button>
+ <button
+ onClick={onShortcuts}
+ className="p-1.5 rounded hover:bg-[#2a2a2a]"
+ title="Keyboard Shortcuts"
+ >
+ <Keyboard size={14} />
+ </button>
+ </div>
+
+ {/* Auto-save status */}
+ {lastSaved && (
+ <span className="text-[10px]" style={{ color: FINCEPT_COLORS.TEXT_SECONDARY }}>
+ {isAutoSaving ? 'Saving...' : `Saved ${lastSaved.toLocaleTimeString()}`}
+ </span>
+ )}
+ </div>
+
+ <div className="flex items-center gap-2">
+ <button
+ onClick={onTemplateGallery}
+ className="px-3 py-1 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-1"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <LayoutTemplate size={14} />
+ Templates
+ </button>
+ <button
+ onClick={onLoad}
+ className="px-3 py-1 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-1"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <FolderOpen size={14} />
+ {t('header.load')}
+ </button>
+ <button
+ onClick={onSave}
+ disabled={isSaving}
+ className="px-3 py-1 text-xs rounded hover:bg-[#2a2a2a] transition-colors flex items-center gap-1 disabled:opacity-50"
+ style={{ color: FINCEPT_COLORS.TEXT_PRIMARY }}
+ >
+ <Save size={14} />
+ {isSaving ? t('header.saving') : t('header.save')}
+ </button>
+ <button
+ onClick={onExport}
+ disabled={!hasComponents}
+ className="px-3 py-1 text-xs rounded transition-colors flex items-center gap-1 disabled:opacity-50"
+ style={{
+ backgroundColor: FINCEPT_COLORS.ORANGE,
+ color: FINCEPT_COLORS.BLACK,
+ fontWeight: 'bold'
+ }}
+ >
+ <Download size={14} />
+ Export
+ </button>
+ </div>
+ </div>
+ );
+};
+
+export default ReportHeader;
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/SortableComponent.tsx b/fincept-terminal-desktop/src/components/tabs/report-builder/SortableComponent.tsx
new file mode 100644
index 000000000..8a871a329
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/SortableComponent.tsx
@@ -0,0 +1,122 @@
+import React from 'react';
+import { useSortable } from '@dnd-kit/sortable';
+import { CSS } from '@dnd-kit/utilities';
+import {
+ Type,
+ AlignLeft,
+ BarChart3,
+ Table,
+ Image as ImageIcon,
+ Code,
+ Minus,
+ Quote,
+ List,
+ Hash,
+ TrendingUp,
+ Activity,
+ Database,
+ PenTool,
+ AlertTriangle,
+ QrCode,
+ Stamp,
+ FileText,
+ Move,
+ Copy,
+ Trash2,
+} from 'lucide-react';
+import { ReportComponent } from '@/services/core/reportService';
+import { SortableComponentProps } from './types';
+
+// Get icon for component type
+const getComponentIcon = (type: ReportComponent['type']) => {
+ switch (type) {
+ case 'heading': return <Type size={14} />;
+ case 'text': return <AlignLeft size={14} />;
+ case 'chart': return <BarChart3 size={14} />;
+ case 'table': return <Table size={14} />;
+ case 'image': return <ImageIcon size={14} />;
+ case 'code': return <Code size={14} />;
+ case 'divider': return <Minus size={14} />;
+ case 'quote': return <Quote size={14} />;
+ case 'list': return <List size={14} />;
+ case 'toc': return <Hash size={14} />;
+ case 'kpi': return <TrendingUp size={14} />;
+ case 'sparkline': return <Activity size={14} />;
+ case 'liveTable': return <Database size={14} />;
+ case 'signature': return <PenTool size={14} />;
+ case 'disclaimer': return <AlertTriangle size={14} />;
+ case 'qrcode': return <QrCode size={14} />;
+ case 'watermark': return <Stamp size={14} />;
+ default: return <FileText size={14} />;
+ }
+};
+
+// Get preview text for component
+const getPreviewText = (component: ReportComponent): string => {
+ if (component.content) {
+ return String(component.content).substring(0, 40);
+ }
+ return `${component.type.charAt(0).toUpperCase() + component.type.slice(1)} component`;
+};
+
+export const SortableComponent: React.FC<SortableComponentProps> = ({
+ component,
+ isSelected,
+ onClick,
+ onDelete,
+ onDuplicate,
+}) => {
+ const {
+ attributes,
+ listeners,
+ setNodeRef,
+ transform,
+ transition,
+ } = useSortable({ id: component.id });
+
+ const style = {
+ transform: CSS.Transform.toString(transform),
+ transition,
+ };
+
+ return (
+ <div
+ ref={setNodeRef}
+ style={style}
+ className={`flex items-center justify-between p-2 mb-1 cursor-pointer transition-colors border-l-2 ${
+ isSelected
+ ? 'bg-[#2a2a2a] border-l-[#FFA500]'
+ : 'bg-transparent border-l-transparent hover:bg-[#1a1a1a]'
+ }`}
+ onClick={onClick}
+ >
+ <div className="flex items-center gap-2 flex-1 min-w-0">
+ <div {...attributes} {...listeners} className="cursor-move text-gray-500 hover:text-[#FFA500]">
+ <Move size={14} />
+ </div>
+ <div className="text-[#FFA500]">
+ {getComponentIcon(component.type)}
+ </div>
+ <span className="text-xs text-gray-400 truncate">{getPreviewText(component)}</span>
+ </div>
+ <div className="flex gap-1">
+ <button
+ onClick={(e) => { e.stopPropagation(); onDuplicate(); }}
+ className="p-1 hover:bg-[#333333] rounded text-gray-400 hover:text-[#FFA500]"
+ title="Duplicate"
+ >
+ <Copy size={12} />
+ </button>
+ <button
+ onClick={(e) => { e.stopPropagation(); onDelete(); }}
+ className="p-1 hover:bg-[#333333] rounded text-gray-400 hover:text-red-500"
+ title="Delete"
+ >
+ <Trash2 size={12} />
+ </button>
+ </div>
+ </div>
+ );
+};
+
+export default SortableComponent;
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/constants.ts b/fincept-terminal-desktop/src/components/tabs/report-builder/constants.ts
new file mode 100644
index 000000000..5ecbffed4
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/constants.ts
@@ -0,0 +1,71 @@
+// Fincept color palette for Report Builder
+export const FINCEPT_COLORS = {
+ ORANGE: '#FFA500',
+ WHITE: '#FFFFFF',
+ BLACK: '#000000',
+ DARK_BG: '#0a0a0a',
+ PANEL_BG: '#1a1a1a',
+ BORDER: '#333333',
+ HOVER: '#2a2a2a',
+ TEXT_PRIMARY: '#FFFFFF',
+ TEXT_SECONDARY: '#999999',
+} as const;
+
+// Page theme options
+export const PAGE_THEMES = {
+ classic: 'Classic White',
+ minimal: 'Minimal Grid',
+ geometric: 'Geometric Triangles',
+ pattern: 'Diagonal Pattern',
+ modern: 'Modern Gradient (Dark)',
+ gradient: 'Professional Gradient (Dark)',
+} as const;
+
+// Font family options
+export const FONT_FAMILIES = [
+ { value: 'Arial, sans-serif', label: 'Arial' },
+ { value: "'Times New Roman', serif", label: 'Times New Roman' },
+ { value: 'Georgia, serif', label: 'Georgia' },
+ { value: "'Courier New', monospace", label: 'Courier New' },
+ { value: 'Verdana, sans-serif', label: 'Verdana' },
+ { value: "'Trebuchet MS', sans-serif", label: 'Trebuchet MS' },
+ { value: "'Palatino Linotype', serif", label: 'Palatino' },
+ { value: 'Garamond, serif', label: 'Garamond' },
+ { value: "'Comic Sans MS', cursive", label: 'Comic Sans MS' },
+ { value: "'Lucida Console', monospace", label: 'Lucida Console' },
+] as const;
+
+// Font size options
+export const FONT_SIZES = [
+ { value: 'xs', label: 'Extra Small' },
+ { value: 'sm', label: 'Small' },
+ { value: 'base', label: 'Base' },
+ { value: 'lg', label: 'Large' },
+ { value: 'xl', label: 'Extra Large' },
+ { value: '2xl', label: '2X Large' },
+ { value: '3xl', label: '3X Large' },
+] as const;
+
+// Chart type options
+export const CHART_TYPES = [
+ { value: 'bar', label: 'Bar Chart' },
+ { value: 'line', label: 'Line Chart' },
+ { value: 'pie', label: 'Pie Chart' },
+ { value: 'area', label: 'Area Chart' },
+] as const;
+
+// Preset colors for color picker
+export const PRESET_COLORS = [
+ '#ffffff', '#f8f9fa', '#e9ecef', '#dee2e6', '#ced4da', '#adb5bd', '#6c757d', '#495057',
+ '#fff3cd', '#d1ecf1', '#d4edda', '#f8d7da', '#e2e3e5', '#d6d8db', '#fef5e7', '#ebf5fb',
+ '#ff0000', '#ff7f00', '#ffff00', '#00ff00', '#00ffff', '#0000ff', '#8b00ff', '#ff00ff',
+ '#fff5f5', '#ffe6e6', '#ffd6cc', '#ffe5cc', '#fff4cc', '#ffffcc', '#f0fff4', '#f0f9ff',
+] as const;
+
+// AI Quick action prompts
+export const AI_QUICK_ACTIONS: Record<string, string> = {
+ improve: 'Can you help me improve the content of this report? Suggest better wording and structure.',
+ expand: 'Can you help me expand on the current content with more details and insights?',
+ summarize: 'Can you help me create a concise executive summary for this report?',
+ grammar: 'Can you check the grammar and suggest improvements for professional writing?',
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/hooks.ts b/fincept-terminal-desktop/src/components/tabs/report-builder/hooks.ts
new file mode 100644
index 000000000..622f7fcc3
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/hooks.ts
@@ -0,0 +1,536 @@
+import { useState, useCallback, useEffect } from 'react';
+import { ReportTemplate, ReportComponent, reportService } from '@/services/core/reportService';
+import { sqliteService } from '@/services/core/sqliteService';
+import { llmApiService, ChatMessage as APIMessage } from '@/services/chat/llmApi';
+import { brandKitService, BrandKit } from '@/services/core/brandKitService';
+import { save, open } from '@tauri-apps/plugin-dialog';
+import { invoke } from '@tauri-apps/api/core';
+import { toast } from 'sonner';
+import { arrayMove } from '@dnd-kit/sortable';
+import { DragEndEvent } from '@dnd-kit/core';
+import { AIMessage, AIModel, AdvancedStyles, TOCItem } from './types';
+import { AI_QUICK_ACTIONS } from './constants';
+
+// Hook for managing the report template
+export const useReportTemplate = () => {
+ const [template, setTemplate] = useState<ReportTemplate>({
+ id: `report-${Date.now()}`,
+ name: 'New Financial Report',
+ description: 'Professional financial research report',
+ components: [],
+ metadata: {
+ author: '',
+ company: '',
+ date: new Date().toISOString().split('T')[0],
+ title: 'Financial Research Report',
+ },
+ styles: {
+ pageSize: 'A4',
+ orientation: 'portrait',
+ margins: '20mm',
+ headerFooter: true,
+ },
+ });
+
+ const [selectedComponent, setSelectedComponent] = useState<string | null>(null);
+
+ // Get selected component data
+ const selectedComp = template.components.find(c => c.id === selectedComponent);
+
+ // Add component
+ const addComponent = useCallback((type: ReportComponent['type']) => {
+ const newComponent: ReportComponent = {
+ id: `component-${Date.now()}`,
+ type,
+ content: (type === 'divider' || type === 'pagebreak' || type === 'coverpage' || type === 'section' || type === 'columns') ? '' :
+ type === 'heading' ? 'New Heading' :
+ type === 'subheading' ? 'New Subheading' :
+ type === 'text' ? 'Enter text here...' :
+ type === 'quote' ? 'Enter quote text here...' :
+ type === 'disclaimer' ? 'This report is for informational purposes only.' : '',
+ config: {
+ fontSize: type === 'heading' ? '2xl' : type === 'subheading' ? 'xl' : 'base',
+ fontWeight: type === 'heading' || type === 'subheading' ? 'bold' : 'normal',
+ alignment: 'left',
+ ...(type === 'columns' && { columnCount: 2 }),
+ ...(type === 'section' && {
+ sectionTitle: 'New Section',
+ sectionStyle: 'default',
+ backgroundColor: '#f8f9fa',
+ borderColor: '#FFA500',
+ padding: '15px'
+ }),
+ ...(type === 'coverpage' && {
+ subtitle: '',
+ backgroundColor: '#0a0a0a',
+ }),
+ ...(type === 'quote' && {
+ quoteType: 'quote',
+ author: '',
+ }),
+ ...(type === 'list' && {
+ items: ['Item 1', 'Item 2', 'Item 3'],
+ ordered: false,
+ }),
+ ...(type === 'toc' && {
+ showPageNumbers: true,
+ }),
+ ...(type === 'kpi' && {
+ kpis: [
+ { label: 'Revenue', value: '$1.2M', change: 12.5, trend: 'up' },
+ { label: 'Profit', value: '$340K', change: 8.2, trend: 'up' },
+ { label: 'Margin', value: '28.3%', change: -2.1, trend: 'down' },
+ ],
+ }),
+ ...(type === 'sparkline' && {
+ data: [10, 25, 15, 30, 20, 35, 28],
+ color: '#FFA500',
+ }),
+ ...(type === 'liveTable' && {
+ dataSource: 'portfolio',
+ columns: ['Symbol', 'Price', 'Change', 'Volume'],
+ }),
+ ...(type === 'dynamicChart' && {
+ chartType: 'line',
+ data: [
+ { name: 'Jan', value: 100 },
+ { name: 'Feb', value: 120 },
+ { name: 'Mar', value: 115 },
+ { name: 'Apr', value: 140 },
+ ],
+ }),
+ ...(type === 'signature' && {
+ name: 'John Doe',
+ title: 'Analyst',
+ showLine: true,
+ }),
+ ...(type === 'disclaimer' && {
+ disclaimerType: 'standard',
+ }),
+ ...(type === 'qrcode' && {
+ value: 'https://example.com',
+ size: 100,
+ label: 'Scan for more info',
+ }),
+ ...(type === 'watermark' && {
+ text: 'CONFIDENTIAL',
+ opacity: 0.1,
+ rotation: -45,
+ }),
+ },
+ ...(type === 'columns' || type === 'section' ? { children: [] } : {}),
+ };
+
+ setTemplate(prev => ({
+ ...prev,
+ components: [...prev.components, newComponent],
+ }));
+ setSelectedComponent(newComponent.id);
+ toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} added`);
+
+ return newComponent;
+ }, []);
+
+ // Update component
+ const updateComponent = useCallback((id: string, updates: Partial<ReportComponent>) => {
+ setTemplate(prev => ({
+ ...prev,
+ components: prev.components.map(comp =>
+ comp.id === id ? { ...comp, ...updates } : comp
+ ),
+ }));
+ }, []);
+
+ // Delete component
+ const deleteComponent = useCallback((id: string) => {
+ setTemplate(prev => ({
+ ...prev,
+ components: prev.components.filter(comp => comp.id !== id),
+ }));
+ if (selectedComponent === id) {
+ setSelectedComponent(null);
+ }
+ toast.success('Component deleted');
+ }, [selectedComponent]);
+
+ // Duplicate component
+ const duplicateComponent = useCallback((id: string) => {
+ const component = template.components.find(c => c.id === id);
+ if (component) {
+ const newComponent = {
+ ...component,
+ id: `component-${Date.now()}`,
+ };
+ setTemplate(prev => ({
+ ...prev,
+ components: [...prev.components, newComponent],
+ }));
+ toast.success('Component duplicated');
+ }
+ }, [template.components]);
+
+ // Handle drag end
+ const handleDragEnd = useCallback((event: DragEndEvent) => {
+ const { active, over } = event;
+ if (over && active.id !== over.id) {
+ setTemplate(prev => {
+ const oldIndex = prev.components.findIndex(c => c.id === active.id);
+ const newIndex = prev.components.findIndex(c => c.id === over.id);
+ return {
+ ...prev,
+ components: arrayMove(prev.components, oldIndex, newIndex),
+ };
+ });
+ }
+ }, []);
+
+ // Update metadata
+ const updateMetadata = useCallback((updates: Partial<ReportTemplate['metadata']>) => {
+ setTemplate(prev => ({
+ ...prev,
+ metadata: { ...prev.metadata, ...updates },
+ }));
+ }, []);
+
+ // Generate TOC items from headings
+ const tocItems: TOCItem[] = template.components
+ .filter(c => c.type === 'heading' || c.type === 'subheading')
+ .map((c, idx) => ({
+ id: c.id,
+ title: String(c.content || `Section ${idx + 1}`),
+ level: c.type === 'heading' ? 1 : 2,
+ page: Math.floor(idx / 3) + 1,
+ }));
+
+ return {
+ template,
+ setTemplate,
+ selectedComponent,
+ setSelectedComponent,
+ selectedComp,
+ addComponent,
+ updateComponent,
+ deleteComponent,
+ duplicateComponent,
+ handleDragEnd,
+ updateMetadata,
+ tocItems,
+ };
+};
+
+// Hook for file operations (save/load/export)
+export const useFileOperations = (
+ template: ReportTemplate,
+ setTemplate: (t: ReportTemplate) => void
+) => {
+ const [isSaving, setIsSaving] = useState(false);
+ const [isGenerating, setIsGenerating] = useState(false);
+ const [showSuccessDialog, setShowSuccessDialog] = useState(false);
+ const [generatedPdfPath, setGeneratedPdfPath] = useState('');
+
+ // Save template
+ const saveTemplate = async () => {
+ try {
+ setIsSaving(true);
+ const filePath = await save({
+ filters: [{
+ name: 'JSON',
+ extensions: ['json']
+ }],
+ defaultPath: `${template.name}.json`
+ });
+
+ if (filePath) {
+ await reportService.saveTemplate(template);
+ toast.success('Template saved successfully');
+ }
+ } catch (error) {
+ console.error('Error saving template:', error);
+ toast.error('Failed to save template');
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ // Load template
+ const loadTemplate = async () => {
+ try {
+ await open({
+ filters: [{
+ name: 'JSON',
+ extensions: ['json']
+ }],
+ multiple: false
+ });
+
+ const templates = await reportService.getTemplates();
+ if (templates.length > 0) {
+ setTemplate(templates[0]);
+ toast.success('Template loaded successfully');
+ } else {
+ toast.info('No saved templates found. Use a sample template instead.');
+ }
+ } catch (error) {
+ console.error('Error loading template:', error);
+ toast.error('Failed to load template');
+ }
+ };
+
+ // Generate PDF
+ const generatePdf = async () => {
+ try {
+ setIsGenerating(true);
+
+ const filePath = await save({
+ filters: [{
+ name: 'PDF',
+ extensions: ['pdf']
+ }],
+ defaultPath: `${template.metadata.title || 'report'}.pdf`
+ });
+
+ if (filePath) {
+ await invoke('generate_report_pdf', {
+ templateJson: JSON.stringify(template),
+ outputPath: filePath
+ });
+
+ setGeneratedPdfPath(filePath);
+ setShowSuccessDialog(true);
+ }
+ } catch (error) {
+ console.error('Error generating PDF:', error);
+ toast.error('Failed to generate PDF');
+ } finally {
+ setIsGenerating(false);
+ }
+ };
+
+ // Show in folder
+ const handleShowInFolder = async () => {
+ try {
+ const folderPath = generatedPdfPath.substring(0, generatedPdfPath.lastIndexOf('\\'));
+ await invoke('open_folder', { path: folderPath });
+ setShowSuccessDialog(false);
+ } catch (error) {
+ console.error('Error opening folder:', error);
+ toast.error('Failed to open folder');
+ }
+ };
+
+ return {
+ isSaving,
+ isGenerating,
+ showSuccessDialog,
+ setShowSuccessDialog,
+ generatedPdfPath,
+ saveTemplate,
+ loadTemplate,
+ generatePdf,
+ handleShowInFolder,
+ };
+};
+
+// Hook for AI chat functionality
+export const useAIChat = (template: ReportTemplate, fontFamily: string, defaultFontSize: number, pageTheme: string) => {
+ const [messages, setMessages] = useState<AIMessage[]>([]);
+ const [input, setInput] = useState('');
+ const [isTyping, setIsTyping] = useState(false);
+ const [streamingContent, setStreamingContent] = useState('');
+ const [currentProvider, setCurrentProvider] = useState('ollama');
+ const [availableModels, setAvailableModels] = useState<AIModel[]>([]);
+
+ // Load available AI models
+ useEffect(() => {
+ const loadModels = async () => {
+ try {
+ const configs = await sqliteService.getLLMConfigs();
+ const models = configs.map((config: any) => ({
+ id: config.config_name,
+ name: config.model_name || config.config_name,
+ provider: config.provider
+ }));
+ setAvailableModels(models);
+
+ const activeConfig = await sqliteService.getActiveLLMConfig();
+ if (activeConfig) {
+ setCurrentProvider(activeConfig.provider);
+ }
+ } catch (error) {
+ console.error('Failed to load models:', error);
+ }
+ };
+ loadModels();
+ }, []);
+
+ // Send message
+ const sendMessage = async () => {
+ if (!input.trim()) return;
+
+ const userMessage = { role: 'user', content: input.trim() };
+ setMessages(prev => [...prev, userMessage]);
+ setInput('');
+ setIsTyping(true);
+ setStreamingContent('');
+
+ try {
+ const activeConfig = await sqliteService.getActiveLLMConfig();
+ if (!activeConfig) {
+ setMessages(prev => [...prev, {
+ role: 'assistant',
+ content: 'Please configure your LLM settings first in the Chat tab or Settings.'
+ }]);
+ setIsTyping(false);
+ return;
+ }
+
+ const contextMessage = `I'm working on a report titled "${template.metadata.title}". ${
+ template.components.length > 0
+ ? `It has ${template.components.length} components including ${template.components.map(c => c.type).join(', ')}.`
+ : 'It\'s empty so far.'
+ } The report uses ${fontFamily} font at ${defaultFontSize}pt with ${pageTheme} theme.`;
+
+ const conversationHistory: APIMessage[] = [
+ { role: 'system', content: `You are a professional writing assistant helping to create financial reports. ${contextMessage}` },
+ ...messages.map(msg => ({
+ role: msg.role as 'user' | 'assistant',
+ content: msg.content
+ })),
+ { role: 'user', content: userMessage.content }
+ ];
+
+ let fullResponse = '';
+
+ const response = await llmApiService.chat(
+ userMessage.content,
+ conversationHistory,
+ (chunk, done) => {
+ if (!done) {
+ fullResponse += chunk;
+ setStreamingContent(fullResponse);
+ }
+ }
+ );
+
+ if (response.error) {
+ throw new Error(response.error);
+ }
+
+ fullResponse = response.content;
+
+ setMessages(prev => [...prev, {
+ role: 'assistant',
+ content: fullResponse
+ }]);
+ setStreamingContent('');
+ } catch (error) {
+ console.error('AI Error:', error);
+ setMessages(prev => [...prev, {
+ role: 'assistant',
+ content: 'Sorry, I encountered an error. Please try again.'
+ }]);
+ } finally {
+ setIsTyping(false);
+ }
+ };
+
+ // Quick action
+ const handleQuickAction = (action: string) => {
+ setInput(AI_QUICK_ACTIONS[action] || '');
+ };
+
+ return {
+ messages,
+ input,
+ setInput,
+ isTyping,
+ streamingContent,
+ currentProvider,
+ setCurrentProvider,
+ availableModels,
+ sendMessage,
+ handleQuickAction,
+ };
+};
+
+// Hook for brand kit and advanced styles
+export const useBrandKit = () => {
+ const [activeBrandKit, setActiveBrandKit] = useState<BrandKit | null>(null);
+ const [advancedStyles, setAdvancedStyles] = useState<AdvancedStyles>({
+ customCSS: '',
+ headerTemplate: null,
+ footerTemplate: null,
+ paragraphStyles: null,
+ });
+
+ // Load active brand kit on mount
+ useEffect(() => {
+ const loadBrandKit = async () => {
+ try {
+ const kit = await brandKitService.getActiveBrandKit();
+ if (kit) {
+ setActiveBrandKit(kit);
+ setAdvancedStyles({
+ customCSS: kit.customCSS || '',
+ headerTemplate: kit.headerTemplate || null,
+ footerTemplate: kit.footerTemplate || null,
+ paragraphStyles: kit.paragraphStyles || null,
+ });
+ }
+ } catch (error) {
+ console.error('Failed to load brand kit:', error);
+ }
+ };
+ loadBrandKit();
+ }, []);
+
+ // Handle brand kit change
+ const handleBrandKitChange = useCallback((brandKit: BrandKit) => {
+ setActiveBrandKit(brandKit);
+ setAdvancedStyles({
+ customCSS: brandKit.customCSS || '',
+ headerTemplate: brandKit.headerTemplate || null,
+ footerTemplate: brandKit.footerTemplate || null,
+ paragraphStyles: brandKit.paragraphStyles || null,
+ });
+ toast.success(`Applied brand kit: ${brandKit.name}`);
+
+ return brandKit.fonts.find(f => f.usage === 'body')?.family;
+ }, []);
+
+ return {
+ activeBrandKit,
+ advancedStyles,
+ setAdvancedStyles,
+ handleBrandKitChange,
+ };
+};
+
+// Hook for image upload
+export const useImageUpload = (
+ selectedComp: ReportComponent | undefined,
+ updateComponent: (id: string, updates: Partial<ReportComponent>) => void
+) => {
+ const handleImageUpload = async () => {
+ try {
+ const selected = await open({
+ multiple: false,
+ filters: [{
+ name: 'Images',
+ extensions: ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp']
+ }]
+ });
+
+ if (selected && typeof selected === 'string' && selectedComp) {
+ updateComponent(selectedComp.id, {
+ config: { ...selectedComp.config, imageUrl: selected }
+ });
+ toast.success('Image uploaded');
+ }
+ } catch (error) {
+ toast.error('Failed to upload image');
+ }
+ };
+
+ return { handleImageUpload };
+};
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/index.ts b/fincept-terminal-desktop/src/components/tabs/report-builder/index.ts
new file mode 100644
index 000000000..5199586a4
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/index.ts
@@ -0,0 +1,35 @@
+// Main component
+export { default as ReportBuilderTab } from './ReportBuilderTab';
+export { default } from './ReportBuilderTab';
+
+// Sub-components
+export { ReportHeader } from './ReportHeader';
+export { ComponentToolbar } from './ComponentToolbar';
+export { DocumentCanvas, getThemeBackground } from './DocumentCanvas';
+export { PropertiesPanel } from './PropertiesPanel';
+export { AIChatPanel } from './AIChatPanel';
+export { SortableComponent } from './SortableComponent';
+
+// Existing components (already in folder)
+export { AdvancedStylingPanel } from './AdvancedStylingPanel';
+export { ExportDialog } from './ExportDialog';
+export { TemplateGallery } from './TemplateGallery';
+export * from './DataComponents';
+export * from './AdditionalComponents';
+export * from './CollaborationFeatures';
+export * from './ProductivityFeatures';
+
+// Hooks
+export {
+ useReportTemplate,
+ useFileOperations,
+ useAIChat,
+ useBrandKit,
+ useImageUpload,
+} from './hooks';
+
+// Types
+export * from './types';
+
+// Constants
+export * from './constants';
diff --git a/fincept-terminal-desktop/src/components/tabs/report-builder/types.ts b/fincept-terminal-desktop/src/components/tabs/report-builder/types.ts
new file mode 100644
index 000000000..b8efc2b65
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/report-builder/types.ts
@@ -0,0 +1,159 @@
+import { ReportTemplate, ReportComponent } from '@/services/core/reportService';
+import { BrandKit, HeaderFooterTemplate, ParagraphStyles } from '@/services/core/brandKitService';
+
+// Page theme type
+export type PageTheme = 'classic' | 'modern' | 'geometric' | 'gradient' | 'minimal' | 'pattern';
+
+// Right panel view options
+export type RightPanelView = 'split' | 'properties' | 'chat' | 'styling' | 'comments' | 'history';
+
+// AI Message interface
+export interface AIMessage {
+ role: string;
+ content: string;
+}
+
+// AI Model info interface
+export interface AIModel {
+ id: string;
+ name: string;
+ provider: string;
+}
+
+// Advanced styles interface
+export interface AdvancedStyles {
+ customCSS: string;
+ headerTemplate: HeaderFooterTemplate | null;
+ footerTemplate: HeaderFooterTemplate | null;
+ paragraphStyles: ParagraphStyles | null;
+}
+
+// Table of Contents item interface
+export interface TOCItem {
+ id: string;
+ title: string;
+ level: number;
+ page: number;
+}
+
+// Report builder state interface
+export interface ReportBuilderState {
+ template: ReportTemplate;
+ selectedComponent: string | null;
+ isGenerating: boolean;
+ isSaving: boolean;
+ showSuccessDialog: boolean;
+ generatedPdfPath: string;
+ showExportDialog: boolean;
+ pageTheme: PageTheme;
+ fontFamily: string;
+ defaultFontSize: number;
+ isBold: boolean;
+ isItalic: boolean;
+ customBgColor: string;
+ showColorPicker: boolean;
+ rightPanelView: RightPanelView;
+ showTemplateGallery: boolean;
+ showFindReplace: boolean;
+ showShortcuts: boolean;
+ revisionModeEnabled: boolean;
+ activeBrandKit: BrandKit | null;
+ advancedStyles: AdvancedStyles;
+}
+
+// Component props interfaces
+export interface SortableComponentProps {
+ component: ReportComponent;
+ isSelected: boolean;
+ onClick: () => void;
+ onDelete: () => void;
+ onDuplicate: () => void;
+}
+
+export interface ComponentToolbarProps {
+ onAddComponent: (type: ReportComponent['type']) => void;
+ template: ReportTemplate;
+ selectedComponent: string | null;
+ onSelectComponent: (id: string | null) => void;
+ onDeleteComponent: (id: string) => void;
+ onDuplicateComponent: (id: string) => void;
+ onDragEnd: (event: any) => void;
+ pageTheme: PageTheme;
+ onPageThemeChange: (theme: PageTheme) => void;
+ customBgColor: string;
+ onCustomBgColorChange: (color: string) => void;
+ showColorPicker: boolean;
+ onShowColorPickerChange: (show: boolean) => void;
+ fontFamily: string;
+ onFontFamilyChange: (font: string) => void;
+ defaultFontSize: number;
+ onDefaultFontSizeChange: (size: number) => void;
+ isBold: boolean;
+ onIsBoldChange: (bold: boolean) => void;
+ isItalic: boolean;
+ onIsItalicChange: (italic: boolean) => void;
+}
+
+export interface DocumentCanvasProps {
+ template: ReportTemplate;
+ selectedComponent: string | null;
+ onSelectComponent: (id: string | null) => void;
+ pageTheme: PageTheme;
+ customBgColor: string;
+ fontFamily: string;
+ defaultFontSize: number;
+ isBold: boolean;
+ isItalic: boolean;
+ advancedStyles: AdvancedStyles;
+ tocItems: TOCItem[];
+}
+
+export interface PropertiesPanelProps {
+ selectedComponent: ReportComponent | undefined;
+ onUpdateComponent: (id: string, updates: Partial<ReportComponent>) => void;
+ onDeleteComponent: (id: string) => void;
+ onDuplicateComponent: (id: string) => void;
+ onClearSelection: () => void;
+ onSaveAsTemplate: () => void;
+ onImageUpload: () => void;
+}
+
+export interface AIChatPanelProps {
+ messages: AIMessage[];
+ input: string;
+ onInputChange: (value: string) => void;
+ onSendMessage: () => void;
+ onQuickAction: (action: string) => void;
+ isTyping: boolean;
+ streamingContent: string;
+ currentProvider: string;
+ onProviderChange: (provider: string) => void;
+ availableModels: AIModel[];
+}
+
+export interface ReportHeaderProps {
+ canUndo: boolean;
+ canRedo: boolean;
+ onUndo: () => void;
+ onRedo: () => void;
+ onFindReplace: () => void;
+ onShortcuts: () => void;
+ onTemplateGallery: () => void;
+ onLoad: () => void;
+ onSave: () => void;
+ onExport: () => void;
+ isSaving: boolean;
+ isAutoSaving: boolean;
+ lastSaved: Date | null;
+ hasComponents: boolean;
+}
+
+// Theme background style result
+export interface ThemeBackgroundStyle {
+ backgroundColor?: string;
+ background?: string;
+ backgroundSize?: string;
+ backgroundPosition?: string;
+ backgroundImage?: string;
+ color: string;
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/screener/ScreenerTab.tsx b/fincept-terminal-desktop/src/components/tabs/screener/ScreenerTab.tsx
new file mode 100644
index 000000000..2dd59acb1
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/screener/ScreenerTab.tsx
@@ -0,0 +1,555 @@
+import React, { useState, useEffect, useMemo, useCallback, memo } from 'react';
+import { useTerminalTheme } from '@/contexts/ThemeContext';
+import { useTranslation } from 'react-i18next';
+import { Search, Download, BarChart3, Loader2, AlertCircle, FolderTree } from 'lucide-react';
+import { TabFooter } from '@/components/common/TabFooter';
+
+import { useScreenerData } from './hooks';
+import { SeriesBrowserModal, SeriesChart, SeriesDataTable } from './components';
+import { POPULAR_SERIES } from './constants';
+
+// Memoized quick-add button component
+const QuickAddButton = memo(({
+ seriesId,
+ isSelected,
+ onClick,
+ colors,
+ fontSize
+}: {
+ seriesId: string;
+ isSelected: boolean;
+ onClick: () => void;
+ colors: any;
+ fontSize: any;
+}) => (
+ <button
+ onClick={onClick}
+ style={{
+ background: isSelected ? `${colors.success}22` : colors.background,
+ border: `1px solid ${isSelected ? colors.success : colors.textMuted}44`,
+ color: isSelected ? colors.success : colors.textMuted,
+ padding: '4px 10px',
+ fontSize: fontSize.tiny,
+ cursor: 'pointer',
+ borderRadius: '3px',
+ fontWeight: isSelected ? 'bold' : 'normal',
+ transition: 'all 0.15s'
+ }}
+ >
+ {seriesId}
+ </button>
+));
+
+QuickAddButton.displayName = 'QuickAddButton';
+
+function ScreenerTab() {
+ const { colors, fontSize, fontFamily, fontWeight, fontStyle } = useTerminalTheme();
+ const { t } = useTranslation('screener');
+
+ // Form state
+ const [seriesIds, setSeriesIds] = useState('GDP');
+ const [startDate, setStartDate] = useState('2000-01-01');
+ const [endDate, setEndDate] = useState(() => new Date().toISOString().split('T')[0]);
+ const [chartType, setChartType] = useState<'line' | 'area'>('line');
+ const [normalizeData, setNormalizeData] = useState(false);
+ const [showBrowser, setShowBrowser] = useState(false);
+
+ // Data hook
+ const {
+ data,
+ searchResults,
+ categories,
+ categorySeriesResults,
+ loading,
+ loadingMessage,
+ searchLoading,
+ categoryLoading,
+ categorySeriesLoading,
+ error,
+ apiKeyConfigured,
+ fetchData,
+ searchSeries,
+ loadCategories,
+ loadCategorySeries,
+ checkApiKey,
+ } = useScreenerData();
+
+ // Check API key on mount
+ useEffect(() => {
+ checkApiKey();
+ }, [checkApiKey]);
+
+ // Delayed auto-fetch after API key check
+ useEffect(() => {
+ if (apiKeyConfigured && data.length === 0 && !loading) {
+ const timer = setTimeout(() => {
+ fetchData(seriesIds, startDate, endDate);
+ }, 500);
+ return () => clearTimeout(timer);
+ }
+ }, [apiKeyConfigured]); // Only run when apiKeyConfigured changes
+
+ // Memoize current series IDs set
+ const currentSeriesIdsSet = useMemo(() => {
+ return new Set(seriesIds.split(',').map(s => s.trim()).filter(Boolean));
+ }, [seriesIds]);
+
+ // Handlers
+ const handleFetchData = useCallback(() => {
+ fetchData(seriesIds, startDate, endDate);
+ }, [fetchData, seriesIds, startDate, endDate]);
+
+ const handleSeriesIdsChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
+ setSeriesIds(e.target.value);
+ }, []);
+
+ const handleStartDateChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
+ setStartDate(e.target.value);
+ }, []);
+
+ const handleEndDateChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
+ setEndDate(e.target.value);
+ }, []);
+
+ const toggleChartType = useCallback(() => {
+ setChartType(prev => prev === 'line' ? 'area' : 'line');
+ }, []);
+
+ const toggleNormalize = useCallback(() => {
+ setNormalizeData(prev => !prev);
+ }, []);
+
+ const handleAddPopularSeries = useCallback((id: string) => {
+ setSeriesIds(prev => {
+ const currentIds = prev.split(',').map(s => s.trim()).filter(Boolean);
+ if (currentIds.includes(id)) {
+ return currentIds.filter(sid => sid !== id).join(',');
+ }
+ return prev ? `${prev},${id}` : id;
+ });
+ }, []);
+
+ const handleAddSeriesFromBrowser = useCallback((id: string) => {
+ if (!currentSeriesIdsSet.has(id)) {
+ const newIds = seriesIds ? `${seriesIds},${id}` : id;
+ setSeriesIds(newIds);
+ // Auto-fetch after adding
+ setTimeout(() => {
+ fetchData(newIds, startDate, endDate);
+ }, 100);
+ }
+ }, [currentSeriesIdsSet, seriesIds, startDate, endDate, fetchData]);
+
+ const handleOpenBrowser = useCallback(() => {
+ setShowBrowser(true);
+ if (categories.length === 0) {
+ loadCategories(0);
+ }
+ }, [categories.length, loadCategories]);
+
+ const handleCloseBrowser = useCallback(() => {
+ setShowBrowser(false);
+ }, []);
+
+ // Export to CSV
+ const exportToCSV = useCallback(() => {
+ if (data.length === 0) return;
+
+ const allDates = new Set<string>();
+ data.forEach(series => {
+ series.observations.forEach(obs => allDates.add(obs.date));
+ });
+ const sortedDates = Array.from(allDates).sort();
+
+ const headers = ['Date', ...data.map(s => s.series_id)].join(',');
+ const rows = sortedDates.map(date => {
+ const values = data.map(series => {
+ const obs = series.observations.find(o => o.date === date);
+ return obs?.value || '';
+ });
+ return [date, ...values].join(',');
+ });
+
+ const csv = [headers, ...rows].join('\n');
+ const blob = new Blob([csv], { type: 'text/csv' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `fred_data_${new Date().toISOString().split('T')[0]}.csv`;
+ a.click();
+ URL.revokeObjectURL(url);
+ }, [data]);
+
+ // Memoize container style
+ const containerStyle = useMemo(() => ({
+ width: '100%',
+ height: '100%',
+ display: 'flex',
+ flexDirection: 'column' as const,
+ backgroundColor: colors.background,
+ color: colors.text,
+ fontFamily,
+ fontWeight,
+ fontStyle,
+ overflow: 'hidden',
+ fontSize: fontSize.body
+ }), [colors.background, colors.text, fontFamily, fontWeight, fontStyle, fontSize.body]);
+
+ // Memoize scrollbar style
+ const scrollbarStyle = useMemo(() => `
+ *::-webkit-scrollbar { width: 6px; height: 6px; }
+ *::-webkit-scrollbar-track { background: ${colors.background}; }
+ *::-webkit-scrollbar-thumb { background: ${colors.panel}; border-radius: 3px; }
+ *::-webkit-scrollbar-thumb:hover { background: ${colors.textMuted}; }
+ `, [colors.background, colors.panel, colors.textMuted]);
+
+ // Total observations count
+ const totalObservations = useMemo(() => {
+ return data.reduce((acc, s) => acc + s.observation_count, 0);
+ }, [data]);
+
+ return (
+ <div style={containerStyle}>
+ <style>{scrollbarStyle}</style>
+
+ {/* Series Browser Modal */}
+ <SeriesBrowserModal
+ isOpen={showBrowser}
+ onClose={handleCloseBrowser}
+ onAddSeries={handleAddSeriesFromBrowser}
+ currentSeriesIds={currentSeriesIdsSet}
+ searchResults={searchResults}
+ searchLoading={searchLoading}
+ categories={categories}
+ categoryLoading={categoryLoading}
+ categorySeriesResults={categorySeriesResults}
+ categorySeriesLoading={categorySeriesLoading}
+ onSearch={searchSeries}
+ onLoadCategories={loadCategories}
+ onLoadCategorySeries={loadCategorySeries}
+ colors={colors}
+ fontSize={fontSize}
+ />
+
+ {/* Header */}
+ <div style={{
+ borderBottom: `1px solid ${colors.primary}`,
+ padding: '10px 16px',
+ background: colors.panel,
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
+ <BarChart3 size={16} color={colors.primary} />
+ <span style={{ color: colors.primary, fontSize: fontSize.heading, fontWeight: 'bold', letterSpacing: '0.5px' }}>
+ {t('header.title', 'ECONOMIC DATA SCREENER')}
+ </span>
+ </div>
+ <div style={{ display: 'flex', gap: '6px' }}>
+ <button
+ onClick={toggleChartType}
+ style={{
+ background: colors.background,
+ border: `1px solid ${colors.primary}33`,
+ color: colors.primary,
+ padding: '6px 12px',
+ fontSize: fontSize.small,
+ cursor: 'pointer',
+ borderRadius: '3px',
+ fontWeight: 'bold',
+ transition: 'all 0.15s'
+ }}
+ >
+ {chartType === 'line' ? 'AREA' : 'LINE'}
+ </button>
+ <button
+ onClick={toggleNormalize}
+ disabled={data.length <= 1}
+ style={{
+ background: normalizeData ? colors.primary : colors.background,
+ border: `1px solid ${colors.primary}33`,
+ color: normalizeData ? colors.background : colors.primary,
+ padding: '6px 12px',
+ fontSize: fontSize.small,
+ cursor: data.length > 1 ? 'pointer' : 'not-allowed',
+ borderRadius: '3px',
+ fontWeight: 'bold',
+ opacity: data.length > 1 ? 1 : 0.5,
+ transition: 'all 0.15s'
+ }}
+ >
+ NORMALIZE
+ </button>
+ <button
+ onClick={exportToCSV}
+ disabled={data.length === 0}
+ style={{
+ background: data.length > 0 ? colors.background : colors.panel,
+ border: `1px solid ${data.length > 0 ? colors.success : colors.textMuted}33`,
+ color: data.length > 0 ? colors.success : colors.textMuted,
+ padding: '6px 12px',
+ fontSize: fontSize.small,
+ cursor: data.length > 0 ? 'pointer' : 'not-allowed',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ fontWeight: 'bold',
+ opacity: data.length > 0 ? 1 : 0.5,
+ transition: 'opacity 0.15s'
+ }}
+ >
+ <Download size={12} />
+ CSV
+ </button>
+ </div>
+ </div>
+
+ {/* API Key Warning */}
+ {!apiKeyConfigured && (
+ <div style={{
+ background: `${colors.warning}11`,
+ border: `1px solid ${colors.warning}`,
+ padding: '12px 16px',
+ display: 'flex',
+ alignItems: 'flex-start',
+ gap: '12px',
+ flexShrink: 0
+ }}>
+ <AlertCircle size={20} color={colors.warning} style={{ flexShrink: 0, marginTop: '2px' }} />
+ <div style={{ flex: 1 }}>
+ <p style={{ color: colors.warning, fontSize: fontSize.body, fontWeight: 'bold', marginBottom: '6px' }}>
+ {t('apiKey.required', 'FRED API Key Required')}
+ </p>
+ <p style={{ color: colors.text, fontSize: fontSize.small, lineHeight: '1.5', marginBottom: '8px' }}>
+ Configure your FRED API key in <strong>Settings → Credentials</strong> to access economic data.
+ </p>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
+ <p style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>
+ <strong style={{ color: colors.warning }}>1.</strong> Get free API key at{' '}
+ <a
+ href="https://research.stlouisfed.org/useraccount/apikey"
+ target="_blank"
+ rel="noopener noreferrer"
+ style={{ color: colors.info, textDecoration: 'underline' }}
+ >
+ research.stlouisfed.org
+ </a>
+ </p>
+ <p style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>
+ <strong style={{ color: colors.warning }}>2.</strong> Add to <strong>Settings → Credentials → FRED_API_KEY</strong>
+ </p>
+ <p style={{ color: colors.textMuted, fontSize: fontSize.tiny }}>
+ <strong style={{ color: colors.warning }}>3.</strong> Save and reload this tab
+ </p>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Query Panel */}
+ <div style={{
+ borderBottom: `1px solid ${colors.panel}`,
+ padding: '12px 16px',
+ background: colors.panel,
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr auto', gap: '10px', marginBottom: '10px' }}>
+ <div>
+ <label style={{ color: colors.textMuted, fontSize: fontSize.tiny, display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
+ {t('form.seriesIds', 'SERIES IDS (comma-separated)')}
+ </label>
+ <input
+ type="text"
+ value={seriesIds}
+ onChange={handleSeriesIdsChange}
+ placeholder="GDP,UNRATE,CPIAUCSL"
+ style={{
+ width: '100%',
+ background: colors.background,
+ border: `1px solid ${colors.textMuted}33`,
+ color: colors.text,
+ padding: '8px 10px',
+ fontSize: fontSize.small,
+ borderRadius: '3px',
+ outline: 'none'
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ color: colors.textMuted, fontSize: fontSize.tiny, display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
+ START DATE
+ </label>
+ <input
+ type="date"
+ value={startDate}
+ onChange={handleStartDateChange}
+ style={{
+ width: '100%',
+ background: colors.background,
+ border: `1px solid ${colors.textMuted}33`,
+ color: colors.text,
+ padding: '8px 10px',
+ fontSize: fontSize.small,
+ borderRadius: '3px',
+ outline: 'none'
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ color: colors.textMuted, fontSize: fontSize.tiny, display: 'block', marginBottom: '4px', fontWeight: 'bold' }}>
+ END DATE
+ </label>
+ <input
+ type="date"
+ value={endDate}
+ onChange={handleEndDateChange}
+ style={{
+ width: '100%',
+ background: colors.background,
+ border: `1px solid ${colors.textMuted}33`,
+ color: colors.text,
+ padding: '8px 10px',
+ fontSize: fontSize.small,
+ borderRadius: '3px',
+ outline: 'none'
+ }}
+ />
+ </div>
+ <button
+ onClick={handleFetchData}
+ disabled={loading}
+ style={{
+ background: loading ? colors.panel : colors.primary,
+ border: 'none',
+ color: colors.background,
+ padding: '0 18px',
+ fontSize: fontSize.small,
+ cursor: loading ? 'not-allowed' : 'pointer',
+ borderRadius: '3px',
+ fontWeight: 'bold',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ alignSelf: 'end',
+ opacity: loading ? 0.6 : 1,
+ transition: 'all 0.15s'
+ }}
+ >
+ {loading ? <Loader2 size={12} className="animate-spin" /> : <Search size={12} />}
+ {loading ? t('buttons.loading', 'LOADING...') : t('buttons.fetch', 'FETCH')}
+ </button>
+ </div>
+
+ {/* Popular Series Quick Add & Browse Button */}
+ <div style={{ display: 'flex', alignItems: 'flex-end', gap: '10px' }}>
+ <div style={{ flex: 1 }}>
+ <label style={{ color: colors.textMuted, fontSize: fontSize.tiny, marginBottom: '6px', display: 'block', fontWeight: 'bold' }}>
+ {t('form.quickAdd', 'QUICK ADD')}
+ </label>
+ <div style={{ display: 'flex', gap: '4px', flexWrap: 'wrap' }}>
+ {POPULAR_SERIES.map(series => (
+ <QuickAddButton
+ key={series.id}
+ seriesId={series.id}
+ isSelected={currentSeriesIdsSet.has(series.id)}
+ onClick={() => handleAddPopularSeries(series.id)}
+ colors={colors}
+ fontSize={fontSize}
+ />
+ ))}
+ </div>
+ </div>
+ <button
+ onClick={handleOpenBrowser}
+ disabled={!apiKeyConfigured}
+ style={{
+ background: apiKeyConfigured ? colors.primary : colors.panel,
+ border: `1px solid ${apiKeyConfigured ? colors.primary : colors.textMuted}44`,
+ color: apiKeyConfigured ? colors.background : colors.textMuted,
+ padding: '8px 14px',
+ fontSize: fontSize.small,
+ cursor: apiKeyConfigured ? 'pointer' : 'not-allowed',
+ borderRadius: '3px',
+ fontWeight: 'bold',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ whiteSpace: 'nowrap',
+ opacity: apiKeyConfigured ? 1 : 0.5,
+ transition: 'opacity 0.15s'
+ }}
+ >
+ <FolderTree size={12} />
+ {t('buttons.browse', 'BROWSE SERIES')}
+ </button>
+ </div>
+ </div>
+
+ {/* Main Content */}
+ <div style={{ flex: 1, display: 'flex', gap: '12px', padding: '12px 16px', overflow: 'hidden', minHeight: 0 }}>
+ {/* Chart Section */}
+ <div style={{ flex: 2, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
+ <div style={{
+ background: colors.panel,
+ border: `1px solid ${colors.primary}33`,
+ borderRadius: '4px',
+ padding: '14px',
+ height: '100%',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ <h3 style={{ color: colors.primary, fontSize: fontSize.body, fontWeight: 'bold', marginBottom: '10px', letterSpacing: '0.5px' }}>
+ {t('chart.title', 'TIME SERIES CHART')}
+ </h3>
+ <SeriesChart
+ data={data}
+ chartType={chartType}
+ normalizeData={normalizeData}
+ loading={loading}
+ loadingMessage={loadingMessage}
+ error={error}
+ apiKeyConfigured={apiKeyConfigured}
+ colors={colors}
+ fontSize={fontSize}
+ />
+ </div>
+ </div>
+
+ {/* Data Tables */}
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, overflowY: 'auto', gap: '10px' }}>
+ {data.map(series => (
+ <SeriesDataTable
+ key={series.series_id}
+ series={series}
+ colors={colors}
+ fontSize={fontSize}
+ />
+ ))}
+ </div>
+ </div>
+
+ {/* Footer */}
+ <TabFooter
+ tabName="ECONOMIC SCREENER"
+ leftInfo={[
+ { label: 'FRED Economic Data', color: colors.accent },
+ { label: 'Federal Reserve Bank of St. Louis', color: colors.textMuted },
+ ]}
+ statusInfo={
+ data.length > 0 && (
+ <span style={{ color: colors.primary, fontWeight: 'bold' }}>
+ {data.length} series | {totalObservations} observations
+ </span>
+ )
+ }
+ backgroundColor={colors.panel}
+ borderColor={colors.primary}
+ />
+ </div>
+ );
+}
+
+export default memo(ScreenerTab);
diff --git a/fincept-terminal-desktop/src/components/tabs/screener/components/SeriesBrowserModal.tsx b/fincept-terminal-desktop/src/components/tabs/screener/components/SeriesBrowserModal.tsx
new file mode 100644
index 000000000..9f4423be2
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/screener/components/SeriesBrowserModal.tsx
@@ -0,0 +1,459 @@
+import React, { memo, useCallback, useState, useEffect } from 'react';
+import { Search, FolderTree, X, Plus, ArrowLeft, ChevronRight, Loader2, TrendingUp } from 'lucide-react';
+import type { SearchResult, Category, CategoryPath } from '../types';
+import { POPULAR_CATEGORIES, SEARCH_DEBOUNCE_MS } from '../constants';
+
+interface SeriesBrowserModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ onAddSeries: (id: string) => void;
+ currentSeriesIds: Set<string>;
+ searchResults: SearchResult[];
+ searchLoading: boolean;
+ categories: Category[];
+ categoryLoading: boolean;
+ categorySeriesResults: SearchResult[];
+ categorySeriesLoading: boolean;
+ onSearch: (query: string) => void;
+ onLoadCategories: (categoryId: number) => void;
+ onLoadCategorySeries: (categoryId: number) => void;
+ colors: any;
+ fontSize: any;
+}
+
+const SearchResultItem = memo(({
+ result,
+ isAdded,
+ onAdd,
+ colors
+}: {
+ result: SearchResult;
+ isAdded: boolean;
+ onAdd: () => void;
+ colors: any;
+}) => (
+ <div
+ style={{
+ background: colors.panel,
+ border: `1px solid ${colors.border || '#1a1a1a'}`,
+ borderRadius: '4px',
+ padding: '12px',
+ display: 'flex',
+ alignItems: 'flex-start',
+ justifyContent: 'space-between',
+ gap: '12px'
+ }}
+ >
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
+ <span style={{ color: colors.primary, fontSize: '11px', fontWeight: 'bold', fontFamily: 'monospace' }}>
+ {result.id}
+ </span>
+ <span style={{ color: colors.textMuted, fontSize: '9px' }}>
+ Pop: {result.popularity}
+ </span>
+ </div>
+ <p style={{ color: colors.text, fontSize: '10px', marginBottom: '4px' }}>
+ {result.title}
+ </p>
+ <div style={{ display: 'flex', gap: '12px', fontSize: '9px', color: colors.textMuted }}>
+ <span>Freq: {result.frequency}</span>
+ <span>Units: {result.units}</span>
+ <span>Updated: {result.last_updated?.split('T')[0]}</span>
+ </div>
+ </div>
+ <button
+ onClick={onAdd}
+ disabled={isAdded}
+ style={{
+ background: isAdded ? colors.success + '33' : colors.primary,
+ border: 'none',
+ color: isAdded ? colors.success : colors.background,
+ padding: '6px 12px',
+ fontSize: '10px',
+ cursor: isAdded ? 'not-allowed' : 'pointer',
+ borderRadius: '3px',
+ fontWeight: 'bold',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ whiteSpace: 'nowrap',
+ opacity: isAdded ? 0.7 : 1
+ }}
+ >
+ <Plus size={12} />
+ {isAdded ? 'ADDED' : 'ADD'}
+ </button>
+ </div>
+));
+
+SearchResultItem.displayName = 'SearchResultItem';
+
+const CategoryButton = memo(({
+ category,
+ onClick,
+ colors
+}: {
+ category: { id: number; name: string };
+ onClick: () => void;
+ colors: any;
+}) => (
+ <button
+ onClick={onClick}
+ style={{
+ background: colors.background,
+ border: `1px solid ${colors.border || '#2a2a2a'}`,
+ color: colors.text,
+ padding: '8px 10px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ textAlign: 'left',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between'
+ }}
+ >
+ <span>{category.name}</span>
+ <ChevronRight size={12} color={colors.textMuted} />
+ </button>
+));
+
+CategoryButton.displayName = 'CategoryButton';
+
+function SeriesBrowserModal({
+ isOpen,
+ onClose,
+ onAddSeries,
+ currentSeriesIds,
+ searchResults,
+ searchLoading,
+ categories,
+ categoryLoading,
+ categorySeriesResults,
+ categorySeriesLoading,
+ onSearch,
+ onLoadCategories,
+ onLoadCategorySeries,
+ colors,
+ fontSize,
+}: SeriesBrowserModalProps) {
+ const [searchQuery, setSearchQuery] = useState('');
+ const [currentCategory, setCurrentCategory] = useState(0);
+ const [categoryPath, setCategoryPath] = useState<CategoryPath[]>([{ id: 0, name: 'All Categories' }]);
+
+ // Search debounce
+ useEffect(() => {
+ const timer = setTimeout(() => {
+ if (searchQuery && isOpen) {
+ onSearch(searchQuery);
+ }
+ }, SEARCH_DEBOUNCE_MS);
+ return () => clearTimeout(timer);
+ }, [searchQuery, isOpen, onSearch]);
+
+ // Load initial categories
+ useEffect(() => {
+ if (isOpen && categories.length === 0) {
+ onLoadCategories(0);
+ }
+ }, [isOpen, categories.length, onLoadCategories]);
+
+ const handleNavigateToCategory = useCallback((cat: { id: number; name: string }) => {
+ setCurrentCategory(cat.id);
+ setCategoryPath(prev => [...prev, cat]);
+ setSearchQuery('');
+
+ // Load both subcategories and series
+ onLoadCategories(cat.id);
+ onLoadCategorySeries(cat.id);
+ }, [onLoadCategories, onLoadCategorySeries]);
+
+ const handleNavigateBack = useCallback(() => {
+ if (categoryPath.length > 1) {
+ const newPath = categoryPath.slice(0, -1);
+ setCategoryPath(newPath);
+ const parentId = newPath[newPath.length - 1].id;
+ setCurrentCategory(parentId);
+ onLoadCategories(parentId);
+ }
+ }, [categoryPath, onLoadCategories]);
+
+ const handleAddSeries = useCallback((id: string) => {
+ onAddSeries(id);
+ }, [onAddSeries]);
+
+ if (!isOpen) return null;
+
+ return (
+ <div style={{
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ background: 'rgba(0,0,0,0.95)',
+ zIndex: 1000,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: '20px',
+ backdropFilter: 'blur(4px)'
+ }}>
+ <div style={{
+ background: colors.background,
+ border: `1px solid ${colors.primary}`,
+ borderRadius: '4px',
+ width: '90%',
+ maxWidth: '1200px',
+ height: '85vh',
+ display: 'flex',
+ flexDirection: 'column',
+ overflow: 'hidden',
+ boxShadow: `0 8px 32px ${colors.primary}33`
+ }}>
+ {/* Modal Header */}
+ <div style={{
+ borderBottom: `1px solid ${colors.primary}`,
+ padding: '12px 20px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ background: colors.panel
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
+ <FolderTree size={16} color={colors.primary} />
+ <span style={{ color: colors.primary, fontSize: fontSize.heading, fontWeight: 'bold', letterSpacing: '0.5px' }}>
+ FRED SERIES BROWSER
+ </span>
+ </div>
+ <button
+ onClick={onClose}
+ style={{
+ background: 'transparent',
+ border: 'none',
+ color: colors.textMuted,
+ cursor: 'pointer',
+ padding: '4px',
+ display: 'flex',
+ alignItems: 'center'
+ }}
+ >
+ <X size={18} />
+ </button>
+ </div>
+
+ {/* Search Bar */}
+ <div style={{ padding: '12px 20px', borderBottom: `1px solid ${colors.panel}` }}>
+ <div style={{ position: 'relative' }}>
+ <Search size={14} color={colors.textMuted} style={{ position: 'absolute', left: '12px', top: '50%', transform: 'translateY(-50%)' }} />
+ <input
+ type="text"
+ placeholder="Search FRED series by keyword (e.g., 'unemployment', 'inflation', 'GDP')..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ style={{
+ width: '100%',
+ background: colors.panel,
+ border: `1px solid ${colors.textMuted}33`,
+ color: colors.text,
+ padding: '10px 40px 10px 40px',
+ fontSize: fontSize.small,
+ borderRadius: '3px',
+ outline: 'none',
+ transition: 'border-color 0.2s'
+ }}
+ />
+ {searchLoading && (
+ <Loader2 size={14} className="animate-spin" style={{ position: 'absolute', right: '12px', top: '50%', transform: 'translateY(-50%)', color: colors.primary }} />
+ )}
+ </div>
+ </div>
+
+ {/* Content Area */}
+ <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
+ {/* Left Panel - Categories */}
+ {!searchQuery && (
+ <div style={{
+ width: '350px',
+ borderRight: `1px solid ${colors.border || '#1a1a1a'}`,
+ display: 'flex',
+ flexDirection: 'column',
+ background: colors.background
+ }}>
+ {/* Breadcrumb */}
+ <div style={{
+ padding: '12px 16px',
+ borderBottom: `1px solid ${colors.border || '#1a1a1a'}`,
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px'
+ }}>
+ {categoryPath.length > 1 && (
+ <button
+ onClick={handleNavigateBack}
+ style={{
+ background: colors.panel,
+ border: `1px solid ${colors.border || '#2a2a2a'}`,
+ color: colors.primary,
+ padding: '4px 8px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <ArrowLeft size={12} />
+ BACK
+ </button>
+ )}
+ <span style={{ color: colors.textMuted, fontSize: '10px', flex: 1 }}>
+ {categoryPath.map((p, i) => (
+ <span key={`${p.id}-${i}`}>
+ {i > 0 && ' > '}
+ {p.name}
+ </span>
+ ))}
+ </span>
+ </div>
+
+ {/* Popular Categories (only at root) */}
+ {currentCategory === 0 && (
+ <div style={{ padding: '12px', borderBottom: `1px solid ${colors.border || '#1a1a1a'}`, maxHeight: '200px', overflowY: 'auto' }}>
+ <h4 style={{ color: colors.primary, fontSize: '10px', marginBottom: '8px', fontWeight: 'bold' }}>
+ POPULAR CATEGORIES
+ </h4>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
+ {POPULAR_CATEGORIES.map((cat, idx) => (
+ <CategoryButton
+ key={`pop-${cat.id}-${idx}`}
+ category={{ id: cat.id, name: cat.name }}
+ onClick={() => handleNavigateToCategory({ id: cat.id, name: cat.name })}
+ colors={colors}
+ />
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Category List */}
+ <div style={{ flex: 1, overflowY: 'auto', padding: '12px' }}>
+ <h4 style={{ color: colors.textMuted, fontSize: '9px', marginBottom: '8px', fontWeight: 'bold' }}>
+ {categoryLoading ? 'LOADING...' : `SUBCATEGORIES (${categories.length})`}
+ </h4>
+ {categories.length === 0 && !categoryLoading && currentCategory !== 0 && (
+ <p style={{ color: colors.textMuted, fontSize: '10px' }}>No subcategories found</p>
+ )}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
+ {categories.map((cat, idx) => (
+ <CategoryButton
+ key={`cat-${cat.id}-${idx}`}
+ category={cat}
+ onClick={() => handleNavigateToCategory(cat)}
+ colors={colors}
+ />
+ ))}
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Right Panel - Results */}
+ <div style={{ flex: 1, overflowY: 'auto', padding: '16px 20px' }}>
+ {categorySeriesLoading && !searchQuery ? (
+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: '16px' }}>
+ <Loader2 size={32} color={colors.primary} className="animate-spin" />
+ <p style={{ color: colors.textMuted, fontSize: fontSize.small }}>
+ Loading series in category...
+ </p>
+ </div>
+ ) : searchQuery ? (
+ <>
+ <h3 style={{ color: colors.primary, fontSize: '11px', marginBottom: '12px', fontWeight: 'bold' }}>
+ SEARCH RESULTS ({searchResults.length})
+ </h3>
+ {searchResults.length === 0 && !searchLoading && (
+ <p style={{ color: colors.textMuted, fontSize: '10px' }}>No results found</p>
+ )}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ {searchResults.map((result) => (
+ <SearchResultItem
+ key={result.id}
+ result={result}
+ isAdded={currentSeriesIds.has(result.id)}
+ onAdd={() => handleAddSeries(result.id)}
+ colors={colors}
+ />
+ ))}
+ </div>
+ </>
+ ) : categorySeriesResults.length > 0 ? (
+ <>
+ <h3 style={{ color: colors.primary, fontSize: '11px', marginBottom: '12px', fontWeight: 'bold' }}>
+ SERIES IN THIS CATEGORY ({categorySeriesResults.length})
+ </h3>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
+ {categorySeriesResults.map((result) => (
+ <SearchResultItem
+ key={result.id}
+ result={result}
+ isAdded={currentSeriesIds.has(result.id)}
+ onAdd={() => handleAddSeries(result.id)}
+ colors={colors}
+ />
+ ))}
+ </div>
+ </>
+ ) : (
+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: '16px' }}>
+ <TrendingUp size={48} color={colors.textMuted} style={{ opacity: 0.3 }} />
+ <div style={{ textAlign: 'center', maxWidth: '500px' }}>
+ <p style={{ color: colors.textMuted, fontSize: '12px', marginBottom: '8px' }}>
+ <strong>Search for any economic data series</strong>
+ </p>
+ <p style={{ color: colors.textMuted, fontSize: '10px', lineHeight: '1.5', opacity: 0.7 }}>
+ Try searching for terms like "unemployment", "inflation", "GDP", "interest rates", "housing", etc.
+ Or browse through categories on the left to discover available data series.
+ </p>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Modal Footer */}
+ <div style={{
+ borderTop: `1px solid ${colors.border || '#1a1a1a'}`,
+ padding: '12px 20px',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ background: colors.panel
+ }}>
+ <span style={{ color: colors.textMuted, fontSize: '9px' }}>
+ Federal Reserve Economic Data (FRED) | 800,000+ series available
+ </span>
+ <button
+ onClick={onClose}
+ style={{
+ background: colors.primary,
+ border: 'none',
+ color: colors.background,
+ padding: '8px 16px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ fontWeight: 'bold'
+ }}
+ >
+ DONE
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+export default memo(SeriesBrowserModal);
diff --git a/fincept-terminal-desktop/src/components/tabs/screener/components/SeriesChart.tsx b/fincept-terminal-desktop/src/components/tabs/screener/components/SeriesChart.tsx
new file mode 100644
index 000000000..21601742f
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/screener/components/SeriesChart.tsx
@@ -0,0 +1,227 @@
+import React, { memo, useMemo } from 'react';
+import { LineChart, Line, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
+import { Loader2, TrendingUp, AlertCircle } from 'lucide-react';
+import type { FREDSeries } from '../types';
+import { CHART_COLORS } from '../constants';
+
+interface SeriesChartProps {
+ data: FREDSeries[];
+ chartType: 'line' | 'area';
+ normalizeData: boolean;
+ loading: boolean;
+ loadingMessage: string;
+ error: string | null;
+ apiKeyConfigured: boolean;
+ colors: any;
+ fontSize: any;
+}
+
+function SeriesChart({
+ data,
+ chartType,
+ normalizeData,
+ loading,
+ loadingMessage,
+ error,
+ apiKeyConfigured,
+ colors,
+ fontSize,
+}: SeriesChartProps) {
+ // Memoize chart data preparation
+ const chartData = useMemo(() => {
+ if (data.length === 0) return [];
+
+ const allDates = new Set<string>();
+ data.forEach(series => {
+ series.observations.forEach(obs => allDates.add(obs.date));
+ });
+
+ const sortedDates = Array.from(allDates).sort();
+
+ // First pass: collect all values
+ const rawData = sortedDates.map(date => {
+ const point: Record<string, any> = { date };
+ data.forEach(series => {
+ const obs = series.observations.find(o => o.date === date);
+ point[series.series_id] = obs?.value ?? null;
+ });
+ return point;
+ });
+
+ // If normalization is enabled, normalize each series to 0-100 scale
+ if (normalizeData && data.length > 1) {
+ const seriesStats: Record<string, { min: number; max: number }> = {};
+
+ data.forEach(series => {
+ const values = series.observations
+ .map(obs => parseFloat(obs.value.toString()))
+ .filter(v => !isNaN(v) && v !== null);
+ if (values.length > 0) {
+ seriesStats[series.series_id] = {
+ min: Math.min(...values),
+ max: Math.max(...values)
+ };
+ }
+ });
+
+ return rawData.map(point => {
+ const normalizedPoint: Record<string, any> = { date: point.date };
+ data.forEach(series => {
+ const value = point[series.series_id];
+ if (value !== null && value !== undefined && seriesStats[series.series_id]) {
+ const { min, max } = seriesStats[series.series_id];
+ const range = max - min;
+ normalizedPoint[series.series_id] = range > 0 ? ((value - min) / range) * 100 : 50;
+ } else {
+ normalizedPoint[series.series_id] = null;
+ }
+ });
+ return normalizedPoint;
+ });
+ }
+
+ return rawData;
+ }, [data, normalizeData]);
+
+ // Memoize tooltip style
+ const tooltipStyle = useMemo(() => ({
+ contentStyle: {
+ background: colors.background,
+ border: `1px solid ${colors.primary}`,
+ borderRadius: '3px',
+ fontSize: fontSize.small
+ },
+ labelStyle: { color: colors.primary, fontSize: fontSize.tiny },
+ itemStyle: { color: colors.text, fontSize: fontSize.tiny }
+ }), [colors, fontSize]);
+
+ // Memoize axis style
+ const axisStyle = useMemo(() => ({
+ fontSize: fontSize.tiny,
+ fill: colors.textMuted
+ }), [colors.textMuted, fontSize.tiny]);
+
+ if (loading) {
+ return (
+ <div style={{
+ flex: 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexDirection: 'column',
+ gap: '16px'
+ }}>
+ <Loader2 size={48} color={colors.primary} className="animate-spin" />
+ <div style={{ textAlign: 'center' }}>
+ <p style={{ color: colors.primary, fontSize: fontSize.body, fontWeight: 'bold', marginBottom: '6px' }}>
+ {loadingMessage}
+ </p>
+ <p style={{ color: colors.textMuted, fontSize: fontSize.small }}>
+ Please wait while we fetch data from FRED...
+ </p>
+ </div>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div style={{
+ background: `${colors.alert}11`,
+ border: `2px solid ${colors.alert}`,
+ color: colors.alert,
+ padding: '16px',
+ borderRadius: '4px',
+ fontSize: '11px',
+ marginBottom: '12px',
+ display: 'flex',
+ alignItems: 'flex-start',
+ gap: '12px',
+ boxShadow: `0 2px 8px ${colors.alert}33`
+ }}>
+ <AlertCircle size={20} style={{ flexShrink: 0, marginTop: '2px' }} />
+ <div style={{ flex: 1 }}>
+ <p style={{ fontWeight: 'bold', marginBottom: '4px' }}>Error Fetching Data</p>
+ <p style={{ color: colors.text, fontSize: '10px', opacity: 0.8 }}>{error}</p>
+ {!apiKeyConfigured && (
+ <p style={{ color: colors.text, fontSize: '10px', marginTop: '8px', opacity: 0.8 }}>
+ 💡 Tip: Make sure you've configured your FRED API key in Settings → Credentials
+ </p>
+ )}
+ </div>
+ </div>
+ );
+ }
+
+ if (data.length === 0) {
+ return (
+ <div style={{
+ flex: 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ color: colors.textMuted,
+ fontSize: fontSize.body,
+ flexDirection: 'column',
+ gap: '10px'
+ }}>
+ <TrendingUp size={48} color={colors.textMuted} style={{ opacity: 0.3 }} />
+ <p style={{ color: colors.text }}>No data to display</p>
+ <p style={{ fontSize: fontSize.small, color: colors.textMuted }}>
+ Enter series IDs and click Fetch to load data
+ </p>
+ </div>
+ );
+ }
+
+ const ChartComponent = chartType === 'line' ? LineChart : AreaChart;
+ const DataComponent = chartType === 'line' ? Line : Area;
+
+ return (
+ <div style={{ flex: 1, minHeight: 0 }}>
+ <ResponsiveContainer width="100%" height="100%">
+ <ChartComponent data={chartData} margin={{ top: 5, right: 20, left: 10, bottom: 5 }}>
+ <CartesianGrid strokeDasharray="3 3" stroke={`${colors.textMuted}22`} />
+ <XAxis dataKey="date" stroke={colors.textMuted} style={axisStyle} />
+ <YAxis
+ stroke={colors.textMuted}
+ style={axisStyle}
+ label={normalizeData ? {
+ value: 'Normalized (0-100)',
+ angle: -90,
+ position: 'insideLeft',
+ style: { fontSize: fontSize.tiny, fill: colors.textMuted }
+ } : undefined}
+ />
+ <Tooltip {...tooltipStyle} />
+ <Legend wrapperStyle={{ fontSize: fontSize.tiny }} />
+ {data.map((series, idx) => {
+ const color = CHART_COLORS[idx % CHART_COLORS.length];
+ return chartType === 'line' ? (
+ <Line
+ key={series.series_id}
+ type="monotone"
+ dataKey={series.series_id}
+ stroke={color}
+ strokeWidth={2}
+ dot={false}
+ isAnimationActive={false}
+ />
+ ) : (
+ <Area
+ key={series.series_id}
+ type="monotone"
+ dataKey={series.series_id}
+ stroke={color}
+ fill={`${color}33`}
+ isAnimationActive={false}
+ />
+ );
+ })}
+ </ChartComponent>
+ </ResponsiveContainer>
+ </div>
+ );
+}
+
+export default memo(SeriesChart);
diff --git a/fincept-terminal-desktop/src/components/tabs/screener/components/SeriesDataTable.tsx b/fincept-terminal-desktop/src/components/tabs/screener/components/SeriesDataTable.tsx
new file mode 100644
index 000000000..7146d28d1
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/screener/components/SeriesDataTable.tsx
@@ -0,0 +1,58 @@
+import React, { memo } from 'react';
+import type { FREDSeries } from '../types';
+
+interface SeriesDataTableProps {
+ series: FREDSeries;
+ colors: any;
+ fontSize: any;
+}
+
+function SeriesDataTable({ series, colors, fontSize }: SeriesDataTableProps) {
+ return (
+ <div
+ style={{
+ background: colors.panel,
+ border: `1px solid ${colors.primary}33`,
+ borderRadius: '4px',
+ padding: '12px',
+ flexShrink: 0
+ }}
+ >
+ <div style={{ borderBottom: `1px solid ${colors.textMuted}33`, paddingBottom: '8px', marginBottom: '8px' }}>
+ <h4 style={{ color: colors.primary, fontSize: fontSize.body, fontWeight: 'bold', marginBottom: '4px' }}>
+ {series.series_id}
+ </h4>
+ <p style={{ color: colors.text, fontSize: fontSize.tiny, marginBottom: '6px' }}>{series.title}</p>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px', fontSize: fontSize.tiny, color: colors.textMuted }}>
+ <span>Units: {series.units}</span>
+ <span>Freq: {series.frequency}</span>
+ <span>Obs: {series.observation_count}</span>
+ <span>Updated: {series.last_updated?.split('T')[0]}</span>
+ </div>
+ </div>
+
+ <div style={{ maxHeight: '200px', overflowY: 'auto' }}>
+ <table style={{ width: '100%', fontSize: fontSize.tiny, borderCollapse: 'collapse' }}>
+ <thead style={{ position: 'sticky', top: 0, background: colors.panel }}>
+ <tr style={{ borderBottom: `1px solid ${colors.textMuted}33` }}>
+ <th style={{ color: colors.textMuted, textAlign: 'left', padding: '6px 4px', fontWeight: 'bold' }}>Date</th>
+ <th style={{ color: colors.textMuted, textAlign: 'right', padding: '6px 4px', fontWeight: 'bold' }}>Value</th>
+ </tr>
+ </thead>
+ <tbody>
+ {series.observations.slice(-20).reverse().map((obs, idx) => (
+ <tr key={`${obs.date}-${idx}`} style={{ borderBottom: `1px solid ${colors.background}` }}>
+ <td style={{ color: colors.textMuted, padding: '4px' }}>{obs.date}</td>
+ <td style={{ color: colors.text, textAlign: 'right', padding: '4px', fontFamily: 'monospace', fontSize: fontSize.tiny }}>
+ {obs.value.toFixed(2)}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ );
+}
+
+export default memo(SeriesDataTable);
diff --git a/fincept-terminal-desktop/src/components/tabs/screener/components/index.ts b/fincept-terminal-desktop/src/components/tabs/screener/components/index.ts
new file mode 100644
index 000000000..a2b9bcb37
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/screener/components/index.ts
@@ -0,0 +1,3 @@
+export { default as SeriesBrowserModal } from './SeriesBrowserModal';
+export { default as SeriesChart } from './SeriesChart';
+export { default as SeriesDataTable } from './SeriesDataTable';
diff --git a/fincept-terminal-desktop/src/components/tabs/screener/constants.ts b/fincept-terminal-desktop/src/components/tabs/screener/constants.ts
new file mode 100644
index 000000000..a651203af
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/screener/constants.ts
@@ -0,0 +1,30 @@
+import type { PopularSeries, PopularCategory } from './types';
+
+export const POPULAR_SERIES: PopularSeries[] = [
+ { id: 'GDP', name: 'Gross Domestic Product', cat: 'Economic' },
+ { id: 'UNRATE', name: 'Unemployment Rate', cat: 'Labor' },
+ { id: 'CPIAUCSL', name: 'Consumer Price Index', cat: 'Inflation' },
+ { id: 'FEDFUNDS', name: 'Federal Funds Rate', cat: 'Interest Rates' },
+ { id: 'DGS10', name: '10-Year Treasury Rate', cat: 'Bonds' },
+ { id: 'DEXUSEU', name: 'USD/EUR Exchange Rate', cat: 'Forex' },
+ { id: 'DCOILWTICO', name: 'WTI Crude Oil Price', cat: 'Commodities' },
+ { id: 'GOLDAMGBD228NLBM', name: 'Gold Price', cat: 'Commodities' }
+];
+
+export const POPULAR_CATEGORIES: PopularCategory[] = [
+ { id: 32991, name: 'Money, Banking, & Finance', desc: 'Money supply, interest rates, banking data' },
+ { id: 10, name: 'Population, Employment, Labor', desc: 'Employment, unemployment, labor statistics' },
+ { id: 32455, name: 'Prices', desc: 'Inflation, CPI, PPI, commodity prices' },
+ { id: 1, name: 'Production & Business', desc: 'Industrial production, capacity utilization' },
+ { id: 32263, name: 'International Data', desc: 'Trade, exchange rates, foreign markets' },
+ { id: 33060, name: 'U.S. Regional Data', desc: 'State and metro area statistics' },
+];
+
+// Cache duration in milliseconds (5 minutes)
+export const CACHE_DURATION = 5 * 60 * 1000;
+
+// Search debounce delay
+export const SEARCH_DEBOUNCE_MS = 300;
+
+// Chart colors
+export const CHART_COLORS = ['#ea580c', '#22c55e', '#3b82f6', '#eab308', '#ef4444'];
diff --git a/fincept-terminal-desktop/src/components/tabs/screener/hooks/index.ts b/fincept-terminal-desktop/src/components/tabs/screener/hooks/index.ts
new file mode 100644
index 000000000..45c09202f
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/screener/hooks/index.ts
@@ -0,0 +1 @@
+export { useScreenerData } from './useScreenerData';
diff --git a/fincept-terminal-desktop/src/components/tabs/screener/hooks/useScreenerData.ts b/fincept-terminal-desktop/src/components/tabs/screener/hooks/useScreenerData.ts
new file mode 100644
index 000000000..e95ae396c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/screener/hooks/useScreenerData.ts
@@ -0,0 +1,268 @@
+import { useState, useCallback, useRef } from 'react';
+import { invoke } from '@tauri-apps/api/core';
+import { sqliteService } from '@/services/core/sqliteService';
+import type { FREDSeries, SearchResult, Category, SeriesCache, CachedData } from '../types';
+import { CACHE_DURATION } from '../constants';
+
+interface UseScreenerDataReturn {
+ // Data
+ data: FREDSeries[];
+ searchResults: SearchResult[];
+ categories: Category[];
+ categorySeriesResults: SearchResult[];
+
+ // Loading states
+ loading: boolean;
+ loadingMessage: string;
+ searchLoading: boolean;
+ categoryLoading: boolean;
+ categorySeriesLoading: boolean;
+
+ // Error
+ error: string | null;
+
+ // API key
+ apiKeyConfigured: boolean;
+
+ // Actions
+ fetchData: (seriesIds: string, startDate: string, endDate: string) => Promise<void>;
+ searchSeries: (query: string) => Promise<void>;
+ loadCategories: (categoryId?: number) => Promise<void>;
+ loadCategorySeries: (categoryId: number) => Promise<void>;
+ checkApiKey: () => Promise<void>;
+ clearError: () => void;
+}
+
+export function useScreenerData(): UseScreenerDataReturn {
+ const [data, setData] = useState<FREDSeries[]>([]);
+ const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
+ const [categories, setCategories] = useState<Category[]>([]);
+ const [categorySeriesResults, setCategorySeriesResults] = useState<SearchResult[]>([]);
+
+ const [loading, setLoading] = useState(false);
+ const [loadingMessage, setLoadingMessage] = useState('');
+ const [searchLoading, setSearchLoading] = useState(false);
+ const [categoryLoading, setCategoryLoading] = useState(false);
+ const [categorySeriesLoading, setCategorySeriesLoading] = useState(false);
+
+ const [error, setError] = useState<string | null>(null);
+ const [apiKeyConfigured, setApiKeyConfigured] = useState(false);
+
+ // Cache for series data
+ const seriesCache = useRef<SeriesCache>(new Map());
+
+ const isCacheValid = useCallback((cached: CachedData<FREDSeries> | undefined): boolean => {
+ if (!cached) return false;
+ return Date.now() - cached.timestamp < CACHE_DURATION;
+ }, []);
+
+ const checkApiKey = useCallback(async () => {
+ try {
+ const apiKey = await sqliteService.getApiKey('FRED');
+ setApiKeyConfigured(!!apiKey);
+ } catch (err) {
+ console.error('[ScreenerData] Failed to check FRED API key:', err);
+ setApiKeyConfigured(false);
+ }
+ }, []);
+
+ const clearError = useCallback(() => {
+ setError(null);
+ }, []);
+
+ const fetchData = useCallback(async (seriesIds: string, startDate: string, endDate: string) => {
+ setLoading(true);
+ setError(null);
+ setLoadingMessage('Initializing...');
+
+ try {
+ const apiKey = await sqliteService.getApiKey('FRED');
+ if (!apiKey) {
+ setError('FRED API key not configured. Please add it in Settings > Credentials.');
+ setApiKeyConfigured(false);
+ return;
+ }
+
+ // Remove duplicates and trim
+ const ids = [...new Set(seriesIds.split(',').map(s => s.trim()).filter(Boolean))];
+
+ if (ids.length === 0) {
+ setError('Please enter at least one series ID');
+ return;
+ }
+
+ // Check cache for already loaded series
+ const cachedSeries: FREDSeries[] = [];
+ const idsToFetch: string[] = [];
+
+ for (const id of ids) {
+ const cacheKey = `${id}-${startDate}-${endDate}`;
+ const cached = seriesCache.current.get(cacheKey);
+ if (isCacheValid(cached)) {
+ cachedSeries.push(cached!.data);
+ } else {
+ idsToFetch.push(id);
+ }
+ }
+
+ if (idsToFetch.length === 0) {
+ // All data is cached
+ setData(cachedSeries);
+ setLoadingMessage('Loaded from cache!');
+ setTimeout(() => setLoadingMessage(''), 1000);
+ return;
+ }
+
+ setLoadingMessage(`Fetching ${idsToFetch.length} series from FRED API...`);
+ const args = ['multiple', ...idsToFetch, startDate, endDate];
+
+ const result = await invoke<string>('execute_python_script', {
+ scriptName: 'fred_data.py',
+ args,
+ env: { FRED_API_KEY: apiKey }
+ });
+
+ setLoadingMessage('Processing data...');
+ const parsed = JSON.parse(result);
+
+ if (parsed.error) {
+ setError(`API Error: ${parsed.error}`);
+ } else if (Array.isArray(parsed)) {
+ const errorSeries = parsed.find((s: FREDSeries) => s.error);
+ if (errorSeries) {
+ setError(`Failed to fetch ${errorSeries.series_id}: ${errorSeries.error}`);
+ } else {
+ // Cache the new data
+ for (const series of parsed) {
+ const cacheKey = `${series.series_id}-${startDate}-${endDate}`;
+ seriesCache.current.set(cacheKey, {
+ data: series,
+ timestamp: Date.now()
+ });
+ }
+
+ // Combine cached and new data, maintaining order
+ const allData = ids.map(id => {
+ const cached = cachedSeries.find(s => s.series_id === id);
+ if (cached) return cached;
+ return parsed.find((s: FREDSeries) => s.series_id === id);
+ }).filter(Boolean) as FREDSeries[];
+
+ setData(allData);
+ setError(null);
+ setLoadingMessage(`Successfully loaded ${allData.length} series!`);
+ setTimeout(() => setLoadingMessage(''), 2000);
+ }
+ } else {
+ setData(parsed);
+ }
+ } catch (err: any) {
+ setError(err.message || 'Failed to fetch data');
+ } finally {
+ setLoading(false);
+ }
+ }, [isCacheValid]);
+
+ const searchSeries = useCallback(async (query: string) => {
+ if (!query.trim()) {
+ setSearchResults([]);
+ return;
+ }
+
+ setSearchLoading(true);
+ try {
+ const apiKey = await sqliteService.getApiKey('FRED');
+ if (!apiKey) return;
+
+ const result = await invoke<string>('execute_python_script', {
+ scriptName: 'fred_data.py',
+ args: ['search', query, '50'],
+ env: { FRED_API_KEY: apiKey }
+ });
+
+ const parsed = JSON.parse(result);
+ if (!parsed.error && parsed.series) {
+ setSearchResults(parsed.series);
+ } else {
+ setSearchResults([]);
+ }
+ } catch (err) {
+ setSearchResults([]);
+ } finally {
+ setSearchLoading(false);
+ }
+ }, []);
+
+ const loadCategories = useCallback(async (categoryId: number = 0) => {
+ setCategoryLoading(true);
+ try {
+ const apiKey = await sqliteService.getApiKey('FRED');
+ if (!apiKey) return;
+
+ const result = await invoke<string>('execute_python_script', {
+ scriptName: 'fred_data.py',
+ args: ['categories', categoryId.toString()],
+ env: { FRED_API_KEY: apiKey }
+ });
+
+ const parsed = JSON.parse(result);
+ if (!parsed.error && parsed.categories) {
+ setCategories(parsed.categories);
+ } else {
+ setCategories([]);
+ }
+ } catch (err) {
+ setCategories([]);
+ } finally {
+ setCategoryLoading(false);
+ }
+ }, []);
+
+ const loadCategorySeries = useCallback(async (categoryId: number) => {
+ setCategorySeriesLoading(true);
+ try {
+ const apiKey = await sqliteService.getApiKey('FRED');
+ if (!apiKey) {
+ setCategorySeriesLoading(false);
+ return;
+ }
+
+ const result = await invoke<string>('execute_python_script', {
+ scriptName: 'fred_data.py',
+ args: ['category_series', categoryId.toString(), '50'],
+ env: { FRED_API_KEY: apiKey }
+ });
+
+ const parsed = JSON.parse(result);
+ if (!parsed.error && parsed.series) {
+ setCategorySeriesResults(parsed.series);
+ } else {
+ setCategorySeriesResults([]);
+ }
+ } catch (err) {
+ setCategorySeriesResults([]);
+ } finally {
+ setCategorySeriesLoading(false);
+ }
+ }, []);
+
+ return {
+ data,
+ searchResults,
+ categories,
+ categorySeriesResults,
+ loading,
+ loadingMessage,
+ searchLoading,
+ categoryLoading,
+ categorySeriesLoading,
+ error,
+ apiKeyConfigured,
+ fetchData,
+ searchSeries,
+ loadCategories,
+ loadCategorySeries,
+ checkApiKey,
+ clearError,
+ };
+}
diff --git a/fincept-terminal-desktop/src/components/tabs/screener/index.ts b/fincept-terminal-desktop/src/components/tabs/screener/index.ts
new file mode 100644
index 000000000..e0b63244e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/screener/index.ts
@@ -0,0 +1,4 @@
+export { default } from "./ScreenerTab";
+export { default as ScreenerTab } from "./ScreenerTab";
+export * from "./types";
+export * from "./constants";
diff --git a/fincept-terminal-desktop/src/components/tabs/screener/types.ts b/fincept-terminal-desktop/src/components/tabs/screener/types.ts
new file mode 100644
index 000000000..e6be17ac3
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/screener/types.ts
@@ -0,0 +1,59 @@
+// Types for Screener Tab
+
+export interface SeriesData {
+ date: string;
+ value: number;
+}
+
+export interface FREDSeries {
+ series_id: string;
+ title: string;
+ units: string;
+ frequency: string;
+ seasonal_adjustment: string;
+ last_updated: string;
+ observations: SeriesData[];
+ observation_count: number;
+ error?: string;
+}
+
+export interface SearchResult {
+ id: string;
+ title: string;
+ frequency: string;
+ units: string;
+ seasonal_adjustment: string;
+ last_updated: string;
+ popularity: number;
+}
+
+export interface Category {
+ id: number;
+ name: string;
+ parent_id: number;
+}
+
+export interface CategoryPath {
+ id: number;
+ name: string;
+}
+
+export interface PopularSeries {
+ id: string;
+ name: string;
+ cat: string;
+}
+
+export interface PopularCategory {
+ id: number;
+ name: string;
+ desc: string;
+}
+
+// Cache types
+export interface CachedData<T> {
+ data: T;
+ timestamp: number;
+}
+
+export type SeriesCache = Map<string, CachedData<FREDSeries>>;
diff --git a/fincept-terminal-desktop/src/components/tabs/SupportTicketTab.tsx b/fincept-terminal-desktop/src/components/tabs/support-ticket/SupportTicketTab.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/SupportTicketTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/support-ticket/SupportTicketTab.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/support-ticket/index.ts b/fincept-terminal-desktop/src/components/tabs/support-ticket/index.ts
new file mode 100644
index 000000000..277f4977d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/support-ticket/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./SupportTicketTab";
+export { default as SupportTicketTab } from "./SupportTicketTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/TickerEditModal.tsx b/fincept-terminal-desktop/src/components/tabs/ticker-edit-modal/TickerEditModal.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/TickerEditModal.tsx
rename to fincept-terminal-desktop/src/components/tabs/ticker-edit-modal/TickerEditModal.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/ticker-edit-modal/index.ts b/fincept-terminal-desktop/src/components/tabs/ticker-edit-modal/index.ts
new file mode 100644
index 000000000..08d2633c1
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ticker-edit-modal/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./TickerEditModal";
+export { default as TickerEditModal } from "./TickerEditModal";
diff --git a/fincept-terminal-desktop/src/components/tabs/ToolCallDisplay.tsx b/fincept-terminal-desktop/src/components/tabs/tool-call-display/ToolCallDisplay.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/ToolCallDisplay.tsx
rename to fincept-terminal-desktop/src/components/tabs/tool-call-display/ToolCallDisplay.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/tool-call-display/index.ts b/fincept-terminal-desktop/src/components/tabs/tool-call-display/index.ts
new file mode 100644
index 000000000..5f042ce9d
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/tool-call-display/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./ToolCallDisplay";
+export { default as ToolCallDisplay } from "./ToolCallDisplay";
diff --git a/fincept-terminal-desktop/src/components/tabs/TradeVisualizationTab.tsx b/fincept-terminal-desktop/src/components/tabs/trade-visualization/TradeVisualizationTab.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/TradeVisualizationTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/trade-visualization/TradeVisualizationTab.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/trade-visualization/index.ts b/fincept-terminal-desktop/src/components/tabs/trade-visualization/index.ts
new file mode 100644
index 000000000..7d27b823e
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/trade-visualization/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./TradeVisualizationTab";
+export { default as TradeVisualizationTab } from "./TradeVisualizationTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/Visualization3DTab.tsx b/fincept-terminal-desktop/src/components/tabs/visualization-3d/Visualization3DTab.tsx
similarity index 100%
rename from fincept-terminal-desktop/src/components/tabs/Visualization3DTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/visualization-3d/Visualization3DTab.tsx
diff --git a/fincept-terminal-desktop/src/components/tabs/visualization-3d/index.ts b/fincept-terminal-desktop/src/components/tabs/visualization-3d/index.ts
new file mode 100644
index 000000000..00a65a6ed
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/visualization-3d/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./Visualization3DTab";
+export { default as Visualization3DTab } from "./Visualization3DTab";
diff --git a/fincept-terminal-desktop/src/components/tabs/WatchlistTab.tsx b/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistTab.tsx
similarity index 97%
rename from fincept-terminal-desktop/src/components/tabs/WatchlistTab.tsx
rename to fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistTab.tsx
index c35d026bd..d75cb3a00 100644
--- a/fincept-terminal-desktop/src/components/tabs/WatchlistTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistTab.tsx
@@ -4,17 +4,17 @@ import {
watchlistService,
Watchlist,
WatchlistStockWithQuote
-} from '../../services/core/watchlistService';
-import { contextRecorderService } from '../../services/data-sources/contextRecorderService';
-import { useWatchlistStocks, useMarketMovers, useVolumeLeaders } from '../../hooks/useWatchlist';
-import WatchlistSidebar from './watchlist/WatchlistSidebar';
-import StockListView from './watchlist/StockListView';
+} from '@/services/core/watchlistService';
+import { contextRecorderService } from '@/services/data-sources/contextRecorderService';
+import { useWatchlistStocks, useMarketMovers, useVolumeLeaders } from '@/hooks/useWatchlist';
+import WatchlistSidebar from './WatchlistSidebar';
+import StockListView from './StockListView';
import { TabFooter } from '@/components/common/TabFooter';
-import StockDetailPanel from './watchlist/StockDetailPanel';
-import CreateWatchlistModal from './watchlist/CreateWatchlistModal';
-import AddStockModal from './watchlist/AddStockModal';
-import RecordingControlPanel from '../common/RecordingControlPanel';
-import { getFinceptColors, SortCriteria, sortStocks, getNextWatchlistColor } from './watchlist/utils';
+import StockDetailPanel from './StockDetailPanel';
+import CreateWatchlistModal from './CreateWatchlistModal';
+import AddStockModal from './AddStockModal';
+import RecordingControlPanel from '@/components/common/RecordingControlPanel';
+import { getFinceptColors, SortCriteria, sortStocks, getNextWatchlistColor } from './utils';
import { useTerminalTheme } from '@/contexts/ThemeContext';
import { useTranslation } from 'react-i18next';
diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/index.ts b/fincept-terminal-desktop/src/components/tabs/watchlist/index.ts
new file mode 100644
index 000000000..279a6f507
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/index.ts
@@ -0,0 +1,2 @@
+export { default } from "./WatchlistTab";
+export { default as WatchlistTab } from "./WatchlistTab";
diff --git a/fincept-terminal-desktop/src/services/geopolitics/relationshipMapService.ts b/fincept-terminal-desktop/src/services/geopolitics/relationshipMapService.ts
index 39af3c5ff..701958e89 100644
--- a/fincept-terminal-desktop/src/services/geopolitics/relationshipMapService.ts
+++ b/fincept-terminal-desktop/src/services/geopolitics/relationshipMapService.ts
@@ -116,12 +116,51 @@ export interface RelationshipMapData {
// SERVICE CLASS
// ============================================================================
+// Cache configuration
+const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes
+
+interface CacheEntry<T> {
+ data: T;
+ timestamp: number;
+}
+
class RelationshipMapService {
+ // In-memory cache for relationship data
+ private cache: Map<string, CacheEntry<RelationshipMapData>> = new Map();
+
+ /**
+ * Check if cache entry is still valid
+ */
+ private isCacheValid<T>(entry: CacheEntry<T> | undefined): boolean {
+ if (!entry) return false;
+ return Date.now() - entry.timestamp < CACHE_DURATION;
+ }
+
+ /**
+ * Clear cache for a specific ticker or all
+ */
+ clearCache(ticker?: string): void {
+ if (ticker) {
+ this.cache.delete(ticker.toUpperCase());
+ } else {
+ this.cache.clear();
+ }
+ }
/**
* Get comprehensive relationship map data for a ticker
*/
async getRelationshipMap(ticker: string): Promise<RelationshipMapData> {
+ const upperTicker = ticker.toUpperCase();
+
+ // Check cache first
+ const cached = this.cache.get(upperTicker);
+ if (this.isCacheValid(cached)) {
+ console.log(`[RelationshipMapService] Cache hit for ${upperTicker}`);
+ return cached!.data;
+ }
+
+ console.log(`[RelationshipMapService] Cache miss for ${upperTicker}, fetching...`);
try {
const [edgarCompany, edgarProxy, edgarFilings, edgarEvents, yfinanceInfo] = await Promise.allSettled([
this.getEdgarCompany(ticker),
@@ -137,7 +176,15 @@ class RelationshipMapService {
const eventsData = edgarEvents.status === 'fulfilled' ? edgarEvents.value : null;
const yfinanceData = yfinanceInfo.status === 'fulfilled' ? yfinanceInfo.value : null;
- return this.combineData(ticker, companyData, proxyData, filingsData, eventsData, yfinanceData);
+ const result = this.combineData(ticker, companyData, proxyData, filingsData, eventsData, yfinanceData);
+
+ // Store in cache
+ this.cache.set(upperTicker, {
+ data: result,
+ timestamp: Date.now(),
+ });
+
+ return result;
} catch (error) {
console.error('[RelationshipMapService] Error:', error);
throw error;
diff --git a/fincept-terminal-desktop/src/services/support/index.ts b/fincept-terminal-desktop/src/services/support/index.ts
new file mode 100644
index 000000000..ec0fa2d43
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/support/index.ts
@@ -0,0 +1,2 @@
+// Support services barrel export
+export * from './supportApi';
diff --git a/fincept-terminal-desktop/src/services/support/supportApi.ts b/fincept-terminal-desktop/src/services/support/supportApi.ts
new file mode 100644
index 000000000..efad955bf
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/support/supportApi.ts
@@ -0,0 +1,175 @@
+// Support API Service - Feedback, Contact, Newsletter endpoints
+
+const API_BASE_URL = 'https://finceptbackend.share.zrok.io';
+
+// Types
+export interface ContactFormData {
+ name: string;
+ email: string;
+ subject: string;
+ message: string;
+}
+
+export interface FeedbackFormData {
+ name?: string;
+ email?: string;
+ rating: number;
+ feedback_text: string;
+ category?: string;
+}
+
+export interface NewsletterSubscribeData {
+ email: string;
+ source?: string;
+}
+
+export interface ApiResponse<T = any> {
+ success: boolean;
+ data?: T;
+ message?: string;
+ error?: string;
+}
+
+// API Functions
+
+/**
+ * Submit contact form (public endpoint)
+ */
+export async function submitContactForm(data: ContactFormData): Promise<ApiResponse> {
+ try {
+ const response = await fetch(`${API_BASE_URL}/support/contact`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(data),
+ });
+
+ const result = await response.json();
+
+ if (!response.ok) {
+ return {
+ success: false,
+ error: result.detail || 'Failed to submit contact form',
+ };
+ }
+
+ return {
+ success: true,
+ data: result,
+ message: 'Contact form submitted successfully',
+ };
+ } catch (error) {
+ console.error('Contact form submission error:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Network error',
+ };
+ }
+}
+
+/**
+ * Submit feedback (public endpoint)
+ */
+export async function submitFeedback(data: FeedbackFormData): Promise<ApiResponse> {
+ try {
+ const response = await fetch(`${API_BASE_URL}/support/feedback`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(data),
+ });
+
+ const result = await response.json();
+
+ if (!response.ok) {
+ return {
+ success: false,
+ error: result.detail || 'Failed to submit feedback',
+ };
+ }
+
+ return {
+ success: true,
+ data: result,
+ message: 'Feedback submitted successfully',
+ };
+ } catch (error) {
+ console.error('Feedback submission error:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Network error',
+ };
+ }
+}
+
+/**
+ * Subscribe to newsletter (public endpoint)
+ */
+export async function subscribeToNewsletter(data: NewsletterSubscribeData): Promise<ApiResponse> {
+ try {
+ const response = await fetch(`${API_BASE_URL}/support/newsletter/subscribe`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(data),
+ });
+
+ const result = await response.json();
+
+ if (!response.ok) {
+ return {
+ success: false,
+ error: result.detail || 'Failed to subscribe to newsletter',
+ };
+ }
+
+ return {
+ success: true,
+ data: result,
+ message: 'Successfully subscribed to newsletter',
+ };
+ } catch (error) {
+ console.error('Newsletter subscription error:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Network error',
+ };
+ }
+}
+
+/**
+ * Get support categories (public endpoint)
+ */
+export async function getSupportCategories(): Promise<ApiResponse<string[]>> {
+ try {
+ const response = await fetch(`${API_BASE_URL}/support/categories`, {
+ method: 'GET',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ const result = await response.json();
+
+ if (!response.ok) {
+ return {
+ success: false,
+ error: result.detail || 'Failed to fetch categories',
+ };
+ }
+
+ return {
+ success: true,
+ data: result,
+ };
+ } catch (error) {
+ console.error('Get categories error:', error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Network error',
+ };
+ }
+}
diff --git a/openapi.json b/openapi.json
new file mode 100644
index 000000000..bedf9fb8c
--- /dev/null
+++ b/openapi.json
@@ -0,0 +1 @@
+{"openapi":"3.1.0","info":{"title":"Fincept API","description":"Modular Financial Data API","version":"3.0.0"},"paths":{"/auth/user/verify-simulate":{"post":{"tags":["authentication"],"summary":"Simulate User Verification","description":"Simulate OTP verification for testing purposes","operationId":"simulate_user_verification_auth_user_verify_simulate_post","parameters":[{"name":"email","in":"query","required":true,"schema":{"type":"string","title":"Email"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/register":{"post":{"tags":["users"],"summary":"Register User","description":"Register new user account","operationId":"register_user_user_register_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserRegistration"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/verify-otp":{"post":{"tags":["users"],"summary":"Verify Otp","description":"Verify OTP and activate account","operationId":"verify_otp_user_verify_otp_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OTPVerification"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/login":{"post":{"tags":["users"],"summary":"Login User","description":"User login with history tracking","operationId":"login_user_user_login_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserLogin"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/verify-mfa":{"post":{"tags":["users"],"summary":"Verify Mfa Login","description":"Verify MFA code and complete login","operationId":"verify_mfa_login_user_verify_mfa_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OTPVerification"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/forgot-password":{"post":{"tags":["users"],"summary":"Forgot Password","description":"Request password reset","operationId":"forgot_password_user_forgot_password_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PasswordReset"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/reset-password":{"post":{"tags":["users"],"summary":"Reset Password","description":"Reset password with OTP","operationId":"reset_password_user_reset_password_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PasswordResetConfirm"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/profile":{"get":{"tags":["users"],"summary":"Get User Profile","description":"Get user profile information","operationId":"get_user_profile_user_profile_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]},"put":{"tags":["users"],"summary":"Update User Profile","description":"Update user profile information","operationId":"update_user_profile_user_profile_put","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Profile Data"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/regenerate-api-key":{"post":{"tags":["users"],"summary":"Regenerate Api Key","description":"Regenerate user API key","operationId":"regenerate_api_key_user_regenerate_api_key_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/usage":{"get":{"tags":["users"],"summary":"Get User Usage","description":"Get user's API usage statistics","operationId":"get_user_usage_user_usage_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/login-history":{"get":{"tags":["users"],"summary":"Get My Login History","description":"Get current user's login history","operationId":"get_my_login_history_user_login_history_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}},{"name":"offset","in":"query","required":false,"schema":{"type":"integer","default":0,"title":"Offset"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/subscribe":{"post":{"tags":["users"],"summary":"Subscribe To Database","description":"Subscribe to a database","operationId":"subscribe_to_database_user_subscribe_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DatabaseSubscriptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/subscriptions":{"get":{"tags":["users"],"summary":"Get User Subscriptions","description":"Get user's database subscriptions","operationId":"get_user_subscriptions_user_subscriptions_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/transactions":{"get":{"tags":["users"],"summary":"Get User Transactions","description":"Get user's transaction history","operationId":"get_user_transactions_user_transactions_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/mfa/enable":{"post":{"tags":["users"],"summary":"Enable Mfa","description":"Enable MFA (Multi-Factor Authentication) - Email-based","operationId":"enable_mfa_user_mfa_enable_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/mfa/disable":{"post":{"tags":["users"],"summary":"Disable Mfa","description":"Disable MFA (requires password confirmation)","operationId":"disable_mfa_user_mfa_disable_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Password Data"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/account":{"delete":{"tags":["users"],"summary":"Delete User Account","description":"Delete user account","operationId":"delete_user_account_user_account_delete","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Confirmation Data"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/admin/users":{"get":{"tags":["users"],"summary":"List All Users","description":"List all users (admin only)","operationId":"list_all_users_user_admin_users_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/user/admin/user/{user_id}":{"get":{"tags":["users"],"summary":"Get User Details","description":"Get detailed user information (admin only)","operationId":"get_user_details_user_admin_user__user_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"integer","title":"User Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/admin/user/{user_id}/credits":{"post":{"tags":["users"],"summary":"Manage User Credits","description":"Manage user credits (admin only)","operationId":"manage_user_credits_user_admin_user__user_id__credits_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"integer","title":"User Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"title":"Credits Data"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/user/admin/stats":{"get":{"tags":["users"],"summary":"Get Admin Statistics","description":"Get system statistics (admin only)","operationId":"get_admin_statistics_user_admin_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/guest/register":{"post":{"tags":["guests"],"summary":"Register Device","description":"Register device and create guest user with temporary API key (50 credits one-time per IP)","operationId":"register_device_guest_register_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DeviceRegistration"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/guest/status":{"get":{"tags":["guests"],"summary":"Guest Status","description":"Get guest user status and usage","operationId":"guest_status_guest_status_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/guest/extend":{"post":{"tags":["guests"],"summary":"Extend Guest Session","description":"Extend guest session if near expiry","operationId":"extend_guest_session_guest_extend_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/guest/usage":{"get":{"tags":["guests"],"summary":"Get Guest Usage","description":"Get guest user's API usage statistics","operationId":"get_guest_usage_guest_usage_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/guest/session":{"delete":{"tags":["guests"],"summary":"Delete Guest Session","description":"Delete guest session and all associated data","operationId":"delete_guest_session_guest_session_delete","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/guest/databases":{"get":{"tags":["guests"],"summary":"List Public Databases","description":"List public databases available to guests","operationId":"list_public_databases_guest_databases_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/guest/database/{database_name}/tables":{"get":{"tags":["guests"],"summary":"Get Database Tables Guest","description":"Get tables in database for guests","operationId":"get_database_tables_guest_guest_database__database_name__tables_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"database_name","in":"path","required":true,"schema":{"type":"string","title":"Database Name"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/guest/database/{database_name}/{table_name}/data":{"get":{"tags":["guests"],"summary":"Get Table Data Guest","description":"Get data from table for guests (limited)","operationId":"get_table_data_guest_guest_database__database_name___table_name__data_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"database_name","in":"path","required":true,"schema":{"type":"string","title":"Database Name"}},{"name":"table_name","in":"path","required":true,"schema":{"type":"string","title":"Table Name"}},{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":5,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/guest/admin/guests":{"get":{"tags":["guests"],"summary":"Get All Guests","description":"Get all guest users (admin only - would need admin auth in production)","operationId":"get_all_guests_guest_admin_guests_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/guest/admin/cleanup":{"post":{"tags":["guests"],"summary":"Manual Cleanup Expired Guests","description":"Manually trigger cleanup of expired guests (admin only)","operationId":"manual_cleanup_expired_guests_guest_admin_cleanup_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/guest/admin/stats":{"get":{"tags":["guests"],"summary":"Get Guest Statistics","description":"Get guest user statistics (admin only)","operationId":"get_guest_statistics_guest_admin_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/admin/system/config":{"get":{"tags":["admin"],"summary":"Get System Config","description":"Get all system configurations","operationId":"get_system_config_admin_system_config_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]},"post":{"tags":["admin"],"summary":"Create System Config","description":"Create system configuration","operationId":"create_system_config_admin_system_config_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SystemConfigRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/admin/system/config/{config_id}":{"put":{"tags":["admin"],"summary":"Update System Config","description":"Update system configuration","operationId":"update_system_config_admin_system_config__config_id__put","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"config_id","in":"path","required":true,"schema":{"type":"integer","title":"Config Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"title":"Config Data"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"delete":{"tags":["admin"],"summary":"Delete System Config","description":"Delete system configuration","operationId":"delete_system_config_admin_system_config__config_id__delete","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"config_id","in":"path","required":true,"schema":{"type":"integer","title":"Config Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/analytics/usage":{"get":{"tags":["admin"],"summary":"Get Usage Analytics","description":"Get detailed API usage analytics","operationId":"get_usage_analytics_admin_analytics_usage_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"days","in":"query","required":false,"schema":{"type":"integer","default":30,"title":"Days"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/analytics/performance":{"get":{"tags":["admin"],"summary":"Get Performance Analytics","description":"Get performance analytics","operationId":"get_performance_analytics_admin_analytics_performance_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"hours","in":"query","required":false,"schema":{"type":"integer","default":24,"title":"Hours"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/login-audit":{"get":{"tags":["admin"],"summary":"Get Login Audit","description":"Get login audit log for all users","operationId":"get_login_audit_admin_login_audit_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"User Id"}},{"name":"ip_address","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Ip Address"}},{"name":"success_only","in":"query","required":false,"schema":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Success Only"}},{"name":"days","in":"query","required":false,"schema":{"type":"integer","default":30,"title":"Days"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":100,"title":"Limit"}},{"name":"offset","in":"query","required":false,"schema":{"type":"integer","default":0,"title":"Offset"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/login-stats":{"get":{"tags":["admin"],"summary":"Get Login Stats","description":"Get login statistics","operationId":"get_login_stats_admin_login_stats_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"days","in":"query","required":false,"schema":{"type":"integer","default":30,"title":"Days"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/broadcast":{"post":{"tags":["admin"],"summary":"Broadcast Message","description":"Send broadcast message to users","operationId":"broadcast_message_admin_broadcast_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BroadcastMessageRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/admin/maintenance/cleanup":{"post":{"tags":["admin"],"summary":"Run Maintenance Cleanup","description":"Run system maintenance and cleanup","operationId":"run_maintenance_cleanup_admin_maintenance_cleanup_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/admin/logs":{"get":{"tags":["admin"],"summary":"Get System Logs","description":"Get system logs (mock implementation)","operationId":"get_system_logs_admin_logs_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"lines","in":"query","required":false,"schema":{"type":"integer","default":100,"title":"Lines"}},{"name":"level","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Level"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/export/users":{"get":{"tags":["admin"],"summary":"Export Users Data","description":"Export users data","operationId":"export_users_data_admin_export_users_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"format","in":"query","required":false,"schema":{"type":"string","default":"json","title":"Format"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/export/usage":{"get":{"tags":["admin"],"summary":"Export Usage Data","description":"Export API usage data","operationId":"export_usage_data_admin_export_usage_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"days","in":"query","required":false,"schema":{"type":"integer","default":30,"title":"Days"}},{"name":"format","in":"query","required":false,"schema":{"type":"string","default":"json","title":"Format"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/health":{"get":{"tags":["admin"],"summary":"Admin System Health","description":"Check admin system health","operationId":"admin_system_health_admin_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/admin/users/simple":{"get":{"tags":["admin"],"summary":"Get All Users Simple","description":"Get all users' names and emails (simple list)","operationId":"get_all_users_simple_admin_users_simple_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/admin/users":{"get":{"tags":["admin"],"summary":"List All Users","description":"List all users with filtering and pagination","operationId":"list_all_users_admin_users_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":50,"title":"Limit"}},{"name":"search","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Search"}},{"name":"account_type","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Account Type"}},{"name":"is_verified","in":"query","required":false,"schema":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Is Verified"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"post":{"tags":["admin"],"summary":"Create User","description":"Create new user (admin only)","operationId":"create_user_admin_users_post","security":[{"APIKeyHeader":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserCreateRequest"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/users/{user_id}":{"get":{"tags":["admin"],"summary":"Get User Details","description":"Get detailed user information","operationId":"get_user_details_admin_users__user_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"integer","title":"User Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"put":{"tags":["admin"],"summary":"Update User","description":"Update user information","operationId":"update_user_admin_users__user_id__put","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"integer","title":"User Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserUpdateRequest"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"delete":{"tags":["admin"],"summary":"Delete User","description":"Delete user account","operationId":"delete_user_admin_users__user_id__delete","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"integer","title":"User Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/users/{user_id}/credits":{"post":{"tags":["admin"],"summary":"Adjust User Credits","description":"Adjust user credit balance","operationId":"adjust_user_credits_admin_users__user_id__credits_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"integer","title":"User Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreditAdjustmentRequest"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/users/{user_id}/reset-password":{"post":{"tags":["admin"],"summary":"Reset User Password","description":"Reset user password","operationId":"reset_user_password_admin_users__user_id__reset_password_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"path","required":true,"schema":{"type":"integer","title":"User Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"title":"Password Data"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/guests":{"get":{"tags":["admin"],"summary":"List Guest Users","description":"List all guest users","operationId":"list_guest_users_admin_guests_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":50,"title":"Limit"}},{"name":"platform","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Platform"}},{"name":"is_active","in":"query","required":false,"schema":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Is Active"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/guests/cleanup":{"post":{"tags":["admin"],"summary":"Cleanup Expired Guests Endpoint","description":"Manually cleanup expired guests","operationId":"cleanup_expired_guests_endpoint_admin_guests_cleanup_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/admin/guests/{guest_id}":{"delete":{"tags":["admin"],"summary":"Delete Guest User","description":"Delete specific guest user","operationId":"delete_guest_user_admin_guests__guest_id__delete","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"guest_id","in":"path","required":true,"schema":{"type":"integer","title":"Guest Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/databases":{"get":{"tags":["admin"],"summary":"List Databases","description":"List all databases in registry","operationId":"list_databases_admin_databases_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]},"post":{"tags":["admin"],"summary":"Create Database","description":"Create new database registry entry","operationId":"create_database_admin_databases_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DatabaseCreateRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/admin/databases/{database_id}":{"put":{"tags":["admin"],"summary":"Update Database","description":"Update database registry entry","operationId":"update_database_admin_databases__database_id__put","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"database_id","in":"path","required":true,"schema":{"type":"integer","title":"Database Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"title":"Db Data"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/admin/system/stats":{"get":{"tags":["admin"],"summary":"Get System Statistics","description":"Get comprehensive system statistics","operationId":"get_system_statistics_admin_system_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/cashfree/plans":{"get":{"tags":["payments"],"summary":"Get Plans","description":"Get all available subscription plans (USD only)\nPublic endpoint - no authentication required","operationId":"get_plans_cashfree_plans_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/cashfree/config":{"get":{"tags":["payments"],"summary":"Get Config","description":"Get Cashfree configuration and supported currencies","operationId":"get_config_cashfree_config_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/cashfree/create-order":{"post":{"tags":["payments"],"summary":"Create Order","description":"Create Cashfree payment order for subscription\n\nReference: https://www.cashfree.com/docs/api-reference/payments/latest/orders/create","operationId":"create_order_cashfree_create_order_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateOrderRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/cashfree/order/{order_id}":{"get":{"tags":["payments"],"summary":"Get Order Status","description":"Get Cashfree order status\n\nReference: https://www.cashfree.com/docs/api-reference/payments/latest/orders/get","operationId":"get_order_status_cashfree_order__order_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"order_id","in":"path","required":true,"schema":{"type":"string","title":"Order Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/cashfree/payments/{order_id}":{"get":{"tags":["payments"],"summary":"Get Order Payments","description":"Get all payment attempts for an order\n\nReference: https://www.cashfree.com/docs/api-reference/payments/latest/payments/get-payments-for-order","operationId":"get_order_payments_cashfree_payments__order_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"order_id","in":"path","required":true,"schema":{"type":"string","title":"Order Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/cashfree/subscription":{"get":{"tags":["payments"],"summary":"Get User Subscription","description":"Get user's current subscription details","operationId":"get_user_subscription_cashfree_subscription_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/cashfree/payments":{"get":{"tags":["payments"],"summary":"Get User Payments","description":"Get user's payment history with pagination","operationId":"get_user_payments_cashfree_payments_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/cashfree/usage":{"get":{"tags":["payments"],"summary":"Get Credit Usage","description":"Get user's credit usage statistics","operationId":"get_credit_usage_cashfree_usage_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"days","in":"query","required":false,"schema":{"type":"integer","default":30,"title":"Days"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/cashfree/webhook":{"post":{"tags":["payments"],"summary":"Handle Webhook","description":"Handle Cashfree payment webhook events\n\nReference: https://www.cashfree.com/docs/payments/online/webhooks\n\nEvents:\n- PAYMENT_SUCCESS_WEBHOOK\n- PAYMENT_FAILED_WEBHOOK\n- PAYMENT_USER_DROPPED_WEBHOOK","operationId":"handle_webhook_cashfree_webhook_post","parameters":[{"name":"x-webhook-timestamp","in":"header","required":false,"schema":{"type":"string","title":"X-Webhook-Timestamp"}},{"name":"x-webhook-signature","in":"header","required":false,"schema":{"type":"string","title":"X-Webhook-Signature"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/payment/plans":{"get":{"tags":["payments"],"summary":"Get Plans","description":"Get all available subscription plans (USD only)\nPublic endpoint - no authentication required","operationId":"get_plans_payment_plans_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/payment/config":{"get":{"tags":["payments"],"summary":"Get Config","description":"Get Cashfree configuration and supported currencies","operationId":"get_config_payment_config_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/payment/create-order":{"post":{"tags":["payments"],"summary":"Create Order","description":"Create Cashfree payment order for subscription\n\nReference: https://www.cashfree.com/docs/api-reference/payments/latest/orders/create","operationId":"create_order_payment_create_order_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateOrderRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/payment/order/{order_id}":{"get":{"tags":["payments"],"summary":"Get Order Status","description":"Get Cashfree order status\n\nReference: https://www.cashfree.com/docs/api-reference/payments/latest/orders/get","operationId":"get_order_status_payment_order__order_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"order_id","in":"path","required":true,"schema":{"type":"string","title":"Order Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/payment/payments/{order_id}":{"get":{"tags":["payments"],"summary":"Get Order Payments","description":"Get all payment attempts for an order\n\nReference: https://www.cashfree.com/docs/api-reference/payments/latest/payments/get-payments-for-order","operationId":"get_order_payments_payment_payments__order_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"order_id","in":"path","required":true,"schema":{"type":"string","title":"Order Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/payment/subscription":{"get":{"tags":["payments"],"summary":"Get User Subscription","description":"Get user's current subscription details","operationId":"get_user_subscription_payment_subscription_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/payment/payments":{"get":{"tags":["payments"],"summary":"Get User Payments","description":"Get user's payment history with pagination","operationId":"get_user_payments_payment_payments_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/payment/usage":{"get":{"tags":["payments"],"summary":"Get Credit Usage","description":"Get user's credit usage statistics","operationId":"get_credit_usage_payment_usage_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"days","in":"query","required":false,"schema":{"type":"integer","default":30,"title":"Days"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/payment/webhook":{"post":{"tags":["payments"],"summary":"Handle Webhook","description":"Handle Cashfree payment webhook events\n\nReference: https://www.cashfree.com/docs/payments/online/webhooks\n\nEvents:\n- PAYMENT_SUCCESS_WEBHOOK\n- PAYMENT_FAILED_WEBHOOK\n- PAYMENT_USER_DROPPED_WEBHOOK","operationId":"handle_webhook_payment_webhook_post","parameters":[{"name":"x-webhook-timestamp","in":"header","required":false,"schema":{"type":"string","title":"X-Webhook-Timestamp"}},{"name":"x-webhook-signature","in":"header","required":false,"schema":{"type":"string","title":"X-Webhook-Signature"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/news/single-domain/{domain}":{"get":{"tags":["news"],"summary":"Get News From Single Domain","description":"Get news from a single domain with 0.10 credit cost","operationId":"get_news_from_single_domain_news_single_domain__domain__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"domain","in":"path","required":true,"schema":{"type":"string","title":"Domain"}},{"name":"category","in":"query","required":false,"schema":{"anyOf":[{"$ref":"#/components/schemas/NewsCategory"},{"type":"null"}],"title":"Category"}},{"name":"country","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Country"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":100,"minimum":1,"default":10,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/news/multiple-domains":{"post":{"tags":["news"],"summary":"Get News From Multiple Domains","description":"Get news from multiple domains with 0.25 credit cost","operationId":"get_news_from_multiple_domains_news_multiple_domains_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NewsRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/news/date-range":{"post":{"tags":["news"],"summary":"Get News By Date Range","description":"Get news within a specific date range with 0.15 credit cost","operationId":"get_news_by_date_range_news_date_range_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DateRangeRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/news/country/{country_code}":{"get":{"tags":["news"],"summary":"Get News By Country","description":"Get news from a specific country with 0.12 credit cost","operationId":"get_news_by_country_news_country__country_code__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"country_code","in":"path","required":true,"schema":{"type":"string","title":"Country Code"}},{"name":"category","in":"query","required":false,"schema":{"anyOf":[{"$ref":"#/components/schemas/NewsCategory"},{"type":"null"}],"title":"Category"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":100,"minimum":1,"default":10,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/news/topic-search":{"post":{"tags":["news"],"summary":"Search News By Topic","description":"Search news by keywords/topics with 0.12 credit cost","operationId":"search_news_by_topic_news_topic_search_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TopicSearchRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/news/categories":{"get":{"tags":["news"],"summary":"Get Available Categories","description":"Get list of available news categories (free endpoint)","operationId":"get_available_categories_news_categories_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/news/pricing":{"get":{"tags":["news"],"summary":"Get News Pricing","description":"Get credit costs for different news operations (free endpoint)","operationId":"get_news_pricing_news_pricing_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/news/stats":{"get":{"tags":["news"],"summary":"Get News Usage Stats","description":"Get user's news API usage statistics","operationId":"get_news_usage_stats_news_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/news/analyze":{"post":{"tags":["news"],"summary":"Analyze News Article","description":"AI-powered news article analysis\nExtracts article content and performs comprehensive financial analysis\nCost: 10 credits","operationId":"analyze_news_article_news_analyze_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NewsAnalysisRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/support/tickets":{"get":{"tags":["support"],"summary":"Get User Tickets","description":"Get user's support tickets","operationId":"get_user_tickets_support_tickets_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]},"post":{"tags":["support"],"summary":"Create Ticket","description":"Create new support ticket (requires authentication)","operationId":"create_ticket_support_tickets_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TicketCreate"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/support/tickets/{ticket_id}":{"get":{"tags":["support"],"summary":"Get Ticket Details","description":"Get detailed ticket information with messages","operationId":"get_ticket_details_support_tickets__ticket_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"ticket_id","in":"path","required":true,"schema":{"type":"integer","title":"Ticket Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"put":{"tags":["support"],"summary":"Update Ticket","description":"Update ticket status (user can only close/reopen)","operationId":"update_ticket_support_tickets__ticket_id__put","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"ticket_id","in":"path","required":true,"schema":{"type":"integer","title":"Ticket Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TicketUpdate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/support/tickets/{ticket_id}/messages":{"post":{"tags":["support"],"summary":"Add Ticket Message","description":"Add message to support ticket","operationId":"add_ticket_message_support_tickets__ticket_id__messages_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"ticket_id","in":"path","required":true,"schema":{"type":"integer","title":"Ticket Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MessageCreate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/support/contact":{"post":{"tags":["support"],"summary":"Submit Contact Form","description":"Submit contact form (public endpoint)","operationId":"submit_contact_form_support_contact_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContactFormCreate"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/support/feedback":{"post":{"tags":["support"],"summary":"Submit Feedback","description":"Submit feedback (public endpoint)","operationId":"submit_feedback_support_feedback_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FeedbackCreate"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/support/categories":{"get":{"tags":["support"],"summary":"Get Support Categories","description":"Get available support categories (public endpoint)","operationId":"get_support_categories_support_categories_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/support/stats":{"get":{"tags":["support"],"summary":"Get Support Stats","description":"Get user's support statistics","operationId":"get_support_stats_support_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/support/newsletter/subscribe":{"post":{"tags":["support"],"summary":"Subscribe To Newsletter","description":"Subscribe to Fincept newsletter (public endpoint - no authentication required)","operationId":"subscribe_to_newsletter_support_newsletter_subscribe_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NewsletterSubscribe"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/support/newsletter/unsubscribe":{"post":{"tags":["support"],"summary":"Unsubscribe From Newsletter","description":"Unsubscribe from newsletter (public endpoint)","operationId":"unsubscribe_from_newsletter_support_newsletter_unsubscribe_post","parameters":[{"name":"email","in":"query","required":true,"schema":{"type":"string","format":"email","title":"Email"}},{"name":"token","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Token"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/support/newsletter/status":{"get":{"tags":["support"],"summary":"Check Newsletter Status","description":"Check newsletter subscription status (public endpoint)","operationId":"check_newsletter_status_support_newsletter_status_get","parameters":[{"name":"email","in":"query","required":true,"schema":{"type":"string","format":"email","title":"Email"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/sessions":{"get":{"tags":["chat"],"summary":"Get Chat Sessions","description":"Get user's chat sessions (both registered and guest users)","operationId":"get_chat_sessions_chat_sessions_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":50,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"post":{"tags":["chat"],"summary":"Create Chat Session","description":"Create new chat session","operationId":"create_chat_session_chat_sessions_post","security":[{"APIKeyHeader":[]}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatSessionCreate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/sessions/bulk-delete":{"delete":{"tags":["chat"],"summary":"Bulk Delete Sessions","description":"Bulk delete chat sessions (registered users only)","operationId":"bulk_delete_sessions_chat_sessions_bulk_delete_delete","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Session Data"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/chat/sessions/{session_uuid}":{"get":{"tags":["chat"],"summary":"Get Chat Session","description":"Get specific chat session with messages","operationId":"get_chat_session_chat_sessions__session_uuid__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"session_uuid","in":"path","required":true,"schema":{"type":"string","title":"Session Uuid"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"delete":{"tags":["chat"],"summary":"Delete Chat Session","description":"Delete chat session and all messages","operationId":"delete_chat_session_chat_sessions__session_uuid__delete","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"session_uuid","in":"path","required":true,"schema":{"type":"string","title":"Session Uuid"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/sessions/{session_uuid}/messages":{"post":{"tags":["chat"],"summary":"Send Chat Message","description":"Send message to chat session and get AI response","operationId":"send_chat_message_chat_sessions__session_uuid__messages_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"session_uuid","in":"path","required":true,"schema":{"type":"string","title":"Session Uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatMessageCreate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/sessions/{session_uuid}/activate":{"put":{"tags":["chat"],"summary":"Activate Chat Session","description":"Activate a chat session (deactivates others)","operationId":"activate_chat_session_chat_sessions__session_uuid__activate_put","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"session_uuid","in":"path","required":true,"schema":{"type":"string","title":"Session Uuid"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/sessions/{session_uuid}/title":{"put":{"tags":["chat"],"summary":"Update Chat Title","description":"Update chat session title","operationId":"update_chat_title_chat_sessions__session_uuid__title_put","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"session_uuid","in":"path","required":true,"schema":{"type":"string","title":"Session Uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"title":"Title Data"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/stats":{"get":{"tags":["chat"],"summary":"Get Chat Statistics","description":"Get chat statistics for current user","operationId":"get_chat_statistics_chat_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/chat/export":{"post":{"tags":["chat"],"summary":"Export Chat Sessions","description":"Export chat sessions to JSON (registered users only)","operationId":"export_chat_sessions_chat_export_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Export Data"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/chat/admin/statistics":{"get":{"tags":["chat"],"summary":"Get Admin Chat Statistics","description":"Get system-wide chat statistics (admin only)","operationId":"get_admin_chat_statistics_chat_admin_statistics_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/chat/admin/sessions":{"get":{"tags":["chat"],"summary":"Get Admin Chat Sessions","description":"Get all chat sessions with pagination (admin only)","operationId":"get_admin_chat_sessions_chat_admin_sessions_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":50,"title":"Limit"}},{"name":"user_type","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"User Type"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/quick-chat":{"post":{"tags":["chat"],"summary":"Quick Chat","description":"Quick chat without session management (for testing)","operationId":"quick_chat_chat_quick_chat_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatMessageCreate"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/chat/search":{"get":{"tags":["chat"],"summary":"Search Chat Messages","description":"Search chat messages","operationId":"search_chat_messages_chat_search_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"query","in":"query","required":true,"schema":{"type":"string","title":"Query"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/chat/templates":{"get":{"tags":["chat"],"summary":"Get Chat Templates","description":"Get predefined chat templates (registered users only)","operationId":"get_chat_templates_chat_templates_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/chat/templates/{template_id}/start":{"post":{"tags":["chat"],"summary":"Start Template Session","description":"Start a chat session from template (registered users only)","operationId":"start_template_session_chat_templates__template_id__start_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"template_id","in":"path","required":true,"schema":{"type":"string","title":"Template Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/categories":{"get":{"tags":["forum"],"summary":"Get Forum Categories","description":"Get all forum categories (accessible to both users and guests)","operationId":"get_forum_categories_forum_categories_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/forum/categories/{category_id}/posts":{"get":{"tags":["forum"],"summary":"Get Category Posts","description":"Get posts in a specific category","operationId":"get_category_posts_forum_categories__category_id__posts_get","parameters":[{"name":"category_id","in":"path","required":true,"schema":{"type":"integer","title":"Category Id"}},{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":50,"minimum":1,"default":20,"title":"Limit"}},{"name":"sort_by","in":"query","required":false,"schema":{"type":"string","pattern":"^(latest|popular|views|replies)$","default":"latest","title":"Sort By"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"post":{"tags":["forum"],"summary":"Create Forum Post","description":"Create new forum post (registered users only)","operationId":"create_forum_post_forum_categories__category_id__posts_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"category_id","in":"path","required":true,"schema":{"type":"integer","title":"Category Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForumPostCreate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/posts/trending":{"get":{"tags":["forum"],"summary":"Get Trending Posts","description":"Get trending forum posts","operationId":"get_trending_posts_forum_posts_trending_get","parameters":[{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":50,"minimum":1,"default":10,"title":"Limit"}},{"name":"timeframe","in":"query","required":false,"schema":{"type":"string","pattern":"^(day|week|month)$","default":"week","title":"Timeframe"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/posts/{post_uuid}":{"get":{"tags":["forum"],"summary":"Get Forum Post","description":"Get specific forum post with comments","operationId":"get_forum_post_forum_posts__post_uuid__get","parameters":[{"name":"post_uuid","in":"path","required":true,"schema":{"type":"string","title":"Post Uuid"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/posts/{post_uuid}/comments":{"post":{"tags":["forum"],"summary":"Create Forum Comment","description":"Create comment on forum post (registered users only)","operationId":"create_forum_comment_forum_posts__post_uuid__comments_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"post_uuid","in":"path","required":true,"schema":{"type":"string","title":"Post Uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForumCommentCreate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/posts/{post_uuid}/vote":{"post":{"tags":["forum"],"summary":"Vote On Post","description":"Vote on forum post (registered users only)","operationId":"vote_on_post_forum_posts__post_uuid__vote_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"post_uuid","in":"path","required":true,"schema":{"type":"string","title":"Post Uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForumVoteCreate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/comments/{comment_uuid}/vote":{"post":{"tags":["forum"],"summary":"Vote On Comment","description":"Vote on forum comment (registered users only)","operationId":"vote_on_comment_forum_comments__comment_uuid__vote_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"comment_uuid","in":"path","required":true,"schema":{"type":"string","title":"Comment Uuid"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForumVoteCreate"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/search":{"get":{"tags":["forum"],"summary":"Search Forum","description":"Search forum posts and comments","operationId":"search_forum_forum_search_get","parameters":[{"name":"q","in":"query","required":true,"schema":{"type":"string","minLength":2,"maxLength":100,"title":"Q"}},{"name":"category_id","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Category Id"}},{"name":"post_type","in":"query","required":false,"schema":{"type":"string","pattern":"^(all|posts|comments)$","default":"all","title":"Post Type"}},{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":50,"minimum":1,"default":20,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/stats":{"get":{"tags":["forum"],"summary":"Get Forum Statistics","description":"Get forum statistics","operationId":"get_forum_statistics_forum_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/forum/profile/{username}":{"get":{"tags":["forum"],"summary":"Get Forum User Profile","description":"Get forum user profile (registered users only)","operationId":"get_forum_user_profile_forum_profile__username__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"username","in":"path","required":true,"schema":{"type":"string","title":"Username"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/forum/profile":{"get":{"tags":["forum"],"summary":"Get My Forum Profile","description":"Get current user's forum profile","operationId":"get_my_forum_profile_forum_profile_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]},"put":{"tags":["forum"],"summary":"Update Forum Profile","description":"Update current user's forum profile","operationId":"update_forum_profile_forum_profile_put","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForumProfileUpdate"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/forum/admin/categories":{"post":{"tags":["forum"],"summary":"Create Forum Category","description":"Create new forum category (admin only)","operationId":"create_forum_category_forum_admin_categories_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Category Data"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/forum/admin/statistics":{"get":{"tags":["forum"],"summary":"Get Admin Forum Statistics","description":"Get detailed forum statistics (admin only)","operationId":"get_admin_forum_statistics_forum_admin_statistics_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/marketplace/upload":{"post":{"tags":["marketplace"],"summary":"Upload Dataset","description":"Upload dataset to marketplace with pricing options","operationId":"upload_dataset_marketplace_upload_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"metadata","in":"query","required":true,"schema":{"type":"string","title":"Metadata"}}],"requestBody":{"required":true,"content":{"multipart/form-data":{"schema":{"$ref":"#/components/schemas/Body_upload_dataset_marketplace_upload_post"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/datasets":{"get":{"tags":["marketplace"],"summary":"Browse Datasets","description":"Browse marketplace datasets (registered users only)","operationId":"browse_datasets_marketplace_datasets_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"category","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Category"}},{"name":"search","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Search"}},{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}},{"name":"sort_by","in":"query","required":false,"schema":{"type":"string","default":"uploaded_at","title":"Sort By"}},{"name":"sort_order","in":"query","required":false,"schema":{"type":"string","default":"desc","title":"Sort Order"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/my-purchases":{"get":{"tags":["marketplace"],"summary":"Get User Purchases","description":"Get user's dataset purchases","operationId":"get_user_purchases_marketplace_my_purchases_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/my-datasets":{"get":{"tags":["marketplace"],"summary":"Get My Datasets","description":"Get user's uploaded datasets with status filtering","operationId":"get_my_datasets_marketplace_my_datasets_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"page","in":"query","required":false,"schema":{"type":"integer","default":1,"title":"Page"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}},{"name":"status","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Status"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/datasets/{dataset_id}":{"patch":{"tags":["marketplace"],"summary":"Update Dataset","description":"Update dataset metadata (only owner can update, only if pending/rejected)","operationId":"update_dataset_marketplace_datasets__dataset_id__patch","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"integer","title":"Dataset Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"title":"Update Data"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"delete":{"tags":["marketplace"],"summary":"Delete Dataset","description":"Delete dataset (only owner can delete, only if not purchased by others)","operationId":"delete_dataset_marketplace_datasets__dataset_id__delete","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"integer","title":"Dataset Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}},"get":{"tags":["marketplace"],"summary":"Get Dataset Details","description":"Get detailed dataset information","operationId":"get_dataset_details_marketplace_datasets__dataset_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"integer","title":"Dataset Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/datasets/{dataset_id}/purchase":{"post":{"tags":["marketplace"],"summary":"Purchase Dataset","description":"Purchase dataset (free - just registers access)","operationId":"purchase_dataset_marketplace_datasets__dataset_id__purchase_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"integer","title":"Dataset Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/datasets/{dataset_id}/download":{"post":{"tags":["marketplace"],"summary":"Download Dataset","description":"Download dataset file (free for all registered users)","operationId":"download_dataset_marketplace_datasets__dataset_id__download_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"integer","title":"Dataset Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/my-datasets/analytics":{"get":{"tags":["marketplace"],"summary":"Get Dataset Analytics","description":"Get analytics for user's uploaded datasets","operationId":"get_dataset_analytics_marketplace_my_datasets_analytics_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/marketplace/admin/stats":{"get":{"tags":["marketplace"],"summary":"Get Marketplace Stats","description":"Get comprehensive marketplace statistics","operationId":"get_marketplace_stats_marketplace_admin_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/marketplace/admin/pending-datasets":{"get":{"tags":["marketplace"],"summary":"Get Pending Datasets","description":"Get all pending datasets for approval","operationId":"get_pending_datasets_marketplace_admin_pending_datasets_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/marketplace/admin/datasets/{dataset_id}/approve":{"post":{"tags":["marketplace"],"summary":"Approve Dataset","description":"Approve a pending dataset","operationId":"approve_dataset_marketplace_admin_datasets__dataset_id__approve_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"integer","title":"Dataset Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marketplace/admin/datasets/{dataset_id}/reject":{"post":{"tags":["marketplace"],"summary":"Reject Dataset","description":"Reject a pending dataset","operationId":"reject_dataset_marketplace_admin_datasets__dataset_id__reject_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"dataset_id","in":"path","required":true,"schema":{"type":"integer","title":"Dataset Id"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":true,"title":"Rejection Data"}}}},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/research/papers/search":{"get":{"tags":["research","research"],"summary":"Search Papers","description":"Search academic papers from arXiv with pagination\nCost: 1 credit per 10 papers (per page)\nRate limit: 1 request per second\n\nReturns 10 papers per page. Each page costs 1 credit.\nExample: page=1 returns papers 1-10, page=2 returns papers 11-20","operationId":"search_papers_research_papers_search_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"query","in":"query","required":true,"schema":{"type":"string","description":"Search query (keywords separated by space)","title":"Query"},"description":"Search query (keywords separated by space)"},{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"description":"Page number (1-indexed)","default":1,"title":"Page"},"description":"Page number (1-indexed)"}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/research/papers/trending":{"get":{"tags":["research","research"],"summary":"Get Trending Papers","description":"Get trending recent papers by topic with pagination\nCost: 1 credit per 10 papers (per page)\nRate limit: 1 request per second","operationId":"get_trending_papers_research_papers_trending_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"topic","in":"query","required":true,"schema":{"type":"string","description":"Research topic","title":"Topic"},"description":"Research topic"},{"name":"days","in":"query","required":false,"schema":{"type":"integer","maximum":365,"minimum":7,"description":"Days to look back","default":30,"title":"Days"},"description":"Days to look back"},{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"description":"Page number","default":1,"title":"Page"},"description":"Page number"}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/research/content-reader":{"post":{"tags":["research","research"],"summary":"Content Reader","description":"Extract and read content from web documents\nCost: 0.25 credits per request\nRate limit: 1 request per second","operationId":"content_reader_research_content_reader_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ContentReaderRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/research/web-search":{"post":{"tags":["research","research"],"summary":"Web Search","description":"Search the web for financial and market intelligence","operationId":"web_search_research_web_search_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/WebSearchRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/research/chat":{"post":{"tags":["research","research"],"summary":"Fincept Chat","description":"Official Fincept AI Chat","operationId":"fincept_chat_research_chat_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChatRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/research/grokipedia":{"post":{"tags":["research","research"],"summary":"Grokipedia Fetch","description":"Fetch knowledge articles from Grokipedia (xAI's knowledge base)\n\nThis endpoint retrieves comprehensive articles from Grokipedia, covering various topics\nwith detailed content, references, and citations.\n\nCost: 0.25 credits per request\nRate limit: 1 request per second\n\nParameters:\n- slug: Article slug/identifier (e.g., \"artificial-intelligence\", \"climate-change\")\n- extract_refs: Extract and include references (default: true)\n- truncate: Limit content to N characters (optional)\n- citations: Include citation formatting (default: false)\n\nExample slugs:\n- \"bitcoin\"\n- \"machine-learning\"\n- \"quantum-computing\"\n- \"financial-markets\"","operationId":"grokipedia_fetch_research_grokipedia_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GrokipediaRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/research/pdf/extract":{"post":{"tags":["research","research"],"summary":"Extract Pdf Text","description":"Extract text from uploaded PDF file\nDynamic Pricing:\n- 1-10 pages: 1 credit\n- 11-50 pages: 2 credits\n- 51-100 pages: 3 credits\n- 101-200 pages: 5 credits\n- 201+ pages: 10 credits\nRate limit: 1 request per second\nMax file size: 10MB","operationId":"extract_pdf_text_research_pdf_extract_post","requestBody":{"content":{"multipart/form-data":{"schema":{"$ref":"#/components/schemas/Body_extract_pdf_text_research_pdf_extract_post"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/research/health":{"get":{"tags":["research","research"],"summary":"Research Health","description":"Health check for Fincept research module","operationId":"research_health_research_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/research/llm":{"post":{"tags":["research","research"],"summary":"General Llm Inference","description":"General-purpose LLM endpoint for running agents, processing data, and AI tasks.\n\nThis endpoint allows you to use Fincept API as your LLM provider for:\n- Running AI agents\n- Data processing and analysis\n- Code generation\n- Text summarization\n- Question answering\n- Any other LLM-based tasks\n\nCost: 5 credits per successful response\nNote: Credits are ONLY deducted on successful LLM response. If the LLM fails, no credits are charged.\n\nRate limit: 1 request per second","operationId":"general_llm_inference_research_llm_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LLMRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/research/visual-analysis":{"post":{"tags":["research","research"],"summary":"Satellite Visual Analysis","description":"Multimodal Visual Analysis using Fincept Vision AI for satellite imagery and visual understanding.\n\nThis endpoint enables advanced visual analysis capabilities including:\n- Satellite image analysis and interpretation\n- Geographic feature detection and classification\n- Land use and land cover analysis\n- Urban planning and infrastructure mapping\n- Environmental monitoring\n- Agricultural assessment\n- Disaster response and damage assessment\n- Object detection and counting in images\n- Visual question answering\n- Image description and captioning\n\nModel: Fincept Vision AI (Multimodal Vision-Language Model)\n- Native multimodal understanding\n- 128K context window\n- Advanced visual reasoning\n- Function calling capabilities\n- High-resolution image processing\n\nCost: 10 credits per successful response\nNote: Credits are ONLY deducted on successful analysis. If the model fails, no credits are charged.\n\nRate limit: 1 request per second\n\nExample Use Cases:\n- \"Identify all buildings in this satellite image\"\n- \"What type of land use is shown in this area?\"\n- \"Detect any changes or anomalies in this image\"\n- \"Count the number of vehicles in this parking lot\"\n- \"Analyze the vegetation health in this agricultural field\"","operationId":"satellite_visual_analysis_research_visual_analysis_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VisualAnalysisRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/research/news-events":{"get":{"tags":["research","research"],"summary":"Get News Events","description":"Highly configurable news events endpoint with independent filter parameters\n\n**Cost:** 3 credits per request\n\n**Features:**\n- Filter by country, city/cities, and/or event category (all work independently)\n- Get unique lists: cities, countries, or categories\n- All filters work in any combination\n- Pagination support (30 events per page by default)\n- Returns all 10 columns of data\n\n**Filter Parameters (all optional and independent):**\n- country: Filter by country name (e.g., \"India\")\n- city: Single city filter (e.g., \"Mumbai\")\n- cities: Multiple cities filter (comma-separated, e.g., \"Mumbai,Delhi,Bangalore\")\n- event_category: Filter by category\n\n**Unique List Parameters (mutually exclusive):**\n- get_unique_cities: Return unique cities list (default: false)\n- get_unique_countries: Return unique countries list (default: false)\n- get_unique_categories: Return unique event categories list (default: false)\n\n**Pagination Parameters:**\n- page: Page number (default: 1)\n- limit: Events per page (default: 30, max: 100)\n\n**Examples:**\n- Get events: No unique parameters\n- Get all cities in India: country=India&get_unique_cities=true\n- Get all countries with protests: event_category=protests&get_unique_countries=true\n- Get categories for Mumbai: city=Mumbai&get_unique_categories=true\n\n**Returns:** Events with pagination OR unique list (cities/countries/categories)","operationId":"get_news_events_research_news_events_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"country","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"Filter by country (e.g., 'India', 'USA')","title":"Country"},"description":"Filter by country (e.g., 'India', 'USA')"},{"name":"city","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"Filter by single city (e.g., 'Mumbai')","title":"City"},"description":"Filter by single city (e.g., 'Mumbai')"},{"name":"cities","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"Filter by multiple cities (comma-separated, e.g., 'Mumbai,Delhi,Bangalore')","title":"Cities"},"description":"Filter by multiple cities (comma-separated, e.g., 'Mumbai,Delhi,Bangalore')"},{"name":"event_category","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"Filter by event category","title":"Event Category"},"description":"Filter by event category"},{"name":"get_unique_cities","in":"query","required":false,"schema":{"type":"boolean","description":"Return list of unique cities instead of events","default":false,"title":"Get Unique Cities"},"description":"Return list of unique cities instead of events"},{"name":"get_unique_countries","in":"query","required":false,"schema":{"type":"boolean","description":"Return list of unique countries instead of events","default":false,"title":"Get Unique Countries"},"description":"Return list of unique countries instead of events"},{"name":"get_unique_categories","in":"query","required":false,"schema":{"type":"boolean","description":"Return list of unique event categories instead of events","default":false,"title":"Get Unique Categories"},"description":"Return list of unique event categories instead of events"},{"name":"page","in":"query","required":false,"schema":{"type":"integer","minimum":1,"description":"Page number (starts from 1)","default":1,"title":"Page"},"description":"Page number (starts from 1)"},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":100,"minimum":1,"description":"Events per page (max 100)","default":30,"title":"Limit"},"description":"Events per page (max 100)"}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/marine/vessel/position":{"post":{"tags":["marine","marine"],"summary":"Get Vessel Position","description":"Get last known position of a vessel by IMO\nCost: 1 credit per request","operationId":"get_vessel_position_marine_vessel_position_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VesselPositionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/marine/vessel/history":{"post":{"tags":["marine","marine"],"summary":"Get Vessel History","description":"Get complete historical location data for a vessel\nCost: 5 credits per request","operationId":"get_vessel_history_marine_vessel_history_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VesselPositionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/marine/vessel/multi":{"post":{"tags":["marine","marine"],"summary":"Get Multi Vessel Positions","description":"Get last known positions for multiple vessels (max 50)\nCost: 3 credits per request","operationId":"get_multi_vessel_positions_marine_vessel_multi_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MultiVesselRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/marine/vessel/area-search":{"post":{"tags":["marine","marine"],"summary":"Search Vessels In Area","description":"Search for all vessels in a defined geographic area\nCost: 8 credits per request\n\nParameters:\n- min_lat, max_lat, min_lng, max_lng: Geographic boundary\n- days_ago (optional): Get historical data from N days ago (0-365)\n If not provided or 0, returns current/latest positions","operationId":"search_vessels_in_area_marine_vessel_area_search_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AreaSearchRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/marine/health":{"get":{"tags":["marine","marine"],"summary":"Marine Health","description":"Health check for marine module","operationId":"marine_health_marine_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/aircraft/health":{"get":{"tags":["aircraft","aircraft"],"summary":"Aircraft Health","description":"Health check for aircraft tracking module","operationId":"aircraft_health_aircraft_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/aircraft/track":{"post":{"tags":["aircraft","aircraft"],"summary":"Track Aircraft","description":"Track aircraft by ID using PlaneFinder API with Selenium\nCost: 0.25 credits per successful request\nRate limit: 1 request per second","operationId":"track_aircraft_aircraft_track_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AircraftRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/aircraft/{aircraft_id}":{"get":{"tags":["aircraft","aircraft"],"summary":"Get Aircraft Endpoint","description":"Get aircraft data by ID (raw format)\nSimple endpoint without authentication for testing","operationId":"get_aircraft_endpoint_aircraft__aircraft_id__get","parameters":[{"name":"aircraft_id","in":"path","required":true,"schema":{"type":"string","title":"Aircraft Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/aircraft/{aircraft_id}/raw":{"get":{"tags":["aircraft","aircraft"],"summary":"Get Aircraft Raw","description":"Get raw aircraft data by ID\nSimple endpoint without authentication for testing","operationId":"get_aircraft_raw_aircraft__aircraft_id__raw_get","parameters":[{"name":"aircraft_id","in":"path","required":true,"schema":{"type":"string","title":"Aircraft Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/health":{"get":{"tags":["twitter","twitter"],"summary":"Twitter Health","description":"Health check for Twitter integration module","operationId":"twitter_health_twitter_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/twitter/countries":{"get":{"tags":["twitter","twitter"],"summary":"Get Available Countries","description":"Get list of all available countries for Twitter trends\nNo authentication required","operationId":"get_available_countries_twitter_countries_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/twitter/trends":{"get":{"tags":["twitter","twitter"],"summary":"Get Twitter Trends","description":"Get current Twitter trending topics for a country\n\nParameters:\n- country: Country name (optional, default: \"worldwide\")\n Examples: \"india\", \"usa\", \"uk\", \"japan\", \"brazil\", \"france\", etc.\n Use /twitter/countries to see all available countries\n\nCost: 0.5 credits per request\nRate limit: 1 request per 2 seconds","operationId":"get_twitter_trends_twitter_trends_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"country","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Country"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/user/tweets":{"get":{"tags":["twitter","twitter"],"summary":"Get User Tweets","description":"Get user's latest tweets (up to 20 per request)\n\nParameters:\n- username: Twitter screen name (e.g., \"elonmusk\")\n- user_id: Twitter user ID (recommended, more stable than username)\n- cursor: Pagination cursor for next page\n\nNote: Either username OR user_id is required. If both provided, user_id takes priority.\n\nCost: 1.0 credit per request (returns up to 20 tweets)\nRate limit: 1 request per 2 seconds\n\nReturns tweets sorted by created_at with pagination support.","operationId":"get_user_tweets_twitter_user_tweets_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"username","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Username"}},{"name":"user_id","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"User Id"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/tweets":{"get":{"tags":["twitter","twitter"],"summary":"Get Tweets By Ids","description":"Get tweets by their IDs\n\nParameters:\n- tweet_ids: Comma-separated tweet IDs (e.g., \"1846987139428634858,1866332309399781537\")\n\nCost: 0.5 credits per request\nRate limit: 1 request per 2 seconds\n\nReturns tweet data for the specified IDs.","operationId":"get_tweets_by_ids_twitter_tweets_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"tweet_ids","in":"query","required":true,"schema":{"type":"string","title":"Tweet Ids"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/tweet/replies":{"get":{"tags":["twitter","twitter"],"summary":"Get Tweet Replies","description":"Get replies to a tweet (up to 20 per request)\n\nParameters:\n- tweet_id: The tweet ID to get replies for (required)\n- since_time: On or after specified unix timestamp in seconds (optional)\n- until_time: Before specified unix timestamp in seconds (optional)\n- cursor: Pagination cursor for next page (optional)\n\nNote: tweet_id must be an original tweet (not a reply to another tweet)\n and should be the first tweet in a thread.\n\nCost: 1.0 credit per request (returns up to 20 replies)\nRate limit: 1 request per 2 seconds\n\nReturns replies sorted by reply time (descending) with pagination support.","operationId":"get_tweet_replies_twitter_tweet_replies_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"tweet_id","in":"query","required":true,"schema":{"type":"string","title":"Tweet Id"}},{"name":"since_time","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Since Time"}},{"name":"until_time","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Until Time"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/tweet/quotes":{"get":{"tags":["twitter","twitter"],"summary":"Get Tweet Quotes","description":"Get quote tweets of a tweet (20 quotes per request)\n\nParameters:\n- tweet_id: The tweet ID to get quotes for (required)\n- since_time: On or after specified unix timestamp in seconds (optional)\n- until_time: Before specified unix timestamp in seconds (optional)\n- include_replies: Include replies in results (default: true)\n- cursor: Pagination cursor for next page (optional)\n\nCost: 1.0 credit per request (returns 20 quotes)\nRate limit: 1 request per 2 seconds\n\nReturns quote tweets sorted by quote time (descending) with pagination support.","operationId":"get_tweet_quotes_twitter_tweet_quotes_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"tweet_id","in":"query","required":true,"schema":{"type":"string","title":"Tweet Id"}},{"name":"since_time","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Since Time"}},{"name":"until_time","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Until Time"}},{"name":"include_replies","in":"query","required":false,"schema":{"type":"boolean","default":true,"title":"Include Replies"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/tweet/retweeters":{"get":{"tags":["twitter","twitter"],"summary":"Get Tweet Retweeters","description":"Get users who retweeted a tweet (~100 users per request)\n\nParameters:\n- tweet_id: The tweet ID to get retweeters for (required)\n- cursor: Pagination cursor for next page (optional)\n\nCost: 1.5 credits per request (returns ~100 users)\nRate limit: 1 request per 2 seconds\n\nReturns users who retweeted the tweet, sorted by retweet time (descending) with pagination support.","operationId":"get_tweet_retweeters_twitter_tweet_retweeters_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"tweet_id","in":"query","required":true,"schema":{"type":"string","title":"Tweet Id"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/article":{"get":{"tags":["twitter","twitter"],"summary":"Get Twitter Article","description":"Get full article content from a Twitter article tweet\n\n PREMIUM ENDPOINT - Costs 100 credits per article!\n\nParameters:\n- tweet_id: The tweet ID of the article (required)\n\nCost: 100 credits per article (PREMIUM)\nRate limit: 1 request per 2 seconds\n\nReturns full article content including title, preview, cover image, and full text.\nThis is a premium endpoint due to the comprehensive article data provided.","operationId":"get_twitter_article_twitter_article_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"tweet_id","in":"query","required":true,"schema":{"type":"string","title":"Tweet Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/tweet/thread_context":{"get":{"tags":["twitter","twitter"],"summary":"Get Tweet Thread Context","description":"Get the full thread context of a tweet\n\nThis endpoint retrieves the entire conversation thread containing the specified tweet.\nFor example, if a thread has tweets t1 -> t2 -> t3 -> t4, t5, t6 (all replying to t3),\nproviding t3 will return the entire thread: t1, t2, t3, t4, t5, t6.\n\nParameters:\n- tweet_id: The tweet ID (can be a reply or original tweet)\n- cursor: Pagination cursor for next page (optional)\n\nNote: Pagination size varies due to Twitter API limitations.\nThe number of tweets per page is not fixed.\n\nCost: 2.0 credits per request (variable tweets per page)\nRate limit: 1 request per 2 seconds\n\nReturns the full thread context with pagination support.","operationId":"get_tweet_thread_context_twitter_tweet_thread_context_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"tweet_id","in":"query","required":true,"schema":{"type":"string","title":"Tweet Id"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/tweet/advanced_search":{"get":{"tags":["twitter","twitter"],"summary":"Advanced Tweet Search","description":"Advanced search for tweets with powerful query syntax\n\nSupports advanced Twitter search operators for precise tweet discovery.\n\nParameters:\n- query: Search query with advanced operators (required)\n Examples:\n - \"AI\" OR \"Twitter\" from:elonmusk since:2021-12-31_23:59:59_UTC\n - \"#bitcoin\" min_faves:100\n - \"python\" filter:verified\n See: https://github.com/igorbrigadir/twitter-advanced-search\n\n- query_type: \"Latest\" (chronological) or \"Top\" (most relevant)\n- cursor: Pagination cursor for next page (optional)\n\nCost: 2.5 credits per request (up to 20 tweets)\nRate limit: 1 request per 2 seconds\n\nReturns search results with pagination support.","operationId":"advanced_tweet_search_twitter_tweet_advanced_search_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"query","in":"query","required":true,"schema":{"type":"string","title":"Query"}},{"name":"query_type","in":"query","required":false,"schema":{"type":"string","default":"Latest","title":"Query Type"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/user/search":{"get":{"tags":["twitter","twitter"],"summary":"Search Users","description":"Search for Twitter users by keyword\n\nParameters:\n- query: Search keyword (required)\n- cursor: Pagination cursor for next page (optional)\n\nCost: 1.5 credits per request\nRate limit: 1 request per 2 seconds\n\nReturns matching users with pagination support.","operationId":"search_users_twitter_user_search_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"query","in":"query","required":true,"schema":{"type":"string","title":"Query"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/twitter/user/mentions":{"get":{"tags":["twitter","twitter"],"summary":"Get User Mentions","description":"Get tweet mentions by user screen name\nEach page returns exactly 20 mentions\nOrder by mention time descending\nCost: 1.0 credit per request\nRate limit: 1 request per 2 seconds","operationId":"get_user_mentions_twitter_user_mentions_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"userName","in":"query","required":true,"schema":{"type":"string","title":"Username"}},{"name":"sinceTime","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Sincetime"}},{"name":"untilTime","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Untiltime"}},{"name":"cursor","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Cursor"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/analytics/my-login-history":{"get":{"tags":["analytics"],"summary":"Get My Login History","description":"Get current user's login history (User only sees their own)","operationId":"get_my_login_history_analytics_my_login_history_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}},{"name":"offset","in":"query","required":false,"schema":{"type":"integer","default":0,"title":"Offset"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/analytics/admin/dashboard":{"get":{"tags":["analytics"],"summary":"Get Admin Dashboard","description":"Get comprehensive dashboard statistics (Admin only)","operationId":"get_admin_dashboard_analytics_admin_dashboard_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/analytics/admin/users/growth":{"get":{"tags":["analytics"],"summary":"Get User Growth","description":"Get user growth analytics (Admin only)","operationId":"get_user_growth_analytics_admin_users_growth_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/analytics/admin/engagement":{"get":{"tags":["analytics"],"summary":"Get Engagement Metrics","description":"Get user engagement metrics (Admin only)","operationId":"get_engagement_metrics_analytics_admin_engagement_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/analytics/admin/api-stats":{"get":{"tags":["analytics"],"summary":"Get Api Statistics","description":"Get API usage statistics (Admin only)","operationId":"get_api_statistics_analytics_admin_api_stats_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/analytics/admin/usage":{"get":{"tags":["analytics"],"summary":"Get Usage Analytics","description":"Get detailed API usage analytics (Admin only)","operationId":"get_usage_analytics_analytics_admin_usage_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"days","in":"query","required":false,"schema":{"type":"integer","default":30,"title":"Days"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/analytics/admin/performance":{"get":{"tags":["analytics"],"summary":"Get Performance Analytics","description":"Get performance analytics (Admin only)","operationId":"get_performance_analytics_analytics_admin_performance_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"hours","in":"query","required":false,"schema":{"type":"integer","default":24,"title":"Hours"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/analytics/admin/login-audit":{"get":{"tags":["analytics"],"summary":"Get Login Audit","description":"Get login audit log for all users (Admin only)","operationId":"get_login_audit_analytics_admin_login_audit_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"user_id","in":"query","required":false,"schema":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"User Id"}},{"name":"ip_address","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Ip Address"}},{"name":"success_only","in":"query","required":false,"schema":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Success Only"}},{"name":"days","in":"query","required":false,"schema":{"type":"integer","default":30,"title":"Days"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":100,"title":"Limit"}},{"name":"offset","in":"query","required":false,"schema":{"type":"integer","default":0,"title":"Offset"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/analytics/admin/revenue-analytics":{"get":{"tags":["analytics"],"summary":"Get Admin Revenue Analytics","description":"Get marketplace revenue analytics (Admin only)","operationId":"get_admin_revenue_analytics_analytics_admin_revenue_analytics_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/analytics/admin/subscription-analytics":{"get":{"tags":["analytics"],"summary":"Get Subscription Analytics","description":"Get subscription analytics (Admin only) - DISABLED - Payment system to be reimplemented","operationId":"get_subscription_analytics_analytics_admin_subscription_analytics_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/speech/decompose":{"post":{"tags":["speech"],"summary":"Decompose Speech","description":"Decompose financial/political speech into structured components.\n\n- Requires API key authentication\n- Costs 2-10 credits based on text size\n- Maximum text length: 500,000 characters\n- Processing is done asynchronously for long texts (>10K chars)\n\nCredit tiers:\n- <5K chars: 2 credits\n- <15K chars: 3 credits\n- <30K chars: 4 credits\n- <50K chars: 5 credits\n- <100K chars: 6 credits\n- <200K chars: 8 credits\n- 200K+ chars: 10 credits","operationId":"decompose_speech_speech_decompose_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SpeechInput"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/speech/status/{analysis_id}":{"get":{"tags":["speech"],"summary":"Get Analysis Status","description":"Get status of a speech analysis (user can only access their own)","operationId":"get_analysis_status_speech_status__analysis_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"analysis_id","in":"path","required":true,"schema":{"type":"string","title":"Analysis Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/speech/history":{"get":{"tags":["speech"],"summary":"Get Analysis History","description":"Get user's speech analysis history","operationId":"get_analysis_history_speech_history_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":20,"title":"Limit"}},{"name":"offset","in":"query","required":false,"schema":{"type":"integer","default":0,"title":"Offset"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/speech/result/{analysis_id}":{"get":{"tags":["speech"],"summary":"Get Full Result","description":"Get full decomposition result including raw passes (user's own only)","operationId":"get_full_result_speech_result__analysis_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"analysis_id","in":"path","required":true,"schema":{"type":"string","title":"Analysis Id"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/trade/countries":{"get":{"tags":["trade"],"summary":"Get Countries","description":"Get list of countries with optional filtering\n\n- continent: Filter by continent ID (af, as, eu, na, sa, oc)\n- search: Search country name","operationId":"get_countries_trade_countries_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"continent","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Continent"}},{"name":"search","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Search"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/trade/continents":{"get":{"tags":["trade"],"summary":"Get Continents","description":"Get list of all continents","operationId":"get_continents_trade_continents_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/trade/products":{"get":{"tags":["trade"],"summary":"Get Products","description":"Get product hierarchy\n\n- level: Filter by level (Section, HS2, HS4, HS6)\n- parent: Get children of parent HS code","operationId":"get_products_trade_products_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"level","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Level"}},{"name":"parent","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Parent"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/trade/bilateral":{"get":{"tags":["trade"],"summary":"Get Bilateral Trade","description":"Get bilateral trade data between countries\n\nReturns trade flows between exporters and importers for a specific product and year","operationId":"get_bilateral_trade_trade_bilateral_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"hs_code","in":"query","required":true,"schema":{"type":"string","description":"HS product code","title":"Hs Code"},"description":"HS product code"},{"name":"year","in":"query","required":true,"schema":{"type":"integer","description":"Year (1995-2023)","title":"Year"},"description":"Year (1995-2023)"},{"name":"exporter","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"Exporter country ID","title":"Exporter"},"description":"Exporter country ID"},{"name":"importer","in":"query","required":false,"schema":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"Importer country ID","title":"Importer"},"description":"Importer country ID"},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":1000,"default":100,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/trade/country-partners/{country_id}":{"get":{"tags":["trade"],"summary":"Get Country Trade Partners","description":"Get top trading partners for a country (for Chord Diagram)\n\nReturns ranked list of trading partners with trade values","operationId":"get_country_trade_partners_trade_country_partners__country_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"country_id","in":"path","required":true,"schema":{"type":"string","title":"Country Id"}},{"name":"year","in":"query","required":true,"schema":{"type":"integer","description":"Year (1995-2023)","title":"Year"},"description":"Year (1995-2023)"},{"name":"hs_code","in":"query","required":false,"schema":{"type":"string","description":"HS product code","default":"1","title":"Hs Code"},"description":"HS product code"},{"name":"flow_type","in":"query","required":false,"schema":{"type":"string","description":"export, import, or total","default":"total","title":"Flow Type"},"description":"export, import, or total"},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":200,"default":50,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/trade/chord-data/{country_id}":{"get":{"tags":["trade"],"summary":"Get Chord Diagram Data","description":"Get data formatted for Chord Diagram visualization (like Bloomberg Terminal)\n\nReturns:\n- nodes: List of countries (source + top partners)\n- flows: Trade flows between countries\n- rankings: Ranked list of partners with total trade","operationId":"get_chord_diagram_data_trade_chord_data__country_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"country_id","in":"path","required":true,"schema":{"type":"string","title":"Country Id"}},{"name":"year","in":"query","required":false,"schema":{"type":"integer","description":"Year (1995-2023)","default":2017,"title":"Year"},"description":"Year (1995-2023)"},{"name":"hs_code","in":"query","required":false,"schema":{"type":"string","description":"HS product code","default":"1","title":"Hs Code"},"description":"HS product code"},{"name":"top_n","in":"query","required":false,"schema":{"type":"integer","maximum":50,"description":"Number of top partners","default":15,"title":"Top N"},"description":"Number of top partners"}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/trade/time-series/{country_id}":{"get":{"tags":["trade"],"summary":"Get Trade Time Series","description":"Get time series trade data for a country\n\nReturns trade values over time for trend analysis","operationId":"get_trade_time_series_trade_time_series__country_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"country_id","in":"path","required":true,"schema":{"type":"string","title":"Country Id"}},{"name":"hs_code","in":"query","required":false,"schema":{"type":"string","description":"HS product code","default":"1","title":"Hs Code"},"description":"HS product code"},{"name":"start_year","in":"query","required":false,"schema":{"type":"integer","default":1995,"title":"Start Year"}},{"name":"end_year","in":"query","required":false,"schema":{"type":"integer","default":2023,"title":"End Year"}},{"name":"flow","in":"query","required":false,"schema":{"type":"string","description":"export, import, or both","default":"both","title":"Flow"},"description":"export, import, or both"}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/trade/growth/{country_id}":{"get":{"tags":["trade"],"summary":"Get Trade Growth","description":"Get trade growth rates for a country","operationId":"get_trade_growth_trade_growth__country_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"country_id","in":"path","required":true,"schema":{"type":"string","title":"Country Id"}},{"name":"hs_code","in":"query","required":false,"schema":{"type":"string","description":"HS product code","default":"1","title":"Hs Code"},"description":"HS product code"},{"name":"year","in":"query","required":false,"schema":{"type":"integer","default":2023,"title":"Year"}},{"name":"flow","in":"query","required":false,"schema":{"type":"string","description":"export or import","default":"export","title":"Flow"},"description":"export or import"}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/trade/balance/{country_id}":{"get":{"tags":["trade"],"summary":"Get Trade Balance","description":"Get trade balance (surplus/deficit) for a country","operationId":"get_trade_balance_trade_balance__country_id__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"country_id","in":"path","required":true,"schema":{"type":"string","title":"Country Id"}},{"name":"hs_code","in":"query","required":false,"schema":{"type":"string","description":"HS product code","default":"1","title":"Hs Code"},"description":"HS product code"},{"name":"year","in":"query","required":false,"schema":{"type":"integer","default":2023,"title":"Year"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/trade/top-exporters":{"get":{"tags":["trade"],"summary":"Get Top Exporters","description":"Get top exporting countries for a product","operationId":"get_top_exporters_trade_top_exporters_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"hs_code","in":"query","required":false,"schema":{"type":"string","description":"HS product code","default":"1","title":"Hs Code"},"description":"HS product code"},{"name":"year","in":"query","required":false,"schema":{"type":"integer","default":2023,"title":"Year"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":100,"default":20,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/trade/top-importers":{"get":{"tags":["trade"],"summary":"Get Top Importers","description":"Get top importing countries for a product","operationId":"get_top_importers_trade_top_importers_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"hs_code","in":"query","required":false,"schema":{"type":"string","description":"HS product code","default":"1","title":"Hs Code"},"description":"HS product code"},{"name":"year","in":"query","required":false,"schema":{"type":"integer","default":2023,"title":"Year"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","maximum":100,"default":20,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/trade/continent-trade":{"get":{"tags":["trade"],"summary":"Get Continent Trade","description":"Get trade by continent","operationId":"get_continent_trade_trade_continent_trade_get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"hs_code","in":"query","required":false,"schema":{"type":"string","description":"HS product code","default":"1","title":"Hs Code"},"description":"HS product code"},{"name":"year","in":"query","required":false,"schema":{"type":"integer","default":2023,"title":"Year"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/trade/health":{"get":{"tags":["trade"],"summary":"Health Check","description":"Health check for trade analytics API","operationId":"health_check_trade_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/data/info":{"get":{"tags":["quantlib-free"],"summary":"Data Module Info","description":"Data module information","operationId":"data_module_info_quantlib_data_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/data/get-index":{"post":{"tags":["quantlib-free"],"summary":"Get Index Endpoint","operationId":"get_index_endpoint_quantlib_data_get_index_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GetIndexRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/create-ibor-index":{"post":{"tags":["quantlib-free"],"summary":"Create Ibor Index","operationId":"create_ibor_index_quantlib_data_create_ibor_index_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IBORIndexRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/create-rfr-index":{"post":{"tags":["quantlib-free"],"summary":"Create Rfr Index","operationId":"create_rfr_index_quantlib_data_create_rfr_index_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RFRIndexRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/create-fx-index":{"post":{"tags":["quantlib-free"],"summary":"Create Fx Index","operationId":"create_fx_index_quantlib_data_create_fx_index_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FXIndexRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/create-inflation-index":{"post":{"tags":["quantlib-free"],"summary":"Create Inflation Index","operationId":"create_inflation_index_quantlib_data_create_inflation_index_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/InflationIndexRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/sofr":{"get":{"tags":["quantlib-free"],"summary":"Get Sofr Index","operationId":"get_sofr_index_quantlib_data_sofr_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/sonia":{"get":{"tags":["quantlib-free"],"summary":"Get Sonia Index","operationId":"get_sonia_index_quantlib_data_sonia_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/estr":{"get":{"tags":["quantlib-free"],"summary":"Get Estr Index","operationId":"get_estr_index_quantlib_data_estr_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/tonar":{"get":{"tags":["quantlib-free"],"summary":"Get Tonar Index","operationId":"get_tonar_index_quantlib_data_tonar_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/term-sofr":{"get":{"tags":["quantlib-free"],"summary":"Get Term Sofr Index","operationId":"get_term_sofr_index_quantlib_data_term_sofr_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/euribor":{"get":{"tags":["quantlib-free"],"summary":"Get Euribor Index","operationId":"get_euribor_index_quantlib_data_euribor_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/create-ibor-fixing":{"post":{"tags":["quantlib-free"],"summary":"Create Ibor Fixing","operationId":"create_ibor_fixing_quantlib_data_create_ibor_fixing_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IBORFixingRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/create-rfr-fixing":{"post":{"tags":["quantlib-free"],"summary":"Create Rfr Fixing","operationId":"create_rfr_fixing_quantlib_data_create_rfr_fixing_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RFRFixingRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/create-fx-fixing":{"post":{"tags":["quantlib-free"],"summary":"Create Fx Fixing","operationId":"create_fx_fixing_quantlib_data_create_fx_fixing_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FXFixingRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/create-inflation-fixing":{"post":{"tags":["quantlib-free"],"summary":"Create Inflation Fixing","operationId":"create_inflation_fixing_quantlib_data_create_inflation_fixing_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/InflationFixingRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/create-fixing-store":{"post":{"tags":["quantlib-free"],"summary":"Create Fixing Store","operationId":"create_fixing_store_quantlib_data_create_fixing_store_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/fixing-error-types":{"get":{"tags":["quantlib-free"],"summary":"Get Fixing Error Types","operationId":"get_fixing_error_types_quantlib_data_fixing_error_types_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/fixing-types":{"get":{"tags":["quantlib-free"],"summary":"Get Fixing Types","operationId":"get_fixing_types_quantlib_data_fixing_types_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/fixings-module":{"get":{"tags":["quantlib-free"],"summary":"Get Fixings Module","operationId":"get_fixings_module_quantlib_data_fixings_module_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/data/indices-module":{"get":{"tags":["quantlib-free"],"summary":"Get Indices Module","operationId":"get_indices_module_quantlib_data_indices_module_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/info":{"get":{"tags":["quantlib-free"],"summary":"Scheduling Module Info","description":"Scheduling module information","operationId":"scheduling_module_info_quantlib_scheduling_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/scheduling/actual360":{"post":{"tags":["quantlib-free"],"summary":"Actual360","operationId":"actual360_quantlib_scheduling_actual360_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__DayCountRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/actual365fixed":{"post":{"tags":["quantlib-free"],"summary":"Actual365Fixed","operationId":"actual365fixed_quantlib_scheduling_actual365fixed_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__DayCountRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/actual365actual":{"post":{"tags":["quantlib-free"],"summary":"Actual365Actual","operationId":"actual365actual_quantlib_scheduling_actual365actual_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__DayCountRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/actualactualisda":{"post":{"tags":["quantlib-free"],"summary":"Actualactualisda","operationId":"actualactualisda_quantlib_scheduling_actualactualisda_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__DayCountRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/thirty360":{"post":{"tags":["quantlib-free"],"summary":"Thirty360","operationId":"thirty360_quantlib_scheduling_thirty360_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__DayCountRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/thirty360european":{"post":{"tags":["quantlib-free"],"summary":"Thirty360European","operationId":"thirty360european_quantlib_scheduling_thirty360european_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__DayCountRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/thirtye360":{"post":{"tags":["quantlib-free"],"summary":"Thirtye360","operationId":"thirtye360_quantlib_scheduling_thirtye360_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__DayCountRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/thirtye360isda":{"post":{"tags":["quantlib-free"],"summary":"Thirtye360Isda","operationId":"thirtye360isda_quantlib_scheduling_thirtye360isda_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__DayCountRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/business252":{"post":{"tags":["quantlib-free"],"summary":"Business252","operationId":"business252_quantlib_scheduling_business252_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__DayCountRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/year-fraction":{"post":{"tags":["quantlib-free"],"summary":"Year Fraction Endpoint","operationId":"year_fraction_endpoint_quantlib_scheduling_year_fraction_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/YearFractionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/target-calendar":{"post":{"tags":["quantlib-free"],"summary":"Target Calendar","operationId":"target_calendar_quantlib_scheduling_target_calendar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__CalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/us-calendar":{"post":{"tags":["quantlib-free"],"summary":"Us Calendar","operationId":"us_calendar_quantlib_scheduling_us_calendar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__CalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/uk-calendar":{"post":{"tags":["quantlib-free"],"summary":"Uk Calendar","operationId":"uk_calendar_quantlib_scheduling_uk_calendar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__CalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/japan-calendar":{"post":{"tags":["quantlib-free"],"summary":"Japan Calendar","operationId":"japan_calendar_quantlib_scheduling_japan_calendar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__CalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/get-calendar":{"post":{"tags":["quantlib-free"],"summary":"Get Calendar Endpoint","operationId":"get_calendar_endpoint_quantlib_scheduling_get_calendar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GetCalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/combined-calendar":{"post":{"tags":["quantlib-free"],"summary":"Combined Calendar","operationId":"combined_calendar_quantlib_scheduling_combined_calendar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CombinedCalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/weekend-calendar":{"post":{"tags":["quantlib-free"],"summary":"Weekend Calendar","operationId":"weekend_calendar_quantlib_scheduling_weekend_calendar_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/following":{"post":{"tags":["quantlib-free"],"summary":"Following","operationId":"following_quantlib_scheduling_following_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AdjustmentRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/modified-following":{"post":{"tags":["quantlib-free"],"summary":"Modified Following","operationId":"modified_following_quantlib_scheduling_modified_following_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AdjustmentRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/preceding":{"post":{"tags":["quantlib-free"],"summary":"Preceding","operationId":"preceding_quantlib_scheduling_preceding_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AdjustmentRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/modified-preceding":{"post":{"tags":["quantlib-free"],"summary":"Modified Preceding","operationId":"modified_preceding_quantlib_scheduling_modified_preceding_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AdjustmentRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/unadjusted":{"post":{"tags":["quantlib-free"],"summary":"Unadjusted","operationId":"unadjusted_quantlib_scheduling_unadjusted_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UnadjustedRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/business-day-adjustment":{"post":{"tags":["quantlib-free"],"summary":"Business Day Adjustment Endpoint","operationId":"business_day_adjustment_endpoint_quantlib_scheduling_business_day_adjustment_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BusinessDayAdjustmentRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/generate-schedule":{"post":{"tags":["quantlib-free"],"summary":"Generate Schedule","operationId":"generate_schedule_quantlib_scheduling_generate_schedule_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ScheduleRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/frequency-annual":{"get":{"tags":["quantlib-free"],"summary":"Frequency Annual","operationId":"frequency_annual_quantlib_scheduling_frequency_annual_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/frequency-semiannual":{"get":{"tags":["quantlib-free"],"summary":"Frequency Semiannual","operationId":"frequency_semiannual_quantlib_scheduling_frequency_semiannual_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/frequency-quarterly":{"get":{"tags":["quantlib-free"],"summary":"Frequency Quarterly","operationId":"frequency_quarterly_quantlib_scheduling_frequency_quarterly_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/frequency-monthly":{"get":{"tags":["quantlib-free"],"summary":"Frequency Monthly","operationId":"frequency_monthly_quantlib_scheduling_frequency_monthly_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/frequency-weekly":{"get":{"tags":["quantlib-free"],"summary":"Frequency Weekly","operationId":"frequency_weekly_quantlib_scheduling_frequency_weekly_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/frequency-daily":{"get":{"tags":["quantlib-free"],"summary":"Frequency Daily","operationId":"frequency_daily_quantlib_scheduling_frequency_daily_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/frequency-once":{"get":{"tags":["quantlib-free"],"summary":"Frequency Once","operationId":"frequency_once_quantlib_scheduling_frequency_once_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/stub-types":{"get":{"tags":["quantlib-free"],"summary":"Stub Types","operationId":"stub_types_quantlib_scheduling_stub_types_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/adjustment-types":{"get":{"tags":["quantlib-free"],"summary":"Adjustment Types","operationId":"adjustment_types_quantlib_scheduling_adjustment_types_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/adjust-date":{"post":{"tags":["quantlib-free"],"summary":"Adjust Date Endpoint","description":"Adjust a date according to business day convention","operationId":"adjust_date_endpoint_quantlib_scheduling_adjust_date_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/day-count-convention-info":{"get":{"tags":["quantlib-free"],"summary":"Get Day Count Convention Info","description":"Get documentation for DayCountConvention base class","operationId":"get_day_count_convention_info_quantlib_scheduling_day_count_convention_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/utils/info":{"get":{"tags":["quantlib-free"],"summary":"Utils Module Info","description":"Utils module information","operationId":"utils_module_info_quantlib_utils_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/utils/add-business-days":{"post":{"tags":["quantlib-free"],"summary":"Add Business Days Util","operationId":"add_business_days_util_quantlib_utils_add_business_days_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AddBusinessDaysRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/imm-date/{year}/{month}":{"get":{"tags":["quantlib-free"],"summary":"Imm Date Util","operationId":"imm_date_util_quantlib_utils_imm_date__year___month__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"year","in":"path","required":true,"schema":{"type":"integer","title":"Year"}},{"name":"month","in":"path","required":true,"schema":{"type":"integer","title":"Month"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/quantlib/utils/easter-date/{year}":{"get":{"tags":["quantlib-free"],"summary":"Easter Date Util","operationId":"easter_date_util_quantlib_utils_easter_date__year__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"year","in":"path","required":true,"schema":{"type":"integer","title":"Year"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/quantlib/utils/cubic-spline":{"post":{"tags":["quantlib-free"],"summary":"Cubic Spline Util","operationId":"cubic_spline_util_quantlib_utils_cubic_spline_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/InterpolationRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/brent":{"post":{"tags":["quantlib-free"],"summary":"Brent Util","operationId":"brent_util_quantlib_utils_brent_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SolverUtilRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/bisection":{"post":{"tags":["quantlib-free"],"summary":"Bisection Util","operationId":"bisection_util_quantlib_utils_bisection_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SolverUtilRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/cholesky":{"post":{"tags":["quantlib-free"],"summary":"Cholesky Util","operationId":"cholesky_util_quantlib_utils_cholesky_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MatrixUtilRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/eigenvalues":{"post":{"tags":["quantlib-free"],"summary":"Eigenvalues Util","operationId":"eigenvalues_util_quantlib_utils_eigenvalues_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MatrixUtilRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/svd":{"post":{"tags":["quantlib-free"],"summary":"Svd Util","operationId":"svd_util_quantlib_utils_svd_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SVDRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/inverse-matrix":{"post":{"tags":["quantlib-free"],"summary":"Inverse Matrix Util","operationId":"inverse_matrix_util_quantlib_utils_inverse_matrix_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/InverseMatrixRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/determinant":{"post":{"tags":["quantlib-free"],"summary":"Determinant Util","operationId":"determinant_util_quantlib_utils_determinant_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DeterminantRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/newton-raphson":{"post":{"tags":["quantlib-free"],"summary":"Newton Raphson Util","operationId":"newton_raphson_util_quantlib_utils_newton_raphson_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__NewtonRaphsonRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/secant-method":{"post":{"tags":["quantlib-free"],"summary":"Secant Method Util","operationId":"secant_method_util_quantlib_utils_secant_method_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SecantMethodRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/linear-interpolation":{"post":{"tags":["quantlib-free"],"summary":"Linear Interpolation Util","operationId":"linear_interpolation_util_quantlib_utils_linear_interpolation_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LinearInterpRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/log-linear-interpolation":{"post":{"tags":["quantlib-free"],"summary":"Log Linear Interpolation Util","operationId":"log_linear_interpolation_util_quantlib_utils_log_linear_interpolation_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LogLinearInterpRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/hermite-interpolation":{"post":{"tags":["quantlib-free"],"summary":"Hermite Interpolation Util","operationId":"hermite_interpolation_util_quantlib_utils_hermite_interpolation_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HermiteInterpRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/dot-product":{"post":{"tags":["quantlib-free"],"summary":"Dot Product Util","operationId":"dot_product_util_quantlib_utils_dot_product_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VectorDotProductRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/cross-product":{"post":{"tags":["quantlib-free"],"summary":"Cross Product Util","operationId":"cross_product_util_quantlib_utils_cross_product_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VectorCrossProductRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/vector-norm":{"post":{"tags":["quantlib-free"],"summary":"Vector Norm Util","operationId":"vector_norm_util_quantlib_utils_vector_norm_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VectorNormRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/is-end-of-month":{"post":{"tags":["quantlib-free"],"summary":"Is End Of Month Util","operationId":"is_end_of_month_util_quantlib_utils_is_end_of_month_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DateCheckRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/is-quarter-end":{"post":{"tags":["quantlib-free"],"summary":"Is Quarter End Util","operationId":"is_quarter_end_util_quantlib_utils_is_quarter_end_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DateCheckRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/is-year-end":{"post":{"tags":["quantlib-free"],"summary":"Is Year End Util","operationId":"is_year_end_util_quantlib_utils_is_year_end_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DateCheckRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/australia-calendar":{"post":{"tags":["quantlib-free"],"summary":"Australia Calendar Util","operationId":"australia_calendar_util_quantlib_utils_australia_calendar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AustraliaCalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/brazil-calendar":{"post":{"tags":["quantlib-free"],"summary":"Brazil Calendar Util","operationId":"brazil_calendar_util_quantlib_utils_brazil_calendar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BrazilCalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/china-calendar":{"post":{"tags":["quantlib-free"],"summary":"China Calendar Util","operationId":"china_calendar_util_quantlib_utils_china_calendar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChinaCalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/india-calendar":{"post":{"tags":["quantlib-free"],"summary":"India Calendar Util","operationId":"india_calendar_util_quantlib_utils_india_calendar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IndiaCalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/switzerland-calendar":{"post":{"tags":["quantlib-free"],"summary":"Switzerland Calendar Util","operationId":"switzerland_calendar_util_quantlib_utils_switzerland_calendar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SwitzerlandCalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/canada-calendar":{"post":{"tags":["quantlib-free"],"summary":"Canada Calendar Util","operationId":"canada_calendar_util_quantlib_utils_canada_calendar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CanadaCalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/germany-calendar":{"post":{"tags":["quantlib-free"],"summary":"Germany Calendar Util","operationId":"germany_calendar_util_quantlib_utils_germany_calendar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GermanyCalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/france-calendar":{"post":{"tags":["quantlib-free"],"summary":"France Calendar Util","operationId":"france_calendar_util_quantlib_utils_france_calendar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FranceCalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/adjust-date":{"post":{"tags":["quantlib-free"],"summary":"Adjust Date Util","operationId":"adjust_date_util_quantlib_utils_adjust_date_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AdjustDateRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/advance-date":{"post":{"tags":["quantlib-free"],"summary":"Advance Date Util","operationId":"advance_date_util_quantlib_utils_advance_date_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AdvanceDateRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/business-days-between":{"post":{"tags":["quantlib-free"],"summary":"Business Days Between Util","operationId":"business_days_between_util_quantlib_utils_business_days_between_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BusinessDaysBetweenRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/mean":{"post":{"tags":["quantlib-free"],"summary":"Mean Util","operationId":"mean_util_quantlib_utils_mean_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MeanRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/variance":{"post":{"tags":["quantlib-free"],"summary":"Variance Util","operationId":"variance_util_quantlib_utils_variance_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VarianceRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/standard-deviation":{"post":{"tags":["quantlib-free"],"summary":"Standard Deviation Util","operationId":"standard_deviation_util_quantlib_utils_standard_deviation_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/StandardDeviationRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/correlation":{"post":{"tags":["quantlib-free"],"summary":"Correlation Util","operationId":"correlation_util_quantlib_utils_correlation_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CorrelationRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/backward-flat-interpolation":{"post":{"tags":["quantlib-free"],"summary":"Backward Flat Interpolation Util","operationId":"backward_flat_interpolation_util_quantlib_utils_backward_flat_interpolation_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BackwardFlatInterpRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/forward-flat-interpolation":{"post":{"tags":["quantlib-free"],"summary":"Forward Flat Interpolation Util","operationId":"forward_flat_interpolation_util_quantlib_utils_forward_flat_interpolation_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForwardFlatInterpRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/uniform-random":{"post":{"tags":["quantlib-free"],"summary":"Uniform Random Util","operationId":"uniform_random_util_quantlib_utils_uniform_random_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UniformRandomRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/normal-random":{"post":{"tags":["quantlib-free"],"summary":"Normal Random Util","operationId":"normal_random_util_quantlib_utils_normal_random_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NormalRandomRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/create-currency":{"post":{"tags":["quantlib-free"],"summary":"Create Currency Util","operationId":"create_currency_util_quantlib_utils_create_currency_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CurrencyRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/create-money":{"post":{"tags":["quantlib-free"],"summary":"Create Money Util","operationId":"create_money_util_quantlib_utils_create_money_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MoneyRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/forward-difference":{"post":{"tags":["quantlib-free"],"summary":"Forward Difference Util","operationId":"forward_difference_util_quantlib_utils_forward_difference_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NumericalDerivativeRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/backward-difference":{"post":{"tags":["quantlib-free"],"summary":"Backward Difference Util","operationId":"backward_difference_util_quantlib_utils_backward_difference_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NumericalDerivativeRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/central-difference":{"post":{"tags":["quantlib-free"],"summary":"Central Difference Util","operationId":"central_difference_util_quantlib_utils_central_difference_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NumericalDerivativeRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/finite-difference":{"post":{"tags":["quantlib-free"],"summary":"Finite Difference Util","operationId":"finite_difference_util_quantlib_utils_finite_difference_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FiniteDifferenceRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/trapezoid-rule":{"post":{"tags":["quantlib-free"],"summary":"Trapezoid Rule Util","operationId":"trapezoid_rule_util_quantlib_utils_trapezoid_rule_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IntegrationRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/simpson-rule":{"post":{"tags":["quantlib-free"],"summary":"Simpson Rule Util","operationId":"simpson_rule_util_quantlib_utils_simpson_rule_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IntegrationRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/gaussian-quadrature":{"post":{"tags":["quantlib-free"],"summary":"Gaussian Quadrature Util","operationId":"gaussian_quadrature_util_quantlib_utils_gaussian_quadrature_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IntegrationRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/matrix-multiply":{"post":{"tags":["quantlib-free"],"summary":"Matrix Multiply Util","operationId":"matrix_multiply_util_quantlib_utils_matrix_multiply_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MatrixMultiplyRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/matrix-transpose":{"post":{"tags":["quantlib-free"],"summary":"Matrix Transpose Util","operationId":"matrix_transpose_util_quantlib_utils_matrix_transpose_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MatrixUtilRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/lu-decomposition":{"post":{"tags":["quantlib-free"],"summary":"Lu Decomposition Util","operationId":"lu_decomposition_util_quantlib_utils_lu_decomposition_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MatrixUtilRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/qr-decomposition":{"post":{"tags":["quantlib-free"],"summary":"Qr Decomposition Util","operationId":"qr_decomposition_util_quantlib_utils_qr_decomposition_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MatrixUtilRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/nelder-mead":{"post":{"tags":["quantlib-free"],"summary":"Nelder Mead Util","operationId":"nelder_mead_util_quantlib_utils_nelder_mead_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OptimizationRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/powell-method":{"post":{"tags":["quantlib-free"],"summary":"Powell Method Util","operationId":"powell_method_util_quantlib_utils_powell_method_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OptimizationRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/golden-section-search":{"post":{"tags":["quantlib-free"],"summary":"Golden Section Search Util","operationId":"golden_section_search_util_quantlib_utils_golden_section_search_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GoldenSectionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/monotone-convex-interpolation":{"post":{"tags":["quantlib-free"],"summary":"Monotone Convex Interpolation Util","operationId":"monotone_convex_interpolation_util_quantlib_utils_monotone_convex_interpolation_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/InterpolationRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/extrapolate-flat":{"post":{"tags":["quantlib-free"],"summary":"Extrapolate Flat Util","operationId":"extrapolate_flat_util_quantlib_utils_extrapolate_flat_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExtrapolationRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/eigenvectors":{"post":{"tags":["quantlib-free"],"summary":"Eigenvectors Util","operationId":"eigenvectors_util_quantlib_utils_eigenvectors_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MatrixUtilRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/normalize-vector":{"post":{"tags":["quantlib-free"],"summary":"Normalize Vector Util","operationId":"normalize_vector_util_quantlib_utils_normalize_vector_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VectorNormRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/solve-linear-system":{"post":{"tags":["quantlib-free"],"summary":"Solve Linear System Util","operationId":"solve_linear_system_util_quantlib_utils_solve_linear_system_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LinearSystemRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/nth-weekday":{"post":{"tags":["quantlib-free"],"summary":"Nth Weekday Util","operationId":"nth_weekday_util_quantlib_utils_nth_weekday_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NthWeekdayRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/is-weekend":{"post":{"tags":["quantlib-free"],"summary":"Is Weekend Util","operationId":"is_weekend_util_quantlib_utils_is_weekend_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DateCheckRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/is-month-end":{"post":{"tags":["quantlib-free"],"summary":"Is Month End Util","operationId":"is_month_end_util_quantlib_utils_is_month_end_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DateCheckRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/is-imm-date":{"post":{"tags":["quantlib-free"],"summary":"Is Imm Date Util","operationId":"is_imm_date_util_quantlib_utils_is_imm_date_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IMMDateCheckRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/next-imm-date":{"post":{"tags":["quantlib-free"],"summary":"Next Imm Date Util","operationId":"next_imm_date_util_quantlib_utils_next_imm_date_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NextIMMDateRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/extrapolate-linear":{"post":{"tags":["quantlib-free"],"summary":"Extrapolate Linear Util","operationId":"extrapolate_linear_util_quantlib_utils_extrapolate_linear_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExtrapolateLinearRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/find-interval":{"post":{"tags":["quantlib-free"],"summary":"Find Interval Util","operationId":"find_interval_util_quantlib_utils_find_interval_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FindIntervalRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/validate-currency":{"post":{"tags":["quantlib-free"],"summary":"Validate Currency Util","operationId":"validate_currency_util_quantlib_utils_validate_currency_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidateCurrencyRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/validate-date-order":{"post":{"tags":["quantlib-free"],"summary":"Validate Date Order Util","operationId":"validate_date_order_util_quantlib_utils_validate_date_order_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_core__ValidateDateOrderRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/validate-positive":{"post":{"tags":["quantlib-free"],"summary":"Validate Positive Util","operationId":"validate_positive_util_quantlib_utils_validate_positive_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidatePositiveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/validate-probability":{"post":{"tags":["quantlib-free"],"summary":"Validate Probability Util","operationId":"validate_probability_util_quantlib_utils_validate_probability_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidateProbabilityRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/validate-rate":{"post":{"tags":["quantlib-free"],"summary":"Validate Rate Util","operationId":"validate_rate_util_quantlib_utils_validate_rate_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidateRateRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/validate-tenor":{"post":{"tags":["quantlib-free"],"summary":"Validate Tenor Util","operationId":"validate_tenor_util_quantlib_utils_validate_tenor_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidateTenorRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/is-scalar":{"post":{"tags":["quantlib-free"],"summary":"Is Scalar Util","operationId":"is_scalar_util_quantlib_utils_is_scalar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TypeCheckRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/is-vector":{"post":{"tags":["quantlib-free"],"summary":"Is Vector Util","operationId":"is_vector_util_quantlib_utils_is_vector_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TypeCheckRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/is-matrix":{"post":{"tags":["quantlib-free"],"summary":"Is Matrix Util","operationId":"is_matrix_util_quantlib_utils_is_matrix_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TypeCheckRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/coerce-to-float":{"post":{"tags":["quantlib-free"],"summary":"Coerce To Float Util","operationId":"coerce_to_float_util_quantlib_utils_coerce_to_float_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CoerceFloatRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/thirty360-european":{"post":{"tags":["quantlib-free"],"summary":"Thirty360 European Daycount","operationId":"thirty360_european_daycount_quantlib_scheduling_thirty360_european_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__DayCountRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/scheduling/thirtye360-daycount":{"post":{"tags":["quantlib-free"],"summary":"Thirtye360 Daycount","operationId":"thirtye360_daycount_quantlib_scheduling_thirtye360_daycount_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__DayCountRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/canada-calendar-check":{"post":{"tags":["quantlib-free"],"summary":"Canada Calendar Check","operationId":"canada_calendar_check_quantlib_utils_canada_calendar_check_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__CalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/japan-calendar-check":{"post":{"tags":["quantlib-free"],"summary":"Japan Calendar Check","operationId":"japan_calendar_check_quantlib_utils_japan_calendar_check_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__CalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/switzerland-calendar-check":{"post":{"tags":["quantlib-free"],"summary":"Switzerland Calendar Check","operationId":"switzerland_calendar_check_quantlib_utils_switzerland_calendar_check_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_utils__CalendarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/debug-print":{"post":{"tags":["quantlib-free"],"summary":"Debug Print Util","operationId":"debug_print_util_quantlib_utils_debug_print_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LogMessageRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/get-logger/{name}":{"get":{"tags":["quantlib-free"],"summary":"Get Logger Util","operationId":"get_logger_util_quantlib_utils_get_logger__name__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"name","in":"path","required":true,"schema":{"type":"string","title":"Name"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/quantlib/utils/log-function-call":{"post":{"tags":["quantlib-free"],"summary":"Log Function Call Util","operationId":"log_function_call_util_quantlib_utils_log_function_call_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FunctionCallLogRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/log-execution-time":{"post":{"tags":["quantlib-free"],"summary":"Log Execution Time Util","operationId":"log_execution_time_util_quantlib_utils_log_execution_time_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExecutionTimeRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/memory-usage":{"get":{"tags":["quantlib-free"],"summary":"Memory Usage Util","operationId":"memory_usage_util_quantlib_utils_memory_usage_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/profile-function":{"post":{"tags":["quantlib-free"],"summary":"Profile Function Util","operationId":"profile_function_util_quantlib_utils_profile_function_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProfileFunctionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/coerce-to-list":{"post":{"tags":["quantlib-free"],"summary":"Coerce To List Util","operationId":"coerce_to_list_util_quantlib_utils_coerce_to_list_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CoerceToListRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/matrix-inverse":{"post":{"tags":["quantlib-free"],"summary":"Matrix Inverse Endpoint","description":"Calculate matrix inverse","operationId":"matrix_inverse_endpoint_quantlib_utils_matrix_inverse_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/newton-method":{"post":{"tags":["quantlib-free"],"summary":"Newton Method Endpoint","description":"Solve equation using Newton's method","operationId":"newton_method_endpoint_quantlib_utils_newton_method_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/utils/svd-decomposition":{"post":{"tags":["quantlib-free"],"summary":"Svd Decomposition Endpoint","description":"Calculate singular value decomposition","operationId":"svd_decomposition_endpoint_quantlib_utils_svd_decomposition_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/info":{"get":{"tags":["quantlib-starter"],"summary":"Curves Module Info","description":"Curves module information","operationId":"curves_module_info_quantlib_curves_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/curves/create-discount-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Discount Curve","operationId":"create_discount_curve_quantlib_curves_create_discount_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-forward-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Forward Curve","operationId":"create_forward_curve_quantlib_curves_create_forward_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-zero-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Zero Curve","operationId":"create_zero_curve_quantlib_curves_create_zero_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-inflation-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Inflation Curve","operationId":"create_inflation_curve_quantlib_curves_create_inflation_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-real-rate-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Real Rate Curve","operationId":"create_real_rate_curve_quantlib_curves_create_real_rate_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-ois-discount-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Ois Discount Curve","operationId":"create_ois_discount_curve_quantlib_curves_create_ois_discount_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-ibor-projection-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Ibor Projection Curve","operationId":"create_ibor_projection_curve_quantlib_curves_create_ibor_projection_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-cross-currency-basis-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Cross Currency Basis Curve","operationId":"create_cross_currency_basis_curve_quantlib_curves_create_cross_currency_basis_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-composite-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Composite Curve","operationId":"create_composite_curve_quantlib_curves_create_composite_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-proxy-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Proxy Curve","operationId":"create_proxy_curve_quantlib_curves_create_proxy_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-scaled-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Scaled Curve","operationId":"create_scaled_curve_quantlib_curves_create_scaled_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/interpolator/linear":{"post":{"tags":["quantlib-starter"],"summary":"Create Linear Interpolator","operationId":"create_linear_interpolator_quantlib_curves_interpolator_linear_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/interpolator/log-linear":{"post":{"tags":["quantlib-starter"],"summary":"Create Log Linear Interpolator","operationId":"create_log_linear_interpolator_quantlib_curves_interpolator_log_linear_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/interpolator/cubic-spline":{"post":{"tags":["quantlib-starter"],"summary":"Create Cubic Spline Interpolator","operationId":"create_cubic_spline_interpolator_quantlib_curves_interpolator_cubic_spline_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/interpolator/monotone-convex":{"post":{"tags":["quantlib-starter"],"summary":"Create Monotone Convex Interpolator","operationId":"create_monotone_convex_interpolator_quantlib_curves_interpolator_monotone_convex_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/interpolator/flat-forward":{"post":{"tags":["quantlib-starter"],"summary":"Create Flat Forward Interpolator","operationId":"create_flat_forward_interpolator_quantlib_curves_interpolator_flat_forward_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/interpolator/flat-backward":{"post":{"tags":["quantlib-starter"],"summary":"Create Flat Backward Interpolator","operationId":"create_flat_backward_interpolator_quantlib_curves_interpolator_flat_backward_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-nelson-siegel":{"post":{"tags":["quantlib-starter"],"summary":"Create Nelson Siegel Curve","operationId":"create_nelson_siegel_curve_quantlib_curves_create_nelson_siegel_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NelsonSiegelRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-nelson-siegel-svensson":{"post":{"tags":["quantlib-starter"],"summary":"Create Nelson Siegel Svensson Curve","operationId":"create_nelson_siegel_svensson_curve_quantlib_curves_create_nelson_siegel_svensson_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NelsonSiegelSvenssonRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/operations/parallel-shift":{"post":{"tags":["quantlib-starter"],"summary":"Parallel Shift Curve","operationId":"parallel_shift_curve_quantlib_curves_operations_parallel_shift_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ShiftCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/operations/twist":{"post":{"tags":["quantlib-starter"],"summary":"Twist Curve Endpoint","operationId":"twist_curve_endpoint_quantlib_curves_operations_twist_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TwistCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/operations/butterfly-shift":{"post":{"tags":["quantlib-starter"],"summary":"Butterfly Shift Endpoint","operationId":"butterfly_shift_endpoint_quantlib_curves_operations_butterfly_shift_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ShiftCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/operations/key-rate-shift":{"post":{"tags":["quantlib-starter"],"summary":"Key Rate Shift Endpoint","operationId":"key_rate_shift_endpoint_quantlib_curves_operations_key_rate_shift_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyRateShiftRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/operations/roll":{"post":{"tags":["quantlib-starter"],"summary":"Roll Curve Endpoint","operationId":"roll_curve_endpoint_quantlib_curves_operations_roll_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RollCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-shifted-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Shifted Curve","operationId":"create_shifted_curve_quantlib_curves_create_shifted_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ShiftCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-twisted-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Twisted Curve","operationId":"create_twisted_curve_quantlib_curves_create_twisted_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TwistCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-butterfly-shifted-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Butterfly Shifted Curve","operationId":"create_butterfly_shifted_curve_quantlib_curves_create_butterfly_shifted_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ShiftCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-key-rate-shifted-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Key Rate Shifted Curve","operationId":"create_key_rate_shifted_curve_quantlib_curves_create_key_rate_shifted_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/KeyRateShiftRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-time-shifted-curve":{"post":{"tags":["quantlib-starter"],"summary":"Create Time Shifted Curve","operationId":"create_time_shifted_curve_quantlib_curves_create_time_shifted_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RollCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-multicurve-framework":{"post":{"tags":["quantlib-starter"],"summary":"Create Multicurve Framework","operationId":"create_multicurve_framework_quantlib_curves_create_multicurve_framework_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MulticurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/bootstrap-inflation":{"post":{"tags":["quantlib-starter"],"summary":"Bootstrap Inflation Curve Endpoint","operationId":"bootstrap_inflation_curve_endpoint_quantlib_curves_bootstrap_inflation_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BootstrapInflationRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/calibrate-multicurve":{"post":{"tags":["quantlib-starter"],"summary":"Calibrate Multicurve Endpoint","operationId":"calibrate_multicurve_endpoint_quantlib_curves_calibrate_multicurve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CalibrateMulticurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-curve-database":{"post":{"tags":["quantlib-starter"],"summary":"Create Curve Database","operationId":"create_curve_database_quantlib_curves_create_curve_database_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-curve-set":{"post":{"tags":["quantlib-starter"],"summary":"Create Curve Set","operationId":"create_curve_set_quantlib_curves_create_curve_set_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-curve-version":{"post":{"tags":["quantlib-starter"],"summary":"Create Curve Version","operationId":"create_curve_version_quantlib_curves_create_curve_version_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-curve-wrapper":{"post":{"tags":["quantlib-starter"],"summary":"Create Curve Wrapper","operationId":"create_curve_wrapper_quantlib_curves_create_curve_wrapper_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-incremental-updater":{"post":{"tags":["quantlib-starter"],"summary":"Create Incremental Updater","operationId":"create_incremental_updater_quantlib_curves_create_incremental_updater_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-curve-constraints":{"post":{"tags":["quantlib-starter"],"summary":"Create Curve Constraints","operationId":"create_curve_constraints_quantlib_curves_create_curve_constraints_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-monotonicity-constraint":{"post":{"tags":["quantlib-starter"],"summary":"Create Monotonicity Constraint","operationId":"create_monotonicity_constraint_quantlib_curves_create_monotonicity_constraint_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-smoothness-constraint":{"post":{"tags":["quantlib-starter"],"summary":"Create Smoothness Constraint","operationId":"create_smoothness_constraint_quantlib_curves_create_smoothness_constraint_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-constrained-fitter":{"post":{"tags":["quantlib-starter"],"summary":"Create Constrained Fitter","operationId":"create_constrained_fitter_quantlib_curves_create_constrained_fitter_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-inflation-seasonality":{"post":{"tags":["quantlib-starter"],"summary":"Create Inflation Seasonality","operationId":"create_inflation_seasonality_quantlib_curves_create_inflation_seasonality_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/create-seasonality-model":{"post":{"tags":["quantlib-starter"],"summary":"Create Seasonality Model","operationId":"create_seasonality_model_quantlib_curves_create_seasonality_model_post","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/base/curve":{"get":{"tags":["quantlib-starter"],"summary":"Get Curve Base Class","operationId":"get_curve_base_class_quantlib_curves_base_curve_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/base/interpolator":{"get":{"tags":["quantlib-starter"],"summary":"Get Interpolator Base Class","operationId":"get_interpolator_base_class_quantlib_curves_base_interpolator_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/enums/shift-types":{"get":{"tags":["quantlib-starter"],"summary":"Get Shift Types","operationId":"get_shift_types_quantlib_curves_enums_shift_types_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/enums/shift-spaces":{"get":{"tags":["quantlib-starter"],"summary":"Get Shift Spaces","operationId":"get_shift_spaces_quantlib_curves_enums_shift_spaces_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/submodules/curve":{"get":{"tags":["quantlib-starter"],"summary":"Get Curve Module","operationId":"get_curve_module_quantlib_curves_submodules_curve_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/submodules/interpolation":{"get":{"tags":["quantlib-starter"],"summary":"Get Interpolation Module","operationId":"get_interpolation_module_quantlib_curves_submodules_interpolation_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/submodules/operations":{"get":{"tags":["quantlib-starter"],"summary":"Get Operations Module","operationId":"get_operations_module_quantlib_curves_submodules_operations_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/submodules/inflation":{"get":{"tags":["quantlib-starter"],"summary":"Get Inflation Module","operationId":"get_inflation_module_quantlib_curves_submodules_inflation_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/submodules/multicurve":{"get":{"tags":["quantlib-starter"],"summary":"Get Multicurve Module","operationId":"get_multicurve_module_quantlib_curves_submodules_multicurve_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/submodules/parametric":{"get":{"tags":["quantlib-starter"],"summary":"Get Parametric Module","operationId":"get_parametric_module_quantlib_curves_submodules_parametric_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/curves/submodules/advanced":{"get":{"tags":["quantlib-starter"],"summary":"Get Advanced Module","operationId":"get_advanced_module_quantlib_curves_submodules_advanced_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/info":{"get":{"tags":["quantlib-starter"],"summary":"Core Module Info","description":"Core module information","operationId":"core_module_info_quantlib_core_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/core/create-currency":{"post":{"tags":["quantlib-starter"],"summary":"Create Currency","operationId":"create_currency_quantlib_core_create_currency_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateCurrencyRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-money":{"post":{"tags":["quantlib-starter"],"summary":"Create Money","operationId":"create_money_quantlib_core_create_money_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateMoneyRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-rate":{"post":{"tags":["quantlib-starter"],"summary":"Create Rate","operationId":"create_rate_quantlib_core_create_rate_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateRateRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-spread":{"post":{"tags":["quantlib-starter"],"summary":"Create Spread","operationId":"create_spread_quantlib_core_create_spread_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateSpreadRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/currency-decimals/{code}":{"get":{"tags":["quantlib-starter"],"summary":"Get Currency Decimals","operationId":"get_currency_decimals_quantlib_core_currency_decimals__code__get","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"code","in":"path","required":true,"schema":{"type":"string","title":"Code"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/quantlib/core/create-tenor":{"post":{"tags":["quantlib-starter"],"summary":"Create Tenor","operationId":"create_tenor_quantlib_core_create_tenor_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateTenorRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/date-to-excel":{"post":{"tags":["quantlib-starter"],"summary":"Date To Excel","operationId":"date_to_excel_quantlib_core_date_to_excel_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DateToExcelRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/to-date":{"post":{"tags":["quantlib-starter"],"summary":"To Date Endpoint","operationId":"to_date_endpoint_quantlib_core_to_date_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ToDateRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/as-currency":{"post":{"tags":["quantlib-starter"],"summary":"As Currency","operationId":"as_currency_quantlib_core_as_currency_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AsCurrencyRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/as-money":{"post":{"tags":["quantlib-starter"],"summary":"As Money","operationId":"as_money_quantlib_core_as_money_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateMoneyRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/as-rate":{"post":{"tags":["quantlib-starter"],"summary":"As Rate","operationId":"as_rate_quantlib_core_as_rate_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateRateRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/as-tenor":{"post":{"tags":["quantlib-starter"],"summary":"As Tenor","operationId":"as_tenor_quantlib_core_as_tenor_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateTenorRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/as-date":{"post":{"tags":["quantlib-starter"],"summary":"As Date","operationId":"as_date_quantlib_core_as_date_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ToDateRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/math/exp":{"post":{"tags":["quantlib-starter"],"summary":"Math Exp","operationId":"math_exp_quantlib_core_math_exp_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MathRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/math/log":{"post":{"tags":["quantlib-starter"],"summary":"Math Log","operationId":"math_log_quantlib_core_math_log_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MathRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/math/sqrt":{"post":{"tags":["quantlib-starter"],"summary":"Math Sqrt","operationId":"math_sqrt_quantlib_core_math_sqrt_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MathRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/math/sin":{"post":{"tags":["quantlib-starter"],"summary":"Math Sin","operationId":"math_sin_quantlib_core_math_sin_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MathRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/math/cos":{"post":{"tags":["quantlib-starter"],"summary":"Math Cos","operationId":"math_cos_quantlib_core_math_cos_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MathRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/math/tan":{"post":{"tags":["quantlib-starter"],"summary":"Math Tan","operationId":"math_tan_quantlib_core_math_tan_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MathRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/math/sinh":{"post":{"tags":["quantlib-starter"],"summary":"Math Sinh","operationId":"math_sinh_quantlib_core_math_sinh_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MathRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/math/cosh":{"post":{"tags":["quantlib-starter"],"summary":"Math Cosh","operationId":"math_cosh_quantlib_core_math_cosh_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MathRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/math/tanh":{"post":{"tags":["quantlib-starter"],"summary":"Math Tanh","operationId":"math_tanh_quantlib_core_math_tanh_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MathRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/math/power":{"post":{"tags":["quantlib-starter"],"summary":"Math Power","operationId":"math_power_quantlib_core_math_power_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PowerRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/math/taylor-expand":{"post":{"tags":["quantlib-starter"],"summary":"Taylor Expand","operationId":"taylor_expand_quantlib_core_math_taylor_expand_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TaylorExpandRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/autodiff/create-dual":{"post":{"tags":["quantlib-starter"],"summary":"Create Dual","operationId":"create_dual_quantlib_core_autodiff_create_dual_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateDualRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/autodiff/create-hyperdual":{"post":{"tags":["quantlib-starter"],"summary":"Create Hyperdual","operationId":"create_hyperdual_quantlib_core_autodiff_create_hyperdual_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateHyperDualRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/autodiff/gradient":{"post":{"tags":["quantlib-starter"],"summary":"Compute Gradient","operationId":"compute_gradient_quantlib_core_autodiff_gradient_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GradientRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/autodiff/hessian":{"post":{"tags":["quantlib-starter"],"summary":"Compute Hessian","operationId":"compute_hessian_quantlib_core_autodiff_hessian_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GradientRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/autodiff/jacobian":{"post":{"tags":["quantlib-starter"],"summary":"Compute Jacobian","operationId":"compute_jacobian_quantlib_core_autodiff_jacobian_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GradientRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/validate-date-order":{"post":{"tags":["quantlib-starter"],"summary":"Validate Date Order","operationId":"validate_date_order_quantlib_core_validate_date_order_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_core__ValidateDateOrderRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/validate-positive":{"post":{"tags":["quantlib-starter"],"summary":"Validate Positive","operationId":"validate_positive_quantlib_core_validate_positive_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidateValueRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/validate-non-negative":{"post":{"tags":["quantlib-starter"],"summary":"Validate Non Negative","operationId":"validate_non_negative_quantlib_core_validate_non_negative_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidateValueRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/validate-in-range":{"post":{"tags":["quantlib-starter"],"summary":"Validate In Range","operationId":"validate_in_range_quantlib_core_validate_in_range_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidateRangeRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-fixed-leg":{"post":{"tags":["quantlib-starter"],"summary":"Create Fixed Leg","operationId":"create_fixed_leg_quantlib_core_create_fixed_leg_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFixedLegRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-float-leg":{"post":{"tags":["quantlib-starter"],"summary":"Create Float Leg","operationId":"create_float_leg_quantlib_core_create_float_leg_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFixedLegRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-zero-coupon-leg":{"post":{"tags":["quantlib-starter"],"summary":"Create Zero Coupon Leg","operationId":"create_zero_coupon_leg_quantlib_core_create_zero_coupon_leg_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFixedLegRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-amortizing-leg":{"post":{"tags":["quantlib-starter"],"summary":"Create Amortizing Leg","operationId":"create_amortizing_leg_quantlib_core_create_amortizing_leg_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFixedLegRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-compounding-leg":{"post":{"tags":["quantlib-starter"],"summary":"Create Compounding Leg","operationId":"create_compounding_leg_quantlib_core_create_compounding_leg_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFixedLegRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-inflation-leg":{"post":{"tags":["quantlib-starter"],"summary":"Create Inflation Leg","operationId":"create_inflation_leg_quantlib_core_create_inflation_leg_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFixedLegRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-custom-leg":{"post":{"tags":["quantlib-starter"],"summary":"Create Custom Leg","operationId":"create_custom_leg_quantlib_core_create_custom_leg_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFixedLegRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-credit-premium-leg":{"post":{"tags":["quantlib-starter"],"summary":"Create Credit Premium Leg","operationId":"create_credit_premium_leg_quantlib_core_create_credit_premium_leg_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFixedLegRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-fixed-period":{"post":{"tags":["quantlib-starter"],"summary":"Create Fixed Period","operationId":"create_fixed_period_quantlib_core_create_fixed_period_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFixedPeriodRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-float-period":{"post":{"tags":["quantlib-starter"],"summary":"Create Float Period","operationId":"create_float_period_quantlib_core_create_float_period_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFixedPeriodRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-inflation-period":{"post":{"tags":["quantlib-starter"],"summary":"Create Inflation Period","operationId":"create_inflation_period_quantlib_core_create_inflation_period_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFixedPeriodRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-compounded-rfr-period":{"post":{"tags":["quantlib-starter"],"summary":"Create Compounded Rfr Period","operationId":"create_compounded_rfr_period_quantlib_core_create_compounded_rfr_period_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFixedPeriodRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-credit-protection-period":{"post":{"tags":["quantlib-starter"],"summary":"Create Credit Protection Period","operationId":"create_credit_protection_period_quantlib_core_create_credit_protection_period_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFixedPeriodRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-notional-schedule":{"post":{"tags":["quantlib-starter"],"summary":"Create Notional Schedule","operationId":"create_notional_schedule_quantlib_core_create_notional_schedule_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateNotionalScheduleRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-fee-payment":{"post":{"tags":["quantlib-starter"],"summary":"Create Fee Payment","operationId":"create_fee_payment_quantlib_core_create_fee_payment_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateFeePaymentRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/create-principal-exchange":{"post":{"tags":["quantlib-starter"],"summary":"Create Principal Exchange","operationId":"create_principal_exchange_quantlib_core_create_principal_exchange_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreatePrincipalExchangeRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/total-cashflows":{"post":{"tags":["quantlib-starter"],"summary":"Total Cashflows Endpoint","operationId":"total_cashflows_endpoint_quantlib_core_total_cashflows_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CashflowsRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/total-npv":{"post":{"tags":["quantlib-starter"],"summary":"Total Npv Endpoint","operationId":"total_npv_endpoint_quantlib_core_total_npv_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CashflowsRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/to-datetime":{"post":{"tags":["quantlib-starter"],"summary":"To Datetime Endpoint","operationId":"to_datetime_endpoint_quantlib_core_to_datetime_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ToDateTimeRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/enums/rate-units":{"get":{"tags":["quantlib-starter"],"summary":"Get Rate Units","operationId":"get_rate_units_quantlib_core_enums_rate_units_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/enums/compounding-methods":{"get":{"tags":["quantlib-starter"],"summary":"Get Compounding Methods","operationId":"get_compounding_methods_quantlib_core_enums_compounding_methods_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/enums/notional-types":{"get":{"tags":["quantlib-starter"],"summary":"Get Notional Types","operationId":"get_notional_types_quantlib_core_enums_notional_types_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/enums/observation-methods":{"get":{"tags":["quantlib-starter"],"summary":"Get Observation Methods","operationId":"get_observation_methods_quantlib_core_enums_observation_methods_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/enums/exchange-types":{"get":{"tags":["quantlib-starter"],"summary":"Get Exchange Types","operationId":"get_exchange_types_quantlib_core_enums_exchange_types_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/enums/stub-types":{"get":{"tags":["quantlib-starter"],"summary":"Get Stub Types","operationId":"get_stub_types_quantlib_core_enums_stub_types_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/enums/fixing-types":{"get":{"tags":["quantlib-starter"],"summary":"Get Fixing Types","operationId":"get_fixing_types_quantlib_core_enums_fixing_types_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/numba-available":{"get":{"tags":["quantlib-starter"],"summary":"Get Numba Status","operationId":"get_numba_status_quantlib_core_numba_available_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/submodules/legs":{"get":{"tags":["quantlib-starter"],"summary":"Get Legs Module","operationId":"get_legs_module_quantlib_core_submodules_legs_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/submodules/periods":{"get":{"tags":["quantlib-starter"],"summary":"Get Periods Module","operationId":"get_periods_module_quantlib_core_submodules_periods_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/submodules/types":{"get":{"tags":["quantlib-starter"],"summary":"Get Types Module","operationId":"get_types_module_quantlib_core_submodules_types_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/submodules/autodiff":{"get":{"tags":["quantlib-starter"],"summary":"Get Autodiff Module","operationId":"get_autodiff_module_quantlib_core_submodules_autodiff_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/submodules/math-utils":{"get":{"tags":["quantlib-starter"],"summary":"Get Math Utils Module","operationId":"get_math_utils_module_quantlib_core_submodules_math_utils_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/submodules/numba-ops":{"get":{"tags":["quantlib-starter"],"summary":"Get Numba Ops Module","operationId":"get_numba_ops_module_quantlib_core_submodules_numba_ops_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/core/compounding-methods":{"get":{"tags":["quantlib-starter"],"summary":"Get Compounding Methods","description":"Get available compounding method values","operationId":"get_compounding_methods_quantlib_core_compounding_methods_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/core/exchange-types":{"get":{"tags":["quantlib-starter"],"summary":"Get Exchange Types","description":"Get available exchange type values","operationId":"get_exchange_types_quantlib_core_exchange_types_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/core/fixing-types":{"get":{"tags":["quantlib-starter"],"summary":"Get Fixing Types","description":"Get available fixing type values","operationId":"get_fixing_types_quantlib_core_fixing_types_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/core/notional-types":{"get":{"tags":["quantlib-starter"],"summary":"Get Notional Types","description":"Get available notional type values","operationId":"get_notional_types_quantlib_core_notional_types_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/core/observation-methods":{"get":{"tags":["quantlib-starter"],"summary":"Get Observation Methods","description":"Get available observation method values","operationId":"get_observation_methods_quantlib_core_observation_methods_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/core/stub-types":{"get":{"tags":["quantlib-starter"],"summary":"Get Stub Types","description":"Get available stub type values","operationId":"get_stub_types_quantlib_core_stub_types_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/core/base-leg-info":{"get":{"tags":["quantlib-starter"],"summary":"Get Base Leg Info","description":"Get documentation for BaseLeg abstract class","operationId":"get_base_leg_info_quantlib_core_base_leg_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/core/base-period-info":{"get":{"tags":["quantlib-starter"],"summary":"Get Base Period Info","description":"Get documentation for BasePeriod abstract class","operationId":"get_base_period_info_quantlib_core_base_period_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/fx/info":{"get":{"tags":["quantlib-starter"],"summary":"Fx Module Info","description":"FX module information","operationId":"fx_module_info_quantlib_fx_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/fx/create-fx-quote":{"post":{"tags":["quantlib-starter"],"summary":"Create Fx Quote","operationId":"create_fx_quote_quantlib_fx_create_fx_quote_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FXQuoteRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/fx/create-fx-forward-quote":{"post":{"tags":["quantlib-starter"],"summary":"Create Fx Forward Quote","operationId":"create_fx_forward_quote_quantlib_fx_create_fx_forward_quote_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FXForwardQuoteRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/fx/enums/quote-conventions":{"get":{"tags":["quantlib-starter"],"summary":"Get Quote Conventions","operationId":"get_quote_conventions_quantlib_fx_enums_quote_conventions_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/fx/create-rate-matrix":{"post":{"tags":["quantlib-starter"],"summary":"Create Rate Matrix","operationId":"create_rate_matrix_quantlib_fx_create_rate_matrix_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FXRateMatrixRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/fx/create-forward-calculator":{"post":{"tags":["quantlib-starter"],"summary":"Create Forward Calculator","operationId":"create_forward_calculator_quantlib_fx_create_forward_calculator_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FXForwardCalculatorRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/fx/calculate-forward-points":{"post":{"tags":["quantlib-starter"],"summary":"Calculate Forward Points Endpoint","operationId":"calculate_forward_points_endpoint_quantlib_fx_calculate_forward_points_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FXForwardPointsRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/fx/calculate-outright-forward":{"post":{"tags":["quantlib-starter"],"summary":"Calculate Outright Forward Endpoint","operationId":"calculate_outright_forward_endpoint_quantlib_fx_calculate_outright_forward_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FXOutrightForwardRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/fx/submodules/rates":{"get":{"tags":["quantlib-starter"],"summary":"Get Rates Module","operationId":"get_rates_module_quantlib_fx_submodules_rates_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/fx/submodules/forwards":{"get":{"tags":["quantlib-starter"],"summary":"Get Forwards Module","operationId":"get_forwards_module_quantlib_fx_submodules_forwards_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/fx/quote-conventions":{"get":{"tags":["quantlib-starter"],"summary":"Get Quote Conventions","description":"Get available FX quote convention values","operationId":"get_quote_conventions_quantlib_fx_quote_conventions_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/instruments/info":{"get":{"tags":["quantlib-professional"],"summary":"Instruments Module Info","description":"Instruments module information","operationId":"instruments_module_info_quantlib_instruments_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/instruments/create-bond":{"post":{"tags":["quantlib-professional"],"summary":"Create Bond","operationId":"create_bond_quantlib_instruments_create_bond_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BondRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-fixed-rate-bond":{"post":{"tags":["quantlib-professional"],"summary":"Create Fixed Rate Bond","operationId":"create_fixed_rate_bond_quantlib_instruments_create_fixed_rate_bond_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FixedRateBondRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-floating-rate-bond":{"post":{"tags":["quantlib-professional"],"summary":"Create Floating Rate Bond","operationId":"create_floating_rate_bond_quantlib_instruments_create_floating_rate_bond_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FloatingRateBondRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-zero-coupon-bond":{"post":{"tags":["quantlib-professional"],"summary":"Create Zero Coupon Bond","operationId":"create_zero_coupon_bond_quantlib_instruments_create_zero_coupon_bond_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ZeroCouponBondRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-call-provision":{"post":{"tags":["quantlib-professional"],"summary":"Create Call Provision","operationId":"create_call_provision_quantlib_instruments_create_call_provision_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CallProvisionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-call-schedule":{"post":{"tags":["quantlib-professional"],"summary":"Create Call Schedule","operationId":"create_call_schedule_quantlib_instruments_create_call_schedule_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CallScheduleRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-callable-bond":{"post":{"tags":["quantlib-professional"],"summary":"Create Callable Bond","operationId":"create_callable_bond_quantlib_instruments_create_callable_bond_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CallableBondRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-callable-puttable-bond":{"post":{"tags":["quantlib-professional"],"summary":"Create Callable Puttable Bond","operationId":"create_callable_puttable_bond_quantlib_instruments_create_callable_puttable_bond_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CallablePuttableBondRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-bond-price-result":{"post":{"tags":["quantlib-professional"],"summary":"Create Bond Price Result","operationId":"create_bond_price_result_quantlib_instruments_create_bond_price_result_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BondPriceResultRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-interest-rate-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Interest Rate Swap","operationId":"create_interest_rate_swap_quantlib_instruments_create_interest_rate_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/InterestRateSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-basis-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Basis Swap","operationId":"create_basis_swap_quantlib_instruments_create_basis_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BasisSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-cross-currency-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Cross Currency Swap","operationId":"create_cross_currency_swap_quantlib_instruments_create_cross_currency_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CrossCurrencySwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-cross-currency-basis-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Cross Currency Basis Swap","operationId":"create_cross_currency_basis_swap_quantlib_instruments_create_cross_currency_basis_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CrossCurrencyBasisSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-amortizing-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Amortizing Swap","operationId":"create_amortizing_swap_quantlib_instruments_create_amortizing_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AmortizingSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-compounded-rfr-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Compounded Rfr Swap","operationId":"create_compounded_rfr_swap_quantlib_instruments_create_compounded_rfr_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CompoundedRFRSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-sofr-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Sofr Swap Endpoint","operationId":"create_sofr_swap_endpoint_quantlib_instruments_create_sofr_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/InterestRateSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-sonia-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Sonia Swap Endpoint","operationId":"create_sonia_swap_endpoint_quantlib_instruments_create_sonia_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/InterestRateSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-estr-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Estr Swap Endpoint","operationId":"create_estr_swap_endpoint_quantlib_instruments_create_estr_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/InterestRateSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-cms-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Cms Swap","operationId":"create_cms_swap_quantlib_instruments_create_cms_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CMSSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-callable-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Callable Swap","operationId":"create_callable_swap_quantlib_instruments_create_callable_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CallableSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-callable-puttable-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Callable Puttable Swap","operationId":"create_callable_puttable_swap_quantlib_instruments_create_callable_puttable_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CallablePuttableSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-capped-floored-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Capped Floored Swap","operationId":"create_capped_floored_swap_quantlib_instruments_create_capped_floored_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CappedFlooredSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-vanilla-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Vanilla Option","operationId":"create_vanilla_option_quantlib_instruments_create_vanilla_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VanillaOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-barrier-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Barrier Option","operationId":"create_barrier_option_quantlib_instruments_create_barrier_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BarrierOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-discrete-barrier-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Discrete Barrier Option","operationId":"create_discrete_barrier_option_quantlib_instruments_create_discrete_barrier_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DiscreteBarrierOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-double-barrier-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Double Barrier Option","operationId":"create_double_barrier_option_quantlib_instruments_create_double_barrier_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DoubleBarrierOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-asian-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Asian Option","operationId":"create_asian_option_quantlib_instruments_create_asian_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AsianOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-arithmetic-asian-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Arithmetic Asian Option","operationId":"create_arithmetic_asian_option_quantlib_instruments_create_arithmetic_asian_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ArithmeticAsianOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-digital-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Digital Option","operationId":"create_digital_option_quantlib_instruments_create_digital_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DigitalOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-lookback-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Lookback Option","operationId":"create_lookback_option_quantlib_instruments_create_lookback_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LookbackOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-chooser-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Chooser Option","operationId":"create_chooser_option_quantlib_instruments_create_chooser_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ChooserOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-compound-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Compound Option","operationId":"create_compound_option_quantlib_instruments_create_compound_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CompoundOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-rainbow-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Rainbow Option","operationId":"create_rainbow_option_quantlib_instruments_create_rainbow_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RainbowOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-quanto-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Quanto Option","operationId":"create_quanto_option_quantlib_instruments_create_quanto_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/QuantoOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-cap":{"post":{"tags":["quantlib-professional"],"summary":"Create Cap","operationId":"create_cap_quantlib_instruments_create_cap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-floor":{"post":{"tags":["quantlib-professional"],"summary":"Create Floor","operationId":"create_floor_quantlib_instruments_create_floor_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FloorRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-collar":{"post":{"tags":["quantlib-professional"],"summary":"Create Collar","operationId":"create_collar_quantlib_instruments_create_collar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CollarRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-swaption":{"post":{"tags":["quantlib-professional"],"summary":"Create Swaption","operationId":"create_swaption_quantlib_instruments_create_swaption_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SwaptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-tarn":{"post":{"tags":["quantlib-professional"],"summary":"Create Tarn","operationId":"create_tarn_quantlib_instruments_create_tarn_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TARNRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-bond-future":{"post":{"tags":["quantlib-professional"],"summary":"Create Bond Future","operationId":"create_bond_future_quantlib_instruments_create_bond_future_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BondFutureRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-commodity-future":{"post":{"tags":["quantlib-professional"],"summary":"Create Commodity Future","operationId":"create_commodity_future_quantlib_instruments_create_commodity_future_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CommodityFutureRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-fra":{"post":{"tags":["quantlib-professional"],"summary":"Create Fra","operationId":"create_fra_quantlib_instruments_create_fra_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FRARequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-forward":{"post":{"tags":["quantlib-professional"],"summary":"Create Forward","operationId":"create_forward_quantlib_instruments_create_forward_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForwardRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-futures-contract":{"post":{"tags":["quantlib-professional"],"summary":"Create Futures Contract","operationId":"create_futures_contract_quantlib_instruments_create_futures_contract_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FuturesContractRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-credit-default-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Credit Default Swap","operationId":"create_credit_default_swap_quantlib_instruments_create_credit_default_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreditDefaultSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-cds-bootstrap":{"post":{"tags":["quantlib-professional"],"summary":"Create Cds Bootstrap","operationId":"create_cds_bootstrap_quantlib_instruments_create_cds_bootstrap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CDSBootstrapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-cds-result":{"post":{"tags":["quantlib-professional"],"summary":"Create Cds Result","operationId":"create_cds_result_quantlib_instruments_create_cds_result_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CDSResultRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-constant-hazard-rate":{"post":{"tags":["quantlib-professional"],"summary":"Create Constant Hazard Rate","operationId":"create_constant_hazard_rate_quantlib_instruments_create_constant_hazard_rate_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConstantHazardRateRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-total-return-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Total Return Swap","operationId":"create_total_return_swap_quantlib_instruments_create_total_return_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TotalReturnSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-credit-linked-note":{"post":{"tags":["quantlib-professional"],"summary":"Create Credit Linked Note","operationId":"create_credit_linked_note_quantlib_instruments_create_credit_linked_note_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreditLinkedNoteRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-first-to-default-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create First To Default Swap","operationId":"create_first_to_default_swap_quantlib_instruments_create_first_to_default_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FirstToDefaultSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-nth-to-default-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Nth To Default Swap","operationId":"create_nth_to_default_swap_quantlib_instruments_create_nth_to_default_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/NthToDefaultSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-asset-backed-security":{"post":{"tags":["quantlib-professional"],"summary":"Create Asset Backed Security","operationId":"create_asset_backed_security_quantlib_instruments_create_asset_backed_security_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AssetBackedSecurityRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-mortgage-backed-security":{"post":{"tags":["quantlib-professional"],"summary":"Create Mortgage Backed Security","operationId":"create_mortgage_backed_security_quantlib_instruments_create_mortgage_backed_security_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MortgageBackedSecurityRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-cdo":{"post":{"tags":["quantlib-professional"],"summary":"Create Cdo","operationId":"create_cdo_quantlib_instruments_create_cdo_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CDORequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-clo":{"post":{"tags":["quantlib-professional"],"summary":"Create Clo","operationId":"create_clo_quantlib_instruments_create_clo_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CLORequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-tranche":{"post":{"tags":["quantlib-professional"],"summary":"Create Tranche","operationId":"create_tranche_quantlib_instruments_create_tranche_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TrancheRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-convertible-bond":{"post":{"tags":["quantlib-professional"],"summary":"Create Convertible Bond","operationId":"create_convertible_bond_quantlib_instruments_create_convertible_bond_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConvertibleBondRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-conversion-terms":{"post":{"tags":["quantlib-professional"],"summary":"Create Conversion Terms","operationId":"create_conversion_terms_quantlib_instruments_create_conversion_terms_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConversionTermsRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-conversion-trigger":{"post":{"tags":["quantlib-professional"],"summary":"Create Conversion Trigger","operationId":"create_conversion_trigger_quantlib_instruments_create_conversion_trigger_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ConversionTriggerRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-mandatory-convertible":{"post":{"tags":["quantlib-professional"],"summary":"Create Mandatory Convertible","operationId":"create_mandatory_convertible_quantlib_instruments_create_mandatory_convertible_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MandatoryConvertibleRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-reverse-convertible":{"post":{"tags":["quantlib-professional"],"summary":"Create Reverse Convertible","operationId":"create_reverse_convertible_quantlib_instruments_create_reverse_convertible_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ReverseConvertibleRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-commodity-index":{"post":{"tags":["quantlib-professional"],"summary":"Create Commodity Index","operationId":"create_commodity_index_quantlib_instruments_create_commodity_index_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CommodityIndexRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-commodity-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Commodity Option","operationId":"create_commodity_option_quantlib_instruments_create_commodity_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CommodityOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-commodity-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Commodity Swap","operationId":"create_commodity_swap_quantlib_instruments_create_commodity_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CommoditySwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-weather-derivative":{"post":{"tags":["quantlib-professional"],"summary":"Create Weather Derivative","operationId":"create_weather_derivative_quantlib_instruments_create_weather_derivative_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/WeatherDerivativeRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/calculate-degree-days":{"post":{"tags":["quantlib-professional"],"summary":"Calculate Degree Days Endpoint","operationId":"calculate_degree_days_endpoint_quantlib_instruments_calculate_degree_days_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-equity-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Equity Swap","operationId":"create_equity_swap_quantlib_instruments_create_equity_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EquitySwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-variance-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Variance Swap","operationId":"create_variance_swap_quantlib_instruments_create_variance_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VarianceSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-volatility-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Volatility Swap","operationId":"create_volatility_swap_quantlib_instruments_create_volatility_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VolatilitySwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-fx-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Fx Option","operationId":"create_fx_option_quantlib_instruments_create_fx_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FXOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-fx-forward":{"post":{"tags":["quantlib-professional"],"summary":"Create Fx Forward","operationId":"create_fx_forward_quantlib_instruments_create_fx_forward_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FXForwardRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-deposit":{"post":{"tags":["quantlib-professional"],"summary":"Create Deposit","operationId":"create_deposit_quantlib_instruments_create_deposit_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DepositRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-commercial-paper":{"post":{"tags":["quantlib-professional"],"summary":"Create Commercial Paper","operationId":"create_commercial_paper_quantlib_instruments_create_commercial_paper_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CommercialPaperRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-certificate-of-deposit":{"post":{"tags":["quantlib-professional"],"summary":"Create Certificate Of Deposit","operationId":"create_certificate_of_deposit_quantlib_instruments_create_certificate_of_deposit_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CertificateOfDepositRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-catastrophe-bond":{"post":{"tags":["quantlib-professional"],"summary":"Create Catastrophe Bond","operationId":"create_catastrophe_bond_quantlib_instruments_create_catastrophe_bond_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CatastropheBondRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-inflation-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Inflation Swap","operationId":"create_inflation_swap_quantlib_instruments_create_inflation_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/InflationSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-treasury-bill":{"post":{"tags":["quantlib-professional"],"summary":"Create Treasury Bill","operationId":"create_treasury_bill_quantlib_instruments_create_treasury_bill_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TreasuryBillRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-repo":{"post":{"tags":["quantlib-professional"],"summary":"Create Repo","operationId":"create_repo_quantlib_instruments_create_repo_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RepoRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-stir-future":{"post":{"tags":["quantlib-professional"],"summary":"Create Stir Future","operationId":"create_stir_future_quantlib_instruments_create_stir_future_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/STIRFutureRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-overnight-index-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Overnight Index Swap","operationId":"create_overnight_index_swap_quantlib_instruments_create_overnight_index_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OvernightIndexSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-tenor-basis-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Tenor Basis Swap","operationId":"create_tenor_basis_swap_quantlib_instruments_create_tenor_basis_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TenorBasisSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-single-currency-basis-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Single Currency Basis Swap","operationId":"create_single_currency_basis_swap_quantlib_instruments_create_single_currency_basis_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SingleCurrencyBasisSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-rfr-basis-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Rfr Basis Swap","operationId":"create_rfr_basis_swap_quantlib_instruments_create_rfr_basis_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RFRBasisSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-zero-coupon-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Zero Coupon Swap","operationId":"create_zero_coupon_swap_quantlib_instruments_create_zero_coupon_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ZeroCouponSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-zero-zero-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Zero Zero Swap","operationId":"create_zero_zero_swap_quantlib_instruments_create_zero_zero_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ZeroZeroSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-range-accrual-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Range Accrual Swap","operationId":"create_range_accrual_swap_quantlib_instruments_create_range_accrual_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RangeAccrualSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-mtm-cross-currency-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Mtm Cross Currency Swap","operationId":"create_mtm_cross_currency_swap_quantlib_instruments_create_mtm_cross_currency_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MTMCrossCurrencySwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-puttable-bond":{"post":{"tags":["quantlib-professional"],"summary":"Create Puttable Bond","operationId":"create_puttable_bond_quantlib_instruments_create_puttable_bond_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PuttableBondRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-puttable-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Puttable Swap","operationId":"create_puttable_swap_quantlib_instruments_create_puttable_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PuttableSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-inflation-linked-bond":{"post":{"tags":["quantlib-professional"],"summary":"Create Inflation Linked Bond","operationId":"create_inflation_linked_bond_quantlib_instruments_create_inflation_linked_bond_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/InflationLinkedBondRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-inflation-indexed-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Inflation Indexed Swap","operationId":"create_inflation_indexed_swap_quantlib_instruments_create_inflation_indexed_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/InflationIndexedSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-year-on-year-inflation-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Year On Year Inflation Swap","operationId":"create_year_on_year_inflation_swap_quantlib_instruments_create_year_on_year_inflation_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/YearOnYearInflationSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-zero-coupon-inflation-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Zero Coupon Inflation Swap","operationId":"create_zero_coupon_inflation_swap_quantlib_instruments_create_zero_coupon_inflation_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ZeroCouponInflationSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-forward-start-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Forward Start Option","operationId":"create_forward_start_option_quantlib_instruments_create_forward_start_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ForwardStartOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-spread-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Spread Option","operationId":"create_spread_option_quantlib_instruments_create_spread_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SpreadOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-exchange-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Exchange Option","operationId":"create_exchange_option_quantlib_instruments_create_exchange_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExchangeOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-fx-swap":{"post":{"tags":["quantlib-professional"],"summary":"Create Fx Swap","operationId":"create_fx_swap_quantlib_instruments_create_fx_swap_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FXSwapRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-fx-spot":{"post":{"tags":["quantlib-professional"],"summary":"Create Fx Spot","operationId":"create_fx_spot_quantlib_instruments_create_fx_spot_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FXSpotRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-option-result":{"post":{"tags":["quantlib-professional"],"summary":"Create Option Result","operationId":"create_option_result_quantlib_instruments_create_option_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-fra-result":{"post":{"tags":["quantlib-professional"],"summary":"Create Fra Result","operationId":"create_fra_result_quantlib_instruments_create_fra_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-futures-result":{"post":{"tags":["quantlib-professional"],"summary":"Create Futures Result","operationId":"create_futures_result_quantlib_instruments_create_futures_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-fx-forward-result":{"post":{"tags":["quantlib-professional"],"summary":"Create Fx Forward Result","operationId":"create_fx_forward_result_quantlib_instruments_create_fx_forward_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-fx-option-result":{"post":{"tags":["quantlib-professional"],"summary":"Create Fx Option Result","operationId":"create_fx_option_result_quantlib_instruments_create_fx_option_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-xccy-result":{"post":{"tags":["quantlib-professional"],"summary":"Create Xccy Result","operationId":"create_xccy_result_quantlib_instruments_create_xccy_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-xccy-swap-result":{"post":{"tags":["quantlib-professional"],"summary":"Create Xccy Swap Result","operationId":"create_xccy_swap_result_quantlib_instruments_create_xccy_swap_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-fixed-leg":{"post":{"tags":["quantlib-professional"],"summary":"Create Fixed Leg","operationId":"create_fixed_leg_quantlib_instruments_create_fixed_leg_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-floating-leg":{"post":{"tags":["quantlib-professional"],"summary":"Create Floating Leg","operationId":"create_floating_leg_quantlib_instruments_create_floating_leg_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-notional-schedule":{"post":{"tags":["quantlib-professional"],"summary":"Create Notional Schedule","operationId":"create_notional_schedule_quantlib_instruments_create_notional_schedule_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-put-provision":{"post":{"tags":["quantlib-professional"],"summary":"Create Put Provision","operationId":"create_put_provision_quantlib_instruments_create_put_provision_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-put-schedule":{"post":{"tags":["quantlib-professional"],"summary":"Create Put Schedule","operationId":"create_put_schedule_quantlib_instruments_create_put_schedule_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-fixed-strike-lookback":{"post":{"tags":["quantlib-professional"],"summary":"Create Fixed Strike Lookback","operationId":"create_fixed_strike_lookback_quantlib_instruments_create_fixed_strike_lookback_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FixedStrikeLookbackRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-floating-strike-lookback":{"post":{"tags":["quantlib-professional"],"summary":"Create Floating Strike Lookback","operationId":"create_floating_strike_lookback_quantlib_instruments_create_floating_strike_lookback_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FloatingStrikeLookbackRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-geometric-asian-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Geometric Asian Option","operationId":"create_geometric_asian_option_quantlib_instruments_create_geometric_asian_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GeometricAsianOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-hazard-rate-curve":{"post":{"tags":["quantlib-professional"],"summary":"Create Hazard Rate Curve","operationId":"create_hazard_rate_curve_quantlib_instruments_create_hazard_rate_curve_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-piecewise-hazard-rate":{"post":{"tags":["quantlib-professional"],"summary":"Create Piecewise Hazard Rate","operationId":"create_piecewise_hazard_rate_quantlib_instruments_create_piecewise_hazard_rate_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-survival-curve":{"post":{"tags":["quantlib-professional"],"summary":"Create Survival Curve","operationId":"create_survival_curve_quantlib_instruments_create_survival_curve_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-forward-rate-agreement":{"post":{"tags":["quantlib-professional"],"summary":"Create Forward Rate Agreement","operationId":"create_forward_rate_agreement_quantlib_instruments_create_forward_rate_agreement_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FRARequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-mortgage-pool":{"post":{"tags":["quantlib-professional"],"summary":"Create Mortgage Pool","operationId":"create_mortgage_pool_quantlib_instruments_create_mortgage_pool_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-prepayment-model":{"post":{"tags":["quantlib-professional"],"summary":"Create Prepayment Model","operationId":"create_prepayment_model_quantlib_instruments_create_prepayment_model_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-notional-step":{"post":{"tags":["quantlib-professional"],"summary":"Create Notional Step","operationId":"create_notional_step_quantlib_instruments_create_notional_step_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-exercise-schedule":{"post":{"tags":["quantlib-professional"],"summary":"Create Exercise Schedule","operationId":"create_exercise_schedule_quantlib_instruments_create_exercise_schedule_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-exotic-barrier-option":{"post":{"tags":["quantlib-professional"],"summary":"Create Exotic Barrier Option","operationId":"create_exotic_barrier_option_quantlib_instruments_create_exotic_barrier_option_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExoticBarrierOptionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-ois-index":{"post":{"tags":["quantlib-professional"],"summary":"Create Ois Index","operationId":"create_ois_index_quantlib_instruments_create_ois_index_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-ffvsofr-basis":{"post":{"tags":["quantlib-professional"],"summary":"Create Ffvsofr Basis","operationId":"create_ffvsofr_basis_quantlib_instruments_create_ffvsofr_basis_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-weather-index":{"post":{"tags":["quantlib-professional"],"summary":"Create Weather Index","operationId":"create_weather_index_quantlib_instruments_create_weather_index_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/WeatherIndexRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/create-weather-measurement":{"post":{"tags":["quantlib-professional"],"summary":"Create Weather Measurement","operationId":"create_weather_measurement_quantlib_instruments_create_weather_measurement_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/enums/option-type":{"get":{"tags":["quantlib-professional"],"summary":"Get Option Type Enum","operationId":"get_option_type_enum_quantlib_instruments_enums_option_type_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/enums/barrier-type":{"get":{"tags":["quantlib-professional"],"summary":"Get Barrier Type Enum","operationId":"get_barrier_type_enum_quantlib_instruments_enums_barrier_type_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/enums/averaging-type":{"get":{"tags":["quantlib-professional"],"summary":"Get Averaging Type Enum","operationId":"get_averaging_type_enum_quantlib_instruments_enums_averaging_type_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/enums/commodity-type":{"get":{"tags":["quantlib-professional"],"summary":"Get Commodity Type Enum","operationId":"get_commodity_type_enum_quantlib_instruments_enums_commodity_type_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/enums/compounding-method":{"get":{"tags":["quantlib-professional"],"summary":"Get Compounding Method Enum","operationId":"get_compounding_method_enum_quantlib_instruments_enums_compounding_method_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/enums/exercise-type":{"get":{"tags":["quantlib-professional"],"summary":"Get Exercise Type Enum","operationId":"get_exercise_type_enum_quantlib_instruments_enums_exercise_type_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/enums/option-style":{"get":{"tags":["quantlib-professional"],"summary":"Get Option Style Enum","operationId":"get_option_style_enum_quantlib_instruments_enums_option_style_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/enums/swaption-type":{"get":{"tags":["quantlib-professional"],"summary":"Get Swaption Type Enum","operationId":"get_swaption_type_enum_quantlib_instruments_enums_swaption_type_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/enums/swap-type":{"get":{"tags":["quantlib-professional"],"summary":"Get Swap Type Enum","operationId":"get_swap_type_enum_quantlib_instruments_enums_swap_type_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/enums/notional-type":{"get":{"tags":["quantlib-professional"],"summary":"Get Notional Type Enum","operationId":"get_notional_type_enum_quantlib_instruments_enums_notional_type_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/enums/mbs-type":{"get":{"tags":["quantlib-professional"],"summary":"Get Mbs Type Enum","operationId":"get_mbs_type_enum_quantlib_instruments_enums_mbs_type_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/enums/xccy-swap-type":{"get":{"tags":["quantlib-professional"],"summary":"Get Xccy Swap Type Enum","operationId":"get_xccy_swap_type_enum_quantlib_instruments_enums_xccy_swap_type_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/enums/exotic-barrier-type":{"get":{"tags":["quantlib-professional"],"summary":"Get Exotic Barrier Type Enum","operationId":"get_exotic_barrier_type_enum_quantlib_instruments_enums_exotic_barrier_type_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/enums/observation-shift":{"get":{"tags":["quantlib-professional"],"summary":"Get Observation Shift Enum","operationId":"get_observation_shift_enum_quantlib_instruments_enums_observation_shift_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/calculate-realized-variance":{"post":{"tags":["quantlib-professional"],"summary":"Calculate Realized Variance Endpoint","operationId":"calculate_realized_variance_endpoint_quantlib_instruments_calculate_realized_variance_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RealizedVarianceRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/calculate-realized-volatility":{"post":{"tags":["quantlib-professional"],"summary":"Calculate Realized Volatility Endpoint","operationId":"calculate_realized_volatility_endpoint_quantlib_instruments_calculate_realized_volatility_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RealizedVarianceRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/submodules/bonds":{"get":{"tags":["quantlib-professional"],"summary":"Get Bonds Submodule","operationId":"get_bonds_submodule_quantlib_instruments_submodules_bonds_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/submodules/rates":{"get":{"tags":["quantlib-professional"],"summary":"Get Rates Submodule","operationId":"get_rates_submodule_quantlib_instruments_submodules_rates_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/submodules/exotics":{"get":{"tags":["quantlib-professional"],"summary":"Get Exotics Submodule","operationId":"get_exotics_submodule_quantlib_instruments_submodules_exotics_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/submodules/credit":{"get":{"tags":["quantlib-professional"],"summary":"Get Credit Submodule","operationId":"get_credit_submodule_quantlib_instruments_submodules_credit_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/submodules/securitization":{"get":{"tags":["quantlib-professional"],"summary":"Get Securitization Submodule","operationId":"get_securitization_submodule_quantlib_instruments_submodules_securitization_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/submodules/convertible":{"get":{"tags":["quantlib-professional"],"summary":"Get Convertible Submodule","operationId":"get_convertible_submodule_quantlib_instruments_submodules_convertible_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/submodules/commodity":{"get":{"tags":["quantlib-professional"],"summary":"Get Commodity Submodule","operationId":"get_commodity_submodule_quantlib_instruments_submodules_commodity_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/submodules/equity":{"get":{"tags":["quantlib-professional"],"summary":"Get Equity Submodule","operationId":"get_equity_submodule_quantlib_instruments_submodules_equity_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/submodules/fx":{"get":{"tags":["quantlib-professional"],"summary":"Get Fx Submodule","operationId":"get_fx_submodule_quantlib_instruments_submodules_fx_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/submodules/embedded-options":{"get":{"tags":["quantlib-professional"],"summary":"Get Embedded Options Submodule","operationId":"get_embedded_options_submodule_quantlib_instruments_submodules_embedded_options_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/submodules/money-market":{"get":{"tags":["quantlib-professional"],"summary":"Get Money Market Submodule","operationId":"get_money_market_submodule_quantlib_instruments_submodules_money_market_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/submodules/alternative":{"get":{"tags":["quantlib-professional"],"summary":"Get Alternative Submodule","operationId":"get_alternative_submodule_quantlib_instruments_submodules_alternative_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/submodules/math":{"get":{"tags":["quantlib-professional"],"summary":"Get Math Submodule","operationId":"get_math_submodule_quantlib_instruments_submodules_math_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/instruments/degree-days":{"post":{"tags":["quantlib-professional"],"summary":"Degree Days Endpoint","operationId":"degree_days_endpoint_quantlib_instruments_degree_days_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/volatility/info":{"get":{"tags":["quantlib-professional"],"summary":"Volatility Module Info","description":"Volatility module information","operationId":"volatility_module_info_quantlib_volatility_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/volatility/create-flat-volatility":{"post":{"tags":["quantlib-professional"],"summary":"Create Flat Volatility","operationId":"create_flat_volatility_quantlib_volatility_create_flat_volatility_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FlatVolatilityRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/volatility/create-volatility-surface":{"post":{"tags":["quantlib-professional"],"summary":"Create Volatility Surface","operationId":"create_volatility_surface_quantlib_volatility_create_volatility_surface_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VolatilitySurfaceRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/volatility/create-volatility-cube":{"post":{"tags":["quantlib-professional"],"summary":"Create Volatility Cube","operationId":"create_volatility_cube_quantlib_volatility_create_volatility_cube_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VolatilityCubeRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/volatility/create-term-structure-volatility":{"post":{"tags":["quantlib-professional"],"summary":"Create Term Structure Volatility","operationId":"create_term_structure_volatility_quantlib_volatility_create_term_structure_volatility_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TermStructureVolatilityRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/volatility/create-local-volatility":{"post":{"tags":["quantlib-professional"],"summary":"Create Local Volatility","operationId":"create_local_volatility_quantlib_volatility_create_local_volatility_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LocalVolatilityRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/volatility/create-dupire-local-vol":{"post":{"tags":["quantlib-professional"],"summary":"Create Dupire Local Vol","operationId":"create_dupire_local_vol_quantlib_volatility_create_dupire_local_vol_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DupireLocalVolRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/volatility/create-sabr-parameters":{"post":{"tags":["quantlib-professional"],"summary":"Create Sabr Parameters","operationId":"create_sabr_parameters_quantlib_volatility_create_sabr_parameters_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SABRParametersRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/volatility/create-sabr-model":{"post":{"tags":["quantlib-professional"],"summary":"Create Sabr Model","operationId":"create_sabr_model_quantlib_volatility_create_sabr_model_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SABRModelRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/volatility/sabr-implied-vol":{"post":{"tags":["quantlib-professional"],"summary":"Sabr Implied Vol Endpoint","operationId":"sabr_implied_vol_endpoint_quantlib_volatility_sabr_implied_vol_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SABRImpliedVolRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/volatility/calibrate-sabr":{"post":{"tags":["quantlib-professional"],"summary":"Calibrate Sabr Endpoint","operationId":"calibrate_sabr_endpoint_quantlib_volatility_calibrate_sabr_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CalibrateSABRRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/volatility/submodules/surface":{"get":{"tags":["quantlib-professional"],"summary":"Get Surface Submodule","operationId":"get_surface_submodule_quantlib_volatility_submodules_surface_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/volatility/submodules/sabr":{"get":{"tags":["quantlib-professional"],"summary":"Get Sabr Submodule","operationId":"get_sabr_submodule_quantlib_volatility_submodules_sabr_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/volatility/submodules/local-vol":{"get":{"tags":["quantlib-professional"],"summary":"Get Local Vol Submodule","operationId":"get_local_vol_submodule_quantlib_volatility_submodules_local_vol_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/solver/info":{"get":{"tags":["quantlib-professional"],"summary":"Solver Module Info","description":"Solver module information","operationId":"solver_module_info_quantlib_solver_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/solver/create-brent-solver":{"post":{"tags":["quantlib-professional"],"summary":"Create Brent Solver","operationId":"create_brent_solver_quantlib_solver_create_brent_solver_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BrentSolverRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/solver/create-newton-raphson":{"post":{"tags":["quantlib-professional"],"summary":"Create Newton Raphson","operationId":"create_newton_raphson_quantlib_solver_create_newton_raphson_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_solver__NewtonRaphsonRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/solver/create-levenberg-marquardt":{"post":{"tags":["quantlib-professional"],"summary":"Create Levenberg Marquardt","operationId":"create_levenberg_marquardt_quantlib_solver_create_levenberg_marquardt_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LevenbergMarquardtRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/solver/create-gauss-newton":{"post":{"tags":["quantlib-professional"],"summary":"Create Gauss Newton","operationId":"create_gauss_newton_quantlib_solver_create_gauss_newton_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GaussNewtonRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/solver/create-bootstrap-config":{"post":{"tags":["quantlib-professional"],"summary":"Create Bootstrap Config","operationId":"create_bootstrap_config_quantlib_solver_create_bootstrap_config_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BootstrapConfigRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/solver/create-curve-solver":{"post":{"tags":["quantlib-professional"],"summary":"Create Curve Solver","operationId":"create_curve_solver_quantlib_solver_create_curve_solver_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CurveSolverRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/solver/create-calibration-result":{"post":{"tags":["quantlib-professional"],"summary":"Create Calibration Result","operationId":"create_calibration_result_quantlib_solver_create_calibration_result_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CalibrationResultRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/solver/bootstrap-curve":{"post":{"tags":["quantlib-professional"],"summary":"Bootstrap Curve Endpoint","operationId":"bootstrap_curve_endpoint_quantlib_solver_bootstrap_curve_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BootstrapCurveRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/solver/submodules/bootstrap":{"get":{"tags":["quantlib-professional"],"summary":"Get Bootstrap Submodule","operationId":"get_bootstrap_submodule_quantlib_solver_submodules_bootstrap_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/solver/submodules/optimizer":{"get":{"tags":["quantlib-professional"],"summary":"Get Optimizer Submodule","operationId":"get_optimizer_submodule_quantlib_solver_submodules_optimizer_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/info":{"get":{"tags":["quantlib-professional"],"summary":"Portfolio Module Info","description":"Portfolio module information","operationId":"portfolio_module_info_quantlib_portfolio_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/portfolio/create-portfolio-constraints":{"post":{"tags":["quantlib-professional"],"summary":"Create Portfolio Constraints","operationId":"create_portfolio_constraints_quantlib_portfolio_create_portfolio_constraints_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PortfolioConstraintsRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/create-mean-variance-optimizer":{"post":{"tags":["quantlib-professional"],"summary":"Create Mean Variance Optimizer","operationId":"create_mean_variance_optimizer_quantlib_portfolio_create_mean_variance_optimizer_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MeanVarianceOptimizerRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/create-optimization-result":{"post":{"tags":["quantlib-professional"],"summary":"Create Optimization Result","operationId":"create_optimization_result_quantlib_portfolio_create_optimization_result_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OptimizationResultRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/create-portfolio-risk":{"post":{"tags":["quantlib-professional"],"summary":"Create Portfolio Risk","operationId":"create_portfolio_risk_quantlib_portfolio_create_portfolio_risk_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/PortfolioRiskRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/create-risk-parity":{"post":{"tags":["quantlib-professional"],"summary":"Create Risk Parity","operationId":"create_risk_parity_quantlib_portfolio_create_risk_parity_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RiskParityRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/create-equal-risk-contribution":{"post":{"tags":["quantlib-professional"],"summary":"Create Equal Risk Contribution","operationId":"create_equal_risk_contribution_quantlib_portfolio_create_equal_risk_contribution_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EqualRiskContributionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/create-hierarchical-risk-parity":{"post":{"tags":["quantlib-professional"],"summary":"Create Hierarchical Risk Parity","operationId":"create_hierarchical_risk_parity_quantlib_portfolio_create_hierarchical_risk_parity_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HierarchicalRiskParityRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/create-view":{"post":{"tags":["quantlib-professional"],"summary":"Create View","operationId":"create_view_quantlib_portfolio_create_view_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ViewRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/create-black-litterman":{"post":{"tags":["quantlib-professional"],"summary":"Create Black Litterman","operationId":"create_black_litterman_quantlib_portfolio_create_black_litterman_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BlackLittermanRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/enums/view-type":{"get":{"tags":["quantlib-professional"],"summary":"Get View Type Enum","operationId":"get_view_type_enum_quantlib_portfolio_enums_view_type_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/min-variance-portfolio":{"post":{"tags":["quantlib-professional"],"summary":"Min Variance Portfolio Endpoint","operationId":"min_variance_portfolio_endpoint_quantlib_portfolio_min_variance_portfolio_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MinVariancePortfolioRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/max-sharpe-portfolio":{"post":{"tags":["quantlib-professional"],"summary":"Max Sharpe Portfolio Endpoint","operationId":"max_sharpe_portfolio_endpoint_quantlib_portfolio_max_sharpe_portfolio_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MaxSharpePortfolioRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/target-return-portfolio":{"post":{"tags":["quantlib-professional"],"summary":"Target Return Portfolio Endpoint","operationId":"target_return_portfolio_endpoint_quantlib_portfolio_target_return_portfolio_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TargetReturnPortfolioRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/efficient-frontier":{"post":{"tags":["quantlib-professional"],"summary":"Efficient Frontier Endpoint","operationId":"efficient_frontier_endpoint_quantlib_portfolio_efficient_frontier_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EfficientFrontierRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/equilibrium-returns":{"post":{"tags":["quantlib-professional"],"summary":"Equilibrium Returns Endpoint","operationId":"equilibrium_returns_endpoint_quantlib_portfolio_equilibrium_returns_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/EquilibriumReturnsRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/calculate-var":{"post":{"tags":["quantlib-professional"],"summary":"Calculate Var Endpoint","operationId":"calculate_var_endpoint_quantlib_portfolio_calculate_var_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_risk__VaRRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/calculate-cvar":{"post":{"tags":["quantlib-professional"],"summary":"Calculate Cvar Endpoint","operationId":"calculate_cvar_endpoint_quantlib_portfolio_calculate_cvar_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CVaRRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/marginal-risk-contribution":{"post":{"tags":["quantlib-professional"],"summary":"Marginal Risk Contribution Endpoint","operationId":"marginal_risk_contribution_endpoint_quantlib_portfolio_marginal_risk_contribution_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MarginalRiskContributionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/component-risk":{"post":{"tags":["quantlib-professional"],"summary":"Component Risk Endpoint","operationId":"component_risk_endpoint_quantlib_portfolio_component_risk_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ComponentRiskRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/submodules/optimization":{"get":{"tags":["quantlib-professional"],"summary":"Get Optimization Submodule","operationId":"get_optimization_submodule_quantlib_portfolio_submodules_optimization_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/submodules/risk-metrics":{"get":{"tags":["quantlib-professional"],"summary":"Get Risk Metrics Submodule","operationId":"get_risk_metrics_submodule_quantlib_portfolio_submodules_risk_metrics_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/submodules/black-litterman":{"get":{"tags":["quantlib-professional"],"summary":"Get Black Litterman Submodule","operationId":"get_black_litterman_submodule_quantlib_portfolio_submodules_black_litterman_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/portfolio/submodules/risk-parity":{"get":{"tags":["quantlib-professional"],"summary":"Get Risk Parity Submodule","operationId":"get_risk_parity_submodule_quantlib_portfolio_submodules_risk_parity_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/info":{"get":{"tags":["quantlib-enterprise"],"summary":"Models Module Info","description":"Models module information","operationId":"models_module_info_quantlib_models_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/models/create-heston-parameters":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Heston Parameters","operationId":"create_heston_parameters_quantlib_models_create_heston_parameters_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HestonParametersRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-heston-model":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Heston Model","operationId":"create_heston_model_quantlib_models_create_heston_model_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HestonModelRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-heston-pricer":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Heston Pricer","operationId":"create_heston_pricer_quantlib_models_create_heston_pricer_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HestonModelRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-sabr-parameters":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Sabr Parameters Enhanced","operationId":"create_sabr_parameters_enhanced_quantlib_models_create_sabr_parameters_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SABRParametersEnhancedRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-sabr-model-enhanced":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Sabr Model Enhanced","operationId":"create_sabr_model_enhanced_quantlib_models_create_sabr_model_enhanced_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SABRModelEnhancedRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-svi":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Svi","operationId":"create_svi_quantlib_models_create_svi_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SVIRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-ssvi":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Ssvi","operationId":"create_ssvi_quantlib_models_create_ssvi_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SSVIRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-dupire-local-vol":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Dupire Local Vol Model","operationId":"create_dupire_local_vol_model_quantlib_models_create_dupire_local_vol_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-short-rate-parameters":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Short Rate Parameters","operationId":"create_short_rate_parameters_quantlib_models_create_short_rate_parameters_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ShortRateParametersRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-vasicek-model":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Vasicek Model","operationId":"create_vasicek_model_quantlib_models_create_vasicek_model_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VasicekModelRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-vasicek":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Vasicek Function","operationId":"create_vasicek_function_quantlib_models_create_vasicek_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VasicekModelRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-hull-white-model":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Hull White Model","operationId":"create_hull_white_model_quantlib_models_create_hull_white_model_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HullWhiteModelRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-hull-white":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Hull White Function","operationId":"create_hull_white_function_quantlib_models_create_hull_white_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HullWhiteModelRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-cir-model":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Cir Model","operationId":"create_cir_model_quantlib_models_create_cir_model_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CIRModelRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-cir":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Cir Function","operationId":"create_cir_function_quantlib_models_create_cir_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CIRModelRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-black-karasinski-model":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Black Karasinski Model","operationId":"create_black_karasinski_model_quantlib_models_create_black_karasinski_model_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BlackKarasinskiModelRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-merton-parameters":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Merton Parameters","operationId":"create_merton_parameters_quantlib_models_create_merton_parameters_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MertonParametersRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-merton-jump-diffusion":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Merton Jump Diffusion","operationId":"create_merton_jump_diffusion_quantlib_models_create_merton_jump_diffusion_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MertonJumpDiffusionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/merton-call-price":{"post":{"tags":["quantlib-enterprise"],"summary":"Merton Call Price Endpoint","operationId":"merton_call_price_endpoint_quantlib_models_merton_call_price_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MertonCallPriceRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-kou-parameters":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Kou Parameters","operationId":"create_kou_parameters_quantlib_models_create_kou_parameters_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/KouParametersRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-kou-jump-diffusion":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Kou Jump Diffusion","operationId":"create_kou_jump_diffusion_quantlib_models_create_kou_jump_diffusion_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/KouJumpDiffusionRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/kou-call-price":{"post":{"tags":["quantlib-enterprise"],"summary":"Kou Call Price Endpoint","operationId":"kou_call_price_endpoint_quantlib_models_kou_call_price_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/KouCallPriceRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-vg-parameters":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Vg Parameters","operationId":"create_vg_parameters_quantlib_models_create_vg_parameters_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VGParametersRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-variance-gamma":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Variance Gamma","operationId":"create_variance_gamma_quantlib_models_create_variance_gamma_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VarianceGammaRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/vg-call-price":{"post":{"tags":["quantlib-enterprise"],"summary":"Vg Call Price Endpoint","operationId":"vg_call_price_endpoint_quantlib_models_vg_call_price_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/VGCallPriceRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-local-vol-surface":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Local Vol Surface","operationId":"create_local_vol_surface_quantlib_models_create_local_vol_surface_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-flat-local-vol":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Flat Local Vol Endpoint","operationId":"create_flat_local_vol_endpoint_quantlib_models_create_flat_local_vol_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/create-svi-local-vol":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Svi Local Vol Endpoint","operationId":"create_svi_local_vol_endpoint_quantlib_models_create_svi_local_vol_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/submodules/stochastic-vol":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Stochastic Vol Submodule","operationId":"get_stochastic_vol_submodule_quantlib_models_submodules_stochastic_vol_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/submodules/short-rate":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Short Rate Submodule","operationId":"get_short_rate_submodule_quantlib_models_submodules_short_rate_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/submodules/jump-diffusion":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Jump Diffusion Submodule","operationId":"get_jump_diffusion_submodule_quantlib_models_submodules_jump_diffusion_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/models/submodules/local-vol":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Local Vol Submodule","operationId":"get_local_vol_submodule_quantlib_models_submodules_local_vol_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/info":{"get":{"tags":["quantlib-enterprise"],"summary":"Risk Module Info","description":"Risk module information","operationId":"risk_module_info_quantlib_risk_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/risk/create-historical-var":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Historical Var","operationId":"create_historical_var_quantlib_risk_create_historical_var_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/HistoricalVaRRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-parametric-var":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Parametric Var","operationId":"create_parametric_var_quantlib_risk_create_parametric_var_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ParametricVaRRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-monte-carlo-var":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Monte Carlo Var","operationId":"create_monte_carlo_var_quantlib_risk_create_monte_carlo_var_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/MonteCarloVaRRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-component-var-calculator":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Component Var Calculator","operationId":"create_component_var_calculator_quantlib_risk_create_component_var_calculator_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/ComponentVaRCalculatorRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-component-var-result":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Component Var Result","operationId":"create_component_var_result_quantlib_risk_create_component_var_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-incremental-var-calculator":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Incremental Var Calculator","operationId":"create_incremental_var_calculator_quantlib_risk_create_incremental_var_calculator_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IncrementalVaRCalculatorRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-incremental-var-result":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Incremental Var Result","operationId":"create_incremental_var_result_quantlib_risk_create_incremental_var_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-liquidity-adjusted-var":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Liquidity Adjusted Var","operationId":"create_liquidity_adjusted_var_quantlib_risk_create_liquidity_adjusted_var_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LiquidityAdjustedVaRRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-liquidity-adjustment":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Liquidity Adjustment","operationId":"create_liquidity_adjustment_quantlib_risk_create_liquidity_adjustment_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-coherent-risk-measure":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Coherent Risk Measure","operationId":"create_coherent_risk_measure_quantlib_risk_create_coherent_risk_measure_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-credit-parameters":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Credit Parameters","operationId":"create_credit_parameters_quantlib_risk_create_credit_parameters_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreditParametersRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-funding-parameters":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Funding Parameters","operationId":"create_funding_parameters_quantlib_risk_create_funding_parameters_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FundingParametersRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-cva-calculator":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Cva Calculator","operationId":"create_cva_calculator_quantlib_risk_create_cva_calculator_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CVACalculatorRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-fva-calculator":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Fva Calculator","operationId":"create_fva_calculator_quantlib_risk_create_fva_calculator_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/FVACalculatorRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-kva-calculator":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Kva Calculator","operationId":"create_kva_calculator_quantlib_risk_create_kva_calculator_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-mva-calculator":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Mva Calculator","operationId":"create_mva_calculator_quantlib_risk_create_mva_calculator_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-vega-var":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Vega Var","operationId":"create_vega_var_quantlib_risk_create_vega_var_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-vol-of-vol-var":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Vol Of Vol Var","operationId":"create_vol_of_vol_var_quantlib_risk_create_vol_of_vol_var_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-xva-calculator":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Xva Calculator","operationId":"create_xva_calculator_quantlib_risk_create_xva_calculator_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-xva-result":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Xva Result","operationId":"create_xva_result_quantlib_risk_create_xva_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-correlation-scenario":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Correlation Scenario","operationId":"create_correlation_scenario_quantlib_risk_create_correlation_scenario_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-correlation-stress-tester":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Correlation Stress Tester","operationId":"create_correlation_stress_tester_quantlib_risk_create_correlation_stress_tester_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-scenario-builder":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Scenario Builder","operationId":"create_scenario_builder_quantlib_risk_create_scenario_builder_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-stress-scenario":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Stress Scenario","operationId":"create_stress_scenario_quantlib_risk_create_stress_scenario_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-stress-tester":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Stress Tester","operationId":"create_stress_tester_quantlib_risk_create_stress_tester_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-stress-test-result":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Stress Test Result","operationId":"create_stress_test_result_quantlib_risk_create_stress_test_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-backtest-result":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Backtest Result","operationId":"create_backtest_result_quantlib_risk_create_backtest_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/backtest-var-model":{"post":{"tags":["quantlib-enterprise"],"summary":"Backtest Var Model Endpoint","operationId":"backtest_var_model_endpoint_quantlib_risk_backtest_var_model_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BacktestVaRModelRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/calculate-delta":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Delta Endpoint","operationId":"calculate_delta_endpoint_quantlib_risk_calculate_delta_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GreeksRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/calculate-gamma":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Gamma Endpoint","operationId":"calculate_gamma_endpoint_quantlib_risk_calculate_gamma_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GreeksRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/calculate-vega":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Vega Endpoint","operationId":"calculate_vega_endpoint_quantlib_risk_calculate_vega_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GreeksRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/calculate-theta":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Theta Endpoint","operationId":"calculate_theta_endpoint_quantlib_risk_calculate_theta_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GreeksRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/calculate-rho":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Rho Endpoint","operationId":"calculate_rho_endpoint_quantlib_risk_calculate_rho_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GreeksRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/full-greeks":{"post":{"tags":["quantlib-enterprise"],"summary":"Full Greeks Endpoint","operationId":"full_greeks_endpoint_quantlib_risk_full_greeks_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GreeksRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/bucket-delta":{"post":{"tags":["quantlib-enterprise"],"summary":"Bucket Delta Endpoint","operationId":"bucket_delta_endpoint_quantlib_risk_bucket_delta_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/key-rate-duration":{"post":{"tags":["quantlib-enterprise"],"summary":"Key Rate Duration Endpoint","operationId":"key_rate_duration_endpoint_quantlib_risk_key_rate_duration_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/conditional-value-at-risk":{"post":{"tags":["quantlib-enterprise"],"summary":"Conditional Value At Risk Endpoint","operationId":"conditional_value_at_risk_endpoint_quantlib_risk_conditional_value_at_risk_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_risk__VaRRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/expected-shortfall-optimization":{"post":{"tags":["quantlib-enterprise"],"summary":"Expected Shortfall Optimization Endpoint","operationId":"expected_shortfall_optimization_endpoint_quantlib_risk_expected_shortfall_optimization_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/marginal-var":{"post":{"tags":["quantlib-enterprise"],"summary":"Marginal Var Endpoint","operationId":"marginal_var_endpoint_quantlib_risk_marginal_var_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/component-var":{"post":{"tags":["quantlib-enterprise"],"summary":"Component Var Endpoint","operationId":"component_var_endpoint_quantlib_risk_component_var_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/incremental-var":{"post":{"tags":["quantlib-enterprise"],"summary":"Incremental Var Endpoint","operationId":"incremental_var_endpoint_quantlib_risk_incremental_var_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/tail-conditional-expectation":{"post":{"tags":["quantlib-enterprise"],"summary":"Tail Conditional Expectation Endpoint","operationId":"tail_conditional_expectation_endpoint_quantlib_risk_tail_conditional_expectation_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_risk__VaRRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/tail-dependence-coefficient":{"post":{"tags":["quantlib-enterprise"],"summary":"Tail Dependence Coefficient Endpoint","operationId":"tail_dependence_coefficient_endpoint_quantlib_risk_tail_dependence_coefficient_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/worst-conditional-expectation":{"post":{"tags":["quantlib-enterprise"],"summary":"Worst Conditional Expectation Endpoint","operationId":"worst_conditional_expectation_endpoint_quantlib_risk_worst_conditional_expectation_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/quantlib_risk__VaRRequest"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-position":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Position","operationId":"create_position_quantlib_risk_create_position_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-portfolio":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Portfolio Risk","operationId":"create_portfolio_risk_quantlib_risk_create_portfolio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-portfolio-analytics":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Portfolio Analytics","operationId":"create_portfolio_analytics_quantlib_risk_create_portfolio_analytics_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-portfolio-risk-result":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Portfolio Risk Result","operationId":"create_portfolio_risk_result_quantlib_risk_create_portfolio_risk_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-scenario":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Scenario","operationId":"create_scenario_quantlib_risk_create_scenario_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-scenario-analysis":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Scenario Analysis","operationId":"create_scenario_analysis_quantlib_risk_create_scenario_analysis_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-stress-test":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Stress Test","operationId":"create_stress_test_quantlib_risk_create_stress_test_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-stress-result":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Stress Result","operationId":"create_stress_result_quantlib_risk_create_stress_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-tail-risk-analyzer":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Tail Risk Analyzer","operationId":"create_tail_risk_analyzer_quantlib_risk_create_tail_risk_analyzer_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-tail-risk-metrics":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Tail Risk Metrics","operationId":"create_tail_risk_metrics_quantlib_risk_create_tail_risk_metrics_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-var-backtester":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Var Backtester","operationId":"create_var_backtester_quantlib_risk_create_var_backtester_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-var-result":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Var Result","operationId":"create_var_result_quantlib_risk_create_var_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/create-xva-engine":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Xva Engine","operationId":"create_xva_engine_quantlib_risk_create_xva_engine_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/enums/scenario-type":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Scenario Type Enum","operationId":"get_scenario_type_enum_quantlib_risk_enums_scenario_type_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/enums/traffic-light-zone":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Traffic Light Zone Enum","operationId":"get_traffic_light_zone_enum_quantlib_risk_enums_traffic_light_zone_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/enums/asset-class":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Asset Class Enum","operationId":"get_asset_class_enum_quantlib_risk_enums_asset_class_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/submodules/var":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Var Submodule","operationId":"get_var_submodule_quantlib_risk_submodules_var_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/submodules/xva":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Xva Submodule","operationId":"get_xva_submodule_quantlib_risk_submodules_xva_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/submodules/sensitivities":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Sensitivities Submodule","operationId":"get_sensitivities_submodule_quantlib_risk_submodules_sensitivities_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/submodules/stress":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Stress Submodule","operationId":"get_stress_submodule_quantlib_risk_submodules_stress_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/submodules/tail-risk":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Tail Risk Submodule","operationId":"get_tail_risk_submodule_quantlib_risk_submodules_tail_risk_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/submodules/backtesting":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Backtesting Submodule","operationId":"get_backtesting_submodule_quantlib_risk_submodules_backtesting_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/submodules/portfolio":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Portfolio Submodule","operationId":"get_portfolio_submodule_quantlib_risk_submodules_portfolio_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/submodules/advanced-var":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Advanced Var Submodule","operationId":"get_advanced_var_submodule_quantlib_risk_submodules_advanced_var_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/risk/submodules/correlation-stress":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Correlation Stress Submodule","operationId":"get_correlation_stress_submodule_quantlib_risk_submodules_correlation_stress_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/info":{"get":{"tags":["quantlib-enterprise"],"summary":"Analysis Module Info","description":"Analysis module information","operationId":"analysis_module_info_quantlib_analysis_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/analysis/adjust-goodwill":{"post":{"tags":["quantlib-enterprise"],"summary":"Adjust Goodwill","operationId":"adjust_goodwill_quantlib_analysis_adjust_goodwill_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/adjust-pension":{"post":{"tags":["quantlib-enterprise"],"summary":"Adjust Pension","operationId":"adjust_pension_quantlib_analysis_adjust_pension_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/adjust-stock-compensation":{"post":{"tags":["quantlib-enterprise"],"summary":"Adjust Stock Compensation","operationId":"adjust_stock_compensation_quantlib_analysis_adjust_stock_compensation_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/adjusted-ffo":{"post":{"tags":["quantlib-enterprise"],"summary":"Adjusted Ffo","operationId":"adjusted_ffo_quantlib_analysis_adjusted_ffo_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/altman-z-score":{"post":{"tags":["quantlib-enterprise"],"summary":"Altman Z Score","operationId":"altman_z_score_quantlib_analysis_altman_z_score_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/altman-z-prime":{"post":{"tags":["quantlib-enterprise"],"summary":"Altman Z Prime","operationId":"altman_z_prime_quantlib_analysis_altman_z_prime_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/altman-z-double-prime":{"post":{"tags":["quantlib-enterprise"],"summary":"Altman Z Double Prime","operationId":"altman_z_double_prime_quantlib_analysis_altman_z_double_prime_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/asset-growth-factor":{"post":{"tags":["quantlib-enterprise"],"summary":"Asset Growth Factor","operationId":"asset_growth_factor_quantlib_analysis_asset_growth_factor_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/asset-turnover":{"post":{"tags":["quantlib-enterprise"],"summary":"Asset Turnover","operationId":"asset_turnover_quantlib_analysis_asset_turnover_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/beneish-m-score":{"post":{"tags":["quantlib-enterprise"],"summary":"Beneish M Score","operationId":"beneish_m_score_quantlib_analysis_beneish_m_score_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/breakup-value-analysis":{"post":{"tags":["quantlib-enterprise"],"summary":"Breakup Value Analysis","operationId":"breakup_value_analysis_quantlib_analysis_breakup_value_analysis_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/cagr":{"post":{"tags":["quantlib-enterprise"],"summary":"Cagr","operationId":"cagr_quantlib_analysis_cagr_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/calculate-factor-exposures":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Factor Exposures","operationId":"calculate_factor_exposures_quantlib_analysis_calculate_factor_exposures_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/calculate-ownership-dilution":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Ownership Dilution","operationId":"calculate_ownership_dilution_quantlib_analysis_calculate_ownership_dilution_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/capacity-factor":{"post":{"tags":["quantlib-enterprise"],"summary":"Capacity Factor","operationId":"capacity_factor_quantlib_analysis_capacity_factor_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/capitalize-operating-leases":{"post":{"tags":["quantlib-enterprise"],"summary":"Capitalize Operating Leases","operationId":"capitalize_operating_leases_quantlib_analysis_capitalize_operating_leases_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/capitalize-rd":{"post":{"tags":["quantlib-enterprise"],"summary":"Capitalize Rd","operationId":"capitalize_rd_quantlib_analysis_capitalize_rd_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/cash-conversion-cycle":{"post":{"tags":["quantlib-enterprise"],"summary":"Cash Conversion Cycle","operationId":"cash_conversion_cycle_quantlib_analysis_cash_conversion_cycle_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/cash-conversion-quality":{"post":{"tags":["quantlib-enterprise"],"summary":"Cash Conversion Quality","operationId":"cash_conversion_quality_quantlib_analysis_cash_conversion_quality_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/cash-flow-margin":{"post":{"tags":["quantlib-enterprise"],"summary":"Cash Flow Margin","operationId":"cash_flow_margin_quantlib_analysis_cash_flow_margin_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/cash-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Cash Ratio","operationId":"cash_ratio_quantlib_analysis_cash_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/cfroi":{"post":{"tags":["quantlib-enterprise"],"summary":"Cfroi","operationId":"cfroi_quantlib_analysis_cfroi_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/combined-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Combined Ratio","operationId":"combined_ratio_quantlib_analysis_combined_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/composite-quality-score":{"post":{"tags":["quantlib-enterprise"],"summary":"Composite Quality Score","operationId":"composite_quality_score_quantlib_analysis_composite_quality_score_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/composite-value-score":{"post":{"tags":["quantlib-enterprise"],"summary":"Composite Value Score","operationId":"composite_value_score_quantlib_analysis_composite_value_score_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/conglomerate-discount":{"post":{"tags":["quantlib-enterprise"],"summary":"Conglomerate Discount","operationId":"conglomerate_discount_quantlib_analysis_conglomerate_discount_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/cost-of-equity-capm":{"post":{"tags":["quantlib-enterprise"],"summary":"Cost Of Equity Capm","operationId":"cost_of_equity_capm_quantlib_analysis_cost_of_equity_capm_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/credit-spread-from-pd":{"post":{"tags":["quantlib-enterprise"],"summary":"Credit Spread From Pd","operationId":"credit_spread_from_pd_quantlib_analysis_credit_spread_from_pd_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/credit-spread-merton":{"post":{"tags":["quantlib-enterprise"],"summary":"Credit Spread Merton","operationId":"credit_spread_merton_quantlib_analysis_credit_spread_merton_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/current-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Current Ratio","operationId":"current_ratio_quantlib_analysis_current_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/days-inventory":{"post":{"tags":["quantlib-enterprise"],"summary":"Days Inventory","operationId":"days_inventory_quantlib_analysis_days_inventory_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/days-payables":{"post":{"tags":["quantlib-enterprise"],"summary":"Days Payables","operationId":"days_payables_quantlib_analysis_days_payables_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/days-receivables":{"post":{"tags":["quantlib-enterprise"],"summary":"Days Receivables","operationId":"days_receivables_quantlib_analysis_days_receivables_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/ddm-valuation":{"post":{"tags":["quantlib-enterprise"],"summary":"Ddm Valuation","operationId":"ddm_valuation_quantlib_analysis_ddm_valuation_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/debt-capacity":{"post":{"tags":["quantlib-enterprise"],"summary":"Debt Capacity","operationId":"debt_capacity_quantlib_analysis_debt_capacity_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/debt-service-coverage":{"post":{"tags":["quantlib-enterprise"],"summary":"Debt Service Coverage","operationId":"debt_service_coverage_quantlib_analysis_debt_service_coverage_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/debt-to-assets":{"post":{"tags":["quantlib-enterprise"],"summary":"Debt To Assets","operationId":"debt_to_assets_quantlib_analysis_debt_to_assets_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/debt-to-equity":{"post":{"tags":["quantlib-enterprise"],"summary":"Debt To Equity","operationId":"debt_to_equity_quantlib_analysis_debt_to_equity_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/defensive-interval":{"post":{"tags":["quantlib-enterprise"],"summary":"Defensive Interval","operationId":"defensive_interval_quantlib_analysis_defensive_interval_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/distance-to-default":{"post":{"tags":["quantlib-enterprise"],"summary":"Distance To Default","operationId":"distance_to_default_quantlib_analysis_distance_to_default_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/calculate-function":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Function","description":"Universal endpoint for all remaining analysis functions.\nPass 'function_name' and parameters in request body.\n\nSupported functions: dividend_yield, dupont_3_factor, dupont_5_factor, ebitda_margin,\neconomic_value_added, ev_to_ebitda, fcfe, fcff, gordon_growth_model, gross_margin,\ninterest_coverage, inventory_turnover, net_margin, operating_margin, payout_ratio,\npe_to_growth, piotroski_f_score, price_to_book, price_to_sales, quick_ratio,\nreturn_on_assets, return_on_equity, return_on_invested_capital, revenue_growth,\nsustainable_growth_rate, times_interest_earned, tobin_q, wacc, working_capital,\nand 67 more...","operationId":"calculate_function_quantlib_analysis_calculate_function_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-financial-analyzer":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Financial Analyzer","operationId":"create_financial_analyzer_quantlib_analysis_create_financial_analyzer_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-dcf-model":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Dcf Model","operationId":"create_dcf_model_quantlib_analysis_create_dcf_model_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-dupont-analysis":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Dupont Analysis","operationId":"create_dupont_analysis_quantlib_analysis_create_dupont_analysis_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-credit-analysis":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Credit Analysis","operationId":"create_credit_analysis_quantlib_analysis_create_credit_analysis_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-valuation-analysis":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Valuation Analysis","operationId":"create_valuation_analysis_quantlib_analysis_create_valuation_analysis_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-comparable-analysis":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Comparable Analysis","operationId":"create_comparable_analysis_quantlib_analysis_create_comparable_analysis_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-financial-statements":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Financial Statements","operationId":"create_financial_statements_quantlib_analysis_create_financial_statements_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-balance-sheet":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Balance Sheet","operationId":"create_balance_sheet_quantlib_analysis_create_balance_sheet_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-income-statement":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Income Statement","operationId":"create_income_statement_quantlib_analysis_create_income_statement_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-cash-flow-statement":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Cash Flow Statement","operationId":"create_cash_flow_statement_quantlib_analysis_create_cash_flow_statement_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-class-instance":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Class Instance","description":"Universal endpoint for creating instances of analysis classes.\nPass 'class_name' and constructor parameters in request body.\n\nSupported classes: Company, CompanyFundamentals, AnalysisReport, ValuationResult,\nProfitabilityAnalysis, LiquidityAnalysis, SolvencyAnalysis, EfficiencyAnalysis,\nGrowthAnalysis, CashFlowAnalysis, CapitalStructureAnalysis, SegmentAnalysis,\nFactorAnalysis, BankingAnalysis, InsuranceAnalysis, REITAnalysis, UtilityAnalysis,\nand 36 more...","operationId":"create_class_instance_quantlib_analysis_create_class_instance_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/valuation":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Valuation Submodule","operationId":"get_valuation_submodule_quantlib_analysis_submodules_valuation_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/credit":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Credit Submodule","operationId":"get_credit_submodule_quantlib_analysis_submodules_credit_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/quality":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Quality Submodule","operationId":"get_quality_submodule_quantlib_analysis_submodules_quality_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/dcf":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Dcf Submodule","operationId":"get_dcf_submodule_quantlib_analysis_submodules_dcf_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/dupont":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Dupont Submodule","operationId":"get_dupont_submodule_quantlib_analysis_submodules_dupont_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/comparable":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Comparable Submodule","operationId":"get_comparable_submodule_quantlib_analysis_submodules_comparable_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/profitability":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Profitability Submodule","operationId":"get_profitability_submodule_quantlib_analysis_submodules_profitability_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/liquidity":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Liquidity Submodule","operationId":"get_liquidity_submodule_quantlib_analysis_submodules_liquidity_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/solvency":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Solvency Submodule","operationId":"get_solvency_submodule_quantlib_analysis_submodules_solvency_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/efficiency":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Efficiency Submodule","operationId":"get_efficiency_submodule_quantlib_analysis_submodules_efficiency_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/growth":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Growth Submodule","operationId":"get_growth_submodule_quantlib_analysis_submodules_growth_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/cashflow":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Cashflow Submodule","operationId":"get_cashflow_submodule_quantlib_analysis_submodules_cashflow_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/capital-structure":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Capital Structure Submodule","operationId":"get_capital_structure_submodule_quantlib_analysis_submodules_capital_structure_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/comprehensive":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Comprehensive Submodule","operationId":"get_comprehensive_submodule_quantlib_analysis_submodules_comprehensive_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/factor-models":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Factor Models Submodule","operationId":"get_factor_models_submodule_quantlib_analysis_submodules_factor_models_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/industry":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Industry Submodule","operationId":"get_industry_submodule_quantlib_analysis_submodules_industry_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/predictive":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Predictive Submodule","operationId":"get_predictive_submodule_quantlib_analysis_submodules_predictive_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/proforma":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Proforma Submodule","operationId":"get_proforma_submodule_quantlib_analysis_submodules_proforma_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/segment":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Segment Submodule","operationId":"get_segment_submodule_quantlib_analysis_submodules_segment_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/startup":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Startup Submodule","operationId":"get_startup_submodule_quantlib_analysis_submodules_startup_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/submodules/statements":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Statements Submodule","operationId":"get_statements_submodule_quantlib_analysis_submodules_statements_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/gross-margin":{"post":{"tags":["quantlib-enterprise"],"summary":"Gross Margin Endpoint","operationId":"gross_margin_endpoint_quantlib_analysis_gross_margin_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/operating-margin":{"post":{"tags":["quantlib-enterprise"],"summary":"Operating Margin Endpoint","operationId":"operating_margin_endpoint_quantlib_analysis_operating_margin_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/net-margin":{"post":{"tags":["quantlib-enterprise"],"summary":"Net Margin Endpoint","operationId":"net_margin_endpoint_quantlib_analysis_net_margin_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/return-on-assets":{"post":{"tags":["quantlib-enterprise"],"summary":"Return On Assets Endpoint","operationId":"return_on_assets_endpoint_quantlib_analysis_return_on_assets_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/return-on-equity":{"post":{"tags":["quantlib-enterprise"],"summary":"Return On Equity Endpoint","operationId":"return_on_equity_endpoint_quantlib_analysis_return_on_equity_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/return-on-invested-capital":{"post":{"tags":["quantlib-enterprise"],"summary":"Return On Invested Capital Endpoint","operationId":"return_on_invested_capital_endpoint_quantlib_analysis_return_on_invested_capital_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/return-on-capital-employed":{"post":{"tags":["quantlib-enterprise"],"summary":"Return On Capital Employed Endpoint","operationId":"return_on_capital_employed_endpoint_quantlib_analysis_return_on_capital_employed_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/inventory-turnover":{"post":{"tags":["quantlib-enterprise"],"summary":"Inventory Turnover Endpoint","operationId":"inventory_turnover_endpoint_quantlib_analysis_inventory_turnover_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/receivables-turnover":{"post":{"tags":["quantlib-enterprise"],"summary":"Receivables Turnover Endpoint","operationId":"receivables_turnover_endpoint_quantlib_analysis_receivables_turnover_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/payables-turnover":{"post":{"tags":["quantlib-enterprise"],"summary":"Payables Turnover Endpoint","operationId":"payables_turnover_endpoint_quantlib_analysis_payables_turnover_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/interest-coverage":{"post":{"tags":["quantlib-enterprise"],"summary":"Interest Coverage Endpoint","operationId":"interest_coverage_endpoint_quantlib_analysis_interest_coverage_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/quick-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Quick Ratio Endpoint","operationId":"quick_ratio_endpoint_quantlib_analysis_quick_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/invested-capital":{"post":{"tags":["quantlib-enterprise"],"summary":"Invested Capital Endpoint","operationId":"invested_capital_endpoint_quantlib_analysis_invested_capital_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/nopat":{"post":{"tags":["quantlib-enterprise"],"summary":"Nopat Endpoint","operationId":"nopat_endpoint_quantlib_analysis_nopat_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/wacc":{"post":{"tags":["quantlib-enterprise"],"summary":"Wacc Endpoint","operationId":"wacc_endpoint_quantlib_analysis_wacc_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/sustainable-growth-rate":{"post":{"tags":["quantlib-enterprise"],"summary":"Sustainable Growth Rate Endpoint","operationId":"sustainable_growth_rate_endpoint_quantlib_analysis_sustainable_growth_rate_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/internal-growth-rate":{"post":{"tags":["quantlib-enterprise"],"summary":"Internal Growth Rate Endpoint","operationId":"internal_growth_rate_endpoint_quantlib_analysis_internal_growth_rate_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/price-to-earnings":{"post":{"tags":["quantlib-enterprise"],"summary":"Price To Earnings Endpoint","operationId":"price_to_earnings_endpoint_quantlib_analysis_price_to_earnings_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/price-to-book":{"post":{"tags":["quantlib-enterprise"],"summary":"Price To Book Endpoint","operationId":"price_to_book_endpoint_quantlib_analysis_price_to_book_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/price-to-sales":{"post":{"tags":["quantlib-enterprise"],"summary":"Price To Sales Endpoint","operationId":"price_to_sales_endpoint_quantlib_analysis_price_to_sales_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/peg-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Peg Ratio Endpoint","operationId":"peg_ratio_endpoint_quantlib_analysis_peg_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/market-value-added":{"post":{"tags":["quantlib-enterprise"],"summary":"Market Value Added Endpoint","operationId":"market_value_added_endpoint_quantlib_analysis_market_value_added_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/two-stage-dcf":{"post":{"tags":["quantlib-enterprise"],"summary":"Two Stage Dcf Endpoint","operationId":"two_stage_dcf_endpoint_quantlib_analysis_two_stage_dcf_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/three-stage-dcf":{"post":{"tags":["quantlib-enterprise"],"summary":"Three Stage Dcf Endpoint","operationId":"three_stage_dcf_endpoint_quantlib_analysis_three_stage_dcf_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/terminal-value-perpetuity":{"post":{"tags":["quantlib-enterprise"],"summary":"Terminal Value Perpetuity Endpoint","operationId":"terminal_value_perpetuity_endpoint_quantlib_analysis_terminal_value_perpetuity_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/terminal-value-exit-multiple":{"post":{"tags":["quantlib-enterprise"],"summary":"Terminal Value Exit Multiple Endpoint","operationId":"terminal_value_exit_multiple_endpoint_quantlib_analysis_terminal_value_exit_multiple_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/two-stage-ddm":{"post":{"tags":["quantlib-enterprise"],"summary":"Two Stage Ddm Endpoint","operationId":"two_stage_ddm_endpoint_quantlib_analysis_two_stage_ddm_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/residual-income-valuation":{"post":{"tags":["quantlib-enterprise"],"summary":"Residual Income Valuation Endpoint","operationId":"residual_income_valuation_endpoint_quantlib_analysis_residual_income_valuation_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/residual-income":{"post":{"tags":["quantlib-enterprise"],"summary":"Residual Income Endpoint","operationId":"residual_income_endpoint_quantlib_analysis_residual_income_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/relative-valuation":{"post":{"tags":["quantlib-enterprise"],"summary":"Relative Valuation Endpoint","operationId":"relative_valuation_endpoint_quantlib_analysis_relative_valuation_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/sum-of-the-parts":{"post":{"tags":["quantlib-enterprise"],"summary":"Sum Of The Parts Endpoint","operationId":"sum_of_the_parts_endpoint_quantlib_analysis_sum_of_the_parts_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/justified-pb-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Justified Pb Ratio Endpoint","operationId":"justified_pb_ratio_endpoint_quantlib_analysis_justified_pb_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/three-stage-dcf-fade":{"post":{"tags":["quantlib-enterprise"],"summary":"Three Stage Dcf Fade Endpoint","operationId":"three_stage_dcf_fade_endpoint_quantlib_analysis_three_stage_dcf_fade_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/n-stage-dcf":{"post":{"tags":["quantlib-enterprise"],"summary":"N Stage Dcf Endpoint","operationId":"n_stage_dcf_endpoint_quantlib_analysis_n_stage_dcf_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/peer-comparison":{"post":{"tags":["quantlib-enterprise"],"summary":"Peer Comparison Endpoint","operationId":"peer_comparison_endpoint_quantlib_analysis_peer_comparison_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/quality-of-earnings":{"post":{"tags":["quantlib-enterprise"],"summary":"Quality Of Earnings Endpoint","operationId":"quality_of_earnings_endpoint_quantlib_analysis_quality_of_earnings_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/normalize-earnings":{"post":{"tags":["quantlib-enterprise"],"summary":"Normalize Earnings Endpoint","operationId":"normalize_earnings_endpoint_quantlib_analysis_normalize_earnings_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/lifo-to-fifo-adjustment":{"post":{"tags":["quantlib-enterprise"],"summary":"Lifo To Fifo Adjustment Endpoint","operationId":"lifo_to_fifo_adjustment_endpoint_quantlib_analysis_lifo_to_fifo_adjustment_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/segment-profitability":{"post":{"tags":["quantlib-enterprise"],"summary":"Segment Profitability Endpoint","operationId":"segment_profitability_endpoint_quantlib_analysis_segment_profitability_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/size-factor":{"post":{"tags":["quantlib-enterprise"],"summary":"Size Factor Endpoint","operationId":"size_factor_endpoint_quantlib_analysis_size_factor_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/sloan-accruals-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Sloan Accruals Ratio Endpoint","operationId":"sloan_accruals_ratio_endpoint_quantlib_analysis_sloan_accruals_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/ohlson-o-score":{"post":{"tags":["quantlib-enterprise"],"summary":"Ohlson O Score Endpoint","operationId":"ohlson_o_score_endpoint_quantlib_analysis_ohlson_o_score_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/piotroski-f-score":{"post":{"tags":["quantlib-enterprise"],"summary":"Piotroski F Score Endpoint","operationId":"piotroski_f_score_endpoint_quantlib_analysis_piotroski_f_score_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/springate-score":{"post":{"tags":["quantlib-enterprise"],"summary":"Springate Score Endpoint","operationId":"springate_score_endpoint_quantlib_analysis_springate_score_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/zmijewski-score":{"post":{"tags":["quantlib-enterprise"],"summary":"Zmijewski Score Endpoint","operationId":"zmijewski_score_endpoint_quantlib_analysis_zmijewski_score_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/percentile-rank":{"post":{"tags":["quantlib-enterprise"],"summary":"Percentile Rank Endpoint","operationId":"percentile_rank_endpoint_quantlib_analysis_percentile_rank_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/optimal-debt-ratio-tradeoff":{"post":{"tags":["quantlib-enterprise"],"summary":"Optimal Debt Ratio Tradeoff Endpoint","operationId":"optimal_debt_ratio_tradeoff_endpoint_quantlib_analysis_optimal_debt_ratio_tradeoff_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/wacc-minimization":{"post":{"tags":["quantlib-enterprise"],"summary":"Wacc Minimization Endpoint","operationId":"wacc_minimization_endpoint_quantlib_analysis_wacc_minimization_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/mm-proposition-2":{"post":{"tags":["quantlib-enterprise"],"summary":"Mm Proposition 2 Endpoint","operationId":"mm_proposition_2_endpoint_quantlib_analysis_mm_proposition_2_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/loan-to-deposit-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Loan To Deposit Ratio Endpoint","operationId":"loan_to_deposit_ratio_endpoint_quantlib_analysis_loan_to_deposit_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/non-performing-loan-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Non Performing Loan Ratio Endpoint","operationId":"non_performing_loan_ratio_endpoint_quantlib_analysis_non_performing_loan_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/net-interest-margin":{"post":{"tags":["quantlib-enterprise"],"summary":"Net Interest Margin Endpoint","operationId":"net_interest_margin_endpoint_quantlib_analysis_net_interest_margin_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/tier1-capital-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Tier1 Capital Ratio Endpoint","operationId":"tier1_capital_ratio_endpoint_quantlib_analysis_tier1_capital_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/price-to-ffo":{"post":{"tags":["quantlib-enterprise"],"summary":"Price To Ffo Endpoint","operationId":"price_to_ffo_endpoint_quantlib_analysis_price_to_ffo_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/net-asset-value":{"post":{"tags":["quantlib-enterprise"],"summary":"Net Asset Value Endpoint","operationId":"net_asset_value_endpoint_quantlib_analysis_net_asset_value_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/implied-cap-rate":{"post":{"tags":["quantlib-enterprise"],"summary":"Implied Cap Rate Endpoint","operationId":"implied_cap_rate_endpoint_quantlib_analysis_implied_cap_rate_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/loss-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Loss Ratio Endpoint","operationId":"loss_ratio_endpoint_quantlib_analysis_loss_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/premium-to-surplus":{"post":{"tags":["quantlib-enterprise"],"summary":"Premium To Surplus Endpoint","operationId":"premium_to_surplus_endpoint_quantlib_analysis_premium_to_surplus_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/rate-base":{"post":{"tags":["quantlib-enterprise"],"summary":"Rate Base Endpoint","operationId":"rate_base_endpoint_quantlib_analysis_rate_base_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/earned-return-on-rate-base":{"post":{"tags":["quantlib-enterprise"],"summary":"Earned Return On Rate Base Endpoint","operationId":"earned_return_on_rate_base_endpoint_quantlib_analysis_earned_return_on_rate_base_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/merton-model":{"post":{"tags":["quantlib-enterprise"],"summary":"Merton Model Endpoint","operationId":"merton_model_endpoint_quantlib_analysis_merton_model_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/probability-of-default-from-dd":{"post":{"tags":["quantlib-enterprise"],"summary":"Probability Of Default From Dd Endpoint","operationId":"probability_of_default_from_dd_endpoint_quantlib_analysis_probability_of_default_from_dd_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/unexpected-loss":{"post":{"tags":["quantlib-enterprise"],"summary":"Unexpected Loss Endpoint","operationId":"unexpected_loss_endpoint_quantlib_analysis_unexpected_loss_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/pd-to-rating":{"post":{"tags":["quantlib-enterprise"],"summary":"Pd To Rating Endpoint","operationId":"pd_to_rating_endpoint_quantlib_analysis_pd_to_rating_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/rating-to-pd":{"post":{"tags":["quantlib-enterprise"],"summary":"Rating To Pd Endpoint","operationId":"rating_to_pd_endpoint_quantlib_analysis_rating_to_pd_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/tax-shield-value":{"post":{"tags":["quantlib-enterprise"],"summary":"Tax Shield Value Endpoint","operationId":"tax_shield_value_endpoint_quantlib_analysis_tax_shield_value_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/unlever-beta":{"post":{"tags":["quantlib-enterprise"],"summary":"Unlever Beta Endpoint","operationId":"unlever_beta_endpoint_quantlib_analysis_unlever_beta_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/prat-model":{"post":{"tags":["quantlib-enterprise"],"summary":"Prat Model Endpoint","operationId":"prat_model_endpoint_quantlib_analysis_prat_model_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/pre-revenue-valuation-range":{"post":{"tags":["quantlib-enterprise"],"summary":"Pre Revenue Valuation Range Endpoint","operationId":"pre_revenue_valuation_range_endpoint_quantlib_analysis_pre_revenue_valuation_range_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/dividend-yield":{"post":{"tags":["quantlib-enterprise"],"summary":"Dividend Yield Endpoint","operationId":"dividend_yield_endpoint_quantlib_analysis_dividend_yield_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/dupont-3-factor":{"post":{"tags":["quantlib-enterprise"],"summary":"Dupont 3 Factor Endpoint","operationId":"dupont_3_factor_endpoint_quantlib_analysis_dupont_3_factor_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/dupont-5-factor":{"post":{"tags":["quantlib-enterprise"],"summary":"Dupont 5 Factor Endpoint","operationId":"dupont_5_factor_endpoint_quantlib_analysis_dupont_5_factor_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/earnings-persistence":{"post":{"tags":["quantlib-enterprise"],"summary":"Earnings Persistence Endpoint","operationId":"earnings_persistence_endpoint_quantlib_analysis_earnings_persistence_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/earnings-yield":{"post":{"tags":["quantlib-enterprise"],"summary":"Earnings Yield Endpoint","operationId":"earnings_yield_endpoint_quantlib_analysis_earnings_yield_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/ebitda-margin":{"post":{"tags":["quantlib-enterprise"],"summary":"Ebitda Margin Endpoint","operationId":"ebitda_margin_endpoint_quantlib_analysis_ebitda_margin_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/economic-value-added":{"post":{"tags":["quantlib-enterprise"],"summary":"Economic Value Added Endpoint","operationId":"economic_value_added_endpoint_quantlib_analysis_economic_value_added_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/efficiency-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Efficiency Ratio Endpoint","operationId":"efficiency_ratio_endpoint_quantlib_analysis_efficiency_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/ev-to-ebitda":{"post":{"tags":["quantlib-enterprise"],"summary":"Ev To Ebitda Endpoint","operationId":"ev_to_ebitda_endpoint_quantlib_analysis_ev_to_ebitda_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/eva-spread":{"post":{"tags":["quantlib-enterprise"],"summary":"Eva Spread Endpoint","operationId":"eva_spread_endpoint_quantlib_analysis_eva_spread_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/expected-default-frequency":{"post":{"tags":["quantlib-enterprise"],"summary":"Expected Default Frequency Endpoint","operationId":"expected_default_frequency_endpoint_quantlib_analysis_expected_default_frequency_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/expected-distress-cost":{"post":{"tags":["quantlib-enterprise"],"summary":"Expected Distress Cost Endpoint","operationId":"expected_distress_cost_endpoint_quantlib_analysis_expected_distress_cost_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/expected-loss":{"post":{"tags":["quantlib-enterprise"],"summary":"Expected Loss Endpoint","operationId":"expected_loss_endpoint_quantlib_analysis_expected_loss_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/expense-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Expense Ratio Endpoint","operationId":"expense_ratio_endpoint_quantlib_analysis_expense_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/fcfe":{"post":{"tags":["quantlib-enterprise"],"summary":"Fcfe Endpoint","operationId":"fcfe_endpoint_quantlib_analysis_fcfe_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/fcfe-valuation":{"post":{"tags":["quantlib-enterprise"],"summary":"Fcfe Valuation Endpoint","operationId":"fcfe_valuation_endpoint_quantlib_analysis_fcfe_valuation_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/fcff":{"post":{"tags":["quantlib-enterprise"],"summary":"Fcff Endpoint","operationId":"fcff_endpoint_quantlib_analysis_fcff_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/fcff-valuation":{"post":{"tags":["quantlib-enterprise"],"summary":"Fcff Valuation Endpoint","operationId":"fcff_valuation_endpoint_quantlib_analysis_fcff_valuation_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/ffo-to-debt":{"post":{"tags":["quantlib-enterprise"],"summary":"Ffo To Debt Endpoint","operationId":"ffo_to_debt_endpoint_quantlib_analysis_ffo_to_debt_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/financial-leverage":{"post":{"tags":["quantlib-enterprise"],"summary":"Financial Leverage Endpoint","operationId":"financial_leverage_endpoint_quantlib_analysis_financial_leverage_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/free-cash-flow":{"post":{"tags":["quantlib-enterprise"],"summary":"Free Cash Flow Endpoint","operationId":"free_cash_flow_endpoint_quantlib_analysis_free_cash_flow_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/funds-from-operations":{"post":{"tags":["quantlib-enterprise"],"summary":"Funds From Operations Endpoint","operationId":"funds_from_operations_endpoint_quantlib_analysis_funds_from_operations_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/gordon-growth-model":{"post":{"tags":["quantlib-enterprise"],"summary":"Gordon Growth Model Endpoint","operationId":"gordon_growth_model_endpoint_quantlib_analysis_gordon_growth_model_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/graham-number":{"post":{"tags":["quantlib-enterprise"],"summary":"Graham Number Endpoint","operationId":"graham_number_endpoint_quantlib_analysis_graham_number_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/gross-profitability-factor":{"post":{"tags":["quantlib-enterprise"],"summary":"Gross Profitability Factor Endpoint","operationId":"gross_profitability_factor_endpoint_quantlib_analysis_gross_profitability_factor_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/h-model-dcf":{"post":{"tags":["quantlib-enterprise"],"summary":"H Model Dcf Endpoint","operationId":"h_model_dcf_endpoint_quantlib_analysis_h_model_dcf_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/hamada-equation":{"post":{"tags":["quantlib-enterprise"],"summary":"Hamada Equation Endpoint","operationId":"hamada_equation_endpoint_quantlib_analysis_hamada_equation_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-banking-financials":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Banking Financials","operationId":"create_banking_financials_quantlib_analysis_create_banking_financials_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-insurance-financials":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Insurance Financials","operationId":"create_insurance_financials_quantlib_analysis_create_insurance_financials_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-reit-financials":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Reit Financials","operationId":"create_reit_financials_quantlib_analysis_create_reit_financials_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-utility-financials":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Utility Financials","operationId":"create_utility_financials_quantlib_analysis_create_utility_financials_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-berkus-method":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Berkus Method","operationId":"create_berkus_method_quantlib_analysis_create_berkus_method_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-berkus-score":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Berkus Score","operationId":"create_berkus_score_quantlib_analysis_create_berkus_score_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-first-chicago-method":{"post":{"tags":["quantlib-enterprise"],"summary":"Create First Chicago Method","operationId":"create_first_chicago_method_quantlib_analysis_create_first_chicago_method_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-venture-capital-method":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Venture Capital Method","operationId":"create_venture_capital_method_quantlib_analysis_create_venture_capital_method_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-milestone-valuation":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Milestone Valuation","operationId":"create_milestone_valuation_quantlib_analysis_create_milestone_valuation_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-network-effects-valuation":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Network Effects Valuation","operationId":"create_network_effects_valuation_quantlib_analysis_create_network_effects_valuation_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-option-pricing-valuation":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Option Pricing Valuation","operationId":"create_option_pricing_valuation_quantlib_analysis_create_option_pricing_valuation_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-scorecard-valuation":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Scorecard Valuation","operationId":"create_scorecard_valuation_quantlib_analysis_create_scorecard_valuation_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-eva-analysis":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Eva Analysis","operationId":"create_eva_analysis_quantlib_analysis_create_eva_analysis_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-earnings-quality-analysis":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Earnings Quality Analysis","operationId":"create_earnings_quality_analysis_quantlib_analysis_create_earnings_quality_analysis_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-proforma-analysis":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Proforma Analysis","operationId":"create_proforma_analysis_quantlib_analysis_create_proforma_analysis_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-residual-income-analysis":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Residual Income Analysis","operationId":"create_residual_income_analysis_quantlib_analysis_create_residual_income_analysis_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-business-segment":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Business Segment","operationId":"create_business_segment_quantlib_analysis_create_business_segment_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-geographic-segment":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Geographic Segment","operationId":"create_geographic_segment_quantlib_analysis_create_geographic_segment_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-factor-exposures":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Factor Exposures","operationId":"create_factor_exposures_quantlib_analysis_create_factor_exposures_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-ratio-summary":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Ratio Summary","operationId":"create_ratio_summary_quantlib_analysis_create_ratio_summary_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-risk-factor-summation":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Risk Factor Summation","operationId":"create_risk_factor_summation_quantlib_analysis_create_risk_factor_summation_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-milestone":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Milestone","operationId":"create_milestone_quantlib_analysis_create_milestone_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-scenario":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Scenario","operationId":"create_scenario_quantlib_analysis_create_scenario_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/create-scorecard-factors":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Scorecard Factors","operationId":"create_scorecard_factors_quantlib_analysis_create_scorecard_factors_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/analysis/risk-levels":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Risk Levels","description":"Get available risk level values","operationId":"get_risk_levels_quantlib_analysis_risk_levels_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/analysis/startup-stages":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Startup Stages","description":"Get available startup stage values","operationId":"get_startup_stages_quantlib_analysis_startup_stages_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/regulatory/info":{"get":{"tags":["quantlib-enterprise"],"summary":"Regulatory Module Info","description":"Regulatory module information","operationId":"regulatory_module_info_quantlib_regulatory_info_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/regulatory/calculate-cet1-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Cet1 Ratio","operationId":"calculate_cet1_ratio_quantlib_regulatory_calculate_cet1_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/calculate-tier1-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Tier1 Ratio","operationId":"calculate_tier1_ratio_quantlib_regulatory_calculate_tier1_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/calculate-total-capital-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Total Capital Ratio","operationId":"calculate_total_capital_ratio_quantlib_regulatory_calculate_total_capital_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/calculate-leverage-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Leverage Ratio","operationId":"calculate_leverage_ratio_quantlib_regulatory_calculate_leverage_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/calculate-lcr":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Lcr","operationId":"calculate_lcr_quantlib_regulatory_calculate_lcr_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/calculate-nsfr":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Nsfr","operationId":"calculate_nsfr_quantlib_regulatory_calculate_nsfr_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/calculate-pfe":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Pfe","operationId":"calculate_pfe_quantlib_regulatory_calculate_pfe_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/calculate-rc":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Rc","operationId":"calculate_rc_quantlib_regulatory_calculate_rc_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/calculate-ead-ccr":{"post":{"tags":["quantlib-enterprise"],"summary":"Calculate Ead Ccr","operationId":"calculate_ead_ccr_quantlib_regulatory_calculate_ead_ccr_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/addon-aggregation":{"post":{"tags":["quantlib-enterprise"],"summary":"Addon Aggregation","operationId":"addon_aggregation_quantlib_regulatory_addon_aggregation_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/assess-stage":{"post":{"tags":["quantlib-enterprise"],"summary":"Assess Stage","operationId":"assess_stage_quantlib_regulatory_assess_stage_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/significant-increase-in-credit-risk":{"post":{"tags":["quantlib-enterprise"],"summary":"Significant Increase In Credit Risk","operationId":"significant_increase_in_credit_risk_quantlib_regulatory_significant_increase_in_credit_risk_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/twelve-month-ecl":{"post":{"tags":["quantlib-enterprise"],"summary":"Twelve Month Ecl","operationId":"twelve_month_ecl_quantlib_regulatory_twelve_month_ecl_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/lifetime-ecl":{"post":{"tags":["quantlib-enterprise"],"summary":"Lifetime Ecl","operationId":"lifetime_ecl_quantlib_regulatory_lifetime_ecl_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/project-capital-ratios":{"post":{"tags":["quantlib-enterprise"],"summary":"Project Capital Ratios","operationId":"project_capital_ratios_quantlib_regulatory_project_capital_ratios_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-basel-calculator":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Basel Calculator","operationId":"create_basel_calculator_quantlib_regulatory_create_basel_calculator_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-capital-ratios":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Capital Ratios","operationId":"create_capital_ratios_quantlib_regulatory_create_capital_ratios_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-cet1":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Cet1","operationId":"create_cet1_quantlib_regulatory_create_cet1_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-credit-risk-standardized":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Credit Risk Standardized","operationId":"create_credit_risk_standardized_quantlib_regulatory_create_credit_risk_standardized_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-credit-risk-irb":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Credit Risk Irb","operationId":"create_credit_risk_irb_quantlib_regulatory_create_credit_risk_irb_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-ecl-calculator":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Ecl Calculator","operationId":"create_ecl_calculator_quantlib_regulatory_create_ecl_calculator_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-ccar-test":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Ccar Test","operationId":"create_ccar_test_quantlib_regulatory_create_ccar_test_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-dfast-test":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Dfast Test","operationId":"create_dfast_test_quantlib_regulatory_create_dfast_test_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-class-instance":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Regulatory Class","description":"Universal endpoint for creating regulatory class instances.\nPass 'class_name' and constructor parameters in request body.\n\nSupported classes: AdverseScenario, BaselineScenario, CapitalCharge, CapitalProjection,\nCashInflows, CashOutflows, CreditExposure, DeltaRisk, CurvatureRisk, VegaRisk,\nAvailableStableFunding, RequiredStableFunding, LiquidityCoverageRatio,\nNetStableFundingRatio, AssetClass, AssetClassCCR, MarketRiskCharge,\nOperationalRiskCharge, and 40 more...","operationId":"create_regulatory_class_quantlib_regulatory_create_class_instance_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/submodules/basel":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Basel Submodule","operationId":"get_basel_submodule_quantlib_regulatory_submodules_basel_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/submodules/frtb":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Frtb Submodule","operationId":"get_frtb_submodule_quantlib_regulatory_submodules_frtb_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/submodules/ifrs9":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Ifrs9 Submodule","operationId":"get_ifrs9_submodule_quantlib_regulatory_submodules_ifrs9_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/submodules/liquidity":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Liquidity Submodule","operationId":"get_liquidity_submodule_quantlib_regulatory_submodules_liquidity_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/submodules/saccr":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Saccr Submodule","operationId":"get_saccr_submodule_quantlib_regulatory_submodules_saccr_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/submodules/stress":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Stress Submodule","operationId":"get_stress_submodule_quantlib_regulatory_submodules_stress_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-common-equity-tier1":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Common Equity Tier1","operationId":"create_common_equity_tier1_quantlib_regulatory_create_common_equity_tier1_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-tier1-capital":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Tier1 Capital","operationId":"create_tier1_capital_quantlib_regulatory_create_tier1_capital_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-tier2-capital":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Tier2 Capital","operationId":"create_tier2_capital_quantlib_regulatory_create_tier2_capital_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-credit-exposure":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Credit Exposure","operationId":"create_credit_exposure_quantlib_regulatory_create_credit_exposure_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-risk-weighted-assets":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Risk Weighted Assets","operationId":"create_risk_weighted_assets_quantlib_regulatory_create_risk_weighted_assets_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-leverage-ratio":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Leverage Ratio","operationId":"create_leverage_ratio_quantlib_regulatory_create_leverage_ratio_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-operational-risk":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Operational Risk","operationId":"create_operational_risk_quantlib_regulatory_create_operational_risk_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-market-risk-standardized":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Market Risk Standardized","operationId":"create_market_risk_standardized_quantlib_regulatory_create_market_risk_standardized_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-frtb-sa-calculator":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Frtb Sa Calculator","operationId":"create_frtb_sa_calculator_quantlib_regulatory_create_frtb_sa_calculator_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-delta-risk":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Delta Risk","operationId":"create_delta_risk_quantlib_regulatory_create_delta_risk_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-vega-risk":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Vega Risk","operationId":"create_vega_risk_quantlib_regulatory_create_vega_risk_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-curvature-risk":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Curvature Risk","operationId":"create_curvature_risk_quantlib_regulatory_create_curvature_risk_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-capital-charge":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Capital Charge","operationId":"create_capital_charge_quantlib_regulatory_create_capital_charge_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-frtb-result":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Frtb Result","operationId":"create_frtb_result_quantlib_regulatory_create_frtb_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-sensitivity-result":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Sensitivity Result","operationId":"create_sensitivity_result_quantlib_regulatory_create_sensitivity_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-sensitivity-based-method":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Sensitivity Based Method","operationId":"create_sensitivity_based_method_quantlib_regulatory_create_sensitivity_based_method_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-ifrs9-calculator":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Ifrs9 Calculator","operationId":"create_ifrs9_calculator_quantlib_regulatory_create_ifrs9_calculator_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-expected-credit-loss":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Expected Credit Loss","operationId":"create_expected_credit_loss_quantlib_regulatory_create_expected_credit_loss_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-stage-assessment":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Stage Assessment","operationId":"create_stage_assessment_quantlib_regulatory_create_stage_assessment_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-probability-of-default":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Probability Of Default","operationId":"create_probability_of_default_quantlib_regulatory_create_probability_of_default_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-loss-given-default":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Loss Given Default","operationId":"create_loss_given_default_quantlib_regulatory_create_loss_given_default_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-exposure-at-default":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Exposure At Default","operationId":"create_exposure_at_default_quantlib_regulatory_create_exposure_at_default_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-lcr-calculator":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Lcr Calculator","operationId":"create_lcr_calculator_quantlib_regulatory_create_lcr_calculator_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-nsfr-calculator":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Nsfr Calculator","operationId":"create_nsfr_calculator_quantlib_regulatory_create_nsfr_calculator_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-high-quality-liquid-assets":{"post":{"tags":["quantlib-enterprise"],"summary":"Create High Quality Liquid Assets","operationId":"create_high_quality_liquid_assets_quantlib_regulatory_create_high_quality_liquid_assets_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-cash-outflows":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Cash Outflows","operationId":"create_cash_outflows_quantlib_regulatory_create_cash_outflows_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-cash-inflows":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Cash Inflows","operationId":"create_cash_inflows_quantlib_regulatory_create_cash_inflows_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-available-stable-funding":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Available Stable Funding","operationId":"create_available_stable_funding_quantlib_regulatory_create_available_stable_funding_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-required-stable-funding":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Required Stable Funding","operationId":"create_required_stable_funding_quantlib_regulatory_create_required_stable_funding_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-liquidity-ratios":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Liquidity Ratios","operationId":"create_liquidity_ratios_quantlib_regulatory_create_liquidity_ratios_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-saccr-calculator":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Saccr Calculator","operationId":"create_saccr_calculator_quantlib_regulatory_create_saccr_calculator_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-replacement-cost":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Replacement Cost","operationId":"create_replacement_cost_quantlib_regulatory_create_replacement_cost_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-potential-future-exposure":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Potential Future Exposure","operationId":"create_potential_future_exposure_quantlib_regulatory_create_potential_future_exposure_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-hedging-set":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Hedging Set","operationId":"create_hedging_set_quantlib_regulatory_create_hedging_set_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-exposure-at-default-ccr":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Exposure At Default Ccr","operationId":"create_exposure_at_default_ccr_quantlib_regulatory_create_exposure_at_default_ccr_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-maturity-factor":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Maturity Factor","operationId":"create_maturity_factor_quantlib_regulatory_create_maturity_factor_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-supervisory-delta":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Supervisory Delta","operationId":"create_supervisory_delta_quantlib_regulatory_create_supervisory_delta_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-stress-test-framework":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Stress Test Framework","operationId":"create_stress_test_framework_quantlib_regulatory_create_stress_test_framework_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-stress-scenario":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Stress Scenario","operationId":"create_stress_scenario_quantlib_regulatory_create_stress_scenario_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-baseline-scenario":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Baseline Scenario","operationId":"create_baseline_scenario_quantlib_regulatory_create_baseline_scenario_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-adverse-scenario":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Adverse Scenario","operationId":"create_adverse_scenario_quantlib_regulatory_create_adverse_scenario_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-severely-adverse-scenario":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Severely Adverse Scenario","operationId":"create_severely_adverse_scenario_quantlib_regulatory_create_severely_adverse_scenario_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-stress-test-result":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Stress Test Result","operationId":"create_stress_test_result_quantlib_regulatory_create_stress_test_result_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-capital-projection":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Capital Projection","operationId":"create_capital_projection_quantlib_regulatory_create_capital_projection_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/create-stress-period":{"post":{"tags":["quantlib-enterprise"],"summary":"Create Stress Period","operationId":"create_stress_period_quantlib_regulatory_create_stress_period_post","requestBody":{"content":{"application/json":{"schema":{"additionalProperties":true,"type":"object","title":"Req"}}},"required":true},"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}},"security":[{"APIKeyHeader":[]}]}},"/quantlib/regulatory/hqla-levels":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Hqla Levels","description":"Get available HQLA (High Quality Liquid Assets) level values","operationId":"get_hqla_levels_quantlib_regulatory_hqla_levels_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/regulatory/risk-classes":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Risk Classes","description":"Get available Basel risk class values","operationId":"get_risk_classes_quantlib_regulatory_risk_classes_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/quantlib/regulatory/risk-factors":{"get":{"tags":["quantlib-enterprise"],"summary":"Get Risk Factors","description":"Get available risk factor type values","operationId":"get_risk_factors_quantlib_regulatory_risk_factors_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/search/symbols":{"get":{"tags":["search"],"summary":"Http Symbol Search","description":"HTTP endpoint for symbol search (alternative to WebSocket)\n\nQuery params:\n query: Search term\n limit: Maximum results (default 50, max 100)","operationId":"http_symbol_search_search_symbols_get","parameters":[{"name":"query","in":"query","required":false,"schema":{"type":"string","default":"","title":"Query"}},{"name":"limit","in":"query","required":false,"schema":{"type":"integer","default":50,"title":"Limit"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/":{"get":{"summary":"Root","description":"API status endpoint","operationId":"root__get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/health":{"get":{"summary":"Health Check","description":"System health check","operationId":"health_check_health_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/auth/status":{"get":{"summary":"Auth Status","description":"Check authentication status","operationId":"auth_status_auth_status_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/test":{"get":{"summary":"Test Endpoint","description":"Test endpoint","operationId":"test_endpoint_test_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/mcp/sync":{"post":{"summary":"Manual Mcp Sync","description":"Manually trigger MCP scripts sync from GitHub (Admin only)\n\nArgs:\n force: Force sync even if not time yet (default False)","operationId":"manual_mcp_sync_mcp_sync_post","security":[{"APIKeyHeader":[]}],"parameters":[{"name":"force","in":"query","required":false,"schema":{"type":"boolean","default":false,"title":"Force"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/mcp/status":{"get":{"summary":"Mcp Status","description":"Get MCP system status (tools available, last sync, etc.)","operationId":"mcp_status_mcp_status_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}}},"components":{"schemas":{"AddBusinessDaysRequest":{"properties":{"start_date":{"type":"string","title":"Start Date"},"days":{"type":"integer","title":"Days"}},"type":"object","required":["start_date","days"],"title":"AddBusinessDaysRequest"},"AdjustDateRequest":{"properties":{"date":{"type":"string","title":"Date"},"business_day_convention":{"type":"string","title":"Business Day Convention","default":"Following"},"calendar_type":{"type":"string","title":"Calendar Type","default":"TARGET"}},"type":"object","required":["date"],"title":"AdjustDateRequest"},"AdjustmentRequest":{"properties":{"date":{"type":"string","title":"Date"},"calendar":{"type":"string","title":"Calendar","default":"TARGET"}},"type":"object","required":["date"],"title":"AdjustmentRequest"},"AdvanceDateRequest":{"properties":{"date":{"type":"string","title":"Date"},"period":{"type":"string","title":"Period"},"business_day_convention":{"type":"string","title":"Business Day Convention","default":"Following"},"calendar_type":{"type":"string","title":"Calendar Type","default":"TARGET"}},"type":"object","required":["date","period"],"title":"AdvanceDateRequest"},"AircraftRequest":{"properties":{"aircraft_id":{"type":"string","title":"Aircraft Id"}},"type":"object","required":["aircraft_id"],"title":"AircraftRequest"},"AmortizingSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"initial_notional":{"type":"number","title":"Initial Notional"},"fixed_rate":{"type":"number","title":"Fixed Rate"},"amortization_schedule":{"items":{"type":"number"},"type":"array","title":"Amortization Schedule"}},"type":"object","required":["effective_date","termination_date","initial_notional","fixed_rate","amortization_schedule"],"title":"AmortizingSwapRequest"},"AreaSearchRequest":{"properties":{"min_lat":{"type":"number","title":"Min Lat"},"max_lat":{"type":"number","title":"Max Lat"},"min_lng":{"type":"number","title":"Min Lng"},"max_lng":{"type":"number","title":"Max Lng"},"days_ago":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Days Ago"}},"type":"object","required":["min_lat","max_lat","min_lng","max_lng"],"title":"AreaSearchRequest"},"ArithmeticAsianOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"strike":{"type":"number","title":"Strike"},"observation_dates":{"items":{"type":"string"},"type":"array","title":"Observation Dates"},"expiry_date":{"type":"string","title":"Expiry Date"}},"type":"object","required":["option_type","strike","observation_dates","expiry_date"],"title":"ArithmeticAsianOptionRequest"},"AsCurrencyRequest":{"properties":{"value":{"type":"string","title":"Value"}},"type":"object","required":["value"],"title":"AsCurrencyRequest"},"AsianOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"strike":{"type":"number","title":"Strike"},"averaging_type":{"type":"string","title":"Averaging Type"},"observation_dates":{"items":{"type":"string"},"type":"array","title":"Observation Dates"},"expiry_date":{"type":"string","title":"Expiry Date"}},"type":"object","required":["option_type","strike","averaging_type","observation_dates","expiry_date"],"title":"AsianOptionRequest"},"AssetBackedSecurityRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"notional":{"type":"number","title":"Notional"},"coupon_rate":{"type":"number","title":"Coupon Rate"},"collateral_type":{"type":"string","title":"Collateral Type"}},"type":"object","required":["issue_date","maturity_date","notional","coupon_rate","collateral_type"],"title":"AssetBackedSecurityRequest"},"AustraliaCalendarRequest":{"properties":{"calendar_type":{"type":"string","title":"Calendar Type","default":"Settlement"}},"type":"object","title":"AustraliaCalendarRequest"},"BacktestVaRModelRequest":{"properties":{"var_estimates":{"items":{"type":"number"},"type":"array","title":"Var Estimates"},"actual_losses":{"items":{"type":"number"},"type":"array","title":"Actual Losses"},"confidence_level":{"type":"number","title":"Confidence Level","default":0.95}},"type":"object","required":["var_estimates","actual_losses"],"title":"BacktestVaRModelRequest"},"BackwardFlatInterpRequest":{"properties":{"x_values":{"items":{"type":"number"},"type":"array","title":"X Values"},"y_values":{"items":{"type":"number"},"type":"array","title":"Y Values"},"x":{"type":"number","title":"X"}},"type":"object","required":["x_values","y_values","x"],"title":"BackwardFlatInterpRequest"},"BarrierOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"barrier_type":{"type":"string","title":"Barrier Type"},"strike":{"type":"number","title":"Strike"},"barrier":{"type":"number","title":"Barrier"},"expiry_date":{"type":"string","title":"Expiry Date"}},"type":"object","required":["option_type","barrier_type","strike","barrier","expiry_date"],"title":"BarrierOptionRequest"},"BasisSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"index1":{"type":"string","title":"Index1"},"index2":{"type":"string","title":"Index2"},"spread":{"type":"number","title":"Spread","default":0.0}},"type":"object","required":["effective_date","termination_date","notional","index1","index2"],"title":"BasisSwapRequest"},"BlackKarasinskiModelRequest":{"properties":{"r0":{"type":"number","title":"R0"},"a":{"type":"number","title":"A"},"sigma":{"type":"number","title":"Sigma"}},"type":"object","required":["r0","a","sigma"],"title":"BlackKarasinskiModelRequest"},"BlackLittermanRequest":{"properties":{"market_weights":{"items":{"type":"number"},"type":"array","title":"Market Weights"},"covariance_matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Covariance Matrix"},"views":{"items":{"$ref":"#/components/schemas/ViewRequest"},"type":"array","title":"Views"},"risk_aversion":{"type":"number","title":"Risk Aversion","default":2.5},"tau":{"type":"number","title":"Tau","default":0.025}},"type":"object","required":["market_weights","covariance_matrix","views"],"title":"BlackLittermanRequest"},"Body_extract_pdf_text_research_pdf_extract_post":{"properties":{"file":{"type":"string","format":"binary","title":"File","description":"PDF file to process"}},"type":"object","required":["file"],"title":"Body_extract_pdf_text_research_pdf_extract_post"},"Body_upload_dataset_marketplace_upload_post":{"properties":{"file":{"type":"string","format":"binary","title":"File"}},"type":"object","required":["file"],"title":"Body_upload_dataset_marketplace_upload_post"},"BondFutureRequest":{"properties":{"delivery_date":{"type":"string","title":"Delivery Date"},"basket_bonds":{"items":{"type":"string"},"type":"array","title":"Basket Bonds"},"conversion_factors":{"items":{"type":"number"},"type":"array","title":"Conversion Factors"}},"type":"object","required":["delivery_date","basket_bonds","conversion_factors"],"title":"BondFutureRequest"},"BondPriceResultRequest":{"properties":{"clean_price":{"type":"number","title":"Clean Price"},"dirty_price":{"type":"number","title":"Dirty Price"},"accrued_interest":{"type":"number","title":"Accrued Interest"}},"type":"object","required":["clean_price","dirty_price","accrued_interest"],"title":"BondPriceResultRequest"},"BondRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"face_value":{"type":"number","title":"Face Value","default":100.0},"currency":{"type":"string","title":"Currency","default":"USD"}},"type":"object","required":["issue_date","maturity_date"],"title":"BondRequest"},"BootstrapConfigRequest":{"properties":{"tolerance":{"type":"number","title":"Tolerance","default":1e-06},"max_iterations":{"type":"integer","title":"Max Iterations","default":100},"interpolation_method":{"type":"string","title":"Interpolation Method","default":"LINEAR"}},"type":"object","title":"BootstrapConfigRequest"},"BootstrapCurveRequest":{"properties":{"instruments":{"items":{"additionalProperties":true,"type":"object"},"type":"array","title":"Instruments"},"config":{"$ref":"#/components/schemas/BootstrapConfigRequest"}},"type":"object","required":["instruments","config"],"title":"BootstrapCurveRequest"},"BootstrapInflationRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"},"cpi_dates":{"items":{"type":"string"},"type":"array","title":"Cpi Dates"},"cpi_values":{"items":{"type":"number"},"type":"array","title":"Cpi Values"}},"type":"object","required":["reference_date","cpi_dates","cpi_values"],"title":"BootstrapInflationRequest"},"BrazilCalendarRequest":{"properties":{"calendar_type":{"type":"string","title":"Calendar Type","default":"Settlement"}},"type":"object","title":"BrazilCalendarRequest"},"BrentSolverRequest":{"properties":{"tolerance":{"type":"number","title":"Tolerance","default":1e-06},"max_iterations":{"type":"integer","title":"Max Iterations","default":100}},"type":"object","title":"BrentSolverRequest"},"BroadcastMessageRequest":{"properties":{"subject":{"type":"string","title":"Subject"},"message":{"type":"string","title":"Message"},"target_users":{"type":"string","title":"Target Users","default":"all"}},"type":"object","required":["subject","message"],"title":"BroadcastMessageRequest"},"BusinessDayAdjustmentRequest":{"properties":{"adjustment_type":{"type":"string","title":"Adjustment Type"}},"type":"object","required":["adjustment_type"],"title":"BusinessDayAdjustmentRequest"},"BusinessDaysBetweenRequest":{"properties":{"from_date":{"type":"string","title":"From Date"},"to_date":{"type":"string","title":"To Date"},"calendar_type":{"type":"string","title":"Calendar Type","default":"TARGET"}},"type":"object","required":["from_date","to_date"],"title":"BusinessDaysBetweenRequest"},"CDORequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"notional":{"type":"number","title":"Notional"},"attachment_point":{"type":"number","title":"Attachment Point"},"detachment_point":{"type":"number","title":"Detachment Point"}},"type":"object","required":["issue_date","maturity_date","notional","attachment_point","detachment_point"],"title":"CDORequest"},"CDSBootstrapRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"},"maturities":{"items":{"type":"string"},"type":"array","title":"Maturities"},"spreads":{"items":{"type":"number"},"type":"array","title":"Spreads"},"recovery_rate":{"type":"number","title":"Recovery Rate","default":0.4}},"type":"object","required":["reference_date","maturities","spreads"],"title":"CDSBootstrapRequest"},"CDSResultRequest":{"properties":{"fair_spread":{"type":"number","title":"Fair Spread"},"default_probability":{"type":"number","title":"Default Probability"},"upfront":{"type":"number","title":"Upfront"}},"type":"object","required":["fair_spread","default_probability","upfront"],"title":"CDSResultRequest"},"CIRModelRequest":{"properties":{"r0":{"type":"number","title":"R0"},"a":{"type":"number","title":"A"},"b":{"type":"number","title":"B"},"sigma":{"type":"number","title":"Sigma"}},"type":"object","required":["r0","a","b","sigma"],"title":"CIRModelRequest"},"CLORequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"notional":{"type":"number","title":"Notional"},"senior_tranche_pct":{"type":"number","title":"Senior Tranche Pct"}},"type":"object","required":["issue_date","maturity_date","notional","senior_tranche_pct"],"title":"CLORequest"},"CMSSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"cms_tenor":{"type":"string","title":"Cms Tenor"},"spread":{"type":"number","title":"Spread","default":0.0}},"type":"object","required":["effective_date","termination_date","notional","cms_tenor"],"title":"CMSSwapRequest"},"CVACalculatorRequest":{"properties":{"exposure_profile":{"items":{"type":"number"},"type":"array","title":"Exposure Profile"},"credit_parameters":{"$ref":"#/components/schemas/CreditParametersRequest"},"discount_factors":{"items":{"type":"number"},"type":"array","title":"Discount Factors"}},"type":"object","required":["exposure_profile","credit_parameters","discount_factors"],"title":"CVACalculatorRequest"},"CVaRRequest":{"properties":{"returns":{"items":{"type":"number"},"type":"array","title":"Returns"},"confidence_level":{"type":"number","title":"Confidence Level","default":0.95}},"type":"object","required":["returns"],"title":"CVaRRequest"},"CalibrateMulticurveRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"},"instruments":{"items":{"additionalProperties":true,"type":"object"},"type":"array","title":"Instruments"}},"type":"object","required":["reference_date","instruments"],"title":"CalibrateMulticurveRequest"},"CalibrateSABRRequest":{"properties":{"forward":{"type":"number","title":"Forward"},"expiry":{"type":"number","title":"Expiry"},"strikes":{"items":{"type":"number"},"type":"array","title":"Strikes"},"market_vols":{"items":{"type":"number"},"type":"array","title":"Market Vols"},"beta":{"type":"number","title":"Beta","default":0.5}},"type":"object","required":["forward","expiry","strikes","market_vols"],"title":"CalibrateSABRRequest"},"CalibrationResultRequest":{"properties":{"success":{"type":"boolean","title":"Success"},"iterations":{"type":"integer","title":"Iterations"},"final_error":{"type":"number","title":"Final Error"},"parameters":{"items":{"type":"number"},"type":"array","title":"Parameters"}},"type":"object","required":["success","iterations","final_error","parameters"],"title":"CalibrationResultRequest"},"CallProvisionRequest":{"properties":{"call_date":{"type":"string","title":"Call Date"},"call_price":{"type":"number","title":"Call Price"},"call_type":{"type":"string","title":"Call Type","default":"AMERICAN"}},"type":"object","required":["call_date","call_price"],"title":"CallProvisionRequest"},"CallScheduleRequest":{"properties":{"call_dates":{"items":{"type":"string"},"type":"array","title":"Call Dates"},"call_prices":{"items":{"type":"number"},"type":"array","title":"Call Prices"}},"type":"object","required":["call_dates","call_prices"],"title":"CallScheduleRequest"},"CallableBondRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"coupon_rate":{"type":"number","title":"Coupon Rate"},"call_schedule":{"$ref":"#/components/schemas/CallScheduleRequest"},"face_value":{"type":"number","title":"Face Value","default":100.0}},"type":"object","required":["issue_date","maturity_date","coupon_rate","call_schedule"],"title":"CallableBondRequest"},"CallablePuttableBondRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"coupon_rate":{"type":"number","title":"Coupon Rate"},"face_value":{"type":"number","title":"Face Value","default":100.0}},"type":"object","required":["issue_date","maturity_date","coupon_rate"],"title":"CallablePuttableBondRequest"},"CallablePuttableSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"fixed_rate":{"type":"number","title":"Fixed Rate"}},"type":"object","required":["effective_date","termination_date","notional","fixed_rate"],"title":"CallablePuttableSwapRequest"},"CallableSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"fixed_rate":{"type":"number","title":"Fixed Rate"},"call_dates":{"items":{"type":"string"},"type":"array","title":"Call Dates"}},"type":"object","required":["effective_date","termination_date","notional","fixed_rate","call_dates"],"title":"CallableSwapRequest"},"CanadaCalendarRequest":{"properties":{"calendar_type":{"type":"string","title":"Calendar Type","default":"TARGET"}},"type":"object","title":"CanadaCalendarRequest"},"CapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"strike_rate":{"type":"number","title":"Strike Rate"},"index_name":{"type":"string","title":"Index Name"}},"type":"object","required":["effective_date","termination_date","notional","strike_rate","index_name"],"title":"CapRequest"},"CappedFlooredSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"cap_rate":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Cap Rate"},"floor_rate":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Floor Rate"}},"type":"object","required":["effective_date","termination_date","notional"],"title":"CappedFlooredSwapRequest"},"CashflowsRequest":{"properties":{"leg_type":{"type":"string","title":"Leg Type"},"notional":{"type":"number","title":"Notional"},"rate":{"type":"number","title":"Rate"},"start_date":{"type":"string","title":"Start Date"},"end_date":{"type":"string","title":"End Date"}},"type":"object","required":["leg_type","notional","rate","start_date","end_date"],"title":"CashflowsRequest"},"CatastropheBondRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"notional":{"type":"number","title":"Notional"},"coupon_rate":{"type":"number","title":"Coupon Rate"},"trigger_event":{"type":"string","title":"Trigger Event"}},"type":"object","required":["issue_date","maturity_date","notional","coupon_rate","trigger_event"],"title":"CatastropheBondRequest"},"CertificateOfDepositRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"notional":{"type":"number","title":"Notional"},"rate":{"type":"number","title":"Rate"}},"type":"object","required":["issue_date","maturity_date","notional","rate"],"title":"CertificateOfDepositRequest"},"ChatMessageCreate":{"properties":{"content":{"type":"string","title":"Content"}},"type":"object","required":["content"],"title":"ChatMessageCreate"},"ChatRequest":{"properties":{"messages":{"items":{},"type":"array","title":"Messages"},"model":{"type":"string","title":"Model","default":"meituan/longcat-flash-chat:free"}},"type":"object","required":["messages"],"title":"ChatRequest"},"ChatSessionCreate":{"properties":{"title":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Title","default":"New Conversation"}},"type":"object","title":"ChatSessionCreate"},"ChinaCalendarRequest":{"properties":{"calendar_type":{"type":"string","title":"Calendar Type","default":"SSE"}},"type":"object","title":"ChinaCalendarRequest"},"ChooserOptionRequest":{"properties":{"strike":{"type":"number","title":"Strike"},"choice_date":{"type":"string","title":"Choice Date"},"expiry_date":{"type":"string","title":"Expiry Date"}},"type":"object","required":["strike","choice_date","expiry_date"],"title":"ChooserOptionRequest"},"CoerceFloatRequest":{"properties":{"value":{"title":"Value"}},"type":"object","required":["value"],"title":"CoerceFloatRequest"},"CoerceToListRequest":{"properties":{"value":{"title":"Value"}},"type":"object","required":["value"],"title":"CoerceToListRequest"},"CollarRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"cap_rate":{"type":"number","title":"Cap Rate"},"floor_rate":{"type":"number","title":"Floor Rate"}},"type":"object","required":["effective_date","termination_date","notional","cap_rate","floor_rate"],"title":"CollarRequest"},"CombinedCalendarRequest":{"properties":{"calendar1":{"type":"string","title":"Calendar1"},"calendar2":{"type":"string","title":"Calendar2"}},"type":"object","required":["calendar1","calendar2"],"title":"CombinedCalendarRequest"},"CommercialPaperRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"face_value":{"type":"number","title":"Face Value"},"discount_rate":{"type":"number","title":"Discount Rate"}},"type":"object","required":["issue_date","maturity_date","face_value","discount_rate"],"title":"CommercialPaperRequest"},"CommodityFutureRequest":{"properties":{"delivery_date":{"type":"string","title":"Delivery Date"},"commodity_type":{"type":"string","title":"Commodity Type"},"quantity":{"type":"number","title":"Quantity"},"price":{"type":"number","title":"Price"}},"type":"object","required":["delivery_date","commodity_type","quantity","price"],"title":"CommodityFutureRequest"},"CommodityIndexRequest":{"properties":{"name":{"type":"string","title":"Name"},"commodity_type":{"type":"string","title":"Commodity Type"}},"type":"object","required":["name","commodity_type"],"title":"CommodityIndexRequest"},"CommodityOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"strike":{"type":"number","title":"Strike"},"expiry_date":{"type":"string","title":"Expiry Date"},"commodity_type":{"type":"string","title":"Commodity Type"}},"type":"object","required":["option_type","strike","expiry_date","commodity_type"],"title":"CommodityOptionRequest"},"CommoditySwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"fixed_price":{"type":"number","title":"Fixed Price"},"commodity_type":{"type":"string","title":"Commodity Type"}},"type":"object","required":["effective_date","termination_date","notional","fixed_price","commodity_type"],"title":"CommoditySwapRequest"},"ComponentRiskRequest":{"properties":{"weights":{"items":{"type":"number"},"type":"array","title":"Weights"},"covariance_matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Covariance Matrix"}},"type":"object","required":["weights","covariance_matrix"],"title":"ComponentRiskRequest"},"ComponentVaRCalculatorRequest":{"properties":{"weights":{"items":{"type":"number"},"type":"array","title":"Weights"},"covariance_matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Covariance Matrix"},"confidence_level":{"type":"number","title":"Confidence Level","default":0.95}},"type":"object","required":["weights","covariance_matrix"],"title":"ComponentVaRCalculatorRequest"},"CompoundOptionRequest":{"properties":{"underlying_option_type":{"type":"string","title":"Underlying Option Type"},"compound_option_type":{"type":"string","title":"Compound Option Type"},"underlying_strike":{"type":"number","title":"Underlying Strike"},"compound_strike":{"type":"number","title":"Compound Strike"},"compound_expiry":{"type":"string","title":"Compound Expiry"},"underlying_expiry":{"type":"string","title":"Underlying Expiry"}},"type":"object","required":["underlying_option_type","compound_option_type","underlying_strike","compound_strike","compound_expiry","underlying_expiry"],"title":"CompoundOptionRequest"},"CompoundedRFRSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"rfr_index":{"type":"string","title":"Rfr Index"},"spread":{"type":"number","title":"Spread","default":0.0}},"type":"object","required":["effective_date","termination_date","notional","rfr_index"],"title":"CompoundedRFRSwapRequest"},"ConstantHazardRateRequest":{"properties":{"hazard_rate":{"type":"number","title":"Hazard Rate"},"reference_date":{"type":"string","title":"Reference Date"}},"type":"object","required":["hazard_rate","reference_date"],"title":"ConstantHazardRateRequest"},"ContactFormCreate":{"properties":{"name":{"type":"string","title":"Name"},"email":{"type":"string","format":"email","title":"Email"},"subject":{"type":"string","title":"Subject"},"message":{"type":"string","title":"Message"}},"type":"object","required":["name","email","subject","message"],"title":"ContactFormCreate"},"ContentReaderRequest":{"properties":{"url":{"type":"string","maxLength":2083,"minLength":1,"format":"uri","title":"Url"},"format":{"type":"string","title":"Format","default":"markdown"}},"type":"object","required":["url"],"title":"ContentReaderRequest"},"ConversionTermsRequest":{"properties":{"conversion_ratio":{"type":"number","title":"Conversion Ratio"},"conversion_price":{"type":"number","title":"Conversion Price"},"conversion_start":{"type":"string","title":"Conversion Start"},"conversion_end":{"type":"string","title":"Conversion End"}},"type":"object","required":["conversion_ratio","conversion_price","conversion_start","conversion_end"],"title":"ConversionTermsRequest"},"ConversionTriggerRequest":{"properties":{"trigger_type":{"type":"string","title":"Trigger Type"},"trigger_level":{"type":"number","title":"Trigger Level"},"observation_period":{"type":"string","title":"Observation Period"}},"type":"object","required":["trigger_type","trigger_level","observation_period"],"title":"ConversionTriggerRequest"},"ConvertibleBondRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"coupon_rate":{"type":"number","title":"Coupon Rate"},"conversion_ratio":{"type":"number","title":"Conversion Ratio"},"face_value":{"type":"number","title":"Face Value","default":100.0}},"type":"object","required":["issue_date","maturity_date","coupon_rate","conversion_ratio"],"title":"ConvertibleBondRequest"},"CorrelationRequest":{"properties":{"data_x":{"items":{"type":"number"},"type":"array","title":"Data X"},"data_y":{"items":{"type":"number"},"type":"array","title":"Data Y"}},"type":"object","required":["data_x","data_y"],"title":"CorrelationRequest"},"CreateCurrencyRequest":{"properties":{"code":{"type":"string","title":"Code"}},"type":"object","required":["code"],"title":"CreateCurrencyRequest"},"CreateCurveRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"},"tenors":{"items":{"type":"number"},"type":"array","title":"Tenors","description":"Tenors in years"},"values":{"items":{"type":"number"},"type":"array","title":"Values","description":"Discount factors or rates"},"interpolation":{"type":"string","title":"Interpolation","description":"Interpolation method","default":"LINEAR"}},"type":"object","required":["reference_date","tenors","values"],"title":"CreateCurveRequest"},"CreateDualRequest":{"properties":{"value":{"type":"number","title":"Value"},"derivative":{"type":"number","title":"Derivative","default":1.0}},"type":"object","required":["value"],"title":"CreateDualRequest"},"CreateFeePaymentRequest":{"properties":{"payment_date":{"type":"string","title":"Payment Date"},"amount":{"type":"number","title":"Amount"}},"type":"object","required":["payment_date","amount"],"title":"CreateFeePaymentRequest"},"CreateFixedLegRequest":{"properties":{"notional":{"type":"number","title":"Notional"},"rate":{"type":"number","title":"Rate"},"start_date":{"type":"string","title":"Start Date"},"end_date":{"type":"string","title":"End Date"},"frequency":{"type":"string","title":"Frequency","default":"SEMI_ANNUAL"}},"type":"object","required":["notional","rate","start_date","end_date"],"title":"CreateFixedLegRequest"},"CreateFixedPeriodRequest":{"properties":{"start_date":{"type":"string","title":"Start Date"},"end_date":{"type":"string","title":"End Date"},"notional":{"type":"number","title":"Notional"},"rate":{"type":"number","title":"Rate"}},"type":"object","required":["start_date","end_date","notional","rate"],"title":"CreateFixedPeriodRequest"},"CreateHyperDualRequest":{"properties":{"value":{"type":"number","title":"Value"},"first_derivative":{"type":"number","title":"First Derivative","default":1.0},"second_derivative":{"type":"number","title":"Second Derivative","default":0.0}},"type":"object","required":["value"],"title":"CreateHyperDualRequest"},"CreateMoneyRequest":{"properties":{"amount":{"type":"number","title":"Amount"},"currency_code":{"type":"string","title":"Currency Code"}},"type":"object","required":["amount","currency_code"],"title":"CreateMoneyRequest"},"CreateNotionalScheduleRequest":{"properties":{"dates":{"items":{"type":"string"},"type":"array","title":"Dates"},"notionals":{"items":{"type":"number"},"type":"array","title":"Notionals"}},"type":"object","required":["dates","notionals"],"title":"CreateNotionalScheduleRequest"},"CreateOrderRequest":{"properties":{"plan_id":{"type":"string","title":"Plan Id"},"currency":{"type":"string","title":"Currency","default":"USD"},"return_url":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Return Url"},"customer_phone":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Customer Phone"}},"type":"object","required":["plan_id"],"title":"CreateOrderRequest","description":"Request model for creating Cashfree payment order"},"CreatePrincipalExchangeRequest":{"properties":{"exchange_date":{"type":"string","title":"Exchange Date"},"notional":{"type":"number","title":"Notional"}},"type":"object","required":["exchange_date","notional"],"title":"CreatePrincipalExchangeRequest"},"CreateRateRequest":{"properties":{"value":{"type":"number","title":"Value"},"unit":{"type":"string","title":"Unit","default":"PERCENT"}},"type":"object","required":["value"],"title":"CreateRateRequest"},"CreateSpreadRequest":{"properties":{"value":{"type":"number","title":"Value"}},"type":"object","required":["value"],"title":"CreateSpreadRequest"},"CreateTenorRequest":{"properties":{"tenor_string":{"type":"string","title":"Tenor String"}},"type":"object","required":["tenor_string"],"title":"CreateTenorRequest"},"CreditAdjustmentRequest":{"properties":{"action":{"type":"string","title":"Action"},"amount":{"type":"integer","title":"Amount"},"reason":{"type":"string","title":"Reason","default":"Admin adjustment"}},"type":"object","required":["action","amount"],"title":"CreditAdjustmentRequest"},"CreditDefaultSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"spread":{"type":"number","title":"Spread"},"recovery_rate":{"type":"number","title":"Recovery Rate","default":0.4}},"type":"object","required":["effective_date","termination_date","notional","spread"],"title":"CreditDefaultSwapRequest"},"CreditLinkedNoteRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"notional":{"type":"number","title":"Notional"},"coupon_rate":{"type":"number","title":"Coupon Rate"},"reference_entity":{"type":"string","title":"Reference Entity"}},"type":"object","required":["issue_date","maturity_date","notional","coupon_rate","reference_entity"],"title":"CreditLinkedNoteRequest"},"CreditParametersRequest":{"properties":{"default_probability":{"type":"number","title":"Default Probability"},"recovery_rate":{"type":"number","title":"Recovery Rate"},"credit_spread":{"type":"number","title":"Credit Spread"}},"type":"object","required":["default_probability","recovery_rate","credit_spread"],"title":"CreditParametersRequest"},"CrossCurrencyBasisSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"spread":{"type":"number","title":"Spread"}},"type":"object","required":["effective_date","termination_date","notional","spread"],"title":"CrossCurrencyBasisSwapRequest"},"CrossCurrencySwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional_domestic":{"type":"number","title":"Notional Domestic"},"notional_foreign":{"type":"number","title":"Notional Foreign"},"domestic_currency":{"type":"string","title":"Domestic Currency"},"foreign_currency":{"type":"string","title":"Foreign Currency"}},"type":"object","required":["effective_date","termination_date","notional_domestic","notional_foreign","domestic_currency","foreign_currency"],"title":"CrossCurrencySwapRequest"},"CurrencyRequest":{"properties":{"currency_code":{"type":"string","title":"Currency Code"}},"type":"object","required":["currency_code"],"title":"CurrencyRequest"},"CurveSolverRequest":{"properties":{"config":{"$ref":"#/components/schemas/BootstrapConfigRequest"}},"type":"object","required":["config"],"title":"CurveSolverRequest"},"DatabaseCreateRequest":{"properties":{"database_name":{"type":"string","title":"Database Name"},"display_name":{"type":"string","title":"Display Name"},"description":{"type":"string","title":"Description","default":""},"category":{"type":"string","title":"Category","default":"general"},"is_public":{"type":"boolean","title":"Is Public","default":false},"requires_subscription":{"type":"boolean","title":"Requires Subscription","default":true},"cost_per_request":{"type":"integer","title":"Cost Per Request","default":20},"free_tier_limit":{"type":"integer","title":"Free Tier Limit","default":10},"total_tables":{"type":"integer","title":"Total Tables","default":0}},"type":"object","required":["database_name","display_name"],"title":"DatabaseCreateRequest"},"DatabaseSubscriptionRequest":{"properties":{"database_name":{"type":"string","title":"Database Name"}},"type":"object","required":["database_name"],"title":"DatabaseSubscriptionRequest"},"DateCheckRequest":{"properties":{"date":{"type":"string","title":"Date"}},"type":"object","required":["date"],"title":"DateCheckRequest"},"DateRangeRequest":{"properties":{"start_date":{"type":"string","format":"date-time","title":"Start Date"},"end_date":{"type":"string","format":"date-time","title":"End Date"},"domains":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Domains"},"category":{"anyOf":[{"$ref":"#/components/schemas/NewsCategory"},{"type":"null"}]},"limit":{"type":"integer","title":"Limit","default":10}},"type":"object","required":["start_date","end_date"],"title":"DateRangeRequest"},"DateToExcelRequest":{"properties":{"date_str":{"type":"string","title":"Date Str"}},"type":"object","required":["date_str"],"title":"DateToExcelRequest"},"DepositRequest":{"properties":{"start_date":{"type":"string","title":"Start Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"notional":{"type":"number","title":"Notional"},"rate":{"type":"number","title":"Rate"}},"type":"object","required":["start_date","maturity_date","notional","rate"],"title":"DepositRequest"},"DeterminantRequest":{"properties":{"matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Matrix"}},"type":"object","required":["matrix"],"title":"DeterminantRequest"},"DeviceRegistration":{"properties":{"device_id":{"type":"string","title":"Device Id"},"device_name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Device Name"},"platform":{"type":"string","title":"Platform"},"hardware_info":{"additionalProperties":true,"type":"object","title":"Hardware Info"}},"type":"object","required":["device_id","platform","hardware_info"],"title":"DeviceRegistration"},"DigitalOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"strike":{"type":"number","title":"Strike"},"payout":{"type":"number","title":"Payout"},"expiry_date":{"type":"string","title":"Expiry Date"}},"type":"object","required":["option_type","strike","payout","expiry_date"],"title":"DigitalOptionRequest"},"DiscreteBarrierOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"barrier_type":{"type":"string","title":"Barrier Type"},"strike":{"type":"number","title":"Strike"},"barrier":{"type":"number","title":"Barrier"},"observation_dates":{"items":{"type":"string"},"type":"array","title":"Observation Dates"},"expiry_date":{"type":"string","title":"Expiry Date"}},"type":"object","required":["option_type","barrier_type","strike","barrier","observation_dates","expiry_date"],"title":"DiscreteBarrierOptionRequest"},"DoubleBarrierOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"strike":{"type":"number","title":"Strike"},"lower_barrier":{"type":"number","title":"Lower Barrier"},"upper_barrier":{"type":"number","title":"Upper Barrier"},"expiry_date":{"type":"string","title":"Expiry Date"}},"type":"object","required":["option_type","strike","lower_barrier","upper_barrier","expiry_date"],"title":"DoubleBarrierOptionRequest"},"DupireLocalVolRequest":{"properties":{"spot":{"type":"number","title":"Spot"},"risk_free_rate":{"type":"number","title":"Risk Free Rate"},"dividend_yield":{"type":"number","title":"Dividend Yield"},"volatility_surface":{"$ref":"#/components/schemas/VolatilitySurfaceRequest"}},"type":"object","required":["spot","risk_free_rate","dividend_yield","volatility_surface"],"title":"DupireLocalVolRequest"},"EfficientFrontierRequest":{"properties":{"expected_returns":{"items":{"type":"number"},"type":"array","title":"Expected Returns"},"covariance_matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Covariance Matrix"},"num_portfolios":{"type":"integer","title":"Num Portfolios","default":100}},"type":"object","required":["expected_returns","covariance_matrix"],"title":"EfficientFrontierRequest"},"EqualRiskContributionRequest":{"properties":{"covariance_matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Covariance Matrix"}},"type":"object","required":["covariance_matrix"],"title":"EqualRiskContributionRequest"},"EquilibriumReturnsRequest":{"properties":{"market_weights":{"items":{"type":"number"},"type":"array","title":"Market Weights"},"covariance_matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Covariance Matrix"},"risk_aversion":{"type":"number","title":"Risk Aversion","default":2.5}},"type":"object","required":["market_weights","covariance_matrix"],"title":"EquilibriumReturnsRequest"},"EquitySwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"equity_leg_return":{"type":"string","title":"Equity Leg Return"},"fixed_leg_rate":{"type":"number","title":"Fixed Leg Rate"}},"type":"object","required":["effective_date","termination_date","notional","equity_leg_return","fixed_leg_rate"],"title":"EquitySwapRequest"},"ExchangeOptionRequest":{"properties":{"expiry_date":{"type":"string","title":"Expiry Date"},"quantity1":{"type":"number","title":"Quantity1"},"quantity2":{"type":"number","title":"Quantity2"}},"type":"object","required":["expiry_date","quantity1","quantity2"],"title":"ExchangeOptionRequest"},"ExecutionTimeRequest":{"properties":{"function_name":{"type":"string","title":"Function Name"},"execution_time":{"type":"number","title":"Execution Time"}},"type":"object","required":["function_name","execution_time"],"title":"ExecutionTimeRequest"},"ExoticBarrierOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"barrier_type":{"type":"string","title":"Barrier Type"},"strike":{"type":"number","title":"Strike"},"barrier":{"type":"number","title":"Barrier"},"expiry_date":{"type":"string","title":"Expiry Date"}},"type":"object","required":["option_type","barrier_type","strike","barrier","expiry_date"],"title":"ExoticBarrierOptionRequest"},"ExtrapolateLinearRequest":{"properties":{"x_values":{"items":{"type":"number"},"type":"array","title":"X Values"},"y_values":{"items":{"type":"number"},"type":"array","title":"Y Values"},"x":{"type":"number","title":"X"}},"type":"object","required":["x_values","y_values","x"],"title":"ExtrapolateLinearRequest"},"ExtrapolationRequest":{"properties":{"x_values":{"items":{"type":"number"},"type":"array","title":"X Values"},"y_values":{"items":{"type":"number"},"type":"array","title":"Y Values"},"x":{"type":"number","title":"X"}},"type":"object","required":["x_values","y_values","x"],"title":"ExtrapolationRequest"},"FRARequest":{"properties":{"start_date":{"type":"string","title":"Start Date"},"end_date":{"type":"string","title":"End Date"},"notional":{"type":"number","title":"Notional"},"agreed_rate":{"type":"number","title":"Agreed Rate"},"index_name":{"type":"string","title":"Index Name"}},"type":"object","required":["start_date","end_date","notional","agreed_rate","index_name"],"title":"FRARequest"},"FVACalculatorRequest":{"properties":{"exposure_profile":{"items":{"type":"number"},"type":"array","title":"Exposure Profile"},"funding_parameters":{"$ref":"#/components/schemas/FundingParametersRequest"},"discount_factors":{"items":{"type":"number"},"type":"array","title":"Discount Factors"}},"type":"object","required":["exposure_profile","funding_parameters","discount_factors"],"title":"FVACalculatorRequest"},"FXFixingRequest":{"properties":{"index_name":{"type":"string","title":"Index Name"},"fixing_date":{"type":"string","title":"Fixing Date"},"value":{"type":"number","title":"Value"},"base_currency":{"type":"string","title":"Base Currency"},"quote_currency":{"type":"string","title":"Quote Currency"},"source":{"type":"string","title":"Source","default":"Manual"}},"type":"object","required":["index_name","fixing_date","value","base_currency","quote_currency"],"title":"FXFixingRequest"},"FXForwardCalculatorRequest":{"properties":{"pair":{"type":"string","title":"Pair","description":"Currency pair (e.g., 'EURUSD')"},"spot":{"type":"number","title":"Spot","description":"Spot rate"},"base_curve":{"items":{"additionalProperties":{"type":"number"},"type":"object"},"type":"array","title":"Base Curve","description":"Base currency discount curve"},"quote_curve":{"items":{"additionalProperties":{"type":"number"},"type":"object"},"type":"array","title":"Quote Curve","description":"Quote currency discount curve"},"spot_date":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Spot Date","description":"Spot date (YYYY-MM-DD)"},"continuous":{"type":"boolean","title":"Continuous","description":"Use continuous compounding","default":true}},"type":"object","required":["pair","spot","base_curve","quote_curve"],"title":"FXForwardCalculatorRequest"},"FXForwardPointsRequest":{"properties":{"spot":{"type":"number","title":"Spot","description":"Spot rate"},"base_rate":{"type":"number","title":"Base Rate","description":"Base currency interest rate"},"quote_rate":{"type":"number","title":"Quote Rate","description":"Quote currency interest rate"},"days":{"type":"integer","title":"Days","description":"Days to forward date"},"pair":{"type":"string","title":"Pair","description":"Currency pair"},"in_pips":{"type":"boolean","title":"In Pips","description":"Return result in pips","default":true}},"type":"object","required":["spot","base_rate","quote_rate","days","pair"],"title":"FXForwardPointsRequest"},"FXForwardQuoteRequest":{"properties":{"base":{"type":"string","title":"Base"},"quote":{"type":"string","title":"Quote"},"spot":{"type":"number","title":"Spot"},"forward_points":{"type":"number","title":"Forward Points"},"value_date":{"type":"string","title":"Value Date"}},"type":"object","required":["base","quote","spot","forward_points","value_date"],"title":"FXForwardQuoteRequest"},"FXForwardRequest":{"properties":{"settlement_date":{"type":"string","title":"Settlement Date"},"domestic_currency":{"type":"string","title":"Domestic Currency"},"foreign_currency":{"type":"string","title":"Foreign Currency"},"notional":{"type":"number","title":"Notional"},"forward_rate":{"type":"number","title":"Forward Rate"}},"type":"object","required":["settlement_date","domestic_currency","foreign_currency","notional","forward_rate"],"title":"FXForwardRequest"},"FXIndexRequest":{"properties":{"name":{"type":"string","title":"Name"},"base_currency":{"type":"string","title":"Base Currency"},"quote_currency":{"type":"string","title":"Quote Currency"}},"type":"object","required":["name","base_currency","quote_currency"],"title":"FXIndexRequest"},"FXOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"strike":{"type":"number","title":"Strike"},"expiry_date":{"type":"string","title":"Expiry Date"},"domestic_currency":{"type":"string","title":"Domestic Currency"},"foreign_currency":{"type":"string","title":"Foreign Currency"}},"type":"object","required":["option_type","strike","expiry_date","domestic_currency","foreign_currency"],"title":"FXOptionRequest"},"FXOutrightForwardRequest":{"properties":{"spot":{"type":"number","title":"Spot","description":"Spot rate"},"base_rate":{"type":"number","title":"Base Rate","description":"Base currency interest rate"},"quote_rate":{"type":"number","title":"Quote Rate","description":"Quote currency interest rate"},"days":{"type":"integer","title":"Days","description":"Days to forward date"}},"type":"object","required":["spot","base_rate","quote_rate","days"],"title":"FXOutrightForwardRequest"},"FXQuoteRequest":{"properties":{"base":{"type":"string","title":"Base","description":"Base currency (e.g., 'USD')"},"quote":{"type":"string","title":"Quote","description":"Quote currency (e.g., 'EUR')"},"mid":{"type":"number","title":"Mid","description":"Mid rate"},"bid":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Bid","description":"Bid rate"},"ask":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Ask","description":"Ask rate"},"value_date":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Value Date","description":"Value date (YYYY-MM-DD)"},"source":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source","description":"Quote source"}},"type":"object","required":["base","quote","mid"],"title":"FXQuoteRequest"},"FXRateMatrixRequest":{"properties":{"value_date":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Value Date","description":"Value date (YYYY-MM-DD)"},"quotes":{"items":{"$ref":"#/components/schemas/FXQuoteRequest"},"type":"array","title":"Quotes","description":"List of FX quotes"}},"type":"object","required":["quotes"],"title":"FXRateMatrixRequest"},"FXSpotRequest":{"properties":{"settlement_date":{"type":"string","title":"Settlement Date"},"rate":{"type":"number","title":"Rate"},"notional":{"type":"number","title":"Notional"}},"type":"object","required":["settlement_date","rate","notional"],"title":"FXSpotRequest"},"FXSwapRequest":{"properties":{"near_date":{"type":"string","title":"Near Date"},"far_date":{"type":"string","title":"Far Date"},"notional":{"type":"number","title":"Notional"},"near_rate":{"type":"number","title":"Near Rate"},"far_rate":{"type":"number","title":"Far Rate"}},"type":"object","required":["near_date","far_date","notional","near_rate","far_rate"],"title":"FXSwapRequest"},"FeedbackCreate":{"properties":{"name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Name"},"email":{"anyOf":[{"type":"string","format":"email"},{"type":"null"}],"title":"Email"},"rating":{"type":"integer","title":"Rating"},"feedback_text":{"type":"string","title":"Feedback Text"},"category":{"type":"string","title":"Category","default":"general"}},"type":"object","required":["rating","feedback_text"],"title":"FeedbackCreate"},"FindIntervalRequest":{"properties":{"x_values":{"items":{"type":"number"},"type":"array","title":"X Values"},"x":{"type":"number","title":"X"}},"type":"object","required":["x_values","x"],"title":"FindIntervalRequest"},"FiniteDifferenceRequest":{"properties":{"func_name":{"type":"string","title":"Func Name"},"x":{"type":"number","title":"X"},"h":{"type":"number","title":"H","default":1e-05}},"type":"object","required":["func_name","x"],"title":"FiniteDifferenceRequest"},"FirstToDefaultSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"spread":{"type":"number","title":"Spread"},"reference_names":{"items":{"type":"string"},"type":"array","title":"Reference Names"}},"type":"object","required":["effective_date","termination_date","notional","spread","reference_names"],"title":"FirstToDefaultSwapRequest"},"FixedRateBondRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"coupon_rate":{"type":"number","title":"Coupon Rate"},"frequency":{"type":"string","title":"Frequency","default":"SEMI_ANNUAL"},"face_value":{"type":"number","title":"Face Value","default":100.0}},"type":"object","required":["issue_date","maturity_date","coupon_rate"],"title":"FixedRateBondRequest"},"FixedStrikeLookbackRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"strike":{"type":"number","title":"Strike"},"expiry_date":{"type":"string","title":"Expiry Date"}},"type":"object","required":["option_type","strike","expiry_date"],"title":"FixedStrikeLookbackRequest"},"FlatVolatilityRequest":{"properties":{"volatility":{"type":"number","title":"Volatility"},"reference_date":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Reference Date"}},"type":"object","required":["volatility"],"title":"FlatVolatilityRequest"},"FloatingRateBondRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"index_name":{"type":"string","title":"Index Name"},"spread":{"type":"number","title":"Spread","default":0.0},"frequency":{"type":"string","title":"Frequency","default":"QUARTERLY"},"face_value":{"type":"number","title":"Face Value","default":100.0}},"type":"object","required":["issue_date","maturity_date","index_name"],"title":"FloatingRateBondRequest"},"FloatingStrikeLookbackRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"expiry_date":{"type":"string","title":"Expiry Date"}},"type":"object","required":["option_type","expiry_date"],"title":"FloatingStrikeLookbackRequest"},"FloorRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"strike_rate":{"type":"number","title":"Strike Rate"},"index_name":{"type":"string","title":"Index Name"}},"type":"object","required":["effective_date","termination_date","notional","strike_rate","index_name"],"title":"FloorRequest"},"ForumCommentCreate":{"properties":{"content":{"type":"string","title":"Content"},"parent_comment_id":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Parent Comment Id"}},"type":"object","required":["content"],"title":"ForumCommentCreate"},"ForumPostCreate":{"properties":{"title":{"type":"string","title":"Title"},"content":{"type":"string","title":"Content"},"category_id":{"type":"integer","title":"Category Id"}},"type":"object","required":["title","content","category_id"],"title":"ForumPostCreate"},"ForumProfileUpdate":{"properties":{"display_name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Display Name"},"bio":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Bio"},"avatar_color":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Avatar Color"},"signature":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Signature"},"show_email":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Show Email"},"email_notifications":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Email Notifications"}},"type":"object","title":"ForumProfileUpdate"},"ForumVoteCreate":{"properties":{"vote_type":{"type":"string","title":"Vote Type"}},"type":"object","required":["vote_type"],"title":"ForumVoteCreate"},"ForwardFlatInterpRequest":{"properties":{"x_values":{"items":{"type":"number"},"type":"array","title":"X Values"},"y_values":{"items":{"type":"number"},"type":"array","title":"Y Values"},"x":{"type":"number","title":"X"}},"type":"object","required":["x_values","y_values","x"],"title":"ForwardFlatInterpRequest"},"ForwardRequest":{"properties":{"settlement_date":{"type":"string","title":"Settlement Date"},"forward_price":{"type":"number","title":"Forward Price"},"notional":{"type":"number","title":"Notional"}},"type":"object","required":["settlement_date","forward_price","notional"],"title":"ForwardRequest"},"ForwardStartOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"strike":{"type":"number","title":"Strike"},"start_date":{"type":"string","title":"Start Date"},"expiry_date":{"type":"string","title":"Expiry Date"}},"type":"object","required":["option_type","strike","start_date","expiry_date"],"title":"ForwardStartOptionRequest"},"FranceCalendarRequest":{"properties":{"calendar_type":{"type":"string","title":"Calendar Type","default":"TARGET"}},"type":"object","title":"FranceCalendarRequest"},"FunctionCallLogRequest":{"properties":{"function_name":{"type":"string","title":"Function Name"},"args":{"items":{},"type":"array","title":"Args","default":[]}},"type":"object","required":["function_name"],"title":"FunctionCallLogRequest"},"FundingParametersRequest":{"properties":{"funding_spread":{"type":"number","title":"Funding Spread"},"collateral_rate":{"type":"number","title":"Collateral Rate"}},"type":"object","required":["funding_spread","collateral_rate"],"title":"FundingParametersRequest"},"FuturesContractRequest":{"properties":{"delivery_date":{"type":"string","title":"Delivery Date"},"contract_size":{"type":"number","title":"Contract Size"},"price":{"type":"number","title":"Price"}},"type":"object","required":["delivery_date","contract_size","price"],"title":"FuturesContractRequest"},"GaussNewtonRequest":{"properties":{"tolerance":{"type":"number","title":"Tolerance","default":1e-06},"max_iterations":{"type":"integer","title":"Max Iterations","default":100}},"type":"object","title":"GaussNewtonRequest"},"GeometricAsianOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"strike":{"type":"number","title":"Strike"},"observation_dates":{"items":{"type":"string"},"type":"array","title":"Observation Dates"},"expiry_date":{"type":"string","title":"Expiry Date"}},"type":"object","required":["option_type","strike","observation_dates","expiry_date"],"title":"GeometricAsianOptionRequest"},"GermanyCalendarRequest":{"properties":{"calendar_type":{"type":"string","title":"Calendar Type","default":"TARGET"}},"type":"object","title":"GermanyCalendarRequest"},"GetCalendarRequest":{"properties":{"calendar_name":{"type":"string","title":"Calendar Name"}},"type":"object","required":["calendar_name"],"title":"GetCalendarRequest"},"GetIndexRequest":{"properties":{"name":{"type":"string","title":"Name"}},"type":"object","required":["name"],"title":"GetIndexRequest"},"GoldenSectionRequest":{"properties":{"func_name":{"type":"string","title":"Func Name"},"a":{"type":"number","title":"A"},"b":{"type":"number","title":"B"},"tolerance":{"type":"number","title":"Tolerance","default":1e-06}},"type":"object","required":["func_name","a","b"],"title":"GoldenSectionRequest"},"GradientRequest":{"properties":{"func_name":{"type":"string","title":"Func Name"},"x":{"items":{"type":"number"},"type":"array","title":"X"}},"type":"object","required":["func_name","x"],"title":"GradientRequest"},"GreeksRequest":{"properties":{"spot":{"type":"number","title":"Spot"},"strike":{"type":"number","title":"Strike"},"expiry":{"type":"number","title":"Expiry"},"volatility":{"type":"number","title":"Volatility"},"risk_free_rate":{"type":"number","title":"Risk Free Rate"},"option_type":{"type":"string","title":"Option Type","default":"CALL"}},"type":"object","required":["spot","strike","expiry","volatility","risk_free_rate"],"title":"GreeksRequest"},"GrokipediaRequest":{"properties":{"slug":{"type":"string","title":"Slug"},"extract_refs":{"type":"boolean","title":"Extract Refs","default":true},"truncate":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Truncate"},"citations":{"type":"boolean","title":"Citations","default":false}},"type":"object","required":["slug"],"title":"GrokipediaRequest"},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"HermiteInterpRequest":{"properties":{"x_values":{"items":{"type":"number"},"type":"array","title":"X Values"},"y_values":{"items":{"type":"number"},"type":"array","title":"Y Values"},"derivatives":{"items":{"type":"number"},"type":"array","title":"Derivatives"},"x_interp":{"type":"number","title":"X Interp"}},"type":"object","required":["x_values","y_values","derivatives","x_interp"],"title":"HermiteInterpRequest"},"HestonModelRequest":{"properties":{"spot":{"type":"number","title":"Spot"},"risk_free_rate":{"type":"number","title":"Risk Free Rate"},"dividend_yield":{"type":"number","title":"Dividend Yield"},"parameters":{"$ref":"#/components/schemas/HestonParametersRequest"}},"type":"object","required":["spot","risk_free_rate","dividend_yield","parameters"],"title":"HestonModelRequest"},"HestonParametersRequest":{"properties":{"v0":{"type":"number","title":"V0","description":"Initial variance"},"kappa":{"type":"number","title":"Kappa","description":"Mean reversion speed"},"theta":{"type":"number","title":"Theta","description":"Long-term variance"},"sigma":{"type":"number","title":"Sigma","description":"Volatility of volatility"},"rho":{"type":"number","title":"Rho","description":"Correlation"}},"type":"object","required":["v0","kappa","theta","sigma","rho"],"title":"HestonParametersRequest"},"HierarchicalRiskParityRequest":{"properties":{"covariance_matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Covariance Matrix"},"expected_returns":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Expected Returns"}},"type":"object","required":["covariance_matrix"],"title":"HierarchicalRiskParityRequest"},"HistoricalVaRRequest":{"properties":{"returns":{"items":{"type":"number"},"type":"array","title":"Returns"},"confidence_level":{"type":"number","title":"Confidence Level","default":0.95},"lookback_period":{"type":"integer","title":"Lookback Period","default":252}},"type":"object","required":["returns"],"title":"HistoricalVaRRequest"},"HullWhiteModelRequest":{"properties":{"r0":{"type":"number","title":"R0"},"a":{"type":"number","title":"A"},"sigma":{"type":"number","title":"Sigma"}},"type":"object","required":["r0","a","sigma"],"title":"HullWhiteModelRequest"},"IBORFixingRequest":{"properties":{"index_name":{"type":"string","title":"Index Name"},"fixing_date":{"type":"string","title":"Fixing Date"},"value":{"type":"number","title":"Value"},"tenor":{"type":"string","title":"Tenor"},"source":{"type":"string","title":"Source","default":"Manual"}},"type":"object","required":["index_name","fixing_date","value","tenor"],"title":"IBORFixingRequest"},"IBORIndexRequest":{"properties":{"name":{"type":"string","title":"Name"},"currency":{"type":"string","title":"Currency"},"tenor":{"type":"string","title":"Tenor"}},"type":"object","required":["name","currency","tenor"],"title":"IBORIndexRequest"},"IMMDateCheckRequest":{"properties":{"date":{"type":"string","title":"Date"}},"type":"object","required":["date"],"title":"IMMDateCheckRequest"},"IncrementalVaRCalculatorRequest":{"properties":{"portfolio_var":{"type":"number","title":"Portfolio Var"},"asset_weights":{"items":{"type":"number"},"type":"array","title":"Asset Weights"}},"type":"object","required":["portfolio_var","asset_weights"],"title":"IncrementalVaRCalculatorRequest"},"IndiaCalendarRequest":{"properties":{"calendar_type":{"type":"string","title":"Calendar Type","default":"NSE"}},"type":"object","title":"IndiaCalendarRequest"},"InflationFixingRequest":{"properties":{"index_name":{"type":"string","title":"Index Name"},"fixing_date":{"type":"string","title":"Fixing Date"},"value":{"type":"number","title":"Value"},"reference_month":{"type":"string","title":"Reference Month"},"source":{"type":"string","title":"Source","default":"Manual"}},"type":"object","required":["index_name","fixing_date","value","reference_month"],"title":"InflationFixingRequest"},"InflationIndexRequest":{"properties":{"name":{"type":"string","title":"Name"},"currency":{"type":"string","title":"Currency"}},"type":"object","required":["name","currency"],"title":"InflationIndexRequest"},"InflationIndexedSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"fixed_rate":{"type":"number","title":"Fixed Rate"},"inflation_index":{"type":"string","title":"Inflation Index"}},"type":"object","required":["effective_date","termination_date","notional","fixed_rate","inflation_index"],"title":"InflationIndexedSwapRequest"},"InflationLinkedBondRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"notional":{"type":"number","title":"Notional"},"real_coupon_rate":{"type":"number","title":"Real Coupon Rate"},"inflation_index":{"type":"string","title":"Inflation Index"}},"type":"object","required":["issue_date","maturity_date","notional","real_coupon_rate","inflation_index"],"title":"InflationLinkedBondRequest"},"InflationSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"fixed_rate":{"type":"number","title":"Fixed Rate"},"inflation_index":{"type":"string","title":"Inflation Index"}},"type":"object","required":["effective_date","termination_date","notional","fixed_rate","inflation_index"],"title":"InflationSwapRequest"},"IntegrationRequest":{"properties":{"func_name":{"type":"string","title":"Func Name"},"a":{"type":"number","title":"A"},"b":{"type":"number","title":"B"},"n":{"type":"integer","title":"N","default":100}},"type":"object","required":["func_name","a","b"],"title":"IntegrationRequest"},"InterestRateSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"fixed_rate":{"type":"number","title":"Fixed Rate"},"frequency":{"type":"string","title":"Frequency","default":"SEMI_ANNUAL"}},"type":"object","required":["effective_date","termination_date","notional","fixed_rate"],"title":"InterestRateSwapRequest"},"InterpolationRequest":{"properties":{"x":{"type":"number","title":"X"},"x_values":{"items":{"type":"number"},"type":"array","title":"X Values"},"y_values":{"items":{"type":"number"},"type":"array","title":"Y Values"}},"type":"object","required":["x","x_values","y_values"],"title":"InterpolationRequest"},"InverseMatrixRequest":{"properties":{"matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Matrix"}},"type":"object","required":["matrix"],"title":"InverseMatrixRequest"},"KeyRateShiftRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"},"tenors":{"items":{"type":"number"},"type":"array","title":"Tenors"},"values":{"items":{"type":"number"},"type":"array","title":"Values"},"key_tenor":{"type":"number","title":"Key Tenor"},"shift":{"type":"number","title":"Shift"}},"type":"object","required":["reference_date","tenors","values","key_tenor","shift"],"title":"KeyRateShiftRequest"},"KouCallPriceRequest":{"properties":{"spot":{"type":"number","title":"Spot"},"strike":{"type":"number","title":"Strike"},"expiry":{"type":"number","title":"Expiry"},"risk_free_rate":{"type":"number","title":"Risk Free Rate"},"volatility":{"type":"number","title":"Volatility"},"lambda":{"type":"number","title":"Lambda"},"p":{"type":"number","title":"P"},"eta1":{"type":"number","title":"Eta1"},"eta2":{"type":"number","title":"Eta2"}},"type":"object","required":["spot","strike","expiry","risk_free_rate","volatility","lambda","p","eta1","eta2"],"title":"KouCallPriceRequest"},"KouJumpDiffusionRequest":{"properties":{"spot":{"type":"number","title":"Spot"},"risk_free_rate":{"type":"number","title":"Risk Free Rate"},"volatility":{"type":"number","title":"Volatility"},"parameters":{"$ref":"#/components/schemas/KouParametersRequest"}},"type":"object","required":["spot","risk_free_rate","volatility","parameters"],"title":"KouJumpDiffusionRequest"},"KouParametersRequest":{"properties":{"lambda":{"type":"number","title":"Lambda"},"p":{"type":"number","title":"P"},"eta1":{"type":"number","title":"Eta1"},"eta2":{"type":"number","title":"Eta2"}},"type":"object","required":["lambda","p","eta1","eta2"],"title":"KouParametersRequest"},"LLMRequest":{"properties":{"prompt":{"type":"string","title":"Prompt"},"max_tokens":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Max Tokens","default":4096},"temperature":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Temperature","default":0.7}},"type":"object","required":["prompt"],"title":"LLMRequest"},"LevenbergMarquardtRequest":{"properties":{"tolerance":{"type":"number","title":"Tolerance","default":1e-06},"max_iterations":{"type":"integer","title":"Max Iterations","default":100},"lambda_initial":{"type":"number","title":"Lambda Initial","default":0.01}},"type":"object","title":"LevenbergMarquardtRequest"},"LinearInterpRequest":{"properties":{"x_values":{"items":{"type":"number"},"type":"array","title":"X Values"},"y_values":{"items":{"type":"number"},"type":"array","title":"Y Values"},"x_interp":{"type":"number","title":"X Interp"}},"type":"object","required":["x_values","y_values","x_interp"],"title":"LinearInterpRequest"},"LinearSystemRequest":{"properties":{"matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Matrix"},"vector":{"items":{"type":"number"},"type":"array","title":"Vector"}},"type":"object","required":["matrix","vector"],"title":"LinearSystemRequest"},"LiquidityAdjustedVaRRequest":{"properties":{"base_var":{"type":"number","title":"Base Var"},"liquidity_adjustment":{"type":"number","title":"Liquidity Adjustment"},"time_to_liquidate":{"type":"integer","title":"Time To Liquidate"}},"type":"object","required":["base_var","liquidity_adjustment","time_to_liquidate"],"title":"LiquidityAdjustedVaRRequest"},"LocalVolatilityRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"},"strikes":{"items":{"type":"number"},"type":"array","title":"Strikes"},"expiries":{"items":{"type":"string"},"type":"array","title":"Expiries"},"local_vols":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Local Vols"}},"type":"object","required":["reference_date","strikes","expiries","local_vols"],"title":"LocalVolatilityRequest"},"LogLinearInterpRequest":{"properties":{"x_values":{"items":{"type":"number"},"type":"array","title":"X Values"},"y_values":{"items":{"type":"number"},"type":"array","title":"Y Values"},"x_interp":{"type":"number","title":"X Interp"}},"type":"object","required":["x_values","y_values","x_interp"],"title":"LogLinearInterpRequest"},"LogMessageRequest":{"properties":{"message":{"type":"string","title":"Message"},"level":{"type":"string","title":"Level","default":"INFO"}},"type":"object","required":["message"],"title":"LogMessageRequest"},"LookbackOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"lookback_type":{"type":"string","title":"Lookback Type"},"strike":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Strike"},"expiry_date":{"type":"string","title":"Expiry Date"}},"type":"object","required":["option_type","lookback_type","expiry_date"],"title":"LookbackOptionRequest"},"MTMCrossCurrencySwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional_domestic":{"type":"number","title":"Notional Domestic"},"notional_foreign":{"type":"number","title":"Notional Foreign"},"domestic_currency":{"type":"string","title":"Domestic Currency"},"foreign_currency":{"type":"string","title":"Foreign Currency"}},"type":"object","required":["effective_date","termination_date","notional_domestic","notional_foreign","domestic_currency","foreign_currency"],"title":"MTMCrossCurrencySwapRequest"},"MandatoryConvertibleRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"coupon_rate":{"type":"number","title":"Coupon Rate"},"conversion_ratio":{"type":"number","title":"Conversion Ratio"}},"type":"object","required":["issue_date","maturity_date","coupon_rate","conversion_ratio"],"title":"MandatoryConvertibleRequest"},"MarginalRiskContributionRequest":{"properties":{"weights":{"items":{"type":"number"},"type":"array","title":"Weights"},"covariance_matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Covariance Matrix"}},"type":"object","required":["weights","covariance_matrix"],"title":"MarginalRiskContributionRequest"},"MathRequest":{"properties":{"x":{"type":"number","title":"X"}},"type":"object","required":["x"],"title":"MathRequest"},"MatrixMultiplyRequest":{"properties":{"matrix_a":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Matrix A"},"matrix_b":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Matrix B"}},"type":"object","required":["matrix_a","matrix_b"],"title":"MatrixMultiplyRequest"},"MatrixUtilRequest":{"properties":{"matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Matrix"}},"type":"object","required":["matrix"],"title":"MatrixUtilRequest"},"MaxSharpePortfolioRequest":{"properties":{"expected_returns":{"items":{"type":"number"},"type":"array","title":"Expected Returns"},"covariance_matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Covariance Matrix"},"risk_free_rate":{"type":"number","title":"Risk Free Rate","default":0.0}},"type":"object","required":["expected_returns","covariance_matrix"],"title":"MaxSharpePortfolioRequest"},"MeanRequest":{"properties":{"data":{"items":{"type":"number"},"type":"array","title":"Data"}},"type":"object","required":["data"],"title":"MeanRequest"},"MeanVarianceOptimizerRequest":{"properties":{"expected_returns":{"items":{"type":"number"},"type":"array","title":"Expected Returns"},"covariance_matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Covariance Matrix"},"constraints":{"anyOf":[{"$ref":"#/components/schemas/PortfolioConstraintsRequest"},{"type":"null"}]}},"type":"object","required":["expected_returns","covariance_matrix"],"title":"MeanVarianceOptimizerRequest"},"MertonCallPriceRequest":{"properties":{"spot":{"type":"number","title":"Spot"},"strike":{"type":"number","title":"Strike"},"expiry":{"type":"number","title":"Expiry"},"risk_free_rate":{"type":"number","title":"Risk Free Rate"},"volatility":{"type":"number","title":"Volatility"},"lambda":{"type":"number","title":"Lambda"},"mu_j":{"type":"number","title":"Mu J"},"sigma_j":{"type":"number","title":"Sigma J"}},"type":"object","required":["spot","strike","expiry","risk_free_rate","volatility","lambda","mu_j","sigma_j"],"title":"MertonCallPriceRequest"},"MertonJumpDiffusionRequest":{"properties":{"spot":{"type":"number","title":"Spot"},"risk_free_rate":{"type":"number","title":"Risk Free Rate"},"volatility":{"type":"number","title":"Volatility"},"parameters":{"$ref":"#/components/schemas/MertonParametersRequest"}},"type":"object","required":["spot","risk_free_rate","volatility","parameters"],"title":"MertonJumpDiffusionRequest"},"MertonParametersRequest":{"properties":{"lambda":{"type":"number","title":"Lambda"},"mu_j":{"type":"number","title":"Mu J"},"sigma_j":{"type":"number","title":"Sigma J"}},"type":"object","required":["lambda","mu_j","sigma_j"],"title":"MertonParametersRequest"},"MessageCreate":{"properties":{"message":{"type":"string","title":"Message"}},"type":"object","required":["message"],"title":"MessageCreate"},"MinVariancePortfolioRequest":{"properties":{"expected_returns":{"items":{"type":"number"},"type":"array","title":"Expected Returns"},"covariance_matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Covariance Matrix"}},"type":"object","required":["expected_returns","covariance_matrix"],"title":"MinVariancePortfolioRequest"},"MoneyRequest":{"properties":{"amount":{"type":"number","title":"Amount"},"currency_code":{"type":"string","title":"Currency Code"}},"type":"object","required":["amount","currency_code"],"title":"MoneyRequest"},"MonteCarloVaRRequest":{"properties":{"simulations":{"type":"integer","title":"Simulations","default":10000},"confidence_level":{"type":"number","title":"Confidence Level","default":0.95},"time_horizon":{"type":"integer","title":"Time Horizon","default":1}},"type":"object","title":"MonteCarloVaRRequest"},"MortgageBackedSecurityRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"notional":{"type":"number","title":"Notional"},"coupon_rate":{"type":"number","title":"Coupon Rate"},"prepayment_speed":{"type":"number","title":"Prepayment Speed"}},"type":"object","required":["issue_date","maturity_date","notional","coupon_rate","prepayment_speed"],"title":"MortgageBackedSecurityRequest"},"MultiVesselRequest":{"properties":{"imos":{"items":{"type":"string"},"type":"array","title":"Imos"}},"type":"object","required":["imos"],"title":"MultiVesselRequest"},"MulticurveRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"},"discount_tenors":{"items":{"type":"number"},"type":"array","title":"Discount Tenors"},"discount_values":{"items":{"type":"number"},"type":"array","title":"Discount Values"}},"type":"object","required":["reference_date","discount_tenors","discount_values"],"title":"MulticurveRequest"},"NelsonSiegelRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"},"beta0":{"type":"number","title":"Beta0"},"beta1":{"type":"number","title":"Beta1"},"beta2":{"type":"number","title":"Beta2"},"tau":{"type":"number","title":"Tau"}},"type":"object","required":["reference_date","beta0","beta1","beta2","tau"],"title":"NelsonSiegelRequest"},"NelsonSiegelSvenssonRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"},"beta0":{"type":"number","title":"Beta0"},"beta1":{"type":"number","title":"Beta1"},"beta2":{"type":"number","title":"Beta2"},"beta3":{"type":"number","title":"Beta3"},"tau1":{"type":"number","title":"Tau1"},"tau2":{"type":"number","title":"Tau2"}},"type":"object","required":["reference_date","beta0","beta1","beta2","beta3","tau1","tau2"],"title":"NelsonSiegelSvenssonRequest"},"NewsAnalysisRequest":{"properties":{"url":{"type":"string","title":"Url"}},"type":"object","required":["url"],"title":"NewsAnalysisRequest"},"NewsCategory":{"type":"string","enum":["business","technology","sports","entertainment","health","science","politics","world","local"],"title":"NewsCategory"},"NewsRequest":{"properties":{"domains":{"items":{"type":"string"},"type":"array","title":"Domains"},"category":{"anyOf":[{"$ref":"#/components/schemas/NewsCategory"},{"type":"null"}]},"country":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Country"},"language":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Language","default":"en"},"limit":{"type":"integer","title":"Limit","default":10}},"type":"object","required":["domains"],"title":"NewsRequest"},"NewsletterSubscribe":{"properties":{"email":{"type":"string","format":"email","title":"Email"},"source":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Source","default":"website"}},"type":"object","required":["email"],"title":"NewsletterSubscribe"},"NextIMMDateRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"}},"type":"object","required":["reference_date"],"title":"NextIMMDateRequest"},"NormalRandomRequest":{"properties":{"seed":{"type":"integer","title":"Seed","default":42},"size":{"type":"integer","title":"Size","default":1},"mean":{"type":"number","title":"Mean","default":0.0},"std_dev":{"type":"number","title":"Std Dev","default":1.0}},"type":"object","title":"NormalRandomRequest"},"NthToDefaultSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"spread":{"type":"number","title":"Spread"},"reference_names":{"items":{"type":"string"},"type":"array","title":"Reference Names"},"nth":{"type":"integer","title":"Nth"}},"type":"object","required":["effective_date","termination_date","notional","spread","reference_names","nth"],"title":"NthToDefaultSwapRequest"},"NthWeekdayRequest":{"properties":{"year":{"type":"integer","title":"Year"},"month":{"type":"integer","title":"Month"},"weekday":{"type":"integer","title":"Weekday"},"n":{"type":"integer","title":"N"}},"type":"object","required":["year","month","weekday","n"],"title":"NthWeekdayRequest"},"NumericalDerivativeRequest":{"properties":{"x_values":{"items":{"type":"number"},"type":"array","title":"X Values"},"y_values":{"items":{"type":"number"},"type":"array","title":"Y Values"}},"type":"object","required":["x_values","y_values"],"title":"NumericalDerivativeRequest"},"OTPVerification":{"properties":{"email":{"type":"string","format":"email","title":"Email"},"otp":{"type":"string","title":"Otp"}},"type":"object","required":["email","otp"],"title":"OTPVerification"},"OptimizationRequest":{"properties":{"func_name":{"type":"string","title":"Func Name"},"initial_guess":{"items":{"type":"number"},"type":"array","title":"Initial Guess"},"tolerance":{"type":"number","title":"Tolerance","default":1e-06},"max_iterations":{"type":"integer","title":"Max Iterations","default":100}},"type":"object","required":["func_name","initial_guess"],"title":"OptimizationRequest"},"OptimizationResultRequest":{"properties":{"weights":{"items":{"type":"number"},"type":"array","title":"Weights"},"expected_return":{"type":"number","title":"Expected Return"},"volatility":{"type":"number","title":"Volatility"},"sharpe_ratio":{"type":"number","title":"Sharpe Ratio"}},"type":"object","required":["weights","expected_return","volatility","sharpe_ratio"],"title":"OptimizationResultRequest"},"OvernightIndexSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"fixed_rate":{"type":"number","title":"Fixed Rate"},"ois_index":{"type":"string","title":"Ois Index"}},"type":"object","required":["effective_date","termination_date","notional","fixed_rate","ois_index"],"title":"OvernightIndexSwapRequest"},"ParametricVaRRequest":{"properties":{"mean":{"type":"number","title":"Mean"},"std_dev":{"type":"number","title":"Std Dev"},"confidence_level":{"type":"number","title":"Confidence Level","default":0.95},"portfolio_value":{"type":"number","title":"Portfolio Value"}},"type":"object","required":["mean","std_dev","portfolio_value"],"title":"ParametricVaRRequest"},"PasswordReset":{"properties":{"email":{"type":"string","format":"email","title":"Email"}},"type":"object","required":["email"],"title":"PasswordReset"},"PasswordResetConfirm":{"properties":{"email":{"type":"string","format":"email","title":"Email"},"otp":{"type":"string","title":"Otp"},"new_password":{"type":"string","title":"New Password"}},"type":"object","required":["email","otp","new_password"],"title":"PasswordResetConfirm"},"PortfolioConstraintsRequest":{"properties":{"min_weights":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Min Weights"},"max_weights":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Max Weights"},"target_return":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Target Return"},"max_volatility":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Max Volatility"}},"type":"object","title":"PortfolioConstraintsRequest"},"PortfolioRiskRequest":{"properties":{"weights":{"items":{"type":"number"},"type":"array","title":"Weights"},"covariance_matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Covariance Matrix"}},"type":"object","required":["weights","covariance_matrix"],"title":"PortfolioRiskRequest"},"PowerRequest":{"properties":{"x":{"type":"number","title":"X"},"y":{"type":"number","title":"Y"}},"type":"object","required":["x","y"],"title":"PowerRequest"},"ProfileFunctionRequest":{"properties":{"function_name":{"type":"string","title":"Function Name"},"args":{"items":{},"type":"array","title":"Args","default":[]}},"type":"object","required":["function_name"],"title":"ProfileFunctionRequest"},"PuttableBondRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"coupon_rate":{"type":"number","title":"Coupon Rate"},"face_value":{"type":"number","title":"Face Value","default":100.0}},"type":"object","required":["issue_date","maturity_date","coupon_rate"],"title":"PuttableBondRequest"},"PuttableSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"fixed_rate":{"type":"number","title":"Fixed Rate"}},"type":"object","required":["effective_date","termination_date","notional","fixed_rate"],"title":"PuttableSwapRequest"},"QuantoOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"strike":{"type":"number","title":"Strike"},"expiry_date":{"type":"string","title":"Expiry Date"},"quanto_factor":{"type":"number","title":"Quanto Factor"}},"type":"object","required":["option_type","strike","expiry_date","quanto_factor"],"title":"QuantoOptionRequest"},"RFRBasisSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"rfr1":{"type":"string","title":"Rfr1"},"rfr2":{"type":"string","title":"Rfr2"},"spread":{"type":"number","title":"Spread"}},"type":"object","required":["effective_date","termination_date","notional","rfr1","rfr2","spread"],"title":"RFRBasisSwapRequest"},"RFRFixingRequest":{"properties":{"index_name":{"type":"string","title":"Index Name"},"fixing_date":{"type":"string","title":"Fixing Date"},"value":{"type":"number","title":"Value"},"source":{"type":"string","title":"Source","default":"Manual"}},"type":"object","required":["index_name","fixing_date","value"],"title":"RFRFixingRequest"},"RFRIndexRequest":{"properties":{"name":{"type":"string","title":"Name"},"currency":{"type":"string","title":"Currency"}},"type":"object","required":["name","currency"],"title":"RFRIndexRequest"},"RainbowOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"strike":{"type":"number","title":"Strike"},"expiry_date":{"type":"string","title":"Expiry Date"},"num_assets":{"type":"integer","title":"Num Assets"}},"type":"object","required":["option_type","strike","expiry_date","num_assets"],"title":"RainbowOptionRequest"},"RangeAccrualSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"lower_barrier":{"type":"number","title":"Lower Barrier"},"upper_barrier":{"type":"number","title":"Upper Barrier"}},"type":"object","required":["effective_date","termination_date","notional","lower_barrier","upper_barrier"],"title":"RangeAccrualSwapRequest"},"RealizedVarianceRequest":{"properties":{"prices":{"items":{"type":"number"},"type":"array","title":"Prices"},"annualization_factor":{"type":"number","title":"Annualization Factor","default":252.0}},"type":"object","required":["prices"],"title":"RealizedVarianceRequest"},"RepoRequest":{"properties":{"start_date":{"type":"string","title":"Start Date"},"end_date":{"type":"string","title":"End Date"},"notional":{"type":"number","title":"Notional"},"repo_rate":{"type":"number","title":"Repo Rate"}},"type":"object","required":["start_date","end_date","notional","repo_rate"],"title":"RepoRequest"},"ReverseConvertibleRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"coupon_rate":{"type":"number","title":"Coupon Rate"},"knock_in_barrier":{"type":"number","title":"Knock In Barrier"}},"type":"object","required":["issue_date","maturity_date","coupon_rate","knock_in_barrier"],"title":"ReverseConvertibleRequest"},"RiskParityRequest":{"properties":{"covariance_matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Covariance Matrix"},"target_risk":{"anyOf":[{"items":{"type":"number"},"type":"array"},{"type":"null"}],"title":"Target Risk"}},"type":"object","required":["covariance_matrix"],"title":"RiskParityRequest"},"RollCurveRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"},"tenors":{"items":{"type":"number"},"type":"array","title":"Tenors"},"values":{"items":{"type":"number"},"type":"array","title":"Values"},"days":{"type":"integer","title":"Days"}},"type":"object","required":["reference_date","tenors","values","days"],"title":"RollCurveRequest"},"SABRImpliedVolRequest":{"properties":{"forward":{"type":"number","title":"Forward"},"strike":{"type":"number","title":"Strike"},"expiry":{"type":"number","title":"Expiry"},"alpha":{"type":"number","title":"Alpha"},"beta":{"type":"number","title":"Beta"},"rho":{"type":"number","title":"Rho"},"nu":{"type":"number","title":"Nu"}},"type":"object","required":["forward","strike","expiry","alpha","beta","rho","nu"],"title":"SABRImpliedVolRequest"},"SABRModelEnhancedRequest":{"properties":{"forward":{"type":"number","title":"Forward"},"expiry":{"type":"number","title":"Expiry"},"parameters":{"$ref":"#/components/schemas/SABRParametersEnhancedRequest"}},"type":"object","required":["forward","expiry","parameters"],"title":"SABRModelEnhancedRequest"},"SABRModelRequest":{"properties":{"forward":{"type":"number","title":"Forward"},"expiry":{"type":"number","title":"Expiry"},"parameters":{"$ref":"#/components/schemas/SABRParametersRequest"}},"type":"object","required":["forward","expiry","parameters"],"title":"SABRModelRequest"},"SABRParametersEnhancedRequest":{"properties":{"alpha":{"type":"number","title":"Alpha"},"beta":{"type":"number","title":"Beta"},"rho":{"type":"number","title":"Rho"},"nu":{"type":"number","title":"Nu"}},"type":"object","required":["alpha","beta","rho","nu"],"title":"SABRParametersEnhancedRequest"},"SABRParametersRequest":{"properties":{"alpha":{"type":"number","title":"Alpha"},"beta":{"type":"number","title":"Beta"},"rho":{"type":"number","title":"Rho"},"nu":{"type":"number","title":"Nu"}},"type":"object","required":["alpha","beta","rho","nu"],"title":"SABRParametersRequest"},"SSVIRequest":{"properties":{"theta_t":{"type":"number","title":"Theta T"},"phi":{"type":"number","title":"Phi"},"rho":{"type":"number","title":"Rho"}},"type":"object","required":["theta_t","phi","rho"],"title":"SSVIRequest"},"STIRFutureRequest":{"properties":{"delivery_date":{"type":"string","title":"Delivery Date"},"contract_size":{"type":"number","title":"Contract Size"},"price":{"type":"number","title":"Price"}},"type":"object","required":["delivery_date","contract_size","price"],"title":"STIRFutureRequest"},"SVDRequest":{"properties":{"matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Matrix"}},"type":"object","required":["matrix"],"title":"SVDRequest"},"SVIRequest":{"properties":{"a":{"type":"number","title":"A"},"b":{"type":"number","title":"B"},"rho":{"type":"number","title":"Rho"},"m":{"type":"number","title":"M"},"sigma":{"type":"number","title":"Sigma"}},"type":"object","required":["a","b","rho","m","sigma"],"title":"SVIRequest"},"ScheduleRequest":{"properties":{"start_date":{"type":"string","title":"Start Date"},"end_date":{"type":"string","title":"End Date"},"frequency":{"type":"string","title":"Frequency","default":"SEMI_ANNUAL"}},"type":"object","required":["start_date","end_date"],"title":"ScheduleRequest"},"SecantMethodRequest":{"properties":{"func_name":{"type":"string","title":"Func Name"},"x0":{"type":"number","title":"X0"},"x1":{"type":"number","title":"X1"},"tolerance":{"type":"number","title":"Tolerance","default":1e-06},"max_iterations":{"type":"integer","title":"Max Iterations","default":100}},"type":"object","required":["func_name","x0","x1"],"title":"SecantMethodRequest"},"ShiftCurveRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"},"tenors":{"items":{"type":"number"},"type":"array","title":"Tenors"},"values":{"items":{"type":"number"},"type":"array","title":"Values"},"shift":{"type":"number","title":"Shift"}},"type":"object","required":["reference_date","tenors","values","shift"],"title":"ShiftCurveRequest"},"ShortRateParametersRequest":{"properties":{"mean_reversion":{"type":"number","title":"Mean Reversion"},"volatility":{"type":"number","title":"Volatility"},"long_term_rate":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Long Term Rate"}},"type":"object","required":["mean_reversion","volatility"],"title":"ShortRateParametersRequest"},"SingleCurrencyBasisSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"spread":{"type":"number","title":"Spread"}},"type":"object","required":["effective_date","termination_date","notional","spread"],"title":"SingleCurrencyBasisSwapRequest"},"SolverUtilRequest":{"properties":{"a":{"type":"number","title":"A"},"b":{"type":"number","title":"B"},"tolerance":{"type":"number","title":"Tolerance","default":1e-06}},"type":"object","required":["a","b"],"title":"SolverUtilRequest"},"SpeechInput":{"properties":{"text":{"type":"string","maxLength":500000,"minLength":50,"title":"Text","description":"Raw speech text (50-500K chars)"}},"type":"object","required":["text"],"title":"SpeechInput"},"SpreadOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"strike":{"type":"number","title":"Strike"},"expiry_date":{"type":"string","title":"Expiry Date"}},"type":"object","required":["option_type","strike","expiry_date"],"title":"SpreadOptionRequest"},"StandardDeviationRequest":{"properties":{"data":{"items":{"type":"number"},"type":"array","title":"Data"}},"type":"object","required":["data"],"title":"StandardDeviationRequest"},"SwaptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"strike":{"type":"number","title":"Strike"},"expiry_date":{"type":"string","title":"Expiry Date"},"swap_start":{"type":"string","title":"Swap Start"},"swap_end":{"type":"string","title":"Swap End"},"notional":{"type":"number","title":"Notional"}},"type":"object","required":["option_type","strike","expiry_date","swap_start","swap_end","notional"],"title":"SwaptionRequest"},"SwitzerlandCalendarRequest":{"properties":{"calendar_type":{"type":"string","title":"Calendar Type","default":"TARGET"}},"type":"object","title":"SwitzerlandCalendarRequest"},"SystemConfigRequest":{"properties":{"config_key":{"type":"string","title":"Config Key"},"config_value":{"type":"string","title":"Config Value"},"config_type":{"type":"string","title":"Config Type","default":"string"},"description":{"type":"string","title":"Description","default":""}},"type":"object","required":["config_key","config_value"],"title":"SystemConfigRequest"},"TARNRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"target_redemption":{"type":"number","title":"Target Redemption"}},"type":"object","required":["effective_date","termination_date","notional","target_redemption"],"title":"TARNRequest"},"TargetReturnPortfolioRequest":{"properties":{"expected_returns":{"items":{"type":"number"},"type":"array","title":"Expected Returns"},"covariance_matrix":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Covariance Matrix"},"target_return":{"type":"number","title":"Target Return"}},"type":"object","required":["expected_returns","covariance_matrix","target_return"],"title":"TargetReturnPortfolioRequest"},"TaylorExpandRequest":{"properties":{"func_name":{"type":"string","title":"Func Name"},"x":{"type":"number","title":"X"},"order":{"type":"integer","title":"Order","default":2}},"type":"object","required":["func_name","x"],"title":"TaylorExpandRequest"},"TenorBasisSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"pay_tenor":{"type":"string","title":"Pay Tenor"},"receive_tenor":{"type":"string","title":"Receive Tenor"},"spread":{"type":"number","title":"Spread"}},"type":"object","required":["effective_date","termination_date","notional","pay_tenor","receive_tenor","spread"],"title":"TenorBasisSwapRequest"},"TermStructureVolatilityRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"},"expiries":{"items":{"type":"string"},"type":"array","title":"Expiries"},"volatilities":{"items":{"type":"number"},"type":"array","title":"Volatilities"}},"type":"object","required":["reference_date","expiries","volatilities"],"title":"TermStructureVolatilityRequest"},"TicketCreate":{"properties":{"subject":{"type":"string","title":"Subject"},"description":{"type":"string","title":"Description"},"category":{"type":"string","title":"Category"},"priority":{"type":"string","title":"Priority","default":"medium"}},"type":"object","required":["subject","description","category"],"title":"TicketCreate"},"TicketUpdate":{"properties":{"status":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Status"}},"type":"object","title":"TicketUpdate"},"ToDateRequest":{"properties":{"value":{"title":"Value"}},"type":"object","required":["value"],"title":"ToDateRequest"},"ToDateTimeRequest":{"properties":{"date_str":{"type":"string","title":"Date Str"}},"type":"object","required":["date_str"],"title":"ToDateTimeRequest"},"TopicSearchRequest":{"properties":{"keywords":{"items":{"type":"string"},"type":"array","title":"Keywords"},"domains":{"anyOf":[{"items":{"type":"string"},"type":"array"},{"type":"null"}],"title":"Domains"},"country":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Country"},"limit":{"type":"integer","title":"Limit","default":10}},"type":"object","required":["keywords"],"title":"TopicSearchRequest"},"TotalReturnSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"reference_asset":{"type":"string","title":"Reference Asset"},"funding_spread":{"type":"number","title":"Funding Spread"}},"type":"object","required":["effective_date","termination_date","notional","reference_asset","funding_spread"],"title":"TotalReturnSwapRequest"},"TrancheRequest":{"properties":{"attachment_point":{"type":"number","title":"Attachment Point"},"detachment_point":{"type":"number","title":"Detachment Point"},"notional":{"type":"number","title":"Notional"}},"type":"object","required":["attachment_point","detachment_point","notional"],"title":"TrancheRequest"},"TreasuryBillRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"face_value":{"type":"number","title":"Face Value","default":100.0},"discount_rate":{"type":"number","title":"Discount Rate"}},"type":"object","required":["issue_date","maturity_date","discount_rate"],"title":"TreasuryBillRequest"},"TwistCurveRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"},"tenors":{"items":{"type":"number"},"type":"array","title":"Tenors"},"values":{"items":{"type":"number"},"type":"array","title":"Values"},"short_shift":{"type":"number","title":"Short Shift"},"long_shift":{"type":"number","title":"Long Shift"}},"type":"object","required":["reference_date","tenors","values","short_shift","long_shift"],"title":"TwistCurveRequest"},"TypeCheckRequest":{"properties":{"value":{"title":"Value"}},"type":"object","required":["value"],"title":"TypeCheckRequest"},"UnadjustedRequest":{"properties":{"date":{"type":"string","title":"Date"}},"type":"object","required":["date"],"title":"UnadjustedRequest"},"UniformRandomRequest":{"properties":{"seed":{"type":"integer","title":"Seed","default":42},"size":{"type":"integer","title":"Size","default":1}},"type":"object","title":"UniformRandomRequest"},"UserCreateRequest":{"properties":{"username":{"type":"string","title":"Username"},"email":{"type":"string","format":"email","title":"Email"},"password":{"type":"string","title":"Password"},"account_type":{"type":"string","title":"Account Type","default":"free"},"is_admin":{"type":"boolean","title":"Is Admin","default":false},"is_verified":{"type":"boolean","title":"Is Verified","default":true},"credit_balance":{"type":"integer","title":"Credit Balance","default":0}},"type":"object","required":["username","email","password"],"title":"UserCreateRequest"},"UserLogin":{"properties":{"email":{"type":"string","format":"email","title":"Email"},"password":{"type":"string","title":"Password"}},"type":"object","required":["email","password"],"title":"UserLogin"},"UserRegistration":{"properties":{"username":{"type":"string","title":"Username"},"email":{"type":"string","format":"email","title":"Email"},"password":{"type":"string","title":"Password"},"phone":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Phone"},"country":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Country"},"country_code":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Country Code"}},"type":"object","required":["username","email","password"],"title":"UserRegistration"},"UserUpdateRequest":{"properties":{"username":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Username"},"email":{"anyOf":[{"type":"string","format":"email"},{"type":"null"}],"title":"Email"},"account_type":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Account Type"},"is_verified":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Is Verified"},"is_admin":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Is Admin"},"credit_balance":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Credit Balance"}},"type":"object","title":"UserUpdateRequest"},"VGCallPriceRequest":{"properties":{"spot":{"type":"number","title":"Spot"},"strike":{"type":"number","title":"Strike"},"expiry":{"type":"number","title":"Expiry"},"risk_free_rate":{"type":"number","title":"Risk Free Rate"},"sigma":{"type":"number","title":"Sigma"},"nu":{"type":"number","title":"Nu"},"theta":{"type":"number","title":"Theta"}},"type":"object","required":["spot","strike","expiry","risk_free_rate","sigma","nu","theta"],"title":"VGCallPriceRequest"},"VGParametersRequest":{"properties":{"sigma":{"type":"number","title":"Sigma"},"nu":{"type":"number","title":"Nu"},"theta":{"type":"number","title":"Theta"}},"type":"object","required":["sigma","nu","theta"],"title":"VGParametersRequest"},"ValidateCurrencyRequest":{"properties":{"currency_code":{"type":"string","title":"Currency Code"}},"type":"object","required":["currency_code"],"title":"ValidateCurrencyRequest"},"ValidatePositiveRequest":{"properties":{"value":{"type":"number","title":"Value"}},"type":"object","required":["value"],"title":"ValidatePositiveRequest"},"ValidateProbabilityRequest":{"properties":{"value":{"type":"number","title":"Value"}},"type":"object","required":["value"],"title":"ValidateProbabilityRequest"},"ValidateRangeRequest":{"properties":{"value":{"type":"number","title":"Value"},"min_val":{"type":"number","title":"Min Val"},"max_val":{"type":"number","title":"Max Val"}},"type":"object","required":["value","min_val","max_val"],"title":"ValidateRangeRequest"},"ValidateRateRequest":{"properties":{"rate":{"type":"number","title":"Rate"}},"type":"object","required":["rate"],"title":"ValidateRateRequest"},"ValidateTenorRequest":{"properties":{"tenor":{"type":"string","title":"Tenor"}},"type":"object","required":["tenor"],"title":"ValidateTenorRequest"},"ValidateValueRequest":{"properties":{"value":{"type":"number","title":"Value"}},"type":"object","required":["value"],"title":"ValidateValueRequest"},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"},"VanillaOptionRequest":{"properties":{"option_type":{"type":"string","title":"Option Type"},"strike":{"type":"number","title":"Strike"},"expiry_date":{"type":"string","title":"Expiry Date"},"spot":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Spot"}},"type":"object","required":["option_type","strike","expiry_date"],"title":"VanillaOptionRequest"},"VarianceGammaRequest":{"properties":{"spot":{"type":"number","title":"Spot"},"risk_free_rate":{"type":"number","title":"Risk Free Rate"},"parameters":{"$ref":"#/components/schemas/VGParametersRequest"}},"type":"object","required":["spot","risk_free_rate","parameters"],"title":"VarianceGammaRequest"},"VarianceRequest":{"properties":{"data":{"items":{"type":"number"},"type":"array","title":"Data"}},"type":"object","required":["data"],"title":"VarianceRequest"},"VarianceSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"strike_variance":{"type":"number","title":"Strike Variance"}},"type":"object","required":["effective_date","termination_date","notional","strike_variance"],"title":"VarianceSwapRequest"},"VasicekModelRequest":{"properties":{"r0":{"type":"number","title":"R0"},"a":{"type":"number","title":"A"},"b":{"type":"number","title":"B"},"sigma":{"type":"number","title":"Sigma"}},"type":"object","required":["r0","a","b","sigma"],"title":"VasicekModelRequest"},"VectorCrossProductRequest":{"properties":{"vector1":{"items":{"type":"number"},"type":"array","title":"Vector1"},"vector2":{"items":{"type":"number"},"type":"array","title":"Vector2"}},"type":"object","required":["vector1","vector2"],"title":"VectorCrossProductRequest"},"VectorDotProductRequest":{"properties":{"vector1":{"items":{"type":"number"},"type":"array","title":"Vector1"},"vector2":{"items":{"type":"number"},"type":"array","title":"Vector2"}},"type":"object","required":["vector1","vector2"],"title":"VectorDotProductRequest"},"VectorNormRequest":{"properties":{"vector":{"items":{"type":"number"},"type":"array","title":"Vector"}},"type":"object","required":["vector"],"title":"VectorNormRequest"},"VesselPositionRequest":{"properties":{"imo":{"type":"string","title":"Imo"}},"type":"object","required":["imo"],"title":"VesselPositionRequest"},"ViewRequest":{"properties":{"view_type":{"type":"string","title":"View Type"},"assets":{"items":{"type":"integer"},"type":"array","title":"Assets"},"expected_return":{"type":"number","title":"Expected Return"},"confidence":{"type":"number","title":"Confidence","default":1.0}},"type":"object","required":["view_type","assets","expected_return"],"title":"ViewRequest"},"VisualAnalysisRequest":{"properties":{"image_url":{"type":"string","title":"Image Url"},"prompt":{"type":"string","title":"Prompt"},"max_tokens":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Max Tokens","default":4096},"temperature":{"anyOf":[{"type":"number"},{"type":"null"}],"title":"Temperature","default":0.7},"enable_thinking":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Enable Thinking","default":false}},"type":"object","required":["image_url","prompt"],"title":"VisualAnalysisRequest"},"VolatilityCubeRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"},"strikes":{"items":{"type":"number"},"type":"array","title":"Strikes"},"expiries":{"items":{"type":"string"},"type":"array","title":"Expiries"},"tenors":{"items":{"type":"string"},"type":"array","title":"Tenors"},"volatilities":{"items":{"items":{"items":{"type":"number"},"type":"array"},"type":"array"},"type":"array","title":"Volatilities"}},"type":"object","required":["reference_date","strikes","expiries","tenors","volatilities"],"title":"VolatilityCubeRequest"},"VolatilitySurfaceRequest":{"properties":{"reference_date":{"type":"string","title":"Reference Date"},"strikes":{"items":{"type":"number"},"type":"array","title":"Strikes"},"expiries":{"items":{"type":"string"},"type":"array","title":"Expiries"},"volatilities":{"items":{"items":{"type":"number"},"type":"array"},"type":"array","title":"Volatilities"}},"type":"object","required":["reference_date","strikes","expiries","volatilities"],"title":"VolatilitySurfaceRequest"},"VolatilitySwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"strike_volatility":{"type":"number","title":"Strike Volatility"}},"type":"object","required":["effective_date","termination_date","notional","strike_volatility"],"title":"VolatilitySwapRequest"},"WeatherDerivativeRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"strike_temperature":{"type":"number","title":"Strike Temperature"}},"type":"object","required":["effective_date","termination_date","notional","strike_temperature"],"title":"WeatherDerivativeRequest"},"WeatherIndexRequest":{"properties":{"name":{"type":"string","title":"Name"},"location":{"type":"string","title":"Location"}},"type":"object","required":["name","location"],"title":"WeatherIndexRequest"},"WebSearchRequest":{"properties":{"query":{"type":"string","title":"Query"},"engine":{"type":"string","title":"Engine","default":"google"}},"type":"object","required":["query"],"title":"WebSearchRequest"},"YearFractionRequest":{"properties":{"start_date":{"type":"string","title":"Start Date"},"end_date":{"type":"string","title":"End Date"},"convention":{"type":"string","title":"Convention","default":"Actual360"}},"type":"object","required":["start_date","end_date"],"title":"YearFractionRequest"},"YearOnYearInflationSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"fixed_rate":{"type":"number","title":"Fixed Rate"},"inflation_index":{"type":"string","title":"Inflation Index"}},"type":"object","required":["effective_date","termination_date","notional","fixed_rate","inflation_index"],"title":"YearOnYearInflationSwapRequest"},"ZeroCouponBondRequest":{"properties":{"issue_date":{"type":"string","title":"Issue Date"},"maturity_date":{"type":"string","title":"Maturity Date"},"face_value":{"type":"number","title":"Face Value","default":100.0}},"type":"object","required":["issue_date","maturity_date"],"title":"ZeroCouponBondRequest"},"ZeroCouponInflationSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"fixed_rate":{"type":"number","title":"Fixed Rate"},"inflation_index":{"type":"string","title":"Inflation Index"}},"type":"object","required":["effective_date","termination_date","notional","fixed_rate","inflation_index"],"title":"ZeroCouponInflationSwapRequest"},"ZeroCouponSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"},"fixed_rate":{"type":"number","title":"Fixed Rate"}},"type":"object","required":["effective_date","termination_date","notional","fixed_rate"],"title":"ZeroCouponSwapRequest"},"ZeroZeroSwapRequest":{"properties":{"effective_date":{"type":"string","title":"Effective Date"},"termination_date":{"type":"string","title":"Termination Date"},"notional":{"type":"number","title":"Notional"}},"type":"object","required":["effective_date","termination_date","notional"],"title":"ZeroZeroSwapRequest"},"quantlib_core__ValidateDateOrderRequest":{"properties":{"start_date":{"type":"string","title":"Start Date"},"end_date":{"type":"string","title":"End Date"}},"type":"object","required":["start_date","end_date"],"title":"ValidateDateOrderRequest"},"quantlib_risk__VaRRequest":{"properties":{"returns":{"items":{"type":"number"},"type":"array","title":"Returns"},"confidence_level":{"type":"number","title":"Confidence Level","default":0.95}},"type":"object","required":["returns"],"title":"VaRRequest"},"quantlib_solver__NewtonRaphsonRequest":{"properties":{"tolerance":{"type":"number","title":"Tolerance","default":1e-06},"max_iterations":{"type":"integer","title":"Max Iterations","default":100}},"type":"object","title":"NewtonRaphsonRequest"},"quantlib_utils__CalendarRequest":{"properties":{"date":{"type":"string","title":"Date"}},"type":"object","required":["date"],"title":"CalendarRequest"},"quantlib_utils__DayCountRequest":{"properties":{"start_date":{"type":"string","title":"Start Date"},"end_date":{"type":"string","title":"End Date"}},"type":"object","required":["start_date","end_date"],"title":"DayCountRequest"},"quantlib_utils__NewtonRaphsonRequest":{"properties":{"func_name":{"type":"string","title":"Func Name"},"initial_guess":{"type":"number","title":"Initial Guess"},"tolerance":{"type":"number","title":"Tolerance","default":1e-06},"max_iterations":{"type":"integer","title":"Max Iterations","default":100}},"type":"object","required":["func_name","initial_guess"],"title":"NewtonRaphsonRequest"}},"securitySchemes":{"APIKeyHeader":{"type":"apiKey","in":"header","name":"X-API-Key"}}}}
\ No newline at end of file