在 GitHub 上查看

Grail Expert MA

概述

Grail Expert MA 是 MetaTrader 4 专家 _GrailExpertMAV1_0 在 StockSharp 平台上的移植版本。策略跟踪最近若干根 K 线的高点和低点通道,当行情突破该通道并形成足够的空间后,等待价格回撤到预设水平再入场。典型价格((最高价 + 最低价 + 收盘价)/3)的指数移动平均线提供方向过滤——只有当最近两根已完成 K 线之间的 EMA 变化超过指定点数时才允许交易。风险控制与原策略一致,使用固定点差的止损、止盈,并且在已有持仓时禁止生成新的订单。

策略逻辑

EMA 斜率趋势过滤

  • 在每根 K 线收盘时计算典型价格的 EMA。
  • 最近两次 EMA 数值的差值必须超过 EMA Slope (pips) 参数(点数会根据品种的最小价位增量换算为价格)。
  • 斜率为正仅允许多头回撤,斜率为负仅允许空头回撤,斜率不足则暂停交易。

突破区间追踪

  • 保存最近 Range Period 根已完成 K 线的最高价和最低价,形成一个动态通道。
  • 通道高度用于过滤噪声突破,如果新的极值距离另一侧不足 2 * Breakout Buffer + Take Profit 点,则放弃该信号。

准备入场价格

  • 当当前 K 线创出新高时,计算多头触发价格:High - Breakout Buffer - Take Profit 点。
  • 当当前 K 线创出新低时,计算空头触发价格:Low + Breakout Buffer + Take Profit 点。
  • 只有在突破幅度满足原始 EA 的要求时才会保留这些价格。

入场触发条件

  • 计算出的价格在该根 K 线内保持有效。若最低价触及或跌破多头价格且 EMA 斜率为正,则买入开仓。
  • 若最高价触及或上破空头价格且 EMA 斜率为负,则卖出开仓。
  • 策略一次只允许一笔持仓;一旦提交市价单,将立即清除所有挂起的入场价格。

持仓管理

  • 多头仓位的止损设置为 Entry - Stop Loss 点,止盈设置为 Entry + Take Profit 点(参数为 0 时表示不启用)。
  • 空头仓位的止损、止盈对称设置。
  • 当后续 K 线的最高价/最低价触及相应水平时立即平仓,实现与原 EA 类似的处理。

额外保护

  • 每当新的 K 线收盘都会刷新区间,并删除落在区间之外的挂单价格。
  • 所有点数参数都会根据合约的价格精度自动换算,例如五位报价外汇品种的一点等于十个最小价位。
  • 在 EMA 尚未形成或区间尚未积累足够历史之前,策略保持等待状态。

参数说明

  • Order Volume – 市价单交易量(手数或合约数)。
  • Take Profit (pips) – 固定止盈点数,设为 0 可关闭止盈。
  • Stop Loss (pips) – 固定止损点数,设为 0 可关闭止损。
  • Range Period – 计算突破通道所需的已完成 K 线数量。
  • EMA Period – 典型价格 EMA 的周期长度。
  • EMA Slope (pips) – 最近两个 EMA 值之间的最小点差要求。
  • Breakout Buffer (pips) – 突破后在极值之外额外等待的点差。
  • Candle Type – 订阅的 K 线周期(默认:1 小时)。

实现细节

  • 订阅的蜡烛数据包含未完成的更新,以模拟原策略对盘中高低点的监控。
  • EMA 仅在蜡烛收盘时更新,等效于 MQL4 中对 iMA 指标使用 1 和 2 的偏移量。
  • 为了避免昂贵的重新遍历,突破区间通过有界队列维护,而非在每个步骤重新扫描历史。
  • 该目录仅提供 C# 版本,暂不包含 Python 代码。
using System;

using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Grail Expert MA: SMA crossover with ATR stops.
/// </summary>
public class GrailExpertMaStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _fastSmaLength;
	private readonly StrategyParam<int> _slowSmaLength;
	private readonly StrategyParam<int> _atrLength;

	private decimal _prevFast;
	private decimal _prevSlow;
	private decimal _entryPrice;

	public GrailExpertMaStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
			.SetDisplay("Candle Type", "Timeframe.", "General");

		_fastSmaLength = Param(nameof(FastSmaLength), 10)
			.SetDisplay("Fast SMA", "Fast SMA period.", "Indicators");

		_slowSmaLength = Param(nameof(SlowSmaLength), 40)
			.SetDisplay("Slow SMA", "Slow SMA period.", "Indicators");

		_atrLength = Param(nameof(AtrLength), 14)
			.SetDisplay("ATR Length", "ATR period.", "Indicators");
	}

	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	public int FastSmaLength
	{
		get => _fastSmaLength.Value;
		set => _fastSmaLength.Value = value;
	}

	public int SlowSmaLength
	{
		get => _slowSmaLength.Value;
		set => _slowSmaLength.Value = value;
	}

	public int AtrLength
	{
		get => _atrLength.Value;
		set => _atrLength.Value = value;
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();

		_prevFast = 0;
		_prevSlow = 0;
		_entryPrice = 0;
	}

		protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		_prevFast = 0;
		_prevSlow = 0;
		_entryPrice = 0;

		var fastSma = new SimpleMovingAverage { Length = FastSmaLength };
		var slowSma = new SimpleMovingAverage { Length = SlowSmaLength };
		var atr = new AverageTrueRange { Length = AtrLength };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(fastSma, slowSma, atr, ProcessCandle)
			.Start();

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, fastSma);
			DrawIndicator(area, slowSma);
			DrawOwnTrades(area);
		}
	}

	private void ProcessCandle(ICandleMessage candle, decimal fastVal, decimal slowVal, decimal atrVal)
	{
		if (candle.State != CandleStates.Finished)
			return;

		if (_prevFast == 0 || _prevSlow == 0 || atrVal <= 0)
		{
			_prevFast = fastVal;
			_prevSlow = slowVal;
			return;
		}

		var close = candle.ClosePrice;

		if (Position > 0)
		{
			if (fastVal < slowVal && _prevFast >= _prevSlow)
			{
				SellMarket();
				_entryPrice = 0;
			}
			else if (close <= _entryPrice - atrVal * 2m)
			{
				SellMarket();
				_entryPrice = 0;
			}
		}
		else if (Position < 0)
		{
			if (fastVal > slowVal && _prevFast <= _prevSlow)
			{
				BuyMarket();
				_entryPrice = 0;
			}
			else if (close >= _entryPrice + atrVal * 2m)
			{
				BuyMarket();
				_entryPrice = 0;
			}
		}

		if (Position == 0)
		{
			if (fastVal > slowVal && _prevFast <= _prevSlow)
			{
				_entryPrice = close;
				BuyMarket();
			}
			else if (fastVal < slowVal && _prevFast >= _prevSlow)
			{
				_entryPrice = close;
				SellMarket();
			}
		}

		_prevFast = fastVal;
		_prevSlow = slowVal;
	}
}