Auf GitHub ansehen

Autotrader Momentum Strategie

Überblick

Die Autotrader Momentum Strategie ist eine Konvertierung des MetaTrader 5 Expert Advisors Autotrader Momentum (barabashkakvn's Edition). Der Algorithmus bewertet den aktuellen Momentum, indem er den Schlusskurs der Überwachungskerze mit dem Schlusskurs einer historischen Referenzkerze vergleicht. Wird ein bullischer Momentum-Wechsel erkannt, kauft die Strategie; erscheint ein bärischer Wechsel, wird verkauft. Alle Orders werden zum Marktpreis über StockSharp's High-Level Trading-API ausgeführt.

Die Implementierung behält den ursprünglichen Fokus auf punktbasierter Risikosteuerung bei. Stop-Loss-, Take-Profit- und Trailing-Stop-Abstände werden in Pips definiert und automatisch in Preisoffsets auf Basis des PriceStep des Instruments übersetzt. Die Unterstützung für drei- und fünfstellige Kursnotierungen bleibt durch Anwendung der gleichen 10x-Anpassung aus dem MQL-Code erhalten. Die Trailing-Logik wird bei jeder abgeschlossenen Kerze vor der Berücksichtigung neuer Einstiege ausgewertet, um sicherzustellen, dass das Risikomanagement das EA-Verhalten widerspiegelt, schützende Ausstiege zu priorisieren.

Handelslogik

  1. Den konfigurierten CandleType abonnieren und nur abgeschlossene Kerzen verarbeiten, passend zur "neuen Balken"-Logik des ursprünglichen EA.
  2. Ein rollendes Fenster mit Schlusskursen der Größe max(CurrentBarIndex, ComparableBarIndex) + 1 pflegen.
  3. Den Schlusskurs der überwachten Kerze (CurrentBarIndex, Standard 0) mit dem Schlusskurs der historischen Kerze (ComparableBarIndex, Standard 15) vergleichen.
  4. Ist der überwachte Schlusskurs größer als der Referenzschlusskurs, das Short-Exposure schließen und das konfigurierte Handelsvolumen kaufen.
  5. Ist der überwachte Schlusskurs kleiner als der Referenzschlusskurs, das Long-Exposure schließen und das konfigurierte Handelsvolumen verkaufen.
  6. Jeder Einstieg berechnet den durchschnittlichen Einstiegspreis neu und aktualisiert die Stop-Loss-, Take-Profit- und Trailing-Stop-Level.

Da StockSharp-Strategien mit einer Nettoposition arbeiten, kombinieren Umkehrungen das Volumen, das zum Schließen des entgegengesetzten Exposures erforderlich ist, mit dem konfigurierten Basisvolumen. Dies entspricht dem MQL-Verhalten, das zuerst die entgegengesetzte Seite schloss und dann eine neue Order der gewünschten Größe eröffnete.

Parameter

  • CandleType – Zeitrahmen für den Preisvergleich. Standard: 1 Stunde.
  • TradeVolume – Basis-Marktordervolumen. Wird bei jedem Signal zusätzlich zu dem Volumen angewendet, das zum Umkehren einer bestehenden Position benötigt wird.
  • StopLossPips – Schutz-Stop-Abstand in Pips. Auf 0 setzen, um den festen Stop-Loss zu deaktivieren.
  • TakeProfitPips – Gewinnziel-Abstand in Pips. Auf 0 setzen, um den festen Take-Profit zu deaktivieren.
  • TrailingStopPips – Abstand, der vom Trailing Stop eingehalten wird. Auf 0 setzen, um das Trailing zu deaktivieren.
  • TrailingStepPips – Minimale günstige Bewegung, die erforderlich ist, bevor der Trailing Stop vorgerückt wird. Muss positiv sein, wenn Trailing aktiviert ist.
  • CurrentBarIndex – Index der Überwachungskerze (0 = zuletzt abgeschlossener Balken).
  • ComparableBarIndex – Index der historischen Kerze für den Momentum-Vergleich.

Alle Pip-basierten Einstellungen werden mithilfe des PriceStep des Instruments in Preisoffsets umgerechnet. Repräsentiert der Step drei oder fünf Dezimalstellen, wird der Offset mit 10 multipliziert, um die MetaTrader-Definition eines Pips zu reproduzieren.

Risikomanagement

  • Feste Stops und Ziele: Wenn StopLossPips oder TakeProfitPips größer als null sind, pflegt die Strategie entsprechende Preislevel relativ zum gemittelten Einstiegspreis.
  • Trailing Stop: Aktiviert, wenn sowohl TrailingStopPips als auch TrailingStepPips positiv sind. Die Trailing-Logik verschiebt den Schutz-Stop erst, nachdem sich der Preis um mindestens TrailingStopPips + TrailingStepPips vom gemittelten Einstiegspreis entfernt hat, und repliziert damit die EA-Anforderung, die sicherstellte, dass die Bewegung groß genug ist, bevor der Stop angepasst wird.
  • Zustandsreset: Kehrt die Position zu null zurück—entweder durch strategiegetriebene Ausstiege oder externe Eingriffe—wird der zwischengespeicherte Risikostand gelöscht, um veraltete Stop- oder Take-Profit-Level zu vermeiden.

Implementierungshinweise

  • Die Strategie stützt sich ausschließlich auf StockSharp's High-Level Markt-API (BuyMarket, SellMarket) und vermeidet Indikatorsammlungen, um den Konvertierungsrichtlinien treu zu bleiben.
  • Schlusskurse werden in einer einfachen rollenden Liste gepuffert, sodass CurrentBarIndex und ComparableBarIndex zur Laufzeit ohne Neustart geändert werden können.
  • Da StockSharp mit einer Nettoposition arbeitet, werden Stop-Loss- und Take-Profit-Level für das aggregierte Exposure verfolgt. Werden zusätzliche Orders in dieselbe Richtung geschichtet, berechnet der Code einen volumengewichteten Durchschnittseinstiegspreis, bevor die Risiko-Level aktualisiert werden.
  • Trailing-Stop-Anpassungen und schützende Ausstiege werden vor neuen Signalen bei jeder Kerze verarbeitet, um zu verhindern, dass neue Einstiege ausgewertet werden, wenn bereits ein Ausstieg für diesen Balken ausgegeben wurde.

Originalstrategie-Referenz

  • Quelle: MQL/22409/Autotrader Momentum.mq5
  • Autor: barabashkakvn (MetaTrader-Community)
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>
/// Momentum strategy converted from the MetaTrader 5 expert advisor "Autotrader Momentum".
/// Compares the most recent closing price with a historical reference bar and reverses positions when momentum shifts.
/// Includes configurable fixed stops, take profit targets, and an optional trailing stop engine measured in pips.
/// </summary>
public class AutotraderMomentumStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<decimal> _tradeVolume;
	private readonly StrategyParam<int> _stopLossPips;
	private readonly StrategyParam<int> _takeProfitPips;
	private readonly StrategyParam<int> _trailingStopPips;
	private readonly StrategyParam<int> _trailingStepPips;
	private readonly StrategyParam<int> _cooldownBars;
	private readonly StrategyParam<int> _currentBarIndex;
	private readonly StrategyParam<int> _comparableBarIndex;

	private readonly List<decimal> _closeHistory = new();

	private decimal? _entryPrice;
	private decimal? _stopPrice;
	private decimal? _takeProfitPrice;
	private bool _isLongPosition;

	private decimal _pipValue;
	private decimal _stopLossOffset;
	private decimal _takeProfitOffset;
	private decimal _trailingStopOffset;
	private decimal _trailingStepOffset;
	private int _cooldownLeft;

	/// <summary>
	/// Initializes a new instance of the <see cref="AutotraderMomentumStrategy"/> class.
	/// </summary>
	public AutotraderMomentumStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Primary timeframe for price comparisons", "Data");

		_tradeVolume = Param(nameof(TradeVolume), 1m)
			.SetDisplay("Trade Volume", "Base order volume used for market entries", "Trading")
			.SetGreaterThanZero();

		_stopLossPips = Param(nameof(StopLossPips), 50)
			.SetDisplay("Stop Loss (pips)", "Protective stop distance expressed in pips", "Risk")
			.SetNotNegative();

		_takeProfitPips = Param(nameof(TakeProfitPips), 50)
			.SetDisplay("Take Profit (pips)", "Profit target distance expressed in pips", "Risk")
			.SetNotNegative();

		_trailingStopPips = Param(nameof(TrailingStopPips), 0)
			.SetDisplay("Trailing Stop (pips)", "Distance maintained by the trailing stop in pips", "Risk")
			.SetNotNegative();

		_trailingStepPips = Param(nameof(TrailingStepPips), 5)
			.SetDisplay("Trailing Step (pips)", "Minimum progress before the trailing stop advances", "Risk")
			.SetNotNegative();

		_cooldownBars = Param(nameof(CooldownBars), 2)
			.SetDisplay("Cooldown Bars", "Bars to wait after entries and exits", "Risk")
			.SetNotNegative();

		_currentBarIndex = Param(nameof(CurrentBarIndex), 0)
			.SetDisplay("Current Bar Index", "Index of the candle used as the signal source", "Logic")
			.SetNotNegative();

		_comparableBarIndex = Param(nameof(ComparableBarIndex), 8)
			.SetDisplay("Comparable Bar Index", "Historical candle index used for momentum comparison", "Logic")
			.SetNotNegative();
	}

	/// <summary>
	/// Gets or sets the candle type used for generating signals.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Gets or sets the base order volume.
	/// </summary>
	public decimal TradeVolume
	{
		get => _tradeVolume.Value;
		set => _tradeVolume.Value = value;
	}

	/// <summary>
	/// Gets or sets the stop-loss distance in pips.
	/// </summary>
	public int StopLossPips
	{
		get => _stopLossPips.Value;
		set => _stopLossPips.Value = value;
	}

	/// <summary>
	/// Gets or sets the take-profit distance in pips.
	/// </summary>
	public int TakeProfitPips
	{
		get => _takeProfitPips.Value;
		set => _takeProfitPips.Value = value;
	}

	/// <summary>
	/// Gets or sets the trailing stop distance in pips.
	/// </summary>
	public int TrailingStopPips
	{
		get => _trailingStopPips.Value;
		set => _trailingStopPips.Value = value;
	}

	/// <summary>
	/// Gets or sets the trailing step distance in pips.
	/// </summary>
	public int TrailingStepPips
	{
		get => _trailingStepPips.Value;
		set => _trailingStepPips.Value = value;
	}

	/// <summary>
	/// Gets or sets the index of the candle considered the "current" bar in comparisons.
	/// </summary>
	public int CurrentBarIndex
	{
		get => _currentBarIndex.Value;
		set => _currentBarIndex.Value = value;
	}

	/// <summary>
	/// Gets or sets the index of the historical bar used for comparison.
	/// </summary>
	public int ComparableBarIndex
	{
		get => _comparableBarIndex.Value;
		set => _comparableBarIndex.Value = value;
	}

	public int CooldownBars
	{
		get => _cooldownBars.Value;
		set => _cooldownBars.Value = value;
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();

		_closeHistory.Clear();
		ResetPositionState();

		_pipValue = 0m;
		_stopLossOffset = 0m;
		_takeProfitOffset = 0m;
		_trailingStopOffset = 0m;
		_trailingStepOffset = 0m;
		_cooldownLeft = 0;
	}

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

		if (TrailingStopPips > 0 && TrailingStepPips <= 0)
			throw new InvalidOperationException("Trailing step must be positive when trailing stop is enabled.");

		Volume = TradeVolume;

		_pipValue = CalculatePipValue();
		_stopLossOffset = StopLossPips > 0 ? StopLossPips * _pipValue : 0m;
		_takeProfitOffset = TakeProfitPips > 0 ? TakeProfitPips * _pipValue : 0m;
		_trailingStopOffset = TrailingStopPips > 0 ? TrailingStopPips * _pipValue : 0m;
		_trailingStepOffset = TrailingStepPips > 0 ? TrailingStepPips * _pipValue : 0m;
		_cooldownLeft = 0;

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

	private void ProcessCandle(ICandleMessage candle)
	{
		// Ignore incomplete candles to mirror the original new-bar processing style.
		if (candle.State != CandleStates.Finished)
			return;

		if (_cooldownLeft > 0)
			_cooldownLeft--;

		// Update trailing and risk management before evaluating fresh signals.
		UpdateTrailingStop(candle);
		var exitTriggered = ManageProtectiveExits(candle);

		// Maintain the rolling window of closes used for momentum comparisons.
		UpdateCloseHistory(candle.ClosePrice);

		// Skip signal generation if an exit order has just been triggered on this bar.
		if (exitTriggered)
			return;

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		if (_cooldownLeft > 0)
			return;

		var requiredHistory = Math.Max(CurrentBarIndex, ComparableBarIndex) + 1;
		if (_closeHistory.Count < requiredHistory)
			return;

		var currentClose = GetCloseAtIndex(CurrentBarIndex);
		var comparableClose = GetCloseAtIndex(ComparableBarIndex);
		if (currentClose == null || comparableClose == null)
			return;

		// Enter long when the monitored bar closes above the reference bar.
		if (currentClose > comparableClose && Position <= 0)
		{
			EnterPosition(true, candle);
		}
		// Enter short when the monitored bar closes below the reference bar.
		else if (currentClose < comparableClose && Position >= 0)
		{
			EnterPosition(false, candle);
		}
	}

	private void UpdateCloseHistory(decimal closePrice)
	{
		var maxCount = Math.Max(CurrentBarIndex, ComparableBarIndex) + 1;
		if (maxCount <= 0)
			maxCount = 1;

		_closeHistory.Add(closePrice);
		if (_closeHistory.Count > maxCount)
			_closeHistory.RemoveAt(0);
	}

	private decimal? GetCloseAtIndex(int indexFromCurrent)
	{
		if (indexFromCurrent < 0)
			return null;

		var targetIndex = _closeHistory.Count - 1 - indexFromCurrent;
		if (targetIndex < 0 || targetIndex >= _closeHistory.Count)
			return null;

		return _closeHistory[targetIndex];
	}

	private void EnterPosition(bool isLong, ICandleMessage candle)
	{
		var baseVolume = TradeVolume;
		if (baseVolume <= 0m)
			return;

		var previousPosition = Position;
		decimal volume;

		if (isLong)
		{
			volume = baseVolume;
			if (previousPosition < 0m)
				volume += Math.Abs(previousPosition);

			if (volume <= 0m)
				return;

			// Buy enough volume to close any short exposure and add the configured trade size.
			BuyMarket(volume);

			if (previousPosition <= 0m)
			{
				// Treat reversals and fresh entries as a brand-new long position.
				_entryPrice = candle.ClosePrice;
			}
			else
			{
				// Blend the existing average price with the new fill to keep risk metrics consistent.
				var existingVolume = previousPosition;
				var totalVolume = existingVolume + baseVolume;
				if (totalVolume > 0m)
				{
					var existingEntry = _entryPrice ?? candle.ClosePrice;
					_entryPrice = (existingEntry * existingVolume + candle.ClosePrice * baseVolume) / totalVolume;
				}
			}

			_isLongPosition = true;
		}
		else
		{
			volume = baseVolume;
			if (previousPosition > 0m)
				volume += previousPosition;

			if (volume <= 0m)
				return;

			// Sell enough volume to close any long exposure and add the configured trade size.
			SellMarket(volume);

			if (previousPosition >= 0m)
			{
				// Treat reversals and fresh entries as a brand-new short position.
				_entryPrice = candle.ClosePrice;
			}
			else
			{
				// Blend the existing short average price with the new fill.
				var existingVolume = Math.Abs(previousPosition);
				var totalVolume = existingVolume + baseVolume;
				if (totalVolume > 0m)
				{
					var existingEntry = _entryPrice ?? candle.ClosePrice;
					_entryPrice = (existingEntry * existingVolume + candle.ClosePrice * baseVolume) / totalVolume;
				}
			}

			_isLongPosition = false;
		}

		_stopPrice = CalculateStopPrice(_isLongPosition, _entryPrice);
		_takeProfitPrice = CalculateTakeProfit(_isLongPosition, _entryPrice);
		_cooldownLeft = CooldownBars;
	}

	private decimal? CalculateStopPrice(bool isLong, decimal? entryPrice)
	{
		if (entryPrice == null || _stopLossOffset <= 0m)
			return null;

		return isLong ? entryPrice - _stopLossOffset : entryPrice + _stopLossOffset;
	}

	private decimal? CalculateTakeProfit(bool isLong, decimal? entryPrice)
	{
		if (entryPrice == null || _takeProfitOffset <= 0m)
			return null;

		return isLong ? entryPrice + _takeProfitOffset : entryPrice - _takeProfitOffset;
	}

	private void UpdateTrailingStop(ICandleMessage candle)
	{
		if (_trailingStopOffset <= 0m || _trailingStepOffset <= 0m || _entryPrice == null)
			return;

		if (Position > 0m)
		{
			var progress = candle.HighPrice - _entryPrice.Value;
			if (progress <= _trailingStopOffset + _trailingStepOffset)
				return;

			// Shift the trailing stop only when the move is large enough to respect the configured step.
			var desiredStop = candle.ClosePrice - _trailingStopOffset;
			if (_stopPrice is decimal currentStop)
			{
				if (desiredStop - currentStop >= _trailingStepOffset)
					_stopPrice = desiredStop;
			}
			else
			{
				_stopPrice = desiredStop;
			}
		}
		else if (Position < 0m)
		{
			var progress = _entryPrice.Value - candle.LowPrice;
			if (progress <= _trailingStopOffset + _trailingStepOffset)
				return;

			var desiredStop = candle.ClosePrice + _trailingStopOffset;
			if (_stopPrice is decimal currentStop)
			{
				if (currentStop - desiredStop >= _trailingStepOffset)
					_stopPrice = desiredStop;
			}
			else
			{
				_stopPrice = desiredStop;
			}
		}
	}

	private bool ManageProtectiveExits(ICandleMessage candle)
	{
		if (Position > 0m)
		{
			// Close the long position if the bar traded through the stop level.
			if (_stopPrice is decimal stop && candle.LowPrice <= stop)
			{
				SellMarket(Position);
				ResetPositionState();
				_cooldownLeft = CooldownBars;
				return true;
			}

			// Lock in profits once the take-profit threshold has been reached.
			if (_takeProfitPrice is decimal take && candle.HighPrice >= take)
			{
				SellMarket(Position);
				ResetPositionState();
				_cooldownLeft = CooldownBars;
				return true;
			}
		}
		else if (Position < 0m)
		{
			var volume = Math.Abs(Position);

			if (_stopPrice is decimal stop && candle.HighPrice >= stop)
			{
				BuyMarket(volume);
				ResetPositionState();
				_cooldownLeft = CooldownBars;
				return true;
			}

			if (_takeProfitPrice is decimal take && candle.LowPrice <= take)
			{
				BuyMarket(volume);
				ResetPositionState();
				_cooldownLeft = CooldownBars;
				return true;
			}
		}
		else
		{
			// Ensure cached state is flushed once all positions are closed externally.
			ResetPositionState();
		}

		return false;
	}

	private void ResetPositionState()
	{
		_entryPrice = null;
		_stopPrice = null;
		_takeProfitPrice = null;
		_isLongPosition = false;
	}

	private decimal CalculatePipValue()
	{
		var step = Security?.PriceStep ?? 0m;
		if (step <= 0m)
			return 1m;

		var scaled = step;
		var digits = 0;
		while (scaled < 1m && digits < 10)
		{
			scaled *= 10m;
			digits++;
		}

		// Adjust for three and five decimal quotes to emulate the MetaTrader point multiplier.
		var adjust = (digits == 3 || digits == 5) ? 10m : 1m;
		return step * adjust;
	}
}