在 GitHub 上查看

VR MARS 策略

该示例演示如何将 MQL4 手动交易面板 VR---MARS-EN 简化移植到 StockSharp。

原始脚本提供五个预设手数以及用于立即买入或卖出的按钮,同时显示各种交易信息。在此 C# 版本中,视觉面板被移除,但保留了从五个手数中选择并执行市价单的核心思想。

参数

  • Lot1 – 第一手的大小。
  • Lot2 – 第二手的大小。
  • Lot3 – 第三手的大小。
  • Lot4 – 第四手的大小。
  • Lot5 – 第五手的大小。
  • SelectedLot – 1 到 5 之间的数字,指定使用哪个手数。
  • Buy – 当为 true 时,在策略启动时发送买入市价单。
  • Sell – 当为 true 时,在策略启动时发送卖出市价单。

两个方向标志应只启用一个。策略启动后会开启仓位保护,并使用高级辅助方法发送相应的市价单。

说明

此策略仅用于学习目的,不包含任何额外的交易逻辑。

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;

/// <summary>
/// VR MARS strategy using EMA crossover with volume lots.
/// </summary>
public class VRMarsStrategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevFast;
	private decimal _prevSlow;
	private bool _hasPrev;

	public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
	public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public VRMarsStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 5)
			.SetGreaterThanZero()
			.SetDisplay("Fast EMA", "Fast EMA period", "Indicators");
		_slowPeriod = Param(nameof(SlowPeriod), 20)
			.SetGreaterThanZero()
			.SetDisplay("Slow EMA", "Slow EMA period", "Indicators");
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles", "General");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
		=> [(Security, CandleType)];

	protected override void OnReseted()
	{
		base.OnReseted();
		_prevFast = 0; _prevSlow = 0; _hasPrev = false;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var fast = new ExponentialMovingAverage { Length = FastPeriod };
		var slow = new ExponentialMovingAverage { Length = SlowPeriod };

		SubscribeCandles(CandleType).Bind(fast, slow, ProcessCandle).Start();
	}

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

		if (!_hasPrev) { _prevFast = fast; _prevSlow = slow; _hasPrev = true; return; }

		if (_prevFast <= _prevSlow && fast > slow)
		{
			if (Position < 0) BuyMarket();
			if (Position <= 0) BuyMarket();
		}
		else if (_prevFast >= _prevSlow && fast < slow)
		{
			if (Position > 0) SellMarket();
			if (Position >= 0) SellMarket();
		}

		_prevFast = fast; _prevSlow = slow;
	}
}