QTrade/strategies/simple_ma_strategy.py

104 lines
3.3 KiB
Python
Raw Normal View History

"""
示例策略:简单移动平均线交叉策略
这是一个简单的示例策略,展示如何使用策略框架。
策略逻辑:
- 当短期均线上穿长期均线时,买入
- 当短期均线下穿长期均线时,卖出
"""
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()