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
- Al iniciar, la estrategia se suscribe a velas y activa
StartProtection con trailing.
- Después de la primera vela completada, la estrategia compra a precio de mercado.
- Cuando el precio se mueve a favor de la posición, el nivel del stop se mueve para mantener la distancia definida por
TrailPoints.
- 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.
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes
from StockSharp.Algo.Strategies import Strategy
class simple_trailing_stop_strategy(Strategy):
"""One long entry after first finished candle; engine-native trailing protection."""
def __init__(self):
super(simple_trailing_stop_strategy, self).__init__()
self._trail_points = self.Param("TrailPoints", 100.0).SetGreaterThanZero() \
.SetDisplay("Trail Points", "Trailing distance in security price steps", "Protection")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(8))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._submitted_entry = False
self._entry_order = None
@property
def TrailPoints(self):
return self._trail_points.Value
@TrailPoints.setter
def TrailPoints(self, value):
self._trail_points.Value = value
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
def OnReseted(self):
super(simple_trailing_stop_strategy, self).OnReseted()
self._submitted_entry = False
self._entry_order = None
def OnStarted2(self, time):
super(simple_trailing_stop_strategy, self).OnStarted2(time)
self._submitted_entry = False
self._entry_order = None
step = self.Security.PriceStep
if step is None or step <= 0:
step = 1
self.StartProtection(
takeProfit=None,
stopLoss=Unit(self.TrailPoints * step, UnitTypes.Absolute),
isStopTrailing=True,
useMarketOrders=True)
self.SubscribeCandles(self.CandleType).Bind(self.ProcessCandle).Start()
def ProcessCandle(self, candle):
if candle.State != CandleStates.Finished or self._submitted_entry:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
self._submitted_entry = True
self._entry_order = self.BuyMarket(self.Volume)
def CreateClone(self):
return simple_trailing_stop_strategy()