在 GitHub 上查看

EMA Sticker 策略

该策略使用指数移动平均线 (EMA) 追踪短期趋势。当收盘价上穿 EMA 时开多单,当收盘价下穿 EMA 时开空单。可选的固定止损和止盈用于控制风险。

细节

  • 入场条件
    • 多头Close > EMA
    • 空头Close < EMA
  • 方向:双向。
  • 出场条件
    • 反向信号或达到设定的止损/止盈水平。
  • 止损/止盈:支持,以价格单位设置的可选止损和止盈。
  • 默认值
    • EMA 周期 = 5。
    • 止损 = 0.001。
    • 止盈 = 0.001。
  • 筛选器
    • 类别:趋势跟随
    • 方向:双向
    • 指标:单一
    • 止损:有
    • 复杂度:简单
    • 时间框架:短期
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>
/// Simple EMA-based trend following strategy.
/// Buys when price crosses above EMA, sells on opposite cross.
/// </summary>
public class EmaStickerStrategy : Strategy
{
	private readonly StrategyParam<int> _maPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private bool _wasAbove;
	private bool _hasPrev;

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

	public EmaStickerStrategy()
	{
		_maPeriod = Param(nameof(MaPeriod), 10)
			.SetGreaterThanZero()
			.SetDisplay("EMA Period", "Length of the EMA", "Parameters");

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

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_wasAbove = false;
		_hasPrev = false;
	}

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

		var ema = new ExponentialMovingAverage { Length = MaPeriod };

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

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

		var isAbove = candle.ClosePrice > emaValue;

		if (!_hasPrev)
		{
			_wasAbove = isAbove;
			_hasPrev = true;
			return;
		}

		// Cross above EMA -> buy
		if (isAbove && !_wasAbove)
		{
			if (Position < 0)
				BuyMarket();
			if (Position <= 0)
				BuyMarket();
		}
		// Cross below EMA -> sell
		else if (!isAbove && _wasAbove)
		{
			if (Position > 0)
				SellMarket();
			if (Position >= 0)
				SellMarket();
		}

		_wasAbove = isAbove;
	}
}