Kaito Box with RSI Div Strategy
The strategy buys when price breaks below the recent box range with bullish RSI divergence in a downtrend and exits when bearish divergence appears in an uptrend.
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Box breakout strategy with RSI and MA200 filters.
/// </summary>
public class KaitoBoxWithRsiDivStrategy : Strategy
{
private readonly StrategyParam<int> _boxLength;
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<int> _maPeriod;
private readonly StrategyParam<int> _maxEntries;
private readonly StrategyParam<int> _holdBars;
private readonly StrategyParam<int> _cooldownBars;
private readonly StrategyParam<DataType> _candleType;
private int _entriesExecuted;
private int _barsInPosition;
private int _barsSinceSignal;
/// <summary>
/// Length of the box range.
/// </summary>
public int BoxLength
{
get => _boxLength.Value;
set => _boxLength.Value = value;
}
/// <summary>
/// Length of RSI indicator.
/// </summary>
public int RsiLength
{
get => _rsiLength.Value;
set => _rsiLength.Value = value;
}
/// <summary>
/// Period for long trend filter.
/// </summary>
public int MaPeriod
{
get => _maPeriod.Value;
set => _maPeriod.Value = value;
}
/// <summary>
/// Maximum number of entries per run.
/// </summary>
public int MaxEntries
{
get => _maxEntries.Value;
set => _maxEntries.Value = value;
}
/// <summary>
/// Maximum holding period in finished candles.
/// </summary>
public int HoldBars
{
get => _holdBars.Value;
set => _holdBars.Value = value;
}
/// <summary>
/// Minimum bars between entries.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// Candle type used by the strategy.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes a new instance of the strategy.
/// </summary>
public KaitoBoxWithRsiDivStrategy()
{
_boxLength = Param(nameof(BoxLength), 20)
.SetGreaterThanZero()
.SetDisplay("Box Length", "Length of the box range", "General");
_rsiLength = Param(nameof(RsiLength), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Length", "Length of RSI", "General");
_maPeriod = Param(nameof(MaPeriod), 200)
.SetGreaterThanZero()
.SetDisplay("MA Period", "Trend moving average period", "Trend");
_maxEntries = Param(nameof(MaxEntries), 45)
.SetGreaterThanZero()
.SetDisplay("Max Entries", "Maximum entries per run", "Risk");
_holdBars = Param(nameof(HoldBars), 240)
.SetGreaterThanZero()
.SetDisplay("Hold Bars", "Bars to hold position before forced exit", "Risk");
_cooldownBars = Param(nameof(CooldownBars), 240)
.SetGreaterThanZero()
.SetDisplay("Cooldown Bars", "Minimum bars between entries", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(3).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_entriesExecuted = 0;
_barsInPosition = 0;
_barsSinceSignal = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var highest = new Highest { Length = BoxLength };
var lowest = new Lowest { Length = BoxLength };
var rsi = new RelativeStrengthIndex { Length = RsiLength };
var ma = new SimpleMovingAverage { Length = MaPeriod };
_entriesExecuted = 0;
_barsInPosition = 0;
_barsSinceSignal = CooldownBars;
var subscription = SubscribeCandles(CandleType);
subscription.Bind(highest, lowest, rsi, ma, ProcessCandle).Start();
}
private void ProcessCandle(ICandleMessage candle, decimal highestHigh, decimal lowestLow, decimal rsiValue, decimal maValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (Position != 0)
{
_barsInPosition++;
if (_barsInPosition >= HoldBars)
{
if (Position > 0)
SellMarket(Math.Abs(Position));
else
BuyMarket(Math.Abs(Position));
_barsInPosition = 0;
_barsSinceSignal = 0;
}
return;
}
_barsInPosition = 0;
_barsSinceSignal++;
if (_entriesExecuted >= MaxEntries || _barsSinceSignal < CooldownBars)
return;
var longSignal = candle.HighPrice >= highestHigh && rsiValue > 55m && candle.ClosePrice > maValue;
var shortSignal = candle.LowPrice <= lowestLow && rsiValue < 45m && candle.ClosePrice < maValue;
if (longSignal)
{
BuyMarket();
_entriesExecuted++;
_barsSinceSignal = 0;
}
else if (shortSignal)
{
SellMarket();
_entriesExecuted++;
_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 Highest, Lowest, RelativeStrengthIndex, SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class kaito_box_with_rsi_div_strategy(Strategy):
def __init__(self):
super(kaito_box_with_rsi_div_strategy, self).__init__()
self._box_length = self.Param("BoxLength", 20) \
.SetGreaterThanZero() \
.SetDisplay("Box Length", "Length of the box range", "General")
self._rsi_length = self.Param("RsiLength", 14) \
.SetGreaterThanZero() \
.SetDisplay("RSI Length", "Length of RSI", "General")
self._ma_period = self.Param("MaPeriod", 200) \
.SetGreaterThanZero() \
.SetDisplay("MA Period", "Trend moving average period", "Trend")
self._hold_bars = self.Param("HoldBars", 240) \
.SetGreaterThanZero() \
.SetDisplay("Hold Bars", "Bars to hold position before forced exit", "Risk")
self._cooldown_bars = self.Param("CooldownBars", 240) \
.SetGreaterThanZero() \
.SetDisplay("Cooldown Bars", "Minimum bars between entries", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(3))) \
.SetDisplay("Candle Type", "Timeframe for candles", "General")
self._bars_in_position = 0
self._bars_since_signal = 0
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
def OnReseted(self):
super(kaito_box_with_rsi_div_strategy, self).OnReseted()
self._bars_in_position = 0
self._bars_since_signal = 0
def OnStarted2(self, time):
super(kaito_box_with_rsi_div_strategy, self).OnStarted2(time)
highest = Highest()
highest.Length = self._box_length.Value
lowest = Lowest()
lowest.Length = self._box_length.Value
rsi = RelativeStrengthIndex()
rsi.Length = self._rsi_length.Value
ma = SimpleMovingAverage()
ma.Length = self._ma_period.Value
self._bars_since_signal = self._cooldown_bars.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(highest, lowest, rsi, ma, self.OnProcess).Start()
def OnProcess(self, candle, highest_val, lowest_val, rsi_val, ma_val):
if candle.State != CandleStates.Finished:
return
h_val = float(highest_val)
l_val = float(lowest_val)
rsi_v = float(rsi_val)
ma_v = float(ma_val)
close = float(candle.ClosePrice)
high = float(candle.HighPrice)
low = float(candle.LowPrice)
hold = self._hold_bars.Value
cd = self._cooldown_bars.Value
if self.Position != 0:
self._bars_in_position += 1
if self._bars_in_position >= hold:
if self.Position > 0:
self.SellMarket()
else:
self.BuyMarket()
self._bars_in_position = 0
self._bars_since_signal = 0
return
self._bars_in_position = 0
self._bars_since_signal += 1
if self._bars_since_signal < cd:
return
long_signal = high >= h_val and rsi_v > 55 and close > ma_v
short_signal = low <= l_val and rsi_v < 45 and close < ma_v
if long_signal:
self.BuyMarket()
self._bars_since_signal = 0
elif short_signal:
self.SellMarket()
self._bars_since_signal = 0
def CreateClone(self):
return kaito_box_with_rsi_div_strategy()