View on GitHub

Exp Highs Lows Signal

Overview

Exp Highs Lows Signal is a direct port of the MetaTrader 5 expert advisor Exp_HighsLowsSignal. The strategy relies on a pattern detector that searches for a configurable number of consecutive candles that print higher highs and higher lows (bullish sequence) or lower highs and lower lows (bearish sequence). Once a sequence is found, the strategy delays the reaction by the configured number of closed bars, closes any opposite exposure, and optionally opens a position in the detected direction. Protective stops are expressed in price steps to mirror the point-based money management used by the original robot.

Strategy logic

Highs/Lows sequence detector

  • The detector evaluates each finished candle on the selected timeframe.
  • A bullish signal requires SequenceLength consecutive comparisons where both the current high and the current low are strictly greater than the previous bar.
  • A bearish signal requires SequenceLength consecutive comparisons where both the current high and the current low are strictly lower than the previous bar.
  • Signals are queued and released after SignalBarDelay closed candles, matching the SignalBar setting from the MQL implementation.

Entry rules

  • Long entries
    • Triggered when a bullish sequence becomes active and AllowLongEntry is enabled.
    • Any existing short position is closed first (if AllowShortExit is true), then a market buy order is submitted with volume OrderVolume + |Position| to cover shorts and establish the desired long size.
  • Short entries
    • Triggered when a bearish sequence becomes active and AllowShortEntry is enabled.
    • Any existing long position is closed first (if AllowLongExit is true), then a market sell order is submitted with volume OrderVolume + |Position| to cover longs and establish the desired short size.

Exit rules

  • A bullish sequence always requests AllowShortExit to close open shorts.
  • A bearish sequence always requests AllowLongExit to close open longs.
  • When the relevant flag is disabled, the opposite exposure remains untouched, allowing the user to trade only one direction or run the detector in "alerts only" mode.

Risk management

  • StopLossTicks and TakeProfitTicks represent distances in price steps (points). A value of 0 disables the corresponding protective order, reproducing the behaviour of the original EA.
  • StartProtection converts those distances into absolute price offsets so that all market entries automatically receive matching stop-loss and take-profit orders.

Parameters

  • OrderVolume – base order volume used when a new trade is opened.
  • AllowLongEntry / AllowShortEntry – toggles that enable long or short entries on their respective signals.
  • AllowLongExit / AllowShortExit – toggles that allow the strategy to flatten opposite positions when the counter-trend signal appears.
  • StopLossTicks / TakeProfitTicks – protective distances in price steps; set to 0 to disable.
  • SequenceLength – number of consecutive comparisons required to qualify a bullish or bearish sequence (equivalent to HowManyCandles in MT5).
  • SignalBarDelay – number of closed candles to wait before acting on a signal (equivalent to the SignalBar input).
  • CandleType – timeframe used to build the Highs/Lows detector (default: 4-hour candles).

Additional notes

  • The strategy stores only the minimal amount of candle history required for the detector, keeping the behaviour identical to the MT5 custom indicator.
  • Because all order management occurs through StartProtection, backtests and live trading automatically receive matching stop and take-profit orders without extra code.
  • Disable the corresponding Allow flags to turn the strategy into a directional filter or a pure signalling tool.
  • No Python translation is provided; only the C# version is available in this package.
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>
/// Highs Lows Signal strategy using EMA crossover.
/// Buys when fast EMA crosses above slow EMA, sells on reverse.
/// </summary>
public class ExpHighsLowsSignalStrategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<int> _stopLossPoints;
	private readonly StrategyParam<int> _takeProfitPoints;

	private ExponentialMovingAverage _fast;
	private ExponentialMovingAverage _slow;

	private decimal _prevFast;
	private decimal _prevSlow;
	private decimal _entryPrice;
	private int _cooldown;

	public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
	public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
	public int StopLossPoints { get => _stopLossPoints.Value; set => _stopLossPoints.Value = value; }
	public int TakeProfitPoints { get => _takeProfitPoints.Value; set => _takeProfitPoints.Value = value; }

	public ExpHighsLowsSignalStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 14).SetGreaterThanZero().SetDisplay("Fast Period", "Fast EMA period", "Indicator");
		_slowPeriod = Param(nameof(SlowPeriod), 50).SetGreaterThanZero().SetDisplay("Slow Period", "Slow EMA period", "Indicator");
		_stopLossPoints = Param(nameof(StopLossPoints), 200).SetNotNegative().SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");
		_takeProfitPoints = Param(nameof(TakeProfitPoints), 400).SetNotNegative().SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
	}

	protected override void OnReseted()
	{
		base.OnReseted();
		_fast = null; _slow = null;
		_prevFast = 0; _prevSlow = 0; _entryPrice = 0; _cooldown = 0;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);
		_fast = new ExponentialMovingAverage { Length = FastPeriod };
		_slow = new ExponentialMovingAverage { Length = SlowPeriod };
		var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
		subscription.Bind(_fast, _slow, ProcessCandle);
		subscription.Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
	{
		if (candle.State != CandleStates.Finished) return;
		if (!_fast.IsFormed || !_slow.IsFormed) { _prevFast = fastValue; _prevSlow = slowValue; return; }
		if (_cooldown > 0) { _cooldown--; _prevFast = fastValue; _prevSlow = slowValue; return; }

		var close = candle.ClosePrice;
		var step = Security?.PriceStep ?? 1m;

		if (Position > 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}
		else if (Position < 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}

		if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
		{ if (Position < 0) BuyMarket(); BuyMarket(); _entryPrice = close; _cooldown = 100; }
		else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
		{ if (Position > 0) SellMarket(); SellMarket(); _entryPrice = close; _cooldown = 100; }

		_prevFast = fastValue; _prevSlow = slowValue;
	}
}