Esta estrategia es una conversión simplificada del experto MQL5 original "LeManTrendHist". Se basa en un histograma basado en EMA para generar señales de trading.
Idea
El algoritmo original calcula un histograma personalizado derivado de extremos de precio y rangos suavizados. Para esta muestra, el histograma se aproxima mediante una media móvil exponencial de los rangos de velas.
Lógica de la estrategia
Calcular el valor EMA para cada vela completada.
Comparar los tres últimos valores EMA.
Cuando el valor del medio es menor que el más antiguo y el nuevo valor sube por encima de él, se abre una posición larga y se cierran las posiciones cortas.
Cuando el valor del medio es mayor que el más antiguo y el nuevo valor cae por debajo de él, se abre una posición corta y se cierran las posiciones largas.
Parámetros
Candle Type – marco temporal de las velas procesadas.
EMA Period – longitud del EMA usado en el histograma de marcador de posición.
Signal Bar – desplazamiento histórico para los valores del indicador (mantenido por compatibilidad, no se usa en la lógica simplificada).
Buy/Sell Open – habilitar entradas largas o cortas.
Buy/Sell Close – habilitar el cierre de posiciones existentes.
Notas
El indicador real LeManTrendHist utiliza algoritmos de suavizado complejos que aún no están implementados. La implementación actual actúa como un marcador de posición y debe reemplazarse con el indicador completo para uso en producción.
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>
/// LeManTrendHist strategy using EMA slope changes as trend signals.
/// </summary>
public class LeManTrendHistStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _emaPeriod;
private decimal? _value1;
private decimal? _value2;
private decimal? _value3;
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int EmaPeriod
{
get => _emaPeriod.Value;
set => _emaPeriod.Value = value;
}
public LeManTrendHistStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
_emaPeriod = Param(nameof(EmaPeriod), 3)
.SetGreaterThanZero()
.SetDisplay("EMA Period", "EMA length", "Parameters");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_value1 = null;
_value2 = null;
_value3 = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ema = new ExponentialMovingAverage { Length = EmaPeriod };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(ema, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, ema);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal emaValue)
{
if (candle.State != CandleStates.Finished)
return;
_value3 = _value2;
_value2 = _value1;
_value1 = emaValue;
if (_value1 is null || _value2 is null || _value3 is null)
return;
// EMA turned up (was falling, now rising)
if (_value2 < _value3 && _value1 > _value2)
{
if (Position < 0)
BuyMarket();
if (Position <= 0)
BuyMarket();
}
// EMA turned down (was rising, now falling)
else if (_value2 > _value3 && _value1 < _value2)
{
if (Position > 0)
SellMarket();
if (Position >= 0)
SellMarket();
}
}
}
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
from StockSharp.Algo.Strategies import Strategy
class leman_trend_hist_strategy(Strategy):
def __init__(self):
super(leman_trend_hist_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._ema_period = self.Param("EmaPeriod", 3) \
.SetDisplay("EMA Period", "EMA length", "Parameters")
self._value1 = None
self._value2 = None
self._value3 = None
@property
def candle_type(self):
return self._candle_type.Value
@property
def ema_period(self):
return self._ema_period.Value
def OnReseted(self):
super(leman_trend_hist_strategy, self).OnReseted()
self._value1 = None
self._value2 = None
self._value3 = None
def OnStarted2(self, time):
super(leman_trend_hist_strategy, self).OnStarted2(time)
ema = ExponentialMovingAverage()
ema.Length = self.ema_period
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)
def process_candle(self, candle, ema_value):
if candle.State != CandleStates.Finished:
return
ema_value = float(ema_value)
self._value3 = self._value2
self._value2 = self._value1
self._value1 = ema_value
if self._value1 is None or self._value2 is None or self._value3 is None:
return
# EMA turned up
if self._value2 < self._value3 and self._value1 > self._value2:
if self.Position < 0:
self.BuyMarket()
if self.Position <= 0:
self.BuyMarket()
# EMA turned down
elif self._value2 > self._value3 and self._value1 < self._value2:
if self.Position > 0:
self.SellMarket()
if self.Position >= 0:
self.SellMarket()
def CreateClone(self):
return leman_trend_hist_strategy()