GitHub で見る

Vhf Sliding Windows戦略

概要

  • Vladimir KarputovによるMetaTrader 5エキスパートアドバイザー**「VHF EA」**から変換。
  • Vertical Horizontal Filter(VHF)インジケーターを使用して市場レジームをトレンドまたはレンジとして分類します。
  • StockSharpがサポートするあらゆるインストゥルメントと時間軸で動作します;ローソク足タイプパラメーターを変更して目的のチャートに合わせるだけです。

トレードロジック

  1. 選択したローソク足シリーズをサブスクライブし、各完成ローソク足で期間VhfPeriodのVHFインジケーターを計算します。
  2. 最近のVHF値の2つのスライディングウィンドウを維持します:
    • メインウィンドウ(MainWindowSize – 全体的なVHF範囲と中間点を確立します。
    • ワーキングウィンドウ(WorkingWindowSize – ローカルVHF中央値を上回るまたは下回る短期ブレイクを検出します。
  3. 強気または弱気のトレンドレジームは、現在のVHF値が両方のウィンドウの中間点より大きい場合のみ確認されます。
  4. トレンドレジーム中、最新の終値をMainWindowSizeバー前の終値と比較します:
    • 参照より高いクローズ → デフォルトの動作はロングポジションを開く/維持する。
    • 参照より低いクローズ → デフォルトの動作はショートポジションを開く/維持する。
    • これらの方向を反転するにはReverseSignalsを有効にします。
  5. VHF値がレンジゾーンに戻ると(現在のVHFが両方の中間点より上にない)、戦略はオープンポジションをクローズします。
  6. ポジションフリップは、反対側をクローズし、単一の市場注文で新しいポジションを開くのに十分なボリュームを買う/売ることで処理されます。

パラメーター

パラメーター 説明 デフォルト 備考
MainWindowSize プライマリスライディングウィンドウのVHF値の数。 11 WorkingWindowSizeより大きくなければなりません。
WorkingWindowSize セカンダリウィンドウのVHF値の数。 7 ブレイクアウトのより速い確認を提供します。
VhfPeriod Vertical Horizontal Filterのルックバック期間。 9 インジケーターの感度を決定します。
Volume 新規エントリーに使用する注文ボリューム(ロット)。 1 方向を反転する際に現在の絶対ポジションに追加されます。
ReverseSignals 価格方向から導出されたロング/ショートロジックを反転します。 true 元のEAのデフォルト動作と一致します。
CandleType データサブスクリプションの時間軸とローソク足タイプ。 15分足時間軸 他のチャートに戦略を適応させるために変更します。

資金管理とエグジット

  • 戦略は常にVolumeで定義された固定ボリュームを取引します。
  • 保護的なストップ管理はStockSharpの組み込みStartProtection()ヘルパーに委任され、予期しない残留ポジションを安全にクローズします。
  • ストップロスまたはテイクプロフィットのターゲットはコード化されていません;エグジットはVHFによって検出されたレジームの切り替えに依存します。

実装ノート

  • プロジェクトのガイドラインに従い、インジケーターバインディングを使用した高レベルローソク足サブスクリプションAPIを使用します。
  • MQLバージョンと同一のカスタムVertical Horizontal Filterインジケーターが戦略に組み込まれています。
  • ログステートメントは、デバッグを容易にするために各ポジション変更とレジーム遷移を記述します。
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;

public class VhfSlidingWindowsStrategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<int> _stopLossPoints;
	private readonly StrategyParam<int> _takeProfitPoints;

	private ExponentialMovingAverage _fast;
	private ExponentialMovingAverage _slow;

	private decimal _prevFast;
	private decimal _prevSlow;
	private decimal _entryPrice;
	private int _cooldown;

	public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
	public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
	public int StopLossPoints { get => _stopLossPoints.Value; set => _stopLossPoints.Value = value; }
	public int TakeProfitPoints { get => _takeProfitPoints.Value; set => _takeProfitPoints.Value = value; }

	public VhfSlidingWindowsStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 14).SetGreaterThanZero().SetDisplay("Fast Period", "Fast EMA period", "Indicator");
		_slowPeriod = Param(nameof(SlowPeriod), 50).SetGreaterThanZero().SetDisplay("Slow Period", "Slow EMA period", "Indicator");
		_stopLossPoints = Param(nameof(StopLossPoints), 200).SetNotNegative().SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");
		_takeProfitPoints = Param(nameof(TakeProfitPoints), 400).SetNotNegative().SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
	}

	protected override void OnReseted()
	{
		base.OnReseted();
		_fast = null; _slow = null;
		_prevFast = 0; _prevSlow = 0; _entryPrice = 0; _cooldown = 0;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);
		_fast = new ExponentialMovingAverage { Length = FastPeriod };
		_slow = new ExponentialMovingAverage { Length = SlowPeriod };
		var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
		subscription.Bind(_fast, _slow, ProcessCandle);
		subscription.Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
	{
		if (candle.State != CandleStates.Finished) return;
		if (!_fast.IsFormed || !_slow.IsFormed) { _prevFast = fastValue; _prevSlow = slowValue; return; }
		if (_cooldown > 0) { _cooldown--; _prevFast = fastValue; _prevSlow = slowValue; return; }

		var close = candle.ClosePrice;
		var step = Security?.PriceStep ?? 1m;

		if (Position > 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}
		else if (Position < 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}

		if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
		{ if (Position < 0) BuyMarket(); BuyMarket(); _entryPrice = close; _cooldown = 100; }
		else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
		{ if (Position > 0) SellMarket(); SellMarket(); _entryPrice = close; _cooldown = 100; }

		_prevFast = fastValue; _prevSlow = slowValue;
	}
}