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
This commit is contained in:
parent
61feb5daa0
commit
14caec147b
71
config/strategy_config.yaml
Normal file
71
config/strategy_config.yaml
Normal 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
|
||||||
246
docs/backend_refactor.md
Normal file
246
docs/backend_refactor.md
Normal file
@ -0,0 +1,246 @@
|
|||||||
|
# 后端架构重构说明
|
||||||
|
|
||||||
|
## 架构概览
|
||||||
|
|
||||||
|
新的后端架构将业务逻辑从通信层完全分离,采用分层设计:
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────┐
|
||||||
|
│ WebSocket Server (通信层) │
|
||||||
|
│ ws_server_refactored.py │
|
||||||
|
│ - 接收/发送WebSocket消息 │
|
||||||
|
│ - 协议解析 │
|
||||||
|
│ - 不包含业务逻辑 │
|
||||||
|
└────────────┬────────────────────────┘
|
||||||
|
│ 委托
|
||||||
|
↓
|
||||||
|
┌─────────────────────────────────────┐
|
||||||
|
│ Strategy Service (业务层) │
|
||||||
|
│ │
|
||||||
|
│ ├─ StrategyExecutor (执行器) │
|
||||||
|
│ ├─ StrategyManager (策略管理) │
|
||||||
|
│ ├─ PositionManager (持仓管理) │
|
||||||
|
│ ├─ RiskManager (风控管理) │
|
||||||
|
│ ├─ TradeRecorder (交易记录) │
|
||||||
|
│ └─ ConfigLoader (配置加载) │
|
||||||
|
└─────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## 核心特性
|
||||||
|
|
||||||
|
### 1. 一个股票多个策略
|
||||||
|
- 每个策略实例完全独立
|
||||||
|
- 独立的资金分配
|
||||||
|
- 独立的持仓管理
|
||||||
|
- 独立的风控参数
|
||||||
|
|
||||||
|
### 2. 多层级风控
|
||||||
|
- **全局风控**: 总资金、总仓位限制
|
||||||
|
- **实例风控**: 单个策略的资金、仓位、止损止盈
|
||||||
|
- **信号风控**: 单次交易的合法性检查
|
||||||
|
|
||||||
|
### 3. 无信号聚合
|
||||||
|
- 每个策略实例独立计算和返回信号
|
||||||
|
- 后端返回所有策略的信号列表
|
||||||
|
- 前端/回测引擎决定如何执行
|
||||||
|
|
||||||
|
## 目录结构
|
||||||
|
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
├── strategy_service/ # 业务层模块
|
||||||
|
│ ├── __init__.py
|
||||||
|
│ ├── config_loader.py # 配置加载器
|
||||||
|
│ ├── strategy_manager.py # 策略管理器
|
||||||
|
│ ├── position_manager.py # 持仓管理器
|
||||||
|
│ ├── risk_manager.py # 风控管理器
|
||||||
|
│ ├── trade_recorder.py # 交易记录器
|
||||||
|
│ └── strategy_executor.py # 策略执行器(核心)
|
||||||
|
│
|
||||||
|
├── networks/server/
|
||||||
|
│ ├── ws_server.py # 旧版本(保留)
|
||||||
|
│ └── ws_server_refactored.py # 新版本(重构后)
|
||||||
|
│
|
||||||
|
└── config/
|
||||||
|
└── strategy_config.yaml # 策略配置文件
|
||||||
|
|
||||||
|
strategies/ # 策略实现目录
|
||||||
|
├── ma_strategy.py
|
||||||
|
├── macd_strategy.py
|
||||||
|
└── ...
|
||||||
|
```
|
||||||
|
|
||||||
|
## 配置文件
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
global:
|
||||||
|
total_capital: 1000000
|
||||||
|
max_position_ratio: 0.8
|
||||||
|
|
||||||
|
strategy_instances:
|
||||||
|
- id: "ma_short_000001" # 唯一ID
|
||||||
|
symbol: "000001.SZ" # 股票代码
|
||||||
|
strategy_class: "MAStrategy" # 策略类名
|
||||||
|
capital: 100000 # 分配资金
|
||||||
|
params: # 策略参数
|
||||||
|
short_period: 5
|
||||||
|
long_period: 20
|
||||||
|
risk: # 风控参数
|
||||||
|
max_position_ratio: 0.8
|
||||||
|
stop_loss: 0.05
|
||||||
|
```
|
||||||
|
|
||||||
|
## 核心模块
|
||||||
|
|
||||||
|
### ConfigLoader
|
||||||
|
- 加载并验证配置文件
|
||||||
|
- 提供配置查询接口
|
||||||
|
- 支持热更新
|
||||||
|
|
||||||
|
### StrategyManager
|
||||||
|
- 创建和管理所有策略实例
|
||||||
|
- 动态加载策略类
|
||||||
|
- 提供策略查询接口
|
||||||
|
|
||||||
|
### PositionManager
|
||||||
|
- 管理每个策略实例的持仓
|
||||||
|
- 管理每个策略实例的资金
|
||||||
|
- 计算盈亏
|
||||||
|
- 策略间完全隔离
|
||||||
|
|
||||||
|
### RiskManager
|
||||||
|
- 全局风控检查
|
||||||
|
- 策略实例风控检查
|
||||||
|
- 信号合法性检查
|
||||||
|
|
||||||
|
### TradeRecorder
|
||||||
|
- 记录所有信号
|
||||||
|
- 记录所有成交
|
||||||
|
- 提供历史查询
|
||||||
|
- 计算策略绩效
|
||||||
|
|
||||||
|
### StrategyExecutor
|
||||||
|
- 核心协调器
|
||||||
|
- 接收K线数据
|
||||||
|
- 调用策略计算
|
||||||
|
- 执行风控检查
|
||||||
|
- 记录信号
|
||||||
|
- 返回结果
|
||||||
|
|
||||||
|
## 数据流
|
||||||
|
|
||||||
|
```
|
||||||
|
1. K线数据进入
|
||||||
|
↓
|
||||||
|
2. WebSocket Server 接收并解析
|
||||||
|
↓
|
||||||
|
3. StrategyExecutor 处理
|
||||||
|
├─ 获取该股票的所有策略实例
|
||||||
|
├─ 并行调用每个策略计算
|
||||||
|
├─ 对每个信号进行风控检查
|
||||||
|
└─ 记录信号
|
||||||
|
↓
|
||||||
|
4. 返回所有通过风控的信号
|
||||||
|
↓
|
||||||
|
5. 前端/回测引擎执行交易
|
||||||
|
↓
|
||||||
|
6. 成交结果返回
|
||||||
|
↓
|
||||||
|
7. StrategyExecutor 更新持仓和资金
|
||||||
|
```
|
||||||
|
|
||||||
|
## 协议更新
|
||||||
|
|
||||||
|
### 请求: KLINE_DATA
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"header": {...},
|
||||||
|
"msg_type": "KLINE_DATA",
|
||||||
|
"symbol": "000001.SZ",
|
||||||
|
"data": {...}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 响应: TRADE_SIGNALS (复数)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"header": {...},
|
||||||
|
"msg_type": "TRADE_SIGNALS",
|
||||||
|
"signals": [
|
||||||
|
{
|
||||||
|
"instance_id": "ma_short_000001",
|
||||||
|
"symbol": "000001.SZ",
|
||||||
|
"action": "BUY",
|
||||||
|
"price": 10.5,
|
||||||
|
"quantity": 1000,
|
||||||
|
"message": "Golden cross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"instance_id": "macd_000001",
|
||||||
|
"symbol": "000001.SZ",
|
||||||
|
"action": "HOLD",
|
||||||
|
"price": 10.5,
|
||||||
|
"quantity": 0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 请求: TRADE_RESULT (成交反馈)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"header": {...},
|
||||||
|
"msg_type": "TRADE_RESULT",
|
||||||
|
"instance_id": "ma_short_000001",
|
||||||
|
"symbol": "000001.SZ",
|
||||||
|
"action": "BUY",
|
||||||
|
"price": 10.5,
|
||||||
|
"quantity": 1000,
|
||||||
|
"trade_id": "...",
|
||||||
|
"signal_id": "..."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 使用方法
|
||||||
|
|
||||||
|
### 启动服务器
|
||||||
|
```python
|
||||||
|
from src.networks.server.ws_server_refactored import start_server
|
||||||
|
|
||||||
|
start_server(
|
||||||
|
host="0.0.0.0",
|
||||||
|
port=8000,
|
||||||
|
config_path="config/strategy_config.yaml"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 添加新策略
|
||||||
|
1. 在 `strategies/` 目录创建策略类
|
||||||
|
2. 在配置文件中添加策略实例
|
||||||
|
3. 重启服务器
|
||||||
|
|
||||||
|
### 热更新配置
|
||||||
|
```python
|
||||||
|
# ConfigLoader 支持 reload() 方法
|
||||||
|
# 未来可以添加配置文件监听
|
||||||
|
```
|
||||||
|
|
||||||
|
## 优势
|
||||||
|
|
||||||
|
1. **清晰的职责分离**: 通信层和业务层完全解耦
|
||||||
|
2. **高度模块化**: 每个模块职责单一,易于测试和维护
|
||||||
|
3. **灵活的配置**: 通过配置文件管理所有策略实例
|
||||||
|
4. **策略隔离**: 每个策略实例资金和持仓完全隔离
|
||||||
|
5. **多层风控**: 全局、实例、信号三层风控保护
|
||||||
|
6. **易于扩展**: 添加新策略无需修改核心代码
|
||||||
|
7. **完整记录**: 所有信号和成交都有详细记录
|
||||||
|
|
||||||
|
## 后续工作
|
||||||
|
|
||||||
|
- [ ] 实现具体的策略类 (MAStrategy, MACDStrategy等)
|
||||||
|
- [ ] 添加策略基类定义标准接口
|
||||||
|
- [ ] 实现配置文件热更新
|
||||||
|
- [ ] 添加数据库持久化(使用 TradeRecorder)
|
||||||
|
- [ ] 添加性能监控和日志
|
||||||
|
- [ ] 编写单元测试
|
||||||
|
- [ ] 添加WebSocket断线重连机制
|
||||||
@ -4,7 +4,6 @@
|
|||||||
简单的回测引擎类
|
简单的回测引擎类
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import re
|
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
|
||||||
from src.data_service.data_service import DataService
|
from src.data_service.data_service import DataService
|
||||||
|
|||||||
@ -5,11 +5,7 @@
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
from typing import Dict, Any, List
|
from typing import Dict, Any, List
|
||||||
from .table_utils import (
|
from .table_utils import SUPPORTED_PERIODS
|
||||||
get_all_kline_table_names,
|
|
||||||
get_all_indicator_table_names,
|
|
||||||
SUPPORTED_PERIODS,
|
|
||||||
)
|
|
||||||
|
|
||||||
# ==================== Tick 表 ====================
|
# ==================== Tick 表 ====================
|
||||||
TICK_TABLE = {
|
TICK_TABLE = {
|
||||||
|
|||||||
374
src/networks/server/ws_server_refactored.py
Normal file
374
src/networks/server/ws_server_refactored.py
Normal file
@ -0,0 +1,374 @@
|
|||||||
|
"""
|
||||||
|
策略服务器 (Strategy Server) - 重构版
|
||||||
|
|
||||||
|
纯WebSocket通信层,业务逻辑委托给 StrategyExecutor
|
||||||
|
协议版本: v1.0
|
||||||
|
"""
|
||||||
|
|
||||||
|
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
|
||||||
|
from typing import Optional
|
||||||
|
import uvicorn
|
||||||
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from src.core.logger import get_logger
|
||||||
|
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
|
||||||
|
|
||||||
|
logger = get_logger("StrategyServer")
|
||||||
|
|
||||||
|
app = FastAPI(title="QTrade Strategy Server", version="1.0.0")
|
||||||
|
|
||||||
|
# 全局业务层实例
|
||||||
|
strategy_executor: Optional[StrategyExecutor] = None
|
||||||
|
|
||||||
|
|
||||||
|
def initialize_services(config_path: str = "config/strategy_config.yaml") -> bool:
|
||||||
|
"""
|
||||||
|
初始化所有服务
|
||||||
|
|
||||||
|
Args:
|
||||||
|
config_path: 配置文件路径
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
是否初始化成功
|
||||||
|
"""
|
||||||
|
global strategy_executor
|
||||||
|
|
||||||
|
try:
|
||||||
|
logger.info("Initializing strategy services...")
|
||||||
|
|
||||||
|
# 1. 加载配置
|
||||||
|
config_loader = ConfigLoader(config_path)
|
||||||
|
if not config_loader.load():
|
||||||
|
logger.error("Failed to load config")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 2. 初始化持仓管理器
|
||||||
|
position_manager = PositionManager(config_loader)
|
||||||
|
if not position_manager.initialize():
|
||||||
|
logger.error("Failed to initialize position manager")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 3. 初始化策略管理器
|
||||||
|
strategy_manager = StrategyManager(config_loader)
|
||||||
|
if not strategy_manager.initialize():
|
||||||
|
logger.error("Failed to initialize strategy manager")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 4. 初始化风控管理器
|
||||||
|
risk_manager = RiskManager(config_loader, position_manager)
|
||||||
|
|
||||||
|
# 5. 初始化交易记录器
|
||||||
|
trade_recorder = TradeRecorder()
|
||||||
|
|
||||||
|
# 6. 创建策略执行器
|
||||||
|
strategy_executor = StrategyExecutor(
|
||||||
|
strategy_manager, position_manager, risk_manager, trade_recorder
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info("Strategy services initialized successfully")
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to initialize services: {e}", exc_info=True)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def create_response_header(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,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.websocket("/ws/strategy")
|
||||||
|
async def websocket_strategy_endpoint(websocket: 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")
|
||||||
|
|
||||||
|
# 分发处理
|
||||||
|
if msg_type == "KLINE_DATA":
|
||||||
|
response = await handle_kline_data(message, req_msg_id)
|
||||||
|
elif msg_type == "KLINE_DATA_BATCH":
|
||||||
|
response = await handle_kline_batch(message, req_msg_id)
|
||||||
|
elif msg_type == "TRADE_RESULT":
|
||||||
|
response = await handle_trade_result(message, req_msg_id)
|
||||||
|
elif msg_type == "QUERY_STATUS":
|
||||||
|
response = await handle_query_status(req_msg_id)
|
||||||
|
else:
|
||||||
|
response = 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 = create_error_response(str(e), "INTERNAL_ERROR")
|
||||||
|
await websocket.send_text(json.dumps(error_response))
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
async def handle_kline_data(message: dict, req_msg_id: str) -> dict:
|
||||||
|
"""
|
||||||
|
处理单条K线数据
|
||||||
|
|
||||||
|
Args:
|
||||||
|
message: 请求消息
|
||||||
|
req_msg_id: 请求消息ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
响应消息
|
||||||
|
"""
|
||||||
|
if not strategy_executor:
|
||||||
|
return create_error_response(
|
||||||
|
"Strategy executor not initialized", "SERVICE_NOT_READY", req_msg_id
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
symbol = message.get("symbol")
|
||||||
|
kline_data = {
|
||||||
|
"open": message["data"]["open"],
|
||||||
|
"high": message["data"]["high"],
|
||||||
|
"low": message["data"]["low"],
|
||||||
|
"close": message["data"]["close"],
|
||||||
|
"volume": message["data"]["volume"],
|
||||||
|
}
|
||||||
|
|
||||||
|
# 调用业务层
|
||||||
|
signals = strategy_executor.process_kline(symbol, kline_data)
|
||||||
|
|
||||||
|
# 构建响应
|
||||||
|
if not signals:
|
||||||
|
# 没有信号,返回HOLD
|
||||||
|
return {
|
||||||
|
"header": create_response_header(req_msg_id),
|
||||||
|
"msg_type": "TRADE_SIGNALS",
|
||||||
|
"signals": [],
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
# 返回所有信号
|
||||||
|
return {
|
||||||
|
"header": create_response_header(req_msg_id),
|
||||||
|
"msg_type": "TRADE_SIGNALS",
|
||||||
|
"signals": [
|
||||||
|
{
|
||||||
|
"instance_id": signal.instance_id,
|
||||||
|
"symbol": signal.symbol,
|
||||||
|
"action": signal.action,
|
||||||
|
"price": signal.price,
|
||||||
|
"quantity": signal.quantity,
|
||||||
|
"message": signal.message,
|
||||||
|
}
|
||||||
|
for signal in signals
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error handling kline data: {e}", exc_info=True)
|
||||||
|
return create_error_response(str(e), "PROCESSING_ERROR", req_msg_id)
|
||||||
|
|
||||||
|
|
||||||
|
async def handle_kline_batch(message: dict, req_msg_id: str) -> dict:
|
||||||
|
"""
|
||||||
|
处理批量K线数据
|
||||||
|
|
||||||
|
Args:
|
||||||
|
message: 请求消息
|
||||||
|
req_msg_id: 请求消息ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
响应消息
|
||||||
|
"""
|
||||||
|
if not strategy_executor:
|
||||||
|
return create_error_response(
|
||||||
|
"Strategy executor not initialized", "SERVICE_NOT_READY", req_msg_id
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
batch_data = message.get("batch_data", [])
|
||||||
|
klines_dict = {}
|
||||||
|
|
||||||
|
for item in batch_data:
|
||||||
|
symbol = item["symbol"]
|
||||||
|
klines_dict[symbol] = {
|
||||||
|
"open": item["data"]["open"],
|
||||||
|
"high": item["data"]["high"],
|
||||||
|
"low": item["data"]["low"],
|
||||||
|
"close": item["data"]["close"],
|
||||||
|
"volume": item["data"]["volume"],
|
||||||
|
}
|
||||||
|
|
||||||
|
# 调用业务层
|
||||||
|
results = strategy_executor.process_klines_batch(klines_dict)
|
||||||
|
|
||||||
|
# 构建响应
|
||||||
|
all_signals = []
|
||||||
|
for symbol, signals in results.items():
|
||||||
|
for signal in signals:
|
||||||
|
all_signals.append(
|
||||||
|
{
|
||||||
|
"instance_id": signal.instance_id,
|
||||||
|
"symbol": signal.symbol,
|
||||||
|
"action": signal.action,
|
||||||
|
"price": signal.price,
|
||||||
|
"quantity": signal.quantity,
|
||||||
|
"message": signal.message,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"header": create_response_header(req_msg_id),
|
||||||
|
"msg_type": "TRADE_SIGNALS",
|
||||||
|
"signals": all_signals,
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error handling kline batch: {e}", exc_info=True)
|
||||||
|
return create_error_response(str(e), "PROCESSING_ERROR", req_msg_id)
|
||||||
|
|
||||||
|
|
||||||
|
async def handle_trade_result(message: dict, req_msg_id: str) -> dict:
|
||||||
|
"""
|
||||||
|
处理交易成交结果
|
||||||
|
|
||||||
|
Args:
|
||||||
|
message: 请求消息
|
||||||
|
req_msg_id: 请求消息ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
响应消息
|
||||||
|
"""
|
||||||
|
if not strategy_executor:
|
||||||
|
return create_error_response(
|
||||||
|
"Strategy executor not initialized", "SERVICE_NOT_READY", req_msg_id
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
instance_id = message.get("instance_id")
|
||||||
|
trade_result = {
|
||||||
|
"symbol": message.get("symbol"),
|
||||||
|
"action": message.get("action"),
|
||||||
|
"price": message.get("price"),
|
||||||
|
"quantity": message.get("quantity"),
|
||||||
|
"trade_id": message.get("trade_id"),
|
||||||
|
"signal_id": message.get("signal_id"),
|
||||||
|
}
|
||||||
|
|
||||||
|
# 调用业务层
|
||||||
|
success = strategy_executor.process_trade_result(instance_id, trade_result)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
return {
|
||||||
|
"header": create_response_header(req_msg_id),
|
||||||
|
"msg_type": "ACK",
|
||||||
|
"status": "success",
|
||||||
|
"message": "Trade result processed",
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
return create_error_response(
|
||||||
|
"Failed to process trade result", "PROCESSING_ERROR", req_msg_id
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error handling trade result: {e}", exc_info=True)
|
||||||
|
return create_error_response(str(e), "PROCESSING_ERROR", req_msg_id)
|
||||||
|
|
||||||
|
|
||||||
|
async def handle_query_status(req_msg_id: str) -> dict:
|
||||||
|
"""
|
||||||
|
查询状态
|
||||||
|
|
||||||
|
Args:
|
||||||
|
req_msg_id: 请求消息ID
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
响应消息
|
||||||
|
"""
|
||||||
|
if not strategy_executor:
|
||||||
|
return create_error_response(
|
||||||
|
"Strategy executor not initialized", "SERVICE_NOT_READY", req_msg_id
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
status = strategy_executor.get_status()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"header": create_response_header(req_msg_id),
|
||||||
|
"msg_type": "STATUS",
|
||||||
|
"data": status,
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error querying status: {e}", exc_info=True)
|
||||||
|
return create_error_response(str(e), "PROCESSING_ERROR", req_msg_id)
|
||||||
|
|
||||||
|
|
||||||
|
def create_error_response(
|
||||||
|
error_message: str, error_code: str, req_msg_id: Optional[str] = None
|
||||||
|
) -> dict:
|
||||||
|
"""创建错误响应"""
|
||||||
|
return {
|
||||||
|
"header": create_response_header(req_msg_id),
|
||||||
|
"msg_type": "ERROR",
|
||||||
|
"error_code": error_code,
|
||||||
|
"error_message": error_message,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def start_server(
|
||||||
|
host: str = "0.0.0.0",
|
||||||
|
port: int = 8000,
|
||||||
|
config_path: str = "config/strategy_config.yaml",
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
启动策略服务器
|
||||||
|
|
||||||
|
Args:
|
||||||
|
host: 监听地址
|
||||||
|
port: 监听端口
|
||||||
|
config_path: 配置文件路径
|
||||||
|
"""
|
||||||
|
logger.info(f"Starting strategy server on {host}:{port}")
|
||||||
|
|
||||||
|
# 初始化服务
|
||||||
|
if not initialize_services(config_path):
|
||||||
|
logger.error("Failed to initialize services, server will not start")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 启动服务器
|
||||||
|
uvicorn.run(app, host=host, port=port, log_level="info")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# 开发模式:直接启动
|
||||||
|
start_server()
|
||||||
21
src/strategy_service/__init__.py
Normal file
21
src/strategy_service/__init__.py
Normal 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",
|
||||||
|
]
|
||||||
204
src/strategy_service/config_loader.py
Normal file
204
src/strategy_service/config_loader.py
Normal 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()
|
||||||
289
src/strategy_service/position_manager.py
Normal file
289
src/strategy_service/position_manager.py
Normal file
@ -0,0 +1,289 @@
|
|||||||
|
"""
|
||||||
|
持仓管理器 (Position Manager)
|
||||||
|
|
||||||
|
负责管理每个策略实例的持仓和资金
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Dict, Optional
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
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),
|
||||||
|
}
|
||||||
254
src/strategy_service/risk_manager.py
Normal file
254
src/strategy_service/risk_manager.py
Normal file
@ -0,0 +1,254 @@
|
|||||||
|
"""
|
||||||
|
风控管理器 (Risk Manager)
|
||||||
|
|
||||||
|
负责多层级风控检查
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Dict, Optional
|
||||||
|
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),
|
||||||
|
}
|
||||||
225
src/strategy_service/strategy_executor.py
Normal file
225
src/strategy_service/strategy_executor.py
Normal file
@ -0,0 +1,225 @@
|
|||||||
|
"""
|
||||||
|
策略执行器 (Strategy Executor)
|
||||||
|
|
||||||
|
负责执行策略并生成交易信号
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Dict, List, Optional
|
||||||
|
from datetime import datetime
|
||||||
|
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)
|
||||||
|
|
||||||
|
# 调用策略计算
|
||||||
|
# 假设策略有compute方法返回action, price, quantity
|
||||||
|
result = strategy_obj.compute(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 all([action, price, quantity, symbol]):
|
||||||
|
logger.error(f"Invalid trade result: {trade_result}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 更新持仓
|
||||||
|
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(),
|
||||||
|
}
|
||||||
207
src/strategy_service/strategy_manager.py
Normal file
207
src/strategy_service/strategy_manager.py
Normal file
@ -0,0 +1,207 @@
|
|||||||
|
"""
|
||||||
|
策略管理器 (Strategy Manager)
|
||||||
|
|
||||||
|
负责管理所有策略实例的创建、缓存和查询
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Dict, List, Tuple, Optional, Type
|
||||||
|
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
|
||||||
267
src/strategy_service/trade_recorder.py
Normal file
267
src/strategy_service/trade_recorder.py
Normal 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}")
|
||||||
Loading…
Reference in New Issue
Block a user