Simple MACD EA 策略
概述
Simple MACD EA 策略源自 MetaTrader 平台上的经典顾问程序 “Simple MACD EA”。策略使用两条指数移动平均线(EMA)来模拟 MACD 柱状图,并在 1 分钟 K 线级别上确定趋势方向。当 100 周期 EMA 上穿用户设定周期的 EMA 时开多头;当 100 周期 EMA 下穿该 EMA 时开空头。策略始终仅保持一笔持仓。
交易管理逻辑
- 趋势识别: 通过 EMA(100) 与可配置 EMA 的差值得到当前趋势信号(
+1、0、-1)。信号由负转正时开多,由正转负时开空。 - 动能确认: 策略额外跟踪 MACD EMA 与更慢一档 EMA(周期为
MACD level + 1)之间的差值。当价格已经至少盈利 5 个点且该差值朝不利方向缩小时,会提前平仓。 - 时间保护: 持仓超过设定的评估周期后,会启动柔性止损,逐步收紧相对于入场价可接受的回撤。
- 移动止损: 当持仓盈利并维持足够长时间后,激活内部移动止损。止损价会以设定的点数跟随价格移动,并且只能更新限定次数,超过上限即直接平仓。
- 趋势反转离场: 如果趋势信号反向且价格已经至少盈利 5 个点,立即退出持仓。
参数
- Candle Type – 用于指标计算的 K 线类型(默认 1 分钟)。
- Volume – 开仓的交易量。
- MACD Level – MACD 慢线使用的 EMA 周期,同时自动生成周期为
MACD Level + 1的辅助 EMA。 - Trailing Stop – 移动止损的点数距离,设为 0 表示关闭该功能。
- Trailing Updates – 单笔交易允许的移动止损更新次数上限。
- Wait Cycles – 启动柔性止损前需等待的评估周期数。
其他说明
- 策略在反手之前会先平掉当前仓位。
- 使用标的物的最小报价步长将点值转换为实际价格。
- 实现基于 StockSharp 的高级蜡烛订阅 API,不使用自定义指标缓冲区。
using System;
using System.Collections.Generic;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Simple MACD EA strategy using fast/slow EMA difference for trend detection.
/// Buy when EMA difference crosses above zero, sell when it crosses below zero.
/// </summary>
public class SimpleMacdEaStrategy : Strategy
{
private readonly StrategyParam<int> _fastEmaPeriod;
private readonly StrategyParam<int> _slowEmaPeriod;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevDiff;
private bool _hasPrev;
public int FastEmaPeriod
{
get => _fastEmaPeriod.Value;
set => _fastEmaPeriod.Value = value;
}
public int SlowEmaPeriod
{
get => _slowEmaPeriod.Value;
set => _slowEmaPeriod.Value = value;
}
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public SimpleMacdEaStrategy()
{
_fastEmaPeriod = Param(nameof(FastEmaPeriod), 12)
.SetDisplay("Fast EMA", "Fast EMA period", "Indicators");
_slowEmaPeriod = Param(nameof(SlowEmaPeriod), 26)
.SetDisplay("Slow EMA", "Slow EMA period", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Candle timeframe", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevDiff = 0m;
_hasPrev = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_hasPrev = false;
var fastEma = new ExponentialMovingAverage { Length = FastEmaPeriod };
var slowEma = new ExponentialMovingAverage { Length = SlowEmaPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fastEma, slowEma, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow)
{
if (candle.State != CandleStates.Finished)
return;
var diff = fast - slow;
if (!_hasPrev)
{
_prevDiff = diff;
_hasPrev = true;
return;
}
// Buy: MACD crosses above zero
var longSignal = _prevDiff <= 0 && diff > 0;
// Sell: MACD crosses below zero
var shortSignal = _prevDiff >= 0 && diff < 0;
if (Position <= 0 && longSignal)
{
if (Position < 0)
BuyMarket();
BuyMarket();
}
else if (Position >= 0 && shortSignal)
{
if (Position > 0)
SellMarket();
SellMarket();
}
_prevDiff = diff;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class simple_macd_ea_strategy(Strategy):
"""Simple MACD EA using fast/slow EMA difference for trend detection.
Buy when EMA difference crosses above zero, sell when it crosses below zero."""
def __init__(self):
super(simple_macd_ea_strategy, self).__init__()
self._fast_ema_period = self.Param("FastEmaPeriod", 12) \
.SetDisplay("Fast EMA", "Fast EMA period", "Indicators")
self._slow_ema_period = self.Param("SlowEmaPeriod", 26) \
.SetDisplay("Slow EMA", "Slow EMA period", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Candle timeframe", "General")
self._prev_diff = 0.0
self._has_prev = False
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
@property
def FastEmaPeriod(self):
return self._fast_ema_period.Value
@property
def SlowEmaPeriod(self):
return self._slow_ema_period.Value
def OnReseted(self):
super(simple_macd_ea_strategy, self).OnReseted()
self._prev_diff = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(simple_macd_ea_strategy, self).OnStarted2(time)
self._has_prev = False
fast_ema = ExponentialMovingAverage()
fast_ema.Length = self.FastEmaPeriod
slow_ema = ExponentialMovingAverage()
slow_ema.Length = self.SlowEmaPeriod
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(fast_ema, slow_ema, self._process_candle).Start()
def _process_candle(self, candle, fast, slow):
if candle.State != CandleStates.Finished:
return
diff = float(fast) - float(slow)
if not self._has_prev:
self._prev_diff = diff
self._has_prev = True
return
# Buy: MACD crosses above zero
long_signal = self._prev_diff <= 0 and diff > 0
# Sell: MACD crosses below zero
short_signal = self._prev_diff >= 0 and diff < 0
if self.Position <= 0 and long_signal:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif self.Position >= 0 and short_signal:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_diff = diff
def CreateClone(self):
return simple_macd_ea_strategy()