Ver en GitHub

Estrategia MADX-07 ADX MA

Esta estrategia ha sido convertida del asesor experto MQL4 MADX-07. Opera en velas H4 y combina dos medias móviles con el Índice de Movimiento Direccional Promedio (ADX) como filtros.

Lógica

  • Entrada larga: Precio por encima de la MA lenta, MA rápida por encima de la MA lenta, precio al menos MaDifference puntos por encima de la MA rápida durante las dos últimas velas, ADX subiendo por encima de AdxMainLevel con +DI subiendo y -DI bajando.
  • Entrada corta: Condiciones espejo.
  • La posición se cierra cuando el beneficio en puntos alcanza CloseProfit o cuando se ejecuta una orden limitada a una distancia de TakeProfit.

Parámetros

  • BigMaPeriod (25) – período de la MA lenta.
  • BigMaType – tipo de la MA lenta.
  • SmallMaPeriod (5) – período de la MA rápida.
  • SmallMaType – tipo de la MA rápida.
  • MaDifference (5) – distancia mínima entre el precio y la MA rápida en puntos.
  • AdxPeriod (11) – período de cálculo del ADX.
  • AdxMainLevel (13) – valor mínimo del ADX.
  • AdxPlusLevel (13) – valor mínimo del +DI.
  • AdxMinusLevel (14) – valor mínimo del -DI.
  • TakeProfit (299) – distancia del take-profit en puntos.
  • CloseProfit (13) – beneficio en puntos para la salida anticipada.
  • Volume (0.1) – volumen de la operación.
  • CandleType – marco temporal de las velas (por defecto H4).
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>
/// Strategy combining EMA crossover for trend following.
/// </summary>
public class Madx07AdxMaStrategy : Strategy
{
	private readonly StrategyParam<int> _bigMaPeriod;
	private readonly StrategyParam<int> _smallMaPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevSmall;
	private decimal _prevBig;
	private bool _hasPrev;

	public int BigMaPeriod { get => _bigMaPeriod.Value; set => _bigMaPeriod.Value = value; }
	public int SmallMaPeriod { get => _smallMaPeriod.Value; set => _smallMaPeriod.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public Madx07AdxMaStrategy()
	{
		_bigMaPeriod = Param(nameof(BigMaPeriod), 25)
			.SetGreaterThanZero()
			.SetDisplay("Big MA Period", "Period of the slower MA", "MA");

		_smallMaPeriod = Param(nameof(SmallMaPeriod), 10)
			.SetGreaterThanZero()
			.SetDisplay("Small MA Period", "Period of the faster MA", "MA");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Candle type", "General");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
		=> [(Security, CandleType)];

	protected override void OnReseted()
	{
		base.OnReseted();
		_prevSmall = 0;
		_prevBig = 0;
		_hasPrev = false;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var bigMa = new ExponentialMovingAverage { Length = BigMaPeriod };
		var smallMa = new ExponentialMovingAverage { Length = SmallMaPeriod };

		SubscribeCandles(CandleType)
			.Bind(bigMa, smallMa, ProcessCandle)
			.Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal bigMaVal, decimal smallMaVal)
	{
		if (candle.State != CandleStates.Finished) return;

		if (!_hasPrev)
		{
			_prevSmall = smallMaVal;
			_prevBig = bigMaVal;
			_hasPrev = true;
			return;
		}

		var crossUp = _prevSmall <= _prevBig && smallMaVal > bigMaVal;
		var crossDown = _prevSmall >= _prevBig && smallMaVal < bigMaVal;

		if (crossUp && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		else if (crossDown && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevSmall = smallMaVal;
		_prevBig = bigMaVal;
	}
}