Стратегия ZMFX Stolid 5a EA
Мультифреймовая трендовая стратегия, входящая на откатах, подтвержденных RSI и Stochastic. Система определяет основной тренд по 4-часовому Stochastic и 1-часовым сглаженным средним. Позиции открываются при развороте свечи в зонах перепроданности/перекупленности RSI и закрываются по противоположным сигналам.
Детали
- Условия входа:
- Лонг:
UpTrend && PreviousBarDown && PrevRSI < 30 && (RSI15 < 30 => double volume) - Шорт:
DownTrend && PreviousBarUp && PrevRSI > 70 && (RSI15 > 70 => double volume)
- Лонг:
- Лонг/Шорт: Оба
- Стопы: Явных стопов нет; выход по условиям индикаторов
- Значения по умолчанию:
Volume= 1mCandleType= TimeSpan.FromMinutes(5).TimeFrame()
- Фильтры:
- Категория: Тренд
- Направление: Оба
- Индикаторы: RSI, Stochastic, Smoothed Moving Average
- Стопы: Нет
- Сложность: Средняя
- Таймфрейм: Мультифреймовый
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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>
/// ZMFX Stolid strategy - trades pullbacks within the main trend.
/// Uses RSI for oversold/overbought, EMA crossover for trend direction.
/// </summary>
public class ZmfxStolid5aEaStrategy : Strategy
{
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<int> _fastEmaLength;
private readonly StrategyParam<int> _slowEmaLength;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevRsi;
private bool _hasPrevRsi;
public int RsiLength { get => _rsiLength.Value; set => _rsiLength.Value = value; }
public int FastEmaLength { get => _fastEmaLength.Value; set => _fastEmaLength.Value = value; }
public int SlowEmaLength { get => _slowEmaLength.Value; set => _slowEmaLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ZmfxStolid5aEaStrategy()
{
_rsiLength = Param(nameof(RsiLength), 11)
.SetGreaterThanZero()
.SetDisplay("RSI Length", "RSI period", "Indicators");
_fastEmaLength = Param(nameof(FastEmaLength), 20)
.SetGreaterThanZero()
.SetDisplay("Fast EMA", "Fast EMA period", "Indicators");
_slowEmaLength = Param(nameof(SlowEmaLength), 50)
.SetGreaterThanZero()
.SetDisplay("Slow EMA", "Slow EMA period", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_prevRsi = 0;
_hasPrevRsi = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var rsi = new RelativeStrengthIndex { Length = RsiLength };
var fastEma = new ExponentialMovingAverage { Length = FastEmaLength };
var slowEma = new ExponentialMovingAverage { Length = SlowEmaLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(rsi, fastEma, slowEma, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal rsi, decimal fastEma, decimal slowEma)
{
if (candle.State != CandleStates.Finished)
return;
if (!_hasPrevRsi)
{
_prevRsi = rsi;
_hasPrevRsi = true;
return;
}
var upTrend = fastEma > slowEma;
var downTrend = fastEma < slowEma;
// Buy pullback: uptrend, RSI was oversold, now crossing up
if (upTrend && _prevRsi < 35 && rsi >= 35 && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
}
// Sell pullback: downtrend, RSI was overbought, now crossing down
else if (downTrend && _prevRsi > 65 && rsi <= 65 && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
}
// Exit long on RSI overbought or trend reversal
if (Position > 0 && (rsi > 75 || fastEma < slowEma))
{
SellMarket();
}
// Exit short on RSI oversold or trend reversal
else if (Position < 0 && (rsi < 25 || fastEma > slowEma))
{
BuyMarket();
}
_prevRsi = rsi;
}
}
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 zmfx_stolid5a_ea_strategy(Strategy):
def __init__(self):
super(zmfx_stolid5a_ea_strategy, self).__init__()
self._rsi_length = self.Param("RsiLength", 11) \
.SetDisplay("RSI Length", "RSI period", "Indicators")
self._fast_ema_length = self.Param("FastEmaLength", 20) \
.SetDisplay("Fast EMA", "Fast EMA period", "Indicators")
self._slow_ema_length = self.Param("SlowEmaLength", 50) \
.SetDisplay("Slow EMA", "Slow EMA period", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_rsi = 0.0
self._has_prev_rsi = False
@property
def rsi_length(self):
return self._rsi_length.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 candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(zmfx_stolid5a_ea_strategy, self).OnReseted()
self._prev_rsi = 0.0
self._has_prev_rsi = False
def OnStarted2(self, time):
super(zmfx_stolid5a_ea_strategy, self).OnStarted2(time)
rsi = RelativeStrengthIndex()
rsi.Length = self.rsi_length
fast_ema = ExponentialMovingAverage()
fast_ema.Length = self.fast_ema_length
slow_ema = ExponentialMovingAverage()
slow_ema.Length = self.slow_ema_length
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(rsi, fast_ema, slow_ema, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, rsi, fast_ema, slow_ema):
if candle.State != CandleStates.Finished:
return
if not self._has_prev_rsi:
self._prev_rsi = rsi
self._has_prev_rsi = True
return
up_trend = fast_ema > slow_ema
down_trend = fast_ema < slow_ema
# Buy pullback: uptrend, RSI was oversold, now crossing up
if up_trend and self._prev_rsi < 35 and rsi >= 35 and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
# Sell pullback: downtrend, RSI was overbought, now crossing down
elif down_trend and self._prev_rsi > 65 and rsi <= 65 and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
# Exit long on RSI overbought or trend reversal
if self.Position > 0 and (rsi > 75 or fast_ema < slow_ema):
self.SellMarket()
# Exit short on RSI oversold or trend reversal
elif self.Position < 0 and (rsi < 25 or fast_ema > slow_ema):
self.BuyMarket()
self._prev_rsi = rsi
def CreateClone(self):
return zmfx_stolid5a_ea_strategy()