ATR MACD 戦略
ATR MACD は、MACD クロスオーバーでトレードする際に Average True Range のボラティリティをポジションサイズの調整に使用します。 ATR の値が大きいほどトレードサイズが小さくなり、異なる市場局面でもリスクを一定に保ちます。
テストでは平均年間リターンは約154%を示しています。株式市場で最も良いパフォーマンスを発揮します。
MACD がシグナルラインをクロスしたときにエントリーし、反対のクロスオーバーまたはパーセントストップでイグジットします。
この組み合わせは、変化するボラティリティを考慮しながらモメンタムを捉えることを目指します。
詳細
- エントリー条件: インジケーターシグナル
- ロング/ショート: 両方
- エグジット条件: ストップロスまたは反対シグナル
- ストップ: はい、パーセントベース
- デフォルト値:
CandleType= 15 minuteStopLossPercent= 2MacdFast= 12MacdSlow= 26MacdSignal= 9AtrPeriod= 14AtrAvgPeriod= 20 MACDがシグナル線を上抜ければ買い、下抜ければ売り、反対のクロスでドテンします。新しいポジションのサイズは、Volumeに直近AtrAvgPeriod個のATRの平均を掛けて現在のATRで割り、数量刻みに切り下げた値です。
- フィルター:
- カテゴリ: トレンドフォロー
- 方向: 両方
- インジケーター: ATR, MACD
- ストップ: はい
- 複雑さ: 中級
- 時間軸: イントラデイ
- 季節性: いいえ
- ニューラルネットワーク: いいえ
- ダイバージェンス: いいえ
- リスクレベル: 中
using System;
using System.Collections.Generic;
using System.Linq;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// ATR MACD strategy.
/// A MACD cross above its signal line goes long and a cross below goes short, the opposite cross reversing the position.
/// Each new position is sized as Volume times the average of the last AtrAvgPeriod ATR values divided by the current ATR,
/// rounded down to the volume step, so higher volatility trades smaller. A percent stop limits the loss.
/// </summary>
public class AtrMacdStrategy : Strategy
{
private readonly StrategyParam<int> _macdFast;
private readonly StrategyParam<int> _macdSlow;
private readonly StrategyParam<int> _macdSignal;
private readonly StrategyParam<int> _atrPeriod;
private readonly StrategyParam<int> _atrAvgPeriod;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
private bool? _prevAbove;
private readonly List<decimal> _atrs = [];
/// <summary>
/// Fast EMA period of MACD.
/// </summary>
public int MacdFast
{
get => _macdFast.Value;
set => _macdFast.Value = value;
}
/// <summary>
/// Slow EMA period of MACD.
/// </summary>
public int MacdSlow
{
get => _macdSlow.Value;
set => _macdSlow.Value = value;
}
/// <summary>
/// Signal line period of MACD.
/// </summary>
public int MacdSignal
{
get => _macdSignal.Value;
set => _macdSignal.Value = value;
}
/// <summary>
/// Period of ATR.
/// </summary>
public int AtrPeriod
{
get => _atrPeriod.Value;
set => _atrPeriod.Value = value;
}
/// <summary>
/// ATR values the typical volatility is averaged over.
/// </summary>
public int AtrAvgPeriod
{
get => _atrAvgPeriod.Value;
set => _atrAvgPeriod.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 AtrMacdStrategy()
{
_macdFast = Param(nameof(MacdFast), 12)
.SetGreaterThanZero()
.SetDisplay("MACD Fast", "Fast EMA period of MACD", "MACD");
_macdSlow = Param(nameof(MacdSlow), 26)
.SetGreaterThanZero()
.SetDisplay("MACD Slow", "Slow EMA period of MACD", "MACD");
_macdSignal = Param(nameof(MacdSignal), 9)
.SetGreaterThanZero()
.SetDisplay("MACD Signal", "Signal line period of MACD", "MACD");
_atrPeriod = Param(nameof(AtrPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("ATR Period", "Period of ATR", "Sizing");
_atrAvgPeriod = Param(nameof(AtrAvgPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("ATR Average Period", "ATR values the typical volatility is averaged over", "Sizing");
_stopLossPercent = Param(nameof(StopLossPercent), 2m)
.SetNotNegative()
.SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).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();
_prevAbove = null;
_atrs.Clear();
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevAbove = null;
_atrs.Clear();
var macd = new MovingAverageConvergenceDivergenceSignal
{
Macd =
{
ShortMa = { Length = MacdFast },
LongMa = { Length = MacdSlow },
},
SignalMa = { Length = MacdSignal }
};
var atr = new AverageTrueRange { Length = AtrPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(macd, atr, 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, macd);
DrawIndicator(oscillators, atr);
}
}
}
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 macdValue, IIndicatorValue atrValue)
{
if (candle.State != CandleStates.Finished)
return;
if (atrValue.IsFormed)
{
_atrs.Add(atrValue.GetValue<decimal>());
if (_atrs.Count > AtrAvgPeriod)
_atrs.RemoveAt(0);
}
if (!macdValue.IsFormed)
return;
var macdTyped = (MovingAverageConvergenceDivergenceSignalValue)macdValue;
if (macdTyped.Macd is not decimal macd || macdTyped.Signal is not decimal signal)
return;
var isAbove = macd > signal;
var wasAbove = _prevAbove;
_prevAbove = isAbove;
if (wasAbove is not bool was || was == isAbove || _atrs.Count < AtrAvgPeriod)
return;
var currentAtr = _atrs[^1];
if (currentAtr <= 0 || !IsFormedAndOnlineAndAllowTrading())
return;
var size = Volume * _atrs.Average() / currentAtr;
if (Security?.VolumeStep is decimal step && step > 0)
size = Math.Max(step, Math.Floor(size / step) * step);
if (isAbove && Position <= 0)
BuyMarket(size + Math.Abs(Position));
else if (!isAbove && Position >= 0)
SellMarket(size + 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, Decimal, Math
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes, Level1Fields
from StockSharp.BusinessEntities import Subscription
from StockSharp.Algo.Indicators import MovingAverageConvergenceDivergenceSignal, AverageTrueRange
from StockSharp.Algo.Strategies import Strategy
class atr_macd_strategy(Strategy):
"""
ATR MACD strategy.
A MACD cross above its signal line goes long and a cross below goes short, the opposite cross reversing the position.
Each new position is sized as Volume times the average of the last AtrAvgPeriod ATR values divided by the current ATR,
rounded down to the volume step, so higher volatility trades smaller. A percent stop limits the loss.
"""
def __init__(self):
super(atr_macd_strategy, self).__init__()
self._macd_fast = self.Param("MacdFast", 12).SetGreaterThanZero().SetDisplay("MACD Fast", "Fast EMA period of MACD", "MACD")
self._macd_slow = self.Param("MacdSlow", 26).SetGreaterThanZero().SetDisplay("MACD Slow", "Slow EMA period of MACD", "MACD")
self._macd_signal = self.Param("MacdSignal", 9).SetGreaterThanZero().SetDisplay("MACD Signal", "Signal line period of MACD", "MACD")
self._atr_period = self.Param("AtrPeriod", 14).SetGreaterThanZero().SetDisplay("ATR Period", "Period of ATR", "Sizing")
self._atr_avg_period = self.Param("AtrAvgPeriod", 20).SetGreaterThanZero().SetDisplay("ATR Average Period", "ATR values the typical volatility is averaged over", "Sizing")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0).SetNotNegative().SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(15))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._reset_state()
@property
def candle_type(self):
return self._candle_type.Value
def _reset_state(self):
self._prev_above = None
self._atrs = []
def OnReseted(self):
super(atr_macd_strategy, self).OnReseted()
self._reset_state()
def OnStarted2(self, time):
super(atr_macd_strategy, self).OnStarted2(time)
self._reset_state()
macd = MovingAverageConvergenceDivergenceSignal()
macd.Macd.ShortMa.Length = self._macd_fast.Value
macd.Macd.LongMa.Length = self._macd_slow.Value
macd.SignalMa.Length = self._macd_signal.Value
atr = AverageTrueRange()
atr.Length = self._atr_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(macd, atr, 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.DrawOwnTrades(area)
oscillators = self.CreateChartArea()
if oscillators is not None:
self.DrawIndicator(oscillators, macd)
self.DrawIndicator(oscillators, atr)
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_value, atr_value):
if candle.State != CandleStates.Finished:
return
avg_period = self._atr_avg_period.Value
if atr_value.IsFormed:
self._atrs.append(atr_value.GetValue[Decimal](None))
if len(self._atrs) > avg_period:
self._atrs.pop(0)
if not macd_value.IsFormed:
return
if macd_value.Macd is None or macd_value.Signal is None:
return
is_above = macd_value.Macd > macd_value.Signal
was_above = self._prev_above
self._prev_above = is_above
if was_above is None or was_above == is_above or len(self._atrs) < avg_period:
return
current_atr = self._atrs[-1]
if current_atr <= 0 or not self.IsFormedAndOnlineAndAllowTrading():
return
total = Decimal(0)
for value in self._atrs:
total += value
size = self.Volume * (total / Decimal(avg_period)) / current_atr
step = self.Security.VolumeStep if self.Security is not None else None
if step is not None and step > 0:
size = Math.Max(step, Math.Floor(size / step) * step)
if is_above and self.Position <= 0:
self.BuyMarket(size + abs(self.Position))
elif not is_above and self.Position >= 0:
self.SellMarket(size + abs(self.Position))
def CreateClone(self):
return atr_macd_strategy()