View on GitHub

Exp ATR Trailing Strategy

This example demonstrates how to manage existing positions with a trailing stop based on the Average True Range (ATR) indicator. The strategy does not generate entry signals; it only adjusts the exit level of an open position according to market volatility.

How it works

  1. The strategy subscribes to candle data of a chosen timeframe.
  2. An AverageTrueRange indicator is calculated on each candle.
  3. For long positions the stop level is moved up to Close - ATR * BuyFactor.
  4. For short positions the stop level is moved down to Close + ATR * SellFactor.
  5. When price crosses the trailing level the position is closed at market.

The trailing stop only moves in the direction of the trade and never retreats, providing a volatility adjusted exit.

Parameters

Name Description
AtrPeriod ATR calculation period.
BuyFactor Multiplier applied to ATR when trailing a long position.
SellFactor Multiplier applied to ATR when trailing a short position.
CandleType Timeframe of candles used for analysis.

Usage notes

  • Attach the strategy to a security and open a position manually or from another strategy.
  • Suitable for risk management where exits are controlled separately from entries.
  • Chart area displays candles, ATR values and executed trades for visual analysis.

References

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>
/// ATR trailing stop strategy. Enters on EMA crossover, exits when ATR trailing stop is hit.
/// </summary>
public class ExpAtrTrailingStrategy : Strategy
{
	private readonly StrategyParam<int> _stdPeriod;
	private readonly StrategyParam<decimal> _stdFactor;
	private readonly StrategyParam<int> _fastEma;
	private readonly StrategyParam<int> _slowEma;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _longTrail;
	private decimal _shortTrail;
	private decimal _prevFast;
	private decimal _prevSlow;
	private bool _hasPrev;

	public int StdPeriod { get => _stdPeriod.Value; set => _stdPeriod.Value = value; }
	public decimal StdFactor { get => _stdFactor.Value; set => _stdFactor.Value = value; }
	public int FastEma { get => _fastEma.Value; set => _fastEma.Value = value; }
	public int SlowEma { get => _slowEma.Value; set => _slowEma.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public ExpAtrTrailingStrategy()
	{
		_stdPeriod = Param(nameof(StdPeriod), 14)
			.SetGreaterThanZero()
			.SetDisplay("StdDev Period", "StdDev period", "Indicators");

		_stdFactor = Param(nameof(StdFactor), 2m)
			.SetDisplay("StdDev Factor", "StdDev multiplier for trailing stop", "Indicators");

		_fastEma = Param(nameof(FastEma), 10)
			.SetGreaterThanZero()
			.SetDisplay("Fast EMA", "Fast EMA for entry", "Indicators");

		_slowEma = Param(nameof(SlowEma), 30)
			.SetGreaterThanZero()
			.SetDisplay("Slow EMA", "Slow EMA for entry", "Indicators");

		_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();
		_longTrail = 0;
		_shortTrail = 0;
		_prevFast = 0;
		_prevSlow = 0;
		_hasPrev = false;
	}

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

		var fast = new ExponentialMovingAverage { Length = FastEma };
		var slow = new ExponentialMovingAverage { Length = SlowEma };
		var stdDev = new StandardDeviation { Length = StdPeriod };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(fast, slow, stdDev, ProcessCandle)
			.Start();

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

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

		// Trail management
		if (Position > 0)
		{
			var stop = candle.ClosePrice - stdVal * StdFactor;
			if (stop > _longTrail)
				_longTrail = stop;

			if (candle.LowPrice <= _longTrail)
			{
				SellMarket();
				_longTrail = 0;
			}
		}
		else if (Position < 0)
		{
			var stop = candle.ClosePrice + stdVal * StdFactor;
			if (stop < _shortTrail || _shortTrail == 0)
				_shortTrail = stop;

			if (candle.HighPrice >= _shortTrail)
			{
				BuyMarket();
				_shortTrail = 0;
			}
		}

		// Entry signals
		if (_hasPrev && stdVal > 0)
		{
			var crossUp = _prevFast <= _prevSlow && fast > slow;
			var crossDown = _prevFast >= _prevSlow && fast < slow;

			if (crossUp && Position <= 0)
			{
				BuyMarket();
				_longTrail = candle.ClosePrice - stdVal * StdFactor;
				_shortTrail = 0;
			}
			else if (crossDown && Position >= 0)
			{
				SellMarket();
				_shortTrail = candle.ClosePrice + stdVal * StdFactor;
				_longTrail = 0;
			}
		}

		_prevFast = fast;
		_prevSlow = slow;
		_hasPrev = true;
	}
}