主要修改: 1. CacheManager 负责数据库降级(单一职责) - 缓存未命中自动从数据库加载 - 移除 StrategyManager/Context 的 db_manager 依赖 2. 添加 StrategyContext 核心组件 - Position: 持仓管理 - Capital: 资金管理 - RiskState: 风险控制 - BaseStrategy: 策略基类 3. 配置与类型修复 - global.yaml 添加完整缓存配置 - 修复 Pylance 类型推断错误 - Config.load_with_global() 合并全局配置 4. 技术设计文档 - 架构重构总结 - 缓存设计方案 - Context 共享策略 - 接口最小化原则
902 lines
29 KiB
Markdown
902 lines
29 KiB
Markdown
# 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。
|