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.

codebase improvements

tilakpatel22d7b069d80d02
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index 1bfb340cd..c6e234620 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -1295,7 +1295,6 @@ set(SERVICE_SOURCES
src/services/data_normalization/DataNormalizationService.cpp
src/services/data_normalization/DataMappingTestClient.cpp
src/core/services/Services.cpp
- src/python/ScriptCatalog.cpp
# NewsService split; see NewsService.cpp header.
src/services/news/NewsService.cpp
src/services/news/NewsService_LiveFeed.cpp
@@ -1563,6 +1562,7 @@ set(SCREEN_SOURCES
src/screens/trade_viz/TradeVizScreen.cpp
# DocsScreen split into pages files; see DocsScreen.cpp header.
src/screens/docs/DocsScreen.cpp
+ src/screens/screener/ScreenerScreen.cpp
src/screens/docs/DocsScreen_Pages_Intro.cpp
src/screens/docs/DocsScreen_Pages_Trading.cpp
src/screens/docs/DocsScreen_Pages_Data.cpp
@@ -1658,8 +1658,6 @@ set(SCREEN_SOURCES
src/screens/forum/ForumScreen.cpp
src/screens/forum/ForumFeedPanel.cpp
src/screens/forum/ForumSidebarPanel.cpp
- src/screens/forum/ForumPostListPanel.cpp
- src/screens/forum/ForumPostReaderPanel.cpp
src/screens/forum/ForumThreadPanel.cpp
src/services/forum/ForumService.cpp
# CryptoTradingScreen split; see header comment.
@@ -2242,6 +2240,7 @@ set_source_files_properties(
src/screens/dashboard/widgets/RiskMetricsWidget.cpp
src/screens/dashboard/widgets/ScreenerWidget.cpp
src/screens/dashboard/widgets/SectorHeatmapWidget.cpp
+ src/screens/screener/ScreenerScreen.cpp
src/screens/dashboard/widgets/StockQuoteWidget.cpp
src/screens/dashboard/widgets/TopMoversWidget.cpp
src/screens/dashboard/widgets/RecentFilesWidget.cpp
@@ -2321,8 +2320,6 @@ set_source_files_properties(
src/screens/excel/SpreadsheetWidget.cpp
src/screens/file_manager/FileManagerScreen.cpp
src/screens/forum/ForumFeedPanel.cpp
- src/screens/forum/ForumPostListPanel.cpp
- src/screens/forum/ForumPostReaderPanel.cpp
src/screens/forum/ForumScreen.cpp
src/screens/forum/ForumSidebarPanel.cpp
src/screens/forum/ForumThreadPanel.cpp
diff --git a/fincept-qt/scripts/agno_trading/__init__.py b/fincept-qt/scripts/agno_trading/__init__.py
deleted file mode 100644
index 25f31860b..000000000
--- a/fincept-qt/scripts/agno_trading/__init__.py
+++ /dev/null
@@ -1,41 +0,0 @@
-"""
-Agno Trading Agent System
-==========================
-
-A comprehensive AI trading agent framework powered by Agno.
-Supports multiple LLM providers, trading strategies, and market analysis.
-
-Architecture:
-- core/: Base classes and agent management
-- agents/: Specialized trading agents (analyst, trader, risk manager, etc.)
-- tools/: Market data, technical analysis, order execution tools
-- knowledge/: Market research, historical data, documentation
-- utils/: Helper functions and utilities
-- config/: Configuration management
-
-Author: Fincept Terminal
-Version: 1.0.0
-"""
-
-__version__ = "1.0.0"
-__author__ = "Fincept Terminal"
-
-from .core.agent_manager import AgentManager
-from .core.team_orchestrator import TeamOrchestrator
-from .agents import (
- MarketAnalystAgent,
- TradingStrategyAgent,
- RiskManagerAgent,
- PortfolioManagerAgent,
- SentimentAnalystAgent
-)
-
-__all__ = [
- "AgentManager",
- "TeamOrchestrator",
- "MarketAnalystAgent",
- "TradingStrategyAgent",
- "RiskManagerAgent",
- "PortfolioManagerAgent",
- "SentimentAnalystAgent"
-]
diff --git a/fincept-qt/scripts/agno_trading/agents/__init__.py b/fincept-qt/scripts/agno_trading/agents/__init__.py
deleted file mode 100644
index db95e4f05..000000000
--- a/fincept-qt/scripts/agno_trading/agents/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-"""
-Specialized Trading Agents
-
-This module provides specialized AI agents for different trading tasks.
-Each agent has specific expertise and tools optimized for their role.
-"""
-
-from .market_analyst import MarketAnalystAgent
-from .trading_strategy import TradingStrategyAgent
-from .risk_manager import RiskManagerAgent
-from .portfolio_manager import PortfolioManagerAgent
-from .sentiment_analyst import SentimentAnalystAgent
-
-__all__ = [
- 'MarketAnalystAgent',
- 'TradingStrategyAgent',
- 'RiskManagerAgent',
- 'PortfolioManagerAgent',
- 'SentimentAnalystAgent',
-]
diff --git a/fincept-qt/scripts/agno_trading/config/__init__.py b/fincept-qt/scripts/agno_trading/config/__init__.py
deleted file mode 100644
index bb834ac5a..000000000
--- a/fincept-qt/scripts/agno_trading/config/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-"""Configuration module for Agno trading agents"""
-
-from .settings import AgnoConfig, LLMConfig, TradingConfig
-from .models import get_model, list_available_models
-
-__all__ = ["AgnoConfig", "LLMConfig", "TradingConfig", "get_model", "list_available_models"]
diff --git a/fincept-qt/scripts/agno_trading/config/models.py b/fincept-qt/scripts/agno_trading/config/models.py
deleted file mode 100644
index 065c8e8e2..000000000
--- a/fincept-qt/scripts/agno_trading/config/models.py
+++ /dev/null
@@ -1,395 +0,0 @@
-"""
-LLM Model Registry and Factory
-===============================
-
-Centralized registry of all supported LLM models with their capabilities
-and factory functions to create Agno model instances.
-"""
-
-from typing import Dict, List, Any, Optional
-from dataclasses import dataclass
-from .settings import LLMProvider, LLMConfig
-
-
-@dataclass
-class ModelCapabilities:
- """Model capabilities and specifications"""
- max_tokens: int
- supports_streaming: bool
- supports_function_calling: bool
- supports_vision: bool = False
- supports_reasoning: bool = False
- context_window: int = 0
- cost_per_1k_input: float = 0.0
- cost_per_1k_output: float = 0.0
-
-
-# Model Registry with capabilities
-MODEL_REGISTRY: Dict[str, Dict[str, ModelCapabilities]] = {
- # OpenAI Models
- "openai": {
- "gpt-4": ModelCapabilities(
- max_tokens=8192,
- context_window=8192,
- supports_streaming=True,
- supports_function_calling=True,
- supports_vision=False,
- cost_per_1k_input=0.03,
- cost_per_1k_output=0.06
- ),
- "gpt-4-turbo": ModelCapabilities(
- max_tokens=4096,
- context_window=128000,
- supports_streaming=True,
- supports_function_calling=True,
- supports_vision=True,
- cost_per_1k_input=0.01,
- cost_per_1k_output=0.03
- ),
- "gpt-4o": ModelCapabilities(
- max_tokens=16384,
- context_window=128000,
- supports_streaming=True,
- supports_function_calling=True,
- supports_vision=True,
- cost_per_1k_input=0.005,
- cost_per_1k_output=0.015
- ),
- "gpt-4o-mini": ModelCapabilities(
- max_tokens=16384,
- context_window=128000,
- supports_streaming=True,
- supports_function_calling=True,
- supports_vision=True,
- cost_per_1k_input=0.00015,
- cost_per_1k_output=0.0006
- ),
- "o1": ModelCapabilities(
- max_tokens=100000,
- context_window=200000,
- supports_streaming=False,
- supports_function_calling=False,
- supports_reasoning=True,
- cost_per_1k_input=0.015,
- cost_per_1k_output=0.06
- ),
- "o1-mini": ModelCapabilities(
- max_tokens=65536,
- context_window=128000,
- supports_streaming=False,
- supports_function_calling=False,
- supports_reasoning=True,
- cost_per_1k_input=0.003,
- cost_per_1k_output=0.012
- ),
- "o4": ModelCapabilities(
- max_tokens=100000,
- context_window=200000,
- supports_streaming=False,
- supports_function_calling=True,
- supports_reasoning=True,
- cost_per_1k_input=0.01,
- cost_per_1k_output=0.04
- ),
- },
- # Anthropic Models
- "anthropic": {
- "claude-3-opus": ModelCapabilities(
- max_tokens=4096,
- context_window=200000,
- supports_streaming=True,
- supports_function_calling=True,
- supports_vision=True,
- cost_per_1k_input=0.015,
- cost_per_1k_output=0.075
- ),
- "claude-3-sonnet": ModelCapabilities(
- max_tokens=4096,
- context_window=200000,
- supports_streaming=True,
- supports_function_calling=True,
- supports_vision=True,
- cost_per_1k_input=0.003,
- cost_per_1k_output=0.015
- ),
- "claude-3-haiku": ModelCapabilities(
- max_tokens=4096,
- context_window=200000,
- supports_streaming=True,
- supports_function_calling=True,
- supports_vision=True,
- cost_per_1k_input=0.00025,
- cost_per_1k_output=0.00125
- ),
- "claude-sonnet-4": ModelCapabilities(
- max_tokens=8192,
- context_window=200000,
- supports_streaming=True,
- supports_function_calling=True,
- supports_vision=True,
- cost_per_1k_input=0.003,
- cost_per_1k_output=0.015
- ),
- "claude-opus-4": ModelCapabilities(
- max_tokens=8192,
- context_window=200000,
- supports_streaming=True,
- supports_function_calling=True,
- supports_vision=True,
- cost_per_1k_input=0.015,
- cost_per_1k_output=0.075
- ),
- },
- # Google Models
- "google": {
- "gemini-pro": ModelCapabilities(
- max_tokens=8192,
- context_window=32768,
- supports_streaming=True,
- supports_function_calling=True,
- supports_vision=False,
- cost_per_1k_input=0.0005,
- cost_per_1k_output=0.0015
- ),
- "gemini-pro-vision": ModelCapabilities(
- max_tokens=4096,
- context_window=16384,
- supports_streaming=True,
- supports_function_calling=True,
- supports_vision=True,
- cost_per_1k_input=0.00025,
- cost_per_1k_output=0.0005
- ),
- "gemini-1.5-pro": ModelCapabilities(
- max_tokens=8192,
- context_window=2000000,
- supports_streaming=True,
- supports_function_calling=True,
- supports_vision=True,
- cost_per_1k_input=0.00125,
- cost_per_1k_output=0.00375
- ),
- "gemini-1.5-flash": ModelCapabilities(
- max_tokens=8192,
- context_window=1000000,
- supports_streaming=True,
- supports_function_calling=True,
- supports_vision=True,
- cost_per_1k_input=0.000075,
- cost_per_1k_output=0.00030
- ),
- "gemini-2.0-flash": ModelCapabilities(
- max_tokens=8192,
- context_window=1000000,
- supports_streaming=True,
- supports_function_calling=True,
- supports_vision=True,
- cost_per_1k_input=0.000075,
- cost_per_1k_output=0.00030
- ),
- },
- # Groq Models
- "groq": {
- "llama-3.1-8b": ModelCapabilities(
- max_tokens=8000,
- context_window=128000,
- supports_streaming=True,
- supports_function_calling=True,
- cost_per_1k_input=0.00005,
- cost_per_1k_output=0.00008
- ),
- "llama-3.1-70b": ModelCapabilities(
- max_tokens=8000,
- context_window=128000,
- supports_streaming=True,
- supports_function_calling=True,
- cost_per_1k_input=0.00059,
- cost_per_1k_output=0.00079
- ),
- "mixtral-8x7b": ModelCapabilities(
- max_tokens=32768,
- context_window=32768,
- supports_streaming=True,
- supports_function_calling=True,
- cost_per_1k_input=0.00024,
- cost_per_1k_output=0.00024
- ),
- },
- # DeepSeek Models
- "deepseek": {
- "deepseek-chat": ModelCapabilities(
- max_tokens=4096,
- context_window=64000,
- supports_streaming=True,
- supports_function_calling=True,
- cost_per_1k_input=0.00014,
- cost_per_1k_output=0.00028
- ),
- "deepseek-coder": ModelCapabilities(
- max_tokens=4096,
- context_window=16000,
- supports_streaming=True,
- supports_function_calling=True,
- cost_per_1k_input=0.00014,
- cost_per_1k_output=0.00028
- ),
- "deepseek-reasoner": ModelCapabilities(
- max_tokens=8000,
- context_window=64000,
- supports_streaming=True,
- supports_function_calling=True,
- supports_reasoning=True,
- cost_per_1k_input=0.00055,
- cost_per_1k_output=0.0022
- ),
- },
- # xAI Grok Models
- "xai": {
- "grok-beta": ModelCapabilities(
- max_tokens=8192,
- context_window=131072,
- supports_streaming=True,
- supports_function_calling=True,
- cost_per_1k_input=0.005,
- cost_per_1k_output=0.015
- ),
- "grok-2": ModelCapabilities(
- max_tokens=8192,
- context_window=131072,
- supports_streaming=True,
- supports_function_calling=True,
- cost_per_1k_input=0.002,
- cost_per_1k_output=0.01
- ),
- },
- # Ollama Models (Local)
- "ollama": {
- "llama3.1": ModelCapabilities(
- max_tokens=8192,
- context_window=128000,
- supports_streaming=True,
- supports_function_calling=True,
- cost_per_1k_input=0.0,
- cost_per_1k_output=0.0
- ),
- "mistral": ModelCapabilities(
- max_tokens=8192,
- context_window=32768,
- supports_streaming=True,
- supports_function_calling=True,
- cost_per_1k_input=0.0,
- cost_per_1k_output=0.0
- ),
- "qwen2.5": ModelCapabilities(
- max_tokens=8192,
- context_window=128000,
- supports_streaming=True,
- supports_function_calling=True,
- cost_per_1k_input=0.0,
- cost_per_1k_output=0.0
- ),
- },
-}
-
-
-def get_model(provider: str, model_name: str) -> Optional[ModelCapabilities]:
- """Get model capabilities"""
- return MODEL_REGISTRY.get(provider, {}).get(model_name)
-
-
-def list_available_models(provider: Optional[str] = None) -> Dict[str, List[str]]:
- """List all available models, optionally filtered by provider"""
- if provider:
- return {provider: list(MODEL_REGISTRY.get(provider, {}).keys())}
- return {prov: list(models.keys()) for prov, models in MODEL_REGISTRY.items()}
-
-
-def get_best_model_for_task(
- task: str,
- budget: str = "medium",
- requires_reasoning: bool = False
-) -> tuple[str, str]:
- """
- Recommend best model for a specific task
-
- Args:
- task: Type of task (trading, analysis, risk_management, etc.)
- budget: Budget level (low, medium, high)
- requires_reasoning: Whether reasoning capabilities are needed
-
- Returns:
- Tuple of (provider, model_name)
- """
-
- if requires_reasoning:
- if budget == "high":
- return ("openai", "o4")
- elif budget == "medium":
- return ("openai", "o1-mini")
- else:
- return ("deepseek", "deepseek-reasoner")
-
- if task == "trading":
- # Fast, accurate, function calling
- if budget == "high":
- return ("anthropic", "claude-sonnet-4")
- elif budget == "medium":
- return ("openai", "gpt-4o-mini")
- else:
- return ("groq", "llama-3.1-70b")
-
- elif task == "analysis":
- # Deep understanding, large context
- if budget == "high":
- return ("google", "gemini-1.5-pro")
- elif budget == "medium":
- return ("anthropic", "claude-3-sonnet")
- else:
- return ("groq", "mixtral-8x7b")
-
- elif task == "risk_management":
- # Conservative, accurate
- if budget == "high":
- return ("openai", "gpt-4")
- elif budget == "medium":
- return ("anthropic", "claude-3-sonnet")
- else:
- return ("deepseek", "deepseek-chat")
-
- # Default
- return ("openai", "gpt-4o-mini")
-
-
-def validate_model_config(llm_config: LLMConfig) -> tuple[bool, Optional[str]]:
- """
- Validate LLM configuration
-
- Returns:
- Tuple of (is_valid, error_message)
- """
- provider = llm_config.provider.value
- model = llm_config.model
-
- # Check if model exists
- if provider not in MODEL_REGISTRY:
- return False, f"Provider '{provider}' not found in registry"
-
- if model not in MODEL_REGISTRY[provider]:
- available = ", ".join(MODEL_REGISTRY[provider].keys())
- return False, f"Model '{model}' not found for provider '{provider}'. Available: {available}"
-
- capabilities = MODEL_REGISTRY[provider][model]
-
- # Check max_tokens
- if llm_config.max_tokens and llm_config.max_tokens > capabilities.max_tokens:
- return False, f"max_tokens ({llm_config.max_tokens}) exceeds model limit ({capabilities.max_tokens})"
-
- # Check streaming support
- if llm_config.stream and not capabilities.supports_streaming:
- return False, f"Model '{model}' does not support streaming"
-
- # Check reasoning
- if llm_config.reasoning_effort and not capabilities.supports_reasoning:
- return False, f"Model '{model}' does not support reasoning"
-
- return True, None
diff --git a/fincept-qt/scripts/agno_trading/config/settings.py b/fincept-qt/scripts/agno_trading/config/settings.py
deleted file mode 100644
index 3a85693b7..000000000
--- a/fincept-qt/scripts/agno_trading/config/settings.py
+++ /dev/null
@@ -1,379 +0,0 @@
-"""
-Configuration Settings for Agno Trading Agents
-===============================================
-
-Manages all configuration for LLM providers, trading parameters,
-knowledge bases, memory systems, and agent behaviors.
-"""
-
-import os
-from typing import Optional, Dict, Any, List
-from dataclasses import dataclass, field
-from enum import Enum
-
-
-class LLMProvider(str, Enum):
- """Supported LLM providers"""
- OPENAI = "openai"
- ANTHROPIC = "anthropic"
- GOOGLE = "google"
- GROQ = "groq"
- DEEPSEEK = "deepseek"
- XAI = "xai" # Grok
- OLLAMA = "ollama"
- COHERE = "cohere"
- MISTRAL = "mistral"
- TOGETHER = "together"
- FIREWORKS = "fireworks"
-
-
-class TradingMode(str, Enum):
- """Trading execution modes"""
- PAPER = "paper"
- LIVE = "live"
- BACKTEST = "backtest"
- ANALYSIS_ONLY = "analysis_only"
-
-
-@dataclass
-class LLMConfig:
- """LLM Provider Configuration"""
-
- # Provider details
- provider: LLMProvider = LLMProvider.OPENAI
- model: str = "gpt-4"
-
- # API Configuration
- api_key: Optional[str] = None
- api_base: Optional[str] = None
- organization: Optional[str] = None
-
- # Model parameters
- temperature: float = 0.7
- max_tokens: Optional[int] = 4096
- top_p: float = 1.0
- top_k: Optional[int] = None
- frequency_penalty: float = 0.0
- presence_penalty: float = 0.0
-
- # Reasoning parameters (for reasoning models like o1)
- reasoning_effort: Optional[str] = None # "low", "medium", "high"
-
- # Streaming
- stream: bool = False
-
- # Timeout
- timeout: int = 60
-
- # Model-specific settings
- model_kwargs: Dict[str, Any] = field(default_factory=dict)
-
- def __post_init__(self):
- """Load API key from environment if not provided"""
- if not self.api_key:
- env_var_map = {
- LLMProvider.OPENAI: "OPENAI_API_KEY",
- LLMProvider.ANTHROPIC: "ANTHROPIC_API_KEY",
- LLMProvider.GOOGLE: "GOOGLE_API_KEY",
- LLMProvider.GROQ: "GROQ_API_KEY",
- LLMProvider.DEEPSEEK: "DEEPSEEK_API_KEY",
- LLMProvider.XAI: "XAI_API_KEY",
- LLMProvider.COHERE: "COHERE_API_KEY",
- LLMProvider.MISTRAL: "MISTRAL_API_KEY",
- }
- env_var = env_var_map.get(self.provider)
- if env_var:
- self.api_key = os.getenv(env_var)
-
- def to_agno_model_string(self) -> str:
- """Convert to Agno model string format: provider:model"""
- return f"{self.provider.value}:{self.model}"
-
-
-@dataclass
-class KnowledgeConfig:
- """Knowledge base configuration"""
-
- # Vector database settings
- vector_db: str = "lancedb" # lancedb, chromadb, pgvector, etc.
- vector_db_path: Optional[str] = None
-
- # Embedder settings
- embedder_provider: str = "openai"
- embedder_model: str = "text-embedding-3-small"
- embedder_api_key: Optional[str] = None
- embedder_dimensions: int = 1536
-
- # Search settings
- search_type: str = "hybrid" # "vector", "keyword", "hybrid"
- search_limit: int = 5
-
- # Content sources
- enable_market_news: bool = True
- enable_economic_data: bool = True
- enable_company_filings: bool = False
- enable_research_reports: bool = False
-
- # Chunking strategy
- chunk_size: int = 1000
- chunk_overlap: int = 200
-
-
-@dataclass
-class MemoryConfig:
- """Memory system configuration"""
-
- # Memory persistence
- enable_memory: bool = True
- memory_db: str = "sqlite" # sqlite, postgres, redis
- memory_db_path: Optional[str] = None
-
- # Session management
- enable_sessions: bool = True
- max_session_history: int = 100
-
- # Memory optimization
- enable_summarization: bool = True
- summarization_threshold: int = 50 # messages
-
- # User-specific memory
- enable_user_memory: bool = True
-
-
-@dataclass
-class TradingConfig:
- """Trading-specific configuration"""
-
- # Trading mode
- mode: TradingMode = TradingMode.PAPER
-
- # Risk parameters
- max_position_size: float = 0.1 # 10% of portfolio
- max_leverage: float = 1.0 # No leverage by default
- max_drawdown: float = 0.2 # 20% max drawdown
- stop_loss_pct: float = 0.05 # 5% stop loss
- take_profit_pct: float = 0.15 # 15% take profit
-
- # Portfolio parameters
- initial_capital: float = 10000.0
- commission_rate: float = 0.001 # 0.1%
- slippage_pct: float = 0.0005 # 0.05%
-
- # Market data
- market_data_provider: str = "ccxt" # ccxt, yfinance, polygon
- exchange: str = "kraken" # For crypto
- symbols: List[str] = field(default_factory=lambda: ["BTC/USD", "ETH/USD"])
- timeframe: str = "1h"
-
- # Order execution
- order_type: str = "limit" # limit, market
- time_in_force: str = "gtc" # gtc, ioc, fok
-
- # Trading hours
- trading_hours_start: str = "00:00"
- trading_hours_end: str = "23:59"
- timezone: str = "UTC"
-
- # Backtesting
- backtest_start_date: Optional[str] = None
- backtest_end_date: Optional[str] = None
-
-
-@dataclass
-class AgentConfig:
- """Individual agent configuration"""
-
- # Agent identity
- name: str = "TradingAgent"
- role: str = "trader"
- description: str = "An AI trading agent"
-
- # Instructions
- instructions: List[str] = field(default_factory=list)
- system_prompt: Optional[str] = None
-
- # Tools
- tools: List[str] = field(default_factory=list)
- enable_all_tools: bool = False
-
- # Knowledge
- enable_knowledge: bool = True
-
- # Memory
- enable_memory: bool = True
-
- # Model
- llm_config: Optional[LLMConfig] = None
-
- # Execution
- show_tool_calls: bool = True
- markdown: bool = True
- debug_mode: bool = False
-
- # Output schema
- structured_outputs: bool = False
- output_model: Optional[str] = None
-
-
-@dataclass
-class TeamConfig:
- """Team of agents configuration"""
-
- # Team identity
- name: str = "TradingTeam"
- description: str = "A team of AI trading agents"
-
- # Leader
- lead_agent: Optional[str] = None
-
- # Members
- members: List[str] = field(default_factory=list)
-
- # Delegation
- delegation_strategy: str = "sequential" # sequential, parallel, all
-
- # Model (inherited by all members if not specified)
- llm_config: Optional[LLMConfig] = None
-
- # Team memory
- enable_shared_memory: bool = True
-
- # Execution
- show_tool_calls: bool = True
- markdown: bool = True
-
-
-@dataclass
-class WorkflowConfig:
- """Workflow configuration"""
-
- # Workflow identity
- name: str = "TradingWorkflow"
- description: str = "AI trading workflow"
-
- # Steps
- steps: List[Dict[str, Any]] = field(default_factory=list)
-
- # Execution
- parallel_steps: bool = False
- early_stop: bool = True
-
- # Session
- enable_session: bool = True
-
- # Model
- llm_config: Optional[LLMConfig] = None
-
-
-@dataclass
-class AgnoConfig:
- """
- Main configuration class for Agno trading system
- Aggregates all sub-configurations
- """
-
- # Sub-configurations
- llm: LLMConfig = field(default_factory=LLMConfig)
- knowledge: KnowledgeConfig = field(default_factory=KnowledgeConfig)
- memory: MemoryConfig = field(default_factory=MemoryConfig)
- trading: TradingConfig = field(default_factory=TradingConfig)
-
- # Global settings
- debug: bool = False
- log_level: str = "INFO"
-
- # Database
- db_url: Optional[str] = None # For AgentOS
-
- # API Keys (loaded from environment)
- api_keys: Dict[str, str] = field(default_factory=dict)
-
- def __post_init__(self):
- """Load environment variables"""
- # Load API keys
- api_key_vars = [
- "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GOOGLE_API_KEY",
- "GROQ_API_KEY", "DEEPSEEK_API_KEY", "XAI_API_KEY",
- "COHERE_API_KEY", "MISTRAL_API_KEY"
- ]
- for var in api_key_vars:
- value = os.getenv(var)
- if value:
- self.api_keys[var] = value
-
- @classmethod
- def from_dict(cls, config_dict: Dict[str, Any]) -> "AgnoConfig":
- """Create configuration from dictionary"""
- llm_config = LLMConfig(**config_dict.get("llm", {}))
- knowledge_config = KnowledgeConfig(**config_dict.get("knowledge", {}))
- memory_config = MemoryConfig(**config_dict.get("memory", {}))
- trading_config = TradingConfig(**config_dict.get("trading", {}))
-
- return cls(
- llm=llm_config,
- knowledge=knowledge_config,
- memory=memory_config,
- trading=trading_config,
- debug=config_dict.get("debug", False),
- log_level=config_dict.get("log_level", "INFO"),
- db_url=config_dict.get("db_url")
- )
-
- def to_dict(self) -> Dict[str, Any]:
- """Convert configuration to dictionary"""
- return {
- "llm": {
- "provider": self.llm.provider.value,
- "model": self.llm.model,
- "temperature": self.llm.temperature,
- "max_tokens": self.llm.max_tokens,
- "top_p": self.llm.top_p,
- "reasoning_effort": self.llm.reasoning_effort,
- "stream": self.llm.stream,
- },
- "knowledge": {
- "vector_db": self.knowledge.vector_db,
- "search_type": self.knowledge.search_type,
- "search_limit": self.knowledge.search_limit,
- },
- "memory": {
- "enable_memory": self.memory.enable_memory,
- "enable_sessions": self.memory.enable_sessions,
- "max_session_history": self.memory.max_session_history,
- },
- "trading": {
- "mode": self.trading.mode.value,
- "max_position_size": self.trading.max_position_size,
- "max_leverage": self.trading.max_leverage,
- "stop_loss_pct": self.trading.stop_loss_pct,
- "symbols": self.trading.symbols,
- },
- "debug": self.debug,
- "log_level": self.log_level,
- }
-
-
-# Default configurations for different use cases
-DEFAULT_ANALYST_CONFIG = AgentConfig(
- name="MarketAnalyst",
- role="market_analyst",
- description="Analyzes market data and provides insights",
- tools=["get_market_data", "calculate_technical_indicators", "get_news"],
- llm_config=LLMConfig(provider=LLMProvider.OPENAI, model="gpt-4", temperature=0.3)
-)
-
-DEFAULT_TRADER_CONFIG = AgentConfig(
- name="TradingStrategy",
- role="trader",
- description="Develops and executes trading strategies",
- tools=["get_market_data", "place_order", "get_positions", "calculate_technical_indicators"],
- llm_config=LLMConfig(provider=LLMProvider.ANTHROPIC, model="claude-sonnet-4", temperature=0.5)
-)
-
-DEFAULT_RISK_MANAGER_CONFIG = AgentConfig(
- name="RiskManager",
- role="risk_manager",
- description="Manages portfolio risk and monitors positions",
- tools=["get_positions", "calculate_var", "get_portfolio_metrics"],
- llm_config=LLMConfig(provider=LLMProvider.OPENAI, model="gpt-4", temperature=0.2)
-)
diff --git a/fincept-qt/scripts/agno_trading/core/__init__.py b/fincept-qt/scripts/agno_trading/core/__init__.py
deleted file mode 100644
index 0d22d61b8..000000000
--- a/fincept-qt/scripts/agno_trading/core/__init__.py
+++ /dev/null
@@ -1,18 +0,0 @@
-"""
-Core Agno Trading Agent Framework
-
-This module provides the foundational classes for creating and managing
-AI trading agents using the Agno framework.
-"""
-
-from .base_agent import BaseAgent
-from .agent_manager import AgentManager
-from .team_orchestrator import TeamOrchestrator
-from .workflow_engine import WorkflowEngine
-
-__all__ = [
- 'BaseAgent',
- 'AgentManager',
- 'TeamOrchestrator',
- 'WorkflowEngine',
-]
diff --git a/fincept-qt/scripts/agno_trading/core/agent_evolution.py b/fincept-qt/scripts/agno_trading/core/agent_evolution.py
deleted file mode 100644
index d18f61728..000000000
--- a/fincept-qt/scripts/agno_trading/core/agent_evolution.py
+++ /dev/null
@@ -1,350 +0,0 @@
-"""
-Agent Evolution System
-Self-learning agents that improve from trading history
-"""
-
-import json
-import sys
-from typing import Dict, Any, List, Optional
-from datetime import datetime
-from collections import Counter
-
-
-class AgentEvolution:
- """
- Manages agent self-evolution through performance analysis
- """
-
- def __init__(self):
- """Initialize evolution system"""
- self.evolution_triggers = {
- 'loss_streak': 3, # Evolve after 3 consecutive losses
- 'poor_win_rate': 0.40, # Evolve if win rate below 40%
- 'large_drawdown': 0.10, # Evolve if drawdown > 10%
- 'consistent_wins': 5, # Reinforce after 5 consecutive wins
- 'trades_milestone': 20 # Evolve every 20 trades
- }
-
- def should_evolve(self, agent_id: str, performance: Dict[str, Any]) -> tuple[bool, str]:
- """
- Check if agent should evolve based on performance
-
- Args:
- agent_id: Agent ID
- performance: Performance metrics
-
- Returns:
- (should_evolve, trigger_reason)
- """
- # Check loss streak
- if performance.get('consecutive_losses', 0) >= self.evolution_triggers['loss_streak']:
- return True, 'loss_streak'
-
- # Check poor win rate
- if performance.get('total_trades', 0) >= 10: # Need minimum trades
- if performance.get('win_rate', 100) < self.evolution_triggers['poor_win_rate'] * 100:
- return True, 'poor_win_rate'
-
- # Check large drawdown
- if performance.get('current_drawdown', 0) >= self.evolution_triggers['large_drawdown']:
- return True, 'large_drawdown'
-
- # Check trade milestones
- if performance.get('total_trades', 0) > 0 and performance.get('total_trades', 0) % self.evolution_triggers['trades_milestone'] == 0:
- return True, 'trades_milestone'
-
- return False, None
-
- def analyze_patterns(self, agent_id: str) -> Dict[str, Any]:
- """
- Analyze trading patterns from history
-
- Args:
- agent_id: Agent ID
-
- Returns:
- Pattern analysis
- """
- from agno_trading.db.database_manager import get_db_manager
- db = get_db_manager()
-
- # Get trade history
- trades = db.get_agent_trades(agent_id, limit=100)
-
- if not trades:
- return {
- 'total_analyzed': 0,
- 'patterns': {}
- }
-
- # Separate winners and losers
- winners = [t for t in trades if t['pnl'] > 0]
- losers = [t for t in trades if t['pnl'] < 0]
-
- analysis = {
- 'total_analyzed': len(trades),
- 'winners_count': len(winners),
- 'losers_count': len(losers),
- 'patterns': {}
- }
-
- # Pattern 1: Winning vs Losing Symbols
- winning_symbols = Counter([t['symbol'] for t in winners])
- losing_symbols = Counter([t['symbol'] for t in losers])
-
- analysis['patterns']['best_symbols'] = [sym for sym, _ in winning_symbols.most_common(3)]
- analysis['patterns']['worst_symbols'] = [sym for sym, _ in losing_symbols.most_common(3)]
-
- # Pattern 2: Winning vs Losing Sides
- winning_sides = Counter([t['side'] for t in winners])
- losing_sides = Counter([t['side'] for t in losers])
-
- analysis['patterns']['best_side'] = winning_sides.most_common(1)[0][0] if winning_sides else 'buy'
- analysis['patterns']['worst_side'] = losing_sides.most_common(1)[0][0] if losing_sides else None
-
- # Pattern 3: Trade timing (hour of day if available)
- # Pattern 4: Position sizing patterns
- avg_winning_size = sum(t['quantity'] * t['entry_price'] for t in winners) / len(winners) if winners else 0
- avg_losing_size = sum(t['quantity'] * t['entry_price'] for t in losers) / len(losers) if losers else 0
-
- analysis['patterns']['avg_winning_size'] = avg_winning_size
- analysis['patterns']['avg_losing_size'] = avg_losing_size
-
- if avg_winning_size < avg_losing_size:
- analysis['patterns']['sizing_issue'] = 'winning_trades_too_small'
- elif avg_losing_size > avg_winning_size * 1.5:
- analysis['patterns']['sizing_issue'] = 'losing_trades_too_large'
- else:
- analysis['patterns']['sizing_issue'] = None
-
- # Pattern 5: Stop loss hit rate
- trades_with_sl = [t for t in trades if t['stop_loss'] is not None]
- if trades_with_sl:
- sl_hit_count = sum(1 for t in losers if t['stop_loss'] and abs(t['exit_price'] - t['stop_loss']) / t['stop_loss'] < 0.01)
- analysis['patterns']['stop_loss_hit_rate'] = sl_hit_count / len(losers) if losers else 0
- else:
- analysis['patterns']['stop_loss_hit_rate'] = 0
-
- # Pattern 6: Take profit hit rate
- trades_with_tp = [t for t in trades if t['take_profit'] is not None]
- if trades_with_tp:
- tp_hit_count = sum(1 for t in winners if t['take_profit'] and abs(t['exit_price'] - t['take_profit']) / t['take_profit'] < 0.01)
- analysis['patterns']['take_profit_hit_rate'] = tp_hit_count / len(winners) if winners else 0
- else:
- analysis['patterns']['take_profit_hit_rate'] = 0
-
- return analysis
-
- def generate_new_instructions(
- self,
- agent_id: str,
- current_instructions: List[str],
- patterns: Dict[str, Any],
- trigger: str
- ) -> List[str]:
- """
- Generate improved instructions based on patterns
-
- Args:
- agent_id: Agent ID
- current_instructions: Current agent instructions
- patterns: Pattern analysis
- trigger: Evolution trigger
-
- Returns:
- New instructions
- """
- new_instructions = current_instructions.copy()
-
- # Add learning-based instructions
- learning_instructions = []
-
- # From symbol patterns
- if patterns.get('best_symbols'):
- learning_instructions.append(
- f"LEARNED: You have better win rates with {', '.join(patterns['best_symbols'][:2])}. Favor these symbols when possible."
- )
-
- if patterns.get('worst_symbols'):
- learning_instructions.append(
- f"LEARNED: You have poor performance with {', '.join(patterns['worst_symbols'][:2])}. Be more cautious or avoid these symbols."
- )
-
- # From side patterns
- if patterns.get('best_side') and patterns.get('worst_side'):
- if patterns['best_side'] != patterns['worst_side']:
- learning_instructions.append(
- f"LEARNED: Your {patterns['best_side'].upper()} trades outperform {patterns['worst_side'].upper()} trades. Focus on {patterns['best_side'].upper()} setups."
- )
-
- # From sizing patterns
- sizing_issue = patterns.get('sizing_issue')
- if sizing_issue == 'winning_trades_too_small':
- learning_instructions.append(
- "LEARNED: Your winning trades are smaller than losing trades. Increase position size on high-confidence setups."
- )
- elif sizing_issue == 'losing_trades_too_large':
- learning_instructions.append(
- "LEARNED: Your losing trades are too large. Reduce position size to manage risk better."
- )
-
- # From stop loss patterns
- sl_hit_rate = patterns.get('stop_loss_hit_rate', 0)
- if sl_hit_rate > 0.7:
- learning_instructions.append(
- "LEARNED: Your stop losses are being hit frequently (70%+). Consider wider stops or better entry timing."
- )
- elif sl_hit_rate < 0.3:
- learning_instructions.append(
- "LEARNED: Your stop losses are rarely hit. Your risk management is working well - maintain this approach."
- )
-
- # From take profit patterns
- tp_hit_rate = patterns.get('take_profit_hit_rate', 0)
- if tp_hit_rate > 0.7:
- learning_instructions.append(
- "LEARNED: Your take profit targets are being hit consistently. Consider setting more ambitious targets."
- )
- elif tp_hit_rate < 0.3:
- learning_instructions.append(
- "LEARNED: Your take profit targets are rarely hit. Consider more conservative targets or trailing stops."
- )
-
- # Trigger-specific instructions
- if trigger == 'loss_streak':
- learning_instructions.append(
- "CAUTION: You're currently in a losing streak. Reduce position sizes by 50% until you have 2 consecutive wins."
- )
- elif trigger == 'poor_win_rate':
- learning_instructions.append(
- "STRATEGY SHIFT: Your win rate is below 40%. Focus on HIGH PROBABILITY setups only. Skip marginal trades."
- )
- elif trigger == 'large_drawdown':
- learning_instructions.append(
- "RISK ALERT: Drawdown is over 10%. STOP TRADING until you review your strategy. Reduce position sizes when resuming."
- )
-
- # Prepend learning instructions
- new_instructions = learning_instructions + new_instructions
-
- return new_instructions
-
- def evolve_agent(
- self,
- agent_id: str,
- model: str,
- current_instructions: List[str],
- trigger: str,
- notes: Optional[str] = None
- ) -> Dict[str, Any]:
- """
- Evolve an agent based on performance
-
- Args:
- agent_id: Agent ID
- model: Model name
- current_instructions: Current instructions
- trigger: Evolution trigger
- notes: Optional notes
-
- Returns:
- Evolution result
- """
- from agno_trading.db.database_manager import get_db_manager
- db = get_db_manager()
-
- try:
- # Get current performance
- performance = db.get_agent_performance(agent_id)
- if not performance:
- return {'success': False, 'error': 'Agent performance not found'}
-
- # Analyze patterns
- patterns = self.analyze_patterns(agent_id)
-
- # Generate new instructions
- new_instructions = self.generate_new_instructions(
- agent_id,
- current_instructions,
- patterns['patterns'],
- trigger
- )
-
- # Record evolution
- evolution_data = {
- 'agent_id': agent_id,
- 'model': model,
- 'evolution_trigger': trigger,
- 'old_instructions': json.dumps(current_instructions),
- 'new_instructions': json.dumps(new_instructions),
- 'metrics_before': json.dumps({
- 'total_pnl': performance['total_pnl'],
- 'win_rate': performance['win_rate'],
- 'total_trades': performance['total_trades'],
- 'sharpe_ratio': performance['sharpe_ratio']
- }),
- 'metrics_after': json.dumps({}), # Will be updated later
- 'timestamp': int(datetime.now().timestamp()),
- 'notes': notes or json.dumps(patterns)
- }
-
- db.log_evolution(evolution_data)
-
- return {
- 'success': True,
- 'agent_id': agent_id,
- 'trigger': trigger,
- 'old_instructions': current_instructions,
- 'new_instructions': new_instructions,
- 'patterns': patterns,
- 'metrics_before': {
- 'total_pnl': performance['total_pnl'],
- 'win_rate': performance['win_rate'],
- 'total_trades': performance['total_trades']
- }
- }
-
- except Exception as e:
- print(f"[Evolution] Error: {str(e)}", file=sys.stderr)
- import traceback
- traceback.print_exc(file=sys.stderr)
-
- return {
- 'success': False,
- 'error': f"Evolution failed: {str(e)}"
- }
-
- def get_evolution_summary(self, agent_id: str) -> Dict[str, Any]:
- """
- Get evolution summary for an agent
-
- Args:
- agent_id: Agent ID
-
- Returns:
- Evolution summary
- """
- from agno_trading.db.database_manager import get_db_manager
- db = get_db_manager()
-
- history = db.get_evolution_history(agent_id, limit=10)
- performance = db.get_agent_performance(agent_id)
-
- return {
- 'agent_id': agent_id,
- 'total_evolutions': len(history),
- 'evolution_history': history,
- 'current_performance': performance,
- 'last_evolution': history[0] if history else None
- }
-
-
-# Global instance
-_agent_evolution = None
-
-def get_agent_evolution() -> AgentEvolution:
- """Get singleton agent evolution system"""
- global _agent_evolution
- if _agent_evolution is None:
- _agent_evolution = AgentEvolution()
- return _agent_evolution
diff --git a/fincept-qt/scripts/agno_trading/core/agent_manager.py b/fincept-qt/scripts/agno_trading/core/agent_manager.py
deleted file mode 100644
index 9ed3a369e..000000000
--- a/fincept-qt/scripts/agno_trading/core/agent_manager.py
+++ /dev/null
@@ -1,375 +0,0 @@
-"""
-Agent Manager
-
-This module manages the lifecycle of trading agents:
-- Creating and destroying agents
-- Tracking active agents
-- Managing agent resources
-- Agent performance monitoring
-"""
-
-import json
-from typing import Dict, List, Optional, Any
-from datetime import datetime
-from dataclasses import dataclass, asdict
-
-from .base_agent import BaseAgent, AgentConfig
-
-
-@dataclass
-class AgentMetrics:
- """Performance metrics for an agent"""
- total_runs: int = 0
- successful_runs: int = 0
- failed_runs: int = 0
- total_tokens_used: int = 0
- total_cost: float = 0.0
- average_response_time: float = 0.0
- last_run_at: Optional[str] = None
-
-
-class AgentManager:
- """
- Manages lifecycle and monitoring of trading agents
-
- Features:
- - Agent creation and destruction
- - Agent registry and lookup
- - Performance metrics tracking
- - Resource management
- - Agent health monitoring
- """
-
- def __init__(self):
- """Initialize the agent manager"""
- self.agents: Dict[str, BaseAgent] = {}
- self.metrics: Dict[str, AgentMetrics] = {}
- self.created_at = datetime.now()
-
- def create_agent(self, config: AgentConfig) -> str:
- """
- Create a new trading agent
-
- Args:
- config: Agent configuration
-
- Returns:
- agent_id: Unique identifier for the created agent
-
- Raises:
- ValueError: If agent creation fails
- """
- try:
- # Create agent instance
- agent = BaseAgent(config)
-
- # Register agent
- agent_id = agent.agent_id
- self.agents[agent_id] = agent
- self.metrics[agent_id] = AgentMetrics()
-
- return agent_id
-
- except Exception as e:
- raise ValueError(f"Failed to create agent: {str(e)}")
-
- def get_agent(self, agent_id: str) -> Optional[BaseAgent]:
- """
- Get an agent by ID
-
- Args:
- agent_id: Agent identifier
-
- Returns:
- Agent instance or None if not found
- """
- return self.agents.get(agent_id)
-
- def list_agents(self) -> List[Dict[str, Any]]:
- """
- List all active agents
-
- Returns:
- List of agent information dictionaries
- """
- return [
- {
- **agent.to_dict(),
- "metrics": asdict(self.metrics.get(agent_id, AgentMetrics()))
- }
- for agent_id, agent in self.agents.items()
- ]
-
- def destroy_agent(self, agent_id: str) -> bool:
- """
- Destroy an agent and clean up resources
-
- Args:
- agent_id: Agent identifier
-
- Returns:
- True if agent was destroyed, False if not found
- """
- if agent_id in self.agents:
- # Clean up agent resources
- agent = self.agents[agent_id]
- # Clear all sessions
- for session_id in list(agent.sessions.keys()):
- agent.clear_session(session_id)
-
- # Remove from registry
- del self.agents[agent_id]
-
- # Keep metrics for historical tracking
- # but mark as destroyed
- if agent_id in self.metrics:
- self.metrics[agent_id].last_run_at = datetime.now().isoformat()
-
- return True
-
- return False
-
- def run_agent(
- self,
- agent_id: str,
- prompt: str,
- session_id: Optional[str] = None,
- stream: bool = False,
- **kwargs
- ) -> Dict[str, Any]:
- """
- Run an agent with a prompt and track metrics
-
- Args:
- agent_id: Agent identifier
- prompt: User prompt
- session_id: Optional session ID
- stream: Whether to stream response
- **kwargs: Additional parameters
-
- Returns:
- Response dictionary with content and metadata
-
- Raises:
- ValueError: If agent not found or execution fails
- """
- # Get agent
- agent = self.get_agent(agent_id)
- if not agent:
- raise ValueError(f"Agent not found: {agent_id}")
-
- # Track metrics
- metrics = self.metrics.get(agent_id, AgentMetrics())
- start_time = datetime.now()
-
- try:
- # Run agent
- response = agent.run(
- prompt=prompt,
- session_id=session_id,
- stream=stream,
- **kwargs
- )
-
- # Calculate response time
- end_time = datetime.now()
- response_time = (end_time - start_time).total_seconds()
-
- # Update metrics
- metrics.total_runs += 1
- metrics.successful_runs += 1
- metrics.last_run_at = end_time.isoformat()
-
- # Update average response time
- if metrics.average_response_time == 0:
- metrics.average_response_time = response_time
- else:
- metrics.average_response_time = (
- (metrics.average_response_time * (metrics.total_runs - 1) + response_time) /
- metrics.total_runs
- )
-
- # Extract token usage and cost if available
- if hasattr(response, 'metrics'):
- if hasattr(response.metrics, 'input_tokens'):
- metrics.total_tokens_used += response.metrics.input_tokens
- if hasattr(response.metrics, 'output_tokens'):
- metrics.total_tokens_used += response.metrics.output_tokens
-
- self.metrics[agent_id] = metrics
-
- # Format response
- result = {
- "agent_id": agent_id,
- "session_id": session_id,
- "content": agent._extract_response_content(response),
- "response_time": response_time,
- "timestamp": end_time.isoformat(),
- "stream": stream,
- }
-
- # Add metrics if available
- if hasattr(response, 'metrics'):
- result["metrics"] = {
- "input_tokens": getattr(response.metrics, 'input_tokens', 0),
- "output_tokens": getattr(response.metrics, 'output_tokens', 0),
- "total_tokens": getattr(response.metrics, 'total_tokens', 0),
- }
-
- return result
-
- except Exception as e:
- # Update failure metrics
- metrics.total_runs += 1
- metrics.failed_runs += 1
- metrics.last_run_at = datetime.now().isoformat()
- self.metrics[agent_id] = metrics
-
- raise ValueError(f"Agent execution failed: {str(e)}")
-
- def get_agent_metrics(self, agent_id: str) -> Optional[Dict[str, Any]]:
- """
- Get performance metrics for an agent
-
- Args:
- agent_id: Agent identifier
-
- Returns:
- Metrics dictionary or None if not found
- """
- metrics = self.metrics.get(agent_id)
- if metrics:
- return asdict(metrics)
- return None
-
- def get_session_history(
- self,
- agent_id: str,
- session_id: str
- ) -> List[Dict[str, Any]]:
- """
- Get conversation history for an agent session
-
- Args:
- agent_id: Agent identifier
- session_id: Session identifier
-
- Returns:
- List of conversation messages
- """
- agent = self.get_agent(agent_id)
- if agent:
- return agent.get_session_history(session_id)
- return []
-
- def clear_session(self, agent_id: str, session_id: str) -> bool:
- """
- Clear a specific agent session
-
- Args:
- agent_id: Agent identifier
- session_id: Session identifier
-
- Returns:
- True if session was cleared, False if not found
- """
- agent = self.get_agent(agent_id)
- if agent:
- agent.clear_session(session_id)
- return True
- return False
-
- def get_manager_stats(self) -> Dict[str, Any]:
- """
- Get overall manager statistics
-
- Returns:
- Statistics dictionary
- """
- total_agents = len(self.agents)
- total_runs = sum(m.total_runs for m in self.metrics.values())
- total_successful = sum(m.successful_runs for m in self.metrics.values())
- total_failed = sum(m.failed_runs for m in self.metrics.values())
- total_tokens = sum(m.total_tokens_used for m in self.metrics.values())
- total_cost = sum(m.total_cost for m in self.metrics.values())
-
- return {
- "manager_uptime": (datetime.now() - self.created_at).total_seconds(),
- "total_agents": total_agents,
- "active_agents": total_agents,
- "total_runs": total_runs,
- "successful_runs": total_successful,
- "failed_runs": total_failed,
- "success_rate": (total_successful / total_runs * 100) if total_runs > 0 else 0,
- "total_tokens_used": total_tokens,
- "total_cost": total_cost,
- }
-
- def health_check(self) -> Dict[str, Any]:
- """
- Perform health check on all agents
-
- Returns:
- Health status dictionary
- """
- healthy_agents = []
- unhealthy_agents = []
-
- for agent_id, agent in self.agents.items():
- metrics = self.metrics.get(agent_id, AgentMetrics())
-
- # Basic health criteria
- is_healthy = True
- health_issues = []
-
- # Check failure rate
- if metrics.total_runs > 0:
- failure_rate = metrics.failed_runs / metrics.total_runs
- if failure_rate > 0.5: # More than 50% failures
- is_healthy = False
- health_issues.append(f"High failure rate: {failure_rate:.1%}")
-
- # Check if agent has been used recently
- if metrics.last_run_at:
- # Agent has been used, all good
- pass
- elif (datetime.now() - agent.created_at).total_seconds() > 3600:
- # Agent created more than 1 hour ago but never used
- health_issues.append("Agent never used")
-
- agent_health = {
- "agent_id": agent_id,
- "name": agent.config.name,
- "is_healthy": is_healthy,
- "issues": health_issues,
- "metrics": asdict(metrics)
- }
-
- if is_healthy:
- healthy_agents.append(agent_health)
- else:
- unhealthy_agents.append(agent_health)
-
- return {
- "timestamp": datetime.now().isoformat(),
- "total_agents": len(self.agents),
- "healthy_count": len(healthy_agents),
- "unhealthy_count": len(unhealthy_agents),
- "healthy_agents": healthy_agents,
- "unhealthy_agents": unhealthy_agents,
- }
-
- def __repr__(self) -> str:
- return f"<AgentManager(agents={len(self.agents)}, uptime={(datetime.now() - self.created_at).total_seconds():.0f}s)>"
-
-
-# Global agent manager instance
-_agent_manager = None
-
-
-def get_agent_manager() -> AgentManager:
- """Get the global agent manager instance"""
- global _agent_manager
- if _agent_manager is None:
- _agent_manager = AgentManager()
- return _agent_manager
diff --git a/fincept-qt/scripts/agno_trading/core/auto_trader.py b/fincept-qt/scripts/agno_trading/core/auto_trader.py
deleted file mode 100644
index 24736a983..000000000
--- a/fincept-qt/scripts/agno_trading/core/auto_trader.py
+++ /dev/null
@@ -1,408 +0,0 @@
-"""
-Auto Trading Engine
-
-Implements automatic trading loop inspired by Alpha Arena.
-Executes trades based on AI agent recommendations with safety controls.
-"""
-
-import asyncio
-import json
-from typing import Dict, Any, Optional, List, Callable
-from datetime import datetime, timedelta
-from dataclasses import dataclass, field
-import time
-
-
-@dataclass
-class TradingSignal:
- """Trading signal from AI agent"""
- symbol: str
- direction: str # 'long' or 'short'
- entry_price: float
- stop_loss: float
- take_profit: float
- position_size: float
- leverage: float
- confidence: float # 0.0 to 1.0
- reasoning: str
- timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
-
-
-@dataclass
-class SafetyLimits:
- """Safety limits for auto-trading"""
- max_position_size: float = 0.1 # 10% of portfolio
- max_leverage: float = 1.0 # No leverage by default
- max_drawdown: float = 0.15 # 15% max drawdown
- max_daily_loss: float = 0.05 # 5% max daily loss
- min_confidence: float = 0.6 # Minimum confidence to execute
- max_open_positions: int = 5
- require_stop_loss: bool = True
- require_take_profit: bool = True
-
-
-@dataclass
-class TradingState:
- """Current state of auto-trading"""
- is_running: bool = False
- total_trades: int = 0
- winning_trades: int = 0
- losing_trades: int = 0
- total_pnl: float = 0.0
- current_drawdown: float = 0.0
- daily_pnl: float = 0.0
- peak_equity: float = 0.0
- last_trade_time: Optional[str] = None
- start_time: Optional[str] = None
- circuit_breaker_triggered: bool = False
-
-
-class AutoTrader:
- """
- Automatic trading engine that executes AI agent recommendations
-
- Features:
- - Configurable execution loop (2-3 min like Alpha Arena)
- - Dynamic TP/SL based on volatility
- - Position sizing with confidence weighting
- - Safety limits and circuit breakers
- - Emergency stop mechanism
- """
-
- def __init__(
- self,
- agent,
- execution_interval: int = 180, # 3 minutes like Alpha Arena
- safety_limits: Optional[SafetyLimits] = None,
- initial_capital: float = 10000.0
- ):
- """
- Initialize auto-trader
-
- Args:
- agent: Trading agent instance
- execution_interval: Seconds between execution cycles (default 180 = 3 min)
- safety_limits: Safety configuration
- initial_capital: Starting capital
- """
- self.agent = agent
- self.execution_interval = execution_interval
- self.safety_limits = safety_limits or SafetyLimits()
- self.initial_capital = initial_capital
- self.current_capital = initial_capital
-
- self.state = TradingState()
- self.positions: Dict[str, Dict[str, Any]] = {}
- self.trade_history: List[Dict[str, Any]] = []
-
- self.callbacks: Dict[str, Callable] = {}
- self._stop_requested = False
-
- def register_callback(self, event: str, callback: Callable):
- """Register callback for events (trade_executed, position_closed, etc.)"""
- self.callbacks[event] = callback
-
- async def start(self):
- """Start auto-trading loop"""
- if self.state.is_running:
- return {"error": "Auto-trader already running"}
-
- self.state.is_running = True
- self.state.start_time = datetime.now().isoformat()
- self.state.peak_equity = self.current_capital
- self._stop_requested = False
-
- print(f"[AutoTrader] Starting with ${self.current_capital:.2f} capital")
- print(f"[AutoTrader] Execution interval: {self.execution_interval}s")
-
- try:
- while self.state.is_running and not self._stop_requested:
- # Check safety limits
- if self._check_circuit_breaker():
- self._trigger_emergency_stop("Circuit breaker triggered")
- break
-
- # Execute trading cycle
- await self._execute_cycle()
-
- # Wait for next cycle
- await asyncio.sleep(self.execution_interval)
-
- except Exception as e:
- print(f"[AutoTrader] Error in trading loop: {e}")
- self.state.is_running = False
-
- return {
- "stopped": True,
- "total_trades": self.state.total_trades,
- "final_pnl": self.state.total_pnl
- }
-
- def stop(self):
- """Stop auto-trading gracefully"""
- print("[AutoTrader] Stop requested")
- self._stop_requested = True
- self.state.is_running = False
-
- def emergency_stop(self):
- """Emergency stop - close all positions immediately"""
- print("[AutoTrader] EMERGENCY STOP - Closing all positions")
- self._close_all_positions()
- self.stop()
-
- async def _execute_cycle(self):
- """Execute one trading cycle (Alpha Arena style)"""
- try:
- # 1. Get market data and portfolio state
- market_data = self._get_market_data()
- portfolio_state = self._get_portfolio_state()
-
- # 2. Get AI agent decision
- prompt = self._build_trading_prompt(market_data, portfolio_state)
- response = self.agent.run(prompt)
-
- # 3. Parse signal
- signal = self._parse_signal(response)
-
- if not signal:
- print("[AutoTrader] No signal from agent")
- return
-
- # 4. Validate signal against safety limits
- if not self._validate_signal(signal):
- print(f"[AutoTrader] Signal rejected by safety checks")
- return
-
- # 5. Calculate position size with confidence weighting
- position_size = self._calculate_position_size(signal)
-
- # 6. Execute trade
- await self._execute_trade(signal, position_size)
-
- # 7. Manage existing positions (check TP/SL)
- self._manage_positions()
-
- except Exception as e:
- print(f"[AutoTrader] Error in cycle: {e}")
-
- def _build_trading_prompt(self, market_data: Dict, portfolio: Dict) -> str:
- """Build prompt for agent (Alpha Arena style)"""
- return f"""
- You are an autonomous trading agent. Analyze the market and provide a trading decision.
-
- **Current Market Data:**
- {json.dumps(market_data, indent=2)}
-
- **Current Portfolio:**
- - Capital: ${portfolio.get('capital', 0):.2f}
- - Open Positions: {portfolio.get('position_count', 0)}
- - Daily P&L: ${portfolio.get('daily_pnl', 0):.2f}
- - Total P&L: ${portfolio.get('total_pnl', 0):.2f}
-
- **Your Task:**
- Decide whether to:
- 1. Open a new position (LONG or SHORT)
- 2. Close existing positions
- 3. Hold current positions
-
- **Required Response Format:**
- {{
- "action": "long" | "short" | "close" | "hold",
- "symbol": "BTC/USD",
- "entry_price": 50000.0,
- "stop_loss": 48000.0,
- "take_profit": 55000.0,
- "position_size_pct": 0.1,
- "leverage": 1.0,
- "confidence": 0.75,
- "reasoning": "Detailed explanation of your decision"
- }}
-
- **Important:**
- - Confidence must be 0.0 to 1.0
- - Always set stop_loss and take_profit
- - Consider volatility for TP/SL placement
- - Max position size: {self.safety_limits.max_position_size * 100}% of capital
- """
-
- def _parse_signal(self, response) -> Optional[TradingSignal]:
- """Parse agent response into trading signal"""
- try:
- content = self.agent._extract_response_content(response)
-
- # Try to extract JSON from response
- import re
- json_match = re.search(r'\{[^}]+\}', content, re.DOTALL)
- if not json_match:
- return None
-
- data = json.loads(json_match.group())
-
- if data.get('action') in ['hold', 'close']:
- return None
-
- return TradingSignal(
- symbol=data.get('symbol', 'BTC/USD'),
- direction=data['action'],
- entry_price=data['entry_price'],
- stop_loss=data['stop_loss'],
- take_profit=data['take_profit'],
- position_size=data.get('position_size_pct', 0.05),
- leverage=data.get('leverage', 1.0),
- confidence=data.get('confidence', 0.5),
- reasoning=data.get('reasoning', '')
- )
- except Exception as e:
- print(f"[AutoTrader] Failed to parse signal: {e}")
- return None
-
- def _validate_signal(self, signal: TradingSignal) -> bool:
- """Validate signal against safety limits"""
-
- # Check confidence
- if signal.confidence < self.safety_limits.min_confidence:
- print(f"[AutoTrader] Confidence too low: {signal.confidence}")
- return False
-
- # Check position size
- if signal.position_size > self.safety_limits.max_position_size:
- print(f"[AutoTrader] Position size too large: {signal.position_size}")
- return False
-
- # Check leverage
- if signal.leverage > self.safety_limits.max_leverage:
- print(f"[AutoTrader] Leverage too high: {signal.leverage}")
- return False
-
- # Check TP/SL required
- if self.safety_limits.require_stop_loss and not signal.stop_loss:
- print("[AutoTrader] Stop loss required but not provided")
- return False
-
- if self.safety_limits.require_take_profit and not signal.take_profit:
- print("[AutoTrader] Take profit required but not provided")
- return False
-
- # Check max open positions
- if len(self.positions) >= self.safety_limits.max_open_positions:
- print("[AutoTrader] Max open positions reached")
- return False
-
- return True
-
- def _calculate_position_size(self, signal: TradingSignal) -> float:
- """Calculate position size with confidence weighting (Alpha Arena style)"""
- # Base position size from signal
- base_size = signal.position_size * self.current_capital
-
- # Weight by confidence
- confidence_weighted = base_size * signal.confidence
-
- # Apply leverage
- leveraged_size = confidence_weighted * signal.leverage
-
- # Respect max limits
- max_size = self.safety_limits.max_position_size * self.current_capital
-
- return min(leveraged_size, max_size)
-
- async def _execute_trade(self, signal: TradingSignal, position_size: float):
- """Execute trade based on signal"""
- print(f"[AutoTrader] Executing {signal.direction.upper()} on {signal.symbol}")
- print(f"[AutoTrader] Size: ${position_size:.2f}, Confidence: {signal.confidence:.2f}")
-
- # In production, this would call actual exchange API
- # For now, simulate execution
-
- trade = {
- "id": f"trade_{self.state.total_trades + 1}",
- "symbol": signal.symbol,
- "direction": signal.direction,
- "entry_price": signal.entry_price,
- "size": position_size,
- "stop_loss": signal.stop_loss,
- "take_profit": signal.take_profit,
- "confidence": signal.confidence,
- "opened_at": datetime.now().isoformat(),
- "status": "open"
- }
-
- self.positions[trade['id']] = trade
- self.trade_history.append(trade)
- self.state.total_trades += 1
- self.state.last_trade_time = datetime.now().isoformat()
-
- # Trigger callback
- if 'trade_executed' in self.callbacks:
- self.callbacks['trade_executed'](trade)
-
- def _manage_positions(self):
- """Check and manage open positions (TP/SL)"""
- for trade_id, position in list(self.positions.items()):
- # In production, get current price from market
- # For now, simulate price movement
-
- # Check if TP or SL hit
- # self._check_exit_conditions(position)
- pass
-
- def _check_circuit_breaker(self) -> bool:
- """Check if circuit breaker should trigger"""
-
- # Check max drawdown
- if self.state.current_drawdown >= self.safety_limits.max_drawdown:
- print(f"[AutoTrader] Max drawdown reached: {self.state.current_drawdown:.2%}")
- return True
-
- # Check max daily loss
- if abs(self.state.daily_pnl) >= self.safety_limits.max_daily_loss * self.initial_capital:
- print(f"[AutoTrader] Max daily loss reached: ${self.state.daily_pnl:.2f}")
- return True
-
- return False
-
- def _trigger_emergency_stop(self, reason: str):
- """Trigger emergency stop"""
- print(f"[AutoTrader] EMERGENCY STOP: {reason}")
- self.state.circuit_breaker_triggered = True
- self._close_all_positions()
- self.stop()
-
- def _close_all_positions(self):
- """Close all open positions immediately"""
- for trade_id in list(self.positions.keys()):
- print(f"[AutoTrader] Closing position {trade_id}")
- del self.positions[trade_id]
-
- def _get_market_data(self) -> Dict:
- """Get current market data"""
- # In production, fetch from exchange
- return {
- "symbol": "BTC/USD",
- "price": 50000.0,
- "timestamp": datetime.now().isoformat()
- }
-
- def _get_portfolio_state(self) -> Dict:
- """Get current portfolio state"""
- return {
- "capital": self.current_capital,
- "position_count": len(self.positions),
- "daily_pnl": self.state.daily_pnl,
- "total_pnl": self.state.total_pnl
- }
-
- def get_state(self) -> Dict[str, Any]:
- """Get current auto-trader state"""
- return {
- "is_running": self.state.is_running,
- "total_trades": self.state.total_trades,
- "winning_trades": self.state.winning_trades,
- "losing_trades": self.state.losing_trades,
- "win_rate": (self.state.winning_trades / self.state.total_trades * 100) if self.state.total_trades > 0 else 0,
- "total_pnl": self.state.total_pnl,
- "current_drawdown": self.state.current_drawdown,
- "daily_pnl": self.state.daily_pnl,
- "open_positions": len(self.positions),
- "circuit_breaker": self.state.circuit_breaker_triggered
- }
diff --git a/fincept-qt/scripts/agno_trading/core/base_agent.py b/fincept-qt/scripts/agno_trading/core/base_agent.py
deleted file mode 100644
index f78a6f1c8..000000000
--- a/fincept-qt/scripts/agno_trading/core/base_agent.py
+++ /dev/null
@@ -1,364 +0,0 @@
-"""
-Base Agent Class
-
-This module implements the base trading agent class using the Agno framework.
-All specialized trading agents inherit from this base class.
-"""
-
-import os
-import sys
-import json
-from typing import List, Optional, Dict, Any, Union
-from datetime import datetime
-from dataclasses import dataclass, field
-
-try:
- from agno.agent import Agent
- from agno.models.response import ModelResponse
- from agno.tools.toolkit import Toolkit
- from agno.knowledge import Knowledge
- from agno.memory import MemoryManager
- AGNO_AVAILABLE = True
-except ImportError:
- AGNO_AVAILABLE = False
- # Fallback types for when Agno is not installed
- Agent = None
- ModelResponse = None
- Toolkit = None
- Knowledge = None
- MemoryManager = None
-
-
-@dataclass
-class AgentConfig:
- """Configuration for a trading agent"""
- name: str
- role: str
- description: str
- instructions: List[str] = field(default_factory=list)
-
- # LLM Configuration
- model_provider: str = "openai"
- model_name: str = "gpt-4o-mini"
- temperature: float = 0.7
- max_tokens: Optional[int] = 4096
-
- # Agent Capabilities
- tools: List[str] = field(default_factory=list)
- enable_knowledge: bool = False
- enable_memory: bool = False
-
- # Trading Configuration
- symbols: List[str] = field(default_factory=lambda: ["BTC/USD"])
- risk_tolerance: str = "moderate" # conservative, moderate, aggressive
-
- # Behavior
- show_tool_calls: bool = True
- markdown: bool = True
- stream: bool = False
-
- # Advanced
- reasoning_effort: Optional[str] = None # For o1/o3/o4 models
- structured_outputs: bool = False
- response_format: Optional[Dict[str, Any]] = None
-
-
-class BaseAgent:
- """
- Base Trading Agent using Agno framework
-
- This class provides common functionality for all trading agents:
- - Agent initialization with LLM configuration
- - Tool registration and execution
- - Knowledge base integration
- - Memory management
- - Session handling
- - Response streaming
- """
-
- def __init__(self, config: AgentConfig):
- """
- Initialize the base trading agent
-
- Args:
- config: Agent configuration object
- """
- if not AGNO_AVAILABLE:
- raise ImportError(
- "Agno framework is not installed. "
- "Install it with: pip install agno>=0.3.0"
- )
-
- self.config = config
- self.agent_id = f"{config.name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
- self.created_at = datetime.now()
-
- # Initialize LLM model
- self.model = self._initialize_model()
-
- # Initialize tools
- self.tools = self._initialize_tools()
-
- # Initialize knowledge base
- self.knowledge = self._initialize_knowledge() if config.enable_knowledge else None
-
- # Initialize memory
- self.memory = self._initialize_memory() if config.enable_memory else None
-
- # Create Agno agent
- self.agent = self._create_agent()
-
- # Session tracking
- self.sessions: Dict[str, List[Dict[str, Any]]] = {}
-
- def _initialize_model(self) -> Any:
- """Initialize the LLM model based on configuration"""
- provider = self.config.model_provider.lower()
- model_name = self.config.model_name
-
- # Get API key from environment
- api_key_map = {
- "openai": os.getenv("OPENAI_API_KEY"),
- "anthropic": os.getenv("ANTHROPIC_API_KEY"),
- "google": os.getenv("GOOGLE_API_KEY"),
- "gemini": os.getenv("GOOGLE_API_KEY"), # Gemini uses Google API key
- "groq": os.getenv("GROQ_API_KEY"),
- "deepseek": os.getenv("DEEPSEEK_API_KEY"),
- "xai": os.getenv("XAI_API_KEY"),
- "cohere": os.getenv("COHERE_API_KEY"),
- "mistral": os.getenv("MISTRAL_API_KEY"),
- "together": os.getenv("TOGETHER_API_KEY"),
- "fireworks": os.getenv("FIREWORKS_API_KEY"),
- }
-
- api_key = api_key_map.get(provider)
-
- # Model configuration
- model_config = {
- "id": model_name,
- "api_key": api_key,
- }
-
- # Add optional parameters
- if self.config.reasoning_effort:
- model_config["reasoning_effort"] = self.config.reasoning_effort
-
- # Provider-specific model initialization
- if provider == "openai":
- from agno.models.openai import OpenAIChat
- return OpenAIChat(**model_config)
- elif provider == "anthropic":
- from agno.models.anthropic import Claude
- return Claude(**model_config)
- elif provider == "google" or provider == "gemini":
- # Use OpenAI-compatible API for Google Gemini
- # Support both "google" and "gemini" as provider names
- from agno.models.openai import OpenAIChat
- return OpenAIChat(
- id=model_name,
- api_key=api_key,
- base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
- )
- elif provider == "groq":
- from agno.models.groq import Groq
- return Groq(**model_config)
- elif provider == "deepseek":
- from agno.models.openai import OpenAIChat
- return OpenAIChat(
- id=model_name,
- api_key=api_key,
- base_url="https://api.deepseek.com"
- )
- elif provider == "xai":
- from agno.models.openai import OpenAIChat
- return OpenAIChat(
- id=model_name,
- api_key=api_key,
- base_url="https://api.x.ai/v1"
- )
- elif provider == "ollama":
- from agno.models.ollama import Ollama
- return Ollama(id=model_name)
- else:
- # Default to OpenAI-compatible
- from agno.models.openai import OpenAIChat
- return OpenAIChat(**model_config)
-
- def _initialize_tools(self) -> List[Any]:
- """Initialize agent tools based on configuration"""
- tools = []
-
- # Tool registry mapping
- tool_registry = {
- "market_data": self._get_market_data_tools,
- "technical_analysis": self._get_technical_analysis_tools,
- "order_execution": self._get_order_execution_tools,
- "portfolio": self._get_portfolio_tools,
- "news_sentiment": self._get_news_sentiment_tools,
- }
-
- # Load configured tools
- for tool_name in self.config.tools:
- if tool_name in tool_registry:
- tool_fn = tool_registry[tool_name]
- tools.extend(tool_fn())
-
- return tools
-
- def _get_market_data_tools(self) -> List[Any]:
- """Get market data tools"""
- try:
- from tools.market_data import get_market_data_tools
- return get_market_data_tools()
- except ImportError:
- return []
-
- def _get_technical_analysis_tools(self) -> List[Any]:
- """Get technical analysis tools"""
- try:
- from tools.technical_indicators import get_technical_analysis_tools
- return get_technical_analysis_tools()
- except ImportError:
- return []
-
- def _get_order_execution_tools(self) -> List[Any]:
- """Get order execution tools"""
- # Placeholder - will be implemented in tools/order_execution.py
- return []
-
- def _get_portfolio_tools(self) -> List[Any]:
- """Get portfolio management tools"""
- # Placeholder - will be implemented in tools/portfolio_tools.py
- return []
-
- def _get_news_sentiment_tools(self) -> List[Any]:
- """Get news and sentiment tools"""
- # Placeholder - will be implemented in tools/news_sentiment.py
- return []
-
- def _initialize_knowledge(self) -> Optional[Knowledge]:
- """Initialize knowledge base for the agent"""
- if not self.config.enable_knowledge:
- return None
-
- # Will be implemented with proper vector DB configuration
- # from agno.knowledge.lancedb import LanceDBKnowledge
- # return LanceDBKnowledge(...)
- return None
-
- def _initialize_memory(self) -> Optional[MemoryManager]:
- """Initialize memory for the agent"""
- if not self.config.enable_memory:
- return None
-
- # Will be implemented with proper database configuration
- # from agno.memory.db.sqlite import SqliteMemory
- # return SqliteMemory(...)
- return None
-
- def _create_agent(self) -> Agent:
- """Create the Agno agent instance"""
- agent_params = {
- "name": self.config.name,
- "role": self.config.role,
- "model": self.model,
- "description": self.config.description,
- "instructions": self.config.instructions,
- "tools": self.tools if self.tools else None,
- "knowledge": self.knowledge,
- "markdown": self.config.markdown,
- }
-
- # Add optional parameters
- if self.config.structured_outputs:
- agent_params["structured_outputs"] = True
-
- if self.config.response_format:
- agent_params["response_format"] = self.config.response_format
-
- return Agent(**agent_params)
-
- def run(
- self,
- prompt: str,
- session_id: Optional[str] = None,
- stream: bool = False,
- **kwargs
- ) -> Union[ModelResponse, Any]:
- """
- Run the agent with a prompt
-
- Args:
- prompt: User prompt/query
- session_id: Optional session ID for conversation continuity
- stream: Whether to stream the response
- **kwargs: Additional parameters to pass to agent.run()
-
- Returns:
- ModelResponse object or streaming response
- """
- # Log what's being sent to the model
- print(f"\n{'='*80}", file=sys.stderr)
- print(f"[Agent: {self.config.name}] Running with model: {self.config.model_provider}:{self.config.model_name}", file=sys.stderr)
- print(f"Prompt length: {len(prompt)} chars", file=sys.stderr)
- print(f"Prompt preview: {prompt[:500]}...", file=sys.stderr)
- print(f"{'='*80}\n", file=sys.stderr)
-
- # Track in session
- if session_id:
- if session_id not in self.sessions:
- self.sessions[session_id] = []
- self.sessions[session_id].append({
- "timestamp": datetime.now().isoformat(),
- "prompt": prompt,
- "type": "user"
- })
-
- # Run agent (Agno uses 'input' parameter)
- response = self.agent.run(prompt, stream=stream or self.config.stream, **kwargs)
-
- # Track response in session
- if session_id and not stream:
- self.sessions[session_id].append({
- "timestamp": datetime.now().isoformat(),
- "response": self._extract_response_content(response),
- "type": "assistant"
- })
-
- return response
-
- def _extract_response_content(self, response: ModelResponse) -> str:
- """Extract content from ModelResponse"""
- if hasattr(response, 'content'):
- return response.content
- elif hasattr(response, 'message'):
- return response.message
- else:
- return str(response)
-
- def get_session_history(self, session_id: str) -> List[Dict[str, Any]]:
- """Get conversation history for a session"""
- return self.sessions.get(session_id, [])
-
- def clear_session(self, session_id: str) -> None:
- """Clear a specific session"""
- if session_id in self.sessions:
- del self.sessions[session_id]
-
- def to_dict(self) -> Dict[str, Any]:
- """Convert agent to dictionary representation"""
- return {
- "agent_id": self.agent_id,
- "name": self.config.name,
- "role": self.config.role,
- "description": self.config.description,
- "model_provider": self.config.model_provider,
- "model_name": self.config.model_name,
- "tools": self.config.tools,
- "symbols": self.config.symbols,
- "created_at": self.created_at.isoformat(),
- "active_sessions": len(self.sessions),
- }
-
- def __repr__(self) -> str:
- return f"<BaseAgent(id={self.agent_id}, name={self.config.name}, role={self.config.role})>"
diff --git a/fincept-qt/scripts/agno_trading/core/debate_orchestrator.py b/fincept-qt/scripts/agno_trading/core/debate_orchestrator.py
deleted file mode 100644
index f999e6543..000000000
--- a/fincept-qt/scripts/agno_trading/core/debate_orchestrator.py
+++ /dev/null
@@ -1,424 +0,0 @@
-"""
-Debate Orchestrator
-Manages Bull/Bear/Analyst debate system for trading decisions
-"""
-
-import sys
-import json
-from typing import Dict, Any, List, Optional
-from datetime import datetime
-import time
-
-try:
- from agno.agent import Agent
- from agno.models.response import ModelResponse
- AGNO_AVAILABLE = True
-except ImportError:
- AGNO_AVAILABLE = False
- Agent = None
- ModelResponse = None
-
-
-class DebateOrchestrator:
- """
- Orchestrates multi-agent debates for trading decisions
- Bull/Bear/Analyst format inspired by Alpha Arena
- """
-
- def __init__(self):
- """Initialize debate orchestrator"""
- if not AGNO_AVAILABLE:
- raise ImportError("Agno framework not available")
-
- def create_debate_agents(
- self,
- bull_model: str,
- bear_model: str,
- analyst_model: str,
- api_keys: Dict[str, str]
- ) -> Dict[str, Agent]:
- """
- Create Bull, Bear, and Analyst agents
-
- Args:
- bull_model: Model for bull agent (e.g., "openai:gpt-4o")
- bear_model: Model for bear agent
- analyst_model: Model for analyst agent
- api_keys: API keys for providers
-
- Returns:
- Dictionary of agents
- """
- # Set API keys
- import os
- for key, value in api_keys.items():
- os.environ[key] = value
-
- # Parse model strings
- bull_provider, bull_model_name = self._parse_model_string(bull_model)
- bear_provider, bear_model_name = self._parse_model_string(bear_model)
- analyst_provider, analyst_model_name = self._parse_model_string(analyst_model)
-
- # Initialize models
- bull_llm = self._get_model(bull_provider, bull_model_name, api_keys)
- bear_llm = self._get_model(bear_provider, bear_model_name, api_keys)
- analyst_llm = self._get_model(analyst_provider, analyst_model_name, api_keys)
-
- # Create Bull Agent (Optimistic)
- bull_agent = Agent(
- name="Bull Agent",
- role="Bullish Market Analyst",
- model=bull_llm,
- description="Analyzes markets from a bullish perspective, identifying opportunities for long positions",
- instructions=[
- "You are a bullish trading analyst. Your role is to identify REASONS TO BUY.",
- "Analyze market data, technical indicators, and sentiment to build a BULLISH case.",
- "Focus on: upward momentum, support levels, positive catalysts, bullish patterns.",
- "Be persuasive but use data and reasoning to support your arguments.",
- "Structure your argument: 1) Technical Analysis 2) Fundamental Catalysts 3) Risk Factors 4) Entry Strategy",
- "End with a clear BUY recommendation and target price if the case is strong."
- ],
- markdown=True
- )
-
- # Create Bear Agent (Pessimistic)
- bear_agent = Agent(
- name="Bear Agent",
- role="Bearish Market Analyst",
- model=bear_llm,
- description="Analyzes markets from a bearish perspective, identifying risks for short positions or avoiding longs",
- instructions=[
- "You are a bearish trading analyst. Your role is to identify REASONS TO SELL or AVOID.",
- "Analyze market data, technical indicators, and sentiment to build a BEARISH case.",
- "Focus on: downward momentum, resistance levels, negative catalysts, bearish patterns.",
- "Be persuasive but use data and reasoning to support your arguments.",
- "Structure your argument: 1) Technical Weaknesses 2) Fundamental Risks 3) Market Conditions 4) Exit/Short Strategy",
- "End with a clear SELL/AVOID recommendation and target price if the case is strong."
- ],
- markdown=True
- )
-
- # Create Analyst Agent (Neutral Decision Maker)
- analyst_agent = Agent(
- name="Analyst Agent",
- role="Chief Trading Analyst",
- model=analyst_llm,
- description="Synthesizes bull and bear arguments to make final trading decision",
- instructions=[
- "You are the CHIEF ANALYST. You listen to both BULL and BEAR arguments and make the FINAL DECISION.",
- "Be OBJECTIVE and DATA-DRIVEN. Do not favor either side - evaluate based on strength of evidence.",
- "Your decision process:",
- " 1) Summarize bull's strongest points",
- " 2) Summarize bear's strongest points",
- " 3) Identify which side has stronger evidence",
- " 4) Consider risk/reward ratio",
- " 5) Make FINAL CALL: BUY, SELL, or HOLD",
- "Provide: Action (BUY/SELL/HOLD), Entry Price, Stop Loss, Take Profit, Position Size %, Confidence (0-100%)",
- "Be decisive - the market waits for no one."
- ],
- markdown=True
- )
-
- return {
- 'bull': bull_agent,
- 'bear': bear_agent,
- 'analyst': analyst_agent
- }
-
- def run_debate(
- self,
- symbol: str,
- market_data: Dict[str, Any],
- bull_model: str,
- bear_model: str,
- analyst_model: str,
- api_keys: Dict[str, str]
- ) -> Dict[str, Any]:
- """
- Run a full debate session
-
- Args:
- symbol: Trading symbol
- market_data: Market data context
- bull_model: Bull agent model
- bear_model: Bear agent model
- analyst_model: Analyst agent model
- api_keys: API keys
-
- Returns:
- Debate result with final decision
- """
- start_time = time.time()
-
- try:
- # Create agents
- agents = self.create_debate_agents(bull_model, bear_model, analyst_model, api_keys)
-
- # Prepare market context
- context = self._format_market_context(symbol, market_data)
-
- # Step 1: Bull makes case
- print(f"[Debate] Bull agent analyzing {symbol}...", file=sys.stderr)
- bull_prompt = f"""
-Analyze {symbol} and make a BULLISH case for why traders should BUY.
-
-Market Context:
-{context}
-
-Provide your analysis with supporting data and reasoning.
-"""
- bull_response = agents['bull'].run(bull_prompt, stream=False)
- bull_argument = self._extract_response_content(bull_response)
-
- print(f"[Debate] Bull argument: {len(bull_argument)} chars", file=sys.stderr)
-
- # Step 2: Bear makes case
- print(f"[Debate] Bear agent analyzing {symbol}...", file=sys.stderr)
- bear_prompt = f"""
-Analyze {symbol} and make a BEARISH case for why traders should SELL or AVOID.
-
-Market Context:
-{context}
-
-Provide your analysis with supporting data and reasoning.
-"""
- bear_response = agents['bear'].run(bear_prompt, stream=False)
- bear_argument = self._extract_response_content(bear_response)
-
- print(f"[Debate] Bear argument: {len(bear_argument)} chars", file=sys.stderr)
-
- # Step 3: Analyst makes final decision
- print(f"[Debate] Analyst making final decision...", file=sys.stderr)
- analyst_prompt = f"""
-You have heard both sides of the debate for {symbol}.
-
-**BULL ARGUMENT:**
-{bull_argument}
-
-**BEAR ARGUMENT:**
-{bear_argument}
-
-**MARKET DATA:**
-{context}
-
-As the Chief Analyst, make your FINAL TRADING DECISION.
-
-Format your response as:
-DECISION: [BUY/SELL/HOLD]
-CONFIDENCE: [0-100]%
-ENTRY PRICE: $[price]
-STOP LOSS: $[price]
-TAKE PROFIT: $[price]
-POSITION SIZE: [0-100]%
-REASONING: [Brief explanation of why you made this decision]
-"""
- analyst_response = agents['analyst'].run(analyst_prompt, stream=False)
- analyst_decision = self._extract_response_content(analyst_response)
-
- print(f"[Debate] Analyst decision: {len(analyst_decision)} chars", file=sys.stderr)
-
- # Parse analyst decision
- final_decision = self._parse_analyst_decision(analyst_decision)
-
- # Calculate execution time
- execution_time_ms = int((time.time() - start_time) * 1000)
-
- # Record debate in database
- debate_data = {
- 'id': f"debate_{symbol}_{int(datetime.now().timestamp())}",
- 'symbol': symbol,
- 'bull_model': bull_model,
- 'bear_model': bear_model,
- 'analyst_model': analyst_model,
- 'bull_argument': bull_argument,
- 'bear_argument': bear_argument,
- 'analyst_decision': analyst_decision,
- 'final_action': final_decision.get('action', 'HOLD'),
- 'confidence': final_decision.get('confidence', 50),
- 'timestamp': int(datetime.now().timestamp()),
- 'execution_time_ms': execution_time_ms
- }
-
- from agno_trading.db.database_manager import get_db_manager
- db = get_db_manager()
- debate_id = db.record_debate(debate_data)
-
- return {
- 'success': True,
- 'debate_id': debate_id,
- 'symbol': symbol,
- 'bull_argument': bull_argument,
- 'bear_argument': bear_argument,
- 'analyst_decision': analyst_decision,
- 'final_action': final_decision.get('action'),
- 'confidence': final_decision.get('confidence'),
- 'entry_price': final_decision.get('entry_price'),
- 'stop_loss': final_decision.get('stop_loss'),
- 'take_profit': final_decision.get('take_profit'),
- 'position_size': final_decision.get('position_size'),
- 'reasoning': final_decision.get('reasoning'),
- 'execution_time_ms': execution_time_ms
- }
-
- except Exception as e:
- print(f"[Debate] Error: {str(e)}", file=sys.stderr)
- import traceback
- traceback.print_exc(file=sys.stderr)
-
- return {
- 'success': False,
- 'error': f"Debate failed: {str(e)}"
- }
-
- def _parse_model_string(self, model_string: str) -> tuple:
- """Parse model string like 'openai:gpt-4o' into provider and model name"""
- if ':' in model_string:
- provider, model = model_string.split(':', 1)
- else:
- provider = 'openai'
- model = model_string
-
- # Normalize provider
- provider = provider.lower()
- if provider == 'gemini':
- provider = 'google'
-
- return provider, model
-
- def _get_model(self, provider: str, model_name: str, api_keys: Dict[str, str]):
- """Get LLM model instance"""
- from agno.models.openai import OpenAIChat
-
- api_key_map = {
- 'openai': 'OPENAI_API_KEY',
- 'google': 'GOOGLE_API_KEY',
- 'anthropic': 'ANTHROPIC_API_KEY',
- 'groq': 'GROQ_API_KEY',
- 'deepseek': 'DEEPSEEK_API_KEY',
- 'xai': 'XAI_API_KEY'
- }
-
- key_name = api_key_map.get(provider, f"{provider.upper()}_API_KEY")
- api_key = api_keys.get(key_name, api_keys.get(f"GEMINI_API_KEY" if provider == "google" else ""))
-
- if provider == 'openai':
- from agno.models.openai import OpenAIChat
- return OpenAIChat(id=model_name, api_key=api_key)
- elif provider == 'anthropic':
- from agno.models.anthropic import Claude
- return Claude(id=model_name, api_key=api_key)
- elif provider == 'google':
- return OpenAIChat(
- id=model_name,
- api_key=api_key,
- base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
- )
- elif provider == 'groq':
- from agno.models.groq import Groq
- return Groq(id=model_name, api_key=api_key)
- elif provider == 'deepseek':
- return OpenAIChat(
- id=model_name,
- api_key=api_key,
- base_url="https://api.deepseek.com"
- )
- elif provider == 'xai':
- return OpenAIChat(
- id=model_name,
- api_key=api_key,
- base_url="https://api.x.ai/v1"
- )
- else:
- return OpenAIChat(id=model_name, api_key=api_key)
-
- def _format_market_context(self, symbol: str, market_data: Dict[str, Any]) -> str:
- """Format market data into readable context"""
- context_parts = [f"Symbol: {symbol}"]
-
- if 'price' in market_data:
- context_parts.append(f"Current Price: ${market_data['price']:.2f}")
-
- if 'change_24h' in market_data:
- context_parts.append(f"24h Change: {market_data['change_24h']:+.2f}%")
-
- if 'volume_24h' in market_data:
- context_parts.append(f"24h Volume: ${market_data['volume_24h']:,.0f}")
-
- if 'indicators' in market_data:
- context_parts.append("\nTechnical Indicators:")
- for key, value in market_data['indicators'].items():
- context_parts.append(f" - {key}: {value}")
-
- return "\n".join(context_parts)
-
- def _extract_response_content(self, response: ModelResponse) -> str:
- """Extract content from model response"""
- if hasattr(response, 'content'):
- return response.content
- elif hasattr(response, 'message'):
- return response.message
- else:
- return str(response)
-
- def _parse_analyst_decision(self, decision_text: str) -> Dict[str, Any]:
- """Parse analyst decision text into structured format"""
- import re
-
- result = {
- 'action': 'HOLD',
- 'confidence': 50,
- 'entry_price': None,
- 'stop_loss': None,
- 'take_profit': None,
- 'position_size': 10,
- 'reasoning': ''
- }
-
- # Extract DECISION
- decision_match = re.search(r'DECISION:\s*(\w+)', decision_text, re.IGNORECASE)
- if decision_match:
- result['action'] = decision_match.group(1).upper()
-
- # Extract CONFIDENCE
- confidence_match = re.search(r'CONFIDENCE:\s*(\d+)', decision_text, re.IGNORECASE)
- if confidence_match:
- result['confidence'] = int(confidence_match.group(1))
-
- # Extract prices
- entry_match = re.search(r'ENTRY PRICE:\s*\$?([0-9,.]+)', decision_text, re.IGNORECASE)
- if entry_match:
- result['entry_price'] = float(entry_match.group(1).replace(',', ''))
-
- sl_match = re.search(r'STOP LOSS:\s*\$?([0-9,.]+)', decision_text, re.IGNORECASE)
- if sl_match:
- result['stop_loss'] = float(sl_match.group(1).replace(',', ''))
-
- tp_match = re.search(r'TAKE PROFIT:\s*\$?([0-9,.]+)', decision_text, re.IGNORECASE)
- if tp_match:
- result['take_profit'] = float(tp_match.group(1).replace(',', ''))
-
- # Extract position size
- pos_match = re.search(r'POSITION SIZE:\s*(\d+)', decision_text, re.IGNORECASE)
- if pos_match:
- result['position_size'] = int(pos_match.group(1))
-
- # Extract reasoning
- reasoning_match = re.search(r'REASONING:\s*(.+?)(?:\n\n|\Z)', decision_text, re.IGNORECASE | re.DOTALL)
- if reasoning_match:
- result['reasoning'] = reasoning_match.group(1).strip()
- else:
- # Use full text as reasoning if no specific section found
- result['reasoning'] = decision_text[:500]
-
- return result
-
-
-# Global instance
-_debate_orchestrator = None
-
-def get_debate_orchestrator() -> DebateOrchestrator:
- """Get singleton debate orchestrator"""
- global _debate_orchestrator
- if _debate_orchestrator is None:
- _debate_orchestrator = DebateOrchestrator()
- return _debate_orchestrator
diff --git a/fincept-qt/scripts/agno_trading/core/trade_executor.py b/fincept-qt/scripts/agno_trading/core/trade_executor.py
deleted file mode 100644
index 7faf551e8..000000000
--- a/fincept-qt/scripts/agno_trading/core/trade_executor.py
+++ /dev/null
@@ -1,303 +0,0 @@
-"""
-Trade Executor
-Executes trades based on agent signals with risk management
-"""
-
-import json
-import sys
-from typing import Dict, Any, Optional
-from datetime import datetime
-
-
-class TradeExecutor:
- """
- Executes trades with risk validation and position management
- """
-
- def __init__(self, risk_config: Optional[Dict] = None):
- """
- Initialize trade executor
-
- Args:
- risk_config: Risk management configuration
- """
- self.risk_config = risk_config or {
- 'max_position_size_pct': 0.10, # 10% of portfolio
- 'max_leverage': 2.0,
- 'max_daily_loss_pct': 0.05, # 5% max daily loss
- 'min_risk_reward_ratio': 1.5,
- 'max_open_positions': 5,
- 'enable_stop_loss': True,
- 'enable_take_profit': True
- }
-
- def validate_trade_signal(
- self,
- signal: Dict[str, Any],
- portfolio_data: Dict[str, Any]
- ) -> Dict[str, Any]:
- """
- Validate trade signal against risk management rules
-
- Args:
- signal: Trade signal from agent
- portfolio_data: Current portfolio state
-
- Returns:
- Validation result with approved status and adjusted parameters
- """
- validation = {
- 'approved': True,
- 'reasons': [],
- 'warnings': [],
- 'adjusted_signal': signal.copy()
- }
-
- portfolio_value = portfolio_data.get('total_value', 10000.0)
- daily_pnl = portfolio_data.get('daily_pnl', 0)
- open_positions = len(portfolio_data.get('positions', []))
-
- # Safety check: Ensure portfolio_value is positive to prevent division by zero
- if portfolio_value <= 0:
- validation['approved'] = False
- validation['reasons'].append(
- f"Portfolio value is zero or negative (${portfolio_value:.2f}). Cannot process trades."
- )
- return validation
-
- # Check 1: Daily loss limit
- if daily_pnl < 0:
- daily_loss_pct = abs(daily_pnl / portfolio_value)
- if daily_loss_pct >= self.risk_config['max_daily_loss_pct']:
- validation['approved'] = False
- validation['reasons'].append(
- f"Daily loss limit reached ({daily_loss_pct*100:.1f}% >= {self.risk_config['max_daily_loss_pct']*100}%)"
- )
- return validation
-
- # Check 2: Max open positions
- if open_positions >= self.risk_config['max_open_positions']:
- validation['approved'] = False
- validation['reasons'].append(
- f"Maximum open positions reached ({open_positions}/{self.risk_config['max_open_positions']})"
- )
- return validation
-
- # Check 3: Position size limit
- entry_price = signal.get('entry_price', 0)
- quantity = signal.get('quantity', 0)
-
- # Validate entry price to prevent division by zero
- if entry_price <= 0:
- validation['approved'] = False
- validation['reasons'].append(
- f"Invalid entry price: {entry_price}. Entry price must be positive."
- )
- return validation
-
- intended_value = quantity * entry_price
- position_size_pct = intended_value / portfolio_value
-
- max_allowed_pct = self.risk_config['max_position_size_pct']
-
- if position_size_pct > max_allowed_pct:
- # Adjust quantity to fit within limits
- adjusted_quantity = (portfolio_value * max_allowed_pct) / entry_price
- validation['adjusted_signal']['quantity'] = adjusted_quantity
- validation['warnings'].append(
- f"Position size reduced from {position_size_pct*100:.1f}% to {max_allowed_pct*100}%"
- )
-
- # Check 4: Risk/Reward ratio (if stop loss and take profit provided)
- if signal.get('stop_loss') and signal.get('take_profit'):
- entry_price = signal.get('entry_price', 0)
- stop_loss = signal['stop_loss']
- take_profit = signal['take_profit']
- side = signal.get('side', 'buy')
-
- if side == 'buy':
- risk = abs(entry_price - stop_loss)
- reward = abs(take_profit - entry_price)
- else: # sell/short
- risk = abs(stop_loss - entry_price)
- reward = abs(entry_price - take_profit)
-
- rr_ratio = reward / risk if risk > 0 else 0
-
- if rr_ratio < self.risk_config['min_risk_reward_ratio']:
- validation['approved'] = False
- validation['reasons'].append(
- f"Risk/Reward ratio too low ({rr_ratio:.2f} < {self.risk_config['min_risk_reward_ratio']})"
- )
- return validation
-
- # Check 5: Mandatory stop loss
- if self.risk_config['enable_stop_loss'] and not signal.get('stop_loss'):
- # Auto-calculate stop loss (2% from entry)
- entry_price = signal.get('entry_price', 0)
- side = signal.get('side', 'buy')
-
- if side == 'buy':
- auto_stop_loss = entry_price * 0.98 # 2% below
- else:
- auto_stop_loss = entry_price * 1.02 # 2% above
-
- validation['adjusted_signal']['stop_loss'] = auto_stop_loss
- validation['warnings'].append(f"Auto stop-loss added at {auto_stop_loss:.2f}")
-
- # Check 6: Mandatory take profit
- if self.risk_config['enable_take_profit'] and not signal.get('take_profit'):
- # Auto-calculate take profit (4% from entry for 2:1 R:R)
- entry_price = signal.get('entry_price', 0)
- side = signal.get('side', 'buy')
-
- if side == 'buy':
- auto_take_profit = entry_price * 1.04 # 4% above
- else:
- auto_take_profit = entry_price * 0.96 # 4% below
-
- validation['adjusted_signal']['take_profit'] = auto_take_profit
- validation['warnings'].append(f"Auto take-profit added at {auto_take_profit:.2f}")
-
- return validation
-
- def execute_trade(
- self,
- signal: Dict[str, Any],
- portfolio_data: Dict[str, Any],
- agent_id: str,
- model: str,
- paper_trading: bool = True
- ) -> Dict[str, Any]:
- """
- Execute trade with risk validation
-
- Args:
- signal: Trade signal
- portfolio_data: Current portfolio state
- agent_id: Agent identifier
- model: Model name
- paper_trading: Whether this is paper trading
-
- Returns:
- Execution result
- """
- start_time = datetime.now()
-
- # Validate signal
- validation = self.validate_trade_signal(signal, portfolio_data)
-
- if not validation['approved']:
- return {
- 'success': False,
- 'error': 'Trade rejected by risk management',
- 'reasons': validation['reasons'],
- 'warnings': validation['warnings']
- }
-
- # Use adjusted signal
- adjusted_signal = validation['adjusted_signal']
-
- # Prepare trade data
- trade_data = {
- 'agent_id': agent_id,
- 'model': model,
- 'symbol': adjusted_signal['symbol'],
- 'side': adjusted_signal.get('side', 'buy'),
- 'order_type': adjusted_signal.get('order_type', 'market'),
- 'quantity': adjusted_signal.get('quantity', 0),
- 'entry_price': adjusted_signal.get('entry_price', 0),
- 'stop_loss': adjusted_signal.get('stop_loss'),
- 'take_profit': adjusted_signal.get('take_profit'),
- 'reasoning': adjusted_signal.get('reasoning', ''),
- 'metadata': {
- 'strategy': adjusted_signal.get('strategy'),
- 'confidence': adjusted_signal.get('confidence'),
- 'indicators': adjusted_signal.get('indicators', {}),
- 'original_signal': signal
- },
- 'is_paper_trade': paper_trading,
- 'entry_timestamp': int(datetime.now().timestamp()),
- 'execution_time_ms': 0
- }
-
- # Record in database
- try:
- from agno_trading.db.database_manager import get_db_manager
- db = get_db_manager()
- trade_id = db.record_trade(trade_data)
-
- # Log decision
- db.log_decision({
- 'agent_id': agent_id,
- 'model': model,
- 'decision_type': 'trade',
- 'symbol': adjusted_signal['symbol'],
- 'decision': f"{adjusted_signal['side'].upper()} {adjusted_signal['quantity']:.4f} @ {adjusted_signal['entry_price']:.2f}",
- 'reasoning': adjusted_signal.get('reasoning'),
- 'confidence': adjusted_signal.get('confidence'),
- 'timestamp': int(datetime.now().timestamp())
- })
-
- execution_time_ms = int((datetime.now() - start_time).total_seconds() * 1000)
-
- return {
- 'success': True,
- 'trade_id': trade_id,
- 'trade_data': trade_data,
- 'warnings': validation['warnings'],
- 'execution_time_ms': execution_time_ms
- }
-
- except Exception as e:
- return {
- 'success': False,
- 'error': f"Trade execution failed: {str(e)}"
- }
-
- def close_position(
- self,
- trade_id: int,
- exit_price: float,
- reason: str = 'manual'
- ) -> Dict[str, Any]:
- """
- Close an open position
-
- Args:
- trade_id: Trade ID to close
- exit_price: Exit price
- reason: Reason for closing
-
- Returns:
- Close result
- """
- try:
- from agno_trading.db.database_manager import get_db_manager
- db = get_db_manager()
-
- db.close_trade(trade_id, exit_price)
-
- return {
- 'success': True,
- 'trade_id': trade_id,
- 'exit_price': exit_price,
- 'reason': reason
- }
-
- except Exception as e:
- return {
- 'success': False,
- 'error': f"Failed to close position: {str(e)}"
- }
-
-
-# Global instance
-_trade_executor = None
-
-def get_trade_executor() -> TradeExecutor:
- """Get singleton trade executor"""
- global _trade_executor
- if _trade_executor is None:
- _trade_executor = TradeExecutor()
- return _trade_executor
diff --git a/fincept-qt/scripts/agno_trading/core/workflow_engine.py b/fincept-qt/scripts/agno_trading/core/workflow_engine.py
deleted file mode 100644
index 1cf31e1ef..000000000
--- a/fincept-qt/scripts/agno_trading/core/workflow_engine.py
+++ /dev/null
@@ -1,147 +0,0 @@
-"""
-Workflow Engine
-
-This module manages deterministic trading workflows.
-"""
-
-from typing import List, Dict, Any, Optional, Callable
-from datetime import datetime
-from dataclasses import dataclass
-
-
-@dataclass
-class WorkflowStep:
- """A single step in a workflow"""
- name: str
- function: Callable
- inputs: Dict[str, Any]
- outputs: List[str]
- condition: Optional[Callable] = None
-
-
-class WorkflowEngine:
- """
- Executes deterministic trading workflows
-
- Features:
- - Sequential step execution
- - Conditional branching
- - Error handling and recovery
- - State persistence
- """
-
- def __init__(self):
- """Initialize workflow engine"""
- self.workflows: Dict[str, List[WorkflowStep]] = {}
- self.execution_history: List[Dict[str, Any]] = []
- self.created_at = datetime.now()
-
- def create_workflow(
- self,
- name: str,
- steps: List[WorkflowStep]
- ) -> str:
- """
- Create a new workflow
-
- Args:
- name: Workflow name
- steps: List of workflow steps
-
- Returns:
- workflow_id: Unique workflow identifier
- """
- workflow_id = f"workflow_{name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
- self.workflows[workflow_id] = steps
- return workflow_id
-
- def execute_workflow(
- self,
- workflow_id: str,
- initial_inputs: Dict[str, Any] = None
- ) -> Dict[str, Any]:
- """
- Execute a workflow
-
- Args:
- workflow_id: Workflow identifier
- initial_inputs: Initial workflow inputs
-
- Returns:
- Workflow execution result
- """
- if workflow_id not in self.workflows:
- raise ValueError(f"Workflow not found: {workflow_id}")
-
- steps = self.workflows[workflow_id]
- state = initial_inputs or {}
- results = []
-
- start_time = datetime.now()
-
- try:
- for step in steps:
- # Check condition if exists
- if step.condition and not step.condition(state):
- continue
-
- # Execute step
- step_result = step.function(**{**step.inputs, **state})
-
- # Update state with outputs
- for output_key in step.outputs:
- if output_key in step_result:
- state[output_key] = step_result[output_key]
-
- results.append({
- "step": step.name,
- "status": "completed",
- "result": step_result
- })
-
- end_time = datetime.now()
- execution_time = (end_time - start_time).total_seconds()
-
- execution = {
- "workflow_id": workflow_id,
- "status": "completed",
- "execution_time": execution_time,
- "steps": results,
- "final_state": state,
- "timestamp": end_time.isoformat()
- }
-
- self.execution_history.append(execution)
-
- return execution
-
- except Exception as e:
- return {
- "workflow_id": workflow_id,
- "status": "failed",
- "error": str(e),
- "steps": results,
- "timestamp": datetime.now().isoformat()
- }
-
-
-# Example workflow patterns for trading:
-# 1. Market Analysis Workflow:
-# - Fetch market data
-# - Calculate indicators
-# - Analyze patterns
-# - Generate insights
-#
-# 2. Signal Generation Workflow:
-# - Market analysis
-# - Strategy evaluation
-# - Signal generation
-# - Risk assessment
-# - Order preparation
-#
-# 3. Risk Management Workflow:
-# - Portfolio evaluation
-# - Position sizing
-# - Stop loss calculation
-# - Exposure analysis
-# - Rebalancing recommendations
diff --git a/fincept-qt/scripts/agno_trading/db/database_manager.py b/fincept-qt/scripts/agno_trading/db/database_manager.py
deleted file mode 100644
index 997b6283b..000000000
--- a/fincept-qt/scripts/agno_trading/db/database_manager.py
+++ /dev/null
@@ -1,810 +0,0 @@
-"""
-Database Manager for Agno Trading System
-Handles all database operations for agent trades, performance, decisions, and evolution
-"""
-
-import sqlite3
-import json
-import os
-from typing import Dict, List, Any, Optional, Tuple
-from datetime import datetime, timedelta
-import sys
-
-class DatabaseManager:
- def __init__(self, db_path: Optional[str] = None):
- """Initialize database manager"""
- if db_path is None:
- # Use FINCEPT_DATA_DIR env var if set by host, otherwise use platform-specific app data
- data_dir = os.environ.get("FINCEPT_DATA_DIR")
- if data_dir:
- db_dir = os.path.join(data_dir, 'alpha_arena')
- else:
- # Fallback to platform-specific user data directory
- if os.name == "nt": # Windows
- base = os.environ.get("LOCALAPPDATA", os.path.expanduser("~/AppData/Local"))
- elif hasattr(os, 'uname') and os.uname().sysname == "Darwin": # macOS
- base = os.path.expanduser("~/Library/Application Support")
- else: # Linux
- base = os.path.expanduser("~/.local/share")
- db_dir = os.path.join(base, 'fincept-dev', 'alpha_arena')
- os.makedirs(db_dir, exist_ok=True)
- db_path = os.path.join(db_dir, 'agno_trading.db')
- print(f"[DatabaseManager] Using database at: {db_path}", file=sys.stderr)
-
- self.db_path = db_path
- self.initialize_database()
-
- def get_connection(self) -> sqlite3.Connection:
- """Get database connection"""
- conn = sqlite3.connect(self.db_path)
- conn.row_factory = sqlite3.Row
- return conn
-
- def initialize_database(self):
- """Create tables if they don't exist"""
- schema_path = os.path.join(os.path.dirname(__file__), 'schema.sql')
-
- conn = self.get_connection()
-
- if os.path.exists(schema_path):
- with open(schema_path, 'r') as f:
- schema_sql = f.read()
- conn.executescript(schema_sql)
-
- # Initialize competition-related tables
- self._initialize_competition_tables(conn)
-
- conn.commit()
- conn.close()
-
- # ============================================================================
- # TRADE OPERATIONS
- # ============================================================================
-
- def record_trade(self, trade_data: Dict[str, Any]) -> int:
- """Record a new trade"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- cursor.execute("""
- INSERT INTO agent_trades (
- agent_id, model, symbol, side, order_type, quantity,
- entry_price, stop_loss, take_profit, entry_timestamp,
- reasoning, metadata, execution_time_ms, is_paper_trade
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- """, (
- trade_data['agent_id'],
- trade_data['model'],
- trade_data['symbol'],
- trade_data['side'],
- trade_data.get('order_type', 'market'),
- trade_data['quantity'],
- trade_data['entry_price'],
- trade_data.get('stop_loss'),
- trade_data.get('take_profit'),
- trade_data.get('entry_timestamp', int(datetime.now().timestamp())),
- trade_data.get('reasoning'),
- json.dumps(trade_data.get('metadata', {})),
- trade_data.get('execution_time_ms', 0),
- trade_data.get('is_paper_trade', 1)
- ))
-
- trade_id = cursor.lastrowid
- conn.commit()
- conn.close()
-
- # Update performance metrics
- self.update_performance_metrics(trade_data['agent_id'])
-
- return trade_id
-
- def close_trade(self, trade_id: int, exit_price: float, exit_timestamp: Optional[int] = None):
- """Close an open trade"""
- if exit_timestamp is None:
- exit_timestamp = int(datetime.now().timestamp())
-
- conn = self.get_connection()
- cursor = conn.cursor()
-
- # Get trade details
- cursor.execute("SELECT * FROM agent_trades WHERE id = ?", (trade_id,))
- trade = cursor.fetchone()
-
- if not trade:
- conn.close()
- return
-
- # Calculate P&L
- quantity = trade['quantity']
- entry_price = trade['entry_price']
- side = trade['side']
-
- if side == 'buy':
- pnl = (exit_price - entry_price) * quantity
- else: # sell/short
- pnl = (entry_price - exit_price) * quantity
-
- # Calculate P&L percentage based on total cost basis (including estimated fees)
- # This gives a more accurate return on capital deployed
- # Note: If fees are tracked in metadata, use them; otherwise estimate ~0.1% round-trip
- metadata = json.loads(trade['metadata']) if trade['metadata'] else {}
- entry_fee = metadata.get('entry_fee', entry_price * quantity * 0.0005) # 0.05% default
- exit_fee = metadata.get('exit_fee', exit_price * quantity * 0.0005) # 0.05% default
- total_fees = entry_fee + exit_fee
-
- # Actual P&L after fees
- pnl_after_fees = pnl - total_fees
-
- # Cost basis = entry cost + entry fee (capital actually deployed)
- cost_basis = (entry_price * quantity) + entry_fee
-
- # P&L percent based on cost basis
- pnl_percent = (pnl_after_fees / cost_basis) * 100 if cost_basis > 0 else 0
-
- # Update trade (store pnl_after_fees for accurate reporting)
- cursor.execute("""
- UPDATE agent_trades
- SET exit_price = ?, exit_timestamp = ?, pnl = ?, pnl_percent = ?, status = 'closed'
- WHERE id = ?
- """, (exit_price, exit_timestamp, pnl_after_fees, pnl_percent, trade_id))
-
- conn.commit()
- conn.close()
-
- # Update performance metrics
- self.update_performance_metrics(trade['agent_id'])
-
- def get_agent_trades(self, agent_id: str, limit: int = 100, status: Optional[str] = None) -> List[Dict]:
- """Get trades for an agent"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- if status:
- cursor.execute("""
- SELECT * FROM agent_trades
- WHERE agent_id = ? AND status = ?
- ORDER BY entry_timestamp DESC
- LIMIT ?
- """, (agent_id, status, limit))
- else:
- cursor.execute("""
- SELECT * FROM agent_trades
- WHERE agent_id = ?
- ORDER BY entry_timestamp DESC
- LIMIT ?
- """, (agent_id, limit))
-
- trades = [dict(row) for row in cursor.fetchall()]
- conn.close()
-
- return trades
-
- # ============================================================================
- # PERFORMANCE METRICS
- # ============================================================================
-
- def update_performance_metrics(self, agent_id: str):
- """Recalculate and update performance metrics for an agent"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- # Get all closed trades
- cursor.execute("""
- SELECT * FROM agent_trades
- WHERE agent_id = ? AND status = 'closed'
- ORDER BY entry_timestamp ASC
- """, (agent_id,))
-
- trades = cursor.fetchall()
-
- if not trades:
- conn.close()
- return
-
- # Calculate metrics
- total_trades = len(trades)
- winning_trades = len([t for t in trades if t['pnl'] > 0])
- losing_trades = len([t for t in trades if t['pnl'] < 0])
-
- total_pnl = sum(t['pnl'] for t in trades)
-
- # Time-based P&L
- now = datetime.now().timestamp()
- day_ago = now - 86400
- week_ago = now - 604800
- month_ago = now - 2592000
-
- daily_pnl = sum(t['pnl'] for t in trades if t['exit_timestamp'] and t['exit_timestamp'] >= day_ago)
- weekly_pnl = sum(t['pnl'] for t in trades if t['exit_timestamp'] and t['exit_timestamp'] >= week_ago)
- monthly_pnl = sum(t['pnl'] for t in trades if t['exit_timestamp'] and t['exit_timestamp'] >= month_ago)
-
- win_rate = (winning_trades / total_trades * 100) if total_trades > 0 else 0
-
- # Win/Loss stats
- wins = [t['pnl'] for t in trades if t['pnl'] > 0]
- losses = [abs(t['pnl']) for t in trades if t['pnl'] < 0]
-
- avg_win = sum(wins) / len(wins) if wins else 0
- avg_loss = sum(losses) / len(losses) if losses else 0
-
- largest_win = max(wins) if wins else 0
- largest_loss = max(losses) if losses else 0
-
- profit_factor = (sum(wins) / sum(losses)) if losses and sum(losses) > 0 else 0
-
- # Risk-free rate assumption (annualized, e.g., 4% = 0.04)
- risk_free_rate_annual = 0.04
-
- # Sharpe Ratio (properly annualized)
- # Convert pnl_percent from percentage (e.g., 5.0) to decimal (0.05)
- sharpe_ratio = 0.0
- sortino_ratio = 0.0
-
- if len(trades) >= 2:
- # Convert percentage returns to decimal returns
- returns = [t['pnl_percent'] / 100.0 for t in trades if t['pnl_percent'] is not None]
-
- if returns:
- avg_return = sum(returns) / len(returns)
-
- # Calculate standard deviation
- variance = sum((r - avg_return) ** 2 for r in returns) / len(returns)
- std_dev = variance ** 0.5
-
- # Annualization factor (assuming daily trades, ~252 trading days/year)
- # Adjust based on actual trading frequency
- annualization_factor = 252 ** 0.5
-
- # Daily risk-free rate
- risk_free_rate_daily = risk_free_rate_annual / 252
-
- # Sharpe Ratio: (avg_return - risk_free_rate) / std_dev * sqrt(252)
- if std_dev > 0:
- sharpe_ratio = ((avg_return - risk_free_rate_daily) / std_dev) * annualization_factor
- else:
- sharpe_ratio = 0.0
-
- # Sortino Ratio: Uses downside deviation instead of standard deviation
- # Only considers negative returns (downside risk)
- negative_returns = [r for r in returns if r < 0]
- if negative_returns:
- downside_variance = sum(r ** 2 for r in negative_returns) / len(returns)
- downside_deviation = downside_variance ** 0.5
-
- if downside_deviation > 0:
- sortino_ratio = ((avg_return - risk_free_rate_daily) / downside_deviation) * annualization_factor
- else:
- sortino_ratio = 0.0
- else:
- # No negative returns - exceptional performance
- sortino_ratio = sharpe_ratio * 1.5 if sharpe_ratio > 0 else 0.0
-
- # Drawdown calculation
- cumulative_pnl = []
- running_pnl = 0
- for trade in trades:
- running_pnl += trade['pnl']
- cumulative_pnl.append(running_pnl)
-
- peak = cumulative_pnl[0]
- max_drawdown = 0
- current_drawdown = 0
-
- for pnl in cumulative_pnl:
- if pnl > peak:
- peak = pnl
- drawdown = (peak - pnl) / abs(peak) if peak != 0 else 0
- max_drawdown = max(max_drawdown, drawdown)
-
- if cumulative_pnl:
- current_drawdown = (peak - cumulative_pnl[-1]) / abs(peak) if peak != 0 else 0
-
- # Consecutive wins/losses
- consecutive_wins = 0
- consecutive_losses = 0
- max_consecutive_wins = 0
- max_consecutive_losses = 0
- current_streak_wins = 0
- current_streak_losses = 0
-
- for trade in trades:
- if trade['pnl'] > 0:
- current_streak_wins += 1
- current_streak_losses = 0
- max_consecutive_wins = max(max_consecutive_wins, current_streak_wins)
- elif trade['pnl'] < 0:
- current_streak_losses += 1
- current_streak_wins = 0
- max_consecutive_losses = max(max_consecutive_losses, current_streak_losses)
-
- consecutive_wins = current_streak_wins
- consecutive_losses = current_streak_losses
-
- # Total volume
- total_volume = sum(t['quantity'] * t['entry_price'] for t in trades)
-
- # Open positions
- cursor.execute("SELECT COUNT(*) as count FROM agent_trades WHERE agent_id = ? AND status = 'open'", (agent_id,))
- positions = cursor.fetchone()['count']
-
- # Last trade timestamp
- last_trade_timestamp = trades[-1]['exit_timestamp'] if trades[-1]['exit_timestamp'] else trades[-1]['entry_timestamp']
-
- # Get model name
- cursor.execute("SELECT model FROM agent_trades WHERE agent_id = ? LIMIT 1", (agent_id,))
- result = cursor.fetchone()
- model = result['model'] if result else 'unknown'
-
- # Upsert performance metrics
- cursor.execute("""
- INSERT OR REPLACE INTO agent_performance (
- agent_id, model, total_trades, winning_trades, losing_trades,
- total_pnl, daily_pnl, weekly_pnl, monthly_pnl, win_rate,
- sharpe_ratio, sortino_ratio, max_drawdown, current_drawdown,
- avg_win, avg_loss, profit_factor, largest_win, largest_loss,
- consecutive_wins, consecutive_losses, max_consecutive_wins,
- max_consecutive_losses, total_volume, positions, last_trade_timestamp,
- last_updated
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- """, (
- agent_id, model, total_trades, winning_trades, losing_trades,
- total_pnl, daily_pnl, weekly_pnl, monthly_pnl, win_rate,
- sharpe_ratio, sortino_ratio, max_drawdown, current_drawdown,
- avg_win, avg_loss, profit_factor, largest_win, largest_loss,
- consecutive_wins, consecutive_losses, max_consecutive_wins,
- max_consecutive_losses, total_volume, positions, last_trade_timestamp,
- int(datetime.now().timestamp())
- ))
-
- conn.commit()
- conn.close()
-
- def get_agent_performance(self, agent_id: str) -> Optional[Dict]:
- """Get performance metrics for an agent"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- cursor.execute("SELECT * FROM agent_performance WHERE agent_id = ?", (agent_id,))
- result = cursor.fetchone()
-
- conn.close()
-
- return dict(result) if result else None
-
- def get_leaderboard(self, limit: int = 20) -> List[Dict]:
- """Get leaderboard of all agents sorted by total P&L"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- cursor.execute("""
- SELECT * FROM agent_performance
- ORDER BY total_pnl DESC
- LIMIT ?
- """, (limit,))
-
- leaderboard = [dict(row) for row in cursor.fetchall()]
- conn.close()
-
- return leaderboard
-
- # ============================================================================
- # DECISIONS LOG
- # ============================================================================
-
- def log_decision(self, decision_data: Dict[str, Any]):
- """Log an agent decision for real-time feed"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- cursor.execute("""
- INSERT INTO agent_decisions (
- agent_id, model, decision_type, symbol, decision,
- reasoning, confidence, timestamp, execution_time_ms
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
- """, (
- decision_data['agent_id'],
- decision_data['model'],
- decision_data['decision_type'],
- decision_data.get('symbol'),
- decision_data['decision'],
- decision_data.get('reasoning'),
- decision_data.get('confidence'),
- decision_data.get('timestamp', int(datetime.now().timestamp())),
- decision_data.get('execution_time_ms', 0)
- ))
-
- conn.commit()
- conn.close()
-
- def get_recent_decisions(self, limit: int = 50, agent_id: Optional[str] = None) -> List[Dict]:
- """Get recent decisions from all or specific agent"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- if agent_id:
- cursor.execute("""
- SELECT * FROM agent_decisions
- WHERE agent_id = ?
- ORDER BY timestamp DESC
- LIMIT ?
- """, (agent_id, limit))
- else:
- cursor.execute("""
- SELECT * FROM agent_decisions
- ORDER BY timestamp DESC
- LIMIT ?
- """, (limit,))
-
- decisions = [dict(row) for row in cursor.fetchall()]
- conn.close()
-
- return decisions
-
- # ============================================================================
- # EVOLUTION
- # ============================================================================
-
- def log_evolution(self, evolution_data: Dict[str, Any]):
- """Log agent evolution event"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- cursor.execute("""
- INSERT INTO agent_evolution (
- agent_id, model, evolution_trigger, old_instructions,
- new_instructions, metrics_before, metrics_after, timestamp, notes
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
- """, (
- evolution_data['agent_id'],
- evolution_data['model'],
- evolution_data['evolution_trigger'],
- evolution_data.get('old_instructions'),
- evolution_data['new_instructions'],
- json.dumps(evolution_data.get('metrics_before', {})),
- json.dumps(evolution_data.get('metrics_after', {})),
- evolution_data.get('timestamp', int(datetime.now().timestamp())),
- evolution_data.get('notes')
- ))
-
- conn.commit()
- conn.close()
-
- def get_evolution_history(self, agent_id: str, limit: int = 10) -> List[Dict]:
- """Get evolution history for an agent"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- cursor.execute("""
- SELECT * FROM agent_evolution
- WHERE agent_id = ?
- ORDER BY timestamp DESC
- LIMIT ?
- """, (agent_id, limit))
-
- history = [dict(row) for row in cursor.fetchall()]
- conn.close()
-
- return history
-
- # ============================================================================
- # DEBATE SESSIONS
- # ============================================================================
-
- def record_debate(self, debate_data: Dict[str, Any]) -> str:
- """Record a debate session"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- debate_id = debate_data.get('id', f"debate_{int(datetime.now().timestamp())}")
-
- cursor.execute("""
- INSERT OR REPLACE INTO debate_sessions (
- id, symbol, bull_model, bear_model, analyst_model,
- bull_argument, bear_argument, analyst_decision,
- final_action, confidence, timestamp, execution_time_ms
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- """, (
- debate_id,
- debate_data['symbol'],
- debate_data['bull_model'],
- debate_data['bear_model'],
- debate_data['analyst_model'],
- debate_data.get('bull_argument'),
- debate_data.get('bear_argument'),
- debate_data.get('analyst_decision'),
- debate_data.get('final_action'),
- debate_data.get('confidence'),
- debate_data.get('timestamp', int(datetime.now().timestamp())),
- debate_data.get('execution_time_ms', 0)
- ))
-
- conn.commit()
- conn.close()
-
- return debate_id
-
- def get_recent_debates(self, limit: int = 10) -> List[Dict]:
- """Get recent debate sessions"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- cursor.execute("""
- SELECT * FROM debate_sessions
- ORDER BY timestamp DESC
- LIMIT ?
- """, (limit,))
-
- debates = [dict(row) for row in cursor.fetchall()]
- conn.close()
-
- return debates
-
-
- # ============================================================================
- # COMPETITION STATE MANAGEMENT
- # ============================================================================
-
- def save_competition_config(self, competition_id: str, name: str, models_json: str,
- symbol: str, mode: str, api_keys_json: str = "{}"):
- """Save competition configuration to database"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- cursor.execute("""
- INSERT OR REPLACE INTO competition_configs (
- competition_id, name, models_json, symbol, mode,
- api_keys_json, status, created_at
- ) VALUES (?, ?, ?, ?, ?, ?, 'created', ?)
- """, (
- competition_id, name, models_json, symbol, mode,
- api_keys_json, int(datetime.now().timestamp())
- ))
-
- conn.commit()
- conn.close()
- print(f"[DatabaseManager] Saved competition config: {competition_id}", file=sys.stderr)
-
- def get_competition_config(self, competition_id: str) -> Optional[Dict]:
- """Get competition configuration from database"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- cursor.execute("""
- SELECT * FROM competition_configs WHERE competition_id = ?
- """, (competition_id,))
-
- result = cursor.fetchone()
- conn.close()
-
- if result:
- return dict(result)
- return None
-
- def get_active_competition(self) -> Optional[Dict]:
- """Get the most recent active competition"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- cursor.execute("""
- SELECT * FROM competition_configs
- WHERE status IN ('created', 'running')
- ORDER BY created_at DESC LIMIT 1
- """)
-
- result = cursor.fetchone()
- conn.close()
-
- if result:
- return dict(result)
- return None
-
- def update_competition_status(self, competition_id: str, status: str):
- """Update competition status"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- cursor.execute("""
- UPDATE competition_configs SET status = ? WHERE competition_id = ?
- """, (status, competition_id))
-
- conn.commit()
- conn.close()
-
- def save_model_state(self, competition_id: str, model_name: str,
- capital: float, positions_json: str, trades_count: int,
- total_pnl: float = 0.0, portfolio_value: float = 0.0):
- """Save model state for competition"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- # Generate unique ID
- state_id = f"{competition_id}_{model_name}"
-
- cursor.execute("""
- INSERT OR REPLACE INTO alpha_model_states (
- id, competition_id, model_name, capital, positions_json,
- trades_count, total_pnl, portfolio_value, updated_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
- """, (
- state_id, competition_id, model_name, capital, positions_json,
- trades_count, total_pnl, portfolio_value, int(datetime.now().timestamp())
- ))
-
- conn.commit()
- conn.close()
-
- def get_model_states(self, competition_id: str) -> List[Dict]:
- """Get all model states for a competition"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- cursor.execute("""
- SELECT * FROM alpha_model_states WHERE competition_id = ?
- """, (competition_id,))
-
- results = [dict(row) for row in cursor.fetchall()]
- conn.close()
-
- return results
-
- def _initialize_competition_tables(self, conn: sqlite3.Connection):
- """Create competition-related tables (called from initialize_database)"""
- # Competition config and model state tables
- conn.executescript("""
- CREATE TABLE IF NOT EXISTS competition_configs (
- competition_id TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- models_json TEXT NOT NULL,
- symbol TEXT NOT NULL,
- mode TEXT NOT NULL,
- api_keys_json TEXT,
- status TEXT DEFAULT 'created',
- created_at INTEGER
- );
-
- CREATE TABLE IF NOT EXISTS alpha_performance_snapshots (
- id TEXT PRIMARY KEY,
- competition_id TEXT NOT NULL,
- cycle_number INTEGER NOT NULL,
- model_name TEXT NOT NULL,
- portfolio_value REAL NOT NULL,
- cash REAL NOT NULL,
- pnl REAL NOT NULL,
- return_pct REAL NOT NULL,
- positions_count INTEGER NOT NULL,
- trades_count INTEGER NOT NULL,
- timestamp TEXT NOT NULL
- );
-
- CREATE TABLE IF NOT EXISTS alpha_decision_logs (
- id TEXT PRIMARY KEY,
- competition_id TEXT NOT NULL,
- model_name TEXT NOT NULL,
- cycle_number INTEGER NOT NULL,
- action TEXT NOT NULL,
- symbol TEXT NOT NULL,
- quantity REAL,
- confidence REAL NOT NULL,
- reasoning TEXT NOT NULL,
- trade_executed TEXT NOT NULL,
- price_at_decision REAL,
- portfolio_value_before REAL,
- portfolio_value_after REAL,
- timestamp TEXT NOT NULL
- );
-
- CREATE INDEX IF NOT EXISTS idx_competition_configs_status ON competition_configs(status);
- CREATE INDEX IF NOT EXISTS idx_alpha_snapshots_competition ON alpha_performance_snapshots(competition_id);
- CREATE INDEX IF NOT EXISTS idx_alpha_snapshots_cycle ON alpha_performance_snapshots(cycle_number);
- CREATE INDEX IF NOT EXISTS idx_alpha_decision_logs_competition ON alpha_decision_logs(competition_id);
- CREATE INDEX IF NOT EXISTS idx_alpha_decision_logs_model ON alpha_decision_logs(model_name);
- CREATE INDEX IF NOT EXISTS idx_alpha_decision_logs_cycle ON alpha_decision_logs(cycle_number);
- """)
-
- def save_decision_log(self, competition_id: str, model_name: str, cycle_number: int,
- action: str, symbol: str, quantity: float, confidence: float,
- reasoning: str, trade_executed: bool, price_at_decision: float,
- portfolio_value_before: float, portfolio_value_after: float):
- """Save decision log to database"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- # Generate unique ID
- timestamp = int(datetime.now().timestamp() * 1000)
- decision_id = f"{competition_id}_{model_name}_{cycle_number}_{timestamp}"
-
- cursor.execute("""
- INSERT INTO alpha_decision_logs (
- id, competition_id, model_name, cycle_number, action, symbol, quantity,
- confidence, reasoning, trade_executed, price_at_decision,
- portfolio_value_before, portfolio_value_after, timestamp
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- """, (
- decision_id, competition_id, model_name, cycle_number, action, symbol, quantity,
- confidence, reasoning, trade_executed, price_at_decision,
- portfolio_value_before, portfolio_value_after, timestamp
- ))
-
- conn.commit()
- conn.close()
-
- def save_performance_snapshot(self, competition_id: str, cycle_number: int,
- model_name: str, portfolio_value: float, cash: float,
- pnl: float, return_pct: float, positions_count: int,
- trades_count: int):
- """Save performance snapshot to database"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- # Generate unique ID
- timestamp = int(datetime.now().timestamp() * 1000)
- snapshot_id = f"{competition_id}_{model_name}_{cycle_number}_{timestamp}"
-
- cursor.execute("""
- INSERT INTO alpha_performance_snapshots (
- id, competition_id, cycle_number, model_name, portfolio_value, cash,
- pnl, return_pct, positions_count, trades_count, timestamp
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- """, (
- snapshot_id, competition_id, cycle_number, model_name, portfolio_value, cash,
- pnl, return_pct, positions_count, trades_count, timestamp
- ))
-
- conn.commit()
- conn.close()
-
- def get_decision_logs(self, competition_id: str, limit: int = 50) -> List[Dict]:
- """Get recent decision logs for a competition"""
- conn = self.get_connection()
- cursor = conn.cursor()
-
- cursor.execute("""
- SELECT * FROM alpha_decision_logs
- WHERE competition_id = ?
- ORDER BY timestamp DESC
- LIMIT ?
- """, (competition_id, limit))
-
- results = [dict(row) for row in cursor.fetchall()]
- conn.close()
-
- return results
-
-
-# Thread-safe singleton implementation
-import threading
-
-_db_manager = None
-_db_manager_lock = threading.Lock()
-
-def get_db_manager() -> DatabaseManager:
- """
- Get singleton database manager instance (thread-safe).
-
- Uses double-checked locking pattern to ensure thread safety
- while minimizing lock contention after initialization.
- """
- global _db_manager
-
- # First check without lock (fast path for already-initialized case)
- if _db_manager is not None:
- return _db_manager
-
- # Acquire lock for initialization
- with _db_manager_lock:
- # Double-check after acquiring lock (another thread may have initialized)
- if _db_manager is None:
- _db_manager = DatabaseManager()
-
- return _db_manager
-
-
-def reset_db_manager() -> None:
- """
- Reset the singleton instance (useful for testing).
- Thread-safe reset of the database manager.
- """
- global _db_manager
-
- with _db_manager_lock:
- _db_manager = None
diff --git a/fincept-qt/scripts/agno_trading/db/schema.sql b/fincept-qt/scripts/agno_trading/db/schema.sql
deleted file mode 100644
index 517da9dae..000000000
--- a/fincept-qt/scripts/agno_trading/db/schema.sql
+++ /dev/null
@@ -1,157 +0,0 @@
--- Agno Trading Database Schema
--- Agent Performance Tracking & Trade History
-
--- Agent Trades Table
-CREATE TABLE IF NOT EXISTS agent_trades (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- agent_id TEXT NOT NULL,
- model TEXT NOT NULL,
- symbol TEXT NOT NULL,
- side TEXT NOT NULL, -- 'buy' or 'sell'
- order_type TEXT NOT NULL, -- 'market', 'limit', 'stop'
- quantity REAL NOT NULL,
- entry_price REAL NOT NULL,
- exit_price REAL,
- stop_loss REAL,
- take_profit REAL,
- pnl REAL DEFAULT 0,
- pnl_percent REAL DEFAULT 0,
- status TEXT DEFAULT 'open', -- 'open', 'closed', 'cancelled'
- entry_timestamp INTEGER NOT NULL,
- exit_timestamp INTEGER,
- reasoning TEXT,
- metadata TEXT, -- JSON: strategy, signals, indicators
- execution_time_ms INTEGER,
- is_paper_trade BOOLEAN DEFAULT 1,
- created_at INTEGER DEFAULT (strftime('%s', 'now'))
-);
-
--- Agent Performance Metrics Table
-CREATE TABLE IF NOT EXISTS agent_performance (
- agent_id TEXT PRIMARY KEY,
- model TEXT NOT NULL,
- total_trades INTEGER DEFAULT 0,
- winning_trades INTEGER DEFAULT 0,
- losing_trades INTEGER DEFAULT 0,
- total_pnl REAL DEFAULT 0,
- daily_pnl REAL DEFAULT 0,
- weekly_pnl REAL DEFAULT 0,
- monthly_pnl REAL DEFAULT 0,
- win_rate REAL DEFAULT 0,
- sharpe_ratio REAL DEFAULT 0,
- sortino_ratio REAL DEFAULT 0,
- max_drawdown REAL DEFAULT 0,
- current_drawdown REAL DEFAULT 0,
- avg_win REAL DEFAULT 0,
- avg_loss REAL DEFAULT 0,
- profit_factor REAL DEFAULT 0,
- largest_win REAL DEFAULT 0,
- largest_loss REAL DEFAULT 0,
- consecutive_wins INTEGER DEFAULT 0,
- consecutive_losses INTEGER DEFAULT 0,
- max_consecutive_wins INTEGER DEFAULT 0,
- max_consecutive_losses INTEGER DEFAULT 0,
- total_volume REAL DEFAULT 0,
- positions INTEGER DEFAULT 0,
- last_trade_timestamp INTEGER,
- last_updated INTEGER DEFAULT (strftime('%s', 'now'))
-);
-
--- Agent Decisions Log (for real-time feed)
-CREATE TABLE IF NOT EXISTS agent_decisions (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- agent_id TEXT NOT NULL,
- model TEXT NOT NULL,
- decision_type TEXT NOT NULL, -- 'analysis', 'signal', 'trade', 'risk'
- symbol TEXT,
- decision TEXT NOT NULL,
- reasoning TEXT,
- confidence REAL,
- timestamp INTEGER NOT NULL,
- execution_time_ms INTEGER
-);
-
--- Competitions Table
-CREATE TABLE IF NOT EXISTS competitions (
- id TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- symbol TEXT NOT NULL,
- task_type TEXT NOT NULL,
- participating_models TEXT NOT NULL, -- JSON array
- status TEXT DEFAULT 'active', -- 'active', 'completed', 'cancelled'
- start_timestamp INTEGER NOT NULL,
- end_timestamp INTEGER,
- consensus_action TEXT,
- consensus_confidence REAL,
- results TEXT, -- JSON
- created_at INTEGER DEFAULT (strftime('%s', 'now'))
-);
-
--- Agent Evolution History
-CREATE TABLE IF NOT EXISTS agent_evolution (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- agent_id TEXT NOT NULL,
- model TEXT NOT NULL,
- evolution_trigger TEXT NOT NULL, -- 'performance', 'loss_streak', 'win_streak', 'manual'
- old_instructions TEXT,
- new_instructions TEXT NOT NULL,
- metrics_before TEXT, -- JSON
- metrics_after TEXT, -- JSON
- timestamp INTEGER NOT NULL,
- notes TEXT
-);
-
--- Debate Sessions Table
-CREATE TABLE IF NOT EXISTS debate_sessions (
- id TEXT PRIMARY KEY,
- symbol TEXT NOT NULL,
- bull_model TEXT NOT NULL,
- bear_model TEXT NOT NULL,
- analyst_model TEXT NOT NULL,
- bull_argument TEXT,
- bear_argument TEXT,
- analyst_decision TEXT,
- final_action TEXT,
- confidence REAL,
- timestamp INTEGER NOT NULL,
- execution_time_ms INTEGER
-);
-
--- Alpha Arena Competition Configurations
-CREATE TABLE IF NOT EXISTS competition_configs (
- competition_id TEXT PRIMARY KEY,
- name TEXT NOT NULL,
- models_json TEXT NOT NULL,
- symbol TEXT NOT NULL,
- mode TEXT NOT NULL,
- api_keys_json TEXT,
- status TEXT DEFAULT 'created',
- created_at INTEGER NOT NULL
-);
-
--- Alpha Arena Model States
-CREATE TABLE IF NOT EXISTS alpha_model_states (
- id TEXT PRIMARY KEY,
- competition_id TEXT NOT NULL,
- model_name TEXT NOT NULL,
- provider TEXT,
- model_id TEXT,
- capital REAL NOT NULL,
- positions_json TEXT,
- trades_count INTEGER DEFAULT 0,
- total_pnl REAL DEFAULT 0,
- portfolio_value REAL NOT NULL,
- created_at INTEGER DEFAULT (strftime('%s', 'now')),
- updated_at INTEGER DEFAULT (strftime('%s', 'now'))
-);
-
--- Indexes for Performance
-CREATE INDEX IF NOT EXISTS idx_agent_trades_agent ON agent_trades(agent_id);
-CREATE INDEX IF NOT EXISTS idx_agent_trades_symbol ON agent_trades(symbol);
-CREATE INDEX IF NOT EXISTS idx_agent_trades_status ON agent_trades(status);
-CREATE INDEX IF NOT EXISTS idx_agent_trades_timestamp ON agent_trades(entry_timestamp DESC);
-CREATE INDEX IF NOT EXISTS idx_agent_decisions_agent ON agent_decisions(agent_id);
-CREATE INDEX IF NOT EXISTS idx_agent_decisions_timestamp ON agent_decisions(timestamp DESC);
-CREATE INDEX IF NOT EXISTS idx_competitions_status ON competitions(status);
-CREATE INDEX IF NOT EXISTS idx_competition_configs_status ON competition_configs(status);
-CREATE INDEX IF NOT EXISTS idx_alpha_model_states_comp ON alpha_model_states(competition_id);
diff --git a/fincept-qt/scripts/agno_trading/framework/__init__.py b/fincept-qt/scripts/agno_trading/framework/__init__.py
deleted file mode 100644
index 289af9076..000000000
--- a/fincept-qt/scripts/agno_trading/framework/__init__.py
+++ /dev/null
@@ -1,71 +0,0 @@
-"""
-Alpha Arena Trading Framework
-
-A modular, extensible trading framework for multi-LLM competitions.
-Based on ValueCell architecture with clean separation of concerns.
-"""
-
-from .types import (
- TradeInstruction,
- TxResult,
- PortfolioView,
- PositionSnapshot,
- ComposeContext,
- ComposeResult,
- DecisionCycleResult,
- FeaturesResult,
- FeatureVector,
- Candle,
- MarketSnapshot,
- TradeDigest,
- TradeDigestEntry,
- Side,
- TxStatus,
- TradingMode,
-)
-
-from .base_composer import BaseComposer
-from .base_execution import BaseExecutionGateway
-from .base_portfolio import BasePortfolioService
-from .base_features import BaseFeaturesPipeline
-from .portfolio_service import InMemoryPortfolioService
-from .paper_execution import PaperExecutionGateway
-from .market_data_source import CCXTMarketDataSource
-from .features_pipeline import TechnicalFeaturesPipeline
-from .llm_composer import LLMComposer, ModelConfig
-from .decision_coordinator import DecisionCoordinator
-from .competition_runtime import CompetitionRuntime
-
-__all__ = [
- # Types
- "TradeInstruction",
- "TxResult",
- "PortfolioView",
- "PositionSnapshot",
- "ComposeContext",
- "ComposeResult",
- "DecisionCycleResult",
- "FeaturesResult",
- "FeatureVector",
- "Candle",
- "MarketSnapshot",
- "TradeDigest",
- "TradeDigestEntry",
- "Side",
- "TxStatus",
- "TradingMode",
- # Base Classes
- "BaseComposer",
- "BaseExecutionGateway",
- "BasePortfolioService",
- "BaseFeaturesPipeline",
- # Implementations
- "InMemoryPortfolioService",
- "PaperExecutionGateway",
- "CCXTMarketDataSource",
- "TechnicalFeaturesPipeline",
- "LLMComposer",
- "ModelConfig",
- "DecisionCoordinator",
- "CompetitionRuntime",
-]
diff --git a/fincept-qt/scripts/agno_trading/framework/base_composer.py b/fincept-qt/scripts/agno_trading/framework/base_composer.py
deleted file mode 100644
index 8a5b41fc7..000000000
--- a/fincept-qt/scripts/agno_trading/framework/base_composer.py
+++ /dev/null
@@ -1,40 +0,0 @@
-"""
-Base interface for decision composers.
-"""
-
-from abc import ABC, abstractmethod
-from .types import ComposeContext, ComposeResult
-
-
-class BaseComposer(ABC):
- """
- Base class for all composers.
-
- A composer takes market context and generates trade instructions.
- Different implementations can use:
- - LLM-based decisions (GPT-4, Claude, etc.)
- - Rule-based strategies (grid trading, momentum, mean reversion)
- - ML models (LSTM, transformers, reinforcement learning)
- """
-
- @abstractmethod
- async def compose(self, context: ComposeContext) -> ComposeResult:
- """
- Generate trading instructions based on context.
-
- Args:
- context: Market data, portfolio state, and historical performance
-
- Returns:
- ComposeResult with trade instructions
- """
- pass
-
- async def validate_instructions(self, result: ComposeResult) -> ComposeResult:
- """
- Optional validation hook for generated instructions.
- Can apply guardrails, risk limits, etc.
-
- Override in subclasses if needed.
- """
- return result
diff --git a/fincept-qt/scripts/agno_trading/framework/base_execution.py b/fincept-qt/scripts/agno_trading/framework/base_execution.py
deleted file mode 100644
index 166e78d5e..000000000
--- a/fincept-qt/scripts/agno_trading/framework/base_execution.py
+++ /dev/null
@@ -1,51 +0,0 @@
-"""
-Base interface for execution gateways.
-"""
-
-from abc import ABC, abstractmethod
-from typing import List
-from .types import TradeInstruction, TxResult, FeatureVector
-
-
-class BaseExecutionGateway(ABC):
- """
- Base class for all execution gateways.
-
- An execution gateway takes trade instructions and executes them,
- either in paper trading mode or against a live exchange.
- """
-
- @abstractmethod
- async def execute(
- self,
- instructions: List[TradeInstruction],
- market_features: List[FeatureVector]
- ) -> List[TxResult]:
- """
- Execute trade instructions.
-
- Args:
- instructions: List of trades to execute
- market_features: Current market data (for paper trading price reference)
-
- Returns:
- List of transaction results
- """
- pass
-
- @abstractmethod
- async def test_connection(self) -> bool:
- """
- Test connection to execution venue.
-
- Returns:
- True if connected, False otherwise
- """
- pass
-
- @abstractmethod
- async def close(self) -> None:
- """
- Close connection and clean up resources.
- """
- pass
diff --git a/fincept-qt/scripts/agno_trading/framework/base_features.py b/fincept-qt/scripts/agno_trading/framework/base_features.py
deleted file mode 100644
index 56e646d84..000000000
--- a/fincept-qt/scripts/agno_trading/framework/base_features.py
+++ /dev/null
@@ -1,34 +0,0 @@
-"""
-Base interface for features pipelines.
-"""
-
-from abc import ABC, abstractmethod
-from .types import FeaturesResult
-
-
-class BaseFeaturesPipeline(ABC):
- """
- Base class for feature extraction pipelines.
-
- A features pipeline fetches market data and computes technical indicators.
- """
-
- @abstractmethod
- async def build(self) -> FeaturesResult:
- """
- Build feature vectors from market data.
-
- Returns:
- FeaturesResult with computed features
- """
- pass
-
- @abstractmethod
- async def update_symbols(self, symbols: list[str]) -> None:
- """
- Update the list of symbols to track.
-
- Args:
- symbols: List of trading symbols
- """
- pass
diff --git a/fincept-qt/scripts/agno_trading/framework/base_portfolio.py b/fincept-qt/scripts/agno_trading/framework/base_portfolio.py
deleted file mode 100644
index d078a651a..000000000
--- a/fincept-qt/scripts/agno_trading/framework/base_portfolio.py
+++ /dev/null
@@ -1,55 +0,0 @@
-"""
-Base interface for portfolio services.
-"""
-
-from abc import ABC, abstractmethod
-from typing import Dict
-from .types import TxResult, PortfolioView
-
-
-class BasePortfolioService(ABC):
- """
- Base class for portfolio management.
-
- Tracks cash, positions, realized/unrealized P&L.
- """
-
- @abstractmethod
- async def apply_trade(self, tx: TxResult) -> None:
- """
- Apply a completed trade to the portfolio.
-
- Args:
- tx: Transaction result from execution gateway
- """
- pass
-
- @abstractmethod
- async def mark_to_market(self, prices: Dict[str, float]) -> None:
- """
- Update unrealized P&L based on current market prices.
-
- Args:
- prices: Dict of symbol -> current price
- """
- pass
-
- @abstractmethod
- async def get_portfolio_view(self) -> PortfolioView:
- """
- Get current portfolio snapshot.
-
- Returns:
- PortfolioView with cash, positions, and P&L
- """
- pass
-
- @abstractmethod
- async def reset(self, initial_capital: float) -> None:
- """
- Reset portfolio to initial state.
-
- Args:
- initial_capital: Starting cash balance
- """
- pass
diff --git a/fincept-qt/scripts/agno_trading/framework/competition_runtime.py b/fincept-qt/scripts/agno_trading/framework/competition_runtime.py
deleted file mode 100644
index 78abf9fc1..000000000
--- a/fincept-qt/scripts/agno_trading/framework/competition_runtime.py
+++ /dev/null
@@ -1,178 +0,0 @@
-"""
-Competition runtime for managing Alpha Arena competitions.
-"""
-
-import asyncio
-from typing import List, Dict, Optional
-from .decision_coordinator import DecisionCoordinator
-from .llm_composer import LLMComposer, ModelConfig
-from .paper_execution import PaperExecutionGateway
-from .portfolio_service import InMemoryPortfolioService
-from .market_data_source import CCXTMarketDataSource
-from .features_pipeline import TechnicalFeaturesPipeline
-from .types import DecisionCycleResult
-
-
-class CompetitionRuntime:
- """
- Runtime for managing a multi-model trading competition.
-
- Responsibilities:
- - Initialize all components (composer, execution, portfolios, etc.)
- - Run trading cycles at specified intervals
- - Persist state to database
- - Stream updates to UI
- """
-
- def __init__(
- self,
- competition_id: str,
- models: List[ModelConfig],
- symbols: List[str],
- initial_capital: float = 10000.0,
- exchange_id: str = "kraken",
- custom_prompt: Optional[str] = None
- ):
- """
- Initialize competition runtime.
-
- Args:
- competition_id: Unique competition ID
- models: List of competing LLM models
- symbols: List of trading symbols
- initial_capital: Starting capital per model
- exchange_id: Exchange for market data
- custom_prompt: Optional custom trading instructions
- """
- self.competition_id = competition_id
- self.models = models
- self.symbols = symbols
- self.initial_capital = initial_capital
- self.is_running = False
-
- # Create components
- self.market_data_source = CCXTMarketDataSource(
- exchange_id=exchange_id,
- testnet=False,
- rate_limit=True
- )
-
- self.features_pipeline = TechnicalFeaturesPipeline(
- market_data_source=self.market_data_source,
- symbols=symbols,
- interval="1h", # 1-hour candles for better technical analysis
- lookback=168 # 168 hours = 7 days of hourly data
- )
-
- self.execution_gateway = PaperExecutionGateway(
- fee_bps=10.0,
- default_slippage_bps=5.0
- )
-
- # Create portfolio for each model
- self.portfolios: Dict[str, InMemoryPortfolioService] = {}
- model_names = [model.name for model in models]
-
- for model_name in model_names:
- self.portfolios[model_name] = InMemoryPortfolioService(
- initial_capital=initial_capital
- )
-
- # Create composer
- self.composer = LLMComposer(
- models=models,
- custom_prompt=custom_prompt,
- max_positions=3,
- max_leverage=10.0
- )
-
- # Create coordinator
- self.coordinator = DecisionCoordinator(
- strategy_id=competition_id,
- composer=self.composer,
- execution_gateway=self.execution_gateway,
- features_pipeline=self.features_pipeline,
- portfolios=self.portfolios,
- model_names=model_names
- )
-
- async def run_cycle(self) -> DecisionCycleResult:
- """
- Run a single trading cycle.
-
- Returns:
- DecisionCycleResult with all decisions and executions
- """
- result = await self.coordinator.run_once()
- return result
-
- async def run_continuous(self, cycle_interval_seconds: int = 900):
- """
- Run continuous trading cycles.
-
- Args:
- cycle_interval_seconds: Seconds between cycles (default: 900 = 15 minutes)
- """
- self.is_running = True
-
- while self.is_running:
- try:
- # Run cycle
- result = await self.run_cycle()
-
- print(f"Cycle {result.cycle_number} complete", flush=True)
-
- # Wait for next cycle
- await asyncio.sleep(cycle_interval_seconds)
-
- except Exception as e:
- print(f"Error in trading cycle: {e}", flush=True)
- # Continue despite errors
- await asyncio.sleep(cycle_interval_seconds)
-
- def stop(self):
- """Stop the competition."""
- self.is_running = False
-
- async def get_leaderboard(self) -> List[Dict]:
- """
- Get current leaderboard.
-
- Returns:
- List of model rankings
- """
- leaderboard = []
-
- for model_name, portfolio in self.portfolios.items():
- view = await portfolio.get_portfolio_view()
- leaderboard.append({
- "model_name": model_name,
- "portfolio_value": view.total_value,
- "total_pnl": view.total_realized_pnl + view.total_unrealized_pnl,
- "return_pct": ((view.total_value - self.initial_capital) / self.initial_capital) * 100.0,
- "trades_count": view.trades_count,
- "cash": view.cash,
- "positions_count": len(view.positions)
- })
-
- # Sort by portfolio value
- leaderboard.sort(key=lambda x: x["portfolio_value"], reverse=True)
-
- # Add rank
- for i, entry in enumerate(leaderboard):
- entry["rank"] = i + 1
-
- return leaderboard
-
- async def get_portfolio_snapshot(self, model_name: str) -> Optional[Dict]:
- """Get portfolio snapshot for a specific model."""
- if model_name not in self.portfolios:
- return None
-
- view = await self.portfolios[model_name].get_portfolio_view()
- return view.to_dict()
-
- async def close(self):
- """Clean up resources."""
- await self.market_data_source.close()
- await self.execution_gateway.close()
diff --git a/fincept-qt/scripts/agno_trading/framework/decision_coordinator.py b/fincept-qt/scripts/agno_trading/framework/decision_coordinator.py
deleted file mode 100644
index 2eaf45282..000000000
--- a/fincept-qt/scripts/agno_trading/framework/decision_coordinator.py
+++ /dev/null
@@ -1,168 +0,0 @@
-"""
-Decision coordinator for orchestrating trading cycles.
-"""
-
-import time
-import uuid
-from typing import List, Dict
-from .base_composer import BaseComposer
-from .base_execution import BaseExecutionGateway
-from .base_portfolio import BasePortfolioService
-from .base_features import BaseFeaturesPipeline
-from .types import (
- ComposeContext,
- DecisionCycleResult,
- PortfolioView,
- TradeDigest,
- ComposeResult
-)
-
-
-class DecisionCoordinator:
- """
- Coordinates a single trading cycle.
-
- Flow:
- 1. Build features (market data + technical indicators)
- 2. Get portfolio state
- 3. Build performance digest
- 4. LLM decision via composer
- 5. Execute trades
- 6. Update portfolio
- 7. Return results
- """
-
- def __init__(
- self,
- strategy_id: str,
- composer: BaseComposer,
- execution_gateway: BaseExecutionGateway,
- features_pipeline: BaseFeaturesPipeline,
- portfolios: Dict[str, BasePortfolioService], # One per model
- model_names: List[str]
- ):
- """
- Initialize decision coordinator.
-
- Args:
- strategy_id: Competition/strategy ID
- composer: Decision composer (LLM-based)
- execution_gateway: Execution gateway (paper or live)
- features_pipeline: Features pipeline
- portfolios: Dict of model_name -> portfolio service
- model_names: List of competing model names
- """
- self.strategy_id = strategy_id
- self.composer = composer
- self.execution_gateway = execution_gateway
- self.features_pipeline = features_pipeline
- self.portfolios = portfolios
- self.model_names = model_names
- self.cycle_count = 0
-
- async def run_once(self) -> DecisionCycleResult:
- """
- Execute one trading cycle for all models.
-
- Returns:
- DecisionCycleResult with all decisions and executions
- """
- self.cycle_count += 1
- timestamp_ms = int(time.time() * 1000)
- cycle_id = f"cycle_{uuid.uuid4().hex[:8]}"
-
- # 1. Build features
- features_result = await self.features_pipeline.build()
-
- # 2. Get all decisions from competing models
- compose_results: List[ComposeResult] = []
- all_instructions = []
-
- for model_name in self.model_names:
- # Get portfolio for this model
- portfolio = self.portfolios[model_name]
- portfolio_view = await portfolio.get_portfolio_view()
-
- # Build digest (simplified - can be enhanced)
- digest = TradeDigest(
- total_trades=portfolio_view.trades_count,
- total_realized_pnl=portfolio_view.total_realized_pnl,
- overall_win_rate=0.0, # TODO: Calculate from trade history
- sharpe_ratio=0.0, # TODO: Calculate
- max_drawdown=0.0, # TODO: Calculate
- by_instrument={}
- )
-
- # Create context
- context = ComposeContext(
- ts=timestamp_ms,
- compose_id=f"{cycle_id}_{model_name}",
- strategy_id=self.strategy_id,
- model_name=model_name,
- features=features_result.features,
- portfolio=portfolio_view,
- digest=digest
- )
-
- # Get decision from LLM
- compose_result = await self.composer.compose(context)
- compose_results.append(compose_result)
-
- # Collect instructions
- all_instructions.extend(compose_result.instructions)
-
- # 3. Execute all trades
- tx_results = await self.execution_gateway.execute(
- all_instructions,
- features_result.features
- )
-
- # 4. Apply trades to respective portfolios
- for tx in tx_results:
- model_name = tx.instruction.model_name
- if model_name and model_name in self.portfolios:
- await self.portfolios[model_name].apply_trade(tx)
-
- # 5. Mark portfolios to market
- current_prices = {
- feat.symbol: feat.close
- for feat in features_result.features
- }
-
- for portfolio in self.portfolios.values():
- await portfolio.mark_to_market(current_prices)
-
- # 6. Get updated portfolio snapshots
- portfolio_snapshots = {}
- for model_name in self.model_names:
- portfolio_snapshots[model_name] = await self.portfolios[model_name].get_portfolio_view()
-
- # 7. Build leaderboard
- leaderboard = []
- for model_name in self.model_names:
- portfolio_view = portfolio_snapshots[model_name]
- leaderboard.append({
- "model_name": model_name,
- "portfolio_value": portfolio_view.total_value,
- "total_pnl": portfolio_view.total_realized_pnl + portfolio_view.total_unrealized_pnl,
- "trades_count": portfolio_view.trades_count,
- "cash": portfolio_view.cash
- })
-
- # Sort by portfolio value (descending)
- leaderboard.sort(key=lambda x: x["portfolio_value"], reverse=True)
-
- # Add rank
- for i, entry in enumerate(leaderboard):
- entry["rank"] = i + 1
-
- # 8. Return complete cycle result
- return DecisionCycleResult(
- cycle_id=cycle_id,
- cycle_number=self.cycle_count,
- timestamp_ms=timestamp_ms,
- compose_results=compose_results,
- tx_results=tx_results,
- portfolio_snapshots=portfolio_snapshots,
- leaderboard=leaderboard
- )
diff --git a/fincept-qt/scripts/agno_trading/framework/features_pipeline.py b/fincept-qt/scripts/agno_trading/framework/features_pipeline.py
deleted file mode 100644
index 380e463f6..000000000
--- a/fincept-qt/scripts/agno_trading/framework/features_pipeline.py
+++ /dev/null
@@ -1,268 +0,0 @@
-"""
-Features pipeline for computing technical indicators.
-"""
-
-import time
-import numpy as np
-from typing import List, Dict, Optional
-from .base_features import BaseFeaturesPipeline
-from .market_data_source import CCXTMarketDataSource
-from .types import FeaturesResult, FeatureVector, Candle, MarketSnapshot
-
-
-class TechnicalFeaturesPipeline(BaseFeaturesPipeline):
- """
- Features pipeline that computes technical indicators.
-
- Indicators:
- - RSI (Relative Strength Index)
- - MACD (Moving Average Convergence Divergence)
- - Bollinger Bands
- - ATR (Average True Range)
- - Volatility
- """
-
- def __init__(
- self,
- market_data_source: CCXTMarketDataSource,
- symbols: List[str],
- interval: str = "1m",
- lookback: int = 100
- ):
- """
- Initialize features pipeline.
-
- Args:
- market_data_source: Market data source
- symbols: List of symbols to track
- interval: Candle interval
- lookback: Number of candles to fetch
- """
- self.market_data_source = market_data_source
- self.symbols = symbols
- self.interval = interval
- self.lookback = lookback
-
- async def build(self) -> FeaturesResult:
- """
- Build feature vectors with technical indicators.
- """
- timestamp_ms = int(time.time() * 1000)
-
- # Fetch candles
- candles_map = await self.market_data_source.get_recent_candles(
- self.symbols,
- self.interval,
- self.lookback
- )
-
- # Fetch market snapshots
- snapshots = await self.market_data_source.get_market_snapshot(self.symbols)
- snapshot_map = {snap.symbol: snap for snap in snapshots}
-
- # Compute features for each symbol
- features = []
-
- for symbol in self.symbols:
- candles = candles_map.get(symbol, [])
- snapshot = snapshot_map.get(symbol)
-
- if not candles or not snapshot:
- continue
-
- # Latest candle
- latest = candles[-1]
-
- # Compute technical indicators
- indicators = self._compute_indicators(candles)
-
- # Calculate spread in basis points
- spread_bps = 0.0
- if snapshot.ask > 0 and snapshot.bid > 0:
- spread_bps = ((snapshot.ask - snapshot.bid) / snapshot.bid) * 10000.0
-
- features.append(FeatureVector(
- symbol=symbol,
- timestamp_ms=timestamp_ms,
- close=latest.close,
- open=latest.open,
- high=latest.high,
- low=latest.low,
- volume=latest.volume,
- bid=snapshot.bid,
- ask=snapshot.ask,
- spread_bps=spread_bps,
- rsi_14=indicators.get('rsi_14'),
- macd=indicators.get('macd'),
- macd_signal=indicators.get('macd_signal'),
- macd_histogram=indicators.get('macd_histogram'),
- bb_upper=indicators.get('bb_upper'),
- bb_middle=indicators.get('bb_middle'),
- bb_lower=indicators.get('bb_lower'),
- atr_14=indicators.get('atr_14'),
- volatility_24h=indicators.get('volatility_24h'),
- ))
-
- return FeaturesResult(
- features=features,
- timestamp_ms=timestamp_ms,
- lookback_periods=self.lookback
- )
-
- def _compute_indicators(self, candles: List[Candle]) -> Dict[str, Optional[float]]:
- """
- Compute technical indicators from candles.
- """
- if len(candles) < 30:
- return {}
-
- closes = np.array([c.close for c in candles])
- highs = np.array([c.high for c in candles])
- lows = np.array([c.low for c in candles])
-
- indicators = {}
-
- try:
- # RSI (14-period)
- indicators['rsi_14'] = self._compute_rsi(closes, period=14)
-
- # MACD (12, 26, 9)
- macd_data = self._compute_macd(closes, fast=12, slow=26, signal=9)
- indicators.update(macd_data)
-
- # Bollinger Bands (20, 2)
- bb_data = self._compute_bollinger_bands(closes, period=20, std_dev=2.0)
- indicators.update(bb_data)
-
- # ATR (14-period)
- indicators['atr_14'] = self._compute_atr(highs, lows, closes, period=14)
-
- # Volatility (rolling standard deviation)
- indicators['volatility_24h'] = float(np.std(closes[-24:]) if len(closes) >= 24 else 0.0)
-
- except Exception as e:
- print(f"Error computing indicators: {e}", flush=True)
-
- return indicators
-
- def _compute_rsi(self, prices: np.ndarray, period: int = 14) -> Optional[float]:
- """Compute RSI (Relative Strength Index)."""
- if len(prices) < period + 1:
- return None
-
- deltas = np.diff(prices)
- gains = np.where(deltas > 0, deltas, 0)
- losses = np.where(deltas < 0, -deltas, 0)
-
- avg_gain = np.mean(gains[-period:])
- avg_loss = np.mean(losses[-period:])
-
- if avg_loss == 0:
- return 100.0
-
- rs = avg_gain / avg_loss
- rsi = 100.0 - (100.0 / (1.0 + rs))
-
- return float(rsi)
-
- def _compute_macd(
- self,
- prices: np.ndarray,
- fast: int = 12,
- slow: int = 26,
- signal: int = 9
- ) -> Dict[str, Optional[float]]:
- """Compute MACD (Moving Average Convergence Divergence)."""
- if len(prices) < slow + signal:
- return {
- 'macd': None,
- 'macd_signal': None,
- 'macd_histogram': None
- }
-
- # Exponential moving averages
- ema_fast = self._ema(prices, fast)
- ema_slow = self._ema(prices, slow)
-
- macd_line = ema_fast - ema_slow
-
- # Signal line (EMA of MACD)
- macd_values = []
- for i in range(len(prices) - slow + 1):
- macd_values.append(ema_fast - ema_slow)
-
- signal_line = self._ema(np.array(macd_values), signal)
-
- histogram = macd_line - signal_line
-
- return {
- 'macd': float(macd_line),
- 'macd_signal': float(signal_line),
- 'macd_histogram': float(histogram)
- }
-
- def _compute_bollinger_bands(
- self,
- prices: np.ndarray,
- period: int = 20,
- std_dev: float = 2.0
- ) -> Dict[str, Optional[float]]:
- """Compute Bollinger Bands."""
- if len(prices) < period:
- return {
- 'bb_upper': None,
- 'bb_middle': None,
- 'bb_lower': None
- }
-
- recent = prices[-period:]
- middle = float(np.mean(recent))
- std = float(np.std(recent))
-
- upper = middle + (std_dev * std)
- lower = middle - (std_dev * std)
-
- return {
- 'bb_upper': upper,
- 'bb_middle': middle,
- 'bb_lower': lower
- }
-
- def _compute_atr(
- self,
- highs: np.ndarray,
- lows: np.ndarray,
- closes: np.ndarray,
- period: int = 14
- ) -> Optional[float]:
- """Compute ATR (Average True Range)."""
- if len(highs) < period + 1:
- return None
-
- true_ranges = []
- for i in range(1, len(highs)):
- high_low = highs[i] - lows[i]
- high_close = abs(highs[i] - closes[i - 1])
- low_close = abs(lows[i] - closes[i - 1])
- true_range = max(high_low, high_close, low_close)
- true_ranges.append(true_range)
-
- atr = float(np.mean(true_ranges[-period:]))
- return atr
-
- def _ema(self, prices: np.ndarray, period: int) -> float:
- """Calculate Exponential Moving Average."""
- if len(prices) < period:
- return float(np.mean(prices))
-
- multiplier = 2.0 / (period + 1.0)
- ema = float(np.mean(prices[:period]))
-
- for price in prices[period:]:
- ema = (price * multiplier) + (ema * (1.0 - multiplier))
-
- return ema
-
- async def update_symbols(self, symbols: List[str]) -> None:
- """Update the list of symbols to track."""
- self.symbols = symbols
diff --git a/fincept-qt/scripts/agno_trading/framework/llm_composer.py b/fincept-qt/scripts/agno_trading/framework/llm_composer.py
deleted file mode 100644
index 79645bd2c..000000000
--- a/fincept-qt/scripts/agno_trading/framework/llm_composer.py
+++ /dev/null
@@ -1,346 +0,0 @@
-"""
-LLM-based composer for multi-model trading competitions.
-"""
-
-import json
-import asyncio
-import time
-import sys
-from typing import List, Dict, Optional
-from dataclasses import dataclass
-
-from agno.agent import Agent as AgnoAgent
-from agno.models.openai import OpenAIChat
-
-try:
- from agno.models.anthropic import Claude
-except ImportError:
- Claude = None
-
-try:
- from agno.models.google import Gemini
-except ImportError:
- Gemini = None
-
-from .base_composer import BaseComposer
-from .types import ComposeContext, ComposeResult, TradeInstruction, Side
-
-
-@dataclass
-class ModelConfig:
- """Configuration for a single LLM model."""
- name: str
- provider: str # openai, google, anthropic, openrouter, deepseek, groq
- model_id: str
- api_key: str
- temperature: float = 0.7
- max_tokens: int = 1000
- timeout_seconds: int = 30
-
-
-class LLMComposer(BaseComposer):
- """
- LLM-based composer for trading decisions.
-
- Supports multiple LLM providers and models competing simultaneously.
- """
-
- def __init__(
- self,
- models: List[ModelConfig],
- custom_prompt: Optional[str] = None,
- max_positions: int = 3,
- max_leverage: float = 10.0
- ):
- """
- Initialize LLM composer.
-
- Args:
- models: List of model configurations
- custom_prompt: Optional custom trading instructions
- max_positions: Maximum concurrent positions (guardrail)
- max_leverage: Maximum leverage allowed (guardrail)
- """
- self.models = models
- self.custom_prompt = custom_prompt
- self.max_positions = max_positions
- self.max_leverage = max_leverage
- self._agents: Dict[str, AgnoAgent] = {}
-
- def _create_agent(self, model_config: ModelConfig) -> AgnoAgent:
- """Create Agno agent for a model."""
-
- # Create model based on provider
- if model_config.provider == "openai":
- # o1/o4 models use max_completion_tokens and don't support custom temperature
- if model_config.model_id.startswith(('o1-', 'o4-')):
- model = OpenAIChat(
- id=model_config.model_id,
- api_key=model_config.api_key,
- max_completion_tokens=model_config.max_tokens
- # temperature not supported for o1/o4 models
- )
- else:
- model = OpenAIChat(
- id=model_config.model_id,
- api_key=model_config.api_key,
- temperature=model_config.temperature,
- max_tokens=model_config.max_tokens
- )
- elif model_config.provider == "google" and Gemini:
- model = Gemini(
- id=model_config.model_id,
- api_key=model_config.api_key
- )
- elif model_config.provider == "anthropic" and Claude:
- model = Claude(
- id=model_config.model_id,
- api_key=model_config.api_key
- )
- else:
- # Use OpenAI-compatible for other providers (OpenRouter, DeepSeek, Groq)
- base_url_map = {
- "openrouter": "https://openrouter.ai/api/v1",
- "deepseek": "https://api.deepseek.com/v1",
- "groq": "https://api.groq.com/openai/v1"
- }
- base_url = base_url_map.get(model_config.provider, "https://api.openai.com/v1")
-
- model = OpenAIChat(
- id=model_config.model_id,
- api_key=model_config.api_key,
- base_url=base_url,
- temperature=model_config.temperature,
- max_tokens=model_config.max_tokens
- )
-
- # Create agent with structured output
- agent = AgnoAgent(
- model=model,
- markdown=False
- )
-
- return agent
-
- def _build_prompt(self, context: ComposeContext) -> str:
- """
- Build trading prompt from context.
- """
- # Portfolio summary
- portfolio_summary = f"""
-PORTFOLIO SUMMARY:
-- Cash: ${context.portfolio.cash:.2f}
-- Total Value: ${context.portfolio.total_value:.2f}
-- Unrealized P&L: ${context.portfolio.total_unrealized_pnl:.2f}
-- Realized P&L: ${context.portfolio.total_realized_pnl:.2f}
-- Trades: {context.portfolio.trades_count}
-"""
-
- # Current positions
- positions_str = ""
- if context.portfolio.positions:
- positions_str = "\nCURRENT POSITIONS:\n"
- for symbol, pos in context.portfolio.positions.items():
- pnl_pct = (pos.unrealized_pnl / (pos.avg_entry_price * abs(pos.quantity))) * 100 if pos.avg_entry_price > 0 else 0
- positions_str += f"- {symbol}: {pos.quantity:.4f} @ ${pos.avg_entry_price:.2f}, Current: ${pos.current_price:.2f}, P&L: ${pos.unrealized_pnl:.2f} ({pnl_pct:+.2f}%)\n"
- else:
- positions_str = "\nNo open positions.\n"
-
- # Market data
- market_data = "\nMARKET DATA:\n"
- for feat in context.features:
- market_data += f"\n{feat.symbol}:\n"
- market_data += f" Price: ${feat.close:.2f} (Bid: ${feat.bid:.2f}, Ask: ${feat.ask:.2f})\n"
- market_data += f" 24h Change: {((feat.close - feat.open) / feat.open * 100) if feat.open > 0 else 0:.2f}%\n"
-
- if feat.rsi_14:
- market_data += f" RSI(14): {feat.rsi_14:.2f}\n"
- if feat.macd:
- market_data += f" MACD: {feat.macd:.4f}, Signal: {feat.macd_signal:.4f}, Histogram: {feat.macd_histogram:.4f}\n"
- if feat.bb_upper:
- market_data += f" Bollinger Bands: Upper ${feat.bb_upper:.2f}, Middle ${feat.bb_middle:.2f}, Lower ${feat.bb_lower:.2f}\n"
- if feat.atr_14:
- market_data += f" ATR(14): ${feat.atr_14:.2f}\n"
-
- # Performance digest
- digest_str = ""
- if context.digest and context.digest.total_trades > 0:
- digest_str = f"""
-PERFORMANCE HISTORY:
-- Total Trades: {context.digest.total_trades}
-- Total Realized P&L: ${context.digest.total_realized_pnl:.2f}
-- Win Rate: {context.digest.overall_win_rate:.1f}%
-- Sharpe Ratio: {context.digest.sharpe_ratio:.2f}
-- Max Drawdown: {context.digest.max_drawdown:.2f}%
-"""
-
- # Custom instructions
- custom_instructions = ""
- if self.custom_prompt:
- custom_instructions = f"\nCUSTOM TRADING INSTRUCTIONS:\n{self.custom_prompt}\n"
-
- # Combine into full prompt
- prompt = f"""You are an expert cryptocurrency trader. Analyze the market data and make a trading decision.
-
-{portfolio_summary}
-{positions_str}
-{market_data}
-{digest_str}
-{custom_instructions}
-
-RULES:
-1. You can BUY, SELL, HOLD, or WAIT for each symbol
-2. Consider technical indicators (RSI, MACD, Bollinger Bands, ATR)
-3. Manage risk - don't over-leverage
-4. Maximum {self.max_positions} positions at once
-5. Maximum {self.max_leverage}x leverage
-6. Provide clear reasoning for your decision
-
-DECISION TYPES:
-- BUY: Enter a long position or add to existing long
-- SELL: Enter a short position or close/reduce long position
-- HOLD: Maintain current positions (use when you have open positions but don't want to trade)
-- WAIT: No action, waiting for better opportunity (use when you have NO positions)
-
-Respond with a JSON object in this exact format:
-{{
- "decision": "BUY" or "SELL" or "HOLD" or "WAIT",
- "symbol": "BTC/USD",
- "quantity": 0.01,
- "leverage": 1.0,
- "confidence": 0.75,
- "reasoning": "Detailed explanation of your decision"
-}}
-
-If you decide to HOLD or WAIT, set quantity to 0.
-"""
-
- return prompt
-
- async def compose(self, context: ComposeContext) -> ComposeResult:
- """
- Generate trading instruction using LLM.
-
- Runs a single model specified in context.model_name.
- """
- model_config = next((m for m in self.models if m.name == context.model_name), None)
-
- if not model_config:
- # Return empty result if model not found
- return ComposeResult(
- instructions=[],
- compose_id=context.compose_id,
- model_name=context.model_name,
- rationale="Model not found",
- decision_type="WAIT"
- )
-
- # Get or create agent
- if model_config.name not in self._agents:
- self._agents[model_config.name] = self._create_agent(model_config)
-
- agent = self._agents[model_config.name]
-
- # Build prompt
- prompt = self._build_prompt(context)
-
- try:
- print(f"[LLMComposer] Calling {model_config.name} for trading decision...", flush=True, file=sys.stderr)
-
- # Call LLM (agent.run() is synchronous in Agno SDK)
- # Run it in executor to avoid blocking the event loop
- loop = asyncio.get_event_loop()
- response = await asyncio.wait_for(
- loop.run_in_executor(None, lambda: agent.run(prompt)),
- timeout=model_config.timeout_seconds
- )
-
- # Parse JSON response
- response_text = response.content if hasattr(response, 'content') else str(response)
- print(f"[LLMComposer] {model_config.name} response: {response_text[:200]}...", flush=True, file=sys.stderr)
-
- # Extract JSON from response
- decision_data = self._extract_json(response_text)
- print(f"[LLMComposer] {model_config.name} decision: {decision_data}", flush=True, file=sys.stderr)
-
- # Convert to TradeInstruction
- instructions = []
- decision_type = 'WAIT' # Default
-
- if decision_data:
- decision = decision_data.get('decision', 'WAIT').upper()
- decision_type = decision
- symbol = decision_data.get('symbol', context.features[0].symbol if context.features else 'BTC/USD')
- quantity = float(decision_data.get('quantity', 0))
- leverage = min(float(decision_data.get('leverage', 1.0)), self.max_leverage)
- confidence = float(decision_data.get('confidence', 0.5))
- reasoning = decision_data.get('reasoning', '')
-
- # Only create trade instructions for BUY/SELL with quantity > 0
- if decision in ['BUY', 'SELL'] and quantity > 0:
- instructions.append(TradeInstruction(
- symbol=symbol,
- side=Side.BUY if decision == 'BUY' else Side.SELL,
- quantity=quantity,
- leverage=leverage,
- max_slippage_bps=50,
- model_name=model_config.name,
- reasoning=reasoning,
- confidence=confidence
- ))
-
- return ComposeResult(
- instructions=instructions,
- compose_id=context.compose_id,
- model_name=model_config.name,
- rationale=decision_data.get('reasoning', '') if decision_data else '',
- decision_type=decision_type # Store the decision type (BUY/SELL/HOLD/WAIT)
- )
-
- except asyncio.TimeoutError:
- print(f"[LLMComposer] TIMEOUT for model {model_config.name} after {model_config.timeout_seconds}s", flush=True, file=sys.stderr)
- return ComposeResult(
- instructions=[],
- compose_id=context.compose_id,
- model_name=model_config.name,
- rationale="Model timed out",
- decision_type="WAIT"
- )
- except Exception as e:
- print(f"[LLMComposer] ERROR in {model_config.name}: {type(e).__name__}: {e}", flush=True, file=sys.stderr)
- import traceback
- traceback.print_exc(file=sys.stderr)
- return ComposeResult(
- instructions=[],
- compose_id=context.compose_id,
- model_name=model_config.name,
- rationale=f"Error: {str(e)}",
- decision_type="WAIT"
- )
-
- def _extract_json(self, text: str) -> Optional[Dict]:
- """Extract JSON object from text response."""
- try:
- # Try direct JSON parse
- return json.loads(text)
- except:
- pass
-
- # Try to find JSON block in markdown
- import re
- json_match = re.search(r'```json\s*(\{.*?\})\s*```', text, re.DOTALL)
- if json_match:
- try:
- return json.loads(json_match.group(1))
- except:
- pass
-
- # Try to find any JSON object
- json_match = re.search(r'\{.*?\}', text, re.DOTALL)
- if json_match:
- try:
- return json.loads(json_match.group(0))
- except:
- pass
-
- return None
diff --git a/fincept-qt/scripts/agno_trading/framework/market_data_source.py b/fincept-qt/scripts/agno_trading/framework/market_data_source.py
deleted file mode 100644
index bc3b74c95..000000000
--- a/fincept-qt/scripts/agno_trading/framework/market_data_source.py
+++ /dev/null
@@ -1,193 +0,0 @@
-"""
-Market data source using CCXT for fetching candles and snapshots.
-"""
-
-import ccxt
-import time
-import asyncio
-from typing import List, Dict, Optional
-from datetime import datetime
-from .types import Candle, MarketSnapshot
-
-
-class CCXTMarketDataSource:
- """
- Market data source using CCXT library.
-
- Supports multiple exchanges (Binance, Kraken, Coinbase, etc.)
- """
-
- def __init__(
- self,
- exchange_id: str = "kraken",
- testnet: bool = False,
- rate_limit: bool = True
- ):
- """
- Initialize market data source.
-
- Args:
- exchange_id: Exchange name (binance, kraken, coinbase, etc.)
- testnet: Use testnet/sandbox (if available)
- rate_limit: Enable rate limiting
- """
- self.exchange_id = exchange_id
- self.testnet = testnet
- self.rate_limit = rate_limit
- self._exchange: Optional[ccxt.Exchange] = None
- self._last_request_time = 0.0
- self._min_request_interval = 1.0 # 1 second between requests
-
- def _get_exchange(self) -> ccxt.Exchange:
- """Get or create exchange instance."""
- if self._exchange is None:
- exchange_class = getattr(ccxt, self.exchange_id)
- config = {
- 'enableRateLimit': self.rate_limit,
- 'timeout': 10000,
- }
-
- if self.testnet:
- config['sandbox'] = True
-
- self._exchange = exchange_class(config)
-
- return self._exchange
-
- async def _rate_limit_delay(self) -> None:
- """Enforce rate limiting."""
- if not self.rate_limit:
- return
-
- now = time.time()
- time_since_last = now - self._last_request_time
-
- if time_since_last < self._min_request_interval:
- await asyncio.sleep(self._min_request_interval - time_since_last)
-
- self._last_request_time = time.time()
-
- async def get_recent_candles(
- self,
- symbols: List[str],
- interval: str = "1m",
- lookback: int = 100
- ) -> Dict[str, List[Candle]]:
- """
- Fetch recent OHLCV candles for multiple symbols.
-
- Args:
- symbols: List of trading pairs (e.g., ["BTC/USD", "ETH/USD"])
- interval: Timeframe (1m, 5m, 15m, 1h, 1d)
- lookback: Number of candles to fetch
-
- Returns:
- Dict mapping symbol -> list of candles
- """
- exchange = self._get_exchange()
- result = {}
-
- for symbol in symbols:
- try:
- await self._rate_limit_delay()
-
- # Fetch OHLCV data
- ohlcv = exchange.fetch_ohlcv(
- symbol=symbol,
- timeframe=interval,
- limit=lookback
- )
-
- # Convert to Candle objects
- candles = [
- Candle(
- timestamp=int(row[0]),
- open=float(row[1]),
- high=float(row[2]),
- low=float(row[3]),
- close=float(row[4]),
- volume=float(row[5])
- )
- for row in ohlcv
- ]
-
- result[symbol] = candles
-
- except Exception as e:
- print(f"Error fetching candles for {symbol}: {e}", flush=True)
- result[symbol] = []
-
- return result
-
- async def get_market_snapshot(
- self,
- symbols: List[str]
- ) -> List[MarketSnapshot]:
- """
- Get real-time market snapshots for multiple symbols.
-
- Args:
- symbols: List of trading pairs
-
- Returns:
- List of MarketSnapshot objects
- """
- exchange = self._get_exchange()
- snapshots = []
- timestamp_ms = int(time.time() * 1000)
-
- for symbol in symbols:
- try:
- await self._rate_limit_delay()
-
- # Fetch ticker
- ticker = exchange.fetch_ticker(symbol)
-
- # Extract data
- last_price = float(ticker.get('last', 0))
- bid = float(ticker.get('bid', last_price))
- ask = float(ticker.get('ask', last_price))
- volume_24h = float(ticker.get('quoteVolume', 0))
- high_24h = float(ticker.get('high', last_price))
- low_24h = float(ticker.get('low', last_price))
-
- # Calculate 24h change
- open_24h = float(ticker.get('open', last_price))
- change_24h_pct = 0.0
- if open_24h > 0:
- change_24h_pct = ((last_price - open_24h) / open_24h) * 100.0
-
- snapshots.append(MarketSnapshot(
- symbol=symbol,
- last_price=last_price,
- bid=bid,
- ask=ask,
- volume_24h=volume_24h,
- high_24h=high_24h,
- low_24h=low_24h,
- change_24h_pct=change_24h_pct,
- timestamp_ms=timestamp_ms
- ))
-
- except Exception as e:
- print(f"Error fetching snapshot for {symbol}: {e}", flush=True)
- # Create default snapshot on error
- snapshots.append(MarketSnapshot(
- symbol=symbol,
- last_price=0.0,
- bid=0.0,
- ask=0.0,
- volume_24h=0.0,
- high_24h=0.0,
- low_24h=0.0,
- change_24h_pct=0.0,
- timestamp_ms=timestamp_ms
- ))
-
- return snapshots
-
- async def close(self) -> None:
- """Close exchange connection."""
- if self._exchange is not None:
- await self._exchange.close()
- self._exchange = None
diff --git a/fincept-qt/scripts/agno_trading/framework/paper_execution.py b/fincept-qt/scripts/agno_trading/framework/paper_execution.py
deleted file mode 100644
index c08645cb1..000000000
--- a/fincept-qt/scripts/agno_trading/framework/paper_execution.py
+++ /dev/null
@@ -1,106 +0,0 @@
-"""
-Paper trading execution gateway.
-Simulates order fills without connecting to a real exchange.
-"""
-
-import time
-from typing import List
-from .base_execution import BaseExecutionGateway
-from .types import TradeInstruction, TxResult, FeatureVector, TxStatus, Side
-
-
-class PaperExecutionGateway(BaseExecutionGateway):
- """
- Paper trading execution gateway.
-
- Simulates instant fills at market price with configurable slippage and fees.
- """
-
- def __init__(self, fee_bps: float = 10.0, default_slippage_bps: float = 5.0):
- """
- Initialize paper trading gateway.
-
- Args:
- fee_bps: Trading fee in basis points (default 10 bps = 0.1%)
- default_slippage_bps: Default slippage in basis points (default 5 bps = 0.05%)
- """
- self.fee_bps = fee_bps
- self.default_slippage_bps = default_slippage_bps
-
- async def execute(
- self,
- instructions: List[TradeInstruction],
- market_features: List[FeatureVector]
- ) -> List[TxResult]:
- """
- Execute trade instructions in paper trading mode.
-
- Simulates fills at current market price ± slippage.
- """
- results = []
-
- # Build price map from features
- price_map = {
- feat.symbol: feat.close
- for feat in market_features
- }
-
- timestamp_ms = int(time.time() * 1000)
-
- for inst in instructions:
- # Skip HOLD instructions
- if inst.side == Side.HOLD:
- continue
-
- # Get reference price
- if inst.symbol not in price_map:
- # Reject if no price available
- results.append(TxResult(
- instruction=inst,
- status=TxStatus.REJECTED,
- error_message=f"No market price available for {inst.symbol}",
- timestamp_ms=timestamp_ms
- ))
- continue
-
- reference_price = price_map[inst.symbol]
-
- # Apply slippage
- slippage_bps = min(inst.max_slippage_bps, self.default_slippage_bps)
- slippage_factor = slippage_bps / 10000.0
-
- if inst.side == Side.BUY:
- # Buy at ask (higher price)
- fill_price = reference_price * (1 + slippage_factor)
- else: # SELL
- # Sell at bid (lower price)
- fill_price = reference_price * (1 - slippage_factor)
-
- # Calculate notional and fee
- notional = inst.quantity * fill_price
- fee = notional * (self.fee_bps / 10000.0)
-
- # Create successful fill
- results.append(TxResult(
- instruction=inst,
- status=TxStatus.FILLED,
- fill_price=fill_price,
- fill_quantity=inst.quantity,
- fee=fee,
- notional=notional,
- timestamp_ms=timestamp_ms
- ))
-
- return results
-
- async def test_connection(self) -> bool:
- """
- Paper trading always "connected".
- """
- return True
-
- async def close(self) -> None:
- """
- No cleanup needed for paper trading.
- """
- pass
diff --git a/fincept-qt/scripts/agno_trading/framework/portfolio_service.py b/fincept-qt/scripts/agno_trading/framework/portfolio_service.py
deleted file mode 100644
index 6914c292c..000000000
--- a/fincept-qt/scripts/agno_trading/framework/portfolio_service.py
+++ /dev/null
@@ -1,239 +0,0 @@
-"""
-In-memory portfolio service for tracking trading state.
-"""
-
-import time
-from typing import Dict
-from .base_portfolio import BasePortfolioService
-from .types import TxResult, PortfolioView, PositionSnapshot, Side, TxStatus
-
-
-class InMemoryPortfolioService(BasePortfolioService):
- """
- In-memory portfolio service.
-
- Tracks:
- - Cash balance
- - Open positions (long/short)
- - Realized P&L (from closed trades)
- - Unrealized P&L (mark-to-market)
- """
-
- def __init__(self, initial_capital: float = 10000.0):
- """
- Initialize portfolio.
-
- Args:
- initial_capital: Starting cash balance
- """
- self.initial_capital = initial_capital
- self.cash = initial_capital
- self.positions: Dict[str, PositionSnapshot] = {}
- self.total_realized_pnl = 0.0
- self.trades_count = 0
-
- async def apply_trade(self, tx: TxResult) -> None:
- """
- Apply a completed trade to the portfolio.
-
- Logic:
- - BUY: Deduct cash, increase/open long position
- - SELL: Add cash, reduce/close long or open short position
- """
- if tx.status != TxStatus.FILLED:
- return
-
- inst = tx.instruction
- symbol = inst.symbol
- side = inst.side
- quantity = tx.fill_quantity or 0.0
- price = tx.fill_price or 0.0
- fee = tx.fee
-
- # Update trade count
- self.trades_count += 1
-
- # Handle BUY
- if side == Side.BUY:
- cost = (quantity * price) + fee
- self.cash -= cost
-
- # Update or create position
- if symbol in self.positions:
- pos = self.positions[symbol]
- total_qty = pos.quantity + quantity
- total_cost = (pos.quantity * pos.avg_entry_price) + (quantity * price)
- new_avg_price = total_cost / total_qty if total_qty > 0 else price
-
- self.positions[symbol] = PositionSnapshot(
- symbol=symbol,
- quantity=total_qty,
- avg_entry_price=new_avg_price,
- current_price=price,
- unrealized_pnl=0.0, # Will be updated in mark_to_market
- leverage=inst.leverage,
- side=Side.BUY
- )
- else:
- self.positions[symbol] = PositionSnapshot(
- symbol=symbol,
- quantity=quantity,
- avg_entry_price=price,
- current_price=price,
- unrealized_pnl=0.0,
- leverage=inst.leverage,
- side=Side.BUY
- )
-
- # Handle SELL
- elif side == Side.SELL:
- proceeds = (quantity * price) - fee
- self.cash += proceeds
-
- if symbol in self.positions:
- pos = self.positions[symbol]
-
- if pos.quantity >= quantity:
- # Partial or full close of long position
- realized_pnl = (price - pos.avg_entry_price) * quantity
- self.total_realized_pnl += realized_pnl
-
- remaining_qty = pos.quantity - quantity
- if remaining_qty > 0.01: # Keep position open
- self.positions[symbol] = PositionSnapshot(
- symbol=symbol,
- quantity=remaining_qty,
- avg_entry_price=pos.avg_entry_price,
- current_price=price,
- unrealized_pnl=0.0,
- leverage=pos.leverage,
- side=Side.BUY
- )
- else:
- # Close position completely
- del self.positions[symbol]
- else:
- # Short position (sell more than we have)
- # First close existing long, then open short
- realized_pnl = (price - pos.avg_entry_price) * pos.quantity
- self.total_realized_pnl += realized_pnl
-
- short_qty = quantity - pos.quantity
- # For short, we need margin (assume 50% margin requirement)
- margin_required = (short_qty * price) * 0.5
- self.cash -= margin_required
-
- self.positions[symbol] = PositionSnapshot(
- symbol=symbol,
- quantity=-short_qty, # Negative for short
- avg_entry_price=price,
- current_price=price,
- unrealized_pnl=0.0,
- leverage=inst.leverage,
- side=Side.SELL
- )
- else:
- # Opening short position directly
- margin_required = (quantity * price) * 0.5
- self.cash -= margin_required
-
- self.positions[symbol] = PositionSnapshot(
- symbol=symbol,
- quantity=-quantity,
- avg_entry_price=price,
- current_price=price,
- unrealized_pnl=0.0,
- leverage=inst.leverage,
- side=Side.SELL
- )
-
- async def mark_to_market(self, prices: Dict[str, float]) -> None:
- """
- Update unrealized P&L based on current market prices.
- """
- for symbol, pos in self.positions.items():
- if symbol in prices:
- current_price = prices[symbol]
- pos.current_price = current_price
-
- if pos.quantity > 0:
- # Long position
- pos.unrealized_pnl = (current_price - pos.avg_entry_price) * pos.quantity
- else:
- # Short position
- pos.unrealized_pnl = (pos.avg_entry_price - current_price) * abs(pos.quantity)
-
- async def get_portfolio_view(self) -> PortfolioView:
- """
- Get current portfolio snapshot.
-
- Total portfolio value = Cash + Position Values (at current market prices)
-
- For long positions: position_value = quantity * current_price
- For short positions: position_value = margin_held + unrealized_pnl
- (margin is already deducted from cash when opening short)
- """
- total_unrealized_pnl = sum(pos.unrealized_pnl for pos in self.positions.values())
-
- # Calculate exposures
- gross_exposure = 0.0
- net_exposure = 0.0
-
- for pos in self.positions.values():
- notional = abs(pos.quantity) * pos.current_price
- gross_exposure += notional
-
- if pos.quantity > 0:
- # Long position: positive exposure
- net_exposure += notional
- else:
- # Short position: negative exposure
- net_exposure -= notional
-
- # Total value = Cash + Long Position Values + Unrealized P&L from shorts
- # For longs: unrealized_pnl is already embedded in (current_price - entry_price) * qty
- # So we use: Cash + Long Positions Market Value + Short Unrealized P&L
- # Simplified: Cash + Gross Long Exposure + Total Unrealized P&L (which includes both)
-
- # More accurate calculation:
- # - Cash includes proceeds/margin from trades
- # - Long positions: add current market value
- # - Short positions: margin is in cash, add/subtract unrealized P&L
-
- # Calculate long positions value at cost basis + unrealized gain/loss
- long_positions_value = sum(
- pos.quantity * pos.current_price
- for pos in self.positions.values()
- if pos.quantity > 0
- )
-
- # Short positions: only unrealized P&L affects value (margin already in cash)
- short_unrealized_pnl = sum(
- pos.unrealized_pnl
- for pos in self.positions.values()
- if pos.quantity < 0
- )
-
- # Total portfolio value
- total_value = self.cash + long_positions_value + short_unrealized_pnl
-
- return PortfolioView(
- cash=self.cash,
- positions=self.positions.copy(),
- total_value=total_value,
- total_unrealized_pnl=total_unrealized_pnl,
- total_realized_pnl=self.total_realized_pnl,
- gross_exposure=gross_exposure,
- net_exposure=net_exposure,
- trades_count=self.trades_count
- )
-
- async def reset(self, initial_capital: float) -> None:
- """
- Reset portfolio to initial state.
- """
- self.initial_capital = initial_capital
- self.cash = initial_capital
- self.positions = {}
- self.total_realized_pnl = 0.0
- self.trades_count = 0
diff --git a/fincept-qt/scripts/agno_trading/framework/types.py b/fincept-qt/scripts/agno_trading/framework/types.py
deleted file mode 100644
index cb2bd5afb..000000000
--- a/fincept-qt/scripts/agno_trading/framework/types.py
+++ /dev/null
@@ -1,355 +0,0 @@
-"""
-Core types for the Alpha Arena trading framework.
-"""
-
-from dataclasses import dataclass, field
-from typing import Dict, List, Optional, Literal
-from enum import Enum
-from datetime import datetime
-
-
-class Side(str, Enum):
- """Trade side."""
- BUY = "BUY"
- SELL = "SELL"
- HOLD = "HOLD"
-
-
-class TxStatus(str, Enum):
- """Transaction status."""
- FILLED = "FILLED"
- REJECTED = "REJECTED"
- PENDING = "PENDING"
- CANCELLED = "CANCELLED"
-
-
-class TradingMode(str, Enum):
- """Trading mode."""
- PAPER = "PAPER"
- LIVE = "LIVE"
-
-
-@dataclass
-class TradeInstruction:
- """
- Instruction to execute a trade.
- Generated by composer, consumed by execution gateway.
- """
- symbol: str
- side: Side
- quantity: float
- leverage: float = 1.0
- max_slippage_bps: int = 50 # 0.5%
- model_name: Optional[str] = None # For multi-model competitions
- reasoning: Optional[str] = None
- confidence: Optional[float] = None
-
-
-@dataclass
-class TxResult:
- """
- Result of a trade execution.
- Returned by execution gateway, consumed by portfolio service.
- """
- instruction: TradeInstruction
- status: TxStatus
- fill_price: Optional[float] = None
- fill_quantity: Optional[float] = None
- fee: float = 0.0
- notional: float = 0.0
- timestamp_ms: int = 0
- error_message: Optional[str] = None
-
- def to_dict(self) -> dict:
- return {
- "symbol": self.instruction.symbol,
- "side": self.instruction.side.value,
- "quantity": self.fill_quantity or 0.0,
- "price": self.fill_price or 0.0,
- "fee": self.fee,
- "notional": self.notional,
- "status": self.status.value,
- "model_name": self.instruction.model_name,
- "reasoning": self.instruction.reasoning,
- "confidence": self.instruction.confidence,
- "timestamp_ms": self.timestamp_ms,
- }
-
-
-@dataclass
-class PositionSnapshot:
- """Snapshot of a single position."""
- symbol: str
- quantity: float
- avg_entry_price: float
- current_price: float
- unrealized_pnl: float
- leverage: float = 1.0
- side: Side = Side.BUY
-
-
-@dataclass
-class PortfolioView:
- """
- Complete portfolio state at a point in time.
- Returned by portfolio service.
- """
- cash: float
- positions: Dict[str, PositionSnapshot]
- total_value: float
- total_unrealized_pnl: float
- total_realized_pnl: float
- gross_exposure: float
- net_exposure: float
- trades_count: int = 0
-
- def to_dict(self) -> dict:
- return {
- "cash": self.cash,
- "positions": {
- sym: {
- "symbol": pos.symbol,
- "quantity": pos.quantity,
- "avg_entry_price": pos.avg_entry_price,
- "current_price": pos.current_price,
- "unrealized_pnl": pos.unrealized_pnl,
- "leverage": pos.leverage,
- "side": pos.side.value,
- }
- for sym, pos in self.positions.items()
- },
- "total_value": self.total_value,
- "total_unrealized_pnl": self.total_unrealized_pnl,
- "total_realized_pnl": self.total_realized_pnl,
- "gross_exposure": self.gross_exposure,
- "net_exposure": self.net_exposure,
- "trades_count": self.trades_count,
- }
-
-
-@dataclass
-class Candle:
- """OHLCV candle."""
- timestamp: int # Unix timestamp in milliseconds
- open: float
- high: float
- low: float
- close: float
- volume: float
-
-
-@dataclass
-class MarketSnapshot:
- """Real-time market snapshot for a symbol."""
- symbol: str
- last_price: float
- bid: float
- ask: float
- volume_24h: float
- high_24h: float
- low_24h: float
- change_24h_pct: float
- timestamp_ms: int
-
-
-@dataclass
-class FeatureVector:
- """
- Feature vector for a symbol at a point in time.
- Contains price data and technical indicators.
- """
- symbol: str
- timestamp_ms: int
-
- # Price data
- close: float
- open: float
- high: float
- low: float
- volume: float
-
- # Market snapshot
- bid: float
- ask: float
- spread_bps: float
-
- # Technical indicators
- rsi_14: Optional[float] = None
- macd: Optional[float] = None
- macd_signal: Optional[float] = None
- macd_histogram: Optional[float] = None
- bb_upper: Optional[float] = None
- bb_middle: Optional[float] = None
- bb_lower: Optional[float] = None
- atr_14: Optional[float] = None
-
- # Volatility
- volatility_24h: Optional[float] = None
-
- def to_dict(self) -> dict:
- return {
- "symbol": self.symbol,
- "timestamp_ms": self.timestamp_ms,
- "close": self.close,
- "open": self.open,
- "high": self.high,
- "low": self.low,
- "volume": self.volume,
- "bid": self.bid,
- "ask": self.ask,
- "spread_bps": self.spread_bps,
- "rsi_14": self.rsi_14,
- "macd": self.macd,
- "macd_signal": self.macd_signal,
- "macd_histogram": self.macd_histogram,
- "bb_upper": self.bb_upper,
- "bb_middle": self.bb_middle,
- "bb_lower": self.bb_lower,
- "atr_14": self.atr_14,
- "volatility_24h": self.volatility_24h,
- }
-
-
-@dataclass
-class FeaturesResult:
- """Result from features pipeline."""
- features: List[FeatureVector]
- timestamp_ms: int
- lookback_periods: int
-
-
-@dataclass
-class TradeDigestEntry:
- """Performance digest for a single symbol."""
- symbol: str
- trade_count: int
- realized_pnl: float
- win_rate: float
- avg_holding_ms: int
- last_trade_ts: int
-
-
-@dataclass
-class TradeDigest:
- """
- Performance digest across all trading.
- Used to inform LLM of historical performance.
- """
- total_trades: int
- total_realized_pnl: float
- overall_win_rate: float
- sharpe_ratio: float
- max_drawdown: float
- by_instrument: Dict[str, TradeDigestEntry]
-
- def to_dict(self) -> dict:
- return {
- "total_trades": self.total_trades,
- "total_realized_pnl": self.total_realized_pnl,
- "overall_win_rate": self.overall_win_rate,
- "sharpe_ratio": self.sharpe_ratio,
- "max_drawdown": self.max_drawdown,
- "by_instrument": {
- sym: {
- "symbol": entry.symbol,
- "trade_count": entry.trade_count,
- "realized_pnl": entry.realized_pnl,
- "win_rate": entry.win_rate,
- "avg_holding_ms": entry.avg_holding_ms,
- }
- for sym, entry in self.by_instrument.items()
- },
- }
-
-
-@dataclass
-class ComposeContext:
- """
- Context provided to composer for decision making.
- Contains all information needed to make a trading decision.
- """
- ts: int # Current timestamp in milliseconds
- compose_id: str # Unique ID for this decision cycle
- strategy_id: str # Competition/strategy ID
- model_name: str # Model making the decision
-
- # Market data
- features: List[FeatureVector]
-
- # Portfolio state
- portfolio: PortfolioView
-
- # Historical performance
- digest: Optional[TradeDigest] = None
-
- # Custom prompt/instructions
- custom_prompt: Optional[str] = None
-
-
-@dataclass
-class ComposeResult:
- """
- Result from composer.
- Contains trade instructions to execute.
- """
- instructions: List[TradeInstruction]
- compose_id: str
- model_name: str
- rationale: Optional[str] = None
- decision_type: Optional[str] = None # BUY, SELL, HOLD, or WAIT
- metadata: Dict = field(default_factory=dict)
-
-
-@dataclass
-class DecisionCycleResult:
- """
- Complete result of a decision cycle.
- Includes decisions, executions, and updated portfolio.
- """
- cycle_id: str
- cycle_number: int
- timestamp_ms: int
-
- # Decisions from all models
- compose_results: List[ComposeResult]
-
- # Execution results
- tx_results: List[TxResult]
-
- # Updated portfolio snapshots (per model)
- portfolio_snapshots: Dict[str, PortfolioView]
-
- # Performance metrics
- leaderboard: List[Dict] # Rankings by P&L
-
- def to_dict(self) -> dict:
- return {
- "cycle_id": self.cycle_id,
- "cycle_number": self.cycle_number,
- "timestamp_ms": self.timestamp_ms,
- "compose_results": [
- {
- "compose_id": cr.compose_id,
- "model_name": cr.model_name,
- "instructions": [
- {
- "symbol": inst.symbol,
- "side": inst.side.value,
- "quantity": inst.quantity,
- "leverage": inst.leverage,
- "reasoning": inst.reasoning,
- "confidence": inst.confidence,
- }
- for inst in cr.instructions
- ],
- "rationale": cr.rationale,
- }
- for cr in self.compose_results
- ],
- "tx_results": [tx.to_dict() for tx in self.tx_results],
- "portfolio_snapshots": {
- model: snapshot.to_dict()
- for model, snapshot in self.portfolio_snapshots.items()
- },
- "leaderboard": self.leaderboard,
- }
diff --git a/fincept-qt/scripts/agno_trading/tools/__init__.py b/fincept-qt/scripts/agno_trading/tools/__init__.py
deleted file mode 100644
index 856a1abc4..000000000
--- a/fincept-qt/scripts/agno_trading/tools/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-"""
-Trading Tools
-
-This module provides tools that agents can use to interact with markets,
-execute trades, analyze data, and access information.
-"""
-
-from .market_data import get_market_data_tools
-from .technical_indicators import get_technical_analysis_tools
-from .order_execution import get_order_execution_tools
-from .portfolio_tools import get_portfolio_tools
-from .news_sentiment import get_news_sentiment_tools
-
-__all__ = [
- 'get_market_data_tools',
- 'get_technical_analysis_tools',
- 'get_order_execution_tools',
- 'get_portfolio_tools',
- 'get_news_sentiment_tools',
-]
diff --git a/fincept-qt/scripts/agno_trading/tools/kraken_api.py b/fincept-qt/scripts/agno_trading/tools/kraken_api.py
deleted file mode 100644
index 75adb3e63..000000000
--- a/fincept-qt/scripts/agno_trading/tools/kraken_api.py
+++ /dev/null
@@ -1,154 +0,0 @@
-"""
-Kraken REST API Integration
-Fetches market data from Kraken exchange (NO WebSocket - REST only)
-"""
-
-import requests
-from typing import Dict, Any, List, Optional
-from datetime import datetime
-import time
-
-
-class KrakenAPI:
- """Kraken REST API client for market data"""
-
- BASE_URL = "https://api.kraken.com/0/public"
-
- def __init__(self):
- self.session = requests.Session()
- self.session.headers.update({
- 'User-Agent': 'Fincept-Terminal/1.0'
- })
- self.last_request_time = 0
- self.min_request_interval = 1.0 # 1 second between requests
-
- def _rate_limit(self):
- """Ensure we don't exceed rate limits"""
- elapsed = time.time() - self.last_request_time
- if elapsed < self.min_request_interval:
- time.sleep(self.min_request_interval - elapsed)
- self.last_request_time = time.time()
-
- def get_ticker(self, pair: str = "XBTUSD") -> Dict[str, Any]:
- """
- Get current ticker data
-
- Args:
- pair: Trading pair (e.g., XBTUSD for BTC/USD)
-
- Returns:
- Dict with current price, bid, ask, volume, etc.
- """
- self._rate_limit()
-
- try:
- response = self.session.get(
- f"{self.BASE_URL}/Ticker",
- params={"pair": pair},
- timeout=10
- )
- response.raise_for_status()
- data = response.json()
-
- if data.get('error') and len(data['error']) > 0:
- return {"error": f"Kraken API error: {data['error']}"}
-
- result = data.get('result', {})
- if not result or pair not in result:
- # Try alternate pair name
- alt_pair = list(result.keys())[0] if result else None
- if alt_pair:
- ticker = result[alt_pair]
- else:
- return {"error": "No ticker data returned"}
- else:
- ticker = result[pair]
-
- # Parse Kraken ticker format
- # [ask, bid, last_price, volume, vwap, trades, low, high, open]
- return {
- "symbol": pair,
- "price": float(ticker['c'][0]), # Last trade price
- "bid": float(ticker['b'][0]), # Best bid
- "ask": float(ticker['a'][0]), # Best ask
- "high_24h": float(ticker['h'][1]), # 24h high
- "low_24h": float(ticker['l'][1]), # 24h low
- "volume_24h": float(ticker['v'][1]), # 24h volume
- "vwap_24h": float(ticker['p'][1]), # 24h VWAP
- "open": float(ticker['o']), # Open price
- "timestamp": datetime.now().isoformat(),
- "source": "kraken_rest"
- }
-
- except Exception as e:
- return {"error": f"Failed to fetch ticker: {str(e)}"}
-
- def get_ohlc(self, pair: str = "XBTUSD", interval: int = 60) -> Dict[str, Any]:
- """
- Get OHLC (candlestick) data
-
- Args:
- pair: Trading pair
- interval: Time interval in minutes (1, 5, 15, 30, 60, 240, 1440)
-
- Returns:
- Dict with OHLC data
- """
- self._rate_limit()
-
- try:
- response = self.session.get(
- f"{self.BASE_URL}/OHLC",
- params={"pair": pair, "interval": interval},
- timeout=10
- )
- response.raise_for_status()
- data = response.json()
-
- if data.get('error') and len(data['error']) > 0:
- return {"error": f"Kraken API error: {data['error']}"}
-
- result = data.get('result', {})
- pair_data = None
- for key in result:
- if key != 'last':
- pair_data = result[key]
- break
-
- if not pair_data:
- return {"error": "No OHLC data returned"}
-
- # Get last 50 candles
- candles = []
- for candle in pair_data[-50:]:
- candles.append({
- "time": int(candle[0]),
- "open": float(candle[1]),
- "high": float(candle[2]),
- "low": float(candle[3]),
- "close": float(candle[4]),
- "volume": float(candle[6])
- })
-
- return {
- "symbol": pair,
- "interval": interval,
- "candles": candles,
- "count": len(candles),
- "timestamp": datetime.now().isoformat(),
- "source": "kraken_rest"
- }
-
- except Exception as e:
- return {"error": f"Failed to fetch OHLC: {str(e)}"}
-
-
-# Singleton instance
-_kraken_api = None
-
-def get_kraken_api() -> KrakenAPI:
- """Get singleton Kraken API instance"""
- global _kraken_api
- if _kraken_api is None:
- _kraken_api = KrakenAPI()
- return _kraken_api
diff --git a/fincept-qt/scripts/agno_trading/tools/market_data.py b/fincept-qt/scripts/agno_trading/tools/market_data.py
deleted file mode 100644
index f09ba008c..000000000
--- a/fincept-qt/scripts/agno_trading/tools/market_data.py
+++ /dev/null
@@ -1,264 +0,0 @@
-"""
-Market Data Tools
-
-Provides tools for agents to fetch real-time and historical market data.
-Integrates with existing Fincept Terminal data sources.
-"""
-
-import json
-from typing import List, Dict, Any, Optional
-from datetime import datetime, timedelta
-
-try:
- import yfinance as yf
- YFINANCE_AVAILABLE = True
-except ImportError:
- YFINANCE_AVAILABLE = False
-
-try:
- import ccxt
- CCXT_AVAILABLE = True
-except ImportError:
- CCXT_AVAILABLE = False
-
-
-def get_current_price(symbol: str, exchange: str = "binance") -> Dict[str, Any]:
- """
- Get current price for a symbol
-
- Args:
- symbol: Trading symbol (e.g., "BTC/USDT", "AAPL")
- exchange: Exchange name (default: binance)
-
- Returns:
- Dictionary with price information
- """
- try:
- # Try crypto first with CCXT
- if CCXT_AVAILABLE and "/" in symbol:
- exchange_obj = getattr(ccxt, exchange)()
- ticker = exchange_obj.fetch_ticker(symbol)
-
- return {
- "symbol": symbol,
- "exchange": exchange,
- "price": ticker['last'],
- "bid": ticker['bid'],
- "ask": ticker['ask'],
- "high_24h": ticker['high'],
- "low_24h": ticker['low'],
- "volume_24h": ticker['baseVolume'],
- "timestamp": datetime.now().isoformat(),
- "source": "ccxt"
- }
-
- # Try stock with yfinance
- elif YFINANCE_AVAILABLE:
- ticker = yf.Ticker(symbol)
- info = ticker.info
-
- return {
- "symbol": symbol,
- "price": info.get('currentPrice') or info.get('regularMarketPrice'),
- "bid": info.get('bid'),
- "ask": info.get('ask'),
- "open": info.get('regularMarketOpen'),
- "high": info.get('dayHigh'),
- "low": info.get('dayLow'),
- "volume": info.get('volume'),
- "market_cap": info.get('marketCap'),
- "timestamp": datetime.now().isoformat(),
- "source": "yfinance"
- }
-
- else:
- return {"error": "No market data library available. Install yfinance or ccxt."}
-
- except Exception as e:
- return {"error": f"Failed to fetch price: {str(e)}"}
-
-
-def get_historical_data(
- symbol: str,
- period: str = "1mo",
- interval: str = "1d",
- exchange: str = "binance"
-) -> Dict[str, Any]:
- """
- Get historical price data
-
- Args:
- symbol: Trading symbol
- period: Time period (1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max)
- interval: Data interval (1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo)
- exchange: Exchange name for crypto
-
- Returns:
- Dictionary with historical data
- """
- try:
- if YFINANCE_AVAILABLE:
- # Convert crypto symbols to yfinance format: BTC/USD -> BTC-USD
- yf_symbol = symbol.replace('/', '-')
- ticker = yf.Ticker(yf_symbol)
- hist = ticker.history(period=period, interval=interval)
-
- if hist.empty:
- return {"error": "No historical data available"}
-
- return {
- "symbol": symbol,
- "period": period,
- "interval": interval,
- "data": hist.to_dict('records'),
- "count": len(hist),
- "timestamp": datetime.now().isoformat(),
- "source": "yfinance"
- }
-
- else:
- return {"error": "yfinance not available. Install with: pip install yfinance"}
-
- except Exception as e:
- return {"error": f"Failed to fetch historical data: {str(e)}"}
-
-
-def get_market_summary(symbols: List[str]) -> Dict[str, Any]:
- """
- Get market summary for multiple symbols
-
- Args:
- symbols: List of symbols to fetch
-
- Returns:
- Dictionary with summary data for all symbols
- """
- summary = {
- "timestamp": datetime.now().isoformat(),
- "symbols": {},
- "errors": []
- }
-
- for symbol in symbols:
- try:
- price_data = get_current_price(symbol)
- if "error" not in price_data:
- summary["symbols"][symbol] = price_data
- else:
- summary["errors"].append(f"{symbol}: {price_data['error']}")
- except Exception as e:
- summary["errors"].append(f"{symbol}: {str(e)}")
-
- return summary
-
-
-def get_ohlcv_data(
- symbol: str,
- timeframe: str = "1d",
- limit: int = 100,
- exchange: str = "binance"
-) -> Dict[str, Any]:
- """
- Get OHLCV (Open, High, Low, Close, Volume) data
-
- Args:
- symbol: Trading symbol
- timeframe: Timeframe (1m, 5m, 15m, 1h, 4h, 1d, 1w)
- limit: Number of candles to fetch
- exchange: Exchange name
-
- Returns:
- Dictionary with OHLCV data
- """
- try:
- if CCXT_AVAILABLE and "/" in symbol:
- exchange_obj = getattr(ccxt, exchange)()
- ohlcv = exchange_obj.fetch_ohlcv(symbol, timeframe, limit=limit)
-
- # Format data
- formatted_data = []
- for candle in ohlcv:
- formatted_data.append({
- "timestamp": candle[0],
- "datetime": datetime.fromtimestamp(candle[0] / 1000).isoformat(),
- "open": candle[1],
- "high": candle[2],
- "low": candle[3],
- "close": candle[4],
- "volume": candle[5]
- })
-
- return {
- "symbol": symbol,
- "timeframe": timeframe,
- "exchange": exchange,
- "data": formatted_data,
- "count": len(formatted_data),
- "source": "ccxt"
- }
-
- else:
- return {"error": "CCXT not available or invalid symbol format"}
-
- except Exception as e:
- return {"error": f"Failed to fetch OHLCV data: {str(e)}"}
-
-
-def get_orderbook(symbol: str, exchange: str = "binance", limit: int = 20) -> Dict[str, Any]:
- """
- Get current order book
-
- Args:
- symbol: Trading symbol
- exchange: Exchange name
- limit: Number of orders to fetch per side
-
- Returns:
- Dictionary with orderbook data
- """
- try:
- if CCXT_AVAILABLE:
- exchange_obj = getattr(ccxt, exchange)()
- orderbook = exchange_obj.fetch_order_book(symbol, limit=limit)
-
- return {
- "symbol": symbol,
- "exchange": exchange,
- "bids": orderbook['bids'][:limit],
- "asks": orderbook['asks'][:limit],
- "timestamp": orderbook.get('timestamp'),
- "datetime": orderbook.get('datetime'),
- "source": "ccxt"
- }
-
- else:
- return {"error": "CCXT not available"}
-
- except Exception as e:
- return {"error": f"Failed to fetch orderbook: {str(e)}"}
-
-
-def get_market_data_tools() -> List[Any]:
- """
- Get list of market data tools for Agno agents
-
- Returns:
- List of tool functions
- """
- return [
- get_current_price,
- get_historical_data,
- get_market_summary,
- get_ohlcv_data,
- get_orderbook,
- ]
-
-
-# Tool descriptions for LLM
-TOOL_DESCRIPTIONS = {
- "get_current_price": "Get the current market price for a symbol. Supports both crypto (BTC/USDT) and stocks (AAPL).",
- "get_historical_data": "Fetch historical price data for analysis. Supports various time periods and intervals.",
- "get_market_summary": "Get a quick summary of multiple symbols at once for market overview.",
- "get_ohlcv_data": "Get OHLCV candlestick data for charting and technical analysis.",
- "get_orderbook": "View the current order book to analyze market depth and liquidity.",
-}
diff --git a/fincept-qt/scripts/agno_trading/tools/news_sentiment.py b/fincept-qt/scripts/agno_trading/tools/news_sentiment.py
deleted file mode 100644
index 7d82eb1d7..000000000
--- a/fincept-qt/scripts/agno_trading/tools/news_sentiment.py
+++ /dev/null
@@ -1,96 +0,0 @@
-"""
-News and Sentiment Analysis Tools
-
-Provides tools for fetching news and analyzing market sentiment.
-"""
-
-from typing import List, Dict, Any, Optional
-from datetime import datetime, timedelta
-
-
-def get_news(
- symbol: str,
- limit: int = 10,
- source: str = "general"
-) -> Dict[str, Any]:
- """
- Get news articles for a symbol
-
- Args:
- symbol: Trading symbol
- limit: Number of articles to fetch
- source: News source
-
- Returns:
- News articles
- """
- # Placeholder - will integrate with actual news APIs
- return {
- "symbol": symbol,
- "articles": [],
- "count": 0,
- "message": "News API integration pending. Will support NewsAPI, Benzinga, etc.",
- "timestamp": datetime.now().isoformat()
- }
-
-
-def analyze_sentiment(text: str) -> Dict[str, Any]:
- """
- Analyze sentiment of text
-
- Args:
- text: Text to analyze
-
- Returns:
- Sentiment analysis results
- """
- # Placeholder - will integrate with sentiment analysis
- return {
- "text_length": len(text),
- "sentiment": "neutral",
- "score": 0.0,
- "confidence": 0.0,
- "message": "Sentiment analysis integration pending. Will support TextBlob, VADER, or LLM-based analysis.",
- "timestamp": datetime.now().isoformat()
- }
-
-
-def get_market_sentiment(
- symbol: str,
- sources: List[str] = ["news", "social"]
-) -> Dict[str, Any]:
- """
- Get overall market sentiment for a symbol
-
- Args:
- symbol: Trading symbol
- sources: List of sources to analyze
-
- Returns:
- Aggregated sentiment
- """
- return {
- "symbol": symbol,
- "sources": sources,
- "overall_sentiment": "neutral",
- "sentiment_score": 0.0,
- "confidence": 0.0,
- "message": "Market sentiment aggregation pending.",
- "timestamp": datetime.now().isoformat()
- }
-
-
-def get_news_sentiment_tools() -> List[Any]:
- """Get news and sentiment tools"""
- return [
- get_news,
- analyze_sentiment,
- get_market_sentiment,
- ]
-
-
-TOOL_DESCRIPTIONS = {
- "get_news": "Fetch recent news articles for a symbol from various sources.",
- "analyze_sentiment": "Analyze the sentiment (positive, negative, neutral) of a text.",
- "get_market_sentiment": "Get aggregated market sentiment from news and social media sources.",
-}
diff --git a/fincept-qt/scripts/agno_trading/tools/portfolio_tools.py b/fincept-qt/scripts/agno_trading/tools/portfolio_tools.py
deleted file mode 100644
index 0ebfdd122..000000000
--- a/fincept-qt/scripts/agno_trading/tools/portfolio_tools.py
+++ /dev/null
@@ -1,184 +0,0 @@
-"""
-Portfolio Management Tools
-
-Provides tools for portfolio analysis and management.
-"""
-
-from typing import List, Dict, Any, Optional
-from datetime import datetime
-import math
-
-
-def calculate_portfolio_metrics(
- positions: List[Dict[str, Any]],
- initial_capital: float = 10000.0
-) -> Dict[str, Any]:
- """
- Calculate portfolio performance metrics
-
- Args:
- positions: List of positions with symbol, quantity, entry_price, current_price
- initial_capital: Initial portfolio capital
-
- Returns:
- Portfolio metrics including returns, sharpe ratio, etc.
- """
- try:
- total_value = 0
- total_pnl = 0
- total_pnl_pct = 0
-
- position_details = []
-
- for pos in positions:
- quantity = pos.get('quantity', 0)
- entry_price = pos.get('entry_price', 0)
- current_price = pos.get('current_price', 0)
-
- position_value = quantity * current_price
- position_cost = quantity * entry_price
- position_pnl = position_value - position_cost
- position_pnl_pct = (position_pnl / position_cost * 100) if position_cost > 0 else 0
-
- total_value += position_value
- total_pnl += position_pnl
-
- position_details.append({
- "symbol": pos.get('symbol'),
- "quantity": quantity,
- "entry_price": entry_price,
- "current_price": current_price,
- "value": position_value,
- "cost": position_cost,
- "pnl": position_pnl,
- "pnl_pct": position_pnl_pct
- })
-
- total_return_pct = (total_pnl / initial_capital * 100) if initial_capital > 0 else 0
-
- return {
- "total_value": total_value,
- "total_pnl": total_pnl,
- "total_return_pct": total_return_pct,
- "position_count": len(positions),
- "positions": position_details,
- "timestamp": datetime.now().isoformat()
- }
-
- except Exception as e:
- return {"error": f"Portfolio metrics calculation failed: {str(e)}"}
-
-
-def calculate_position_size(
- account_balance: float,
- risk_per_trade: float,
- entry_price: float,
- stop_loss_price: float
-) -> Dict[str, Any]:
- """
- Calculate optimal position size based on risk management
-
- Args:
- account_balance: Total account balance
- risk_per_trade: Risk percentage per trade (e.g., 0.02 for 2%)
- entry_price: Planned entry price
- stop_loss_price: Stop loss price
-
- Returns:
- Recommended position size
- """
- try:
- risk_amount = account_balance * risk_per_trade
- price_risk = abs(entry_price - stop_loss_price)
-
- if price_risk == 0:
- return {"error": "Entry price and stop loss cannot be the same"}
-
- position_size = risk_amount / price_risk
- position_value = position_size * entry_price
- position_pct = (position_value / account_balance * 100) if account_balance > 0 else 0
-
- return {
- "position_size": position_size,
- "position_value": position_value,
- "position_pct": position_pct,
- "risk_amount": risk_amount,
- "risk_pct": risk_per_trade * 100,
- "entry_price": entry_price,
- "stop_loss_price": stop_loss_price,
- "price_risk": price_risk
- }
-
- except Exception as e:
- return {"error": f"Position size calculation failed: {str(e)}"}
-
-
-def analyze_portfolio_risk(
- positions: List[Dict[str, Any]],
- correlations: Optional[Dict[str, float]] = None
-) -> Dict[str, Any]:
- """
- Analyze portfolio risk and diversification
-
- Args:
- positions: List of positions
- correlations: Optional correlation matrix
-
- Returns:
- Risk analysis
- """
- try:
- total_value = sum(pos.get('value', 0) for pos in positions)
-
- # Calculate concentration
- concentrations = []
- for pos in positions:
- value = pos.get('value', 0)
- concentration = (value / total_value * 100) if total_value > 0 else 0
- concentrations.append({
- "symbol": pos.get('symbol'),
- "value": value,
- "concentration_pct": concentration
- })
-
- # Find max concentration
- max_concentration = max(concentrations, key=lambda x: x['concentration_pct']) if concentrations else None
-
- # Assess diversification
- diversification_score = 0
- if len(positions) >= 10:
- diversification_score = 100
- elif len(positions) >= 5:
- diversification_score = 75
- elif len(positions) >= 3:
- diversification_score = 50
- else:
- diversification_score = 25
-
- return {
- "total_value": total_value,
- "position_count": len(positions),
- "concentrations": concentrations,
- "max_concentration": max_concentration,
- "diversification_score": diversification_score,
- "risk_level": "High" if (max_concentration and max_concentration['concentration_pct'] > 30) else "Medium" if (max_concentration and max_concentration['concentration_pct'] > 20) else "Low"
- }
-
- except Exception as e:
- return {"error": f"Risk analysis failed: {str(e)}"}
-
-
-def get_portfolio_tools() -> List[Any]:
- """Get portfolio management tools"""
- return [
- calculate_portfolio_metrics,
- calculate_position_size,
- analyze_portfolio_risk,
- ]
-
-
-TOOL_DESCRIPTIONS = {
- "calculate_portfolio_metrics": "Calculate comprehensive portfolio metrics including total value, P&L, and returns.",
- "calculate_position_size": "Calculate optimal position size based on risk management rules and stop loss.",
- "analyze_portfolio_risk": "Analyze portfolio risk, concentration, and diversification levels.",
-}
diff --git a/fincept-qt/scripts/agno_trading/tools/technical_indicators.py b/fincept-qt/scripts/agno_trading/tools/technical_indicators.py
deleted file mode 100644
index c370b9643..000000000
--- a/fincept-qt/scripts/agno_trading/tools/technical_indicators.py
+++ /dev/null
@@ -1,376 +0,0 @@
-"""
-Technical Analysis Tools
-
-Provides technical indicators and analysis tools for trading agents.
-"""
-
-import json
-from typing import List, Dict, Any, Optional
-import math
-
-try:
- import pandas as pd
- import numpy as np
- PANDAS_AVAILABLE = True
-except ImportError:
- PANDAS_AVAILABLE = False
-
-try:
- import talib
- TALIB_AVAILABLE = True
-except ImportError:
- TALIB_AVAILABLE = False
-
-
-def calculate_sma(prices: List[float], period: int = 20) -> Dict[str, Any]:
- """
- Calculate Simple Moving Average
-
- Args:
- prices: List of prices
- period: Period for SMA calculation
-
- Returns:
- Dictionary with SMA values
- """
- try:
- if not PANDAS_AVAILABLE:
- # Manual calculation
- if len(prices) < period:
- return {"error": f"Not enough data. Need at least {period} prices."}
-
- sma_values = []
- for i in range(len(prices) - period + 1):
- window = prices[i:i+period]
- sma = sum(window) / period
- sma_values.append(sma)
-
- return {
- "indicator": "SMA",
- "period": period,
- "values": sma_values,
- "current": sma_values[-1] if sma_values else None,
- "count": len(sma_values)
- }
-
- else:
- # Use pandas
- series = pd.Series(prices)
- sma = series.rolling(window=period).mean()
-
- return {
- "indicator": "SMA",
- "period": period,
- "values": sma.dropna().tolist(),
- "current": float(sma.iloc[-1]) if not pd.isna(sma.iloc[-1]) else None,
- "count": len(sma.dropna())
- }
-
- except Exception as e:
- return {"error": f"SMA calculation failed: {str(e)}"}
-
-
-def calculate_ema(prices: List[float], period: int = 20) -> Dict[str, Any]:
- """
- Calculate Exponential Moving Average
-
- Args:
- prices: List of prices
- period: Period for EMA calculation
-
- Returns:
- Dictionary with EMA values
- """
- try:
- if TALIB_AVAILABLE:
- prices_array = np.array(prices)
- ema = talib.EMA(prices_array, timeperiod=period)
-
- return {
- "indicator": "EMA",
- "period": period,
- "values": ema[~np.isnan(ema)].tolist(),
- "current": float(ema[-1]) if not np.isnan(ema[-1]) else None,
- "source": "talib"
- }
-
- elif PANDAS_AVAILABLE:
- series = pd.Series(prices)
- ema = series.ewm(span=period, adjust=False).mean()
-
- return {
- "indicator": "EMA",
- "period": period,
- "values": ema.tolist(),
- "current": float(ema.iloc[-1]),
- "source": "pandas"
- }
-
- else:
- return {"error": "pandas or talib required for EMA calculation"}
-
- except Exception as e:
- return {"error": f"EMA calculation failed: {str(e)}"}
-
-
-def calculate_rsi(prices: List[float], period: int = 14) -> Dict[str, Any]:
- """
- Calculate Relative Strength Index
-
- Args:
- prices: List of prices
- period: Period for RSI calculation
-
- Returns:
- Dictionary with RSI values and interpretation
- """
- try:
- if TALIB_AVAILABLE:
- prices_array = np.array(prices)
- rsi = talib.RSI(prices_array, timeperiod=period)
-
- current_rsi = float(rsi[-1]) if not np.isnan(rsi[-1]) else None
-
- # Interpret RSI
- interpretation = ""
- if current_rsi:
- if current_rsi > 70:
- interpretation = "Overbought - Potential sell signal"
- elif current_rsi < 30:
- interpretation = "Oversold - Potential buy signal"
- else:
- interpretation = "Neutral"
-
- return {
- "indicator": "RSI",
- "period": period,
- "values": rsi[~np.isnan(rsi)].tolist(),
- "current": current_rsi,
- "interpretation": interpretation,
- "source": "talib"
- }
-
- else:
- return {"error": "talib required for RSI calculation. Install with: pip install TA-Lib"}
-
- except Exception as e:
- return {"error": f"RSI calculation failed: {str(e)}"}
-
-
-def calculate_macd(
- prices: List[float],
- fast_period: int = 12,
- slow_period: int = 26,
- signal_period: int = 9
-) -> Dict[str, Any]:
- """
- Calculate MACD (Moving Average Convergence Divergence)
-
- Args:
- prices: List of prices
- fast_period: Fast EMA period
- slow_period: Slow EMA period
- signal_period: Signal line period
-
- Returns:
- Dictionary with MACD values
- """
- try:
- if TALIB_AVAILABLE:
- prices_array = np.array(prices)
- macd, signal, histogram = talib.MACD(
- prices_array,
- fastperiod=fast_period,
- slowperiod=slow_period,
- signalperiod=signal_period
- )
-
- # Clean NaN values
- valid_indices = ~(np.isnan(macd) | np.isnan(signal) | np.isnan(histogram))
-
- current_macd = float(macd[-1]) if not np.isnan(macd[-1]) else None
- current_signal = float(signal[-1]) if not np.isnan(signal[-1]) else None
- current_histogram = float(histogram[-1]) if not np.isnan(histogram[-1]) else None
-
- # Interpret MACD
- interpretation = ""
- if current_macd and current_signal:
- if current_macd > current_signal:
- interpretation = "Bullish - MACD above signal line"
- else:
- interpretation = "Bearish - MACD below signal line"
-
- return {
- "indicator": "MACD",
- "fast_period": fast_period,
- "slow_period": slow_period,
- "signal_period": signal_period,
- "macd": macd[valid_indices].tolist(),
- "signal": signal[valid_indices].tolist(),
- "histogram": histogram[valid_indices].tolist(),
- "current_macd": current_macd,
- "current_signal": current_signal,
- "current_histogram": current_histogram,
- "interpretation": interpretation,
- "source": "talib"
- }
-
- else:
- return {"error": "talib required for MACD calculation"}
-
- except Exception as e:
- return {"error": f"MACD calculation failed: {str(e)}"}
-
-
-def calculate_bollinger_bands(
- prices: List[float],
- period: int = 20,
- std_dev: float = 2.0
-) -> Dict[str, Any]:
- """
- Calculate Bollinger Bands
-
- Args:
- prices: List of prices
- period: Period for calculation
- std_dev: Standard deviation multiplier
-
- Returns:
- Dictionary with Bollinger Bands
- """
- try:
- if TALIB_AVAILABLE:
- prices_array = np.array(prices)
- upper, middle, lower = talib.BBANDS(
- prices_array,
- timeperiod=period,
- nbdevup=std_dev,
- nbdevdn=std_dev,
- matype=0
- )
-
- current_price = prices[-1]
- current_upper = float(upper[-1]) if not np.isnan(upper[-1]) else None
- current_middle = float(middle[-1]) if not np.isnan(middle[-1]) else None
- current_lower = float(lower[-1]) if not np.isnan(lower[-1]) else None
-
- # Interpret position
- interpretation = ""
- if current_upper and current_lower:
- if current_price > current_upper:
- interpretation = "Price above upper band - Potentially overbought"
- elif current_price < current_lower:
- interpretation = "Price below lower band - Potentially oversold"
- else:
- interpretation = "Price within bands - Normal range"
-
- return {
- "indicator": "Bollinger Bands",
- "period": period,
- "std_dev": std_dev,
- "upper_band": upper[~np.isnan(upper)].tolist(),
- "middle_band": middle[~np.isnan(middle)].tolist(),
- "lower_band": lower[~np.isnan(lower)].tolist(),
- "current_upper": current_upper,
- "current_middle": current_middle,
- "current_lower": current_lower,
- "current_price": current_price,
- "interpretation": interpretation,
- "source": "talib"
- }
-
- else:
- return {"error": "talib required for Bollinger Bands calculation"}
-
- except Exception as e:
- return {"error": f"Bollinger Bands calculation failed: {str(e)}"}
-
-
-def detect_support_resistance(
- prices: List[float],
- window: int = 5,
- threshold: float = 0.02
-) -> Dict[str, Any]:
- """
- Detect support and resistance levels
-
- Args:
- prices: List of prices
- window: Window size for peak detection
- threshold: Minimum price change threshold
-
- Returns:
- Dictionary with support and resistance levels
- """
- try:
- if not PANDAS_AVAILABLE:
- return {"error": "pandas required for support/resistance detection"}
-
- series = pd.Series(prices)
-
- # Find local maxima (resistance)
- resistance_levels = []
- for i in range(window, len(prices) - window):
- if all(prices[i] >= prices[i-j] for j in range(1, window+1)) and \
- all(prices[i] >= prices[i+j] for j in range(1, window+1)):
- resistance_levels.append(prices[i])
-
- # Find local minima (support)
- support_levels = []
- for i in range(window, len(prices) - window):
- if all(prices[i] <= prices[i-j] for j in range(1, window+1)) and \
- all(prices[i] <= prices[i+j] for j in range(1, window+1)):
- support_levels.append(prices[i])
-
- current_price = prices[-1]
-
- # Find nearest levels
- nearest_resistance = min(
- [r for r in resistance_levels if r > current_price],
- default=None
- )
- nearest_support = max(
- [s for s in support_levels if s < current_price],
- default=None
- )
-
- return {
- "current_price": current_price,
- "support_levels": sorted(set(support_levels)),
- "resistance_levels": sorted(set(resistance_levels)),
- "nearest_support": nearest_support,
- "nearest_resistance": nearest_resistance,
- "support_count": len(support_levels),
- "resistance_count": len(resistance_levels)
- }
-
- except Exception as e:
- return {"error": f"Support/Resistance detection failed: {str(e)}"}
-
-
-def get_technical_analysis_tools() -> List[Any]:
- """
- Get list of technical analysis tools for Agno agents
-
- Returns:
- List of tool functions
- """
- return [
- calculate_sma,
- calculate_ema,
- calculate_rsi,
- calculate_macd,
- calculate_bollinger_bands,
- detect_support_resistance,
- ]
-
-
-# Tool descriptions for LLM
-TOOL_DESCRIPTIONS = {
- "calculate_sma": "Calculate Simple Moving Average to identify trend direction and smooth out price action.",
- "calculate_ema": "Calculate Exponential Moving Average which gives more weight to recent prices.",
- "calculate_rsi": "Calculate Relative Strength Index to identify overbought/oversold conditions (>70 overbought, <30 oversold).",
- "calculate_macd": "Calculate MACD indicator to identify trend changes and momentum shifts.",
- "calculate_bollinger_bands": "Calculate Bollinger Bands to measure volatility and identify potential reversal points.",
- "detect_support_resistance": "Detect support and resistance levels where price tends to reverse or consolidate.",
-}
diff --git a/fincept-qt/scripts/agno_trading/utils/__init__.py b/fincept-qt/scripts/agno_trading/utils/__init__.py
deleted file mode 100644
index 8a53983c3..000000000
--- a/fincept-qt/scripts/agno_trading/utils/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-"""Utility modules"""
-
-from .tp_sl_calculator import TPSLCalculator
-from .confidence_scorer import ConfidenceScorer
-
-__all__ = ['TPSLCalculator', 'ConfidenceScorer']
diff --git a/fincept-qt/scripts/agno_trading/utils/confidence_scorer.py b/fincept-qt/scripts/agno_trading/utils/confidence_scorer.py
deleted file mode 100644
index 3825d128f..000000000
--- a/fincept-qt/scripts/agno_trading/utils/confidence_scorer.py
+++ /dev/null
@@ -1,245 +0,0 @@
-"""
-Confidence Scorer
-
-Calculate confidence scores for trading signals based on multiple factors.
-Inspired by Alpha Arena's 0-1 confidence scoring system.
-"""
-
-from typing import Dict, List
-import math
-
-
-class ConfidenceScorer:
- """
- Calculate confidence scores (0.0 to 1.0) for trading signals
-
- Factors considered:
- - Technical indicator alignment
- - Trend strength
- - Volume confirmation
- - Risk/reward ratio
- - Market volatility
- """
-
- @staticmethod
- def calculate_comprehensive_confidence(
- indicator_alignment: float = 0.5,
- trend_strength: float = 0.5,
- volume_confirmation: float = 0.5,
- risk_reward_ratio: float = 2.0,
- volatility_factor: float = 0.5,
- weights: Dict[str, float] = None
- ) -> Dict[str, float]:
- """
- Calculate overall confidence score
-
- Args:
- indicator_alignment: 0-1, how many indicators agree
- trend_strength: 0-1, strength of trend
- volume_confirmation: 0-1, volume supports the move
- risk_reward_ratio: Actual R:R ratio
- volatility_factor: 0-1, volatility level (0=low, 1=high)
- weights: Custom weights for each factor
-
- Returns:
- Dictionary with confidence score and breakdown
- """
-
- # Default weights
- if weights is None:
- weights = {
- 'indicators': 0.30,
- 'trend': 0.25,
- 'volume': 0.20,
- 'risk_reward': 0.15,
- 'volatility': 0.10
- }
-
- # Normalize risk/reward to 0-1 scale (assuming 3:1 is excellent)
- rr_normalized = min(risk_reward_ratio / 3.0, 1.0)
-
- # Lower volatility = higher confidence
- volatility_score = 1.0 - volatility_factor
-
- # Calculate weighted score
- confidence = (
- indicator_alignment * weights['indicators'] +
- trend_strength * weights['trend'] +
- volume_confirmation * weights['volume'] +
- rr_normalized * weights['risk_reward'] +
- volatility_score * weights['volatility']
- )
-
- # Ensure 0-1 range
- confidence = max(0.0, min(1.0, confidence))
-
- return {
- "confidence": round(confidence, 3),
- "breakdown": {
- "indicator_alignment": round(indicator_alignment, 2),
- "trend_strength": round(trend_strength, 2),
- "volume_confirmation": round(volume_confirmation, 2),
- "risk_reward_score": round(rr_normalized, 2),
- "volatility_score": round(volatility_score, 2)
- },
- "rating": ConfidenceScorer._get_confidence_rating(confidence)
- }
-
- @staticmethod
- def calculate_indicator_alignment(
- indicators: Dict[str, str]
- ) -> float:
- """
- Calculate how well indicators align
-
- Args:
- indicators: Dict of indicator signals (e.g., {'RSI': 'buy', 'MACD': 'buy', 'EMA': 'sell'})
-
- Returns:
- Alignment score 0-1
- """
-
- if not indicators:
- return 0.5
-
- signals = list(indicators.values())
- buy_count = signals.count('buy') + signals.count('bullish')
- sell_count = signals.count('sell') + signals.count('bearish')
- total = len(signals)
-
- # If all agree, score is 1.0
- alignment = max(buy_count, sell_count) / total if total > 0 else 0
-
- return alignment
-
- @staticmethod
- def calculate_trend_strength(
- current_price: float,
- ma_20: float,
- ma_50: float,
- ma_200: float = None
- ) -> float:
- """
- Calculate trend strength from moving averages
-
- Args:
- current_price: Current market price
- ma_20: 20-period MA
- ma_50: 50-period MA
- ma_200: 200-period MA (optional)
-
- Returns:
- Trend strength 0-1
- """
-
- score = 0.0
-
- # Check if price is trending
- if current_price > ma_20 > ma_50:
- score = 0.6 # Uptrend
- elif current_price < ma_20 < ma_50:
- score = 0.6 # Downtrend
-
- # Bonus for 200 MA alignment
- if ma_200:
- if (current_price > ma_20 > ma_50 > ma_200) or \
- (current_price < ma_20 < ma_50 < ma_200):
- score = 1.0 # Strong trend
-
- return score
-
- @staticmethod
- def calculate_volume_confirmation(
- current_volume: float,
- avg_volume: float,
- volume_threshold: float = 1.2
- ) -> float:
- """
- Calculate volume confirmation score
-
- Args:
- current_volume: Current volume
- avg_volume: Average volume
- volume_threshold: Multiplier for significant volume
-
- Returns:
- Volume confirmation 0-1
- """
-
- if avg_volume == 0:
- return 0.5
-
- volume_ratio = current_volume / avg_volume
-
- if volume_ratio >= volume_threshold:
- # High volume = strong confirmation
- return min(volume_ratio / 2.0, 1.0)
- else:
- # Low volume = weak confirmation
- return 0.3
-
- @staticmethod
- def adjust_for_market_conditions(
- base_confidence: float,
- market_condition: str
- ) -> float:
- """
- Adjust confidence based on market conditions
-
- Args:
- base_confidence: Base confidence score
- market_condition: 'trending', 'ranging', 'volatile', 'calm'
-
- Returns:
- Adjusted confidence
- """
-
- adjustments = {
- 'trending': 1.1, # Boost in trending markets
- 'ranging': 0.9, # Reduce in ranging markets
- 'volatile': 0.85, # Reduce in volatile markets
- 'calm': 1.0, # No change in calm markets
- }
-
- multiplier = adjustments.get(market_condition, 1.0)
- adjusted = base_confidence * multiplier
-
- return max(0.0, min(1.0, adjusted))
-
- @staticmethod
- def _get_confidence_rating(confidence: float) -> str:
- """Get text rating for confidence score"""
-
- if confidence >= 0.8:
- return "Very High"
- elif confidence >= 0.7:
- return "High"
- elif confidence >= 0.6:
- return "Medium"
- elif confidence >= 0.5:
- return "Low"
- else:
- return "Very Low"
-
- @staticmethod
- def recommend_action(confidence: float, min_threshold: float = 0.6) -> str:
- """
- Recommend action based on confidence
-
- Args:
- confidence: Confidence score
- min_threshold: Minimum confidence to trade
-
- Returns:
- Recommended action
- """
-
- if confidence >= min_threshold:
- if confidence >= 0.8:
- return "STRONG_EXECUTE"
- elif confidence >= 0.7:
- return "EXECUTE"
- else:
- return "EXECUTE_WITH_CAUTION"
- else:
- return "SKIP"
diff --git a/fincept-qt/scripts/agno_trading/utils/tp_sl_calculator.py b/fincept-qt/scripts/agno_trading/utils/tp_sl_calculator.py
deleted file mode 100644
index c9d4b12f4..000000000
--- a/fincept-qt/scripts/agno_trading/utils/tp_sl_calculator.py
+++ /dev/null
@@ -1,221 +0,0 @@
-"""
-TP/SL Calculator
-
-Dynamic Take Profit and Stop Loss calculation based on volatility and market conditions.
-Inspired by Alpha Arena's adaptive TP/SL logic.
-"""
-
-from typing import Dict, Tuple
-import math
-
-
-class TPSLCalculator:
- """
- Calculate dynamic TP/SL levels based on:
- - Current volatility (ATR)
- - Risk/reward ratio
- - Market conditions
- """
-
- @staticmethod
- def calculate_dynamic_tp_sl(
- entry_price: float,
- direction: str,
- volatility: float,
- risk_reward_ratio: float = 2.0,
- atr_multiplier: float = 2.0
- ) -> Dict[str, float]:
- """
- Calculate TP/SL levels dynamically
-
- Args:
- entry_price: Entry price
- direction: 'long' or 'short'
- volatility: Current volatility (ATR or standard deviation)
- risk_reward_ratio: Desired risk/reward ratio (default 2:1)
- atr_multiplier: Multiplier for ATR to set SL distance
-
- Returns:
- Dictionary with stop_loss, take_profit, risk_amount, reward_amount
- """
-
- # Calculate stop loss distance based on volatility
- sl_distance = volatility * atr_multiplier
-
- if direction.lower() == 'long':
- stop_loss = entry_price - sl_distance
- take_profit = entry_price + (sl_distance * risk_reward_ratio)
- else: # short
- stop_loss = entry_price + sl_distance
- take_profit = entry_price - (sl_distance * risk_reward_ratio)
-
- return {
- "stop_loss": round(stop_loss, 2),
- "take_profit": round(take_profit, 2),
- "sl_distance": round(sl_distance, 2),
- "tp_distance": round(sl_distance * risk_reward_ratio, 2),
- "risk_reward_ratio": risk_reward_ratio
- }
-
- @staticmethod
- def calculate_from_percentage(
- entry_price: float,
- direction: str,
- sl_percent: float = 2.0,
- tp_percent: float = 5.0
- ) -> Dict[str, float]:
- """
- Calculate TP/SL based on percentage
-
- Args:
- entry_price: Entry price
- direction: 'long' or 'short'
- sl_percent: Stop loss percentage (e.g., 2.0 for 2%)
- tp_percent: Take profit percentage (e.g., 5.0 for 5%)
-
- Returns:
- Dictionary with stop_loss and take_profit
- """
-
- sl_amount = entry_price * (sl_percent / 100)
- tp_amount = entry_price * (tp_percent / 100)
-
- if direction.lower() == 'long':
- stop_loss = entry_price - sl_amount
- take_profit = entry_price + tp_amount
- else: # short
- stop_loss = entry_price + sl_amount
- take_profit = entry_price - tp_amount
-
- return {
- "stop_loss": round(stop_loss, 2),
- "take_profit": round(take_profit, 2),
- "sl_percent": sl_percent,
- "tp_percent": tp_percent,
- "risk_reward_ratio": tp_percent / sl_percent
- }
-
- @staticmethod
- def calculate_trailing_stop(
- entry_price: float,
- current_price: float,
- direction: str,
- trail_percent: float = 1.0
- ) -> float:
- """
- Calculate trailing stop loss
-
- Args:
- entry_price: Original entry price
- current_price: Current market price
- direction: 'long' or 'short'
- trail_percent: Trailing distance as percentage
-
- Returns:
- New stop loss level
- """
-
- if direction.lower() == 'long':
- # For long, trail below current price
- trailing_stop = current_price * (1 - trail_percent / 100)
- # Never move stop down
- original_stop = entry_price * (1 - trail_percent / 100)
- return max(trailing_stop, original_stop)
- else: # short
- # For short, trail above current price
- trailing_stop = current_price * (1 + trail_percent / 100)
- # Never move stop up
- original_stop = entry_price * (1 + trail_percent / 100)
- return min(trailing_stop, original_stop)
-
- @staticmethod
- def estimate_volatility_from_price_history(
- prices: list,
- period: int = 14
- ) -> float:
- """
- Estimate volatility from price history using ATR approximation
-
- Args:
- prices: List of recent prices
- period: Period for calculation
-
- Returns:
- Estimated volatility
- """
-
- if len(prices) < period + 1:
- # Use simple percentage of current price if not enough data
- return prices[-1] * 0.02 if prices else 0
-
- # Calculate simple volatility as average price range
- ranges = []
- for i in range(len(prices) - period, len(prices)):
- if i > 0:
- ranges.append(abs(prices[i] - prices[i-1]))
-
- avg_range = sum(ranges) / len(ranges) if ranges else 0
- return avg_range
-
- @staticmethod
- def validate_tp_sl(
- entry_price: float,
- stop_loss: float,
- take_profit: float,
- direction: str,
- min_risk_reward: float = 1.5
- ) -> Dict[str, any]:
- """
- Validate TP/SL levels
-
- Args:
- entry_price: Entry price
- stop_loss: Stop loss level
- take_profit: Take profit level
- direction: 'long' or 'short'
- min_risk_reward: Minimum acceptable risk/reward ratio
-
- Returns:
- Validation result with errors if any
- """
-
- errors = []
- warnings = []
-
- if direction.lower() == 'long':
- # For long: SL < entry < TP
- if stop_loss >= entry_price:
- errors.append("Stop loss must be below entry price for long positions")
-
- if take_profit <= entry_price:
- errors.append("Take profit must be above entry price for long positions")
-
- if stop_loss < entry_price and take_profit > entry_price:
- risk = entry_price - stop_loss
- reward = take_profit - entry_price
- rr_ratio = reward / risk if risk > 0 else 0
-
- if rr_ratio < min_risk_reward:
- warnings.append(f"Risk/reward ratio {rr_ratio:.2f} is below minimum {min_risk_reward}")
-
- else: # short
- # For short: SL > entry > TP
- if stop_loss <= entry_price:
- errors.append("Stop loss must be above entry price for short positions")
-
- if take_profit >= entry_price:
- errors.append("Take profit must be below entry price for short positions")
-
- if stop_loss > entry_price and take_profit < entry_price:
- risk = stop_loss - entry_price
- reward = entry_price - take_profit
- rr_ratio = reward / risk if risk > 0 else 0
-
- if rr_ratio < min_risk_reward:
- warnings.append(f"Risk/reward ratio {rr_ratio:.2f} is below minimum {min_risk_reward}")
-
- return {
- "valid": len(errors) == 0,
- "errors": errors,
- "warnings": warnings
- }
diff --git a/fincept-qt/scripts/agno_trading_service.py b/fincept-qt/scripts/agno_trading_service.py
deleted file mode 100644
index ce150acf8..000000000
--- a/fincept-qt/scripts/agno_trading_service.py
+++ /dev/null
@@ -1,546 +0,0 @@
-#!/usr/bin/env python
-"""
-Alpha Arena Trading Service - New Framework
-===========================================
-
-Streamlined service using the modular trading framework.
-Clean separation of concerns, extensible architecture.
-
-Commands:
- - create_competition: Create a new multi-LLM competition
- - run_cycle: Execute a single trading cycle
- - start_competition: Start continuous trading
- - stop_competition: Stop the competition
- - get_leaderboard_alpha: Get current rankings
- - get_model_decisions_alpha: Get recent decisions
-"""
-
-import sys
-import json
-import os
-import asyncio
-from typing import Dict, Any, Optional
-
-# Configure logging - stderr only
-import logging
-logging.basicConfig(
- level=logging.ERROR,
- format='%(levelname)s: %(message)s',
- stream=sys.stderr,
- force=True
-)
-
-# Redirect stdout to stderr (preserve stdout for JSON)
-class StdoutToStderr:
- def write(self, text):
- sys.stderr.write(text)
- def flush(self):
- sys.stderr.flush()
-
-_original_stdout = sys.stdout
-
-def _suppress_stdout():
- sys.stdout = StdoutToStderr()
-
-def _restore_stdout():
- sys.stdout = _original_stdout
-
-_suppress_stdout()
-
-# Disable loguru
-os.environ['LOGURU_LEVEL'] = 'CRITICAL'
-os.environ['LOGURU_AUTOINIT'] = 'False'
-
-# Add to path
-sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'agno_trading'))
-
-try:
- from loguru import logger
- logger.remove()
- logger.add(sys.stderr, level="CRITICAL")
-except ImportError:
- pass
-
-# Import framework
-from framework import CompetitionRuntime, ModelConfig
-from db.database_manager import DatabaseManager
-
-# Global competition instance
-_active_competition: Optional[CompetitionRuntime] = None
-_db_manager: Optional[DatabaseManager] = None
-
-
-def get_db_manager() -> DatabaseManager:
- """Get or create database manager."""
- global _db_manager
- if _db_manager is None:
- _db_manager = DatabaseManager()
- return _db_manager
-
-
-def create_competition_command(args: list) -> Dict[str, Any]:
- """
- Create a new Alpha Arena competition.
-
- Args:
- args[0]: JSON string with competition config
- {
- "competition_id": "comp_123",
- "competition_name": "My Competition",
- "models": [
- {
- "name": "GPT-4",
- "provider": "openai",
- "model_id": "gpt-4",
- "api_key": "sk-..."
- },
- ...
- ],
- "symbols": ["BTC/USD"],
- "initial_capital": 10000.0,
- "exchange_id": "kraken",
- "custom_prompt": "Optional strategy instructions"
- }
- """
- global _active_competition
-
- try:
- config = json.loads(args[0])
-
- competition_id = config["competition_id"]
- competition_name = config.get("competition_name", "Untitled")
- symbols = config.get("symbols", ["BTC/USD"])
- initial_capital = float(config.get("initial_capital", 10000.0))
- exchange_id = config.get("exchange_id", "kraken")
- custom_prompt = config.get("custom_prompt")
-
- # Parse model configs
- models = []
- for model_data in config["models"]:
- models.append(ModelConfig(
- name=model_data["name"],
- provider=model_data["provider"],
- model_id=model_data["model_id"],
- api_key=model_data["api_key"],
- temperature=float(model_data.get("temperature", 0.7)),
- max_tokens=int(model_data.get("max_tokens", 1000)),
- timeout_seconds=int(model_data.get("timeout_seconds", 30))
- ))
-
- # Create competition runtime
- _active_competition = CompetitionRuntime(
- competition_id=competition_id,
- models=models,
- symbols=symbols,
- initial_capital=initial_capital,
- exchange_id=exchange_id,
- custom_prompt=custom_prompt
- )
-
- # Save to database
- db = get_db_manager()
- models_json = json.dumps([{
- "name": m.name,
- "provider": m.provider,
- "model_id": m.model_id
- } for m in models])
-
- db.save_competition_config(
- competition_id=competition_id,
- name=competition_name,
- models_json=models_json,
- symbol=symbols[0], # Primary symbol
- mode="baseline", # Default mode
- api_keys_json=json.dumps({m.name: m.api_key for m in models})
- )
-
- # Save model states
- for model in models:
- db.save_model_state(
- competition_id=competition_id,
- model_name=model.name,
- capital=initial_capital,
- positions_json="{}",
- trades_count=0,
- total_pnl=0.0,
- portfolio_value=initial_capital
- )
-
- return {
- "success": True,
- "competition_id": competition_id,
- "models": [m.name for m in models],
- "symbols": symbols
- }
-
- except Exception as e:
- print(f"[ERROR] create_competition failed: {e}", file=sys.stderr)
- import traceback
- traceback.print_exc(file=sys.stderr)
- return {"success": False, "error": str(e)}
-
-
-def load_competition_from_db(competition_id: str) -> Optional[CompetitionRuntime]:
- """Load competition from database."""
- try:
- db = get_db_manager()
-
- # Get competition config
- conn = db.get_connection()
- cursor = conn.cursor()
- cursor.execute("""
- SELECT name, models_json, symbol, api_keys_json
- FROM competition_configs
- WHERE competition_id = ?
- """, (competition_id,))
-
- row = cursor.fetchone()
- if not row:
- conn.close()
- print(f"[ERROR] Competition {competition_id} not found in database", file=sys.stderr)
- return None
-
- name, models_json, symbol, api_keys_json = row
-
- # Parse models
- models_data = json.loads(models_json)
- api_keys = json.loads(api_keys_json) if api_keys_json else {}
-
- models = []
- for model_data in models_data:
- model_name = model_data["name"]
- api_key = api_keys.get(model_name, "")
-
- models.append(ModelConfig(
- name=model_name,
- provider=model_data["provider"],
- model_id=model_data["model_id"],
- api_key=api_key,
- temperature=0.7,
- max_tokens=1000,
- timeout_seconds=30
- ))
-
- # Get model states to restore portfolios
- cursor.execute("""
- SELECT model_name, capital, positions_json, trades_count, total_pnl, portfolio_value
- FROM alpha_model_states
- WHERE competition_id = ?
- """, (competition_id,))
-
- model_states = {}
- for row in cursor.fetchall():
- model_name, capital, positions_json, trades_count, total_pnl, portfolio_value = row
- model_states[model_name] = {
- "capital": capital,
- "positions": json.loads(positions_json) if positions_json else {},
- "trades_count": trades_count,
- "total_pnl": total_pnl,
- "portfolio_value": portfolio_value
- }
-
- conn.close()
-
- # Create competition
- competition = CompetitionRuntime(
- competition_id=competition_id,
- models=models,
- symbols=[symbol],
- initial_capital=10000.0, # Will restore from states
- exchange_id="kraken",
- custom_prompt=None
- )
-
- # Restore portfolio states
- for model_name, state in model_states.items():
- if model_name in competition.portfolios:
- portfolio = competition.portfolios[model_name]
- portfolio.cash = state["capital"]
- portfolio.trades_count = state["trades_count"]
- portfolio.total_realized_pnl = state["total_pnl"]
- # TODO: Restore positions from state["positions"]
-
- print(f"[INFO] Loaded competition {competition_id} from database", file=sys.stderr)
- return competition
-
- except Exception as e:
- print(f"[ERROR] Failed to load competition: {e}", file=sys.stderr)
- import traceback
- traceback.print_exc(file=sys.stderr)
- return None
-
-
-async def run_cycle_async(args: list) -> Dict[str, Any]:
- """Run a single trading cycle (async)."""
- global _active_competition
-
- try:
- # Get competition ID from args
- competition_id = args[0] if args else None
-
- # If no active competition, try to load from database
- if _active_competition is None:
- if not competition_id:
- return {"success": False, "error": "No competition ID provided"}
-
- print(f"[INFO] Loading competition {competition_id} from database", file=sys.stderr)
- _active_competition = load_competition_from_db(competition_id)
-
- if _active_competition is None:
- return {"success": False, "error": "Failed to load competition from database"}
-
- # Verify competition ID matches if provided
- if competition_id and _active_competition.competition_id != competition_id:
- print(f"[INFO] Switching to competition {competition_id}", file=sys.stderr)
- _active_competition = load_competition_from_db(competition_id)
-
- if _active_competition is None:
- return {"success": False, "error": "Failed to load competition from database"}
-
- # Run cycle
- result = await _active_competition.run_cycle()
-
- # Save to database
- db = get_db_manager()
- competition_id = _active_competition.competition_id
-
- # Save ALL decisions (including HOLD/WAIT)
- for compose_result in result.compose_results:
- # Get portfolio value before
- portfolio_before = result.portfolio_snapshots.get(compose_result.model_name)
- portfolio_value_before = portfolio_before.total_value if portfolio_before else 0.0
-
- # Get the decision type (BUY/SELL/HOLD/WAIT)
- decision_type = compose_result.decision_type or 'WAIT'
-
- if compose_result.instructions:
- # BUY or SELL decision with trade execution
- for instruction in compose_result.instructions:
- db.save_decision_log(
- competition_id=competition_id,
- model_name=instruction.model_name or compose_result.model_name,
- cycle_number=result.cycle_number,
- action=instruction.side.value,
- symbol=instruction.symbol,
- quantity=instruction.quantity,
- confidence=instruction.confidence or 0.5,
- reasoning=instruction.reasoning or "",
- trade_executed=True,
- price_at_decision=0.0, # Will be updated with tx result
- portfolio_value_before=portfolio_value_before,
- portfolio_value_after=0.0 # Will be updated below
- )
- else:
- # HOLD or WAIT decision (no trade execution)
- # Get symbol from features or use competition default
- symbol = _active_competition.symbols[0] if _active_competition.symbols else 'BTC/USD'
-
- db.save_decision_log(
- competition_id=competition_id,
- model_name=compose_result.model_name,
- cycle_number=result.cycle_number,
- action=decision_type, # HOLD or WAIT
- symbol=symbol,
- quantity=0.0,
- confidence=0.5,
- reasoning=compose_result.rationale or "",
- trade_executed=False,
- price_at_decision=0.0,
- portfolio_value_before=portfolio_value_before,
- portfolio_value_after=portfolio_value_before # No change
- )
-
- # Save portfolio snapshots
- for model_name, portfolio_view in result.portfolio_snapshots.items():
- db.save_performance_snapshot(
- competition_id=competition_id,
- cycle_number=result.cycle_number,
- model_name=model_name,
- portfolio_value=portfolio_view.total_value,
- cash=portfolio_view.cash,
- pnl=portfolio_view.total_realized_pnl + portfolio_view.total_unrealized_pnl,
- return_pct=((portfolio_view.total_value - _active_competition.initial_capital) / _active_competition.initial_capital) * 100.0,
- positions_count=len(portfolio_view.positions),
- trades_count=portfolio_view.trades_count
- )
-
- # Update model state
- db.save_model_state(
- competition_id=competition_id,
- model_name=model_name,
- capital=portfolio_view.cash,
- positions_json=json.dumps(portfolio_view.to_dict()["positions"]),
- trades_count=portfolio_view.trades_count,
- total_pnl=portfolio_view.total_realized_pnl + portfolio_view.total_unrealized_pnl,
- portfolio_value=portfolio_view.total_value
- )
-
- return {
- "success": True,
- "cycle_number": result.cycle_number,
- "leaderboard": result.leaderboard,
- "decisions_count": len(result.tx_results)
- }
-
- except Exception as e:
- print(f"[ERROR] run_cycle failed: {e}", file=sys.stderr)
- import traceback
- traceback.print_exc(file=sys.stderr)
- return {"success": False, "error": str(e)}
-
-
-def run_cycle_command(args: list) -> Dict[str, Any]:
- """Run a single trading cycle (sync wrapper)."""
- return asyncio.run(run_cycle_async(args))
-
-
-def start_competition_command(args: list) -> Dict[str, Any]:
- """Start continuous trading (runs one cycle then returns)."""
- return run_cycle_command(args)
-
-
-def stop_competition_command(args: list) -> Dict[str, Any]:
- """Stop the competition."""
- global _active_competition
-
- try:
- if _active_competition:
- _active_competition.stop()
- asyncio.run(_active_competition.close())
- _active_competition = None
-
- return {"success": True}
-
- except Exception as e:
- print(f"[ERROR] stop_competition failed: {e}", file=sys.stderr)
- return {"success": False, "error": str(e)}
-
-
-async def get_leaderboard_async(args: list) -> Dict[str, Any]:
- """Get current leaderboard (async)."""
- global _active_competition
-
- try:
- # Get competition ID from args
- competition_id = args[0] if args else None
-
- # If no active competition, try to load from database
- if _active_competition is None:
- if not competition_id:
- return {"success": False, "error": "No competition ID provided"}
-
- print(f"[INFO] Loading competition {competition_id} for leaderboard", file=sys.stderr)
- _active_competition = load_competition_from_db(competition_id)
-
- if _active_competition is None:
- return {"success": False, "error": "Failed to load competition from database"}
-
- # Verify competition ID matches if provided - but DON'T reload if match
- if competition_id and _active_competition.competition_id != competition_id:
- print(f"[INFO] Switching to competition {competition_id}", file=sys.stderr)
- _active_competition = load_competition_from_db(competition_id)
-
- if _active_competition is None:
- return {"success": False, "error": "Failed to load competition from database"}
- elif competition_id and _active_competition.competition_id == competition_id:
- # Competition matches - sync portfolio states from DB to ensure consistency
- db = get_db_manager()
- conn = db.get_connection()
- cursor = conn.cursor()
- cursor.execute("""
- SELECT model_name, capital, positions_json, trades_count, total_pnl, portfolio_value
- FROM alpha_model_states
- WHERE competition_id = ?
- """, (competition_id,))
-
- for row in cursor.fetchall():
- model_name, capital, positions_json, trades_count, total_pnl, portfolio_value = row
- if model_name in _active_competition.portfolios:
- portfolio = _active_competition.portfolios[model_name]
- portfolio.cash = capital
- portfolio.trades_count = trades_count
- portfolio.total_realized_pnl = total_pnl
-
- conn.close()
-
- leaderboard = await _active_competition.get_leaderboard()
-
- return {
- "success": True,
- "leaderboard": leaderboard
- }
-
- except Exception as e:
- print(f"[ERROR] get_leaderboard failed: {e}", file=sys.stderr)
- import traceback
- traceback.print_exc(file=sys.stderr)
- return {"success": False, "error": str(e)}
-
-
-def get_leaderboard_command(args: list) -> Dict[str, Any]:
- """Get current leaderboard (sync wrapper)."""
- return asyncio.run(get_leaderboard_async(args))
-
-
-def get_model_decisions_command(args: list) -> Dict[str, Any]:
- """Get recent model decisions from database."""
- try:
- competition_id = args[0] if args else None
- if not competition_id:
- return {"success": False, "error": "competition_id required"}
-
- db = get_db_manager()
- decisions = db.get_decision_logs(competition_id, limit=50)
-
- return {
- "success": True,
- "decisions": decisions
- }
-
- except Exception as e:
- print(f"[ERROR] get_model_decisions failed: {e}", file=sys.stderr)
- return {"success": False, "error": str(e)}
-
-
-# Command registry
-COMMANDS = {
- "create_competition": create_competition_command,
- "run_cycle": run_cycle_command,
- "start_competition": start_competition_command,
- "stop_competition": stop_competition_command,
- "get_leaderboard_alpha": get_leaderboard_command,
- "get_model_decisions_alpha": get_model_decisions_command,
-}
-
-
-def main():
- """Main entry point."""
- if len(sys.argv) < 2:
- _restore_stdout()
- print(json.dumps({
- "success": False,
- "error": "No command specified"
- }))
- return
-
- command = sys.argv[1]
- args = sys.argv[2:]
-
- if command not in COMMANDS:
- _restore_stdout()
- print(json.dumps({
- "success": False,
- "error": f"Unknown command: {command}"
- }))
- return
-
- # Execute command
- result = COMMANDS[command](args)
-
- # Output JSON result
- _restore_stdout()
- print(json.dumps(result))
-
-
-if __name__ == "__main__":
- main()
diff --git a/fincept-qt/scripts/akshare_alternative.py b/fincept-qt/scripts/akshare_alternative.py
index 83b73ab54..e0ab851a8 100644
--- a/fincept-qt/scripts/akshare_alternative.py
+++ b/fincept-qt/scripts/akshare_alternative.py
@@ -71,6 +71,7 @@ class AlternativeDataWrapper:
return {
"success": True,
"data": self._convert_dataframe_to_json_safe(result),
+ "columns": (list(result.columns) if hasattr(result, "columns") else []),
"count": len(result),
"timestamp": int(datetime.now().timestamp()),
"source": f"akshare.{func.__name__}"
@@ -256,7 +257,10 @@ if __name__ == "__main__":
if hasattr(wrapper, method_name):
method = getattr(wrapper, method_name)
try:
- result = method(*args) if args else method()
+ try:
+ result = method(*args)
+ except TypeError:
+ result = method()
print(json.dumps(result, ensure_ascii=True, cls=DateTimeEncoder))
except Exception as e:
print(json.dumps({"success": False, "error": str(e), "endpoint": endpoint}))
diff --git a/fincept-qt/scripts/akshare_bonds.py b/fincept-qt/scripts/akshare_bonds.py
index 4d56913ec..312af0e4a 100644
--- a/fincept-qt/scripts/akshare_bonds.py
+++ b/fincept-qt/scripts/akshare_bonds.py
@@ -67,6 +67,7 @@ class BondsWrapper:
return {
"success": True,
"data": self._convert_dataframe_to_json_safe(result),
+ "columns": (list(result.columns) if hasattr(result, "columns") else []),
"count": len(result),
"timestamp": int(datetime.now().timestamp()),
"source": f"akshare.{func.__name__}"
diff --git a/fincept-qt/scripts/akshare_crypto.py b/fincept-qt/scripts/akshare_crypto.py
index 6ef184af2..b1ed5de33 100644
--- a/fincept-qt/scripts/akshare_crypto.py
+++ b/fincept-qt/scripts/akshare_crypto.py
@@ -37,7 +37,7 @@ def safe_call(func, *args, **kwargs):
result = result.replace([float("inf"), float("-inf")], None)
result = result.where(pd.notna(result), None)
data = result.to_dict(orient='records')
- return {"success": True, "data": data, "count": len(data)}
+ return {"success": True, "data": data, "columns": list(result.columns), "count": len(data)}
elif isinstance(result, (list, dict)):
return {"success": True, "data": result, "count": len(result) if isinstance(result, list) else 1}
else:
@@ -118,7 +118,10 @@ def main():
elif endpoint in ENDPOINTS:
func = ENDPOINTS[endpoint]["func"]
if args:
- result = func(*args)
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func() # endpoint takes no/fewer args - ignore UI default
else:
result = func()
else:
diff --git a/fincept-qt/scripts/akshare_currency.py b/fincept-qt/scripts/akshare_currency.py
index 50efc4051..c244c95b4 100644
--- a/fincept-qt/scripts/akshare_currency.py
+++ b/fincept-qt/scripts/akshare_currency.py
@@ -37,7 +37,7 @@ def safe_call(func, *args, **kwargs):
result = result.replace([float("inf"), float("-inf")], None)
result = result.where(pd.notna(result), None)
data = result.to_dict(orient='records')
- return {"success": True, "data": data, "count": len(data)}
+ return {"success": True, "data": data, "columns": list(result.columns), "count": len(data)}
elif isinstance(result, (list, dict)):
return {"success": True, "data": result, "count": len(result) if isinstance(result, list) else 1}
else:
@@ -143,7 +143,10 @@ def main():
elif endpoint in ENDPOINTS:
func = ENDPOINTS[endpoint]["func"]
if args:
- result = func(*args)
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func() # endpoint takes no/fewer args - ignore UI default
else:
result = func()
else:
diff --git a/fincept-qt/scripts/akshare_data.py b/fincept-qt/scripts/akshare_data.py
index 13d558af2..050ff4981 100644
--- a/fincept-qt/scripts/akshare_data.py
+++ b/fincept-qt/scripts/akshare_data.py
@@ -122,6 +122,7 @@ class AKShareDataWrapper:
return {
"success": True,
"data": df_copy.to_dict('records'),
+ "columns": list(df_copy.columns),
"count": len(result),
"timestamp": int(datetime.now().timestamp())
}
@@ -432,6 +433,8 @@ def main():
result = method(symbol=args[0], start_date=args[1] if len(args) > 1 else None, end_date=args[2] if len(args) > 2 else None)
else:
result = method(*args)
+ except TypeError:
+ result = method() # endpoint takes no/fewer args - ignore UI default
except Exception as e:
result = {"error": str(e), "endpoint": endpoint}
else:
@@ -475,7 +478,10 @@ if __name__ == "__main__":
if hasattr(wrapper, method_name):
method = getattr(wrapper, method_name)
try:
- result = method(*args) if args else method()
+ try:
+ result = method(*args)
+ except TypeError:
+ result = method()
print(json.dumps(result, ensure_ascii=True))
except Exception as e:
print(json.dumps({"success": False, "error": str(e), "endpoint": endpoint}))
diff --git a/fincept-qt/scripts/akshare_derivatives.py b/fincept-qt/scripts/akshare_derivatives.py
index 6aaf8a872..a8c74992c 100644
--- a/fincept-qt/scripts/akshare_derivatives.py
+++ b/fincept-qt/scripts/akshare_derivatives.py
@@ -66,6 +66,7 @@ class DerivativesWrapper:
return {
"success": True,
"data": self._convert_dataframe_to_json_safe(result),
+ "columns": (list(result.columns) if hasattr(result, "columns") else []),
"count": len(result),
"timestamp": int(datetime.now().timestamp()),
"source": f"akshare.{func.__name__}"
@@ -383,7 +384,10 @@ if __name__ == "__main__":
if hasattr(wrapper, method_name):
method = getattr(wrapper, method_name)
try:
- result = method(*args) if args else method()
+ try:
+ result = method(*args)
+ except TypeError:
+ result = method()
print(json.dumps(result, ensure_ascii=True, cls=DateTimeEncoder))
except Exception as e:
print(json.dumps({"success": False, "error": str(e), "endpoint": endpoint}))
diff --git a/fincept-qt/scripts/akshare_economics_china.py b/fincept-qt/scripts/akshare_economics_china.py
index 329d0cec1..89e12189e 100644
--- a/fincept-qt/scripts/akshare_economics_china.py
+++ b/fincept-qt/scripts/akshare_economics_china.py
@@ -91,6 +91,7 @@ class ChinaEconomicsWrapper:
return {
"success": True,
"data": self._convert_dataframe_to_json_safe(result),
+ "columns": (list(result.columns) if hasattr(result, "columns") else []),
"count": len(result),
"timestamp": int(datetime.now().timestamp()),
"source": f"akshare.{func.__name__}"
@@ -509,7 +510,10 @@ if __name__ == "__main__":
if hasattr(wrapper, method_name):
method = getattr(wrapper, method_name)
try:
- result = method(*args) if args else method()
+ try:
+ result = method(*args)
+ except TypeError:
+ result = method()
print(json.dumps(result, ensure_ascii=True, cls=DateTimeEncoder))
except Exception as e:
print(json.dumps({"success": False, "error": str(e), "endpoint": endpoint}))
diff --git a/fincept-qt/scripts/akshare_energy.py b/fincept-qt/scripts/akshare_energy.py
index 3d4a65a48..913b4cc3c 100644
--- a/fincept-qt/scripts/akshare_energy.py
+++ b/fincept-qt/scripts/akshare_energy.py
@@ -37,7 +37,7 @@ def safe_call(func, *args, **kwargs):
result = result.replace([float("inf"), float("-inf")], None)
result = result.where(pd.notna(result), None)
data = result.to_dict(orient='records')
- return {"success": True, "data": data, "count": len(data)}
+ return {"success": True, "data": data, "columns": list(result.columns), "count": len(data)}
elif isinstance(result, (list, dict)):
return {"success": True, "data": result, "count": len(result) if isinstance(result, list) else 1}
else:
@@ -147,7 +147,10 @@ def main():
elif endpoint in ENDPOINTS:
func = ENDPOINTS[endpoint]["func"]
if args:
- result = func(*args)
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func() # endpoint takes no/fewer args - ignore UI default
else:
result = func()
else:
diff --git a/fincept-qt/scripts/akshare_funds_expanded.py b/fincept-qt/scripts/akshare_funds_expanded.py
index e4b937264..fab855a39 100644
--- a/fincept-qt/scripts/akshare_funds_expanded.py
+++ b/fincept-qt/scripts/akshare_funds_expanded.py
@@ -73,6 +73,7 @@ class ExpandedFundsWrapper:
return {
"success": True,
"data": self._convert_dataframe_to_json_safe(result),
+ "columns": (list(result.columns) if hasattr(result, "columns") else []),
"count": len(result),
"timestamp": int(datetime.now().timestamp()),
"data_quality": "high",
@@ -585,7 +586,10 @@ if __name__ == "__main__":
if hasattr(wrapper, method_name):
method = getattr(wrapper, method_name)
try:
- result = method(*args) if args else method()
+ try:
+ result = method(*args)
+ except TypeError:
+ result = method()
print(json.dumps(result, ensure_ascii=True))
except Exception as e:
print(json.dumps({"success": False, "error": str(e), "endpoint": endpoint}))
diff --git a/fincept-qt/scripts/akshare_futures.py b/fincept-qt/scripts/akshare_futures.py
index fae9b1e98..2ac5b824d 100644
--- a/fincept-qt/scripts/akshare_futures.py
+++ b/fincept-qt/scripts/akshare_futures.py
@@ -37,7 +37,7 @@ def safe_call(func, *args, **kwargs):
result = result.replace([float("inf"), float("-inf")], None)
result = result.where(pd.notna(result), None)
data = result.to_dict(orient='records')
- return {"success": True, "data": data, "count": len(data)}
+ return {"success": True, "data": data, "columns": list(result.columns), "count": len(data)}
elif isinstance(result, (list, dict)):
return {"success": True, "data": result, "count": len(result) if isinstance(result, list) else 1}
else:
@@ -450,7 +450,10 @@ def main():
elif endpoint in ENDPOINTS:
func = ENDPOINTS[endpoint]["func"]
if args:
- result = func(*args)
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func() # endpoint takes no/fewer args - ignore UI default
else:
result = func()
else:
diff --git a/fincept-qt/scripts/akshare_index.py b/fincept-qt/scripts/akshare_index.py
index 18681b5e0..082fad631 100644
--- a/fincept-qt/scripts/akshare_index.py
+++ b/fincept-qt/scripts/akshare_index.py
@@ -38,7 +38,7 @@ def safe_call(func, *args, **kwargs):
result = result.replace([float('inf'), float('-inf')], None)
result = result.where(pd.notna(result), None)
data = result.to_dict(orient='records')
- return {"success": True, "data": data, "count": len(data)}
+ return {"success": True, "data": data, "columns": list(result.columns), "count": len(data)}
elif isinstance(result, (list, dict)):
return {"success": True, "data": result, "count": len(result) if isinstance(result, list) else 1}
else:
@@ -584,7 +584,10 @@ def main():
elif endpoint in ENDPOINTS:
func = ENDPOINTS[endpoint]["func"]
if args:
- result = func(*args)
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func() # endpoint takes no/fewer args - ignore UI default
else:
result = func()
else:
diff --git a/fincept-qt/scripts/akshare_macro.py b/fincept-qt/scripts/akshare_macro.py
index 8efcba6f0..39f4b21ca 100644
--- a/fincept-qt/scripts/akshare_macro.py
+++ b/fincept-qt/scripts/akshare_macro.py
@@ -74,6 +74,7 @@ class MacroEconomicWrapper:
return {
"success": True,
"data": data,
+ "columns": (list(df.columns) if hasattr(df, "columns") else []),
"error": None
}
diff --git a/fincept-qt/scripts/akshare_misc.py b/fincept-qt/scripts/akshare_misc.py
index 16c330ae4..ec93ec7bd 100644
--- a/fincept-qt/scripts/akshare_misc.py
+++ b/fincept-qt/scripts/akshare_misc.py
@@ -54,7 +54,7 @@ class MiscWrapper:
else:
data = df
- return {"success": True, "data": data, "error": None}
+ return {"success": True, "data": data, "columns": (list(df.columns) if hasattr(df, 'columns') else []), "error": None}
except Exception as e:
if attempt == max_retries - 1:
@@ -662,7 +662,10 @@ def main():
func = getattr(wrapper, function_name)
# Parse additional arguments if needed
args = sys.argv[2:] if len(sys.argv) > 2 else []
- result = func(*args) if args else func()
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func()
print(json.dumps(result, cls=DateTimeEncoder, ensure_ascii=True))
else:
print(json.dumps({
diff --git a/fincept-qt/scripts/akshare_news.py b/fincept-qt/scripts/akshare_news.py
index 8b472afed..a60245992 100644
--- a/fincept-qt/scripts/akshare_news.py
+++ b/fincept-qt/scripts/akshare_news.py
@@ -37,7 +37,7 @@ def safe_call(func, *args, **kwargs):
result = result.replace([float("inf"), float("-inf")], None)
result = result.where(pd.notna(result), None)
data = result.to_dict(orient='records')
- return {"success": True, "data": data, "count": len(data)}
+ return {"success": True, "data": data, "columns": list(result.columns), "count": len(data)}
elif isinstance(result, (list, dict)):
return {"success": True, "data": result, "count": len(result) if isinstance(result, list) else 1}
else:
@@ -128,7 +128,10 @@ def main():
elif endpoint in ENDPOINTS:
func = ENDPOINTS[endpoint]["func"]
if args:
- result = func(*args)
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func() # endpoint takes no/fewer args - ignore UI default
else:
result = func()
else:
diff --git a/fincept-qt/scripts/akshare_reits.py b/fincept-qt/scripts/akshare_reits.py
index 952070c06..3f46ebe9a 100644
--- a/fincept-qt/scripts/akshare_reits.py
+++ b/fincept-qt/scripts/akshare_reits.py
@@ -37,7 +37,7 @@ def safe_call(func, *args, **kwargs):
result = result.replace([float("inf"), float("-inf")], None)
result = result.where(pd.notna(result), None)
data = result.to_dict(orient='records')
- return {"success": True, "data": data, "count": len(data)}
+ return {"success": True, "data": data, "columns": list(result.columns), "count": len(data)}
elif isinstance(result, (list, dict)):
return {"success": True, "data": result, "count": len(result) if isinstance(result, list) else 1}
else:
@@ -113,7 +113,10 @@ def main():
elif endpoint in ENDPOINTS:
func = ENDPOINTS[endpoint]["func"]
if args:
- result = func(*args)
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func() # endpoint takes no/fewer args - ignore UI default
else:
result = func()
else:
diff --git a/fincept-qt/scripts/akshare_stocks_board.py b/fincept-qt/scripts/akshare_stocks_board.py
index e72346d24..5f489c48b 100644
--- a/fincept-qt/scripts/akshare_stocks_board.py
+++ b/fincept-qt/scripts/akshare_stocks_board.py
@@ -38,7 +38,7 @@ def safe_call(func, *args, **kwargs):
result = result.replace([float("inf"), float("-inf")], None)
result = result.where(pd.notna(result), None)
data = result.to_dict(orient='records')
- return {"success": True, "data": data, "count": len(data)}
+ return {"success": True, "data": data, "columns": list(result.columns), "count": len(data)}
elif isinstance(result, (list, dict)):
return {"success": True, "data": result, "count": len(result) if isinstance(result, list) else 1}
else:
@@ -379,7 +379,10 @@ def main():
elif endpoint in ENDPOINTS:
func = ENDPOINTS[endpoint]["func"]
if args:
- result = func(*args)
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func() # endpoint takes no/fewer args - ignore UI default
else:
result = func()
else:
diff --git a/fincept-qt/scripts/akshare_stocks_financial.py b/fincept-qt/scripts/akshare_stocks_financial.py
index ef72eb922..61bb0ea09 100644
--- a/fincept-qt/scripts/akshare_stocks_financial.py
+++ b/fincept-qt/scripts/akshare_stocks_financial.py
@@ -38,7 +38,7 @@ def safe_call(func, *args, **kwargs):
result = result.replace([float("inf"), float("-inf")], None)
result = result.where(pd.notna(result), None)
data = result.to_dict(orient='records')
- return {"success": True, "data": data, "count": len(data)}
+ return {"success": True, "data": data, "columns": list(result.columns), "count": len(data)}
elif isinstance(result, (list, dict)):
return {"success": True, "data": result, "count": len(result) if isinstance(result, list) else 1}
else:
@@ -374,7 +374,10 @@ def main():
elif endpoint in ENDPOINTS:
func = ENDPOINTS[endpoint]["func"]
if args:
- result = func(*args)
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func() # endpoint takes no/fewer args - ignore UI default
else:
result = func()
else:
diff --git a/fincept-qt/scripts/akshare_stocks_funds.py b/fincept-qt/scripts/akshare_stocks_funds.py
index 9494fb8e9..e0e5d0a2a 100644
--- a/fincept-qt/scripts/akshare_stocks_funds.py
+++ b/fincept-qt/scripts/akshare_stocks_funds.py
@@ -38,7 +38,7 @@ def safe_call(func, *args, **kwargs):
result = result.replace([float("inf"), float("-inf")], None)
result = result.where(pd.notna(result), None)
data = result.to_dict(orient='records')
- return {"success": True, "data": data, "count": len(data)}
+ return {"success": True, "data": data, "columns": list(result.columns), "count": len(data)}
elif isinstance(result, (list, dict)):
return {"success": True, "data": result, "count": len(result) if isinstance(result, list) else 1}
else:
@@ -434,7 +434,10 @@ def main():
elif endpoint in ENDPOINTS:
func = ENDPOINTS[endpoint]["func"]
if args:
- result = func(*args)
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func() # endpoint takes no/fewer args - ignore UI default
else:
result = func()
else:
diff --git a/fincept-qt/scripts/akshare_stocks_historical.py b/fincept-qt/scripts/akshare_stocks_historical.py
index a8bd83a83..3eea4a2b0 100644
--- a/fincept-qt/scripts/akshare_stocks_historical.py
+++ b/fincept-qt/scripts/akshare_stocks_historical.py
@@ -38,7 +38,7 @@ def safe_call(func, *args, **kwargs):
result = result.replace([float("inf"), float("-inf")], None)
result = result.where(pd.notna(result), None)
data = result.to_dict(orient='records')
- return {"success": True, "data": data, "count": len(data)}
+ return {"success": True, "data": data, "columns": list(result.columns), "count": len(data)}
elif isinstance(result, (list, dict)):
return {"success": True, "data": result, "count": len(result) if isinstance(result, list) else 1}
else:
@@ -434,7 +434,10 @@ def main():
elif endpoint in ENDPOINTS:
func = ENDPOINTS[endpoint]["func"]
if args:
- result = func(*args)
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func() # endpoint takes no/fewer args - ignore UI default
else:
result = func()
else:
diff --git a/fincept-qt/scripts/akshare_stocks_holders.py b/fincept-qt/scripts/akshare_stocks_holders.py
index f7282296b..5e9a9d6f4 100644
--- a/fincept-qt/scripts/akshare_stocks_holders.py
+++ b/fincept-qt/scripts/akshare_stocks_holders.py
@@ -38,7 +38,7 @@ def safe_call(func, *args, **kwargs):
result = result.replace([float("inf"), float("-inf")], None)
result = result.where(pd.notna(result), None)
data = result.to_dict(orient='records')
- return {"success": True, "data": data, "count": len(data)}
+ return {"success": True, "data": data, "columns": list(result.columns), "count": len(data)}
elif isinstance(result, (list, dict)):
return {"success": True, "data": result, "count": len(result) if isinstance(result, list) else 1}
else:
@@ -394,7 +394,10 @@ def main():
elif endpoint in ENDPOINTS:
func = ENDPOINTS[endpoint]["func"]
if args:
- result = func(*args)
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func() # endpoint takes no/fewer args - ignore UI default
else:
result = func()
else:
diff --git a/fincept-qt/scripts/akshare_stocks_hot.py b/fincept-qt/scripts/akshare_stocks_hot.py
index 2b98acb0e..d2bd73522 100644
--- a/fincept-qt/scripts/akshare_stocks_hot.py
+++ b/fincept-qt/scripts/akshare_stocks_hot.py
@@ -38,7 +38,7 @@ def safe_call(func, *args, **kwargs):
result = result.replace([float("inf"), float("-inf")], None)
result = result.where(pd.notna(result), None)
data = result.to_dict(orient='records')
- return {"success": True, "data": data, "count": len(data)}
+ return {"success": True, "data": data, "columns": list(result.columns), "count": len(data)}
elif isinstance(result, (list, dict)):
return {"success": True, "data": result, "count": len(result) if isinstance(result, list) else 1}
else:
@@ -436,7 +436,10 @@ def main():
elif endpoint in ENDPOINTS:
func = ENDPOINTS[endpoint]["func"]
if args:
- result = func(*args)
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func() # endpoint takes no/fewer args - ignore UI default
else:
result = func()
else:
diff --git a/fincept-qt/scripts/akshare_stocks_margin.py b/fincept-qt/scripts/akshare_stocks_margin.py
index 30b704a0f..c5c152bb4 100644
--- a/fincept-qt/scripts/akshare_stocks_margin.py
+++ b/fincept-qt/scripts/akshare_stocks_margin.py
@@ -38,7 +38,7 @@ def safe_call(func, *args, **kwargs):
result = result.replace([float("inf"), float("-inf")], None)
result = result.where(pd.notna(result), None)
data = result.to_dict(orient='records')
- return {"success": True, "data": data, "count": len(data)}
+ return {"success": True, "data": data, "columns": list(result.columns), "count": len(data)}
elif isinstance(result, (list, dict)):
return {"success": True, "data": result, "count": len(result) if isinstance(result, list) else 1}
else:
@@ -399,7 +399,10 @@ def main():
elif endpoint in ENDPOINTS:
func = ENDPOINTS[endpoint]["func"]
if args:
- result = func(*args)
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func() # endpoint takes no/fewer args - ignore UI default
else:
result = func()
else:
diff --git a/fincept-qt/scripts/akshare_stocks_realtime.py b/fincept-qt/scripts/akshare_stocks_realtime.py
index 8ded1a99a..1df3d7bf8 100644
--- a/fincept-qt/scripts/akshare_stocks_realtime.py
+++ b/fincept-qt/scripts/akshare_stocks_realtime.py
@@ -38,7 +38,7 @@ def safe_call(func, *args, **kwargs):
result = result.replace([float("inf"), float("-inf")], None)
result = result.where(pd.notna(result), None)
data = result.to_dict(orient='records')
- return {"success": True, "data": data, "count": len(data)}
+ return {"success": True, "data": data, "columns": list(result.columns), "count": len(data)}
elif isinstance(result, (list, dict)):
return {"success": True, "data": result, "count": len(result) if isinstance(result, list) else 1}
else:
@@ -389,7 +389,10 @@ def main():
elif endpoint in ENDPOINTS:
func = ENDPOINTS[endpoint]["func"]
if args:
- result = func(*args)
+ try:
+ result = func(*args)
+ except TypeError:
+ result = func() # endpoint takes no/fewer args - ignore UI default
else:
result = func()
else:
diff --git a/fincept-qt/src/app/WindowFrame_Setup.cpp b/fincept-qt/src/app/WindowFrame_Setup.cpp
index 87593b020..b6964cd7d 100644
--- a/fincept-qt/src/app/WindowFrame_Setup.cpp
+++ b/fincept-qt/src/app/WindowFrame_Setup.cpp
@@ -71,6 +71,7 @@
#include "screens/quantlib/QuantLibScreen.h"
#include "screens/relationship_map/RelationshipMapScreen.h"
#include "screens/report_builder/ReportBuilderScreen.h"
+#include "screens/screener/ScreenerScreen.h"
#include "screens/settings/SettingsScreen.h"
#include "screens/support/SupportScreen.h"
#include "screens/surface_analytics/SurfaceAnalyticsScreen.h"
@@ -263,6 +264,7 @@ void WindowFrame::setup_dock_screens() {
dock_router_->register_factory("derivatives", []() { return new screens::DerivativesScreen; });
dock_router_->register_factory("fno", []() { return new screens::fno::FnoScreen; });
dock_router_->register_factory("equity_research", []() { return new screens::EquityResearchScreen; });
+ dock_router_->register_factory("screener", []() { return new screens::ScreenerScreen; });
dock_router_->register_factory("ma_analytics", []() { return new screens::MAAnalyticsScreen; });
dock_router_->register_factory("alt_investments", []() { return new screens::AltInvestmentsScreen; });
dock_router_->register_factory("geopolitics", []() { return new screens::GeopoliticsScreen; });
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index 0a2ad2d6f..e056e908c 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -449,6 +449,9 @@ int main(int argc, char* argv[]) {
if (auto creds = fincept::services::prediction::PredictionCredentialStore::load_kalshi()) {
ks->set_credentials(*creds);
}
+ // Register the Kalshi WS producer + push-only topic policies
+ // (prediction:kalshi:price:*, prediction:kalshi:orderbook:*) with the hub.
+ ks->ensure_registered_with_hub();
}
if (auto* fi = reg.adapter(QStringLiteral("fincept"))) {
fi->ensure_registered_with_hub();
diff --git a/fincept-qt/src/core/events/EventBus.cpp b/fincept-qt/src/core/events/EventBus.cpp
index 1b66d54a9..7a49fb92b 100644
--- a/fincept-qt/src/core/events/EventBus.cpp
+++ b/fincept-qt/src/core/events/EventBus.cpp
@@ -1,5 +1,7 @@
#include "core/events/EventBus.h"
+#include <QMutexLocker>
+
namespace fincept {
EventBus& EventBus::instance() {
@@ -8,22 +10,36 @@ EventBus& EventBus::instance() {
}
EventBus::HandlerId EventBus::subscribe(const QString& event, Handler handler) {
+ QMutexLocker lock(&mutex_);
HandlerId id = next_id_++;
subscriptions_.append({id, event, std::move(handler)});
return id;
}
void EventBus::unsubscribe(HandlerId id) {
+ QMutexLocker lock(&mutex_);
subscriptions_.removeIf([id](const Subscription& s) { return s.id == id; });
}
void EventBus::publish(const QString& event, const QVariantMap& data) {
emit eventPublished(event, data);
- for (const auto& sub : subscriptions_) {
- if (sub.event == event) {
- sub.handler(data);
+
+ // Snapshot the matching handlers under the lock, then invoke them OUTSIDE the
+ // lock. publish() can run on worker threads (e.g. a workflow "MCP Tool" node
+ // executing on a QtConcurrent pool thread) while subscribe()/unsubscribe()
+ // mutate subscriptions_ on the main thread — iterating the live QList raced a
+ // reallocation → use-after-free. Invoking outside the lock also lets a
+ // handler safely (un)subscribe without deadlocking or invalidating the loop.
+ QList<Handler> matched;
+ {
+ QMutexLocker lock(&mutex_);
+ for (const auto& sub : subscriptions_) {
+ if (sub.event == event)
+ matched.append(sub.handler);
}
}
+ for (const auto& handler : matched)
+ handler(data);
}
} // namespace fincept
diff --git a/fincept-qt/src/core/events/EventBus.h b/fincept-qt/src/core/events/EventBus.h
index 2a5b8ad63..84e1a92a6 100644
--- a/fincept-qt/src/core/events/EventBus.h
+++ b/fincept-qt/src/core/events/EventBus.h
@@ -1,6 +1,7 @@
#pragma once
#include <QHash>
#include <QList>
+#include <QMutex>
#include <QObject>
#include <QVariantMap>
@@ -36,6 +37,9 @@ class EventBus : public QObject {
QList<Subscription> subscriptions_;
HandlerId next_id_ = 1;
+ // Guards subscriptions_/next_id_. publish() may run on worker threads while
+ // subscribe()/unsubscribe() run on the main thread (see EventBus.cpp).
+ QMutex mutex_;
};
} // namespace fincept
diff --git a/fincept-qt/src/core/net/NetSpeedMeter.cpp b/fincept-qt/src/core/net/NetSpeedMeter.cpp
index 7d53fbd8b..11a920fb2 100644
--- a/fincept-qt/src/core/net/NetSpeedMeter.cpp
+++ b/fincept-qt/src/core/net/NetSpeedMeter.cpp
@@ -7,16 +7,14 @@
#if defined(Q_OS_WIN)
// The project defines WIN32_LEAN_AND_MEAN globally, which strips winsock from
-// <windows.h>. Pull the pieces we need explicitly in the right order so
-// MIB_IF_ROW2 / GetIfTable2 (declared in netioapi.h) compile cleanly.
-# ifndef _WINSOCKAPI_
-# define _WINSOCKAPI_ // prevent windows.h from including winsock1
-# endif
-# include <iphlpapi.h>
-# include <netioapi.h>
-# include <windows.h>
+// <windows.h>. iphlpapi/netioapi need the base Windows + winsock2 types
+// already declared (SDK 26100+ headers are not self-sufficient), so the
+// order below is mandatory: winsock2 → windows → iphlpapi → netioapi.
# include <winsock2.h>
# include <ws2tcpip.h>
+# include <windows.h>
+# include <iphlpapi.h>
+# include <netioapi.h>
# pragma comment(lib, "iphlpapi.lib")
#elif defined(Q_OS_MACOS)
# include <ifaddrs.h>
diff --git a/fincept-qt/src/mcp/McpManager.cpp b/fincept-qt/src/mcp/McpManager.cpp
index f2948c608..d1179f64b 100644
--- a/fincept-qt/src/mcp/McpManager.cpp
+++ b/fincept-qt/src/mcp/McpManager.cpp
@@ -8,7 +8,9 @@
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
+#include <QPointer>
#include <QUuid>
+#include <QtConcurrent/QtConcurrent>
namespace fincept::mcp {
@@ -290,36 +292,64 @@ void McpManager::stop_health_check() {
}
void McpManager::do_health_check() {
- QMutexLocker lock(&mutex_);
- QStringList running_ids = clients_.keys();
- lock.unlock();
+ // Don't overlap passes: a slow ping could still be running when the timer
+ // fires again.
+ bool expected = false;
+ if (!health_check_running_.compare_exchange_strong(expected, true))
+ return;
- for (const auto& id : running_ids) {
- QMutexLocker l(&mutex_);
- if (!clients_.contains(id))
- continue;
- McpClient* client = clients_[id].get();
- l.unlock();
-
- auto r = client->ping();
- if (r.is_err()) {
- LOG_WARN(TAG, "Health check failed for " + id + ": " + QString::fromStdString(r.error()));
-
- int attempts = restart_attempts_.value(id, 0);
- if (attempts < MAX_RESTART_ATTEMPTS) {
- restart_attempts_[id] = attempts + 1;
- LOG_INFO(TAG, QString("Restarting server %1 (attempt %2/%3)")
- .arg(id)
- .arg(attempts + 1)
- .arg(MAX_RESTART_ATTEMPTS));
- restart_server(id);
- } else {
- LOG_ERROR(TAG, "Server " + id + " exceeded max restart attempts — giving up");
- McpServerRepository::instance().set_status(id, "error");
- }
- } else {
- restart_attempts_.remove(id); // reset on success
+ // Snapshot the clients under the lock — shared_ptr copies keep each alive
+ // across its ping() even if stop_server() removes the map entry meanwhile.
+ QVector<QPair<QString, std::shared_ptr<McpClient>>> targets;
+ {
+ QMutexLocker lock(&mutex_);
+ targets.reserve(clients_.size());
+ for (auto it = clients_.constBegin(); it != clients_.constEnd(); ++it)
+ if (it.value())
+ targets.append({it.key(), it.value()});
+ }
+ if (targets.isEmpty()) {
+ health_check_running_ = false;
+ return;
+ }
+
+ // Ping OFF the UI thread. ping() blocks up to ~5s per server, so looping on
+ // the UI thread froze the whole terminal every health tick (P1). The
+ // follow-up (restart) is marshalled back to the main thread in
+ // on_health_result() because it manages a thread-affine QProcess.
+ QPointer<McpManager> self = this;
+ (void)QtConcurrent::run([self, targets]() {
+ for (const auto& t : targets) {
+ const bool ok = !t.second->ping().is_err();
+ if (!self)
+ return;
+ const QString id = t.first;
+ QMetaObject::invokeMethod(
+ self, [self, id, ok]() { if (self) self->on_health_result(id, ok); }, Qt::QueuedConnection);
}
+ if (self)
+ QMetaObject::invokeMethod(
+ self, [self]() { if (self) self->health_check_running_ = false; }, Qt::QueuedConnection);
+ });
+}
+
+void McpManager::on_health_result(const QString& id, bool ok) {
+ // Runs on the main thread: safe to restart (QProcess) and touch
+ // restart_attempts_ (only mutated here).
+ if (ok) {
+ restart_attempts_.remove(id); // reset on success
+ return;
+ }
+ LOG_WARN(TAG, "Health check failed for " + id);
+ const int attempts = restart_attempts_.value(id, 0);
+ if (attempts < MAX_RESTART_ATTEMPTS) {
+ restart_attempts_[id] = attempts + 1;
+ LOG_INFO(TAG,
+ QString("Restarting server %1 (attempt %2/%3)").arg(id).arg(attempts + 1).arg(MAX_RESTART_ATTEMPTS));
+ restart_server(id);
+ } else {
+ LOG_ERROR(TAG, "Server " + id + " exceeded max restart attempts — giving up");
+ McpServerRepository::instance().set_status(id, "error");
}
}
@@ -337,12 +367,19 @@ std::vector<ExternalTool> McpManager::get_all_external_tools() {
Result<QJsonObject> McpManager::call_external_tool(const QString& server_id, const QString& tool_name,
const QJsonObject& args) {
- QMutexLocker lock(&mutex_);
- McpClient* client = get_client(server_id);
- if (!client)
- return Result<QJsonObject>::err("Server not running: " + server_id.toStdString());
- lock.unlock();
-
+ // Hold a shared_ptr COPY across the (blocking, up to ~120s) call. This runs
+ // on a QtConcurrent pool thread while stop_server()/restart_server() can run
+ // on the main thread and erase the map entry; the previous raw pointer then
+ // outlived the McpClient it pointed at → use-after-free. The copy keeps the
+ // object alive until the call returns.
+ std::shared_ptr<McpClient> client;
+ {
+ QMutexLocker lock(&mutex_);
+ auto it = clients_.find(server_id);
+ if (it == clients_.end() || !it.value())
+ return Result<QJsonObject>::err("Server not running: " + server_id.toStdString());
+ client = it.value();
+ }
return client->call_tool(tool_name, args);
}
diff --git a/fincept-qt/src/mcp/McpManager.h b/fincept-qt/src/mcp/McpManager.h
index 3d9189630..b1ce3a538 100644
--- a/fincept-qt/src/mcp/McpManager.h
+++ b/fincept-qt/src/mcp/McpManager.h
@@ -10,6 +10,7 @@
#include <QObject>
#include <QTimer>
+#include <atomic>
#include <memory>
#include <vector>
@@ -68,11 +69,15 @@ class McpManager : public QObject {
QTimer* health_timer_ = nullptr;
mutable QMutex mutex_;
+ std::atomic<bool> health_check_running_{false}; // guards against overlapping async health passes
static constexpr int MAX_RESTART_ATTEMPTS = 3;
McpClient* get_client(const QString& id) const;
void refresh_tools_for(const QString& id);
+ // Handles one server's ping result on the MAIN thread (restart uses QProcess,
+ // which is thread-affine and must stay on the thread that owns it).
+ void on_health_result(const QString& id, bool ok);
private slots:
void do_health_check();
diff --git a/fincept-qt/src/mcp/McpService.cpp b/fincept-qt/src/mcp/McpService.cpp
index 468d1f723..02e4e6f2b 100644
--- a/fincept-qt/src/mcp/McpService.cpp
+++ b/fincept-qt/src/mcp/McpService.cpp
@@ -6,6 +6,7 @@
#include "core/logging/Logger.h"
#include "mcp/McpManager.h"
#include "mcp/McpProvider.h"
+#include "mcp/TerminalMcpBridge.h"
#include "mcp/ToolRetriever.h"
#include <QCoreApplication>
@@ -475,7 +476,15 @@ QFuture<ToolResult> McpService::execute_openai_function_async(const QString& fun
// even if each one blocks its own pool thread. Phase 5's dispatcher
// unification will use these futures with QtFuture::whenAll to join
// a round of tool calls in parallel.
- return QtConcurrent::run([server_id, tool_name, args]() -> ToolResult {
+ // Carry the agent-gating flags across the thread hop. execute_tool() runs
+ // the auth check, which reads TerminalMcpBridge's thread_local flags; those
+ // default to false on the pool thread, so without re-establishing them an
+ // agent-originated external call would be mis-classified as a chat call and
+ // skip the destructive-tool gate.
+ const bool call_in_progress = TerminalMcpBridge::is_call_in_progress();
+ const bool destructive_allowed = TerminalMcpBridge::is_destructive_allowed();
+ return QtConcurrent::run([server_id, tool_name, args, call_in_progress, destructive_allowed]() -> ToolResult {
+ TerminalMcpBridge::ScopedCallFlags flags(call_in_progress, destructive_allowed);
return McpService::instance().execute_tool(server_id, tool_name, args);
});
}
diff --git a/fincept-qt/src/mcp/TerminalMcpBridge.cpp b/fincept-qt/src/mcp/TerminalMcpBridge.cpp
index 731a93f78..cd59d7799 100644
--- a/fincept-qt/src/mcp/TerminalMcpBridge.cpp
+++ b/fincept-qt/src/mcp/TerminalMcpBridge.cpp
@@ -59,6 +59,19 @@ struct CallFlagGuard {
};
} // namespace
+// Public RAII helper — re-establishes the (thread_local) gating flags on the
+// pool thread that runs an external tool, then restores the prior values.
+TerminalMcpBridge::ScopedCallFlags::ScopedCallFlags(bool call_in_progress, bool destructive_allowed)
+ : prev_in_progress_(tls_call_in_progress), prev_destructive_(tls_destructive_allowed) {
+ tls_call_in_progress = call_in_progress;
+ tls_destructive_allowed = destructive_allowed;
+}
+
+TerminalMcpBridge::ScopedCallFlags::~ScopedCallFlags() {
+ tls_call_in_progress = prev_in_progress_;
+ tls_destructive_allowed = prev_destructive_;
+}
+
TerminalMcpBridge& TerminalMcpBridge::instance() {
static TerminalMcpBridge s;
return s;
@@ -77,6 +90,7 @@ bool TerminalMcpBridge::start() {
if (!server_->listen(QHostAddress::LocalHost, 0)) {
LOG_ERROR(TAG, "Failed to bind 127.0.0.1: " + server_->errorString());
+ emit bridge_error(QStringLiteral("Failed to bind terminal MCP bridge: ") + server_->errorString());
server_->deleteLater();
server_ = nullptr;
return false;
diff --git a/fincept-qt/src/mcp/TerminalMcpBridge.h b/fincept-qt/src/mcp/TerminalMcpBridge.h
index 2a48dc76f..4682ee30b 100644
--- a/fincept-qt/src/mcp/TerminalMcpBridge.h
+++ b/fincept-qt/src/mcp/TerminalMcpBridge.h
@@ -67,6 +67,24 @@ class TerminalMcpBridge : public QObject {
/// token. Only meaningful while is_call_in_progress() is true.
static bool is_destructive_allowed();
+ /// RAII helper that re-establishes the agent-gating flags on ANOTHER thread.
+ /// The flags above are thread_local, so when an external tool call hops onto
+ /// a QtConcurrent pool thread (McpService::execute_openai_function_async) the
+ /// agent context is lost and the auth checker would treat it as a chat call
+ /// — bypassing the destructive-tool gate. Capture the flags on the bridge
+ /// thread, then construct one of these inside the pool-thread lambda.
+ class ScopedCallFlags {
+ public:
+ ScopedCallFlags(bool call_in_progress, bool destructive_allowed);
+ ~ScopedCallFlags();
+ ScopedCallFlags(const ScopedCallFlags&) = delete;
+ ScopedCallFlags& operator=(const ScopedCallFlags&) = delete;
+
+ private:
+ bool prev_in_progress_;
+ bool prev_destructive_;
+ };
+
/// Build the catalog payload that AgentService injects into
/// `config["terminal_tools"]`. Output shape (per item):
/// { "name": str, "description": str, "inputSchema": {JSON Schema} }
diff --git a/fincept-qt/src/mcp/tools/EdgarTools.cpp b/fincept-qt/src/mcp/tools/EdgarTools.cpp
index f6fe0815f..c58caa8c0 100644
--- a/fincept-qt/src/mcp/tools/EdgarTools.cpp
+++ b/fincept-qt/src/mcp/tools/EdgarTools.cpp
@@ -1,5 +1,5 @@
// EdgarTools.cpp — SEC EDGAR MCP tools
-// Calls Analytics/sec_edgar/edgar_fetcher.py directly via PythonRunner.
+// Calls mcp/edgar/main.py directly via PythonRunner.
// Completely separate from M&A Analytics.
#include "mcp/tools/EdgarTools.h"
diff --git a/fincept-qt/src/mcp/tools/FileManagerTools.cpp b/fincept-qt/src/mcp/tools/FileManagerTools.cpp
index 3a11ab555..06012a4dc 100644
--- a/fincept-qt/src/mcp/tools/FileManagerTools.cpp
+++ b/fincept-qt/src/mcp/tools/FileManagerTools.cpp
@@ -277,6 +277,43 @@ std::vector<ToolDef> get_file_manager_tools() {
QFileInfo fi(src);
if (!fi.exists() || !fi.isFile())
return ToolResult::fail("File not found at source_path");
+
+ // Security: refuse to import files that look like credentials/secrets.
+ // Without this an LLM could import ~/.aws/credentials, a .env, or an
+ // SSH key into managed storage and then read it straight back via
+ // read_file_contents — a secret-exfiltration path.
+ {
+ const QString lp = QDir::fromNativeSeparators(src).toLower();
+ const QString base = fi.fileName().toLower();
+ static const QStringList kSecretDirs = {"/.ssh/", "/.aws/", "/.gnupg/", "/.kube/",
+ "/.docker/", "/.azure/", "/.config/gcloud/"};
+ static const QStringList kSecretNames = {".env", "credentials", "id_rsa", "id_ed25519",
+ "id_dsa", "id_ecdsa", ".netrc", ".pgpass",
+ ".git-credentials", ".npmrc"};
+ static const QStringList kSecretExts = {".pem", ".key", ".pfx", ".p12", ".keystore", ".jks", ".ppk"};
+ bool secret = false;
+ for (const auto& d : kSecretDirs)
+ if (lp.contains(d)) {
+ secret = true;
+ break;
+ }
+ if (!secret)
+ for (const auto& n : kSecretNames)
+ if (base == n || base.startsWith(n)) {
+ secret = true;
+ break;
+ }
+ if (!secret)
+ for (const auto& e : kSecretExts)
+ if (base.endsWith(e)) {
+ secret = true;
+ break;
+ }
+ if (secret)
+ return ToolResult::fail("Refusing to import a file that looks like a credential or secret "
+ "(SSH/AWS/GPG key, .env, credentials, .pem/.key, etc.).");
+ }
+
const QString id = services::FileManagerService::instance().import_file(src, screen);
if (id.isEmpty())
return ToolResult::fail("Import failed");
@@ -314,6 +351,15 @@ std::vector<ToolDef> get_file_manager_tools() {
const QString screen = args["source_screen"].toString().trimmed();
if (name.isEmpty())
return ToolResult::fail("Missing 'name'");
+ // Security (path traversal): `name` is used to build a path under
+ // storage_dir, and QDir::filePath()/QFile::remove()/rename() do NOT
+ // strip ".." or an absolute prefix — a name like "../../secret.txt"
+ // would delete then overwrite an arbitrary file on disk. Require a
+ // plain filename with no path component.
+ const QString safe_name = QFileInfo(name).fileName();
+ if (safe_name.isEmpty() || safe_name != name || safe_name == QLatin1String(".") ||
+ safe_name == QLatin1String(".."))
+ return ToolResult::fail("Invalid 'name': must be a plain filename, not a path");
auto& svc = services::FileManagerService::instance();
// Stage the content in a temp file inside storage_dir, then import.
@@ -322,7 +368,7 @@ std::vector<ToolDef> get_file_manager_tools() {
return ToolResult::fail("Cannot create storage dir");
const QString tmp_path =
- dir.filePath(QStringLiteral(".incoming_%1_%2").arg(QDateTime::currentMSecsSinceEpoch()).arg(name));
+ dir.filePath(QStringLiteral(".incoming_%1_%2").arg(QDateTime::currentMSecsSinceEpoch()).arg(safe_name));
QFile f(tmp_path);
if (!f.open(QIODevice::WriteOnly | QIODevice::Text))
return ToolResult::fail("Cannot open temp file for writing");
@@ -335,7 +381,7 @@ std::vector<ToolDef> get_file_manager_tools() {
// Rename to the desired display name so import sees the right
// original-name (FileManagerService uses QFileInfo::fileName()).
- const QString staged = dir.filePath(name);
+ const QString staged = dir.filePath(safe_name);
QFile::remove(staged);
QFile::rename(tmp_path, staged);
diff --git a/fincept-qt/src/mcp/tools/LiveTradingTools.cpp b/fincept-qt/src/mcp/tools/LiveTradingTools.cpp
index b562384ed..c22f1c39c 100644
--- a/fincept-qt/src/mcp/tools/LiveTradingTools.cpp
+++ b/fincept-qt/src/mcp/tools/LiveTradingTools.cpp
@@ -281,6 +281,19 @@ std::vector<ToolDef> get_live_trading_tools() {
order.price = args["price"].toDouble(0.0);
order.product_type = parse_product(args["product"].toString("MIS"));
+ // Semi-Auto gate: a live smart order places a REAL position-delta
+ // order, so the AI must not execute it unattended. Unlike
+ // live_place_order this previously went straight to place_smart_order,
+ // bypassing the approval queue. The queue's executor only replays
+ // UnifiedOrders (not position-aware smart orders), so we can't safely
+ // queue this one — refuse in Semi-Auto rather than bypass the gate.
+ if (ActionCenter::instance().should_queue(account_id, "smartorder")) {
+ return ToolResult::fail(
+ "This account is in Semi-Auto approval mode. Position-aware smart orders cannot be queued for "
+ "approval yet — use live_place_order (which supports the approval queue), or switch the account "
+ "out of Semi-Auto to place smart orders directly.");
+ }
+
auto resp = UnifiedTrading::instance().place_smart_order(account_id, order);
if (!resp.success)
return ToolResult::fail(resp.error.isEmpty() ? "Smart order failed" : resp.error);
diff --git a/fincept-qt/src/mcp/tools/MAAnalyticsTools.cpp b/fincept-qt/src/mcp/tools/MAAnalyticsTools.cpp
index c9d586096..76ef9849f 100644
--- a/fincept-qt/src/mcp/tools/MAAnalyticsTools.cpp
+++ b/fincept-qt/src/mcp/tools/MAAnalyticsTools.cpp
@@ -137,10 +137,11 @@ static ToolDef make_ma_cmd_tool(const char* name, const char* desc, const QStrin
return t;
}
-// The keyless data-connector manifest (auto-generated). Defines kDataConnectorManifest.
+// The data-connector manifest (auto-generated). Defines kDataConnectorManifest
+// (127 keyed + 63 keyless = 190 connectors; the loop below iterates all of them).
#include "mcp/tools/DataConnectorManifest.inc"
-// Build one dispatcher tool per keyless `scripts/*_data.py` connector from the
+// Build one dispatcher tool per `scripts/*_data.py` connector from the
// embedded manifest. Each connector shares the uniform positional ABI
// `python <script> <command> [args…] → JSON`; the tool exposes the command as an
// enum and forwards optional positional args. Category "data-connectors".
diff --git a/fincept-qt/src/mcp/tools/QuantLibApiTools.h b/fincept-qt/src/mcp/tools/QuantLibApiTools.h
deleted file mode 100644
index 5f8071ebd..000000000
--- a/fincept-qt/src/mcp/tools/QuantLibApiTools.h
+++ /dev/null
@@ -1,8 +0,0 @@
-#pragma once
-#include "mcp/McpTypes.h"
-
-#include <vector>
-
-namespace fincept::mcp::tools {
-std::vector<ToolDef> get_quantlib_api_tools();
-} // namespace fincept::mcp::tools
diff --git a/fincept-qt/src/network/http/HttpClient.cpp b/fincept-qt/src/network/http/HttpClient.cpp
index c7026fdfc..e2c0a1768 100644
--- a/fincept-qt/src/network/http/HttpClient.cpp
+++ b/fincept-qt/src/network/http/HttpClient.cpp
@@ -44,6 +44,12 @@ QNetworkRequest HttpClient::build_request(const QString& url) const {
void HttpClient::handle_reply(QNetworkReply* reply, JsonCallback callback, const QObject* context) {
// Connect to caller-provided context so caller destruction auto-disconnects before the lambda fires.
const QObject* receiver = context ? context : static_cast<const QObject*>(this);
+ // Safety net: guarantee the reply is always deleted. If `context` is
+ // destroyed before the reply finishes, Qt auto-disconnects the callback
+ // lambda below and its reply->deleteLater() would never run → the reply
+ // leaks until app exit. deleteLater() is idempotent, so a double-call when
+ // the lambda also runs is harmless.
+ connect(reply, &QNetworkReply::finished, reply, &QObject::deleteLater);
connect(reply, &QNetworkReply::finished, receiver, [reply, cb = std::move(callback)]() {
reply->deleteLater();
diff --git a/fincept-qt/src/network/websocket/WebSocketClient.cpp b/fincept-qt/src/network/websocket/WebSocketClient.cpp
index d57a898a1..25becb1b5 100644
--- a/fincept-qt/src/network/websocket/WebSocketClient.cpp
+++ b/fincept-qt/src/network/websocket/WebSocketClient.cpp
@@ -82,7 +82,7 @@ void WebSocketClient::connect_to(const QString& url) {
self->url_ = u;
self->reconnect_attempts_ = 0;
self->reconnect_stopped_ = false; // a fresh connect re-enables auto-reconnect
- LOG_INFO(kTag, QString("[%1] Connecting to %2").arg(thread_label(), u));
+ LOG_INFO(kTag, QString("[%1] Connecting to %2").arg(thread_label(), redact_url(u)));
self->socket_->open(QUrl(u));
});
}
@@ -136,14 +136,14 @@ bool WebSocketClient::is_connected() const {
}
void WebSocketClient::on_connected() {
- LOG_INFO(kTag, QString("[%1] Connected to %2").arg(thread_label(), url_));
+ LOG_INFO(kTag, QString("[%1] Connected to %2").arg(thread_label(), redact_url(url_)));
reconnect_attempts_ = 0;
emit connected();
}
void WebSocketClient::on_disconnected() {
LOG_WARN(kTag, QString("[%1] Disconnected from %2 (state=%3)")
- .arg(thread_label(), url_)
+ .arg(thread_label(), redact_url(url_))
.arg(static_cast<int>(socket_ ? socket_->state() : QAbstractSocket::UnconnectedState)));
emit disconnected();
if (!reconnect_stopped_ && reconnect_attempts_ < MAX_RECONNECT_ATTEMPTS) {
@@ -158,7 +158,7 @@ void WebSocketClient::on_disconnected() {
LOG_ERROR(kTag, QString("[%1] Max reconnect attempts (%2) reached for %3")
.arg(thread_label())
.arg(MAX_RECONNECT_ATTEMPTS)
- .arg(url_));
+ .arg(redact_url(url_)));
}
}
diff --git a/fincept-qt/src/python/ScriptCatalog.cpp b/fincept-qt/src/python/ScriptCatalog.cpp
deleted file mode 100644
index 74d6cdd50..000000000
--- a/fincept-qt/src/python/ScriptCatalog.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-#include "python/ScriptCatalog.h"
-
-namespace fincept::python {
-
-ScriptCatalog& ScriptCatalog::instance() {
- static ScriptCatalog s;
- return s;
-}
-
-ScriptCatalog::ScriptCatalog() {
- seed_builtins();
-}
-
-void ScriptCatalog::register_entry(CatalogEntry entry) {
- const QString name = entry.name;
- entries_.insert(name, std::move(entry));
-}
-
-std::optional<CatalogEntry> ScriptCatalog::resolve(const QString& name) const {
- auto it = entries_.find(name);
- if (it == entries_.end())
- return std::nullopt;
- return it.value();
-}
-
-QStringList ScriptCatalog::names() const {
- return entries_.keys();
-}
-
-void ScriptCatalog::seed_builtins() {
- // Hot-path scripts that multiple services hardcode today. Each migration
- // PR moves a few more entries here and replaces the literal string at the
- // callsite with `ScriptCatalog::instance().resolve(name)->relpath`.
- register_entry({QStringLiteral("market.yfinance"), QStringLiteral("yfinance_data.py"), VenvId::Numpy2});
- register_entry(
- {QStringLiteral("agent.finagent_core"), QStringLiteral("agents/finagent_core/main.py"), VenvId::Numpy2});
- register_entry(
- {QStringLiteral("market.asia_china"), QStringLiteral("china_market_data_service.py"), VenvId::Numpy2});
- // Numpy1-only — vectorbt, gluonts, financepy backtests live here.
- register_entry({QStringLiteral("backtest.vectorbt"),
- QStringLiteral("Analytics/backtesting/vectorbt/vectorbt_provider.py"), VenvId::Numpy1});
-}
-
-} // namespace fincept::python
diff --git a/fincept-qt/src/python/ScriptCatalog.h b/fincept-qt/src/python/ScriptCatalog.h
deleted file mode 100644
index aab75ec7d..000000000
--- a/fincept-qt/src/python/ScriptCatalog.h
+++ /dev/null
@@ -1,62 +0,0 @@
-#pragma once
-// Phase 11 scaffolding — registry over the 1,423 scripts under `scripts/`.
-//
-// Today, ~10+ services hardcode literal paths:
-// PythonRunner::run("yfinance_data.py", args)
-// PythonRunner::run("agents/finagent_core/main.py", args)
-//
-// Renaming a script breaks compilation across the codebase. `ScriptCatalog`
-// resolves logical names to (rel_path, venv) tuples. Callers reference scripts
-// by name; the catalog is the single source of truth for file location and
-// runtime requirements.
-//
-// The catalog seeds itself with the small set of hot-path scripts. New entries
-// register from anywhere via `register_entry`. A future build step can
-// auto-generate `scripts/catalog.json` and load it here.
-
-#include <QHash>
-#include <QString>
-#include <QStringList>
-
-#include <optional>
-
-namespace fincept::python {
-
-/// Which managed venv a script needs.
-/// Mirrors `PythonSetupManager`'s two venvs.
-enum class VenvId {
- Numpy2, ///< Default — pyportfolioopt-free, modern NumPy.
- Numpy1, ///< Legacy — vectorbt, gluonts, financepy, ffn, functime.
-};
-
-struct CatalogEntry {
- QString name; ///< Canonical logical name (e.g. "market.yfinance").
- QString relpath; ///< Path under fincept-qt/scripts/ (forward slashes).
- VenvId venv = VenvId::Numpy2;
-};
-
-/// Process-global script catalog.
-///
-/// First call seeds with hot-path entries. Additional entries register at
-/// any time (typically once at startup by the owning service).
-class ScriptCatalog {
- public:
- static ScriptCatalog& instance();
-
- /// Register or replace an entry. Idempotent.
- void register_entry(CatalogEntry entry);
-
- /// Look up by logical name. Returns std::nullopt if not registered.
- std::optional<CatalogEntry> resolve(const QString& name) const;
-
- /// All registered logical names.
- QStringList names() const;
-
- private:
- ScriptCatalog();
- void seed_builtins();
-
- QHash<QString, CatalogEntry> entries_;
-};
-
-} // namespace fincept::python
diff --git a/fincept-qt/src/screens/akshare/AkShareScreen.cpp b/fincept-qt/src/screens/akshare/AkShareScreen.cpp
index e59302515..347bb1309 100644
--- a/fincept-qt/src/screens/akshare/AkShareScreen.cpp
+++ b/fincept-qt/src/screens/akshare/AkShareScreen.cpp
@@ -4,12 +4,17 @@
#include "core/session/ScreenStateManager.h"
#include "services/akshare/AkShareService.h"
#include "storage/cache/CacheManager.h"
+#include "ui/tables/NumericTableWidgetItem.h"
#include "ui/theme/Theme.h"
#include <QGridLayout>
#include <QHBoxLayout>
+#include <QJsonArray>
#include <QJsonDocument>
+#include <QJsonObject>
#include <QPointer>
+
+#include <cmath>
#include <QScrollArea>
#include <QTimer>
#include <QVBoxLayout>
@@ -711,12 +716,21 @@ void AkShareScreen::execute_query(const QString& script, const QString& endpoint
const QVariant cached = fincept::CacheManager::instance().get(cache_key);
if (!cached.isNull()) {
auto doc = QJsonDocument::fromJson(cached.toString().toUtf8());
- if (doc.isArray() && !doc.array().isEmpty()) {
- const QJsonArray data_array = doc.array();
+ QJsonArray data_array;
+ QStringList cols;
+ if (doc.isObject()) {
+ const auto o = doc.object();
+ data_array = o["rows"].toArray();
+ for (const auto& c : o["columns"].toArray())
+ cols << c.toString();
+ } else if (doc.isArray()) {
+ data_array = doc.array(); // legacy cache entries (rows only)
+ }
+ if (!data_array.isEmpty()) {
record_count_->setText(tr("%1 records").arg(data_array.size()));
record_count_->show();
data_status_->setText(tr("%1 (cached)").arg(endpoint));
- display_table_data(data_array);
+ display_table_data(data_array, cols);
display_json_data(data_array);
return;
}
@@ -747,12 +761,15 @@ void AkShareScreen::execute_query(const QString& script, const QString& endpoint
self->data_status_->setText(endpoint);
if (!data_array.isEmpty()) {
+ QJsonObject cache_obj;
+ cache_obj["rows"] = data_array;
+ cache_obj["columns"] = QJsonArray::fromStringList(r.columns);
fincept::CacheManager::instance().put(
- cache_key, QVariant(QString::fromUtf8(QJsonDocument(data_array).toJson(QJsonDocument::Compact))),
+ cache_key, QVariant(QString::fromUtf8(QJsonDocument(cache_obj).toJson(QJsonDocument::Compact))),
2 * 60, "akshare");
}
- self->display_table_data(data_array);
+ self->display_table_data(data_array, r.columns);
self->display_json_data(data_array);
LOG_INFO("AkShare", "Query " + endpoint + ": " + QString::number(count) + " records");
@@ -761,7 +778,7 @@ void AkShareScreen::execute_query(const QString& script, const QString& endpoint
// ── Display ─────────────────────────────────────────────────────────────────
-void AkShareScreen::display_table_data(const QJsonArray& rows_json) {
+void AkShareScreen::display_table_data(const QJsonArray& rows_json, const QStringList& ordered_columns) {
data_table_->setSortingEnabled(false);
data_table_->clear();
data_table_->setRowCount(0);
@@ -772,11 +789,15 @@ void AkShareScreen::display_table_data(const QJsonArray& rows_json) {
return;
}
- // Extract columns from first row
- QStringList columns;
- auto first = rows_json[0].toObject();
- for (auto it = first.begin(); it != first.end(); ++it) {
- columns << it.key();
+ // Column order: prefer the ordered list the script supplied. QJsonObject
+ // sorts its keys, so deriving columns from a row scrambled the source
+ // DataFrame's real column order (akshare 序号/代码/名称/最新价 came out in
+ // meaningless Unicode order). Fall back to the first row's keys.
+ QStringList columns = ordered_columns;
+ if (columns.isEmpty()) {
+ auto first = rows_json[0].toObject();
+ for (auto it = first.begin(); it != first.end(); ++it)
+ columns << it.key();
}
data_table_->setColumnCount(columns.size());
@@ -792,14 +813,29 @@ void AkShareScreen::display_table_data(const QJsonArray& rows_json) {
auto val = obj.value(columns[col]);
QString text;
if (val.isDouble()) {
- text = QString::number(val.toDouble(), 'g', 10);
+ const double v = val.toDouble();
+ if (v == std::floor(v) && std::abs(v) < 1e15) {
+ // Exact integer (volume, market cap, index number) — render
+ // in full, never in scientific notation (the old 'g',10
+ // format turned e.g. a large 成交额 into "1.23e+10").
+ text = QString::number(static_cast<qint64>(v));
+ } else {
+ text = QString::number(v, 'f', 4);
+ if (text.contains('.')) {
+ while (text.endsWith('0'))
+ text.chop(1);
+ if (text.endsWith('.'))
+ text.chop(1);
+ }
+ }
} else if (val.isNull()) {
text = "--";
} else {
text = val.toVariant().toString();
}
- auto* item = new QTableWidgetItem(text);
+ QTableWidgetItem* item = val.isDouble() ? new ui::NumericTableWidgetItem(text, val.toDouble())
+ : new QTableWidgetItem(text);
item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
// Color numbers in cyan, negative in red
diff --git a/fincept-qt/src/screens/akshare/AkShareScreen.h b/fincept-qt/src/screens/akshare/AkShareScreen.h
index 78e708764..3a890e346 100644
--- a/fincept-qt/src/screens/akshare/AkShareScreen.h
+++ b/fincept-qt/src/screens/akshare/AkShareScreen.h
@@ -70,7 +70,7 @@ class AkShareScreen : public QWidget, public IStatefulScreen {
void load_endpoints(const AkShareSource& source);
void populate_endpoint_list(const QJsonObject& result);
void execute_query(const QString& script, const QString& endpoint, const QStringList& args);
- void display_table_data(const QJsonArray& data);
+ void display_table_data(const QJsonArray& data, const QStringList& columns = {});
void display_json_data(const QJsonArray& data);
void display_error(const QString& error);
void set_loading(bool loading);
diff --git a/fincept-qt/src/screens/asia_markets/AsiaMarketsScreen.cpp b/fincept-qt/src/screens/asia_markets/AsiaMarketsScreen.cpp
index dc30e6787..b1fe621b0 100644
--- a/fincept-qt/src/screens/asia_markets/AsiaMarketsScreen.cpp
+++ b/fincept-qt/src/screens/asia_markets/AsiaMarketsScreen.cpp
@@ -4,6 +4,7 @@
#include "core/session/ScreenStateManager.h"
#include "services/asia_markets/AsiaMarketsService.h"
#include "storage/cache/CacheManager.h"
+#include "ui/tables/NumericTableWidgetItem.h"
#include "ui/theme/Theme.h"
#include <QGridLayout>
@@ -751,7 +752,8 @@ void AsiaMarketsScreen::display_table(const QJsonArray& rows_json) {
text = val.toVariant().toString();
}
- auto* item = new QTableWidgetItem(text);
+ QTableWidgetItem* item = val.isDouble() ? new ui::NumericTableWidgetItem(text, val.toDouble())
+ : new QTableWidgetItem(text);
item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
if (val.isDouble())
item->setForeground(is_neg ? col_neg : col_pos);
diff --git a/fincept-qt/src/screens/chat_mode/ChatModeService.cpp b/fincept-qt/src/screens/chat_mode/ChatModeService.cpp
index 31ef7c6ed..3a7fc71ff 100644
--- a/fincept-qt/src/screens/chat_mode/ChatModeService.cpp
+++ b/fincept-qt/src/screens/chat_mode/ChatModeService.cpp
@@ -886,6 +886,7 @@ QNetworkReply* ChatModeService::stream_message(const QString& message, const QSt
sse_reply_ = sse_nam_->post(req, QJsonDocument(body).toJson(QJsonDocument::Compact));
sse_current_event_.clear();
+ sse_terminal_emitted_ = false; // fresh stream — no terminal signal yet
connect(sse_reply_, &QNetworkReply::readyRead, this, [this]() {
while (sse_reply_ && sse_reply_->canReadLine()) {
@@ -905,10 +906,18 @@ QNetworkReply* ChatModeService::stream_message(const QString& message, const QSt
if (net_err != QNetworkReply::NoError && net_err != QNetworkReply::OperationCanceledError) {
const QString body = QString::fromUtf8(sse_reply_->readAll().left(200));
LOG_WARN("ChatModeService", QString("SSE error body: %1").arg(body));
+ sse_terminal_emitted_ = true;
emit stream_error(QString("Stream failed (HTTP %1)").arg(status));
}
sse_reply_->deleteLater();
sse_reply_ = nullptr;
+ // A clean close (or a cancel) that never sent a "finish"/"error" event
+ // still needs a terminal signal, otherwise the chat panel leaves its
+ // input disabled forever.
+ if (!sse_terminal_emitted_) {
+ sse_terminal_emitted_ = true;
+ emit stream_finish(0);
+ }
});
return sse_reply_;
@@ -920,6 +929,13 @@ void ChatModeService::abort_stream() {
sse_reply_->deleteLater();
sse_reply_ = nullptr;
}
+ // A user-initiated Stop otherwise emits no terminal signal (the finished
+ // handler skips OperationCanceledError), so the chat panel's input would
+ // stay disabled forever. Emit one if none has gone out for this stream.
+ if (!sse_terminal_emitted_) {
+ sse_terminal_emitted_ = true;
+ emit stream_finish(0);
+ }
}
void ChatModeService::handle_sse_line(const QByteArray& line) {
@@ -964,6 +980,7 @@ void ChatModeService::handle_sse_line(const QByteArray& line) {
} else if (ev == "finish") {
const int total = data["totalTokens"].toInt();
LOG_INFO("ChatModeService", QString("SSE finish: %1 total tokens").arg(total));
+ sse_terminal_emitted_ = true;
emit stream_finish(total);
} else if (ev == "heartbeat") {
LOG_DEBUG("ChatModeService", "SSE heartbeat");
@@ -971,6 +988,7 @@ void ChatModeService::handle_sse_line(const QByteArray& line) {
} else if (ev == "error") {
const QString msg = data["message"].toString();
LOG_WARN("ChatModeService", "SSE error: " + msg);
+ sse_terminal_emitted_ = true;
emit stream_error(msg);
} else if (!ev.isEmpty()) {
LOG_DEBUG("ChatModeService", "SSE unknown event: " + ev);
diff --git a/fincept-qt/src/screens/chat_mode/ChatModeService.h b/fincept-qt/src/screens/chat_mode/ChatModeService.h
index e60428b5f..bba92d75d 100644
--- a/fincept-qt/src/screens/chat_mode/ChatModeService.h
+++ b/fincept-qt/src/screens/chat_mode/ChatModeService.h
@@ -189,6 +189,7 @@ class ChatModeService : public QObject {
QNetworkAccessManager* sse_nam_ = nullptr; // dedicated for SSE stream
QNetworkReply* sse_reply_ = nullptr; // active agent SSE connection
QString sse_current_event_; // tracks "event:" field
+ bool sse_terminal_emitted_ = false; // a stream_finish/stream_error went out for this stream
QNetworkReply* task_sse_reply_ = nullptr; // active task activity SSE
QString task_sse_event_;
diff --git a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp
index 409fcca52..d5a041397 100644
--- a/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp
+++ b/fincept-qt/src/screens/crypto_trading/CryptoTradingScreen.cpp
@@ -77,6 +77,11 @@ void CryptoTradingScreen::showEvent(QShowEvent* event) {
clock_timer_->start();
if (ws_flush_timer_)
ws_flush_timer_->start();
+ // Restart the live positions/P&L poller if we're in LIVE mode. hideEvent
+ // stopped it and it was only ever (re)started from the mode toggle, so
+ // tabbing away and back froze live P&L until the mode was re-toggled.
+ if (live_data_timer_ && trading_mode_ == crypto::TradingMode::Live)
+ live_data_timer_->start(5000);
LOG_INFO(TAG, "Screen visible — WS-only mode (no REST polling)");
}
diff --git a/fincept-qt/src/screens/dashboard/DashboardScreen.cpp b/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
index d87249897..95571d2ae 100644
--- a/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
+++ b/fincept-qt/src/screens/dashboard/DashboardScreen.cpp
@@ -15,6 +15,7 @@
#include "ui/widgets/NotifToast.h"
#include <QDataStream>
+#include <QJsonDocument>
#include <QEvent>
#include <QHideEvent>
#include <QPalette>
@@ -189,8 +190,21 @@ void DashboardScreen::showEvent(QShowEvent* event) {
QWidget::showEvent(event);
refresh_theme();
- if (ticker_bar_)
- ticker_bar_->resume();
+ if (ticker_bar_) {
+ // Honour the appearance settings that were previously saved but never
+ // read: "Show Ticker Bar" toggles visibility; "Enable Animations" toggles
+ // the scroll (off → the bar shows its symbols but doesn't animate).
+ auto& repo = SettingsRepository::instance();
+ const auto tr = repo.get("appearance.show_ticker_bar");
+ const bool show_ticker = !tr.is_ok() ? true : tr.value() != "false";
+ const auto ar = repo.get("appearance.animations");
+ const bool animations = !ar.is_ok() ? true : ar.value() != "false";
+ ticker_bar_->setVisible(show_ticker);
+ if (show_ticker && animations)
+ ticker_bar_->resume();
+ else
+ ticker_bar_->pause();
+ }
// Subscribe to current ticker symbols — hub schedules refreshes per TopicPolicy.
hub_resubscribe_ticker();
@@ -341,20 +355,33 @@ bool DashboardScreen::eventFilter(QObject* obj, QEvent* event) {
// ── Save / Restore layout via SettingsRepository ──────────────────────────────
+namespace {
+// Magic + version prefix for the serialized dashboard layout blob. Distinguishes
+// the current config-carrying format from the legacy one (which packed items
+// with no per-item config). `cols` (a small int) never collides with the magic,
+// so legacy blobs are still decoded (with empty per-item config).
+constexpr quint32 kDashLayoutMagic = 0xDA58A101u;
+constexpr quint32 kDashLayoutVersion = 1;
+} // namespace
+
void DashboardScreen::save_layout() {
save_timer_->stop();
GridLayout layout = canvas_->current_layout();
- // Serialize: cols, row_h, margin, item count, then each item
+ // Serialize: magic+version, cols, row_h, margin, item count, then each item
+ // (including its per-instance config — dropping it reverted every configured
+ // widget to defaults on restart).
QByteArray buf;
QDataStream stream(&buf, QIODevice::WriteOnly);
+ stream << kDashLayoutMagic << kDashLayoutVersion;
stream << layout.cols << layout.row_h << layout.margin;
stream << static_cast<int>(layout.items.size());
for (const auto& item : layout.items) {
stream << item.id << item.instance_id;
stream << item.cell.x << item.cell.y << item.cell.w << item.cell.h;
stream << item.cell.min_w << item.cell.min_h;
+ stream << QJsonDocument(item.config).toJson(QJsonDocument::Compact);
}
QString encoded = buf.toBase64();
@@ -384,7 +411,19 @@ void DashboardScreen::restore_layout() {
GridLayout layout;
int count = 0;
- stream >> layout.cols >> layout.row_h >> layout.margin >> count;
+ // Detect the format: a leading magic means the config-carrying
+ // blob; otherwise the 4 bytes we read were the legacy `cols`.
+ quint32 lead = 0;
+ stream >> lead;
+ const bool has_config = (lead == kDashLayoutMagic);
+ if (has_config) {
+ quint32 version = 0;
+ stream >> version; // reserved for future migrations
+ stream >> layout.cols >> layout.row_h >> layout.margin >> count;
+ } else {
+ layout.cols = static_cast<int>(lead);
+ stream >> layout.row_h >> layout.margin >> count;
+ }
if (count <= 0 || count > 100) {
self->build_default_layout();
@@ -396,6 +435,13 @@ void DashboardScreen::restore_layout() {
stream >> item.id >> item.instance_id;
stream >> item.cell.x >> item.cell.y >> item.cell.w >> item.cell.h;
stream >> item.cell.min_w >> item.cell.min_h;
+ if (has_config) {
+ QByteArray cfg_bytes;
+ stream >> cfg_bytes;
+ const auto doc = QJsonDocument::fromJson(cfg_bytes);
+ if (doc.isObject())
+ item.config = doc.object();
+ }
layout.items.append(item);
}
diff --git a/fincept-qt/src/screens/dashboard/DashboardStatusBar.cpp b/fincept-qt/src/screens/dashboard/DashboardStatusBar.cpp
index 061a5862a..a88839f59 100644
--- a/fincept-qt/src/screens/dashboard/DashboardStatusBar.cpp
+++ b/fincept-qt/src/screens/dashboard/DashboardStatusBar.cpp
@@ -19,8 +19,8 @@
#if defined(Q_OS_WIN)
// windows.h must come first — psapi.h depends on its types (BOOL, WINAPI, …)
// and including psapi.h alone yields C2146 / C2086 cascades.
-# include <psapi.h>
# include <windows.h>
+# include <psapi.h>
#elif defined(Q_OS_MAC)
# include <mach/mach.h>
#elif defined(Q_OS_LINUX)
diff --git a/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.cpp
index 6fa98bec4..26fee7923 100644
--- a/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/BrokerHoldingsWidget.cpp
@@ -17,8 +17,10 @@
#include <QJsonObject>
#include <QLabel>
#include <QMessageBox>
+#include <QPointer>
#include <QPushButton>
#include <QStringList>
+#include <QtConcurrent/QtConcurrent>
namespace fincept::screens::widgets {
@@ -233,14 +235,30 @@ void BrokerHoldingsWidget::square_off_holding(const trading::BrokerHolding& h) {
if (answer != QMessageBox::Yes)
return;
- const auto resp = trading::UnifiedTrading::instance().place_order(account_id_, make_square_off_order(h));
- if (resp.success) {
- QMessageBox::information(this, tr("Square Off Holding"),
- tr("Sell order placed for %1 (order %2).").arg(h.symbol, resp.order_id));
- } else {
- QMessageBox::critical(this, tr("Square Off Holding"),
- tr("Failed to square off %1: %2").arg(h.symbol, resp.message));
- }
+ // place_order blocks on a synchronous broker REST call for a live account —
+ // run it off the UI thread (P1) and marshal the result dialog back.
+ const trading::UnifiedOrder order = make_square_off_order(h);
+ const QString account = account_id_;
+ const QString sym = h.symbol;
+ QPointer<BrokerHoldingsWidget> self = this;
+ (void)QtConcurrent::run([self, account, order, sym]() {
+ const auto resp = trading::UnifiedTrading::instance().place_order(account, order);
+ if (!self)
+ return;
+ QMetaObject::invokeMethod(
+ self,
+ [self, resp, sym]() {
+ if (!self)
+ return;
+ if (resp.success)
+ QMessageBox::information(self, tr("Square Off Holding"),
+ tr("Sell order placed for %1 (order %2).").arg(sym, resp.order_id));
+ else
+ QMessageBox::critical(self, tr("Square Off Holding"),
+ tr("Failed to square off %1: %2").arg(sym, resp.message));
+ },
+ Qt::QueuedConnection);
+ });
}
void BrokerHoldingsWidget::square_off_all() {
@@ -267,25 +285,49 @@ void BrokerHoldingsWidget::square_off_all() {
if (answer != QMessageBox::Yes)
return;
- int placed = 0;
- QStringList failures;
- for (const auto& h : targets) {
- const auto resp = trading::UnifiedTrading::instance().place_order(account_id_, make_square_off_order(h));
- if (resp.success)
- ++placed;
- else
- failures.append(QStringLiteral("%1 (%2)").arg(h.symbol, resp.message));
- }
-
- if (failures.isEmpty()) {
- QMessageBox::information(this, tr("Square Off All Holdings"), tr("Placed %1 sell order(s).").arg(placed));
- } else {
- QMessageBox::warning(this, tr("Square Off All Holdings"),
- tr("Placed %1 order(s). %2 failed:\n%3")
- .arg(placed)
- .arg(failures.size())
- .arg(failures.join(QStringLiteral("\n"))));
- }
+ // Pre-build every order on the UI thread, then place them off the UI thread:
+ // each place_order is a blocking broker REST round-trip for a live account,
+ // so looping synchronously here froze the whole terminal for seconds (P1).
+ struct SquareOffJob {
+ QString symbol;
+ trading::UnifiedOrder order;
+ };
+ QVector<SquareOffJob> jobs;
+ jobs.reserve(targets.size());
+ for (const auto& h : targets)
+ jobs.append({h.symbol, make_square_off_order(h)});
+
+ const QString account = account_id_;
+ QPointer<BrokerHoldingsWidget> self = this;
+ (void)QtConcurrent::run([self, account, jobs]() {
+ int placed = 0;
+ QStringList failures;
+ for (const auto& j : jobs) {
+ const auto resp = trading::UnifiedTrading::instance().place_order(account, j.order);
+ if (resp.success)
+ ++placed;
+ else
+ failures.append(QStringLiteral("%1 (%2)").arg(j.symbol, resp.message));
+ }
+ if (!self)
+ return;
+ QMetaObject::invokeMethod(
+ self,
+ [self, placed, failures]() {
+ if (!self)
+ return;
+ if (failures.isEmpty())
+ QMessageBox::information(self, tr("Square Off All Holdings"),
+ tr("Placed %1 sell order(s).").arg(placed));
+ else
+ QMessageBox::warning(self, tr("Square Off All Holdings"),
+ tr("Placed %1 order(s). %2 failed:\n%3")
+ .arg(placed)
+ .arg(failures.size())
+ .arg(failures.join(QStringLiteral("\n"))));
+ },
+ Qt::QueuedConnection);
+ });
}
void BrokerHoldingsWidget::on_theme_changed() {
diff --git a/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp
index ad5056332..75adcdcb7 100644
--- a/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/QuickTradeWidget.cpp
@@ -296,9 +296,22 @@ void QuickTradeWidget::submit_order() {
QString price_str = type == "MARKET" ? tr("market price ($%1)").arg(current_price_, 0, 'f', 2)
: QString("$%1").arg(price_input_->text());
+ // This dashboard widget has no broker/account binding, so it cannot place a
+ // real or paper order. Previously it popped an "Order sent to trading
+ // engine" success box while sending nothing — a dangerous false confirmation
+ // on a trading terminal. Be honest and point the user at the real order
+ // entry (Equity/Crypto Trading), which has account selection, paper/live
+ // routing and an explicit confirmation. (Wiring Quick Trade to an account is
+ // tracked as a follow-up.)
+ Q_UNUSED(price_str)
QMessageBox::information(
- this, tr("Order Submitted"),
- tr("%1 %2 %3 @ %4\nOrder sent to trading engine.").arg(side).arg(qty, 0, 'f', 0).arg(sym).arg(price_str));
+ this, tr("Quick Trade"),
+ tr("Quick Trade is a preview widget and is not connected to a trading account — no order was placed.\n\n"
+ "To place %1 %2 %3, use the Equity Trading or Crypto Trading screen, which routes the order to your "
+ "selected broker/paper account with confirmation.")
+ .arg(side)
+ .arg(qty, 0, 'f', 0)
+ .arg(sym));
}
void QuickTradeWidget::retranslateUi() {
diff --git a/fincept-qt/src/screens/data_sources/ConnectorRegistry.h b/fincept-qt/src/screens/data_sources/ConnectorRegistry.h
index d52b1a3c1..e7dbd864a 100644
--- a/fincept-qt/src/screens/data_sources/ConnectorRegistry.h
+++ b/fincept-qt/src/screens/data_sources/ConnectorRegistry.h
@@ -1,5 +1,5 @@
#pragma once
-// ConnectorRegistry — singleton holding all 78 data source connector definitions.
+// ConnectorRegistry — singleton holding all 118 data source connector definitions.
// Connector files self-register via static init.
#include "screens/data_sources/DataSourceTypes.h"
diff --git a/fincept-qt/src/screens/economics/panels/EconPanelBase.cpp b/fincept-qt/src/screens/economics/panels/EconPanelBase.cpp
index 6240abe5d..b9d50fb9c 100644
--- a/fincept-qt/src/screens/economics/panels/EconPanelBase.cpp
+++ b/fincept-qt/src/screens/economics/panels/EconPanelBase.cpp
@@ -397,7 +397,15 @@ void EconPanelBase::render_page() {
}
void EconPanelBase::update_stats(const QJsonArray& rows) {
- QVector<double> vals;
+ // Collect (date, value) pairs and sort chronologically so LATEST/CHANGE are
+ // correct whether the provider returns oldest- or newest-first (min/max/avg
+ // are order-independent). ISO-style dates sort correctly lexically; rows
+ // without a recognisable date keep their original order (stable sort).
+ struct DatedVal {
+ QString date;
+ double value;
+ };
+ QVector<DatedVal> pts;
for (const auto& v : rows) {
const auto obj = v.toObject();
QJsonValue jv = obj["value"];
@@ -422,9 +430,22 @@ void EconPanelBase::update_stats(const QJsonArray& rows) {
d = jv.toDouble();
ok = true;
}
- if (ok)
- vals << d;
+ if (!ok)
+ continue;
+ QString date;
+ for (const char* k : {"date", "Date", "TIME_PERIOD", "period", "Period", "time", "obs_date"}) {
+ if (obj.contains(QLatin1String(k))) {
+ date = obj[QLatin1String(k)].toString();
+ break;
+ }
+ }
+ pts.append({date, d});
}
+ std::stable_sort(pts.begin(), pts.end(), [](const DatedVal& a, const DatedVal& b) { return a.date < b.date; });
+ QVector<double> vals;
+ vals.reserve(pts.size());
+ for (const auto& p : pts)
+ vals << p.value;
if (vals.isEmpty()) {
for (auto* l : {stat_latest_, stat_change_, stat_min_, stat_max_, stat_avg_, stat_count_})
diff --git a/fincept-qt/src/screens/equity_research/EquityPeersTab.cpp b/fincept-qt/src/screens/equity_research/EquityPeersTab.cpp
index da7830f0b..c41540efd 100644
--- a/fincept-qt/src/screens/equity_research/EquityPeersTab.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityPeersTab.cpp
@@ -2,6 +2,7 @@
#include "screens/equity_research/EquityPeersTab.h"
#include "services/equity/EquityResearchService.h"
+#include "ui/tables/NumericTableWidgetItem.h"
#include "ui/theme/Theme.h"
#include <QEvent>
@@ -183,7 +184,13 @@ void EquityPeersTab::populate_table(const QVector<services::equity::PeerData>& p
auto set_cell = [&](int row, int col, const QString& text, const QColor& fg = QColor(),
Qt::Alignment align = Qt::AlignRight | Qt::AlignVCenter) {
- auto* item = new QTableWidgetItem(text);
+ // Sort numeric columns by magnitude, not lexically ("15","150","5"…).
+ // Parse the formatted value; non-numeric cells ("—") use a plain item.
+ QString num = text;
+ num.remove('%').remove(',').remove('$');
+ bool ok = false;
+ const double value = num.toDouble(&ok);
+ QTableWidgetItem* item = ok ? new ui::NumericTableWidgetItem(text, value) : new QTableWidgetItem(text);
item->setTextAlignment(align);
if (fg.isValid())
item->setForeground(fg);
diff --git a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
index 0527a98e4..5a48da14b 100644
--- a/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
+++ b/fincept-qt/src/screens/equity_research/EquityResearchScreen.cpp
@@ -362,6 +362,11 @@ QWidget* EquityResearchScreen::build_quote_bar() {
// Called when a new quote (price/change/volume) arrives from the service
void EquityResearchScreen::on_quote_loaded(services::equity::QuoteData q) {
+ // Guard: ignore a late quote for a symbol the user already navigated away
+ // from (matches on_info_loaded below), otherwise a stale price flashes in
+ // the header bar over the newly-selected symbol.
+ if (q.symbol != current_symbol_)
+ return;
update_quote_bar(q);
}
diff --git a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
index 96de965c2..a6e215b5a 100644
--- a/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityBottomPanel.cpp
@@ -1416,7 +1416,32 @@ void EquityBottomPanel::set_orders(const QVector<trading::BrokerOrderInfo>& orde
dlg->exec();
dlg->deleteLater();
});
- orders_table_->setCellWidget(i, 9, btn);
+ // CANCEL — kills the open order. Confirmed here because on_cancel_order
+ // cancels immediately with no downstream prompt and equity orders are live.
+ auto* cancel_row_btn = new QPushButton(tr("CANCEL"));
+ cancel_row_btn->setObjectName("eqTableBtn");
+ cancel_row_btn->setFixedHeight(18);
+ cancel_row_btn->setStyleSheet(QString("QPushButton#eqTableBtn { background: rgba(220,38,38,0.12); "
+ "color: %1; border: 1px solid %2; font-size: 10px; "
+ "padding: 0 6px; border-radius: 2px; }")
+ .arg(fincept::ui::colors::NEGATIVE())
+ .arg(fincept::ui::colors::NEGATIVE_DIM()));
+ cancel_row_btn->setCursor(Qt::PointingHandCursor);
+ const QString cancel_oid = o.order_id;
+ connect(cancel_row_btn, &QPushButton::clicked, this, [this, cancel_oid]() {
+ if (QMessageBox::question(this, tr("Cancel Order"), tr("Cancel order %1?").arg(cancel_oid.left(12)),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes)
+ emit cancel_order_requested(cancel_oid);
+ });
+
+ auto* action_cell = new QWidget;
+ auto* action_lay = new QHBoxLayout(action_cell);
+ action_lay->setContentsMargins(2, 0, 2, 0);
+ action_lay->setSpacing(4);
+ action_lay->addWidget(btn);
+ action_lay->addWidget(cancel_row_btn);
+ action_lay->addStretch();
+ orders_table_->setCellWidget(i, 9, action_cell);
} else {
orders_table_->setCellWidget(i, 9, nullptr);
}
diff --git a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp
index 9954c2245..ae7442585 100644
--- a/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityOrderEntry.cpp
@@ -603,12 +603,43 @@ void EquityOrderEntry::on_submit() {
return;
}
+ // Validate price/trigger for the order types that require them. Without this
+ // a blank Limit price sends price=0 to the broker (and a paper SELL-limit @0
+ // would fill at market).
+ const trading::OrderType otype = selected_order_type();
+ const double limit_px = price_edit_->text().toDouble();
+ const double trigger_px = stop_price_edit_->text().toDouble();
+ if ((otype == trading::OrderType::Limit || otype == trading::OrderType::StopLossLimit) && limit_px <= 0.0) {
+ status_label_->setText(tr("Enter a valid limit price"));
+ status_label_->setStyleSheet(QString("color: %1;").arg(colors::NEGATIVE()));
+ return;
+ }
+ if ((otype == trading::OrderType::StopLoss || otype == trading::OrderType::StopLossLimit) && trigger_px <= 0.0) {
+ status_label_->setText(tr("Enter a valid trigger price"));
+ status_label_->setStyleSheet(QString("color: %1;").arg(colors::NEGATIVE()));
+ return;
+ }
+
+ // Double-submit guard: in Auto mode there is no confirm dialog, so a rapid
+ // double-click would emit two live orders. Briefly disable the button; a
+ // single-shot timer re-enables it.
+ if (submit_btn_) {
+ if (!submit_btn_->isEnabled())
+ return;
+ submit_btn_->setEnabled(false);
+ QPointer<EquityOrderEntry> self = this;
+ QTimer::singleShot(1000, this, [self]() {
+ if (self && self->submit_btn_)
+ self->submit_btn_->setEnabled(true);
+ });
+ }
+
trading::UnifiedOrder order;
order.symbol = current_symbol_;
order.exchange = exchange_combo_->currentText();
order.side = is_buy_side_ ? trading::OrderSide::Buy : trading::OrderSide::Sell;
- order.order_type = selected_order_type();
+ order.order_type = otype;
order.quantity = qty;
order.price = price_edit_->text().toDouble();
order.stop_price = stop_price_edit_->text().toDouble();
diff --git a/fincept-qt/src/screens/excel/SpreadsheetWidget.cpp b/fincept-qt/src/screens/excel/SpreadsheetWidget.cpp
index 7c6bada70..70f652242 100644
--- a/fincept-qt/src/screens/excel/SpreadsheetWidget.cpp
+++ b/fincept-qt/src/screens/excel/SpreadsheetWidget.cpp
@@ -11,6 +11,7 @@
#include <QMenu>
#include <QMimeData>
#include <QRegularExpression>
+#include <QSet>
#include <QVBoxLayout>
#include <algorithm>
@@ -108,6 +109,21 @@ QVariant SpreadsheetItem::evaluate_formula() const {
if (!tableWidget())
return "#ERR";
+ // Guard against self-referential / circular formulas ("=A1" in A1, or
+ // A1→B1→A1). Evaluating a formula reads other cells' DisplayRole, which
+ // re-enters evaluate_formula(); without this a cycle recurses until the
+ // stack overflows and the whole terminal crashes on the next repaint. Track
+ // the items currently on the evaluation stack (single UI thread) and return
+ // #CYCLE on re-entry instead of recursing.
+ static thread_local QSet<const SpreadsheetItem*> evaluating;
+ if (evaluating.contains(this))
+ return QStringLiteral("#CYCLE");
+ evaluating.insert(this);
+ struct EvalGuard {
+ const SpreadsheetItem* item;
+ ~EvalGuard() { evaluating.remove(item); }
+ } eval_guard{this};
+
QString expr = raw_text_.mid(1).trimmed().toUpper();
// ── Function calls: SUM, AVG/AVERAGE, MIN, MAX, COUNT ────────────────
diff --git a/fincept-qt/src/screens/fno/BuilderSubTab.cpp b/fincept-qt/src/screens/fno/BuilderSubTab.cpp
index 9ac166656..dc4598efa 100644
--- a/fincept-qt/src/screens/fno/BuilderSubTab.cpp
+++ b/fincept-qt/src/screens/fno/BuilderSubTab.cpp
@@ -384,6 +384,25 @@ void BuilderSubTab::on_trade_clicked() {
return;
}
+ // SAFETY (money-loss guard): this action is paper-only — the button, tooltip,
+ // confirm dialog and toast all say "paper", and it fills every leg as a
+ // market order at the current premium. UnifiedTrading::place_order routes by
+ // the account's real trading_mode, so if the resolved account is LIVE this
+ // would fire real broker orders while the entire UI claims "paper". Refuse
+ // instead. (Live F&O trading is done per-leg from the option chain's
+ // right-click Buy/Sell, which maps the broker-native symbol, confirms LIVE
+ // explicitly, and places off the UI thread.)
+ const BrokerAccount acct = AccountManager::instance().get_account(account_id);
+ if (acct.trading_mode == QStringLiteral("live")) {
+ QMessageBox::warning(
+ this, tr("Paper trade only"),
+ tr("The %1 account is in LIVE mode.\n\n“Trade All (Paper)” only places simulated paper orders — it will "
+ "not place live orders. To trade this strategy live, place each leg from the option chain "
+ "(right-click a strike → Buy / Sell), which confirms each live order individually.")
+ .arg(acct.display_name.isEmpty() ? broker : acct.display_name));
+ return;
+ }
+
int placed = 0;
int failed = 0;
QStringList failures;
diff --git a/fincept-qt/src/screens/forum/ForumPostListPanel.cpp b/fincept-qt/src/screens/forum/ForumPostListPanel.cpp
deleted file mode 100644
index 62a4f6126..000000000
--- a/fincept-qt/src/screens/forum/ForumPostListPanel.cpp
+++ /dev/null
@@ -1,433 +0,0 @@
-// src/screens/forum/ForumPostListPanel.cpp
-#include "screens/forum/ForumPostListPanel.h"
-
-#include "ui/theme/Theme.h"
-#include "ui/theme/ThemeManager.h"
-
-#include <QCoreApplication>
-#include <QDateTime>
-#include <QFrame>
-#include <QHBoxLayout>
-#include <QPushButton>
-#include <QScrollArea>
-
-#include <cmath>
-
-namespace fincept::screens {
-
-static QString M(int sz = 12) {
- return QString("font-family:'Consolas','Courier New',monospace;font-size:%1px;").arg(sz);
-}
-
-static QString rel_time(const QString& iso) {
- if (iso.isEmpty())
- return {};
- auto dt = QDateTime::fromString(iso, Qt::ISODate);
- if (!dt.isValid())
- dt = QDateTime::fromString(iso.left(19), "yyyy-MM-ddTHH:mm:ss");
- if (!dt.isValid())
- return iso.left(10);
- qint64 sec = dt.secsTo(QDateTime::currentDateTimeUtc());
- if (sec < 0)
- sec = 0;
- if (sec < 60)
- return QCoreApplication::translate("ForumPostListPanel", "%1s ago").arg(sec);
- if (sec < 3600)
- return QCoreApplication::translate("ForumPostListPanel", "%1m ago").arg(sec / 60);
- if (sec < 86400)
- return QCoreApplication::translate("ForumPostListPanel", "%1h ago").arg(sec / 3600);
- return QCoreApplication::translate("ForumPostListPanel", "%1d ago").arg(sec / 86400);
-}
-
-static QString fmt_num(int n) {
- if (n >= 10000)
- return QString("%1K").arg(n / 1000);
- if (n >= 1000)
- return QString("%1.%2K").arg(n / 1000).arg((n % 1000) / 100);
- return QString::number(n);
-}
-
-static QString det_color(const QString& s) {
- static const char* pal[] = {"#d97706", "#06b6d4", "#10b981", "#8b5cf6", "#f97316",
- "#3b82f6", "#ec4899", "#14b8a6", "#84cc16", "#ef4444"};
- return pal[qHash(s) % 10];
-}
-
-ForumPostListPanel::ForumPostListPanel(QWidget* parent) : QWidget(parent) {
- connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this, [this](const ui::ThemeTokens&) {
- setStyleSheet(QString("background:%1;color:%2;").arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY()));
- });
- build_ui();
-}
-
-void ForumPostListPanel::build_ui() {
- setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
- auto* root = new QVBoxLayout(this);
- root->setContentsMargins(0, 0, 0, 0);
- root->setSpacing(0);
-
- // ── Channel header ────────────────────────────────────────────────────────
- auto* hdr = new QWidget(this);
- hdr->setFixedHeight(44);
- hdr->setStyleSheet(
- QString("background:%1;border-bottom:1px solid %2;").arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
- auto* hdr_hl = new QHBoxLayout(hdr);
- hdr_hl->setContentsMargins(16, 0, 16, 0);
- hdr_hl->setSpacing(10);
-
- auto* hash = new QLabel("#");
- hash->setStyleSheet(
- QString("color:%1;font-size:20px;font-weight:700;background:transparent;%2").arg(ui::colors::AMBER(), M(20)));
- hash->setFixedWidth(18);
-
- channel_label_ = new QLabel("all-posts");
- channel_label_->setStyleSheet(QString("color:%1;font-size:14px;font-weight:700;background:transparent;%2")
- .arg(ui::colors::TEXT_PRIMARY(), M(14)));
-
- count_label_ = new QLabel;
- count_label_->setStyleSheet(
- QString("color:%1;font-size:11px;background:transparent;%2").arg(ui::colors::TEXT_TERTIARY(), M(11)));
-
- hdr_hl->addWidget(hash);
- hdr_hl->addWidget(channel_label_, 1);
- hdr_hl->addWidget(count_label_);
- root->addWidget(hdr);
-
- // ── Scrollable card feed ──────────────────────────────────────────────────
- scroll_ = new QScrollArea;
- scroll_->setWidgetResizable(true);
- scroll_->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- scroll_->setStyleSheet(QString("QScrollArea{border:none;background:%1;}"
- "QScrollBar:vertical{width:6px;background:transparent;margin:0;}"
- "QScrollBar::handle:vertical{background:%2;min-height:40px;"
- "border-radius:3px;}"
- "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical"
- "{height:0;}")
- .arg(ui::colors::BG_BASE(), ui::colors::BORDER_DIM()));
-
- feed_container_ = new QWidget(this);
- feed_container_->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
- feed_layout_ = new QVBoxLayout(feed_container_);
- feed_layout_->setContentsMargins(0, 0, 0, 0);
- feed_layout_->setSpacing(0);
- feed_layout_->addStretch();
-
- scroll_->setWidget(feed_container_);
- root->addWidget(scroll_, 1);
-
- skeleton_timer_ = new QTimer(this);
- skeleton_timer_->setInterval(400);
- connect(skeleton_timer_, &QTimer::timeout, this, &ForumPostListPanel::pulse_skeleton);
-}
-
-void ForumPostListPanel::set_header(const QString& title, const QString& color) {
- Q_UNUSED(color)
- channel_label_->setText(title.toLower().replace(' ', '-'));
-}
-
-void ForumPostListPanel::set_loading(bool on) {
- if (on) {
- show_skeleton();
- } else {
- skeleton_timer_->stop();
- if (skeleton_widget_) {
- skeleton_widget_->deleteLater();
- skeleton_widget_ = nullptr;
- }
- }
-}
-
-void ForumPostListPanel::show_skeleton() {
- if (skeleton_widget_) {
- skeleton_widget_->deleteLater();
- skeleton_widget_ = nullptr;
- }
-
- skeleton_widget_ = new QWidget(feed_container_);
- auto* sk_vl = new QVBoxLayout(skeleton_widget_);
- sk_vl->setContentsMargins(12, 8, 12, 8);
- sk_vl->setSpacing(6);
-
- for (int i = 0; i < 8; ++i) {
- auto* card = new QWidget(this);
- card->setFixedHeight(68);
- card->setStyleSheet(QString("background:%1;border:1px solid %2;border-radius:4px;")
- .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
- auto* cvl = new QVBoxLayout(card);
- cvl->setContentsMargins(14, 10, 14, 10);
- cvl->setSpacing(8);
-
- auto* bar1 = new QWidget(this);
- bar1->setFixedHeight(10);
- bar1->setStyleSheet(QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"
- "stop:0 %1,stop:%2 %3,stop:1 %1);border-radius:5px;")
- .arg(ui::colors::BORDER_DIM())
- .arg(0.3 + (i % 4) * 0.15)
- .arg(ui::colors::BORDER_MED()));
- bar1->setMaximumWidth(200 + i * 20);
-
- auto* bar2 = new QWidget(this);
- bar2->setFixedHeight(7);
- bar2->setStyleSheet(QString("background:%1;border-radius:3px;").arg(ui::colors::BORDER_DIM()));
- bar2->setMaximumWidth(120);
-
- cvl->addWidget(bar1);
- cvl->addWidget(bar2);
- cvl->addStretch();
- sk_vl->addWidget(card);
- }
-
- sk_vl->addStretch();
- feed_layout_->insertWidget(0, skeleton_widget_);
- skeleton_timer_->start();
-}
-
-void ForumPostListPanel::pulse_skeleton() {
- if (!skeleton_widget_)
- return;
- static int off = 0;
- off = (off + 15) % 100;
- double s = off / 100.0;
- double e = std::min(1.0, s + 0.3);
- QString bg = QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"
- "stop:0 %1,stop:%2 %3,stop:%4 %1);border-radius:5px;")
- .arg(ui::colors::BORDER_DIM())
- .arg(s, 0, 'f', 2)
- .arg(ui::colors::BORDER_MED())
- .arg(e, 0, 'f', 2);
-
- auto* lay = qobject_cast<QVBoxLayout*>(skeleton_widget_->layout());
- if (!lay)
- return;
- for (int i = 0; i < lay->count(); ++i) {
- auto* item = lay->itemAt(i);
- if (!item || !item->widget())
- continue;
- auto* card = item->widget();
- auto* cvl = qobject_cast<QVBoxLayout*>(card->layout());
- if (!cvl)
- continue;
- for (int j = 0; j < cvl->count(); ++j) {
- auto* ci = cvl->itemAt(j);
- if (ci && ci->widget() && ci->widget()->height() >= 7 && ci->widget()->height() <= 12)
- ci->widget()->setStyleSheet(bg);
- }
- }
-}
-
-void ForumPostListPanel::clear() {
- feed_container_->setUpdatesEnabled(false);
- while (feed_layout_->count() > 0) {
- auto* item = feed_layout_->takeAt(0);
- if (item->widget())
- item->widget()->deleteLater();
- delete item;
- }
- feed_container_->setUpdatesEnabled(true);
- active_uuid_.clear();
-}
-
-void ForumPostListPanel::set_active_post(const QString& uuid) {
- active_uuid_ = uuid;
-}
-
-void ForumPostListPanel::set_posts(const services::ForumPostsPage& page, const QString& category_color) {
- current_page_ = page;
- category_color_ = category_color;
- skeleton_timer_->stop();
- if (skeleton_widget_) {
- skeleton_widget_->deleteLater();
- skeleton_widget_ = nullptr;
- }
- rebuild_feed();
-}
-
-void ForumPostListPanel::rebuild_feed() {
- clear();
- count_label_->setText(current_page_.total > 0 ? tr("%1 posts").arg(current_page_.total) : QString());
-
- if (current_page_.posts.isEmpty()) {
- auto* empty = new QWidget(this);
- empty->setMinimumHeight(120);
- empty->setStyleSheet("background:transparent;");
- auto* el = new QVBoxLayout(empty);
- el->setAlignment(Qt::AlignCenter);
- el->setSpacing(6);
-
- auto* icon = new QLabel("◇");
- icon->setAlignment(Qt::AlignCenter);
- icon->setStyleSheet(QString("color:%1;font-size:24px;background:transparent;").arg(ui::colors::BORDER_DIM()));
-
- auto* lbl = new QLabel(tr("NO POSTS YET"));
- lbl->setAlignment(Qt::AlignCenter);
- lbl->setStyleSheet(QString("color:%1;font-size:13px;font-weight:700;letter-spacing:1.5px;"
- "background:transparent;%2")
- .arg(ui::colors::TEXT_TERTIARY(), M(13)));
-
- auto* sub = new QLabel(tr("Be the first to start a discussion"));
- sub->setAlignment(Qt::AlignCenter);
- sub->setStyleSheet(
- QString("color:%1;font-size:11px;background:transparent;%2").arg(ui::colors::TEXT_DIM(), M(11)));
-
- el->addWidget(icon);
- el->addWidget(lbl);
- el->addWidget(sub);
- feed_layout_->addWidget(empty);
- feed_layout_->addStretch();
- return;
- }
-
- feed_container_->setUpdatesEnabled(false);
-
- for (int i = 0; i < current_page_.posts.size(); ++i) {
- const auto& post = current_page_.posts[i];
- const bool active = (post.post_uuid == active_uuid_);
- QString cat_color = post.category_color.isEmpty() ? det_color(post.category_name) : post.category_color;
-
- auto* card = new QWidget(this);
- card->setCursor(Qt::PointingHandCursor);
- card->setStyleSheet(active ? QString("background:rgba(217,119,6,0.04);"
- "border-bottom:1px solid %1;"
- "border-left:3px solid %2;")
- .arg(ui::colors::BORDER_DIM(), cat_color)
- : QString("background:%1;"
- "border-bottom:1px solid %2;"
- "border-left:3px solid transparent;")
- .arg(ui::colors::BG_BASE(), ui::colors::BORDER_DIM()));
-
- auto* card_vl = new QVBoxLayout(card);
- card_vl->setContentsMargins(14, 10, 14, 8);
- card_vl->setSpacing(4);
-
- // ── Top row: avatar + name + category chip + time ─────────────────────
- auto* top_row = new QWidget(this);
- top_row->setStyleSheet("background:transparent;");
- auto* top_hl = new QHBoxLayout(top_row);
- top_hl->setContentsMargins(0, 0, 0, 0);
- top_hl->setSpacing(8);
-
- auto* avatar =
- new QLabel(post.author_display_name.isEmpty() ? "?" : post.author_display_name.left(2).toUpper());
- avatar->setFixedSize(24, 24);
- avatar->setAlignment(Qt::AlignCenter);
- avatar->setStyleSheet(QString("color:%1;font-size:9px;font-weight:700;background:%2;"
- "border-radius:12px;%3")
- .arg(ui::colors::BG_BASE(), det_color(post.author_display_name), M(9)));
-
- auto* author = new QLabel(post.author_display_name.left(16));
- author->setStyleSheet(QString("color:%1;font-size:11px;font-weight:600;"
- "background:transparent;%2")
- .arg(ui::colors::TEXT_PRIMARY(), M(11)));
-
- auto* cat_chip = new QLabel(post.category_name.toUpper().left(12));
- cat_chip->setStyleSheet(QString("color:%1;font-size:9px;font-weight:700;background:transparent;"
- "border:1px solid %1;padding:1px 6px;letter-spacing:0.5px;"
- "border-radius:8px;%2")
- .arg(cat_color, M(9)));
-
- auto* time_lbl = new QLabel(rel_time(post.created_at));
- time_lbl->setStyleSheet(
- QString("color:%1;font-size:10px;background:transparent;%2").arg(ui::colors::TEXT_DIM(), M(10)));
-
- top_hl->addWidget(avatar);
- top_hl->addWidget(author);
- top_hl->addSpacing(4);
- top_hl->addWidget(cat_chip);
- top_hl->addStretch();
- top_hl->addWidget(time_lbl);
- card_vl->addWidget(top_row);
-
- // ── Title ─────────────────────────────────────────────────────────────
- auto* title_lbl = new QLabel(post.title);
- title_lbl->setWordWrap(false);
- title_lbl->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
- title_lbl->setStyleSheet(active ? QString("color:%1;font-size:13px;font-weight:700;"
- "background:transparent;%2")
- .arg(ui::colors::TEXT_PRIMARY(), M(13))
- : QString("color:%1;font-size:13px;font-weight:600;"
- "background:transparent;%2")
- .arg(ui::colors::TEXT_PRIMARY(), M(13)));
- card_vl->addWidget(title_lbl);
-
- // ── Engagement ────────────────────────────────────────────────────────
- auto* eng_row = new QWidget(this);
- eng_row->setStyleSheet("background:transparent;");
- auto* eng_hl = new QHBoxLayout(eng_row);
- eng_hl->setContentsMargins(0, 2, 0, 0);
- eng_hl->setSpacing(14);
-
- auto mk_eng = [&](const QString& icon, const QString& val, const QString& color) {
- auto* lbl = new QLabel(icon + " " + val);
- lbl->setStyleSheet(QString("color:%1;font-size:10px;background:transparent;%2").arg(color, M(10)));
- return lbl;
- };
-
- QString like_color = post.likes > 0 ? ui::colors::AMBER() : QString(ui::colors::BORDER_DIM());
- QString rep_color = post.reply_count > 0 ? ui::colors::CYAN() : QString(ui::colors::BORDER_DIM());
-
- eng_hl->addWidget(mk_eng("▲", fmt_num(post.likes), like_color));
- eng_hl->addWidget(mk_eng("◆", fmt_num(post.reply_count), rep_color));
- eng_hl->addWidget(mk_eng("◉", fmt_num(post.views), QString(ui::colors::BORDER_DIM())));
- eng_hl->addStretch();
-
- if (post.reply_count > 5) {
- auto* hot = new QLabel(tr("● HOT"));
- hot->setStyleSheet(QString("color:%1;font-size:9px;font-weight:700;"
- "background:rgba(220,38,38,0.08);padding:1px 6px;"
- "border-radius:6px;%2")
- .arg(ui::colors::NEGATIVE(), M(9)));
- eng_hl->addWidget(hot);
- }
- card_vl->addWidget(eng_row);
-
- // ── Click handler ─────────────────────────────────────────────────────
- auto* click_btn = new QPushButton(card);
- click_btn->setGeometry(0, 0, 3000, 200);
- click_btn->setFlat(true);
- click_btn->setStyleSheet("QPushButton{background:transparent;border:none;}");
- click_btn->raise();
-
- auto p = post;
- connect(click_btn, &QPushButton::clicked, this, [this, p]() {
- active_uuid_ = p.post_uuid;
- rebuild_feed();
- emit post_selected(p);
- });
-
- feed_layout_->addWidget(card);
- }
-
- // ── Load more ─────────────────────────────────────────────────────────────
- if (current_page_.page < current_page_.pages) {
- int remaining = current_page_.total - current_page_.posts.size();
- auto* more_btn = new QPushButton(tr("Load %1 more posts").arg(remaining));
- more_btn->setFixedHeight(34);
- more_btn->setCursor(Qt::PointingHandCursor);
- more_btn->setStyleSheet(QString("QPushButton{background:%1;color:%2;border:none;"
- "border-top:1px solid %3;font-size:12px;font-weight:600;%4}"
- "QPushButton:hover{color:%5;"
- "background:rgba(217,119,6,0.04);}")
- .arg(ui::colors::BG_SURFACE(), ui::colors::TEXT_TERTIARY(),
- ui::colors::BORDER_DIM(), M(12), ui::colors::AMBER()));
- int next = current_page_.page + 1;
- connect(more_btn, &QPushButton::clicked, this, [this, next]() { emit load_more_requested(next); });
- feed_layout_->addWidget(more_btn);
- }
-
- feed_layout_->addStretch();
- feed_container_->setUpdatesEnabled(true);
-}
-
-void ForumPostListPanel::changeEvent(QEvent* event) {
- if (event->type() == QEvent::LanguageChange)
- retranslateUi();
- QWidget::changeEvent(event);
-}
-
-void ForumPostListPanel::retranslateUi() {
- // The channel name and all post cards reflect live data; re-render the feed
- // so its tr() strings (counts, badges, relative times, empty state) update.
- rebuild_feed();
-}
-
-} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/forum/ForumPostListPanel.h b/fincept-qt/src/screens/forum/ForumPostListPanel.h
deleted file mode 100644
index 12a5110e4..000000000
--- a/fincept-qt/src/screens/forum/ForumPostListPanel.h
+++ /dev/null
@@ -1,58 +0,0 @@
-// src/screens/forum/ForumPostListPanel.h
-#pragma once
-#include "services/forum/ForumModels.h"
-
-#include <QEvent>
-#include <QLabel>
-#include <QScrollArea>
-#include <QTimer>
-#include <QVBoxLayout>
-#include <QWidget>
-
-namespace fincept::screens {
-
-class ForumPostListPanel : public QWidget {
- Q_OBJECT
- public:
- explicit ForumPostListPanel(QWidget* parent = nullptr);
-
- void set_posts(const services::ForumPostsPage& page, const QString& category_color = {});
- void set_loading(bool on);
- void set_header(const QString& title, const QString& color);
- void set_active_post(const QString& uuid);
- void clear();
-
- signals:
- void post_selected(const services::ForumPost& post);
- void load_more_requested(int page);
-
- protected:
- void changeEvent(QEvent* event) override;
-
- private:
- void build_ui();
- void rebuild_feed();
- void show_skeleton();
- void pulse_skeleton();
- void retranslateUi();
-
- // Header bar
- QLabel* channel_label_ = nullptr; // "# general"
- QLabel* count_label_ = nullptr;
- QWidget* filter_bar_ = nullptr;
-
- // Feed
- QWidget* feed_container_ = nullptr;
- QVBoxLayout* feed_layout_ = nullptr;
- QScrollArea* scroll_ = nullptr;
-
- // Skeleton
- QWidget* skeleton_widget_ = nullptr;
- QTimer* skeleton_timer_ = nullptr;
-
- services::ForumPostsPage current_page_;
- QString active_uuid_;
- QString category_color_;
-};
-
-} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/forum/ForumPostReaderPanel.cpp b/fincept-qt/src/screens/forum/ForumPostReaderPanel.cpp
deleted file mode 100644
index 797afff6f..000000000
--- a/fincept-qt/src/screens/forum/ForumPostReaderPanel.cpp
+++ /dev/null
@@ -1,565 +0,0 @@
-// src/screens/forum/ForumPostReaderPanel.cpp
-#include "screens/forum/ForumPostReaderPanel.h"
-
-#include "services/forum/ForumService.h"
-#include "ui/theme/Theme.h"
-#include "ui/theme/ThemeManager.h"
-
-#include <QCoreApplication>
-#include <QDateTime>
-#include <QFrame>
-#include <QHBoxLayout>
-#include <QPushButton>
-#include <QScrollArea>
-
-namespace fincept::screens {
-
-static QString M(int sz = 12) {
- return QString("font-family:'Consolas','Courier New',monospace;font-size:%1px;").arg(sz);
-}
-
-static QString rel_time(const QString& iso) {
- if (iso.isEmpty())
- return {};
- auto dt = QDateTime::fromString(iso, Qt::ISODate);
- if (!dt.isValid())
- dt = QDateTime::fromString(iso.left(19), "yyyy-MM-ddTHH:mm:ss");
- if (!dt.isValid())
- return iso.left(10);
- qint64 sec = dt.secsTo(QDateTime::currentDateTimeUtc());
- if (sec < 0)
- sec = 0;
- if (sec < 60)
- return QCoreApplication::translate("ForumPostReaderPanel", "%1s ago").arg(sec);
- if (sec < 3600)
- return QCoreApplication::translate("ForumPostReaderPanel", "%1m ago").arg(sec / 60);
- if (sec < 86400)
- return QCoreApplication::translate("ForumPostReaderPanel", "%1h ago").arg(sec / 3600);
- return QCoreApplication::translate("ForumPostReaderPanel", "%1d ago").arg(sec / 86400);
-}
-
-static QString det_color(const QString& s) {
- static const char* pal[] = {"#d97706", "#06b6d4", "#10b981", "#8b5cf6", "#f97316",
- "#3b82f6", "#ec4899", "#14b8a6", "#84cc16", "#ef4444"};
- return pal[qHash(s) % 10];
-}
-
-ForumPostReaderPanel::ForumPostReaderPanel(QWidget* parent) : QWidget(parent) {
- connect(&ui::ThemeManager::instance(), &ui::ThemeManager::theme_changed, this, [this](const ui::ThemeTokens&) {
- setStyleSheet(QString("background:%1;color:%2;").arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY()));
- });
- build_ui();
-}
-
-void ForumPostReaderPanel::build_ui() {
- setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
- auto* root = new QVBoxLayout(this);
- root->setContentsMargins(0, 0, 0, 0);
- root->setSpacing(0);
-
- stack_ = new QStackedWidget(this);
-
- // ── Page 0: empty placeholder ─────────────────────────────────────────────
- auto* empty_page = new QWidget(this);
- empty_page->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
- {
- auto* vl = new QVBoxLayout(empty_page);
- vl->setAlignment(Qt::AlignCenter);
- vl->setSpacing(10);
-
- auto* icon = new QLabel("◈");
- icon->setAlignment(Qt::AlignCenter);
- icon->setStyleSheet(QString("color:%1;font-size:40px;background:transparent;").arg(ui::colors::BORDER_DIM()));
-
- empty_title_ = new QLabel(tr("SELECT A POST"));
- empty_title_->setAlignment(Qt::AlignCenter);
- empty_title_->setStyleSheet(QString("color:%1;font-size:14px;font-weight:700;letter-spacing:2px;"
- "background:transparent;%2")
- .arg(ui::colors::TEXT_TERTIARY(), M(14)));
-
- empty_sub_ = new QLabel(tr("Click any post from the feed to read it"));
- empty_sub_->setAlignment(Qt::AlignCenter);
- empty_sub_->setStyleSheet(
- QString("color:%1;font-size:11px;background:transparent;%2").arg(ui::colors::TEXT_DIM(), M(11)));
-
- vl->addWidget(icon);
- vl->addSpacing(4);
- vl->addWidget(empty_title_);
- vl->addWidget(empty_sub_);
- }
- stack_->addWidget(empty_page); // 0
-
- // ── Page 1: loading ───────────────────────────────────────────────────────
- auto* load_page = new QWidget(this);
- load_page->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
- {
- auto* vl = new QVBoxLayout(load_page);
- vl->setAlignment(Qt::AlignCenter);
- vl->setSpacing(10);
-
- spin_label_ = new QLabel("⣾");
- spin_label_->setAlignment(Qt::AlignCenter);
- spin_label_->setStyleSheet(
- QString("color:%1;font-size:24px;background:transparent;%2").arg(ui::colors::AMBER(), M(24)));
-
- loading_text_ = new QLabel(tr("Loading..."));
- loading_text_->setAlignment(Qt::AlignCenter);
- loading_text_->setStyleSheet(
- QString("color:%1;font-size:11px;background:transparent;%2").arg(ui::colors::TEXT_TERTIARY(), M(11)));
-
- vl->addWidget(spin_label_);
- vl->addWidget(loading_text_);
- }
- stack_->addWidget(load_page); // 1
-
- spin_timer_ = new QTimer(this);
- spin_timer_->setInterval(100);
- connect(spin_timer_, &QTimer::timeout, this, [this]() {
- static const QString frames[] = {"⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"};
- spin_label_->setText(frames[spin_frame_++ % 8]);
- });
-
- // ── Page 2: content ───────────────────────────────────────────────────────
- content_page_ = new QWidget(this);
- content_page_->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
- auto* content_root = new QVBoxLayout(content_page_);
- content_root->setContentsMargins(0, 0, 0, 0);
- content_root->setSpacing(0);
-
- // ── Post header with gradient background ──────────────────────────────────
- auto* post_hdr = new QWidget(this);
- post_hdr->setStyleSheet(QString("background:qlineargradient(x1:0,y1:0,x2:0,y2:1,"
- "stop:0 %1,stop:1 %2);"
- "border-bottom:1px solid %3;")
- .arg(ui::colors::BG_SURFACE(), ui::colors::BG_BASE(), ui::colors::BORDER_DIM()));
- auto* hdr_vl = new QVBoxLayout(post_hdr);
- hdr_vl->setContentsMargins(20, 16, 20, 14);
- hdr_vl->setSpacing(8);
-
- // Category chip + time row
- auto* chip_row = new QWidget(this);
- chip_row->setStyleSheet("background:transparent;");
- auto* chip_hl = new QHBoxLayout(chip_row);
- chip_hl->setContentsMargins(0, 0, 0, 0);
- chip_hl->setSpacing(8);
-
- category_chip_ = new QLabel;
- category_chip_->setFixedHeight(18);
- category_chip_->setStyleSheet(QString("color:%1;font-size:9px;font-weight:700;letter-spacing:0.8px;"
- "background:transparent;border:1px solid %1;"
- "padding:1px 8px;border-radius:9px;%2")
- .arg(ui::colors::AMBER(), M(9)));
-
- meta_label_ = new QLabel;
- meta_label_->setStyleSheet(
- QString("color:%1;font-size:10px;background:transparent;%2").arg(ui::colors::TEXT_DIM(), M(10)));
-
- chip_hl->addWidget(category_chip_);
- chip_hl->addStretch();
- chip_hl->addWidget(meta_label_);
- hdr_vl->addWidget(chip_row);
-
- // Title
- title_label_ = new QLabel;
- title_label_->setWordWrap(true);
- title_label_->setStyleSheet(QString("color:%1;font-size:16px;font-weight:700;line-height:1.4;"
- "background:transparent;%2")
- .arg(ui::colors::TEXT_PRIMARY(), M(16)));
- hdr_vl->addWidget(title_label_);
-
- // Author row
- author_label_ = new QLabel;
- author_label_->setTextFormat(Qt::RichText);
- author_label_->setTextInteractionFlags(Qt::TextBrowserInteraction);
- author_label_->setOpenExternalLinks(false);
- author_label_->setStyleSheet(
- QString("color:%1;font-size:11px;background:transparent;%2").arg(ui::colors::TEXT_TERTIARY(), M(11)));
- connect(author_label_, &QLabel::linkActivated, this, [this](const QString& link) {
- if (link.startsWith("author:"))
- emit author_clicked(link.mid(7));
- });
- hdr_vl->addWidget(author_label_);
-
- // Gradient separator
- auto* hdr_sep = new QWidget(this);
- hdr_sep->setFixedHeight(2);
- hdr_sep->setStyleSheet(QString("background:qlineargradient(x1:0,y1:0,x2:1,y2:0,"
- "stop:0 %1,stop:0.3 %2,stop:1 transparent);")
- .arg(ui::colors::AMBER(), ui::colors::BORDER_DIM()));
- hdr_vl->addWidget(hdr_sep);
- content_root->addWidget(post_hdr);
-
- // ── Scrollable area ───────────────────────────────────────────────────────
- auto* scroll = new QScrollArea;
- scroll->setWidgetResizable(true);
- scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- scroll->setStyleSheet(QString("QScrollArea{border:none;background:%1;}"
- "QScrollBar:vertical{width:6px;background:transparent;margin:0;}"
- "QScrollBar::handle:vertical{background:%2;min-height:30px;"
- "border-radius:3px;}"
- "QScrollBar::add-line:vertical,QScrollBar::sub-line:vertical"
- "{height:0;}")
- .arg(ui::colors::BG_BASE(), ui::colors::BORDER_DIM()));
-
- auto* scroll_w = new QWidget(this);
- scroll_w->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
- auto* scroll_vl = new QVBoxLayout(scroll_w);
- scroll_vl->setContentsMargins(0, 0, 0, 0);
- scroll_vl->setSpacing(0);
-
- // Post body
- body_label_ = new QLabel;
- body_label_->setWordWrap(true);
- body_label_->setTextFormat(Qt::PlainText);
- body_label_->setAlignment(Qt::AlignTop | Qt::AlignLeft);
- body_label_->setStyleSheet(QString("color:%1;font-size:13px;line-height:1.7;background:transparent;"
- "padding:16px 20px;border-bottom:1px solid %2;%3")
- .arg(ui::colors::TEXT_SECONDARY(), ui::colors::BORDER_DIM(), M(13)));
- scroll_vl->addWidget(body_label_);
-
- // ── Engagement bar ────────────────────────────────────────────────────────
- auto* eng_bar = new QWidget(this);
- eng_bar->setFixedHeight(40);
- eng_bar->setStyleSheet(
- QString("background:%1;border-bottom:1px solid %2;").arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
- auto* eng_hl = new QHBoxLayout(eng_bar);
- eng_hl->setContentsMargins(20, 0, 20, 0);
- eng_hl->setSpacing(14);
-
- up_btn_ = new QPushButton(tr("▲ Upvote"));
- up_btn_->setFixedHeight(26);
- up_btn_->setCursor(Qt::PointingHandCursor);
- up_btn_->setStyleSheet(QString("QPushButton{background:rgba(217,119,6,0.06);"
- "color:%1;border:1px solid rgba(217,119,6,0.2);"
- "font-size:10px;font-weight:700;padding:0 12px;"
- "border-radius:13px;%2}"
- "QPushButton:hover{background:rgba(217,119,6,0.12);"
- "color:%3;border-color:rgba(217,119,6,0.5);}")
- .arg(ui::colors::TEXT_SECONDARY(), M(10), ui::colors::AMBER()));
- connect(up_btn_, &QPushButton::clicked, this, [this]() {
- if (!current_detail_.post.post_uuid.isEmpty())
- emit vote_post(current_detail_.post.post_uuid, "up");
- });
-
- likes_label_ = new QLabel("▲ 0");
- likes_label_->setStyleSheet(
- QString("color:%1;font-size:11px;background:transparent;%2").arg(ui::colors::TEXT_TERTIARY(), M(11)));
-
- replies_label_ = new QLabel(tr("◆ %1 replies").arg(0));
- replies_label_->setStyleSheet(
- QString("color:%1;font-size:11px;background:transparent;%2").arg(ui::colors::TEXT_TERTIARY(), M(11)));
-
- views_label_ = new QLabel(tr("◉ %1 views").arg(0));
- views_label_->setStyleSheet(
- QString("color:%1;font-size:11px;background:transparent;%2").arg(ui::colors::TEXT_DIM(), M(11)));
-
- eng_hl->addWidget(up_btn_);
- eng_hl->addWidget(likes_label_);
- eng_hl->addWidget(replies_label_);
- eng_hl->addStretch();
- eng_hl->addWidget(views_label_);
- scroll_vl->addWidget(eng_bar);
-
- // ── Comments header ───────────────────────────────────────────────────────
- auto* com_hdr = new QWidget(this);
- com_hdr->setFixedHeight(28);
- com_hdr->setStyleSheet(
- QString("background:%1;border-bottom:1px solid %2;").arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
- auto* com_hdr_hl = new QHBoxLayout(com_hdr);
- com_hdr_hl->setContentsMargins(20, 0, 20, 0);
- com_hdr_hl->setSpacing(6);
- auto* com_dot = new QLabel("◆");
- com_dot->setStyleSheet(QString("color:%1;font-size:7px;background:transparent;").arg(ui::colors::CYAN()));
- replies_hdr_ = new QLabel(tr("REPLIES"));
- replies_hdr_->setStyleSheet(QString("color:%1;font-size:10px;font-weight:700;letter-spacing:1.5px;"
- "background:transparent;%2")
- .arg(ui::colors::TEXT_TERTIARY(), M(10)));
- com_hdr_hl->addWidget(com_dot);
- com_hdr_hl->addWidget(replies_hdr_);
- com_hdr_hl->addStretch();
- scroll_vl->addWidget(com_hdr);
-
- // Comments area
- comments_area_ = new QWidget(this);
- comments_area_->setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
- comments_layout_ = new QVBoxLayout(comments_area_);
- comments_layout_->setContentsMargins(0, 0, 0, 0);
- comments_layout_->setSpacing(0);
- scroll_vl->addWidget(comments_area_);
- scroll_vl->addStretch();
-
- scroll->setWidget(scroll_w);
- content_root->addWidget(scroll, 1);
-
- // ── Reply compose bar ─────────────────────────────────────────────────────
- auto* compose = new QWidget(this);
- compose->setFixedHeight(48);
- compose->setStyleSheet(
- QString("background:%1;border-top:1px solid %2;").arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
- auto* compose_hl = new QHBoxLayout(compose);
- compose_hl->setContentsMargins(16, 8, 16, 8);
- compose_hl->setSpacing(8);
-
- reply_input_ = new QLineEdit;
- reply_input_->setPlaceholderText(tr("Write a reply..."));
- reply_input_->setFixedHeight(32);
- reply_input_->setStyleSheet(QString("QLineEdit{background:rgba(255,255,255,0.03);color:%1;"
- "border:1px solid %2;padding:4px 12px;font-size:12px;"
- "border-radius:4px;%3}"
- "QLineEdit:focus{border-color:%4;color:%5;}"
- "QLineEdit::placeholder{color:%6;}")
- .arg(ui::colors::TEXT_SECONDARY(), ui::colors::BORDER_DIM(), M(12),
- ui::colors::BORDER_BRIGHT(), ui::colors::TEXT_PRIMARY(),
- ui::colors::TEXT_DIM()));
-
- send_btn_ = new QPushButton(tr("Reply"));
- send_btn_->setFixedSize(72, 32);
- send_btn_->setCursor(Qt::PointingHandCursor);
- send_btn_->setStyleSheet(QString("QPushButton{background:rgba(217,119,6,0.1);color:%1;"
- "border:1px solid rgba(217,119,6,0.25);font-size:11px;"
- "font-weight:700;border-radius:4px;%2}"
- "QPushButton:hover{background:rgba(217,119,6,0.2);"
- "color:%3;border-color:rgba(217,119,6,0.5);}")
- .arg(ui::colors::TEXT_SECONDARY(), M(11), ui::colors::AMBER()));
-
- auto submit = [this]() {
- QString text = reply_input_->text().trimmed();
- if (text.isEmpty() || current_detail_.post.post_uuid.isEmpty())
- return;
- emit comment_submitted(current_detail_.post.post_uuid, text);
- reply_input_->clear();
- };
- connect(send_btn_, &QPushButton::clicked, this, submit);
- connect(reply_input_, &QLineEdit::returnPressed, this, submit);
-
- compose_hl->addWidget(reply_input_, 1);
- compose_hl->addWidget(send_btn_);
- content_root->addWidget(compose);
-
- stack_->addWidget(content_page_); // 2
- root->addWidget(stack_, 1);
- stack_->setCurrentIndex(0);
-}
-
-void ForumPostReaderPanel::set_loading(bool on) {
- if (on) {
- spin_frame_ = 0;
- spin_timer_->start();
- stack_->setCurrentIndex(1);
- } else {
- spin_timer_->stop();
- }
-}
-
-void ForumPostReaderPanel::clear() {
- spin_timer_->stop();
- stack_->setCurrentIndex(0);
- current_detail_ = {};
-}
-
-void ForumPostReaderPanel::show_post(const services::ForumPostDetail& detail) {
- spin_timer_->stop();
- current_detail_ = detail;
-
- QString cat_color =
- detail.post.category_color.isEmpty() ? det_color(detail.post.category_name) : detail.post.category_color;
-
- category_chip_->setText(detail.post.category_name.toUpper());
- category_chip_->setStyleSheet(QString("color:%1;font-size:9px;font-weight:700;letter-spacing:0.8px;"
- "background:transparent;border:1px solid %1;"
- "padding:1px 8px;border-radius:9px;%2")
- .arg(cat_color, M(9)));
-
- meta_label_->setText(rel_time(detail.post.created_at));
- title_label_->setText(detail.post.title);
-
- // Author
- QString av_color = det_color(detail.post.author_display_name);
- QString initials =
- detail.post.author_display_name.isEmpty() ? "?" : detail.post.author_display_name.left(2).toUpper();
- author_label_->setText(QString("<span style='background:%1;color:%2;font-size:9px;"
- "font-family:Consolas;padding:2px 5px;font-weight:700;"
- "border-radius:10px;'>%3</span>"
- "&nbsp;"
- "<a href='author:%4' style='color:%5;text-decoration:none;"
- "font-family:Consolas;font-size:11px;font-weight:600;'>%6</a>")
- .arg(av_color, ui::colors::BG_BASE(), initials, detail.post.author_name,
- ui::colors::TEXT_SECONDARY(), detail.post.author_display_name));
-
- body_label_->setText(detail.post.content);
-
- // Engagement
- bool voted = (detail.post.user_vote == "up");
- QString lc = voted || detail.post.likes > 0 ? ui::colors::AMBER() : ui::colors::TEXT_DIM();
- likes_label_->setText(QString("▲ %1").arg(detail.post.likes));
- likes_label_->setStyleSheet(QString("color:%1;font-size:11px;font-weight:600;"
- "background:transparent;%2")
- .arg(lc, M(11)));
-
- replies_label_->setText(detail.total_comments == 1 ? tr("◆ %1 reply").arg(detail.total_comments)
- : tr("◆ %1 replies").arg(detail.total_comments));
-
- views_label_->setText(tr("◉ %1 views").arg(detail.post.views));
-
- rebuild_comments();
- stack_->setCurrentIndex(2);
-}
-
-void ForumPostReaderPanel::rebuild_comments() {
- while (comments_layout_->count() > 0) {
- auto* item = comments_layout_->takeAt(0);
- if (item->widget())
- item->widget()->deleteLater();
- delete item;
- }
-
- if (current_detail_.comments.isEmpty()) {
- auto* no_com = new QWidget(this);
- no_com->setMinimumHeight(60);
- no_com->setStyleSheet("background:transparent;");
- auto* vl = new QVBoxLayout(no_com);
- vl->setAlignment(Qt::AlignCenter);
- vl->setSpacing(4);
-
- auto* icon = new QLabel("◇");
- icon->setAlignment(Qt::AlignCenter);
- icon->setStyleSheet(QString("color:%1;font-size:18px;background:transparent;").arg(ui::colors::BORDER_DIM()));
-
- auto* lbl = new QLabel(tr("NO REPLIES YET"));
- lbl->setAlignment(Qt::AlignCenter);
- lbl->setStyleSheet(QString("color:%1;font-size:11px;font-weight:700;letter-spacing:1px;"
- "background:transparent;%2")
- .arg(ui::colors::TEXT_TERTIARY(), M(11)));
-
- vl->addWidget(icon);
- vl->addWidget(lbl);
- comments_layout_->addWidget(no_com);
- return;
- }
-
- for (int i = 0; i < current_detail_.comments.size(); ++i) {
- const auto& c = current_detail_.comments[i];
- QString avc = det_color(c.author_display_name);
-
- auto* row = new QWidget(this);
- row->setStyleSheet(
- QString("background:%1;border-bottom:1px solid %2;")
- .arg(i % 2 == 0 ? ui::colors::BG_BASE() : ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
- auto* row_vl = new QVBoxLayout(row);
- row_vl->setContentsMargins(20, 10, 20, 8);
- row_vl->setSpacing(5);
-
- // ── Comment header ────────────────────────────────────────────────────
- auto* com_top = new QWidget(this);
- com_top->setStyleSheet("background:transparent;");
- auto* com_hl = new QHBoxLayout(com_top);
- com_hl->setContentsMargins(0, 0, 0, 0);
- com_hl->setSpacing(8);
-
- auto* thread_line = new QWidget(this);
- thread_line->setFixedSize(3, 20);
- thread_line->setStyleSheet(QString("background:%1;border-radius:1px;").arg(avc));
-
- auto* av = new QLabel(c.author_display_name.left(2).toUpper());
- av->setFixedSize(22, 22);
- av->setAlignment(Qt::AlignCenter);
- av->setStyleSheet(QString("color:%1;font-size:9px;font-weight:700;background:%2;"
- "border-radius:11px;%3")
- .arg(ui::colors::BG_BASE(), avc, M(9)));
-
- auto* author_lbl = new QLabel(c.author_display_name);
- author_lbl->setStyleSheet(QString("color:%1;font-size:11px;font-weight:600;"
- "background:transparent;%2")
- .arg(ui::colors::TEXT_PRIMARY(), M(11)));
-
- auto* time_lbl = new QLabel(rel_time(c.created_at));
- time_lbl->setStyleSheet(
- QString("color:%1;font-size:10px;background:transparent;%2").arg(ui::colors::TEXT_DIM(), M(10)));
-
- bool voted = (c.user_vote == "up");
- auto* likes_lbl = new QLabel(QString("▲ %1").arg(c.likes));
- likes_lbl->setStyleSheet(QString("color:%1;font-size:10px;font-weight:600;"
- "background:transparent;%2")
- .arg(voted || c.likes > 0 ? ui::colors::AMBER() : ui::colors::TEXT_DIM(), M(10)));
-
- com_hl->addWidget(thread_line);
- com_hl->addWidget(av);
- com_hl->addWidget(author_lbl);
- com_hl->addStretch();
- com_hl->addWidget(time_lbl);
- com_hl->addSpacing(6);
- com_hl->addWidget(likes_lbl);
- row_vl->addWidget(com_top);
-
- // ── Comment body ──────────────────────────────────────────────────────
- auto* body = new QLabel(c.content);
- body->setWordWrap(true);
- body->setTextFormat(Qt::PlainText);
- body->setAlignment(Qt::AlignTop | Qt::AlignLeft);
- body->setStyleSheet(QString("color:%1;font-size:12px;line-height:1.5;"
- "background:transparent;padding-left:28px;%2")
- .arg(ui::colors::TEXT_SECONDARY(), M(12)));
- row_vl->addWidget(body);
-
- // ── Action row ────────────────────────────────────────────────────────
- auto* act_row = new QWidget(this);
- act_row->setStyleSheet("background:transparent;");
- auto* act_hl = new QHBoxLayout(act_row);
- act_hl->setContentsMargins(28, 0, 0, 0);
- act_hl->setSpacing(12);
-
- auto make_act = [&](const QString& label, const QString& color, const QString& vtype) {
- auto* btn = new QPushButton(label);
- btn->setFixedHeight(18);
- btn->setCursor(Qt::PointingHandCursor);
- bool active = (c.user_vote == vtype);
- btn->setStyleSheet(active ? QString("QPushButton{background:transparent;color:%1;"
- "border:none;font-size:10px;font-weight:700;"
- "padding:0;%2}")
- .arg(color, M(10))
- : QString("QPushButton{background:transparent;color:%1;"
- "border:none;font-size:10px;padding:0;%2}"
- "QPushButton:hover{color:%3;}")
- .arg(ui::colors::TEXT_DIM(), M(10), color));
- auto uuid = c.comment_uuid;
- connect(btn, &QPushButton::clicked, this, [this, uuid, vtype]() { emit vote_comment(uuid, vtype); });
- return btn;
- };
-
- act_hl->addWidget(make_act(tr("▲ upvote"), ui::colors::AMBER(), "up"));
- act_hl->addWidget(make_act(tr("▼ downvote"), ui::colors::TEXT_TERTIARY(), "down"));
- act_hl->addStretch();
- row_vl->addWidget(act_row);
-
- comments_layout_->addWidget(row);
- }
-}
-
-void ForumPostReaderPanel::changeEvent(QEvent* event) {
- if (event->type() == QEvent::LanguageChange)
- retranslateUi();
- QWidget::changeEvent(event);
-}
-
-void ForumPostReaderPanel::retranslateUi() {
- if (empty_title_)
- empty_title_->setText(tr("SELECT A POST"));
- if (empty_sub_)
- empty_sub_->setText(tr("Click any post from the feed to read it"));
- if (loading_text_)
- loading_text_->setText(tr("Loading..."));
- if (up_btn_)
- up_btn_->setText(tr("▲ Upvote"));
- if (replies_hdr_)
- replies_hdr_->setText(tr("REPLIES"));
- if (reply_input_)
- reply_input_->setPlaceholderText(tr("Write a reply..."));
- if (send_btn_)
- send_btn_->setText(tr("Reply"));
- // Post header/body, counters and comments are live data; re-show the
- // current post so they re-render in the new language.
- if (!current_detail_.post.post_uuid.isEmpty() && stack_ && stack_->currentIndex() == 2)
- show_post(current_detail_);
-}
-
-} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/forum/ForumPostReaderPanel.h b/fincept-qt/src/screens/forum/ForumPostReaderPanel.h
deleted file mode 100644
index 6958b3d2e..000000000
--- a/fincept-qt/src/screens/forum/ForumPostReaderPanel.h
+++ /dev/null
@@ -1,80 +0,0 @@
-// src/screens/forum/ForumPostReaderPanel.h
-#pragma once
-#include "services/forum/ForumModels.h"
-
-#include <QEvent>
-#include <QLabel>
-#include <QLineEdit>
-#include <QPushButton>
-#include <QStackedWidget>
-#include <QTimer>
-#include <QVBoxLayout>
-#include <QWidget>
-
-namespace fincept::screens {
-
-class ForumPostReaderPanel : public QWidget {
- Q_OBJECT
- public:
- explicit ForumPostReaderPanel(QWidget* parent = nullptr);
-
- void show_post(const services::ForumPostDetail& detail);
- void set_loading(bool on);
- void clear();
-
- signals:
- void comment_submitted(const QString& post_uuid, const QString& content);
- void vote_post(const QString& post_uuid, const QString& vote_type);
- void vote_comment(const QString& comment_uuid, const QString& vote_type);
- void author_clicked(const QString& username);
-
- protected:
- void changeEvent(QEvent* event) override;
-
- private:
- void build_ui();
- void rebuild_comments();
- void retranslateUi();
-
- // Static chrome (cached for retranslateUi)
- QLabel* empty_title_ = nullptr;
- QLabel* empty_sub_ = nullptr;
- QLabel* loading_text_ = nullptr;
- QPushButton* up_btn_ = nullptr;
- QLabel* replies_hdr_ = nullptr;
- QPushButton* send_btn_ = nullptr;
-
- QStackedWidget* stack_ = nullptr; // 0=empty, 1=loading, 2=content
- QWidget* content_page_ = nullptr;
-
- // Post header
- QLabel* category_chip_ = nullptr;
- QLabel* title_label_ = nullptr;
- QLabel* author_label_ = nullptr;
- QLabel* meta_label_ = nullptr;
-
- // Post body
- QLabel* body_label_ = nullptr;
-
- // Engagement bar
- QWidget* vote_up_btn_ = nullptr;
- QLabel* likes_label_ = nullptr;
- QLabel* replies_label_ = nullptr;
- QLabel* views_label_ = nullptr;
-
- // Comments
- QWidget* comments_area_ = nullptr;
- QVBoxLayout* comments_layout_ = nullptr;
-
- // Reply input
- QLineEdit* reply_input_ = nullptr;
-
- // Loading spinner
- QLabel* spin_label_ = nullptr;
- QTimer* spin_timer_ = nullptr;
- int spin_frame_ = 0;
-
- services::ForumPostDetail current_detail_;
-};
-
-} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/forum/ForumScreen.cpp b/fincept-qt/src/screens/forum/ForumScreen.cpp
index 12d67ae96..682ab4ffa 100644
--- a/fincept-qt/src/screens/forum/ForumScreen.cpp
+++ b/fincept-qt/src/screens/forum/ForumScreen.cpp
@@ -14,6 +14,8 @@
#include <QFrame>
#include <QHBoxLayout>
#include <QHideEvent>
+#include <QMessageBox>
+#include <QPointer>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
@@ -120,15 +122,26 @@ void ForumScreen::build_ui() {
connect(thread_, &ForumThreadPanel::back_requested, this, &ForumScreen::navigate_back_to_feed);
connect(thread_, &ForumThreadPanel::comment_submitted, this, [this](const QString& uuid, const QString& content) {
- services::ForumService::instance().create_comment(uuid, content, [this, uuid](bool ok, const QString&) {
+ QPointer<ForumScreen> self = this;
+ services::ForumService::instance().create_comment(uuid, content, [self, uuid](bool ok, const QString& msg) {
+ if (!self)
+ return;
if (ok) {
- thread_->set_loading(true);
- services::ForumService::instance().fetch_post(uuid, [this](bool ok2, services::ForumPostDetail d) {
+ self->thread_->clear_reply_input(); // only clear once it actually posted
+ self->thread_->set_loading(true);
+ services::ForumService::instance().fetch_post(uuid, [self](bool ok2, services::ForumPostDetail d) {
+ if (!self)
+ return;
if (ok2)
- thread_->show_post(d);
+ self->thread_->show_post(d);
else
- thread_->set_loading(false);
+ self->thread_->set_loading(false);
});
+ } else {
+ LOG_WARN("ForumScreen", "Create comment failed: " + msg);
+ QMessageBox::warning(self, ForumScreen::tr("Reply Failed"),
+ msg.isEmpty() ? ForumScreen::tr("Could not post your reply. Please try again.")
+ : ForumScreen::tr("Could not post your reply: %1").arg(msg));
}
});
});
@@ -512,18 +525,39 @@ void ForumScreen::show_new_post_dialog(int category_id) {
"border-color:rgba(217,119,6,0.6);"
"background:rgba(217,119,6,0.2);}")
.arg(ui::colors::TEXT_SECONDARY(), M(11), ui::colors::AMBER()));
- connect(submit, &QPushButton::clicked, this, [this, dlg, title_edit, body_edit, category_id]() {
+ connect(submit, &QPushButton::clicked, this, [this, dlg, title_edit, body_edit, submit, category_id]() {
QString title = title_edit->text().trimmed();
QString content = body_edit->toPlainText().trimmed();
if (title.isEmpty() || content.isEmpty())
return;
- dlg->accept();
+ // Keep the dialog (and the user's typed post) open until the async call
+ // returns. Only close on success; on failure re-enable Publish and show
+ // the error so the text isn't lost. The old code accept()ed (discarding
+ // the text) BEFORE the call and merely LOG_WARN'd on failure.
+ submit->setEnabled(false);
+ submit->setText(tr("PUBLISHING…"));
+ QPointer<ForumScreen> self = this;
+ QPointer<QDialog> dlg_guard(dlg);
+ QPointer<QPushButton> submit_guard(submit);
services::ForumService::instance().create_post(
- category_id, title, content, [this](bool ok, const QString& msg) {
- if (ok)
- on_category_selected(active_category_id_, active_category_name_, active_category_color_);
- else
- LOG_WARN("ForumScreen", "Create post failed: " + msg);
+ category_id, title, content, [self, dlg_guard, submit_guard](bool ok, const QString& msg) {
+ if (ok) {
+ if (dlg_guard)
+ dlg_guard->accept();
+ if (self)
+ self->on_category_selected(self->active_category_id_, self->active_category_name_,
+ self->active_category_color_);
+ return;
+ }
+ LOG_WARN("ForumScreen", "Create post failed: " + msg);
+ if (submit_guard) {
+ submit_guard->setEnabled(true);
+ submit_guard->setText(ForumScreen::tr("PUBLISH POST"));
+ }
+ if (dlg_guard)
+ QMessageBox::warning(dlg_guard, ForumScreen::tr("Post Failed"),
+ msg.isEmpty() ? ForumScreen::tr("Could not publish your post. Please try again.")
+ : ForumScreen::tr("Could not publish your post: %1").arg(msg));
});
});
diff --git a/fincept-qt/src/screens/forum/ForumThreadPanel.cpp b/fincept-qt/src/screens/forum/ForumThreadPanel.cpp
index c26b4aa2b..4c5b4d188 100644
--- a/fincept-qt/src/screens/forum/ForumThreadPanel.cpp
+++ b/fincept-qt/src/screens/forum/ForumThreadPanel.cpp
@@ -401,8 +401,10 @@ void ForumThreadPanel::build_ui() {
QString txt = t_reply_input_->text().trimmed();
if (txt.isEmpty() || current_.post.post_uuid.isEmpty())
return;
+ // Don't clear optimistically — ForumScreen calls clear_reply_input()
+ // only after the comment actually posts, so a network/auth failure keeps
+ // the user's typed reply instead of silently discarding it.
emit comment_submitted(current_.post.post_uuid, txt);
- t_reply_input_->clear();
};
connect(send_btn_, &QPushButton::clicked, this, submit);
connect(t_reply_input_, &QLineEdit::returnPressed, this, submit);
@@ -431,6 +433,11 @@ void ForumThreadPanel::set_loading(bool on) {
}
}
+void ForumThreadPanel::clear_reply_input() {
+ if (t_reply_input_)
+ t_reply_input_->clear();
+}
+
void ForumThreadPanel::clear() {
spin_timer_->stop();
current_ = {};
diff --git a/fincept-qt/src/screens/forum/ForumThreadPanel.h b/fincept-qt/src/screens/forum/ForumThreadPanel.h
index fee2ed949..a90f040c6 100644
--- a/fincept-qt/src/screens/forum/ForumThreadPanel.h
+++ b/fincept-qt/src/screens/forum/ForumThreadPanel.h
@@ -20,6 +20,9 @@ class ForumThreadPanel : public QWidget {
void show_post(const services::ForumPostDetail& detail);
void set_loading(bool on);
+ /// Clear the reply composer. Called by ForumScreen only after a reply has
+ /// actually posted, so a failed submit keeps the user's text.
+ void clear_reply_input();
void clear();
QString reply_draft() const;
void set_reply_draft(const QString& text);
diff --git a/fincept-qt/src/screens/gov_data/GovDataScreen.cpp b/fincept-qt/src/screens/gov_data/GovDataScreen.cpp
index 0b44b9aa9..f060d5083 100644
--- a/fincept-qt/src/screens/gov_data/GovDataScreen.cpp
+++ b/fincept-qt/src/screens/gov_data/GovDataScreen.cpp
@@ -156,13 +156,11 @@ void GovDataScreen::build_ui() {
} else if (prov.id == "hk") {
panel = new GovDataHKPanel(panel_stack_);
} else if (prov.id == "universal-ckan") {
- GovProviderOptions ckan_opts;
- ckan_opts.portal_combo_items = {"data.gov.uk", "open.canada.ca", "data.gov.au", "data.gov.hk",
- "opendata.swiss", "data.gouv.fr", "data.gov", "openafrica.net"};
- ckan_opts.portal_combo_tooltip =
- tr("This panel uses datagovuk_api.py which queries data.gov.uk.\n"
- "The selector shows all CKAN portals covered by the universal provider.");
- panel = new GovDataProviderPanel(prov.script, prov.color, "Publishers", ckan_opts, panel_stack_);
+ // The universal CKAN connector (datagovuk_api.py) hardcodes the
+ // data.gov.uk endpoint, so serve this provider with the dedicated UK
+ // panel (Publishers → Datasets → Resources + search) instead of the
+ // generic provider panel with its non-functional portal selector.
+ panel = new GovDataUKPanel(panel_stack_);
} else if (prov.id == "australia") {
panel = new GovDataAustraliaPanel(panel_stack_);
} else {
diff --git a/fincept-qt/src/screens/markets/MarketPanel.cpp b/fincept-qt/src/screens/markets/MarketPanel.cpp
index 4b1af2fac..de1a6242c 100644
--- a/fincept-qt/src/screens/markets/MarketPanel.cpp
+++ b/fincept-qt/src/screens/markets/MarketPanel.cpp
@@ -217,7 +217,11 @@ void MarketPanel::open_cols_dropdown() {
// NAME is now the locked first column (renders the friendly name), so the
// optional set offers TICKER instead for users who also want the raw symbol.
- const QStringList optional = {"CHG", "CHG%", "HIGH", "LOW", "VOL", "BID", "ASK", "OPEN", "TICKER"};
+ // BID/ASK/OPEN are intentionally omitted: the markets quote snapshot
+ // (QuoteData) carries no bid, ask, or open, so those columns could only ever
+ // render "--". (Wiring real values would need MarketDataService + the hub
+ // QuoteData serialization to carry them — tracked as a follow-up.)
+ const QStringList optional = {"CHG", "CHG%", "HIGH", "LOW", "VOL", "TICKER"};
for (const QString& col : optional) {
auto* act = menu->addAction(column_label(col));
@@ -486,11 +490,11 @@ void MarketPanel::populate(const QVector<services::QuoteData>& quotes) {
table_->setItem(row, ci,
mk(fincept::ui::formatting::format_compact_volume(static_cast<qint64>(q.volume)),
ui::colors::TEXT_DIM()));
- else if (col == "BID")
- table_->setItem(row, ci, mk("--", ui::colors::TEXT_DIM()));
- else if (col == "ASK")
- table_->setItem(row, ci, mk("--", ui::colors::TEXT_DIM()));
- else if (col == "OPEN")
+ else if (col == "BID" || col == "ASK" || col == "OPEN")
+ // No data source in the markets QuoteData snapshot (only OHLC
+ // high/low + last/change/volume are populated). Dropped from the
+ // column picker; this fallback keeps legacy saved configs from
+ // showing an empty cell / hitting the unknown-column path.
table_->setItem(row, ci, mk("--", ui::colors::TEXT_DIM()));
}
}
diff --git a/fincept-qt/src/screens/markets/MarketsScreen.cpp b/fincept-qt/src/screens/markets/MarketsScreen.cpp
index 51956e84f..64f41092f 100644
--- a/fincept-qt/src/screens/markets/MarketsScreen.cpp
+++ b/fincept-qt/src/screens/markets/MarketsScreen.cpp
@@ -529,15 +529,23 @@ void MarketsScreen::update_clocks() {
void MarketsScreen::showEvent(QShowEvent* event) {
QWidget::showEvent(event);
- // Distribute equal space now that geometry is valid.
- // Horizontal: equal column widths.
- if (h_splitter_ && h_splitter_->count() > 1) {
- QList<int> hsizes;
- for (int i = 0; i < h_splitter_->count(); ++i)
- hsizes.append(1000);
- h_splitter_->setSizes(hsizes);
+ // Horizontal (column widths): apply ONCE, now that geometry is valid —
+ // restore the user's saved widths if any, else fall back to equal columns.
+ // Doing an unconditional equalize on EVERY show wiped the saved/manually
+ // adjusted widths that restore_splitter_state() had applied.
+ if (!h_splitter_initialized_ && h_splitter_ && h_splitter_->count() > 1) {
+ h_splitter_initialized_ = true;
+ auto res = SettingsRepository::instance().get("markets_splitter_state");
+ if (res.is_ok() && !res.value().isEmpty()) {
+ restore_splitter_state();
+ } else {
+ QList<int> hsizes;
+ for (int i = 0; i < h_splitter_->count(); ++i)
+ hsizes.append(1000);
+ h_splitter_->setSizes(hsizes);
+ }
}
- // Vertical: equal panel heights within each column.
+ // Vertical: equal panel heights within each column (always, by design).
for (auto* vs : col_splitters_) {
if (vs->count() > 1) {
QList<int> vsizes;
diff --git a/fincept-qt/src/screens/markets/MarketsScreen.h b/fincept-qt/src/screens/markets/MarketsScreen.h
index bd8a65ee7..bbf77d2c0 100644
--- a/fincept-qt/src/screens/markets/MarketsScreen.h
+++ b/fincept-qt/src/screens/markets/MarketsScreen.h
@@ -66,6 +66,7 @@ class MarketsScreen : public QWidget {
// Splitter tree
QSplitter* h_splitter_ = nullptr; // horizontal — columns
QVector<QSplitter*> col_splitters_; // vertical — panels within each column
+ bool h_splitter_initialized_ = false; // horizontal widths applied once (restore/equalize) on first show
// Header bar widgets
QWidget* header_bar_ = nullptr;
diff --git a/fincept-qt/src/screens/news/NewsScreen.cpp b/fincept-qt/src/screens/news/NewsScreen.cpp
index 56dd68ab4..076c2593f 100644
--- a/fincept-qt/src/screens/news/NewsScreen.cpp
+++ b/fincept-qt/src/screens/news/NewsScreen.cpp
@@ -709,35 +709,33 @@ void NewsScreen::apply_filters_async() {
const QString variant = active_variant_;
const QString lang_filter = active_lang_.toLower();
- // For 7D / 30D ranges, merge DB history
- if (time_range == "7D" || time_range == "30D") {
- const int64_t window_sec = (time_range == "30D") ? (30LL * 86400) : (7LL * 86400);
- const int64_t cutoff = QDateTime::currentSecsSinceEpoch() - window_sec;
-
- QSet<QString> live_ids;
- live_ids.reserve(articles_copy.size());
- for (const auto& a : std::as_const(articles_copy))
- live_ids.insert(a.id);
-
- auto merge_into = [&](const QVector<services::NewsArticle>& extras) {
- for (const auto& a : extras)
- if (!live_ids.contains(a.id))
- articles_copy.append(a);
- };
-
- if (!search_lower.isEmpty()) {
- auto fts_result = fincept::NewsArticleRepository::instance().search_fts(search_lower, cutoff, 1000);
- if (fts_result.is_ok())
- merge_into(fts_result.value());
- } else {
- auto db_result = fincept::NewsArticleRepository::instance().load_recent(cutoff, {}, 5000);
- if (db_result.is_ok())
- merge_into(db_result.value());
- }
- }
-
(void)QtConcurrent::run([self, gen, articles_copy = std::move(articles_copy), category, time_range, search_lower,
- sort, variant, lang_filter]() {
+ sort, variant, lang_filter]() mutable {
+ // 7D/30D history merge — moved OFF the UI thread. Reading up to 5000 rows
+ // from SQLite on the UI thread stuttered the UI on each filter keystroke.
+ // Safe on a worker: Database hands out per-thread cloned connections.
+ if (time_range == "7D" || time_range == "30D") {
+ const int64_t hist_window = (time_range == "30D") ? (30LL * 86400) : (7LL * 86400);
+ const int64_t cutoff = QDateTime::currentSecsSinceEpoch() - hist_window;
+ QSet<QString> live_ids;
+ live_ids.reserve(articles_copy.size());
+ for (const auto& a : std::as_const(articles_copy))
+ live_ids.insert(a.id);
+ auto merge_into = [&](const QVector<services::NewsArticle>& extras) {
+ for (const auto& a : extras)
+ if (!live_ids.contains(a.id))
+ articles_copy.append(a);
+ };
+ if (!search_lower.isEmpty()) {
+ auto fts_result = fincept::NewsArticleRepository::instance().search_fts(search_lower, cutoff, 1000);
+ if (fts_result.is_ok())
+ merge_into(fts_result.value());
+ } else {
+ auto db_result = fincept::NewsArticleRepository::instance().load_recent(cutoff, {}, 5000);
+ if (db_result.is_ok())
+ merge_into(db_result.value());
+ }
+ }
int64_t window_sec = 0;
if (time_range == "1H")
window_sec = 3600;
diff --git a/fincept-qt/src/screens/node_editor/NodeEditorScreen.cpp b/fincept-qt/src/screens/node_editor/NodeEditorScreen.cpp
index 6bdb77288..3cc4aa8f2 100644
--- a/fincept-qt/src/screens/node_editor/NodeEditorScreen.cpp
+++ b/fincept-qt/src/screens/node_editor/NodeEditorScreen.cpp
@@ -120,6 +120,21 @@ void NodeEditorScreen::keyPressEvent(QKeyEvent* event) {
if (auto* node = dynamic_cast<NodeItem*>(item))
ids.append(node->node_def().id);
}
+ if (ids.isEmpty()) {
+ event->accept();
+ return;
+ }
+ // Confirm: deletion is NOT undoable (no QUndoCommand is pushed for it)
+ // and the 30s autosave persists it, so an accidental Delete/Backspace
+ // would silently and permanently lose the nodes and their connections.
+ const auto ans = QMessageBox::question(
+ this, tr("Delete Nodes"),
+ tr("Delete %1 selected node(s) and their connections? This cannot be undone.").arg(ids.size()),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (ans != QMessageBox::Yes) {
+ event->accept();
+ return;
+ }
for (const auto& id : ids)
scene_->remove_node(id);
properties_->clear();
diff --git a/fincept-qt/src/screens/polymarket/PolymarketOrderBook.cpp b/fincept-qt/src/screens/polymarket/PolymarketOrderBook.cpp
index 63b2f2214..d7cd55235 100644
--- a/fincept-qt/src/screens/polymarket/PolymarketOrderBook.cpp
+++ b/fincept-qt/src/screens/polymarket/PolymarketOrderBook.cpp
@@ -81,19 +81,44 @@ void PolymarketOrderBook::mousePressEvent(QMouseEvent* event) {
if (y < HEADER_HEIGHT)
return;
- QMutexLocker lock(&mutex_);
- int row_idx = (y - HEADER_HEIGHT) / ROW_HEIGHT;
- int ask_rows = qMin(asks_.size(), 10);
-
- if (row_idx < ask_rows && row_idx < asks_.size()) {
- int ask_i = ask_rows - 1 - row_idx;
- emit price_clicked(asks_[ask_i].price);
- } else {
- int bid_idx = row_idx - ask_rows - 1; // -1 for spread row
- if (bid_idx >= 0 && bid_idx < bids_.size()) {
- emit price_clicked(bids_[bid_idx].price);
+ // Resolve which price level was clicked using the SAME visible-row counts the
+ // painter used, otherwise a click lands on a different level than the one
+ // drawn (which, for a trading order book, fills the order form with a wrong
+ // price). Compute under the lock, then emit outside it so a slot that calls
+ // back into set_data()/clear() can't deadlock on mutex_.
+ double clicked_price = 0.0;
+ bool has_click = false;
+ {
+ QMutexLocker lock(&mutex_);
+ int row_idx = (y - HEADER_HEIGHT) / ROW_HEIGHT;
+ int ask_rows = 0, bid_rows = 0;
+ visible_row_counts(ask_rows, bid_rows);
+
+ if (row_idx < ask_rows) {
+ // Asks are painted highest-first (reversed), so the top row is the
+ // last ask index and the row just above the spread is asks_[0].
+ int ask_i = ask_rows - 1 - row_idx;
+ if (ask_i >= 0 && ask_i < asks_.size()) {
+ clicked_price = asks_[ask_i].price;
+ has_click = true;
+ }
+ } else {
+ int bid_idx = row_idx - ask_rows - 1; // -1 for the spread row
+ if (bid_idx >= 0 && bid_idx < bid_rows && bid_idx < bids_.size()) {
+ clicked_price = bids_[bid_idx].price;
+ has_click = true;
+ }
}
}
+ if (has_click)
+ emit price_clicked(clicked_price);
+}
+
+void PolymarketOrderBook::visible_row_counts(int& ask_rows, int& bid_rows) const {
+ const int h = height();
+ const int max_rows = (h - HEADER_HEIGHT) / ROW_HEIGHT;
+ ask_rows = qMin(asks_.size(), qMax(1, max_rows / 2 - 1));
+ bid_rows = qMin(bids_.size(), qMax(1, max_rows / 2 - 1));
}
void PolymarketOrderBook::rebuild_cache() {
@@ -129,9 +154,8 @@ void PolymarketOrderBook::rebuild_cache() {
p.setPen(QColor(colors::BORDER_DIM()));
p.drawLine(0, HEADER_HEIGHT - 1, w, HEADER_HEIGHT - 1);
- int max_rows = (h - HEADER_HEIGHT) / ROW_HEIGHT;
- int ask_rows = qMin(asks_.size(), qMax(1, max_rows / 2 - 1));
- int bid_rows = qMin(bids_.size(), qMax(1, max_rows / 2 - 1));
+ int ask_rows = 0, bid_rows = 0;
+ visible_row_counts(ask_rows, bid_rows);
// Find max cumulative size for depth bars
double max_depth = 0;
diff --git a/fincept-qt/src/screens/polymarket/PolymarketOrderBook.h b/fincept-qt/src/screens/polymarket/PolymarketOrderBook.h
index 1c5e5aa19..54f1d1b98 100644
--- a/fincept-qt/src/screens/polymarket/PolymarketOrderBook.h
+++ b/fincept-qt/src/screens/polymarket/PolymarketOrderBook.h
@@ -34,6 +34,10 @@ class PolymarketOrderBook : public QWidget {
private:
void rebuild_cache();
+ // Number of ask/bid levels actually painted, derived from the current widget
+ // height. Both the painter and the click hit-test MUST use this so a click
+ // maps to the same level that was drawn. Caller must hold mutex_.
+ void visible_row_counts(int& ask_rows, int& bid_rows) const;
QVector<fincept::services::prediction::OrderLevel> bids_;
QVector<fincept::services::prediction::OrderLevel> asks_;
diff --git a/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp b/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp
index 379f0a355..6bd25c682 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioBlotter.cpp
@@ -366,9 +366,10 @@ void PortfolioBlotter::update_row_price(const QString& symbol, double ltp, doubl
auto* item = table_->item(r, 0);
if (!item || item->data(Qt::UserRole).toString() != symbol)
continue;
- // Column layout: SYMBOL(0), QTY(1), AVG(2), LAST(3), MKT VAL(4), COST(5), P&L(6), P&L%(7), CHG%(8),
- // SPARKLINE(9), WT%(10)
- if (auto* last_item = table_->item(r, 3))
+ // Column layout: SYMBOL(0), QTY(1), LAST(2), AVG COST(3), MKT VAL(4), COST BASIS(5), P&L(6), P&L%(7),
+ // CHG%(8), TREND(9), WT%(10). LAST is column 2 — the old code wrote the
+ // live price into column 3 (AVG COST), corrupting the displayed cost.
+ if (auto* last_item = table_->item(r, 2))
last_item->setText(format_value(ltp));
// Recalculate market value & P&L from holdings data
const int idx = r + (current_page_ - 1) * page_size_;
@@ -606,6 +607,11 @@ void PortfolioBlotter::populate_table() {
// SYMBOL
set_cell(0, h.symbol, ui::colors::CYAN, Qt::AlignLeft | Qt::AlignVCenter);
+ // Stash the raw symbol on the cell so live broker-price ticks
+ // (update_row_price) can locate this row — its guard matches col-0
+ // Qt::UserRole, which was never set, so live prices never updated.
+ if (auto* sym_item = table_->item(r, 0))
+ sym_item->setData(Qt::UserRole, h.symbol);
// QTY
set_cell(1, format_value(h.quantity, h.quantity == std::floor(h.quantity) ? 0 : 2));
diff --git a/fincept-qt/src/screens/portfolio/PortfolioOrderPanel.cpp b/fincept-qt/src/screens/portfolio/PortfolioOrderPanel.cpp
index dead9d649..44abe55f6 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioOrderPanel.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioOrderPanel.cpp
@@ -85,10 +85,12 @@ void PortfolioOrderPanel::build_ui() {
connect(buy_tab_, &QPushButton::clicked, this, [this, update_tabs]() {
side_ = "BUY";
update_tabs();
+ update_display(); // refresh the submit button label/colour for the new side
});
connect(sell_tab_, &QPushButton::clicked, this, [this, update_tabs]() {
side_ = "SELL";
update_tabs();
+ update_display();
});
layout->addLayout(side_row);
diff --git a/fincept-qt/src/screens/portfolio/PortfolioTxnPanel.cpp b/fincept-qt/src/screens/portfolio/PortfolioTxnPanel.cpp
index c7cfb7846..4d684bb53 100644
--- a/fincept-qt/src/screens/portfolio/PortfolioTxnPanel.cpp
+++ b/fincept-qt/src/screens/portfolio/PortfolioTxnPanel.cpp
@@ -2,6 +2,7 @@
#include "screens/portfolio/PortfolioTxnPanel.h"
#include "screens/portfolio/PortfolioPanelHeader.h"
+#include "ui/tables/NumericTableWidgetItem.h"
#include "ui/theme/Theme.h"
#include <QEvent>
@@ -148,20 +149,20 @@ void PortfolioTxnPanel::populate() {
type_item->setFont(QFont(ui::fonts::DATA_FAMILY, 11, QFont::Bold));
table_->setItem(row, 2, type_item);
- // Qty
- auto* qty_item = new QTableWidgetItem(QString::number(t.quantity, 'f', 4));
+ // Qty — numeric item so header-sort orders by magnitude, not lexically
+ auto* qty_item = new ui::NumericTableWidgetItem(QString::number(t.quantity, 'f', 4), t.quantity);
qty_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
qty_item->setForeground(QColor(ui::colors::TEXT_PRIMARY()));
table_->setItem(row, 3, qty_item);
// Price
- auto* price_item = new QTableWidgetItem(QString::number(t.price, 'f', 2));
+ auto* price_item = new ui::NumericTableWidgetItem(QString::number(t.price, 'f', 2), t.price);
price_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
price_item->setForeground(QColor(ui::colors::TEXT_PRIMARY()));
table_->setItem(row, 4, price_item);
// Total
- auto* total_item = new QTableWidgetItem(QString::number(t.total_value, 'f', 2));
+ auto* total_item = new ui::NumericTableWidgetItem(QString::number(t.total_value, 'f', 2), t.total_value);
total_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
const char* total_color = (t.transaction_type == "BUY") ? ui::colors::NEGATIVE
: (t.transaction_type == "SELL") ? ui::colors::POSITIVE
diff --git a/fincept-qt/src/screens/quantlib/QuantLibScreen.cpp b/fincept-qt/src/screens/quantlib/QuantLibScreen.cpp
index 76cdfea92..e1737aa61 100644
--- a/fincept-qt/src/screens/quantlib/QuantLibScreen.cpp
+++ b/fincept-qt/src/screens/quantlib/QuantLibScreen.cpp
@@ -8,6 +8,7 @@
#include "core/logging/Logger.h"
#include "core/session/ScreenStateManager.h"
#include "services/quantlib/QuantLibClient.h"
+#include "ui/tables/NumericTableWidgetItem.h"
#include "ui/theme/Theme.h"
#include "ui/theme/ThemeManager.h"
@@ -623,7 +624,8 @@ void QuantLibScreen::display_result_array(const QJsonArray& arr) {
QString text = val.isDouble() ? QString::number(val.toDouble(), 'g', 10)
: val.isNull() ? "--"
: val.toVariant().toString();
- auto* item = new QTableWidgetItem(text);
+ QTableWidgetItem* item = val.isDouble() ? new ui::NumericTableWidgetItem(text, val.toDouble())
+ : new QTableWidgetItem(text);
item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
if (val.isDouble())
item->setForeground(QColor(val.toDouble() < 0 ? colors::NEGATIVE() : colors::CYAN()));
diff --git a/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.cpp b/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.cpp
index 258f919dc..7b4fb069c 100644
--- a/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.cpp
+++ b/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.cpp
@@ -11,6 +11,7 @@
#include <QGraphicsPathItem>
#include <QGraphicsSceneMouseEvent>
#include <QMouseEvent>
+#include <QTransform>
#include <QPainter>
#include <QPainterPath>
#include <QPen>
@@ -73,6 +74,7 @@ class RelNode : public QGraphicsItem {
RelNode(const QString& label, const QString& sub, const QColor& accent, qreal w, qreal h, Role role)
: label_(label), sub_(sub), accent_(accent), w_(w), h_(h), role_(role) {
setFlag(QGraphicsItem::ItemIsMovable, role != Role::Center);
+ setFlag(QGraphicsItem::ItemIsSelectable); // required for the click→detail-panel path
setFlag(QGraphicsItem::ItemSendsGeometryChanges);
setCacheMode(QGraphicsItem::DeviceCoordinateCache);
setZValue(role == Role::Center ? 5 : (role == Role::Hub ? 3 : 1));
@@ -253,10 +255,17 @@ class RelNode : public QGraphicsItem {
return QGraphicsItem::itemChange(change, value);
}
void mousePressEvent(QGraphicsSceneMouseEvent* event) override {
- if (role_ == Role::Center && event->button() == Qt::LeftButton) {
- auto* rms = qobject_cast<RelationshipGraphScene*>(scene());
- if (rms)
- emit rms->center_card_clicked(label_.split(" ").first());
+ if (event->button() == Qt::LeftButton) {
+ if (auto* rms = qobject_cast<RelationshipGraphScene*>(scene())) {
+ if (role_ == Role::Center)
+ emit rms->center_card_clicked(label_.split(" ").first());
+ // Every node (not just the center) opens the right-side detail
+ // panel. The panel slot looks up rich data by this label.
+ const QString category = (role_ == Role::Center) ? QStringLiteral("COMPANY")
+ : (role_ == Role::Hub) ? QStringLiteral("SECTOR / GROUP")
+ : QStringLiteral("PEER / RELATED");
+ emit rms->node_activated(label_, sub_, category);
+ }
}
update();
QGraphicsItem::mousePressEvent(event);
@@ -634,6 +643,7 @@ void RelationshipGraphView::fit_to_content() {
return;
fitInView(scene()->itemsBoundingRect().adjusted(-60, -60, 60, 60), Qt::KeepAspectRatio);
current_zoom_ = transform().m11();
+ emit zoom_changed(current_zoom_);
}
void RelationshipGraphView::reset_zoom() {
@@ -642,6 +652,13 @@ void RelationshipGraphView::reset_zoom() {
fit_to_content();
}
+void RelationshipGraphScene::mousePressEvent(QGraphicsSceneMouseEvent* event) {
+ // Empty-canvas click (no item under cursor) → let listeners clear selection/detail.
+ if (!itemAt(event->scenePos(), QTransform()))
+ emit background_clicked();
+ QGraphicsScene::mousePressEvent(event);
+}
+
void RelationshipGraphView::wheelEvent(QWheelEvent* event) {
double delta = event->pixelDelta().isNull() ? event->angleDelta().y() / 120.0 : event->pixelDelta().y() / 120.0;
if (qFuzzyIsNull(delta)) {
@@ -656,6 +673,7 @@ void RelationshipGraphView::wheelEvent(QWheelEvent* event) {
factor = kMaxZoom / current_zoom_;
scale(factor, factor);
current_zoom_ *= factor;
+ emit zoom_changed(current_zoom_);
event->accept();
}
diff --git a/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.h b/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.h
index b384db47b..3dcbc3fdd 100644
--- a/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.h
+++ b/fincept-qt/src/screens/relationship_map/RelationshipGraphScene.h
@@ -27,8 +27,12 @@ class RelationshipGraphScene : public QGraphicsScene {
signals:
void center_card_clicked(const QString& ticker);
+ void node_activated(const QString& label, const QString& sub, const QString& category);
void background_clicked();
+ protected:
+ void mousePressEvent(QGraphicsSceneMouseEvent* event) override;
+
private:
// kept as no-ops for ABI stability — layout is now pure radial/deterministic
void start_simulation();
diff --git a/fincept-qt/src/screens/relationship_map/RelationshipMapScreen.cpp b/fincept-qt/src/screens/relationship_map/RelationshipMapScreen.cpp
index 9a4289e32..8a403df5c 100644
--- a/fincept-qt/src/screens/relationship_map/RelationshipMapScreen.cpp
+++ b/fincept-qt/src/screens/relationship_map/RelationshipMapScreen.cpp
@@ -305,6 +305,19 @@ void RelationshipMapScreen::build_ui() {
connect(scene_, &relmap::RelationshipGraphScene::center_card_clicked, this, [](const QString& ticker) {
fincept::EventBus::instance().publish("equity_research.load_symbol", {{"symbol", ticker}, {"type", "equity"}});
});
+ // Any node click opens the right-side detail panel (previously the slot was
+ // never connected, so the panel was unreachable).
+ connect(scene_, &relmap::RelationshipGraphScene::node_activated, this, &RelationshipMapScreen::on_node_selected);
+ // Empty-canvas click dismisses the detail panel (deselect).
+ connect(scene_, &relmap::RelationshipGraphScene::background_clicked, this, [this]() {
+ if (detail_panel_)
+ detail_panel_->hide();
+ });
+ // Live zoom indicator surfaced on the FIT button tooltip.
+ connect(view_, &relmap::RelationshipGraphView::zoom_changed, this, [this](double f) {
+ if (fit_btn_)
+ fit_btn_->setToolTip(tr("Zoom %1% — click to fit (Home)").arg(qRound(f * 100.0)));
+ });
}
// ── Filter Panel ─────────────────────────────────────────────────────────────
@@ -678,42 +691,18 @@ void RelationshipMapScreen::rebuild_graph() {
update_status_bar();
}
-void RelationshipMapScreen::on_node_selected() {
- auto items = scene_->selectedItems();
- if (items.isEmpty()) {
+void RelationshipMapScreen::on_node_selected(const QString& label, const QString& sublabel,
+ const QString& category_text) {
+ // Driven by RelationshipGraphScene::node_activated (any node click). The
+ // node carries only label/sub/category; rich properties are looked up from
+ // current_data_ by matching the label against the company / peer tickers.
+ if (label.isEmpty()) {
detail_panel_->hide();
return;
}
- // Find the GraphNodeItem
- for (auto* item : items) {
- // Dynamic cast to our custom type
- auto* rect = dynamic_cast<QGraphicsRectItem*>(item);
- if (!rect)
- continue;
-
- // Access node data through scene items — we stored it in the item
- // Since GraphNodeItem is defined in the .cpp, we use a different approach:
- // Get the data from item's tooltip or child text items
- auto children = rect->childItems();
- QString label, category_text, sublabel;
- QMap<QString, QString> props;
-
- if (children.size() >= 2) {
- auto* badge_item = dynamic_cast<QGraphicsTextItem*>(children[0]);
- auto* label_item = dynamic_cast<QGraphicsTextItem*>(children[1]);
- if (badge_item)
- category_text = badge_item->toPlainText();
- if (label_item)
- label = label_item->toPlainText();
- if (children.size() >= 3) {
- auto* sub_item = dynamic_cast<QGraphicsTextItem*>(children[2]);
- if (sub_item)
- sublabel = sub_item->toPlainText();
- }
- }
-
- detail_title_->setText(label.isEmpty() ? tr("NODE") : label);
+ {
+ detail_title_->setText(label);
detail_category_->setText(category_text);
detail_category_->setStyleSheet(
QString("color: %1; font-size: 9px; font-weight: 700; letter-spacing: 0.5px; %2")
@@ -782,7 +771,6 @@ void RelationshipMapScreen::on_node_selected() {
}
detail_panel_->show();
- break;
}
}
diff --git a/fincept-qt/src/screens/relationship_map/RelationshipMapScreen.h b/fincept-qt/src/screens/relationship_map/RelationshipMapScreen.h
index 5c5776aa7..6fb0db3c9 100644
--- a/fincept-qt/src/screens/relationship_map/RelationshipMapScreen.h
+++ b/fincept-qt/src/screens/relationship_map/RelationshipMapScreen.h
@@ -57,7 +57,7 @@ class RelationshipMapScreen : public QWidget, public IStatefulScreen {
void on_data_ready(const fincept::relmap::RelationshipData& data);
void on_fetch_failed(const QString& error);
void on_progress(int percent, const QString& message);
- void on_node_selected();
+ void on_node_selected(const QString& label, const QString& sublabel, const QString& category_text);
void rebuild_graph();
void update_status_bar();
QWidget* build_filter_panel();
diff --git a/fincept-qt/src/screens/screener/ScreenerScreen.cpp b/fincept-qt/src/screens/screener/ScreenerScreen.cpp
new file mode 100644
index 000000000..f0b8bd721
--- /dev/null
+++ b/fincept-qt/src/screens/screener/ScreenerScreen.cpp
@@ -0,0 +1,293 @@
+#include "screens/screener/ScreenerScreen.h"
+
+#include "datahub/DataHub.h"
+#include "datahub/DataHubMetaTypes.h"
+#include "ui/theme/Theme.h"
+
+#include <QComboBox>
+#include <QEvent>
+#include <QHBoxLayout>
+#include <QHeaderView>
+#include <QLabel>
+#include <QLineEdit>
+#include <QPushButton>
+#include <QTableWidget>
+#include <QTableWidgetItem>
+#include <QVBoxLayout>
+
+#include <algorithm>
+
+namespace fincept::screens {
+
+namespace {
+// Broad large-cap basket across sectors — mirrors the dashboard ScreenerWidget
+// basket, extended for a full-screen view.
+const QStringList kBasket = {
+ "AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "META", "TSLA", "NFLX", "AMD", "INTC", "AVGO", "ORCL", "CRM",
+ "ADBE", "CSCO", "QCOM", "TXN", "JPM", "GS", "BAC", "WFC", "MS", "C", "BRK-B", "V", "MA",
+ "AXP", "PYPL", "WMT", "COST", "TGT", "HD", "LOW", "NKE", "MCD", "SBUX", "AMGN", "PFE", "JNJ",
+ "MRK", "ABBV", "LLY", "UNH", "XOM", "CVX", "SLB", "COP", "NEE", "DUK", "SO", "CAT", "GE",
+ "HON", "RTX", "BA", "DE", "PLTR", "COIN", "SOFI", "SNAP", "UBER", "ABNB", "SHOP", "SQ"};
+
+QString fmt_volume(double v) {
+ if (v >= 1e9)
+ return QString("%1B").arg(v / 1e9, 0, 'f', 1);
+ if (v >= 1e6)
+ return QString("%1M").arg(v / 1e6, 0, 'f', 1);
+ if (v >= 1e3)
+ return QString("%1K").arg(v / 1e3, 0, 'f', 0);
+ return QString::number(static_cast<long long>(v));
+}
+} // namespace
+
+ScreenerScreen::ScreenerScreen(QWidget* parent) : QWidget(parent) {
+ build_ui();
+ apply_styles();
+ retranslate();
+}
+
+void ScreenerScreen::build_ui() {
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(0, 0, 0, 0);
+ root->setSpacing(0);
+
+ // ── Header bar ──────────────────────────────────────────────────────────
+ header_bar_ = new QWidget(this);
+ auto* hb = new QHBoxLayout(header_bar_);
+ hb->setContentsMargins(16, 12, 16, 12);
+ hb->setSpacing(10);
+
+ auto* title_box = new QVBoxLayout;
+ title_box->setSpacing(1);
+ title_lbl_ = new QLabel;
+ title_lbl_->setObjectName("screenerTitle");
+ subtitle_lbl_ = new QLabel;
+ subtitle_lbl_->setObjectName("screenerSubtitle");
+ title_box->addWidget(title_lbl_);
+ title_box->addWidget(subtitle_lbl_);
+ hb->addLayout(title_box);
+ hb->addStretch();
+
+ search_ = new QLineEdit;
+ search_->setClearButtonEnabled(true);
+ search_->setFixedWidth(220);
+ connect(search_, &QLineEdit::textChanged, this, [this](const QString&) { apply_filter(); });
+ hb->addWidget(search_);
+
+ sort_combo_ = new QComboBox;
+ connect(sort_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
+ [this](int) { apply_filter(); });
+ hb->addWidget(sort_combo_);
+
+ count_lbl_ = new QLabel;
+ count_lbl_->setObjectName("screenerCount");
+ hb->addWidget(count_lbl_);
+
+ refresh_btn_ = new QPushButton;
+ refresh_btn_->setCursor(Qt::PointingHandCursor);
+ connect(refresh_btn_, &QPushButton::clicked, this, &ScreenerScreen::refresh_now);
+ hb->addWidget(refresh_btn_);
+
+ root->addWidget(header_bar_);
+
+ // ── Results table ───────────────────────────────────────────────────────
+ table_ = new QTableWidget(this);
+ table_->setColumnCount(5);
+ table_->setSelectionBehavior(QAbstractItemView::SelectRows);
+ table_->setSelectionMode(QAbstractItemView::SingleSelection);
+ table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ table_->setShowGrid(false);
+ table_->setAlternatingRowColors(true);
+ table_->verticalHeader()->setVisible(false);
+ table_->horizontalHeader()->setHighlightSections(false);
+ table_->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
+ table_->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
+ table_->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
+ table_->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents);
+ table_->horizontalHeader()->setSectionResizeMode(4, QHeaderView::ResizeToContents);
+ root->addWidget(table_, 1);
+}
+
+void ScreenerScreen::apply_styles() {
+ setStyleSheet(
+ QString("ScreenerScreen { background: %1; }").arg(ui::colors::BG_BASE()) +
+ QString("#screenerTitle { color: %1; font-size: 16px; font-weight: 700; }").arg(ui::colors::TEXT_PRIMARY()) +
+ QString("#screenerSubtitle { color: %1; font-size: 11px; }").arg(ui::colors::TEXT_TERTIARY()) +
+ QString("#screenerCount { color: %1; font-size: 11px; }").arg(ui::colors::TEXT_TERTIARY()) +
+ QString("QLineEdit { background: %1; color: %2; border: 1px solid %3; border-radius: 3px; padding: 4px 8px; }")
+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_MED()) +
+ QString("QComboBox { background: %1; color: %2; border: 1px solid %3; border-radius: 3px; padding: 4px 8px; }"
+ "QComboBox QAbstractItemView { background: %1; color: %2; border: 1px solid %3; }")
+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_MED()) +
+ QString("QPushButton { background: %1; color: %2; border: 1px solid %3; border-radius: 3px; padding: 4px 12px; }"
+ "QPushButton:hover { border-color: %4; }")
+ .arg(ui::colors::BG_RAISED(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_MED(), ui::colors::INFO()));
+
+ if (header_bar_)
+ header_bar_->setStyleSheet(QString("background: %1; border-bottom: 1px solid %2;")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::BORDER_DIM()));
+
+ if (table_)
+ table_->setStyleSheet(
+ QString("QTableWidget { background: %1; color: %2; border: none; gridline-color: %3; }")
+ .arg(ui::colors::BG_BASE(), ui::colors::TEXT_PRIMARY(), ui::colors::BORDER_DIM()) +
+ QString("QTableWidget::item { padding: 6px 8px; }") +
+ QString("QTableWidget::item:alternate { background: %1; }").arg(ui::colors::BG_RAISED()) +
+ QString("QHeaderView::section { background: %1; color: %2; border: none; border-bottom: 1px solid %3; "
+ "padding: 6px 8px; font-size: 10px; font-weight: 700; }")
+ .arg(ui::colors::BG_SURFACE(), ui::colors::TEXT_TERTIARY(), ui::colors::BORDER_MED()));
+}
+
+void ScreenerScreen::retranslate() {
+ title_lbl_->setText(tr("STOCK SCREENER"));
+ subtitle_lbl_->setText(tr("Filter a broad large-cap basket by change, volume, or price"));
+ search_->setPlaceholderText(tr("Search symbol or name…"));
+ refresh_btn_->setText(tr("REFRESH"));
+
+ const int prev = sort_combo_->currentIndex();
+ QSignalBlocker block(sort_combo_);
+ sort_combo_->clear();
+ sort_combo_->addItems({tr("% CHANGE ↑"), tr("% CHANGE ↓"), tr("VOLUME ↓"), tr("PRICE ↓"), tr("PRICE ↑")});
+ sort_combo_->setCurrentIndex(prev < 0 ? 0 : prev);
+
+ table_->setHorizontalHeaderLabels(
+ {tr("SYMBOL"), tr("NAME"), tr("PRICE"), tr("CHG%"), tr("VOLUME")});
+
+ rebuild_from_cache();
+}
+
+void ScreenerScreen::showEvent(QShowEvent* e) {
+ QWidget::showEvent(e);
+ if (!hub_active_)
+ hub_subscribe_all();
+}
+
+void ScreenerScreen::hideEvent(QHideEvent* e) {
+ QWidget::hideEvent(e);
+ if (hub_active_)
+ hub_unsubscribe_all();
+}
+
+void ScreenerScreen::changeEvent(QEvent* e) {
+ QWidget::changeEvent(e);
+ if (!e)
+ return;
+ if (e->type() == QEvent::StyleChange || e->type() == QEvent::PaletteChange)
+ apply_styles();
+ else if (e->type() == QEvent::LanguageChange)
+ retranslate();
+}
+
+void ScreenerScreen::hub_subscribe_all() {
+ auto& hub = datahub::DataHub::instance();
+ for (const auto& sym : kBasket) {
+ const QString topic = QStringLiteral("market:quote:") + sym;
+ hub.subscribe(this, topic, [this, sym](const QVariant& v) {
+ if (!v.canConvert<services::QuoteData>())
+ return;
+ row_cache_.insert(sym, v.value<services::QuoteData>());
+ rebuild_from_cache();
+ });
+ }
+ hub_active_ = true;
+}
+
+void ScreenerScreen::hub_unsubscribe_all() {
+ datahub::DataHub::instance().unsubscribe(this);
+ hub_active_ = false;
+}
+
+void ScreenerScreen::refresh_now() {
+ auto& hub = datahub::DataHub::instance();
+ QStringList topics;
+ topics.reserve(kBasket.size());
+ for (const auto& sym : kBasket)
+ topics.append(QStringLiteral("market:quote:") + sym);
+ hub.request(topics, /*force=*/true); // user-triggered: bypass min_interval
+}
+
+void ScreenerScreen::rebuild_from_cache() {
+ all_quotes_.clear();
+ all_quotes_.reserve(row_cache_.size());
+ for (const auto& sym : kBasket) {
+ auto it = row_cache_.constFind(sym);
+ if (it != row_cache_.constEnd())
+ all_quotes_.append(it.value());
+ }
+ apply_filter();
+}
+
+void ScreenerScreen::apply_filter() {
+ QVector<services::QuoteData> rows = all_quotes_;
+
+ const QString needle = search_ ? search_->text().trimmed() : QString();
+ if (!needle.isEmpty()) {
+ QVector<services::QuoteData> filtered;
+ filtered.reserve(rows.size());
+ for (const auto& q : rows) {
+ if (q.symbol.contains(needle, Qt::CaseInsensitive) || q.name.contains(needle, Qt::CaseInsensitive))
+ filtered.append(q);
+ }
+ rows = filtered;
+ }
+
+ const int idx = sort_combo_ ? sort_combo_->currentIndex() : 0;
+ switch (idx) {
+ case 0: // % change desc (top gainers first)
+ std::sort(rows.begin(), rows.end(), [](const auto& a, const auto& b) { return a.change_pct > b.change_pct; });
+ break;
+ case 1: // % change asc (top losers first)
+ std::sort(rows.begin(), rows.end(), [](const auto& a, const auto& b) { return a.change_pct < b.change_pct; });
+ break;
+ case 2: // volume desc
+ std::sort(rows.begin(), rows.end(), [](const auto& a, const auto& b) { return a.volume > b.volume; });
+ break;
+ case 3: // price desc
+ std::sort(rows.begin(), rows.end(), [](const auto& a, const auto& b) { return a.price > b.price; });
+ break;
+ case 4: // price asc
+ std::sort(rows.begin(), rows.end(), [](const auto& a, const auto& b) { return a.price < b.price; });
+ break;
+ default:
+ break;
+ }
+
+ render_rows(rows);
+ if (count_lbl_)
+ count_lbl_->setText(tr("%1 of %2 symbols").arg(rows.size()).arg(kBasket.size()));
+}
+
+void ScreenerScreen::render_rows(const QVector<services::QuoteData>& rows) {
+ table_->setRowCount(rows.size());
+ for (int r = 0; r < rows.size(); ++r) {
+ const auto& q = rows[r];
+
+ auto* sym = new QTableWidgetItem(q.symbol);
+ sym->setForeground(QColor(ui::colors::INFO()));
+ QFont bold = sym->font();
+ bold.setBold(true);
+ sym->setFont(bold);
+ table_->setItem(r, 0, sym);
+
+ table_->setItem(r, 1, new QTableWidgetItem(q.name));
+
+ auto* price = new QTableWidgetItem(QString("$%1").arg(q.price, 0, 'f', 2));
+ price->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ table_->setItem(r, 2, price);
+
+ auto* chg = new QTableWidgetItem(
+ QString("%1%2%").arg(q.change_pct >= 0 ? "+" : "").arg(q.change_pct, 0, 'f', 2));
+ chg->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ chg->setForeground(QColor(q.change_pct > 0 ? ui::colors::POSITIVE()
+ : q.change_pct < 0 ? ui::colors::NEGATIVE()
+ : ui::colors::TEXT_PRIMARY()));
+ table_->setItem(r, 3, chg);
+
+ auto* vol = new QTableWidgetItem(fmt_volume(q.volume));
+ vol->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
+ vol->setForeground(QColor(ui::colors::TEXT_SECONDARY()));
+ table_->setItem(r, 4, vol);
+ }
+}
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/screener/ScreenerScreen.h b/fincept-qt/src/screens/screener/ScreenerScreen.h
new file mode 100644
index 000000000..dbe9c06f6
--- /dev/null
+++ b/fincept-qt/src/screens/screener/ScreenerScreen.h
@@ -0,0 +1,62 @@
+#pragma once
+#include "services/markets/MarketDataService.h"
+
+#include <QHash>
+#include <QVector>
+#include <QWidget>
+
+class QComboBox;
+class QLabel;
+class QLineEdit;
+class QPushButton;
+class QTableWidget;
+
+namespace fincept::screens {
+
+/// Full-screen Stock Screener.
+///
+/// Reuses the dashboard `ScreenerWidget` data path — subscribes to
+/// `market:quote:<sym>` on the DataHub for a broad large-cap basket, caches
+/// each delivery, and sorts/filters client-side. Presents the result as a
+/// full-width table with a symbol/name search box and a sort selector.
+///
+/// Hub lifecycle follows P3/D3: subscribe in `showEvent`, unsubscribe in
+/// `hideEvent`, so the producer pauses when the screen isn't visible.
+class ScreenerScreen : public QWidget {
+ Q_OBJECT
+ public:
+ explicit ScreenerScreen(QWidget* parent = nullptr);
+
+ protected:
+ void showEvent(QShowEvent* e) override;
+ void hideEvent(QHideEvent* e) override;
+ void changeEvent(QEvent* e) override;
+
+ private:
+ void build_ui();
+ void apply_styles();
+ void retranslate();
+
+ void hub_subscribe_all();
+ void hub_unsubscribe_all();
+ /// Recompute `all_quotes_` from `row_cache_` (in basket order) then filter.
+ void rebuild_from_cache();
+ void apply_filter();
+ void render_rows(const QVector<services::QuoteData>& rows);
+ void refresh_now();
+
+ QLineEdit* search_ = nullptr;
+ QComboBox* sort_combo_ = nullptr;
+ QPushButton* refresh_btn_ = nullptr;
+ QLabel* title_lbl_ = nullptr;
+ QLabel* subtitle_lbl_ = nullptr;
+ QLabel* count_lbl_ = nullptr;
+ QWidget* header_bar_ = nullptr;
+ QTableWidget* table_ = nullptr;
+
+ QHash<QString, services::QuoteData> row_cache_;
+ QVector<services::QuoteData> all_quotes_;
+ bool hub_active_ = false;
+};
+
+} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp b/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
index c509edda8..ba519ada0 100644
--- a/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
+++ b/fincept-qt/src/screens/watchlist/WatchlistScreen.cpp
@@ -761,11 +761,17 @@ void WatchlistScreen::on_remove_stock() {
if (current_wl_id_.isEmpty())
return;
- int row = table_->currentRow();
- if (row < 0 || row >= stocks_.size())
+ // Read the symbol from the selected VISUAL row's first column, not
+ // stocks_[currentRow()]: sorting is enabled, so the visual row index no
+ // longer maps to the insertion-ordered stocks_ vector — indexing it would
+ // remove the WRONG symbol from the watchlist.
+ const int row = table_->currentRow();
+ auto* sym_item = (row >= 0) ? table_->item(row, 0) : nullptr;
+ if (!sym_item)
+ return;
+ const QString symbol = sym_item->text();
+ if (symbol.isEmpty())
return;
-
- QString symbol = stocks_[row].symbol;
fincept::WatchlistRepository::instance().remove_stock(current_wl_id_, symbol);
load_stocks();
}
@@ -973,13 +979,15 @@ void WatchlistScreen::restore_state(const QVariantMap& state) {
void WatchlistScreen::on_group_symbol_changed(const SymbolRef& ref) {
if (!table_ || !ref.is_valid())
return;
- // Select the row whose symbol matches; scroll into view. No-op if the
- // ticker isn't in this watchlist.
- for (int r = 0; r < stocks_.size(); ++r) {
- if (stocks_[r].symbol.compare(ref.symbol, Qt::CaseInsensitive) == 0) {
+ // Match against the table's VISUAL rows (column 0 = symbol), not the
+ // insertion-ordered stocks_ vector: with sorting enabled, selectRow(stocks_
+ // index) would highlight the wrong row. No-op if the ticker isn't shown.
+ for (int r = 0; r < table_->rowCount(); ++r) {
+ auto* it = table_->item(r, 0);
+ if (it && it->text().compare(ref.symbol, Qt::CaseInsensitive) == 0) {
QSignalBlocker block(table_); // avoid re-emitting publish
table_->selectRow(r);
- table_->scrollToItem(table_->item(r, 0), QAbstractItemView::PositionAtCenter);
+ table_->scrollToItem(it, QAbstractItemView::PositionAtCenter);
return;
}
}
@@ -988,19 +996,23 @@ void WatchlistScreen::on_group_symbol_changed(const SymbolRef& ref) {
SymbolRef WatchlistScreen::current_symbol() const {
if (!table_)
return {};
+ // Symbol from the selected visual row's column 0 (sort-safe), not
+ // stocks_[currentRow()] which is wrong once the user sorts a column.
const int r = table_->currentRow();
- if (r < 0 || r >= stocks_.size())
+ auto* sym_item = (r >= 0) ? table_->item(r, 0) : nullptr;
+ if (!sym_item || sym_item->text().isEmpty())
return {};
- return SymbolRef::equity(stocks_[r].symbol);
+ return SymbolRef::equity(sym_item->text());
}
void WatchlistScreen::publish_selection_to_group() {
if (link_group_ == SymbolGroup::None || !table_)
return;
const int r = table_->currentRow();
- if (r < 0 || r >= stocks_.size())
+ auto* sym_item = (r >= 0) ? table_->item(r, 0) : nullptr;
+ if (!sym_item || sym_item->text().isEmpty())
return;
- const SymbolRef ref = SymbolRef::equity(stocks_[r].symbol);
+ const SymbolRef ref = SymbolRef::equity(sym_item->text());
SymbolContext::instance().set_group_symbol(link_group_, ref, this);
}
diff --git a/fincept-qt/src/services/agents/AgentService.cpp b/fincept-qt/src/services/agents/AgentService.cpp
index f9f8e49fa..4808d52fe 100644
--- a/fincept-qt/src/services/agents/AgentService.cpp
+++ b/fincept-qt/src/services/agents/AgentService.cpp
@@ -49,6 +49,8 @@ AgentService::AgentService(QObject* parent) : QObject(parent) {
// checker that gates agent-originated tool calls. Both are idempotent;
// failure to bind the port is logged but not fatal — agents simply lose
// terminal-tool access.
+ connect(&mcp::TerminalMcpBridge::instance(), &mcp::TerminalMcpBridge::bridge_error, this,
+ [](const QString& msg) { LOG_ERROR("AgentService", "Terminal MCP bridge error: " + msg); });
if (mcp::TerminalMcpBridge::instance().start()) {
LOG_INFO("AgentService", "Terminal MCP bridge started: " + mcp::TerminalMcpBridge::instance().endpoint());
} else {
diff --git a/fincept-qt/src/services/akshare/AkShareService.cpp b/fincept-qt/src/services/akshare/AkShareService.cpp
index da5db8547..705d0e3d1 100644
--- a/fincept-qt/src/services/akshare/AkShareService.cpp
+++ b/fincept-qt/src/services/akshare/AkShareService.cpp
@@ -118,8 +118,18 @@ void AkShareService::query(const QString& script, const QString& endpoint, const
rows.append(obj);
}
+ // Ordered column names, if the script supplied them. QJsonObject sorts
+ // its keys, so deriving columns from a row would scramble the source
+ // DataFrame's column order — the script's explicit list preserves it.
+ QStringList columns;
+ if (obj.contains("columns") && obj["columns"].isArray()) {
+ for (const auto& c : obj["columns"].toArray())
+ columns << c.toString();
+ }
+
out.success = true;
out.rows = rows;
+ out.columns = columns;
if (cb)
cb(out);
});
diff --git a/fincept-qt/src/services/akshare/AkShareService.h b/fincept-qt/src/services/akshare/AkShareService.h
index 48e5b5299..e6ebbc998 100644
--- a/fincept-qt/src/services/akshare/AkShareService.h
+++ b/fincept-qt/src/services/akshare/AkShareService.h
@@ -25,6 +25,7 @@ struct EndpointsResult {
struct QueryResult {
bool success = false;
QJsonArray rows;
+ QStringList columns; // ordered column names from the source DataFrame (empty if the script didn't supply them)
QString error;
};
diff --git a/fincept-qt/src/services/common/RestServiceBase.h b/fincept-qt/src/services/common/RestServiceBase.h
deleted file mode 100644
index dc10fcba9..000000000
--- a/fincept-qt/src/services/common/RestServiceBase.h
+++ /dev/null
@@ -1,61 +0,0 @@
-#pragma once
-// Phase 5 scaffolding — shared helper for "GET URL → parse JSON → emit" services.
-//
-// ~13 services today follow this near-identical pattern:
-// 1. Build URL from inputs
-// 2. Hit HttpClient with a context-scoped callback
-// 3. Stale-request gate (request_id / pending_query)
-// 4. Cache via CacheManager with a per-service TTL
-// 5. Parse JSON to a typed result
-// 6. Emit `*_ready(request_id, result)` or `*_failed(request_id, reason)`
-//
-// `RestServiceBase` collapses steps 2–6. A subclass provides the URL builder
-// and the parser; the base does the rest.
-
-#include "core/result/Result.h"
-#include "network/http/HttpClient.h"
-
-#include <QJsonDocument>
-#include <QObject>
-#include <QPointer>
-#include <QString>
-
-#include <functional>
-
-namespace fincept::services {
-
-/// Base class for thin REST-and-emit services.
-///
-/// Subclasses inherit `QObject` through this base, declare their own typed
-/// signal, and call `fetch_and_emit(...)` from public methods. The base owns
-/// the network call, the QPointer-context lifetime guard, and the JSON parsing
-/// dispatch.
-///
-/// Caching is opt-in — pass a non-empty `cache_key` and a TTL and the helper
-/// will consult `CacheManager` before issuing the request.
-///
-/// This is **not** a `Producer` — for topic-based fan-out, use a DataHub
-/// `Producer`. `RestServiceBase` is for one-shot request/response services
-/// like `MarketSearchService`.
-class RestServiceBase : public QObject {
- Q_OBJECT
- public:
- explicit RestServiceBase(QObject* parent = nullptr) : QObject(parent) {}
-
- protected:
- /// Issue `GET url`. On success, hand the parsed JSON to `on_response`.
- /// `on_response` is run on the Qt event loop only if `this` is still alive.
- void fetch_json(const QString& url, std::function<void(Result<QJsonDocument>)> on_response) {
- QPointer<RestServiceBase> self = this;
- HttpClient::instance().get(
- url,
- [self, cb = std::move(on_response)](Result<QJsonDocument> result) {
- if (!self)
- return;
- cb(std::move(result));
- },
- this);
- }
-};
-
-} // namespace fincept::services
diff --git a/fincept-qt/src/services/markets/MarketSearchService.cpp b/fincept-qt/src/services/markets/MarketSearchService.cpp
index 829b34df9..f7479f845 100644
--- a/fincept-qt/src/services/markets/MarketSearchService.cpp
+++ b/fincept-qt/src/services/markets/MarketSearchService.cpp
@@ -6,6 +6,7 @@
#include <QJsonArray>
#include <QJsonDocument>
#include <QPointer>
+#include <QUrl>
#include <algorithm>
@@ -58,9 +59,13 @@ void MarketSearchService::search(const QString& query, const QString& type, int
}
const int clamped = std::clamp(limit, kMinLimit, kMaxLimit);
- QString url = QString("/market/search?q=%1&limit=%2").arg(q).arg(clamped);
+ // Percent-encode the query so symbols like "S&P" / "AT&T" / spaces don't
+ // break the query string (the raw '&' would be read as a param separator).
+ QString url = QString("/market/search?q=%1&limit=%2")
+ .arg(QString::fromUtf8(QUrl::toPercentEncoding(q)))
+ .arg(clamped);
if (!type.isEmpty())
- url += "&type=" + type;
+ url += "&type=" + QString::fromUtf8(QUrl::toPercentEncoding(type));
QPointer<MarketSearchService> self = this;
HttpClient::instance().get(
diff --git a/fincept-qt/src/services/news/NewsService.cpp b/fincept-qt/src/services/news/NewsService.cpp
index 2060e35ae..509893673 100644
--- a/fincept-qt/src/services/news/NewsService.cpp
+++ b/fincept-qt/src/services/news/NewsService.cpp
@@ -345,32 +345,42 @@ void NewsService::fetch_all_news_progressive(bool force, ArticlesCallback final_
sources.insert(a.source);
state->service->active_sources_ = sources.values();
- QJsonArray parr;
- for (const auto& a : all) {
- QJsonObject o;
- o["id"] = a.id;
- o["time"] = a.time;
- o["headline"] = a.headline;
- o["summary"] = a.summary;
- o["source"] = a.source;
- o["region"] = a.region;
- o["category"] = a.category;
- o["link"] = a.link;
- o["sort_ts"] = static_cast<qint64>(a.sort_ts);
- o["tier"] = a.tier;
- o["priority"] = priority_string(a.priority);
- o["sentiment"] = sentiment_string(a.sentiment);
- o["impact"] = impact_string(a.impact);
- o["lang"] = a.lang;
- QJsonArray tickers;
- for (const auto& t : a.tickers)
- tickers.append(t);
- o["tickers"] = tickers;
- parr.append(o);
+ // Only rewrite the on-disk cache when we actually fetched
+ // articles. If every feed failed (e.g. full network loss) `all`
+ // is empty — overwriting the cache with an empty array would wipe
+ // the last-known-good news and leave a blank widget after a
+ // restart. Keep the previous cache in that case.
+ if (!all.isEmpty()) {
+ QJsonArray parr;
+ for (const auto& a : all) {
+ QJsonObject o;
+ o["id"] = a.id;
+ o["time"] = a.time;
+ o["headline"] = a.headline;
+ o["summary"] = a.summary;
+ o["source"] = a.source;
+ o["region"] = a.region;
+ o["category"] = a.category;
+ o["link"] = a.link;
+ o["sort_ts"] = static_cast<qint64>(a.sort_ts);
+ o["tier"] = a.tier;
+ o["priority"] = priority_string(a.priority);
+ o["sentiment"] = sentiment_string(a.sentiment);
+ o["impact"] = impact_string(a.impact);
+ o["lang"] = a.lang;
+ QJsonArray tickers;
+ for (const auto& t : a.tickers)
+ tickers.append(t);
+ o["tickers"] = tickers;
+ parr.append(o);
+ }
+ fincept::CacheManager::instance().put(
+ "news:articles",
+ QVariant(QString::fromUtf8(QJsonDocument(parr).toJson(QJsonDocument::Compact))),
+ kArticleCacheTtlSec, "news");
+ } else {
+ LOG_WARN("NewsService", "All feeds returned no articles — keeping last-known-good cache");
}
- fincept::CacheManager::instance().put(
- "news:articles", QVariant(QString::fromUtf8(QJsonDocument(parr).toJson(QJsonDocument::Compact))),
- kArticleCacheTtlSec, "news");
LOG_INFO(
"NewsService",
diff --git a/fincept-qt/src/services/news/NewsService_LiveFeed.cpp b/fincept-qt/src/services/news/NewsService_LiveFeed.cpp
index 397d16e29..6797e3ceb 100644
--- a/fincept-qt/src/services/news/NewsService_LiveFeed.cpp
+++ b/fincept-qt/src/services/news/NewsService_LiveFeed.cpp
@@ -102,6 +102,16 @@ void NewsService::connect_live_feed(const QString& ws_url) {
a.link = o["link"].toString();
a.sort_ts = o["sort_ts"].toVariant().toLongLong();
a.tier = o["tier"].toInt(4);
+ // Preserve the NLP enrichment — omitting these fields on the
+ // round-trip stripped priority/sentiment/impact/lang/tickers
+ // from every cached row on each live push, breaking colouring,
+ // priority sort and ticker filters.
+ a.priority = priority_from_string(o["priority"].toString());
+ a.sentiment = sentiment_from_string(o["sentiment"].toString());
+ a.impact = impact_from_string(o["impact"].toString());
+ a.lang = o["lang"].toString();
+ for (const auto& t : o["tickers"].toArray())
+ a.tickers << t.toString();
updated.append(a);
}
}
@@ -120,6 +130,15 @@ void NewsService::connect_live_feed(const QString& ws_url) {
o["link"] = a.link;
o["sort_ts"] = static_cast<qint64>(a.sort_ts);
o["tier"] = a.tier;
+ // Write the enrichment back too, so it survives the next live push.
+ o["priority"] = priority_string(a.priority);
+ o["sentiment"] = sentiment_string(a.sentiment);
+ o["impact"] = impact_string(a.impact);
+ o["lang"] = a.lang;
+ QJsonArray tk;
+ for (const auto& t : a.tickers)
+ tk.append(t);
+ o["tickers"] = tk;
narr.append(o);
}
fincept::CacheManager::instance().put(
diff --git a/fincept-qt/src/services/options/FiiDiiService.cpp b/fincept-qt/src/services/options/FiiDiiService.cpp
index 7ae9fe24e..e28850e3a 100644
--- a/fincept-qt/src/services/options/FiiDiiService.cpp
+++ b/fincept-qt/src/services/options/FiiDiiService.cpp
@@ -167,7 +167,11 @@ void FiiDiiService::kick_off_refresh() {
auto qr = fincept::FiiDiiRepository::instance().get_recent(kPublishWindowDays);
if (qr.is_err()) {
- LOG_WARN("FiiDii", QString("get_recent failed: %1").arg(QString::fromStdString(qr.error())));
+ // Must publish_error so the hub clears the in-flight state for kTopic;
+ // otherwise subscribers spin on "loading" until the ~30s watchdog.
+ const QString err = QString("get_recent failed: %1").arg(QString::fromStdString(qr.error()));
+ LOG_WARN("FiiDii", err);
+ fincept::datahub::DataHub::instance().publish_error(kTopic, err);
return;
}
QVector<FiiDiiDay> rows = qr.value();
diff --git a/fincept-qt/src/services/portfolio/PortfolioService_Metrics.cpp b/fincept-qt/src/services/portfolio/PortfolioService_Metrics.cpp
index dc854798e..3302187cb 100644
--- a/fincept-qt/src/services/portfolio/PortfolioService_Metrics.cpp
+++ b/fincept-qt/src/services/portfolio/PortfolioService_Metrics.cpp
@@ -382,7 +382,11 @@ void PortfolioService::compute_metrics(const portfolio::PortfolioSummary& summar
const double var = (sum_sq / n) - (mean * mean);
const double daily_vol = std::sqrt(std::max(var, 0.0));
const double ann_vol = daily_vol * std::sqrt(252.0);
- metrics.volatility = ann_vol * 100.0; // store as %
+ // day_change_percent is already in percent units, so daily_vol/ann_vol
+ // are too — do NOT multiply by 100 again (that produced ~100x-inflated
+ // "2380%" volatility). The full-history path stores ann_vol directly,
+ // and vol_score/sharpe below already treat it as a percentage.
+ metrics.volatility = ann_vol; // already in %
const double rf_daily = rf_rate_ / 252.0;
if (daily_vol > 1e-6)
metrics.sharpe = ((mean / 100.0 - rf_daily) / (daily_vol / 100.0)) * std::sqrt(252.0);
diff --git a/fincept-qt/src/services/workflow/RiskManager.cpp b/fincept-qt/src/services/workflow/RiskManager.cpp
index 6ee63846b..45f642958 100644
--- a/fincept-qt/src/services/workflow/RiskManager.cpp
+++ b/fincept-qt/src/services/workflow/RiskManager.cpp
@@ -21,6 +21,15 @@ QVector<RiskCheckResult> RiskManager::validate_order(const QString& symbol, cons
QVector<RiskCheckResult> results;
double order_value = quantity * price;
+ // Daily counters roll over at midnight. This method is const (the real reset
+ // lives in record_trade), so use effective values: once the calendar day has
+ // changed, yesterday's count / volume / loss no longer apply — otherwise the
+ // first order after midnight is wrongly blocked by yesterday's daily loss.
+ const bool same_day = (daily_stats_.date == QDate::currentDate().toString(Qt::ISODate));
+ const int eff_trade_count = same_day ? daily_stats_.trade_count : 0;
+ const double eff_volume = same_day ? daily_stats_.volume : 0.0;
+ const double eff_realized_pnl = same_day ? daily_stats_.realized_pnl : 0.0;
+
// Position size check
if (quantity > limits_.max_position_size) {
results.append({false, RiskSeverity::Error, "position_size",
@@ -50,16 +59,16 @@ QVector<RiskCheckResult> RiskManager::validate_order(const QString& symbol, cons
}
// Daily trade count check
- if (daily_stats_.trade_count >= limits_.max_daily_trades) {
+ if (eff_trade_count >= limits_.max_daily_trades) {
results.append(
{false, RiskSeverity::Warning, "daily_trades",
- QString("Daily trade count %1 at limit %2").arg(daily_stats_.trade_count).arg(limits_.max_daily_trades)});
+ QString("Daily trade count %1 at limit %2").arg(eff_trade_count).arg(limits_.max_daily_trades)});
} else {
results.append({true, RiskSeverity::Info, "daily_trades", "OK"});
}
// Daily volume check
- if (daily_stats_.volume + order_value > limits_.max_daily_volume) {
+ if (eff_volume + order_value > limits_.max_daily_volume) {
results.append({false, RiskSeverity::Warning, "daily_volume",
QString("Daily volume would exceed $%1 limit").arg(limits_.max_daily_volume, 0, 'f', 2)});
} else {
@@ -67,10 +76,10 @@ QVector<RiskCheckResult> RiskManager::validate_order(const QString& symbol, cons
}
// Daily loss limit check
- if (daily_stats_.realized_pnl < -limits_.daily_loss_limit) {
+ if (eff_realized_pnl < -limits_.daily_loss_limit) {
results.append({false, RiskSeverity::Critical, "daily_loss",
QString("Daily loss $%1 exceeds limit $%2")
- .arg(-daily_stats_.realized_pnl, 0, 'f', 2)
+ .arg(-eff_realized_pnl, 0, 'f', 2)
.arg(limits_.daily_loss_limit, 0, 'f', 2)});
} else {
results.append({true, RiskSeverity::Info, "daily_loss", "OK"});
diff --git a/fincept-qt/src/services/workflow/WorkflowExecutor.cpp b/fincept-qt/src/services/workflow/WorkflowExecutor.cpp
index 36825a06b..d7766818f 100644
--- a/fincept-qt/src/services/workflow/WorkflowExecutor.cpp
+++ b/fincept-qt/src/services/workflow/WorkflowExecutor.cpp
@@ -286,12 +286,15 @@ QVector<QString> WorkflowExecutor::topological_sort() const {
while (front < queue.size()) {
QString u = queue[front++];
- // Skip disabled nodes
+ // A disabled node does not execute, but we MUST still relax its outgoing
+ // edges (treat it as pass-through). The old code `continue`d before the
+ // edge-relaxation loop, so every downstream node kept a permanently
+ // non-zero in-degree and was silently stranded — never added to `order`,
+ // excluded from total_count_, yet execution still reported success.
auto nd_it = node_map_.constFind(u);
- if (nd_it != node_map_.constEnd() && nd_it->disabled)
- continue;
-
- order.append(u);
+ const bool disabled = (nd_it != node_map_.constEnd() && nd_it->disabled);
+ if (!disabled)
+ order.append(u);
for (const auto& v : adjacency_.value(u)) {
in_deg[v]--;
diff --git a/fincept-qt/src/services/workflow/adapters/ServiceBridges.cpp b/fincept-qt/src/services/workflow/adapters/ServiceBridges.cpp
index ba8f312a6..43b8c631a 100644
--- a/fincept-qt/src/services/workflow/adapters/ServiceBridges.cpp
+++ b/fincept-qt/src/services/workflow/adapters/ServiceBridges.cpp
@@ -9,6 +9,8 @@
#include "services/workflow/ConfirmationService.h"
#include "services/workflow/NodeRegistry.h"
#include "services/workflow/RiskManager.h"
+#include "services/workflow/WorkflowExecutor.h"
+#include "storage/repositories/WorkflowRepository.h"
#include "trading/AccountManager.h"
#include "trading/ActionCenter.h"
#include "trading/BrokerRegistry.h"
@@ -31,6 +33,7 @@
#include <QPointer>
#include <QPrinter>
#include <QRegularExpression>
+#include <QSet>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
@@ -2358,6 +2361,75 @@ print(json.dumps({"path": path, "chart_type": chart_type, "size": os.path.getsiz
};
}
+ // ── Execute Workflow — run another saved workflow as a sub-workflow ──
+ auto* subwf_def = const_cast<NodeTypeDef*>(registry.find("control.execute_workflow"));
+ if (subwf_def && !subwf_def->execute) {
+ subwf_def->execute = [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
+ std::function<void(bool, QJsonValue, QString)> cb) {
+ const QString wf_id = params.value("workflow_id").toString().trimmed();
+ if (wf_id.isEmpty()) {
+ cb(false, {}, "Workflow ID is required");
+ return;
+ }
+
+ // Recursion / cycle guard across nested execute_workflow nodes. Runs on the
+ // UI thread; executors are signal-driven on the same thread, so a plain set
+ // is sufficient. Blocks A→A and A→B→A; A→B→C is allowed.
+ static QSet<QString> in_flight;
+ if (in_flight.contains(wf_id)) {
+ cb(false, {}, QString("Cyclic sub-workflow execution detected for '%1'").arg(wf_id));
+ return;
+ }
+
+ auto loaded = fincept::WorkflowRepository::instance().load(wf_id);
+ if (loaded.is_err()) {
+ cb(false, {},
+ QString("Failed to load workflow '%1': %2").arg(wf_id, QString::fromStdString(loaded.error())));
+ return;
+ }
+
+ WorkflowDef sub = loaded.value();
+ if (sub.nodes.isEmpty()) {
+ cb(false, {}, QString("Sub-workflow '%1' has no executable nodes").arg(wf_id));
+ return;
+ }
+
+ // Expose this node's inbound payload to the sub-workflow via static_data.
+ if (!inputs.isEmpty() && !inputs[0].isNull() && !inputs[0].isUndefined()) {
+ QJsonObject sd = sub.static_data;
+ sd["parent_input"] = inputs[0];
+ sub.static_data = sd;
+ }
+
+ in_flight.insert(wf_id);
+ auto* exec = new WorkflowExecutor();
+ QObject::connect(exec, &WorkflowExecutor::execution_finished, exec,
+ [cb, wf_id, exec](const WorkflowExecutionResult& result) {
+ in_flight.remove(wf_id);
+
+ QJsonObject out;
+ out["workflow_id"] = result.workflow_id;
+ out["success"] = result.success;
+ out["duration_ms"] = result.total_duration_ms;
+ QJsonObject node_outputs;
+ for (const auto& nr : result.node_results)
+ node_outputs[nr.node_id] = nr.output;
+ out["nodes"] = node_outputs;
+ if (!result.error.isEmpty())
+ out["error"] = result.error;
+
+ if (result.success)
+ cb(true, out, {});
+ else
+ cb(false, out, result.error.isEmpty() ? "Sub-workflow failed" : result.error);
+
+ exec->deleteLater();
+ });
+ exec->execute(sub);
+ };
+ LOG_INFO("ServiceBridges", "control.execute_workflow bridge wired");
+ }
+
LOG_INFO("ServiceBridges", "Utility bridges wired");
}
diff --git a/fincept-qt/src/services/workflow/nodes/AnalyticsNodes.cpp b/fincept-qt/src/services/workflow/nodes/AnalyticsNodes.cpp
index 7bc93bdc7..463d8f3ec 100644
--- a/fincept-qt/src/services/workflow/nodes/AnalyticsNodes.cpp
+++ b/fincept-qt/src/services/workflow/nodes/AnalyticsNodes.cpp
@@ -671,9 +671,13 @@ void register_analytics_nodes(NodeRegistry& registry) {
int n_sims = static_cast<int>(params.value("simulations").toDouble(1000));
int horizon = static_cast<int>(params.value("horizon_days").toDouble(252));
- // Cap simulations for performance
- if (n_sims > 10000)
- n_sims = 10000;
+ // Clamp: >10000 sims is a perf risk; <1 sim leaves final_prices
+ // empty and the percentile reads below (final_prices[n_sims/2],
+ // .first(), .last()) would be out-of-bounds → crash. A negative
+ // horizon must not underflow the inner loop bound either.
+ n_sims = qBound(1, n_sims, 10000);
+ if (horizon < 0)
+ horizon = 0;
double start_price = prices.last();
QVector<double> final_prices;
diff --git a/fincept-qt/src/services/workflow/nodes/DataFormatNodes.cpp b/fincept-qt/src/services/workflow/nodes/DataFormatNodes.cpp
index b978b0c85..ff5fc3f54 100644
--- a/fincept-qt/src/services/workflow/nodes/DataFormatNodes.cpp
+++ b/fincept-qt/src/services/workflow/nodes/DataFormatNodes.cpp
@@ -5,6 +5,8 @@
#include <QJsonArray>
#include <QJsonDocument>
#include <QRegularExpression>
+#include <QXmlStreamReader>
+#include <QXmlStreamWriter>
namespace fincept::workflow {
@@ -22,6 +24,80 @@ QJsonValue resolve_dot_path(const QJsonObject& root, const QString& path) {
return current;
}
+// ── XML ⇄ JSON helpers (format.xml) ─────────────────────────────────────────
+// Recursive XML element → JSON. `xml` must be positioned on the StartElement.
+// Attributes become "@name" keys, mixed text becomes "#text", repeated child
+// elements collapse into arrays, and a text-only element yields a bare string.
+QJsonValue xml_element_to_json(QXmlStreamReader& xml) {
+ QJsonObject obj;
+ for (const auto& a : xml.attributes())
+ obj.insert("@" + a.name().toString(), a.value().toString());
+
+ QString text;
+ bool done = false;
+ while (!done && !xml.atEnd()) {
+ switch (xml.readNext()) {
+ case QXmlStreamReader::StartElement: {
+ const QString name = xml.name().toString();
+ const QJsonValue child = xml_element_to_json(xml);
+ if (obj.contains(name)) {
+ const QJsonValue existing = obj.value(name);
+ QJsonArray arr = existing.isArray() ? existing.toArray() : QJsonArray{existing};
+ arr.append(child);
+ obj[name] = arr;
+ } else {
+ obj.insert(name, child);
+ }
+ break;
+ }
+ case QXmlStreamReader::Characters:
+ if (!xml.isWhitespace())
+ text += xml.text().toString();
+ break;
+ case QXmlStreamReader::EndElement:
+ done = true;
+ break;
+ default:
+ break;
+ }
+ }
+
+ const QString trimmed = text.trimmed();
+ if (obj.isEmpty())
+ return trimmed; // leaf text node
+ if (!trimmed.isEmpty())
+ obj.insert("#text", trimmed);
+ return obj;
+}
+
+// Recursive JSON → XML. `name` is the element name to emit `value` under.
+// "@key" → attribute, "#text" → element text, arrays → repeated elements.
+void json_value_to_xml(QXmlStreamWriter& w, const QString& name, const QJsonValue& value) {
+ if (value.isArray()) {
+ for (const QJsonValue& item : value.toArray())
+ json_value_to_xml(w, name, item);
+ return;
+ }
+ if (value.isObject()) {
+ w.writeStartElement(name);
+ const QJsonObject o = value.toObject();
+ for (auto it = o.begin(); it != o.end(); ++it)
+ if (it.key().startsWith('@'))
+ w.writeAttribute(it.key().mid(1), it.value().toVariant().toString());
+ for (auto it = o.begin(); it != o.end(); ++it) {
+ if (it.key().startsWith('@'))
+ continue;
+ if (it.key() == "#text")
+ w.writeCharacters(it.value().toVariant().toString());
+ else
+ json_value_to_xml(w, it.key(), it.value());
+ }
+ w.writeEndElement();
+ return;
+ }
+ w.writeTextElement(name, value.isNull() ? QString() : value.toVariant().toString());
+}
+
} // anonymous namespace
void register_data_format_nodes(NodeRegistry& registry) {
@@ -134,10 +210,66 @@ void register_data_format_nodes(NodeRegistry& registry) {
{"operation", "Operation", "select", "parse", {"parse", "generate"}, ""},
},
.execute =
- [](const QJsonObject&, const QVector<QJsonValue>& inputs,
+ [](const QJsonObject& params, const QVector<QJsonValue>& inputs,
std::function<void(bool, QJsonValue, QString)> cb) {
- auto data = inputs.isEmpty() ? QJsonValue{} : inputs[0];
- cb(true, data, {});
+ const QJsonValue input = inputs.isEmpty() ? QJsonValue{} : inputs[0];
+ const QString op = params.value("operation").toString("parse");
+
+ if (op == "generate") {
+ // JSON → XML string.
+ if (!input.isObject() && !input.isArray()) {
+ cb(false, {}, "format.xml generate: input must be an object or array");
+ return;
+ }
+ QString xml_out;
+ QXmlStreamWriter w(&xml_out);
+ w.setAutoFormatting(true);
+ w.writeStartDocument();
+ if (input.isObject()) {
+ const QJsonObject o = input.toObject();
+ if (o.size() == 1) {
+ // Single top-level key → use it as the document root element.
+ const auto it = o.begin();
+ json_value_to_xml(w, it.key(), it.value());
+ } else {
+ json_value_to_xml(w, "root", input);
+ }
+ } else {
+ json_value_to_xml(w, "root", input);
+ }
+ w.writeEndDocument();
+ QJsonObject out;
+ out["xml"] = xml_out;
+ cb(true, out, {});
+ return;
+ }
+
+ // Default: parse XML string → JSON (wrapped under its root element name).
+ QString raw;
+ if (input.isString()) {
+ raw = input.toString();
+ } else if (input.isObject()) {
+ const QJsonObject obj = input.toObject();
+ raw = obj.value("xml").toString(obj.value("text").toString());
+ }
+ if (raw.trimmed().isEmpty()) {
+ cb(false, {}, "format.xml parse: no XML string input to parse");
+ return;
+ }
+ QXmlStreamReader xml(raw);
+ while (!xml.atEnd() && xml.readNext() != QXmlStreamReader::StartElement) {
+ }
+ if (xml.hasError() || xml.atEnd()) {
+ cb(false, {},
+ xml.hasError() ? QString("format.xml parse: %1").arg(xml.errorString())
+ : QStringLiteral("format.xml parse: no root element"));
+ return;
+ }
+ const QString root_name = xml.name().toString();
+ const QJsonValue parsed = xml_element_to_json(xml);
+ QJsonObject out;
+ out.insert(root_name, parsed);
+ cb(true, out, {});
},
});
@@ -281,7 +413,9 @@ void register_data_format_nodes(NodeRegistry& registry) {
}
QString delim_param = params.value("delimiter").toString(",");
- QChar delimiter = (delim_param == "\\t") ? '\t' : delim_param.at(0);
+ // An explicitly-cleared delimiter param is an empty string (not
+ // the default), so .at(0) would read out of bounds → crash.
+ QChar delimiter = (delim_param == "\\t") ? '\t' : (delim_param.isEmpty() ? ',' : delim_param.at(0));
bool has_header = params.value("has_header").toBool(true);
// Split into lines, handling \r\n and \n.
diff --git a/fincept-qt/src/services/workflow/nodes/SafetyNodes.cpp b/fincept-qt/src/services/workflow/nodes/SafetyNodes.cpp
index 55f1e869a..a9a3f1c09 100644
--- a/fincept-qt/src/services/workflow/nodes/SafetyNodes.cpp
+++ b/fincept-qt/src/services/workflow/nodes/SafetyNodes.cpp
@@ -50,7 +50,15 @@ void register_safety_nodes(NodeRegistry& registry) {
QStringList failures;
- if (portfolio_value > 0 && price > 0) {
+ // Fail CLOSED when the data needed to size the position is
+ // missing: a risk gate that can't evaluate its rule because the
+ // upstream portfolio_value/price is absent must not wave the
+ // trade through. The old code skipped the check (fail-open).
+ if (portfolio_value <= 0 || price <= 0) {
+ failures << QString("Cannot verify position size — missing %1")
+ .arg(portfolio_value <= 0 ? QStringLiteral("portfolio_value")
+ : QStringLiteral("price"));
+ } else {
double position_value = quantity * price;
double position_pct = (position_value / portfolio_value) * 100.0;
if (position_pct > max_pos_pct)
diff --git a/fincept-qt/src/storage/repositories/DashboardLayoutRepository.cpp b/fincept-qt/src/storage/repositories/DashboardLayoutRepository.cpp
index 8acccfd4e..be264a82b 100644
--- a/fincept-qt/src/storage/repositories/DashboardLayoutRepository.cpp
+++ b/fincept-qt/src/storage/repositories/DashboardLayoutRepository.cpp
@@ -68,8 +68,16 @@ Result<screens::GridLayout> DashboardLayoutRepository::load_layout(const QString
}
Result<void> DashboardLayoutRepository::save_layout(const screens::GridLayout& layout, const QString& profile_name) {
- // Upsert the layout profile
- auto r = exec_write("INSERT INTO dashboard_layouts (profile_name, cols, row_height, margin, is_active, updated_at) "
+ // Persist the layout header + widget instances atomically. save_layout()
+ // DELETEs all instances then re-INSERTs them; without a transaction a
+ // mid-loop failure or crash reloads an empty/corrupt dashboard. Wrap in one
+ // transaction, roll back on error.
+ if (auto tx = db().begin_transaction(); tx.is_err())
+ return tx;
+
+ const auto body = [&]() -> Result<void> {
+ // Upsert the layout profile
+ auto r = exec_write("INSERT INTO dashboard_layouts (profile_name, cols, row_height, margin, is_active, updated_at) "
"VALUES (?, ?, ?, ?, 1, datetime('now')) "
"ON CONFLICT(profile_name) DO UPDATE SET "
"cols=excluded.cols, row_height=excluded.row_height, margin=excluded.margin, "
@@ -104,6 +112,15 @@ Result<void> DashboardLayoutRepository::save_layout(const screens::GridLayout& l
if (ri.is_err())
return ri;
}
+ return Result<void>::ok();
+ }; // body
+
+ if (Result<void> br = body(); br.is_err()) {
+ db().rollback();
+ return br;
+ }
+ if (auto cr = db().commit(); cr.is_err())
+ return cr;
LOG_INFO("DashboardRepo", QString("Saved %1 widgets for profile '%2'").arg(layout.items.size()).arg(profile_name));
SyncOutbox::record_unique("dashboard", profile_name, "upsert");
diff --git a/fincept-qt/src/storage/repositories/LlmConfigRepository.cpp b/fincept-qt/src/storage/repositories/LlmConfigRepository.cpp
index e2f40fd2a..cf725517c 100644
--- a/fincept-qt/src/storage/repositories/LlmConfigRepository.cpp
+++ b/fincept-qt/src/storage/repositories/LlmConfigRepository.cpp
@@ -1,7 +1,39 @@
#include "storage/repositories/LlmConfigRepository.h"
+#include "storage/secure/SecureStorage.h"
+
namespace fincept {
+namespace {
+// Encrypt LLM API keys at rest: keep them in SecureStorage (AES-256-GCM,
+// machine-bound key) instead of the plaintext SQL column. Reads fall back to
+// the column so pre-existing plaintext rows keep working and no key is ever
+// lost; writes move the key into SecureStorage and blank the column (only when
+// the encrypted store succeeds — otherwise the plaintext value is kept).
+QString provider_secret_key(const QString& provider) {
+ return QStringLiteral("llm:apikey:provider:") + provider;
+}
+QString model_secret_key(const QString& id) {
+ return QStringLiteral("llm:apikey:model:") + id;
+}
+
+void hydrate_provider_key(LlmConfig& c) {
+ if (!c.api_key.isEmpty())
+ return; // legacy plaintext already present in the column
+ auto sr = SecureStorage::instance().retrieve(provider_secret_key(c.provider));
+ if (sr.is_ok())
+ c.api_key = sr.value();
+}
+
+void hydrate_model_key(LlmModelConfig& m) {
+ if (!m.api_key.isEmpty())
+ return;
+ auto sr = SecureStorage::instance().retrieve(model_secret_key(m.id));
+ if (sr.is_ok())
+ m.api_key = sr.value();
+}
+} // namespace
+
LlmConfigRepository& LlmConfigRepository::instance() {
static LlmConfigRepository s;
return s;
@@ -19,22 +51,39 @@ LlmModelConfig LlmConfigRepository::map_model(QSqlQuery& q) {
}
Result<QVector<LlmConfig>> LlmConfigRepository::list_providers() {
- return query_list("SELECT provider, api_key, base_url, model, is_active, tools_enabled, created_at, updated_at "
- "FROM llm_configs ORDER BY provider",
- {}, map_config);
+ auto r = query_list("SELECT provider, api_key, base_url, model, is_active, tools_enabled, created_at, updated_at "
+ "FROM llm_configs ORDER BY provider",
+ {}, map_config);
+ if (r.is_err())
+ return r;
+ QVector<LlmConfig> out = r.value();
+ for (auto& c : out)
+ hydrate_provider_key(c);
+ return Result<QVector<LlmConfig>>::ok(std::move(out));
}
Result<LlmConfig> LlmConfigRepository::get_active_provider() {
- return query_one("SELECT provider, api_key, base_url, model, is_active, tools_enabled, created_at, updated_at "
- "FROM llm_configs WHERE is_active = 1 LIMIT 1",
- {}, map_config);
+ auto r = query_one("SELECT provider, api_key, base_url, model, is_active, tools_enabled, created_at, updated_at "
+ "FROM llm_configs WHERE is_active = 1 LIMIT 1",
+ {}, map_config);
+ if (r.is_ok()) {
+ LlmConfig c = r.value();
+ hydrate_provider_key(c);
+ return Result<LlmConfig>::ok(std::move(c));
+ }
+ return r;
}
Result<void> LlmConfigRepository::save_provider(const LlmConfig& c) {
+ // Move the API key into SecureStorage; blank the plaintext column only if the
+ // encrypted store succeeded, so a SecureStorage failure never loses the key.
+ QString column_key = c.api_key;
+ if (!c.api_key.isEmpty() && SecureStorage::instance().store(provider_secret_key(c.provider), c.api_key).is_ok())
+ column_key.clear();
return exec_write(
"INSERT OR REPLACE INTO llm_configs (provider, api_key, base_url, model, is_active, tools_enabled, updated_at) "
"VALUES (?, ?, ?, ?, ?, ?, datetime('now'))",
- {c.provider, c.api_key, c.base_url, c.model, c.is_active ? 1 : 0, c.tools_enabled ? 1 : 0});
+ {c.provider, column_key, c.base_url, c.model, c.is_active ? 1 : 0, c.tools_enabled ? 1 : 0});
}
Result<void> LlmConfigRepository::set_active(const QString& provider) {
@@ -43,6 +92,7 @@ Result<void> LlmConfigRepository::set_active(const QString& provider) {
}
Result<void> LlmConfigRepository::delete_provider(const QString& provider) {
+ SecureStorage::instance().remove(provider_secret_key(provider)); // drop the encrypted key too
return exec_write("DELETE FROM llm_configs WHERE provider = ?", {provider});
}
@@ -81,8 +131,11 @@ Result<QVector<LlmModelConfig>> LlmConfigRepository::list_models(const QString&
return Result<QVector<LlmModelConfig>>::err(r.error());
QVector<LlmModelConfig> result;
auto& q = r.value();
- while (q.next())
- result.append(map_model(q));
+ while (q.next()) {
+ LlmModelConfig m = map_model(q);
+ hydrate_model_key(m);
+ result.append(m);
+ }
return Result<QVector<LlmModelConfig>>::ok(std::move(result));
}
auto r = db().execute("SELECT id, provider, model_id, display_name, api_key, base_url, "
@@ -99,14 +152,20 @@ Result<QVector<LlmModelConfig>> LlmConfigRepository::list_models(const QString&
}
Result<void> LlmConfigRepository::save_model(const LlmModelConfig& m) {
+ // Same as save_provider: encrypt the per-model API key, blank the column
+ // only if the encrypted store succeeded.
+ QString column_key = m.api_key;
+ if (!m.api_key.isEmpty() && SecureStorage::instance().store(model_secret_key(m.id), m.api_key).is_ok())
+ column_key.clear();
return exec_write("INSERT OR REPLACE INTO llm_model_configs "
"(id, provider, model_id, display_name, api_key, base_url, is_enabled, is_default, updated_at) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))",
- {m.id, m.provider, m.model_id, m.display_name, m.api_key, m.base_url, m.is_enabled ? 1 : 0,
+ {m.id, m.provider, m.model_id, m.display_name, column_key, m.base_url, m.is_enabled ? 1 : 0,
m.is_default ? 1 : 0});
}
Result<void> LlmConfigRepository::delete_model(const QString& id) {
+ SecureStorage::instance().remove(model_secret_key(id));
return exec_write("DELETE FROM llm_model_configs WHERE id = ?", {id});
}
diff --git a/fincept-qt/src/storage/repositories/LlmProfileRepository.cpp b/fincept-qt/src/storage/repositories/LlmProfileRepository.cpp
index 27b5b7ad6..91ba884a6 100644
--- a/fincept-qt/src/storage/repositories/LlmProfileRepository.cpp
+++ b/fincept-qt/src/storage/repositories/LlmProfileRepository.cpp
@@ -3,12 +3,22 @@
#include "storage/repositories/LlmProfileRepository.h"
#include "core/logging/Logger.h"
+#include "storage/repositories/LlmConfigRepository.h"
+#include "storage/secure/SecureStorage.h"
#include <QSqlQuery>
#include <QUuid>
namespace fincept {
+namespace {
+// Encrypt the profile API key at rest in SecureStorage; reads fall back to the
+// plaintext column so legacy rows keep working and no key is lost.
+QString profile_secret_key(const QString& id) {
+ return QStringLiteral("llm:apikey:profile:") + id;
+}
+} // namespace
+
// ── Singleton ────────────────────────────────────────────────────────────────
LlmProfileRepository& LlmProfileRepository::instance() {
@@ -32,6 +42,13 @@ LlmProfile LlmProfileRepository::map_profile(QSqlQuery& q) {
p.is_default = q.value(9).toBool();
p.created_at = q.value(10).toString();
p.updated_at = q.value(11).toString();
+ // Decrypt the api_key from SecureStorage when the column is blank (encrypted
+ // row); a non-empty column is a legacy plaintext value, used as-is.
+ if (p.api_key.isEmpty() && !p.id.isEmpty()) {
+ auto sr = SecureStorage::instance().retrieve(profile_secret_key(p.id));
+ if (sr.is_ok())
+ p.api_key = sr.value();
+ }
return p;
}
@@ -54,15 +71,21 @@ Result<void> LlmProfileRepository::save_profile(const LlmProfile& p) {
// Generate id if empty (new profile)
QString id = p.id.isEmpty() ? QUuid::createUuid().toString(QUuid::WithoutBraces) : p.id;
+ // Encrypt the api_key; blank the column only if the encrypted store worked.
+ QString column_key = p.api_key;
+ if (!p.api_key.isEmpty() && SecureStorage::instance().store(profile_secret_key(id), p.api_key).is_ok())
+ column_key.clear();
+
return exec_write("INSERT OR REPLACE INTO llm_profiles "
" (id, name, provider, model_id, api_key, base_url, "
" temperature, max_tokens, system_prompt, is_default, updated_at) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))",
- {id, p.name, p.provider, p.model_id, p.api_key, p.base_url, p.temperature, p.max_tokens,
+ {id, p.name, p.provider, p.model_id, column_key, p.base_url, p.temperature, p.max_tokens,
p.system_prompt, p.is_default ? 1 : 0});
}
Result<void> LlmProfileRepository::delete_profile(const QString& id) {
+ SecureStorage::instance().remove(profile_secret_key(id)); // drop the encrypted key too
// Assignments cascade-delete via FK ON DELETE CASCADE
return exec_write("DELETE FROM llm_profiles WHERE id = ?", {id});
}
@@ -145,21 +168,23 @@ ResolvedLlmProfile LlmProfileRepository::profile_to_resolved(const LlmProfile& p
}
ResolvedLlmProfile LlmProfileRepository::legacy_fallback() const {
- // Read from llm_configs (old table) as last resort
- auto r = db().execute("SELECT provider, api_key, base_url, model FROM llm_configs WHERE is_active = 1 LIMIT 1");
- if (r.is_err())
+ // Read the active provider via LlmConfigRepository (which decrypts the
+ // api_key from SecureStorage) rather than a raw SELECT on llm_configs —
+ // that column is now blanked for encrypted rows.
+ auto cr = LlmConfigRepository::instance().get_active_provider();
+ if (cr.is_err())
return {};
- auto& q = r.value();
- if (!q.next())
+ const LlmConfig c = cr.value();
+ if (c.provider.isEmpty())
return {};
ResolvedLlmProfile rp;
rp.profile_id = {};
rp.profile_name = "Legacy Active";
- rp.provider = q.value(0).toString();
- rp.api_key = q.value(1).toString();
- rp.base_url = q.value(2).toString();
- rp.model_id = q.value(3).toString();
+ rp.provider = c.provider;
+ rp.api_key = c.api_key;
+ rp.base_url = c.base_url;
+ rp.model_id = c.model;
// Pull global temperature/max_tokens
auto gs = db().execute("SELECT temperature, max_tokens FROM llm_global_settings WHERE id = 1");
diff --git a/fincept-qt/src/storage/repositories/McpServerRepository.cpp b/fincept-qt/src/storage/repositories/McpServerRepository.cpp
index 9e307152a..f4d3826f2 100644
--- a/fincept-qt/src/storage/repositories/McpServerRepository.cpp
+++ b/fincept-qt/src/storage/repositories/McpServerRepository.cpp
@@ -1,17 +1,34 @@
#include "storage/repositories/McpServerRepository.h"
+#include "storage/secure/SecureStorage.h"
+
namespace fincept {
+namespace {
+// The `env` blob holds an MCP server's environment variables, which routinely
+// include API tokens. Encrypt it at rest in SecureStorage; reads fall back to
+// the plaintext column so legacy rows keep working and nothing is lost.
+QString mcp_env_secret_key(const QString& id) {
+ return QStringLiteral("mcp:env:") + id;
+}
+} // namespace
+
McpServerRepository& McpServerRepository::instance() {
static McpServerRepository s;
return s;
}
McpServer McpServerRepository::map_row(QSqlQuery& q) {
- return {q.value(0).toString(), q.value(1).toString(), q.value(2).toString(), q.value(3).toString(),
- q.value(4).toString(), q.value(5).toString(), q.value(6).toString(), q.value(7).toString(),
- q.value(8).toBool(), q.value(9).toBool(), q.value(10).toString(), q.value(11).toString(),
- q.value(12).toString()};
+ McpServer s{q.value(0).toString(), q.value(1).toString(), q.value(2).toString(), q.value(3).toString(),
+ q.value(4).toString(), q.value(5).toString(), q.value(6).toString(), q.value(7).toString(),
+ q.value(8).toBool(), q.value(9).toBool(), q.value(10).toString(), q.value(11).toString(),
+ q.value(12).toString()};
+ if (s.env.isEmpty() && !s.id.isEmpty()) {
+ auto sr = SecureStorage::instance().retrieve(mcp_env_secret_key(s.id));
+ if (sr.is_ok())
+ s.env = sr.value();
+ }
+ return s;
}
static const char* kCols = "id, name, description, command, args, env, category, icon, enabled, "
@@ -26,15 +43,20 @@ Result<McpServer> McpServerRepository::get(const QString& id) {
}
Result<void> McpServerRepository::save(const McpServer& s) {
+ // Encrypt the env blob; blank the column only if the encrypted store worked.
+ QString column_env = s.env;
+ if (!s.env.isEmpty() && SecureStorage::instance().store(mcp_env_secret_key(s.id), s.env).is_ok())
+ column_env.clear();
return exec_write(
"INSERT OR REPLACE INTO mcp_servers "
"(id, name, description, command, args, env, category, icon, enabled, auto_start, status, updated_at) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))",
- {s.id, s.name, s.description, s.command, s.args, s.env, s.category, s.icon, s.enabled ? 1 : 0,
+ {s.id, s.name, s.description, s.command, s.args, column_env, s.category, s.icon, s.enabled ? 1 : 0,
s.auto_start ? 1 : 0, s.status});
}
Result<void> McpServerRepository::remove(const QString& id) {
+ SecureStorage::instance().remove(mcp_env_secret_key(id)); // drop the encrypted env too
return exec_write("DELETE FROM mcp_servers WHERE id = ?", {id});
}
diff --git a/fincept-qt/src/storage/repositories/WorkflowRepository.cpp b/fincept-qt/src/storage/repositories/WorkflowRepository.cpp
index c604028d5..3ccb54abe 100644
--- a/fincept-qt/src/storage/repositories/WorkflowRepository.cpp
+++ b/fincept-qt/src/storage/repositories/WorkflowRepository.cpp
@@ -21,8 +21,17 @@ WorkflowRow WorkflowRepository::map_row(QSqlQuery& q) {
}
Result<void> WorkflowRepository::save(const workflow::WorkflowDef& wf) {
- // Upsert the workflow header
- auto r = exec_write("INSERT INTO workflows (id, name, description, status, static_data, updated_at) "
+ // Persist header + nodes + edges atomically. save() DELETEs all existing
+ // nodes/edges then re-INSERTs them; without a transaction a mid-sequence
+ // failure (constraint / disk-full) or a crash would leave the graph
+ // partially wiped and the next load() would return an empty/corrupt
+ // workflow. Wrap the whole rewrite in one transaction, roll back on error.
+ if (auto tx = db().begin_transaction(); tx.is_err())
+ return tx;
+
+ const auto body = [&]() -> Result<void> {
+ // Upsert the workflow header
+ auto r = exec_write("INSERT INTO workflows (id, name, description, status, static_data, updated_at) "
"VALUES (?, ?, ?, ?, ?, datetime('now')) "
"ON CONFLICT(id) DO UPDATE SET "
" name = excluded.name,"
@@ -74,6 +83,15 @@ Result<void> WorkflowRepository::save(const workflow::WorkflowDef& wf) {
if (r.is_err())
return r;
}
+ return Result<void>::ok();
+ }; // body
+
+ if (Result<void> br = body(); br.is_err()) {
+ db().rollback();
+ return br;
+ }
+ if (auto cr = db().commit(); cr.is_err())
+ return cr;
LOG_INFO("WorkflowRepo",
QString("Saved workflow: %1 (%2 nodes, %3 edges)").arg(wf.name).arg(wf.nodes.size()).arg(wf.edges.size()));
diff --git a/fincept-qt/src/trading/BrokerRegistry.h b/fincept-qt/src/trading/BrokerRegistry.h
index df850a7e2..0443e5e57 100644
--- a/fincept-qt/src/trading/BrokerRegistry.h
+++ b/fincept-qt/src/trading/BrokerRegistry.h
@@ -1,5 +1,5 @@
#pragma once
-// Broker Registry — factory + lookup for all 16 broker implementations
+// Broker Registry — factory + lookup for all 22 broker implementations
#include "trading/BrokerInterface.h"
diff --git a/fincept-qt/src/trading/UnifiedTrading.cpp b/fincept-qt/src/trading/UnifiedTrading.cpp
index 60420c7c3..781bb69ef 100644
--- a/fincept-qt/src/trading/UnifiedTrading.cpp
+++ b/fincept-qt/src/trading/UnifiedTrading.cpp
@@ -107,25 +107,26 @@ UnifiedOrderResponse UnifiedTrading::place_paper_order(const TradingSession& ses
QString side_str = order_side_str(order.side);
QString type_str = order_type_str(order.order_type);
+ // Fill/reference price = caller-supplied LTP (order.price). The old code used
+ // a hardcoded 1000.0 for market orders, fabricating P&L. Reject a market fill
+ // with no usable price instead, matching the account-based place_order path.
std::optional<double> price_opt;
- if (order.order_type == OrderType::Market) {
- price_opt = 1000.0;
- } else if (order.price > 0) {
+ if (order.price > 0)
price_opt = order.price;
- }
std::optional<double> stop_opt;
if (order.stop_price > 0)
stop_opt = order.stop_price;
+ if (order.order_type == OrderType::Market && !price_opt)
+ return {false, "", "No live price yet for a market fill — wait for quotes to load", "paper"};
+
try {
auto paper_order = pt_place_order(session.paper_portfolio_id, symbol, side_str, type_str, order.quantity,
price_opt, stop_opt, false);
- if (order.order_type == OrderType::Market) {
- double fill_price = order.price > 0 ? order.price : 1000.0;
- pt_fill_order(paper_order.id, fill_price);
- }
+ if (order.order_type == OrderType::Market)
+ pt_fill_order(paper_order.id, *price_opt);
return {true, paper_order.id, "Paper order placed", "paper"};
} catch (const std::exception& e) {
@@ -532,11 +533,20 @@ ApiResponse<SmartOrderResult> UnifiedTrading::place_smart_order(const QString& a
return {true, SmartOrderResult{false, {}, {}, 0, "No action needed. Position already at target."}, {}};
}
- auto side_str = (action == OrderSide::Buy) ? QString("buy") : QString("sell");
+ // Fill at the caller-supplied live price (SmartOrder.price = LTP), NOT a
+ // hardcoded 1000.0 sentinel — that fabricated P&L (closing a 250-cost
+ // long booked (1000-250)·qty of phantom profit, and a net-new position
+ // opened at 1000). Reject a paper market fill with no usable price, the
+ // same way the regular paper place_order path does.
+ if (order.price <= 0.0)
+ return {false, std::nullopt,
+ QString("No live price for a paper smart-order fill on %1 (supply SmartOrder.price = LTP)")
+ .arg(paper_sym)};
+ const auto side_str = (action == OrderSide::Buy) ? QString("buy") : QString("sell");
try {
auto paper_order = pt_place_order(account.paper_portfolio_id, paper_sym, side_str, "market", quantity,
- std::nullopt, std::nullopt, false);
- pt_fill_order(paper_order.id, 1000.0);
+ order.price, std::nullopt, false);
+ pt_fill_order(paper_order.id, order.price);
return {true,
SmartOrderResult{true, paper_order.id, action, quantity,
QString("Paper: adjusted from %1 to %2").arg(current).arg(target)},
@@ -665,7 +675,9 @@ void UnifiedTrading::place_basket_orders(const QString& account_id, const Basket
}
QPointer<UnifiedTrading> self = this;
- (void)QtConcurrent::run([self, orders, is_paper, broker, creds, paper_portfolio_id, callback]() {
+ const QString basket_strategy = basket.strategy_name;
+ (void)QtConcurrent::run(
+ [self, account_id, basket_strategy, orders, is_paper, broker, creds, paper_portfolio_id, callback]() {
BasketOrderResult result;
result.total = orders.size();
@@ -733,7 +745,10 @@ void UnifiedTrading::place_basket_orders(const QString& account_id, const Basket
return;
QMetaObject::invokeMethod(
self,
- [self, result, callback]() {
+ [self, account_id, basket_strategy, is_paper, result, callback]() {
+ // Notify listeners (e.g. TradingNotificationBridge) that the basket finished.
+ publish(BasketCompletedEvent{account_id, basket_strategy, result.successful, result.failed,
+ result.total, is_paper ? QStringLiteral("paper") : QStringLiteral("live")});
if (callback)
callback(result);
},
diff --git a/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp b/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
index 44b165cfd..86f1e7262 100644
--- a/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
+++ b/fincept-qt/src/trading/brokers/dhan/DhanBroker.cpp
@@ -212,7 +212,7 @@ TokenExchangeResponse DhanBroker::exchange_token(const QString& api_key, const Q
// The live validation sweep is the authoritative guard; this expiry is only
// a startup hint so a token isn't shown green long after it has lapsed.
const QString extra = with_token_expiry({}, rolling_expiry_epoch(24));
- LOG_INFO(TAG, "Token exchange OK, client_id=" + api_key);
+ LOG_INFO(TAG, "Token exchange OK"); // don't log client_id (P14)
return {true, api_secret, /*refresh*/ "", api_key, /*additional*/ extra, ""};
}
diff --git a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp
index f482aa865..305096cdd 100644
--- a/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp
+++ b/fincept-qt/src/trading/brokers/zerodha/ZerodhaBroker.cpp
@@ -151,8 +151,8 @@ TokenExchangeResponse ZerodhaBroker::exchange_token(const QString& api_key, cons
QByteArray input = (api_key + request_token + api_secret).toUtf8();
QString checksum = QCryptographicHash::hash(input, QCryptographicHash::Sha256).toHex();
- LOG_INFO("Zerodha", QString("exchange_token: api_key=%1 req_token_len=%2 secret_len=%3")
- .arg(api_key)
+ LOG_INFO("Zerodha", QString("exchange_token: api_key_len=%1 req_token_len=%2 secret_len=%3")
+ .arg(api_key.length())
.arg(request_token.length())
.arg(api_secret.length()));
diff --git a/fincept-qt/src/trading/instruments/InstrumentDecompress.cpp b/fincept-qt/src/trading/instruments/InstrumentDecompress.cpp
index 91d8f98ec..bc9ad60f9 100644
--- a/fincept-qt/src/trading/instruments/InstrumentDecompress.cpp
+++ b/fincept-qt/src/trading/instruments/InstrumentDecompress.cpp
@@ -3,6 +3,16 @@
#include "core/logging/Logger.h"
#include <cstring>
+// Qt Core bundles zlib and exports it with a `z_` prefix (see Qt's zconf.h:
+// "Qt Core must export these symbols, define Z_PREFIX to avoid clashes with
+// system zlib"). We link Qt6::ZlibPrivate on Windows, so the calls must be
+// prefixed too. Qt's own zconf.h auto-defines Z_PREFIX, but if another zlib.h
+// shadows it on the include path (e.g. a PostgreSQL install whose include dir
+// precedes QtZlib), the unprefixed symbols won't link. Define it ourselves so
+// inflate() → z_inflate() regardless of which standard zlib.h is picked up.
+#ifndef Z_PREFIX
+# define Z_PREFIX
+#endif
#include <zlib.h>
namespace fincept::trading::decompress {
diff --git a/fincept-qt/src/ui/tables/NumericTableWidgetItem.h b/fincept-qt/src/ui/tables/NumericTableWidgetItem.h
new file mode 100644
index 000000000..2dfc0442d
--- /dev/null
+++ b/fincept-qt/src/ui/tables/NumericTableWidgetItem.h
@@ -0,0 +1,31 @@
+#pragma once
+
+#include <QTableWidgetItem>
+
+namespace fincept::ui {
+
+// A QTableWidgetItem that SORTS by a numeric value while DISPLAYING arbitrary
+// (formatted) text. Plain QTableWidgetItem::operator< compares the DisplayRole
+// as a string, so "10" sorts before "9" and "$1,000" before "$200" — wrong for
+// any numeric column. Use this for price / quantity / ratio / percent cells so
+// header-click sorting orders by magnitude.
+//
+// table->setItem(row, col, new ui::NumericTableWidgetItem(QString::number(v,'f',2), v));
+class NumericTableWidgetItem : public QTableWidgetItem {
+ public:
+ NumericTableWidgetItem(const QString& display_text, double value)
+ : QTableWidgetItem(display_text), value_(value) {}
+
+ bool operator<(const QTableWidgetItem& other) const override {
+ if (const auto* o = dynamic_cast<const NumericTableWidgetItem*>(&other))
+ return value_ < o->value_;
+ return QTableWidgetItem::operator<(other);
+ }
+
+ double numeric_value() const { return value_; }
+
+ private:
+ double value_ = 0.0;
+};
+
+} // namespace fincept::ui