Estrategia de Rompimiento por Pendiente de EMA
La estrategia de Rompimiento por Pendiente de EMA observa la tasa de cambio de la EMA. Una pendiente inusualmente pronunciada indica que se está formando una nueva tendencia.
Las pruebas indican un rendimiento anual promedio de aproximadamente 127%. Funciona mejor en el mercado de acciones.
Las entradas se producen cuando la pendiente supera su nivel típico en un múltiplo de desviación estándar, tomando operaciones en la dirección de la aceleración con un stop protector.
Atrae a operadores activos que buscan una exposición temprana a la tendencia. Las posiciones se cierran cuando la pendiente regresa hacia las lecturas normales. El valor predeterminado es EmaLength = 20.
Detalles
- Criterios de entrada: El indicador supera el promedio por el multiplicador de desviación.
- Largo/Corto: Ambos direcciones.
- Criterios de salida: El indicador revierte al promedio.
- Stops: Sí.
- Valores predeterminados:
EmaLength= 20LookbackPeriod= 20DeviationMultiplier= 2mStopLossPercent= 2mCandleType= TimeSpan.FromMinutes(5)
- Filtros:
- Categoría: Ruptura
- Dirección: Ambos
- Indicadores: EMA
- Stops: Sí
- Complejidad: Intermedio
- Marco temporal: Corto plazo
- Estacionalidad: No
- Redes neuronales: No
- Divergencia: No
- Nivel de riesgo: Medio
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>
/// Strategy based on Exponential Moving Average Slope breakout
/// Enters positions when the slope of EMA exceeds average slope plus a multiple of standard deviation
/// </summary>
public class EmaSlopeBreakoutStrategy : Strategy
{
private readonly StrategyParam<int> _emaLength;
private readonly StrategyParam<int> _lookbackPeriod;
private readonly StrategyParam<decimal> _deviationMultiplier;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _stopLossPercent;
private ExponentialMovingAverage _ema;
private decimal _prevEmaValue;
private decimal _currentSlope;
private decimal _avgSlope;
private decimal _stdDevSlope;
private decimal[] _slopes;
private int _currentIndex;
private bool _isInitialized;
/// <summary>
/// Exponential Moving Average length
/// </summary>
public int EmaLength
{
get => _emaLength.Value;
set => _emaLength.Value = value;
}
/// <summary>
/// Lookback period for slope statistics calculation
/// </summary>
public int LookbackPeriod
{
get => _lookbackPeriod.Value;
set => _lookbackPeriod.Value = value;
}
/// <summary>
/// Standard deviation multiplier for breakout detection
/// </summary>
public decimal DeviationMultiplier
{
get => _deviationMultiplier.Value;
set => _deviationMultiplier.Value = value;
}
/// <summary>
/// Candle type
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Stop loss percentage
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Constructor
/// </summary>
public EmaSlopeBreakoutStrategy()
{
_emaLength = Param(nameof(EmaLength), 20)
.SetGreaterThanZero()
.SetDisplay("EMA Length", "Period for Exponential Moving Average", "Indicator Parameters")
.SetOptimize(10, 50, 5);
_lookbackPeriod = Param(nameof(LookbackPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("Lookback Period", "Period for slope statistics calculation", "Strategy Parameters")
.SetOptimize(10, 50, 5);
_deviationMultiplier = Param(nameof(DeviationMultiplier), 2m)
.SetGreaterThanZero()
.SetDisplay("Deviation Multiplier", "Standard deviation multiplier for breakout detection", "Strategy Parameters")
.SetOptimize(1m, 3m, 0.5m);
_stopLossPercent = Param(nameof(StopLossPercent), 2m)
.SetGreaterThanZero()
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk Management");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevEmaValue = 0;
_currentSlope = 0;
_avgSlope = 0;
_stdDevSlope = 0;
_currentIndex = 0;
_isInitialized = false;
_slopes = new decimal[LookbackPeriod];
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
_slopes = new decimal[LookbackPeriod];
_ema = new EMA { Length = EmaLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_ema, ProcessCandle)
.Start();
// Setup chart visualization if available
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _ema);
DrawOwnTrades(area);
}
// Set up position protection
StartProtection(
takeProfit: null, // We'll handle exits via strategy logic
stopLoss: new Unit(StopLossPercent, UnitTypes.Percent)
);
base.OnStarted2(time);
}
private void ProcessCandle(ICandleMessage candle, decimal emaValue)
{
// Skip unfinished candles
if (candle.State != CandleStates.Finished)
return;
// Check if indicator is formed
if (!_ema.IsFormed)
return;
// Calculate the slope
if (!_isInitialized)
{
_prevEmaValue = emaValue;
_isInitialized = true;
return;
}
// Calculate current slope (simple difference for now)
_currentSlope = emaValue - _prevEmaValue;
// Store slope in array and update index
_slopes[_currentIndex] = _currentSlope;
_currentIndex = (_currentIndex + 1) % LookbackPeriod;
// Calculate statistics once we have enough data
if (!IsFormedAndOnlineAndAllowTrading())
return;
CalculateStatistics();
// Trading logic
if (Math.Abs(_avgSlope) > 0) // Avoid division by zero
{
// Long signal: slope exceeds average + k*stddev (slope is positive and we don't have a long position)
if (_currentSlope > 0 &&
_currentSlope > _avgSlope + DeviationMultiplier * _stdDevSlope &&
Position <= 0)
{
// Cancel existing orders
CancelActiveOrders();
// Enter long position
var volume = Volume + Math.Abs(Position);
BuyMarket(volume);
LogInfo($"Long signal: Slope {_currentSlope} > Avg {_avgSlope} + {DeviationMultiplier}*StdDev {_stdDevSlope}");
}
// Short signal: slope exceeds average + k*stddev in negative direction (slope is negative and we don't have a short position)
else if (_currentSlope < 0 &&
_currentSlope < _avgSlope - DeviationMultiplier * _stdDevSlope &&
Position >= 0)
{
// Cancel existing orders
CancelActiveOrders();
// Enter short position
var volume = Volume + Math.Abs(Position);
SellMarket(volume);
LogInfo($"Short signal: Slope {_currentSlope} < Avg {_avgSlope} - {DeviationMultiplier}*StdDev {_stdDevSlope}");
}
// Exit conditions - when slope returns to average
if (Position > 0 && _currentSlope < _avgSlope)
{
// Exit long position
SellMarket(Math.Abs(Position));
LogInfo($"Exit long: Slope {_currentSlope} < Avg {_avgSlope}");
}
else if (Position < 0 && _currentSlope > _avgSlope)
{
// Exit short position
BuyMarket(Math.Abs(Position));
LogInfo($"Exit short: Slope {_currentSlope} > Avg {_avgSlope}");
}
}
// Store current EMA value for next slope calculation
_prevEmaValue = emaValue;
}
private void CalculateStatistics()
{
// Reset statistics
_avgSlope = 0;
decimal sumSquaredDiffs = 0;
// Calculate average
for (int i = 0; i < LookbackPeriod; i++)
{
_avgSlope += _slopes[i];
}
_avgSlope /= LookbackPeriod;
// Calculate standard deviation
for (int i = 0; i < LookbackPeriod; i++)
{
decimal diff = _slopes[i] - _avgSlope;
sumSquaredDiffs += diff * diff;
}
_stdDevSlope = (decimal)Math.Sqrt((double)(sumSquaredDiffs / LookbackPeriod));
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
import math
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes
from StockSharp.Algo.Indicators import ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class ema_slope_breakout_strategy(Strategy):
"""
Strategy based on EMA slope breakout.
Enters when slope of EMA exceeds average slope plus a multiple of standard deviation.
Exits when slope returns to average.
"""
def __init__(self):
super(ema_slope_breakout_strategy, self).__init__()
self._ema_length = self.Param("EmaLength", 20) \
.SetDisplay("EMA Length", "Period for EMA", "Indicator Parameters")
self._lookback_period = self.Param("LookbackPeriod", 20) \
.SetDisplay("Lookback Period", "Period for slope statistics", "Strategy Parameters")
self._deviation_multiplier = self.Param("DeviationMultiplier", 2.0) \
.SetDisplay("Deviation Multiplier", "Std dev multiplier for breakout", "Strategy Parameters")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0) \
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk Management")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._prev_ema_value = 0.0
self._current_slope = 0.0
self._avg_slope = 0.0
self._std_dev_slope = 0.0
self._slopes = None
self._current_index = 0
self._is_initialized = False
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(ema_slope_breakout_strategy, self).OnReseted()
self._prev_ema_value = 0.0
self._current_slope = 0.0
self._avg_slope = 0.0
self._std_dev_slope = 0.0
lookback = int(self._lookback_period.Value)
self._slopes = [0.0] * lookback
self._current_index = 0
self._is_initialized = False
def OnStarted2(self, time):
super(ema_slope_breakout_strategy, self).OnStarted2(time)
lookback = int(self._lookback_period.Value)
self._slopes = [0.0] * lookback
self._current_index = 0
ema = ExponentialMovingAverage()
ema.Length = self._ema_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ema)
self.DrawOwnTrades(area)
self.StartProtection(None, Unit(self._stop_loss_percent.Value, UnitTypes.Percent))
def _process_candle(self, candle, ema_val):
if candle.State != CandleStates.Finished:
return
ema_val = float(ema_val)
if not self._is_initialized:
self._prev_ema_value = ema_val
self._is_initialized = True
return
self._current_slope = ema_val - self._prev_ema_value
lookback = int(self._lookback_period.Value)
if self._slopes is None or len(self._slopes) != lookback:
self._slopes = [0.0] * lookback
self._current_index = 0
self._slopes[self._current_index] = self._current_slope
self._current_index = (self._current_index + 1) % lookback
if not self.IsFormedAndOnlineAndAllowTrading():
self._prev_ema_value = ema_val
return
self._calculate_statistics()
if abs(self._avg_slope) > 0:
dev_mult = float(self._deviation_multiplier.Value)
if (self._current_slope > 0 and
self._current_slope > self._avg_slope + dev_mult * self._std_dev_slope and
self.Position <= 0):
self.CancelActiveOrders()
vol = self.Volume + Math.Abs(self.Position)
self.BuyMarket(vol)
elif (self._current_slope < 0 and
self._current_slope < self._avg_slope - dev_mult * self._std_dev_slope and
self.Position >= 0):
self.CancelActiveOrders()
vol = self.Volume + Math.Abs(self.Position)
self.SellMarket(vol)
if self.Position > 0 and self._current_slope < self._avg_slope:
self.SellMarket(Math.Abs(self.Position))
elif self.Position < 0 and self._current_slope > self._avg_slope:
self.BuyMarket(Math.Abs(self.Position))
self._prev_ema_value = ema_val
def _calculate_statistics(self):
lookback = int(self._lookback_period.Value)
self._avg_slope = 0.0
sum_sq = 0.0
for i in range(lookback):
self._avg_slope += self._slopes[i]
self._avg_slope /= float(lookback)
for i in range(lookback):
diff = self._slopes[i] - self._avg_slope
sum_sq += diff * diff
self._std_dev_slope = math.sqrt(sum_sq / float(lookback))
def CreateClone(self):
return ema_slope_breakout_strategy()