在 GitHub 上查看

Line Order Single Entry 策略

Line Order 策略是 MQL4 脚本“LineOrder”(10715) 的移植版本。策略在市场价格达到预设的进场线时开仓,并通过止损、止盈以及可选的移动止损来管理仓位。

参数

  • Entry Price – 触发开仓的价格。
  • Stop Loss (pips) – 从进场价到初始止损的距离。
  • Take Profit (pips) – 从进场价到止盈的距离。
  • Trailing Stop (pips) – 移动止损距离,0 表示关闭。
  • Candle Type – 用于计算的 K 线类型。

交易逻辑

  1. 策略订阅选定类型的 K 线。
  2. 完成的 K 线收盘价高于进场价时做多,低于进场价时做空。
  3. 进场后根据品种的价格步长计算止损和止盈。
  4. 如果启用移动止损,则止损价随行情向盈利方向移动。
  5. 当价格触及止损或止盈时平仓。

该实现是原始 MQL 脚本的简化版本,用于在用户定义的价格线自动执行订单。

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>
/// Line order strategy that enters when price crosses a predefined level.
/// Uses SMA as the dynamic entry line.
/// </summary>
public class LineOrderSingleEntryStrategy : Strategy
{
	private readonly StrategyParam<int> _smaLength;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevClose;
	private decimal _prevSma;
	private bool _hasPrev;

	public int SmaLength { get => _smaLength.Value; set => _smaLength.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public LineOrderSingleEntryStrategy()
	{
		_smaLength = Param(nameof(SmaLength), 20)
			.SetGreaterThanZero()
			.SetDisplay("SMA Length", "Moving average period", "Parameters");

		_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();
		_prevClose = 0;
		_prevSma = 0;
		_hasPrev = false;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var sma = new SimpleMovingAverage { Length = SmaLength };

		var subscription = SubscribeCandles(CandleType);
		subscription.Bind(sma, ProcessCandle).Start();
	}

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

		var close = candle.ClosePrice;

		if (_hasPrev)
		{
			// Cross above SMA
			if (_prevClose <= _prevSma && close > smaValue && Position <= 0)
			{
				BuyMarket();
			}
			// Cross below SMA
			else if (_prevClose >= _prevSma && close < smaValue && Position >= 0)
			{
				SellMarket();
			}
		}

		_prevClose = close;
		_prevSma = smaValue;
		_hasPrev = true;
	}
}