QTrade/docs/tech_designs/REFACTOR_SUMMARY.md
cuizhan 0f23037448 重构架构:实现单一职责原则和最小接口设计
主要修改:
1. CacheManager 负责数据库降级(单一职责)
   - 缓存未命中自动从数据库加载
   - 移除 StrategyManager/Context 的 db_manager 依赖

2. 添加 StrategyContext 核心组件
   - Position: 持仓管理
   - Capital: 资金管理
   - RiskState: 风险控制
   - BaseStrategy: 策略基类

3. 配置与类型修复
   - global.yaml 添加完整缓存配置
   - 修复 Pylance 类型推断错误
   - Config.load_with_global() 合并全局配置

4. 技术设计文档
   - 架构重构总结
   - 缓存设计方案
   - Context 共享策略
   - 接口最小化原则
2025-12-27 22:52:40 +08:00

547 lines
14 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 重构完成总结
> **日期**: 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接口