Compare commits
3 Commits
b44f761c2b
...
593565bb36
| Author | SHA1 | Date | |
|---|---|---|---|
| 593565bb36 | |||
| 37a5df8bf6 | |||
| 0f23037448 |
@ -31,7 +31,10 @@ def start_server():
|
||||
print("=" * 60)
|
||||
print("正在启动 QTrade Server...")
|
||||
print("=" * 60)
|
||||
subprocess.run([sys.executable, "-m", "src.qtrade_server"], cwd=workspace)
|
||||
try:
|
||||
subprocess.run([sys.executable, "-m", "src.qtrade_server"], cwd=workspace)
|
||||
except KeyboardInterrupt:
|
||||
print("\n✓ 服务器已正常关闭")
|
||||
|
||||
|
||||
def start_client_newwindow():
|
||||
@ -52,7 +55,10 @@ def start_client():
|
||||
print("\n" + "=" * 60)
|
||||
print("正在启动 Backtest Client...")
|
||||
print("=" * 60)
|
||||
subprocess.run([sys.executable, "-m", "src.backtest.main"], cwd=workspace)
|
||||
try:
|
||||
subprocess.run([sys.executable, "-m", "src.backtest.main"], cwd=workspace)
|
||||
except KeyboardInterrupt:
|
||||
print("\n✓ 客户端已正常关闭")
|
||||
|
||||
|
||||
def main():
|
||||
@ -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"
|
||||
@ -1,17 +0,0 @@
|
||||
# 策略实例配置: debug_000001
|
||||
# 平安银行 - 每条K线都打印,不生成信号
|
||||
|
||||
instance_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 # 最大仓位80%
|
||||
stop_loss: 0.05 # 止损5%
|
||||
@ -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
|
||||
@ -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
|
||||
@ -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:
|
||||
level: "DEBUG"
|
||||
file:
|
||||
path: "logs/backtest"
|
||||
enabled: true
|
||||
prompt_level: ["ERROR", "WARNING", "INFO"]
|
||||
filepath: "d:\\workspace\\QTrade\\logs"
|
||||
max_size: 10485760 # 10MB
|
||||
backup_count: 5
|
||||
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
|
||||
@ -1,134 +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
|
||||
|
||||
# 日志配置(公用)
|
||||
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: "production" # 可选值: backtest, simulation, production
|
||||
@ -1,38 +1,116 @@
|
||||
# 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:
|
||||
level: "INFO"
|
||||
file:
|
||||
path: "logs/production"
|
||||
backup_count: 10 # 实盘保留更多日志
|
||||
enabled: true
|
||||
prompt_level: ["ERROR", "WARNING", "INFO"]
|
||||
filepath: "d:\\workspace\\QTrade\\logs"
|
||||
max_size: 10485760 # 10MB
|
||||
backup_count: 5
|
||||
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
|
||||
|
||||
# ==================== MiniQMT 实盘交易配置 ====================
|
||||
miniqmt:
|
||||
userdata_path: "D:\\国金QMT交易端模拟\\userdata_mini" # MiniQMT userdata_mini 路径
|
||||
session_id: 123456 # 会话ID(不同策略使用不同ID)
|
||||
account:
|
||||
account_id: "40004091" # 交易账号
|
||||
account_type: "STOCK" # 账户类型(STOCK/HUGANGTONG/SHENGANGTONG)
|
||||
|
||||
# ==================== 下载数据源配置 ====================
|
||||
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"
|
||||
|
||||
@ -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:
|
||||
level: "DEBUG"
|
||||
file:
|
||||
path: "logs/simulation"
|
||||
enabled: true
|
||||
prompt_level: ["ERROR", "WARNING", "INFO"]
|
||||
filepath: "d:\\workspace\\QTrade\\logs"
|
||||
max_size: 10485760 # 10MB
|
||||
backup_count: 5
|
||||
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"
|
||||
|
||||
35
configs/strategies/debug_000001.yaml
Normal file
35
configs/strategies/debug_000001.yaml
Normal file
@ -0,0 +1,35 @@
|
||||
# 策略实例配置: debug_000001
|
||||
# 平安银行 - 每条K线都打印,不生成信号
|
||||
|
||||
instance_id: "debug_000001"
|
||||
symbol: "000001.SZ" # 股票代码
|
||||
symbol_name: "平安银行" # 股票名称
|
||||
symbol_type: "stock" # 股票类型,stock,etf,future,option,bond
|
||||
symbol_decimal_places: 2 # 小数位数, 股票为2,期货,ETF等为3
|
||||
strategy_class: "DebugStrategy"
|
||||
capital: 100000
|
||||
|
||||
# 策略参数
|
||||
params:
|
||||
print_every: 1 # 每条K线都打印
|
||||
simulate_signal: false # 不生成模拟信号
|
||||
|
||||
# 风控参数
|
||||
risk:
|
||||
max_position_ratio: 0.8 # 最大仓位80%
|
||||
stop_loss: 0.05 # 止损5%
|
||||
|
||||
# ==================== 仅对回测生效 ====================
|
||||
# 交易费率配置
|
||||
backtrade:
|
||||
trading_type: t1 # 交易类型 T+0 或 T+1
|
||||
trading_fees:
|
||||
commission_rate: 0.00005 # 佣金率 0.005%(买卖双向收取)ETF 为万0.5, 股票为万0.85
|
||||
min_commission: 5.0 # 最低佣金 5元
|
||||
stamp_tax_rate: 0.001 # 印花税率 0.1%(仅卖出时收取)
|
||||
transfer_fee_rate: 0.00002 # 过户费率 0.002%(买卖双向收取), 万0.2
|
||||
slippage: 0.0001 # 滑点 0.01%(买卖双向影响)
|
||||
start_date: "2025-01-01" # 回测开始日期
|
||||
end_date: "2025-12-31" # 回测结束日期
|
||||
period: "1m" # 回测K线周期
|
||||
|
||||
102
docs/logger_prompt_level_guide.md
Normal file
102
docs/logger_prompt_level_guide.md
Normal file
@ -0,0 +1,102 @@
|
||||
# Logger prompt_level 配置说明
|
||||
|
||||
## 功能概述
|
||||
|
||||
Logger 已升级为使用 `prompt_level` 配置,替代原来的 `logging.level`。只有在 `prompt_level` 列表中的日志级别才会被输出。
|
||||
|
||||
## 配置方式
|
||||
|
||||
在环境配置文件(backtest.yaml / simulation.yaml / production.yaml)中设置:
|
||||
|
||||
```yaml
|
||||
logging:
|
||||
enabled: true
|
||||
prompt_level: ["ERROR", "WARNING", "INFO"] # 只输出这三个级别
|
||||
filepath: "d:\\workspace\\QTrade\\logs"
|
||||
max_size: 10485760 # 10MB
|
||||
backup_count: 5
|
||||
path: "logs/backtest"
|
||||
```
|
||||
|
||||
## 支持的级别
|
||||
|
||||
- `"DEBUG"` - 调试信息
|
||||
- `"INFO"` - 一般信息
|
||||
- `"WARNING"` - 警告信息
|
||||
- `"ERROR"` - 错误信息
|
||||
|
||||
## 使用场景
|
||||
|
||||
### 1. 生产环境 - 只记录错误和警告
|
||||
|
||||
```yaml
|
||||
prompt_level: ["ERROR", "WARNING"]
|
||||
```
|
||||
|
||||
适用于生产环境,减少日志量,只关注问题。
|
||||
|
||||
### 2. 开发/测试环境 - 记录详细信息
|
||||
|
||||
```yaml
|
||||
prompt_level: ["ERROR", "WARNING", "INFO", "DEBUG"]
|
||||
```
|
||||
|
||||
适用于开发调试,查看所有日志。
|
||||
|
||||
### 3. 模拟环境 - 平衡模式
|
||||
|
||||
```yaml
|
||||
prompt_level: ["ERROR", "WARNING", "INFO"]
|
||||
```
|
||||
|
||||
适用于模拟交易,记录重要信息,过滤调试信息。
|
||||
|
||||
## 代码示例
|
||||
|
||||
```python
|
||||
from core.config import Config
|
||||
from core.logger import Logger
|
||||
|
||||
# 初始化
|
||||
Config.initialize("simulation") # 使用 simulation.yaml 配置
|
||||
Logger.initialize()
|
||||
|
||||
# 记录日志
|
||||
Logger.debug("调试信息") # 不会输出(不在 prompt_level 中)
|
||||
Logger.info("一般信息") # 会输出
|
||||
Logger.warning("警告信息") # 会输出
|
||||
Logger.error("错误信息") # 会输出
|
||||
```
|
||||
|
||||
## 实现原理
|
||||
|
||||
1. **LevelFilter 过滤器**:自定义 logging.Filter,只允许指定级别通过
|
||||
2. **Logger 级别设置为 DEBUG**:允许所有级别的日志进入
|
||||
3. **Handler 添加过滤器**:在控制台和文件输出前进行过滤
|
||||
|
||||
## 优势
|
||||
|
||||
- ✅ **灵活性**:可以任意组合日志级别
|
||||
- ✅ **配置化**:通过 YAML 配置,无需修改代码
|
||||
- ✅ **性能**:不需要的日志在 handler 层就被过滤,不会写入文件
|
||||
- ✅ **清晰度**:配置文件明确显示哪些级别会被记录
|
||||
|
||||
## 测试验证
|
||||
|
||||
运行测试脚本验证功能:
|
||||
|
||||
```bash
|
||||
# 测试默认配置(ERROR, WARNING, INFO)
|
||||
conda activate py311
|
||||
python test_logger_levels.py
|
||||
|
||||
# 测试自定义配置(仅 ERROR, WARNING)
|
||||
python test_logger_custom.py
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. `prompt_level` 必须是列表类型,即使只有一个级别也要用 `["ERROR"]`
|
||||
2. 级别名称必须是大写字符串:`"ERROR"`, `"WARNING"`, `"INFO"`, `"DEBUG"`
|
||||
3. 如果 `prompt_level` 未配置,默认为 `["INFO", "WARNING", "ERROR"]`
|
||||
4. 更改配置后需要重启应用才能生效
|
||||
242
docs/realtrade_guide.md
Normal file
242
docs/realtrade_guide.md
Normal file
@ -0,0 +1,242 @@
|
||||
# 实盘交易使用说明
|
||||
|
||||
## 📋 概述
|
||||
|
||||
实盘交易模块使用 MiniQMT 进行真实市场交易。客户端先连接策略服务器获取交易信号,然后通过 MiniQMT API 执行实盘交易。
|
||||
|
||||
## ⚙️ 配置
|
||||
|
||||
### 1. 修改 `configs/production.yaml`
|
||||
|
||||
```yaml
|
||||
# ==================== MiniQMT 实盘交易配置 ====================
|
||||
miniqmt:
|
||||
userdata_path: "D:\\国金QMT交易端模拟\\userdata_mini" # 修改为你的路径
|
||||
session_id: 123456 # 会话ID(不同策略使用不同ID)
|
||||
account:
|
||||
account_id: "40004091" # 修改为你的交易账号
|
||||
account_type: "STOCK" # 账户类型(STOCK/HUGANGTONG/SHENGANGTONG)
|
||||
|
||||
# ==================== 客户端适配器配置 ====================
|
||||
client_adapters:
|
||||
production_adapter:
|
||||
server_url: "ws://localhost:8010/ws/strategy"
|
||||
timeout: 30 # seconds
|
||||
```
|
||||
|
||||
### 2. 配置说明
|
||||
|
||||
- **userdata_path**: MiniQMT 的 `userdata_mini` 文件夹路径
|
||||
- **session_id**: 会话编号,不同策略使用不同的 ID
|
||||
- **account_id**: 你的交易账号
|
||||
- **account_type**:
|
||||
- `STOCK`: 普通股票账户
|
||||
- `HUGANGTONG`: 沪港通
|
||||
- `SHENGANGTONG`: 深港通
|
||||
|
||||
## 🚀 启动方式
|
||||
|
||||
### 方式一:使用启动脚本(推荐)
|
||||
|
||||
#### 1. 同时启动服务器和客户端(服务器新窗口,客户端当前窗口)
|
||||
```bash
|
||||
python realtrade_runner.py both
|
||||
```
|
||||
|
||||
#### 2. 分别启动
|
||||
|
||||
**先启动服务器(新窗口):**
|
||||
```bash
|
||||
python realtrade_runner.py server newwindow
|
||||
```
|
||||
|
||||
**再启动客户端(当前窗口):**
|
||||
```bash
|
||||
python realtrade_runner.py client
|
||||
```
|
||||
|
||||
#### 3. 都在新窗口启动
|
||||
```bash
|
||||
python realtrade_runner.py both newwindow
|
||||
```
|
||||
|
||||
### 方式二:手动启动
|
||||
|
||||
#### 1. 先启动策略服务器
|
||||
```bash
|
||||
python -m src.qtrade_server
|
||||
```
|
||||
|
||||
#### 2. 等待5秒后启动实盘客户端
|
||||
```bash
|
||||
python -m src.realtrade.main
|
||||
```
|
||||
|
||||
## 📊 功能说明
|
||||
|
||||
### 1. 连接 MiniQMT
|
||||
客户端启动时会自动连接 MiniQMT 交易接口:
|
||||
- 建立交易连接
|
||||
- 订阅账户推送
|
||||
- 注册交易回调
|
||||
|
||||
### 2. 查询账户信息
|
||||
启动后会自动查询:
|
||||
- 总资产
|
||||
- 可用资金
|
||||
- 冻结资金
|
||||
- 持仓市值
|
||||
- 总盈亏
|
||||
- 当前持仓列表
|
||||
|
||||
### 3. 获取交易信号
|
||||
通过 WebSocket 连接策略服务器:
|
||||
- 发送 K线数据
|
||||
- 接收交易信号(BUY/SELL/HOLD)
|
||||
|
||||
### 4. 执行交易(默认禁用)
|
||||
**⚠️ 为安全起见,默认不自动执行交易信号!**
|
||||
|
||||
如需启用自动交易,需要在 `src/realtrade/main.py` 中取消注释:
|
||||
|
||||
```python
|
||||
# 取消注释以下代码以执行实盘交易(危险操作!)
|
||||
order_id = adapter.place_order(
|
||||
symbol=signal.symbol,
|
||||
action=signal.action,
|
||||
price=signal.price,
|
||||
quantity=signal.quantity,
|
||||
)
|
||||
```
|
||||
|
||||
### 5. 交易回调
|
||||
实时接收 MiniQMT 推送:
|
||||
- 委托回报
|
||||
- 成交回报
|
||||
- 委托失败
|
||||
- 撤单失败
|
||||
- 账户状态变化
|
||||
|
||||
## 🔧 核心组件
|
||||
|
||||
### MiniQMTClientAdapter
|
||||
|
||||
**初始化参数:**
|
||||
- `server_url`: 策略服务器 WebSocket 地址
|
||||
- `timeout`: 超时时间
|
||||
- `miniqmt_path`: MiniQMT userdata_mini 路径
|
||||
- `session_id`: 会话ID
|
||||
- `account_id`: 交易账号
|
||||
- `account_type`: 账户类型
|
||||
|
||||
**主要方法:**
|
||||
```python
|
||||
# 连接 MiniQMT
|
||||
adapter.connect()
|
||||
|
||||
# 发送 K线获取信号
|
||||
signal = adapter.send_kline(symbol, kline, kline_time, period)
|
||||
|
||||
# 批量发送 K线
|
||||
signals = adapter.send_klines_batch(klines_data, kline_time, period)
|
||||
|
||||
# 下单
|
||||
order_id = adapter.place_order(symbol, action, price, quantity)
|
||||
|
||||
# 撤单
|
||||
adapter.cancel_order(order_id)
|
||||
|
||||
# 查询资产
|
||||
asset = adapter.query_account_asset()
|
||||
|
||||
# 查询持仓
|
||||
positions = adapter.query_positions()
|
||||
|
||||
# 查询委托
|
||||
orders = adapter.query_orders()
|
||||
|
||||
# 关闭连接
|
||||
adapter.close()
|
||||
```
|
||||
|
||||
## ⚠️ 安全警告
|
||||
|
||||
### 实盘交易风险
|
||||
|
||||
1. **资金安全**: 这是真实市场交易,会产生真实的资金损失!
|
||||
2. **策略测试**: 务必先在回测和模拟盘中充分测试策略
|
||||
3. **风控措施**: 设置止损、仓位控制等风险管理措施
|
||||
4. **监控**: 实时监控账户状态和交易情况
|
||||
5. **人工介入**: 必要时人工干预交易
|
||||
|
||||
### 建议
|
||||
|
||||
- ✅ 先在回测环境测试策略
|
||||
- ✅ 再在模拟盘环境验证
|
||||
- ✅ 小资金量测试实盘
|
||||
- ✅ 设置合理的风控参数
|
||||
- ✅ 24小时监控(或交易时段内)
|
||||
- ❌ 不要使用未经测试的策略
|
||||
- ❌ 不要在实盘直接修改代码
|
||||
- ❌ 不要忽视风险提示
|
||||
|
||||
## 📝 日志
|
||||
|
||||
实盘交易日志保存在:
|
||||
```
|
||||
logs/production/qtrade_YYYYMMDD.log
|
||||
```
|
||||
|
||||
建议定期查看日志,了解:
|
||||
- 连接状态
|
||||
- 交易信号
|
||||
- 订单执行情况
|
||||
- 异常错误
|
||||
|
||||
## 🔄 对比回测模式
|
||||
|
||||
| 特性 | 回测模式 | 实盘模式 |
|
||||
| -------- | --------------------- | -------------------- |
|
||||
| 数据源 | 历史数据 | 实时行情 |
|
||||
| 交易执行 | 模拟撮合 | 真实下单 |
|
||||
| 资金 | 虚拟资金 | 真实资金 |
|
||||
| 风险 | 无风险 | 真实风险 |
|
||||
| 服务器 | QTrade Server | QTrade Server |
|
||||
| 客户端 | BacktestClientAdapter | MiniQMTClientAdapter |
|
||||
| 配置文件 | backtest.yaml | production.yaml |
|
||||
| 启动脚本 | backtest_runner.py | realtrade_runner.py |
|
||||
|
||||
## 🆘 故障排除
|
||||
|
||||
### 1. MiniQMT 连接失败
|
||||
- 检查 `userdata_path` 路径是否正确
|
||||
- 确认 MiniQMT 是否已启动
|
||||
- 检查 `session_id` 是否与其他程序冲突
|
||||
|
||||
### 2. 策略服务器连接失败
|
||||
- 确认服务器是否已启动
|
||||
- 检查 `server_url` 配置是否正确
|
||||
- 查看服务器日志
|
||||
|
||||
### 3. 下单失败
|
||||
- 检查账户资金是否充足
|
||||
- 确认标的代码格式是否正确(如 "600000.SH")
|
||||
- 检查交易时间段
|
||||
- 查看 MiniQMT 错误回调信息
|
||||
|
||||
### 4. 权限问题
|
||||
- 确认账户是否有交易权限
|
||||
- 检查是否在交易时间段内
|
||||
- 确认标的是否停牌
|
||||
|
||||
## 📞 技术支持
|
||||
|
||||
如有问题,请查看:
|
||||
1. 日志文件:`logs/production/`
|
||||
2. 配置文件:`configs/production.yaml`
|
||||
3. 适配器代码:`src/realtrade/miniqmt_client_adapter.py`
|
||||
4. 主程序:`src/realtrade/main.py`
|
||||
|
||||
---
|
||||
|
||||
**再次提醒:实盘交易有风险,投资需谨慎!**
|
||||
137
docs/table_cleanup_summary.md
Normal file
137
docs/table_cleanup_summary.md
Normal file
@ -0,0 +1,137 @@
|
||||
# 表结构清理总结
|
||||
|
||||
## 完成的工作
|
||||
|
||||
### 1. 删除了旧的表定义
|
||||
从 `table_schemas.py` 中删除了以下旧表定义:
|
||||
- ✅ **ORDER_TABLE** (旧版本)
|
||||
- ✅ **TRADE_TABLE** (旧版本)
|
||||
- ✅ **POSITION_TABLE** (旧版本)
|
||||
- ✅ **ACCOUNT_TABLE** (已重命名为 ASSET_TABLE)
|
||||
- ✅ **SYMBOL_TABLE** (Symbol 模型已删除,信息移至配置文件)
|
||||
|
||||
### 2. 更新了表定义导入
|
||||
在 `table_schemas.py` 中:
|
||||
```python
|
||||
from .trading_table_schemas import (
|
||||
ORDER_TABLE,
|
||||
TRADE_TABLE,
|
||||
POSITION_TABLE,
|
||||
ASSET_TABLE,
|
||||
)
|
||||
```
|
||||
|
||||
### 3. 更新了 SIGNAL_TABLE
|
||||
添加了 `instance_id` 字段和相应索引:
|
||||
```python
|
||||
"instance_id": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": False,
|
||||
"comment": "策略实例ID",
|
||||
}
|
||||
```
|
||||
|
||||
索引:
|
||||
```python
|
||||
{"name": "idx_instance", "columns": ["instance_id"]}
|
||||
```
|
||||
|
||||
### 4. 更新了 ALL_TABLES 字典
|
||||
```python
|
||||
ALL_TABLES = {
|
||||
**ALL_KLINE_TABLES,
|
||||
**ALL_INDICATOR_TABLES,
|
||||
"ticks": TICK_TABLE,
|
||||
"signals": SIGNAL_TABLE,
|
||||
# 交易相关表(从 trading_table_schemas 导入)
|
||||
"orders": ORDER_TABLE,
|
||||
"trades": TRADE_TABLE,
|
||||
"positions": POSITION_TABLE,
|
||||
"assets": ASSET_TABLE, # 不再是 accounts
|
||||
}
|
||||
```
|
||||
|
||||
### 5. 更新了模块导出
|
||||
更新 `database_manager/__init__.py`:
|
||||
- 移除:ACCOUNT_TABLE, SYMBOL_TABLE
|
||||
- 添加:从 `trading_table_schemas` 导入新的表定义
|
||||
- 新增:ASSET_TABLE
|
||||
|
||||
### 6. 清理了未使用的导入
|
||||
- 从 `trading_table_schemas.py` 移除 `Dict, Any`
|
||||
- 从 `trading_cache.py` 移除 `datetime`
|
||||
|
||||
## 表结构对比
|
||||
|
||||
### 旧表 vs 新表
|
||||
|
||||
| 旧表名 | 新表名 | 变化 |
|
||||
| -------------- | --------- | ----------------------------------------- |
|
||||
| orders (旧) | orders | 完全重构,增加 instance_id 等字段 |
|
||||
| trades (旧) | trades | 完全重构,增加 instance_id 和 cost_detail |
|
||||
| positions (旧) | positions | 完全重构,增加大量统计字段 |
|
||||
| accounts | assets | 重命名,增加完整的资产管理字段 |
|
||||
| symbols | (删除) | 信息移至 YAML 配置文件 |
|
||||
|
||||
## 核心改进
|
||||
|
||||
### 多策略实例隔离
|
||||
所有交易相关表都包含:
|
||||
- `instance_id`: 策略实例ID(必填)
|
||||
- `strategy_name`: 策略名称(必填)
|
||||
- 相应的组合索引
|
||||
|
||||
### 字段统计
|
||||
- **ORDER_TABLE**: 22 个字段,6 个索引
|
||||
- **TRADE_TABLE**: 13 个字段,6 个索引
|
||||
- **POSITION_TABLE**: 29 个字段,4 个索引
|
||||
- **ASSET_TABLE**: 30 个字段,2 个索引
|
||||
- **SIGNAL_TABLE**: 13 个字段(新增 instance_id),5 个索引
|
||||
|
||||
## 测试结果
|
||||
|
||||
✅ 所有表定义正确导入
|
||||
✅ ALL_TABLES 包含所有新表
|
||||
✅ 旧表(accounts, symbols)已删除
|
||||
✅ 所有交易表包含 instance_id 字段
|
||||
✅ 所有必需索引已创建
|
||||
✅ 无 Python 语法错误
|
||||
|
||||
## 下一步
|
||||
|
||||
1. **测试数据库表创建**
|
||||
- 使用 DatabaseManager 创建表
|
||||
- 验证表结构是否符合预期
|
||||
|
||||
2. **测试存储层**
|
||||
- 使用 TradingDataStorage 保存和读取数据
|
||||
- 验证 instance_id 隔离是否有效
|
||||
|
||||
3. **测试缓存层**
|
||||
- 使用 TradingCache 缓存和检索数据
|
||||
- 验证实例隔离逻辑
|
||||
|
||||
4. **集成到回测引擎**
|
||||
- 在回测任务中使用新的表结构
|
||||
- 验证多策略实例是否正确隔离
|
||||
|
||||
## 文件变更清单
|
||||
|
||||
### 修改的文件
|
||||
- ✅ `src/database_manager/table_schemas.py` - 删除旧表,更新导入
|
||||
- ✅ `src/database_manager/__init__.py` - 更新导出
|
||||
- ✅ `src/database_manager/trading_table_schemas.py` - 清理导入
|
||||
- ✅ `src/cache/trading_cache.py` - 清理导入
|
||||
|
||||
### 新增的文件
|
||||
- ✅ `test_table_schemas.py` - 表结构测试脚本
|
||||
|
||||
### 已删除的定义
|
||||
- ❌ ORDER_TABLE (旧版本,约70行)
|
||||
- ❌ TRADE_TABLE (旧版本,约60行)
|
||||
- ❌ POSITION_TABLE (旧版本,约70行)
|
||||
- ❌ ACCOUNT_TABLE (旧版本,约50行)
|
||||
- ❌ SYMBOL_TABLE (约70行)
|
||||
|
||||
**总删除行数**: ~320 行废弃代码
|
||||
546
docs/tech_designs/REFACTOR_SUMMARY.md
Normal file
546
docs/tech_designs/REFACTOR_SUMMARY.md
Normal file
@ -0,0 +1,546 @@
|
||||
# 重构完成总结
|
||||
|
||||
> **日期**: 2025-12-27
|
||||
> **重构目标**: 实现简化的两层架构,Context直接提供数据访问方法
|
||||
> **原则**: 不考虑兼容性,全新重构
|
||||
|
||||
---
|
||||
|
||||
## 1. 重构概览
|
||||
|
||||
### 1.1 架构变化
|
||||
|
||||
**原架构(假想的三层)**:
|
||||
```
|
||||
Strategy → StrategyContext → SharedServices → CacheManager
|
||||
```
|
||||
|
||||
**新架构(两层)**:
|
||||
```
|
||||
Strategy → StrategyContext → CacheManager
|
||||
```
|
||||
|
||||
### 1.2 核心变化
|
||||
|
||||
| 变化项 | 重构前 | 重构后 |
|
||||
| --------------- | ---------------------------- | ------------------------- |
|
||||
| **中间层** | 需要 SharedServices | ❌ 删除 |
|
||||
| **Context职责** | 持有SharedServices引用 | 直接持有cache_manager引用 |
|
||||
| **数据访问** | context._shared.get_klines() | context.get_klines() |
|
||||
| **共享机制** | 传入SharedServices实例 | 传入cache_manager实例 |
|
||||
| **策略基类** | 无统一基类 | 新增BaseStrategy |
|
||||
|
||||
---
|
||||
|
||||
## 2. 新增文件
|
||||
|
||||
### 2.1 核心类
|
||||
|
||||
| 文件 | 说明 | 行数 |
|
||||
| ------------------------------------------------------------ | ------------------------ | ---- |
|
||||
| [src/core/position.py](src/core/position.py) | 持仓管理(独立状态) | ~100 |
|
||||
| [src/core/capital.py](src/core/capital.py) | 资金管理(独立状态) | ~130 |
|
||||
| [src/core/risk_state.py](src/core/risk_state.py) | 风险状态管理(独立状态) | ~180 |
|
||||
| [src/core/strategy_context.py](src/core/strategy_context.py) | 策略上下文(核心) | ~360 |
|
||||
| [src/core/base_strategy.py](src/core/base_strategy.py) | 策略基类 | ~80 |
|
||||
|
||||
### 2.2 详细说明
|
||||
|
||||
#### Position (持仓管理)
|
||||
```python
|
||||
@dataclass
|
||||
class Position:
|
||||
symbol: str
|
||||
shares: float = 0.0 # 持仓数量
|
||||
cost: float = 0.0 # 持仓成本
|
||||
|
||||
@property
|
||||
def avg_price(self) -> float
|
||||
def update(self, shares_change, cost_change)
|
||||
def calculate_profit(self, current_price) -> float
|
||||
```
|
||||
|
||||
#### Capital (资金管理)
|
||||
```python
|
||||
@dataclass
|
||||
class Capital:
|
||||
initial_cash: float
|
||||
available_cash: float
|
||||
frozen_cash: float
|
||||
|
||||
def freeze(self, amount) -> bool
|
||||
def unfreeze(self, amount) -> bool
|
||||
def update(self, amount)
|
||||
```
|
||||
|
||||
#### RiskState (风险状态)
|
||||
```python
|
||||
@dataclass
|
||||
class RiskState:
|
||||
max_position_ratio: float
|
||||
stop_loss_ratio: float
|
||||
stop_profit_ratio: float
|
||||
|
||||
def check_position_limit(self, ...) -> bool
|
||||
def check_stop_loss(self, ...) -> bool
|
||||
def record_loss(self, loss_amount)
|
||||
```
|
||||
|
||||
#### StrategyContext (核心)
|
||||
```python
|
||||
class StrategyContext:
|
||||
def __init__(
|
||||
self,
|
||||
cache_manager, # 共享实例
|
||||
db_manager, # 共享实例(可选)
|
||||
instance_id,
|
||||
symbol,
|
||||
instance_config,
|
||||
enable_db_fallback
|
||||
)
|
||||
|
||||
# 共享资源(私有)
|
||||
self._cache_manager
|
||||
self._db_manager
|
||||
|
||||
# 独立状态
|
||||
self._position: Position
|
||||
self._capital: Capital
|
||||
self._risk_state: RiskState
|
||||
|
||||
# 数据访问接口
|
||||
def get_klines(...) -> DataFrame
|
||||
def get_indicators(...) -> DataFrame
|
||||
|
||||
# 状态访问接口
|
||||
def get_position() -> Position
|
||||
def get_capital() -> Capital
|
||||
def get_risk_state() -> RiskState
|
||||
```
|
||||
|
||||
#### BaseStrategy (策略基类)
|
||||
```python
|
||||
class BaseStrategy(ABC):
|
||||
def __init__(self, context: StrategyContext, **params)
|
||||
|
||||
@abstractmethod
|
||||
def compute(self, kline_data) -> Optional[Dict]
|
||||
|
||||
def on_init(self) # 可选回调
|
||||
def on_trade(self, ...) # 可选回调
|
||||
def on_error(self, ...) # 可选回调
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 修改文件
|
||||
|
||||
### 3.1 StrategyManager
|
||||
|
||||
**文件**: [src/strategy_manager.py](src/strategy_manager.py)
|
||||
|
||||
**关键修改**:
|
||||
```python
|
||||
# 修改前
|
||||
def __init__(self, config_dir):
|
||||
self.config_dir = Path(config_dir)
|
||||
|
||||
# 修改后
|
||||
def __init__(
|
||||
self,
|
||||
config_dir: str,
|
||||
cache_manager, # 新增:共享实例
|
||||
db_manager=None, # 新增:共享实例(可选)
|
||||
enable_db_fallback=False # 新增:降级开关
|
||||
):
|
||||
self.config_dir = Path(config_dir)
|
||||
self._cache_manager = cache_manager
|
||||
self._db_manager = db_manager
|
||||
self._enable_db_fallback = enable_db_fallback
|
||||
```
|
||||
|
||||
**创建策略实例的变化**:
|
||||
```python
|
||||
# 修改前
|
||||
strategy_obj = strategy_class(**params)
|
||||
|
||||
# 修改后
|
||||
# 1. 创建Context
|
||||
context = StrategyContext(
|
||||
cache_manager=self._cache_manager,
|
||||
db_manager=self._db_manager,
|
||||
instance_id=instance_id,
|
||||
symbol=symbol,
|
||||
instance_config=config,
|
||||
enable_db_fallback=self._enable_db_fallback
|
||||
)
|
||||
|
||||
# 2. 创建策略实例(传入context)
|
||||
strategy_obj = strategy_class(context=context, **params)
|
||||
|
||||
# 3. 调用初始化回调
|
||||
if hasattr(strategy_obj, 'on_init'):
|
||||
strategy_obj.on_init()
|
||||
```
|
||||
|
||||
### 3.2 qtrade_server.py
|
||||
|
||||
**文件**: [src/qtrade_server.py](src/qtrade_server.py)
|
||||
|
||||
**新增初始化函数**:
|
||||
```python
|
||||
def initialize_server(
|
||||
config_dir: str = "config/strategies",
|
||||
cache_config: Optional[dict] = None
|
||||
):
|
||||
global strategy_manager, cache_manager
|
||||
|
||||
# 1. 初始化缓存管理器
|
||||
cache_manager = CacheManager(cache_config or default_config)
|
||||
|
||||
# 2. 初始化策略管理器(直接传入共享资源)
|
||||
strategy_manager = StrategyManager(
|
||||
config_dir=config_dir,
|
||||
cache_manager=cache_manager,
|
||||
db_manager=None,
|
||||
enable_db_fallback=False
|
||||
)
|
||||
|
||||
# 3. 加载并初始化所有策略
|
||||
strategy_manager.initialize()
|
||||
```
|
||||
|
||||
**启动函数修改**:
|
||||
```python
|
||||
def start_server(host, port, config_dir):
|
||||
# 初始化服务器(不再是initialize_strategy_manager)
|
||||
if not initialize_server(config_dir):
|
||||
return
|
||||
|
||||
# 注册关闭钩子
|
||||
signal.signal(signal.SIGTERM, on_shutdown)
|
||||
signal.signal(signal.SIGINT, on_shutdown)
|
||||
|
||||
# 创建并启动WebSocket服务器
|
||||
ws_server = WebSocketServer(...)
|
||||
ws_server.start(host, port)
|
||||
```
|
||||
|
||||
### 3.3 DebugStrategy
|
||||
|
||||
**文件**: [src/strategies/debug_strategy.py](src/strategies/debug_strategy.py)
|
||||
|
||||
**关键修改**:
|
||||
```python
|
||||
# 修改前
|
||||
class DebugStrategy:
|
||||
def __init__(self, **params):
|
||||
self.print_every = params.get("print_every", 1)
|
||||
self.last_price = None
|
||||
|
||||
# 修改后
|
||||
class DebugStrategy(BaseStrategy):
|
||||
def on_init(self):
|
||||
# 从 self.params 和 self.context 获取信息
|
||||
self.print_every = self.params.get("print_every", 1)
|
||||
self.last_price = None
|
||||
|
||||
print(f"[{self.context.instance_id}] Initialized")
|
||||
print(f" Symbol: {self.context.symbol}")
|
||||
print(f" Capital: {self.context.get_capital().initial_cash:.2f}")
|
||||
```
|
||||
|
||||
**compute方法修改**:
|
||||
```python
|
||||
def compute(self, kline_data):
|
||||
# 可以访问Context的所有方法
|
||||
position = self.context.get_position()
|
||||
capital = self.context.get_capital()
|
||||
|
||||
print(f"[{self.context.instance_id}] K-line #{self.kline_count}")
|
||||
print(f" Position: {position.shares:.2f} @ {position.avg_price:.2f}")
|
||||
print(f" Capital: {capital.available_cash:.2f}")
|
||||
|
||||
# ...计算逻辑
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 数据流说明
|
||||
|
||||
### 4.1 服务器启动流程
|
||||
|
||||
```
|
||||
1. 加载配置
|
||||
config = load_config('global_config.yaml')
|
||||
|
||||
2. 初始化缓存管理器
|
||||
cache_manager = CacheManager(config['cache']) # 单例
|
||||
|
||||
3. 初始化策略管理器
|
||||
strategy_manager = StrategyManager(
|
||||
config_dir='config/strategies',
|
||||
cache_manager=cache_manager, # 传入共享实例
|
||||
db_manager=None
|
||||
)
|
||||
|
||||
4. 加载策略配置并创建实例
|
||||
for each config in configs:
|
||||
context = StrategyContext(
|
||||
cache_manager, # 同一个实例
|
||||
...
|
||||
)
|
||||
strategy = DebugStrategy(context, **params)
|
||||
strategy.on_init()
|
||||
|
||||
5. 启动WebSocket服务器
|
||||
ws_server.start(host, port)
|
||||
```
|
||||
|
||||
### 4.2 运行时数据流
|
||||
|
||||
```
|
||||
1. WebSocket收到K线数据
|
||||
message = {"symbol": "000001.SZ", "data": {...}}
|
||||
|
||||
2. 分发到StrategyManager
|
||||
signals = strategy_manager.dispatch_kline(symbol, kline_data)
|
||||
|
||||
3. 调用策略compute方法
|
||||
for strategy in strategies[symbol]:
|
||||
result = strategy.compute(kline_data)
|
||||
|
||||
# 策略内部
|
||||
history = self.context.get_klines('000001.SZ', '1m', last_n=100)
|
||||
|
||||
# Context内部
|
||||
df = self._cache_manager.get_klines(symbol, period)
|
||||
|
||||
4. 返回信号
|
||||
return signals
|
||||
```
|
||||
|
||||
### 4.3 共享机制说明
|
||||
|
||||
```python
|
||||
# 服务器启动时
|
||||
cache_manager = CacheManager(...) # 创建一个实例
|
||||
|
||||
# 创建多个Context
|
||||
context1 = StrategyContext(cache_manager, ...) # 传入引用
|
||||
context2 = StrategyContext(cache_manager, ...) # 传入同一个引用
|
||||
|
||||
# 验证共享
|
||||
context1._cache_manager is context2._cache_manager # True
|
||||
|
||||
# 它们访问的是同一个缓存
|
||||
context1.get_klines('000001.SZ', '1m') # 从同一个cache读取
|
||||
context2.get_klines('000001.SZ', '1m') # 从同一个cache读取
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 设计优势
|
||||
|
||||
### 5.1 简洁性
|
||||
|
||||
| 方面 | 三层架构 | 两层架构 |
|
||||
| ------------ | ------------------------------------------- | -------------------------- |
|
||||
| **中间层** | SharedServices | ❌ 无 |
|
||||
| **调用链** | Strategy → Context → SharedServices → Cache | Strategy → Context → Cache |
|
||||
| **代码行数** | 更多 | 更少 |
|
||||
| **理解难度** | 高(为什么需要SharedServices?) | 低(直观) |
|
||||
|
||||
### 5.2 封装性
|
||||
|
||||
```python
|
||||
# ✅ 好的封装
|
||||
context.get_klines(...) # 策略不知道数据从哪来
|
||||
|
||||
# Context内部可以:
|
||||
# - 从缓存读取
|
||||
# - 缓存未命中时降级到数据库
|
||||
# - 对策略完全透明
|
||||
```
|
||||
|
||||
### 5.3 可维护性
|
||||
|
||||
**修改数据访问逻辑**:
|
||||
- 只需修改 StrategyContext.get_klines() 方法
|
||||
- 策略代码无需修改
|
||||
- 降级逻辑对策略透明
|
||||
|
||||
**添加新的数据源**:
|
||||
- 在Context内部添加新的私有成员
|
||||
- 修改get_klines()方法的实现
|
||||
- 策略接口保持不变
|
||||
|
||||
---
|
||||
|
||||
## 6. 使用示例
|
||||
|
||||
### 6.1 编写新策略
|
||||
|
||||
```python
|
||||
from src.core.base_strategy import BaseStrategy
|
||||
|
||||
class MyStrategy(BaseStrategy):
|
||||
def on_init(self):
|
||||
"""初始化"""
|
||||
self.ma_period = self.params.get('ma_period', 20)
|
||||
print(f"Strategy initialized: {self.context.instance_id}")
|
||||
|
||||
def compute(self, kline_data):
|
||||
"""计算信号"""
|
||||
# 获取历史数据
|
||||
history = self.context.get_klines(period='1m', last_n=100)
|
||||
if history is None or len(history) < self.ma_period:
|
||||
return None
|
||||
|
||||
# 计算指标
|
||||
ma = history['close'].rolling(self.ma_period).mean()
|
||||
current_price = kline_data['close']
|
||||
|
||||
# 获取持仓和资金
|
||||
position = self.context.get_position()
|
||||
capital = self.context.get_capital()
|
||||
|
||||
# 检查风险
|
||||
risk = self.context.get_risk_state()
|
||||
if risk.is_risk_locked:
|
||||
return None
|
||||
|
||||
# 生成信号
|
||||
if current_price > ma.iloc[-1] and position.is_empty:
|
||||
return {
|
||||
'action': 'BUY',
|
||||
'symbol': self.context.symbol,
|
||||
'price': current_price,
|
||||
'quantity': 100,
|
||||
'reason': f'Price above MA{self.ma_period}'
|
||||
}
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
### 6.2 策略配置
|
||||
|
||||
```yaml
|
||||
# config/strategies/my_strategy_000001.yaml
|
||||
instance_id: "my_strategy_000001"
|
||||
symbol: "000001.SZ"
|
||||
strategy_class: "MyStrategy"
|
||||
params:
|
||||
ma_period: 20
|
||||
initial_capital: 1000000.0
|
||||
max_position_ratio: 0.5
|
||||
stop_loss_ratio: 0.05
|
||||
```
|
||||
|
||||
### 6.3 启动服务器
|
||||
|
||||
```python
|
||||
# 方式1:直接启动(会自动加载所有配置)
|
||||
from src.qtrade_server import start_server
|
||||
start_server(host='0.0.0.0', port=8000)
|
||||
|
||||
# 方式2:自定义配置
|
||||
from src.qtrade_server import initialize_server, start_server
|
||||
|
||||
# 初始化
|
||||
initialize_server(
|
||||
config_dir='config/strategies',
|
||||
cache_config={
|
||||
'cache': {
|
||||
'enabled': True,
|
||||
'max_memory_mb': 4096
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
# 启动
|
||||
start_server(host='0.0.0.0', port=8000)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. 注意事项
|
||||
|
||||
### 7.1 策略必须继承BaseStrategy
|
||||
|
||||
```python
|
||||
# ❌ 错误
|
||||
class MyStrategy:
|
||||
def __init__(self, **params):
|
||||
pass
|
||||
|
||||
# ✅ 正确
|
||||
class MyStrategy(BaseStrategy):
|
||||
def on_init(self):
|
||||
pass
|
||||
|
||||
def compute(self, kline_data):
|
||||
pass
|
||||
```
|
||||
|
||||
### 7.2 Context是策略的唯一接口
|
||||
|
||||
```python
|
||||
# ❌ 不要直接访问私有成员
|
||||
self.context._cache_manager # 不要这样做
|
||||
|
||||
# ✅ 使用公开方法
|
||||
self.context.get_klines(...) # 正确方式
|
||||
```
|
||||
|
||||
### 7.3 共享资源是只读的
|
||||
|
||||
```python
|
||||
# Context内部
|
||||
self._cache_manager # 只读取,不要修改状态
|
||||
|
||||
# 策略可以修改自己的独立状态
|
||||
position = self.context.get_position()
|
||||
position.update(100, 5000.0) # ✅ 可以
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. 下一步工作
|
||||
|
||||
### 8.1 需要实现的功能
|
||||
|
||||
- [ ] 缓存预加载机制(从数据库加载历史数据)
|
||||
- [ ] CacheManager扩展(append_kline, get_klines_range)
|
||||
- [ ] 数据库降级逻辑完善
|
||||
- [ ] 服务器关闭时保存缓存(可选)
|
||||
|
||||
### 8.2 需要测试的场景
|
||||
|
||||
- [ ] 单个策略实例
|
||||
- [ ] 多个策略实例(同symbol)
|
||||
- [ ] 多个策略实例(不同symbol)
|
||||
- [ ] 缓存命中和未命中
|
||||
- [ ] 持仓和资金更新
|
||||
- [ ] 风险控制触发
|
||||
|
||||
---
|
||||
|
||||
## 9. 设计文档
|
||||
|
||||
相关设计文档:
|
||||
1. [qtrade_server_cache_design.md](docs/tech_designs/qtrade_server_cache_design.md) - 缓存机制设计
|
||||
2. [qtrade_server_cache_architecture_review.md](docs/tech_designs/qtrade_server_cache_architecture_review.md) - 架构评审
|
||||
3. [strategy_context_sharing_design.md](docs/tech_designs/strategy_context_sharing_design.md) - Context共享策略
|
||||
4. [shared_services_interface_minimization.md](docs/tech_designs/shared_services_interface_minimization.md) - 接口最小化
|
||||
5. [context_direct_methods_design.md](docs/tech_designs/context_direct_methods_design.md) - Context直接方法设计
|
||||
|
||||
---
|
||||
|
||||
**重构完成!** ✅
|
||||
|
||||
核心思想:
|
||||
- ✅ 不需要SharedServices中间层
|
||||
- ✅ Context直接提供所有方法
|
||||
- ✅ 共享通过传入同一个实例实现
|
||||
- ✅ 策略只依赖Context接口
|
||||
859
docs/tech_designs/context_direct_methods_design.md
Normal file
859
docs/tech_designs/context_direct_methods_design.md
Normal file
@ -0,0 +1,859 @@
|
||||
# Context 直接方法设计
|
||||
|
||||
> **核心观点**: 不需要 SharedServices 中间层,数据访问方法直接放在 StrategyContext 上
|
||||
> **用户观点**: "不用封装这么多层,可以直接变为 context 的方法,是不是更好?"
|
||||
> **日期**: 2025-12-27
|
||||
> **结论**: ✅ 完全正确!更简洁、更直观
|
||||
|
||||
---
|
||||
|
||||
## 1. 架构对比
|
||||
|
||||
### 1.1 原设计(三层)
|
||||
|
||||
```
|
||||
Strategy
|
||||
↓ 调用
|
||||
StrategyContext
|
||||
↓ context._shared.get_klines()
|
||||
SharedServices (中间层)
|
||||
↓ self._cache_manager.get_klines()
|
||||
CacheManager
|
||||
```
|
||||
|
||||
**代码示例**:
|
||||
```python
|
||||
# 策略中使用
|
||||
class MAStrategy:
|
||||
def compute(self, kline_data):
|
||||
# ❌ 需要通过 _shared 访问
|
||||
history = self.context._shared.get_klines('000001.SZ', '1m', last_n=100)
|
||||
|
||||
# 或者封装在 Context 的委托方法中
|
||||
history = self.context.get_klines('000001.SZ', '1m', last_n=100)
|
||||
# 但内部实现: return self._shared.get_klines(...)
|
||||
```
|
||||
|
||||
**问题**:
|
||||
- ❌ 多了一层 SharedServices 间接性
|
||||
- ❌ StrategyContext 需要委托所有方法
|
||||
- ❌ 增加了复杂度
|
||||
|
||||
### 1.2 新设计(两层)
|
||||
|
||||
```
|
||||
Strategy
|
||||
↓ 调用
|
||||
StrategyContext (直接提供方法)
|
||||
↓ self._cache_manager.get_klines()
|
||||
CacheManager
|
||||
```
|
||||
|
||||
**代码示例**:
|
||||
```python
|
||||
# 策略中使用
|
||||
class MAStrategy:
|
||||
def compute(self, kline_data):
|
||||
# ✅ 直接调用 context 的方法
|
||||
history = self.context.get_klines('000001.SZ', '1m', last_n=100)
|
||||
|
||||
# context 内部直接访问 cache_manager
|
||||
# 不需要通过 SharedServices
|
||||
```
|
||||
|
||||
**优点**:
|
||||
- ✅ 减少一层间接性
|
||||
- ✅ 代码更简洁直观
|
||||
- ✅ Context 直接封装数据访问逻辑
|
||||
- ✅ 符合"Context 是策略的唯一接口"理念
|
||||
|
||||
---
|
||||
|
||||
## 2. 新设计实现
|
||||
|
||||
### 2.1 StrategyContext 实现
|
||||
|
||||
```python
|
||||
class StrategyContext:
|
||||
"""
|
||||
策略上下文(直接提供所有方法)
|
||||
|
||||
设计原则:
|
||||
1. Context 是策略访问所有资源的唯一入口
|
||||
2. 内部直接持有 cache_manager、db_manager(私有)
|
||||
3. 对外提供高层接口,隐藏实现细节
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cache_manager: CacheManager,
|
||||
db_manager: Optional[DBManager],
|
||||
instance_id: str,
|
||||
symbol: str,
|
||||
instance_config: dict,
|
||||
enable_db_fallback: bool = False
|
||||
):
|
||||
"""
|
||||
初始化策略上下文
|
||||
|
||||
Args:
|
||||
cache_manager: 缓存管理器(共享实例)
|
||||
db_manager: 数据库管理器(共享实例,可选)
|
||||
instance_id: 策略实例ID
|
||||
symbol: 交易标的
|
||||
instance_config: 实例配置
|
||||
enable_db_fallback: 是否启用数据库降级
|
||||
"""
|
||||
# ==================== 共享资源(私有) ====================
|
||||
# 注意:这些是传入的共享实例,不是新创建的
|
||||
self._cache_manager = cache_manager
|
||||
self._db_manager = db_manager
|
||||
self._enable_db_fallback = enable_db_fallback
|
||||
|
||||
# ==================== 实例信息 ====================
|
||||
self.instance_id = instance_id
|
||||
self.symbol = symbol
|
||||
self.config = instance_config
|
||||
|
||||
# ==================== 独立状态 ====================
|
||||
self._position = Position(
|
||||
symbol=symbol,
|
||||
initial_shares=0,
|
||||
initial_cost=0.0
|
||||
)
|
||||
|
||||
self._capital = Capital(
|
||||
initial_cash=instance_config.get('initial_capital', 1000000.0)
|
||||
)
|
||||
|
||||
self._risk_state = RiskState(
|
||||
max_position_ratio=instance_config.get('max_position_ratio', 0.5),
|
||||
stop_loss_ratio=instance_config.get('stop_loss_ratio', 0.05)
|
||||
)
|
||||
|
||||
# ==================== 数据访问接口(直接实现) ====================
|
||||
|
||||
def get_klines(
|
||||
self,
|
||||
symbol: Optional[str] = None,
|
||||
period: str = '1m',
|
||||
last_n: Optional[int] = None,
|
||||
start: Optional[pd.Timestamp] = None,
|
||||
end: Optional[pd.Timestamp] = None
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
获取K线数据(直接从缓存获取)
|
||||
|
||||
这是策略访问数据的主要方式
|
||||
|
||||
Args:
|
||||
symbol: 标的代码,默认使用实例的 symbol
|
||||
period: 周期
|
||||
last_n: 最近N条
|
||||
start: 开始时间
|
||||
end: 结束时间
|
||||
|
||||
Returns:
|
||||
K线DataFrame,如果不存在返回None
|
||||
"""
|
||||
target_symbol = symbol or self.symbol
|
||||
|
||||
# 1. 从缓存读取
|
||||
df = self._cache_manager.get_klines_range(
|
||||
symbol=target_symbol,
|
||||
period=period,
|
||||
last_n=last_n,
|
||||
start=start,
|
||||
end=end
|
||||
)
|
||||
|
||||
# 2. 缓存命中
|
||||
if df is not None and not df.empty:
|
||||
if last_n is None or len(df) >= last_n:
|
||||
return df
|
||||
|
||||
# 3. 缓存未命中,尝试降级(可选)
|
||||
if self._enable_db_fallback and self._db_manager:
|
||||
logger.warning(
|
||||
f"[{self.instance_id}] Cache miss: {target_symbol}_{period}, "
|
||||
f"loading from database"
|
||||
)
|
||||
df = self._load_from_database(target_symbol, period, last_n, start, end)
|
||||
|
||||
# 加载后填充缓存
|
||||
if df is not None and not df.empty:
|
||||
self._cache_manager.set_klines(target_symbol, period, {'klines': df})
|
||||
|
||||
return df
|
||||
|
||||
# 4. 无降级或降级失败
|
||||
logger.warning(
|
||||
f"[{self.instance_id}] No data available: {target_symbol}_{period}"
|
||||
)
|
||||
return None
|
||||
|
||||
def get_indicators(
|
||||
self,
|
||||
symbol: Optional[str] = None,
|
||||
period: str = '1m',
|
||||
indicator_type: str = 'MACD'
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
获取指标数据
|
||||
|
||||
Args:
|
||||
symbol: 标的代码,默认使用实例的 symbol
|
||||
period: 周期
|
||||
indicator_type: 指标类型
|
||||
|
||||
Returns:
|
||||
指标DataFrame,如果不存在返回None
|
||||
"""
|
||||
target_symbol = symbol or self.symbol
|
||||
return self._cache_manager.get_indicator(target_symbol, period, indicator_type)
|
||||
|
||||
# ==================== 状态访问接口 ====================
|
||||
|
||||
def get_position(self) -> Position:
|
||||
"""获取持仓信息(独立状态)"""
|
||||
return self._position
|
||||
|
||||
def get_capital(self) -> Capital:
|
||||
"""获取资金信息(独立状态)"""
|
||||
return self._capital
|
||||
|
||||
def get_risk_state(self) -> RiskState:
|
||||
"""获取风险状态(独立状态)"""
|
||||
return self._risk_state
|
||||
|
||||
def update_position(self, shares: float, cost: float):
|
||||
"""更新持仓"""
|
||||
self._position.update(shares, cost)
|
||||
|
||||
def update_capital(self, cash_change: float):
|
||||
"""更新资金"""
|
||||
self._capital.update(cash_change)
|
||||
|
||||
# ==================== 私有方法 ====================
|
||||
|
||||
def _load_from_database(
|
||||
self,
|
||||
symbol: str,
|
||||
period: str,
|
||||
last_n: Optional[int],
|
||||
start: Optional[pd.Timestamp],
|
||||
end: Optional[pd.Timestamp]
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
从数据库加载数据(私有方法)
|
||||
|
||||
降级逻辑封装在内部
|
||||
"""
|
||||
if not self._db_manager:
|
||||
return None
|
||||
|
||||
try:
|
||||
if last_n:
|
||||
df = self._db_manager.load_klines_last_n(symbol, period, last_n)
|
||||
else:
|
||||
df = self._db_manager.load_klines_range(symbol, period, start, end)
|
||||
return df
|
||||
except Exception as e:
|
||||
logger.error(f"[{self.instance_id}] Failed to load from database: {e}")
|
||||
return None
|
||||
|
||||
# ==================== 工具方法 ====================
|
||||
|
||||
def get_cache_info(self, symbol: Optional[str] = None, period: str = '1m') -> dict:
|
||||
"""
|
||||
获取缓存信息(用于调试)
|
||||
|
||||
Args:
|
||||
symbol: 标的代码
|
||||
period: 周期
|
||||
|
||||
Returns:
|
||||
缓存信息字典
|
||||
"""
|
||||
target_symbol = symbol or self.symbol
|
||||
return self._cache_manager.get_cache_info(target_symbol, period)
|
||||
```
|
||||
|
||||
### 2.2 关键点说明
|
||||
|
||||
**Q: 多个策略实例如何共享 cache_manager?**
|
||||
```python
|
||||
# 答案:传入同一个实例
|
||||
|
||||
# 服务器启动时
|
||||
cache_manager = CacheManager(...) # 单例
|
||||
db_manager = DBManager(...) # 单例
|
||||
|
||||
# 创建多个策略上下文
|
||||
context1 = StrategyContext(
|
||||
cache_manager=cache_manager, # ← 共享实例
|
||||
db_manager=db_manager, # ← 共享实例
|
||||
instance_id='debug_000001',
|
||||
...
|
||||
)
|
||||
|
||||
context2 = StrategyContext(
|
||||
cache_manager=cache_manager, # ← 同一个实例
|
||||
db_manager=db_manager, # ← 同一个实例
|
||||
instance_id='debug_600000',
|
||||
...
|
||||
)
|
||||
|
||||
# cache_manager 是共享的,多个 context 只是持有引用
|
||||
# 不会创建多个 cache_manager
|
||||
```
|
||||
|
||||
**Q: 这样还算是"共享"吗?**
|
||||
```python
|
||||
# ✅ 是的!虽然每个 Context 都有 self._cache_manager
|
||||
# 但它们都指向同一个对象
|
||||
|
||||
context1._cache_manager is context2._cache_manager # True
|
||||
|
||||
# 类比:多个人共享同一个图书馆
|
||||
# 每个人都知道图书馆在哪(持有引用)
|
||||
# 但图书馆只有一个(同一个实例)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. StrategyManager 的变化
|
||||
|
||||
### 3.1 原设计
|
||||
|
||||
```python
|
||||
class StrategyManager:
|
||||
def __init__(self, config_dir, shared_services):
|
||||
self.shared_services = shared_services
|
||||
# ...
|
||||
|
||||
def _create_strategy_instance(self, strategy_class, instance_config):
|
||||
# 创建 Context,传入 SharedServices
|
||||
context = StrategyContext(
|
||||
shared_services=self.shared_services, # ← 传入中间层
|
||||
instance_id=instance_config['instance_id'],
|
||||
instance_config=instance_config
|
||||
)
|
||||
return strategy_class(context=context)
|
||||
```
|
||||
|
||||
### 3.2 新设计
|
||||
|
||||
```python
|
||||
class StrategyManager:
|
||||
def __init__(
|
||||
self,
|
||||
config_dir: str,
|
||||
cache_manager: CacheManager,
|
||||
db_manager: Optional[DBManager] = None,
|
||||
enable_db_fallback: bool = False
|
||||
):
|
||||
"""
|
||||
初始化策略管理器
|
||||
|
||||
Args:
|
||||
config_dir: 策略配置目录
|
||||
cache_manager: 缓存管理器(共享实例)
|
||||
db_manager: 数据库管理器(共享实例,可选)
|
||||
enable_db_fallback: 是否启用数据库降级
|
||||
"""
|
||||
self.config_dir = config_dir
|
||||
|
||||
# 直接持有共享资源
|
||||
self._cache_manager = cache_manager
|
||||
self._db_manager = db_manager
|
||||
self._enable_db_fallback = enable_db_fallback
|
||||
|
||||
self.strategies = {}
|
||||
self._load_strategies()
|
||||
|
||||
def _create_strategy_instance(
|
||||
self,
|
||||
strategy_class: Type[BaseStrategy],
|
||||
instance_config: dict
|
||||
) -> BaseStrategy:
|
||||
"""
|
||||
创建策略实例
|
||||
|
||||
Args:
|
||||
strategy_class: 策略类
|
||||
instance_config: 实例配置
|
||||
|
||||
Returns:
|
||||
策略实例
|
||||
"""
|
||||
# 创建 Context,直接传入共享资源
|
||||
context = StrategyContext(
|
||||
cache_manager=self._cache_manager, # ← 传入共享实例
|
||||
db_manager=self._db_manager, # ← 传入共享实例
|
||||
instance_id=instance_config['instance_id'],
|
||||
symbol=instance_config['symbol'],
|
||||
instance_config=instance_config,
|
||||
enable_db_fallback=self._enable_db_fallback
|
||||
)
|
||||
|
||||
# 创建策略实例
|
||||
strategy = strategy_class(
|
||||
context=context,
|
||||
**instance_config.get('params', {})
|
||||
)
|
||||
|
||||
return strategy
|
||||
```
|
||||
|
||||
**变化**:
|
||||
- ✅ 不再需要 SharedServices 参数
|
||||
- ✅ 直接接收 cache_manager 和 db_manager
|
||||
- ✅ 创建 Context 时直接传入共享资源
|
||||
|
||||
---
|
||||
|
||||
## 4. 服务器启动代码
|
||||
|
||||
### 4.1 原设计(三层)
|
||||
|
||||
```python
|
||||
def start_server(host, port, config_path):
|
||||
# 1. 初始化组件
|
||||
db_manager = DBManager(...)
|
||||
cache_manager = CacheManager(...)
|
||||
|
||||
# 2. 预加载
|
||||
preload_cache_data(db_manager, cache_manager, config)
|
||||
|
||||
# 3. 创建 SharedServices(中间层)
|
||||
shared_services = SharedServices(
|
||||
cache_manager=cache_manager,
|
||||
db_manager=db_manager,
|
||||
enable_db_fallback=False
|
||||
)
|
||||
|
||||
# 4. 创建 StrategyManager
|
||||
strategy_manager = StrategyManager(
|
||||
config_dir='config/strategies',
|
||||
shared_services=shared_services # ← 传入中间层
|
||||
)
|
||||
|
||||
# ...
|
||||
```
|
||||
|
||||
### 4.2 新设计(两层)
|
||||
|
||||
```python
|
||||
def start_server(host, port, config_path):
|
||||
"""启动服务器"""
|
||||
|
||||
# 1. 加载配置
|
||||
config = load_config(config_path)
|
||||
|
||||
# 2. 初始化数据库
|
||||
db_manager = DBManager(config['database'])
|
||||
|
||||
# 3. 初始化缓存
|
||||
cache_manager = CacheManager(config['cache'])
|
||||
|
||||
# 4. 预加载数据
|
||||
logger.info("Preloading data from database...")
|
||||
preload_cache_data(
|
||||
db_manager=db_manager,
|
||||
cache_manager=cache_manager,
|
||||
config=config
|
||||
)
|
||||
logger.info("Preload completed")
|
||||
|
||||
# 5. 创建策略管理器(直接传入共享资源)
|
||||
strategy_manager = StrategyManager(
|
||||
config_dir='config/strategies',
|
||||
cache_manager=cache_manager, # ← 直接传入
|
||||
db_manager=db_manager, # ← 直接传入
|
||||
enable_db_fallback=config['cache'].get('fallback', {}).get('enabled', False)
|
||||
)
|
||||
|
||||
logger.info(f"Loaded {len(strategy_manager.strategies)} strategy instances")
|
||||
|
||||
# 6. 注册关闭钩子
|
||||
def on_shutdown():
|
||||
logger.info("Server shutting down...")
|
||||
|
||||
# 可选:保存缓存到数据库
|
||||
if config['cache'].get('persist_on_shutdown', False):
|
||||
save_cache_to_database(cache_manager, db_manager)
|
||||
|
||||
# 关闭数据库连接
|
||||
db_manager.close()
|
||||
logger.info("Shutdown completed")
|
||||
|
||||
signal.signal(signal.SIGTERM, lambda s, f: on_shutdown())
|
||||
signal.signal(signal.SIGINT, lambda s, f: on_shutdown())
|
||||
|
||||
# 7. 创建 WebSocket 服务器
|
||||
ws_server = WebSocketServer(
|
||||
strategy_manager=strategy_manager,
|
||||
config=config['websocket']
|
||||
)
|
||||
|
||||
# 8. 启动服务器
|
||||
logger.info(f"Starting server on {host}:{port}")
|
||||
ws_server.start(host, port)
|
||||
```
|
||||
|
||||
**变化**:
|
||||
- ✅ 不再创建 SharedServices
|
||||
- ✅ 直接将 cache_manager 和 db_manager 传给 StrategyManager
|
||||
- ✅ 代码更简洁
|
||||
|
||||
---
|
||||
|
||||
## 5. 策略使用示例
|
||||
|
||||
### 5.1 原设计
|
||||
|
||||
```python
|
||||
class MAStrategy(BaseStrategy):
|
||||
def compute(self, kline_data):
|
||||
# 通过 context 访问数据
|
||||
# 但 context 内部需要委托给 _shared
|
||||
history = self.context.get_klines(
|
||||
symbol=self.context.symbol,
|
||||
period='1m',
|
||||
last_n=100
|
||||
)
|
||||
|
||||
# Context 内部实现:
|
||||
# def get_klines(self, ...):
|
||||
# return self._shared.get_klines(...) # 多一层
|
||||
```
|
||||
|
||||
### 5.2 新设计
|
||||
|
||||
```python
|
||||
class MAStrategy(BaseStrategy):
|
||||
def compute(self, kline_data):
|
||||
# 直接通过 context 访问数据
|
||||
history = self.context.get_klines(
|
||||
symbol=self.context.symbol,
|
||||
period='1m',
|
||||
last_n=100
|
||||
)
|
||||
|
||||
# Context 内部直接实现:
|
||||
# def get_klines(self, ...):
|
||||
# return self._cache_manager.get_klines_range(...) # 直接访问
|
||||
|
||||
# 使用简化:symbol 默认为 context.symbol
|
||||
history = self.context.get_klines(period='1m', last_n=100)
|
||||
|
||||
# 访问独立状态
|
||||
position = self.context.get_position()
|
||||
capital = self.context.get_capital()
|
||||
|
||||
# 计算信号
|
||||
if len(history) >= 100:
|
||||
ma = history['close'].rolling(20).mean()
|
||||
if history['close'].iloc[-1] > ma.iloc[-1]:
|
||||
return 'BUY'
|
||||
|
||||
return 'HOLD'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 对比总结
|
||||
|
||||
### 6.1 架构层次对比
|
||||
|
||||
| 方面 | 原设计(三层) | 新设计(两层) |
|
||||
| ---------------- | ------------------------------------------- | ------------------------------- |
|
||||
| **层次结构** | Strategy → Context → SharedServices → Cache | Strategy → Context → Cache |
|
||||
| **中间层** | SharedServices | ❌ 无 |
|
||||
| **Context 职责** | 持有独立状态 + 委托数据访问 | 持有独立状态 + 直接实现数据访问 |
|
||||
| **代码调用** | `context._shared.get_klines()` | `context.get_klines()` |
|
||||
| **复杂度** | 高(多一层) | 低(减少一层) |
|
||||
|
||||
### 6.2 优缺点对比
|
||||
|
||||
#### 原设计(三层)
|
||||
|
||||
**优点**:
|
||||
- ✅ 明确区分"共享资源"和"独立状态"
|
||||
- ✅ SharedServices 可以单独测试
|
||||
|
||||
**缺点**:
|
||||
- ❌ 多了一层间接性
|
||||
- ❌ Context 需要委托所有数据访问方法
|
||||
- ❌ 代码冗余(SharedServices 和 Context 都有 get_klines)
|
||||
- ❌ 理解成本高(为什么需要 SharedServices?)
|
||||
|
||||
#### 新设计(两层)
|
||||
|
||||
**优点**:
|
||||
- ✅ **减少一层间接性**
|
||||
- ✅ **Context 直接实现所有方法,无需委托**
|
||||
- ✅ **代码更简洁直观**
|
||||
- ✅ **符合"Context 是策略的唯一接口"理念**
|
||||
- ✅ **共享机制依然存在(传入同一个实例)**
|
||||
|
||||
**缺点**:
|
||||
- ⚠️ Context 的职责略微增加(数据访问 + 状态管理)
|
||||
- 但这是合理的!Context 本来就应该是策略的"环境"
|
||||
|
||||
### 6.3 共享机制对比
|
||||
|
||||
两种设计的共享机制**本质相同**:
|
||||
|
||||
| 方面 | 原设计 | 新设计 |
|
||||
| ------------ | --------------------------- | --------------------------- |
|
||||
| **共享方式** | 传入 SharedServices 实例 | 传入 cache_manager 实例 |
|
||||
| **是否共享** | ✅ 是(SharedServices 单例) | ✅ 是(cache_manager 单例) |
|
||||
| **内存占用** | 每个 Context 8 字节(引用) | 每个 Context 8 字节(引用) |
|
||||
| **并发安全** | 取决于 CacheManager | 取决于 CacheManager |
|
||||
|
||||
**结论**:新设计依然是共享的,只是少了一层包装。
|
||||
|
||||
---
|
||||
|
||||
## 7. 实现检查清单
|
||||
|
||||
### 7.1 需要修改的文件
|
||||
|
||||
| 文件 | 修改内容 | 说明 |
|
||||
| --------------------------------- | ------------ | -------------------------------------- |
|
||||
| `src/core/strategy_context.py` | 重新实现 | 直接提供数据访问方法 |
|
||||
| `src/strategy_manager.py` | 修改参数 | 接收 cache_manager 而非 SharedServices |
|
||||
| `src/qtrade_server.py` | 简化启动逻辑 | 不创建 SharedServices |
|
||||
| ~~`src/core/shared_services.py`~~ | ❌ 删除 | 不再需要 |
|
||||
|
||||
### 7.2 StrategyContext 需要实现的方法
|
||||
|
||||
**数据访问方法**:
|
||||
```python
|
||||
def get_klines(self, symbol, period, last_n, start, end) -> DataFrame
|
||||
def get_indicators(self, symbol, period, indicator_type) -> DataFrame
|
||||
def _load_from_database(self, ...) -> DataFrame # 私有
|
||||
```
|
||||
|
||||
**状态访问方法**:
|
||||
```python
|
||||
def get_position(self) -> Position
|
||||
def get_capital(self) -> Capital
|
||||
def get_risk_state(self) -> RiskState
|
||||
def update_position(self, shares, cost)
|
||||
def update_capital(self, cash_change)
|
||||
```
|
||||
|
||||
**工具方法**:
|
||||
```python
|
||||
def get_cache_info(self, symbol, period) -> dict
|
||||
```
|
||||
|
||||
### 7.3 StrategyManager 需要的修改
|
||||
|
||||
```python
|
||||
# 修改构造函数签名
|
||||
def __init__(
|
||||
self,
|
||||
config_dir: str,
|
||||
cache_manager: CacheManager, # 新增
|
||||
db_manager: DBManager = None, # 新增
|
||||
enable_db_fallback: bool = False # 新增
|
||||
):
|
||||
# 不再接收 shared_services
|
||||
pass
|
||||
|
||||
# 修改创建 Context 的逻辑
|
||||
def _create_strategy_instance(self, strategy_class, instance_config):
|
||||
context = StrategyContext(
|
||||
cache_manager=self._cache_manager, # 直接传入
|
||||
db_manager=self._db_manager,
|
||||
instance_id=instance_config['instance_id'],
|
||||
symbol=instance_config['symbol'],
|
||||
instance_config=instance_config,
|
||||
enable_db_fallback=self._enable_db_fallback
|
||||
)
|
||||
return strategy_class(context=context, ...)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. 设计原则验证
|
||||
|
||||
### 8.1 是否违反设计原则?
|
||||
|
||||
| 原则 | 原设计 | 新设计 | 说明 |
|
||||
| ------------ | ------ | ------ | ----------------------------------------- |
|
||||
| **单一职责** | ✅ 符合 | ✅ 符合 | Context 职责是"提供策略运行环境" |
|
||||
| **接口隔离** | ✅ 符合 | ✅ 符合 | 策略只依赖 Context 接口 |
|
||||
| **依赖倒置** | ✅ 符合 | ✅ 符合 | 依赖抽象(Context),不依赖实现 |
|
||||
| **最少知识** | ⚠️ 一般 | ✅ 更好 | 策略只知道 Context,不知道 SharedServices |
|
||||
| **简洁性** | ⚠️ 复杂 | ✅ 简洁 | 减少一层间接性 |
|
||||
|
||||
### 8.2 Context 的职责是否过重?
|
||||
|
||||
**Context 的职责**:
|
||||
1. 提供数据访问接口(get_klines, get_indicators)
|
||||
2. 管理独立状态(Position, Capital, RiskState)
|
||||
3. 封装降级逻辑(可选)
|
||||
|
||||
**分析**:
|
||||
- ✅ 这些都是"策略运行环境"的一部分
|
||||
- ✅ 符合 Context 的定义
|
||||
- ✅ 职责清晰,内聚性高
|
||||
|
||||
**类比**:
|
||||
```
|
||||
HttpRequest (Web 框架中的 Context)
|
||||
├── get_parameter() ← 获取请求参数
|
||||
├── get_header() ← 获取请求头
|
||||
├── get_session() ← 获取会话
|
||||
└── get_cookie() ← 获取 Cookie
|
||||
|
||||
StrategyContext (交易系统中的 Context)
|
||||
├── get_klines() ← 获取K线数据
|
||||
├── get_indicators() ← 获取指标数据
|
||||
├── get_position() ← 获取持仓
|
||||
└── get_capital() ← 获取资金
|
||||
```
|
||||
|
||||
**结论**:Context 的职责不算过重,这是合理的封装。
|
||||
|
||||
---
|
||||
|
||||
## 9. 最终设计
|
||||
|
||||
### 9.1 架构图
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ QTradeServer │
|
||||
│ │
|
||||
│ 1. 初始化 cache_manager (单例) │
|
||||
│ 2. 初始化 db_manager (单例) │
|
||||
│ 3. 预加载数据 │
|
||||
│ 4. 创建 StrategyManager │
|
||||
│ ↓ │
|
||||
│ 传入 cache_manager, db_manager │
|
||||
└──────────────────┬──────────────────────┘
|
||||
│
|
||||
↓
|
||||
┌─────────────────────────────────────────┐
|
||||
│ StrategyManager │
|
||||
│ │
|
||||
│ 持有: cache_manager, db_manager │
|
||||
│ │
|
||||
│ 创建多个 StrategyContext: │
|
||||
│ context1 = StrategyContext( │
|
||||
│ cache_manager, ← 共享实例 │
|
||||
│ db_manager, ← 共享实例 │
|
||||
│ instance_id='debug_000001' │
|
||||
│ ) │
|
||||
│ context2 = StrategyContext( │
|
||||
│ cache_manager, ← 同一个实例 │
|
||||
│ db_manager, ← 同一个实例 │
|
||||
│ instance_id='debug_600000' │
|
||||
│ ) │
|
||||
└──────────────────┬──────────────────────┘
|
||||
│
|
||||
↓
|
||||
┌─────────────────────────────────────────┐
|
||||
│ StrategyContext │
|
||||
│ │
|
||||
│ 私有成员: │
|
||||
│ _cache_manager (共享引用) │
|
||||
│ _db_manager (共享引用) │
|
||||
│ │
|
||||
│ 独立状态: │
|
||||
│ _position │
|
||||
│ _capital │
|
||||
│ _risk_state │
|
||||
│ │
|
||||
│ 公开方法: │
|
||||
│ get_klines() ← 直接实现 │
|
||||
│ get_indicators() ← 直接实现 │
|
||||
│ get_position() │
|
||||
│ get_capital() │
|
||||
└──────────────────┬──────────────────────┘
|
||||
│
|
||||
↓
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Strategy │
|
||||
│ │
|
||||
│ def compute(self, kline_data): │
|
||||
│ history = self.context.get_klines()│
|
||||
│ position = self.context.get_position()│
|
||||
│ # ... │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 9.2 数据流
|
||||
|
||||
```
|
||||
Strategy 请求数据
|
||||
↓
|
||||
context.get_klines(symbol, period, last_n)
|
||||
↓
|
||||
Context 内部逻辑:
|
||||
1. df = self._cache_manager.get_klines_range(...)
|
||||
2. if df is None and self._enable_db_fallback:
|
||||
df = self._load_from_database(...)
|
||||
self._cache_manager.set_klines(...)
|
||||
3. return df
|
||||
↓
|
||||
返回 DataFrame 给策略
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. 总结
|
||||
|
||||
### 10.1 用户观点的正确性
|
||||
|
||||
✅ **用户观点完全正确**:
|
||||
|
||||
1. **"不用封装这么多层"**
|
||||
- ✅ 正确!SharedServices 是多余的中间层
|
||||
- ✅ 直接在 Context 上实现更简洁
|
||||
|
||||
2. **"可以直接变为 context 的方法"**
|
||||
- ✅ 完全正确!Context 本来就应该是策略的唯一接口
|
||||
- ✅ 数据访问方法属于 Context 的职责范畴
|
||||
|
||||
3. **"是不是更好?"**
|
||||
- ✅ 确实更好!代码更简洁、理解更容易、维护更方便
|
||||
|
||||
### 10.2 关键设计点
|
||||
|
||||
| 设计点 | 说明 |
|
||||
| ------------ | -------------------------------------------------- |
|
||||
| **共享机制** | 通过传入同一个实例实现共享,而非创建中间层 |
|
||||
| **接口位置** | 数据访问方法直接在 Context 上实现 |
|
||||
| **降级逻辑** | 封装在 Context 内部,对策略透明 |
|
||||
| **独立状态** | 每个 Context 有独立的 Position、Capital、RiskState |
|
||||
| **架构层次** | Strategy → Context → CacheManager(两层) |
|
||||
|
||||
### 10.3 实现步骤
|
||||
|
||||
1. **重新实现 StrategyContext**
|
||||
- 直接持有 cache_manager 和 db_manager(私有)
|
||||
- 实现 get_klines()、get_indicators() 等方法
|
||||
- 封装降级逻辑
|
||||
|
||||
2. **修改 StrategyManager**
|
||||
- 接收 cache_manager 和 db_manager 参数
|
||||
- 创建 Context 时直接传入共享资源
|
||||
|
||||
3. **简化 qtrade_server.py**
|
||||
- 不创建 SharedServices
|
||||
- 直接将共享资源传给 StrategyManager
|
||||
|
||||
4. **删除 shared_services.py**
|
||||
- 不再需要这个文件
|
||||
|
||||
---
|
||||
|
||||
**最终结论**:
|
||||
新设计更简洁、更直观,减少了不必要的中间层,同时依然保持了共享机制和良好的封装性。这是一个更好的设计!
|
||||
1529
docs/tech_designs/qtrade_server_cache_design.md
Normal file
1529
docs/tech_designs/qtrade_server_cache_design.md
Normal file
File diff suppressed because it is too large
Load Diff
852
docs/tech_designs/shared_services_interface_minimization.md
Normal file
852
docs/tech_designs/shared_services_interface_minimization.md
Normal file
@ -0,0 +1,852 @@
|
||||
# SharedServices 接口最小化设计
|
||||
|
||||
> **核心问题**: SharedServices 是否需要暴露 DBManager、DataService 等底层能力?
|
||||
> **用户观点**: 策略只需要获取数据,数据库操作应该在服务器启动/关闭时完成
|
||||
> **日期**: 2025-12-27
|
||||
> **结论**: ✅ 正确!应该最小化暴露的接口
|
||||
|
||||
---
|
||||
|
||||
## 1. 问题分析
|
||||
|
||||
### 1.1 当前设计的问题
|
||||
|
||||
```python
|
||||
class SharedServices:
|
||||
"""当前设计(过度暴露)"""
|
||||
|
||||
def __init__(self, cache_manager, db_manager, config, data_service):
|
||||
self.cache_manager = cache_manager # ❌ 暴露了
|
||||
self.db_manager = db_manager # ❌ 暴露了
|
||||
self.config = config # ❌ 暴露了
|
||||
self.data_service = data_service # ❌ 暴露了
|
||||
```
|
||||
|
||||
**问题**:
|
||||
1. **过度暴露内部实现**:策略可以直接访问 `cache_manager`, `db_manager`
|
||||
2. **违反封装原则**:策略知道了不该知道的细节
|
||||
3. **增加耦合**:策略依赖了底层实现
|
||||
4. **难以重构**:改变内部实现需要修改所有使用的地方
|
||||
|
||||
### 1.2 策略真正需要什么?
|
||||
|
||||
让我们分析策略的实际需求:
|
||||
|
||||
```python
|
||||
class MAStrategy:
|
||||
"""一个典型的策略需要什么?"""
|
||||
|
||||
def compute(self, kline_data):
|
||||
# 需求1: 获取历史K线数据
|
||||
history = ??? # 策略只想要数据,不关心从哪来
|
||||
|
||||
# 需求2: 获取指标数据(可选)
|
||||
macd = ???
|
||||
|
||||
# 需求3: 查询持仓(独立状态,不在这里讨论)
|
||||
position = self.context.get_position()
|
||||
|
||||
# 需求4: 策略参数(独立配置,不在这里讨论)
|
||||
ma_period = self.params['ma_period']
|
||||
|
||||
# 策略不需要:
|
||||
# ❌ 直接访问数据库
|
||||
# ❌ 知道缓存的存在
|
||||
# ❌ 知道数据从哪来
|
||||
# ❌ 管理连接池
|
||||
```
|
||||
|
||||
**结论**:策略只需要两个数据访问接口:
|
||||
1. `get_klines(symbol, period, last_n)` → 返回 DataFrame
|
||||
2. `get_indicators(symbol, period, type)` → 返回 DataFrame
|
||||
|
||||
---
|
||||
|
||||
## 2. 数据流分析
|
||||
|
||||
### 2.1 服务器启动阶段
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ 服务器启动流程 │
|
||||
└─────────────────────────────────────────────────┘
|
||||
|
||||
1. 加载配置
|
||||
config = load_config('global_config.yaml')
|
||||
|
||||
2. 初始化数据库连接
|
||||
db_manager = DBManager(config['database'])
|
||||
|
||||
3. 初始化缓存
|
||||
cache_manager = CacheManager(config['cache'])
|
||||
|
||||
4. 预加载数据(核心操作)
|
||||
┌────────────────────────────────────────┐
|
||||
│ 从数据库批量加载历史数据到缓存 │
|
||||
│ │
|
||||
│ for each symbol in symbols: │
|
||||
│ for each period in periods: │
|
||||
│ df = db_manager.load_klines(...) │ ← 数据库操作
|
||||
│ cache_manager.set(...) │ ← 填充缓存
|
||||
└────────────────────────────────────────┘
|
||||
|
||||
5. 创建 SharedServices
|
||||
shared = SharedServices(cache_manager) ← 只传缓存!
|
||||
|
||||
✅ 此时缓存已经预加载完毕
|
||||
✅ 策略运行时不需要访问数据库
|
||||
✅ DBManager 可以关闭或保持在服务器层面
|
||||
|
||||
6. 启动策略管理器
|
||||
strategy_manager = StrategyManager(shared)
|
||||
|
||||
7. 启动 WebSocket 服务器
|
||||
```
|
||||
|
||||
**关键点**:
|
||||
- ✅ **数据库操作只在启动时发生**
|
||||
- ✅ **预加载后,策略只访问缓存**
|
||||
- ✅ **DBManager 不需要传给 SharedServices**
|
||||
|
||||
### 2.2 服务器运行阶段
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ 实时数据处理 │
|
||||
└─────────────────────────────────────────────────┘
|
||||
|
||||
1. 新K线数据到达
|
||||
WebSocket 收到: {symbol, timestamp, OHLCV}
|
||||
|
||||
2. 追加到缓存
|
||||
cache_manager.append_kline(...)
|
||||
|
||||
✅ 只操作缓存,不涉及数据库
|
||||
|
||||
3. 分发到策略
|
||||
signals = strategy_manager.dispatch_kline(...)
|
||||
|
||||
策略内部:
|
||||
history = context.get_klines(...) ← 从缓存读取
|
||||
|
||||
✅ 策略完全不知道数据库的存在
|
||||
|
||||
4. 返回信号
|
||||
return signals
|
||||
```
|
||||
|
||||
**关键点**:
|
||||
- ✅ **运行时只操作缓存**
|
||||
- ✅ **策略不需要访问数据库**
|
||||
- ✅ **数据库连接可以关闭(如果需要节省资源)**
|
||||
|
||||
### 2.3 服务器关闭阶段
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ 优雅关闭流程 │
|
||||
└─────────────────────────────────────────────────┘
|
||||
|
||||
1. 接收关闭信号
|
||||
SIGTERM / Ctrl+C
|
||||
|
||||
2. 停止接收新数据
|
||||
ws_server.stop()
|
||||
|
||||
3. 保存缓存到数据库(可选)
|
||||
┌────────────────────────────────────────┐
|
||||
│ 如果需要持久化缓存的更新数据: │
|
||||
│ │
|
||||
│ for key, data in cache_manager.items():│
|
||||
│ db_manager.save_klines(...) │ ← 数据库写入
|
||||
└────────────────────────────────────────┘
|
||||
|
||||
或者
|
||||
┌────────────────────────────────────────┐
|
||||
│ 如果不需要持久化: │
|
||||
│ 直接丢弃缓存 │
|
||||
│ 下次启动重新从数据库加载 │
|
||||
└────────────────────────────────────────┘
|
||||
|
||||
4. 关闭数据库连接
|
||||
db_manager.close()
|
||||
|
||||
5. 退出
|
||||
```
|
||||
|
||||
**关键点**:
|
||||
- ✅ **保存缓存是服务器的职责,不是策略的职责**
|
||||
- ✅ **策略根本不参与关闭流程**
|
||||
|
||||
### 2.4 缓存未命中降级(可选功能)
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ 缓存未命中处理 │
|
||||
└─────────────────────────────────────────────────┘
|
||||
|
||||
场景:策略请求的数据不在缓存中
|
||||
|
||||
策略调用:
|
||||
df = context.get_klines('000001.SZ', '1m', last_n=100)
|
||||
|
||||
SharedServices 内部:
|
||||
def get_klines(self, symbol, period, last_n):
|
||||
# 1. 先从缓存取
|
||||
df = self._cache_manager.get_klines_range(...)
|
||||
|
||||
# 2. 缓存命中,直接返回
|
||||
if df is not None and len(df) >= last_n:
|
||||
return df
|
||||
|
||||
# 3. 缓存未命中,降级到数据库(可选)
|
||||
if self._enable_db_fallback:
|
||||
df = self._db_manager.load_klines(...) ← 降级逻辑
|
||||
# 加载后填充缓存
|
||||
self._cache_manager.set_klines(...)
|
||||
return df
|
||||
|
||||
# 4. 不允许降级,返回 None
|
||||
return None
|
||||
|
||||
策略看到的:
|
||||
df = context.get_klines(...)
|
||||
# 策略完全不知道数据从缓存来还是数据库来
|
||||
# 这是封装!
|
||||
```
|
||||
|
||||
**关键点**:
|
||||
- ✅ **降级逻辑封装在 SharedServices 内部**
|
||||
- ✅ **策略不需要知道降级的存在**
|
||||
- ✅ **DBManager 是 SharedServices 的私有成员**
|
||||
|
||||
---
|
||||
|
||||
## 3. 推荐设计:最小化接口
|
||||
|
||||
### 3.1 新设计方案
|
||||
|
||||
```python
|
||||
class SharedServices:
|
||||
"""
|
||||
共享服务(最小化接口)
|
||||
|
||||
设计原则:
|
||||
1. 只暴露策略真正需要的接口
|
||||
2. 隐藏所有实现细节
|
||||
3. 封装降级逻辑
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cache_manager: CacheManager,
|
||||
db_manager: Optional[DBManager] = None, # 可选,用于降级
|
||||
enable_db_fallback: bool = False # 是否启用降级
|
||||
):
|
||||
"""
|
||||
初始化共享服务
|
||||
|
||||
Args:
|
||||
cache_manager: 缓存管理器(必需)
|
||||
db_manager: 数据库管理器(可选,用于降级)
|
||||
enable_db_fallback: 是否启用数据库降级
|
||||
"""
|
||||
# ✅ 私有成员:策略无法直接访问
|
||||
self._cache_manager = cache_manager
|
||||
self._db_manager = db_manager
|
||||
self._enable_db_fallback = enable_db_fallback
|
||||
|
||||
# ==================== 公开接口(最小化) ====================
|
||||
|
||||
def get_klines(
|
||||
self,
|
||||
symbol: str,
|
||||
period: str,
|
||||
last_n: Optional[int] = None,
|
||||
start: Optional[pd.Timestamp] = None,
|
||||
end: Optional[pd.Timestamp] = None
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
获取K线数据(唯一的数据访问接口)
|
||||
|
||||
这是策略唯一需要的接口!
|
||||
|
||||
Args:
|
||||
symbol: 标的代码
|
||||
period: 周期
|
||||
last_n: 最近N条
|
||||
start: 开始时间(可选)
|
||||
end: 结束时间(可选)
|
||||
|
||||
Returns:
|
||||
K线DataFrame,如果不存在返回None
|
||||
|
||||
内部逻辑:
|
||||
1. 优先从缓存读取
|
||||
2. 缓存未命中且启用降级,从数据库读取
|
||||
3. 读取后自动填充缓存
|
||||
4. 策略完全不知道这些细节
|
||||
"""
|
||||
# 1. 从缓存读取
|
||||
df = self._cache_manager.get_klines_range(
|
||||
symbol, period, last_n=last_n, start=start, end=end
|
||||
)
|
||||
|
||||
# 2. 缓存命中
|
||||
if df is not None and not df.empty:
|
||||
if last_n is None or len(df) >= last_n:
|
||||
return df
|
||||
|
||||
# 3. 缓存未命中,尝试降级
|
||||
if self._enable_db_fallback and self._db_manager:
|
||||
logger.warning(f"Cache miss: {symbol}_{period}, loading from database")
|
||||
df = self._load_from_database(symbol, period, last_n, start, end)
|
||||
|
||||
# 加载后填充缓存
|
||||
if df is not None and not df.empty:
|
||||
self._cache_manager.set_klines(symbol, period, {'klines': df})
|
||||
|
||||
return df
|
||||
|
||||
# 4. 无降级或降级失败
|
||||
return None
|
||||
|
||||
def get_indicators(
|
||||
self,
|
||||
symbol: str,
|
||||
period: str,
|
||||
indicator_type: str
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
获取指标数据(第二个公开接口)
|
||||
|
||||
Args:
|
||||
symbol: 标的代码
|
||||
period: 周期
|
||||
indicator_type: 指标类型(如 'MACD', 'KDJ')
|
||||
|
||||
Returns:
|
||||
指标DataFrame,如果不存在返回None
|
||||
"""
|
||||
# 只从缓存读取指标
|
||||
# 指标由指标计算器提前计算好放入缓存
|
||||
return self._cache_manager.get_indicator(symbol, period, indicator_type)
|
||||
|
||||
# ==================== 私有方法(策略无法访问) ====================
|
||||
|
||||
def _load_from_database(
|
||||
self,
|
||||
symbol: str,
|
||||
period: str,
|
||||
last_n: Optional[int],
|
||||
start: Optional[pd.Timestamp],
|
||||
end: Optional[pd.Timestamp]
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
从数据库加载数据(私有方法)
|
||||
|
||||
策略无法直接调用此方法
|
||||
"""
|
||||
if not self._db_manager:
|
||||
return None
|
||||
|
||||
try:
|
||||
# 构造查询参数
|
||||
if last_n:
|
||||
# 获取最近N条
|
||||
df = self._db_manager.load_klines_last_n(symbol, period, last_n)
|
||||
else:
|
||||
# 获取时间范围
|
||||
df = self._db_manager.load_klines_range(symbol, period, start, end)
|
||||
|
||||
return df
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load from database: {e}")
|
||||
return None
|
||||
|
||||
# ==================== 工具方法(可选) ====================
|
||||
|
||||
def get_cache_stats(self) -> dict:
|
||||
"""
|
||||
获取缓存统计信息(用于监控)
|
||||
|
||||
这不是策略需要的,是服务器管理需要的
|
||||
"""
|
||||
return self._cache_manager.get_stats()
|
||||
```
|
||||
|
||||
### 3.2 对比:接口暴露
|
||||
|
||||
| 设计 | 暴露的接口 | 策略可以访问 | 问题 |
|
||||
| ---------- | ------------------------------------------------------- | ------------ | ---------- |
|
||||
| **原设计** | `cache_manager`, `db_manager`, `config`, `data_service` | 所有底层组件 | ❌ 过度暴露 |
|
||||
| **新设计** | `get_klines()`, `get_indicators()` | 只有数据接口 | ✅ 最小化 |
|
||||
|
||||
```python
|
||||
# ❌ 原设计:策略可以直接访问底层
|
||||
shared.cache_manager.get(...) # 不应该暴露
|
||||
shared.db_manager.query(...) # 不应该暴露
|
||||
shared.config['database']['host'] # 不应该暴露
|
||||
|
||||
# ✅ 新设计:策略只能访问高层接口
|
||||
shared.get_klines(...) # 唯一方式
|
||||
shared.get_indicators(...) # 唯一方式
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 数据库操作的职责划分
|
||||
|
||||
### 4.1 谁负责数据库操作?
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ 数据库操作职责 │
|
||||
└─────────────────────────────────────────────────┘
|
||||
|
||||
操作类型 负责者 时机
|
||||
─────────────────────────────────────────────────
|
||||
预加载历史数据 QTradeServer 启动时
|
||||
追加实时数据到缓存 QTradeServer 运行时
|
||||
保存缓存到数据库 QTradeServer 关闭时
|
||||
缓存未命中降级 SharedServices 运行时(可选)
|
||||
(内部私有逻辑)
|
||||
```
|
||||
|
||||
### 4.2 服务器启动时的数据库操作
|
||||
|
||||
```python
|
||||
# qtrade_server.py
|
||||
|
||||
def start_server(host, port, config_path):
|
||||
"""启动服务器"""
|
||||
|
||||
# 1. 加载配置
|
||||
config = load_config(config_path)
|
||||
|
||||
# 2. 初始化数据库(服务器级别)
|
||||
db_manager = DBManager(config['database'])
|
||||
|
||||
# 3. 初始化缓存
|
||||
cache_manager = CacheManager(config['cache'])
|
||||
|
||||
# 4. 预加载数据(服务器职责)
|
||||
logger.info("Preloading data from database...")
|
||||
preload_cache_data(
|
||||
db_manager=db_manager, # ← 服务器使用数据库
|
||||
cache_manager=cache_manager,
|
||||
config=config
|
||||
)
|
||||
logger.info("Preload completed")
|
||||
|
||||
# 5. 创建共享服务(只传缓存)
|
||||
shared_services = SharedServices(
|
||||
cache_manager=cache_manager,
|
||||
db_manager=db_manager, # ← 可选,用于降级
|
||||
enable_db_fallback=False # ← 默认禁用降级
|
||||
)
|
||||
|
||||
# 6. 初始化策略管理器
|
||||
strategy_manager = StrategyManager(
|
||||
config_dir="config/strategies",
|
||||
shared_services=shared_services
|
||||
)
|
||||
|
||||
# 7. 注册关闭钩子(服务器职责)
|
||||
def on_shutdown():
|
||||
logger.info("Server shutting down...")
|
||||
|
||||
# 可选:保存缓存到数据库
|
||||
if config['cache'].get('persist_on_shutdown', False):
|
||||
save_cache_to_database(cache_manager, db_manager)
|
||||
|
||||
# 关闭数据库连接
|
||||
db_manager.close()
|
||||
|
||||
logger.info("Shutdown completed")
|
||||
|
||||
signal.signal(signal.SIGTERM, lambda s, f: on_shutdown())
|
||||
signal.signal(signal.SIGINT, lambda s, f: on_shutdown())
|
||||
|
||||
# 8. 启动服务器
|
||||
ws_server = WebSocketServer(...)
|
||||
ws_server.start(host, port)
|
||||
```
|
||||
|
||||
**关键点**:
|
||||
- ✅ **数据库操作在服务器层面,不在策略层面**
|
||||
- ✅ **预加载和保存都是服务器的职责**
|
||||
- ✅ **策略完全不参与数据库操作**
|
||||
|
||||
### 4.3 预加载函数实现
|
||||
|
||||
```python
|
||||
def preload_cache_data(
|
||||
db_manager: DBManager,
|
||||
cache_manager: CacheManager,
|
||||
config: dict
|
||||
) -> None:
|
||||
"""
|
||||
预加载历史数据到缓存
|
||||
|
||||
这是服务器启动时的一次性操作
|
||||
|
||||
Args:
|
||||
db_manager: 数据库管理器
|
||||
cache_manager: 缓存管理器
|
||||
config: 全局配置
|
||||
"""
|
||||
preload_config = config['cache']['preload']
|
||||
|
||||
if not preload_config['enabled']:
|
||||
logger.info("Preload disabled, skipping")
|
||||
return
|
||||
|
||||
# 解析配置
|
||||
time_range = parse_time_range(preload_config['time_range'])
|
||||
periods = preload_config['periods']
|
||||
|
||||
# 计算时间范围
|
||||
end_date = datetime.now()
|
||||
start_date = end_date - time_range
|
||||
|
||||
# 收集需要预加载的symbols
|
||||
symbols = collect_symbols_from_strategy_configs(config['strategy_configs_dir'])
|
||||
|
||||
logger.info(f"Preloading {len(symbols)} symbols, {len(periods)} periods")
|
||||
logger.info(f"Time range: {start_date} ~ {end_date}")
|
||||
|
||||
# 批量加载
|
||||
success_count = 0
|
||||
fail_count = 0
|
||||
|
||||
for symbol in symbols:
|
||||
for period in periods:
|
||||
try:
|
||||
# 从数据库加载
|
||||
df = db_manager.load_klines_range(
|
||||
symbol=symbol,
|
||||
period=period,
|
||||
start=start_date,
|
||||
end=end_date
|
||||
)
|
||||
|
||||
if df is not None and not df.empty:
|
||||
# 填充缓存
|
||||
cache_manager.set_klines(symbol, period, {'klines': df})
|
||||
logger.info(f"✓ Preloaded {symbol}_{period}: {len(df)} rows")
|
||||
success_count += 1
|
||||
else:
|
||||
logger.warning(f"No data for {symbol}_{period}")
|
||||
fail_count += 1
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to preload {symbol}_{period}: {e}")
|
||||
fail_count += 1
|
||||
|
||||
logger.info(f"Preload summary: {success_count} success, {fail_count} failed")
|
||||
```
|
||||
|
||||
### 4.4 保存缓存函数实现(可选)
|
||||
|
||||
```python
|
||||
def save_cache_to_database(
|
||||
cache_manager: CacheManager,
|
||||
db_manager: DBManager
|
||||
) -> None:
|
||||
"""
|
||||
保存缓存数据到数据库
|
||||
|
||||
这是服务器关闭时的操作(可选)
|
||||
|
||||
Args:
|
||||
cache_manager: 缓存管理器
|
||||
db_manager: 数据库管理器
|
||||
"""
|
||||
logger.info("Saving cache to database...")
|
||||
|
||||
stats = cache_manager.get_stats()
|
||||
total = stats['size']
|
||||
saved = 0
|
||||
|
||||
# 遍历所有缓存项
|
||||
for key in cache_manager.keys():
|
||||
try:
|
||||
symbol, period = key.split('_', 1)
|
||||
df = cache_manager.get_klines(symbol, period)
|
||||
|
||||
if df is not None and not df.empty:
|
||||
# 保存到数据库
|
||||
db_manager.save_klines(symbol, period, df)
|
||||
saved += 1
|
||||
logger.debug(f"✓ Saved {key}: {len(df)} rows")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to save {key}: {e}")
|
||||
|
||||
logger.info(f"Save completed: {saved}/{total}")
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 是否需要降级逻辑?
|
||||
|
||||
### 5.1 两种模式对比
|
||||
|
||||
#### 模式A:纯缓存模式(推荐用于实盘)
|
||||
|
||||
```python
|
||||
# 配置
|
||||
cache:
|
||||
preload:
|
||||
enabled: true
|
||||
time_range: "3M"
|
||||
|
||||
shared_services = SharedServices(
|
||||
cache_manager=cache_manager,
|
||||
db_manager=None, # ← 不传数据库
|
||||
enable_db_fallback=False # ← 禁用降级
|
||||
)
|
||||
|
||||
# 特点
|
||||
✅ 启动时预加载足够的历史数据
|
||||
✅ 运行时只访问缓存,性能最优
|
||||
✅ 缓存未命中返回 None,策略处理
|
||||
❌ 如果缓存数据不足,策略无法获取
|
||||
```
|
||||
|
||||
**适用场景**:
|
||||
- 实盘交易:预加载3个月数据已足够
|
||||
- 性能敏感:不希望运行时访问数据库
|
||||
- 简单部署:不需要保持数据库连接
|
||||
|
||||
#### 模式B:缓存+降级模式(推荐用于开发)
|
||||
|
||||
```python
|
||||
# 配置
|
||||
cache:
|
||||
preload:
|
||||
enabled: true
|
||||
time_range: "7D" # 只预加载7天(减少启动时间)
|
||||
fallback:
|
||||
enabled: true # 启用降级
|
||||
|
||||
shared_services = SharedServices(
|
||||
cache_manager=cache_manager,
|
||||
db_manager=db_manager, # ← 传数据库
|
||||
enable_db_fallback=True # ← 启用降级
|
||||
)
|
||||
|
||||
# 特点
|
||||
✅ 启动快(少量预加载)
|
||||
✅ 缓存未命中自动从数据库加载
|
||||
✅ 开发灵活(不用担心缓存不足)
|
||||
⚠️ 运行时可能访问数据库(性能影响小)
|
||||
```
|
||||
|
||||
**适用场景**:
|
||||
- 开发测试:快速启动,灵活调试
|
||||
- 回测:需要大量历史数据
|
||||
- 策略研发:需要访问任意时间段数据
|
||||
|
||||
### 5.2 推荐配置
|
||||
|
||||
**生产环境(实盘)**:
|
||||
```yaml
|
||||
cache:
|
||||
enabled: true
|
||||
preload:
|
||||
enabled: true
|
||||
time_range: "3M" # 充足的历史数据
|
||||
periods: ["1m", "1d"]
|
||||
fallback:
|
||||
enabled: false # 禁用降级,纯缓存
|
||||
```
|
||||
|
||||
**开发环境**:
|
||||
```yaml
|
||||
cache:
|
||||
enabled: true
|
||||
preload:
|
||||
enabled: true
|
||||
time_range: "7D" # 快速启动
|
||||
periods: ["1d"] # 少量数据
|
||||
fallback:
|
||||
enabled: true # 启用降级
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 架构图对比
|
||||
|
||||
### 6.1 原设计(过度暴露)
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ SharedServices │
|
||||
│ │
|
||||
│ + cache_manager (public) ───────┐ │
|
||||
│ + db_manager (public) ───────┼─┐ │
|
||||
│ + config (public) ───────┼─┼─┐│
|
||||
│ + data_service (public) ───────┼─┼─┤│
|
||||
│ │ │ │││
|
||||
└────────────────────────────────────┼─┼─┤│
|
||||
│ │ ││
|
||||
StrategyContext │ │ ││
|
||||
↓ │ │ ││
|
||||
Strategy 可以直接访问│ │ ││
|
||||
↓ │ │ ││
|
||||
context._shared.cache_manager ←┘││
|
||||
context._shared.db_manager ──────┘│
|
||||
context._shared.config ───────────┘
|
||||
|
||||
❌ 问题:策略可以访问所有底层组件
|
||||
```
|
||||
|
||||
### 6.2 新设计(最小化接口)
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ SharedServices │
|
||||
│ │
|
||||
│ - _cache_manager (private) │
|
||||
│ - _db_manager (private) │
|
||||
│ - _config (private) │
|
||||
│ │
|
||||
│ 公开接口: │
|
||||
│ + get_klines() │
|
||||
│ + get_indicators() │
|
||||
│ │
|
||||
│ 内部降级逻辑(策略不可见): │
|
||||
│ 缓存命中 → 返回 │
|
||||
│ 缓存未命中 → 降级到数据库(可选) │
|
||||
│ │
|
||||
└─────────────────────────────────────────┘
|
||||
↑
|
||||
│ 只能访问公开接口
|
||||
│
|
||||
StrategyContext
|
||||
↓
|
||||
Strategy
|
||||
↓
|
||||
context.get_klines(...) ← 唯一方式
|
||||
|
||||
✅ 优点:策略只能访问高层接口
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. 总结
|
||||
|
||||
### 7.1 核心设计原则
|
||||
|
||||
| 原则 | 说明 | 体现 |
|
||||
| -------------- | ------------------ | --------------------------------------- |
|
||||
| **接口最小化** | 只暴露必要的接口 | 只暴露 get_klines() 和 get_indicators() |
|
||||
| **封装实现** | 隐藏内部细节 | 缓存、数据库都是私有成员 |
|
||||
| **关注点分离** | 策略不关心数据来源 | 降级逻辑对策略透明 |
|
||||
| **单一职责** | 每个组件职责清晰 | 数据库操作是服务器的职责,不是策略的 |
|
||||
|
||||
### 7.2 用户观点的正确性
|
||||
|
||||
✅ **用户观点完全正确**:
|
||||
|
||||
1. **"策略不需要知道数据库"**
|
||||
- ✅ 正确!策略只需要数据接口
|
||||
- ✅ 数据从哪来应该对策略透明
|
||||
|
||||
2. **"启动时预加载,关闭时保存"**
|
||||
- ✅ 正确!这是服务器的职责
|
||||
- ✅ 运行时只操作缓存,性能最优
|
||||
|
||||
3. **"不需要暴露这么多底层能力"**
|
||||
- ✅ 完全正确!应该最小化接口
|
||||
- ✅ cache_manager、db_manager 应该是私有的
|
||||
|
||||
### 7.3 推荐实现
|
||||
|
||||
```python
|
||||
# ==================== 新设计 ====================
|
||||
|
||||
class SharedServices:
|
||||
"""共享服务(最小化接口)"""
|
||||
|
||||
def __init__(self, cache_manager, db_manager=None, enable_db_fallback=False):
|
||||
# 私有成员
|
||||
self._cache_manager = cache_manager
|
||||
self._db_manager = db_manager
|
||||
self._enable_db_fallback = enable_db_fallback
|
||||
|
||||
# 公开接口(仅2个)
|
||||
def get_klines(self, symbol, period, last_n=None):
|
||||
"""策略唯一的数据访问方式"""
|
||||
# 1. 从缓存读取
|
||||
df = self._cache_manager.get_klines_range(...)
|
||||
if df is not None:
|
||||
return df
|
||||
|
||||
# 2. 可选:降级到数据库
|
||||
if self._enable_db_fallback:
|
||||
df = self._load_from_database(...)
|
||||
self._cache_manager.set_klines(...) # 填充缓存
|
||||
|
||||
return df
|
||||
|
||||
def get_indicators(self, symbol, period, indicator_type):
|
||||
"""第二个公开接口"""
|
||||
return self._cache_manager.get_indicator(...)
|
||||
|
||||
# 私有方法(策略无法访问)
|
||||
def _load_from_database(self, ...):
|
||||
"""降级逻辑(私有)"""
|
||||
pass
|
||||
|
||||
# ==================== 服务器启动 ====================
|
||||
|
||||
def start_server(host, port, config_path):
|
||||
# 1. 初始化组件
|
||||
db_manager = DBManager(config['database'])
|
||||
cache_manager = CacheManager(config['cache'])
|
||||
|
||||
# 2. 预加载(服务器职责)
|
||||
preload_cache_data(db_manager, cache_manager, config)
|
||||
|
||||
# 3. 创建共享服务(最小化接口)
|
||||
shared = SharedServices(
|
||||
cache_manager=cache_manager,
|
||||
db_manager=db_manager, # 可选
|
||||
enable_db_fallback=False # 生产建议禁用
|
||||
)
|
||||
|
||||
# 4. 启动策略管理器
|
||||
strategy_manager = StrategyManager(config_dir, shared)
|
||||
|
||||
# 5. 注册关闭钩子(服务器职责)
|
||||
def on_shutdown():
|
||||
# 可选:保存缓存
|
||||
if config['cache'].get('persist_on_shutdown'):
|
||||
save_cache_to_database(cache_manager, db_manager)
|
||||
db_manager.close()
|
||||
|
||||
# 6. 启动服务器
|
||||
ws_server.start(host, port)
|
||||
```
|
||||
|
||||
### 7.4 设计对比总结
|
||||
|
||||
| 方面 | 原设计 | 新设计 |
|
||||
| -------------- | ----------------------------------- | -------------------------------- |
|
||||
| **暴露接口** | 4个(cache/db/config/data_service) | 2个(get_klines/get_indicators) |
|
||||
| **策略依赖** | 依赖底层实现 | 只依赖数据接口 |
|
||||
| **数据库访问** | 策略可以直接访问 | 策略完全不知道 |
|
||||
| **降级逻辑** | 暴露给策略 | 封装在内部 |
|
||||
| **封装性** | ❌ 差 | ✅ 好 |
|
||||
| **可维护性** | ❌ 难以重构 | ✅ 易于修改 |
|
||||
|
||||
---
|
||||
|
||||
**设计结论**:
|
||||
用户的观点完全正确!应该采用**最小化接口设计**,只暴露 `get_klines()` 和 `get_indicators()` 两个接口,所有底层实现(缓存、数据库)都应该是私有的。数据库操作应该在服务器启动/关闭时完成,运行时策略只访问缓存。
|
||||
|
||||
**下一步**:
|
||||
基于此设计重新实现 SharedServices 和相关组件。
|
||||
901
docs/tech_designs/strategy_context_sharing_design.md
Normal file
901
docs/tech_designs/strategy_context_sharing_design.md
Normal file
@ -0,0 +1,901 @@
|
||||
# Strategy Context 共享策略设计
|
||||
|
||||
> **核心问题**: 策略的 Context 应该是每个策略独立一个,还是所有策略共享一个?
|
||||
> **日期**: 2025-12-27
|
||||
> **结论**: **混合模式** - 共享服务 + 独立状态
|
||||
|
||||
---
|
||||
|
||||
## 1. 问题分析
|
||||
|
||||
### 1.1 Context 包含的内容分类
|
||||
|
||||
让我们先分析 Context 中包含的内容,它们可以分为两大类:
|
||||
|
||||
```
|
||||
Context 包含内容
|
||||
│
|
||||
├── 📦 共享服务 (Shared Services)
|
||||
│ ├── CacheManager - 数据缓存(全局共享)
|
||||
│ ├── DBManager - 数据库连接(全局共享)
|
||||
│ ├── ConfigManager - 配置管理(全局共享)
|
||||
│ └── DataService - 数据服务(全局共享)
|
||||
│
|
||||
└── 🔒 独立状态 (Instance State)
|
||||
├── PositionManager - 持仓管理(每个策略独立)
|
||||
├── Capital - 资金管理(每个策略独立)
|
||||
├── RiskControl - 风控状态(每个策略独立)
|
||||
└── StrategyState - 策略内部状态(每个策略独立)
|
||||
```
|
||||
|
||||
### 1.2 典型场景对比
|
||||
|
||||
**场景1:获取K线数据**
|
||||
```python
|
||||
# 这是共享的操作
|
||||
context.get_klines('000001.SZ', '1m', last_n=20)
|
||||
|
||||
✅ 应该共享:
|
||||
- CacheManager 是全局的
|
||||
- 所有策略读取相同的市场数据
|
||||
- 没有副作用,只读操作
|
||||
```
|
||||
|
||||
**场景2:查询持仓**
|
||||
```python
|
||||
# 这是独立的状态
|
||||
context.get_position('000001.SZ')
|
||||
|
||||
❌ 不能共享:
|
||||
- 策略A的持仓 ≠ 策略B的持仓
|
||||
- 同一个股票,不同策略可能有不同仓位
|
||||
- 每个策略有独立的资金分配
|
||||
```
|
||||
|
||||
**场景3:风控检查**
|
||||
```python
|
||||
# 这是独立的状态
|
||||
context.check_risk(signal)
|
||||
|
||||
❌ 不能共享:
|
||||
- 策略A的风控参数 ≠ 策略B的风控参数
|
||||
- 止损线、最大仓位等都是独立的
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 三种设计方案对比
|
||||
|
||||
### 方案A:完全共享 Context ❌
|
||||
|
||||
```python
|
||||
# 所有策略共享一个 Context
|
||||
global_context = StrategyContext(cache_manager, config)
|
||||
|
||||
strategy1 = DebugStrategy(context=global_context, instance_id='debug1')
|
||||
strategy2 = MAStrategy(context=global_context, instance_id='ma1')
|
||||
```
|
||||
|
||||
**问题**:
|
||||
```python
|
||||
# ❌ 持仓数据混乱
|
||||
strategy1.context.get_position('000001.SZ') # 返回什么?strategy1的还是strategy2的?
|
||||
|
||||
# ❌ 风控混乱
|
||||
strategy1.context.check_risk(signal) # 用的是哪个策略的风控参数?
|
||||
|
||||
# ❌ 状态污染
|
||||
strategy1.context.update_position(...) # 会影响strategy2吗?
|
||||
```
|
||||
|
||||
**结论**:❌ **不可行** - 无法区分策略独立状态
|
||||
|
||||
---
|
||||
|
||||
### 方案B:完全独立 Context ❌
|
||||
|
||||
```python
|
||||
# 每个策略独立创建一个 Context
|
||||
context1 = StrategyContext(cache_manager, config, instance_id='debug1')
|
||||
context2 = StrategyContext(cache_manager, config, instance_id='ma1')
|
||||
|
||||
strategy1 = DebugStrategy(context=context1)
|
||||
strategy2 = MAStrategy(context=context2)
|
||||
```
|
||||
|
||||
**问题**:
|
||||
```python
|
||||
# ❌ 资源浪费
|
||||
每个 Context 都要持有 cache_manager 引用(虽然指向同一个对象)
|
||||
每个 Context 都要持有 db_manager 引用
|
||||
每个 Context 都要持有 config 引用
|
||||
|
||||
# ❌ 维护困难
|
||||
如果要添加新的共享服务,需要修改所有 Context 实例
|
||||
|
||||
# ⚠️ 潜在的内存浪费
|
||||
虽然共享服务是引用,但 Context 对象本身会有多份
|
||||
```
|
||||
|
||||
**结论**:⚠️ **可行但不优雅** - 浪费资源,维护困难
|
||||
|
||||
---
|
||||
|
||||
### 方案C:混合模式(共享服务 + 独立状态)✅ 推荐
|
||||
|
||||
```python
|
||||
# 1. 全局共享服务
|
||||
shared_services = SharedServices(
|
||||
cache_manager=cache_manager,
|
||||
db_manager=db_manager,
|
||||
config=config
|
||||
)
|
||||
|
||||
# 2. 每个策略有独立的 Context
|
||||
context1 = StrategyContext(
|
||||
shared_services=shared_services,
|
||||
instance_id='debug_000001',
|
||||
instance_config=load_config('debug_000001.yaml')
|
||||
)
|
||||
|
||||
context2 = StrategyContext(
|
||||
shared_services=shared_services,
|
||||
instance_id='ma_000001',
|
||||
instance_config=load_config('ma_000001.yaml')
|
||||
)
|
||||
|
||||
# 3. 策略使用各自的 Context
|
||||
strategy1 = DebugStrategy(context=context1)
|
||||
strategy2 = MAStrategy(context=context2)
|
||||
```
|
||||
|
||||
**优势**:
|
||||
```python
|
||||
# ✅ 共享服务高效访问
|
||||
context1.get_klines(...) # 通过 shared_services.cache_manager
|
||||
context2.get_klines(...) # 使用同一个 cache_manager
|
||||
|
||||
# ✅ 独立状态互不影响
|
||||
context1.get_position('000001.SZ') # 返回 strategy1 的持仓
|
||||
context2.get_position('000001.SZ') # 返回 strategy2 的持仓
|
||||
|
||||
# ✅ 资源高效利用
|
||||
只有一份 cache_manager, db_manager, config
|
||||
但每个策略有自己的 position, capital, risk_state
|
||||
|
||||
# ✅ 易于扩展
|
||||
添加新的共享服务:只需修改 SharedServices
|
||||
添加新的独立状态:只需修改 StrategyContext
|
||||
```
|
||||
|
||||
**结论**:✅ **推荐方案** - 平衡了效率和隔离性
|
||||
|
||||
---
|
||||
|
||||
## 3. 推荐架构设计
|
||||
|
||||
### 3.1 架构图
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ QTradeServer │
|
||||
│ │
|
||||
│ ┌────────────────────────────────────────────────────┐ │
|
||||
│ │ SharedServices (全局单例) │ │
|
||||
│ │ │ │
|
||||
│ │ - cache_manager: CacheManager │ │
|
||||
│ │ - db_manager: DBManager │ │
|
||||
│ │ - config: GlobalConfig │ │
|
||||
│ │ - data_service: DataService │ │
|
||||
│ │ │ │
|
||||
│ │ + get_klines(symbol, period, ...) │ │
|
||||
│ │ + get_indicators(symbol, period, type) │ │
|
||||
│ │ + get_config(key) │ │
|
||||
│ └────────────────────────────────────────────────────┘ │
|
||||
│ ↑ 引用 │
|
||||
│ ┌───────────────┼───────────────┐ │
|
||||
│ │ │ │ │
|
||||
│ ┌──────┴──────┐ ┌──────┴──────┐ ┌─────┴───────┐ │
|
||||
│ │ Context1 │ │ Context2 │ │ Context3 │ │
|
||||
│ │ (debug1) │ │ (ma1) │ │ (macd1) │ │
|
||||
│ │ │ │ │ │ │ │
|
||||
│ │ shared: ref │ │ shared: ref │ │ shared: ref │ │
|
||||
│ │ instance_id │ │ instance_id │ │ instance_id │ │
|
||||
│ │ position │ │ position │ │ position │ │
|
||||
│ │ capital │ │ capital │ │ capital │ │
|
||||
│ │ risk_state │ │ risk_state │ │ risk_state │ │
|
||||
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
|
||||
│ │ │ │ │
|
||||
└─────────┼───────────────┼───────────────┼───────────────────┘
|
||||
↓ ↓ ↓
|
||||
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
|
||||
│ Strategy1 │ │ Strategy2 │ │ Strategy3 │
|
||||
│ (debug) │ │ (ma) │ │ (macd) │
|
||||
└─────────────┘ └─────────────┘ └─────────────┘
|
||||
```
|
||||
|
||||
### 3.2 类设计
|
||||
|
||||
#### SharedServices(共享服务容器)
|
||||
|
||||
```python
|
||||
class SharedServices:
|
||||
"""
|
||||
共享服务容器(全局单例)
|
||||
|
||||
包含所有策略共享的只读服务
|
||||
线程安全,无状态(或状态全局共享)
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cache_manager: CacheManager,
|
||||
db_manager: DBManager,
|
||||
config: GlobalConfig,
|
||||
data_service: Optional[DataService] = None
|
||||
):
|
||||
"""
|
||||
初始化共享服务
|
||||
|
||||
Args:
|
||||
cache_manager: 数据缓存管理器(全局共享)
|
||||
db_manager: 数据库管理器(连接池)
|
||||
config: 全局配置
|
||||
data_service: 可选的数据服务(封装缓存+数据库)
|
||||
"""
|
||||
self.cache_manager = cache_manager
|
||||
self.db_manager = db_manager
|
||||
self.config = config
|
||||
self.data_service = data_service or DataService(cache_manager, db_manager)
|
||||
|
||||
def get_klines(
|
||||
self,
|
||||
symbol: str,
|
||||
period: str,
|
||||
last_n: Optional[int] = None,
|
||||
start: Optional[pd.Timestamp] = None,
|
||||
end: Optional[pd.Timestamp] = None
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
获取K线数据(只读操作,线程安全)
|
||||
|
||||
这是共享操作:所有策略读取相同的市场数据
|
||||
"""
|
||||
return self.data_service.get_klines(symbol, period, last_n, start, end)
|
||||
|
||||
def get_indicators(
|
||||
self,
|
||||
symbol: str,
|
||||
period: str,
|
||||
indicator_type: str
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
获取指标数据(只读操作,线程安全)
|
||||
"""
|
||||
return self.data_service.get_indicators(symbol, period, indicator_type)
|
||||
|
||||
def get_global_config(self, key: str) -> Any:
|
||||
"""
|
||||
获取全局配置(只读操作)
|
||||
"""
|
||||
return self.config.get(key)
|
||||
```
|
||||
|
||||
#### StrategyContext(策略上下文 - 每个策略独立)
|
||||
|
||||
```python
|
||||
class StrategyContext:
|
||||
"""
|
||||
策略上下文(每个策略实例独立)
|
||||
|
||||
包含:
|
||||
- 共享服务的引用(只读)
|
||||
- 策略实例独立的状态(读写)
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
shared_services: SharedServices,
|
||||
instance_id: str,
|
||||
instance_config: dict
|
||||
):
|
||||
"""
|
||||
初始化策略上下文
|
||||
|
||||
Args:
|
||||
shared_services: 共享服务容器(引用)
|
||||
instance_id: 策略实例ID
|
||||
instance_config: 策略实例配置
|
||||
"""
|
||||
# 共享服务引用(只读)
|
||||
self._shared = shared_services
|
||||
|
||||
# 策略实例信息
|
||||
self.instance_id = instance_id
|
||||
self.instance_config = instance_config
|
||||
self.symbol = instance_config['symbol']
|
||||
|
||||
# 独立状态(每个策略独立)
|
||||
self._position = Position(
|
||||
symbol=self.symbol,
|
||||
capital=instance_config['capital']
|
||||
)
|
||||
self._capital = Capital(
|
||||
total=instance_config['capital']
|
||||
)
|
||||
self._risk_state = RiskState(
|
||||
config=instance_config.get('risk', {})
|
||||
)
|
||||
|
||||
# ==================== 共享服务访问 ====================
|
||||
|
||||
def get_klines(
|
||||
self,
|
||||
symbol: Optional[str] = None,
|
||||
period: str = '1m',
|
||||
last_n: Optional[int] = None
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
获取K线数据(委托给共享服务)
|
||||
|
||||
Args:
|
||||
symbol: 股票代码(如果不指定,使用策略配置的symbol)
|
||||
period: 周期
|
||||
last_n: 最近N条
|
||||
|
||||
Returns:
|
||||
K线DataFrame
|
||||
"""
|
||||
symbol = symbol or self.symbol
|
||||
return self._shared.get_klines(symbol, period, last_n=last_n)
|
||||
|
||||
def get_indicators(
|
||||
self,
|
||||
indicator_type: str,
|
||||
symbol: Optional[str] = None,
|
||||
period: str = '1m'
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
获取指标数据(委托给共享服务)
|
||||
"""
|
||||
symbol = symbol or self.symbol
|
||||
return self._shared.get_indicators(symbol, period, indicator_type)
|
||||
|
||||
# ==================== 独立状态访问 ====================
|
||||
|
||||
def get_position(self) -> Position:
|
||||
"""
|
||||
获取当前持仓(策略独立)
|
||||
|
||||
每个策略实例有自己的持仓
|
||||
"""
|
||||
return self._position
|
||||
|
||||
def update_position(
|
||||
self,
|
||||
action: str,
|
||||
quantity: int,
|
||||
price: float
|
||||
) -> bool:
|
||||
"""
|
||||
更新持仓(策略独立)
|
||||
|
||||
修改此策略实例的持仓,不影响其他策略
|
||||
"""
|
||||
if action == 'BUY':
|
||||
return self._position.buy(quantity, price)
|
||||
elif action == 'SELL':
|
||||
return self._position.sell(quantity, price)
|
||||
return False
|
||||
|
||||
def get_capital(self) -> Capital:
|
||||
"""
|
||||
获取资金信息(策略独立)
|
||||
|
||||
每个策略实例有独立的资金分配
|
||||
"""
|
||||
return self._capital
|
||||
|
||||
def check_risk(self, signal: dict) -> bool:
|
||||
"""
|
||||
风控检查(策略独立)
|
||||
|
||||
使用此策略实例的风控参数
|
||||
"""
|
||||
# 检查资金是否充足
|
||||
required_capital = signal['quantity'] * signal['price']
|
||||
if required_capital > self._capital.available:
|
||||
return False
|
||||
|
||||
# 检查仓位限制
|
||||
max_position_ratio = self._risk_state.max_position_ratio
|
||||
current_ratio = self._position.get_position_ratio()
|
||||
if current_ratio >= max_position_ratio:
|
||||
return False
|
||||
|
||||
# 检查止损线
|
||||
if self._position.has_position():
|
||||
loss_pct = self._position.get_loss_pct(signal['price'])
|
||||
if loss_pct < -self._risk_state.stop_loss:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def get_instance_info(self) -> dict:
|
||||
"""
|
||||
获取实例信息(策略独立)
|
||||
"""
|
||||
return {
|
||||
'instance_id': self.instance_id,
|
||||
'symbol': self.symbol,
|
||||
'capital': self._capital.total,
|
||||
'available_capital': self._capital.available,
|
||||
'position': self._position.to_dict(),
|
||||
'risk_state': self._risk_state.to_dict()
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 共享 vs 独立内容清单
|
||||
|
||||
### 4.1 共享内容(通过 SharedServices)
|
||||
|
||||
| 服务/数据 | 共享原因 | 访问方式 | 特点 |
|
||||
| ---------------- | -------------------------------------- | ------------------------------- | -------------- |
|
||||
| **CacheManager** | 全局数据缓存,所有策略读取相同市场数据 | `context._shared.cache_manager` | 只读,线程安全 |
|
||||
| **DBManager** | 数据库连接池,避免重复连接 | `context._shared.db_manager` | 只读,连接池 |
|
||||
| **GlobalConfig** | 全局配置(如总资金、全局风控) | `context._shared.config` | 只读 |
|
||||
| **DataService** | 封装数据访问逻辑(缓存+数据库) | `context._shared.data_service` | 只读,有降级 |
|
||||
| **K线数据** | 市场数据,所有策略看到的是相同的 | `context.get_klines()` | 只读 |
|
||||
| **指标数据** | 基于K线计算,所有策略相同 | `context.get_indicators()` | 只读 |
|
||||
|
||||
**共享特征**:
|
||||
- ✅ **只读操作**:不修改数据,只查询
|
||||
- ✅ **无副作用**:多个策略同时访问不冲突
|
||||
- ✅ **线程安全**:可以并发访问
|
||||
- ✅ **资源高效**:避免重复创建和内存浪费
|
||||
|
||||
### 4.2 独立内容(每个 StrategyContext)
|
||||
|
||||
| 状态/数据 | 独立原因 | 访问方式 | 特点 |
|
||||
| ------------------ | -------------------------- | ------------------------- | -------------- |
|
||||
| **Position** | 每个策略有独立持仓 | `context.get_position()` | 读写,策略隔离 |
|
||||
| **Capital** | 每个策略有独立资金分配 | `context.get_capital()` | 读写,策略隔离 |
|
||||
| **RiskState** | 每个策略有独立风控参数 | `context.check_risk()` | 读写,策略隔离 |
|
||||
| **InstanceConfig** | 每个策略有独立配置 | `context.instance_config` | 只读,策略专属 |
|
||||
| **StrategyState** | 策略内部状态(如MA历史值) | 策略内部管理 | 读写,策略内部 |
|
||||
|
||||
**独立特征**:
|
||||
- 🔒 **有状态**:会被修改,有副作用
|
||||
- 🔒 **策略隔离**:策略A的修改不影响策略B
|
||||
- 🔒 **独立配置**:每个策略有自己的参数
|
||||
- 🔒 **独立资金**:避免多策略资金冲突
|
||||
|
||||
---
|
||||
|
||||
## 5. 典型使用场景示例
|
||||
|
||||
### 场景1:策略获取历史数据(共享)
|
||||
|
||||
```python
|
||||
class MAStrategy:
|
||||
def __init__(self, context: StrategyContext, **params):
|
||||
self.context = context
|
||||
self.ma_period = params.get('ma_period', 20)
|
||||
|
||||
def compute(self, kline_data: dict):
|
||||
# ✅ 通过 context 获取历史数据(共享服务)
|
||||
history = self.context.get_klines(
|
||||
period='1m',
|
||||
last_n=self.ma_period
|
||||
)
|
||||
|
||||
if history is None or len(history) < self.ma_period:
|
||||
return None
|
||||
|
||||
# 计算均线
|
||||
ma = history['close'].mean()
|
||||
|
||||
# 生成信号
|
||||
current_price = kline_data['close']
|
||||
if current_price > ma:
|
||||
return {'action': 'BUY', 'price': current_price, 'quantity': 100}
|
||||
|
||||
return None
|
||||
```
|
||||
|
||||
**分析**:
|
||||
- `get_klines()` 访问共享的 CacheManager
|
||||
- 所有 MA 策略实例看到的历史数据是相同的
|
||||
- 这是只读操作,线程安全
|
||||
|
||||
### 场景2:策略检查持仓(独立)
|
||||
|
||||
```python
|
||||
class MAStrategy:
|
||||
def compute(self, kline_data: dict):
|
||||
# ... 生成信号
|
||||
signal = {'action': 'BUY', 'price': 10.5, 'quantity': 100}
|
||||
|
||||
# ✅ 检查此策略的持仓(独立状态)
|
||||
position = self.context.get_position()
|
||||
|
||||
# 如果已经持仓,不重复买入
|
||||
if position.quantity > 0:
|
||||
logger.info(f"Already holding {position.quantity} shares")
|
||||
return None
|
||||
|
||||
# ✅ 检查此策略的资金(独立状态)
|
||||
capital = self.context.get_capital()
|
||||
required = signal['quantity'] * signal['price']
|
||||
|
||||
if capital.available < required:
|
||||
logger.warning(f"Insufficient capital: need {required}, have {capital.available}")
|
||||
return None
|
||||
|
||||
# ✅ 风控检查(独立参数)
|
||||
if not self.context.check_risk(signal):
|
||||
logger.warning("Risk check failed")
|
||||
return None
|
||||
|
||||
return signal
|
||||
```
|
||||
|
||||
**分析**:
|
||||
- `get_position()` 返回此策略实例的持仓
|
||||
- `get_capital()` 返回此策略实例的资金
|
||||
- `check_risk()` 使用此策略实例的风控参数
|
||||
- 这些都是独立状态,不影响其他策略
|
||||
|
||||
### 场景3:策略执行交易后更新状态(独立)
|
||||
|
||||
```python
|
||||
# qtrade_server.py
|
||||
|
||||
async def handle_trade_result(message: dict) -> dict:
|
||||
"""
|
||||
处理交易成交反馈
|
||||
"""
|
||||
instance_id = message.get('instance_id')
|
||||
action = message.get('action')
|
||||
quantity = message.get('quantity')
|
||||
price = message.get('price')
|
||||
|
||||
# 查找对应的策略实例
|
||||
strategy = strategy_manager.get_instance(instance_id)
|
||||
if not strategy:
|
||||
raise ValueError(f"Strategy not found: {instance_id}")
|
||||
|
||||
# ✅ 更新此策略的持仓(独立状态)
|
||||
success = strategy.context.update_position(
|
||||
action=action,
|
||||
quantity=quantity,
|
||||
price=price
|
||||
)
|
||||
|
||||
if success:
|
||||
logger.info(f"Position updated for {instance_id}: {action} {quantity}@{price}")
|
||||
return {"msg_type": "ACK", "status": "success"}
|
||||
else:
|
||||
return {"msg_type": "ERROR", "message": "Failed to update position"}
|
||||
```
|
||||
|
||||
**分析**:
|
||||
- `update_position()` 只修改此策略实例的持仓
|
||||
- 策略A买入不影响策略B的持仓
|
||||
- 这是写操作,但由于隔离,不会冲突
|
||||
|
||||
---
|
||||
|
||||
## 6. 内存和性能分析
|
||||
|
||||
### 6.1 内存占用估算
|
||||
|
||||
**假设场景**:
|
||||
- 3个策略实例
|
||||
- 2个标的(000001.SZ, 600000.SH)
|
||||
- 2个周期(1m, 1d)
|
||||
- 每个缓存1000条数据
|
||||
|
||||
#### 完全独立 Context(方案B)
|
||||
|
||||
```
|
||||
每个 Context 独立持有所有服务:
|
||||
|
||||
Context1:
|
||||
- cache_manager 引用: 8 bytes
|
||||
- db_manager 引用: 8 bytes
|
||||
- config 引用: 8 bytes
|
||||
- position: ~1 KB
|
||||
- capital: ~0.5 KB
|
||||
- risk_state: ~0.5 KB
|
||||
Total: ~2 KB
|
||||
|
||||
3个Context总计: ~6 KB (只算独立数据,共享服务只有引用)
|
||||
```
|
||||
|
||||
#### 混合模式(方案C - 推荐)
|
||||
|
||||
```
|
||||
SharedServices (全局1份):
|
||||
- cache_manager: 8 bytes (指针)
|
||||
- db_manager: 8 bytes (指针)
|
||||
- config: 8 bytes (指针)
|
||||
Total: 24 bytes
|
||||
|
||||
每个 Context:
|
||||
- shared 引用: 8 bytes
|
||||
- position: ~1 KB
|
||||
- capital: ~0.5 KB
|
||||
- risk_state: ~0.5 KB
|
||||
Total: ~2 KB
|
||||
|
||||
3个Context总计: ~6 KB + 24 bytes
|
||||
|
||||
结论:内存差异可忽略(因为共享服务本来就是引用)
|
||||
```
|
||||
|
||||
**关键点**:无论哪种方案,共享服务(CacheManager等)都只有一份实际对象,其他都是引用。
|
||||
|
||||
### 6.2 性能对比
|
||||
|
||||
| 操作 | 完全独立 | 混合模式 | 差异 |
|
||||
| ------------ | ----------------------------- | ------------------------------------- | -------------------- |
|
||||
| **获取K线** | `context.cache_manager.get()` | `context._shared.cache_manager.get()` | 多一次间接访问,~1ns |
|
||||
| **查询持仓** | `context.position.get()` | `context._position.get()` | 无差异 |
|
||||
| **风控检查** | `context.check_risk()` | `context.check_risk()` | 无差异 |
|
||||
|
||||
**结论**:性能差异可忽略(多一次指针解引用,现代CPU缓存友好)
|
||||
|
||||
### 6.3 扩展性对比
|
||||
|
||||
**添加新的共享服务**:
|
||||
|
||||
```python
|
||||
# 方案B:完全独立 - 需要修改所有 Context 实例
|
||||
context1 = StrategyContext(cache, db, config, new_service) # ❌ 需要修改
|
||||
context2 = StrategyContext(cache, db, config, new_service) # ❌ 需要修改
|
||||
context3 = StrategyContext(cache, db, config, new_service) # ❌ 需要修改
|
||||
|
||||
# 方案C:混合模式 - 只需修改 SharedServices
|
||||
shared = SharedServices(cache, db, config, new_service) # ✅ 只改一处
|
||||
context1 = StrategyContext(shared, 'inst1', cfg1) # ✅ 无需改
|
||||
context2 = StrategyContext(shared, 'inst2', cfg2) # ✅ 无需改
|
||||
context3 = StrategyContext(shared, 'inst3', cfg3) # ✅ 无需改
|
||||
```
|
||||
|
||||
**结论**:混合模式扩展性更好
|
||||
|
||||
---
|
||||
|
||||
## 7. 推荐实现步骤
|
||||
|
||||
### Phase 1: 定义共享服务容器
|
||||
|
||||
```python
|
||||
# src/core/shared_services.py
|
||||
|
||||
class SharedServices:
|
||||
"""全局共享服务容器"""
|
||||
|
||||
def __init__(self, cache_manager, db_manager, config):
|
||||
self.cache_manager = cache_manager
|
||||
self.db_manager = db_manager
|
||||
self.config = config
|
||||
|
||||
# 可选:封装一个 DataService
|
||||
self.data_service = DataService(cache_manager, db_manager)
|
||||
|
||||
def get_klines(self, symbol, period, last_n=None):
|
||||
"""委托给 DataService"""
|
||||
return self.data_service.get_klines(symbol, period, last_n)
|
||||
```
|
||||
|
||||
### Phase 2: 实现 StrategyContext
|
||||
|
||||
```python
|
||||
# src/core/strategy_context.py
|
||||
|
||||
class StrategyContext:
|
||||
"""策略上下文(每个策略独立)"""
|
||||
|
||||
def __init__(self, shared_services, instance_id, instance_config):
|
||||
self._shared = shared_services
|
||||
self.instance_id = instance_id
|
||||
self.symbol = instance_config['symbol']
|
||||
|
||||
# 独立状态
|
||||
self._position = Position(symbol=self.symbol)
|
||||
self._capital = Capital(total=instance_config['capital'])
|
||||
self._risk_state = RiskState(instance_config.get('risk', {}))
|
||||
|
||||
# 共享服务代理方法
|
||||
def get_klines(self, symbol=None, period='1m', last_n=None):
|
||||
symbol = symbol or self.symbol
|
||||
return self._shared.get_klines(symbol, period, last_n)
|
||||
|
||||
# 独立状态访问方法
|
||||
def get_position(self):
|
||||
return self._position
|
||||
|
||||
def update_position(self, action, quantity, price):
|
||||
# 修改独立状态
|
||||
pass
|
||||
```
|
||||
|
||||
### Phase 3: 修改 StrategyManager
|
||||
|
||||
```python
|
||||
# src/strategy_manager.py
|
||||
|
||||
class StrategyManager:
|
||||
def __init__(self, config_dir, shared_services):
|
||||
self.config_dir = config_dir
|
||||
self.shared_services = shared_services # 持有共享服务引用
|
||||
self.instances = {}
|
||||
|
||||
def _create_strategy_instance(self, strategy_class, instance_config):
|
||||
# 为每个策略创建独立的 Context
|
||||
context = StrategyContext(
|
||||
shared_services=self.shared_services,
|
||||
instance_id=instance_config['instance_id'],
|
||||
instance_config=instance_config
|
||||
)
|
||||
|
||||
# 创建策略实例
|
||||
return strategy_class(context=context, **instance_config['params'])
|
||||
```
|
||||
|
||||
### Phase 4: 服务器启动流程
|
||||
|
||||
```python
|
||||
# src/qtrade_server.py
|
||||
|
||||
def start_server(host, port, config_path):
|
||||
# 1. 初始化共享服务
|
||||
config = load_config(config_path)
|
||||
cache_manager = initialize_cache_manager(config)
|
||||
db_manager = initialize_db_manager(config)
|
||||
|
||||
shared_services = SharedServices(
|
||||
cache_manager=cache_manager,
|
||||
db_manager=db_manager,
|
||||
config=config
|
||||
)
|
||||
|
||||
# 2. 预加载数据(使用共享的 cache_manager)
|
||||
preload_cache_data(cache_manager, config)
|
||||
|
||||
# 3. 初始化策略管理器(传入共享服务)
|
||||
strategy_manager = StrategyManager(
|
||||
config_dir="config/strategies",
|
||||
shared_services=shared_services
|
||||
)
|
||||
strategy_manager.initialize()
|
||||
|
||||
# 4. 启动服务器
|
||||
ws_server = WebSocketServer(...)
|
||||
ws_server.start(host, port)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. 最佳实践和注意事项
|
||||
|
||||
### 8.1 共享服务设计原则
|
||||
|
||||
✅ **应该共享的**:
|
||||
1. **无状态或全局状态**:CacheManager、DBManager
|
||||
2. **只读操作**:获取市场数据、配置查询
|
||||
3. **线程安全**:可以并发访问的服务
|
||||
4. **资源密集**:连接池、大对象
|
||||
|
||||
❌ **不应该共享的**:
|
||||
1. **有策略独立状态**:持仓、资金、风控状态
|
||||
2. **写操作有副作用**:修改持仓、更新资金
|
||||
3. **策略专属配置**:单个策略的参数
|
||||
4. **策略内部缓存**:MA计算的历史值
|
||||
|
||||
### 8.2 Context 设计原则
|
||||
|
||||
```python
|
||||
class StrategyContext:
|
||||
"""
|
||||
设计原则:
|
||||
1. 共享服务:通过引用访问,不直接暴露
|
||||
2. 独立状态:封装在 Context 内部,提供访问接口
|
||||
3. 便捷方法:提供高层接口,隐藏实现细节
|
||||
"""
|
||||
|
||||
def get_klines(self, ...):
|
||||
"""✅ 便捷方法:策略不需要知道 _shared 的存在"""
|
||||
return self._shared.get_klines(...)
|
||||
|
||||
def _get_cache_manager(self):
|
||||
"""❌ 不要暴露内部实现"""
|
||||
return self._shared.cache_manager # 不推荐
|
||||
```
|
||||
|
||||
### 8.3 线程安全考虑
|
||||
|
||||
```python
|
||||
class StrategyContext:
|
||||
"""
|
||||
线程安全策略:
|
||||
- 共享服务:假设它们是线程安全的(只读或有锁)
|
||||
- 独立状态:不需要锁(每个线程访问不同的 Context)
|
||||
"""
|
||||
|
||||
def update_position(self, ...):
|
||||
"""
|
||||
这个方法修改独立状态,不需要锁
|
||||
因为每个策略有自己的 Context
|
||||
"""
|
||||
self._position.update(...) # 安全,独立状态
|
||||
|
||||
def get_klines(self, ...):
|
||||
"""
|
||||
这个方法访问共享服务,由 CacheManager 保证线程安全
|
||||
"""
|
||||
return self._shared.cache_manager.get(...) # 安全,CacheManager 有锁
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. 总结
|
||||
|
||||
### 9.1 设计决策
|
||||
|
||||
| 问题 | 答案 | 理由 |
|
||||
| ----------------- | ------------------------------------ | -------------------- |
|
||||
| Context是否共享? | **部分共享** | 共享服务 + 独立状态 |
|
||||
| 如何组织? | **SharedServices + StrategyContext** | 清晰的职责分离 |
|
||||
| 性能影响? | **可忽略** | 只多一次指针解引用 |
|
||||
| 内存占用? | **几乎相同** | 共享服务本来就是引用 |
|
||||
| 扩展性? | **更好** | 添加服务只改一处 |
|
||||
|
||||
### 9.2 推荐方案
|
||||
|
||||
```
|
||||
✅ 推荐:混合模式(方案C)
|
||||
|
||||
SharedServices (全局1份)
|
||||
├── cache_manager
|
||||
├── db_manager
|
||||
├── config
|
||||
└── data_service
|
||||
|
||||
StrategyContext (每个策略1份)
|
||||
├── shared_services (引用)
|
||||
├── instance_id
|
||||
├── position (独立)
|
||||
├── capital (独立)
|
||||
└── risk_state (独立)
|
||||
```
|
||||
|
||||
### 9.3 核心原则
|
||||
|
||||
1. **共享只读,独立读写**
|
||||
- 市场数据:共享(所有策略看到相同数据)
|
||||
- 策略状态:独立(避免相互影响)
|
||||
|
||||
2. **按职责分离**
|
||||
- SharedServices:提供全局服务
|
||||
- StrategyContext:管理策略独立状态
|
||||
|
||||
3. **最小化暴露**
|
||||
- 策略不直接访问 SharedServices
|
||||
- 通过 Context 提供的接口访问
|
||||
|
||||
4. **易于测试和扩展**
|
||||
- Mock SharedServices 即可测试策略
|
||||
- 添加新服务不影响现有代码
|
||||
|
||||
---
|
||||
|
||||
**设计结论**:
|
||||
采用 **混合模式**,既保证了资源高效利用(共享服务),又保证了策略隔离性(独立状态)。
|
||||
|
||||
**下一步**:
|
||||
基于此方案实现 SharedServices 和 StrategyContext。
|
||||
1
learning_matirals/CSkhQuant
Submodule
1
learning_matirals/CSkhQuant
Submodule
@ -0,0 +1 @@
|
||||
Subproject commit eb0f20c8faa6425b7198bbf2692c0b4b749c243d
|
||||
@ -1 +0,0 @@
|
||||
Subproject commit fe4c29d05b03b8cdc5832ee5f4bed83d5f271198
|
||||
10
main.py
10
main.py
@ -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)
|
||||
132
realtrade_runner.py
Normal file
132
realtrade_runner.py
Normal file
@ -0,0 +1,132 @@
|
||||
"""
|
||||
实盘交易客户端启动脚本
|
||||
|
||||
使用 MiniQMT 进行实盘交易,先连接策略服务器获取信号,然后执行实盘交易
|
||||
"""
|
||||
|
||||
import time
|
||||
from datetime import datetime
|
||||
import pandas as pd
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from src.core.config import Config
|
||||
from src.core.logger import Logger
|
||||
from src.realtrade.miniqmt_client_adapter import MiniQMTClientAdapter
|
||||
|
||||
|
||||
workspace = Path(__file__).parent
|
||||
|
||||
"""
|
||||
股票池配置
|
||||
|
||||
定义实盘交易的股票池,包含股票代码、名称和K线周期
|
||||
"""
|
||||
|
||||
STOCK_POOL = [
|
||||
{"symbol": "601288.SH", "symbol_name": "农业银行", "period": "1m"},
|
||||
{"symbol": "600593.SH", "symbol_name": "大连圣亚", "period": "5m"},
|
||||
# 添加更多股票...
|
||||
]
|
||||
|
||||
|
||||
def start_server_newwindow():
|
||||
"""启动服务器进程(在新的控制台窗口)"""
|
||||
print("=" * 60)
|
||||
print("正在启动 QTrade Server(新窗口)...")
|
||||
print("=" * 60)
|
||||
subprocess.Popen(
|
||||
[sys.executable, "-m", "src.qtrade_server"],
|
||||
cwd=workspace,
|
||||
creationflags=subprocess.CREATE_NEW_CONSOLE, # Windows下在新控制台窗口启动
|
||||
)
|
||||
print("✓ 服务器已在新窗口启动,等待5秒...")
|
||||
|
||||
|
||||
def start_server():
|
||||
"""启动服务器进程(直接显示输出)"""
|
||||
print("=" * 60)
|
||||
print("正在启动 QTrade Server...")
|
||||
print("=" * 60)
|
||||
try:
|
||||
subprocess.run([sys.executable, "-m", "src.qtrade_server"], cwd=workspace)
|
||||
except KeyboardInterrupt:
|
||||
print("\n✓ 服务器已正常关闭")
|
||||
|
||||
|
||||
def main():
|
||||
config = Config.initialize("production")
|
||||
Logger.initialize("realtrade")
|
||||
Logger.info("=" * 60)
|
||||
Logger.info("启动 QTrade 实盘交易客户端")
|
||||
Logger.info("=" * 60)
|
||||
if not config:
|
||||
Logger.error("✗ 配置加载失败,退出程序")
|
||||
return
|
||||
Logger.info("配置加载完成")
|
||||
|
||||
"""实盘交易主函数"""
|
||||
|
||||
# 启动服务端
|
||||
Logger.info("\n启动策略服务器...")
|
||||
start_server_newwindow()
|
||||
Logger.info("✓ 策略服务器启动命令已发送,等待5秒...")
|
||||
time.sleep(5) # 等待服务器启动
|
||||
|
||||
# 启动miniQMT客户端适配器
|
||||
Logger.info("\n初始化 MiniQMT 客户端适配器...")
|
||||
|
||||
# 从配置获取参数
|
||||
server_url = config.get("client_adapters.production_adapter.server_url")
|
||||
timeout = config.get("client_adapters.production_adapter.timeout", 30)
|
||||
|
||||
miniqmt_path = config.get("miniqmt.userdata_path")
|
||||
session_id = config.get("miniqmt.session_id", 123456)
|
||||
account_id = config.get("miniqmt.account.account_id")
|
||||
account_type = config.get("miniqmt.account.account_type", "STOCK")
|
||||
|
||||
Logger.info(f"服务器地址: {server_url}")
|
||||
Logger.info(f"MiniQMT 路径: {miniqmt_path}")
|
||||
Logger.info(f"交易账号: {account_id}")
|
||||
Logger.info(f"账户类型: {account_type}")
|
||||
|
||||
# 创建实盘客户端适配器
|
||||
adapter = MiniQMTClientAdapter(
|
||||
server_url=server_url,
|
||||
timeout=timeout,
|
||||
miniqmt_path=miniqmt_path,
|
||||
session_id=session_id,
|
||||
account_id=account_id,
|
||||
account_type=account_type,
|
||||
stockpool=STOCK_POOL,
|
||||
)
|
||||
# 连接 MiniQMT
|
||||
Logger.info("\n连接 MiniQMT 交易接口...")
|
||||
if not adapter.run():
|
||||
Logger.error("MiniQMT 连接失败,退出程序")
|
||||
return
|
||||
|
||||
Logger.info("✓ MiniQMT 连接成功")
|
||||
|
||||
try:
|
||||
# 保持连接,接收交易推送
|
||||
Logger.info("\n" + "=" * 60)
|
||||
Logger.info("实盘交易客户端运行中...")
|
||||
Logger.info("按 Ctrl+C 退出")
|
||||
Logger.info("=" * 60)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
Logger.info("\n\n收到退出信号,正在关闭...")
|
||||
|
||||
except Exception as e:
|
||||
Logger.error(f"运行异常: {e}", exc_info=True)
|
||||
finally:
|
||||
# 关闭连接
|
||||
adapter.close()
|
||||
Logger.info("✓ 实盘交易客户端已关闭")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -36,4 +36,5 @@ pytz>=2023.0
|
||||
xtquant # 迅投QMT数据源
|
||||
fastapi>=0.95.0 # 用于构建API服务
|
||||
uvicorn[standard]
|
||||
websockets>=11.0.0 # 用于WebSocket通信
|
||||
websockets>=11.0.0 # 用于WebSocket通信
|
||||
pyyaml
|
||||
@ -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)
|
||||
|
||||
@ -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}"
|
||||
)
|
||||
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -118,8 +118,8 @@ class KlineCanvas(FigureCanvasQTAgg):
|
||||
def _load_indicator_config(self):
|
||||
"""加载指标配置参数"""
|
||||
try:
|
||||
config = Config("configs/global.yaml")
|
||||
indicators_config = config.get("indicators")
|
||||
# 使用Config单例,无需初始化
|
||||
indicators_config = Config.get("indicators")
|
||||
|
||||
if not indicators_config:
|
||||
raise ValueError("配置文件中未找到 'indicators' 配置项")
|
||||
@ -131,7 +131,7 @@ class KlineCanvas(FigureCanvasQTAgg):
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n❌ 配置文件读取失败: {e}")
|
||||
print("请检查 configs/global.yaml 文件中的 indicators 配置项")
|
||||
print("请检查配置文件中的 indicators 配置项")
|
||||
sys.exit(1)
|
||||
|
||||
def _load_macd_config(self, indicators_config):
|
||||
@ -1071,14 +1071,22 @@ def main():
|
||||
if "py311" not in sys.executable.lower():
|
||||
print("警告: 建议使用py311环境")
|
||||
|
||||
# 加载配置和DataService
|
||||
# 初始化配置(使用Config单例)
|
||||
try:
|
||||
config = Config()
|
||||
config.load_with_global("configs/backtest.yaml")
|
||||
data_service = DataService.from_config(config)
|
||||
Config.initialize()
|
||||
print("✓ Config初始化成功")
|
||||
except Exception as e:
|
||||
print(f"✗ Config初始化失败: {e}")
|
||||
traceback.print_exc()
|
||||
sys.exit(1)
|
||||
|
||||
# 初始化DataService
|
||||
try:
|
||||
data_service = DataService.from_config()
|
||||
print("✓ DataService初始化成功")
|
||||
except Exception as e:
|
||||
print(f"✗ DataService初始化失败: {e}")
|
||||
traceback.print_exc()
|
||||
sys.exit(1)
|
||||
|
||||
# 创建应用
|
||||
|
||||
@ -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()}
|
||||
|
||||
@ -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")
|
||||
|
||||
@ -24,8 +24,15 @@ class BacktestTask:
|
||||
strategy_name: str,
|
||||
strategy_params: Optional[dict] = None,
|
||||
initial_capital: float = 100000.0,
|
||||
trading_type: str = "t1",
|
||||
commission_rate: float = 0.0003,
|
||||
slippage_rate: float = 0.0001,
|
||||
min_commission: float = 5.0,
|
||||
stamp_tax_rate: float = 0.001,
|
||||
transfer_fee_rate: float = 0.00002,
|
||||
slippage: float = 0.0001,
|
||||
symbol_name: Optional[str] = None,
|
||||
symbol_type: str = "stock",
|
||||
symbol_decimal_places: int = 2,
|
||||
):
|
||||
"""
|
||||
初始化回测任务
|
||||
@ -38,8 +45,15 @@ class BacktestTask:
|
||||
strategy_name: 策略名称
|
||||
strategy_params: 策略参数字典
|
||||
initial_capital: 初始资金
|
||||
commission_rate: 手续费率
|
||||
slippage_rate: 滑点率
|
||||
trading_type: 交易类型(t0/t1,T+0或T+1)
|
||||
commission_rate: 佣金率(买卖双向收取)
|
||||
min_commission: 最低佣金
|
||||
stamp_tax_rate: 印花税率(仅卖出时收取)
|
||||
transfer_fee_rate: 过户费率(买卖双向收取)
|
||||
slippage: 滑点(买卖双向影响)
|
||||
symbol_name: 标的名称
|
||||
symbol_type: 标的类型(stock/etf/future/option/bond)
|
||||
symbol_decimal_places: 价格小数位数(股票为2,期货/ETF等为3)
|
||||
"""
|
||||
# 参数验证
|
||||
if not symbols:
|
||||
@ -57,8 +71,21 @@ class BacktestTask:
|
||||
self.strategy_name = strategy_name
|
||||
self.strategy_params = strategy_params or {}
|
||||
self.initial_capital = initial_capital
|
||||
|
||||
# 标的信息
|
||||
self.symbol_name = symbol_name
|
||||
self.symbol_type = symbol_type
|
||||
self.symbol_decimal_places = symbol_decimal_places
|
||||
|
||||
# 交易配置
|
||||
self.trading_type = trading_type.lower() # 统一转为小写
|
||||
|
||||
# 交易费率配置
|
||||
self.commission_rate = commission_rate
|
||||
self.slippage_rate = slippage_rate
|
||||
self.min_commission = min_commission
|
||||
self.stamp_tax_rate = stamp_tax_rate
|
||||
self.transfer_fee_rate = transfer_fee_rate
|
||||
self.slippage = slippage
|
||||
|
||||
def __repr__(self) -> str:
|
||||
"""字符串表示"""
|
||||
|
||||
212
src/backtest/bt_task_loader.py
Normal file
212
src/backtest/bt_task_loader.py
Normal file
@ -0,0 +1,212 @@
|
||||
"""
|
||||
回测任务加载器 (Backtest Task Loader)
|
||||
|
||||
从配置文件加载回测任务配置,自动生成 BacktestTask 对象
|
||||
"""
|
||||
|
||||
from typing import Dict, Any
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
import yaml
|
||||
|
||||
from src.backtest.bt_task import BacktestTask
|
||||
from src.core.logger import Logger
|
||||
|
||||
|
||||
class BacktestTaskLoader:
|
||||
"""
|
||||
回测任务加载器
|
||||
|
||||
从策略配置文件(YAML)中读取配置,自动生成回测任务对象
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def load_from_file(config_path: str) -> BacktestTask:
|
||||
"""
|
||||
从配置文件加载回测任务
|
||||
|
||||
Args:
|
||||
config_path: 配置文件路径
|
||||
|
||||
Returns:
|
||||
BacktestTask 对象
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 配置文件不存在
|
||||
ValueError: 配置文件格式错误或缺少必要字段
|
||||
"""
|
||||
# 检查文件是否存在
|
||||
config_file = Path(config_path)
|
||||
if not config_file.exists():
|
||||
raise FileNotFoundError(f"配置文件不存在: {config_path}")
|
||||
|
||||
# 读取 YAML 配置
|
||||
Logger.info(f"加载回测配置: {config_path}")
|
||||
with open(config_file, "r", encoding="utf-8") as f:
|
||||
config = yaml.safe_load(f)
|
||||
|
||||
# 解析并创建任务
|
||||
return BacktestTaskLoader._parse_config(config, config_path)
|
||||
|
||||
@staticmethod
|
||||
def _parse_config(config: Dict[str, Any], config_path: str) -> BacktestTask:
|
||||
"""
|
||||
解析配置字典,生成 BacktestTask 对象
|
||||
|
||||
Args:
|
||||
config: 配置字典
|
||||
config_path: 配置文件路径(用于日志)
|
||||
|
||||
Returns:
|
||||
BacktestTask 对象
|
||||
"""
|
||||
# 验证必要字段
|
||||
required_fields = ["symbol", "strategy_class", "capital"]
|
||||
for field in required_fields:
|
||||
if field not in config:
|
||||
raise ValueError(f"配置文件缺少必要字段: {field}")
|
||||
|
||||
# 检查回测配置
|
||||
if "backtrade" not in config:
|
||||
raise ValueError("配置文件缺少 'backtrade' 回测配置")
|
||||
|
||||
backtrade = config["backtrade"]
|
||||
if "start_date" not in backtrade:
|
||||
raise ValueError("回测配置缺少 'start_date'")
|
||||
if "end_date" not in backtrade:
|
||||
raise ValueError("回测配置缺少 'end_date'")
|
||||
if "period" not in backtrade:
|
||||
raise ValueError("回测配置缺少 'period'")
|
||||
|
||||
# 解析基本信息
|
||||
symbols = [config["symbol"]] # 单个标的转为列表
|
||||
strategy_name = config["strategy_class"]
|
||||
initial_capital = float(config["capital"])
|
||||
|
||||
# 解析日期
|
||||
start_date = BacktestTaskLoader._parse_date(backtrade["start_date"])
|
||||
end_date = BacktestTaskLoader._parse_date(backtrade["end_date"])
|
||||
period = backtrade["period"]
|
||||
|
||||
# 解析策略参数
|
||||
strategy_params = config.get("params", {})
|
||||
|
||||
# 解析标的信息(必填)
|
||||
if "symbol_name" not in config:
|
||||
raise ValueError("配置文件缺少必要字段: symbol_name")
|
||||
if "symbol_type" not in config:
|
||||
raise ValueError("配置文件缺少必要字段: symbol_type")
|
||||
if "symbol_decimal_places" not in config:
|
||||
raise ValueError("配置文件缺少必要字段: symbol_decimal_places")
|
||||
|
||||
symbol_name = config["symbol_name"]
|
||||
symbol_type = config["symbol_type"]
|
||||
symbol_decimal_places = config["symbol_decimal_places"]
|
||||
|
||||
# 解析交易类型(必填)
|
||||
if "trading_type" not in backtrade:
|
||||
raise ValueError("回测配置缺少必要字段: trading_type")
|
||||
trading_type = backtrade["trading_type"]
|
||||
|
||||
# 解析交易费率配置(必填)
|
||||
if "trading_fees" not in backtrade:
|
||||
raise ValueError("回测配置缺少必要字段: trading_fees")
|
||||
|
||||
trading_fees = backtrade["trading_fees"]
|
||||
|
||||
# 验证所有交易费率字段
|
||||
required_fee_fields = [
|
||||
"commission_rate",
|
||||
"min_commission",
|
||||
"stamp_tax_rate",
|
||||
"transfer_fee_rate",
|
||||
"slippage",
|
||||
]
|
||||
for field in required_fee_fields:
|
||||
if field not in trading_fees:
|
||||
raise ValueError(f"交易费率配置缺少必要字段: {field}")
|
||||
|
||||
commission_rate = trading_fees["commission_rate"]
|
||||
min_commission = trading_fees["min_commission"]
|
||||
stamp_tax_rate = trading_fees["stamp_tax_rate"]
|
||||
transfer_fee_rate = trading_fees["transfer_fee_rate"]
|
||||
slippage = trading_fees["slippage"]
|
||||
|
||||
# 创建任务对象
|
||||
task = BacktestTask(
|
||||
symbols=symbols,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
period=period,
|
||||
strategy_name=strategy_name,
|
||||
strategy_params=strategy_params,
|
||||
initial_capital=initial_capital,
|
||||
trading_type=trading_type,
|
||||
commission_rate=commission_rate,
|
||||
min_commission=min_commission,
|
||||
stamp_tax_rate=stamp_tax_rate,
|
||||
transfer_fee_rate=transfer_fee_rate,
|
||||
slippage=slippage,
|
||||
symbol_name=symbol_name,
|
||||
symbol_type=symbol_type,
|
||||
symbol_decimal_places=symbol_decimal_places,
|
||||
)
|
||||
|
||||
Logger.info(f"回测任务加载成功: {task}")
|
||||
Logger.debug(f" 标的: {symbols[0]} ({symbol_name})")
|
||||
Logger.debug(f" 策略: {strategy_name}")
|
||||
Logger.debug(f" 周期: {period}")
|
||||
Logger.debug(f" 时间: {start_date.date()} ~ {end_date.date()}")
|
||||
Logger.debug(f" 初始资金: {initial_capital:,.2f}")
|
||||
Logger.debug(f" 交易类型: {trading_type.upper()}")
|
||||
Logger.debug(
|
||||
f" 佣金率: {commission_rate * 10000:.2f}‱ (最低{min_commission}元)"
|
||||
)
|
||||
Logger.debug(f" 印花税率: {stamp_tax_rate * 10000:.2f}‱ (仅卖出)")
|
||||
Logger.debug(f" 过户费率: {transfer_fee_rate * 10000:.2f}‱")
|
||||
Logger.debug(f" 滑点: {slippage * 10000:.2f}‱")
|
||||
|
||||
return task
|
||||
|
||||
@staticmethod
|
||||
def _parse_date(date_str: str) -> datetime:
|
||||
"""
|
||||
解析日期字符串
|
||||
|
||||
Args:
|
||||
date_str: 日期字符串,支持格式 'YYYY-MM-DD' 或 'YYYYMMDD'
|
||||
|
||||
Returns:
|
||||
datetime 对象
|
||||
"""
|
||||
if isinstance(date_str, datetime):
|
||||
return date_str
|
||||
|
||||
# 尝试不同的日期格式
|
||||
formats = ["%Y-%m-%d", "%Y%m%d", "%Y/%m/%d"]
|
||||
for fmt in formats:
|
||||
try:
|
||||
return datetime.strptime(date_str, fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
raise ValueError(
|
||||
f"无法解析日期格式: {date_str},支持格式: YYYY-MM-DD, YYYYMMDD, YYYY/MM/DD"
|
||||
)
|
||||
|
||||
|
||||
def load_backtest_task(config_path: str) -> BacktestTask:
|
||||
"""
|
||||
便捷函数:从配置文件加载回测任务
|
||||
|
||||
Args:
|
||||
config_path: 配置文件路径
|
||||
|
||||
Returns:
|
||||
BacktestTask 对象
|
||||
|
||||
Example:
|
||||
>>> task = load_backtest_task("configs/strategies/debug_000001.yaml")
|
||||
>>> print(task)
|
||||
"""
|
||||
return BacktestTaskLoader.load_from_file(config_path)
|
||||
@ -10,57 +10,50 @@ 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.backtest.bt_task_loader import BacktestTaskLoader
|
||||
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"],
|
||||
start_date=datetime(2024, 1, 1),
|
||||
end_date=datetime(2024, 12, 31),
|
||||
period="1d",
|
||||
strategy_name="MA_Strategy",
|
||||
strategy_params={"fast_period": 5, "slow_period": 20},
|
||||
initial_capital=100000.0,
|
||||
)
|
||||
task = BacktestTaskLoader.load_from_file("configs/strategies/debug_000001.yaml")
|
||||
|
||||
# Add task
|
||||
engine.add_task(task)
|
||||
|
||||
# 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__":
|
||||
|
||||
5
src/cache/__init__.py
vendored
5
src/cache/__init__.py
vendored
@ -1,10 +1,11 @@
|
||||
"""
|
||||
缓存模块
|
||||
|
||||
提供市场数据和业务数据的内存缓存功能
|
||||
提供市场数据和交易数据的内存缓存功能
|
||||
注意:推荐使用 src.data.DataService 作为统一数据访问接口
|
||||
"""
|
||||
|
||||
from .cache_manager import CacheManager
|
||||
from .trading_cache import TradingCache
|
||||
|
||||
__all__ = ["CacheManager"]
|
||||
__all__ = ["CacheManager", "TradingCache"]
|
||||
|
||||
126
src/cache/cache_manager.py
vendored
126
src/cache/cache_manager.py
vendored
@ -5,8 +5,9 @@
|
||||
职责:只负责数据的存取,不涉及数据加载、验证、计算
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
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,50 +30,149 @@ class CacheManager:
|
||||
- ✗ 指标计算逻辑(由DataService负责)
|
||||
"""
|
||||
|
||||
def __init__(self, config: Union[dict, Config]):
|
||||
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]] = {}
|
||||
|
||||
logger.info(
|
||||
f"CacheManager initialized: enabled={self.enabled}, max_memory={self.max_memory_mb}MB"
|
||||
f"CacheManager initialized: enabled={self.enabled}, max_memory={self.max_memory_mb}MB, "
|
||||
f"db_fallback={'enabled' if db_manager else 'disabled'}"
|
||||
)
|
||||
|
||||
def get_klines(self, symbol: str, period: str) -> Optional[pd.DataFrame]:
|
||||
# 只从cache中获取数据,如果开始时间为空,则返回所有数据
|
||||
def get_klines_from_cache(
|
||||
self,
|
||||
symbol: str,
|
||||
period: str,
|
||||
startdate: Optional[datetime] = None,
|
||||
enddate: Optional[datetime] = None,
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
获取缓存数据(纯Key-Value查询)
|
||||
获取K线数据(纯缓存查询,不访问数据库)
|
||||
|
||||
Args:
|
||||
symbol: 标的代码
|
||||
period: 周期
|
||||
|
||||
startdate: 开始时间(可选),为None时返回所有缓存数据
|
||||
enddate: 结束时间(可选),为None时返回所有缓存数据
|
||||
Returns:
|
||||
缓存中的K线DataFrame或None
|
||||
K线DataFrame或None
|
||||
"""
|
||||
if not self.enabled:
|
||||
return None
|
||||
|
||||
key = self._make_key(symbol, period)
|
||||
|
||||
if key in self._cache:
|
||||
cached = self._cache[key]
|
||||
klines = cached.get("klines")
|
||||
|
||||
if klines is not None and not klines.empty:
|
||||
# 如果没有指定时间范围,返回所有缓存数据
|
||||
if startdate is None or enddate is None:
|
||||
logger.debug(f"Cache query (no filter): {key}, {len(klines)} rows")
|
||||
return klines
|
||||
|
||||
# 根据时间范围过滤
|
||||
filtered_data = klines[
|
||||
(klines.index >= startdate) & (klines.index <= enddate)
|
||||
]
|
||||
logger.debug(
|
||||
f"Cache query (filtered): {key}, "
|
||||
f"{len(filtered_data)} rows from {len(klines)} cached rows"
|
||||
)
|
||||
return filtered_data if not filtered_data.empty else None
|
||||
|
||||
return None
|
||||
|
||||
# 获取指定周期与时间范围的K线数据
|
||||
def get_klines(
|
||||
self, symbol: str, period: str, startdate: datetime, enddate: datetime
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
获取K线数据(带数据库降级和时间范围过滤)
|
||||
|
||||
Args:
|
||||
symbol: 标的代码
|
||||
period: 周期
|
||||
startdate: 开始时间
|
||||
enddate: 结束时间
|
||||
Returns:
|
||||
K线DataFrame或None(已过滤到指定时间范围)
|
||||
"""
|
||||
if not self.enabled:
|
||||
return None
|
||||
|
||||
key = self._make_key(symbol, period)
|
||||
|
||||
# 1. 先查缓存
|
||||
if key in self._cache:
|
||||
cached = self._cache[key]
|
||||
cache_data = cached.get("klines")
|
||||
|
||||
if cache_data is not None and not cache_data.empty:
|
||||
return cache_data
|
||||
# 检查缓存数据的时间范围
|
||||
cache_start = cache_data.index.min()
|
||||
cache_end = cache_data.index.max()
|
||||
|
||||
# 判断缓存是否覆盖请求的时间范围
|
||||
if cache_start <= startdate and cache_end >= enddate:
|
||||
# 缓存完全覆盖,直接过滤返回
|
||||
filtered_data = cache_data[
|
||||
(cache_data.index >= startdate) & (cache_data.index <= enddate)
|
||||
]
|
||||
logger.debug(
|
||||
f"Cache hit: {key}, filtered {len(filtered_data)} rows "
|
||||
f"from {len(cache_data)} cached rows"
|
||||
)
|
||||
return filtered_data if not filtered_data.empty else None
|
||||
else:
|
||||
# 缓存不完全覆盖,需要从数据库重新加载
|
||||
logger.debug(
|
||||
f"Cache partial hit: {key}, "
|
||||
f"cached[{cache_start.date()}~{cache_end.date()}] "
|
||||
f"requested[{startdate.date()}~{enddate.date()}], "
|
||||
f"reloading from database"
|
||||
)
|
||||
|
||||
# 2. 缓存未命中或不完整,尝试从数据库加载
|
||||
if self._db_manager:
|
||||
logger.debug(f"Cache miss: {key}, loading from database")
|
||||
try:
|
||||
# 从数据库加载所有数据(为了缓存完整数据)
|
||||
df = self._db_manager.load_klines_all(symbol, period)
|
||||
|
||||
if df is not None and not df.empty:
|
||||
# 加载成功,填充缓存
|
||||
self.set_klines(symbol, period, {"klines": df})
|
||||
logger.info(
|
||||
f"Loaded {len(df)} rows from database and cached: {key}"
|
||||
)
|
||||
|
||||
# 过滤到请求的时间范围
|
||||
filtered_data = df[(df.index >= startdate) & (df.index <= enddate)]
|
||||
logger.debug(
|
||||
f"Filtered {len(filtered_data)} rows "
|
||||
f"from {len(df)} database rows"
|
||||
)
|
||||
return filtered_data if not filtered_data.empty else None
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load from database: {key}, error: {e}")
|
||||
|
||||
# 3. 数据库也没有
|
||||
return None
|
||||
|
||||
def set_klines(self, symbol: str, period: str, data: Dict[str, Any]) -> None:
|
||||
|
||||
166
src/cache/trading_cache.py
vendored
Normal file
166
src/cache/trading_cache.py
vendored
Normal file
@ -0,0 +1,166 @@
|
||||
"""
|
||||
交易数据缓存管理器
|
||||
|
||||
为 Order, Trade, Position, Asset 提供内存缓存
|
||||
"""
|
||||
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from src.core.models import Order, Trade, Position, Asset
|
||||
from src.core.logger import Logger
|
||||
|
||||
|
||||
class TradingCache:
|
||||
"""
|
||||
交易数据缓存管理器
|
||||
|
||||
提供交易数据的快速内存访问,按策略实例隔离
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""初始化交易缓存"""
|
||||
# 缓存结构:{instance_id: {...}}
|
||||
self._orders: Dict[
|
||||
str, Dict[str, Order]
|
||||
] = {} # {instance_id: {order_id: Order}}
|
||||
self._trades: Dict[str, List[Trade]] = {} # {instance_id: [Trade, ...]}
|
||||
self._positions: Dict[
|
||||
str, Dict[str, Position]
|
||||
] = {} # {instance_id: {symbol: Position}}
|
||||
self._assets: Dict[str, Asset] = {} # {instance_id: Asset}
|
||||
|
||||
Logger.info("TradingCache initialized")
|
||||
|
||||
# ==================== Order 缓存 ====================
|
||||
|
||||
def cache_order(self, order: Order) -> None:
|
||||
"""缓存订单"""
|
||||
if order.instance_id not in self._orders:
|
||||
self._orders[order.instance_id] = {}
|
||||
|
||||
self._orders[order.instance_id][order.order_id] = order
|
||||
Logger.debug(f"Cached order: {order.order_id}")
|
||||
|
||||
def get_order(self, instance_id: str, order_id: str) -> Optional[Order]:
|
||||
"""获取订单"""
|
||||
if instance_id in self._orders:
|
||||
return self._orders[instance_id].get(order_id)
|
||||
return None
|
||||
|
||||
def get_orders_by_instance(self, instance_id: str) -> List[Order]:
|
||||
"""获取实例的所有订单"""
|
||||
if instance_id in self._orders:
|
||||
return list(self._orders[instance_id].values())
|
||||
return []
|
||||
|
||||
def get_orders_by_symbol(self, instance_id: str, symbol: str) -> List[Order]:
|
||||
"""获取实例某个标的的所有订单"""
|
||||
orders = self.get_orders_by_instance(instance_id)
|
||||
return [o for o in orders if o.symbol == symbol]
|
||||
|
||||
# ==================== Trade 缓存 ====================
|
||||
|
||||
def cache_trade(self, trade: Trade) -> None:
|
||||
"""缓存成交记录"""
|
||||
if trade.instance_id not in self._trades:
|
||||
self._trades[trade.instance_id] = []
|
||||
|
||||
self._trades[trade.instance_id].append(trade)
|
||||
Logger.debug(f"Cached trade: {trade.trade_id}")
|
||||
|
||||
def get_trades_by_instance(self, instance_id: str) -> List[Trade]:
|
||||
"""获取实例的所有成交"""
|
||||
return self._trades.get(instance_id, [])
|
||||
|
||||
def get_trades_by_symbol(self, instance_id: str, symbol: str) -> List[Trade]:
|
||||
"""获取实例某个标的的所有成交"""
|
||||
trades = self.get_trades_by_instance(instance_id)
|
||||
return [t for t in trades if t.symbol == symbol]
|
||||
|
||||
def get_trades_by_order(self, instance_id: str, order_id: str) -> List[Trade]:
|
||||
"""获取某个订单的所有成交"""
|
||||
trades = self.get_trades_by_instance(instance_id)
|
||||
return [t for t in trades if t.order_id == order_id]
|
||||
|
||||
# ==================== Position 缓存 ====================
|
||||
|
||||
def cache_position(self, position: Position) -> None:
|
||||
"""缓存持仓"""
|
||||
if position.instance_id not in self._positions:
|
||||
self._positions[position.instance_id] = {}
|
||||
|
||||
self._positions[position.instance_id][position.symbol] = position
|
||||
Logger.debug(f"Cached position: {position.instance_id}_{position.symbol}")
|
||||
|
||||
def get_position(self, instance_id: str, symbol: str) -> Optional[Position]:
|
||||
"""获取持仓"""
|
||||
if instance_id in self._positions:
|
||||
return self._positions[instance_id].get(symbol)
|
||||
return None
|
||||
|
||||
def get_positions_by_instance(self, instance_id: str) -> List[Position]:
|
||||
"""获取实例的所有持仓"""
|
||||
if instance_id in self._positions:
|
||||
return list(self._positions[instance_id].values())
|
||||
return []
|
||||
|
||||
def remove_position(self, instance_id: str, symbol: str) -> None:
|
||||
"""移除持仓(持仓为0时)"""
|
||||
if instance_id in self._positions and symbol in self._positions[instance_id]:
|
||||
del self._positions[instance_id][symbol]
|
||||
Logger.debug(f"Removed position: {instance_id}_{symbol}")
|
||||
|
||||
# ==================== Asset 缓存 ====================
|
||||
|
||||
def cache_asset(self, asset: Asset) -> None:
|
||||
"""缓存资产"""
|
||||
self._assets[asset.instance_id] = asset
|
||||
Logger.debug(f"Cached asset: {asset.instance_id}")
|
||||
|
||||
def get_asset(self, instance_id: str) -> Optional[Asset]:
|
||||
"""获取资产"""
|
||||
return self._assets.get(instance_id)
|
||||
|
||||
def get_all_assets(self) -> List[Asset]:
|
||||
"""获取所有资产"""
|
||||
return list(self._assets.values())
|
||||
|
||||
# ==================== 批量操作 ====================
|
||||
|
||||
def clear_instance(self, instance_id: str) -> None:
|
||||
"""清除实例的所有缓存数据"""
|
||||
if instance_id in self._orders:
|
||||
del self._orders[instance_id]
|
||||
if instance_id in self._trades:
|
||||
del self._trades[instance_id]
|
||||
if instance_id in self._positions:
|
||||
del self._positions[instance_id]
|
||||
if instance_id in self._assets:
|
||||
del self._assets[instance_id]
|
||||
|
||||
Logger.info(f"Cleared cache for instance: {instance_id}")
|
||||
|
||||
def clear_all(self) -> None:
|
||||
"""清除所有缓存"""
|
||||
self._orders.clear()
|
||||
self._trades.clear()
|
||||
self._positions.clear()
|
||||
self._assets.clear()
|
||||
|
||||
Logger.info("Cleared all trading cache")
|
||||
|
||||
# ==================== 统计信息 ====================
|
||||
|
||||
def get_stats(self) -> Dict[str, int]:
|
||||
"""获取缓存统计信息"""
|
||||
total_orders = sum(len(orders) for orders in self._orders.values())
|
||||
total_trades = sum(len(trades) for trades in self._trades.values())
|
||||
total_positions = sum(len(positions) for positions in self._positions.values())
|
||||
|
||||
return {
|
||||
"instances": len(self._assets),
|
||||
"orders": total_orders,
|
||||
"trades": total_trades,
|
||||
"positions": total_positions,
|
||||
"assets": len(self._assets),
|
||||
}
|
||||
@ -19,25 +19,15 @@ from .models import (
|
||||
Order,
|
||||
Trade,
|
||||
Position,
|
||||
Account,
|
||||
Asset,
|
||||
Signal,
|
||||
Symbol,
|
||||
)
|
||||
|
||||
# 配置管理
|
||||
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__ = [
|
||||
# 枚举
|
||||
@ -54,20 +44,10 @@ __all__ = [
|
||||
"Order",
|
||||
"Trade",
|
||||
"Position",
|
||||
"Account",
|
||||
"Asset",
|
||||
"Signal",
|
||||
"Symbol",
|
||||
# 配置
|
||||
"Config",
|
||||
"get_config",
|
||||
"set_config",
|
||||
# 日志
|
||||
"Logger",
|
||||
"get_logger",
|
||||
"set_log_level",
|
||||
"debug",
|
||||
"info",
|
||||
"warning",
|
||||
"error",
|
||||
"exception",
|
||||
]
|
||||
|
||||
106
src/core/base_strategy.py
Normal file
106
src/core/base_strategy.py
Normal file
@ -0,0 +1,106 @@
|
||||
"""
|
||||
策略基类 (BaseStrategy)
|
||||
|
||||
所有策略必须继承此基类
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Dict, Any, Optional
|
||||
import logging
|
||||
|
||||
from src.core.strategy_context import StrategyContext
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BaseStrategy(ABC):
|
||||
"""
|
||||
策略基类
|
||||
|
||||
所有策略都应该继承此类并实现 compute 方法
|
||||
"""
|
||||
|
||||
def __init__(self, context: StrategyContext, **params):
|
||||
"""
|
||||
初始化策略
|
||||
|
||||
Args:
|
||||
context: 策略上下文
|
||||
**params: 策略参数
|
||||
"""
|
||||
self.context: StrategyContext = context
|
||||
self.params: Dict[str, Any] = params
|
||||
|
||||
logger.info(
|
||||
f"Strategy initialized: instance_id={context.instance_id}, "
|
||||
f"symbol={context.symbol}, params={params}"
|
||||
)
|
||||
|
||||
@abstractmethod
|
||||
def compute(self, kline_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
计算信号(必须实现)
|
||||
|
||||
Args:
|
||||
kline_data: K线数据字典
|
||||
{
|
||||
'symbol': str,
|
||||
'timestamp': str,
|
||||
'open': float,
|
||||
'high': float,
|
||||
'low': float,
|
||||
'close': float,
|
||||
'volume': float
|
||||
}
|
||||
|
||||
Returns:
|
||||
信号字典或None
|
||||
{
|
||||
'action': 'BUY' | 'SELL' | 'HOLD',
|
||||
'symbol': str,
|
||||
'price': float,
|
||||
'quantity': int,
|
||||
'reason': str # 可选
|
||||
}
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_init(self):
|
||||
"""
|
||||
初始化回调(可选实现)
|
||||
|
||||
在策略加载完成后调用,可以在这里做一些初始化工作
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_trade(self, trade_result: Dict[str, Any]):
|
||||
"""
|
||||
交易回调(可选实现)
|
||||
|
||||
在交易执行后调用
|
||||
|
||||
Args:
|
||||
trade_result: 交易结果
|
||||
{
|
||||
'action': str,
|
||||
'symbol': str,
|
||||
'price': float,
|
||||
'quantity': int,
|
||||
'success': bool,
|
||||
'message': str
|
||||
}
|
||||
"""
|
||||
pass
|
||||
|
||||
def on_error(self, error: Exception):
|
||||
"""
|
||||
错误回调(可选实现)
|
||||
|
||||
在策略执行出错时调用
|
||||
|
||||
Args:
|
||||
error: 异常对象
|
||||
"""
|
||||
logger.error(
|
||||
f"Strategy error in {self.context.instance_id}: {error}", exc_info=True
|
||||
)
|
||||
125
src/core/capital.py
Normal file
125
src/core/capital.py
Normal file
@ -0,0 +1,125 @@
|
||||
"""
|
||||
资金管理 (Capital)
|
||||
|
||||
管理单个策略实例的资金信息
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Capital:
|
||||
"""
|
||||
资金信息(独立状态)
|
||||
|
||||
每个策略实例拥有独立的资金账户
|
||||
"""
|
||||
|
||||
initial_cash: float # 初始资金
|
||||
available_cash: float = 0.0 # 可用资金
|
||||
frozen_cash: float = 0.0 # 冻结资金
|
||||
|
||||
def __post_init__(self):
|
||||
"""初始化后设置可用资金"""
|
||||
if self.available_cash == 0.0:
|
||||
self.available_cash = self.initial_cash
|
||||
|
||||
@property
|
||||
def total_cash(self) -> float:
|
||||
"""总资金"""
|
||||
return self.available_cash + self.frozen_cash
|
||||
|
||||
@property
|
||||
def cash_usage_ratio(self) -> float:
|
||||
"""资金使用率"""
|
||||
if self.initial_cash == 0:
|
||||
return 0.0
|
||||
return (self.initial_cash - self.available_cash) / self.initial_cash
|
||||
|
||||
def freeze(self, amount: float) -> bool:
|
||||
"""
|
||||
冻结资金
|
||||
|
||||
Args:
|
||||
amount: 冻结金额
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
if amount <= 0:
|
||||
logger.error(f"Invalid freeze amount: {amount}")
|
||||
return False
|
||||
|
||||
if self.available_cash < amount:
|
||||
logger.warning(
|
||||
f"Insufficient cash: available={self.available_cash:.2f}, "
|
||||
f"required={amount:.2f}"
|
||||
)
|
||||
return False
|
||||
|
||||
self.available_cash -= amount
|
||||
self.frozen_cash += amount
|
||||
|
||||
logger.debug(
|
||||
f"Cash frozen: amount={amount:.2f}, "
|
||||
f"available={self.available_cash:.2f}, "
|
||||
f"frozen={self.frozen_cash:.2f}"
|
||||
)
|
||||
return True
|
||||
|
||||
def unfreeze(self, amount: float) -> bool:
|
||||
"""
|
||||
解冻资金
|
||||
|
||||
Args:
|
||||
amount: 解冻金额
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
if amount <= 0:
|
||||
logger.error(f"Invalid unfreeze amount: {amount}")
|
||||
return False
|
||||
|
||||
if self.frozen_cash < amount:
|
||||
logger.error(
|
||||
f"Insufficient frozen cash: frozen={self.frozen_cash:.2f}, "
|
||||
f"amount={amount:.2f}"
|
||||
)
|
||||
return False
|
||||
|
||||
self.frozen_cash -= amount
|
||||
self.available_cash += amount
|
||||
|
||||
logger.debug(
|
||||
f"Cash unfrozen: amount={amount:.2f}, "
|
||||
f"available={self.available_cash:.2f}, "
|
||||
f"frozen={self.frozen_cash:.2f}"
|
||||
)
|
||||
return True
|
||||
|
||||
def update(self, amount: float):
|
||||
"""
|
||||
更新资金(盈亏结算)
|
||||
|
||||
Args:
|
||||
amount: 变化金额(正数为盈利,负数为亏损)
|
||||
"""
|
||||
self.available_cash += amount
|
||||
logger.debug(
|
||||
f"Capital updated: amount={amount:+.2f}, "
|
||||
f"available={self.available_cash:.2f}"
|
||||
)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""转换为字典"""
|
||||
return {
|
||||
"initial_cash": self.initial_cash,
|
||||
"available_cash": self.available_cash,
|
||||
"frozen_cash": self.frozen_cash,
|
||||
"total_cash": self.total_cash,
|
||||
"cash_usage_ratio": self.cash_usage_ratio,
|
||||
}
|
||||
@ -1,54 +1,212 @@
|
||||
"""
|
||||
配置管理工具类
|
||||
支持读取、修改和保存 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 加载对应环境配置
|
||||
- 支持显式指定环境名称或配置文件路径
|
||||
- 配置文件不存在时自动回退到 global.yaml 并发出警告
|
||||
- 通过类方法直接访问,无需传递实例
|
||||
|
||||
使用示例:
|
||||
# 方式1: 自动读取 global.yaml 的 current_mode
|
||||
Config.initialize()
|
||||
|
||||
# 方式2: 显式指定环境名称
|
||||
Config.initialize("backtest") # 回测环境
|
||||
Config.initialize("simulation") # 模拟环境
|
||||
Config.initialize("production") # 生产环境
|
||||
|
||||
# 方式3: 指定配置文件路径
|
||||
Config.initialize("configs/custom.yaml")
|
||||
|
||||
# 获取配置(任意位置直接调用)
|
||||
db_host = Config.get("database.host")
|
||||
db_name = Config.get("database.database")
|
||||
|
||||
# 环境判断
|
||||
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, env_mode: Union[str, Path, None] = None) -> "Config":
|
||||
"""
|
||||
初始化配置对象
|
||||
初始化配置(程序入口调用一次)
|
||||
|
||||
工作流程:
|
||||
1. 如果 env_mode 是完整路径(Path 或包含 / \\ 的字符串),直接加载该配置文件
|
||||
2. 如果 env_mode 是环境名称字符串(如 "backtest"),加载对应的配置文件
|
||||
3. 如果环境配置文件不存在,回退到 global.yaml 并发出警告
|
||||
4. 如果 env_mode 为 None,先读取 global.yaml 获取 current_mode,然后加载对应配置
|
||||
|
||||
Args:
|
||||
config_file: 配置文件路径,支持相对路径和绝对路径
|
||||
如果为 None,从环境变量 CONFIG_FILE 读取
|
||||
env_mode: 环境模式或配置文件路径
|
||||
- None: 自动从 global.yaml 读取 current_mode
|
||||
- "backtest" / "simulation" / "production": 环境名称
|
||||
- Path 或文件路径字符串: 直接加载指定文件
|
||||
|
||||
Returns:
|
||||
Config 实例
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: global.yaml 不存在
|
||||
ValueError: current_mode 值无效
|
||||
|
||||
Examples:
|
||||
>>> Config.initialize() # 自动读取 global.yaml 的 current_mode
|
||||
>>> Config.initialize("backtest") # 显式指定回测环境
|
||||
>>> Config.initialize("production") # 显式指定生产环境
|
||||
>>> Config.initialize("configs/custom.yaml") # 指定配置文件路径
|
||||
"""
|
||||
self._data: Dict[str, Any] = {}
|
||||
self._config_file: Optional[Path] = None
|
||||
if cls._initialized and env_mode 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)
|
||||
# 判断是否为文件路径(包含路径分隔符或是 Path 对象)
|
||||
is_file_path = False
|
||||
if env_mode is not None:
|
||||
if isinstance(env_mode, Path):
|
||||
is_file_path = True
|
||||
elif isinstance(env_mode, str) and (
|
||||
"/" in env_mode
|
||||
or "\\" in env_mode
|
||||
or env_mode.endswith(".yaml")
|
||||
or env_mode.endswith(".yml")
|
||||
):
|
||||
is_file_path = True
|
||||
|
||||
def load(self, config_file: Union[str, Path], merge: bool = False) -> "Config":
|
||||
if is_file_path:
|
||||
# 直接加载指定的配置文件
|
||||
if env_mode is not None: # 类型守卫
|
||||
instance._load(env_mode)
|
||||
cls._current_mode = cls.get("environment.mode", "unknown")
|
||||
elif env_mode is not None:
|
||||
# 环境名称字符串(如 "backtest", "simulation", "production")
|
||||
env_name = str(env_mode).lower()
|
||||
|
||||
# 验证环境名称
|
||||
valid_envs = ["backtest", "simulation", "production"]
|
||||
if env_name not in valid_envs:
|
||||
print(
|
||||
f"[WARNING] 未知的环境名称: {env_name},有效值为: {', '.join(valid_envs)}。"
|
||||
f"回退到使用 global.yaml"
|
||||
)
|
||||
# 回退到 global.yaml
|
||||
instance._load_global_config()
|
||||
cls._current_mode = "unknown"
|
||||
else:
|
||||
# 尝试加载对应的环境配置文件
|
||||
config_path = Path(cls.CONFIG_DIR) / f"{env_name}.yaml"
|
||||
if config_path.exists():
|
||||
instance._load(config_path)
|
||||
cls._current_mode = env_name
|
||||
else:
|
||||
# 配置文件不存在,回退到 global.yaml
|
||||
print(
|
||||
f"[WARNING] 环境配置文件不存在: {config_path}。回退到使用 global.yaml"
|
||||
)
|
||||
instance._load_global_config()
|
||||
cls._current_mode = env_name # 保留环境名称,但使用 global 配置
|
||||
else:
|
||||
# env_mode 为 None:先读取 global.yaml 获取 current_mode
|
||||
global_path = Path(cls.GLOBAL_CONFIG_PATH)
|
||||
if not global_path.exists():
|
||||
raise FileNotFoundError(f"全局配置文件不存在: {global_path}")
|
||||
|
||||
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():
|
||||
# 配置文件不存在,回退到 global.yaml
|
||||
print(
|
||||
f"[WARNING] 环境配置文件不存在: {config_path}。回退到使用 global.yaml"
|
||||
)
|
||||
instance._load_global_config()
|
||||
cls._current_mode = current_mode
|
||||
else:
|
||||
instance._load(config_path)
|
||||
cls._current_mode = current_mode
|
||||
|
||||
cls._initialized = True
|
||||
return instance
|
||||
|
||||
def _load_global_config(self) -> None:
|
||||
"""
|
||||
加载配置文件
|
||||
加载 global.yaml 配置(内部方法)
|
||||
当环境配置文件不存在时,回退使用此配置
|
||||
"""
|
||||
global_path = Path(Config.GLOBAL_CONFIG_PATH)
|
||||
if not global_path.exists():
|
||||
raise FileNotFoundError(f"全局配置文件不存在: {global_path}")
|
||||
|
||||
with open(global_path, "r", encoding="utf-8") as f:
|
||||
Config._data = yaml.safe_load(f) or {}
|
||||
|
||||
Config._config_file = global_path
|
||||
|
||||
@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 +219,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 +291,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)})"
|
||||
|
||||
@ -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:
|
||||
"""
|
||||
错误码常量
|
||||
|
||||
@ -1,202 +1,208 @@
|
||||
"""
|
||||
日志工具类
|
||||
支持四个级别的日志记录: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, List
|
||||
|
||||
from .config import get_config
|
||||
from .config import Config
|
||||
|
||||
|
||||
class LevelFilter(logging.Filter):
|
||||
"""
|
||||
日志级别过滤器
|
||||
只允许在指定级别列表中的日志通过
|
||||
"""
|
||||
|
||||
def __init__(self, allowed_levels: List[str]):
|
||||
"""
|
||||
初始化过滤器
|
||||
|
||||
Args:
|
||||
allowed_levels: 允许的日志级别列表,如 ["ERROR", "WARNING", "INFO"]
|
||||
"""
|
||||
super().__init__()
|
||||
self.allowed_levels = {
|
||||
getattr(logging, level.upper()) for level in allowed_levels
|
||||
}
|
||||
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
"""
|
||||
判断日志记录是否应该被输出
|
||||
|
||||
Args:
|
||||
record: 日志记录对象
|
||||
|
||||
Returns:
|
||||
True 如果该级别在允许列表中,否则 False
|
||||
"""
|
||||
return record.levelno in self.allowed_levels
|
||||
|
||||
|
||||
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 实例
|
||||
|
||||
def __init__(self, name: str = "QTrade"):
|
||||
"""
|
||||
初始化日志对象
|
||||
|
||||
Args:
|
||||
name: 日志名称,用于区分不同模块
|
||||
"""
|
||||
self.name = name
|
||||
self.logger = logging.getLogger(name)
|
||||
|
||||
# 避免重复添加 handler
|
||||
if not self.logger.handlers:
|
||||
self._setup_logger()
|
||||
|
||||
def _setup_logger(self):
|
||||
"""配置日志"""
|
||||
# 读取配置
|
||||
config = get_config()
|
||||
|
||||
# 日志级别
|
||||
level_str = config.get("logging.level", "INFO")
|
||||
level = getattr(logging, level_str.upper(), logging.INFO)
|
||||
self.logger.setLevel(level)
|
||||
|
||||
# 日志格式
|
||||
log_format = config.get(
|
||||
"logging.format", "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
)
|
||||
formatter = logging.Formatter(log_format)
|
||||
|
||||
# 控制台处理器(设置UTF-8编码避免中文乱码)
|
||||
import io
|
||||
|
||||
# 包装stdout为UTF-8流
|
||||
utf8_stdout = io.TextIOWrapper(
|
||||
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)
|
||||
|
||||
# 文件处理器
|
||||
if config.get("logging.file.enabled", True):
|
||||
log_path = config.get("logging.file.path", "logs")
|
||||
max_size = config.get("logging.file.max_size", 10485760) # 10MB
|
||||
backup_count = config.get("logging.file.backup_count", 5)
|
||||
|
||||
# 创建日志目录
|
||||
log_dir = Path(log_path)
|
||||
if not log_dir.is_absolute():
|
||||
# 相对路径,相对于项目根目录
|
||||
project_root = Path(__file__).parent.parent.parent
|
||||
log_dir = project_root / log_path
|
||||
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 日志文件路径
|
||||
log_file = log_dir / f"{self.name}.log"
|
||||
|
||||
# 使用 RotatingFileHandler 进行日志轮转
|
||||
file_handler = RotatingFileHandler(
|
||||
log_file, maxBytes=max_size, backupCount=backup_count, encoding="utf-8"
|
||||
)
|
||||
file_handler.setLevel(level)
|
||||
file_handler.setFormatter(formatter)
|
||||
self.logger.addHandler(file_handler)
|
||||
|
||||
def debug(self, message: str, *args, **kwargs):
|
||||
"""记录 DEBUG 级别日志"""
|
||||
self.logger.debug(message, *args, **kwargs)
|
||||
|
||||
def info(self, message: str, *args, **kwargs):
|
||||
"""记录 INFO 级别日志"""
|
||||
self.logger.info(message, *args, **kwargs)
|
||||
|
||||
def warning(self, message: str, *args, **kwargs):
|
||||
"""记录 WARNING 级别日志"""
|
||||
self.logger.warning(message, *args, **kwargs)
|
||||
|
||||
def error(self, message: str, *args, **kwargs):
|
||||
"""记录 ERROR 级别日志"""
|
||||
self.logger.error(message, *args, **kwargs)
|
||||
|
||||
def exception(self, message: str, *args, **kwargs):
|
||||
"""记录 ERROR 级别日志,并包含异常堆栈信息"""
|
||||
self.logger.exception(message, *args, **kwargs)
|
||||
# ==================== 单例相关 ====================
|
||||
_loggers: Dict[str, logging.Logger] = {}
|
||||
_initialized: bool = False
|
||||
_default_name: str = "QTrade"
|
||||
|
||||
@classmethod
|
||||
def get_logger(cls, name: str = "QTrade") -> "Logger":
|
||||
def initialize(cls, default_name: str = "QTrade", level: str = "INFO") -> None:
|
||||
"""
|
||||
获取指定名称的日志实例(单例模式)
|
||||
初始化日志系统(程序入口调用一次)
|
||||
|
||||
Args:
|
||||
name: 日志名称
|
||||
|
||||
Returns:
|
||||
Logger 实例
|
||||
|
||||
Examples:
|
||||
>>> logger = Logger.get_logger("QTrade")
|
||||
>>> logger.info("系统启动")
|
||||
default_name: 默认日志器名称
|
||||
"""
|
||||
if name not in cls._instances:
|
||||
cls._instances[name] = cls(name)
|
||||
return cls._instances[name]
|
||||
if cls._initialized:
|
||||
return
|
||||
|
||||
cls._default_name = default_name
|
||||
cls._get_or_create_logger(default_name, level)
|
||||
cls._initialized = True
|
||||
|
||||
# 全局日志实例
|
||||
_global_logger: Optional[Logger] = None
|
||||
@classmethod
|
||||
def _get_or_create_logger(cls, name: str, level: str = "INFO") -> logging.Logger:
|
||||
"""获取或创建日志器"""
|
||||
if name in cls._loggers:
|
||||
return cls._loggers[name]
|
||||
|
||||
logger = logging.getLogger(name)
|
||||
|
||||
def get_logger(name: str = "QTrade") -> Logger:
|
||||
"""
|
||||
获取日志实例
|
||||
if not logger.handlers:
|
||||
cls._setup_logger(logger, name, level)
|
||||
|
||||
Args:
|
||||
name: 日志名称,用于区分不同模块
|
||||
cls._loggers[name] = logger
|
||||
return logger
|
||||
|
||||
Returns:
|
||||
Logger 实例
|
||||
@classmethod
|
||||
def _setup_logger(
|
||||
cls, logger: logging.Logger, name: str, level: str = "INFO"
|
||||
) -> None:
|
||||
"""配置日志器"""
|
||||
|
||||
Examples:
|
||||
>>> from src.core import get_logger
|
||||
>>> logger = get_logger("Strategy")
|
||||
>>> logger.info("策略初始化完成")
|
||||
>>> logger.error("策略执行失败")
|
||||
"""
|
||||
return Logger.get_logger(name)
|
||||
# 设置为最低级别DEBUG,由Filter控制实际输出
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
# 日志格式
|
||||
log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
formatter = logging.Formatter(log_format)
|
||||
|
||||
def set_log_level(level: str):
|
||||
"""
|
||||
动态设置日志级别
|
||||
# 从配置读取允许的日志级别列表
|
||||
prompt_levels = Config.get("logging.prompt_level", ["INFO", "WARNING", "ERROR"])
|
||||
level_filter = LevelFilter(prompt_levels)
|
||||
|
||||
Args:
|
||||
level: 日志级别 DEBUG, INFO, WARNING, ERROR
|
||||
# 控制台处理器(UTF-8编码)
|
||||
utf8_stdout = io.TextIOWrapper(
|
||||
sys.stdout.buffer,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
line_buffering=True,
|
||||
)
|
||||
console_handler = logging.StreamHandler(utf8_stdout)
|
||||
console_handler.setLevel(logging.DEBUG) # Handler级别设为DEBUG
|
||||
console_handler.setFormatter(formatter)
|
||||
console_handler.addFilter(level_filter) # 添加级别过滤器
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
Examples:
|
||||
>>> from src.core import set_log_level
|
||||
>>> set_log_level("DEBUG")
|
||||
"""
|
||||
level_value = getattr(logging, level.upper(), logging.INFO)
|
||||
# 文件处理器
|
||||
if Config.get("logging.enabled"):
|
||||
log_path = Config.get("logging.filepath")
|
||||
log_dir = Path(log_path)
|
||||
|
||||
# 更新所有已创建的 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)
|
||||
if log_dir.is_absolute():
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
log_file = log_dir / f"{name}.log"
|
||||
|
||||
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(logging.DEBUG) # Handler级别设为DEBUG
|
||||
file_handler.setFormatter(formatter)
|
||||
file_handler.addFilter(level_filter) # 添加级别过滤器
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
# 便捷函数
|
||||
def debug(message: str, *args, **kwargs):
|
||||
"""记录 DEBUG 级别日志"""
|
||||
get_logger().debug(message, *args, **kwargs)
|
||||
@classmethod
|
||||
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)
|
||||
|
||||
def info(message: str, *args, **kwargs):
|
||||
"""记录 INFO 级别日志"""
|
||||
get_logger().info(message, *args, **kwargs)
|
||||
# ==================== 日志方法 ====================
|
||||
@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)
|
||||
|
||||
def warning(message: str, *args, **kwargs):
|
||||
"""记录 WARNING 级别日志"""
|
||||
get_logger().warning(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)
|
||||
|
||||
def error(message: str, *args, **kwargs):
|
||||
"""记录 ERROR 级别日志"""
|
||||
get_logger().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:
|
||||
"""
|
||||
设置所有日志器的级别
|
||||
|
||||
def exception(message: str, *args, **kwargs):
|
||||
"""记录 ERROR 级别日志,并包含异常堆栈信息"""
|
||||
get_logger().exception(message, *args, **kwargs)
|
||||
Args:
|
||||
level: 日志级别 DEBUG, INFO, WARNING, ERROR
|
||||
"""
|
||||
level_value = getattr(logging, level.upper())
|
||||
if level_value is None:
|
||||
raise ValueError(f"无效的日志级别: {level}")
|
||||
|
||||
for logger in cls._loggers.values():
|
||||
logger.setLevel(level_value)
|
||||
for handler in logger.handlers:
|
||||
handler.setLevel(level_value)
|
||||
|
||||
@ -23,11 +23,10 @@ from .trade import Trade
|
||||
|
||||
# 持仓账户对象
|
||||
from .position import Position
|
||||
from .account import Account
|
||||
from .account import Asset # Account重命名为Asset
|
||||
|
||||
# 策略标的对象
|
||||
# 策略信号对象
|
||||
from .signal import Signal
|
||||
from .symbol import Symbol
|
||||
|
||||
__all__ = [
|
||||
# 枚举
|
||||
@ -44,7 +43,6 @@ __all__ = [
|
||||
"Order",
|
||||
"Trade",
|
||||
"Position",
|
||||
"Account",
|
||||
"Asset",
|
||||
"Signal",
|
||||
"Symbol",
|
||||
]
|
||||
|
||||
@ -1,48 +1,85 @@
|
||||
"""
|
||||
账户对象
|
||||
资产账户对象
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class Account(BaseModel):
|
||||
class Asset(BaseModel):
|
||||
"""
|
||||
账户(可变)
|
||||
|
||||
资产账户(可变)
|
||||
|
||||
示例:
|
||||
account = Account(
|
||||
account_id="ACC_001",
|
||||
asset = Asset(
|
||||
instance_id="debug_000001",
|
||||
strategy_name="DebugStrategy",
|
||||
initial_capital=1000000.0,
|
||||
total_asset=1000000.0,
|
||||
available_cash=500000.0,
|
||||
cash=500000.0,
|
||||
update_time=datetime.now()
|
||||
)
|
||||
"""
|
||||
account_id: str = Field(..., description="账户ID", min_length=1)
|
||||
|
||||
|
||||
# 基本信息
|
||||
instance_id: str = Field(..., description="策略实例ID", min_length=1)
|
||||
strategy_name: str = Field(..., description="策略类名", min_length=1)
|
||||
|
||||
# 资金信息
|
||||
total_asset: float = Field(
|
||||
...,
|
||||
description="总资产 = available_cash + frozen_cash + market_value",
|
||||
ge=0
|
||||
)
|
||||
initial_capital: float = Field(..., description="初始资金", gt=0)
|
||||
total_asset: float = Field(..., description="总资产", ge=0)
|
||||
cash: float = Field(..., description="现金", ge=0)
|
||||
available_cash: float = Field(..., description="可用资金", ge=0)
|
||||
frozen_cash: float = Field(0.0, description="冻结资金(挂单冻结)", ge=0)
|
||||
|
||||
# 市值信息
|
||||
market_value: float = Field(0.0, description="持仓市值", ge=0)
|
||||
|
||||
long_market_value: float = Field(0.0, description="多头市值", ge=0)
|
||||
short_market_value: float = Field(0.0, description="空头市值(期货)", ge=0)
|
||||
|
||||
# 盈亏信息
|
||||
total_pnl: float = Field(0.0, description="总盈亏")
|
||||
total_return: float = Field(0.0, description="总收益率")
|
||||
unrealized_pnl: float = Field(0.0, description="浮动盈亏")
|
||||
realized_pnl: float = Field(0.0, description="已实现盈亏")
|
||||
|
||||
# 当日数据
|
||||
daily_pnl: float = Field(0.0, description="当日盈亏")
|
||||
|
||||
daily_return: float = Field(0.0, description="当日收益率")
|
||||
pre_total_asset: float = Field(0.0, description="前一日总资产")
|
||||
|
||||
# 交易成本统计
|
||||
total_commission: float = Field(0.0, description="累计佣金", ge=0)
|
||||
total_stamp_tax: float = Field(0.0, description="累计印花税", ge=0)
|
||||
total_transfer_fee: float = Field(0.0, description="累计过户费", ge=0)
|
||||
total_slippage: float = Field(0.0, description="累计滑点成本", ge=0)
|
||||
total_cost: float = Field(0.0, description="累计总成本", ge=0)
|
||||
trade_count: int = Field(0, description="交易次数", ge=0)
|
||||
|
||||
# 风控指标
|
||||
max_drawdown: float = Field(0.0, description="最大回撤")
|
||||
max_drawdown_ratio: float = Field(0.0, description="最大回撤率")
|
||||
leverage: float = Field(0.0, description="杠杆率", ge=0)
|
||||
|
||||
# 时间信息
|
||||
init_time: Optional[datetime] = Field(None, description="账户初始化时间")
|
||||
last_trade_time: Optional[datetime] = Field(None, description="最后交易时间")
|
||||
update_time: datetime = Field(..., description="更新时间")
|
||||
|
||||
|
||||
def model_post_init(self, __context) -> None:
|
||||
"""对象创建后验证总资产一致性"""
|
||||
calculated_total = self.available_cash + self.frozen_cash + self.market_value
|
||||
calculated_total = self.cash + self.market_value
|
||||
# 允许0.01的误差(浮点数精度)
|
||||
if abs(self.total_asset - calculated_total) > 0.01:
|
||||
raise ValueError(
|
||||
f'总资产({self.total_asset})必须等于 '
|
||||
f'可用资金({self.available_cash}) + '
|
||||
f'冻结资金({self.frozen_cash}) + '
|
||||
f'持仓市值({self.market_value}) = {calculated_total}'
|
||||
f"总资产({self.total_asset})必须等于 "
|
||||
f"现金({self.cash}) + "
|
||||
f"持仓市值({self.market_value}) = {calculated_total}"
|
||||
)
|
||||
|
||||
# 验证可用资金
|
||||
if self.available_cash > self.cash:
|
||||
raise ValueError(
|
||||
f"可用资金({self.available_cash})不能大于现金({self.cash})"
|
||||
)
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from typing import Optional, Dict, Any
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from .enums import OrderSide, OrderType, OrderStatus
|
||||
|
||||
@ -15,7 +15,10 @@ class Order(BaseModel):
|
||||
示例:
|
||||
order = Order(
|
||||
order_id="ORD_20240101_001",
|
||||
instance_id="debug_000001",
|
||||
strategy_name="DebugStrategy",
|
||||
symbol="000001.SZ",
|
||||
symbol_name="平安银行",
|
||||
side=OrderSide.BUY,
|
||||
order_type=OrderType.LIMIT,
|
||||
price=10.5,
|
||||
@ -25,20 +28,39 @@ class Order(BaseModel):
|
||||
)
|
||||
"""
|
||||
|
||||
# 基本信息
|
||||
order_id: str = Field(..., description="订单ID(唯一)", min_length=1)
|
||||
instance_id: str = Field(..., description="策略实例ID", min_length=1)
|
||||
strategy_name: str = Field(..., description="策略类名", min_length=1)
|
||||
|
||||
# 标的信息
|
||||
symbol: str = Field(..., description="标的代码", min_length=1)
|
||||
symbol_name: Optional[str] = Field(None, description="标的名称")
|
||||
|
||||
# 订单信息
|
||||
side: OrderSide = Field(..., description="方向")
|
||||
order_type: OrderType = Field(..., description="订单类型")
|
||||
price: float = Field(..., description="价格", ge=0)
|
||||
volume: int = Field(..., description="数量", gt=0)
|
||||
price: float = Field(..., description="委托价格", ge=0)
|
||||
volume: int = Field(..., description="委托数量", gt=0)
|
||||
|
||||
# 成交信息
|
||||
filled_volume: int = Field(0, description="已成交数量", ge=0)
|
||||
filled_price: float = Field(0.0, description="成交均价", ge=0)
|
||||
actual_price: float = Field(0.0, description="实际价格(含滑点)", ge=0)
|
||||
status: OrderStatus = Field(OrderStatus.PENDING, description="状态")
|
||||
|
||||
create_time: datetime = Field(..., description="创建时间")
|
||||
update_time: datetime = Field(..., description="更新时间")
|
||||
cancel_time: Optional[datetime] = Field(None, description="撤销时间")
|
||||
# 成本信息
|
||||
cost_detail: Optional[Dict[str, Any]] = Field(None, description="成本明细")
|
||||
|
||||
strategy_name: Optional[str] = Field(None, description="来源策略")
|
||||
# 时间信息
|
||||
create_time: datetime = Field(..., description="创建时间")
|
||||
submit_time: Optional[datetime] = Field(None, description="提交时间")
|
||||
filled_time: Optional[datetime] = Field(None, description="完全成交时间")
|
||||
cancel_time: Optional[datetime] = Field(None, description="撤销时间")
|
||||
update_time: datetime = Field(..., description="更新时间")
|
||||
|
||||
# 附加信息
|
||||
reason: Optional[str] = Field(None, description="交易原因")
|
||||
remark: Optional[str] = Field(None, description="备注")
|
||||
|
||||
@field_validator("symbol")
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from .enums import PositionDirection
|
||||
|
||||
@ -13,33 +14,61 @@ class Position(BaseModel):
|
||||
|
||||
示例:
|
||||
position = Position(
|
||||
instance_id="debug_000001",
|
||||
strategy_name="DebugStrategy",
|
||||
symbol="000001.SZ",
|
||||
symbol_name="平安银行",
|
||||
direction=PositionDirection.LONG,
|
||||
volume=1000,
|
||||
available_volume=900,
|
||||
avg_price=10.0,
|
||||
avg_cost=10.0,
|
||||
update_time=datetime.now()
|
||||
)
|
||||
"""
|
||||
|
||||
# 基本信息
|
||||
instance_id: str = Field(..., description="策略实例ID", min_length=1)
|
||||
strategy_name: str = Field(..., description="策略类名", min_length=1)
|
||||
|
||||
# 标的信息
|
||||
symbol: str = Field(..., description="标的代码", min_length=1)
|
||||
symbol_name: Optional[str] = Field(None, description="标的名称")
|
||||
symbol_type: Optional[str] = Field(None, description="标的类型")
|
||||
decimal_places: int = Field(2, description="价格小数位数", ge=0)
|
||||
|
||||
# 持仓信息
|
||||
direction: PositionDirection = Field(..., description="方向(股票统一用long)")
|
||||
volume: int = Field(..., description="持仓量", ge=0)
|
||||
available_volume: int = Field(..., description="可用量(考虑T+1)", ge=0)
|
||||
frozen_volume: int = Field(0, description="冻结量(挂单冻结)", ge=0)
|
||||
|
||||
avg_price: float = Field(..., description="平均成本", gt=0)
|
||||
last_price: float = Field(0.0, description="最新价", ge=0)
|
||||
|
||||
# 盈亏(动态计算,也可以存储)
|
||||
market_value: float = Field(0.0, description="市值 = volume * last_price", ge=0)
|
||||
unrealized_pnl: float = Field(0.0, description="浮动盈亏")
|
||||
realized_pnl: float = Field(0.0, description="已实现盈亏(平仓产生)")
|
||||
|
||||
update_time: datetime = Field(..., description="更新时间")
|
||||
|
||||
# 股票特有:今仓/昨仓(用于T+1)
|
||||
today_volume: int = Field(0, description="今日买入量(T+1不可卖)", ge=0)
|
||||
yesterday_volume: int = Field(0, description="昨日持仓量", ge=0)
|
||||
|
||||
# 成本和价格
|
||||
avg_cost: float = Field(..., description="平均成本价", gt=0)
|
||||
current_price: float = Field(0.0, description="最新价", ge=0)
|
||||
open_price: float = Field(0.0, description="建仓价格", ge=0)
|
||||
|
||||
# 市值和盈亏
|
||||
market_value: float = Field(0.0, description="市值 = volume * current_price", ge=0)
|
||||
cost_value: float = Field(0.0, description="成本价值 = volume * avg_cost", ge=0)
|
||||
unrealized_pnl: float = Field(0.0, description="浮动盈亏")
|
||||
unrealized_pnl_ratio: float = Field(0.0, description="浮动盈亏率")
|
||||
realized_pnl: float = Field(0.0, description="已实现盈亏(平仓产生)")
|
||||
realized_pnl_ratio: float = Field(0.0, description="已实现盈亏率")
|
||||
|
||||
# 持仓占比
|
||||
position_ratio: float = Field(0.0, description="持仓占总资产比例", ge=0)
|
||||
|
||||
# 交易统计
|
||||
buy_times: int = Field(0, description="买入次数", ge=0)
|
||||
sell_times: int = Field(0, description="卖出次数", ge=0)
|
||||
total_cost: float = Field(0.0, description="累计交易成本", ge=0)
|
||||
|
||||
# 时间信息
|
||||
first_buy_time: Optional[datetime] = Field(None, description="首次买入时间")
|
||||
last_trade_time: Optional[datetime] = Field(None, description="最后交易时间")
|
||||
update_time: datetime = Field(..., description="更新时间")
|
||||
|
||||
@field_validator("symbol")
|
||||
@classmethod
|
||||
|
||||
@ -15,8 +15,9 @@ class Signal(BaseModel):
|
||||
示例:
|
||||
signal = Signal(
|
||||
signal_id="SIG_20240101_001",
|
||||
instance_id="debug_000001",
|
||||
strategy_name="DebugStrategy",
|
||||
symbol="000001.SZ",
|
||||
strategy_name="MA_Strategy",
|
||||
signal_type=SignalType.BUY,
|
||||
price=10.5,
|
||||
target_volume=100,
|
||||
@ -25,8 +26,9 @@ class Signal(BaseModel):
|
||||
"""
|
||||
|
||||
signal_id: str = Field(..., description="信号ID(唯一)", min_length=1)
|
||||
instance_id: str = Field(..., description="策略实例ID", min_length=1)
|
||||
strategy_name: str = Field(..., description="策略类名", min_length=1)
|
||||
symbol: str = Field(..., description="标的代码", min_length=1)
|
||||
strategy_name: str = Field(..., description="策略名称", min_length=1)
|
||||
signal_type: SignalType = Field(..., description="信号类型")
|
||||
|
||||
price: float = Field(..., description="信号触发价格", gt=0)
|
||||
|
||||
@ -1,56 +0,0 @@
|
||||
"""
|
||||
标的信息对象
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
from .enums import ProductType, Exchange
|
||||
|
||||
|
||||
class Symbol(BaseModel):
|
||||
"""
|
||||
标的信息(不可变)
|
||||
|
||||
示例:
|
||||
symbol = Symbol(
|
||||
code="000001.SZ",
|
||||
name="平安银行",
|
||||
exchange=Exchange.SZ,
|
||||
product_type=ProductType.STOCK
|
||||
)
|
||||
"""
|
||||
|
||||
code: str = Field(..., description="完整代码,如 000001.SZ", min_length=1)
|
||||
name: str = Field(..., description="名称", min_length=1)
|
||||
exchange: Exchange = Field(..., description="交易所")
|
||||
product_type: ProductType = Field(..., description="产品类型")
|
||||
|
||||
lot_size: int = Field(100, description="最小交易单位(股票100股,期货1手)", gt=0)
|
||||
tick_size: float = Field(0.01, description="最小价格变动", gt=0)
|
||||
|
||||
# 期货特有
|
||||
margin_rate: Optional[float] = Field(None, description="保证金比例", gt=0, le=1)
|
||||
multiplier: Optional[int] = Field(None, description="合约乘数", gt=0)
|
||||
|
||||
is_trading: bool = Field(True, description="是否可交易")
|
||||
|
||||
model_config = ConfigDict(frozen=True) # 不可变
|
||||
|
||||
@field_validator("code")
|
||||
@classmethod
|
||||
def validate_code(cls, v: str) -> str:
|
||||
"""验证标的代码格式"""
|
||||
v = v.upper()
|
||||
if not v or len(v) < 4:
|
||||
raise ValueError("标的代码长度至少4个字符")
|
||||
|
||||
return v
|
||||
|
||||
def model_post_init(self, __context) -> None:
|
||||
"""对象创建后验证"""
|
||||
# 验证期货必须有保证金比例和合约乘数
|
||||
if self.product_type == ProductType.FUTURE:
|
||||
if self.margin_rate is None:
|
||||
raise ValueError("期货必须设置保证金比例(margin_rate)")
|
||||
if self.multiplier is None:
|
||||
raise ValueError("期货必须设置合约乘数(multiplier)")
|
||||
@ -3,6 +3,7 @@
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional, Dict, Any
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
from .enums import OrderSide
|
||||
|
||||
@ -15,24 +16,38 @@ class Trade(BaseModel):
|
||||
trade = Trade(
|
||||
trade_id="TRD_20240101_001",
|
||||
order_id="ORD_20240101_001",
|
||||
instance_id="debug_000001",
|
||||
strategy_name="DebugStrategy",
|
||||
symbol="000001.SZ",
|
||||
symbol_name="平安银行",
|
||||
side=OrderSide.BUY,
|
||||
price=10.5,
|
||||
volume=100,
|
||||
amount=1050.0,
|
||||
commission=1.5,
|
||||
trade_time=datetime.now()
|
||||
)
|
||||
"""
|
||||
|
||||
# 基本信息
|
||||
trade_id: str = Field(..., description="成交ID(唯一)", min_length=1)
|
||||
order_id: str = Field(..., description="关联订单ID", min_length=1)
|
||||
instance_id: str = Field(..., description="策略实例ID", min_length=1)
|
||||
strategy_name: str = Field(..., description="策略类名", min_length=1)
|
||||
|
||||
# 标的信息
|
||||
symbol: str = Field(..., description="标的代码", min_length=1)
|
||||
symbol_name: Optional[str] = Field(None, description="标的名称")
|
||||
|
||||
# 成交信息
|
||||
side: OrderSide = Field(..., description="方向")
|
||||
price: float = Field(..., description="成交价", gt=0)
|
||||
volume: int = Field(..., description="成交量", gt=0)
|
||||
amount: float = Field(..., description="成交额 = price * volume", gt=0)
|
||||
commission: float = Field(0.0, description="手续费", ge=0)
|
||||
|
||||
# 成本信息
|
||||
cost_detail: Optional[Dict[str, Any]] = Field(None, description="成本明细")
|
||||
|
||||
# 时间信息
|
||||
trade_time: datetime = Field(..., description="成交时间")
|
||||
|
||||
model_config = ConfigDict(frozen=True) # 不可变
|
||||
|
||||
95
src/core/position.py
Normal file
95
src/core/position.py
Normal file
@ -0,0 +1,95 @@
|
||||
"""
|
||||
持仓管理 (Position)
|
||||
|
||||
管理单个策略实例的持仓信息
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Position:
|
||||
"""
|
||||
持仓信息(独立状态)
|
||||
|
||||
每个策略实例拥有独立的持仓
|
||||
"""
|
||||
|
||||
symbol: str
|
||||
shares: float = 0.0 # 持仓数量
|
||||
cost: float = 0.0 # 持仓成本
|
||||
|
||||
@property
|
||||
def avg_price(self) -> float:
|
||||
"""平均持仓价格"""
|
||||
if self.shares == 0:
|
||||
return 0.0
|
||||
return self.cost / self.shares
|
||||
|
||||
@property
|
||||
def is_empty(self) -> bool:
|
||||
"""是否空仓"""
|
||||
return self.shares == 0
|
||||
|
||||
def update(self, shares_change: float, cost_change: float):
|
||||
"""
|
||||
更新持仓
|
||||
|
||||
Args:
|
||||
shares_change: 持仓变化(正数为买入,负数为卖出)
|
||||
cost_change: 成本变化
|
||||
"""
|
||||
self.shares += shares_change
|
||||
self.cost += cost_change
|
||||
|
||||
# 清空时重置成本
|
||||
if abs(self.shares) < 1e-6:
|
||||
self.shares = 0.0
|
||||
self.cost = 0.0
|
||||
|
||||
logger.debug(
|
||||
f"Position updated: {self.symbol} "
|
||||
f"shares={self.shares:.2f}, cost={self.cost:.2f}, "
|
||||
f"avg_price={self.avg_price:.2f}"
|
||||
)
|
||||
|
||||
def calculate_profit(self, current_price: float) -> float:
|
||||
"""
|
||||
计算浮动盈亏
|
||||
|
||||
Args:
|
||||
current_price: 当前价格
|
||||
|
||||
Returns:
|
||||
浮动盈亏金额
|
||||
"""
|
||||
if self.is_empty:
|
||||
return 0.0
|
||||
return (current_price - self.avg_price) * self.shares
|
||||
|
||||
def calculate_profit_pct(self, current_price: float) -> float:
|
||||
"""
|
||||
计算浮动盈亏百分比
|
||||
|
||||
Args:
|
||||
current_price: 当前价格
|
||||
|
||||
Returns:
|
||||
浮动盈亏百分比
|
||||
"""
|
||||
if self.is_empty or self.avg_price == 0:
|
||||
return 0.0
|
||||
return ((current_price - self.avg_price) / self.avg_price) * 100
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""转换为字典"""
|
||||
return {
|
||||
"symbol": self.symbol,
|
||||
"shares": self.shares,
|
||||
"cost": self.cost,
|
||||
"avg_price": self.avg_price,
|
||||
"is_empty": self.is_empty,
|
||||
}
|
||||
161
src/core/risk_state.py
Normal file
161
src/core/risk_state.py
Normal file
@ -0,0 +1,161 @@
|
||||
"""
|
||||
风险状态管理 (RiskState)
|
||||
|
||||
管理单个策略实例的风险参数和状态
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class RiskState:
|
||||
"""
|
||||
风险状态(独立状态)
|
||||
|
||||
每个策略实例拥有独立的风险参数
|
||||
"""
|
||||
|
||||
# 风险参数
|
||||
max_position_ratio: float = 0.5 # 最大持仓比例
|
||||
stop_loss_ratio: float = 0.05 # 止损比例
|
||||
stop_profit_ratio: float = 0.20 # 止盈比例
|
||||
max_single_loss: float = 10000.0 # 单次最大亏损
|
||||
|
||||
# 风险状态
|
||||
total_loss: float = 0.0 # 累计亏损
|
||||
daily_loss: float = 0.0 # 当日亏损
|
||||
consecutive_losses: int = 0 # 连续亏损次数
|
||||
is_risk_locked: bool = False # 是否风控锁定
|
||||
|
||||
def check_position_limit(self, position_value: float, total_value: float) -> bool:
|
||||
"""
|
||||
检查持仓是否超限
|
||||
|
||||
Args:
|
||||
position_value: 持仓市值
|
||||
total_value: 总资产
|
||||
|
||||
Returns:
|
||||
是否符合限制
|
||||
"""
|
||||
if total_value == 0:
|
||||
return True
|
||||
|
||||
ratio = position_value / total_value
|
||||
if ratio > self.max_position_ratio:
|
||||
logger.warning(
|
||||
f"Position ratio exceeds limit: {ratio:.2%} > {self.max_position_ratio:.2%}"
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
def check_stop_loss(self, current_price: float, cost_price: float) -> bool:
|
||||
"""
|
||||
检查是否触发止损
|
||||
|
||||
Args:
|
||||
current_price: 当前价格
|
||||
cost_price: 成本价
|
||||
|
||||
Returns:
|
||||
是否触发止损
|
||||
"""
|
||||
if cost_price == 0:
|
||||
return False
|
||||
|
||||
loss_ratio = (cost_price - current_price) / cost_price
|
||||
if loss_ratio >= self.stop_loss_ratio:
|
||||
logger.warning(
|
||||
f"Stop loss triggered: loss={loss_ratio:.2%}, "
|
||||
f"threshold={self.stop_loss_ratio:.2%}"
|
||||
)
|
||||
return True
|
||||
return False
|
||||
|
||||
def check_stop_profit(self, current_price: float, cost_price: float) -> bool:
|
||||
"""
|
||||
检查是否触发止盈
|
||||
|
||||
Args:
|
||||
current_price: 当前价格
|
||||
cost_price: 成本价
|
||||
|
||||
Returns:
|
||||
是否触发止盈
|
||||
"""
|
||||
if cost_price == 0:
|
||||
return False
|
||||
|
||||
profit_ratio = (current_price - cost_price) / cost_price
|
||||
if profit_ratio >= self.stop_profit_ratio:
|
||||
logger.info(
|
||||
f"Stop profit triggered: profit={profit_ratio:.2%}, "
|
||||
f"threshold={self.stop_profit_ratio:.2%}"
|
||||
)
|
||||
return True
|
||||
return False
|
||||
|
||||
def record_loss(self, loss_amount: float):
|
||||
"""
|
||||
记录亏损
|
||||
|
||||
Args:
|
||||
loss_amount: 亏损金额(正数)
|
||||
"""
|
||||
self.total_loss += loss_amount
|
||||
self.daily_loss += loss_amount
|
||||
self.consecutive_losses += 1
|
||||
|
||||
# 检查是否需要风控锁定
|
||||
if loss_amount > self.max_single_loss:
|
||||
logger.error(
|
||||
f"Single loss exceeds limit: {loss_amount:.2f} > {self.max_single_loss:.2f}"
|
||||
)
|
||||
self.lock()
|
||||
|
||||
logger.warning(
|
||||
f"Loss recorded: amount={loss_amount:.2f}, "
|
||||
f"total={self.total_loss:.2f}, "
|
||||
f"consecutive={self.consecutive_losses}"
|
||||
)
|
||||
|
||||
def record_profit(self, profit_amount: float):
|
||||
"""
|
||||
记录盈利
|
||||
|
||||
Args:
|
||||
profit_amount: 盈利金额(正数)
|
||||
"""
|
||||
self.consecutive_losses = 0 # 重置连续亏损
|
||||
logger.info(f"Profit recorded: {profit_amount:.2f}")
|
||||
|
||||
def reset_daily_loss(self):
|
||||
"""重置当日亏损"""
|
||||
self.daily_loss = 0.0
|
||||
logger.debug("Daily loss reset")
|
||||
|
||||
def lock(self):
|
||||
"""风控锁定"""
|
||||
self.is_risk_locked = True
|
||||
logger.error("Risk locked! Trading suspended.")
|
||||
|
||||
def unlock(self):
|
||||
"""解除风控锁定"""
|
||||
self.is_risk_locked = False
|
||||
logger.info("Risk unlocked")
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""转换为字典"""
|
||||
return {
|
||||
"max_position_ratio": self.max_position_ratio,
|
||||
"stop_loss_ratio": self.stop_loss_ratio,
|
||||
"stop_profit_ratio": self.stop_profit_ratio,
|
||||
"max_single_loss": self.max_single_loss,
|
||||
"total_loss": self.total_loss,
|
||||
"daily_loss": self.daily_loss,
|
||||
"consecutive_losses": self.consecutive_losses,
|
||||
"is_risk_locked": self.is_risk_locked,
|
||||
}
|
||||
316
src/core/strategy_context.py
Normal file
316
src/core/strategy_context.py
Normal file
@ -0,0 +1,316 @@
|
||||
"""
|
||||
策略上下文 (StrategyContext)
|
||||
|
||||
策略运行的上下文环境,提供数据访问和状态管理
|
||||
|
||||
设计原则:
|
||||
1. Context 是策略访问所有资源的唯一入口
|
||||
2. 直接持有共享资源(cache_manager、db_manager)
|
||||
3. 对外提供高层接口,隐藏实现细节
|
||||
4. 每个策略实例有独立的 Context
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
import pandas as pd
|
||||
import logging
|
||||
|
||||
from src.core.position import Position
|
||||
from src.core.capital import Capital
|
||||
from src.core.risk_state import RiskState
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class StrategyContext:
|
||||
"""
|
||||
策略上下文(直接提供所有方法)
|
||||
|
||||
共享资源:通过传入同一个实例实现共享
|
||||
独立状态:每个Context有自己的Position、Capital、RiskState
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cache_manager,
|
||||
instance_id: str,
|
||||
symbol: str,
|
||||
instance_config: dict,
|
||||
):
|
||||
"""
|
||||
初始化策略上下文
|
||||
|
||||
Args:
|
||||
cache_manager: 缓存管理器(共享实例)
|
||||
instance_id: 策略实例ID
|
||||
symbol: 交易标的
|
||||
instance_config: 实例配置
|
||||
"""
|
||||
# ==================== 共享资源(私有) ====================
|
||||
# 注意:这是传入的共享实例,不是新创建的
|
||||
self._cache_manager = cache_manager
|
||||
|
||||
# ==================== 实例信息 ====================
|
||||
self.instance_id = instance_id
|
||||
self.symbol = symbol
|
||||
self.config = instance_config
|
||||
|
||||
# ==================== 独立状态 ====================
|
||||
self._position = Position(
|
||||
symbol=symbol,
|
||||
shares=instance_config.get("initial_shares", 0),
|
||||
cost=instance_config.get("initial_cost", 0.0),
|
||||
)
|
||||
|
||||
self._capital = Capital(
|
||||
initial_cash=instance_config.get("initial_capital", 1000000.0)
|
||||
)
|
||||
|
||||
self._risk_state = RiskState(
|
||||
max_position_ratio=instance_config.get("max_position_ratio", 0.5),
|
||||
stop_loss_ratio=instance_config.get("stop_loss_ratio", 0.05),
|
||||
stop_profit_ratio=instance_config.get("stop_profit_ratio", 0.20),
|
||||
max_single_loss=instance_config.get("max_single_loss", 10000.0),
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"StrategyContext initialized: instance_id={instance_id}, "
|
||||
f"symbol={symbol}, capital={self._capital.initial_cash:.2f}"
|
||||
)
|
||||
|
||||
# ==================== 数据访问接口(直接实现) ====================
|
||||
|
||||
def get_klines(
|
||||
self,
|
||||
symbol: Optional[str] = None,
|
||||
period: str = "1m",
|
||||
last_n: Optional[int] = None,
|
||||
start: Optional[pd.Timestamp] = None,
|
||||
end: Optional[pd.Timestamp] = None,
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
获取K线数据(直接从缓存获取)
|
||||
|
||||
这是策略访问数据的主要方式
|
||||
|
||||
Args:
|
||||
symbol: 标的代码,默认使用实例的 symbol
|
||||
period: 周期
|
||||
last_n: 最近N条
|
||||
start: 开始时间
|
||||
end: 结束时间
|
||||
|
||||
Returns:
|
||||
K线DataFrame,如果不存在返回None
|
||||
"""
|
||||
target_symbol = symbol or self.symbol
|
||||
|
||||
# 1. 从缓存读取
|
||||
try:
|
||||
data = self._cache_manager.get_klines(target_symbol, period)
|
||||
if data is None:
|
||||
logger.debug(
|
||||
f"[{self.instance_id}] No cache data for {target_symbol}_{period}"
|
||||
)
|
||||
return self._handle_cache_miss(
|
||||
target_symbol, period, last_n, start, end
|
||||
)
|
||||
|
||||
df = data.get("klines")
|
||||
if df is None or df.empty:
|
||||
logger.debug(
|
||||
f"[{self.instance_id}] Empty cache for {target_symbol}_{period}"
|
||||
)
|
||||
return self._handle_cache_miss(
|
||||
target_symbol, period, last_n, start, end
|
||||
)
|
||||
|
||||
# 2. 根据参数过滤数据
|
||||
result = self._filter_klines(df, last_n, start, end)
|
||||
|
||||
if result is not None and not result.empty:
|
||||
return result
|
||||
else:
|
||||
logger.warning(
|
||||
f"[{self.instance_id}] Filtered result is empty for {target_symbol}_{period}"
|
||||
)
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"[{self.instance_id}] Error getting klines: {e}", exc_info=True
|
||||
)
|
||||
return None
|
||||
|
||||
def _filter_klines(
|
||||
self,
|
||||
df: pd.DataFrame,
|
||||
last_n: Optional[int] = None,
|
||||
start: Optional[pd.Timestamp] = None,
|
||||
end: Optional[pd.Timestamp] = None,
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
过滤K线数据
|
||||
|
||||
Args:
|
||||
df: 原始DataFrame
|
||||
last_n: 最近N条
|
||||
start: 开始时间
|
||||
end: 结束时间
|
||||
|
||||
Returns:
|
||||
过滤后的DataFrame
|
||||
"""
|
||||
result = df.copy()
|
||||
|
||||
# 时间范围过滤
|
||||
if "timestamp" in result.columns:
|
||||
if start is not None:
|
||||
result = result[result["timestamp"] >= start]
|
||||
if end is not None:
|
||||
result = result[result["timestamp"] <= end]
|
||||
|
||||
# 最近N条
|
||||
if last_n is not None and last_n > 0:
|
||||
result = result.tail(last_n)
|
||||
|
||||
return result
|
||||
|
||||
def _handle_cache_miss(
|
||||
self,
|
||||
symbol: str,
|
||||
period: str,
|
||||
last_n: Optional[int],
|
||||
start: Optional[pd.Timestamp],
|
||||
end: Optional[pd.Timestamp],
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
处理缓存未命中
|
||||
|
||||
Args:
|
||||
symbol: 标的代码
|
||||
period: 周期
|
||||
last_n: 最近N条
|
||||
start: 开始时间
|
||||
end: 结束时间
|
||||
|
||||
Returns:
|
||||
None(缓存未命中直接返回None,CacheManager会自动处理数据库降级)
|
||||
"""
|
||||
# 缓存未命中,返回None
|
||||
# 注意:CacheManager已经在get_klines时处理了数据库降级
|
||||
logger.warning(f"[{self.instance_id}] No data available: {symbol}_{period}")
|
||||
return None
|
||||
|
||||
def get_indicators(
|
||||
self,
|
||||
symbol: Optional[str] = None,
|
||||
period: str = "1m",
|
||||
indicator_type: str = "MACD",
|
||||
) -> Optional[pd.DataFrame]:
|
||||
"""
|
||||
获取指标数据
|
||||
|
||||
Args:
|
||||
symbol: 标的代码,默认使用实例的 symbol
|
||||
period: 周期
|
||||
indicator_type: 指标类型
|
||||
|
||||
Returns:
|
||||
指标DataFrame,如果不存在返回None
|
||||
"""
|
||||
target_symbol = symbol or self.symbol
|
||||
try:
|
||||
return self._cache_manager.get_indicator(
|
||||
target_symbol, period, indicator_type
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"[{self.instance_id}] Error getting indicators: {e}", exc_info=True
|
||||
)
|
||||
return None
|
||||
|
||||
# ==================== 状态访问接口 ====================
|
||||
|
||||
def get_position(self) -> Position:
|
||||
"""获取持仓信息(独立状态)"""
|
||||
return self._position
|
||||
|
||||
def get_capital(self) -> Capital:
|
||||
"""获取资金信息(独立状态)"""
|
||||
return self._capital
|
||||
|
||||
def get_risk_state(self) -> RiskState:
|
||||
"""获取风险状态(独立状态)"""
|
||||
return self._risk_state
|
||||
|
||||
def update_position(self, shares_change: float, cost_change: float):
|
||||
"""
|
||||
更新持仓
|
||||
|
||||
Args:
|
||||
shares_change: 持仓变化
|
||||
cost_change: 成本变化
|
||||
"""
|
||||
self._position.update(shares_change, cost_change)
|
||||
|
||||
def update_capital(self, amount: float):
|
||||
"""
|
||||
更新资金
|
||||
|
||||
Args:
|
||||
amount: 资金变化
|
||||
"""
|
||||
self._capital.update(amount)
|
||||
|
||||
# ==================== 工具方法 ====================
|
||||
|
||||
def get_cache_info(self, symbol: Optional[str] = None, period: str = "1m") -> dict:
|
||||
"""
|
||||
获取缓存信息(用于调试)
|
||||
|
||||
Args:
|
||||
symbol: 标的代码
|
||||
period: 周期
|
||||
|
||||
Returns:
|
||||
缓存信息字典
|
||||
"""
|
||||
target_symbol = symbol or self.symbol
|
||||
try:
|
||||
data = self._cache_manager.get_klines(target_symbol, period)
|
||||
if data is None:
|
||||
return {"exists": False}
|
||||
|
||||
df = data.get("klines")
|
||||
if df is None or df.empty:
|
||||
return {"exists": True, "rows": 0}
|
||||
|
||||
return {
|
||||
"exists": True,
|
||||
"rows": len(df),
|
||||
"columns": list(df.columns),
|
||||
"first_timestamp": df["timestamp"].iloc[0]
|
||||
if "timestamp" in df.columns
|
||||
else None,
|
||||
"last_timestamp": df["timestamp"].iloc[-1]
|
||||
if "timestamp" in df.columns
|
||||
else None,
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"[{self.instance_id}] Error getting cache info: {e}")
|
||||
return {"error": str(e)}
|
||||
|
||||
def get_status(self) -> dict:
|
||||
"""
|
||||
获取上下文状态
|
||||
|
||||
Returns:
|
||||
状态字典
|
||||
"""
|
||||
return {
|
||||
"instance_id": self.instance_id,
|
||||
"symbol": self.symbol,
|
||||
"position": self._position.to_dict(),
|
||||
"capital": self._capital.to_dict(),
|
||||
"risk_state": self._risk_state.to_dict(),
|
||||
}
|
||||
@ -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")
|
||||
|
||||
@ -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
|
||||
|
||||
|
||||
@ -11,6 +11,8 @@ from xtquant import xtdatacenter as xtdc
|
||||
|
||||
from src.data_downloader.base_downloader import BaseDataDownloader
|
||||
from src.core.models import Kline
|
||||
from src.core.config import Config
|
||||
from src.core.logger import Logger
|
||||
|
||||
|
||||
class XtQuantDownloader(BaseDataDownloader):
|
||||
@ -72,9 +74,9 @@ class XtQuantDownloader(BaseDataDownloader):
|
||||
"""析构函数:关闭 XtQuant 连接"""
|
||||
try:
|
||||
xtdc.close() # type: ignore
|
||||
self.logger.debug("XtQuant connection closed")
|
||||
Logger.debug("XtQuant connection closed")
|
||||
except Exception as e:
|
||||
self.logger.debug(f"Error closing XtQuant connection: {e}")
|
||||
Logger.debug(f"Error closing XtQuant connection: {e}")
|
||||
|
||||
def _init_xtquant(
|
||||
self, token: Optional[str], optimize_addresses: Optional[List[str]]
|
||||
@ -82,13 +84,13 @@ class XtQuantDownloader(BaseDataDownloader):
|
||||
"""初始化 XtQuant 数据中心"""
|
||||
# 获取 token(从配置文件 data_source.xtquant.xtquant_token 读取)
|
||||
if token is None:
|
||||
token = self.config.get("data_source.xtquant.xtquant_token")
|
||||
token = Config.get("data_downloader.xtquant.xtquant_token")
|
||||
if not token:
|
||||
raise ValueError(
|
||||
"XtQuant token 未设置,请在配置文件 data_source.xtquant.xtquant_token 中设置或通过参数传入"
|
||||
)
|
||||
|
||||
self.logger.info(f"Initializing XtQuant data center, Token: {token[:20]}...")
|
||||
Logger.info(f"Initializing XtQuant data center, Token: {token[:20]}...")
|
||||
|
||||
# 设置 token
|
||||
xtdc.set_token(token)
|
||||
@ -96,35 +98,35 @@ class XtQuantDownloader(BaseDataDownloader):
|
||||
# 初始化数据中心
|
||||
try:
|
||||
xtdc.init()
|
||||
self.logger.info("XtQuant data center initialized successfully")
|
||||
Logger.info("XtQuant data center initialized successfully")
|
||||
except Exception as e:
|
||||
self.logger.error(f"XtQuant data center initialization failed: {e}")
|
||||
Logger.error(f"XtQuant data center initialization failed: {e}")
|
||||
raise
|
||||
|
||||
# 设置优化地址
|
||||
if optimize_addresses is None:
|
||||
optimize_addresses = self.config.get(
|
||||
optimize_addresses = Config.get(
|
||||
"data_source.xtquant.optimize_addresses", []
|
||||
)
|
||||
|
||||
if optimize_addresses:
|
||||
try:
|
||||
xtdc.set_allow_optmize_address(optimize_addresses)
|
||||
self.logger.info(
|
||||
Logger.info(
|
||||
f"Optimize addresses set: {len(optimize_addresses)} addresses"
|
||||
)
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to set optimize addresses: {e}")
|
||||
Logger.warning(f"Failed to set optimize addresses: {e}")
|
||||
|
||||
# 下载基础数据
|
||||
try:
|
||||
self.logger.info("Downloading sector data...")
|
||||
Logger.info("Downloading sector data...")
|
||||
xtdata.download_sector_data()
|
||||
self.logger.info("Downloading historical contracts data...")
|
||||
Logger.info("Downloading historical contracts data...")
|
||||
xtdata.download_history_contracts()
|
||||
self.logger.info("Base data download completed")
|
||||
Logger.info("Base data download completed")
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Base data download failed: {e}")
|
||||
Logger.warning(f"Base data download failed: {e}")
|
||||
|
||||
def _download_klines(
|
||||
self, symbol: str, start_date: datetime, end_date: datetime, period: str
|
||||
@ -150,12 +152,10 @@ class XtQuantDownloader(BaseDataDownloader):
|
||||
|
||||
# 先下载历史数据(确保本地有缓存)
|
||||
try:
|
||||
self.logger.debug(
|
||||
f"Downloading {symbol} [{period}] historical data to local..."
|
||||
)
|
||||
Logger.debug(f"Downloading {symbol} [{period}] historical data to local...")
|
||||
xtdata.download_history_data(symbol, xt_period, start_str, end_str)
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to download historical data to local: {e}")
|
||||
Logger.warning(f"Failed to download historical data to local: {e}")
|
||||
|
||||
# 从本地获取数据
|
||||
try:
|
||||
@ -171,11 +171,11 @@ class XtQuantDownloader(BaseDataDownloader):
|
||||
)
|
||||
|
||||
if symbol not in data or len(data[symbol]) == 0:
|
||||
self.logger.warning(f"{symbol} [{period}] has no data")
|
||||
Logger.warning(f"{symbol} [{period}] has no data")
|
||||
return []
|
||||
|
||||
df = data[symbol]
|
||||
self.logger.debug(f"Retrieved {len(df)} records for {symbol} [{period}]")
|
||||
Logger.debug(f"Retrieved {len(df)} records for {symbol} [{period}]")
|
||||
|
||||
# 转换为 Kline 对象
|
||||
klines = []
|
||||
@ -213,12 +213,10 @@ class XtQuantDownloader(BaseDataDownloader):
|
||||
|
||||
# 打印第一条数据的时间戳信息用于调试
|
||||
if not first_logged:
|
||||
self.logger.debug(
|
||||
Logger.debug(
|
||||
f"First timestamp - raw: {timestamp}, type: {type(timestamp)}"
|
||||
)
|
||||
self.logger.debug(
|
||||
f"First timestamp - converted: {dt}, type: {type(dt)}"
|
||||
)
|
||||
Logger.debug(f"First timestamp - converted: {dt}, type: {type(dt)}")
|
||||
first_logged = True
|
||||
|
||||
kline = Kline(
|
||||
@ -240,5 +238,5 @@ class XtQuantDownloader(BaseDataDownloader):
|
||||
return klines
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"Failed to retrieve {symbol} [{period}] data: {e}")
|
||||
Logger.error(f"Failed to retrieve {symbol} [{period}] data: {e}")
|
||||
raise
|
||||
|
||||
@ -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,34 +139,34 @@ 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."
|
||||
)
|
||||
return None
|
||||
|
||||
# ========== 步骤1: 检查缓存 ==========
|
||||
cache_data = self.cache.get_klines(symbol, period)
|
||||
cache_data = self.cache.get_klines(symbol, period, startdate, enddate)
|
||||
|
||||
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,
|
||||
@ -448,7 +433,26 @@ class DataService:
|
||||
return self.storage.get_date_range(symbol, period)
|
||||
|
||||
# ========== 内部辅助方法 ==========
|
||||
# 检查所需要的数据是否在缓存中
|
||||
def _check_data_exist_in_cache(
|
||||
self, symbol: str, period: str, startdate: datetime, enddate: datetime
|
||||
) -> bool:
|
||||
"""
|
||||
检查数据是否在缓存中
|
||||
|
||||
Args:
|
||||
symbol: 标的代码
|
||||
period: 周期
|
||||
startdate: 开始时间
|
||||
enddate: 结束时间
|
||||
|
||||
Returns:
|
||||
True如果数据在缓存中
|
||||
"""
|
||||
cache_data = self.cache.get_klines(symbol, period, startdate, enddate)
|
||||
return cache_data is not None and not cache_data.empty
|
||||
|
||||
# 重新计算并保存所有启用的指标
|
||||
def _recalculate_and_save_indicators(
|
||||
self, symbol: str, period: str, klines: pd.DataFrame
|
||||
) -> None:
|
||||
@ -463,12 +467,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 +497,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 +530,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 +577,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 +585,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 +600,7 @@ class DataService:
|
||||
self.downloader.close()
|
||||
# 关闭storage连接
|
||||
self.storage.close()
|
||||
logger.info("DataService closed")
|
||||
Logger.info("DataService closed")
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
@ -6,8 +6,10 @@
|
||||
|
||||
from .storage_layer import StorageLayer
|
||||
from .mysql_storage import MySQLStorage
|
||||
from .trading_storage import TradingDataStorage
|
||||
|
||||
__all__ = [
|
||||
"StorageLayer",
|
||||
"MySQLStorage",
|
||||
"TradingDataStorage",
|
||||
]
|
||||
|
||||
@ -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")
|
||||
|
||||
@ -5,12 +5,9 @@
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Optional
|
||||
from typing import Optional, List, Dict, Any
|
||||
from datetime import datetime
|
||||
import pandas as pd
|
||||
from src.core.logger import get_logger
|
||||
|
||||
logger = get_logger("StorageLayer")
|
||||
|
||||
|
||||
class StorageLayer(ABC):
|
||||
@ -24,6 +21,8 @@ class StorageLayer(ABC):
|
||||
- 其他存储后端
|
||||
"""
|
||||
|
||||
# ==================== K线和指标数据接口 ====================
|
||||
|
||||
@abstractmethod
|
||||
def load_klines(
|
||||
self,
|
||||
@ -157,3 +156,218 @@ class StorageLayer(ABC):
|
||||
def close(self):
|
||||
"""关闭存储连接"""
|
||||
pass
|
||||
|
||||
# ==================== 交易对象存储接口 ====================
|
||||
|
||||
@abstractmethod
|
||||
def save_order(self, order: Any) -> bool:
|
||||
"""
|
||||
保存订单
|
||||
|
||||
Args:
|
||||
order: Order对象
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_orders(
|
||||
self,
|
||||
instance_id: Optional[str] = None,
|
||||
symbol: Optional[str] = None,
|
||||
status: Optional[str] = None,
|
||||
start_time: Optional[datetime] = None,
|
||||
end_time: Optional[datetime] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
获取订单列表
|
||||
|
||||
Args:
|
||||
instance_id: 策略实例ID(可选)
|
||||
symbol: 标的代码(可选)
|
||||
status: 订单状态(可选)
|
||||
start_time: 开始时间(可选)
|
||||
end_time: 结束时间(可选)
|
||||
|
||||
Returns:
|
||||
订单字典列表
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_order_by_id(self, order_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
根据订单ID获取订单
|
||||
|
||||
Args:
|
||||
order_id: 订单ID
|
||||
|
||||
Returns:
|
||||
订单字典或None
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def save_trade(self, trade: Any) -> bool:
|
||||
"""
|
||||
保存成交记录
|
||||
|
||||
Args:
|
||||
trade: Trade对象
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_trades(
|
||||
self,
|
||||
instance_id: Optional[str] = None,
|
||||
symbol: Optional[str] = None,
|
||||
order_id: Optional[str] = None,
|
||||
start_time: Optional[datetime] = None,
|
||||
end_time: Optional[datetime] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
获取成交记录列表
|
||||
|
||||
Args:
|
||||
instance_id: 策略实例ID(可选)
|
||||
symbol: 标的代码(可选)
|
||||
order_id: 订单ID(可选)
|
||||
start_time: 开始时间(可选)
|
||||
end_time: 结束时间(可选)
|
||||
|
||||
Returns:
|
||||
成交记录字典列表
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_trade_by_id(self, trade_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
根据成交ID获取成交记录
|
||||
|
||||
Args:
|
||||
trade_id: 成交ID
|
||||
|
||||
Returns:
|
||||
成交记录字典或None
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def save_position(self, position: Any) -> bool:
|
||||
"""
|
||||
保存持仓
|
||||
|
||||
Args:
|
||||
position: Position对象
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_positions(
|
||||
self,
|
||||
instance_id: Optional[str] = None,
|
||||
symbol: Optional[str] = None,
|
||||
direction: Optional[str] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
获取持仓列表
|
||||
|
||||
Args:
|
||||
instance_id: 策略实例ID(可选)
|
||||
symbol: 标的代码(可选)
|
||||
direction: 持仓方向(可选)
|
||||
|
||||
Returns:
|
||||
持仓字典列表
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_position(
|
||||
self, instance_id: str, symbol: str, direction: str
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
获取指定持仓
|
||||
|
||||
Args:
|
||||
instance_id: 策略实例ID
|
||||
symbol: 标的代码
|
||||
direction: 持仓方向
|
||||
|
||||
Returns:
|
||||
持仓字典或None
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def save_asset(self, asset: Any) -> bool:
|
||||
"""
|
||||
保存资产账户
|
||||
|
||||
Args:
|
||||
asset: Asset对象
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_asset(self, instance_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
获取资产账户
|
||||
|
||||
Args:
|
||||
instance_id: 策略实例ID
|
||||
|
||||
Returns:
|
||||
资产字典或None
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def save_signal(self, signal: Any) -> bool:
|
||||
"""
|
||||
保存交易信号
|
||||
|
||||
Args:
|
||||
signal: Signal对象
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_signals(
|
||||
self,
|
||||
instance_id: Optional[str] = None,
|
||||
symbol: Optional[str] = None,
|
||||
executed: Optional[bool] = None,
|
||||
start_time: Optional[datetime] = None,
|
||||
end_time: Optional[datetime] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
获取信号列表
|
||||
|
||||
Args:
|
||||
instance_id: 策略实例ID(可选)
|
||||
symbol: 标的代码(可选)
|
||||
executed: 是否已执行(可选)
|
||||
start_time: 开始时间(可选)
|
||||
end_time: 结束时间(可选)
|
||||
|
||||
Returns:
|
||||
信号字典列表
|
||||
"""
|
||||
pass
|
||||
|
||||
562
src/data_storage/trading_storage.py
Normal file
562
src/data_storage/trading_storage.py
Normal file
@ -0,0 +1,562 @@
|
||||
"""
|
||||
交易数据存储扩展
|
||||
|
||||
为 Order, Trade, Position, Asset 提供数据库存储接口
|
||||
"""
|
||||
|
||||
from typing import List, Optional, Dict, Any
|
||||
from datetime import datetime
|
||||
import json
|
||||
from sqlalchemy import text
|
||||
|
||||
from src.core.models import Order, Trade, Position, Asset
|
||||
from src.core.logger import Logger
|
||||
from src.database_manager import DatabaseManager
|
||||
|
||||
|
||||
class TradingDataStorage:
|
||||
"""
|
||||
交易数据存储类
|
||||
|
||||
提供 Order, Trade, Position, Asset 的数据库CRUD操作
|
||||
"""
|
||||
|
||||
def __init__(self, database: str, db_manager: Optional[DatabaseManager] = None):
|
||||
"""
|
||||
初始化交易数据存储
|
||||
|
||||
Args:
|
||||
database: 数据库名
|
||||
db_manager: 数据库管理器(可选)
|
||||
"""
|
||||
self.database = database
|
||||
self.db_manager = db_manager if db_manager is not None else DatabaseManager()
|
||||
self.engine = None
|
||||
|
||||
def _get_engine(self):
|
||||
"""获取数据库引擎(懒加载)"""
|
||||
if self.engine is None:
|
||||
self.engine = self.db_manager._create_db_engine(self.database)
|
||||
return self.engine
|
||||
|
||||
# ==================== Order 操作 ====================
|
||||
|
||||
def save_order(self, order: Order) -> bool:
|
||||
"""
|
||||
保存订单
|
||||
|
||||
Args:
|
||||
order: Order对象
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
try:
|
||||
engine = self._get_engine()
|
||||
|
||||
# 序列化 cost_detail
|
||||
cost_detail_json = (
|
||||
json.dumps(order.cost_detail) if order.cost_detail else None
|
||||
)
|
||||
|
||||
query = text("""
|
||||
INSERT INTO orders (
|
||||
order_id, instance_id, strategy_name,
|
||||
symbol, symbol_name,
|
||||
side, order_type, price, volume,
|
||||
filled_volume, filled_price, actual_price, status,
|
||||
cost_detail,
|
||||
create_time, submit_time, filled_time, cancel_time, update_time,
|
||||
reason, remark
|
||||
) VALUES (
|
||||
:order_id, :instance_id, :strategy_name,
|
||||
:symbol, :symbol_name,
|
||||
:side, :order_type, :price, :volume,
|
||||
:filled_volume, :filled_price, :actual_price, :status,
|
||||
:cost_detail,
|
||||
:create_time, :submit_time, :filled_time, :cancel_time, :update_time,
|
||||
:reason, :remark
|
||||
)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
filled_volume=VALUES(filled_volume),
|
||||
filled_price=VALUES(filled_price),
|
||||
actual_price=VALUES(actual_price),
|
||||
status=VALUES(status),
|
||||
cost_detail=VALUES(cost_detail),
|
||||
filled_time=VALUES(filled_time),
|
||||
cancel_time=VALUES(cancel_time),
|
||||
update_time=VALUES(update_time)
|
||||
""")
|
||||
|
||||
with engine.connect() as conn:
|
||||
conn.execute(
|
||||
query,
|
||||
{
|
||||
"order_id": order.order_id,
|
||||
"instance_id": order.instance_id,
|
||||
"strategy_name": order.strategy_name,
|
||||
"symbol": order.symbol,
|
||||
"symbol_name": order.symbol_name,
|
||||
"side": order.side.value,
|
||||
"order_type": order.order_type.value,
|
||||
"price": order.price,
|
||||
"volume": order.volume,
|
||||
"filled_volume": order.filled_volume,
|
||||
"filled_price": order.filled_price,
|
||||
"actual_price": order.actual_price,
|
||||
"status": order.status.value,
|
||||
"cost_detail": cost_detail_json,
|
||||
"create_time": order.create_time,
|
||||
"submit_time": order.submit_time,
|
||||
"filled_time": order.filled_time,
|
||||
"cancel_time": order.cancel_time,
|
||||
"update_time": order.update_time,
|
||||
"reason": order.reason,
|
||||
"remark": order.remark,
|
||||
},
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
Logger.debug(f"Saved order: {order.order_id}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
Logger.error(f"Failed to save order {order.order_id}: {e}")
|
||||
return False
|
||||
|
||||
def get_orders(
|
||||
self,
|
||||
instance_id: Optional[str] = None,
|
||||
symbol: Optional[str] = None,
|
||||
start_time: Optional[datetime] = None,
|
||||
end_time: Optional[datetime] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
查询订单
|
||||
|
||||
Args:
|
||||
instance_id: 策略实例ID
|
||||
symbol: 股票代码
|
||||
start_time: 开始时间
|
||||
end_time: 结束时间
|
||||
|
||||
Returns:
|
||||
订单字典列表
|
||||
"""
|
||||
try:
|
||||
engine = self._get_engine()
|
||||
|
||||
where_clauses = []
|
||||
params = {}
|
||||
|
||||
if instance_id:
|
||||
where_clauses.append("instance_id = :instance_id")
|
||||
params["instance_id"] = instance_id
|
||||
|
||||
if symbol:
|
||||
where_clauses.append("symbol = :symbol")
|
||||
params["symbol"] = symbol
|
||||
|
||||
if start_time:
|
||||
where_clauses.append("create_time >= :start_time")
|
||||
params["start_time"] = start_time
|
||||
|
||||
if end_time:
|
||||
where_clauses.append("create_time <= :end_time")
|
||||
params["end_time"] = end_time
|
||||
|
||||
where_clause = " AND ".join(where_clauses) if where_clauses else "1=1"
|
||||
|
||||
query = text(f"""
|
||||
SELECT * FROM orders
|
||||
WHERE {where_clause}
|
||||
ORDER BY create_time DESC
|
||||
""")
|
||||
|
||||
with engine.connect() as conn:
|
||||
result = conn.execute(query, params)
|
||||
rows = result.fetchall()
|
||||
|
||||
# 转换为字典列表
|
||||
orders = []
|
||||
for row in rows:
|
||||
order_dict = dict(row._mapping)
|
||||
# 反序列化 cost_detail
|
||||
if order_dict.get("cost_detail"):
|
||||
order_dict["cost_detail"] = json.loads(order_dict["cost_detail"])
|
||||
orders.append(order_dict)
|
||||
|
||||
return orders
|
||||
|
||||
except Exception as e:
|
||||
Logger.error(f"Failed to get orders: {e}")
|
||||
return []
|
||||
|
||||
# ==================== Trade 操作 ====================
|
||||
|
||||
def save_trade(self, trade: Trade) -> bool:
|
||||
"""保存成交记录"""
|
||||
try:
|
||||
engine = self._get_engine()
|
||||
|
||||
# 序列化 cost_detail
|
||||
cost_detail_json = (
|
||||
json.dumps(trade.cost_detail) if trade.cost_detail else None
|
||||
)
|
||||
|
||||
query = text("""
|
||||
INSERT INTO trades (
|
||||
trade_id, order_id, instance_id, strategy_name,
|
||||
symbol, symbol_name,
|
||||
side, price, volume, amount,
|
||||
cost_detail,
|
||||
trade_time
|
||||
) VALUES (
|
||||
:trade_id, :order_id, :instance_id, :strategy_name,
|
||||
:symbol, :symbol_name,
|
||||
:side, :price, :volume, :amount,
|
||||
:cost_detail,
|
||||
:trade_time
|
||||
)
|
||||
""")
|
||||
|
||||
with engine.connect() as conn:
|
||||
conn.execute(
|
||||
query,
|
||||
{
|
||||
"trade_id": trade.trade_id,
|
||||
"order_id": trade.order_id,
|
||||
"instance_id": trade.instance_id,
|
||||
"strategy_name": trade.strategy_name,
|
||||
"symbol": trade.symbol,
|
||||
"symbol_name": trade.symbol_name,
|
||||
"side": trade.side.value,
|
||||
"price": trade.price,
|
||||
"volume": trade.volume,
|
||||
"amount": trade.amount,
|
||||
"cost_detail": cost_detail_json,
|
||||
"trade_time": trade.trade_time,
|
||||
},
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
Logger.debug(f"Saved trade: {trade.trade_id}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
Logger.error(f"Failed to save trade {trade.trade_id}: {e}")
|
||||
return False
|
||||
|
||||
def get_trades(
|
||||
self,
|
||||
instance_id: Optional[str] = None,
|
||||
symbol: Optional[str] = None,
|
||||
start_time: Optional[datetime] = None,
|
||||
end_time: Optional[datetime] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""查询成交记录"""
|
||||
try:
|
||||
engine = self._get_engine()
|
||||
|
||||
where_clauses = []
|
||||
params = {}
|
||||
|
||||
if instance_id:
|
||||
where_clauses.append("instance_id = :instance_id")
|
||||
params["instance_id"] = instance_id
|
||||
|
||||
if symbol:
|
||||
where_clauses.append("symbol = :symbol")
|
||||
params["symbol"] = symbol
|
||||
|
||||
if start_time:
|
||||
where_clauses.append("trade_time >= :start_time")
|
||||
params["start_time"] = start_time
|
||||
|
||||
if end_time:
|
||||
where_clauses.append("trade_time <= :end_time")
|
||||
params["end_time"] = end_time
|
||||
|
||||
where_clause = " AND ".join(where_clauses) if where_clauses else "1=1"
|
||||
|
||||
query = text(f"""
|
||||
SELECT * FROM trades
|
||||
WHERE {where_clause}
|
||||
ORDER BY trade_time DESC
|
||||
""")
|
||||
|
||||
with engine.connect() as conn:
|
||||
result = conn.execute(query, params)
|
||||
rows = result.fetchall()
|
||||
|
||||
trades = []
|
||||
for row in rows:
|
||||
trade_dict = dict(row._mapping)
|
||||
if trade_dict.get("cost_detail"):
|
||||
trade_dict["cost_detail"] = json.loads(trade_dict["cost_detail"])
|
||||
trades.append(trade_dict)
|
||||
|
||||
return trades
|
||||
|
||||
except Exception as e:
|
||||
Logger.error(f"Failed to get trades: {e}")
|
||||
return []
|
||||
|
||||
# ==================== Position 操作 ====================
|
||||
|
||||
def save_position(self, position: Position) -> bool:
|
||||
"""保存或更新持仓"""
|
||||
try:
|
||||
engine = self._get_engine()
|
||||
|
||||
query = text("""
|
||||
INSERT INTO positions (
|
||||
instance_id, strategy_name,
|
||||
symbol, symbol_name, symbol_type, decimal_places,
|
||||
direction, volume, available_volume, frozen_volume,
|
||||
today_volume, yesterday_volume,
|
||||
avg_cost, current_price, open_price,
|
||||
market_value, cost_value,
|
||||
unrealized_pnl, unrealized_pnl_ratio,
|
||||
realized_pnl, realized_pnl_ratio,
|
||||
position_ratio,
|
||||
buy_times, sell_times, total_cost,
|
||||
first_buy_time, last_trade_time, update_time
|
||||
) VALUES (
|
||||
:instance_id, :strategy_name,
|
||||
:symbol, :symbol_name, :symbol_type, :decimal_places,
|
||||
:direction, :volume, :available_volume, :frozen_volume,
|
||||
:today_volume, :yesterday_volume,
|
||||
:avg_cost, :current_price, :open_price,
|
||||
:market_value, :cost_value,
|
||||
:unrealized_pnl, :unrealized_pnl_ratio,
|
||||
:realized_pnl, :realized_pnl_ratio,
|
||||
:position_ratio,
|
||||
:buy_times, :sell_times, :total_cost,
|
||||
:first_buy_time, :last_trade_time, :update_time
|
||||
)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
volume=VALUES(volume),
|
||||
available_volume=VALUES(available_volume),
|
||||
frozen_volume=VALUES(frozen_volume),
|
||||
today_volume=VALUES(today_volume),
|
||||
yesterday_volume=VALUES(yesterday_volume),
|
||||
avg_cost=VALUES(avg_cost),
|
||||
current_price=VALUES(current_price),
|
||||
market_value=VALUES(market_value),
|
||||
cost_value=VALUES(cost_value),
|
||||
unrealized_pnl=VALUES(unrealized_pnl),
|
||||
unrealized_pnl_ratio=VALUES(unrealized_pnl_ratio),
|
||||
realized_pnl=VALUES(realized_pnl),
|
||||
realized_pnl_ratio=VALUES(realized_pnl_ratio),
|
||||
position_ratio=VALUES(position_ratio),
|
||||
buy_times=VALUES(buy_times),
|
||||
sell_times=VALUES(sell_times),
|
||||
total_cost=VALUES(total_cost),
|
||||
last_trade_time=VALUES(last_trade_time),
|
||||
update_time=VALUES(update_time)
|
||||
""")
|
||||
|
||||
with engine.connect() as conn:
|
||||
conn.execute(
|
||||
query,
|
||||
{
|
||||
"instance_id": position.instance_id,
|
||||
"strategy_name": position.strategy_name,
|
||||
"symbol": position.symbol,
|
||||
"symbol_name": position.symbol_name,
|
||||
"symbol_type": position.symbol_type,
|
||||
"decimal_places": position.decimal_places,
|
||||
"direction": position.direction.value,
|
||||
"volume": position.volume,
|
||||
"available_volume": position.available_volume,
|
||||
"frozen_volume": position.frozen_volume,
|
||||
"today_volume": position.today_volume,
|
||||
"yesterday_volume": position.yesterday_volume,
|
||||
"avg_cost": position.avg_cost,
|
||||
"current_price": position.current_price,
|
||||
"open_price": position.open_price,
|
||||
"market_value": position.market_value,
|
||||
"cost_value": position.cost_value,
|
||||
"unrealized_pnl": position.unrealized_pnl,
|
||||
"unrealized_pnl_ratio": position.unrealized_pnl_ratio,
|
||||
"realized_pnl": position.realized_pnl,
|
||||
"realized_pnl_ratio": position.realized_pnl_ratio,
|
||||
"position_ratio": position.position_ratio,
|
||||
"buy_times": position.buy_times,
|
||||
"sell_times": position.sell_times,
|
||||
"total_cost": position.total_cost,
|
||||
"first_buy_time": position.first_buy_time,
|
||||
"last_trade_time": position.last_trade_time,
|
||||
"update_time": position.update_time,
|
||||
},
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
Logger.debug(f"Saved position: {position.instance_id}_{position.symbol}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
Logger.error(f"Failed to save position: {e}")
|
||||
return False
|
||||
|
||||
def get_positions(
|
||||
self,
|
||||
instance_id: Optional[str] = None,
|
||||
symbol: Optional[str] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""查询持仓"""
|
||||
try:
|
||||
engine = self._get_engine()
|
||||
|
||||
where_clauses = []
|
||||
params = {}
|
||||
|
||||
if instance_id:
|
||||
where_clauses.append("instance_id = :instance_id")
|
||||
params["instance_id"] = instance_id
|
||||
|
||||
if symbol:
|
||||
where_clauses.append("symbol = :symbol")
|
||||
params["symbol"] = symbol
|
||||
|
||||
where_clause = " AND ".join(where_clauses) if where_clauses else "1=1"
|
||||
|
||||
query = text(f"""
|
||||
SELECT * FROM positions
|
||||
WHERE {where_clause}
|
||||
ORDER BY update_time DESC
|
||||
""")
|
||||
|
||||
with engine.connect() as conn:
|
||||
result = conn.execute(query, params)
|
||||
rows = result.fetchall()
|
||||
|
||||
return [dict(row._mapping) for row in rows]
|
||||
|
||||
except Exception as e:
|
||||
Logger.error(f"Failed to get positions: {e}")
|
||||
return []
|
||||
|
||||
# ==================== Asset 操作 ====================
|
||||
|
||||
def save_asset(self, asset: Asset) -> bool:
|
||||
"""保存或更新资产"""
|
||||
try:
|
||||
engine = self._get_engine()
|
||||
|
||||
query = text("""
|
||||
INSERT INTO assets (
|
||||
instance_id, strategy_name,
|
||||
initial_capital, total_asset, cash, available_cash, frozen_cash,
|
||||
market_value, long_market_value, short_market_value,
|
||||
total_pnl, total_return, unrealized_pnl, realized_pnl,
|
||||
daily_pnl, daily_return, pre_total_asset,
|
||||
total_commission, total_stamp_tax, total_transfer_fee,
|
||||
total_slippage, total_cost, trade_count,
|
||||
max_drawdown, max_drawdown_ratio, leverage,
|
||||
init_time, last_trade_time, update_time
|
||||
) VALUES (
|
||||
:instance_id, :strategy_name,
|
||||
:initial_capital, :total_asset, :cash, :available_cash, :frozen_cash,
|
||||
:market_value, :long_market_value, :short_market_value,
|
||||
:total_pnl, :total_return, :unrealized_pnl, :realized_pnl,
|
||||
:daily_pnl, :daily_return, :pre_total_asset,
|
||||
:total_commission, :total_stamp_tax, :total_transfer_fee,
|
||||
:total_slippage, :total_cost, :trade_count,
|
||||
:max_drawdown, :max_drawdown_ratio, :leverage,
|
||||
:init_time, :last_trade_time, :update_time
|
||||
)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
total_asset=VALUES(total_asset),
|
||||
cash=VALUES(cash),
|
||||
available_cash=VALUES(available_cash),
|
||||
frozen_cash=VALUES(frozen_cash),
|
||||
market_value=VALUES(market_value),
|
||||
long_market_value=VALUES(long_market_value),
|
||||
short_market_value=VALUES(short_market_value),
|
||||
total_pnl=VALUES(total_pnl),
|
||||
total_return=VALUES(total_return),
|
||||
unrealized_pnl=VALUES(unrealized_pnl),
|
||||
realized_pnl=VALUES(realized_pnl),
|
||||
daily_pnl=VALUES(daily_pnl),
|
||||
daily_return=VALUES(daily_return),
|
||||
pre_total_asset=VALUES(pre_total_asset),
|
||||
total_commission=VALUES(total_commission),
|
||||
total_stamp_tax=VALUES(total_stamp_tax),
|
||||
total_transfer_fee=VALUES(total_transfer_fee),
|
||||
total_slippage=VALUES(total_slippage),
|
||||
total_cost=VALUES(total_cost),
|
||||
trade_count=VALUES(trade_count),
|
||||
max_drawdown=VALUES(max_drawdown),
|
||||
max_drawdown_ratio=VALUES(max_drawdown_ratio),
|
||||
leverage=VALUES(leverage),
|
||||
last_trade_time=VALUES(last_trade_time),
|
||||
update_time=VALUES(update_time)
|
||||
""")
|
||||
|
||||
with engine.connect() as conn:
|
||||
conn.execute(
|
||||
query,
|
||||
{
|
||||
"instance_id": asset.instance_id,
|
||||
"strategy_name": asset.strategy_name,
|
||||
"initial_capital": asset.initial_capital,
|
||||
"total_asset": asset.total_asset,
|
||||
"cash": asset.cash,
|
||||
"available_cash": asset.available_cash,
|
||||
"frozen_cash": asset.frozen_cash,
|
||||
"market_value": asset.market_value,
|
||||
"long_market_value": asset.long_market_value,
|
||||
"short_market_value": asset.short_market_value,
|
||||
"total_pnl": asset.total_pnl,
|
||||
"total_return": asset.total_return,
|
||||
"unrealized_pnl": asset.unrealized_pnl,
|
||||
"realized_pnl": asset.realized_pnl,
|
||||
"daily_pnl": asset.daily_pnl,
|
||||
"daily_return": asset.daily_return,
|
||||
"pre_total_asset": asset.pre_total_asset,
|
||||
"total_commission": asset.total_commission,
|
||||
"total_stamp_tax": asset.total_stamp_tax,
|
||||
"total_transfer_fee": asset.total_transfer_fee,
|
||||
"total_slippage": asset.total_slippage,
|
||||
"total_cost": asset.total_cost,
|
||||
"trade_count": asset.trade_count,
|
||||
"max_drawdown": asset.max_drawdown,
|
||||
"max_drawdown_ratio": asset.max_drawdown_ratio,
|
||||
"leverage": asset.leverage,
|
||||
"init_time": asset.init_time,
|
||||
"last_trade_time": asset.last_trade_time,
|
||||
"update_time": asset.update_time,
|
||||
},
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
Logger.debug(f"Saved asset: {asset.instance_id}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
Logger.error(f"Failed to save asset: {e}")
|
||||
return False
|
||||
|
||||
def get_asset(self, instance_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""查询资产"""
|
||||
try:
|
||||
engine = self._get_engine()
|
||||
|
||||
query = text("""
|
||||
SELECT * FROM assets
|
||||
WHERE instance_id = :instance_id
|
||||
""")
|
||||
|
||||
with engine.connect() as conn:
|
||||
result = conn.execute(query, {"instance_id": instance_id})
|
||||
row = result.fetchone()
|
||||
|
||||
if row:
|
||||
return dict(row._mapping)
|
||||
return None
|
||||
|
||||
except Exception as e:
|
||||
Logger.error(f"Failed to get asset: {e}")
|
||||
return None
|
||||
@ -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:
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -8,14 +8,15 @@ from .table_schemas import (
|
||||
get_table_definition,
|
||||
get_all_table_names,
|
||||
TICK_TABLE,
|
||||
SIGNAL_TABLE,
|
||||
create_kline_table_definition,
|
||||
create_indicator_table_definition,
|
||||
)
|
||||
from .trading_table_schemas import (
|
||||
ORDER_TABLE,
|
||||
TRADE_TABLE,
|
||||
POSITION_TABLE,
|
||||
ACCOUNT_TABLE,
|
||||
SIGNAL_TABLE,
|
||||
SYMBOL_TABLE,
|
||||
create_kline_table_definition,
|
||||
create_indicator_table_definition,
|
||||
ASSET_TABLE,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
@ -27,9 +28,8 @@ __all__ = [
|
||||
"ORDER_TABLE",
|
||||
"TRADE_TABLE",
|
||||
"POSITION_TABLE",
|
||||
"ACCOUNT_TABLE",
|
||||
"ASSET_TABLE",
|
||||
"SIGNAL_TABLE",
|
||||
"SYMBOL_TABLE",
|
||||
"create_kline_table_definition",
|
||||
"create_indicator_table_definition",
|
||||
]
|
||||
|
||||
@ -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}")
|
||||
|
||||
@ -6,6 +6,12 @@
|
||||
|
||||
from typing import Dict, Any, List
|
||||
from .table_utils import SUPPORTED_PERIODS, SUPPORTED_INDICATORS
|
||||
from .trading_table_schemas import (
|
||||
ORDER_TABLE,
|
||||
TRADE_TABLE,
|
||||
POSITION_TABLE,
|
||||
ASSET_TABLE,
|
||||
)
|
||||
|
||||
# ==================== Tick 表 ====================
|
||||
TICK_TABLE = {
|
||||
@ -287,256 +293,6 @@ def create_indicator_table_definition(indicator: str, period: str) -> Dict[str,
|
||||
}
|
||||
|
||||
|
||||
# ==================== Order 表 ====================
|
||||
ORDER_TABLE = {
|
||||
"name": "orders",
|
||||
"comment": "订单表",
|
||||
"columns": {
|
||||
"id": {
|
||||
"type": "Integer",
|
||||
"primary_key": True,
|
||||
"nullable": False,
|
||||
"comment": "自增主键",
|
||||
},
|
||||
"order_id": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": False,
|
||||
"comment": "订单ID(唯一)",
|
||||
},
|
||||
"symbol": {
|
||||
"type": "String",
|
||||
"length": 20,
|
||||
"nullable": False,
|
||||
"comment": "标的代码",
|
||||
},
|
||||
"side": {
|
||||
"type": "String",
|
||||
"length": 10,
|
||||
"nullable": False,
|
||||
"comment": "方向(buy/sell)",
|
||||
},
|
||||
"order_type": {
|
||||
"type": "String",
|
||||
"length": 10,
|
||||
"nullable": False,
|
||||
"comment": "订单类型(limit/market/stop)",
|
||||
},
|
||||
"price": {"type": "Float", "nullable": False, "comment": "价格"},
|
||||
"volume": {"type": "Integer", "nullable": False, "comment": "数量"},
|
||||
"filled_volume": {
|
||||
"type": "Integer",
|
||||
"nullable": False,
|
||||
"default": 0,
|
||||
"comment": "已成交数量",
|
||||
},
|
||||
"status": {
|
||||
"type": "String",
|
||||
"length": 20,
|
||||
"nullable": False,
|
||||
"comment": "状态(pending/partial/filled/cancelled/rejected)",
|
||||
},
|
||||
"create_time": {"type": "DateTime", "nullable": False, "comment": "创建时间"},
|
||||
"update_time": {"type": "DateTime", "nullable": False, "comment": "更新时间"},
|
||||
"cancel_time": {"type": "DateTime", "nullable": True, "comment": "撤销时间"},
|
||||
"strategy_name": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": True,
|
||||
"comment": "来源策略",
|
||||
},
|
||||
"remark": {
|
||||
"type": "String",
|
||||
"length": 200,
|
||||
"nullable": True,
|
||||
"comment": "备注",
|
||||
},
|
||||
},
|
||||
"indexes": [
|
||||
{"name": "idx_order_id", "columns": ["order_id"], "unique": True},
|
||||
{"name": "idx_symbol_time", "columns": ["symbol", "create_time"]},
|
||||
{"name": "idx_status", "columns": ["status"]},
|
||||
{"name": "idx_strategy", "columns": ["strategy_name"]},
|
||||
],
|
||||
}
|
||||
|
||||
# ==================== Trade 表 ====================
|
||||
TRADE_TABLE = {
|
||||
"name": "trades",
|
||||
"comment": "成交记录表",
|
||||
"columns": {
|
||||
"id": {
|
||||
"type": "Integer",
|
||||
"primary_key": True,
|
||||
"nullable": False,
|
||||
"comment": "自增主键",
|
||||
},
|
||||
"trade_id": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": False,
|
||||
"comment": "成交ID(唯一)",
|
||||
},
|
||||
"order_id": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": False,
|
||||
"comment": "订单ID",
|
||||
},
|
||||
"symbol": {
|
||||
"type": "String",
|
||||
"length": 20,
|
||||
"nullable": False,
|
||||
"comment": "标的代码",
|
||||
},
|
||||
"side": {
|
||||
"type": "String",
|
||||
"length": 10,
|
||||
"nullable": False,
|
||||
"comment": "方向(buy/sell)",
|
||||
},
|
||||
"price": {"type": "Float", "nullable": False, "comment": "成交价"},
|
||||
"volume": {"type": "Integer", "nullable": False, "comment": "成交量"},
|
||||
"amount": {"type": "Float", "nullable": False, "comment": "成交额"},
|
||||
"commission": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "手续费",
|
||||
},
|
||||
"trade_time": {"type": "DateTime", "nullable": False, "comment": "成交时间"},
|
||||
"strategy_name": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": True,
|
||||
"comment": "来源策略",
|
||||
},
|
||||
},
|
||||
"indexes": [
|
||||
{"name": "idx_trade_id", "columns": ["trade_id"], "unique": True},
|
||||
{"name": "idx_order_id", "columns": ["order_id"]},
|
||||
{"name": "idx_symbol_time", "columns": ["symbol", "trade_time"]},
|
||||
{"name": "idx_strategy", "columns": ["strategy_name"]},
|
||||
],
|
||||
}
|
||||
|
||||
# ==================== Position 表 ====================
|
||||
POSITION_TABLE = {
|
||||
"name": "positions",
|
||||
"comment": "持仓表",
|
||||
"columns": {
|
||||
"id": {
|
||||
"type": "Integer",
|
||||
"primary_key": True,
|
||||
"nullable": False,
|
||||
"comment": "自增主键",
|
||||
},
|
||||
"symbol": {
|
||||
"type": "String",
|
||||
"length": 20,
|
||||
"nullable": False,
|
||||
"comment": "标的代码",
|
||||
},
|
||||
"direction": {
|
||||
"type": "String",
|
||||
"length": 10,
|
||||
"nullable": False,
|
||||
"comment": "方向(long/short)",
|
||||
},
|
||||
"volume": {"type": "Integer", "nullable": False, "comment": "持仓量"},
|
||||
"available_volume": {"type": "Integer", "nullable": False, "comment": "可用量"},
|
||||
"frozen_volume": {
|
||||
"type": "Integer",
|
||||
"nullable": False,
|
||||
"default": 0,
|
||||
"comment": "冻结量",
|
||||
},
|
||||
"avg_price": {"type": "Float", "nullable": False, "comment": "平均成本"},
|
||||
"last_price": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "最新价",
|
||||
},
|
||||
"market_value": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "市值",
|
||||
},
|
||||
"unrealized_pnl": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "浮动盈亏",
|
||||
},
|
||||
"realized_pnl": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "已实现盈亏",
|
||||
},
|
||||
"today_volume": {
|
||||
"type": "Integer",
|
||||
"nullable": False,
|
||||
"default": 0,
|
||||
"comment": "今日买入量(T+1)",
|
||||
},
|
||||
"update_time": {"type": "DateTime", "nullable": False, "comment": "更新时间"},
|
||||
},
|
||||
"indexes": [
|
||||
{
|
||||
"name": "idx_symbol_direction",
|
||||
"columns": ["symbol", "direction"],
|
||||
"unique": True,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
# ==================== Account 表 ====================
|
||||
ACCOUNT_TABLE = {
|
||||
"name": "accounts",
|
||||
"comment": "账户表",
|
||||
"columns": {
|
||||
"id": {
|
||||
"type": "Integer",
|
||||
"primary_key": True,
|
||||
"nullable": False,
|
||||
"comment": "自增主键",
|
||||
},
|
||||
"account_id": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": False,
|
||||
"comment": "账户ID(唯一)",
|
||||
},
|
||||
"total_asset": {"type": "Float", "nullable": False, "comment": "总资产"},
|
||||
"available_cash": {"type": "Float", "nullable": False, "comment": "可用资金"},
|
||||
"frozen_cash": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "冻结资金",
|
||||
},
|
||||
"market_value": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "持仓市值",
|
||||
},
|
||||
"total_pnl": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "总盈亏",
|
||||
},
|
||||
"update_time": {"type": "DateTime", "nullable": False, "comment": "更新时间"},
|
||||
},
|
||||
"indexes": [
|
||||
{"name": "idx_account_id", "columns": ["account_id"], "unique": True},
|
||||
],
|
||||
}
|
||||
|
||||
# ==================== Signal 表 ====================
|
||||
SIGNAL_TABLE = {
|
||||
"name": "signals",
|
||||
@ -554,6 +310,12 @@ SIGNAL_TABLE = {
|
||||
"nullable": False,
|
||||
"comment": "信号ID(唯一)",
|
||||
},
|
||||
"instance_id": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": False,
|
||||
"comment": "策略实例ID",
|
||||
},
|
||||
"strategy_name": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
@ -597,79 +359,13 @@ SIGNAL_TABLE = {
|
||||
},
|
||||
"indexes": [
|
||||
{"name": "idx_signal_id", "columns": ["signal_id"], "unique": True},
|
||||
{"name": "idx_instance", "columns": ["instance_id"]},
|
||||
{"name": "idx_strategy_symbol", "columns": ["strategy_name", "symbol"]},
|
||||
{"name": "idx_executed", "columns": ["executed"]},
|
||||
{"name": "idx_generate_time", "columns": ["generate_time"]},
|
||||
],
|
||||
}
|
||||
|
||||
# ==================== Symbol 表 ====================
|
||||
SYMBOL_TABLE = {
|
||||
"name": "symbols",
|
||||
"comment": "标的信息表",
|
||||
"columns": {
|
||||
"id": {
|
||||
"type": "Integer",
|
||||
"primary_key": True,
|
||||
"nullable": False,
|
||||
"comment": "自增主键",
|
||||
},
|
||||
"symbol": {
|
||||
"type": "String",
|
||||
"length": 20,
|
||||
"nullable": False,
|
||||
"comment": "标的代码(唯一)",
|
||||
},
|
||||
"name": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": False,
|
||||
"comment": "标的名称",
|
||||
},
|
||||
"exchange": {
|
||||
"type": "String",
|
||||
"length": 10,
|
||||
"nullable": False,
|
||||
"comment": "交易所",
|
||||
},
|
||||
"product_type": {
|
||||
"type": "String",
|
||||
"length": 10,
|
||||
"nullable": False,
|
||||
"comment": "产品类型(stock/future/option/fund)",
|
||||
},
|
||||
"lot_size": {
|
||||
"type": "Integer",
|
||||
"nullable": False,
|
||||
"default": 100,
|
||||
"comment": "最小交易单位",
|
||||
},
|
||||
"tick_size": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.01,
|
||||
"comment": "最小价格变动",
|
||||
},
|
||||
"margin_rate": {
|
||||
"type": "Float",
|
||||
"nullable": True,
|
||||
"comment": "保证金比例(期货)",
|
||||
},
|
||||
"multiplier": {
|
||||
"type": "Integer",
|
||||
"nullable": True,
|
||||
"comment": "合约乘数(期货)",
|
||||
},
|
||||
"listed_date": {"type": "DateTime", "nullable": True, "comment": "上市日期"},
|
||||
"delisted_date": {"type": "DateTime", "nullable": True, "comment": "退市日期"},
|
||||
},
|
||||
"indexes": [
|
||||
{"name": "idx_symbol", "columns": ["symbol"], "unique": True},
|
||||
{"name": "idx_exchange", "columns": ["exchange"]},
|
||||
{"name": "idx_product_type", "columns": ["product_type"]},
|
||||
],
|
||||
}
|
||||
|
||||
# ==================== 所有表定义 ====================
|
||||
# 动态生成所有周期的K线表
|
||||
ALL_KLINE_TABLES = {
|
||||
@ -690,12 +386,12 @@ ALL_TABLES = {
|
||||
**ALL_KLINE_TABLES,
|
||||
**ALL_INDICATOR_TABLES,
|
||||
"ticks": TICK_TABLE,
|
||||
"signals": SIGNAL_TABLE,
|
||||
# 交易相关表(从 trading_table_schemas 导入)
|
||||
"orders": ORDER_TABLE,
|
||||
"trades": TRADE_TABLE,
|
||||
"positions": POSITION_TABLE,
|
||||
"accounts": ACCOUNT_TABLE,
|
||||
"signals": SIGNAL_TABLE,
|
||||
"symbols": SYMBOL_TABLE,
|
||||
"assets": ASSET_TABLE,
|
||||
}
|
||||
|
||||
|
||||
|
||||
561
src/database_manager/trading_table_schemas.py
Normal file
561
src/database_manager/trading_table_schemas.py
Normal file
@ -0,0 +1,561 @@
|
||||
"""
|
||||
交易数据表结构定义
|
||||
|
||||
为 Order, Trade, Position, Asset 模型定义表结构
|
||||
"""
|
||||
|
||||
# ==================== Order 表 ====================
|
||||
ORDER_TABLE = {
|
||||
"name": "orders",
|
||||
"comment": "订单表(包含策略实例隔离)",
|
||||
"columns": {
|
||||
"id": {
|
||||
"type": "Integer",
|
||||
"primary_key": True,
|
||||
"auto_increment": True,
|
||||
"nullable": False,
|
||||
"comment": "自增主键",
|
||||
},
|
||||
# 基本信息
|
||||
"order_id": {
|
||||
"type": "String",
|
||||
"length": 100,
|
||||
"nullable": False,
|
||||
"comment": "订单ID(唯一)",
|
||||
},
|
||||
"instance_id": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": False,
|
||||
"comment": "策略实例ID",
|
||||
},
|
||||
"strategy_name": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": False,
|
||||
"comment": "策略类名",
|
||||
},
|
||||
# 标的信息
|
||||
"symbol": {
|
||||
"type": "String",
|
||||
"length": 20,
|
||||
"nullable": False,
|
||||
"comment": "标的代码",
|
||||
},
|
||||
"symbol_name": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": True,
|
||||
"comment": "标的名称",
|
||||
},
|
||||
# 订单信息
|
||||
"side": {
|
||||
"type": "String",
|
||||
"length": 10,
|
||||
"nullable": False,
|
||||
"comment": "方向(buy/sell)",
|
||||
},
|
||||
"order_type": {
|
||||
"type": "String",
|
||||
"length": 10,
|
||||
"nullable": False,
|
||||
"comment": "订单类型(limit/market/stop)",
|
||||
},
|
||||
"price": {"type": "Float", "nullable": False, "comment": "委托价格"},
|
||||
"volume": {"type": "Integer", "nullable": False, "comment": "委托数量"},
|
||||
# 成交信息
|
||||
"filled_volume": {
|
||||
"type": "Integer",
|
||||
"nullable": False,
|
||||
"default": 0,
|
||||
"comment": "已成交数量",
|
||||
},
|
||||
"filled_price": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "成交均价",
|
||||
},
|
||||
"actual_price": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "实际价格(含滑点)",
|
||||
},
|
||||
"status": {
|
||||
"type": "String",
|
||||
"length": 20,
|
||||
"nullable": False,
|
||||
"comment": "状态(pending/partial/filled/cancelled/rejected)",
|
||||
},
|
||||
# 成本信息(JSON存储)
|
||||
"cost_detail": {
|
||||
"type": "Text",
|
||||
"nullable": True,
|
||||
"comment": "成本明细(JSON格式)",
|
||||
},
|
||||
# 时间信息
|
||||
"create_time": {"type": "DateTime", "nullable": False, "comment": "创建时间"},
|
||||
"submit_time": {"type": "DateTime", "nullable": True, "comment": "提交时间"},
|
||||
"filled_time": {
|
||||
"type": "DateTime",
|
||||
"nullable": True,
|
||||
"comment": "完全成交时间",
|
||||
},
|
||||
"cancel_time": {"type": "DateTime", "nullable": True, "comment": "撤销时间"},
|
||||
"update_time": {"type": "DateTime", "nullable": False, "comment": "更新时间"},
|
||||
# 附加信息
|
||||
"reason": {
|
||||
"type": "String",
|
||||
"length": 200,
|
||||
"nullable": True,
|
||||
"comment": "交易原因",
|
||||
},
|
||||
"remark": {
|
||||
"type": "String",
|
||||
"length": 200,
|
||||
"nullable": True,
|
||||
"comment": "备注",
|
||||
},
|
||||
},
|
||||
"indexes": [
|
||||
{"name": "idx_order_id", "columns": ["order_id"], "unique": True},
|
||||
{"name": "idx_instance", "columns": ["instance_id"]},
|
||||
{"name": "idx_instance_symbol", "columns": ["instance_id", "symbol"]},
|
||||
{"name": "idx_symbol_time", "columns": ["symbol", "create_time"]},
|
||||
{"name": "idx_status", "columns": ["status"]},
|
||||
{"name": "idx_strategy", "columns": ["strategy_name"]},
|
||||
],
|
||||
}
|
||||
|
||||
# ==================== Trade 表 ====================
|
||||
TRADE_TABLE = {
|
||||
"name": "trades",
|
||||
"comment": "成交记录表(包含策略实例隔离)",
|
||||
"columns": {
|
||||
"id": {
|
||||
"type": "Integer",
|
||||
"primary_key": True,
|
||||
"auto_increment": True,
|
||||
"nullable": False,
|
||||
"comment": "自增主键",
|
||||
},
|
||||
# 基本信息
|
||||
"trade_id": {
|
||||
"type": "String",
|
||||
"length": 100,
|
||||
"nullable": False,
|
||||
"comment": "成交ID(唯一)",
|
||||
},
|
||||
"order_id": {
|
||||
"type": "String",
|
||||
"length": 100,
|
||||
"nullable": False,
|
||||
"comment": "关联订单ID",
|
||||
},
|
||||
"instance_id": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": False,
|
||||
"comment": "策略实例ID",
|
||||
},
|
||||
"strategy_name": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": False,
|
||||
"comment": "策略类名",
|
||||
},
|
||||
# 标的信息
|
||||
"symbol": {
|
||||
"type": "String",
|
||||
"length": 20,
|
||||
"nullable": False,
|
||||
"comment": "标的代码",
|
||||
},
|
||||
"symbol_name": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": True,
|
||||
"comment": "标的名称",
|
||||
},
|
||||
# 成交信息
|
||||
"side": {
|
||||
"type": "String",
|
||||
"length": 10,
|
||||
"nullable": False,
|
||||
"comment": "方向(buy/sell)",
|
||||
},
|
||||
"price": {"type": "Float", "nullable": False, "comment": "成交价"},
|
||||
"volume": {"type": "Integer", "nullable": False, "comment": "成交量"},
|
||||
"amount": {"type": "Float", "nullable": False, "comment": "成交额"},
|
||||
# 成本信息(JSON存储)
|
||||
"cost_detail": {
|
||||
"type": "Text",
|
||||
"nullable": True,
|
||||
"comment": "成本明细(JSON格式)",
|
||||
},
|
||||
# 时间信息
|
||||
"trade_time": {"type": "DateTime", "nullable": False, "comment": "成交时间"},
|
||||
},
|
||||
"indexes": [
|
||||
{"name": "idx_trade_id", "columns": ["trade_id"], "unique": True},
|
||||
{"name": "idx_order_id", "columns": ["order_id"]},
|
||||
{"name": "idx_instance", "columns": ["instance_id"]},
|
||||
{"name": "idx_instance_symbol", "columns": ["instance_id", "symbol"]},
|
||||
{"name": "idx_symbol_time", "columns": ["symbol", "trade_time"]},
|
||||
{"name": "idx_strategy", "columns": ["strategy_name"]},
|
||||
],
|
||||
}
|
||||
|
||||
# ==================== Position 表 ====================
|
||||
POSITION_TABLE = {
|
||||
"name": "positions",
|
||||
"comment": "持仓表(包含策略实例隔离)",
|
||||
"columns": {
|
||||
"id": {
|
||||
"type": "Integer",
|
||||
"primary_key": True,
|
||||
"auto_increment": True,
|
||||
"nullable": False,
|
||||
"comment": "自增主键",
|
||||
},
|
||||
# 基本信息
|
||||
"instance_id": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": False,
|
||||
"comment": "策略实例ID",
|
||||
},
|
||||
"strategy_name": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": False,
|
||||
"comment": "策略类名",
|
||||
},
|
||||
# 标的信息
|
||||
"symbol": {
|
||||
"type": "String",
|
||||
"length": 20,
|
||||
"nullable": False,
|
||||
"comment": "标的代码",
|
||||
},
|
||||
"symbol_name": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": True,
|
||||
"comment": "标的名称",
|
||||
},
|
||||
"symbol_type": {
|
||||
"type": "String",
|
||||
"length": 20,
|
||||
"nullable": True,
|
||||
"comment": "标的类型",
|
||||
},
|
||||
"decimal_places": {
|
||||
"type": "Integer",
|
||||
"nullable": False,
|
||||
"default": 2,
|
||||
"comment": "价格小数位数",
|
||||
},
|
||||
# 持仓信息
|
||||
"direction": {
|
||||
"type": "String",
|
||||
"length": 10,
|
||||
"nullable": False,
|
||||
"comment": "方向(long/short)",
|
||||
},
|
||||
"volume": {"type": "Integer", "nullable": False, "comment": "持仓量"},
|
||||
"available_volume": {"type": "Integer", "nullable": False, "comment": "可用量"},
|
||||
"frozen_volume": {
|
||||
"type": "Integer",
|
||||
"nullable": False,
|
||||
"default": 0,
|
||||
"comment": "冻结量",
|
||||
},
|
||||
"today_volume": {
|
||||
"type": "Integer",
|
||||
"nullable": False,
|
||||
"default": 0,
|
||||
"comment": "今日买入量",
|
||||
},
|
||||
"yesterday_volume": {
|
||||
"type": "Integer",
|
||||
"nullable": False,
|
||||
"default": 0,
|
||||
"comment": "昨日持仓量",
|
||||
},
|
||||
# 成本和价格
|
||||
"avg_cost": {"type": "Float", "nullable": False, "comment": "平均成本价"},
|
||||
"current_price": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "最新价",
|
||||
},
|
||||
"open_price": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "建仓价格",
|
||||
},
|
||||
# 市值和盈亏
|
||||
"market_value": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "市值",
|
||||
},
|
||||
"cost_value": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "成本价值",
|
||||
},
|
||||
"unrealized_pnl": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "浮动盈亏",
|
||||
},
|
||||
"unrealized_pnl_ratio": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "浮动盈亏率",
|
||||
},
|
||||
"realized_pnl": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "已实现盈亏",
|
||||
},
|
||||
"realized_pnl_ratio": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "已实现盈亏率",
|
||||
},
|
||||
# 持仓占比
|
||||
"position_ratio": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "持仓占比",
|
||||
},
|
||||
# 交易统计
|
||||
"buy_times": {
|
||||
"type": "Integer",
|
||||
"nullable": False,
|
||||
"default": 0,
|
||||
"comment": "买入次数",
|
||||
},
|
||||
"sell_times": {
|
||||
"type": "Integer",
|
||||
"nullable": False,
|
||||
"default": 0,
|
||||
"comment": "卖出次数",
|
||||
},
|
||||
"total_cost": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "累计交易成本",
|
||||
},
|
||||
# 时间信息
|
||||
"first_buy_time": {
|
||||
"type": "DateTime",
|
||||
"nullable": True,
|
||||
"comment": "首次买入时间",
|
||||
},
|
||||
"last_trade_time": {
|
||||
"type": "DateTime",
|
||||
"nullable": True,
|
||||
"comment": "最后交易时间",
|
||||
},
|
||||
"update_time": {"type": "DateTime", "nullable": False, "comment": "更新时间"},
|
||||
},
|
||||
"indexes": [
|
||||
{
|
||||
"name": "idx_instance_symbol",
|
||||
"columns": ["instance_id", "symbol"],
|
||||
"unique": True,
|
||||
},
|
||||
{"name": "idx_instance", "columns": ["instance_id"]},
|
||||
{"name": "idx_symbol", "columns": ["symbol"]},
|
||||
{"name": "idx_strategy", "columns": ["strategy_name"]},
|
||||
],
|
||||
}
|
||||
|
||||
# ==================== Asset 表(Account重命名)====================
|
||||
ASSET_TABLE = {
|
||||
"name": "assets",
|
||||
"comment": "资产账户表(包含策略实例隔离)",
|
||||
"columns": {
|
||||
"id": {
|
||||
"type": "Integer",
|
||||
"primary_key": True,
|
||||
"auto_increment": True,
|
||||
"nullable": False,
|
||||
"comment": "自增主键",
|
||||
},
|
||||
# 基本信息
|
||||
"instance_id": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": False,
|
||||
"comment": "策略实例ID(唯一)",
|
||||
},
|
||||
"strategy_name": {
|
||||
"type": "String",
|
||||
"length": 50,
|
||||
"nullable": False,
|
||||
"comment": "策略类名",
|
||||
},
|
||||
# 资金信息
|
||||
"initial_capital": {"type": "Float", "nullable": False, "comment": "初始资金"},
|
||||
"total_asset": {"type": "Float", "nullable": False, "comment": "总资产"},
|
||||
"cash": {"type": "Float", "nullable": False, "comment": "现金"},
|
||||
"available_cash": {"type": "Float", "nullable": False, "comment": "可用资金"},
|
||||
"frozen_cash": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "冻结资金",
|
||||
},
|
||||
# 市值信息
|
||||
"market_value": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "持仓市值",
|
||||
},
|
||||
"long_market_value": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "多头市值",
|
||||
},
|
||||
"short_market_value": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "空头市值",
|
||||
},
|
||||
# 盈亏信息
|
||||
"total_pnl": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "总盈亏",
|
||||
},
|
||||
"total_return": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "总收益率",
|
||||
},
|
||||
"unrealized_pnl": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "浮动盈亏",
|
||||
},
|
||||
"realized_pnl": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "已实现盈亏",
|
||||
},
|
||||
# 当日数据
|
||||
"daily_pnl": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "当日盈亏",
|
||||
},
|
||||
"daily_return": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "当日收益率",
|
||||
},
|
||||
"pre_total_asset": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "前一日总资产",
|
||||
},
|
||||
# 交易成本统计
|
||||
"total_commission": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "累计佣金",
|
||||
},
|
||||
"total_stamp_tax": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "累计印花税",
|
||||
},
|
||||
"total_transfer_fee": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "累计过户费",
|
||||
},
|
||||
"total_slippage": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "累计滑点成本",
|
||||
},
|
||||
"total_cost": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "累计总成本",
|
||||
},
|
||||
"trade_count": {
|
||||
"type": "Integer",
|
||||
"nullable": False,
|
||||
"default": 0,
|
||||
"comment": "交易次数",
|
||||
},
|
||||
# 风控指标
|
||||
"max_drawdown": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "最大回撤",
|
||||
},
|
||||
"max_drawdown_ratio": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "最大回撤率",
|
||||
},
|
||||
"leverage": {
|
||||
"type": "Float",
|
||||
"nullable": False,
|
||||
"default": 0.0,
|
||||
"comment": "杠杆率",
|
||||
},
|
||||
# 时间信息
|
||||
"init_time": {
|
||||
"type": "DateTime",
|
||||
"nullable": True,
|
||||
"comment": "账户初始化时间",
|
||||
},
|
||||
"last_trade_time": {
|
||||
"type": "DateTime",
|
||||
"nullable": True,
|
||||
"comment": "最后交易时间",
|
||||
},
|
||||
"update_time": {"type": "DateTime", "nullable": False, "comment": "更新时间"},
|
||||
},
|
||||
"indexes": [
|
||||
{"name": "idx_instance_id", "columns": ["instance_id"], "unique": True},
|
||||
{"name": "idx_strategy", "columns": ["strategy_name"]},
|
||||
],
|
||||
}
|
||||
@ -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}")
|
||||
|
||||
@ -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")
|
||||
|
||||
@ -4,41 +4,145 @@ 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
|
||||
|
||||
logger = get_logger("QTradeServer")
|
||||
|
||||
# 策略管理器
|
||||
strategy_manager: Optional[StrategyManager] = None
|
||||
from src.cache.cache_manager import CacheManager
|
||||
from src.database_manager.db_manager import DatabaseManager
|
||||
from src.data_storage.mysql_storage import MySQLStorage
|
||||
|
||||
|
||||
def initialize_strategy_manager(config_dir: str = "config/strategies"):
|
||||
# ==================== 全局对象 ====================
|
||||
stratge_config_dir: str = "config/strategies"
|
||||
strategy_manager = None
|
||||
cache_manager = None
|
||||
db_manager = None
|
||||
|
||||
|
||||
def initialize_server(cfg_file: str, strategy_cfg_dir: str) -> bool:
|
||||
"""
|
||||
初始化策略管理器
|
||||
初始化服务器
|
||||
|
||||
Args:
|
||||
config_dir: 策略配置文件目录
|
||||
cfg_file: 配置文件路径
|
||||
strategy_cfg_dir: 策略配置文件目录
|
||||
"""
|
||||
global strategy_manager
|
||||
global strategy_manager, cache_manager, db_manager
|
||||
stratge_config_dir = strategy_cfg_dir
|
||||
|
||||
logger.info("Initializing StrategyManager...")
|
||||
# 1. 第一步:初始化配置(全局单例)
|
||||
print(f"Loading configuration from {cfg_file}...")
|
||||
try:
|
||||
Config.initialize(cfg_file)
|
||||
print("✓ Configuration loaded successfully")
|
||||
except Exception as e:
|
||||
print(f"✗ Failed to load configuration: {e}")
|
||||
import traceback
|
||||
|
||||
# 创建策略管理器
|
||||
strategy_manager = StrategyManager(config_dir)
|
||||
|
||||
# 初始化(加载配置并创建实例)
|
||||
if not strategy_manager.initialize():
|
||||
logger.error("Failed to initialize StrategyManager")
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
logger.info("StrategyManager initialized successfully")
|
||||
# 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")
|
||||
except Exception as e:
|
||||
Logger.warning(f"Failed to initialize DatabaseManager: {e}")
|
||||
db_manager = None
|
||||
return False
|
||||
|
||||
# 4. 初始化缓存管理器(传入db_manager用于数据库降级)
|
||||
cache_manager = CacheManager(db_manager=db_manager)
|
||||
if cache_manager is None:
|
||||
Logger.error("Failed to create CacheManager")
|
||||
return False
|
||||
else:
|
||||
Logger.info("CacheManager initialized")
|
||||
|
||||
# 4. 初始化策略管理器(传入共享资源)
|
||||
strategy_manager = StrategyManager(
|
||||
config_dir=stratge_config_dir, cache_manager=cache_manager
|
||||
)
|
||||
if strategy_manager is None:
|
||||
Logger.error("Failed to create StrategyManager")
|
||||
return False
|
||||
|
||||
# 4. 加载并初始化所有策略
|
||||
if not strategy_manager.initialize():
|
||||
Logger.error("Failed to initialize StrategyManager")
|
||||
return False
|
||||
|
||||
Logger.info("QTrade Server initialized successfully")
|
||||
return True
|
||||
|
||||
|
||||
def save_cache_to_database(cache_manager: CacheManager, db_manager: DatabaseManager):
|
||||
"""
|
||||
保存缓存数据到数据库
|
||||
|
||||
Args:
|
||||
cache_manager: 缓存管理器
|
||||
db_manager: 数据库管理器
|
||||
"""
|
||||
try:
|
||||
# 获取缓存统计信息
|
||||
stats = cache_manager.get_stats()
|
||||
if stats["size"] == 0:
|
||||
Logger.info("No cache data to save")
|
||||
return
|
||||
|
||||
Logger.info(f"Saving {stats['size']} cache entries to database...")
|
||||
|
||||
# 使用Config单例
|
||||
storage = MySQLStorage(db_manager) # type: ignore
|
||||
|
||||
saved_count = 0
|
||||
failed_count = 0
|
||||
|
||||
# 遍历所有缓存的symbol和period
|
||||
for symbol, symbol_info in stats["symbols"].items():
|
||||
for period in symbol_info["periods"]:
|
||||
try:
|
||||
# 获取K线数据
|
||||
klines_data = cache_manager.get_klines_from_cache(symbol, period)
|
||||
|
||||
if klines_data is not None and not klines_data.empty:
|
||||
# 保存到数据库
|
||||
count = storage.save_klines(symbol, period, klines_data)
|
||||
if count > 0:
|
||||
saved_count += 1
|
||||
Logger.info(
|
||||
f"✓ Saved cache: {symbol}_{period} ({count} rows)"
|
||||
)
|
||||
else:
|
||||
failed_count += 1
|
||||
Logger.warning(f"✗ Failed to save: {symbol}_{period}")
|
||||
else:
|
||||
Logger.debug(f"Skip empty cache: {symbol}_{period}")
|
||||
|
||||
except Exception as e:
|
||||
failed_count += 1
|
||||
Logger.error(f"Error saving {symbol}_{period}: {e}")
|
||||
|
||||
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}")
|
||||
|
||||
|
||||
async def handle_kline_data(message: dict) -> dict:
|
||||
"""
|
||||
处理单条K线数据
|
||||
@ -62,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 = {
|
||||
@ -104,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:
|
||||
@ -134,31 +238,97 @@ async def handle_kline_batch(message: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def start_server(
|
||||
host: str = "0.0.0.0", port: int = 8000, config_dir: str = "config/strategies"
|
||||
):
|
||||
def start_server():
|
||||
"""
|
||||
启动服务器
|
||||
|
||||
Args:
|
||||
host: 监听地址
|
||||
port: 监听端口
|
||||
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 Dir: {config_dir}")
|
||||
logger.info("=" * 60)
|
||||
# 1. 首先初始化配置
|
||||
print("=" * 60)
|
||||
print("QTrade Strategy Server Starting")
|
||||
print("=" * 60)
|
||||
|
||||
# 初始化配置(使用 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")
|
||||
|
||||
# 初始化策略管理器
|
||||
if not initialize_strategy_manager(config_dir):
|
||||
logger.error("Failed to initialize, server will not start")
|
||||
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...")
|
||||
|
||||
# 保存缓存到数据库
|
||||
if cache_manager and db_manager:
|
||||
try:
|
||||
Logger.info("Saving cache to database...")
|
||||
save_cache_to_database(cache_manager, db_manager)
|
||||
Logger.info("Cache saved successfully")
|
||||
except Exception as e:
|
||||
Logger.error(f"Failed to save cache: {e}")
|
||||
|
||||
Logger.info("Shutdown completed")
|
||||
sys.exit(0)
|
||||
|
||||
signal.signal(signal.SIGTERM, on_shutdown)
|
||||
signal.signal(signal.SIGINT, on_shutdown)
|
||||
|
||||
# 创建WebSocket服务器
|
||||
ws_server = WebSocketServer(title="QTrade Strategy Server", version="1.0.0")
|
||||
|
||||
|
||||
278
src/realtrade/miniqmt_client_adapter.py
Normal file
278
src/realtrade/miniqmt_client_adapter.py
Normal file
@ -0,0 +1,278 @@
|
||||
"""
|
||||
MiniQMT 实盘交易客户端适配器
|
||||
|
||||
负责业务逻辑:
|
||||
- 连接 MiniQMT 交易接口
|
||||
- 发送 K线数据到策略服务器
|
||||
- 接收交易信号
|
||||
- 执行实盘交易委托
|
||||
"""
|
||||
|
||||
from typing import Optional, Dict
|
||||
from datetime import datetime
|
||||
from dataclasses import dataclass
|
||||
import pandas as pd
|
||||
import uuid
|
||||
|
||||
from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
|
||||
from xtquant.xttype import StockAccount
|
||||
from xtquant import xtconstant
|
||||
from xtquant import xtdata
|
||||
|
||||
from src.networks.client.ws_client import WSClient
|
||||
from src.core.logger import Logger
|
||||
|
||||
g_wsclient: Optional[WSClient] = None
|
||||
|
||||
|
||||
def init_wsclient(server_url: str, timeout: int) -> WSClient:
|
||||
"""初始化全局 WSClient 实例"""
|
||||
global g_wsclient
|
||||
if g_wsclient is None:
|
||||
g_wsclient = WSClient(server_url, timeout)
|
||||
return g_wsclient
|
||||
|
||||
|
||||
def get_wsclient() -> Optional[WSClient]:
|
||||
"""获取全局 WSClient 实例"""
|
||||
global g_wsclient
|
||||
return g_wsclient
|
||||
|
||||
|
||||
# 实时行情数据回调
|
||||
# on_data(datas),回调参数datas格式为 { stock1 : data1, stock2 : data2, ... }
|
||||
def on_realtime_data(datas):
|
||||
Logger.info(f"Received realtime data: {datas}")
|
||||
wsclient = get_wsclient()
|
||||
if wsclient:
|
||||
message = []
|
||||
for symbol, data in datas.items():
|
||||
# 构造消息
|
||||
|
||||
message = {
|
||||
"symbol": symbol,
|
||||
"datetime": data.get(
|
||||
"datetime", datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
),
|
||||
"open": data.get("open", 0.0),
|
||||
"high": data.get("high", 0.0),
|
||||
"low": data.get("low", 0.0),
|
||||
"close": data.get("close", 0.0),
|
||||
"volume": data.get("volume", 0),
|
||||
}
|
||||
# respone = wsclient.send("kline_data", message)
|
||||
# 获取买卖信号
|
||||
|
||||
Logger.info(f"Sent data to server: {message}")
|
||||
|
||||
|
||||
class MiniQMTTraderCallback(XtQuantTraderCallback):
|
||||
"""MiniQMT 交易回调"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def on_disconnected(self):
|
||||
"""连接断开"""
|
||||
Logger.warning("MiniQMT 连接断开")
|
||||
|
||||
def on_stock_order(self, order):
|
||||
"""
|
||||
委托回报推送
|
||||
|
||||
Args:
|
||||
order: XtOrder对象
|
||||
"""
|
||||
Logger.info(
|
||||
f"委托回报: {order.stock_code}, "
|
||||
f"状态={order.order_status}, "
|
||||
f"系统编号={order.order_sysid}"
|
||||
)
|
||||
|
||||
def on_stock_trade(self, trade):
|
||||
"""
|
||||
成交变动推送
|
||||
|
||||
Args:
|
||||
trade: XtTrade对象
|
||||
"""
|
||||
Logger.info(
|
||||
f"成交回报: {trade.stock_code}, "
|
||||
f"订单ID={trade.order_id}, "
|
||||
f"成交价={trade.traded_price}, "
|
||||
f"成交量={trade.traded_volume}"
|
||||
)
|
||||
|
||||
def on_order_error(self, order_error):
|
||||
"""
|
||||
委托失败推送
|
||||
|
||||
Args:
|
||||
order_error: XtOrderError对象
|
||||
"""
|
||||
Logger.error(
|
||||
f"委托失败: 订单ID={order_error.order_id}, "
|
||||
f"错误码={order_error.error_id}, "
|
||||
f"错误信息={order_error.error_msg}"
|
||||
)
|
||||
|
||||
def on_cancel_error(self, cancel_error):
|
||||
"""
|
||||
撤单失败推送
|
||||
|
||||
Args:
|
||||
cancel_error: XtCancelError对象
|
||||
"""
|
||||
Logger.error(
|
||||
f"撤单失败: 订单ID={cancel_error.order_id}, "
|
||||
f"错误码={cancel_error.error_id}, "
|
||||
f"错误信息={cancel_error.error_msg}"
|
||||
)
|
||||
|
||||
def on_order_stock_async_response(self, response):
|
||||
"""
|
||||
异步下单回报
|
||||
|
||||
Args:
|
||||
response: XtOrderResponse对象
|
||||
"""
|
||||
Logger.info(
|
||||
f"异步下单回报: 订单ID={response.order_id}, 响应={response.order_remark}"
|
||||
)
|
||||
|
||||
def on_account_status(self, status):
|
||||
"""
|
||||
账户状态变化推送
|
||||
|
||||
Args:
|
||||
status: XtAccountStatus对象
|
||||
"""
|
||||
Logger.info(f"账户状态: {status.account_id}, 状态={status.account_type}")
|
||||
|
||||
|
||||
class MiniQMTClientAdapter:
|
||||
"""
|
||||
MiniQMT 实盘交易客户端适配器
|
||||
|
||||
负责:
|
||||
- 连接 MiniQMT 交易接口
|
||||
- 发送 K线数据到策略服务器获取信号
|
||||
- 执行实盘交易委托
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
server_url: str,
|
||||
timeout: int,
|
||||
miniqmt_path: str,
|
||||
session_id: int,
|
||||
account_id: str,
|
||||
account_type: str = "STOCK",
|
||||
stockpool: Optional[list] = None,
|
||||
):
|
||||
"""
|
||||
初始化 MiniQMT 客户端适配器
|
||||
|
||||
Args:
|
||||
server_url: 策略服务器 WebSocket 地址
|
||||
timeout: 超时时间(秒)
|
||||
miniqmt_path: MiniQMT userdata_mini 路径
|
||||
session_id: 会话ID(不同策略使用不同ID)
|
||||
account_id: 交易账号
|
||||
account_type: 账户类型(STOCK/HUGANGTONG/SHENGANGTONG)
|
||||
stockpool: 交易股票池(默认为空,表示全部股票)
|
||||
"""
|
||||
# 策略服务器 WebSocket 客户端
|
||||
init_wsclient(server_url, timeout)
|
||||
self.stockpool = stockpool if stockpool is not None else []
|
||||
# MiniQMT 交易客户端
|
||||
self.xt_trader = XtQuantTrader(miniqmt_path, session_id)
|
||||
self.account = StockAccount(account_id, account_type)
|
||||
self.callback = MiniQMTTraderCallback()
|
||||
# 注册回调
|
||||
self.xt_trader.register_callback(self.callback)
|
||||
|
||||
# 交易股票池
|
||||
if len(self.stockpool) == 0:
|
||||
Logger.warning("交易股票池为空,表示全部股票可交易")
|
||||
else:
|
||||
for symbol_info in self.stockpool:
|
||||
symbol = symbol_info.get("symbol")
|
||||
symbol_name = symbol_info.get("name", "")
|
||||
symbol_period = symbol_info.get("period")
|
||||
xtdata.subscribe_quote(
|
||||
symbol, period=symbol_period, callback=on_realtime_data
|
||||
)
|
||||
Logger.info(
|
||||
f"Subscribed to quote: {symbol} ({symbol_name}), period={symbol_period}"
|
||||
)
|
||||
|
||||
# 连接状态
|
||||
self.is_connected = False
|
||||
|
||||
Logger.info(
|
||||
f"MiniQMTClientAdapter initialized: "
|
||||
f"account={account_id}, type={account_type}"
|
||||
)
|
||||
|
||||
def run(self) -> bool:
|
||||
"""启动连接"""
|
||||
self.is_connected = self._connect()
|
||||
if not self.is_connected:
|
||||
Logger.error("MiniQMT 连接失败,无法运行客户端适配器")
|
||||
return self.is_connected
|
||||
|
||||
Logger.info("MiniQMT 客户端适配器运行中,按 Ctrl+C 退出")
|
||||
try:
|
||||
self.xt_trader.run_forever()
|
||||
except KeyboardInterrupt:
|
||||
Logger.info("收到退出信号,正在关闭连接...")
|
||||
self.close()
|
||||
return True
|
||||
|
||||
def close(self):
|
||||
"""关闭连接"""
|
||||
try:
|
||||
if self.is_connected:
|
||||
self.xt_trader.stop()
|
||||
self.is_connected = False
|
||||
Logger.info("MiniQMT 连接已关闭")
|
||||
|
||||
wsclient = get_wsclient()
|
||||
if wsclient:
|
||||
wsclient.close()
|
||||
Logger.info("WebSocket 连接已关闭")
|
||||
|
||||
except Exception as e:
|
||||
Logger.error(f"关闭连接异常: {e}")
|
||||
|
||||
def _connect(self) -> bool:
|
||||
"""
|
||||
连接 MiniQMT 交易接口
|
||||
|
||||
Returns:
|
||||
是否连接成功
|
||||
"""
|
||||
try:
|
||||
# 启动交易线程
|
||||
self.xt_trader.start()
|
||||
|
||||
# 建立交易连接
|
||||
connect_result = self.xt_trader.connect()
|
||||
if connect_result != 0:
|
||||
Logger.error(f"MiniQMT 连接失败: {connect_result}")
|
||||
return False
|
||||
|
||||
# 订阅账户推送
|
||||
subscribe_result = self.xt_trader.subscribe(self.account)
|
||||
if subscribe_result != 0:
|
||||
Logger.error(f"MiniQMT 订阅账户失败: {subscribe_result}")
|
||||
return False
|
||||
|
||||
self.is_connected = True
|
||||
Logger.info("MiniQMT 连接成功")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
Logger.error(f"MiniQMT 连接异常: {e}")
|
||||
return False
|
||||
@ -11,40 +11,38 @@
|
||||
"""
|
||||
|
||||
from typing import Dict, Any, Optional
|
||||
from src.core.base_strategy import BaseStrategy
|
||||
|
||||
|
||||
class DebugStrategy:
|
||||
class DebugStrategy(BaseStrategy):
|
||||
"""
|
||||
调试策略
|
||||
|
||||
只打印信息,不执行实际交易逻辑
|
||||
"""
|
||||
|
||||
def __init__(self, **params):
|
||||
"""
|
||||
初始化策略
|
||||
|
||||
Args:
|
||||
print_every: 每N条K线打印一次(默认1,即每条都打印)
|
||||
simulate_signal: 是否模拟生成信号(默认False)
|
||||
signal_threshold: 模拟信号触发阈值(默认5.0,价格变化百分比)
|
||||
"""
|
||||
self.print_every = params.get("print_every", 1)
|
||||
self.simulate_signal = params.get("simulate_signal", False)
|
||||
self.signal_threshold = params.get("signal_threshold", 5.0)
|
||||
def on_init(self):
|
||||
"""初始化回调"""
|
||||
# 策略参数
|
||||
self.print_every = self.params.get("print_every", 1)
|
||||
self.simulate_signal = self.params.get("simulate_signal", False)
|
||||
self.signal_threshold = self.params.get("signal_threshold", 5.0)
|
||||
|
||||
# 状态
|
||||
self.kline_count = 0
|
||||
self.last_price = None
|
||||
|
||||
print(f"[DebugStrategy] Initialized with params: {params}")
|
||||
print(f"[DebugStrategy] Initialized: {self.context.instance_id}")
|
||||
print(f" Symbol: {self.context.symbol}")
|
||||
print(f" Params: {self.params}")
|
||||
print(f" Initial Capital: {self.context.get_capital().initial_cash:.2f}")
|
||||
|
||||
def on_bar(self, bar_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
||||
def compute(self, kline_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
处理K线数据
|
||||
|
||||
Args:
|
||||
bar_data: K线数据字典
|
||||
kline_data: K线数据字典
|
||||
|
||||
Returns:
|
||||
信号字典(如果生成信号)或None
|
||||
@ -52,17 +50,17 @@ class DebugStrategy:
|
||||
self.kline_count += 1
|
||||
|
||||
# 提取K线数据
|
||||
symbol = bar_data.get("symbol", "UNKNOWN")
|
||||
timestamp = bar_data.get("timestamp", "")
|
||||
open_price = bar_data.get("open", 0)
|
||||
high = bar_data.get("high", 0)
|
||||
low = bar_data.get("low", 0)
|
||||
close = bar_data.get("close", 0)
|
||||
volume = bar_data.get("volume", 0)
|
||||
symbol = kline_data.get("symbol", "UNKNOWN")
|
||||
timestamp = kline_data.get("timestamp", "")
|
||||
open_price = kline_data.get("open", 0)
|
||||
high = kline_data.get("high", 0)
|
||||
low = kline_data.get("low", 0)
|
||||
close = kline_data.get("close", 0)
|
||||
volume = kline_data.get("volume", 0)
|
||||
|
||||
# 按设定频率打印K线信息
|
||||
if self.kline_count % self.print_every == 0:
|
||||
print(f"\n[DebugStrategy] K-line #{self.kline_count}")
|
||||
print(f"\n[{self.context.instance_id}] K-line #{self.kline_count}")
|
||||
print(f" Symbol: {symbol}")
|
||||
print(f" Time: {timestamp}")
|
||||
print(
|
||||
@ -70,6 +68,14 @@ class DebugStrategy:
|
||||
)
|
||||
print(f" Volume: {volume}")
|
||||
|
||||
# 打印持仓和资金信息
|
||||
position = self.context.get_position()
|
||||
capital = self.context.get_capital()
|
||||
print(
|
||||
f" Position: {position.shares:.2f} shares @ {position.avg_price:.2f}"
|
||||
)
|
||||
print(f" Capital: {capital.available_cash:.2f}")
|
||||
|
||||
# 计算价格变化
|
||||
if self.last_price is not None:
|
||||
price_change = ((close - self.last_price) / self.last_price) * 100
|
||||
@ -88,7 +94,7 @@ class DebugStrategy:
|
||||
"quantity": 100,
|
||||
"reason": f"Price increased by {price_change_pct:.2f}%",
|
||||
}
|
||||
print(f"\n[DebugStrategy] 🟢 BUY Signal Generated!")
|
||||
print(f"\n[{self.context.instance_id}] 🟢 BUY Signal Generated!")
|
||||
print(f" Reason: {signal['reason']}")
|
||||
|
||||
elif price_change_pct < -self.signal_threshold:
|
||||
@ -99,7 +105,7 @@ class DebugStrategy:
|
||||
"quantity": 100,
|
||||
"reason": f"Price decreased by {price_change_pct:.2f}%",
|
||||
}
|
||||
print(f"\n[DebugStrategy] 🔴 SELL Signal Generated!")
|
||||
print(f"\n[{self.context.instance_id}] 🔴 SELL Signal Generated!")
|
||||
print(f" Reason: {signal['reason']}")
|
||||
|
||||
# 更新状态
|
||||
@ -107,18 +113,6 @@ class DebugStrategy:
|
||||
|
||||
return signal
|
||||
|
||||
def compute(self, bar_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
处理K线数据(compute接口,与on_bar相同)
|
||||
|
||||
Args:
|
||||
bar_data: K线数据字典
|
||||
|
||||
Returns:
|
||||
信号字典(如果生成信号)或None
|
||||
"""
|
||||
return self.on_bar(bar_data)
|
||||
|
||||
def get_status(self) -> Dict[str, Any]:
|
||||
"""
|
||||
获取策略状态
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
"""
|
||||
"""
|
||||
策略管理器 (Strategy Manager)
|
||||
|
||||
负责:
|
||||
@ -14,9 +14,8 @@ from pathlib import Path
|
||||
import yaml
|
||||
import importlib
|
||||
|
||||
from src.core.logger import get_logger
|
||||
|
||||
logger = get_logger("StrategyManager")
|
||||
from src.core.strategy_context import StrategyContext
|
||||
from src.core.logger import Logger
|
||||
|
||||
|
||||
class StrategyManager:
|
||||
@ -29,15 +28,22 @@ class StrategyManager:
|
||||
- 动态加载策略类
|
||||
"""
|
||||
|
||||
def __init__(self, config_dir: str = "config/strategies"):
|
||||
def __init__(
|
||||
self,
|
||||
config_dir: str,
|
||||
cache_manager,
|
||||
):
|
||||
"""
|
||||
初始化策略管理器
|
||||
|
||||
Args:
|
||||
config_dir: 策略配置文件目录
|
||||
cache_manager: 缓存管理器(共享实例)
|
||||
"""
|
||||
self.config_dir = Path(config_dir)
|
||||
|
||||
# 直接持有共享资源
|
||||
self._cache_manager = cache_manager
|
||||
# 策略实例字典: {instance_id: strategy_object}
|
||||
self.instances: Dict[str, Any] = {}
|
||||
|
||||
@ -47,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:
|
||||
"""
|
||||
@ -58,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:
|
||||
@ -78,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:
|
||||
@ -103,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
|
||||
|
||||
# 创建每个策略实例
|
||||
@ -119,19 +125,31 @@ 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
|
||||
|
||||
# 创建策略实例
|
||||
strategy_obj = strategy_class(**params)
|
||||
# 创建策略上下文
|
||||
context = StrategyContext(
|
||||
cache_manager=self._cache_manager,
|
||||
instance_id=instance_id,
|
||||
symbol=symbol,
|
||||
instance_config=config,
|
||||
)
|
||||
|
||||
# 创建策略实例(传入context)
|
||||
strategy_obj = strategy_class(context=context, **params)
|
||||
|
||||
# 调用初始化回调
|
||||
if hasattr(strategy_obj, "on_init"):
|
||||
strategy_obj.on_init()
|
||||
|
||||
# 存储实例
|
||||
self.instances[instance_id] = strategy_obj
|
||||
@ -141,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(f"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):
|
||||
@ -190,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:
|
||||
@ -223,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}"
|
||||
)
|
||||
|
||||
@ -257,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
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -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
|
||||
|
||||
Loading…
Reference in New Issue
Block a user