GitHub で見る

Frank Udヘッジグリッド戦略

概要

Frank Udヘッジグリッド戦略はMetaTraderエキスパートアドバイザー「Frank Ud」をStockSharpの高レベルAPIに直接移植したものです。このボットは同一銘柄でロングとショートのバスケットを同時に保持し、アクティブなバスケットに対して価格がドリフトするたびにマーチンゲール方式の平均化を実行します。すべてのシグナル処理は最良のビッド/アスク(Level 1)の更新に基づいて行われ、低レイテンシー実行やティックバイティックのバックテストに適しています。

取引ロジック

  1. 初期ヘッジ – ポジションが開いていない場合、戦略は同じ量の買いと売りの成行注文を即座に開きます。各注文はpipで表されたストップロスとテイクプロフィットを受け取ります。
  2. ストップ/テイク管理 – 両方のバスケットが存在する間、その保護レベルが尊重されます。価格が保護レベルに達すると対応するバスケットが閉じられます。
  3. 片側管理 – 買いまたは売りのポジションのみが残ると、戦略は:
    • アクティブなバスケットの出来高加重平均エントリー価格を計算します。
    • 共通テイクプロフィットを平均価格 ± 設定距離に再割り当てします。
    • ストップロスを削除します(元のEAはこの時点からテイクプロフィットのみに依存します)。
  4. マーチンゲールステップ – 価格がアクティブなバスケットに対して設定ステップ以上動くと、戦略はマルチプライヤーを倍増させて新しい成行注文を開きます。ヘルパーメソッドAdjustVolumeは各注文を銘柄のボリュームステップ、最小値、最大値に合わせて維持します。
  5. サイクルリセット – すべてのバスケットが閉じられると、マルチプライヤーは1にリセットされ、新しいヘッジサイクルが始まります。

パラメーター

  • TakeProfitPips – バスケット平均価格と集合テイクプロフィット目標の間の距離(デフォルト:12 pip)。
  • StopLossPips – 最初のヘッジ注文のみに使用される保護ストップ距離(デフォルト:12 pip)。
  • StepPips – 次のマーチンゲール注文を追加する前に必要な逆方向の動き(デフォルト:16 pip)。
  • AutoLottrueの場合、戦略はLotSizeを使用します;それ以外は銘柄の最小ボリュームで取引します。
  • LotSizeAutoLotが有効な場合にマーチンゲールマルチプライヤーと共に使用されるカスタムベースロットサイズ。

実装上の注意

  • この変換は高レベルStrategy APIを使用:Level 1のサブスクリプションがロジックを駆動し、注文配置はBuyMarket/SellMarketヘルパーに依存します。
  • ポジション追跡は内部的:戦略は元のMetaTrader平均化ルールを再現できるよう、各バスケット注文のエントリー価格とボリュームを保存します。
  • マルチプライヤー(_multiplier)はEAのCoefficient変数を反映し、各追加注文後に倍増します。すべてのトレードが閉じられると1にリセットされます。
  • AdjustVolumeはMQL5のLotCheck関数をエミュレートし、要求されたボリュームを許可されたトレードステップとコントラクト制限に丸めます。
  • この戦略はソースEAと同様にロングとショートのバスケットを同時に保持するため、ヘッジング対応口座が必要です。

ファイル

  • CS/FrankUdStrategy.cs – 各ブロックを説明する英語のインラインコメント付きメイン戦略実装。
  • README.md – このドキュメント。
  • README_ru.md – ロシア語翻訳。
  • README_zh.md – 簡体字中国語翻訳。
using System;
using System.Linq;
using System.Collections.Generic;

using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;

using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Hedging grid strategy converted from the Frank Ud MetaTrader expert.
/// Opens a position and adds martingale entries when price moves against the trade.
/// Closes all on take profit from average price.
/// </summary>
public class FrankUdStrategy : Strategy
{
	private readonly StrategyParam<decimal> _takeProfit;
	private readonly StrategyParam<decimal> _stopLoss;
	private readonly StrategyParam<decimal> _stepDistance;
	private readonly StrategyParam<int> _maxEntries;
	private readonly StrategyParam<DataType> _candleType;

	private int _lastSignal;

	public decimal TakeProfit { get => _takeProfit.Value; set => _takeProfit.Value = value; }
	public decimal StopLoss { get => _stopLoss.Value; set => _stopLoss.Value = value; }
	public decimal StepDistance { get => _stepDistance.Value; set => _stepDistance.Value = value; }
	public int MaxEntries { get => _maxEntries.Value; set => _maxEntries.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public FrankUdStrategy()
	{
		_takeProfit = Param(nameof(TakeProfit), 5000m)
			.SetGreaterThanZero()
			.SetDisplay("Take Profit", "Take profit distance from avg price", "Risk");

		_stopLoss = Param(nameof(StopLoss), 5000m)
			.SetGreaterThanZero()
			.SetDisplay("Stop Loss", "Stop loss distance from avg price", "Risk");

		_stepDistance = Param(nameof(StepDistance), 300m)
			.SetGreaterThanZero()
			.SetDisplay("Step Distance", "Price distance for adding martingale entries", "Grid");

		_maxEntries = Param(nameof(MaxEntries), 1)
			.SetGreaterThanZero()
			.SetDisplay("Max Entries", "Maximum martingale entries", "Grid");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
			.SetDisplay("Candle Type", "Candle type for calculations", "General");
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_lastSignal = 0;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		SubscribeCandles(CandleType)
			.Bind(ProcessCandle)
			.Start();

		StartProtection(
			new Unit(TakeProfit, UnitTypes.Absolute),
			new Unit(StopLoss, UnitTypes.Absolute));
	}

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

		var bodySize = (candle.ClosePrice - candle.OpenPrice).Abs();
		if (bodySize < StepDistance)
			return;

		var direction = candle.ClosePrice > candle.OpenPrice ? 1 : -1;
		if (direction == _lastSignal)
			return;

		if (direction > 0 && Position <= 0)
		{
			BuyMarket();
			_lastSignal = 1;
		}
		else if (direction < 0 && Position >= 0)
		{
			SellMarket();
			_lastSignal = -1;
		}
	}
}