在 GitHub 上查看

RSI Hull MA Strategy

此策略结合RSI与Hull移动平均线。当RSI低于30且HMA上升时做多;当RSI高于70且HMA下降时做空,分别对应超卖和超买状态。

测试表明年均收益约为 58%,该策略在股票市场表现最佳。

适合在混合市场中寻找机会的交易者。

细节

  • 入场条件:
    • 多头: RSI < 30 && HMA(t) > HMA(t-1)
    • 空头: RSI > 70 && HMA(t) < HMA(t-1)
  • 多/空: 双向
  • 离场条件:
    • 多头: RSI回到中性区域时平仓
    • 空头: RSI回到中性区域时平仓
  • 止损: 是
  • 默认值:
    • RsiPeriod = 14
    • HullPeriod = 9
    • AtrPeriod = 14
    • AtrMultiplier = 2m
    • CandleType = TimeSpan.FromMinutes(5)
  • 过滤器:
    • 类别: Mixed
    • 方向: 双向
    • 指标: RSI Hull MA
    • 止损: 是
    • 复杂度: 中等
    • 时间框架: 日内
    • 季节性: 否
    • 神经网络: 否
    • 背离: 否
    • 风险等级: 中等
using System;
using System.Linq;
using System.Collections.Generic;

using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;

using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Strategy based on RSI and Hull Moving Average indicators
/// </summary>
public class RsiHullMaStrategy : Strategy
{
	private readonly StrategyParam<int> _rsiPeriod;
	private readonly StrategyParam<int> _hullPeriod;
	private readonly StrategyParam<int> _cooldownBars;
	private readonly StrategyParam<int> _atrPeriod;
	private readonly StrategyParam<decimal> _atrMultiplier;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _previousHullValue;
	private decimal _previousRsiValue;
	private int _cooldown;

	/// <summary>
	/// RSI period
	/// </summary>
	public int RsiPeriod
	{
		get => _rsiPeriod.Value;
		set => _rsiPeriod.Value = value;
	}

	/// <summary>
	/// Hull MA period
	/// </summary>
	public int HullPeriod
	{
		get => _hullPeriod.Value;
		set => _hullPeriod.Value = value;
	}

	/// <summary>
	/// Bars to wait between trades.
	/// </summary>
	public int CooldownBars
	{
		get => _cooldownBars.Value;
		set => _cooldownBars.Value = value;
	}

	/// <summary>
	/// ATR period for stop-loss
	/// </summary>
	public int AtrPeriod
	{
		get => _atrPeriod.Value;
		set => _atrPeriod.Value = value;
	}

	/// <summary>
	/// ATR multiplier for stop-loss
	/// </summary>
	public decimal AtrMultiplier
	{
		get => _atrMultiplier.Value;
		set => _atrMultiplier.Value = value;
	}

	/// <summary>
	/// Candle type for strategy
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Constructor
	/// </summary>
	public RsiHullMaStrategy()
	{
		_rsiPeriod = Param(nameof(RsiPeriod), 14)
			.SetRange(5, 30)
			.SetDisplay("RSI Period", "Period for RSI indicator", "Indicators")
			;

		_hullPeriod = Param(nameof(HullPeriod), 9)
			.SetRange(5, 20)
			.SetDisplay("Hull MA Period", "Period for Hull Moving Average", "Indicators")
			;

		_cooldownBars = Param(nameof(CooldownBars), 30)
			.SetRange(1, 200)
			.SetDisplay("Cooldown Bars", "Bars between trades", "General");

		_atrPeriod = Param(nameof(AtrPeriod), 14)
			.SetRange(7, 28)
			.SetDisplay("ATR Period", "ATR period for stop-loss calculation", "Risk Management")
			;

		_atrMultiplier = Param(nameof(AtrMultiplier), 2m)
			.SetRange(1m, 4m)
			.SetDisplay("ATR Multiplier", "Multiplier for ATR-based stop-loss", "Risk Management")
			;

		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles to use", "General");
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		return [(Security, CandleType)];
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();

		_previousHullValue = default;
		_previousRsiValue = 50m;
		_cooldown = 0;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		// Initialize indicators
		var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
		var hullMA = new ExponentialMovingAverage { Length = HullPeriod };
		var atr = new AverageTrueRange { Length = AtrPeriod };

		// Create subscription and bind indicators
		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(rsi, hullMA, atr, ProcessIndicators)
			.Start();
		
		// Setup chart visualization if available
		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, rsi);
			DrawIndicator(area, hullMA);
			DrawOwnTrades(area);
		}
	}

	private void ProcessIndicators(ICandleMessage candle, decimal rsiValue, decimal hullValue, decimal atrValue)
	{
		// Skip unfinished candles
		if (candle.State != CandleStates.Finished)
			return;

		// Check if strategy is ready to trade
		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		// Store previous Hull value for slope detection
		var previousHullValue = _previousHullValue;
		_previousHullValue = hullValue;
		var previousRsiValue = _previousRsiValue;
		_previousRsiValue = rsiValue;

		// Skip first candle until we have previous value
		if (previousHullValue == 0)
			return;

		// Trading logic:
		// Long: RSI < 30 && HMA(t) > HMA(t-1) (oversold with rising HMA)
		// Short: RSI > 70 && HMA(t) < HMA(t-1) (overbought with falling HMA)
		
		var hullSlope = hullValue > previousHullValue;
		var crossedBelowThreshold = previousRsiValue >= 45m && rsiValue < 45m;
		var crossedAboveThreshold = previousRsiValue <= 55m && rsiValue > 55m;

		if (_cooldown > 0)
			_cooldown--;

		if (_cooldown == 0 && crossedBelowThreshold && hullSlope && Position <= 0)
		{
			var volume = Volume + Math.Abs(Position);
			BuyMarket(volume);
			_cooldown = CooldownBars;
		}
		else if (_cooldown == 0 && crossedAboveThreshold && !hullSlope && Position >= 0)
		{
			var volume = Volume + Math.Abs(Position);
			SellMarket(volume);
			_cooldown = CooldownBars;
		}
		// Exit conditions
		else if (Position > 0 && (rsiValue > 52m || !hullSlope))
		{
			SellMarket(Position);
			_cooldown = CooldownBars;
		}
		else if (Position < 0 && (rsiValue < 48m || hullSlope))
		{
			BuyMarket(Math.Abs(Position));
			_cooldown = CooldownBars;
		}
	}
}