重构配置系统:改为Config/Logger单例模式,拆分环境配置文件

主要改动:
1. Config类改为单例模式,支持根据global.yaml的current_mode自动加载环境配置
2. Logger类改为单例模式,通过类方法直接访问
3. 拆分配置文件:global.yaml仅指定模式,backtest.yaml/simulation.yaml/production.yaml存储各环境配置
4. 移除所有config参数传递,使用Config.get()直接访问
5. 移除所有logger实例传递,使用Logger.info()等类方法直接访问
6. 修复初始化顺序:Config.initialize() -> Logger.initialize() -> 其他组件
7. 修复Logger参数默认值,确保所有方法可正常调用
8. 新增三个环境配置文件结构统一,只有参数值不同
9. 客户端URL端口修正为8030(回测)/8020(模拟)/8010(实盘)

配置文件变更:
- configs/global.yaml:简化为仅包含current_mode
- configs/backtest.yaml:回测环境完整配置
- configs/simulation.yaml:模拟环境完整配置
- configs/production.yaml:实盘环境完整配置

代码重构:
- src/core/config.py:单例模式,自动加载环境配置
- src/core/logger.py:单例模式,类方法访问
- 所有模块:移除config/logger参数,使用单例访问
This commit is contained in:
cuizhan 2026-01-12 19:07:23 +08:00
parent 0f23037448
commit 37a5df8bf6
44 changed files with 1108 additions and 1279 deletions

View File

@ -1,15 +0,0 @@
# 全局策略配置
# 适用于所有策略实例的全局参数
# 全局资金配置
global:
total_capital: 1000000 # 总资金100万
max_position_ratio: 0.8 # 最大总仓位80%
# 全局风控配置
risk:
max_drawdown: 0.2 # 最大回撤20%
max_daily_loss: 0.05 # 单日最大亏损5%
# 策略实例配置目录
strategy_configs_dir: "config/strategies"

View File

@ -1,71 +0,0 @@
# 策略配置文件
# 定义策略实例、资金分配、风控参数等
# 全局配置
global:
total_capital: 1000000 # 总资金100万
max_position_ratio: 0.8 # 最大总仓位80%
# 策略实例配置
strategy_instances:
# 策略实例1: 000001.SZ 的短期MA策略
- id: "ma_short_000001"
symbol: "000001.SZ"
strategy_class: "MAStrategy"
capital: 100000 # 分配资金10万
params:
short_period: 5
long_period: 20
risk:
max_position_ratio: 0.8 # 最大仓位80%
stop_loss: 0.05 # 止损5%
stop_profit: 0.15 # 止盈15%
# 策略实例2: 000001.SZ 的MACD策略
- id: "macd_000001"
symbol: "000001.SZ"
strategy_class: "MACDStrategy"
capital: 80000
params:
fast: 12
slow: 26
signal: 9
risk:
max_position_ratio: 0.6
stop_loss: 0.03
# 策略实例3: 000001.SZ 的长期MA策略
- id: "ma_long_000001"
symbol: "000001.SZ"
strategy_class: "MAStrategy"
capital: 120000
params:
short_period: 10
long_period: 30
risk:
max_position_ratio: 0.7
stop_loss: 0.04
stop_profit: 0.20
# 策略实例4: 600000.SH 的Momentum策略
- id: "momentum_600000"
symbol: "600000.SH"
strategy_class: "MomentumStrategy"
capital: 200000
params:
period: 20
risk:
max_position_ratio: 0.6
stop_loss: 0.05
# 策略实例5: 600519.SH 的Grid策略
- id: "grid_600519"
symbol: "600519.SH"
strategy_class: "GridStrategy"
capital: 300000
params:
grid_size: 0.02
levels: 5
risk:
max_position_ratio: 0.5
stop_loss: 0.08

View File

@ -1,46 +0,0 @@
# 策略配置文件 - 调试模式
# 使用DebugStrategy进行调试
# 全局配置
global:
total_capital: 1000000 # 总资金100万
max_position_ratio: 0.8 # 最大总仓位80%
# 策略实例配置
strategy_instances:
# 调试策略实例1: 平安银行 - 每条K线都打印
- id: "debug_000001"
symbol: "000001.SZ"
strategy_class: "DebugStrategy"
capital: 100000
params:
print_every: 1 # 每条K线都打印
simulate_signal: false # 不生成模拟信号
risk:
max_position_ratio: 0.8
stop_loss: 0.05
# 调试策略实例2: 平安银行 - 带信号模拟
- id: "debug_signal_000001"
symbol: "000001.SZ"
strategy_class: "DebugStrategy"
capital: 80000
params:
print_every: 1
simulate_signal: true # 生成模拟信号
signal_threshold: 2.0 # 价格变化2%触发信号
risk:
max_position_ratio: 0.6
stop_loss: 0.03
# 调试策略实例3: 浦发银行 - 每5条打印一次
- id: "debug_600000"
symbol: "600000.SH"
strategy_class: "DebugStrategy"
capital: 120000
params:
print_every: 5 # 每5条K线打印一次
simulate_signal: false
risk:
max_position_ratio: 0.7
stop_loss: 0.04

View File

@ -1,51 +1,108 @@
# QTrade 回测环境配置
# 数据库: qtrade_backtest
# 端口: 8030
# 说明: 公用配置在 global.yaml 中定义,此文件只包含回测环境特有配置
# QTrade 回测环境配置文件
# 环境配置
# ==================== 环境配置 ====================
environment:
mode: "backtest" # 环境模式
db_name: "qtrade_backtest"
mode: "backtest"
# 应用配置(特有)
app:
name: "QTrade-Backtest"
env: "backtest"
debug: true
# 数据库配置(特有)
# ==================== MySQL 配置 ====================
database:
host: "127.0.0.1"
port: 3306
user: "root"
password: "1234"
database: "qtrade_backtest"
pool_size: 5
pool_recycle: 3600
echo: false
# 日志配置(特有)
# ==================== 缓存配置 ====================
cache:
type: "memory" # memory-内存缓存
max_memory_mb: 4096 # 最大内存限制 4GB
# ==================== 日志配置 ====================
logging:
enabled: true
filepath: "d:\\workspace\\QTrade\\logs"
max_size: 10485760 # 10MB
backup_count: 5
level: "DEBUG"
file:
path: "logs/backtest"
path: "logs/backtest"
# 服务端口配置(特有)
# ==================== 策略配置 ====================
strategies:
strategy_folder: "d:/workspace/QTrade/configs/strategies"
max_concurrent_strategies: 50
# ==================== 客户端适配器配置 ====================
client_adapters:
backtest_adapter:
server_url: "ws://localhost:8030/ws/strategy"
timeout: 30 # seconds
# ==================== 下载数据源配置 ====================
data_downloader:
downloader: "xtquant"
xtquant:
xtquant_path: "C:\\Program Files\\国金证券QMT交易端\\userdata_mini\\datadir"
xtquant_token: "e83d8eec5226c0b4db4a1d40830e09e4ffe73e15"
optimize_addresses:
- "115.231.218.73:55310"
- "115.231.218.79:55310"
- "218.16.123.11:55310"
- "218.16.123.27:55310"
# ==================== 行情配置 ====================
market:
kline_periods:
- "tick"
- "1m"
- "5m"
- "15m"
- "30m"
- "60m"
- "1d"
- "1w"
# ==================== 技术指标配置 ====================
indicators:
enabled: true
enabled_indicators:
- macd
- kdj
- boll
- rsi
- ma
macd:
fast_period: 6
slow_period: 13
signal_period: 5
kdj:
period: 9
k_period: 3
d_period: 3
boll:
period: 20
std_multiplier: 2.0
rsi:
fast: 6
mid: 12
slow: 24
ma:
periods: [5, 10, 20, 60]
# ==================== 交易配置 ====================
trading:
sessions:
morning:
start: "09:30"
end: "11:30"
afternoon:
start: "13:00"
end: "15:00"
# ==================== 服务端口配置 ====================
services:
trading_service:
host: "0.0.0.0"
port: 8030
# 回测配置
backtest:
# 数据播放器配置
data_player:
# 历史数据推送地址
callback_url: "http://127.0.0.1:8030/api/v1/market/tick"
# 播放速度(1=实时,10=10倍速)
speed: 1
# 数据来源
data_source: "database" # database 或 csv
# 撮合引擎配置
matching:
# 撮合模式
mode: "market" # market-市价成交, limit-限价撮合
# 滑点(基点,1基点=0.01%)
slippage: 0 # 0表示无滑点
# 手续费率
commission_rate: 0.0003 # 万3
# 印花税率(卖出时)
stamp_tax_rate: 0.001 # 千1

View File

@ -1,142 +1,9 @@
# QTrade 全局公共配置
# 说明: 此文件包含所有服务共用的配置项
# QTrade 全局配置文件 - 环境模式选择
# 说明: 用于指定当前运行环境,系统会自动加载对应的配置文件
# 使用方式: 修改 current_mode 的值来切换环境
# - backtest: 回测环境,加载 configs/backtest.yaml
# - simulation: 模拟盘环境,加载 configs/simulation.yaml
# - production: 实盘环境,加载 configs/production.yaml
# 环境变量配置(对应 .env 文件内容)
environment:
# 当前环境: backtest, simulation, production
env: "backtest"
# 配置文件路径
config_file: "configs/backtest.yaml"
# 环境对应的配置文件映射
config_mapping:
backtest: "configs/backtest.yaml"
simulation: "configs/simulation.yaml"
production: "configs/production.yaml"
# 应用配置
app:
version: "2.0.0" # 公用版本号
# MySQL 配置(公用)
database:
host: "127.0.0.1"
port: 3306
user: "root"
password: "1234"
pool_size: 5
pool_recycle: 3600
echo: false
# 缓存配置(公用)
cache:
enabled: true
type: "memory" # memory-内存缓存
max_memory_mb: 4096 # 最大内存限制 4GB
capacity: 10000 # 最大缓存条目数
ttl: 3600 # 缓存过期时间(秒)
# 日志配置(公用)
logging:
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
file:
enabled: true
max_size: 10485760 # 10MB
backup_count: 5
# 数据源配置(公用)
data_source:
# 数据下载器类型: xtquant, qmt, tushare, akshare 等
downloader: "xtquant"
# XtQuant 下载器配置
xtquant:
xtquant_path: "C:\\Program Files\\国金证券QMT交易端\\userdata_mini\\datadir"
xtquant_token: "e83d8eec5226c0b4db4a1d40830e09e4ffe73e15" # XtQuant 数据接口 token(需要申请)
# XtQuant 优化地址(可选,用于提升数据下载速度)
optimize_addresses:
- "115.231.218.73:55310"
- "115.231.218.79:55310"
- "218.16.123.11:55310"
- "218.16.123.27:55310"
# 未来扩展:其他下载器配置
# qmt:
# ...
# tushare:
# token: "your_token_here"
# 数据检查器配置
data_checker:
# 报告配置
report:
enabled: false # 是否启用报告生成(默认关闭)
directory: "reports/datacheck" # 报告保存目录
# 行情配置(公用)
market:
kline_periods:
- "tick"
- "1m"
- "5m"
- "15m"
- "30m"
- "60m"
- "1d"
- "1w"
cache_ttl: 60
# 技术指标配置(公用)
indicators:
# 是否启用指标计算
enabled: true
# 要计算的指标列表
# 支持的指标类型: macd, kdj, boll, rsi, ma
enabled_indicators:
- macd
- kdj
- boll
- rsi
- ma
# 各指标的参数配置
macd:
fast_period: 6 # 快速EMA周期
slow_period: 13 # 慢速EMA周期
signal_period: 5 # 信号线周期
kdj:
period: 9 # RSV计算周期
k_period: 3 # K值平滑周期
d_period: 3 # D值平滑周期
boll:
period: 20 # 移动平均周期
std_multiplier: 2.0 # 标准差倍数
rsi:
fast: 6 # 快速RSI周期
mid: 12 # 中速RSI周期
slow: 24 # 慢速RSI周期
ma:
periods: [5, 10, 20, 60] # 移动平均线周期列表
# 交易配置(公用)
trading:
sessions:
morning:
start: "09:30"
end: "11:30"
afternoon:
start: "13:00"
end: "15:00"
# 服务端口配置(公用)
services:
trading_service:
host: "0.0.0.0"
# QMT交易配置(公用部分)
qmt:
account_type: "STOCK" # STOCK-股票账户, CREDIT-信用账户
# ==================== 环境模式配置 ====================
current_mode: "backtest"

View File

@ -1,38 +1,108 @@
# QTrade 实盘环境配置
# 数据库: qtrade_live
# 端口: 8010
# 说明: 公用配置在 global.yaml 中定义,此文件只包含实盘环境特有配置
# QTrade 实盘环境配置文件
# 环境配置
# ==================== 环境配置 ====================
environment:
mode: "live" # 环境模式
db_name: "qtrade_live"
mode: "production"
# 应用配置(特有)
app:
name: "QTrade-Live"
env: "production"
debug: false
# 数据库配置(特有)
# ==================== MySQL 配置 ====================
database:
host: "127.0.0.1"
port: 3306
user: "root"
password: "1234"
database: "qtrade_live"
pool_size: 5
pool_recycle: 3600
echo: false
# 日志配置(特有)
# ==================== 缓存配置 ====================
cache:
type: "memory" # memory-内存缓存
max_memory_mb: 4096 # 最大内存限制 4GB
# ==================== 日志配置 ====================
logging:
enabled: true
filepath: "d:\\workspace\\QTrade\\logs"
max_size: 10485760 # 10MB
backup_count: 5
level: "INFO"
file:
path: "logs/production"
backup_count: 10 # 实盘保留更多日志
path: "logs/production"
# 服务端口配置(特有)
# ==================== 策略配置 ====================
strategies:
strategy_folder: "d:/workspace/QTrade/configs/strategies"
max_concurrent_strategies: 50
# ==================== 客户端适配器配置 ====================
client_adapters:
production_adapter:
server_url: "ws://localhost:8010/ws/strategy"
timeout: 30 # seconds
# ==================== 下载数据源配置 ====================
data_downloader:
downloader: "xtquant"
xtquant:
xtquant_path: "C:\\Program Files\\国金证券QMT交易端\\userdata_mini\\datadir"
xtquant_token: "e83d8eec5226c0b4db4a1d40830e09e4ffe73e15"
optimize_addresses:
- "115.231.218.73:55310"
- "115.231.218.79:55310"
- "218.16.123.11:55310"
- "218.16.123.27:55310"
# ==================== 行情配置 ====================
market:
kline_periods:
- "tick"
- "1m"
- "5m"
- "15m"
- "30m"
- "60m"
- "1d"
- "1w"
# ==================== 技术指标配置 ====================
indicators:
enabled: true
enabled_indicators:
- macd
- kdj
- boll
- rsi
- ma
macd:
fast_period: 6
slow_period: 13
signal_period: 5
kdj:
period: 9
k_period: 3
d_period: 3
boll:
period: 20
std_multiplier: 2.0
rsi:
fast: 6
mid: 12
slow: 24
ma:
periods: [5, 10, 20, 60]
# ==================== 交易配置 ====================
trading:
sessions:
morning:
start: "09:30"
end: "11:30"
afternoon:
start: "13:00"
end: "15:00"
# ==================== 服务端口配置 ====================
services:
trading_service:
host: "0.0.0.0"
port: 8010
# QMT配置(特有)
qmt:
account_id: "" # 需要填写实际账号
session_id: 123456 # 会话ID
callback_url: "http://127.0.0.1:8010/api/v1/market/tick"
trade_callback_url: "http://127.0.0.1:8010/api/v1/trade/fill"

View File

@ -1,37 +1,108 @@
# QTrade 模拟环境配置
# 数据库: qtrade_sim
# 端口: 8020
# 说明: 公用配置在 global.yaml 中定义,此文件只包含模拟环境特有配置
# QTrade 模拟盘环境配置文件
# 环境配置
# ==================== 环境配置 ====================
environment:
mode: "sim" # 环境模式
db_name: "qtrade_sim"
mode: "simulation"
# 应用配置(特有)
app:
name: "QTrade-Simulation"
env: "simulation"
debug: true
# 数据库配置(特有)
# ==================== MySQL 配置 ====================
database:
host: "127.0.0.1"
port: 3306
user: "root"
password: "1234"
database: "qtrade_sim"
pool_size: 5
pool_recycle: 3600
echo: false
# 日志配置(特有)
# ==================== 缓存配置 ====================
cache:
type: "memory" # memory-内存缓存
max_memory_mb: 4096 # 最大内存限制 4GB
# ==================== 日志配置 ====================
logging:
enabled: true
filepath: "d:\\workspace\\QTrade\\logs"
max_size: 10485760 # 10MB
backup_count: 5
level: "DEBUG"
file:
path: "logs/simulation"
path: "logs/simulation"
# 服务端口配置(特有)
# ==================== 策略配置 ====================
strategies:
strategy_folder: "d:/workspace/QTrade/configs/strategies"
max_concurrent_strategies: 50
# ==================== 客户端适配器配置 ====================
client_adapters:
simulation_adapter:
server_url: "ws://localhost:8020/ws/strategy"
timeout: 30 # seconds
# ==================== 下载数据源配置 ====================
data_downloader:
downloader: "xtquant"
xtquant:
xtquant_path: "C:\\Program Files\\国金证券QMT交易端\\userdata_mini\\datadir"
xtquant_token: "e83d8eec5226c0b4db4a1d40830e09e4ffe73e15"
optimize_addresses:
- "115.231.218.73:55310"
- "115.231.218.79:55310"
- "218.16.123.11:55310"
- "218.16.123.27:55310"
# ==================== 行情配置 ====================
market:
kline_periods:
- "tick"
- "1m"
- "5m"
- "15m"
- "30m"
- "60m"
- "1d"
- "1w"
# ==================== 技术指标配置 ====================
indicators:
enabled: true
enabled_indicators:
- macd
- kdj
- boll
- rsi
- ma
macd:
fast_period: 6
slow_period: 13
signal_period: 5
kdj:
period: 9
k_period: 3
d_period: 3
boll:
period: 20
std_multiplier: 2.0
rsi:
fast: 6
mid: 12
slow: 24
ma:
periods: [5, 10, 20, 60]
# ==================== 交易配置 ====================
trading:
sessions:
morning:
start: "09:30"
end: "11:30"
afternoon:
start: "13:00"
end: "15:00"
# ==================== 服务端口配置 ====================
services:
trading_service:
host: "0.0.0.0"
port: 8020
# QMT配置(特有)
qmt:
account_id: "" # 需要填写模拟账号
session_id: 123457 # 会话ID(与实盘不同)
callback_url: "http://127.0.0.1:8020/api/v1/market/tick"
trade_callback_url: "http://127.0.0.1:8020/api/v1/trade/fill"

10
main.py
View File

@ -1,10 +0,0 @@
"""
QTrade Server主启动脚本
启动策略服务器
"""
from src.networks.server.ws_server import start_server
if __name__ == "__main__":
start_server(host="0.0.0.0", port=8000)

View File

@ -1,4 +1,4 @@
"""
"""
数据库管理交互式脚本
提供交互式命令行界面管理数据库
"""
@ -11,12 +11,9 @@ from pathlib import Path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
# 设置环境变量
os.environ["CONFIG_FILE"] = "configs/backtest.yaml"
# 导入必须在路径设置和环境变量之后
# 导入必须在路径设置之后
from src.database_manager import DatabaseManager # noqa: E402
from src.core import get_config # noqa: E402
from src.core.config import Config # noqa: E402
from sqlalchemy import create_engine, text # noqa: E402
@ -24,9 +21,9 @@ class DatabaseAdminCLI:
"""数据库管理命令行界面"""
def __init__(self):
Config.initialize()
self.db_manager = DatabaseManager()
self.config = get_config()
self.current_db = self.config.get("database.database")
self.current_db = Config.get("database.database")
self.running = True
def print_banner(self):
@ -196,7 +193,7 @@ class DatabaseAdminCLI:
if self.db_manager.drop_database(database, confirm=True):
print(f"✓ 数据库已删除: {database}")
if self.current_db == database:
self.current_db = self.config.get("database.database")
self.current_db = Config.get("database.database")
print(f"✓ 已切换回默认数据库: {self.current_db}")
else:
print(f"✗ 数据库删除失败: {database}")
@ -279,9 +276,9 @@ class DatabaseAdminCLI:
# 创建数据库连接
db_url = (
f"mysql+pymysql://{self.config.get('database.user')}:"
f"{self.config.get('database.password')}@"
f"{self.config.get('database.host')}:{self.config.get('database.port')}"
f"mysql+pymysql://{Config.get('database.user')}:"
f"{Config.get('database.password')}@"
f"{Config.get('database.host')}:{Config.get('database.port')}"
f"/{self.current_db}"
)
engine = create_engine(db_url, echo=False)
@ -331,9 +328,9 @@ class DatabaseAdminCLI:
# 创建数据库连接
db_url = (
f"mysql+pymysql://{self.config.get('database.user')}:"
f"{self.config.get('database.password')}@"
f"{self.config.get('database.host')}:{self.config.get('database.port')}"
f"mysql+pymysql://{Config.get('database.user')}:"
f"{Config.get('database.password')}@"
f"{Config.get('database.host')}:{Config.get('database.port')}"
f"/{self.current_db}"
)
engine = create_engine(db_url, echo=False)
@ -435,9 +432,9 @@ class DatabaseAdminCLI:
return
db_url = (
f"mysql+pymysql://{self.config.get('database.user')}:"
f"{self.config.get('database.password')}@"
f"{self.config.get('database.host')}:{self.config.get('database.port')}"
f"mysql+pymysql://{Config.get('database.user')}:"
f"{Config.get('database.password')}@"
f"{Config.get('database.host')}:{Config.get('database.port')}"
f"/{self.current_db}"
)
engine = create_engine(db_url, echo=False)
@ -469,9 +466,9 @@ class DatabaseAdminCLI:
return
db_url = (
f"mysql+pymysql://{self.config.get('database.user')}:"
f"{self.config.get('database.password')}@"
f"{self.config.get('database.host')}:{self.config.get('database.port')}"
f"mysql+pymysql://{Config.get('database.user')}:"
f"{Config.get('database.password')}@"
f"{Config.get('database.host')}:{Config.get('database.port')}"
f"/{self.current_db}"
)
engine = create_engine(db_url, echo=False)

View File

@ -12,11 +12,8 @@ from pathlib import Path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
# 设置环境变量
os.environ["CONFIG_FILE"] = "configs/backtest.yaml"
from src.database_manager import DatabaseManager
from src.core import get_config
from src.core.config import Config
from sqlalchemy import text
@ -40,10 +37,10 @@ def main():
print(" 删除旧格式的指标表")
print("=" * 70)
# 初始化数据库管理器
config = get_config()
# 初始化配置和数据库管理器
Config.initialize()
db_manager = DatabaseManager()
database = config.get("database.database")
database = Config.get("database.database")
print(f"\n当前数据库: {database}")
@ -75,9 +72,9 @@ def main():
print("\n开始删除...")
db_url = (
f"mysql+pymysql://{config.get('database.user')}:"
f"{config.get('database.password')}@"
f"{config.get('database.host')}:{config.get('database.port')}"
f"mysql+pymysql://{Config.get('database.user')}:"
f"{Config.get('database.password')}@"
f"{Config.get('database.host')}:{Config.get('database.port')}"
f"/{database}"
)

View File

@ -6,15 +6,14 @@ from pathlib import Path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
os.environ["CONFIG_FILE"] = "configs/backtest.yaml"
from src.database_manager import DatabaseManager
from src.core import get_config
from src.core.config import Config
from sqlalchemy import create_engine, text
config = get_config()
Config.initialize()
db = DatabaseManager()
db_name = config.get("database.database")
db_name = Config.get("database.database")
# 获取所有旧格式的表
tables = db.list_tables(db_name)
@ -32,9 +31,9 @@ print("开始删除...\n")
# 创建数据库连接
db_url = (
f"mysql+pymysql://{config.get('database.user')}:"
f"{config.get('database.password')}@"
f"{config.get('database.host')}:{config.get('database.port')}"
f"mysql+pymysql://{Config.get('database.user')}:"
f"{Config.get('database.password')}@"
f"{Config.get('database.host')}:{Config.get('database.port')}"
f"/{db_name}"
)
engine = create_engine(db_url)

View File

@ -1073,8 +1073,7 @@ def main():
# 加载配置和DataService
try:
config = Config()
config.load_with_global("configs/backtest.yaml")
config = Config("configs/backtest.yaml")
data_service = DataService.from_config(config)
print("✓ DataService初始化成功")
except Exception as e:

View File

@ -7,16 +7,14 @@
- 调用底层WebSocket客户端进行通信
"""
from typing import Optional, Dict, List
from typing import Optional, Dict
from datetime import datetime
from dataclasses import dataclass
import pandas as pd
import uuid
from src.networks.client.ws_client import WSClient
from src.core.logger import get_logger
logger = get_logger("StrategyClient")
from src.core.logger import Logger
@dataclass
@ -41,9 +39,7 @@ class BacktestClientAdapter:
- 调用WSClient发送消息
"""
def __init__(
self, server_url: str = "ws://localhost:8000/ws/strategy", timeout: int = 30
):
def __init__(self, server_url: str, timeout: int):
"""
初始化策略客户端适配器
@ -52,7 +48,7 @@ class BacktestClientAdapter:
timeout: 超时时间(秒)
"""
self.ws_client = WSClient(server_url, timeout)
logger.info("BacktestClientAdapter initialized")
Logger.info("BacktestClientAdapter initialized")
def _create_header(self) -> dict:
"""创建协议头 v1.0"""
@ -100,7 +96,7 @@ class BacktestClientAdapter:
# 检查是否是错误消息
if response.get("msg_type") == "ERROR":
logger.error(
Logger.error(
f"Server error: {response.get('error_code')} - {response.get('error_message')}"
)
return None
@ -164,7 +160,7 @@ class BacktestClientAdapter:
# 检查是否是错误消息
if response.get("msg_type") == "ERROR":
logger.error(
Logger.error(
f"Server error: {response.get('error_code')} - {response.get('error_message')}"
)
return {symbol: None for symbol in klines_data.keys()}

View File

@ -9,9 +9,7 @@ from typing import List, Optional
from src.data_service.data_service import DataService
from src.backtest.bt_task import BacktestTask
from src.backtest.bt_client_adapter import BacktestClientAdapter
from src.core.logger import get_logger
logger = get_logger("BacktestEngine")
from src.core.logger import Logger
class BacktestEngine:
@ -34,9 +32,9 @@ class BacktestEngine:
self.tasks: List[BacktestTask] = [] # 任务列表
if self.backtest_client:
logger.info("BacktestEngine initialized with BacktestClientAdapter")
Logger.info("BacktestEngine initialized with BacktestClientAdapter")
else:
logger.info("BacktestEngine initialized without BacktestClientAdapter")
Logger.info("BacktestEngine initialized without BacktestClientAdapter")
def add_task(self, task: BacktestTask) -> None:
"""
@ -46,7 +44,7 @@ class BacktestEngine:
task: 回测任务对象
"""
self.tasks.append(task)
logger.info(
Logger.info(
f"Task added: {task.strategy_name} on {task.symbols} "
f"({task.start_date.date()} to {task.end_date.date()}, {task.period})"
)
@ -63,20 +61,20 @@ class BacktestEngine:
def clear_tasks(self) -> None:
"""清空所有任务"""
self.tasks.clear()
logger.info("All tasks cleared")
Logger.info("All tasks cleared")
def run(self) -> None:
"""运行所有回测任务"""
if not self.tasks:
logger.warning("No tasks to run")
Logger.warning("No tasks to run")
return
logger.info(f"Starting {len(self.tasks)} backtest task(s)")
Logger.info(f"Starting {len(self.tasks)} backtest task(s)")
for task_idx, task in enumerate(self.tasks, 1):
logger.info("=" * 60)
logger.info(f"Task {task_idx}/{len(self.tasks)}: {task.strategy_name}")
logger.info(
Logger.info("=" * 60)
Logger.info(f"Task {task_idx}/{len(self.tasks)}: {task.strategy_name}")
Logger.info(
f"Symbols: {task.symbols}, Period: {task.period}, "
f"Time: {task.start_date.date()}~{task.end_date.date()}"
)
@ -92,10 +90,10 @@ class BacktestEngine:
)
if df is not None and not df.empty:
data_dict[symbol] = df
logger.info(f" {symbol}: {len(df)} records")
Logger.info(f" {symbol}: {len(df)} records")
if not data_dict:
logger.error("Data is empty, skipping this task")
Logger.error("Data is empty, skipping this task")
continue
# 2. 播放数据
@ -104,7 +102,7 @@ class BacktestEngine:
all_timestamps.update(df.index)
timestamps = sorted(all_timestamps)
logger.info(f"Starting to play {len(timestamps)} timestamps")
Logger.info(f"Starting to play {len(timestamps)} timestamps")
for idx, timestamp in enumerate(timestamps, 1):
current_bars = {}
@ -124,13 +122,12 @@ class BacktestEngine:
)
# 处理返回信号
if response is not None:
logger.info(f"Received response: {response}")
Logger.info(f"Received response: {response}")
# 每50个时间点输出一次进度
if idx % 50 == 0:
logger.info(f" Progress: {idx}/{len(timestamps)}")
Logger.info(f" Progress: {idx}/{len(timestamps)}")
Logger.info(f"Task {task_idx} completed")
logger.info(f"Task {task_idx} completed")
logger.info("=" * 60)
logger.info("All backtest tasks completed")
Logger.info("=" * 60)
Logger.info("All backtest tasks completed")

View File

@ -10,35 +10,36 @@ from src.data_service.data_service import DataService
from src.backtest.bt_engine import BacktestEngine
from src.backtest.bt_task import BacktestTask
from src.backtest.bt_client_adapter import BacktestClientAdapter
from src.core.logger import get_logger
from src.core.logger import Logger
from src.core.config import Config
logger = get_logger("BacktestMain")
def main():
"""Main function"""
logger.info("=== Backtest system starting ===")
# 首先初始化配置
Config.initialize()
# 然后初始化日志
Logger.initialize("Backtest")
Logger.info("=== Backtest system starting ===")
# Load configuration
config = Config()
config.load_with_global("configs/backtest.yaml")
logger.info("Config loaded")
Logger.info("Config loaded")
# Initialize data service
data_service = DataService.from_config(config)
logger.info("DataService initialized")
data_service = DataService.from_config()
Logger.info("DataService initialized")
# Initialize strategy client (increase timeout)
config_bt_client = Config.get("client_adapters.backtest_adapter")
backtest_client = BacktestClientAdapter(
"ws://localhost:8000/ws/strategy", timeout=30
config_bt_client.get("server_url"), timeout=config_bt_client.get("timeout")
)
logger.info("BacktestClientAdapter initialized")
Logger.info("BacktestClientAdapter initialized")
# Initialize backtest engine (pass in BacktestClientAdapter)
engine = BacktestEngine(data_service, backtest_client)
logger.info("BacktestEngine created")
Logger.info("BacktestEngine created")
# Create backtest task example
task = BacktestTask(
symbols=["000001.SZ", "600000.SH"],
@ -55,12 +56,11 @@ def main():
# View task list
tasks = engine.get_tasks()
logger.info(f"Total tasks: {len(tasks)}")
Logger.info(f"Total tasks: {len(tasks)}")
# Run all backtest tasks
engine.run()
logger.info("=== Backtest system initialization completed ===")
Logger.info("=== Backtest system initialization completed ===")
if __name__ == "__main__":

View File

@ -6,7 +6,7 @@
"""
import logging
from typing import Dict, Optional, Any, Union
from typing import Dict, Optional, Any
import pandas as pd
from src.core.config import Config
@ -29,21 +29,19 @@ class CacheManager:
- ✗ 指标计算逻辑(由DataService负责)
"""
def __init__(self, config: Union[dict, Config], db_manager=None):
def __init__(self, db_manager=None):
"""
初始化缓存管理器
Args:
config: 配置字典或Config对象,包含cache相关配置
db_manager: 数据库管理器(可选),用于缓存未命中时从数据库加载
"""
self.config = config
self._db_manager = db_manager
# 获取缓存配置
cache_config = config.get("cache", {})
# 从Config单例获取缓存配置
cache_config = Config.get("cache", {})
self.enabled = cache_config.get("enabled", True)
self.max_memory_mb = cache_config.get("max_memory_mb", 4096) # 默认4GB
self.max_memory_mb = cache_config.get("max_memory_mb", 4096)
# 核心数据结构
self._cache: Dict[str, Dict[str, Any]] = {}

View File

@ -25,19 +25,10 @@ from .models import (
)
# 配置管理
from .config import Config, get_config, set_config
from .config import Config
# 日志管理
from .logger import (
Logger,
get_logger,
set_log_level,
debug,
info,
warning,
error,
exception,
)
from .logger import Logger
__all__ = [
# 枚举
@ -59,15 +50,6 @@ __all__ = [
"Symbol",
# 配置
"Config",
"get_config",
"set_config",
# 日志
"Logger",
"get_logger",
"set_log_level",
"debug",
"info",
"warning",
"error",
"exception",
]

View File

@ -1,54 +1,135 @@
"""
配置管理工具类
支持读取、修改和保存 YAML 配置文件
配置管理工具类 - 单例模式
支持环境自动识别,根据 current_mode 自动加载对应的环境配置文件
"""
import os
from pathlib import Path
from typing import Any, Dict, Optional, Union
from typing import Any, Dict, Union
import yaml
class Config:
"""
配置管理类
配置管理类(单例模式)
功能:
- 读取 YAML 配置文件
- 支持嵌套键访问(如 'database.host')
- 修改配置值
- 保存配置到文件
- 合并多个配置文件(全局配置 + 环境配置)
特性:
- 单例模式,全局唯一实例
- 支持嵌套键访问(如 "database.host")
- 自动根据 global.yaml 中的 current_mode 加载对应环境配置
- 通过类方法直接访问,无需传递实例
使用示例:
# 初始化配置(只需调用一次,通常在程序入口)
Config.initialize() # 自动读取 global.yaml 的 current_mode,然后加载对应配置
# 获取配置(任意位置直接调用)
db_host = Config.get("database.host")
db_name = Config.get("database.database")
# 获取实例(如果需要)
config = Config.instance()
# 环境判断
if Config.is_production():
print("生产环境")
"""
def __init__(self, config_file: Optional[Union[str, Path]] = None):
# ==================== 配置文件路径 ====================
GLOBAL_CONFIG_PATH = "d:/workspace/QTrade/configs/global.yaml"
CONFIG_DIR = "d:/workspace/QTrade/configs"
# ==================== 单例相关 ====================
_instance: "Config | None" = None
_data: Dict[str, Any] = {}
_config_file: Union[Path, None] = None
_current_mode: str = ""
_initialized: bool = False
def __new__(cls):
"""单例模式:确保只有一个配置实例"""
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
@classmethod
def initialize(cls, file_path: Union[str, Path, None] = None) -> "Config":
"""
初始化配置对象
初始化配置(程序入口调用一次)
工作流程:
1. 如果指定了 file_path,直接加载该配置文件
2. 否则,先读取 global.yaml 获取 current_mode
3. 根据 current_mode 自动加载对应的配置文件(backtest.yaml/simulation.yaml/production.yaml)
Args:
config_file: 配置文件路径,支持相对路径和绝对路径
如果为 None,从环境变量 CONFIG_FILE 读取
file_path: 配置文件路径,如果为 None 则自动根据 current_mode 加载
Returns:
Config 实例
Raises:
FileNotFoundError: 配置文件不存在
ValueError: current_mode 值无效
"""
self._data: Dict[str, Any] = {}
self._config_file: Optional[Path] = None
if cls._initialized and file_path is None:
return cls._instance # type: ignore
if config_file is None:
# 从环境变量读取
config_file = os.environ.get("CONFIG_FILE")
instance = cls()
if config_file:
self.load(config_file)
if file_path:
# 直接加载指定的配置文件
instance._load(file_path)
cls._current_mode = cls.get("environment.mode", "unknown")
else:
# 先读取 global.yaml 获取 current_mode
global_path = Path(cls.GLOBAL_CONFIG_PATH)
if not global_path.exists():
raise FileNotFoundError(f"全局配置文件不存在: {global_path}")
def load(self, config_file: Union[str, Path], merge: bool = False) -> "Config":
with open(global_path, "r", encoding="utf-8") as f:
global_config = yaml.safe_load(f) or {}
current_mode = global_config.get("current_mode")
if not current_mode:
raise ValueError("global.yaml 中未找到 current_mode 配置")
if current_mode not in ["backtest", "simulation", "production"]:
raise ValueError(
f"无效的 current_mode 值: {current_mode},必须是 backtest/simulation/production 之一"
)
# 根据 current_mode 加载对应的配置文件
config_path = Path(cls.CONFIG_DIR) / f"{current_mode}.yaml"
if not config_path.exists():
raise FileNotFoundError(f"环境配置文件不存在: {config_path}")
instance._load(config_path)
cls._current_mode = current_mode
cls._initialized = True
return instance
@classmethod
def instance(cls) -> "Config":
"""
加载配置文件
获取配置实例
Returns:
Config 实例
Raises:
RuntimeError: 配置未初始化
"""
if not cls._initialized:
raise RuntimeError("Config 未初始化,请先调用 Config.initialize()")
return cls._instance # type: ignore
def _load(self, config_file: Union[str, Path]) -> None:
"""
加载配置文件(内部方法)
Args:
config_file: 配置文件路径
merge: 是否合并到现有配置(True)还是覆盖(False)
Returns:
self,支持链式调用
"""
config_path = Path(config_file)
@ -61,80 +142,67 @@ class Config:
raise FileNotFoundError(f"配置文件不存在: {config_path}")
with open(config_path, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
Config._data = yaml.safe_load(f) or {}
if merge:
self._merge_dict(self._data, data)
else:
self._data = data
self._config_file = config_path
Config._config_file = config_path
return self
def load_with_global(self, env_config: Union[str, Path]) -> "Config":
@classmethod
def get(cls, key: str, default: Any = None) -> Any:
"""
加载环境配置并合并全局配置
获取配置值(类方法,直接调用)
支持嵌套键访问,使用点号分隔(如 'database.host')
Args:
env_config: 环境配置文件(如 'configs/production.yaml')
Returns:
self,支持链式调用
"""
# 先加载全局配置
self.load("configs/global.yaml")
# 再加载环境配置并合并
self.load(env_config, merge=True)
return self
def get(self, key: str, default: Any = None) -> Any:
"""
获取配置值,支持嵌套键
Args:
key: 配置键,支持点分隔的嵌套键(如 'database.host')
default: 默认值
key: 配置键(支持嵌套,如 'database.host')
default: 默认值,如果配置不存在则返回此值
Returns:
配置值
Raises:
RuntimeError: 配置未初始化
Examples:
>>> config.get('app.name')
'QTrade'
>>> config.get('database.host')
>>> Config.get('database.host')
'127.0.0.1'
>>> Config.get('database.database')
'qtrade_backtest'
>>> Config.get('nonexistent.key', 'default_value')
'default_value'
"""
if not cls._initialized:
raise RuntimeError("Config 未初始化,请先调用 Config.initialize()")
keys = key.split(".")
value = self._data
value = cls._data
for k in keys:
for i, k in enumerate(keys):
if isinstance(value, dict):
value = value.get(k)
if k not in value:
return default
value = value[k]
else:
return default
if value is None:
return default
return value
def set(self, key: str, value: Any) -> "Config":
@classmethod
def set(cls, key: str, value: Any) -> None:
"""
设置配置值,支持嵌套键
设置配置值(类方法)
支持嵌套键设置,使用点号分隔(如 'database.host')
Args:
key: 配置键,支持点分隔的嵌套键
key: 配置键(支持嵌套,如 'database.host')
value: 配置值
Returns:
self,支持链式调用
Examples:
>>> config.set('database.host', '192.168.1.100')
>>> config.set('app.debug', True)
"""
if not cls._initialized:
raise RuntimeError("Config 未初始化,请先调用 Config.initialize()")
keys = key.split(".")
data = self._data
data = cls._data
# 遍历到倒数第二个键
for k in keys[:-1]:
@ -146,140 +214,49 @@ class Config:
# 设置最后一个键的值
data[keys[-1]] = value
return self
def update(self, data: Dict[str, Any]) -> "Config":
@classmethod
def reload(cls, file_path: Union[str, Path, None] = None) -> None:
"""
批量更新配置
重新加载配置文件
Args:
data: 配置字典
Returns:
self,支持链式调用
Examples:
>>> config.update({
... 'database.host': '192.168.1.100',
... 'database.port': 3307
... })
file_path: 配置文件路径,如果为 None,重新加载当前文件
"""
for key, value in data.items():
self.set(key, value)
return self
if file_path is None:
if cls._config_file is None:
raise ValueError("没有可重新加载的配置文件")
file_path = cls._config_file
def save(self, config_file: Optional[Union[str, Path]] = None) -> "Config":
"""
保存配置到文件
cls.instance()._load(file_path)
Args:
config_file: 配置文件路径,如果为 None,保存到原文件
@classmethod
def to_dict(cls) -> Dict[str, Any]:
"""返回配置字典的副本"""
return cls._data.copy()
Returns:
self,支持链式调用
"""
if config_file is None:
config_file = self._config_file
@classmethod
def get_env_mode(cls) -> str:
"""获取当前环境模式: backtest、simulation 或 production"""
if cls._current_mode:
return cls._current_mode
return cls.get("environment.mode", "unknown")
if config_file is None:
raise ValueError("未指定配置文件路径")
@classmethod
def is_production(cls) -> bool:
"""判断是否为生产环境"""
return cls.get_env_mode() == "production"
config_path = Path(config_file)
@classmethod
def is_simulation(cls) -> bool:
"""判断是否为模拟环境"""
return cls.get_env_mode() == "simulation"
# 确保目录存在
config_path.parent.mkdir(parents=True, exist_ok=True)
with open(config_path, "w", encoding="utf-8") as f:
yaml.safe_dump(
self._data,
f,
allow_unicode=True,
default_flow_style=False,
sort_keys=False,
)
return self
def to_dict(self) -> Dict[str, Any]:
"""
返回配置字典
Returns:
配置字典的副本
"""
return self._data.copy()
def __getitem__(self, key: str) -> Any:
"""支持字典式访问"""
value = self.get(key)
if value is None:
raise KeyError(f"配置键不存在: {key}")
return value
def __setitem__(self, key: str, value: Any) -> None:
"""支持字典式赋值"""
self.set(key, value)
def __contains__(self, key: str) -> bool:
"""支持 in 操作"""
return self.get(key) is not None
@classmethod
def is_backtest(cls) -> bool:
"""判断是否为回测环境"""
return cls.get_env_mode() == "backtest"
def __repr__(self) -> str:
return f"Config(file={self._config_file}, keys={len(self._data)})"
@staticmethod
def _merge_dict(base: Dict, override: Dict) -> None:
"""
递归合并字典(原地修改 base)
Args:
base: 基础字典
override: 覆盖字典
"""
for key, value in override.items():
if key in base and isinstance(base[key], dict) and isinstance(value, dict):
Config._merge_dict(base[key], value)
else:
base[key] = value
# 全局配置实例
_global_config: Optional[Config] = None
def get_config() -> Config:
"""
获取全局配置实例(单例模式)
Returns:
全局配置对象
Examples:
>>> from src.core.config import get_config
>>> config = get_config()
>>> db_host = config.get('database.host')
"""
global _global_config
if _global_config is None:
# 从环境变量读取配置文件
config_file = os.environ.get("CONFIG_FILE")
if config_file:
_global_config = Config().load_with_global(config_file)
else:
# 默认加载全局配置
_global_config = Config("configs/global.yaml")
return _global_config
def set_config(config: Config) -> None:
"""
设置全局配置实例
Args:
config: 配置对象
"""
global _global_config
_global_config = config
env = self.get_env_mode()
return f"Config(file={self._config_file}, env={env}, keys={len(self._data)})"

View File

@ -5,6 +5,47 @@
"""
class ConfigKey:
"""
配置文件键名常量
使用示例:
from src.core.constants import ConfigKey
from src.core.config import Config
config = Config("configs/backtest.yaml")
db_host = config.get(ConfigKey.DATABASE_HOST)
cache_enabled = config.get(ConfigKey.CACHE_ENABLED)
"""
# 数据库配置
DATABASE_HOST = "database.host"
DATABASE_PORT = "database.port"
DATABASE_USER = "database.user"
DATABASE_PASSWORD = "database.password"
DATABASE_DATABASE = "database.database"
# 缓存配置
CACHE_ENABLED = "cache.enabled"
CACHE_TYPE = "cache.type"
CACHE_MAX_MEMORY_MB = "cache.max_memory_mb"
CACHE_CAPACITY = "cache.capacity"
CACHE_TTL = "cache.ttl"
# 日志配置
LOG_LEVEL = "log.level"
LOG_FILE = "log.file"
LOG_FORMAT = "log.format"
# 数据下载配置
DATA_SOURCE = "data.source"
DATA_START_DATE = "data.start_date"
DATA_END_DATE = "data.end_date"
# 策略配置
STRATEGY_CONFIG_DIR = "strategy.config_dir"
class Period:
"""
周期常量定义(与 global.yaml 中的 kline_periods 保持一致)
@ -260,32 +301,6 @@ class IndicatorColumns:
return cls.MACD_ALL + cls.KDJ_ALL + cls.BOLL_ALL + cls.RSI_ALL + cls.MA_ALL
class ConfigKey:
"""
配置键名常量
使用示例:
from src.core.constants import ConfigKey
cache_enabled = config.get(ConfigKey.CACHE_ENABLED, True)
"""
# 缓存配置
CACHE_ENABLED = "cache_enabled"
CACHE_MAX_MEMORY_MB = "cache_max_memory_mb"
# 数据库配置
DB_TYPE = "db_type"
DB_PATH = "db_path"
# 数据源配置
DATA_SOURCE = "data_source"
# 日志配置
LOG_LEVEL = "log_level"
LOG_PATH = "log_path"
class ErrorCode:
"""
错误码常量

View File

@ -1,202 +1,168 @@
"""
日志工具类
支持四个级别的日志记录:DEBUG, INFO, WARNING, ERROR
日志工具类 - 单例模式
通过 Logger 类方法直接访问,无需获取实例
"""
import logging
import io
import sys
from pathlib import Path
from logging.handlers import RotatingFileHandler
from typing import Optional
from typing import Dict, Optional
from .config import get_config
from .config import Config
class Logger:
"""
日志管理类
日志管理类(单例模式)
功能:
- 支持四个日志级别:DEBUG, INFO, WARNING, ERROR
- 同时输出到控制台和文件
- 支持日志轮转(按文件大小)
- 从配置文件读取日志设置
特性:
- 支持多个命名日志器
- 通过类方法直接访问
- 自动从 Config 读取配置
使用示例:
# 初始化(程序入口调用一次,Config 必须先初始化)
Logger.initialize()
# 直接使用类方法记录日志
Logger.info("消息")
Logger.error("错误信息")
# 使用命名日志器
Logger.info("消息", name="Strategy")
Logger.debug("调试信息", name="DataService")
# 设置日志级别
Logger.set_level("DEBUG")
"""
_instances = {} # 存储不同名称的 logger 实例
# ==================== 单例相关 ====================
_loggers: Dict[str, logging.Logger] = {}
_initialized: bool = False
_default_name: str = "QTrade"
def __init__(self, name: str = "QTrade"):
@classmethod
def initialize(cls, default_name: str = "QTrade", level: str = "INFO") -> None:
"""
初始化日志对象
初始化日志系统(程序入口调用一次)
Args:
name: 日志名称,用于区分不同模块
default_name: 默认日志器名称
"""
self.name = name
self.logger = logging.getLogger(name)
if cls._initialized:
return
# 避免重复添加 handler
if not self.logger.handlers:
self._setup_logger()
cls._default_name = default_name
cls._get_or_create_logger(default_name, level)
cls._initialized = True
def _setup_logger(self):
"""配置日志"""
# 读取配置
config = get_config()
@classmethod
def _get_or_create_logger(cls, name: str, level: str = "INFO") -> logging.Logger:
"""获取或创建日志器"""
if name in cls._loggers:
return cls._loggers[name]
# 日志级别
level_str = config.get("logging.level", "INFO")
level = getattr(logging, level_str.upper(), logging.INFO)
self.logger.setLevel(level)
logger = logging.getLogger(name)
if not logger.handlers:
cls._setup_logger(logger, name, level)
cls._loggers[name] = logger
return logger
@classmethod
def _setup_logger(cls, logger: logging.Logger, name: str, level: str = "INFO") -> None:
"""配置日志器"""
logger.setLevel(level)
# 日志格式
log_format = config.get(
"logging.format", "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
formatter = logging.Formatter(log_format)
# 控制台处理器(设置UTF-8编码避免中文乱码)
import io
# 包装stdout为UTF-8流
# 控制台处理器(UTF-8编码)
utf8_stdout = io.TextIOWrapper(
sys.stdout.buffer, encoding="utf-8", errors="replace", line_buffering=True
sys.stdout.buffer,
encoding="utf-8",
errors="replace",
line_buffering=True,
)
console_handler = logging.StreamHandler(utf8_stdout)
console_handler.setLevel(level)
console_handler.setFormatter(formatter)
self.logger.addHandler(console_handler)
logger.addHandler(console_handler)
# 文件处理器
if config.get("logging.file.enabled", True):
log_path = config.get("logging.file.path", "logs")
max_size = config.get("logging.file.max_size", 10485760) # 10MB
backup_count = config.get("logging.file.backup_count", 5)
# 创建日志目录
if Config.get("logging.enabled"):
log_path = Config.get("logging.filepath")
log_dir = Path(log_path)
if not log_dir.is_absolute():
# 相对路径,相对于项目根目录
project_root = Path(__file__).parent.parent.parent
log_dir = project_root / log_path
log_dir.mkdir(parents=True, exist_ok=True)
if log_dir.is_absolute():
log_dir.mkdir(parents=True, exist_ok=True)
log_file = log_dir / f"{name}.log"
# 日志文件路径
log_file = log_dir / f"{self.name}.log"
# 使用 RotatingFileHandler 进行日志轮转
file_handler = RotatingFileHandler(
log_file, maxBytes=max_size, backupCount=backup_count, encoding="utf-8"
)
file_handler.setLevel(level)
file_handler.setFormatter(formatter)
self.logger.addHandler(file_handler)
def debug(self, message: str, *args, **kwargs):
"""记录 DEBUG 级别日志"""
self.logger.debug(message, *args, **kwargs)
def info(self, message: str, *args, **kwargs):
"""记录 INFO 级别日志"""
self.logger.info(message, *args, **kwargs)
def warning(self, message: str, *args, **kwargs):
"""记录 WARNING 级别日志"""
self.logger.warning(message, *args, **kwargs)
def error(self, message: str, *args, **kwargs):
"""记录 ERROR 级别日志"""
self.logger.error(message, *args, **kwargs)
def exception(self, message: str, *args, **kwargs):
"""记录 ERROR 级别日志,并包含异常堆栈信息"""
self.logger.exception(message, *args, **kwargs)
max_size = Config.get("logging.max_size")
backup_count = Config.get("logging.backup_count")
file_handler = RotatingFileHandler(
log_file,
maxBytes=max_size,
backupCount=backup_count,
encoding="utf-8",
)
file_handler.setLevel(level)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
@classmethod
def get_logger(cls, name: str = "QTrade") -> "Logger":
def _get_logger(cls, name: Optional[str] = None) -> logging.Logger:
"""获取日志器"""
if not cls._initialized:
raise RuntimeError("Logger 未初始化,请先调用 Logger.initialize()")
log_name = name or cls._default_name
return cls._get_or_create_logger(log_name)
# ==================== 日志方法 ====================
@classmethod
def debug(cls, message: str, *args, name: Optional[str] = None, **kwargs):
"""记录 DEBUG 级别日志"""
cls._get_logger(name).debug(message, *args, **kwargs)
@classmethod
def info(cls, message: str, *args, name: Optional[str] = None, **kwargs):
"""记录 INFO 级别日志"""
cls._get_logger(name).info(message, *args, **kwargs)
@classmethod
def warning(cls, message: str, *args, name: Optional[str] = None, **kwargs):
"""记录 WARNING 级别日志"""
cls._get_logger(name).warning(message, *args, **kwargs)
@classmethod
def error(cls, message: str, *args, name: Optional[str] = None, **kwargs):
"""记录 ERROR 级别日志"""
cls._get_logger(name).error(message, *args, **kwargs)
@classmethod
def exception(cls, message: str, *args, name: Optional[str] = None, **kwargs):
"""记录异常日志(包含堆栈信息)"""
cls._get_logger(name).exception(message, *args, **kwargs)
@classmethod
def set_level(cls, level: str) -> None:
"""
获取指定名称的日志实例(单例模式)
设置所有日志器的级别
Args:
name: 日志名称
Returns:
Logger 实例
Examples:
>>> logger = Logger.get_logger("QTrade")
>>> logger.info("系统启动")
level: 日志级别 DEBUG, INFO, WARNING, ERROR
"""
if name not in cls._instances:
cls._instances[name] = cls(name)
return cls._instances[name]
level_value = getattr(logging, level.upper())
if level_value is None:
raise ValueError(f"无效的日志级别: {level}")
# 全局日志实例
_global_logger: Optional[Logger] = None
def get_logger(name: str = "QTrade") -> Logger:
"""
获取日志实例
Args:
name: 日志名称,用于区分不同模块
Returns:
Logger 实例
Examples:
>>> from src.core import get_logger
>>> logger = get_logger("Strategy")
>>> logger.info("策略初始化完成")
>>> logger.error("策略执行失败")
"""
return Logger.get_logger(name)
def set_log_level(level: str):
"""
动态设置日志级别
Args:
level: 日志级别 DEBUG, INFO, WARNING, ERROR
Examples:
>>> from src.core import set_log_level
>>> set_log_level("DEBUG")
"""
level_value = getattr(logging, level.upper(), logging.INFO)
# 更新所有已创建的 logger 实例
for logger_instance in Logger._instances.values():
logger_instance.logger.setLevel(level_value)
for handler in logger_instance.logger.handlers:
handler.setLevel(level_value)
# 便捷函数
def debug(message: str, *args, **kwargs):
"""记录 DEBUG 级别日志"""
get_logger().debug(message, *args, **kwargs)
def info(message: str, *args, **kwargs):
"""记录 INFO 级别日志"""
get_logger().info(message, *args, **kwargs)
def warning(message: str, *args, **kwargs):
"""记录 WARNING 级别日志"""
get_logger().warning(message, *args, **kwargs)
def error(message: str, *args, **kwargs):
"""记录 ERROR 级别日志"""
get_logger().error(message, *args, **kwargs)
def exception(message: str, *args, **kwargs):
"""记录 ERROR 级别日志,并包含异常堆栈信息"""
get_logger().exception(message, *args, **kwargs)
for logger in cls._loggers.values():
logger.setLevel(level_value)
for handler in logger.handlers:
handler.setLevel(level_value)

View File

@ -1,4 +1,4 @@
"""
"""
数据下载基类
定义数据下载的通用接口和流程
"""
@ -10,8 +10,8 @@ import pandas as pd
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
from src.core.logger import get_logger
from src.core.config import get_config
from src.core.logger import Logger
from src.core.config import Config
from src.core.models import Kline
from src.database_manager import DatabaseManager, get_table_definition
@ -60,15 +60,12 @@ class BaseDataDownloader(ABC):
periods: 数据周期列表,如 ['1m', '5m', '1d'],默认为 ['1d']
database: 目标数据库名,默认从配置读取
"""
self.logger = get_logger(self.__class__.__name__)
self.config = get_config()
# 参数验证和转换
self.symbols = self._validate_symbols(symbols)
self.start_date = self._parse_date(start_date)
self.end_date = self._parse_date(end_date)
self.periods = periods or ["1d"]
self.database = database or self.config.get("database.database")
self.database = database or Config.get("database.database")
if not self.database:
raise ValueError(
@ -81,7 +78,7 @@ class BaseDataDownloader(ABC):
# 初始化数据库连接
self._init_database()
self.logger.info(
Logger.info(
f"数据下载器初始化完成: {len(self.symbols)} 个标的, "
f"{self.start_date.date()} ~ {self.end_date.date()}, "
f"周期: {self.periods}"
@ -126,14 +123,14 @@ class BaseDataDownloader(ABC):
if period not in valid_periods:
raise ValueError(f"不支持的周期: {period},支持: {valid_periods}")
self.logger.debug("Parameter validation passed")
Logger.debug("Parameter validation passed")
def _init_database(self):
"""初始化数据库连接"""
# 创建数据库(如果不存在)
db_manager = DatabaseManager()
if not db_manager.database_exists(self.database):
self.logger.warning(f"Database {self.database} does not exist, creating...")
Logger.warning(f"Database {self.database} does not exist, creating...")
db_manager.create_database(self.database)
# 确保对应周期的 klines 表存在
@ -147,7 +144,7 @@ class BaseDataDownloader(ABC):
for period in SUPPORTED_PERIODS:
table_name = get_kline_table_name(period)
if not db_manager.table_exists(self.database, table_name):
self.logger.warning(f"Table {table_name} does not exist, creating...")
Logger.warning(f"Table {table_name} does not exist, creating...")
table_def = create_kline_table_definition(period)
db_manager.create_table(
database=self.database,
@ -162,14 +159,14 @@ class BaseDataDownloader(ABC):
self.engine = self._create_engine()
self.Session = sessionmaker(bind=self.engine)
self.logger.debug(f"Database connection initialized: {self.database}")
Logger.debug(f"Database connection initialized: {self.database}")
def _create_engine(self):
"""创建数据库引擎"""
host = self.config.get("database.host", "127.0.0.1")
port = self.config.get("database.port", 3306)
user = self.config.get("database.user", "root")
password = self.config.get("database.password", "")
host = Config.get("database.host", "127.0.0.1")
port = Config.get("database.port", 3306)
user = Config.get("database.user", "root")
password = Config.get("database.password", "")
connection_url = (
f"mysql+pymysql://{user}:{password}@"
@ -203,16 +200,16 @@ class BaseDataDownloader(ABC):
股票K线数据字典,格式: {f"{symbol}_{period}": DataFrame}
DataFrame包含列: timestamp, open, high, low, close, volume, amount
"""
self.logger.info("=" * 50)
self.logger.info("Starting data download (download only, not saving)")
self.logger.info("=" * 50)
Logger.info("=" * 50)
Logger.info("Starting data download (download only, not saving)")
Logger.info("=" * 50)
result = {}
for symbol in self.symbols:
for period in self.periods:
try:
self.logger.info(f"Downloading {symbol} [{period}] data...")
Logger.info(f"Downloading {symbol} [{period}] data...")
# 调用子类实现的下载方法
klines = self._download_klines(
@ -228,18 +225,18 @@ class BaseDataDownloader(ABC):
key = f"{symbol}_{period}"
result[key] = df
self.logger.info(
Logger.info(
f"✓ {symbol} [{period}]: downloaded {len(df)} records"
)
else:
self.logger.warning(f"✗ {symbol} [{period}]: no data")
Logger.warning(f"✗ {symbol} [{period}]: no data")
except Exception as e:
self.logger.error(f"✗ {symbol} [{period}]: download failed - {e}")
Logger.error(f"✗ {symbol} [{period}]: download failed - {e}")
self.logger.info("=" * 50)
self.logger.info(f"Download completed, retrieved {len(result)} datasets")
self.logger.info("=" * 50)
Logger.info("=" * 50)
Logger.info(f"Download completed, retrieved {len(result)} datasets")
Logger.info("=" * 50)
return result
@ -277,9 +274,9 @@ class BaseDataDownloader(ABC):
Returns:
统计信息字典
"""
self.logger.info("=" * 50)
self.logger.info("Starting data download")
self.logger.info("=" * 50)
Logger.info("=" * 50)
Logger.info("Starting data download")
Logger.info("=" * 50)
stats = {
"total_symbols": len(self.symbols),
@ -293,7 +290,7 @@ class BaseDataDownloader(ABC):
for symbol in self.symbols:
for period in self.periods:
try:
self.logger.info(f"Downloading {symbol} [{period}] data...")
Logger.info(f"Downloading {symbol} [{period}] data...")
# 调用子类实现的下载方法
klines = self._download_klines(
@ -309,7 +306,7 @@ class BaseDataDownloader(ABC):
stats["success_count"] += 1
stats["total_records"] += saved_count
self.logger.info(
Logger.info(
f"✓ {symbol} [{period}]: 下载 {len(klines)} 条, "
f"保存 {saved_count} 条"
)
@ -324,7 +321,7 @@ class BaseDataDownloader(ABC):
}
)
else:
self.logger.warning(f"✗ {symbol} [{period}]: no data")
Logger.warning(f"✗ {symbol} [{period}]: no data")
stats["failed_count"] += 1
stats["details"].append(
{
@ -337,7 +334,7 @@ class BaseDataDownloader(ABC):
)
except Exception as e:
self.logger.error(f"✗ {symbol} [{period}]: download failed - {e}")
Logger.error(f"✗ {symbol} [{period}]: download failed - {e}")
stats["failed_count"] += 1
stats["details"].append(
{
@ -348,16 +345,16 @@ class BaseDataDownloader(ABC):
}
)
self.logger.info("=" * 50)
self.logger.info("Download completed")
self.logger.info(
Logger.info("=" * 50)
Logger.info("Download completed")
Logger.info(
f"Total: {stats['total_symbols']} symbols x {stats['total_periods']} periods"
)
self.logger.info(
Logger.info(
f"Success: {stats['success_count']}, Failed: {stats['failed_count']}"
)
self.logger.info(f"Saved records: {stats['total_records']}")
self.logger.info("=" * 50)
Logger.info(f"Saved records: {stats['total_records']}")
Logger.info("=" * 50)
return stats
@ -413,11 +410,11 @@ class BaseDataDownloader(ABC):
saved_count += 1
session.commit()
self.logger.debug(f"Saved {saved_count} records to database")
Logger.debug(f"Saved {saved_count} records to database")
except Exception as e:
session.rollback()
self.logger.error(f"Failed to save data: {e}")
Logger.error(f"Failed to save data: {e}")
raise
finally:
session.close()
@ -428,4 +425,4 @@ class BaseDataDownloader(ABC):
"""关闭数据库连接"""
if hasattr(self, "engine"):
self.engine.dispose()
self.logger.info("Database connection closed")
Logger.info("Database connection closed")

View File

@ -4,16 +4,14 @@
协调数据下载、存储、增量更新
"""
from typing import List, Optional, Dict, Union
from typing import List, Optional, Dict
from datetime import datetime, timedelta
from src.data_storage.storage_layer import StorageLayer
from src.data_downloader import DownloaderFactory
from src.core.logger import get_logger
from src.core.logger import Logger
from src.core.config import Config
logger = get_logger("DownloaderManager")
class DownloaderManager:
"""
@ -35,37 +33,31 @@ class DownloaderManager:
result = manager.update_to_latest(['000001', '600000'], ['1d'])
"""
def __init__(self, config: Union[Dict, Config], storage: StorageLayer):
def __init__(self, storage: StorageLayer):
"""
初始化下载管理器
Args:
config: 配置字典或Config对象
storage: 存储层实例
"""
self.config = config
self.storage = storage
# 缓存downloader实例,保持长连接
self._downloader_instance = None
# 获取下载器类型(兼容Config对象和dict)
if isinstance(config, Config):
self.downloader_type = config.get("data_source.downloader", "xtquant")
else:
downloader_config = config.get("data_source", {})
self.downloader_type = downloader_config.get("downloader", "xtquant")
# 直接从Config单例获取下载器类型
self.downloader_type = Config.get("data_downloader.downloader")
# 验证下载器是否可用
if not DownloaderFactory.is_registered(self.downloader_type):
available = DownloaderFactory.get_available_downloaders()
logger.warning(
Logger.warning(
f"Downloader '{self.downloader_type}' not registered, "
f"available: {', '.join(available)}"
)
self.downloader_type = None
logger.info(f"DownloaderManager initialized: downloader={self.downloader_type}")
Logger.info(f"DownloaderManager initialized: downloader={self.downloader_type}")
def _get_or_create_downloader(
self,
@ -77,7 +69,7 @@ class DownloaderManager:
"""获取或创建downloader实例,复用连接"""
# 如果已经有实例,直接返回
if self._downloader_instance is not None:
logger.debug("Reusing existing downloader instance")
Logger.debug("Reusing existing downloader instance")
# 更新参数
self._downloader_instance.symbols = symbols
self._downloader_instance.start_date = start_date
@ -86,15 +78,13 @@ class DownloaderManager:
return self._downloader_instance
# 创建新实例
if self.downloader_type is None:
raise RuntimeError("No downloader configured")
downloader_class = DownloaderFactory.create(self.downloader_type)
# 获取数据库名称(兼容Config对象和dict)
if isinstance(self.config, Config):
database = self.config.get("database.database", "qtrade_backtest")
else:
database = self.config.get("database", {}).get(
"database", "qtrade_backtest"
)
# 从Config单例获取数据库名称
database = Config.get("database.database", "qtrade_backtest")
self._downloader_instance = downloader_class(
symbols=symbols,
@ -104,20 +94,20 @@ class DownloaderManager:
database=database,
)
logger.info("Created new downloader instance (will be reused)")
Logger.info("Created new downloader instance (will be reused)")
return self._downloader_instance
def close(self):
"""关闭下载器连接"""
if self._downloader_instance is not None:
try:
# 调用downloader的清理方法
if hasattr(self._downloader_instance, "__del__"):
self._downloader_instance.__del__()
# 调用downloader的close方法(如果存在)
if hasattr(self._downloader_instance, "close"):
self._downloader_instance.close()
self._downloader_instance = None
logger.info("Downloader connection closed")
Logger.info("Downloader connection closed")
except Exception as e:
logger.warning(f"Error closing downloader: {e}")
Logger.warning(f"Error closing downloader: {e}")
def download_and_save(
self,
@ -151,7 +141,7 @@ class DownloaderManager:
if periods is None:
periods = ["1d"]
logger.info(
Logger.info(
f"Download request: {len(symbols)} symbols, "
f"{start_date.date()}~{end_date.date()}, "
f"periods={periods}, force={force}"
@ -167,18 +157,18 @@ class DownloaderManager:
for symbol in symbols:
if not self.storage.exists(symbol, period, start_date, end_date):
symbols_to_download.append(symbol)
logger.debug(f"Need download: {symbol}_{period}")
Logger.debug(f"Need download: {symbol}_{period}")
else:
logger.debug(f"Data exists, skip: {symbol}_{period}")
Logger.debug(f"Data exists, skip: {symbol}_{period}")
results[f"{symbol}_{period}"] = 0
else:
symbols_to_download = symbols
if not symbols_to_download:
logger.info(f"No symbols to download for period {period}")
Logger.info(f"No symbols to download for period {period}")
continue
logger.info(
Logger.info(
f"Downloading {len(symbols_to_download)}/{len(symbols)} symbols for {period}"
)
@ -204,18 +194,18 @@ class DownloaderManager:
try:
saved_count = self.storage.save_klines(symbol, period, df)
results[key] = saved_count
logger.info(
Logger.info(
f"✓ {key}: downloaded and saved {saved_count} records"
)
except Exception as e:
logger.error(f"✗ {key}: save failed - {e}")
Logger.error(f"✗ {key}: save failed - {e}")
results[key] = 0
else:
logger.warning(f"✗ {key}: download returned no data")
Logger.warning(f"✗ {key}: download returned no data")
results[key] = 0
except Exception as e:
logger.error(f"Download failed for period {period}: {e}")
Logger.error(f"Download failed for period {period}: {e}")
for symbol in symbols_to_download:
results[f"{symbol}_{period}"] = 0
@ -228,7 +218,7 @@ class DownloaderManager:
else 0
)
logger.info(
Logger.info(
f"Download completed: {total_saved} total records saved, "
f"success rate: {success_rate:.1%}"
)
@ -255,7 +245,7 @@ class DownloaderManager:
if periods is None:
periods = ["1d"]
logger.info(f"Incremental update: {len(symbols)} symbols, periods={periods}")
Logger.info(f"Incremental update: {len(symbols)} symbols, periods={periods}")
results = {}
end_date = datetime.now()
@ -273,14 +263,14 @@ class DownloaderManager:
start_date = date_range[1] + timedelta(days=1)
if start_date >= end_date:
logger.debug(f"{key}: already up-to-date")
Logger.debug(f"{key}: already up-to-date")
results[key] = 0
continue
logger.debug(f"{key}: updating from {start_date.date()}")
Logger.debug(f"{key}: updating from {start_date.date()}")
else:
# 没有数据,无法进行增量更新
logger.error(
Logger.error(
f"{key}: no existing data found, cannot perform incremental update. "
f"Please use download_and_save() with explicit date range first."
)
@ -299,11 +289,11 @@ class DownloaderManager:
results[key] = download_result.get(key, 0)
except Exception as e:
logger.error(f"Update failed for {key}: {e}")
Logger.error(f"Update failed for {key}: {e}")
results[key] = 0
total_updated = sum(results.values())
logger.info(f"Update completed: {total_updated} records updated")
Logger.info(f"Update completed: {total_updated} records updated")
return results

View File

@ -1,10 +1,10 @@
"""
"""
数据服务 - 统一的数据访问入口
提供简洁的API,自动处理缓存、存储、下载、计算
"""
from typing import Dict, Optional, List, Union
from typing import Dict, Optional, List
from datetime import datetime
import pandas as pd
@ -12,11 +12,9 @@ from src.cache.cache_manager import CacheManager
from src.data_storage.storage_layer import StorageLayer
from src.data_downloader.downloader_manager import DownloaderManager
from src.indicator_calculator.indicator_manager import IndicatorManager
from src.core.logger import get_logger
from src.core.logger import Logger
from src.core.config import Config
from src.core.constants import IndicatorType, KlineColumns, IndicatorColumns
logger = get_logger("DataService")
from src.core.constants import IndicatorType, IndicatorColumns
class DataService:
@ -30,11 +28,14 @@ class DataService:
- 指标计算
示例:
# 确保Config已初始化
Config.initialize()
# 方式1: 从配置创建(推荐)
service = DataService.from_config(config)
service = DataService.from_config()
# 方式2: 手动注入依赖(高级用法)
service = DataService(config, storage, cache, downloader)
service = DataService(storage, cache)
# 获取K线(自动处理缓存)
klines = service.get_klines('000001', '1d', start, end)
@ -51,7 +52,6 @@ class DataService:
def __init__(
self,
config: Union[Dict, Config],
storage: StorageLayer,
cache: CacheManager,
):
@ -59,70 +59,55 @@ class DataService:
初始化数据服务
Args:
config: 配置字典或Config对象
storage: 存储层实例
cache: 缓存管理器实例
"""
self.config = config
self.storage = storage
self.cache = cache
# 初始化downloader
self.downloader = DownloaderManager(config, storage)
# 初始化downloader(直接使用Config单例)
self.downloader = DownloaderManager(storage)
# 初始化指标计算器
# 从Config单例获取指标配置
indicator_configs = {}
if isinstance(config, Config):
indicators_section = config.get("indicators", {})
enabled_indicators = indicators_section.get("enabled_indicators", [])
# 只提取各指标的参数配置
for indicator_name in enabled_indicators:
if indicator_name in indicators_section:
indicator_configs[indicator_name] = indicators_section[
indicator_name
]
elif isinstance(config, dict):
indicators_section = config.get("indicators", {})
enabled_indicators = indicators_section.get("enabled_indicators", [])
# 只提取各指标的参数配置
for indicator_name in enabled_indicators:
if indicator_name in indicators_section:
indicator_configs[indicator_name] = indicators_section[
indicator_name
]
indicators_section = Config.get("indicators", {})
enabled_indicators = indicators_section.get("enabled_indicators", [])
# 只提取各指标的参数配置
for indicator_name in enabled_indicators:
if indicator_name in indicators_section:
indicator_configs[indicator_name] = indicators_section[indicator_name]
self.indicator_manager = IndicatorManager(indicator_configs)
logger.info("DataService initialized with downloader and indicator_manager")
Logger.info("DataService initialized with downloader and indicator_manager")
@classmethod
def from_config(cls, config: Union[Dict, Config]) -> "DataService":
def from_config(cls) -> "DataService":
"""
从配置创建 DataService 实例(工厂方法)
自动初始化所有依赖组件:storage、cache、validator、downloader
Args:
config: 配置对象或配置字典
自动初始化所有依赖组件:storage、cache、downloader
所有组件都直接使用Config单例获取配置
Returns:
DataService 实例
Example:
config = Config()
config.load_with_global("configs/backtest.yaml")
service = DataService.from_config(config)
# 确保Config已初始化
Config.initialize()
service = DataService.from_config()
"""
# 导入MySQLStorage(避免循环导入)
from src.data_storage.mysql_storage import MySQLStorage
# 初始化 storage
storage = MySQLStorage(config)
# 初始化 storage(直接使用Config单例)
storage = MySQLStorage()
# 初始化 cache
cache = CacheManager(config)
# 初始化 cache(直接使用Config单例)
cache = CacheManager()
# 创建 DataService 实例
return cls(config, storage, cache)
return cls(storage, cache)
# ========== K线数据 ==========
def get_klines(
@ -154,7 +139,7 @@ class DataService:
"""
# 参数检查:必须提供时间范围
if startdate is None or enddate is None:
logger.error(
Logger.error(
f"Invalid parameters for {symbol} {period}: "
f"start={startdate}, end={enddate}. Both start and end must be provided."
)
@ -164,24 +149,24 @@ class DataService:
cache_data = self.cache.get_klines(symbol, period)
if cache_data is not None and not cache_data.empty:
logger.debug(f"Cache data found for {symbol} {period}")
Logger.debug(f"Cache data found for {symbol} {period}")
# 返回时间切片
mask = (cache_data.index >= startdate) & (cache_data.index <= enddate)
return cache_data[mask]
# ========== 步骤2: 从数据库加载 ==========
logger.debug(f"Loading from storage: {symbol} {period}")
Logger.debug(f"Loading from storage: {symbol} {period}")
db_data = self.storage.load_klines(symbol, period, startdate, enddate)
if db_data is not None and not db_data.empty:
# 数据库有数据,直接使用
self.cache.set_klines(symbol, period, {"klines": db_data})
logger.debug(f"DB data loaded and cached: {symbol} {period}")
Logger.debug(f"DB data loaded and cached: {symbol} {period}")
mask = (db_data.index >= startdate) & (db_data.index <= enddate)
return db_data[mask]
# ========== 步骤3: 触发下载 ==========
logger.info(
Logger.info(
f"Data incomplete/missing for {symbol} {period}, triggering download"
)
@ -199,7 +184,7 @@ class DataService:
if final_data is not None and not final_data.empty:
# 更新缓存
self.cache.set_klines(symbol, period, {"klines": final_data})
logger.info(
Logger.info(
f"Downloaded and loaded {len(final_data)} records for {symbol} {period}"
)
@ -209,13 +194,13 @@ class DataService:
mask = (final_data.index >= startdate) & (final_data.index <= enddate)
return final_data[mask]
else:
logger.warning(
Logger.warning(
f"Download completed but still no data for {symbol} {period}"
)
return None
except Exception as e:
logger.error(f"Failed to download data for {symbol} {period}: {e}")
Logger.error(f"Failed to download data for {symbol} {period}: {e}")
return None
def get_multiple(
@ -244,9 +229,9 @@ class DataService:
if klines is not None and not klines.empty:
result[symbol] = klines
else:
logger.warning(f"No klines for {symbol}_{period}")
Logger.warning(f"No klines for {symbol}_{period}")
logger.debug(f"Loaded {len(result)}/{len(symbols)} symbols")
Logger.debug(f"Loaded {len(result)}/{len(symbols)} symbols")
return result
def download_klines(
@ -304,7 +289,7 @@ class DataService:
"""
# 验证指标类型是否有效
if not IndicatorType.is_valid(indicator_name):
logger.error(f"Unknown indicator type: {indicator_name}")
Logger.error(f"Unknown indicator type: {indicator_name}")
return None
# 先尝试从缓存获取指标
@ -322,7 +307,7 @@ class DataService:
return indicator_data
# 缓存未命中,直接从数据库读取
logger.info(
Logger.info(
f"Loading indicator from database: {symbol}_{period}_{indicator_name}"
)
@ -343,7 +328,7 @@ class DataService:
return indicator_data
# 数据库中没有,返回None(不自动计算或下载)
logger.warning(
Logger.warning(
f"Indicator not found in database: {symbol}_{period}_{indicator_name}"
)
return None
@ -380,9 +365,9 @@ class DataService:
if indicator is not None and not indicator.empty:
result[symbol] = indicator
else:
logger.warning(f"No indicator {indicator_name} for {symbol}_{period}")
Logger.warning(f"No indicator {indicator_name} for {symbol}_{period}")
logger.debug(f"Loaded {len(result)}/{len(symbols)} indicators")
Logger.debug(f"Loaded {len(result)}/{len(symbols)} indicators")
return result
# ========== 数据管理 ==========
@ -395,7 +380,7 @@ class DataService:
symbols: 标的列表
periods: 周期列表(None则使用配置)
"""
logger.warning(
Logger.warning(
"DataService.preload() is deprecated. "
"Data will be automatically cached when accessed via get_klines()."
)
@ -409,7 +394,7 @@ class DataService:
period: 周期(None=该标的所有周期)
"""
# TODO: 实现缓存失效逻辑
logger.warning("Cache invalidation not implemented in simplified CacheManager")
Logger.warning("Cache invalidation not implemented in simplified CacheManager")
def exists(
self,
@ -463,12 +448,12 @@ class DataService:
enabled_indicators = self.indicator_manager.get_enabled_indicators()
if not enabled_indicators:
logger.debug(
Logger.debug(
f"No indicators enabled, skip calculation for {symbol}_{period}"
)
return
logger.info(
Logger.info(
f"Recalculating {len(enabled_indicators)} indicators for {symbol}_{period}"
)
@ -493,20 +478,20 @@ class DataService:
self.cache.set_indicator(
symbol, period, indicator_name, indicator_columns
)
logger.debug(
Logger.debug(
f"Saved indicator: {symbol}_{period}_{indicator_name}"
)
else:
logger.warning(
Logger.warning(
f"No columns found for indicator: {indicator_name}"
)
except Exception as e:
logger.error(f"Failed to save indicator {indicator_name}: {e}")
Logger.error(f"Failed to save indicator {indicator_name}: {e}")
continue
except Exception as e:
logger.error(f"Failed to calculate indicators: {e}")
Logger.error(f"Failed to calculate indicators: {e}")
def _get_indicator_columns(
self, df: pd.DataFrame, indicator_name: str
@ -526,14 +511,14 @@ class DataService:
expected_columns = IndicatorColumns.get_columns(indicator_name)
if not expected_columns:
logger.warning(f"Unknown indicator: {indicator_name}")
Logger.warning(f"Unknown indicator: {indicator_name}")
return pd.DataFrame()
# 只保留DataFrame中实际存在的列
existing_columns = [col for col in expected_columns if col in df.columns]
if not existing_columns:
logger.warning(
Logger.warning(
f"No columns found for indicator {indicator_name} in DataFrame. "
f"Expected: {expected_columns}, Available: {list(df.columns)}"
)
@ -573,7 +558,7 @@ class DataService:
stats = self.cache.get_stats()
checks["cache"] = stats["enabled"]
except Exception as e:
logger.error(f"Cache health check failed: {e}")
Logger.error(f"Cache health check failed: {e}")
checks["cache"] = False
# 检查存储
@ -581,7 +566,7 @@ class DataService:
# 尝试获取一个标的的时间范围
checks["storage"] = True
except Exception as e:
logger.error(f"Storage health check failed: {e}")
Logger.error(f"Storage health check failed: {e}")
checks["storage"] = False
checks["overall"] = all(checks.values())
@ -596,7 +581,7 @@ class DataService:
self.downloader.close()
# 关闭storage连接
self.storage.close()
logger.info("DataService closed")
Logger.info("DataService closed")
def __enter__(self):
return self

View File

@ -5,7 +5,7 @@ MySQL存储层实现
"""
from datetime import datetime
from typing import Optional, Dict, Union, Any
from typing import Optional, Dict, Any
import pandas as pd
from sqlalchemy import text
@ -15,10 +15,9 @@ from src.database_manager.table_utils import (
get_kline_table_name,
get_indicator_table_name,
)
from src.core.logger import get_logger
from src.core.config import Config
logger = get_logger("MySQLStorage")
from src.core.config import Config
from src.core.logger import Logger
class MySQLStorage(StorageLayer):
@ -28,28 +27,19 @@ class MySQLStorage(StorageLayer):
整合了原来的KlineReader、IndicatorReader、IndicatorWriter逻辑
"""
def __init__(
self, config: Union[Dict, Config], db_manager: Optional[DatabaseManager] = None
):
def __init__(self, db_manager: Optional[DatabaseManager] = None):
"""
初始化MySQL存储
Args:
config: 配置字典或Config对象
db_manager: 数据库管理器实例(可选)
"""
self.config = config
self.db_manager = db_manager if db_manager is not None else DatabaseManager()
# 兼容 Config 对象和字典
if isinstance(config, Config):
self.database = config.get("database.database", "qtrade_backtest")
else:
self.database = config.get("database", {}).get(
"database", "qtrade_backtest"
)
# 从Config单例获取数据库名称
self.database = Config.get("database.database", "qtrade_backtest")
logger.info(f"MySQLStorage initialized: database={self.database}")
Logger.info(f"MySQLStorage initialized: database={self.database}")
def load_klines(
self,
@ -95,7 +85,7 @@ class MySQLStorage(StorageLayer):
df = pd.read_sql(query, conn, params=params) # type: ignore
if df.empty:
logger.debug(f"No klines found: {symbol}_{period}")
Logger.debug(f"No klines found: {symbol}_{period}")
return None
# 转换时间列并设置索引
@ -105,11 +95,11 @@ class MySQLStorage(StorageLayer):
# 为兼容性保留timestamp列
df["timestamp"] = df.index
logger.debug(f"Loaded {len(df)} klines: {symbol}_{period}")
Logger.debug(f"Loaded {len(df)} klines: {symbol}_{period}")
return df
except Exception as e:
logger.error(f"Failed to load klines {symbol}_{period}: {e}")
Logger.error(f"Failed to load klines {symbol}_{period}: {e}")
return None
def load_indicators(
@ -157,7 +147,7 @@ class MySQLStorage(StorageLayer):
df = pd.read_sql(query, conn, params=params) # type: ignore
if df.empty:
logger.debug(f"No indicators found: {symbol}_{period}_{indicator_name}")
Logger.debug(f"No indicators found: {symbol}_{period}_{indicator_name}")
return None
# 转换时间列并设置索引
@ -168,13 +158,13 @@ class MySQLStorage(StorageLayer):
if "symbol" in df.columns:
df = df.drop(columns=["symbol"])
logger.debug(
Logger.debug(
f"Loaded {len(df)} indicator records: {symbol}_{period}_{indicator_name}"
)
return df
except Exception as e:
logger.error(
Logger.error(
f"Failed to load indicators {symbol}_{period}_{indicator_name}: {e}"
)
return None
@ -232,7 +222,7 @@ class MySQLStorage(StorageLayer):
)
deleted_count = result.rowcount
if deleted_count > 0:
logger.info(
Logger.info(
f"Deleted {deleted_count} old records for {symbol}_{period} in range {min_time} ~ {max_time}"
)
@ -248,17 +238,17 @@ class MySQLStorage(StorageLayer):
)
total_saved += len(batch)
if len(df_to_save) > batch_size:
logger.debug(
Logger.debug(
f"Saved batch {i // batch_size + 1}: {len(batch)} records"
)
finally:
engine.dispose()
logger.info(f"Saved {total_saved} klines: {symbol}_{period}")
Logger.info(f"Saved {total_saved} klines: {symbol}_{period}")
return total_saved
except Exception as e:
logger.error(f"Failed to save klines {symbol}_{period}: {e}")
Logger.error(f"Failed to save klines {symbol}_{period}: {e}")
return 0
def save_indicators(
@ -312,13 +302,13 @@ class MySQLStorage(StorageLayer):
finally:
engine.dispose()
logger.info(
Logger.info(
f"Saved {len(df)} indicator records: {symbol}_{period}_{indicator_name}"
)
return len(df)
except Exception as e:
logger.error(
Logger.error(
f"Failed to save indicators {symbol}_{period}_{indicator_name}: {e}"
)
return 0
@ -344,27 +334,27 @@ class MySQLStorage(StorageLayer):
if date_range is None:
# 数据库中没有任何数据
logger.debug(f"No data in DB for {symbol}_{period}")
Logger.debug(f"No data in DB for {symbol}_{period}")
return False
db_start, db_end = date_range
# 检查数据库的时间范围是否覆盖请求的时间范围
if db_start <= start_date and db_end >= end_date:
logger.debug(
Logger.debug(
f"Data exists: {symbol}_{period} DB[{db_start.date()}~{db_end.date()}] "
f"covers requested[{start_date.date()}~{end_date.date()}]"
)
return True
else:
logger.debug(
Logger.debug(
f"Data incomplete: {symbol}_{period} DB[{db_start.date()}~{db_end.date()}] "
f"does not cover requested[{start_date.date()}~{end_date.date()}]"
)
return False
except Exception as e:
logger.error(f"Failed to check existence {symbol}_{period}: {e}")
Logger.error(f"Failed to check existence {symbol}_{period}: {e}")
return False
def get_date_range(
@ -397,11 +387,11 @@ class MySQLStorage(StorageLayer):
return None
except Exception as e:
logger.error(f"Failed to get date range {symbol}_{period}: {e}")
Logger.error(f"Failed to get date range {symbol}_{period}: {e}")
return None
def close(self):
"""关闭数据库连接"""
if self.db_manager:
self.db_manager.close()
logger.debug("MySQLStorage closed")
Logger.debug("MySQLStorage closed")

View File

@ -8,9 +8,6 @@ from abc import ABC, abstractmethod
from typing import Optional
from datetime import datetime
import pandas as pd
from src.core.logger import get_logger
logger = get_logger("StorageLayer")
class StorageLayer(ABC):

View File

@ -7,10 +7,10 @@
from datetime import datetime
import pandas as pd
from src.core.logger import get_logger
from src.core.logger import LazyLogger
from .validation_result import ValidationResult
logger = get_logger("CompletenessValidator")
logger = LazyLogger("CompletenessValidator")
class CompletenessValidator:

View File

@ -8,13 +8,13 @@ from typing import Dict, List, Optional
from datetime import datetime
import pandas as pd
from src.core.logger import get_logger
from src.core.logger import LazyLogger
from .validation_result import ValidationResult
from .quality_validator import QualityValidator
from .completeness_validator import CompletenessValidator
from .indicator_validator import IndicatorValidator
logger = get_logger("DataValidator")
logger = LazyLogger("DataValidator")
class DataValidator:

View File

@ -7,10 +7,10 @@
import pandas as pd
import numpy as np
from src.core.logger import get_logger
from src.core.logger import LazyLogger
from .validation_result import ValidationResult
logger = get_logger("IndicatorValidator")
logger = LazyLogger("IndicatorValidator")
class IndicatorValidator:

View File

@ -7,10 +7,10 @@
from typing import List, Optional
import pandas as pd
from src.core.logger import get_logger
from src.core.logger import LazyLogger
from .validation_result import ValidationResult
logger = get_logger("QualityValidator")
logger = LazyLogger("QualityValidator")
class QualityValidator:

View File

@ -5,9 +5,9 @@
"""
from typing import Dict, Any
from src.core.logger import get_logger
from src.core.logger import LazyLogger
logger = get_logger("Validator")
logger = LazyLogger("Validator")
class ValidationResult:

View File

@ -24,17 +24,15 @@ from sqlalchemy.types import DECIMAL
from sqlalchemy.engine import Engine
from sqlalchemy.exc import SQLAlchemyError
from src.core.logger import get_logger
from src.core.config import get_config
logger = get_logger("DatabaseManager")
from src.core.config import Config
from src.core.logger import Logger
class DatabaseManager:
"""
数据库管理器
功能:
功能:
- 检查数据库是否存在
- 创建数据库
- 删除数据库
@ -42,7 +40,7 @@ class DatabaseManager:
- 删除表
- 检查表是否存在
架构说明:
架构说明:
- 使用连接池(pool_size=5),不需要保持长连接
- 每个进程连接一个数据库(由配置文件指定)
- 回测/模拟/实时 各自独立运行
@ -64,14 +62,12 @@ class DatabaseManager:
user: 数据库用户名
password: 数据库密码
"""
config = get_config()
self.host = host or config.get("database.host", "127.0.0.1")
self.port = port or config.get("database.port", 3306)
self.user = user or config.get("database.user", "root")
self.password = password or config.get("database.password", "")
self.pool_size = config.get("database.pool_size", 5)
self.pool_recycle = config.get("database.pool_recycle", 3600)
self.host = host or Config.get("database.host", "127.0.0.1")
self.port = port or Config.get("database.port", 3306)
self.user = user or Config.get("database.user", "root")
self.password = password or Config.get("database.password", "")
self.pool_size = Config.get("database.pool_size", 5)
self.pool_recycle = Config.get("database.pool_recycle", 3600)
# 创建不指定数据库的连接(用于管理数据库)
self._admin_engine = self._create_admin_engine()
@ -79,7 +75,7 @@ class DatabaseManager:
# 缓存各个数据库的engine,避免重复创建
self._db_engines: Dict[str, Engine] = {}
logger.info(
Logger.info(
f"Database manager initialized: {self.user}@{self.host}:{self.port}"
)
@ -111,7 +107,7 @@ class DatabaseManager:
pool_recycle=self.pool_recycle,
pool_pre_ping=True,
)
logger.debug(f"Created engine for database: {database}")
Logger.debug(f"Created engine for database: {database}")
return self._db_engines[database]
def _create_db_engine(self, database: str) -> Engine:
@ -135,12 +131,12 @@ class DatabaseManager:
with self._admin_engine.connect() as conn:
result = conn.execute(text(f"SHOW DATABASES LIKE '{database}'"))
exists = result.fetchone() is not None
logger.debug(
Logger.debug(
f"Check database {database}: {'exists' if exists else 'not exists'}"
)
return exists
except SQLAlchemyError as e:
logger.error(f"Failed to check database: {e}")
Logger.error(f"Failed to check database: {e}")
return False
def create_database(self, database: str, if_not_exists: bool = True) -> bool:
@ -156,7 +152,7 @@ class DatabaseManager:
"""
try:
if if_not_exists and self.database_exists(database):
logger.info(f"Database {database} already exists, skip creation")
Logger.info(f"Database {database} already exists, skip creation")
return True
with self._admin_engine.connect() as conn:
@ -167,10 +163,10 @@ class DatabaseManager:
)
)
conn.commit()
logger.info(f"✓ Created database: {database}")
Logger.info(f"✓ Created database: {database}")
return True
except SQLAlchemyError as e:
logger.error(f"Failed to create database: {e}")
Logger.error(f"Failed to create database: {e}")
return False
def drop_database(self, database: str, confirm: bool = False) -> bool:
@ -185,21 +181,21 @@ class DatabaseManager:
是否成功
"""
if not confirm:
logger.warning("Database deletion requires confirmation: confirm=True")
Logger.warning("Database deletion requires confirmation: confirm=True")
return False
try:
if not self.database_exists(database):
logger.warning(f"Database {database} does not exist")
Logger.warning(f"Database {database} does not exist")
return False
with self._admin_engine.connect() as conn:
conn.execute(text(f"DROP DATABASE `{database}`"))
conn.commit()
logger.info(f"✓ Dropped database: {database}")
Logger.info(f"✓ Dropped database: {database}")
return True
except SQLAlchemyError as e:
logger.error(f"Failed to drop database: {e}")
Logger.error(f"Failed to drop database: {e}")
return False
def list_databases(self) -> List[str]:
@ -222,7 +218,7 @@ class DatabaseManager:
]
return databases
except SQLAlchemyError as e:
logger.error(f"Failed to list databases: {e}")
Logger.error(f"Failed to list databases: {e}")
return []
def table_exists(self, database: str, table: str) -> bool:
@ -240,12 +236,12 @@ class DatabaseManager:
engine = self._create_db_engine(database)
inspector = inspect(engine)
exists = table in inspector.get_table_names()
logger.debug(
Logger.debug(
f"Check table {database}.{table}: {'exists' if exists else 'not exists'}"
)
return exists
except SQLAlchemyError as e:
logger.error(f"Failed to check table: {e}")
Logger.error(f"Failed to check table: {e}")
return False
def list_tables(self, database: str) -> List[str]:
@ -263,7 +259,7 @@ class DatabaseManager:
inspector = inspect(engine)
return inspector.get_table_names()
except SQLAlchemyError as e:
logger.error(f"Failed to list tables: {e}")
Logger.error(f"Failed to list tables: {e}")
return []
def create_table(
@ -280,7 +276,7 @@ class DatabaseManager:
Args:
database: 数据库名
table_name: 表名
columns: 列定义,格式:
columns: 列定义,格式:
{
'column_name': {
'type': 'String'/'Integer'/'Float'/'DateTime'/'Boolean'/'Text'/'JSON',
@ -303,7 +299,7 @@ class DatabaseManager:
"""
try:
if if_not_exists and self.table_exists(database, table_name):
logger.info(
Logger.info(
f"Table {database}.{table_name} already exists, skip creation"
)
return True
@ -316,7 +312,7 @@ class DatabaseManager:
for col_name, col_def in columns.items():
col_type_str = col_def.get("type", "String")
# 映射类型(String 直接返回实例,其他返回类)
# 映射类型(String 直接返回实例,其他返回类<EFBFBD>?
if col_type_str == "String":
col_type = String(col_def.get("length", 50))
elif col_type_str == "Integer":
@ -324,7 +320,7 @@ class DatabaseManager:
elif col_type_str == "Float":
col_type = Float()
elif col_type_str == "Decimal":
# DECIMAL类型,用于精确存储价格等数值
# DECIMAL类型,用于精确存储价格等数<EFBFBD>?
# precision: 总位数,scale: 小数位数
precision = col_def.get("precision", 10)
scale = col_def.get("scale", 3)
@ -350,7 +346,7 @@ class DatabaseManager:
)
table_columns.append(column)
# 创建表对象
# 创建表对<EFBFBD>?
table = Table(table_name, metadata, *table_columns)
# 添加索引
@ -368,11 +364,11 @@ class DatabaseManager:
# 创建表
metadata.create_all(engine)
logger.info(f"✓ Created table: {database}.{table_name}")
Logger.info(f"✓ Created table: {database}.{table_name}")
return True
except SQLAlchemyError as e:
logger.error(f"Failed to create table: {e}")
Logger.error(f"Failed to create table: {e}")
return False
def drop_table(self, database: str, table: str, confirm: bool = False) -> bool:
@ -388,22 +384,22 @@ class DatabaseManager:
是否成功
"""
if not confirm:
logger.warning("Table deletion requires confirmation: confirm=True")
Logger.warning("Table deletion requires confirmation: confirm=True")
return False
try:
if not self.table_exists(database, table):
logger.warning(f"Table {database}.{table} does not exist")
Logger.warning(f"Table {database}.{table} does not exist")
return False
engine = self._create_db_engine(database)
with engine.connect() as conn:
conn.execute(text(f"DROP TABLE `{table}`"))
conn.commit()
logger.info(f"✓ Dropped table: {database}.{table}")
Logger.info(f"✓ Dropped table: {database}.{table}")
return True
except SQLAlchemyError as e:
logger.error(f"Failed to drop table: {e}")
Logger.error(f"Failed to drop table: {e}")
return False
def get_table_schema(self, database: str, table: str) -> Dict[str, Any]:
@ -427,7 +423,7 @@ class DatabaseManager:
return {"columns": columns, "indexes": indexes, "primary_key": pk}
except SQLAlchemyError as e:
logger.error(f"Failed to get table schema: {e}")
Logger.error(f"Failed to get table schema: {e}")
return {}
def close(self):
@ -436,15 +432,15 @@ class DatabaseManager:
# 关闭管理员engine
if hasattr(self, "_admin_engine"):
self._admin_engine.dispose()
logger.debug("Admin engine disposed")
Logger.debug("Admin engine disposed")
# 关闭所有数据库engine
if hasattr(self, "_db_engines"):
for db_name, engine in self._db_engines.items():
engine.dispose()
logger.debug(f"Engine disposed for database: {db_name}")
Logger.debug(f"Engine disposed for database: {db_name}")
self._db_engines.clear()
logger.info("Database manager connections closed")
Logger.info("Database manager connections closed")
except Exception as e:
logger.warning(f"Error closing database connections: {e}")
Logger.warning(f"Error closing database connections: {e}")

View File

@ -1,4 +1,4 @@
"""
"""
WebSocket客户端 (WebSocket Client)
纯粹的WebSocket通信层,只负责:
@ -12,9 +12,7 @@ import asyncio
import websockets
import json
from src.core.logger import get_logger
logger = get_logger("WSClient")
from src.core.logger import Logger
class WSClient:
@ -41,20 +39,20 @@ class WSClient:
self.loop = None
self.connected = False
self.connection_attempted = False
logger.info(f"WSClient initialized: {self.server_url}")
Logger.info(f"WSClient initialized: {self.server_url}")
async def connect(self):
"""建立WebSocket连接"""
try:
logger.info(f"Attempting to connect to {self.server_url}...")
Logger.info(f"Attempting to connect to {self.server_url}...")
self.websocket = await websockets.connect(
self.server_url, ping_interval=20, ping_timeout=10
)
self.connected = True
logger.info("WebSocket connected successfully")
Logger.info("WebSocket connected successfully")
except Exception as e:
self.connected = False
logger.error(f"Failed to connect WebSocket: {e}")
Logger.error(f"Failed to connect WebSocket: {e}")
raise
async def disconnect(self):
@ -62,7 +60,7 @@ class WSClient:
if self.websocket:
await self.websocket.close()
self.connected = False
logger.info("WebSocket disconnected")
Logger.info("WebSocket disconnected")
async def send_async(self, message: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
@ -75,7 +73,7 @@ class WSClient:
服务器响应(字典格式)或None
"""
if not self.websocket:
logger.error("WebSocket not connected")
Logger.error("WebSocket not connected")
return None
try:
@ -91,13 +89,13 @@ class WSClient:
return json.loads(response)
except asyncio.TimeoutError:
logger.error(f"Request timeout after {self.timeout}s")
Logger.error(f"Request timeout after {self.timeout}s")
return None
except Exception as e:
# 忽略正常的WebSocket关闭(错误码1000)
error_msg = str(e)
if "1000" not in error_msg or "OK" not in error_msg:
logger.error(f"WebSocket error: {e}")
Logger.error(f"WebSocket error: {e}")
return None
def send(self, message: Dict[str, Any]) -> Optional[Dict[str, Any]]:
@ -125,7 +123,7 @@ class WSClient:
try:
self.loop.run_until_complete(self.connect())
except Exception as e:
logger.error(f"Connection failed, will not retry: {e}")
Logger.error(f"Connection failed, will not retry: {e}")
self.connected = False
return None
@ -141,4 +139,4 @@ class WSClient:
self.loop.close()
self.loop = None
except Exception as e:
logger.error(f"Error closing connection: {e}")
Logger.error(f"Error closing connection: {e}")

View File

@ -1,4 +1,4 @@
"""
"""
WebSocket通信服务器 - 纯通信层
提供基础的WebSocket通信功能,业务逻辑由调用方实现
@ -11,9 +11,8 @@ import uvicorn
import json
from datetime import datetime
from src.core.logger import get_logger
from src.core.logger import Logger
logger = get_logger("WSServer")
# 消息处理器类型定义
# Handler 返回业务数据字典或 None,由 WebSocketServer 包装成完整响应
@ -49,7 +48,7 @@ class WebSocketServer:
返回业务数据,由服务器自动包装成完整响应
"""
self.message_handlers[msg_type] = handler
logger.info(f"Registered handler for message type: {msg_type}")
Logger.info(f"Registered handler for message type: {msg_type}")
async def _handle_websocket(self, websocket: WebSocket):
"""
@ -59,7 +58,7 @@ class WebSocketServer:
websocket: WebSocket连接
"""
await websocket.accept()
logger.info(f"Client connected: {websocket.client}")
Logger.info(f"Client connected: {websocket.client}")
try:
while True:
@ -71,7 +70,7 @@ class WebSocketServer:
header = message.get("header", {})
req_msg_id = header.get("msg_id")
logger.debug(f"Received message type: {msg_type}")
Logger.debug(f"Received message type: {msg_type}")
# 查找并调用处理器
handler = self.message_handlers.get(msg_type)
@ -82,7 +81,7 @@ class WebSocketServer:
# 包装成完整响应
response = self._wrap_response(business_data, req_msg_id)
except Exception as e:
logger.error(f"Handler error: {e}", exc_info=True)
Logger.error(f"Handler error: {e}", exc_info=True)
response = self._create_error_response(
str(e), "PROCESSING_ERROR", req_msg_id
)
@ -97,9 +96,9 @@ class WebSocketServer:
await websocket.send_text(json.dumps(response))
except WebSocketDisconnect:
logger.info(f"Client disconnected: {websocket.client}")
Logger.info(f"Client disconnected: {websocket.client}")
except Exception as e:
logger.error(f"WebSocket error: {e}", exc_info=True)
Logger.error(f"WebSocket error: {e}", exc_info=True)
try:
error_response = self._create_error_response(str(e), "INTERNAL_ERROR")
await websocket.send_text(json.dumps(error_response))
@ -153,5 +152,5 @@ class WebSocketServer:
host: 监听地址
port: 监听端口
"""
logger.info(f"Starting WebSocket server on {host}:{port}")
Logger.info(f"Starting WebSocket server on {host}:{port}")
uvicorn.run(self.app, host=host, port=port, log_level="info")

View File

@ -4,91 +4,86 @@ QTrade Strategy Server - 使用WebSocketServer通信层
接收客户端发送的K线数据,通过StrategyManager分发到多个策略实例
"""
from typing import Optional
import signal
import sys
from src.core.logger import get_logger
# ==================== 导入依赖 ====================
from src.core.config import Config
from src.core.logger import Logger
from src.strategy_manager import StrategyManager
from src.networks.server.ws_server import WebSocketServer
from src.cache.cache_manager import CacheManager
from src.database_manager.db_manager import DatabaseManager
from src.data_storage.mysql_storage import MySQLStorage
logger = get_logger("QTradeServer")
# 全局对象
strategy_manager: Optional[StrategyManager] = None
cache_manager: Optional[CacheManager] = None
db_manager: Optional[DatabaseManager] = None
# ==================== 全局对象 ====================
stratge_config_dir: str = "config/strategies"
strategy_manager = None
cache_manager = None
db_manager = None
def initialize_server(
config_file: str = "configs/backtest.yaml",
config_dir: str = "config/strategies",
) -> bool:
def initialize_server(cfg_file: str, strategy_cfg_dir: str) -> bool:
"""
初始化服务器
Args:
config_file: 配置文件路径
config_dir: 策略配置文件目录
cfg_file: 配置文件路径
strategy_cfg_dir: 策略配置文件目录
"""
global strategy_manager, cache_manager, db_manager
stratge_config_dir = strategy_cfg_dir
logger.info("Initializing QTrade Server...")
# 1. 加载配置文件(合并全局配置)
# 1. 第一步:初始化配置(全局单例)
print(f"Loading configuration from {cfg_file}...")
try:
config = Config()
config.load_with_global(config_file)
logger.info(f"Configuration loaded from {config_file} with global.yaml")
Config.initialize(cfg_file)
print("✓ Configuration loaded successfully")
except Exception as e:
logger.error(f"Failed to load configuration: {e}")
print(f"✗ Failed to load configuration: {e}")
import traceback
traceback.print_exc()
return False
# 2. 初始化数据库管理器
# 2. 初始化 logger(Config已初始化,Logger会自动使用Config类方法)
Logger.initialize(default_name="QTradeServer")
Logger.info("Initializing QTrade Server...")
Logger.info(f"Configuration loaded from {cfg_file}")
# 3. 初始化数据库管理器
try:
db_manager = DatabaseManager()
logger.info("DatabaseManager initialized")
Logger.info("DatabaseManager initialized")
except Exception as e:
logger.warning(f"Failed to initialize DatabaseManager: {e}")
Logger.warning(f"Failed to initialize DatabaseManager: {e}")
db_manager = None
return False
# 3. 初始化缓存管理器(传入db_manager用于数据库降级)
cache_config = config.get("cache")
if cache_config is None:
# 使用默认缓存配置
logger.warning("Cache configuration not found, using default configuration")
cache_config = {
"type": "memory",
"capacity": 1000,
"ttl": 3600,
}
cache_manager = CacheManager(cache_config, db_manager=db_manager)
# 4. 初始化缓存管理器(传入db_manager用于数据库降级)
cache_manager = CacheManager(db_manager=db_manager)
if cache_manager is None:
logger.error("Failed to create CacheManager")
Logger.error("Failed to create CacheManager")
return False
else:
logger.info("CacheManager initialized")
Logger.info("CacheManager initialized")
# 4. 初始化策略管理器(传入共享资源)
strategy_manager = StrategyManager(
config_dir=config_dir, cache_manager=cache_manager
config_dir=stratge_config_dir, cache_manager=cache_manager
)
if strategy_manager is None:
logger.error("Failed to create StrategyManager")
Logger.error("Failed to create StrategyManager")
return False
# 4. 加载并初始化所有策略
if not strategy_manager.initialize():
logger.error("Failed to initialize StrategyManager")
Logger.error("Failed to initialize StrategyManager")
return False
logger.info("QTrade Server initialized successfully")
Logger.info("QTrade Server initialized successfully")
return True
@ -104,14 +99,13 @@ def save_cache_to_database(cache_manager: CacheManager, db_manager: DatabaseMana
# 获取缓存统计信息
stats = cache_manager.get_stats()
if stats["size"] == 0:
logger.info("No cache data to save")
Logger.info("No cache data to save")
return
logger.info(f"Saving {stats['size']} cache entries to database...")
Logger.info(f"Saving {stats['size']} cache entries to database...")
# 创建存储层(传入config和db_manager)
config = Config("configs/backtest.yaml")
storage = MySQLStorage(config._data, db_manager)
# 使用Config单例
storage = MySQLStorage(db_manager)
saved_count = 0
failed_count = 0
@ -128,25 +122,25 @@ def save_cache_to_database(cache_manager: CacheManager, db_manager: DatabaseMana
count = storage.save_klines(symbol, period, klines_data)
if count > 0:
saved_count += 1
logger.info(
Logger.info(
f"✓ Saved cache: {symbol}_{period} ({count} rows)"
)
else:
failed_count += 1
logger.warning(f"✗ Failed to save: {symbol}_{period}")
Logger.warning(f"✗ Failed to save: {symbol}_{period}")
else:
logger.debug(f"Skip empty cache: {symbol}_{period}")
Logger.debug(f"Skip empty cache: {symbol}_{period}")
except Exception as e:
failed_count += 1
logger.error(f"Error saving {symbol}_{period}: {e}", exc_info=True)
Logger.error(f"Error saving {symbol}_{period}: {e}")
logger.info(
Logger.info(
f"Cache save completed: {saved_count} succeeded, {failed_count} failed"
)
except Exception as e:
logger.error(f"Failed to save cache to database: {e}", exc_info=True)
Logger.error(f"Failed to save cache to database: {e}")
async def handle_kline_data(message: dict) -> dict:
@ -172,7 +166,7 @@ async def handle_kline_data(message: dict) -> dict:
if not symbol:
raise ValueError("Symbol is required")
logger.info(f"Processing K-line: {symbol} {kline_time}")
Logger.info(f"Processing K-line: {symbol} {kline_time}")
# 构建完整的K线数据
kline_data = {
@ -214,7 +208,7 @@ async def handle_kline_batch(message: dict) -> dict:
batch_data = message.get("batch_data", [])
all_signals = []
logger.info(f"Processing batch: {len(batch_data)} symbols")
Logger.info(f"Processing batch: {len(batch_data)} symbols")
# 处理每个标的的K线
for item in batch_data:
@ -244,50 +238,92 @@ async def handle_kline_batch(message: dict) -> dict:
}
def start_server(
host: str = "0.0.0.0",
port: int = 8000,
config_file: str = "configs/backtest.yaml",
config_dir: str = "config/strategies",
):
def start_server():
"""
启动服务器
Args:
host: 监听地址
port: 监听端口
config_file: 配置文件路径
config_dir: 策略配置文件目录
所有配置从 Config 类获取
"""
logger.info("=" * 60)
logger.info("QTrade Strategy Server Starting")
logger.info("=" * 60)
logger.info(f"Host: {host}")
logger.info(f"Port: {port}")
logger.info(f"WebSocket URL: ws://{host}:{port}/ws/strategy")
logger.info(f"Config File: {config_file}")
logger.info(f"Config Dir: {config_dir}")
logger.info("=" * 60)
# 1. 首先初始化配置
print("=" * 60)
print("QTrade Strategy Server Starting")
print("=" * 60)
# 初始化服务器
if not initialize_server(config_file, config_dir):
logger.error("Failed to initialize, server will not start")
# 初始化配置(使用 Config 类中定义的默认路径)
try:
Config.initialize()
except Exception as e:
print(f"✗ Failed to load configuration: {e}")
import traceback
traceback.print_exc()
return
# 从配置获取服务器参数
host = Config.get("services.trading_service.host")
port = Config.get("services.trading_service.port")
config_dir = Config.get("strategies.strategy_folder") # 策略配置目录
print(f"Host: {host}")
print(f"Port: {port}")
print(f"WebSocket URL: ws://{host}:{port}/ws/strategy")
print(f"Environment: {Config.get_env_mode()}")
print("=" * 60)
# 初始化服务器其他组件
global strategy_manager, cache_manager, db_manager
# 初始化 logger
Logger.initialize(default_name="QTradeServer")
Logger.info("Initializing QTrade Server...")
# 初始化数据库管理器
try:
db_manager = DatabaseManager()
Logger.info("DatabaseManager initialized")
except Exception as e:
Logger.error(f"Failed to initialize DatabaseManager: {e}")
db_manager = None
return
# 初始化缓存管理器
cache_manager = CacheManager(db_manager=db_manager)
if cache_manager is None:
Logger.error("Failed to create CacheManager")
return
Logger.info("CacheManager initialized")
# 初始化策略管理器
strategy_manager = StrategyManager(
config_dir=config_dir, cache_manager=cache_manager
)
if strategy_manager is None:
Logger.error("Failed to create StrategyManager")
return
if not strategy_manager.initialize():
Logger.error("Failed to initialize StrategyManager")
return
Logger.info("QTrade Server initialized successfully")
Logger.info("=" * 60)
Logger.info("Server initialization completed")
Logger.info("=" * 60)
# 注册关闭钩子
def on_shutdown(signum=None, frame=None):
logger.info("Server shutting down...")
Logger.info("Server shutting down...")
# 保存缓存到数据库
if cache_manager and db_manager:
try:
logger.info("Saving cache to database...")
Logger.info("Saving cache to database...")
save_cache_to_database(cache_manager, db_manager)
logger.info("Cache saved successfully")
Logger.info("Cache saved successfully")
except Exception as e:
logger.error(f"Failed to save cache: {e}", exc_info=True)
Logger.error(f"Failed to save cache: {e}")
logger.info("Shutdown completed")
Logger.info("Shutdown completed")
sys.exit(0)
signal.signal(signal.SIGTERM, on_shutdown)

View File

@ -14,10 +14,8 @@ from pathlib import Path
import yaml
import importlib
from src.core.logger import get_logger
from src.core.strategy_context import StrategyContext
logger = get_logger("StrategyManager")
from src.core.logger import Logger
class StrategyManager:
@ -34,14 +32,14 @@ class StrategyManager:
self,
config_dir: str,
cache_manager,
):
):
"""
初始化策略管理器
Args:
config_dir: 策略配置文件目录
cache_manager: 缓存管理器(共享实例)
"""
"""
self.config_dir = Path(config_dir)
# 直接持有共享资源
@ -55,7 +53,7 @@ class StrategyManager:
# 配置缓存: {instance_id: config_dict}
self.configs: Dict[str, Dict] = {}
logger.info(f"StrategyManager initialized with config_dir: {config_dir}")
Logger.info(f"StrategyManager initialized with config_dir: {config_dir}")
def load_configs(self) -> bool:
"""
@ -66,17 +64,17 @@ class StrategyManager:
"""
try:
if not self.config_dir.exists():
logger.error(f"Config directory not found: {self.config_dir}")
Logger.error(f"Config directory not found: {self.config_dir}")
return False
# 查找所有yaml文件
config_files = list(self.config_dir.glob("*.yaml"))
if not config_files:
logger.warning(f"No config files found in {self.config_dir}")
Logger.warning(f"No config files found in {self.config_dir}")
return False
logger.info(f"Found {len(config_files)} config files")
Logger.info(f"Found {len(config_files)} config files")
# 加载每个配置文件
for config_file in config_files:
@ -86,21 +84,21 @@ class StrategyManager:
instance_id = config.get("instance_id")
if not instance_id:
logger.error(f"Missing instance_id in {config_file}")
Logger.error(f"Missing instance_id in {config_file}")
continue
self.configs[instance_id] = config
logger.info(f"Loaded config: {instance_id} from {config_file.name}")
Logger.info(f"Loaded config: {instance_id} from {config_file.name}")
except Exception as e:
logger.error(f"Failed to load {config_file}: {e}")
Logger.error(f"Failed to load {config_file}: {e}")
continue
logger.info(f"Successfully loaded {len(self.configs)} strategy configs")
Logger.info(f"Successfully loaded {len(self.configs)} strategy configs")
return len(self.configs) > 0
except Exception as e:
logger.error(f"Failed to load configs: {e}", exc_info=True)
Logger.error(f"Failed to load configs: {e}", exc_info=True)
return False
def initialize(self) -> bool:
@ -111,11 +109,11 @@ class StrategyManager:
是否初始化成功
"""
try:
logger.info("Initializing strategy instances...")
Logger.info("Initializing strategy instances...")
# 先加载配置
if not self.load_configs():
logger.error("Failed to load configs")
Logger.error("Failed to load strategy configs")
return False
# 创建每个策略实例
@ -127,13 +125,13 @@ class StrategyManager:
params = config.get("params", {})
if not symbol or not strategy_class_name:
logger.error(f"Invalid config for {instance_id}")
Logger.error(f"Invalid config for {instance_id}")
continue
# 动态加载策略类
strategy_class = self._load_strategy_class(strategy_class_name)
if not strategy_class:
logger.error(
Logger.error(
f"Failed to load strategy class: {strategy_class_name}"
)
continue
@ -161,29 +159,29 @@ class StrategyManager:
self.symbol_index[symbol] = []
self.symbol_index[symbol].append((instance_id, strategy_obj))
logger.info(
Logger.info(
f"✓ Created instance: {instance_id} ({strategy_class_name}) for {symbol}"
)
except Exception as e:
logger.error(
Logger.error(
f"Failed to create instance {instance_id}: {e}", exc_info=True
)
continue
# 打印统计信息
logger.info("=" * 60)
logger.info("Strategy initialization completed:")
logger.info(f" Total instances: {len(self.instances)}")
logger.info(f" Symbols covered: {len(self.symbol_index)}")
Logger.info("=" * 60)
Logger.info("Strategy initialization completed:")
Logger.info(f" Total instances: {len(self.instances)}")
Logger.info(f" Symbols covered: {len(self.symbol_index)}")
for symbol, instances_list in self.symbol_index.items():
logger.info(f" {symbol}: {len(instances_list)} instance(s)")
logger.info("=" * 60)
Logger.info(f" {symbol}: {len(instances_list)} instance(s)")
Logger.info("=" * 60)
return len(self.instances) > 0
except Exception as e:
logger.error(f"Failed to initialize: {e}", exc_info=True)
Logger.error(f"Failed to initialize: {e}", exc_info=True)
return False
def _load_strategy_class(self, class_name: str):
@ -210,7 +208,7 @@ class StrategyManager:
return strategy_class
except Exception as e:
logger.error(f"Failed to load strategy class {class_name}: {e}")
Logger.error(f"Failed to load strategy class {class_name}: {e}")
return None
def _class_to_module_name(self, class_name: str) -> str:
@ -243,10 +241,10 @@ class StrategyManager:
instances_list = self.symbol_index.get(symbol, [])
if not instances_list:
logger.debug(f"No strategy instances for {symbol}")
Logger.debug(f"No strategy instances for {symbol}")
return []
logger.debug(
Logger.debug(
f"Dispatching K-line to {len(instances_list)} instances for {symbol}"
)
@ -277,10 +275,10 @@ class StrategyManager:
}
all_signals.append(signal)
logger.info(f"Signal from {instance_id}: {action} {symbol}")
Logger.info(f"Signal from {instance_id}: {action} {symbol}")
except Exception as e:
logger.error(f"Error in instance {instance_id}: {e}", exc_info=True)
Logger.error(f"Error in instance {instance_id}: {e}", exc_info=True)
continue
return all_signals

View File

@ -8,9 +8,9 @@ from typing import Dict, List, Optional, Any
import yaml
from pathlib import Path
from src.core.logger import get_logger
from src.core.logger import LazyLogger
logger = get_logger("ConfigLoader")
logger = LazyLogger("ConfigLoader")
class ConfigLoader:

View File

@ -8,9 +8,9 @@ from typing import Dict, Optional
from dataclasses import dataclass
from src.strategy_service.config_loader import ConfigLoader
from src.core.logger import get_logger
from src.core.logger import LazyLogger
logger = get_logger("PositionManager")
logger = LazyLogger("PositionManager")
@dataclass

View File

@ -9,9 +9,9 @@ from dataclasses import dataclass
from src.strategy_service.config_loader import ConfigLoader
from src.strategy_service.position_manager import PositionManager
from src.core.logger import get_logger
from src.core.logger import LazyLogger
logger = get_logger("RiskManager")
logger = LazyLogger("RiskManager")
@dataclass

View File

@ -11,9 +11,9 @@ from src.strategy_service.strategy_manager import StrategyManager
from src.strategy_service.position_manager import PositionManager
from src.strategy_service.risk_manager import RiskManager, TradeSignal
from src.strategy_service.trade_recorder import TradeRecorder
from src.core.logger import get_logger
from src.core.logger import LazyLogger
logger = get_logger("StrategyExecutor")
logger = LazyLogger("StrategyExecutor")
class StrategyExecutor:
@ -79,10 +79,7 @@ class StrategyExecutor:
self.position_manager.update_price(instance_id, current_price)
# 构建完整的K线数据(包含symbol)
full_kline_data = {
"symbol": symbol,
**kline_data
}
full_kline_data = {"symbol": symbol, **kline_data}
# 调用策略计算
# 假设策略有compute方法返回action, price, quantity

View File

@ -8,9 +8,9 @@ from typing import Dict, List, Tuple, Optional, Type, Any
import importlib
from src.strategy_service.config_loader import ConfigLoader
from src.core.logger import get_logger
from src.core.logger import LazyLogger
logger = get_logger("StrategyManager")
logger = LazyLogger("StrategyManager")
class StrategyManager:

View File

@ -9,9 +9,9 @@ from datetime import datetime
from dataclasses import dataclass, asdict
import json
from src.core.logger import get_logger
from src.core.logger import LazyLogger
logger = get_logger("TradeRecorder")
logger = LazyLogger("TradeRecorder")
@dataclass