Ver en GitHub

5Mins Envelopes

The 5Mins Envelopes strategy reproduces the MetaTrader expert that trades five-minute candles around a linear weighted moving average envelope. It looks for price spikes that stretch well beyond the bands and then enters in the mean-reversion direction. A spread filter, static stop-loss, optional take-profit, and trailing stop mirror the original money management.

Trading Logic

  • Indicator: Linear Weighted Moving Average (LWMA) calculated on the median price (high+low)/2 with a period of 3.
  • Envelope width: 0.05% deviation from the LWMA value (upper and lower bands).
  • Signal detection (evaluated on the previous completed candle and current bid):
    • Long: Previous candle low stays more than DistancePoints below the lower band and the current bid is also beyond that distance.
    • Short: Previous candle high stays more than DistancePoints above the upper band and the current bid is also beyond that distance.
  • Filters:
    • Only one position at a time (new entries require the current position to be flat).
    • If MaxSpreadPoints is greater than zero, the bid/ask spread must stay below this threshold before submitting a new order.

Risk Management

  • Order volume: TradeVolume parameter controls the market order size.
  • Stop-loss: StopLossPoints converts to absolute price distance using the instrument tick size.
  • Take-profit: Optional TakeProfitPoints; set to zero to disable.
  • Trailing stop: Optional TrailingStopPoints; set to zero to disable.
  • Protection: The StartProtection helper applies all exits with market orders, matching the MetaTrader behaviour.

Parameters

  • TradeVolume = 1m
  • DistancePoints = 140
  • EnvelopePeriod = 3
  • EnvelopeDeviationPercent = 0.05m
  • StopLossPoints = 250
  • TakeProfitPoints = 0
  • TrailingStopPoints = 120
  • MaxSpreadPoints = 25
  • CandleType = TimeFrame(5 minutes)

Tags

  • Category: Mean Reversion
  • Direction: Both
  • Indicators: WeightedMovingAverage
  • Stops: Yes (fixed + trailing)
  • Timeframe: Intraday (M5)
  • Complexity: Beginner
  • Risk Level: Medium
  • Seasonality: No
  • Neural Networks: No
  • Divergence: No
namespace StockSharp.Samples.Strategies;

using System;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.Messages;

/// <summary>
/// 5 Mins Envelopes strategy: envelope breakout using SMA with deviation bands.
/// Buys when price crosses above upper envelope, sells when below lower envelope.
/// </summary>
public class FiveMinsEnvelopesStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _maPeriod;
	private readonly StrategyParam<decimal> _deviation;
	private bool _wasAboveUpper;
	private bool _wasBelowLower;
	private bool _hasPrevSignal;

	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
	public int MaPeriod { get => _maPeriod.Value; set => _maPeriod.Value = value; }
	public decimal Deviation { get => _deviation.Value; set => _deviation.Value = value; }

	public FiveMinsEnvelopesStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
			.SetDisplay("Candle Type", "Candle timeframe", "General");
		_maPeriod = Param(nameof(MaPeriod), 50)
			.SetGreaterThanZero()
			.SetDisplay("MA Period", "Moving average period", "Indicators");
		_deviation = Param(nameof(Deviation), 0.3m)
			.SetDisplay("Deviation %", "Envelope deviation percent", "Indicators");
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_wasAboveUpper = false;
		_wasBelowLower = false;
		_hasPrevSignal = false;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);
		_hasPrevSignal = false;
		var sma = new SimpleMovingAverage { Length = MaPeriod };
		var subscription = SubscribeCandles(CandleType);
		subscription.Bind(sma, ProcessCandle).Start();
	}

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

		var close = candle.ClosePrice;
		var upper = smaValue * (1 + Deviation / 100m);
		var lower = smaValue * (1 - Deviation / 100m);
		var aboveUpper = close > upper;
		var belowLower = close < lower;

		if (_hasPrevSignal)
		{
			if (aboveUpper && !_wasAboveUpper && Position <= 0)
				BuyMarket();
			else if (belowLower && !_wasBelowLower && Position >= 0)
				SellMarket();
		}

		_wasAboveUpper = aboveUpper;
		_wasBelowLower = belowLower;
		_hasPrevSignal = true;
	}
}