在 GitHub 上查看

VR Setka 网格策略

该策略在 StockSharp 中重现了 MetaTrader 4 的 "VR---SETKAa3hM" 网格系统。根据价格相对于当日高低点的百分比偏离来开启买入或卖出订单,可选地使用马丁加仓算法增加每笔订单的数量。策略跟踪所有订单的平均入场价,并在其基础上设置统一的止盈目标。

参数

  • Distance: 网格层之间的点数距离。
  • TakeProfit: 第一个订单的止盈目标点数。
  • Correction: 当存在多单时加到平均价格上的额外点数。
  • SignalPercent: 用于判断价格偏离日内区间的百分比阈值。
  • UseMartingale: 是否按马丁公式增加下单量。
  • CandleType: 用于计算信号的K线周期。

逻辑

  1. 每当一根K线收盘后,计算收盘价相对于当日最高和最低价的位置。
  2. 如果前一根K线为阳线且收盘价位于日高附近,则开启或加仓买入网格。
  3. 如果前一根K线为阴线且收盘价位于日低附近,则开启或加仓卖出网格。
  4. 每当价格逆势运行 Distance 点时加开一个订单。
  5. 当价格回到平均入场价并加上 Correction(买单)或减去 Correction(卖单)时,使用市价单全部平仓。
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>
/// EMA trend + candle direction strategy (converted from grid).
/// </summary>
public class VrSetkaGridStrategy : Strategy
{
	private readonly StrategyParam<int> _emaPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevEma;
	private decimal _prevClose;
	private bool _hasPrev;

	public int EmaPeriod { get => _emaPeriod.Value; set => _emaPeriod.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public VrSetkaGridStrategy()
	{
		_emaPeriod = Param(nameof(EmaPeriod), 20)
			.SetGreaterThanZero()
			.SetDisplay("EMA Period", "EMA period for trend", "Indicators");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Base candle series", "General");
	}

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_prevEma = 0;
		_prevClose = 0;
		_hasPrev = false;
	}

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

		var ema = new ExponentialMovingAverage { Length = EmaPeriod };

		SubscribeCandles(CandleType)
			.Bind(ema, ProcessCandle)
			.Start();
	}

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

		var close = candle.ClosePrice;

		if (!_hasPrev)
		{
			_prevEma = emaValue;
			_prevClose = close;
			_hasPrev = true;
			return;
		}

		var crossUp = _prevClose <= _prevEma && close > emaValue;
		var crossDown = _prevClose >= _prevEma && close < emaValue;

		if (crossUp && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		else if (crossDown && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevEma = emaValue;
		_prevClose = close;
	}
}