diff --git a/test_run.py b/backtest_runner.py similarity index 100% rename from test_run.py rename to backtest_runner.py diff --git a/configs/backtest.yaml b/configs/backtest.yaml index b76b330..6d73889 100644 --- a/configs/backtest.yaml +++ b/configs/backtest.yaml @@ -23,10 +23,10 @@ cache: # ==================== 日志配置 ==================== logging: enabled: true + prompt_level: ["ERROR", "WARNING", "INFO"] filepath: "d:\\workspace\\QTrade\\logs" max_size: 10485760 # 10MB backup_count: 5 - level: "DEBUG" path: "logs/backtest" # ==================== 策略配置 ==================== diff --git a/configs/global.yaml b/configs/global.yaml index f43091d..8a1d5d2 100644 --- a/configs/global.yaml +++ b/configs/global.yaml @@ -6,4 +6,4 @@ # - production: 实盘环境,加载 configs/production.yaml # ==================== 环境模式配置 ==================== -current_mode: "backtest" \ No newline at end of file +current_mode: "production" # 可选值: backtest, simulation, production \ No newline at end of file diff --git a/configs/production.yaml b/configs/production.yaml index 08ff40f..6ac95fe 100644 --- a/configs/production.yaml +++ b/configs/production.yaml @@ -23,10 +23,10 @@ cache: # ==================== 日志配置 ==================== logging: enabled: true + prompt_level: ["ERROR", "WARNING", "INFO"] filepath: "d:\\workspace\\QTrade\\logs" max_size: 10485760 # 10MB backup_count: 5 - level: "INFO" path: "logs/production" # ==================== 策略配置 ==================== @@ -40,6 +40,14 @@ client_adapters: server_url: "ws://localhost:8010/ws/strategy" timeout: 30 # seconds +# ==================== MiniQMT 实盘交易配置 ==================== +miniqmt: + userdata_path: "D:\\国金QMT交易端模拟\\userdata_mini" # MiniQMT userdata_mini 路径 + session_id: 123456 # 会话ID(不同策略使用不同ID) + account: + account_id: "40004091" # 交易账号 + account_type: "STOCK" # 账户类型(STOCK/HUGANGTONG/SHENGANGTONG) + # ==================== 下载数据源配置 ==================== data_downloader: downloader: "xtquant" diff --git a/configs/simulation.yaml b/configs/simulation.yaml index 04dc001..9c7dc0a 100644 --- a/configs/simulation.yaml +++ b/configs/simulation.yaml @@ -23,10 +23,10 @@ cache: # ==================== 日志配置 ==================== logging: enabled: true + prompt_level: ["ERROR", "WARNING", "INFO"] filepath: "d:\\workspace\\QTrade\\logs" max_size: 10485760 # 10MB backup_count: 5 - level: "DEBUG" path: "logs/simulation" # ==================== 策略配置 ==================== diff --git a/configs/strategies/debug_000001.yaml b/configs/strategies/debug_000001.yaml index 571ea31..fcaa625 100644 --- a/configs/strategies/debug_000001.yaml +++ b/configs/strategies/debug_000001.yaml @@ -2,7 +2,10 @@ # 平安银行 - 每条K线都打印,不生成信号 instance_id: "debug_000001" -symbol: "000001.SZ" +symbol: "000001.SZ" # 股票代码 +symbol_name: "平安银行" # 股票名称 +symbol_type: "stock" # 股票类型,stock,etf,future,option,bond +symbol_decimal_places: 2 # 小数位数, 股票为2,期货,ETF等为3 strategy_class: "DebugStrategy" capital: 100000 @@ -15,3 +18,18 @@ params: risk: max_position_ratio: 0.8 # 最大仓位80% stop_loss: 0.05 # 止损5% + +# ==================== 仅对回测生效 ==================== +# 交易费率配置 +backtrade: + trading_type: t1 # 交易类型 T+0 或 T+1 + trading_fees: + commission_rate: 0.00005 # 佣金率 0.005%(买卖双向收取)ETF 为万0.5, 股票为万0.85 + min_commission: 5.0 # 最低佣金 5元 + stamp_tax_rate: 0.001 # 印花税率 0.1%(仅卖出时收取) + transfer_fee_rate: 0.00002 # 过户费率 0.002%(买卖双向收取), 万0.2 + slippage: 0.0001 # 滑点 0.01%(买卖双向影响) + start_date: "2025-01-01" # 回测开始日期 + end_date: "2025-12-31" # 回测结束日期 + period: "1m" # 回测K线周期 + diff --git a/docs/logger_prompt_level_guide.md b/docs/logger_prompt_level_guide.md new file mode 100644 index 0000000..f181df5 --- /dev/null +++ b/docs/logger_prompt_level_guide.md @@ -0,0 +1,102 @@ +# Logger prompt_level 配置说明 + +## 功能概述 + +Logger 已升级为使用 `prompt_level` 配置,替代原来的 `logging.level`。只有在 `prompt_level` 列表中的日志级别才会被输出。 + +## 配置方式 + +在环境配置文件(backtest.yaml / simulation.yaml / production.yaml)中设置: + +```yaml +logging: + enabled: true + prompt_level: ["ERROR", "WARNING", "INFO"] # 只输出这三个级别 + filepath: "d:\\workspace\\QTrade\\logs" + max_size: 10485760 # 10MB + backup_count: 5 + path: "logs/backtest" +``` + +## 支持的级别 + +- `"DEBUG"` - 调试信息 +- `"INFO"` - 一般信息 +- `"WARNING"` - 警告信息 +- `"ERROR"` - 错误信息 + +## 使用场景 + +### 1. 生产环境 - 只记录错误和警告 + +```yaml +prompt_level: ["ERROR", "WARNING"] +``` + +适用于生产环境,减少日志量,只关注问题。 + +### 2. 开发/测试环境 - 记录详细信息 + +```yaml +prompt_level: ["ERROR", "WARNING", "INFO", "DEBUG"] +``` + +适用于开发调试,查看所有日志。 + +### 3. 模拟环境 - 平衡模式 + +```yaml +prompt_level: ["ERROR", "WARNING", "INFO"] +``` + +适用于模拟交易,记录重要信息,过滤调试信息。 + +## 代码示例 + +```python +from core.config import Config +from core.logger import Logger + +# 初始化 +Config.initialize("simulation") # 使用 simulation.yaml 配置 +Logger.initialize() + +# 记录日志 +Logger.debug("调试信息") # 不会输出(不在 prompt_level 中) +Logger.info("一般信息") # 会输出 +Logger.warning("警告信息") # 会输出 +Logger.error("错误信息") # 会输出 +``` + +## 实现原理 + +1. **LevelFilter 过滤器**:自定义 logging.Filter,只允许指定级别通过 +2. **Logger 级别设置为 DEBUG**:允许所有级别的日志进入 +3. **Handler 添加过滤器**:在控制台和文件输出前进行过滤 + +## 优势 + +- ✅ **灵活性**:可以任意组合日志级别 +- ✅ **配置化**:通过 YAML 配置,无需修改代码 +- ✅ **性能**:不需要的日志在 handler 层就被过滤,不会写入文件 +- ✅ **清晰度**:配置文件明确显示哪些级别会被记录 + +## 测试验证 + +运行测试脚本验证功能: + +```bash +# 测试默认配置(ERROR, WARNING, INFO) +conda activate py311 +python test_logger_levels.py + +# 测试自定义配置(仅 ERROR, WARNING) +python test_logger_custom.py +``` + +## 注意事项 + +1. `prompt_level` 必须是列表类型,即使只有一个级别也要用 `["ERROR"]` +2. 级别名称必须是大写字符串:`"ERROR"`, `"WARNING"`, `"INFO"`, `"DEBUG"` +3. 如果 `prompt_level` 未配置,默认为 `["INFO", "WARNING", "ERROR"]` +4. 更改配置后需要重启应用才能生效 diff --git a/docs/realtrade_guide.md b/docs/realtrade_guide.md new file mode 100644 index 0000000..40479da --- /dev/null +++ b/docs/realtrade_guide.md @@ -0,0 +1,242 @@ +# 实盘交易使用说明 + +## 📋 概述 + +实盘交易模块使用 MiniQMT 进行真实市场交易。客户端先连接策略服务器获取交易信号,然后通过 MiniQMT API 执行实盘交易。 + +## ⚙️ 配置 + +### 1. 修改 `configs/production.yaml` + +```yaml +# ==================== MiniQMT 实盘交易配置 ==================== +miniqmt: + userdata_path: "D:\\国金QMT交易端模拟\\userdata_mini" # 修改为你的路径 + session_id: 123456 # 会话ID(不同策略使用不同ID) + account: + account_id: "40004091" # 修改为你的交易账号 + account_type: "STOCK" # 账户类型(STOCK/HUGANGTONG/SHENGANGTONG) + +# ==================== 客户端适配器配置 ==================== +client_adapters: + production_adapter: + server_url: "ws://localhost:8010/ws/strategy" + timeout: 30 # seconds +``` + +### 2. 配置说明 + +- **userdata_path**: MiniQMT 的 `userdata_mini` 文件夹路径 +- **session_id**: 会话编号,不同策略使用不同的 ID +- **account_id**: 你的交易账号 +- **account_type**: + - `STOCK`: 普通股票账户 + - `HUGANGTONG`: 沪港通 + - `SHENGANGTONG`: 深港通 + +## 🚀 启动方式 + +### 方式一:使用启动脚本(推荐) + +#### 1. 同时启动服务器和客户端(服务器新窗口,客户端当前窗口) +```bash +python realtrade_runner.py both +``` + +#### 2. 分别启动 + +**先启动服务器(新窗口):** +```bash +python realtrade_runner.py server newwindow +``` + +**再启动客户端(当前窗口):** +```bash +python realtrade_runner.py client +``` + +#### 3. 都在新窗口启动 +```bash +python realtrade_runner.py both newwindow +``` + +### 方式二:手动启动 + +#### 1. 先启动策略服务器 +```bash +python -m src.qtrade_server +``` + +#### 2. 等待5秒后启动实盘客户端 +```bash +python -m src.realtrade.main +``` + +## 📊 功能说明 + +### 1. 连接 MiniQMT +客户端启动时会自动连接 MiniQMT 交易接口: +- 建立交易连接 +- 订阅账户推送 +- 注册交易回调 + +### 2. 查询账户信息 +启动后会自动查询: +- 总资产 +- 可用资金 +- 冻结资金 +- 持仓市值 +- 总盈亏 +- 当前持仓列表 + +### 3. 获取交易信号 +通过 WebSocket 连接策略服务器: +- 发送 K线数据 +- 接收交易信号(BUY/SELL/HOLD) + +### 4. 执行交易(默认禁用) +**⚠️ 为安全起见,默认不自动执行交易信号!** + +如需启用自动交易,需要在 `src/realtrade/main.py` 中取消注释: + +```python +# 取消注释以下代码以执行实盘交易(危险操作!) +order_id = adapter.place_order( + symbol=signal.symbol, + action=signal.action, + price=signal.price, + quantity=signal.quantity, +) +``` + +### 5. 交易回调 +实时接收 MiniQMT 推送: +- 委托回报 +- 成交回报 +- 委托失败 +- 撤单失败 +- 账户状态变化 + +## 🔧 核心组件 + +### MiniQMTClientAdapter + +**初始化参数:** +- `server_url`: 策略服务器 WebSocket 地址 +- `timeout`: 超时时间 +- `miniqmt_path`: MiniQMT userdata_mini 路径 +- `session_id`: 会话ID +- `account_id`: 交易账号 +- `account_type`: 账户类型 + +**主要方法:** +```python +# 连接 MiniQMT +adapter.connect() + +# 发送 K线获取信号 +signal = adapter.send_kline(symbol, kline, kline_time, period) + +# 批量发送 K线 +signals = adapter.send_klines_batch(klines_data, kline_time, period) + +# 下单 +order_id = adapter.place_order(symbol, action, price, quantity) + +# 撤单 +adapter.cancel_order(order_id) + +# 查询资产 +asset = adapter.query_account_asset() + +# 查询持仓 +positions = adapter.query_positions() + +# 查询委托 +orders = adapter.query_orders() + +# 关闭连接 +adapter.close() +``` + +## ⚠️ 安全警告 + +### 实盘交易风险 + +1. **资金安全**: 这是真实市场交易,会产生真实的资金损失! +2. **策略测试**: 务必先在回测和模拟盘中充分测试策略 +3. **风控措施**: 设置止损、仓位控制等风险管理措施 +4. **监控**: 实时监控账户状态和交易情况 +5. **人工介入**: 必要时人工干预交易 + +### 建议 + +- ✅ 先在回测环境测试策略 +- ✅ 再在模拟盘环境验证 +- ✅ 小资金量测试实盘 +- ✅ 设置合理的风控参数 +- ✅ 24小时监控(或交易时段内) +- ❌ 不要使用未经测试的策略 +- ❌ 不要在实盘直接修改代码 +- ❌ 不要忽视风险提示 + +## 📝 日志 + +实盘交易日志保存在: +``` +logs/production/qtrade_YYYYMMDD.log +``` + +建议定期查看日志,了解: +- 连接状态 +- 交易信号 +- 订单执行情况 +- 异常错误 + +## 🔄 对比回测模式 + +| 特性 | 回测模式 | 实盘模式 | +| -------- | --------------------- | -------------------- | +| 数据源 | 历史数据 | 实时行情 | +| 交易执行 | 模拟撮合 | 真实下单 | +| 资金 | 虚拟资金 | 真实资金 | +| 风险 | 无风险 | 真实风险 | +| 服务器 | QTrade Server | QTrade Server | +| 客户端 | BacktestClientAdapter | MiniQMTClientAdapter | +| 配置文件 | backtest.yaml | production.yaml | +| 启动脚本 | backtest_runner.py | realtrade_runner.py | + +## 🆘 故障排除 + +### 1. MiniQMT 连接失败 +- 检查 `userdata_path` 路径是否正确 +- 确认 MiniQMT 是否已启动 +- 检查 `session_id` 是否与其他程序冲突 + +### 2. 策略服务器连接失败 +- 确认服务器是否已启动 +- 检查 `server_url` 配置是否正确 +- 查看服务器日志 + +### 3. 下单失败 +- 检查账户资金是否充足 +- 确认标的代码格式是否正确(如 "600000.SH") +- 检查交易时间段 +- 查看 MiniQMT 错误回调信息 + +### 4. 权限问题 +- 确认账户是否有交易权限 +- 检查是否在交易时间段内 +- 确认标的是否停牌 + +## 📞 技术支持 + +如有问题,请查看: +1. 日志文件:`logs/production/` +2. 配置文件:`configs/production.yaml` +3. 适配器代码:`src/realtrade/miniqmt_client_adapter.py` +4. 主程序:`src/realtrade/main.py` + +--- + +**再次提醒:实盘交易有风险,投资需谨慎!** diff --git a/docs/table_cleanup_summary.md b/docs/table_cleanup_summary.md new file mode 100644 index 0000000..a02a2c9 --- /dev/null +++ b/docs/table_cleanup_summary.md @@ -0,0 +1,137 @@ +# 表结构清理总结 + +## 完成的工作 + +### 1. 删除了旧的表定义 +从 `table_schemas.py` 中删除了以下旧表定义: +- ✅ **ORDER_TABLE** (旧版本) +- ✅ **TRADE_TABLE** (旧版本) +- ✅ **POSITION_TABLE** (旧版本) +- ✅ **ACCOUNT_TABLE** (已重命名为 ASSET_TABLE) +- ✅ **SYMBOL_TABLE** (Symbol 模型已删除,信息移至配置文件) + +### 2. 更新了表定义导入 +在 `table_schemas.py` 中: +```python +from .trading_table_schemas import ( + ORDER_TABLE, + TRADE_TABLE, + POSITION_TABLE, + ASSET_TABLE, +) +``` + +### 3. 更新了 SIGNAL_TABLE +添加了 `instance_id` 字段和相应索引: +```python +"instance_id": { + "type": "String", + "length": 50, + "nullable": False, + "comment": "策略实例ID", +} +``` + +索引: +```python +{"name": "idx_instance", "columns": ["instance_id"]} +``` + +### 4. 更新了 ALL_TABLES 字典 +```python +ALL_TABLES = { + **ALL_KLINE_TABLES, + **ALL_INDICATOR_TABLES, + "ticks": TICK_TABLE, + "signals": SIGNAL_TABLE, + # 交易相关表(从 trading_table_schemas 导入) + "orders": ORDER_TABLE, + "trades": TRADE_TABLE, + "positions": POSITION_TABLE, + "assets": ASSET_TABLE, # 不再是 accounts +} +``` + +### 5. 更新了模块导出 +更新 `database_manager/__init__.py`: +- 移除:ACCOUNT_TABLE, SYMBOL_TABLE +- 添加:从 `trading_table_schemas` 导入新的表定义 +- 新增:ASSET_TABLE + +### 6. 清理了未使用的导入 +- 从 `trading_table_schemas.py` 移除 `Dict, Any` +- 从 `trading_cache.py` 移除 `datetime` + +## 表结构对比 + +### 旧表 vs 新表 + +| 旧表名 | 新表名 | 变化 | +| -------------- | --------- | ----------------------------------------- | +| orders (旧) | orders | 完全重构,增加 instance_id 等字段 | +| trades (旧) | trades | 完全重构,增加 instance_id 和 cost_detail | +| positions (旧) | positions | 完全重构,增加大量统计字段 | +| accounts | assets | 重命名,增加完整的资产管理字段 | +| symbols | (删除) | 信息移至 YAML 配置文件 | + +## 核心改进 + +### 多策略实例隔离 +所有交易相关表都包含: +- `instance_id`: 策略实例ID(必填) +- `strategy_name`: 策略名称(必填) +- 相应的组合索引 + +### 字段统计 +- **ORDER_TABLE**: 22 个字段,6 个索引 +- **TRADE_TABLE**: 13 个字段,6 个索引 +- **POSITION_TABLE**: 29 个字段,4 个索引 +- **ASSET_TABLE**: 30 个字段,2 个索引 +- **SIGNAL_TABLE**: 13 个字段(新增 instance_id),5 个索引 + +## 测试结果 + +✅ 所有表定义正确导入 +✅ ALL_TABLES 包含所有新表 +✅ 旧表(accounts, symbols)已删除 +✅ 所有交易表包含 instance_id 字段 +✅ 所有必需索引已创建 +✅ 无 Python 语法错误 + +## 下一步 + +1. **测试数据库表创建** + - 使用 DatabaseManager 创建表 + - 验证表结构是否符合预期 + +2. **测试存储层** + - 使用 TradingDataStorage 保存和读取数据 + - 验证 instance_id 隔离是否有效 + +3. **测试缓存层** + - 使用 TradingCache 缓存和检索数据 + - 验证实例隔离逻辑 + +4. **集成到回测引擎** + - 在回测任务中使用新的表结构 + - 验证多策略实例是否正确隔离 + +## 文件变更清单 + +### 修改的文件 +- ✅ `src/database_manager/table_schemas.py` - 删除旧表,更新导入 +- ✅ `src/database_manager/__init__.py` - 更新导出 +- ✅ `src/database_manager/trading_table_schemas.py` - 清理导入 +- ✅ `src/cache/trading_cache.py` - 清理导入 + +### 新增的文件 +- ✅ `test_table_schemas.py` - 表结构测试脚本 + +### 已删除的定义 +- ❌ ORDER_TABLE (旧版本,约70行) +- ❌ TRADE_TABLE (旧版本,约60行) +- ❌ POSITION_TABLE (旧版本,约70行) +- ❌ ACCOUNT_TABLE (旧版本,约50行) +- ❌ SYMBOL_TABLE (约70行) + +**总删除行数**: ~320 行废弃代码 diff --git a/learning_matirals/CSkhQuant b/learning_matirals/CSkhQuant new file mode 160000 index 0000000..eb0f20c --- /dev/null +++ b/learning_matirals/CSkhQuant @@ -0,0 +1 @@ +Subproject commit eb0f20c8faa6425b7198bbf2692c0b4b749c243d diff --git a/learning_matirals/OSkhQuant b/learning_matirals/OSkhQuant deleted file mode 160000 index fe4c29d..0000000 --- a/learning_matirals/OSkhQuant +++ /dev/null @@ -1 +0,0 @@ -Subproject commit fe4c29d05b03b8cdc5832ee5f4bed83d5f271198 diff --git a/realtrade_runner.py b/realtrade_runner.py new file mode 100644 index 0000000..13cfa5c --- /dev/null +++ b/realtrade_runner.py @@ -0,0 +1,132 @@ +""" +实盘交易客户端启动脚本 + +使用 MiniQMT 进行实盘交易,先连接策略服务器获取信号,然后执行实盘交易 +""" + +import time +from datetime import datetime +import pandas as pd +import subprocess +import sys +import time +from pathlib import Path + +from src.core.config import Config +from src.core.logger import Logger +from src.realtrade.miniqmt_client_adapter import MiniQMTClientAdapter + + +workspace = Path(__file__).parent + +""" +股票池配置 + +定义实盘交易的股票池,包含股票代码、名称和K线周期 +""" + +STOCK_POOL = [ + {"symbol": "601288.SH", "symbol_name": "农业银行", "period": "1m"}, + {"symbol": "600593.SH", "symbol_name": "大连圣亚", "period": "5m"}, + # 添加更多股票... +] + + +def start_server_newwindow(): + """启动服务器进程(在新的控制台窗口)""" + print("=" * 60) + print("正在启动 QTrade Server(新窗口)...") + print("=" * 60) + subprocess.Popen( + [sys.executable, "-m", "src.qtrade_server"], + cwd=workspace, + creationflags=subprocess.CREATE_NEW_CONSOLE, # Windows下在新控制台窗口启动 + ) + print("✓ 服务器已在新窗口启动,等待5秒...") + + +def start_server(): + """启动服务器进程(直接显示输出)""" + print("=" * 60) + print("正在启动 QTrade Server...") + print("=" * 60) + try: + subprocess.run([sys.executable, "-m", "src.qtrade_server"], cwd=workspace) + except KeyboardInterrupt: + print("\n✓ 服务器已正常关闭") + + +def main(): + config = Config.initialize("production") + Logger.initialize("realtrade") + Logger.info("=" * 60) + Logger.info("启动 QTrade 实盘交易客户端") + Logger.info("=" * 60) + if not config: + Logger.error("✗ 配置加载失败,退出程序") + return + Logger.info("配置加载完成") + + """实盘交易主函数""" + + # 启动服务端 + Logger.info("\n启动策略服务器...") + start_server_newwindow() + Logger.info("✓ 策略服务器启动命令已发送,等待5秒...") + time.sleep(5) # 等待服务器启动 + + # 启动miniQMT客户端适配器 + Logger.info("\n初始化 MiniQMT 客户端适配器...") + + # 从配置获取参数 + server_url = config.get("client_adapters.production_adapter.server_url") + timeout = config.get("client_adapters.production_adapter.timeout", 30) + + miniqmt_path = config.get("miniqmt.userdata_path") + session_id = config.get("miniqmt.session_id", 123456) + account_id = config.get("miniqmt.account.account_id") + account_type = config.get("miniqmt.account.account_type", "STOCK") + + Logger.info(f"服务器地址: {server_url}") + Logger.info(f"MiniQMT 路径: {miniqmt_path}") + Logger.info(f"交易账号: {account_id}") + Logger.info(f"账户类型: {account_type}") + + # 创建实盘客户端适配器 + adapter = MiniQMTClientAdapter( + server_url=server_url, + timeout=timeout, + miniqmt_path=miniqmt_path, + session_id=session_id, + account_id=account_id, + account_type=account_type, + stockpool=STOCK_POOL, + ) + # 连接 MiniQMT + Logger.info("\n连接 MiniQMT 交易接口...") + if not adapter.run(): + Logger.error("MiniQMT 连接失败,退出程序") + return + + Logger.info("✓ MiniQMT 连接成功") + + try: + # 保持连接,接收交易推送 + Logger.info("\n" + "=" * 60) + Logger.info("实盘交易客户端运行中...") + Logger.info("按 Ctrl+C 退出") + Logger.info("=" * 60) + + except KeyboardInterrupt: + Logger.info("\n\n收到退出信号,正在关闭...") + + except Exception as e: + Logger.error(f"运行异常: {e}", exc_info=True) + finally: + # 关闭连接 + adapter.close() + Logger.info("✓ 实盘交易客户端已关闭") + + +if __name__ == "__main__": + main() diff --git a/requirements.txt b/requirements.txt index a3a5b83..88ef601 100644 --- a/requirements.txt +++ b/requirements.txt @@ -36,4 +36,5 @@ pytz>=2023.0 xtquant # 迅投QMT数据源 fastapi>=0.95.0 # 用于构建API服务 uvicorn[standard] -websockets>=11.0.0 # 用于WebSocket通信 \ No newline at end of file +websockets>=11.0.0 # 用于WebSocket通信 +pyyaml \ No newline at end of file diff --git a/simple_kline_viewer.py b/simple_kline_viewer.py index c16f56c..32814ed 100644 --- a/simple_kline_viewer.py +++ b/simple_kline_viewer.py @@ -118,8 +118,8 @@ class KlineCanvas(FigureCanvasQTAgg): def _load_indicator_config(self): """加载指标配置参数""" try: - config = Config("configs/global.yaml") - indicators_config = config.get("indicators") + # 使用Config单例,无需初始化 + indicators_config = Config.get("indicators") if not indicators_config: raise ValueError("配置文件中未找到 'indicators' 配置项") @@ -131,7 +131,7 @@ class KlineCanvas(FigureCanvasQTAgg): except Exception as e: print(f"\n❌ 配置文件读取失败: {e}") - print("请检查 configs/global.yaml 文件中的 indicators 配置项") + print("请检查配置文件中的 indicators 配置项") sys.exit(1) def _load_macd_config(self, indicators_config): @@ -1071,13 +1071,22 @@ def main(): if "py311" not in sys.executable.lower(): print("警告: 建议使用py311环境") - # 加载配置和DataService + # 初始化配置(使用Config单例) try: - config = Config("configs/backtest.yaml") - data_service = DataService.from_config(config) + Config.initialize() + print("✓ Config初始化成功") + except Exception as e: + print(f"✗ Config初始化失败: {e}") + traceback.print_exc() + sys.exit(1) + + # 初始化DataService + try: + data_service = DataService.from_config() print("✓ DataService初始化成功") except Exception as e: print(f"✗ DataService初始化失败: {e}") + traceback.print_exc() sys.exit(1) # 创建应用 diff --git a/src/backtest/bt_task.py b/src/backtest/bt_task.py index d25e2f7..c343d05 100644 --- a/src/backtest/bt_task.py +++ b/src/backtest/bt_task.py @@ -24,8 +24,15 @@ class BacktestTask: strategy_name: str, strategy_params: Optional[dict] = None, initial_capital: float = 100000.0, + trading_type: str = "t1", commission_rate: float = 0.0003, - slippage_rate: float = 0.0001, + min_commission: float = 5.0, + stamp_tax_rate: float = 0.001, + transfer_fee_rate: float = 0.00002, + slippage: float = 0.0001, + symbol_name: Optional[str] = None, + symbol_type: str = "stock", + symbol_decimal_places: int = 2, ): """ 初始化回测任务 @@ -38,8 +45,15 @@ class BacktestTask: strategy_name: 策略名称 strategy_params: 策略参数字典 initial_capital: 初始资金 - commission_rate: 手续费率 - slippage_rate: 滑点率 + trading_type: 交易类型(t0/t1,T+0或T+1) + commission_rate: 佣金率(买卖双向收取) + min_commission: 最低佣金 + stamp_tax_rate: 印花税率(仅卖出时收取) + transfer_fee_rate: 过户费率(买卖双向收取) + slippage: 滑点(买卖双向影响) + symbol_name: 标的名称 + symbol_type: 标的类型(stock/etf/future/option/bond) + symbol_decimal_places: 价格小数位数(股票为2,期货/ETF等为3) """ # 参数验证 if not symbols: @@ -57,8 +71,21 @@ class BacktestTask: self.strategy_name = strategy_name self.strategy_params = strategy_params or {} self.initial_capital = initial_capital + + # 标的信息 + self.symbol_name = symbol_name + self.symbol_type = symbol_type + self.symbol_decimal_places = symbol_decimal_places + + # 交易配置 + self.trading_type = trading_type.lower() # 统一转为小写 + + # 交易费率配置 self.commission_rate = commission_rate - self.slippage_rate = slippage_rate + self.min_commission = min_commission + self.stamp_tax_rate = stamp_tax_rate + self.transfer_fee_rate = transfer_fee_rate + self.slippage = slippage def __repr__(self) -> str: """字符串表示""" diff --git a/src/backtest/bt_task_loader.py b/src/backtest/bt_task_loader.py new file mode 100644 index 0000000..a3da1f1 --- /dev/null +++ b/src/backtest/bt_task_loader.py @@ -0,0 +1,212 @@ +""" +回测任务加载器 (Backtest Task Loader) + +从配置文件加载回测任务配置,自动生成 BacktestTask 对象 +""" + +from typing import Dict, Any +from datetime import datetime +from pathlib import Path +import yaml + +from src.backtest.bt_task import BacktestTask +from src.core.logger import Logger + + +class BacktestTaskLoader: + """ + 回测任务加载器 + + 从策略配置文件(YAML)中读取配置,自动生成回测任务对象 + """ + + @staticmethod + def load_from_file(config_path: str) -> BacktestTask: + """ + 从配置文件加载回测任务 + + Args: + config_path: 配置文件路径 + + Returns: + BacktestTask 对象 + + Raises: + FileNotFoundError: 配置文件不存在 + ValueError: 配置文件格式错误或缺少必要字段 + """ + # 检查文件是否存在 + config_file = Path(config_path) + if not config_file.exists(): + raise FileNotFoundError(f"配置文件不存在: {config_path}") + + # 读取 YAML 配置 + Logger.info(f"加载回测配置: {config_path}") + with open(config_file, "r", encoding="utf-8") as f: + config = yaml.safe_load(f) + + # 解析并创建任务 + return BacktestTaskLoader._parse_config(config, config_path) + + @staticmethod + def _parse_config(config: Dict[str, Any], config_path: str) -> BacktestTask: + """ + 解析配置字典,生成 BacktestTask 对象 + + Args: + config: 配置字典 + config_path: 配置文件路径(用于日志) + + Returns: + BacktestTask 对象 + """ + # 验证必要字段 + required_fields = ["symbol", "strategy_class", "capital"] + for field in required_fields: + if field not in config: + raise ValueError(f"配置文件缺少必要字段: {field}") + + # 检查回测配置 + if "backtrade" not in config: + raise ValueError("配置文件缺少 'backtrade' 回测配置") + + backtrade = config["backtrade"] + if "start_date" not in backtrade: + raise ValueError("回测配置缺少 'start_date'") + if "end_date" not in backtrade: + raise ValueError("回测配置缺少 'end_date'") + if "period" not in backtrade: + raise ValueError("回测配置缺少 'period'") + + # 解析基本信息 + symbols = [config["symbol"]] # 单个标的转为列表 + strategy_name = config["strategy_class"] + initial_capital = float(config["capital"]) + + # 解析日期 + start_date = BacktestTaskLoader._parse_date(backtrade["start_date"]) + end_date = BacktestTaskLoader._parse_date(backtrade["end_date"]) + period = backtrade["period"] + + # 解析策略参数 + strategy_params = config.get("params", {}) + + # 解析标的信息(必填) + if "symbol_name" not in config: + raise ValueError("配置文件缺少必要字段: symbol_name") + if "symbol_type" not in config: + raise ValueError("配置文件缺少必要字段: symbol_type") + if "symbol_decimal_places" not in config: + raise ValueError("配置文件缺少必要字段: symbol_decimal_places") + + symbol_name = config["symbol_name"] + symbol_type = config["symbol_type"] + symbol_decimal_places = config["symbol_decimal_places"] + + # 解析交易类型(必填) + if "trading_type" not in backtrade: + raise ValueError("回测配置缺少必要字段: trading_type") + trading_type = backtrade["trading_type"] + + # 解析交易费率配置(必填) + if "trading_fees" not in backtrade: + raise ValueError("回测配置缺少必要字段: trading_fees") + + trading_fees = backtrade["trading_fees"] + + # 验证所有交易费率字段 + required_fee_fields = [ + "commission_rate", + "min_commission", + "stamp_tax_rate", + "transfer_fee_rate", + "slippage", + ] + for field in required_fee_fields: + if field not in trading_fees: + raise ValueError(f"交易费率配置缺少必要字段: {field}") + + commission_rate = trading_fees["commission_rate"] + min_commission = trading_fees["min_commission"] + stamp_tax_rate = trading_fees["stamp_tax_rate"] + transfer_fee_rate = trading_fees["transfer_fee_rate"] + slippage = trading_fees["slippage"] + + # 创建任务对象 + task = BacktestTask( + symbols=symbols, + start_date=start_date, + end_date=end_date, + period=period, + strategy_name=strategy_name, + strategy_params=strategy_params, + initial_capital=initial_capital, + trading_type=trading_type, + commission_rate=commission_rate, + min_commission=min_commission, + stamp_tax_rate=stamp_tax_rate, + transfer_fee_rate=transfer_fee_rate, + slippage=slippage, + symbol_name=symbol_name, + symbol_type=symbol_type, + symbol_decimal_places=symbol_decimal_places, + ) + + Logger.info(f"回测任务加载成功: {task}") + Logger.debug(f" 标的: {symbols[0]} ({symbol_name})") + Logger.debug(f" 策略: {strategy_name}") + Logger.debug(f" 周期: {period}") + Logger.debug(f" 时间: {start_date.date()} ~ {end_date.date()}") + Logger.debug(f" 初始资金: {initial_capital:,.2f}") + Logger.debug(f" 交易类型: {trading_type.upper()}") + Logger.debug( + f" 佣金率: {commission_rate * 10000:.2f}‱ (最低{min_commission}元)" + ) + Logger.debug(f" 印花税率: {stamp_tax_rate * 10000:.2f}‱ (仅卖出)") + Logger.debug(f" 过户费率: {transfer_fee_rate * 10000:.2f}‱") + Logger.debug(f" 滑点: {slippage * 10000:.2f}‱") + + return task + + @staticmethod + def _parse_date(date_str: str) -> datetime: + """ + 解析日期字符串 + + Args: + date_str: 日期字符串,支持格式 'YYYY-MM-DD' 或 'YYYYMMDD' + + Returns: + datetime 对象 + """ + if isinstance(date_str, datetime): + return date_str + + # 尝试不同的日期格式 + formats = ["%Y-%m-%d", "%Y%m%d", "%Y/%m/%d"] + for fmt in formats: + try: + return datetime.strptime(date_str, fmt) + except ValueError: + continue + + raise ValueError( + f"无法解析日期格式: {date_str},支持格式: YYYY-MM-DD, YYYYMMDD, YYYY/MM/DD" + ) + + +def load_backtest_task(config_path: str) -> BacktestTask: + """ + 便捷函数:从配置文件加载回测任务 + + Args: + config_path: 配置文件路径 + + Returns: + BacktestTask 对象 + + Example: + >>> task = load_backtest_task("configs/strategies/debug_000001.yaml") + >>> print(task) + """ + return BacktestTaskLoader.load_from_file(config_path) diff --git a/src/backtest/main.py b/src/backtest/main.py index 04a7670..010ab58 100644 --- a/src/backtest/main.py +++ b/src/backtest/main.py @@ -10,6 +10,7 @@ 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.backtest.bt_task_loader import BacktestTaskLoader from src.core.logger import Logger from src.core.config import Config @@ -41,15 +42,7 @@ def main(): 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, - ) + task = BacktestTaskLoader.load_from_file("configs/strategies/debug_000001.yaml") # Add task engine.add_task(task) diff --git a/src/cache/__init__.py b/src/cache/__init__.py index 4869103..e5e8596 100644 --- a/src/cache/__init__.py +++ b/src/cache/__init__.py @@ -1,10 +1,11 @@ """ 缓存模块 -提供市场数据和业务数据的内存缓存功能 +提供市场数据和交易数据的内存缓存功能 注意:推荐使用 src.data.DataService 作为统一数据访问接口 """ from .cache_manager import CacheManager +from .trading_cache import TradingCache -__all__ = ["CacheManager"] +__all__ = ["CacheManager", "TradingCache"] diff --git a/src/cache/cache_manager.py b/src/cache/cache_manager.py index b6363c0..25db9d5 100644 --- a/src/cache/cache_manager.py +++ b/src/cache/cache_manager.py @@ -5,6 +5,7 @@ 职责:只负责数据的存取,不涉及数据加载、验证、计算 """ +from datetime import datetime import logging from typing import Dict, Optional, Any import pandas as pd @@ -51,14 +52,22 @@ class CacheManager: f"db_fallback={'enabled' if db_manager else 'disabled'}" ) - def get_klines(self, symbol: str, period: str) -> Optional[pd.DataFrame]: + # 只从cache中获取数据,如果开始时间为空,则返回所有数据 + def get_klines_from_cache( + self, + symbol: str, + period: str, + startdate: Optional[datetime] = None, + enddate: Optional[datetime] = None, + ) -> Optional[pd.DataFrame]: """ - 获取K线数据(带数据库降级) + 获取K线数据(纯缓存查询,不访问数据库) Args: symbol: 标的代码 period: 周期 - + startdate: 开始时间(可选),为None时返回所有缓存数据 + enddate: 结束时间(可选),为None时返回所有缓存数据 Returns: K线DataFrame或None """ @@ -67,19 +76,83 @@ class CacheManager: key = self._make_key(symbol, period) + if key in self._cache: + cached = self._cache[key] + klines = cached.get("klines") + + if klines is not None and not klines.empty: + # 如果没有指定时间范围,返回所有缓存数据 + if startdate is None or enddate is None: + logger.debug(f"Cache query (no filter): {key}, {len(klines)} rows") + return klines + + # 根据时间范围过滤 + filtered_data = klines[ + (klines.index >= startdate) & (klines.index <= enddate) + ] + logger.debug( + f"Cache query (filtered): {key}, " + f"{len(filtered_data)} rows from {len(klines)} cached rows" + ) + return filtered_data if not filtered_data.empty else None + + return None + + # 获取指定周期与时间范围的K线数据 + def get_klines( + self, symbol: str, period: str, startdate: datetime, enddate: datetime + ) -> Optional[pd.DataFrame]: + """ + 获取K线数据(带数据库降级和时间范围过滤) + + Args: + symbol: 标的代码 + period: 周期 + startdate: 开始时间 + enddate: 结束时间 + Returns: + K线DataFrame或None(已过滤到指定时间范围) + """ + if not self.enabled: + return None + + key = self._make_key(symbol, period) + # 1. 先查缓存 if key in self._cache: cached = self._cache[key] cache_data = cached.get("klines") if cache_data is not None and not cache_data.empty: - return cache_data + # 检查缓存数据的时间范围 + cache_start = cache_data.index.min() + cache_end = cache_data.index.max() - # 2. 缓存未命中,尝试从数据库加载 + # 判断缓存是否覆盖请求的时间范围 + if cache_start <= startdate and cache_end >= enddate: + # 缓存完全覆盖,直接过滤返回 + filtered_data = cache_data[ + (cache_data.index >= startdate) & (cache_data.index <= enddate) + ] + logger.debug( + f"Cache hit: {key}, filtered {len(filtered_data)} rows " + f"from {len(cache_data)} cached rows" + ) + return filtered_data if not filtered_data.empty else None + else: + # 缓存不完全覆盖,需要从数据库重新加载 + logger.debug( + f"Cache partial hit: {key}, " + f"cached[{cache_start.date()}~{cache_end.date()}] " + f"requested[{startdate.date()}~{enddate.date()}], " + f"reloading from database" + ) + + # 2. 缓存未命中或不完整,尝试从数据库加载 if self._db_manager: logger.debug(f"Cache miss: {key}, loading from database") try: - # 从数据库加载所有数据 + # 从数据库加载所有数据(为了缓存完整数据) df = self._db_manager.load_klines_all(symbol, period) if df is not None and not df.empty: @@ -88,7 +161,14 @@ class CacheManager: logger.info( f"Loaded {len(df)} rows from database and cached: {key}" ) - return df + + # 过滤到请求的时间范围 + filtered_data = df[(df.index >= startdate) & (df.index <= enddate)] + logger.debug( + f"Filtered {len(filtered_data)} rows " + f"from {len(df)} database rows" + ) + return filtered_data if not filtered_data.empty else None except Exception as e: logger.error(f"Failed to load from database: {key}, error: {e}") diff --git a/src/cache/trading_cache.py b/src/cache/trading_cache.py new file mode 100644 index 0000000..13fed72 --- /dev/null +++ b/src/cache/trading_cache.py @@ -0,0 +1,166 @@ +""" +交易数据缓存管理器 + +为 Order, Trade, Position, Asset 提供内存缓存 +""" + +from typing import Dict, List, Optional + +from src.core.models import Order, Trade, Position, Asset +from src.core.logger import Logger + + +class TradingCache: + """ + 交易数据缓存管理器 + + 提供交易数据的快速内存访问,按策略实例隔离 + """ + + def __init__(self): + """初始化交易缓存""" + # 缓存结构:{instance_id: {...}} + self._orders: Dict[ + str, Dict[str, Order] + ] = {} # {instance_id: {order_id: Order}} + self._trades: Dict[str, List[Trade]] = {} # {instance_id: [Trade, ...]} + self._positions: Dict[ + str, Dict[str, Position] + ] = {} # {instance_id: {symbol: Position}} + self._assets: Dict[str, Asset] = {} # {instance_id: Asset} + + Logger.info("TradingCache initialized") + + # ==================== Order 缓存 ==================== + + def cache_order(self, order: Order) -> None: + """缓存订单""" + if order.instance_id not in self._orders: + self._orders[order.instance_id] = {} + + self._orders[order.instance_id][order.order_id] = order + Logger.debug(f"Cached order: {order.order_id}") + + def get_order(self, instance_id: str, order_id: str) -> Optional[Order]: + """获取订单""" + if instance_id in self._orders: + return self._orders[instance_id].get(order_id) + return None + + def get_orders_by_instance(self, instance_id: str) -> List[Order]: + """获取实例的所有订单""" + if instance_id in self._orders: + return list(self._orders[instance_id].values()) + return [] + + def get_orders_by_symbol(self, instance_id: str, symbol: str) -> List[Order]: + """获取实例某个标的的所有订单""" + orders = self.get_orders_by_instance(instance_id) + return [o for o in orders if o.symbol == symbol] + + # ==================== Trade 缓存 ==================== + + def cache_trade(self, trade: Trade) -> None: + """缓存成交记录""" + if trade.instance_id not in self._trades: + self._trades[trade.instance_id] = [] + + self._trades[trade.instance_id].append(trade) + Logger.debug(f"Cached trade: {trade.trade_id}") + + def get_trades_by_instance(self, instance_id: str) -> List[Trade]: + """获取实例的所有成交""" + return self._trades.get(instance_id, []) + + def get_trades_by_symbol(self, instance_id: str, symbol: str) -> List[Trade]: + """获取实例某个标的的所有成交""" + trades = self.get_trades_by_instance(instance_id) + return [t for t in trades if t.symbol == symbol] + + def get_trades_by_order(self, instance_id: str, order_id: str) -> List[Trade]: + """获取某个订单的所有成交""" + trades = self.get_trades_by_instance(instance_id) + return [t for t in trades if t.order_id == order_id] + + # ==================== Position 缓存 ==================== + + def cache_position(self, position: Position) -> None: + """缓存持仓""" + if position.instance_id not in self._positions: + self._positions[position.instance_id] = {} + + self._positions[position.instance_id][position.symbol] = position + Logger.debug(f"Cached position: {position.instance_id}_{position.symbol}") + + def get_position(self, instance_id: str, symbol: str) -> Optional[Position]: + """获取持仓""" + if instance_id in self._positions: + return self._positions[instance_id].get(symbol) + return None + + def get_positions_by_instance(self, instance_id: str) -> List[Position]: + """获取实例的所有持仓""" + if instance_id in self._positions: + return list(self._positions[instance_id].values()) + return [] + + def remove_position(self, instance_id: str, symbol: str) -> None: + """移除持仓(持仓为0时)""" + if instance_id in self._positions and symbol in self._positions[instance_id]: + del self._positions[instance_id][symbol] + Logger.debug(f"Removed position: {instance_id}_{symbol}") + + # ==================== Asset 缓存 ==================== + + def cache_asset(self, asset: Asset) -> None: + """缓存资产""" + self._assets[asset.instance_id] = asset + Logger.debug(f"Cached asset: {asset.instance_id}") + + def get_asset(self, instance_id: str) -> Optional[Asset]: + """获取资产""" + return self._assets.get(instance_id) + + def get_all_assets(self) -> List[Asset]: + """获取所有资产""" + return list(self._assets.values()) + + # ==================== 批量操作 ==================== + + def clear_instance(self, instance_id: str) -> None: + """清除实例的所有缓存数据""" + if instance_id in self._orders: + del self._orders[instance_id] + if instance_id in self._trades: + del self._trades[instance_id] + if instance_id in self._positions: + del self._positions[instance_id] + if instance_id in self._assets: + del self._assets[instance_id] + + Logger.info(f"Cleared cache for instance: {instance_id}") + + def clear_all(self) -> None: + """清除所有缓存""" + self._orders.clear() + self._trades.clear() + self._positions.clear() + self._assets.clear() + + Logger.info("Cleared all trading cache") + + # ==================== 统计信息 ==================== + + def get_stats(self) -> Dict[str, int]: + """获取缓存统计信息""" + total_orders = sum(len(orders) for orders in self._orders.values()) + total_trades = sum(len(trades) for trades in self._trades.values()) + total_positions = sum(len(positions) for positions in self._positions.values()) + + return { + "instances": len(self._assets), + "orders": total_orders, + "trades": total_trades, + "positions": total_positions, + "assets": len(self._assets), + } diff --git a/src/core/__init__.py b/src/core/__init__.py index d6bf2ec..56bccb8 100644 --- a/src/core/__init__.py +++ b/src/core/__init__.py @@ -19,9 +19,8 @@ from .models import ( Order, Trade, Position, - Account, + Asset, Signal, - Symbol, ) # 配置管理 @@ -45,9 +44,8 @@ __all__ = [ "Order", "Trade", "Position", - "Account", + "Asset", "Signal", - "Symbol", # 配置 "Config", # 日志 diff --git a/src/core/config.py b/src/core/config.py index 25ce568..7ad3d53 100644 --- a/src/core/config.py +++ b/src/core/config.py @@ -16,19 +16,26 @@ class Config: - 单例模式,全局唯一实例 - 支持嵌套键访问(如 "database.host") - 自动根据 global.yaml 中的 current_mode 加载对应环境配置 + - 支持显式指定环境名称或配置文件路径 + - 配置文件不存在时自动回退到 global.yaml 并发出警告 - 通过类方法直接访问,无需传递实例 使用示例: - # 初始化配置(只需调用一次,通常在程序入口) - Config.initialize() # 自动读取 global.yaml 的 current_mode,然后加载对应配置 + # 方式1: 自动读取 global.yaml 的 current_mode + Config.initialize() + + # 方式2: 显式指定环境名称 + Config.initialize("backtest") # 回测环境 + Config.initialize("simulation") # 模拟环境 + Config.initialize("production") # 生产环境 + + # 方式3: 指定配置文件路径 + Config.initialize("configs/custom.yaml") # 获取配置(任意位置直接调用) db_host = Config.get("database.host") db_name = Config.get("database.database") - # 获取实例(如果需要) - config = Config.instance() - # 环境判断 if Config.is_production(): print("生产环境") @@ -52,36 +59,87 @@ class Config: return cls._instance @classmethod - def initialize(cls, file_path: Union[str, Path, None] = None) -> "Config": + def initialize(cls, env_mode: Union[str, Path, None] = None) -> "Config": """ 初始化配置(程序入口调用一次) 工作流程: - 1. 如果指定了 file_path,直接加载该配置文件 - 2. 否则,先读取 global.yaml 获取 current_mode - 3. 根据 current_mode 自动加载对应的配置文件(backtest.yaml/simulation.yaml/production.yaml) + 1. 如果 env_mode 是完整路径(Path 或包含 / \\ 的字符串),直接加载该配置文件 + 2. 如果 env_mode 是环境名称字符串(如 "backtest"),加载对应的配置文件 + 3. 如果环境配置文件不存在,回退到 global.yaml 并发出警告 + 4. 如果 env_mode 为 None,先读取 global.yaml 获取 current_mode,然后加载对应配置 Args: - file_path: 配置文件路径,如果为 None 则自动根据 current_mode 加载 + env_mode: 环境模式或配置文件路径 + - None: 自动从 global.yaml 读取 current_mode + - "backtest" / "simulation" / "production": 环境名称 + - Path 或文件路径字符串: 直接加载指定文件 Returns: Config 实例 Raises: - FileNotFoundError: 配置文件不存在 + FileNotFoundError: global.yaml 不存在 ValueError: current_mode 值无效 + + Examples: + >>> Config.initialize() # 自动读取 global.yaml 的 current_mode + >>> Config.initialize("backtest") # 显式指定回测环境 + >>> Config.initialize("production") # 显式指定生产环境 + >>> Config.initialize("configs/custom.yaml") # 指定配置文件路径 """ - if cls._initialized and file_path is None: + if cls._initialized and env_mode is None: return cls._instance # type: ignore instance = cls() - if file_path: + # 判断是否为文件路径(包含路径分隔符或是 Path 对象) + is_file_path = False + if env_mode is not None: + if isinstance(env_mode, Path): + is_file_path = True + elif isinstance(env_mode, str) and ( + "/" in env_mode + or "\\" in env_mode + or env_mode.endswith(".yaml") + or env_mode.endswith(".yml") + ): + is_file_path = True + + if is_file_path: # 直接加载指定的配置文件 - instance._load(file_path) - cls._current_mode = cls.get("environment.mode", "unknown") + if env_mode is not None: # 类型守卫 + instance._load(env_mode) + cls._current_mode = cls.get("environment.mode", "unknown") + elif env_mode is not None: + # 环境名称字符串(如 "backtest", "simulation", "production") + env_name = str(env_mode).lower() + + # 验证环境名称 + valid_envs = ["backtest", "simulation", "production"] + if env_name not in valid_envs: + print( + f"[WARNING] 未知的环境名称: {env_name},有效值为: {', '.join(valid_envs)}。" + f"回退到使用 global.yaml" + ) + # 回退到 global.yaml + instance._load_global_config() + cls._current_mode = "unknown" + else: + # 尝试加载对应的环境配置文件 + config_path = Path(cls.CONFIG_DIR) / f"{env_name}.yaml" + if config_path.exists(): + instance._load(config_path) + cls._current_mode = env_name + else: + # 配置文件不存在,回退到 global.yaml + print( + f"[WARNING] 环境配置文件不存在: {config_path}。回退到使用 global.yaml" + ) + instance._load_global_config() + cls._current_mode = env_name # 保留环境名称,但使用 global 配置 else: - # 先读取 global.yaml 获取 current_mode + # env_mode 为 None:先读取 global.yaml 获取 current_mode global_path = Path(cls.GLOBAL_CONFIG_PATH) if not global_path.exists(): raise FileNotFoundError(f"全局配置文件不存在: {global_path}") @@ -101,14 +159,33 @@ class Config: # 根据 current_mode 加载对应的配置文件 config_path = Path(cls.CONFIG_DIR) / f"{current_mode}.yaml" if not config_path.exists(): - raise FileNotFoundError(f"环境配置文件不存在: {config_path}") - - instance._load(config_path) - cls._current_mode = current_mode + # 配置文件不存在,回退到 global.yaml + print( + f"[WARNING] 环境配置文件不存在: {config_path}。回退到使用 global.yaml" + ) + instance._load_global_config() + cls._current_mode = current_mode + else: + instance._load(config_path) + cls._current_mode = current_mode cls._initialized = True return instance + def _load_global_config(self) -> None: + """ + 加载 global.yaml 配置(内部方法) + 当环境配置文件不存在时,回退使用此配置 + """ + global_path = Path(Config.GLOBAL_CONFIG_PATH) + if not global_path.exists(): + raise FileNotFoundError(f"全局配置文件不存在: {global_path}") + + with open(global_path, "r", encoding="utf-8") as f: + Config._data = yaml.safe_load(f) or {} + + Config._config_file = global_path + @classmethod def instance(cls) -> "Config": """ diff --git a/src/core/logger.py b/src/core/logger.py index 77a5652..c8ccbfd 100644 --- a/src/core/logger.py +++ b/src/core/logger.py @@ -8,11 +8,42 @@ import io import sys from pathlib import Path from logging.handlers import RotatingFileHandler -from typing import Dict, Optional +from typing import Dict, Optional, List from .config import Config +class LevelFilter(logging.Filter): + """ + 日志级别过滤器 + 只允许在指定级别列表中的日志通过 + """ + + def __init__(self, allowed_levels: List[str]): + """ + 初始化过滤器 + + Args: + allowed_levels: 允许的日志级别列表,如 ["ERROR", "WARNING", "INFO"] + """ + super().__init__() + self.allowed_levels = { + getattr(logging, level.upper()) for level in allowed_levels + } + + def filter(self, record: logging.LogRecord) -> bool: + """ + 判断日志记录是否应该被输出 + + Args: + record: 日志记录对象 + + Returns: + True 如果该级别在允许列表中,否则 False + """ + return record.levelno in self.allowed_levels + + class Logger: """ 日志管理类(单例模式) @@ -73,15 +104,22 @@ class Logger: return logger @classmethod - def _setup_logger(cls, logger: logging.Logger, name: str, level: str = "INFO") -> None: + def _setup_logger( + cls, logger: logging.Logger, name: str, level: str = "INFO" + ) -> None: """配置日志器""" - logger.setLevel(level) + # 设置为最低级别DEBUG,由Filter控制实际输出 + logger.setLevel(logging.DEBUG) # 日志格式 log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" formatter = logging.Formatter(log_format) + # 从配置读取允许的日志级别列表 + prompt_levels = Config.get("logging.prompt_level", ["INFO", "WARNING", "ERROR"]) + level_filter = LevelFilter(prompt_levels) + # 控制台处理器(UTF-8编码) utf8_stdout = io.TextIOWrapper( sys.stdout.buffer, @@ -90,8 +128,9 @@ class Logger: line_buffering=True, ) console_handler = logging.StreamHandler(utf8_stdout) - console_handler.setLevel(level) + console_handler.setLevel(logging.DEBUG) # Handler级别设为DEBUG console_handler.setFormatter(formatter) + console_handler.addFilter(level_filter) # 添加级别过滤器 logger.addHandler(console_handler) # 文件处理器 @@ -111,8 +150,9 @@ class Logger: backupCount=backup_count, encoding="utf-8", ) - file_handler.setLevel(level) + file_handler.setLevel(logging.DEBUG) # Handler级别设为DEBUG file_handler.setFormatter(formatter) + file_handler.addFilter(level_filter) # 添加级别过滤器 logger.addHandler(file_handler) @classmethod diff --git a/src/core/models/__init__.py b/src/core/models/__init__.py index d577795..0e1cd2e 100644 --- a/src/core/models/__init__.py +++ b/src/core/models/__init__.py @@ -23,11 +23,10 @@ from .trade import Trade # 持仓账户对象 from .position import Position -from .account import Account +from .account import Asset # Account重命名为Asset -# 策略标的对象 +# 策略信号对象 from .signal import Signal -from .symbol import Symbol __all__ = [ # 枚举 @@ -44,7 +43,6 @@ __all__ = [ "Order", "Trade", "Position", - "Account", + "Asset", "Signal", - "Symbol", ] diff --git a/src/core/models/account.py b/src/core/models/account.py index b83678b..d0a1ec1 100644 --- a/src/core/models/account.py +++ b/src/core/models/account.py @@ -1,48 +1,85 @@ """ -账户对象 +资产账户对象 """ + from datetime import datetime +from typing import Optional from pydantic import BaseModel, Field -class Account(BaseModel): +class Asset(BaseModel): """ - 账户(可变) - + 资产账户(可变) + 示例: - account = Account( - account_id="ACC_001", + asset = Asset( + instance_id="debug_000001", + strategy_name="DebugStrategy", + initial_capital=1000000.0, total_asset=1000000.0, - available_cash=500000.0, + cash=500000.0, update_time=datetime.now() ) """ - account_id: str = Field(..., description="账户ID", min_length=1) - + + # 基本信息 + instance_id: str = Field(..., description="策略实例ID", min_length=1) + strategy_name: str = Field(..., description="策略类名", min_length=1) + # 资金信息 - total_asset: float = Field( - ..., - description="总资产 = available_cash + frozen_cash + market_value", - ge=0 - ) + initial_capital: float = Field(..., description="初始资金", gt=0) + total_asset: float = Field(..., description="总资产", ge=0) + cash: float = Field(..., description="现金", ge=0) available_cash: float = Field(..., description="可用资金", ge=0) frozen_cash: float = Field(0.0, description="冻结资金(挂单冻结)", ge=0) + + # 市值信息 market_value: float = Field(0.0, description="持仓市值", ge=0) - + long_market_value: float = Field(0.0, description="多头市值", ge=0) + short_market_value: float = Field(0.0, description="空头市值(期货)", ge=0) + # 盈亏信息 total_pnl: float = Field(0.0, description="总盈亏") + total_return: float = Field(0.0, description="总收益率") + unrealized_pnl: float = Field(0.0, description="浮动盈亏") + realized_pnl: float = Field(0.0, description="已实现盈亏") + + # 当日数据 daily_pnl: float = Field(0.0, description="当日盈亏") - + daily_return: float = Field(0.0, description="当日收益率") + pre_total_asset: float = Field(0.0, description="前一日总资产") + + # 交易成本统计 + total_commission: float = Field(0.0, description="累计佣金", ge=0) + total_stamp_tax: float = Field(0.0, description="累计印花税", ge=0) + total_transfer_fee: float = Field(0.0, description="累计过户费", ge=0) + total_slippage: float = Field(0.0, description="累计滑点成本", ge=0) + total_cost: float = Field(0.0, description="累计总成本", ge=0) + trade_count: int = Field(0, description="交易次数", ge=0) + + # 风控指标 + max_drawdown: float = Field(0.0, description="最大回撤") + max_drawdown_ratio: float = Field(0.0, description="最大回撤率") + leverage: float = Field(0.0, description="杠杆率", ge=0) + + # 时间信息 + init_time: Optional[datetime] = Field(None, description="账户初始化时间") + last_trade_time: Optional[datetime] = Field(None, description="最后交易时间") update_time: datetime = Field(..., description="更新时间") - + def model_post_init(self, __context) -> None: """对象创建后验证总资产一致性""" - calculated_total = self.available_cash + self.frozen_cash + self.market_value + calculated_total = self.cash + self.market_value # 允许0.01的误差(浮点数精度) if abs(self.total_asset - calculated_total) > 0.01: raise ValueError( - f'总资产({self.total_asset})必须等于 ' - f'可用资金({self.available_cash}) + ' - f'冻结资金({self.frozen_cash}) + ' - f'持仓市值({self.market_value}) = {calculated_total}' + f"总资产({self.total_asset})必须等于 " + f"现金({self.cash}) + " + f"持仓市值({self.market_value}) = {calculated_total}" + ) + + # 验证可用资金 + if self.available_cash > self.cash: + raise ValueError( + f"可用资金({self.available_cash})不能大于现金({self.cash})" ) diff --git a/src/core/models/order.py b/src/core/models/order.py index 4e20b96..c1289bd 100644 --- a/src/core/models/order.py +++ b/src/core/models/order.py @@ -3,7 +3,7 @@ """ from datetime import datetime -from typing import Optional +from typing import Optional, Dict, Any from pydantic import BaseModel, Field, field_validator from .enums import OrderSide, OrderType, OrderStatus @@ -15,7 +15,10 @@ class Order(BaseModel): 示例: order = Order( order_id="ORD_20240101_001", + instance_id="debug_000001", + strategy_name="DebugStrategy", symbol="000001.SZ", + symbol_name="平安银行", side=OrderSide.BUY, order_type=OrderType.LIMIT, price=10.5, @@ -25,20 +28,39 @@ class Order(BaseModel): ) """ + # 基本信息 order_id: str = Field(..., description="订单ID(唯一)", min_length=1) + instance_id: str = Field(..., description="策略实例ID", min_length=1) + strategy_name: str = Field(..., description="策略类名", min_length=1) + + # 标的信息 symbol: str = Field(..., description="标的代码", min_length=1) + symbol_name: Optional[str] = Field(None, description="标的名称") + + # 订单信息 side: OrderSide = Field(..., description="方向") order_type: OrderType = Field(..., description="订单类型") - price: float = Field(..., description="价格", ge=0) - volume: int = Field(..., description="数量", gt=0) + price: float = Field(..., description="委托价格", ge=0) + volume: int = Field(..., description="委托数量", gt=0) + + # 成交信息 filled_volume: int = Field(0, description="已成交数量", ge=0) + filled_price: float = Field(0.0, description="成交均价", ge=0) + actual_price: float = Field(0.0, description="实际价格(含滑点)", ge=0) status: OrderStatus = Field(OrderStatus.PENDING, description="状态") - create_time: datetime = Field(..., description="创建时间") - update_time: datetime = Field(..., description="更新时间") - cancel_time: Optional[datetime] = Field(None, description="撤销时间") + # 成本信息 + cost_detail: Optional[Dict[str, Any]] = Field(None, description="成本明细") - strategy_name: Optional[str] = Field(None, description="来源策略") + # 时间信息 + create_time: datetime = Field(..., description="创建时间") + submit_time: Optional[datetime] = Field(None, description="提交时间") + filled_time: Optional[datetime] = Field(None, description="完全成交时间") + cancel_time: Optional[datetime] = Field(None, description="撤销时间") + update_time: datetime = Field(..., description="更新时间") + + # 附加信息 + reason: Optional[str] = Field(None, description="交易原因") remark: Optional[str] = Field(None, description="备注") @field_validator("symbol") diff --git a/src/core/models/position.py b/src/core/models/position.py index 5ba5f51..b545998 100644 --- a/src/core/models/position.py +++ b/src/core/models/position.py @@ -3,6 +3,7 @@ """ from datetime import datetime +from typing import Optional from pydantic import BaseModel, Field, field_validator from .enums import PositionDirection @@ -13,33 +14,61 @@ class Position(BaseModel): 示例: position = Position( + instance_id="debug_000001", + strategy_name="DebugStrategy", symbol="000001.SZ", + symbol_name="平安银行", direction=PositionDirection.LONG, volume=1000, available_volume=900, - avg_price=10.0, + avg_cost=10.0, update_time=datetime.now() ) """ + # 基本信息 + instance_id: str = Field(..., description="策略实例ID", min_length=1) + strategy_name: str = Field(..., description="策略类名", min_length=1) + + # 标的信息 symbol: str = Field(..., description="标的代码", min_length=1) + symbol_name: Optional[str] = Field(None, description="标的名称") + symbol_type: Optional[str] = Field(None, description="标的类型") + decimal_places: int = Field(2, description="价格小数位数", ge=0) + + # 持仓信息 direction: PositionDirection = Field(..., description="方向(股票统一用long)") volume: int = Field(..., description="持仓量", ge=0) available_volume: int = Field(..., description="可用量(考虑T+1)", ge=0) frozen_volume: int = Field(0, description="冻结量(挂单冻结)", ge=0) - - avg_price: float = Field(..., description="平均成本", gt=0) - last_price: float = Field(0.0, description="最新价", ge=0) - - # 盈亏(动态计算,也可以存储) - market_value: float = Field(0.0, description="市值 = volume * last_price", ge=0) - unrealized_pnl: float = Field(0.0, description="浮动盈亏") - realized_pnl: float = Field(0.0, description="已实现盈亏(平仓产生)") - - update_time: datetime = Field(..., description="更新时间") - - # 股票特有:今仓/昨仓(用于T+1) today_volume: int = Field(0, description="今日买入量(T+1不可卖)", ge=0) + yesterday_volume: int = Field(0, description="昨日持仓量", ge=0) + + # 成本和价格 + avg_cost: float = Field(..., description="平均成本价", gt=0) + current_price: float = Field(0.0, description="最新价", ge=0) + open_price: float = Field(0.0, description="建仓价格", ge=0) + + # 市值和盈亏 + market_value: float = Field(0.0, description="市值 = volume * current_price", ge=0) + cost_value: float = Field(0.0, description="成本价值 = volume * avg_cost", ge=0) + unrealized_pnl: float = Field(0.0, description="浮动盈亏") + unrealized_pnl_ratio: float = Field(0.0, description="浮动盈亏率") + realized_pnl: float = Field(0.0, description="已实现盈亏(平仓产生)") + realized_pnl_ratio: float = Field(0.0, description="已实现盈亏率") + + # 持仓占比 + position_ratio: float = Field(0.0, description="持仓占总资产比例", ge=0) + + # 交易统计 + buy_times: int = Field(0, description="买入次数", ge=0) + sell_times: int = Field(0, description="卖出次数", ge=0) + total_cost: float = Field(0.0, description="累计交易成本", ge=0) + + # 时间信息 + first_buy_time: Optional[datetime] = Field(None, description="首次买入时间") + last_trade_time: Optional[datetime] = Field(None, description="最后交易时间") + update_time: datetime = Field(..., description="更新时间") @field_validator("symbol") @classmethod diff --git a/src/core/models/signal.py b/src/core/models/signal.py index 955c8bf..cfad2fd 100644 --- a/src/core/models/signal.py +++ b/src/core/models/signal.py @@ -15,8 +15,9 @@ class Signal(BaseModel): 示例: signal = Signal( signal_id="SIG_20240101_001", + instance_id="debug_000001", + strategy_name="DebugStrategy", symbol="000001.SZ", - strategy_name="MA_Strategy", signal_type=SignalType.BUY, price=10.5, target_volume=100, @@ -25,8 +26,9 @@ class Signal(BaseModel): """ signal_id: str = Field(..., description="信号ID(唯一)", min_length=1) + instance_id: str = Field(..., description="策略实例ID", min_length=1) + strategy_name: str = Field(..., description="策略类名", min_length=1) symbol: str = Field(..., description="标的代码", min_length=1) - strategy_name: str = Field(..., description="策略名称", min_length=1) signal_type: SignalType = Field(..., description="信号类型") price: float = Field(..., description="信号触发价格", gt=0) diff --git a/src/core/models/symbol.py b/src/core/models/symbol.py deleted file mode 100644 index cd7d963..0000000 --- a/src/core/models/symbol.py +++ /dev/null @@ -1,56 +0,0 @@ -""" -标的信息对象 -""" - -from typing import Optional -from pydantic import BaseModel, ConfigDict, Field, field_validator -from .enums import ProductType, Exchange - - -class Symbol(BaseModel): - """ - 标的信息(不可变) - - 示例: - symbol = Symbol( - code="000001.SZ", - name="平安银行", - exchange=Exchange.SZ, - product_type=ProductType.STOCK - ) - """ - - code: str = Field(..., description="完整代码,如 000001.SZ", min_length=1) - name: str = Field(..., description="名称", min_length=1) - exchange: Exchange = Field(..., description="交易所") - product_type: ProductType = Field(..., description="产品类型") - - lot_size: int = Field(100, description="最小交易单位(股票100股,期货1手)", gt=0) - tick_size: float = Field(0.01, description="最小价格变动", gt=0) - - # 期货特有 - margin_rate: Optional[float] = Field(None, description="保证金比例", gt=0, le=1) - multiplier: Optional[int] = Field(None, description="合约乘数", gt=0) - - is_trading: bool = Field(True, description="是否可交易") - - model_config = ConfigDict(frozen=True) # 不可变 - - @field_validator("code") - @classmethod - def validate_code(cls, v: str) -> str: - """验证标的代码格式""" - v = v.upper() - if not v or len(v) < 4: - raise ValueError("标的代码长度至少4个字符") - - return v - - def model_post_init(self, __context) -> None: - """对象创建后验证""" - # 验证期货必须有保证金比例和合约乘数 - if self.product_type == ProductType.FUTURE: - if self.margin_rate is None: - raise ValueError("期货必须设置保证金比例(margin_rate)") - if self.multiplier is None: - raise ValueError("期货必须设置合约乘数(multiplier)") diff --git a/src/core/models/trade.py b/src/core/models/trade.py index 87407e5..3491783 100644 --- a/src/core/models/trade.py +++ b/src/core/models/trade.py @@ -3,6 +3,7 @@ """ from datetime import datetime +from typing import Optional, Dict, Any from pydantic import BaseModel, ConfigDict, Field, field_validator from .enums import OrderSide @@ -15,24 +16,38 @@ class Trade(BaseModel): trade = Trade( trade_id="TRD_20240101_001", order_id="ORD_20240101_001", + instance_id="debug_000001", + strategy_name="DebugStrategy", symbol="000001.SZ", + symbol_name="平安银行", side=OrderSide.BUY, price=10.5, volume=100, amount=1050.0, - commission=1.5, trade_time=datetime.now() ) """ + # 基本信息 trade_id: str = Field(..., description="成交ID(唯一)", min_length=1) order_id: str = Field(..., description="关联订单ID", min_length=1) + instance_id: str = Field(..., description="策略实例ID", min_length=1) + strategy_name: str = Field(..., description="策略类名", min_length=1) + + # 标的信息 symbol: str = Field(..., description="标的代码", min_length=1) + symbol_name: Optional[str] = Field(None, description="标的名称") + + # 成交信息 side: OrderSide = Field(..., description="方向") price: float = Field(..., description="成交价", gt=0) volume: int = Field(..., description="成交量", gt=0) amount: float = Field(..., description="成交额 = price * volume", gt=0) - commission: float = Field(0.0, description="手续费", ge=0) + + # 成本信息 + cost_detail: Optional[Dict[str, Any]] = Field(None, description="成本明细") + + # 时间信息 trade_time: datetime = Field(..., description="成交时间") model_config = ConfigDict(frozen=True) # 不可变 diff --git a/src/data_downloader/xtquant_downloader.py b/src/data_downloader/xtquant_downloader.py index 916efc6..0ef5973 100644 --- a/src/data_downloader/xtquant_downloader.py +++ b/src/data_downloader/xtquant_downloader.py @@ -11,6 +11,8 @@ from xtquant import xtdatacenter as xtdc from src.data_downloader.base_downloader import BaseDataDownloader from src.core.models import Kline +from src.core.config import Config +from src.core.logger import Logger class XtQuantDownloader(BaseDataDownloader): @@ -72,9 +74,9 @@ class XtQuantDownloader(BaseDataDownloader): """析构函数:关闭 XtQuant 连接""" try: xtdc.close() # type: ignore - self.logger.debug("XtQuant connection closed") + Logger.debug("XtQuant connection closed") except Exception as e: - self.logger.debug(f"Error closing XtQuant connection: {e}") + Logger.debug(f"Error closing XtQuant connection: {e}") def _init_xtquant( self, token: Optional[str], optimize_addresses: Optional[List[str]] @@ -82,13 +84,13 @@ class XtQuantDownloader(BaseDataDownloader): """初始化 XtQuant 数据中心""" # 获取 token(从配置文件 data_source.xtquant.xtquant_token 读取) if token is None: - token = self.config.get("data_source.xtquant.xtquant_token") + token = Config.get("data_downloader.xtquant.xtquant_token") if not token: raise ValueError( "XtQuant token 未设置,请在配置文件 data_source.xtquant.xtquant_token 中设置或通过参数传入" ) - self.logger.info(f"Initializing XtQuant data center, Token: {token[:20]}...") + Logger.info(f"Initializing XtQuant data center, Token: {token[:20]}...") # 设置 token xtdc.set_token(token) @@ -96,35 +98,35 @@ class XtQuantDownloader(BaseDataDownloader): # 初始化数据中心 try: xtdc.init() - self.logger.info("XtQuant data center initialized successfully") + Logger.info("XtQuant data center initialized successfully") except Exception as e: - self.logger.error(f"XtQuant data center initialization failed: {e}") + Logger.error(f"XtQuant data center initialization failed: {e}") raise # 设置优化地址 if optimize_addresses is None: - optimize_addresses = self.config.get( + optimize_addresses = Config.get( "data_source.xtquant.optimize_addresses", [] ) if optimize_addresses: try: xtdc.set_allow_optmize_address(optimize_addresses) - self.logger.info( + Logger.info( f"Optimize addresses set: {len(optimize_addresses)} addresses" ) except Exception as e: - self.logger.warning(f"Failed to set optimize addresses: {e}") + Logger.warning(f"Failed to set optimize addresses: {e}") # 下载基础数据 try: - self.logger.info("Downloading sector data...") + Logger.info("Downloading sector data...") xtdata.download_sector_data() - self.logger.info("Downloading historical contracts data...") + Logger.info("Downloading historical contracts data...") xtdata.download_history_contracts() - self.logger.info("Base data download completed") + Logger.info("Base data download completed") except Exception as e: - self.logger.warning(f"Base data download failed: {e}") + Logger.warning(f"Base data download failed: {e}") def _download_klines( self, symbol: str, start_date: datetime, end_date: datetime, period: str @@ -150,12 +152,10 @@ class XtQuantDownloader(BaseDataDownloader): # 先下载历史数据(确保本地有缓存) try: - self.logger.debug( - f"Downloading {symbol} [{period}] historical data to local..." - ) + 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"Failed to download historical data to local: {e}") + Logger.warning(f"Failed to download historical data to local: {e}") # 从本地获取数据 try: @@ -171,11 +171,11 @@ class XtQuantDownloader(BaseDataDownloader): ) if symbol not in data or len(data[symbol]) == 0: - self.logger.warning(f"{symbol} [{period}] has no data") + Logger.warning(f"{symbol} [{period}] has no data") return [] df = data[symbol] - self.logger.debug(f"Retrieved {len(df)} records for {symbol} [{period}]") + Logger.debug(f"Retrieved {len(df)} records for {symbol} [{period}]") # 转换为 Kline 对象 klines = [] @@ -213,12 +213,10 @@ class XtQuantDownloader(BaseDataDownloader): # 打印第一条数据的时间戳信息用于调试 if not first_logged: - self.logger.debug( + Logger.debug( f"First timestamp - raw: {timestamp}, type: {type(timestamp)}" ) - self.logger.debug( - f"First timestamp - converted: {dt}, type: {type(dt)}" - ) + Logger.debug(f"First timestamp - converted: {dt}, type: {type(dt)}") first_logged = True kline = Kline( @@ -240,5 +238,5 @@ class XtQuantDownloader(BaseDataDownloader): return klines except Exception as e: - self.logger.error(f"Failed to retrieve {symbol} [{period}] data: {e}") + Logger.error(f"Failed to retrieve {symbol} [{period}] data: {e}") raise diff --git a/src/data_service/data_service.py b/src/data_service/data_service.py index 7441e62..e721715 100644 --- a/src/data_service/data_service.py +++ b/src/data_service/data_service.py @@ -146,7 +146,7 @@ class DataService: return None # ========== 步骤1: 检查缓存 ========== - cache_data = self.cache.get_klines(symbol, period) + cache_data = self.cache.get_klines(symbol, period, startdate, enddate) if cache_data is not None and not cache_data.empty: Logger.debug(f"Cache data found for {symbol} {period}") @@ -433,7 +433,26 @@ class DataService: return self.storage.get_date_range(symbol, period) # ========== 内部辅助方法 ========== + # 检查所需要的数据是否在缓存中 + def _check_data_exist_in_cache( + self, symbol: str, period: str, startdate: datetime, enddate: datetime + ) -> bool: + """ + 检查数据是否在缓存中 + Args: + symbol: 标的代码 + period: 周期 + startdate: 开始时间 + enddate: 结束时间 + + Returns: + True如果数据在缓存中 + """ + cache_data = self.cache.get_klines(symbol, period, startdate, enddate) + return cache_data is not None and not cache_data.empty + + # 重新计算并保存所有启用的指标 def _recalculate_and_save_indicators( self, symbol: str, period: str, klines: pd.DataFrame ) -> None: diff --git a/src/data_storage/__init__.py b/src/data_storage/__init__.py index bbdc8e9..6bbf6aa 100644 --- a/src/data_storage/__init__.py +++ b/src/data_storage/__init__.py @@ -6,8 +6,10 @@ from .storage_layer import StorageLayer from .mysql_storage import MySQLStorage +from .trading_storage import TradingDataStorage __all__ = [ "StorageLayer", "MySQLStorage", + "TradingDataStorage", ] diff --git a/src/data_storage/storage_layer.py b/src/data_storage/storage_layer.py index a5aaaa7..3f04eb0 100644 --- a/src/data_storage/storage_layer.py +++ b/src/data_storage/storage_layer.py @@ -5,7 +5,7 @@ """ from abc import ABC, abstractmethod -from typing import Optional +from typing import Optional, List, Dict, Any from datetime import datetime import pandas as pd @@ -21,6 +21,8 @@ class StorageLayer(ABC): - 其他存储后端 """ + # ==================== K线和指标数据接口 ==================== + @abstractmethod def load_klines( self, @@ -154,3 +156,218 @@ class StorageLayer(ABC): def close(self): """关闭存储连接""" pass + + # ==================== 交易对象存储接口 ==================== + + @abstractmethod + def save_order(self, order: Any) -> bool: + """ + 保存订单 + + Args: + order: Order对象 + + Returns: + 是否成功 + """ + pass + + @abstractmethod + def get_orders( + self, + instance_id: Optional[str] = None, + symbol: Optional[str] = None, + status: Optional[str] = None, + start_time: Optional[datetime] = None, + end_time: Optional[datetime] = None, + ) -> List[Dict[str, Any]]: + """ + 获取订单列表 + + Args: + instance_id: 策略实例ID(可选) + symbol: 标的代码(可选) + status: 订单状态(可选) + start_time: 开始时间(可选) + end_time: 结束时间(可选) + + Returns: + 订单字典列表 + """ + pass + + @abstractmethod + def get_order_by_id(self, order_id: str) -> Optional[Dict[str, Any]]: + """ + 根据订单ID获取订单 + + Args: + order_id: 订单ID + + Returns: + 订单字典或None + """ + pass + + @abstractmethod + def save_trade(self, trade: Any) -> bool: + """ + 保存成交记录 + + Args: + trade: Trade对象 + + Returns: + 是否成功 + """ + pass + + @abstractmethod + def get_trades( + self, + instance_id: Optional[str] = None, + symbol: Optional[str] = None, + order_id: Optional[str] = None, + start_time: Optional[datetime] = None, + end_time: Optional[datetime] = None, + ) -> List[Dict[str, Any]]: + """ + 获取成交记录列表 + + Args: + instance_id: 策略实例ID(可选) + symbol: 标的代码(可选) + order_id: 订单ID(可选) + start_time: 开始时间(可选) + end_time: 结束时间(可选) + + Returns: + 成交记录字典列表 + """ + pass + + @abstractmethod + def get_trade_by_id(self, trade_id: str) -> Optional[Dict[str, Any]]: + """ + 根据成交ID获取成交记录 + + Args: + trade_id: 成交ID + + Returns: + 成交记录字典或None + """ + pass + + @abstractmethod + def save_position(self, position: Any) -> bool: + """ + 保存持仓 + + Args: + position: Position对象 + + Returns: + 是否成功 + """ + pass + + @abstractmethod + def get_positions( + self, + instance_id: Optional[str] = None, + symbol: Optional[str] = None, + direction: Optional[str] = None, + ) -> List[Dict[str, Any]]: + """ + 获取持仓列表 + + Args: + instance_id: 策略实例ID(可选) + symbol: 标的代码(可选) + direction: 持仓方向(可选) + + Returns: + 持仓字典列表 + """ + pass + + @abstractmethod + def get_position( + self, instance_id: str, symbol: str, direction: str + ) -> Optional[Dict[str, Any]]: + """ + 获取指定持仓 + + Args: + instance_id: 策略实例ID + symbol: 标的代码 + direction: 持仓方向 + + Returns: + 持仓字典或None + """ + pass + + @abstractmethod + def save_asset(self, asset: Any) -> bool: + """ + 保存资产账户 + + Args: + asset: Asset对象 + + Returns: + 是否成功 + """ + pass + + @abstractmethod + def get_asset(self, instance_id: str) -> Optional[Dict[str, Any]]: + """ + 获取资产账户 + + Args: + instance_id: 策略实例ID + + Returns: + 资产字典或None + """ + pass + + @abstractmethod + def save_signal(self, signal: Any) -> bool: + """ + 保存交易信号 + + Args: + signal: Signal对象 + + Returns: + 是否成功 + """ + pass + + @abstractmethod + def get_signals( + self, + instance_id: Optional[str] = None, + symbol: Optional[str] = None, + executed: Optional[bool] = None, + start_time: Optional[datetime] = None, + end_time: Optional[datetime] = None, + ) -> List[Dict[str, Any]]: + """ + 获取信号列表 + + Args: + instance_id: 策略实例ID(可选) + symbol: 标的代码(可选) + executed: 是否已执行(可选) + start_time: 开始时间(可选) + end_time: 结束时间(可选) + + Returns: + 信号字典列表 + """ + pass diff --git a/src/data_storage/trading_storage.py b/src/data_storage/trading_storage.py new file mode 100644 index 0000000..492aea0 --- /dev/null +++ b/src/data_storage/trading_storage.py @@ -0,0 +1,562 @@ +""" +交易数据存储扩展 + +为 Order, Trade, Position, Asset 提供数据库存储接口 +""" + +from typing import List, Optional, Dict, Any +from datetime import datetime +import json +from sqlalchemy import text + +from src.core.models import Order, Trade, Position, Asset +from src.core.logger import Logger +from src.database_manager import DatabaseManager + + +class TradingDataStorage: + """ + 交易数据存储类 + + 提供 Order, Trade, Position, Asset 的数据库CRUD操作 + """ + + def __init__(self, database: str, db_manager: Optional[DatabaseManager] = None): + """ + 初始化交易数据存储 + + Args: + database: 数据库名 + db_manager: 数据库管理器(可选) + """ + self.database = database + self.db_manager = db_manager if db_manager is not None else DatabaseManager() + self.engine = None + + def _get_engine(self): + """获取数据库引擎(懒加载)""" + if self.engine is None: + self.engine = self.db_manager._create_db_engine(self.database) + return self.engine + + # ==================== Order 操作 ==================== + + def save_order(self, order: Order) -> bool: + """ + 保存订单 + + Args: + order: Order对象 + + Returns: + 是否成功 + """ + try: + engine = self._get_engine() + + # 序列化 cost_detail + cost_detail_json = ( + json.dumps(order.cost_detail) if order.cost_detail else None + ) + + query = text(""" + INSERT INTO orders ( + order_id, instance_id, strategy_name, + symbol, symbol_name, + side, order_type, price, volume, + filled_volume, filled_price, actual_price, status, + cost_detail, + create_time, submit_time, filled_time, cancel_time, update_time, + reason, remark + ) VALUES ( + :order_id, :instance_id, :strategy_name, + :symbol, :symbol_name, + :side, :order_type, :price, :volume, + :filled_volume, :filled_price, :actual_price, :status, + :cost_detail, + :create_time, :submit_time, :filled_time, :cancel_time, :update_time, + :reason, :remark + ) + ON DUPLICATE KEY UPDATE + filled_volume=VALUES(filled_volume), + filled_price=VALUES(filled_price), + actual_price=VALUES(actual_price), + status=VALUES(status), + cost_detail=VALUES(cost_detail), + filled_time=VALUES(filled_time), + cancel_time=VALUES(cancel_time), + update_time=VALUES(update_time) + """) + + with engine.connect() as conn: + conn.execute( + query, + { + "order_id": order.order_id, + "instance_id": order.instance_id, + "strategy_name": order.strategy_name, + "symbol": order.symbol, + "symbol_name": order.symbol_name, + "side": order.side.value, + "order_type": order.order_type.value, + "price": order.price, + "volume": order.volume, + "filled_volume": order.filled_volume, + "filled_price": order.filled_price, + "actual_price": order.actual_price, + "status": order.status.value, + "cost_detail": cost_detail_json, + "create_time": order.create_time, + "submit_time": order.submit_time, + "filled_time": order.filled_time, + "cancel_time": order.cancel_time, + "update_time": order.update_time, + "reason": order.reason, + "remark": order.remark, + }, + ) + conn.commit() + + Logger.debug(f"Saved order: {order.order_id}") + return True + + except Exception as e: + Logger.error(f"Failed to save order {order.order_id}: {e}") + return False + + def get_orders( + self, + instance_id: Optional[str] = None, + symbol: Optional[str] = None, + start_time: Optional[datetime] = None, + end_time: Optional[datetime] = None, + ) -> List[Dict[str, Any]]: + """ + 查询订单 + + Args: + instance_id: 策略实例ID + symbol: 股票代码 + start_time: 开始时间 + end_time: 结束时间 + + Returns: + 订单字典列表 + """ + try: + engine = self._get_engine() + + where_clauses = [] + params = {} + + if instance_id: + where_clauses.append("instance_id = :instance_id") + params["instance_id"] = instance_id + + if symbol: + where_clauses.append("symbol = :symbol") + params["symbol"] = symbol + + if start_time: + where_clauses.append("create_time >= :start_time") + params["start_time"] = start_time + + if end_time: + where_clauses.append("create_time <= :end_time") + params["end_time"] = end_time + + where_clause = " AND ".join(where_clauses) if where_clauses else "1=1" + + query = text(f""" + SELECT * FROM orders + WHERE {where_clause} + ORDER BY create_time DESC + """) + + with engine.connect() as conn: + result = conn.execute(query, params) + rows = result.fetchall() + + # 转换为字典列表 + orders = [] + for row in rows: + order_dict = dict(row._mapping) + # 反序列化 cost_detail + if order_dict.get("cost_detail"): + order_dict["cost_detail"] = json.loads(order_dict["cost_detail"]) + orders.append(order_dict) + + return orders + + except Exception as e: + Logger.error(f"Failed to get orders: {e}") + return [] + + # ==================== Trade 操作 ==================== + + def save_trade(self, trade: Trade) -> bool: + """保存成交记录""" + try: + engine = self._get_engine() + + # 序列化 cost_detail + cost_detail_json = ( + json.dumps(trade.cost_detail) if trade.cost_detail else None + ) + + query = text(""" + INSERT INTO trades ( + trade_id, order_id, instance_id, strategy_name, + symbol, symbol_name, + side, price, volume, amount, + cost_detail, + trade_time + ) VALUES ( + :trade_id, :order_id, :instance_id, :strategy_name, + :symbol, :symbol_name, + :side, :price, :volume, :amount, + :cost_detail, + :trade_time + ) + """) + + with engine.connect() as conn: + conn.execute( + query, + { + "trade_id": trade.trade_id, + "order_id": trade.order_id, + "instance_id": trade.instance_id, + "strategy_name": trade.strategy_name, + "symbol": trade.symbol, + "symbol_name": trade.symbol_name, + "side": trade.side.value, + "price": trade.price, + "volume": trade.volume, + "amount": trade.amount, + "cost_detail": cost_detail_json, + "trade_time": trade.trade_time, + }, + ) + conn.commit() + + Logger.debug(f"Saved trade: {trade.trade_id}") + return True + + except Exception as e: + Logger.error(f"Failed to save trade {trade.trade_id}: {e}") + return False + + def get_trades( + self, + instance_id: Optional[str] = None, + symbol: Optional[str] = None, + start_time: Optional[datetime] = None, + end_time: Optional[datetime] = None, + ) -> List[Dict[str, Any]]: + """查询成交记录""" + try: + engine = self._get_engine() + + where_clauses = [] + params = {} + + if instance_id: + where_clauses.append("instance_id = :instance_id") + params["instance_id"] = instance_id + + if symbol: + where_clauses.append("symbol = :symbol") + params["symbol"] = symbol + + if start_time: + where_clauses.append("trade_time >= :start_time") + params["start_time"] = start_time + + if end_time: + where_clauses.append("trade_time <= :end_time") + params["end_time"] = end_time + + where_clause = " AND ".join(where_clauses) if where_clauses else "1=1" + + query = text(f""" + SELECT * FROM trades + WHERE {where_clause} + ORDER BY trade_time DESC + """) + + with engine.connect() as conn: + result = conn.execute(query, params) + rows = result.fetchall() + + trades = [] + for row in rows: + trade_dict = dict(row._mapping) + if trade_dict.get("cost_detail"): + trade_dict["cost_detail"] = json.loads(trade_dict["cost_detail"]) + trades.append(trade_dict) + + return trades + + except Exception as e: + Logger.error(f"Failed to get trades: {e}") + return [] + + # ==================== Position 操作 ==================== + + def save_position(self, position: Position) -> bool: + """保存或更新持仓""" + try: + engine = self._get_engine() + + query = text(""" + INSERT INTO positions ( + instance_id, strategy_name, + symbol, symbol_name, symbol_type, decimal_places, + direction, volume, available_volume, frozen_volume, + today_volume, yesterday_volume, + avg_cost, current_price, open_price, + market_value, cost_value, + unrealized_pnl, unrealized_pnl_ratio, + realized_pnl, realized_pnl_ratio, + position_ratio, + buy_times, sell_times, total_cost, + first_buy_time, last_trade_time, update_time + ) VALUES ( + :instance_id, :strategy_name, + :symbol, :symbol_name, :symbol_type, :decimal_places, + :direction, :volume, :available_volume, :frozen_volume, + :today_volume, :yesterday_volume, + :avg_cost, :current_price, :open_price, + :market_value, :cost_value, + :unrealized_pnl, :unrealized_pnl_ratio, + :realized_pnl, :realized_pnl_ratio, + :position_ratio, + :buy_times, :sell_times, :total_cost, + :first_buy_time, :last_trade_time, :update_time + ) + ON DUPLICATE KEY UPDATE + volume=VALUES(volume), + available_volume=VALUES(available_volume), + frozen_volume=VALUES(frozen_volume), + today_volume=VALUES(today_volume), + yesterday_volume=VALUES(yesterday_volume), + avg_cost=VALUES(avg_cost), + current_price=VALUES(current_price), + market_value=VALUES(market_value), + cost_value=VALUES(cost_value), + unrealized_pnl=VALUES(unrealized_pnl), + unrealized_pnl_ratio=VALUES(unrealized_pnl_ratio), + realized_pnl=VALUES(realized_pnl), + realized_pnl_ratio=VALUES(realized_pnl_ratio), + position_ratio=VALUES(position_ratio), + buy_times=VALUES(buy_times), + sell_times=VALUES(sell_times), + total_cost=VALUES(total_cost), + last_trade_time=VALUES(last_trade_time), + update_time=VALUES(update_time) + """) + + with engine.connect() as conn: + conn.execute( + query, + { + "instance_id": position.instance_id, + "strategy_name": position.strategy_name, + "symbol": position.symbol, + "symbol_name": position.symbol_name, + "symbol_type": position.symbol_type, + "decimal_places": position.decimal_places, + "direction": position.direction.value, + "volume": position.volume, + "available_volume": position.available_volume, + "frozen_volume": position.frozen_volume, + "today_volume": position.today_volume, + "yesterday_volume": position.yesterday_volume, + "avg_cost": position.avg_cost, + "current_price": position.current_price, + "open_price": position.open_price, + "market_value": position.market_value, + "cost_value": position.cost_value, + "unrealized_pnl": position.unrealized_pnl, + "unrealized_pnl_ratio": position.unrealized_pnl_ratio, + "realized_pnl": position.realized_pnl, + "realized_pnl_ratio": position.realized_pnl_ratio, + "position_ratio": position.position_ratio, + "buy_times": position.buy_times, + "sell_times": position.sell_times, + "total_cost": position.total_cost, + "first_buy_time": position.first_buy_time, + "last_trade_time": position.last_trade_time, + "update_time": position.update_time, + }, + ) + conn.commit() + + Logger.debug(f"Saved position: {position.instance_id}_{position.symbol}") + return True + + except Exception as e: + Logger.error(f"Failed to save position: {e}") + return False + + def get_positions( + self, + instance_id: Optional[str] = None, + symbol: Optional[str] = None, + ) -> List[Dict[str, Any]]: + """查询持仓""" + try: + engine = self._get_engine() + + where_clauses = [] + params = {} + + if instance_id: + where_clauses.append("instance_id = :instance_id") + params["instance_id"] = instance_id + + if symbol: + where_clauses.append("symbol = :symbol") + params["symbol"] = symbol + + where_clause = " AND ".join(where_clauses) if where_clauses else "1=1" + + query = text(f""" + SELECT * FROM positions + WHERE {where_clause} + ORDER BY update_time DESC + """) + + with engine.connect() as conn: + result = conn.execute(query, params) + rows = result.fetchall() + + return [dict(row._mapping) for row in rows] + + except Exception as e: + Logger.error(f"Failed to get positions: {e}") + return [] + + # ==================== Asset 操作 ==================== + + def save_asset(self, asset: Asset) -> bool: + """保存或更新资产""" + try: + engine = self._get_engine() + + query = text(""" + INSERT INTO assets ( + instance_id, strategy_name, + initial_capital, total_asset, cash, available_cash, frozen_cash, + market_value, long_market_value, short_market_value, + total_pnl, total_return, unrealized_pnl, realized_pnl, + daily_pnl, daily_return, pre_total_asset, + total_commission, total_stamp_tax, total_transfer_fee, + total_slippage, total_cost, trade_count, + max_drawdown, max_drawdown_ratio, leverage, + init_time, last_trade_time, update_time + ) VALUES ( + :instance_id, :strategy_name, + :initial_capital, :total_asset, :cash, :available_cash, :frozen_cash, + :market_value, :long_market_value, :short_market_value, + :total_pnl, :total_return, :unrealized_pnl, :realized_pnl, + :daily_pnl, :daily_return, :pre_total_asset, + :total_commission, :total_stamp_tax, :total_transfer_fee, + :total_slippage, :total_cost, :trade_count, + :max_drawdown, :max_drawdown_ratio, :leverage, + :init_time, :last_trade_time, :update_time + ) + ON DUPLICATE KEY UPDATE + total_asset=VALUES(total_asset), + cash=VALUES(cash), + available_cash=VALUES(available_cash), + frozen_cash=VALUES(frozen_cash), + market_value=VALUES(market_value), + long_market_value=VALUES(long_market_value), + short_market_value=VALUES(short_market_value), + total_pnl=VALUES(total_pnl), + total_return=VALUES(total_return), + unrealized_pnl=VALUES(unrealized_pnl), + realized_pnl=VALUES(realized_pnl), + daily_pnl=VALUES(daily_pnl), + daily_return=VALUES(daily_return), + pre_total_asset=VALUES(pre_total_asset), + total_commission=VALUES(total_commission), + total_stamp_tax=VALUES(total_stamp_tax), + total_transfer_fee=VALUES(total_transfer_fee), + total_slippage=VALUES(total_slippage), + total_cost=VALUES(total_cost), + trade_count=VALUES(trade_count), + max_drawdown=VALUES(max_drawdown), + max_drawdown_ratio=VALUES(max_drawdown_ratio), + leverage=VALUES(leverage), + last_trade_time=VALUES(last_trade_time), + update_time=VALUES(update_time) + """) + + with engine.connect() as conn: + conn.execute( + query, + { + "instance_id": asset.instance_id, + "strategy_name": asset.strategy_name, + "initial_capital": asset.initial_capital, + "total_asset": asset.total_asset, + "cash": asset.cash, + "available_cash": asset.available_cash, + "frozen_cash": asset.frozen_cash, + "market_value": asset.market_value, + "long_market_value": asset.long_market_value, + "short_market_value": asset.short_market_value, + "total_pnl": asset.total_pnl, + "total_return": asset.total_return, + "unrealized_pnl": asset.unrealized_pnl, + "realized_pnl": asset.realized_pnl, + "daily_pnl": asset.daily_pnl, + "daily_return": asset.daily_return, + "pre_total_asset": asset.pre_total_asset, + "total_commission": asset.total_commission, + "total_stamp_tax": asset.total_stamp_tax, + "total_transfer_fee": asset.total_transfer_fee, + "total_slippage": asset.total_slippage, + "total_cost": asset.total_cost, + "trade_count": asset.trade_count, + "max_drawdown": asset.max_drawdown, + "max_drawdown_ratio": asset.max_drawdown_ratio, + "leverage": asset.leverage, + "init_time": asset.init_time, + "last_trade_time": asset.last_trade_time, + "update_time": asset.update_time, + }, + ) + conn.commit() + + Logger.debug(f"Saved asset: {asset.instance_id}") + return True + + except Exception as e: + Logger.error(f"Failed to save asset: {e}") + return False + + def get_asset(self, instance_id: str) -> Optional[Dict[str, Any]]: + """查询资产""" + try: + engine = self._get_engine() + + query = text(""" + SELECT * FROM assets + WHERE instance_id = :instance_id + """) + + with engine.connect() as conn: + result = conn.execute(query, {"instance_id": instance_id}) + row = result.fetchone() + + if row: + return dict(row._mapping) + return None + + except Exception as e: + Logger.error(f"Failed to get asset: {e}") + return None diff --git a/src/database_manager/__init__.py b/src/database_manager/__init__.py index 4cd19f3..487204d 100644 --- a/src/database_manager/__init__.py +++ b/src/database_manager/__init__.py @@ -8,14 +8,15 @@ from .table_schemas import ( get_table_definition, get_all_table_names, TICK_TABLE, + SIGNAL_TABLE, + create_kline_table_definition, + create_indicator_table_definition, +) +from .trading_table_schemas import ( ORDER_TABLE, TRADE_TABLE, POSITION_TABLE, - ACCOUNT_TABLE, - SIGNAL_TABLE, - SYMBOL_TABLE, - create_kline_table_definition, - create_indicator_table_definition, + ASSET_TABLE, ) __all__ = [ @@ -27,9 +28,8 @@ __all__ = [ "ORDER_TABLE", "TRADE_TABLE", "POSITION_TABLE", - "ACCOUNT_TABLE", + "ASSET_TABLE", "SIGNAL_TABLE", - "SYMBOL_TABLE", "create_kline_table_definition", "create_indicator_table_definition", ] diff --git a/src/database_manager/table_schemas.py b/src/database_manager/table_schemas.py index ac43618..ee6fd16 100644 --- a/src/database_manager/table_schemas.py +++ b/src/database_manager/table_schemas.py @@ -6,6 +6,12 @@ from typing import Dict, Any, List from .table_utils import SUPPORTED_PERIODS, SUPPORTED_INDICATORS +from .trading_table_schemas import ( + ORDER_TABLE, + TRADE_TABLE, + POSITION_TABLE, + ASSET_TABLE, +) # ==================== Tick 表 ==================== TICK_TABLE = { @@ -287,256 +293,6 @@ def create_indicator_table_definition(indicator: str, period: str) -> Dict[str, } -# ==================== Order 表 ==================== -ORDER_TABLE = { - "name": "orders", - "comment": "订单表", - "columns": { - "id": { - "type": "Integer", - "primary_key": True, - "nullable": False, - "comment": "自增主键", - }, - "order_id": { - "type": "String", - "length": 50, - "nullable": False, - "comment": "订单ID(唯一)", - }, - "symbol": { - "type": "String", - "length": 20, - "nullable": False, - "comment": "标的代码", - }, - "side": { - "type": "String", - "length": 10, - "nullable": False, - "comment": "方向(buy/sell)", - }, - "order_type": { - "type": "String", - "length": 10, - "nullable": False, - "comment": "订单类型(limit/market/stop)", - }, - "price": {"type": "Float", "nullable": False, "comment": "价格"}, - "volume": {"type": "Integer", "nullable": False, "comment": "数量"}, - "filled_volume": { - "type": "Integer", - "nullable": False, - "default": 0, - "comment": "已成交数量", - }, - "status": { - "type": "String", - "length": 20, - "nullable": False, - "comment": "状态(pending/partial/filled/cancelled/rejected)", - }, - "create_time": {"type": "DateTime", "nullable": False, "comment": "创建时间"}, - "update_time": {"type": "DateTime", "nullable": False, "comment": "更新时间"}, - "cancel_time": {"type": "DateTime", "nullable": True, "comment": "撤销时间"}, - "strategy_name": { - "type": "String", - "length": 50, - "nullable": True, - "comment": "来源策略", - }, - "remark": { - "type": "String", - "length": 200, - "nullable": True, - "comment": "备注", - }, - }, - "indexes": [ - {"name": "idx_order_id", "columns": ["order_id"], "unique": True}, - {"name": "idx_symbol_time", "columns": ["symbol", "create_time"]}, - {"name": "idx_status", "columns": ["status"]}, - {"name": "idx_strategy", "columns": ["strategy_name"]}, - ], -} - -# ==================== Trade 表 ==================== -TRADE_TABLE = { - "name": "trades", - "comment": "成交记录表", - "columns": { - "id": { - "type": "Integer", - "primary_key": True, - "nullable": False, - "comment": "自增主键", - }, - "trade_id": { - "type": "String", - "length": 50, - "nullable": False, - "comment": "成交ID(唯一)", - }, - "order_id": { - "type": "String", - "length": 50, - "nullable": False, - "comment": "订单ID", - }, - "symbol": { - "type": "String", - "length": 20, - "nullable": False, - "comment": "标的代码", - }, - "side": { - "type": "String", - "length": 10, - "nullable": False, - "comment": "方向(buy/sell)", - }, - "price": {"type": "Float", "nullable": False, "comment": "成交价"}, - "volume": {"type": "Integer", "nullable": False, "comment": "成交量"}, - "amount": {"type": "Float", "nullable": False, "comment": "成交额"}, - "commission": { - "type": "Float", - "nullable": False, - "default": 0.0, - "comment": "手续费", - }, - "trade_time": {"type": "DateTime", "nullable": False, "comment": "成交时间"}, - "strategy_name": { - "type": "String", - "length": 50, - "nullable": True, - "comment": "来源策略", - }, - }, - "indexes": [ - {"name": "idx_trade_id", "columns": ["trade_id"], "unique": True}, - {"name": "idx_order_id", "columns": ["order_id"]}, - {"name": "idx_symbol_time", "columns": ["symbol", "trade_time"]}, - {"name": "idx_strategy", "columns": ["strategy_name"]}, - ], -} - -# ==================== Position 表 ==================== -POSITION_TABLE = { - "name": "positions", - "comment": "持仓表", - "columns": { - "id": { - "type": "Integer", - "primary_key": True, - "nullable": False, - "comment": "自增主键", - }, - "symbol": { - "type": "String", - "length": 20, - "nullable": False, - "comment": "标的代码", - }, - "direction": { - "type": "String", - "length": 10, - "nullable": False, - "comment": "方向(long/short)", - }, - "volume": {"type": "Integer", "nullable": False, "comment": "持仓量"}, - "available_volume": {"type": "Integer", "nullable": False, "comment": "可用量"}, - "frozen_volume": { - "type": "Integer", - "nullable": False, - "default": 0, - "comment": "冻结量", - }, - "avg_price": {"type": "Float", "nullable": False, "comment": "平均成本"}, - "last_price": { - "type": "Float", - "nullable": False, - "default": 0.0, - "comment": "最新价", - }, - "market_value": { - "type": "Float", - "nullable": False, - "default": 0.0, - "comment": "市值", - }, - "unrealized_pnl": { - "type": "Float", - "nullable": False, - "default": 0.0, - "comment": "浮动盈亏", - }, - "realized_pnl": { - "type": "Float", - "nullable": False, - "default": 0.0, - "comment": "已实现盈亏", - }, - "today_volume": { - "type": "Integer", - "nullable": False, - "default": 0, - "comment": "今日买入量(T+1)", - }, - "update_time": {"type": "DateTime", "nullable": False, "comment": "更新时间"}, - }, - "indexes": [ - { - "name": "idx_symbol_direction", - "columns": ["symbol", "direction"], - "unique": True, - }, - ], -} - -# ==================== Account 表 ==================== -ACCOUNT_TABLE = { - "name": "accounts", - "comment": "账户表", - "columns": { - "id": { - "type": "Integer", - "primary_key": True, - "nullable": False, - "comment": "自增主键", - }, - "account_id": { - "type": "String", - "length": 50, - "nullable": False, - "comment": "账户ID(唯一)", - }, - "total_asset": {"type": "Float", "nullable": False, "comment": "总资产"}, - "available_cash": {"type": "Float", "nullable": False, "comment": "可用资金"}, - "frozen_cash": { - "type": "Float", - "nullable": False, - "default": 0.0, - "comment": "冻结资金", - }, - "market_value": { - "type": "Float", - "nullable": False, - "default": 0.0, - "comment": "持仓市值", - }, - "total_pnl": { - "type": "Float", - "nullable": False, - "default": 0.0, - "comment": "总盈亏", - }, - "update_time": {"type": "DateTime", "nullable": False, "comment": "更新时间"}, - }, - "indexes": [ - {"name": "idx_account_id", "columns": ["account_id"], "unique": True}, - ], -} - # ==================== Signal 表 ==================== SIGNAL_TABLE = { "name": "signals", @@ -554,6 +310,12 @@ SIGNAL_TABLE = { "nullable": False, "comment": "信号ID(唯一)", }, + "instance_id": { + "type": "String", + "length": 50, + "nullable": False, + "comment": "策略实例ID", + }, "strategy_name": { "type": "String", "length": 50, @@ -597,79 +359,13 @@ SIGNAL_TABLE = { }, "indexes": [ {"name": "idx_signal_id", "columns": ["signal_id"], "unique": True}, + {"name": "idx_instance", "columns": ["instance_id"]}, {"name": "idx_strategy_symbol", "columns": ["strategy_name", "symbol"]}, {"name": "idx_executed", "columns": ["executed"]}, {"name": "idx_generate_time", "columns": ["generate_time"]}, ], } -# ==================== Symbol 表 ==================== -SYMBOL_TABLE = { - "name": "symbols", - "comment": "标的信息表", - "columns": { - "id": { - "type": "Integer", - "primary_key": True, - "nullable": False, - "comment": "自增主键", - }, - "symbol": { - "type": "String", - "length": 20, - "nullable": False, - "comment": "标的代码(唯一)", - }, - "name": { - "type": "String", - "length": 50, - "nullable": False, - "comment": "标的名称", - }, - "exchange": { - "type": "String", - "length": 10, - "nullable": False, - "comment": "交易所", - }, - "product_type": { - "type": "String", - "length": 10, - "nullable": False, - "comment": "产品类型(stock/future/option/fund)", - }, - "lot_size": { - "type": "Integer", - "nullable": False, - "default": 100, - "comment": "最小交易单位", - }, - "tick_size": { - "type": "Float", - "nullable": False, - "default": 0.01, - "comment": "最小价格变动", - }, - "margin_rate": { - "type": "Float", - "nullable": True, - "comment": "保证金比例(期货)", - }, - "multiplier": { - "type": "Integer", - "nullable": True, - "comment": "合约乘数(期货)", - }, - "listed_date": {"type": "DateTime", "nullable": True, "comment": "上市日期"}, - "delisted_date": {"type": "DateTime", "nullable": True, "comment": "退市日期"}, - }, - "indexes": [ - {"name": "idx_symbol", "columns": ["symbol"], "unique": True}, - {"name": "idx_exchange", "columns": ["exchange"]}, - {"name": "idx_product_type", "columns": ["product_type"]}, - ], -} - # ==================== 所有表定义 ==================== # 动态生成所有周期的K线表 ALL_KLINE_TABLES = { @@ -690,12 +386,12 @@ ALL_TABLES = { **ALL_KLINE_TABLES, **ALL_INDICATOR_TABLES, "ticks": TICK_TABLE, + "signals": SIGNAL_TABLE, + # 交易相关表(从 trading_table_schemas 导入) "orders": ORDER_TABLE, "trades": TRADE_TABLE, "positions": POSITION_TABLE, - "accounts": ACCOUNT_TABLE, - "signals": SIGNAL_TABLE, - "symbols": SYMBOL_TABLE, + "assets": ASSET_TABLE, } diff --git a/src/database_manager/trading_table_schemas.py b/src/database_manager/trading_table_schemas.py new file mode 100644 index 0000000..744c2f6 --- /dev/null +++ b/src/database_manager/trading_table_schemas.py @@ -0,0 +1,561 @@ +""" +交易数据表结构定义 + +为 Order, Trade, Position, Asset 模型定义表结构 +""" + +# ==================== Order 表 ==================== +ORDER_TABLE = { + "name": "orders", + "comment": "订单表(包含策略实例隔离)", + "columns": { + "id": { + "type": "Integer", + "primary_key": True, + "auto_increment": True, + "nullable": False, + "comment": "自增主键", + }, + # 基本信息 + "order_id": { + "type": "String", + "length": 100, + "nullable": False, + "comment": "订单ID(唯一)", + }, + "instance_id": { + "type": "String", + "length": 50, + "nullable": False, + "comment": "策略实例ID", + }, + "strategy_name": { + "type": "String", + "length": 50, + "nullable": False, + "comment": "策略类名", + }, + # 标的信息 + "symbol": { + "type": "String", + "length": 20, + "nullable": False, + "comment": "标的代码", + }, + "symbol_name": { + "type": "String", + "length": 50, + "nullable": True, + "comment": "标的名称", + }, + # 订单信息 + "side": { + "type": "String", + "length": 10, + "nullable": False, + "comment": "方向(buy/sell)", + }, + "order_type": { + "type": "String", + "length": 10, + "nullable": False, + "comment": "订单类型(limit/market/stop)", + }, + "price": {"type": "Float", "nullable": False, "comment": "委托价格"}, + "volume": {"type": "Integer", "nullable": False, "comment": "委托数量"}, + # 成交信息 + "filled_volume": { + "type": "Integer", + "nullable": False, + "default": 0, + "comment": "已成交数量", + }, + "filled_price": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "成交均价", + }, + "actual_price": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "实际价格(含滑点)", + }, + "status": { + "type": "String", + "length": 20, + "nullable": False, + "comment": "状态(pending/partial/filled/cancelled/rejected)", + }, + # 成本信息(JSON存储) + "cost_detail": { + "type": "Text", + "nullable": True, + "comment": "成本明细(JSON格式)", + }, + # 时间信息 + "create_time": {"type": "DateTime", "nullable": False, "comment": "创建时间"}, + "submit_time": {"type": "DateTime", "nullable": True, "comment": "提交时间"}, + "filled_time": { + "type": "DateTime", + "nullable": True, + "comment": "完全成交时间", + }, + "cancel_time": {"type": "DateTime", "nullable": True, "comment": "撤销时间"}, + "update_time": {"type": "DateTime", "nullable": False, "comment": "更新时间"}, + # 附加信息 + "reason": { + "type": "String", + "length": 200, + "nullable": True, + "comment": "交易原因", + }, + "remark": { + "type": "String", + "length": 200, + "nullable": True, + "comment": "备注", + }, + }, + "indexes": [ + {"name": "idx_order_id", "columns": ["order_id"], "unique": True}, + {"name": "idx_instance", "columns": ["instance_id"]}, + {"name": "idx_instance_symbol", "columns": ["instance_id", "symbol"]}, + {"name": "idx_symbol_time", "columns": ["symbol", "create_time"]}, + {"name": "idx_status", "columns": ["status"]}, + {"name": "idx_strategy", "columns": ["strategy_name"]}, + ], +} + +# ==================== Trade 表 ==================== +TRADE_TABLE = { + "name": "trades", + "comment": "成交记录表(包含策略实例隔离)", + "columns": { + "id": { + "type": "Integer", + "primary_key": True, + "auto_increment": True, + "nullable": False, + "comment": "自增主键", + }, + # 基本信息 + "trade_id": { + "type": "String", + "length": 100, + "nullable": False, + "comment": "成交ID(唯一)", + }, + "order_id": { + "type": "String", + "length": 100, + "nullable": False, + "comment": "关联订单ID", + }, + "instance_id": { + "type": "String", + "length": 50, + "nullable": False, + "comment": "策略实例ID", + }, + "strategy_name": { + "type": "String", + "length": 50, + "nullable": False, + "comment": "策略类名", + }, + # 标的信息 + "symbol": { + "type": "String", + "length": 20, + "nullable": False, + "comment": "标的代码", + }, + "symbol_name": { + "type": "String", + "length": 50, + "nullable": True, + "comment": "标的名称", + }, + # 成交信息 + "side": { + "type": "String", + "length": 10, + "nullable": False, + "comment": "方向(buy/sell)", + }, + "price": {"type": "Float", "nullable": False, "comment": "成交价"}, + "volume": {"type": "Integer", "nullable": False, "comment": "成交量"}, + "amount": {"type": "Float", "nullable": False, "comment": "成交额"}, + # 成本信息(JSON存储) + "cost_detail": { + "type": "Text", + "nullable": True, + "comment": "成本明细(JSON格式)", + }, + # 时间信息 + "trade_time": {"type": "DateTime", "nullable": False, "comment": "成交时间"}, + }, + "indexes": [ + {"name": "idx_trade_id", "columns": ["trade_id"], "unique": True}, + {"name": "idx_order_id", "columns": ["order_id"]}, + {"name": "idx_instance", "columns": ["instance_id"]}, + {"name": "idx_instance_symbol", "columns": ["instance_id", "symbol"]}, + {"name": "idx_symbol_time", "columns": ["symbol", "trade_time"]}, + {"name": "idx_strategy", "columns": ["strategy_name"]}, + ], +} + +# ==================== Position 表 ==================== +POSITION_TABLE = { + "name": "positions", + "comment": "持仓表(包含策略实例隔离)", + "columns": { + "id": { + "type": "Integer", + "primary_key": True, + "auto_increment": True, + "nullable": False, + "comment": "自增主键", + }, + # 基本信息 + "instance_id": { + "type": "String", + "length": 50, + "nullable": False, + "comment": "策略实例ID", + }, + "strategy_name": { + "type": "String", + "length": 50, + "nullable": False, + "comment": "策略类名", + }, + # 标的信息 + "symbol": { + "type": "String", + "length": 20, + "nullable": False, + "comment": "标的代码", + }, + "symbol_name": { + "type": "String", + "length": 50, + "nullable": True, + "comment": "标的名称", + }, + "symbol_type": { + "type": "String", + "length": 20, + "nullable": True, + "comment": "标的类型", + }, + "decimal_places": { + "type": "Integer", + "nullable": False, + "default": 2, + "comment": "价格小数位数", + }, + # 持仓信息 + "direction": { + "type": "String", + "length": 10, + "nullable": False, + "comment": "方向(long/short)", + }, + "volume": {"type": "Integer", "nullable": False, "comment": "持仓量"}, + "available_volume": {"type": "Integer", "nullable": False, "comment": "可用量"}, + "frozen_volume": { + "type": "Integer", + "nullable": False, + "default": 0, + "comment": "冻结量", + }, + "today_volume": { + "type": "Integer", + "nullable": False, + "default": 0, + "comment": "今日买入量", + }, + "yesterday_volume": { + "type": "Integer", + "nullable": False, + "default": 0, + "comment": "昨日持仓量", + }, + # 成本和价格 + "avg_cost": {"type": "Float", "nullable": False, "comment": "平均成本价"}, + "current_price": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "最新价", + }, + "open_price": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "建仓价格", + }, + # 市值和盈亏 + "market_value": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "市值", + }, + "cost_value": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "成本价值", + }, + "unrealized_pnl": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "浮动盈亏", + }, + "unrealized_pnl_ratio": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "浮动盈亏率", + }, + "realized_pnl": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "已实现盈亏", + }, + "realized_pnl_ratio": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "已实现盈亏率", + }, + # 持仓占比 + "position_ratio": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "持仓占比", + }, + # 交易统计 + "buy_times": { + "type": "Integer", + "nullable": False, + "default": 0, + "comment": "买入次数", + }, + "sell_times": { + "type": "Integer", + "nullable": False, + "default": 0, + "comment": "卖出次数", + }, + "total_cost": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "累计交易成本", + }, + # 时间信息 + "first_buy_time": { + "type": "DateTime", + "nullable": True, + "comment": "首次买入时间", + }, + "last_trade_time": { + "type": "DateTime", + "nullable": True, + "comment": "最后交易时间", + }, + "update_time": {"type": "DateTime", "nullable": False, "comment": "更新时间"}, + }, + "indexes": [ + { + "name": "idx_instance_symbol", + "columns": ["instance_id", "symbol"], + "unique": True, + }, + {"name": "idx_instance", "columns": ["instance_id"]}, + {"name": "idx_symbol", "columns": ["symbol"]}, + {"name": "idx_strategy", "columns": ["strategy_name"]}, + ], +} + +# ==================== Asset 表(Account重命名)==================== +ASSET_TABLE = { + "name": "assets", + "comment": "资产账户表(包含策略实例隔离)", + "columns": { + "id": { + "type": "Integer", + "primary_key": True, + "auto_increment": True, + "nullable": False, + "comment": "自增主键", + }, + # 基本信息 + "instance_id": { + "type": "String", + "length": 50, + "nullable": False, + "comment": "策略实例ID(唯一)", + }, + "strategy_name": { + "type": "String", + "length": 50, + "nullable": False, + "comment": "策略类名", + }, + # 资金信息 + "initial_capital": {"type": "Float", "nullable": False, "comment": "初始资金"}, + "total_asset": {"type": "Float", "nullable": False, "comment": "总资产"}, + "cash": {"type": "Float", "nullable": False, "comment": "现金"}, + "available_cash": {"type": "Float", "nullable": False, "comment": "可用资金"}, + "frozen_cash": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "冻结资金", + }, + # 市值信息 + "market_value": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "持仓市值", + }, + "long_market_value": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "多头市值", + }, + "short_market_value": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "空头市值", + }, + # 盈亏信息 + "total_pnl": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "总盈亏", + }, + "total_return": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "总收益率", + }, + "unrealized_pnl": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "浮动盈亏", + }, + "realized_pnl": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "已实现盈亏", + }, + # 当日数据 + "daily_pnl": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "当日盈亏", + }, + "daily_return": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "当日收益率", + }, + "pre_total_asset": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "前一日总资产", + }, + # 交易成本统计 + "total_commission": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "累计佣金", + }, + "total_stamp_tax": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "累计印花税", + }, + "total_transfer_fee": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "累计过户费", + }, + "total_slippage": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "累计滑点成本", + }, + "total_cost": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "累计总成本", + }, + "trade_count": { + "type": "Integer", + "nullable": False, + "default": 0, + "comment": "交易次数", + }, + # 风控指标 + "max_drawdown": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "最大回撤", + }, + "max_drawdown_ratio": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "最大回撤率", + }, + "leverage": { + "type": "Float", + "nullable": False, + "default": 0.0, + "comment": "杠杆率", + }, + # 时间信息 + "init_time": { + "type": "DateTime", + "nullable": True, + "comment": "账户初始化时间", + }, + "last_trade_time": { + "type": "DateTime", + "nullable": True, + "comment": "最后交易时间", + }, + "update_time": {"type": "DateTime", "nullable": False, "comment": "更新时间"}, + }, + "indexes": [ + {"name": "idx_instance_id", "columns": ["instance_id"], "unique": True}, + {"name": "idx_strategy", "columns": ["strategy_name"]}, + ], +} diff --git a/src/qtrade_server.py b/src/qtrade_server.py index 5042cd1..0ee6bb9 100644 --- a/src/qtrade_server.py +++ b/src/qtrade_server.py @@ -105,7 +105,7 @@ def save_cache_to_database(cache_manager: CacheManager, db_manager: DatabaseMana Logger.info(f"Saving {stats['size']} cache entries to database...") # 使用Config单例 - storage = MySQLStorage(db_manager) + storage = MySQLStorage(db_manager) # type: ignore saved_count = 0 failed_count = 0 @@ -115,7 +115,7 @@ def save_cache_to_database(cache_manager: CacheManager, db_manager: DatabaseMana for period in symbol_info["periods"]: try: # 获取K线数据 - klines_data = cache_manager.get_klines(symbol, period) + klines_data = cache_manager.get_klines_from_cache(symbol, period) if klines_data is not None and not klines_data.empty: # 保存到数据库 diff --git a/src/realtrade/miniqmt_client_adapter.py b/src/realtrade/miniqmt_client_adapter.py new file mode 100644 index 0000000..b24b448 --- /dev/null +++ b/src/realtrade/miniqmt_client_adapter.py @@ -0,0 +1,278 @@ +""" +MiniQMT 实盘交易客户端适配器 + +负责业务逻辑: +- 连接 MiniQMT 交易接口 +- 发送 K线数据到策略服务器 +- 接收交易信号 +- 执行实盘交易委托 +""" + +from typing import Optional, Dict +from datetime import datetime +from dataclasses import dataclass +import pandas as pd +import uuid + +from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback +from xtquant.xttype import StockAccount +from xtquant import xtconstant +from xtquant import xtdata + +from src.networks.client.ws_client import WSClient +from src.core.logger import Logger + +g_wsclient: Optional[WSClient] = None + + +def init_wsclient(server_url: str, timeout: int) -> WSClient: + """初始化全局 WSClient 实例""" + global g_wsclient + if g_wsclient is None: + g_wsclient = WSClient(server_url, timeout) + return g_wsclient + + +def get_wsclient() -> Optional[WSClient]: + """获取全局 WSClient 实例""" + global g_wsclient + return g_wsclient + + +# 实时行情数据回调 +# on_data(datas),回调参数datas格式为 { stock1 : data1, stock2 : data2, ... } +def on_realtime_data(datas): + Logger.info(f"Received realtime data: {datas}") + wsclient = get_wsclient() + if wsclient: + message = [] + for symbol, data in datas.items(): + # 构造消息 + + message = { + "symbol": symbol, + "datetime": data.get( + "datetime", datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ), + "open": data.get("open", 0.0), + "high": data.get("high", 0.0), + "low": data.get("low", 0.0), + "close": data.get("close", 0.0), + "volume": data.get("volume", 0), + } + # respone = wsclient.send("kline_data", message) + # 获取买卖信号 + + Logger.info(f"Sent data to server: {message}") + + +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( + f"委托回报: {order.stock_code}, " + f"状态={order.order_status}, " + f"系统编号={order.order_sysid}" + ) + + def on_stock_trade(self, trade): + """ + 成交变动推送 + + Args: + trade: XtTrade对象 + """ + Logger.info( + f"成交回报: {trade.stock_code}, " + f"订单ID={trade.order_id}, " + f"成交价={trade.traded_price}, " + f"成交量={trade.traded_volume}" + ) + + 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.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( + f"异步下单回报: 订单ID={response.order_id}, 响应={response.order_remark}" + ) + + def on_account_status(self, status): + """ + 账户状态变化推送 + + Args: + status: XtAccountStatus对象 + """ + Logger.info(f"账户状态: {status.account_id}, 状态={status.account_type}") + + +class MiniQMTClientAdapter: + """ + MiniQMT 实盘交易客户端适配器 + + 负责: + - 连接 MiniQMT 交易接口 + - 发送 K线数据到策略服务器获取信号 + - 执行实盘交易委托 + """ + + def __init__( + self, + server_url: str, + timeout: int, + miniqmt_path: str, + session_id: int, + account_id: str, + account_type: str = "STOCK", + stockpool: Optional[list] = None, + ): + """ + 初始化 MiniQMT 客户端适配器 + + Args: + server_url: 策略服务器 WebSocket 地址 + timeout: 超时时间(秒) + miniqmt_path: MiniQMT userdata_mini 路径 + session_id: 会话ID(不同策略使用不同ID) + account_id: 交易账号 + account_type: 账户类型(STOCK/HUGANGTONG/SHENGANGTONG) + stockpool: 交易股票池(默认为空,表示全部股票) + """ + # 策略服务器 WebSocket 客户端 + init_wsclient(server_url, timeout) + self.stockpool = stockpool if stockpool is not None else [] + # MiniQMT 交易客户端 + self.xt_trader = XtQuantTrader(miniqmt_path, session_id) + self.account = StockAccount(account_id, account_type) + self.callback = MiniQMTTraderCallback() + # 注册回调 + self.xt_trader.register_callback(self.callback) + + # 交易股票池 + if len(self.stockpool) == 0: + Logger.warning("交易股票池为空,表示全部股票可交易") + else: + for symbol_info in self.stockpool: + symbol = symbol_info.get("symbol") + symbol_name = symbol_info.get("name", "") + symbol_period = symbol_info.get("period") + xtdata.subscribe_quote( + symbol, period=symbol_period, callback=on_realtime_data + ) + Logger.info( + f"Subscribed to quote: {symbol} ({symbol_name}), period={symbol_period}" + ) + + # 连接状态 + self.is_connected = False + + Logger.info( + f"MiniQMTClientAdapter initialized: " + f"account={account_id}, type={account_type}" + ) + + def run(self) -> bool: + """启动连接""" + self.is_connected = self._connect() + if not self.is_connected: + Logger.error("MiniQMT 连接失败,无法运行客户端适配器") + return self.is_connected + + Logger.info("MiniQMT 客户端适配器运行中,按 Ctrl+C 退出") + try: + self.xt_trader.run_forever() + except KeyboardInterrupt: + Logger.info("收到退出信号,正在关闭连接...") + self.close() + return True + + def close(self): + """关闭连接""" + try: + if self.is_connected: + self.xt_trader.stop() + self.is_connected = False + Logger.info("MiniQMT 连接已关闭") + + wsclient = get_wsclient() + if wsclient: + wsclient.close() + Logger.info("WebSocket 连接已关闭") + + except Exception as e: + Logger.error(f"关闭连接异常: {e}") + + def _connect(self) -> bool: + """ + 连接 MiniQMT 交易接口 + + Returns: + 是否连接成功 + """ + try: + # 启动交易线程 + self.xt_trader.start() + + # 建立交易连接 + connect_result = self.xt_trader.connect() + if connect_result != 0: + Logger.error(f"MiniQMT 连接失败: {connect_result}") + return False + + # 订阅账户推送 + subscribe_result = self.xt_trader.subscribe(self.account) + if subscribe_result != 0: + Logger.error(f"MiniQMT 订阅账户失败: {subscribe_result}") + return False + + self.is_connected = True + Logger.info("MiniQMT 连接成功") + return True + + except Exception as e: + Logger.error(f"MiniQMT 连接异常: {e}") + return False