Ver en GitHub

Donchian Channel

Strategy based on Donchian Channel

Testing indicates an average annual return of about 52%. It performs best in the crypto market.

Donchian Channel Breakout trades new highs and lows based on the channel range. A close beyond the upper band signals strength, while a drop below the lower band invites shorts. Exits occur when price returns to the midpoint.

The channel is calculated from the highest high and lowest low over a lookback window. When price pierces these bounds, the system expects volatility expansion and positions accordingly.

Details

  • Entry Criteria: Signals based on Price Action.
  • Long/Short: Both directions.
  • Exit Criteria: Opposite signal.
  • Stops: No.
  • Default Values:
    • ChannelPeriod = 20
    • CandleType = TimeSpan.FromMinutes(5)
  • Filters:
    • Category: Trend
    • Direction: Both
    • Indicators: Price Action
    • Stops: No
    • Complexity: Basic
    • Timeframe: Intraday (5m)
    • 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>
/// Strategy based on Donchian Channel.
/// It enters long position when price breaks through the upper band and short position when price breaks through the lower band.
/// </summary>
public class DonchianChannelStrategy : Strategy
{
	private readonly StrategyParam<int> _channelPeriod;
	private readonly StrategyParam<DataType> _candleType;

	// Current state
	private decimal _prevClosePrice;
	private decimal _prevUpperBand;
	private decimal _prevLowerBand;

	/// <summary>
	/// Period for Donchian Channel.
	/// </summary>
	public int ChannelPeriod
	{
		get => _channelPeriod.Value;
		set => _channelPeriod.Value = value;
	}

	/// <summary>
	/// Candle type.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Initialize the Donchian Channel strategy.
	/// </summary>
	public DonchianChannelStrategy()
	{
		_channelPeriod = Param(nameof(ChannelPeriod), 1000)
			.SetDisplay("Channel Period", "Period for Donchian Channel calculation", "Indicators")
			
			.SetOptimize(10, 50, 5);

		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1).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();
		_prevClosePrice = default;
		_prevUpperBand = default;
		_prevLowerBand = default;

	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		// Create indicators
		var donchian = new DonchianChannels { Length = ChannelPeriod };

		// Create subscription and bind indicators
		var subscription = SubscribeCandles(CandleType);
		subscription
			.BindEx(donchian, ProcessCandle)
			.Start();

		// Setup chart visualization if available
		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, donchian);
			DrawOwnTrades(area);
		}
	}

	private void ProcessCandle(ICandleMessage candle, IIndicatorValue donchianValue)
	{
		// Skip unfinished candles
		if (candle.State != CandleStates.Finished)
			return;

		// Check if strategy is ready to trade
		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		var donchianTyped = (DonchianChannelsValue)donchianValue;
		
		if (donchianTyped.UpperBand is not decimal upperValue ||
			donchianTyped.LowerBand is not decimal lowerValue ||
			donchianTyped.Middle is not decimal midValue)
		{
			return;
		}

		// Skip the first received value for proper comparison
		if (_prevUpperBand == 0)
		{
			_prevClosePrice = candle.ClosePrice;
			_prevUpperBand = upperValue;
			_prevLowerBand = lowerValue;
			return;
		}

		// Check for breakouts
		var isUpperBreakout = candle.ClosePrice > _prevUpperBand && _prevClosePrice <= _prevUpperBand;
		var isLowerBreakout = candle.ClosePrice < _prevLowerBand && _prevClosePrice >= _prevLowerBand;

		// Entry logic - breakout reversal
		if (isUpperBreakout && Position <= 0)
		{
			BuyMarket(Volume + Math.Abs(Position));
		}
		else if (isLowerBreakout && Position >= 0)
		{
			SellMarket(Volume + Math.Abs(Position));
		}

		// Update previous values
		_prevClosePrice = candle.ClosePrice;
		_prevUpperBand = upperValue;
		_prevLowerBand = lowerValue;
	}
}