diff --git a/backend/app/crypto_agent/crypto_agent.py b/backend/app/crypto_agent/crypto_agent.py index 9fa0e4e..150a7f8 100644 --- a/backend/app/crypto_agent/crypto_agent.py +++ b/backend/app/crypto_agent/crypto_agent.py @@ -20,8 +20,22 @@ from app.crypto_agent.llm_signal_analyzer import LLMSignalAnalyzer class CryptoAgent: """加密货币交易信号智能体(LLM 驱动版)""" + _instance = None + _initialized = False + + def __new__(cls, *args, **kwargs): + """单例模式 - 确保只有一个实例""" + if cls._instance is None: + cls._instance = super().__new__(cls) + return cls._instance + def __init__(self): """初始化智能体""" + # 防止重复初始化 + if CryptoAgent._initialized: + return + + CryptoAgent._initialized = True self.settings = get_settings() self.binance = binance_service self.feishu = get_feishu_service() @@ -647,5 +661,13 @@ class CryptoAgent: } -# 全局实例 -crypto_agent = CryptoAgent() +# 全局单例 +_crypto_agent: Optional['CryptoAgent'] = None + + +def get_crypto_agent() -> 'CryptoAgent': + """获取加密货币智能体单例""" + global _crypto_agent + if _crypto_agent is None: + _crypto_agent = CryptoAgent() + return _crypto_agent diff --git a/backend/app/main.py b/backend/app/main.py index 3d44239..321849f 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -194,9 +194,14 @@ async def lifespan(app: FastAPI): # 启动加密货币智能体 if getattr(settings, 'crypto_symbols', '') and settings.crypto_symbols.strip(): try: - from app.crypto_agent.crypto_agent import crypto_agent - _crypto_agent_task = asyncio.create_task(crypto_agent.run()) - logger.info(f"加密货币智能体已启动,监控: {settings.crypto_symbols}") + from app.crypto_agent.crypto_agent import get_crypto_agent + crypto_agent = get_crypto_agent() + # 防止重复启动 + if not crypto_agent.running: + _crypto_agent_task = asyncio.create_task(crypto_agent.run()) + logger.info(f"加密货币智能体已启动,监控: {settings.crypto_symbols}") + else: + logger.info("加密货币智能体已在运行中") except Exception as e: logger.error(f"加密货币智能体启动失败: {e}") diff --git a/backend/run_crypto_agent.py b/backend/run_crypto_agent.py index 66fac18..c3e4e6a 100644 --- a/backend/run_crypto_agent.py +++ b/backend/run_crypto_agent.py @@ -9,7 +9,7 @@ import os # 添加项目路径 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -from app.crypto_agent.crypto_agent import crypto_agent +from app.crypto_agent.crypto_agent import get_crypto_agent from app.utils.logger import logger @@ -20,6 +20,7 @@ async def main(): logger.info("=" * 50) try: + crypto_agent = get_crypto_agent() await crypto_agent.run() except KeyboardInterrupt: logger.info("收到停止信号,正在关闭...")