在 GitHub 上查看

Exp Moving Average FN Strategy

该策略基于指数移动平均线 (EMA) 斜率的反转进行交易。当 EMA 在下降后转向上升时做多,当 EMA 在上升后转向下降时做空。止损和止盈以绝对价格单位表示。

细节

  • 入场条件
    • 做多:EMA 斜率由下降转为上升。
    • 做空:EMA 斜率由上升转为下降。
  • 方向:双向。
  • 出场条件
    • 斜率反转为相反方向。
    • 触发止损或止盈。
  • 止损:是,使用绝对价格距离。
  • 默认值
    • EMA Length = 12
    • Stop Loss = 1000
    • Take Profit = 2000
    • Candle Type = 4-hour timeframe
  • 过滤器
    • 类别:趋势跟随
    • 方向:双向
    • 指标:单一(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>
/// EMA slope reversal strategy.
/// Enters long when EMA turns up, short when EMA turns down.
/// </summary>
public class ExpMovingAverageFnStrategy : Strategy
{
	private readonly StrategyParam<int> _length;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevEma;
	private decimal _prevPrevEma;
	private int _count;

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

	public ExpMovingAverageFnStrategy()
	{
		_length = Param(nameof(Length), 12)
			.SetGreaterThanZero()
			.SetDisplay("EMA Length", "EMA period", "Indicator");

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

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevEma = 0;
		_prevPrevEma = 0;
		_count = 0;
	}

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

		var ema = new ExponentialMovingAverage { Length = Length };

		SubscribeCandles(CandleType)
			.Bind(ema, ProcessCandle)
			.Start();
	}

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

		_count++;

		if (_count < 3)
		{
			_prevPrevEma = _prevEma;
			_prevEma = emaValue;
			return;
		}

		// Buy when EMA turns up
		var turnUp = _prevEma < _prevPrevEma && emaValue > _prevEma;
		// Sell when EMA turns down
		var turnDown = _prevEma > _prevPrevEma && emaValue < _prevEma;

		if (turnUp && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		else if (turnDown && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevPrevEma = _prevEma;
		_prevEma = emaValue;
	}
}