Стратегия Bollinger Breakout Momentum
Конвертированная из оригинальной стратегии MQL. Торгует прорывы полос Боллинджера, подтверждённые EMA, MACD и RSI. Стратегия совершает только одну сделку на каждое расширение волатильности, сопровождая стоп по средней полосе и используя фиксированный тейк-профит в пунктах.
Детали
- Условия входа:
- Лонг: ширина полос выше
BreakoutFactor, MACD > 0, RSI > 50, EMA выше средней полосы, предыдущий закрытие выше предыдущей верхней полосы - Шорт: ширина полос выше
BreakoutFactor, MACD < 0, RSI < 50, EMA ниже средней полосы, предыдущее закрытие ниже предыдущей нижней полосы
- Лонг: ширина полос выше
- Длинные/Короткие: Оба направления
- Условия выхода:
- Лонг: цена касается стопа по средней полосе или достигает тейк-профита
- Шорт: цена касается стопа по средней полосе или достигает тейк-профита
- Стопы: Стоп-уровень — текущая средняя полоса Боллинджера, обновляется на каждой свече
- Тейк-профит: Фиксированное расстояние в пунктах
- Значения по умолчанию:
BollingerLength= 18BollingerDeviation= 2mBreakoutFactor= 0.0015mTakeProfitPips= 100CandleType= TimeSpan.FromMinutes(5).TimeFrame()
- Фильтры:
- Категория: Breakout
- Направление: Оба
- Индикаторы: Bollinger Bands, EMA, MACD, RSI
- Стопы: Да
- Сложность: Средняя
- Таймфрейм: Внутридневной
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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>
/// Strategy trading Bollinger Band breakouts with band momentum confirmation.
/// </summary>
public class BollingerBreakoutMomentumStrategy : Strategy
{
private readonly StrategyParam<int> _bollingerLength;
private readonly StrategyParam<decimal> _bollingerDeviation;
private readonly StrategyParam<int> _takeProfitPips;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _breakoutPercent;
private readonly StrategyParam<int> _cooldownBars;
private decimal _stopPrice;
private decimal _takePrice;
private decimal? _prevUpper;
private decimal? _prevLower;
private decimal? _prevMiddle;
private int _cooldownRemaining;
public int BollingerLength { get => _bollingerLength.Value; set => _bollingerLength.Value = value; }
public decimal BollingerDeviation { get => _bollingerDeviation.Value; set => _bollingerDeviation.Value = value; }
public int TakeProfitPips { get => _takeProfitPips.Value; set => _takeProfitPips.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public decimal BreakoutPercent { get => _breakoutPercent.Value; set => _breakoutPercent.Value = value; }
public int CooldownBars { get => _cooldownBars.Value; set => _cooldownBars.Value = value; }
public BollingerBreakoutMomentumStrategy()
{
_bollingerLength = Param(nameof(BollingerLength), 18)
.SetDisplay("BB Length", "Bollinger Bands length", "Parameters");
_bollingerDeviation = Param(nameof(BollingerDeviation), 2m)
.SetDisplay("BB Deviation", "Bollinger Bands deviation", "Parameters");
_takeProfitPips = Param(nameof(TakeProfitPips), 200)
.SetDisplay("Take Profit (pips)", "Distance for profit target", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of working candles", "General");
_breakoutPercent = Param(nameof(BreakoutPercent), 0.002m)
.SetDisplay("Breakout %", "Minimum breakout beyond the Bollinger boundary", "Filters");
_cooldownBars = Param(nameof(CooldownBars), 4)
.SetDisplay("Cooldown Bars", "Completed candles to wait after a position change", "Trading");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_stopPrice = 0m;
_takePrice = 0m;
_prevUpper = null;
_prevLower = null;
_prevMiddle = null;
_cooldownRemaining = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var bollinger = new BollingerBands
{
Length = BollingerLength,
Width = BollingerDeviation
};
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(bollinger, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, bollinger);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue bbValue)
{
if (candle.State != CandleStates.Finished || !bbValue.IsFinal)
return;
if (_cooldownRemaining > 0)
_cooldownRemaining--;
var bb = (BollingerBandsValue)bbValue;
if (bb.UpBand is not decimal upper || bb.LowBand is not decimal lower || bb.MovingAverage is not decimal middle)
return;
var step = Security.PriceStep ?? 1m;
var price = candle.ClosePrice;
if (Position > 0)
{
if (candle.LowPrice <= _stopPrice || candle.HighPrice >= _takePrice)
{
SellMarket();
_cooldownRemaining = CooldownBars;
}
else
{
_stopPrice = Math.Max(_stopPrice, middle);
}
}
else if (Position < 0)
{
if (candle.HighPrice >= _stopPrice || candle.LowPrice <= _takePrice)
{
BuyMarket();
_cooldownRemaining = CooldownBars;
}
else
{
_stopPrice = Math.Min(_stopPrice, middle);
}
}
else if (_prevUpper is decimal prevUpper && _prevLower is decimal prevLower && _prevMiddle is decimal prevMiddle && _cooldownRemaining == 0)
{
var upperRising = upper > prevUpper && middle > prevMiddle;
var lowerFalling = lower < prevLower && middle < prevMiddle;
var buySignal = upperRising && price > upper * (1m + BreakoutPercent);
var sellSignal = lowerFalling && price < lower * (1m - BreakoutPercent);
if (buySignal)
{
BuyMarket();
_stopPrice = middle;
_takePrice = price + TakeProfitPips * step;
_cooldownRemaining = CooldownBars;
}
else if (sellSignal)
{
SellMarket();
_stopPrice = middle;
_takePrice = price - TakeProfitPips * step;
_cooldownRemaining = CooldownBars;
}
}
_prevUpper = upper;
_prevLower = lower;
_prevMiddle = middle;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import BollingerBands
from StockSharp.Algo.Strategies import Strategy
class bollinger_breakout_momentum_strategy(Strategy):
def __init__(self):
super(bollinger_breakout_momentum_strategy, self).__init__()
self._bollinger_length = self.Param("BollingerLength", 18) \
.SetDisplay("BB Length", "Bollinger Bands length", "Parameters")
self._bollinger_deviation = self.Param("BollingerDeviation", 2.0) \
.SetDisplay("BB Deviation", "Bollinger Bands deviation", "Parameters")
self._take_profit_pips = self.Param("TakeProfitPips", 200) \
.SetDisplay("Take Profit (pips)", "Distance for profit target", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of working candles", "General")
self._breakout_percent = self.Param("BreakoutPercent", 0.002) \
.SetDisplay("Breakout %", "Minimum breakout beyond the Bollinger boundary", "Filters")
self._cooldown_bars = self.Param("CooldownBars", 4) \
.SetDisplay("Cooldown Bars", "Completed candles to wait after a position change", "Trading")
self._stop_price = 0.0
self._take_price = 0.0
self._prev_upper = None
self._prev_lower = None
self._prev_middle = None
self._cooldown_remaining = 0
@property
def bollinger_length(self):
return self._bollinger_length.Value
@property
def bollinger_deviation(self):
return self._bollinger_deviation.Value
@property
def take_profit_pips(self):
return self._take_profit_pips.Value
@property
def candle_type(self):
return self._candle_type.Value
@property
def breakout_percent(self):
return self._breakout_percent.Value
@property
def cooldown_bars(self):
return self._cooldown_bars.Value
def OnReseted(self):
super(bollinger_breakout_momentum_strategy, self).OnReseted()
self._stop_price = 0.0
self._take_price = 0.0
self._prev_upper = None
self._prev_lower = None
self._prev_middle = None
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(bollinger_breakout_momentum_strategy, self).OnStarted2(time)
bollinger = BollingerBands()
bollinger.Length = self.bollinger_length
bollinger.Width = self.bollinger_deviation
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(bollinger, self.OnProcess).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, bollinger)
self.DrawOwnTrades(area)
def OnProcess(self, candle, bb_value):
if candle.State != CandleStates.Finished or not bb_value.IsFinal:
return
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
upper = bb_value.UpBand
lower = bb_value.LowBand
middle = bb_value.MovingAverage
if upper is None or lower is None or middle is None:
return
upper = float(upper)
lower = float(lower)
middle = float(middle)
step = self.Security.PriceStep
step = float(step) if step is not None else 1.0
price = float(candle.ClosePrice)
if self.Position > 0:
if float(candle.LowPrice) <= self._stop_price or float(candle.HighPrice) >= self._take_price:
self.SellMarket()
self._cooldown_remaining = self.cooldown_bars
else:
self._stop_price = max(self._stop_price, middle)
elif self.Position < 0:
if float(candle.HighPrice) >= self._stop_price or float(candle.LowPrice) <= self._take_price:
self.BuyMarket()
self._cooldown_remaining = self.cooldown_bars
else:
self._stop_price = min(self._stop_price, middle)
elif self._prev_upper is not None and self._prev_lower is not None and self._prev_middle is not None and self._cooldown_remaining == 0:
upper_rising = upper > self._prev_upper and middle > self._prev_middle
lower_falling = lower < self._prev_lower and middle < self._prev_middle
buy_signal = upper_rising and price > upper * (1.0 + float(self.breakout_percent))
sell_signal = lower_falling and price < lower * (1.0 - float(self.breakout_percent))
if buy_signal:
self.BuyMarket()
self._stop_price = middle
self._take_price = price + float(self.take_profit_pips) * step
self._cooldown_remaining = self.cooldown_bars
elif sell_signal:
self.SellMarket()
self._stop_price = middle
self._take_price = price - float(self.take_profit_pips) * step
self._cooldown_remaining = self.cooldown_bars
self._prev_upper = upper
self._prev_lower = lower
self._prev_middle = middle
def CreateClone(self):
return bollinger_breakout_momentum_strategy()