GitHub で見る

VR Setka P2 戦略

この戦略はMetaTrader 4のエキスパートVR---SETKAp2から移植されたグリッドベースのアプローチです。 日次クローズが日高または日安から一定の割合で乖離したときに取引します。 日高からの大幅な下落後にロングポジションを開き、 日安からの大幅な上昇後にショートポジションを開きます。ポジション保有後は固定のテイクプロフィット距離で決済します。ボリュームはオプションでシンプルなMartingaleスキームを使用して増やすことができます。

パラメーター

  • TakeProfit – 価格ステップ単位の利益目標までの距離。
  • Lot – 各取引の基本ボリューム。
  • Percent – 日次レンジから計算されるパーセンテージ閾値。
  • UseMartingale – 損失ポジションに追加する際のボリューム増加を有効にする。
  • Slippage – 注文の許容価格スリッページ。
  • Correlation – グリッドレベル計算時に適用されるオフセット。
  • Candle Type – 計算に使用する時間軸(デフォルトは日足)。

ロジック

  1. 日次ローソク足を購読する。
  2. 各完成ローソク足について、日高・日安からのパーセント乖離を計算する。
  3. 乖離と前のローソク足の方向に応じてロングまたはショートでエントリーする。
  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;
	}
}