View on GitHub

Weekly Rebound Corridor Strategy

Overview

The Weekly Rebound Corridor strategy replicates the behavior of the MetaTrader 4 Expert Advisor 2_Otkat_Sys_v1_1. The system searches for a strong gap between the previous session close and the open price that occurred 24 candles earlier. When the detected gap exceeds a configurable corridor threshold and it is the specified trading day of the week, the strategy enters the market during the first minutes of the new trading day. Protective stop-loss and take-profit levels are applied, and all open positions are force-closed shortly before the trading session ends.

Trading Logic

  1. Data Preparation
    • Uses minute candles by default. The candle type is configurable to accommodate other bar sizes.
    • Keeps track of the previous candle close and maintains a circular buffer that returns the open price observed 24 candles ago.
  2. Signal Generation
    • On the specified trading day of the week (MetaTrader format: 0 = Sunday, 6 = Saturday), the strategy evaluates finished candles whose local time is between 00:00 and 00:03.
    • Calculates the difference between the historical open (24 candles ago) and the latest closed candle. If the difference exceeds the configured corridor threshold, a market order is sent:
      • Long setup: Historical open minus previous close is greater than the corridor threshold.
      • Short setup: Previous close minus historical open is greater than the corridor threshold.
    • Each trading day can trigger at most one entry.
  3. Trade Management
    • Stop-loss and take-profit levels are expressed in points. The tick size of the instrument converts the point values into actual price offsets.
    • Long trades add the original MT4 offset of three extra points to the take-profit distance.
    • The strategy continuously monitors candle highs and lows to detect stop-loss or take-profit hits and closes the open position with a market order when triggered.
    • Any remaining open position is closed after 22:45 local exchange time to emulate the end-of-day flat rule from the original Expert Advisor.

Parameters

Name Description Default
TakeProfitPoints Take-profit distance in points. Long trades add three additional points, as defined in the MT4 script. 5
StopLossPoints Stop-loss distance in points. 49
TradeVolume Volume submitted with market orders. The value is automatically aligned with the instrument volume step. 1
CorridorPoints Minimum required gap between the historical open and the most recent close. 10
TradeDayOfWeek Trading day in MetaTrader numbering (0 = Sunday6 = Saturday). 5 (Friday)
CandleType Candle data type used for analysis. 1 minute

Notes

  • The strategy operates exclusively on completed candles to align with the project guidelines.
  • Ensure that the selected instrument provides enough historical data to build the 24-candle buffer before expecting entries.
  • The volume and point-based parameters should be adjusted to match the instrument specification (tick size, lot step, trading schedule).
using System;

using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

public class WeeklyReboundCorridorStrategy : Strategy
{
	private readonly StrategyParam<int> _rsiPeriod;
	private readonly StrategyParam<int> _emaPeriod;
	private readonly StrategyParam<decimal> _oversold;
	private readonly StrategyParam<decimal> _overbought;
	private readonly StrategyParam<int> _cooldownCandles;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevRsi;
	private bool _hasPrev;
	private int _cooldownRemaining;

	public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
	public int EmaPeriod { get => _emaPeriod.Value; set => _emaPeriod.Value = value; }
	public decimal Oversold { get => _oversold.Value; set => _oversold.Value = value; }
	public decimal Overbought { get => _overbought.Value; set => _overbought.Value = value; }
	public int CooldownCandles { get => _cooldownCandles.Value; set => _cooldownCandles.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public WeeklyReboundCorridorStrategy()
	{
		_rsiPeriod = Param(nameof(RsiPeriod), 14).SetDisplay("RSI Period", "RSI lookback", "Indicators");
		_emaPeriod = Param(nameof(EmaPeriod), 50).SetDisplay("EMA Period", "EMA filter", "Indicators");
		_oversold = Param(nameof(Oversold), 25m).SetDisplay("Oversold", "RSI oversold level", "Levels");
		_overbought = Param(nameof(Overbought), 75m).SetDisplay("Overbought", "RSI overbought level", "Levels");
		_cooldownCandles = Param(nameof(CooldownCandles), 50).SetDisplay("Cooldown", "Candles between signals", "General");
		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame()).SetDisplay("Candle Type", "Candle timeframe", "General");
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevRsi = default;
		_hasPrev = default;
		_cooldownRemaining = default;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);
		_prevRsi = 0;
		_hasPrev = false;
		_cooldownRemaining = 0;

		var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
		var ema = new ExponentialMovingAverage { Length = EmaPeriod };
		var subscription = SubscribeCandles(CandleType);
		subscription.Bind(rsi, ema, ProcessCandle).Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal rsi, decimal ema)
	{
		if (candle.State != CandleStates.Finished) return;
		var close = candle.ClosePrice;
		if (!_hasPrev) { _prevRsi = rsi; _hasPrev = true; return; }

		if (_cooldownRemaining > 0)
		{
			_cooldownRemaining--;
			_prevRsi = rsi;
			return;
		}

		var oversold = Oversold;
		var overbought = Overbought;

		if (_prevRsi >= oversold && rsi < oversold && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
			_cooldownRemaining = CooldownCandles;
		}
		else if (_prevRsi <= overbought && rsi > overbought && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
			_cooldownRemaining = CooldownCandles;
		}
		_prevRsi = rsi;
	}
}