GitHub で見る

レンジ相場ブレイクアウト戦略

この戦略は、3本の移動平均線が狭いバンド内に収束している静かな相場局面を検出します。価格がこのレンジの上または下にブレイクアウトすると、戦略はブレイクアウトの方向にエントリーし、生まれつつあるトレンドを捉えようとします。

システムは速い・中間・遅いSMAの間の差を観察します。これらの平均の最大差が指定された本数のバーにわたって設定されたしきい値を下回ると、市場は「レンジ相場」とみなされます。その期間の最高値と最安値がブレイクアウトレベルを定義します。

価格がこれらの極値を超えて終値を付けるとトレードが建てられます。ポジションは逆の条件によって保護されます。価格がレンジに戻ったり、レンジ幅の倍数の利益に達したりするとポジションが決済されます。

詳細

  • エントリー条件:
    • ロング: SMAの差がShakeThresholdを下回るRangeLength本のバーのレンジの後、価格がレンジの最高値より上で終値を付けたときにエントリー。
    • ショート: 同じレンジ条件の下、価格がレンジの最安値より下で終値を付けたときにエントリー。
  • ロング/ショート: 両方向。
  • エグジット条件:
    • ロング: 価格がレンジの安値より下に戻った場合、または利益が4 * (レンジ高値 - レンジ安値)を超えた場合に決済。
    • ショート: 価格がレンジの高値より上に戻った場合、または利益が4 * (レンジ高値 - レンジ安値)を超えた場合に決済。
  • ストップ: レンジの境界と利益の倍数に基づく暗黙的な退出。
  • デフォルト値:
    • FastSma = 38
    • MidSma = 140
    • SlowSma = 210
    • ShakeThreshold = 250
    • RangeLength = 200
    • CandleType = TimeSpan.FromMinutes(1)
  • フィルター:
    • カテゴリ: ブレイクアウト
    • 方向: 両方
    • インジケーター: SMA, Highest, Lowest
    • ストップ: はい
    • 複雑さ: 基本
    • 時間軸: イントラデイ
    • 季節性: いいえ
    • ニューラルネットワーク: いいえ
    • ダイバージェンス: いいえ
    • リスクレベル: 中
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>
/// Breakout strategy that waits for converging SMAs and trades on breakout.
/// </summary>
public class BreakTheRangeBoundStrategy : Strategy
{
	private readonly StrategyParam<int> _fastSma;
	private readonly StrategyParam<int> _slowSma;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevFast;
	private decimal _prevSlow;
	private decimal _prevClose;
	private bool _hasPrev;

	public int FastSma { get => _fastSma.Value; set => _fastSma.Value = value; }
	public int SlowSma { get => _slowSma.Value; set => _slowSma.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public BreakTheRangeBoundStrategy()
	{
		_fastSma = Param(nameof(FastSma), 10)
			.SetGreaterThanZero()
			.SetDisplay("Fast SMA", "Fast moving average period", "Parameters");

		_slowSma = Param(nameof(SlowSma), 50)
			.SetGreaterThanZero()
			.SetDisplay("Slow SMA", "Slow moving average period", "Parameters");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles", "General");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
		=> [(Security, CandleType)];

	protected override void OnReseted()
	{
		base.OnReseted();
		_prevFast = 0;
		_prevSlow = 0;
		_prevClose = 0;
		_hasPrev = false;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var fast = new ExponentialMovingAverage { Length = FastSma };
		var slow = new ExponentialMovingAverage { Length = SlowSma };

		SubscribeCandles(CandleType).Bind(fast, slow, ProcessCandle).Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
	{
		if (candle.State != CandleStates.Finished) return;

		var close = candle.ClosePrice;

		if (!_hasPrev)
		{
			_prevFast = fastValue;
			_prevSlow = slowValue;
			_prevClose = close;
			_hasPrev = true;
			return;
		}

		// Cross above slow SMA => buy breakout
		if (_prevClose <= _prevSlow && close > slowValue && fastValue > slowValue && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		// Cross below slow SMA => sell breakout
		else if (_prevClose >= _prevSlow && close < slowValue && fastValue < slowValue && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevFast = fastValue;
		_prevSlow = slowValue;
		_prevClose = close;
	}
}