diff --git a/docs/websocket_protocol.md b/docs/websocket_protocol.md new file mode 100644 index 0000000..7bea2b4 --- /dev/null +++ b/docs/websocket_protocol.md @@ -0,0 +1,446 @@ +# 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) +- 心跳机制 +- 请求追踪和关联优化 \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..b4b0c69 --- /dev/null +++ b/main.py @@ -0,0 +1,10 @@ +""" +QTrade Server主启动脚本 + +启动策略服务器 +""" + +from src.networks.server.ws_server import start_server + +if __name__ == "__main__": + start_server(host="0.0.0.0", port=8000) diff --git a/requirements.txt b/requirements.txt index b839d88..a3a5b83 100644 --- a/requirements.txt +++ b/requirements.txt @@ -34,3 +34,6 @@ pytz>=2023.0 # ==================== 数据源(可选) ==================== xtquant # 迅投QMT数据源 +fastapi>=0.95.0 # 用于构建API服务 +uvicorn[standard] +websockets>=11.0.0 # 用于WebSocket通信 \ No newline at end of file diff --git a/src/backtest/bt_client_adapter.py b/src/backtest/bt_client_adapter.py new file mode 100644 index 0000000..b8c34a5 --- /dev/null +++ b/src/backtest/bt_client_adapter.py @@ -0,0 +1,121 @@ +""" +策略客户端适配器 (Strategy Client Adapter) + +负责业务逻辑: +- 构建协议消息(K线数据、协议头等) +- 解析服务器响应(交易信号) +- 调用底层WebSocket客户端进行通信 +""" + +from typing import Optional +from datetime import datetime +from dataclasses import dataclass +import pandas as pd +import uuid + +from src.networks.client.ws_client import WSClient +from src.core.logger import get_logger + +logger = get_logger("StrategyClient") + + +@dataclass +class TradeSignal: + """交易信号""" + + symbol: str + action: str # "BUY", "SELL", "HOLD" + price: float # 建议交易价格 + quantity: int # 交易数量(股数) + message: str = "" + req_msg_id: Optional[str] = None # 请求消息ID + + +class BacktestClientAdapter: + """ + 策略客户端适配器 + + 负责: + - 构建协议v1.0格式的消息 + - 解析交易信号 + - 调用WSClient发送消息 + """ + + def __init__( + self, server_url: str = "ws://localhost:8000/ws/strategy", timeout: int = 30 + ): + """ + 初始化策略客户端适配器 + + Args: + server_url: WebSocket服务器地址 + timeout: 超时时间(秒) + """ + self.ws_client = WSClient(server_url, timeout) + logger.info("BacktestClientAdapter initialized") + + def _create_header(self) -> dict: + """创建协议头 v1.0""" + return { + "version": "1.0", + "msg_id": str(uuid.uuid4()), + "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3], + } + + def send_kline( + self, symbol: str, kline: pd.Series, kline_time: datetime, period: str = "1d" + ) -> Optional[TradeSignal]: + """ + 发送K线数据到服务器 + + Args: + symbol: 标的代码 + kline: K线数据(Series,包含open/high/low/close/volume) + kline_time: K线时间戳 + period: K线周期 (1m, 5m, 15m, 30m, 1h, 1d, 1w, 1M) + + Returns: + 交易信号或None(如果请求失败) + """ + # 构建请求数据 v1.0 + request_data = { + "header": self._create_header(), + "msg_type": "KLINE_DATA", + "symbol": symbol, + "period": period, + "kline_time": kline_time.strftime("%Y-%m-%d %H:%M:%S"), + "data": { + "open": float(kline["open"]), + "high": float(kline["high"]), + "low": float(kline["low"]), + "close": float(kline["close"]), + "volume": int(kline["volume"]), + }, + } + + # 发送消息 + response = self.ws_client.send(request_data) + if not response: + return None + + # 检查是否是错误消息 + if response.get("msg_type") == "ERROR": + logger.error( + f"Server error: {response.get('error_code')} - {response.get('error_message')}" + ) + return None + + # 解析交易信号 v1.0 + signal = TradeSignal( + symbol=response.get("symbol", symbol), + action=response.get("action", "HOLD"), + price=response.get("price", 0.0), + quantity=response.get("quantity", 0), + message=response.get("message", ""), + req_msg_id=response.get("header", {}).get("req_msg_id"), + ) + return signal + + def close(self): + """关闭连接""" + self.ws_client.close() diff --git a/src/backtest/bt_engine.py b/src/backtest/bt_engine.py new file mode 100644 index 0000000..08eb450 --- /dev/null +++ b/src/backtest/bt_engine.py @@ -0,0 +1,134 @@ +""" +回测引擎 (Backtest Engine) + +简单的回测引擎类 +""" + +from typing import List, Optional + +from src.data_service.data_service import DataService +from src.backtest.bt_task import BacktestTask +from src.backtest.bt_client_adapter import BacktestClientAdapter +from src.core.logger import get_logger + +logger = get_logger("BacktestEngine") + + +class BacktestEngine: + """回测引擎""" + + def __init__( + self, + data_service: DataService, + backtest_client: Optional[BacktestClientAdapter] = None, + ): + """ + 初始化回测引擎 + + Args: + data_service: 数据服务实例 + backtest_client: 策略客户端适配器(可选,如果提供则发送数据到策略服务器) + """ + self.data_service = data_service + self.backtest_client = backtest_client + self.tasks: List[BacktestTask] = [] # 任务列表 + + if self.backtest_client: + logger.info("BacktestEngine initialized with BacktestClientAdapter") + else: + logger.info("BacktestEngine initialized without BacktestClientAdapter") + + def add_task(self, task: BacktestTask) -> None: + """ + 添加回测任务 + + Args: + task: 回测任务对象 + """ + self.tasks.append(task) + logger.info( + f"Task added: {task.strategy_name} on {task.symbols} " + f"({task.start_date.date()} to {task.end_date.date()}, {task.period})" + ) + + def get_tasks(self) -> List[BacktestTask]: + """ + 获取所有任务 + + Returns: + 任务列表 + """ + return self.tasks + + def clear_tasks(self) -> None: + """清空所有任务""" + self.tasks.clear() + logger.info("All tasks cleared") + + def run(self) -> None: + """运行所有回测任务""" + if not self.tasks: + logger.warning("No tasks to run") + return + + logger.info(f"Starting {len(self.tasks)} backtest task(s)") + + for task_idx, task in enumerate(self.tasks, 1): + logger.info("=" * 60) + logger.info(f"Task {task_idx}/{len(self.tasks)}: {task.strategy_name}") + logger.info( + f"Symbols: {task.symbols}, Period: {task.period}, " + f"Time: {task.start_date.date()}~{task.end_date.date()}" + ) + + # 1. 获取数据 + data_dict = {} + for symbol in task.symbols: + df = self.data_service.get_klines( + symbol=symbol, + period=task.period, + startdate=task.start_date, + enddate=task.end_date, + ) + if df is not None and not df.empty: + data_dict[symbol] = df + logger.info(f" {symbol}: {len(df)} records") + + if not data_dict: + logger.error("Data is empty, skipping this task") + continue + + # 2. 播放数据 + all_timestamps = set() + for df in data_dict.values(): + all_timestamps.update(df.index) + timestamps = sorted(all_timestamps) + + logger.info(f"Starting to play {len(timestamps)} timestamps") + + for idx, timestamp in enumerate(timestamps, 1): + current_bars = {} + for symbol, df in data_dict.items(): + if timestamp in df.index: + current_bars[symbol] = df.loc[timestamp] + + # 如果配置了BacktestClientAdapter,发送K线数据到策略服务器 + if self.backtest_client: + for symbol, bar in current_bars.items(): + # 使用send_kline接口,传入period信息 + self.backtest_client.send_kline( + symbol=symbol, + kline=bar, + kline_time=timestamp, + period=task.period, + ) + # 暂不处理返回的信号,后续可以添加策略逻辑 + + # 每50个时间点输出一次进度 + if idx % 50 == 0: + logger.info(f" Progress: {idx}/{len(timestamps)}") + + logger.info(f"Task {task_idx} completed") + + logger.info("=" * 60) + logger.info("All backtest tasks completed") diff --git a/src/backtest/bt_task.py b/src/backtest/bt_task.py new file mode 100644 index 0000000..d25e2f7 --- /dev/null +++ b/src/backtest/bt_task.py @@ -0,0 +1,70 @@ +""" +回测任务 (Backtest Task) + +定义回测任务的数据结构 +""" + +from typing import List, Optional +from datetime import datetime + + +class BacktestTask: + """ + 回测任务 + + 包含回测的所有必要信息,每个任务对象代表一次回测 + """ + + def __init__( + self, + symbols: List[str], + start_date: datetime, + end_date: datetime, + period: str, + strategy_name: str, + strategy_params: Optional[dict] = None, + initial_capital: float = 100000.0, + commission_rate: float = 0.0003, + slippage_rate: float = 0.0001, + ): + """ + 初始化回测任务 + + Args: + symbols: 回测标的列表 + start_date: 开始时间 + end_date: 结束时间 + period: K线周期(如'1d', '1h', '30m') + strategy_name: 策略名称 + strategy_params: 策略参数字典 + initial_capital: 初始资金 + commission_rate: 手续费率 + slippage_rate: 滑点率 + """ + # 参数验证 + if not symbols: + raise ValueError("symbols cannot be empty") + if start_date >= end_date: + raise ValueError("start_date must be before end_date") + if initial_capital <= 0: + raise ValueError("initial_capital must be positive") + + # 赋值 + self.symbols = symbols + self.start_date = start_date + self.end_date = end_date + self.period = period + self.strategy_name = strategy_name + self.strategy_params = strategy_params or {} + self.initial_capital = initial_capital + self.commission_rate = commission_rate + self.slippage_rate = slippage_rate + + def __repr__(self) -> str: + """字符串表示""" + return ( + f"BacktestTask(strategy={self.strategy_name}, " + f"symbols={self.symbols}, " + f"period={self.period}, " + f"date={self.start_date.date()}~{self.end_date.date()})" + ) diff --git a/src/backtest/main.py b/src/backtest/main.py new file mode 100644 index 0000000..bc47e34 --- /dev/null +++ b/src/backtest/main.py @@ -0,0 +1,67 @@ +""" +回测系统主入口 + +演示BacktestEngine的使用 +""" + +from datetime import datetime + +from src.data_service.data_service import DataService +from src.backtest.bt_engine import BacktestEngine +from src.backtest.bt_task import BacktestTask +from src.backtest.bt_client_adapter import BacktestClientAdapter +from src.core.logger import get_logger +from src.core.config import Config + +logger = get_logger("BacktestMain") + + +def main(): + """Main function""" + logger.info("=== Backtest system starting ===") + + # Load configuration + config = Config() + config.load_with_global("configs/backtest.yaml") + logger.info("Config loaded") + + # Initialize data service + data_service = DataService.from_config(config) + logger.info("DataService initialized") + + # Initialize strategy client (increase timeout) + backtest_client = BacktestClientAdapter( + "ws://localhost:8000/ws/strategy", timeout=30 + ) + logger.info("BacktestClientAdapter initialized") + + # Initialize backtest engine (pass in BacktestClientAdapter) + engine = BacktestEngine(data_service, backtest_client) + logger.info("BacktestEngine created") + + # Create backtest task example + task = BacktestTask( + symbols=["000001.SZ", "600000.SH"], + start_date=datetime(2024, 1, 1), + end_date=datetime(2024, 12, 31), + period="1d", + strategy_name="MA_Strategy", + strategy_params={"fast_period": 5, "slow_period": 20}, + initial_capital=100000.0, + ) + + # Add task + engine.add_task(task) + + # View task list + tasks = engine.get_tasks() + logger.info(f"Total tasks: {len(tasks)}") + + # Run all backtest tasks + engine.run() + + logger.info("=== Backtest system initialization completed ===") + + +if __name__ == "__main__": + main() diff --git a/src/data_downloader/base_downloader.py b/src/data_downloader/base_downloader.py index 3ac34ff..cec6689 100644 --- a/src/data_downloader/base_downloader.py +++ b/src/data_downloader/base_downloader.py @@ -126,14 +126,14 @@ class BaseDataDownloader(ABC): if period not in valid_periods: raise ValueError(f"不支持的周期: {period},支持: {valid_periods}") - self.logger.debug("参数验证通过") + self.logger.debug("Parameter validation passed") def _init_database(self): """初始化数据库连接""" # 创建数据库(如果不存在) db_manager = DatabaseManager() if not db_manager.database_exists(self.database): - self.logger.warning(f"数据库 {self.database} 不存在,正在创建...") + self.logger.warning(f"Database {self.database} does not exist, creating...") db_manager.create_database(self.database) # 确保对应周期的 klines 表存在 @@ -147,7 +147,7 @@ class BaseDataDownloader(ABC): for period in SUPPORTED_PERIODS: table_name = get_kline_table_name(period) if not db_manager.table_exists(self.database, table_name): - self.logger.warning(f"表 {table_name} 不存在,正在创建...") + self.logger.warning(f"Table {table_name} does not exist, creating...") table_def = create_kline_table_definition(period) db_manager.create_table( database=self.database, @@ -162,7 +162,7 @@ class BaseDataDownloader(ABC): self.engine = self._create_engine() self.Session = sessionmaker(bind=self.engine) - self.logger.debug(f"数据库连接初始化完成: {self.database}") + self.logger.debug(f"Database connection initialized: {self.database}") def _create_engine(self): """创建数据库引擎""" @@ -204,7 +204,7 @@ class BaseDataDownloader(ABC): DataFrame包含列: timestamp, open, high, low, close, volume, amount """ self.logger.info("=" * 50) - self.logger.info("开始下载数据(仅下载,不保存)") + self.logger.info("Starting data download (download only, not saving)") self.logger.info("=" * 50) result = {} @@ -212,7 +212,7 @@ class BaseDataDownloader(ABC): for symbol in self.symbols: for period in self.periods: try: - self.logger.info(f"下载 {symbol} [{period}] 数据...") + self.logger.info(f"Downloading {symbol} [{period}] data...") # 调用子类实现的下载方法 klines = self._download_klines( @@ -228,15 +228,17 @@ class BaseDataDownloader(ABC): key = f"{symbol}_{period}" result[key] = df - self.logger.info(f"✓ {symbol} [{period}]: 下载 {len(df)} 条") + self.logger.info( + f"✓ {symbol} [{period}]: downloaded {len(df)} records" + ) else: - self.logger.warning(f"✗ {symbol} [{period}]: 无数据") + self.logger.warning(f"✗ {symbol} [{period}]: no data") except Exception as e: - self.logger.error(f"✗ {symbol} [{period}]: 下载失败 - {e}") + self.logger.error(f"✗ {symbol} [{period}]: download failed - {e}") self.logger.info("=" * 50) - self.logger.info(f"下载完成,共获取 {len(result)} 个数据集") + self.logger.info(f"Download completed, retrieved {len(result)} datasets") self.logger.info("=" * 50) return result @@ -276,7 +278,7 @@ class BaseDataDownloader(ABC): 统计信息字典 """ self.logger.info("=" * 50) - self.logger.info("开始下载数据") + self.logger.info("Starting data download") self.logger.info("=" * 50) stats = { @@ -291,7 +293,7 @@ class BaseDataDownloader(ABC): for symbol in self.symbols: for period in self.periods: try: - self.logger.info(f"下载 {symbol} [{period}] 数据...") + self.logger.info(f"Downloading {symbol} [{period}] data...") # 调用子类实现的下载方法 klines = self._download_klines( @@ -322,7 +324,7 @@ class BaseDataDownloader(ABC): } ) else: - self.logger.warning(f"✗ {symbol} [{period}]: 无数据") + self.logger.warning(f"✗ {symbol} [{period}]: no data") stats["failed_count"] += 1 stats["details"].append( { @@ -335,7 +337,7 @@ class BaseDataDownloader(ABC): ) except Exception as e: - self.logger.error(f"✗ {symbol} [{period}]: 下载失败 - {e}") + self.logger.error(f"✗ {symbol} [{period}]: download failed - {e}") stats["failed_count"] += 1 stats["details"].append( { @@ -347,14 +349,14 @@ class BaseDataDownloader(ABC): ) self.logger.info("=" * 50) - self.logger.info("下载完成") + self.logger.info("Download completed") self.logger.info( - f"总计: {stats['total_symbols']} 个标的 x {stats['total_periods']} 个周期" + f"Total: {stats['total_symbols']} symbols x {stats['total_periods']} periods" ) self.logger.info( - f"成功: {stats['success_count']}, 失败: {stats['failed_count']}" + f"Success: {stats['success_count']}, Failed: {stats['failed_count']}" ) - self.logger.info(f"保存记录数: {stats['total_records']}") + self.logger.info(f"Saved records: {stats['total_records']}") self.logger.info("=" * 50) return stats @@ -411,11 +413,11 @@ class BaseDataDownloader(ABC): saved_count += 1 session.commit() - self.logger.debug(f"保存 {saved_count} 条记录到数据库") + self.logger.debug(f"Saved {saved_count} records to database") except Exception as e: session.rollback() - self.logger.error(f"保存数据失败: {e}") + self.logger.error(f"Failed to save data: {e}") raise finally: session.close() @@ -426,4 +428,4 @@ class BaseDataDownloader(ABC): """关闭数据库连接""" if hasattr(self, "engine"): self.engine.dispose() - self.logger.info("数据库连接已关闭") + self.logger.info("Database connection closed") diff --git a/src/data_downloader/xtquant_downloader.py b/src/data_downloader/xtquant_downloader.py index 9031cef..2086248 100644 --- a/src/data_downloader/xtquant_downloader.py +++ b/src/data_downloader/xtquant_downloader.py @@ -72,9 +72,9 @@ class XtQuantDownloader(BaseDataDownloader): """析构函数:关闭 XtQuant 连接""" try: xtdc.close() - self.logger.debug("XtQuant 连接已关闭") + self.logger.debug("XtQuant connection closed") except Exception as e: - self.logger.debug(f"关闭 XtQuant 连接时出错: {e}") + self.logger.debug(f"Error closing XtQuant connection: {e}") def _init_xtquant( self, token: Optional[str], optimize_addresses: Optional[List[str]] @@ -88,7 +88,7 @@ class XtQuantDownloader(BaseDataDownloader): "XtQuant token 未设置,请在配置文件 data_source.xtquant.xtquant_token 中设置或通过参数传入" ) - self.logger.info(f"初始化 XtQuant 数据中心,Token: {token[:20]}...") + self.logger.info(f"Initializing XtQuant data center, Token: {token[:20]}...") # 设置 token xtdc.set_token(token) @@ -96,9 +96,9 @@ class XtQuantDownloader(BaseDataDownloader): # 初始化数据中心 try: xtdc.init() - self.logger.info("XtQuant 数据中心初始化成功") + self.logger.info("XtQuant data center initialized successfully") except Exception as e: - self.logger.error(f"XtQuant 数据中心初始化失败: {e}") + self.logger.error(f"XtQuant data center initialization failed: {e}") raise # 设置优化地址 @@ -110,19 +110,21 @@ class XtQuantDownloader(BaseDataDownloader): if optimize_addresses: try: xtdc.set_allow_optmize_address(optimize_addresses) - self.logger.info(f"优化地址已设置: {len(optimize_addresses)} 个") + self.logger.info( + f"Optimize addresses set: {len(optimize_addresses)} addresses" + ) except Exception as e: - self.logger.warning(f"优化地址设置失败: {e}") + self.logger.warning(f"Failed to set optimize addresses: {e}") # 下载基础数据 try: - self.logger.info("下载板块数据...") + self.logger.info("Downloading sector data...") xtdata.download_sector_data() - self.logger.info("下载历史合约数据...") + self.logger.info("Downloading historical contracts data...") xtdata.download_history_contracts() - self.logger.info("基础数据下载完成") + self.logger.info("Base data download completed") except Exception as e: - self.logger.warning(f"基础数据下载失败: {e}") + self.logger.warning(f"Base data download failed: {e}") def _download_klines( self, symbol: str, start_date: datetime, end_date: datetime, period: str @@ -148,10 +150,12 @@ class XtQuantDownloader(BaseDataDownloader): # 先下载历史数据(确保本地有缓存) try: - self.logger.debug(f"下载 {symbol} [{period}] 历史数据到本地...") + self.logger.debug( + f"Downloading {symbol} [{period}] historical data to local..." + ) xtdata.download_history_data(symbol, xt_period, start_str, end_str) except Exception as e: - self.logger.warning(f"下载历史数据到本地失败: {e}") + self.logger.warning(f"Failed to download historical data to local: {e}") # 从本地获取数据 try: @@ -167,11 +171,11 @@ class XtQuantDownloader(BaseDataDownloader): ) if symbol not in data or len(data[symbol]) == 0: - self.logger.warning(f"{symbol} [{period}] 没有数据") + self.logger.warning(f"{symbol} [{period}] has no data") return [] df = data[symbol] - self.logger.debug(f"获取到 {len(df)} 条 {symbol} [{period}] 数据") + self.logger.debug(f"Retrieved {len(df)} records for {symbol} [{period}]") # 转换为 Kline 对象 klines = [] @@ -210,9 +214,11 @@ class XtQuantDownloader(BaseDataDownloader): # 打印第一条数据的时间戳信息用于调试 if not first_logged: self.logger.debug( - f"第一条时间戳 - 原始: {timestamp}, 类型: {type(timestamp)}" + f"First timestamp - raw: {timestamp}, type: {type(timestamp)}" + ) + self.logger.debug( + f"First timestamp - converted: {dt}, type: {type(dt)}" ) - self.logger.debug(f"第一条时间戳 - 转换后: {dt}, 类型: {type(dt)}") first_logged = True kline = Kline( @@ -234,5 +240,5 @@ class XtQuantDownloader(BaseDataDownloader): return klines except Exception as e: - self.logger.error(f"获取 {symbol} [{period}] 数据失败: {e}") + self.logger.error(f"Failed to retrieve {symbol} [{period}] data: {e}") raise diff --git a/src/database_manager/db_manager.py b/src/database_manager/db_manager.py index ad7ba41..f865c50 100644 --- a/src/database_manager/db_manager.py +++ b/src/database_manager/db_manager.py @@ -79,7 +79,9 @@ class DatabaseManager: # 缓存各个数据库的engine,避免重复创建 self._db_engines: Dict[str, Engine] = {} - logger.info(f"数据库管理器初始化完成: {self.user}@{self.host}:{self.port}") + logger.info( + f"Database manager initialized: {self.user}@{self.host}:{self.port}" + ) def _create_admin_engine(self) -> Engine: """创建管理员引擎(不指定数据库,带连接池)""" @@ -133,10 +135,12 @@ class DatabaseManager: with self._admin_engine.connect() as conn: result = conn.execute(text(f"SHOW DATABASES LIKE '{database}'")) exists = result.fetchone() is not None - logger.debug(f"检查数据库 {database}: {'存在' if exists else '不存在'}") + logger.debug( + f"Check database {database}: {'exists' if exists else 'not exists'}" + ) return exists except SQLAlchemyError as e: - logger.error(f"检查数据库失败: {e}") + logger.error(f"Failed to check database: {e}") return False def create_database(self, database: str, if_not_exists: bool = True) -> bool: @@ -152,7 +156,7 @@ class DatabaseManager: """ try: if if_not_exists and self.database_exists(database): - logger.info(f"数据库 {database} 已存在,跳过创建") + logger.info(f"Database {database} already exists, skip creation") return True with self._admin_engine.connect() as conn: @@ -163,10 +167,10 @@ class DatabaseManager: ) ) conn.commit() - logger.info(f"✓ 创建数据库: {database}") + logger.info(f"✓ Created database: {database}") return True except SQLAlchemyError as e: - logger.error(f"创建数据库失败: {e}") + logger.error(f"Failed to create database: {e}") return False def drop_database(self, database: str, confirm: bool = False) -> bool: @@ -181,21 +185,21 @@ class DatabaseManager: 是否成功 """ if not confirm: - logger.warning("删除数据库需要确认: confirm=True") + logger.warning("Database deletion requires confirmation: confirm=True") return False try: if not self.database_exists(database): - logger.warning(f"数据库 {database} 不存在") + logger.warning(f"Database {database} does not exist") return False with self._admin_engine.connect() as conn: conn.execute(text(f"DROP DATABASE `{database}`")) conn.commit() - logger.info(f"✓ 删除数据库: {database}") + logger.info(f"✓ Dropped database: {database}") return True except SQLAlchemyError as e: - logger.error(f"删除数据库失败: {e}") + logger.error(f"Failed to drop database: {e}") return False def list_databases(self) -> List[str]: @@ -218,7 +222,7 @@ class DatabaseManager: ] return databases except SQLAlchemyError as e: - logger.error(f"列出数据库失败: {e}") + logger.error(f"Failed to list databases: {e}") return [] def table_exists(self, database: str, table: str) -> bool: @@ -236,10 +240,12 @@ class DatabaseManager: engine = self._create_db_engine(database) inspector = inspect(engine) exists = table in inspector.get_table_names() - logger.debug(f"检查表 {database}.{table}: {'存在' if exists else '不存在'}") + logger.debug( + f"Check table {database}.{table}: {'exists' if exists else 'not exists'}" + ) return exists except SQLAlchemyError as e: - logger.error(f"检查表失败: {e}") + logger.error(f"Failed to check table: {e}") return False def list_tables(self, database: str) -> List[str]: @@ -257,7 +263,7 @@ class DatabaseManager: inspector = inspect(engine) return inspector.get_table_names() except SQLAlchemyError as e: - logger.error(f"列出表失败: {e}") + logger.error(f"Failed to list tables: {e}") return [] def create_table( @@ -297,7 +303,9 @@ class DatabaseManager: """ try: if if_not_exists and self.table_exists(database, table_name): - logger.info(f"表 {database}.{table_name} 已存在,跳过创建") + logger.info( + f"Table {database}.{table_name} already exists, skip creation" + ) return True engine = self._create_db_engine(database) @@ -360,11 +368,11 @@ class DatabaseManager: # 创建表 metadata.create_all(engine) - logger.info(f"✓ 创建表: {database}.{table_name}") + logger.info(f"✓ Created table: {database}.{table_name}") return True except SQLAlchemyError as e: - logger.error(f"创建表失败: {e}") + logger.error(f"Failed to create table: {e}") return False def drop_table(self, database: str, table: str, confirm: bool = False) -> bool: @@ -380,22 +388,22 @@ class DatabaseManager: 是否成功 """ if not confirm: - logger.warning("删除表需要确认: confirm=True") + logger.warning("Table deletion requires confirmation: confirm=True") return False try: if not self.table_exists(database, table): - logger.warning(f"表 {database}.{table} 不存在") + logger.warning(f"Table {database}.{table} does not exist") return False engine = self._create_db_engine(database) with engine.connect() as conn: conn.execute(text(f"DROP TABLE `{table}`")) conn.commit() - logger.info(f"✓ 删除表: {database}.{table}") + logger.info(f"✓ Dropped table: {database}.{table}") return True except SQLAlchemyError as e: - logger.error(f"删除表失败: {e}") + logger.error(f"Failed to drop table: {e}") return False def get_table_schema(self, database: str, table: str) -> Dict[str, Any]: @@ -419,7 +427,7 @@ class DatabaseManager: return {"columns": columns, "indexes": indexes, "primary_key": pk} except SQLAlchemyError as e: - logger.error(f"获取表结构失败: {e}") + logger.error(f"Failed to get table schema: {e}") return {} def close(self): @@ -437,6 +445,6 @@ class DatabaseManager: logger.debug(f"Engine disposed for database: {db_name}") self._db_engines.clear() - logger.info("数据库管理器连接已关闭") + logger.info("Database manager connections closed") except Exception as e: - logger.warning(f"关闭数据库连接时出错: {e}") + logger.warning(f"Error closing database connections: {e}") diff --git a/src/indicator_calculator/indicator_manager.py b/src/indicator_calculator/indicator_manager.py index fbf761b..81390b0 100644 --- a/src/indicator_calculator/indicator_manager.py +++ b/src/indicator_calculator/indicator_manager.py @@ -51,11 +51,15 @@ class IndicatorManager: try: indicator_class = self.INDICATOR_MAP[indicator_name] self.indicators[indicator_name] = indicator_class(config) - self.logger.info(f"初始化指标: {indicator_name}, 配置: {config}") + self.logger.info( + f"Initialized indicator: {indicator_name}, config: {config}" + ) except Exception as e: - self.logger.error(f"初始化指标 {indicator_name} 失败: {e}") + self.logger.error( + f"Failed to initialize indicator {indicator_name}: {e}" + ) else: - self.logger.warning(f"未知的指标类型: {indicator_name}") + self.logger.warning(f"Unknown indicator type: {indicator_name}") def add_indicator(self, indicator_name: str, config: Dict | None = None): """添加指标计算器 @@ -75,7 +79,7 @@ class IndicatorManager: indicator_class = self.INDICATOR_MAP[indicator_name] self.indicators[indicator_name] = indicator_class(config) - self.logger.info(f"添加指标: {indicator_name}, 配置: {config}") + self.logger.info(f"Added indicator: {indicator_name}, config: {config}") def remove_indicator(self, indicator_name: str): """移除指标计算器 @@ -85,7 +89,7 @@ class IndicatorManager: """ if indicator_name in self.indicators: del self.indicators[indicator_name] - self.logger.info(f"移除指标: {indicator_name}") + self.logger.info(f"Removed indicator: {indicator_name}") def calculate_all( self, kline_data: Dict[str, pd.DataFrame] @@ -103,9 +107,11 @@ class IndicatorManager: for stock_code, df in kline_data.items(): try: result[stock_code] = self.calculate(df) - self.logger.debug(f"成功计算 {stock_code} 的所有指标") + self.logger.debug( + f"Successfully calculated all indicators for {stock_code}" + ) except Exception as e: - self.logger.error(f"计算 {stock_code} 的指标时出错: {e}") + self.logger.error(f"Error calculating indicators for {stock_code}: {e}") # 计算失败时返回原始数据 result[stock_code] = df @@ -131,15 +137,19 @@ class IndicatorManager: # 依次计算每个指标 for indicator_name in indicators_to_calc: if indicator_name not in self.indicators: - self.logger.warning(f"指标 {indicator_name} 未配置,跳过") + self.logger.warning( + f"Indicator {indicator_name} not configured, skipping" + ) continue try: indicator = self.indicators[indicator_name] result = indicator.calculate(result) - self.logger.debug(f"成功计算指标: {indicator_name}") + self.logger.debug( + f"Successfully calculated indicator: {indicator_name}" + ) except Exception as e: - self.logger.error(f"计算指标 {indicator_name} 时出错: {e}") + self.logger.error(f"Error calculating indicator {indicator_name}: {e}") # 继续计算其他指标 continue diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..e69de29 diff --git a/src/networks/__init__.py b/src/networks/__init__.py new file mode 100644 index 0000000..f3964db --- /dev/null +++ b/src/networks/__init__.py @@ -0,0 +1,9 @@ +""" +Networks模块 + +提供客户端和服务端通信能力 +""" + +from src.networks.client.ws_client import WSClient + +__all__ = ["WSClient"] diff --git a/src/networks/client/__init__.py b/src/networks/client/__init__.py new file mode 100644 index 0000000..b2cce0f --- /dev/null +++ b/src/networks/client/__init__.py @@ -0,0 +1,7 @@ +""" +客户端模块 +""" + +from src.networks.client.ws_client import WSClient + +__all__ = ["WSClient"] diff --git a/src/networks/client/ws_client.py b/src/networks/client/ws_client.py new file mode 100644 index 0000000..1460e0a --- /dev/null +++ b/src/networks/client/ws_client.py @@ -0,0 +1,144 @@ +""" +WebSocket客户端 (WebSocket Client) + +纯粹的WebSocket通信层,只负责: +- 建立和管理WebSocket连接 +- 发送和接收消息 +- 不包含任何业务逻辑 +""" + +from typing import Optional, Dict, Any +import asyncio +import websockets +import json + +from src.core.logger import get_logger + +logger = get_logger("WSClient") + + +class WSClient: + """ + WebSocket客户端 + + 纯粹的通信层,只负责: + - 连接管理 + - 消息收发 + - 不解析业务数据 + """ + + def __init__(self, server_url: str, timeout: int = 30): + """ + 初始化WebSocket客户端 + + Args: + server_url: WebSocket服务器地址(完整URL,如 ws://localhost:8000/ws/strategy) + timeout: 超时时间(秒) + """ + self.server_url = server_url + self.timeout = timeout + self.websocket = None + self.loop = None + self.connected = False + self.connection_attempted = False + logger.info(f"WSClient initialized: {self.server_url}") + + async def connect(self): + """建立WebSocket连接""" + try: + logger.info(f"Attempting to connect to {self.server_url}...") + self.websocket = await websockets.connect( + self.server_url, ping_interval=20, ping_timeout=10 + ) + self.connected = True + logger.info("WebSocket connected successfully") + except Exception as e: + self.connected = False + logger.error(f"Failed to connect WebSocket: {e}") + raise + + async def disconnect(self): + """关闭WebSocket连接""" + if self.websocket: + await self.websocket.close() + self.connected = False + logger.info("WebSocket disconnected") + + async def send_async(self, message: Dict[str, Any]) -> Optional[Dict[str, Any]]: + """ + 异步发送消息并接收响应 + + Args: + message: 要发送的消息(字典格式) + + Returns: + 服务器响应(字典格式)或None + """ + if not self.websocket: + logger.error("WebSocket not connected") + return None + + try: + # 发送消息 + await self.websocket.send(json.dumps(message)) + + # 接收响应 + response = await asyncio.wait_for( + self.websocket.recv(), timeout=self.timeout + ) + + # 解析JSON + return json.loads(response) + + except asyncio.TimeoutError: + logger.error(f"Request timeout after {self.timeout}s") + return None + except Exception as e: + # 忽略正常的WebSocket关闭(错误码1000) + error_msg = str(e) + if "1000" not in error_msg or "OK" not in error_msg: + logger.error(f"WebSocket error: {e}") + return None + + def send(self, message: Dict[str, Any]) -> Optional[Dict[str, Any]]: + """ + 发送消息并接收响应(同步接口) + + Args: + message: 要发送的消息(字典格式) + + Returns: + 服务器响应(字典格式)或None + """ + # 如果已经尝试连接过但失败了,不再重试 + if self.connection_attempted and not self.connected: + return None + + # 如果没有事件循环,创建一个 + if not self.loop: + self.loop = asyncio.new_event_loop() + asyncio.set_event_loop(self.loop) + + # 如果未连接,先建立连接(只尝试一次) + if not self.websocket: + self.connection_attempted = True + try: + self.loop.run_until_complete(self.connect()) + except Exception as e: + logger.error(f"Connection failed, will not retry: {e}") + self.connected = False + return None + + # 执行异步发送 + return self.loop.run_until_complete(self.send_async(message)) + + def close(self): + """关闭客户端连接""" + try: + if self.websocket and self.loop: + self.loop.run_until_complete(self.disconnect()) + if self.loop: + self.loop.close() + self.loop = None + except Exception as e: + logger.error(f"Error closing connection: {e}") diff --git a/src/networks/server/__init__.py b/src/networks/server/__init__.py new file mode 100644 index 0000000..553ee4d --- /dev/null +++ b/src/networks/server/__init__.py @@ -0,0 +1,7 @@ +""" +服务端模块 +""" + +from src.networks.server.ws_server import start_server + +__all__ = ["start_server"] diff --git a/src/networks/server/ws_server.py b/src/networks/server/ws_server.py new file mode 100644 index 0000000..fb5e602 --- /dev/null +++ b/src/networks/server/ws_server.py @@ -0,0 +1,274 @@ +""" +策略服务器 (Strategy Server) + +基于FastAPI的WebSocket实现,接收K线数据,返回交易信号 +协议版本: v1.0 +""" + +from fastapi import FastAPI, WebSocket, WebSocketDisconnect +from pydantic import BaseModel +from typing import List, Optional +import uvicorn +import json +import uuid +from datetime import datetime + +from src.core.logger import get_logger + +logger = get_logger("StrategyServer") + +app = FastAPI(title="QTrade Strategy Server", version="1.0.0") + + +# ========== 数据模型 v1.0 ========== + + +class ProtocolHeader(BaseModel): + """协议头""" + + version: str = "1.0" + msg_id: str + timestamp: str # 可读格式: YYYY-MM-DD HH:MM:SS.mmm + req_msg_id: Optional[str] = None # 响应消息关联请求ID + + +class KlineDataModel(BaseModel): + """K线数据字段""" + + open: float + high: float + low: float + close: float + volume: int + + +class KlineData(BaseModel): + """单条K线数据消息""" + + header: ProtocolHeader + msg_type: str = "KLINE_DATA" + symbol: str + period: str # 1m, 5m, 15m, 30m, 1h, 1d, 1w, 1M + kline_time: str # K线时间: YYYY-MM-DD HH:MM:SS + data: KlineDataModel + + +class KlineDataBatch(BaseModel): + """批量K线数据消息""" + + header: ProtocolHeader + msg_type: str = "KLINE_DATA_BATCH" + + class KlineItem(BaseModel): + symbol: str + period: str + kline_time: str + data: KlineDataModel + + klines: List[KlineItem] + + +class TradeSignal(BaseModel): + """交易信号响应""" + + header: ProtocolHeader + msg_type: str = "TRADE_SIGNAL" + symbol: str + action: str # BUY, SELL, HOLD + price: float # 建议交易价格 + quantity: int # 交易数量(股数) + message: str = "" + + +class TradeSignalBatch(BaseModel): + """批量交易信号响应""" + + header: ProtocolHeader + msg_type: str = "TRADE_SIGNAL_BATCH" + + class SignalItem(BaseModel): + symbol: str + action: str + price: float + quantity: int + message: str = "" + + signals: List[SignalItem] + + +class ErrorMessage(BaseModel): + """错误消息""" + + header: ProtocolHeader + msg_type: str = "ERROR" + error_code: str + error_message: str + + +def create_response_header(req_header: ProtocolHeader) -> ProtocolHeader: + """创建响应协议头""" + return ProtocolHeader( + version="1.0", + msg_id=str(uuid.uuid4()), + timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3], + req_msg_id=req_header.msg_id, + ) + + +def execute_strategy(symbol: str, kline_data: KlineDataModel, period: str) -> dict: + """ + 执行策略逻辑 + + TODO: 实现真实策略 + 当前返回HOLD信号 + """ + return { + "action": "HOLD", + "price": kline_data.close, + "quantity": 0, + "message": "暂无策略", + } + + +# ========== API接口 ========== + + +@app.websocket("/ws/strategy") +async def websocket_strategy(websocket: WebSocket): + """ + WebSocket策略接口 v1.0 + + 接收K线数据,返回交易信号 + 支持单条和批量模式 + """ + await websocket.accept() + logger.info("WebSocket client connected") + + try: + while True: + # 接收消息 + data = await websocket.receive_text() + message_dict = json.loads(data) + + msg_type = message_dict.get("msg_type") + + # 检查协议版本 + header_data = message_dict.get("header", {}) + if header_data.get("version") != "1.0": + error = ErrorMessage( + header=ProtocolHeader( + version="1.0", + msg_id=str(uuid.uuid4()), + timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3], + req_msg_id=header_data.get("msg_id"), + ), + error_code="INVALID_VERSION", + error_message=f"Unsupported protocol version: {header_data.get('version')}", + ) + await websocket.send_text(error.model_dump_json()) + continue + + # 处理单条K线数据 + if msg_type == "KLINE_DATA": + try: + kline = KlineData(**message_dict) + + # 执行策略 + signal_data = execute_strategy( + kline.symbol, kline.data, kline.period + ) + + # 构建响应 + response = TradeSignal( + header=create_response_header(kline.header), + symbol=kline.symbol, + action=signal_data["action"], + price=signal_data["price"], + quantity=signal_data["quantity"], + message=signal_data["message"], + ) + + await websocket.send_text(response.model_dump_json()) + + except Exception as e: + error = ErrorMessage( + header=create_response_header(kline.header), + error_code="STRATEGY_ERROR", + error_message=str(e), + ) + await websocket.send_text(error.model_dump_json()) + + # 处理批量K线数据 + elif msg_type == "KLINE_DATA_BATCH": + try: + kline_batch = KlineDataBatch(**message_dict) + + # 对每条K线执行策略 + signals = [] + for kline_item in kline_batch.klines: + signal_data = execute_strategy( + kline_item.symbol, kline_item.data, kline_item.period + ) + signals.append( + TradeSignalBatch.SignalItem( + symbol=kline_item.symbol, + action=signal_data["action"], + price=signal_data["price"], + quantity=signal_data["quantity"], + message=signal_data["message"], + ) + ) + + # 构建批量响应 + response = TradeSignalBatch( + header=create_response_header(kline_batch.header), + signals=signals, + ) + + await websocket.send_text(response.model_dump_json()) + + except Exception as e: + error = ErrorMessage( + header=create_response_header(kline_batch.header), + error_code="STRATEGY_ERROR", + error_message=str(e), + ) + await websocket.send_text(error.model_dump_json()) + + else: + # 未知消息类型 + error = ErrorMessage( + header=ProtocolHeader( + version="1.0", + msg_id=str(uuid.uuid4()), + timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3], + ), + error_code="INVALID_DATA", + error_message=f"Unknown message type: {msg_type}", + ) + await websocket.send_text(error.model_dump_json()) + + except WebSocketDisconnect: + logger.info("WebSocket client disconnected") + except Exception as e: + logger.error(f"WebSocket error: {e}") + await websocket.close() + + +# ========== 启动服务器 ========== + + +def start_server(host: str = "0.0.0.0", port: int = 8000): + """ + 启动策略服务器 + + Args: + host: 监听地址 + port: 监听端口 + """ + logger.info(f"Starting strategy server on {host}:{port}") + uvicorn.run(app, host=host, port=port, log_level="info") + + +if __name__ == "__main__": + start_server() diff --git a/test_run.py b/test_run.py new file mode 100644 index 0000000..e2ffb03 --- /dev/null +++ b/test_run.py @@ -0,0 +1,65 @@ +""" +测试启动脚本 - 简单版本 + +先启动服务器,等待一段时间后启动客户端 +""" + +import subprocess +import sys +import time +from pathlib import Path + +# 工作目录 +workspace = Path(__file__).parent + + +def start_server(): + """启动服务器进程(在新的控制台窗口)""" + print("=" * 60) + print("正在启动 QTrade Server(新窗口)...") + print("=" * 60) + subprocess.Popen( + [sys.executable, "-m", "src.networks.server.ws_server"], + cwd=workspace, + creationflags=subprocess.CREATE_NEW_CONSOLE, # Windows下在新控制台窗口启动 + ) + print("✓ 服务器已在新窗口启动,等待5秒...") + + +def start_client(): + """启动客户端进程(直接显示输出)""" + print("\n" + "=" * 60) + print("正在启动 Backtest Client...") + print("=" * 60) + subprocess.run([sys.executable, "-m", "src.backtest.main"], cwd=workspace) + + +def main(): + """主函数""" + if len(sys.argv) > 1 and sys.argv[1] == "server": + # 只启动服务器 + start_server() + elif len(sys.argv) > 1 and sys.argv[1] == "client": + # 只启动客户端 + start_client() + elif len(sys.argv) > 1 and sys.argv[1] == "both": + # 同时启动服务器和客户端 + print("=" * 60) + print("同时启动服务器和客户端") + print("=" * 60) + start_server() + time.sleep(5) # 等待服务器启动 + print("\n现在启动客户端...") + start_client() + else: + print("使用方法:") + print(" 启动服务器: python test_run.py server") + print(" 启动客户端: python test_run.py client") + print(" 同时启动: python test_run.py both") + print("\n建议:") + print(" 1. 先运行: python test_run.py server (会弹出新窗口)") + print(" 2. 然后运行: python test_run.py client") + + +if __name__ == "__main__": + main()