QTrade/docs/tech_designs/qtrade_server_cache_design.md

1530 lines
45 KiB
Markdown
Raw Normal View History

# 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
**状态**: 设计完成,待实现