Donchian Stochastic 戦略
Donchian Channel + Stochastic 戦略。価格が Donchian Channel をブレイクし、Stochastic が売られすぎ/買われすぎ条件を確認した際に市場に参入します。
テストでは年平均収益率は約 85% を示しています。暗号資産市場で最もパフォーマンスが優れています。
Donchian チャネルを超えたブレイクアウトは Stochastic のモメンタムで確認されます。価格がレンジを脱出してオシレーターが同意した時点でトレードが始まります。
即座の追随を期待するトレーダーに有用です。エントリー価格の一定割合がストップを設定します。
詳細
- エントリー条件:
- ロング:
Close > DonchianHigh && StochK > StochOverbought - ショート:
Close < DonchianLow && StochK < StochOversold
- ロング:
- ロング/ショート: 両方
- エグジット条件: ブレイクアウトの失敗または反対シグナル
- ストップ:
StopLossPercentを使用したパーセントベース - デフォルト値:
DonchianPeriod= 20StochPeriod= 14StochK= 3StochOverbought= 80StochOversold= 20CandleType= TimeSpan.FromMinutes(5).TimeFrame()StopLossPercent= 2 直前DonchianPeriod本のチャネルの上抜けは%KがStochOverboughtを上回るとき、下抜けは%KがStochOversoldを下回るときに確認されます。逆の読み方(上抜け時に%Kが売られすぎ)は実際にはほぼ起こりません。%KはStochPeriod本のストキャスティクスをStochK本で平滑化した値で、%Dは関与しません。価格が突破した水準の反対側に戻って引けたらブレイク失敗としてポジションを閉じます。 保有ポジションと逆方向のエントリーシグナルはドテンになります。
- フィルター:
- カテゴリ: ブレイクアウト
- 方向: 両方
- インジケーター: Donchian Channel, Stochastic Oscillator
- ストップ: はい
- 複雑さ: 中級
- 時間軸: 中期
- 季節性: いいえ
- ニューラルネットワーク: いいえ
- ダイバージェンス: いいえ
- リスクレベル: 中
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()