在 GitHub 上查看
MACD No Sample
概述
MACD No Sample 是将 MetaTrader 5 专家顾问 MACD No Sample 迁移到 StockSharp 的版本。策略使用移动平均线斜率检查和 MACD 信号线交叉,同时对 MACD 振幅设置以点(pip)表示的最小阈值。当满足做多条件时会先平掉空头仓位再开多单,做空逻辑完全对称。风险控制延续原策略,提供按点数计算的止损、止盈、移动止损,以及可选的按风险百分比动态计算下单手数。
策略逻辑
指标准备
- 移动平均滤波——可配置的移动平均(SMA、EMA、SMMA 或 LWMA),可选择使用收盘价、开盘价、最高价、最低价、中价、典型价或加权价。当前值与上一根 K 线的比较 (
MA[0] > MA[1] 或 <) 用来判定趋势方向。
- MACD 信号——根据独立的快/慢 EMA 周期以及信号线周期计算 MACD,并使用同样可配置的价格源。监控 MACD 与信号线的交叉情况,并将 MACD 的绝对值与点差阈值比较。
入场规则
- 多头
- 最新收盘的 K 线中移动平均值向上。
- MACD 位于零轴下方,但刚刚上穿信号线(当前 MACD > 当前信号,同时上一根 MACD < 上一根信号)。
- MACD 绝对值大于设定的点数阈值(通过检测到的点值转换成价格)。
- 在下多单之前平掉全部空头仓位。
- 空头
- 移动平均向下。
- MACD 位于零轴上方,但刚刚下穿信号线(当前 MACD < 当前信号,同时上一根 MACD > 上一根信号)。
- MACD 绝对值大于点数阈值。
- 在下空单之前平掉全部多头仓位。
离场与持仓管理
- 固定止损 / 止盈——使用点数转换成价格偏移。参数为
0 时表示禁用。
- 移动止损——当移动止损距离大于零时启动。策略记录进场后的最佳价格,并在价格至少改善移动步长(点数)后才抬升/下移止损,从不放宽。
- 按风险百分比下单(可选)——启用后根据账户权益、止损距离以及风险百分比计算下单量,结果会对齐至交易品种的
VolumeStep,并遵守 MinVolume 和 MaxVolume 限制。
实现细节
- 使用高级 API,通过
SubscribeCandles() 订阅 K 线,在 ProcessCandle 回调中手动驱动指标,未调用任何 GetValue 方法。
- 指标输入严格遵循所选价格类型,并使用 StockSharp 内置的移动平均与 MACD 指标实现。
- 点值检测与原 EA 保持一致:对于三位或五位报价的品种,将价格步长乘以 10。
- 止损与移动止损通过市价平仓实现,不会额外注册止损挂单。
- 仅提供 C# 版本,当前没有 Python 实现。
参数
- Volume – 固定下单手数。
- Stop Loss (pips) – 止损距离,
0 表示关闭。
- Take Profit (pips) – 止盈距离,
0 表示关闭。
- Trailing Stop (pips) – 移动止损距离,
0 表示关闭。
- Trailing Step (pips) – 移动止损每次调整所需的最小点数改善。
- Position Sizing – 选择固定手数或风险百分比模式。
- Risk Percent – 启用风险模式时使用的账户风险百分比。
- MA Period / Method / Price – 移动平均的周期、算法与价格源。
- MACD Fast / Slow / Signal – MACD 的快、慢 EMA 以及信号线周期。
- MACD Price – MACD 使用的价格源。
- MACD Level (pips) – 触发交易所需的 MACD 最小绝对值(点)。
- Candle Type – 计算所使用的时间框架。
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 No Sample strategy using EMA crossover.
/// </summary>
public class MacdNoSampleStrategy : Strategy
{
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<int> _stopLossPoints;
private readonly StrategyParam<int> _takeProfitPoints;
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
private decimal _prevFast;
private decimal _prevSlow;
private decimal _entryPrice;
private int _cooldown;
public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
public int StopLossPoints { get => _stopLossPoints.Value; set => _stopLossPoints.Value = value; }
public int TakeProfitPoints { get => _takeProfitPoints.Value; set => _takeProfitPoints.Value = value; }
public MacdNoSampleStrategy()
{
_fastPeriod = Param(nameof(FastPeriod), 12).SetGreaterThanZero().SetDisplay("Fast Period", "Fast EMA period", "Indicator");
_slowPeriod = Param(nameof(SlowPeriod), 50).SetGreaterThanZero().SetDisplay("Slow Period", "Slow EMA period", "Indicator");
_stopLossPoints = Param(nameof(StopLossPoints), 200).SetNotNegative().SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");
_takeProfitPoints = Param(nameof(TakeProfitPoints), 400).SetNotNegative().SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
}
protected override void OnReseted()
{
base.OnReseted();
_fast = null; _slow = null;
_prevFast = 0; _prevSlow = 0; _entryPrice = 0; _cooldown = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_fast = new ExponentialMovingAverage { Length = FastPeriod };
_slow = new ExponentialMovingAverage { Length = SlowPeriod };
var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
subscription.Bind(_fast, _slow, ProcessCandle);
subscription.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
{
if (candle.State != CandleStates.Finished) return;
if (!_fast.IsFormed || !_slow.IsFormed) { _prevFast = fastValue; _prevSlow = slowValue; return; }
if (_cooldown > 0) { _cooldown--; _prevFast = fastValue; _prevSlow = slowValue; return; }
var close = candle.ClosePrice;
var step = Security?.PriceStep ?? 1m;
if (Position > 0 && _entryPrice > 0)
{
if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
}
else if (Position < 0 && _entryPrice > 0)
{
if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
}
if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
{ if (Position < 0) BuyMarket(); BuyMarket(); _entryPrice = close; _cooldown = 100; }
else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
{ if (Position > 0) SellMarket(); SellMarket(); _entryPrice = close; _cooldown = 100; }
_prevFast = fastValue; _prevSlow = slowValue;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class macd_no_sample_strategy(Strategy):
"""
MACD No Sample: EMA crossover with manual SL/TP via price steps.
"""
def __init__(self):
super(macd_no_sample_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 12).SetDisplay("Fast Period", "Fast EMA period", "Indicator")
self._slow_period = self.Param("SlowPeriod", 50).SetDisplay("Slow Period", "Slow EMA period", "Indicator")
self._stop_loss_points = self.Param("StopLossPoints", 200).SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk")
self._take_profit_points = self.Param("TakeProfitPoints", 400).SetDisplay("Take Profit", "Take-profit in price steps", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Candles", "General")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(macd_no_sample_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(macd_no_sample_strategy, self).OnStarted2(time)
self._fast_ind = ExponentialMovingAverage()
self._fast_ind.Length = self._fast_period.Value
self._slow_ind = ExponentialMovingAverage()
self._slow_ind.Length = self._slow_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._fast_ind, self._slow_ind, self._process_candle).Start()
def _process_candle(self, candle, fast_val, slow_val):
if candle.State != CandleStates.Finished:
return
fast = float(fast_val)
slow = float(slow_val)
if not self._fast_ind.IsFormed or not self._slow_ind.IsFormed:
self._prev_fast = fast
self._prev_slow = slow
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_fast = fast
self._prev_slow = slow
return
close = float(candle.ClosePrice)
step = float(self.Security.PriceStep) if self.Security is not None and self.Security.PriceStep is not None else 1.0
if self.Position > 0 and self._entry_price > 0:
if self._stop_loss_points.Value > 0 and close <= self._entry_price - self._stop_loss_points.Value * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast
self._prev_slow = slow
return
if self._take_profit_points.Value > 0 and close >= self._entry_price + self._take_profit_points.Value * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast
self._prev_slow = slow
return
elif self.Position < 0 and self._entry_price > 0:
if self._stop_loss_points.Value > 0 and close >= self._entry_price + self._stop_loss_points.Value * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast
self._prev_slow = slow
return
if self._take_profit_points.Value > 0 and close <= self._entry_price - self._take_profit_points.Value * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast
self._prev_slow = slow
return
if self._prev_fast <= self._prev_slow and fast > slow and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._entry_price = close
self._cooldown = 100
elif self._prev_fast >= self._prev_slow and fast < slow and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._entry_price = close
self._cooldown = 100
self._prev_fast = fast
self._prev_slow = slow
def CreateClone(self):
return macd_no_sample_strategy()