GitHub で見る

MACD EMA SAR Bollinger BullBear戦略

MACD、EMAクロス、Parabolic SAR、ボリンジャーバンド、Bulls/Bears Powerインジケーターを組み合わせます。アクティブな時間帯のみ取引します。

詳細

  • エントリー条件:
    • ロング: MACD < Signal、直近2つの高値がボリンジャーバンド上限を下回る、EMA3 > EMA34、SARが価格を下回る、Bulls Power > 0 かつ減少中。
    • ショート: MACD > Signal、EMA3 < EMA34、SARが価格を上回る、Bears Power < 0 かつ増加中。
  • ロング/ショート: 両方向。
  • エグジット条件:
    • 専用の決済ルールなし。反対のシグナルでポジションをクローズ。
  • ストップ: なし。
  • デフォルト値:
    • MACD Fast = 12
    • MACD Slow = 26
    • MACD Signal = 9
    • Fast EMA Period = 3
    • Slow EMA Period = 34
    • Power Period = 13
    • SAR Step = 0.02
    • SAR Max = 0.2
    • Bollinger Period = 20
    • Bollinger Deviation = 2.0
    • Candle Type = 15分
    • Session Start = 09:00
    • Session End = 17:00
  • フィルター:
    • カテゴリ: トレンドフォロー
    • 方向: 両方
    • インジケーター: 複数
    • ストップ: いいえ
    • 複雑さ: 中級
    • 時間軸: イントラデイ
    • 季節性: いいえ
    • ニューラルネットワーク: いいえ
    • ダイバージェンス: いいえ
    • リスクレベル: 中
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>
/// Strategy based on MACD histogram, EMA crossover and Parabolic SAR confirmation.
/// Buys when MACD histogram positive, fast EMA above slow EMA, SAR below price.
/// Sells on opposite conditions.
/// </summary>
public class MacdEmaSarBollingerBullBearStrategy : Strategy
{
	private readonly StrategyParam<int> _fastMaPeriod;
	private readonly StrategyParam<int> _slowMaPeriod;
	private readonly StrategyParam<DataType> _candleType;

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

	public int FastMaPeriod { get => _fastMaPeriod.Value; set => _fastMaPeriod.Value = value; }
	public int SlowMaPeriod { get => _slowMaPeriod.Value; set => _slowMaPeriod.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public MacdEmaSarBollingerBullBearStrategy()
	{
		_fastMaPeriod = Param(nameof(FastMaPeriod), 8)
			.SetGreaterThanZero()
			.SetDisplay("Fast EMA", "Fast EMA period", "Indicators");

		_slowMaPeriod = Param(nameof(SlowMaPeriod), 21)
			.SetGreaterThanZero()
			.SetDisplay("Slow EMA", "Slow EMA period", "Indicators");

		_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;
		_hasPrev = false;
	}

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

		var fastEma = new ExponentialMovingAverage { Length = FastMaPeriod };
		var slowEma = new ExponentialMovingAverage { Length = SlowMaPeriod };
		var sar = new ParabolicSar();
		var macd = new MovingAverageConvergenceDivergence();

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(fastEma, slowEma, sar, macd, ProcessCandle)
			.Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow, decimal sarVal, decimal macdVal)
	{
		if (candle.State != CandleStates.Finished)
			return;

		if (!_hasPrev)
		{
			_prevFast = fast;
			_prevSlow = slow;
			_hasPrev = true;
			return;
		}

		var close = candle.ClosePrice;

		// Buy: EMA crossover up + SAR below
		var buySignal = _prevFast <= _prevSlow && fast > slow &&
			sarVal < close;

		// Sell: EMA crossover down + SAR above
		var sellSignal = _prevFast >= _prevSlow && fast < slow &&
			sarVal > close;

		if (buySignal)
		{
			if (Position < 0)
				BuyMarket();
			if (Position <= 0)
				BuyMarket();
		}
		else if (sellSignal)
		{
			if (Position > 0)
				SellMarket();
			if (Position >= 0)
				SellMarket();
		}

		_prevFast = fast;
		_prevSlow = slow;
	}
}