Открыть на GitHub

Стратегия NonLagDot

Стратегия основана на индикаторе NonLagDot. Индикатор сглаживает цену и окрашивает точки, показывая направление тренда. Стратегия открывает длинную позицию при смене индикатора вверх и короткую при смене вниз. Перед открытием новой позиции противоположная позиция закрывается.

Подробности

  • Условия входа:
    • Длинная: индикатор меняется с нисходящего на восходящий (наклон скользящей средней становится положительным)
    • Короткая: индикатор меняется с восходящего на нисходящий (наклон становится отрицательным)
  • Long/Short: Оба
  • Условия выхода: противоположный сигнал
  • Стопы: опциональный стоп-лосс в процентах
  • Параметры по умолчанию:
    • Length = 10
    • CandleType = TimeSpan.FromHours(1).TimeFrame()
    • StopLossPercent = 1m
  • Фильтры:
    • Категория: Следование тренду
    • Направление: Оба
    • Индикаторы: Наклон SMA как приближение NonLagDot
    • Стопы: Да
    • Сложность: Базовая
    • Таймфрейм: Внутридневной
    • Сезонность: Нет
    • Нейросети: Нет
    • Дивергенция: Нет
    • Уровень риска: Средний
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>
/// Strategy based on NonLagDot indicator trend changes.
/// Uses a simple moving average to approximate NonLagDot behavior.
/// When the moving average slope turns positive, a long position is opened.
/// When the slope turns negative, a short position is opened.
/// Opposite positions are closed before opening new ones.
/// </summary>
public class NonLagDotStrategy : Strategy
{
	private readonly StrategyParam<int> _length;
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<decimal> _stopLossPercent;

	private ExponentialMovingAverage _sma;
	private decimal? _prevSma;
	private int _prevTrend;

	/// <summary>
	/// Moving average length approximating NonLagDot.
	/// </summary>
	public int Length
	{
		get => _length.Value;
		set => _length.Value = value;
	}

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

	/// <summary>
	/// Stop-loss percentage.
	/// </summary>
	public decimal StopLossPercent
	{
		get => _stopLossPercent.Value;
		set => _stopLossPercent.Value = value;
	}

	/// <summary>
	/// Initializes a new instance of the strategy.
	/// </summary>
	public NonLagDotStrategy()
	{
		_length = Param(nameof(Length), 10)
			.SetGreaterThanZero()
			.SetDisplay("Length", "Moving average period", "Indicator");

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

		_stopLossPercent = Param(nameof(StopLossPercent), 1m)
			.SetGreaterThanZero()
			.SetDisplay("Stop Loss %", "Percent based stop-loss", "Risk");
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_sma = null;
		_prevSma = null;
		_prevTrend = 0;
	}

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

		_sma = new ExponentialMovingAverage { Length = Length };

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

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, _sma);
			DrawOwnTrades(area);
		}
	}

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

		if (_prevSma is null)
		{
			_prevSma = sma;
			return;
		}

		var trend = sma > _prevSma ? 1 : sma < _prevSma ? -1 : _prevTrend;

		if (!IsFormedAndOnlineAndAllowTrading())
		{
			_prevTrend = trend;
			_prevSma = sma;
			return;
		}

		if (trend > 0 && _prevTrend < 0 && Position <= 0)
			BuyMarket();
		else if (trend < 0 && _prevTrend > 0 && Position >= 0)
			SellMarket();

		_prevTrend = trend;
		_prevSma = sma;
	}
}