GitHub で見る

モメンタム・ダイバージェンス戦略

モメンタム・ダイバージェンス戦略は、モメンタムの読みを価格方向と比較して、反転の早期兆候を発見します。ダイバージェンスは、価格が新しい極値を作るのにモメンタム指標が確認できない場合に発生し、勢いの弱まりを示唆します。

テストによると、平均年間リターンは約106%です。株式市場で最も高いパフォーマンスを発揮します。

価格がより低い安値を記録しながらモメンタムオシレーターがより高い安値を示す時に強気セットアップが発生します。価格がより高い高値を押し上げるがモメンタムが追随しない時に弱気セットアップが形成されます。モメンタムがゼロに戻るか、ダイバージェンスが無効になるとポジションが決済されます。

このアプローチは、トレンドを追うのではなく転換点を予測しようとするトレーダーにアピールします。ダイバージェンスシグナルに反してマーケットが動き続ける場合のリスクを管理するためにストップを使用します。

詳細

  • エントリー条件:
    • ロング: 価格がより低い安値を作る && Momentumがより高い安値を示す
    • ショート: 価格がより高い高値を作る && Momentumがより低い高値を示す
  • ロング/ショート: 両方。
  • エグジット条件:
    • ロング: モメンタムがゼロを下抜けた時に決済
    • ショート: モメンタムがゼロを上抜けた時に決済
  • ストップ: あり、固定ストップロス。
  • デフォルト値:
    • MomentumPeriod = 14
    • StopLossPercent = 2 安値切り下げは終値が前の終値を下回る一方で、モメンタム(終値からMomentumPeriod本前の終値を引いた値)が前の値を上回ることを指し、高値切り上げはその逆です。ゼロクロス決済はエントリー後にモメンタムがゼロを通過するのを待ちます。固定ストップはエントリー価格のStopLossPercentで、ローソク足の間も監視されます。0で無効になります。どのルールも移動平均を使わないため、MaPeriodは削除しました。 保有ポジションと逆方向のエントリーシグナルはドテンになります。
    • CandleType = TimeSpan.FromMinutes(5)
  • フィルター:
    • カテゴリ: リバーサル
    • 方向: 両方
    • インジケーター: Momentum
    • ストップ: あり
    • 複雑さ: 中級
    • 時間軸: イントラデイ
    • 季節性: いいえ
    • ニューラルネットワーク: いいえ
    • ダイバージェンス: はい
    • リスクレベル: 中
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>
/// Momentum Divergence strategy.
/// A close below the previous close while MomentumPeriod momentum rises above its previous value is a bullish divergence and goes long;
/// a close above the previous close while momentum falls is a bearish one and goes short, reversing an opposite position. A long closes
/// when momentum crosses below zero and a short when it crosses above zero, and a percent stop limits the loss.
/// </summary>
public class MomentumDivergenceStrategy : Strategy
{
	private readonly StrategyParam<int> _momentumPeriod;
	private readonly StrategyParam<decimal> _stopLossPercent;
	private readonly StrategyParam<DataType> _candleType;

	private decimal? _prevClose;
	private decimal? _prevMomentum;

	/// <summary>
	/// Period of the momentum indicator.
	/// </summary>
	public int MomentumPeriod
	{
		get => _momentumPeriod.Value;
		set => _momentumPeriod.Value = value;
	}

	/// <summary>
	/// Stop loss percentage from entry price.
	/// </summary>
	public decimal StopLossPercent
	{
		get => _stopLossPercent.Value;
		set => _stopLossPercent.Value = value;
	}

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

	/// <summary>
	/// Constructor.
	/// </summary>
	public MomentumDivergenceStrategy()
	{
		_momentumPeriod = Param(nameof(MomentumPeriod), 14)
			.SetGreaterThanZero()
			.SetDisplay("Momentum Period", "Period of the momentum indicator", "Indicators");

		_stopLossPercent = Param(nameof(StopLossPercent), 2m)
			.SetNotNegative()
			.SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk");

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

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		return [(Security, CandleType)];
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevClose = null;
		_prevMomentum = null;
	}

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

		_prevClose = null;
		_prevMomentum = null;

		var momentum = new Momentum { Length = MomentumPeriod };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.BindEx(momentum, ProcessCandle)
			.Start();

		StartProtection(new Unit(), new Unit(StopLossPercent, UnitTypes.Percent), useMarketOrders: true, isLocalStop: true);

		// The stop has to see prices between candles, not only at their close.
		foreach (var field in new[] { Level1Fields.BestBidPrice, Level1Fields.BestAskPrice })
		{
			var quotes = new Subscription(DataType.Level1, Security);
			quotes.MarketData.BuildField = field;
			SubscribeLevel1(quotes).Bind(ObserveProtectionQuote).Start();
		}

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawOwnTrades(area);

			var oscillators = CreateChartArea();
			if (oscillators != null)
			{
				DrawIndicator(oscillators, momentum);
			}
		}
	}

	private void ObserveProtectionQuote(Level1ChangeMessage quote)
	{
		// The high-level handler activates native protection before this callback, also between signal bars.
	}

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

		if (!momentumValue.IsFormed)
			return;

		var close = candle.ClosePrice;
		var value = momentumValue.GetValue<decimal>();
		var prevClose = _prevClose;
		var prevMomentum = _prevMomentum;
		_prevClose = close;
		_prevMomentum = value;

		if (prevClose is not decimal lastClose || prevMomentum is not decimal lastMomentum)
			return;

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		var bullish = close < lastClose && value > lastMomentum;
		var bearish = close > lastClose && value < lastMomentum;

		if (bullish && Position <= 0)
			BuyMarket(Volume + Math.Abs(Position));
		else if (bearish && Position >= 0)
			SellMarket(Volume + Math.Abs(Position));
		else if (Position > 0 && lastMomentum >= 0 && value < 0)
			SellMarket(Position);
		else if (Position < 0 && lastMomentum <= 0 && value > 0)
			BuyMarket(-Position);
	}
}