Ver en GitHub

RSI Hull MA Strategy

This strategy uses RSI Hull MA indicators to generate signals. Long entry occurs when RSI < 30 && HMA(t) > HMA(t-1) (oversold with rising HMA). Short entry occurs when RSI > 70 && HMA(t) < HMA(t-1) (overbought with falling HMA). It is suitable for traders seeking opportunities in mixed markets.

Testing indicates an average annual return of about 58%. It performs best in the stocks market.

Details

  • Entry Criteria:
    • Long: RSI < 30 && HMA(t) > HMA(t-1) (oversold with rising HMA)
    • Short: RSI > 70 && HMA(t) < HMA(t-1) (overbought with falling HMA)
  • Long/Short: Both sides.
  • Exit Criteria:
    • Long: Exit long position when RSI returns to neutral zone
    • Short: Exit short position when RSI returns to neutral zone
  • Stops: Yes.
  • Default Values:
    • RsiPeriod = 14
    • HullPeriod = 9
    • AtrPeriod = 14
    • AtrMultiplier = 2m
    • CandleType = TimeSpan.FromMinutes(5)
  • Filters:
    • Category: Mixed
    • Direction: Both
    • Indicators: RSI Hull MA
    • Stops: Yes
    • Complexity: Intermediate
    • Timeframe: Intraday
    • Seasonality: No
    • Neural networks: No
    • Divergence: No
    • Risk Level: Medium
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;
		}
	}
}