Стратегия Scalping EMA RSI MACD
Скальпинговая стратегия на 30‑минутных свечах использует пересечение быстрых и медленных EMA, трендовую EMA, фильтры RSI и MACD, а также условие по объёму. Стоп-лосс рассчитывается по ATR, тейк-профит определяется фиксированным соотношением риск/прибыль.
Подробности
- Критерии входа: Пересечение EMA в направлении тренда, RSI в допустимых пределах, подтверждение MACD и высокий объём.
- Длинные/Короткие: Оба направления.
- Критерии выхода: Срабатывание стопа или цели.
- Стопы: Стоп-лосс по ATR и тейк-профит по RiskReward.
- Значения по умолчанию:
FastEmaLength= 12SlowEmaLength= 26TrendEmaLength= 55RsiLength= 14RsiOverbought= 65RsiOversold= 35MacdFast= 12MacdSlow= 26MacdSignal= 9AtrLength= 14AtrMultiplier= 2.0RiskReward= 2.0VolumeMaLength= 20VolumeThreshold= 1.3CandleType= TimeSpan.FromMinutes(30)
- Фильтры:
- Категория: Scalping
- Направление: Оба
- Индикаторы: EMA, RSI, MACD, ATR, Объём
- Стопы: Да
- Сложность: Средняя
- Таймфрейм: Внутридневной (30м)
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
namespace StockSharp.Samples.Strategies;
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
/// <summary>
/// 30-minute scalping strategy based on EMA crossover with RSI, MACD and ATR filter.
/// Buys on bullish EMA cross in uptrend with RSI/MACD confirmation.
/// Sells on bearish EMA cross in downtrend with RSI/MACD confirmation.
/// Uses ATR-based stop-loss and take-profit exits.
/// </summary>
public class ScalpingEmaRsiMacdStrategy : Strategy
{
private readonly StrategyParam<int> _fastEmaLength;
private readonly StrategyParam<int> _slowEmaLength;
private readonly StrategyParam<int> _trendEmaLength;
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<int> _rsiOverbought;
private readonly StrategyParam<int> _rsiOversold;
private readonly StrategyParam<int> _atrLength;
private readonly StrategyParam<decimal> _atrMultiplier;
private readonly StrategyParam<decimal> _riskReward;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _cooldownBars;
private decimal _prevFastEma;
private decimal _prevSlowEma;
private decimal _prevMacd;
private decimal _stopPrice;
private decimal _takeProfitPrice;
private decimal _entryPrice;
private int _cooldownRemaining;
public int FastEmaLength { get => _fastEmaLength.Value; set => _fastEmaLength.Value = value; }
public int SlowEmaLength { get => _slowEmaLength.Value; set => _slowEmaLength.Value = value; }
public int TrendEmaLength { get => _trendEmaLength.Value; set => _trendEmaLength.Value = value; }
public int RsiLength { get => _rsiLength.Value; set => _rsiLength.Value = value; }
public int RsiOverbought { get => _rsiOverbought.Value; set => _rsiOverbought.Value = value; }
public int RsiOversold { get => _rsiOversold.Value; set => _rsiOversold.Value = value; }
public int AtrLength { get => _atrLength.Value; set => _atrLength.Value = value; }
public decimal AtrMultiplier { get => _atrMultiplier.Value; set => _atrMultiplier.Value = value; }
public decimal RiskReward { get => _riskReward.Value; set => _riskReward.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int CooldownBars { get => _cooldownBars.Value; set => _cooldownBars.Value = value; }
public ScalpingEmaRsiMacdStrategy()
{
_fastEmaLength = Param(nameof(FastEmaLength), 12)
.SetDisplay("Fast EMA Length", "Length for fast EMA", "Indicators");
_slowEmaLength = Param(nameof(SlowEmaLength), 26)
.SetDisplay("Slow EMA Length", "Length for slow EMA", "Indicators");
_trendEmaLength = Param(nameof(TrendEmaLength), 55)
.SetDisplay("Trend EMA Length", "Length for trend EMA", "Indicators");
_rsiLength = Param(nameof(RsiLength), 14)
.SetDisplay("RSI Length", "Length for RSI", "Indicators");
_rsiOverbought = Param(nameof(RsiOverbought), 65)
.SetDisplay("RSI Overbought", "Upper RSI bound", "Indicators");
_rsiOversold = Param(nameof(RsiOversold), 35)
.SetDisplay("RSI Oversold", "Lower RSI bound", "Indicators");
_atrLength = Param(nameof(AtrLength), 14)
.SetDisplay("ATR Length", "Length for ATR", "Indicators");
_atrMultiplier = Param(nameof(AtrMultiplier), 2m)
.SetDisplay("ATR Multiplier", "Multiplier for stop-loss", "Risk");
_riskReward = Param(nameof(RiskReward), 2m)
.SetDisplay("Risk Reward", "Take profit multiplier", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
_cooldownBars = Param(nameof(CooldownBars), 10)
.SetDisplay("Cooldown Bars", "Bars between trades", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevFastEma = 0;
_prevSlowEma = 0;
_prevMacd = 0;
_stopPrice = 0;
_takeProfitPrice = 0;
_entryPrice = 0;
_cooldownRemaining = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fastEma = new ExponentialMovingAverage { Length = FastEmaLength };
var slowEma = new ExponentialMovingAverage { Length = SlowEmaLength };
var trendEma = new ExponentialMovingAverage { Length = TrendEmaLength };
var rsi = new RelativeStrengthIndex { Length = RsiLength };
var macd = new MovingAverageConvergenceDivergence();
macd.ShortMa.Length = FastEmaLength;
macd.LongMa.Length = SlowEmaLength;
var atr = new AverageTrueRange { Length = AtrLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fastEma, slowEma, trendEma, rsi, macd, atr, 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 fastEma, decimal slowEma, decimal trendEma, decimal rsi, decimal macd, decimal atr)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
{
_prevFastEma = fastEma;
_prevSlowEma = slowEma;
_prevMacd = macd;
return;
}
var close = candle.ClosePrice;
// Check stop-loss and take-profit exits first
if (Position > 0 && _stopPrice > 0)
{
if (candle.LowPrice <= _stopPrice || candle.HighPrice >= _takeProfitPrice)
{
SellMarket(Math.Abs(Position));
_stopPrice = 0;
_takeProfitPrice = 0;
_cooldownRemaining = CooldownBars;
_prevFastEma = fastEma;
_prevSlowEma = slowEma;
_prevMacd = macd;
return;
}
}
else if (Position < 0 && _stopPrice > 0)
{
if (candle.HighPrice >= _stopPrice || candle.LowPrice <= _takeProfitPrice)
{
BuyMarket(Math.Abs(Position));
_stopPrice = 0;
_takeProfitPrice = 0;
_cooldownRemaining = CooldownBars;
_prevFastEma = fastEma;
_prevSlowEma = slowEma;
_prevMacd = macd;
return;
}
}
if (_cooldownRemaining > 0)
{
_cooldownRemaining--;
_prevFastEma = fastEma;
_prevSlowEma = slowEma;
_prevMacd = macd;
return;
}
// Trend detection
var upTrend = close > trendEma && fastEma > slowEma;
var downTrend = close < trendEma && fastEma < slowEma;
// EMA crossover detection
var bullCross = _prevFastEma > 0 && _prevFastEma <= _prevSlowEma && fastEma > slowEma;
var bearCross = _prevFastEma > 0 && _prevFastEma >= _prevSlowEma && fastEma < slowEma;
// MACD momentum
var macdRising = macd > _prevMacd;
var macdFalling = macd < _prevMacd;
// Entry conditions
var longCondition = bullCross && upTrend && rsi > 40m && rsi < RsiOverbought && macdRising;
var shortCondition = bearCross && downTrend && rsi < 60m && rsi > RsiOversold && macdFalling;
if (longCondition && Position <= 0)
{
if (Position < 0)
BuyMarket(Math.Abs(Position));
BuyMarket(Volume);
_entryPrice = close;
_stopPrice = close - atr * AtrMultiplier;
_takeProfitPrice = close + (close - _stopPrice) * RiskReward;
_cooldownRemaining = CooldownBars;
}
else if (shortCondition && Position >= 0)
{
if (Position > 0)
SellMarket(Math.Abs(Position));
SellMarket(Volume);
_entryPrice = close;
_stopPrice = close + atr * AtrMultiplier;
_takeProfitPrice = close - (_stopPrice - close) * RiskReward;
_cooldownRemaining = CooldownBars;
}
_prevFastEma = fastEma;
_prevSlowEma = slowEma;
_prevMacd = macd;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import (ExponentialMovingAverage, RelativeStrengthIndex,
MovingAverageConvergenceDivergence, AverageTrueRange)
from StockSharp.Algo.Strategies import Strategy
class scalping_ema_rsi_macd_strategy(Strategy):
"""Scalping EMA RSI MACD Strategy."""
def __init__(self):
super(scalping_ema_rsi_macd_strategy, self).__init__()
self._fast_ema_length = self.Param("FastEmaLength", 12) \
.SetDisplay("Fast EMA Length", "Length for fast EMA", "Indicators")
self._slow_ema_length = self.Param("SlowEmaLength", 26) \
.SetDisplay("Slow EMA Length", "Length for slow EMA", "Indicators")
self._trend_ema_length = self.Param("TrendEmaLength", 55) \
.SetDisplay("Trend EMA Length", "Length for trend EMA", "Indicators")
self._rsi_length = self.Param("RsiLength", 14) \
.SetDisplay("RSI Length", "Length for RSI", "Indicators")
self._rsi_overbought = self.Param("RsiOverbought", 65) \
.SetDisplay("RSI Overbought", "Upper RSI bound", "Indicators")
self._rsi_oversold = self.Param("RsiOversold", 35) \
.SetDisplay("RSI Oversold", "Lower RSI bound", "Indicators")
self._atr_length = self.Param("AtrLength", 14) \
.SetDisplay("ATR Length", "Length for ATR", "Indicators")
self._atr_multiplier = self.Param("AtrMultiplier", 2.0) \
.SetDisplay("ATR Multiplier", "Multiplier for stop-loss", "Risk")
self._risk_reward = self.Param("RiskReward", 2.0) \
.SetDisplay("Risk Reward", "Take profit multiplier", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(30))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._cooldown_bars = self.Param("CooldownBars", 10) \
.SetDisplay("Cooldown Bars", "Bars between trades", "Risk")
self._prev_fast_ema = 0.0
self._prev_slow_ema = 0.0
self._prev_macd = 0.0
self._stop_price = 0.0
self._take_profit_price = 0.0
self._entry_price = 0.0
self._cooldown_remaining = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(scalping_ema_rsi_macd_strategy, self).OnReseted()
self._prev_fast_ema = 0.0
self._prev_slow_ema = 0.0
self._prev_macd = 0.0
self._stop_price = 0.0
self._take_profit_price = 0.0
self._entry_price = 0.0
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(scalping_ema_rsi_macd_strategy, self).OnStarted2(time)
fast_ema = ExponentialMovingAverage()
fast_ema.Length = int(self._fast_ema_length.Value)
slow_ema = ExponentialMovingAverage()
slow_ema.Length = int(self._slow_ema_length.Value)
trend_ema = ExponentialMovingAverage()
trend_ema.Length = int(self._trend_ema_length.Value)
rsi = RelativeStrengthIndex()
rsi.Length = int(self._rsi_length.Value)
macd = MovingAverageConvergenceDivergence()
macd.ShortMa.Length = int(self._fast_ema_length.Value)
macd.LongMa.Length = int(self._slow_ema_length.Value)
atr = AverageTrueRange()
atr.Length = int(self._atr_length.Value)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast_ema, slow_ema, trend_ema, rsi, macd, atr, 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_ema, slow_ema, trend_ema, rsi, macd, atr):
if candle.State != CandleStates.Finished:
return
if not self.IsFormedAndOnlineAndAllowTrading():
self._prev_fast_ema = float(fast_ema)
self._prev_slow_ema = float(slow_ema)
self._prev_macd = float(macd)
return
close = float(candle.ClosePrice)
fast_v = float(fast_ema)
slow_v = float(slow_ema)
trend_v = float(trend_ema)
rsi_v = float(rsi)
macd_v = float(macd)
atr_v = float(atr)
cooldown = int(self._cooldown_bars.Value)
# Check stop-loss and take-profit exits first
if self.Position > 0 and self._stop_price > 0:
if float(candle.LowPrice) <= self._stop_price or float(candle.HighPrice) >= self._take_profit_price:
self.SellMarket(Math.Abs(self.Position))
self._stop_price = 0.0
self._take_profit_price = 0.0
self._cooldown_remaining = cooldown
self._prev_fast_ema = fast_v
self._prev_slow_ema = slow_v
self._prev_macd = macd_v
return
elif self.Position < 0 and self._stop_price > 0:
if float(candle.HighPrice) >= self._stop_price or float(candle.LowPrice) <= self._take_profit_price:
self.BuyMarket(Math.Abs(self.Position))
self._stop_price = 0.0
self._take_profit_price = 0.0
self._cooldown_remaining = cooldown
self._prev_fast_ema = fast_v
self._prev_slow_ema = slow_v
self._prev_macd = macd_v
return
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
self._prev_fast_ema = fast_v
self._prev_slow_ema = slow_v
self._prev_macd = macd_v
return
up_trend = close > trend_v and fast_v > slow_v
down_trend = close < trend_v and fast_v < slow_v
bull_cross = self._prev_fast_ema > 0 and self._prev_fast_ema <= self._prev_slow_ema and fast_v > slow_v
bear_cross = self._prev_fast_ema > 0 and self._prev_fast_ema >= self._prev_slow_ema and fast_v < slow_v
macd_rising = macd_v > self._prev_macd
macd_falling = macd_v < self._prev_macd
rsi_ob = float(self._rsi_overbought.Value)
rsi_os = float(self._rsi_oversold.Value)
long_condition = bull_cross and up_trend and rsi_v > 40 and rsi_v < rsi_ob and macd_rising
short_condition = bear_cross and down_trend and rsi_v < 60 and rsi_v > rsi_os and macd_falling
atr_mult = float(self._atr_multiplier.Value)
rr = float(self._risk_reward.Value)
if long_condition and self.Position <= 0:
if self.Position < 0:
self.BuyMarket(Math.Abs(self.Position))
self.BuyMarket(self.Volume)
self._entry_price = close
self._stop_price = close - atr_v * atr_mult
self._take_profit_price = close + (close - self._stop_price) * rr
self._cooldown_remaining = cooldown
elif short_condition and self.Position >= 0:
if self.Position > 0:
self.SellMarket(Math.Abs(self.Position))
self.SellMarket(self.Volume)
self._entry_price = close
self._stop_price = close + atr_v * atr_mult
self._take_profit_price = close - (self._stop_price - close) * rr
self._cooldown_remaining = cooldown
self._prev_fast_ema = fast_v
self._prev_slow_ema = slow_v
self._prev_macd = macd_v
def CreateClone(self):
return scalping_ema_rsi_macd_strategy()