Long and Short with Multi Indicators Strategy
This strategy uses RSI, Rate of Change and a selectable moving average to generate long and short signals. It applies an ATR-based trailing stop for exits.
Details
- Entry Criteria:
- Long: RSI between oversold and overbought, ROC > 0 and price above MA.
- Short: Bearish trend confirmed, ROC < 0 and price below MA.
- Long/Short: Long and short.
- Exit Criteria:
- ATR-based trailing stop or indicator stop conditions.
- Stops: ATR trailing stop.
- Default Values:
RsiLength= 5RsiOverbought= 70RsiOversold= 44RocLength= 4MaLength= 24MaTypeParam= TEMAAtrLength= 14AtrMultiplier= 2BearishMaLength= 200BearishTrendDuration= 5
- Filters:
- Category: Trend following
- Direction: Long & Short
- Indicators: RSI, ROC, MA, ATR
- Stops: Yes
- Complexity: Medium
- Timeframe: Any
- Seasonality: No
- Neural networks: No
- Divergence: No
- Risk level: Medium
using System;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Long and Short strategy with RSI, ROC and EMA trend filter.
/// </summary>
public class LongAndShortWithMultiIndicatorsStrategy : Strategy
{
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<int> _rsiOverbought;
private readonly StrategyParam<int> _rsiOversold;
private readonly StrategyParam<int> _rocLength;
private readonly StrategyParam<int> _maLength;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _cooldownBars;
private RelativeStrengthIndex _rsi;
private RateOfChange _roc;
private ExponentialMovingAverage _ma;
private int _barsSinceSignal;
public int RsiLength { get => _rsiLength.Value; set => _rsiLength.Value = value; }
public int RsiOverbought { get => _rsiOverbought.Value; set => _rsiOverbought.Value = value; }
public int RsiOversold { get => _rsiOversold.Value; set => _rsiOversold.Value = value; }
public int RocLength { get => _rocLength.Value; set => _rocLength.Value = value; }
public int MaLength { get => _maLength.Value; set => _maLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int CooldownBars { get => _cooldownBars.Value; set => _cooldownBars.Value = value; }
public LongAndShortWithMultiIndicatorsStrategy()
{
_rsiLength = Param(nameof(RsiLength), 14)
.SetDisplay("RSI Length", "Length of RSI", "Indicators")
.SetGreaterThanZero();
_rsiOverbought = Param(nameof(RsiOverbought), 70)
.SetDisplay("RSI Overbought", "RSI overbought level", "Indicators");
_rsiOversold = Param(nameof(RsiOversold), 30)
.SetDisplay("RSI Oversold", "RSI oversold level", "Indicators");
_rocLength = Param(nameof(RocLength), 10)
.SetDisplay("ROC Length", "Length of ROC", "Indicators")
.SetGreaterThanZero();
_maLength = Param(nameof(MaLength), 20)
.SetDisplay("MA Length", "Length of moving average", "Indicators")
.SetGreaterThanZero();
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
_cooldownBars = Param(nameof(CooldownBars), 60)
.SetDisplay("Cooldown Bars", "Min bars between signals", "General");
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_rsi = null;
_roc = null;
_ma = null;
_barsSinceSignal = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_barsSinceSignal = 0;
_rsi = new RelativeStrengthIndex { Length = RsiLength };
_roc = new RateOfChange { Length = RocLength };
_ma = new ExponentialMovingAverage { Length = MaLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_rsi, _roc, _ma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _ma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal rsiVal, decimal rocVal, decimal maVal)
{
if (candle.State != CandleStates.Finished)
return;
_barsSinceSignal++;
if (!_rsi.IsFormed || !_roc.IsFormed || !_ma.IsFormed)
return;
if (_barsSinceSignal < CooldownBars)
return;
var close = candle.ClosePrice;
// Long: price above MA trend + RSI not overbought + positive momentum
var longSignal = close > maVal && rsiVal < RsiOverbought && rocVal > 0;
// Short: price below MA trend + RSI not oversold + negative momentum
var shortSignal = close < maVal && rsiVal > RsiOversold && rocVal < 0;
if (longSignal && Position <= 0)
{
BuyMarket(Volume + Math.Abs(Position));
_barsSinceSignal = 0;
}
else if (shortSignal && Position >= 0)
{
SellMarket(Volume + Math.Abs(Position));
_barsSinceSignal = 0;
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import RelativeStrengthIndex, RateOfChange, ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class long_and_short_with_multi_indicators_strategy(Strategy):
"""
Long/Short with RSI, ROC and EMA trend filter.
Long when price above MA + RSI not overbought + positive momentum.
"""
def __init__(self):
super(long_and_short_with_multi_indicators_strategy, self).__init__()
self._rsi_length = self.Param("RsiLength", 14) \
.SetDisplay("RSI Length", "Length of RSI", "Indicators")
self._rsi_overbought = self.Param("RsiOverbought", 70) \
.SetDisplay("RSI Overbought", "Overbought level", "Indicators")
self._rsi_oversold = self.Param("RsiOversold", 30) \
.SetDisplay("RSI Oversold", "Oversold level", "Indicators")
self._roc_length = self.Param("RocLength", 10) \
.SetDisplay("ROC Length", "Length of ROC", "Indicators")
self._ma_length = self.Param("MaLength", 20) \
.SetDisplay("MA Length", "Length of MA", "Indicators")
self._cooldown_bars = self.Param("CooldownBars", 60) \
.SetDisplay("Cooldown Bars", "Min bars between signals", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._bars_since_signal = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(long_and_short_with_multi_indicators_strategy, self).OnReseted()
self._bars_since_signal = 0
def OnStarted2(self, time):
super(long_and_short_with_multi_indicators_strategy, self).OnStarted2(time)
self._bars_since_signal = 0
self._rsi = RelativeStrengthIndex()
self._rsi.Length = self._rsi_length.Value
self._roc = RateOfChange()
self._roc.Length = self._roc_length.Value
self._ma = ExponentialMovingAverage()
self._ma.Length = self._ma_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._rsi, self._roc, self._ma, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._ma)
self.DrawOwnTrades(area)
def _process_candle(self, candle, rsi_val, roc_val, ma_val):
if candle.State != CandleStates.Finished:
return
self._bars_since_signal += 1
if not self._rsi.IsFormed or not self._roc.IsFormed or not self._ma.IsFormed:
return
if self._bars_since_signal < self._cooldown_bars.Value:
return
close = float(candle.ClosePrice)
rsi = float(rsi_val)
roc = float(roc_val)
ma = float(ma_val)
long_signal = close > ma and rsi < self._rsi_overbought.Value and roc > 0
short_signal = close < ma and rsi > self._rsi_oversold.Value and roc < 0
if long_signal and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
self._bars_since_signal = 0
elif short_signal and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
self._bars_since_signal = 0
def CreateClone(self):
return long_and_short_with_multi_indicators_strategy()