2025-12-08 17:53:35 +08:00
|
|
|
|
"""
|
|
|
|
|
|
QTrade 配置管理模块
|
|
|
|
|
|
|
|
|
|
|
|
使用 Pydantic Settings 进行配置管理,支持:
|
|
|
|
|
|
- YAML 配置文件
|
|
|
|
|
|
- 环境变量覆盖
|
|
|
|
|
|
- 配置验证
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
import os
|
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
from typing import Any
|
|
|
|
|
|
|
|
|
|
|
|
import yaml
|
|
|
|
|
|
from pydantic import BaseModel, Field
|
|
|
|
|
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_project_root() -> Path:
|
|
|
|
|
|
"""获取项目根目录"""
|
|
|
|
|
|
# 从当前文件向上查找,找到包含 configs 目录的位置
|
|
|
|
|
|
current = Path(__file__).resolve()
|
|
|
|
|
|
for parent in [current] + list(current.parents):
|
|
|
|
|
|
if (parent / "configs").is_dir():
|
|
|
|
|
|
return parent
|
|
|
|
|
|
# 如果找不到,返回当前工作目录
|
|
|
|
|
|
return Path.cwd()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def load_yaml_config(config_path: Path) -> dict[str, Any]:
|
|
|
|
|
|
"""加载 YAML 配置文件"""
|
|
|
|
|
|
if not config_path.exists():
|
|
|
|
|
|
return {}
|
|
|
|
|
|
with open(config_path, "r", encoding="utf-8") as f:
|
|
|
|
|
|
return yaml.safe_load(f) or {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ========== 使用 BaseModel 定义嵌套配置 ==========
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class RedisConfig(BaseModel):
|
|
|
|
|
|
"""Redis 配置"""
|
|
|
|
|
|
|
|
|
|
|
|
host: str = "127.0.0.1"
|
|
|
|
|
|
port: int = 6379
|
|
|
|
|
|
password: str = ""
|
|
|
|
|
|
db: int = 0
|
|
|
|
|
|
pool_size: int = 10
|
|
|
|
|
|
pool_timeout: int = 30
|
|
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
|
def url(self) -> str:
|
|
|
|
|
|
"""生成 Redis URL"""
|
|
|
|
|
|
auth = f":{self.password}@" if self.password else ""
|
|
|
|
|
|
return f"redis://{auth}{self.host}:{self.port}/{self.db}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class DatabaseConfig(BaseModel):
|
|
|
|
|
|
"""数据库配置"""
|
|
|
|
|
|
|
|
|
|
|
|
host: str = "127.0.0.1"
|
|
|
|
|
|
port: int = 3306
|
|
|
|
|
|
user: str = "root"
|
|
|
|
|
|
password: str = ""
|
|
|
|
|
|
database: str = "qtrade"
|
|
|
|
|
|
pool_size: int = 5
|
|
|
|
|
|
pool_recycle: int = 3600
|
|
|
|
|
|
echo: bool = False
|
|
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
|
def url(self) -> str:
|
|
|
|
|
|
"""生成数据库 URL (异步)"""
|
|
|
|
|
|
return (
|
|
|
|
|
|
f"mysql+aiomysql://{self.user}:{self.password}@"
|
|
|
|
|
|
f"{self.host}:{self.port}/{self.database}?charset=utf8mb4"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
|
def sync_url(self) -> str:
|
|
|
|
|
|
"""生成数据库 URL (同步,用于迁移)"""
|
|
|
|
|
|
return (
|
|
|
|
|
|
f"mysql+pymysql://{self.user}:{self.password}@"
|
|
|
|
|
|
f"{self.host}:{self.port}/{self.database}?charset=utf8mb4"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ServiceConfig(BaseModel):
|
|
|
|
|
|
"""单个服务配置"""
|
|
|
|
|
|
|
|
|
|
|
|
host: str = "0.0.0.0"
|
|
|
|
|
|
port: int
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ServicesConfig(BaseModel):
|
|
|
|
|
|
"""所有服务配置"""
|
|
|
|
|
|
|
|
|
|
|
|
gateway: ServiceConfig = ServiceConfig(port=8001)
|
|
|
|
|
|
core_service: ServiceConfig = ServiceConfig(port=8010)
|
|
|
|
|
|
data_service: ServiceConfig = ServiceConfig(port=8020)
|
|
|
|
|
|
strategy_engine: ServiceConfig = ServiceConfig(port=8030)
|
2025-12-09 00:36:27 +08:00
|
|
|
|
qmt_adapter: ServiceConfig = ServiceConfig(port=8040)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class QMTConfig(BaseModel):
|
|
|
|
|
|
"""QMT 配置"""
|
|
|
|
|
|
|
|
|
|
|
|
path: str = ""
|
|
|
|
|
|
session_id: int = 123456
|
|
|
|
|
|
account_id: str = ""
|
|
|
|
|
|
simulation: bool = True
|
2025-12-08 17:53:35 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class LoggingFileConfig(BaseModel):
|
|
|
|
|
|
"""日志文件配置"""
|
|
|
|
|
|
|
|
|
|
|
|
enabled: bool = True
|
|
|
|
|
|
path: str = "logs"
|
|
|
|
|
|
max_size: int = 10485760 # 10MB
|
|
|
|
|
|
backup_count: int = 5
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class LoggingConfig(BaseModel):
|
|
|
|
|
|
"""日志配置"""
|
|
|
|
|
|
|
|
|
|
|
|
level: str = "INFO"
|
|
|
|
|
|
format: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
|
|
|
|
file: LoggingFileConfig = LoggingFileConfig()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class MarketConfig(BaseModel):
|
|
|
|
|
|
"""行情配置"""
|
|
|
|
|
|
|
|
|
|
|
|
kline_periods: list[str] = ["1m", "5m", "15m", "30m", "60m", "1d", "1w"]
|
|
|
|
|
|
cache_ttl: int = 60
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class TradingSessionConfig(BaseModel):
|
|
|
|
|
|
"""交易时段配置"""
|
|
|
|
|
|
|
|
|
|
|
|
start: str
|
|
|
|
|
|
end: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class TradingSessionsConfig(BaseModel):
|
|
|
|
|
|
"""交易时段集合"""
|
|
|
|
|
|
|
|
|
|
|
|
morning: TradingSessionConfig = TradingSessionConfig(start="09:30", end="11:30")
|
|
|
|
|
|
afternoon: TradingSessionConfig = TradingSessionConfig(start="13:00", end="15:00")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class RiskConfig(BaseModel):
|
|
|
|
|
|
"""风控配置"""
|
|
|
|
|
|
|
|
|
|
|
|
max_position_ratio: float = 0.3
|
|
|
|
|
|
max_order_value: float = 1000000
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class TradingConfig(BaseModel):
|
|
|
|
|
|
"""交易配置"""
|
|
|
|
|
|
|
|
|
|
|
|
sessions: TradingSessionsConfig = TradingSessionsConfig()
|
|
|
|
|
|
risk: RiskConfig = RiskConfig()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class AppConfig(BaseModel):
|
|
|
|
|
|
"""应用配置"""
|
|
|
|
|
|
|
|
|
|
|
|
name: str = "QTrade"
|
|
|
|
|
|
version: str = "2.0.0"
|
|
|
|
|
|
env: str = "development"
|
|
|
|
|
|
debug: bool = True
|
|
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
|
def is_production(self) -> bool:
|
|
|
|
|
|
return self.env == "production"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ========== 主配置类 ==========
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Settings(BaseSettings):
|
|
|
|
|
|
"""
|
|
|
|
|
|
主配置类
|
|
|
|
|
|
|
|
|
|
|
|
配置优先级(从高到低):
|
|
|
|
|
|
1. 环境变量
|
|
|
|
|
|
2. YAML 配置文件
|
|
|
|
|
|
3. 默认值
|
|
|
|
|
|
|
|
|
|
|
|
环境变量映射:
|
|
|
|
|
|
- QTRADE_ENV -> app.env
|
|
|
|
|
|
- REDIS_HOST -> redis.host
|
|
|
|
|
|
- DB_HOST -> database.host
|
|
|
|
|
|
- LOG_LEVEL -> logging.level
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
model_config = SettingsConfigDict(
|
|
|
|
|
|
env_file=".env",
|
|
|
|
|
|
env_file_encoding="utf-8",
|
|
|
|
|
|
extra="ignore",
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# 嵌套配置
|
|
|
|
|
|
app: AppConfig = AppConfig()
|
|
|
|
|
|
redis: RedisConfig = RedisConfig()
|
|
|
|
|
|
database: DatabaseConfig = DatabaseConfig()
|
|
|
|
|
|
services: ServicesConfig = ServicesConfig()
|
|
|
|
|
|
logging: LoggingConfig = LoggingConfig()
|
|
|
|
|
|
market: MarketConfig = MarketConfig()
|
|
|
|
|
|
trading: TradingConfig = TradingConfig()
|
2025-12-09 00:36:27 +08:00
|
|
|
|
qmt: QMTConfig = QMTConfig()
|
2025-12-08 17:53:35 +08:00
|
|
|
|
|
|
|
|
|
|
# 项目路径
|
|
|
|
|
|
project_root: Path = Field(default_factory=get_project_root)
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self, **kwargs):
|
|
|
|
|
|
# 先加载 YAML 配置
|
|
|
|
|
|
yaml_config = _load_yaml_config()
|
|
|
|
|
|
|
|
|
|
|
|
# 处理环境变量覆盖
|
|
|
|
|
|
env_overrides = _get_env_overrides()
|
|
|
|
|
|
|
|
|
|
|
|
# 合并配置: 默认值 < YAML < 环境变量 < kwargs
|
|
|
|
|
|
merged = _deep_merge(yaml_config, env_overrides)
|
|
|
|
|
|
merged = _deep_merge(merged, kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
super().__init__(**merged)
|
|
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
|
def logs_dir(self) -> Path:
|
|
|
|
|
|
"""日志目录"""
|
|
|
|
|
|
logs_path = self.project_root / self.logging.file.path
|
|
|
|
|
|
logs_path.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
return logs_path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _load_yaml_config() -> dict[str, Any]:
|
|
|
|
|
|
"""加载 YAML 配置"""
|
|
|
|
|
|
config_path = get_project_root() / "configs" / "settings.yaml"
|
|
|
|
|
|
return load_yaml_config(config_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _get_env_overrides() -> dict[str, Any]:
|
|
|
|
|
|
"""从环境变量获取配置覆盖"""
|
|
|
|
|
|
overrides: dict[str, Any] = {}
|
|
|
|
|
|
|
|
|
|
|
|
# 应用环境
|
|
|
|
|
|
if env := os.getenv("QTRADE_ENV"):
|
|
|
|
|
|
overrides.setdefault("app", {})["env"] = env
|
|
|
|
|
|
|
|
|
|
|
|
# Redis
|
|
|
|
|
|
if host := os.getenv("REDIS_HOST"):
|
|
|
|
|
|
overrides.setdefault("redis", {})["host"] = host
|
|
|
|
|
|
if port := os.getenv("REDIS_PORT"):
|
|
|
|
|
|
overrides.setdefault("redis", {})["port"] = int(port)
|
|
|
|
|
|
if password := os.getenv("REDIS_PASSWORD"):
|
|
|
|
|
|
overrides.setdefault("redis", {})["password"] = password
|
|
|
|
|
|
if db := os.getenv("REDIS_DB"):
|
|
|
|
|
|
overrides.setdefault("redis", {})["db"] = int(db)
|
|
|
|
|
|
|
|
|
|
|
|
# 数据库
|
|
|
|
|
|
if host := os.getenv("DB_HOST"):
|
|
|
|
|
|
overrides.setdefault("database", {})["host"] = host
|
|
|
|
|
|
if port := os.getenv("DB_PORT"):
|
|
|
|
|
|
overrides.setdefault("database", {})["port"] = int(port)
|
|
|
|
|
|
if user := os.getenv("DB_USER"):
|
|
|
|
|
|
overrides.setdefault("database", {})["user"] = user
|
|
|
|
|
|
if password := os.getenv("DB_PASSWORD"):
|
|
|
|
|
|
overrides.setdefault("database", {})["password"] = password
|
|
|
|
|
|
if name := os.getenv("DB_NAME"):
|
|
|
|
|
|
overrides.setdefault("database", {})["database"] = name
|
|
|
|
|
|
|
|
|
|
|
|
# 日志
|
|
|
|
|
|
if level := os.getenv("LOG_LEVEL"):
|
|
|
|
|
|
overrides.setdefault("logging", {})["level"] = level
|
|
|
|
|
|
|
|
|
|
|
|
return overrides
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _deep_merge(base: dict, override: dict) -> dict:
|
|
|
|
|
|
"""深度合并字典"""
|
|
|
|
|
|
result = base.copy()
|
|
|
|
|
|
for key, value in override.items():
|
|
|
|
|
|
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
|
|
|
|
|
|
result[key] = _deep_merge(result[key], value)
|
|
|
|
|
|
else:
|
|
|
|
|
|
result[key] = value
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 全局配置实例
|
|
|
|
|
|
settings = Settings()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# 便捷访问
|
|
|
|
|
|
def get_settings() -> Settings:
|
|
|
|
|
|
"""获取配置实例"""
|
|
|
|
|
|
return settings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def reload_settings() -> Settings:
|
|
|
|
|
|
"""重新加载配置"""
|
|
|
|
|
|
global settings
|
|
|
|
|
|
settings = Settings()
|
|
|
|
|
|
return settings
|