Auf GitHub ansehen

Alexav SpeedUp M1 Strategie

Überblick

  • Konvertierung des Expert Advisors "Alexav SpeedUp M1" aus MetaTrader 5 in die StockSharp High-Level-API.
  • Entwickelt für schnelle Märkte im 1-Minuten-Zeitrahmen (Standard) und reagiert auf ungewöhnlich große Kerzenkörper.
  • Eröffnet eine einzige Nettoposition in Richtung des starken Kerzenkörpers und verwaltet sie mit festem Stop-Loss, Take-Profit und einem gestuften Trailing-Stop.
  • Verwendet pip-basierte Eingaben, die automatisch nach der Tick-Größe des Instruments und der Dezimalgenauigkeit in Preisabstände umgerechnet werden.

Ursprüngliche Idee vs. StockSharp-Implementierung

  • Der ursprüngliche EA öffnete auf Hedging-Konten gleichzeitig Long- und Short-Trades. StockSharp-Strategien arbeiten in einer Netting-Umgebung, daher hält dieser Port nur eine Position gleichzeitig und tritt in Richtung der großen Kerze ein.
  • Die Trailing-Stop-Logik folgt der MT5-Version: Sie wartet, bis der Preis sich um TrailingStop + TrailingStep bewegt hat, bevor der Stop um die Trailing-Distanz näher gerückt wird, und aktualisiert nur, wenn der Preis mindestens einen Trailing-Step über den vorherigen Stop hinaus vorrückt.
  • Pip-Abstände werden in Preiseinheiten umgerechnet, indem mit der minimalen Tick-Größe multipliziert wird. Für Forex-Symbole mit 3 oder 5 Dezimalstellen multipliziert der Code den Tick mit 10, um die MT5-Pip-Behandlung zu emulieren.

Einstiegsregeln

  1. Mit abgeschlossenen Kerzen des ausgewählten Zeitrahmens arbeiten (Standard: 1 Minute).
  2. Den Kerzenkörper messen: abs(Close - Open).
  3. Wenn der Körper MinimumBodySizePips * pipSize überschreitet und keine aktive Position vorhanden ist, in Richtung des Kerzenkörpers einsteigen:
    • Bullische Kerze → Long-Position eröffnen.
    • Bärische Kerze → Short-Position eröffnen.

Ausstiegsregeln

  • Stop-Loss – platziert StopLossPips * pipSize vom Einstiegspreis entfernt. Deaktiviert, wenn der Parameter null ist.
  • Take-Profit – platziert TakeProfitPips * pipSize vom Einstieg entfernt. Deaktiviert, wenn der Parameter null ist.
  • Trailing-Stop – aktiviert, wenn TrailingStopPips > 0 und TrailingStepPips > 0.
    • Wird aktiviert, nachdem der Trade mindestens TrailingStopPips + TrailingStepPips Pips gewonnen hat.
    • Bei Long-Trades wird der Stop auf Close - TrailingStopPips * pipSize verschoben, wenn die Bedingung erfüllt ist und der Preis mindestens einen Trailing-Step über den vorherigen Stop hinaus vorrückte.
    • Bei Short-Trades wird der Stop mit derselben Schritt-Bedingung auf Close + TrailingStopPips * pipSize verschoben.

Parameter

  • OrderVolume – Handelsgröße in Lots (Standard 0.1).
  • StopLossPips – Stop-Loss-Abstand in Pips (Standard 30).
  • TakeProfitPips – Take-Profit-Abstand in Pips (Standard 90).
  • TrailingStopPips – Trailing-Stop-Abstand in Pips (Standard 10).
  • TrailingStepPips – Mindest-Vorwärtsbewegung, bevor der Trailing-Stop aktualisiert wird (Standard 5). Muss größer als null sein, wenn der Trailing-Stop aktiviert ist.
  • MinimumBodySizePips – Mindest-Körpergröße (in Pips), die zum Auslösen eines Trades erforderlich ist (Standard 100).
  • CandleType – Zeitrahmen für Kerzen (Standard 1 Minute).

Visualisierung

  • Die Strategie zeichnet automatisch die ausgewählte Kerzenserie und eigene Trades im Diagrammbereich, wenn einer verfügbar ist, was die Signalinspektion beim Testen vereinfacht.

Verwendungshinweise

  • Die Standardkonfiguration spiegelt die MT5-Einstellungen wider. Pip-Abstände anpassen, um die Volatilität des gehandelten Instruments zu berücksichtigen.
  • Da nur eine Nettoposition unterstützt wird, die Strategie nicht auf Hedging-Konten ausführen, die gleichzeitige Long- und Short-Positionen erwarten.
  • Für Märkte mit größeren Tick-Größen die pip-basierten Eingaben entsprechend reduzieren, um vergleichbare Preisabstände beizubehalten.
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>
/// Candle breakout strategy converted from the Alexav SpeedUp M1 expert advisor.
/// Enters in the direction of strong candle bodies and manages exits with optional stop-loss,
/// take-profit, and trailing stop logic.
/// </summary>
public class AlexavSpeedUpM1Strategy : Strategy
{
	private readonly StrategyParam<decimal> _orderVolume;
	private readonly StrategyParam<int> _stopLossPips;
	private readonly StrategyParam<int> _takeProfitPips;
	private readonly StrategyParam<int> _trailingStopPips;
	private readonly StrategyParam<int> _trailingStepPips;
	private readonly StrategyParam<int> _minimumBodySizePips;
	private readonly StrategyParam<DataType> _candleType;

	private Sides? _currentDirection;
	private decimal _entryPrice;
	private decimal? _stopPrice;
	private decimal? _takeProfitPrice;
	private decimal? _trailingStopDistance;
	private decimal? _trailingStepDistance;

	/// <summary>
	/// Order volume in lots.
	/// </summary>
	public decimal OrderVolume
	{
		get => _orderVolume.Value;
		set => _orderVolume.Value = value;
	}

	/// <summary>
	/// Stop-loss distance in pips.
	/// </summary>
	public int StopLossPips
	{
		get => _stopLossPips.Value;
		set => _stopLossPips.Value = value;
	}

	/// <summary>
	/// Take-profit distance in pips.
	/// </summary>
	public int TakeProfitPips
	{
		get => _takeProfitPips.Value;
		set => _takeProfitPips.Value = value;
	}

	/// <summary>
	/// Trailing stop distance in pips.
	/// </summary>
	public int TrailingStopPips
	{
		get => _trailingStopPips.Value;
		set => _trailingStopPips.Value = value;
	}

	/// <summary>
	/// Trailing step in pips.
	/// </summary>
	public int TrailingStepPips
	{
		get => _trailingStepPips.Value;
		set => _trailingStepPips.Value = value;
	}

	/// <summary>
	/// Minimum candle body size required to open a trade, expressed in pips.
	/// </summary>
	public int MinimumBodySizePips
	{
		get => _minimumBodySizePips.Value;
		set => _minimumBodySizePips.Value = value;
	}

	/// <summary>
	/// Type of candles used for calculations.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Initializes a new instance of <see cref="AlexavSpeedUpM1Strategy"/>.
	/// </summary>
	public AlexavSpeedUpM1Strategy()
	{
		_orderVolume = Param(nameof(OrderVolume), 0.1m)
		.SetGreaterThanZero()
		.SetDisplay("Order Volume", "Position size in lots", "General");

		_stopLossPips = Param(nameof(StopLossPips), 30)
		.SetDisplay("Stop Loss (pips)", "Stop-loss distance in pips", "Risk Management")
		
		.SetOptimize(10, 100, 10);

		_takeProfitPips = Param(nameof(TakeProfitPips), 90)
		.SetDisplay("Take Profit (pips)", "Take-profit distance in pips", "Risk Management")
		
		.SetOptimize(30, 180, 30);

		_trailingStopPips = Param(nameof(TrailingStopPips), 10)
		.SetDisplay("Trailing Stop (pips)", "Trailing stop distance in pips", "Risk Management")
		
		.SetOptimize(5, 30, 5);

		_trailingStepPips = Param(nameof(TrailingStepPips), 5)
		.SetDisplay("Trailing Step (pips)", "Price movement required to move the trailing stop", "Risk Management")
		
		.SetOptimize(5, 20, 5);

		_minimumBodySizePips = Param(nameof(MinimumBodySizePips), 100)
		.SetDisplay("Minimum Body (pips)", "Minimum candle body size to trigger entries", "Signal")
		
		.SetOptimize(50, 200, 10);

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

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

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

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

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

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

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

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

		if (_currentDirection != null && Position == 0)
			ResetPositionState();

		if (_currentDirection != null)
		{
			if (ManageActivePosition(candle))
				return;
		}


		var pipSize = GetPipSize();
		var minimumBody = MinimumBodySizePips <= 0 ? 0m : MinimumBodySizePips * pipSize;
		var bodySize = Math.Abs(candle.ClosePrice - candle.OpenPrice);

		if (bodySize <= minimumBody)
			return;

		if (_currentDirection != null)
			return;

		var direction = candle.ClosePrice >= candle.OpenPrice ? Sides.Buy : Sides.Sell;
		OpenPosition(direction, candle.ClosePrice);
	}

	private bool ManageActivePosition(ICandleMessage candle)
	{
		if (_currentDirection == null)
			return false;

		var high = candle.HighPrice;
		var low = candle.LowPrice;
		var close = candle.ClosePrice;

		if (_currentDirection == Sides.Buy)
		{
			if (_stopPrice is decimal stop && low <= stop)
			{
				ClosePosition();
				return true;
			}

			if (_takeProfitPrice is decimal take && high >= take)
			{
				ClosePosition();
				return true;
			}

			UpdateTrailingStopForLong(close);
		}
		else if (_currentDirection == Sides.Sell)
		{
			if (_stopPrice is decimal stop && high >= stop)
			{
				ClosePosition();
				return true;
			}

			if (_takeProfitPrice is decimal take && low <= take)
			{
				ClosePosition();
				return true;
			}

			UpdateTrailingStopForShort(close);
		}

		return false;
	}

	private void OpenPosition(Sides direction, decimal price)
	{
		if (OrderVolume <= 0)
			return;

		var desiredPosition = direction == Sides.Buy ? OrderVolume : -OrderVolume;
		var difference = desiredPosition - Position;

		if (difference > 0)
			BuyMarket(difference);
		else if (difference < 0)
			SellMarket(-difference);

		_currentDirection = direction;
		_entryPrice = price;

		var pipSize = GetPipSize();

		_stopPrice = StopLossPips > 0
			? direction == Sides.Buy
				? price - StopLossPips * pipSize
				: price + StopLossPips * pipSize
			: null;

		_takeProfitPrice = TakeProfitPips > 0
			? direction == Sides.Buy
				? price + TakeProfitPips * pipSize
				: price - TakeProfitPips * pipSize
			: null;

		if (TrailingStopPips > 0)
		{
			_trailingStopDistance = TrailingStopPips * pipSize;
			_trailingStepDistance = TrailingStepPips * pipSize;
		}
		else
		{
			_trailingStopDistance = null;
			_trailingStepDistance = null;
		}
	}

	private void ClosePosition()
	{
		var currentPosition = Position;

		if (currentPosition > 0)
			SellMarket(currentPosition);
		else if (currentPosition < 0)
			BuyMarket(-currentPosition);

		ResetPositionState();
	}

	private void UpdateTrailingStopForLong(decimal price)
	{
		if (_trailingStopDistance is not decimal trailing || _trailingStepDistance is not decimal step)
			return;

		if (price - _entryPrice < trailing + step)
			return;

		var candidate = price - trailing;

		if (_stopPrice is decimal stop && stop >= candidate - step)
			return;

		_stopPrice = candidate;
	}

	private void UpdateTrailingStopForShort(decimal price)
	{
		if (_trailingStopDistance is not decimal trailing || _trailingStepDistance is not decimal step)
			return;

		if (_entryPrice - price < trailing + step)
			return;

		var candidate = price + trailing;

		if (_stopPrice is decimal stop && stop <= candidate + step)
			return;

		_stopPrice = candidate;
	}

	private void ResetPositionState()
	{
		_currentDirection = null;
		_entryPrice = 0m;
		_stopPrice = null;
		_takeProfitPrice = null;
		_trailingStopDistance = null;
		_trailingStepDistance = null;
	}

	private decimal GetPipSize()
	{
		var step = Security?.PriceStep ?? 0.0001m;
		var decimals = Security?.Decimals ?? 5;

		if (decimals == 3 || decimals == 5)
			return step * 10m;

		return step;
	}
}