iD EMARSI on Chart Strategy
This strategy trades crossovers between the RSI plotted on the price chart and its exponential moving average. A long position opens when the RSI crosses above the EMA, and a short position opens on the opposite crossover. Signals can be filtered by minimum trend duration and positions are protected with optional take profit and trailing stop in percent.
Parameters
- Candle Type
- RSI Length
- EMA Length
- Min Trend Bars
- Use Filtered Signals
- Take Profit %
- Trailing Stop %
namespace StockSharp.Samples.Strategies;
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
/// <summary>
/// RSI with EMA crossover strategy.
/// Enters when RSI crosses its own EMA.
/// </summary>
public class IdEmarsiOnChartStrategy : Strategy
{
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<int> _emaLength;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevRsi;
private decimal _prevEma;
private bool _isInitialized;
public int RsiLength { get => _rsiLength.Value; set => _rsiLength.Value = value; }
public int EmaLength { get => _emaLength.Value; set => _emaLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
public IdEmarsiOnChartStrategy()
{
_rsiLength = Param(nameof(RsiLength), 16)
.SetDisplay("RSI Length", "RSI length", "General");
_emaLength = Param(nameof(EmaLength), 42)
.SetDisplay("EMA Length", "EMA of RSI length", "General");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Candle type", "General");
}
protected override void OnReseted()
{
base.OnReseted();
_prevRsi = 0;
_prevEma = 0;
_isInitialized = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var rsi = new RelativeStrengthIndex { Length = RsiLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(rsi, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal rsiValue)
{
if (candle.State != CandleStates.Finished)
return;
// Calculate EMA of RSI manually (exponential smoothing)
var alpha = 2m / (EmaLength + 1m);
var emaValue = !_isInitialized ? rsiValue : _prevEma * (1 - alpha) + rsiValue * alpha;
if (!_isInitialized)
{
_prevRsi = rsiValue;
_prevEma = emaValue;
_isInitialized = true;
return;
}
var crossUp = _prevRsi <= _prevEma && rsiValue > emaValue;
var crossDown = _prevRsi >= _prevEma && rsiValue < emaValue;
if (crossUp && Position <= 0)
BuyMarket();
else if (crossDown && Position >= 0)
SellMarket();
_prevRsi = rsiValue;
_prevEma = emaValue;
}
}
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
from StockSharp.Algo.Strategies import Strategy
class id_emarsi_on_chart_strategy(Strategy):
"""
RSI with EMA crossover strategy. Enters when RSI crosses
its own EMA (calculated manually via exponential smoothing).
"""
def __init__(self):
super(id_emarsi_on_chart_strategy, self).__init__()
self._rsi_length = self.Param("RsiLength", 16) \
.SetDisplay("RSI Length", "RSI length", "General")
self._ema_length = self.Param("EmaLength", 42) \
.SetDisplay("EMA Length", "EMA of RSI length", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Candle type", "General")
self._prev_rsi = 0.0
self._prev_ema = 0.0
self._is_initialized = False
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(id_emarsi_on_chart_strategy, self).OnReseted()
self._prev_rsi = 0.0
self._prev_ema = 0.0
self._is_initialized = False
def OnStarted2(self, time):
super(id_emarsi_on_chart_strategy, self).OnStarted2(time)
rsi = RelativeStrengthIndex()
rsi.Length = self._rsi_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(rsi, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def _process_candle(self, candle, rsi_val):
if candle.State != CandleStates.Finished:
return
rsi = float(rsi_val)
alpha = 2.0 / (self._ema_length.Value + 1.0)
if not self._is_initialized:
ema = rsi
else:
ema = self._prev_ema * (1.0 - alpha) + rsi * alpha
if not self._is_initialized:
self._prev_rsi = rsi
self._prev_ema = ema
self._is_initialized = True
return
cross_up = self._prev_rsi <= self._prev_ema and rsi > ema
cross_down = self._prev_rsi >= self._prev_ema and rsi < ema
if cross_up and self.Position <= 0:
self.BuyMarket()
elif cross_down and self.Position >= 0:
self.SellMarket()
self._prev_rsi = rsi
self._prev_ema = ema
def CreateClone(self):
return id_emarsi_on_chart_strategy()