Стратегия RSI Hull MA
Стратегия использует индикаторы RSI и Hull Moving Average. Длинная позиция открывается при RSI ниже 30 и растущей HMA, то есть HMA(t) > HMA(t‑1). Короткая позиция формируется, когда RSI выше 70 и HMA(t) < HMA(t‑1), что указывает на перекупленность при падающей HMA.
Тестирование показывает среднегодичную доходность около 58%. Стратегию лучше запускать на фондовом рынке.
Подходит трейдерам, ищущим возможности в смешанном рынке.
Детали
- Условия входа:
- Лонг: RSI < 30 и HMA(t) > HMA(t-1) (перепроданность и рост HMA)
- Шорт: RSI > 70 и HMA(t) < HMA(t-1) (перекупленность и падение HMA)
- Лонг/Шорт: обе стороны.
- Условия выхода:
- Лонг: Закрыть длинную позицию при возвращении RSI в нейтральную зону
- Шорт: Закрыть короткую позицию при возвращении RSI в нейтральную зону
- Стопы: да.
- Значения по умолчанию:
RsiPeriod= 14HullPeriod= 9AtrPeriod= 14AtrMultiplier= 2mCandleType= TimeSpan.FromMinutes(5)
- Фильтры:
- Категория: Смешанная
- Направление: Оба
- Индикаторы: 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;
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import RelativeStrengthIndex, ExponentialMovingAverage, AverageTrueRange
from StockSharp.Algo.Strategies import Strategy
from datatype_extensions import *
class rsi_hull_ma_strategy(Strategy):
"""
Strategy based on RSI and Hull Moving Average indicators
"""
def __init__(self):
super(rsi_hull_ma_strategy, self).__init__()
self._rsi_period = self.Param("RsiPeriod", 14) \
.SetRange(5, 30) \
.SetDisplay("RSI Period", "Period for RSI indicator", "Indicators")
self._hull_period = self.Param("HullPeriod", 9) \
.SetRange(5, 20) \
.SetDisplay("Hull MA Period", "Period for Hull Moving Average", "Indicators")
self._cooldown_bars = self.Param("CooldownBars", 30) \
.SetRange(1, 200) \
.SetDisplay("Cooldown Bars", "Bars between trades", "General")
self._atr_period = self.Param("AtrPeriod", 14) \
.SetRange(7, 28) \
.SetDisplay("ATR Period", "ATR period for stop-loss calculation", "Risk Management")
self._atr_multiplier = self.Param("AtrMultiplier", 2.0) \
.SetRange(1.0, 4.0) \
.SetDisplay("ATR Multiplier", "Multiplier for ATR-based stop-loss", "Risk Management")
self._candle_type = self.Param("CandleType", tf(30)) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._previous_hull_value = 0.0
self._previous_rsi_value = 50.0
self._cooldown = 0
@property
def CandleType(self):
return self._candle_type.Value
def OnReseted(self):
super(rsi_hull_ma_strategy, self).OnReseted()
self._previous_hull_value = 0.0
self._previous_rsi_value = 50.0
self._cooldown = 0
def OnStarted2(self, time):
super(rsi_hull_ma_strategy, self).OnStarted2(time)
self._previous_hull_value = 0.0
self._previous_rsi_value = 50.0
self._cooldown = 0
rsi = RelativeStrengthIndex()
rsi.Length = self._rsi_period.Value
hull_ma = ExponentialMovingAverage()
hull_ma.Length = self._hull_period.Value
atr = AverageTrueRange()
atr.Length = self._atr_period.Value
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(rsi, hull_ma, atr, self.ProcessIndicators).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, rsi)
self.DrawIndicator(area, hull_ma)
self.DrawOwnTrades(area)
def ProcessIndicators(self, candle, rsi_value, hull_value, atr_value):
if candle.State != CandleStates.Finished:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
previous_hull = self._previous_hull_value
self._previous_hull_value = float(hull_value)
previous_rsi = self._previous_rsi_value
self._previous_rsi_value = float(rsi_value)
if previous_hull == 0:
return
hull_slope = float(hull_value) > previous_hull
crossed_below = previous_rsi >= 45 and float(rsi_value) < 45
crossed_above = previous_rsi <= 55 and float(rsi_value) > 55
if self._cooldown > 0:
self._cooldown -= 1
cooldown_val = int(self._cooldown_bars.Value)
if self._cooldown == 0 and crossed_below and hull_slope and self.Position <= 0:
volume = self.Volume + abs(self.Position)
self.BuyMarket(volume)
self._cooldown = cooldown_val
elif self._cooldown == 0 and crossed_above and not hull_slope and self.Position >= 0:
volume = self.Volume + abs(self.Position)
self.SellMarket(volume)
self._cooldown = cooldown_val
elif self.Position > 0 and (float(rsi_value) > 52 or not hull_slope):
self.SellMarket(self.Position)
self._cooldown = cooldown_val
elif self.Position < 0 and (float(rsi_value) < 48 or hull_slope):
self.BuyMarket(abs(self.Position))
self._cooldown = cooldown_val
def CreateClone(self):
return rsi_hull_ma_strategy()