Auf GitHub ansehen

Bollinger Volatility Breakout

Die Strategie verwendet abgeschlossene 5-Minuten-Kerzen und wartet auf vollständig gebildete Indikatoren und eine Handelsfreigabe. Alle gleitenden Statistiken enthalten die Signalkerze. C ist ihr Schlusskurs, M = SMA(C, 20), D = Populationsstandardabweichung(C, 20), U = M + 2 × D, L = M − 2 × D und A = ATR(14) mit Wilder-Glättung der True Range.

Hohe Volatilität liegt bei A >= SMA(A, 14) + 2 × Populationsstandardabweichung(A, 14) vor. Die Preisniveaus entsprechen dem oberen, mittleren und unteren Bollinger-Band.

Ohne Position wird bei bestätigter hoher Volatilität und C >= U gekauft beziehungsweise bei C <= L verkauft. Das Einstiegsvolumen ist Volume. Ein neuer Einstieg ist erst nach der Wartefrist und ohne ausstehende Order erlaubt. Für den Einstieg muss A > 0 gelten.

k = StopLossMultiplier. Schlusskurs und ATR der Einstiegskerze werden festgehalten: Long-Stop C_entry − k × A_entry, Short-Stop C_entry + k × A_entry. Auf jeder abgeschlossenen Kerze wird die gesamte tatsächliche Position per Market-Order geschlossen, wenn der Schlusskurs den festen Stop erreicht, für Long C <= M, für Short C >= M gilt oder die hohe Volatilität endet.

Nach einer Order sind neue Einstiege für die folgenden 84 abgeschlossenen Kerzen gesperrt; Ausstiege bleiben aktiv. Die Stop-Prüfung erfolgt zum Kerzenschluss, die Market-Order wird zum verfügbaren Preis ausgeführt. Der Stop-Abstand bleibt während der Position fest. Es gibt weder Take-Profit noch Trailing-Stop.

Standardparameter

BollingerPeriod = 20
BollingerDeviation = 2
AtrPeriod = 14
AtrDeviationMultiplier = 2
StopLossMultiplier = 2
CooldownBars = 84
CandleType = TimeSpan.FromMinutes(5).TimeFrame()
namespace StockSharp.Samples.Strategies;

using System;
using System.Collections.Generic;

using Ecng.Common;

using StockSharp.Algo;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

/// <summary>
/// Breakout strategy that trades Bollinger band breaks only when ATR expands beyond its recent regime.
/// </summary>
public class BollingerVolatilityBreakoutStrategy : Strategy
{
	private readonly StrategyParam<int> _bollingerPeriod;
	private readonly StrategyParam<decimal> _bollingerDeviation;
	private readonly StrategyParam<int> _atrPeriod;
	private readonly StrategyParam<decimal> _atrDeviationMultiplier;
	private readonly StrategyParam<decimal> _stopLossMultiplier;
	private readonly StrategyParam<int> _cooldownBars;
	private readonly StrategyParam<DataType> _candleType;

	private BollingerBands _bollingerBands;
	private AverageTrueRange _atr;
	private SimpleMovingAverage _atrSma;
	private StandardDeviation _atrStdDev;
	private decimal _stopPrice;
	private Order _pendingOrder;
	private int _cooldown;

	/// <summary>
	/// Period for Bollinger bands calculation.
	/// </summary>
	public int BollingerPeriod
	{
		get => _bollingerPeriod.Value;
		set => _bollingerPeriod.Value = value;
	}

	/// <summary>
	/// Standard deviation multiplier for Bollinger bands.
	/// </summary>
	public decimal BollingerDeviation
	{
		get => _bollingerDeviation.Value;
		set => _bollingerDeviation.Value = value;
	}

	/// <summary>
	/// Period for ATR calculation.
	/// </summary>
	public int AtrPeriod
	{
		get => _atrPeriod.Value;
		set => _atrPeriod.Value = value;
	}

	/// <summary>
	/// ATR standard deviation multiplier used for volatility confirmation.
	/// </summary>
	public decimal AtrDeviationMultiplier
	{
		get => _atrDeviationMultiplier.Value;
		set => _atrDeviationMultiplier.Value = value;
	}

	/// <summary>
	/// ATR multiplier used for stop distance.
	/// </summary>
	public decimal StopLossMultiplier
	{
		get => _stopLossMultiplier.Value;
		set => _stopLossMultiplier.Value = value;
	}

	/// <summary>
	/// Bars to wait after each order.
	/// </summary>
	public int CooldownBars
	{
		get => _cooldownBars.Value;
		set => _cooldownBars.Value = value;
	}

	/// <summary>
	/// Candle type.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Initializes strategy parameters.
	/// </summary>
	public BollingerVolatilityBreakoutStrategy()
	{
		_bollingerPeriod = Param(nameof(BollingerPeriod), 20)
			.SetRange(5, 100)
			.SetDisplay("Bollinger Period", "Period for Bollinger band calculation", "Indicators");

		_bollingerDeviation = Param(nameof(BollingerDeviation), 2m)
			.SetRange(0.5m, 5m)
			.SetDisplay("Bollinger Deviation", "Standard deviation multiplier for Bollinger bands", "Indicators");

		_atrPeriod = Param(nameof(AtrPeriod), 14)
			.SetRange(5, 50)
			.SetDisplay("ATR Period", "Period for ATR calculation", "Indicators");

		_atrDeviationMultiplier = Param(nameof(AtrDeviationMultiplier), 2m)
			.SetRange(0.1m, 5m)
			.SetDisplay("ATR Deviation Multiplier", "ATR regime threshold multiplier", "Signals");

		_stopLossMultiplier = Param(nameof(StopLossMultiplier), 2m)
			.SetRange(0.5m, 10m)
			.SetDisplay("Stop Loss Multiplier", "ATR multiplier used for stop distance", "Risk");

		_cooldownBars = Param(nameof(CooldownBars), 84)
			.SetRange(1, 500)
			.SetDisplay("Cooldown Bars", "Bars to wait after each order", "Risk");

		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles for the strategy", "General");
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		if (Security != null)
			yield return (Security, CandleType);
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();

		_bollingerBands = null;
		_atr = null;
		_atrSma = null;
		_atrStdDev = null;
		_stopPrice = 0m;
		_pendingOrder = null;
		_cooldown = 0;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		if (Security == null)
			throw new InvalidOperationException("Security is not specified.");

		_bollingerBands = new BollingerBands
		{
			Length = BollingerPeriod,
			Width = BollingerDeviation,
		};
		_atr = new AverageTrueRange { Length = AtrPeriod };
		_atrSma = new SimpleMovingAverage { Length = AtrPeriod };
		_atrStdDev = new StandardDeviation { Length = AtrPeriod };
		_cooldown = 0;

		var subscription = SubscribeCandles(CandleType);

		subscription
			.BindEx(_bollingerBands, ProcessCandle)
			.Start();

		var area = CreateChartArea();

		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, _bollingerBands);
			DrawIndicator(area, _atr);
			DrawOwnTrades(area);
		}
	}

	private bool IsOrderPending => _pendingOrder is not null && _pendingOrder.State is not (OrderStates.Done or OrderStates.Failed);

	private void ProcessCandle(ICandleMessage candle, IIndicatorValue bollingerValue)
	{
		if (candle.State != CandleStates.Finished)
			return;

		var typedBands = (BollingerBandsValue)bollingerValue;

		if (typedBands.UpBand is not decimal upperBand ||
			typedBands.LowBand is not decimal lowerBand ||
			typedBands.MovingAverage is not decimal middleBand)
			return;

		var atrValue = _atr.Process(candle).ToDecimal();
		var atrAverageValue = _atrSma.Process(atrValue, candle.OpenTime, true).ToDecimal();
		var atrStdDevValue = _atrStdDev.Process(atrValue, candle.OpenTime, true).ToDecimal();

		if (!_bollingerBands.IsFormed || !_atr.IsFormed || !_atrSma.IsFormed || !_atrStdDev.IsFormed)
			return;

		var isCoolingDown = _cooldown > 0;
		if (isCoolingDown)
			_cooldown--;

		if (!IsFormedAndOnlineAndAllowTrading() || IsOrderPending)
			return;

		var volatilityThreshold = atrAverageValue + AtrDeviationMultiplier * atrStdDevValue;
		var isHighVolatility = atrValue >= volatilityThreshold;
		var price = candle.ClosePrice;

		if (Position == 0)
		{
			if (isCoolingDown || !isHighVolatility || atrValue <= 0m)
				return;

			if (price >= upperBand)
			{
				_stopPrice = price - atrValue * StopLossMultiplier;
				_pendingOrder = BuyMarket();
				_cooldown = CooldownBars;
			}
			else if (price <= lowerBand)
			{
				_stopPrice = price + atrValue * StopLossMultiplier;
				_pendingOrder = SellMarket();
				_cooldown = CooldownBars;
			}

			return;
		}

		if (Position > 0)
		{
			if (price <= middleBand || !isHighVolatility || price <= _stopPrice)
			{
				_pendingOrder = SellMarket(Math.Abs(Position));
				_cooldown = CooldownBars;
			}
		}
		else if (Position < 0)
		{
			if (price >= middleBand || !isHighVolatility || price >= _stopPrice)
			{
				_pendingOrder = BuyMarket(Math.Abs(Position));
				_cooldown = CooldownBars;
			}
		}
	}
}