Auf GitHub ansehen

Strategie Auto Trailing Stop

Fügt bestehenden Positionen automatisch Stop-Loss- und Take-Profit-Aufträge hinzu und zieht den Stop nach, während sich der Preis in die günstige Richtung bewegt.

Details

  • Einstiegskriterien: Keine, die Strategie eröffnet keine Trades.
  • Long/Short: Arbeitet sowohl mit bereits offenen Long- als auch Short-Positionen.
  • Ausstiegskriterien: Stop-Loss- und Take-Profit-Aufträge. Der Trailing Stop wird aktualisiert, nachdem sich der Preis um die Hälfte der Trailing-Distanz bewegt hat.
  • Stops: Initiale Stop-Loss- und Take-Profit-Aufträge werden gesetzt, sobald die Position erscheint; der Stop-Loss folgt durch TrailingStopStep.
  • Standardwerte: TrailingStop 6, TrailingStopStep 1, TakeProfit 35, StopLoss 114.
  • Filter: Optionale Deaktivierung von Trailing Stop, automatischem Take-Profit oder automatischem Stop-Loss über Parameter.

Parameter

  • FridayTrade - Trailing an Freitagen erlauben.
  • UseTrailingStop - Trailing-Stop-Logik aktivieren.
  • AutoTrailingStop - Standard-Trailing-Distanz von 6 verwenden, wenn wahr.
  • TrailingStop - Trailing-Distanz in Preiseinheiten, wenn AutoTrailingStop falsch ist.
  • TrailingStopStep - minimale Preisbewegung, bevor der Trailing Stop verschoben wird.
  • AutomaticTakeProfit - automatisch einen Take-Profit-Auftrag platzieren.
  • TakeProfit - Take-Profit-Distanz.
  • AutomaticStopLoss - automatisch einen Stop-Loss-Auftrag platzieren.
  • StopLoss - Stop-Loss-Distanz.
  • CandleType - Kerzentyp für Preisaktualisierungen (Standard 1 Minute).
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>
/// Strategy that opens positions using a simple MA crossover and protects
/// them with a trailing stop loss and take profit.
/// </summary>
public class AutoTrailingStopStrategy : Strategy
{
	private readonly StrategyParam<int> _fastMaPeriod;
	private readonly StrategyParam<int> _slowMaPeriod;
	private readonly StrategyParam<decimal> _takeProfitPct;
	private readonly StrategyParam<decimal> _stopLossPct;
	private readonly StrategyParam<DataType> _candleType;

	private SimpleMovingAverage _slowMa;
	private decimal _prevFast;
	private decimal _prevSlow;
	private bool _isFirst = true;

	public int FastMaPeriod { get => _fastMaPeriod.Value; set => _fastMaPeriod.Value = value; }
	public int SlowMaPeriod { get => _slowMaPeriod.Value; set => _slowMaPeriod.Value = value; }
	public decimal TakeProfitPct { get => _takeProfitPct.Value; set => _takeProfitPct.Value = value; }
	public decimal StopLossPct { get => _stopLossPct.Value; set => _stopLossPct.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public AutoTrailingStopStrategy()
	{
		_fastMaPeriod = Param(nameof(FastMaPeriod), 5)
			.SetGreaterThanZero()
			.SetDisplay("Fast MA", "Fast moving average period", "Indicators");

		_slowMaPeriod = Param(nameof(SlowMaPeriod), 20)
			.SetGreaterThanZero()
			.SetDisplay("Slow MA", "Slow moving average period", "Indicators");

		_takeProfitPct = Param(nameof(TakeProfitPct), 5m)
			.SetDisplay("Take Profit %", "Take profit percentage", "Protection");

		_stopLossPct = Param(nameof(StopLossPct), 3m)
			.SetDisplay("Stop Loss %", "Initial stop loss percentage", "Protection");

		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
			.SetDisplay("Candle Type", "Candle type for price updates", "General");
	}

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

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

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

		var fastMa = new SimpleMovingAverage { Length = FastMaPeriod };
		_slowMa = new SimpleMovingAverage { Length = SlowMaPeriod };

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

		StartProtection(
			stopLoss: new Unit(StopLossPct, UnitTypes.Percent),
			takeProfit: new Unit(TakeProfitPct, UnitTypes.Percent)
		);

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

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

		var slowResult = _slowMa.Process(candle.ClosePrice, candle.OpenTime, true);
		if (!slowResult.IsFormed)
			return;

		var slow = slowResult.ToDecimal();

		if (_isFirst)
		{
			_prevFast = fast;
			_prevSlow = slow;
			_isFirst = false;
			return;
		}

		// Bullish crossover: fast crosses above slow
		if (_prevFast <= _prevSlow && fast > slow && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		// Bearish crossover: fast crosses below slow
		else if (_prevFast >= _prevSlow && fast < slow && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevFast = fast;
		_prevSlow = slow;
	}
}