feat: 添加 PyQt6 桌面控制台
- 新增控制台应用入口 (src/console/main.py) - 新增主窗口 (main_window.py) - 新增 5 个功能页面: - dashboard_page.py: 仪表盘 - services_page.py: 服务管理 - strategies_page.py: 策略配置 - settings_page.py: 系统设置 - logs_page.py: 运行日志 - 更新 README.md 文档 - 更新 ARCHITECTURE.md 架构文档 - 更新 BUILD_PLAN.md 构建方案
This commit is contained in:
parent
085427959c
commit
16b468c17d
359
README.md
359
README.md
@ -1,45 +1,61 @@
|
|||||||
# QTrade - 量化交易系统 (v2.0)
|
# QTrade - A股量化交易系统
|
||||||
|
|
||||||
轻量级 A 股量化交易系统,基于微服务架构。
|
轻量级 A股量化交易系统,基于 Python 微服务架构。
|
||||||
|
|
||||||
> ⚠️ **重构中**: 系统正在从单体架构重构为微服务架构
|
## ✨ 特性
|
||||||
|
|
||||||
## 特性
|
|
||||||
|
|
||||||
- 🚀 **微服务架构**: FastAPI + Redis + MySQL
|
- 🚀 **微服务架构**: FastAPI + Redis + MySQL
|
||||||
- 📊 **实时行情**: 通过 QMT 获取实时行情数据
|
- 📊 **实时行情**: 通过 QMT 获取 A股实时行情数据
|
||||||
- 🤖 **策略引擎**: 支持多策略并行运行
|
- 🤖 **策略引擎**: 支持多策略并行运行 (网格/均线/双均线)
|
||||||
- 💹 **股票-策略配对**: 每个配对独立管理持仓和资金
|
- 💹 **股票-策略配对**: 每个配对独立管理持仓和资金
|
||||||
- 🔄 **回测支持**: 回测与实盘使用相同代码
|
- 🔄 **回测支持**: 回测与实盘使用相同代码
|
||||||
|
- 🖥️ **桌面控制台**: PyQt6 可视化管理界面
|
||||||
- 🐧 **跨平台**: 支持 Linux 和 Windows
|
- 🐧 **跨平台**: 支持 Linux 和 Windows
|
||||||
|
|
||||||
## 架构
|
## 🏗️ 架构
|
||||||
|
|
||||||
```
|
```
|
||||||
┌─────────────┐
|
┌─────────────────────────────────────────────────────────────────┐
|
||||||
│ Gateway │ ← 外部 API 入口 (8001)
|
│ PyQt6 Console (桌面控制台) │
|
||||||
└──────┬──────┘
|
│ 服务管理 | 策略配置 | 系统设置 | 日志查看 │
|
||||||
|
└─────────────────────────────────────────────────────────────────┘
|
||||||
│
|
│
|
||||||
┌──────┴──────┬────────────────┬─────────────────┐
|
▼
|
||||||
│ │ │ │
|
┌─────────────────────────┐
|
||||||
▼ ▼ ▼ ▼
|
│ Gateway │
|
||||||
┌──────────┐ ┌────────────┐ ┌──────────────┐ ┌─────────────┐
|
│ FastAPI :8001 │
|
||||||
│Core Svc │ │Data Service│ │Strategy Eng. │ │QMT Adapter │
|
│ (API 入口) │
|
||||||
│ (8010) │ │ (8020) │ │ (8030) │ │ (Py 3.6) │
|
└───────────┬─────────────┘
|
||||||
└──────────┘ └────────────┘ └──────────────┘ └─────────────┘
|
│
|
||||||
│ │ │ │
|
┌───────────────────────┼───────────────────────┐
|
||||||
└─────────────┴────────────────┴─────────────────┘
|
│ │ │
|
||||||
|
▼ ▼ ▼
|
||||||
|
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
|
||||||
|
│ Core Service │ │ Data Service │ │Strategy Engine│
|
||||||
|
│ :8010 │ │ :8020 │ │ :8030 │
|
||||||
|
├───────────────┤ ├───────────────┤ ├───────────────┤
|
||||||
|
│ 订单管理 │ │ 行情接收/分发 │ │ 策略管理 │
|
||||||
|
│ 持仓管理 │ │ K线存储查询 │ │ 信号生成 │
|
||||||
|
│ 资金管理 │ │ 回测数据回放 │ │ 策略执行 │
|
||||||
|
│ 配对管理 │ │ │ │ │
|
||||||
|
└───────────────┘ └───────────────┘ └───────────────┘
|
||||||
|
│ │ │
|
||||||
|
└───────────────────────┼───────────────────────┘
|
||||||
│
|
│
|
||||||
┌─────┴─────┐
|
┌─────┴─────┐
|
||||||
│ Redis │
|
│ Redis │ ← Pub/Sub + Cache
|
||||||
└─────┬─────┘
|
└─────┬─────┘
|
||||||
│
|
┌───────────┴───────────┐
|
||||||
┌─────┴─────┐
|
│ │
|
||||||
│ MySQL │
|
▼ ▼
|
||||||
└───────────┘
|
┌─────────────────┐ ┌─────────────────┐
|
||||||
|
│ QMT Adapter │ │ MySQL │
|
||||||
|
│ :8040 (模拟) │ │ (数据持久化) │
|
||||||
|
│ Python 3.6 │ │ │
|
||||||
|
└─────────────────┘ └─────────────────┘
|
||||||
```
|
```
|
||||||
|
|
||||||
## 📋 项目结构
|
## 📁 项目结构
|
||||||
|
|
||||||
```
|
```
|
||||||
QTrade/
|
QTrade/
|
||||||
@ -47,183 +63,158 @@ QTrade/
|
|||||||
│ └── architecture/
|
│ └── architecture/
|
||||||
│ ├── ARCHITECTURE.md # 架构设计
|
│ ├── ARCHITECTURE.md # 架构设计
|
||||||
│ └── BUILD_PLAN.md # 构建方案
|
│ └── BUILD_PLAN.md # 构建方案
|
||||||
|
│
|
||||||
├── src/
|
├── src/
|
||||||
│ ├── core/ # 核心模块
|
│ ├── core/ # 核心模块
|
||||||
│ │ ├── config.py # 配置管理
|
│ │ ├── config.py # 配置管理 (Pydantic + YAML)
|
||||||
│ │ ├── database.py # 数据库连接
|
│ │ ├── database.py # 数据库连接 (SQLAlchemy 2.0 async)
|
||||||
│ │ ├── redis_client.py # Redis 客户端
|
│ │ ├── redis_client.py # Redis 客户端 (asyncio)
|
||||||
│ │ ├── logger.py # 日志模块
|
│ │ ├── logger.py # 日志模块
|
||||||
│ │ └── models/ # 数据模型
|
│ │ └── models/ # 数据模型 (Pydantic)
|
||||||
│ ├── gateway/ # API 网关
|
│ │
|
||||||
│ ├── core_service/ # 核心业务服务
|
│ ├── gateway/ # API 网关 (:8001)
|
||||||
│ ├── data_service/ # 数据服务
|
│ │ ├── app.py # FastAPI 应用
|
||||||
│ ├── strategy_engine/ # 策略引擎
|
│ │ └── routes/ # 路由模块
|
||||||
│ └── qmt_adapter/ # QMT 适配层
|
│ │
|
||||||
├── configs/ # 配置文件
|
│ ├── core_service/ # 核心业务服务 (:8010)
|
||||||
│ └── settings.yaml
|
│ │ ├── services/ # 业务逻辑
|
||||||
├── database/ # 数据库脚本
|
│ │ │ ├── order_service.py
|
||||||
├── scripts/ # 运维脚本
|
│ │ │ ├── position_service.py
|
||||||
├── tests/ # 测试
|
│ │ │ ├── balance_service.py
|
||||||
└── logs/ # 日志
|
│ │ │ └── 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. 安装依赖
|
### 1. 环境准备
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
# Python 3.10+
|
||||||
|
python --version
|
||||||
|
|
||||||
|
# 安装依赖
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
|
|
||||||
|
# 安装 PyQt6 (控制台)
|
||||||
|
pip install PyQt6
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. 配置
|
### 2. 配置
|
||||||
|
|
||||||
```bash
|
编辑 `configs/settings.yaml`:
|
||||||
# 复制配置模板
|
|
||||||
copy configs\.env.example configs\.env
|
|
||||||
|
|
||||||
# 根据需要编辑各个配置文件
|
```yaml
|
||||||
# - configs/global_config.yaml # 全局配置
|
redis:
|
||||||
# - configs/log.yaml # 日志配置(必需)
|
host: 127.0.0.1
|
||||||
# - configs/database.yaml # 数据库配置(如需使用)
|
port: 6379
|
||||||
# - configs/networks.yaml # 网络服务配置(如需使用)
|
|
||||||
# - configs/qmt.yaml # QMT 配置(如需使用)
|
database:
|
||||||
# - configs/strategy.yaml # 策略配置(如需使用)
|
host: 127.0.0.1
|
||||||
# - configs/.env # 敏感信息(密码等)
|
port: 3306
|
||||||
|
user: root
|
||||||
|
password: your_password
|
||||||
|
database: qtrade
|
||||||
|
|
||||||
|
qmt:
|
||||||
|
path: D:/QMT/userdata_mini
|
||||||
|
simulation: true # 模拟模式
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. 运行
|
### 3. 初始化数据库
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 启动 Socket 服务器
|
mysql -u root -p < database/init.sql
|
||||||
python src/main.py
|
|
||||||
|
|
||||||
# 或使用新架构
|
|
||||||
python src/main_v2.py
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 📦 核心依赖
|
### 4. 启动服务
|
||||||
|
|
||||||
- **pyyaml** - 配置文件解析
|
**方式一: 命令行启动**
|
||||||
- **pandas** - 数据处理
|
|
||||||
- **numpy** - 数值计算
|
|
||||||
- **peewee** - 数据库 ORM(可选)
|
|
||||||
- **pytest** - 测试框架(可选)
|
|
||||||
|
|
||||||
## <20> 目录说明
|
```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
|
||||||
|
|
||||||
### configs/ - 运行时配置
|
# 启动所有服务
|
||||||
**用途**: 存放程序运行时需要读取的所有配置文件
|
python -m src.main all
|
||||||
- `global_config.yaml` - 全局配置(项目信息、路径、环境等)
|
|
||||||
- `log.yaml` - 日志配置(必需)
|
|
||||||
- `database.yaml` - 数据库配置
|
|
||||||
- `networks.yaml` - 网络服务配置(Socket + HTTP)
|
|
||||||
- `qmt.yaml` - QMT 配置
|
|
||||||
- `strategy.yaml` - 策略配置
|
|
||||||
- `config.example.yaml` - 配置示例
|
|
||||||
- `.env` - 敏感信息配置(密码、密钥等,不提交到 git)
|
|
||||||
- `.env.example` - 环境变量模板
|
|
||||||
|
|
||||||
### src/ - 源代码
|
|
||||||
**用途**: 所有源代码文件
|
|
||||||
- 分层架构:core → utils → 业务层(networks/database/datas/strategy)
|
|
||||||
- 统一入口:`main.py` 或 `main_v2.py`
|
|
||||||
|
|
||||||
### logs/ - 日志文件
|
|
||||||
**用途**: 存放程序运行时自动生成的日志文件
|
|
||||||
- `qtrade.log` - 应用主日志
|
|
||||||
- 自动轮转,保留最近的日志
|
|
||||||
|
|
||||||
### tests/ - 测试代码
|
|
||||||
**用途**: 存放单元测试和集成测试的代码和用例
|
|
||||||
- 单元测试:测试单个函数/类
|
|
||||||
- 集成测试:测试完整流程
|
|
||||||
- 使用 pytest 运行
|
|
||||||
|
|
||||||
### examples_and_demos/ - 程序示例
|
|
||||||
**用途**: 存放具体的程序使用示例
|
|
||||||
- Socket 通信示例
|
|
||||||
- HTTP 服务示例
|
|
||||||
- 配置加载示例
|
|
||||||
- 策略使用示例
|
|
||||||
|
|
||||||
### docs/ - 文档
|
|
||||||
**用途**: 存放相关文档和 API 说明
|
|
||||||
- 架构设计文档
|
|
||||||
- API 接口文档
|
|
||||||
- 开发指南
|
|
||||||
- 使用说明
|
|
||||||
|
|
||||||
### data/ - 数据文件(可选)
|
|
||||||
**用途**: 存放数据文件
|
|
||||||
- `raw/` - 原始数据(CSV 等)
|
|
||||||
- `processed/` - 处理后的数据
|
|
||||||
- `cache/` - 缓存数据
|
|
||||||
|
|
||||||
## 📚 架构说明
|
|
||||||
|
|
||||||
### 分层架构
|
|
||||||
|
|
||||||
```
|
|
||||||
应用层 (main.py)
|
|
||||||
↓
|
|
||||||
策略层 (strategy/)
|
|
||||||
↓
|
|
||||||
业务层 (networks/, datas/, database/)
|
|
||||||
↓
|
|
||||||
核心层 (core/)
|
|
||||||
↓
|
|
||||||
工具层 (utils/)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 核心模块
|
**方式二: PyQt6 控制台 (推荐)**
|
||||||
|
|
||||||
- **core/** - 定义核心抽象和协议
|
```bash
|
||||||
- **networks/** - 网络通信(Socket + HTTP)
|
python -m src.console.main
|
||||||
- **database/** - 数据库操作和 ORM 模型
|
|
||||||
- **datas/** - 数据处理和技术指标计算
|
|
||||||
- **strategy/** - 交易策略实现
|
|
||||||
- **utils/** - 日志、配置等工具
|
|
||||||
|
|
||||||
## 📖 使用示例
|
|
||||||
|
|
||||||
### Socket 客户端
|
|
||||||
|
|
||||||
```python
|
|
||||||
from src.networks import SimpleQTradeSocketClient
|
|
||||||
|
|
||||||
client = SimpleQTradeSocketClient(host='127.0.0.1', port=8888)
|
|
||||||
client.connect()
|
|
||||||
client.send({"type": "ping", "data": {}})
|
|
||||||
response = client.receive()
|
|
||||||
client.disconnect()
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 数据处理
|
## 📊 服务端口
|
||||||
|
|
||||||
```python
|
| 服务 | 端口 | 说明 |
|
||||||
from src.datas import KlineDataProcessor
|
| --------------- | ---- | ------------ |
|
||||||
import pandas as pd
|
| Gateway | 8001 | API 网关入口 |
|
||||||
|
| Core Service | 8010 | 核心业务服务 |
|
||||||
|
| Data Service | 8020 | 数据服务 |
|
||||||
|
| Strategy Engine | 8030 | 策略引擎 |
|
||||||
|
| QMT Adapter | 8040 | QMT 适配器 |
|
||||||
|
|
||||||
processor = KlineDataProcessor()
|
## 🎯 内置策略
|
||||||
df = pd.read_csv('data/raw/stock.csv')
|
|
||||||
df_clean = processor.clean_data(df)
|
|
||||||
df_indicators = processor.calculate_indicators(df_clean)
|
|
||||||
```
|
|
||||||
|
|
||||||
### 网格策略
|
| 策略 | 说明 | 参数 |
|
||||||
|
| ---------- | -------------------- | -------------------------- |
|
||||||
|
| 网格策略 | 区间震荡套利 | 上下限价格、网格数量 |
|
||||||
|
| 均线交叉 | 短期均线穿越长期均线 | 短期周期、长期周期 |
|
||||||
|
| 双均线策略 | 均线交叉 + 止盈止损 | 短/长期周期、止盈/止损比例 |
|
||||||
|
|
||||||
```python
|
## 🖥️ 控制台功能
|
||||||
from src.strategy import GridStrategy
|
|
||||||
|
|
||||||
strategy = GridStrategy(
|
| 页面 | 功能 |
|
||||||
upper_price=10.0,
|
| -------- | ----------------------------------- |
|
||||||
lower_price=8.0,
|
| 仪表盘 | 系统概览、服务状态、快捷操作 |
|
||||||
grid_levels=10
|
| 服务管理 | 启动/停止/重启服务、健康状态监控 |
|
||||||
)
|
| 策略配置 | 股票-策略配对管理、参数配置 |
|
||||||
|
| 系统设置 | Redis/MySQL/QMT/端口 配置、连接测试 |
|
||||||
signal = strategy.get_signal(current_price=9.0)
|
| 运行日志 | 实时日志查看、按服务过滤、日志导出 |
|
||||||
print(signal['action']) # buy/sell/hold
|
|
||||||
```
|
|
||||||
|
|
||||||
## 🧪 测试
|
## 🧪 测试
|
||||||
|
|
||||||
@ -232,22 +223,28 @@ print(signal['action']) # buy/sell/hold
|
|||||||
pytest tests/ -v
|
pytest tests/ -v
|
||||||
|
|
||||||
# 运行特定测试
|
# 运行特定测试
|
||||||
pytest tests/test_simple_socket.py
|
pytest tests/test_core/ -v
|
||||||
```
|
```
|
||||||
|
|
||||||
## 📝 更多示例
|
## 📦 核心依赖
|
||||||
|
|
||||||
查看 `examples_and_demos/` 目录:
|
| 依赖 | 版本 | 用途 |
|
||||||
|
| ---------- | ------ | ------------ |
|
||||||
- **socket/** - Socket 通信示例
|
| FastAPI | 0.100+ | Web 框架 |
|
||||||
- **http/** - HTTP 服务示例
|
| 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. **配置文件** - 确保 `configs/.env` 不要提交到 git
|
1. **QMT 依赖**: QMT Adapter 需要安装 xtquant SDK (仅 Windows)
|
||||||
2. **数据库** - 首次使用需要创建数据库和表
|
2. **模拟模式**: 未安装 xtquant 时自动进入模拟模式
|
||||||
3. **QMT** - 需要单独安装 QMT 客户端和 xtquant 库
|
3. **Redis/MySQL**: 确保服务已启动
|
||||||
4. **端口** - 确保配置的端口没有被占用
|
4. **端口冲突**: 检查端口是否被占用
|
||||||
|
|
||||||
## 📄 License
|
## 📄 License
|
||||||
|
|
||||||
@ -259,5 +256,5 @@ yyppdcc
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**Version**: 0.2.1
|
**Version**: 2.0.0
|
||||||
**Status**: 轻量化开发版
|
**Status**: 开发中
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
# QTrade 系统架构设计
|
# QTrade 系统架构设计
|
||||||
|
|
||||||
> 创建日期: 2025-12-08
|
> 创建日期: 2025-12-08
|
||||||
|
> 更新日期: 2025-12-09
|
||||||
> 版本: 2.0
|
> 版本: 2.0
|
||||||
|
|
||||||
## 一、系统概述
|
## 一、系统概述
|
||||||
@ -12,6 +13,7 @@ QTrade 是一个轻量化的 A股量化交易系统,采用微服务架构,
|
|||||||
- **实时行情**: 对接 QMT 获取 A股实时行情
|
- **实时行情**: 对接 QMT 获取 A股实时行情
|
||||||
- **策略管理**: 支持同一股票配置多个策略,独立管理仓位和资金
|
- **策略管理**: 支持同一股票配置多个策略,独立管理仓位和资金
|
||||||
- **回测系统**: 复用实盘代码,从数据库回放历史数据模拟实盘
|
- **回测系统**: 复用实盘代码,从数据库回放历史数据模拟实盘
|
||||||
|
- **桌面控制台**: PyQt6 桌面应用,可视化管理所有服务
|
||||||
- **跨平台**: 主系统支持 Linux/Windows,QMT适配层仅 Windows
|
- **跨平台**: 主系统支持 Linux/Windows,QMT适配层仅 Windows
|
||||||
- **水平扩展**: 支持多机部署 (2-3台)
|
- **水平扩展**: 支持多机部署 (2-3台)
|
||||||
|
|
||||||
@ -21,18 +23,24 @@ QTrade 是一个轻量化的 A股量化交易系统,采用微服务架构,
|
|||||||
|
|
||||||
### 2.1 服务列表
|
### 2.1 服务列表
|
||||||
|
|
||||||
| 服务 | 端口 | Python版本 | 职责 |
|
| 服务 | 端口 | Python版本 | 状态 | 职责 |
|
||||||
| ------------------- | ------ | ---------- | ------------------------------------------------ |
|
| ------------------- | ---- | ---------- | -------- | ------------------------------------------------ |
|
||||||
| **gateway** | 8001 | 3.10+ | API入口、路由分发、认证鉴权、请求日志 |
|
| **gateway** | 8001 | 3.10+ | ✅ 已完成 | API入口、路由分发、认证鉴权、请求日志 |
|
||||||
| **core-service** | 8010 | 3.10+ | 交易管理、风控检查、账户管理、持仓管理、配对管理 |
|
| **core-service** | 8010 | 3.10+ | ✅ 已完成 | 交易管理、风控检查、账户管理、持仓管理、配对管理 |
|
||||||
| **data-service** | 8020 | 3.10+ | 行情接收/分发、K线存储查询、回测数据回放 |
|
| **data-service** | 8020 | 3.10+ | ✅ 已完成 | 行情接收/分发、K线存储查询、回测数据回放 |
|
||||||
| **strategy-engine** | 8030 | 3.10+ | 策略管理、策略执行、信号生成 |
|
| **strategy-engine** | 8030 | 3.10+ | ✅ 已完成 | 策略管理、策略执行、信号生成 |
|
||||||
| **qmt-adapter** | 无HTTP | 3.6 | QMT行情采集、交易执行、账户同步 (仅Windows) |
|
| **qmt-adapter** | 8040 | 3.10+ | ✅ 已完成 | QMT行情采集、交易执行、账户同步 (支持模拟模式) |
|
||||||
|
| **console** | - | 3.10+ | ✅ 已完成 | PyQt6 桌面控制台 |
|
||||||
|
|
||||||
### 2.2 架构图
|
### 2.2 架构图
|
||||||
|
|
||||||
```
|
```
|
||||||
外部调用(Web/App/脚本)
|
┌─────────────────────────────────────────────────────────────────┐
|
||||||
|
│ PyQt6 Console (桌面控制台) │
|
||||||
|
│ 仪表盘 | 服务管理 | 策略配置 | 系统设置 | 日志 │
|
||||||
|
└─────────────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
外部调用(Web/App/脚本/控制台)
|
||||||
│
|
│
|
||||||
│ HTTP REST
|
│ HTTP REST
|
||||||
▼
|
▼
|
||||||
@ -41,7 +49,7 @@ QTrade 是一个轻量化的 A股量化交易系统,采用微服务架构,
|
|||||||
│ (API入口) │
|
│ (API入口) │
|
||||||
└────────┬────────┘
|
└────────┬────────┘
|
||||||
│
|
│
|
||||||
│ Redis Pub/Sub
|
│ HTTP + Redis Pub/Sub
|
||||||
▼
|
▼
|
||||||
┌────────────────────┼────────────────────┐
|
┌────────────────────┼────────────────────┐
|
||||||
│ │ │
|
│ │ │
|
||||||
@ -50,10 +58,10 @@ QTrade 是一个轻量化的 A股量化交易系统,采用微服务架构,
|
|||||||
│ core-service │ │ data-service │ │strategy-engine│
|
│ core-service │ │ data-service │ │strategy-engine│
|
||||||
│ FastAPI:8010 │ │ FastAPI:8020 │ │ FastAPI:8030 │
|
│ FastAPI:8010 │ │ FastAPI:8020 │ │ FastAPI:8030 │
|
||||||
│ │ │ │ │ │
|
│ │ │ │ │ │
|
||||||
│ - 交易管理 │ │ - 行情分发 │ │ - 策略管理 │
|
│ - 订单管理 │ │ - 行情分发 │ │ - 策略管理 │
|
||||||
│ - 风控检查 │ │ - K线存储 │ │ - 信号生成 │
|
│ - 持仓管理 │ │ - K线存储 │ │ - 信号生成 │
|
||||||
│ - 账户管理 │ │ - 回测回放 │ │ │
|
│ - 资金管理 │ │ - 回测回放 │ │ - 网格策略 │
|
||||||
│ - 配对管理 │ │ │ │ │
|
│ - 配对管理 │ │ │ │ - 均线策略 │
|
||||||
└──────────────┘ └──────────────┘ └──────────────┘
|
└──────────────┘ └──────────────┘ └──────────────┘
|
||||||
│ │ │
|
│ │ │
|
||||||
└────────────────────┼────────────────────┘
|
└────────────────────┼────────────────────┘
|
||||||
@ -65,8 +73,8 @@ QTrade 是一个轻量化的 A股量化交易系统,采用微服务架构,
|
|||||||
▼ ▼
|
▼ ▼
|
||||||
┌─────────────────┐ ┌─────────────────┐
|
┌─────────────────┐ ┌─────────────────┐
|
||||||
│ qmt-adapter │ │ MySQL │
|
│ qmt-adapter │ │ MySQL │
|
||||||
│ (Python 3.6) │ │ (数据持久化) │
|
│ FastAPI:8040 │ │ (数据持久化) │
|
||||||
│ Windows Only │ │ │
|
│ (支持模拟模式) │ │ │
|
||||||
└─────────────────┘ └─────────────────┘
|
└─────────────────┘ └─────────────────┘
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
@ -272,9 +280,31 @@ service:broadcast:{event} # 广播事件
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 九、版本记录
|
## 九、控制台 (PyQt6)
|
||||||
|
|
||||||
|
### 9.1 功能模块
|
||||||
|
|
||||||
|
| 页面 | 功能 |
|
||||||
|
| -------- | ---------------------------------------- |
|
||||||
|
| 仪表盘 | 系统概览、服务状态卡片、快捷操作 |
|
||||||
|
| 服务管理 | 启动/停止/重启服务、健康状态自动检测 |
|
||||||
|
| 策略配置 | 股票-策略配对管理、参数配置表单 |
|
||||||
|
| 系统设置 | Redis/MySQL/QMT/端口配置、连接测试 |
|
||||||
|
| 运行日志 | 实时日志查看、按服务过滤、自动刷新、导出 |
|
||||||
|
|
||||||
|
### 9.2 技术特性
|
||||||
|
|
||||||
|
- **进程管理**: subprocess 启动/停止服务进程
|
||||||
|
- **健康检测**: QThread 后台线程 + httpx 请求 /ping
|
||||||
|
- **配置管理**: 读写 settings.yaml 配置文件
|
||||||
|
- **连接测试**: 支持 Redis/MySQL 连接测试
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 十、版本记录
|
||||||
|
|
||||||
| 版本 | 日期 | 说明 |
|
| 版本 | 日期 | 说明 |
|
||||||
| ---- | ---------- | ------------------ |
|
| ---- | ---------- | ------------------------------- |
|
||||||
| 2.0 | 2025-12-08 | 微服务架构重构设计 |
|
| 2.0 | 2025-12-09 | 微服务架构完成,PyQt6控制台完成 |
|
||||||
|
| 1.5 | 2025-12-08 | 微服务架构重构设计 |
|
||||||
| 1.0 | - | 原单体架构 |
|
| 1.0 | - | 原单体架构 |
|
||||||
|
|||||||
@ -1,7 +1,8 @@
|
|||||||
# QTrade 重构构建方案
|
# QTrade 重构构建方案
|
||||||
|
|
||||||
> 创建日期: 2025-12-08
|
> 创建日期: 2025-12-08
|
||||||
> 状态: 进行中
|
> 更新日期: 2025-12-09
|
||||||
|
> 状态: ✅ 已完成
|
||||||
|
|
||||||
## 一、重构目标
|
## 一、重构目标
|
||||||
|
|
||||||
@ -10,6 +11,7 @@
|
|||||||
- 服务化拆分
|
- 服务化拆分
|
||||||
- 实盘/回测代码复用
|
- 实盘/回测代码复用
|
||||||
- 跨平台支持
|
- 跨平台支持
|
||||||
|
- PyQt6 桌面控制台
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -52,11 +54,11 @@ src/core/
|
|||||||
|
|
||||||
| 任务 | 状态 | 说明 |
|
| 任务 | 状态 | 说明 |
|
||||||
| -------------------- | -------- | ------------------ |
|
| -------------------- | -------- | ------------------ |
|
||||||
| 2.1 FastAPI 应用框架 | ⬜ 待开始 | 应用实例、生命周期 |
|
| 2.1 FastAPI 应用框架 | ✅ 已完成 | 应用实例、生命周期 |
|
||||||
| 2.2 健康检查接口 | ⬜ 待开始 | /health |
|
| 2.2 健康检查接口 | ✅ 已完成 | /ping |
|
||||||
| 2.3 路由结构 | ⬜ 待开始 | 路由模块划分 |
|
| 2.3 路由结构 | ✅ 已完成 | 路由模块划分 |
|
||||||
| 2.4 中间件 | ⬜ 待开始 | 日志、异常处理 |
|
| 2.4 中间件 | ✅ 已完成 | 日志、异常处理 |
|
||||||
| 2.5 启动脚本 | ⬜ 待开始 | 服务启动入口 |
|
| 2.5 启动脚本 | ✅ 已完成 | 服务启动入口 |
|
||||||
|
|
||||||
**产出物**:
|
**产出物**:
|
||||||
```
|
```
|
||||||
@ -83,12 +85,12 @@ src/gateway/
|
|||||||
|
|
||||||
| 任务 | 状态 | 说明 |
|
| 任务 | 状态 | 说明 |
|
||||||
| ---------------- | -------- | --------------- |
|
| ---------------- | -------- | --------------- |
|
||||||
| 3.1 服务框架 | ⬜ 待开始 | FastAPI 应用 |
|
| 3.1 服务框架 | ✅ 已完成 | FastAPI 应用 |
|
||||||
| 3.2 行情接收模块 | ⬜ 待开始 | 订阅 Redis 行情 |
|
| 3.2 行情接收模块 | ✅ 已完成 | 订阅 Redis 行情 |
|
||||||
| 3.3 行情分发模块 | ⬜ 待开始 | 分发给策略引擎 |
|
| 3.3 行情分发模块 | ✅ 已完成 | 分发给策略引擎 |
|
||||||
| 3.4 K线存储模块 | ⬜ 待开始 | 按周期分表存储 |
|
| 3.4 K线存储模块 | ✅ 已完成 | 按周期分表存储 |
|
||||||
| 3.5 K线查询接口 | ⬜ 待开始 | 历史数据查询 |
|
| 3.5 K线查询接口 | ✅ 已完成 | 历史数据查询 |
|
||||||
| 3.6 回测数据回放 | ⬜ 待开始 | 模拟QMT推送 |
|
| 3.6 回测数据回放 | ✅ 已完成 | 模拟QMT推送 |
|
||||||
|
|
||||||
**产出物**:
|
**产出物**:
|
||||||
```
|
```
|
||||||
@ -104,13 +106,9 @@ src/data_service/
|
|||||||
│ ├── storage.py # K线存储
|
│ ├── storage.py # K线存储
|
||||||
│ ├── query.py # K线查询
|
│ ├── query.py # K线查询
|
||||||
│ └── models.py # K线ORM模型
|
│ └── models.py # K线ORM模型
|
||||||
├── backtest/
|
|
||||||
│ ├── data_player.py # 数据回放
|
|
||||||
│ └── matcher.py # 模拟撮合
|
|
||||||
└── routes/
|
└── routes/
|
||||||
├── market.py
|
├── market.py
|
||||||
├── kline.py
|
└── kline.py
|
||||||
└── backtest.py
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@ -121,12 +119,12 @@ src/data_service/
|
|||||||
|
|
||||||
| 任务 | 状态 | 说明 |
|
| 任务 | 状态 | 说明 |
|
||||||
| ---------------- | -------- | -------------------- |
|
| ---------------- | -------- | -------------------- |
|
||||||
| 4.1 服务框架 | ⬜ 待开始 | FastAPI 应用 |
|
| 4.1 服务框架 | ✅ 已完成 | FastAPI 应用 |
|
||||||
| 4.2 配对管理模块 | ⬜ 待开始 | 股票-策略配对 CRUD |
|
| 4.2 配对管理模块 | ✅ 已完成 | 股票-策略配对 CRUD |
|
||||||
| 4.3 订单管理模块 | ⬜ 待开始 | 订单创建、查询、撤销 |
|
| 4.3 订单管理模块 | ✅ 已完成 | 订单创建、查询、撤销 |
|
||||||
| 4.4 风控模块 | ⬜ 待开始 | 下单前风控检查 |
|
| 4.4 风控模块 | ✅ 已完成 | 下单前风控检查 |
|
||||||
| 4.5 持仓管理模块 | ⬜ 待开始 | 持仓更新、查询 |
|
| 4.5 持仓管理模块 | ✅ 已完成 | 持仓更新、查询 |
|
||||||
| 4.6 资金管理模块 | ⬜ 待开始 | 资金冻结、释放 |
|
| 4.6 资金管理模块 | ✅ 已完成 | 资金冻结、释放 |
|
||||||
|
|
||||||
**产出物**:
|
**产出物**:
|
||||||
```
|
```
|
||||||
@ -134,20 +132,17 @@ src/core_service/
|
|||||||
├── __init__.py
|
├── __init__.py
|
||||||
├── main.py
|
├── main.py
|
||||||
├── app.py
|
├── app.py
|
||||||
├── symbol_strategy/
|
├── services/
|
||||||
│ └── manager.py # 配对管理
|
│ ├── order_service.py
|
||||||
├── trading/
|
│ ├── position_service.py
|
||||||
│ ├── order_manager.py
|
│ ├── balance_service.py
|
||||||
│ └── executor.py # 发送到Redis
|
│ └── pairing_service.py
|
||||||
├── risk/
|
|
||||||
│ └── checker.py # 风控检查
|
|
||||||
├── account/
|
|
||||||
│ ├── position_manager.py
|
|
||||||
│ └── balance_manager.py
|
|
||||||
└── routes/
|
└── routes/
|
||||||
├── symbol_strategy.py
|
|
||||||
├── order.py
|
├── order.py
|
||||||
├── position.py
|
├── position.py
|
||||||
|
├── balance.py
|
||||||
|
└── pairing.py
|
||||||
|
```
|
||||||
└── account.py
|
└── account.py
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -159,11 +154,11 @@ src/core_service/
|
|||||||
|
|
||||||
| 任务 | 状态 | 说明 |
|
| 任务 | 状态 | 说明 |
|
||||||
| ---------------- | -------- | ------------------ |
|
| ---------------- | -------- | ------------------ |
|
||||||
| 5.1 服务框架 | ⬜ 待开始 | FastAPI 应用 |
|
| 5.1 服务框架 | ✅ 已完成 | FastAPI 应用 |
|
||||||
| 5.2 策略管理模块 | ⬜ 待开始 | 策略加载、启停 |
|
| 5.2 策略管理模块 | ✅ 已完成 | 策略加载、启停 |
|
||||||
| 5.3 行情订阅模块 | ⬜ 待开始 | 订阅 Redis 行情 |
|
| 5.3 行情订阅模块 | ✅ 已完成 | 订阅 Redis 行情 |
|
||||||
| 5.4 信号生成模块 | ⬜ 待开始 | 策略执行、信号输出 |
|
| 5.4 信号生成模块 | ✅ 已完成 | 策略执行、信号输出 |
|
||||||
| 5.5 策略基类 | ⬜ 待开始 | 策略抽象接口 |
|
| 5.5 策略基类 | ✅ 已完成 | 策略抽象接口 |
|
||||||
|
|
||||||
**产出物**:
|
**产出物**:
|
||||||
```
|
```
|
||||||
@ -171,65 +166,90 @@ src/strategy_engine/
|
|||||||
├── __init__.py
|
├── __init__.py
|
||||||
├── main.py
|
├── main.py
|
||||||
├── app.py
|
├── app.py
|
||||||
|
├── strategies/
|
||||||
|
│ ├── base.py # 策略基类
|
||||||
|
│ ├── grid_strategy.py # 网格策略
|
||||||
|
│ └── ma_strategy.py # 均线策略
|
||||||
├── engine/
|
├── engine/
|
||||||
│ ├── manager.py # 策略管理
|
│ ├── manager.py # 策略管理
|
||||||
│ ├── executor.py # 策略执行器
|
│ └── executor.py # 策略执行器
|
||||||
│ └── base_strategy.py # 策略基类
|
|
||||||
├── market/
|
|
||||||
│ └── subscriber.py # 行情订阅
|
|
||||||
└── routes/
|
└── routes/
|
||||||
└── strategy.py
|
└── strategy.py
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 阶段6: QMT Adapter (Python 3.6)
|
### 阶段6: QMT Adapter
|
||||||
|
|
||||||
**目标**: 建立QMT适配层
|
**目标**: 建立QMT适配层
|
||||||
|
|
||||||
| 任务 | 状态 | 说明 |
|
| 任务 | 状态 | 说明 |
|
||||||
| ---------------- | -------- | --------------- |
|
| ---------------- | -------- | --------------- |
|
||||||
| 6.1 项目结构 | ⬜ 待开始 | Python 3.6 兼容 |
|
| 6.1 项目结构 | ✅ 已完成 | FastAPI 应用 |
|
||||||
| 6.2 行情采集模块 | ⬜ 待开始 | QMT → Redis |
|
| 6.2 行情采集模块 | ✅ 已完成 | QMT → Redis |
|
||||||
| 6.3 交易执行模块 | ⬜ 待开始 | Redis → QMT |
|
| 6.3 交易执行模块 | ✅ 已完成 | Redis → QMT |
|
||||||
| 6.4 账户同步模块 | ⬜ 待开始 | QMT → Redis |
|
| 6.4 账户同步模块 | ✅ 已完成 | QMT → Redis |
|
||||||
| 6.5 启动脚本 | ⬜ 待开始 | 独立运行 |
|
| 6.5 模拟模式 | ✅ 已完成 | 无xtquant时模拟 |
|
||||||
|
|
||||||
**产出物**:
|
**产出物**:
|
||||||
```
|
```
|
||||||
src/qmt_adapter/
|
src/qmt_adapter/
|
||||||
├── __init__.py
|
├── __init__.py
|
||||||
├── main.py # 入口
|
├── main.py # 入口
|
||||||
|
├── app.py # FastAPI 应用
|
||||||
|
├── qmt_client.py # QMT SDK 封装
|
||||||
├── market_feeder.py # 行情采集
|
├── market_feeder.py # 行情采集
|
||||||
├── trade_executor.py # 交易执行
|
├── trade_executor.py # 交易执行
|
||||||
├── account_sync.py # 账户同步
|
├── account_sync.py # 账户同步
|
||||||
└── qmt_client.py # QMT SDK 封装
|
└── routes/
|
||||||
|
└── qmt.py
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 阶段7: 数据库与配置
|
### 阶段7: PyQt6 控制台
|
||||||
|
|
||||||
**目标**: 完善数据库和配置
|
**目标**: 建立桌面管理控制台
|
||||||
|
|
||||||
| 任务 | 状态 | 说明 |
|
| 任务 | 状态 | 说明 |
|
||||||
| ------------------ | -------- | ------------- |
|
| ---------------- | -------- | ------------------ |
|
||||||
| 7.1 数据库迁移脚本 | ⬜ 待开始 | Alembic |
|
| 7.1 应用框架 | ✅ 已完成 | PyQt6 主窗口 |
|
||||||
| 7.2 初始化SQL | ⬜ 待开始 | 表结构 |
|
| 7.2 仪表盘页面 | ✅ 已完成 | 系统概览、快捷操作 |
|
||||||
| 7.3 配置文件模板 | ⬜ 待开始 | settings.yaml |
|
| 7.3 服务管理页面 | ✅ 已完成 | 启停服务、健康检测 |
|
||||||
| 7.4 环境变量示例 | ⬜ 待开始 | .env.example |
|
| 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: 测试与文档
|
||||||
|
|
||||||
**目标**: 建立部署方案
|
**目标**: 完善测试和文档
|
||||||
|
|
||||||
| 任务 | 状态 | 说明 |
|
| 任务 | 状态 | 说明 |
|
||||||
| ------------------- | -------- | ---------- |
|
| ---------------- | -------- | ------------- |
|
||||||
| 8.1 启动脚本 | ⬜ 待开始 | 跨平台启动 |
|
| 8.1 单元测试 | ✅ 已完成 | pytest |
|
||||||
| 8.2 Supervisor 配置 | ⬜ 待开始 | 进程管理 |
|
| 8.2 数据库初始化 | ✅ 已完成 | init.sql |
|
||||||
| 8.3 部署文档 | ⬜ 待开始 | 部署说明 |
|
| 8.3 配置文件模板 | ✅ 已完成 | settings.yaml |
|
||||||
|
| 8.4 README 文档 | ✅ 已完成 | 使用说明 |
|
||||||
|
| 8.5 架构文档 | ✅ 已完成 | 设计说明 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -243,29 +263,24 @@ QTrade/
|
|||||||
│ └── BUILD_PLAN.md # 本文档
|
│ └── BUILD_PLAN.md # 本文档
|
||||||
│
|
│
|
||||||
├── src/
|
├── src/
|
||||||
│ ├── core/ # 阶段1: 核心模块
|
│ ├── core/ # 阶段1: 核心模块 ✅
|
||||||
│ ├── gateway/ # 阶段2: API网关
|
│ ├── gateway/ # 阶段2: API网关 ✅
|
||||||
│ ├── data_service/ # 阶段3: 数据服务
|
│ ├── data_service/ # 阶段3: 数据服务 ✅
|
||||||
│ ├── core_service/ # 阶段4: 核心业务
|
│ ├── core_service/ # 阶段4: 核心业务 ✅
|
||||||
│ ├── strategy_engine/ # 阶段5: 策略引擎
|
│ ├── strategy_engine/ # 阶段5: 策略引擎 ✅
|
||||||
│ └── qmt_adapter/ # 阶段6: QMT适配
|
│ ├── qmt_adapter/ # 阶段6: QMT适配 ✅
|
||||||
|
│ ├── console/ # 阶段7: PyQt6控制台 ✅
|
||||||
|
│ └── main.py # 服务启动入口
|
||||||
│
|
│
|
||||||
├── configs/
|
├── configs/
|
||||||
│ ├── settings.yaml # 主配置
|
│ └── settings.yaml # 主配置
|
||||||
│ └── logging.yaml # 日志配置
|
|
||||||
│
|
│
|
||||||
├── database/
|
├── database/
|
||||||
│ ├── migrations/ # 数据库迁移
|
|
||||||
│ └── init.sql # 初始化SQL
|
│ └── init.sql # 初始化SQL
|
||||||
│
|
│
|
||||||
├── scripts/
|
├── tests/ # 测试 ✅
|
||||||
│ ├── start.py # 启动脚本
|
├── requirements.txt # Python 依赖
|
||||||
│ └── supervisord/ # Supervisor配置
|
└── README.md # 项目文档 ✅
|
||||||
│
|
|
||||||
├── tests/ # 测试
|
|
||||||
├── requirements.txt # Python 3.10+ 依赖
|
|
||||||
├── requirements36.txt # Python 3.6 依赖
|
|
||||||
└── README.md
|
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@ -274,24 +289,32 @@ QTrade/
|
|||||||
|
|
||||||
### 当前状态
|
### 当前状态
|
||||||
|
|
||||||
- **当前阶段**: 阶段2 - Gateway 服务
|
- **当前阶段**: ✅ 全部完成
|
||||||
- **当前任务**: 2.1 FastAPI 应用框架
|
- **完成日期**: 2025-12-09
|
||||||
- **开始日期**: 2025-12-08
|
- **总文件数**: 60+
|
||||||
- **预计完成**: -
|
- **总代码行**: 6000+
|
||||||
|
|
||||||
### 进度记录
|
### 进度记录
|
||||||
|
|
||||||
| 日期 | 完成内容 | 备注 |
|
| 日期 | 完成内容 | 备注 |
|
||||||
| ---------- | ------------ | -------------------------------------------------- |
|
| ---------- | ------------- | -------------------------------------------------- |
|
||||||
| 2025-12-08 | 架构设计完成 | 确定技术方案 |
|
| 2025-12-08 | 架构设计完成 | 确定技术方案 |
|
||||||
| 2025-12-08 | 构建方案创建 | 本文档 |
|
| 2025-12-08 | 构建方案创建 | 本文档 |
|
||||||
| 2025-12-08 | 阶段1完成 | 核心模块 (config, redis, database, logger, models) |
|
| 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. **不兼容旧代码**: 重构不考虑与现有代码的兼容性
|
1. **QMT模拟模式**: 未安装xtquant SDK时自动启用模拟模式
|
||||||
2. **一步步来**: 每完成一个任务验证后再进行下一个
|
2. **Python版本**: 主服务使用 Python 3.10+,支持async/await
|
||||||
3. **及时纠偏**: 发现问题立即讨论调整
|
3. **依赖管理**: 使用 pip install -r requirements.txt 安装
|
||||||
4. **文档同步**: 代码变更同步更新文档
|
4. **文档同步**: 代码变更同步更新文档
|
||||||
|
|||||||
7
src/console/__init__.py
Normal file
7
src/console/__init__.py
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
"""
|
||||||
|
QTrade Console - 控制台应用
|
||||||
|
|
||||||
|
基于 PyQt6 的桌面管理界面
|
||||||
|
"""
|
||||||
|
|
||||||
|
__version__ = "1.0.0"
|
||||||
48
src/console/main.py
Normal file
48
src/console/main.py
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
"""
|
||||||
|
控制台主入口
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# 添加项目根目录到 path
|
||||||
|
project_root = Path(__file__).parent.parent.parent
|
||||||
|
sys.path.insert(0, str(project_root))
|
||||||
|
|
||||||
|
from PyQt6.QtWidgets import QApplication # noqa: E402
|
||||||
|
from PyQt6.QtCore import Qt # noqa: E402
|
||||||
|
from PyQt6.QtGui import QFont # noqa: E402
|
||||||
|
|
||||||
|
from src.console.windows.main_window import MainWindow # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
"""启动控制台"""
|
||||||
|
# 高 DPI 支持
|
||||||
|
QApplication.setHighDpiScaleFactorRoundingPolicy(
|
||||||
|
Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
|
||||||
|
)
|
||||||
|
|
||||||
|
app = QApplication(sys.argv)
|
||||||
|
|
||||||
|
# 设置应用信息
|
||||||
|
app.setApplicationName("QTrade Console")
|
||||||
|
app.setApplicationVersion("1.0.0")
|
||||||
|
app.setOrganizationName("QTrade")
|
||||||
|
|
||||||
|
# 设置默认字体
|
||||||
|
font = QFont("Microsoft YaHei", 9)
|
||||||
|
app.setFont(font)
|
||||||
|
|
||||||
|
# 设置样式
|
||||||
|
app.setStyle("Fusion")
|
||||||
|
|
||||||
|
# 创建主窗口
|
||||||
|
window = MainWindow()
|
||||||
|
window.show()
|
||||||
|
|
||||||
|
sys.exit(app.exec())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
3
src/console/windows/__init__.py
Normal file
3
src/console/windows/__init__.py
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
"""
|
||||||
|
窗口模块
|
||||||
|
"""
|
||||||
228
src/console/windows/main_window.py
Normal file
228
src/console/windows/main_window.py
Normal file
@ -0,0 +1,228 @@
|
|||||||
|
"""
|
||||||
|
主窗口
|
||||||
|
"""
|
||||||
|
|
||||||
|
from PyQt6.QtWidgets import (
|
||||||
|
QMainWindow,
|
||||||
|
QWidget,
|
||||||
|
QVBoxLayout,
|
||||||
|
QHBoxLayout,
|
||||||
|
QStackedWidget,
|
||||||
|
QListWidget,
|
||||||
|
QListWidgetItem,
|
||||||
|
QStatusBar,
|
||||||
|
QLabel,
|
||||||
|
QFrame,
|
||||||
|
)
|
||||||
|
from PyQt6.QtCore import Qt, QTimer, QSize
|
||||||
|
|
||||||
|
from .pages.dashboard_page import DashboardPage
|
||||||
|
from .pages.services_page import ServicesPage
|
||||||
|
from .pages.strategies_page import StrategiesPage
|
||||||
|
from .pages.settings_page import SettingsPage
|
||||||
|
from .pages.logs_page import LogsPage
|
||||||
|
|
||||||
|
|
||||||
|
class MainWindow(QMainWindow):
|
||||||
|
"""主窗口"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__()
|
||||||
|
|
||||||
|
self.setWindowTitle("QTrade 控制台")
|
||||||
|
self.setMinimumSize(1200, 800)
|
||||||
|
self.resize(1400, 900)
|
||||||
|
|
||||||
|
# 初始化 UI
|
||||||
|
self._init_ui()
|
||||||
|
|
||||||
|
# 启动状态检查定时器
|
||||||
|
self._status_timer = QTimer()
|
||||||
|
self._status_timer.timeout.connect(self._update_status)
|
||||||
|
self._status_timer.start(5000) # 5秒检查一次
|
||||||
|
|
||||||
|
# 初始状态检查
|
||||||
|
self._update_status()
|
||||||
|
|
||||||
|
def _init_ui(self) -> None:
|
||||||
|
"""初始化界面"""
|
||||||
|
# 中央部件
|
||||||
|
central = QWidget()
|
||||||
|
self.setCentralWidget(central)
|
||||||
|
|
||||||
|
# 主布局
|
||||||
|
main_layout = QHBoxLayout(central)
|
||||||
|
main_layout.setContentsMargins(0, 0, 0, 0)
|
||||||
|
main_layout.setSpacing(0)
|
||||||
|
|
||||||
|
# 左侧导航栏
|
||||||
|
nav_frame = self._create_nav()
|
||||||
|
main_layout.addWidget(nav_frame)
|
||||||
|
|
||||||
|
# 右侧内容区
|
||||||
|
self._content_stack = QStackedWidget()
|
||||||
|
self._content_stack.setStyleSheet("""
|
||||||
|
QStackedWidget {
|
||||||
|
background-color: #f5f5f5;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
|
||||||
|
# 添加页面
|
||||||
|
self._dashboard_page = DashboardPage()
|
||||||
|
self._services_page = ServicesPage()
|
||||||
|
self._strategies_page = StrategiesPage()
|
||||||
|
self._settings_page = SettingsPage()
|
||||||
|
self._logs_page = LogsPage()
|
||||||
|
|
||||||
|
self._content_stack.addWidget(self._dashboard_page)
|
||||||
|
self._content_stack.addWidget(self._services_page)
|
||||||
|
self._content_stack.addWidget(self._strategies_page)
|
||||||
|
self._content_stack.addWidget(self._settings_page)
|
||||||
|
self._content_stack.addWidget(self._logs_page)
|
||||||
|
|
||||||
|
main_layout.addWidget(self._content_stack, 1)
|
||||||
|
|
||||||
|
# 状态栏
|
||||||
|
self._init_status_bar()
|
||||||
|
|
||||||
|
def _create_nav(self) -> QFrame:
|
||||||
|
"""创建导航栏"""
|
||||||
|
frame = QFrame()
|
||||||
|
frame.setFixedWidth(200)
|
||||||
|
frame.setStyleSheet("""
|
||||||
|
QFrame {
|
||||||
|
background-color: #2c3e50;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
|
||||||
|
layout = QVBoxLayout(frame)
|
||||||
|
layout.setContentsMargins(0, 0, 0, 0)
|
||||||
|
layout.setSpacing(0)
|
||||||
|
|
||||||
|
# Logo 区域
|
||||||
|
logo_label = QLabel("QTrade")
|
||||||
|
logo_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
logo_label.setFixedHeight(60)
|
||||||
|
logo_label.setStyleSheet("""
|
||||||
|
QLabel {
|
||||||
|
color: white;
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: bold;
|
||||||
|
background-color: #1a252f;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
layout.addWidget(logo_label)
|
||||||
|
|
||||||
|
# 导航列表
|
||||||
|
self._nav_list = QListWidget()
|
||||||
|
self._nav_list.setStyleSheet("""
|
||||||
|
QListWidget {
|
||||||
|
background-color: transparent;
|
||||||
|
border: none;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
QListWidget::item {
|
||||||
|
color: #bdc3c7;
|
||||||
|
padding: 15px 20px;
|
||||||
|
border-left: 3px solid transparent;
|
||||||
|
}
|
||||||
|
QListWidget::item:hover {
|
||||||
|
background-color: #34495e;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
QListWidget::item:selected {
|
||||||
|
background-color: #3498db;
|
||||||
|
color: white;
|
||||||
|
border-left: 3px solid #2980b9;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
|
||||||
|
# 添加导航项
|
||||||
|
nav_items = [
|
||||||
|
("📊", "仪表盘"),
|
||||||
|
("⚙️", "服务管理"),
|
||||||
|
("📈", "策略配置"),
|
||||||
|
("🔧", "系统设置"),
|
||||||
|
("📋", "运行日志"),
|
||||||
|
]
|
||||||
|
|
||||||
|
for icon, text in nav_items:
|
||||||
|
item = QListWidgetItem(f" {icon} {text}")
|
||||||
|
item.setSizeHint(QSize(200, 50))
|
||||||
|
self._nav_list.addItem(item)
|
||||||
|
|
||||||
|
self._nav_list.setCurrentRow(0)
|
||||||
|
self._nav_list.currentRowChanged.connect(self._on_nav_changed)
|
||||||
|
|
||||||
|
layout.addWidget(self._nav_list)
|
||||||
|
layout.addStretch()
|
||||||
|
|
||||||
|
# 版本信息
|
||||||
|
version_label = QLabel("v1.0.0")
|
||||||
|
version_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
version_label.setFixedHeight(30)
|
||||||
|
version_label.setStyleSheet("""
|
||||||
|
QLabel {
|
||||||
|
color: #7f8c8d;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
layout.addWidget(version_label)
|
||||||
|
|
||||||
|
return frame
|
||||||
|
|
||||||
|
def _init_status_bar(self) -> None:
|
||||||
|
"""初始化状态栏"""
|
||||||
|
status_bar = QStatusBar()
|
||||||
|
self.setStatusBar(status_bar)
|
||||||
|
|
||||||
|
# Redis 状态
|
||||||
|
self._redis_label = QLabel("Redis: 检测中...")
|
||||||
|
self._redis_label.setStyleSheet("color: #7f8c8d;")
|
||||||
|
status_bar.addWidget(self._redis_label)
|
||||||
|
|
||||||
|
# 分隔符
|
||||||
|
status_bar.addWidget(QLabel(" | "))
|
||||||
|
|
||||||
|
# MySQL 状态
|
||||||
|
self._mysql_label = QLabel("MySQL: 检测中...")
|
||||||
|
self._mysql_label.setStyleSheet("color: #7f8c8d;")
|
||||||
|
status_bar.addWidget(self._mysql_label)
|
||||||
|
|
||||||
|
# 分隔符
|
||||||
|
status_bar.addWidget(QLabel(" | "))
|
||||||
|
|
||||||
|
# 运行服务数
|
||||||
|
self._services_label = QLabel("运行中服务: 0/5")
|
||||||
|
status_bar.addWidget(self._services_label)
|
||||||
|
|
||||||
|
# 右侧时间
|
||||||
|
self._time_label = QLabel()
|
||||||
|
status_bar.addPermanentWidget(self._time_label)
|
||||||
|
|
||||||
|
# 时间更新定时器
|
||||||
|
time_timer = QTimer(self)
|
||||||
|
time_timer.timeout.connect(self._update_time)
|
||||||
|
time_timer.start(1000)
|
||||||
|
self._update_time()
|
||||||
|
|
||||||
|
def _on_nav_changed(self, index: int) -> None:
|
||||||
|
"""导航切换"""
|
||||||
|
self._content_stack.setCurrentIndex(index)
|
||||||
|
|
||||||
|
def _update_status(self) -> None:
|
||||||
|
"""更新状态"""
|
||||||
|
# 这里后续添加实际的状态检测逻辑
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _update_time(self) -> None:
|
||||||
|
"""更新时间显示"""
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
now = datetime.now()
|
||||||
|
self._time_label.setText(now.strftime("%Y-%m-%d %H:%M:%S"))
|
||||||
|
|
||||||
|
def closeEvent(self, event) -> None: # type: ignore
|
||||||
|
"""关闭事件"""
|
||||||
|
self._status_timer.stop()
|
||||||
|
event.accept()
|
||||||
17
src/console/windows/pages/__init__.py
Normal file
17
src/console/windows/pages/__init__.py
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
"""
|
||||||
|
页面模块
|
||||||
|
"""
|
||||||
|
|
||||||
|
from .dashboard_page import DashboardPage
|
||||||
|
from .services_page import ServicesPage
|
||||||
|
from .strategies_page import StrategiesPage
|
||||||
|
from .settings_page import SettingsPage
|
||||||
|
from .logs_page import LogsPage
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"DashboardPage",
|
||||||
|
"ServicesPage",
|
||||||
|
"StrategiesPage",
|
||||||
|
"SettingsPage",
|
||||||
|
"LogsPage",
|
||||||
|
]
|
||||||
256
src/console/windows/pages/dashboard_page.py
Normal file
256
src/console/windows/pages/dashboard_page.py
Normal file
@ -0,0 +1,256 @@
|
|||||||
|
"""
|
||||||
|
仪表盘页面
|
||||||
|
"""
|
||||||
|
|
||||||
|
from PyQt6.QtWidgets import (
|
||||||
|
QWidget,
|
||||||
|
QVBoxLayout,
|
||||||
|
QHBoxLayout,
|
||||||
|
QLabel,
|
||||||
|
QFrame,
|
||||||
|
QGridLayout,
|
||||||
|
QPushButton,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class DashboardPage(QWidget):
|
||||||
|
"""仪表盘页面"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self._init_ui()
|
||||||
|
|
||||||
|
def _init_ui(self) -> None:
|
||||||
|
"""初始化界面"""
|
||||||
|
layout = QVBoxLayout(self)
|
||||||
|
layout.setContentsMargins(20, 20, 20, 20)
|
||||||
|
layout.setSpacing(20)
|
||||||
|
|
||||||
|
# 标题
|
||||||
|
title = QLabel("仪表盘")
|
||||||
|
title.setStyleSheet("""
|
||||||
|
QLabel {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #2c3e50;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
layout.addWidget(title)
|
||||||
|
|
||||||
|
# 统计卡片
|
||||||
|
cards_layout = QHBoxLayout()
|
||||||
|
cards_layout.setSpacing(20)
|
||||||
|
|
||||||
|
# 服务状态卡片
|
||||||
|
self._services_card = self._create_stat_card(
|
||||||
|
"运行中服务", "0 / 5", "#3498db", "⚙️"
|
||||||
|
)
|
||||||
|
cards_layout.addWidget(self._services_card)
|
||||||
|
|
||||||
|
# 策略数量卡片
|
||||||
|
self._strategies_card = self._create_stat_card("活跃策略", "0", "#2ecc71", "📈")
|
||||||
|
cards_layout.addWidget(self._strategies_card)
|
||||||
|
|
||||||
|
# 今日订单卡片
|
||||||
|
self._orders_card = self._create_stat_card("今日订单", "0", "#e74c3c", "📝")
|
||||||
|
cards_layout.addWidget(self._orders_card)
|
||||||
|
|
||||||
|
# 今日盈亏卡片
|
||||||
|
self._pnl_card = self._create_stat_card("今日盈亏", "¥0.00", "#9b59b6", "💰")
|
||||||
|
cards_layout.addWidget(self._pnl_card)
|
||||||
|
|
||||||
|
layout.addLayout(cards_layout)
|
||||||
|
|
||||||
|
# 快捷操作区
|
||||||
|
quick_frame = QFrame()
|
||||||
|
quick_frame.setStyleSheet("""
|
||||||
|
QFrame {
|
||||||
|
background-color: white;
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
quick_layout = QVBoxLayout(quick_frame)
|
||||||
|
quick_layout.setContentsMargins(20, 20, 20, 20)
|
||||||
|
|
||||||
|
quick_title = QLabel("快捷操作")
|
||||||
|
quick_title.setStyleSheet("""
|
||||||
|
QLabel {
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #2c3e50;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
quick_layout.addWidget(quick_title)
|
||||||
|
|
||||||
|
buttons_layout = QHBoxLayout()
|
||||||
|
buttons_layout.setSpacing(15)
|
||||||
|
|
||||||
|
start_all_btn = QPushButton("🚀 一键启动全部")
|
||||||
|
start_all_btn.setStyleSheet(self._get_button_style("#27ae60"))
|
||||||
|
start_all_btn.setFixedHeight(45)
|
||||||
|
buttons_layout.addWidget(start_all_btn)
|
||||||
|
|
||||||
|
stop_all_btn = QPushButton("⏹️ 一键停止全部")
|
||||||
|
stop_all_btn.setStyleSheet(self._get_button_style("#e74c3c"))
|
||||||
|
stop_all_btn.setFixedHeight(45)
|
||||||
|
buttons_layout.addWidget(stop_all_btn)
|
||||||
|
|
||||||
|
restart_all_btn = QPushButton("🔄 重启全部服务")
|
||||||
|
restart_all_btn.setStyleSheet(self._get_button_style("#3498db"))
|
||||||
|
restart_all_btn.setFixedHeight(45)
|
||||||
|
buttons_layout.addWidget(restart_all_btn)
|
||||||
|
|
||||||
|
buttons_layout.addStretch()
|
||||||
|
quick_layout.addLayout(buttons_layout)
|
||||||
|
|
||||||
|
layout.addWidget(quick_frame)
|
||||||
|
|
||||||
|
# 服务状态概览
|
||||||
|
status_frame = QFrame()
|
||||||
|
status_frame.setStyleSheet("""
|
||||||
|
QFrame {
|
||||||
|
background-color: white;
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
status_layout = QVBoxLayout(status_frame)
|
||||||
|
status_layout.setContentsMargins(20, 20, 20, 20)
|
||||||
|
|
||||||
|
status_title = QLabel("服务状态概览")
|
||||||
|
status_title.setStyleSheet("""
|
||||||
|
QLabel {
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #2c3e50;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
status_layout.addWidget(status_title)
|
||||||
|
|
||||||
|
# 服务列表
|
||||||
|
services_grid = QGridLayout()
|
||||||
|
services_grid.setSpacing(10)
|
||||||
|
|
||||||
|
services = [
|
||||||
|
("Gateway", "8001", False),
|
||||||
|
("Core Service", "8010", False),
|
||||||
|
("Data Service", "8020", False),
|
||||||
|
("Strategy Engine", "8030", False),
|
||||||
|
("QMT Adapter", "8040", False),
|
||||||
|
]
|
||||||
|
|
||||||
|
for i, (name, port, running) in enumerate(services):
|
||||||
|
service_widget = self._create_service_status(name, port, running)
|
||||||
|
services_grid.addWidget(service_widget, i // 3, i % 3)
|
||||||
|
|
||||||
|
status_layout.addLayout(services_grid)
|
||||||
|
|
||||||
|
layout.addWidget(status_frame)
|
||||||
|
layout.addStretch()
|
||||||
|
|
||||||
|
def _create_stat_card(
|
||||||
|
self, title: str, value: str, color: str, icon: str
|
||||||
|
) -> QFrame:
|
||||||
|
"""创建统计卡片"""
|
||||||
|
card = QFrame()
|
||||||
|
card.setStyleSheet(f"""
|
||||||
|
QFrame {{
|
||||||
|
background-color: white;
|
||||||
|
border-radius: 8px;
|
||||||
|
border-left: 4px solid {color};
|
||||||
|
}}
|
||||||
|
""")
|
||||||
|
card.setFixedHeight(100)
|
||||||
|
|
||||||
|
layout = QHBoxLayout(card)
|
||||||
|
layout.setContentsMargins(20, 15, 20, 15)
|
||||||
|
|
||||||
|
# 左侧文字
|
||||||
|
text_layout = QVBoxLayout()
|
||||||
|
|
||||||
|
title_label = QLabel(title)
|
||||||
|
title_label.setStyleSheet("""
|
||||||
|
QLabel {
|
||||||
|
color: #7f8c8d;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
text_layout.addWidget(title_label)
|
||||||
|
|
||||||
|
value_label = QLabel(value)
|
||||||
|
value_label.setStyleSheet(f"""
|
||||||
|
QLabel {{
|
||||||
|
color: {color};
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: bold;
|
||||||
|
}}
|
||||||
|
""")
|
||||||
|
text_layout.addWidget(value_label)
|
||||||
|
|
||||||
|
layout.addLayout(text_layout)
|
||||||
|
layout.addStretch()
|
||||||
|
|
||||||
|
# 右侧图标
|
||||||
|
icon_label = QLabel(icon)
|
||||||
|
icon_label.setStyleSheet("""
|
||||||
|
QLabel {
|
||||||
|
font-size: 36px;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
layout.addWidget(icon_label)
|
||||||
|
|
||||||
|
return card
|
||||||
|
|
||||||
|
def _create_service_status(self, name: str, port: str, running: bool) -> QFrame:
|
||||||
|
"""创建服务状态项"""
|
||||||
|
frame = QFrame()
|
||||||
|
frame.setStyleSheet("""
|
||||||
|
QFrame {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 10px;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
frame.setFixedHeight(60)
|
||||||
|
|
||||||
|
layout = QHBoxLayout(frame)
|
||||||
|
layout.setContentsMargins(15, 10, 15, 10)
|
||||||
|
|
||||||
|
# 状态指示灯
|
||||||
|
status_color = "#27ae60" if running else "#95a5a6"
|
||||||
|
status_dot = QLabel("●")
|
||||||
|
status_dot.setStyleSheet(f"color: {status_color}; font-size: 14px;")
|
||||||
|
layout.addWidget(status_dot)
|
||||||
|
|
||||||
|
# 服务名
|
||||||
|
name_label = QLabel(f"{name}")
|
||||||
|
name_label.setStyleSheet("font-weight: bold; color: #2c3e50;")
|
||||||
|
layout.addWidget(name_label)
|
||||||
|
|
||||||
|
layout.addStretch()
|
||||||
|
|
||||||
|
# 端口
|
||||||
|
port_label = QLabel(f":{port}")
|
||||||
|
port_label.setStyleSheet("color: #7f8c8d;")
|
||||||
|
layout.addWidget(port_label)
|
||||||
|
|
||||||
|
return frame
|
||||||
|
|
||||||
|
def _get_button_style(self, color: str) -> str:
|
||||||
|
"""获取按钮样式"""
|
||||||
|
return f"""
|
||||||
|
QPushButton {{
|
||||||
|
background-color: {color};
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 10px 20px;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: bold;
|
||||||
|
}}
|
||||||
|
QPushButton:hover {{
|
||||||
|
background-color: {color}dd;
|
||||||
|
}}
|
||||||
|
QPushButton:pressed {{
|
||||||
|
background-color: {color}aa;
|
||||||
|
}}
|
||||||
|
"""
|
||||||
205
src/console/windows/pages/logs_page.py
Normal file
205
src/console/windows/pages/logs_page.py
Normal file
@ -0,0 +1,205 @@
|
|||||||
|
"""
|
||||||
|
日志查看页面
|
||||||
|
"""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from PyQt6.QtWidgets import (
|
||||||
|
QWidget,
|
||||||
|
QVBoxLayout,
|
||||||
|
QHBoxLayout,
|
||||||
|
QLabel,
|
||||||
|
QPushButton,
|
||||||
|
QTextEdit,
|
||||||
|
QComboBox,
|
||||||
|
QFileDialog,
|
||||||
|
)
|
||||||
|
from PyQt6.QtCore import QTimer
|
||||||
|
from PyQt6.QtGui import QFont
|
||||||
|
|
||||||
|
|
||||||
|
class LogsPage(QWidget):
|
||||||
|
"""日志查看页面"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self._current_file: Path | None = None
|
||||||
|
self._init_ui()
|
||||||
|
|
||||||
|
# 自动刷新定时器
|
||||||
|
self._refresh_timer = QTimer()
|
||||||
|
self._refresh_timer.timeout.connect(self._auto_refresh)
|
||||||
|
|
||||||
|
def _init_ui(self) -> None:
|
||||||
|
"""初始化界面"""
|
||||||
|
layout = QVBoxLayout(self)
|
||||||
|
layout.setContentsMargins(20, 20, 20, 20)
|
||||||
|
layout.setSpacing(15)
|
||||||
|
|
||||||
|
# 标题栏
|
||||||
|
header_layout = QHBoxLayout()
|
||||||
|
|
||||||
|
title = QLabel("运行日志")
|
||||||
|
title.setStyleSheet("""
|
||||||
|
QLabel {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #2c3e50;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
header_layout.addWidget(title)
|
||||||
|
|
||||||
|
header_layout.addStretch()
|
||||||
|
|
||||||
|
# 服务选择
|
||||||
|
service_label = QLabel("服务:")
|
||||||
|
header_layout.addWidget(service_label)
|
||||||
|
|
||||||
|
self._service_combo = QComboBox()
|
||||||
|
self._service_combo.setFixedWidth(150)
|
||||||
|
self._service_combo.addItem("全部日志", "all")
|
||||||
|
self._service_combo.addItem("Gateway", "gateway")
|
||||||
|
self._service_combo.addItem("Core Service", "core_service")
|
||||||
|
self._service_combo.addItem("Data Service", "data_service")
|
||||||
|
self._service_combo.addItem("Strategy Engine", "strategy_engine")
|
||||||
|
self._service_combo.addItem("QMT Adapter", "qmt_adapter")
|
||||||
|
self._service_combo.currentIndexChanged.connect(self._on_service_changed)
|
||||||
|
header_layout.addWidget(self._service_combo)
|
||||||
|
|
||||||
|
# 自动刷新
|
||||||
|
self._auto_refresh_btn = QPushButton("自动刷新: 关")
|
||||||
|
self._auto_refresh_btn.setCheckable(True)
|
||||||
|
self._auto_refresh_btn.clicked.connect(self._toggle_auto_refresh)
|
||||||
|
header_layout.addWidget(self._auto_refresh_btn)
|
||||||
|
|
||||||
|
# 刷新按钮
|
||||||
|
refresh_btn = QPushButton("🔄 刷新")
|
||||||
|
refresh_btn.clicked.connect(self._refresh_logs)
|
||||||
|
header_layout.addWidget(refresh_btn)
|
||||||
|
|
||||||
|
# 清空按钮
|
||||||
|
clear_btn = QPushButton("🗑️ 清空")
|
||||||
|
clear_btn.clicked.connect(self._clear_logs)
|
||||||
|
header_layout.addWidget(clear_btn)
|
||||||
|
|
||||||
|
# 导出按钮
|
||||||
|
export_btn = QPushButton("📥 导出")
|
||||||
|
export_btn.clicked.connect(self._export_logs)
|
||||||
|
header_layout.addWidget(export_btn)
|
||||||
|
|
||||||
|
layout.addLayout(header_layout)
|
||||||
|
|
||||||
|
# 日志显示区域
|
||||||
|
self._log_text = QTextEdit()
|
||||||
|
self._log_text.setReadOnly(True)
|
||||||
|
self._log_text.setFont(QFont("Consolas", 10))
|
||||||
|
self._log_text.setStyleSheet("""
|
||||||
|
QTextEdit {
|
||||||
|
background-color: #1e1e1e;
|
||||||
|
color: #d4d4d4;
|
||||||
|
border: 1px solid #333;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 10px;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
|
||||||
|
# 示例日志
|
||||||
|
self._log_text.setPlainText(self._get_sample_logs())
|
||||||
|
|
||||||
|
layout.addWidget(self._log_text)
|
||||||
|
|
||||||
|
# 状态栏
|
||||||
|
status_layout = QHBoxLayout()
|
||||||
|
|
||||||
|
self._status_label = QLabel("就绪")
|
||||||
|
self._status_label.setStyleSheet("color: #7f8c8d;")
|
||||||
|
status_layout.addWidget(self._status_label)
|
||||||
|
|
||||||
|
status_layout.addStretch()
|
||||||
|
|
||||||
|
self._line_count_label = QLabel("行数: 0")
|
||||||
|
self._line_count_label.setStyleSheet("color: #7f8c8d;")
|
||||||
|
status_layout.addWidget(self._line_count_label)
|
||||||
|
|
||||||
|
layout.addLayout(status_layout)
|
||||||
|
|
||||||
|
# 更新行数
|
||||||
|
self._update_line_count()
|
||||||
|
|
||||||
|
def _get_sample_logs(self) -> str:
|
||||||
|
"""获取示例日志"""
|
||||||
|
return """2024-01-15 09:30:00 INFO [gateway] 服务启动中...
|
||||||
|
2024-01-15 09:30:01 INFO [gateway] Redis 连接成功
|
||||||
|
2024-01-15 09:30:01 INFO [gateway] 数据库连接成功
|
||||||
|
2024-01-15 09:30:02 INFO [gateway] 服务启动完成,监听端口 8001
|
||||||
|
2024-01-15 09:30:05 INFO [core_service] 服务启动中...
|
||||||
|
2024-01-15 09:30:06 INFO [core_service] 服务启动完成,监听端口 8010
|
||||||
|
2024-01-15 09:30:10 INFO [data_service] 服务启动中...
|
||||||
|
2024-01-15 09:30:11 INFO [data_service] 服务启动完成,监听端口 8020
|
||||||
|
2024-01-15 09:30:15 INFO [strategy_engine] 服务启动中...
|
||||||
|
2024-01-15 09:30:15 INFO [strategy_engine] 加载策略: grid, ma_cross, dual_ma
|
||||||
|
2024-01-15 09:30:16 INFO [strategy_engine] 服务启动完成,监听端口 8030
|
||||||
|
2024-01-15 09:30:20 INFO [qmt_adapter] 服务启动中...
|
||||||
|
2024-01-15 09:30:20 WARN [qmt_adapter] XtQuant SDK 未安装,使用模拟模式
|
||||||
|
2024-01-15 09:30:21 INFO [qmt_adapter] 服务启动完成,监听端口 8040
|
||||||
|
2024-01-15 09:31:00 INFO [strategy_engine] 收到行情: 000001.SZ, price=10.50
|
||||||
|
2024-01-15 09:31:00 INFO [strategy_engine] 网格策略触发买入信号
|
||||||
|
2024-01-15 09:31:01 INFO [core_service] 创建订单: 000001.SZ, BUY, 100股
|
||||||
|
2024-01-15 09:31:02 INFO [qmt_adapter] 订单已提交: ORD_20240115_001"""
|
||||||
|
|
||||||
|
def _on_service_changed(self, index: int) -> None:
|
||||||
|
"""服务选择变化"""
|
||||||
|
self._refresh_logs()
|
||||||
|
|
||||||
|
def _toggle_auto_refresh(self, checked: bool) -> None:
|
||||||
|
"""切换自动刷新"""
|
||||||
|
if checked:
|
||||||
|
self._auto_refresh_btn.setText("自动刷新: 开")
|
||||||
|
self._refresh_timer.start(3000) # 3秒刷新一次
|
||||||
|
else:
|
||||||
|
self._auto_refresh_btn.setText("自动刷新: 关")
|
||||||
|
self._refresh_timer.stop()
|
||||||
|
|
||||||
|
def _auto_refresh(self) -> None:
|
||||||
|
"""自动刷新"""
|
||||||
|
self._refresh_logs()
|
||||||
|
|
||||||
|
def _refresh_logs(self) -> None:
|
||||||
|
"""刷新日志"""
|
||||||
|
# TODO: 从日志文件读取
|
||||||
|
self._status_label.setText(f"已刷新 - {datetime.now().strftime('%H:%M:%S')}")
|
||||||
|
self._update_line_count()
|
||||||
|
|
||||||
|
def _clear_logs(self) -> None:
|
||||||
|
"""清空日志显示"""
|
||||||
|
self._log_text.clear()
|
||||||
|
self._update_line_count()
|
||||||
|
|
||||||
|
def _export_logs(self) -> None:
|
||||||
|
"""导出日志"""
|
||||||
|
file_path, _ = QFileDialog.getSaveFileName(
|
||||||
|
self,
|
||||||
|
"导出日志",
|
||||||
|
f"qtrade_log_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt",
|
||||||
|
"Text Files (*.txt);;All Files (*)",
|
||||||
|
)
|
||||||
|
|
||||||
|
if file_path:
|
||||||
|
try:
|
||||||
|
with open(file_path, "w", encoding="utf-8") as f:
|
||||||
|
f.write(self._log_text.toPlainText())
|
||||||
|
self._status_label.setText(f"日志已导出: {file_path}")
|
||||||
|
except Exception as e:
|
||||||
|
self._status_label.setText(f"导出失败: {e}")
|
||||||
|
|
||||||
|
def _update_line_count(self) -> None:
|
||||||
|
"""更新行数"""
|
||||||
|
text = self._log_text.toPlainText()
|
||||||
|
line_count = len(text.split("\n")) if text else 0
|
||||||
|
self._line_count_label.setText(f"行数: {line_count}")
|
||||||
|
|
||||||
|
def closeEvent(self, event) -> None: # type: ignore
|
||||||
|
"""关闭事件"""
|
||||||
|
self._refresh_timer.stop()
|
||||||
|
event.accept()
|
||||||
368
src/console/windows/pages/services_page.py
Normal file
368
src/console/windows/pages/services_page.py
Normal file
@ -0,0 +1,368 @@
|
|||||||
|
"""
|
||||||
|
服务管理页面
|
||||||
|
"""
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
from PyQt6.QtWidgets import (
|
||||||
|
QWidget,
|
||||||
|
QVBoxLayout,
|
||||||
|
QHBoxLayout,
|
||||||
|
QLabel,
|
||||||
|
QPushButton,
|
||||||
|
QTableWidget,
|
||||||
|
QTableWidgetItem,
|
||||||
|
QHeaderView,
|
||||||
|
QMessageBox,
|
||||||
|
)
|
||||||
|
from PyQt6.QtCore import Qt, QTimer, QThread, pyqtSignal
|
||||||
|
from PyQt6.QtGui import QColor
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
|
||||||
|
class ServiceChecker(QThread):
|
||||||
|
"""服务检查线程"""
|
||||||
|
|
||||||
|
status_updated = pyqtSignal(str, bool) # service_name, is_running
|
||||||
|
|
||||||
|
def __init__(self, services: list) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self._services = services
|
||||||
|
self._running = True
|
||||||
|
|
||||||
|
def run(self) -> None:
|
||||||
|
"""运行检查"""
|
||||||
|
for name, port in self._services:
|
||||||
|
if not self._running:
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
response = httpx.get(
|
||||||
|
f"http://127.0.0.1:{port}/ping",
|
||||||
|
timeout=2.0,
|
||||||
|
)
|
||||||
|
is_running = response.status_code == 200
|
||||||
|
except Exception:
|
||||||
|
is_running = False
|
||||||
|
|
||||||
|
self.status_updated.emit(name, is_running)
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
"""停止检查"""
|
||||||
|
self._running = False
|
||||||
|
|
||||||
|
|
||||||
|
class ServicesPage(QWidget):
|
||||||
|
"""服务管理页面"""
|
||||||
|
|
||||||
|
SERVICES = [
|
||||||
|
("gateway", "Gateway", 8001, "API 网关"),
|
||||||
|
("core_service", "Core Service", 8010, "核心服务"),
|
||||||
|
("data_service", "Data Service", 8020, "数据服务"),
|
||||||
|
("strategy_engine", "Strategy Engine", 8030, "策略引擎"),
|
||||||
|
("qmt_adapter", "QMT Adapter", 8040, "QMT 适配器"),
|
||||||
|
]
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self._processes: Dict[str, subprocess.Popen] = {}
|
||||||
|
self._init_ui()
|
||||||
|
|
||||||
|
# 状态检查定时器
|
||||||
|
self._check_timer = QTimer()
|
||||||
|
self._check_timer.timeout.connect(self._check_services)
|
||||||
|
self._check_timer.start(5000)
|
||||||
|
|
||||||
|
# 初始检查
|
||||||
|
QTimer.singleShot(500, self._check_services)
|
||||||
|
|
||||||
|
def _init_ui(self) -> None:
|
||||||
|
"""初始化界面"""
|
||||||
|
layout = QVBoxLayout(self)
|
||||||
|
layout.setContentsMargins(20, 20, 20, 20)
|
||||||
|
layout.setSpacing(20)
|
||||||
|
|
||||||
|
# 标题栏
|
||||||
|
header_layout = QHBoxLayout()
|
||||||
|
|
||||||
|
title = QLabel("服务管理")
|
||||||
|
title.setStyleSheet("""
|
||||||
|
QLabel {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #2c3e50;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
header_layout.addWidget(title)
|
||||||
|
|
||||||
|
header_layout.addStretch()
|
||||||
|
|
||||||
|
# 全局操作按钮
|
||||||
|
start_all_btn = QPushButton("🚀 启动全部")
|
||||||
|
start_all_btn.setStyleSheet(self._get_button_style("#27ae60"))
|
||||||
|
start_all_btn.clicked.connect(self._start_all)
|
||||||
|
header_layout.addWidget(start_all_btn)
|
||||||
|
|
||||||
|
stop_all_btn = QPushButton("⏹️ 停止全部")
|
||||||
|
stop_all_btn.setStyleSheet(self._get_button_style("#e74c3c"))
|
||||||
|
stop_all_btn.clicked.connect(self._stop_all)
|
||||||
|
header_layout.addWidget(stop_all_btn)
|
||||||
|
|
||||||
|
refresh_btn = QPushButton("🔄 刷新状态")
|
||||||
|
refresh_btn.setStyleSheet(self._get_button_style("#3498db"))
|
||||||
|
refresh_btn.clicked.connect(self._check_services)
|
||||||
|
header_layout.addWidget(refresh_btn)
|
||||||
|
|
||||||
|
layout.addLayout(header_layout)
|
||||||
|
|
||||||
|
# 服务表格
|
||||||
|
self._table = QTableWidget()
|
||||||
|
self._table.setColumnCount(6)
|
||||||
|
self._table.setHorizontalHeaderLabels(
|
||||||
|
["服务名称", "端口", "说明", "状态", "PID", "操作"]
|
||||||
|
)
|
||||||
|
|
||||||
|
# 设置表头
|
||||||
|
header = self._table.horizontalHeader()
|
||||||
|
if header is not None:
|
||||||
|
header.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)
|
||||||
|
header.setSectionResizeMode(1, QHeaderView.ResizeMode.Fixed)
|
||||||
|
header.setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch)
|
||||||
|
header.setSectionResizeMode(3, QHeaderView.ResizeMode.Fixed)
|
||||||
|
header.setSectionResizeMode(4, QHeaderView.ResizeMode.Fixed)
|
||||||
|
header.setSectionResizeMode(5, QHeaderView.ResizeMode.Fixed)
|
||||||
|
|
||||||
|
self._table.setColumnWidth(0, 150)
|
||||||
|
self._table.setColumnWidth(1, 80)
|
||||||
|
self._table.setColumnWidth(3, 100)
|
||||||
|
self._table.setColumnWidth(4, 80)
|
||||||
|
self._table.setColumnWidth(5, 200)
|
||||||
|
|
||||||
|
self._table.setStyleSheet("""
|
||||||
|
QTableWidget {
|
||||||
|
background-color: white;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 8px;
|
||||||
|
gridline-color: #eee;
|
||||||
|
}
|
||||||
|
QTableWidget::item {
|
||||||
|
padding: 10px;
|
||||||
|
}
|
||||||
|
QHeaderView::section {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
padding: 10px;
|
||||||
|
border: none;
|
||||||
|
border-bottom: 1px solid #ddd;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
|
||||||
|
v_header = self._table.verticalHeader()
|
||||||
|
if v_header is not None:
|
||||||
|
v_header.setVisible(False)
|
||||||
|
self._table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
|
||||||
|
self._table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
|
||||||
|
|
||||||
|
# 填充表格
|
||||||
|
self._table.setRowCount(len(self.SERVICES))
|
||||||
|
for row, (key, name, port, desc) in enumerate(self.SERVICES):
|
||||||
|
self._table.setRowHeight(row, 60)
|
||||||
|
|
||||||
|
# 服务名
|
||||||
|
name_item = QTableWidgetItem(name)
|
||||||
|
name_item.setData(Qt.ItemDataRole.UserRole, key)
|
||||||
|
self._table.setItem(row, 0, name_item)
|
||||||
|
|
||||||
|
# 端口
|
||||||
|
port_item = QTableWidgetItem(str(port))
|
||||||
|
port_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
self._table.setItem(row, 1, port_item)
|
||||||
|
|
||||||
|
# 说明
|
||||||
|
self._table.setItem(row, 2, QTableWidgetItem(desc))
|
||||||
|
|
||||||
|
# 状态
|
||||||
|
status_item = QTableWidgetItem("检测中...")
|
||||||
|
status_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
self._table.setItem(row, 3, status_item)
|
||||||
|
|
||||||
|
# PID
|
||||||
|
pid_item = QTableWidgetItem("-")
|
||||||
|
pid_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
self._table.setItem(row, 4, pid_item)
|
||||||
|
|
||||||
|
# 操作按钮
|
||||||
|
btn_widget = QWidget()
|
||||||
|
btn_layout = QHBoxLayout(btn_widget)
|
||||||
|
btn_layout.setContentsMargins(5, 5, 5, 5)
|
||||||
|
btn_layout.setSpacing(5)
|
||||||
|
|
||||||
|
start_btn = QPushButton("启动")
|
||||||
|
start_btn.setStyleSheet(self._get_small_button_style("#27ae60"))
|
||||||
|
start_btn.setProperty("service_key", key)
|
||||||
|
start_btn.clicked.connect(lambda checked, k=key: self._start_service(k))
|
||||||
|
btn_layout.addWidget(start_btn)
|
||||||
|
|
||||||
|
stop_btn = QPushButton("停止")
|
||||||
|
stop_btn.setStyleSheet(self._get_small_button_style("#e74c3c"))
|
||||||
|
stop_btn.setProperty("service_key", key)
|
||||||
|
stop_btn.clicked.connect(lambda checked, k=key: self._stop_service(k))
|
||||||
|
btn_layout.addWidget(stop_btn)
|
||||||
|
|
||||||
|
log_btn = QPushButton("日志")
|
||||||
|
log_btn.setStyleSheet(self._get_small_button_style("#9b59b6"))
|
||||||
|
log_btn.clicked.connect(lambda checked, k=key: self._view_logs(k))
|
||||||
|
btn_layout.addWidget(log_btn)
|
||||||
|
|
||||||
|
self._table.setCellWidget(row, 5, btn_widget)
|
||||||
|
|
||||||
|
layout.addWidget(self._table)
|
||||||
|
|
||||||
|
def _check_services(self) -> None:
|
||||||
|
"""检查服务状态"""
|
||||||
|
services = [(name, port) for _, name, port, _ in self.SERVICES]
|
||||||
|
self._checker = ServiceChecker(services)
|
||||||
|
self._checker.status_updated.connect(self._on_status_updated)
|
||||||
|
self._checker.start()
|
||||||
|
|
||||||
|
def _on_status_updated(self, name: str, is_running: bool) -> None:
|
||||||
|
"""状态更新回调"""
|
||||||
|
for row in range(self._table.rowCount()):
|
||||||
|
name_item = self._table.item(row, 0)
|
||||||
|
status_item = self._table.item(row, 3)
|
||||||
|
if name_item is not None and name_item.text() == name:
|
||||||
|
if status_item is not None:
|
||||||
|
if is_running:
|
||||||
|
status_item.setText("✅ 运行中")
|
||||||
|
status_item.setForeground(QColor("#27ae60"))
|
||||||
|
else:
|
||||||
|
status_item.setText("⭕ 已停止")
|
||||||
|
status_item.setForeground(QColor("#95a5a6"))
|
||||||
|
break
|
||||||
|
|
||||||
|
def _start_service(self, service_key: str) -> None:
|
||||||
|
"""启动服务"""
|
||||||
|
if service_key in self._processes:
|
||||||
|
proc = self._processes[service_key]
|
||||||
|
if proc.poll() is None: # 还在运行
|
||||||
|
QMessageBox.warning(self, "提示", f"服务 {service_key} 已在运行中")
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 启动进程
|
||||||
|
proc = subprocess.Popen(
|
||||||
|
["python", "-m", "src.main", service_key],
|
||||||
|
cwd=str(self._get_project_root()),
|
||||||
|
creationflags=subprocess.CREATE_NEW_CONSOLE,
|
||||||
|
)
|
||||||
|
self._processes[service_key] = proc
|
||||||
|
|
||||||
|
# 更新 PID
|
||||||
|
for row in range(self._table.rowCount()):
|
||||||
|
item = self._table.item(row, 0)
|
||||||
|
if (
|
||||||
|
item is not None
|
||||||
|
and item.data(Qt.ItemDataRole.UserRole) == service_key
|
||||||
|
):
|
||||||
|
pid_item = self._table.item(row, 4)
|
||||||
|
if pid_item is not None:
|
||||||
|
pid_item.setText(str(proc.pid))
|
||||||
|
break
|
||||||
|
|
||||||
|
QMessageBox.information(self, "成功", f"服务 {service_key} 已启动")
|
||||||
|
|
||||||
|
# 延迟检查状态
|
||||||
|
QTimer.singleShot(2000, self._check_services)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
QMessageBox.critical(self, "错误", f"启动失败: {e}")
|
||||||
|
|
||||||
|
def _stop_service(self, service_key: str) -> None:
|
||||||
|
"""停止服务"""
|
||||||
|
if service_key in self._processes:
|
||||||
|
proc = self._processes[service_key]
|
||||||
|
if proc.poll() is None:
|
||||||
|
proc.terminate()
|
||||||
|
try:
|
||||||
|
proc.wait(timeout=5)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
proc.kill()
|
||||||
|
|
||||||
|
del self._processes[service_key]
|
||||||
|
|
||||||
|
# 更新 PID
|
||||||
|
for row in range(self._table.rowCount()):
|
||||||
|
item = self._table.item(row, 0)
|
||||||
|
if (
|
||||||
|
item is not None
|
||||||
|
and item.data(Qt.ItemDataRole.UserRole) == service_key
|
||||||
|
):
|
||||||
|
pid_item = self._table.item(row, 4)
|
||||||
|
if pid_item is not None:
|
||||||
|
pid_item.setText("-")
|
||||||
|
break
|
||||||
|
|
||||||
|
QMessageBox.information(self, "成功", f"服务 {service_key} 已停止")
|
||||||
|
QTimer.singleShot(1000, self._check_services)
|
||||||
|
return
|
||||||
|
|
||||||
|
QMessageBox.warning(self, "提示", f"服务 {service_key} 未在本控制台启动")
|
||||||
|
|
||||||
|
def _start_all(self) -> None:
|
||||||
|
"""启动全部服务"""
|
||||||
|
for key, _, _, _ in self.SERVICES:
|
||||||
|
self._start_service(key)
|
||||||
|
|
||||||
|
def _stop_all(self) -> None:
|
||||||
|
"""停止全部服务"""
|
||||||
|
for key in list(self._processes.keys()):
|
||||||
|
self._stop_service(key)
|
||||||
|
|
||||||
|
def _view_logs(self, service_key: str) -> None:
|
||||||
|
"""查看日志"""
|
||||||
|
QMessageBox.information(self, "提示", f"日志功能开发中: {service_key}")
|
||||||
|
|
||||||
|
def _get_project_root(self):
|
||||||
|
"""获取项目根目录"""
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
return Path(__file__).parent.parent.parent.parent.parent
|
||||||
|
|
||||||
|
def _get_button_style(self, color: str) -> str:
|
||||||
|
"""获取按钮样式"""
|
||||||
|
return f"""
|
||||||
|
QPushButton {{
|
||||||
|
background-color: {color};
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 8px 16px;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: bold;
|
||||||
|
}}
|
||||||
|
QPushButton:hover {{
|
||||||
|
background-color: {color}dd;
|
||||||
|
}}
|
||||||
|
"""
|
||||||
|
|
||||||
|
def _get_small_button_style(self, color: str) -> str:
|
||||||
|
"""获取小按钮样式"""
|
||||||
|
return f"""
|
||||||
|
QPushButton {{
|
||||||
|
background-color: {color};
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 5px 10px;
|
||||||
|
font-size: 12px;
|
||||||
|
}}
|
||||||
|
QPushButton:hover {{
|
||||||
|
background-color: {color}dd;
|
||||||
|
}}
|
||||||
|
"""
|
||||||
|
|
||||||
|
def closeEvent(self, event) -> None: # type: ignore
|
||||||
|
"""关闭事件"""
|
||||||
|
self._check_timer.stop()
|
||||||
|
event.accept()
|
||||||
423
src/console/windows/pages/settings_page.py
Normal file
423
src/console/windows/pages/settings_page.py
Normal file
@ -0,0 +1,423 @@
|
|||||||
|
"""
|
||||||
|
系统设置页面
|
||||||
|
"""
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PyQt6.QtWidgets import (
|
||||||
|
QWidget,
|
||||||
|
QVBoxLayout,
|
||||||
|
QHBoxLayout,
|
||||||
|
QLabel,
|
||||||
|
QPushButton,
|
||||||
|
QLineEdit,
|
||||||
|
QSpinBox,
|
||||||
|
QFormLayout,
|
||||||
|
QTabWidget,
|
||||||
|
QMessageBox,
|
||||||
|
QCheckBox,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class SettingsPage(QWidget):
|
||||||
|
"""系统设置页面"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self._init_ui()
|
||||||
|
self._load_config()
|
||||||
|
|
||||||
|
def _init_ui(self) -> None:
|
||||||
|
"""初始化界面"""
|
||||||
|
layout = QVBoxLayout(self)
|
||||||
|
layout.setContentsMargins(20, 20, 20, 20)
|
||||||
|
layout.setSpacing(20)
|
||||||
|
|
||||||
|
# 标题
|
||||||
|
title = QLabel("系统设置")
|
||||||
|
title.setStyleSheet("""
|
||||||
|
QLabel {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #2c3e50;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
layout.addWidget(title)
|
||||||
|
|
||||||
|
# Tab 页
|
||||||
|
tab_widget = QTabWidget()
|
||||||
|
tab_widget.setStyleSheet("""
|
||||||
|
QTabWidget::pane {
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 8px;
|
||||||
|
background-color: white;
|
||||||
|
}
|
||||||
|
QTabBar::tab {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
padding: 10px 20px;
|
||||||
|
margin-right: 2px;
|
||||||
|
border-top-left-radius: 6px;
|
||||||
|
border-top-right-radius: 6px;
|
||||||
|
}
|
||||||
|
QTabBar::tab:selected {
|
||||||
|
background-color: white;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
|
||||||
|
# Redis 配置
|
||||||
|
redis_tab = self._create_redis_tab()
|
||||||
|
tab_widget.addTab(redis_tab, "Redis 配置")
|
||||||
|
|
||||||
|
# MySQL 配置
|
||||||
|
mysql_tab = self._create_mysql_tab()
|
||||||
|
tab_widget.addTab(mysql_tab, "MySQL 配置")
|
||||||
|
|
||||||
|
# QMT 配置
|
||||||
|
qmt_tab = self._create_qmt_tab()
|
||||||
|
tab_widget.addTab(qmt_tab, "QMT 配置")
|
||||||
|
|
||||||
|
# 服务端口配置
|
||||||
|
ports_tab = self._create_ports_tab()
|
||||||
|
tab_widget.addTab(ports_tab, "服务端口")
|
||||||
|
|
||||||
|
layout.addWidget(tab_widget)
|
||||||
|
|
||||||
|
# 保存按钮
|
||||||
|
btn_layout = QHBoxLayout()
|
||||||
|
btn_layout.addStretch()
|
||||||
|
|
||||||
|
reset_btn = QPushButton("重置")
|
||||||
|
reset_btn.setFixedWidth(100)
|
||||||
|
reset_btn.clicked.connect(self._load_config)
|
||||||
|
btn_layout.addWidget(reset_btn)
|
||||||
|
|
||||||
|
save_btn = QPushButton("保存配置")
|
||||||
|
save_btn.setFixedWidth(100)
|
||||||
|
save_btn.setStyleSheet("""
|
||||||
|
QPushButton {
|
||||||
|
background-color: #3498db;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 10px;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
QPushButton:hover {
|
||||||
|
background-color: #2980b9;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
save_btn.clicked.connect(self._save_config)
|
||||||
|
btn_layout.addWidget(save_btn)
|
||||||
|
|
||||||
|
layout.addLayout(btn_layout)
|
||||||
|
|
||||||
|
def _create_redis_tab(self) -> QWidget:
|
||||||
|
"""创建 Redis 配置 Tab"""
|
||||||
|
widget = QWidget()
|
||||||
|
layout = QVBoxLayout(widget)
|
||||||
|
layout.setContentsMargins(20, 20, 20, 20)
|
||||||
|
|
||||||
|
form = QFormLayout()
|
||||||
|
form.setSpacing(15)
|
||||||
|
|
||||||
|
self._redis_host = QLineEdit()
|
||||||
|
self._redis_host.setPlaceholderText("127.0.0.1")
|
||||||
|
form.addRow("主机地址:", self._redis_host)
|
||||||
|
|
||||||
|
self._redis_port = QSpinBox()
|
||||||
|
self._redis_port.setRange(1, 65535)
|
||||||
|
self._redis_port.setValue(6379)
|
||||||
|
form.addRow("端口:", self._redis_port)
|
||||||
|
|
||||||
|
self._redis_password = QLineEdit()
|
||||||
|
self._redis_password.setEchoMode(QLineEdit.EchoMode.Password)
|
||||||
|
self._redis_password.setPlaceholderText("留空表示无密码")
|
||||||
|
form.addRow("密码:", self._redis_password)
|
||||||
|
|
||||||
|
self._redis_db = QSpinBox()
|
||||||
|
self._redis_db.setRange(0, 15)
|
||||||
|
self._redis_db.setValue(0)
|
||||||
|
form.addRow("数据库:", self._redis_db)
|
||||||
|
|
||||||
|
layout.addLayout(form)
|
||||||
|
|
||||||
|
# 测试连接按钮
|
||||||
|
test_btn = QPushButton("测试连接")
|
||||||
|
test_btn.setFixedWidth(100)
|
||||||
|
test_btn.clicked.connect(self._test_redis)
|
||||||
|
layout.addWidget(test_btn)
|
||||||
|
|
||||||
|
layout.addStretch()
|
||||||
|
return widget
|
||||||
|
|
||||||
|
def _create_mysql_tab(self) -> QWidget:
|
||||||
|
"""创建 MySQL 配置 Tab"""
|
||||||
|
widget = QWidget()
|
||||||
|
layout = QVBoxLayout(widget)
|
||||||
|
layout.setContentsMargins(20, 20, 20, 20)
|
||||||
|
|
||||||
|
form = QFormLayout()
|
||||||
|
form.setSpacing(15)
|
||||||
|
|
||||||
|
self._mysql_host = QLineEdit()
|
||||||
|
self._mysql_host.setPlaceholderText("127.0.0.1")
|
||||||
|
form.addRow("主机地址:", self._mysql_host)
|
||||||
|
|
||||||
|
self._mysql_port = QSpinBox()
|
||||||
|
self._mysql_port.setRange(1, 65535)
|
||||||
|
self._mysql_port.setValue(3306)
|
||||||
|
form.addRow("端口:", self._mysql_port)
|
||||||
|
|
||||||
|
self._mysql_user = QLineEdit()
|
||||||
|
self._mysql_user.setPlaceholderText("root")
|
||||||
|
form.addRow("用户名:", self._mysql_user)
|
||||||
|
|
||||||
|
self._mysql_password = QLineEdit()
|
||||||
|
self._mysql_password.setEchoMode(QLineEdit.EchoMode.Password)
|
||||||
|
form.addRow("密码:", self._mysql_password)
|
||||||
|
|
||||||
|
self._mysql_database = QLineEdit()
|
||||||
|
self._mysql_database.setPlaceholderText("qtrade")
|
||||||
|
form.addRow("数据库名:", self._mysql_database)
|
||||||
|
|
||||||
|
layout.addLayout(form)
|
||||||
|
|
||||||
|
# 测试连接按钮
|
||||||
|
test_btn = QPushButton("测试连接")
|
||||||
|
test_btn.setFixedWidth(100)
|
||||||
|
test_btn.clicked.connect(self._test_mysql)
|
||||||
|
layout.addWidget(test_btn)
|
||||||
|
|
||||||
|
layout.addStretch()
|
||||||
|
return widget
|
||||||
|
|
||||||
|
def _create_qmt_tab(self) -> QWidget:
|
||||||
|
"""创建 QMT 配置 Tab"""
|
||||||
|
widget = QWidget()
|
||||||
|
layout = QVBoxLayout(widget)
|
||||||
|
layout.setContentsMargins(20, 20, 20, 20)
|
||||||
|
|
||||||
|
form = QFormLayout()
|
||||||
|
form.setSpacing(15)
|
||||||
|
|
||||||
|
self._qmt_path = QLineEdit()
|
||||||
|
self._qmt_path.setPlaceholderText("D:/QMT/userdata_mini")
|
||||||
|
form.addRow("QMT 路径:", self._qmt_path)
|
||||||
|
|
||||||
|
self._qmt_account = QLineEdit()
|
||||||
|
self._qmt_account.setPlaceholderText("资金账号")
|
||||||
|
form.addRow("资金账号:", self._qmt_account)
|
||||||
|
|
||||||
|
self._qmt_session_id = QSpinBox()
|
||||||
|
self._qmt_session_id.setRange(1, 999999)
|
||||||
|
self._qmt_session_id.setValue(123456)
|
||||||
|
form.addRow("会话 ID:", self._qmt_session_id)
|
||||||
|
|
||||||
|
self._qmt_simulation = QCheckBox("启用模拟模式")
|
||||||
|
self._qmt_simulation.setChecked(True)
|
||||||
|
form.addRow("", self._qmt_simulation)
|
||||||
|
|
||||||
|
layout.addLayout(form)
|
||||||
|
|
||||||
|
# 提示
|
||||||
|
tip = QLabel("提示: QMT 路径为 Mini QMT 的 userdata_mini 目录")
|
||||||
|
tip.setStyleSheet("color: #7f8c8d; font-size: 12px;")
|
||||||
|
layout.addWidget(tip)
|
||||||
|
|
||||||
|
layout.addStretch()
|
||||||
|
return widget
|
||||||
|
|
||||||
|
def _create_ports_tab(self) -> QWidget:
|
||||||
|
"""创建服务端口配置 Tab"""
|
||||||
|
widget = QWidget()
|
||||||
|
layout = QVBoxLayout(widget)
|
||||||
|
layout.setContentsMargins(20, 20, 20, 20)
|
||||||
|
|
||||||
|
form = QFormLayout()
|
||||||
|
form.setSpacing(15)
|
||||||
|
|
||||||
|
self._port_gateway = QSpinBox()
|
||||||
|
self._port_gateway.setRange(1, 65535)
|
||||||
|
self._port_gateway.setValue(8001)
|
||||||
|
form.addRow("Gateway:", self._port_gateway)
|
||||||
|
|
||||||
|
self._port_core = QSpinBox()
|
||||||
|
self._port_core.setRange(1, 65535)
|
||||||
|
self._port_core.setValue(8010)
|
||||||
|
form.addRow("Core Service:", self._port_core)
|
||||||
|
|
||||||
|
self._port_data = QSpinBox()
|
||||||
|
self._port_data.setRange(1, 65535)
|
||||||
|
self._port_data.setValue(8020)
|
||||||
|
form.addRow("Data Service:", self._port_data)
|
||||||
|
|
||||||
|
self._port_strategy = QSpinBox()
|
||||||
|
self._port_strategy.setRange(1, 65535)
|
||||||
|
self._port_strategy.setValue(8030)
|
||||||
|
form.addRow("Strategy Engine:", self._port_strategy)
|
||||||
|
|
||||||
|
self._port_qmt = QSpinBox()
|
||||||
|
self._port_qmt.setRange(1, 65535)
|
||||||
|
self._port_qmt.setValue(8040)
|
||||||
|
form.addRow("QMT Adapter:", self._port_qmt)
|
||||||
|
|
||||||
|
layout.addLayout(form)
|
||||||
|
layout.addStretch()
|
||||||
|
return widget
|
||||||
|
|
||||||
|
def _get_config_path(self) -> Path:
|
||||||
|
"""获取配置文件路径"""
|
||||||
|
return (
|
||||||
|
Path(__file__).parent.parent.parent.parent.parent
|
||||||
|
/ "configs"
|
||||||
|
/ "settings.yaml"
|
||||||
|
)
|
||||||
|
|
||||||
|
def _load_config(self) -> None:
|
||||||
|
"""加载配置"""
|
||||||
|
config_path = self._get_config_path()
|
||||||
|
if not config_path.exists():
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(config_path, "r", encoding="utf-8") as f:
|
||||||
|
config = yaml.safe_load(f) or {}
|
||||||
|
|
||||||
|
# Redis
|
||||||
|
redis = config.get("redis", {})
|
||||||
|
self._redis_host.setText(redis.get("host", "127.0.0.1"))
|
||||||
|
self._redis_port.setValue(redis.get("port", 6379))
|
||||||
|
self._redis_password.setText(redis.get("password", ""))
|
||||||
|
self._redis_db.setValue(redis.get("db", 0))
|
||||||
|
|
||||||
|
# MySQL
|
||||||
|
db = config.get("database", {})
|
||||||
|
self._mysql_host.setText(db.get("host", "127.0.0.1"))
|
||||||
|
self._mysql_port.setValue(db.get("port", 3306))
|
||||||
|
self._mysql_user.setText(db.get("user", "root"))
|
||||||
|
self._mysql_password.setText(db.get("password", ""))
|
||||||
|
self._mysql_database.setText(db.get("database", "qtrade"))
|
||||||
|
|
||||||
|
# QMT
|
||||||
|
qmt = config.get("qmt", {})
|
||||||
|
self._qmt_path.setText(qmt.get("path", ""))
|
||||||
|
self._qmt_account.setText(qmt.get("account_id", ""))
|
||||||
|
self._qmt_session_id.setValue(qmt.get("session_id", 123456))
|
||||||
|
self._qmt_simulation.setChecked(qmt.get("simulation", True))
|
||||||
|
|
||||||
|
# 服务端口
|
||||||
|
services = config.get("services", {})
|
||||||
|
self._port_gateway.setValue(services.get("gateway", {}).get("port", 8001))
|
||||||
|
self._port_core.setValue(services.get("core_service", {}).get("port", 8010))
|
||||||
|
self._port_data.setValue(services.get("data_service", {}).get("port", 8020))
|
||||||
|
self._port_strategy.setValue(
|
||||||
|
services.get("strategy_engine", {}).get("port", 8030)
|
||||||
|
)
|
||||||
|
self._port_qmt.setValue(services.get("qmt_adapter", {}).get("port", 8040))
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
QMessageBox.warning(self, "警告", f"加载配置失败: {e}")
|
||||||
|
|
||||||
|
def _save_config(self) -> None:
|
||||||
|
"""保存配置"""
|
||||||
|
config_path = self._get_config_path()
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 读取现有配置
|
||||||
|
if config_path.exists():
|
||||||
|
with open(config_path, "r", encoding="utf-8") as f:
|
||||||
|
config = yaml.safe_load(f) or {}
|
||||||
|
else:
|
||||||
|
config = {}
|
||||||
|
|
||||||
|
# 更新配置
|
||||||
|
config["redis"] = {
|
||||||
|
"host": self._redis_host.text() or "127.0.0.1",
|
||||||
|
"port": self._redis_port.value(),
|
||||||
|
"password": self._redis_password.text(),
|
||||||
|
"db": self._redis_db.value(),
|
||||||
|
"pool_size": config.get("redis", {}).get("pool_size", 10),
|
||||||
|
"pool_timeout": config.get("redis", {}).get("pool_timeout", 30),
|
||||||
|
}
|
||||||
|
|
||||||
|
config["database"] = {
|
||||||
|
"host": self._mysql_host.text() or "127.0.0.1",
|
||||||
|
"port": self._mysql_port.value(),
|
||||||
|
"user": self._mysql_user.text() or "root",
|
||||||
|
"password": self._mysql_password.text(),
|
||||||
|
"database": self._mysql_database.text() or "qtrade",
|
||||||
|
"pool_size": config.get("database", {}).get("pool_size", 5),
|
||||||
|
"pool_recycle": config.get("database", {}).get("pool_recycle", 3600),
|
||||||
|
"echo": config.get("database", {}).get("echo", False),
|
||||||
|
}
|
||||||
|
|
||||||
|
config["qmt"] = {
|
||||||
|
"path": self._qmt_path.text(),
|
||||||
|
"session_id": self._qmt_session_id.value(),
|
||||||
|
"account_id": self._qmt_account.text(),
|
||||||
|
"simulation": self._qmt_simulation.isChecked(),
|
||||||
|
}
|
||||||
|
|
||||||
|
config["services"] = {
|
||||||
|
"gateway": {"host": "0.0.0.0", "port": self._port_gateway.value()},
|
||||||
|
"core_service": {"host": "0.0.0.0", "port": self._port_core.value()},
|
||||||
|
"data_service": {"host": "0.0.0.0", "port": self._port_data.value()},
|
||||||
|
"strategy_engine": {
|
||||||
|
"host": "0.0.0.0",
|
||||||
|
"port": self._port_strategy.value(),
|
||||||
|
},
|
||||||
|
"qmt_adapter": {"host": "0.0.0.0", "port": self._port_qmt.value()},
|
||||||
|
}
|
||||||
|
|
||||||
|
# 保存
|
||||||
|
with open(config_path, "w", encoding="utf-8") as f:
|
||||||
|
yaml.dump(
|
||||||
|
config,
|
||||||
|
f,
|
||||||
|
allow_unicode=True,
|
||||||
|
default_flow_style=False,
|
||||||
|
sort_keys=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
QMessageBox.information(self, "成功", "配置已保存,重启服务后生效")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
QMessageBox.critical(self, "错误", f"保存配置失败: {e}")
|
||||||
|
|
||||||
|
def _test_redis(self) -> None:
|
||||||
|
"""测试 Redis 连接"""
|
||||||
|
try:
|
||||||
|
import redis
|
||||||
|
|
||||||
|
client = redis.Redis(
|
||||||
|
host=self._redis_host.text() or "127.0.0.1",
|
||||||
|
port=self._redis_port.value(),
|
||||||
|
password=self._redis_password.text() or None,
|
||||||
|
db=self._redis_db.value(),
|
||||||
|
socket_timeout=5,
|
||||||
|
)
|
||||||
|
client.ping()
|
||||||
|
QMessageBox.information(self, "成功", "Redis 连接成功!")
|
||||||
|
except Exception as e:
|
||||||
|
QMessageBox.critical(self, "失败", f"Redis 连接失败: {e}")
|
||||||
|
|
||||||
|
def _test_mysql(self) -> None:
|
||||||
|
"""测试 MySQL 连接"""
|
||||||
|
try:
|
||||||
|
import pymysql
|
||||||
|
|
||||||
|
conn = pymysql.connect(
|
||||||
|
host=self._mysql_host.text() or "127.0.0.1",
|
||||||
|
port=self._mysql_port.value(),
|
||||||
|
user=self._mysql_user.text() or "root",
|
||||||
|
password=self._mysql_password.text(),
|
||||||
|
database=self._mysql_database.text() or "qtrade",
|
||||||
|
connect_timeout=5,
|
||||||
|
)
|
||||||
|
conn.close()
|
||||||
|
QMessageBox.information(self, "成功", "MySQL 连接成功!")
|
||||||
|
except Exception as e:
|
||||||
|
QMessageBox.critical(self, "失败", f"MySQL 连接失败: {e}")
|
||||||
413
src/console/windows/pages/strategies_page.py
Normal file
413
src/console/windows/pages/strategies_page.py
Normal file
@ -0,0 +1,413 @@
|
|||||||
|
"""
|
||||||
|
策略配置页面
|
||||||
|
"""
|
||||||
|
|
||||||
|
from PyQt6.QtWidgets import (
|
||||||
|
QWidget,
|
||||||
|
QVBoxLayout,
|
||||||
|
QHBoxLayout,
|
||||||
|
QLabel,
|
||||||
|
QFrame,
|
||||||
|
QPushButton,
|
||||||
|
QTableWidget,
|
||||||
|
QTableWidgetItem,
|
||||||
|
QHeaderView,
|
||||||
|
QDialog,
|
||||||
|
QFormLayout,
|
||||||
|
QLineEdit,
|
||||||
|
QComboBox,
|
||||||
|
QDoubleSpinBox,
|
||||||
|
QMessageBox,
|
||||||
|
QSpinBox,
|
||||||
|
)
|
||||||
|
from PyQt6.QtCore import Qt # noqa: F401 用于 AlignmentFlag
|
||||||
|
from PyQt6.QtGui import QColor
|
||||||
|
|
||||||
|
|
||||||
|
class AddPairingDialog(QDialog):
|
||||||
|
"""添加配对对话框"""
|
||||||
|
|
||||||
|
STRATEGIES = [
|
||||||
|
("grid", "网格策略"),
|
||||||
|
("ma_cross", "均线交叉"),
|
||||||
|
("dual_ma", "双均线策略"),
|
||||||
|
]
|
||||||
|
|
||||||
|
def __init__(self, parent=None) -> None:
|
||||||
|
super().__init__(parent)
|
||||||
|
self.setWindowTitle("新建策略配对")
|
||||||
|
self.setFixedSize(500, 500)
|
||||||
|
self._init_ui()
|
||||||
|
|
||||||
|
def _init_ui(self) -> None:
|
||||||
|
"""初始化界面"""
|
||||||
|
layout = QVBoxLayout(self)
|
||||||
|
layout.setSpacing(15)
|
||||||
|
|
||||||
|
form = QFormLayout()
|
||||||
|
form.setSpacing(10)
|
||||||
|
|
||||||
|
# 股票代码
|
||||||
|
self._code_input = QLineEdit()
|
||||||
|
self._code_input.setPlaceholderText("例如: 000001.SZ")
|
||||||
|
form.addRow("股票代码:", self._code_input)
|
||||||
|
|
||||||
|
# 策略选择
|
||||||
|
self._strategy_combo = QComboBox()
|
||||||
|
for key, name in self.STRATEGIES:
|
||||||
|
self._strategy_combo.addItem(name, key)
|
||||||
|
self._strategy_combo.currentIndexChanged.connect(self._on_strategy_changed)
|
||||||
|
form.addRow("策略类型:", self._strategy_combo)
|
||||||
|
|
||||||
|
# 初始资金
|
||||||
|
self._capital_input = QDoubleSpinBox()
|
||||||
|
self._capital_input.setRange(1000, 10000000)
|
||||||
|
self._capital_input.setValue(100000)
|
||||||
|
self._capital_input.setPrefix("¥ ")
|
||||||
|
self._capital_input.setDecimals(2)
|
||||||
|
form.addRow("初始资金:", self._capital_input)
|
||||||
|
|
||||||
|
layout.addLayout(form)
|
||||||
|
|
||||||
|
# 策略参数区域
|
||||||
|
params_label = QLabel("策略参数:")
|
||||||
|
params_label.setStyleSheet("font-weight: bold;")
|
||||||
|
layout.addWidget(params_label)
|
||||||
|
|
||||||
|
self._params_frame = QFrame()
|
||||||
|
self._params_frame.setStyleSheet("""
|
||||||
|
QFrame {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 10px;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
self._params_layout = QFormLayout(self._params_frame)
|
||||||
|
layout.addWidget(self._params_frame)
|
||||||
|
|
||||||
|
# 初始化参数表单
|
||||||
|
self._on_strategy_changed(0)
|
||||||
|
|
||||||
|
layout.addStretch()
|
||||||
|
|
||||||
|
# 按钮
|
||||||
|
btn_layout = QHBoxLayout()
|
||||||
|
btn_layout.addStretch()
|
||||||
|
|
||||||
|
cancel_btn = QPushButton("取消")
|
||||||
|
cancel_btn.setFixedWidth(80)
|
||||||
|
cancel_btn.clicked.connect(self.reject)
|
||||||
|
btn_layout.addWidget(cancel_btn)
|
||||||
|
|
||||||
|
confirm_btn = QPushButton("确认")
|
||||||
|
confirm_btn.setFixedWidth(80)
|
||||||
|
confirm_btn.setStyleSheet("""
|
||||||
|
QPushButton {
|
||||||
|
background-color: #3498db;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 8px;
|
||||||
|
}
|
||||||
|
QPushButton:hover {
|
||||||
|
background-color: #2980b9;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
confirm_btn.clicked.connect(self._on_confirm)
|
||||||
|
btn_layout.addWidget(confirm_btn)
|
||||||
|
|
||||||
|
layout.addLayout(btn_layout)
|
||||||
|
|
||||||
|
def _on_strategy_changed(self, index: int) -> None:
|
||||||
|
"""策略切换"""
|
||||||
|
# 清空参数表单
|
||||||
|
while self._params_layout.count():
|
||||||
|
item = self._params_layout.takeAt(0)
|
||||||
|
if item is not None:
|
||||||
|
widget = item.widget()
|
||||||
|
if widget is not None:
|
||||||
|
widget.deleteLater()
|
||||||
|
|
||||||
|
strategy_key = self._strategy_combo.currentData()
|
||||||
|
|
||||||
|
if strategy_key == "grid":
|
||||||
|
# 网格策略参数
|
||||||
|
self._upper_price = QDoubleSpinBox()
|
||||||
|
self._upper_price.setRange(0.01, 9999)
|
||||||
|
self._upper_price.setValue(15.0)
|
||||||
|
self._params_layout.addRow("上限价格:", self._upper_price)
|
||||||
|
|
||||||
|
self._lower_price = QDoubleSpinBox()
|
||||||
|
self._lower_price.setRange(0.01, 9999)
|
||||||
|
self._lower_price.setValue(10.0)
|
||||||
|
self._params_layout.addRow("下限价格:", self._lower_price)
|
||||||
|
|
||||||
|
self._grid_count = QSpinBox()
|
||||||
|
self._grid_count.setRange(2, 100)
|
||||||
|
self._grid_count.setValue(10)
|
||||||
|
self._params_layout.addRow("网格数量:", self._grid_count)
|
||||||
|
|
||||||
|
elif strategy_key in ("ma_cross", "dual_ma"):
|
||||||
|
# 均线策略参数
|
||||||
|
self._short_period = QSpinBox()
|
||||||
|
self._short_period.setRange(1, 100)
|
||||||
|
self._short_period.setValue(5)
|
||||||
|
self._params_layout.addRow("短期均线:", self._short_period)
|
||||||
|
|
||||||
|
self._long_period = QSpinBox()
|
||||||
|
self._long_period.setRange(1, 500)
|
||||||
|
self._long_period.setValue(20)
|
||||||
|
self._params_layout.addRow("长期均线:", self._long_period)
|
||||||
|
|
||||||
|
if strategy_key == "dual_ma":
|
||||||
|
self._stop_loss = QDoubleSpinBox()
|
||||||
|
self._stop_loss.setRange(0.01, 0.5)
|
||||||
|
self._stop_loss.setValue(0.05)
|
||||||
|
self._stop_loss.setSuffix(" %")
|
||||||
|
self._params_layout.addRow("止损比例:", self._stop_loss)
|
||||||
|
|
||||||
|
self._take_profit = QDoubleSpinBox()
|
||||||
|
self._take_profit.setRange(0.01, 1.0)
|
||||||
|
self._take_profit.setValue(0.10)
|
||||||
|
self._take_profit.setSuffix(" %")
|
||||||
|
self._params_layout.addRow("止盈比例:", self._take_profit)
|
||||||
|
|
||||||
|
def _on_confirm(self) -> None:
|
||||||
|
"""确认"""
|
||||||
|
code = self._code_input.text().strip()
|
||||||
|
if not code:
|
||||||
|
QMessageBox.warning(self, "提示", "请输入股票代码")
|
||||||
|
return
|
||||||
|
|
||||||
|
self.accept()
|
||||||
|
|
||||||
|
def get_data(self) -> dict:
|
||||||
|
"""获取数据"""
|
||||||
|
strategy_key = self._strategy_combo.currentData()
|
||||||
|
|
||||||
|
params = {}
|
||||||
|
if strategy_key == "grid":
|
||||||
|
params = {
|
||||||
|
"upper_price": self._upper_price.value(),
|
||||||
|
"lower_price": self._lower_price.value(),
|
||||||
|
"grid_count": self._grid_count.value(),
|
||||||
|
}
|
||||||
|
elif strategy_key == "ma_cross":
|
||||||
|
params = {
|
||||||
|
"short_period": self._short_period.value(),
|
||||||
|
"long_period": self._long_period.value(),
|
||||||
|
}
|
||||||
|
elif strategy_key == "dual_ma":
|
||||||
|
params = {
|
||||||
|
"short_period": self._short_period.value(),
|
||||||
|
"long_period": self._long_period.value(),
|
||||||
|
"stop_loss": self._stop_loss.value(),
|
||||||
|
"take_profit": self._take_profit.value(),
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"symbol": self._code_input.text().strip(),
|
||||||
|
"strategy_id": strategy_key,
|
||||||
|
"initial_capital": self._capital_input.value(),
|
||||||
|
"params": params,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class StrategiesPage(QWidget):
|
||||||
|
"""策略配置页面"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self._init_ui()
|
||||||
|
|
||||||
|
def _init_ui(self) -> None:
|
||||||
|
"""初始化界面"""
|
||||||
|
layout = QVBoxLayout(self)
|
||||||
|
layout.setContentsMargins(20, 20, 20, 20)
|
||||||
|
layout.setSpacing(20)
|
||||||
|
|
||||||
|
# 标题栏
|
||||||
|
header_layout = QHBoxLayout()
|
||||||
|
|
||||||
|
title = QLabel("策略配置")
|
||||||
|
title.setStyleSheet("""
|
||||||
|
QLabel {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #2c3e50;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
header_layout.addWidget(title)
|
||||||
|
|
||||||
|
header_layout.addStretch()
|
||||||
|
|
||||||
|
# 添加按钮
|
||||||
|
add_btn = QPushButton("➕ 新建配对")
|
||||||
|
add_btn.setStyleSheet("""
|
||||||
|
QPushButton {
|
||||||
|
background-color: #27ae60;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 8px 16px;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
QPushButton:hover {
|
||||||
|
background-color: #219a52;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
add_btn.clicked.connect(self._add_pairing)
|
||||||
|
header_layout.addWidget(add_btn)
|
||||||
|
|
||||||
|
layout.addLayout(header_layout)
|
||||||
|
|
||||||
|
# 配对表格
|
||||||
|
self._table = QTableWidget()
|
||||||
|
self._table.setColumnCount(6)
|
||||||
|
self._table.setHorizontalHeaderLabels(
|
||||||
|
["股票代码", "策略", "状态", "初始资金", "当前盈亏", "操作"]
|
||||||
|
)
|
||||||
|
|
||||||
|
header = self._table.horizontalHeader()
|
||||||
|
if header is not None:
|
||||||
|
header.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)
|
||||||
|
header.setSectionResizeMode(1, QHeaderView.ResizeMode.Fixed)
|
||||||
|
header.setSectionResizeMode(2, QHeaderView.ResizeMode.Fixed)
|
||||||
|
header.setSectionResizeMode(3, QHeaderView.ResizeMode.Fixed)
|
||||||
|
header.setSectionResizeMode(4, QHeaderView.ResizeMode.Stretch)
|
||||||
|
header.setSectionResizeMode(5, QHeaderView.ResizeMode.Fixed)
|
||||||
|
|
||||||
|
self._table.setColumnWidth(0, 120)
|
||||||
|
self._table.setColumnWidth(1, 120)
|
||||||
|
self._table.setColumnWidth(2, 100)
|
||||||
|
self._table.setColumnWidth(3, 120)
|
||||||
|
self._table.setColumnWidth(5, 180)
|
||||||
|
|
||||||
|
self._table.setStyleSheet("""
|
||||||
|
QTableWidget {
|
||||||
|
background-color: white;
|
||||||
|
border: 1px solid #ddd;
|
||||||
|
border-radius: 8px;
|
||||||
|
gridline-color: #eee;
|
||||||
|
}
|
||||||
|
QTableWidget::item {
|
||||||
|
padding: 10px;
|
||||||
|
}
|
||||||
|
QHeaderView::section {
|
||||||
|
background-color: #f8f9fa;
|
||||||
|
padding: 10px;
|
||||||
|
border: none;
|
||||||
|
border-bottom: 1px solid #ddd;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
|
||||||
|
v_header = self._table.verticalHeader()
|
||||||
|
if v_header is not None:
|
||||||
|
v_header.setVisible(False)
|
||||||
|
self._table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
|
||||||
|
self._table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
|
||||||
|
|
||||||
|
layout.addWidget(self._table)
|
||||||
|
|
||||||
|
# 加载示例数据
|
||||||
|
self._load_sample_data()
|
||||||
|
|
||||||
|
def _load_sample_data(self) -> None:
|
||||||
|
"""加载示例数据"""
|
||||||
|
sample_data = [
|
||||||
|
("000001.SZ", "网格策略", "运行中", 100000, 5230.50),
|
||||||
|
("600000.SH", "双均线策略", "已暂停", 50000, -1200.00),
|
||||||
|
]
|
||||||
|
|
||||||
|
self._table.setRowCount(len(sample_data))
|
||||||
|
|
||||||
|
for row, (code, strategy, status, capital, pnl) in enumerate(sample_data):
|
||||||
|
self._table.setRowHeight(row, 55)
|
||||||
|
|
||||||
|
# 股票代码
|
||||||
|
self._table.setItem(row, 0, QTableWidgetItem(code))
|
||||||
|
|
||||||
|
# 策略
|
||||||
|
self._table.setItem(row, 1, QTableWidgetItem(strategy))
|
||||||
|
|
||||||
|
# 状态
|
||||||
|
status_item = QTableWidgetItem(status)
|
||||||
|
status_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
if status == "运行中":
|
||||||
|
status_item.setForeground(QColor("#27ae60"))
|
||||||
|
else:
|
||||||
|
status_item.setForeground(QColor("#95a5a6"))
|
||||||
|
self._table.setItem(row, 2, status_item)
|
||||||
|
|
||||||
|
# 初始资金
|
||||||
|
capital_item = QTableWidgetItem(f"¥{capital:,.2f}")
|
||||||
|
capital_item.setTextAlignment(
|
||||||
|
Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter
|
||||||
|
)
|
||||||
|
self._table.setItem(row, 3, capital_item)
|
||||||
|
|
||||||
|
# 盈亏
|
||||||
|
pnl_item = QTableWidgetItem(f"¥{pnl:+,.2f}")
|
||||||
|
pnl_item.setTextAlignment(
|
||||||
|
Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter
|
||||||
|
)
|
||||||
|
if pnl >= 0:
|
||||||
|
pnl_item.setForeground(QColor("#e74c3c"))
|
||||||
|
else:
|
||||||
|
pnl_item.setForeground(QColor("#27ae60"))
|
||||||
|
self._table.setItem(row, 4, pnl_item)
|
||||||
|
|
||||||
|
# 操作按钮
|
||||||
|
btn_widget = QWidget()
|
||||||
|
btn_layout = QHBoxLayout(btn_widget)
|
||||||
|
btn_layout.setContentsMargins(5, 5, 5, 5)
|
||||||
|
btn_layout.setSpacing(5)
|
||||||
|
|
||||||
|
if status == "运行中":
|
||||||
|
pause_btn = QPushButton("暂停")
|
||||||
|
pause_btn.setStyleSheet(self._get_small_button_style("#f39c12"))
|
||||||
|
btn_layout.addWidget(pause_btn)
|
||||||
|
else:
|
||||||
|
start_btn = QPushButton("启动")
|
||||||
|
start_btn.setStyleSheet(self._get_small_button_style("#27ae60"))
|
||||||
|
btn_layout.addWidget(start_btn)
|
||||||
|
|
||||||
|
edit_btn = QPushButton("编辑")
|
||||||
|
edit_btn.setStyleSheet(self._get_small_button_style("#3498db"))
|
||||||
|
btn_layout.addWidget(edit_btn)
|
||||||
|
|
||||||
|
delete_btn = QPushButton("删除")
|
||||||
|
delete_btn.setStyleSheet(self._get_small_button_style("#e74c3c"))
|
||||||
|
btn_layout.addWidget(delete_btn)
|
||||||
|
|
||||||
|
self._table.setCellWidget(row, 5, btn_widget)
|
||||||
|
|
||||||
|
def _add_pairing(self) -> None:
|
||||||
|
"""添加配对"""
|
||||||
|
dialog = AddPairingDialog(self)
|
||||||
|
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||||
|
data = dialog.get_data()
|
||||||
|
QMessageBox.information(
|
||||||
|
self,
|
||||||
|
"成功",
|
||||||
|
f"已创建配对:\n股票: {data['symbol']}\n策略: {data['strategy_id']}\n资金: ¥{data['initial_capital']:,.2f}",
|
||||||
|
)
|
||||||
|
# TODO: 调用 API 创建配对
|
||||||
|
|
||||||
|
def _get_small_button_style(self, color: str) -> str:
|
||||||
|
"""获取小按钮样式"""
|
||||||
|
return f"""
|
||||||
|
QPushButton {{
|
||||||
|
background-color: {color};
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 5px 10px;
|
||||||
|
font-size: 12px;
|
||||||
|
}}
|
||||||
|
QPushButton:hover {{
|
||||||
|
background-color: {color}dd;
|
||||||
|
}}
|
||||||
|
"""
|
||||||
Loading…
Reference in New Issue
Block a user