ATR 退出策略
该策略基于 EMA 金叉并使用 ATR 跟踪止损和部分止盈。
using System;
using System.Linq;
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>
/// EMA crossover strategy with ATR based trailing exits.
/// </summary>
public class AtrExitStrategy : Strategy
{
private readonly StrategyParam<int> _fastLen;
private readonly StrategyParam<int> _slowLen;
private readonly StrategyParam<int> _atrLen;
private readonly StrategyParam<DataType> _candleType;
private decimal _entryPrice;
private decimal _stopPrice;
private decimal _prevFast;
private decimal _prevSlow;
public int FastLength { get => _fastLen.Value; set => _fastLen.Value = value; }
public int SlowLength { get => _slowLen.Value; set => _slowLen.Value = value; }
public int AtrLength { get => _atrLen.Value; set => _atrLen.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public AtrExitStrategy()
{
_fastLen = Param(nameof(FastLength), 10).SetGreaterThanZero().SetDisplay("Fast EMA", "Fast EMA length", "General");
_slowLen = Param(nameof(SlowLength), 30).SetGreaterThanZero().SetDisplay("Slow EMA", "Slow EMA length", "General");
_atrLen = Param(nameof(AtrLength), 14).SetGreaterThanZero().SetDisplay("ATR Length", "ATR period", "General");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to process", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_entryPrice = 0m;
_stopPrice = 0m;
_prevFast = 0m;
_prevSlow = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fast = new ExponentialMovingAverage { Length = FastLength };
var slow = new ExponentialMovingAverage { Length = SlowLength };
var atr = new AverageTrueRange { Length = AtrLength };
var sub = SubscribeCandles(CandleType);
sub.Bind(fast, slow, atr, Process).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, sub);
DrawIndicator(area, fast);
DrawIndicator(area, slow);
DrawOwnTrades(area);
}
}
private void Process(ICandleMessage candle, decimal fast, decimal slow, decimal atr)
{
if (candle.State != CandleStates.Finished)
return;
var crossUp = _prevFast <= _prevSlow && fast > slow;
var crossDown = _prevFast >= _prevSlow && fast < slow;
if (Position == 0)
{
if (crossUp)
{
_entryPrice = candle.ClosePrice;
_stopPrice = _entryPrice - 1.5m * atr;
BuyMarket();
}
else if (crossDown)
{
_entryPrice = candle.ClosePrice;
_stopPrice = _entryPrice + 1.5m * atr;
SellMarket();
}
}
else if (Position > 0)
{
// Trailing stop using ATR
var newStop = candle.ClosePrice - 1.5m * atr;
if (newStop > _stopPrice)
_stopPrice = newStop;
if (candle.ClosePrice < _stopPrice || crossDown)
SellMarket();
}
else if (Position < 0)
{
var newStop = candle.ClosePrice + 1.5m * atr;
if (newStop < _stopPrice)
_stopPrice = newStop;
if (candle.ClosePrice > _stopPrice || crossUp)
BuyMarket();
}
_prevFast = fast;
_prevSlow = slow;
}
}
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 AverageTrueRange, ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class atr_exit_strategy(Strategy):
def __init__(self):
super(atr_exit_strategy, self).__init__()
self._fast_len = self.Param("FastLength", 10) \
.SetDisplay("Fast EMA", "Fast EMA length", "General")
self._slow_len = self.Param("SlowLength", 30) \
.SetDisplay("Slow EMA", "Slow EMA length", "General")
self._atr_len = self.Param("AtrLength", 14) \
.SetDisplay("ATR Length", "ATR period", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles to process", "General")
self._entry_price = 0.0
self._stop_price = 0.0
self._prev_fast = 0.0
self._prev_slow = 0.0
@property
def fast_length(self):
return self._fast_len.Value
@property
def slow_length(self):
return self._slow_len.Value
@property
def atr_length(self):
return self._atr_len.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(atr_exit_strategy, self).OnReseted()
self._entry_price = 0.0
self._stop_price = 0.0
self._prev_fast = 0.0
self._prev_slow = 0.0
def OnStarted2(self, time):
super(atr_exit_strategy, self).OnStarted2(time)
fast = ExponentialMovingAverage()
fast.Length = self.fast_length
slow = ExponentialMovingAverage()
slow.Length = self.slow_length
atr = AverageTrueRange()
atr.Length = self.atr_length
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast, slow, atr, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, fast)
self.DrawIndicator(area, slow)
self.DrawOwnTrades(area)
def on_process(self, candle, fast, slow, atr):
if candle.State != CandleStates.Finished:
return
cross_up = self._prev_fast <= self._prev_slow and fast > slow
cross_down = self._prev_fast >= self._prev_slow and fast < slow
if self.Position == 0:
if cross_up:
self._entry_price = candle.ClosePrice
self._stop_price = self._entry_price - 1.5 * atr
self.BuyMarket()
elif cross_down:
self._entry_price = candle.ClosePrice
self._stop_price = self._entry_price + 1.5 * atr
self.SellMarket()
elif self.Position > 0:
new_stop = candle.ClosePrice - 1.5 * atr
if new_stop > self._stop_price:
self._stop_price = new_stop
if candle.ClosePrice < self._stop_price or cross_down:
self.SellMarket()
elif self.Position < 0:
new_stop = candle.ClosePrice + 1.5 * atr
if new_stop < self._stop_price:
self._stop_price = new_stop
if candle.ClosePrice > self._stop_price or cross_up:
self.BuyMarket()
self._prev_fast = fast
self._prev_slow = slow
def CreateClone(self):
return atr_exit_strategy()