237 lines
7.0 KiB
Python
237 lines
7.0 KiB
Python
"""
|
||
策略执行器 (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(),
|
||
}
|