Прорыв N-дневного диапазона
Стратегия прорыва максимумов и минимумов за N дней.
Тестирование показывает среднегодичную доходность около 43%. Стратегию лучше запускать на фондовом рынке.
Наблюдает за новыми максимумами или минимумами за указанный период. Вход происходит, когда цена пробивает крайний N-дневный уровень, что предполагает развитие импульса. Для выхода используется фильтр скользящей средней и процентный стоп.
Ожидание пробоя предыдущего экстремума помогает поймать начало движения. Фильтр по средне скользящей, следующей за трендом, защищает от ложных сигналов во время консолидации.
Детали
- Критерии входа: сигналы на основе MA.
- Длинные/короткие: оба направления.
- Критерии выхода: противоположный сигнал или стоп.
- Стопы: да.
- Значения по умолчанию:
LookbackPeriod= 20MaPeriod= 20StopLossPercent= 2.0mCandleType= TimeSpan.FromDays(1)
- Фильтры:
- Категория: Прорыв
- Направление: Оба
- Индикаторы: MA
- Стопы: Да
- Сложность: Базовая
- Таймфрейм: Дневной
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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>
/// N-day high/low breakout strategy.
/// Enters long when price breaks above the N-day high.
/// Enters short when price breaks below the N-day low.
/// Exits when price crosses the moving average.
/// </summary>
public class NdayBreakoutStrategy : Strategy
{
private readonly StrategyParam<int> _lookbackPeriod;
private readonly StrategyParam<int> _maPeriod;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
// Indicators for entry conditions
private Highest _highest;
private Lowest _lowest;
private SMA _ma;
// Values for tracking breakouts
private decimal _nDayHigh;
private decimal _nDayLow;
private bool _isFormed;
/// <summary>
/// Period for looking back to determine the highest/lowest value.
/// </summary>
public int LookbackPeriod
{
get => _lookbackPeriod.Value;
set => _lookbackPeriod.Value = value;
}
/// <summary>
/// Period for the moving average used for exit signals.
/// </summary>
public int MaPeriod
{
get => _maPeriod.Value;
set => _maPeriod.Value = value;
}
/// <summary>
/// Stop-loss percentage.
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// The type of candles to use for strategy calculation.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public NdayBreakoutStrategy()
{
_lookbackPeriod = Param(nameof(LookbackPeriod), 1500)
.SetGreaterThanZero()
.SetDisplay("Lookback Period", "Number of bars to determine the high/low range", "Strategy Parameters")
.SetOptimize(10, 30, 5);
_maPeriod = Param(nameof(MaPeriod), 300)
.SetGreaterThanZero()
.SetDisplay("MA Period", "Period for the moving average used as exit signal", "Strategy Parameters")
.SetOptimize(10, 30, 5);
_stopLossPercent = Param(nameof(StopLossPercent), 2.0m)
.SetGreaterThanZero()
.SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk Management")
.SetOptimize(1.0m, 3.0m, 0.5m);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "Strategy Parameters");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
// Initialize tracking variables
_nDayHigh = 0;
_nDayLow = decimal.MaxValue;
_isFormed = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
// Create indicators
_highest = new Highest { Length = LookbackPeriod };
_lowest = new Lowest { Length = LookbackPeriod };
_ma = new SMA { Length = MaPeriod };
// Create and setup subscription for candles
var subscription = SubscribeCandles(CandleType);
// Bind indicators to candles
subscription
.Bind(_highest, _lowest, _ma, ProcessCandle)
.Start();
// Setup chart visualization if available
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _highest);
DrawIndicator(area, _lowest);
DrawIndicator(area, _ma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal highestValue, decimal lowestValue, decimal maValue)
{
// Skip unfinished candles
if (candle.State != CandleStates.Finished)
return;
// Wait until indicators are formed
if (!_isFormed)
{
// Check if highest and lowest indicators are now formed
if (_highest.IsFormed && _lowest.IsFormed)
{
_nDayHigh = highestValue;
_nDayLow = lowestValue;
_isFormed = true;
LogInfo($"Indicators formed. Initial N-day high: {_nDayHigh}, N-day low: {_nDayLow}");
}
return;
}
// Check if strategy is ready to trade
if (!IsFormedAndOnlineAndAllowTrading())
return;
LogInfo($"Processing candle: High={candle.HighPrice}, Low={candle.LowPrice}, Close={candle.ClosePrice}");
LogInfo($"Current N-day high: {_nDayHigh}, N-day low: {_nDayLow}, MA: {maValue}");
// Entry logic - only trigger on breakouts (reversal style)
if (candle.HighPrice > _nDayHigh && Position <= 0)
{
// Long entry - price breaks above the N-day high
BuyMarket(Volume + Math.Abs(Position));
}
else if (candle.LowPrice < _nDayLow && Position >= 0)
{
// Short entry - price breaks below the N-day low
SellMarket(Volume + Math.Abs(Position));
}
// Update N-day high and low values for next candle
_nDayHigh = highestValue;
_nDayLow = lowestValue;
}
}
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 Highest, Lowest, SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class nday_breakout_strategy(Strategy):
"""
N-day high/low breakout strategy.
Enters long when price breaks above the N-day high.
Enters short when price breaks below the N-day low.
"""
def __init__(self):
super(nday_breakout_strategy, self).__init__()
self._lookback_period = self.Param("LookbackPeriod", 1500).SetDisplay("Lookback Period", "Number of bars to determine the high/low range", "Strategy Parameters")
self._ma_period = self.Param("MaPeriod", 300).SetDisplay("MA Period", "Period for the moving average used as exit signal", "Strategy Parameters")
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(1))).SetDisplay("Candle Type", "Type of candles to use", "Strategy Parameters")
self._n_day_high = 0.0
self._n_day_low = float('inf')
self._is_formed = False
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(nday_breakout_strategy, self).OnReseted()
self._n_day_high = 0.0
self._n_day_low = float('inf')
self._is_formed = False
def OnStarted2(self, time):
super(nday_breakout_strategy, self).OnStarted2(time)
self._highest = Highest()
self._highest.Length = self._lookback_period.Value
self._lowest = Lowest()
self._lowest.Length = self._lookback_period.Value
self._ma = SimpleMovingAverage()
self._ma.Length = self._ma_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._highest, self._lowest, self._ma, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._highest)
self.DrawIndicator(area, self._lowest)
self.DrawIndicator(area, self._ma)
self.DrawOwnTrades(area)
def _process_candle(self, candle, highest_val, lowest_val, ma_val):
if candle.State != CandleStates.Finished:
return
if not self._is_formed:
if self._highest.IsFormed and self._lowest.IsFormed:
self._n_day_high = float(highest_val)
self._n_day_low = float(lowest_val)
self._is_formed = True
return
h = float(highest_val)
l = float(lowest_val)
if float(candle.HighPrice) > self._n_day_high and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif float(candle.LowPrice) < self._n_day_low and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
self._n_day_high = h
self._n_day_low = l
def CreateClone(self):
return nday_breakout_strategy()