在 GitHub 上查看

BeerGod EMA 定时策略

该策略将 MetaTrader 上的 BeerGodEA 迁移到 StockSharp 平台。它基于均值回归思想,仅在单一标的上操作,通过监控 60 周期指数移动平均线 (EMA) 并比较上一根 K 线的收盘价来寻找机会。信号只会在每根 K 线开盘后经过指定的分钟数 时检查一次,从而复刻原始 EA 先等待再下单的逻辑。

当价格暂时偏离 EMA 且 EMA 的方向与价格运动相反时,策略会建立市场头寸,期望价格回归。如果当前存在反向持仓, 策略会自动扩大新订单的数量,先平掉旧仓,再在同一笔交易中打开新的方向仓位。

工作流程

  1. 订阅指定周期的 K 线(默认 5 分钟),并根据收盘价计算 60 周期 EMA。
  2. 实时跟踪当前 K 线。每当出现新的一根 K 线时,保存上一根 K 线的 EMA 数值以及收盘价,以便后续比较。
  3. 当距离开盘达到设定的分钟数(默认 3 分钟)时,检查下述条件:
    • 买入条件:当前价格 < 当前 EMA,EMA 低于前一根 K 线的 EMA(EMA 向下),且当前价格 < 上一根 K 线收盘价。
    • 卖出条件:当前价格 > 当前 EMA,EMA 高于前一根 K 线的 EMA(EMA 向上),且当前价格 > 上一根 K 线收盘价。
  4. 若满足买入条件且当前没有多头头寸,则发送市场买单。下单数量会自动加上现有空头仓位,使得一次交易即可平掉 空头并建立新的多头仓位。卖出条件的处理方式与之对称。
  5. 当某根 K 线触发交易后,该根 K 线的信号将标记为已处理,避免在同一根 K 线上重复入场。

参数说明

  • Volume – 下单数量(默认 1 手)。当需要反向操作时,订单会额外加上当前持仓量,从而一次性完成平仓与反向建仓。
  • EMA Length – EMA 的计算周期(默认 60)。
  • Trigger Minutes – 自 K 线开盘起等待的分钟数,达到后才评估信号(默认 3)。如果错过该时间窗口,将等待下一根 K 线。
  • Candle Type – 用于计算的 K 线类型(默认 5 分钟 K 线)。

交易提示

  • 只要标的提供 K 线数据和 Level1 行情,该策略即可运行。若交易时段与原始 EA 不同,可调整 K 线周期。
  • 同一时间仅持有一个方向的仓位。策略通过调整订单数量自动完成反向仓位的平仓与开仓。
  • 原策略未设置固定的止损/止盈,如有需要可在外部加入风险控制措施。
  • 策略启动时会调用 StartProtection,以便在连接异常或人工干预时由 StockSharp 自动处理紧急平仓。
using System;
using System.Linq;
using System.Collections.Generic;

using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;

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

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Mean-reversion strategy that triggers trades a few minutes after the bar opens using an EMA trend filter.
/// </summary>
public class BeerGodEmaTimingStrategy : Strategy
{
	private readonly StrategyParam<int> _emaLength;
	private readonly StrategyParam<int> _triggerMinutes;
	private readonly StrategyParam<DataType> _candleType;

	private EMA _ema = null!;
	private DateTimeOffset _currentCandleOpenTime = DateTimeOffset.MinValue;
	private decimal _currentEma;
	private decimal _previousEma;
	private decimal _currentClose;
	private decimal _previousClose;


	/// <summary>
	/// EMA length used as the directional filter.
	/// </summary>
	public int EmaLength
	{
		get => _emaLength.Value;
		set => _emaLength.Value = value;
	}

	/// <summary>
	/// Minutes from the candle open when the entry check is performed.
	/// </summary>
	public int TriggerMinutesFromOpen
	{
		get => _triggerMinutes.Value;
		set => _triggerMinutes.Value = value;
	}

	/// <summary>
	/// Candle type used for signal generation.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Initializes a new instance of <see cref="BeerGodEmaTimingStrategy"/>.
	/// </summary>
	public BeerGodEmaTimingStrategy()
	{

		_emaLength = Param(nameof(EmaLength), 60)
			.SetGreaterThanZero()
			.SetDisplay("EMA Length", "EMA length for the trend filter", "Indicator")
			
			.SetOptimize(20, 120, 10);

		_triggerMinutes = Param(nameof(TriggerMinutesFromOpen), 3)
			.SetNotNegative()
			.SetDisplay("Trigger Minutes", "Minutes after open to check signals", "Timing")
			
			.SetOptimize(1, 10, 1);

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Primary candle type", "General");
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		return [(Security, CandleType)];
	}

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

		_currentCandleOpenTime = DateTimeOffset.MinValue;
		_currentEma = 0m;
		_previousEma = 0m;
		_currentClose = 0m;
		_previousClose = 0m;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		_ema = new EMA
		{
			Length = EmaLength
		};

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(_ema, ProcessCandle)
			.Start();

		// no fixed protection needed
	}

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

		_previousEma = _currentEma;
		_previousClose = _currentClose;

		_currentEma = emaValue;
		_currentClose = candle.ClosePrice;

		if (!_ema.IsFormed || _previousEma == 0m)
			return;

		var price = candle.ClosePrice;
		var maCurrent = _currentEma;
		var maPrevious = _previousEma;
		var prevClose = _previousClose;

		var newBuy = price < maCurrent && maCurrent < maPrevious && price < prevClose;
		var newSell = price > maCurrent && maCurrent > maPrevious && price > prevClose;

		if (!newBuy && !newSell)
			return;

		if (newBuy && Position <= 0)
		{
			BuyMarket();
		}
		else if (newSell && Position >= 0)
		{
			SellMarket();
		}
	}
}