MACD RSI EMA BB ATR Day Trading Strategy
Интрадейная стратегия, сочетающая пересечение MACD, границы RSI и направление тренда по EMA с фильтром сжатия полос Боллинджера. Управление рисками основано на стоп-лоссе по ATR, трейлинг-стопе и тейк-профите по коэффициенту риск/прибыль.
Детали
- Условия входа: MACD пересекает сигнал по тренду, RSI в пределах порогов и нет сжатия BB.
- Длинные/короткие: Оба направления.
- Условия выхода: Противоположный стоп или цель.
- Стопы: Стоп-лосс по ATR, трейлинг-стоп и тейк-профит по RiskReward.
- Значения по умолчанию:
MacdFast= 12MacdSlow= 26MacdSignal= 9RsiLength= 14RsiOverbought= 70RsiOversold= 30EmaFast= 9EmaSlow= 21AtrLength= 14AtrMultiplier= 2.0TrailAtrMultiplier= 1.5BbLength= 20BbMultiplier= 2.0RiskReward= 2.0CandleType= TimeSpan.FromMinutes(5)
- Фильтры:
- Категория: Trend Following
- Направление: Оба
- Индикаторы: MACD, RSI, EMA, Bollinger Bands, ATR
- Стопы: Да
- Сложность: Средняя
- Таймфрейм: Внутридневной (5m)
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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>
/// Day trading strategy using EMA crossover with RSI and ATR stops.
/// </summary>
public class MacdRsiEmaBbAtrDayTradingStrategy : Strategy
{
private readonly StrategyParam<int> _emaFastLen;
private readonly StrategyParam<int> _emaSlowLen;
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<int> _atrLength;
private readonly StrategyParam<decimal> _atrMultiplier;
private readonly StrategyParam<DataType> _candleType;
private ExponentialMovingAverage _emaFast;
private ExponentialMovingAverage _emaSlow;
private RelativeStrengthIndex _rsi;
private AverageTrueRange _atr;
private decimal _prevFast;
private decimal _prevSlow;
private bool _initialized;
private decimal _stopPrice;
private int _cooldown;
public int EmaFastLen { get => _emaFastLen.Value; set => _emaFastLen.Value = value; }
public int EmaSlowLen { get => _emaSlowLen.Value; set => _emaSlowLen.Value = value; }
public int RsiLength { get => _rsiLength.Value; set => _rsiLength.Value = value; }
public int AtrLength { get => _atrLength.Value; set => _atrLength.Value = value; }
public decimal AtrMultiplier { get => _atrMultiplier.Value; set => _atrMultiplier.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public MacdRsiEmaBbAtrDayTradingStrategy()
{
_emaFastLen = Param(nameof(EmaFastLen), 9).SetDisplay("Fast EMA", "Fast EMA", "Indicators");
_emaSlowLen = Param(nameof(EmaSlowLen), 21).SetDisplay("Slow EMA", "Slow EMA", "Indicators");
_rsiLength = Param(nameof(RsiLength), 14).SetDisplay("RSI", "RSI period", "Indicators");
_atrLength = Param(nameof(AtrLength), 14).SetDisplay("ATR", "ATR period", "Indicators");
_atrMultiplier = Param(nameof(AtrMultiplier), 3.0m).SetDisplay("ATR Mult", "ATR stop mult", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(25).TimeFrame())
.SetDisplay("Candle Type", "Candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevFast = default;
_prevSlow = default;
_initialized = false;
_stopPrice = default;
_cooldown = default;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_emaFast = new ExponentialMovingAverage { Length = EmaFastLen };
_emaSlow = new ExponentialMovingAverage { Length = EmaSlowLen };
_rsi = new RelativeStrengthIndex { Length = RsiLength };
_atr = new AverageTrueRange { Length = AtrLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_emaFast, _emaSlow, _rsi, _atr, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _emaFast);
DrawIndicator(area, _emaSlow);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow, decimal rsi, decimal atr)
{
if (candle.State != CandleStates.Finished)
return;
if (!_emaFast.IsFormed || !_emaSlow.IsFormed || !_rsi.IsFormed || !_atr.IsFormed)
return;
if (!_initialized)
{
_prevFast = fast;
_prevSlow = slow;
_initialized = true;
return;
}
if (_cooldown > 0)
{
_cooldown--;
_prevFast = fast;
_prevSlow = slow;
return;
}
var crossUp = _prevFast <= _prevSlow && fast > slow;
var crossDown = _prevFast >= _prevSlow && fast < slow;
// Entry with RSI confirmation
if (crossUp && rsi > 25 && rsi < 80 && Position <= 0)
{
if (Position < 0)
BuyMarket();
BuyMarket();
_stopPrice = candle.ClosePrice - atr * AtrMultiplier;
_cooldown = 8;
}
else if (crossDown && rsi > 20 && rsi < 75 && Position >= 0)
{
if (Position > 0)
SellMarket();
SellMarket();
_stopPrice = candle.ClosePrice + atr * AtrMultiplier;
_cooldown = 8;
}
// ATR stop exit
if (Position > 0 && _stopPrice > 0 && candle.ClosePrice <= _stopPrice)
{
SellMarket();
_stopPrice = 0;
_cooldown = 10;
}
else if (Position < 0 && _stopPrice > 0 && candle.ClosePrice >= _stopPrice)
{
BuyMarket();
_stopPrice = 0;
_cooldown = 10;
}
_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 ExponentialMovingAverage, RelativeStrengthIndex, AverageTrueRange
from StockSharp.Algo.Strategies import Strategy
class macd_rsi_ema_bb_atr_day_trading_strategy(Strategy):
"""
Day trading: EMA crossover with RSI confirmation and ATR-based stop loss.
"""
def __init__(self):
super(macd_rsi_ema_bb_atr_day_trading_strategy, self).__init__()
self._ema_fast_len = self.Param("EmaFastLen", 9).SetDisplay("Fast EMA", "Fast EMA", "Indicators")
self._ema_slow_len = self.Param("EmaSlowLen", 21).SetDisplay("Slow EMA", "Slow EMA", "Indicators")
self._rsi_length = self.Param("RsiLength", 14).SetDisplay("RSI", "RSI period", "Indicators")
self._atr_length = self.Param("AtrLength", 14).SetDisplay("ATR", "ATR period", "Indicators")
self._atr_multiplier = self.Param("AtrMultiplier", 3.0).SetDisplay("ATR Mult", "ATR stop mult", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(25))).SetDisplay("Candle Type", "Candles", "General")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._initialized = False
self._stop_price = 0.0
self._cooldown = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(macd_rsi_ema_bb_atr_day_trading_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._initialized = False
self._stop_price = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(macd_rsi_ema_bb_atr_day_trading_strategy, self).OnStarted2(time)
self._ema_fast = ExponentialMovingAverage()
self._ema_fast.Length = self._ema_fast_len.Value
self._ema_slow = ExponentialMovingAverage()
self._ema_slow.Length = self._ema_slow_len.Value
self._rsi = RelativeStrengthIndex()
self._rsi.Length = self._rsi_length.Value
self._atr = AverageTrueRange()
self._atr.Length = self._atr_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._ema_fast, self._ema_slow, self._rsi, self._atr, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._ema_fast)
self.DrawIndicator(area, self._ema_slow)
self.DrawOwnTrades(area)
def _process_candle(self, candle, fast_val, slow_val, rsi_val, atr_val):
if candle.State != CandleStates.Finished:
return
if not self._ema_fast.IsFormed or not self._ema_slow.IsFormed or not self._rsi.IsFormed or not self._atr.IsFormed:
return
fast = float(fast_val)
slow = float(slow_val)
rsi = float(rsi_val)
atr = float(atr_val)
if not self._initialized:
self._prev_fast = fast
self._prev_slow = slow
self._initialized = True
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_fast = fast
self._prev_slow = slow
return
close = float(candle.ClosePrice)
cross_up = self._prev_fast <= self._prev_slow and fast > slow
cross_down = self._prev_fast >= self._prev_slow and fast < slow
if cross_up and rsi > 25 and rsi < 80 and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._stop_price = close - atr * float(self._atr_multiplier.Value)
self._cooldown = 8
elif cross_down and rsi > 20 and rsi < 75 and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._stop_price = close + atr * float(self._atr_multiplier.Value)
self._cooldown = 8
if self.Position > 0 and self._stop_price > 0 and close <= self._stop_price:
self.SellMarket()
self._stop_price = 0.0
self._cooldown = 10
elif self.Position < 0 and self._stop_price > 0 and close >= self._stop_price:
self.BuyMarket()
self._stop_price = 0.0
self._cooldown = 10
self._prev_fast = fast
self._prev_slow = slow
def CreateClone(self):
return macd_rsi_ema_bb_atr_day_trading_strategy()