主要修改: 1. CacheManager 负责数据库降级(单一职责) - 缓存未命中自动从数据库加载 - 移除 StrategyManager/Context 的 db_manager 依赖 2. 添加 StrategyContext 核心组件 - Position: 持仓管理 - Capital: 资金管理 - RiskState: 风险控制 - BaseStrategy: 策略基类 3. 配置与类型修复 - global.yaml 添加完整缓存配置 - 修复 Pylance 类型推断错误 - Config.load_with_global() 合并全局配置 4. 技术设计文档 - 架构重构总结 - 缓存设计方案 - Context 共享策略 - 接口最小化原则
107 lines
2.5 KiB
Python
107 lines
2.5 KiB
Python
"""
|
|
策略基类 (BaseStrategy)
|
|
|
|
所有策略必须继承此基类
|
|
"""
|
|
|
|
from abc import ABC, abstractmethod
|
|
from typing import Dict, Any, Optional
|
|
import logging
|
|
|
|
from src.core.strategy_context import StrategyContext
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class BaseStrategy(ABC):
|
|
"""
|
|
策略基类
|
|
|
|
所有策略都应该继承此类并实现 compute 方法
|
|
"""
|
|
|
|
def __init__(self, context: StrategyContext, **params):
|
|
"""
|
|
初始化策略
|
|
|
|
Args:
|
|
context: 策略上下文
|
|
**params: 策略参数
|
|
"""
|
|
self.context: StrategyContext = context
|
|
self.params: Dict[str, Any] = params
|
|
|
|
logger.info(
|
|
f"Strategy initialized: instance_id={context.instance_id}, "
|
|
f"symbol={context.symbol}, params={params}"
|
|
)
|
|
|
|
@abstractmethod
|
|
def compute(self, kline_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
"""
|
|
计算信号(必须实现)
|
|
|
|
Args:
|
|
kline_data: K线数据字典
|
|
{
|
|
'symbol': str,
|
|
'timestamp': str,
|
|
'open': float,
|
|
'high': float,
|
|
'low': float,
|
|
'close': float,
|
|
'volume': float
|
|
}
|
|
|
|
Returns:
|
|
信号字典或None
|
|
{
|
|
'action': 'BUY' | 'SELL' | 'HOLD',
|
|
'symbol': str,
|
|
'price': float,
|
|
'quantity': int,
|
|
'reason': str # 可选
|
|
}
|
|
"""
|
|
pass
|
|
|
|
def on_init(self):
|
|
"""
|
|
初始化回调(可选实现)
|
|
|
|
在策略加载完成后调用,可以在这里做一些初始化工作
|
|
"""
|
|
pass
|
|
|
|
def on_trade(self, trade_result: Dict[str, Any]):
|
|
"""
|
|
交易回调(可选实现)
|
|
|
|
在交易执行后调用
|
|
|
|
Args:
|
|
trade_result: 交易结果
|
|
{
|
|
'action': str,
|
|
'symbol': str,
|
|
'price': float,
|
|
'quantity': int,
|
|
'success': bool,
|
|
'message': str
|
|
}
|
|
"""
|
|
pass
|
|
|
|
def on_error(self, error: Exception):
|
|
"""
|
|
错误回调(可选实现)
|
|
|
|
在策略执行出错时调用
|
|
|
|
Args:
|
|
error: 异常对象
|
|
"""
|
|
logger.error(
|
|
f"Strategy error in {self.context.instance_id}: {error}", exc_info=True
|
|
)
|