Стратегия ASCTrendND
Эта стратегия основана на эксперте ASCTrendND из MQL5. Она использует простое скользящее среднее для основного сигнала, фильтр RSI для подтверждения силы и трейлинг-стоп на основе ATR для выхода из позиций. Подход упрощенно повторяет логику ASCTrend + NRTR + TrendStrength на высокоуровневом API StockSharp.
Подробности
- Условия входа:
- Покупка: Цена закрытия выше SMA и RSI > 50.
- Продажа: Цена закрытия ниже SMA и RSI < 50.
- Условия выхода:
- Трейлинг-стоп по ATR * множитель или противоположный сигнал.
- Стопы: Только трейлинг-стоп на основе ATR.
- Значения по умолчанию:
SmaPeriod= 50RsiPeriod= 14AtrPeriod= 14AtrMultiplier= 2.0CandleType= свечи 5 минут
- Фильтры:
- Категория: Следование за трендом
- Направление: Покупка и продажа
- Индикаторы: SMA, RSI, ATR
- Стопы: Трейлинг-стоп
- Сложность: Низкая
- Таймфрейм: 5м
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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>
/// ASCTrendND-inspired strategy using SMA, RSI and ATR-based trailing stop.
/// </summary>
public class AscTrendNdStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _smaPeriod;
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<int> _atrPeriod;
private readonly StrategyParam<decimal> _atrMultiplier;
private SimpleMovingAverage _sma;
private RelativeStrengthIndex _rsi;
private AverageTrueRange _atr;
private decimal? _stopPrice;
/// <summary>
/// Candle type for strategy calculation.
/// </summary>
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
/// <summary>
/// SMA period.
/// </summary>
public int SmaPeriod { get => _smaPeriod.Value; set => _smaPeriod.Value = value; }
/// <summary>
/// RSI period.
/// </summary>
public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
/// <summary>
/// ATR period for volatility estimate.
/// </summary>
public int AtrPeriod { get => _atrPeriod.Value; set => _atrPeriod.Value = value; }
/// <summary>
/// ATR multiplier for trailing stop distance.
/// </summary>
public decimal AtrMultiplier { get => _atrMultiplier.Value; set => _atrMultiplier.Value = value; }
/// <summary>
/// Initializes strategy parameters.
/// </summary>
public AscTrendNdStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of source candles", "General");
_smaPeriod = Param(nameof(SmaPeriod), 50)
.SetGreaterThanZero()
.SetDisplay("SMA Period", "Length of simple moving average", "Indicators");
_rsiPeriod = Param(nameof(RsiPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Period", "Length of relative strength index", "Indicators");
_atrPeriod = Param(nameof(AtrPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("ATR Period", "Length of average true range", "Risk");
_atrMultiplier = Param(nameof(AtrMultiplier), 2m)
.SetGreaterThanZero()
.SetDisplay("ATR Multiplier", "ATR multiplier for stop trailing", "Risk");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_sma = null;
_rsi = null;
_atr = null;
_stopPrice = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_stopPrice = null;
_sma = new SimpleMovingAverage { Length = SmaPeriod };
_rsi = new RelativeStrengthIndex { Length = RsiPeriod };
_atr = new AverageTrueRange { Length = AtrPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_sma, _rsi, _atr, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _sma);
DrawIndicator(area, _rsi);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal smaValue, decimal rsiValue, decimal atrValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var price = candle.ClosePrice;
if (Position == 0)
{
if (price > smaValue && rsiValue > 50m)
{
_stopPrice = price - atrValue * AtrMultiplier;
BuyMarket();
}
else if (price < smaValue && rsiValue < 50m)
{
_stopPrice = price + atrValue * AtrMultiplier;
SellMarket();
}
return;
}
if (_stopPrice is null)
return;
if (Position > 0)
{
var newStop = price - atrValue * AtrMultiplier;
if (newStop > _stopPrice)
_stopPrice = newStop;
if (price <= _stopPrice)
SellMarket();
}
else
{
var newStop = price + atrValue * AtrMultiplier;
if (newStop < _stopPrice)
_stopPrice = newStop;
if (price >= _stopPrice)
BuyMarket();
}
}
}
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 SimpleMovingAverage, RelativeStrengthIndex, AverageTrueRange
from StockSharp.Algo.Strategies import Strategy
class asc_trend_nd_strategy(Strategy):
def __init__(self):
super(asc_trend_nd_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of source candles", "General")
self._sma_period = self.Param("SmaPeriod", 50) \
.SetDisplay("SMA Period", "Length of simple moving average", "Indicators")
self._rsi_period = self.Param("RsiPeriod", 14) \
.SetDisplay("RSI Period", "Length of relative strength index", "Indicators")
self._atr_period = self.Param("AtrPeriod", 14) \
.SetDisplay("ATR Period", "Length of average true range", "Risk")
self._atr_multiplier = self.Param("AtrMultiplier", 2.0) \
.SetDisplay("ATR Multiplier", "ATR multiplier for stop trailing", "Risk")
self._stop_price = None
@property
def candle_type(self):
return self._candle_type.Value
@property
def sma_period(self):
return self._sma_period.Value
@property
def rsi_period(self):
return self._rsi_period.Value
@property
def atr_period(self):
return self._atr_period.Value
@property
def atr_multiplier(self):
return self._atr_multiplier.Value
def OnReseted(self):
super(asc_trend_nd_strategy, self).OnReseted()
self._stop_price = None
def OnStarted2(self, time):
super(asc_trend_nd_strategy, self).OnStarted2(time)
self._stop_price = None
sma = SimpleMovingAverage()
sma.Length = self.sma_period
rsi = RelativeStrengthIndex()
rsi.Length = self.rsi_period
atr = AverageTrueRange()
atr.Length = self.atr_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(sma, rsi, atr, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, sma)
self.DrawIndicator(area, rsi)
self.DrawOwnTrades(area)
def process_candle(self, candle, sma_value, rsi_value, atr_value):
if candle.State != CandleStates.Finished:
return
price = float(candle.ClosePrice)
sma_value = float(sma_value)
rsi_value = float(rsi_value)
atr_value = float(atr_value)
atr_mult = float(self.atr_multiplier)
if self.Position == 0:
if price > sma_value and rsi_value > 50.0:
self._stop_price = price - atr_value * atr_mult
self.BuyMarket()
elif price < sma_value and rsi_value < 50.0:
self._stop_price = price + atr_value * atr_mult
self.SellMarket()
return
if self._stop_price is None:
return
if self.Position > 0:
new_stop = price - atr_value * atr_mult
if new_stop > self._stop_price:
self._stop_price = new_stop
if price <= self._stop_price:
self.SellMarket()
else:
new_stop = price + atr_value * atr_mult
if new_stop < self._stop_price:
self._stop_price = new_stop
if price >= self._stop_price:
self.BuyMarket()
def CreateClone(self):
return asc_trend_nd_strategy()