375 lines
11 KiB
Python
375 lines
11 KiB
Python
|
|
"""
|
|||
|
|
策略服务器 (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()
|