在 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,并遵守 MinVolumeMaxVolume 限制。

实现细节

  • 使用高级 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;
	}
}