GitHub で見る

VR Setka グリッド戦略

この戦略は、MetaTrader の「VR---SETKAa3hM」グリッドシステムの StockSharp 実装です。日次レンジからのパーセンテージ偏差に基づいて買いまたは売り注文のシーケンスを開き、オプションでマルチンゲール乗数を使用してボリュームを増やします。すべての未決注文の平均エントリー価格を追跡し、統一されたテイクプロフィット目標を設定します。

パラメーター

  • Distance: グリッドレベル間の価格距離(ポイント)。
  • TakeProfit: 最初の注文の利益目標(ポイント)。
  • Correction: 複数の注文が開いているときに平均価格に追加される追加利益(ポイント)。
  • SignalPercent: 日次レンジからの偏差を検出するために使用されるパーセンテージ閾値。
  • UseMartingale: 開いている注文数でボリュームを乗算する。
  • CandleType: シグナル計算に使用するローソク足の時間軸。

ロジック

  1. 完成したローソク足が現れたとき、当日の高値・安値に対する現在の終値が計算されます。
  2. 前のローソク足が強気で、終値が当日高値を十分に下回っている場合、買いグリッドを開始または継続します。
  3. 前のローソク足が弱気で、終値が当日安値を十分に上回っている場合、売りグリッドを開始または継続します。
  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;
	}
}