ATR MACD 策略
该策略利用平均真实波幅(ATR)来调整仓位规模,并根据MACD的交叉进行交易。 ATR数值越大,持仓规模越小,从而在不同市场环境中保持风险一致。 当MACD与信号线交叉时入场,反向交叉或百分比止损触发退出。 这种组合旨在捕获动量的同时考虑到波动性的变化。
测试表明年均收益约为 154%,该策略在股票市场表现最佳。
细节
- 入场条件:指标信号
- 多/空:均可
- 退出条件:止损或反向信号
- 止损:是,按百分比
- 默认值:
CandleType= 15分钟StopLossPercent= 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()