Ver en GitHub

Estrategia Simple de Trailing Stop

Este ejemplo demuestra cómo gestionar una posición abierta con un trailing stop usando la API de alto nivel de StockSharp.

Descripción general

  • Abre una única posición larga después de recibir la primera vela completada.
  • Activa la protección de posición con un trailing stop.
  • El precio del stop sigue al precio actual a una distancia fija.

Parámetros

  • TrailPoints – distancia en puntos de precio usada para seguir el stop.
  • CandleType – tipo de velas procesadas por la estrategia.

Lógica

  1. Al iniciar, la estrategia se suscribe a velas y activa StartProtection con trailing.
  2. Después de la primera vela completada, la estrategia compra a precio de mercado.
  3. Cuando el precio se mueve a favor de la posición, el nivel del stop se mueve para mantener la distancia definida por TrailPoints.
  4. Si el precio revierte y toca el trailing stop, la posición se cierra automáticamente.

La estrategia está simplificada y está pensada para mostrar el uso básico del trailing stop.

using System;
using System.Collections.Generic;

using Ecng.Common;

using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Demonstrates exactly one market long entry after the first finished candle,
/// followed by the engine's fill-price-based native trailing stop.
/// </summary>
public class SimpleTrailingStopStrategy : Strategy
{
	private readonly StrategyParam<decimal> _trailPoints;
	private readonly StrategyParam<DataType> _candleType;
	private bool _submittedEntry;
	private Order _entryOrder;

	public decimal TrailPoints { get => _trailPoints.Value; set => _trailPoints.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public SimpleTrailingStopStrategy()
	{
		_trailPoints = Param(nameof(TrailPoints), 100m).SetGreaterThanZero()
			.SetDisplay("Trail Points", "Trailing distance in security price steps", "Protection");
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(8).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles", "General");
	}

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_submittedEntry = false;
		_entryOrder = null;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);
		_submittedEntry = false;
		_entryOrder = null;

		StartProtection(
			takeProfit: null,
			stopLoss: new Unit(TrailPoints * (Security.PriceStep ?? 1m), UnitTypes.Absolute),
			isStopTrailing: true,
			useMarketOrders: true);

		SubscribeCandles(CandleType).Bind(ProcessCandle).Start();
	}

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

		// Mark before sending: avoid duplicate opens on synchronous fills or callbacks.
		_submittedEntry = true;
		_entryOrder = BuyMarket(Volume);
		// Do not reopen after a protective stop fills: this is a one-shot example.
	}
}