107 lines
2.5 KiB
Python
107 lines
2.5 KiB
Python
|
|
"""
|
|||
|
|
策略基类 (BaseStrategy)
|
|||
|
|
|
|||
|
|
所有策略必须继承此基类
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
from abc import ABC, abstractmethod
|
|||
|
|
from typing import Dict, Any, Optional
|
|||
|
|
import logging
|
|||
|
|
|
|||
|
|
from src.core.strategy_context import StrategyContext
|
|||
|
|
|
|||
|
|
logger = logging.getLogger(__name__)
|
|||
|
|
|
|||
|
|
|
|||
|
|
class BaseStrategy(ABC):
|
|||
|
|
"""
|
|||
|
|
策略基类
|
|||
|
|
|
|||
|
|
所有策略都应该继承此类并实现 compute 方法
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
def __init__(self, context: StrategyContext, **params):
|
|||
|
|
"""
|
|||
|
|
初始化策略
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
context: 策略上下文
|
|||
|
|
**params: 策略参数
|
|||
|
|
"""
|
|||
|
|
self.context: StrategyContext = context
|
|||
|
|
self.params: Dict[str, Any] = params
|
|||
|
|
|
|||
|
|
logger.info(
|
|||
|
|
f"Strategy initialized: instance_id={context.instance_id}, "
|
|||
|
|
f"symbol={context.symbol}, params={params}"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
@abstractmethod
|
|||
|
|
def compute(self, kline_data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|||
|
|
"""
|
|||
|
|
计算信号(必须实现)
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
kline_data: K线数据字典
|
|||
|
|
{
|
|||
|
|
'symbol': str,
|
|||
|
|
'timestamp': str,
|
|||
|
|
'open': float,
|
|||
|
|
'high': float,
|
|||
|
|
'low': float,
|
|||
|
|
'close': float,
|
|||
|
|
'volume': float
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
信号字典或None
|
|||
|
|
{
|
|||
|
|
'action': 'BUY' | 'SELL' | 'HOLD',
|
|||
|
|
'symbol': str,
|
|||
|
|
'price': float,
|
|||
|
|
'quantity': int,
|
|||
|
|
'reason': str # 可选
|
|||
|
|
}
|
|||
|
|
"""
|
|||
|
|
pass
|
|||
|
|
|
|||
|
|
def on_init(self):
|
|||
|
|
"""
|
|||
|
|
初始化回调(可选实现)
|
|||
|
|
|
|||
|
|
在策略加载完成后调用,可以在这里做一些初始化工作
|
|||
|
|
"""
|
|||
|
|
pass
|
|||
|
|
|
|||
|
|
def on_trade(self, trade_result: Dict[str, Any]):
|
|||
|
|
"""
|
|||
|
|
交易回调(可选实现)
|
|||
|
|
|
|||
|
|
在交易执行后调用
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
trade_result: 交易结果
|
|||
|
|
{
|
|||
|
|
'action': str,
|
|||
|
|
'symbol': str,
|
|||
|
|
'price': float,
|
|||
|
|
'quantity': int,
|
|||
|
|
'success': bool,
|
|||
|
|
'message': str
|
|||
|
|
}
|
|||
|
|
"""
|
|||
|
|
pass
|
|||
|
|
|
|||
|
|
def on_error(self, error: Exception):
|
|||
|
|
"""
|
|||
|
|
错误回调(可选实现)
|
|||
|
|
|
|||
|
|
在策略执行出错时调用
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
error: 异常对象
|
|||
|
|
"""
|
|||
|
|
logger.error(
|
|||
|
|
f"Strategy error in {self.context.instance_id}: {error}", exc_info=True
|
|||
|
|
)
|