View on GitHub

EA Vishal EURGBP H4 Strategy

Overview

The EA Vishal EURGBP H4 Strategy replicates the original MetaTrader expert advisor that combines a stochastic crossover entry filter with envelope-based exits. The logic operates on H4 candles by default and uses virtual risk management tools (stop-loss, take-profit, and optional trailing stop) defined in pips, closely mirroring the MT4 behaviour.

Trading Logic

  • Entry – the strategy waits for a stochastic crossover evaluated on the two most recent completed candles. A long position is opened when %K crosses below %D between bar n-2 and n-1. A short position is opened on the opposite crossover. Only one position can be active at a time.
  • Exit – active positions are managed in three layers:
    1. Envelope breakout – if the next bar opens beyond the previous envelope band while the earlier bar opened inside, the position is closed immediately.
    2. Virtual stop-loss / take-profit – target prices are computed from the entry price using the configured pip distances.
    3. Optional trailing stop – when enabled and a stop-loss is defined, the stop level trails the highest (for longs) or lowest (for shorts) value of the previous candle minus/plus the stop distance.

Parameters

Name Default Description
Volume 0.5 Order volume in lots for every trade.
StopLossPips 0 Hard stop-loss distance in pips (0 disables the stop).
TakeProfitPips 22 Take-profit distance in pips (0 disables the target).
UseTrailingStop false Enables the virtual trailing stop that follows the previous candle’s extremum. Requires StopLossPips > 0.
StochasticKPeriod 6 Lookback period for the stochastic %K calculation.
StochasticDPeriod 3 Smoothing period for the %D line.
StochasticSlowing 1 Slowing factor applied to %K.
EnvelopePeriod 32 Length of the SMA used as the envelope basis.
EnvelopeDeviationPercent 0.3 Deviation in percent applied above/below the SMA to build the envelopes.
CandleType H4 time frame Candle series that feeds the strategy (default is four-hour candles).

Notes

  • All parameters are exposed for optimisation in StockSharp Studio.
  • Protective levels are tracked internally and executed with market orders when the candle range pierces them, matching the behaviour of the original expert advisor on new bar events.
  • The strategy relies on finished candles only, ensuring deterministic backtests and production behaviour.
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 EaVishalEurgbpH4Strategy : 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 EaVishalEurgbpH4Strategy()
	{
		_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;
	}
}