MACDヒストグラム リバーサルストラテジー
MACDヒストグラムはMACD線とそのシグナル線の差を表します。ゼロ以上またはゼロ以下へのクロスは、しばしばモメンタムの転換を示します。この戦略はそのゼロライン・クロスを取引し、パーセンテージストップでリスクを管理します。
テストでは年平均リターン約160%を示しています。外国為替市場で最も優れたパフォーマンスを発揮します。
各ローソク足でMACDヒストグラムが計算されます。負から正に転換すると、ロングポジションが開かれます。正から負への転換がショート売りを引き起こします。この戦略はゼロのクロスオーバーのみを探すため、取引はシンプルで通常は短期間です。
モメンタムが期待した方向に続かない場合、損失を抑えるためにストップが使用されます。
詳細
- エントリー条件: MACDヒストグラムがゼロをクロスする。
- ロング/ショート: 両方。
- エグジット条件: ストップロス。
- ストップ: はい、パーセンテージベース。
- デフォルト値:
FastPeriod= 12SlowPeriod= 26SignalPeriod= 9StopLossPercent= 2CandleType= 15 minute
- フィルター:
- カテゴリ: モメンタム
- 方向: 両方
- インジケーター: 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 Histogram Reversal strategy.
/// The position turns long when the MACD histogram (MACD - Signal) turns positive and short when it turns negative;
/// a zero histogram keeps its previous sign. A percent stop limits the loss.
/// </summary>
public class MacdHistogramReversalStrategy : Strategy
{
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<int> _signalPeriod;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _stopLossPercent;
private bool? _prevPositive;
/// <summary>
/// Fast EMA period.
/// </summary>
public int FastPeriod
{
get => _fastPeriod.Value;
set => _fastPeriod.Value = value;
}
/// <summary>
/// Slow EMA period.
/// </summary>
public int SlowPeriod
{
get => _slowPeriod.Value;
set => _slowPeriod.Value = value;
}
/// <summary>
/// Signal line period.
/// </summary>
public int SignalPeriod
{
get => _signalPeriod.Value;
set => _signalPeriod.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Stop-loss percentage.
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public MacdHistogramReversalStrategy()
{
_fastPeriod = Param(nameof(FastPeriod), 12)
.SetRange(8, 16)
.SetDisplay("Fast Period", "Fast EMA period for MACD", "MACD");
_slowPeriod = Param(nameof(SlowPeriod), 26)
.SetRange(20, 30)
.SetDisplay("Slow Period", "Slow EMA period for MACD", "MACD");
_signalPeriod = Param(nameof(SignalPeriod), 9)
.SetRange(7, 13)
.SetDisplay("Signal Period", "Signal line period", "MACD");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_stopLossPercent = Param(nameof(StopLossPercent), 2m)
.SetNotNegative()
.SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevPositive = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevPositive = null;
var macdHist = new MovingAverageConvergenceDivergenceHistogram
{
Macd =
{
ShortMa = { Length = FastPeriod },
LongMa = { Length = SlowPeriod },
},
SignalMa = { Length = SignalPeriod }
};
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(macdHist, 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);
DrawIndicator(area, macdHist);
DrawOwnTrades(area);
}
}
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 macdIv)
{
if (candle.State != CandleStates.Finished || !macdIv.IsFormed)
return;
var mv = (IMacdHistogramValue)macdIv;
if (mv.Macd is not decimal macdVal || mv.Signal is not decimal signalVal)
return;
var histogram = macdVal - signalVal;
if (histogram == 0)
return;
var positive = histogram > 0;
var wasPositive = _prevPositive;
_prevPositive = positive;
if (wasPositive is not bool previous || previous == positive || !IsFormedAndOnlineAndAllowTrading())
return;
if (positive && Position <= 0)
BuyMarket(Volume + Math.Abs(Position));
else if (!positive && Position >= 0)
SellMarket(Volume + Math.Abs(Position));
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
clr.AddReference("StockSharp.BusinessEntities")
from System import TimeSpan, Math, Decimal
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes, Level1Fields
from StockSharp.BusinessEntities import Subscription
from StockSharp.Algo.Indicators import MovingAverageConvergenceDivergenceHistogram
from StockSharp.Algo.Strategies import Strategy
class macd_histogram_reversal_strategy(Strategy):
"""
MACD Histogram Reversal strategy.
The position turns long when the MACD histogram (MACD - Signal) turns positive and short when it turns negative;
a zero histogram keeps its previous sign. A percent stop limits the loss.
"""
def __init__(self):
super(macd_histogram_reversal_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 12).SetRange(8, 16).SetDisplay("Fast Period", "Fast EMA period for MACD", "MACD")
self._slow_period = self.Param("SlowPeriod", 26).SetRange(20, 30).SetDisplay("Slow Period", "Slow EMA period for MACD", "MACD")
self._signal_period = self.Param("SignalPeriod", 9).SetRange(7, 13).SetDisplay("Signal Period", "Signal line period", "MACD")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(15))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0).SetNotNegative().SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk")
self._prev_positive = None
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(macd_histogram_reversal_strategy, self).OnReseted()
self._prev_positive = None
def OnStarted2(self, time):
super(macd_histogram_reversal_strategy, self).OnStarted2(time)
self._prev_positive = None
macd_hist = MovingAverageConvergenceDivergenceHistogram()
macd_hist.Macd.ShortMa.Length = self._fast_period.Value
macd_hist.Macd.LongMa.Length = self._slow_period.Value
macd_hist.SignalMa.Length = self._signal_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(macd_hist, self._process_candle).Start()
self.StartProtection(Unit(), Unit(Decimal(self._stop_loss_percent.Value), UnitTypes.Percent), useMarketOrders=True, isLocalStop=True)
# The stop has to see prices between candles, not only at their close.
for field in (Level1Fields.BestBidPrice, Level1Fields.BestAskPrice):
quotes = Subscription(DataType.Level1, self.Security)
quotes.MarketData.BuildField = field
self.SubscribeLevel1(quotes).Bind(self._observe_protection_quote).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, macd_hist)
self.DrawOwnTrades(area)
def _observe_protection_quote(self, quote):
# The high-level handler activates native protection before the callback, including between bars.
pass
def _process_candle(self, candle, macd_iv):
if candle.State != CandleStates.Finished or not macd_iv.IsFormed:
return
if macd_iv.Macd is None or macd_iv.Signal is None:
return
histogram = macd_iv.Macd - macd_iv.Signal
if histogram == 0:
return
positive = histogram > 0
was_positive = self._prev_positive
self._prev_positive = positive
if was_positive is None or was_positive == positive or not self.IsFormedAndOnlineAndAllowTrading():
return
if positive and self.Position <= 0:
self.BuyMarket(self.Volume + Math.Abs(self.Position))
elif not positive and self.Position >= 0:
self.SellMarket(self.Volume + Math.Abs(self.Position))
def CreateClone(self):
return macd_histogram_reversal_strategy()