在 GitHub 上查看

EMA交叉信号策略

该策略基于两条指数移动平均线(EMA)的交叉进行交易。根据选定的K线序列计算快速EMA和慢速EMA。当快速EMA上穿慢速EMA时,策略可以平掉当前的空头并在需要时开多头;当快速EMA下穿慢速EMA时,策略可以平掉多头并在需要时开空头。

在建立新头寸后,策略可根据设置的距离自动挂出止盈和止损单,距离以跳动点数计。每次新入场时,这些保护性订单都会被取消并重新挂出。

策略提供开多、开空以及分别关闭多头或空头的开关,用户可独立启用或禁用每个方向。所有计算仅在收盘完成的K线上执行。

参数

  • 快速周期 – 快速EMA的长度。
  • 慢速周期 – 慢速EMA的长度。
  • K线类型 – 用于计算的时间框架。
  • 允许开多 – 当快速EMA上穿慢速EMA时开多。
  • 允许开空 – 当快速EMA下穿慢速EMA时开空。
  • 允许平多 – 当快速EMA下穿慢速EMA时平多。
  • 允许平空 – 当快速EMA上穿慢速EMA时平空。
  • 止盈跳数 – 入场价到止盈价的跳动点数。
  • 止损跳数 – 入场价到止损价的跳动点数。
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>
/// Trades EMA crossovers with optional separate entry and exit permissions for long and short positions.
/// </summary>
public class EmaCrossoverSignalStrategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private bool _isInitialized;
	private bool _wasFastAboveSlow;

	public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
	public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public EmaCrossoverSignalStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 5)
			.SetGreaterThanZero()
			.SetDisplay("Fast Period", "Length of the fast EMA", "EMA");

		_slowPeriod = Param(nameof(SlowPeriod), 13)
			.SetGreaterThanZero()
			.SetDisplay("Slow Period", "Length of the slow EMA", "EMA");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Timeframe for calculations", "General");
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_isInitialized = default;
		_wasFastAboveSlow = default;
	}

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

		var fastEma = new ExponentialMovingAverage { Length = FastPeriod };
		var slowEma = new ExponentialMovingAverage { Length = SlowPeriod };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(fastEma, slowEma, Process)
			.Start();
	}

	private void Process(ICandleMessage candle, decimal fastValue, decimal slowValue)
	{
		if (candle.State != CandleStates.Finished)
			return;

		if (!_isInitialized)
		{
			_wasFastAboveSlow = fastValue > slowValue;
			_isInitialized = true;
			return;
		}

		var isFastAboveSlow = fastValue > slowValue;

		if (_wasFastAboveSlow != isFastAboveSlow)
		{
			if (isFastAboveSlow)
			{
				// Upward crossover - buy signal
				if (Position < 0)
					BuyMarket();
				if (Position <= 0)
					BuyMarket();
			}
			else
			{
				// Downward crossover - sell signal
				if (Position > 0)
					SellMarket();
				if (Position >= 0)
					SellMarket();
			}

			_wasFastAboveSlow = isFastAboveSlow;
		}
	}
}