Estrategia Donchian Stochastic
Estrategia Donchian Channel + Stochastic. La estrategia entra al mercado cuando el precio rompe el Canal de Donchian con el Stochastic confirmando condiciones de sobreventa/sobrecompra.
Las pruebas indican un rendimiento anual promedio de aproximadamente 85%. Funciona mejor en el mercado de criptomonedas.
Las rupturas más allá del canal de Donchian se confirman con el impulso del Stochastic. Las operaciones comienzan en cuanto el precio escapa del rango y el oscilador lo confirma.
Útil para traders que esperan un seguimiento inmediato. Un porcentaje fijo del precio de entrada establece el stop.
Detalles
- Criterios de entrada:
- Largo:
Close > DonchianHigh && StochK > StochOverbought - Corto:
Close < DonchianLow && StochK < StochOversold
- Largo:
- Largo/Corto: Ambos
- Criterios de salida: Fallo de ruptura o señal opuesta
- Stops: Basados en porcentaje usando
StopLossPercent - Valores predeterminados:
DonchianPeriod= 20StochPeriod= 14StochK= 3StochOverbought= 80StochOversold= 20CandleType= TimeSpan.FromMinutes(5).TimeFrame()StopLossPercent= 2 Una ruptura alcista de las DonchianPeriod velas anteriores se confirma cuando %K está por encima de StochOverbought y una bajista cuando %K está por debajo de StochOversold; la lectura contraria, un %K sobrevendido en una ruptura alcista, prácticamente no ocurre. %K es el estocástico de StochPeriod velas suavizado en StochK velas, y %D no interviene. La ruptura falla, y la posición se cierra, cuando el precio vuelve a cerrar al otro lado del nivel roto. Una señal de entrada contra una posición abierta la invierte.
- Filtros:
- Categoría: Ruptura
- Dirección: Ambos
- Indicadores: Donchian Channel, Stochastic Oscillator
- Stops: Sí
- Complejidad: Intermedio
- Marco temporal: Medio plazo
- 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>
/// Donchian Stochastic strategy.
/// The channel spans the highest high and lowest low of the previous DonchianPeriod candles. A close above it with %K above StochOverbought
/// confirms momentum and goes long, a close below it with %K below StochOversold goes short, reversing an opposite position;
/// %K is the stochastic over StochPeriod candles smoothed over StochK candles.
/// The breakout fails, closing the position, when price closes back beyond the broken level, and a percent stop limits the loss.
/// </summary>
public class DonchianStochasticStrategy : Strategy
{
private readonly StrategyParam<int> _donchianPeriod;
private readonly StrategyParam<int> _stochPeriod;
private readonly StrategyParam<int> _stochK;
private readonly StrategyParam<decimal> _stochOverbought;
private readonly StrategyParam<decimal> _stochOversold;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevUpper;
private decimal? _prevLower;
private decimal _breakoutLevel;
/// <summary>
/// Previous candles the channel spans.
/// </summary>
public int DonchianPeriod
{
get => _donchianPeriod.Value;
set => _donchianPeriod.Value = value;
}
/// <summary>
/// Lookback period of the raw stochastic.
/// </summary>
public int StochPeriod
{
get => _stochPeriod.Value;
set => _stochPeriod.Value = value;
}
/// <summary>
/// Smoothing period of %K.
/// </summary>
public int StochK
{
get => _stochK.Value;
set => _stochK.Value = value;
}
/// <summary>
/// %K level that confirms an upside breakout.
/// </summary>
public decimal StochOverbought
{
get => _stochOverbought.Value;
set => _stochOverbought.Value = value;
}
/// <summary>
/// %K level that confirms a downside breakout.
/// </summary>
public decimal StochOversold
{
get => _stochOversold.Value;
set => _stochOversold.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 DonchianStochasticStrategy()
{
_donchianPeriod = Param(nameof(DonchianPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("Donchian Period", "Previous candles the channel spans", "Indicators");
_stochPeriod = Param(nameof(StochPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("Stochastic Period", "Lookback period of the raw stochastic", "Stochastic");
_stochK = Param(nameof(StochK), 3)
.SetGreaterThanZero()
.SetDisplay("Stochastic %K", "Smoothing period of %K", "Stochastic");
_stochOverbought = Param(nameof(StochOverbought), 80m)
.SetDisplay("Stochastic Overbought", "%K level that confirms an upside breakout", "Stochastic");
_stochOversold = Param(nameof(StochOversold), 20m)
.SetDisplay("Stochastic Oversold", "%K level that confirms a downside breakout", "Stochastic");
_stopLossPercent = Param(nameof(StopLossPercent), 2m)
.SetNotNegative()
.SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).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;
_breakoutLevel = default;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevUpper = null;
_prevLower = null;
_breakoutLevel = default;
var donchian = new DonchianChannels { Length = DonchianPeriod };
// The D line of the core oscillator is the smoothed %K.
var stochastic = new StochasticOscillator
{
K = { Length = StochPeriod },
D = { Length = StochK },
};
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(donchian, stochastic, 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, stochastic);
}
}
}
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 stochasticValue)
{
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 (!stochasticValue.IsFormed || upper is not decimal channelHigh || lower is not decimal channelLow)
return;
if (stochasticValue is not IStochasticOscillatorValue { D: decimal k })
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var close = candle.ClosePrice;
if (close > channelHigh && k > StochOverbought && Position <= 0)
{
BuyMarket(Volume + Math.Abs(Position));
_breakoutLevel = channelHigh;
}
else if (close < channelLow && k < StochOversold && Position >= 0)
{
SellMarket(Volume + Math.Abs(Position));
_breakoutLevel = channelLow;
}
else if (Position > 0 && close < _breakoutLevel)
{
SellMarket(Position);
}
else if (Position < 0 && close > _breakoutLevel)
{
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, StochasticOscillator
from StockSharp.Algo.Strategies import Strategy
class donchian_stochastic_strategy(Strategy):
"""
Donchian Stochastic strategy.
The channel spans the highest high and lowest low of the previous DonchianPeriod candles. A close above it with %K above StochOverbought
confirms momentum and goes long, a close below it with %K below StochOversold goes short, reversing an opposite position;
%K is the stochastic over StochPeriod candles smoothed over StochK candles.
The breakout fails, closing the position, when price closes back beyond the broken level, and a percent stop limits the loss.
"""
def __init__(self):
super(donchian_stochastic_strategy, self).__init__()
self._donchian_period = self.Param("DonchianPeriod", 20).SetGreaterThanZero().SetDisplay("Donchian Period", "Previous candles the channel spans", "Indicators")
self._stoch_period = self.Param("StochPeriod", 14).SetGreaterThanZero().SetDisplay("Stochastic Period", "Lookback period of the raw stochastic", "Stochastic")
self._stoch_k = self.Param("StochK", 3).SetGreaterThanZero().SetDisplay("Stochastic %K", "Smoothing period of %K", "Stochastic")
self._stoch_overbought = self.Param("StochOverbought", 80.0).SetDisplay("Stochastic Overbought", "%K level that confirms an upside breakout", "Stochastic")
self._stoch_oversold = self.Param("StochOversold", 20.0).SetDisplay("Stochastic Oversold", "%K level that confirms a downside breakout", "Stochastic")
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(5))).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
self._breakout_level = Decimal(0)
def OnReseted(self):
super(donchian_stochastic_strategy, self).OnReseted()
self._reset_state()
def OnStarted2(self, time):
super(donchian_stochastic_strategy, self).OnStarted2(time)
self._reset_state()
donchian = DonchianChannels()
donchian.Length = self._donchian_period.Value
# The D line of the core oscillator is the smoothed %K.
stochastic = StochasticOscillator()
stochastic.K.Length = self._stoch_period.Value
stochastic.D.Length = self._stoch_k.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(donchian, stochastic, 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, stochastic)
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, stochastic_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 stochastic_value.IsFormed or stochastic_value.D is None or upper is None or lower is None:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
k = stochastic_value.D
close = candle.ClosePrice
if close > upper and k > Decimal(self._stoch_overbought.Value) and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
self._breakout_level = upper
elif close < lower and k < Decimal(self._stoch_oversold.Value) and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
self._breakout_level = lower
elif self.Position > 0 and close < self._breakout_level:
self.SellMarket(self.Position)
elif self.Position < 0 and close > self._breakout_level:
self.BuyMarket(-self.Position)
def CreateClone(self):
return donchian_stochastic_strategy()