Compare commits

..

5 Commits

Author SHA1 Message Date
b44f761c2b 重构通信层:分离业务逻辑和通信细节,实现策略管理器 2025-12-26 19:54:54 +08:00
14caec147b Major refactor: Separate business logic from communication layer
Created strategy_service module with complete architecture:
- ConfigLoader: Load and validate strategy configurations
- StrategyManager: Manage all strategy instances
- PositionManager: Track positions and capital for each instance
- RiskManager: Multi-level risk control (global/instance/signal)
- TradeRecorder: Record all signals and trades
- StrategyExecutor: Core coordinator for strategy execution

Key features:
- One symbol can have multiple independent strategy instances
- Each instance has isolated capital and positions
- No signal aggregation - each instance returns independent signals
- Multi-level risk management
- Configuration-driven strategy deployment
- Clean separation: ws_server (communication) vs strategy_service (business)

Files added:
- src/strategy_service/*.py (6 core modules)
- config/strategy_config.yaml (example configuration)
- src/networks/server/ws_server_refactored.py (new server)
- docs/backend_refactor.md (architecture documentation)

Protocol changes:
- Response now returns multiple signals (TRADE_SIGNALS)
- Each signal includes instance_id for tracking
- Added TRADE_RESULT message for trade feedback
2025-12-26 18:14:56 +08:00
61feb5daa0 Add batch kline sending method and fix type hints
- Added send_klines_batch() method in BacktestClientAdapter for sending multiple symbols' klines in one request
- Updated imports to include Dict and List types
- Fixed Pylance type checking warning in xtquant_downloader.py (added type: ignore for xtdc.close())
- Updated bt_engine.py for compatibility with new adapter methods
2025-12-26 17:49:13 +08:00
67b85ab232 Refactor: Implement WebSocket architecture with separated communication and business logic layers
- Implemented WebSocket protocol v1.0 specification with protocol headers, versioning, and batch support
- Renamed qtrade_server.py -> ws_server.py, client_adapter.py -> ws_client.py to reflect WebSocket implementation
- Created pure communication layer (WSClient) with only connect/send/close functionality
- Created business logic layer (BacktestClientAdapter) for protocol construction and signal parsing
- Updated bt_engine.py to use BacktestClientAdapter for strategy communication
- Fixed datetime formatting issues (time.strftime -> datetime.now().strftime for %f support)
- Fixed WebSocket 1000 OK close code logging issue
- Translated all logger output from Chinese to English for better compatibility
- Successfully tested with 242 K-lines data transmission

Architecture changes:
- networks/ layer: Pure WebSocket communication (no business logic)
- backtest/ layer: Business logic (protocol v1.0 message construction)
- Clear separation of concerns between transport and application layers
2025-12-25 16:15:56 +08:00
b4fd5492ed 重构K线查看器:模块化代码结构,修复Pylance错误
- 移除重复的datetime导入
- 添加类型注解(typing.Any)支持Pylance类型检查
- 提取配置加载为独立方法(_load_indicator_config, _load_macd_config, _load_rsi_config)
- 提取指标计算为独立方法(_calculate_macd, _calculate_rsi)
- 提取键盘导航功能为独立方法(_handle_scroll_left/right, _handle_zoom_in/out等)
- 提取鼠标悬停信息构建为独立方法(_build_hover_info)
- 添加None检查防止类型错误
- 统一时间选择器逻辑:Tab切换时不修改时间范围
- 恢复30m周期支持
- 更新MACD/RSI配色方案(MACD快线白色慢线黄色,RSI快线黄色中线绿色慢线蓝色)
- 删除旧的cache示例文件
2025-12-24 13:38:34 +08:00
41 changed files with 4002 additions and 1203 deletions

15
config/global_config.yaml Normal file
View File

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

View File

@ -0,0 +1,17 @@
# 策略实例配置: 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%

View File

@ -0,0 +1,17 @@
# 策略实例配置: debug_600000
# 浦发银行 - 每5条打印一次
instance_id: "debug_600000"
symbol: "600000.SH"
strategy_class: "DebugStrategy"
capital: 120000
# 策略参数
params:
print_every: 5 # 每5条K线打印一次
simulate_signal: false
# 风控参数
risk:
max_position_ratio: 0.7
stop_loss: 0.04

View File

@ -0,0 +1,18 @@
# 策略实例配置: debug_signal_000001
# 平安银行 - 带信号模拟
instance_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

View File

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

View File

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

View File

@ -1,505 +0,0 @@
# 技术债务文档
> 记录当前架构中可以改进但非紧急的技术债务
> 版本:v1.0
> 日期:2025-12-20
---
## 概述
本文档记录 QTrade 系统中已识别但暂未实现的技术改进项。这些改进项:
- ✅ 已被充分讨论和设计
- ⚠️ 当前架构可用,但有改进空间
- 📋 需要在合适的时机实施
---
## 技术债务总览
| 编号 | 加入时间 | 债务描述 | 优先级 | 影响分析 | 解决方案 |
|------|---------|---------|--------|---------|---------|
| [TD-001](#-td-001-配置类改用-pydantic) | 2025-12-20 | 配置类使用 dict,缺乏类型安全和验证 | 🟡 中 | 配置错误只能运行时发现;缺少 IDE 提示;维护困难 | [Pydantic 配置模型](#-td-001-配置类改用-pydantic) |
| [TD-002](#-td-002-validationresult-改用-pydantic) | 2025-12-20 | ValidationResult 使用简单类 | 🟢 低 | API 序列化不便;缺少类型检查 | [Pydantic 模型](#-td-002-validationresult-改用-pydantic) |
| [TD-003](#-td-003-关键-dataframe-使用-pandera-验证) | 2025-12-20 | DataFrame 无 schema 验证 | 🟢 低 | 列名拼写错误运行时才发现;缺少数据验证 | [Pandera Schema](#-td-003-关键-dataframe-使用-pandera-验证) |
| [TD-004](#-td-004-业务对象使用-pydantic未来需求) | 2025-12-20 | 缺少业务对象定义(Order/Position) | 🟢 低 | Phase 3 回测需要;类型不安全 | [业务对象模型](#-td-004-业务对象使用-pydantic未来需求) |
| [TD-005](#-td-005-redis-分布式缓存扩展性需求) | 2025-12-20 | 单机内存缓存,无法分布式共享 | 🟢 低 | 多进程无法共享;重启数据丢失 | [Redis 缓存实现](#-td-005-redis-分布式缓存扩展性需求) |
| [TD-006](#-td-006-性能监控和-profiling) | 2025-12-20 | 缺少性能监控和 Profiling | 🟢 低 | 无法发现性能瓶颈;缺少健康度监控 | [监控装饰器](#-td-006-性能监控和-profiling) |
**统计:**
- 总计:6 项技术债务
- 高优先级(🔴):0 项
- 中优先级(🟡):1 项
- 低优先级(🟢):5 项
---
## 债务分类
### 🔴 高优先级(影响性能或安全性)
需要在 Phase 3 前解决
### 🟡 中优先级(影响代码质量或可维护性)
可在 Phase 3 或 Phase 4 解决
### 🟢 低优先级(锦上添花)
可持续关注,按需实施
---
## 债务清单
### 🟡 TD-001: 配置类改用 Pydantic
**当前状态:** 使用 dict 管理配置
```python
# 当前实现
config = {
"cache": {
"enabled": True,
"mode": "static",
"max_memory_mb": 1024,
"auto_load": True,
"preload": {
"enabled": True,
"time_range": "1M",
"periods": ["1m", "1d"]
}
},
"database": {
"host": "localhost",
...
}
}
```
**建议改进:** 使用 Pydantic 模型
```python
# 建议实现
from pydantic import BaseModel, Field
from typing import Literal, List
class PreloadConfig(BaseModel):
enabled: bool = True
time_range: str = Field(default="1M", pattern=r"^\d+[MYD]$")
periods: List[str] = ["1m", "1d"]
class CacheConfig(BaseModel):
enabled: bool = True
mode: Literal["static", "dynamic"] = "static"
max_memory_mb: int = Field(default=1024, gt=0)
auto_load: bool = True
preload: PreloadConfig = PreloadConfig()
class DatabaseConfig(BaseModel):
host: str
port: int = Field(default=3306, gt=0, le=65535)
database: str
user: str
password: str
class Config(BaseModel):
cache: CacheConfig = CacheConfig()
database: DatabaseConfig
class Config:
# 支持从环境变量读取
env_prefix = "QTRADE_"
```
**优势:**
- ✅ 类型安全(IDE 自动补全)
- ✅ 配置验证(启动时发现错误)
- ✅ 默认值管理(集中管理)
- ✅ 文档自动生成(配置说明)
- ✅ 环境变量支持(部署灵活)
**成本估算:**
- 工作量:2-3 小时
- 影响范围:需要更新所有读取配置的代码
- 风险:低(纯重构,不改变逻辑)
**实施建议:**
- **时机:** Phase 2.5 或 Phase 3 初期
- **前置条件:** 无
- **阻塞问题:** 无
**参考资料:**
- Pydantic 文档:https://docs.pydantic.dev/
- Settings Management:https://docs.pydantic.dev/latest/concepts/pydantic_settings/
---
### 🟢 TD-002: ValidationResult 改用 Pydantic
**当前状态:** 使用简单的 Python 类
```python
class ValidationResult:
def __init__(self, passed: bool, details: Dict[str, Any]):
self.passed = passed
self.details = details
```
**建议改进:** 使用 Pydantic 模型
```python
from pydantic import BaseModel, Field
from typing import Dict, Any, List
class ValidationResult(BaseModel):
passed: bool
details: Dict[str, Any]
issues: List[str] = Field(default_factory=list)
total_records: int = 0
class Config:
# 允许额外字段(向后兼容)
extra = "allow"
```
**优势:**
- ✅ 类型安全
- ✅ 序列化支持(JSON)
- ✅ 如果未来提供 API,可直接使用
**成本估算:**
- 工作量:1 小时
- 影响范围:小(只在验证器内部使用)
- 风险:低
**实施建议:**
- **时机:** 如果需要暴露验证 API 时实施
- **前置条件:** 无
- **阻塞问题:** 无
- **备注:** 当前实现已经足够,非必要改动
---
### 🟢 TD-003: 关键 DataFrame 使用 Pandera 验证
**当前状态:** DataFrame 没有 schema 验证
```python
# 当前实现
def process_klines(df: pd.DataFrame) -> pd.DataFrame:
# 假设 df 包含正确的列,但没有验证
result = df['close'].rolling(20).mean()
return result
```
**建议改进:** 使用 Pandera 定义 Schema
```python
import pandera as pa
from pandera.typing import DataFrame
# 定义 K线 Schema
class KlineSchema(pa.DataFrameModel):
timestamp: pa.typing.Index[pd.DatetimeIndex]
open: float = pa.Field(ge=0, nullable=False)
high: float = pa.Field(ge=0, nullable=False)
low: float = pa.Field(ge=0, nullable=False)
close: float = pa.Field(ge=0, nullable=False)
volume: float = pa.Field(ge=0, nullable=False)
class Config:
strict = True # 不允许额外列
coerce = True # 自动类型转换
# 使用装饰器验证
@pa.check_types
def process_klines(df: DataFrame[KlineSchema]) -> pd.DataFrame:
# 如果 df 不符合 schema,抛出异常
result = df['close'].rolling(20).mean()
return result
```
**优势:**
- ✅ 防止列名拼写错误(编译时检查)
- ✅ 类型检查(IDE 支持)
- ✅ 数据验证(运行时检查)
- ✅ 文档化(Schema 即文档)
**劣势:**
- ❌ 增加依赖(pandera)
- ❌ 轻微性能开销(验证耗时)
- ❌ 学习成本
**成本估算:**
- 工作量:4-8 小时(定义所有 Schema)
- 影响范围:中等(核心数据流)
- 风险:中(可能发现隐藏的数据问题)
**实施建议:**
- **时机:** Phase 3 或 Phase 4
- **前置条件:** 系统稳定运行一段时间
- **阻塞问题:** 无
- **备注:** 可选功能,根据实际需求决定
**参考资料:**
- Pandera 文档:https://pandera.readthedocs.io/
---
### 🟢 TD-004: 业务对象使用 Pydantic(未来需求)
**当前状态:** 暂无业务对象定义
**未来需求:** 回测和实盘需要定义业务对象
**建议设计:**
```python
from pydantic import BaseModel, Field
from decimal import Decimal
from datetime import datetime
from typing import Literal
from enum import Enum
class OrderStatus(str, Enum):
PENDING = "pending"
FILLED = "filled"
CANCELLED = "cancelled"
REJECTED = "rejected"
class OrderSide(str, Enum):
BUY = "buy"
SELL = "sell"
class Order(BaseModel):
"""订单对象"""
order_id: str
symbol: str
side: OrderSide
price: Decimal = Field(gt=0)
quantity: int = Field(gt=0)
status: OrderStatus = OrderStatus.PENDING
created_at: datetime = Field(default_factory=datetime.now)
filled_at: datetime | None = None
class Config:
use_enum_values = True # 序列化时使用枚举值
class Position(BaseModel):
"""持仓对象"""
symbol: str
quantity: int
avg_cost: Decimal = Field(gt=0)
current_price: Decimal = Field(gt=0)
@property
def market_value(self) -> Decimal:
"""市值"""
return self.quantity * self.current_price
@property
def profit_loss(self) -> Decimal:
"""浮盈浮亏"""
return (self.current_price - self.avg_cost) * self.quantity
@property
def profit_loss_pct(self) -> Decimal:
"""收益率"""
return (self.current_price - self.avg_cost) / self.avg_cost
class Trade(BaseModel):
"""成交对象"""
trade_id: str
order_id: str
symbol: str
side: OrderSide
price: Decimal
quantity: int
commission: Decimal = Field(default=Decimal("0"))
executed_at: datetime
class Portfolio(BaseModel):
"""投资组合"""
account_id: str
cash: Decimal = Field(ge=0)
positions: List[Position] = Field(default_factory=list)
@property
def total_value(self) -> Decimal:
"""总资产"""
position_value = sum(p.market_value for p in self.positions)
return self.cash + position_value
@property
def total_profit_loss(self) -> Decimal:
"""总盈亏"""
return sum(p.profit_loss for p in self.positions)
```
**优势:**
- ✅ 类型安全
- ✅ 业务逻辑封装(@property)
- ✅ 验证规则(price > 0)
- ✅ 序列化支持(API、持久化)
**实施建议:**
- **时机:** Phase 3 回测模块开发时
- **前置条件:** 数据层稳定
- **阻塞问题:** 无
---
### 🟢 TD-005: Redis 分布式缓存(扩展性需求)
**当前状态:** 单机内存缓存
**未来需求:** 多进程/多机器共享缓存
**建议设计:**
```python
from redis import Redis
import pickle
class RedisCacheManager(CacheManager):
"""Redis 缓存管理器"""
def __init__(self, redis_client: Redis, ...):
self.redis = redis_client
super().__init__(...)
def get(self, symbol, period, ...):
key = self._make_key(symbol, period)
# 从 Redis 获取
data = self.redis.get(key)
if data:
df = pickle.loads(data) # 反序列化
return self._slice_data(df, start, end)
# 缓存未命中,加载并缓存
df = self.storage.load_klines(...)
if df is not None:
self.redis.set(key, pickle.dumps(df), ex=3600) # 1小时过期
return df
```
**优势:**
- ✅ 多进程共享缓存
- ✅ 持久化(重启不丢失)
- ✅ 分布式部署
**劣势:**
- ❌ 网络开销
- ❌ 序列化开销
- ❌ 运维复杂度
**实施建议:**
- **时机:** 当单机缓存不够用时
- **前置条件:** 有分布式部署需求
- **阻塞问题:** 需要 Redis 基础设施
- **备注:** 当前单机内存缓存足够
---
### 🟢 TD-006: 性能监控和 Profiling
**当前状态:** 基础日志
**建议改进:** 添加性能监控
```python
import time
from functools import wraps
def profile_time(func):
"""性能分析装饰器"""
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - start
# 记录到监控系统
logger.info(f"{func.__name__} took {elapsed:.3f}s")
metrics.record(f"function.{func.__name__}.duration", elapsed)
return result
return wrapper
# 使用
@profile_time
def get_klines(self, symbol, period, ...):
...
```
**优势:**
- ✅ 发现性能瓶颈
- ✅ 监控系统健康度
- ✅ 性能回归检测
**实施建议:**
- **时机:** Phase 3 或生产部署前
- **前置条件:** 无
- **阻塞问题:** 需要选择监控方案(Prometheus、Grafana)
---
## 实施优先级矩阵
| 债务编号 | 描述 | 优先级 | 工作量 | 价值 | 建议时机 |
| -------- | ------------------------------ | ------ | ------ | ---- | ----------- |
| TD-001 | 配置类改用 Pydantic | 🟡 中 | 2-3h | 高 | Phase 2.5/3 |
| TD-002 | ValidationResult 改用 Pydantic | 🟢 低 | 1h | 中 | 按需 |
| TD-003 | DataFrame 使用 Pandera | 🟢 低 | 4-8h | 中 | Phase 3/4 |
| TD-004 | 业务对象使用 Pydantic | 🟢 低 | 4-6h | 高 | Phase 3 |
| TD-005 | Redis 分布式缓存 | 🟢 低 | 8-16h | 中 | 按需 |
| TD-006 | 性能监控 | 🟢 低 | 4-8h | 高 | Phase 3 |
---
## 决策记录
### DR-001: 暂不实施配置类 Pydantic 化
**日期:** 2025-12-20
**决策:** 暂不改用 Pydantic,保持当前 dict 实现
**理由:**
1. 当前 dict 实现可用,没有阻塞性问题
2. Phase 2 重点是数据层稳定性,不引入新依赖
3. 可在 Phase 2.5 或 Phase 3 统一改进
**后续行动:**
- 记录在技术债务文档
- 在 Phase 3 规划中考虑
- 如果新增复杂配置项,重新评估
---
### DR-002: 数据层全程使用 DataFrame
**日期:** 2025-12-20
**决策:** 数据层(Storage/Cache/Service/Indicator)全程使用 DataFrame
**理由:**
1. 符合最佳实践(避免频繁转换)
2. 性能最优(向量化计算)
3. 边界清晰(API 层才用 Pydantic)
**设计原则:**
```
数据流 (DataFrame) ← 存储/缓存/计算
↕ 转换边界(仅在 API 层)
业务对象 (Pydantic) ← API/配置/业务逻辑
```
**后续行动:**
- 保持当前架构不变
- 文档化最佳实践
- 未来 API 层使用 Pydantic
---
## 回顾计划
- **每季度回顾:** 评估债务的紧急程度
- **版本规划:** 在每个 Phase 规划时考虑技术债务
- **持续更新:** 发现新债务时及时记录
---
## 参考资料
- [数据层架构设计文档](./tech_designs/data_layer_design.md)
- [缓存机制设计文档](./tech_designs/cache_design.md)
- [Pydantic 官方文档](https://docs.pydantic.dev/)
- [Pandera 官方文档](https://pandera.readthedocs.io/)

446
docs/websocket_protocol.md Normal file
View File

@ -0,0 +1,446 @@
# QTrade WebSocket通信协议规范 v1.0
## 1. 连接信息
- **服务器地址**: `ws://localhost:8000/ws/strategy`
- **协议**: WebSocket
- **数据格式**: JSON
- **字符编码**: UTF-8
- **协议版本**: v1.0
## 2. 协议头(Protocol Header)
所有消息必须包含协议头,用于版本控制和消息识别。
**协议头结构**:
```json
{
"header": {
"version": "1.0",
"msg_id": "uuid-string",
"timestamp": "2024-12-24 19:00:00.000"
},
...
}
```
**字段说明**:
| 字段 | 类型 | 必填 | 说明 |
| --------- | ------ | ---- | ------------------------ |
| version | string | 是 | 协议版本号,当前为"1.0" |
| msg_id | string | 是 | 消息唯一ID,建议使用UUID |
| timestamp | string | 是 | 消息时间戳,格式: YYYY-MM-DD HH:MM:SS.mmm |
## 3. 消息类型
### 3.1 客户端请求消息(K线数据)
**消息类型**: `KLINE_DATA` 或 `KLINE_DATA_BATCH`
#### 3.1.1 单条K线数据
**数据结构**:
```json
{
"header": {
"version": "1.0",
"msg_id": "550e8400-e29b-41d4-a716-446655440000",
"timestamp": "2024-12-24 19:00:00.000"
},
"msg_type": "KLINE_DATA",
"symbol": "000001.SZ",
"period": "1d",
"kline_time": "2024-01-01 09:30:00",
"data": {
"open": 10.50,
"high": 10.80,
"low": 10.40,
"close": 10.75,
"volume": 1000000
}
}
```
#### 3.1.2 批量K线数据
**数据结构**:
```json
{
"header": {
"version": "1.0",
"msg_id": "550e8400-e29b-41d4-a716-446655440001",
"timestamp": "2024-12-24 19:00:00.000"
},
"msg_type": "KLINE_DATA_BATCH",
"klines": [
{
"symbol": "000001.SZ",
"period": "1d",
"kline_time": "2024-01-01 09:30:00",
"data": {
"open": 10.50,
"high": 10.80,
"low": 10.40,
"close": 10.75,
"volume": 1000000
}
},
{
"symbol": "600000.SH",
"period": "1d",
"kline_time": "2024-01-01 09:30:00",
"data": {
"open": 8.20,
"high": 8.35,
"low": 8.15,
"close": 8.30,
"volume": 2000000
}
}
]
}
```
**字段说明**:
| 字段 | 类型 | 必填 | 说明 |
| ----------- | ------ | ---- | --------------------------------------------------------- |
| header | object | 是 | 协议头 |
| msg_type | string | 是 | 消息类型: "KLINE_DATA"(单条) 或 "KLINE_DATA_BATCH"(批量) |
| symbol | string | 是 | 股票代码,如"000001.SZ"、"600000.SH" |
| period | string | 是 | K线周期: "1m", "5m", "15m", "30m", "1h", "1d", "1w", "1M" |
| kline_time | string | 是 | K线时间,格式: YYYY-MM-DD HH:MM:SS |
| data.open | float | 是 | 开盘价 |
| data.high | float | 是 | 最高价 |
| data.low | float | 是 | 最低价 |
| data.close | float | 是 | 收盘价 |
| data.volume | int | 是 | 成交量 |
| klines | array | 是 | 批量模式下的K线数据列表 |
**周期说明**:
- `1m`: 1分钟
- `5m`: 5分钟
- `15m`: 15分钟
- `30m`: 30分钟
- `1h`: 1小时
- `1d`: 1天(日K线)
- `1w`: 1周(周K线)
- `1M`: 1月(月K线)
### 3.2 服务器响应消息(交易信号)
**消息类型**: `TRADE_SIGNAL` 或 `TRADE_SIGNAL_BATCH`
#### 3.2.1 单条交易信号
**数据结构**:
```json
{
"header": {
"version": "1.0",
"msg_id": "550e8400-e29b-41d4-a716-446655440002",
"timestamp": "2024-12-24 19:00:00.000",
"req_msg_id": "550e8400-e29b-41d4-a716-446655440000"
},
"msg_type": "TRADE_SIGNAL",
"symbol": "000001.SZ",
"action": "BUY",
"price": 10.75,
"quantity": 100,
"message": "MA金叉信号,建议买入"
}
```
**字段说明**:
| 字段 | 类型 | 必填 | 说明 |
| ----------------- | ------ | ---- | ------------------------------------------------- |
| header | object | 是 | 协议头 |
| header.req_msg_id | string | 是 | 对应的请求消息ID |
| msg_type | string | 是 | 消息类型,固定为"TRADE_SIGNAL" |
| symbol | string | 是 | 股票代码 |
| action | string | 是 | 交易动作: "BUY"(买入)、"SELL"(卖出)、"HOLD"(持有) |
| price | float | 是 | **建议交易价格**(明确在什么价位交易) |
| quantity | int | 是 | **交易数量**(股数,0表示不交易) |
| message | string | 否 | 信号说明或原因 |
**交易动作说明**:
- `BUY`: 买入,price为建议买入价,quantity为买入股数
- `SELL`: 卖出,price为建议卖出价,quantity为卖出股数
- `HOLD`: 持有,不进行交易,quantity为0
#### 3.2.2 批量交易信号
**数据结构**:
```json
{
"header": {
"version": "1.0",
"msg_id": "550e8400-e29b-41d4-a716-446655440003",
"timestamp": "2024-12-24 19:00:00.000",
"req_msg_id": "550e8400-e29b-41d4-a716-446655440001"
},
"msg_type": "TRADE_SIGNAL_BATCH",
"signals": [
{
"symbol": "000001.SZ",
"action": "BUY",
"price": 10.75,
"quantity": 100,
"message": "买入信号"
},
{
"symbol": "600000.SH",
"action": "HOLD",
"price": 8.30,
"quantity": 0,
"message": "观望"
}
]
}
```
### 3.3 错误消息
**消息类型**: `ERROR`
**数据结构**:
```json
{
"header": {
"version": "1.0",
"msg_id": "550e8400-e29b-41d4-a716-446655440004",
"timestamp": "2024-12-24 19:00:00.000",
"req_msg_id": "550e8400-e29b-41d4-a716-446655440000"
},
"msg_type": "ERROR",
"error_code": "INVALID_DATA",
"error_message": "K线数据格式错误: 缺少close字段"
}
```
**字段说明**:
| 字段 | 类型 | 必填 | 说明 |
| ----------------- | ------ | ---- | ----------------------- |
| header | object | 是 | 协议头 |
| header.req_msg_id | string | 否 | 导致错误的请求消息ID |
| msg_type | string | 是 | 消息类型,固定为"ERROR" |
| error_code | string | 是 | 错误代码 |
| error_message | string | 是 | 错误描述 |
**错误码列表**:
- `INVALID_VERSION`: 协议版本不支持
- `INVALID_DATA`: 数据格式错误
- `MISSING_FIELD`: 缺少必填字段
- `INVALID_SYMBOL`: 无效的股票代码
- `INVALID_PERIOD`: 无效的K线周期
- `STRATEGY_ERROR`: 策略执行错误
- `TIMEOUT`: 请求超时
## 4. 通信流程
### 4.1 单条K线流程
```
客户端 服务器
| |
|---- WebSocket连接 ------------------------>|
|<--- 连接成功 -------------------------------|
| |
|---- KLINE_DATA (000001.SZ, 1d) ------------->|
| |--- 执行策略
|<--- TRADE_SIGNAL (BUY, 100股@10.75) -------|
| |
|---- KLINE_DATA (000001.SZ, 1d) ------------->|
| |--- 执行策略
|<--- TRADE_SIGNAL (HOLD, 0股@10.80) --------|
```
### 4.2 批量K线流程
```
客户端 服务器
| |
|---- KLINE_DATA_BATCH (2支股票) ------------->|
| - 000001.SZ (1d) |
| - 600000.SH (1d) |
| |--- 执行策略
|<--- TRADE_SIGNAL_BATCH -------------------- |
| - 000001.SZ: BUY 100股@10.75 |
| - 600000.SH: HOLD 0股@8.30 |
```
## 5. 完整测试用例
### 5.1 单条K线买入信号
**客户端发送**:
```json
{
"header": {
"version": "1.0",
"msg_id": "test-001",
"timestamp": "2024-12-24 19:00:00.000"
},
"msg_type": "KLINE_DATA",
"symbol": "000001.SZ",
"period": "1d",
"kline_time": "2024-01-02 09:30:00",
"data": {
"open": 10.50,
"high": 10.80,
"low": 10.40,
"close": 10.75,
"volume": 1000000
}
}
```
**服务器响应**:
```json
{
"header": {
"version": "1.0",
"msg_id": "resp-001",
"timestamp": "2024-12-24 19:00:00.000",
"req_msg_id": "test-001"
},
"msg_type": "TRADE_SIGNAL",
"symbol": "000001.SZ",
"action": "BUY",
"price": 10.75,
"quantity": 100,
"message": "策略建议在10.75价位买入100股"
}
```
### 5.2 批量K线混合信号
**客户端发送**:
```json
{
"header": {
"version": "1.0",
"msg_id": "test-002",
"timestamp": "2024-12-24 19:00:00.000"
},
"msg_type": "KLINE_DATA_BATCH",
"klines": [
{
"symbol": "000001.SZ",
"period": "1d",
"kline_time": "2024-01-02 09:30:00",
"data": {"open": 10.50, "high": 10.80, "low": 10.40, "close": 10.75, "volume": 1000000}
},
{
"symbol": "600000.SH",
"period": "1d",
"kline_time": "2024-01-02 09:30:00",
"data": {"open": 8.20, "high": 8.35, "low": 8.15, "close": 8.30, "volume": 2000000}
}
]
}
```
**服务器响应**:
```json
{
"header": {
"version": "1.0",
"msg_id": "resp-002",
"timestamp": "2024-12-24 19:00:00.000",
"req_msg_id": "test-002"
},
"msg_type": "TRADE_SIGNAL_BATCH",
"signals": [
{
"symbol": "000001.SZ",
"action": "BUY",
"price": 10.75,
"quantity": 100,
"message": "在10.75价位买入100股"
},
{
"symbol": "600000.SH",
"action": "SELL",
"price": 8.30,
"quantity": 50,
"message": "在8.30价位卖出50股"
}
]
}
```
### 5.3 不同周期K线
**客户端发送(5分钟K线)**:
```json
{
"header": {
"version": "1.0",
"msg_id": "test-003",
"timestamp": "2024-12-24 19:00:00.000"
},
"msg_type": "KLINE_DATA",
"symbol": "000001.SZ",
"period": "5m",
"kline_time": "2024-01-02 09:35:00",
"data": {
"open": 10.50,
"high": 10.55,
"low": 10.48,
"close": 10.52,
"volume": 50000
}
}
```
## 6. 性能指标
- **协议版本**: v1.0
- **连接超时**: 30秒
- **消息超时**: 30秒
- **心跳间隔**: 20秒(Ping)
- **心跳超时**: 10秒(Pong)
- **批量大小**: 建议不超过100条K线
- **建议并发**: 单连接(回测场景)
## 7. 版本升级规则
- **主版本号**: 不兼容的协议变更(如修改必填字段)
- **次版本号**: 向后兼容的功能添加
- **修订号**: 向后兼容的问题修复
当前版本: **v1.0**
- 初始版本
- 支持单条和批量K线传输
- 支持多周期K线
- 明确价格和数量信息
## 8. 注意事项
1. **协议头必填**: 所有消息必须包含header,用于版本控制和追踪
2. **消息ID唯一**: msg_id必须全局唯一,建议使用UUID
3. **版本兼容**: 服务器应检查version字段,不支持的版本返回INVALID_VERSION错误
4. **价格和数量**: 交易信号必须明确指定price(交易价位)和quantity(交易股数)
5. **周期标准化**: period字段必须使用规定的格式(1m, 5m, 1d等)
6. **批量优化**: 多支股票同一时间的K线建议使用批量模式,提升效率
7. **响应关联**: 服务器响应的req_msg_id必须对应客户端请求的msg_id
8. **时间格式**: timestamp使用可读格式 YYYY-MM-DD HH:MM:SS.mmm
9. **交易动作**: action为BUY或SELL时,quantity必须大于0;HOLD时quantity为0
## 9. 当前实现状态
**已实现**:
- 基础WebSocket连接
- 协议头(version, msg_id, timestamp)
- 单条K线数据传输(v1.0格式)
- 交易信号响应(v1.0格式)
- 周期信息(period字段)
- 明确价格和数量(price和quantity必填)
- 错误消息规范(ERROR类型)
- 版本检查机制
**待实现**:
- 批量K线传输(KLINE_DATA_BATCH)
- 批量信号响应(TRADE_SIGNAL_BATCH)
- 心跳机制
- 请求追踪和关联优化

View File

@ -1,293 +0,0 @@
"""
缓存模块使用示例 - Phase 1
演示如何在实际场景中使用缓存管理器
"""
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
import logging
from datetime import datetime
import pandas as pd
from cache.cache_manager import CacheManager
from cache.market_data_cache import MarketDataCache
# 配置日志
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
class MockDBManager:
"""模拟数据库管理器"""
def get_klines(self, symbols, start_date, end_date, period):
"""返回模拟K线数据"""
logger.info(
f"Loading klines from DB: {symbols[0]}, {start_date} to {end_date}, period={period}"
)
# 生成模拟数据
date_range = pd.date_range(start=start_date, end=end_date, freq="1D")
data = {
"open": [100.0 + i * 0.5 for i in range(len(date_range))],
"high": [101.0 + i * 0.5 for i in range(len(date_range))],
"low": [99.0 + i * 0.5 for i in range(len(date_range))],
"close": [100.5 + i * 0.5 for i in range(len(date_range))],
"volume": [1000000 + i * 1000 for i in range(len(date_range))],
}
df = pd.DataFrame(data, index=date_range)
return df
def example_01_basic_usage():
"""示例1:基本使用"""
print("\n" + "=" * 60)
print("示例1:基本使用 - 缓存初始化、存取、统计")
print("=" * 60)
# 1. 初始化配置
config = {
"cache": {
"enabled": True,
"mode": "static",
"max_memory_mb": 1024,
"preload": {
"enabled": False # 暂不预加载
},
}
}
db_manager = MockDBManager()
cache_manager = CacheManager(config, db_manager)
# 2. 手动设置缓存
print("\n步骤1: 设置缓存数据")
test_data = {
"klines": pd.DataFrame(
{
"open": [100, 101, 102],
"high": [101, 102, 103],
"low": [99, 100, 101],
"close": [100.5, 101.5, 102.5],
"volume": [1000000, 1100000, 1200000],
},
index=pd.date_range("2025-01-01", periods=3, freq="1D"),
)
}
cache_manager.set("159915.SZ", "1d", test_data)
print("✓ 缓存已设置: 159915.SZ_1d")
# 3. 从缓存读取
print("\n步骤2: 从缓存读取数据")
klines = cache_manager.get("159915.SZ", "1d")
if klines is not None:
print(f"✓ 读取成功,共 {len(klines)} 条记录")
print(klines)
# 4. 查看统计信息
print("\n步骤3: 查看缓存统计")
stats = cache_manager.get_stats()
print(f"缓存大小: {stats['size']} 项")
print(f"内存占用: {stats['memory_mb']:.2f} MB")
print(f"命中率: {stats['hit_rate']:.1%}")
print(f"总请求数: {stats['total_requests']}")
def example_02_preload():
"""示例2:预加载功能"""
print("\n" + "=" * 60)
print("示例2:预加载功能 - 系统启动时批量加载数据")
print("=" * 60)
# 1. 配置预加载
config = {
"cache": {
"enabled": True,
"mode": "static",
"max_memory_mb": 1024,
"preload": {"enabled": True, "time_range": "1M", "periods": ["1d"]},
}
}
db_manager = MockDBManager()
cache_manager = CacheManager(config, db_manager)
# 2. 执行预加载
print("\n步骤1: 执行预加载")
symbols = ["159915.SZ", "601658.SH", "000001.SZ"]
cache_manager.preload(symbols)
# 3. 验证预加载结果
print("\n步骤2: 验证预加载结果")
stats = cache_manager.get_stats()
print(f"✓ 预加载完成,缓存 {stats['size']} 项")
print(f"✓ 内存占用: {stats['memory_mb']:.2f} MB")
# 4. 测试缓存命中
print("\n步骤3: 测试缓存命中")
klines = cache_manager.get("159915.SZ", "1d")
if klines is not None:
print(f"✓ 命中缓存,数据量: {len(klines)} 条")
# 5. 查看最终统计
stats = cache_manager.get_stats()
print("\n最终统计:")
print(f" 命中次数: {stats['hit_count']}")
print(f" 未命中次数: {stats['miss_count']}")
print(f" 命中率: {stats['hit_rate']:.1%}")
def example_03_time_range_query():
"""示例3:时间范围查询"""
print("\n" + "=" * 60)
print("示例3:时间范围查询 - 按日期范围查询数据")
print("=" * 60)
config = {
"cache": {"enabled": True, "mode": "static", "preload": {"enabled": False}}
}
db_manager = MockDBManager()
cache_manager = CacheManager(config, db_manager)
# 1. 准备数据(10天)
print("\n步骤1: 设置10天的K线数据")
date_range = pd.date_range("2025-01-01", periods=10, freq="1D")
test_data = {
"klines": pd.DataFrame(
{"close": [100 + i for i in range(10)]}, index=date_range
)
}
cache_manager.set("159915.SZ", "1d", test_data)
print("✓ 缓存已设置: 2025-01-01 到 2025-01-10")
# 2. 查询全部数据
print("\n步骤2: 查询全部数据")
all_data = cache_manager.get("159915.SZ", "1d")
if all_data is not None:
print(f"✓ 全部数据: {len(all_data)} 条")
# 3. 查询部分时间范围
print("\n步骤3: 查询 2025-01-03 到 2025-01-07")
start = datetime(2025, 1, 3)
end = datetime(2025, 1, 7)
partial_data = cache_manager.get("159915.SZ", "1d", start=start, end=end)
if partial_data is not None:
print(f"✓ 查询结果: {len(partial_data)} 条")
print(partial_data)
def example_04_invalidate():
"""示例4:缓存失效"""
print("\n" + "=" * 60)
print("示例4:缓存失效 - 清除缓存数据")
print("=" * 60)
config = {
"cache": {"enabled": True, "mode": "static", "preload": {"enabled": False}}
}
db_manager = MockDBManager()
cache_manager = CacheManager(config, db_manager)
# 1. 设置多个缓存
print("\n步骤1: 设置多个缓存项")
test_data = {"klines": pd.DataFrame({"close": [100]}, index=[datetime(2025, 1, 1)])}
cache_manager.set("159915.SZ", "1d", test_data)
cache_manager.set("159915.SZ", "1m", test_data)
cache_manager.set("601658.SH", "1d", test_data)
print(f"✓ 设置了 {cache_manager.get_stats()['size']} 个缓存项")
# 2. 失效特定缓存
print("\n步骤2: 失效 159915.SZ_1d")
cache_manager.invalidate("159915.SZ", "1d")
print(f"✓ 剩余 {cache_manager.get_stats()['size']} 个缓存项")
# 3. 失效某个标的所有周期
print("\n步骤3: 失效 159915.SZ 所有周期")
cache_manager.invalidate("159915.SZ")
print(f"✓ 剩余 {cache_manager.get_stats()['size']} 个缓存项")
# 4. 清空全部缓存
print("\n步骤4: 清空全部缓存")
cache_manager.invalidate()
print(f"✓ 剩余 {cache_manager.get_stats()['size']} 个缓存项")
def example_05_market_data_cache():
"""示例5:MarketDataCache使用"""
print("\n" + "=" * 60)
print("示例5:MarketDataCache - 市场数据专用缓存")
print("=" * 60)
config = {
"cache": {"enabled": True, "mode": "static", "preload": {"enabled": False}}
}
db_manager = MockDBManager()
cache_manager = CacheManager(config, db_manager)
market_cache = MarketDataCache(cache_manager)
# 1. 设置K线和指标数据
print("\n步骤1: 设置K线和指标数据")
date_range = pd.date_range("2025-01-01", periods=5, freq="1D")
test_data = {
"klines": pd.DataFrame({"close": [100, 101, 102, 103, 104]}, index=date_range),
"macd": pd.DataFrame(
{
"dif": [0.5, 0.6, 0.7, 0.8, 0.9],
"dea": [0.4, 0.5, 0.6, 0.7, 0.8],
"macd": [0.1, 0.1, 0.1, 0.1, 0.1],
},
index=date_range,
),
}
cache_manager.set("159915.SZ", "1d", test_data)
print("✓ K线和MACD指标已缓存")
# 2. 获取K线
print("\n步骤2: 获取K线数据")
klines = market_cache.get_klines("159915.SZ", "1d")
if klines is not None:
print(f"✓ K线数据: {len(klines)} 条")
print(klines)
# 3. 获取指标
print("\n步骤3: 获取MACD指标")
macd = market_cache.get_indicator("159915.SZ", "1d", "macd")
if macd is not None:
print(f"✓ MACD数据: {len(macd)} 条")
print(macd)
def main():
"""运行所有示例"""
print("\n" + "=" * 60)
print("缓存模块使用示例 - Phase 1")
print("=" * 60)
try:
example_01_basic_usage()
example_02_preload()
example_03_time_range_query()
example_04_invalidate()
example_05_market_data_cache()
print("\n" + "=" * 60)
print("✓ 所有示例运行完成!")
print("=" * 60)
except Exception as e:
logger.error(f"示例运行失败: {e}", exc_info=True)
if __name__ == "__main__":
main()

10
main.py Normal file
View File

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

View File

@ -34,3 +34,6 @@ pytz>=2023.0
# ==================== 数据源(可选) ====================
xtquant # 迅投QMT数据源
fastapi>=0.95.0 # 用于构建API服务
uvicorn[standard]
websockets>=11.0.0 # 用于WebSocket通信

View File

@ -9,7 +9,7 @@ import os
import io
import traceback
from datetime import datetime
from datetime import datetime
from typing import Any
from PyQt6.QtWidgets import (
QApplication,
@ -64,65 +64,13 @@ class KlineCanvas(FigureCanvasQTAgg):
self.setParent(parent)
# 存储完整数据
self.full_data = None
self.full_data: Any = None # DataFrame类型
self.current_start = 0 # 当前显示起始位置
self.current_end = 100 # 当前显示结束位置
self.display_count = 100 # 默认显示100条
# 加载指标配置参数 - 不使用默认值,读取失败直接报错
try:
config = Config("configs/global.yaml")
indicators_config = config.get("indicators")
if not indicators_config:
raise ValueError("配置文件中未找到 'indicators' 配置项")
# MACD参数
macd_config = indicators_config.get("macd")
if not macd_config:
raise ValueError("配置文件中未找到 'indicators.macd' 配置项")
if "fast_period" not in macd_config:
raise ValueError("配置文件中未找到 'indicators.macd.fast_period'")
if "slow_period" not in macd_config:
raise ValueError("配置文件中未找到 'indicators.macd.slow_period'")
if "signal_period" not in macd_config:
raise ValueError("配置文件中未找到 'indicators.macd.signal_period'")
self.macd_fast = macd_config["fast_period"]
self.macd_slow = macd_config["slow_period"]
self.macd_signal = macd_config["signal_period"]
print(
f"[配置] MACD参数: fast={self.macd_fast}, slow={self.macd_slow}, signal={self.macd_signal}"
)
# RSI参数
rsi_config = indicators_config.get("rsi")
if not rsi_config:
raise ValueError("配置文件中未找到 'indicators.rsi' 配置项")
if "fast" not in rsi_config:
raise ValueError("配置文件中未找到 'indicators.rsi.fast'")
if "mid" not in rsi_config:
raise ValueError("配置文件中未找到 'indicators.rsi.mid'")
if "slow" not in rsi_config:
raise ValueError("配置文件中未找到 'indicators.rsi.slow'")
self.rsi_fast = rsi_config["fast"]
self.rsi_mid = rsi_config["mid"]
self.rsi_slow = rsi_config["slow"]
print(
f"[配置] RSI参数: fast={self.rsi_fast}, mid={self.rsi_mid}, slow={self.rsi_slow}"
)
except Exception as e:
print(f"\n❌ 配置文件读取失败: {e}")
print("请检查 configs/global.yaml 文件中的 indicators 配置项")
import sys
sys.exit(1)
# 加载指标配置参数
self._load_indicator_config()
# 创建专业黑色主题样式(红涨绿跌)
self.style = mpf.make_mpf_style(
@ -158,15 +106,72 @@ class KlineCanvas(FigureCanvasQTAgg):
self._resize_timer = None
# 鼠标悬停显示数据
self.current_display_data = None # 当前显示的数据
self.current_macd_data = None # MACD数据
self.current_rsi_data = None # RSI数据
self.crosshair_vlines = [] # 十字光标垂直线列表(多个子图)
self.info_text = None # 信息文本
self.current_display_data: Any = None # 当前显示的数据(DataFrame)
self.current_macd_data: Any = None # MACD数据(DataFrame)
self.current_rsi_data: Any = None # RSI数据(DataFrame)
self.crosshair_vlines: list = [] # 十字光标垂直线列表(多个子图)
self.info_text: Any = None # 信息文本
# 连接鼠标移动事件
self.mpl_connect("motion_notify_event", self.on_mouse_move)
def _load_indicator_config(self):
"""加载指标配置参数"""
try:
config = Config("configs/global.yaml")
indicators_config = config.get("indicators")
if not indicators_config:
raise ValueError("配置文件中未找到 'indicators' 配置项")
# 加载MACD参数
self._load_macd_config(indicators_config)
# 加载RSI参数
self._load_rsi_config(indicators_config)
except Exception as e:
print(f"\n❌ 配置文件读取失败: {e}")
print("请检查 configs/global.yaml 文件中的 indicators 配置项")
sys.exit(1)
def _load_macd_config(self, indicators_config):
"""加载MACD配置"""
macd_config = indicators_config.get("macd")
if not macd_config:
raise ValueError("配置文件中未找到 'indicators.macd' 配置项")
required_keys = ["fast_period", "slow_period", "signal_period"]
for key in required_keys:
if key not in macd_config:
raise ValueError(f"配置文件中未找到 'indicators.macd.{key}'")
self.macd_fast = macd_config["fast_period"]
self.macd_slow = macd_config["slow_period"]
self.macd_signal = macd_config["signal_period"]
print(
f"[配置] MACD参数: fast={self.macd_fast}, slow={self.macd_slow}, signal={self.macd_signal}"
)
def _load_rsi_config(self, indicators_config):
"""加载RSI配置"""
rsi_config = indicators_config.get("rsi")
if not rsi_config:
raise ValueError("配置文件中未找到 'indicators.rsi' 配置项")
required_keys = ["fast", "mid", "slow"]
for key in required_keys:
if key not in rsi_config:
raise ValueError(f"配置文件中未找到 'indicators.rsi.{key}'")
self.rsi_fast = rsi_config["fast"]
self.rsi_mid = rsi_config["mid"]
self.rsi_slow = rsi_config["slow"]
print(
f"[配置] RSI参数: fast={self.rsi_fast}, mid={self.rsi_mid}, slow={self.rsi_slow}"
)
def resizeEvent(self, event):
"""处理窗口缩放事件 - 延迟重绘避免崩溃"""
super().resizeEvent(event)
@ -186,51 +191,8 @@ class KlineCanvas(FigureCanvasQTAgg):
# 获取鼠标位置对应的数据索引
x_index = int(round(event.xdata))
if 0 <= x_index < len(self.current_display_data):
# 获取该K线的数据
data_row = self.current_display_data.iloc[x_index]
# 获取时间信息(从_original_index列)
if "_original_index" in data_row:
time_value = data_row["_original_index"]
date_str = (
time_value.strftime("%Y-%m-%d %H:%M")
if hasattr(time_value, "strftime")
else str(time_value)
)
else:
date_str = f"Index: {x_index}"
# 构建显示文本 - OHLC
info_text = (
f"{date_str}\n"
f"O: {data_row['open']:.2f} H: {data_row['high']:.2f}\n"
f"L: {data_row['low']:.2f} C: {data_row['close']:.2f}\n"
f"Vol: {data_row['volume']:.0f}"
)
# 添加MACD数据
if self.current_macd_data is not None and x_index < len(
self.current_macd_data
):
macd_row = self.current_macd_data.iloc[x_index]
info_text += (
f"\n\nMACD\n"
f"DIF: {macd_row['dif']:.3f}\n"
f"DEA: {macd_row['dea']:.3f}\n"
f"Hist: {macd_row['histogram']:.3f}"
)
# 添加RSI数据
if self.current_rsi_data is not None and x_index < len(
self.current_rsi_data
):
rsi_row = self.current_rsi_data.iloc[x_index]
info_text += (
f"\n\nRSI\n"
f"RSI6: {rsi_row['rsi6']:.1f}\n"
f"RSI12: {rsi_row['rsi12']:.1f}\n"
f"RSI24: {rsi_row['rsi24']:.1f}"
)
# 构建信息文本
info_text = self._build_hover_info(x_index)
# 清除旧的十字光标和文本
for line in self.crosshair_vlines:
@ -276,71 +238,140 @@ class KlineCanvas(FigureCanvasQTAgg):
except Exception:
pass # 忽略鼠标移动时的错误
def _build_hover_info(self, x_index):
"""构建鼠标悬停时的信息文本"""
if self.current_display_data is None:
return ""
data_row = self.current_display_data.iloc[x_index]
# 获取时间信息
if "_original_index" in data_row:
time_value = data_row["_original_index"]
date_str = (
time_value.strftime("%Y-%m-%d %H:%M")
if hasattr(time_value, "strftime")
else str(time_value)
)
else:
date_str = f"Index: {x_index}"
# OHLC信息
info_text = (
f"{date_str}\n"
f"O: {data_row['open']:.2f} H: {data_row['high']:.2f}\n"
f"L: {data_row['low']:.2f} C: {data_row['close']:.2f}\n"
f"Vol: {data_row['volume']:.0f}"
)
# 添加MACD数据
if self.current_macd_data is not None and x_index < len(self.current_macd_data):
macd_row = self.current_macd_data.iloc[x_index]
info_text += (
f"\n\nMACD\n"
f"DIF: {macd_row['dif']:.3f}\n"
f"DEA: {macd_row['dea']:.3f}\n"
f"Hist: {macd_row['histogram']:.3f}"
)
# 添加RSI数据
if self.current_rsi_data is not None and x_index < len(self.current_rsi_data):
rsi_row = self.current_rsi_data.iloc[x_index]
info_text += (
f"\n\nRSI\n"
f"RSI6: {rsi_row['rsi6']:.1f}\n"
f"RSI12: {rsi_row['rsi12']:.1f}\n"
f"RSI24: {rsi_row['rsi24']:.1f}"
)
return info_text
def keyPressEvent(self, event):
"""处理键盘事件"""
if self.full_data is None or len(self.full_data) == 0:
return
step = max(1, self.display_count // 10) # 每次移动10%
key = event.key()
if key == Qt.Key.Key_Left:
self._handle_scroll_left()
elif key == Qt.Key.Key_Right:
self._handle_scroll_right()
elif key == Qt.Key.Key_Up:
self._handle_zoom_in()
elif key == Qt.Key.Key_Down:
self._handle_zoom_out()
elif key == Qt.Key.Key_Home:
self._handle_goto_start()
elif key == Qt.Key.Key_End:
self._handle_goto_end()
def _handle_scroll_left(self):
"""向左滚动"""
if self.full_data is None:
return
step = max(1, self.display_count // 10)
total_len = len(self.full_data)
if event.key() == Qt.Key.Key_Left:
# 左移
if self.current_start > 0:
self.current_start = max(0, self.current_start - step)
self.current_end = min(
total_len, self.current_start + self.display_count
)
self.update_display()
elif event.key() == Qt.Key.Key_Right:
# 右移
if self.current_end < total_len:
max_start = max(0, total_len - self.display_count)
self.current_start = min(max_start, self.current_start + step)
self.current_end = min(
total_len, self.current_start + self.display_count
)
self.update_display()
elif event.key() == Qt.Key.Key_Up:
# 放大(显示更少数据)
old_count = self.display_count
self.display_count = max(5, self.display_count - 5) # 每次减少5条
if self.display_count != old_count:
# 保持中心位置
center = (self.current_start + self.current_end) // 2
self.current_start = max(0, center - self.display_count // 2)
self.current_end = min(
total_len, self.current_start + self.display_count
)
self.update_display()
elif event.key() == Qt.Key.Key_Down:
# 缩小(显示更多数据)
old_count = self.display_count
self.display_count = min(total_len, self.display_count + 5) # 每次增加5条
if self.display_count != old_count:
# 保持中心位置
center = (self.current_start + self.current_end) // 2
self.current_start = max(0, center - self.display_count // 2)
self.current_end = min(
total_len, self.current_start + self.display_count
)
self.update_display()
elif event.key() == Qt.Key.Key_Home:
# 回到最开始
self.current_start = 0
self.current_end = min(total_len, self.display_count)
if self.current_start > 0:
self.current_start = max(0, self.current_start - step)
self.current_end = min(total_len, self.current_start + self.display_count)
self.update_display()
elif event.key() == Qt.Key.Key_End:
# 跳转到末尾
self.current_start = max(0, total_len - self.display_count)
self.current_end = total_len
def _handle_scroll_right(self):
"""向右滚动"""
if self.full_data is None:
return
step = max(1, self.display_count // 10)
total_len = len(self.full_data)
if self.current_end < total_len:
max_start = max(0, total_len - self.display_count)
self.current_start = min(max_start, self.current_start + step)
self.current_end = min(total_len, self.current_start + self.display_count)
self.update_display()
def _handle_zoom_in(self):
"""放大显示(显示更少数据)"""
if self.full_data is None:
return
total_len = len(self.full_data)
old_count = self.display_count
self.display_count = max(5, self.display_count - 5)
if self.display_count != old_count:
self._recenter_view(total_len)
def _handle_zoom_out(self):
"""缩小显示(显示更多数据)"""
if self.full_data is None:
return
total_len = len(self.full_data)
old_count = self.display_count
self.display_count = min(total_len, self.display_count + 5)
if self.display_count != old_count:
self._recenter_view(total_len)
def _handle_goto_start(self):
"""跳转到开始"""
if self.full_data is None:
return
total_len = len(self.full_data)
self.current_start = 0
self.current_end = min(total_len, self.display_count)
self.update_display()
def _handle_goto_end(self):
"""跳转到结束"""
if self.full_data is None:
return
total_len = len(self.full_data)
self.current_start = max(0, total_len - self.display_count)
self.current_end = total_len
self.update_display()
def _recenter_view(self, total_len):
"""缩放时重新居中视图"""
center = (self.current_start + self.current_end) // 2
self.current_start = max(0, center - self.display_count // 2)
self.current_end = min(total_len, self.current_start + self.display_count)
self.update_display()
def update_display(self):
"""更新显示区域"""
if self.full_data is None:
@ -509,27 +540,44 @@ class KlineCanvas(FigureCanvasQTAgg):
self.draw()
def _calculate_macd(self, df):
"""计算MACD指标"""
import pandas as pd
exp1 = df["close"].ewm(span=self.macd_fast, adjust=False).mean()
exp2 = df["close"].ewm(span=self.macd_slow, adjust=False).mean()
macd = exp1 - exp2
signal = macd.ewm(span=self.macd_signal, adjust=False).mean()
histogram = macd - signal
return pd.DataFrame(
{"dif": macd, "dea": signal, "histogram": histogram}
).reset_index(drop=True)
def _calculate_rsi(self, df, period):
"""计算单个周期的RSI"""
delta = df["close"].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
return rsi
def _plot_macd(self, df, ax):
"""绘制MACD指标(使用配置文件参数)"""
try:
import pandas as pd
# 数据量检查
min_length = self.macd_slow + self.macd_signal
if len(df) < min_length:
return
# 计算MACD(使用配置文件参数)
exp1 = df["close"].ewm(span=self.macd_fast, adjust=False).mean()
exp2 = df["close"].ewm(span=self.macd_slow, adjust=False).mean()
macd = exp1 - exp2
signal = macd.ewm(span=self.macd_signal, adjust=False).mean()
histogram = macd - signal
# 计算MACD
self.current_macd_data = self._calculate_macd(df)
# 保存MACD数据供鼠标悬停使用
self.current_macd_data = pd.DataFrame(
{"dif": macd, "dea": signal, "histogram": histogram}
).reset_index(drop=True)
# 提取数据
macd = self.current_macd_data["dif"]
signal = self.current_macd_data["dea"]
histogram = self.current_macd_data["histogram"]
# 绘制MACD柱状图(红涨绿跌)
colors = ["#ff0000" if x >= 0 else "#00ff00" for x in histogram]
@ -541,8 +589,8 @@ class KlineCanvas(FigureCanvasQTAgg):
width=0.8,
)
# 绘制MACD和信号线
ax.plot(macd.values, color="#00ffff", linewidth=1.5, label="MACD(DIF)")
# 绘制MACD和信号线(快线白色,慢线黄色)
ax.plot(macd.values, color="#ffffff", linewidth=1.5, label="MACD(DIF)")
ax.plot(signal.values, color="#ffff00", linewidth=1.5, label="DEA")
ax.axhline(0, color="white", linewidth=0.5, alpha=0.5)
@ -567,25 +615,18 @@ class KlineCanvas(FigureCanvasQTAgg):
if len(df) < self.rsi_slow + 1:
return
rsi_data = {}
# RSI颜色配置
colors = {
self.rsi_fast: "#ffff00",
self.rsi_mid: "#00ffff",
self.rsi_slow: "#ff00ff",
self.rsi_fast: "#ffff00", # 快线:黄色
self.rsi_mid: "#00ff00", # 中线:绿色
self.rsi_slow: "#0000ff", # 慢线:蓝色
}
# 计算RSI(使用配置文件参数)
# 计算并绘制RSI
rsi_data = {}
for period in [self.rsi_fast, self.rsi_mid, self.rsi_slow]:
delta = df["close"].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
# 保存RSI数据
rsi = self._calculate_rsi(df, period)
rsi_data[f"rsi{period}"] = rsi
# 绘制RSI线
ax.plot(
rsi.values,
color=colors[period],
@ -836,25 +877,7 @@ class SimpleKlineViewer(QMainWindow):
if index < 0 or index >= len(self.period_list):
return
tab_name, period = self.period_list[index]
# 调整日期范围
today = datetime.now()
if period == Period.DAY_1:
# 日线:默认一年
self.start_date_edit.setDate(QDate(2024, 1, 1))
self.end_date_edit.setDate(QDate(today.year, today.month, today.day))
else:
# 分钟线:默认最近15天
from datetime import timedelta
start_date = today - timedelta(days=15)
self.start_date_edit.setDate(
QDate(start_date.year, start_date.month, start_date.day)
)
self.end_date_edit.setDate(QDate(today.year, today.month, today.day))
# 自动加载数据
# 切换Tab时直接加载数据,不修改时间范围
self.load_current_tab_data()
def on_symbol_changed(self, symbol):

8
src/__main__.py Normal file
View File

@ -0,0 +1,8 @@
"""
QTrade Server 入口
"""
from src.qtrade_server import start_server
if __name__ == "__main__":
start_server()

View File

@ -0,0 +1,196 @@
"""
策略客户端适配器 (Strategy Client Adapter)
负责业务逻辑:
- 构建协议消息(K线数据、协议头等)
- 解析服务器响应(交易信号)
- 调用底层WebSocket客户端进行通信
"""
from typing import Optional, Dict, List
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")
@dataclass
class TradeSignal:
"""交易信号"""
symbol: str
action: str # "BUY", "SELL", "HOLD"
price: float # 建议交易价格
quantity: int # 交易数量(股数)
message: str = ""
req_msg_id: Optional[str] = None # 请求消息ID
class BacktestClientAdapter:
"""
策略客户端适配器
负责:
- 构建协议v1.0格式的消息
- 解析交易信号
- 调用WSClient发送消息
"""
def __init__(
self, server_url: str = "ws://localhost:8000/ws/strategy", timeout: int = 30
):
"""
初始化策略客户端适配器
Args:
server_url: WebSocket服务器地址
timeout: 超时时间(秒)
"""
self.ws_client = WSClient(server_url, timeout)
logger.info("BacktestClientAdapter initialized")
def _create_header(self) -> dict:
"""创建协议头 v1.0"""
return {
"version": "1.0",
"msg_id": str(uuid.uuid4()),
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3],
}
def send_kline(
self, symbol: str, kline: pd.Series, kline_time: datetime, period: str = "1d"
) -> Optional[TradeSignal]:
"""
发送K线数据到服务器
Args:
symbol: 标的代码
kline: K线数据(Series,包含open/high/low/close/volume)
kline_time: K线时间戳
period: K线周期 (1m, 5m, 15m, 30m, 1h, 1d, 1w, 1M)
Returns:
交易信号或None(如果请求失败)
"""
# 构建请求数据 v1.0
request_data = {
"header": self._create_header(),
"msg_type": "KLINE_DATA",
"symbol": symbol,
"period": period,
"kline_time": kline_time.strftime("%Y-%m-%d %H:%M:%S"),
"data": {
"open": float(kline["open"]),
"high": float(kline["high"]),
"low": float(kline["low"]),
"close": float(kline["close"]),
"volume": int(kline["volume"]),
},
}
# 发送消息
response = self.ws_client.send(request_data)
if not response:
return None
# 检查是否是错误消息
if response.get("msg_type") == "ERROR":
logger.error(
f"Server error: {response.get('error_code')} - {response.get('error_message')}"
)
return None
# 解析交易信号 v1.0
signal = TradeSignal(
symbol=response.get("symbol", symbol),
action=response.get("action", "HOLD"),
price=response.get("price", 0.0),
quantity=response.get("quantity", 0),
message=response.get("message", ""),
req_msg_id=response.get("header", {}).get("req_msg_id"),
)
return signal
def send_klines_batch(
self,
klines_data: Dict[str, pd.Series],
kline_time: datetime,
period: str = "1d",
) -> Dict[str, Optional[TradeSignal]]:
"""
批量发送多个标的的K线数据
Args:
klines_data: 字典,key为标的代码,value为K线数据(Series,包含open/high/low/close/volume)
kline_time: K线时间戳
period: K线周期 (1m, 5m, 15m, 30m, 1h, 1d, 1w, 1M)
Returns:
字典,key为标的代码,value为交易信号或None
"""
# 构建批量请求数据 v1.0
batch_data = []
for symbol, kline in klines_data.items():
batch_data.append(
{
"symbol": symbol,
"period": period,
"kline_time": kline_time.strftime("%Y-%m-%d %H:%M:%S"),
"data": {
"open": float(kline["open"]),
"high": float(kline["high"]),
"low": float(kline["low"]),
"close": float(kline["close"]),
"volume": int(kline["volume"]),
},
}
)
request_data = {
"header": self._create_header(),
"msg_type": "KLINE_DATA_BATCH",
"batch_data": batch_data,
}
# 发送消息
response = self.ws_client.send(request_data)
if not response:
return {symbol: None for symbol in klines_data.keys()}
# 检查是否是错误消息
if response.get("msg_type") == "ERROR":
logger.error(
f"Server error: {response.get('error_code')} - {response.get('error_message')}"
)
return {symbol: None for symbol in klines_data.keys()}
# 解析批量交易信号
results = {}
signals = response.get("signals", [])
for signal_data in signals:
symbol = signal_data.get("symbol")
if symbol:
results[symbol] = TradeSignal(
symbol=symbol,
action=signal_data.get("action", "HOLD"),
price=signal_data.get("price", 0.0),
quantity=signal_data.get("quantity", 0),
message=signal_data.get("message", ""),
req_msg_id=response.get("header", {}).get("req_msg_id"),
)
# 对于没有返回信号的标的,填充None
for symbol in klines_data.keys():
if symbol not in results:
results[symbol] = None
return results
def close(self):
"""关闭连接"""
self.ws_client.close()

136
src/backtest/bt_engine.py Normal file
View File

@ -0,0 +1,136 @@
"""
回测引擎 (Backtest Engine)
简单的回测引擎类
"""
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")
class BacktestEngine:
"""回测引擎"""
def __init__(
self,
data_service: DataService,
backtest_client: Optional[BacktestClientAdapter] = None,
):
"""
初始化回测引擎
Args:
data_service: 数据服务实例
backtest_client: 策略客户端适配器(可选,如果提供则发送数据到策略服务器)
"""
self.data_service = data_service
self.backtest_client = backtest_client
self.tasks: List[BacktestTask] = [] # 任务列表
if self.backtest_client:
logger.info("BacktestEngine initialized with BacktestClientAdapter")
else:
logger.info("BacktestEngine initialized without BacktestClientAdapter")
def add_task(self, task: BacktestTask) -> None:
"""
添加回测任务
Args:
task: 回测任务对象
"""
self.tasks.append(task)
logger.info(
f"Task added: {task.strategy_name} on {task.symbols} "
f"({task.start_date.date()} to {task.end_date.date()}, {task.period})"
)
def get_tasks(self) -> List[BacktestTask]:
"""
获取所有任务
Returns:
任务列表
"""
return self.tasks
def clear_tasks(self) -> None:
"""清空所有任务"""
self.tasks.clear()
logger.info("All tasks cleared")
def run(self) -> None:
"""运行所有回测任务"""
if not self.tasks:
logger.warning("No tasks to run")
return
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(
f"Symbols: {task.symbols}, Period: {task.period}, "
f"Time: {task.start_date.date()}~{task.end_date.date()}"
)
# 1. 获取数据
data_dict = {}
for symbol in task.symbols:
df = self.data_service.get_klines(
symbol=symbol,
period=task.period,
startdate=task.start_date,
enddate=task.end_date,
)
if df is not None and not df.empty:
data_dict[symbol] = df
logger.info(f" {symbol}: {len(df)} records")
if not data_dict:
logger.error("Data is empty, skipping this task")
continue
# 2. 播放数据
all_timestamps = set()
for df in data_dict.values():
all_timestamps.update(df.index)
timestamps = sorted(all_timestamps)
logger.info(f"Starting to play {len(timestamps)} timestamps")
for idx, timestamp in enumerate(timestamps, 1):
current_bars = {}
for symbol, df in data_dict.items():
if timestamp in df.index:
current_bars[symbol] = df.loc[timestamp]
# 如果配置了BacktestClientAdapter,发送K线数据到策略服务器
if self.backtest_client:
for symbol, bar in current_bars.items():
# 使用send_kline接口,传入period信息
response = self.backtest_client.send_kline(
symbol=symbol,
kline=bar,
kline_time=timestamp,
period=task.period,
)
# 处理返回信号
if response is not None:
logger.info(f"Received response: {response}")
# 每50个时间点输出一次进度
if idx % 50 == 0:
logger.info(f" Progress: {idx}/{len(timestamps)}")
logger.info(f"Task {task_idx} completed")
logger.info("=" * 60)
logger.info("All backtest tasks completed")

70
src/backtest/bt_task.py Normal file
View File

@ -0,0 +1,70 @@
"""
回测任务 (Backtest Task)
定义回测任务的数据结构
"""
from typing import List, Optional
from datetime import datetime
class BacktestTask:
"""
回测任务
包含回测的所有必要信息,每个任务对象代表一次回测
"""
def __init__(
self,
symbols: List[str],
start_date: datetime,
end_date: datetime,
period: str,
strategy_name: str,
strategy_params: Optional[dict] = None,
initial_capital: float = 100000.0,
commission_rate: float = 0.0003,
slippage_rate: float = 0.0001,
):
"""
初始化回测任务
Args:
symbols: 回测标的列表
start_date: 开始时间
end_date: 结束时间
period: K线周期(如'1d', '1h', '30m')
strategy_name: 策略名称
strategy_params: 策略参数字典
initial_capital: 初始资金
commission_rate: 手续费率
slippage_rate: 滑点率
"""
# 参数验证
if not symbols:
raise ValueError("symbols cannot be empty")
if start_date >= end_date:
raise ValueError("start_date must be before end_date")
if initial_capital <= 0:
raise ValueError("initial_capital must be positive")
# 赋值
self.symbols = symbols
self.start_date = start_date
self.end_date = end_date
self.period = period
self.strategy_name = strategy_name
self.strategy_params = strategy_params or {}
self.initial_capital = initial_capital
self.commission_rate = commission_rate
self.slippage_rate = slippage_rate
def __repr__(self) -> str:
"""字符串表示"""
return (
f"BacktestTask(strategy={self.strategy_name}, "
f"symbols={self.symbols}, "
f"period={self.period}, "
f"date={self.start_date.date()}~{self.end_date.date()})"
)

67
src/backtest/main.py Normal file
View File

@ -0,0 +1,67 @@
"""
回测系统主入口
演示BacktestEngine的使用
"""
from datetime import datetime
from src.data_service.data_service import DataService
from src.backtest.bt_engine import BacktestEngine
from src.backtest.bt_task import BacktestTask
from src.backtest.bt_client_adapter import BacktestClientAdapter
from src.core.logger import get_logger
from src.core.config import Config
logger = get_logger("BacktestMain")
def main():
"""Main function"""
logger.info("=== Backtest system starting ===")
# Load configuration
config = Config()
config.load_with_global("configs/backtest.yaml")
logger.info("Config loaded")
# Initialize data service
data_service = DataService.from_config(config)
logger.info("DataService initialized")
# Initialize strategy client (increase timeout)
backtest_client = BacktestClientAdapter(
"ws://localhost:8000/ws/strategy", timeout=30
)
logger.info("BacktestClientAdapter initialized")
# Initialize backtest engine (pass in BacktestClientAdapter)
engine = BacktestEngine(data_service, backtest_client)
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,
)
# Add task
engine.add_task(task)
# View task list
tasks = engine.get_tasks()
logger.info(f"Total tasks: {len(tasks)}")
# Run all backtest tasks
engine.run()
logger.info("=== Backtest system initialization completed ===")
if __name__ == "__main__":
main()

View File

@ -126,14 +126,14 @@ class BaseDataDownloader(ABC):
if period not in valid_periods:
raise ValueError(f"不支持的周期: {period},支持: {valid_periods}")
self.logger.debug("参数验证通过")
self.logger.debug("Parameter validation passed")
def _init_database(self):
"""初始化数据库连接"""
# 创建数据库(如果不存在)
db_manager = DatabaseManager()
if not db_manager.database_exists(self.database):
self.logger.warning(f"数据库 {self.database} 不存在,正在创建...")
self.logger.warning(f"Database {self.database} does not exist, creating...")
db_manager.create_database(self.database)
# 确保对应周期的 klines 表存在
@ -147,7 +147,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_name} 不存在,正在创建...")
self.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,7 +162,7 @@ class BaseDataDownloader(ABC):
self.engine = self._create_engine()
self.Session = sessionmaker(bind=self.engine)
self.logger.debug(f"数据库连接初始化完成: {self.database}")
self.logger.debug(f"Database connection initialized: {self.database}")
def _create_engine(self):
"""创建数据库引擎"""
@ -204,7 +204,7 @@ class BaseDataDownloader(ABC):
DataFrame包含列: timestamp, open, high, low, close, volume, amount
"""
self.logger.info("=" * 50)
self.logger.info("开始下载数据(仅下载,不保存)")
self.logger.info("Starting data download (download only, not saving)")
self.logger.info("=" * 50)
result = {}
@ -212,7 +212,7 @@ class BaseDataDownloader(ABC):
for symbol in self.symbols:
for period in self.periods:
try:
self.logger.info(f"下载 {symbol} [{period}] 数据...")
self.logger.info(f"Downloading {symbol} [{period}] data...")
# 调用子类实现的下载方法
klines = self._download_klines(
@ -228,15 +228,17 @@ class BaseDataDownloader(ABC):
key = f"{symbol}_{period}"
result[key] = df
self.logger.info(f"✓ {symbol} [{period}]: 下载 {len(df)} 条")
self.logger.info(
f"✓ {symbol} [{period}]: downloaded {len(df)} records"
)
else:
self.logger.warning(f"✗ {symbol} [{period}]: 无数据")
self.logger.warning(f"✗ {symbol} [{period}]: no data")
except Exception as e:
self.logger.error(f"✗ {symbol} [{period}]: 下载失败 - {e}")
self.logger.error(f"✗ {symbol} [{period}]: download failed - {e}")
self.logger.info("=" * 50)
self.logger.info(f"下载完成,共获取 {len(result)} 个数据集")
self.logger.info(f"Download completed, retrieved {len(result)} datasets")
self.logger.info("=" * 50)
return result
@ -276,7 +278,7 @@ class BaseDataDownloader(ABC):
统计信息字典
"""
self.logger.info("=" * 50)
self.logger.info("开始下载数据")
self.logger.info("Starting data download")
self.logger.info("=" * 50)
stats = {
@ -291,7 +293,7 @@ class BaseDataDownloader(ABC):
for symbol in self.symbols:
for period in self.periods:
try:
self.logger.info(f"下载 {symbol} [{period}] 数据...")
self.logger.info(f"Downloading {symbol} [{period}] data...")
# 调用子类实现的下载方法
klines = self._download_klines(
@ -322,7 +324,7 @@ class BaseDataDownloader(ABC):
}
)
else:
self.logger.warning(f"✗ {symbol} [{period}]: 无数据")
self.logger.warning(f"✗ {symbol} [{period}]: no data")
stats["failed_count"] += 1
stats["details"].append(
{
@ -335,7 +337,7 @@ class BaseDataDownloader(ABC):
)
except Exception as e:
self.logger.error(f"✗ {symbol} [{period}]: 下载失败 - {e}")
self.logger.error(f"✗ {symbol} [{period}]: download failed - {e}")
stats["failed_count"] += 1
stats["details"].append(
{
@ -347,14 +349,14 @@ class BaseDataDownloader(ABC):
)
self.logger.info("=" * 50)
self.logger.info("下载完成")
self.logger.info("Download completed")
self.logger.info(
f"总计: {stats['total_symbols']} 个标的 x {stats['total_periods']} 个周期"
f"Total: {stats['total_symbols']} symbols x {stats['total_periods']} periods"
)
self.logger.info(
f"成功: {stats['success_count']}, 失败: {stats['failed_count']}"
f"Success: {stats['success_count']}, Failed: {stats['failed_count']}"
)
self.logger.info(f"保存记录数: {stats['total_records']}")
self.logger.info(f"Saved records: {stats['total_records']}")
self.logger.info("=" * 50)
return stats
@ -411,11 +413,11 @@ class BaseDataDownloader(ABC):
saved_count += 1
session.commit()
self.logger.debug(f"保存 {saved_count} 条记录到数据库")
self.logger.debug(f"Saved {saved_count} records to database")
except Exception as e:
session.rollback()
self.logger.error(f"保存数据失败: {e}")
self.logger.error(f"Failed to save data: {e}")
raise
finally:
session.close()
@ -426,4 +428,4 @@ class BaseDataDownloader(ABC):
"""关闭数据库连接"""
if hasattr(self, "engine"):
self.engine.dispose()
self.logger.info("数据库连接已关闭")
self.logger.info("Database connection closed")

View File

@ -71,10 +71,10 @@ class XtQuantDownloader(BaseDataDownloader):
def __del__(self):
"""析构函数:关闭 XtQuant 连接"""
try:
xtdc.close()
self.logger.debug("XtQuant 连接已关闭")
xtdc.close() # type: ignore
self.logger.debug("XtQuant connection closed")
except Exception as e:
self.logger.debug(f"关闭 XtQuant 连接时出错: {e}")
self.logger.debug(f"Error closing XtQuant connection: {e}")
def _init_xtquant(
self, token: Optional[str], optimize_addresses: Optional[List[str]]
@ -88,7 +88,7 @@ class XtQuantDownloader(BaseDataDownloader):
"XtQuant token 未设置,请在配置文件 data_source.xtquant.xtquant_token 中设置或通过参数传入"
)
self.logger.info(f"初始化 XtQuant 数据中心,Token: {token[:20]}...")
self.logger.info(f"Initializing XtQuant data center, Token: {token[:20]}...")
# 设置 token
xtdc.set_token(token)
@ -96,9 +96,9 @@ class XtQuantDownloader(BaseDataDownloader):
# 初始化数据中心
try:
xtdc.init()
self.logger.info("XtQuant 数据中心初始化成功")
self.logger.info("XtQuant data center initialized successfully")
except Exception as e:
self.logger.error(f"XtQuant 数据中心初始化失败: {e}")
self.logger.error(f"XtQuant data center initialization failed: {e}")
raise
# 设置优化地址
@ -110,19 +110,21 @@ class XtQuantDownloader(BaseDataDownloader):
if optimize_addresses:
try:
xtdc.set_allow_optmize_address(optimize_addresses)
self.logger.info(f"优化地址已设置: {len(optimize_addresses)} 个")
self.logger.info(
f"Optimize addresses set: {len(optimize_addresses)} addresses"
)
except Exception as e:
self.logger.warning(f"优化地址设置失败: {e}")
self.logger.warning(f"Failed to set optimize addresses: {e}")
# 下载基础数据
try:
self.logger.info("下载板块数据...")
self.logger.info("Downloading sector data...")
xtdata.download_sector_data()
self.logger.info("下载历史合约数据...")
self.logger.info("Downloading historical contracts data...")
xtdata.download_history_contracts()
self.logger.info("基础数据下载完成")
self.logger.info("Base data download completed")
except Exception as e:
self.logger.warning(f"基础数据下载失败: {e}")
self.logger.warning(f"Base data download failed: {e}")
def _download_klines(
self, symbol: str, start_date: datetime, end_date: datetime, period: str
@ -140,7 +142,7 @@ class XtQuantDownloader(BaseDataDownloader):
K线对象列表
"""
# 转换周期格式
xt_period = self.PERIOD_MAPPING.get(period, period)
xt_period = self.PERIOD_MAPPING[period]
# 转换日期格式为 YYYYMMDD
start_str = start_date.strftime("%Y%m%d")
@ -148,10 +150,12 @@ class XtQuantDownloader(BaseDataDownloader):
# 先下载历史数据(确保本地有缓存)
try:
self.logger.debug(f"下载 {symbol} [{period}] 历史数据到本地...")
self.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"下载历史数据到本地失败: {e}")
self.logger.warning(f"Failed to download historical data to local: {e}")
# 从本地获取数据
try:
@ -167,11 +171,11 @@ class XtQuantDownloader(BaseDataDownloader):
)
if symbol not in data or len(data[symbol]) == 0:
self.logger.warning(f"{symbol} [{period}] 没有数据")
self.logger.warning(f"{symbol} [{period}] has no data")
return []
df = data[symbol]
self.logger.debug(f"获取到 {len(df)} 条 {symbol} [{period}] 数据")
self.logger.debug(f"Retrieved {len(df)} records for {symbol} [{period}]")
# 转换为 Kline 对象
klines = []
@ -210,9 +214,11 @@ class XtQuantDownloader(BaseDataDownloader):
# 打印第一条数据的时间戳信息用于调试
if not first_logged:
self.logger.debug(
f"第一条时间戳 - 原始: {timestamp}, 类型: {type(timestamp)}"
f"First timestamp - raw: {timestamp}, type: {type(timestamp)}"
)
self.logger.debug(
f"First timestamp - converted: {dt}, type: {type(dt)}"
)
self.logger.debug(f"第一条时间戳 - 转换后: {dt}, 类型: {type(dt)}")
first_logged = True
kline = Kline(
@ -234,5 +240,5 @@ class XtQuantDownloader(BaseDataDownloader):
return klines
except Exception as e:
self.logger.error(f"获取 {symbol} [{period}] 数据失败: {e}")
self.logger.error(f"Failed to retrieve {symbol} [{period}] data: {e}")
raise

View File

@ -79,7 +79,9 @@ class DatabaseManager:
# 缓存各个数据库的engine,避免重复创建
self._db_engines: Dict[str, Engine] = {}
logger.info(f"数据库管理器初始化完成: {self.user}@{self.host}:{self.port}")
logger.info(
f"Database manager initialized: {self.user}@{self.host}:{self.port}"
)
def _create_admin_engine(self) -> Engine:
"""创建管理员引擎(不指定数据库,带连接池)"""
@ -133,10 +135,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(f"检查数据库 {database}: {'存在' if exists else '不存在'}")
logger.debug(
f"Check database {database}: {'exists' if exists else 'not exists'}"
)
return exists
except SQLAlchemyError as e:
logger.error(f"检查数据库失败: {e}")
logger.error(f"Failed to check database: {e}")
return False
def create_database(self, database: str, if_not_exists: bool = True) -> bool:
@ -152,7 +156,7 @@ class DatabaseManager:
"""
try:
if if_not_exists and self.database_exists(database):
logger.info(f"数据库 {database} 已存在,跳过创建")
logger.info(f"Database {database} already exists, skip creation")
return True
with self._admin_engine.connect() as conn:
@ -163,10 +167,10 @@ class DatabaseManager:
)
)
conn.commit()
logger.info(f"✓ 创建数据库: {database}")
logger.info(f"✓ Created database: {database}")
return True
except SQLAlchemyError as e:
logger.error(f"创建数据库失败: {e}")
logger.error(f"Failed to create database: {e}")
return False
def drop_database(self, database: str, confirm: bool = False) -> bool:
@ -181,21 +185,21 @@ class DatabaseManager:
是否成功
"""
if not confirm:
logger.warning("删除数据库需要确认: confirm=True")
logger.warning("Database deletion requires confirmation: confirm=True")
return False
try:
if not self.database_exists(database):
logger.warning(f"数据库 {database} 不存在")
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"✓ 删除数据库: {database}")
logger.info(f"✓ Dropped database: {database}")
return True
except SQLAlchemyError as e:
logger.error(f"删除数据库失败: {e}")
logger.error(f"Failed to drop database: {e}")
return False
def list_databases(self) -> List[str]:
@ -218,7 +222,7 @@ class DatabaseManager:
]
return databases
except SQLAlchemyError as e:
logger.error(f"列出数据库失败: {e}")
logger.error(f"Failed to list databases: {e}")
return []
def table_exists(self, database: str, table: str) -> bool:
@ -236,10 +240,12 @@ class DatabaseManager:
engine = self._create_db_engine(database)
inspector = inspect(engine)
exists = table in inspector.get_table_names()
logger.debug(f"检查表 {database}.{table}: {'存在' if exists else '不存在'}")
logger.debug(
f"Check table {database}.{table}: {'exists' if exists else 'not exists'}"
)
return exists
except SQLAlchemyError as e:
logger.error(f"检查表失败: {e}")
logger.error(f"Failed to check table: {e}")
return False
def list_tables(self, database: str) -> List[str]:
@ -257,7 +263,7 @@ class DatabaseManager:
inspector = inspect(engine)
return inspector.get_table_names()
except SQLAlchemyError as e:
logger.error(f"列出表失败: {e}")
logger.error(f"Failed to list tables: {e}")
return []
def create_table(
@ -297,7 +303,9 @@ class DatabaseManager:
"""
try:
if if_not_exists and self.table_exists(database, table_name):
logger.info(f"表 {database}.{table_name} 已存在,跳过创建")
logger.info(
f"Table {database}.{table_name} already exists, skip creation"
)
return True
engine = self._create_db_engine(database)
@ -360,11 +368,11 @@ class DatabaseManager:
# 创建表
metadata.create_all(engine)
logger.info(f"✓ 创建表: {database}.{table_name}")
logger.info(f"✓ Created table: {database}.{table_name}")
return True
except SQLAlchemyError as e:
logger.error(f"创建表失败: {e}")
logger.error(f"Failed to create table: {e}")
return False
def drop_table(self, database: str, table: str, confirm: bool = False) -> bool:
@ -380,22 +388,22 @@ class DatabaseManager:
是否成功
"""
if not confirm:
logger.warning("删除表需要确认: confirm=True")
logger.warning("Table deletion requires confirmation: confirm=True")
return False
try:
if not self.table_exists(database, table):
logger.warning(f"表 {database}.{table} 不存在")
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"✓ 删除表: {database}.{table}")
logger.info(f"✓ Dropped table: {database}.{table}")
return True
except SQLAlchemyError as e:
logger.error(f"删除表失败: {e}")
logger.error(f"Failed to drop table: {e}")
return False
def get_table_schema(self, database: str, table: str) -> Dict[str, Any]:
@ -419,7 +427,7 @@ class DatabaseManager:
return {"columns": columns, "indexes": indexes, "primary_key": pk}
except SQLAlchemyError as e:
logger.error(f"获取表结构失败: {e}")
logger.error(f"Failed to get table schema: {e}")
return {}
def close(self):
@ -437,6 +445,6 @@ class DatabaseManager:
logger.debug(f"Engine disposed for database: {db_name}")
self._db_engines.clear()
logger.info("数据库管理器连接已关闭")
logger.info("Database manager connections closed")
except Exception as e:
logger.warning(f"关闭数据库连接时出错: {e}")
logger.warning(f"Error closing database connections: {e}")

View File

@ -5,11 +5,7 @@
"""
from typing import Dict, Any, List
from .table_utils import (
get_all_kline_table_names,
get_all_indicator_table_names,
SUPPORTED_PERIODS,
)
from .table_utils import SUPPORTED_PERIODS, SUPPORTED_INDICATORS
# ==================== Tick 表 ====================
TICK_TABLE = {
@ -681,9 +677,6 @@ ALL_KLINE_TABLES = {
for period in SUPPORTED_PERIODS
}
# 动态生成所有指标表(所有周期×所有指标)
from .table_utils import SUPPORTED_INDICATORS
ALL_INDICATOR_TABLES = {
f"indicators_{period}_{indicator}": create_indicator_table_definition(
indicator, period

View File

@ -51,11 +51,15 @@ class IndicatorManager:
try:
indicator_class = self.INDICATOR_MAP[indicator_name]
self.indicators[indicator_name] = indicator_class(config)
self.logger.info(f"初始化指标: {indicator_name}, 配置: {config}")
self.logger.info(
f"Initialized indicator: {indicator_name}, config: {config}"
)
except Exception as e:
self.logger.error(f"初始化指标 {indicator_name} 失败: {e}")
self.logger.error(
f"Failed to initialize indicator {indicator_name}: {e}"
)
else:
self.logger.warning(f"未知的指标类型: {indicator_name}")
self.logger.warning(f"Unknown indicator type: {indicator_name}")
def add_indicator(self, indicator_name: str, config: Dict | None = None):
"""添加指标计算器
@ -75,7 +79,7 @@ class IndicatorManager:
indicator_class = self.INDICATOR_MAP[indicator_name]
self.indicators[indicator_name] = indicator_class(config)
self.logger.info(f"添加指标: {indicator_name}, 配置: {config}")
self.logger.info(f"Added indicator: {indicator_name}, config: {config}")
def remove_indicator(self, indicator_name: str):
"""移除指标计算器
@ -85,7 +89,7 @@ class IndicatorManager:
"""
if indicator_name in self.indicators:
del self.indicators[indicator_name]
self.logger.info(f"移除指标: {indicator_name}")
self.logger.info(f"Removed indicator: {indicator_name}")
def calculate_all(
self, kline_data: Dict[str, pd.DataFrame]
@ -103,9 +107,11 @@ class IndicatorManager:
for stock_code, df in kline_data.items():
try:
result[stock_code] = self.calculate(df)
self.logger.debug(f"成功计算 {stock_code} 的所有指标")
self.logger.debug(
f"Successfully calculated all indicators for {stock_code}"
)
except Exception as e:
self.logger.error(f"计算 {stock_code} 的指标时出错: {e}")
self.logger.error(f"Error calculating indicators for {stock_code}: {e}")
# 计算失败时返回原始数据
result[stock_code] = df
@ -131,15 +137,19 @@ class IndicatorManager:
# 依次计算每个指标
for indicator_name in indicators_to_calc:
if indicator_name not in self.indicators:
self.logger.warning(f"指标 {indicator_name} 未配置,跳过")
self.logger.warning(
f"Indicator {indicator_name} not configured, skipping"
)
continue
try:
indicator = self.indicators[indicator_name]
result = indicator.calculate(result)
self.logger.debug(f"成功计算指标: {indicator_name}")
self.logger.debug(
f"Successfully calculated indicator: {indicator_name}"
)
except Exception as e:
self.logger.error(f"计算指标 {indicator_name} 时出错: {e}")
self.logger.error(f"Error calculating indicator {indicator_name}: {e}")
# 继续计算其他指标
continue

9
src/networks/__init__.py Normal file
View File

@ -0,0 +1,9 @@
"""
Networks模块
提供客户端和服务端通信能力
"""
from src.networks.client.ws_client import WSClient
__all__ = ["WSClient"]

View File

@ -0,0 +1,7 @@
"""
客户端模块
"""
from src.networks.client.ws_client import WSClient
__all__ = ["WSClient"]

View File

@ -0,0 +1,144 @@
"""
WebSocket客户端 (WebSocket Client)
纯粹的WebSocket通信层,只负责:
- 建立和管理WebSocket连接
- 发送和接收消息
- 不包含任何业务逻辑
"""
from typing import Optional, Dict, Any
import asyncio
import websockets
import json
from src.core.logger import get_logger
logger = get_logger("WSClient")
class WSClient:
"""
WebSocket客户端
纯粹的通信层,只负责:
- 连接管理
- 消息收发
- 不解析业务数据
"""
def __init__(self, server_url: str, timeout: int = 30):
"""
初始化WebSocket客户端
Args:
server_url: WebSocket服务器地址(完整URL,如 ws://localhost:8000/ws/strategy)
timeout: 超时时间(秒)
"""
self.server_url = server_url
self.timeout = timeout
self.websocket = None
self.loop = None
self.connected = False
self.connection_attempted = False
logger.info(f"WSClient initialized: {self.server_url}")
async def connect(self):
"""建立WebSocket连接"""
try:
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")
except Exception as e:
self.connected = False
logger.error(f"Failed to connect WebSocket: {e}")
raise
async def disconnect(self):
"""关闭WebSocket连接"""
if self.websocket:
await self.websocket.close()
self.connected = False
logger.info("WebSocket disconnected")
async def send_async(self, message: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
异步发送消息并接收响应
Args:
message: 要发送的消息(字典格式)
Returns:
服务器响应(字典格式)或None
"""
if not self.websocket:
logger.error("WebSocket not connected")
return None
try:
# 发送消息
await self.websocket.send(json.dumps(message))
# 接收响应
response = await asyncio.wait_for(
self.websocket.recv(), timeout=self.timeout
)
# 解析JSON
return json.loads(response)
except asyncio.TimeoutError:
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}")
return None
def send(self, message: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
发送消息并接收响应(同步接口)
Args:
message: 要发送的消息(字典格式)
Returns:
服务器响应(字典格式)或None
"""
# 如果已经尝试连接过但失败了,不再重试
if self.connection_attempted and not self.connected:
return None
# 如果没有事件循环,创建一个
if not self.loop:
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
# 如果未连接,先建立连接(只尝试一次)
if not self.websocket:
self.connection_attempted = True
try:
self.loop.run_until_complete(self.connect())
except Exception as e:
logger.error(f"Connection failed, will not retry: {e}")
self.connected = False
return None
# 执行异步发送
return self.loop.run_until_complete(self.send_async(message))
def close(self):
"""关闭客户端连接"""
try:
if self.websocket and self.loop:
self.loop.run_until_complete(self.disconnect())
if self.loop:
self.loop.close()
self.loop = None
except Exception as e:
logger.error(f"Error closing connection: {e}")

View File

@ -0,0 +1,7 @@
"""
服务端模块
"""
from src.networks.server.ws_server import WebSocketServer
__all__ = ["WebSocketServer"]

View File

@ -0,0 +1,157 @@
"""
WebSocket通信服务器 - 纯通信层
提供基础的WebSocket通信功能,业务逻辑由调用方实现
协议版本: v1.0
"""
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from typing import Optional, Callable, Awaitable
import uvicorn
import json
from datetime import datetime
from src.core.logger import get_logger
logger = get_logger("WSServer")
# 消息处理器类型定义
# Handler 返回业务数据字典或 None,由 WebSocketServer 包装成完整响应
MessageHandler = Callable[[dict], Awaitable[dict]]
class WebSocketServer:
"""WebSocket服务器基类 - 纯通信层"""
def __init__(self, title: str = "WebSocket Server", version: str = "1.0.0"):
"""
初始化WebSocket服务器
Args:
title: 服务器标题
version: 版本号
"""
self.app = FastAPI(title=title, version=version)
self.message_handlers: dict[str, MessageHandler] = {}
# 注册WebSocket端点
@self.app.websocket("/ws/strategy")
async def websocket_endpoint(websocket: WebSocket):
await self._handle_websocket(websocket)
def register_handler(self, msg_type: str, handler: MessageHandler):
"""
注册消息处理器
Args:
msg_type: 消息类型
handler: 处理函数 async def handler(message: dict) -> dict
返回业务数据,由服务器自动包装成完整响应
"""
self.message_handlers[msg_type] = handler
logger.info(f"Registered handler for message type: {msg_type}")
async def _handle_websocket(self, websocket: WebSocket):
"""
处理WebSocket连接
Args:
websocket: WebSocket连接
"""
await websocket.accept()
logger.info(f"Client connected: {websocket.client}")
try:
while True:
# 接收消息
data = await websocket.receive_text()
message = json.loads(data)
msg_type = message.get("msg_type")
header = message.get("header", {})
req_msg_id = header.get("msg_id")
logger.debug(f"Received message type: {msg_type}")
# 查找并调用处理器
handler = self.message_handlers.get(msg_type)
if handler:
try:
# 调用业务处理器
business_data = await handler(message)
# 包装成完整响应
response = self._wrap_response(business_data, req_msg_id)
except Exception as e:
logger.error(f"Handler error: {e}", exc_info=True)
response = self._create_error_response(
str(e), "PROCESSING_ERROR", req_msg_id
)
else:
response = self._create_error_response(
f"Unknown message type: {msg_type}",
"UNKNOWN_MSG_TYPE",
req_msg_id,
)
# 返回响应
await websocket.send_text(json.dumps(response))
except WebSocketDisconnect:
logger.info(f"Client disconnected: {websocket.client}")
except Exception as e:
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))
except Exception:
pass
def _create_response_header(self, req_msg_id: Optional[str] = None) -> dict:
"""创建响应头"""
import uuid
return {
"version": "1.0",
"msg_id": str(uuid.uuid4()),
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3],
"req_msg_id": req_msg_id,
}
def _wrap_response(
self, business_data: dict, req_msg_id: Optional[str] = None
) -> dict:
"""
包装业务数据为完整响应
Args:
business_data: 业务处理器返回的数据
req_msg_id: 请求消息ID
Returns:
完整的响应消息
"""
response = {"header": self._create_response_header(req_msg_id)}
response.update(business_data)
return response
def _create_error_response(
self, error_message: str, error_code: str, req_msg_id: Optional[str] = None
) -> dict:
"""创建错误响应"""
return {
"header": self._create_response_header(req_msg_id),
"msg_type": "ERROR",
"error_code": error_code,
"error_message": error_message,
}
def start(self, host: str = "0.0.0.0", port: int = 8000):
"""
启动服务器
Args:
host: 监听地址
port: 监听端口
"""
logger.info(f"Starting WebSocket server on {host}:{port}")
uvicorn.run(self.app, host=host, port=port, log_level="info")

174
src/qtrade_server.py Normal file
View File

@ -0,0 +1,174 @@
"""
QTrade Strategy Server - 使用WebSocketServer通信层
接收客户端发送的K线数据,通过StrategyManager分发到多个策略实例
"""
from typing import Optional
from src.core.logger import get_logger
from src.strategy_manager import StrategyManager
from src.networks.server.ws_server import WebSocketServer
logger = get_logger("QTradeServer")
# 策略管理器
strategy_manager: Optional[StrategyManager] = None
def initialize_strategy_manager(config_dir: str = "config/strategies"):
"""
初始化策略管理器
Args:
config_dir: 策略配置文件目录
"""
global strategy_manager
logger.info("Initializing StrategyManager...")
# 创建策略管理器
strategy_manager = StrategyManager(config_dir)
# 初始化(加载配置并创建实例)
if not strategy_manager.initialize():
logger.error("Failed to initialize StrategyManager")
return False
logger.info("StrategyManager initialized successfully")
return True
async def handle_kline_data(message: dict) -> dict:
"""
处理单条K线数据
Args:
message: 请求消息
Returns:
业务响应数据(由 WebSocketServer 包装成完整响应)
Raises:
Exception: 处理失败时抛出异常
"""
if not strategy_manager:
raise RuntimeError("Strategy manager not initialized")
symbol = message.get("symbol")
kline_time = message.get("kline_time")
data = message.get("data", {})
if not symbol:
raise ValueError("Symbol is required")
logger.info(f"Processing K-line: {symbol} {kline_time}")
# 构建完整的K线数据
kline_data = {
"symbol": symbol,
"timestamp": kline_time,
"open": data.get("open"),
"high": data.get("high"),
"low": data.get("low"),
"close": data.get("close"),
"volume": data.get("volume"),
}
# 分发到策略管理器
signals = strategy_manager.dispatch_kline(symbol, kline_data)
# 返回业务数据
return {
"msg_type": "TRADE_SIGNALS",
"signals": signals,
}
async def handle_kline_batch(message: dict) -> dict:
"""
处理批量K线数据
Args:
message: 请求消息
Returns:
业务响应数据(由 WebSocketServer 包装成完整响应)
Raises:
Exception: 处理失败时抛出异常
"""
if not strategy_manager:
raise RuntimeError("Strategy manager not initialized")
batch_data = message.get("batch_data", [])
all_signals = []
logger.info(f"Processing batch: {len(batch_data)} symbols")
# 处理每个标的的K线
for item in batch_data:
symbol = item.get("symbol")
kline_time = item.get("kline_time")
data = item.get("data", {})
# 构建完整的K线数据
kline_data = {
"symbol": symbol,
"timestamp": kline_time,
"open": data.get("open"),
"high": data.get("high"),
"low": data.get("low"),
"close": data.get("close"),
"volume": data.get("volume"),
}
# 分发到策略管理器
signals = strategy_manager.dispatch_kline(symbol, kline_data)
all_signals.extend(signals)
# 返回业务数据
return {
"msg_type": "TRADE_SIGNALS",
"signals": all_signals,
}
def start_server(
host: str = "0.0.0.0", port: int = 8000, config_dir: str = "config/strategies"
):
"""
启动服务器
Args:
host: 监听地址
port: 监听端口
config_dir: 策略配置文件目录
"""
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)
# 初始化策略管理器
if not initialize_strategy_manager(config_dir):
logger.error("Failed to initialize, server will not start")
return
# 创建WebSocket服务器
ws_server = WebSocketServer(title="QTrade Strategy Server", version="1.0.0")
# 注册消息处理器
ws_server.register_handler("KLINE_DATA", handle_kline_data)
ws_server.register_handler("KLINE_DATA_BATCH", handle_kline_batch)
# 启动服务器
ws_server.start(host=host, port=port)
if __name__ == "__main__":
start_server()

View File

@ -0,0 +1,11 @@
"""
策略包
存放所有自定义策略实现
"""
from .debug_strategy import DebugStrategy
__all__ = [
"DebugStrategy",
]

View File

@ -0,0 +1,140 @@
"""
调试策略 (Debug Strategy)
一个简单的调试策略,用于测试策略框架。
该策略不执行实际交易,只打印K线数据和一些调试信息。
功能:
- 接收K线数据并打印关键信息
- 根据简单条件生成模拟信号(不实际交易)
- 方便调试策略服务框架
"""
from typing import Dict, Any, Optional
class DebugStrategy:
"""
调试策略
只打印信息,不执行实际交易逻辑
"""
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)
# 状态
self.kline_count = 0
self.last_price = None
print(f"[DebugStrategy] Initialized with params: {params}")
def on_bar(self, bar_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
处理K线数据
Args:
bar_data: K线数据字典
Returns:
信号字典(如果生成信号)或None
"""
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)
# 按设定频率打印K线信息
if self.kline_count % self.print_every == 0:
print(f"\n[DebugStrategy] K-line #{self.kline_count}")
print(f" Symbol: {symbol}")
print(f" Time: {timestamp}")
print(
f" OHLC: O={open_price:.2f}, H={high:.2f}, L={low:.2f}, C={close:.2f}"
)
print(f" Volume: {volume}")
# 计算价格变化
if self.last_price is not None:
price_change = ((close - self.last_price) / self.last_price) * 100
print(f" Price Change: {price_change:+.2f}%")
# 模拟信号生成(如果启用)
signal = None
if self.simulate_signal and self.last_price is not None:
price_change_pct = ((close - self.last_price) / self.last_price) * 100
if price_change_pct > self.signal_threshold:
signal = {
"action": "BUY",
"symbol": symbol,
"price": close,
"quantity": 100,
"reason": f"Price increased by {price_change_pct:.2f}%",
}
print(f"\n[DebugStrategy] 🟢 BUY Signal Generated!")
print(f" Reason: {signal['reason']}")
elif price_change_pct < -self.signal_threshold:
signal = {
"action": "SELL",
"symbol": symbol,
"price": close,
"quantity": 100,
"reason": f"Price decreased by {price_change_pct:.2f}%",
}
print(f"\n[DebugStrategy] 🔴 SELL Signal Generated!")
print(f" Reason: {signal['reason']}")
# 更新状态
self.last_price = close
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]:
"""
获取策略状态
Returns:
状态字典
"""
return {
"kline_count": self.kline_count,
"last_price": self.last_price,
"print_every": self.print_every,
"simulate_signal": self.simulate_signal,
}
def reset(self):
"""重置策略状态"""
self.kline_count = 0
self.last_price = None
print("[DebugStrategy] Strategy reset")

315
src/strategy_manager.py Normal file
View File

@ -0,0 +1,315 @@
"""
策略管理器 (Strategy Manager)
负责:
1. 加载多个策略配置文件 (config/strategies/*.yaml)
2. 实例化策略对象
3. 维护 symbol -> [策略实例] 的映射
4. 分发K线数据到对应策略
5. 聚合所有策略返回的信号
"""
from typing import Dict, List, Tuple, Any, Optional
from pathlib import Path
import yaml
import importlib
from src.core.logger import get_logger
logger = get_logger("StrategyManager")
class StrategyManager:
"""
策略管理器
管理多个策略实例,支持:
- 一个symbol配置多个策略实例
- 策略配置文件独立管理
- 动态加载策略类
"""
def __init__(self, config_dir: str = "config/strategies"):
"""
初始化策略管理器
Args:
config_dir: 策略配置文件目录
"""
self.config_dir = Path(config_dir)
# 策略实例字典: {instance_id: strategy_object}
self.instances: Dict[str, Any] = {}
# Symbol索引: {symbol: [(instance_id, strategy_object), ...]}
self.symbol_index: Dict[str, List[Tuple[str, Any]]] = {}
# 配置缓存: {instance_id: config_dict}
self.configs: Dict[str, Dict] = {}
logger.info(f"StrategyManager initialized with config_dir: {config_dir}")
def load_configs(self) -> bool:
"""
加载所有策略配置文件
Returns:
是否加载成功
"""
try:
if not self.config_dir.exists():
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}")
return False
logger.info(f"Found {len(config_files)} config files")
# 加载每个配置文件
for config_file in config_files:
try:
with open(config_file, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
instance_id = config.get("instance_id")
if not instance_id:
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}")
except Exception as e:
logger.error(f"Failed to load {config_file}: {e}")
continue
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)
return False
def initialize(self) -> bool:
"""
初始化所有策略实例
Returns:
是否初始化成功
"""
try:
logger.info("Initializing strategy instances...")
# 先加载配置
if not self.load_configs():
logger.error("Failed to load configs")
return False
# 创建每个策略实例
for instance_id, config in self.configs.items():
try:
# 提取配置信息
symbol = config.get("symbol")
strategy_class_name = config.get("strategy_class")
params = config.get("params", {})
if not symbol or not strategy_class_name:
logger.error(f"Invalid config for {instance_id}")
continue
# 动态加载策略类
strategy_class = self._load_strategy_class(strategy_class_name)
if not strategy_class:
logger.error(
f"Failed to load strategy class: {strategy_class_name}"
)
continue
# 创建策略实例
strategy_obj = strategy_class(**params)
# 存储实例
self.instances[instance_id] = strategy_obj
# 建立symbol索引
if symbol not in self.symbol_index:
self.symbol_index[symbol] = []
self.symbol_index[symbol].append((instance_id, strategy_obj))
logger.info(
f"✓ Created instance: {instance_id} ({strategy_class_name}) for {symbol}"
)
except Exception as e:
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)}")
for symbol, instances_list in self.symbol_index.items():
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)
return False
def _load_strategy_class(self, class_name: str):
"""
动态加载策略类
Args:
class_name: 策略类名 (如 "DebugStrategy")
Returns:
策略类或None
"""
try:
# 将类名转换为模块名 (DebugStrategy -> debug_strategy)
module_name = self._class_to_module_name(class_name)
# 导入模块 (src.strategies.debug_strategy)
module_path = f"src.strategies.{module_name}"
module = importlib.import_module(module_path)
# 获取类
strategy_class = getattr(module, class_name)
return strategy_class
except Exception as e:
logger.error(f"Failed to load strategy class {class_name}: {e}")
return None
def _class_to_module_name(self, class_name: str) -> str:
"""
将类名转换为模块名
DebugStrategy -> debug_strategy
MAStrategy -> ma_strategy
"""
import re
# 驼峰转下划线
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", class_name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
def dispatch_kline(self, symbol: str, kline_data: Dict) -> List[Dict]:
"""
分发K线数据到该symbol的所有策略实例
Args:
symbol: 股票代码
kline_data: K线数据字典
Returns:
信号列表: [
{instance_id: "xxx", action: "BUY", ...},
{instance_id: "yyy", action: "SELL", ...}
]
"""
# 查找该symbol的所有策略实例
instances_list = self.symbol_index.get(symbol, [])
if not instances_list:
logger.debug(f"No strategy instances for {symbol}")
return []
logger.debug(
f"Dispatching K-line to {len(instances_list)} instances for {symbol}"
)
# 收集所有信号
all_signals = []
for instance_id, strategy_obj in instances_list:
try:
# 调用策略compute方法
result = strategy_obj.compute(kline_data)
if not result:
continue
action = result.get("action", "HOLD")
if action == "HOLD":
continue
# 构建信号(添加instance_id)
signal = {
"instance_id": instance_id,
"symbol": result.get("symbol", symbol),
"action": action,
"price": result.get("price", 0.0),
"quantity": result.get("quantity", 0),
"message": result.get("reason", result.get("message", "")),
}
all_signals.append(signal)
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)
continue
return all_signals
def get_instance(self, instance_id: str) -> Optional[Any]:
"""
获取指定策略实例
Args:
instance_id: 实例ID
Returns:
策略对象或None
"""
return self.instances.get(instance_id)
def get_instances_by_symbol(self, symbol: str) -> List[Tuple[str, Any]]:
"""
获取symbol对应的所有策略实例
Args:
symbol: 股票代码
Returns:
[(instance_id, strategy_obj), ...]
"""
return self.symbol_index.get(symbol, [])
def get_all_instances(self) -> Dict[str, Any]:
"""
获取所有策略实例
Returns:
{instance_id: strategy_object}
"""
return self.instances.copy()
def get_status(self) -> Dict[str, Any]:
"""
获取管理器状态
Returns:
状态字典
"""
return {
"total_instances": len(self.instances),
"symbols": list(self.symbol_index.keys()),
"instances_by_symbol": {
symbol: [inst_id for inst_id, _ in instances]
for symbol, instances in self.symbol_index.items()
},
}

View File

@ -0,0 +1,21 @@
"""
策略服务模块
提供策略管理、执行、风控、持仓管理等功能
"""
from src.strategy_service.config_loader import ConfigLoader
from src.strategy_service.strategy_manager import StrategyManager
from src.strategy_service.strategy_executor import StrategyExecutor
from src.strategy_service.position_manager import PositionManager
from src.strategy_service.risk_manager import RiskManager
from src.strategy_service.trade_recorder import TradeRecorder
__all__ = [
"ConfigLoader",
"StrategyManager",
"StrategyExecutor",
"PositionManager",
"RiskManager",
"TradeRecorder",
]

View File

@ -0,0 +1,204 @@
"""
配置加载器 (Config Loader)
负责加载和管理策略配置文件
"""
from typing import Dict, List, Optional, Any
import yaml
from pathlib import Path
from src.core.logger import get_logger
logger = get_logger("ConfigLoader")
class ConfigLoader:
"""
配置加载器
负责:
- 加载strategy_config.yaml配置文件
- 验证配置合法性
- 提供配置查询接口
- 支持热更新
"""
def __init__(self, config_path: str):
"""
初始化配置加载器
Args:
config_path: 配置文件路径
"""
self.config_path = Path(config_path)
self.config: Dict[str, Any] = {}
self._instances_by_id: Dict[str, Dict] = {}
self._instances_by_symbol: Dict[str, List[str]] = {}
def load(self) -> bool:
"""
加载配置文件
Returns:
是否加载成功
"""
try:
if not self.config_path.exists():
logger.error(f"Config file not found: {self.config_path}")
return False
with open(self.config_path, "r", encoding="utf-8") as f:
self.config = yaml.safe_load(f)
# 验证配置
if not self._validate_config():
return False
# 构建索引
self._build_indexes()
logger.info(f"Config loaded successfully from {self.config_path}")
logger.info(f"Total instances: {len(self._instances_by_id)}")
return True
except Exception as e:
logger.error(f"Failed to load config: {e}")
return False
def _validate_config(self) -> bool:
"""
验证配置合法性
Returns:
是否合法
"""
# 检查全局配置
if "global" not in self.config:
logger.error("Missing 'global' section in config")
return False
global_config = self.config["global"]
if "total_capital" not in global_config:
logger.error("Missing 'total_capital' in global config")
return False
# 检查策略实例配置
if "strategy_instances" not in self.config:
logger.error("Missing 'strategy_instances' section in config")
return False
instances = self.config["strategy_instances"]
if not isinstance(instances, list) or len(instances) == 0:
logger.error("'strategy_instances' must be a non-empty list")
return False
# 验证每个实例
instance_ids = set()
total_capital = 0
for instance in instances:
# 检查必需字段
required_fields = ["id", "symbol", "strategy_class", "capital"]
for field in required_fields:
if field not in instance:
logger.error(f"Missing required field '{field}' in instance")
return False
# 检查ID唯一性
instance_id = instance["id"]
if instance_id in instance_ids:
logger.error(f"Duplicate instance ID: {instance_id}")
return False
instance_ids.add(instance_id)
# 累计资金
total_capital += instance["capital"]
# 检查资金分配是否超过总资金
if total_capital > global_config["total_capital"]:
logger.warning(
f"Total allocated capital ({total_capital}) exceeds "
f"global total capital ({global_config['total_capital']})"
)
return True
def _build_indexes(self):
"""构建索引以加速查询"""
self._instances_by_id.clear()
self._instances_by_symbol.clear()
for instance in self.config["strategy_instances"]:
instance_id = instance["id"]
symbol = instance["symbol"]
# ID索引
self._instances_by_id[instance_id] = instance
# Symbol索引
if symbol not in self._instances_by_symbol:
self._instances_by_symbol[symbol] = []
self._instances_by_symbol[symbol].append(instance_id)
def get_instance_config(self, instance_id: str) -> Optional[Dict]:
"""
获取某个策略实例的配置
Args:
instance_id: 策略实例ID
Returns:
配置字典,如果不存在返回None
"""
return self._instances_by_id.get(instance_id)
def get_symbol_instances(self, symbol: str) -> List[Dict]:
"""
获取某个股票的所有策略实例配置
Args:
symbol: 股票代码
Returns:
配置列表
"""
instance_ids = self._instances_by_symbol.get(symbol, [])
return [self._instances_by_id[iid] for iid in instance_ids]
def get_all_instances(self) -> List[Dict]:
"""
获取所有策略实例配置
Returns:
配置列表
"""
return self.config.get("strategy_instances", [])
def get_global_config(self) -> Dict:
"""
获取全局配置
Returns:
全局配置字典
"""
return self.config.get("global", {})
def get_all_symbols(self) -> List[str]:
"""
获取所有配置的股票代码
Returns:
股票代码列表
"""
return list(self._instances_by_symbol.keys())
def reload(self) -> bool:
"""
热更新配置
Returns:
是否成功
"""
logger.info("Reloading config...")
return self.load()

View File

@ -0,0 +1,288 @@
"""
持仓管理器 (Position Manager)
负责管理每个策略实例的持仓和资金
"""
from typing import Dict, Optional
from dataclasses import dataclass
from src.strategy_service.config_loader import ConfigLoader
from src.core.logger import get_logger
logger = get_logger("PositionManager")
@dataclass
class Position:
"""持仓信息"""
symbol: str
quantity: int = 0 # 持仓数量
avg_cost: float = 0.0 # 平均成本
last_price: float = 0.0 # 最新价
def get_market_value(self) -> float:
"""计算市值"""
return self.quantity * self.last_price
def get_pnl(self) -> float:
"""计算浮动盈亏"""
if self.quantity == 0:
return 0.0
return (self.last_price - self.avg_cost) * self.quantity
@dataclass
class Capital:
"""资金信息"""
total: float # 总资金
available: float # 可用资金
frozen: float = 0.0 # 冻结资金
def get_used(self) -> float:
"""计算已使用资金"""
return self.total - self.available
class PositionManager:
"""
持仓管理器
负责:
- 管理每个策略实例的持仓
- 管理每个策略实例的资金
- 计算盈亏
- 策略间持仓和资金隔离
"""
def __init__(self, config_loader: ConfigLoader):
"""
初始化持仓管理器
Args:
config_loader: 配置加载器
"""
self.config_loader = config_loader
# 每个策略实例的持仓:{instance_id: Position}
self.positions: Dict[str, Position] = {}
# 每个策略实例的资金:{instance_id: Capital}
self.capitals: Dict[str, Capital] = {}
def initialize(self) -> bool:
"""
初始化所有策略实例的持仓和资金
Returns:
是否初始化成功
"""
try:
logger.info("Initializing position manager...")
for instance_config in self.config_loader.get_all_instances():
instance_id = instance_config["id"]
symbol = instance_config["symbol"]
capital = instance_config["capital"]
# 初始化持仓
self.positions[instance_id] = Position(symbol=symbol)
# 初始化资金
self.capitals[instance_id] = Capital(total=capital, available=capital)
logger.debug(
f"Initialized position for {instance_id}: "
f"{symbol}, capital={capital}"
)
logger.info(
f"Position manager initialized with {len(self.positions)} instances"
)
return True
except Exception as e:
logger.error(f"Failed to initialize position manager: {e}")
return False
def get_position(self, instance_id: str) -> Optional[Position]:
"""
获取策略实例的持仓
Args:
instance_id: 策略实例ID
Returns:
持仓信息,如果不存在返回None
"""
return self.positions.get(instance_id)
def get_capital(self, instance_id: str) -> Optional[Capital]:
"""
获取策略实例的资金
Args:
instance_id: 策略实例ID
Returns:
资金信息,如果不存在返回None
"""
return self.capitals.get(instance_id)
def get_available_capital(self, instance_id: str) -> float:
"""
获取策略实例的可用资金
Args:
instance_id: 策略实例ID
Returns:
可用资金
"""
capital = self.capitals.get(instance_id)
return capital.available if capital else 0.0
def update_position(
self, instance_id: str, action: str, quantity: int, price: float
) -> bool:
"""
更新策略实例的持仓
Args:
instance_id: 策略实例ID
action: 动作(BUY/SELL)
quantity: 数量
price: 价格
Returns:
是否更新成功
"""
position = self.positions.get(instance_id)
capital = self.capitals.get(instance_id)
if not position or not capital:
logger.error(f"Instance not found: {instance_id}")
return False
try:
if action == "BUY":
# 买入更新
total_cost = position.quantity * position.avg_cost
total_cost += quantity * price
position.quantity += quantity
position.avg_cost = (
total_cost / position.quantity if position.quantity > 0 else 0.0
)
# 更新资金
cost = quantity * price
capital.available -= cost
logger.debug(
f"Updated position (BUY): {instance_id}, "
f"qty={position.quantity}, avg_cost={position.avg_cost:.3f}"
)
elif action == "SELL":
# 卖出更新
if quantity > position.quantity:
logger.error(
f"Insufficient position: {instance_id}, "
f"have={position.quantity}, want={quantity}"
)
return False
position.quantity -= quantity
if position.quantity == 0:
position.avg_cost = 0.0
# 更新资金
proceeds = quantity * price
capital.available += proceeds
logger.debug(
f"Updated position (SELL): {instance_id}, qty={position.quantity}"
)
return True
except Exception as e:
logger.error(f"Failed to update position for {instance_id}: {e}")
return False
def update_price(self, instance_id: str, price: float):
"""
更新最新价格
Args:
instance_id: 策略实例ID
price: 最新价格
"""
position = self.positions.get(instance_id)
if position:
position.last_price = price
def get_instance_pnl(self, instance_id: str) -> float:
"""
计算策略实例的浮动盈亏
Args:
instance_id: 策略实例ID
Returns:
浮动盈亏
"""
position = self.positions.get(instance_id)
if not position:
return 0.0
return position.get_pnl()
def get_total_capital_used(self) -> float:
"""
获取所有策略使用的总资金
Returns:
已使用总资金
"""
total = 0.0
for capital in self.capitals.values():
total += capital.get_used()
return total
def get_total_market_value(self) -> float:
"""
获取所有持仓的总市值
Returns:
总市值
"""
total = 0.0
for position in self.positions.values():
total += position.get_market_value()
return total
def get_total_pnl(self) -> float:
"""
获取所有策略的总盈亏
Returns:
总盈亏
"""
total = 0.0
for instance_id, position in self.positions.items():
total += position.get_pnl()
return total
def get_summary(self) -> Dict:
"""
获取持仓汇总信息
Returns:
汇总字典
"""
return {
"total_capital_used": self.get_total_capital_used(),
"total_market_value": self.get_total_market_value(),
"total_pnl": self.get_total_pnl(),
"instance_count": len(self.positions),
}

View File

@ -0,0 +1,254 @@
"""
风控管理器 (Risk Manager)
负责多层级风控检查
"""
from typing import Dict
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
logger = get_logger("RiskManager")
@dataclass
class TradeSignal:
"""交易信号"""
instance_id: str
symbol: str
action: str # BUY/SELL/HOLD
price: float
quantity: int
message: str = ""
class RiskManager:
"""
风控管理器
负责:
- 全局风控:总仓位、总资金使用率
- 策略实例风控:资金、仓位、止损止盈
- 信号风控:单次交易检查
"""
def __init__(self, config_loader: ConfigLoader, position_manager: PositionManager):
"""
初始化风控管理器
Args:
config_loader: 配置加载器
position_manager: 持仓管理器
"""
self.config_loader = config_loader
self.position_manager = position_manager
def check_signal(self, signal: TradeSignal) -> bool:
"""
检查交易信号是否通过风控
Args:
signal: 交易信号
Returns:
是否通过风控
"""
# 1. 全局风控
if not self._check_global_risk(signal):
logger.warning(f"Signal rejected by global risk: {signal.instance_id}")
return False
# 2. 策略实例风控
if not self._check_instance_risk(signal):
logger.warning(f"Signal rejected by instance risk: {signal.instance_id}")
return False
# 3. 信号级风控
if not self._check_signal_risk(signal):
logger.warning(f"Signal rejected by signal risk: {signal.instance_id}")
return False
return True
def _check_global_risk(self, signal: TradeSignal) -> bool:
"""
全局风控检查
Args:
signal: 交易信号
Returns:
是否通过
"""
if signal.action != "BUY":
# 卖出不检查全局风控
return True
global_config = self.config_loader.get_global_config()
total_capital = global_config.get("total_capital", 0)
max_ratio = global_config.get("max_position_ratio", 1.0)
if total_capital == 0:
logger.error("Total capital is 0")
return False
# 计算当前总资金使用率
used_capital = self.position_manager.get_total_capital_used()
current_ratio = used_capital / total_capital
# 计算交易后的使用率
required = signal.quantity * signal.price
new_ratio = (used_capital + required) / total_capital
if new_ratio > max_ratio:
logger.warning(
f"Global position limit exceeded: current={current_ratio:.2%}, "
f"new={new_ratio:.2%}, max={max_ratio:.2%}"
)
return False
return True
def _check_instance_risk(self, signal: TradeSignal) -> bool:
"""
策略实例风控检查
Args:
signal: 交易信号
Returns:
是否通过
"""
instance_config = self.config_loader.get_instance_config(signal.instance_id)
if not instance_config:
logger.error(f"Instance config not found: {signal.instance_id}")
return False
position = self.position_manager.get_position(signal.instance_id)
capital = self.position_manager.get_capital(signal.instance_id)
if not position or not capital:
logger.error(f"Position or capital not found: {signal.instance_id}")
return False
risk_config = instance_config.get("risk", {})
if signal.action == "BUY":
# 买入检查
# 1. 检查可用资金
required = signal.quantity * signal.price
if required > capital.available:
logger.warning(
f"Insufficient capital: {signal.instance_id}, "
f"required={required:.2f}, available={capital.available:.2f}"
)
return False
# 2. 检查仓位比例
max_ratio = risk_config.get("max_position_ratio", 1.0)
current_used = capital.get_used()
new_used = current_used + required
new_ratio = new_used / capital.total
if new_ratio > max_ratio:
logger.warning(
f"Position ratio exceeded: {signal.instance_id}, "
f"new_ratio={new_ratio:.2%}, max={max_ratio:.2%}"
)
return False
elif signal.action == "SELL":
# 卖出检查
# 1. 检查持仓数量
if signal.quantity > position.quantity:
logger.warning(
f"Insufficient position: {signal.instance_id}, "
f"have={position.quantity}, want={signal.quantity}"
)
return False
# 2. 检查止损
if position.quantity > 0:
pnl = (signal.price - position.avg_cost) * signal.quantity
stop_loss = risk_config.get("stop_loss")
if stop_loss:
loss_threshold = -stop_loss * position.avg_cost * signal.quantity
if pnl < loss_threshold:
logger.info(
f"Stop loss triggered: {signal.instance_id}, "
f"pnl={pnl:.2f}, threshold={loss_threshold:.2f}"
)
# 止损触发,允许卖出
return True
# 3. 检查止盈
stop_profit = risk_config.get("stop_profit")
if stop_profit:
profit_threshold = stop_profit * position.avg_cost * signal.quantity
if pnl > profit_threshold:
logger.info(
f"Stop profit triggered: {signal.instance_id}, "
f"pnl={pnl:.2f}, threshold={profit_threshold:.2f}"
)
# 止盈触发,允许卖出
return True
return True
def _check_signal_risk(self, signal: TradeSignal) -> bool:
"""
信号级风控检查
Args:
signal: 交易信号
Returns:
是否通过
"""
# 1. 检查数量是否为正
if signal.quantity <= 0:
logger.warning(f"Invalid quantity: {signal.quantity}")
return False
# 2. 检查价格是否为正
if signal.price <= 0:
logger.warning(f"Invalid price: {signal.price}")
return False
# 3. 检查交易金额是否过大(防止异常订单)
amount = signal.quantity * signal.price
max_single_trade = 10000000 # 单笔最大1000万
if amount > max_single_trade:
logger.warning(
f"Single trade amount too large: {amount:.2f}, "
f"max={max_single_trade:.2f}"
)
return False
return True
def get_risk_summary(self) -> Dict:
"""
获取风控汇总信息
Returns:
汇总字典
"""
global_config = self.config_loader.get_global_config()
total_capital = global_config.get("total_capital", 0)
used_capital = self.position_manager.get_total_capital_used()
return {
"total_capital": total_capital,
"used_capital": used_capital,
"usage_ratio": used_capital / total_capital if total_capital > 0 else 0,
"max_position_ratio": global_config.get("max_position_ratio", 1.0),
}

View File

@ -0,0 +1,236 @@
"""
策略执行器 (Strategy Executor)
负责执行策略并生成交易信号
"""
from typing import Dict, List
import uuid
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
logger = get_logger("StrategyExecutor")
class StrategyExecutor:
"""
策略执行器
负责:
- 接收K线数据
- 调用策略实例计算信号
- 风控检查
- 记录信号
- 返回所有通过风控的信号
"""
def __init__(
self,
strategy_manager: StrategyManager,
position_manager: PositionManager,
risk_manager: RiskManager,
trade_recorder: TradeRecorder,
):
"""
初始化策略执行器
Args:
strategy_manager: 策略管理器
position_manager: 持仓管理器
risk_manager: 风控管理器
trade_recorder: 交易记录器
"""
self.strategy_manager = strategy_manager
self.position_manager = position_manager
self.risk_manager = risk_manager
self.trade_recorder = trade_recorder
def process_kline(self, symbol: str, kline_data: Dict) -> List[TradeSignal]:
"""
处理单个股票的K线数据
Args:
symbol: 股票代码
kline_data: K线数据字典
Returns:
通过风控的信号列表
"""
# 1. 获取该股票的所有策略实例
instances = self.strategy_manager.get_symbol_instances(symbol)
if not instances:
logger.debug(f"No strategy instances for {symbol}")
return []
logger.debug(f"Processing {symbol} for {len(instances)} instances")
# 2. 并行执行所有策略
signals = []
for instance_id, strategy_obj in instances:
try:
# 更新最新价格(用于计算盈亏)
current_price = kline_data.get("close", 0.0)
self.position_manager.update_price(instance_id, current_price)
# 构建完整的K线数据(包含symbol)
full_kline_data = {
"symbol": symbol,
**kline_data
}
# 调用策略计算
# 假设策略有compute方法返回action, price, quantity
result = strategy_obj.compute(full_kline_data)
if not result:
continue
action = result.get("action", "HOLD")
if action == "HOLD":
continue
# 构建信号
signal = TradeSignal(
instance_id=instance_id,
symbol=symbol,
action=action,
price=result.get("price", current_price),
quantity=result.get("quantity", 0),
message=result.get("message", ""),
)
# 3. 风控检查
if not self.risk_manager.check_signal(signal):
logger.debug(
f"Signal rejected by risk manager: {instance_id} {action}"
)
continue
# 4. 记录信号
signal_id = str(uuid.uuid4())
self.trade_recorder.record_signal(
instance_id=instance_id,
symbol=symbol,
action=action,
price=signal.price,
quantity=signal.quantity,
message=signal.message,
signal_id=signal_id,
)
signals.append(signal)
logger.info(
f"Generated signal: {instance_id} {action} {symbol} "
f"{signal.quantity}@{signal.price:.3f}"
)
except Exception as e:
logger.error(
f"Error processing strategy {instance_id}: {e}", exc_info=True
)
continue
return signals
def process_klines_batch(
self, klines_dict: Dict[str, Dict]
) -> Dict[str, List[TradeSignal]]:
"""
批量处理多个股票的K线数据
Args:
klines_dict: {symbol: kline_data} 字典
Returns:
{symbol: [signals]} 字典
"""
results = {}
for symbol, kline_data in klines_dict.items():
signals = self.process_kline(symbol, kline_data)
if signals:
results[symbol] = signals
return results
def process_trade_result(self, instance_id: str, trade_result: Dict) -> bool:
"""
处理交易成交结果
Args:
instance_id: 策略实例ID
trade_result: 成交结果字典,包含action, price, quantity等
Returns:
是否处理成功
"""
try:
action = trade_result.get("action")
price = trade_result.get("price")
quantity = trade_result.get("quantity")
symbol = trade_result.get("symbol")
if not action or price is None or quantity is None or not symbol:
logger.error(f"Invalid trade result: {trade_result}")
return False
# 确保类型正确
action = str(action)
price = float(price)
quantity = int(quantity)
symbol = str(symbol)
# 更新持仓
success = self.position_manager.update_position(
instance_id=instance_id, action=action, quantity=quantity, price=price
)
if not success:
logger.error(f"Failed to update position for {instance_id}")
return False
# 记录成交
trade_id = trade_result.get("trade_id", str(uuid.uuid4()))
signal_id = trade_result.get("signal_id")
self.trade_recorder.record_trade(
instance_id=instance_id,
symbol=symbol,
action=action,
price=price,
quantity=quantity,
trade_id=trade_id,
signal_id=signal_id,
)
logger.info(
f"Processed trade result: {instance_id} {action} {symbol} "
f"{quantity}@{price:.3f}"
)
return True
except Exception as e:
logger.error(f"Error processing trade result: {e}")
return False
def get_status(self) -> Dict:
"""
获取执行器状态
Returns:
状态字典
"""
return {
"position_summary": self.position_manager.get_summary(),
"risk_summary": self.risk_manager.get_risk_summary(),
"trade_stats": self.trade_recorder.get_all_stats(),
}

View File

@ -0,0 +1,207 @@
"""
策略管理器 (Strategy Manager)
负责管理所有策略实例的创建、缓存和查询
"""
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
logger = get_logger("StrategyManager")
class StrategyManager:
"""
策略管理器
负责:
- 管理所有策略实例对象
- 根据配置创建策略实例
- 提供策略实例查询接口
- 策略生命周期管理
"""
def __init__(self, config_loader: ConfigLoader):
"""
初始化策略管理器
Args:
config_loader: 配置加载器
"""
self.config_loader = config_loader
# 策略实例字典:{instance_id: strategy_object}
self.instances: Dict[str, Any] = {}
# 按股票索引:{symbol: [instance_id1, instance_id2, ...]}
self.symbol_instances: Dict[str, List[str]] = {}
def initialize(self) -> bool:
"""
初始化所有策略实例
根据配置创建每个策略实例对象
Returns:
是否初始化成功
"""
try:
logger.info("Initializing strategy manager...")
for instance_config in self.config_loader.get_all_instances():
instance_id = instance_config["id"]
symbol = instance_config["symbol"]
strategy_class_name = instance_config["strategy_class"]
params = instance_config.get("params", {})
# 获取策略类
strategy_class = self._get_strategy_class(strategy_class_name)
if not strategy_class:
logger.error(
f"Failed to load strategy class: {strategy_class_name}"
)
continue
# 创建策略实例
try:
strategy_obj = strategy_class(**params)
self.instances[instance_id] = strategy_obj
# 建立symbol索引
if symbol not in self.symbol_instances:
self.symbol_instances[symbol] = []
self.symbol_instances[symbol].append(instance_id)
logger.info(
f"Created strategy instance: {instance_id} "
f"({strategy_class_name}) for {symbol}"
)
except Exception as e:
logger.error(
f"Failed to create strategy instance {instance_id}: {e}"
)
continue
logger.info(
f"Strategy manager initialized with {len(self.instances)} instances"
)
return True
except Exception as e:
logger.error(f"Failed to initialize strategy manager: {e}")
return False
def _get_strategy_class(self, class_name: str) -> Optional[Type]:
"""
动态加载策略类
Args:
class_name: 策略类名
Returns:
策略类,如果加载失败返回None
"""
try:
# 尝试从strategies模块加载
# 假设策略类在 strategies 目录下,文件名为类名的小写蛇形命名
# 例如: MAStrategy -> ma_strategy.py
module_name = self._class_name_to_module_name(class_name)
module_path = f"strategies.{module_name}"
module = importlib.import_module(module_path)
strategy_class = getattr(module, class_name)
return strategy_class
except Exception as e:
logger.error(f"Failed to load strategy class {class_name}: {e}")
return None
def _class_name_to_module_name(self, class_name: str) -> str:
"""
将类名转换为模块名
例如: MAStrategy -> ma_strategy
Args:
class_name: 类名
Returns:
模块名
"""
# 简单的驼峰转蛇形
import re
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", class_name)
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
def get_instance(self, instance_id: str) -> Optional[Any]:
"""
获取某个策略实例对象
Args:
instance_id: 策略实例ID
Returns:
策略实例对象,如果不存在返回None
"""
return self.instances.get(instance_id)
def get_symbol_instances(self, symbol: str) -> List[Tuple[str, Any]]:
"""
获取某个股票的所有策略实例
Args:
symbol: 股票代码
Returns:
[(instance_id, strategy_object), ...] 列表
"""
instance_ids = self.symbol_instances.get(symbol, [])
return [
(instance_id, self.instances[instance_id])
for instance_id in instance_ids
if instance_id in self.instances
]
def get_all_instances(self) -> Dict[str, Any]:
"""
获取所有策略实例
Returns:
{instance_id: strategy_object} 字典
"""
return self.instances
def reload_instance(self, instance_id: str) -> bool:
"""
重新加载某个策略实例
Args:
instance_id: 策略实例ID
Returns:
是否成功
"""
instance_config = self.config_loader.get_instance_config(instance_id)
if not instance_config:
logger.error(f"Instance config not found: {instance_id}")
return False
try:
strategy_class_name = instance_config["strategy_class"]
params = instance_config.get("params", {})
strategy_class = self._get_strategy_class(strategy_class_name)
if not strategy_class:
return False
strategy_obj = strategy_class(**params)
self.instances[instance_id] = strategy_obj
logger.info(f"Reloaded strategy instance: {instance_id}")
return True
except Exception as e:
logger.error(f"Failed to reload instance {instance_id}: {e}")
return False

View File

@ -0,0 +1,267 @@
"""
交易记录器 (Trade Recorder)
负责记录所有交易信号和成交信息
"""
from typing import Dict, List, Optional
from datetime import datetime
from dataclasses import dataclass, asdict
import json
from src.core.logger import get_logger
logger = get_logger("TradeRecorder")
@dataclass
class SignalRecord:
"""信号记录"""
instance_id: str
symbol: str
action: str
price: float
quantity: int
message: str
timestamp: str
signal_id: Optional[str] = None
@dataclass
class TradeRecord:
"""成交记录"""
instance_id: str
symbol: str
action: str
price: float
quantity: int
amount: float
timestamp: str
trade_id: Optional[str] = None
signal_id: Optional[str] = None
class TradeRecorder:
"""
交易记录器
负责:
- 记录每个策略实例的信号
- 记录每个策略实例的成交
- 提供历史查询
- 计算策略绩效
"""
def __init__(self):
"""初始化交易记录器"""
# 信号记录:{instance_id: [SignalRecord, ...]}
self.signal_records: Dict[str, List[SignalRecord]] = {}
# 成交记录:{instance_id: [TradeRecord, ...]}
self.trade_records: Dict[str, List[TradeRecord]] = {}
def record_signal(
self,
instance_id: str,
symbol: str,
action: str,
price: float,
quantity: int,
message: str = "",
signal_id: Optional[str] = None,
):
"""
记录交易信号
Args:
instance_id: 策略实例ID
symbol: 股票代码
action: 动作
price: 价格
quantity: 数量
message: 消息
signal_id: 信号ID
"""
record = SignalRecord(
instance_id=instance_id,
symbol=symbol,
action=action,
price=price,
quantity=quantity,
message=message,
timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
signal_id=signal_id,
)
if instance_id not in self.signal_records:
self.signal_records[instance_id] = []
self.signal_records[instance_id].append(record)
logger.debug(
f"Recorded signal: {instance_id} {action} {symbol} {quantity}@{price:.3f}"
)
def record_trade(
self,
instance_id: str,
symbol: str,
action: str,
price: float,
quantity: int,
trade_id: Optional[str] = None,
signal_id: Optional[str] = None,
):
"""
记录成交
Args:
instance_id: 策略实例ID
symbol: 股票代码
action: 动作
price: 价格
quantity: 数量
trade_id: 成交ID
signal_id: 关联的信号ID
"""
amount = price * quantity
record = TradeRecord(
instance_id=instance_id,
symbol=symbol,
action=action,
price=price,
quantity=quantity,
amount=amount,
timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
trade_id=trade_id,
signal_id=signal_id,
)
if instance_id not in self.trade_records:
self.trade_records[instance_id] = []
self.trade_records[instance_id].append(record)
logger.info(
f"Recorded trade: {instance_id} {action} {symbol} "
f"{quantity}@{price:.3f}, amount={amount:.2f}"
)
def get_signal_history(
self, instance_id: str, limit: Optional[int] = None
) -> List[SignalRecord]:
"""
获取信号历史
Args:
instance_id: 策略实例ID
limit: 返回数量限制
Returns:
信号记录列表
"""
records = self.signal_records.get(instance_id, [])
if limit:
return records[-limit:]
return records
def get_trade_history(
self, instance_id: str, limit: Optional[int] = None
) -> List[TradeRecord]:
"""
获取成交历史
Args:
instance_id: 策略实例ID
limit: 返回数量限制
Returns:
成交记录列表
"""
records = self.trade_records.get(instance_id, [])
if limit:
return records[-limit:]
return records
def get_instance_stats(self, instance_id: str) -> Dict:
"""
获取策略实例的统计信息
Args:
instance_id: 策略实例ID
Returns:
统计字典
"""
trades = self.trade_records.get(instance_id, [])
if not trades:
return {
"total_trades": 0,
"buy_count": 0,
"sell_count": 0,
"total_buy_amount": 0.0,
"total_sell_amount": 0.0,
}
buy_trades = [t for t in trades if t.action == "BUY"]
sell_trades = [t for t in trades if t.action == "SELL"]
return {
"total_trades": len(trades),
"buy_count": len(buy_trades),
"sell_count": len(sell_trades),
"total_buy_amount": sum(t.amount for t in buy_trades),
"total_sell_amount": sum(t.amount for t in sell_trades),
"last_trade_time": trades[-1].timestamp if trades else None,
}
def get_all_stats(self) -> Dict:
"""
获取所有策略实例的汇总统计
Returns:
汇总统计字典
"""
all_trades = []
for records in self.trade_records.values():
all_trades.extend(records)
if not all_trades:
return {
"total_instances": len(self.trade_records),
"total_trades": 0,
}
return {
"total_instances": len(self.trade_records),
"total_trades": len(all_trades),
"total_amount": sum(t.amount for t in all_trades),
}
def export_records(self, filepath: str):
"""
导出所有记录到文件
Args:
filepath: 文件路径
"""
try:
data = {
"signals": {
instance_id: [asdict(r) for r in records]
for instance_id, records in self.signal_records.items()
},
"trades": {
instance_id: [asdict(r) for r in records]
for instance_id, records in self.trade_records.items()
},
}
with open(filepath, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
logger.info(f"Records exported to {filepath}")
except Exception as e:
logger.error(f"Failed to export records: {e}")

View File

@ -1,11 +0,0 @@
"""
策略包
存放所有自定义策略。
"""
from .simple_ma_strategy import SimpleMAStrategy
__all__ = [
"SimpleMAStrategy",
]

View File

@ -1,103 +0,0 @@
"""
示例策略:简单移动平均线交叉策略
这是一个简单的示例策略,展示如何使用策略框架。
策略逻辑:
- 当短期均线上穿长期均线时,买入
- 当短期均线下穿长期均线时,卖出
"""
from typing import Dict, Any, List
from src.strategy import BaseStrategy
from src.market.market_gateway import BarData
class SimpleMAStrategy(BaseStrategy):
"""简单移动平均线策略"""
def __init__(self, strategy_id: str, params: Dict[str, Any]):
"""
初始化策略
参数:
short_period: 短期均线周期(默认5)
long_period: 长期均线周期(默认20)
"""
super().__init__(strategy_id, params)
# 策略参数
self.short_period = self.get_param("short_period", 5)
self.long_period = self.get_param("long_period", 20)
# 状态变量
self.prices: List[float] = []
self.position_opened = False
async def on_init(self, context):
"""策略初始化"""
self.logger.info("策略初始化")
self.logger.info(f"短期周期: {self.short_period}")
self.logger.info(f"长期周期: {self.long_period}")
# 加载历史数据用于计算初始均线
history_bars = await context.get_history_bars(self.long_period)
self.prices = [bar.close for bar in history_bars]
self.logger.info(f"加载历史数据: {len(self.prices)} 条")
async def on_bar(self, bar: BarData, context):
"""K线事件处理"""
# 更新价格序列
self.prices.append(bar.close)
if len(self.prices) > self.long_period:
self.prices.pop(0)
# 等待数据足够
if len(self.prices) < self.long_period:
return
# 计算均线
short_ma = sum(self.prices[-self.short_period :]) / self.short_period
long_ma = sum(self.prices[-self.long_period :]) / self.long_period
# 记录信息
self.logger.debug(
f"{bar.time} - 价格: {bar.close:.2f}, "
f"短均线: {short_ma:.2f}, 长均线: {long_ma:.2f}"
)
# 交易逻辑
has_position = context.has_position()
if not has_position and short_ma > long_ma:
# 金叉买入
buy_quantity = int(context.available_cash * 0.95 / bar.close / 100) * 100
if buy_quantity > 0:
self.logger.info(f"金叉信号 - 买入 {buy_quantity} 股 @ {bar.close:.2f}")
await context.buy(
symbol=bar.symbol,
quantity=buy_quantity,
price=bar.close,
)
self.position_opened = True
elif has_position and short_ma < long_ma:
# 死叉卖出
self.logger.info(f"死叉信号 - 平仓 @ {bar.close:.2f}")
await context.close_position()
self.position_opened = False
async def on_order_filled(self, order, context):
"""订单成交回调"""
self.logger.info(f"订单成交: {order.id}")
async def on_stop(self, context):
"""策略停止"""
self.logger.info("策略停止")
# 如果还有持仓,平仓
if context.has_position():
self.logger.info("策略停止时平仓")
await context.close_position()

108
test_run.py Normal file
View File

@ -0,0 +1,108 @@
"""
测试启动脚本 - 简单版本
先启动服务器,等待一段时间后启动客户端
"""
import subprocess
import sys
import time
from pathlib import Path
# 工作目录
workspace = Path(__file__).parent
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)
subprocess.run([sys.executable, "-m", "src.qtrade_server"], cwd=workspace)
def start_client_newwindow():
"""启动客户端进程(在新的控制台窗口)"""
print("\n" + "=" * 60)
print("正在启动 Backtest Client(新窗口)...")
print("=" * 60)
subprocess.Popen(
[sys.executable, "-m", "src.backtest.main"],
cwd=workspace,
creationflags=subprocess.CREATE_NEW_CONSOLE, # Windows下在新控制台窗口启动
)
print("✓ 客户端已在新窗口启动。")
def start_client():
"""启动客户端进程(直接显示输出)"""
print("\n" + "=" * 60)
print("正在启动 Backtest Client...")
print("=" * 60)
subprocess.run([sys.executable, "-m", "src.backtest.main"], cwd=workspace)
def main():
"""主函数"""
# 检查是否使用新窗口模式
use_new_window = len(sys.argv) > 2 and sys.argv[2] == "newwindow"
if len(sys.argv) > 1 and sys.argv[1] == "server":
# 只启动服务器
if use_new_window:
start_server_newwindow()
else:
start_server()
elif len(sys.argv) > 1 and sys.argv[1] == "client":
# 只启动客户端
if use_new_window:
start_client_newwindow()
else:
start_client()
elif len(sys.argv) > 1 and sys.argv[1] == "both":
# 同时启动服务器和客户端
print("=" * 60)
print("同时启动服务器和客户端")
print("=" * 60)
if use_new_window:
# 新窗口模式:两个进程都在新窗口运行
start_server_newwindow()
time.sleep(5) # 等待服务器启动
print("\n现在启动客户端...")
start_client_newwindow()
print("\n✓ 服务器和客户端都已在新窗口启动")
else:
# 默认模式:服务器在新窗口,客户端在当前窗口
start_server_newwindow()
time.sleep(5) # 等待服务器启动
print("\n现在启动客户端...")
start_client()
else:
print("使用方法:")
print(" 启动服务器: python test_run.py server [newwindow]")
print(" 启动客户端: python test_run.py client [newwindow]")
print(" 同时启动: python test_run.py both [newwindow]")
print("\n说明:")
print(" - 默认模式: 进程在当前窗口显示输出")
print(" - newwindow: 进程在新控制台窗口运行")
print("\n建议:")
print(" 1. 先运行: python test_run.py server newwindow")
print(" 2. 然后运行: python test_run.py client")
print(" 或直接: python test_run.py both (服务器新窗口,客户端当前窗口)")
if __name__ == "__main__":
main()