在 GitHub 上查看

EurGbp EA 策略

概述

EurGbp EA 策略重现了原始 MetaTrader 智能交易的思路:比较 EUR/USD 与 GBP/USD 在选定小时周期上的 MACD 动量,并在主要交易品种(通常为 EUR/GBP)上开仓。策略利用欧元与英镑主要货币对之间的相对强弱,提前捕捉交叉盘的潜在走势。

指标

  • MACD (12, 26, 9):用于 EUR/USD,获取信号线与柱状图。
  • MACD (12, 26, 9):用于 GBP/USD,获取信号线与柱状图。

两条指标均使用 Candle Type 参数指定的同一时间框架(默认 1 小时)。

交易逻辑

  1. 同时订阅交易标的、EUR/USD、GBP/USD 的蜡烛数据。
  2. 分别计算两组 MACD 的信号线与柱状图数值。
  3. 买入条件:
    • EUR/USD 柱状图 < GBP/USD 柱状图,且
    • EUR/USD 信号线 > GBP/USD 信号线,且
    • 当前无多头仓位(或存在空头仓位时可被抵消)。
  4. 卖出条件:
    • GBP/USD 柱状图 < EUR/USD 柱状图,且
    • GBP/USD 信号线 > EUR/USD 信号线,且
    • 当前无空头仓位(或存在多头仓位时可被抵消)。
  5. 每根 K 线每个方向只允许一次开仓,避免重复下单。
  6. 开仓后立即按照设定的点数距离挂出止损与止盈。

参数

名称 说明 默认值
Candle Type 三个品种共用的时间框架。 1 小时
EURUSD Security 提供 EUR/USD 数据的证券对象。 必须设置
GBPUSD Security 提供 GBP/USD 数据的证券对象。 必须设置
Volume 下单手数。 0.01
Stop Loss 按价格最小变动单位计算的止损距离。 75
Take Profit 按价格最小变动单位计算的止盈距离。 46

风险管理

  • 止损与止盈均以交易标的的 PriceStep 为单位,请确保该属性有效。
  • 策略启动时会调用 StartProtection(),自动启用保护单管理。
  • 若止损或止盈设为 0,则对应保护单不会创建。

使用说明

  • 启动前请将策略的主交易证券设为目标品种(例如 EUR/GBP)。
  • EURUSD SecurityGBPUSD Security 指定连接中可用的数据源。
  • 需要三个品种在所选时间框架上同步更新,才能稳定产生信号。
  • 策略仅使用市价单,若方向相反则通过反向下单来平掉已有仓位。

转换说明

  • 原始输入参数 _Lots_SL_TP_MagicNumber_Comment_OnlyOneOpenedPos_AutoDigits 均映射为 StockSharp 参数或内置功能。
  • MQL 中的订单关闭辅助函数被高层保护单逻辑所取代。
  • MQL 版本的错误重试循环在 StockSharp 中由订单生命周期管理自动处理,因此无需保留。
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;
	}
}