GitHub で見る

ATR Stop Loss Double SMA Strategy

This strategy enters long when a fast Simple Moving Average (SMA) crosses above a slow SMA and enters short on the opposite cross. An optional stop-loss uses the Average True Range (ATR) multiplied by a user-defined factor to determine exit levels.

Details

  • Entry Criteria:
    • Long: Fast SMA crosses above slow SMA.
    • Short: Fast SMA crosses below slow SMA.
  • Long/Short: Both sides.
  • Exit Criteria:
    • ATR-based stop-loss if enabled.
  • Stops: ATR multiple from entry price.
  • Default Values:
    • FastLength = 15
    • SlowLength = 45
    • AtrLength = 14
    • AtrMultiplier = 2
  • Filters:
    • Category: Trend following
    • Direction: Both
    • Indicators: SMA, ATR
    • Stops: Yes
    • Complexity: Low
    • Timeframe: Any
    • Seasonality: No
    • Neural networks: No
    • Divergence: No
    • Risk level: Medium
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>
/// Double SMA crossover strategy.
/// Buys on fast SMA crossing above slow SMA, sells on crossing below.
/// </summary>
public class AtrStopLossDoubleSmaStrategy : Strategy
{
	private readonly StrategyParam<int> _fastLength;
	private readonly StrategyParam<int> _slowLength;
	private readonly StrategyParam<int> _cooldownBars;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevFast;
	private decimal _prevSlow;
	private int _barIndex;
	private int _lastTradeBar;

	/// <summary>
	/// Fast SMA period.
	/// </summary>
	public int FastLength
	{
		get => _fastLength.Value;
		set => _fastLength.Value = value;
	}

	/// <summary>
	/// Slow SMA period.
	/// </summary>
	public int SlowLength
	{
		get => _slowLength.Value;
		set => _slowLength.Value = value;
	}

	/// <summary>
	/// Cooldown bars between trades.
	/// </summary>
	public int CooldownBars
	{
		get => _cooldownBars.Value;
		set => _cooldownBars.Value = value;
	}

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

	/// <summary>
	/// Constructor.
	/// </summary>
	public AtrStopLossDoubleSmaStrategy()
	{
		_fastLength = Param(nameof(FastLength), 15)
			.SetGreaterThanZero()
			.SetDisplay("Fast SMA", "Period of the fast SMA", "Moving Average");

		_slowLength = Param(nameof(SlowLength), 45)
			.SetGreaterThanZero()
			.SetDisplay("Slow SMA", "Period of the slow SMA", "Moving Average");

		_cooldownBars = Param(nameof(CooldownBars), 350)
			.SetDisplay("Cooldown Bars", "Bars between trades", "Trading");

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

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevFast = 0;
		_prevSlow = 0;
		_barIndex = 0;
		_lastTradeBar = 0;
	}

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

		var fastSma = new SimpleMovingAverage { Length = FastLength };
		var slowSma = new SimpleMovingAverage { Length = SlowLength };

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

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

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

		_barIndex++;

		var cooldownOk = _barIndex - _lastTradeBar > CooldownBars;

		// SMA crossover
		var crossUp = _prevFast > 0 && _prevFast <= _prevSlow && fastValue > slowValue;
		var crossDown = _prevFast > 0 && _prevFast >= _prevSlow && fastValue < slowValue;

		if (crossUp && Position <= 0 && cooldownOk)
		{
			BuyMarket();
			_lastTradeBar = _barIndex;
		}
		else if (crossDown && Position >= 0 && cooldownOk)
		{
			SellMarket();
			_lastTradeBar = _barIndex;
		}

		_prevFast = fastValue;
		_prevSlow = slowValue;
	}
}