Стратегия Triple EMA + QQE Trend Following
Трендовая стратегия, объединяющая две линии TEMA с фильтром QQE. Длинные позиции открываются, когда цена выше обеих TEMA и QQE подает бычий сигнал. Короткие позиции открываются при противоположных условиях. Открытые сделки защищаются трейлинг-стопом в пунктах.
Детали
- Критерии входа: согласованность TEMA и пересечение QQE.
- Длинные/короткие: оба направления.
- Критерии выхода: противоположный сигнал или трейлинг-стоп.
- Стопы: да.
- Значения по умолчанию:
RsiPeriod= 14RsiSmoothing= 5QqeFactor= 4.238mTema1Length= 20Tema2Length= 40StopLossPips= 120CandleType= TimeSpan.FromMinutes(5)
- Фильтры:
- Категория: Тренд
- Направление: Оба
- Индикаторы: EMA, QQE
- Стопы: Трейлинг
- Сложность: Средняя
- Таймфрейм: Внутридневной (5m)
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Triple EMA with QQE-inspired RSI filter and trailing stop.
/// Uses fast/slow EMA crossover confirmed by RSI momentum direction.
/// </summary>
public class TripleEmaQqeTrendFollowingStrategy : Strategy
{
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<int> _fastEmaLength;
private readonly StrategyParam<int> _slowEmaLength;
private readonly StrategyParam<decimal> _trailPct;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevFast;
private decimal _prevSlow;
private decimal _prevRsi;
private decimal _entryPrice;
private int _cooldown;
private int _candleCount;
public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
public int FastEmaLength { get => _fastEmaLength.Value; set => _fastEmaLength.Value = value; }
public int SlowEmaLength { get => _slowEmaLength.Value; set => _slowEmaLength.Value = value; }
public decimal TrailPct { get => _trailPct.Value; set => _trailPct.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public TripleEmaQqeTrendFollowingStrategy()
{
_rsiPeriod = Param(nameof(RsiPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Length", "RSI period", "Indicators");
_fastEmaLength = Param(nameof(FastEmaLength), 10)
.SetGreaterThanZero()
.SetDisplay("Fast EMA", "Fast EMA period", "Indicators");
_slowEmaLength = Param(nameof(SlowEmaLength), 30)
.SetGreaterThanZero()
.SetDisplay("Slow EMA", "Slow EMA period", "Indicators");
_trailPct = Param(nameof(TrailPct), 4m)
.SetGreaterThanZero()
.SetDisplay("Trail %", "Trailing stop percent", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
protected override void OnReseted()
{
base.OnReseted();
_prevFast = 0;
_prevSlow = 0;
_prevRsi = 0;
_entryPrice = 0;
_cooldown = 0;
_candleCount = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fastEma = new ExponentialMovingAverage { Length = FastEmaLength };
var slowEma = new ExponentialMovingAverage { Length = SlowEmaLength };
var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(fastEma, slowEma, rsi, 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 fastVal, decimal slowVal, decimal rsiVal)
{
if (candle.State != CandleStates.Finished)
return;
_candleCount++;
if (_prevFast == 0 || _prevSlow == 0 || _prevRsi == 0)
{
_prevFast = fastVal;
_prevSlow = slowVal;
_prevRsi = rsiVal;
return;
}
if (_cooldown > 0)
{
_cooldown--;
_prevFast = fastVal;
_prevSlow = slowVal;
_prevRsi = rsiVal;
return;
}
var price = candle.ClosePrice;
var trail = TrailPct / 100m;
// EMA trend direction
var trendUp = fastVal > slowVal;
var trendDown = fastVal < slowVal;
// RSI crosses
var rsiCrossUp = _prevRsi <= 50m && rsiVal > 50m;
var rsiCrossDown = _prevRsi >= 50m && rsiVal < 50m;
// Exit conditions
if (Position > 0)
{
if (price < _entryPrice * (1m - trail) || rsiCrossDown)
{
SellMarket();
_entryPrice = 0;
_cooldown = 80;
}
}
else if (Position < 0)
{
if (price > _entryPrice * (1m + trail) || rsiCrossUp)
{
BuyMarket();
_entryPrice = 0;
_cooldown = 80;
}
}
// Entry: RSI cross + EMA trend confirmation
if (Position == 0)
{
if (rsiCrossUp && trendUp)
{
BuyMarket();
_entryPrice = price;
_cooldown = 80;
}
else if (rsiCrossDown && trendDown)
{
SellMarket();
_entryPrice = price;
_cooldown = 80;
}
}
_prevFast = fastVal;
_prevSlow = slowVal;
_prevRsi = rsiVal;
}
}
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, RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class triple_ema_qqe_trend_following_strategy(Strategy):
def __init__(self):
super(triple_ema_qqe_trend_following_strategy, self).__init__()
self._rsi_period = self.Param("RsiPeriod", 14) \
.SetDisplay("RSI Length", "RSI period", "Indicators")
self._fast_ema_length = self.Param("FastEmaLength", 10) \
.SetDisplay("Fast EMA", "Fast EMA period", "Indicators")
self._slow_ema_length = self.Param("SlowEmaLength", 30) \
.SetDisplay("Slow EMA", "Slow EMA period", "Indicators")
self._trail_pct = self.Param("TrailPct", 4.0) \
.SetDisplay("Trail %", "Trailing stop percent", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._prev_rsi = 0.0
self._entry_price = 0.0
self._cooldown = 0
self._candle_count = 0
@property
def rsi_period(self):
return self._rsi_period.Value
@property
def fast_ema_length(self):
return self._fast_ema_length.Value
@property
def slow_ema_length(self):
return self._slow_ema_length.Value
@property
def trail_pct(self):
return self._trail_pct.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(triple_ema_qqe_trend_following_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._prev_rsi = 0.0
self._entry_price = 0.0
self._cooldown = 0
self._candle_count = 0
def OnStarted2(self, time):
super(triple_ema_qqe_trend_following_strategy, self).OnStarted2(time)
fast_ema = ExponentialMovingAverage()
fast_ema.Length = self.fast_ema_length
slow_ema = ExponentialMovingAverage()
slow_ema.Length = self.slow_ema_length
rsi = RelativeStrengthIndex()
rsi.Length = self.rsi_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast_ema, slow_ema, rsi, 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_val, slow_val, rsi_val):
if candle.State != CandleStates.Finished:
return
self._candle_count += 1
fast_val = float(fast_val)
slow_val = float(slow_val)
rsi_val = float(rsi_val)
if self._prev_fast == 0 or self._prev_slow == 0 or self._prev_rsi == 0:
self._prev_fast = fast_val
self._prev_slow = slow_val
self._prev_rsi = rsi_val
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_fast = fast_val
self._prev_slow = slow_val
self._prev_rsi = rsi_val
return
price = float(candle.ClosePrice)
trail = self.trail_pct / 100.0
trend_up = fast_val > slow_val
trend_down = fast_val < slow_val
rsi_cross_up = self._prev_rsi <= 50 and rsi_val > 50
rsi_cross_down = self._prev_rsi >= 50 and rsi_val < 50
if self.Position > 0:
if price < self._entry_price * (1 - trail) or rsi_cross_down:
self.SellMarket()
self._entry_price = 0
self._cooldown = 80
elif self.Position < 0:
if price > self._entry_price * (1 + trail) or rsi_cross_up:
self.BuyMarket()
self._entry_price = 0
self._cooldown = 80
if self.Position == 0:
if rsi_cross_up and trend_up:
self.BuyMarket()
self._entry_price = price
self._cooldown = 80
elif rsi_cross_down and trend_down:
self.SellMarket()
self._entry_price = price
self._cooldown = 80
self._prev_fast = fast_val
self._prev_slow = slow_val
self._prev_rsi = rsi_val
def CreateClone(self):
return triple_ema_qqe_trend_following_strategy()