Autostop 策略
用于自动为已有头寸设置止盈和止损的实用策略。 策略本身不生成交易信号,任何在外部打开的仓位都会按照固定距离进行保护。
详情
- 入场条件:无,订单由外部管理。
- 多空方向:双向。
- 退出条件:仅防护订单。
- 止损:通过 StartProtection 设置固定止盈和止损。
- 默认值:
MonitorTakeProfit= trueMonitorStopLoss= trueTakeProfitTicks= 30StopLossTicks= 30
- 过滤器:
- 类别:风险管理
- 方向:双向
- 指标:无
- 止损:固定
- 复杂度:基础
- 时间框架:任意
- 季节性:无
- 神经网络:无
- 背离:无
- 风险等级:低
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 with automatic take-profit and stop-loss based on ATR.
/// Uses EMA crossover for entry signals with ATR-based TP/SL management.
/// </summary>
public class AutostopStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<int> _atrLength;
private readonly StrategyParam<decimal> _tpMultiplier;
private readonly StrategyParam<decimal> _slMultiplier;
private readonly StrategyParam<DataType> _candleType;
private decimal _entryPrice;
private decimal _takePrice;
private decimal _stopPrice;
public int FastLength { get => _fastLength.Value; set => _fastLength.Value = value; }
public int SlowLength { get => _slowLength.Value; set => _slowLength.Value = value; }
public int AtrLength { get => _atrLength.Value; set => _atrLength.Value = value; }
public decimal TpMultiplier { get => _tpMultiplier.Value; set => _tpMultiplier.Value = value; }
public decimal SlMultiplier { get => _slMultiplier.Value; set => _slMultiplier.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
/// <summary>
/// Initializes a new instance of <see cref="AutostopStrategy"/>.
/// </summary>
public AutostopStrategy()
{
_fastLength = Param(nameof(FastLength), 10)
.SetGreaterThanZero()
.SetDisplay("Fast EMA", "Fast EMA period", "General");
_slowLength = Param(nameof(SlowLength), 20)
.SetGreaterThanZero()
.SetDisplay("Slow EMA", "Slow EMA period", "General");
_atrLength = Param(nameof(AtrLength), 14)
.SetGreaterThanZero()
.SetDisplay("ATR Length", "ATR period for TP/SL", "Risk");
_tpMultiplier = Param(nameof(TpMultiplier), 2m)
.SetGreaterThanZero()
.SetDisplay("TP Multiplier", "ATR multiplier for take profit", "Risk");
_slMultiplier = Param(nameof(SlMultiplier), 1.5m)
.SetGreaterThanZero()
.SetDisplay("SL Multiplier", "ATR multiplier for stop loss", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_entryPrice = 0m;
_takePrice = 0m;
_stopPrice = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fastEma = new ExponentialMovingAverage { Length = FastLength };
var slowEma = new ExponentialMovingAverage { Length = SlowLength };
var atr = new StandardDeviation { Length = AtrLength };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(fastEma, slowEma, atr, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fastEma);
DrawIndicator(area, slowEma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow, decimal atrValue)
{
if (candle.State != CandleStates.Finished)
return;
// Check TP/SL for existing positions
if (Position > 0)
{
if (candle.ClosePrice >= _takePrice || candle.ClosePrice <= _stopPrice)
{
SellMarket();
return;
}
}
else if (Position < 0)
{
if (candle.ClosePrice <= _takePrice || candle.ClosePrice >= _stopPrice)
{
BuyMarket();
return;
}
}
// Entry signals
if (fast > slow && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
_entryPrice = candle.ClosePrice;
_takePrice = _entryPrice + atrValue * TpMultiplier;
_stopPrice = _entryPrice - atrValue * SlMultiplier;
}
else if (fast < slow && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
_entryPrice = candle.ClosePrice;
_takePrice = _entryPrice - atrValue * TpMultiplier;
_stopPrice = _entryPrice + atrValue * SlMultiplier;
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ExponentialMovingAverage, StandardDeviation
from StockSharp.Algo.Strategies import Strategy
class autostop_strategy(Strategy):
def __init__(self):
super(autostop_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 10) \
.SetDisplay("Fast EMA", "Fast EMA period", "General")
self._slow_length = self.Param("SlowLength", 20) \
.SetDisplay("Slow EMA", "Slow EMA period", "General")
self._atr_length = self.Param("AtrLength", 14) \
.SetDisplay("ATR Length", "ATR period for TP/SL", "Risk")
self._tp_multiplier = self.Param("TpMultiplier", 2.0) \
.SetDisplay("TP Multiplier", "ATR multiplier for take profit", "Risk")
self._sl_multiplier = self.Param("SlMultiplier", 1.5) \
.SetDisplay("SL Multiplier", "ATR multiplier for stop loss", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._entry_price = 0.0
self._take_price = 0.0
self._stop_price = 0.0
@property
def fast_length(self):
return self._fast_length.Value
@property
def slow_length(self):
return self._slow_length.Value
@property
def atr_length(self):
return self._atr_length.Value
@property
def tp_multiplier(self):
return self._tp_multiplier.Value
@property
def sl_multiplier(self):
return self._sl_multiplier.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(autostop_strategy, self).OnReseted()
self._entry_price = 0.0
self._take_price = 0.0
self._stop_price = 0.0
def OnStarted2(self, time):
super(autostop_strategy, self).OnStarted2(time)
fast_ema = ExponentialMovingAverage()
fast_ema.Length = self.fast_length
slow_ema = ExponentialMovingAverage()
slow_ema.Length = self.slow_length
atr = StandardDeviation()
atr.Length = self.atr_length
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast_ema, slow_ema, atr, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, fast_ema)
self.DrawIndicator(area, slow_ema)
self.DrawOwnTrades(area)
def on_process(self, candle, fast, slow, atr_value):
if candle.State != CandleStates.Finished:
return
# Check TP/SL for existing positions
if self.Position > 0:
if candle.ClosePrice >= self._take_price or candle.ClosePrice <= self._stop_price:
self.SellMarket()
return
elif self.Position < 0:
if candle.ClosePrice <= self._take_price or candle.ClosePrice >= self._stop_price:
self.BuyMarket()
return
# Entry signals
if fast > slow and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._entry_price = candle.ClosePrice
self._take_price = self._entry_price + atr_value * self.tp_multiplier
self._stop_price = self._entry_price - atr_value * self.sl_multiplier
elif fast < slow and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._entry_price = candle.ClosePrice
self._take_price = self._entry_price - atr_value * self.tp_multiplier
self._stop_price = self._entry_price + atr_value * self.sl_multiplier
def CreateClone(self):
return autostop_strategy()