在 GitHub 上查看

循环市价单策略

该策略由 MetaTrader 4 专家顾问“CycleMarketOrder_V181”转换而来。策略在价格梯度中维护固定数量的交易槽位,当实时买卖价进入槽位区间时立刻提交市价单。每个槽位都有自己的下单量、保本触发距离和追踪止损价,因此网格能够逐步扩大仓位,同时保护已经达到目标利润的仓位。

交易逻辑

  1. 先根据品种的最小报价步长和小数位数确定每个点(pip)的真实价格,针对 5/3 位报价的品种会自动换算成 10 个最小跳动点。随后通过 MaxPriceSpanPipsMaxCount 计算出每个槽位覆盖的价格区间。
  2. 策略订阅 Level-1 行情以复刻原始 EA 的逐笔逻辑,每次更新都会刷新缓存的买价和卖价。
  3. 启用 UseWeekendMode 时,策略会在周末窗口内完全停止操作:周六从 WeekendHour 开始、整个周日以及周一 WeekstartHour 之前均不进行交易。
  4. EntryDirection = 1(多头循环)时,算法从编号最小的槽位开始扫描。一旦卖价位于槽位的 startPriceendPrice 之间,就会按照 OrderVolume 下达市价买单;当 EntryDirection = -1 时使用买价执行对称的空头逻辑。
  5. 槽位状态跟踪挂单、未平仓量以及平均开仓价,同时使用 MagicNumberBase + index 作为日志标识,与 MT4 的 magic number 对应。
  6. 追踪止损在每次 Level-1 更新时执行,并在开新仓之前运行。多头槽位的浮盈超过 BreakEvenPips + TrailingStopPips 后,止损会被移动到 Bid - TrailingStopPips;空头槽位使用 Ask + TrailingStopPips 并采用镜像的保本条件。当市场价格触发该止损时,槽位会通过市价单平仓。
  7. 策略只发送市价单,不存在需要删除的挂单。若出现部分成交,剩余仓位会重新记录,追踪管理会继续,完全平仓后槽位即可重新等待下一次触发。

参数

参数 说明
EntryDirection 交易方向:1 只做多,-1 只做空,0 仅保留追踪而不再开新仓。
MaxPrice 构建价格网格时使用的上沿价格。
MaxCount 网格中启用的槽位数量。
SpanPips 相邻槽位之间的间距(以点 pip 表示)。
OrderVolume 槽位被触发时提交的下单量。
BreakEvenPips 达到该利润距离后才会启动追踪止损。
TrailingStopPips 达到保本条件后使用的追踪距离。
UseWeekendMode 是否启用周末停盘保护。
WeekendHour 周六(终端时间)开始停盘的小时数。
WeekstartHour 周一恢复交易的小时数。
MagicNumberBase 日志中使用的标识偏移量,与原 EA 的 magic number 对齐。

实现说明

  • 槽位管理会记录所有待成交的开仓与平仓指令,防止重复统计成交量。
  • 只要有新增成交导致持仓增加,追踪止损就会被重置,确保其基于最新的平均开仓价。
  • 周末保护仅仅跳过追踪和开仓逻辑,已有仓位保持不变,待时间窗口结束后继续处理。
  • 由于逻辑直接比较买卖价而不是蜡烛收盘价,因此必须订阅 Level-1 行情,才能贴近 MT4 版本的逐笔行为。
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 CycleMarketOrderStrategy : 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 CycleMarketOrderStrategy()
	{
		_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;
	}
}