Стратегия Escort Trend
Стратегия Escort Trend сочетает быстрые и медленные взвешенные скользящие средние (WMA) с подтверждением индикаторами MACD и CCI. Длинная позиция открывается, когда быстрая WMA выше медленной, линия MACD пересекает сверху линию сигнала, а CCI превышает положительный порог. Короткая позиция открывается при обратных условиях. Опционально используются фиксированный стоп-лосс, тейк-профит и трейлинг-стоп.
Подробности
- Условия входа:
- Покупка:
FastWMA > SlowWMAИMACD > SignalИCCI > +Threshold. - Продажа:
FastWMA < SlowWMAИMACD < SignalИCCI < -Threshold.
- Покупка:
- Направление: обе стороны.
- Условия выхода:
- Противоположный сигнал.
- Опциональные стоп-лосс, тейк-профит или трейлинг-стоп.
- Стопы: есть, задаются пользователем.
- Значения по умолчанию:
Fast WMA= 8Slow WMA= 18CCI Period= 14CCI Threshold= 100MACD Fast EMA= 8MACD Slow EMA= 18Take Profit= 200Stop Loss= 55Trailing Stop= 35Trailing Step= 3
- Фильтры:
- Категория: следование тренду
- Направление: обе стороны
- Индикаторы: несколько
- Стопы: есть
- Сложность: средняя
- Таймфрейм: краткосрочный
- Сезонность: нет
- Нейросети: нет
- Дивергенция: нет
- Уровень риска: средний
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>
/// Escort Trend strategy combining WMA crossover with CCI confirmation.
/// Buys when fast WMA above slow WMA and CCI above threshold.
/// Sells when opposite conditions met.
/// </summary>
public class EscortTrendStrategy : Strategy
{
private readonly StrategyParam<int> _fastWmaPeriod;
private readonly StrategyParam<int> _slowWmaPeriod;
private readonly StrategyParam<int> _cciPeriod;
private readonly StrategyParam<decimal> _cciThreshold;
private readonly StrategyParam<decimal> _stopLossPct;
private readonly StrategyParam<decimal> _takeProfitPct;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevFast;
private decimal _prevSlow;
private bool _hasPrev;
public int FastWmaPeriod { get => _fastWmaPeriod.Value; set => _fastWmaPeriod.Value = value; }
public int SlowWmaPeriod { get => _slowWmaPeriod.Value; set => _slowWmaPeriod.Value = value; }
public int CciPeriod { get => _cciPeriod.Value; set => _cciPeriod.Value = value; }
public decimal CciThreshold { get => _cciThreshold.Value; set => _cciThreshold.Value = value; }
public decimal StopLossPct { get => _stopLossPct.Value; set => _stopLossPct.Value = value; }
public decimal TakeProfitPct { get => _takeProfitPct.Value; set => _takeProfitPct.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public EscortTrendStrategy()
{
_fastWmaPeriod = Param(nameof(FastWmaPeriod), 8)
.SetGreaterThanZero()
.SetDisplay("Fast WMA", "Length of fast weighted MA", "General");
_slowWmaPeriod = Param(nameof(SlowWmaPeriod), 18)
.SetGreaterThanZero()
.SetDisplay("Slow WMA", "Length of slow weighted MA", "General");
_cciPeriod = Param(nameof(CciPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("CCI Period", "CCI calculation period", "General");
_cciThreshold = Param(nameof(CciThreshold), 100m)
.SetDisplay("CCI Threshold", "Threshold for CCI signal", "General");
_stopLossPct = Param(nameof(StopLossPct), 2m)
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk");
_takeProfitPct = Param(nameof(TakeProfitPct), 3m)
.SetDisplay("Take Profit %", "Take profit percentage", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).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();
_prevFast = 0;
_prevSlow = 0;
_hasPrev = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fastWma = new WeightedMovingAverage { Length = FastWmaPeriod };
var slowWma = new WeightedMovingAverage { Length = SlowWmaPeriod };
var cci = new CommodityChannelIndex { Length = CciPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fastWma, slowWma, cci, ProcessCandle)
.Start();
StartProtection(
takeProfit: new Unit(TakeProfitPct, UnitTypes.Percent),
stopLoss: new Unit(StopLossPct, UnitTypes.Percent)
);
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow, decimal cciValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_hasPrev)
{
_prevFast = fast;
_prevSlow = slow;
_hasPrev = true;
return;
}
// Buy crossover: fast WMA crosses above slow WMA with CCI confirmation
var crossUp = _prevFast <= _prevSlow && fast > slow && cciValue > CciThreshold;
// Sell crossover: fast WMA crosses below slow WMA with CCI confirmation
var crossDown = _prevFast >= _prevSlow && fast < slow && cciValue < -CciThreshold;
if (crossUp && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
else if (crossDown && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
_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, Unit, UnitTypes
from StockSharp.Algo.Indicators import WeightedMovingAverage, CommodityChannelIndex
from StockSharp.Algo.Strategies import Strategy
class escort_trend_strategy(Strategy):
def __init__(self):
super(escort_trend_strategy, self).__init__()
self._fast_wma_period = self.Param("FastWmaPeriod", 8) \
.SetDisplay("Fast WMA", "Length of fast weighted MA", "General")
self._slow_wma_period = self.Param("SlowWmaPeriod", 18) \
.SetDisplay("Slow WMA", "Length of slow weighted MA", "General")
self._cci_period = self.Param("CciPeriod", 14) \
.SetDisplay("CCI Period", "CCI calculation period", "General")
self._cci_threshold = self.Param("CciThreshold", 100.0) \
.SetDisplay("CCI Threshold", "Threshold for CCI signal", "General")
self._stop_loss_pct = self.Param("StopLossPct", 2.0) \
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk")
self._take_profit_pct = self.Param("TakeProfitPct", 3.0) \
.SetDisplay("Take Profit %", "Take profit percentage", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._has_prev = False
@property
def FastWmaPeriod(self):
return self._fast_wma_period.Value
@FastWmaPeriod.setter
def FastWmaPeriod(self, value):
self._fast_wma_period.Value = value
@property
def SlowWmaPeriod(self):
return self._slow_wma_period.Value
@SlowWmaPeriod.setter
def SlowWmaPeriod(self, value):
self._slow_wma_period.Value = value
@property
def CciPeriod(self):
return self._cci_period.Value
@CciPeriod.setter
def CciPeriod(self, value):
self._cci_period.Value = value
@property
def CciThreshold(self):
return self._cci_threshold.Value
@CciThreshold.setter
def CciThreshold(self, value):
self._cci_threshold.Value = value
@property
def StopLossPct(self):
return self._stop_loss_pct.Value
@StopLossPct.setter
def StopLossPct(self, value):
self._stop_loss_pct.Value = value
@property
def TakeProfitPct(self):
return self._take_profit_pct.Value
@TakeProfitPct.setter
def TakeProfitPct(self, value):
self._take_profit_pct.Value = value
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
def OnStarted2(self, time):
super(escort_trend_strategy, self).OnStarted2(time)
fast_wma = WeightedMovingAverage()
fast_wma.Length = self.FastWmaPeriod
slow_wma = WeightedMovingAverage()
slow_wma.Length = self.SlowWmaPeriod
cci = CommodityChannelIndex()
cci.Length = self.CciPeriod
self.SubscribeCandles(self.CandleType) \
.Bind(fast_wma, slow_wma, cci, self.ProcessCandle) \
.Start()
self.StartProtection(
takeProfit=Unit(self.TakeProfitPct, UnitTypes.Percent),
stopLoss=Unit(self.StopLossPct, UnitTypes.Percent)
)
def ProcessCandle(self, candle, fast, slow, cci_value):
if candle.State != CandleStates.Finished:
return
fast_val = float(fast)
slow_val = float(slow)
cci_val = float(cci_value)
threshold = float(self.CciThreshold)
if not self._has_prev:
self._prev_fast = fast_val
self._prev_slow = slow_val
self._has_prev = True
return
cross_up = self._prev_fast <= self._prev_slow and fast_val > slow_val and cci_val > threshold
cross_down = self._prev_fast >= self._prev_slow and fast_val < slow_val and cci_val < -threshold
if cross_up and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif cross_down and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_fast = fast_val
self._prev_slow = slow_val
def OnReseted(self):
super(escort_trend_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._has_prev = False
def CreateClone(self):
return escort_trend_strategy()