在 GitHub 上查看

三层网格策略

该策略实现一个对称的网格交易系统,可设置多达三层获利等级。 在当前价格上下按照固定间距挂出限价单,当入场单成交后,会在 预设的获利价格挂出反向限价单以锁定利润。策略适用于价格在区间 内震荡的市场环境。

参数

  • Grid Size – 相邻网格之间的价格间距。
  • Levels – 每一侧的网格层数。
  • Base Take Profit – 第一获利等级的基础利润距离。
  • Order Volume – 每个网格订单的数量。
  • Enable Rank1 – 启用基础获利等级。
  • Enable Rank2 – 启用基础加一倍网格间距的获利等级。
  • Enable Rank3 – 启用基础加两倍网格间距的获利等级。
  • Allow Longs – 允许做多一侧的网格。
  • Allow Shorts – 允许做空一侧的网格。
  • Candle Type – 用于确定初始参考价格的蜡烛类型。

交易逻辑

  1. 策略启动后订阅蜡烛并等待第一根完成的蜡烛。
  2. 使用该蜡烛的收盘价构建具有指定层数的网格。
  3. 根据允许的方向在各层挂出买入和/或卖出限价单。
  4. 入场单成交后,根据选择的获利等级计算价格并挂出反向限价单。
  5. 订单保持在市场中直至成交或被人工取消。

该实现是对原始 MQL 网格系统的简化转换,展示了在 StockSharp 高层 API 中实现核心机制的方法。

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>
/// Three-level grid strategy using EMA as center line.
/// Buys on dips below EMA at different levels, sells on rises above EMA.
/// </summary>
public class ThreeLevelGridStrategy : Strategy
{
	private readonly StrategyParam<int> _emaLength;
	private readonly StrategyParam<DataType> _candleType;

	public int EmaLength { get => _emaLength.Value; set => _emaLength.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public ThreeLevelGridStrategy()
	{
		_emaLength = Param(nameof(EmaLength), 30)
			.SetGreaterThanZero()
			.SetDisplay("EMA Length", "EMA period for center line", "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 OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var ema = new ExponentialMovingAverage { Length = EmaLength };
		var atr = new StandardDeviation { Length = 14 };

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

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

		if (atrVal <= 0)
			return;

		var close = candle.ClosePrice;
		var diff = close - emaVal;

		// Buy at different grid levels below EMA
		if (diff < -1.5m * atrVal && Position <= 0)
		{
			if (Position < 0)
				BuyMarket();
			BuyMarket();
		}
		// Sell at different grid levels above EMA
		else if (diff > 1.5m * atrVal && Position >= 0)
		{
			if (Position > 0)
				SellMarket();
			SellMarket();
		}
		// Mean reversion exit
		else if (Position > 0 && close > emaVal + 0.5m * atrVal)
		{
			SellMarket();
		}
		else if (Position < 0 && close < emaVal - 0.5m * atrVal)
		{
			BuyMarket();
		}
	}
}