Donchian CCI 策略
此策略利用唐奇安通道与CCI指标产生信号。当价格突破上轨且CCI高于CciOverbought时做多;当价格跌破下轨且CCI低于CciOversold时做空,即由动量确认的突破。
测试表明年均收益约为 43%,该策略在股票市场表现最佳。
适合在震荡市场中寻找机会的交易者。
细节
- 入场条件:
- 多头:
Price > Donchian Upper && CCI > CciOverbought - 空头:
Price < Donchian Lower && CCI < CciOversold
- 多头:
- 多/空: 双向
- 离场条件:
- 多头: 价格跌破中轨时平仓
- 空头: 价格升破中轨时平仓
- 止损: 是
- 默认值:
DonchianPeriod= 20CciPeriod= 20CciOverbought= 100CciOversold= -100StopLossPercent= 2 通道为之前DonchianPeriod根K线的最高价和最低价,中轨位于两者正中。CCI高于CciOverbought时确认向上突破,低于CciOversold时确认向下突破;相反的读法,即收盘价高于通道时CCI处于超卖,实际上几乎不会出现。与持仓方向相反的入场信号会反转持仓。CandleType= TimeSpan.FromMinutes(5)
- 过滤器:
- 类别: Mixed
- 方向: 双向
- 指标: Donchian CCI
- 止损: 是
- 复杂度: 中等
- 时间框架: 日内
- 季节性: 否
- 神经网络: 否
- 背离: 否
- 风险等级: 中等
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 CCI strategy.
/// The channel spans the highest high and lowest low of the previous DonchianPeriod candles. A close above it with CCI above CciOverbought
/// confirms momentum and goes long, a close below it with CCI below CciOversold 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 DonchianCciStrategy : Strategy
{
private readonly StrategyParam<int> _donchianPeriod;
private readonly StrategyParam<int> _cciPeriod;
private readonly StrategyParam<decimal> _cciOverbought;
private readonly StrategyParam<decimal> _cciOversold;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevUpper;
private decimal? _prevLower;
/// <summary>
/// Previous candles the channel spans.
/// </summary>
public int DonchianPeriod
{
get => _donchianPeriod.Value;
set => _donchianPeriod.Value = value;
}
/// <summary>
/// Period of CCI.
/// </summary>
public int CciPeriod
{
get => _cciPeriod.Value;
set => _cciPeriod.Value = value;
}
/// <summary>
/// CCI level that confirms an upside breakout.
/// </summary>
public decimal CciOverbought
{
get => _cciOverbought.Value;
set => _cciOverbought.Value = value;
}
/// <summary>
/// CCI level that confirms a downside breakout.
/// </summary>
public decimal CciOversold
{
get => _cciOversold.Value;
set => _cciOversold.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 DonchianCciStrategy()
{
_donchianPeriod = Param(nameof(DonchianPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("Donchian Period", "Previous candles the channel spans", "Indicators");
_cciPeriod = Param(nameof(CciPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("CCI Period", "Period of CCI", "Indicators");
_cciOverbought = Param(nameof(CciOverbought), 100m)
.SetDisplay("CCI Overbought", "CCI level that confirms an upside breakout", "Indicators");
_cciOversold = Param(nameof(CciOversold), -100m)
.SetDisplay("CCI Oversold", "CCI 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(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;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevUpper = null;
_prevLower = null;
var donchian = new DonchianChannels { Length = DonchianPeriod };
var cci = new CommodityChannelIndex { Length = CciPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(donchian, cci, 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, cci);
}
}
}
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 cciValue)
{
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 (!cciValue.IsFormed || upper is not decimal channelHigh || lower is not decimal channelLow)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var cci = cciValue.GetValue<decimal>();
var close = candle.ClosePrice;
var middle = (channelHigh + channelLow) / 2;
if (close > channelHigh && cci > CciOverbought && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (close < channelLow && cci < CciOversold && 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, CommodityChannelIndex
from StockSharp.Algo.Strategies import Strategy
class donchian_cci_strategy(Strategy):
"""
Donchian CCI strategy.
The channel spans the highest high and lowest low of the previous DonchianPeriod candles. A close above it with CCI above CciOverbought
confirms momentum and goes long, a close below it with CCI below CciOversold 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(donchian_cci_strategy, self).__init__()
self._donchian_period = self.Param("DonchianPeriod", 20).SetGreaterThanZero().SetDisplay("Donchian Period", "Previous candles the channel spans", "Indicators")
self._cci_period = self.Param("CciPeriod", 20).SetGreaterThanZero().SetDisplay("CCI Period", "Period of CCI", "Indicators")
self._cci_overbought = self.Param("CciOverbought", 100.0).SetDisplay("CCI Overbought", "CCI level that confirms an upside breakout", "Indicators")
self._cci_oversold = self.Param("CciOversold", -100.0).SetDisplay("CCI Oversold", "CCI 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(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
def OnReseted(self):
super(donchian_cci_strategy, self).OnReseted()
self._reset_state()
def OnStarted2(self, time):
super(donchian_cci_strategy, self).OnStarted2(time)
self._reset_state()
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()
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, cci)
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, cci_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 cci_value.IsFormed or upper is None or lower is None:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
cci = cci_value.GetValue[Decimal](None)
close = candle.ClosePrice
middle = (upper + lower) / Decimal(2)
if close > upper and cci > Decimal(self._cci_overbought.Value) and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif close < lower and cci < Decimal(self._cci_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 donchian_cci_strategy()