GitHub で見る

EurGbp EA Strategy

Overview

The EurGbp EA strategy mirrors the original MetaTrader expert advisor by comparing hourly MACD momentum of EUR/USD and GBP/USD while placing trades on the configured primary instrument (typically EUR/GBP). The approach exploits relative strength between euro and pound majors to anticipate moves in the cross pair.

Indicators

  • MACD (12, 26, 9) on EUR/USD (signal and histogram).
  • MACD (12, 26, 9) on GBP/USD (signal and histogram).

Both indicators are evaluated on the same timeframe selected through the Candle Type parameter (default is 1 hour).

Trading Logic

  1. Subscribe to candles for the trading security plus EUR/USD and GBP/USD.
  2. Compute MACD signal and histogram for both reference pairs.
  3. Buy condition:
    • EUR/USD histogram < GBP/USD histogram, and
    • EUR/USD signal > GBP/USD signal,
    • No existing long position (or an existing short that will be flattened).
  4. Sell condition:
    • GBP/USD histogram < EUR/USD histogram, and
    • GBP/USD signal > EUR/USD signal,
    • No existing short position (or an existing long that will be flattened).
  5. Only one trade per bar in each direction is allowed to avoid duplicate entries.
  6. Stop-loss and take-profit orders are attached immediately after entry using the configured point distances.

Parameters

Name Description Default
Candle Type Timeframe for all candle subscriptions. 1 hour
EURUSD Security Instrument providing EUR/USD candles. Must be set
GBPUSD Security Instrument providing GBP/USD candles. Must be set
Volume Order volume (lots). 0.01
Stop Loss Protective stop in price steps. 75
Take Profit Profit target in price steps. 46

Risk Management

  • Stop Loss and Take Profit are measured in price steps of the traded security. Ensure the security has a valid PriceStep value.
  • Protection starts automatically when the strategy launches (StartProtection).
  • If either distance is zero, the respective protective order is skipped.

Usage Notes

  • Assign the main trading security to the strategy instance before start (for example, EUR/GBP).
  • Configure EURUSD Security and GBPUSD Security to reference available data sources within your connection.
  • The strategy requires synchronized data for all three securities on the selected timeframe to generate signals reliably.
  • Only market orders are used. Existing opposite positions are closed by sending the inverse order volume.

Conversion Notes

  • Original inputs _Lots, _SL, _TP, _MagicNumber, _Comment, _OnlyOneOpenedPos, and _AutoDigits are mapped to StockSharp parameters or built-in behavior.
  • Order closure helper routines from the MQL version are replaced with StockSharp high-level protective order management.
  • Error handling and retry loops from the MQL code are omitted because the StockSharp execution model already manages order states and retries.
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 EurGbpEaStrategy : 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 EurGbpEaStrategy()
	{
		_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;
	}
}