feat: 实现XtQuant数据下载器和核心对象系统
- 新增核心对象模型(Tick, Kline, Order, Trade, Position, Account, Signal, Symbol) - 使用Pydantic BaseModel实现自动验证 - 创建DatabaseManager管理数据库和表结构 - 实现BaseDataDownloader抽象基类 - 实现XtQuantDownloader下载历史K线数据 - 添加Config和Logger工具类 - 清理旧的微服务架构代码 - 更新配置文件为简化版本(去除Redis) - 所有测试通过
This commit is contained in:
parent
1e46f31a31
commit
5734bf1fd0
260
README.md
260
README.md
@ -1,260 +0,0 @@
|
||||
# QTrade - A股量化交易系统
|
||||
|
||||
轻量级 A股量化交易系统,基于 Python 微服务架构。
|
||||
|
||||
## ✨ 特性
|
||||
|
||||
- 🚀 **微服务架构**: FastAPI + Redis + MySQL
|
||||
- 📊 **实时行情**: 通过 QMT 获取 A股实时行情数据
|
||||
- 🤖 **策略引擎**: 支持多策略并行运行 (网格/均线/双均线)
|
||||
- 💹 **股票-策略配对**: 每个配对独立管理持仓和资金
|
||||
- 🔄 **回测支持**: 回测与实盘使用相同代码
|
||||
- 🖥️ **桌面控制台**: PyQt6 可视化管理界面
|
||||
- 🐧 **跨平台**: 支持 Linux 和 Windows
|
||||
|
||||
## 🏗️ 架构
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ PyQt6 Console (桌面控制台) │
|
||||
│ 服务管理 | 策略配置 | 系统设置 | 日志查看 │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────┐
|
||||
│ Gateway │
|
||||
│ FastAPI :8001 │
|
||||
│ (API 入口) │
|
||||
└───────────┬─────────────┘
|
||||
│
|
||||
┌───────────────────────┼───────────────────────┐
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
|
||||
│ Core Service │ │ Data Service │ │Strategy Engine│
|
||||
│ :8010 │ │ :8020 │ │ :8030 │
|
||||
├───────────────┤ ├───────────────┤ ├───────────────┤
|
||||
│ 订单管理 │ │ 行情接收/分发 │ │ 策略管理 │
|
||||
│ 持仓管理 │ │ K线存储查询 │ │ 信号生成 │
|
||||
│ 资金管理 │ │ 回测数据回放 │ │ 策略执行 │
|
||||
│ 配对管理 │ │ │ │ │
|
||||
└───────────────┘ └───────────────┘ └───────────────┘
|
||||
│ │ │
|
||||
└───────────────────────┼───────────────────────┘
|
||||
│
|
||||
┌─────┴─────┐
|
||||
│ Redis │ ← Pub/Sub + Cache
|
||||
└─────┬─────┘
|
||||
┌───────────┴───────────┐
|
||||
│ │
|
||||
▼ ▼
|
||||
┌─────────────────┐ ┌─────────────────┐
|
||||
│ QMT Adapter │ │ MySQL │
|
||||
│ :8040 (模拟) │ │ (数据持久化) │
|
||||
│ Python 3.6 │ │ │
|
||||
└─────────────────┘ └─────────────────┘
|
||||
```
|
||||
|
||||
## 📁 项目结构
|
||||
|
||||
```
|
||||
QTrade/
|
||||
├── docs/ # 文档
|
||||
│ └── architecture/
|
||||
│ ├── ARCHITECTURE.md # 架构设计
|
||||
│ └── BUILD_PLAN.md # 构建方案
|
||||
│
|
||||
├── src/
|
||||
│ ├── core/ # 核心模块
|
||||
│ │ ├── config.py # 配置管理 (Pydantic + YAML)
|
||||
│ │ ├── database.py # 数据库连接 (SQLAlchemy 2.0 async)
|
||||
│ │ ├── redis_client.py # Redis 客户端 (asyncio)
|
||||
│ │ ├── logger.py # 日志模块
|
||||
│ │ └── models/ # 数据模型 (Pydantic)
|
||||
│ │
|
||||
│ ├── gateway/ # API 网关 (:8001)
|
||||
│ │ ├── app.py # FastAPI 应用
|
||||
│ │ └── routes/ # 路由模块
|
||||
│ │
|
||||
│ ├── core_service/ # 核心业务服务 (:8010)
|
||||
│ │ ├── services/ # 业务逻辑
|
||||
│ │ │ ├── order_service.py
|
||||
│ │ │ ├── position_service.py
|
||||
│ │ │ ├── balance_service.py
|
||||
│ │ │ └── pairing_service.py
|
||||
│ │ └── routes/ # API 路由
|
||||
│ │
|
||||
│ ├── data_service/ # 数据服务 (:8020)
|
||||
│ │ ├── market/ # 行情模块
|
||||
│ │ └── kline/ # K线存储
|
||||
│ │
|
||||
│ ├── strategy_engine/ # 策略引擎 (:8030)
|
||||
│ │ ├── strategies/ # 策略实现
|
||||
│ │ │ ├── base.py # 策略基类
|
||||
│ │ │ ├── grid_strategy.py # 网格策略
|
||||
│ │ │ └── ma_strategy.py # 均线策略
|
||||
│ │ └── engine/ # 执行引擎
|
||||
│ │
|
||||
│ ├── qmt_adapter/ # QMT 适配器 (:8040)
|
||||
│ │ ├── qmt_client.py # QMT SDK 封装
|
||||
│ │ ├── market_feeder.py # 行情采集
|
||||
│ │ └── trade_executor.py # 交易执行
|
||||
│ │
|
||||
│ ├── console/ # PyQt6 控制台
|
||||
│ │ ├── main.py # 应用入口
|
||||
│ │ └── windows/
|
||||
│ │ ├── main_window.py # 主窗口
|
||||
│ │ └── pages/ # 页面组件
|
||||
│ │ ├── dashboard_page.py # 仪表盘
|
||||
│ │ ├── services_page.py # 服务管理
|
||||
│ │ ├── strategies_page.py # 策略配置
|
||||
│ │ ├── settings_page.py # 系统设置
|
||||
│ │ └── logs_page.py # 运行日志
|
||||
│ │
|
||||
│ └── main.py # 服务启动入口
|
||||
│
|
||||
├── configs/
|
||||
│ └── settings.yaml # 主配置文件
|
||||
│
|
||||
├── database/
|
||||
│ └── init.sql # 数据库初始化
|
||||
│
|
||||
├── tests/ # 单元测试
|
||||
├── requirements.txt # Python 依赖
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 1. 环境准备
|
||||
|
||||
```bash
|
||||
# Python 3.10+
|
||||
python --version
|
||||
|
||||
# 安装依赖
|
||||
pip install -r requirements.txt
|
||||
|
||||
# 安装 PyQt6 (控制台)
|
||||
pip install PyQt6
|
||||
```
|
||||
|
||||
### 2. 配置
|
||||
|
||||
编辑 `configs/settings.yaml`:
|
||||
|
||||
```yaml
|
||||
redis:
|
||||
host: 127.0.0.1
|
||||
port: 6379
|
||||
|
||||
database:
|
||||
host: 127.0.0.1
|
||||
port: 3306
|
||||
user: root
|
||||
password: your_password
|
||||
database: qtrade
|
||||
|
||||
qmt:
|
||||
path: D:/QMT/userdata_mini
|
||||
simulation: true # 模拟模式
|
||||
```
|
||||
|
||||
### 3. 初始化数据库
|
||||
|
||||
```bash
|
||||
mysql -u root -p < database/init.sql
|
||||
```
|
||||
|
||||
### 4. 启动服务
|
||||
|
||||
**方式一: 命令行启动**
|
||||
|
||||
```bash
|
||||
# 启动单个服务
|
||||
python -m src.main gateway
|
||||
python -m src.main core_service
|
||||
python -m src.main data_service
|
||||
python -m src.main strategy_engine
|
||||
python -m src.main qmt_adapter
|
||||
|
||||
# 启动所有服务
|
||||
python -m src.main all
|
||||
```
|
||||
|
||||
**方式二: PyQt6 控制台 (推荐)**
|
||||
|
||||
```bash
|
||||
python -m src.console.main
|
||||
```
|
||||
|
||||
## 📊 服务端口
|
||||
|
||||
| 服务 | 端口 | 说明 |
|
||||
| --------------- | ---- | ------------ |
|
||||
| Gateway | 8001 | API 网关入口 |
|
||||
| Core Service | 8010 | 核心业务服务 |
|
||||
| Data Service | 8020 | 数据服务 |
|
||||
| Strategy Engine | 8030 | 策略引擎 |
|
||||
| QMT Adapter | 8040 | QMT 适配器 |
|
||||
|
||||
## 🎯 内置策略
|
||||
|
||||
| 策略 | 说明 | 参数 |
|
||||
| ---------- | -------------------- | -------------------------- |
|
||||
| 网格策略 | 区间震荡套利 | 上下限价格、网格数量 |
|
||||
| 均线交叉 | 短期均线穿越长期均线 | 短期周期、长期周期 |
|
||||
| 双均线策略 | 均线交叉 + 止盈止损 | 短/长期周期、止盈/止损比例 |
|
||||
|
||||
## 🖥️ 控制台功能
|
||||
|
||||
| 页面 | 功能 |
|
||||
| -------- | ----------------------------------- |
|
||||
| 仪表盘 | 系统概览、服务状态、快捷操作 |
|
||||
| 服务管理 | 启动/停止/重启服务、健康状态监控 |
|
||||
| 策略配置 | 股票-策略配对管理、参数配置 |
|
||||
| 系统设置 | Redis/MySQL/QMT/端口 配置、连接测试 |
|
||||
| 运行日志 | 实时日志查看、按服务过滤、日志导出 |
|
||||
|
||||
## 🧪 测试
|
||||
|
||||
```bash
|
||||
# 运行所有测试
|
||||
pytest tests/ -v
|
||||
|
||||
# 运行特定测试
|
||||
pytest tests/test_core/ -v
|
||||
```
|
||||
|
||||
## 📦 核心依赖
|
||||
|
||||
| 依赖 | 版本 | 用途 |
|
||||
| ---------- | ------ | ------------ |
|
||||
| FastAPI | 0.100+ | Web 框架 |
|
||||
| SQLAlchemy | 2.0+ | ORM (异步) |
|
||||
| redis | 4.5+ | Redis 客户端 |
|
||||
| PyQt6 | 6.4+ | 桌面 GUI |
|
||||
| pydantic | 2.0+ | 数据验证 |
|
||||
| uvicorn | 0.22+ | ASGI 服务器 |
|
||||
| httpx | 0.24+ | HTTP 客户端 |
|
||||
| PyYAML | 6.0+ | 配置文件解析 |
|
||||
|
||||
## ⚠️ 注意事项
|
||||
|
||||
1. **QMT 依赖**: QMT Adapter 需要安装 xtquant SDK (仅 Windows)
|
||||
2. **模拟模式**: 未安装 xtquant 时自动进入模拟模式
|
||||
3. **Redis/MySQL**: 确保服务已启动
|
||||
4. **端口冲突**: 检查端口是否被占用
|
||||
|
||||
## 📄 License
|
||||
|
||||
MIT License
|
||||
|
||||
## 👤 Author
|
||||
|
||||
yyppdcc
|
||||
|
||||
---
|
||||
|
||||
**Version**: 2.0.0
|
||||
**Status**: 开发中
|
||||
@ -1,14 +1,11 @@
|
||||
# QTrade 回测环境配置
|
||||
# 数据库: QTrade_BackTestTrade
|
||||
# Redis前缀: bt:
|
||||
# 端口范围: 10000-10999
|
||||
# 数据库: qtrade_backtest
|
||||
# 端口: 8030
|
||||
|
||||
# 环境配置
|
||||
environment:
|
||||
env: "backtest"
|
||||
db_name: "QTrade_BackTestTrade"
|
||||
redis_prefix: "bt"
|
||||
port_offset: 10000
|
||||
mode: "backtest" # 环境模式
|
||||
db_name: "qtrade_backtest"
|
||||
|
||||
# 应用配置
|
||||
app:
|
||||
@ -17,22 +14,13 @@ app:
|
||||
env: "backtest"
|
||||
debug: true
|
||||
|
||||
# Redis 配置
|
||||
redis:
|
||||
host: "127.0.0.1"
|
||||
port: 6379
|
||||
password: ""
|
||||
db: 1 # 使用不同的Redis DB
|
||||
pool_size: 10
|
||||
pool_timeout: 30
|
||||
|
||||
# MySQL 配置
|
||||
database:
|
||||
host: "127.0.0.1"
|
||||
port: 3306
|
||||
user: "root"
|
||||
password: "1234"
|
||||
# db_name 由 environment.db_name 提供
|
||||
database: "qtrade_backtest"
|
||||
pool_size: 5
|
||||
pool_recycle: 3600
|
||||
echo: false
|
||||
@ -71,12 +59,27 @@ trading:
|
||||
|
||||
# 服务端口配置
|
||||
services:
|
||||
data_service:
|
||||
trading_service:
|
||||
host: "0.0.0.0"
|
||||
port: 10001
|
||||
strategy_service:
|
||||
host: "0.0.0.0"
|
||||
port: 10003
|
||||
backtest_service:
|
||||
host: "0.0.0.0"
|
||||
port: 10007
|
||||
port: 8030
|
||||
|
||||
# 回测配置
|
||||
backtest:
|
||||
# 数据播放器配置
|
||||
data_player:
|
||||
# 历史数据推送地址
|
||||
callback_url: "http://127.0.0.1:8030/api/v1/market/tick"
|
||||
# 播放速度(1=实时,10=10倍速)
|
||||
speed: 1
|
||||
# 数据来源
|
||||
data_source: "database" # database 或 csv
|
||||
# 撮合引擎配置
|
||||
matching:
|
||||
# 撮合模式
|
||||
mode: "market" # market-市价成交, limit-限价撮合
|
||||
# 滑点(基点,1基点=0.01%)
|
||||
slippage: 0 # 0表示无滑点
|
||||
# 手续费率
|
||||
commission_rate: 0.0003 # 万3
|
||||
# 印花税率(卖出时)
|
||||
stamp_tax_rate: 0.001 # 千1
|
||||
@ -8,22 +8,13 @@ app:
|
||||
env: "development" # development, production
|
||||
debug: true
|
||||
|
||||
# Redis 配置
|
||||
redis:
|
||||
host: "127.0.0.1"
|
||||
port: 6379
|
||||
password: ""
|
||||
db: 0
|
||||
pool_size: 10
|
||||
pool_timeout: 30
|
||||
|
||||
# MySQL 配置
|
||||
database:
|
||||
host: "127.0.0.1"
|
||||
port: 3306
|
||||
user: "root"
|
||||
password: "1234"
|
||||
database: "qtrade_stock_data"
|
||||
database: "qtrade_backtest" # 默认数据库
|
||||
pool_size: 5
|
||||
pool_recycle: 3600
|
||||
echo: false
|
||||
@ -60,20 +51,14 @@ trading:
|
||||
start: "13:00"
|
||||
end: "15:00"
|
||||
|
||||
# 服务端口配置(用于服务发现)
|
||||
# 服务端口配置(统一后端架构)
|
||||
services:
|
||||
core_service:
|
||||
live:
|
||||
host: "0.0.0.0"
|
||||
port: 8010
|
||||
database_admin_service:
|
||||
host: "0.0.0.0"
|
||||
port: 8015
|
||||
data_service:
|
||||
sim:
|
||||
host: "0.0.0.0"
|
||||
port: 8020
|
||||
strategy_service:
|
||||
backtest:
|
||||
host: "0.0.0.0"
|
||||
port: 8030
|
||||
qmt_service:
|
||||
host: "0.0.0.0"
|
||||
port: 8040
|
||||
|
||||
@ -1,38 +1,26 @@
|
||||
# QTrade 实盘环境配置
|
||||
# 数据库: QTrade_RealTrade
|
||||
# Redis前缀: real:
|
||||
# 端口范围: 9000-9999
|
||||
# 数据库: qtrade_live
|
||||
# 端口: 8010
|
||||
|
||||
# 环境配置
|
||||
environment:
|
||||
env: "production"
|
||||
db_name: "QTrade_RealTrade"
|
||||
redis_prefix: "real"
|
||||
port_offset: 9000
|
||||
mode: "live" # 环境模式
|
||||
db_name: "qtrade_live"
|
||||
|
||||
# 应用配置
|
||||
app:
|
||||
name: "QTrade"
|
||||
name: "QTrade-Live"
|
||||
version: "2.0.0"
|
||||
env: "production"
|
||||
debug: false
|
||||
|
||||
# Redis 配置
|
||||
redis:
|
||||
host: "127.0.0.1"
|
||||
port: 6379
|
||||
password: ""
|
||||
db: 0
|
||||
pool_size: 10
|
||||
pool_timeout: 30
|
||||
|
||||
# MySQL 配置
|
||||
database:
|
||||
host: "127.0.0.1"
|
||||
port: 3306
|
||||
user: "root"
|
||||
password: "1234"
|
||||
# db_name 由 environment.db_name 提供
|
||||
database: "qtrade_live"
|
||||
pool_size: 5
|
||||
pool_recycle: 3600
|
||||
echo: false
|
||||
@ -71,18 +59,20 @@ trading:
|
||||
|
||||
# 服务端口配置
|
||||
services:
|
||||
core_service:
|
||||
trading_service:
|
||||
host: "0.0.0.0"
|
||||
port: 9010
|
||||
data_service:
|
||||
host: "0.0.0.0"
|
||||
port: 9001
|
||||
strategy_service:
|
||||
host: "0.0.0.0"
|
||||
port: 9003
|
||||
trade_service:
|
||||
host: "0.0.0.0"
|
||||
port: 9005
|
||||
qmt_service:
|
||||
host: "0.0.0.0"
|
||||
port: 9007
|
||||
port: 8010
|
||||
|
||||
# QMT配置(实盘交易接口)
|
||||
qmt:
|
||||
# XtQuant路径
|
||||
xtquant_path: "C:\\Program Files\\国金证券QMT交易端\\userdata_mini\\datadir"
|
||||
# 账号配置
|
||||
account_id: "" # 需要填写实际账号
|
||||
account_type: "STOCK" # STOCK-股票账户, CREDIT-信用账户
|
||||
# 连接配置
|
||||
session_id: 123456 # 会话ID
|
||||
# 数据推送地址(QMT推送数据到这里)
|
||||
callback_url: "http://127.0.0.1:8010/api/v1/market/tick"
|
||||
# 成交回报地址
|
||||
trade_callback_url: "http://127.0.0.1:8010/api/v1/trade/fill"
|
||||
|
||||
@ -1,14 +1,11 @@
|
||||
# QTrade 模拟环境配置
|
||||
# 数据库: QTrade_SimuTrade
|
||||
# Redis前缀: simu:
|
||||
# 端口范围: 11000-11999
|
||||
# 数据库: qtrade_sim
|
||||
# 端口: 8020
|
||||
|
||||
# 环境配置
|
||||
environment:
|
||||
env: "simulation"
|
||||
db_name: "QTrade_SimuTrade"
|
||||
redis_prefix: "simu"
|
||||
port_offset: 11000
|
||||
mode: "sim" # 环境模式
|
||||
db_name: "qtrade_sim"
|
||||
|
||||
# 应用配置
|
||||
app:
|
||||
@ -17,22 +14,13 @@ app:
|
||||
env: "simulation"
|
||||
debug: true
|
||||
|
||||
# Redis 配置
|
||||
redis:
|
||||
host: "127.0.0.1"
|
||||
port: 6379
|
||||
password: ""
|
||||
db: 2 # 使用不同的Redis DB
|
||||
pool_size: 10
|
||||
pool_timeout: 30
|
||||
|
||||
# MySQL 配置
|
||||
database:
|
||||
host: "127.0.0.1"
|
||||
port: 3306
|
||||
user: "root"
|
||||
password: "1234"
|
||||
# db_name 由 environment.db_name 提供
|
||||
database: "qtrade_sim"
|
||||
pool_size: 5
|
||||
pool_recycle: 3600
|
||||
echo: false
|
||||
@ -71,12 +59,20 @@ trading:
|
||||
|
||||
# 服务端口配置
|
||||
services:
|
||||
data_service:
|
||||
trading_service:
|
||||
host: "0.0.0.0"
|
||||
port: 11001
|
||||
strategy_service:
|
||||
host: "0.0.0.0"
|
||||
port: 11003
|
||||
trade_service:
|
||||
host: "0.0.0.0"
|
||||
port: 11005
|
||||
port: 8020
|
||||
|
||||
# QMT配置(模拟交易接口)
|
||||
qmt:
|
||||
# XtQuant路径
|
||||
xtquant_path: "C:\\Program Files\\国金证券QMT交易端\\userdata_mini\\datadir"
|
||||
# 账号配置
|
||||
account_id: "" # 需要填写模拟账号
|
||||
account_type: "STOCK" # STOCK-股票账户, CREDIT-信用账户
|
||||
# 连接配置
|
||||
session_id: 123457 # 会话ID(与实盘不同)
|
||||
# 数据推送地址(QMT推送数据到这里)
|
||||
callback_url: "http://127.0.0.1:8020/api/v1/market/tick"
|
||||
# 成交回报地址
|
||||
trade_callback_url: "http://127.0.0.1:8020/api/v1/trade/fill"
|
||||
|
||||
@ -1,310 +0,0 @@
|
||||
# QTrade 系统架构设计
|
||||
|
||||
> 创建日期: 2025-12-08
|
||||
> 更新日期: 2025-12-09
|
||||
> 版本: 2.0
|
||||
|
||||
## 一、系统概述
|
||||
|
||||
QTrade 是一个轻量化的 A股量化交易系统,采用微服务架构,支持实盘交易和历史回测。
|
||||
|
||||
### 核心特性
|
||||
|
||||
- **实时行情**: 对接 QMT 获取 A股实时行情
|
||||
- **策略管理**: 支持同一股票配置多个策略,独立管理仓位和资金
|
||||
- **回测系统**: 复用实盘代码,从数据库回放历史数据模拟实盘
|
||||
- **桌面控制台**: PyQt6 桌面应用,可视化管理所有服务
|
||||
- **跨平台**: 主系统支持 Linux/Windows,QMT适配层仅 Windows
|
||||
- **水平扩展**: 支持多机部署 (2-3台)
|
||||
|
||||
---
|
||||
|
||||
## 二、服务架构
|
||||
|
||||
### 2.1 服务列表
|
||||
|
||||
| 服务 | 端口 | Python版本 | 状态 | 职责 |
|
||||
| ------------------- | ---- | ---------- | -------- | ------------------------------------------------ |
|
||||
| **gateway** | 8001 | 3.10+ | ✅ 已完成 | API入口、路由分发、认证鉴权、请求日志 |
|
||||
| **core-service** | 8010 | 3.10+ | ✅ 已完成 | 交易管理、风控检查、账户管理、持仓管理、配对管理 |
|
||||
| **data-service** | 8020 | 3.10+ | ✅ 已完成 | 行情接收/分发、K线存储查询、回测数据回放 |
|
||||
| **strategy-engine** | 8030 | 3.10+ | ✅ 已完成 | 策略管理、策略执行、信号生成 |
|
||||
| **qmt-adapter** | 8040 | 3.10+ | ✅ 已完成 | QMT行情采集、交易执行、账户同步 (支持模拟模式) |
|
||||
| **console** | - | 3.10+ | ✅ 已完成 | PyQt6 桌面控制台 |
|
||||
|
||||
### 2.2 架构图
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ PyQt6 Console (桌面控制台) │
|
||||
│ 仪表盘 | 服务管理 | 策略配置 | 系统设置 | 日志 │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
外部调用(Web/App/脚本/控制台)
|
||||
│
|
||||
│ HTTP REST
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ gateway │ FastAPI :8001
|
||||
│ (API入口) │
|
||||
└────────┬────────┘
|
||||
│
|
||||
│ HTTP + Redis Pub/Sub
|
||||
▼
|
||||
┌────────────────────┼────────────────────┐
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
|
||||
│ core-service │ │ data-service │ │strategy-engine│
|
||||
│ FastAPI:8010 │ │ FastAPI:8020 │ │ FastAPI:8030 │
|
||||
│ │ │ │ │ │
|
||||
│ - 订单管理 │ │ - 行情分发 │ │ - 策略管理 │
|
||||
│ - 持仓管理 │ │ - K线存储 │ │ - 信号生成 │
|
||||
│ - 资金管理 │ │ - 回测回放 │ │ - 网格策略 │
|
||||
│ - 配对管理 │ │ │ │ - 均线策略 │
|
||||
└──────────────┘ └──────────────┘ └──────────────┘
|
||||
│ │ │
|
||||
└────────────────────┼────────────────────┘
|
||||
│
|
||||
Redis
|
||||
│
|
||||
┌──────────────┴──────────────┐
|
||||
│ │
|
||||
▼ ▼
|
||||
┌─────────────────┐ ┌─────────────────┐
|
||||
│ qmt-adapter │ │ MySQL │
|
||||
│ FastAPI:8040 │ │ (数据持久化) │
|
||||
│ (支持模拟模式) │ │ │
|
||||
└─────────────────┘ └─────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ QMT 客户端 │
|
||||
│ (券商软件) │
|
||||
└─────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 三、技术选型
|
||||
|
||||
| 组件 | 选择 | 说明 |
|
||||
| ------------- | ------------------------ | ----------------------------- |
|
||||
| **Web框架** | FastAPI | 异步、高性能、自动生成API文档 |
|
||||
| **ORM** | SQLAlchemy 2.0 (async) | 异步数据库操作 |
|
||||
| **数据库** | MySQL | 数据持久化存储 |
|
||||
| **缓存/消息** | Redis | 所有业务数据交换、Pub/Sub |
|
||||
| **配置管理** | Pydantic Settings + YAML | 类型安全的配置 |
|
||||
| **进程管理** | Supervisor | 跨平台进程管理 |
|
||||
| **日志** | Python logging | 标准日志库 |
|
||||
|
||||
---
|
||||
|
||||
## 四、数据流设计
|
||||
|
||||
### 4.1 实盘行情流
|
||||
|
||||
```
|
||||
QMT实时行情
|
||||
│
|
||||
▼
|
||||
qmt-adapter (market_feeder)
|
||||
│
|
||||
│ Redis PUBLISH "market:tick:{symbol}"
|
||||
▼
|
||||
data-service (market/receiver)
|
||||
│
|
||||
│ Redis PUBLISH "market:dispatch:{symbol}"
|
||||
▼
|
||||
strategy-engine (订阅)
|
||||
│
|
||||
│ 生成交易信号
|
||||
▼
|
||||
core-service (trading)
|
||||
│
|
||||
│ Redis PUBLISH "trade:order:submit"
|
||||
▼
|
||||
qmt-adapter (trade_executor)
|
||||
│
|
||||
│ 调用 QMT 下单
|
||||
▼
|
||||
QMT 交易接口
|
||||
```
|
||||
|
||||
### 4.2 回测数据流
|
||||
|
||||
```
|
||||
MySQL (历史K线)
|
||||
│
|
||||
│ 读取
|
||||
▼
|
||||
data-service (backtest/data_player)
|
||||
│
|
||||
│ 模拟实盘节奏
|
||||
│ Redis PUBLISH "market:tick:{symbol}"
|
||||
▼
|
||||
data-service (market/receiver) ← 与实盘完全相同
|
||||
│
|
||||
▼
|
||||
strategy-engine ← 代码无需修改
|
||||
│
|
||||
▼
|
||||
backtest/matcher (模拟撮合) ← 替代 qmt-adapter
|
||||
```
|
||||
|
||||
**关键设计**: 回测时,data_player 模拟 qmt-adapter 的推送行为,下游服务代码完全不变。
|
||||
|
||||
---
|
||||
|
||||
## 五、核心数据模型
|
||||
|
||||
### 5.1 股票-策略配对 (核心)
|
||||
|
||||
```
|
||||
股票 A ──┬── 策略1 → 独立持仓、独立资金
|
||||
├── 策略2 → 独立持仓、独立资金
|
||||
└── 策略3 → 独立持仓、独立资金
|
||||
|
||||
股票 B ──┬── 策略1 → 独立持仓、独立资金
|
||||
└── 策略4 → 独立持仓、独立资金
|
||||
```
|
||||
|
||||
### 5.2 数据库表设计
|
||||
|
||||
| 表名 | 说明 |
|
||||
| ------------------- | ---------------------- |
|
||||
| `strategies` | 策略定义 |
|
||||
| `symbol_strategies` | 股票-策略配对 (核心表) |
|
||||
| `ss_positions` | 配对持仓 |
|
||||
| `ss_accounts` | 配对资金账户 |
|
||||
| `orders` | 订单记录 |
|
||||
| `trades` | 成交记录 |
|
||||
| `klines_1m` | 1分钟K线 |
|
||||
| `klines_5m` | 5分钟K线 |
|
||||
| `klines_15m` | 15分钟K线 |
|
||||
| `klines_30m` | 30分钟K线 |
|
||||
| `klines_60m` | 60分钟K线 |
|
||||
| `klines_1d` | 日K线 |
|
||||
| `klines_1w` | 周K线 |
|
||||
|
||||
---
|
||||
|
||||
## 六、Redis 通道定义
|
||||
|
||||
### 6.1 行情相关
|
||||
|
||||
```
|
||||
market:tick:{symbol} # Tick行情推送
|
||||
market:kline:{symbol}:{period} # K线推送
|
||||
market:dispatch:{symbol} # 行情分发(给策略引擎)
|
||||
```
|
||||
|
||||
### 6.2 交易相关
|
||||
|
||||
```
|
||||
trade:order:submit # 下单请求
|
||||
trade:order:cancel # 撤单请求
|
||||
trade:order:update # 订单状态更新
|
||||
trade:trade:report # 成交回报
|
||||
```
|
||||
|
||||
### 6.3 账户相关
|
||||
|
||||
```
|
||||
account:sync:position # 持仓同步
|
||||
account:sync:balance # 资金同步
|
||||
```
|
||||
|
||||
### 6.4 服务通信
|
||||
|
||||
```
|
||||
service:{from}:{to}:{action} # 服务间请求
|
||||
service:broadcast:{event} # 广播事件
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 七、部署架构
|
||||
|
||||
### 7.1 多机部署示例 (3台)
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────┐
|
||||
│ 主机 A (主节点) │
|
||||
│ 192.168.1.100 │
|
||||
├─────────────────────────────────────┤
|
||||
│ Redis :6379 │
|
||||
│ MySQL :3306 │
|
||||
│ gateway :8001 │
|
||||
│ core-service :8010 │
|
||||
└─────────────────────────────────────┘
|
||||
|
||||
┌─────────────────────────────────────┐
|
||||
│ 主机 B (数据节点) │
|
||||
│ 192.168.1.101 │
|
||||
├─────────────────────────────────────┤
|
||||
│ data-service :8020 │
|
||||
│ strategy-engine :8030 │
|
||||
└─────────────────────────────────────┘
|
||||
|
||||
┌─────────────────────────────────────┐
|
||||
│ 主机 C (QMT节点/Windows) │
|
||||
│ 192.168.1.102 │
|
||||
├─────────────────────────────────────┤
|
||||
│ qmt-adapter (Python 3.6) │
|
||||
│ QMT 客户端 │
|
||||
└─────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 7.2 进程管理
|
||||
|
||||
使用 Supervisor 管理所有服务进程,支持:
|
||||
- 自动启动/重启
|
||||
- 日志管理
|
||||
- 状态监控
|
||||
|
||||
---
|
||||
|
||||
## 八、跨平台支持
|
||||
|
||||
| 平台 | 支持的服务 |
|
||||
| ----------- | ---------------------------------------------------- |
|
||||
| **Linux** | gateway, core-service, data-service, strategy-engine |
|
||||
| **Windows** | 全部服务 + qmt-adapter |
|
||||
|
||||
设计原则:
|
||||
- 使用 `pathlib.Path` 处理路径
|
||||
- 使用 `platform` 模块检测系统
|
||||
- 配置文件使用 YAML,UTF-8 编码
|
||||
- 进程管理使用跨平台方案
|
||||
|
||||
---
|
||||
|
||||
## 九、控制台 (PyQt6)
|
||||
|
||||
### 9.1 功能模块
|
||||
|
||||
| 页面 | 功能 |
|
||||
| -------- | ---------------------------------------- |
|
||||
| 仪表盘 | 系统概览、服务状态卡片、快捷操作 |
|
||||
| 服务管理 | 启动/停止/重启服务、健康状态自动检测 |
|
||||
| 策略配置 | 股票-策略配对管理、参数配置表单 |
|
||||
| 系统设置 | Redis/MySQL/QMT/端口配置、连接测试 |
|
||||
| 运行日志 | 实时日志查看、按服务过滤、自动刷新、导出 |
|
||||
|
||||
### 9.2 技术特性
|
||||
|
||||
- **进程管理**: subprocess 启动/停止服务进程
|
||||
- **健康检测**: QThread 后台线程 + httpx 请求 /ping
|
||||
- **配置管理**: 读写 settings.yaml 配置文件
|
||||
- **连接测试**: 支持 Redis/MySQL 连接测试
|
||||
|
||||
---
|
||||
|
||||
## 十、版本记录
|
||||
|
||||
| 版本 | 日期 | 说明 |
|
||||
| ---- | ---------- | ------------------------------- |
|
||||
| 2.0 | 2025-12-09 | 微服务架构完成,PyQt6控制台完成 |
|
||||
| 1.5 | 2025-12-08 | 微服务架构重构设计 |
|
||||
| 1.0 | - | 原单体架构 |
|
||||
@ -1,370 +0,0 @@
|
||||
# 回测引擎设计文档
|
||||
|
||||
## 设计目标
|
||||
|
||||
创建一个**易用、灵活、可扩展**的回测引擎,满足以下需求:
|
||||
|
||||
1. ✅ 简洁的API - 一行代码即可运行回测
|
||||
2. ✅ GUI友好 - 提供进度回调,方便集成到界面
|
||||
3. ✅ 配置简化 - 用户只需关心核心参数
|
||||
4. ✅ 异步支持 - 支持同步和异步两种模式
|
||||
5. ✅ 完善的反馈 - 状态、进度、日志全方位反馈
|
||||
|
||||
## 架构设计
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ 用户层 │
|
||||
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
|
||||
│ │ 命令行CLI │ │ GUI界面 │ │ Python │ │
|
||||
│ │ │ │ │ │ API │ │
|
||||
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
|
||||
└───────┼───────────────┼───────────────┼───────────────────────┘
|
||||
│ │ │
|
||||
└───────────────┼───────────────┘
|
||||
│
|
||||
┌───────────────────────▼───────────────────────────────────────┐
|
||||
│ BacktestEngine │
|
||||
│ ┌──────────────────────────────────────────────────────┐ │
|
||||
│ │ 核心功能 │ │
|
||||
│ │ • 服务健康检查 • 配置转换 │ │
|
||||
│ │ • 任务提交 • 进度监控 │ │
|
||||
│ │ • 结果获取 • 状态管理 │ │
|
||||
│ └──────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌──────────────────────────────────────────────────────┐ │
|
||||
│ │ ProgressCallback (进度回调) │ │
|
||||
│ │ • on_status_change - 状态变化 │ │
|
||||
│ │ • on_progress_update - 进度更新 │ │
|
||||
│ │ • on_log - 日志输出 │ │
|
||||
│ └──────────────────────────────────────────────────────┘ │
|
||||
└────────────────────────┬───────────────────────────────────────┘
|
||||
│ HTTP API
|
||||
┌────────────────────────▼───────────────────────────────────────┐
|
||||
│ Backtest Service (微服务) │
|
||||
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
|
||||
│ │ Task │ │ Data │ │ Strategy │ │ Trade │ │
|
||||
│ │ Manager │ │ Player │ │ Manager │ │ Simulator│ │
|
||||
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
|
||||
└────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## 核心组件
|
||||
|
||||
### 1. BacktestEngine (引擎核心)
|
||||
|
||||
**职责**:封装与backtest_service的所有交互,提供简洁API
|
||||
|
||||
**主要方法**:
|
||||
```python
|
||||
class BacktestEngine:
|
||||
# 同步接口(推荐GUI和CLI使用)
|
||||
def run(config) -> BacktestResult
|
||||
|
||||
# 异步接口(高级用户)
|
||||
async def run_async(config) -> BacktestResult
|
||||
async def check_service() -> bool
|
||||
async def submit_task(config) -> str
|
||||
async def wait_for_completion(task_id) -> Dict
|
||||
async def get_result(task_id) -> BacktestResult
|
||||
async def list_tasks() -> List[Dict]
|
||||
async def get_task_status(task_id) -> Dict
|
||||
```
|
||||
|
||||
### 2. SimpleBacktestConfig (简化配置)
|
||||
|
||||
**职责**:用户友好的配置模型,自动转换为完整的BacktestConfig
|
||||
|
||||
**设计思想**:
|
||||
- 用户只需填写核心参数
|
||||
- 引擎自动生成task_id、补全默认值
|
||||
- 支持单股票和多股票
|
||||
- 支持初始持仓、自定义费率
|
||||
|
||||
**示例**:
|
||||
```python
|
||||
SimpleBacktestConfig(
|
||||
symbols=["000001.SZ"],
|
||||
start_date="2023-01-01",
|
||||
end_date="2023-12-31",
|
||||
strategy_id="ma_cross",
|
||||
strategy_params={"short_period": 5, "long_period": 10}
|
||||
)
|
||||
```
|
||||
|
||||
### 3. ProgressCallback (进度回调)
|
||||
|
||||
**职责**:提供回测过程的实时反馈
|
||||
|
||||
**使用场景**:
|
||||
- GUI进度条更新
|
||||
- 控制台进度显示
|
||||
- 日志记录
|
||||
- 状态监控
|
||||
|
||||
**实现示例**:
|
||||
```python
|
||||
class GUICallback(ProgressCallback):
|
||||
def on_progress_update(self, progress, message):
|
||||
self.progress_bar.set(progress) # 更新进度条
|
||||
self.status_label.set(message) # 更新状态文本
|
||||
```
|
||||
|
||||
### 4. BacktestResult (结果模型)
|
||||
|
||||
**职责**:统一的回测结果格式
|
||||
|
||||
**关键指标**:
|
||||
- 收益指标:初始/最终资金、总收益、收益率
|
||||
- 交易统计:交易次数、盈亏次数、胜率
|
||||
- 原始数据:完整的服务端返回数据
|
||||
|
||||
## 使用场景
|
||||
|
||||
### 场景1: 命令行快速测试
|
||||
|
||||
```python
|
||||
from src.backtest import quick_backtest
|
||||
|
||||
result = quick_backtest(
|
||||
symbols=["000001.SZ"],
|
||||
start_date="2023-01-01",
|
||||
end_date="2023-12-31",
|
||||
strategy_id="ma_cross",
|
||||
strategy_params={"short_period": 5, "long_period": 10}
|
||||
)
|
||||
|
||||
print(f"收益率: {result.return_pct:.2f}%")
|
||||
```
|
||||
|
||||
**特点**:
|
||||
- ✅ 一行代码运行回测
|
||||
- ✅ 无需创建引擎对象
|
||||
- ✅ 适合快速验证
|
||||
|
||||
### 场景2: GUI集成
|
||||
|
||||
```python
|
||||
class MyGUI:
|
||||
def run_backtest(self):
|
||||
engine = BacktestEngine(callback=GUICallback(self))
|
||||
|
||||
config = SimpleBacktestConfig(
|
||||
symbols=self.symbol_entry.get(),
|
||||
start_date=self.start_date.get(),
|
||||
end_date=self.end_date.get(),
|
||||
strategy_id=self.strategy_combo.get(),
|
||||
strategy_params=self.get_params()
|
||||
)
|
||||
|
||||
# 在后台线程运行
|
||||
threading.Thread(
|
||||
target=lambda: engine.run(config)
|
||||
).start()
|
||||
```
|
||||
|
||||
**特点**:
|
||||
- ✅ 进度条实时更新
|
||||
- ✅ 不阻塞UI线程
|
||||
- ✅ 异常处理友好
|
||||
|
||||
### 场景3: 批量回测
|
||||
|
||||
```python
|
||||
engine = BacktestEngine()
|
||||
|
||||
for symbol in symbols:
|
||||
config = SimpleBacktestConfig(
|
||||
symbols=[symbol],
|
||||
start_date="2023-01-01",
|
||||
end_date="2023-12-31",
|
||||
strategy_id="ma_cross",
|
||||
strategy_params={"short_period": 5, "long_period": 10}
|
||||
)
|
||||
|
||||
result = engine.run(config)
|
||||
results[symbol] = result
|
||||
|
||||
# 分析比较
|
||||
best_symbol = max(results.items(), key=lambda x: x[1].return_pct)
|
||||
```
|
||||
|
||||
**特点**:
|
||||
- ✅ 批量测试多只股票
|
||||
- ✅ 对比分析
|
||||
- ✅ 自动化流程
|
||||
|
||||
### 场景4: 参数优化
|
||||
|
||||
```python
|
||||
best_params = None
|
||||
best_return = -float('inf')
|
||||
|
||||
for short in range(3, 10):
|
||||
for long in range(10, 30):
|
||||
config = SimpleBacktestConfig(
|
||||
symbols=["000001.SZ"],
|
||||
start_date="2023-01-01",
|
||||
end_date="2023-12-31",
|
||||
strategy_id="ma_cross",
|
||||
strategy_params={"short_period": short, "long_period": long}
|
||||
)
|
||||
|
||||
result = engine.run(config)
|
||||
|
||||
if result.return_pct > best_return:
|
||||
best_return = result.return_pct
|
||||
best_params = {"short": short, "long": long}
|
||||
|
||||
print(f"最优参数: {best_params}, 收益率: {best_return:.2f}%")
|
||||
```
|
||||
|
||||
**特点**:
|
||||
- ✅ 网格搜索
|
||||
- ✅ 参数寻优
|
||||
- ✅ 性能评估
|
||||
|
||||
## 文件结构
|
||||
|
||||
```
|
||||
src/backtest/
|
||||
├── __init__.py # 模块导出
|
||||
├── bt_engine.py # 核心引擎(⭐ 主文件)
|
||||
├── main.py # 命令行入口
|
||||
├── test_engine.py # 测试脚本
|
||||
└── README.md # 使用文档
|
||||
|
||||
examples/
|
||||
└── backtest_gui_example.py # GUI示例
|
||||
```
|
||||
|
||||
## 关键设计决策
|
||||
|
||||
### 1. 为什么使用SimpleBacktestConfig?
|
||||
|
||||
**问题**:backtest_service要求的完整配置很复杂,有多层嵌套
|
||||
|
||||
**解决**:
|
||||
- 用户使用简化配置(平铺结构)
|
||||
- 引擎内部自动转换为完整配置
|
||||
- 降低使用门槛
|
||||
|
||||
### 2. 为什么同时提供同步和异步接口?
|
||||
|
||||
**原因**:
|
||||
- GUI/CLI通常使用同步代码(简单)
|
||||
- 高级场景需要异步(性能)
|
||||
- `run()` 内部调用 `asyncio.run(run_async())`
|
||||
|
||||
### 3. 为什么使用回调而不是事件?
|
||||
|
||||
**原因**:
|
||||
- 回调更简单直观
|
||||
- 容易集成到现有框架
|
||||
- 适合单向数据流(引擎→用户)
|
||||
|
||||
### 4. 为什么要自动生成task_id?
|
||||
|
||||
**原因**:
|
||||
- 用户不需要关心任务ID
|
||||
- 避免ID冲突
|
||||
- 使用时间戳保证唯一性
|
||||
|
||||
## 扩展性设计
|
||||
|
||||
### 1. 自定义配置加载器
|
||||
|
||||
```python
|
||||
class YAMLConfigLoader:
|
||||
@staticmethod
|
||||
def load(file_path: str) -> SimpleBacktestConfig:
|
||||
import yaml
|
||||
with open(file_path) as f:
|
||||
data = yaml.safe_load(f)
|
||||
return SimpleBacktestConfig(**data)
|
||||
|
||||
# 使用
|
||||
config = YAMLConfigLoader.load("my_backtest.yaml")
|
||||
result = engine.run(config)
|
||||
```
|
||||
|
||||
### 2. 自定义结果处理器
|
||||
|
||||
```python
|
||||
class ResultAnalyzer:
|
||||
def analyze(self, result: BacktestResult):
|
||||
return {
|
||||
"sharpe_ratio": self.calc_sharpe(result),
|
||||
"max_drawdown": self.calc_drawdown(result),
|
||||
"win_rate": result.win_trades / result.total_trades
|
||||
}
|
||||
|
||||
analyzer = ResultAnalyzer()
|
||||
metrics = analyzer.analyze(result)
|
||||
```
|
||||
|
||||
### 3. 多引擎并发
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
|
||||
async def parallel_backtest(configs):
|
||||
engines = [BacktestEngine() for _ in configs]
|
||||
|
||||
tasks = [
|
||||
engine.run_async(config)
|
||||
for engine, config in zip(engines, configs)
|
||||
]
|
||||
|
||||
results = await asyncio.gather(*tasks)
|
||||
return results
|
||||
|
||||
# 使用
|
||||
results = asyncio.run(parallel_backtest(configs))
|
||||
```
|
||||
|
||||
## 测试验证
|
||||
|
||||
### 运行测试
|
||||
|
||||
```bash
|
||||
# 1. 确保服务启动
|
||||
python -m src.backtest_service.app
|
||||
|
||||
# 2. 运行测试
|
||||
python -m src.backtest.test_engine
|
||||
```
|
||||
|
||||
### 测试覆盖
|
||||
|
||||
- ✅ 服务连接测试
|
||||
- ✅ 任务列表查询
|
||||
- ✅ 基本回测流程
|
||||
- ✅ 异步提交验证
|
||||
- ✅ 进度回调测试
|
||||
|
||||
## 未来优化
|
||||
|
||||
### 短期
|
||||
- [ ] 支持YAML/JSON配置文件
|
||||
- [ ] 增加更多回调事件(交易信号、持仓变化)
|
||||
- [ ] 结果可视化(图表生成)
|
||||
- [ ] 批量回测工具
|
||||
|
||||
### 长期
|
||||
- [ ] 参数优化框架
|
||||
- [ ] 回测报告生成
|
||||
- [ ] 性能指标计算(夏普、最大回撤)
|
||||
- [ ] Web界面集成
|
||||
|
||||
## 总结
|
||||
|
||||
BacktestEngine的设计核心是**简化用户体验**,通过:
|
||||
|
||||
1. **简化配置** - 用户只需关心核心参数
|
||||
2. **统一接口** - 同步/异步两种模式自由选择
|
||||
3. **实时反馈** - 通过回调提供进度和状态
|
||||
4. **易于集成** - 适配CLI、GUI、API等多种场景
|
||||
5. **扩展友好** - 保留足够的扩展点
|
||||
|
||||
这使得回测引擎既适合初学者快速上手,也能满足高级用户的定制需求。
|
||||
@ -1,320 +0,0 @@
|
||||
# QTrade 重构构建方案
|
||||
|
||||
> 创建日期: 2025-12-08
|
||||
> 更新日期: 2025-12-09
|
||||
> 状态: ✅ 已完成
|
||||
|
||||
## 一、重构目标
|
||||
|
||||
将现有单体架构重构为微服务架构,实现:
|
||||
- FastAPI + Redis + MySQL 技术栈
|
||||
- 服务化拆分
|
||||
- 实盘/回测代码复用
|
||||
- 跨平台支持
|
||||
- PyQt6 桌面控制台
|
||||
|
||||
---
|
||||
|
||||
## 二、构建阶段
|
||||
|
||||
### 阶段1: 核心模块 (core)
|
||||
|
||||
**目标**: 建立所有服务共用的基础模块
|
||||
|
||||
| 任务 | 状态 | 说明 |
|
||||
| --------------------------------- | -------- | ------------------------ |
|
||||
| 1.1 项目结构搭建 | ✅ 已完成 | 创建目录结构 |
|
||||
| 1.2 配置管理 (config.py) | ✅ 已完成 | Pydantic Settings + YAML |
|
||||
| 1.3 Redis客户端 (redis_client.py) | ✅ 已完成 | 异步Redis封装 |
|
||||
| 1.4 数据库连接 (database.py) | ✅ 已完成 | SQLAlchemy async |
|
||||
| 1.5 日志模块 (logger.py) | ✅ 已完成 | 统一日志配置 |
|
||||
| 1.6 数据模型 (models/) | ✅ 已完成 | Pydantic 模型定义 |
|
||||
|
||||
**产出物**:
|
||||
```
|
||||
src/core/
|
||||
├── __init__.py
|
||||
├── config.py # 配置管理
|
||||
├── redis_client.py # Redis 客户端
|
||||
├── database.py # 数据库连接
|
||||
├── logger.py # 日志模块
|
||||
└── models/ # 数据模型
|
||||
├── __init__.py
|
||||
├── market.py # 行情数据模型
|
||||
├── order.py # 订单模型
|
||||
├── position.py # 持仓模型
|
||||
└── symbol_strategy.py # 配对模型
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 阶段2: Gateway 服务
|
||||
|
||||
**目标**: 建立 API 入口服务
|
||||
|
||||
| 任务 | 状态 | 说明 |
|
||||
| -------------------- | -------- | ------------------ |
|
||||
| 2.1 FastAPI 应用框架 | ✅ 已完成 | 应用实例、生命周期 |
|
||||
| 2.2 健康检查接口 | ✅ 已完成 | /ping |
|
||||
| 2.3 路由结构 | ✅ 已完成 | 路由模块划分 |
|
||||
| 2.4 中间件 | ✅ 已完成 | 日志、异常处理 |
|
||||
| 2.5 启动脚本 | ✅ 已完成 | 服务启动入口 |
|
||||
|
||||
**产出物**:
|
||||
```
|
||||
src/gateway/
|
||||
├── __init__.py
|
||||
├── main.py # 服务入口
|
||||
├── app.py # FastAPI 应用
|
||||
├── deps.py # 依赖注入
|
||||
├── middleware.py # 中间件
|
||||
└── routes/
|
||||
├── __init__.py
|
||||
├── health.py # 健康检查
|
||||
├── market.py # 行情接口 (转发)
|
||||
├── trading.py # 交易接口 (转发)
|
||||
├── account.py # 账户接口 (转发)
|
||||
└── backtest.py # 回测接口 (转发)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 阶段3: Data Service 服务
|
||||
|
||||
**目标**: 建立数据服务
|
||||
|
||||
| 任务 | 状态 | 说明 |
|
||||
| ---------------- | -------- | --------------- |
|
||||
| 3.1 服务框架 | ✅ 已完成 | FastAPI 应用 |
|
||||
| 3.2 行情接收模块 | ✅ 已完成 | 订阅 Redis 行情 |
|
||||
| 3.3 行情分发模块 | ✅ 已完成 | 分发给策略引擎 |
|
||||
| 3.4 K线存储模块 | ✅ 已完成 | 按周期分表存储 |
|
||||
| 3.5 K线查询接口 | ✅ 已完成 | 历史数据查询 |
|
||||
| 3.6 回测数据回放 | ✅ 已完成 | 模拟QMT推送 |
|
||||
|
||||
**产出物**:
|
||||
```
|
||||
src/data_service/
|
||||
├── __init__.py
|
||||
├── main.py
|
||||
├── app.py
|
||||
├── market/
|
||||
│ ├── receiver.py # 行情接收
|
||||
│ ├── dispatcher.py # 行情分发
|
||||
│ └── cache.py # 行情缓存
|
||||
├── kline/
|
||||
│ ├── storage.py # K线存储
|
||||
│ ├── query.py # K线查询
|
||||
│ └── models.py # K线ORM模型
|
||||
└── routes/
|
||||
├── market.py
|
||||
└── kline.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 阶段4: Core Service 服务
|
||||
|
||||
**目标**: 建立核心业务服务
|
||||
|
||||
| 任务 | 状态 | 说明 |
|
||||
| ---------------- | -------- | -------------------- |
|
||||
| 4.1 服务框架 | ✅ 已完成 | FastAPI 应用 |
|
||||
| 4.2 配对管理模块 | ✅ 已完成 | 股票-策略配对 CRUD |
|
||||
| 4.3 订单管理模块 | ✅ 已完成 | 订单创建、查询、撤销 |
|
||||
| 4.4 风控模块 | ✅ 已完成 | 下单前风控检查 |
|
||||
| 4.5 持仓管理模块 | ✅ 已完成 | 持仓更新、查询 |
|
||||
| 4.6 资金管理模块 | ✅ 已完成 | 资金冻结、释放 |
|
||||
|
||||
**产出物**:
|
||||
```
|
||||
src/core_service/
|
||||
├── __init__.py
|
||||
├── main.py
|
||||
├── app.py
|
||||
├── services/
|
||||
│ ├── order_service.py
|
||||
│ ├── position_service.py
|
||||
│ ├── balance_service.py
|
||||
│ └── pairing_service.py
|
||||
└── routes/
|
||||
├── order.py
|
||||
├── position.py
|
||||
├── balance.py
|
||||
└── pairing.py
|
||||
```
|
||||
└── account.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 阶段5: Strategy Engine 服务
|
||||
|
||||
**目标**: 建立策略引擎服务
|
||||
|
||||
| 任务 | 状态 | 说明 |
|
||||
| ---------------- | -------- | ------------------ |
|
||||
| 5.1 服务框架 | ✅ 已完成 | FastAPI 应用 |
|
||||
| 5.2 策略管理模块 | ✅ 已完成 | 策略加载、启停 |
|
||||
| 5.3 行情订阅模块 | ✅ 已完成 | 订阅 Redis 行情 |
|
||||
| 5.4 信号生成模块 | ✅ 已完成 | 策略执行、信号输出 |
|
||||
| 5.5 策略基类 | ✅ 已完成 | 策略抽象接口 |
|
||||
|
||||
**产出物**:
|
||||
```
|
||||
src/strategy_engine/
|
||||
├── __init__.py
|
||||
├── main.py
|
||||
├── app.py
|
||||
├── strategies/
|
||||
│ ├── base.py # 策略基类
|
||||
│ ├── grid_strategy.py # 网格策略
|
||||
│ └── ma_strategy.py # 均线策略
|
||||
├── engine/
|
||||
│ ├── manager.py # 策略管理
|
||||
│ └── executor.py # 策略执行器
|
||||
└── routes/
|
||||
└── strategy.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 阶段6: QMT Adapter
|
||||
|
||||
**目标**: 建立QMT适配层
|
||||
|
||||
| 任务 | 状态 | 说明 |
|
||||
| ---------------- | -------- | --------------- |
|
||||
| 6.1 项目结构 | ✅ 已完成 | FastAPI 应用 |
|
||||
| 6.2 行情采集模块 | ✅ 已完成 | QMT → Redis |
|
||||
| 6.3 交易执行模块 | ✅ 已完成 | Redis → QMT |
|
||||
| 6.4 账户同步模块 | ✅ 已完成 | QMT → Redis |
|
||||
| 6.5 模拟模式 | ✅ 已完成 | 无xtquant时模拟 |
|
||||
|
||||
**产出物**:
|
||||
```
|
||||
src/qmt_adapter/
|
||||
├── __init__.py
|
||||
├── main.py # 入口
|
||||
├── app.py # FastAPI 应用
|
||||
├── qmt_client.py # QMT SDK 封装
|
||||
├── market_feeder.py # 行情采集
|
||||
├── trade_executor.py # 交易执行
|
||||
├── account_sync.py # 账户同步
|
||||
└── routes/
|
||||
└── qmt.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 阶段7: PyQt6 控制台
|
||||
|
||||
**目标**: 建立桌面管理控制台
|
||||
|
||||
| 任务 | 状态 | 说明 |
|
||||
| ---------------- | -------- | ------------------ |
|
||||
| 7.1 应用框架 | ✅ 已完成 | PyQt6 主窗口 |
|
||||
| 7.2 仪表盘页面 | ✅ 已完成 | 系统概览、快捷操作 |
|
||||
| 7.3 服务管理页面 | ✅ 已完成 | 启停服务、健康检测 |
|
||||
| 7.4 策略配置页面 | ✅ 已完成 | 配对管理、参数配置 |
|
||||
| 7.5 系统设置页面 | ✅ 已完成 | 配置编辑、连接测试 |
|
||||
| 7.6 日志查看页面 | ✅ 已完成 | 实时日志、过滤导出 |
|
||||
|
||||
**产出物**:
|
||||
```
|
||||
src/console/
|
||||
├── __init__.py
|
||||
├── main.py # 应用入口
|
||||
└── windows/
|
||||
├── __init__.py
|
||||
├── main_window.py # 主窗口
|
||||
└── pages/
|
||||
├── __init__.py
|
||||
├── dashboard_page.py # 仪表盘
|
||||
├── services_page.py # 服务管理
|
||||
├── strategies_page.py # 策略配置
|
||||
├── settings_page.py # 系统设置
|
||||
└── logs_page.py # 运行日志
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 阶段8: 测试与文档
|
||||
|
||||
**目标**: 完善测试和文档
|
||||
|
||||
| 任务 | 状态 | 说明 |
|
||||
| ---------------- | -------- | ------------- |
|
||||
| 8.1 单元测试 | ✅ 已完成 | pytest |
|
||||
| 8.2 数据库初始化 | ✅ 已完成 | init.sql |
|
||||
| 8.3 配置文件模板 | ✅ 已完成 | settings.yaml |
|
||||
| 8.4 README 文档 | ✅ 已完成 | 使用说明 |
|
||||
| 8.5 架构文档 | ✅ 已完成 | 设计说明 |
|
||||
|
||||
---
|
||||
|
||||
## 三、目录结构总览
|
||||
|
||||
```
|
||||
QTrade/
|
||||
├── docs/
|
||||
│ └── architecture/
|
||||
│ ├── ARCHITECTURE.md # 架构设计文档
|
||||
│ └── BUILD_PLAN.md # 本文档
|
||||
│
|
||||
├── src/
|
||||
│ ├── core/ # 阶段1: 核心模块 ✅
|
||||
│ ├── gateway/ # 阶段2: API网关 ✅
|
||||
│ ├── data_service/ # 阶段3: 数据服务 ✅
|
||||
│ ├── core_service/ # 阶段4: 核心业务 ✅
|
||||
│ ├── strategy_engine/ # 阶段5: 策略引擎 ✅
|
||||
│ ├── qmt_adapter/ # 阶段6: QMT适配 ✅
|
||||
│ ├── console/ # 阶段7: PyQt6控制台 ✅
|
||||
│ └── main.py # 服务启动入口
|
||||
│
|
||||
├── configs/
|
||||
│ └── settings.yaml # 主配置
|
||||
│
|
||||
├── database/
|
||||
│ └── init.sql # 初始化SQL
|
||||
│
|
||||
├── tests/ # 测试 ✅
|
||||
├── requirements.txt # Python 依赖
|
||||
└── README.md # 项目文档 ✅
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 四、进度跟踪
|
||||
|
||||
### 当前状态
|
||||
|
||||
- **当前阶段**: ✅ 全部完成
|
||||
- **完成日期**: 2025-12-09
|
||||
- **总文件数**: 60+
|
||||
- **总代码行**: 6000+
|
||||
|
||||
### 进度记录
|
||||
|
||||
| 日期 | 完成内容 | 备注 |
|
||||
| ---------- | ------------- | -------------------------------------------------- |
|
||||
| 2025-12-08 | 架构设计完成 | 确定技术方案 |
|
||||
| 2025-12-08 | 构建方案创建 | 本文档 |
|
||||
| 2025-12-08 | 阶段1完成 | 核心模块 (config, redis, database, logger, models) |
|
||||
| 2025-12-08 | 阶段2完成 | Gateway 服务 |
|
||||
| 2025-12-08 | 阶段3完成 | Data Service 服务 |
|
||||
| 2025-12-08 | 阶段4完成 | Core Service 服务 |
|
||||
| 2025-12-08 | 阶段5完成 | Strategy Engine 服务 |
|
||||
| 2025-12-08 | 阶段6完成 | QMT Adapter 服务 |
|
||||
| 2025-12-08 | 阶段8部分完成 | 单元测试、数据库初始化 |
|
||||
| 2025-12-09 | 阶段7完成 | PyQt6 桌面控制台 |
|
||||
| 2025-12-09 | 阶段8完成 | 文档更新 |
|
||||
|
||||
---
|
||||
|
||||
## 五、注意事项
|
||||
|
||||
1. **QMT模拟模式**: 未安装xtquant SDK时自动启用模拟模式
|
||||
2. **Python版本**: 主服务使用 Python 3.10+,支持async/await
|
||||
3. **依赖管理**: 使用 pip install -r requirements.txt 安装
|
||||
4. **文档同步**: 代码变更同步更新文档
|
||||
@ -1,222 +0,0 @@
|
||||
# QTrade 配置管理系统
|
||||
|
||||
## 配置文件结构
|
||||
|
||||
```
|
||||
configs/
|
||||
├── global.yaml # 全局公共配置
|
||||
├── settings.yaml # 旧版配置(废弃,保留用于迁移)
|
||||
└── services/ # 服务独立配置
|
||||
├── core_service.yaml
|
||||
├── data_service.yaml
|
||||
├── strategy_engine.yaml
|
||||
└── qmt_service.yaml
|
||||
```
|
||||
|
||||
## 配置优先级
|
||||
|
||||
配置加载优先级(从低到高):
|
||||
|
||||
1. **global.yaml** - 全局公共配置(最低优先级)
|
||||
2. **services/{service_name}.yaml** - 服务独立配置
|
||||
3. **环境变量** - 运行时覆盖(最高优先级)
|
||||
|
||||
### 环境变量命名规则
|
||||
|
||||
环境变量格式:`QTRADE_{配置路径}`,路径用下划线分隔,例如:
|
||||
|
||||
- `QTRADE_DATABASE_HOST=192.168.1.100` → `database.host`
|
||||
- `QTRADE_REDIS_PORT=6380` → `redis.port`
|
||||
- `QTRADE_APP_ENV=production` → `app.env`
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 1. 加载全局配置
|
||||
|
||||
```python
|
||||
from src.core.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
print(settings.app.name) # QTrade
|
||||
print(settings.redis.url) # redis://127.0.0.1:6379/0
|
||||
print(settings.database.url) # mysql+aiomysql://...
|
||||
```
|
||||
|
||||
### 2. 加载服务配置
|
||||
|
||||
```python
|
||||
from src.core.config import get_settings
|
||||
|
||||
# 加载 data_service 配置
|
||||
settings = get_settings("data_service")
|
||||
|
||||
print(settings.service.name) # DataService
|
||||
print(settings.service.port) # 8020
|
||||
print(settings.data_download.default_days) # 120
|
||||
```
|
||||
|
||||
### 3. 修改并保存配置
|
||||
|
||||
```python
|
||||
from src.core.config import get_settings
|
||||
|
||||
settings = get_settings("qmt_service")
|
||||
|
||||
# 修改配置
|
||||
settings.set("qmt.simulation", False)
|
||||
settings.set("service.port", 8041)
|
||||
|
||||
# 保存到服务配置文件
|
||||
settings.save("service") # 保存到 configs/services/qmt_service.yaml
|
||||
|
||||
# 保存到全局配置文件
|
||||
settings.save("global") # 保存到 configs/global.yaml
|
||||
```
|
||||
|
||||
### 4. 直接使用 ConfigManager
|
||||
|
||||
```python
|
||||
from src.core.config_manager import ConfigManager
|
||||
|
||||
# 加载配置
|
||||
config = ConfigManager.load("strategy_engine")
|
||||
|
||||
# 获取值
|
||||
port = config.get("service.port", 8030)
|
||||
|
||||
# 设置值
|
||||
config.set("strategy.check_interval", 10)
|
||||
|
||||
# 保存
|
||||
config.save()
|
||||
```
|
||||
|
||||
### 5. 环境变量覆盖
|
||||
|
||||
```bash
|
||||
# 在启动服务前设置环境变量
|
||||
export QTRADE_DATABASE_HOST=prod.database.com
|
||||
export QTRADE_REDIS_PORT=6380
|
||||
export QTRADE_APP_ENV=production
|
||||
|
||||
python -m src.data_service.app
|
||||
```
|
||||
|
||||
## 配置文件说明
|
||||
|
||||
### global.yaml
|
||||
|
||||
包含所有服务共用的配置:
|
||||
- 应用信息(名称、版本、环境)
|
||||
- Redis 配置
|
||||
- MySQL 配置
|
||||
- 日志配置
|
||||
- 行情配置
|
||||
- 交易配置
|
||||
- 服务端口映射
|
||||
|
||||
### services/{service_name}.yaml
|
||||
|
||||
每个服务的独立配置:
|
||||
|
||||
**data_service.yaml**
|
||||
- 服务基本信息(名称、端口)
|
||||
- 数据下载配置
|
||||
|
||||
**qmt_service.yaml**
|
||||
- 服务基本信息
|
||||
- QMT 客户端配置
|
||||
- XtQuant 数据中心配置
|
||||
|
||||
**strategy_engine.yaml**
|
||||
- 服务基本信息
|
||||
- 策略自动加载路径
|
||||
- 策略实例检查间隔
|
||||
|
||||
**core_service.yaml**
|
||||
- 服务基本信息
|
||||
|
||||
## 最佳实践
|
||||
|
||||
1. **敏感信息使用环境变量**
|
||||
```bash
|
||||
export QTRADE_DATABASE_PASSWORD=your_password
|
||||
export QTRADE_REDIS_PASSWORD=your_redis_password
|
||||
```
|
||||
|
||||
2. **开发/生产环境分离**
|
||||
```bash
|
||||
# 开发环境
|
||||
export QTRADE_APP_ENV=development
|
||||
|
||||
# 生产环境
|
||||
export QTRADE_APP_ENV=production
|
||||
export QTRADE_DATABASE_HOST=prod.db.com
|
||||
```
|
||||
|
||||
3. **服务启动时加载对应配置**
|
||||
```python
|
||||
# data_service/app.py
|
||||
from src.core.config import get_settings
|
||||
|
||||
settings = get_settings("data_service")
|
||||
|
||||
uvicorn.run(
|
||||
app,
|
||||
host=settings.service.host,
|
||||
port=settings.service.port
|
||||
)
|
||||
```
|
||||
|
||||
4. **配置修改后保存**
|
||||
```python
|
||||
# 修改配置
|
||||
settings.set("service.port", 8021)
|
||||
|
||||
# 保存到服务配置文件(推荐)
|
||||
settings.save("service")
|
||||
```
|
||||
|
||||
## 迁移指南
|
||||
|
||||
### 从旧版 settings.yaml 迁移
|
||||
|
||||
1. 将公共配置复制到 `global.yaml`
|
||||
2. 将服务特定配置拆分到 `services/{service_name}.yaml`
|
||||
3. 更新代码导入:
|
||||
```python
|
||||
# 旧版
|
||||
from src.core.config import settings
|
||||
|
||||
# 新版
|
||||
from src.core.config import get_settings
|
||||
settings = get_settings("data_service")
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
**Q: 如何查看当前生效的配置?**
|
||||
|
||||
```python
|
||||
settings = get_settings("data_service")
|
||||
print(settings._manager.get_all())
|
||||
```
|
||||
|
||||
**Q: 配置修改后如何重新加载?**
|
||||
|
||||
```python
|
||||
settings.reload()
|
||||
```
|
||||
|
||||
**Q: 如何在不同环境使用不同配置?**
|
||||
|
||||
使用环境变量 `QTRADE_APP_ENV` 控制,并在代码中判断:
|
||||
|
||||
```python
|
||||
settings = get_settings()
|
||||
if settings.app.env == "production":
|
||||
# 生产环境逻辑
|
||||
else:
|
||||
# 开发环境逻辑
|
||||
```
|
||||
1053
docs/design_pricinple.md
Normal file
1053
docs/design_pricinple.md
Normal file
File diff suppressed because it is too large
Load Diff
@ -1,245 +0,0 @@
|
||||
# QTrade 多环境配置说明
|
||||
|
||||
## 概述
|
||||
|
||||
QTrade 支持三套完全隔离的运行环境:
|
||||
|
||||
| 环境 | 数据库 | Redis前缀 | 端口范围 | 用途 |
|
||||
| ---------- | -------------------- | --------- | ----------- | -------- |
|
||||
| production | QTrade_RealTrade | real: | 9000-9999 | 实盘交易 |
|
||||
| backtest | QTrade_BackTestTrade | bt: | 10000-10999 | 策略回测 |
|
||||
| simulation | QTrade_SimuTrade | simu: | 11000-11999 | 模拟交易 |
|
||||
|
||||
## 环境隔离
|
||||
|
||||
### 1. 数据库隔离
|
||||
每个环境使用独立的MySQL数据库:
|
||||
- 实盘: `QTrade_RealTrade`
|
||||
- 回测: `QTrade_BackTestTrade`
|
||||
- 模拟: `QTrade_SimuTrade`
|
||||
|
||||
### 2. Redis频道隔离
|
||||
每个环境使用独立的频道前缀:
|
||||
- 实盘: `real:kline:update`, `real:signal:create`
|
||||
- 回测: `bt:kline:update`, `bt:signal:create`
|
||||
- 模拟: `simu:kline:update`, `simu:signal:create`
|
||||
|
||||
### 3. 端口隔离
|
||||
每个环境使用独立的端口范围:
|
||||
- 实盘: 9000-9999
|
||||
- 回测: 10000-10999
|
||||
- 模拟: 11000-11999
|
||||
|
||||
### 4. 日志隔离
|
||||
每个环境使用独立的日志目录:
|
||||
- 实盘: `logs/production/`
|
||||
- 回测: `logs/backtest/`
|
||||
- 模拟: `logs/simulation/`
|
||||
|
||||
## 初始化
|
||||
|
||||
### 1. 创建数据库
|
||||
```bash
|
||||
# 连接MySQL
|
||||
mysql -u root -p
|
||||
|
||||
# 执行初始化脚本
|
||||
source scripts/init_databases.sql;
|
||||
```
|
||||
|
||||
或直接执行:
|
||||
```bash
|
||||
mysql -u root -p < scripts/init_databases.sql
|
||||
```
|
||||
|
||||
### 2. 运行数据库迁移
|
||||
```bash
|
||||
# 实盘环境
|
||||
alembic --config configs/production.yaml upgrade head
|
||||
|
||||
# 回测环境
|
||||
alembic --config configs/backtest.yaml upgrade head
|
||||
|
||||
# 模拟环境
|
||||
alembic --config configs/simulation.yaml upgrade head
|
||||
```
|
||||
|
||||
## 启动服务
|
||||
|
||||
### 使用启动脚本(推荐)
|
||||
|
||||
```bash
|
||||
# 启动实盘环境
|
||||
python scripts/start_services.py production data_service strategy_service trade_service
|
||||
|
||||
# 启动回测环境
|
||||
python scripts/start_services.py backtest data_service strategy_service backtest_service
|
||||
|
||||
# 启动模拟环境
|
||||
python scripts/start_services.py simulation data_service strategy_service trade_service
|
||||
```
|
||||
|
||||
### 手动启动
|
||||
|
||||
**实盘环境**:
|
||||
```bash
|
||||
uvicorn src.data_service.app:app --env-file .env.production
|
||||
uvicorn src.strategy_service.app:app --env-file .env.production
|
||||
uvicorn src.trade_service.app:app --env-file .env.production
|
||||
```
|
||||
|
||||
**回测环境**:
|
||||
```bash
|
||||
uvicorn src.data_service.app:app --env-file .env.backtest
|
||||
uvicorn src.strategy_service.app:app --env-file .env.backtest
|
||||
uvicorn src.backtest_service.app:app --env-file .env.backtest
|
||||
```
|
||||
|
||||
**模拟环境**:
|
||||
```bash
|
||||
uvicorn src.data_service.app:app --env-file .env.simulation
|
||||
uvicorn src.strategy_service.app:app --env-file .env.simulation
|
||||
uvicorn src.trade_service.app:app --env-file .env.simulation
|
||||
```
|
||||
|
||||
## 配置文件
|
||||
|
||||
### 环境配置文件
|
||||
- `configs/production.yaml` - 实盘环境配置
|
||||
- `configs/backtest.yaml` - 回测环境配置
|
||||
- `configs/simulation.yaml` - 模拟环境配置
|
||||
|
||||
### 环境变量文件
|
||||
- `.env.production` - 实盘环境变量
|
||||
- `.env.backtest` - 回测环境变量
|
||||
- `.env.simulation` - 模拟环境变量
|
||||
|
||||
## 代码中使用
|
||||
|
||||
### 获取环境配置
|
||||
```python
|
||||
from src.core.config import settings
|
||||
|
||||
# 当前环境
|
||||
env = settings.environment.env # "production" | "backtest" | "simulation"
|
||||
|
||||
# 数据库名称
|
||||
db_name = settings.environment.db_name # "QTrade_RealTrade" 等
|
||||
|
||||
# Redis前缀
|
||||
prefix = settings.environment.redis_prefix # "real" | "bt" | "simu"
|
||||
|
||||
# 端口偏移
|
||||
offset = settings.environment.port_offset # 9000 | 10000 | 11000
|
||||
```
|
||||
|
||||
### 获取频道名称
|
||||
```python
|
||||
from src.core.config import settings
|
||||
|
||||
# K线更新频道
|
||||
kline_channel = settings.channels.kline_update
|
||||
# production: "real:kline:update"
|
||||
# backtest: "bt:kline:update"
|
||||
# simulation: "simu:kline:update"
|
||||
|
||||
# 信号创建频道
|
||||
signal_channel = settings.channels.signal_create
|
||||
# production: "real:signal:create"
|
||||
# backtest: "bt:signal:create"
|
||||
# simulation: "simu:signal:create"
|
||||
```
|
||||
|
||||
### 订阅/发布
|
||||
```python
|
||||
import redis.asyncio as redis
|
||||
from src.core.config import settings
|
||||
|
||||
# 发布K线数据
|
||||
async def publish_kline(kline_data):
|
||||
r = redis.from_url(settings.redis.url)
|
||||
await r.publish(settings.channels.kline_update, kline_data)
|
||||
|
||||
# 订阅信号
|
||||
async def subscribe_signals():
|
||||
r = redis.from_url(settings.redis.url)
|
||||
pubsub = r.pubsub()
|
||||
await pubsub.subscribe(settings.channels.signal_create)
|
||||
|
||||
async for message in pubsub.listen():
|
||||
# 处理信号
|
||||
pass
|
||||
```
|
||||
|
||||
## 服务端口分配
|
||||
|
||||
### 实盘环境 (9000-9999)
|
||||
- DataService: 9001
|
||||
- StrategyEngine: 9003
|
||||
- TradeService: 9005
|
||||
- QMTService: 9007
|
||||
|
||||
### 回测环境 (10000-10999)
|
||||
- DataService: 10001
|
||||
- StrategyEngine: 10003
|
||||
- BacktestService: 10007
|
||||
|
||||
### 模拟环境 (11000-11999)
|
||||
- DataService: 11001
|
||||
- StrategyEngine: 11003
|
||||
- TradeService: 11005
|
||||
|
||||
## 注意事项
|
||||
|
||||
### 1. 环境切换
|
||||
切换环境时,请确保:
|
||||
- 使用正确的环境变量文件
|
||||
- 配置文件中的环境设置正确
|
||||
- 端口不冲突
|
||||
|
||||
### 2. 数据隔离
|
||||
三个环境的数据完全隔离:
|
||||
- 实盘数据不会影响回测
|
||||
- 回测数据不会影响模拟
|
||||
- 各环境可以同时运行
|
||||
|
||||
### 3. Redis DB分离
|
||||
为了进一步隔离,建议使用不同的Redis DB:
|
||||
- 实盘: db=0
|
||||
- 回测: db=1
|
||||
- 模拟: db=2
|
||||
|
||||
### 4. 日志管理
|
||||
各环境日志独立存储,便于问题排查:
|
||||
```
|
||||
logs/
|
||||
├── production/
|
||||
│ ├── data_service.log
|
||||
│ └── strategy_service.log
|
||||
├── backtest/
|
||||
│ └── backtest_service.log
|
||||
└── simulation/
|
||||
└── trade_service.log
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
### Q: 如何同时运行多个环境?
|
||||
A: 由于端口和数据库完全隔离,可以同时启动三个环境的服务。
|
||||
|
||||
### Q: 环境之间如何切换?
|
||||
A: 使用不同的环境变量文件启动服务即可,或使用启动脚本指定环境。
|
||||
|
||||
### Q: 回测环境可以访问实盘数据吗?
|
||||
A: 不可以。各环境数据库完全独立,如需共享数据请手动迁移或同步。
|
||||
|
||||
### Q: 如何清理某个环境的数据?
|
||||
A: 直接清空对应的数据库即可,不影响其他环境。
|
||||
|
||||
## 最佳实践
|
||||
|
||||
1. **开发阶段**: 使用回测环境或模拟环境
|
||||
2. **测试阶段**: 使用模拟环境验证策略
|
||||
3. **生产阶段**: 使用实盘环境进行真实交易
|
||||
4. **数据备份**: 定期备份各环境数据库
|
||||
5. **日志监控**: 监控各环境日志,及时发现问题
|
||||
@ -1,82 +0,0 @@
|
||||
# ============================================================
|
||||
# QTrade - A股量化交易系统 依赖清单
|
||||
# Python 版本要求: 3.10+
|
||||
# ============================================================
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# 核心依赖 (所有服务都需要)
|
||||
# 模块: src/core/, src/gateway/, src/core_service/,
|
||||
# src/data_service/, src/strategy_engine/, src/qmt_adapter/
|
||||
# ------------------------------------------------------------
|
||||
|
||||
# Web 框架
|
||||
fastapi>=0.104.0
|
||||
uvicorn[standard]>=0.24.0
|
||||
|
||||
# 配置管理
|
||||
pydantic>=2.5.0
|
||||
pydantic-settings>=2.1.0
|
||||
pyyaml>=6.0.0
|
||||
|
||||
# 日志
|
||||
python-json-logger>=2.0.0
|
||||
|
||||
# 类型提示
|
||||
typing_extensions>=4.8.0
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# 数据库依赖 (需要 MySQL 的服务)
|
||||
# 模块: src/core_service/, src/data_service/
|
||||
# ------------------------------------------------------------
|
||||
|
||||
sqlalchemy[asyncio]>=2.0.0
|
||||
aiomysql>=0.2.0
|
||||
pymysql>=1.1.0
|
||||
alembic>=1.12.0
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# Redis 依赖 (需要 Redis 的服务)
|
||||
# 模块: src/core/, src/data_service/, src/strategy_engine/,
|
||||
# src/qmt_adapter/
|
||||
# ------------------------------------------------------------
|
||||
|
||||
redis>=5.0.0
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# HTTP 客户端 (服务间通信、健康检查)
|
||||
# 模块: src/gateway/, src/console/
|
||||
# ------------------------------------------------------------
|
||||
|
||||
httpx>=0.25.0
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# PyQt6 桌面控制台 (可选,仅控制台需要)
|
||||
# 模块: src/console/
|
||||
# 安装命令: pip install PyQt6
|
||||
# ------------------------------------------------------------
|
||||
|
||||
PyQt6>=6.4.0
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# 开发工具 (可选,仅开发环境需要)
|
||||
# ------------------------------------------------------------
|
||||
|
||||
pytest>=7.4.0
|
||||
pytest-asyncio>=0.21.0
|
||||
black>=23.0.0
|
||||
ruff>=0.1.0
|
||||
mypy>=1.6.0
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# 模块依赖总结:
|
||||
# ------------------------------------------------------------
|
||||
#
|
||||
# src/core/ -> pydantic, pyyaml, redis, python-json-logger
|
||||
# src/gateway/ -> fastapi, uvicorn, httpx
|
||||
# src/core_service/ -> fastapi, uvicorn, sqlalchemy, aiomysql
|
||||
# src/data_service/ -> fastapi, uvicorn, sqlalchemy, redis
|
||||
# src/strategy_engine/-> fastapi, uvicorn, redis
|
||||
# src/qmt_adapter/ -> fastapi, uvicorn, redis
|
||||
# src/console/ -> PyQt6, httpx, pyyaml
|
||||
#
|
||||
# ------------------------------------------------------------
|
||||
@ -1,15 +0,0 @@
|
||||
# QTrade Python 3.6 依赖
|
||||
# QMT Adapter 专用
|
||||
|
||||
# Redis
|
||||
redis>=3.5.0,<4.0.0
|
||||
|
||||
# 配置
|
||||
pyyaml>=5.4.0
|
||||
|
||||
# 日志
|
||||
python-json-logger>=2.0.0
|
||||
|
||||
# 类型提示 (兼容 Python 3.6)
|
||||
typing_extensions>=3.7.4
|
||||
dataclasses>=0.8
|
||||
62
scripts/drop_qtrade_databases.py
Normal file
62
scripts/drop_qtrade_databases.py
Normal file
@ -0,0 +1,62 @@
|
||||
"""
|
||||
删除所有 qtrade 开头的数据库
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# 添加项目根目录到路径
|
||||
project_root = Path(__file__).parent.parent
|
||||
sys.path.insert(0, str(project_root))
|
||||
|
||||
# 设置环境变量
|
||||
os.environ["CONFIG_FILE"] = "configs/backtest.yaml"
|
||||
|
||||
from src.database_manager import DatabaseManager
|
||||
|
||||
print("=" * 50)
|
||||
print("删除 qtrade 开头的数据库")
|
||||
print("=" * 50)
|
||||
|
||||
# 初始化数据库管理器
|
||||
db_manager = DatabaseManager()
|
||||
|
||||
# 列出所有数据库
|
||||
print("\n查找 qtrade 开头的数据库...")
|
||||
all_databases = db_manager.list_databases()
|
||||
qtrade_databases = [db for db in all_databases if db.lower().startswith("qtrade")]
|
||||
|
||||
if not qtrade_databases:
|
||||
print("✓ 未找到 qtrade 开头的数据库")
|
||||
else:
|
||||
print(f"\n找到 {len(qtrade_databases)} 个数据库:")
|
||||
for db in qtrade_databases:
|
||||
print(f" - {db}")
|
||||
|
||||
# 删除数据库
|
||||
print("\n开始删除...")
|
||||
for db in qtrade_databases:
|
||||
success = db_manager.drop_database(db, confirm=True)
|
||||
if success:
|
||||
print(f"✓ 已删除: {db}")
|
||||
else:
|
||||
print(f"✗ 删除失败: {db}")
|
||||
|
||||
# 验证
|
||||
print("\n验证删除结果...")
|
||||
remaining = db_manager.list_databases()
|
||||
qtrade_remaining = [db for db in remaining if db.lower().startswith("qtrade")]
|
||||
|
||||
if not qtrade_remaining:
|
||||
print("✓ 所有 qtrade 数据库已删除")
|
||||
else:
|
||||
print(f"⚠ 仍有 {len(qtrade_remaining)} 个数据库:")
|
||||
for db in qtrade_remaining:
|
||||
print(f" - {db}")
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("完成!")
|
||||
print("=" * 50)
|
||||
|
||||
db_manager.close()
|
||||
@ -1,109 +0,0 @@
|
||||
"""
|
||||
初始化多环境数据库
|
||||
|
||||
创建三个独立的数据库:
|
||||
- QTrade_RealTrade (实盘)
|
||||
- QTrade_BackTestTrade (回测)
|
||||
- QTrade_SimuTrade (模拟)
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pymysql
|
||||
from pymysql.err import OperationalError
|
||||
|
||||
# 添加项目路径
|
||||
project_root = Path(__file__).parent.parent
|
||||
sys.path.insert(0, str(project_root))
|
||||
|
||||
# pylint: disable=wrong-import-position
|
||||
from src.core.config import settings
|
||||
|
||||
|
||||
def init_databases():
|
||||
"""初始化三个环境的数据库"""
|
||||
|
||||
# 数据库连接配置(不指定具体数据库)
|
||||
db_config = {
|
||||
"host": settings.database._manager.get("database.host", "127.0.0.1"),
|
||||
"port": settings.database._manager.get("database.port", 3306),
|
||||
"user": settings.database._manager.get("database.user", "root"),
|
||||
"password": settings.database._manager.get("database.password", "1234"),
|
||||
"charset": "utf8mb4",
|
||||
}
|
||||
|
||||
databases = ["QTrade_RealTrade", "QTrade_BackTestTrade", "QTrade_SimuTrade"]
|
||||
|
||||
try:
|
||||
# 连接MySQL服务器
|
||||
print(f"连接MySQL服务器: {db_config['host']}:{db_config['port']}")
|
||||
conn = pymysql.connect(**db_config)
|
||||
cursor = conn.cursor()
|
||||
|
||||
print("\n开始创建数据库...\n")
|
||||
|
||||
for db_name in databases:
|
||||
try:
|
||||
# 创建数据库
|
||||
sql = f"""
|
||||
CREATE DATABASE IF NOT EXISTS {db_name}
|
||||
DEFAULT CHARACTER SET utf8mb4
|
||||
COLLATE utf8mb4_unicode_ci
|
||||
"""
|
||||
cursor.execute(sql)
|
||||
print(f"✓ 数据库创建成功: {db_name}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ 创建数据库失败 {db_name}: {e}")
|
||||
|
||||
# 显示创建的数据库
|
||||
print("\n查询已创建的数据库:")
|
||||
cursor.execute("SHOW DATABASES LIKE 'QTrade_%'")
|
||||
results = cursor.fetchall()
|
||||
|
||||
for row in results:
|
||||
print(f" - {row[0]}")
|
||||
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close()
|
||||
|
||||
print("\n✅ 数据库初始化完成")
|
||||
return True
|
||||
|
||||
except OperationalError as e:
|
||||
print(f"\n❌ 连接MySQL失败: {e}")
|
||||
print("\n请确保:")
|
||||
print(" 1. MySQL服务正在运行")
|
||||
print(" 2. 用户名和密码正确")
|
||||
print(" 3. 防火墙允许连接")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n❌ 初始化失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("=" * 60)
|
||||
print("QTrade 多环境数据库初始化")
|
||||
print("=" * 60)
|
||||
print()
|
||||
|
||||
success = init_databases()
|
||||
|
||||
if success:
|
||||
print("\n下一步:")
|
||||
print(" 运行数据库迁移为每个环境创建表结构")
|
||||
print()
|
||||
print(" # 实盘环境")
|
||||
print(" alembic --config configs/production.yaml upgrade head")
|
||||
print()
|
||||
print(" # 回测环境")
|
||||
print(" alembic --config configs/backtest.yaml upgrade head")
|
||||
print()
|
||||
print(" # 模拟环境")
|
||||
print(" alembic --config configs/simulation.yaml upgrade head")
|
||||
|
||||
sys.exit(0 if success else 1)
|
||||
@ -1,14 +0,0 @@
|
||||
-- QTrade 多环境数据库初始化脚本
|
||||
-- 创建三个独立的数据库用于不同环境
|
||||
|
||||
-- 实盘环境数据库
|
||||
CREATE DATABASE IF NOT EXISTS QTrade_RealTrade DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- 回测环境数据库
|
||||
CREATE DATABASE IF NOT EXISTS QTrade_BackTestTrade DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- 模拟环境数据库
|
||||
CREATE DATABASE IF NOT EXISTS QTrade_SimuTrade DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
-- 显示创建的数据库
|
||||
SHOW DATABASES LIKE 'QTrade_%';
|
||||
@ -1,165 +0,0 @@
|
||||
"""
|
||||
QTrade 多环境服务启动脚本
|
||||
|
||||
支持启动三套独立环境:
|
||||
- production: 实盘环境 (端口9000+, DB: QTrade_RealTrade, Redis: real:)
|
||||
- backtest: 回测环境 (端口10000+, DB: QTrade_BackTestTrade, Redis: bt:)
|
||||
- simulation: 模拟环境 (端口11000+, DB: QTrade_SimuTrade, Redis: simu:)
|
||||
|
||||
用法:
|
||||
# 启动实盘环境的数据服务和策略引擎
|
||||
python scripts/start_services.py production data_service strategy_service
|
||||
|
||||
# 启动回测环境的所有服务
|
||||
python scripts/start_services.py backtest data_service strategy_service backtest_service
|
||||
|
||||
# 启动模拟环境
|
||||
python scripts/start_services.py simulation data_service strategy_service trade_service
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# 项目根目录
|
||||
PROJECT_ROOT = Path(__file__).parent.parent
|
||||
|
||||
# 环境配置
|
||||
ENV_CONFIGS = {
|
||||
"production": {
|
||||
"env_file": ".env.production",
|
||||
"config_file": "configs/production.yaml",
|
||||
"description": "实盘环境",
|
||||
},
|
||||
"backtest": {
|
||||
"env_file": ".env.backtest",
|
||||
"config_file": "configs/backtest.yaml",
|
||||
"description": "回测环境",
|
||||
},
|
||||
"simulation": {
|
||||
"env_file": ".env.simulation",
|
||||
"config_file": "configs/simulation.yaml",
|
||||
"description": "模拟环境",
|
||||
},
|
||||
}
|
||||
|
||||
# 服务配置
|
||||
SERVICE_APPS = {
|
||||
"data_service": "src.data_service.app:app",
|
||||
"strategy_service": "src.strategy_service.app:app",
|
||||
"trade_service": "src.trade_service.app:app",
|
||||
"backtest_service": "src.backtest_service.app:app",
|
||||
}
|
||||
|
||||
|
||||
def start_service(service_name: str, env: str, detach: bool = True):
|
||||
"""
|
||||
启动指定环境的服务
|
||||
|
||||
Args:
|
||||
service_name: 服务名称
|
||||
env: 环境名称 (production/backtest/simulation)
|
||||
detach: 是否后台运行
|
||||
"""
|
||||
if env not in ENV_CONFIGS:
|
||||
print(f"❌ 未知环境: {env}")
|
||||
print(f"支持的环境: {', '.join(ENV_CONFIGS.keys())}")
|
||||
sys.exit(1)
|
||||
|
||||
if service_name not in SERVICE_APPS:
|
||||
print(f"❌ 未知服务: {service_name}")
|
||||
print(f"支持的服务: {', '.join(SERVICE_APPS.keys())}")
|
||||
sys.exit(1)
|
||||
|
||||
env_config = ENV_CONFIGS[env]
|
||||
app_path = SERVICE_APPS[service_name]
|
||||
env_file = PROJECT_ROOT / env_config["env_file"]
|
||||
|
||||
if not env_file.exists():
|
||||
print(f"❌ 环境配置文件不存在: {env_file}")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"🚀 启动 {env_config['description']} - {service_name}")
|
||||
|
||||
# 构建命令
|
||||
cmd = [
|
||||
"uvicorn",
|
||||
app_path,
|
||||
"--env-file",
|
||||
str(env_file),
|
||||
"--reload",
|
||||
]
|
||||
|
||||
# 设置环境变量
|
||||
env_vars = os.environ.copy()
|
||||
env_vars["ENV"] = env
|
||||
env_vars["CONFIG_FILE"] = env_config["config_file"]
|
||||
|
||||
if detach:
|
||||
# Windows 后台运行
|
||||
if sys.platform == "win32":
|
||||
# 创建新的控制台窗口
|
||||
subprocess.Popen(
|
||||
cmd,
|
||||
env=env_vars,
|
||||
creationflags=subprocess.CREATE_NEW_CONSOLE,
|
||||
cwd=PROJECT_ROOT,
|
||||
)
|
||||
else:
|
||||
# Linux/Mac 后台运行
|
||||
subprocess.Popen(
|
||||
cmd,
|
||||
env=env_vars,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
cwd=PROJECT_ROOT,
|
||||
)
|
||||
print(f"✓ {service_name} 已在后台启动")
|
||||
else:
|
||||
# 前台运行
|
||||
subprocess.run(cmd, env=env_vars, cwd=PROJECT_ROOT)
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 3:
|
||||
print("用法: python scripts/start_services.py <env> <service1> [service2] ...")
|
||||
print()
|
||||
print("环境:")
|
||||
for env, config in ENV_CONFIGS.items():
|
||||
print(f" {env:12} - {config['description']}")
|
||||
print()
|
||||
print("服务:")
|
||||
for service in SERVICE_APPS.keys():
|
||||
print(f" {service}")
|
||||
print()
|
||||
print("示例:")
|
||||
print(
|
||||
" python scripts/start_services.py production data_service strategy_service"
|
||||
)
|
||||
print(
|
||||
" python scripts/start_services.py backtest data_service strategy_service backtest_service"
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
env = sys.argv[1]
|
||||
services = sys.argv[2:]
|
||||
|
||||
print("=" * 60)
|
||||
print(f"环境: {ENV_CONFIGS[env]['description']}")
|
||||
print(f"服务: {', '.join(services)}")
|
||||
print("=" * 60)
|
||||
print()
|
||||
|
||||
for service in services:
|
||||
start_service(service, env)
|
||||
time.sleep(1) # 间隔启动
|
||||
|
||||
print()
|
||||
print("✅ 所有服务已启动")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1,3 +0,0 @@
|
||||
"""
|
||||
QTrade 源代码包
|
||||
"""
|
||||
@ -1,23 +0,0 @@
|
||||
"""
|
||||
回测模块
|
||||
|
||||
提供简洁的回测引擎API
|
||||
"""
|
||||
|
||||
from .bt_engine import (
|
||||
BacktestEngine,
|
||||
SimpleBacktestConfig,
|
||||
BacktestResult,
|
||||
BacktestStatus,
|
||||
ProgressCallback,
|
||||
quick_backtest,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"BacktestEngine",
|
||||
"SimpleBacktestConfig",
|
||||
"BacktestResult",
|
||||
"BacktestStatus",
|
||||
"ProgressCallback",
|
||||
"quick_backtest",
|
||||
]
|
||||
@ -1,597 +0,0 @@
|
||||
"""
|
||||
回测引擎
|
||||
|
||||
提供简洁的回测接口,封装与backtest_service的交互
|
||||
支持GUI和命令行调用
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional, Callable, Any
|
||||
from enum import Enum
|
||||
|
||||
import httpx
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.config import settings
|
||||
|
||||
logger = get_logger("backtest.engine")
|
||||
|
||||
|
||||
class BacktestStatus(str, Enum):
|
||||
"""回测状态"""
|
||||
|
||||
IDLE = "idle" # 空闲
|
||||
CHECKING = "checking" # 检查服务
|
||||
PREPARING = "preparing" # 准备配置
|
||||
SUBMITTING = "submitting" # 提交任务
|
||||
RUNNING = "running" # 运行中
|
||||
COMPLETED = "completed" # 完成
|
||||
FAILED = "failed" # 失败
|
||||
|
||||
|
||||
class ProgressCallback:
|
||||
"""进度回调接口"""
|
||||
|
||||
def on_status_change(self, status: BacktestStatus, message: str):
|
||||
"""状态变化回调"""
|
||||
pass
|
||||
|
||||
def on_progress_update(self, progress: float, message: str):
|
||||
"""进度更新回调"""
|
||||
pass
|
||||
|
||||
def on_log(self, level: str, message: str):
|
||||
"""日志回调"""
|
||||
pass
|
||||
|
||||
|
||||
class SimpleBacktestConfig(BaseModel):
|
||||
"""简化的回测配置(用户友好)"""
|
||||
|
||||
# 基本信息
|
||||
task_name: str = Field(default="", description="任务名称")
|
||||
description: str = Field(default="", description="任务描述")
|
||||
|
||||
# 股票配置
|
||||
symbols: List[str] = Field(..., description="股票代码列表")
|
||||
start_date: str = Field(..., description="开始日期 YYYY-MM-DD")
|
||||
end_date: str = Field(..., description="结束日期 YYYY-MM-DD")
|
||||
period: str = Field(default="1d", description="K线周期")
|
||||
|
||||
# 账户配置
|
||||
initial_capital: float = Field(default=100000.0, description="初始资金")
|
||||
initial_positions: Dict[str, Dict] = Field(
|
||||
default_factory=dict, description="初始持仓 {symbol: {quantity, avg_cost}}"
|
||||
)
|
||||
|
||||
# 交易设置
|
||||
commission_rate: float = Field(default=0.0003, description="手续费率")
|
||||
min_commission: float = Field(default=5.0, description="最低手续费")
|
||||
stamp_tax: float = Field(default=0.001, description="印花税")
|
||||
slippage: float = Field(default=0.0001, description="滑点")
|
||||
|
||||
# 策略配置
|
||||
strategy_id: str = Field(..., description="策略ID")
|
||||
strategy_name: str = Field(default="", description="策略名称")
|
||||
strategy_params: Dict = Field(default_factory=dict, description="策略参数")
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
|
||||
|
||||
class BacktestResult(BaseModel):
|
||||
"""回测结果"""
|
||||
|
||||
task_id: str
|
||||
task_name: str
|
||||
status: str
|
||||
|
||||
# 收益指标
|
||||
initial_capital: float
|
||||
final_capital: float
|
||||
total_return: float
|
||||
return_pct: float
|
||||
|
||||
# 交易统计
|
||||
total_trades: int
|
||||
win_trades: Optional[int] = None
|
||||
lose_trades: Optional[int] = None
|
||||
|
||||
# 原始数据
|
||||
raw_data: Optional[Dict] = None
|
||||
|
||||
|
||||
class BacktestEngine:
|
||||
"""
|
||||
回测引擎
|
||||
|
||||
使用示例:
|
||||
# 1. 创建引擎
|
||||
engine = BacktestEngine()
|
||||
|
||||
# 2. 准备配置
|
||||
config = SimpleBacktestConfig(
|
||||
task_name="MA策略测试",
|
||||
symbols=["000001.SZ"],
|
||||
start_date="2023-01-01",
|
||||
end_date="2023-12-31",
|
||||
initial_capital=100000,
|
||||
strategy_id="ma_cross",
|
||||
strategy_params={"short_period": 5, "long_period": 10}
|
||||
)
|
||||
|
||||
# 3. 运行回测
|
||||
result = engine.run(config)
|
||||
|
||||
# 4. 查看结果
|
||||
print(f"收益率: {result.return_pct}%")
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
service_url: Optional[str] = None,
|
||||
callback: Optional[ProgressCallback] = None,
|
||||
):
|
||||
"""
|
||||
初始化回测引擎
|
||||
|
||||
Args:
|
||||
service_url: 回测服务地址,默认从配置读取
|
||||
callback: 进度回调
|
||||
"""
|
||||
# 服务地址
|
||||
if service_url:
|
||||
self.service_url = service_url
|
||||
else:
|
||||
# 从配置读取回测服务端口
|
||||
port = settings.environment.port_offset + 50 # backtest_service
|
||||
self.service_url = f"http://127.0.0.1:{port}"
|
||||
|
||||
self.callback = callback or ProgressCallback()
|
||||
|
||||
# 状态
|
||||
self.status = BacktestStatus.IDLE
|
||||
self.current_task_id: Optional[str] = None
|
||||
|
||||
# HTTP客户端
|
||||
self.client = httpx.AsyncClient(timeout=30.0)
|
||||
|
||||
logger.info(f"回测引擎初始化完成,服务地址: {self.service_url}")
|
||||
|
||||
def _log(self, level: str, message: str):
|
||||
"""记录日志并回调"""
|
||||
if level == "INFO":
|
||||
logger.info(message)
|
||||
elif level == "WARNING":
|
||||
logger.warning(message)
|
||||
elif level == "ERROR":
|
||||
logger.error(message)
|
||||
else:
|
||||
logger.debug(message)
|
||||
|
||||
self.callback.on_log(level, message)
|
||||
|
||||
def _update_status(self, status: BacktestStatus, message: str):
|
||||
"""更新状态"""
|
||||
self.status = status
|
||||
self._log("INFO", f"[{status.value}] {message}")
|
||||
self.callback.on_status_change(status, message)
|
||||
|
||||
def _update_progress(self, progress: float, message: str):
|
||||
"""更新进度"""
|
||||
self.callback.on_progress_update(progress, message)
|
||||
|
||||
async def check_service(self) -> bool:
|
||||
"""
|
||||
检查服务是否可用
|
||||
|
||||
Returns:
|
||||
服务是否可用
|
||||
"""
|
||||
self._update_status(BacktestStatus.CHECKING, "检查回测服务...")
|
||||
|
||||
try:
|
||||
response = await self.client.get(f"{self.service_url}/ping")
|
||||
if response.status_code == 200:
|
||||
self._log("INFO", "✓ 回测服务正常运行")
|
||||
return True
|
||||
else:
|
||||
self._log("ERROR", f"✗ 回测服务响应异常: {response.status_code}")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
self._log("ERROR", f"✗ 无法连接回测服务: {e}")
|
||||
self._log("ERROR", f" 请确保回测服务已启动: {self.service_url}")
|
||||
return False
|
||||
|
||||
def _convert_config(self, config: SimpleBacktestConfig) -> Dict:
|
||||
"""
|
||||
将简化配置转换为完整配置
|
||||
|
||||
Args:
|
||||
config: 简化配置
|
||||
|
||||
Returns:
|
||||
完整的BacktestConfig字典
|
||||
"""
|
||||
# 生成任务ID
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
task_id = f"bt_{timestamp}"
|
||||
|
||||
# 构建股票配置
|
||||
symbols = [
|
||||
{
|
||||
"code": symbol,
|
||||
"start_date": config.start_date,
|
||||
"end_date": config.end_date,
|
||||
"period": config.period,
|
||||
}
|
||||
for symbol in config.symbols
|
||||
]
|
||||
|
||||
# 构建账户配置
|
||||
positions = {}
|
||||
for symbol, pos_info in config.initial_positions.items():
|
||||
positions[symbol] = {
|
||||
"quantity": pos_info.get("quantity", 0),
|
||||
"avg_cost": pos_info.get("avg_cost", 0.0),
|
||||
}
|
||||
|
||||
account = {
|
||||
"initial_capital": config.initial_capital,
|
||||
"positions": positions,
|
||||
}
|
||||
|
||||
# 构建交易配置
|
||||
trade = {
|
||||
"commission_rate": config.commission_rate,
|
||||
"min_commission": config.min_commission,
|
||||
"stamp_tax": config.stamp_tax,
|
||||
"slippage": config.slippage,
|
||||
"slippage_type": "percentage",
|
||||
}
|
||||
|
||||
# 构建策略配置
|
||||
strategies = [
|
||||
{
|
||||
"strategy_id": config.strategy_id,
|
||||
"name": config.strategy_name or config.strategy_id,
|
||||
"symbols": config.symbols,
|
||||
"params": config.strategy_params,
|
||||
"capital_allocation": config.initial_capital,
|
||||
}
|
||||
]
|
||||
|
||||
# 完整配置
|
||||
full_config = {
|
||||
"task_id": task_id,
|
||||
"task_name": config.task_name or f"回测_{task_id}",
|
||||
"description": config.description,
|
||||
"symbols": symbols,
|
||||
"account": account,
|
||||
"trade": trade,
|
||||
"strategies": strategies,
|
||||
}
|
||||
|
||||
return full_config
|
||||
|
||||
async def submit_task(self, config: SimpleBacktestConfig) -> str:
|
||||
"""
|
||||
提交回测任务
|
||||
|
||||
Args:
|
||||
config: 回测配置
|
||||
|
||||
Returns:
|
||||
任务ID
|
||||
"""
|
||||
self._update_status(BacktestStatus.PREPARING, "准备回测配置...")
|
||||
|
||||
# 转换配置
|
||||
full_config = self._convert_config(config)
|
||||
task_id = full_config["task_id"]
|
||||
|
||||
self._log("INFO", f"任务ID: {task_id}")
|
||||
self._log("INFO", f"股票: {', '.join(config.symbols)}")
|
||||
self._log("INFO", f"时间: {config.start_date} ~ {config.end_date}")
|
||||
self._log("INFO", f"策略: {config.strategy_id}")
|
||||
self._log("INFO", f"初始资金: {config.initial_capital:,.2f}")
|
||||
|
||||
self._update_status(BacktestStatus.SUBMITTING, "提交回测任务...")
|
||||
|
||||
try:
|
||||
response = await self.client.post(
|
||||
f"{self.service_url}/backtest/tasks", json=full_config
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
result = response.json()
|
||||
self._log("INFO", f"✓ 任务提交成功: {result.get('message')}")
|
||||
self.current_task_id = task_id
|
||||
return task_id
|
||||
else:
|
||||
error_msg = response.json().get("detail", "未知错误")
|
||||
raise Exception(f"提交失败: {error_msg}")
|
||||
|
||||
except Exception as e:
|
||||
self._log("ERROR", f"✗ 提交任务失败: {e}")
|
||||
raise
|
||||
|
||||
async def wait_for_completion(
|
||||
self, task_id: str, poll_interval: float = 2.0, timeout: float = 600.0
|
||||
) -> Dict:
|
||||
"""
|
||||
等待任务完成
|
||||
|
||||
Args:
|
||||
task_id: 任务ID
|
||||
poll_interval: 轮询间隔(秒)
|
||||
timeout: 超时时间(秒)
|
||||
|
||||
Returns:
|
||||
任务进度信息
|
||||
"""
|
||||
self._update_status(BacktestStatus.RUNNING, "回测执行中...")
|
||||
|
||||
start_time = time.time()
|
||||
last_progress = -1
|
||||
|
||||
while True:
|
||||
# 检查超时
|
||||
if time.time() - start_time > timeout:
|
||||
raise TimeoutError(f"回测超时({timeout}秒)")
|
||||
|
||||
# 查询状态
|
||||
try:
|
||||
response = await self.client.get(
|
||||
f"{self.service_url}/backtest/tasks/{task_id}/status"
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
progress_data = response.json()
|
||||
status = progress_data["status"]
|
||||
progress = progress_data["progress"]
|
||||
message = progress_data.get("message", "")
|
||||
|
||||
# 更新进度
|
||||
if progress != last_progress:
|
||||
self._update_progress(progress, message)
|
||||
last_progress = progress
|
||||
|
||||
# 检查是否完成
|
||||
if status == "completed":
|
||||
self._log("INFO", "✓ 回测完成")
|
||||
return progress_data
|
||||
elif status == "failed":
|
||||
raise Exception(f"回测失败: {message}")
|
||||
|
||||
else:
|
||||
self._log("WARNING", f"查询状态失败: {response.status_code}")
|
||||
|
||||
except Exception as e:
|
||||
self._log("WARNING", f"查询进度异常: {e}")
|
||||
|
||||
# 等待下次轮询
|
||||
await asyncio.sleep(poll_interval)
|
||||
|
||||
async def get_result(self, task_id: str) -> BacktestResult:
|
||||
"""
|
||||
获取回测结果
|
||||
|
||||
Args:
|
||||
task_id: 任务ID
|
||||
|
||||
Returns:
|
||||
回测结果
|
||||
"""
|
||||
self._log("INFO", "获取回测结果...")
|
||||
|
||||
try:
|
||||
response = await self.client.get(
|
||||
f"{self.service_url}/backtest/tasks/{task_id}/result"
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
result_data = response.json()
|
||||
|
||||
result = BacktestResult(
|
||||
task_id=result_data.get("task_id", task_id),
|
||||
task_name=result_data.get("task_name", ""),
|
||||
status="completed",
|
||||
initial_capital=result_data.get("initial_capital", 0),
|
||||
final_capital=result_data.get("final_capital", 0),
|
||||
total_return=result_data.get("total_return", 0),
|
||||
return_pct=result_data.get("return_pct", 0),
|
||||
total_trades=result_data.get("total_trades", 0),
|
||||
win_trades=result_data.get("win_trades"),
|
||||
lose_trades=result_data.get("lose_trades"),
|
||||
raw_data=result_data,
|
||||
)
|
||||
|
||||
self._log("INFO", f"✓ 获取结果成功")
|
||||
self._log("INFO", f" 初始资金: {result.initial_capital:,.2f}")
|
||||
self._log("INFO", f" 最终资金: {result.final_capital:,.2f}")
|
||||
self._log("INFO", f" 总收益: {result.total_return:,.2f}")
|
||||
self._log("INFO", f" 收益率: {result.return_pct:.2f}%")
|
||||
self._log("INFO", f" 交易次数: {result.total_trades}")
|
||||
|
||||
return result
|
||||
|
||||
else:
|
||||
error_msg = response.json().get("detail", "未知错误")
|
||||
raise Exception(f"获取结果失败: {error_msg}")
|
||||
|
||||
except Exception as e:
|
||||
self._log("ERROR", f"✗ 获取结果失败: {e}")
|
||||
raise
|
||||
|
||||
async def run_async(
|
||||
self, config: SimpleBacktestConfig, wait: bool = True
|
||||
) -> BacktestResult:
|
||||
"""
|
||||
异步运行回测
|
||||
|
||||
Args:
|
||||
config: 回测配置
|
||||
wait: 是否等待完成
|
||||
|
||||
Returns:
|
||||
回测结果
|
||||
"""
|
||||
try:
|
||||
# 1. 检查服务
|
||||
if not await self.check_service():
|
||||
raise Exception("回测服务不可用")
|
||||
|
||||
# 2. 提交任务
|
||||
task_id = await self.submit_task(config)
|
||||
|
||||
# 3. 等待完成
|
||||
if wait:
|
||||
await self.wait_for_completion(task_id)
|
||||
|
||||
# 4. 获取结果
|
||||
result = await self.get_result(task_id)
|
||||
|
||||
self._update_status(BacktestStatus.COMPLETED, "回测完成")
|
||||
return result
|
||||
else:
|
||||
# 不等待,返回空结果
|
||||
return BacktestResult(
|
||||
task_id=task_id,
|
||||
task_name=config.task_name,
|
||||
status="running",
|
||||
initial_capital=config.initial_capital,
|
||||
final_capital=0,
|
||||
total_return=0,
|
||||
return_pct=0,
|
||||
total_trades=0,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
self._update_status(BacktestStatus.FAILED, f"回测失败: {e}")
|
||||
raise
|
||||
|
||||
def run(self, config: SimpleBacktestConfig, wait: bool = True) -> BacktestResult:
|
||||
"""
|
||||
同步运行回测(推荐用于GUI和命令行)
|
||||
|
||||
Args:
|
||||
config: 回测配置
|
||||
wait: 是否等待完成
|
||||
|
||||
Returns:
|
||||
回测结果
|
||||
"""
|
||||
return asyncio.run(self.run_async(config, wait))
|
||||
|
||||
async def list_tasks(self) -> List[Dict]:
|
||||
"""
|
||||
获取任务列表
|
||||
|
||||
Returns:
|
||||
任务列表
|
||||
"""
|
||||
try:
|
||||
response = await self.client.get(f"{self.service_url}/backtest/tasks")
|
||||
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
self._log("ERROR", f"获取任务列表失败: {response.status_code}")
|
||||
return []
|
||||
|
||||
except Exception as e:
|
||||
self._log("ERROR", f"获取任务列表异常: {e}")
|
||||
return []
|
||||
|
||||
async def get_task_status(self, task_id: str) -> Optional[Dict]:
|
||||
"""
|
||||
获取任务状态
|
||||
|
||||
Args:
|
||||
task_id: 任务ID
|
||||
|
||||
Returns:
|
||||
任务状态
|
||||
"""
|
||||
try:
|
||||
response = await self.client.get(
|
||||
f"{self.service_url}/backtest/tasks/{task_id}/status"
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
self._log("ERROR", f"获取任务状态异常: {e}")
|
||||
return None
|
||||
|
||||
async def close(self):
|
||||
"""关闭引擎"""
|
||||
await self.client.aclose()
|
||||
|
||||
def __del__(self):
|
||||
"""析构函数"""
|
||||
try:
|
||||
if hasattr(self, "client"):
|
||||
asyncio.run(self.client.aclose())
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
# ==================== 便捷函数 ====================
|
||||
|
||||
|
||||
def quick_backtest(
|
||||
symbols: List[str],
|
||||
start_date: str,
|
||||
end_date: str,
|
||||
strategy_id: str,
|
||||
strategy_params: Dict = None,
|
||||
initial_capital: float = 100000.0,
|
||||
**kwargs,
|
||||
) -> BacktestResult:
|
||||
"""
|
||||
快速回测(一行代码运行回测)
|
||||
|
||||
Args:
|
||||
symbols: 股票代码列表
|
||||
start_date: 开始日期
|
||||
end_date: 结束日期
|
||||
strategy_id: 策略ID
|
||||
strategy_params: 策略参数
|
||||
initial_capital: 初始资金
|
||||
**kwargs: 其他配置参数
|
||||
|
||||
Returns:
|
||||
回测结果
|
||||
|
||||
Example:
|
||||
result = quick_backtest(
|
||||
symbols=["000001.SZ"],
|
||||
start_date="2023-01-01",
|
||||
end_date="2023-12-31",
|
||||
strategy_id="ma_cross",
|
||||
strategy_params={"short_period": 5, "long_period": 10}
|
||||
)
|
||||
print(f"收益率: {result.return_pct}%")
|
||||
"""
|
||||
config = SimpleBacktestConfig(
|
||||
symbols=symbols,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
strategy_id=strategy_id,
|
||||
strategy_params=strategy_params or {},
|
||||
initial_capital=initial_capital,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
engine = BacktestEngine()
|
||||
return engine.run(config)
|
||||
@ -1,212 +0,0 @@
|
||||
"""
|
||||
回测引擎入口
|
||||
|
||||
职责:
|
||||
1. 启动必需的服务(数据库服务、回测服务)
|
||||
2. 监控服务健康状态
|
||||
3. 提供回测任务执行入口
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# 添加项目根目录到 Python 路径
|
||||
project_root = Path(__file__).resolve().parent.parent.parent
|
||||
sys.path.insert(0, str(project_root))
|
||||
|
||||
# 设置回测环境
|
||||
os.environ["CONFIG_FILE"] = "configs/backtest.yaml"
|
||||
|
||||
import asyncio # noqa: E402
|
||||
|
||||
import httpx # noqa: E402
|
||||
|
||||
from src.core.config import settings # noqa: E402
|
||||
from src.core.logger import get_logger # noqa: E402
|
||||
from src.core.service_manager import HTTPService, RedisService, service_manager # noqa: E402
|
||||
|
||||
logger = get_logger("backtest_engine")
|
||||
|
||||
# Database Admin Service URL
|
||||
DATABASE_ADMIN_SERVICE_URL = "http://127.0.0.1:8015"
|
||||
|
||||
|
||||
def setup_services():
|
||||
"""配置并注册所有服务"""
|
||||
services = [
|
||||
# Redis 服务
|
||||
RedisService(
|
||||
name="RedisService",
|
||||
host=settings.redis.host,
|
||||
port=settings.redis.port,
|
||||
db=settings.redis.db,
|
||||
),
|
||||
# 数据库管理服务
|
||||
HTTPService(
|
||||
name="DatabaseAdminService",
|
||||
app="src.database_admin_service.app:app",
|
||||
host="127.0.0.1",
|
||||
port=8015,
|
||||
),
|
||||
# 回测服务
|
||||
HTTPService(
|
||||
name="BacktestService",
|
||||
app="src.backtest_service.app:app",
|
||||
host=settings.services.backtest_service.host,
|
||||
port=settings.services.backtest_service.port,
|
||||
env={"CONFIG_FILE": "configs/backtest.yaml"},
|
||||
),
|
||||
]
|
||||
|
||||
for service in services:
|
||||
service_manager.register(service)
|
||||
|
||||
|
||||
async def check_and_init_database():
|
||||
"""检查并初始化数据库和表结构"""
|
||||
logger.info("\n检查数据库和表结构...")
|
||||
logger.info("=" * 70)
|
||||
|
||||
environment = "backtest"
|
||||
|
||||
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||
# 1. 检查数据库是否存在
|
||||
logger.info(f"\n1️⃣ 检查数据库 ({environment})...")
|
||||
try:
|
||||
response = await client.get(
|
||||
f"{DATABASE_SERVICE_URL}/api/databases/{environment}"
|
||||
)
|
||||
if response.status_code == 200:
|
||||
db_info = response.json()
|
||||
logger.info(
|
||||
f" ✓ 数据库已存在: {db_info['name']} "
|
||||
f"({db_info['table_count']} 表, {db_info['size_mb']:.2f} MB)"
|
||||
)
|
||||
else:
|
||||
# 数据库不存在,创建它
|
||||
logger.info(f" ⚠️ 数据库不存在,正在创建...")
|
||||
response = await client.post(
|
||||
f"{DATABASE_SERVICE_URL}/api/databases",
|
||||
json={"environment": environment},
|
||||
)
|
||||
if response.status_code == 200:
|
||||
result = response.json()
|
||||
logger.info(f" ✓ {result['message']}")
|
||||
else:
|
||||
error = response.json().get("detail", "未知错误")
|
||||
logger.error(f" ✗ 创建数据库失败: {error}")
|
||||
return False
|
||||
|
||||
except httpx.ConnectError:
|
||||
logger.error(f" ✗ 无法连接到 DatabaseService,请确保服务已启动")
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.error(f" ✗ 检查数据库时出错: {e}")
|
||||
return False
|
||||
|
||||
# 2. 检查表结构
|
||||
logger.info(f"\n2️⃣ 检查表结构...")
|
||||
try:
|
||||
response = await client.get(
|
||||
f"{DATABASE_SERVICE_URL}/api/tables/{environment}"
|
||||
)
|
||||
if response.status_code == 200:
|
||||
table_info = response.json()
|
||||
table_count = table_info["total"]
|
||||
|
||||
if table_count == 0:
|
||||
# 表不存在,创建表结构
|
||||
logger.info(f" ⚠️ 表结构不存在,正在创建...")
|
||||
response = await client.post(
|
||||
f"{DATABASE_SERVICE_URL}/api/tables",
|
||||
json={"environment": environment},
|
||||
)
|
||||
if response.status_code == 200:
|
||||
result = response.json()
|
||||
logger.info(f" ✓ {result['message']}")
|
||||
# 显示创建的表(前5个)
|
||||
tables = result.get("tables", [])[:5]
|
||||
for table_name in tables:
|
||||
logger.info(f" • {table_name}")
|
||||
if result.get("count", 0) > 5:
|
||||
logger.info(f" ... 还有 {result['count'] - 5} 个表")
|
||||
else:
|
||||
error = response.json().get("detail", "未知错误")
|
||||
logger.error(f" ✗ 创建表失败: {error}")
|
||||
return False
|
||||
else:
|
||||
logger.info(f" ✓ 表结构完整 ({table_count} 个表)")
|
||||
# 显示一些表名(前5个)
|
||||
tables = table_info["tables"][:5]
|
||||
for table in tables:
|
||||
logger.info(
|
||||
f" • {table['name']} "
|
||||
f"({table['rows']} 行, {table['size_mb']:.2f} MB)"
|
||||
)
|
||||
if table_count > 5:
|
||||
logger.info(f" ... 还有 {table_count - 5} 个表")
|
||||
|
||||
else:
|
||||
logger.error(f" ✗ 获取表列表失败")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f" ✗ 检查表结构时出错: {e}")
|
||||
return False
|
||||
|
||||
logger.info("\n" + "=" * 70)
|
||||
logger.info("✅ 数据库和表结构检查完成")
|
||||
logger.info("=" * 70)
|
||||
return True
|
||||
|
||||
|
||||
async def start_engine():
|
||||
"""启动回测引擎"""
|
||||
logger.info("=" * 70)
|
||||
logger.info("回测引擎启动")
|
||||
logger.info("=" * 70)
|
||||
|
||||
# 注册服务
|
||||
setup_services()
|
||||
|
||||
# 启动所有服务
|
||||
logger.info("\n正在启动回测引擎服务...\n")
|
||||
await service_manager.start_all()
|
||||
|
||||
# 检查并初始化数据库
|
||||
if not await check_and_init_database():
|
||||
logger.error("\n❌ 数据库初始化失败,回测引擎启动中止")
|
||||
await service_manager.stop_all()
|
||||
return False
|
||||
|
||||
logger.info("\n回测引擎已就绪!")
|
||||
logger.info("可以开始执行回测任务")
|
||||
logger.info("按 Ctrl+C 停止所有服务\n")
|
||||
return True
|
||||
|
||||
|
||||
async def main():
|
||||
"""主函数"""
|
||||
success = await start_engine()
|
||||
|
||||
if not success:
|
||||
logger.error("启动失败")
|
||||
return
|
||||
|
||||
# 保持运行
|
||||
try:
|
||||
while True:
|
||||
await asyncio.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
logger.info("\n收到停止信号,正在关闭所有服务...")
|
||||
await service_manager.stop_all()
|
||||
logger.info("所有服务已停止")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
except KeyboardInterrupt:
|
||||
# 优雅退出,不显示堆栈
|
||||
pass
|
||||
@ -1,7 +0,0 @@
|
||||
"""
|
||||
回测服务
|
||||
|
||||
提供策略回测能力,支持历史数据回放和模拟交易
|
||||
"""
|
||||
|
||||
__version__ = "0.2.0"
|
||||
@ -1,76 +0,0 @@
|
||||
"""
|
||||
回测服务 FastAPI 应用
|
||||
|
||||
提供回测任务的创建、查询、执行等功能
|
||||
"""
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from src.core.config import settings
|
||||
from src.core.logger import get_logger
|
||||
|
||||
from .routes import tasks
|
||||
|
||||
logger = get_logger("backtest_service")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""应用生命周期管理"""
|
||||
logger.info("回测服务启动...")
|
||||
logger.info(f"环境: {settings.environment.env}")
|
||||
logger.info(f"数据库: {settings.environment.db_name}")
|
||||
logger.info(f"Redis前缀: {settings.environment.redis_prefix}")
|
||||
|
||||
# 注册内置策略
|
||||
from src.core.strategy import strategy_registry
|
||||
from src.core.strategy.strategies import MACrossStrategy
|
||||
|
||||
strategy_registry.register(MACrossStrategy)
|
||||
logger.info("已注册内置策略")
|
||||
|
||||
yield
|
||||
|
||||
logger.info("回测服务关闭...")
|
||||
|
||||
|
||||
# 创建应用
|
||||
app = FastAPI(
|
||||
title="QTrade 回测服务",
|
||||
description="策略回测和模拟交易服务",
|
||||
version="0.2.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
# CORS
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# 注册路由
|
||||
app.include_router(tasks.router, prefix="/backtest", tags=["回测任务"])
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
"""根路径"""
|
||||
return {
|
||||
"service": "QTrade 回测服务",
|
||||
"version": "0.2.0",
|
||||
"environment": settings.environment.env,
|
||||
"status": "running",
|
||||
}
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
@app.get("/ping")
|
||||
async def health_check():
|
||||
"""健康检查"""
|
||||
return {"status": "healthy", "service": "backtest_service"}
|
||||
@ -1,5 +0,0 @@
|
||||
"""路由模块"""
|
||||
|
||||
from . import tasks
|
||||
|
||||
__all__ = ["tasks"]
|
||||
@ -1,114 +0,0 @@
|
||||
"""
|
||||
回测任务API路由
|
||||
"""
|
||||
|
||||
from typing import List
|
||||
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks
|
||||
|
||||
from ..schemas import BacktestConfig, BacktestResult, TaskProgress, TaskSummary
|
||||
from ..services import task_manager, execute_backtest
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/tasks", response_model=dict)
|
||||
async def create_task(config: BacktestConfig, background_tasks: BackgroundTasks):
|
||||
"""
|
||||
创建回测任务
|
||||
|
||||
Args:
|
||||
config: 回测配置
|
||||
background_tasks: 后台任务
|
||||
|
||||
Returns:
|
||||
任务ID
|
||||
"""
|
||||
try:
|
||||
task_id = task_manager.create_task(config)
|
||||
|
||||
# 在后台执行回测
|
||||
background_tasks.add_task(execute_backtest, task_id, config)
|
||||
|
||||
return {"task_id": task_id, "message": "任务创建成功,开始执行"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"创建任务失败: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/tasks/{task_id}/status", response_model=TaskProgress)
|
||||
async def get_task_status(task_id: str):
|
||||
"""
|
||||
查询任务状态和进度
|
||||
|
||||
Args:
|
||||
task_id: 任务ID
|
||||
|
||||
Returns:
|
||||
任务进度信息
|
||||
"""
|
||||
progress = task_manager.get_progress(task_id)
|
||||
if not progress:
|
||||
raise HTTPException(status_code=404, detail=f"任务不存在: {task_id}")
|
||||
|
||||
return progress
|
||||
|
||||
|
||||
@router.get("/tasks/{task_id}/result", response_model=BacktestResult)
|
||||
async def get_task_result(task_id: str):
|
||||
"""
|
||||
获取回测结果
|
||||
|
||||
Args:
|
||||
task_id: 任务ID
|
||||
|
||||
Returns:
|
||||
回测结果
|
||||
"""
|
||||
import json
|
||||
|
||||
# 检查任务是否存在
|
||||
progress = task_manager.get_progress(task_id)
|
||||
if not progress:
|
||||
raise HTTPException(status_code=404, detail=f"任务不存在: {task_id}")
|
||||
|
||||
# 检查任务是否完成
|
||||
if progress.status != "completed":
|
||||
raise HTTPException(
|
||||
status_code=400, detail=f"任务未完成,当前状态: {progress.status}"
|
||||
)
|
||||
|
||||
# 读取结果文件
|
||||
task_dir = task_manager.get_task_dir(task_id)
|
||||
result_file = task_dir / "summary.json"
|
||||
|
||||
if not result_file.exists():
|
||||
raise HTTPException(status_code=404, detail="结果文件不存在")
|
||||
|
||||
with open(result_file, "r", encoding="utf-8") as f:
|
||||
result_data = json.load(f)
|
||||
|
||||
return BacktestResult(**result_data)
|
||||
|
||||
|
||||
@router.get("/tasks", response_model=List[TaskSummary])
|
||||
async def list_tasks():
|
||||
"""
|
||||
获取任务列表
|
||||
|
||||
Returns:
|
||||
任务摘要列表
|
||||
"""
|
||||
return task_manager.list_tasks()
|
||||
|
||||
|
||||
@router.delete("/tasks/{task_id}")
|
||||
async def delete_task(task_id: str):
|
||||
"""
|
||||
删除任务(暂未实现)
|
||||
|
||||
Args:
|
||||
task_id: 任务ID
|
||||
"""
|
||||
raise HTTPException(status_code=501, detail="功能暂未实现")
|
||||
@ -1,127 +0,0 @@
|
||||
"""
|
||||
回测配置数据模型
|
||||
|
||||
定义回测任务的配置结构(Pydantic模型,用于API验证和配置管理)
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class TaskStatus(str, Enum):
|
||||
"""任务状态"""
|
||||
|
||||
PENDING = "pending" # 等待中
|
||||
PREPARING = "preparing" # 准备中(检查数据、启动服务)
|
||||
RUNNING = "running" # 运行中
|
||||
SAVING = "saving" # 保存结果中
|
||||
COMPLETED = "completed" # 已完成
|
||||
FAILED = "failed" # 失败
|
||||
CANCELLED = "cancelled" # 已取消
|
||||
|
||||
|
||||
class SymbolConfig(BaseModel):
|
||||
"""股票配置"""
|
||||
|
||||
code: str = Field(..., description="股票代码")
|
||||
start_date: str = Field(..., description="开始日期 YYYY-MM-DD")
|
||||
end_date: str = Field(..., description="结束日期 YYYY-MM-DD")
|
||||
period: str = Field(default="1d", description="K线周期")
|
||||
|
||||
|
||||
class PositionInfo(BaseModel):
|
||||
"""持仓信息"""
|
||||
|
||||
quantity: int = Field(..., description="持仓数量")
|
||||
avg_cost: float = Field(..., description="平均成本")
|
||||
|
||||
|
||||
class AccountConfig(BaseModel):
|
||||
"""账户配置"""
|
||||
|
||||
initial_capital: float = Field(gt=0, description="初始资金")
|
||||
positions: Dict[str, PositionInfo] = Field(
|
||||
default_factory=dict, description="初始持仓"
|
||||
)
|
||||
|
||||
|
||||
class TradeConfig(BaseModel):
|
||||
"""交易设置"""
|
||||
|
||||
commission_rate: float = Field(default=0.0003, description="手续费率(默认万三)")
|
||||
min_commission: float = Field(default=5.0, description="最低手续费")
|
||||
stamp_tax: float = Field(default=0.001, description="印花税(卖出时收取)")
|
||||
slippage: float = Field(default=0.0001, description="滑点")
|
||||
slippage_type: str = Field(
|
||||
default="percentage", description="滑点类型:percentage/fixed"
|
||||
)
|
||||
|
||||
|
||||
class StrategyConfig(BaseModel):
|
||||
"""策略配置"""
|
||||
|
||||
strategy_id: str = Field(..., description="策略ID")
|
||||
name: str = Field(..., description="策略名称")
|
||||
symbols: List[str] = Field(..., description="应用的股票代码列表")
|
||||
params: Dict = Field(default_factory=dict, description="策略参数")
|
||||
capital_allocation: float = Field(gt=0, description="分配资金")
|
||||
|
||||
|
||||
class BacktestConfig(BaseModel):
|
||||
"""回测配置"""
|
||||
|
||||
task_id: str = Field(..., description="任务ID")
|
||||
task_name: str = Field(default="", description="任务名称")
|
||||
description: str = Field(default="", description="任务描述")
|
||||
|
||||
# 市场配置
|
||||
symbols: List[SymbolConfig] = Field(..., description="股票列表")
|
||||
|
||||
# 账户配置
|
||||
account: AccountConfig = Field(..., description="账户配置")
|
||||
|
||||
# 交易设置
|
||||
trade: TradeConfig = Field(default_factory=TradeConfig, description="交易设置")
|
||||
|
||||
# 策略配置
|
||||
strategies: List[StrategyConfig] = Field(..., description="策略列表")
|
||||
|
||||
# 元数据
|
||||
created_at: datetime = Field(default_factory=datetime.now, description="创建时间")
|
||||
|
||||
|
||||
class TaskProgress(BaseModel):
|
||||
"""任务进度"""
|
||||
|
||||
task_id: str
|
||||
status: TaskStatus
|
||||
progress: float = Field(ge=0, le=100, description="进度百分比")
|
||||
message: str = Field(default="", description="状态消息")
|
||||
stage: str = Field(default="", description="当前阶段")
|
||||
|
||||
|
||||
class TaskSummary(BaseModel):
|
||||
"""任务摘要(列表展示)"""
|
||||
|
||||
task_id: str
|
||||
task_name: str
|
||||
status: TaskStatus
|
||||
progress: float
|
||||
created_at: datetime
|
||||
completed_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class BacktestResult(BaseModel):
|
||||
"""回测结果"""
|
||||
|
||||
task_id: str
|
||||
initial_capital: float
|
||||
final_capital: float
|
||||
total_return: float
|
||||
return_pct: float
|
||||
total_trades: int
|
||||
win_trades: Optional[int] = None
|
||||
lose_trades: Optional[int] = None
|
||||
@ -1,15 +0,0 @@
|
||||
"""服务模块"""
|
||||
|
||||
from .task_manager import task_manager
|
||||
from .data_player import DataPlayer
|
||||
from .trade_simulator import TradeSimulator
|
||||
from .strategy_manager import BacktestStrategyManager
|
||||
from .backtest_executor import execute_backtest
|
||||
|
||||
__all__ = [
|
||||
"task_manager",
|
||||
"DataPlayer",
|
||||
"TradeSimulator",
|
||||
"BacktestStrategyManager",
|
||||
"execute_backtest",
|
||||
]
|
||||
@ -1,259 +0,0 @@
|
||||
"""
|
||||
回测执行器
|
||||
|
||||
负责整个回测流程的编排和执行
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import datetime
|
||||
from typing import Optional, List, Tuple
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from ..schemas import BacktestConfig, TaskStatus, SymbolConfig
|
||||
from .task_manager import task_manager
|
||||
from .data_player import DataPlayer
|
||||
from .trade_simulator import TradeSimulator
|
||||
from .strategy_manager import BacktestStrategyManager
|
||||
|
||||
logger = get_logger("backtest.executor")
|
||||
|
||||
|
||||
class BacktestExecutor:
|
||||
"""
|
||||
回测执行器
|
||||
|
||||
编排整个回测流程:
|
||||
1. 初始化数据回放器
|
||||
2. 初始化模拟撮合器
|
||||
3. 启动策略实例
|
||||
4. 开始数据回放
|
||||
5. 等待回放完成
|
||||
6. 计算和保存结果
|
||||
"""
|
||||
|
||||
def __init__(self, task_id: str, config: BacktestConfig):
|
||||
"""
|
||||
初始化回测执行器
|
||||
|
||||
Args:
|
||||
task_id: 任务ID
|
||||
config: 回测配置
|
||||
"""
|
||||
self.task_id = task_id
|
||||
self.config = config
|
||||
|
||||
# 生成频道名
|
||||
self.kline_channel_prefix = f"bt:{task_id}:kline"
|
||||
self.signal_channel = f"bt:{task_id}:signal"
|
||||
|
||||
# 初始化组件
|
||||
self.data_players: List[Tuple[DataPlayer, SymbolConfig]] = []
|
||||
self.trade_simulator: Optional[TradeSimulator] = None
|
||||
self.strategy_managers: List[BacktestStrategyManager] = []
|
||||
|
||||
def progress_callback(self, processed: int, total: int, message: str):
|
||||
"""
|
||||
进度回调
|
||||
|
||||
Args:
|
||||
processed: 已处理数量
|
||||
total: 总数量
|
||||
message: 消息
|
||||
"""
|
||||
progress = int((processed / total) * 100)
|
||||
task_manager.update_progress(
|
||||
task_id=self.task_id,
|
||||
progress=progress,
|
||||
message=message,
|
||||
status=TaskStatus.RUNNING,
|
||||
stage="data_replay",
|
||||
)
|
||||
|
||||
async def run(self):
|
||||
"""执行回测"""
|
||||
try:
|
||||
logger.info(f"开始执行回测任务: {self.task_id}")
|
||||
|
||||
# 1. 初始化模拟撮合器
|
||||
task_manager.update_progress(
|
||||
task_id=self.task_id,
|
||||
progress=5,
|
||||
message="初始化模拟撮合器...",
|
||||
status=TaskStatus.RUNNING,
|
||||
stage="init",
|
||||
)
|
||||
|
||||
self.trade_simulator = TradeSimulator(
|
||||
signal_channel=self.signal_channel,
|
||||
account_config=self.config.account,
|
||||
trade_config=self.config.trade,
|
||||
)
|
||||
|
||||
# 2. 为每个策略-股票组合创建策略管理器
|
||||
task_manager.update_progress(
|
||||
task_id=self.task_id,
|
||||
progress=10,
|
||||
message="初始化策略管理器...",
|
||||
status=TaskStatus.RUNNING,
|
||||
stage="init",
|
||||
)
|
||||
|
||||
for strategy_config in self.config.strategies:
|
||||
for symbol in strategy_config.symbols:
|
||||
strategy_manager = BacktestStrategyManager(
|
||||
task_id=self.task_id,
|
||||
strategy_config=strategy_config,
|
||||
account_config=self.config.account,
|
||||
symbol=symbol,
|
||||
)
|
||||
self.strategy_managers.append(strategy_manager)
|
||||
logger.info(f"创建策略管理器: {strategy_config.name} - {symbol}")
|
||||
|
||||
# 3. 为每个股票创建数据回放器
|
||||
task_manager.update_progress(
|
||||
task_id=self.task_id,
|
||||
progress=15,
|
||||
message="初始化数据回放器...",
|
||||
status=TaskStatus.RUNNING,
|
||||
stage="init",
|
||||
)
|
||||
|
||||
symbols_dict = {} # symbol -> SymbolConfig
|
||||
for symbol_config in self.config.symbols:
|
||||
symbols_dict[symbol_config.code] = symbol_config
|
||||
|
||||
# 收集所有需要回放的股票(去重)
|
||||
all_symbols = set()
|
||||
for strategy_config in self.config.strategies:
|
||||
all_symbols.update(strategy_config.symbols)
|
||||
|
||||
for symbol in all_symbols:
|
||||
symbol_config = symbols_dict.get(symbol)
|
||||
if not symbol_config:
|
||||
logger.warning(f"股票配置不存在: {symbol},跳过")
|
||||
continue
|
||||
|
||||
data_player = DataPlayer(
|
||||
redis_channel=f"{self.kline_channel_prefix}:{symbol}"
|
||||
)
|
||||
self.data_players.append((data_player, symbol_config))
|
||||
logger.info(f"创建数据回放器: {symbol}")
|
||||
|
||||
# 4. 并发启动所有组件
|
||||
task_manager.update_progress(
|
||||
task_id=self.task_id,
|
||||
progress=20,
|
||||
message="启动回测组件...",
|
||||
status=TaskStatus.RUNNING,
|
||||
stage="running",
|
||||
)
|
||||
|
||||
tasks = []
|
||||
|
||||
# 启动模拟撮合器
|
||||
simulator_task = asyncio.create_task(self.trade_simulator.run())
|
||||
tasks.append(simulator_task)
|
||||
|
||||
# 启动所有策略管理器
|
||||
for strategy_manager in self.strategy_managers:
|
||||
strategy_task = asyncio.create_task(strategy_manager.run())
|
||||
tasks.append(strategy_task)
|
||||
|
||||
# 启动所有数据回放器
|
||||
for data_player, symbol_config in self.data_players:
|
||||
symbols_config = [
|
||||
{
|
||||
"code": symbol_config.code,
|
||||
"start_date": symbol_config.start_date,
|
||||
"end_date": symbol_config.end_date,
|
||||
"period": symbol_config.period,
|
||||
}
|
||||
]
|
||||
replay_task = asyncio.create_task(
|
||||
data_player.replay(
|
||||
symbols_config=symbols_config,
|
||||
progress_callback=self.progress_callback,
|
||||
)
|
||||
)
|
||||
tasks.append(replay_task)
|
||||
|
||||
# 等待所有数据回放完成
|
||||
logger.info(f"等待 {len(self.data_players)} 个数据回放任务完成...")
|
||||
# 只等待data player任务(前len(self.data_players)个)
|
||||
replay_tasks = tasks[-(len(self.data_players)) :]
|
||||
await asyncio.gather(*replay_tasks)
|
||||
|
||||
# 5. 等待一段时间让信号处理完成
|
||||
task_manager.update_progress(
|
||||
task_id=self.task_id,
|
||||
progress=95,
|
||||
message="等待信号处理完成...",
|
||||
status=TaskStatus.RUNNING,
|
||||
stage="finish",
|
||||
)
|
||||
|
||||
await asyncio.sleep(1)
|
||||
|
||||
# 停止所有策略和撮合器
|
||||
for strategy_manager in self.strategy_managers:
|
||||
await strategy_manager.stop()
|
||||
|
||||
# 取消所有后台任务
|
||||
for task in tasks:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
|
||||
# 6. 获取账户摘要
|
||||
account_summary = self.trade_simulator.get_account_summary()
|
||||
|
||||
# 7. 保存结果
|
||||
task_manager.update_progress(
|
||||
task_id=self.task_id,
|
||||
progress=100,
|
||||
message="回测完成",
|
||||
status=TaskStatus.COMPLETED,
|
||||
stage="finish",
|
||||
)
|
||||
|
||||
# 保存结果到文件
|
||||
result = {
|
||||
"task_id": self.task_id,
|
||||
"config": self.config.model_dump(),
|
||||
"account_summary": account_summary,
|
||||
"trades": [trade.to_dict() for trade in self.trade_simulator.trades],
|
||||
"completed_at": datetime.now().isoformat(),
|
||||
}
|
||||
|
||||
result_file = task_manager.get_task_dir(self.task_id) / "result.json"
|
||||
with open(result_file, "w", encoding="utf-8") as f:
|
||||
json.dump(result, f, ensure_ascii=False, indent=2)
|
||||
|
||||
logger.info(f"✓ 回测任务完成: {self.task_id}")
|
||||
logger.info(
|
||||
f" 总资产: {account_summary['total_assets']:.2f}, "
|
||||
f"收益率: {account_summary['profit_rate']:.2f}%"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"回测执行失败: {e}", exc_info=True)
|
||||
|
||||
task_manager.update_progress(
|
||||
task_id=self.task_id,
|
||||
progress=0,
|
||||
message=f"回测失败: {str(e)}",
|
||||
status=TaskStatus.FAILED,
|
||||
stage="error",
|
||||
)
|
||||
|
||||
|
||||
async def execute_backtest(task_id: str, config: BacktestConfig):
|
||||
"""
|
||||
执行回测任务
|
||||
|
||||
Args:
|
||||
task_id: 任务ID
|
||||
config: 回测配置
|
||||
"""
|
||||
executor = BacktestExecutor(task_id, config)
|
||||
await executor.run()
|
||||
@ -1,197 +0,0 @@
|
||||
"""
|
||||
数据回放器
|
||||
|
||||
负责从数据库加载历史K线数据,并按时间顺序推送到Redis频道
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from typing import List
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from src.core.database import db
|
||||
from src.core.logger import get_logger
|
||||
from src.core.models import get_kline_model
|
||||
from src.core.redis_client import redis_client
|
||||
|
||||
logger = get_logger("backtest.data_player")
|
||||
|
||||
|
||||
class KlineData:
|
||||
"""K线数据结构"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
symbol: str,
|
||||
period: str,
|
||||
timestamp: datetime,
|
||||
open: float,
|
||||
high: float,
|
||||
low: float,
|
||||
close: float,
|
||||
volume: float,
|
||||
):
|
||||
self.symbol = symbol
|
||||
self.period = period
|
||||
self.timestamp = timestamp
|
||||
self.open = open
|
||||
self.high = high
|
||||
self.low = low
|
||||
self.close = close
|
||||
self.volume = volume
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""转换为字典"""
|
||||
return {
|
||||
"symbol": self.symbol,
|
||||
"period": self.period,
|
||||
"timestamp": self.timestamp.isoformat(),
|
||||
"open": self.open,
|
||||
"high": self.high,
|
||||
"low": self.low,
|
||||
"close": self.close,
|
||||
"volume": self.volume,
|
||||
}
|
||||
|
||||
|
||||
class DataPlayer:
|
||||
"""
|
||||
数据回放器
|
||||
|
||||
从数据库加载历史K线数据,按时间顺序推送到Redis
|
||||
"""
|
||||
|
||||
def __init__(self, redis_channel: str):
|
||||
"""
|
||||
初始化数据回放器
|
||||
|
||||
Args:
|
||||
redis_channel: Redis频道名
|
||||
"""
|
||||
self.redis_channel = redis_channel
|
||||
self.total_bars = 0
|
||||
self.processed_bars = 0
|
||||
|
||||
async def load_kline_data(
|
||||
self, symbol: str, start_date: str, end_date: str, period: str
|
||||
) -> List[KlineData]:
|
||||
"""
|
||||
从数据库加载K线数据
|
||||
|
||||
Args:
|
||||
symbol: 股票代码
|
||||
start_date: 开始日期
|
||||
end_date: 结束日期
|
||||
period: K线周期
|
||||
|
||||
Returns:
|
||||
K线数据列表
|
||||
"""
|
||||
logger.info(f"加载 {symbol} {period} 数据: {start_date} ~ {end_date}")
|
||||
|
||||
# 获取对应周期的模型
|
||||
KlineModel = get_kline_model(period)
|
||||
|
||||
# 查询数据
|
||||
async with db.session() as session:
|
||||
stmt = (
|
||||
select(KlineModel)
|
||||
.where(KlineModel.symbol == symbol)
|
||||
.where(KlineModel.time >= start_date)
|
||||
.where(KlineModel.time <= end_date)
|
||||
.order_by(KlineModel.time.asc())
|
||||
)
|
||||
|
||||
result = await session.execute(stmt)
|
||||
rows = result.scalars().all()
|
||||
|
||||
# 转换为KlineData对象
|
||||
kline_list = []
|
||||
for row in rows:
|
||||
kline_list.append(
|
||||
KlineData(
|
||||
symbol=row.symbol,
|
||||
period=period,
|
||||
timestamp=row.time,
|
||||
open=float(row.open),
|
||||
high=float(row.high),
|
||||
low=float(row.low),
|
||||
close=float(row.close),
|
||||
volume=row.volume,
|
||||
)
|
||||
)
|
||||
|
||||
logger.info(f"加载了 {len(kline_list)} 条K线数据")
|
||||
return kline_list
|
||||
|
||||
async def replay(
|
||||
self,
|
||||
symbols_config: List[dict],
|
||||
progress_callback=None,
|
||||
):
|
||||
"""
|
||||
回放数据
|
||||
|
||||
Args:
|
||||
symbols_config: 股票配置列表 [{"code": "000001.SZ", "start_date": ..., "end_date": ..., "period": "1d"}]
|
||||
progress_callback: 进度回调函数 callback(processed, total, message)
|
||||
"""
|
||||
logger.info("开始数据回放...")
|
||||
|
||||
# 1. 加载所有股票的数据
|
||||
all_bars = []
|
||||
for config in symbols_config:
|
||||
bars = await self.load_kline_data(
|
||||
symbol=config["code"],
|
||||
start_date=config["start_date"],
|
||||
end_date=config["end_date"],
|
||||
period=config["period"],
|
||||
)
|
||||
all_bars.extend(bars)
|
||||
|
||||
if not all_bars:
|
||||
logger.warning("没有数据可回放")
|
||||
return
|
||||
|
||||
# 2. 按时间排序(多股票混合)
|
||||
all_bars.sort(key=lambda x: x.timestamp)
|
||||
self.total_bars = len(all_bars)
|
||||
self.processed_bars = 0
|
||||
|
||||
logger.info(f"总共 {self.total_bars} 条K线数据待回放")
|
||||
|
||||
# 3. 连接Redis
|
||||
await redis_client.connect()
|
||||
|
||||
# 4. 逐条推送
|
||||
batch_size = 100 # 每100条更新一次进度
|
||||
|
||||
for bar in all_bars:
|
||||
# 推送K线到Redis
|
||||
await redis_client.publish(self.redis_channel, json.dumps(bar.to_dict()))
|
||||
|
||||
self.processed_bars += 1
|
||||
|
||||
# 更新进度
|
||||
if (
|
||||
self.processed_bars % batch_size == 0
|
||||
or self.processed_bars == self.total_bars
|
||||
):
|
||||
progress = (self.processed_bars / self.total_bars) * 100
|
||||
|
||||
if progress_callback:
|
||||
progress_callback(
|
||||
self.processed_bars,
|
||||
self.total_bars,
|
||||
f"回放中: {self.processed_bars}/{self.total_bars}",
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
f"回放进度: {progress:.1f}% ({self.processed_bars}/{self.total_bars})"
|
||||
)
|
||||
|
||||
# 可以在这里添加延时,模拟真实回放速度
|
||||
# await asyncio.sleep(0.001)
|
||||
|
||||
logger.info("✓ 数据回放完成")
|
||||
@ -1,164 +0,0 @@
|
||||
"""
|
||||
回测策略管理器
|
||||
|
||||
负责在回测环境中运行策略
|
||||
"""
|
||||
|
||||
import json
|
||||
from typing import Optional
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.redis_client import redis_client
|
||||
from src.core.strategy import BaseStrategy, StrategyContext, strategy_registry
|
||||
from ..schemas import StrategyConfig, AccountConfig
|
||||
|
||||
logger = get_logger("backtest.strategy_manager")
|
||||
|
||||
|
||||
class BacktestStrategyManager:
|
||||
"""
|
||||
回测策略管理器
|
||||
|
||||
负责:
|
||||
1. 创建策略实例
|
||||
2. 订阅K线频道
|
||||
3. 驱动策略执行
|
||||
4. 发布交易信号
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
task_id: str,
|
||||
strategy_config: StrategyConfig,
|
||||
account_config: AccountConfig,
|
||||
symbol: str,
|
||||
):
|
||||
"""
|
||||
初始化策略管理器
|
||||
|
||||
Args:
|
||||
task_id: 回测任务ID
|
||||
strategy_config: 策略配置
|
||||
account_config: 账户配置
|
||||
symbol: 股票代码(针对单个股票的策略实例)
|
||||
"""
|
||||
self.task_id = task_id
|
||||
self.strategy_config = strategy_config
|
||||
self.account_config = account_config
|
||||
self.symbol = symbol
|
||||
|
||||
# Redis频道
|
||||
self.kline_channel = f"bt:{task_id}:kline:{symbol}"
|
||||
self.signal_channel = f"bt:{task_id}:signal"
|
||||
|
||||
# 策略实例
|
||||
self.strategy: Optional[BaseStrategy] = None
|
||||
self._running = False
|
||||
|
||||
def _create_strategy_instance(self) -> BaseStrategy:
|
||||
"""创建策略实例"""
|
||||
# 从注册中心获取策略类
|
||||
strategy_class = strategy_registry.get_strategy_class(
|
||||
self.strategy_config.strategy_id
|
||||
)
|
||||
|
||||
if not strategy_class:
|
||||
raise ValueError(
|
||||
f"策略不存在: {self.strategy_config.strategy_id},请先注册策略"
|
||||
)
|
||||
|
||||
# 创建上下文
|
||||
context = StrategyContext(
|
||||
symbol=self.symbol,
|
||||
strategy_id=self.strategy_config.strategy_id,
|
||||
cash=self.account_config.initial_capital,
|
||||
initial_capital=self.account_config.initial_capital,
|
||||
position=0,
|
||||
position_available=0,
|
||||
avg_price=0,
|
||||
params=self.strategy_config.params or {},
|
||||
)
|
||||
|
||||
# 创建策略实例
|
||||
strategy = strategy_class(context)
|
||||
strategy.init()
|
||||
|
||||
logger.info(
|
||||
f"创建策略实例: {self.strategy_config.strategy_id} - "
|
||||
f"{strategy.strategy_name}"
|
||||
)
|
||||
|
||||
return strategy
|
||||
|
||||
async def _process_kline(self, kline_data: dict):
|
||||
"""
|
||||
处理K线数据
|
||||
|
||||
Args:
|
||||
kline_data: K线数据
|
||||
"""
|
||||
if not self.strategy:
|
||||
logger.error("策略实例未初始化")
|
||||
return
|
||||
|
||||
try:
|
||||
# 调用策略处理
|
||||
signal = self.strategy.handle_kline(kline_data)
|
||||
|
||||
if signal and signal.action in ["buy", "sell"]:
|
||||
# 发布信号到信号频道
|
||||
signal_dict = {
|
||||
"symbol": kline_data["symbol"],
|
||||
"signal": signal.action,
|
||||
"price": signal.price,
|
||||
"quantity": signal.quantity,
|
||||
"reason": signal.reason,
|
||||
"timestamp": kline_data["timestamp"],
|
||||
}
|
||||
|
||||
await redis_client.publish(self.signal_channel, json.dumps(signal_dict))
|
||||
|
||||
logger.info(
|
||||
f"发送信号: {signal.action} {kline_data['symbol']} "
|
||||
f"{signal.quantity}股 @{signal.price:.2f} - {signal.reason}"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"处理K线失败: {e}", exc_info=True)
|
||||
|
||||
async def run(self):
|
||||
"""运行策略管理器"""
|
||||
try:
|
||||
# 创建策略实例
|
||||
self.strategy = self._create_strategy_instance()
|
||||
|
||||
logger.info(f"订阅K线频道: {self.kline_channel}")
|
||||
self._running = True
|
||||
|
||||
# 连接Redis
|
||||
await redis_client.connect()
|
||||
|
||||
# 订阅K线频道
|
||||
async with redis_client.subscribe(self.kline_channel) as pubsub:
|
||||
# 监听K线数据
|
||||
async for message in pubsub.listen():
|
||||
if not self._running:
|
||||
break
|
||||
|
||||
if message["type"] == "message":
|
||||
try:
|
||||
kline_data = json.loads(message["data"])
|
||||
await self._process_kline(kline_data)
|
||||
except Exception as e:
|
||||
logger.error(f"处理消息失败: {e}")
|
||||
|
||||
logger.info("策略管理器已停止")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"策略管理器运行失败: {e}", exc_info=True)
|
||||
raise
|
||||
|
||||
async def stop(self):
|
||||
"""停止策略管理器"""
|
||||
self._running = False
|
||||
logger.info("正在停止策略管理器...")
|
||||
@ -1,187 +0,0 @@
|
||||
"""
|
||||
回测任务管理器
|
||||
|
||||
负责任务的创建、状态管理、查询等
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from src.core.logger import get_logger
|
||||
|
||||
from ..schemas import BacktestConfig, TaskProgress, TaskStatus, TaskSummary
|
||||
|
||||
logger = get_logger("backtest.task_manager")
|
||||
|
||||
|
||||
class TaskManager:
|
||||
"""
|
||||
回测任务管理器
|
||||
|
||||
使用内存+文件方式存储任务状态:
|
||||
- 内存:快速查询任务状态
|
||||
- 文件:持久化任务配置和状态
|
||||
"""
|
||||
|
||||
def __init__(self, results_dir: str = "bt_results"):
|
||||
"""
|
||||
初始化任务管理器
|
||||
|
||||
Args:
|
||||
results_dir: 结果保存目录
|
||||
"""
|
||||
self.results_dir = Path(results_dir)
|
||||
self.results_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 内存中的任务状态
|
||||
self._tasks: Dict[str, TaskProgress] = {}
|
||||
|
||||
# 加载已有任务
|
||||
self._load_existing_tasks()
|
||||
|
||||
def _load_existing_tasks(self):
|
||||
"""加载已有的任务"""
|
||||
try:
|
||||
for task_dir in self.results_dir.iterdir():
|
||||
if not task_dir.is_dir():
|
||||
continue
|
||||
|
||||
status_file = task_dir / "status.json"
|
||||
if status_file.exists():
|
||||
with open(status_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
task_id = data["task_id"]
|
||||
self._tasks[task_id] = TaskProgress(**data)
|
||||
|
||||
logger.info(f"加载了 {len(self._tasks)} 个已存在的任务")
|
||||
except Exception as e:
|
||||
logger.warning(f"加载已有任务失败: {e}")
|
||||
|
||||
def create_task(self, config: BacktestConfig) -> str:
|
||||
"""
|
||||
创建新任务
|
||||
|
||||
Args:
|
||||
config: 回测配置
|
||||
|
||||
Returns:
|
||||
任务ID
|
||||
"""
|
||||
task_id = config.task_id
|
||||
|
||||
# 检查任务是否已存在
|
||||
if task_id in self._tasks:
|
||||
raise ValueError(f"任务ID已存在: {task_id}")
|
||||
|
||||
# 创建任务目录
|
||||
task_dir = self.results_dir / task_id
|
||||
task_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 保存配置
|
||||
config_file = task_dir / "config.json"
|
||||
with open(config_file, "w", encoding="utf-8") as f:
|
||||
json.dump(config.model_dump(), f, indent=2, ensure_ascii=False, default=str)
|
||||
|
||||
# 初始化任务状态
|
||||
progress = TaskProgress(
|
||||
task_id=task_id,
|
||||
status=TaskStatus.PENDING,
|
||||
progress=0.0,
|
||||
message="等待执行",
|
||||
stage="pending",
|
||||
)
|
||||
|
||||
self._tasks[task_id] = progress
|
||||
self._save_status(task_id, progress)
|
||||
|
||||
logger.info(f"创建任务: {task_id}")
|
||||
return task_id
|
||||
|
||||
def update_progress(
|
||||
self,
|
||||
task_id: str,
|
||||
progress: float,
|
||||
message: str = "",
|
||||
status: Optional[TaskStatus] = None,
|
||||
stage: str = "",
|
||||
):
|
||||
"""
|
||||
更新任务进度
|
||||
|
||||
Args:
|
||||
task_id: 任务ID
|
||||
progress: 进度(0-100)
|
||||
message: 状态消息
|
||||
status: 任务状态
|
||||
stage: 当前阶段
|
||||
"""
|
||||
if task_id not in self._tasks:
|
||||
logger.warning(f"任务不存在: {task_id}")
|
||||
return
|
||||
|
||||
task = self._tasks[task_id]
|
||||
task.progress = progress
|
||||
if message:
|
||||
task.message = message
|
||||
if status:
|
||||
task.status = status
|
||||
if stage:
|
||||
task.stage = stage
|
||||
|
||||
self._save_status(task_id, task)
|
||||
|
||||
logger.debug(f"任务 {task_id}: {progress:.1f}% - {message}")
|
||||
|
||||
def get_progress(self, task_id: str) -> Optional[TaskProgress]:
|
||||
"""获取任务进度"""
|
||||
return self._tasks.get(task_id)
|
||||
|
||||
def list_tasks(self) -> List[TaskSummary]:
|
||||
"""获取任务列表"""
|
||||
summaries = []
|
||||
|
||||
for task_id, progress in self._tasks.items():
|
||||
# 读取配置获取任务名称
|
||||
config_file = self.results_dir / task_id / "config.json"
|
||||
task_name = ""
|
||||
created_at = datetime.now()
|
||||
|
||||
if config_file.exists():
|
||||
with open(config_file, "r", encoding="utf-8") as f:
|
||||
config_data = json.load(f)
|
||||
task_name = config_data.get("task_name", "")
|
||||
created_at = datetime.fromisoformat(
|
||||
config_data.get("created_at", datetime.now().isoformat())
|
||||
)
|
||||
|
||||
summaries.append(
|
||||
TaskSummary(
|
||||
task_id=task_id,
|
||||
task_name=task_name,
|
||||
status=progress.status,
|
||||
progress=progress.progress,
|
||||
created_at=created_at,
|
||||
)
|
||||
)
|
||||
|
||||
# 按创建时间倒序
|
||||
summaries.sort(key=lambda x: x.created_at, reverse=True)
|
||||
return summaries
|
||||
|
||||
def get_task_dir(self, task_id: str) -> Path:
|
||||
"""获取任务目录"""
|
||||
return self.results_dir / task_id
|
||||
|
||||
def _save_status(self, task_id: str, progress: TaskProgress):
|
||||
"""保存任务状态到文件"""
|
||||
status_file = self.results_dir / task_id / "status.json"
|
||||
with open(status_file, "w", encoding="utf-8") as f:
|
||||
json.dump(
|
||||
progress.model_dump(), f, indent=2, ensure_ascii=False, default=str
|
||||
)
|
||||
|
||||
|
||||
# 全局任务管理器实例
|
||||
task_manager = TaskManager()
|
||||
@ -1,360 +0,0 @@
|
||||
"""
|
||||
模拟撮合器
|
||||
|
||||
负责订阅信号频道、模拟订单撮合、计算手续费和滑点
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.redis_client import redis_client
|
||||
from ..schemas import AccountConfig, TradeConfig
|
||||
|
||||
logger = get_logger("backtest.trade_simulator")
|
||||
|
||||
|
||||
class Position:
|
||||
"""持仓信息"""
|
||||
|
||||
def __init__(self, symbol: str, quantity: int, avg_price: float):
|
||||
self.symbol = symbol
|
||||
self.quantity = quantity
|
||||
self.avg_price = avg_price
|
||||
self.market_value = 0.0
|
||||
self.profit = 0.0
|
||||
self.profit_rate = 0.0
|
||||
|
||||
def update_market_value(self, current_price: float):
|
||||
"""更新市值"""
|
||||
self.market_value = self.quantity * current_price
|
||||
self.profit = self.market_value - self.quantity * self.avg_price
|
||||
self.profit_rate = (
|
||||
self.profit / (self.quantity * self.avg_price) * 100
|
||||
if self.quantity > 0
|
||||
else 0.0
|
||||
)
|
||||
|
||||
|
||||
class TradeRecord:
|
||||
"""交易记录"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
symbol: str,
|
||||
direction: str,
|
||||
price: float,
|
||||
quantity: int,
|
||||
timestamp: datetime,
|
||||
commission: float,
|
||||
tax: float,
|
||||
):
|
||||
self.symbol = symbol
|
||||
self.direction = direction # buy/sell
|
||||
self.price = price
|
||||
self.quantity = quantity
|
||||
self.timestamp = timestamp
|
||||
self.commission = commission
|
||||
self.tax = tax
|
||||
self.amount = price * quantity
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""转换为字典"""
|
||||
return {
|
||||
"symbol": self.symbol,
|
||||
"direction": self.direction,
|
||||
"price": self.price,
|
||||
"quantity": self.quantity,
|
||||
"timestamp": self.timestamp.isoformat(),
|
||||
"commission": self.commission,
|
||||
"tax": self.tax,
|
||||
"amount": self.amount,
|
||||
}
|
||||
|
||||
|
||||
class TradeSimulator:
|
||||
"""
|
||||
模拟撮合器
|
||||
|
||||
订阅信号频道,模拟订单撮合,计算手续费和滑点
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
signal_channel: str,
|
||||
account_config: AccountConfig,
|
||||
trade_config: TradeConfig,
|
||||
):
|
||||
"""
|
||||
初始化模拟撮合器
|
||||
|
||||
Args:
|
||||
signal_channel: 信号频道名
|
||||
account_config: 账户配置
|
||||
trade_config: 交易配置
|
||||
"""
|
||||
self.signal_channel = signal_channel
|
||||
self.account_config = account_config
|
||||
self.trade_config = trade_config
|
||||
|
||||
# 账户状态
|
||||
self.cash = account_config.initial_capital
|
||||
self.positions = {} # {symbol: Position}
|
||||
self.trades = [] # 交易记录列表
|
||||
|
||||
# 当前价格(用于计算市值)
|
||||
self.current_prices = {} # {symbol: price}
|
||||
|
||||
def get_account_summary(self) -> dict:
|
||||
"""获取账户摘要"""
|
||||
# 计算持仓市值
|
||||
position_value = sum(pos.market_value for pos in self.positions.values())
|
||||
|
||||
# 总资产
|
||||
total_assets = self.cash + position_value
|
||||
|
||||
# 收益
|
||||
profit = total_assets - self.account_config.initial_capital
|
||||
profit_rate = profit / self.account_config.initial_capital * 100
|
||||
|
||||
return {
|
||||
"cash": self.cash,
|
||||
"position_value": position_value,
|
||||
"total_assets": total_assets,
|
||||
"profit": profit,
|
||||
"profit_rate": profit_rate,
|
||||
"positions": {
|
||||
symbol: {
|
||||
"quantity": pos.quantity,
|
||||
"avg_price": pos.avg_price,
|
||||
"market_value": pos.market_value,
|
||||
"profit": pos.profit,
|
||||
"profit_rate": pos.profit_rate,
|
||||
}
|
||||
for symbol, pos in self.positions.items()
|
||||
},
|
||||
}
|
||||
|
||||
def update_price(self, symbol: str, price: float):
|
||||
"""
|
||||
更新股票价格
|
||||
|
||||
Args:
|
||||
symbol: 股票代码
|
||||
price: 最新价格
|
||||
"""
|
||||
self.current_prices[symbol] = price
|
||||
|
||||
# 更新持仓市值
|
||||
if symbol in self.positions:
|
||||
self.positions[symbol].update_market_value(price)
|
||||
|
||||
def calculate_commission(self, amount: float) -> float:
|
||||
"""
|
||||
计算佣金
|
||||
|
||||
Args:
|
||||
amount: 交易金额
|
||||
|
||||
Returns:
|
||||
佣金
|
||||
"""
|
||||
commission = amount * self.trade_config.commission_rate
|
||||
return max(commission, self.trade_config.min_commission)
|
||||
|
||||
def calculate_tax(self, amount: float, direction: str) -> float:
|
||||
"""
|
||||
计算印花税(仅卖出收取)
|
||||
|
||||
Args:
|
||||
amount: 交易金额
|
||||
direction: 方向 buy/sell
|
||||
|
||||
Returns:
|
||||
印花税
|
||||
"""
|
||||
if direction == "sell":
|
||||
return amount * self.trade_config.tax_rate
|
||||
return 0.0
|
||||
|
||||
def calculate_slippage(self, price: float, direction: str) -> float:
|
||||
"""
|
||||
计算滑点后的价格
|
||||
|
||||
Args:
|
||||
price: 原价格
|
||||
direction: 方向 buy/sell
|
||||
|
||||
Returns:
|
||||
滑点后的价格
|
||||
"""
|
||||
if direction == "buy":
|
||||
return price * (1 + self.trade_config.slippage)
|
||||
else:
|
||||
return price * (1 - self.trade_config.slippage)
|
||||
|
||||
def execute_buy(
|
||||
self, symbol: str, price: float, quantity: int, timestamp: datetime
|
||||
) -> Optional[TradeRecord]:
|
||||
"""
|
||||
执行买入
|
||||
|
||||
Args:
|
||||
symbol: 股票代码
|
||||
price: 价格
|
||||
quantity: 数量
|
||||
timestamp: 时间戳
|
||||
|
||||
Returns:
|
||||
交易记录,如果失败返回None
|
||||
"""
|
||||
# 计算滑点后的价格
|
||||
actual_price = self.calculate_slippage(price, "buy")
|
||||
|
||||
# 计算交易金额
|
||||
amount = actual_price * quantity
|
||||
|
||||
# 计算佣金和印花税
|
||||
commission = self.calculate_commission(amount)
|
||||
tax = self.calculate_tax(amount, "buy")
|
||||
|
||||
# 计算总成本
|
||||
total_cost = amount + commission + tax
|
||||
|
||||
# 检查资金是否足够
|
||||
if total_cost > self.cash:
|
||||
logger.warning(f"资金不足: 需要 {total_cost:.2f}, 可用 {self.cash:.2f}")
|
||||
return None
|
||||
|
||||
# 扣减资金
|
||||
self.cash -= total_cost
|
||||
|
||||
# 更新持仓
|
||||
if symbol in self.positions:
|
||||
pos = self.positions[symbol]
|
||||
# 计算平均成本
|
||||
total_quantity = pos.quantity + quantity
|
||||
total_cost = pos.avg_price * pos.quantity + amount
|
||||
pos.quantity = total_quantity
|
||||
pos.avg_price = total_cost / total_quantity
|
||||
else:
|
||||
self.positions[symbol] = Position(symbol, quantity, actual_price)
|
||||
|
||||
# 记录交易
|
||||
trade = TradeRecord(
|
||||
symbol=symbol,
|
||||
direction="buy",
|
||||
price=actual_price,
|
||||
quantity=quantity,
|
||||
timestamp=timestamp,
|
||||
commission=commission,
|
||||
tax=tax,
|
||||
)
|
||||
self.trades.append(trade)
|
||||
|
||||
logger.info(
|
||||
f"买入: {symbol} {quantity}股 @{actual_price:.2f} 手续费:{commission:.2f} 税费:{tax:.2f}"
|
||||
)
|
||||
|
||||
return trade
|
||||
|
||||
def execute_sell(
|
||||
self, symbol: str, price: float, quantity: int, timestamp: datetime
|
||||
) -> Optional[TradeRecord]:
|
||||
"""
|
||||
执行卖出
|
||||
|
||||
Args:
|
||||
symbol: 股票代码
|
||||
price: 价格
|
||||
quantity: 数量
|
||||
timestamp: 时间戳
|
||||
|
||||
Returns:
|
||||
交易记录,如果失败返回None
|
||||
"""
|
||||
# 检查持仓是否足够
|
||||
if symbol not in self.positions or self.positions[symbol].quantity < quantity:
|
||||
logger.warning(f"持仓不足: {symbol}")
|
||||
return None
|
||||
|
||||
# 计算滑点后的价格
|
||||
actual_price = self.calculate_slippage(price, "sell")
|
||||
|
||||
# 计算交易金额
|
||||
amount = actual_price * quantity
|
||||
|
||||
# 计算佣金和印花税
|
||||
commission = self.calculate_commission(amount)
|
||||
tax = self.calculate_tax(amount, "sell")
|
||||
|
||||
# 计算实际到账金额
|
||||
net_amount = amount - commission - tax
|
||||
|
||||
# 增加资金
|
||||
self.cash += net_amount
|
||||
|
||||
# 更新持仓
|
||||
pos = self.positions[symbol]
|
||||
pos.quantity -= quantity
|
||||
|
||||
# 如果持仓清空,删除记录
|
||||
if pos.quantity == 0:
|
||||
del self.positions[symbol]
|
||||
|
||||
# 记录交易
|
||||
trade = TradeRecord(
|
||||
symbol=symbol,
|
||||
direction="sell",
|
||||
price=actual_price,
|
||||
quantity=quantity,
|
||||
timestamp=timestamp,
|
||||
commission=commission,
|
||||
tax=tax,
|
||||
)
|
||||
self.trades.append(trade)
|
||||
|
||||
logger.info(
|
||||
f"卖出: {symbol} {quantity}股 @{actual_price:.2f} 手续费:{commission:.2f} 税费:{tax:.2f}"
|
||||
)
|
||||
|
||||
return trade
|
||||
|
||||
async def process_signal(self, signal_data: dict):
|
||||
"""
|
||||
处理信号
|
||||
|
||||
Args:
|
||||
signal_data: 信号数据 {"symbol": "000001.SZ", "signal": "buy/sell", "price": 10.0, "quantity": 100, "timestamp": "..."}
|
||||
"""
|
||||
symbol = signal_data["symbol"]
|
||||
signal = signal_data["signal"]
|
||||
price = signal_data["price"]
|
||||
quantity = signal_data.get("quantity", 100)
|
||||
timestamp = datetime.fromisoformat(signal_data["timestamp"])
|
||||
|
||||
logger.debug(f"收到信号: {symbol} {signal} {quantity}股 @{price}")
|
||||
|
||||
if signal == "buy":
|
||||
self.execute_buy(symbol, price, quantity, timestamp)
|
||||
elif signal == "sell":
|
||||
self.execute_sell(symbol, price, quantity, timestamp)
|
||||
|
||||
async def run(self):
|
||||
"""运行模拟撮合器(订阅信号频道)"""
|
||||
logger.info(f"订阅信号频道: {self.signal_channel}")
|
||||
|
||||
await redis_client.connect()
|
||||
pubsub = await redis_client.subscribe(self.signal_channel)
|
||||
|
||||
try:
|
||||
async for message in pubsub.listen():
|
||||
if message["type"] == "message":
|
||||
try:
|
||||
signal_data = json.loads(message["data"])
|
||||
await self.process_signal(signal_data)
|
||||
except Exception as e:
|
||||
logger.error(f"处理信号失败: {e}")
|
||||
finally:
|
||||
await pubsub.unsubscribe(self.signal_channel)
|
||||
@ -1,91 +1,73 @@
|
||||
"""
|
||||
QTrade Core Module
|
||||
|
||||
核心模块,提供所有服务共用的基础功能:
|
||||
- 配置管理 (config)
|
||||
- Redis 客户端 (redis_client)
|
||||
- 数据库连接 (database)
|
||||
- 日志模块 (logger)
|
||||
- ORM 模型 (models)
|
||||
- 常量定义 (constants)
|
||||
QTrade 核心对象模块
|
||||
定义所有核心数据模型
|
||||
"""
|
||||
|
||||
from .config import settings
|
||||
from .logger import get_logger
|
||||
|
||||
# 导出所有 ORM 模型和枚举
|
||||
# 从 models 子模块导入所有对象
|
||||
from .models import (
|
||||
Base,
|
||||
TimestampMixin,
|
||||
TradeSide,
|
||||
KlineBase,
|
||||
Kline1m,
|
||||
Kline5m,
|
||||
Kline15m,
|
||||
Kline30m,
|
||||
Kline60m,
|
||||
Kline1d,
|
||||
Pairing,
|
||||
PairingStatus,
|
||||
Order,
|
||||
# 枚举
|
||||
OrderSide,
|
||||
OrderType,
|
||||
OrderStatus,
|
||||
PositionDirection,
|
||||
SignalType,
|
||||
ProductType,
|
||||
Exchange,
|
||||
# 对象
|
||||
Tick,
|
||||
Kline,
|
||||
Order,
|
||||
Trade,
|
||||
Position,
|
||||
Account,
|
||||
Signal,
|
||||
SignalStatus,
|
||||
BalanceLog,
|
||||
BalanceLogType,
|
||||
Symbol,
|
||||
)
|
||||
|
||||
# 导出 K线常量
|
||||
from .constants import (
|
||||
KlinePeriod,
|
||||
KLINE_PERIOD_CONFIG,
|
||||
SUPPORTED_PERIODS,
|
||||
get_kline_config,
|
||||
get_kline_table_name,
|
||||
get_kline_interval,
|
||||
get_xt_period,
|
||||
get_kline_models,
|
||||
get_kline_model,
|
||||
# 配置管理
|
||||
from .config import Config, get_config, set_config
|
||||
|
||||
# 日志管理
|
||||
from .logger import (
|
||||
Logger,
|
||||
get_logger,
|
||||
set_log_level,
|
||||
debug,
|
||||
info,
|
||||
warning,
|
||||
error,
|
||||
exception,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# 配置和工具
|
||||
"settings",
|
||||
"get_logger",
|
||||
# ORM 基类
|
||||
"Base",
|
||||
"TimestampMixin",
|
||||
# 通用枚举
|
||||
"TradeSide",
|
||||
# K线实体
|
||||
"KlineBase",
|
||||
"Kline1m",
|
||||
"Kline5m",
|
||||
"Kline15m",
|
||||
"Kline30m",
|
||||
"Kline60m",
|
||||
"Kline1d",
|
||||
# 业务模型
|
||||
"Pairing",
|
||||
"PairingStatus",
|
||||
"Order",
|
||||
# 枚举
|
||||
"OrderSide",
|
||||
"OrderType",
|
||||
"OrderStatus",
|
||||
"PositionDirection",
|
||||
"SignalType",
|
||||
"ProductType",
|
||||
"Exchange",
|
||||
# 对象
|
||||
"Tick",
|
||||
"Kline",
|
||||
"Order",
|
||||
"Trade",
|
||||
"Position",
|
||||
"Account",
|
||||
"Signal",
|
||||
"SignalStatus",
|
||||
"BalanceLog",
|
||||
"BalanceLogType",
|
||||
# K线常量
|
||||
"KlinePeriod",
|
||||
"KLINE_PERIOD_CONFIG",
|
||||
"SUPPORTED_PERIODS",
|
||||
"get_kline_config",
|
||||
"get_kline_table_name",
|
||||
"get_kline_interval",
|
||||
"get_xt_period",
|
||||
"get_kline_models",
|
||||
"get_kline_model",
|
||||
"Symbol",
|
||||
# 配置
|
||||
"Config",
|
||||
"get_config",
|
||||
"set_config",
|
||||
# 日志
|
||||
"Logger",
|
||||
"get_logger",
|
||||
"set_log_level",
|
||||
"debug",
|
||||
"info",
|
||||
"warning",
|
||||
"error",
|
||||
"exception",
|
||||
]
|
||||
|
||||
@ -1,170 +0,0 @@
|
||||
"""
|
||||
FastAPI 应用基类
|
||||
|
||||
提供统一的:
|
||||
- 生命周期管理 (Redis, Database 连接)
|
||||
- 异常处理
|
||||
- 健康检查路由
|
||||
- 中间件配置
|
||||
"""
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import AsyncIterator, Callable, Awaitable, Optional
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from src.core.config import settings
|
||||
from src.core.logger import get_logger
|
||||
from src.core.database import db
|
||||
from src.core.redis_client import redis_client
|
||||
|
||||
|
||||
class BaseApp:
|
||||
"""
|
||||
FastAPI 应用基类
|
||||
|
||||
用法:
|
||||
class DataServiceApp(BaseApp):
|
||||
name = "data_service"
|
||||
title = "QTrade Data Service"
|
||||
description = "数据服务"
|
||||
|
||||
async def on_startup(self):
|
||||
# 启动自定义服务
|
||||
await self.market_receiver.start()
|
||||
|
||||
async def on_shutdown(self):
|
||||
# 关闭自定义服务
|
||||
await self.market_receiver.stop()
|
||||
|
||||
def setup_routes(self):
|
||||
self.app.include_router(kline.router, prefix="/kline")
|
||||
"""
|
||||
|
||||
name: str = "base"
|
||||
title: str = "QTrade Service"
|
||||
description: str = "QTrade 服务"
|
||||
prefix: str = "" # 路由前缀
|
||||
|
||||
# 是否需要 Redis/Database
|
||||
need_redis: bool = True
|
||||
need_database: bool = True
|
||||
|
||||
def __init__(self):
|
||||
self.logger = get_logger(self.name)
|
||||
self.app = self._create_app()
|
||||
|
||||
def _create_app(self) -> FastAPI:
|
||||
"""创建 FastAPI 实例"""
|
||||
app = FastAPI(
|
||||
title=self.title,
|
||||
description=self.description,
|
||||
version=settings.app.version,
|
||||
lifespan=self._lifespan,
|
||||
docs_url="/docs" if settings.app.debug else None,
|
||||
redoc_url="/redoc" if settings.app.debug else None,
|
||||
)
|
||||
|
||||
# CORS 中间件
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# 全局异常处理
|
||||
@app.exception_handler(Exception)
|
||||
async def global_exception_handler(request: Request, exc: Exception):
|
||||
self.logger.error(f"未处理的异常: {exc}", exc_info=True)
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={
|
||||
"code": 500,
|
||||
"message": "服务器内部错误",
|
||||
"detail": str(exc) if settings.app.debug else None,
|
||||
},
|
||||
)
|
||||
|
||||
# 健康检查路由
|
||||
@app.get("/health", tags=["健康检查"])
|
||||
async def health_check():
|
||||
return {
|
||||
"status": "healthy",
|
||||
"service": self.name,
|
||||
"version": settings.app.version,
|
||||
}
|
||||
|
||||
# 子类注册路由
|
||||
self.setup_routes(app)
|
||||
|
||||
return app
|
||||
|
||||
@asynccontextmanager
|
||||
async def _lifespan(self, app: FastAPI) -> AsyncIterator[None]:
|
||||
"""生命周期管理"""
|
||||
self.logger.info(f"{self.title} 启动中...")
|
||||
|
||||
# 连接基础设施
|
||||
if self.need_redis:
|
||||
try:
|
||||
await redis_client.connect()
|
||||
self.logger.info("Redis 连接成功")
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Redis 连接失败: {e}")
|
||||
|
||||
if self.need_database:
|
||||
try:
|
||||
await db.connect()
|
||||
self.logger.info("数据库连接成功")
|
||||
except Exception as e:
|
||||
self.logger.warning(f"数据库连接失败: {e}")
|
||||
|
||||
# 子类启动逻辑
|
||||
await self.on_startup()
|
||||
|
||||
self.logger.info(f"{self.title} 启动完成")
|
||||
|
||||
yield
|
||||
|
||||
self.logger.info(f"{self.title} 关闭中...")
|
||||
|
||||
# 子类关闭逻辑
|
||||
await self.on_shutdown()
|
||||
|
||||
# 断开基础设施
|
||||
if self.need_redis:
|
||||
await redis_client.disconnect()
|
||||
if self.need_database:
|
||||
await db.disconnect()
|
||||
|
||||
self.logger.info(f"{self.title} 已关闭")
|
||||
|
||||
def setup_routes(self, app: FastAPI):
|
||||
"""注册路由 - 子类实现"""
|
||||
pass
|
||||
|
||||
async def on_startup(self):
|
||||
"""启动时执行 - 子类实现"""
|
||||
pass
|
||||
|
||||
async def on_shutdown(self):
|
||||
"""关闭时执行 - 子类实现"""
|
||||
pass
|
||||
|
||||
def run(self, host: Optional[str] = None, port: Optional[int] = None):
|
||||
"""运行服务"""
|
||||
import uvicorn
|
||||
|
||||
_host = host or "0.0.0.0"
|
||||
_port = port or 8000
|
||||
|
||||
uvicorn.run(
|
||||
self.app,
|
||||
host=_host,
|
||||
port=_port,
|
||||
reload=False, # 使用 app 实例时不支持 reload
|
||||
)
|
||||
@ -1,296 +1,285 @@
|
||||
"""
|
||||
QTrade 配置管理模块
|
||||
|
||||
使用统一的配置管理器进行配置管理,支持:
|
||||
- 全局配置 (global.yaml)
|
||||
- 服务独立配置 (services/{service_name}.yaml)
|
||||
- 环境变量覆盖
|
||||
- 配置验证
|
||||
|
||||
配置加载优先级(从低到高):
|
||||
1. global.yaml - 全局公共配置
|
||||
2. services/{service_name}.yaml - 服务独立配置
|
||||
3. 环境变量 - 运行时覆盖
|
||||
配置管理工具类
|
||||
支持读取、修改和保存 YAML 配置文件
|
||||
"""
|
||||
|
||||
from enum import Enum
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
from .config_manager import ConfigManager
|
||||
from typing import Any, Dict, Optional, Union
|
||||
import yaml
|
||||
|
||||
|
||||
# ========== 环境枚举 ==========
|
||||
|
||||
|
||||
class Environment(str, Enum):
|
||||
"""运行环境"""
|
||||
|
||||
PRODUCTION = "production" # 实盘
|
||||
BACKTEST = "backtest" # 回测
|
||||
SIMULATION = "simulation" # 模拟
|
||||
|
||||
|
||||
def get_project_root() -> Path:
|
||||
"""获取项目根目录"""
|
||||
current = Path(__file__).resolve()
|
||||
for parent in [current] + list(current.parents):
|
||||
if (parent / "configs").is_dir():
|
||||
return parent
|
||||
return Path.cwd()
|
||||
|
||||
|
||||
# ========== 配置辅助类 ==========
|
||||
|
||||
|
||||
class ConfigProxy:
|
||||
"""配置代理类,提供便捷的属性访问"""
|
||||
|
||||
def __init__(self, config_manager: ConfigManager, prefix: str = ""):
|
||||
self._manager = config_manager
|
||||
self._prefix = prefix
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
key = f"{self._prefix}.{name}" if self._prefix else name
|
||||
value = self._manager.get(key)
|
||||
|
||||
if isinstance(value, dict):
|
||||
return ConfigProxy(self._manager, key)
|
||||
return value
|
||||
|
||||
def __getitem__(self, key: str) -> Any:
|
||||
return self.__getattr__(key)
|
||||
|
||||
|
||||
class EnvironmentConfig(ConfigProxy):
|
||||
"""环境配置"""
|
||||
|
||||
@property
|
||||
def env(self) -> str:
|
||||
"""当前环境"""
|
||||
return self._manager.get("environment.env", "production")
|
||||
|
||||
@property
|
||||
def db_name(self) -> str:
|
||||
"""数据库名称"""
|
||||
env = self.env
|
||||
db_mapping = {
|
||||
"production": "QTrade_RealTrade",
|
||||
"backtest": "QTrade_BackTestTrade",
|
||||
"simulation": "QTrade_SimuTrade",
|
||||
}
|
||||
return self._manager.get(
|
||||
"environment.db_name", db_mapping.get(env, "qtrade_stock_data")
|
||||
)
|
||||
|
||||
@property
|
||||
def redis_prefix(self) -> str:
|
||||
"""Redis频道前缀"""
|
||||
env = self.env
|
||||
prefix_mapping = {
|
||||
"production": "real",
|
||||
"backtest": "bt",
|
||||
"simulation": "simu",
|
||||
}
|
||||
return self._manager.get(
|
||||
"environment.redis_prefix", prefix_mapping.get(env, "real")
|
||||
)
|
||||
|
||||
@property
|
||||
def port_offset(self) -> int:
|
||||
"""端口偏移量"""
|
||||
env = self.env
|
||||
offset_mapping = {
|
||||
"production": 9000,
|
||||
"backtest": 10000,
|
||||
"simulation": 11000,
|
||||
}
|
||||
return self._manager.get(
|
||||
"environment.port_offset", offset_mapping.get(env, 9000)
|
||||
)
|
||||
|
||||
|
||||
class RedisChannels(ConfigProxy):
|
||||
"""Redis频道配置"""
|
||||
|
||||
def __init__(
|
||||
self, config_manager: ConfigManager, environment_config: EnvironmentConfig
|
||||
):
|
||||
super().__init__(config_manager, "")
|
||||
self._env_config = environment_config
|
||||
|
||||
@property
|
||||
def kline_update(self) -> str:
|
||||
"""K线更新频道"""
|
||||
return f"{self._env_config.redis_prefix}:kline:update"
|
||||
|
||||
@property
|
||||
def signal_create(self) -> str:
|
||||
"""信号创建频道"""
|
||||
return f"{self._env_config.redis_prefix}:signal:create"
|
||||
|
||||
@property
|
||||
def order_update(self) -> str:
|
||||
"""订单更新频道"""
|
||||
return f"{self._env_config.redis_prefix}:order:update"
|
||||
|
||||
@property
|
||||
def trade_update(self) -> str:
|
||||
"""成交更新频道"""
|
||||
return f"{self._env_config.redis_prefix}:trade:update"
|
||||
|
||||
|
||||
class RedisConfig(ConfigProxy):
|
||||
"""Redis 配置"""
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
"""生成 Redis URL"""
|
||||
password = self._manager.get("redis.password", "")
|
||||
host = self._manager.get("redis.host", "127.0.0.1")
|
||||
port = self._manager.get("redis.port", 6379)
|
||||
db = self._manager.get("redis.db", 0)
|
||||
|
||||
auth = f":{password}@" if password else ""
|
||||
return f"redis://{auth}{host}:{port}/{db}"
|
||||
|
||||
|
||||
class DatabaseConfig(ConfigProxy):
|
||||
"""数据库配置"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config_manager: ConfigManager,
|
||||
environment_config: EnvironmentConfig,
|
||||
prefix: str = "database",
|
||||
):
|
||||
super().__init__(config_manager, prefix)
|
||||
self._env_config = environment_config
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
"""生成数据库 URL (异步)"""
|
||||
user = self._manager.get("database.user", "root")
|
||||
password = self._manager.get("database.password", "")
|
||||
host = self._manager.get("database.host", "127.0.0.1")
|
||||
port = self._manager.get("database.port", 3306)
|
||||
# 使用环境配置的数据库名
|
||||
database = self._env_config.db_name
|
||||
|
||||
return (
|
||||
f"mysql+aiomysql://{user}:{password}@"
|
||||
f"{host}:{port}/{database}?charset=utf8mb4"
|
||||
)
|
||||
|
||||
@property
|
||||
def sync_url(self) -> str:
|
||||
"""生成数据库 URL (同步,用于迁移)"""
|
||||
user = self._manager.get("database.user", "root")
|
||||
password = self._manager.get("database.password", "")
|
||||
host = self._manager.get("database.host", "127.0.0.1")
|
||||
port = self._manager.get("database.port", 3306)
|
||||
# 使用环境配置的数据库名
|
||||
database = self._env_config.db_name
|
||||
|
||||
return (
|
||||
f"mysql+pymysql://{user}:{password}@"
|
||||
f"{host}:{port}/{database}?charset=utf8mb4"
|
||||
)
|
||||
|
||||
|
||||
class Settings:
|
||||
class Config:
|
||||
"""
|
||||
统一配置类
|
||||
配置管理类
|
||||
|
||||
使用 ConfigManager 加载配置,支持:
|
||||
- 全局配置 (global.yaml)
|
||||
- 服务配置 (services/{service_name}.yaml)
|
||||
- 环境变量覆盖
|
||||
功能:
|
||||
- 读取 YAML 配置文件
|
||||
- 支持嵌套键访问(如 'database.host')
|
||||
- 修改配置值
|
||||
- 保存配置到文件
|
||||
- 合并多个配置文件(全局配置 + 环境配置)
|
||||
"""
|
||||
|
||||
def __init__(self, service_name: str | None = None):
|
||||
self._manager = ConfigManager(service_name)
|
||||
self._service_name = service_name
|
||||
def __init__(self, config_file: Optional[Union[str, Path]] = None):
|
||||
"""
|
||||
初始化配置对象
|
||||
|
||||
# 创建配置代理
|
||||
self.app = ConfigProxy(self._manager, "app")
|
||||
self.environment = EnvironmentConfig(self._manager, "environment")
|
||||
self.redis = RedisConfig(self._manager, "redis")
|
||||
self.database = DatabaseConfig(self._manager, self.environment, "database")
|
||||
self.channels = RedisChannels(self._manager, self.environment)
|
||||
self.logging = ConfigProxy(self._manager, "logging")
|
||||
self.market = ConfigProxy(self._manager, "market")
|
||||
self.trading = ConfigProxy(self._manager, "trading")
|
||||
Args:
|
||||
config_file: 配置文件路径,支持相对路径和绝对路径
|
||||
如果为 None,从环境变量 CONFIG_FILE 读取
|
||||
"""
|
||||
self._data: Dict[str, Any] = {}
|
||||
self._config_file: Optional[Path] = None
|
||||
|
||||
# 服务配置
|
||||
if service_name:
|
||||
self.service = ConfigProxy(self._manager, "service")
|
||||
# QMT 服务特有配置
|
||||
if service_name == "qmt_service":
|
||||
self.qmt = ConfigProxy(self._manager, "qmt")
|
||||
# 策略引擎特有配置
|
||||
elif service_name == "strategy_engine":
|
||||
self.strategy = ConfigProxy(self._manager, "strategy")
|
||||
# 数据服务特有配置
|
||||
elif service_name == "data_service":
|
||||
self.data_download = ConfigProxy(self._manager, "data_download")
|
||||
if config_file is None:
|
||||
# 从环境变量读取
|
||||
config_file = os.environ.get("CONFIG_FILE")
|
||||
|
||||
if config_file:
|
||||
self.load(config_file)
|
||||
|
||||
def load(self, config_file: Union[str, Path], merge: bool = False) -> "Config":
|
||||
"""
|
||||
加载配置文件
|
||||
|
||||
Args:
|
||||
config_file: 配置文件路径
|
||||
merge: 是否合并到现有配置(True)还是覆盖(False)
|
||||
|
||||
Returns:
|
||||
self,支持链式调用
|
||||
"""
|
||||
config_path = Path(config_file)
|
||||
|
||||
# 如果是相对路径,相对于项目根目录
|
||||
if not config_path.is_absolute():
|
||||
project_root = Path(__file__).parent.parent.parent
|
||||
config_path = project_root / config_path
|
||||
|
||||
if not config_path.exists():
|
||||
raise FileNotFoundError(f"配置文件不存在: {config_path}")
|
||||
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
data = yaml.safe_load(f) or {}
|
||||
|
||||
if merge:
|
||||
self._merge_dict(self._data, data)
|
||||
else:
|
||||
# 加载所有服务端口配置(兼容旧代码)
|
||||
self.services = ConfigProxy(self._manager, "services")
|
||||
self._data = data
|
||||
self._config_file = config_path
|
||||
|
||||
@property
|
||||
def project_root(self) -> Path:
|
||||
"""项目根目录"""
|
||||
return self._manager.project_root
|
||||
return self
|
||||
|
||||
@property
|
||||
def logs_dir(self) -> Path:
|
||||
"""日志目录"""
|
||||
log_path = self._manager.get("logging.file.path", "logs")
|
||||
logs_path = self.project_root / log_path
|
||||
logs_path.mkdir(parents=True, exist_ok=True)
|
||||
return logs_path
|
||||
def load_with_global(self, env_config: Union[str, Path]) -> "Config":
|
||||
"""
|
||||
加载环境配置并合并全局配置
|
||||
|
||||
Args:
|
||||
env_config: 环境配置文件(如 'configs/production.yaml')
|
||||
|
||||
Returns:
|
||||
self,支持链式调用
|
||||
"""
|
||||
# 先加载全局配置
|
||||
self.load("configs/global.yaml")
|
||||
# 再加载环境配置并合并
|
||||
self.load(env_config, merge=True)
|
||||
return self
|
||||
|
||||
def get(self, key: str, default: Any = None) -> Any:
|
||||
"""获取配置值"""
|
||||
return self._manager.get(key, default)
|
||||
"""
|
||||
获取配置值,支持嵌套键
|
||||
|
||||
def set(self, key: str, value: Any) -> None:
|
||||
"""设置配置值"""
|
||||
self._manager.set(key, value)
|
||||
Args:
|
||||
key: 配置键,支持点分隔的嵌套键(如 'database.host')
|
||||
default: 默认值
|
||||
|
||||
def save(self, target: str = "service") -> None:
|
||||
"""保存配置"""
|
||||
self._manager.save(target)
|
||||
Returns:
|
||||
配置值
|
||||
|
||||
def reload(self) -> None:
|
||||
"""重新加载配置"""
|
||||
self._manager._load()
|
||||
Examples:
|
||||
>>> config.get('app.name')
|
||||
'QTrade'
|
||||
>>> config.get('database.host')
|
||||
'127.0.0.1'
|
||||
"""
|
||||
keys = key.split(".")
|
||||
value = self._data
|
||||
|
||||
for k in keys:
|
||||
if isinstance(value, dict):
|
||||
value = value.get(k)
|
||||
else:
|
||||
return default
|
||||
|
||||
if value is None:
|
||||
return default
|
||||
|
||||
return value
|
||||
|
||||
def set(self, key: str, value: Any) -> "Config":
|
||||
"""
|
||||
设置配置值,支持嵌套键
|
||||
|
||||
Args:
|
||||
key: 配置键,支持点分隔的嵌套键
|
||||
value: 配置值
|
||||
|
||||
Returns:
|
||||
self,支持链式调用
|
||||
|
||||
Examples:
|
||||
>>> config.set('database.host', '192.168.1.100')
|
||||
>>> config.set('app.debug', True)
|
||||
"""
|
||||
keys = key.split(".")
|
||||
data = self._data
|
||||
|
||||
# 遍历到倒数第二个键
|
||||
for k in keys[:-1]:
|
||||
if k not in data:
|
||||
data[k] = {}
|
||||
elif not isinstance(data[k], dict):
|
||||
data[k] = {}
|
||||
data = data[k]
|
||||
|
||||
# 设置最后一个键的值
|
||||
data[keys[-1]] = value
|
||||
return self
|
||||
|
||||
def update(self, data: Dict[str, Any]) -> "Config":
|
||||
"""
|
||||
批量更新配置
|
||||
|
||||
Args:
|
||||
data: 配置字典
|
||||
|
||||
Returns:
|
||||
self,支持链式调用
|
||||
|
||||
Examples:
|
||||
>>> config.update({
|
||||
... 'database.host': '192.168.1.100',
|
||||
... 'database.port': 3307
|
||||
... })
|
||||
"""
|
||||
for key, value in data.items():
|
||||
self.set(key, value)
|
||||
return self
|
||||
|
||||
def save(self, config_file: Optional[Union[str, Path]] = None) -> "Config":
|
||||
"""
|
||||
保存配置到文件
|
||||
|
||||
Args:
|
||||
config_file: 配置文件路径,如果为 None,保存到原文件
|
||||
|
||||
Returns:
|
||||
self,支持链式调用
|
||||
"""
|
||||
if config_file is None:
|
||||
config_file = self._config_file
|
||||
|
||||
if config_file is None:
|
||||
raise ValueError("未指定配置文件路径")
|
||||
|
||||
config_path = Path(config_file)
|
||||
|
||||
# 确保目录存在
|
||||
config_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(config_path, "w", encoding="utf-8") as f:
|
||||
yaml.safe_dump(
|
||||
self._data,
|
||||
f,
|
||||
allow_unicode=True,
|
||||
default_flow_style=False,
|
||||
sort_keys=False,
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""
|
||||
返回配置字典
|
||||
|
||||
Returns:
|
||||
配置字典的副本
|
||||
"""
|
||||
return self._data.copy()
|
||||
|
||||
def __getitem__(self, key: str) -> Any:
|
||||
"""支持字典式访问"""
|
||||
value = self.get(key)
|
||||
if value is None:
|
||||
raise KeyError(f"配置键不存在: {key}")
|
||||
return value
|
||||
|
||||
def __setitem__(self, key: str, value: Any) -> None:
|
||||
"""支持字典式赋值"""
|
||||
self.set(key, value)
|
||||
|
||||
def __contains__(self, key: str) -> bool:
|
||||
"""支持 in 操作"""
|
||||
return self.get(key) is not None
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Config(file={self._config_file}, keys={len(self._data)})"
|
||||
|
||||
@staticmethod
|
||||
def _merge_dict(base: Dict, override: Dict) -> None:
|
||||
"""
|
||||
递归合并字典(原地修改 base)
|
||||
|
||||
Args:
|
||||
base: 基础字典
|
||||
override: 覆盖字典
|
||||
"""
|
||||
for key, value in override.items():
|
||||
if key in base and isinstance(base[key], dict) and isinstance(value, dict):
|
||||
Config._merge_dict(base[key], value)
|
||||
else:
|
||||
base[key] = value
|
||||
|
||||
|
||||
# 全局配置实例(默认无服务名,加载全局配置)
|
||||
settings = Settings()
|
||||
# 全局配置实例
|
||||
_global_config: Optional[Config] = None
|
||||
|
||||
|
||||
# 便捷函数
|
||||
def get_settings(service_name: str | None = None) -> Settings:
|
||||
def get_config() -> Config:
|
||||
"""
|
||||
获取配置实例
|
||||
|
||||
Args:
|
||||
service_name: 服务名称,如 "data_service"、"qmt_service" 等
|
||||
获取全局配置实例(单例模式)
|
||||
|
||||
Returns:
|
||||
Settings 实例
|
||||
全局配置对象
|
||||
|
||||
Examples:
|
||||
>>> from src.core.config import get_config
|
||||
>>> config = get_config()
|
||||
>>> db_host = config.get('database.host')
|
||||
"""
|
||||
return Settings(service_name)
|
||||
global _global_config
|
||||
|
||||
if _global_config is None:
|
||||
# 从环境变量读取配置文件
|
||||
config_file = os.environ.get("CONFIG_FILE")
|
||||
|
||||
if config_file:
|
||||
_global_config = Config().load_with_global(config_file)
|
||||
else:
|
||||
# 默认加载全局配置
|
||||
_global_config = Config("configs/global.yaml")
|
||||
|
||||
return _global_config
|
||||
|
||||
|
||||
def reload_settings() -> Settings:
|
||||
"""重新加载全局配置"""
|
||||
global settings
|
||||
settings = Settings()
|
||||
return settings
|
||||
def set_config(config: Config) -> None:
|
||||
"""
|
||||
设置全局配置实例
|
||||
|
||||
Args:
|
||||
config: 配置对象
|
||||
"""
|
||||
global _global_config
|
||||
_global_config = config
|
||||
|
||||
@ -1,273 +0,0 @@
|
||||
"""
|
||||
配置管理工具类
|
||||
|
||||
统一管理配置文件的读取、保存和合并
|
||||
配置加载优先级(从低到高):
|
||||
1. global.yaml - 全局公共配置
|
||||
2. services/{service_name}.yaml - 服务独立配置
|
||||
3. 环境变量 - 运行时覆盖
|
||||
|
||||
使用示例:
|
||||
# 加载配置
|
||||
config = ConfigManager.load("data_service")
|
||||
|
||||
# 获取配置值
|
||||
port = config.get("service.port", 8020)
|
||||
|
||||
# 修改并保存配置
|
||||
config.set("service.port", 8021)
|
||||
config.save()
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
class ConfigManager:
|
||||
"""配置管理器"""
|
||||
|
||||
def __init__(self, service_name: Optional[str] = None):
|
||||
"""
|
||||
初始化配置管理器
|
||||
|
||||
Args:
|
||||
service_name: 服务名称,如 "data_service"、"qmt_service" 等
|
||||
"""
|
||||
self.service_name = service_name
|
||||
self.project_root = self._get_project_root()
|
||||
self.configs_dir = self.project_root / "configs"
|
||||
|
||||
# 支持从环境变量指定配置文件(用于多环境)
|
||||
env_config_file = os.getenv("CONFIG_FILE")
|
||||
if env_config_file:
|
||||
# 使用环境变量指定的配置文件
|
||||
self.env_config_path = self.project_root / env_config_file
|
||||
else:
|
||||
self.env_config_path = None
|
||||
|
||||
self.global_config_path = self.configs_dir / "global.yaml"
|
||||
self.service_config_path = (
|
||||
self.configs_dir / "services" / f"{service_name}.yaml"
|
||||
if service_name
|
||||
else None
|
||||
)
|
||||
|
||||
# 存储合并后的配置
|
||||
self._config: dict[str, Any] = {}
|
||||
|
||||
# 加载配置
|
||||
self._load()
|
||||
|
||||
@staticmethod
|
||||
def _get_project_root() -> Path:
|
||||
"""获取项目根目录"""
|
||||
current = Path(__file__).resolve()
|
||||
for parent in [current] + list(current.parents):
|
||||
if (parent / "configs").is_dir():
|
||||
return parent
|
||||
return Path.cwd()
|
||||
|
||||
def _load(self) -> None:
|
||||
"""加载配置(按优先级合并)"""
|
||||
# 优先级1: 环境配置文件(如果指定)
|
||||
if self.env_config_path and self.env_config_path.exists():
|
||||
self._config = self._load_yaml(self.env_config_path)
|
||||
else:
|
||||
# 优先级2: 加载全局配置
|
||||
self._config = self._load_yaml(self.global_config_path)
|
||||
|
||||
# 优先级3: 加载服务配置并合并
|
||||
if self.service_config_path and self.service_config_path.exists():
|
||||
service_config = self._load_yaml(self.service_config_path)
|
||||
self._deep_merge(self._config, service_config)
|
||||
|
||||
# 优先级4: 环境变量覆盖(格式:QTRADE_DATABASE_HOST=127.0.0.1)
|
||||
self._apply_env_overrides()
|
||||
|
||||
def _load_yaml(self, path: Path) -> dict[str, Any]:
|
||||
"""加载 YAML 文件"""
|
||||
if not path.exists():
|
||||
return {}
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return yaml.safe_load(f) or {}
|
||||
|
||||
def _deep_merge(self, base: dict, override: dict) -> None:
|
||||
"""深度合并字典(override 覆盖 base)"""
|
||||
for key, value in override.items():
|
||||
if key in base and isinstance(base[key], dict) and isinstance(value, dict):
|
||||
self._deep_merge(base[key], value)
|
||||
else:
|
||||
base[key] = value
|
||||
|
||||
def _apply_env_overrides(self) -> None:
|
||||
"""应用环境变量覆盖(格式:QTRADE_DATABASE_HOST)"""
|
||||
prefix = "QTRADE_"
|
||||
for env_key, env_value in os.environ.items():
|
||||
if not env_key.startswith(prefix):
|
||||
continue
|
||||
|
||||
# 转换环境变量为配置路径
|
||||
# QTRADE_DATABASE_HOST -> database.host
|
||||
config_path = env_key[len(prefix) :].lower().replace("_", ".")
|
||||
|
||||
# 尝试智能类型转换
|
||||
typed_value = self._convert_env_value(env_value, config_path)
|
||||
self.set(config_path, typed_value)
|
||||
|
||||
def _convert_env_value(self, value: str, key: str) -> Any:
|
||||
"""
|
||||
智能转换环境变量值类型
|
||||
|
||||
Args:
|
||||
value: 环境变量字符串值
|
||||
key: 配置键路径
|
||||
|
||||
Returns:
|
||||
转换后的值
|
||||
"""
|
||||
# 获取原始配置值,用于判断类型
|
||||
original = self.get(key)
|
||||
|
||||
# 如果原始值是整数,尝试转换为整数
|
||||
if isinstance(original, int):
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# 如果原始值是浮点数,尝试转换为浮点数
|
||||
if isinstance(original, float):
|
||||
try:
|
||||
return float(value)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# 如果原始值是布尔值,转换为布尔值
|
||||
if isinstance(original, bool):
|
||||
return value.lower() in ("true", "1", "yes", "on")
|
||||
|
||||
# 默认返回字符串
|
||||
return value
|
||||
|
||||
def get(self, key: str, default: Any = None) -> Any:
|
||||
"""
|
||||
获取配置值(支持点分路径)
|
||||
|
||||
Args:
|
||||
key: 配置键,支持点分路径,如 "database.host"
|
||||
default: 默认值
|
||||
|
||||
Returns:
|
||||
配置值
|
||||
"""
|
||||
keys = key.split(".")
|
||||
value = self._config
|
||||
|
||||
for k in keys:
|
||||
if isinstance(value, dict) and k in value:
|
||||
value = value[k]
|
||||
else:
|
||||
return default
|
||||
|
||||
return value
|
||||
|
||||
def set(self, key: str, value: Any) -> None:
|
||||
"""
|
||||
设置配置值(支持点分路径)
|
||||
|
||||
Args:
|
||||
key: 配置键,支持点分路径,如 "database.host"
|
||||
value: 配置值
|
||||
"""
|
||||
keys = key.split(".")
|
||||
config = self._config
|
||||
|
||||
for k in keys[:-1]:
|
||||
if k not in config or not isinstance(config[k], dict):
|
||||
config[k] = {}
|
||||
config = config[k]
|
||||
|
||||
config[keys[-1]] = value
|
||||
|
||||
def get_all(self) -> dict[str, Any]:
|
||||
"""获取所有配置"""
|
||||
return self._config.copy()
|
||||
|
||||
def save(self, target: str = "service") -> None:
|
||||
"""
|
||||
保存配置到文件
|
||||
|
||||
Args:
|
||||
target: 保存目标,可选 "global" 或 "service"(默认)
|
||||
"""
|
||||
if target == "global":
|
||||
save_path = self.global_config_path
|
||||
elif target == "service" and self.service_config_path:
|
||||
save_path = self.service_config_path
|
||||
else:
|
||||
raise ValueError(f"无效的保存目标: {target}")
|
||||
|
||||
# 确保目录存在
|
||||
save_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 保存到 YAML
|
||||
with open(save_path, "w", encoding="utf-8") as f:
|
||||
yaml.dump(self._config, f, allow_unicode=True, sort_keys=False)
|
||||
|
||||
@classmethod
|
||||
def load(cls, service_name: Optional[str] = None) -> "ConfigManager":
|
||||
"""
|
||||
加载配置(类方法便捷入口)
|
||||
|
||||
Args:
|
||||
service_name: 服务名称
|
||||
|
||||
Returns:
|
||||
ConfigManager 实例
|
||||
"""
|
||||
return cls(service_name)
|
||||
|
||||
def __getitem__(self, key: str) -> Any:
|
||||
"""支持字典式访问"""
|
||||
return self.get(key)
|
||||
|
||||
def __setitem__(self, key: str, value: Any) -> None:
|
||||
"""支持字典式赋值"""
|
||||
self.set(key, value)
|
||||
|
||||
|
||||
# 便捷函数
|
||||
|
||||
|
||||
def load_config(service_name: Optional[str] = None) -> ConfigManager:
|
||||
"""
|
||||
加载配置
|
||||
|
||||
Args:
|
||||
service_name: 服务名称,如 "data_service"
|
||||
|
||||
Returns:
|
||||
ConfigManager 实例
|
||||
"""
|
||||
return ConfigManager.load(service_name)
|
||||
|
||||
|
||||
def get_config_value(
|
||||
key: str, service_name: Optional[str] = None, default: Any = None
|
||||
) -> Any:
|
||||
"""
|
||||
快速获取配置值
|
||||
|
||||
Args:
|
||||
key: 配置键
|
||||
service_name: 服务名称
|
||||
default: 默认值
|
||||
|
||||
Returns:
|
||||
配置值
|
||||
"""
|
||||
config = ConfigManager.load(service_name)
|
||||
return config.get(key, default)
|
||||
@ -1,31 +0,0 @@
|
||||
"""
|
||||
常量定义模块
|
||||
|
||||
包含:
|
||||
- kline: K线相关常量
|
||||
"""
|
||||
|
||||
from .kline import (
|
||||
KlinePeriod,
|
||||
KLINE_PERIOD_CONFIG,
|
||||
SUPPORTED_PERIODS,
|
||||
get_kline_config,
|
||||
get_kline_table_name,
|
||||
get_kline_interval,
|
||||
get_xt_period,
|
||||
get_kline_models,
|
||||
get_kline_model,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# K线常量
|
||||
"KlinePeriod",
|
||||
"KLINE_PERIOD_CONFIG",
|
||||
"SUPPORTED_PERIODS",
|
||||
"get_kline_config",
|
||||
"get_kline_table_name",
|
||||
"get_kline_interval",
|
||||
"get_xt_period",
|
||||
"get_kline_models",
|
||||
"get_kline_model",
|
||||
]
|
||||
@ -1,178 +0,0 @@
|
||||
"""
|
||||
K线相关常量定义
|
||||
|
||||
统一管理所有K线周期相关的配置和常量
|
||||
"""
|
||||
|
||||
from datetime import timedelta
|
||||
from enum import Enum
|
||||
from typing import Any, TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..models.base import Base
|
||||
|
||||
|
||||
class KlinePeriod(str, Enum):
|
||||
"""K线周期枚举"""
|
||||
|
||||
M1 = "1m"
|
||||
M5 = "5m"
|
||||
M15 = "15m"
|
||||
M30 = "30m"
|
||||
M60 = "60m"
|
||||
D1 = "1d"
|
||||
W1 = "1w"
|
||||
|
||||
|
||||
# K线周期配置(包含所有元数据)
|
||||
KLINE_PERIOD_CONFIG: dict[str, dict[str, Any]] = {
|
||||
"1m": {
|
||||
"label": "1分钟",
|
||||
"interval": timedelta(minutes=1),
|
||||
"interval_minutes": 1,
|
||||
"xt_period": "1m", # XtQuant 周期标识
|
||||
"table_name": "kline_1m",
|
||||
},
|
||||
"5m": {
|
||||
"label": "5分钟",
|
||||
"interval": timedelta(minutes=5),
|
||||
"interval_minutes": 5,
|
||||
"xt_period": "5m",
|
||||
"table_name": "kline_5m",
|
||||
},
|
||||
"15m": {
|
||||
"label": "15分钟",
|
||||
"interval": timedelta(minutes=15),
|
||||
"interval_minutes": 15,
|
||||
"xt_period": "15m",
|
||||
"table_name": "kline_15m",
|
||||
},
|
||||
"30m": {
|
||||
"label": "30分钟",
|
||||
"interval": timedelta(minutes=30),
|
||||
"interval_minutes": 30,
|
||||
"xt_period": "30m",
|
||||
"table_name": "kline_30m",
|
||||
},
|
||||
"60m": {
|
||||
"label": "60分钟",
|
||||
"interval": timedelta(minutes=60),
|
||||
"interval_minutes": 60,
|
||||
"xt_period": "60m",
|
||||
"table_name": "kline_60m",
|
||||
},
|
||||
"1d": {
|
||||
"label": "日K",
|
||||
"interval": timedelta(days=1),
|
||||
"interval_minutes": 1440,
|
||||
"xt_period": "1d",
|
||||
"table_name": "kline_1d",
|
||||
},
|
||||
"1w": {
|
||||
"label": "周K",
|
||||
"interval": timedelta(weeks=1),
|
||||
"interval_minutes": 10080,
|
||||
"xt_period": "1w",
|
||||
"table_name": "kline_1w",
|
||||
},
|
||||
}
|
||||
|
||||
# 支持的周期列表
|
||||
SUPPORTED_PERIODS = list(KLINE_PERIOD_CONFIG.keys())
|
||||
|
||||
|
||||
def get_kline_config(period: str) -> dict[str, Any]:
|
||||
"""
|
||||
获取K线周期配置
|
||||
|
||||
Args:
|
||||
period: 周期 (1m, 5m, 15m, 30m, 60m, 1d, 1w)
|
||||
|
||||
Returns:
|
||||
配置字典
|
||||
|
||||
Raises:
|
||||
ValueError: 不支持的周期
|
||||
"""
|
||||
if period not in KLINE_PERIOD_CONFIG:
|
||||
raise ValueError(f"不支持的K线周期: {period}, 支持: {SUPPORTED_PERIODS}")
|
||||
return KLINE_PERIOD_CONFIG[period]
|
||||
|
||||
|
||||
def get_kline_table_name(period: str) -> str:
|
||||
"""
|
||||
获取K线周期对应的表名
|
||||
|
||||
Args:
|
||||
period: 周期 (1m, 5m, ...)
|
||||
|
||||
Returns:
|
||||
表名
|
||||
"""
|
||||
return get_kline_config(period)["table_name"]
|
||||
|
||||
|
||||
def get_kline_interval(period: str) -> timedelta:
|
||||
"""
|
||||
获取K线周期时间间隔
|
||||
|
||||
Args:
|
||||
period: 周期 (1m, 5m, ...)
|
||||
|
||||
Returns:
|
||||
时间间隔
|
||||
"""
|
||||
return get_kline_config(period)["interval"]
|
||||
|
||||
|
||||
def get_xt_period(period: str) -> str:
|
||||
"""
|
||||
获取XtQuant周期标识
|
||||
|
||||
Args:
|
||||
period: 周期 (1m, 5m, ...)
|
||||
|
||||
Returns:
|
||||
XtQuant周期标识
|
||||
"""
|
||||
return get_kline_config(period)["xt_period"]
|
||||
|
||||
|
||||
def get_kline_models() -> dict[str, type["Base"]]:
|
||||
"""
|
||||
获取K线模型映射表
|
||||
|
||||
延迟导入避免循环依赖
|
||||
|
||||
Returns:
|
||||
周期到模型类的映射
|
||||
"""
|
||||
from ..models.kline import Kline1m, Kline5m, Kline15m, Kline30m, Kline60m, Kline1d
|
||||
|
||||
return {
|
||||
"1m": Kline1m,
|
||||
"5m": Kline5m,
|
||||
"15m": Kline15m,
|
||||
"30m": Kline30m,
|
||||
"60m": Kline60m,
|
||||
"1d": Kline1d,
|
||||
}
|
||||
|
||||
|
||||
def get_kline_model(period: str) -> type["Base"]:
|
||||
"""
|
||||
根据周期获取K线模型类
|
||||
|
||||
Args:
|
||||
period: 周期 (1m, 5m, 15m, 30m, 60m, 1d)
|
||||
|
||||
Returns:
|
||||
对应的K线模型类
|
||||
|
||||
Raises:
|
||||
ValueError: 不支持的周期
|
||||
"""
|
||||
models = get_kline_models()
|
||||
if period not in models:
|
||||
raise ValueError(f"不支持的K线周期: {period}, 支持: {SUPPORTED_PERIODS}")
|
||||
return models[period]
|
||||
@ -1,153 +0,0 @@
|
||||
"""
|
||||
QTrade 数据库模块
|
||||
|
||||
提供 SQLAlchemy 2.0 异步数据库操作:
|
||||
- 异步会话管理
|
||||
- 连接池配置
|
||||
- 基础模型定义
|
||||
"""
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import AsyncIterator, Optional
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
AsyncEngine,
|
||||
AsyncSession,
|
||||
async_sessionmaker,
|
||||
create_async_engine,
|
||||
)
|
||||
|
||||
from .config import settings
|
||||
from .logger import get_logger
|
||||
from .models.base import Base # 从 models 导入 Base
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class Database:
|
||||
"""
|
||||
异步数据库管理器
|
||||
|
||||
提供连接池管理和会话管理
|
||||
"""
|
||||
|
||||
_instance: Optional["Database"] = None
|
||||
_engine: Optional[AsyncEngine] = None
|
||||
_session_factory: Optional[async_sessionmaker[AsyncSession]] = None
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
return cls._instance
|
||||
|
||||
async def connect(self) -> None:
|
||||
"""建立数据库连接"""
|
||||
if self._engine is not None:
|
||||
return
|
||||
|
||||
self._engine = create_async_engine(
|
||||
settings.database.url,
|
||||
pool_size=settings.database.pool_size,
|
||||
pool_recycle=settings.database.pool_recycle,
|
||||
echo=settings.database.echo,
|
||||
pool_pre_ping=True, # 连接健康检查
|
||||
)
|
||||
|
||||
self._session_factory = async_sessionmaker(
|
||||
bind=self._engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
autoflush=False,
|
||||
)
|
||||
|
||||
# 测试连接
|
||||
try:
|
||||
async with self._engine.begin() as conn:
|
||||
await conn.execute(text("SELECT 1"))
|
||||
logger.info(
|
||||
f"数据库连接成功: {settings.database.host}:{settings.database.port}"
|
||||
f"/{settings.database.database}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"数据库连接失败: {e}")
|
||||
raise
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
"""断开数据库连接"""
|
||||
if self._engine:
|
||||
await self._engine.dispose()
|
||||
self._engine = None
|
||||
self._session_factory = None
|
||||
logger.info("数据库连接已断开")
|
||||
|
||||
@property
|
||||
def engine(self) -> AsyncEngine:
|
||||
"""获取数据库引擎"""
|
||||
if self._engine is None:
|
||||
raise RuntimeError("数据库未连接,请先调用 connect()")
|
||||
return self._engine
|
||||
|
||||
@property
|
||||
def session_factory(self) -> async_sessionmaker[AsyncSession]:
|
||||
"""获取会话工厂"""
|
||||
if self._session_factory is None:
|
||||
raise RuntimeError("数据库未连接,请先调用 connect()")
|
||||
return self._session_factory
|
||||
|
||||
@asynccontextmanager
|
||||
async def session(self) -> AsyncIterator[AsyncSession]:
|
||||
"""
|
||||
获取数据库会话(上下文管理器)
|
||||
|
||||
使用方法:
|
||||
async with db.session() as session:
|
||||
result = await session.execute(select(User))
|
||||
"""
|
||||
session = self.session_factory()
|
||||
try:
|
||||
yield session
|
||||
await session.commit()
|
||||
except Exception:
|
||||
await session.rollback()
|
||||
raise
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
async def create_tables(self) -> None:
|
||||
"""创建所有表"""
|
||||
async with self.engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
logger.info("数据库表创建完成")
|
||||
|
||||
async def drop_tables(self) -> None:
|
||||
"""删除所有表(危险操作,仅用于测试)"""
|
||||
async with self.engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.drop_all)
|
||||
logger.warning("数据库表已删除")
|
||||
|
||||
|
||||
# 全局数据库实例
|
||||
db = Database()
|
||||
|
||||
|
||||
# 便捷函数
|
||||
async def get_db() -> Database:
|
||||
"""获取数据库实例(确保已连接)"""
|
||||
if db._engine is None:
|
||||
await db.connect()
|
||||
return db
|
||||
|
||||
|
||||
async def get_session() -> AsyncIterator[AsyncSession]:
|
||||
"""
|
||||
获取数据库会话(用于 FastAPI 依赖注入)
|
||||
|
||||
使用方法:
|
||||
@app.get("/users")
|
||||
async def get_users(session: AsyncSession = Depends(get_session)):
|
||||
result = await session.execute(select(User))
|
||||
return result.scalars().all()
|
||||
"""
|
||||
async with db.session() as session:
|
||||
yield session
|
||||
@ -1,108 +1,196 @@
|
||||
"""
|
||||
QTrade 日志模块
|
||||
|
||||
提供统一的日志配置:
|
||||
- 控制台输出
|
||||
- 文件输出(按大小轮转)
|
||||
- 自定义格式
|
||||
日志工具类
|
||||
支持四个级别的日志记录:DEBUG, INFO, WARNING, ERROR
|
||||
"""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from typing import Optional
|
||||
|
||||
from .config import settings
|
||||
from .config import get_config
|
||||
|
||||
|
||||
def setup_logging(
|
||||
name: Optional[str] = None,
|
||||
level: Optional[str] = None,
|
||||
) -> logging.Logger:
|
||||
class Logger:
|
||||
"""
|
||||
配置日志
|
||||
日志管理类
|
||||
|
||||
Args:
|
||||
name: 日志名称,为 None 时返回根日志
|
||||
level: 日志级别,为 None 时使用配置文件设置
|
||||
|
||||
Returns:
|
||||
配置好的 Logger 实例
|
||||
功能:
|
||||
- 支持四个日志级别:DEBUG, INFO, WARNING, ERROR
|
||||
- 同时输出到控制台和文件
|
||||
- 支持日志轮转(按文件大小)
|
||||
- 从配置文件读取日志设置
|
||||
"""
|
||||
# 获取日志配置
|
||||
log_level = level or settings.logging.level
|
||||
log_format = settings.logging.format
|
||||
|
||||
# 创建日志器
|
||||
logger = logging.getLogger(name)
|
||||
_instances = {} # 存储不同名称的 logger 实例
|
||||
|
||||
# 如果已经配置过,直接返回
|
||||
if logger.handlers:
|
||||
return logger
|
||||
def __init__(self, name: str = "QTrade"):
|
||||
"""
|
||||
初始化日志对象
|
||||
|
||||
logger.setLevel(getattr(logging, log_level.upper()))
|
||||
Args:
|
||||
name: 日志名称,用于区分不同模块
|
||||
"""
|
||||
self.name = name
|
||||
self.logger = logging.getLogger(name)
|
||||
|
||||
# 创建格式化器
|
||||
formatter = logging.Formatter(log_format)
|
||||
# 避免重复添加 handler
|
||||
if not self.logger.handlers:
|
||||
self._setup_logger()
|
||||
|
||||
# 控制台处理器
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setFormatter(formatter)
|
||||
logger.addHandler(console_handler)
|
||||
def _setup_logger(self):
|
||||
"""配置日志"""
|
||||
# 读取配置
|
||||
config = get_config()
|
||||
|
||||
# 文件处理器
|
||||
if settings.logging.file.enabled:
|
||||
logs_dir = settings.logs_dir
|
||||
log_file = logs_dir / f"{name or 'qtrade'}.log"
|
||||
# 日志级别
|
||||
level_str = config.get("logging.level", "INFO")
|
||||
level = getattr(logging, level_str.upper(), logging.INFO)
|
||||
self.logger.setLevel(level)
|
||||
|
||||
file_handler = RotatingFileHandler(
|
||||
log_file,
|
||||
maxBytes=settings.logging.file.max_size,
|
||||
backupCount=settings.logging.file.backup_count,
|
||||
encoding="utf-8",
|
||||
# 日志格式
|
||||
log_format = config.get(
|
||||
"logging.format", "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
)
|
||||
file_handler.setFormatter(formatter)
|
||||
logger.addHandler(file_handler)
|
||||
formatter = logging.Formatter(log_format)
|
||||
|
||||
# 防止日志向上传递
|
||||
logger.propagate = False
|
||||
# 控制台处理器
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(level)
|
||||
console_handler.setFormatter(formatter)
|
||||
self.logger.addHandler(console_handler)
|
||||
|
||||
return logger
|
||||
# 文件处理器
|
||||
if config.get("logging.file.enabled", True):
|
||||
log_path = config.get("logging.file.path", "logs")
|
||||
max_size = config.get("logging.file.max_size", 10485760) # 10MB
|
||||
backup_count = config.get("logging.file.backup_count", 5)
|
||||
|
||||
# 创建日志目录
|
||||
log_dir = Path(log_path)
|
||||
if not log_dir.is_absolute():
|
||||
# 相对路径,相对于项目根目录
|
||||
project_root = Path(__file__).parent.parent.parent
|
||||
log_dir = project_root / log_path
|
||||
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 日志文件路径
|
||||
log_file = log_dir / f"{self.name}.log"
|
||||
|
||||
# 使用 RotatingFileHandler 进行日志轮转
|
||||
file_handler = RotatingFileHandler(
|
||||
log_file, maxBytes=max_size, backupCount=backup_count, encoding="utf-8"
|
||||
)
|
||||
file_handler.setLevel(level)
|
||||
file_handler.setFormatter(formatter)
|
||||
self.logger.addHandler(file_handler)
|
||||
|
||||
def debug(self, message: str, *args, **kwargs):
|
||||
"""记录 DEBUG 级别日志"""
|
||||
self.logger.debug(message, *args, **kwargs)
|
||||
|
||||
def info(self, message: str, *args, **kwargs):
|
||||
"""记录 INFO 级别日志"""
|
||||
self.logger.info(message, *args, **kwargs)
|
||||
|
||||
def warning(self, message: str, *args, **kwargs):
|
||||
"""记录 WARNING 级别日志"""
|
||||
self.logger.warning(message, *args, **kwargs)
|
||||
|
||||
def error(self, message: str, *args, **kwargs):
|
||||
"""记录 ERROR 级别日志"""
|
||||
self.logger.error(message, *args, **kwargs)
|
||||
|
||||
def exception(self, message: str, *args, **kwargs):
|
||||
"""记录 ERROR 级别日志,并包含异常堆栈信息"""
|
||||
self.logger.exception(message, *args, **kwargs)
|
||||
|
||||
@classmethod
|
||||
def get_logger(cls, name: str = "QTrade") -> "Logger":
|
||||
"""
|
||||
获取指定名称的日志实例(单例模式)
|
||||
|
||||
Args:
|
||||
name: 日志名称
|
||||
|
||||
Returns:
|
||||
Logger 实例
|
||||
|
||||
Examples:
|
||||
>>> logger = Logger.get_logger("QTrade")
|
||||
>>> logger.info("系统启动")
|
||||
"""
|
||||
if name not in cls._instances:
|
||||
cls._instances[name] = cls(name)
|
||||
return cls._instances[name]
|
||||
|
||||
|
||||
def get_logger(name: str) -> logging.Logger:
|
||||
# 全局日志实例
|
||||
_global_logger: Optional[Logger] = None
|
||||
|
||||
|
||||
def get_logger(name: str = "QTrade") -> Logger:
|
||||
"""
|
||||
获取日志器
|
||||
获取日志实例
|
||||
|
||||
Args:
|
||||
name: 日志名称,通常使用 __name__
|
||||
name: 日志名称,用于区分不同模块
|
||||
|
||||
Returns:
|
||||
Logger 实例
|
||||
|
||||
使用示例:
|
||||
from core.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
logger.info("Hello World")
|
||||
Examples:
|
||||
>>> from src.core import get_logger
|
||||
>>> logger = get_logger("Strategy")
|
||||
>>> logger.info("策略初始化完成")
|
||||
>>> logger.error("策略执行失败")
|
||||
"""
|
||||
return setup_logging(name)
|
||||
return Logger.get_logger(name)
|
||||
|
||||
|
||||
class LoggerMixin:
|
||||
def set_log_level(level: str):
|
||||
"""
|
||||
日志混入类
|
||||
动态设置日志级别
|
||||
|
||||
为类提供便捷的日志访问
|
||||
Args:
|
||||
level: 日志级别 DEBUG, INFO, WARNING, ERROR
|
||||
|
||||
使用示例:
|
||||
class MyClass(LoggerMixin):
|
||||
def do_something(self):
|
||||
self.logger.info("Doing something")
|
||||
Examples:
|
||||
>>> from src.core import set_log_level
|
||||
>>> set_log_level("DEBUG")
|
||||
"""
|
||||
level_value = getattr(logging, level.upper(), logging.INFO)
|
||||
|
||||
@property
|
||||
def logger(self) -> logging.Logger:
|
||||
if not hasattr(self, "_logger"):
|
||||
self._logger = get_logger(self.__class__.__name__)
|
||||
return self._logger
|
||||
# 更新所有已创建的 logger 实例
|
||||
for logger_instance in Logger._instances.values():
|
||||
logger_instance.logger.setLevel(level_value)
|
||||
for handler in logger_instance.logger.handlers:
|
||||
handler.setLevel(level_value)
|
||||
|
||||
|
||||
# 便捷函数
|
||||
def debug(message: str, *args, **kwargs):
|
||||
"""记录 DEBUG 级别日志"""
|
||||
get_logger().debug(message, *args, **kwargs)
|
||||
|
||||
|
||||
def info(message: str, *args, **kwargs):
|
||||
"""记录 INFO 级别日志"""
|
||||
get_logger().info(message, *args, **kwargs)
|
||||
|
||||
|
||||
def warning(message: str, *args, **kwargs):
|
||||
"""记录 WARNING 级别日志"""
|
||||
get_logger().warning(message, *args, **kwargs)
|
||||
|
||||
|
||||
def error(message: str, *args, **kwargs):
|
||||
"""记录 ERROR 级别日志"""
|
||||
get_logger().error(message, *args, **kwargs)
|
||||
|
||||
|
||||
def exception(message: str, *args, **kwargs):
|
||||
"""记录 ERROR 级别日志,并包含异常堆栈信息"""
|
||||
get_logger().exception(message, *args, **kwargs)
|
||||
|
||||
@ -1,78 +1,50 @@
|
||||
"""
|
||||
QTrade ORM 模型
|
||||
|
||||
数据库 ORM 模型模块,定义所有数据库表结构:
|
||||
- base: ORM 基类和通用混入
|
||||
- common: 通用枚举类型
|
||||
- kline: K线数据模型
|
||||
- pairing: 股票-策略配对模型
|
||||
- order: 订单模型
|
||||
- position: 持仓模型
|
||||
- signal: 交易信号模型
|
||||
- balance_log: 资金变动日志模型
|
||||
QTrade 核心对象模型
|
||||
"""
|
||||
|
||||
# ORM 基类
|
||||
from .base import Base, TimestampMixin
|
||||
|
||||
# 通用枚举
|
||||
from .common import TradeSide
|
||||
|
||||
# K线模型
|
||||
from .kline import (
|
||||
KlineBase,
|
||||
Kline1m,
|
||||
Kline5m,
|
||||
Kline15m,
|
||||
Kline30m,
|
||||
Kline60m,
|
||||
Kline1d,
|
||||
get_kline_model,
|
||||
# 枚举类型
|
||||
from .enums import (
|
||||
OrderSide,
|
||||
OrderType,
|
||||
OrderStatus,
|
||||
PositionDirection,
|
||||
SignalType,
|
||||
ProductType,
|
||||
Exchange,
|
||||
)
|
||||
|
||||
# 配对模型
|
||||
from .pairing import Pairing, PairingStatus
|
||||
# 市场数据对象
|
||||
from .tick import Tick
|
||||
from .kline import Kline
|
||||
|
||||
# 订单模型
|
||||
from .order import Order, OrderType, OrderStatus
|
||||
# 交易对象
|
||||
from .order import Order
|
||||
from .trade import Trade
|
||||
|
||||
# 持仓模型
|
||||
# 持仓账户对象
|
||||
from .position import Position
|
||||
from .account import Account
|
||||
|
||||
# 信号模型
|
||||
from .signal import Signal, SignalStatus
|
||||
|
||||
# 资金日志模型
|
||||
from .balance_log import BalanceLog, BalanceLogType
|
||||
# 策略标的对象
|
||||
from .signal import Signal
|
||||
from .symbol import Symbol
|
||||
|
||||
__all__ = [
|
||||
# ORM 基类
|
||||
"Base",
|
||||
"TimestampMixin",
|
||||
# 通用枚举
|
||||
"TradeSide",
|
||||
# K线
|
||||
"KlineBase",
|
||||
"Kline1m",
|
||||
"Kline5m",
|
||||
"Kline15m",
|
||||
"Kline30m",
|
||||
"Kline60m",
|
||||
"Kline1d",
|
||||
"get_kline_model",
|
||||
# 配对
|
||||
"Pairing",
|
||||
"PairingStatus",
|
||||
# 订单
|
||||
"Order",
|
||||
# 枚举
|
||||
"OrderSide",
|
||||
"OrderType",
|
||||
"OrderStatus",
|
||||
# 持仓
|
||||
"PositionDirection",
|
||||
"SignalType",
|
||||
"ProductType",
|
||||
"Exchange",
|
||||
# 对象
|
||||
"Tick",
|
||||
"Kline",
|
||||
"Order",
|
||||
"Trade",
|
||||
"Position",
|
||||
# 信号
|
||||
"Account",
|
||||
"Signal",
|
||||
"SignalStatus",
|
||||
# 资金日志
|
||||
"BalanceLog",
|
||||
"BalanceLogType",
|
||||
"Symbol",
|
||||
]
|
||||
|
||||
48
src/core/models/account.py
Normal file
48
src/core/models/account.py
Normal file
@ -0,0 +1,48 @@
|
||||
"""
|
||||
账户对象
|
||||
"""
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class Account(BaseModel):
|
||||
"""
|
||||
账户(可变)
|
||||
|
||||
示例:
|
||||
account = Account(
|
||||
account_id="ACC_001",
|
||||
total_asset=1000000.0,
|
||||
available_cash=500000.0,
|
||||
update_time=datetime.now()
|
||||
)
|
||||
"""
|
||||
account_id: str = Field(..., description="账户ID", min_length=1)
|
||||
|
||||
# 资金信息
|
||||
total_asset: float = Field(
|
||||
...,
|
||||
description="总资产 = available_cash + frozen_cash + market_value",
|
||||
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)
|
||||
|
||||
# 盈亏信息
|
||||
total_pnl: float = Field(0.0, description="总盈亏")
|
||||
daily_pnl: float = Field(0.0, description="当日盈亏")
|
||||
|
||||
update_time: datetime = Field(..., description="更新时间")
|
||||
|
||||
def model_post_init(self, __context) -> None:
|
||||
"""对象创建后验证总资产一致性"""
|
||||
calculated_total = self.available_cash + self.frozen_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}'
|
||||
)
|
||||
@ -1,92 +0,0 @@
|
||||
"""
|
||||
资金日志 ORM 模型
|
||||
|
||||
包含:
|
||||
- BalanceLogType: 资金变动类型枚举
|
||||
- BalanceLog: 资金变动日志表
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Numeric, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import Base
|
||||
|
||||
|
||||
class BalanceLogType(str, Enum):
|
||||
"""资金变动类型"""
|
||||
|
||||
DEPOSIT = "deposit" # 入金
|
||||
WITHDRAW = "withdraw" # 出金
|
||||
BUY = "buy" # 买入冻结/扣款
|
||||
SELL = "sell" # 卖出到账
|
||||
COMMISSION = "commission" # 手续费
|
||||
DIVIDEND = "dividend" # 分红
|
||||
ADJUST = "adjust" # 人工调整
|
||||
|
||||
|
||||
class BalanceLog(Base):
|
||||
"""
|
||||
资金变动日志表
|
||||
|
||||
记录配对账户的每一笔资金变动
|
||||
"""
|
||||
|
||||
__tablename__ = "balance_logs"
|
||||
|
||||
# 主键
|
||||
id: Mapped[int] = mapped_column(
|
||||
primary_key=True, autoincrement=True, comment="日志ID"
|
||||
)
|
||||
|
||||
# 关联
|
||||
pairing_id: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
ForeignKey("pairings.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
comment="配对ID",
|
||||
)
|
||||
order_id: Mapped[str | None] = mapped_column(String(32), comment="关联订单ID")
|
||||
|
||||
# 变动信息
|
||||
type: Mapped[str] = mapped_column(String(20), nullable=False, comment="变动类型")
|
||||
amount: Mapped[Decimal] = mapped_column(
|
||||
Numeric(16, 2), nullable=False, comment="变动金额"
|
||||
)
|
||||
balance_before: Mapped[Decimal] = mapped_column(
|
||||
Numeric(16, 2), comment="变动前余额"
|
||||
)
|
||||
balance_after: Mapped[Decimal] = mapped_column(Numeric(16, 2), comment="变动后余额")
|
||||
|
||||
# 说明
|
||||
reason: Mapped[str | None] = mapped_column(Text, comment="变动原因")
|
||||
|
||||
# 时间
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.now, comment="创建时间"
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_balance_logs_pairing_id", "pairing_id"),
|
||||
Index("ix_balance_logs_type", "type"),
|
||||
Index("ix_balance_logs_created_at", "created_at"),
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""转换为字典"""
|
||||
return {
|
||||
"id": self.id,
|
||||
"pairing_id": self.pairing_id,
|
||||
"order_id": self.order_id,
|
||||
"type": self.type,
|
||||
"amount": float(self.amount),
|
||||
"balance_before": float(self.balance_before)
|
||||
if self.balance_before
|
||||
else None,
|
||||
"balance_after": float(self.balance_after) if self.balance_after else None,
|
||||
"reason": self.reason,
|
||||
"created_at": self.created_at.isoformat() if self.created_at else None,
|
||||
}
|
||||
@ -1,145 +0,0 @@
|
||||
"""
|
||||
ORM 模型基类
|
||||
|
||||
提供:
|
||||
- Base: SQLAlchemy 声明式基类
|
||||
- ModelMixin: 通用方法混入 (to_dict, to_json, from_dict)
|
||||
- TimestampMixin: 时间戳字段混入
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
from typing import Any, TypeVar
|
||||
|
||||
from sqlalchemy import MetaData
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
# 表命名规范
|
||||
convention = {
|
||||
"ix": "ix_%(column_0_label)s",
|
||||
"uq": "uq_%(table_name)s_%(column_0_name)s",
|
||||
"ck": "ck_%(table_name)s_%(constraint_name)s",
|
||||
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
|
||||
"pk": "pk_%(table_name)s",
|
||||
}
|
||||
|
||||
metadata = MetaData(naming_convention=convention)
|
||||
|
||||
T = TypeVar("T", bound="Base")
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
"""
|
||||
ORM 声明式基类
|
||||
|
||||
所有数据模型继承此类
|
||||
"""
|
||||
|
||||
metadata = metadata
|
||||
|
||||
def to_dict(self, exclude: set[str] | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
转换为字典
|
||||
|
||||
Args:
|
||||
exclude: 要排除的字段名集合
|
||||
|
||||
Returns:
|
||||
字典形式的数据
|
||||
"""
|
||||
exclude = exclude or set()
|
||||
result = {}
|
||||
|
||||
for column in self.__table__.columns:
|
||||
if column.name in exclude:
|
||||
continue
|
||||
|
||||
value = getattr(self, column.name)
|
||||
|
||||
# 类型转换
|
||||
if isinstance(value, datetime):
|
||||
value = value.isoformat()
|
||||
elif isinstance(value, Decimal):
|
||||
value = float(value)
|
||||
elif isinstance(value, Enum):
|
||||
value = value.value
|
||||
|
||||
result[column.name] = value
|
||||
|
||||
return result
|
||||
|
||||
def to_json(
|
||||
self, exclude: set[str] | None = None, indent: int | None = None
|
||||
) -> str:
|
||||
"""
|
||||
转换为 JSON 字符串
|
||||
|
||||
Args:
|
||||
exclude: 要排除的字段名集合
|
||||
indent: JSON 缩进
|
||||
|
||||
Returns:
|
||||
JSON 字符串
|
||||
"""
|
||||
return json.dumps(self.to_dict(exclude), ensure_ascii=False, indent=indent)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls: type[T], data: dict[str, Any]) -> T:
|
||||
"""
|
||||
从字典创建实例
|
||||
|
||||
Args:
|
||||
data: 字典数据
|
||||
|
||||
Returns:
|
||||
模型实例
|
||||
"""
|
||||
# 只取模型定义的字段
|
||||
valid_keys = {c.name for c in cls.__table__.columns}
|
||||
filtered_data = {k: v for k, v in data.items() if k in valid_keys}
|
||||
return cls(**filtered_data)
|
||||
|
||||
def update_from_dict(
|
||||
self, data: dict[str, Any], exclude: set[str] | None = None
|
||||
) -> None:
|
||||
"""
|
||||
从字典更新实例
|
||||
|
||||
Args:
|
||||
data: 字典数据
|
||||
exclude: 要排除的字段名集合
|
||||
"""
|
||||
exclude = exclude or {"id", "created_at"}
|
||||
valid_keys = {c.name for c in self.__table__.columns}
|
||||
|
||||
for key, value in data.items():
|
||||
if key in exclude:
|
||||
continue
|
||||
if key in valid_keys:
|
||||
setattr(self, key, value)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
"""字符串表示"""
|
||||
class_name = self.__class__.__name__
|
||||
pk = getattr(self, "id", None)
|
||||
return f"<{class_name}(id={pk})>"
|
||||
|
||||
|
||||
class TimestampMixin:
|
||||
"""
|
||||
时间戳混入类
|
||||
|
||||
提供 created_at 和 updated_at 字段
|
||||
"""
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
default=datetime.now,
|
||||
comment="创建时间",
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
default=datetime.now,
|
||||
onupdate=datetime.now,
|
||||
comment="更新时间",
|
||||
)
|
||||
@ -1,14 +0,0 @@
|
||||
"""
|
||||
通用枚举类型
|
||||
|
||||
包含跨多个模型使用的共享枚举
|
||||
"""
|
||||
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class TradeSide(str, Enum):
|
||||
"""交易方向(信号和订单共用)"""
|
||||
|
||||
BUY = "buy" # 买入
|
||||
SELL = "sell" # 卖出
|
||||
65
src/core/models/enums.py
Normal file
65
src/core/models/enums.py
Normal file
@ -0,0 +1,65 @@
|
||||
"""
|
||||
枚举类型定义
|
||||
"""
|
||||
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class OrderSide(str, Enum):
|
||||
"""订单方向"""
|
||||
|
||||
BUY = "buy"
|
||||
SELL = "sell"
|
||||
|
||||
|
||||
class OrderType(str, Enum):
|
||||
"""订单类型"""
|
||||
|
||||
LIMIT = "limit" # 限价
|
||||
MARKET = "market" # 市价
|
||||
STOP = "stop" # 止损
|
||||
|
||||
|
||||
class OrderStatus(str, Enum):
|
||||
"""订单状态"""
|
||||
|
||||
PENDING = "pending" # 待成交
|
||||
PARTIAL = "partial" # 部分成交
|
||||
FILLED = "filled" # 完全成交
|
||||
CANCELLED = "cancelled" # 已撤销
|
||||
REJECTED = "rejected" # 已拒绝
|
||||
|
||||
|
||||
class PositionDirection(str, Enum):
|
||||
"""持仓方向"""
|
||||
|
||||
LONG = "long" # 多头
|
||||
SHORT = "short" # 空头(期货)
|
||||
|
||||
|
||||
class SignalType(str, Enum):
|
||||
"""信号类型"""
|
||||
|
||||
BUY = "buy"
|
||||
SELL = "sell"
|
||||
HOLD = "hold"
|
||||
|
||||
|
||||
class ProductType(str, Enum):
|
||||
"""产品类型"""
|
||||
|
||||
STOCK = "stock" # 股票
|
||||
FUTURE = "future" # 期货
|
||||
OPTION = "option" # 期权
|
||||
FUND = "fund" # 基金
|
||||
|
||||
|
||||
class Exchange(str, Enum):
|
||||
"""交易所"""
|
||||
|
||||
SZ = "SZ" # 深交所
|
||||
SH = "SH" # 上交所
|
||||
CFFEX = "CFFEX" # 中金所
|
||||
SHFE = "SHFE" # 上期所
|
||||
DCE = "DCE" # 大商所
|
||||
CZCE = "CZCE" # 郑商所
|
||||
@ -1,173 +1,56 @@
|
||||
"""
|
||||
K线数据 ORM 模型
|
||||
|
||||
包含:
|
||||
- KlineBase: K线基类
|
||||
- Kline1m, Kline5m, Kline15m, Kline30m, Kline60m, Kline1d: 各周期K线表
|
||||
- get_kline_model: 根据周期获取对应的K线模型类
|
||||
K线数据对象
|
||||
"""
|
||||
|
||||
from datetime import datetime as dt
|
||||
from decimal import Decimal
|
||||
from typing import ClassVar, Type
|
||||
|
||||
from sqlalchemy import BigInteger, DateTime, Index, Numeric, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import Base
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
class KlineBase:
|
||||
class Kline(BaseModel):
|
||||
"""
|
||||
K线基类
|
||||
K线数据(不可变)
|
||||
|
||||
定义K线的通用字段,各周期表继承此类
|
||||
"""
|
||||
|
||||
# 周期标识,子类覆盖
|
||||
period: ClassVar[str] = ""
|
||||
|
||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
|
||||
symbol: Mapped[str] = mapped_column(String(20), nullable=False, comment="股票代码")
|
||||
time: Mapped[dt] = mapped_column(DateTime, nullable=False, comment="K线时间")
|
||||
|
||||
open: Mapped[Decimal] = mapped_column(
|
||||
Numeric(10, 3), nullable=False, comment="开盘价"
|
||||
)
|
||||
high: Mapped[Decimal] = mapped_column(
|
||||
Numeric(10, 3), nullable=False, comment="最高价"
|
||||
)
|
||||
low: Mapped[Decimal] = mapped_column(
|
||||
Numeric(10, 3), nullable=False, comment="最低价"
|
||||
)
|
||||
close: Mapped[Decimal] = mapped_column(
|
||||
Numeric(10, 3), nullable=False, comment="收盘价"
|
||||
)
|
||||
volume: Mapped[int] = mapped_column(BigInteger, default=0, comment="成交量")
|
||||
amount: Mapped[Decimal] = mapped_column(
|
||||
Numeric(20, 2), default=Decimal(0), comment="成交额"
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""转换为字典"""
|
||||
return {
|
||||
"id": self.id,
|
||||
"symbol": self.symbol,
|
||||
"time": self.time.isoformat() if self.time else None,
|
||||
"open": float(self.open),
|
||||
"high": float(self.high),
|
||||
"low": float(self.low),
|
||||
"close": float(self.close),
|
||||
"volume": self.volume,
|
||||
"amount": float(self.amount) if self.amount else 0,
|
||||
"period": self.period,
|
||||
}
|
||||
|
||||
|
||||
class Kline1m(KlineBase, Base):
|
||||
"""1分钟K线"""
|
||||
|
||||
__tablename__ = "kline_1m"
|
||||
period: ClassVar[str] = "1m"
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_kline_1m_symbol", "symbol"),
|
||||
Index("ix_kline_1m_time", "time"),
|
||||
Index("ix_kline_1m_symbol_time", "symbol", "time", unique=True),
|
||||
)
|
||||
|
||||
|
||||
class Kline5m(KlineBase, Base):
|
||||
"""5分钟K线"""
|
||||
|
||||
__tablename__ = "kline_5m"
|
||||
period: ClassVar[str] = "5m"
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_kline_5m_symbol", "symbol"),
|
||||
Index("ix_kline_5m_time", "time"),
|
||||
Index("ix_kline_5m_symbol_time", "symbol", "time", unique=True),
|
||||
)
|
||||
|
||||
|
||||
class Kline15m(KlineBase, Base):
|
||||
"""15分钟K线"""
|
||||
|
||||
__tablename__ = "kline_15m"
|
||||
period: ClassVar[str] = "15m"
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_kline_15m_symbol", "symbol"),
|
||||
Index("ix_kline_15m_time", "time"),
|
||||
Index("ix_kline_15m_symbol_time", "symbol", "time", unique=True),
|
||||
)
|
||||
|
||||
|
||||
class Kline30m(KlineBase, Base):
|
||||
"""30分钟K线"""
|
||||
|
||||
__tablename__ = "kline_30m"
|
||||
period: ClassVar[str] = "30m"
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_kline_30m_symbol", "symbol"),
|
||||
Index("ix_kline_30m_time", "time"),
|
||||
Index("ix_kline_30m_symbol_time", "symbol", "time", unique=True),
|
||||
)
|
||||
|
||||
|
||||
class Kline60m(KlineBase, Base):
|
||||
"""60分钟(1小时)K线"""
|
||||
|
||||
__tablename__ = "kline_60m"
|
||||
period: ClassVar[str] = "60m"
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_kline_60m_symbol", "symbol"),
|
||||
Index("ix_kline_60m_time", "time"),
|
||||
Index("ix_kline_60m_symbol_time", "symbol", "time", unique=True),
|
||||
)
|
||||
|
||||
|
||||
class Kline1d(KlineBase, Base):
|
||||
"""日K线"""
|
||||
|
||||
__tablename__ = "kline_1d"
|
||||
period: ClassVar[str] = "1d"
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_kline_1d_symbol", "symbol"),
|
||||
Index("ix_kline_1d_time", "time"),
|
||||
Index("ix_kline_1d_symbol_time", "symbol", "time", unique=True),
|
||||
)
|
||||
|
||||
|
||||
def get_kline_model(period: str) -> Type[KlineBase]:
|
||||
"""
|
||||
根据周期获取对应的K线模型类
|
||||
|
||||
Args:
|
||||
period: K线周期 (1m, 5m, 15m, 30m, 60m, 1d)
|
||||
|
||||
Returns:
|
||||
对应的K线模型类
|
||||
|
||||
Raises:
|
||||
ValueError: 不支持的周期
|
||||
"""
|
||||
period_map = {
|
||||
"1m": Kline1m,
|
||||
"5m": Kline5m,
|
||||
"15m": Kline15m,
|
||||
"30m": Kline30m,
|
||||
"60m": Kline60m,
|
||||
"1d": Kline1d,
|
||||
}
|
||||
|
||||
model = period_map.get(period)
|
||||
if not model:
|
||||
raise ValueError(
|
||||
f"不支持的K线周期: {period},支持的周期: {list(period_map.keys())}"
|
||||
示例:
|
||||
kline = Kline(
|
||||
symbol="000001.SZ",
|
||||
timestamp=datetime.now(),
|
||||
period="1m",
|
||||
open=10.0,
|
||||
high=10.5,
|
||||
low=9.8,
|
||||
close=10.2,
|
||||
volume=10000
|
||||
)
|
||||
"""
|
||||
|
||||
return model
|
||||
symbol: str = Field(..., description="标的代码", min_length=1)
|
||||
timestamp: datetime = Field(..., description="K线结束时间")
|
||||
period: str = Field(..., description="周期:1m, 5m, 1d 等", pattern=r"^\d+[mhdw]$")
|
||||
|
||||
open: float = Field(..., description="开盘价", gt=0)
|
||||
high: float = Field(..., description="最高价", gt=0)
|
||||
low: float = Field(..., description="最低价", gt=0)
|
||||
close: float = Field(..., description="收盘价", gt=0)
|
||||
volume: int = Field(..., description="成交量", ge=0)
|
||||
amount: Optional[float] = Field(None, description="成交额", ge=0)
|
||||
|
||||
# 期货特有(可选)
|
||||
open_interest: Optional[int] = Field(None, description="持仓量", ge=0)
|
||||
|
||||
model_config = ConfigDict(frozen=True) # 不可变
|
||||
|
||||
@field_validator("symbol")
|
||||
@classmethod
|
||||
def validate_symbol(cls, v: str) -> str:
|
||||
"""验证标的代码格式"""
|
||||
if not v or len(v) < 6:
|
||||
raise ValueError("标的代码长度至少6个字符")
|
||||
return v.upper()
|
||||
|
||||
def model_post_init(self, __context) -> None:
|
||||
"""对象创建后验证OHLC关系"""
|
||||
if self.high < max(self.open, self.close, self.low):
|
||||
raise ValueError(f"最高价({self.high})必须 >= max(开盘价, 收盘价, 最低价)")
|
||||
if self.low > min(self.open, self.close, self.high):
|
||||
raise ValueError(f"最低价({self.low})必须 <= min(开盘价, 收盘价, 最高价)")
|
||||
|
||||
@ -1,207 +1,67 @@
|
||||
"""
|
||||
订单 ORM 模型
|
||||
|
||||
包含:
|
||||
- OrderType: 订单类型枚举
|
||||
- OrderStatus: 订单状态枚举
|
||||
- Order: 订单表
|
||||
订单对象
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Numeric, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import Base, TimestampMixin
|
||||
from .common import TradeSide
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from .enums import OrderSide, OrderType, OrderStatus
|
||||
|
||||
|
||||
class OrderType(str, Enum):
|
||||
"""订单类型"""
|
||||
|
||||
LIMIT = "limit" # 限价单
|
||||
MARKET = "market" # 市价单
|
||||
|
||||
|
||||
class OrderStatus(str, Enum):
|
||||
"""订单状态"""
|
||||
|
||||
PENDING = "pending" # 待提交
|
||||
SUBMITTED = "submitted" # 已提交
|
||||
PARTIAL = "partial" # 部分成交
|
||||
FILLED = "filled" # 全部成交
|
||||
CANCELLED = "cancelled" # 已撤销
|
||||
REJECTED = "rejected" # 已拒绝
|
||||
FAILED = "failed" # 失败
|
||||
|
||||
|
||||
class Order(TimestampMixin, Base):
|
||||
class Order(BaseModel):
|
||||
"""
|
||||
订单表
|
||||
订单(可变)
|
||||
|
||||
记录所有交易订单
|
||||
示例:
|
||||
order = Order(
|
||||
order_id="ORD_20240101_001",
|
||||
symbol="000001.SZ",
|
||||
side=OrderSide.BUY,
|
||||
order_type=OrderType.LIMIT,
|
||||
price=10.5,
|
||||
volume=100,
|
||||
create_time=datetime.now(),
|
||||
update_time=datetime.now()
|
||||
)
|
||||
"""
|
||||
|
||||
__tablename__ = "orders"
|
||||
order_id: str = Field(..., description="订单ID(唯一)", min_length=1)
|
||||
symbol: str = Field(..., description="标的代码", min_length=1)
|
||||
side: OrderSide = Field(..., description="方向")
|
||||
order_type: OrderType = Field(..., description="订单类型")
|
||||
price: float = Field(..., description="价格", ge=0)
|
||||
volume: int = Field(..., description="数量", gt=0)
|
||||
filled_volume: int = Field(0, description="已成交数量", ge=0)
|
||||
status: OrderStatus = Field(OrderStatus.PENDING, description="状态")
|
||||
|
||||
# 主键
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, comment="订单ID")
|
||||
create_time: datetime = Field(..., description="创建时间")
|
||||
update_time: datetime = Field(..., description="更新时间")
|
||||
cancel_time: Optional[datetime] = Field(None, description="撤销时间")
|
||||
|
||||
# 外部订单ID (QMT/券商返回)
|
||||
external_id: Mapped[str | None] = mapped_column(String(64), comment="外部订单ID")
|
||||
strategy_name: Optional[str] = Field(None, description="来源策略")
|
||||
remark: Optional[str] = Field(None, description="备注")
|
||||
|
||||
# 关联
|
||||
pairing_id: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
ForeignKey("pairings.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
comment="配对ID",
|
||||
)
|
||||
signal_id: Mapped[str | None] = mapped_column(String(32), comment="信号ID")
|
||||
@field_validator("symbol")
|
||||
@classmethod
|
||||
def validate_symbol(cls, v: str) -> str:
|
||||
"""验证标的代码格式"""
|
||||
if not v or len(v) < 6:
|
||||
raise ValueError("标的代码长度至少6个字符")
|
||||
return v.upper()
|
||||
|
||||
# 订单内容
|
||||
symbol: Mapped[str] = mapped_column(String(20), nullable=False, comment="股票代码")
|
||||
side: Mapped[str] = mapped_column(String(10), nullable=False, comment="订单方向")
|
||||
order_type: Mapped[str] = mapped_column(
|
||||
String(20), default=OrderType.LIMIT.value, comment="订单类型"
|
||||
)
|
||||
price: Mapped[Decimal] = mapped_column(
|
||||
Numeric(10, 3), nullable=False, comment="委托价格"
|
||||
)
|
||||
quantity: Mapped[int] = mapped_column(nullable=False, comment="委托数量")
|
||||
@field_validator("price")
|
||||
@classmethod
|
||||
def validate_price(cls, v: float, info) -> float:
|
||||
"""验证价格(市价单可以为0)"""
|
||||
if info.data.get("order_type") == OrderType.LIMIT and v <= 0:
|
||||
raise ValueError("限价单价格必须大于0")
|
||||
if v < 0:
|
||||
raise ValueError("价格不能为负数")
|
||||
return v
|
||||
|
||||
# 成交信息
|
||||
filled_quantity: Mapped[int] = mapped_column(default=0, comment="成交数量")
|
||||
filled_amount: Mapped[Decimal] = mapped_column(
|
||||
Numeric(16, 2), default=Decimal(0), comment="成交金额"
|
||||
)
|
||||
avg_price: Mapped[Decimal | None] = mapped_column(
|
||||
Numeric(10, 3), comment="成交均价"
|
||||
)
|
||||
commission: Mapped[Decimal] = mapped_column(
|
||||
Numeric(10, 2), default=Decimal(0), comment="手续费"
|
||||
)
|
||||
|
||||
# 状态
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(20), default=OrderStatus.PENDING.value, comment="订单状态"
|
||||
)
|
||||
message: Mapped[str | None] = mapped_column(Text, comment="状态消息")
|
||||
|
||||
# 时间
|
||||
submitted_at: Mapped[datetime | None] = mapped_column(DateTime, comment="提交时间")
|
||||
filled_at: Mapped[datetime | None] = mapped_column(DateTime, comment="成交时间")
|
||||
cancelled_at: Mapped[datetime | None] = mapped_column(DateTime, comment="撤销时间")
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_orders_pairing_id", "pairing_id"),
|
||||
Index("ix_orders_symbol", "symbol"),
|
||||
Index("ix_orders_status", "status"),
|
||||
Index("ix_orders_created_at", "created_at"),
|
||||
Index("ix_orders_external_id", "external_id"),
|
||||
)
|
||||
|
||||
@property
|
||||
def is_active(self) -> bool:
|
||||
"""订单是否活跃(可撤销)"""
|
||||
return self.status in (
|
||||
OrderStatus.PENDING.value,
|
||||
OrderStatus.SUBMITTED.value,
|
||||
OrderStatus.PARTIAL.value,
|
||||
)
|
||||
|
||||
@property
|
||||
def is_finished(self) -> bool:
|
||||
"""订单是否已结束"""
|
||||
return self.status in (
|
||||
OrderStatus.FILLED.value,
|
||||
OrderStatus.CANCELLED.value,
|
||||
OrderStatus.REJECTED.value,
|
||||
OrderStatus.FAILED.value,
|
||||
)
|
||||
|
||||
@property
|
||||
def unfilled_quantity(self) -> int:
|
||||
"""未成交数量"""
|
||||
return self.quantity - self.filled_quantity
|
||||
|
||||
@property
|
||||
def order_amount(self) -> Decimal:
|
||||
"""订单金额"""
|
||||
return self.price * self.quantity
|
||||
|
||||
def fill(
|
||||
self, quantity: int, price: Decimal, commission: Decimal = Decimal(0)
|
||||
) -> None:
|
||||
"""
|
||||
成交处理
|
||||
|
||||
Args:
|
||||
quantity: 成交数量
|
||||
price: 成交价格
|
||||
commission: 手续费
|
||||
"""
|
||||
if quantity <= 0:
|
||||
return
|
||||
|
||||
# 更新成交数量和金额
|
||||
new_filled = self.filled_quantity + quantity
|
||||
new_amount = self.filled_amount + price * quantity
|
||||
|
||||
self.filled_quantity = new_filled
|
||||
self.filled_amount = new_amount
|
||||
self.avg_price = new_amount / new_filled if new_filled > 0 else None
|
||||
self.commission += commission
|
||||
|
||||
# 更新状态
|
||||
if self.filled_quantity >= self.quantity:
|
||||
self.status = OrderStatus.FILLED.value
|
||||
self.filled_at = datetime.now()
|
||||
elif self.filled_quantity > 0:
|
||||
self.status = OrderStatus.PARTIAL.value
|
||||
|
||||
self.updated_at = datetime.now()
|
||||
|
||||
def cancel(self, message: str | None = None) -> bool:
|
||||
"""
|
||||
撤销订单
|
||||
|
||||
Args:
|
||||
message: 撤销原因
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
if not self.is_active:
|
||||
return False
|
||||
|
||||
self.status = OrderStatus.CANCELLED.value
|
||||
self.cancelled_at = datetime.now()
|
||||
self.message = message
|
||||
self.updated_at = datetime.now()
|
||||
return True
|
||||
|
||||
def reject(self, message: str | None = None) -> None:
|
||||
"""
|
||||
拒绝订单
|
||||
|
||||
Args:
|
||||
message: 拒绝原因
|
||||
"""
|
||||
self.status = OrderStatus.REJECTED.value
|
||||
self.message = message
|
||||
self.updated_at = datetime.now()
|
||||
|
||||
def submit(self, external_id: str | None = None) -> None:
|
||||
"""
|
||||
提交订单
|
||||
|
||||
Args:
|
||||
external_id: 外部订单ID
|
||||
"""
|
||||
self.status = OrderStatus.SUBMITTED.value
|
||||
self.external_id = external_id
|
||||
self.submitted_at = datetime.now()
|
||||
self.updated_at = datetime.now()
|
||||
def model_post_init(self, __context) -> None:
|
||||
"""对象创建后验证"""
|
||||
if self.filled_volume > self.volume:
|
||||
raise ValueError(
|
||||
f"已成交数量({self.filled_volume})不能大于订单数量({self.volume})"
|
||||
)
|
||||
|
||||
@ -1,167 +0,0 @@
|
||||
"""
|
||||
股票-策略配对 ORM 模型
|
||||
|
||||
包含:
|
||||
- PairingStatus: 配对状态枚举
|
||||
- Pairing: 股票-策略配对表
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
|
||||
from sqlalchemy import Index, JSON, Numeric, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import Base, TimestampMixin
|
||||
|
||||
|
||||
class PairingStatus(str, Enum):
|
||||
"""配对状态"""
|
||||
|
||||
ACTIVE = "active" # 运行中
|
||||
PAUSED = "paused" # 已暂停
|
||||
STOPPED = "stopped" # 已停止
|
||||
|
||||
|
||||
class Pairing(TimestampMixin, Base):
|
||||
"""
|
||||
股票-策略配对
|
||||
|
||||
一只股票可以配对多个策略,每个配对有独立的资金和持仓管理
|
||||
"""
|
||||
|
||||
__tablename__ = "pairings"
|
||||
|
||||
# 主键
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, comment="配对ID")
|
||||
|
||||
# 股票信息
|
||||
symbol: Mapped[str] = mapped_column(String(20), nullable=False, comment="股票代码")
|
||||
symbol_name: Mapped[str | None] = mapped_column(String(50), comment="股票名称")
|
||||
|
||||
# 策略信息
|
||||
strategy_id: Mapped[str] = mapped_column(
|
||||
String(50), nullable=False, comment="策略ID"
|
||||
)
|
||||
strategy_name: Mapped[str | None] = mapped_column(String(100), comment="策略名称")
|
||||
|
||||
# 资金配置
|
||||
initial_capital: Mapped[Decimal] = mapped_column(
|
||||
Numeric(16, 2), nullable=False, comment="初始资金"
|
||||
)
|
||||
available_capital: Mapped[Decimal] = mapped_column(
|
||||
Numeric(16, 2), nullable=False, comment="可用资金"
|
||||
)
|
||||
frozen_capital: Mapped[Decimal] = mapped_column(
|
||||
Numeric(16, 2), default=Decimal(0), comment="冻结资金"
|
||||
)
|
||||
|
||||
# 状态
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(20), default=PairingStatus.STOPPED.value, comment="配对状态"
|
||||
)
|
||||
|
||||
# 策略参数 (JSON)
|
||||
params: Mapped[dict | None] = mapped_column(JSON, default=dict, comment="策略参数")
|
||||
|
||||
# 统计信息
|
||||
total_trades: Mapped[int] = mapped_column(default=0, comment="总交易次数")
|
||||
win_trades: Mapped[int] = mapped_column(default=0, comment="盈利次数")
|
||||
loss_trades: Mapped[int] = mapped_column(default=0, comment="亏损次数")
|
||||
total_pnl: Mapped[Decimal] = mapped_column(
|
||||
Numeric(16, 2), default=Decimal(0), comment="累计盈亏"
|
||||
)
|
||||
max_drawdown: Mapped[Decimal] = mapped_column(
|
||||
Numeric(10, 4), default=Decimal(0), comment="最大回撤率"
|
||||
)
|
||||
|
||||
# 备注
|
||||
remark: Mapped[str | None] = mapped_column(Text, comment="备注")
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_pairings_symbol", "symbol"),
|
||||
Index("ix_pairings_strategy_id", "strategy_id"),
|
||||
Index("ix_pairings_status", "status"),
|
||||
Index("ix_pairings_symbol_strategy", "symbol", "strategy_id"),
|
||||
)
|
||||
|
||||
@property
|
||||
def current_capital(self) -> Decimal:
|
||||
"""当前总资金 = 可用 + 冻结"""
|
||||
return self.available_capital + self.frozen_capital
|
||||
|
||||
@property
|
||||
def win_rate(self) -> float | None:
|
||||
"""胜率"""
|
||||
if self.total_trades == 0:
|
||||
return None
|
||||
return self.win_trades / self.total_trades
|
||||
|
||||
@property
|
||||
def return_rate(self) -> float:
|
||||
"""收益率 (%)"""
|
||||
if self.initial_capital == 0:
|
||||
return 0.0
|
||||
return float(
|
||||
(self.current_capital - self.initial_capital) / self.initial_capital * 100
|
||||
)
|
||||
|
||||
def is_active(self) -> bool:
|
||||
"""是否运行中"""
|
||||
return self.status == PairingStatus.ACTIVE.value
|
||||
|
||||
def freeze_capital(self, amount: Decimal) -> bool:
|
||||
"""
|
||||
冻结资金
|
||||
|
||||
Args:
|
||||
amount: 冻结金额
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
if amount > self.available_capital:
|
||||
return False
|
||||
self.available_capital -= amount
|
||||
self.frozen_capital += amount
|
||||
self.updated_at = datetime.now()
|
||||
return True
|
||||
|
||||
def unfreeze_capital(self, amount: Decimal) -> bool:
|
||||
"""
|
||||
解冻资金
|
||||
|
||||
Args:
|
||||
amount: 解冻金额
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
if amount > self.frozen_capital:
|
||||
return False
|
||||
self.frozen_capital -= amount
|
||||
self.available_capital += amount
|
||||
self.updated_at = datetime.now()
|
||||
return True
|
||||
|
||||
def add_capital(self, amount: Decimal) -> None:
|
||||
"""增加可用资金"""
|
||||
self.available_capital += amount
|
||||
self.updated_at = datetime.now()
|
||||
|
||||
def deduct_capital(self, amount: Decimal) -> bool:
|
||||
"""
|
||||
扣减可用资金
|
||||
|
||||
Args:
|
||||
amount: 扣减金额
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
if amount > self.available_capital:
|
||||
return False
|
||||
self.available_capital -= amount
|
||||
self.updated_at = datetime.now()
|
||||
return True
|
||||
@ -1,208 +1,90 @@
|
||||
"""
|
||||
持仓 ORM 模型
|
||||
|
||||
包含:
|
||||
- Position: 持仓表
|
||||
持仓对象
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import ForeignKey, Index, Numeric, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import Base, TimestampMixin
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from .enums import PositionDirection
|
||||
|
||||
|
||||
class Position(TimestampMixin, Base):
|
||||
class Position(BaseModel):
|
||||
"""
|
||||
持仓表
|
||||
持仓(可变)
|
||||
|
||||
记录每个配对的持仓情况
|
||||
注意: 持仓是按 pairing_id 独立管理的,同一股票在不同配对下有独立的持仓记录
|
||||
示例:
|
||||
position = Position(
|
||||
symbol="000001.SZ",
|
||||
direction=PositionDirection.LONG,
|
||||
volume=1000,
|
||||
available_volume=900,
|
||||
avg_price=10.0,
|
||||
update_time=datetime.now()
|
||||
)
|
||||
"""
|
||||
|
||||
__tablename__ = "positions"
|
||||
symbol: str = Field(..., description="标的代码", min_length=1)
|
||||
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)
|
||||
|
||||
# 主键
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, comment="持仓ID")
|
||||
avg_price: float = Field(..., description="平均成本", gt=0)
|
||||
last_price: float = Field(0.0, description="最新价", ge=0)
|
||||
|
||||
# 关联
|
||||
pairing_id: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
ForeignKey("pairings.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
comment="配对ID",
|
||||
)
|
||||
# 盈亏(动态计算,也可以存储)
|
||||
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="已实现盈亏(平仓产生)")
|
||||
|
||||
# 股票信息
|
||||
symbol: Mapped[str] = mapped_column(String(20), nullable=False, comment="股票代码")
|
||||
symbol_name: Mapped[str | None] = mapped_column(String(50), comment="股票名称")
|
||||
update_time: datetime = Field(..., description="更新时间")
|
||||
|
||||
# 持仓数量
|
||||
quantity: Mapped[int] = mapped_column(default=0, comment="持仓数量")
|
||||
available: Mapped[int] = mapped_column(default=0, comment="可用数量 (T+1)")
|
||||
frozen: Mapped[int] = mapped_column(default=0, comment="冻结数量")
|
||||
# 股票特有:今仓/昨仓(用于T+1)
|
||||
today_volume: int = Field(0, description="今日买入量(T+1不可卖)", ge=0)
|
||||
|
||||
# 成本信息
|
||||
avg_cost: Mapped[Decimal] = mapped_column(
|
||||
Numeric(10, 4), default=Decimal(0), comment="持仓成本价"
|
||||
)
|
||||
total_cost: Mapped[Decimal] = mapped_column(
|
||||
Numeric(16, 2), default=Decimal(0), comment="总成本"
|
||||
)
|
||||
@field_validator("symbol")
|
||||
@classmethod
|
||||
def validate_symbol(cls, v: str) -> str:
|
||||
"""验证标的代码格式"""
|
||||
if not v or len(v) < 6:
|
||||
raise ValueError("标的代码长度至少6个字符")
|
||||
return v.upper()
|
||||
|
||||
# 盈亏 (需要实时计算更新)
|
||||
last_price: Mapped[Decimal | None] = mapped_column(
|
||||
Numeric(10, 3), comment="最新价格"
|
||||
)
|
||||
market_value: Mapped[Decimal | None] = mapped_column(Numeric(16, 2), comment="市值")
|
||||
unrealized_pnl: Mapped[Decimal | None] = mapped_column(
|
||||
Numeric(16, 2), comment="浮动盈亏"
|
||||
)
|
||||
realized_pnl: Mapped[Decimal] = mapped_column(
|
||||
Numeric(16, 2), default=Decimal(0), comment="已实现盈亏"
|
||||
)
|
||||
def model_post_init(self, __context) -> None:
|
||||
"""对象创建后验证"""
|
||||
if self.available_volume > self.volume:
|
||||
raise ValueError(
|
||||
f"可用量({self.available_volume})不能大于持仓量({self.volume})"
|
||||
)
|
||||
if self.frozen_volume > self.volume:
|
||||
raise ValueError(
|
||||
f"冻结量({self.frozen_volume})不能大于持仓量({self.volume})"
|
||||
)
|
||||
if self.today_volume > self.volume:
|
||||
raise ValueError(
|
||||
f"今日买入量({self.today_volume})不能大于持仓量({self.volume})"
|
||||
)
|
||||
if self.available_volume + self.frozen_volume > self.volume:
|
||||
raise ValueError(
|
||||
f"可用量({self.available_volume}) + 冻结量({self.frozen_volume}) "
|
||||
f"不能大于持仓量({self.volume})"
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_positions_pairing_id", "pairing_id"),
|
||||
Index("ix_positions_symbol", "symbol"),
|
||||
Index("ix_positions_pairing_symbol", "pairing_id", "symbol", unique=True),
|
||||
)
|
||||
|
||||
@property
|
||||
def pnl_ratio(self) -> float | None:
|
||||
"""盈亏比例 (%)"""
|
||||
if self.total_cost == 0 or self.unrealized_pnl is None:
|
||||
return None
|
||||
return float(self.unrealized_pnl / self.total_cost * 100)
|
||||
|
||||
@property
|
||||
def total_pnl(self) -> Decimal:
|
||||
"""总盈亏 = 浮动盈亏 + 已实现盈亏"""
|
||||
return (self.unrealized_pnl or Decimal(0)) + self.realized_pnl
|
||||
|
||||
def update_price(self, price: Decimal) -> None:
|
||||
def update_market_value(self, price: float) -> None:
|
||||
"""
|
||||
更新最新价格,计算市值和浮动盈亏
|
||||
更新市值和浮动盈亏
|
||||
|
||||
Args:
|
||||
price: 最新价格
|
||||
"""
|
||||
if price <= 0:
|
||||
raise ValueError("价格必须大于0")
|
||||
|
||||
self.last_price = price
|
||||
self.market_value = price * self.quantity
|
||||
# 计算浮动盈亏
|
||||
market_value = self.market_value
|
||||
total_cost = self.total_cost
|
||||
if market_value is not None and total_cost is not None:
|
||||
self.unrealized_pnl = market_value - total_cost
|
||||
self.updated_at = datetime.now()
|
||||
self.market_value = self.volume * price
|
||||
|
||||
def buy(
|
||||
self, quantity: int, price: Decimal, commission: Decimal = Decimal(0)
|
||||
) -> None:
|
||||
"""
|
||||
买入处理
|
||||
if self.direction == PositionDirection.LONG:
|
||||
self.unrealized_pnl = (price - self.avg_price) * self.volume
|
||||
else: # SHORT
|
||||
self.unrealized_pnl = (self.avg_price - price) * self.volume
|
||||
|
||||
Args:
|
||||
quantity: 买入数量
|
||||
price: 买入价格
|
||||
commission: 手续费
|
||||
"""
|
||||
if quantity <= 0:
|
||||
return
|
||||
|
||||
# 计算新的成本
|
||||
buy_cost = price * quantity + commission
|
||||
new_total_cost = self.total_cost + buy_cost
|
||||
new_quantity = self.quantity + quantity
|
||||
|
||||
# 更新持仓
|
||||
self.quantity = new_quantity
|
||||
self.total_cost = new_total_cost
|
||||
self.avg_cost = (
|
||||
new_total_cost / new_quantity if new_quantity > 0 else Decimal(0)
|
||||
)
|
||||
# 注意: T+1 规则,新买入的不计入可用
|
||||
self.updated_at = datetime.now()
|
||||
|
||||
def sell(
|
||||
self, quantity: int, price: Decimal, commission: Decimal = Decimal(0)
|
||||
) -> Decimal:
|
||||
"""
|
||||
卖出处理
|
||||
|
||||
Args:
|
||||
quantity: 卖出数量
|
||||
price: 卖出价格
|
||||
commission: 手续费
|
||||
|
||||
Returns:
|
||||
本次实现盈亏
|
||||
"""
|
||||
if quantity <= 0 or quantity > self.available:
|
||||
raise ValueError(f"卖出数量无效: 请求 {quantity}, 可用 {self.available}")
|
||||
|
||||
# 计算盈亏
|
||||
sell_amount = price * quantity - commission
|
||||
cost = self.avg_cost * quantity
|
||||
realized = sell_amount - cost
|
||||
|
||||
# 更新持仓
|
||||
self.quantity -= quantity
|
||||
self.available -= quantity
|
||||
self.total_cost -= cost
|
||||
self.realized_pnl += realized
|
||||
|
||||
if self.quantity == 0:
|
||||
self.avg_cost = Decimal(0)
|
||||
self.total_cost = Decimal(0)
|
||||
|
||||
self.updated_at = datetime.now()
|
||||
return realized
|
||||
|
||||
def freeze(self, quantity: int) -> bool:
|
||||
"""
|
||||
冻结持仓
|
||||
|
||||
Args:
|
||||
quantity: 冻结数量
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
if quantity > self.available:
|
||||
return False
|
||||
self.available -= quantity
|
||||
self.frozen += quantity
|
||||
self.updated_at = datetime.now()
|
||||
return True
|
||||
|
||||
def unfreeze(self, quantity: int) -> bool:
|
||||
"""
|
||||
解冻持仓
|
||||
|
||||
Args:
|
||||
quantity: 解冻数量
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
if quantity > self.frozen:
|
||||
return False
|
||||
self.frozen -= quantity
|
||||
self.available += quantity
|
||||
self.updated_at = datetime.now()
|
||||
return True
|
||||
|
||||
def settle_daily(self) -> None:
|
||||
"""
|
||||
日终结算 (T+1 可用处理)
|
||||
|
||||
将今日买入的股票变为可用
|
||||
"""
|
||||
# 今日买入 = 总数量 - 可用 - 冻结
|
||||
today_bought = self.quantity - self.available - self.frozen
|
||||
if today_bought > 0:
|
||||
self.available += today_bought
|
||||
self.updated_at = datetime.now()
|
||||
self.update_time = datetime.now()
|
||||
|
||||
@ -1,159 +1,50 @@
|
||||
"""
|
||||
交易信号 ORM 模型
|
||||
|
||||
包含:
|
||||
- SignalStatus: 信号状态枚举
|
||||
- Signal: 信号表
|
||||
交易信号对象
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Numeric, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import Base, TimestampMixin
|
||||
from .common import TradeSide
|
||||
from typing import Optional, Dict, Any
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from .enums import SignalType
|
||||
|
||||
|
||||
class SignalStatus(str, Enum):
|
||||
"""信号状态"""
|
||||
|
||||
PENDING = "pending" # 待处理
|
||||
EXECUTING = "executing" # 执行中
|
||||
EXECUTED = "executed" # 已执行
|
||||
CANCELLED = "cancelled" # 已取消
|
||||
FAILED = "failed" # 执行失败
|
||||
EXPIRED = "expired" # 已过期
|
||||
|
||||
|
||||
class Signal(TimestampMixin, Base):
|
||||
class Signal(BaseModel):
|
||||
"""
|
||||
交易信号表
|
||||
交易信号(可变,因为需要更新executed状态)
|
||||
|
||||
策略产生的交易信号,等待执行
|
||||
"""
|
||||
|
||||
__tablename__ = "signals"
|
||||
|
||||
# 主键
|
||||
id: Mapped[str] = mapped_column(String(32), primary_key=True, comment="信号ID")
|
||||
|
||||
# 关联
|
||||
pairing_id: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
ForeignKey("pairings.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
comment="配对ID",
|
||||
)
|
||||
order_id: Mapped[str | None] = mapped_column(String(32), comment="关联订单ID")
|
||||
|
||||
# 信号内容
|
||||
symbol: Mapped[str] = mapped_column(String(20), nullable=False, comment="股票代码")
|
||||
strategy_id: Mapped[str] = mapped_column(
|
||||
String(50), nullable=False, comment="策略ID"
|
||||
)
|
||||
side: Mapped[str] = mapped_column(String(10), nullable=False, comment="信号方向")
|
||||
price: Mapped[Decimal] = mapped_column(
|
||||
Numeric(10, 3), nullable=False, comment="建议价格"
|
||||
)
|
||||
quantity: Mapped[int] = mapped_column(nullable=False, comment="建议数量")
|
||||
|
||||
# 信号来源和原因
|
||||
source: Mapped[str | None] = mapped_column(String(50), comment="信号来源")
|
||||
reason: Mapped[str | None] = mapped_column(Text, comment="信号原因")
|
||||
|
||||
# 状态
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(20), default=SignalStatus.PENDING.value, comment="信号状态"
|
||||
)
|
||||
message: Mapped[str | None] = mapped_column(Text, comment="状态消息")
|
||||
|
||||
# 时间
|
||||
executed_at: Mapped[datetime | None] = mapped_column(DateTime, comment="执行时间")
|
||||
expired_at: Mapped[datetime | None] = mapped_column(DateTime, comment="过期时间")
|
||||
|
||||
__table_args__ = (
|
||||
Index("ix_signals_pairing_id", "pairing_id"),
|
||||
Index("ix_signals_symbol", "symbol"),
|
||||
Index("ix_signals_status", "status"),
|
||||
Index("ix_signals_created_at", "created_at"),
|
||||
)
|
||||
|
||||
@property
|
||||
def is_pending(self) -> bool:
|
||||
"""是否待处理"""
|
||||
return self.status == SignalStatus.PENDING.value
|
||||
|
||||
@property
|
||||
def is_finished(self) -> bool:
|
||||
"""是否已结束"""
|
||||
return self.status in (
|
||||
SignalStatus.EXECUTED.value,
|
||||
SignalStatus.CANCELLED.value,
|
||||
SignalStatus.FAILED.value,
|
||||
SignalStatus.EXPIRED.value,
|
||||
示例:
|
||||
signal = Signal(
|
||||
signal_id="SIG_20240101_001",
|
||||
symbol="000001.SZ",
|
||||
strategy_name="MA_Strategy",
|
||||
signal_type=SignalType.BUY,
|
||||
price=10.5,
|
||||
target_volume=100,
|
||||
create_time=datetime.now()
|
||||
)
|
||||
"""
|
||||
|
||||
@property
|
||||
def signal_amount(self) -> Decimal:
|
||||
"""信号金额"""
|
||||
return self.price * self.quantity
|
||||
signal_id: str = Field(..., description="信号ID(唯一)", min_length=1)
|
||||
symbol: str = Field(..., description="标的代码", min_length=1)
|
||||
strategy_name: str = Field(..., description="策略名称", min_length=1)
|
||||
signal_type: SignalType = Field(..., description="信号类型")
|
||||
|
||||
def execute(self, order_id: str) -> None:
|
||||
"""
|
||||
标记为已执行
|
||||
price: float = Field(..., description="信号触发价格", gt=0)
|
||||
target_volume: int = Field(..., description="目标数量", gt=0)
|
||||
|
||||
Args:
|
||||
order_id: 关联的订单ID
|
||||
"""
|
||||
self.status = SignalStatus.EXECUTED.value
|
||||
self.order_id = order_id
|
||||
self.executed_at = datetime.now()
|
||||
self.updated_at = datetime.now()
|
||||
strength: float = Field(1.0, description="信号强度 (0-1)", ge=0, le=1)
|
||||
reason: Optional[str] = Field(None, description="信号原因")
|
||||
|
||||
def cancel(self, message: str | None = None) -> None:
|
||||
"""
|
||||
取消信号
|
||||
create_time: datetime = Field(..., description="创建时间")
|
||||
executed: bool = Field(False, description="是否已执行")
|
||||
|
||||
Args:
|
||||
message: 取消原因
|
||||
"""
|
||||
self.status = SignalStatus.CANCELLED.value
|
||||
self.message = message
|
||||
self.updated_at = datetime.now()
|
||||
# 扩展信息(可选)
|
||||
metadata: Optional[Dict[str, Any]] = Field(None, description="扩展信息")
|
||||
|
||||
def fail(self, message: str | None = None) -> None:
|
||||
"""
|
||||
标记为失败
|
||||
|
||||
Args:
|
||||
message: 失败原因
|
||||
"""
|
||||
self.status = SignalStatus.FAILED.value
|
||||
self.message = message
|
||||
self.updated_at = datetime.now()
|
||||
|
||||
def expire(self) -> None:
|
||||
"""标记为过期"""
|
||||
self.status = SignalStatus.EXPIRED.value
|
||||
self.updated_at = datetime.now()
|
||||
|
||||
def start_executing(self) -> None:
|
||||
"""标记为执行中"""
|
||||
self.status = SignalStatus.EXECUTING.value
|
||||
self.updated_at = datetime.now()
|
||||
|
||||
def check_expired(self) -> bool:
|
||||
"""
|
||||
检查是否过期
|
||||
|
||||
Returns:
|
||||
是否过期
|
||||
"""
|
||||
if self.expired_at and datetime.now() > self.expired_at:
|
||||
if self.is_pending:
|
||||
self.expire()
|
||||
return True
|
||||
return False
|
||||
@field_validator("symbol")
|
||||
@classmethod
|
||||
def validate_symbol(cls, v: str) -> str:
|
||||
"""验证标的代码格式"""
|
||||
if not v or len(v) < 6:
|
||||
raise ValueError("标的代码长度至少6个字符")
|
||||
return v.upper()
|
||||
|
||||
56
src/core/models/symbol.py
Normal file
56
src/core/models/symbol.py
Normal file
@ -0,0 +1,56 @@
|
||||
"""
|
||||
标的信息对象
|
||||
"""
|
||||
|
||||
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)")
|
||||
64
src/core/models/tick.py
Normal file
64
src/core/models/tick.py
Normal file
@ -0,0 +1,64 @@
|
||||
"""
|
||||
Tick行情数据对象
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional, List
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
class Tick(BaseModel):
|
||||
"""
|
||||
Tick行情数据(不可变)
|
||||
|
||||
示例:
|
||||
tick = Tick(
|
||||
symbol="000001.SZ",
|
||||
timestamp=datetime.now(),
|
||||
price=10.5,
|
||||
volume=1000
|
||||
)
|
||||
"""
|
||||
|
||||
symbol: str = Field(..., description="标的代码,如 000001.SZ", min_length=1)
|
||||
timestamp: datetime = Field(..., description="时间戳")
|
||||
price: float = Field(..., description="最新价", gt=0)
|
||||
volume: int = Field(..., description="成交量", ge=0)
|
||||
amount: Optional[float] = Field(None, description="成交额", ge=0)
|
||||
|
||||
# 五档行情(可选)
|
||||
bid_prices: Optional[List[float]] = Field(None, description="买盘价格列表")
|
||||
bid_volumes: Optional[List[int]] = Field(None, description="买盘量列表")
|
||||
ask_prices: Optional[List[float]] = Field(None, description="卖盘价格列表")
|
||||
ask_volumes: Optional[List[int]] = Field(None, description="卖盘量列表")
|
||||
|
||||
# 期货特有(可选)
|
||||
open_interest: Optional[int] = Field(None, description="持仓量", ge=0)
|
||||
|
||||
model_config = ConfigDict(frozen=True) # 不可变
|
||||
|
||||
@field_validator("symbol")
|
||||
@classmethod
|
||||
def validate_symbol(cls, v: str) -> str:
|
||||
"""验证标的代码格式"""
|
||||
if not v or len(v) < 6:
|
||||
raise ValueError("标的代码长度至少6个字符")
|
||||
return v.upper()
|
||||
|
||||
@field_validator("bid_prices", "ask_prices")
|
||||
@classmethod
|
||||
def validate_prices(cls, v: Optional[List[float]]) -> Optional[List[float]]:
|
||||
"""验证价格列表"""
|
||||
if v is not None:
|
||||
if any(price <= 0 for price in v):
|
||||
raise ValueError("价格必须大于0")
|
||||
return v
|
||||
|
||||
@field_validator("bid_volumes", "ask_volumes")
|
||||
@classmethod
|
||||
def validate_volumes(cls, v: Optional[List[int]]) -> Optional[List[int]]:
|
||||
"""验证量列表"""
|
||||
if v is not None:
|
||||
if any(vol < 0 for vol in v):
|
||||
raise ValueError("成交量不能为负数")
|
||||
return v
|
||||
53
src/core/models/trade.py
Normal file
53
src/core/models/trade.py
Normal file
@ -0,0 +1,53 @@
|
||||
"""
|
||||
成交记录对象
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
from .enums import OrderSide
|
||||
|
||||
|
||||
class Trade(BaseModel):
|
||||
"""
|
||||
成交记录(不可变)
|
||||
|
||||
示例:
|
||||
trade = Trade(
|
||||
trade_id="TRD_20240101_001",
|
||||
order_id="ORD_20240101_001",
|
||||
symbol="000001.SZ",
|
||||
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)
|
||||
symbol: str = Field(..., description="标的代码", min_length=1)
|
||||
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)
|
||||
trade_time: datetime = Field(..., description="成交时间")
|
||||
|
||||
model_config = ConfigDict(frozen=True) # 不可变
|
||||
|
||||
@field_validator("symbol")
|
||||
@classmethod
|
||||
def validate_symbol(cls, v: str) -> str:
|
||||
"""验证标的代码格式"""
|
||||
if not v or len(v) < 6:
|
||||
raise ValueError("标的代码长度至少6个字符")
|
||||
return v.upper()
|
||||
|
||||
def model_post_init(self, __context) -> None:
|
||||
"""对象创建后验证成交额"""
|
||||
expected_amount = self.price * self.volume
|
||||
# 允许1%的误差(考虑浮点数精度)
|
||||
if abs(self.amount - expected_amount) / expected_amount > 0.01:
|
||||
raise ValueError(f"成交额({self.amount})与价格*数量({expected_amount})不符")
|
||||
@ -1,472 +0,0 @@
|
||||
"""
|
||||
QTrade Redis 客户端模块
|
||||
|
||||
提供异步 Redis 操作封装:
|
||||
- 连接池管理
|
||||
- Pub/Sub 订阅
|
||||
- 常用操作封装
|
||||
"""
|
||||
# pyright: reportGeneralTypeIssues=false
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any, AsyncIterator, Callable, Optional, Set
|
||||
|
||||
import redis.asyncio as redis # type: ignore
|
||||
from redis.asyncio import Redis # type: ignore
|
||||
from redis.asyncio.client import PubSub # type: ignore
|
||||
|
||||
from .config import settings
|
||||
from .logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class RedisClient:
|
||||
"""
|
||||
异步 Redis 客户端
|
||||
|
||||
提供连接池管理和常用操作封装
|
||||
"""
|
||||
|
||||
_instance: Optional["RedisClient"] = None
|
||||
_pool: Optional[redis.ConnectionPool] = None
|
||||
_client: Optional[Redis] = None
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
return cls._instance
|
||||
|
||||
async def connect(self) -> None:
|
||||
"""建立 Redis 连接"""
|
||||
if self._client is not None:
|
||||
return
|
||||
|
||||
self._pool = redis.ConnectionPool.from_url(
|
||||
settings.redis.url,
|
||||
max_connections=settings.redis.pool_size,
|
||||
socket_timeout=settings.redis.pool_timeout,
|
||||
decode_responses=True,
|
||||
)
|
||||
self._client = Redis(connection_pool=self._pool)
|
||||
|
||||
# 测试连接
|
||||
try:
|
||||
assert self._client is not None
|
||||
await self._client.ping()
|
||||
logger.info(f"Redis 连接成功: {settings.redis.host}:{settings.redis.port}")
|
||||
except Exception as e:
|
||||
logger.error(f"Redis 连接失败: {e}")
|
||||
raise
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
"""断开 Redis 连接"""
|
||||
if self._client:
|
||||
await self._client.close()
|
||||
self._client = None
|
||||
if self._pool:
|
||||
await self._pool.disconnect()
|
||||
self._pool = None
|
||||
logger.info("Redis 连接已断开")
|
||||
|
||||
@property
|
||||
def client(self) -> Redis:
|
||||
"""获取 Redis 客户端实例"""
|
||||
if self._client is None:
|
||||
raise RuntimeError("Redis 客户端未连接,请先调用 connect()")
|
||||
return self._client
|
||||
|
||||
# ========== 基础操作 ==========
|
||||
|
||||
async def ping(self) -> bool:
|
||||
"""测试连接"""
|
||||
return await self.client.ping()
|
||||
|
||||
async def get(self, key: str) -> Optional[str]:
|
||||
"""获取值"""
|
||||
return await self.client.get(key)
|
||||
|
||||
async def set(
|
||||
self,
|
||||
key: str,
|
||||
value: str,
|
||||
ex: Optional[int] = None,
|
||||
px: Optional[int] = None,
|
||||
) -> bool:
|
||||
"""设置值"""
|
||||
return await self.client.set(key, value, ex=ex, px=px)
|
||||
|
||||
async def setex(self, key: str, seconds: int, value: str) -> bool:
|
||||
"""设置值并指定过期时间(秒)"""
|
||||
return await self.client.setex(key, seconds, value)
|
||||
|
||||
async def delete(self, *keys: str) -> int:
|
||||
"""删除键"""
|
||||
return await self.client.delete(*keys)
|
||||
|
||||
async def exists(self, *keys: str) -> int:
|
||||
"""检查键是否存在"""
|
||||
return await self.client.exists(*keys)
|
||||
|
||||
async def expire(self, key: str, seconds: int) -> bool:
|
||||
"""设置过期时间"""
|
||||
return await self.client.expire(key, seconds)
|
||||
|
||||
# ========== JSON 操作 ==========
|
||||
|
||||
async def get_json(self, key: str) -> Optional[Any]:
|
||||
"""获取 JSON 对象"""
|
||||
value = await self.get(key)
|
||||
if value is None:
|
||||
return None
|
||||
return json.loads(value)
|
||||
|
||||
async def set_json(
|
||||
self,
|
||||
key: str,
|
||||
value: Any,
|
||||
ex: Optional[int] = None,
|
||||
) -> bool:
|
||||
"""设置 JSON 对象"""
|
||||
return await self.set(key, json.dumps(value, ensure_ascii=False), ex=ex)
|
||||
|
||||
# ========== Hash 操作 ==========
|
||||
|
||||
async def hget(self, name: str, key: str) -> Optional[str]:
|
||||
"""获取 Hash 字段"""
|
||||
return await self.client.hget(name, key)
|
||||
|
||||
async def hset(self, name: str, key: str, value: str) -> int:
|
||||
"""设置 Hash 字段"""
|
||||
return await self.client.hset(name, key, value)
|
||||
|
||||
async def hgetall(self, name: str) -> dict[str, str]:
|
||||
"""获取整个 Hash"""
|
||||
return await self.client.hgetall(name)
|
||||
|
||||
async def hdel(self, name: str, *keys: str) -> int:
|
||||
"""删除 Hash 字段"""
|
||||
return await self.client.hdel(name, *keys)
|
||||
|
||||
async def hset_dict(self, name: str, mapping: dict[str, str]) -> int:
|
||||
"""
|
||||
批量设置 Hash 字段
|
||||
|
||||
Args:
|
||||
name: Hash 键名
|
||||
mapping: {field: value} 字典
|
||||
|
||||
Returns:
|
||||
新增的字段数量
|
||||
"""
|
||||
if not mapping:
|
||||
return 0
|
||||
return await self.client.hset(name, mapping=mapping)
|
||||
|
||||
# ========== List 操作 ==========
|
||||
|
||||
async def lpush(self, name: str, *values: str) -> int:
|
||||
"""左端入队"""
|
||||
return await self.client.lpush(name, *values)
|
||||
|
||||
async def rpush(self, name: str, *values: str) -> int:
|
||||
"""右端入队"""
|
||||
return await self.client.rpush(name, *values)
|
||||
|
||||
async def lpop(self, name: str) -> Optional[str]:
|
||||
"""左端出队"""
|
||||
result = await self.client.lpop(name)
|
||||
return str(result) if result is not None else None
|
||||
|
||||
async def rpop(self, name: str) -> Optional[str]:
|
||||
"""右端出队"""
|
||||
result = await self.client.rpop(name)
|
||||
return str(result) if result is not None else None
|
||||
|
||||
async def lrange(self, name: str, start: int, end: int) -> list[str]:
|
||||
"""获取列表范围"""
|
||||
return await self.client.lrange(name, start, end)
|
||||
|
||||
async def llen(self, name: str) -> int:
|
||||
"""获取列表长度"""
|
||||
return await self.client.llen(name)
|
||||
|
||||
async def brpop(
|
||||
self, keys: str | list[str], timeout: int = 0
|
||||
) -> tuple[str, str] | None:
|
||||
"""
|
||||
阻塞右端出队
|
||||
|
||||
Args:
|
||||
keys: 键名 (单个或多个)
|
||||
timeout: 超时秒数 (0 表示无限等待)
|
||||
|
||||
Returns:
|
||||
(key, value) 元组, 超时返回 None
|
||||
"""
|
||||
if isinstance(keys, str):
|
||||
keys = [keys]
|
||||
result = await self.client.brpop(keys, timeout=timeout)
|
||||
if result is None:
|
||||
return None
|
||||
return (str(result[0]), str(result[1]))
|
||||
|
||||
async def blpop(
|
||||
self, keys: str | list[str], timeout: int = 0
|
||||
) -> tuple[str, str] | None:
|
||||
"""
|
||||
阻塞左端出队
|
||||
|
||||
Args:
|
||||
keys: 键名 (单个或多个)
|
||||
timeout: 超时秒数 (0 表示无限等待)
|
||||
|
||||
Returns:
|
||||
(key, value) 元组, 超时返回 None
|
||||
"""
|
||||
if isinstance(keys, str):
|
||||
keys = [keys]
|
||||
result = await self.client.blpop(keys, timeout=timeout)
|
||||
if result is None:
|
||||
return None
|
||||
return (str(result[0]), str(result[1]))
|
||||
|
||||
# ========== Set 操作 ==========
|
||||
|
||||
async def sadd(self, name: str, *values: str) -> int:
|
||||
"""添加集合成员"""
|
||||
return await self.client.sadd(name, *values)
|
||||
|
||||
async def srem(self, name: str, *values: str) -> int:
|
||||
"""移除集合成员"""
|
||||
return await self.client.srem(name, *values)
|
||||
|
||||
async def smembers(self, name: str) -> Set[str]:
|
||||
"""获取集合所有成员"""
|
||||
return await self.client.smembers(name)
|
||||
|
||||
async def sismember(self, name: str, value: str) -> bool:
|
||||
"""检查是否为集合成员"""
|
||||
result = await self.client.sismember(name, value)
|
||||
return bool(result)
|
||||
|
||||
# ========== Scan 操作 ==========
|
||||
|
||||
async def scan_iter(self, match: Optional[str] = None, count: int = 100):
|
||||
"""
|
||||
迭代扫描键
|
||||
|
||||
Args:
|
||||
match: 匹配模式
|
||||
count: 每次扫描数量
|
||||
|
||||
Yields:
|
||||
匹配的键
|
||||
"""
|
||||
async for key in self.client.scan_iter(match=match, count=count):
|
||||
yield key
|
||||
|
||||
# ========== Pub/Sub 操作 ==========
|
||||
|
||||
async def publish(self, channel: str, message: Any) -> int:
|
||||
"""
|
||||
发布消息
|
||||
|
||||
Args:
|
||||
channel: 频道名称
|
||||
message: 消息内容(自动 JSON 序列化)
|
||||
|
||||
Returns:
|
||||
接收者数量
|
||||
"""
|
||||
if not isinstance(message, str):
|
||||
message = json.dumps(message, ensure_ascii=False)
|
||||
return await self.client.publish(channel, message)
|
||||
|
||||
@asynccontextmanager
|
||||
async def subscribe(
|
||||
self,
|
||||
*channels: str,
|
||||
) -> AsyncIterator[PubSub]:
|
||||
"""
|
||||
订阅频道(上下文管理器)
|
||||
|
||||
使用方法:
|
||||
async with redis_client.subscribe("channel1", "channel2") as pubsub:
|
||||
async for message in pubsub.listen():
|
||||
if message["type"] == "message":
|
||||
print(message["data"])
|
||||
"""
|
||||
pubsub = self.client.pubsub()
|
||||
try:
|
||||
await pubsub.subscribe(*channels)
|
||||
yield pubsub
|
||||
finally:
|
||||
await pubsub.unsubscribe(*channels)
|
||||
await pubsub.close()
|
||||
|
||||
async def subscribe_handler(
|
||||
self,
|
||||
channel: str,
|
||||
handler: Callable[[dict], Any],
|
||||
stop_event: Optional[asyncio.Event] = None,
|
||||
) -> None:
|
||||
"""
|
||||
订阅频道并处理消息
|
||||
|
||||
Args:
|
||||
channel: 频道名称
|
||||
handler: 消息处理函数
|
||||
stop_event: 停止事件
|
||||
"""
|
||||
async with self.subscribe(channel) as pubsub:
|
||||
logger.info(f"开始订阅频道: {channel}")
|
||||
async for message in pubsub.listen():
|
||||
if stop_event and stop_event.is_set():
|
||||
break
|
||||
if message["type"] == "message":
|
||||
try:
|
||||
data = json.loads(message["data"])
|
||||
await handler(data) if asyncio.iscoroutinefunction(
|
||||
handler
|
||||
) else handler(data)
|
||||
except json.JSONDecodeError:
|
||||
# 非 JSON 消息,直接传递
|
||||
await handler(message["data"]) if asyncio.iscoroutinefunction(
|
||||
handler
|
||||
) else handler(message["data"])
|
||||
except Exception as e:
|
||||
logger.error(f"处理消息失败: {e}")
|
||||
|
||||
|
||||
# ========== 预定义的 Redis Key 和 Channel ==========
|
||||
|
||||
|
||||
class RedisKeys:
|
||||
"""Redis Key 常量"""
|
||||
|
||||
# 行情数据
|
||||
QUOTE_PREFIX = "quote:" # quote:{symbol} - 实时行情
|
||||
KLINE_PREFIX = "kline:" # kline:{symbol}:{period} - K线数据
|
||||
|
||||
# 订单
|
||||
ORDER_PREFIX = "order:" # order:{order_id}
|
||||
ORDER_PENDING = "orders:pending" # 待处理订单队列
|
||||
|
||||
# 持仓
|
||||
POSITION_PREFIX = "position:" # position:{pairing_id}
|
||||
|
||||
# 配对
|
||||
PAIRING_PREFIX = "pairing:" # pairing:{id}
|
||||
PAIRING_LIST = "pairings:active" # 活跃配对列表
|
||||
|
||||
# 策略
|
||||
STRATEGY_PREFIX = "strategy:" # strategy:{id}
|
||||
|
||||
# 账户
|
||||
ACCOUNT_PREFIX = "account:" # account:{account_id}
|
||||
|
||||
# 数据下载
|
||||
DATA_DOWNLOAD_QUEUE = "data:download:queue" # 下载任务队列
|
||||
|
||||
@staticmethod
|
||||
def quote(symbol: str) -> str:
|
||||
return f"{RedisKeys.QUOTE_PREFIX}{symbol}"
|
||||
|
||||
@staticmethod
|
||||
def kline(symbol: str, period: str) -> str:
|
||||
return f"{RedisKeys.KLINE_PREFIX}{symbol}:{period}"
|
||||
|
||||
@staticmethod
|
||||
def order(order_id: str) -> str:
|
||||
return f"{RedisKeys.ORDER_PREFIX}{order_id}"
|
||||
|
||||
@staticmethod
|
||||
def position(pairing_id: str) -> str:
|
||||
return f"{RedisKeys.POSITION_PREFIX}{pairing_id}"
|
||||
|
||||
@staticmethod
|
||||
def pairing(pairing_id: str) -> str:
|
||||
return f"{RedisKeys.PAIRING_PREFIX}{pairing_id}"
|
||||
|
||||
|
||||
class RedisChannels:
|
||||
"""Redis Pub/Sub 频道常量(动态获取环境前缀)"""
|
||||
|
||||
@staticmethod
|
||||
def _get_prefix() -> str:
|
||||
"""获取当前环境的Redis前缀"""
|
||||
try:
|
||||
return settings.environment.redis_prefix
|
||||
except:
|
||||
return "real" # 默认实盘环境
|
||||
|
||||
# 行情频道
|
||||
@property
|
||||
def MARKET_QUOTE(self) -> str:
|
||||
return f"{self._get_prefix()}:market:quote" # 实时行情推送
|
||||
|
||||
@property
|
||||
def MARKET_KLINE(self) -> str:
|
||||
return f"{self._get_prefix()}:market:kline" # K线推送
|
||||
|
||||
# 策略频道(使用settings.channels)
|
||||
@property
|
||||
def STRATEGY_QUOTE(self) -> str:
|
||||
"""策略行情频道(兼容旧代码)"""
|
||||
return settings.channels.kline_update
|
||||
|
||||
@property
|
||||
def STRATEGY_KLINE(self) -> str:
|
||||
"""策略K线频道(兼容旧代码)"""
|
||||
return settings.channels.kline_update
|
||||
|
||||
# 交易频道
|
||||
@property
|
||||
def TRADE_ORDER(self) -> str:
|
||||
return f"{self._get_prefix()}:trade:order" # 订单事件
|
||||
|
||||
@property
|
||||
def TRADE_SIGNAL(self) -> str:
|
||||
return settings.channels.signal_create # 使用统一的信号频道
|
||||
|
||||
@property
|
||||
def TRADE_EXEC(self) -> str:
|
||||
return f"{self._get_prefix()}:trade:exec" # 交易执行(发给 QMT)
|
||||
|
||||
# 账户频道
|
||||
@property
|
||||
def ACCOUNT_UPDATE(self) -> str:
|
||||
return f"{self._get_prefix()}:account:update" # 账户更新
|
||||
|
||||
@property
|
||||
def POSITION_UPDATE(self) -> str:
|
||||
return f"{self._get_prefix()}:position:update" # 持仓更新
|
||||
|
||||
# 系统频道
|
||||
@property
|
||||
def SYSTEM_STATUS(self) -> str:
|
||||
return f"{self._get_prefix()}:system:status" # 系统状态
|
||||
|
||||
# 数据同步频道
|
||||
@property
|
||||
def DATA_DOWNLOAD_RESULT(self) -> str:
|
||||
return f"{self._get_prefix()}:data:download:result" # 下载完成通知
|
||||
|
||||
|
||||
# 全局RedisChannels实例
|
||||
RedisChannels = RedisChannels()
|
||||
|
||||
|
||||
# 全局客户端实例
|
||||
redis_client = RedisClient()
|
||||
|
||||
|
||||
# 便捷函数
|
||||
async def get_redis() -> RedisClient:
|
||||
"""获取 Redis 客户端(确保已连接)"""
|
||||
if redis_client._client is None:
|
||||
await redis_client.connect()
|
||||
return redis_client
|
||||
@ -1,39 +0,0 @@
|
||||
"""
|
||||
QTrade API Schemas
|
||||
|
||||
Pydantic 模型,用于 API 请求/响应的数据验证和序列化
|
||||
|
||||
目录结构:
|
||||
- kline.py: K线数据 Schema
|
||||
- pairing.py: 配对 Schema
|
||||
- order.py: 订单 Schema
|
||||
- position.py: 持仓 Schema
|
||||
- signal.py: 信号 Schema
|
||||
"""
|
||||
|
||||
from .kline import KlineCreate, KlineResponse, KlineQuery
|
||||
from .pairing import PairingCreate, PairingResponse, PairingUpdate
|
||||
from .order import OrderCreate, OrderResponse, OrderUpdate
|
||||
from .position import PositionResponse, PositionSummary
|
||||
from .signal import SignalCreate, SignalResponse
|
||||
|
||||
__all__ = [
|
||||
# K线
|
||||
"KlineCreate",
|
||||
"KlineResponse",
|
||||
"KlineQuery",
|
||||
# 配对
|
||||
"PairingCreate",
|
||||
"PairingResponse",
|
||||
"PairingUpdate",
|
||||
# 订单
|
||||
"OrderCreate",
|
||||
"OrderResponse",
|
||||
"OrderUpdate",
|
||||
# 持仓
|
||||
"PositionResponse",
|
||||
"PositionSummary",
|
||||
# 信号
|
||||
"SignalCreate",
|
||||
"SignalResponse",
|
||||
]
|
||||
@ -1,53 +0,0 @@
|
||||
"""
|
||||
K线数据 Schema
|
||||
|
||||
用于 API 请求/响应
|
||||
"""
|
||||
|
||||
from datetime import datetime as dt
|
||||
from typing import Literal, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class KlineCreate(BaseModel):
|
||||
"""创建K线请求"""
|
||||
|
||||
symbol: str = Field(..., description="股票代码")
|
||||
time: dt = Field(..., description="K线时间")
|
||||
open: float = Field(..., gt=0, description="开盘价")
|
||||
high: float = Field(..., gt=0, description="最高价")
|
||||
low: float = Field(..., gt=0, description="最低价")
|
||||
close: float = Field(..., gt=0, description="收盘价")
|
||||
volume: int = Field(default=0, ge=0, description="成交量")
|
||||
amount: float = Field(default=0, ge=0, description="成交额")
|
||||
|
||||
|
||||
class KlineResponse(BaseModel):
|
||||
"""K线响应"""
|
||||
|
||||
id: int = Field(..., description="K线ID")
|
||||
symbol: str = Field(..., description="股票代码")
|
||||
time: dt = Field(..., description="K线时间")
|
||||
open: float = Field(..., description="开盘价")
|
||||
high: float = Field(..., description="最高价")
|
||||
low: float = Field(..., description="最低价")
|
||||
close: float = Field(..., description="收盘价")
|
||||
volume: int = Field(..., description="成交量")
|
||||
amount: float = Field(..., description="成交额")
|
||||
period: str = Field(..., description="K线周期")
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class KlineQuery(BaseModel):
|
||||
"""K线查询请求"""
|
||||
|
||||
symbol: str = Field(..., description="股票代码")
|
||||
period: Literal["1m", "5m", "15m", "30m", "60m", "1d"] = Field(
|
||||
default="1d", description="K线周期"
|
||||
)
|
||||
start_time: Optional[dt] = Field(None, description="开始时间")
|
||||
end_time: Optional[dt] = Field(None, description="结束时间")
|
||||
limit: int = Field(default=100, ge=1, le=1000, description="返回数量")
|
||||
@ -1,73 +0,0 @@
|
||||
"""
|
||||
订单 Schema
|
||||
|
||||
用于 API 请求/响应
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Literal, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class OrderCreate(BaseModel):
|
||||
"""创建订单请求"""
|
||||
|
||||
pairing_id: str = Field(..., description="配对ID")
|
||||
symbol: str = Field(..., description="股票代码")
|
||||
side: Literal["buy", "sell"] = Field(..., description="订单方向")
|
||||
order_type: Literal["limit", "market"] = Field(
|
||||
default="limit", description="订单类型"
|
||||
)
|
||||
price: float = Field(..., gt=0, description="委托价格")
|
||||
quantity: int = Field(..., gt=0, description="委托数量")
|
||||
signal_id: Optional[str] = Field(None, description="关联信号ID")
|
||||
|
||||
|
||||
class OrderUpdate(BaseModel):
|
||||
"""更新订单请求"""
|
||||
|
||||
status: Optional[str] = Field(None, description="订单状态")
|
||||
filled_quantity: Optional[int] = Field(None, description="成交数量")
|
||||
filled_amount: Optional[float] = Field(None, description="成交金额")
|
||||
avg_price: Optional[float] = Field(None, description="成交均价")
|
||||
message: Optional[str] = Field(None, description="状态消息")
|
||||
|
||||
|
||||
class OrderResponse(BaseModel):
|
||||
"""订单响应"""
|
||||
|
||||
id: str = Field(..., description="订单ID")
|
||||
external_id: Optional[str] = Field(None, description="外部订单ID")
|
||||
pairing_id: str = Field(..., description="配对ID")
|
||||
signal_id: Optional[str] = Field(None, description="信号ID")
|
||||
|
||||
# 订单内容
|
||||
symbol: str = Field(..., description="股票代码")
|
||||
side: str = Field(..., description="订单方向")
|
||||
order_type: str = Field(..., description="订单类型")
|
||||
price: float = Field(..., description="委托价格")
|
||||
quantity: int = Field(..., description="委托数量")
|
||||
|
||||
# 成交信息
|
||||
filled_quantity: int = Field(default=0, description="成交数量")
|
||||
filled_amount: float = Field(default=0, description="成交金额")
|
||||
avg_price: Optional[float] = Field(None, description="成交均价")
|
||||
unfilled_quantity: int = Field(..., description="未成交数量")
|
||||
commission: float = Field(default=0, description="手续费")
|
||||
|
||||
# 状态
|
||||
status: str = Field(..., description="订单状态")
|
||||
is_active: bool = Field(..., description="是否活跃")
|
||||
is_finished: bool = Field(..., description="是否已结束")
|
||||
message: Optional[str] = Field(None, description="状态消息")
|
||||
|
||||
# 时间
|
||||
created_at: datetime = Field(..., description="创建时间")
|
||||
updated_at: datetime = Field(..., description="更新时间")
|
||||
submitted_at: Optional[datetime] = Field(None, description="提交时间")
|
||||
filled_at: Optional[datetime] = Field(None, description="成交时间")
|
||||
cancelled_at: Optional[datetime] = Field(None, description="撤销时间")
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
@ -1,68 +0,0 @@
|
||||
"""
|
||||
股票-策略配对 Schema
|
||||
|
||||
用于 API 请求/响应
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class PairingCreate(BaseModel):
|
||||
"""创建配对请求"""
|
||||
|
||||
symbol: str = Field(..., description="股票代码")
|
||||
symbol_name: Optional[str] = Field(None, description="股票名称")
|
||||
strategy_id: str = Field(..., description="策略ID")
|
||||
strategy_name: Optional[str] = Field(None, description="策略名称")
|
||||
initial_capital: float = Field(..., gt=0, description="初始资金")
|
||||
params: Optional[dict] = Field(default_factory=dict, description="策略参数")
|
||||
remark: Optional[str] = Field(None, description="备注")
|
||||
|
||||
|
||||
class PairingUpdate(BaseModel):
|
||||
"""更新配对请求"""
|
||||
|
||||
status: Optional[str] = Field(None, description="状态")
|
||||
params: Optional[dict] = Field(None, description="策略参数")
|
||||
remark: Optional[str] = Field(None, description="备注")
|
||||
|
||||
|
||||
class PairingResponse(BaseModel):
|
||||
"""配对响应"""
|
||||
|
||||
id: str = Field(..., description="配对ID")
|
||||
symbol: str = Field(..., description="股票代码")
|
||||
symbol_name: Optional[str] = Field(None, description="股票名称")
|
||||
strategy_id: str = Field(..., description="策略ID")
|
||||
strategy_name: Optional[str] = Field(None, description="策略名称")
|
||||
|
||||
# 资金
|
||||
initial_capital: float = Field(..., description="初始资金")
|
||||
available_capital: float = Field(..., description="可用资金")
|
||||
frozen_capital: float = Field(..., description="冻结资金")
|
||||
current_capital: float = Field(..., description="当前总资金")
|
||||
|
||||
# 状态
|
||||
status: str = Field(..., description="配对状态")
|
||||
|
||||
# 策略参数
|
||||
params: Optional[dict] = Field(None, description="策略参数")
|
||||
|
||||
# 统计
|
||||
total_trades: int = Field(default=0, description="总交易次数")
|
||||
win_trades: int = Field(default=0, description="盈利次数")
|
||||
loss_trades: int = Field(default=0, description="亏损次数")
|
||||
win_rate: Optional[float] = Field(None, description="胜率")
|
||||
total_pnl: float = Field(default=0, description="累计盈亏")
|
||||
return_rate: float = Field(default=0, description="收益率(%)")
|
||||
max_drawdown: float = Field(default=0, description="最大回撤率")
|
||||
|
||||
# 时间
|
||||
created_at: datetime = Field(..., description="创建时间")
|
||||
updated_at: datetime = Field(..., description="更新时间")
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
@ -1,53 +0,0 @@
|
||||
"""
|
||||
持仓 Schema
|
||||
|
||||
用于 API 请求/响应
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class PositionResponse(BaseModel):
|
||||
"""持仓响应"""
|
||||
|
||||
id: str = Field(..., description="持仓ID")
|
||||
pairing_id: str = Field(..., description="配对ID")
|
||||
symbol: str = Field(..., description="股票代码")
|
||||
symbol_name: Optional[str] = Field(None, description="股票名称")
|
||||
|
||||
# 数量
|
||||
quantity: int = Field(default=0, description="持仓数量")
|
||||
available: int = Field(default=0, description="可用数量")
|
||||
frozen: int = Field(default=0, description="冻结数量")
|
||||
|
||||
# 成本
|
||||
avg_cost: float = Field(default=0, description="持仓成本价")
|
||||
total_cost: float = Field(default=0, description="总成本")
|
||||
|
||||
# 盈亏
|
||||
last_price: Optional[float] = Field(None, description="最新价格")
|
||||
market_value: Optional[float] = Field(None, description="市值")
|
||||
unrealized_pnl: Optional[float] = Field(None, description="浮动盈亏")
|
||||
realized_pnl: float = Field(default=0, description="已实现盈亏")
|
||||
pnl_ratio: Optional[float] = Field(None, description="盈亏比例(%)")
|
||||
|
||||
# 时间
|
||||
created_at: datetime = Field(..., description="创建时间")
|
||||
updated_at: datetime = Field(..., description="更新时间")
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class PositionSummary(BaseModel):
|
||||
"""持仓汇总"""
|
||||
|
||||
pairing_id: str = Field(..., description="配对ID")
|
||||
total_market_value: float = Field(default=0, description="总市值")
|
||||
total_cost: float = Field(default=0, description="总成本")
|
||||
total_unrealized_pnl: float = Field(default=0, description="总浮动盈亏")
|
||||
total_realized_pnl: float = Field(default=0, description="总已实现盈亏")
|
||||
position_count: int = Field(default=0, description="持仓品种数")
|
||||
@ -1,59 +0,0 @@
|
||||
"""
|
||||
交易信号 Schema
|
||||
|
||||
用于 API 请求/响应
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Literal, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class SignalCreate(BaseModel):
|
||||
"""创建信号请求"""
|
||||
|
||||
pairing_id: str = Field(..., description="配对ID")
|
||||
symbol: str = Field(..., description="股票代码")
|
||||
strategy_id: str = Field(..., description="策略ID")
|
||||
side: Literal["buy", "sell"] = Field(..., description="信号方向")
|
||||
price: float = Field(..., gt=0, description="建议价格")
|
||||
quantity: int = Field(..., gt=0, description="建议数量")
|
||||
source: Optional[str] = Field(None, description="信号来源")
|
||||
reason: Optional[str] = Field(None, description="信号原因")
|
||||
expired_at: Optional[datetime] = Field(None, description="过期时间")
|
||||
|
||||
|
||||
class SignalResponse(BaseModel):
|
||||
"""信号响应"""
|
||||
|
||||
id: str = Field(..., description="信号ID")
|
||||
pairing_id: str = Field(..., description="配对ID")
|
||||
order_id: Optional[str] = Field(None, description="关联订单ID")
|
||||
|
||||
# 信号内容
|
||||
symbol: str = Field(..., description="股票代码")
|
||||
strategy_id: str = Field(..., description="策略ID")
|
||||
side: str = Field(..., description="信号方向")
|
||||
price: float = Field(..., description="建议价格")
|
||||
quantity: int = Field(..., description="建议数量")
|
||||
signal_amount: float = Field(..., description="信号金额")
|
||||
|
||||
# 来源
|
||||
source: Optional[str] = Field(None, description="信号来源")
|
||||
reason: Optional[str] = Field(None, description="信号原因")
|
||||
|
||||
# 状态
|
||||
status: str = Field(..., description="信号状态")
|
||||
is_pending: bool = Field(..., description="是否待处理")
|
||||
is_finished: bool = Field(..., description="是否已结束")
|
||||
message: Optional[str] = Field(None, description="状态消息")
|
||||
|
||||
# 时间
|
||||
created_at: datetime = Field(..., description="创建时间")
|
||||
updated_at: datetime = Field(..., description="更新时间")
|
||||
executed_at: Optional[datetime] = Field(None, description="执行时间")
|
||||
expired_at: Optional[datetime] = Field(None, description="过期时间")
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
@ -1,511 +0,0 @@
|
||||
"""
|
||||
服务管理器
|
||||
|
||||
统一管理所有服务的启动、停止和配置
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import time
|
||||
from enum import Enum
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from src.core.logger import get_logger
|
||||
|
||||
logger = get_logger("service_manager")
|
||||
|
||||
|
||||
class ServiceStatus(str, Enum):
|
||||
"""服务状态"""
|
||||
|
||||
STOPPED = "stopped"
|
||||
STARTING = "starting"
|
||||
RUNNING = "running"
|
||||
STOPPING = "stopping"
|
||||
ERROR = "error"
|
||||
|
||||
|
||||
class Service:
|
||||
"""服务基类"""
|
||||
|
||||
def __init__(self, name: str, **config):
|
||||
self.name = name
|
||||
self.config = config
|
||||
self.status = ServiceStatus.STOPPED
|
||||
self.error: Optional[str] = None
|
||||
|
||||
async def start(self):
|
||||
"""启动服务 (子类实现)"""
|
||||
raise NotImplementedError
|
||||
|
||||
async def stop(self):
|
||||
"""停止服务 (子类实现)"""
|
||||
raise NotImplementedError
|
||||
|
||||
def configure(self, **config):
|
||||
"""更新配置"""
|
||||
self.config.update(config)
|
||||
|
||||
|
||||
class ServiceManager:
|
||||
"""
|
||||
服务管理器
|
||||
|
||||
用法:
|
||||
manager = ServiceManager()
|
||||
|
||||
# 注册服务
|
||||
manager.register("redis", RedisService, host="127.0.0.1", port=6379)
|
||||
manager.register("database", DatabaseService)
|
||||
|
||||
# 配置服务
|
||||
manager.configure("redis", password="xxx")
|
||||
|
||||
# 启动/停止
|
||||
await manager.start("redis")
|
||||
await manager.start_all()
|
||||
await manager.stop("redis")
|
||||
await manager.stop_all()
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._services: dict[str, Service] = {}
|
||||
self._start_order: list[str] = [] # 启动顺序
|
||||
|
||||
def register(
|
||||
self,
|
||||
service: Service | str,
|
||||
service_class: type[Service] = None,
|
||||
**config,
|
||||
) -> "ServiceManager":
|
||||
"""
|
||||
注册服务
|
||||
|
||||
Args:
|
||||
service: 服务实例或服务名称
|
||||
service_class: 服务类(当 service 为名称时需要)
|
||||
**config: 服务配置(当 service 为名称时需要)
|
||||
|
||||
Returns:
|
||||
self (支持链式调用)
|
||||
"""
|
||||
# 支持两种方式:
|
||||
# 1. register(service_instance) # 直接传实例
|
||||
# 2. register("name", ServiceClass, **config) # 传名称和类
|
||||
if isinstance(service, Service):
|
||||
# 方式 1: 直接传实例
|
||||
name = service.name
|
||||
service_instance = service
|
||||
else:
|
||||
# 方式 2: 传名称和类
|
||||
name = service
|
||||
if service_class is None:
|
||||
raise ValueError("必须提供 service_class 参数")
|
||||
service_instance = service_class(name, **config)
|
||||
|
||||
if name in self._services:
|
||||
logger.warning(f"服务 {name} 已存在,将被覆盖")
|
||||
|
||||
self._services[name] = service_instance
|
||||
self._start_order.append(name)
|
||||
|
||||
logger.debug(f"注册服务: {name}")
|
||||
return self
|
||||
|
||||
def configure(self, name: str, **config) -> "ServiceManager":
|
||||
"""
|
||||
配置服务
|
||||
|
||||
Args:
|
||||
name: 服务名称
|
||||
**config: 配置项
|
||||
|
||||
Returns:
|
||||
self (支持链式调用)
|
||||
"""
|
||||
if name not in self._services:
|
||||
raise ValueError(f"服务 {name} 未注册")
|
||||
|
||||
self._services[name].configure(**config)
|
||||
logger.debug(f"配置服务 {name}: {config}")
|
||||
return self
|
||||
|
||||
def get(self, name: str) -> Optional[Service]:
|
||||
"""获取服务实例"""
|
||||
return self._services.get(name)
|
||||
|
||||
async def start(self, name: str) -> bool:
|
||||
"""
|
||||
启动单个服务
|
||||
|
||||
Args:
|
||||
name: 服务名称
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
if name not in self._services:
|
||||
logger.error(f"服务 {name} 未注册")
|
||||
return False
|
||||
|
||||
service = self._services[name]
|
||||
|
||||
if service.status == ServiceStatus.RUNNING:
|
||||
logger.warning(f"服务 {name} 已在运行")
|
||||
return True
|
||||
|
||||
try:
|
||||
service.status = ServiceStatus.STARTING
|
||||
logger.info(f"启动服务: {name}")
|
||||
|
||||
await service.start()
|
||||
|
||||
service.status = ServiceStatus.RUNNING
|
||||
service.error = None
|
||||
logger.info(f"✓ 服务 {name} 已启动")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
service.status = ServiceStatus.ERROR
|
||||
service.error = str(e)
|
||||
logger.error(f"✗ 服务 {name} 启动失败: {e}")
|
||||
return False
|
||||
|
||||
async def stop(self, name: str) -> bool:
|
||||
"""
|
||||
停止单个服务
|
||||
|
||||
Args:
|
||||
name: 服务名称
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
if name not in self._services:
|
||||
logger.error(f"服务 {name} 未注册")
|
||||
return False
|
||||
|
||||
service = self._services[name]
|
||||
|
||||
if service.status == ServiceStatus.STOPPED:
|
||||
return True
|
||||
|
||||
try:
|
||||
service.status = ServiceStatus.STOPPING
|
||||
logger.info(f"停止服务: {name}")
|
||||
|
||||
await service.stop()
|
||||
|
||||
service.status = ServiceStatus.STOPPED
|
||||
logger.info(f"✓ 服务 {name} 已停止")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
service.status = ServiceStatus.ERROR
|
||||
service.error = str(e)
|
||||
logger.error(f"✗ 服务 {name} 停止失败: {e}")
|
||||
return False
|
||||
|
||||
async def start_all(self) -> dict[str, bool]:
|
||||
"""
|
||||
按顺序启动所有服务
|
||||
|
||||
Returns:
|
||||
{服务名: 是否成功}
|
||||
"""
|
||||
# 显示启动计划
|
||||
logger.info("\n准备启动以下服务:")
|
||||
for i, name in enumerate(self._start_order, 1):
|
||||
service = self._services[name]
|
||||
if hasattr(service, "port"):
|
||||
logger.info(f" {i}. {name} (端口: {service.port})")
|
||||
else:
|
||||
logger.info(f" {i}. {name}")
|
||||
logger.info("")
|
||||
|
||||
# 启动所有服务
|
||||
results = {}
|
||||
for i, name in enumerate(self._start_order, 1):
|
||||
logger.info(f"[{i}/{len(self._start_order)}] 正在启动 {name}...")
|
||||
results[name] = await self.start(name)
|
||||
|
||||
# 显示结果摘要
|
||||
success_count = sum(1 for v in results.values() if v)
|
||||
logger.info("\n" + "=" * 70)
|
||||
logger.info(f"服务启动完成: {success_count}/{len(results)} 成功")
|
||||
logger.info("=" * 70)
|
||||
|
||||
for name, success in results.items():
|
||||
status = "✓ 运行中" if success else "✗ 失败"
|
||||
logger.info(f" {name}: {status}")
|
||||
|
||||
if success_count < len(results):
|
||||
logger.info("\n💡 提示: 查看日志文件以获取详细错误信息")
|
||||
logger.info(f" 日志目录: logs/")
|
||||
|
||||
return results
|
||||
|
||||
async def stop_all(self) -> dict[str, bool]:
|
||||
"""
|
||||
按逆序停止所有服务
|
||||
|
||||
Returns:
|
||||
{服务名: 是否成功}
|
||||
"""
|
||||
results = {}
|
||||
for name in reversed(self._start_order):
|
||||
results[name] = await self.stop(name)
|
||||
return results
|
||||
|
||||
def status(self, name: str) -> Optional[ServiceStatus]:
|
||||
"""获取服务状态"""
|
||||
service = self._services.get(name)
|
||||
return service.status if service else None
|
||||
|
||||
def list_services(self) -> list[dict]:
|
||||
"""
|
||||
列出所有服务状态
|
||||
|
||||
Returns:
|
||||
[{name, status, error}, ...]
|
||||
"""
|
||||
return [
|
||||
{
|
||||
"name": name,
|
||||
"status": service.status.value,
|
||||
"error": service.error,
|
||||
}
|
||||
for name, service in self._services.items()
|
||||
]
|
||||
|
||||
def print_status(self):
|
||||
"""打印服务状态表"""
|
||||
print("\n服务状态:")
|
||||
print("-" * 40)
|
||||
for name, service in self._services.items():
|
||||
icon = {
|
||||
ServiceStatus.RUNNING: "✓",
|
||||
ServiceStatus.STOPPED: "○",
|
||||
ServiceStatus.ERROR: "✗",
|
||||
ServiceStatus.STARTING: "◐",
|
||||
ServiceStatus.STOPPING: "◑",
|
||||
}.get(service.status, "?")
|
||||
print(f" {icon} {name}: {service.status.value}")
|
||||
if service.error:
|
||||
print(f" 错误: {service.error}")
|
||||
print("-" * 40)
|
||||
|
||||
|
||||
# ============== 内置服务实现 ==============
|
||||
|
||||
|
||||
class RedisService(Service):
|
||||
"""Redis 服务"""
|
||||
|
||||
def __init__(self, name: str, **config):
|
||||
super().__init__(name, **config)
|
||||
self._client = None
|
||||
|
||||
async def start(self):
|
||||
from src.core.redis_client import redis_client
|
||||
|
||||
self._client = redis_client
|
||||
await redis_client.connect()
|
||||
|
||||
async def stop(self):
|
||||
if self._client:
|
||||
await self._client.disconnect()
|
||||
self._client = None
|
||||
|
||||
|
||||
class DatabaseService(Service):
|
||||
"""数据库服务"""
|
||||
|
||||
def __init__(self, name: str, **config):
|
||||
super().__init__(name, **config)
|
||||
self._db = None
|
||||
|
||||
async def start(self):
|
||||
from src.core.database import db
|
||||
|
||||
self._db = db
|
||||
await db.connect()
|
||||
|
||||
async def stop(self):
|
||||
if self._db:
|
||||
await self._db.disconnect()
|
||||
self._db = None
|
||||
|
||||
|
||||
class QMTService(Service):
|
||||
"""QMT 数据服务"""
|
||||
|
||||
def __init__(self, name: str, **config):
|
||||
super().__init__(name, **config)
|
||||
self._downloader = None
|
||||
|
||||
async def start(self):
|
||||
from src.qmt_service.services.data_downloader import data_downloader
|
||||
|
||||
self._downloader = data_downloader
|
||||
await data_downloader.init()
|
||||
|
||||
async def stop(self):
|
||||
# QMT 数据下载器目前没有显式的关闭方法
|
||||
self._downloader = None
|
||||
|
||||
@property
|
||||
def downloader(self):
|
||||
return self._downloader
|
||||
|
||||
|
||||
class DataSyncService(Service):
|
||||
"""
|
||||
数据同步服务
|
||||
|
||||
后台服务,监听 Redis 队列接收下载命令
|
||||
"""
|
||||
|
||||
def __init__(self, name: str, **config):
|
||||
super().__init__(name, **config)
|
||||
self._service = None
|
||||
|
||||
async def start(self):
|
||||
# data_sync_service 已移除,如需数据同步请实现新服务或用 data_downloader 替代
|
||||
self._service = None
|
||||
pass
|
||||
|
||||
async def stop(self):
|
||||
self._service = None
|
||||
pass
|
||||
|
||||
@property
|
||||
def service(self):
|
||||
return self._service
|
||||
|
||||
|
||||
# 全局服务管理器实例
|
||||
service_manager = ServiceManager()
|
||||
|
||||
|
||||
# ============== HTTP 服务实现 ==============
|
||||
|
||||
|
||||
class HTTPService(Service):
|
||||
"""
|
||||
HTTP 服务(外部进程)
|
||||
|
||||
用于启动 FastAPI/Uvicorn 服务
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, name: str, app: str, host: str, port: int, env: dict = None, **config
|
||||
):
|
||||
"""
|
||||
Args:
|
||||
name: 服务名称
|
||||
app: FastAPI 应用路径,如 "src.data_service.app:app"
|
||||
host: 服务主机
|
||||
port: 服务端口
|
||||
env: 环境变量字典
|
||||
**config: 其他配置
|
||||
"""
|
||||
super().__init__(name, **config)
|
||||
self.app = app
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.env = env or {}
|
||||
self._process = None
|
||||
self._log_file = None # 日志文件路径
|
||||
|
||||
async def start(self):
|
||||
"""启动 HTTP 服务"""
|
||||
from pathlib import Path
|
||||
import os
|
||||
|
||||
project_root = Path(__file__).parent.parent.parent
|
||||
logs_dir = project_root / "logs"
|
||||
logs_dir.mkdir(exist_ok=True)
|
||||
|
||||
# 日志文件路径
|
||||
self._log_file = logs_dir / f"{self.name.lower()}.log"
|
||||
|
||||
# 构建环境变量
|
||||
env = os.environ.copy()
|
||||
env.update(self.env)
|
||||
|
||||
# 在后台启动服务(不弹窗)
|
||||
with open(self._log_file, "w", encoding="utf-8") as log:
|
||||
self._process = subprocess.Popen(
|
||||
[
|
||||
"uvicorn",
|
||||
self.app,
|
||||
"--host",
|
||||
self.host,
|
||||
"--port",
|
||||
str(self.port),
|
||||
],
|
||||
stdout=log,
|
||||
stderr=subprocess.STDOUT,
|
||||
cwd=str(project_root),
|
||||
env=env,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW
|
||||
if hasattr(subprocess, "CREATE_NO_WINDOW")
|
||||
else 0,
|
||||
)
|
||||
|
||||
# 等待服务启动
|
||||
time.sleep(3)
|
||||
|
||||
# 检查健康状态
|
||||
if await self._check_health():
|
||||
logger.info(f"✓ {self.name} 启动成功 (端口: {self.port})")
|
||||
else:
|
||||
logger.warning(
|
||||
f"⚠️ {self.name} 启动失败或未响应\n 请查看日志: {self._log_file}"
|
||||
)
|
||||
|
||||
async def stop(self):
|
||||
"""停止 HTTP 服务"""
|
||||
if self._process:
|
||||
try:
|
||||
self._process.terminate()
|
||||
self._process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
self._process.kill()
|
||||
except Exception as e:
|
||||
logger.warning(f"停止 {self.name} 时出错: {e}")
|
||||
finally:
|
||||
self._process = None
|
||||
|
||||
async def _check_health(self, max_retry: int = 3) -> bool:
|
||||
"""检查服务健康状态"""
|
||||
for i in range(max_retry):
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=5.0) as client:
|
||||
response = await client.get(
|
||||
f"http://{self.host}:{self.port}/health"
|
||||
)
|
||||
if response.status_code == 200:
|
||||
return True
|
||||
except Exception:
|
||||
if i < max_retry - 1:
|
||||
await asyncio.sleep(2)
|
||||
return False
|
||||
|
||||
async def check_health(self) -> dict:
|
||||
"""获取服务健康状态详情"""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=5.0) as client:
|
||||
response = await client.get(f"http://{self.host}:{self.port}/health")
|
||||
if response.status_code == 200:
|
||||
return {"healthy": True, "data": response.json()}
|
||||
else:
|
||||
return {"healthy": False, "error": f"HTTP {response.status_code}"}
|
||||
except Exception as e:
|
||||
return {"healthy": False, "error": str(e)}
|
||||
|
||||
|
||||
# 需要导入 asyncio
|
||||
import asyncio # noqa: E402
|
||||
@ -1,10 +0,0 @@
|
||||
"""
|
||||
统一策略框架
|
||||
|
||||
实盘、回测、模拟盘共用的策略基类和工具
|
||||
"""
|
||||
|
||||
from .base_strategy import BaseStrategy, Signal, StrategyContext
|
||||
from .registry import strategy_registry
|
||||
|
||||
__all__ = ["BaseStrategy", "Signal", "StrategyContext", "strategy_registry"]
|
||||
@ -1,232 +0,0 @@
|
||||
"""
|
||||
策略基类
|
||||
|
||||
实盘和回测统一的策略接口
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any, Optional
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class Signal(BaseModel):
|
||||
"""
|
||||
交易信号
|
||||
|
||||
策略返回的交易指令
|
||||
"""
|
||||
|
||||
action: str = Field(..., description="操作 buy/sell/hold")
|
||||
price: float = Field(..., description="建议价格")
|
||||
quantity: int = Field(..., description="数量")
|
||||
reason: str = Field(default="", description="信号原因")
|
||||
timestamp: datetime = Field(default_factory=datetime.now, description="信号时间")
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
|
||||
|
||||
class StrategyContext(BaseModel):
|
||||
"""
|
||||
策略上下文
|
||||
|
||||
由执行器提供,包含策略运行所需的环境信息
|
||||
"""
|
||||
|
||||
# 基本信息
|
||||
symbol: str = Field(..., description="股票代码")
|
||||
strategy_id: str = Field(..., description="策略ID")
|
||||
|
||||
# 资金信息
|
||||
cash: float = Field(default=0, description="可用资金")
|
||||
initial_capital: float = Field(default=0, description="初始资金")
|
||||
|
||||
# 持仓信息
|
||||
position: int = Field(default=0, description="持仓数量")
|
||||
position_available: int = Field(default=0, description="可用持仓")
|
||||
avg_price: float = Field(default=0, description="持仓均价")
|
||||
|
||||
# 策略参数
|
||||
params: dict = Field(default_factory=dict, description="策略参数")
|
||||
|
||||
class Config:
|
||||
extra = "allow"
|
||||
|
||||
|
||||
class BaseStrategy(ABC):
|
||||
"""
|
||||
策略基类
|
||||
|
||||
所有策略必须继承此类并实现 init() 和 handle_kline() 方法
|
||||
|
||||
示例:
|
||||
class MyStrategy(BaseStrategy):
|
||||
strategy_id = "my_strategy"
|
||||
strategy_name = "我的策略"
|
||||
|
||||
def init(self):
|
||||
self.ma5 = []
|
||||
self.ma10 = []
|
||||
|
||||
def handle_kline(self, kline: dict) -> Optional[Signal]:
|
||||
# 只处理日K
|
||||
if kline["period"] != "1d":
|
||||
return None
|
||||
|
||||
# 策略逻辑...
|
||||
return Signal(action="buy", price=10.0, quantity=100)
|
||||
"""
|
||||
|
||||
# ========== 策略元信息(子类必须设置) ==========
|
||||
|
||||
strategy_id: str = ""
|
||||
strategy_name: str = ""
|
||||
description: str = ""
|
||||
version: str = "1.0.0"
|
||||
author: str = ""
|
||||
|
||||
# 参数定义(子类可选设置)
|
||||
params_schema: dict = {}
|
||||
|
||||
def __init__(self, context: StrategyContext):
|
||||
"""
|
||||
初始化策略
|
||||
|
||||
Args:
|
||||
context: 策略上下文(由执行器提供)
|
||||
"""
|
||||
self.context = context
|
||||
|
||||
# ========== 核心接口(子类必须实现) ==========
|
||||
|
||||
def init(self):
|
||||
"""
|
||||
策略初始化(只调用一次)
|
||||
|
||||
用于:
|
||||
- 初始化策略变量
|
||||
- 加载历史数据
|
||||
- 初始化指标
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def handle_kline(self, kline: dict) -> Optional[Signal]:
|
||||
"""
|
||||
处理K线数据(核心接口)
|
||||
|
||||
无论是实盘tick还是回测K线,都调用此方法
|
||||
|
||||
Args:
|
||||
kline: K线数据
|
||||
{
|
||||
"symbol": "000001.SZ",
|
||||
"timestamp": "2025-12-11T10:30:00",
|
||||
"period": "tick" | "1m" | "5m" | "15m" | "30m" | "1h" | "1d",
|
||||
"open": 10.0,
|
||||
"high": 10.1,
|
||||
"low": 9.9,
|
||||
"close": 10.05,
|
||||
"volume": 1000,
|
||||
"amount": 100000.0
|
||||
}
|
||||
|
||||
Returns:
|
||||
Signal: 交易信号,None表示不交易
|
||||
"""
|
||||
pass
|
||||
|
||||
# ========== 状态管理(用于实盘持久化) ==========
|
||||
|
||||
def get_state(self) -> dict:
|
||||
"""
|
||||
获取策略状态(用于持久化)
|
||||
|
||||
实盘在休盘时会调用此方法保存策略状态
|
||||
|
||||
Returns:
|
||||
包含策略状态的字典(需要可JSON序列化)
|
||||
"""
|
||||
return {}
|
||||
|
||||
def set_state(self, state: dict):
|
||||
"""
|
||||
恢复策略状态
|
||||
|
||||
实盘启动时会调用此方法恢复上次保存的状态
|
||||
|
||||
Args:
|
||||
state: 状态字典
|
||||
"""
|
||||
pass
|
||||
|
||||
# ========== 工具属性 ==========
|
||||
|
||||
@property
|
||||
def symbol(self) -> str:
|
||||
"""股票代码"""
|
||||
return self.context.symbol
|
||||
|
||||
@property
|
||||
def cash(self) -> float:
|
||||
"""可用资金"""
|
||||
return self.context.cash
|
||||
|
||||
@property
|
||||
def position(self) -> int:
|
||||
"""持仓数量"""
|
||||
return self.context.position
|
||||
|
||||
@property
|
||||
def position_available(self) -> int:
|
||||
"""可用持仓"""
|
||||
return self.context.position_available
|
||||
|
||||
@property
|
||||
def avg_price(self) -> float:
|
||||
"""持仓均价"""
|
||||
return self.context.avg_price
|
||||
|
||||
@property
|
||||
def params(self) -> dict:
|
||||
"""策略参数"""
|
||||
return self.context.params
|
||||
|
||||
def get_param(self, key: str, default: Any = None) -> Any:
|
||||
"""
|
||||
获取策略参数
|
||||
|
||||
Args:
|
||||
key: 参数名
|
||||
default: 默认值
|
||||
|
||||
Returns:
|
||||
参数值
|
||||
"""
|
||||
return self.context.params.get(key, default)
|
||||
|
||||
def update_context(
|
||||
self,
|
||||
cash: Optional[float] = None,
|
||||
position: Optional[int] = None,
|
||||
position_available: Optional[int] = None,
|
||||
avg_price: Optional[float] = None,
|
||||
):
|
||||
"""
|
||||
更新上下文(由执行器调用)
|
||||
|
||||
Args:
|
||||
cash: 可用资金
|
||||
position: 持仓数量
|
||||
position_available: 可用持仓
|
||||
avg_price: 持仓均价
|
||||
"""
|
||||
if cash is not None:
|
||||
self.context.cash = cash
|
||||
if position is not None:
|
||||
self.context.position = position
|
||||
if position_available is not None:
|
||||
self.context.position_available = position_available
|
||||
if avg_price is not None:
|
||||
self.context.avg_price = avg_price
|
||||
@ -1,343 +0,0 @@
|
||||
"""
|
||||
技术指标库
|
||||
|
||||
基于TA-Lib的指标计算封装
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
from typing import List, Tuple, Optional
|
||||
|
||||
try:
|
||||
import talib
|
||||
|
||||
TALIB_AVAILABLE = True
|
||||
except ImportError:
|
||||
TALIB_AVAILABLE = False
|
||||
|
||||
|
||||
class Indicators:
|
||||
"""
|
||||
技术指标计算
|
||||
|
||||
封装TA-Lib提供常用技术指标计算
|
||||
|
||||
注意: 需要安装 TA-Lib
|
||||
pip install TA-Lib
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def _check_talib():
|
||||
"""检查TA-Lib是否可用"""
|
||||
if not TALIB_AVAILABLE:
|
||||
raise ImportError(
|
||||
"TA-Lib未安装,请先安装: pip install TA-Lib\n"
|
||||
"Windows用户可能需要下载whl文件: "
|
||||
"https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _to_array(data: List[float]) -> np.ndarray:
|
||||
"""转换为numpy数组"""
|
||||
return np.array(data, dtype=np.float64)
|
||||
|
||||
# ========== 移动平均线 ==========
|
||||
|
||||
@staticmethod
|
||||
def SMA(prices: List[float], period: int) -> np.ndarray:
|
||||
"""
|
||||
简单移动平均线
|
||||
|
||||
Args:
|
||||
prices: 价格列表
|
||||
period: 周期
|
||||
|
||||
Returns:
|
||||
MA值数组
|
||||
"""
|
||||
Indicators._check_talib()
|
||||
return talib.SMA(Indicators._to_array(prices), timeperiod=period)
|
||||
|
||||
@staticmethod
|
||||
def EMA(prices: List[float], period: int) -> np.ndarray:
|
||||
"""
|
||||
指数移动平均线
|
||||
|
||||
Args:
|
||||
prices: 价格列表
|
||||
period: 周期
|
||||
|
||||
Returns:
|
||||
EMA值数组
|
||||
"""
|
||||
Indicators._check_talib()
|
||||
return talib.EMA(Indicators._to_array(prices), timeperiod=period)
|
||||
|
||||
@staticmethod
|
||||
def MA(prices: List[float], period: int, ma_type: str = "SMA") -> np.ndarray:
|
||||
"""
|
||||
移动平均线(通用)
|
||||
|
||||
Args:
|
||||
prices: 价格列表
|
||||
period: 周期
|
||||
ma_type: 类型 "SMA" | "EMA" | "WMA"
|
||||
|
||||
Returns:
|
||||
MA值数组
|
||||
"""
|
||||
if ma_type == "EMA":
|
||||
return Indicators.EMA(prices, period)
|
||||
elif ma_type == "WMA":
|
||||
Indicators._check_talib()
|
||||
return talib.WMA(Indicators._to_array(prices), timeperiod=period)
|
||||
else:
|
||||
return Indicators.SMA(prices, period)
|
||||
|
||||
# ========== MACD ==========
|
||||
|
||||
@staticmethod
|
||||
def MACD(
|
||||
prices: List[float],
|
||||
fast_period: int = 12,
|
||||
slow_period: int = 26,
|
||||
signal_period: int = 9,
|
||||
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
|
||||
"""
|
||||
MACD指标
|
||||
|
||||
Args:
|
||||
prices: 价格列表
|
||||
fast_period: 快线周期,默认12
|
||||
slow_period: 慢线周期,默认26
|
||||
signal_period: 信号线周期,默认9
|
||||
|
||||
Returns:
|
||||
(macd, signal, hist) 元组
|
||||
"""
|
||||
Indicators._check_talib()
|
||||
prices_array = Indicators._to_array(prices)
|
||||
macd, signal, hist = talib.MACD(
|
||||
prices_array,
|
||||
fastperiod=fast_period,
|
||||
slowperiod=slow_period,
|
||||
signalperiod=signal_period,
|
||||
)
|
||||
return macd, signal, hist
|
||||
|
||||
# ========== KDJ ==========
|
||||
|
||||
@staticmethod
|
||||
def KDJ(
|
||||
high: List[float],
|
||||
low: List[float],
|
||||
close: List[float],
|
||||
fastk_period: int = 9,
|
||||
slowk_period: int = 3,
|
||||
slowd_period: int = 3,
|
||||
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
|
||||
"""
|
||||
KDJ指标
|
||||
|
||||
注意: TA-Lib没有KDJ,使用STOCH计算K和D,J=3K-2D
|
||||
|
||||
Args:
|
||||
high: 最高价列表
|
||||
low: 最低价列表
|
||||
close: 收盘价列表
|
||||
fastk_period: K值周期,默认9
|
||||
slowk_period: K平滑周期,默认3
|
||||
slowd_period: D平滑周期,默认3
|
||||
|
||||
Returns:
|
||||
(k, d, j) 元组
|
||||
"""
|
||||
Indicators._check_talib()
|
||||
high_array = Indicators._to_array(high)
|
||||
low_array = Indicators._to_array(low)
|
||||
close_array = Indicators._to_array(close)
|
||||
|
||||
from talib._ta_lib import MA_Type
|
||||
|
||||
k, d = talib.STOCH(
|
||||
high_array,
|
||||
low_array,
|
||||
close_array,
|
||||
fastk_period=fastk_period,
|
||||
slowk_period=slowk_period,
|
||||
slowk_matype=MA_Type.SMA,
|
||||
slowd_period=slowd_period,
|
||||
slowd_matype=MA_Type.SMA,
|
||||
)
|
||||
|
||||
# 计算J值: J = 3K - 2D
|
||||
j = 3 * k - 2 * d
|
||||
|
||||
return k, d, j
|
||||
|
||||
# ========== RSI ==========
|
||||
|
||||
@staticmethod
|
||||
def RSI(prices: List[float], period: int = 14) -> np.ndarray:
|
||||
"""
|
||||
相对强弱指标
|
||||
|
||||
Args:
|
||||
prices: 价格列表
|
||||
period: 周期,默认14
|
||||
|
||||
Returns:
|
||||
RSI值数组
|
||||
"""
|
||||
Indicators._check_talib()
|
||||
return talib.RSI(Indicators._to_array(prices), timeperiod=period)
|
||||
|
||||
# ========== 布林带 ==========
|
||||
|
||||
@staticmethod
|
||||
def BBANDS(
|
||||
prices: List[float],
|
||||
period: int = 20,
|
||||
nbdevup: float = 2.0,
|
||||
nbdevdn: float = 2.0,
|
||||
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
|
||||
"""
|
||||
布林带
|
||||
|
||||
Args:
|
||||
prices: 价格列表
|
||||
period: 周期,默认20
|
||||
nbdevup: 上轨标准差倍数,默认2
|
||||
nbdevdn: 下轨标准差倍数,默认2
|
||||
|
||||
Returns:
|
||||
(upper, middle, lower) 元组
|
||||
"""
|
||||
Indicators._check_talib()
|
||||
from talib._ta_lib import MA_Type
|
||||
|
||||
prices_array = Indicators._to_array(prices)
|
||||
upper, middle, lower = talib.BBANDS(
|
||||
prices_array,
|
||||
timeperiod=period,
|
||||
nbdevup=nbdevup,
|
||||
nbdevdn=nbdevdn,
|
||||
matype=MA_Type.SMA,
|
||||
)
|
||||
return upper, middle, lower
|
||||
|
||||
# ========== ATR ==========
|
||||
|
||||
@staticmethod
|
||||
def ATR(
|
||||
high: List[float],
|
||||
low: List[float],
|
||||
close: List[float],
|
||||
period: int = 14,
|
||||
) -> np.ndarray:
|
||||
"""
|
||||
真实波动幅度均值
|
||||
|
||||
Args:
|
||||
high: 最高价列表
|
||||
low: 最低价列表
|
||||
close: 收盘价列表
|
||||
period: 周期,默认14
|
||||
|
||||
Returns:
|
||||
ATR值数组
|
||||
"""
|
||||
Indicators._check_talib()
|
||||
high_array = Indicators._to_array(high)
|
||||
low_array = Indicators._to_array(low)
|
||||
close_array = Indicators._to_array(close)
|
||||
|
||||
return talib.ATR(high_array, low_array, close_array, timeperiod=period)
|
||||
|
||||
# ========== 成交量指标 ==========
|
||||
|
||||
@staticmethod
|
||||
def OBV(close: List[float], volume: List[float]) -> np.ndarray:
|
||||
"""
|
||||
能量潮
|
||||
|
||||
Args:
|
||||
close: 收盘价列表
|
||||
volume: 成交量列表
|
||||
|
||||
Returns:
|
||||
OBV值数组
|
||||
"""
|
||||
Indicators._check_talib()
|
||||
close_array = Indicators._to_array(close)
|
||||
volume_array = Indicators._to_array(volume)
|
||||
return talib.OBV(close_array, volume_array)
|
||||
|
||||
# ========== 形态识别 ==========
|
||||
|
||||
@staticmethod
|
||||
def CDL_PATTERN(
|
||||
open_prices: List[float],
|
||||
high: List[float],
|
||||
low: List[float],
|
||||
close: List[float],
|
||||
pattern: str = "DOJI",
|
||||
) -> Optional[np.ndarray]:
|
||||
"""
|
||||
K线形态识别
|
||||
|
||||
Args:
|
||||
open_prices: 开盘价列表
|
||||
high: 最高价列表
|
||||
low: 最低价列表
|
||||
close: 收盘价列表
|
||||
pattern: 形态名称,如 "DOJI"(十字星)、"HAMMER"(锤子线)等
|
||||
|
||||
Returns:
|
||||
形态信号数组(100=看涨,-100=看跌,0=无)
|
||||
"""
|
||||
Indicators._check_talib()
|
||||
open_array = Indicators._to_array(open_prices)
|
||||
high_array = Indicators._to_array(high)
|
||||
low_array = Indicators._to_array(low)
|
||||
close_array = Indicators._to_array(close)
|
||||
|
||||
pattern_func = f"CDL{pattern.upper()}"
|
||||
if hasattr(talib, pattern_func):
|
||||
return getattr(talib, pattern_func)(
|
||||
open_array, high_array, low_array, close_array
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
# 简化的纯Python实现(当TA-Lib不可用时)
|
||||
class SimpleIndicators:
|
||||
"""
|
||||
简化指标实现(无需TA-Lib)
|
||||
|
||||
仅提供基本指标,精度可能不如TA-Lib
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def SMA(prices: List[float], period: int) -> List[float]:
|
||||
"""简单移动平均"""
|
||||
result = []
|
||||
for i in range(len(prices)):
|
||||
if i < period - 1:
|
||||
result.append(np.nan)
|
||||
else:
|
||||
result.append(np.mean(prices[i - period + 1 : i + 1]))
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def EMA(prices: List[float], period: int) -> List[float]:
|
||||
"""指数移动平均"""
|
||||
result = []
|
||||
multiplier = 2 / (period + 1)
|
||||
|
||||
for i, price in enumerate(prices):
|
||||
if i == 0:
|
||||
result.append(price)
|
||||
else:
|
||||
ema = (price - result[-1]) * multiplier + result[-1]
|
||||
result.append(ema)
|
||||
return result
|
||||
@ -1,169 +0,0 @@
|
||||
"""
|
||||
策略注册中心
|
||||
|
||||
管理所有已注册的策略类
|
||||
"""
|
||||
|
||||
from typing import Optional, Type, List, Dict, Any
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from .base_strategy import BaseStrategy
|
||||
|
||||
logger = get_logger("core.strategy.registry")
|
||||
|
||||
|
||||
class StrategyRegistry:
|
||||
"""
|
||||
策略注册中心(单例)
|
||||
|
||||
用于注册和管理所有策略类
|
||||
"""
|
||||
|
||||
_instance: Optional["StrategyRegistry"] = None
|
||||
|
||||
def __new__(cls) -> "StrategyRegistry":
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
cls._instance._strategies = {}
|
||||
cls._instance._initialized = False
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
if self._initialized:
|
||||
return
|
||||
self._strategies: Dict[str, Type[BaseStrategy]] = {}
|
||||
self._initialized = True
|
||||
|
||||
def register(self, strategy_class: Type[BaseStrategy]) -> None:
|
||||
"""
|
||||
注册策略
|
||||
|
||||
Args:
|
||||
strategy_class: 策略类(必须继承BaseStrategy)
|
||||
|
||||
Raises:
|
||||
ValueError: 如果strategy_id未设置
|
||||
"""
|
||||
if not strategy_class.strategy_id:
|
||||
raise ValueError(f"策略类 {strategy_class.__name__} 未设置 strategy_id")
|
||||
|
||||
if not issubclass(strategy_class, BaseStrategy):
|
||||
raise ValueError(f"策略类 {strategy_class.__name__} 必须继承 BaseStrategy")
|
||||
|
||||
strategy_id = strategy_class.strategy_id
|
||||
|
||||
if strategy_id in self._strategies:
|
||||
logger.warning(f"策略 {strategy_id} 已存在,将被覆盖")
|
||||
|
||||
self._strategies[strategy_id] = strategy_class
|
||||
logger.info(f"注册策略: {strategy_id} - {strategy_class.strategy_name}")
|
||||
|
||||
def unregister(self, strategy_id: str) -> bool:
|
||||
"""
|
||||
注销策略
|
||||
|
||||
Args:
|
||||
strategy_id: 策略ID
|
||||
|
||||
Returns:
|
||||
是否成功注销
|
||||
"""
|
||||
if strategy_id in self._strategies:
|
||||
del self._strategies[strategy_id]
|
||||
logger.info(f"注销策略: {strategy_id}")
|
||||
return True
|
||||
return False
|
||||
|
||||
def get_strategy_class(self, strategy_id: str) -> Optional[Type[BaseStrategy]]:
|
||||
"""
|
||||
获取策略类
|
||||
|
||||
Args:
|
||||
strategy_id: 策略ID
|
||||
|
||||
Returns:
|
||||
策略类,不存在返回None
|
||||
"""
|
||||
return self._strategies.get(strategy_id)
|
||||
|
||||
def has_strategy(self, strategy_id: str) -> bool:
|
||||
"""
|
||||
检查策略是否存在
|
||||
|
||||
Args:
|
||||
strategy_id: 策略ID
|
||||
|
||||
Returns:
|
||||
是否存在
|
||||
"""
|
||||
return strategy_id in self._strategies
|
||||
|
||||
def list_strategies(self, category: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
列出所有策略
|
||||
|
||||
Args:
|
||||
category: 分类过滤(暂未实现)
|
||||
|
||||
Returns:
|
||||
策略信息列表
|
||||
"""
|
||||
strategies = []
|
||||
for strategy_id, strategy_class in self._strategies.items():
|
||||
strategies.append(
|
||||
{
|
||||
"id": strategy_class.strategy_id,
|
||||
"name": strategy_class.strategy_name,
|
||||
"description": strategy_class.description,
|
||||
"version": strategy_class.version,
|
||||
"author": strategy_class.author,
|
||||
}
|
||||
)
|
||||
return strategies
|
||||
|
||||
def get_strategy_info(self, strategy_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
获取策略详细信息
|
||||
|
||||
Args:
|
||||
strategy_id: 策略ID
|
||||
|
||||
Returns:
|
||||
策略信息字典
|
||||
"""
|
||||
strategy_class = self._strategies.get(strategy_id)
|
||||
if not strategy_class:
|
||||
return None
|
||||
|
||||
return {
|
||||
"id": strategy_class.strategy_id,
|
||||
"name": strategy_class.strategy_name,
|
||||
"description": strategy_class.description,
|
||||
"version": strategy_class.version,
|
||||
"author": strategy_class.author,
|
||||
"params_schema": strategy_class.params_schema,
|
||||
}
|
||||
|
||||
def get_params_schema(self, strategy_id: str) -> Optional[dict]:
|
||||
"""
|
||||
获取策略参数定义
|
||||
|
||||
Args:
|
||||
strategy_id: 策略ID
|
||||
|
||||
Returns:
|
||||
参数定义字典
|
||||
"""
|
||||
strategy_class = self._strategies.get(strategy_id)
|
||||
if not strategy_class:
|
||||
return None
|
||||
return strategy_class.params_schema
|
||||
|
||||
def clear(self):
|
||||
"""清空所有注册的策略"""
|
||||
self._strategies.clear()
|
||||
logger.info("已清空所有注册策略")
|
||||
|
||||
|
||||
# 全局单例
|
||||
strategy_registry = StrategyRegistry()
|
||||
@ -1,9 +0,0 @@
|
||||
"""
|
||||
内置策略
|
||||
|
||||
导出所有内置策略,方便注册
|
||||
"""
|
||||
|
||||
from .ma_cross import MACrossStrategy
|
||||
|
||||
__all__ = ["MACrossStrategy"]
|
||||
@ -1,143 +0,0 @@
|
||||
"""
|
||||
示例策略
|
||||
|
||||
演示如何使用统一策略框架编写策略
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from ..base_strategy import BaseStrategy, Signal
|
||||
from ..indicators import Indicators
|
||||
|
||||
logger = get_logger("strategies.ma_cross")
|
||||
|
||||
|
||||
class MACrossStrategy(BaseStrategy):
|
||||
"""
|
||||
双均线策略
|
||||
|
||||
策略逻辑:
|
||||
- 短期均线上穿长期均线时买入(金叉)
|
||||
- 短期均线下穿长期均线时卖出(死叉)
|
||||
"""
|
||||
|
||||
strategy_id = "ma_cross"
|
||||
strategy_name = "双均线策略"
|
||||
description = "基于双均线交叉的趋势跟踪策略"
|
||||
version = "2.0.0"
|
||||
author = "QTrade"
|
||||
|
||||
# 参数定义
|
||||
params_schema = {
|
||||
"short_period": {
|
||||
"type": "int",
|
||||
"default": 5,
|
||||
"min": 2,
|
||||
"max": 50,
|
||||
"description": "短期均线周期",
|
||||
},
|
||||
"long_period": {
|
||||
"type": "int",
|
||||
"default": 10,
|
||||
"min": 5,
|
||||
"max": 200,
|
||||
"description": "长期均线周期",
|
||||
},
|
||||
"period": {
|
||||
"type": "str",
|
||||
"default": "1d",
|
||||
"options": ["tick", "1m", "5m", "15m", "30m", "1h", "1d"],
|
||||
"description": "使用的K线级别",
|
||||
},
|
||||
}
|
||||
|
||||
def init(self):
|
||||
"""初始化策略"""
|
||||
# 获取参数
|
||||
self.short_period = self.get_param("short_period", 5)
|
||||
self.long_period = self.get_param("long_period", 10)
|
||||
self.use_period = self.get_param("period", "1d")
|
||||
|
||||
# 初始化数据存储
|
||||
self.close_prices = []
|
||||
self.ma_short = []
|
||||
self.ma_long = []
|
||||
|
||||
logger.info(
|
||||
f"MA策略初始化: {self.symbol}, "
|
||||
f"短期={self.short_period}, 长期={self.long_period}, "
|
||||
f"级别={self.use_period}"
|
||||
)
|
||||
|
||||
def handle_kline(self, kline: dict) -> Optional[Signal]:
|
||||
"""处理K线"""
|
||||
# 只处理指定级别的K线
|
||||
if kline["period"] != self.use_period:
|
||||
return None
|
||||
|
||||
# 收集收盘价
|
||||
self.close_prices.append(kline["close"])
|
||||
|
||||
# 数据不够,等待
|
||||
if len(self.close_prices) < self.long_period:
|
||||
return None
|
||||
|
||||
# 计算均线
|
||||
try:
|
||||
ma_short = Indicators.SMA(self.close_prices, self.short_period)
|
||||
ma_long = Indicators.SMA(self.close_prices, self.long_period)
|
||||
|
||||
self.ma_short = ma_short.tolist()
|
||||
self.ma_long = ma_long.tolist()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"计算均线失败: {e}")
|
||||
return None
|
||||
|
||||
# 需要至少2个点才能判断交叉
|
||||
if len(self.ma_short) < 2 or len(self.ma_long) < 2:
|
||||
return None
|
||||
|
||||
# 判断交叉
|
||||
prev_short = self.ma_short[-2]
|
||||
prev_long = self.ma_long[-2]
|
||||
curr_short = self.ma_short[-1]
|
||||
curr_long = self.ma_long[-1]
|
||||
|
||||
# 金叉:买入信号
|
||||
if prev_short <= prev_long and curr_short > curr_long:
|
||||
if self.position == 0: # 没有持仓才买
|
||||
return Signal(
|
||||
action="buy",
|
||||
price=kline["close"],
|
||||
quantity=100,
|
||||
reason=f"金叉: MA{self.short_period}上穿MA{self.long_period}",
|
||||
)
|
||||
|
||||
# 死叉:卖出信号
|
||||
elif prev_short >= prev_long and curr_short < curr_long:
|
||||
if self.position > 0: # 有持仓才卖
|
||||
return Signal(
|
||||
action="sell",
|
||||
price=kline["close"],
|
||||
quantity=self.position, # 全部卖出
|
||||
reason=f"死叉: MA{self.short_period}下穿MA{self.long_period}",
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
def get_state(self) -> dict:
|
||||
"""获取策略状态"""
|
||||
return {
|
||||
"close_prices": self.close_prices[-200:], # 只保存最近200个
|
||||
"ma_short": self.ma_short[-200:],
|
||||
"ma_long": self.ma_long[-200:],
|
||||
}
|
||||
|
||||
def set_state(self, state: dict):
|
||||
"""恢复策略状态"""
|
||||
self.close_prices = state.get("close_prices", [])
|
||||
self.ma_short = state.get("ma_short", [])
|
||||
self.ma_long = state.get("ma_long", [])
|
||||
logger.info(f"恢复状态: {len(self.close_prices)}个数据点")
|
||||
@ -1,13 +0,0 @@
|
||||
"""
|
||||
QTrade Core Service 核心业务服务
|
||||
|
||||
提供:
|
||||
- 股票-策略配对管理
|
||||
- 订单管理
|
||||
- 持仓管理
|
||||
- 资金管理
|
||||
"""
|
||||
|
||||
from .app import app
|
||||
|
||||
__all__ = ["app"]
|
||||
@ -1,73 +0,0 @@
|
||||
"""
|
||||
Core Service FastAPI 应用
|
||||
|
||||
核心业务服务,提供:
|
||||
- 股票-策略配对 CRUD
|
||||
- 订单创建、撤销、查询
|
||||
- 持仓管理
|
||||
- 资金管理
|
||||
"""
|
||||
|
||||
from fastapi import FastAPI
|
||||
|
||||
from src.core.base_app import BaseApp
|
||||
from src.core.config import get_settings
|
||||
|
||||
# 加载服务配置
|
||||
settings = get_settings("core_service")
|
||||
|
||||
|
||||
class CoreServiceApp(BaseApp):
|
||||
"""核心业务服务应用"""
|
||||
|
||||
name = "core_service"
|
||||
title = "QTrade Core Service"
|
||||
description = "量化交易系统核心业务服务"
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._order_service = None
|
||||
|
||||
async def on_startup(self):
|
||||
"""启动核心服务"""
|
||||
from .services.order_service import order_service
|
||||
|
||||
self._order_service = order_service
|
||||
|
||||
# 启动订单服务(监听交易回报)
|
||||
try:
|
||||
await order_service.start()
|
||||
self.logger.info("订单服务已启动")
|
||||
except Exception as e:
|
||||
self.logger.warning(f"订单服务启动失败: {e}")
|
||||
|
||||
async def on_shutdown(self):
|
||||
"""关闭核心服务"""
|
||||
if self._order_service:
|
||||
await self._order_service.stop()
|
||||
|
||||
def setup_routes(self, app: FastAPI):
|
||||
"""注册路由"""
|
||||
from .routes import pairing, order, position, balance
|
||||
|
||||
app.include_router(pairing.router, prefix="/pairing", tags=["配对管理"])
|
||||
app.include_router(order.router, prefix="/order", tags=["订单管理"])
|
||||
app.include_router(position.router, prefix="/position", tags=["持仓管理"])
|
||||
app.include_router(balance.router, prefix="/balance", tags=["资金管理"])
|
||||
|
||||
|
||||
# 创建应用实例
|
||||
_app_instance = CoreServiceApp()
|
||||
app = _app_instance.app
|
||||
|
||||
|
||||
def run():
|
||||
"""运行服务"""
|
||||
_app_instance.run(
|
||||
host=settings.services.core_service.host,
|
||||
port=settings.services.core_service.port,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
@ -1,7 +0,0 @@
|
||||
"""
|
||||
Core Service 路由模块
|
||||
"""
|
||||
|
||||
from . import pairing, order, position, balance
|
||||
|
||||
__all__ = ["pairing", "order", "position", "balance"]
|
||||
@ -1,120 +0,0 @@
|
||||
"""
|
||||
资金管理路由
|
||||
|
||||
资金查询与管理
|
||||
"""
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, Query, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from ..services.balance_service import balance_service
|
||||
|
||||
logger = get_logger("core_service.balance")
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class BalanceAdjust(BaseModel):
|
||||
"""资金调整请求"""
|
||||
|
||||
amount: float
|
||||
reason: str
|
||||
|
||||
|
||||
@router.get("/{pairing_id}")
|
||||
async def get_balance(pairing_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
查询配对资金
|
||||
|
||||
Args:
|
||||
pairing_id: 配对ID
|
||||
"""
|
||||
try:
|
||||
result = await balance_service.get_balance(pairing_id)
|
||||
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail=f"配对不存在: {pairing_id}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"查询资金失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_balances(
|
||||
strategy_id: Optional[str] = Query(default=None, description="策略ID"),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
查询资金列表
|
||||
"""
|
||||
try:
|
||||
result = await balance_service.list_balances(strategy_id=strategy_id)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"查询资金列表失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/summary/all")
|
||||
async def get_balance_summary() -> dict[str, Any]:
|
||||
"""
|
||||
获取资金汇总
|
||||
"""
|
||||
try:
|
||||
result = await balance_service.get_summary()
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"获取资金汇总失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/{pairing_id}/adjust")
|
||||
async def adjust_balance(pairing_id: str, adjust: BalanceAdjust) -> dict[str, Any]:
|
||||
"""
|
||||
调整资金(增加或减少初始资金)
|
||||
|
||||
Args:
|
||||
pairing_id: 配对ID
|
||||
adjust: 调整请求
|
||||
"""
|
||||
try:
|
||||
result = await balance_service.adjust_balance(
|
||||
pairing_id=pairing_id,
|
||||
amount=adjust.amount,
|
||||
reason=adjust.reason,
|
||||
)
|
||||
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail=f"配对不存在: {pairing_id}")
|
||||
|
||||
logger.info(f"调整资金: {pairing_id}, {adjust.amount}, {adjust.reason}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"调整资金失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
@ -1,156 +0,0 @@
|
||||
"""
|
||||
订单管理路由
|
||||
|
||||
订单的创建、撤销、查询
|
||||
"""
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, Query, HTTPException
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.models import OrderStatus
|
||||
from src.core.schemas.order import OrderCreate
|
||||
from ..services.order_service import order_service
|
||||
|
||||
logger = get_logger("core_service.order")
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_order(order: OrderCreate) -> dict[str, Any]:
|
||||
"""
|
||||
创建订单
|
||||
|
||||
Args:
|
||||
order: 订单创建请求
|
||||
|
||||
Returns:
|
||||
创建的订单信息
|
||||
"""
|
||||
try:
|
||||
result = await order_service.create_order(order)
|
||||
|
||||
logger.info(
|
||||
f"创建订单: {result['order_id']}, "
|
||||
f"{order.symbol} {order.side} {order.quantity}@{order.price}"
|
||||
)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"创建订单失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/{order_id}")
|
||||
async def cancel_order(
|
||||
order_id: str,
|
||||
reason: Optional[str] = Query(default=None, description="撤销原因"),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
撤销订单
|
||||
|
||||
Args:
|
||||
order_id: 订单ID
|
||||
reason: 撤销原因
|
||||
"""
|
||||
try:
|
||||
result = await order_service.cancel_order(order_id, reason)
|
||||
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail=f"订单不存在: {order_id}")
|
||||
|
||||
logger.info(f"撤销订单: {order_id}, 原因: {reason}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"撤销订单失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/{order_id}")
|
||||
async def get_order(order_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
查询订单详情
|
||||
|
||||
Args:
|
||||
order_id: 订单ID
|
||||
"""
|
||||
try:
|
||||
result = await order_service.get_order(order_id)
|
||||
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail=f"订单不存在: {order_id}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"查询订单失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_orders(
|
||||
pairing_id: Optional[str] = Query(default=None, description="配对ID"),
|
||||
symbol: Optional[str] = Query(default=None, description="股票代码"),
|
||||
status: Optional[OrderStatus] = Query(default=None, description="订单状态"),
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=100),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
查询订单列表
|
||||
"""
|
||||
try:
|
||||
result = await order_service.list_orders(
|
||||
pairing_id=pairing_id,
|
||||
symbol=symbol,
|
||||
status=status,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"查询订单列表失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/today/summary")
|
||||
async def get_today_summary(
|
||||
pairing_id: Optional[str] = Query(default=None, description="配对ID"),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
获取今日订单汇总
|
||||
"""
|
||||
try:
|
||||
result = await order_service.get_today_summary(pairing_id)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"获取今日汇总失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
@ -1,175 +0,0 @@
|
||||
"""
|
||||
配对管理路由
|
||||
|
||||
股票-策略配对的 CRUD 操作
|
||||
"""
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, Query, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.models import PairingStatus
|
||||
from src.core.schemas.pairing import PairingCreate
|
||||
from ..services.pairing_service import pairing_service
|
||||
|
||||
logger = get_logger("core_service.pairing")
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class PairingResponse(BaseModel):
|
||||
"""配对响应"""
|
||||
|
||||
id: str
|
||||
symbol: str
|
||||
strategy_id: str
|
||||
status: str
|
||||
initial_capital: float
|
||||
created_at: Optional[str] = None
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_pairing(pairing: PairingCreate) -> dict[str, Any]:
|
||||
"""
|
||||
创建股票-策略配对
|
||||
|
||||
Args:
|
||||
pairing: 配对创建请求
|
||||
|
||||
Returns:
|
||||
创建的配对信息
|
||||
"""
|
||||
try:
|
||||
result = await pairing_service.create(pairing)
|
||||
|
||||
logger.info(
|
||||
f"创建配对成功: {result['id']}, {pairing.symbol} - {pairing.strategy_id}"
|
||||
)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"创建配对失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/{pairing_id}")
|
||||
async def get_pairing(pairing_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
查询配对详情
|
||||
|
||||
Args:
|
||||
pairing_id: 配对ID
|
||||
"""
|
||||
try:
|
||||
result = await pairing_service.get(pairing_id)
|
||||
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail=f"配对不存在: {pairing_id}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"查询配对失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_pairings(
|
||||
symbol: Optional[str] = Query(default=None, description="股票代码"),
|
||||
strategy_id: Optional[str] = Query(default=None, description="策略ID"),
|
||||
status: Optional[PairingStatus] = Query(default=None, description="配对状态"),
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=100),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
查询配对列表
|
||||
"""
|
||||
try:
|
||||
result = await pairing_service.get_list(
|
||||
symbol=symbol,
|
||||
strategy_id=strategy_id,
|
||||
status=status,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"查询配对列表失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.put("/{pairing_id}/status")
|
||||
async def update_pairing_status(
|
||||
pairing_id: str,
|
||||
status: PairingStatus,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
更新配对状态(启动/暂停/停止)
|
||||
|
||||
Args:
|
||||
pairing_id: 配对ID
|
||||
status: 新状态
|
||||
"""
|
||||
try:
|
||||
result = await pairing_service.update_status(pairing_id, status)
|
||||
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail=f"配对不存在: {pairing_id}")
|
||||
|
||||
logger.info(f"更新配对状态: {pairing_id} -> {status}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"更新配对状态失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/{pairing_id}")
|
||||
async def delete_pairing(pairing_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
删除配对
|
||||
|
||||
Args:
|
||||
pairing_id: 配对ID
|
||||
"""
|
||||
try:
|
||||
success = await pairing_service.delete(pairing_id)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail=f"配对不存在: {pairing_id}")
|
||||
|
||||
logger.info(f"删除配对: {pairing_id}")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {"pairing_id": pairing_id},
|
||||
}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"删除配对失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
@ -1,119 +0,0 @@
|
||||
"""
|
||||
持仓管理路由
|
||||
|
||||
持仓查询与管理
|
||||
"""
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
from fastapi import APIRouter, Query, HTTPException
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from ..services.position_service import position_service
|
||||
|
||||
logger = get_logger("core_service.position")
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/{pairing_id}")
|
||||
async def get_position(pairing_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
查询配对持仓
|
||||
|
||||
Args:
|
||||
pairing_id: 配对ID
|
||||
"""
|
||||
try:
|
||||
result = await position_service.get_position(pairing_id)
|
||||
|
||||
if not result:
|
||||
# 返回空持仓
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"pairing_id": pairing_id,
|
||||
"symbol": None,
|
||||
"quantity": 0,
|
||||
"available": 0,
|
||||
"frozen": 0,
|
||||
"cost_price": 0,
|
||||
"market_value": 0,
|
||||
"pnl": 0,
|
||||
"pnl_ratio": 0,
|
||||
},
|
||||
}
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"查询持仓失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_positions(
|
||||
strategy_id: Optional[str] = Query(default=None, description="策略ID"),
|
||||
symbol: Optional[str] = Query(default=None, description="股票代码"),
|
||||
has_position: Optional[bool] = Query(default=None, description="是否有持仓"),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
查询持仓列表
|
||||
"""
|
||||
try:
|
||||
result = await position_service.list_positions(
|
||||
strategy_id=strategy_id,
|
||||
symbol=symbol,
|
||||
has_position=has_position,
|
||||
)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"查询持仓列表失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/summary/all")
|
||||
async def get_position_summary() -> dict[str, Any]:
|
||||
"""
|
||||
获取持仓汇总
|
||||
"""
|
||||
try:
|
||||
result = await position_service.get_summary()
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"获取持仓汇总失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/{pairing_id}/sync")
|
||||
async def sync_position(pairing_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
同步持仓(从 QMT 同步)
|
||||
|
||||
Args:
|
||||
pairing_id: 配对ID
|
||||
"""
|
||||
try:
|
||||
result = await position_service.sync_position(pairing_id)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"同步持仓失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
@ -1,15 +0,0 @@
|
||||
"""
|
||||
Core Service 业务服务层
|
||||
"""
|
||||
|
||||
from .order_service import order_service
|
||||
from .position_service import position_service
|
||||
from .balance_service import balance_service
|
||||
from .pairing_service import pairing_service
|
||||
|
||||
__all__ = [
|
||||
"order_service",
|
||||
"position_service",
|
||||
"balance_service",
|
||||
"pairing_service",
|
||||
]
|
||||
@ -1,233 +0,0 @@
|
||||
"""
|
||||
资金管理服务
|
||||
|
||||
处理资金查询与调整
|
||||
"""
|
||||
|
||||
from typing import Any, Optional
|
||||
from datetime import datetime as dt
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import select, func
|
||||
|
||||
from src.core.database import db
|
||||
from src.core.logger import get_logger
|
||||
from src.core.models import Pairing, Position, BalanceLog, BalanceLogType
|
||||
|
||||
logger = get_logger("core_service.balance_service")
|
||||
|
||||
|
||||
class BalanceService:
|
||||
"""资金管理服务"""
|
||||
|
||||
async def get_balance(self, pairing_id: str) -> Optional[dict[str, Any]]:
|
||||
"""
|
||||
获取配对资金
|
||||
|
||||
Args:
|
||||
pairing_id: 配对ID
|
||||
|
||||
Returns:
|
||||
资金信息
|
||||
"""
|
||||
async with db.session() as session:
|
||||
stmt = select(Pairing).where(Pairing.id == pairing_id)
|
||||
result = await session.execute(stmt)
|
||||
pairing = result.scalar_one_or_none()
|
||||
|
||||
if not pairing:
|
||||
return None
|
||||
|
||||
initial_capital = (
|
||||
float(pairing.initial_capital) if pairing.initial_capital else 0
|
||||
)
|
||||
available_capital = (
|
||||
float(pairing.available_capital) if pairing.available_capital else 0
|
||||
)
|
||||
|
||||
# 计算持仓市值
|
||||
position_stmt = select(
|
||||
func.sum(Position.quantity * Position.avg_cost)
|
||||
).where(
|
||||
Position.pairing_id == pairing_id,
|
||||
Position.quantity > 0,
|
||||
)
|
||||
position_result = await session.execute(position_stmt)
|
||||
position_value = float(position_result.scalar() or 0)
|
||||
|
||||
# 总资产 = 可用资金 + 持仓市值
|
||||
total_assets = available_capital + position_value
|
||||
|
||||
# 盈亏 = 总资产 - 初始资金
|
||||
pnl = total_assets - initial_capital
|
||||
pnl_ratio = pnl / initial_capital if initial_capital > 0 else 0
|
||||
|
||||
return {
|
||||
"pairing_id": pairing.id,
|
||||
"symbol": pairing.symbol,
|
||||
"strategy_id": pairing.strategy_id,
|
||||
"initial_capital": initial_capital,
|
||||
"available_capital": available_capital,
|
||||
"position_value": position_value,
|
||||
"total_assets": total_assets,
|
||||
"pnl": pnl,
|
||||
"pnl_ratio": pnl_ratio,
|
||||
"status": pairing.status.value if pairing.status else None,
|
||||
"created_at": pairing.created_at.isoformat()
|
||||
if pairing.created_at
|
||||
else None,
|
||||
"updated_at": pairing.updated_at.isoformat()
|
||||
if pairing.updated_at
|
||||
else None,
|
||||
}
|
||||
|
||||
async def list_balances(
|
||||
self,
|
||||
strategy_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""查询资金列表"""
|
||||
async with db.session() as session:
|
||||
stmt = select(Pairing)
|
||||
if strategy_id:
|
||||
stmt = stmt.where(Pairing.strategy_id == strategy_id)
|
||||
stmt = stmt.order_by(Pairing.created_at.desc())
|
||||
|
||||
result = await session.execute(stmt)
|
||||
pairings = result.scalars().all()
|
||||
|
||||
items = []
|
||||
for pairing in pairings:
|
||||
initial_capital = (
|
||||
float(pairing.initial_capital) if pairing.initial_capital else 0
|
||||
)
|
||||
available_capital = (
|
||||
float(pairing.available_capital) if pairing.available_capital else 0
|
||||
)
|
||||
|
||||
# 计算持仓市值
|
||||
position_stmt = select(
|
||||
func.sum(Position.quantity * Position.avg_cost)
|
||||
).where(
|
||||
Position.pairing_id == pairing.id,
|
||||
Position.quantity > 0,
|
||||
)
|
||||
position_result = await session.execute(position_stmt)
|
||||
position_value = float(position_result.scalar() or 0)
|
||||
|
||||
total_assets = available_capital + position_value
|
||||
pnl = total_assets - initial_capital
|
||||
|
||||
items.append(
|
||||
{
|
||||
"pairing_id": pairing.id,
|
||||
"symbol": pairing.symbol,
|
||||
"strategy_id": pairing.strategy_id,
|
||||
"initial_capital": initial_capital,
|
||||
"available_capital": available_capital,
|
||||
"position_value": position_value,
|
||||
"total_assets": total_assets,
|
||||
"pnl": pnl,
|
||||
"status": pairing.status.value if pairing.status else None,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"items": items,
|
||||
"total": len(items),
|
||||
}
|
||||
|
||||
async def get_summary(self) -> dict[str, Any]:
|
||||
"""获取资金汇总"""
|
||||
async with db.session() as session:
|
||||
# 汇总所有配对资金
|
||||
stmt = select(
|
||||
func.count(Pairing.id).label("pairing_count"),
|
||||
func.sum(Pairing.initial_capital).label("total_initial"),
|
||||
func.sum(Pairing.available_capital).label("total_available"),
|
||||
)
|
||||
result = await session.execute(stmt)
|
||||
row = result.one()
|
||||
|
||||
total_initial = float(row.total_initial) if row.total_initial else 0
|
||||
total_available = float(row.total_available) if row.total_available else 0
|
||||
|
||||
# 计算所有持仓市值
|
||||
position_stmt = select(
|
||||
func.sum(Position.quantity * Position.avg_cost)
|
||||
).where(Position.quantity > 0)
|
||||
position_result = await session.execute(position_stmt)
|
||||
total_position_value = float(position_result.scalar() or 0)
|
||||
|
||||
total_assets = total_available + total_position_value
|
||||
total_pnl = total_assets - total_initial
|
||||
total_pnl_ratio = total_pnl / total_initial if total_initial > 0 else 0
|
||||
|
||||
return {
|
||||
"pairing_count": row.pairing_count or 0,
|
||||
"total_initial_capital": total_initial,
|
||||
"total_available_capital": total_available,
|
||||
"total_position_value": total_position_value,
|
||||
"total_assets": total_assets,
|
||||
"total_pnl": total_pnl,
|
||||
"total_pnl_ratio": total_pnl_ratio,
|
||||
}
|
||||
|
||||
async def adjust_balance(
|
||||
self,
|
||||
pairing_id: str,
|
||||
amount: float,
|
||||
reason: str,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
"""
|
||||
调整资金
|
||||
|
||||
Args:
|
||||
pairing_id: 配对ID
|
||||
amount: 调整金额(正数增加,负数减少)
|
||||
reason: 调整原因
|
||||
|
||||
Returns:
|
||||
调整后的资金信息
|
||||
"""
|
||||
now = dt.now()
|
||||
amount_decimal = Decimal(str(amount))
|
||||
|
||||
async with db.session() as session:
|
||||
# 检查配对是否存在
|
||||
stmt = select(Pairing).where(Pairing.id == pairing_id)
|
||||
result = await session.execute(stmt)
|
||||
pairing = result.scalar_one_or_none()
|
||||
|
||||
if not pairing:
|
||||
return None
|
||||
|
||||
new_initial = (pairing.initial_capital or Decimal(0)) + amount_decimal
|
||||
new_available = (pairing.available_capital or Decimal(0)) + amount_decimal
|
||||
|
||||
if new_initial < 0 or new_available < 0:
|
||||
raise ValueError("资金不足,无法调整")
|
||||
|
||||
# 更新资金
|
||||
pairing.initial_capital = new_initial
|
||||
pairing.available_capital = new_available
|
||||
pairing.updated_at = now
|
||||
|
||||
# 记录调整日志
|
||||
log = BalanceLog(
|
||||
pairing_id=pairing_id,
|
||||
log_type=BalanceLogType.ADJUST,
|
||||
amount=amount_decimal,
|
||||
balance_after=new_available,
|
||||
description=reason,
|
||||
created_at=now,
|
||||
)
|
||||
session.add(log)
|
||||
await session.commit()
|
||||
|
||||
logger.info(f"资金调整: {pairing_id}, {amount}, {reason}")
|
||||
|
||||
return await self.get_balance(pairing_id)
|
||||
|
||||
|
||||
# 单例
|
||||
balance_service = BalanceService()
|
||||
@ -1,406 +0,0 @@
|
||||
"""
|
||||
订单管理服务
|
||||
|
||||
处理订单的创建、撤销和查询
|
||||
监听成交回报更新持仓
|
||||
"""
|
||||
|
||||
import uuid
|
||||
import asyncio
|
||||
from typing import Any, Optional
|
||||
from datetime import datetime as dt, date
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import select, func, update, case, and_
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.core.database import db
|
||||
from src.core.redis_client import redis_client
|
||||
from src.core.logger import get_logger
|
||||
from src.core.models import Order, OrderStatus, TradeSide, OrderType, Pairing, Position
|
||||
from src.core.schemas.order import OrderCreate
|
||||
|
||||
logger = get_logger("core_service.order_service")
|
||||
|
||||
|
||||
class OrderService:
|
||||
"""订单管理服务"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.redis_key_prefix = "order:"
|
||||
self._running = False
|
||||
self._trade_listener_task: Optional[asyncio.Task[None]] = None
|
||||
|
||||
async def start(self) -> None:
|
||||
"""启动服务"""
|
||||
self._running = True
|
||||
# 启动成交回报监听
|
||||
self._trade_listener_task = asyncio.create_task(self._listen_trade_reports())
|
||||
logger.info("订单服务已启动")
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""停止服务"""
|
||||
self._running = False
|
||||
if self._trade_listener_task:
|
||||
self._trade_listener_task.cancel()
|
||||
try:
|
||||
await self._trade_listener_task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
logger.info("订单服务已停止")
|
||||
|
||||
async def create_order(self, order: OrderCreate) -> dict[str, Any]:
|
||||
"""
|
||||
创建订单
|
||||
|
||||
Args:
|
||||
order: 订单创建请求
|
||||
|
||||
Returns:
|
||||
创建的订单信息
|
||||
"""
|
||||
order_id = str(uuid.uuid4())[:12]
|
||||
now = dt.now()
|
||||
|
||||
async with db.session() as session:
|
||||
# 检查配对是否存在且运行中
|
||||
stmt = select(Pairing).where(Pairing.id == order.pairing_id)
|
||||
result = await session.execute(stmt)
|
||||
pairing = result.scalar_one_or_none()
|
||||
|
||||
if not pairing:
|
||||
raise ValueError(f"配对不存在: {order.pairing_id}")
|
||||
|
||||
from src.core.models import PairingStatus
|
||||
|
||||
if pairing.status != PairingStatus.ACTIVE:
|
||||
raise ValueError(f"配对未运行: {order.pairing_id}")
|
||||
|
||||
# 买入时检查资金
|
||||
if order.side == TradeSide.BUY:
|
||||
required = Decimal(str(order.price)) * order.quantity
|
||||
if (pairing.available_capital or Decimal(0)) < required:
|
||||
raise ValueError(
|
||||
f"资金不足: 需要 {required}, 可用 {pairing.available_capital}"
|
||||
)
|
||||
|
||||
# 创建订单对象
|
||||
new_order = Order(
|
||||
id=order_id,
|
||||
pairing_id=order.pairing_id,
|
||||
symbol=order.symbol,
|
||||
side=order.side,
|
||||
order_type=order.order_type,
|
||||
price=Decimal(str(order.price)),
|
||||
quantity=order.quantity,
|
||||
filled_quantity=0,
|
||||
status=OrderStatus.PENDING,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
session.add(new_order)
|
||||
await session.commit()
|
||||
await session.refresh(new_order)
|
||||
|
||||
order_data = new_order.to_dict()
|
||||
|
||||
# 发布订单创建事件(QMT 适配器监听)
|
||||
import json
|
||||
from src.core.config import settings
|
||||
|
||||
await redis_client.publish(
|
||||
settings.channels.order_update, json.dumps(order_data)
|
||||
)
|
||||
|
||||
return order_data
|
||||
|
||||
async def cancel_order(
|
||||
self,
|
||||
order_id: str,
|
||||
reason: Optional[str] = None,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
"""撤销订单"""
|
||||
now = dt.now()
|
||||
|
||||
async with db.session() as session:
|
||||
# 检查订单状态
|
||||
stmt = select(Order).where(Order.id == order_id)
|
||||
result = await session.execute(stmt)
|
||||
order = result.scalar_one_or_none()
|
||||
|
||||
if not order:
|
||||
return None
|
||||
|
||||
if order.status not in [OrderStatus.PENDING, OrderStatus.PARTIAL]:
|
||||
raise ValueError(f"订单状态不允许撤销: {order.status.value}")
|
||||
|
||||
# 更新状态
|
||||
order.status = OrderStatus.CANCELLED
|
||||
order.cancel_reason = reason
|
||||
order.updated_at = now
|
||||
await session.commit()
|
||||
|
||||
# 发布撤单事件
|
||||
from src.core.config import settings
|
||||
|
||||
await redis_client.publish(settings.channels.order_update, order_id)
|
||||
|
||||
return await self.get_order(order_id)
|
||||
|
||||
async def get_order(self, order_id: str) -> Optional[dict[str, Any]]:
|
||||
"""获取订单详情"""
|
||||
async with db.session() as session:
|
||||
stmt = select(Order).where(Order.id == order_id)
|
||||
result = await session.execute(stmt)
|
||||
order = result.scalar_one_or_none()
|
||||
|
||||
if not order:
|
||||
return None
|
||||
|
||||
return order.to_dict()
|
||||
|
||||
async def list_orders(
|
||||
self,
|
||||
pairing_id: Optional[str] = None,
|
||||
symbol: Optional[str] = None,
|
||||
status: Optional[OrderStatus] = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
"""查询订单列表"""
|
||||
async with db.session() as session:
|
||||
# 构建查询
|
||||
stmt = select(Order)
|
||||
count_stmt = select(func.count(Order.id))
|
||||
|
||||
if pairing_id:
|
||||
stmt = stmt.where(Order.pairing_id == pairing_id)
|
||||
count_stmt = count_stmt.where(Order.pairing_id == pairing_id)
|
||||
if symbol:
|
||||
stmt = stmt.where(Order.symbol == symbol)
|
||||
count_stmt = count_stmt.where(Order.symbol == symbol)
|
||||
if status:
|
||||
stmt = stmt.where(Order.status == status)
|
||||
count_stmt = count_stmt.where(Order.status == status)
|
||||
|
||||
# 查询总数
|
||||
total_result = await session.execute(count_stmt)
|
||||
total = total_result.scalar() or 0
|
||||
|
||||
# 分页查询
|
||||
offset = (page - 1) * page_size
|
||||
stmt = (
|
||||
stmt.order_by(Order.created_at.desc()).offset(offset).limit(page_size)
|
||||
)
|
||||
result = await session.execute(stmt)
|
||||
orders = result.scalars().all()
|
||||
|
||||
return {
|
||||
"items": [o.to_dict() for o in orders],
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
}
|
||||
|
||||
async def get_today_summary(
|
||||
self,
|
||||
pairing_id: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""获取今日订单汇总"""
|
||||
today = date.today()
|
||||
|
||||
conditions = ["DATE(created_at) = :today"]
|
||||
params: dict[str, Any] = {"today": today}
|
||||
|
||||
if pairing_id:
|
||||
conditions.append("pairing_id = :pairing_id")
|
||||
params["pairing_id"] = pairing_id
|
||||
|
||||
where_clause = " AND ".join(conditions)
|
||||
|
||||
async with db.session() as session:
|
||||
result = await session.execute(
|
||||
text(f"""
|
||||
SELECT
|
||||
COUNT(*) as total,
|
||||
SUM(CASE WHEN status = 'filled' THEN 1 ELSE 0 END) as filled,
|
||||
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled,
|
||||
SUM(CASE WHEN status IN ('pending', 'partial') THEN 1 ELSE 0 END) as pending,
|
||||
SUM(CASE WHEN side = 'buy' AND status = 'filled' THEN filled_quantity * filled_price ELSE 0 END) as buy_amount,
|
||||
SUM(CASE WHEN side = 'sell' AND status = 'filled' THEN filled_quantity * filled_price ELSE 0 END) as sell_amount
|
||||
FROM orders
|
||||
WHERE {where_clause}
|
||||
"""),
|
||||
params,
|
||||
)
|
||||
row = result.fetchone()
|
||||
|
||||
return {
|
||||
"date": today.isoformat(),
|
||||
"total_orders": row[0] if row else 0,
|
||||
"filled_orders": row[1] if row else 0,
|
||||
"cancelled_orders": row[2] if row else 0,
|
||||
"pending_orders": row[3] if row else 0,
|
||||
"buy_amount": float(row[4]) if row and row[4] else 0,
|
||||
"sell_amount": float(row[5]) if row and row[5] else 0,
|
||||
}
|
||||
|
||||
async def _listen_trade_reports(self) -> None:
|
||||
"""监听成交回报"""
|
||||
import json
|
||||
|
||||
logger.info("开始监听成交回报")
|
||||
|
||||
try:
|
||||
async with redis_client.subscribe("trade:report") as pubsub:
|
||||
async for message in pubsub.listen():
|
||||
if not self._running:
|
||||
break
|
||||
|
||||
if message["type"] != "message":
|
||||
continue
|
||||
|
||||
try:
|
||||
trade = json.loads(message["data"])
|
||||
await self._handle_trade_report(trade)
|
||||
except Exception as e:
|
||||
logger.error(f"处理成交回报失败: {e}")
|
||||
except asyncio.CancelledError:
|
||||
logger.info("成交回报监听已取消")
|
||||
except Exception as e:
|
||||
logger.error(f"成交回报监听异常: {e}")
|
||||
|
||||
async def _handle_trade_report(self, trade: dict[str, Any]) -> None:
|
||||
"""
|
||||
处理成交回报
|
||||
|
||||
更新订单状态和持仓
|
||||
"""
|
||||
order_id = trade.get("order_id")
|
||||
filled_qty = trade.get("filled_quantity", 0)
|
||||
filled_price = trade.get("filled_price", 0)
|
||||
|
||||
if not order_id:
|
||||
return
|
||||
|
||||
now = dt.now()
|
||||
|
||||
async with db.session() as session:
|
||||
# 获取订单信息
|
||||
stmt = select(Order).where(Order.id == order_id)
|
||||
result = await session.execute(stmt)
|
||||
order = result.scalar_one_or_none()
|
||||
|
||||
if not order:
|
||||
logger.warning(f"订单不存在: {order_id}")
|
||||
return
|
||||
|
||||
# 更新已成交数量
|
||||
new_filled = (order.filled_quantity or 0) + filled_qty
|
||||
new_status = (
|
||||
OrderStatus.FILLED
|
||||
if new_filled >= order.quantity
|
||||
else OrderStatus.PARTIAL
|
||||
)
|
||||
|
||||
order.filled_quantity = new_filled
|
||||
order.filled_price = Decimal(str(filled_price))
|
||||
order.status = new_status
|
||||
order.updated_at = now
|
||||
|
||||
# 更新持仓
|
||||
await self._update_position(
|
||||
session=session,
|
||||
pairing_id=order.pairing_id,
|
||||
symbol=order.symbol,
|
||||
side=order.side.value
|
||||
if isinstance(order.side, TradeSide)
|
||||
else order.side,
|
||||
quantity=filled_qty,
|
||||
price=filled_price,
|
||||
)
|
||||
|
||||
await session.commit()
|
||||
|
||||
logger.info(f"成交回报处理完成: {order_id}, 成交 {filled_qty}@{filled_price}")
|
||||
|
||||
async def _update_position(
|
||||
self,
|
||||
session: Any,
|
||||
pairing_id: str,
|
||||
symbol: str,
|
||||
side: str,
|
||||
quantity: int,
|
||||
price: float,
|
||||
) -> None:
|
||||
"""更新持仓"""
|
||||
# 获取当前持仓
|
||||
stmt = select(Position).where(
|
||||
Position.pairing_id == pairing_id,
|
||||
Position.symbol == symbol,
|
||||
)
|
||||
result = await session.execute(stmt)
|
||||
position = result.scalar_one_or_none()
|
||||
|
||||
now = dt.now()
|
||||
price_decimal = Decimal(str(price))
|
||||
|
||||
if side == "buy":
|
||||
if position:
|
||||
# 更新持仓
|
||||
old_qty = position.quantity or 0
|
||||
old_cost = position.avg_cost or Decimal(0)
|
||||
new_qty = old_qty + quantity
|
||||
# 加权平均成本
|
||||
new_cost = (
|
||||
(old_qty * old_cost + quantity * price_decimal) / new_qty
|
||||
if new_qty > 0
|
||||
else Decimal(0)
|
||||
)
|
||||
|
||||
position.quantity = new_qty
|
||||
position.avg_cost = new_cost
|
||||
position.total_cost = new_cost * new_qty
|
||||
position.updated_at = now
|
||||
else:
|
||||
# 创建持仓
|
||||
position_id = str(uuid.uuid4())[:8]
|
||||
new_position = Position(
|
||||
id=position_id,
|
||||
pairing_id=pairing_id,
|
||||
symbol=symbol,
|
||||
quantity=quantity,
|
||||
available=quantity,
|
||||
frozen=0,
|
||||
avg_cost=price_decimal,
|
||||
total_cost=price_decimal * quantity,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
session.add(new_position)
|
||||
else: # sell
|
||||
if position:
|
||||
new_qty = max(0, (position.quantity or 0) - quantity)
|
||||
position.quantity = new_qty
|
||||
position.available = new_qty
|
||||
position.updated_at = now
|
||||
|
||||
# 更新配对资金
|
||||
stmt = select(Pairing).where(Pairing.id == pairing_id)
|
||||
result = await session.execute(stmt)
|
||||
pairing = result.scalar_one_or_none()
|
||||
|
||||
if pairing:
|
||||
amount = Decimal(str(quantity * price))
|
||||
if side == "buy":
|
||||
pairing.available_capital = (
|
||||
pairing.available_capital or Decimal(0)
|
||||
) - amount
|
||||
else:
|
||||
pairing.available_capital = (
|
||||
pairing.available_capital or Decimal(0)
|
||||
) + amount
|
||||
|
||||
|
||||
# 单例
|
||||
order_service = OrderService()
|
||||
@ -1,224 +0,0 @@
|
||||
"""
|
||||
配对管理服务
|
||||
|
||||
处理股票-策略配对的业务逻辑
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from typing import Any, Optional
|
||||
from datetime import datetime as dt
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import select, func, delete, update
|
||||
|
||||
from src.core.database import db
|
||||
from src.core.redis_client import redis_client
|
||||
from src.core.logger import get_logger
|
||||
from src.core.models import Pairing, PairingStatus
|
||||
from src.core.schemas.pairing import PairingCreate
|
||||
|
||||
logger = get_logger("core_service.pairing_service")
|
||||
|
||||
|
||||
class PairingService:
|
||||
"""配对管理服务"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.redis_key_prefix = "pairing:"
|
||||
|
||||
async def create(self, pairing: PairingCreate) -> dict[str, Any]:
|
||||
"""
|
||||
创建配对
|
||||
|
||||
Args:
|
||||
pairing: 配对创建请求
|
||||
|
||||
Returns:
|
||||
创建的配对信息
|
||||
"""
|
||||
pairing_id = str(uuid.uuid4())[:8]
|
||||
now = dt.now()
|
||||
|
||||
async with db.session() as session:
|
||||
# 检查是否已存在相同配对
|
||||
stmt = select(Pairing).where(
|
||||
Pairing.symbol == pairing.symbol,
|
||||
Pairing.strategy_id == pairing.strategy_id,
|
||||
Pairing.status != PairingStatus.STOPPED,
|
||||
)
|
||||
result = await session.execute(stmt)
|
||||
existing = result.scalar_one_or_none()
|
||||
|
||||
if existing:
|
||||
raise ValueError(
|
||||
f"已存在相同配对: {pairing.symbol} - {pairing.strategy_id}"
|
||||
)
|
||||
|
||||
# 创建配对对象
|
||||
new_pairing = Pairing(
|
||||
id=pairing_id,
|
||||
symbol=pairing.symbol,
|
||||
strategy_id=pairing.strategy_id,
|
||||
status=PairingStatus.STOPPED,
|
||||
initial_capital=Decimal(str(pairing.initial_capital)),
|
||||
available_capital=Decimal(str(pairing.initial_capital)),
|
||||
params=pairing.params or "{}",
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
session.add(new_pairing)
|
||||
await session.commit()
|
||||
await session.refresh(new_pairing)
|
||||
|
||||
# 缓存到 Redis
|
||||
await self._cache_pairing(pairing_id, new_pairing.to_dict())
|
||||
|
||||
return new_pairing.to_dict()
|
||||
|
||||
async def get(self, pairing_id: str) -> Optional[dict[str, Any]]:
|
||||
"""获取配对详情"""
|
||||
# 先从缓存获取
|
||||
cached = await self._get_cached_pairing(pairing_id)
|
||||
if cached:
|
||||
return cached
|
||||
|
||||
# 从数据库获取
|
||||
async with db.session() as session:
|
||||
stmt = select(Pairing).where(Pairing.id == pairing_id)
|
||||
result = await session.execute(stmt)
|
||||
pairing = result.scalar_one_or_none()
|
||||
|
||||
if not pairing:
|
||||
return None
|
||||
|
||||
data = pairing.to_dict()
|
||||
|
||||
# 缓存
|
||||
await self._cache_pairing(pairing_id, data)
|
||||
|
||||
return data
|
||||
|
||||
async def get_list(
|
||||
self,
|
||||
symbol: Optional[str] = None,
|
||||
strategy_id: Optional[str] = None,
|
||||
status: Optional[PairingStatus] = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
"""查询配对列表"""
|
||||
async with db.session() as session:
|
||||
# 构建查询条件
|
||||
stmt = select(Pairing)
|
||||
count_stmt = select(func.count(Pairing.id))
|
||||
|
||||
if symbol:
|
||||
stmt = stmt.where(Pairing.symbol == symbol)
|
||||
count_stmt = count_stmt.where(Pairing.symbol == symbol)
|
||||
if strategy_id:
|
||||
stmt = stmt.where(Pairing.strategy_id == strategy_id)
|
||||
count_stmt = count_stmt.where(Pairing.strategy_id == strategy_id)
|
||||
if status:
|
||||
stmt = stmt.where(Pairing.status == status)
|
||||
count_stmt = count_stmt.where(Pairing.status == status)
|
||||
|
||||
# 查询总数
|
||||
total_result = await session.execute(count_stmt)
|
||||
total = total_result.scalar() or 0
|
||||
|
||||
# 分页查询
|
||||
offset = (page - 1) * page_size
|
||||
stmt = (
|
||||
stmt.order_by(Pairing.created_at.desc()).offset(offset).limit(page_size)
|
||||
)
|
||||
result = await session.execute(stmt)
|
||||
pairings = result.scalars().all()
|
||||
|
||||
return {
|
||||
"items": [p.to_dict() for p in pairings],
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
}
|
||||
|
||||
async def update_status(
|
||||
self,
|
||||
pairing_id: str,
|
||||
status: PairingStatus,
|
||||
) -> Optional[dict[str, Any]]:
|
||||
"""更新配对状态"""
|
||||
now = dt.now()
|
||||
|
||||
async with db.session() as session:
|
||||
# 查询并更新
|
||||
stmt = select(Pairing).where(Pairing.id == pairing_id)
|
||||
result = await session.execute(stmt)
|
||||
pairing = result.scalar_one_or_none()
|
||||
|
||||
if not pairing:
|
||||
return None
|
||||
|
||||
pairing.status = status
|
||||
pairing.updated_at = now
|
||||
await session.commit()
|
||||
await session.refresh(pairing)
|
||||
|
||||
# 更新缓存
|
||||
await self._invalidate_pairing_cache(pairing_id)
|
||||
|
||||
# 发布状态变更事件
|
||||
await redis_client.publish(
|
||||
"pairing:status_changed", f"{pairing_id}:{status.value}"
|
||||
)
|
||||
|
||||
return await self.get(pairing_id)
|
||||
|
||||
async def delete(self, pairing_id: str) -> bool:
|
||||
"""删除配对"""
|
||||
async with db.session() as session:
|
||||
stmt = delete(Pairing).where(Pairing.id == pairing_id)
|
||||
result = await session.execute(stmt)
|
||||
await session.commit()
|
||||
|
||||
if result.rowcount == 0: # type: ignore
|
||||
return False
|
||||
|
||||
# 清除缓存
|
||||
await self._invalidate_pairing_cache(pairing_id)
|
||||
|
||||
return True
|
||||
|
||||
async def get_active_pairings(self) -> list[dict[str, Any]]:
|
||||
"""获取所有运行中的配对"""
|
||||
async with db.session() as session:
|
||||
stmt = select(Pairing).where(Pairing.status == PairingStatus.ACTIVE)
|
||||
result = await session.execute(stmt)
|
||||
pairings = result.scalars().all()
|
||||
|
||||
return [p.to_dict() for p in pairings]
|
||||
|
||||
async def _cache_pairing(self, pairing_id: str, data: dict[str, Any]) -> None:
|
||||
"""缓存配对信息"""
|
||||
import json
|
||||
|
||||
key = f"{self.redis_key_prefix}{pairing_id}"
|
||||
await redis_client.setex(key, 3600, json.dumps(data))
|
||||
|
||||
async def _get_cached_pairing(self, pairing_id: str) -> Optional[dict[str, Any]]:
|
||||
"""获取缓存的配对信息"""
|
||||
import json
|
||||
|
||||
key = f"{self.redis_key_prefix}{pairing_id}"
|
||||
data = await redis_client.get(key)
|
||||
if data:
|
||||
return json.loads(data)
|
||||
return None
|
||||
|
||||
async def _invalidate_pairing_cache(self, pairing_id: str) -> None:
|
||||
"""清除配对缓存"""
|
||||
key = f"{self.redis_key_prefix}{pairing_id}"
|
||||
await redis_client.delete(key)
|
||||
|
||||
|
||||
# 单例
|
||||
pairing_service = PairingService()
|
||||
@ -1,212 +0,0 @@
|
||||
"""
|
||||
持仓管理服务
|
||||
|
||||
处理持仓查询与同步
|
||||
"""
|
||||
|
||||
from typing import Any, Optional
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import select, func
|
||||
|
||||
from src.core.database import db
|
||||
from src.core.redis_client import redis_client
|
||||
from src.core.logger import get_logger
|
||||
from src.core.models import Position, Pairing
|
||||
|
||||
logger = get_logger("core_service.position_service")
|
||||
|
||||
|
||||
class PositionService:
|
||||
"""持仓管理服务"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.redis_key_prefix = "position:"
|
||||
|
||||
async def get_position(self, pairing_id: str) -> Optional[dict[str, Any]]:
|
||||
"""
|
||||
获取配对持仓
|
||||
|
||||
Args:
|
||||
pairing_id: 配对ID
|
||||
|
||||
Returns:
|
||||
持仓信息
|
||||
"""
|
||||
async with db.session() as session:
|
||||
stmt = select(Position).where(Position.pairing_id == pairing_id)
|
||||
result = await session.execute(stmt)
|
||||
position = result.scalar_one_or_none()
|
||||
|
||||
if not position:
|
||||
return None
|
||||
|
||||
quantity = position.quantity or 0
|
||||
cost_price = float(position.avg_cost) if position.avg_cost else 0
|
||||
|
||||
# 获取最新价格计算市值和盈亏
|
||||
latest_price = await self._get_latest_price(position.symbol)
|
||||
market_value = quantity * latest_price
|
||||
pnl = (latest_price - cost_price) * quantity if cost_price > 0 else 0
|
||||
pnl_ratio = (
|
||||
(latest_price - cost_price) / cost_price if cost_price > 0 else 0
|
||||
)
|
||||
|
||||
data = position.to_dict()
|
||||
data.update(
|
||||
{
|
||||
"latest_price": latest_price,
|
||||
"market_value": market_value,
|
||||
"pnl": pnl,
|
||||
"pnl_ratio": pnl_ratio,
|
||||
}
|
||||
)
|
||||
return data
|
||||
|
||||
async def list_positions(
|
||||
self,
|
||||
strategy_id: Optional[str] = None,
|
||||
symbol: Optional[str] = None,
|
||||
has_position: Optional[bool] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""查询持仓列表"""
|
||||
async with db.session() as session:
|
||||
# 联表查询
|
||||
stmt = select(Position, Pairing.strategy_id).join(
|
||||
Pairing, Position.pairing_id == Pairing.id
|
||||
)
|
||||
|
||||
if strategy_id:
|
||||
stmt = stmt.where(Pairing.strategy_id == strategy_id)
|
||||
if symbol:
|
||||
stmt = stmt.where(Position.symbol == symbol)
|
||||
if has_position is True:
|
||||
stmt = stmt.where(Position.quantity > 0)
|
||||
elif has_position is False:
|
||||
stmt = stmt.where(
|
||||
(Position.quantity == 0) | (Position.quantity.is_(None))
|
||||
)
|
||||
|
||||
stmt = stmt.order_by(Position.updated_at.desc())
|
||||
result = await session.execute(stmt)
|
||||
rows = result.all()
|
||||
|
||||
items = []
|
||||
for position, strat_id in rows:
|
||||
quantity = position.quantity or 0
|
||||
cost_price = float(position.avg_cost) if position.avg_cost else 0
|
||||
|
||||
# 获取最新价格
|
||||
latest_price = await self._get_latest_price(position.symbol)
|
||||
market_value = quantity * latest_price
|
||||
pnl = (latest_price - cost_price) * quantity if cost_price > 0 else 0
|
||||
|
||||
data = position.to_dict()
|
||||
data.update(
|
||||
{
|
||||
"latest_price": latest_price,
|
||||
"market_value": market_value,
|
||||
"pnl": pnl,
|
||||
"strategy_id": strat_id,
|
||||
}
|
||||
)
|
||||
items.append(data)
|
||||
|
||||
return {
|
||||
"items": items,
|
||||
"total": len(items),
|
||||
}
|
||||
|
||||
async def get_summary(self) -> dict[str, Any]:
|
||||
"""获取持仓汇总"""
|
||||
async with db.session() as session:
|
||||
# 统计有持仓的数量
|
||||
stmt = select(
|
||||
func.count(func.distinct(Position.pairing_id)).label("pairing_count"),
|
||||
func.count(func.distinct(Position.symbol)).label("symbol_count"),
|
||||
func.sum(Position.quantity).label("total_quantity"),
|
||||
).where(Position.quantity > 0)
|
||||
result = await session.execute(stmt)
|
||||
row = result.one()
|
||||
|
||||
# 查询所有有持仓的记录
|
||||
positions_stmt = select(Position).where(Position.quantity > 0)
|
||||
positions_result = await session.execute(positions_stmt)
|
||||
positions = positions_result.scalars().all()
|
||||
|
||||
total_market_value = 0.0
|
||||
total_cost = 0.0
|
||||
|
||||
for pos in positions:
|
||||
quantity = pos.quantity or 0
|
||||
cost_price = float(pos.avg_cost) if pos.avg_cost else 0
|
||||
latest_price = await self._get_latest_price(pos.symbol)
|
||||
|
||||
total_market_value += quantity * latest_price
|
||||
total_cost += quantity * cost_price
|
||||
|
||||
total_pnl = total_market_value - total_cost
|
||||
total_pnl_ratio = total_pnl / total_cost if total_cost > 0 else 0
|
||||
|
||||
return {
|
||||
"pairing_count": row.pairing_count or 0,
|
||||
"symbol_count": row.symbol_count or 0,
|
||||
"total_quantity": row.total_quantity or 0,
|
||||
"total_market_value": total_market_value,
|
||||
"total_cost": total_cost,
|
||||
"total_pnl": total_pnl,
|
||||
"total_pnl_ratio": total_pnl_ratio,
|
||||
}
|
||||
|
||||
async def sync_position(self, pairing_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
同步持仓(从 QMT 同步)
|
||||
|
||||
发送同步请求到 QMT 适配器
|
||||
"""
|
||||
import json
|
||||
|
||||
# 发送同步请求
|
||||
await redis_client.publish(
|
||||
"position:sync_request", json.dumps({"pairing_id": pairing_id})
|
||||
)
|
||||
|
||||
logger.info(f"发送持仓同步请求: {pairing_id}")
|
||||
|
||||
# 返回当前持仓
|
||||
position = await self.get_position(pairing_id)
|
||||
return position or {
|
||||
"pairing_id": pairing_id,
|
||||
"sync_requested": True,
|
||||
"message": "同步请求已发送,请稍后刷新",
|
||||
}
|
||||
|
||||
async def _get_latest_price(self, symbol: str) -> float:
|
||||
"""获取最新价格"""
|
||||
# 从 Redis 获取最新价格
|
||||
price_data = await redis_client.get(f"price:{symbol}")
|
||||
if price_data:
|
||||
import json
|
||||
|
||||
try:
|
||||
data = json.loads(price_data)
|
||||
return float(data.get("price", 0))
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
pass
|
||||
|
||||
# 从 Redis 行情数据获取
|
||||
tick_data = await redis_client.get(f"tick:{symbol}")
|
||||
if tick_data:
|
||||
import json
|
||||
|
||||
try:
|
||||
data = json.loads(tick_data)
|
||||
return float(data.get("lastPrice", 0))
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
pass
|
||||
|
||||
return 0.0
|
||||
|
||||
|
||||
# 单例
|
||||
position_service = PositionService()
|
||||
11
src/data_provider/__init__.py
Normal file
11
src/data_provider/__init__.py
Normal file
@ -0,0 +1,11 @@
|
||||
"""
|
||||
数据下载器模块
|
||||
"""
|
||||
|
||||
from .base_downloader import BaseDataDownloader
|
||||
from .xtquant_downloader import XtQuantDownloader
|
||||
|
||||
__all__ = [
|
||||
"BaseDataDownloader",
|
||||
"XtQuantDownloader",
|
||||
]
|
||||
341
src/data_provider/base_downloader.py
Normal file
341
src/data_provider/base_downloader.py
Normal file
@ -0,0 +1,341 @@
|
||||
"""
|
||||
数据下载基类
|
||||
定义数据下载的通用接口和流程
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime
|
||||
from typing import List, Optional, Dict, Any
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from ..core import get_logger, get_config
|
||||
from ..core.models import Kline
|
||||
from ..database_manager import DatabaseManager, get_table_definition
|
||||
|
||||
|
||||
class BaseDataDownloader(ABC):
|
||||
"""
|
||||
数据下载基类
|
||||
|
||||
功能:
|
||||
- 定义要下载的股票列表
|
||||
- 定义时间范围(start_date, end_date)
|
||||
- 定义数据周期(1m/5m/15m/30m/60m/1d/1w)
|
||||
- 下载数据(由子类实现具体逻辑)
|
||||
- 保存数据到数据库
|
||||
|
||||
使用示例:
|
||||
class QMTDownloader(BaseDataDownloader):
|
||||
def _download_klines(self, symbol, start_date, end_date, period):
|
||||
# 实现具体的下载逻辑
|
||||
return klines
|
||||
|
||||
downloader = QMTDownloader(
|
||||
symbols=['000001.SZ', '600000.SH'],
|
||||
start_date='2024-01-01',
|
||||
end_date='2024-12-31',
|
||||
periods=['1d', '60m']
|
||||
)
|
||||
downloader.download_and_save()
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
symbols: List[str],
|
||||
start_date: str | datetime,
|
||||
end_date: str | datetime,
|
||||
periods: Optional[List[str]] = None,
|
||||
database: Optional[str] = None,
|
||||
):
|
||||
"""
|
||||
初始化数据下载器
|
||||
|
||||
Args:
|
||||
symbols: 股票代码列表,如 ['000001.SZ', '600000.SH']
|
||||
start_date: 开始日期,格式 'YYYY-MM-DD' 或 datetime 对象
|
||||
end_date: 结束日期,格式 'YYYY-MM-DD' 或 datetime 对象
|
||||
periods: 数据周期列表,如 ['1m', '5m', '1d'],默认为 ['1d']
|
||||
database: 目标数据库名,默认从配置读取
|
||||
"""
|
||||
self.logger = get_logger(self.__class__.__name__)
|
||||
self.config = get_config()
|
||||
|
||||
# 参数验证和转换
|
||||
self.symbols = self._validate_symbols(symbols)
|
||||
self.start_date = self._parse_date(start_date)
|
||||
self.end_date = self._parse_date(end_date)
|
||||
self.periods = periods or ["1d"]
|
||||
self.database = database or self.config.get("database.database")
|
||||
|
||||
if not self.database:
|
||||
raise ValueError(
|
||||
"未指定目标数据库,请在配置文件中设置 database.database 或通过参数传入"
|
||||
)
|
||||
|
||||
# 验证参数
|
||||
self._validate_parameters()
|
||||
|
||||
# 初始化数据库连接
|
||||
self._init_database()
|
||||
|
||||
self.logger.info(
|
||||
f"数据下载器初始化完成: {len(self.symbols)} 个标的, "
|
||||
f"{self.start_date.date()} ~ {self.end_date.date()}, "
|
||||
f"周期: {self.periods}"
|
||||
)
|
||||
|
||||
def _validate_symbols(self, symbols: List[str]) -> List[str]:
|
||||
"""验证并规范化股票代码"""
|
||||
if not symbols:
|
||||
raise ValueError("股票列表不能为空")
|
||||
|
||||
# 转换为大写
|
||||
return [s.upper() for s in symbols]
|
||||
|
||||
def _parse_date(self, date: str | datetime) -> datetime:
|
||||
"""解析日期"""
|
||||
if isinstance(date, datetime):
|
||||
return date
|
||||
|
||||
if isinstance(date, str):
|
||||
try:
|
||||
return datetime.strptime(date, "%Y-%m-%d")
|
||||
except ValueError:
|
||||
try:
|
||||
return datetime.strptime(date, "%Y%m%d")
|
||||
except ValueError:
|
||||
raise ValueError(
|
||||
f"日期格式错误: {date},支持格式: 'YYYY-MM-DD' 或 'YYYYMMDD'"
|
||||
)
|
||||
|
||||
raise ValueError(f"不支持的日期类型: {type(date)}")
|
||||
|
||||
def _validate_parameters(self):
|
||||
"""验证参数"""
|
||||
if self.start_date >= self.end_date:
|
||||
raise ValueError(
|
||||
f"开始日期必须早于结束日期: {self.start_date} >= {self.end_date}"
|
||||
)
|
||||
|
||||
# 验证周期
|
||||
valid_periods = ["1m", "5m", "15m", "30m", "60m", "1d", "1w"]
|
||||
for period in self.periods:
|
||||
if period not in valid_periods:
|
||||
raise ValueError(f"不支持的周期: {period},支持: {valid_periods}")
|
||||
|
||||
self.logger.debug("参数验证通过")
|
||||
|
||||
def _init_database(self):
|
||||
"""初始化数据库连接"""
|
||||
# 创建数据库(如果不存在)
|
||||
db_manager = DatabaseManager()
|
||||
if not db_manager.database_exists(self.database):
|
||||
self.logger.warning(f"数据库 {self.database} 不存在,正在创建...")
|
||||
db_manager.create_database(self.database)
|
||||
|
||||
# 确保 klines 表存在
|
||||
klines_def = get_table_definition("klines")
|
||||
if not db_manager.table_exists(self.database, "klines"):
|
||||
self.logger.warning("表 klines 不存在,正在创建...")
|
||||
db_manager.create_table(
|
||||
database=self.database,
|
||||
table_name=klines_def["name"],
|
||||
columns=klines_def["columns"],
|
||||
indexes=klines_def["indexes"],
|
||||
)
|
||||
|
||||
db_manager.close()
|
||||
|
||||
# 创建 SQLAlchemy 引擎
|
||||
self.engine = self._create_engine()
|
||||
self.Session = sessionmaker(bind=self.engine)
|
||||
|
||||
self.logger.debug(f"数据库连接初始化完成: {self.database}")
|
||||
|
||||
def _create_engine(self):
|
||||
"""创建数据库引擎"""
|
||||
host = self.config.get("database.host", "127.0.0.1")
|
||||
port = self.config.get("database.port", 3306)
|
||||
user = self.config.get("database.user", "root")
|
||||
password = self.config.get("database.password", "")
|
||||
|
||||
connection_url = (
|
||||
f"mysql+pymysql://{user}:{password}@"
|
||||
f"{host}:{port}/{self.database}?charset=utf8mb4"
|
||||
)
|
||||
return create_engine(connection_url, echo=False, pool_pre_ping=True)
|
||||
|
||||
@abstractmethod
|
||||
def _download_klines(
|
||||
self, symbol: str, start_date: datetime, end_date: datetime, period: str
|
||||
) -> List[Kline]:
|
||||
"""
|
||||
下载K线数据(抽象方法,由子类实现)
|
||||
|
||||
Args:
|
||||
symbol: 股票代码
|
||||
start_date: 开始日期
|
||||
end_date: 结束日期
|
||||
period: 数据周期
|
||||
|
||||
Returns:
|
||||
Kline 对象列表
|
||||
"""
|
||||
pass
|
||||
|
||||
def download_and_save(self) -> Dict[str, Any]:
|
||||
"""
|
||||
下载并保存数据
|
||||
|
||||
Returns:
|
||||
统计信息字典
|
||||
"""
|
||||
self.logger.info("=" * 50)
|
||||
self.logger.info("开始下载数据")
|
||||
self.logger.info("=" * 50)
|
||||
|
||||
stats = {
|
||||
"total_symbols": len(self.symbols),
|
||||
"total_periods": len(self.periods),
|
||||
"success_count": 0,
|
||||
"failed_count": 0,
|
||||
"total_records": 0,
|
||||
"details": [],
|
||||
}
|
||||
|
||||
for symbol in self.symbols:
|
||||
for period in self.periods:
|
||||
try:
|
||||
self.logger.info(f"下载 {symbol} [{period}] 数据...")
|
||||
|
||||
# 调用子类实现的下载方法
|
||||
klines = self._download_klines(
|
||||
symbol=symbol,
|
||||
start_date=self.start_date,
|
||||
end_date=self.end_date,
|
||||
period=period,
|
||||
)
|
||||
|
||||
if klines:
|
||||
# 保存到数据库
|
||||
saved_count = self._save_klines(klines, period)
|
||||
stats["success_count"] += 1
|
||||
stats["total_records"] += saved_count
|
||||
|
||||
self.logger.info(
|
||||
f"✓ {symbol} [{period}]: 下载 {len(klines)} 条, "
|
||||
f"保存 {saved_count} 条"
|
||||
)
|
||||
|
||||
stats["details"].append(
|
||||
{
|
||||
"symbol": symbol,
|
||||
"period": period,
|
||||
"status": "success",
|
||||
"downloaded": len(klines),
|
||||
"saved": saved_count,
|
||||
}
|
||||
)
|
||||
else:
|
||||
self.logger.warning(f"✗ {symbol} [{period}]: 无数据")
|
||||
stats["failed_count"] += 1
|
||||
stats["details"].append(
|
||||
{
|
||||
"symbol": symbol,
|
||||
"period": period,
|
||||
"status": "no_data",
|
||||
"downloaded": 0,
|
||||
"saved": 0,
|
||||
}
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"✗ {symbol} [{period}]: 下载失败 - {e}")
|
||||
stats["failed_count"] += 1
|
||||
stats["details"].append(
|
||||
{
|
||||
"symbol": symbol,
|
||||
"period": period,
|
||||
"status": "error",
|
||||
"error": str(e),
|
||||
}
|
||||
)
|
||||
|
||||
self.logger.info("=" * 50)
|
||||
self.logger.info("下载完成")
|
||||
self.logger.info(
|
||||
f"总计: {stats['total_symbols']} 个标的 x {stats['total_periods']} 个周期"
|
||||
)
|
||||
self.logger.info(
|
||||
f"成功: {stats['success_count']}, 失败: {stats['failed_count']}"
|
||||
)
|
||||
self.logger.info(f"保存记录数: {stats['total_records']}")
|
||||
self.logger.info("=" * 50)
|
||||
|
||||
return stats
|
||||
|
||||
def _save_klines(self, klines: List[Kline], period: str) -> int:
|
||||
"""
|
||||
保存K线数据到数据库
|
||||
|
||||
Args:
|
||||
klines: Kline 对象列表
|
||||
period: 数据周期
|
||||
|
||||
Returns:
|
||||
保存的记录数
|
||||
"""
|
||||
if not klines:
|
||||
return 0
|
||||
|
||||
session = self.Session()
|
||||
saved_count = 0
|
||||
|
||||
try:
|
||||
for kline in klines:
|
||||
# 转换为数据库记录
|
||||
record = {
|
||||
"symbol": kline.symbol,
|
||||
"period": period,
|
||||
"timestamp": kline.timestamp,
|
||||
"open": kline.open,
|
||||
"high": kline.high,
|
||||
"low": kline.low,
|
||||
"close": kline.close,
|
||||
"volume": kline.volume,
|
||||
"amount": kline.amount,
|
||||
}
|
||||
|
||||
# 使用 INSERT ... ON DUPLICATE KEY UPDATE 避免重复
|
||||
# 这里使用原始 SQL
|
||||
sql = """
|
||||
INSERT INTO klines
|
||||
(symbol, period, timestamp, open, high, low, close, volume, amount)
|
||||
VALUES
|
||||
(:symbol, :period, :timestamp, :open, :high, :low, :close, :volume, :amount)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
open=VALUES(open), high=VALUES(high), low=VALUES(low),
|
||||
close=VALUES(close), volume=VALUES(volume), amount=VALUES(amount)
|
||||
"""
|
||||
|
||||
session.execute(text(sql), record)
|
||||
saved_count += 1
|
||||
|
||||
session.commit()
|
||||
self.logger.debug(f"保存 {saved_count} 条记录到数据库")
|
||||
|
||||
except Exception as e:
|
||||
session.rollback()
|
||||
self.logger.error(f"保存数据失败: {e}")
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
return saved_count
|
||||
|
||||
def close(self):
|
||||
"""关闭数据库连接"""
|
||||
if hasattr(self, "engine"):
|
||||
self.engine.dispose()
|
||||
self.logger.info("数据库连接已关闭")
|
||||
196
src/data_provider/xtquant_downloader.py
Normal file
196
src/data_provider/xtquant_downloader.py
Normal file
@ -0,0 +1,196 @@
|
||||
"""
|
||||
XtQuant 数据下载器
|
||||
使用 xtquant 库下载历史 K线数据
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from xtquant import xtdata
|
||||
from xtquant import xtdatacenter as xtdc
|
||||
|
||||
from .base_downloader import BaseDataDownloader
|
||||
from ..core.models import Kline
|
||||
|
||||
|
||||
class XtQuantDownloader(BaseDataDownloader):
|
||||
"""
|
||||
XtQuant 数据下载器
|
||||
|
||||
使用 XtQuant API 下载历史 K线数据
|
||||
|
||||
使用示例:
|
||||
downloader = XtQuantDownloader(
|
||||
symbols=['000001.SZ', '600000.SH'],
|
||||
start_date='2024-01-01',
|
||||
end_date='2024-12-31',
|
||||
periods=['1d', '60m'],
|
||||
token='your_token_here'
|
||||
)
|
||||
downloader.download_and_save()
|
||||
"""
|
||||
|
||||
# XtQuant 周期映射
|
||||
PERIOD_MAPPING = {
|
||||
"1m": "1m",
|
||||
"5m": "5m",
|
||||
"15m": "15m",
|
||||
"30m": "30m",
|
||||
"60m": "1h", # XtQuant 使用 1h
|
||||
"1d": "1d",
|
||||
"1w": "1w",
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
symbols: List[str],
|
||||
start_date: str | datetime,
|
||||
end_date: str | datetime,
|
||||
periods: Optional[List[str]] = None,
|
||||
database: Optional[str] = None,
|
||||
token: Optional[str] = None,
|
||||
optimize_addresses: Optional[List[str]] = None,
|
||||
):
|
||||
"""
|
||||
初始化 XtQuant 下载器
|
||||
|
||||
Args:
|
||||
symbols: 股票代码列表
|
||||
start_date: 开始日期
|
||||
end_date: 结束日期
|
||||
periods: 数据周期列表
|
||||
database: 目标数据库名
|
||||
token: XtQuant Token(如果不提供,从配置文件读取)
|
||||
optimize_addresses: 优化地址列表
|
||||
"""
|
||||
super().__init__(symbols, start_date, end_date, periods, database)
|
||||
|
||||
# 初始化 XtQuant
|
||||
self._init_xtquant(token, optimize_addresses)
|
||||
|
||||
def _init_xtquant(
|
||||
self, token: Optional[str], optimize_addresses: Optional[List[str]]
|
||||
):
|
||||
"""初始化 XtQuant 数据中心"""
|
||||
# 获取 token
|
||||
if token is None:
|
||||
token = self.config.get("xtquant.token")
|
||||
if not token:
|
||||
raise ValueError(
|
||||
"XtQuant token 未设置,请在配置文件中设置或通过参数传入"
|
||||
)
|
||||
|
||||
self.logger.info(f"初始化 XtQuant 数据中心,Token: {token[:20]}...")
|
||||
|
||||
# 设置 token
|
||||
xtdc.set_token(token)
|
||||
|
||||
# 初始化数据中心
|
||||
try:
|
||||
xtdc.init()
|
||||
self.logger.info("XtQuant 数据中心初始化成功")
|
||||
except Exception as e:
|
||||
self.logger.error(f"XtQuant 数据中心初始化失败: {e}")
|
||||
raise
|
||||
|
||||
# 设置优化地址
|
||||
if optimize_addresses is None:
|
||||
optimize_addresses = self.config.get("xtquant.optimize_addresses", [])
|
||||
|
||||
if optimize_addresses:
|
||||
try:
|
||||
xtdc.set_allow_optmize_address(optimize_addresses)
|
||||
self.logger.info(f"优化地址已设置: {len(optimize_addresses)} 个")
|
||||
except Exception as e:
|
||||
self.logger.warning(f"优化地址设置失败: {e}")
|
||||
|
||||
# 下载基础数据
|
||||
try:
|
||||
self.logger.info("下载板块数据...")
|
||||
xtdata.download_sector_data()
|
||||
self.logger.info("下载历史合约数据...")
|
||||
xtdata.download_history_contracts()
|
||||
self.logger.info("基础数据下载完成")
|
||||
except Exception as e:
|
||||
self.logger.warning(f"基础数据下载失败: {e}")
|
||||
|
||||
def _download_klines(
|
||||
self, symbol: str, start_date: datetime, end_date: datetime, period: str
|
||||
) -> List[Kline]:
|
||||
"""
|
||||
下载 K线数据(实现抽象方法)
|
||||
|
||||
Args:
|
||||
symbol: 股票代码
|
||||
start_date: 开始日期
|
||||
end_date: 结束日期
|
||||
period: 数据周期
|
||||
|
||||
Returns:
|
||||
K线对象列表
|
||||
"""
|
||||
# 转换周期格式
|
||||
xt_period = self.PERIOD_MAPPING.get(period, period)
|
||||
|
||||
# 转换日期格式为 YYYYMMDD
|
||||
start_str = start_date.strftime("%Y%m%d")
|
||||
end_str = end_date.strftime("%Y%m%d")
|
||||
|
||||
# 先下载历史数据(确保本地有缓存)
|
||||
try:
|
||||
self.logger.debug(f"下载 {symbol} [{period}] 历史数据到本地...")
|
||||
xtdata.download_history_data(symbol, xt_period, start_str, end_str)
|
||||
except Exception as e:
|
||||
self.logger.warning(f"下载历史数据到本地失败: {e}")
|
||||
|
||||
# 从本地获取数据
|
||||
try:
|
||||
data = xtdata.get_market_data_ex(
|
||||
field_list=["open", "high", "low", "close", "volume", "amount"],
|
||||
stock_list=[symbol],
|
||||
period=xt_period,
|
||||
start_time=start_str,
|
||||
end_time=end_str,
|
||||
count=-1, # 获取所有数据
|
||||
dividend_type="none", # 不复权
|
||||
fill_data=True, # 填充数据
|
||||
)
|
||||
|
||||
if symbol not in data or len(data[symbol]) == 0:
|
||||
self.logger.warning(f"{symbol} [{period}] 没有数据")
|
||||
return []
|
||||
|
||||
df = data[symbol]
|
||||
self.logger.debug(f"获取到 {len(df)} 条 {symbol} [{period}] 数据")
|
||||
|
||||
# 转换为 Kline 对象
|
||||
klines = []
|
||||
for timestamp, row in df.iterrows():
|
||||
# 跳过无效数据
|
||||
if (
|
||||
row["open"] <= 0
|
||||
or row["high"] <= 0
|
||||
or row["low"] <= 0
|
||||
or row["close"] <= 0
|
||||
):
|
||||
continue
|
||||
|
||||
kline = Kline(
|
||||
symbol=symbol,
|
||||
period=period, # 使用我们的标准周期格式
|
||||
timestamp=timestamp,
|
||||
open=round(row["open"], 2),
|
||||
high=round(row["high"], 2),
|
||||
low=round(row["low"], 2),
|
||||
close=round(row["close"], 2),
|
||||
volume=int(row["volume"]),
|
||||
amount=round(row["amount"], 2) if row["amount"] > 0 else None,
|
||||
open_interest=0, # 股票没有持仓量
|
||||
)
|
||||
klines.append(kline)
|
||||
|
||||
return klines
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"获取 {symbol} [{period}] 数据失败: {e}")
|
||||
raise
|
||||
@ -1,12 +0,0 @@
|
||||
"""
|
||||
QTrade Data Service 数据服务
|
||||
|
||||
提供:
|
||||
- 行情数据接收与分发
|
||||
- K线数据存储与查询
|
||||
- 回测数据回放
|
||||
"""
|
||||
|
||||
from .app import app
|
||||
|
||||
__all__ = ["app"]
|
||||
@ -1,83 +0,0 @@
|
||||
"""
|
||||
Data Service FastAPI 应用
|
||||
|
||||
数据服务,提供:
|
||||
- K线数据下载与查询
|
||||
- 行情数据接收与分发
|
||||
- 回测数据回放
|
||||
"""
|
||||
|
||||
from fastapi import FastAPI
|
||||
|
||||
from src.core.base_app import BaseApp
|
||||
from src.core.config import get_settings
|
||||
|
||||
# 加载服务配置
|
||||
settings = get_settings("data_service")
|
||||
|
||||
|
||||
class DataServiceApp(BaseApp):
|
||||
"""数据服务应用"""
|
||||
|
||||
name = "data_service"
|
||||
title = "QTrade Data Service"
|
||||
description = "量化交易系统数据服务"
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._market_receiver = None
|
||||
self._kline_service = None
|
||||
|
||||
async def on_startup(self):
|
||||
"""启动数据服务"""
|
||||
from .services.market_receiver import market_receiver
|
||||
from .services.kline_service import kline_service
|
||||
|
||||
self._market_receiver = market_receiver
|
||||
self._kline_service = kline_service
|
||||
|
||||
# 启动行情接收器
|
||||
try:
|
||||
await market_receiver.start()
|
||||
self.logger.info("行情接收器已启动")
|
||||
except Exception as e:
|
||||
self.logger.warning(f"行情接收器启动失败: {e}")
|
||||
|
||||
# 启动K线服务
|
||||
try:
|
||||
await kline_service.start()
|
||||
self.logger.info("K线服务已启动")
|
||||
except Exception as e:
|
||||
self.logger.warning(f"K线服务启动失败: {e}")
|
||||
|
||||
async def on_shutdown(self):
|
||||
"""关闭数据服务"""
|
||||
if self._market_receiver:
|
||||
await self._market_receiver.stop()
|
||||
if self._kline_service:
|
||||
await self._kline_service.stop()
|
||||
|
||||
def setup_routes(self, app: FastAPI):
|
||||
"""注册路由"""
|
||||
from .routes import market, kline, backtest
|
||||
|
||||
app.include_router(market.router, prefix="/market", tags=["行情"])
|
||||
app.include_router(kline.router, prefix="/kline", tags=["K线"])
|
||||
app.include_router(backtest.router, prefix="/backtest", tags=["回测"])
|
||||
|
||||
|
||||
# 创建应用实例
|
||||
_app_instance = DataServiceApp()
|
||||
app = _app_instance.app
|
||||
|
||||
|
||||
def run():
|
||||
"""运行服务"""
|
||||
_app_instance.run(
|
||||
host=settings.services.data_service.host,
|
||||
port=settings.services.data_service.port,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
@ -1,7 +0,0 @@
|
||||
"""
|
||||
Data Service 路由模块
|
||||
"""
|
||||
|
||||
from . import market, kline, backtest
|
||||
|
||||
__all__ = ["market", "kline", "backtest"]
|
||||
@ -1,160 +0,0 @@
|
||||
"""
|
||||
回测数据路由
|
||||
|
||||
提供:
|
||||
- 回测数据回放控制
|
||||
- 历史行情模拟推送
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
from datetime import datetime as dt
|
||||
|
||||
from fastapi import APIRouter, Query, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from ..services.data_player import data_player, PlaybackStatus
|
||||
|
||||
logger = get_logger("data_service.backtest")
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class PlaybackConfig(BaseModel):
|
||||
"""回放配置"""
|
||||
|
||||
symbols: list[str]
|
||||
start_date: str
|
||||
end_date: str
|
||||
speed: float = 1.0 # 回放速度倍数
|
||||
period: str = "1m" # 回放K线周期
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
async def get_playback_status() -> dict[str, Any]:
|
||||
"""获取回放状态"""
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": data_player.state,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/start")
|
||||
async def start_playback(config: PlaybackConfig) -> dict[str, Any]:
|
||||
"""启动回测数据回放
|
||||
|
||||
Args:
|
||||
config: 回放配置
|
||||
|
||||
Returns:
|
||||
操作结果
|
||||
"""
|
||||
if data_player.status == PlaybackStatus.PLAYING:
|
||||
raise HTTPException(status_code=400, detail="回放已在运行中")
|
||||
|
||||
# 验证配置
|
||||
if not config.symbols:
|
||||
raise HTTPException(status_code=400, detail="请指定回放股票")
|
||||
|
||||
try:
|
||||
start_dt = dt.strptime(config.start_date, "%Y-%m-%d")
|
||||
end_dt = dt.strptime(config.end_date, "%Y-%m-%d")
|
||||
if start_dt >= end_dt:
|
||||
raise HTTPException(status_code=400, detail="结束日期必须大于开始日期")
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="日期格式错误,请使用 YYYY-MM-DD")
|
||||
|
||||
# 启动回放
|
||||
success = await data_player.start(
|
||||
symbols=config.symbols,
|
||||
start_date=config.start_date,
|
||||
end_date=config.end_date,
|
||||
period=config.period,
|
||||
speed=config.speed,
|
||||
)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(
|
||||
status_code=400, detail="启动回放失败,可能没有符合条件的数据"
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"回测回放已启动: {config.symbols}, {config.start_date} - {config.end_date}"
|
||||
)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "回放已启动",
|
||||
"data": data_player.state,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/stop")
|
||||
async def stop_playback() -> dict[str, Any]:
|
||||
"""停止回测数据回放"""
|
||||
if data_player.status == PlaybackStatus.STOPPED:
|
||||
raise HTTPException(status_code=400, detail="回放未在运行")
|
||||
|
||||
await data_player.stop()
|
||||
|
||||
logger.info("回测回放已停止")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "回放已停止",
|
||||
"data": data_player.state,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/pause")
|
||||
async def pause_playback() -> dict[str, Any]:
|
||||
"""暂停回测数据回放"""
|
||||
if data_player.status != PlaybackStatus.PLAYING:
|
||||
raise HTTPException(status_code=400, detail="回放未在运行")
|
||||
|
||||
await data_player.pause()
|
||||
|
||||
logger.info("回测回放已暂停")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "回放已暂停",
|
||||
"data": data_player.state,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/resume")
|
||||
async def resume_playback() -> dict[str, Any]:
|
||||
"""恢复回测数据回放"""
|
||||
if data_player.status != PlaybackStatus.PAUSED:
|
||||
raise HTTPException(status_code=400, detail="回放未在暂停状态")
|
||||
|
||||
await data_player.resume()
|
||||
|
||||
logger.info("回测回放已恢复")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "回放已恢复",
|
||||
"data": data_player.state,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/speed")
|
||||
async def set_playback_speed(
|
||||
speed: float = Query(..., ge=0.1, le=100.0, description="回放速度倍数"),
|
||||
) -> dict[str, Any]:
|
||||
"""设置回放速度
|
||||
|
||||
Args:
|
||||
speed: 速度倍数,0.1-100
|
||||
"""
|
||||
data_player.set_speed(speed)
|
||||
|
||||
logger.info(f"回放速度已设置为 {speed}x")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": f"速度已设置为 {speed}x",
|
||||
"data": {"speed": speed},
|
||||
}
|
||||
@ -1,238 +0,0 @@
|
||||
"""
|
||||
K线数据路由
|
||||
|
||||
提供:
|
||||
- K线数据查询
|
||||
- K线数据存储
|
||||
- K线周期转换
|
||||
"""
|
||||
|
||||
from typing import Any, Optional
|
||||
from datetime import datetime as dt
|
||||
from enum import Enum
|
||||
|
||||
from fastapi import APIRouter, Query, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import text
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.database import db
|
||||
from src.core.redis_client import redis_client
|
||||
|
||||
logger = get_logger("data_service.kline")
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class KlinePeriod(str, Enum):
|
||||
"""K线周期"""
|
||||
|
||||
M1 = "1m"
|
||||
M5 = "5m"
|
||||
M15 = "15m"
|
||||
M30 = "30m"
|
||||
M60 = "60m"
|
||||
D1 = "1d"
|
||||
W1 = "1w"
|
||||
|
||||
|
||||
class KlineData(BaseModel):
|
||||
"""K线数据"""
|
||||
|
||||
symbol: str
|
||||
period: str
|
||||
open: float
|
||||
high: float
|
||||
low: float
|
||||
close: float
|
||||
volume: int
|
||||
amount: float
|
||||
timestamp: dt
|
||||
|
||||
|
||||
class KlineResponse(BaseModel):
|
||||
"""K线响应"""
|
||||
|
||||
code: int = 0
|
||||
message: str = "success"
|
||||
data: list[dict]
|
||||
count: int
|
||||
|
||||
|
||||
# K线周期到表名的映射
|
||||
PERIOD_TABLE_MAP = {
|
||||
"1m": "klines_1m",
|
||||
"5m": "klines_5m",
|
||||
"15m": "klines_15m",
|
||||
"30m": "klines_30m",
|
||||
"60m": "klines_60m",
|
||||
"1d": "klines_1d",
|
||||
"1w": "klines_1w",
|
||||
}
|
||||
|
||||
|
||||
@router.get("/history/{symbol}")
|
||||
async def get_kline_history(
|
||||
symbol: str,
|
||||
period: KlinePeriod = Query(KlinePeriod.D1, description="K线周期"),
|
||||
start_date: Optional[str] = Query(None, description="开始日期 YYYY-MM-DD"),
|
||||
end_date: Optional[str] = Query(None, description="结束日期 YYYY-MM-DD"),
|
||||
limit: int = Query(100, ge=1, le=1000, description="返回数量"),
|
||||
) -> dict[str, Any]:
|
||||
"""获取K线历史数据
|
||||
|
||||
Args:
|
||||
symbol: 股票代码
|
||||
period: K线周期
|
||||
start_date: 开始日期
|
||||
end_date: 结束日期
|
||||
limit: 返回数量限制
|
||||
|
||||
Returns:
|
||||
K线数据列表
|
||||
"""
|
||||
try:
|
||||
table_name = PERIOD_TABLE_MAP.get(period.value)
|
||||
if not table_name:
|
||||
raise HTTPException(status_code=400, detail=f"不支持的K线周期: {period}")
|
||||
|
||||
# 构建查询条件
|
||||
conditions = ["symbol = :symbol"]
|
||||
params = {"symbol": symbol, "limit": limit}
|
||||
|
||||
if start_date:
|
||||
conditions.append("timestamp >= :start_date")
|
||||
params["start_date"] = start_date
|
||||
|
||||
if end_date:
|
||||
conditions.append("timestamp <= :end_date")
|
||||
params["end_date"] = end_date
|
||||
|
||||
where_clause = " AND ".join(conditions)
|
||||
|
||||
query = text(f"""
|
||||
SELECT symbol, open, high, low, close, volume, amount, timestamp
|
||||
FROM {table_name}
|
||||
WHERE {where_clause}
|
||||
ORDER BY timestamp DESC
|
||||
LIMIT :limit
|
||||
""")
|
||||
|
||||
async with db.session() as session:
|
||||
result = await session.execute(query, params)
|
||||
rows = result.fetchall()
|
||||
|
||||
data = [
|
||||
{
|
||||
"symbol": row[0],
|
||||
"open": float(row[1]),
|
||||
"high": float(row[2]),
|
||||
"low": float(row[3]),
|
||||
"close": float(row[4]),
|
||||
"volume": int(row[5]),
|
||||
"amount": float(row[6]),
|
||||
"timestamp": row[7].isoformat() if row[7] else None,
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": list(reversed(data)), # 按时间正序
|
||||
"count": len(data),
|
||||
"period": period.value,
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"获取K线数据失败: {symbol}, {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/latest/{symbol}")
|
||||
async def get_latest_kline(
|
||||
symbol: str,
|
||||
period: KlinePeriod = Query(KlinePeriod.D1, description="K线周期"),
|
||||
) -> dict[str, Any]:
|
||||
"""获取最新K线数据
|
||||
|
||||
Args:
|
||||
symbol: 股票代码
|
||||
period: K线周期
|
||||
|
||||
Returns:
|
||||
最新一根K线数据
|
||||
"""
|
||||
try:
|
||||
# 先从 Redis 缓存获取
|
||||
cache_key = f"kline:{period.value}:{symbol}"
|
||||
cached = await redis_client.hgetall(cache_key)
|
||||
|
||||
if cached:
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": cached,
|
||||
"source": "cache",
|
||||
}
|
||||
|
||||
# 缓存未命中,从数据库获取
|
||||
table_name = PERIOD_TABLE_MAP.get(period.value)
|
||||
|
||||
query = text(f"""
|
||||
SELECT symbol, open, high, low, close, volume, amount, timestamp
|
||||
FROM {table_name}
|
||||
WHERE symbol = :symbol
|
||||
ORDER BY timestamp DESC
|
||||
LIMIT 1
|
||||
""")
|
||||
|
||||
async with db.session() as session:
|
||||
result = await session.execute(query, {"symbol": symbol})
|
||||
row = result.fetchone()
|
||||
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail=f"未找到 {symbol} 的K线数据")
|
||||
|
||||
data = {
|
||||
"symbol": row[0],
|
||||
"open": float(row[1]),
|
||||
"high": float(row[2]),
|
||||
"low": float(row[3]),
|
||||
"close": float(row[4]),
|
||||
"volume": int(row[5]),
|
||||
"amount": float(row[6]),
|
||||
"timestamp": row[7].isoformat() if row[7] else None,
|
||||
}
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": data,
|
||||
"source": "database",
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"获取最新K线失败: {symbol}, {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/periods")
|
||||
async def get_available_periods() -> dict[str, Any]:
|
||||
"""获取支持的K线周期列表"""
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": [
|
||||
{"value": "1m", "name": "1分钟", "table": "klines_1m"},
|
||||
{"value": "5m", "name": "5分钟", "table": "klines_5m"},
|
||||
{"value": "15m", "name": "15分钟", "table": "klines_15m"},
|
||||
{"value": "30m", "name": "30分钟", "table": "klines_30m"},
|
||||
{"value": "60m", "name": "60分钟", "table": "klines_60m"},
|
||||
{"value": "1d", "name": "日线", "table": "klines_1d"},
|
||||
{"value": "1w", "name": "周线", "table": "klines_1w"},
|
||||
],
|
||||
}
|
||||
@ -1,202 +0,0 @@
|
||||
"""
|
||||
行情数据路由
|
||||
|
||||
提供:
|
||||
- 实时行情查询
|
||||
- 行情快照
|
||||
- 行情订阅管理
|
||||
"""
|
||||
|
||||
from typing import Any, Optional
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, Query, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.redis_client import redis_client, RedisKeys
|
||||
|
||||
logger = get_logger("data_service.market")
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class QuoteResponse(BaseModel):
|
||||
"""行情响应"""
|
||||
|
||||
symbol: str
|
||||
name: Optional[str] = None
|
||||
last_price: float
|
||||
open_price: float
|
||||
high_price: float
|
||||
low_price: float
|
||||
pre_close: float
|
||||
volume: int
|
||||
amount: float
|
||||
bid_price: list[float]
|
||||
bid_volume: list[int]
|
||||
ask_price: list[float]
|
||||
ask_volume: list[int]
|
||||
timestamp: datetime
|
||||
|
||||
|
||||
class QuoteListResponse(BaseModel):
|
||||
"""行情列表响应"""
|
||||
|
||||
code: int = 0
|
||||
message: str = "success"
|
||||
data: list[QuoteResponse]
|
||||
count: int
|
||||
|
||||
|
||||
@router.get("/quote/{symbol}")
|
||||
async def get_quote(symbol: str) -> dict[str, Any]:
|
||||
"""获取单个股票实时行情
|
||||
|
||||
Args:
|
||||
symbol: 股票代码,如 600000.SH
|
||||
|
||||
Returns:
|
||||
实时行情数据
|
||||
"""
|
||||
try:
|
||||
quote_key = RedisKeys.quote(symbol)
|
||||
quote_data = await redis_client.hgetall(quote_key)
|
||||
|
||||
if not quote_data:
|
||||
raise HTTPException(
|
||||
status_code=404, detail=f"未找到股票 {symbol} 的行情数据"
|
||||
)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": quote_data,
|
||||
}
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"获取行情失败: {symbol}, {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/quotes")
|
||||
async def get_quotes(
|
||||
symbols: str = Query(..., description="股票代码列表,逗号分隔"),
|
||||
) -> dict[str, Any]:
|
||||
"""批量获取股票实时行情
|
||||
|
||||
Args:
|
||||
symbols: 股票代码列表,逗号分隔,如 600000.SH,000001.SZ
|
||||
|
||||
Returns:
|
||||
行情数据列表
|
||||
"""
|
||||
symbol_list = [s.strip() for s in symbols.split(",") if s.strip()]
|
||||
|
||||
if not symbol_list:
|
||||
raise HTTPException(status_code=400, detail="请提供股票代码")
|
||||
|
||||
if len(symbol_list) > 100:
|
||||
raise HTTPException(status_code=400, detail="单次查询最多100个股票")
|
||||
|
||||
try:
|
||||
result = []
|
||||
for symbol in symbol_list:
|
||||
quote_key = RedisKeys.quote(symbol)
|
||||
quote_data = await redis_client.hgetall(quote_key)
|
||||
if quote_data:
|
||||
quote_data["symbol"] = symbol
|
||||
result.append(quote_data)
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": result,
|
||||
"count": len(result),
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"批量获取行情失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/snapshot")
|
||||
async def get_market_snapshot(
|
||||
market: Optional[str] = Query(None, description="市场代码: SH/SZ"),
|
||||
) -> dict[str, Any]:
|
||||
"""获取市场行情快照
|
||||
|
||||
Args:
|
||||
market: 市场代码,SH 上海,SZ 深圳,不传则获取全部
|
||||
|
||||
Returns:
|
||||
市场行情快照统计
|
||||
"""
|
||||
try:
|
||||
# 从 Redis 获取所有行情数据
|
||||
pattern = "quote:*"
|
||||
quotes = []
|
||||
|
||||
async for key in redis_client.scan_iter(match=pattern):
|
||||
quote_data = await redis_client.hgetall(key)
|
||||
if quote_data:
|
||||
symbol = key.split(":")[-1]
|
||||
# 过滤市场
|
||||
if market:
|
||||
if market.upper() == "SH" and not symbol.endswith(".SH"):
|
||||
continue
|
||||
if market.upper() == "SZ" and not symbol.endswith(".SZ"):
|
||||
continue
|
||||
quote_data["symbol"] = symbol
|
||||
quotes.append(quote_data)
|
||||
|
||||
# 统计信息
|
||||
up_count = 0
|
||||
down_count = 0
|
||||
flat_count = 0
|
||||
|
||||
for q in quotes:
|
||||
last = float(q.get("last_price", 0))
|
||||
pre_close = float(q.get("pre_close", 0))
|
||||
if pre_close > 0:
|
||||
if last > pre_close:
|
||||
up_count += 1
|
||||
elif last < pre_close:
|
||||
down_count += 1
|
||||
else:
|
||||
flat_count += 1
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"market": market or "ALL",
|
||||
"total": len(quotes),
|
||||
"up": up_count,
|
||||
"down": down_count,
|
||||
"flat": flat_count,
|
||||
"timestamp": datetime.now().isoformat(),
|
||||
},
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"获取市场快照失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/subscriptions")
|
||||
async def get_subscriptions() -> dict[str, Any]:
|
||||
"""获取当前订阅的股票列表"""
|
||||
try:
|
||||
# 从 Redis 获取订阅列表
|
||||
subscriptions = await redis_client.smembers("market:subscriptions")
|
||||
|
||||
return {
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"symbols": list(subscriptions) if subscriptions else [],
|
||||
"count": len(subscriptions) if subscriptions else 0,
|
||||
},
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"获取订阅列表失败: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
@ -1,7 +0,0 @@
|
||||
"""
|
||||
Data Service 服务模块
|
||||
"""
|
||||
|
||||
from . import market_receiver, kline_service, data_player
|
||||
|
||||
__all__ = ["market_receiver", "kline_service", "data_player"]
|
||||
@ -1,383 +0,0 @@
|
||||
"""
|
||||
回测数据回放服务
|
||||
|
||||
职责:
|
||||
- 从数据库加载历史数据
|
||||
- 按时间顺序模拟推送行情
|
||||
- 支持暂停、恢复、调速
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from typing import Optional
|
||||
from datetime import datetime as dt
|
||||
from enum import Enum
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.database import db
|
||||
from src.core.redis_client import redis_client, RedisChannels
|
||||
|
||||
logger = get_logger("data_service.data_player")
|
||||
|
||||
|
||||
class PlaybackStatus(str, Enum):
|
||||
"""回放状态"""
|
||||
|
||||
STOPPED = "stopped"
|
||||
PLAYING = "playing"
|
||||
PAUSED = "paused"
|
||||
|
||||
|
||||
class DataPlayer:
|
||||
"""
|
||||
数据回放器
|
||||
|
||||
从数据库加载历史K线数据,按时间顺序模拟推送,
|
||||
用于策略回测
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._status = PlaybackStatus.STOPPED
|
||||
self._task: Optional[asyncio.Task] = None
|
||||
|
||||
# 回放配置
|
||||
self._symbols: list[str] = []
|
||||
self._start_date: Optional[dt] = None
|
||||
self._end_date: Optional[dt] = None
|
||||
self._period: str = "1m"
|
||||
self._speed: float = 1.0
|
||||
|
||||
# 回放状态
|
||||
self._current_time: Optional[dt] = None
|
||||
self._progress: float = 0.0
|
||||
self._total_bars: int = 0
|
||||
self._played_bars: int = 0
|
||||
|
||||
# 暂停事件
|
||||
self._pause_event = asyncio.Event()
|
||||
self._pause_event.set() # 初始非暂停
|
||||
|
||||
@property
|
||||
def status(self) -> PlaybackStatus:
|
||||
"""回放状态"""
|
||||
return self._status
|
||||
|
||||
@property
|
||||
def progress(self) -> float:
|
||||
"""回放进度 0-100"""
|
||||
return self._progress
|
||||
|
||||
@property
|
||||
def current_time(self) -> Optional[str]:
|
||||
"""当前回放时间"""
|
||||
return self._current_time.isoformat() if self._current_time else None
|
||||
|
||||
@property
|
||||
def config(self) -> dict:
|
||||
"""回放配置"""
|
||||
return {
|
||||
"symbols": self._symbols,
|
||||
"start_date": self._start_date.strftime("%Y-%m-%d")
|
||||
if self._start_date
|
||||
else None,
|
||||
"end_date": self._end_date.strftime("%Y-%m-%d") if self._end_date else None,
|
||||
"period": self._period,
|
||||
"speed": self._speed,
|
||||
}
|
||||
|
||||
@property
|
||||
def state(self) -> dict:
|
||||
"""完整状态"""
|
||||
return {
|
||||
"status": self._status.value,
|
||||
"current_time": self.current_time,
|
||||
"progress": self._progress,
|
||||
"total_bars": self._total_bars,
|
||||
"played_bars": self._played_bars,
|
||||
"config": self.config,
|
||||
}
|
||||
|
||||
async def start(
|
||||
self,
|
||||
symbols: list[str],
|
||||
start_date: str,
|
||||
end_date: str,
|
||||
period: str = "1m",
|
||||
speed: float = 1.0,
|
||||
) -> bool:
|
||||
"""
|
||||
启动数据回放
|
||||
|
||||
Args:
|
||||
symbols: 股票代码列表
|
||||
start_date: 开始日期 YYYY-MM-DD
|
||||
end_date: 结束日期 YYYY-MM-DD
|
||||
period: K线周期
|
||||
speed: 回放速度倍数
|
||||
|
||||
Returns:
|
||||
是否启动成功
|
||||
"""
|
||||
if self._status == PlaybackStatus.PLAYING:
|
||||
logger.warning("回放已在运行中")
|
||||
return False
|
||||
|
||||
try:
|
||||
self._symbols = symbols
|
||||
self._start_date = dt.strptime(start_date, "%Y-%m-%d")
|
||||
self._end_date = dt.strptime(end_date, "%Y-%m-%d")
|
||||
self._period = period
|
||||
self._speed = max(0.1, min(100.0, speed))
|
||||
|
||||
# 重置状态
|
||||
self._current_time = self._start_date
|
||||
self._progress = 0.0
|
||||
self._played_bars = 0
|
||||
|
||||
# 计算总K线数
|
||||
self._total_bars = await self._count_bars()
|
||||
|
||||
if self._total_bars == 0:
|
||||
logger.warning("未找到符合条件的K线数据")
|
||||
return False
|
||||
|
||||
# 启动回放任务
|
||||
self._status = PlaybackStatus.PLAYING
|
||||
self._pause_event.set()
|
||||
self._task = asyncio.create_task(self._run())
|
||||
|
||||
logger.info(
|
||||
f"回放已启动: {len(symbols)} 只股票, "
|
||||
f"{start_date} - {end_date}, "
|
||||
f"共 {self._total_bars} 根K线"
|
||||
)
|
||||
|
||||
# 发布回放开始事件
|
||||
await redis_client.publish(
|
||||
"backtest:event",
|
||||
{
|
||||
"event": "started",
|
||||
"config": self.config,
|
||||
"total_bars": self._total_bars,
|
||||
},
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"启动回放失败: {e}")
|
||||
return False
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""停止回放"""
|
||||
if self._status == PlaybackStatus.STOPPED:
|
||||
return
|
||||
|
||||
self._status = PlaybackStatus.STOPPED
|
||||
self._pause_event.set() # 解除暂停以便退出
|
||||
|
||||
if self._task:
|
||||
self._task.cancel()
|
||||
try:
|
||||
await self._task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
self._task = None
|
||||
|
||||
# 发布回放停止事件
|
||||
await redis_client.publish(
|
||||
"backtest:event",
|
||||
{
|
||||
"event": "stopped",
|
||||
"played_bars": self._played_bars,
|
||||
"progress": self._progress,
|
||||
},
|
||||
)
|
||||
|
||||
logger.info(f"回放已停止: 已播放 {self._played_bars}/{self._total_bars}")
|
||||
|
||||
async def pause(self) -> None:
|
||||
"""暂停回放"""
|
||||
if self._status != PlaybackStatus.PLAYING:
|
||||
return
|
||||
|
||||
self._status = PlaybackStatus.PAUSED
|
||||
self._pause_event.clear()
|
||||
|
||||
await redis_client.publish(
|
||||
"backtest:event", {"event": "paused", "current_time": self.current_time}
|
||||
)
|
||||
|
||||
logger.info(f"回放已暂停: {self.current_time}")
|
||||
|
||||
async def resume(self) -> None:
|
||||
"""恢复回放"""
|
||||
if self._status != PlaybackStatus.PAUSED:
|
||||
return
|
||||
|
||||
self._status = PlaybackStatus.PLAYING
|
||||
self._pause_event.set()
|
||||
|
||||
await redis_client.publish(
|
||||
"backtest:event", {"event": "resumed", "current_time": self.current_time}
|
||||
)
|
||||
|
||||
logger.info("回放已恢复")
|
||||
|
||||
def set_speed(self, speed: float) -> None:
|
||||
"""设置回放速度"""
|
||||
self._speed = max(0.1, min(100.0, speed))
|
||||
logger.info(f"回放速度已设置为 {self._speed}x")
|
||||
|
||||
async def _count_bars(self) -> int:
|
||||
"""计算总K线数"""
|
||||
table_name = f"klines_{self._period}"
|
||||
placeholders = ",".join([f":symbol_{i}" for i in range(len(self._symbols))])
|
||||
|
||||
query = text(f"""
|
||||
SELECT COUNT(*)
|
||||
FROM {table_name}
|
||||
WHERE symbol IN ({placeholders})
|
||||
AND timestamp >= :start_date
|
||||
AND timestamp <= :end_date
|
||||
""")
|
||||
|
||||
params: dict[str, object] = {
|
||||
"start_date": self._start_date,
|
||||
"end_date": self._end_date,
|
||||
}
|
||||
for i, symbol in enumerate(self._symbols):
|
||||
params[f"symbol_{i}"] = symbol
|
||||
|
||||
try:
|
||||
async with db.session() as session:
|
||||
result = await session.execute(query, params)
|
||||
row = result.fetchone()
|
||||
return row[0] if row else 0
|
||||
except Exception as e:
|
||||
logger.error(f"统计K线数失败: {e}")
|
||||
return 0
|
||||
|
||||
async def _run(self) -> None:
|
||||
"""运行回放循环"""
|
||||
table_name = f"klines_{self._period}"
|
||||
placeholders = ",".join([f":symbol_{i}" for i in range(len(self._symbols))])
|
||||
|
||||
query = text(f"""
|
||||
SELECT symbol, open, high, low, close, volume, amount, timestamp
|
||||
FROM {table_name}
|
||||
WHERE symbol IN ({placeholders})
|
||||
AND timestamp >= :start_date
|
||||
AND timestamp <= :end_date
|
||||
ORDER BY timestamp ASC
|
||||
""")
|
||||
|
||||
params: dict[str, object] = {
|
||||
"start_date": self._start_date,
|
||||
"end_date": self._end_date,
|
||||
}
|
||||
for i, symbol in enumerate(self._symbols):
|
||||
params[f"symbol_{i}"] = symbol
|
||||
|
||||
try:
|
||||
async with db.session() as session:
|
||||
result = await session.execute(query, params)
|
||||
rows = result.fetchall()
|
||||
|
||||
# 按时间戳分组
|
||||
bars_by_time: dict[dt, list[dict]] = {}
|
||||
for row in rows:
|
||||
timestamp = row[7]
|
||||
bar = {
|
||||
"symbol": row[0],
|
||||
"open": float(row[1]) if row[1] else 0,
|
||||
"high": float(row[2]) if row[2] else 0,
|
||||
"low": float(row[3]) if row[3] else 0,
|
||||
"close": float(row[4]) if row[4] else 0,
|
||||
"volume": int(row[5]) if row[5] else 0,
|
||||
"amount": float(row[6]) if row[6] else 0,
|
||||
"timestamp": timestamp.isoformat() if timestamp else None,
|
||||
"period": self._period,
|
||||
}
|
||||
|
||||
if timestamp not in bars_by_time:
|
||||
bars_by_time[timestamp] = []
|
||||
bars_by_time[timestamp].append(bar)
|
||||
|
||||
# 按时间顺序回放
|
||||
sorted_times = sorted(bars_by_time.keys())
|
||||
|
||||
# 计算时间间隔
|
||||
interval_map = {
|
||||
"1m": 60,
|
||||
"5m": 300,
|
||||
"15m": 900,
|
||||
"30m": 1800,
|
||||
"60m": 3600,
|
||||
"1d": 86400,
|
||||
"1w": 604800,
|
||||
}
|
||||
base_interval = interval_map.get(self._period, 60)
|
||||
|
||||
for i, timestamp in enumerate(sorted_times):
|
||||
# 检查是否停止
|
||||
if self._status == PlaybackStatus.STOPPED:
|
||||
break
|
||||
|
||||
# 等待暂停解除
|
||||
await self._pause_event.wait()
|
||||
|
||||
# 更新当前时间
|
||||
self._current_time = timestamp
|
||||
self._played_bars = i + 1
|
||||
self._progress = (self._played_bars / self._total_bars) * 100
|
||||
|
||||
# 发布K线数据
|
||||
for bar in bars_by_time[timestamp]:
|
||||
await redis_client.publish(RedisChannels.MARKET_KLINE, bar)
|
||||
|
||||
# 同时发布模拟行情
|
||||
quote = {
|
||||
"symbol": bar["symbol"],
|
||||
"last_price": bar["close"],
|
||||
"open_price": bar["open"],
|
||||
"high_price": bar["high"],
|
||||
"low_price": bar["low"],
|
||||
"volume": bar["volume"],
|
||||
"amount": bar["amount"],
|
||||
"timestamp": bar["timestamp"],
|
||||
"source": "backtest",
|
||||
}
|
||||
await redis_client.publish(RedisChannels.MARKET_QUOTE, quote)
|
||||
|
||||
# 按速度延迟
|
||||
delay = base_interval / self._speed
|
||||
# 限制最小延迟,避免过快
|
||||
delay = max(0.001, min(delay, 1.0))
|
||||
await asyncio.sleep(delay)
|
||||
|
||||
# 回放完成
|
||||
if self._status == PlaybackStatus.PLAYING:
|
||||
self._status = PlaybackStatus.STOPPED
|
||||
self._progress = 100.0
|
||||
|
||||
await redis_client.publish(
|
||||
"backtest:event",
|
||||
{
|
||||
"event": "completed",
|
||||
"total_bars": self._total_bars,
|
||||
},
|
||||
)
|
||||
|
||||
logger.info("回放完成")
|
||||
|
||||
except asyncio.CancelledError:
|
||||
logger.info("回放被取消")
|
||||
except Exception as e:
|
||||
logger.error(f"回放异常: {e}", exc_info=True)
|
||||
self._status = PlaybackStatus.STOPPED
|
||||
|
||||
|
||||
# 全局单例
|
||||
data_player = DataPlayer()
|
||||
@ -1,272 +0,0 @@
|
||||
"""
|
||||
K线存储与查询服务
|
||||
|
||||
职责:
|
||||
- K线数据持久化存储
|
||||
- K线数据查询
|
||||
- K线周期聚合
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from typing import Any, Optional
|
||||
from datetime import datetime as dt, timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.dialects.mysql import insert as mysql_insert
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.database import db
|
||||
from src.core.redis_client import redis_client, RedisChannels
|
||||
from src.core.models import (
|
||||
Kline1m,
|
||||
Kline5m,
|
||||
Kline15m,
|
||||
Kline30m,
|
||||
Kline60m,
|
||||
Kline1d,
|
||||
)
|
||||
|
||||
logger = get_logger("data_service.kline_service")
|
||||
|
||||
|
||||
# K线周期配置
|
||||
KLINE_PERIODS = {
|
||||
"1m": {"model": Kline1m, "interval": timedelta(minutes=1)},
|
||||
"5m": {"model": Kline5m, "interval": timedelta(minutes=5)},
|
||||
"15m": {"model": Kline15m, "interval": timedelta(minutes=15)},
|
||||
"30m": {"model": Kline30m, "interval": timedelta(minutes=30)},
|
||||
"60m": {"model": Kline60m, "interval": timedelta(minutes=60)},
|
||||
"1d": {"model": Kline1d, "interval": timedelta(days=1)},
|
||||
}
|
||||
|
||||
|
||||
class KlineService:
|
||||
"""
|
||||
K线服务
|
||||
|
||||
提供K线数据的存储、查询、聚合功能
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._running = False
|
||||
self._task: Optional[asyncio.Task] = None
|
||||
self._pending_klines: list[dict] = []
|
||||
self._batch_size = 100
|
||||
self._flush_interval = 5.0 # 秒
|
||||
self._save_count = 0
|
||||
|
||||
async def start(self) -> None:
|
||||
"""启动K线服务"""
|
||||
if self._running:
|
||||
logger.warning("K线服务已在运行")
|
||||
return
|
||||
|
||||
self._running = True
|
||||
self._task = asyncio.create_task(self._run())
|
||||
logger.info("K线服务已启动")
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""停止K线服务"""
|
||||
self._running = False
|
||||
|
||||
# 刷新剩余数据
|
||||
if self._pending_klines:
|
||||
await self._flush_klines()
|
||||
|
||||
if self._task:
|
||||
self._task.cancel()
|
||||
try:
|
||||
await self._task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
self._task = None
|
||||
|
||||
logger.info(f"K线服务已停止 (保存K线: {self._save_count})")
|
||||
|
||||
async def _run(self) -> None:
|
||||
"""运行K线接收循环"""
|
||||
try:
|
||||
pubsub = redis_client.client.pubsub()
|
||||
await pubsub.subscribe(RedisChannels.MARKET_KLINE)
|
||||
logger.info(f"已订阅K线频道: {RedisChannels.MARKET_KLINE}")
|
||||
|
||||
last_flush = dt.now()
|
||||
|
||||
while self._running:
|
||||
try:
|
||||
message = await asyncio.wait_for(
|
||||
pubsub.get_message(ignore_subscribe_messages=True, timeout=1.0),
|
||||
timeout=2.0,
|
||||
)
|
||||
|
||||
if message and message["type"] == "message":
|
||||
import json
|
||||
|
||||
data = message["data"]
|
||||
if isinstance(data, bytes):
|
||||
data = json.loads(data.decode("utf-8"))
|
||||
elif isinstance(data, str):
|
||||
data = json.loads(data)
|
||||
|
||||
await self._process_kline(data)
|
||||
|
||||
# 定时刷新
|
||||
if (dt.now() - last_flush).total_seconds() >= self._flush_interval:
|
||||
if self._pending_klines:
|
||||
await self._flush_klines()
|
||||
last_flush = dt.now()
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
# 超时检查是否需要刷新
|
||||
if (dt.now() - last_flush).total_seconds() >= self._flush_interval:
|
||||
if self._pending_klines:
|
||||
await self._flush_klines()
|
||||
last_flush = dt.now()
|
||||
except Exception as e:
|
||||
logger.error(f"K线处理异常: {e}")
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
await pubsub.unsubscribe(RedisChannels.MARKET_KLINE)
|
||||
await pubsub.close()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"K线服务异常: {e}", exc_info=True)
|
||||
|
||||
async def _process_kline(self, data: dict) -> None:
|
||||
"""处理单条K线数据"""
|
||||
self._pending_klines.append(data)
|
||||
|
||||
# 达到批量大小则刷新
|
||||
if len(self._pending_klines) >= self._batch_size:
|
||||
await self._flush_klines()
|
||||
|
||||
async def _flush_klines(self) -> None:
|
||||
"""批量保存K线数据"""
|
||||
if not self._pending_klines:
|
||||
return
|
||||
|
||||
klines = self._pending_klines
|
||||
self._pending_klines = []
|
||||
|
||||
# 按周期分组
|
||||
klines_by_period: dict[str, list] = {}
|
||||
for kline in klines:
|
||||
period = kline.get("period", "1m")
|
||||
if period not in klines_by_period:
|
||||
klines_by_period[period] = []
|
||||
klines_by_period[period].append(kline)
|
||||
|
||||
# 分表保存
|
||||
for period, period_klines in klines_by_period.items():
|
||||
await self._save_klines(period, period_klines)
|
||||
|
||||
self._save_count += len(klines)
|
||||
logger.debug(f"已保存 {len(klines)} 条K线数据")
|
||||
|
||||
async def _save_klines(self, period: str, klines: list[dict]) -> None:
|
||||
"""保存指定周期的K线数据"""
|
||||
config = KLINE_PERIODS.get(period)
|
||||
if not config:
|
||||
logger.warning(f"未知K线周期: {period}")
|
||||
return
|
||||
|
||||
model = config["model"]
|
||||
|
||||
try:
|
||||
async with db.session() as session:
|
||||
for kline in klines:
|
||||
# 使用 MySQL 的 INSERT ... ON DUPLICATE KEY UPDATE
|
||||
stmt = mysql_insert(model).values(
|
||||
symbol=kline.get("symbol"),
|
||||
time=kline.get("timestamp"),
|
||||
open=Decimal(str(kline.get("open", 0))),
|
||||
high=Decimal(str(kline.get("high", 0))),
|
||||
low=Decimal(str(kline.get("low", 0))),
|
||||
close=Decimal(str(kline.get("close", 0))),
|
||||
volume=kline.get("volume", 0),
|
||||
amount=Decimal(str(kline.get("amount", 0))),
|
||||
)
|
||||
stmt = stmt.on_duplicate_key_update(
|
||||
open=stmt.inserted.open,
|
||||
high=stmt.inserted.high,
|
||||
low=stmt.inserted.low,
|
||||
close=stmt.inserted.close,
|
||||
volume=stmt.inserted.volume,
|
||||
amount=stmt.inserted.amount,
|
||||
)
|
||||
await session.execute(stmt)
|
||||
await session.commit()
|
||||
except Exception as e:
|
||||
logger.error(f"保存K线失败: {e}")
|
||||
|
||||
async def get_klines(
|
||||
self,
|
||||
symbol: str,
|
||||
period: str = "1d",
|
||||
start_time: Optional[dt] = None,
|
||||
end_time: Optional[dt] = None,
|
||||
limit: int = 100,
|
||||
) -> list[dict]:
|
||||
"""
|
||||
查询K线数据
|
||||
|
||||
Args:
|
||||
symbol: 股票代码
|
||||
period: K线周期
|
||||
start_time: 开始时间
|
||||
end_time: 结束时间
|
||||
limit: 返回数量
|
||||
|
||||
Returns:
|
||||
K线数据列表
|
||||
"""
|
||||
config = KLINE_PERIODS.get(period)
|
||||
if not config:
|
||||
return []
|
||||
|
||||
model = config["model"]
|
||||
|
||||
try:
|
||||
async with db.session() as session:
|
||||
# 构建查询
|
||||
stmt = select(model).where(model.symbol == symbol)
|
||||
|
||||
if start_time:
|
||||
stmt = stmt.where(model.time >= start_time)
|
||||
if end_time:
|
||||
stmt = stmt.where(model.time <= end_time)
|
||||
|
||||
stmt = stmt.order_by(model.time.desc()).limit(limit)
|
||||
|
||||
result = await session.execute(stmt)
|
||||
rows = result.scalars().all()
|
||||
|
||||
# 返回时间正序
|
||||
return [kline.to_dict() for kline in reversed(rows)]
|
||||
except Exception as e:
|
||||
logger.error(f"查询K线失败: {e}")
|
||||
return []
|
||||
|
||||
async def get_latest_kline(self, symbol: str, period: str = "1d") -> Optional[dict]:
|
||||
"""获取最新K线"""
|
||||
klines = await self.get_klines(symbol, period, limit=1)
|
||||
return klines[0] if klines else None
|
||||
|
||||
@property
|
||||
def is_running(self) -> bool:
|
||||
"""是否在运行"""
|
||||
return self._running
|
||||
|
||||
@property
|
||||
def stats(self) -> dict:
|
||||
"""统计信息"""
|
||||
return {
|
||||
"running": self._running,
|
||||
"pending_count": len(self._pending_klines),
|
||||
"save_count": self._save_count,
|
||||
}
|
||||
|
||||
|
||||
# 全局单例
|
||||
kline_service = KlineService()
|
||||
@ -1,199 +0,0 @@
|
||||
"""
|
||||
行情接收与分发服务
|
||||
|
||||
职责:
|
||||
- 订阅 Redis 行情频道,接收 QMT Adapter 推送的行情数据
|
||||
- 将行情数据缓存到 Redis
|
||||
- 转发行情到策略引擎
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from typing import Any, Callable, Optional
|
||||
from datetime import datetime as dt
|
||||
|
||||
from src.core.logger import get_logger
|
||||
from src.core.redis_client import redis_client, RedisChannels, RedisKeys
|
||||
|
||||
logger = get_logger("data_service.market_receiver")
|
||||
|
||||
|
||||
class MarketReceiver:
|
||||
"""
|
||||
行情接收器
|
||||
|
||||
接收 QMT Adapter 推送的行情数据,缓存到 Redis,
|
||||
并转发到策略引擎
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._running = False
|
||||
self._task: Optional[asyncio.Task] = None
|
||||
self._handlers: list[Callable[[dict], Any]] = []
|
||||
self._quote_count = 0
|
||||
self._kline_count = 0
|
||||
|
||||
async def start(self) -> None:
|
||||
"""启动行情接收"""
|
||||
if self._running:
|
||||
logger.warning("行情接收器已在运行")
|
||||
return
|
||||
|
||||
self._running = True
|
||||
self._task = asyncio.create_task(self._run())
|
||||
logger.info("行情接收器已启动")
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""停止行情接收"""
|
||||
self._running = False
|
||||
|
||||
if self._task:
|
||||
self._task.cancel()
|
||||
try:
|
||||
await self._task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
self._task = None
|
||||
|
||||
logger.info(
|
||||
f"行情接收器已停止 (处理行情: {self._quote_count}, K线: {self._kline_count})"
|
||||
)
|
||||
|
||||
def add_handler(self, handler: Callable[[dict], Any]) -> None:
|
||||
"""添加行情处理器"""
|
||||
self._handlers.append(handler)
|
||||
|
||||
def remove_handler(self, handler: Callable[[dict], Any]) -> None:
|
||||
"""移除行情处理器"""
|
||||
if handler in self._handlers:
|
||||
self._handlers.remove(handler)
|
||||
|
||||
async def _run(self) -> None:
|
||||
"""运行行情接收循环"""
|
||||
channels = [
|
||||
RedisChannels.MARKET_QUOTE,
|
||||
RedisChannels.MARKET_KLINE,
|
||||
]
|
||||
|
||||
try:
|
||||
pubsub = redis_client.client.pubsub()
|
||||
await pubsub.subscribe(*channels)
|
||||
logger.info(f"已订阅频道: {channels}")
|
||||
|
||||
while self._running:
|
||||
try:
|
||||
message = await asyncio.wait_for(
|
||||
pubsub.get_message(ignore_subscribe_messages=True, timeout=1.0),
|
||||
timeout=2.0,
|
||||
)
|
||||
|
||||
if message is None:
|
||||
continue
|
||||
|
||||
if message["type"] == "message":
|
||||
channel = message["channel"]
|
||||
if isinstance(channel, bytes):
|
||||
channel = channel.decode("utf-8")
|
||||
|
||||
data = message["data"]
|
||||
if isinstance(data, bytes):
|
||||
data = json.loads(data.decode("utf-8"))
|
||||
elif isinstance(data, str):
|
||||
data = json.loads(data)
|
||||
|
||||
# 根据频道处理不同类型的数据
|
||||
if channel == RedisChannels.MARKET_QUOTE:
|
||||
await self._handle_quote(data)
|
||||
elif channel == RedisChannels.MARKET_KLINE:
|
||||
await self._handle_kline(data)
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
except json.JSONDecodeError as e:
|
||||
logger.warning(f"行情数据解析失败: {e}")
|
||||
except Exception as e:
|
||||
logger.error(f"行情处理异常: {e}")
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
await pubsub.unsubscribe(*channels)
|
||||
await pubsub.close()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"行情接收器异常: {e}", exc_info=True)
|
||||
|
||||
async def _handle_quote(self, data: dict) -> None:
|
||||
"""
|
||||
处理实时行情数据
|
||||
|
||||
Args:
|
||||
data: 行情数据,包含 symbol, last_price, volume 等
|
||||
"""
|
||||
symbol = data.get("symbol")
|
||||
if not symbol:
|
||||
return
|
||||
|
||||
self._quote_count += 1
|
||||
|
||||
# 添加接收时间戳
|
||||
data["receive_time"] = dt.now().isoformat()
|
||||
|
||||
# 缓存到 Redis
|
||||
quote_key = RedisKeys.quote(symbol)
|
||||
await redis_client.hmset(quote_key, data)
|
||||
await redis_client.expire(quote_key, 300) # 5分钟过期
|
||||
|
||||
# 调用注册的处理器
|
||||
for handler in self._handlers:
|
||||
try:
|
||||
result = handler(data)
|
||||
if asyncio.iscoroutine(result):
|
||||
await result
|
||||
except Exception as e:
|
||||
logger.error(f"行情处理器异常: {e}")
|
||||
|
||||
# 转发到策略引擎
|
||||
await redis_client.publish(RedisChannels.STRATEGY_QUOTE, data)
|
||||
|
||||
if self._quote_count % 100 == 0:
|
||||
logger.debug(f"已处理 {self._quote_count} 条行情数据")
|
||||
|
||||
async def _handle_kline(self, data: dict) -> None:
|
||||
"""
|
||||
处理K线数据
|
||||
|
||||
Args:
|
||||
data: K线数据,包含 symbol, period, open, high, low, close 等
|
||||
"""
|
||||
symbol = data.get("symbol")
|
||||
period = data.get("period", "1m")
|
||||
|
||||
if not symbol:
|
||||
return
|
||||
|
||||
self._kline_count += 1
|
||||
|
||||
# 缓存最新K线到 Redis
|
||||
kline_key = f"kline:{period}:{symbol}"
|
||||
await redis_client.hmset(kline_key, data)
|
||||
await redis_client.expire(kline_key, 3600) # 1小时过期
|
||||
|
||||
# 转发到策略引擎
|
||||
await redis_client.publish(RedisChannels.STRATEGY_KLINE, data)
|
||||
|
||||
@property
|
||||
def is_running(self) -> bool:
|
||||
"""是否在运行"""
|
||||
return self._running
|
||||
|
||||
@property
|
||||
def stats(self) -> dict:
|
||||
"""统计信息"""
|
||||
return {
|
||||
"running": self._running,
|
||||
"quote_count": self._quote_count,
|
||||
"kline_count": self._kline_count,
|
||||
}
|
||||
|
||||
|
||||
# 全局单例
|
||||
market_receiver = MarketReceiver()
|
||||
@ -1,9 +0,0 @@
|
||||
"""
|
||||
Database Service
|
||||
|
||||
数据库管理服务模块
|
||||
"""
|
||||
|
||||
from .app import app
|
||||
|
||||
__all__ = ["app"]
|
||||
@ -1,74 +0,0 @@
|
||||
"""
|
||||
Database Service FastAPI 应用
|
||||
|
||||
数据库管理服务,提供:
|
||||
- 数据库管理:创建、删除、查询
|
||||
- 表管理:创建、删除、清空
|
||||
- 数据准备:生成测试K线数据
|
||||
"""
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from src.core.logger import get_logger
|
||||
|
||||
from .routes import databases_router, tables_router, environments_router
|
||||
|
||||
logger = get_logger("database_admin_service")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""应用生命周期管理"""
|
||||
logger.info("数据库管理服务启动...")
|
||||
logger.info("提供数据库和表的管理功能(DBA级别)")
|
||||
|
||||
yield
|
||||
|
||||
logger.info("数据库管理服务关闭...")
|
||||
|
||||
|
||||
# 创建应用
|
||||
app = FastAPI(
|
||||
title="QTrade 数据库管理服务",
|
||||
description="提供数据库和表的管理功能(DBA级别操作)",
|
||||
version="1.0.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
# CORS
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# 注册路由
|
||||
app.include_router(databases_router, prefix="/api")
|
||||
app.include_router(tables_router, prefix="/api")
|
||||
app.include_router(environments_router, prefix="/api")
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
"""服务根路径"""
|
||||
return {
|
||||
"service": "QTrade Database Admin Service",
|
||||
"version": "1.0.0",
|
||||
"status": "running",
|
||||
"description": "数据库管理服务(DBA级别操作)",
|
||||
"endpoints": {
|
||||
"databases": "/api/databases",
|
||||
"tables": "/api/tables",
|
||||
"environments": "/api/environments",
|
||||
"docs": "/docs",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
"""健康检查"""
|
||||
return {"status": "healthy", "service": "database_admin_service"}
|
||||
@ -1,9 +0,0 @@
|
||||
"""
|
||||
Routes 模块
|
||||
"""
|
||||
|
||||
from .databases import router as databases_router
|
||||
from .tables import router as tables_router
|
||||
from .environments import router as environments_router
|
||||
|
||||
__all__ = ["databases_router", "tables_router", "environments_router"]
|
||||
@ -1,74 +0,0 @@
|
||||
"""
|
||||
数据库管理 API 路由
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from src.core.logger import get_logger
|
||||
from ..schemas import (
|
||||
DatabaseListResponse,
|
||||
DatabaseInfo,
|
||||
CreateDatabaseRequest,
|
||||
MessageResponse,
|
||||
)
|
||||
from ..services import db_admin
|
||||
|
||||
logger = get_logger("database_admin_service.routes.databases")
|
||||
|
||||
router = APIRouter(prefix="/databases", tags=["数据库管理"])
|
||||
|
||||
|
||||
@router.get("", response_model=DatabaseListResponse, summary="列出所有数据库")
|
||||
async def list_databases():
|
||||
"""列出所有QTrade数据库及其信息"""
|
||||
try:
|
||||
databases = db_admin.list_databases()
|
||||
return DatabaseListResponse(
|
||||
databases=[DatabaseInfo(**db) for db in databases],
|
||||
total=len(databases),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"列出数据库失败: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/{environment}", response_model=DatabaseInfo, summary="获取数据库信息")
|
||||
async def get_database_info(environment: str):
|
||||
"""获取指定环境数据库的详细信息"""
|
||||
try:
|
||||
db_info = db_admin.get_database_info(environment)
|
||||
return DatabaseInfo(**db_info)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"获取数据库信息失败: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("", response_model=MessageResponse, summary="创建数据库")
|
||||
async def create_database(request: CreateDatabaseRequest):
|
||||
"""创建指定环境的数据库"""
|
||||
try:
|
||||
result = db_admin.create_database(request.environment)
|
||||
return MessageResponse(message=result["message"], success=True)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"创建数据库失败: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/{environment}", response_model=MessageResponse, summary="删除数据库")
|
||||
async def drop_database(environment: str):
|
||||
"""
|
||||
删除指定环境的数据库
|
||||
|
||||
⚠️ 警告:此操作将删除整个数据库及其所有数据,不可恢复!
|
||||
"""
|
||||
try:
|
||||
result = db_admin.drop_database(environment)
|
||||
return MessageResponse(message=result["message"], success=True)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"删除数据库失败: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
@ -1,56 +0,0 @@
|
||||
"""
|
||||
环境初始化 API 路由
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from src.core.logger import get_logger
|
||||
from ..services import env_initializer
|
||||
|
||||
logger = get_logger("database_admin_service.routes.environments")
|
||||
|
||||
router = APIRouter(prefix="/environments", tags=["环境管理"])
|
||||
|
||||
|
||||
class InitializeResponse(BaseModel):
|
||||
"""环境初始化响应"""
|
||||
|
||||
success: bool
|
||||
message: str
|
||||
environment: str
|
||||
details: dict
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{environment}/initialize",
|
||||
response_model=InitializeResponse,
|
||||
summary="初始化环境",
|
||||
)
|
||||
async def initialize_environment(environment: str):
|
||||
"""
|
||||
初始化指定环境的数据库和表结构
|
||||
|
||||
这是一个一键初始化接口,会自动完成:
|
||||
1. 检查数据库是否存在,不存在则创建
|
||||
2. 检查表结构是否完整,不完整则创建
|
||||
|
||||
支持的环境:
|
||||
- production: 实盘环境
|
||||
- backtest: 回测环境
|
||||
- simulation: 模拟环境
|
||||
"""
|
||||
try:
|
||||
result = await env_initializer.initialize_environment(environment)
|
||||
|
||||
return InitializeResponse(
|
||||
success=True,
|
||||
message=f"环境 '{environment}' 初始化完成",
|
||||
environment=environment,
|
||||
details=result,
|
||||
)
|
||||
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"环境初始化失败: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
@ -1,116 +0,0 @@
|
||||
"""
|
||||
表管理 API 路由
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from src.core.logger import get_logger
|
||||
from ..schemas import (
|
||||
TableListResponse,
|
||||
TableInfo,
|
||||
CreateTablesRequest,
|
||||
MessageResponse,
|
||||
)
|
||||
from ..services import table_manager
|
||||
|
||||
logger = get_logger("database_admin_service.routes.tables")
|
||||
|
||||
router = APIRouter(prefix="/tables", tags=["表管理"])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{environment}", response_model=TableListResponse, summary="列出数据库的所有表"
|
||||
)
|
||||
async def list_tables(environment: str):
|
||||
"""列出指定环境数据库中的所有表"""
|
||||
try:
|
||||
tables = table_manager.list_tables(environment)
|
||||
# 获取数据库名称
|
||||
from ..services.db_manager import ENV_DATABASES
|
||||
|
||||
db_name = ENV_DATABASES.get(environment, "unknown")
|
||||
|
||||
return TableListResponse(
|
||||
database=db_name, tables=[TableInfo(**t) for t in tables], total=len(tables)
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"列出表失败: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("", response_model=MessageResponse, summary="创建表结构")
|
||||
async def create_tables(request: CreateTablesRequest):
|
||||
"""
|
||||
为指定环境创建表结构
|
||||
|
||||
这将使用ORM模型定义创建所有表
|
||||
"""
|
||||
try:
|
||||
result = await table_manager.create_tables(request.environment)
|
||||
return MessageResponse(
|
||||
message=f"{result['message']} - {', '.join(result['tables'][:5])}{'...' if len(result['tables']) > 5 else ''}",
|
||||
success=True,
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"创建表失败: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/{environment}", response_model=MessageResponse, summary="删除所有表")
|
||||
async def drop_all_tables(environment: str):
|
||||
"""
|
||||
删除指定环境数据库中的所有表
|
||||
|
||||
⚠️ 警告:此操作将删除所有表结构和数据,不可恢复!
|
||||
"""
|
||||
try:
|
||||
result = table_manager.drop_all_tables(environment)
|
||||
return MessageResponse(message=result["message"], success=True)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"删除所有表失败: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{environment}/{table_name}", response_model=MessageResponse, summary="删除指定表"
|
||||
)
|
||||
async def drop_table(environment: str, table_name: str):
|
||||
"""
|
||||
删除指定环境数据库中的指定表
|
||||
|
||||
⚠️ 警告:此操作将删除表结构和数据,不可恢复!
|
||||
"""
|
||||
try:
|
||||
result = table_manager.drop_table(environment, table_name)
|
||||
return MessageResponse(message=result["message"], success=True)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"删除表失败: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{environment}/{table_name}/truncate",
|
||||
response_model=MessageResponse,
|
||||
summary="清空表数据",
|
||||
)
|
||||
async def truncate_table(environment: str, table_name: str):
|
||||
"""
|
||||
清空指定表的数据(保留表结构)
|
||||
|
||||
⚠️ 警告:此操作将清空表中所有数据,不可恢复!
|
||||
"""
|
||||
try:
|
||||
result = table_manager.truncate_table(environment, table_name)
|
||||
return MessageResponse(message=result["message"], success=True)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception as e:
|
||||
logger.error(f"清空表失败: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
@ -1,117 +0,0 @@
|
||||
"""
|
||||
数据模型定义
|
||||
"""
|
||||
|
||||
from typing import List, Optional
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
# ========== 通用响应 ==========
|
||||
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
"""通用消息响应"""
|
||||
|
||||
message: str
|
||||
success: bool = True
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
"""错误响应"""
|
||||
|
||||
error: str
|
||||
detail: Optional[str] = None
|
||||
success: bool = False
|
||||
|
||||
|
||||
# ========== 数据库相关 ==========
|
||||
|
||||
|
||||
class DatabaseInfo(BaseModel):
|
||||
"""数据库信息"""
|
||||
|
||||
name: str
|
||||
environment: str = "unknown"
|
||||
size_mb: Optional[float] = None
|
||||
table_count: Optional[int] = None
|
||||
|
||||
|
||||
class DatabaseListResponse(BaseModel):
|
||||
"""数据库列表响应"""
|
||||
|
||||
databases: List[DatabaseInfo]
|
||||
total: int
|
||||
|
||||
|
||||
class CreateDatabaseRequest(BaseModel):
|
||||
"""创建数据库请求"""
|
||||
|
||||
environment: str = Field(
|
||||
..., description="环境类型: production/backtest/simulation"
|
||||
)
|
||||
|
||||
|
||||
# ========== 表相关 ==========
|
||||
|
||||
|
||||
class TableInfo(BaseModel):
|
||||
"""表信息"""
|
||||
|
||||
name: str
|
||||
rows: Optional[int] = None
|
||||
size_mb: Optional[float] = None
|
||||
engine: Optional[str] = None
|
||||
|
||||
|
||||
class TableListResponse(BaseModel):
|
||||
"""表列表响应"""
|
||||
|
||||
database: str
|
||||
tables: List[TableInfo]
|
||||
total: int
|
||||
|
||||
|
||||
class CreateTablesRequest(BaseModel):
|
||||
"""创建表请求"""
|
||||
|
||||
environment: str = Field(..., description="环境类型")
|
||||
tables: Optional[List[str]] = Field(
|
||||
None, description="指定表名列表,为空则创建所有表"
|
||||
)
|
||||
|
||||
|
||||
# ========== 数据准备相关 ==========
|
||||
|
||||
|
||||
class PrepareDataRequest(BaseModel):
|
||||
"""准备测试数据请求"""
|
||||
|
||||
environment: str = Field(..., description="环境类型")
|
||||
symbols: List[str] = Field(
|
||||
default=["000001.SZ", "600000.SH"], description="股票代码列表"
|
||||
)
|
||||
period: str = Field(default="1d", description="K线周期")
|
||||
days: int = Field(default=60, ge=1, le=365, description="生成天数")
|
||||
|
||||
|
||||
class PrepareDataResponse(BaseModel):
|
||||
"""准备测试数据响应"""
|
||||
|
||||
environment: str
|
||||
generated_count: int
|
||||
symbols: List[str]
|
||||
message: str
|
||||
success: bool = True
|
||||
|
||||
|
||||
# ========== 数据库操作 ==========
|
||||
|
||||
|
||||
class DatabaseOperation(BaseModel):
|
||||
"""数据库操作"""
|
||||
|
||||
operation: str = Field(
|
||||
..., description="操作类型: drop_db/clean_tables/drop_table/truncate"
|
||||
)
|
||||
environment: str = Field(..., description="环境类型")
|
||||
table_name: Optional[str] = Field(None, description="表名(某些操作需要)")
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user