在 GitHub 上查看

VR Setka P2 策略

该策略源自 MetaTrader 4 专家顾问 VR---SETKAp2,属于基于网格的交易方法。 当日收盘价相对于当天最高或最低偏离设定的百分比时触发交易。 当收盘价从日高下跌指定比例且前一根日线收阳时开多; 当收盘价从日低上涨指定比例且前一根日线收阴时开空。 持仓后在固定的获利距离平仓,并可选择使用简单的马丁格尔加仓方式。

参数

  • TakeProfit – 以价格步长表示的获利距离。
  • Lot – 每笔交易的基础数量。
  • Percent – 根据日内范围计算的百分比阈值。
  • UseMartingale – 在加仓时按马丁格尔方式增加数量。
  • Slippage – 下单允许的滑点。
  • Correlation – 计算网格水平时应用的偏移量。
  • Candle Type – 用于计算的K线周期,默认为日线。

逻辑

  1. 订阅日线K线。
  2. 对于每根完成的K线,计算收盘价相对于日高和日低的百分比偏离。
  3. 根据偏离程度和上一根K线的方向决定做多或做空。
  4. 达到设定的获利目标后平仓。

该示例展示了如何将经典的 MetaTrader 网格策略迁移到 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>
/// Grid based strategy using candle direction and EMA trend.
/// </summary>
public class VrSetkaP2Strategy : Strategy
{
	private readonly StrategyParam<int> _emaPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevOpen;
	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 VrSetkaP2Strategy()
	{
		_emaPeriod = Param(nameof(EmaPeriod), 20)
			.SetGreaterThanZero()
			.SetDisplay("EMA Period", "EMA trend period", "Indicators");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Timeframe for analysis", "General");
	}

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_prevOpen = 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)
		{
			_prevOpen = candle.OpenPrice;
			_prevClose = close;
			_hasPrev = true;
			return;
		}

		// Previous candle bullish + close above EMA => buy
		if (_prevClose > _prevOpen && close > emaValue && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		// Previous candle bearish + close below EMA => sell
		else if (_prevClose < _prevOpen && close < emaValue && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevOpen = candle.OpenPrice;
		_prevClose = close;
	}
}