diff --git a/configs/global.yaml b/configs/global.yaml index 0191131..53cb9f0 100644 --- a/configs/global.yaml +++ b/configs/global.yaml @@ -27,6 +27,14 @@ database: pool_recycle: 3600 echo: false +# 缓存配置(公用) +cache: + enabled: true + type: "memory" # memory-内存缓存 + max_memory_mb: 4096 # 最大内存限制 4GB + capacity: 10000 # 最大缓存条目数 + ttl: 3600 # 缓存过期时间(秒) + # 日志配置(公用) logging: format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s" diff --git a/docs/tech_designs/REFACTOR_SUMMARY.md b/docs/tech_designs/REFACTOR_SUMMARY.md new file mode 100644 index 0000000..7781f7e --- /dev/null +++ b/docs/tech_designs/REFACTOR_SUMMARY.md @@ -0,0 +1,546 @@ +# 重构完成总结 + +> **日期**: 2025-12-27 +> **重构目标**: 实现简化的两层架构,Context直接提供数据访问方法 +> **原则**: 不考虑兼容性,全新重构 + +--- + +## 1. 重构概览 + +### 1.1 架构变化 + +**原架构(假想的三层)**: +``` +Strategy → StrategyContext → SharedServices → CacheManager +``` + +**新架构(两层)**: +``` +Strategy → StrategyContext → CacheManager +``` + +### 1.2 核心变化 + +| 变化项 | 重构前 | 重构后 | +| --------------- | ---------------------------- | ------------------------- | +| **中间层** | 需要 SharedServices | ❌ 删除 | +| **Context职责** | 持有SharedServices引用 | 直接持有cache_manager引用 | +| **数据访问** | context._shared.get_klines() | context.get_klines() | +| **共享机制** | 传入SharedServices实例 | 传入cache_manager实例 | +| **策略基类** | 无统一基类 | 新增BaseStrategy | + +--- + +## 2. 新增文件 + +### 2.1 核心类 + +| 文件 | 说明 | 行数 | +| ------------------------------------------------------------ | ------------------------ | ---- | +| [src/core/position.py](src/core/position.py) | 持仓管理(独立状态) | ~100 | +| [src/core/capital.py](src/core/capital.py) | 资金管理(独立状态) | ~130 | +| [src/core/risk_state.py](src/core/risk_state.py) | 风险状态管理(独立状态) | ~180 | +| [src/core/strategy_context.py](src/core/strategy_context.py) | 策略上下文(核心) | ~360 | +| [src/core/base_strategy.py](src/core/base_strategy.py) | 策略基类 | ~80 | + +### 2.2 详细说明 + +#### Position (持仓管理) +```python +@dataclass +class Position: + symbol: str + shares: float = 0.0 # 持仓数量 + cost: float = 0.0 # 持仓成本 + + @property + def avg_price(self) -> float + def update(self, shares_change, cost_change) + def calculate_profit(self, current_price) -> float +``` + +#### Capital (资金管理) +```python +@dataclass +class Capital: + initial_cash: float + available_cash: float + frozen_cash: float + + def freeze(self, amount) -> bool + def unfreeze(self, amount) -> bool + def update(self, amount) +``` + +#### RiskState (风险状态) +```python +@dataclass +class RiskState: + max_position_ratio: float + stop_loss_ratio: float + stop_profit_ratio: float + + def check_position_limit(self, ...) -> bool + def check_stop_loss(self, ...) -> bool + def record_loss(self, loss_amount) +``` + +#### StrategyContext (核心) +```python +class StrategyContext: + def __init__( + self, + cache_manager, # 共享实例 + db_manager, # 共享实例(可选) + instance_id, + symbol, + instance_config, + enable_db_fallback + ) + + # 共享资源(私有) + self._cache_manager + self._db_manager + + # 独立状态 + self._position: Position + self._capital: Capital + self._risk_state: RiskState + + # 数据访问接口 + def get_klines(...) -> DataFrame + def get_indicators(...) -> DataFrame + + # 状态访问接口 + def get_position() -> Position + def get_capital() -> Capital + def get_risk_state() -> RiskState +``` + +#### BaseStrategy (策略基类) +```python +class BaseStrategy(ABC): + def __init__(self, context: StrategyContext, **params) + + @abstractmethod + def compute(self, kline_data) -> Optional[Dict] + + def on_init(self) # 可选回调 + def on_trade(self, ...) # 可选回调 + def on_error(self, ...) # 可选回调 +``` + +--- + +## 3. 修改文件 + +### 3.1 StrategyManager + +**文件**: [src/strategy_manager.py](src/strategy_manager.py) + +**关键修改**: +```python +# 修改前 +def __init__(self, config_dir): + self.config_dir = Path(config_dir) + +# 修改后 +def __init__( + self, + config_dir: str, + cache_manager, # 新增:共享实例 + db_manager=None, # 新增:共享实例(可选) + enable_db_fallback=False # 新增:降级开关 +): + self.config_dir = Path(config_dir) + self._cache_manager = cache_manager + self._db_manager = db_manager + self._enable_db_fallback = enable_db_fallback +``` + +**创建策略实例的变化**: +```python +# 修改前 +strategy_obj = strategy_class(**params) + +# 修改后 +# 1. 创建Context +context = StrategyContext( + cache_manager=self._cache_manager, + db_manager=self._db_manager, + instance_id=instance_id, + symbol=symbol, + instance_config=config, + enable_db_fallback=self._enable_db_fallback +) + +# 2. 创建策略实例(传入context) +strategy_obj = strategy_class(context=context, **params) + +# 3. 调用初始化回调 +if hasattr(strategy_obj, 'on_init'): + strategy_obj.on_init() +``` + +### 3.2 qtrade_server.py + +**文件**: [src/qtrade_server.py](src/qtrade_server.py) + +**新增初始化函数**: +```python +def initialize_server( + config_dir: str = "config/strategies", + cache_config: Optional[dict] = None +): + global strategy_manager, cache_manager + + # 1. 初始化缓存管理器 + cache_manager = CacheManager(cache_config or default_config) + + # 2. 初始化策略管理器(直接传入共享资源) + strategy_manager = StrategyManager( + config_dir=config_dir, + cache_manager=cache_manager, + db_manager=None, + enable_db_fallback=False + ) + + # 3. 加载并初始化所有策略 + strategy_manager.initialize() +``` + +**启动函数修改**: +```python +def start_server(host, port, config_dir): + # 初始化服务器(不再是initialize_strategy_manager) + if not initialize_server(config_dir): + return + + # 注册关闭钩子 + signal.signal(signal.SIGTERM, on_shutdown) + signal.signal(signal.SIGINT, on_shutdown) + + # 创建并启动WebSocket服务器 + ws_server = WebSocketServer(...) + ws_server.start(host, port) +``` + +### 3.3 DebugStrategy + +**文件**: [src/strategies/debug_strategy.py](src/strategies/debug_strategy.py) + +**关键修改**: +```python +# 修改前 +class DebugStrategy: + def __init__(self, **params): + self.print_every = params.get("print_every", 1) + self.last_price = None + +# 修改后 +class DebugStrategy(BaseStrategy): + def on_init(self): + # 从 self.params 和 self.context 获取信息 + self.print_every = self.params.get("print_every", 1) + self.last_price = None + + print(f"[{self.context.instance_id}] Initialized") + print(f" Symbol: {self.context.symbol}") + print(f" Capital: {self.context.get_capital().initial_cash:.2f}") +``` + +**compute方法修改**: +```python +def compute(self, kline_data): + # 可以访问Context的所有方法 + position = self.context.get_position() + capital = self.context.get_capital() + + print(f"[{self.context.instance_id}] K-line #{self.kline_count}") + print(f" Position: {position.shares:.2f} @ {position.avg_price:.2f}") + print(f" Capital: {capital.available_cash:.2f}") + + # ...计算逻辑 +``` + +--- + +## 4. 数据流说明 + +### 4.1 服务器启动流程 + +``` +1. 加载配置 + config = load_config('global_config.yaml') + +2. 初始化缓存管理器 + cache_manager = CacheManager(config['cache']) # 单例 + +3. 初始化策略管理器 + strategy_manager = StrategyManager( + config_dir='config/strategies', + cache_manager=cache_manager, # 传入共享实例 + db_manager=None + ) + +4. 加载策略配置并创建实例 + for each config in configs: + context = StrategyContext( + cache_manager, # 同一个实例 + ... + ) + strategy = DebugStrategy(context, **params) + strategy.on_init() + +5. 启动WebSocket服务器 + ws_server.start(host, port) +``` + +### 4.2 运行时数据流 + +``` +1. WebSocket收到K线数据 + message = {"symbol": "000001.SZ", "data": {...}} + +2. 分发到StrategyManager + signals = strategy_manager.dispatch_kline(symbol, kline_data) + +3. 调用策略compute方法 + for strategy in strategies[symbol]: + result = strategy.compute(kline_data) + + # 策略内部 + history = self.context.get_klines('000001.SZ', '1m', last_n=100) + + # Context内部 + df = self._cache_manager.get_klines(symbol, period) + +4. 返回信号 + return signals +``` + +### 4.3 共享机制说明 + +```python +# 服务器启动时 +cache_manager = CacheManager(...) # 创建一个实例 + +# 创建多个Context +context1 = StrategyContext(cache_manager, ...) # 传入引用 +context2 = StrategyContext(cache_manager, ...) # 传入同一个引用 + +# 验证共享 +context1._cache_manager is context2._cache_manager # True + +# 它们访问的是同一个缓存 +context1.get_klines('000001.SZ', '1m') # 从同一个cache读取 +context2.get_klines('000001.SZ', '1m') # 从同一个cache读取 +``` + +--- + +## 5. 设计优势 + +### 5.1 简洁性 + +| 方面 | 三层架构 | 两层架构 | +| ------------ | ------------------------------------------- | -------------------------- | +| **中间层** | SharedServices | ❌ 无 | +| **调用链** | Strategy → Context → SharedServices → Cache | Strategy → Context → Cache | +| **代码行数** | 更多 | 更少 | +| **理解难度** | 高(为什么需要SharedServices?) | 低(直观) | + +### 5.2 封装性 + +```python +# ✅ 好的封装 +context.get_klines(...) # 策略不知道数据从哪来 + +# Context内部可以: +# - 从缓存读取 +# - 缓存未命中时降级到数据库 +# - 对策略完全透明 +``` + +### 5.3 可维护性 + +**修改数据访问逻辑**: +- 只需修改 StrategyContext.get_klines() 方法 +- 策略代码无需修改 +- 降级逻辑对策略透明 + +**添加新的数据源**: +- 在Context内部添加新的私有成员 +- 修改get_klines()方法的实现 +- 策略接口保持不变 + +--- + +## 6. 使用示例 + +### 6.1 编写新策略 + +```python +from src.core.base_strategy import BaseStrategy + +class MyStrategy(BaseStrategy): + def on_init(self): + """初始化""" + self.ma_period = self.params.get('ma_period', 20) + print(f"Strategy initialized: {self.context.instance_id}") + + def compute(self, kline_data): + """计算信号""" + # 获取历史数据 + history = self.context.get_klines(period='1m', last_n=100) + if history is None or len(history) < self.ma_period: + return None + + # 计算指标 + ma = history['close'].rolling(self.ma_period).mean() + current_price = kline_data['close'] + + # 获取持仓和资金 + position = self.context.get_position() + capital = self.context.get_capital() + + # 检查风险 + risk = self.context.get_risk_state() + if risk.is_risk_locked: + return None + + # 生成信号 + if current_price > ma.iloc[-1] and position.is_empty: + return { + 'action': 'BUY', + 'symbol': self.context.symbol, + 'price': current_price, + 'quantity': 100, + 'reason': f'Price above MA{self.ma_period}' + } + + return None +``` + +### 6.2 策略配置 + +```yaml +# config/strategies/my_strategy_000001.yaml +instance_id: "my_strategy_000001" +symbol: "000001.SZ" +strategy_class: "MyStrategy" +params: + ma_period: 20 +initial_capital: 1000000.0 +max_position_ratio: 0.5 +stop_loss_ratio: 0.05 +``` + +### 6.3 启动服务器 + +```python +# 方式1:直接启动(会自动加载所有配置) +from src.qtrade_server import start_server +start_server(host='0.0.0.0', port=8000) + +# 方式2:自定义配置 +from src.qtrade_server import initialize_server, start_server + +# 初始化 +initialize_server( + config_dir='config/strategies', + cache_config={ + 'cache': { + 'enabled': True, + 'max_memory_mb': 4096 + } + } +) + +# 启动 +start_server(host='0.0.0.0', port=8000) +``` + +--- + +## 7. 注意事项 + +### 7.1 策略必须继承BaseStrategy + +```python +# ❌ 错误 +class MyStrategy: + def __init__(self, **params): + pass + +# ✅ 正确 +class MyStrategy(BaseStrategy): + def on_init(self): + pass + + def compute(self, kline_data): + pass +``` + +### 7.2 Context是策略的唯一接口 + +```python +# ❌ 不要直接访问私有成员 +self.context._cache_manager # 不要这样做 + +# ✅ 使用公开方法 +self.context.get_klines(...) # 正确方式 +``` + +### 7.3 共享资源是只读的 + +```python +# Context内部 +self._cache_manager # 只读取,不要修改状态 + +# 策略可以修改自己的独立状态 +position = self.context.get_position() +position.update(100, 5000.0) # ✅ 可以 +``` + +--- + +## 8. 下一步工作 + +### 8.1 需要实现的功能 + +- [ ] 缓存预加载机制(从数据库加载历史数据) +- [ ] CacheManager扩展(append_kline, get_klines_range) +- [ ] 数据库降级逻辑完善 +- [ ] 服务器关闭时保存缓存(可选) + +### 8.2 需要测试的场景 + +- [ ] 单个策略实例 +- [ ] 多个策略实例(同symbol) +- [ ] 多个策略实例(不同symbol) +- [ ] 缓存命中和未命中 +- [ ] 持仓和资金更新 +- [ ] 风险控制触发 + +--- + +## 9. 设计文档 + +相关设计文档: +1. [qtrade_server_cache_design.md](docs/tech_designs/qtrade_server_cache_design.md) - 缓存机制设计 +2. [qtrade_server_cache_architecture_review.md](docs/tech_designs/qtrade_server_cache_architecture_review.md) - 架构评审 +3. [strategy_context_sharing_design.md](docs/tech_designs/strategy_context_sharing_design.md) - Context共享策略 +4. [shared_services_interface_minimization.md](docs/tech_designs/shared_services_interface_minimization.md) - 接口最小化 +5. [context_direct_methods_design.md](docs/tech_designs/context_direct_methods_design.md) - Context直接方法设计 + +--- + +**重构完成!** ✅ + +核心思想: +- ✅ 不需要SharedServices中间层 +- ✅ Context直接提供所有方法 +- ✅ 共享通过传入同一个实例实现 +- ✅ 策略只依赖Context接口 diff --git a/docs/tech_designs/context_direct_methods_design.md b/docs/tech_designs/context_direct_methods_design.md new file mode 100644 index 0000000..97eb66d --- /dev/null +++ b/docs/tech_designs/context_direct_methods_design.md @@ -0,0 +1,859 @@ +# Context 直接方法设计 + +> **核心观点**: 不需要 SharedServices 中间层,数据访问方法直接放在 StrategyContext 上 +> **用户观点**: "不用封装这么多层,可以直接变为 context 的方法,是不是更好?" +> **日期**: 2025-12-27 +> **结论**: ✅ 完全正确!更简洁、更直观 + +--- + +## 1. 架构对比 + +### 1.1 原设计(三层) + +``` +Strategy + ↓ 调用 +StrategyContext + ↓ context._shared.get_klines() +SharedServices (中间层) + ↓ self._cache_manager.get_klines() +CacheManager +``` + +**代码示例**: +```python +# 策略中使用 +class MAStrategy: + def compute(self, kline_data): + # ❌ 需要通过 _shared 访问 + history = self.context._shared.get_klines('000001.SZ', '1m', last_n=100) + + # 或者封装在 Context 的委托方法中 + history = self.context.get_klines('000001.SZ', '1m', last_n=100) + # 但内部实现: return self._shared.get_klines(...) +``` + +**问题**: +- ❌ 多了一层 SharedServices 间接性 +- ❌ StrategyContext 需要委托所有方法 +- ❌ 增加了复杂度 + +### 1.2 新设计(两层) + +``` +Strategy + ↓ 调用 +StrategyContext (直接提供方法) + ↓ self._cache_manager.get_klines() +CacheManager +``` + +**代码示例**: +```python +# 策略中使用 +class MAStrategy: + def compute(self, kline_data): + # ✅ 直接调用 context 的方法 + history = self.context.get_klines('000001.SZ', '1m', last_n=100) + + # context 内部直接访问 cache_manager + # 不需要通过 SharedServices +``` + +**优点**: +- ✅ 减少一层间接性 +- ✅ 代码更简洁直观 +- ✅ Context 直接封装数据访问逻辑 +- ✅ 符合"Context 是策略的唯一接口"理念 + +--- + +## 2. 新设计实现 + +### 2.1 StrategyContext 实现 + +```python +class StrategyContext: + """ + 策略上下文(直接提供所有方法) + + 设计原则: + 1. Context 是策略访问所有资源的唯一入口 + 2. 内部直接持有 cache_manager、db_manager(私有) + 3. 对外提供高层接口,隐藏实现细节 + """ + + def __init__( + self, + cache_manager: CacheManager, + db_manager: Optional[DBManager], + instance_id: str, + symbol: str, + instance_config: dict, + enable_db_fallback: bool = False + ): + """ + 初始化策略上下文 + + Args: + cache_manager: 缓存管理器(共享实例) + db_manager: 数据库管理器(共享实例,可选) + instance_id: 策略实例ID + symbol: 交易标的 + instance_config: 实例配置 + enable_db_fallback: 是否启用数据库降级 + """ + # ==================== 共享资源(私有) ==================== + # 注意:这些是传入的共享实例,不是新创建的 + self._cache_manager = cache_manager + self._db_manager = db_manager + self._enable_db_fallback = enable_db_fallback + + # ==================== 实例信息 ==================== + self.instance_id = instance_id + self.symbol = symbol + self.config = instance_config + + # ==================== 独立状态 ==================== + self._position = Position( + symbol=symbol, + initial_shares=0, + initial_cost=0.0 + ) + + self._capital = Capital( + initial_cash=instance_config.get('initial_capital', 1000000.0) + ) + + self._risk_state = RiskState( + max_position_ratio=instance_config.get('max_position_ratio', 0.5), + stop_loss_ratio=instance_config.get('stop_loss_ratio', 0.05) + ) + + # ==================== 数据访问接口(直接实现) ==================== + + def get_klines( + self, + symbol: Optional[str] = None, + period: str = '1m', + last_n: Optional[int] = None, + start: Optional[pd.Timestamp] = None, + end: Optional[pd.Timestamp] = None + ) -> Optional[pd.DataFrame]: + """ + 获取K线数据(直接从缓存获取) + + 这是策略访问数据的主要方式 + + Args: + symbol: 标的代码,默认使用实例的 symbol + period: 周期 + last_n: 最近N条 + start: 开始时间 + end: 结束时间 + + Returns: + K线DataFrame,如果不存在返回None + """ + target_symbol = symbol or self.symbol + + # 1. 从缓存读取 + df = self._cache_manager.get_klines_range( + symbol=target_symbol, + period=period, + last_n=last_n, + start=start, + end=end + ) + + # 2. 缓存命中 + if df is not None and not df.empty: + if last_n is None or len(df) >= last_n: + return df + + # 3. 缓存未命中,尝试降级(可选) + if self._enable_db_fallback and self._db_manager: + logger.warning( + f"[{self.instance_id}] Cache miss: {target_symbol}_{period}, " + f"loading from database" + ) + df = self._load_from_database(target_symbol, period, last_n, start, end) + + # 加载后填充缓存 + if df is not None and not df.empty: + self._cache_manager.set_klines(target_symbol, period, {'klines': df}) + + return df + + # 4. 无降级或降级失败 + logger.warning( + f"[{self.instance_id}] No data available: {target_symbol}_{period}" + ) + return None + + def get_indicators( + self, + symbol: Optional[str] = None, + period: str = '1m', + indicator_type: str = 'MACD' + ) -> Optional[pd.DataFrame]: + """ + 获取指标数据 + + Args: + symbol: 标的代码,默认使用实例的 symbol + period: 周期 + indicator_type: 指标类型 + + Returns: + 指标DataFrame,如果不存在返回None + """ + target_symbol = symbol or self.symbol + return self._cache_manager.get_indicator(target_symbol, period, indicator_type) + + # ==================== 状态访问接口 ==================== + + def get_position(self) -> Position: + """获取持仓信息(独立状态)""" + return self._position + + def get_capital(self) -> Capital: + """获取资金信息(独立状态)""" + return self._capital + + def get_risk_state(self) -> RiskState: + """获取风险状态(独立状态)""" + return self._risk_state + + def update_position(self, shares: float, cost: float): + """更新持仓""" + self._position.update(shares, cost) + + def update_capital(self, cash_change: float): + """更新资金""" + self._capital.update(cash_change) + + # ==================== 私有方法 ==================== + + def _load_from_database( + self, + symbol: str, + period: str, + last_n: Optional[int], + start: Optional[pd.Timestamp], + end: Optional[pd.Timestamp] + ) -> Optional[pd.DataFrame]: + """ + 从数据库加载数据(私有方法) + + 降级逻辑封装在内部 + """ + if not self._db_manager: + return None + + try: + if last_n: + df = self._db_manager.load_klines_last_n(symbol, period, last_n) + else: + df = self._db_manager.load_klines_range(symbol, period, start, end) + return df + except Exception as e: + logger.error(f"[{self.instance_id}] Failed to load from database: {e}") + return None + + # ==================== 工具方法 ==================== + + def get_cache_info(self, symbol: Optional[str] = None, period: str = '1m') -> dict: + """ + 获取缓存信息(用于调试) + + Args: + symbol: 标的代码 + period: 周期 + + Returns: + 缓存信息字典 + """ + target_symbol = symbol or self.symbol + return self._cache_manager.get_cache_info(target_symbol, period) +``` + +### 2.2 关键点说明 + +**Q: 多个策略实例如何共享 cache_manager?** +```python +# 答案:传入同一个实例 + +# 服务器启动时 +cache_manager = CacheManager(...) # 单例 +db_manager = DBManager(...) # 单例 + +# 创建多个策略上下文 +context1 = StrategyContext( + cache_manager=cache_manager, # ← 共享实例 + db_manager=db_manager, # ← 共享实例 + instance_id='debug_000001', + ... +) + +context2 = StrategyContext( + cache_manager=cache_manager, # ← 同一个实例 + db_manager=db_manager, # ← 同一个实例 + instance_id='debug_600000', + ... +) + +# cache_manager 是共享的,多个 context 只是持有引用 +# 不会创建多个 cache_manager +``` + +**Q: 这样还算是"共享"吗?** +```python +# ✅ 是的!虽然每个 Context 都有 self._cache_manager +# 但它们都指向同一个对象 + +context1._cache_manager is context2._cache_manager # True + +# 类比:多个人共享同一个图书馆 +# 每个人都知道图书馆在哪(持有引用) +# 但图书馆只有一个(同一个实例) +``` + +--- + +## 3. StrategyManager 的变化 + +### 3.1 原设计 + +```python +class StrategyManager: + def __init__(self, config_dir, shared_services): + self.shared_services = shared_services + # ... + + def _create_strategy_instance(self, strategy_class, instance_config): + # 创建 Context,传入 SharedServices + context = StrategyContext( + shared_services=self.shared_services, # ← 传入中间层 + instance_id=instance_config['instance_id'], + instance_config=instance_config + ) + return strategy_class(context=context) +``` + +### 3.2 新设计 + +```python +class StrategyManager: + def __init__( + self, + config_dir: str, + cache_manager: CacheManager, + db_manager: Optional[DBManager] = None, + enable_db_fallback: bool = False + ): + """ + 初始化策略管理器 + + Args: + config_dir: 策略配置目录 + cache_manager: 缓存管理器(共享实例) + db_manager: 数据库管理器(共享实例,可选) + enable_db_fallback: 是否启用数据库降级 + """ + self.config_dir = config_dir + + # 直接持有共享资源 + self._cache_manager = cache_manager + self._db_manager = db_manager + self._enable_db_fallback = enable_db_fallback + + self.strategies = {} + self._load_strategies() + + def _create_strategy_instance( + self, + strategy_class: Type[BaseStrategy], + instance_config: dict + ) -> BaseStrategy: + """ + 创建策略实例 + + Args: + strategy_class: 策略类 + instance_config: 实例配置 + + Returns: + 策略实例 + """ + # 创建 Context,直接传入共享资源 + context = StrategyContext( + cache_manager=self._cache_manager, # ← 传入共享实例 + db_manager=self._db_manager, # ← 传入共享实例 + instance_id=instance_config['instance_id'], + symbol=instance_config['symbol'], + instance_config=instance_config, + enable_db_fallback=self._enable_db_fallback + ) + + # 创建策略实例 + strategy = strategy_class( + context=context, + **instance_config.get('params', {}) + ) + + return strategy +``` + +**变化**: +- ✅ 不再需要 SharedServices 参数 +- ✅ 直接接收 cache_manager 和 db_manager +- ✅ 创建 Context 时直接传入共享资源 + +--- + +## 4. 服务器启动代码 + +### 4.1 原设计(三层) + +```python +def start_server(host, port, config_path): + # 1. 初始化组件 + db_manager = DBManager(...) + cache_manager = CacheManager(...) + + # 2. 预加载 + preload_cache_data(db_manager, cache_manager, config) + + # 3. 创建 SharedServices(中间层) + shared_services = SharedServices( + cache_manager=cache_manager, + db_manager=db_manager, + enable_db_fallback=False + ) + + # 4. 创建 StrategyManager + strategy_manager = StrategyManager( + config_dir='config/strategies', + shared_services=shared_services # ← 传入中间层 + ) + + # ... +``` + +### 4.2 新设计(两层) + +```python +def start_server(host, port, config_path): + """启动服务器""" + + # 1. 加载配置 + config = load_config(config_path) + + # 2. 初始化数据库 + db_manager = DBManager(config['database']) + + # 3. 初始化缓存 + cache_manager = CacheManager(config['cache']) + + # 4. 预加载数据 + logger.info("Preloading data from database...") + preload_cache_data( + db_manager=db_manager, + cache_manager=cache_manager, + config=config + ) + logger.info("Preload completed") + + # 5. 创建策略管理器(直接传入共享资源) + strategy_manager = StrategyManager( + config_dir='config/strategies', + cache_manager=cache_manager, # ← 直接传入 + db_manager=db_manager, # ← 直接传入 + enable_db_fallback=config['cache'].get('fallback', {}).get('enabled', False) + ) + + logger.info(f"Loaded {len(strategy_manager.strategies)} strategy instances") + + # 6. 注册关闭钩子 + def on_shutdown(): + logger.info("Server shutting down...") + + # 可选:保存缓存到数据库 + if config['cache'].get('persist_on_shutdown', False): + save_cache_to_database(cache_manager, db_manager) + + # 关闭数据库连接 + db_manager.close() + logger.info("Shutdown completed") + + signal.signal(signal.SIGTERM, lambda s, f: on_shutdown()) + signal.signal(signal.SIGINT, lambda s, f: on_shutdown()) + + # 7. 创建 WebSocket 服务器 + ws_server = WebSocketServer( + strategy_manager=strategy_manager, + config=config['websocket'] + ) + + # 8. 启动服务器 + logger.info(f"Starting server on {host}:{port}") + ws_server.start(host, port) +``` + +**变化**: +- ✅ 不再创建 SharedServices +- ✅ 直接将 cache_manager 和 db_manager 传给 StrategyManager +- ✅ 代码更简洁 + +--- + +## 5. 策略使用示例 + +### 5.1 原设计 + +```python +class MAStrategy(BaseStrategy): + def compute(self, kline_data): + # 通过 context 访问数据 + # 但 context 内部需要委托给 _shared + history = self.context.get_klines( + symbol=self.context.symbol, + period='1m', + last_n=100 + ) + + # Context 内部实现: + # def get_klines(self, ...): + # return self._shared.get_klines(...) # 多一层 +``` + +### 5.2 新设计 + +```python +class MAStrategy(BaseStrategy): + def compute(self, kline_data): + # 直接通过 context 访问数据 + history = self.context.get_klines( + symbol=self.context.symbol, + period='1m', + last_n=100 + ) + + # Context 内部直接实现: + # def get_klines(self, ...): + # return self._cache_manager.get_klines_range(...) # 直接访问 + + # 使用简化:symbol 默认为 context.symbol + history = self.context.get_klines(period='1m', last_n=100) + + # 访问独立状态 + position = self.context.get_position() + capital = self.context.get_capital() + + # 计算信号 + if len(history) >= 100: + ma = history['close'].rolling(20).mean() + if history['close'].iloc[-1] > ma.iloc[-1]: + return 'BUY' + + return 'HOLD' +``` + +--- + +## 6. 对比总结 + +### 6.1 架构层次对比 + +| 方面 | 原设计(三层) | 新设计(两层) | +| ---------------- | ------------------------------------------- | ------------------------------- | +| **层次结构** | Strategy → Context → SharedServices → Cache | Strategy → Context → Cache | +| **中间层** | SharedServices | ❌ 无 | +| **Context 职责** | 持有独立状态 + 委托数据访问 | 持有独立状态 + 直接实现数据访问 | +| **代码调用** | `context._shared.get_klines()` | `context.get_klines()` | +| **复杂度** | 高(多一层) | 低(减少一层) | + +### 6.2 优缺点对比 + +#### 原设计(三层) + +**优点**: +- ✅ 明确区分"共享资源"和"独立状态" +- ✅ SharedServices 可以单独测试 + +**缺点**: +- ❌ 多了一层间接性 +- ❌ Context 需要委托所有数据访问方法 +- ❌ 代码冗余(SharedServices 和 Context 都有 get_klines) +- ❌ 理解成本高(为什么需要 SharedServices?) + +#### 新设计(两层) + +**优点**: +- ✅ **减少一层间接性** +- ✅ **Context 直接实现所有方法,无需委托** +- ✅ **代码更简洁直观** +- ✅ **符合"Context 是策略的唯一接口"理念** +- ✅ **共享机制依然存在(传入同一个实例)** + +**缺点**: +- ⚠️ Context 的职责略微增加(数据访问 + 状态管理) + - 但这是合理的!Context 本来就应该是策略的"环境" + +### 6.3 共享机制对比 + +两种设计的共享机制**本质相同**: + +| 方面 | 原设计 | 新设计 | +| ------------ | --------------------------- | --------------------------- | +| **共享方式** | 传入 SharedServices 实例 | 传入 cache_manager 实例 | +| **是否共享** | ✅ 是(SharedServices 单例) | ✅ 是(cache_manager 单例) | +| **内存占用** | 每个 Context 8 字节(引用) | 每个 Context 8 字节(引用) | +| **并发安全** | 取决于 CacheManager | 取决于 CacheManager | + +**结论**:新设计依然是共享的,只是少了一层包装。 + +--- + +## 7. 实现检查清单 + +### 7.1 需要修改的文件 + +| 文件 | 修改内容 | 说明 | +| --------------------------------- | ------------ | -------------------------------------- | +| `src/core/strategy_context.py` | 重新实现 | 直接提供数据访问方法 | +| `src/strategy_manager.py` | 修改参数 | 接收 cache_manager 而非 SharedServices | +| `src/qtrade_server.py` | 简化启动逻辑 | 不创建 SharedServices | +| ~~`src/core/shared_services.py`~~ | ❌ 删除 | 不再需要 | + +### 7.2 StrategyContext 需要实现的方法 + +**数据访问方法**: +```python +def get_klines(self, symbol, period, last_n, start, end) -> DataFrame +def get_indicators(self, symbol, period, indicator_type) -> DataFrame +def _load_from_database(self, ...) -> DataFrame # 私有 +``` + +**状态访问方法**: +```python +def get_position(self) -> Position +def get_capital(self) -> Capital +def get_risk_state(self) -> RiskState +def update_position(self, shares, cost) +def update_capital(self, cash_change) +``` + +**工具方法**: +```python +def get_cache_info(self, symbol, period) -> dict +``` + +### 7.3 StrategyManager 需要的修改 + +```python +# 修改构造函数签名 +def __init__( + self, + config_dir: str, + cache_manager: CacheManager, # 新增 + db_manager: DBManager = None, # 新增 + enable_db_fallback: bool = False # 新增 +): + # 不再接收 shared_services + pass + +# 修改创建 Context 的逻辑 +def _create_strategy_instance(self, strategy_class, instance_config): + context = StrategyContext( + cache_manager=self._cache_manager, # 直接传入 + db_manager=self._db_manager, + instance_id=instance_config['instance_id'], + symbol=instance_config['symbol'], + instance_config=instance_config, + enable_db_fallback=self._enable_db_fallback + ) + return strategy_class(context=context, ...) +``` + +--- + +## 8. 设计原则验证 + +### 8.1 是否违反设计原则? + +| 原则 | 原设计 | 新设计 | 说明 | +| ------------ | ------ | ------ | ----------------------------------------- | +| **单一职责** | ✅ 符合 | ✅ 符合 | Context 职责是"提供策略运行环境" | +| **接口隔离** | ✅ 符合 | ✅ 符合 | 策略只依赖 Context 接口 | +| **依赖倒置** | ✅ 符合 | ✅ 符合 | 依赖抽象(Context),不依赖实现 | +| **最少知识** | ⚠️ 一般 | ✅ 更好 | 策略只知道 Context,不知道 SharedServices | +| **简洁性** | ⚠️ 复杂 | ✅ 简洁 | 减少一层间接性 | + +### 8.2 Context 的职责是否过重? + +**Context 的职责**: +1. 提供数据访问接口(get_klines, get_indicators) +2. 管理独立状态(Position, Capital, RiskState) +3. 封装降级逻辑(可选) + +**分析**: +- ✅ 这些都是"策略运行环境"的一部分 +- ✅ 符合 Context 的定义 +- ✅ 职责清晰,内聚性高 + +**类比**: +``` +HttpRequest (Web 框架中的 Context) + ├── get_parameter() ← 获取请求参数 + ├── get_header() ← 获取请求头 + ├── get_session() ← 获取会话 + └── get_cookie() ← 获取 Cookie + +StrategyContext (交易系统中的 Context) + ├── get_klines() ← 获取K线数据 + ├── get_indicators() ← 获取指标数据 + ├── get_position() ← 获取持仓 + └── get_capital() ← 获取资金 +``` + +**结论**:Context 的职责不算过重,这是合理的封装。 + +--- + +## 9. 最终设计 + +### 9.1 架构图 + +``` +┌─────────────────────────────────────────┐ +│ QTradeServer │ +│ │ +│ 1. 初始化 cache_manager (单例) │ +│ 2. 初始化 db_manager (单例) │ +│ 3. 预加载数据 │ +│ 4. 创建 StrategyManager │ +│ ↓ │ +│ 传入 cache_manager, db_manager │ +└──────────────────┬──────────────────────┘ + │ + ↓ +┌─────────────────────────────────────────┐ +│ StrategyManager │ +│ │ +│ 持有: cache_manager, db_manager │ +│ │ +│ 创建多个 StrategyContext: │ +│ context1 = StrategyContext( │ +│ cache_manager, ← 共享实例 │ +│ db_manager, ← 共享实例 │ +│ instance_id='debug_000001' │ +│ ) │ +│ context2 = StrategyContext( │ +│ cache_manager, ← 同一个实例 │ +│ db_manager, ← 同一个实例 │ +│ instance_id='debug_600000' │ +│ ) │ +└──────────────────┬──────────────────────┘ + │ + ↓ +┌─────────────────────────────────────────┐ +│ StrategyContext │ +│ │ +│ 私有成员: │ +│ _cache_manager (共享引用) │ +│ _db_manager (共享引用) │ +│ │ +│ 独立状态: │ +│ _position │ +│ _capital │ +│ _risk_state │ +│ │ +│ 公开方法: │ +│ get_klines() ← 直接实现 │ +│ get_indicators() ← 直接实现 │ +│ get_position() │ +│ get_capital() │ +└──────────────────┬──────────────────────┘ + │ + ↓ +┌─────────────────────────────────────────┐ +│ Strategy │ +│ │ +│ def compute(self, kline_data): │ +│ history = self.context.get_klines()│ +│ position = self.context.get_position()│ +│ # ... │ +└─────────────────────────────────────────┘ +``` + +### 9.2 数据流 + +``` +Strategy 请求数据 + ↓ +context.get_klines(symbol, period, last_n) + ↓ +Context 内部逻辑: + 1. df = self._cache_manager.get_klines_range(...) + 2. if df is None and self._enable_db_fallback: + df = self._load_from_database(...) + self._cache_manager.set_klines(...) + 3. return df + ↓ +返回 DataFrame 给策略 +``` + +--- + +## 10. 总结 + +### 10.1 用户观点的正确性 + +✅ **用户观点完全正确**: + +1. **"不用封装这么多层"** + - ✅ 正确!SharedServices 是多余的中间层 + - ✅ 直接在 Context 上实现更简洁 + +2. **"可以直接变为 context 的方法"** + - ✅ 完全正确!Context 本来就应该是策略的唯一接口 + - ✅ 数据访问方法属于 Context 的职责范畴 + +3. **"是不是更好?"** + - ✅ 确实更好!代码更简洁、理解更容易、维护更方便 + +### 10.2 关键设计点 + +| 设计点 | 说明 | +| ------------ | -------------------------------------------------- | +| **共享机制** | 通过传入同一个实例实现共享,而非创建中间层 | +| **接口位置** | 数据访问方法直接在 Context 上实现 | +| **降级逻辑** | 封装在 Context 内部,对策略透明 | +| **独立状态** | 每个 Context 有独立的 Position、Capital、RiskState | +| **架构层次** | Strategy → Context → CacheManager(两层) | + +### 10.3 实现步骤 + +1. **重新实现 StrategyContext** + - 直接持有 cache_manager 和 db_manager(私有) + - 实现 get_klines()、get_indicators() 等方法 + - 封装降级逻辑 + +2. **修改 StrategyManager** + - 接收 cache_manager 和 db_manager 参数 + - 创建 Context 时直接传入共享资源 + +3. **简化 qtrade_server.py** + - 不创建 SharedServices + - 直接将共享资源传给 StrategyManager + +4. **删除 shared_services.py** + - 不再需要这个文件 + +--- + +**最终结论**: +新设计更简洁、更直观,减少了不必要的中间层,同时依然保持了共享机制和良好的封装性。这是一个更好的设计! diff --git a/docs/tech_designs/qtrade_server_cache_design.md b/docs/tech_designs/qtrade_server_cache_design.md new file mode 100644 index 0000000..7e71184 --- /dev/null +++ b/docs/tech_designs/qtrade_server_cache_design.md @@ -0,0 +1,1529 @@ +# QTrade Server 缓存设计方案 + +> **设计日期**: 2025-12-27 +> **设计目标**: 为 qtrade_server 添加缓存机制,支持历史数据预加载和实时数据追加 + +--- + +## 1. 设计背景 + +### 1.1 核心需求 + +**实盘场景的数据需求**: +1. **策略初始化**需要历史数据(如MA需要过去20条K线) +2. **实时交易**会不断收到新的K线数据 +3. **新数据需要追加**到缓存,保持数据连续性 +4. **策略计算**需要访问完整的历史+实时数据 + +**典型场景示例**: +``` +时间轴: + 2024-01-01 ──────────► 2024-12-26 ──────────► 实时 + └─────────────────┘ └──────────────────┘ + 预加载历史数据 实时追加新数据 + (供策略初始化) (持续更新缓存) + +策略需求: +- MA20策略:需要至少20条历史K线 +- MACD策略:需要至少34条历史K线 +- 实时计算:每次新K线到来,基于历史+新数据计算信号 +``` + +### 1.2 为什么需要缓存 + +**问题1:策略冷启动** +- 策略启动时没有历史数据,无法计算指标 +- 解决:预加载最近N条K线到缓存 + +**问题2:重复数据库查询** +- 每次新K线到来,都查询数据库获取历史数据 +- 解决:缓存历史数据,只需追加新数据 + +**问题3:性能瓶颈** +- 实盘每秒可能收到多个symbol的K线 +- 解决:内存缓存提供毫秒级访问速度 + +--- + +## 2. 架构设计 + +### 2.1 整体架构 + +``` +┌─────────────────────────────────────────────────────────┐ +│ QTrade Server 启动流程 │ +└─────────────────────────────────────────────────────────┘ + │ + ↓ + ┌───────────────────────────────┐ + │ 1. 加载配置文件 │ + │ - global_config.yaml │ + │ - strategies/*.yaml │ + └───────────────┬───────────────┘ + │ + ↓ + ┌───────────────────────────────┐ + │ 2. 初始化缓存管理器 │ + │ - CacheManager实例化 │ + │ - 配置缓存容量和策略 │ + └───────────────┬───────────────┘ + │ + ↓ + ┌───────────────────────────────┐ + │ 3. 预加载历史数据 │ + │ - 读取preload配置 │ + │ - 从数据库加载K线数据 │ + │ - 填充缓存 │ + └───────────────┬───────────────┘ + │ + ↓ + ┌───────────────────────────────┐ + │ 4. 初始化策略管理器 │ + │ - 创建策略实例 │ + │ - 注入缓存引用 │ + └───────────────┬───────────────┘ + │ + ↓ + ┌───────────────────────────────┐ + │ 5. 启动WebSocket服务器 │ + │ - 注册消息处理器 │ + │ - 开始接收实时数据 │ + └───────────────────────────────┘ + │ + ↓ +┌─────────────────────────────────────────────────────────┐ +│ 运行时数据流 │ +└─────────────────────────────────────────────────────────┘ + │ + ↓ + ┌───────────────────────────────┐ + │ 新K线数据到达 │ + │ {symbol, timestamp, OHLCV} │ + └───────────────┬───────────────┘ + │ + ↓ + ┌───────────────────────────────┐ + │ 追加到缓存 │ + │ CacheManager.append_kline() │ + └───────────────┬───────────────┘ + │ + ↓ + ┌───────────────────────────────┐ + │ 分发到策略 │ + │ StrategyManager.dispatch() │ + └───────────────┬───────────────┘ + │ + ↓ + ┌───────────────────────────────┐ + │ 策略从缓存读取数据 │ + │ CacheManager.get_klines() │ + └───────────────┬───────────────┘ + │ + ↓ + ┌───────────────────────────────┐ + │ 策略计算信号 │ + │ 返回交易信号 │ + └───────────────────────────────┘ +``` + +### 2.2 核心组件关系 + +``` +┌─────────────────┐ +│ QTradeServer │ +│ - cache_manager ◄────┐ +│ - strategy_mgr │ │ 共享引用 +└─────┬───────────┘ │ + │ │ + ↓ │ +┌─────────────────┐ │ +│ StrategyManager │ │ +│ - cache: ref ───┼────┘ +│ - instances[] │ +└─────┬───────────┘ + │ + ↓ +┌─────────────────┐ ┌──────────────┐ +│ DebugStrategy │────→│ CacheManager │ +│ - cache: ref │ │ - _cache{} │ +└─────────────────┘ └──────────────┘ +``` + +**组件职责**: + +| 组件 | 职责 | 缓存操作 | +| ------------------- | ---------------------------- | --------------------------- | +| **QTradeServer** | 服务器主控,负责初始化和协调 | 创建、预加载、追加新数据 | +| **CacheManager** | 纯缓存存储,Key-Value管理 | 存储、查询、统计 | +| **StrategyManager** | 策略实例管理和分发 | 读取缓存数据传给策略 | +| **Strategy实例** | 策略计算逻辑 | 通过StrategyManager访问缓存 | + +--- + +## 3. 配置文件设计 + +### 3.1 全局配置 (global_config.yaml) + +```yaml +# 全局策略配置 +# 适用于所有策略实例的全局参数 + +# 全局资金配置 +global: + total_capital: 1000000 + max_position_ratio: 0.8 + +# 全局风控配置 +risk: + max_drawdown: 0.2 + max_daily_loss: 0.05 + +# ==================== 缓存配置 ==================== +cache: + enabled: true # 是否启用缓存 + max_memory_mb: 2048 # 最大内存限制 (2GB) + + # 预加载配置 + preload: + enabled: true # 是否启用预加载 + time_range: "3M" # 预加载时间范围 (3个月) + # 格式:数字+单位 (D=天, M=月, Y=年) + # 示例:7D, 1M, 3M, 1Y + + periods: # 预加载的周期列表 + - "1m" # 1分钟K线 + - "5m" # 5分钟K线 + - "15m" # 15分钟K线 + - "1d" # 日K线 + + # 预加载数据源配置 + source: + type: "database" # 数据源类型 (database, csv, api) + database: + host: "localhost" + port: 3306 + database: "qtrade" + user: "root" + password: "password" + + # 缓存更新策略 + update: + auto_append: true # 是否自动追加新数据到缓存 + max_cache_rows: 1000 # 单个symbol-period最大缓存行数 + # 超过后自动删除最旧数据 + trim_strategy: "rolling" # 裁剪策略:rolling/fixed + # rolling: 删除最旧数据保持固定行数 + # fixed: 超过后清空重新加载 + +# 策略实例配置目录 +strategy_configs_dir: "config/strategies" +``` + +### 3.2 策略实例配置 (strategies/xxx.yaml) + +策略实例配置**不需要**单独配置缓存,统一使用全局配置: + +```yaml +# 策略实例配置: debug_000001 +instance_id: "debug_000001" +symbol: "000001.SZ" +strategy_class: "DebugStrategy" +capital: 100000 + +# 策略参数 +params: + print_every: 1 + simulate_signal: false + + # 策略可以声明自己需要的历史数据长度(可选) + required_history_bars: 20 # 需要至少20条历史K线 + required_periods: # 需要的周期数据 + - "1m" + - "1d" + +# 风控参数 +risk: + max_position_ratio: 0.8 + stop_loss: 0.05 +``` + +**说明**: +- `required_history_bars`: 策略声明自己需要的最小历史数据量 +- `required_periods`: 策略声明自己需要哪些周期的数据 +- 这些参数用于验证预加载配置是否满足策略需求 + +### 3.3 配置示例:不同场景 + +**场景1:开发测试(小数据量)** +```yaml +cache: + preload: + time_range: "7D" # 只预加载7天数据 + periods: ["1d"] # 只预加载日K +``` + +**场景2:回测(大数据量)** +```yaml +cache: + preload: + time_range: "1Y" # 预加载1年数据 + periods: ["1m", "5m", "15m", "1d"] +``` + +**场景3:生产实盘(平衡)** +```yaml +cache: + preload: + time_range: "3M" # 预加载3个月 + periods: ["1m", "1d"] # 分钟线+日线 + update: + max_cache_rows: 1000 # 限制内存 + trim_strategy: "rolling" # 滚动更新 +``` + +--- + +## 4. 代码结构设计 + +### 4.1 文件组织 + +``` +src/ +├── qtrade_server.py # 服务器主程序(需要修改) +│ └── 添加缓存初始化和预加载逻辑 +│ +├── cache/ +│ └── cache_manager.py # 缓存管理器(复用现有,可能需要扩展) +│ └── 添加 append_kline() 方法 +│ +├── strategy_manager.py # 策略管理器(需要修改) +│ └── 注入缓存引用,策略可访问缓存 +│ +└── strategies/ + └── debug_strategy.py # 策略实现(需要修改) + └── 通过缓存获取历史数据 +``` + +### 4.2 qtrade_server.py 架构 + +```python +""" +QTrade Strategy Server - 带缓存支持 + +接收客户端发送的K线数据,通过StrategyManager分发到多个策略实例 +支持历史数据预加载和实时数据追加 +""" + +# ==================== 全局变量 ==================== +strategy_manager: Optional[StrategyManager] = None +cache_manager: Optional[CacheManager] = None +config: Optional[dict] = None + +# ==================== 初始化流程 ==================== + +def load_config(config_path: str = "config/global_config.yaml") -> dict: + """ + 加载全局配置 + + Returns: + 配置字典 + """ + # 读取YAML文件 + # 验证必需字段 + # 返回配置字典 + +def initialize_cache_manager(config: dict) -> CacheManager: + """ + 初始化缓存管理器 + + Args: + config: 全局配置字典 + + Returns: + CacheManager实例 + """ + # 提取cache配置 + # 创建CacheManager实例 + # 返回 + +def preload_cache_data(cache_manager: CacheManager, config: dict): + """ + 预加载历史数据到缓存 + + 根据配置从数据库加载历史K线数据并填充缓存 + + Args: + cache_manager: 缓存管理器实例 + config: 全局配置字典 + + 流程: + 1. 解析preload配置 (time_range, periods) + 2. 计算时间范围 (end_date=today, start_date=today-time_range) + 3. 遍历所有策略实例的symbol + 4. 对每个(symbol, period)组合: + - 从数据库加载K线数据 + - 调用 cache_manager.set_klines() + 5. 打印预加载统计信息 + """ + +def initialize_strategy_manager( + config_dir: str, + cache_manager: CacheManager +) -> StrategyManager: + """ + 初始化策略管理器 + + Args: + config_dir: 策略配置文件目录 + cache_manager: 缓存管理器(注入到策略) + + Returns: + StrategyManager实例 + """ + # 创建StrategyManager,传入cache_manager + # 初始化策略实例 + # 返回 + +# ==================== 消息处理 ==================== + +async def handle_kline_data(message: dict) -> dict: + """ + 处理单条K线数据 + + 流程: + 1. 提取K线数据 (symbol, timestamp, OHLCV) + 2. 追加到缓存: cache_manager.append_kline() + 3. 分发到策略: strategy_manager.dispatch_kline() + 4. 返回交易信号 + """ + +async def handle_kline_batch(message: dict) -> dict: + """ + 处理批量K线数据 + + 流程: + 1. 遍历batch_data + 2. 对每条K线: + - 追加到缓存 + - 分发到策略 + 3. 聚合所有信号返回 + """ + +# ==================== 启动服务器 ==================== + +def start_server( + host: str = "0.0.0.0", + port: int = 8000, + config_path: str = "config/global_config.yaml" +): + """ + 启动服务器 + + 完整流程: + 1. 加载配置: load_config() + 2. 初始化缓存: initialize_cache_manager() + 3. 预加载数据: preload_cache_data() + 4. 初始化策略: initialize_strategy_manager() + 5. 创建WebSocket服务器 + 6. 注册消息处理器 + 7. 启动服务器 + """ +``` + +### 4.3 CacheManager 扩展 + +**现有方法**: +- `get_klines()`: 获取缓存数据 +- `set_klines()`: 设置缓存数据 +- `get_indicator()`: 获取指标数据 +- `set_indicator()`: 设置指标数据 + +**需要新增的方法**: + +```python +class CacheManager: + + def append_kline( + self, + symbol: str, + period: str, + new_kline: pd.Series, + max_rows: Optional[int] = None + ) -> bool: + """ + 追加新的K线数据到缓存 + + Args: + symbol: 标的代码 + period: 周期 + new_kline: 新K线数据 (Series with timestamp as index) + max_rows: 最大保留行数,超过则删除最旧数据 + + Returns: + 是否追加成功 + + 流程: + 1. 检查缓存是否存在该key + 2. 如果不存在,创建新的DataFrame + 3. 如果存在,追加到DataFrame末尾 + 4. 如果超过max_rows,删除最旧的行 + 5. 更新meta信息 (time_range) + 6. 返回成功/失败 + + 示例: + new_kline = pd.Series({ + 'open': 10.5, + 'high': 10.8, + 'low': 10.3, + 'close': 10.6, + 'volume': 1000000 + }, name=pd.Timestamp('2024-12-27 09:30:00')) + + cache_manager.append_kline('000001.SZ', '1m', new_kline, max_rows=1000) + """ + + def get_klines_range( + self, + symbol: str, + period: str, + start: Optional[pd.Timestamp] = None, + end: Optional[pd.Timestamp] = None, + last_n: Optional[int] = None + ) -> Optional[pd.DataFrame]: + """ + 获取指定时间范围的K线数据 + + Args: + symbol: 标的代码 + period: 周期 + start: 开始时间(可选) + end: 结束时间(可选) + last_n: 获取最近N条(可选,与start/end互斥) + + Returns: + 符合条件的K线DataFrame或None + + 示例: + # 获取最近20条 + df = cache_manager.get_klines_range('000001.SZ', '1m', last_n=20) + + # 获取指定时间范围 + df = cache_manager.get_klines_range( + '000001.SZ', '1m', + start=pd.Timestamp('2024-12-01'), + end=pd.Timestamp('2024-12-27') + ) + """ + + def get_cache_info( + self, + symbol: str, + period: str + ) -> Optional[Dict[str, Any]]: + """ + 获取缓存信息(不返回数据,只返回元数据) + + Args: + symbol: 标的代码 + period: 周期 + + Returns: + 缓存信息字典: + { + 'exists': True/False, + 'row_count': 1000, + 'time_range': (start_ts, end_ts), + 'memory_mb': 2.5, + 'last_update': timestamp + } + """ +``` + +### 4.4 StrategyManager 修改 + +```python +class StrategyManager: + """ + 策略管理器 - 支持缓存注入 + """ + + def __init__( + self, + config_dir: str = "config/strategies", + cache_manager: Optional[CacheManager] = None # 新增参数 + ): + """ + 初始化策略管理器 + + Args: + config_dir: 策略配置文件目录 + cache_manager: 缓存管理器实例(注入) + """ + self.config_dir = Path(config_dir) + self.cache_manager = cache_manager # 保存引用 + + # ... 其他初始化 + + def _create_strategy_instance( + self, + strategy_class, + params: dict + ): + """ + 创建策略实例 + + Args: + strategy_class: 策略类 + params: 策略参数 + + 流程: + 1. 创建策略实例 + 2. 注入缓存引用: strategy.set_cache(self.cache_manager) + 3. 返回实例 + """ + + def dispatch_kline( + self, + symbol: str, + kline_data: Dict + ) -> List[Dict]: + """ + 分发K线数据到策略(修改版) + + 流程: + 1. 查找symbol对应的策略实例 + 2. 对每个策略实例: + - 策略可以从cache_manager读取历史数据 + - 调用 strategy.compute(kline_data) + - 收集信号 + 3. 返回所有信号 + """ +``` + +### 4.5 Strategy 基类设计 + +```python +class BaseStrategy: + """ + 策略基类 - 支持缓存访问 + """ + + def __init__(self, **params): + self.params = params + self.cache_manager: Optional[CacheManager] = None + + def set_cache(self, cache_manager: CacheManager): + """ + 注入缓存管理器 + + Args: + cache_manager: 缓存管理器实例 + """ + self.cache_manager = cache_manager + + def get_history_klines( + self, + symbol: str, + period: str, + last_n: int + ) -> Optional[pd.DataFrame]: + """ + 获取历史K线数据 + + Args: + symbol: 标的代码 + period: 周期 + last_n: 最近N条 + + Returns: + 历史K线DataFrame + + 示例: + # 策略内部使用 + history = self.get_history_klines('000001.SZ', '1m', 20) + if history is not None: + ma20 = history['close'].mean() + """ + if self.cache_manager: + return self.cache_manager.get_klines_range( + symbol, period, last_n=last_n + ) + return None + + def compute(self, kline_data: Dict) -> Optional[Dict]: + """ + 策略计算方法(子类实现) + + 子类可以使用 self.get_history_klines() 获取历史数据 + """ + raise NotImplementedError +``` + +--- + +## 5. 数据流设计 + +### 5.1 预加载流程 + +``` +启动时间:Server启动 +数据源:MySQL数据库 + +┌─────────────────────────────────────────────────────────┐ +│ 预加载流程 │ +└─────────────────────────────────────────────────────────┘ + +1. 读取配置 + ↓ + preload.time_range = "3M" + preload.periods = ["1m", "1d"] + +2. 收集需要预加载的symbols + ↓ + 遍历所有策略配置文件 + 提取symbol列表: ["000001.SZ", "600000.SH"] + +3. 计算时间范围 + ↓ + today = 2024-12-27 + start_date = today - 3M = 2024-09-27 + +4. 批量加载数据 + ↓ + For each symbol in ["000001.SZ", "600000.SH"]: + For each period in ["1m", "1d"]: + ┌─────────────────────────────────────┐ + │ SQL查询: │ + │ SELECT * FROM klines_1m │ + │ WHERE symbol = '000001.SZ' │ + │ AND timestamp >= '2024-09-27' │ + │ AND timestamp <= '2024-12-27' │ + │ ORDER BY timestamp ASC │ + └─────────────────────────────────────┘ + ↓ + 得到DataFrame (shape: ~13000 rows × 6 cols) + ↓ + cache_manager.set_klines( + symbol='000001.SZ', + period='1m', + data={'klines': df} + ) + ↓ + 日志: "✓ Preloaded 000001.SZ_1m: 13000 rows" + +5. 预加载完成 + ↓ + 统计信息: + - 总计加载: 4 个 (symbol, period) 组合 + - 总行数: ~50000 rows + - 内存占用: ~80 MB + - 耗时: 2.5s +``` + +### 5.2 实时追加流程 + +``` +运行时:每次收到新K线 + +┌─────────────────────────────────────────────────────────┐ +│ 实时数据追加流程 │ +└─────────────────────────────────────────────────────────┘ + +1. WebSocket收到消息 + ↓ + { + "msg_type": "KLINE_DATA", + "symbol": "000001.SZ", + "period": "1m", + "kline_time": "2024-12-27 14:30:00", + "data": { + "open": 10.5, + "high": 10.8, + "low": 10.3, + "close": 10.6, + "volume": 1000000 + } + } + +2. 解析并构造Series + ↓ + new_kline = pd.Series({ + 'open': 10.5, + 'high': 10.8, + 'low': 10.3, + 'close': 10.6, + 'volume': 1000000 + }, name=pd.Timestamp('2024-12-27 14:30:00')) + +3. 追加到缓存 + ↓ + cache_manager.append_kline( + symbol='000001.SZ', + period='1m', + new_kline=new_kline, + max_rows=1000 # 限制缓存大小 + ) + ↓ + 缓存内部操作: + - 获取现有DataFrame (shape: 999 × 6) + - 追加新行 (shape: 1000 × 6) + - 如果超过max_rows,删除最旧的1行 + - 更新meta信息 + +4. 分发到策略 + ↓ + strategy_manager.dispatch_kline( + symbol='000001.SZ', + kline_data=kline_data + ) + ↓ + 策略内部: + - 从缓存获取历史数据: + history = cache_manager.get_klines_range('000001.SZ', '1m', last_n=20) + - 计算指标: ma20 = history['close'].mean() + - 生成信号: return {'action': 'BUY', ...} + +5. 返回信号 + ↓ + 返回给客户端 +``` + +### 5.3 缓存滚动更新示例 + +``` +时间轴示例(max_rows=5): + +初始状态: +┌──────────────┬───────┬───────┬───────┐ +│ Timestamp │ Close │ ... │ │ +├──────────────┼───────┼───────┼───────┤ +│ 09:30:00 │ 10.0 │ ... │ 行1 │ +│ 09:31:00 │ 10.1 │ ... │ 行2 │ +│ 09:32:00 │ 10.2 │ ... │ 行3 │ +│ 09:33:00 │ 10.3 │ ... │ 行4 │ +│ 09:34:00 │ 10.4 │ ... │ 行5 │ ← 最新 +└──────────────┴───────┴───────┴───────┘ +缓存大小: 5 rows + +新K线到达:09:35:00, close=10.5 +↓ +追加并滚动: +┌──────────────┬───────┬───────┬───────┐ +│ Timestamp │ Close │ ... │ │ +├──────────────┼───────┼───────┼───────┤ +│ 09:31:00 │ 10.1 │ ... │ 行2 │ ← 删除行1 +│ 09:32:00 │ 10.2 │ ... │ 行3 │ +│ 09:33:00 │ 10.3 │ ... │ 行4 │ +│ 09:34:00 │ 10.4 │ ... │ 行5 │ +│ 09:35:00 │ 10.5 │ ... │ 行6 │ ← 新增 +└──────────────┴───────┴───────┴───────┘ +缓存大小: 仍然是5 rows + +策略使用: +df = cache_manager.get_klines_range('000001.SZ', '1m', last_n=5) +# 返回最近5条:09:31 ~ 09:35 +ma5 = df['close'].mean() # (10.1+10.2+10.3+10.4+10.5)/5 = 10.3 +``` + +--- + +## 6. 核心实现细节 + +### 6.1 时间范围解析 + +```python +def parse_time_range(time_range_str: str) -> timedelta: + """ + 解析时间范围字符串 + + 格式:数字+单位 + - D: 天 (Day) + - M: 月 (Month, 按30天计算) + - Y: 年 (Year, 按365天计算) + + 示例: + "7D" -> timedelta(days=7) + "3M" -> timedelta(days=90) + "1Y" -> timedelta(days=365) + """ + import re + + match = re.match(r'(\d+)([DMY])', time_range_str) + if not match: + raise ValueError(f"Invalid time_range format: {time_range_str}") + + value, unit = match.groups() + value = int(value) + + if unit == 'D': + return timedelta(days=value) + elif unit == 'M': + return timedelta(days=value * 30) + elif unit == 'Y': + return timedelta(days=value * 365) +``` + +### 6.2 Symbol列表收集 + +```python +def collect_symbols_from_configs(config_dir: str) -> List[str]: + """ + 从所有策略配置文件中收集symbol列表 + + Args: + config_dir: 策略配置目录 + + Returns: + 去重后的symbol列表 + """ + symbols = set() + + for config_file in Path(config_dir).glob("*.yaml"): + with open(config_file) as f: + config = yaml.safe_load(f) + symbol = config.get('symbol') + if symbol: + symbols.add(symbol) + + return list(symbols) +``` + +### 6.3 数据库批量加载 + +```python +def load_klines_from_db( + db_manager: DBManager, + symbol: str, + period: str, + start_date: datetime, + end_date: datetime +) -> pd.DataFrame: + """ + 从数据库批量加载K线数据 + + Args: + db_manager: 数据库管理器 + symbol: 标的代码 + period: 周期 + start_date: 开始日期 + end_date: 结束日期 + + Returns: + K线DataFrame + """ + # 构造SQL查询 + table_name = f"klines_{period}" + query = f""" + SELECT timestamp, open, high, low, close, volume + FROM {table_name} + WHERE symbol = %s + AND timestamp >= %s + AND timestamp <= %s + ORDER BY timestamp ASC + """ + + # 执行查询 + df = db_manager.query_to_dataframe( + query, + params=(symbol, start_date, end_date) + ) + + # 设置索引 + if not df.empty: + df.set_index('timestamp', inplace=True) + + return df +``` + +### 6.4 追加数据实现 + +```python +def append_kline( + self, + symbol: str, + period: str, + new_kline: pd.Series, + max_rows: Optional[int] = None +) -> bool: + """ + 追加新K线到缓存(详细实现) + """ + key = self._make_key(symbol, period) + + # 情况1:缓存不存在,创建新缓存 + if key not in self._cache: + df = pd.DataFrame([new_kline]) + self.set_klines(symbol, period, {'klines': df}) + return True + + # 情况2:缓存存在,追加数据 + cached = self._cache[key] + df = cached.get('klines') + + if df is None or df.empty: + df = pd.DataFrame([new_kline]) + else: + # 检查是否重复 + if new_kline.name in df.index: + logger.warning(f"Duplicate timestamp: {new_kline.name}") + return False + + # 追加新行 + df = pd.concat([df, pd.DataFrame([new_kline])], axis=0) + + # 如果超过max_rows,删除最旧的行 + if max_rows and len(df) > max_rows: + df = df.iloc[-max_rows:] + + # 更新缓存 + cached['klines'] = df + cached['meta']['time_range'] = (df.index.min(), df.index.max()) + + return True +``` + +--- + +## 7. 性能优化 + +### 7.1 预加载优化 + +**问题**:预加载大量数据可能导致启动慢 + +**优化方案**: + +1. **并行加载**: + ```python + # 使用线程池并行加载多个symbol + from concurrent.futures import ThreadPoolExecutor + + with ThreadPoolExecutor(max_workers=4) as executor: + futures = [] + for symbol in symbols: + for period in periods: + future = executor.submit( + load_klines_from_db, + db_manager, symbol, period, start_date, end_date + ) + futures.append((symbol, period, future)) + + for symbol, period, future in futures: + df = future.result() + cache_manager.set_klines(symbol, period, {'klines': df}) + ``` + +2. **分批加载**: + ```python + # 先加载必需的周期(1d),后台异步加载其他周期(1m) + essential_periods = ['1d'] + optional_periods = ['1m', '5m'] + + # 同步加载必需周期 + for period in essential_periods: + load_and_cache(period) + + # 异步加载可选周期 + threading.Thread(target=load_optional_periods, daemon=True).start() + ``` + +3. **渐进式加载**: + ```python + # 先加载最近1个月,后台加载更早的数据 + load_recent_data(time_range='1M') # 快速启动 + load_historical_data(time_range='3M') # 后台加载 + ``` + +### 7.2 内存管理 + +**策略1:限制单个缓存大小** +```yaml +cache: + update: + max_cache_rows: 1000 # 每个symbol-period最多1000行 +``` + +**策略2:LRU淘汰机制** +```python +# 如果总内存超过限制,淘汰最久未使用的缓存 +if cache_manager.get_stats()['memory_mb'] > max_memory_mb: + cache_manager.evict_lru() +``` + +**策略3:按需加载** +```python +# 策略首次访问某个period时才加载 +def get_klines_lazy(symbol, period): + if not cache_manager.has(symbol, period): + data = load_from_db(symbol, period) + cache_manager.set_klines(symbol, period, data) + return cache_manager.get_klines(symbol, period) +``` + +### 7.3 并发访问 + +**问题**:多个策略并发读取缓存 + +**解决方案**: + +```python +import threading + +class CacheManager: + def __init__(self, config): + self._cache = {} + self._lock = threading.RLock() # 可重入锁 + + def get_klines(self, symbol, period): + with self._lock: + # 读操作加锁(保证数据一致性) + return self._cache.get(key) + + def append_kline(self, symbol, period, new_kline): + with self._lock: + # 写操作加锁 + self._cache[key]['klines'] = updated_df +``` + +--- + +## 8. 错误处理 + +### 8.1 预加载失败处理 + +```python +def preload_cache_data(cache_manager, config): + """预加载数据,带错误处理""" + + try: + symbols = collect_symbols() + periods = config['cache']['preload']['periods'] + + success_count = 0 + fail_count = 0 + + for symbol in symbols: + for period in periods: + try: + # 尝试加载数据 + df = load_klines_from_db(...) + cache_manager.set_klines(symbol, period, {'klines': df}) + success_count += 1 + + except Exception as e: + logger.error(f"Failed to preload {symbol}_{period}: {e}") + fail_count += 1 + # 继续加载其他数据,不中断 + continue + + logger.info(f"Preload completed: {success_count} success, {fail_count} failed") + + # 如果全部失败,警告但不中断启动 + if success_count == 0: + logger.warning("No data preloaded, server will start with empty cache") + + except Exception as e: + logger.error(f"Preload failed: {e}") + # 预加载失败不影响服务器启动 + logger.warning("Server will start with empty cache") +``` + +### 8.2 追加数据失败处理 + +```python +async def handle_kline_data(message: dict) -> dict: + """处理K线,带容错""" + + # 1. 尝试追加到缓存 + try: + new_kline = construct_kline(message) + cache_manager.append_kline(symbol, period, new_kline) + except Exception as e: + logger.error(f"Failed to append to cache: {e}") + # 缓存失败不影响策略计算 + + # 2. 分发到策略(即使缓存失败也继续) + signals = strategy_manager.dispatch_kline(symbol, kline_data) + + return {"msg_type": "TRADE_SIGNALS", "signals": signals} +``` + +### 8.3 缓存缺失降级 + +```python +class BaseStrategy: + + def get_history_klines(self, symbol, period, last_n): + """获取历史数据,带降级""" + + # 1. 尝试从缓存读取 + if self.cache_manager: + df = self.cache_manager.get_klines_range(symbol, period, last_n=last_n) + if df is not None: + return df + + # 2. 缓存未命中,从数据库加载 + logger.warning(f"Cache miss for {symbol}_{period}, loading from database") + df = load_from_database(symbol, period, last_n) + + # 3. 加载后填充缓存 + if df is not None and self.cache_manager: + self.cache_manager.set_klines(symbol, period, {'klines': df}) + + return df +``` + +--- + +## 9. 测试验证 + +### 9.1 单元测试 + +```python +# tests/test_cache_manager.py + +def test_append_kline(): + """测试追加K线""" + cache = CacheManager({'cache': {'enabled': True}}) + + # 追加第一条 + kline1 = pd.Series({'close': 10.0}, name=pd.Timestamp('2024-01-01')) + assert cache.append_kline('000001.SZ', '1d', kline1) + + # 追加第二条 + kline2 = pd.Series({'close': 10.5}, name=pd.Timestamp('2024-01-02')) + assert cache.append_kline('000001.SZ', '1d', kline2) + + # 验证缓存 + df = cache.get_klines('000001.SZ', '1d') + assert len(df) == 2 + assert df.iloc[-1]['close'] == 10.5 + +def test_rolling_cache(): + """测试滚动缓存""" + cache = CacheManager({'cache': {'enabled': True}}) + + # 追加5条数据,max_rows=3 + for i in range(5): + kline = pd.Series({'close': 10.0+i}, name=pd.Timestamp(f'2024-01-0{i+1}')) + cache.append_kline('000001.SZ', '1d', kline, max_rows=3) + + # 验证只保留最新3条 + df = cache.get_klines('000001.SZ', '1d') + assert len(df) == 3 + assert df.iloc[0]['close'] == 12.0 # 2024-01-03 + assert df.iloc[-1]['close'] == 14.0 # 2024-01-05 +``` + +### 9.2 集成测试 + +```python +# tests/test_qtrade_server_cache.py + +def test_preload_and_realtime(): + """测试预加载+实时追加流程""" + + # 1. 启动服务器(预加载) + config = load_config('config/global_config.yaml') + cache_manager = initialize_cache_manager(config) + preload_cache_data(cache_manager, config) + + # 验证预加载 + df = cache_manager.get_klines('000001.SZ', '1d') + assert df is not None + assert len(df) > 0 + initial_count = len(df) + + # 2. 模拟实时数据到达 + new_kline = pd.Series({ + 'open': 10.5, 'high': 10.8, 'low': 10.3, + 'close': 10.6, 'volume': 1000000 + }, name=pd.Timestamp('2024-12-27 14:30:00')) + + cache_manager.append_kline('000001.SZ', '1m', new_kline) + + # 3. 验证追加成功 + df_updated = cache_manager.get_klines('000001.SZ', '1m') + assert len(df_updated) == initial_count + 1 + assert df_updated.iloc[-1]['close'] == 10.6 +``` + +### 9.3 性能测试 + +```python +def test_preload_performance(): + """测试预加载性能""" + import time + + start = time.time() + + # 预加载3个月数据,2个symbol,2个周期 + # 预期数据量:~50000行 + preload_cache_data(cache_manager, config) + + elapsed = time.time() - start + + # 验证性能指标 + assert elapsed < 5.0 # 应该在5秒内完成 + + stats = cache_manager.get_stats() + assert stats['memory_mb'] < 100 # 内存占用应该<100MB + +def test_append_performance(): + """测试追加性能""" + import time + + # 模拟1000次实时追加 + start = time.time() + + for i in range(1000): + kline = create_random_kline() + cache_manager.append_kline('000001.SZ', '1m', kline) + + elapsed = time.time() - start + + # 验证性能:1000次追加应该<1秒 + assert elapsed < 1.0 + assert elapsed / 1000 < 0.001 # 平均每次<1ms +``` + +--- + +## 10. 监控和日志 + +### 10.1 关键日志 + +```python +# 预加载阶段 +logger.info("=" * 60) +logger.info("Starting cache preload...") +logger.info(f" Time range: {start_date} ~ {end_date}") +logger.info(f" Symbols: {len(symbols)}") +logger.info(f" Periods: {periods}") +logger.info("=" * 60) + +# 每个数据加载 +logger.info(f"✓ Preloaded {symbol}_{period}: {len(df)} rows, {df.memory_usage().sum()/1e6:.2f} MB") + +# 预加载完成 +logger.info("=" * 60) +logger.info("Cache preload completed:") +logger.info(f" Success: {success_count}/{total_count}") +logger.info(f" Total rows: {total_rows}") +logger.info(f" Memory usage: {total_memory_mb:.2f} MB") +logger.info(f" Time elapsed: {elapsed:.2f}s") +logger.info("=" * 60) + +# 实时追加 +logger.debug(f"Appended to cache: {symbol}_{period} @ {timestamp}") + +# 缓存命中/未命中 +logger.debug(f"Cache hit: {symbol}_{period}") +logger.warning(f"Cache miss: {symbol}_{period}, loading from database") +``` + +### 10.2 监控指标 + +```python +def get_cache_metrics() -> Dict[str, Any]: + """获取缓存监控指标""" + stats = cache_manager.get_stats() + + return { + 'cache_enabled': stats['enabled'], + 'cache_size': stats['size'], # 缓存项数量 + 'memory_mb': stats['memory_mb'], # 内存占用 + 'memory_usage_pct': stats['memory_mb'] / max_memory_mb * 100, + 'hit_rate': calculate_hit_rate(), # 缓存命中率 + 'symbols_cached': len(stats['symbols']), + 'total_rows': sum_all_rows(), + } + +# 定期打印监控信息 +def log_cache_stats(): + metrics = get_cache_metrics() + logger.info(f"Cache Stats: " + f"size={metrics['cache_size']}, " + f"memory={metrics['memory_mb']:.2f}MB " + f"({metrics['memory_usage_pct']:.1f}%), " + f"hit_rate={metrics['hit_rate']:.2f}%") +``` + +--- + +## 11. 总结 + +### 11.1 关键设计决策 + +| 决策点 | 方案 | 理由 | +| -------------- | ------------------- | -------------------------------------- | +| **缓存实现** | 复用 CacheManager | 避免重复造轮,保持架构统一 | +| **配置位置** | global_config.yaml | 全局配置,所有策略共享 | +| **预加载时机** | Server启动时 | 确保策略初始化时有数据可用 | +| **数据追加** | 实时追加到缓存 | 保持数据连续性,策略始终能访问最新数据 | +| **缓存注入** | 通过StrategyManager | 解耦策略和缓存,便于测试和替换 | +| **滚动策略** | 限制max_rows | 控制内存占用,避免无限增长 | + +### 11.2 实现步骤 + +**Phase 1: 基础框架**(1-2天) +1. ✅ 设计配置文件结构 +2. ⬜ 扩展 CacheManager(append_kline, get_klines_range) +3. ⬜ 修改 qtrade_server 初始化流程 +4. ⬜ 实现预加载逻辑 + +**Phase 2: 实时追加**(1天) +1. ⬜ 修改 handle_kline_data 添加追加逻辑 +2. ⬜ 测试追加功能 +3. ⬜ 实现滚动更新 + +**Phase 3: 策略集成**(1天) +1. ⬜ 修改 StrategyManager 注入缓存 +2. ⬜ 修改策略基类添加缓存访问接口 +3. ⬜ 更新 DebugStrategy 演示缓存使用 + +**Phase 4: 优化和测试**(1-2天) +1. ⬜ 性能优化(并行加载) +2. ⬜ 错误处理和降级 +3. ⬜ 单元测试和集成测试 +4. ⬜ 监控和日志 + +### 11.3 验收标准 + +**功能验收**: +- ✅ 服务器启动时成功预加载历史数据 +- ✅ 实时K线数据能正确追加到缓存 +- ✅ 策略能从缓存读取历史数据 +- ✅ 缓存滚动更新正常工作 +- ✅ 配置文件能正确控制预加载行为 + +**性能验收**: +- ✅ 预加载3个月数据(2 symbols × 2 periods)< 5秒 +- ✅ 单次追加操作 < 1ms +- ✅ 内存占用符合配置限制 +- ✅ 缓存命中率 > 95% + +**稳定性验收**: +- ✅ 预加载失败不影响服务器启动 +- ✅ 追加失败不影响策略计算 +- ✅ 并发读写无数据竞争 +- ✅ 长时间运行内存不泄漏 + +--- + +## 12. 附录 + +### 12.1 配置示例完整版 + +```yaml +# config/global_config.yaml - 生产环境配置 + +# 全局资金配置 +global: + total_capital: 1000000 + max_position_ratio: 0.8 + +# 全局风控配置 +risk: + max_drawdown: 0.2 + max_daily_loss: 0.05 + +# ==================== 缓存配置 ==================== +cache: + # 基础配置 + enabled: true + max_memory_mb: 2048 # 最大2GB内存 + + # 预加载配置 + preload: + enabled: true + time_range: "3M" # 预加载3个月 + periods: + - "1m" # 1分钟线 + - "5m" # 5分钟线 + - "1d" # 日线 + + # 数据源配置 + source: + type: "database" + database: + host: "localhost" + port: 3306 + database: "qtrade" + user: "root" + password: "${DB_PASSWORD}" # 支持环境变量 + + # 预加载选项 + parallel: true # 并行加载 + max_workers: 4 # 最多4个线程 + batch_size: 1000 # 每批加载1000条 + + # 运行时更新策略 + update: + auto_append: true # 自动追加新数据 + max_cache_rows: 1000 # 单个缓存最多1000行 + trim_strategy: "rolling" # 滚动删除旧数据 + + # 缓存刷新策略 + refresh: + enabled: false # 是否定期刷新 + interval_minutes: 60 # 每小时刷新一次 + + # 缓存失效策略 + eviction: + strategy: "lru" # LRU淘汰策略 + check_interval: 300 # 每5分钟检查一次 + + # 监控配置 + monitoring: + log_stats: true # 定期打印统计信息 + log_interval_minutes: 10 # 每10分钟打印一次 + +# 策略实例配置目录 +strategy_configs_dir: "config/strategies" +``` + +### 12.2 数据结构示例 + +**缓存内部结构**: +```python +self._cache = { + "000001.SZ_1m": { + "klines": DataFrame[ + timestamp (index) | open | high | low | close | volume + ─────────────────┼───────┼───────┼───────┼───────┼──────── + 2024-09-27 09:30 | 10.50 | 10.60 | 10.45 | 10.55 | 1000000 + 2024-09-27 09:31 | 10.55 | 10.65 | 10.50 | 10.60 | 1100000 + ... + 2024-12-27 14:30 | 11.00 | 11.10 | 10.95 | 11.05 | 1200000 + ], + "meta": { + "time_range": (Timestamp('2024-09-27 09:30'), Timestamp('2024-12-27 14:30')), + "row_count": 13000, + "last_update": Timestamp('2024-12-27 14:30:00') + } + }, + "000001.SZ_1d": { ... }, + "600000.SH_1m": { ... }, + ... +} +``` + +### 12.3 错误码定义 + +```python +class CacheErrorCode: + """缓存错误码""" + SUCCESS = 0 + CACHE_DISABLED = 1001 # 缓存未启用 + DUPLICATE_TIMESTAMP = 1002 # 时间戳重复 + MEMORY_LIMIT_EXCEEDED = 1003 # 超过内存限制 + INVALID_DATA = 1004 # 无效数据 + DB_CONNECTION_ERROR = 1005 # 数据库连接失败 + PRELOAD_FAILED = 1006 # 预加载失败 +``` + +--- + +**文档版本**: v1.0 +**最后更新**: 2025-12-27 +**状态**: 设计完成,待实现 diff --git a/docs/tech_designs/shared_services_interface_minimization.md b/docs/tech_designs/shared_services_interface_minimization.md new file mode 100644 index 0000000..4dd09a1 --- /dev/null +++ b/docs/tech_designs/shared_services_interface_minimization.md @@ -0,0 +1,852 @@ +# SharedServices 接口最小化设计 + +> **核心问题**: SharedServices 是否需要暴露 DBManager、DataService 等底层能力? +> **用户观点**: 策略只需要获取数据,数据库操作应该在服务器启动/关闭时完成 +> **日期**: 2025-12-27 +> **结论**: ✅ 正确!应该最小化暴露的接口 + +--- + +## 1. 问题分析 + +### 1.1 当前设计的问题 + +```python +class SharedServices: + """当前设计(过度暴露)""" + + def __init__(self, cache_manager, db_manager, config, data_service): + self.cache_manager = cache_manager # ❌ 暴露了 + self.db_manager = db_manager # ❌ 暴露了 + self.config = config # ❌ 暴露了 + self.data_service = data_service # ❌ 暴露了 +``` + +**问题**: +1. **过度暴露内部实现**:策略可以直接访问 `cache_manager`, `db_manager` +2. **违反封装原则**:策略知道了不该知道的细节 +3. **增加耦合**:策略依赖了底层实现 +4. **难以重构**:改变内部实现需要修改所有使用的地方 + +### 1.2 策略真正需要什么? + +让我们分析策略的实际需求: + +```python +class MAStrategy: + """一个典型的策略需要什么?""" + + def compute(self, kline_data): + # 需求1: 获取历史K线数据 + history = ??? # 策略只想要数据,不关心从哪来 + + # 需求2: 获取指标数据(可选) + macd = ??? + + # 需求3: 查询持仓(独立状态,不在这里讨论) + position = self.context.get_position() + + # 需求4: 策略参数(独立配置,不在这里讨论) + ma_period = self.params['ma_period'] + + # 策略不需要: + # ❌ 直接访问数据库 + # ❌ 知道缓存的存在 + # ❌ 知道数据从哪来 + # ❌ 管理连接池 +``` + +**结论**:策略只需要两个数据访问接口: +1. `get_klines(symbol, period, last_n)` → 返回 DataFrame +2. `get_indicators(symbol, period, type)` → 返回 DataFrame + +--- + +## 2. 数据流分析 + +### 2.1 服务器启动阶段 + +``` +┌─────────────────────────────────────────────────┐ +│ 服务器启动流程 │ +└─────────────────────────────────────────────────┘ + +1. 加载配置 + config = load_config('global_config.yaml') + +2. 初始化数据库连接 + db_manager = DBManager(config['database']) + +3. 初始化缓存 + cache_manager = CacheManager(config['cache']) + +4. 预加载数据(核心操作) + ┌────────────────────────────────────────┐ + │ 从数据库批量加载历史数据到缓存 │ + │ │ + │ for each symbol in symbols: │ + │ for each period in periods: │ + │ df = db_manager.load_klines(...) │ ← 数据库操作 + │ cache_manager.set(...) │ ← 填充缓存 + └────────────────────────────────────────┘ + +5. 创建 SharedServices + shared = SharedServices(cache_manager) ← 只传缓存! + + ✅ 此时缓存已经预加载完毕 + ✅ 策略运行时不需要访问数据库 + ✅ DBManager 可以关闭或保持在服务器层面 + +6. 启动策略管理器 + strategy_manager = StrategyManager(shared) + +7. 启动 WebSocket 服务器 +``` + +**关键点**: +- ✅ **数据库操作只在启动时发生** +- ✅ **预加载后,策略只访问缓存** +- ✅ **DBManager 不需要传给 SharedServices** + +### 2.2 服务器运行阶段 + +``` +┌─────────────────────────────────────────────────┐ +│ 实时数据处理 │ +└─────────────────────────────────────────────────┘ + +1. 新K线数据到达 + WebSocket 收到: {symbol, timestamp, OHLCV} + +2. 追加到缓存 + cache_manager.append_kline(...) + + ✅ 只操作缓存,不涉及数据库 + +3. 分发到策略 + signals = strategy_manager.dispatch_kline(...) + + 策略内部: + history = context.get_klines(...) ← 从缓存读取 + + ✅ 策略完全不知道数据库的存在 + +4. 返回信号 + return signals +``` + +**关键点**: +- ✅ **运行时只操作缓存** +- ✅ **策略不需要访问数据库** +- ✅ **数据库连接可以关闭(如果需要节省资源)** + +### 2.3 服务器关闭阶段 + +``` +┌─────────────────────────────────────────────────┐ +│ 优雅关闭流程 │ +└─────────────────────────────────────────────────┘ + +1. 接收关闭信号 + SIGTERM / Ctrl+C + +2. 停止接收新数据 + ws_server.stop() + +3. 保存缓存到数据库(可选) + ┌────────────────────────────────────────┐ + │ 如果需要持久化缓存的更新数据: │ + │ │ + │ for key, data in cache_manager.items():│ + │ db_manager.save_klines(...) │ ← 数据库写入 + └────────────────────────────────────────┘ + + 或者 + ┌────────────────────────────────────────┐ + │ 如果不需要持久化: │ + │ 直接丢弃缓存 │ + │ 下次启动重新从数据库加载 │ + └────────────────────────────────────────┘ + +4. 关闭数据库连接 + db_manager.close() + +5. 退出 +``` + +**关键点**: +- ✅ **保存缓存是服务器的职责,不是策略的职责** +- ✅ **策略根本不参与关闭流程** + +### 2.4 缓存未命中降级(可选功能) + +``` +┌─────────────────────────────────────────────────┐ +│ 缓存未命中处理 │ +└─────────────────────────────────────────────────┘ + +场景:策略请求的数据不在缓存中 + +策略调用: + df = context.get_klines('000001.SZ', '1m', last_n=100) + +SharedServices 内部: + def get_klines(self, symbol, period, last_n): + # 1. 先从缓存取 + df = self._cache_manager.get_klines_range(...) + + # 2. 缓存命中,直接返回 + if df is not None and len(df) >= last_n: + return df + + # 3. 缓存未命中,降级到数据库(可选) + if self._enable_db_fallback: + df = self._db_manager.load_klines(...) ← 降级逻辑 + # 加载后填充缓存 + self._cache_manager.set_klines(...) + return df + + # 4. 不允许降级,返回 None + return None + +策略看到的: + df = context.get_klines(...) + # 策略完全不知道数据从缓存来还是数据库来 + # 这是封装! +``` + +**关键点**: +- ✅ **降级逻辑封装在 SharedServices 内部** +- ✅ **策略不需要知道降级的存在** +- ✅ **DBManager 是 SharedServices 的私有成员** + +--- + +## 3. 推荐设计:最小化接口 + +### 3.1 新设计方案 + +```python +class SharedServices: + """ + 共享服务(最小化接口) + + 设计原则: + 1. 只暴露策略真正需要的接口 + 2. 隐藏所有实现细节 + 3. 封装降级逻辑 + """ + + def __init__( + self, + cache_manager: CacheManager, + db_manager: Optional[DBManager] = None, # 可选,用于降级 + enable_db_fallback: bool = False # 是否启用降级 + ): + """ + 初始化共享服务 + + Args: + cache_manager: 缓存管理器(必需) + db_manager: 数据库管理器(可选,用于降级) + enable_db_fallback: 是否启用数据库降级 + """ + # ✅ 私有成员:策略无法直接访问 + self._cache_manager = cache_manager + self._db_manager = db_manager + self._enable_db_fallback = enable_db_fallback + + # ==================== 公开接口(最小化) ==================== + + def get_klines( + self, + symbol: str, + period: str, + last_n: Optional[int] = None, + start: Optional[pd.Timestamp] = None, + end: Optional[pd.Timestamp] = None + ) -> Optional[pd.DataFrame]: + """ + 获取K线数据(唯一的数据访问接口) + + 这是策略唯一需要的接口! + + Args: + symbol: 标的代码 + period: 周期 + last_n: 最近N条 + start: 开始时间(可选) + end: 结束时间(可选) + + Returns: + K线DataFrame,如果不存在返回None + + 内部逻辑: + 1. 优先从缓存读取 + 2. 缓存未命中且启用降级,从数据库读取 + 3. 读取后自动填充缓存 + 4. 策略完全不知道这些细节 + """ + # 1. 从缓存读取 + df = self._cache_manager.get_klines_range( + symbol, period, last_n=last_n, start=start, end=end + ) + + # 2. 缓存命中 + if df is not None and not df.empty: + if last_n is None or len(df) >= last_n: + return df + + # 3. 缓存未命中,尝试降级 + if self._enable_db_fallback and self._db_manager: + logger.warning(f"Cache miss: {symbol}_{period}, loading from database") + df = self._load_from_database(symbol, period, last_n, start, end) + + # 加载后填充缓存 + if df is not None and not df.empty: + self._cache_manager.set_klines(symbol, period, {'klines': df}) + + return df + + # 4. 无降级或降级失败 + return None + + def get_indicators( + self, + symbol: str, + period: str, + indicator_type: str + ) -> Optional[pd.DataFrame]: + """ + 获取指标数据(第二个公开接口) + + Args: + symbol: 标的代码 + period: 周期 + indicator_type: 指标类型(如 'MACD', 'KDJ') + + Returns: + 指标DataFrame,如果不存在返回None + """ + # 只从缓存读取指标 + # 指标由指标计算器提前计算好放入缓存 + return self._cache_manager.get_indicator(symbol, period, indicator_type) + + # ==================== 私有方法(策略无法访问) ==================== + + def _load_from_database( + self, + symbol: str, + period: str, + last_n: Optional[int], + start: Optional[pd.Timestamp], + end: Optional[pd.Timestamp] + ) -> Optional[pd.DataFrame]: + """ + 从数据库加载数据(私有方法) + + 策略无法直接调用此方法 + """ + if not self._db_manager: + return None + + try: + # 构造查询参数 + if last_n: + # 获取最近N条 + df = self._db_manager.load_klines_last_n(symbol, period, last_n) + else: + # 获取时间范围 + df = self._db_manager.load_klines_range(symbol, period, start, end) + + return df + except Exception as e: + logger.error(f"Failed to load from database: {e}") + return None + + # ==================== 工具方法(可选) ==================== + + def get_cache_stats(self) -> dict: + """ + 获取缓存统计信息(用于监控) + + 这不是策略需要的,是服务器管理需要的 + """ + return self._cache_manager.get_stats() +``` + +### 3.2 对比:接口暴露 + +| 设计 | 暴露的接口 | 策略可以访问 | 问题 | +| ---------- | ------------------------------------------------------- | ------------ | ---------- | +| **原设计** | `cache_manager`, `db_manager`, `config`, `data_service` | 所有底层组件 | ❌ 过度暴露 | +| **新设计** | `get_klines()`, `get_indicators()` | 只有数据接口 | ✅ 最小化 | + +```python +# ❌ 原设计:策略可以直接访问底层 +shared.cache_manager.get(...) # 不应该暴露 +shared.db_manager.query(...) # 不应该暴露 +shared.config['database']['host'] # 不应该暴露 + +# ✅ 新设计:策略只能访问高层接口 +shared.get_klines(...) # 唯一方式 +shared.get_indicators(...) # 唯一方式 +``` + +--- + +## 4. 数据库操作的职责划分 + +### 4.1 谁负责数据库操作? + +``` +┌─────────────────────────────────────────────────┐ +│ 数据库操作职责 │ +└─────────────────────────────────────────────────┘ + +操作类型 负责者 时机 +───────────────────────────────────────────────── +预加载历史数据 QTradeServer 启动时 +追加实时数据到缓存 QTradeServer 运行时 +保存缓存到数据库 QTradeServer 关闭时 +缓存未命中降级 SharedServices 运行时(可选) + (内部私有逻辑) +``` + +### 4.2 服务器启动时的数据库操作 + +```python +# qtrade_server.py + +def start_server(host, port, config_path): + """启动服务器""" + + # 1. 加载配置 + config = load_config(config_path) + + # 2. 初始化数据库(服务器级别) + db_manager = DBManager(config['database']) + + # 3. 初始化缓存 + cache_manager = CacheManager(config['cache']) + + # 4. 预加载数据(服务器职责) + logger.info("Preloading data from database...") + preload_cache_data( + db_manager=db_manager, # ← 服务器使用数据库 + cache_manager=cache_manager, + config=config + ) + logger.info("Preload completed") + + # 5. 创建共享服务(只传缓存) + shared_services = SharedServices( + cache_manager=cache_manager, + db_manager=db_manager, # ← 可选,用于降级 + enable_db_fallback=False # ← 默认禁用降级 + ) + + # 6. 初始化策略管理器 + strategy_manager = StrategyManager( + config_dir="config/strategies", + shared_services=shared_services + ) + + # 7. 注册关闭钩子(服务器职责) + def on_shutdown(): + logger.info("Server shutting down...") + + # 可选:保存缓存到数据库 + if config['cache'].get('persist_on_shutdown', False): + save_cache_to_database(cache_manager, db_manager) + + # 关闭数据库连接 + db_manager.close() + + logger.info("Shutdown completed") + + signal.signal(signal.SIGTERM, lambda s, f: on_shutdown()) + signal.signal(signal.SIGINT, lambda s, f: on_shutdown()) + + # 8. 启动服务器 + ws_server = WebSocketServer(...) + ws_server.start(host, port) +``` + +**关键点**: +- ✅ **数据库操作在服务器层面,不在策略层面** +- ✅ **预加载和保存都是服务器的职责** +- ✅ **策略完全不参与数据库操作** + +### 4.3 预加载函数实现 + +```python +def preload_cache_data( + db_manager: DBManager, + cache_manager: CacheManager, + config: dict +) -> None: + """ + 预加载历史数据到缓存 + + 这是服务器启动时的一次性操作 + + Args: + db_manager: 数据库管理器 + cache_manager: 缓存管理器 + config: 全局配置 + """ + preload_config = config['cache']['preload'] + + if not preload_config['enabled']: + logger.info("Preload disabled, skipping") + return + + # 解析配置 + time_range = parse_time_range(preload_config['time_range']) + periods = preload_config['periods'] + + # 计算时间范围 + end_date = datetime.now() + start_date = end_date - time_range + + # 收集需要预加载的symbols + symbols = collect_symbols_from_strategy_configs(config['strategy_configs_dir']) + + logger.info(f"Preloading {len(symbols)} symbols, {len(periods)} periods") + logger.info(f"Time range: {start_date} ~ {end_date}") + + # 批量加载 + success_count = 0 + fail_count = 0 + + for symbol in symbols: + for period in periods: + try: + # 从数据库加载 + df = db_manager.load_klines_range( + symbol=symbol, + period=period, + start=start_date, + end=end_date + ) + + if df is not None and not df.empty: + # 填充缓存 + cache_manager.set_klines(symbol, period, {'klines': df}) + logger.info(f"✓ Preloaded {symbol}_{period}: {len(df)} rows") + success_count += 1 + else: + logger.warning(f"No data for {symbol}_{period}") + fail_count += 1 + + except Exception as e: + logger.error(f"Failed to preload {symbol}_{period}: {e}") + fail_count += 1 + + logger.info(f"Preload summary: {success_count} success, {fail_count} failed") +``` + +### 4.4 保存缓存函数实现(可选) + +```python +def save_cache_to_database( + cache_manager: CacheManager, + db_manager: DBManager +) -> None: + """ + 保存缓存数据到数据库 + + 这是服务器关闭时的操作(可选) + + Args: + cache_manager: 缓存管理器 + db_manager: 数据库管理器 + """ + logger.info("Saving cache to database...") + + stats = cache_manager.get_stats() + total = stats['size'] + saved = 0 + + # 遍历所有缓存项 + for key in cache_manager.keys(): + try: + symbol, period = key.split('_', 1) + df = cache_manager.get_klines(symbol, period) + + if df is not None and not df.empty: + # 保存到数据库 + db_manager.save_klines(symbol, period, df) + saved += 1 + logger.debug(f"✓ Saved {key}: {len(df)} rows") + + except Exception as e: + logger.error(f"Failed to save {key}: {e}") + + logger.info(f"Save completed: {saved}/{total}") +``` + +--- + +## 5. 是否需要降级逻辑? + +### 5.1 两种模式对比 + +#### 模式A:纯缓存模式(推荐用于实盘) + +```python +# 配置 +cache: + preload: + enabled: true + time_range: "3M" + +shared_services = SharedServices( + cache_manager=cache_manager, + db_manager=None, # ← 不传数据库 + enable_db_fallback=False # ← 禁用降级 +) + +# 特点 +✅ 启动时预加载足够的历史数据 +✅ 运行时只访问缓存,性能最优 +✅ 缓存未命中返回 None,策略处理 +❌ 如果缓存数据不足,策略无法获取 +``` + +**适用场景**: +- 实盘交易:预加载3个月数据已足够 +- 性能敏感:不希望运行时访问数据库 +- 简单部署:不需要保持数据库连接 + +#### 模式B:缓存+降级模式(推荐用于开发) + +```python +# 配置 +cache: + preload: + enabled: true + time_range: "7D" # 只预加载7天(减少启动时间) + fallback: + enabled: true # 启用降级 + +shared_services = SharedServices( + cache_manager=cache_manager, + db_manager=db_manager, # ← 传数据库 + enable_db_fallback=True # ← 启用降级 +) + +# 特点 +✅ 启动快(少量预加载) +✅ 缓存未命中自动从数据库加载 +✅ 开发灵活(不用担心缓存不足) +⚠️ 运行时可能访问数据库(性能影响小) +``` + +**适用场景**: +- 开发测试:快速启动,灵活调试 +- 回测:需要大量历史数据 +- 策略研发:需要访问任意时间段数据 + +### 5.2 推荐配置 + +**生产环境(实盘)**: +```yaml +cache: + enabled: true + preload: + enabled: true + time_range: "3M" # 充足的历史数据 + periods: ["1m", "1d"] + fallback: + enabled: false # 禁用降级,纯缓存 +``` + +**开发环境**: +```yaml +cache: + enabled: true + preload: + enabled: true + time_range: "7D" # 快速启动 + periods: ["1d"] # 少量数据 + fallback: + enabled: true # 启用降级 +``` + +--- + +## 6. 架构图对比 + +### 6.1 原设计(过度暴露) + +``` +┌─────────────────────────────────────────┐ +│ SharedServices │ +│ │ +│ + cache_manager (public) ───────┐ │ +│ + db_manager (public) ───────┼─┐ │ +│ + config (public) ───────┼─┼─┐│ +│ + data_service (public) ───────┼─┼─┤│ +│ │ │ │││ +└────────────────────────────────────┼─┼─┤│ + │ │ ││ + StrategyContext │ │ ││ + ↓ │ │ ││ + Strategy 可以直接访问│ │ ││ + ↓ │ │ ││ + context._shared.cache_manager ←┘││ + context._shared.db_manager ──────┘│ + context._shared.config ───────────┘ + +❌ 问题:策略可以访问所有底层组件 +``` + +### 6.2 新设计(最小化接口) + +``` +┌─────────────────────────────────────────┐ +│ SharedServices │ +│ │ +│ - _cache_manager (private) │ +│ - _db_manager (private) │ +│ - _config (private) │ +│ │ +│ 公开接口: │ +│ + get_klines() │ +│ + get_indicators() │ +│ │ +│ 内部降级逻辑(策略不可见): │ +│ 缓存命中 → 返回 │ +│ 缓存未命中 → 降级到数据库(可选) │ +│ │ +└─────────────────────────────────────────┘ + ↑ + │ 只能访问公开接口 + │ + StrategyContext + ↓ + Strategy + ↓ + context.get_klines(...) ← 唯一方式 + +✅ 优点:策略只能访问高层接口 +``` + +--- + +## 7. 总结 + +### 7.1 核心设计原则 + +| 原则 | 说明 | 体现 | +| -------------- | ------------------ | --------------------------------------- | +| **接口最小化** | 只暴露必要的接口 | 只暴露 get_klines() 和 get_indicators() | +| **封装实现** | 隐藏内部细节 | 缓存、数据库都是私有成员 | +| **关注点分离** | 策略不关心数据来源 | 降级逻辑对策略透明 | +| **单一职责** | 每个组件职责清晰 | 数据库操作是服务器的职责,不是策略的 | + +### 7.2 用户观点的正确性 + +✅ **用户观点完全正确**: + +1. **"策略不需要知道数据库"** + - ✅ 正确!策略只需要数据接口 + - ✅ 数据从哪来应该对策略透明 + +2. **"启动时预加载,关闭时保存"** + - ✅ 正确!这是服务器的职责 + - ✅ 运行时只操作缓存,性能最优 + +3. **"不需要暴露这么多底层能力"** + - ✅ 完全正确!应该最小化接口 + - ✅ cache_manager、db_manager 应该是私有的 + +### 7.3 推荐实现 + +```python +# ==================== 新设计 ==================== + +class SharedServices: + """共享服务(最小化接口)""" + + def __init__(self, cache_manager, db_manager=None, enable_db_fallback=False): + # 私有成员 + self._cache_manager = cache_manager + self._db_manager = db_manager + self._enable_db_fallback = enable_db_fallback + + # 公开接口(仅2个) + def get_klines(self, symbol, period, last_n=None): + """策略唯一的数据访问方式""" + # 1. 从缓存读取 + df = self._cache_manager.get_klines_range(...) + if df is not None: + return df + + # 2. 可选:降级到数据库 + if self._enable_db_fallback: + df = self._load_from_database(...) + self._cache_manager.set_klines(...) # 填充缓存 + + return df + + def get_indicators(self, symbol, period, indicator_type): + """第二个公开接口""" + return self._cache_manager.get_indicator(...) + + # 私有方法(策略无法访问) + def _load_from_database(self, ...): + """降级逻辑(私有)""" + pass + +# ==================== 服务器启动 ==================== + +def start_server(host, port, config_path): + # 1. 初始化组件 + db_manager = DBManager(config['database']) + cache_manager = CacheManager(config['cache']) + + # 2. 预加载(服务器职责) + preload_cache_data(db_manager, cache_manager, config) + + # 3. 创建共享服务(最小化接口) + shared = SharedServices( + cache_manager=cache_manager, + db_manager=db_manager, # 可选 + enable_db_fallback=False # 生产建议禁用 + ) + + # 4. 启动策略管理器 + strategy_manager = StrategyManager(config_dir, shared) + + # 5. 注册关闭钩子(服务器职责) + def on_shutdown(): + # 可选:保存缓存 + if config['cache'].get('persist_on_shutdown'): + save_cache_to_database(cache_manager, db_manager) + db_manager.close() + + # 6. 启动服务器 + ws_server.start(host, port) +``` + +### 7.4 设计对比总结 + +| 方面 | 原设计 | 新设计 | +| -------------- | ----------------------------------- | -------------------------------- | +| **暴露接口** | 4个(cache/db/config/data_service) | 2个(get_klines/get_indicators) | +| **策略依赖** | 依赖底层实现 | 只依赖数据接口 | +| **数据库访问** | 策略可以直接访问 | 策略完全不知道 | +| **降级逻辑** | 暴露给策略 | 封装在内部 | +| **封装性** | ❌ 差 | ✅ 好 | +| **可维护性** | ❌ 难以重构 | ✅ 易于修改 | + +--- + +**设计结论**: +用户的观点完全正确!应该采用**最小化接口设计**,只暴露 `get_klines()` 和 `get_indicators()` 两个接口,所有底层实现(缓存、数据库)都应该是私有的。数据库操作应该在服务器启动/关闭时完成,运行时策略只访问缓存。 + +**下一步**: +基于此设计重新实现 SharedServices 和相关组件。 diff --git a/docs/tech_designs/strategy_context_sharing_design.md b/docs/tech_designs/strategy_context_sharing_design.md new file mode 100644 index 0000000..d691ab7 --- /dev/null +++ b/docs/tech_designs/strategy_context_sharing_design.md @@ -0,0 +1,901 @@ +# Strategy Context 共享策略设计 + +> **核心问题**: 策略的 Context 应该是每个策略独立一个,还是所有策略共享一个? +> **日期**: 2025-12-27 +> **结论**: **混合模式** - 共享服务 + 独立状态 + +--- + +## 1. 问题分析 + +### 1.1 Context 包含的内容分类 + +让我们先分析 Context 中包含的内容,它们可以分为两大类: + +``` +Context 包含内容 +│ +├── 📦 共享服务 (Shared Services) +│ ├── CacheManager - 数据缓存(全局共享) +│ ├── DBManager - 数据库连接(全局共享) +│ ├── ConfigManager - 配置管理(全局共享) +│ └── DataService - 数据服务(全局共享) +│ +└── 🔒 独立状态 (Instance State) + ├── PositionManager - 持仓管理(每个策略独立) + ├── Capital - 资金管理(每个策略独立) + ├── RiskControl - 风控状态(每个策略独立) + └── StrategyState - 策略内部状态(每个策略独立) +``` + +### 1.2 典型场景对比 + +**场景1:获取K线数据** +```python +# 这是共享的操作 +context.get_klines('000001.SZ', '1m', last_n=20) + +✅ 应该共享: +- CacheManager 是全局的 +- 所有策略读取相同的市场数据 +- 没有副作用,只读操作 +``` + +**场景2:查询持仓** +```python +# 这是独立的状态 +context.get_position('000001.SZ') + +❌ 不能共享: +- 策略A的持仓 ≠ 策略B的持仓 +- 同一个股票,不同策略可能有不同仓位 +- 每个策略有独立的资金分配 +``` + +**场景3:风控检查** +```python +# 这是独立的状态 +context.check_risk(signal) + +❌ 不能共享: +- 策略A的风控参数 ≠ 策略B的风控参数 +- 止损线、最大仓位等都是独立的 +``` + +--- + +## 2. 三种设计方案对比 + +### 方案A:完全共享 Context ❌ + +```python +# 所有策略共享一个 Context +global_context = StrategyContext(cache_manager, config) + +strategy1 = DebugStrategy(context=global_context, instance_id='debug1') +strategy2 = MAStrategy(context=global_context, instance_id='ma1') +``` + +**问题**: +```python +# ❌ 持仓数据混乱 +strategy1.context.get_position('000001.SZ') # 返回什么?strategy1的还是strategy2的? + +# ❌ 风控混乱 +strategy1.context.check_risk(signal) # 用的是哪个策略的风控参数? + +# ❌ 状态污染 +strategy1.context.update_position(...) # 会影响strategy2吗? +``` + +**结论**:❌ **不可行** - 无法区分策略独立状态 + +--- + +### 方案B:完全独立 Context ❌ + +```python +# 每个策略独立创建一个 Context +context1 = StrategyContext(cache_manager, config, instance_id='debug1') +context2 = StrategyContext(cache_manager, config, instance_id='ma1') + +strategy1 = DebugStrategy(context=context1) +strategy2 = MAStrategy(context=context2) +``` + +**问题**: +```python +# ❌ 资源浪费 +每个 Context 都要持有 cache_manager 引用(虽然指向同一个对象) +每个 Context 都要持有 db_manager 引用 +每个 Context 都要持有 config 引用 + +# ❌ 维护困难 +如果要添加新的共享服务,需要修改所有 Context 实例 + +# ⚠️ 潜在的内存浪费 +虽然共享服务是引用,但 Context 对象本身会有多份 +``` + +**结论**:⚠️ **可行但不优雅** - 浪费资源,维护困难 + +--- + +### 方案C:混合模式(共享服务 + 独立状态)✅ 推荐 + +```python +# 1. 全局共享服务 +shared_services = SharedServices( + cache_manager=cache_manager, + db_manager=db_manager, + config=config +) + +# 2. 每个策略有独立的 Context +context1 = StrategyContext( + shared_services=shared_services, + instance_id='debug_000001', + instance_config=load_config('debug_000001.yaml') +) + +context2 = StrategyContext( + shared_services=shared_services, + instance_id='ma_000001', + instance_config=load_config('ma_000001.yaml') +) + +# 3. 策略使用各自的 Context +strategy1 = DebugStrategy(context=context1) +strategy2 = MAStrategy(context=context2) +``` + +**优势**: +```python +# ✅ 共享服务高效访问 +context1.get_klines(...) # 通过 shared_services.cache_manager +context2.get_klines(...) # 使用同一个 cache_manager + +# ✅ 独立状态互不影响 +context1.get_position('000001.SZ') # 返回 strategy1 的持仓 +context2.get_position('000001.SZ') # 返回 strategy2 的持仓 + +# ✅ 资源高效利用 +只有一份 cache_manager, db_manager, config +但每个策略有自己的 position, capital, risk_state + +# ✅ 易于扩展 +添加新的共享服务:只需修改 SharedServices +添加新的独立状态:只需修改 StrategyContext +``` + +**结论**:✅ **推荐方案** - 平衡了效率和隔离性 + +--- + +## 3. 推荐架构设计 + +### 3.1 架构图 + +``` +┌─────────────────────────────────────────────────────────────┐ +│ QTradeServer │ +│ │ +│ ┌────────────────────────────────────────────────────┐ │ +│ │ SharedServices (全局单例) │ │ +│ │ │ │ +│ │ - cache_manager: CacheManager │ │ +│ │ - db_manager: DBManager │ │ +│ │ - config: GlobalConfig │ │ +│ │ - data_service: DataService │ │ +│ │ │ │ +│ │ + get_klines(symbol, period, ...) │ │ +│ │ + get_indicators(symbol, period, type) │ │ +│ │ + get_config(key) │ │ +│ └────────────────────────────────────────────────────┘ │ +│ ↑ 引用 │ +│ ┌───────────────┼───────────────┐ │ +│ │ │ │ │ +│ ┌──────┴──────┐ ┌──────┴──────┐ ┌─────┴───────┐ │ +│ │ Context1 │ │ Context2 │ │ Context3 │ │ +│ │ (debug1) │ │ (ma1) │ │ (macd1) │ │ +│ │ │ │ │ │ │ │ +│ │ shared: ref │ │ shared: ref │ │ shared: ref │ │ +│ │ instance_id │ │ instance_id │ │ instance_id │ │ +│ │ position │ │ position │ │ position │ │ +│ │ capital │ │ capital │ │ capital │ │ +│ │ risk_state │ │ risk_state │ │ risk_state │ │ +│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ +│ │ │ │ │ +└─────────┼───────────────┼───────────────┼───────────────────┘ + ↓ ↓ ↓ + ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ + │ Strategy1 │ │ Strategy2 │ │ Strategy3 │ + │ (debug) │ │ (ma) │ │ (macd) │ + └─────────────┘ └─────────────┘ └─────────────┘ +``` + +### 3.2 类设计 + +#### SharedServices(共享服务容器) + +```python +class SharedServices: + """ + 共享服务容器(全局单例) + + 包含所有策略共享的只读服务 + 线程安全,无状态(或状态全局共享) + """ + + def __init__( + self, + cache_manager: CacheManager, + db_manager: DBManager, + config: GlobalConfig, + data_service: Optional[DataService] = None + ): + """ + 初始化共享服务 + + Args: + cache_manager: 数据缓存管理器(全局共享) + db_manager: 数据库管理器(连接池) + config: 全局配置 + data_service: 可选的数据服务(封装缓存+数据库) + """ + self.cache_manager = cache_manager + self.db_manager = db_manager + self.config = config + self.data_service = data_service or DataService(cache_manager, db_manager) + + def get_klines( + self, + symbol: str, + period: str, + last_n: Optional[int] = None, + start: Optional[pd.Timestamp] = None, + end: Optional[pd.Timestamp] = None + ) -> Optional[pd.DataFrame]: + """ + 获取K线数据(只读操作,线程安全) + + 这是共享操作:所有策略读取相同的市场数据 + """ + return self.data_service.get_klines(symbol, period, last_n, start, end) + + def get_indicators( + self, + symbol: str, + period: str, + indicator_type: str + ) -> Optional[pd.DataFrame]: + """ + 获取指标数据(只读操作,线程安全) + """ + return self.data_service.get_indicators(symbol, period, indicator_type) + + def get_global_config(self, key: str) -> Any: + """ + 获取全局配置(只读操作) + """ + return self.config.get(key) +``` + +#### StrategyContext(策略上下文 - 每个策略独立) + +```python +class StrategyContext: + """ + 策略上下文(每个策略实例独立) + + 包含: + - 共享服务的引用(只读) + - 策略实例独立的状态(读写) + """ + + def __init__( + self, + shared_services: SharedServices, + instance_id: str, + instance_config: dict + ): + """ + 初始化策略上下文 + + Args: + shared_services: 共享服务容器(引用) + instance_id: 策略实例ID + instance_config: 策略实例配置 + """ + # 共享服务引用(只读) + self._shared = shared_services + + # 策略实例信息 + self.instance_id = instance_id + self.instance_config = instance_config + self.symbol = instance_config['symbol'] + + # 独立状态(每个策略独立) + self._position = Position( + symbol=self.symbol, + capital=instance_config['capital'] + ) + self._capital = Capital( + total=instance_config['capital'] + ) + self._risk_state = RiskState( + config=instance_config.get('risk', {}) + ) + + # ==================== 共享服务访问 ==================== + + def get_klines( + self, + symbol: Optional[str] = None, + period: str = '1m', + last_n: Optional[int] = None + ) -> Optional[pd.DataFrame]: + """ + 获取K线数据(委托给共享服务) + + Args: + symbol: 股票代码(如果不指定,使用策略配置的symbol) + period: 周期 + last_n: 最近N条 + + Returns: + K线DataFrame + """ + symbol = symbol or self.symbol + return self._shared.get_klines(symbol, period, last_n=last_n) + + def get_indicators( + self, + indicator_type: str, + symbol: Optional[str] = None, + period: str = '1m' + ) -> Optional[pd.DataFrame]: + """ + 获取指标数据(委托给共享服务) + """ + symbol = symbol or self.symbol + return self._shared.get_indicators(symbol, period, indicator_type) + + # ==================== 独立状态访问 ==================== + + def get_position(self) -> Position: + """ + 获取当前持仓(策略独立) + + 每个策略实例有自己的持仓 + """ + return self._position + + def update_position( + self, + action: str, + quantity: int, + price: float + ) -> bool: + """ + 更新持仓(策略独立) + + 修改此策略实例的持仓,不影响其他策略 + """ + if action == 'BUY': + return self._position.buy(quantity, price) + elif action == 'SELL': + return self._position.sell(quantity, price) + return False + + def get_capital(self) -> Capital: + """ + 获取资金信息(策略独立) + + 每个策略实例有独立的资金分配 + """ + return self._capital + + def check_risk(self, signal: dict) -> bool: + """ + 风控检查(策略独立) + + 使用此策略实例的风控参数 + """ + # 检查资金是否充足 + required_capital = signal['quantity'] * signal['price'] + if required_capital > self._capital.available: + return False + + # 检查仓位限制 + max_position_ratio = self._risk_state.max_position_ratio + current_ratio = self._position.get_position_ratio() + if current_ratio >= max_position_ratio: + return False + + # 检查止损线 + if self._position.has_position(): + loss_pct = self._position.get_loss_pct(signal['price']) + if loss_pct < -self._risk_state.stop_loss: + return False + + return True + + def get_instance_info(self) -> dict: + """ + 获取实例信息(策略独立) + """ + return { + 'instance_id': self.instance_id, + 'symbol': self.symbol, + 'capital': self._capital.total, + 'available_capital': self._capital.available, + 'position': self._position.to_dict(), + 'risk_state': self._risk_state.to_dict() + } +``` + +--- + +## 4. 共享 vs 独立内容清单 + +### 4.1 共享内容(通过 SharedServices) + +| 服务/数据 | 共享原因 | 访问方式 | 特点 | +| ---------------- | -------------------------------------- | ------------------------------- | -------------- | +| **CacheManager** | 全局数据缓存,所有策略读取相同市场数据 | `context._shared.cache_manager` | 只读,线程安全 | +| **DBManager** | 数据库连接池,避免重复连接 | `context._shared.db_manager` | 只读,连接池 | +| **GlobalConfig** | 全局配置(如总资金、全局风控) | `context._shared.config` | 只读 | +| **DataService** | 封装数据访问逻辑(缓存+数据库) | `context._shared.data_service` | 只读,有降级 | +| **K线数据** | 市场数据,所有策略看到的是相同的 | `context.get_klines()` | 只读 | +| **指标数据** | 基于K线计算,所有策略相同 | `context.get_indicators()` | 只读 | + +**共享特征**: +- ✅ **只读操作**:不修改数据,只查询 +- ✅ **无副作用**:多个策略同时访问不冲突 +- ✅ **线程安全**:可以并发访问 +- ✅ **资源高效**:避免重复创建和内存浪费 + +### 4.2 独立内容(每个 StrategyContext) + +| 状态/数据 | 独立原因 | 访问方式 | 特点 | +| ------------------ | -------------------------- | ------------------------- | -------------- | +| **Position** | 每个策略有独立持仓 | `context.get_position()` | 读写,策略隔离 | +| **Capital** | 每个策略有独立资金分配 | `context.get_capital()` | 读写,策略隔离 | +| **RiskState** | 每个策略有独立风控参数 | `context.check_risk()` | 读写,策略隔离 | +| **InstanceConfig** | 每个策略有独立配置 | `context.instance_config` | 只读,策略专属 | +| **StrategyState** | 策略内部状态(如MA历史值) | 策略内部管理 | 读写,策略内部 | + +**独立特征**: +- 🔒 **有状态**:会被修改,有副作用 +- 🔒 **策略隔离**:策略A的修改不影响策略B +- 🔒 **独立配置**:每个策略有自己的参数 +- 🔒 **独立资金**:避免多策略资金冲突 + +--- + +## 5. 典型使用场景示例 + +### 场景1:策略获取历史数据(共享) + +```python +class MAStrategy: + def __init__(self, context: StrategyContext, **params): + self.context = context + self.ma_period = params.get('ma_period', 20) + + def compute(self, kline_data: dict): + # ✅ 通过 context 获取历史数据(共享服务) + history = self.context.get_klines( + period='1m', + last_n=self.ma_period + ) + + if history is None or len(history) < self.ma_period: + return None + + # 计算均线 + ma = history['close'].mean() + + # 生成信号 + current_price = kline_data['close'] + if current_price > ma: + return {'action': 'BUY', 'price': current_price, 'quantity': 100} + + return None +``` + +**分析**: +- `get_klines()` 访问共享的 CacheManager +- 所有 MA 策略实例看到的历史数据是相同的 +- 这是只读操作,线程安全 + +### 场景2:策略检查持仓(独立) + +```python +class MAStrategy: + def compute(self, kline_data: dict): + # ... 生成信号 + signal = {'action': 'BUY', 'price': 10.5, 'quantity': 100} + + # ✅ 检查此策略的持仓(独立状态) + position = self.context.get_position() + + # 如果已经持仓,不重复买入 + if position.quantity > 0: + logger.info(f"Already holding {position.quantity} shares") + return None + + # ✅ 检查此策略的资金(独立状态) + capital = self.context.get_capital() + required = signal['quantity'] * signal['price'] + + if capital.available < required: + logger.warning(f"Insufficient capital: need {required}, have {capital.available}") + return None + + # ✅ 风控检查(独立参数) + if not self.context.check_risk(signal): + logger.warning("Risk check failed") + return None + + return signal +``` + +**分析**: +- `get_position()` 返回此策略实例的持仓 +- `get_capital()` 返回此策略实例的资金 +- `check_risk()` 使用此策略实例的风控参数 +- 这些都是独立状态,不影响其他策略 + +### 场景3:策略执行交易后更新状态(独立) + +```python +# qtrade_server.py + +async def handle_trade_result(message: dict) -> dict: + """ + 处理交易成交反馈 + """ + instance_id = message.get('instance_id') + action = message.get('action') + quantity = message.get('quantity') + price = message.get('price') + + # 查找对应的策略实例 + strategy = strategy_manager.get_instance(instance_id) + if not strategy: + raise ValueError(f"Strategy not found: {instance_id}") + + # ✅ 更新此策略的持仓(独立状态) + success = strategy.context.update_position( + action=action, + quantity=quantity, + price=price + ) + + if success: + logger.info(f"Position updated for {instance_id}: {action} {quantity}@{price}") + return {"msg_type": "ACK", "status": "success"} + else: + return {"msg_type": "ERROR", "message": "Failed to update position"} +``` + +**分析**: +- `update_position()` 只修改此策略实例的持仓 +- 策略A买入不影响策略B的持仓 +- 这是写操作,但由于隔离,不会冲突 + +--- + +## 6. 内存和性能分析 + +### 6.1 内存占用估算 + +**假设场景**: +- 3个策略实例 +- 2个标的(000001.SZ, 600000.SH) +- 2个周期(1m, 1d) +- 每个缓存1000条数据 + +#### 完全独立 Context(方案B) + +``` +每个 Context 独立持有所有服务: + +Context1: + - cache_manager 引用: 8 bytes + - db_manager 引用: 8 bytes + - config 引用: 8 bytes + - position: ~1 KB + - capital: ~0.5 KB + - risk_state: ~0.5 KB + Total: ~2 KB + +3个Context总计: ~6 KB (只算独立数据,共享服务只有引用) +``` + +#### 混合模式(方案C - 推荐) + +``` +SharedServices (全局1份): + - cache_manager: 8 bytes (指针) + - db_manager: 8 bytes (指针) + - config: 8 bytes (指针) + Total: 24 bytes + +每个 Context: + - shared 引用: 8 bytes + - position: ~1 KB + - capital: ~0.5 KB + - risk_state: ~0.5 KB + Total: ~2 KB + +3个Context总计: ~6 KB + 24 bytes + +结论:内存差异可忽略(因为共享服务本来就是引用) +``` + +**关键点**:无论哪种方案,共享服务(CacheManager等)都只有一份实际对象,其他都是引用。 + +### 6.2 性能对比 + +| 操作 | 完全独立 | 混合模式 | 差异 | +| ------------ | ----------------------------- | ------------------------------------- | -------------------- | +| **获取K线** | `context.cache_manager.get()` | `context._shared.cache_manager.get()` | 多一次间接访问,~1ns | +| **查询持仓** | `context.position.get()` | `context._position.get()` | 无差异 | +| **风控检查** | `context.check_risk()` | `context.check_risk()` | 无差异 | + +**结论**:性能差异可忽略(多一次指针解引用,现代CPU缓存友好) + +### 6.3 扩展性对比 + +**添加新的共享服务**: + +```python +# 方案B:完全独立 - 需要修改所有 Context 实例 +context1 = StrategyContext(cache, db, config, new_service) # ❌ 需要修改 +context2 = StrategyContext(cache, db, config, new_service) # ❌ 需要修改 +context3 = StrategyContext(cache, db, config, new_service) # ❌ 需要修改 + +# 方案C:混合模式 - 只需修改 SharedServices +shared = SharedServices(cache, db, config, new_service) # ✅ 只改一处 +context1 = StrategyContext(shared, 'inst1', cfg1) # ✅ 无需改 +context2 = StrategyContext(shared, 'inst2', cfg2) # ✅ 无需改 +context3 = StrategyContext(shared, 'inst3', cfg3) # ✅ 无需改 +``` + +**结论**:混合模式扩展性更好 + +--- + +## 7. 推荐实现步骤 + +### Phase 1: 定义共享服务容器 + +```python +# src/core/shared_services.py + +class SharedServices: + """全局共享服务容器""" + + def __init__(self, cache_manager, db_manager, config): + self.cache_manager = cache_manager + self.db_manager = db_manager + self.config = config + + # 可选:封装一个 DataService + self.data_service = DataService(cache_manager, db_manager) + + def get_klines(self, symbol, period, last_n=None): + """委托给 DataService""" + return self.data_service.get_klines(symbol, period, last_n) +``` + +### Phase 2: 实现 StrategyContext + +```python +# src/core/strategy_context.py + +class StrategyContext: + """策略上下文(每个策略独立)""" + + def __init__(self, shared_services, instance_id, instance_config): + self._shared = shared_services + self.instance_id = instance_id + self.symbol = instance_config['symbol'] + + # 独立状态 + self._position = Position(symbol=self.symbol) + self._capital = Capital(total=instance_config['capital']) + self._risk_state = RiskState(instance_config.get('risk', {})) + + # 共享服务代理方法 + def get_klines(self, symbol=None, period='1m', last_n=None): + symbol = symbol or self.symbol + return self._shared.get_klines(symbol, period, last_n) + + # 独立状态访问方法 + def get_position(self): + return self._position + + def update_position(self, action, quantity, price): + # 修改独立状态 + pass +``` + +### Phase 3: 修改 StrategyManager + +```python +# src/strategy_manager.py + +class StrategyManager: + def __init__(self, config_dir, shared_services): + self.config_dir = config_dir + self.shared_services = shared_services # 持有共享服务引用 + self.instances = {} + + def _create_strategy_instance(self, strategy_class, instance_config): + # 为每个策略创建独立的 Context + context = StrategyContext( + shared_services=self.shared_services, + instance_id=instance_config['instance_id'], + instance_config=instance_config + ) + + # 创建策略实例 + return strategy_class(context=context, **instance_config['params']) +``` + +### Phase 4: 服务器启动流程 + +```python +# src/qtrade_server.py + +def start_server(host, port, config_path): + # 1. 初始化共享服务 + config = load_config(config_path) + cache_manager = initialize_cache_manager(config) + db_manager = initialize_db_manager(config) + + shared_services = SharedServices( + cache_manager=cache_manager, + db_manager=db_manager, + config=config + ) + + # 2. 预加载数据(使用共享的 cache_manager) + preload_cache_data(cache_manager, config) + + # 3. 初始化策略管理器(传入共享服务) + strategy_manager = StrategyManager( + config_dir="config/strategies", + shared_services=shared_services + ) + strategy_manager.initialize() + + # 4. 启动服务器 + ws_server = WebSocketServer(...) + ws_server.start(host, port) +``` + +--- + +## 8. 最佳实践和注意事项 + +### 8.1 共享服务设计原则 + +✅ **应该共享的**: +1. **无状态或全局状态**:CacheManager、DBManager +2. **只读操作**:获取市场数据、配置查询 +3. **线程安全**:可以并发访问的服务 +4. **资源密集**:连接池、大对象 + +❌ **不应该共享的**: +1. **有策略独立状态**:持仓、资金、风控状态 +2. **写操作有副作用**:修改持仓、更新资金 +3. **策略专属配置**:单个策略的参数 +4. **策略内部缓存**:MA计算的历史值 + +### 8.2 Context 设计原则 + +```python +class StrategyContext: + """ + 设计原则: + 1. 共享服务:通过引用访问,不直接暴露 + 2. 独立状态:封装在 Context 内部,提供访问接口 + 3. 便捷方法:提供高层接口,隐藏实现细节 + """ + + def get_klines(self, ...): + """✅ 便捷方法:策略不需要知道 _shared 的存在""" + return self._shared.get_klines(...) + + def _get_cache_manager(self): + """❌ 不要暴露内部实现""" + return self._shared.cache_manager # 不推荐 +``` + +### 8.3 线程安全考虑 + +```python +class StrategyContext: + """ + 线程安全策略: + - 共享服务:假设它们是线程安全的(只读或有锁) + - 独立状态:不需要锁(每个线程访问不同的 Context) + """ + + def update_position(self, ...): + """ + 这个方法修改独立状态,不需要锁 + 因为每个策略有自己的 Context + """ + self._position.update(...) # 安全,独立状态 + + def get_klines(self, ...): + """ + 这个方法访问共享服务,由 CacheManager 保证线程安全 + """ + return self._shared.cache_manager.get(...) # 安全,CacheManager 有锁 +``` + +--- + +## 9. 总结 + +### 9.1 设计决策 + +| 问题 | 答案 | 理由 | +| ----------------- | ------------------------------------ | -------------------- | +| Context是否共享? | **部分共享** | 共享服务 + 独立状态 | +| 如何组织? | **SharedServices + StrategyContext** | 清晰的职责分离 | +| 性能影响? | **可忽略** | 只多一次指针解引用 | +| 内存占用? | **几乎相同** | 共享服务本来就是引用 | +| 扩展性? | **更好** | 添加服务只改一处 | + +### 9.2 推荐方案 + +``` +✅ 推荐:混合模式(方案C) + +SharedServices (全局1份) + ├── cache_manager + ├── db_manager + ├── config + └── data_service + +StrategyContext (每个策略1份) + ├── shared_services (引用) + ├── instance_id + ├── position (独立) + ├── capital (独立) + └── risk_state (独立) +``` + +### 9.3 核心原则 + +1. **共享只读,独立读写** + - 市场数据:共享(所有策略看到相同数据) + - 策略状态:独立(避免相互影响) + +2. **按职责分离** + - SharedServices:提供全局服务 + - StrategyContext:管理策略独立状态 + +3. **最小化暴露** + - 策略不直接访问 SharedServices + - 通过 Context 提供的接口访问 + +4. **易于测试和扩展** + - Mock SharedServices 即可测试策略 + - 添加新服务不影响现有代码 + +--- + +**设计结论**: +采用 **混合模式**,既保证了资源高效利用(共享服务),又保证了策略隔离性(独立状态)。 + +**下一步**: +基于此方案实现 SharedServices 和 StrategyContext。 diff --git a/src/cache/cache_manager.py b/src/cache/cache_manager.py index c14a434..cbe2026 100644 --- a/src/cache/cache_manager.py +++ b/src/cache/cache_manager.py @@ -29,14 +29,16 @@ class CacheManager: - ✗ 指标计算逻辑(由DataService负责) """ - def __init__(self, config: Union[dict, Config]): + def __init__(self, config: Union[dict, Config], db_manager=None): """ 初始化缓存管理器 Args: config: 配置字典或Config对象,包含cache相关配置 + db_manager: 数据库管理器(可选),用于缓存未命中时从数据库加载 """ self.config = config + self._db_manager = db_manager # 获取缓存配置 cache_config = config.get("cache", {}) @@ -47,25 +49,27 @@ class CacheManager: self._cache: Dict[str, Dict[str, Any]] = {} logger.info( - f"CacheManager initialized: enabled={self.enabled}, max_memory={self.max_memory_mb}MB" + f"CacheManager initialized: enabled={self.enabled}, max_memory={self.max_memory_mb}MB, " + f"db_fallback={'enabled' if db_manager else 'disabled'}" ) def get_klines(self, symbol: str, period: str) -> Optional[pd.DataFrame]: """ - 获取缓存数据(纯Key-Value查询) + 获取K线数据(带数据库降级) Args: symbol: 标的代码 period: 周期 Returns: - 缓存中的K线DataFrame或None + K线DataFrame或None """ if not self.enabled: return None key = self._make_key(symbol, period) + # 1. 先查缓存 if key in self._cache: cached = self._cache[key] cache_data = cached.get("klines") @@ -73,6 +77,24 @@ class CacheManager: if cache_data is not None and not cache_data.empty: return cache_data + # 2. 缓存未命中,尝试从数据库加载 + if self._db_manager: + logger.debug(f"Cache miss: {key}, loading from database") + try: + # 从数据库加载所有数据 + df = self._db_manager.load_klines_all(symbol, period) + + if df is not None and not df.empty: + # 加载成功,填充缓存 + self.set_klines(symbol, period, {"klines": df}) + logger.info( + f"Loaded {len(df)} rows from database and cached: {key}" + ) + return df + except Exception as e: + logger.error(f"Failed to load from database: {key}, error: {e}") + + # 3. 数据库也没有 return None def set_klines(self, symbol: str, period: str, data: Dict[str, Any]) -> None: diff --git a/src/core/base_strategy.py b/src/core/base_strategy.py new file mode 100644 index 0000000..bab30b1 --- /dev/null +++ b/src/core/base_strategy.py @@ -0,0 +1,106 @@ +""" +策略基类 (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 + ) diff --git a/src/core/capital.py b/src/core/capital.py new file mode 100644 index 0000000..6ea179a --- /dev/null +++ b/src/core/capital.py @@ -0,0 +1,125 @@ +""" +资金管理 (Capital) + +管理单个策略实例的资金信息 +""" + +from dataclasses import dataclass +import logging + +logger = logging.getLogger(__name__) + + +@dataclass +class Capital: + """ + 资金信息(独立状态) + + 每个策略实例拥有独立的资金账户 + """ + + initial_cash: float # 初始资金 + available_cash: float = 0.0 # 可用资金 + frozen_cash: float = 0.0 # 冻结资金 + + def __post_init__(self): + """初始化后设置可用资金""" + if self.available_cash == 0.0: + self.available_cash = self.initial_cash + + @property + def total_cash(self) -> float: + """总资金""" + return self.available_cash + self.frozen_cash + + @property + def cash_usage_ratio(self) -> float: + """资金使用率""" + if self.initial_cash == 0: + return 0.0 + return (self.initial_cash - self.available_cash) / self.initial_cash + + def freeze(self, amount: float) -> bool: + """ + 冻结资金 + + Args: + amount: 冻结金额 + + Returns: + 是否成功 + """ + if amount <= 0: + logger.error(f"Invalid freeze amount: {amount}") + return False + + if self.available_cash < amount: + logger.warning( + f"Insufficient cash: available={self.available_cash:.2f}, " + f"required={amount:.2f}" + ) + return False + + self.available_cash -= amount + self.frozen_cash += amount + + logger.debug( + f"Cash frozen: amount={amount:.2f}, " + f"available={self.available_cash:.2f}, " + f"frozen={self.frozen_cash:.2f}" + ) + return True + + def unfreeze(self, amount: float) -> bool: + """ + 解冻资金 + + Args: + amount: 解冻金额 + + Returns: + 是否成功 + """ + if amount <= 0: + logger.error(f"Invalid unfreeze amount: {amount}") + return False + + if self.frozen_cash < amount: + logger.error( + f"Insufficient frozen cash: frozen={self.frozen_cash:.2f}, " + f"amount={amount:.2f}" + ) + return False + + self.frozen_cash -= amount + self.available_cash += amount + + logger.debug( + f"Cash unfrozen: amount={amount:.2f}, " + f"available={self.available_cash:.2f}, " + f"frozen={self.frozen_cash:.2f}" + ) + return True + + def update(self, amount: float): + """ + 更新资金(盈亏结算) + + Args: + amount: 变化金额(正数为盈利,负数为亏损) + """ + self.available_cash += amount + logger.debug( + f"Capital updated: amount={amount:+.2f}, " + f"available={self.available_cash:.2f}" + ) + + def to_dict(self) -> dict: + """转换为字典""" + return { + "initial_cash": self.initial_cash, + "available_cash": self.available_cash, + "frozen_cash": self.frozen_cash, + "total_cash": self.total_cash, + "cash_usage_ratio": self.cash_usage_ratio, + } diff --git a/src/core/position.py b/src/core/position.py new file mode 100644 index 0000000..61d488b --- /dev/null +++ b/src/core/position.py @@ -0,0 +1,95 @@ +""" +持仓管理 (Position) + +管理单个策略实例的持仓信息 +""" + +from dataclasses import dataclass +import logging + +logger = logging.getLogger(__name__) + + +@dataclass +class Position: + """ + 持仓信息(独立状态) + + 每个策略实例拥有独立的持仓 + """ + + symbol: str + shares: float = 0.0 # 持仓数量 + cost: float = 0.0 # 持仓成本 + + @property + def avg_price(self) -> float: + """平均持仓价格""" + if self.shares == 0: + return 0.0 + return self.cost / self.shares + + @property + def is_empty(self) -> bool: + """是否空仓""" + return self.shares == 0 + + def update(self, shares_change: float, cost_change: float): + """ + 更新持仓 + + Args: + shares_change: 持仓变化(正数为买入,负数为卖出) + cost_change: 成本变化 + """ + self.shares += shares_change + self.cost += cost_change + + # 清空时重置成本 + if abs(self.shares) < 1e-6: + self.shares = 0.0 + self.cost = 0.0 + + logger.debug( + f"Position updated: {self.symbol} " + f"shares={self.shares:.2f}, cost={self.cost:.2f}, " + f"avg_price={self.avg_price:.2f}" + ) + + def calculate_profit(self, current_price: float) -> float: + """ + 计算浮动盈亏 + + Args: + current_price: 当前价格 + + Returns: + 浮动盈亏金额 + """ + if self.is_empty: + return 0.0 + return (current_price - self.avg_price) * self.shares + + def calculate_profit_pct(self, current_price: float) -> float: + """ + 计算浮动盈亏百分比 + + Args: + current_price: 当前价格 + + Returns: + 浮动盈亏百分比 + """ + if self.is_empty or self.avg_price == 0: + return 0.0 + return ((current_price - self.avg_price) / self.avg_price) * 100 + + def to_dict(self) -> dict: + """转换为字典""" + return { + "symbol": self.symbol, + "shares": self.shares, + "cost": self.cost, + "avg_price": self.avg_price, + "is_empty": self.is_empty, + } diff --git a/src/core/risk_state.py b/src/core/risk_state.py new file mode 100644 index 0000000..32d0eac --- /dev/null +++ b/src/core/risk_state.py @@ -0,0 +1,161 @@ +""" +风险状态管理 (RiskState) + +管理单个策略实例的风险参数和状态 +""" + +from dataclasses import dataclass +import logging + +logger = logging.getLogger(__name__) + + +@dataclass +class RiskState: + """ + 风险状态(独立状态) + + 每个策略实例拥有独立的风险参数 + """ + + # 风险参数 + max_position_ratio: float = 0.5 # 最大持仓比例 + stop_loss_ratio: float = 0.05 # 止损比例 + stop_profit_ratio: float = 0.20 # 止盈比例 + max_single_loss: float = 10000.0 # 单次最大亏损 + + # 风险状态 + total_loss: float = 0.0 # 累计亏损 + daily_loss: float = 0.0 # 当日亏损 + consecutive_losses: int = 0 # 连续亏损次数 + is_risk_locked: bool = False # 是否风控锁定 + + def check_position_limit(self, position_value: float, total_value: float) -> bool: + """ + 检查持仓是否超限 + + Args: + position_value: 持仓市值 + total_value: 总资产 + + Returns: + 是否符合限制 + """ + if total_value == 0: + return True + + ratio = position_value / total_value + if ratio > self.max_position_ratio: + logger.warning( + f"Position ratio exceeds limit: {ratio:.2%} > {self.max_position_ratio:.2%}" + ) + return False + return True + + def check_stop_loss(self, current_price: float, cost_price: float) -> bool: + """ + 检查是否触发止损 + + Args: + current_price: 当前价格 + cost_price: 成本价 + + Returns: + 是否触发止损 + """ + if cost_price == 0: + return False + + loss_ratio = (cost_price - current_price) / cost_price + if loss_ratio >= self.stop_loss_ratio: + logger.warning( + f"Stop loss triggered: loss={loss_ratio:.2%}, " + f"threshold={self.stop_loss_ratio:.2%}" + ) + return True + return False + + def check_stop_profit(self, current_price: float, cost_price: float) -> bool: + """ + 检查是否触发止盈 + + Args: + current_price: 当前价格 + cost_price: 成本价 + + Returns: + 是否触发止盈 + """ + if cost_price == 0: + return False + + profit_ratio = (current_price - cost_price) / cost_price + if profit_ratio >= self.stop_profit_ratio: + logger.info( + f"Stop profit triggered: profit={profit_ratio:.2%}, " + f"threshold={self.stop_profit_ratio:.2%}" + ) + return True + return False + + def record_loss(self, loss_amount: float): + """ + 记录亏损 + + Args: + loss_amount: 亏损金额(正数) + """ + self.total_loss += loss_amount + self.daily_loss += loss_amount + self.consecutive_losses += 1 + + # 检查是否需要风控锁定 + if loss_amount > self.max_single_loss: + logger.error( + f"Single loss exceeds limit: {loss_amount:.2f} > {self.max_single_loss:.2f}" + ) + self.lock() + + logger.warning( + f"Loss recorded: amount={loss_amount:.2f}, " + f"total={self.total_loss:.2f}, " + f"consecutive={self.consecutive_losses}" + ) + + def record_profit(self, profit_amount: float): + """ + 记录盈利 + + Args: + profit_amount: 盈利金额(正数) + """ + self.consecutive_losses = 0 # 重置连续亏损 + logger.info(f"Profit recorded: {profit_amount:.2f}") + + def reset_daily_loss(self): + """重置当日亏损""" + self.daily_loss = 0.0 + logger.debug("Daily loss reset") + + def lock(self): + """风控锁定""" + self.is_risk_locked = True + logger.error("Risk locked! Trading suspended.") + + def unlock(self): + """解除风控锁定""" + self.is_risk_locked = False + logger.info("Risk unlocked") + + def to_dict(self) -> dict: + """转换为字典""" + return { + "max_position_ratio": self.max_position_ratio, + "stop_loss_ratio": self.stop_loss_ratio, + "stop_profit_ratio": self.stop_profit_ratio, + "max_single_loss": self.max_single_loss, + "total_loss": self.total_loss, + "daily_loss": self.daily_loss, + "consecutive_losses": self.consecutive_losses, + "is_risk_locked": self.is_risk_locked, + } diff --git a/src/core/strategy_context.py b/src/core/strategy_context.py new file mode 100644 index 0000000..1470768 --- /dev/null +++ b/src/core/strategy_context.py @@ -0,0 +1,316 @@ +""" +策略上下文 (StrategyContext) + +策略运行的上下文环境,提供数据访问和状态管理 + +设计原则: +1. Context 是策略访问所有资源的唯一入口 +2. 直接持有共享资源(cache_manager、db_manager) +3. 对外提供高层接口,隐藏实现细节 +4. 每个策略实例有独立的 Context +""" + +from typing import Optional +import pandas as pd +import logging + +from src.core.position import Position +from src.core.capital import Capital +from src.core.risk_state import RiskState + +logger = logging.getLogger(__name__) + + +class StrategyContext: + """ + 策略上下文(直接提供所有方法) + + 共享资源:通过传入同一个实例实现共享 + 独立状态:每个Context有自己的Position、Capital、RiskState + """ + + def __init__( + self, + cache_manager, + instance_id: str, + symbol: str, + instance_config: dict, + ): + """ + 初始化策略上下文 + + Args: + cache_manager: 缓存管理器(共享实例) + instance_id: 策略实例ID + symbol: 交易标的 + instance_config: 实例配置 + """ + # ==================== 共享资源(私有) ==================== + # 注意:这是传入的共享实例,不是新创建的 + self._cache_manager = cache_manager + + # ==================== 实例信息 ==================== + self.instance_id = instance_id + self.symbol = symbol + self.config = instance_config + + # ==================== 独立状态 ==================== + self._position = Position( + symbol=symbol, + shares=instance_config.get("initial_shares", 0), + cost=instance_config.get("initial_cost", 0.0), + ) + + self._capital = Capital( + initial_cash=instance_config.get("initial_capital", 1000000.0) + ) + + self._risk_state = RiskState( + max_position_ratio=instance_config.get("max_position_ratio", 0.5), + stop_loss_ratio=instance_config.get("stop_loss_ratio", 0.05), + stop_profit_ratio=instance_config.get("stop_profit_ratio", 0.20), + max_single_loss=instance_config.get("max_single_loss", 10000.0), + ) + + logger.info( + f"StrategyContext initialized: instance_id={instance_id}, " + f"symbol={symbol}, capital={self._capital.initial_cash:.2f}" + ) + + # ==================== 数据访问接口(直接实现) ==================== + + def get_klines( + self, + symbol: Optional[str] = None, + period: str = "1m", + last_n: Optional[int] = None, + start: Optional[pd.Timestamp] = None, + end: Optional[pd.Timestamp] = None, + ) -> Optional[pd.DataFrame]: + """ + 获取K线数据(直接从缓存获取) + + 这是策略访问数据的主要方式 + + Args: + symbol: 标的代码,默认使用实例的 symbol + period: 周期 + last_n: 最近N条 + start: 开始时间 + end: 结束时间 + + Returns: + K线DataFrame,如果不存在返回None + """ + target_symbol = symbol or self.symbol + + # 1. 从缓存读取 + try: + data = self._cache_manager.get_klines(target_symbol, period) + if data is None: + logger.debug( + f"[{self.instance_id}] No cache data for {target_symbol}_{period}" + ) + return self._handle_cache_miss( + target_symbol, period, last_n, start, end + ) + + df = data.get("klines") + if df is None or df.empty: + logger.debug( + f"[{self.instance_id}] Empty cache for {target_symbol}_{period}" + ) + return self._handle_cache_miss( + target_symbol, period, last_n, start, end + ) + + # 2. 根据参数过滤数据 + result = self._filter_klines(df, last_n, start, end) + + if result is not None and not result.empty: + return result + else: + logger.warning( + f"[{self.instance_id}] Filtered result is empty for {target_symbol}_{period}" + ) + return None + + except Exception as e: + logger.error( + f"[{self.instance_id}] Error getting klines: {e}", exc_info=True + ) + return None + + def _filter_klines( + self, + df: pd.DataFrame, + last_n: Optional[int] = None, + start: Optional[pd.Timestamp] = None, + end: Optional[pd.Timestamp] = None, + ) -> Optional[pd.DataFrame]: + """ + 过滤K线数据 + + Args: + df: 原始DataFrame + last_n: 最近N条 + start: 开始时间 + end: 结束时间 + + Returns: + 过滤后的DataFrame + """ + result = df.copy() + + # 时间范围过滤 + if "timestamp" in result.columns: + if start is not None: + result = result[result["timestamp"] >= start] + if end is not None: + result = result[result["timestamp"] <= end] + + # 最近N条 + if last_n is not None and last_n > 0: + result = result.tail(last_n) + + return result + + def _handle_cache_miss( + self, + symbol: str, + period: str, + last_n: Optional[int], + start: Optional[pd.Timestamp], + end: Optional[pd.Timestamp], + ) -> Optional[pd.DataFrame]: + """ + 处理缓存未命中 + + Args: + symbol: 标的代码 + period: 周期 + last_n: 最近N条 + start: 开始时间 + end: 结束时间 + + Returns: + None(缓存未命中直接返回None,CacheManager会自动处理数据库降级) + """ + # 缓存未命中,返回None + # 注意:CacheManager已经在get_klines时处理了数据库降级 + logger.warning(f"[{self.instance_id}] No data available: {symbol}_{period}") + return None + + def get_indicators( + self, + symbol: Optional[str] = None, + period: str = "1m", + indicator_type: str = "MACD", + ) -> Optional[pd.DataFrame]: + """ + 获取指标数据 + + Args: + symbol: 标的代码,默认使用实例的 symbol + period: 周期 + indicator_type: 指标类型 + + Returns: + 指标DataFrame,如果不存在返回None + """ + target_symbol = symbol or self.symbol + try: + return self._cache_manager.get_indicator( + target_symbol, period, indicator_type + ) + except Exception as e: + logger.error( + f"[{self.instance_id}] Error getting indicators: {e}", exc_info=True + ) + return None + + # ==================== 状态访问接口 ==================== + + def get_position(self) -> Position: + """获取持仓信息(独立状态)""" + return self._position + + def get_capital(self) -> Capital: + """获取资金信息(独立状态)""" + return self._capital + + def get_risk_state(self) -> RiskState: + """获取风险状态(独立状态)""" + return self._risk_state + + def update_position(self, shares_change: float, cost_change: float): + """ + 更新持仓 + + Args: + shares_change: 持仓变化 + cost_change: 成本变化 + """ + self._position.update(shares_change, cost_change) + + def update_capital(self, amount: float): + """ + 更新资金 + + Args: + amount: 资金变化 + """ + self._capital.update(amount) + + # ==================== 工具方法 ==================== + + def get_cache_info(self, symbol: Optional[str] = None, period: str = "1m") -> dict: + """ + 获取缓存信息(用于调试) + + Args: + symbol: 标的代码 + period: 周期 + + Returns: + 缓存信息字典 + """ + target_symbol = symbol or self.symbol + try: + data = self._cache_manager.get_klines(target_symbol, period) + if data is None: + return {"exists": False} + + df = data.get("klines") + if df is None or df.empty: + return {"exists": True, "rows": 0} + + return { + "exists": True, + "rows": len(df), + "columns": list(df.columns), + "first_timestamp": df["timestamp"].iloc[0] + if "timestamp" in df.columns + else None, + "last_timestamp": df["timestamp"].iloc[-1] + if "timestamp" in df.columns + else None, + } + except Exception as e: + logger.error(f"[{self.instance_id}] Error getting cache info: {e}") + return {"error": str(e)} + + def get_status(self) -> dict: + """ + 获取上下文状态 + + Returns: + 状态字典 + """ + return { + "instance_id": self.instance_id, + "symbol": self.symbol, + "position": self._position.to_dict(), + "capital": self._capital.to_dict(), + "risk_state": self._risk_state.to_dict(), + } diff --git a/src/qtrade_server.py b/src/qtrade_server.py index 8789ebb..b3e22a9 100644 --- a/src/qtrade_server.py +++ b/src/qtrade_server.py @@ -5,40 +5,150 @@ QTrade Strategy Server - 使用WebSocketServer通信层 """ from typing import Optional +import signal +import sys from src.core.logger import get_logger +from src.core.config import Config from src.strategy_manager import StrategyManager from src.networks.server.ws_server import WebSocketServer +from src.cache.cache_manager import CacheManager +from src.database_manager.db_manager import DatabaseManager +from src.data_storage.mysql_storage import MySQLStorage logger = get_logger("QTradeServer") -# 策略管理器 +# 全局对象 strategy_manager: Optional[StrategyManager] = None +cache_manager: Optional[CacheManager] = None +db_manager: Optional[DatabaseManager] = None -def initialize_strategy_manager(config_dir: str = "config/strategies"): +def initialize_server( + config_file: str = "configs/backtest.yaml", + config_dir: str = "config/strategies", +) -> bool: """ - 初始化策略管理器 + 初始化服务器 Args: + config_file: 配置文件路径 config_dir: 策略配置文件目录 """ - global strategy_manager + global strategy_manager, cache_manager, db_manager - logger.info("Initializing StrategyManager...") + logger.info("Initializing QTrade Server...") - # 创建策略管理器 - strategy_manager = StrategyManager(config_dir) + # 1. 加载配置文件(合并全局配置) + try: + config = Config() + config.load_with_global(config_file) + logger.info(f"Configuration loaded from {config_file} with global.yaml") + except Exception as e: + logger.error(f"Failed to load configuration: {e}") + return False - # 初始化(加载配置并创建实例) + # 2. 初始化数据库管理器 + try: + db_manager = DatabaseManager() + logger.info("DatabaseManager initialized") + except Exception as e: + logger.warning(f"Failed to initialize DatabaseManager: {e}") + db_manager = None + return False + + # 3. 初始化缓存管理器(传入db_manager用于数据库降级) + cache_config = config.get("cache") + if cache_config is None: + # 使用默认缓存配置 + logger.warning("Cache configuration not found, using default configuration") + cache_config = { + "type": "memory", + "capacity": 1000, + "ttl": 3600, + } + + cache_manager = CacheManager(cache_config, db_manager=db_manager) + if cache_manager is None: + logger.error("Failed to create CacheManager") + return False + else: + logger.info("CacheManager initialized") + + # 4. 初始化策略管理器(传入共享资源) + strategy_manager = StrategyManager( + config_dir=config_dir, cache_manager=cache_manager + ) + if strategy_manager is None: + logger.error("Failed to create StrategyManager") + return False + + # 4. 加载并初始化所有策略 if not strategy_manager.initialize(): logger.error("Failed to initialize StrategyManager") return False - logger.info("StrategyManager initialized successfully") + logger.info("QTrade Server initialized successfully") return True +def save_cache_to_database(cache_manager: CacheManager, db_manager: DatabaseManager): + """ + 保存缓存数据到数据库 + + Args: + cache_manager: 缓存管理器 + db_manager: 数据库管理器 + """ + try: + # 获取缓存统计信息 + stats = cache_manager.get_stats() + if stats["size"] == 0: + logger.info("No cache data to save") + return + + logger.info(f"Saving {stats['size']} cache entries to database...") + + # 创建存储层(传入config和db_manager) + config = Config("configs/backtest.yaml") + storage = MySQLStorage(config._data, db_manager) + + saved_count = 0 + failed_count = 0 + + # 遍历所有缓存的symbol和period + for symbol, symbol_info in stats["symbols"].items(): + for period in symbol_info["periods"]: + try: + # 获取K线数据 + klines_data = cache_manager.get_klines(symbol, period) + + if klines_data is not None and not klines_data.empty: + # 保存到数据库 + count = storage.save_klines(symbol, period, klines_data) + if count > 0: + saved_count += 1 + logger.info( + f"✓ Saved cache: {symbol}_{period} ({count} rows)" + ) + else: + failed_count += 1 + logger.warning(f"✗ Failed to save: {symbol}_{period}") + else: + logger.debug(f"Skip empty cache: {symbol}_{period}") + + except Exception as e: + failed_count += 1 + logger.error(f"Error saving {symbol}_{period}: {e}", exc_info=True) + + logger.info( + f"Cache save completed: {saved_count} succeeded, {failed_count} failed" + ) + + except Exception as e: + logger.error(f"Failed to save cache to database: {e}", exc_info=True) + + async def handle_kline_data(message: dict) -> dict: """ 处理单条K线数据 @@ -135,7 +245,10 @@ async def handle_kline_batch(message: dict) -> dict: def start_server( - host: str = "0.0.0.0", port: int = 8000, config_dir: str = "config/strategies" + host: str = "0.0.0.0", + port: int = 8000, + config_file: str = "configs/backtest.yaml", + config_dir: str = "config/strategies", ): """ 启动服务器 @@ -143,6 +256,7 @@ def start_server( Args: host: 监听地址 port: 监听端口 + config_file: 配置文件路径 config_dir: 策略配置文件目录 """ logger.info("=" * 60) @@ -151,14 +265,34 @@ def start_server( logger.info(f"Host: {host}") logger.info(f"Port: {port}") logger.info(f"WebSocket URL: ws://{host}:{port}/ws/strategy") + logger.info(f"Config File: {config_file}") logger.info(f"Config Dir: {config_dir}") logger.info("=" * 60) - # 初始化策略管理器 - if not initialize_strategy_manager(config_dir): + # 初始化服务器 + if not initialize_server(config_file, config_dir): logger.error("Failed to initialize, server will not start") return + # 注册关闭钩子 + def on_shutdown(signum=None, frame=None): + logger.info("Server shutting down...") + + # 保存缓存到数据库 + if cache_manager and db_manager: + try: + logger.info("Saving cache to database...") + save_cache_to_database(cache_manager, db_manager) + logger.info("Cache saved successfully") + except Exception as e: + logger.error(f"Failed to save cache: {e}", exc_info=True) + + logger.info("Shutdown completed") + sys.exit(0) + + signal.signal(signal.SIGTERM, on_shutdown) + signal.signal(signal.SIGINT, on_shutdown) + # 创建WebSocket服务器 ws_server = WebSocketServer(title="QTrade Strategy Server", version="1.0.0") diff --git a/src/strategies/debug_strategy.py b/src/strategies/debug_strategy.py index ee13528..3ce733f 100644 --- a/src/strategies/debug_strategy.py +++ b/src/strategies/debug_strategy.py @@ -11,40 +11,38 @@ """ from typing import Dict, Any, Optional +from src.core.base_strategy import BaseStrategy -class DebugStrategy: +class DebugStrategy(BaseStrategy): """ 调试策略 只打印信息,不执行实际交易逻辑 """ - def __init__(self, **params): - """ - 初始化策略 - - Args: - print_every: 每N条K线打印一次(默认1,即每条都打印) - simulate_signal: 是否模拟生成信号(默认False) - signal_threshold: 模拟信号触发阈值(默认5.0,价格变化百分比) - """ - self.print_every = params.get("print_every", 1) - self.simulate_signal = params.get("simulate_signal", False) - self.signal_threshold = params.get("signal_threshold", 5.0) + def on_init(self): + """初始化回调""" + # 策略参数 + self.print_every = self.params.get("print_every", 1) + self.simulate_signal = self.params.get("simulate_signal", False) + self.signal_threshold = self.params.get("signal_threshold", 5.0) # 状态 self.kline_count = 0 self.last_price = None - print(f"[DebugStrategy] Initialized with params: {params}") + print(f"[DebugStrategy] Initialized: {self.context.instance_id}") + print(f" Symbol: {self.context.symbol}") + print(f" Params: {self.params}") + print(f" Initial Capital: {self.context.get_capital().initial_cash:.2f}") - def on_bar(self, bar_data: Dict[str, Any]) -> Optional[Dict[str, Any]]: + def compute(self, kline_data: Dict[str, Any]) -> Optional[Dict[str, Any]]: """ 处理K线数据 Args: - bar_data: K线数据字典 + kline_data: K线数据字典 Returns: 信号字典(如果生成信号)或None @@ -52,17 +50,17 @@ class DebugStrategy: self.kline_count += 1 # 提取K线数据 - symbol = bar_data.get("symbol", "UNKNOWN") - timestamp = bar_data.get("timestamp", "") - open_price = bar_data.get("open", 0) - high = bar_data.get("high", 0) - low = bar_data.get("low", 0) - close = bar_data.get("close", 0) - volume = bar_data.get("volume", 0) + symbol = kline_data.get("symbol", "UNKNOWN") + timestamp = kline_data.get("timestamp", "") + open_price = kline_data.get("open", 0) + high = kline_data.get("high", 0) + low = kline_data.get("low", 0) + close = kline_data.get("close", 0) + volume = kline_data.get("volume", 0) # 按设定频率打印K线信息 if self.kline_count % self.print_every == 0: - print(f"\n[DebugStrategy] K-line #{self.kline_count}") + print(f"\n[{self.context.instance_id}] K-line #{self.kline_count}") print(f" Symbol: {symbol}") print(f" Time: {timestamp}") print( @@ -70,6 +68,14 @@ class DebugStrategy: ) print(f" Volume: {volume}") + # 打印持仓和资金信息 + position = self.context.get_position() + capital = self.context.get_capital() + print( + f" Position: {position.shares:.2f} shares @ {position.avg_price:.2f}" + ) + print(f" Capital: {capital.available_cash:.2f}") + # 计算价格变化 if self.last_price is not None: price_change = ((close - self.last_price) / self.last_price) * 100 @@ -88,7 +94,7 @@ class DebugStrategy: "quantity": 100, "reason": f"Price increased by {price_change_pct:.2f}%", } - print(f"\n[DebugStrategy] 🟢 BUY Signal Generated!") + print(f"\n[{self.context.instance_id}] 🟢 BUY Signal Generated!") print(f" Reason: {signal['reason']}") elif price_change_pct < -self.signal_threshold: @@ -99,7 +105,7 @@ class DebugStrategy: "quantity": 100, "reason": f"Price decreased by {price_change_pct:.2f}%", } - print(f"\n[DebugStrategy] 🔴 SELL Signal Generated!") + print(f"\n[{self.context.instance_id}] 🔴 SELL Signal Generated!") print(f" Reason: {signal['reason']}") # 更新状态 @@ -107,18 +113,6 @@ class DebugStrategy: return signal - def compute(self, bar_data: Dict[str, Any]) -> Optional[Dict[str, Any]]: - """ - 处理K线数据(compute接口,与on_bar相同) - - Args: - bar_data: K线数据字典 - - Returns: - 信号字典(如果生成信号)或None - """ - return self.on_bar(bar_data) - def get_status(self) -> Dict[str, Any]: """ 获取策略状态 diff --git a/src/strategy_manager.py b/src/strategy_manager.py index 4c04b0d..24b7aa6 100644 --- a/src/strategy_manager.py +++ b/src/strategy_manager.py @@ -1,4 +1,4 @@ -""" +""" 策略管理器 (Strategy Manager) 负责: @@ -15,6 +15,7 @@ import yaml import importlib from src.core.logger import get_logger +from src.core.strategy_context import StrategyContext logger = get_logger("StrategyManager") @@ -29,15 +30,22 @@ class StrategyManager: - 动态加载策略类 """ - def __init__(self, config_dir: str = "config/strategies"): + def __init__( + self, + config_dir: str, + cache_manager, + ): """ 初始化策略管理器 Args: config_dir: 策略配置文件目录 - """ + cache_manager: 缓存管理器(共享实例) + """ self.config_dir = Path(config_dir) + # 直接持有共享资源 + self._cache_manager = cache_manager # 策略实例字典: {instance_id: strategy_object} self.instances: Dict[str, Any] = {} @@ -130,8 +138,20 @@ class StrategyManager: ) continue - # 创建策略实例 - strategy_obj = strategy_class(**params) + # 创建策略上下文 + context = StrategyContext( + cache_manager=self._cache_manager, + instance_id=instance_id, + symbol=symbol, + instance_config=config, + ) + + # 创建策略实例(传入context) + strategy_obj = strategy_class(context=context, **params) + + # 调用初始化回调 + if hasattr(strategy_obj, "on_init"): + strategy_obj.on_init() # 存储实例 self.instances[instance_id] = strategy_obj @@ -153,7 +173,7 @@ class StrategyManager: # 打印统计信息 logger.info("=" * 60) - logger.info(f"Strategy initialization completed:") + logger.info("Strategy initialization completed:") logger.info(f" Total instances: {len(self.instances)}") logger.info(f" Symbols covered: {len(self.symbol_index)}") for symbol, instances_list in self.symbol_index.items(): diff --git a/test_run.py b/test_run.py index 0247757..cdb918f 100644 --- a/test_run.py +++ b/test_run.py @@ -31,7 +31,10 @@ def start_server(): print("=" * 60) print("正在启动 QTrade Server...") print("=" * 60) - subprocess.run([sys.executable, "-m", "src.qtrade_server"], cwd=workspace) + try: + subprocess.run([sys.executable, "-m", "src.qtrade_server"], cwd=workspace) + except KeyboardInterrupt: + print("\n✓ 服务器已正常关闭") def start_client_newwindow(): @@ -52,7 +55,10 @@ def start_client(): print("\n" + "=" * 60) print("正在启动 Backtest Client...") print("=" * 60) - subprocess.run([sys.executable, "-m", "src.backtest.main"], cwd=workspace) + try: + subprocess.run([sys.executable, "-m", "src.backtest.main"], cwd=workspace) + except KeyboardInterrupt: + print("\n✓ 客户端已正常关闭") def main():