在 GitHub 上查看

Bollinger 带宽突破策略

该策略跟踪布林带宽度的迅速扩张。当数值超出常态时,价格往往开始新的波动。

测试表明年均收益约为 109%,该策略在加密市场表现最佳。

当带宽突破根据历史数据与偏差倍数设定的区间时开仓,可做多也可做空,并配合止损。带宽回到平均水平即平仓。

适合动量交易者捕捉波动初期的扩张。

详细信息

  • 入场条件: Indicator exceeds average by deviation multiplier.
  • Long/Short: 双向 directions.
  • 退出条件: Indicator reverts to average.
  • 止损: 是
  • 默认值:
    • BollingerLength = 20
    • BollingerDeviation = 2.0m
    • AvgPeriod = 20
    • Multiplier = 2.0m
    • CandleType = TimeSpan.FromMinutes(5)
    • StopMultiplier = 2
  • 筛选条件:
    • 类别: 突破
    • 方向: 双向
    • 指标: Bollinger
    • 止损: 是
    • 复杂度: 中等
    • 时间框架: 短期
    • 季节性: 否
    • 神经网络: 否
    • 背离: 否
    • 风险等级: 中等
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>
/// Strategy that trades on Bollinger Band width breakouts.
/// When Bollinger Band width increases significantly above its average, 
/// it enters position in the direction determined by price movement.
/// </summary>
public class BollingerWidthBreakoutStrategy : Strategy
{
	private readonly StrategyParam<int> _bollingerLength;
	private readonly StrategyParam<decimal> _bollingerDeviation;
	private readonly StrategyParam<int> _avgPeriod;
	private readonly StrategyParam<decimal> _multiplier;
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _stopMultiplier;
	
	private BollingerBands _bollinger;
	private SimpleMovingAverage _widthAverage;
	private AverageTrueRange _atr;

	/// <summary>
	/// Bollinger Bands period.
	/// </summary>
	public int BollingerLength
	{
		get => _bollingerLength.Value;
		set => _bollingerLength.Value = value;
	}
	
	/// <summary>
	/// Bollinger Bands standard deviation multiplier.
	/// </summary>
	public decimal BollingerDeviation
	{
		get => _bollingerDeviation.Value;
		set => _bollingerDeviation.Value = value;
	}
	
	/// <summary>
	/// Period for width average calculation.
	/// </summary>
	public int AvgPeriod
	{
		get => _avgPeriod.Value;
		set => _avgPeriod.Value = value;
	}
	
	/// <summary>
	/// Standard deviation multiplier for breakout detection.
	/// </summary>
	public decimal Multiplier
	{
		get => _multiplier.Value;
		set => _multiplier.Value = value;
	}
	
	/// <summary>
	/// Candle type for strategy.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}
	
	/// <summary>
	/// Stop-loss ATR multiplier.
	/// </summary>
	public int StopMultiplier
	{
		get => _stopMultiplier.Value;
		set => _stopMultiplier.Value = value;
	}
	
	/// <summary>
	/// Initialize <see cref="BollingerWidthBreakoutStrategy"/>.
	/// </summary>
	public BollingerWidthBreakoutStrategy()
	{
		_bollingerLength = Param(nameof(BollingerLength), 20)
			.SetGreaterThanZero()
			.SetDisplay("Bollinger Length", "Period of the Bollinger Bands indicator", "Indicators")
			
			.SetOptimize(10, 50, 5);
			
		_bollingerDeviation = Param(nameof(BollingerDeviation), 2.0m)
			.SetGreaterThanZero()
			.SetDisplay("Bollinger Deviation", "Standard deviation multiplier for Bollinger Bands", "Indicators")
			
			.SetOptimize(1.0m, 3.0m, 0.5m);
		
		_avgPeriod = Param(nameof(AvgPeriod), 20)
			.SetGreaterThanZero()
			.SetDisplay("Average Period", "Period for Bollinger width average calculation", "Indicators")
			
			.SetOptimize(10, 50, 5);
		
		_multiplier = Param(nameof(Multiplier), 1.5m)
			.SetGreaterThanZero()
			.SetDisplay("Multiplier", "Standard deviation multiplier for breakout detection", "Indicators")

			.SetOptimize(1.0m, 3.0m, 0.5m);
		
		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles to use", "General");
		
		_stopMultiplier = Param(nameof(StopMultiplier), 2)
			.SetGreaterThanZero()
			.SetDisplay("Stop Multiplier", "ATR multiplier for stop-loss", "Risk Management")
			
			.SetOptimize(1, 5, 1);
	}
	
	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		return [(Security, CandleType)];
	}
	
	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
	}

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


		// Create indicators
		_bollinger = new BollingerBands
		{
			Length = BollingerLength,
			Width = BollingerDeviation
		};
		
		_widthAverage = new SMA { Length = AvgPeriod };
		_atr = new AverageTrueRange { Length = BollingerLength };
		
		// Create subscription
		var subscription = SubscribeCandles(CandleType);
		
		// Bind Bollinger Bands
		subscription
			.BindEx(_bollinger, _atr, ProcessBollinger)
			.Start();

		StartProtection(
			takeProfit: new Unit(2, UnitTypes.Percent),
			stopLoss: new Unit(1, UnitTypes.Percent)
		);

		// Create chart area for visualization
		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, _bollinger);
			DrawOwnTrades(area);
		}
	}
	
	private void ProcessBollinger(ICandleMessage candle, IIndicatorValue bollingerValue, IIndicatorValue atrValue)
	{
		if (candle.State != CandleStates.Finished)
			return;

		if (!bollingerValue.IsFinal || !atrValue.IsFinal || bollingerValue.IsEmpty || atrValue.IsEmpty)
			return;
		
		// Calculate Bollinger Band width
		if (bollingerValue is not BollingerBandsValue bollingerTyped)
			return;

		if (bollingerTyped.UpBand is not decimal upperBand)
			return;

		if (bollingerTyped.LowBand is not decimal lowerBand)
			return;

		var lastWidth = upperBand - lowerBand;

		// Process width through average
		var widthAvgValue = _widthAverage.Process(new DecimalIndicatorValue(_widthAverage, lastWidth, candle.ServerTime) { IsFinal = true });
		var avgWidth = widthAvgValue.ToDecimal();
		
		// Skip if indicators are not formed yet
		if (!_widthAverage.IsFormed)
		{
			return;
		}

		// Bollinger width breakout detection
		if (lastWidth > avgWidth * (1m + Multiplier / 10m))
		{
			// Determine direction based on price and bands
			var upperDistance = (candle.ClosePrice - upperBand).Abs();
			var lowerDistance = (candle.ClosePrice - lowerBand).Abs();
			var priceDirection = upperDistance < lowerDistance;

			if (priceDirection && Position == 0)
			{
				BuyMarket();
			}
			else if (!priceDirection && Position == 0)
			{
				SellMarket();
			}
		}
	}
}