feat: 多环境配置架构改造 (v0.2)
- 支持三套独立环境:实盘(production)、回测(backtest)、模拟(simulation) - 环境完全隔离:独立数据库、Redis频道前缀、端口范围 - 配置系统改造: * 新增环境配置类(EnvironmentConfig)和频道配置类(RedisChannels) * 数据库名、Redis频道自动根据环境切换 * 支持从环境变量(CONFIG_FILE)加载配置 - Redis频道动态化: * RedisChannels类改为使用动态前缀 * 信号/订单频道使用统一配置 - 数据库初始化: * 创建三个独立数据库(QTrade_RealTrade/BackTestTrade/SimuTrade) * 提供Python初始化脚本 - 清理冗余代码: * 删除废弃的services配置目录 * 删除旧的启动脚本和初始化脚本 * 删除未使用的backtest目录 - 新增工具脚本: * start_services.py - 多环境服务启动 * init_databases.py - 数据库初始化 * test_config.py - 配置测试 环境映射: - production: DB=QTrade_RealTrade, Redis=real:, Port=9000+ - backtest: DB=QTrade_BackTestTrade, Redis=bt:, Port=10000+ - simulation: DB=QTrade_SimuTrade, Redis=simu:, Port=11000+
This commit is contained in:
parent
f13bf9b7fd
commit
2f721650c9
3
.env.backtest
Normal file
3
.env.backtest
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# 回测环境变量配置
|
||||||
|
ENV=backtest
|
||||||
|
CONFIG_FILE=configs/backtest.yaml
|
||||||
3
.env.production
Normal file
3
.env.production
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# 实盘环境变量配置
|
||||||
|
ENV=production
|
||||||
|
CONFIG_FILE=configs/production.yaml
|
||||||
3
.env.simulation
Normal file
3
.env.simulation
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# 模拟环境变量配置
|
||||||
|
ENV=simulation
|
||||||
|
CONFIG_FILE=configs/simulation.yaml
|
||||||
82
configs/backtest.yaml
Normal file
82
configs/backtest.yaml
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
# QTrade 回测环境配置
|
||||||
|
# 数据库: QTrade_BackTestTrade
|
||||||
|
# Redis前缀: bt:
|
||||||
|
# 端口范围: 10000-10999
|
||||||
|
|
||||||
|
# 环境配置
|
||||||
|
environment:
|
||||||
|
env: "backtest"
|
||||||
|
db_name: "QTrade_BackTestTrade"
|
||||||
|
redis_prefix: "bt"
|
||||||
|
port_offset: 10000
|
||||||
|
|
||||||
|
# 应用配置
|
||||||
|
app:
|
||||||
|
name: "QTrade-Backtest"
|
||||||
|
version: "2.0.0"
|
||||||
|
env: "backtest"
|
||||||
|
debug: true
|
||||||
|
|
||||||
|
# Redis 配置
|
||||||
|
redis:
|
||||||
|
host: "127.0.0.1"
|
||||||
|
port: 6379
|
||||||
|
password: ""
|
||||||
|
db: 1 # 使用不同的Redis DB
|
||||||
|
pool_size: 10
|
||||||
|
pool_timeout: 30
|
||||||
|
|
||||||
|
# MySQL 配置
|
||||||
|
database:
|
||||||
|
host: "127.0.0.1"
|
||||||
|
port: 3306
|
||||||
|
user: "root"
|
||||||
|
password: "1234"
|
||||||
|
# db_name 由 environment.db_name 提供
|
||||||
|
pool_size: 5
|
||||||
|
pool_recycle: 3600
|
||||||
|
echo: false
|
||||||
|
|
||||||
|
# 日志配置
|
||||||
|
logging:
|
||||||
|
level: "DEBUG"
|
||||||
|
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||||
|
file:
|
||||||
|
enabled: true
|
||||||
|
path: "logs/backtest"
|
||||||
|
max_size: 10485760
|
||||||
|
backup_count: 5
|
||||||
|
|
||||||
|
# 行情配置
|
||||||
|
market:
|
||||||
|
kline_periods:
|
||||||
|
- "1m"
|
||||||
|
- "5m"
|
||||||
|
- "15m"
|
||||||
|
- "30m"
|
||||||
|
- "60m"
|
||||||
|
- "1d"
|
||||||
|
- "1w"
|
||||||
|
cache_ttl: 60
|
||||||
|
|
||||||
|
# 交易配置
|
||||||
|
trading:
|
||||||
|
sessions:
|
||||||
|
morning:
|
||||||
|
start: "09:30"
|
||||||
|
end: "11:30"
|
||||||
|
afternoon:
|
||||||
|
start: "13:00"
|
||||||
|
end: "15:00"
|
||||||
|
|
||||||
|
# 服务端口配置
|
||||||
|
services:
|
||||||
|
data_service:
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 10001
|
||||||
|
strategy_engine:
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 10003
|
||||||
|
backtest_service:
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 10007
|
||||||
88
configs/production.yaml
Normal file
88
configs/production.yaml
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
# QTrade 实盘环境配置
|
||||||
|
# 数据库: QTrade_RealTrade
|
||||||
|
# Redis前缀: real:
|
||||||
|
# 端口范围: 9000-9999
|
||||||
|
|
||||||
|
# 环境配置
|
||||||
|
environment:
|
||||||
|
env: "production"
|
||||||
|
db_name: "QTrade_RealTrade"
|
||||||
|
redis_prefix: "real"
|
||||||
|
port_offset: 9000
|
||||||
|
|
||||||
|
# 应用配置
|
||||||
|
app:
|
||||||
|
name: "QTrade"
|
||||||
|
version: "2.0.0"
|
||||||
|
env: "production"
|
||||||
|
debug: false
|
||||||
|
|
||||||
|
# Redis 配置
|
||||||
|
redis:
|
||||||
|
host: "127.0.0.1"
|
||||||
|
port: 6379
|
||||||
|
password: ""
|
||||||
|
db: 0
|
||||||
|
pool_size: 10
|
||||||
|
pool_timeout: 30
|
||||||
|
|
||||||
|
# MySQL 配置
|
||||||
|
database:
|
||||||
|
host: "127.0.0.1"
|
||||||
|
port: 3306
|
||||||
|
user: "root"
|
||||||
|
password: "1234"
|
||||||
|
# db_name 由 environment.db_name 提供
|
||||||
|
pool_size: 5
|
||||||
|
pool_recycle: 3600
|
||||||
|
echo: false
|
||||||
|
|
||||||
|
# 日志配置
|
||||||
|
logging:
|
||||||
|
level: "INFO"
|
||||||
|
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||||
|
file:
|
||||||
|
enabled: true
|
||||||
|
path: "logs/production"
|
||||||
|
max_size: 10485760
|
||||||
|
backup_count: 10
|
||||||
|
|
||||||
|
# 行情配置
|
||||||
|
market:
|
||||||
|
kline_periods:
|
||||||
|
- "1m"
|
||||||
|
- "5m"
|
||||||
|
- "15m"
|
||||||
|
- "30m"
|
||||||
|
- "60m"
|
||||||
|
- "1d"
|
||||||
|
- "1w"
|
||||||
|
cache_ttl: 60
|
||||||
|
|
||||||
|
# 交易配置
|
||||||
|
trading:
|
||||||
|
sessions:
|
||||||
|
morning:
|
||||||
|
start: "09:30"
|
||||||
|
end: "11:30"
|
||||||
|
afternoon:
|
||||||
|
start: "13:00"
|
||||||
|
end: "15:00"
|
||||||
|
|
||||||
|
# 服务端口配置
|
||||||
|
services:
|
||||||
|
core_service:
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 9010
|
||||||
|
data_service:
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 9001
|
||||||
|
strategy_engine:
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 9003
|
||||||
|
trade_service:
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 9005
|
||||||
|
qmt_service:
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 9007
|
||||||
@ -1,8 +0,0 @@
|
|||||||
# Core Service 配置
|
|
||||||
|
|
||||||
service:
|
|
||||||
name: "CoreService"
|
|
||||||
host: "0.0.0.0"
|
|
||||||
port: 8010
|
|
||||||
workers: 1
|
|
||||||
reload: true
|
|
||||||
@ -1,17 +0,0 @@
|
|||||||
# Data Service 配置
|
|
||||||
|
|
||||||
service:
|
|
||||||
name: "DataService"
|
|
||||||
host: "0.0.0.0"
|
|
||||||
port: 8020
|
|
||||||
workers: 1
|
|
||||||
reload: true # 开发模式自动重载
|
|
||||||
|
|
||||||
# 数据下载配置
|
|
||||||
data_download:
|
|
||||||
# 默认下载天数
|
|
||||||
default_days: 120
|
|
||||||
# 批量下载并发数
|
|
||||||
batch_size: 10
|
|
||||||
# 下载超时(秒)
|
|
||||||
timeout: 60
|
|
||||||
@ -1,29 +0,0 @@
|
|||||||
# QMT Service 配置
|
|
||||||
|
|
||||||
service:
|
|
||||||
name: "QMTService"
|
|
||||||
host: "0.0.0.0"
|
|
||||||
port: 8040
|
|
||||||
workers: 1
|
|
||||||
reload: true
|
|
||||||
|
|
||||||
# QMT 客户端配置
|
|
||||||
qmt:
|
|
||||||
# QMT 客户端路径 (Mini QMT 安装目录)
|
|
||||||
path: "D:/国金证券QMT/userdata_mini"
|
|
||||||
# 会话 ID
|
|
||||||
session_id: 123456
|
|
||||||
# 资金账号
|
|
||||||
account_id: ""
|
|
||||||
# 是否启用模拟模式
|
|
||||||
simulation: true
|
|
||||||
# 数据中心 Token (用于 xtquant 独立数据下载)
|
|
||||||
data_token: "e83d8eec5226c0b4db4a1d40830e09e4ffe73e15"
|
|
||||||
# 优化地址列表
|
|
||||||
optimize_addresses:
|
|
||||||
- "115.231.218.73:55310"
|
|
||||||
- "115.231.218.79:55310"
|
|
||||||
- "218.16.123.11:55310"
|
|
||||||
- "218.16.123.27:55310"
|
|
||||||
# XtQuant 数据存储目录
|
|
||||||
data_home_dir: "caches/xtquant"
|
|
||||||
@ -1,17 +0,0 @@
|
|||||||
# Strategy Engine 配置
|
|
||||||
|
|
||||||
service:
|
|
||||||
name: "StrategyEngine"
|
|
||||||
host: "0.0.0.0"
|
|
||||||
port: 8030
|
|
||||||
workers: 1
|
|
||||||
reload: true
|
|
||||||
|
|
||||||
# 策略引擎配置
|
|
||||||
strategy:
|
|
||||||
# 策略自动加载路径
|
|
||||||
auto_load_path: "src/strategies"
|
|
||||||
# 策略实例检查间隔(秒)
|
|
||||||
check_interval: 5
|
|
||||||
# 是否启用行情监听
|
|
||||||
enable_tick_listener: true
|
|
||||||
82
configs/simulation.yaml
Normal file
82
configs/simulation.yaml
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
# QTrade 模拟环境配置
|
||||||
|
# 数据库: QTrade_SimuTrade
|
||||||
|
# Redis前缀: simu:
|
||||||
|
# 端口范围: 11000-11999
|
||||||
|
|
||||||
|
# 环境配置
|
||||||
|
environment:
|
||||||
|
env: "simulation"
|
||||||
|
db_name: "QTrade_SimuTrade"
|
||||||
|
redis_prefix: "simu"
|
||||||
|
port_offset: 11000
|
||||||
|
|
||||||
|
# 应用配置
|
||||||
|
app:
|
||||||
|
name: "QTrade-Simulation"
|
||||||
|
version: "2.0.0"
|
||||||
|
env: "simulation"
|
||||||
|
debug: true
|
||||||
|
|
||||||
|
# Redis 配置
|
||||||
|
redis:
|
||||||
|
host: "127.0.0.1"
|
||||||
|
port: 6379
|
||||||
|
password: ""
|
||||||
|
db: 2 # 使用不同的Redis DB
|
||||||
|
pool_size: 10
|
||||||
|
pool_timeout: 30
|
||||||
|
|
||||||
|
# MySQL 配置
|
||||||
|
database:
|
||||||
|
host: "127.0.0.1"
|
||||||
|
port: 3306
|
||||||
|
user: "root"
|
||||||
|
password: "1234"
|
||||||
|
# db_name 由 environment.db_name 提供
|
||||||
|
pool_size: 5
|
||||||
|
pool_recycle: 3600
|
||||||
|
echo: false
|
||||||
|
|
||||||
|
# 日志配置
|
||||||
|
logging:
|
||||||
|
level: "DEBUG"
|
||||||
|
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||||
|
file:
|
||||||
|
enabled: true
|
||||||
|
path: "logs/simulation"
|
||||||
|
max_size: 10485760
|
||||||
|
backup_count: 5
|
||||||
|
|
||||||
|
# 行情配置
|
||||||
|
market:
|
||||||
|
kline_periods:
|
||||||
|
- "1m"
|
||||||
|
- "5m"
|
||||||
|
- "15m"
|
||||||
|
- "30m"
|
||||||
|
- "60m"
|
||||||
|
- "1d"
|
||||||
|
- "1w"
|
||||||
|
cache_ttl: 60
|
||||||
|
|
||||||
|
# 交易配置
|
||||||
|
trading:
|
||||||
|
sessions:
|
||||||
|
morning:
|
||||||
|
start: "09:30"
|
||||||
|
end: "11:30"
|
||||||
|
afternoon:
|
||||||
|
start: "13:00"
|
||||||
|
end: "15:00"
|
||||||
|
|
||||||
|
# 服务端口配置
|
||||||
|
services:
|
||||||
|
data_service:
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 11001
|
||||||
|
strategy_engine:
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 11003
|
||||||
|
trade_service:
|
||||||
|
host: "0.0.0.0"
|
||||||
|
port: 11005
|
||||||
245
docs/multi_env_guide.md
Normal file
245
docs/multi_env_guide.md
Normal file
@ -0,0 +1,245 @@
|
|||||||
|
# QTrade 多环境配置说明
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
QTrade 支持三套完全隔离的运行环境:
|
||||||
|
|
||||||
|
| 环境 | 数据库 | Redis前缀 | 端口范围 | 用途 |
|
||||||
|
| ---------- | -------------------- | --------- | ----------- | -------- |
|
||||||
|
| production | QTrade_RealTrade | real: | 9000-9999 | 实盘交易 |
|
||||||
|
| backtest | QTrade_BackTestTrade | bt: | 10000-10999 | 策略回测 |
|
||||||
|
| simulation | QTrade_SimuTrade | simu: | 11000-11999 | 模拟交易 |
|
||||||
|
|
||||||
|
## 环境隔离
|
||||||
|
|
||||||
|
### 1. 数据库隔离
|
||||||
|
每个环境使用独立的MySQL数据库:
|
||||||
|
- 实盘: `QTrade_RealTrade`
|
||||||
|
- 回测: `QTrade_BackTestTrade`
|
||||||
|
- 模拟: `QTrade_SimuTrade`
|
||||||
|
|
||||||
|
### 2. Redis频道隔离
|
||||||
|
每个环境使用独立的频道前缀:
|
||||||
|
- 实盘: `real:kline:update`, `real:signal:create`
|
||||||
|
- 回测: `bt:kline:update`, `bt:signal:create`
|
||||||
|
- 模拟: `simu:kline:update`, `simu:signal:create`
|
||||||
|
|
||||||
|
### 3. 端口隔离
|
||||||
|
每个环境使用独立的端口范围:
|
||||||
|
- 实盘: 9000-9999
|
||||||
|
- 回测: 10000-10999
|
||||||
|
- 模拟: 11000-11999
|
||||||
|
|
||||||
|
### 4. 日志隔离
|
||||||
|
每个环境使用独立的日志目录:
|
||||||
|
- 实盘: `logs/production/`
|
||||||
|
- 回测: `logs/backtest/`
|
||||||
|
- 模拟: `logs/simulation/`
|
||||||
|
|
||||||
|
## 初始化
|
||||||
|
|
||||||
|
### 1. 创建数据库
|
||||||
|
```bash
|
||||||
|
# 连接MySQL
|
||||||
|
mysql -u root -p
|
||||||
|
|
||||||
|
# 执行初始化脚本
|
||||||
|
source scripts/init_databases.sql;
|
||||||
|
```
|
||||||
|
|
||||||
|
或直接执行:
|
||||||
|
```bash
|
||||||
|
mysql -u root -p < scripts/init_databases.sql
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 运行数据库迁移
|
||||||
|
```bash
|
||||||
|
# 实盘环境
|
||||||
|
alembic --config configs/production.yaml upgrade head
|
||||||
|
|
||||||
|
# 回测环境
|
||||||
|
alembic --config configs/backtest.yaml upgrade head
|
||||||
|
|
||||||
|
# 模拟环境
|
||||||
|
alembic --config configs/simulation.yaml upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
|
## 启动服务
|
||||||
|
|
||||||
|
### 使用启动脚本(推荐)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 启动实盘环境
|
||||||
|
python scripts/start_services.py production data_service strategy_engine trade_service
|
||||||
|
|
||||||
|
# 启动回测环境
|
||||||
|
python scripts/start_services.py backtest data_service strategy_engine backtest_service
|
||||||
|
|
||||||
|
# 启动模拟环境
|
||||||
|
python scripts/start_services.py simulation data_service strategy_engine trade_service
|
||||||
|
```
|
||||||
|
|
||||||
|
### 手动启动
|
||||||
|
|
||||||
|
**实盘环境**:
|
||||||
|
```bash
|
||||||
|
uvicorn src.data_service.app:app --env-file .env.production
|
||||||
|
uvicorn src.strategy_engine.app:app --env-file .env.production
|
||||||
|
uvicorn src.trade_service.app:app --env-file .env.production
|
||||||
|
```
|
||||||
|
|
||||||
|
**回测环境**:
|
||||||
|
```bash
|
||||||
|
uvicorn src.data_service.app:app --env-file .env.backtest
|
||||||
|
uvicorn src.strategy_engine.app:app --env-file .env.backtest
|
||||||
|
uvicorn src.backtest_service.app:app --env-file .env.backtest
|
||||||
|
```
|
||||||
|
|
||||||
|
**模拟环境**:
|
||||||
|
```bash
|
||||||
|
uvicorn src.data_service.app:app --env-file .env.simulation
|
||||||
|
uvicorn src.strategy_engine.app:app --env-file .env.simulation
|
||||||
|
uvicorn src.trade_service.app:app --env-file .env.simulation
|
||||||
|
```
|
||||||
|
|
||||||
|
## 配置文件
|
||||||
|
|
||||||
|
### 环境配置文件
|
||||||
|
- `configs/production.yaml` - 实盘环境配置
|
||||||
|
- `configs/backtest.yaml` - 回测环境配置
|
||||||
|
- `configs/simulation.yaml` - 模拟环境配置
|
||||||
|
|
||||||
|
### 环境变量文件
|
||||||
|
- `.env.production` - 实盘环境变量
|
||||||
|
- `.env.backtest` - 回测环境变量
|
||||||
|
- `.env.simulation` - 模拟环境变量
|
||||||
|
|
||||||
|
## 代码中使用
|
||||||
|
|
||||||
|
### 获取环境配置
|
||||||
|
```python
|
||||||
|
from src.core.config import settings
|
||||||
|
|
||||||
|
# 当前环境
|
||||||
|
env = settings.environment.env # "production" | "backtest" | "simulation"
|
||||||
|
|
||||||
|
# 数据库名称
|
||||||
|
db_name = settings.environment.db_name # "QTrade_RealTrade" 等
|
||||||
|
|
||||||
|
# Redis前缀
|
||||||
|
prefix = settings.environment.redis_prefix # "real" | "bt" | "simu"
|
||||||
|
|
||||||
|
# 端口偏移
|
||||||
|
offset = settings.environment.port_offset # 9000 | 10000 | 11000
|
||||||
|
```
|
||||||
|
|
||||||
|
### 获取频道名称
|
||||||
|
```python
|
||||||
|
from src.core.config import settings
|
||||||
|
|
||||||
|
# K线更新频道
|
||||||
|
kline_channel = settings.channels.kline_update
|
||||||
|
# production: "real:kline:update"
|
||||||
|
# backtest: "bt:kline:update"
|
||||||
|
# simulation: "simu:kline:update"
|
||||||
|
|
||||||
|
# 信号创建频道
|
||||||
|
signal_channel = settings.channels.signal_create
|
||||||
|
# production: "real:signal:create"
|
||||||
|
# backtest: "bt:signal:create"
|
||||||
|
# simulation: "simu:signal:create"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 订阅/发布
|
||||||
|
```python
|
||||||
|
import redis.asyncio as redis
|
||||||
|
from src.core.config import settings
|
||||||
|
|
||||||
|
# 发布K线数据
|
||||||
|
async def publish_kline(kline_data):
|
||||||
|
r = redis.from_url(settings.redis.url)
|
||||||
|
await r.publish(settings.channels.kline_update, kline_data)
|
||||||
|
|
||||||
|
# 订阅信号
|
||||||
|
async def subscribe_signals():
|
||||||
|
r = redis.from_url(settings.redis.url)
|
||||||
|
pubsub = r.pubsub()
|
||||||
|
await pubsub.subscribe(settings.channels.signal_create)
|
||||||
|
|
||||||
|
async for message in pubsub.listen():
|
||||||
|
# 处理信号
|
||||||
|
pass
|
||||||
|
```
|
||||||
|
|
||||||
|
## 服务端口分配
|
||||||
|
|
||||||
|
### 实盘环境 (9000-9999)
|
||||||
|
- DataService: 9001
|
||||||
|
- StrategyEngine: 9003
|
||||||
|
- TradeService: 9005
|
||||||
|
- QMTService: 9007
|
||||||
|
|
||||||
|
### 回测环境 (10000-10999)
|
||||||
|
- DataService: 10001
|
||||||
|
- StrategyEngine: 10003
|
||||||
|
- BacktestService: 10007
|
||||||
|
|
||||||
|
### 模拟环境 (11000-11999)
|
||||||
|
- DataService: 11001
|
||||||
|
- StrategyEngine: 11003
|
||||||
|
- TradeService: 11005
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
### 1. 环境切换
|
||||||
|
切换环境时,请确保:
|
||||||
|
- 使用正确的环境变量文件
|
||||||
|
- 配置文件中的环境设置正确
|
||||||
|
- 端口不冲突
|
||||||
|
|
||||||
|
### 2. 数据隔离
|
||||||
|
三个环境的数据完全隔离:
|
||||||
|
- 实盘数据不会影响回测
|
||||||
|
- 回测数据不会影响模拟
|
||||||
|
- 各环境可以同时运行
|
||||||
|
|
||||||
|
### 3. Redis DB分离
|
||||||
|
为了进一步隔离,建议使用不同的Redis DB:
|
||||||
|
- 实盘: db=0
|
||||||
|
- 回测: db=1
|
||||||
|
- 模拟: db=2
|
||||||
|
|
||||||
|
### 4. 日志管理
|
||||||
|
各环境日志独立存储,便于问题排查:
|
||||||
|
```
|
||||||
|
logs/
|
||||||
|
├── production/
|
||||||
|
│ ├── data_service.log
|
||||||
|
│ └── strategy_engine.log
|
||||||
|
├── backtest/
|
||||||
|
│ └── backtest_service.log
|
||||||
|
└── simulation/
|
||||||
|
└── trade_service.log
|
||||||
|
```
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### Q: 如何同时运行多个环境?
|
||||||
|
A: 由于端口和数据库完全隔离,可以同时启动三个环境的服务。
|
||||||
|
|
||||||
|
### Q: 环境之间如何切换?
|
||||||
|
A: 使用不同的环境变量文件启动服务即可,或使用启动脚本指定环境。
|
||||||
|
|
||||||
|
### Q: 回测环境可以访问实盘数据吗?
|
||||||
|
A: 不可以。各环境数据库完全独立,如需共享数据请手动迁移或同步。
|
||||||
|
|
||||||
|
### Q: 如何清理某个环境的数据?
|
||||||
|
A: 直接清空对应的数据库即可,不影响其他环境。
|
||||||
|
|
||||||
|
## 最佳实践
|
||||||
|
|
||||||
|
1. **开发阶段**: 使用回测环境或模拟环境
|
||||||
|
2. **测试阶段**: 使用模拟环境验证策略
|
||||||
|
3. **生产阶段**: 使用实盘环境进行真实交易
|
||||||
|
4. **数据备份**: 定期备份各环境数据库
|
||||||
|
5. **日志监控**: 监控各环境日志,及时发现问题
|
||||||
108
scripts/init_databases.py
Normal file
108
scripts/init_databases.py
Normal file
@ -0,0 +1,108 @@
|
|||||||
|
"""
|
||||||
|
初始化多环境数据库
|
||||||
|
|
||||||
|
创建三个独立的数据库:
|
||||||
|
- QTrade_RealTrade (实盘)
|
||||||
|
- QTrade_BackTestTrade (回测)
|
||||||
|
- QTrade_SimuTrade (模拟)
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pymysql
|
||||||
|
from pymysql.err import OperationalError
|
||||||
|
|
||||||
|
# 添加项目路径
|
||||||
|
project_root = Path(__file__).parent.parent
|
||||||
|
sys.path.insert(0, str(project_root))
|
||||||
|
|
||||||
|
from src.core.config import settings
|
||||||
|
|
||||||
|
|
||||||
|
def init_databases():
|
||||||
|
"""初始化三个环境的数据库"""
|
||||||
|
|
||||||
|
# 数据库连接配置(不指定具体数据库)
|
||||||
|
db_config = {
|
||||||
|
"host": settings.database._manager.get("database.host", "127.0.0.1"),
|
||||||
|
"port": settings.database._manager.get("database.port", 3306),
|
||||||
|
"user": settings.database._manager.get("database.user", "root"),
|
||||||
|
"password": settings.database._manager.get("database.password", "1234"),
|
||||||
|
"charset": "utf8mb4",
|
||||||
|
}
|
||||||
|
|
||||||
|
databases = ["QTrade_RealTrade", "QTrade_BackTestTrade", "QTrade_SimuTrade"]
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 连接MySQL服务器
|
||||||
|
print(f"连接MySQL服务器: {db_config['host']}:{db_config['port']}")
|
||||||
|
conn = pymysql.connect(**db_config)
|
||||||
|
cursor = conn.cursor()
|
||||||
|
|
||||||
|
print("\n开始创建数据库...\n")
|
||||||
|
|
||||||
|
for db_name in databases:
|
||||||
|
try:
|
||||||
|
# 创建数据库
|
||||||
|
sql = f"""
|
||||||
|
CREATE DATABASE IF NOT EXISTS {db_name}
|
||||||
|
DEFAULT CHARACTER SET utf8mb4
|
||||||
|
COLLATE utf8mb4_unicode_ci
|
||||||
|
"""
|
||||||
|
cursor.execute(sql)
|
||||||
|
print(f"✓ 数据库创建成功: {db_name}")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"✗ 创建数据库失败 {db_name}: {e}")
|
||||||
|
|
||||||
|
# 显示创建的数据库
|
||||||
|
print("\n查询已创建的数据库:")
|
||||||
|
cursor.execute("SHOW DATABASES LIKE 'QTrade_%'")
|
||||||
|
results = cursor.fetchall()
|
||||||
|
|
||||||
|
for row in results:
|
||||||
|
print(f" - {row[0]}")
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
cursor.close()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
print("\n✅ 数据库初始化完成")
|
||||||
|
return True
|
||||||
|
|
||||||
|
except OperationalError as e:
|
||||||
|
print(f"\n❌ 连接MySQL失败: {e}")
|
||||||
|
print("\n请确保:")
|
||||||
|
print(" 1. MySQL服务正在运行")
|
||||||
|
print(" 2. 用户名和密码正确")
|
||||||
|
print(" 3. 防火墙允许连接")
|
||||||
|
return False
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"\n❌ 初始化失败: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print("=" * 60)
|
||||||
|
print("QTrade 多环境数据库初始化")
|
||||||
|
print("=" * 60)
|
||||||
|
print()
|
||||||
|
|
||||||
|
success = init_databases()
|
||||||
|
|
||||||
|
if success:
|
||||||
|
print("\n下一步:")
|
||||||
|
print(" 运行数据库迁移为每个环境创建表结构")
|
||||||
|
print()
|
||||||
|
print(" # 实盘环境")
|
||||||
|
print(" alembic --config configs/production.yaml upgrade head")
|
||||||
|
print()
|
||||||
|
print(" # 回测环境")
|
||||||
|
print(" alembic --config configs/backtest.yaml upgrade head")
|
||||||
|
print()
|
||||||
|
print(" # 模拟环境")
|
||||||
|
print(" alembic --config configs/simulation.yaml upgrade head")
|
||||||
|
|
||||||
|
sys.exit(0 if success else 1)
|
||||||
14
scripts/init_databases.sql
Normal file
14
scripts/init_databases.sql
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
-- QTrade 多环境数据库初始化脚本
|
||||||
|
-- 创建三个独立的数据库用于不同环境
|
||||||
|
|
||||||
|
-- 实盘环境数据库
|
||||||
|
CREATE DATABASE IF NOT EXISTS QTrade_RealTrade DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- 回测环境数据库
|
||||||
|
CREATE DATABASE IF NOT EXISTS QTrade_BackTestTrade DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- 模拟环境数据库
|
||||||
|
CREATE DATABASE IF NOT EXISTS QTrade_SimuTrade DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
|
||||||
|
-- 显示创建的数据库
|
||||||
|
SHOW DATABASES LIKE 'QTrade_%';
|
||||||
@ -1,53 +0,0 @@
|
|||||||
"""
|
|
||||||
数据库初始化脚本
|
|
||||||
|
|
||||||
创建所有数据库表
|
|
||||||
"""
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
# 添加项目根目录到 Python 路径
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
|
||||||
sys.path.insert(0, str(ROOT))
|
|
||||||
|
|
||||||
from src.core.database import db
|
|
||||||
from src.core.logger import get_logger
|
|
||||||
|
|
||||||
# 导入所有模型,确保它们被注册到 Base.metadata
|
|
||||||
from src.core.models import (
|
|
||||||
Kline1d,
|
|
||||||
Kline1m,
|
|
||||||
Kline5m,
|
|
||||||
Kline15m,
|
|
||||||
Kline30m,
|
|
||||||
Kline60m,
|
|
||||||
)
|
|
||||||
|
|
||||||
logger = get_logger("init_db")
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
"""初始化数据库"""
|
|
||||||
logger.info("开始初始化数据库...")
|
|
||||||
|
|
||||||
try:
|
|
||||||
# 连接数据库
|
|
||||||
await db.connect()
|
|
||||||
|
|
||||||
# 创建所有表
|
|
||||||
await db.create_tables()
|
|
||||||
|
|
||||||
logger.info("数据库初始化完成!")
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"数据库初始化失败: {e}")
|
|
||||||
raise
|
|
||||||
finally:
|
|
||||||
# 断开连接
|
|
||||||
await db.disconnect()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(main())
|
|
||||||
@ -1,45 +0,0 @@
|
|||||||
@echo off
|
|
||||||
REM QTrade 服务启动脚本
|
|
||||||
REM 启动所有微服务
|
|
||||||
|
|
||||||
echo ========================================
|
|
||||||
echo QTrade 量化交易系统
|
|
||||||
echo ========================================
|
|
||||||
echo.
|
|
||||||
|
|
||||||
cd /d %~dp0\..
|
|
||||||
|
|
||||||
echo 启动 Gateway (8001)...
|
|
||||||
start "Gateway" cmd /k "python -m src.main gateway"
|
|
||||||
timeout /t 2 /nobreak > nul
|
|
||||||
|
|
||||||
echo 启动 Core Service (8010)...
|
|
||||||
start "Core Service" cmd /k "python -m src.main core_service"
|
|
||||||
timeout /t 2 /nobreak > nul
|
|
||||||
|
|
||||||
echo 启动 Data Service (8020)...
|
|
||||||
start "Data Service" cmd /k "python -m src.main data_service"
|
|
||||||
timeout /t 2 /nobreak > nul
|
|
||||||
|
|
||||||
echo 启动 Strategy Engine (8030)...
|
|
||||||
start "Strategy Engine" cmd /k "python -m src.main strategy_engine"
|
|
||||||
timeout /t 2 /nobreak > nul
|
|
||||||
|
|
||||||
echo 启动 QMT Adapter (8040)...
|
|
||||||
start "QMT Adapter" cmd /k "python -m src.main qmt_adapter"
|
|
||||||
timeout /t 2 /nobreak > nul
|
|
||||||
|
|
||||||
echo.
|
|
||||||
echo ========================================
|
|
||||||
echo 所有服务已启动!
|
|
||||||
echo ========================================
|
|
||||||
echo.
|
|
||||||
echo 服务列表:
|
|
||||||
echo - Gateway: http://localhost:8001
|
|
||||||
echo - Core Service: http://localhost:8010
|
|
||||||
echo - Data Service: http://localhost:8020
|
|
||||||
echo - Strategy Engine: http://localhost:8030
|
|
||||||
echo - QMT Adapter: http://localhost:8040
|
|
||||||
echo.
|
|
||||||
echo 按任意键关闭此窗口...
|
|
||||||
pause > nul
|
|
||||||
165
scripts/start_services.py
Normal file
165
scripts/start_services.py
Normal file
@ -0,0 +1,165 @@
|
|||||||
|
"""
|
||||||
|
QTrade 多环境服务启动脚本
|
||||||
|
|
||||||
|
支持启动三套独立环境:
|
||||||
|
- production: 实盘环境 (端口9000+, DB: QTrade_RealTrade, Redis: real:)
|
||||||
|
- backtest: 回测环境 (端口10000+, DB: QTrade_BackTestTrade, Redis: bt:)
|
||||||
|
- simulation: 模拟环境 (端口11000+, DB: QTrade_SimuTrade, Redis: simu:)
|
||||||
|
|
||||||
|
用法:
|
||||||
|
# 启动实盘环境的数据服务和策略引擎
|
||||||
|
python scripts/start_services.py production data_service strategy_engine
|
||||||
|
|
||||||
|
# 启动回测环境的所有服务
|
||||||
|
python scripts/start_services.py backtest data_service strategy_engine backtest_service
|
||||||
|
|
||||||
|
# 启动模拟环境
|
||||||
|
python scripts/start_services.py simulation data_service strategy_engine trade_service
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
# 项目根目录
|
||||||
|
PROJECT_ROOT = Path(__file__).parent.parent
|
||||||
|
|
||||||
|
# 环境配置
|
||||||
|
ENV_CONFIGS = {
|
||||||
|
"production": {
|
||||||
|
"env_file": ".env.production",
|
||||||
|
"config_file": "configs/production.yaml",
|
||||||
|
"description": "实盘环境",
|
||||||
|
},
|
||||||
|
"backtest": {
|
||||||
|
"env_file": ".env.backtest",
|
||||||
|
"config_file": "configs/backtest.yaml",
|
||||||
|
"description": "回测环境",
|
||||||
|
},
|
||||||
|
"simulation": {
|
||||||
|
"env_file": ".env.simulation",
|
||||||
|
"config_file": "configs/simulation.yaml",
|
||||||
|
"description": "模拟环境",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
# 服务配置
|
||||||
|
SERVICE_APPS = {
|
||||||
|
"data_service": "src.data_service.app:app",
|
||||||
|
"strategy_engine": "src.strategy_engine.app:app",
|
||||||
|
"trade_service": "src.trade_service.app:app",
|
||||||
|
"backtest_service": "src.backtest_service.app:app",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def start_service(service_name: str, env: str, detach: bool = True):
|
||||||
|
"""
|
||||||
|
启动指定环境的服务
|
||||||
|
|
||||||
|
Args:
|
||||||
|
service_name: 服务名称
|
||||||
|
env: 环境名称 (production/backtest/simulation)
|
||||||
|
detach: 是否后台运行
|
||||||
|
"""
|
||||||
|
if env not in ENV_CONFIGS:
|
||||||
|
print(f"❌ 未知环境: {env}")
|
||||||
|
print(f"支持的环境: {', '.join(ENV_CONFIGS.keys())}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
if service_name not in SERVICE_APPS:
|
||||||
|
print(f"❌ 未知服务: {service_name}")
|
||||||
|
print(f"支持的服务: {', '.join(SERVICE_APPS.keys())}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
env_config = ENV_CONFIGS[env]
|
||||||
|
app_path = SERVICE_APPS[service_name]
|
||||||
|
env_file = PROJECT_ROOT / env_config["env_file"]
|
||||||
|
|
||||||
|
if not env_file.exists():
|
||||||
|
print(f"❌ 环境配置文件不存在: {env_file}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
print(f"🚀 启动 {env_config['description']} - {service_name}")
|
||||||
|
|
||||||
|
# 构建命令
|
||||||
|
cmd = [
|
||||||
|
"uvicorn",
|
||||||
|
app_path,
|
||||||
|
"--env-file",
|
||||||
|
str(env_file),
|
||||||
|
"--reload",
|
||||||
|
]
|
||||||
|
|
||||||
|
# 设置环境变量
|
||||||
|
env_vars = os.environ.copy()
|
||||||
|
env_vars["ENV"] = env
|
||||||
|
env_vars["CONFIG_FILE"] = env_config["config_file"]
|
||||||
|
|
||||||
|
if detach:
|
||||||
|
# Windows 后台运行
|
||||||
|
if sys.platform == "win32":
|
||||||
|
# 创建新的控制台窗口
|
||||||
|
subprocess.Popen(
|
||||||
|
cmd,
|
||||||
|
env=env_vars,
|
||||||
|
creationflags=subprocess.CREATE_NEW_CONSOLE,
|
||||||
|
cwd=PROJECT_ROOT,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# Linux/Mac 后台运行
|
||||||
|
subprocess.Popen(
|
||||||
|
cmd,
|
||||||
|
env=env_vars,
|
||||||
|
stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
cwd=PROJECT_ROOT,
|
||||||
|
)
|
||||||
|
print(f"✓ {service_name} 已在后台启动")
|
||||||
|
else:
|
||||||
|
# 前台运行
|
||||||
|
subprocess.run(cmd, env=env_vars, cwd=PROJECT_ROOT)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
if len(sys.argv) < 3:
|
||||||
|
print("用法: python scripts/start_services.py <env> <service1> [service2] ...")
|
||||||
|
print()
|
||||||
|
print("环境:")
|
||||||
|
for env, config in ENV_CONFIGS.items():
|
||||||
|
print(f" {env:12} - {config['description']}")
|
||||||
|
print()
|
||||||
|
print("服务:")
|
||||||
|
for service in SERVICE_APPS.keys():
|
||||||
|
print(f" {service}")
|
||||||
|
print()
|
||||||
|
print("示例:")
|
||||||
|
print(
|
||||||
|
" python scripts/start_services.py production data_service strategy_engine"
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
" python scripts/start_services.py backtest data_service strategy_engine backtest_service"
|
||||||
|
)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
env = sys.argv[1]
|
||||||
|
services = sys.argv[2:]
|
||||||
|
|
||||||
|
print("=" * 60)
|
||||||
|
print(f"环境: {ENV_CONFIGS[env]['description']}")
|
||||||
|
print(f"服务: {', '.join(services)}")
|
||||||
|
print("=" * 60)
|
||||||
|
print()
|
||||||
|
|
||||||
|
for service in services:
|
||||||
|
start_service(service, env)
|
||||||
|
time.sleep(1) # 间隔启动
|
||||||
|
|
||||||
|
print()
|
||||||
|
print("✅ 所有服务已启动")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@ -1,13 +0,0 @@
|
|||||||
@echo off
|
|
||||||
REM QTrade 服务停止脚本
|
|
||||||
|
|
||||||
echo 正在停止所有 QTrade 服务...
|
|
||||||
|
|
||||||
taskkill /FI "WINDOWTITLE eq Gateway*" /F 2>nul
|
|
||||||
taskkill /FI "WINDOWTITLE eq Core Service*" /F 2>nul
|
|
||||||
taskkill /FI "WINDOWTITLE eq Data Service*" /F 2>nul
|
|
||||||
taskkill /FI "WINDOWTITLE eq Strategy Engine*" /F 2>nul
|
|
||||||
taskkill /FI "WINDOWTITLE eq QMT Adapter*" /F 2>nul
|
|
||||||
|
|
||||||
echo 所有服务已停止
|
|
||||||
pause
|
|
||||||
61
scripts/test_config.py
Normal file
61
scripts/test_config.py
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
"""
|
||||||
|
测试多环境配置
|
||||||
|
|
||||||
|
验证不同环境的配置是否正确加载
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# 添加项目根目录到路径
|
||||||
|
project_root = Path(__file__).parent.parent
|
||||||
|
sys.path.insert(0, str(project_root))
|
||||||
|
|
||||||
|
|
||||||
|
def test_environment(env_name: str, env_file: str):
|
||||||
|
"""测试指定环境的配置"""
|
||||||
|
print(f"\n{'=' * 60}")
|
||||||
|
print(f"测试环境: {env_name}")
|
||||||
|
print(f"{'=' * 60}")
|
||||||
|
|
||||||
|
# 设置环境变量
|
||||||
|
os.environ["CONFIG_FILE"] = f"configs/{env_file}"
|
||||||
|
|
||||||
|
# 重新导入配置(清除缓存)
|
||||||
|
if "src.core.config" in sys.modules:
|
||||||
|
del sys.modules["src.core.config"]
|
||||||
|
|
||||||
|
from src.core.config import settings
|
||||||
|
|
||||||
|
# 显示配置信息
|
||||||
|
print(f"环境名称: {settings.environment.env}")
|
||||||
|
print(f"数据库名: {settings.environment.db_name}")
|
||||||
|
print(f"Redis前缀: {settings.environment.redis_prefix}")
|
||||||
|
print(f"端口偏移: {settings.environment.port_offset}")
|
||||||
|
print()
|
||||||
|
print(f"数据库URL: {settings.database.url}")
|
||||||
|
print()
|
||||||
|
print("Redis频道:")
|
||||||
|
print(f" K线更新: {settings.channels.kline_update}")
|
||||||
|
print(f" 信号创建: {settings.channels.signal_create}")
|
||||||
|
print(f" 订单更新: {settings.channels.order_update}")
|
||||||
|
print(f" 成交更新: {settings.channels.trade_update}")
|
||||||
|
print()
|
||||||
|
print("服务端口:")
|
||||||
|
try:
|
||||||
|
print(f" DataService: {settings.services.data_service.port}")
|
||||||
|
print(f" StrategyEngine: {settings.services.strategy_engine.port}")
|
||||||
|
except:
|
||||||
|
print(" (服务端口配置可能不存在)")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# 测试三个环境
|
||||||
|
test_environment("实盘环境", "production.yaml")
|
||||||
|
test_environment("回测环境", "backtest.yaml")
|
||||||
|
test_environment("模拟环境", "simulation.yaml")
|
||||||
|
|
||||||
|
print(f"\n{'=' * 60}")
|
||||||
|
print("✅ 所有环境配置测试完成")
|
||||||
|
print(f"{'=' * 60}\n")
|
||||||
@ -13,6 +13,7 @@ QTrade 配置管理模块
|
|||||||
3. 环境变量 - 运行时覆盖
|
3. 环境变量 - 运行时覆盖
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
from enum import Enum
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@ -22,6 +23,17 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
|
|||||||
from .config_manager import ConfigManager
|
from .config_manager import ConfigManager
|
||||||
|
|
||||||
|
|
||||||
|
# ========== 环境枚举 ==========
|
||||||
|
|
||||||
|
|
||||||
|
class Environment(str, Enum):
|
||||||
|
"""运行环境"""
|
||||||
|
|
||||||
|
PRODUCTION = "production" # 实盘
|
||||||
|
BACKTEST = "backtest" # 回测
|
||||||
|
SIMULATION = "simulation" # 模拟
|
||||||
|
|
||||||
|
|
||||||
def get_project_root() -> Path:
|
def get_project_root() -> Path:
|
||||||
"""获取项目根目录"""
|
"""获取项目根目录"""
|
||||||
current = Path(__file__).resolve()
|
current = Path(__file__).resolve()
|
||||||
@ -53,6 +65,84 @@ class ConfigProxy:
|
|||||||
return self.__getattr__(key)
|
return self.__getattr__(key)
|
||||||
|
|
||||||
|
|
||||||
|
class EnvironmentConfig(ConfigProxy):
|
||||||
|
"""环境配置"""
|
||||||
|
|
||||||
|
@property
|
||||||
|
def env(self) -> str:
|
||||||
|
"""当前环境"""
|
||||||
|
return self._manager.get("environment.env", "production")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def db_name(self) -> str:
|
||||||
|
"""数据库名称"""
|
||||||
|
env = self.env
|
||||||
|
db_mapping = {
|
||||||
|
"production": "QTrade_RealTrade",
|
||||||
|
"backtest": "QTrade_BackTestTrade",
|
||||||
|
"simulation": "QTrade_SimuTrade",
|
||||||
|
}
|
||||||
|
return self._manager.get(
|
||||||
|
"environment.db_name", db_mapping.get(env, "qtrade_stock_data")
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def redis_prefix(self) -> str:
|
||||||
|
"""Redis频道前缀"""
|
||||||
|
env = self.env
|
||||||
|
prefix_mapping = {
|
||||||
|
"production": "real",
|
||||||
|
"backtest": "bt",
|
||||||
|
"simulation": "simu",
|
||||||
|
}
|
||||||
|
return self._manager.get(
|
||||||
|
"environment.redis_prefix", prefix_mapping.get(env, "real")
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def port_offset(self) -> int:
|
||||||
|
"""端口偏移量"""
|
||||||
|
env = self.env
|
||||||
|
offset_mapping = {
|
||||||
|
"production": 9000,
|
||||||
|
"backtest": 10000,
|
||||||
|
"simulation": 11000,
|
||||||
|
}
|
||||||
|
return self._manager.get(
|
||||||
|
"environment.port_offset", offset_mapping.get(env, 9000)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class RedisChannels(ConfigProxy):
|
||||||
|
"""Redis频道配置"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self, config_manager: ConfigManager, environment_config: EnvironmentConfig
|
||||||
|
):
|
||||||
|
super().__init__(config_manager, "")
|
||||||
|
self._env_config = environment_config
|
||||||
|
|
||||||
|
@property
|
||||||
|
def kline_update(self) -> str:
|
||||||
|
"""K线更新频道"""
|
||||||
|
return f"{self._env_config.redis_prefix}:kline:update"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def signal_create(self) -> str:
|
||||||
|
"""信号创建频道"""
|
||||||
|
return f"{self._env_config.redis_prefix}:signal:create"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def order_update(self) -> str:
|
||||||
|
"""订单更新频道"""
|
||||||
|
return f"{self._env_config.redis_prefix}:order:update"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def trade_update(self) -> str:
|
||||||
|
"""成交更新频道"""
|
||||||
|
return f"{self._env_config.redis_prefix}:trade:update"
|
||||||
|
|
||||||
|
|
||||||
class RedisConfig(ConfigProxy):
|
class RedisConfig(ConfigProxy):
|
||||||
"""Redis 配置"""
|
"""Redis 配置"""
|
||||||
|
|
||||||
@ -71,6 +161,15 @@ class RedisConfig(ConfigProxy):
|
|||||||
class DatabaseConfig(ConfigProxy):
|
class DatabaseConfig(ConfigProxy):
|
||||||
"""数据库配置"""
|
"""数据库配置"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
config_manager: ConfigManager,
|
||||||
|
environment_config: EnvironmentConfig,
|
||||||
|
prefix: str = "database",
|
||||||
|
):
|
||||||
|
super().__init__(config_manager, prefix)
|
||||||
|
self._env_config = environment_config
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def url(self) -> str:
|
def url(self) -> str:
|
||||||
"""生成数据库 URL (异步)"""
|
"""生成数据库 URL (异步)"""
|
||||||
@ -78,7 +177,8 @@ class DatabaseConfig(ConfigProxy):
|
|||||||
password = self._manager.get("database.password", "")
|
password = self._manager.get("database.password", "")
|
||||||
host = self._manager.get("database.host", "127.0.0.1")
|
host = self._manager.get("database.host", "127.0.0.1")
|
||||||
port = self._manager.get("database.port", 3306)
|
port = self._manager.get("database.port", 3306)
|
||||||
database = self._manager.get("database.database", "qtrade")
|
# 使用环境配置的数据库名
|
||||||
|
database = self._env_config.db_name
|
||||||
|
|
||||||
return (
|
return (
|
||||||
f"mysql+aiomysql://{user}:{password}@"
|
f"mysql+aiomysql://{user}:{password}@"
|
||||||
@ -92,7 +192,8 @@ class DatabaseConfig(ConfigProxy):
|
|||||||
password = self._manager.get("database.password", "")
|
password = self._manager.get("database.password", "")
|
||||||
host = self._manager.get("database.host", "127.0.0.1")
|
host = self._manager.get("database.host", "127.0.0.1")
|
||||||
port = self._manager.get("database.port", 3306)
|
port = self._manager.get("database.port", 3306)
|
||||||
database = self._manager.get("database.database", "qtrade")
|
# 使用环境配置的数据库名
|
||||||
|
database = self._env_config.db_name
|
||||||
|
|
||||||
return (
|
return (
|
||||||
f"mysql+pymysql://{user}:{password}@"
|
f"mysql+pymysql://{user}:{password}@"
|
||||||
@ -116,8 +217,10 @@ class Settings:
|
|||||||
|
|
||||||
# 创建配置代理
|
# 创建配置代理
|
||||||
self.app = ConfigProxy(self._manager, "app")
|
self.app = ConfigProxy(self._manager, "app")
|
||||||
|
self.environment = EnvironmentConfig(self._manager, "environment")
|
||||||
self.redis = RedisConfig(self._manager, "redis")
|
self.redis = RedisConfig(self._manager, "redis")
|
||||||
self.database = DatabaseConfig(self._manager, "database")
|
self.database = DatabaseConfig(self._manager, self.environment, "database")
|
||||||
|
self.channels = RedisChannels(self._manager, self.environment)
|
||||||
self.logging = ConfigProxy(self._manager, "logging")
|
self.logging = ConfigProxy(self._manager, "logging")
|
||||||
self.market = ConfigProxy(self._manager, "market")
|
self.market = ConfigProxy(self._manager, "market")
|
||||||
self.trading = ConfigProxy(self._manager, "trading")
|
self.trading = ConfigProxy(self._manager, "trading")
|
||||||
|
|||||||
@ -39,6 +39,15 @@ class ConfigManager:
|
|||||||
self.service_name = service_name
|
self.service_name = service_name
|
||||||
self.project_root = self._get_project_root()
|
self.project_root = self._get_project_root()
|
||||||
self.configs_dir = self.project_root / "configs"
|
self.configs_dir = self.project_root / "configs"
|
||||||
|
|
||||||
|
# 支持从环境变量指定配置文件(用于多环境)
|
||||||
|
env_config_file = os.getenv("CONFIG_FILE")
|
||||||
|
if env_config_file:
|
||||||
|
# 使用环境变量指定的配置文件
|
||||||
|
self.env_config_path = self.project_root / env_config_file
|
||||||
|
else:
|
||||||
|
self.env_config_path = None
|
||||||
|
|
||||||
self.global_config_path = self.configs_dir / "global.yaml"
|
self.global_config_path = self.configs_dir / "global.yaml"
|
||||||
self.service_config_path = (
|
self.service_config_path = (
|
||||||
self.configs_dir / "services" / f"{service_name}.yaml"
|
self.configs_dir / "services" / f"{service_name}.yaml"
|
||||||
@ -63,15 +72,19 @@ class ConfigManager:
|
|||||||
|
|
||||||
def _load(self) -> None:
|
def _load(self) -> None:
|
||||||
"""加载配置(按优先级合并)"""
|
"""加载配置(按优先级合并)"""
|
||||||
# 1. 加载全局配置
|
# 优先级1: 环境配置文件(如果指定)
|
||||||
|
if self.env_config_path and self.env_config_path.exists():
|
||||||
|
self._config = self._load_yaml(self.env_config_path)
|
||||||
|
else:
|
||||||
|
# 优先级2: 加载全局配置
|
||||||
self._config = self._load_yaml(self.global_config_path)
|
self._config = self._load_yaml(self.global_config_path)
|
||||||
|
|
||||||
# 2. 加载服务配置并合并
|
# 优先级3: 加载服务配置并合并
|
||||||
if self.service_config_path and self.service_config_path.exists():
|
if self.service_config_path and self.service_config_path.exists():
|
||||||
service_config = self._load_yaml(self.service_config_path)
|
service_config = self._load_yaml(self.service_config_path)
|
||||||
self._deep_merge(self._config, service_config)
|
self._deep_merge(self._config, service_config)
|
||||||
|
|
||||||
# 3. 环境变量覆盖(格式:QTRADE_DATABASE_HOST=127.0.0.1)
|
# 优先级4: 环境变量覆盖(格式:QTRADE_DATABASE_HOST=127.0.0.1)
|
||||||
self._apply_env_overrides()
|
self._apply_env_overrides()
|
||||||
|
|
||||||
def _load_yaml(self, path: Path) -> dict[str, Any]:
|
def _load_yaml(self, path: Path) -> dict[str, Any]:
|
||||||
|
|||||||
@ -393,26 +393,71 @@ class RedisKeys:
|
|||||||
|
|
||||||
|
|
||||||
class RedisChannels:
|
class RedisChannels:
|
||||||
"""Redis Pub/Sub 频道常量"""
|
"""Redis Pub/Sub 频道常量(动态获取环境前缀)"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _get_prefix() -> str:
|
||||||
|
"""获取当前环境的Redis前缀"""
|
||||||
|
try:
|
||||||
|
return settings.environment.redis_prefix
|
||||||
|
except:
|
||||||
|
return "real" # 默认实盘环境
|
||||||
|
|
||||||
# 行情频道
|
# 行情频道
|
||||||
MARKET_QUOTE = "market:quote" # 实时行情推送
|
@property
|
||||||
MARKET_KLINE = "market:kline" # K线推送
|
def MARKET_QUOTE(self) -> str:
|
||||||
|
return f"{self._get_prefix()}:market:quote" # 实时行情推送
|
||||||
|
|
||||||
|
@property
|
||||||
|
def MARKET_KLINE(self) -> str:
|
||||||
|
return f"{self._get_prefix()}:market:kline" # K线推送
|
||||||
|
|
||||||
|
# 策略频道(使用settings.channels)
|
||||||
|
@property
|
||||||
|
def STRATEGY_QUOTE(self) -> str:
|
||||||
|
"""策略行情频道(兼容旧代码)"""
|
||||||
|
return settings.channels.kline_update
|
||||||
|
|
||||||
|
@property
|
||||||
|
def STRATEGY_KLINE(self) -> str:
|
||||||
|
"""策略K线频道(兼容旧代码)"""
|
||||||
|
return settings.channels.kline_update
|
||||||
|
|
||||||
# 交易频道
|
# 交易频道
|
||||||
TRADE_ORDER = "trade:order" # 订单事件
|
@property
|
||||||
TRADE_SIGNAL = "trade:signal" # 交易信号
|
def TRADE_ORDER(self) -> str:
|
||||||
TRADE_EXEC = "trade:exec" # 交易执行(发给 QMT)
|
return f"{self._get_prefix()}:trade:order" # 订单事件
|
||||||
|
|
||||||
|
@property
|
||||||
|
def TRADE_SIGNAL(self) -> str:
|
||||||
|
return settings.channels.signal_create # 使用统一的信号频道
|
||||||
|
|
||||||
|
@property
|
||||||
|
def TRADE_EXEC(self) -> str:
|
||||||
|
return f"{self._get_prefix()}:trade:exec" # 交易执行(发给 QMT)
|
||||||
|
|
||||||
# 账户频道
|
# 账户频道
|
||||||
ACCOUNT_UPDATE = "account:update" # 账户更新
|
@property
|
||||||
POSITION_UPDATE = "position:update" # 持仓更新
|
def ACCOUNT_UPDATE(self) -> str:
|
||||||
|
return f"{self._get_prefix()}:account:update" # 账户更新
|
||||||
|
|
||||||
|
@property
|
||||||
|
def POSITION_UPDATE(self) -> str:
|
||||||
|
return f"{self._get_prefix()}:position:update" # 持仓更新
|
||||||
|
|
||||||
# 系统频道
|
# 系统频道
|
||||||
SYSTEM_STATUS = "system:status" # 系统状态
|
@property
|
||||||
|
def SYSTEM_STATUS(self) -> str:
|
||||||
|
return f"{self._get_prefix()}:system:status" # 系统状态
|
||||||
|
|
||||||
# 数据同步频道
|
# 数据同步频道
|
||||||
DATA_DOWNLOAD_RESULT = "data:download:result" # 下载完成通知
|
@property
|
||||||
|
def DATA_DOWNLOAD_RESULT(self) -> str:
|
||||||
|
return f"{self._get_prefix()}:data:download:result" # 下载完成通知
|
||||||
|
|
||||||
|
|
||||||
|
# 全局RedisChannels实例
|
||||||
|
RedisChannels = RedisChannels()
|
||||||
|
|
||||||
|
|
||||||
# 全局客户端实例
|
# 全局客户端实例
|
||||||
|
|||||||
@ -106,8 +106,11 @@ class OrderService:
|
|||||||
|
|
||||||
# 发布订单创建事件(QMT 适配器监听)
|
# 发布订单创建事件(QMT 适配器监听)
|
||||||
import json
|
import json
|
||||||
|
from src.core.config import settings
|
||||||
|
|
||||||
await redis_client.publish("order:created", json.dumps(order_data))
|
await redis_client.publish(
|
||||||
|
settings.channels.order_update, json.dumps(order_data)
|
||||||
|
)
|
||||||
|
|
||||||
return order_data
|
return order_data
|
||||||
|
|
||||||
@ -138,7 +141,9 @@ class OrderService:
|
|||||||
await session.commit()
|
await session.commit()
|
||||||
|
|
||||||
# 发布撤单事件
|
# 发布撤单事件
|
||||||
await redis_client.publish("order:cancelled", order_id)
|
from src.core.config import settings
|
||||||
|
|
||||||
|
await redis_client.publish(settings.channels.order_update, order_id)
|
||||||
|
|
||||||
return await self.get_order(order_id)
|
return await self.get_order(order_id)
|
||||||
|
|
||||||
|
|||||||
@ -79,7 +79,11 @@ class SignalManager:
|
|||||||
signal_data = new_signal.to_dict()
|
signal_data = new_signal.to_dict()
|
||||||
|
|
||||||
# 发布信号到 Redis(Core Service 监听并创建订单)
|
# 发布信号到 Redis(Core Service 监听并创建订单)
|
||||||
await redis_client.publish("signal:created", json.dumps(signal_data))
|
from src.core.config import settings
|
||||||
|
|
||||||
|
await redis_client.publish(
|
||||||
|
settings.channels.signal_create, json.dumps(signal_data)
|
||||||
|
)
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
f"创建信号: {signal_id} - {symbol} {side.value} {quantity}@{price} - {reason}"
|
f"创建信号: {signal_id} - {symbol} {side.value} {quantity}@{price} - {reason}"
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user