Donchian CCI Strategy
This strategy uses Donchian CCI indicators to generate signals. Long entry occurs when Price > Donchian Upper && CCI < -100 (breakout up with oversold conditions). Short entry occurs when Price < Donchian Lower && CCI > 100 (breakout down with overbought conditions). It is suitable for traders seeking opportunities in mixed markets.
Testing indicates an average annual return of about 43%. It performs best in the stocks market.
Details
- Entry Criteria:
- Long: Price > Donchian Upper && CCI < -100 (breakout up with oversold conditions)
- Short: Price < Donchian Lower && CCI > 100 (breakout down with overbought conditions)
- Long/Short: Both sides.
- Exit Criteria:
- Long: Exit long position when price falls below middle band
- Short: Exit short position when price rises above middle band
- Stops: Yes.
- Default Values:
DonchianPeriod= 20CciPeriod= 20StopLossPercent= 2mCandleType= TimeSpan.FromMinutes(5)
- Filters:
- Category: Mixed
- Direction: Both
- Indicators: Donchian CCI
- Stops: Yes
- 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>
/// Strategy based on Donchian Channels and CCI indicators
/// </summary>
public class DonchianCciStrategy : Strategy
{
private readonly StrategyParam<int> _donchianPeriod;
private readonly StrategyParam<int> _cciPeriod;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
/// <summary>
/// Period for Donchian Channel
/// </summary>
public int DonchianPeriod
{
get => _donchianPeriod.Value;
set => _donchianPeriod.Value = value;
}
/// <summary>
/// Period for CCI indicator
/// </summary>
public int CciPeriod
{
get => _cciPeriod.Value;
set => _cciPeriod.Value = value;
}
/// <summary>
/// Stop-loss percentage
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Candle type for strategy
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor
/// </summary>
public DonchianCciStrategy()
{
_donchianPeriod = Param(nameof(DonchianPeriod), 20)
.SetRange(10, 50)
.SetDisplay("Donchian Period", "Period for Donchian Channel", "Indicators")
;
_cciPeriod = Param(nameof(CciPeriod), 20)
.SetRange(10, 50)
.SetDisplay("CCI Period", "Period for CCI indicator", "Indicators")
;
_stopLossPercent = Param(nameof(StopLossPercent), 2m)
.SetRange(0.5m, 5m)
.SetDisplay("Stop-Loss %", "Stop-loss percentage from entry price", "Risk Management")
;
_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)];
}
private int _cooldown;
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_cooldown = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
// Initialize Indicators
var donchian = new DonchianChannels { Length = DonchianPeriod };
var cci = new CommodityChannelIndex { Length = CciPeriod };
// Create subscription and bind indicators
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(donchian, cci, ProcessIndicators)
.Start();
// Setup chart visualization if available
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, donchian);
DrawIndicator(area, cci);
DrawOwnTrades(area);
}
}
private void ProcessIndicators(ICandleMessage candle, IIndicatorValue donchianValue, IIndicatorValue cciValue)
{
// Skip unfinished candles
if (candle.State != CandleStates.Finished)
return;
var donchianTyped = (DonchianChannelsValue)donchianValue;
var upperBand = donchianTyped.UpperBand ?? 0m;
var lowerBand = donchianTyped.LowerBand ?? 0m;
var middleBand = donchianTyped.Middle ?? 0m;
if (upperBand == 0m || lowerBand == 0m)
return;
var cciDec = cciValue.ToDecimal();
var price = candle.ClosePrice;
if (_cooldown > 0)
_cooldown--;
if (_cooldown == 0 && price >= upperBand && cciDec > 0 && Position <= 0)
{
BuyMarket();
_cooldown = 50;
}
else if (_cooldown == 0 && price <= lowerBand && cciDec < 0 && Position >= 0)
{
SellMarket();
_cooldown = 50;
}
else if (Position > 0 && price < middleBand)
{
SellMarket();
_cooldown = 50;
}
else if (Position < 0 && price > middleBand)
{
BuyMarket();
_cooldown = 50;
}
}
}
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 DonchianChannels, CommodityChannelIndex
from StockSharp.Algo.Strategies import Strategy
class donchian_cci_strategy(Strategy):
"""
Strategy based on Donchian Channels and CCI indicators.
Buys when price touches upper Donchian band with CCI > 0.
Sells when price touches lower Donchian band with CCI < 0.
Exits when price crosses middle band.
"""
def __init__(self):
super(donchian_cci_strategy, self).__init__()
self._donchian_period = self.Param("DonchianPeriod", 20) \
.SetDisplay("Donchian Period", "Period for Donchian Channel", "Indicators")
self._cci_period = self.Param("CciPeriod", 20) \
.SetDisplay("CCI Period", "Period for CCI indicator", "Indicators")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0) \
.SetDisplay("Stop-Loss %", "Stop-loss percentage from entry price", "Risk Management")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._cooldown = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(donchian_cci_strategy, self).OnReseted()
self._cooldown = 0
def OnStarted2(self, time):
super(donchian_cci_strategy, self).OnStarted2(time)
donchian = DonchianChannels()
donchian.Length = self._donchian_period.Value
cci = CommodityChannelIndex()
cci.Length = self._cci_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(donchian, cci, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, donchian)
self.DrawIndicator(area, cci)
self.DrawOwnTrades(area)
def _process_candle(self, candle, donchian_value, cci_value):
if candle.State != CandleStates.Finished:
return
upper = donchian_value.UpperBand
lower = donchian_value.LowerBand
middle = donchian_value.Middle
if upper is None or lower is None or middle is None:
return
upper = float(upper)
lower = float(lower)
middle = float(middle)
cci_dec = float(cci_value)
price = float(candle.ClosePrice)
if self._cooldown > 0:
self._cooldown -= 1
if self._cooldown == 0 and price >= upper and cci_dec > 0 and self.Position <= 0:
self.BuyMarket()
self._cooldown = 50
elif self._cooldown == 0 and price <= lower and cci_dec < 0 and self.Position >= 0:
self.SellMarket()
self._cooldown = 50
elif self.Position > 0 and price < middle:
self.SellMarket()
self._cooldown = 50
elif self.Position < 0 and price > middle:
self.BuyMarket()
self._cooldown = 50
def CreateClone(self):
return donchian_cci_strategy()