Ver no GitHub

ADX Smoothed Cross Strategy

Summary

The strategy trades based on a double-smoothed Average Directional Index (ADX). It compares the smoothed +DI and -DI lines to detect trend changes. When the smoothed +DI line crosses above the smoothed -DI line, the strategy enters a long position. When the smoothed +DI line crosses below the smoothed -DI line, it opens a short position.

How It Works

  • Uses an ADX indicator with configurable period.
  • Applies two exponential smoothing passes controlled by Alpha1 and Alpha2 parameters.
  • A long signal occurs when the previous smoothed +DI was below the smoothed -DI and the current smoothed +DI is above.
  • A short signal occurs on the opposite cross.
  • Optional parameters allow disabling long or short trades and control whether existing positions can be closed when an opposite signal appears.
  • Built-in risk management sets stop-loss and take-profit levels in points.

Parameters

Name Description
AdxPeriod Period for the ADX calculation.
Alpha1 First smoothing coefficient (0-1).
Alpha2 Second smoothing coefficient (0-1).
StopLoss Stop-loss in points.
TakeProfit Take-profit in points.
AllowBuy Enable long entries.
AllowSell Enable short entries.
AllowCloseBuy Allow closing long positions on sell signals.
AllowCloseSell Allow closing short positions on buy signals.
CandleType Timeframe used for the indicator.

Notes

  • Only finished candles are processed.
  • The strategy uses the high-level API with indicator binding.
  • Stop-loss and take-profit are handled via StartProtection.
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>
/// Smoothed EMA crossover strategy (ADX-inspired directional cross concept).
/// Buys when fast EMA crosses above slow EMA, sells when below.
/// </summary>
public class AdxSmoothedCrossStrategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal? _prevFast;
	private decimal? _prevSlow;

	public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
	public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public AdxSmoothedCrossStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 10)
			.SetGreaterThanZero()
			.SetDisplay("Fast Period", "Fast EMA period", "Indicator");

		_slowPeriod = Param(nameof(SlowPeriod), 25)
			.SetGreaterThanZero()
			.SetDisplay("Slow Period", "Slow EMA period", "Indicator");

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

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

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

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

		var fast = new ExponentialMovingAverage { Length = FastPeriod };
		var slow = new ExponentialMovingAverage { Length = SlowPeriod };

		SubscribeCandles(CandleType)
			.Bind(fast, slow, ProcessCandle)
			.Start();
	}

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

		if (_prevFast is null || _prevSlow is null)
		{
			_prevFast = fastValue;
			_prevSlow = slowValue;
			return;
		}

		var crossUp = _prevFast <= _prevSlow && fastValue > slowValue;
		var crossDown = _prevFast >= _prevSlow && fastValue < slowValue;

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

		_prevFast = fastValue;
		_prevSlow = slowValue;
	}
}