GitHub で見る

MACDダイバージェンス (MACD Divergence)

MACDダイバージェンスは、価格の動きとMACDインジケーターの乖離を探します。価格がより高い高値を付けているにもかかわらずMACDの高値が低下している場合はモメンタムの弱体化(弱気ダイバージェンス)を示し、価格がより低い安値を付けているにもかかわらずMACDの安値が上昇している場合は強気リバーサルの可能性を示します。

テストでは年平均リターンが約70%となっています。株式市場での運用に最も適しています。

ダイバージェンスを検出した後、システムはMACDがシグナルラインをクロスするのを待ってからエントリーします。MACDが逆方向にクロスするかストップロスが発動した場合にトレードを決済します。

詳細

  • エントリー条件: 強気または弱気ダイバージェンス、かつMACDがシグナルラインをクロス。
  • ロング/ショート: 両方。
  • エグジット条件: MACDが逆方向にクロスするかストップ。
  • ストップ: はい。
  • デフォルト値:
    • FastMacdPeriod = 12
    • SlowMacdPeriod = 26
    • SignalPeriod = 9
    • DivergencePeriod = 5
    • CandleType = TimeSpan.FromMinutes(15)
    • StopLossPercent = 2.0m
  • フィルター:
    • カテゴリ: ダイバージェンス
    • 方向: 両方
    • インジケーター: MACD
    • ストップ: はい
    • 複雑さ: 中級
    • 時間軸: イントラデイ
    • 季節性: いいえ
    • ニューラルネットワーク: いいえ
    • ダイバージェンス: はい
    • リスクレベル: 中
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>
/// MACD Divergence strategy.
/// Detects divergences between price and MACD for reversal signals.
/// Bullish: price falling but MACD rising.
/// Bearish: price rising but MACD falling.
/// </summary>
public class MacdDivergenceStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _cooldownBars;

	private decimal _prevPrice;
	private decimal _prevMacd;
	private int _cooldown;

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

	/// <summary>
	/// Cooldown bars between trades.
	/// </summary>
	public int CooldownBars
	{
		get => _cooldownBars.Value;
		set => _cooldownBars.Value = value;
	}

	/// <summary>
	/// Constructor.
	/// </summary>
	public MacdDivergenceStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles to use", "General");

		_cooldownBars = Param(nameof(CooldownBars), 500)
			.SetRange(1, 1000)
			.SetDisplay("Cooldown Bars", "Bars to wait between trades", "General");
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevPrice = default;
		_prevMacd = default;
		_cooldown = default;
	}

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

		_prevPrice = 0;
		_prevMacd = 0;
		_cooldown = 0;

		var macd = new MovingAverageConvergenceDivergenceSignal();

		var subscription = SubscribeCandles(_candleType.Value);
		subscription
			.BindEx(macd, ProcessCandle)
			.Start();

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

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

		if (!macdValue.IsFormed)
			return;

		var macdTyped = (MovingAverageConvergenceDivergenceSignalValue)macdValue;

		if (macdTyped.Macd is not decimal macdLine || macdTyped.Signal is not decimal signal)
			return;

		if (_prevPrice == 0)
		{
			_prevPrice = candle.ClosePrice;
			_prevMacd = macdLine;
			return;
		}

		if (_cooldown > 0)
		{
			_cooldown--;
			_prevPrice = candle.ClosePrice;
			_prevMacd = macdLine;
			return;
		}

		// Bullish divergence: price down but MACD up
		var bullishDiv = candle.ClosePrice < _prevPrice && macdLine > _prevMacd;
		// Bearish divergence: price up but MACD down
		var bearishDiv = candle.ClosePrice > _prevPrice && macdLine < _prevMacd;

		if (Position == 0 && bullishDiv && macdLine > signal)
		{
			BuyMarket();
			_cooldown = CooldownBars;
		}
		else if (Position == 0 && bearishDiv && macdLine < signal)
		{
			SellMarket();
			_cooldown = CooldownBars;
		}
		else if (Position > 0 && macdLine < signal)
		{
			SellMarket();
			_cooldown = CooldownBars;
		}
		else if (Position < 0 && macdLine > signal)
		{
			BuyMarket();
			_cooldown = CooldownBars;
		}

		_prevPrice = candle.ClosePrice;
		_prevMacd = macdLine;
	}
}