在 GitHub 上查看

EMA Prediction 策略

该策略基于 EMA Prediction 指标,当快速和慢速指数移动平均线在确认方向的 K 线中发生交叉时产生信号。

当快速 EMA 在看涨 K 线上向上穿过慢速 EMA 时,策略开多并关闭所有空头。当快速 EMA 在看跌 K 线上向下穿过慢速 EMA 时,策略开空并关闭所有多头。

细节

  • 入场条件
    • 多头:快速 EMA 上穿慢速 EMA 且 K 线为阳线。
    • 空头:快速 EMA 下穿慢速 EMA 且 K 线为阴线。
  • 多/空:双向
  • 离场条件:反向信号
  • 止损:固定止盈与止损
  • 默认值
    • CandleType = 6 小时 K 线
    • FastPeriod = 1
    • SlowPeriod = 2
    • StopLossTicks = 1000
    • TakeProfitTicks = 2000
  • 过滤器
    • 类别:均线交叉
    • 方向:双向
    • 指标:EMA
    • 止损:止盈与止损
    • 复杂度:基础
    • 时间框架:6 小时
    • 季节性:无
    • 神经网络:无
    • 背离:无
    • 风险等级:中等
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>
/// Strategy based on EMA crossover prediction indicator.
/// </summary>
public class EmaPredictionStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<decimal> _takeProfitTicks;
	private readonly StrategyParam<decimal> _stopLossTicks;

	private decimal _prevFast;
	private decimal _prevSlow;
	private bool _initialized;

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

	/// <summary>
	/// Fast EMA period.
	/// </summary>
	public int FastPeriod
	{
		get => _fastPeriod.Value;
		set => _fastPeriod.Value = value;
	}

	/// <summary>
	/// Slow EMA period.
	/// </summary>
	public int SlowPeriod
	{
		get => _slowPeriod.Value;
		set => _slowPeriod.Value = value;
	}

	/// <summary>
	/// Take profit in ticks.
	/// </summary>
	public decimal TakeProfitTicks
	{
		get => _takeProfitTicks.Value;
		set => _takeProfitTicks.Value = value;
	}

	/// <summary>
	/// Stop loss in ticks.
	/// </summary>
	public decimal StopLossTicks
	{
		get => _stopLossTicks.Value;
		set => _stopLossTicks.Value = value;
	}

	/// <summary>
	/// Initializes a new instance of the strategy.
	/// </summary>
	public EmaPredictionStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Timeframe for calculations", "General");

		_fastPeriod = Param(nameof(FastPeriod), 5)
			.SetDisplay("Fast EMA Period", "Period of fast EMA", "Indicator")
			.SetGreaterThanZero();

		_slowPeriod = Param(nameof(SlowPeriod), 20)
			.SetDisplay("Slow EMA Period", "Period of slow EMA", "Indicator")
			.SetGreaterThanZero();

		_takeProfitTicks = Param(nameof(TakeProfitTicks), 2000m)
			.SetDisplay("Take Profit Ticks", "Take profit in ticks", "Risk Management")
			.SetNotNegative();

		_stopLossTicks = Param(nameof(StopLossTicks), 1000m)
			.SetDisplay("Stop Loss Ticks", "Stop loss in ticks", "Risk Management")
			.SetNotNegative();
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevFast = default;
		_prevSlow = default;
		_initialized = default;
	}

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

		var fast = new ExponentialMovingAverage { Length = FastPeriod };
		var slow = new ExponentialMovingAverage { Length = SlowPeriod };

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

		var step = Security.PriceStep ?? 1m;
		StartProtection(
			new Unit(StopLossTicks * step, UnitTypes.Absolute),
			new Unit(TakeProfitTicks * step, UnitTypes.Absolute));
	}

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

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		if (!_initialized)
		{
			_prevFast = fast;
			_prevSlow = slow;
			_initialized = true;
			return;
		}

		var bullish = _prevFast < _prevSlow && fast > slow && candle.OpenPrice < candle.ClosePrice;
		var bearish = _prevFast > _prevSlow && fast < slow && candle.OpenPrice > candle.ClosePrice;

		if (bullish && Position <= 0)
		{
			if (Position < 0)
				BuyMarket();
			BuyMarket();
		}
		else if (bearish && Position >= 0)
		{
			if (Position > 0)
				SellMarket();
			SellMarket();
		}

		_prevFast = fast;
		_prevSlow = slow;
	}
}