GitHub で見る

Explosion Range Expansion Strategy

Overview

Explosion Range Expansion Strategy is a breakout system converted from the MetaTrader 5 expert advisor "Explosion". The algorithm compares the range of the current completed candle with the previous candle and opens a market position in the direction of the candle body whenever the range expansion exceeds a configurable ratio. The StockSharp version keeps the original money-management features and adds convenient parameters for schedule control and trailing stop management.

Trading Rules

  • Range Expansion: Calculate the current candle range (High - Low) and compare it with the previous candle range. If the current range is greater than the previous range multiplied by Range Ratio, a signal is generated.
  • Direction Filter:
    • If the candle closes above its open and the current position is flat or short, a long market order is sent.
    • If the candle closes below its open and the current position is flat or long, a short market order is sent.
  • Trading Window: Signals are accepted only when the candle close time falls between Start Hour and End Hour (inclusive).
  • Daily Limit: When One Trade Per Day is enabled, only the first qualifying entry of the trading day is executed.
  • Pause Between Trades: After a position entry the strategy waits Pause (sec) seconds before accepting a new signal.
  • Maximum Exposure: The net position size cannot exceed Max Positions * Order Volume.

Exits and Risk Management

  • Initial Protection: Optional stop-loss and take-profit levels are defined in price steps and calculated from the entry price.
  • Trailing Stop: When enabled, the stop-loss is moved closer to price after a minimum profit threshold (Trailing Stop + Trailing Step) is achieved. The trailing logic maintains the same behaviour as in the original EA.
  • Manual Close on Targets: If the candle range hits either the stop-loss or take-profit level intrabar, the position is closed using a market order.

Parameters

  • Candle Type – Data type used for candle subscription.
  • Order Volume – Size of each position in lots.
  • Range Ratio – Multiplier applied to the previous candle range to trigger entries.
  • Max Positions – Maximum number of lots allowed simultaneously.
  • Pause (sec) – Minimum time in seconds between entries.
  • Start Hour / End Hour – Trading hours filter (0–23).
  • One Trade Per Day – Restricts the strategy to one entry per calendar day.
  • Stop Loss – Initial stop-loss distance in price steps.
  • Take Profit – Initial take-profit distance in price steps.
  • Trailing Stop – Trailing stop distance in price steps.
  • Trailing Step – Additional distance required before trailing is updated.

Conversion Notes

  • The strategy uses the high-level SubscribeCandles and Bind API for indicator-free signal processing.
  • Trailing stop, trading window, pause, and daily limit reproduce the original MQ5 logic.
  • Money management is expressed via a single volume parameter; risk-percentage lot sizing from the original script is not supported in this version.
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;

public class ExplosionRangeExpansionStrategy : 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 ExplosionRangeExpansionStrategy()
	{
		_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;
	}
}