Compare commits

...

2 Commits

6 changed files with 287 additions and 1948 deletions

286
analyze_miniqmt_callback.py Normal file
View File

@ -0,0 +1,286 @@
"""
MiniQMT 实盘交易客户端适配器
负责业务逻辑:
- 连接 MiniQMT 交易接口
- 发送 K线数据到策略服务器
- 接收交易信号
- 执行实盘交易委托
"""
from re import L
import time
from datetime import datetime
from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
from xtquant.xttype import StockAccount
from xtquant import xtconstant
from xtquant import xtdata
from src.core.logger import Logger
from src.core.config import Config
STOCK_POOL = [
{"symbol": "601288.SH", "symbol_name": "农业银行", "period": "5m"},
# {"symbol": "600593.SH", "symbol_name": "大连圣亚", "period": "1m"},
# 添加更多股票...
]
def on_realtime_data(datas):
"""
实时行情数据回调
Args:
datas: 行情数据字典,格式为 {symbol: [data1, data2, ...]}
每个data包含: time, open, high, low, close, volume, amount等字段
"""
return
if not datas:
return
Logger.info("=" * 60)
Logger.info(f"收到实时行情数据,标的数量: {len(datas)}")
# 初始化消息字典
# 遍历每个标的的行情数据
symbols = datas.keys()
for symbol in symbols:
for data in datas[symbol]:
if data:
# data 格式示例:
# {
# 'time': 1768529940000, # 时间戳(毫秒)
# 'open': 7.24, # 开盘价
# 'high': 7.24, # 最高价
# 'low': 7.23, # 最低价
# 'close': 7.23, # 收盘价
# 'volume': 5798, # 成交量
# 'amount': 4193948.0, # 成交额
# 'settlementPrice': 0.0, # 结算价
# 'openInterest': 13, # 持仓量
# 'dr': 1.0, # 除权因子
# 'totaldr': 2.24, # 累计除权因子
# 'preClose': 7.18, # 前收盘价
# 'suspendFlag': 23 # 停牌标志
# }
# 解析时间戳
time_value = data.get("time")
readable_time = _parse_timestamp(time_value)
Logger.info(f" 股票代码: {symbol} | 时间: {readable_time} | ")
Logger.info(f"Data content: {data}")
Logger.info("------------------get_market_data_ex---------------------")
exDatas = xtdata.get_market_data_ex(
field_list=["time", "open", "high", "low", "close", "volume", "amount"],
stock_list=[symbol],
period="5m",
start_time="",
end_time="",
count=3, # 获取最近3条行数据
dividend_type="none", # 不复权
)
# 只有一个标的
for symbol, df in exDatas.items():
for _, row in df.iterrows():
# 解析时间, 这里的timestamp 非整数时间戳
readable_time = _parse_timestamp(row["time"])
Logger.info(
f" [get_market_data_ex] 股票代码: {symbol} | time: {row['time']} | 可读时间时间: {readable_time} | "
f"开盘价: {row['open']} | 收盘价: {row['close']} | "
f"最高价: {row['high']} | 最低价: {row['low']} | "
f"成交量: {row['volume']} | 成交额: {row['amount']}"
)
def _parse_timestamp(timestamp: int) -> str:
"""
解析时间戳为可读格式
Args:
timestamp: 时间戳(秒或毫秒)
Returns:
格式化的时间字符串
"""
if not isinstance(timestamp, (int, float)):
return "无效时间"
try:
# 判断是毫秒还是秒时间戳
if timestamp > 1e12:
dt = datetime.fromtimestamp(timestamp / 1000)
else:
dt = datetime.fromtimestamp(timestamp)
return dt.strftime("%Y-%m-%d %H:%M:%S")
except Exception as e:
Logger.warning(f"时间戳解析失败: {timestamp}, 错误: {e}")
return "时间解析失败"
class MiniQMTTraderCallback(XtQuantTraderCallback):
"""MiniQMT 交易回调"""
def __init__(self):
super().__init__()
def on_disconnected(self):
"""连接断开"""
Logger.warning("MiniQMT 连接断开")
def on_stock_order(self, order):
"""
委托回报推送
Args:
order: XtOrder对象
"""
Logger.info("-------------on_stock_order called-------------")
Logger.info(f"parmameter order: {order}")
Logger.info(
f"委托回报: {order.stock_code}, "
f"状态={order.order_status}, "
f"系统编号={order.order_sysid}"
)
def on_stock_trade(self, trade):
"""
成交变动推送
Args:
trade: XtTrade对象
"""
Logger.info("-------------on_stock_trade called-------------")
Logger.info(f"parmameter trade: {trade}")
Logger.info(
f"成交回报: {trade.stock_code}, "
f"订单ID={trade.order_id}, "
f"成交价={trade.traded_price}, "
f"成交量={trade.traded_volume}"
f"order_id={trade.order_id}"
)
def on_order_error(self, order_error):
"""
委托失败推送
Args:
order_error: XtOrderError对象
"""
Logger.error(
f"委托失败: 订单ID={order_error.order_id}, "
f"错误码={order_error.error_id}, "
f"错误信息={order_error.error_msg}"
)
def on_cancel_error(self, cancel_error):
"""
撤单失败推送
Args:
cancel_error: XtCancelError对象
"""
Logger.info("-------------on_cancel_error called-------------")
Logger.info(f"parmameter cancel_error: {cancel_error}")
Logger.error(
f"撤单失败: 订单ID={cancel_error.order_id}, "
f"错误码={cancel_error.error_id}, "
f"错误信息={cancel_error.error_msg}"
)
def on_order_stock_async_response(self, response):
"""
异步下单回报
Args:
response: XtOrderResponse对象
"""
Logger.info("-------------on_order_stock_async_response called-------------")
Logger.info(f"parmameter response: {response}")
Logger.info(
f"异步下单回报: 订单ID={response.order_id}, 响应={response.order_remark}"
)
def on_account_status(self, status):
"""
账户状态变化推送
Args:
status: XtAccountStatus对象
"""
Logger.info("-------------on_account_status called-------------")
Logger.info(f"parmameter status: {status}")
Logger.info(f"账户状态: {status.account_id}, 状态={status.account_type}")
def main():
"""实盘交易主函数"""
config = Config.initialize("production")
Logger.initialize("xtquant_miniqmt_trader")
Logger.info("=" * 60)
Logger.info("启动 QTrade 实盘交易客户端")
Logger.info("=" * 60)
if not config:
Logger.error("✗ 配置加载失败,退出程序")
return
Logger.info("配置加载完成")
# 从配置获取参数
miniqmt_path = config.get("miniqmt.userdata_path")
session_id = config.get("miniqmt.session_id")
account_id = config.get("miniqmt.account.account_id")
account_type = config.get("miniqmt.account.account_type")
Logger.info(f"MiniQMT 路径: {miniqmt_path}")
Logger.info(f"交易账号: {account_id}")
Logger.info(f"账户类型: {account_type}")
xt_trader = XtQuantTrader(miniqmt_path, session_id)
account = StockAccount(account_id, account_type)
callback = MiniQMTTraderCallback()
# 注册回调
xt_trader.register_callback(callback)
# 启动交易线程
xt_trader.start()
# 建立交易连接
connect_result = xt_trader.connect()
if connect_result != 0:
Logger.error(f"MiniQMT 连接失败: {connect_result}")
return False
Logger.info("MiniQMT 连接成功")
subscribe_result = xt_trader.subscribe(account)
if subscribe_result != 0:
Logger.error(f"MiniQMT 订阅账户失败: {subscribe_result}")
return False
# 交易股票池
if len(STOCK_POOL) == 0:
Logger.warning("交易股票池为空,表示全部股票可交易")
else:
for symbol_info in STOCK_POOL:
symbol = symbol_info.get("symbol")
symbol_name = symbol_info.get("name", "")
symbol_period = symbol_info.get("period", "1m")
xtdata.subscribe_quote(
symbol, period=symbol_period, callback=on_realtime_data
)
Logger.info(
f"Subscribed to quote: {symbol} ({symbol_name}), period={symbol_period}"
)
Logger.info("等待3秒初始化完成...")
time.sleep(3)
try:
xt_trader.run_forever()
except KeyboardInterrupt:
Logger.info("收到退出信号,正在关闭连接...")
if __name__ == "__main__":
main()

View File

@ -48,7 +48,7 @@ miniqmt:
userdata_path: "D:\\国金QMT交易端模拟\\userdata_mini" # MiniQMT userdata_mini 路径 userdata_path: "D:\\国金QMT交易端模拟\\userdata_mini" # MiniQMT userdata_mini 路径
session_id: 123456 # 会话ID(不同策略使用不同ID) session_id: 123456 # 会话ID(不同策略使用不同ID)
account: account:
account_id: "40004091" # 交易账号 account_id: "40004091" # 模拟交易账号
account_type: "STOCK" # 账户类型(STOCK/HUGANGTONG/SHENGANGTONG) account_type: "STOCK" # 账户类型(STOCK/HUGANGTONG/SHENGANGTONG)
# ==================== 下载数据源配置 ==================== # ==================== 下载数据源配置 ====================

View File

@ -1,546 +0,0 @@
# 重构完成总结
> **日期**: 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接口

View File

@ -1,955 +0,0 @@
# 缓存机制设计文档
> 版本:v2.1
> 日期:2025-12-20
> 状态:已实现(Phase 1&2,v2.1 统一命名)
---
## 设计背景
量化交易系统在运行过程中需要频繁读取K线和技术指标数据,直接从MySQL数据库查询会产生较大的性能开销。为提升系统响应速度,需要设计一个内存缓存层来优化数据访问性能。
**核心需求**:
- 回测环境和实盘环境采用统一的缓存机制,降低实现复杂度
- 系统启动时预加载指定时间范围的数据(默认1个月,可配置)
- 支持透明缓存:自动加载缺失数据
- 与存储层解耦:依赖StorageLayer抽象,不依赖具体实现
- 支持后续扩展至账户信息、持仓记录、交易订单等业务数据
**重构改进(v2.0)**:
- ✅ 从依赖DatabaseManager改为依赖StorageLayer(存储抽象)
- ✅ 实现透明缓存:缓存未命中自动从存储加载
- ✅ 新增auto_loads指标:跟踪自动加载次数
- ✅ 移除直接数据库查询方法,统一通过storage
---
## 设计原则
### 简单性优先
采用轻量级实现方案,不引入Redis等外部依赖组件。基于Python内置字典和Pandas DataFrame构建缓存层。
- **统一接口**:提供get/preload/invalidate三个核心方法
- **透明缓存**:缓存未命中自动加载,上层无感知
- **双模式设计**:static模式(回测环境)和dynamic模式(实盘环境),通过配置文件区分
- **最小化接口**:保持接口简洁,避免过度设计
### 架构统一性
```
DataService (统一入口)
↓
CacheManager (缓存层)
↓
StorageLayer (存储抽象)
↓
├─ MySQLStorage (MySQL实现)
├─ ParquetStorage (Parquet实现 - 未来)
└─ HDF5Storage (HDF5实现 - 未来)
```
**关键改进(v2.1)**:
- ✅ CacheManager不再直接依赖DatabaseManager
- ✅ 通过StorageLayer抽象,支持可插拔的存储后端
- ✅ 统一命名:storage → data_storage, validator → data_validator
- ✅ 路径:`src/data_storage/storage_layer.py`
- 回测和实盘使用相同的缓存逻辑,运行差异通过配置控制:
- 回测环境:静态加载模式,数据永不过期,不执行淘汰策略
- 实盘环境:动态刷新模式,数据过期时间5-10分钟,采用LRU淘汰算法
---
## 数据结构
### 缓存键设计
```python
# 缓存键格式
cache_key = f"{symbol}_{period}"
# 示例:
# "159915.SZ_1m" - 标的159915.SZ的1分钟周期数据
# "601658.SH_1d" - 标的601658.SH的日线周期数据
```
### 缓存内容
```python
_cache = {
"159915.SZ_1m": {
"klines": DataFrame, # K线数据
"macd": DataFrame, # MACD指标
"kdj": DataFrame, # KDJ指标
"rsi": DataFrame, # RSI指标
"boll": DataFrame, # BOLL指标
"meta": {
"time_range": (start_date, end_date), # 数据时间范围
"loaded_at": datetime, # 什么时候加载的
"last_access": datetime, # 最后一次访问
"access_count": int, # 访问了多少次
}
}
}
```
### 设计优势
- **可读性强**:数据结构清晰,便于理解和维护
- **性能优异**:字典查找时间复杂度O(1),DataFrame切片操作高效
- **易于调试**:支持随时查看缓存状态
- **扩展性好**:添加新指标只需增加对应的键值对
---
## 配置方案
### 全局统一配置
```yaml
# configs/config.yaml
cache:
enabled: true
mode: "static" # 运行模式:static(回测) / dynamic(实盘)
preload:
enabled: true # 是否启动时预加载
time_range: "1M" # 预加载时间范围:1M/3M/6M/1Y
periods: ["1m", "1d"] # 预加载的周期列表
refresh:
interval: 60 # 刷新检查间隔(秒),仅dynamic模式生效
eviction:
strategy: "LRU" # 淘汰策略:LRU/LFU,仅dynamic模式生效
max_items: 100 # 缓存项数量上限
ttl:
klines: 300 # K线数据TTL(秒),仅dynamic模式生效
indicators: 600 # 指标数据TTL(秒),仅dynamic模式生效
max_memory_mb: 1024 # 内存上限(MB)
```
### 配置说明
| 参数 | 说明 | static模式 | dynamic模式 |
| ---------- | ---------------------- | ---------- | ------------ |
| mode | 运行模式,决定缓存行为 | 必需 | 必需 |
| preload | 启动预加载配置 | 生效 | 生效 |
| refresh | 定期刷新配置 | **忽略** | 生效 |
| eviction | 淘汰策略配置 | **忽略** | 生效 |
| ttl | 数据过期时间 | **忽略** | 生效 |
| preload | ✅ | ✅ | 都需要预加载 |
| refresh | ❌ | ✅ | 实盘要刷新 |
| eviction | ❌ | ✅ | 实盘要淘汰 |
| ttl | 无限 | 5-10分钟 | 过期时间 |
| max_memory | 1GB | 512MB | 内存上限 |
---
## 内存占用估算
### 单只股票数据量
**1分钟K线(1个月)**:
```
交易天数:21天
每天K线:240条(4小时交易)
总数据量:21 × 240 = 5,040条
单条K线:
- timestamp: 8字节
- OHLC: 32字节(4个float64)
- volume/amount: 16字节
- symbol: 20字节
- DataFrame开销: ×2
实际占用:~150字节/条 × 5,040 = 0.74 MB
```
**技术指标(1个月)**:
```
4个指标(MACD/KDJ/RSI/BOLL)
每个指标3-4列
单条数据:~200字节
实际占用:~200字节/条 × 5,040 = 0.96 MB
```
**1日K线(1个月)**:
```
只有21条数据,忽略不计
```
### 100只股票总内存
```
单只股票:1.7 MB(1m K线+指标 + 1d K线+指标)
100只股票:170 MB(纯数据)
Python开销:
- 字典结构:+20%
- DataFrame:+30%
- 字符串:+10%
实际占用:170 × 1.6 = 272 MB
系统预留:272 × 1.5 = 408 MB
```
**估算结论**:100只标的 × 1个月 × 2周期 ≈ **400-500 MB**
### 推荐配置
- **回测环境**:建议配置1GB(预留充足余量,支持加载更多历史数据)
- **实盘环境**:建议配置512MB(满足基本需求,控制内存占用)
- **多周期场景**:如需支持5m/15m/30m周期,建议配置扩展至1-2GB
---
## 工作流程
### 数据读取流程
```
1. 接收请求:get_klines(symbol, start, end, period)
↓
2. 生成缓存键:"{symbol}_{period}"
↓
3. 缓存查找:
- 缓存命中且时间范围覆盖且未过期
→ 直接返回数据切片
- 缓存部分命中
→ 增量加载缺失时间段数据
- 缓存未命中
→ 全量加载所需数据
↓
4. 更新缓存(针对新加载的数据)
↓
5. 返回查询结果
```
### 启动预加载
```python
# 系统启动时自动执行
def startup():
# 1. 初始化CacheManager
cache = CacheManager(config, db_manager)
# 2. 读取配置
preload_config = config.get('cache.preload')
if not preload_config.get('enabled'):
return
# 3. 确定加载范围
time_range = preload_config.get('time_range', '1M')
periods = preload_config.get('periods', ['1m', '1d'])
# 4. 从调用方获取标的列表(不从配置读取SQL)
# 回测:从回测配置获取
# 实盘:从交易系统获取持仓+关注列表
symbols = get_symbols_from_caller() # 由上层提供
# 5. 批量加载
for symbol in symbols:
for period in periods:
klines = db_manager.load_klines(symbol, period, ...)
indicators = db_manager.load_indicators(symbol, period, ...)
cache.set(f"{symbol}_{period}", data)
# 6. 输出统计
# [INFO] 预加载完成: 200项(100股×2周期), 内存占用=450MB
```
### 关闭保存策略
```python
def shutdown():
# 市场数据:一般不需要保存(都在数据库里)
market_cache.shutdown(save_data=False)
# 业务数据:必须保存(账户、持仓等)
business_cache.shutdown(save_data=True)
```
**持久化策略**:
- **市场数据**:通常无需持久化(只读数据,数据库为主数据源)
- **脏数据**:实时计算生成的新指标数据需要持久化
- **业务数据**:账户信息、持仓记录、交易订单等必须持久化
- **统计信息**(可选):缓存命中率、热点数据等分析数据
---
## 核心接口
### CacheManager类(v2.0 实现)
```python
class CacheManager:
"""
智能缓存管理器
v2.0改进:
- 依赖StorageLayer抽象,不依赖具体存储实现
- 透明缓存:自动加载缺失数据
- 新增auto_loads指标
"""
def __init__(self, storage: StorageLayer, indicator_manager):
"""
初始化缓存管理器
Args:
storage: 存储层抽象(不再是DatabaseManager)
indicator_manager: 指标管理器
"""
self.storage = storage # ← 关键改进:依赖抽象
self.indicator_manager = indicator_manager
self._cache = {}
self._metrics = {
'hits': 0,
'misses': 0,
'auto_loads': 0 # ← 新增:自动加载次数
}
def get(
self,
symbol: str,
period: str,
start_date: datetime,
end_date: datetime,
data_type: str = 'klines',
indicator_name: Optional[str] = None,
**indicator_params
) -> Optional[pd.DataFrame]:
"""
获取数据(透明缓存)
流程:
1. 检查缓存是否命中
2. 命中且覆盖范围足够 → 返回切片
3. 未命中 → 自动从storage加载并缓存
新特性:透明缓存,上层无需关心缓存是否命中
"""
key = f"{symbol}_{period}"
# 检查缓存
if key in self._cache:
cached = self._cache[key]
# 检查时间范围是否覆盖
if self._covers_range(cached, start_date, end_date):
self._metrics['hits'] += 1
return self._slice_data(cached, start_date, end_date, data_type)
# 缓存未命中,自动加载 ← 关键改进
self._metrics['misses'] += 1
self._metrics['auto_loads'] += 1
logger.info(f"缓存未命中,自动加载:{symbol}_{period}")
if data_type == 'klines':
# 从storage加载K线
df = self.storage.load_klines(symbol, period, start_date, end_date)
elif data_type == 'indicator':
# 从storage加载指标
df = self.storage.load_indicators(
symbol, period, indicator_name, start_date, end_date
)
# 如果指标不存在,自动计算
if df is None:
klines = self.storage.load_klines(symbol, period, start_date, end_date)
if klines is not None:
df = self.calculate_and_cache_indicator(
symbol, period, indicator_name, klines, **indicator_params
)
# 加载成功,缓存数据
if df is not None:
if key not in self._cache:
self._cache[key] = {'klines': None, 'indicators': {}}
if data_type == 'klines':
self._cache[key]['klines'] = df
else:
self._cache[key]['indicators'][indicator_name] = df
return df
def preload(
self,
symbol: str,
period: str,
start_date: datetime,
end_date: datetime
) -> None:
"""
预加载数据到缓存
改进:统一使用storage.load_klines()
"""
logger.info(f"预加载缓存:{symbol}_{period}")
# 从storage加载
df = self.storage.load_klines(symbol, period, start_date, end_date)
if df is not None:
key = f"{symbol}_{period}"
self._cache[key] = {
'klines': df,
'indicators': {},
'meta': {
'time_range': (start_date, end_date),
'loaded_at': datetime.now()
}
}
logger.info(f"预加载成功:{symbol}_{period}, {len(df)}行")
def invalidate(self, symbol: str = None, period: str = None) -> None:
"""失效缓存"""
if symbol is None and period is None:
self._cache.clear() # 清空全部
elif period is None:
# 清空某个symbol的所有周期
keys = [k for k in self._cache.keys() if k.startswith(f"{symbol}_")]
for k in keys:
del self._cache[k]
else:
# 清空特定缓存
key = f"{symbol}_{period}"
self._cache.pop(key, None)
def get_metrics(self) -> dict:
"""获取缓存指标"""
total = self._metrics['hits'] + self._metrics['misses']
hit_rate = self._metrics['hits'] / total if total > 0 else 0
return {
'hits': self._metrics['hits'],
'misses': self._metrics['misses'],
'auto_loads': self._metrics['auto_loads'], # ← 新增指标
'hit_rate': hit_rate,
'cache_size': len(self._cache)
}
def calculate_and_cache_indicator(
self,
symbol: str,
period: str,
indicator_name: str,
klines: pd.DataFrame,
**params
) -> pd.DataFrame:
"""计算指标并缓存"""
# 使用IndicatorManager计算
indicator_df = self.indicator_manager.calculate(
indicator_name, klines, **params
)
if indicator_df is not None:
# 缓存指标数据
key = f"{symbol}_{period}"
if key not in self._cache:
self._cache[key] = {'klines': klines, 'indicators': {}}
self._cache[key]['indicators'][indicator_name] = indicator_df
# 保存到存储(可选)
self.storage.save_indicators(
symbol, period, indicator_name, indicator_df
)
return indicator_df
def _covers_range(self, cached, start_date, end_date) -> bool:
"""检查缓存是否覆盖所需时间范围"""
if 'meta' not in cached:
return False
cache_start, cache_end = cached['meta']['time_range']
return cache_start <= start_date and cache_end >= end_date
def _slice_data(
self,
cached,
start_date,
end_date,
data_type
) -> pd.DataFrame:
"""从缓存数据中切片"""
if data_type == 'klines':
df = cached['klines']
else:
df = cached['indicators'].get(data_type)
if df is None:
return None
# 时间范围切片
mask = (df['timestamp'] >= start_date) & (df['timestamp'] <= end_date)
return df[mask]
```
### 关键改进说明
| 特性 | v1.0设计 | v2.0实现 | 改进 |
| -------- | --------------- | ---------------- | -------------------- |
| 存储依赖 | DatabaseManager | StorageLayer | ✅ 解耦,支持多种存储 |
| 缓存策略 | 手动加载 | 透明缓存 | ✅ 自动加载,上层无感 |
| 指标 | hits/misses | +auto_loads | ✅ 更好的监控 |
| 数据加载 | _load_from_db() | storage.load_*() | ✅ 统一接口 |
| 指标计算 | 手动触发 | 自动计算+缓存 | ✅ 更智能 |
### 日志输出
```python
# 回测模式(简单日志)
[CACHE] MISS: 159915.SZ_1m, loading from DB
[CACHE] HIT : 159915.SZ_1m, slice 2025-12-01 to 2025-12-15
[CACHE] STATS: size=10, hit_rate=85%, memory=150MB
# 实盘模式(详细日志)
[CACHE] MISS: 159915.SZ_1m, loading from DB
[CACHE] HIT : 159915.SZ_1m, slice 2025-12-01 to 2025-12-15
[CACHE] EXPIRED: 159915.SZ_1m, age=320s > ttl=300s, reloading
[CACHE] EVICT: 601658.SH_1d, LRU, access_count=2, free 50MB
[CACHE] STATS: size=50/50, hit_rate=75%, memory=480/512MB
```
---
## 扩展到业务数据
### 数据分类设计
市场数据和业务数据的特性存在显著差异:
| 特性 | 市场数据 | 业务数据 |
| ------ | ---------------- | -------------- |
| 数据量 | 大(数百MB级别) | 小(数MB级别) |
| 读写 | 只读 | 频繁读写 |
| 数据源 | 数据库 | 内存主导 |
| 保存 | 可选 | 必须持久化 |
| 过期 | 支持TTL机制 | 实时有效性 |
### 架构扩展设计
```python
class CacheManager:
def __init__(self, config, db_manager):
# 分类管理缓存模块
self.market_cache = MarketDataCache(config, db_manager)
self.business_cache = BusinessDataCache(config, db_manager)
def get(self, data_type, key, **kwargs):
"""统一数据访问接口"""
if data_type in ['klines', 'indicators']:
return self.market_cache.get(data_type, key, **kwargs)
elif data_type in ['accounts', 'positions', 'orders', 'trades']:
return self.business_cache.get(data_type, key, **kwargs)
def shutdown(self):
# 市场数据:可选持久化
self.market_cache.shutdown(save_data=False)
# 业务数据:强制持久化
self.business_cache.shutdown(save_data=True)
```
### 业务数据缓存实现
```python
class BusinessDataCache:
def __init__(self, config, db_manager):
self._cache = {
'accounts': {}, # {account_id: Account}
'positions': {}, # {account_id: [Position]}
'orders': {}, # {order_id: Order}
'trades': {}, # {trade_id: Trade}
}
self._dirty = {
'accounts': set(),
'positions': set(),
'orders': set(),
'trades': set(),
}
def set(self, data_type, key, value, immediate_save=False):
"""设置数据并标记为脏数据"""
self._cache[data_type][key] = value
self._dirty[data_type].add(key)
# 关键操作支持立即持久化
if immediate_save:
self._save_single(data_type, key, value)
def shutdown(self, save_data=True):
"""关闭时持久化所有脏数据"""
if not save_data:
return
# 持久化账户信息
for account_id in self._dirty['accounts']:
account = self._cache['accounts'][account_id]
self.db_manager.save_account(account)
# 持久化持仓记录
for account_id in self._dirty['positions']:
positions = self._cache['positions'][account_id]
self.db_manager.save_positions(positions)
# 持久化订单信息
for order_id in self._dirty['orders']:
order = self._cache['orders'][order_id]
self.db_manager.save_order(order)
# 持久化成交记录
for trade_id in self._dirty['trades']:
trade = self._cache['trades'][trade_id]
self.db_manager.save_trade(trade)
```
### 配置扩展方案
```yaml
cache:
# 市场数据配置(已有配置)
market_data:
max_memory_mb: 512
# ...
# 业务数据配置(新增配置)
business_data:
max_memory_mb: 64 # 业务数据内存上限
accounts:
cache_all: true # 缓存所有账户信息
save_on_change: true # 数据变化时标记脏标志
save_interval: 300 # 自动持久化间隔5分钟
positions:
cache_all: true
save_on_change: true
save_interval: 60 # 持仓变化频繁,1分钟持久化
orders:
cache_recent: true # 仅缓存近期订单
recent_days: 7 # 缓存最近7天订单
save_on_change: true
trades:
cache_recent: true
recent_days: 7
save_on_change: true
```
### 内存占用估算(扩展后)
```
市场数据(100只标的):400-500 MB
业务数据(10个账户):
- 账户信息: 10 × 1KB = 10 KB
- 持仓记录: 10账户 × 20持仓 × 500B = 100 KB
- 订单数据: 7天 × 100单/天 × 1KB = 700 KB
- 成交记录: 7天 × 100笔/天 × 1KB = 700 KB
- 小计: ~2 MB
总计: 500 MB + 2 MB ≈ 500 MB
```
---
## 使用示例
### 基本用法(v2.0)
```python
from src.data.mysql_storage import MySQLStorage
from src.cache.cache_manager import CacheManager
from src.data.data_service import DataService
# 1. 初始化存储层(不再直接用DatabaseManager)
storage = MySQLStorage(config)
# 2. 初始化缓存(依赖StorageLayer)
cache = CacheManager(storage, indicator_manager)
# 3. 创建数据服务
service = DataService(config, storage, cache)
# 4. 获取数据(透明缓存,自动加载)
df = service.get_klines(
symbol="000001.SZ",
period="1d",
start_date="2024-01-01",
end_date="2024-12-31"
)
# 第一次:缓存未命中,自动从storage加载
# 第二次:缓存命中,直接返回
# 5. 获取指标(自动计算并缓存)
macd = service.get_indicator(
symbol="000001.SZ",
period="1d",
indicator_name="macd",
start_date="2024-01-01",
end_date="2024-12-31"
)
# 6. 查看缓存指标
metrics = cache.get_metrics()
print(metrics)
# {
# 'hits': 5,
# 'misses': 2,
# 'auto_loads': 2, ← 新增:自动加载次数
# 'hit_rate': 0.71,
# 'cache_size': 3
# }
```
### 预加载缓存
```python
# 系统启动时预加载
symbols = ["000001.SZ", "600000.SH", "600519.SH"]
for symbol in symbols:
cache.preload(
symbol=symbol,
period="1d",
start_date=datetime.now() - timedelta(days=30),
end_date=datetime.now()
)
logger.info("缓存预加载完成")
```
### 手动失效缓存
```python
# 清空全部缓存
cache.invalidate()
# 清空某个标的的所有周期
cache.invalidate("000001.SZ")
# 清空特定缓存
cache.invalidate("000001.SZ", "1d")
```
---
## 调试工具
### 查看缓存状态
```python
# 总体统计
stats = provider.cache.get_stats()
print(stats)
# {'size': 200, 'hit_rate': 0.85, 'memory_mb': 450, 'items': [...]}
# 查看某个缓存详情
info = provider.cache.inspect("159915.SZ_1m")
print(info)
# {
# 'data_range': (2025-11-01, 2025-12-19),
# 'rows': 2400,
# 'loaded_at': '2025-12-19 10:00:00',
# 'last_access': '2025-12-19 10:05:23',
# 'access_count': 15,
# 'age_seconds': 323,
# 'expired': False
# }
```
### 手动操作
```python
# 清空全部缓存
provider.cache.clear()
# 失效某个股票的缓存
provider.cache.invalidate("159915.SZ")
# 失效特定缓存
provider.cache.invalidate("159915.SZ", "1m")
# 手动触发保存
provider.cache.save_now()
```
### 性能分析
```python
# 启用性能日志
cache.enable_profiling()
# 运行策略...
# 查看报告
report = cache.get_performance_report()
# {
# 'total_requests': 1000,
# 'cache_hits': 850,
# 'cache_misses': 150,
# 'hit_rate': 0.85,
# 'avg_hit_time_ms': 0.5,
# 'avg_miss_time_ms': 50.2,
# 'slowest_queries': [...]
# }
```
---
## 实现计划
### Phase 1:基础功能 ✅ **已完成**
- [x] CacheManager基础类
- [x] 依赖StorageLayer抽象(不再依赖DatabaseManager)
- [x] 透明缓存:get()方法自动加载
- [x] preload()预加载方法
- [x] invalidate()失效缓存
- [x] get_metrics()指标统计
- [x] auto_loads指标
**实际代码量**:~200行,已在Phase 1完成
**状态**:✅ 已实现并测试通过
### Phase 2:指标计算 ✅ **已完成**
- [x] calculate_and_cache_indicator()自动计算指标
- [x] 指标数据缓存
- [x] 指标自动保存到存储
**实际代码量**:+80行
**状态**:✅ 已实现
### Phase 3:动态模式(未来按需实现)
- [ ] dynamic模式
- [ ] TTL过期机制
- [ ] LRU淘汰策略
- [ ] 定期刷新
**估算工作量**:+150行代码,半天
**优先级**:中(实盘环境需要时实现)
### Phase 4:业务数据缓存(未来扩展)
- [ ] 账户、持仓缓存
- [ ] 订单、成交缓存
- [ ] 自动持久化机制
**估算工作量**:+200行代码,1天
**优先级**:低(有交易功能时再实现)
---
## 性能数据(实测)
### 缓存效果
| 场景 | 命中率 | 平均响应时间 |
| ---------------- | ------ | ------------------------------ |
| 回测(预加载后) | > 95% | < 1ms |
| 回测(冷启动) | ~60% | ~50ms(首次加载) |
| 实盘 | > 80% | < 1ms(命中)/ ~50ms(未命中) |
### 内存占用
| 数据规模 | 实际占用 | 说明 |
| -------------------- | -------- | -------------- |
| 1只标的1个月1d数据 | ~2MB | K线+4个指标 |
| 100只标的1个月1d数据 | ~200MB | 实测数据 |
| 10只标的1个月1m数据 | ~100MB | 分钟级数据量大 |
### 自动加载统计
```python
# 运行一段时间后查看指标
metrics = cache.get_metrics()
print(f"命中率: {metrics['hit_rate']:.2%}")
print(f"自动加载次数: {metrics['auto_loads']}")
# 输出示例:
# 命中率: 85.00%
# 自动加载次数: 3
```
---
## 注意事项
### 渐进式实现原则
- 优先实现Phase 1,满足基本需求后再扩展
- 回测场景使用static模式已完全满足需求
- 实盘环境需要时再实现dynamic模式
- 避免一次性实现所有功能导致过度设计
### 配置灵活性
- 支持通过配置文件关闭缓存(enabled=false)便于调试
- 内存资源不足时可减小preload时间范围
- TTL参数支持实时调整优化
- 日志级别可按需配置
### 性能监控
- 定期检查hit_rate,低于80%需进行优化
- 内存占用超过90%上限需扩容或调整配置
- 记录并分析慢查询日志
### 数据一致性
- 业务数据必须确保持久化成功
- 关键操作使用immediate_save参数
- 系统关闭时确保shutdown方法被正确调用
- 建议增加异常恢复机制保障数据安全
---
## 总结
### 设计核心优势
1. **实现简洁**:基于Python字典实现,无需外部服务依赖
2. **架构解耦**:依赖StorageLayer抽象,支持可插拔存储后端
3. **透明缓存**:自动加载缺失数据,上层无感知
4. **配置灵活**:配置驱动设计,支持运行时参数调整
5. **调试友好**:日志输出清晰,状态信息可查询
6. **扩展便捷**:新增数据类型仅需少量代码改动
### v2.0核心改进
| 方面 | v1.0设计 | v2.0实现 | 收益 |
| ------------ | --------------- | ------------ | -------------------- |
| **存储依赖** | DatabaseManager | StorageLayer | ✅ 解耦,支持多存储 |
| **缓存策略** | 手动加载 | 透明缓存 | ✅ 自动化,易用性提升 |
| **监控指标** | hits/misses | +auto_loads | ✅ 更好的可观测性 |
| **指标计算** | 外部触发 | 自动计算 | ✅ 一体化体验 |
| **测试友好** | 依赖具体实现 | 依赖抽象 | ✅ 易Mock,易测试 |
### 实施状态
- ✅ **Phase 1&2已完成**:基础缓存+指标计算
- ⏳ **Phase 3待实现**:动态模式(实盘需要时)
- ⏳ **Phase 4待扩展**:业务数据缓存(有交易功能时)
### 下一步计划
1. **短期**:在实际使用中收集性能数据,优化缓存策略
2. **中期**:实现dynamic模式,支持实盘环境
3. **长期**:扩展到业务数据缓存(账户、持仓、订单)
---
**文档维护者:** QTrade开发团队
**最后更新:** 2025-12-20
**相关文档:** [数据层架构设计](./data_layer_design.md)

View File

@ -1,446 +0,0 @@
# QTrade WebSocket通信协议规范 v1.0
## 1. 连接信息
- **服务器地址**: `ws://localhost:8000/ws/strategy`
- **协议**: WebSocket
- **数据格式**: JSON
- **字符编码**: UTF-8
- **协议版本**: v1.0
## 2. 协议头(Protocol Header)
所有消息必须包含协议头,用于版本控制和消息识别。
**协议头结构**:
```json
{
"header": {
"version": "1.0",
"msg_id": "uuid-string",
"timestamp": "2024-12-24 19:00:00.000"
},
...
}
```
**字段说明**:
| 字段 | 类型 | 必填 | 说明 |
| --------- | ------ | ---- | ----------------------------------------- |
| version | string | 是 | 协议版本号,当前为"1.0" |
| msg_id | string | 是 | 消息唯一ID,建议使用UUID |
| timestamp | string | 是 | 消息时间戳,格式: YYYY-MM-DD HH:MM:SS.mmm |
## 3. 消息类型
### 3.1 客户端请求消息(K线数据)
**消息类型**: `KLINE_DATA` 或 `KLINE_DATA_BATCH`
#### 3.1.1 单条K线数据
**数据结构**:
```json
{
"header": {
"version": "1.0",
"msg_id": "550e8400-e29b-41d4-a716-446655440000",
"timestamp": "2024-12-24 19:00:00.000"
},
"msg_type": "KLINE_DATA",
"symbol": "000001.SZ",
"period": "1d",
"kline_time": "2024-01-01 09:30:00",
"data": {
"open": 10.50,
"high": 10.80,
"low": 10.40,
"close": 10.75,
"volume": 1000000
}
}
```
#### 3.1.2 批量K线数据
**数据结构**:
```json
{
"header": {
"version": "1.0",
"msg_id": "550e8400-e29b-41d4-a716-446655440001",
"timestamp": "2024-12-24 19:00:00.000"
},
"msg_type": "KLINE_DATA_BATCH",
"klines": [
{
"symbol": "000001.SZ",
"period": "1d",
"kline_time": "2024-01-01 09:30:00",
"data": {
"open": 10.50,
"high": 10.80,
"low": 10.40,
"close": 10.75,
"volume": 1000000
}
},
{
"symbol": "600000.SH",
"period": "1d",
"kline_time": "2024-01-01 09:30:00",
"data": {
"open": 8.20,
"high": 8.35,
"low": 8.15,
"close": 8.30,
"volume": 2000000
}
}
]
}
```
**字段说明**:
| 字段 | 类型 | 必填 | 说明 |
| ----------- | ------ | ---- | --------------------------------------------------------- |
| header | object | 是 | 协议头 |
| msg_type | string | 是 | 消息类型: "KLINE_DATA"(单条) 或 "KLINE_DATA_BATCH"(批量) |
| symbol | string | 是 | 股票代码,如"000001.SZ"、"600000.SH" |
| period | string | 是 | K线周期: "1m", "5m", "15m", "30m", "1h", "1d", "1w", "1M" |
| kline_time | string | 是 | K线时间,格式: YYYY-MM-DD HH:MM:SS |
| data.open | float | 是 | 开盘价 |
| data.high | float | 是 | 最高价 |
| data.low | float | 是 | 最低价 |
| data.close | float | 是 | 收盘价 |
| data.volume | int | 是 | 成交量 |
| klines | array | 是 | 批量模式下的K线数据列表 |
**周期说明**:
- `1m`: 1分钟
- `5m`: 5分钟
- `15m`: 15分钟
- `30m`: 30分钟
- `1h`: 1小时
- `1d`: 1天(日K线)
- `1w`: 1周(周K线)
- `1M`: 1月(月K线)
### 3.2 服务器响应消息(交易信号)
**消息类型**: `TRADE_SIGNAL` 或 `TRADE_SIGNAL_BATCH`
#### 3.2.1 单条交易信号
**数据结构**:
```json
{
"header": {
"version": "1.0",
"msg_id": "550e8400-e29b-41d4-a716-446655440002",
"timestamp": "2024-12-24 19:00:00.000",
"req_msg_id": "550e8400-e29b-41d4-a716-446655440000"
},
"msg_type": "TRADE_SIGNAL",
"symbol": "000001.SZ",
"action": "BUY",
"price": 10.75,
"quantity": 100,
"message": "MA金叉信号,建议买入"
}
```
**字段说明**:
| 字段 | 类型 | 必填 | 说明 |
| ----------------- | ------ | ---- | ------------------------------------------------- |
| header | object | 是 | 协议头 |
| header.req_msg_id | string | 是 | 对应的请求消息ID |
| msg_type | string | 是 | 消息类型,固定为"TRADE_SIGNAL" |
| symbol | string | 是 | 股票代码 |
| action | string | 是 | 交易动作: "BUY"(买入)、"SELL"(卖出)、"HOLD"(持有) |
| price | float | 是 | **建议交易价格**(明确在什么价位交易) |
| quantity | int | 是 | **交易数量**(股数,0表示不交易) |
| message | string | 否 | 信号说明或原因 |
**交易动作说明**:
- `BUY`: 买入,price为建议买入价,quantity为买入股数
- `SELL`: 卖出,price为建议卖出价,quantity为卖出股数
- `HOLD`: 持有,不进行交易,quantity为0
#### 3.2.2 批量交易信号
**数据结构**:
```json
{
"header": {
"version": "1.0",
"msg_id": "550e8400-e29b-41d4-a716-446655440003",
"timestamp": "2024-12-24 19:00:00.000",
"req_msg_id": "550e8400-e29b-41d4-a716-446655440001"
},
"msg_type": "TRADE_SIGNAL_BATCH",
"signals": [
{
"symbol": "000001.SZ",
"action": "BUY",
"price": 10.75,
"quantity": 100,
"message": "买入信号"
},
{
"symbol": "600000.SH",
"action": "HOLD",
"price": 8.30,
"quantity": 0,
"message": "观望"
}
]
}
```
### 3.3 错误消息
**消息类型**: `ERROR`
**数据结构**:
```json
{
"header": {
"version": "1.0",
"msg_id": "550e8400-e29b-41d4-a716-446655440004",
"timestamp": "2024-12-24 19:00:00.000",
"req_msg_id": "550e8400-e29b-41d4-a716-446655440000"
},
"msg_type": "ERROR",
"error_code": "INVALID_DATA",
"error_message": "K线数据格式错误: 缺少close字段"
}
```
**字段说明**:
| 字段 | 类型 | 必填 | 说明 |
| ----------------- | ------ | ---- | ----------------------- |
| header | object | 是 | 协议头 |
| header.req_msg_id | string | 否 | 导致错误的请求消息ID |
| msg_type | string | 是 | 消息类型,固定为"ERROR" |
| error_code | string | 是 | 错误代码 |
| error_message | string | 是 | 错误描述 |
**错误码列表**:
- `INVALID_VERSION`: 协议版本不支持
- `INVALID_DATA`: 数据格式错误
- `MISSING_FIELD`: 缺少必填字段
- `INVALID_SYMBOL`: 无效的股票代码
- `INVALID_PERIOD`: 无效的K线周期
- `STRATEGY_ERROR`: 策略执行错误
- `TIMEOUT`: 请求超时
## 4. 通信流程
### 4.1 单条K线流程
```
客户端 服务器
| |
|---- WebSocket连接 ------------------------>|
|<--- 连接成功 -------------------------------|
| |
|---- KLINE_DATA (000001.SZ, 1d) ------------->|
| |--- 执行策略
|<--- TRADE_SIGNAL (BUY, 100股@10.75) -------|
| |
|---- KLINE_DATA (000001.SZ, 1d) ------------->|
| |--- 执行策略
|<--- TRADE_SIGNAL (HOLD, 0股@10.80) --------|
```
### 4.2 批量K线流程
```
客户端 服务器
| |
|---- KLINE_DATA_BATCH (2支股票) ------------->|
| - 000001.SZ (1d) |
| - 600000.SH (1d) |
| |--- 执行策略
|<--- TRADE_SIGNAL_BATCH -------------------- |
| - 000001.SZ: BUY 100股@10.75 |
| - 600000.SH: HOLD 0股@8.30 |
```
## 5. 完整测试用例
### 5.1 单条K线买入信号
**客户端发送**:
```json
{
"header": {
"version": "1.0",
"msg_id": "test-001",
"timestamp": "2024-12-24 19:00:00.000"
},
"msg_type": "KLINE_DATA",
"symbol": "000001.SZ",
"period": "1d",
"kline_time": "2024-01-02 09:30:00",
"data": {
"open": 10.50,
"high": 10.80,
"low": 10.40,
"close": 10.75,
"volume": 1000000
}
}
```
**服务器响应**:
```json
{
"header": {
"version": "1.0",
"msg_id": "resp-001",
"timestamp": "2024-12-24 19:00:00.000",
"req_msg_id": "test-001"
},
"msg_type": "TRADE_SIGNAL",
"symbol": "000001.SZ",
"action": "BUY",
"price": 10.75,
"quantity": 100,
"message": "策略建议在10.75价位买入100股"
}
```
### 5.2 批量K线混合信号
**客户端发送**:
```json
{
"header": {
"version": "1.0",
"msg_id": "test-002",
"timestamp": "2024-12-24 19:00:00.000"
},
"msg_type": "KLINE_DATA_BATCH",
"klines": [
{
"symbol": "000001.SZ",
"period": "1d",
"kline_time": "2024-01-02 09:30:00",
"data": {"open": 10.50, "high": 10.80, "low": 10.40, "close": 10.75, "volume": 1000000}
},
{
"symbol": "600000.SH",
"period": "1d",
"kline_time": "2024-01-02 09:30:00",
"data": {"open": 8.20, "high": 8.35, "low": 8.15, "close": 8.30, "volume": 2000000}
}
]
}
```
**服务器响应**:
```json
{
"header": {
"version": "1.0",
"msg_id": "resp-002",
"timestamp": "2024-12-24 19:00:00.000",
"req_msg_id": "test-002"
},
"msg_type": "TRADE_SIGNAL_BATCH",
"signals": [
{
"symbol": "000001.SZ",
"action": "BUY",
"price": 10.75,
"quantity": 100,
"message": "在10.75价位买入100股"
},
{
"symbol": "600000.SH",
"action": "SELL",
"price": 8.30,
"quantity": 50,
"message": "在8.30价位卖出50股"
}
]
}
```
### 5.3 不同周期K线
**客户端发送(5分钟K线)**:
```json
{
"header": {
"version": "1.0",
"msg_id": "test-003",
"timestamp": "2024-12-24 19:00:00.000"
},
"msg_type": "KLINE_DATA",
"symbol": "000001.SZ",
"period": "5m",
"kline_time": "2024-01-02 09:35:00",
"data": {
"open": 10.50,
"high": 10.55,
"low": 10.48,
"close": 10.52,
"volume": 50000
}
}
```
## 6. 性能指标
- **协议版本**: v1.0
- **连接超时**: 30秒
- **消息超时**: 30秒
- **心跳间隔**: 20秒(Ping)
- **心跳超时**: 10秒(Pong)
- **批量大小**: 建议不超过100条K线
- **建议并发**: 单连接(回测场景)
## 7. 版本升级规则
- **主版本号**: 不兼容的协议变更(如修改必填字段)
- **次版本号**: 向后兼容的功能添加
- **修订号**: 向后兼容的问题修复
当前版本: **v1.0**
- 初始版本
- 支持单条和批量K线传输
- 支持多周期K线
- 明确价格和数量信息
## 8. 注意事项
1. **协议头必填**: 所有消息必须包含header,用于版本控制和追踪
2. **消息ID唯一**: msg_id必须全局唯一,建议使用UUID
3. **版本兼容**: 服务器应检查version字段,不支持的版本返回INVALID_VERSION错误
4. **价格和数量**: 交易信号必须明确指定price(交易价位)和quantity(交易股数)
5. **周期标准化**: period字段必须使用规定的格式(1m, 5m, 1d等)
6. **批量优化**: 多支股票同一时间的K线建议使用批量模式,提升效率
7. **响应关联**: 服务器响应的req_msg_id必须对应客户端请求的msg_id
8. **时间格式**: timestamp使用可读格式 YYYY-MM-DD HH:MM:SS.mmm
9. **交易动作**: action为BUY或SELL时,quantity必须大于0;HOLD时quantity为0
## 9. 当前实现状态
**已实现**:
- 基础WebSocket连接
- 协议头(version, msg_id, timestamp)
- 单条K线数据传输(v1.0格式)
- 交易信号响应(v1.0格式)
- 周期信息(period字段)
- 明确价格和数量(price和quantity必填)
- 错误消息规范(ERROR类型)
- 版本检查机制
**待实现**:
- 批量K线传输(KLINE_DATA_BATCH)
- 批量信号响应(TRADE_SIGNAL_BATCH)
- 心跳机制
- 请求追踪和关联优化