Estrategia RSI Donchian
La estrategia RSI Donchian busca extremos de momentum que coincidan con rupturas del Canal Donchian. El índice de fuerza relativa mide las condiciones de sobrecompra y sobreventa mientras que el canal define los máximos y mínimos recientes del precio.
Las pruebas indican un rendimiento anual promedio de aproximadamente 82%. Funciona mejor en el mercado de acciones.
Aparece una señal de compra cuando el RSI está por encima de RsiOverbought mientras el precio rompe por encima de la banda superior Donchian. Una señal corta se forma cuando el RSI está por debajo de RsiOversold mientras el precio cae a través de la banda inferior. Las salidas ocurren una vez que el precio regresa a la línea media Donchian, señalando un retorno al equilibrio.
Este método funciona bien para traders activos que prefieren seguir un momentum fuerte pero aun así operan con niveles claros de ruptura. El stop-loss ayuda a limitar el riesgo si el momentum no revierte rápidamente.
Detalles
- Criterios de entrada:
- Largo: RSI > RsiOverbought && Close > Donchian High
- Corto: RSI < RsiOversold && Close < Donchian Low
- Largo/Corto: Ambos lados.
- Criterios de salida:
- Largo: Salir cuando close < Donchian Middle
- Corto: Salir cuando close > Donchian Middle
- Stops: Sí, stop-loss porcentual.
- Valores predeterminados:
RsiPeriod = 14
DonchianPeriod = 20
RsiOverbought = 70
RsiOversold = 30
StopLossPercent = 2
El canal es el máximo y el mínimo de las DonchianPeriod velas anteriores, y su punto medio está a mitad de camino entre ellos. Una ruptura alcista se confirma cuando el RSI está por encima de RsiOverbought y una bajista cuando está por debajo de RsiOversold; la lectura contraria, un RSI sobrevendido con un cierre por encima del canal, prácticamente no ocurre. El stop es un StopLossPercent fijo del precio de entrada, vigilado también entre velas. Una señal de entrada contra una posición abierta la invierte.
CandleType = TimeSpan.FromMinutes(15)
- Filtros:
- Categoría: Mixto
- Dirección: Ambos
- Indicadores: RSI, Donchian Channel
- Stops: Sí
- Complejidad: Intermedio
- Marco temporal: Intradía
- Estacionalidad: No
- Redes neuronales: No
- Divergencia: No
- Nivel de riesgo: Medio
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>
/// RSI Donchian strategy.
/// The channel spans the highest high and lowest low of the previous DonchianPeriod candles. A close above it with RSI above RsiOverbought
/// confirms momentum and goes long, a close below it with RSI below RsiOversold goes short, reversing an opposite position. A long closes
/// when price falls below the channel middle and a short when it rises above it, and a percent stop limits the loss.
/// </summary>
public class RsiDonchianStrategy : Strategy
{
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<int> _donchianPeriod;
private readonly StrategyParam<decimal> _rsiOverbought;
private readonly StrategyParam<decimal> _rsiOversold;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevUpper;
private decimal? _prevLower;
/// <summary>
/// Period of RSI.
/// </summary>
public int RsiPeriod
{
get => _rsiPeriod.Value;
set => _rsiPeriod.Value = value;
}
/// <summary>
/// Previous candles the channel spans.
/// </summary>
public int DonchianPeriod
{
get => _donchianPeriod.Value;
set => _donchianPeriod.Value = value;
}
/// <summary>
/// RSI level that confirms an upside breakout.
/// </summary>
public decimal RsiOverbought
{
get => _rsiOverbought.Value;
set => _rsiOverbought.Value = value;
}
/// <summary>
/// RSI level that confirms a downside breakout.
/// </summary>
public decimal RsiOversold
{
get => _rsiOversold.Value;
set => _rsiOversold.Value = value;
}
/// <summary>
/// Stop loss percentage from entry price.
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public RsiDonchianStrategy()
{
_rsiPeriod = Param(nameof(RsiPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Period", "Period of RSI", "Indicators");
_donchianPeriod = Param(nameof(DonchianPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("Donchian Period", "Previous candles the channel spans", "Indicators");
_rsiOverbought = Param(nameof(RsiOverbought), 70m)
.SetDisplay("RSI Overbought", "RSI level that confirms an upside breakout", "Indicators");
_rsiOversold = Param(nameof(RsiOversold), 30m)
.SetDisplay("RSI Oversold", "RSI level that confirms a downside breakout", "Indicators");
_stopLossPercent = Param(nameof(StopLossPercent), 2m)
.SetNotNegative()
.SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk");
_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();
_prevUpper = null;
_prevLower = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevUpper = null;
_prevLower = null;
var donchian = new DonchianChannels { Length = DonchianPeriod };
var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(donchian, rsi, ProcessCandle)
.Start();
StartProtection(new Unit(), new Unit(StopLossPercent, UnitTypes.Percent), useMarketOrders: true, isLocalStop: true);
// The stop has to see prices between candles, not only at their close.
foreach (var field in new[] { Level1Fields.BestBidPrice, Level1Fields.BestAskPrice })
{
var quotes = new Subscription(DataType.Level1, Security);
quotes.MarketData.BuildField = field;
SubscribeLevel1(quotes).Bind(ObserveProtectionQuote).Start();
}
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, donchian);
DrawOwnTrades(area);
var oscillators = CreateChartArea();
if (oscillators != null)
{
DrawIndicator(oscillators, rsi);
}
}
}
private void ObserveProtectionQuote(Level1ChangeMessage quote)
{
// The high-level handler activates native protection before this callback, also between signal bars.
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue donchianValue, IIndicatorValue rsiValue)
{
if (candle.State != CandleStates.Finished)
return;
// The channel is measured on the candles before this one.
var upper = _prevUpper;
var lower = _prevLower;
if (donchianValue.IsFormed && donchianValue is IDonchianChannelsValue { UpperBand: decimal currentUpper, LowerBand: decimal currentLower })
{
_prevUpper = currentUpper;
_prevLower = currentLower;
}
if (!rsiValue.IsFormed || upper is not decimal channelHigh || lower is not decimal channelLow)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var rsi = rsiValue.GetValue<decimal>();
var close = candle.ClosePrice;
var middle = (channelHigh + channelLow) / 2;
if (close > channelHigh && rsi > RsiOverbought && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (close < channelLow && rsi < RsiOversold && Position >= 0)
SellMarket(Volume + Math.Abs(Position));
else if (Position > 0 && close < middle)
SellMarket(Position);
else if (Position < 0 && close > middle)
BuyMarket(-Position);
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
clr.AddReference("StockSharp.BusinessEntities")
from System import TimeSpan, Decimal
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes, Level1Fields
from StockSharp.BusinessEntities import Subscription
from StockSharp.Algo.Indicators import DonchianChannels, RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class rsi_donchian_strategy(Strategy):
"""
RSI Donchian strategy.
The channel spans the highest high and lowest low of the previous DonchianPeriod candles. A close above it with RSI above RsiOverbought
confirms momentum and goes long, a close below it with RSI below RsiOversold goes short, reversing an opposite position. A long closes
when price falls below the channel middle and a short when it rises above it, and a percent stop limits the loss.
"""
def __init__(self):
super(rsi_donchian_strategy, self).__init__()
self._rsi_period = self.Param("RsiPeriod", 14).SetGreaterThanZero().SetDisplay("RSI Period", "Period of RSI", "Indicators")
self._donchian_period = self.Param("DonchianPeriod", 20).SetGreaterThanZero().SetDisplay("Donchian Period", "Previous candles the channel spans", "Indicators")
self._rsi_overbought = self.Param("RsiOverbought", 70.0).SetDisplay("RSI Overbought", "RSI level that confirms an upside breakout", "Indicators")
self._rsi_oversold = self.Param("RsiOversold", 30.0).SetDisplay("RSI Oversold", "RSI level that confirms a downside breakout", "Indicators")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0).SetNotNegative().SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(15))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._reset_state()
@property
def candle_type(self):
return self._candle_type.Value
def _reset_state(self):
self._prev_upper = None
self._prev_lower = None
def OnReseted(self):
super(rsi_donchian_strategy, self).OnReseted()
self._reset_state()
def OnStarted2(self, time):
super(rsi_donchian_strategy, self).OnStarted2(time)
self._reset_state()
donchian = DonchianChannels()
donchian.Length = self._donchian_period.Value
rsi = RelativeStrengthIndex()
rsi.Length = self._rsi_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(donchian, rsi, self._process_candle).Start()
self.StartProtection(Unit(), Unit(Decimal(self._stop_loss_percent.Value), UnitTypes.Percent), useMarketOrders=True, isLocalStop=True)
# The stop has to see prices between candles, not only at their close.
for field in (Level1Fields.BestBidPrice, Level1Fields.BestAskPrice):
quotes = Subscription(DataType.Level1, self.Security)
quotes.MarketData.BuildField = field
self.SubscribeLevel1(quotes).Bind(self._observe_protection_quote).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, donchian)
self.DrawOwnTrades(area)
oscillators = self.CreateChartArea()
if oscillators is not None:
self.DrawIndicator(oscillators, rsi)
def _observe_protection_quote(self, quote):
# The high-level handler activates native protection before the callback, including between bars.
pass
def _process_candle(self, candle, donchian_value, rsi_value):
if candle.State != CandleStates.Finished:
return
# The channel is measured on the candles before this one.
upper = self._prev_upper
lower = self._prev_lower
if donchian_value.IsFormed and donchian_value.UpperBand is not None and donchian_value.LowerBand is not None:
self._prev_upper = donchian_value.UpperBand
self._prev_lower = donchian_value.LowerBand
if not rsi_value.IsFormed or upper is None or lower is None:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
rsi = rsi_value.GetValue[Decimal](None)
close = candle.ClosePrice
middle = (upper + lower) / Decimal(2)
if close > upper and rsi > Decimal(self._rsi_overbought.Value) and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif close < lower and rsi < Decimal(self._rsi_oversold.Value) and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
elif self.Position > 0 and close < middle:
self.SellMarket(self.Position)
elif self.Position < 0 and close > middle:
self.BuyMarket(-self.Position)
def CreateClone(self):
return rsi_donchian_strategy()