Donchian HL Width Cycle Information
Стратегия, торгующая на изменениях циклов ширины канала Дончиана.
Стратегия отслеживает отношение экстремумов свечей к каналу Дончиана. После нисходящего цикла вход в лонг происходит при достижении верхней границы, а после восходящего цикла — вход в шорт при касании нижней границы.
Детали
- Критерий входа: Смена направления цикла по каналу Дончиана.
- Длинные/короткие: Оба направления.
- Критерий выхода: Противоположный сигнал цикла.
- Стопы: Нет.
- Значения по умолчанию:
Length= 28CandleType= TimeSpan.FromMinutes(5)
- Фильтры:
- Категория: Тренд
- Направление: Оба
- Индикаторы: Дончиан
- Стопы: Нет
- Сложность: Базовая
- Таймфрейм: Внутридневной (5м)
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
using System;
using System.Linq;
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 channel cycle strategy.
/// Tracks Donchian channel breakouts and cycles between upper and lower bands.
/// </summary>
public class DonchianHlWidthCycleInformationStrategy : Strategy
{
private readonly StrategyParam<int> _length;
private readonly StrategyParam<DataType> _candleType;
private int _cycleTrend;
public int Length { get => _length.Value; set => _length.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public DonchianHlWidthCycleInformationStrategy()
{
_length = Param(nameof(Length), 20)
.SetDisplay("Donchian Length", "Lookback for Donchian channel", "Donchian");
_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()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_cycleTrend = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var highest = new Highest { Length = Length };
var lowest = new Lowest { Length = Length };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(highest, lowest, ProcessCandle)
.Start();
StartProtection(
takeProfit: new Unit(2, UnitTypes.Percent),
stopLoss: new Unit(1, UnitTypes.Percent)
);
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal upper, decimal lower)
{
if (candle.State != CandleStates.Finished)
return;
if (upper == lower)
return;
// Cycle detection: breakout above upper band or below lower band
if (candle.ClosePrice >= upper && _cycleTrend != 1)
{
_cycleTrend = 1;
if (Position == 0)
BuyMarket();
}
else if (candle.ClosePrice <= lower && _cycleTrend != -1)
{
_cycleTrend = -1;
if (Position == 0)
SellMarket();
}
}
}
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, Unit, UnitTypes
from StockSharp.Algo.Indicators import Highest, Lowest
from StockSharp.Algo.Strategies import Strategy
class donchian_hl_width_cycle_information_strategy(Strategy):
def __init__(self):
super(donchian_hl_width_cycle_information_strategy, self).__init__()
self._length = self.Param("Length", 20) \
.SetDisplay("Donchian Length", "Lookback for Donchian channel", "Donchian")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._cycle_trend = 0
@property
def length(self):
return self._length.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(donchian_hl_width_cycle_information_strategy, self).OnReseted()
self._cycle_trend = 0
def OnStarted2(self, time):
super(donchian_hl_width_cycle_information_strategy, self).OnStarted2(time)
highest = Highest()
highest.Length = self.length
lowest = Lowest()
lowest.Length = self.length
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(highest, lowest, self.on_process).Start()
self.StartProtection(
takeProfit=Unit(2, UnitTypes.Percent),
stopLoss=Unit(1, UnitTypes.Percent)
)
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, upper, lower):
if candle.State != CandleStates.Finished:
return
if upper == lower:
return
# Cycle detection: breakout above upper band or below lower band
if candle.ClosePrice >= upper and self._cycle_trend != 1:
self._cycle_trend = 1
if self.Position == 0:
self.BuyMarket()
elif candle.ClosePrice <= lower and self._cycle_trend != -1:
self._cycle_trend = -1
if self.Position == 0:
self.SellMarket()
def CreateClone(self):
return donchian_hl_width_cycle_information_strategy()