BB RSI Trailing Stop Strategy
Combines Bollinger Bands with RSI momentum and protects trades with a conditional trailing stop. Longs occur when price pierces the lower band and RSI exits oversold. Shorts trigger on the upper band with overbought RSI.
The stop-loss starts at a fixed distance and converts to a trailing stop once price moves favorably by a preset offset.
Details
- Entry Criteria: Bollinger Band breakout with RSI confirmation
- Long/Short: Both
- Exit Criteria: Initial stop-loss or trailing stop
- Stops: Yes, dynamic trailing
- Default Values:
BollingerPeriod= 25BollingerDeviation= 2RsiPeriod= 14RsiOverbought= 60RsiOversold= 33StopLossPoints= 50TrailOffsetPoints= 99TrailStopPoints= 40
- Filters:
- Category: Mean reversion
- Direction: Both
- Indicators: Bollinger Bands, RSI
- Stops: Trailing
- 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>
/// Bollinger Bands and RSI strategy with conditional trailing stop.
/// </summary>
public class BbRsiTrailingStopStrategy : Strategy
{
private readonly StrategyParam<int> _bollingerPeriod;
private readonly StrategyParam<decimal> _bollingerDeviation;
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<decimal> _rsiOverbought;
private readonly StrategyParam<decimal> _rsiOversold;
private readonly StrategyParam<decimal> _stopLossPoints;
private readonly StrategyParam<decimal> _trailOffsetPoints;
private readonly StrategyParam<decimal> _trailStopPoints;
private readonly StrategyParam<DataType> _candleType;
private decimal _entryPrice;
private decimal _stopPrice;
private decimal _trailingPrice;
private bool _trailingActive;
private int _cooldown;
/// <summary>
/// Bollinger Bands period.
/// </summary>
public int BollingerPeriod
{
get => _bollingerPeriod.Value;
set => _bollingerPeriod.Value = value;
}
/// <summary>
/// Bollinger Bands deviation multiplier.
/// </summary>
public decimal BollingerDeviation
{
get => _bollingerDeviation.Value;
set => _bollingerDeviation.Value = value;
}
/// <summary>
/// RSI calculation period.
/// </summary>
public int RsiPeriod
{
get => _rsiPeriod.Value;
set => _rsiPeriod.Value = value;
}
/// <summary>
/// RSI overbought level.
/// </summary>
public decimal RsiOverbought
{
get => _rsiOverbought.Value;
set => _rsiOverbought.Value = value;
}
/// <summary>
/// RSI oversold level.
/// </summary>
public decimal RsiOversold
{
get => _rsiOversold.Value;
set => _rsiOversold.Value = value;
}
/// <summary>
/// Initial stop loss in price points.
/// </summary>
public decimal StopLossPoints
{
get => _stopLossPoints.Value;
set => _stopLossPoints.Value = value;
}
/// <summary>
/// Profit required to activate trailing stop.
/// </summary>
public decimal TrailOffsetPoints
{
get => _trailOffsetPoints.Value;
set => _trailOffsetPoints.Value = value;
}
/// <summary>
/// Trailing stop distance in price points.
/// </summary>
public decimal TrailStopPoints
{
get => _trailStopPoints.Value;
set => _trailStopPoints.Value = value;
}
/// <summary>
/// Candle type for strategy calculation.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes strategy parameters.
/// </summary>
public BbRsiTrailingStopStrategy()
{
_bollingerPeriod = Param(nameof(BollingerPeriod), 40)
.SetDisplay("Bollinger Period", "Period for Bollinger Bands", "Indicators")
.SetOptimize(10, 50, 5);
_bollingerDeviation = Param(nameof(BollingerDeviation), 2.5m)
.SetDisplay("Bollinger Deviation", "Deviation multiplier", "Indicators")
.SetOptimize(1m, 3m, 0.5m);
_rsiPeriod = Param(nameof(RsiPeriod), 14)
.SetDisplay("RSI Period", "RSI calculation period", "Indicators")
.SetOptimize(7, 21, 7);
_rsiOverbought = Param(nameof(RsiOverbought), 70m)
.SetDisplay("RSI Overbought", "Overbought level", "Indicators")
.SetOptimize(50m, 80m, 5m);
_rsiOversold = Param(nameof(RsiOversold), 30m)
.SetDisplay("RSI Oversold", "Oversold level", "Indicators")
.SetOptimize(20m, 40m, 5m);
_stopLossPoints = Param(nameof(StopLossPoints), 3000m)
.SetDisplay("Stop Loss Points", "Initial stop loss in points", "Risk Management")
.SetOptimize(20m, 100m, 10m);
_trailOffsetPoints = Param(nameof(TrailOffsetPoints), 2000m)
.SetDisplay("Trail Offset Points", "Profit to activate trailing stop", "Risk Management")
.SetOptimize(50m, 150m, 10m);
_trailStopPoints = Param(nameof(TrailStopPoints), 1500m)
.SetDisplay("Trail Stop Points", "Trailing stop distance", "Risk Management")
.SetOptimize(20m, 80m, 10m);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).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();
_entryPrice = 0;
_stopPrice = 0;
_trailingPrice = 0;
_trailingActive = false;
_cooldown = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var bollinger = new BollingerBands
{
Length = BollingerPeriod,
Width = BollingerDeviation
};
var rsi = new RelativeStrengthIndex
{
Length = RsiPeriod
};
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(bollinger, rsi, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, bollinger);
DrawIndicator(area, rsi);
DrawOwnTrades(area);
}
}
private void ResetStops()
{
_entryPrice = 0;
_stopPrice = 0;
_trailingPrice = 0;
_trailingActive = false;
_cooldown = 100;
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue bollingerValue, IIndicatorValue rsiValue)
{
if (candle.State != CandleStates.Finished)
return;
if (bollingerValue is not BollingerBandsValue bb ||
bb.UpBand is not decimal upper ||
bb.LowBand is not decimal lower ||
!rsiValue.IsFormed)
return;
var rsi = rsiValue.GetValue<decimal>();
if (_cooldown > 0)
_cooldown--;
if (Position == 0 && _cooldown == 0)
{
if (candle.LowPrice < lower && rsi < RsiOversold)
{
BuyMarket();
_entryPrice = candle.ClosePrice;
_stopPrice = _entryPrice - StopLossPoints;
_cooldown = 100;
}
else if (candle.HighPrice > upper && rsi > RsiOverbought)
{
SellMarket();
_entryPrice = candle.ClosePrice;
_stopPrice = _entryPrice + StopLossPoints;
_cooldown = 100;
}
}
else if (Position > 0)
{
if (!_trailingActive && candle.ClosePrice - _entryPrice >= TrailOffsetPoints)
{
_trailingActive = true;
_trailingPrice = candle.ClosePrice - TrailStopPoints;
}
if (_trailingActive)
{
var newLevel = candle.ClosePrice - TrailStopPoints;
if (newLevel > _trailingPrice)
_trailingPrice = newLevel;
}
// Exit on stop or trailing stop
if (candle.LowPrice <= _stopPrice || (_trailingActive && candle.LowPrice <= _trailingPrice))
{
SellMarket();
ResetStops();
}
}
else
{
if (!_trailingActive && _entryPrice - candle.ClosePrice >= TrailOffsetPoints)
{
_trailingActive = true;
_trailingPrice = candle.ClosePrice + TrailStopPoints;
}
if (_trailingActive)
{
var newLevel = candle.ClosePrice + TrailStopPoints;
if (newLevel < _trailingPrice || _trailingPrice == 0)
_trailingPrice = newLevel;
}
// Exit on stop or trailing stop
if (candle.HighPrice >= _stopPrice || (_trailingActive && candle.HighPrice >= _trailingPrice))
{
BuyMarket();
ResetStops();
}
}
}
}
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 BollingerBands, RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class bb_rsi_trailing_stop_strategy(Strategy):
def __init__(self):
super(bb_rsi_trailing_stop_strategy, self).__init__()
self._bollinger_period = self.Param("BollingerPeriod", 40) \
.SetDisplay("Bollinger Period", "Period for Bollinger Bands", "Indicators")
self._bollinger_deviation = self.Param("BollingerDeviation", 2.5) \
.SetDisplay("Bollinger Deviation", "Deviation multiplier", "Indicators")
self._rsi_period = self.Param("RsiPeriod", 14) \
.SetDisplay("RSI Period", "RSI calculation period", "Indicators")
self._rsi_overbought = self.Param("RsiOverbought", 70.0) \
.SetDisplay("RSI Overbought", "Overbought level", "Indicators")
self._rsi_oversold = self.Param("RsiOversold", 30.0) \
.SetDisplay("RSI Oversold", "Oversold level", "Indicators")
self._stop_loss_points = self.Param("StopLossPoints", 3000.0) \
.SetDisplay("Stop Loss Points", "Initial stop loss in points", "Risk Management")
self._trail_offset_points = self.Param("TrailOffsetPoints", 2000.0) \
.SetDisplay("Trail Offset Points", "Profit to activate trailing stop", "Risk Management")
self._trail_stop_points = self.Param("TrailStopPoints", 1500.0) \
.SetDisplay("Trail Stop Points", "Trailing stop distance", "Risk Management")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(15))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._entry_price = 0.0
self._stop_price = 0.0
self._trailing_price = 0.0
self._trailing_active = False
self._cooldown = 0
@property
def bollinger_period(self):
return self._bollinger_period.Value
@property
def bollinger_deviation(self):
return self._bollinger_deviation.Value
@property
def rsi_period(self):
return self._rsi_period.Value
@property
def rsi_overbought(self):
return self._rsi_overbought.Value
@property
def rsi_oversold(self):
return self._rsi_oversold.Value
@property
def stop_loss_points(self):
return self._stop_loss_points.Value
@property
def trail_offset_points(self):
return self._trail_offset_points.Value
@property
def trail_stop_points(self):
return self._trail_stop_points.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(bb_rsi_trailing_stop_strategy, self).OnReseted()
self._entry_price = 0.0
self._stop_price = 0.0
self._trailing_price = 0.0
self._trailing_active = False
self._cooldown = 0
def _reset_stops(self):
self._entry_price = 0.0
self._stop_price = 0.0
self._trailing_price = 0.0
self._trailing_active = False
self._cooldown = 100
def OnStarted2(self, time):
super(bb_rsi_trailing_stop_strategy, self).OnStarted2(time)
bb = BollingerBands()
bb.Length = self.bollinger_period
bb.Width = self.bollinger_deviation
rsi = RelativeStrengthIndex()
rsi.Length = self.rsi_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(bb, rsi, self.OnProcess).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, bb)
self.DrawIndicator(area, rsi)
self.DrawOwnTrades(area)
def OnProcess(self, candle, bb_value, rsi_value):
if candle.State != CandleStates.Finished:
return
upper = bb_value.UpBand
lower = bb_value.LowBand
if upper is None or lower is None:
return
if not rsi_value.IsFormed:
return
rsi = float(rsi_value)
if self._cooldown > 0:
self._cooldown -= 1
if self.Position == 0 and self._cooldown == 0:
if candle.LowPrice < lower and rsi < self.rsi_oversold:
self.BuyMarket()
self._entry_price = float(candle.ClosePrice)
self._stop_price = self._entry_price - self.stop_loss_points
self._cooldown = 100
elif candle.HighPrice > upper and rsi > self.rsi_overbought:
self.SellMarket()
self._entry_price = float(candle.ClosePrice)
self._stop_price = self._entry_price + self.stop_loss_points
self._cooldown = 100
elif self.Position > 0:
if not self._trailing_active and float(candle.ClosePrice) - self._entry_price >= self.trail_offset_points:
self._trailing_active = True
self._trailing_price = float(candle.ClosePrice) - self.trail_stop_points
if self._trailing_active:
new_level = float(candle.ClosePrice) - self.trail_stop_points
if new_level > self._trailing_price:
self._trailing_price = new_level
if candle.LowPrice <= self._stop_price or (self._trailing_active and candle.LowPrice <= self._trailing_price):
self.SellMarket()
self._reset_stops()
else:
if not self._trailing_active and self._entry_price - float(candle.ClosePrice) >= self.trail_offset_points:
self._trailing_active = True
self._trailing_price = float(candle.ClosePrice) + self.trail_stop_points
if self._trailing_active:
new_level = float(candle.ClosePrice) + self.trail_stop_points
if new_level < self._trailing_price or self._trailing_price == 0:
self._trailing_price = new_level
if candle.HighPrice >= self._stop_price or (self._trailing_active and candle.HighPrice >= self._trailing_price):
self.BuyMarket()
self._reset_stops()
def CreateClone(self):
return bb_rsi_trailing_stop_strategy()