Открыть на GitHub

Стратегия ZapTeam Pro v6 — EMA

Упрощённая версия на основе пересечения EMA21 и EMA50 с фильтром тренда EMA200. Покупает при бычьем пересечении и продаёт при медвежьем (шорты опциональны).

Детали

  • Условие входа: EMA21 пересекает EMA50 с трендовым фильтром
  • Длин/Корот: Оба (шорты опциональны)
  • Условие выхода: Обратное пересечение
  • Стопы: Нет
  • Значения по умолчанию:
    • Ema21Length = 21
    • Ema50Length = 50
    • Ema200Length = 200
  • Фильтры:
    • Категория: Тренд
    • Направление: Оба
    • Индикаторы: EMA
    • Стопы: Нет
    • Сложность: Базовая
    • Таймфрейм: Внутридневной
    • Сезонность: Нет
    • Нейросети: Нет
    • Дивергенция: Нет
    • Уровень риска: Средний
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>
/// EMA crossover with long term trend filter.
/// </summary>
public class ZapTeamProV6EmaStrategy : Strategy
{
	private readonly StrategyParam<int> _ema21Length;
	private readonly StrategyParam<int> _ema50Length;
	private readonly StrategyParam<int> _ema200Length;
	private readonly StrategyParam<bool> _enableShorts;
	private readonly StrategyParam<DataType> _candleType;

	private decimal? _prev21;
	private decimal? _prev50;

	public int Ema21Length { get => _ema21Length.Value; set => _ema21Length.Value = value; }
	public int Ema50Length { get => _ema50Length.Value; set => _ema50Length.Value = value; }
	public int Ema200Length { get => _ema200Length.Value; set => _ema200Length.Value = value; }
	public bool EnableShorts { get => _enableShorts.Value; set => _enableShorts.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public ZapTeamProV6EmaStrategy()
	{
		_ema21Length = Param(nameof(Ema21Length), 21)
			.SetGreaterThanZero()
			.SetDisplay("EMA 21", "Fast EMA length", "Indicators")
			;

		_ema50Length = Param(nameof(Ema50Length), 50)
			.SetGreaterThanZero()
			.SetDisplay("EMA 50", "Slow EMA length", "Indicators")
			;

		_ema200Length = Param(nameof(Ema200Length), 200)
			.SetGreaterThanZero()
			.SetDisplay("EMA 200", "Trend EMA length", "Indicators")
			;

		_enableShorts = Param(nameof(EnableShorts), false)
			.SetDisplay("Enable Shorts", "Allow short trades", "General");

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

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prev21 = null;
		_prev50 = null;
	}

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

		var ema21 = new ExponentialMovingAverage { Length = Ema21Length };
		var ema50 = new ExponentialMovingAverage { Length = Ema50Length };
		var ema200 = new ExponentialMovingAverage { Length = Ema200Length };

		_prev21 = null;
		_prev50 = null;

		var subscription = SubscribeCandles(CandleType);
		subscription.Bind(ema21, ema50, ema200, ProcessCandle).Start();
	}

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

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		if (_prev21 is null)
		{
			_prev21 = ema21;
			_prev50 = ema50;
			return;
		}

		var crossUp = _prev21 <= _prev50 && ema21 > ema50;
		var crossDown = _prev21 >= _prev50 && ema21 < ema50;
		var trendLong = candle.ClosePrice > ema200;
		var trendShort = candle.ClosePrice < ema200;

		if (crossUp && trendLong && Position <= 0)
		{
			BuyMarket();
		}
		else if (crossDown && trendShort && EnableShorts && Position >= 0)
		{
			SellMarket();
		}

		_prev21 = ema21;
		_prev50 = ema50;
	}
}