Ver en GitHub

Estrategia de Reversión de Rango Pipso

Esta estrategia es un port de StockSharp del asesor experto Pipso de MQL5. Actúa como un sistema de reversión a la media que vende en rupturas alcistas y compra en rupturas bajistas de un rango reciente de máximo/mínimo, limitando la actividad a una sesión de trading configurable.

Idea principal

  • Construir un canal estilo Donchian a partir del máximo más alto y el mínimo más bajo de los últimos LookbackPeriod candles finalizados (por defecto 36).
  • Monitorear el límite superior para desvanecer rupturas al alza y el límite inferior para desvanecer rupturas a la baja.
  • Abrir posiciones solo cuando el candle actual comienza dentro de la ventana de trading definida por StartHour y EndHour.

Lógica de trading

Criterios de entrada

  • Entrada corta: cuando el máximo del candle toca o supera el máximo del canal anterior, cerrar cualquier posición larga y, si se está dentro de la ventana de sesión, vender OrderVolume contratos a mercado. El modelo registra el precio de entrada como el máximo del canal.
  • Entrada larga: cuando el mínimo del candle toca o rompe por debajo del mínimo del canal anterior, cerrar cualquier posición corta y, si el trading está permitido, comprar OrderVolume contratos a mercado con el mínimo del canal como referencia de entrada.

Criterios de salida

  • Las posiciones se cierran inmediatamente cuando el precio toca el lado opuesto del canal (reflejando el comportamiento del EA original).
  • Se coloca un stop de protección a una distancia fija del precio de entrada. La distancia del stop equivale a (channelHigh - channelLow) * (1 + StopRangePercent / 100); con el valor predeterminado StopRangePercent = 300 el stop queda a cuatro anchos de canal de distancia.
  • Los stops se evalúan en los extremos del candle: una posición larga se cierra si el mínimo del candle cae por debajo del stop, y una corta si el máximo supera el stop.

Filtro de sesión

  • StartHour y EndHour se especifican en hora del exchange. Si StartHour < EndHour la estrategia opera solo entre esas horas en el mismo día. Si StartHour > EndHour la ventana cruza la medianoche, habilitando sesiones nocturnas (por ej., 21 → 9).
  • Cuando la ventana está deshabilitada (StartHour == EndHour) la estrategia permanece sin posiciones.

Parámetros

  • OrderVolume (predeterminado 0.1) – volumen de trading por orden.
  • LookbackPeriod (predeterminado 36) – número de candles usados para calcular el canal.
  • StartHour (predeterminado 21) – hora (0–23) en que se abre la sesión.
  • EndHour (predeterminado 9) – hora (0–23) en que se cierra la sesión.
  • StopRangePercent (predeterminado 300) – porcentaje adicional del ancho del canal añadido al rango bruto antes de convertirlo a distancia de stop.
  • CandleType (predeterminado candles de 1 hora) – marco temporal usado para los cálculos.

Indicadores y datos

  • Usa los indicadores Highest y Lowest de StockSharp para rastrear los límites del canal.
  • Funciona con cualquier instrumento que proporcione datos de candles continuos que coincidan con el CandleType seleccionado.
  • El EA original espera que el marco temporal del gráfico represente el horizonte de decisión; puede ajustar CandleType para reproducir esas condiciones.

Notas

  • La lógica opera en candles finalizados para evitar ruido intrabarra; en feeds en vivo los precios de stop/entrada aproximan dónde el EA de MQL5 interactuaría con los ticks.
  • No se define un objetivo de take-profit—los beneficios se realizan cuando el precio revierte al límite opuesto o cuando se alcanza el stop.
  • Considere calibrar las horas de sesión, la longitud del rango y el multiplicador del stop a la volatilidad del instrumento de trading.
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>
/// Range-reversal strategy translated from the Pipso MQL5 expert advisor.
/// The system fades breakouts of the recent high/low range during a configurable trading session.
/// </summary>
public class PipsoStrategy : Strategy
{
	private readonly StrategyParam<decimal> _orderVolume;
	private readonly StrategyParam<int> _lookbackPeriod;
	private readonly StrategyParam<int> _startHour;
	private readonly StrategyParam<int> _endHour;
	private readonly StrategyParam<decimal> _stopRangePercent;
	private readonly StrategyParam<DataType> _candleType;

	private Highest _highest = null!;
	private Lowest _lowest = null!;
	private decimal _previousHighest;
	private decimal _previousLowest;
	private bool _isChannelInitialized;

	private decimal? _entryPrice;
	private decimal? _stopPrice;
	private Sides? _entrySide;

	/// <summary>
	/// Trade volume expressed in lots or contracts.
	/// </summary>
	public decimal OrderVolume
	{
		get => _orderVolume.Value;
		set => _orderVolume.Value = value;
	}

	/// <summary>
	/// Number of candles used to compute the high/low channel.
	/// </summary>
	public int LookbackPeriod
	{
		get => _lookbackPeriod.Value;
		set => _lookbackPeriod.Value = value;
	}

	/// <summary>
	/// Hour when the strategy is allowed to start trading.
	/// </summary>
	public int StartHour
	{
		get => _startHour.Value;
		set => _startHour.Value = value;
	}

	/// <summary>
	/// Hour when trading should stop.
	/// </summary>
	public int EndHour
	{
		get => _endHour.Value;
		set => _endHour.Value = value;
	}

	/// <summary>
	/// Multiplier applied to the channel width to compute the stop distance.
	/// </summary>
	public decimal StopRangePercent
	{
		get => _stopRangePercent.Value;
		set => _stopRangePercent.Value = value;
	}

	/// <summary>
	/// Candle type used for calculations.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Initializes strategy parameters.
	/// </summary>
	public PipsoStrategy()
	{
		_orderVolume = Param(nameof(OrderVolume), 1m)
			.SetGreaterThanZero()
			.SetDisplay("Volume", "Order volume per trade", "General");

		_lookbackPeriod = Param(nameof(LookbackPeriod), 36)
			.SetGreaterThanZero()
			.SetDisplay("Lookback Period", "Number of candles used for high/low extremes", "Channel");

		_startHour = Param(nameof(StartHour), 21)
			.SetDisplay("Start Hour", "Session start hour (0-23)", "Session");

		_endHour = Param(nameof(EndHour), 9)
			.SetDisplay("End Hour", "Session end hour (0-23)", "Session");

		_stopRangePercent = Param(nameof(StopRangePercent), 300m)
			.SetGreaterThanZero()
			.SetDisplay("Stop Range %", "Extra percentage of the channel width for stop distance", "Risk");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
			.SetDisplay("Candle Type", "Time frame used for calculations", "General");
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		return [(Security, CandleType)];
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_previousHighest = 0m;
		_previousLowest = 0m;
		_isChannelInitialized = false;
		ResetTradeState();
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		Volume = OrderVolume;

		_highest = new Highest { Length = LookbackPeriod };
		_lowest = new Lowest { Length = LookbackPeriod };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(_highest, _lowest, ProcessCandle)
			.Start();
	}

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

		if (!_highest.IsFormed || !_lowest.IsFormed)
		{
			_previousHighest = highestValue;
			_previousLowest = lowestValue;
			return;
		}

		if (!_isChannelInitialized)
		{
			_previousHighest = highestValue;
			_previousLowest = lowestValue;
			_isChannelInitialized = true;
			return;
		}

		// Indicators are bound via .Bind, no need for IsFormedAndOnlineAndAllowTrading.

		var channelHigh = _previousHighest;
		var channelLow = _previousLowest;

		ManageStopLoss(candle);

		var channelRange = channelHigh - channelLow;
		var breakoutHigh = candle.HighPrice >= channelHigh && channelRange > 0m;
		var breakoutLow = candle.LowPrice <= channelLow && channelRange > 0m;
		var canTrade = IsWithinTradingWindow(candle.OpenTime);

		if (breakoutHigh && Position > 0)
		{
			SellMarket();
			ResetTradeState();
		}

		if (breakoutLow && Position < 0)
		{
			BuyMarket();
			ResetTradeState();
		}

		if (channelRange > 0m)
		{
			var stopDistance = channelRange * (1m + StopRangePercent / 100m);

			if (breakoutHigh && Position == 0 && canTrade)
			{
				SellMarket();
				_entrySide = Sides.Sell;
				_entryPrice = channelHigh;
				_stopPrice = _entryPrice + stopDistance;
			}
			else if (breakoutLow && Position == 0 && canTrade)
			{
				BuyMarket();
				_entrySide = Sides.Buy;
				_entryPrice = channelLow;
				_stopPrice = _entryPrice - stopDistance;
			}
		}

		if (Position == 0)
			ResetTradeState();

		_previousHighest = highestValue;
		_previousLowest = lowestValue;
	}

	private void ManageStopLoss(ICandleMessage candle)
	{
		if (_entrySide is null || _stopPrice is null)
			return;

		if (_entrySide == Sides.Buy)
		{
			if (Position <= 0)
			{
				ResetTradeState();
				return;
			}

			if (candle.LowPrice <= _stopPrice.Value)
			{
				SellMarket();
				ResetTradeState();
			}
		}
		else if (_entrySide == Sides.Sell)
		{
			if (Position >= 0)
			{
				ResetTradeState();
				return;
			}

			if (candle.HighPrice >= _stopPrice.Value)
			{
				BuyMarket();
				ResetTradeState();
			}
		}
	}

	private bool IsWithinTradingWindow(DateTimeOffset time)
	{
		var normalizedStart = ((StartHour % 24) + 24) % 24;
		var normalizedEnd = ((EndHour % 24) + 24) % 24;

		if (normalizedStart == normalizedEnd)
			return false;

		var start = new TimeSpan(normalizedStart, 0, 0);
		var end = new TimeSpan(normalizedEnd, 0, 0);
		var current = time.TimeOfDay;

		return normalizedStart < normalizedEnd
			? current >= start && current <= end
			: current >= start || current <= end;
	}

	private void ResetTradeState()
	{
		_entryPrice = null;
		_stopPrice = null;
		_entrySide = null;
	}
}