GitHub で見る

フランク・ウッド ミニマル戦略

このサンプルは、高レベルの戦略 API を使用して、古典的な Frank Ud MetaTrader エキスパート アドバイザーを StockSharp に移植します。元の MQL スクリプトは、最新のエントリーに対して価格が変動するたびにポジションを追加し続けるヘッジ マーチンゲール グリッドを実行します。最新の (したがって最大の) 注文が一定数の pips を獲得すると、利益がロックされ、その後、その側の すべての 取引が同時にクローズされます。

コアロジック

  1. 対称ヘッジ この戦略は、市場ポジションの 2 つの独立したはしご (長いはしごと短いはしご) を維持します。したがって、MetaTrader のヘッジ モードのように、ロングとショートを同時に保持することが可能です。
  2. Martingale の進行。 いずれかのサイドの最初のオーダーでは、InitialVolume (デフォルトは 0.1 ロット) が使用されます。同じ側​​の後続の各エントリは、現在開いている最大ボリュームを 2 倍にします。音量調整は、楽器の MinVolumeMaxVolume、および VolumeStep の制約を考慮します。
  3. エントリー間隔 新しいポジションは、価格が既存のラダーの最良エントリー価格を少なくとも ReEntryPips (デフォルトは 41 ピップス) 超えた場合にのみ追加されます。長いはしごは売値が lowest_buy - ReEntryPips を下回るのを待ち、短いはしごは買値が highest_sell + ReEntryPips を超えるまで待ちます。
  4. 利益の収穫。 各ラダーで、最大量の取引が「トリガー」注文として機能します。利益が TakeProfitPips (デフォルトは 65 ピップス) を超える場合、または価格が MQL バージョンで使用される暗黙的なテイクプロフィットレベル (TakeProfitPips + 25) に達すると、その側のすべてのポジションが 1 つの成行注文でフラット化されます。
  5. Margin protection. Before submitting any new entry the strategy verifies that the free margin reported by the portfolio (CurrentValue - BlockedValue) stays above Balance × MinimumFreeMarginRatio (default 0.5).ブローカーがポートフォリオ統計を報告しない場合、チェックは元のエキスパートの固定量の動作に戻ります。

パラメーター

パラメータ 説明
TakeProfitPips 最新の最大注文で測定されたピップ利益のしきい値。それを超えると、その側のすべてのポジションがクローズされます。
ReEntryPips 新しいマーチンゲール注文が追加される前の、既存の最良のエントリーと現在の買値/買値の間の最小ピップ距離。
InitialVolume 各ラダーの最初の注文の基本ロット サイズ。後続の注文では、最大アクティブ量が 2 倍になります。
MinimumFreeMarginRatio 新規エントリーが許可される前に必要な残高に対する自由証拠金の比率。チェックを無効にするには、0 に設定します。

実装メモ

  • この戦略はレベル 1 の相場のみに依存します。入札の更新は短いラダー ロジックを駆動し、売りの更新は長いラダー ロジックを駆動します。
  • 注文インテントは内部辞書で追跡されるため、OnNewMyTrade は約定によってラダーが開かれたのか閉じられたのかを知ることができます。これは、MQL ソースの明示的なチケット簿記を模倣しています。
  • ポジション ブックキーピングは、累積統計をクエリする代わりに、すべての約定 (価格と出来高) をリストに保存し、最大ロットとそのエントリー価格を見つけるために使用された MQL 配列の動作を保持します。
  • 元のエキスパートが各テイクプロフィット注文に設定した追加の 25 ピップ バッファーは、追加の終了条件として保持されます。

注意: 要求に応じて、現時点では Python ポートは意図的に省略されています。このフォルダーには、C# 実装と多言語ドキュメントのみが含まれています。

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>
/// Minimal port of the Frank Ud averaging expert from MetaTrader.
/// The strategy opens hedged martingale grids and liquidates both sides
/// once the newest position reaches the configured profit in pips.
/// </summary>
public class FrankUdMinimalStrategy : Strategy
{
	private readonly StrategyParam<decimal> _takeProfitPips;
	private readonly StrategyParam<decimal> _reEntryPips;
	private readonly StrategyParam<decimal> _initialVolume;
	private readonly StrategyParam<decimal> _minimumFreeMarginRatio;
	private readonly StrategyParam<decimal> _extraTakeProfitPips;

	private readonly List<PositionEntry> _longEntries = new();
	private readonly List<PositionEntry> _shortEntries = new();
	private readonly Dictionary<long, OrderActions> _orderActions = new();

	private decimal _pointValue;
	private decimal _takeProfitThreshold;
	private decimal _takeProfitDistance;
	private decimal _reEntryDistance;
	private decimal _baseVolume;
	private decimal _lastBid;
	private decimal _lastAsk;

	/// <summary>
	/// Creates a new instance of <see cref="FrankUdMinimalStrategy"/> with default parameters.
	/// </summary>
	public FrankUdMinimalStrategy()
	{
		_takeProfitPips = Param(nameof(TakeProfitPips), 65m)
		.SetDisplay("Profit trigger (pips)", "Pip profit that forces an exit of all positions.", "Risk")
		.SetGreaterThanZero();

		_reEntryPips = Param(nameof(ReEntryPips), 41m)
		.SetDisplay("Re-entry distance (pips)", "Pip distance required before adding the next grid order.", "Grid")
		.SetGreaterThanZero();

		_initialVolume = Param(nameof(InitialVolume), 0.1m)
		.SetDisplay("Initial volume", "Base lot used for the very first order.", "Risk")
		.SetGreaterThanZero();

		_minimumFreeMarginRatio = Param(nameof(MinimumFreeMarginRatio), 0.5m)
		.SetDisplay("Free margin ratio", "Free margin must stay above Balance × Ratio before adding orders.", "Risk")
		.SetGreaterThanZero();

		_extraTakeProfitPips = Param(nameof(ExtraTakeProfitPips), 25m)
		.SetDisplay("Buffer profit (pips)", "Additional pip distance applied when calculating buffered targets.", "Risk")
		.SetNotNegative();
}

	/// <summary>
	/// Profit threshold expressed in pips.
	/// </summary>
	public decimal TakeProfitPips
	{
		get => _takeProfitPips.Value;
		set => _takeProfitPips.Value = value;
	}

	/// <summary>
	/// Distance in pips between consecutive martingale entries.
	/// </summary>
	public decimal ReEntryPips
	{
		get => _reEntryPips.Value;
		set => _reEntryPips.Value = value;
	}

	/// <summary>
	/// Base lot volume for the very first order.
	/// </summary>
	public decimal InitialVolume
	{
		get => _initialVolume.Value;
		set => _initialVolume.Value = value;
	}

	/// <summary>
	/// Minimal free margin ratio required to send new orders.
	/// </summary>
	public decimal MinimumFreeMarginRatio
{
		get => _minimumFreeMarginRatio.Value;
		set => _minimumFreeMarginRatio.Value = value;
}

	/// <summary>
	/// Additional pip buffer added to the take-profit distance.
	/// </summary>
	public decimal ExtraTakeProfitPips
	{
		get => _extraTakeProfitPips.Value;
		set => _extraTakeProfitPips.Value = value;
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();

		_longEntries.Clear();
		_shortEntries.Clear();
		_orderActions.Clear();

		_pointValue = 0m;
		_takeProfitThreshold = 0m;
		_takeProfitDistance = 0m;
		_reEntryDistance = 0m;
		_baseVolume = 0m;
		_lastBid = 0m;
		_lastAsk = 0m;
	}

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

		var security = Security ?? throw new InvalidOperationException("Security is not assigned.");
		var priceStep = security.PriceStep ?? 0.01m;

		_pointValue = priceStep;
		_takeProfitThreshold = TakeProfitPips;
		_takeProfitDistance = (TakeProfitPips + ExtraTakeProfitPips) * _pointValue;
		_reEntryDistance = ReEntryPips * _pointValue;
		_baseVolume = AdjustVolume(InitialVolume);

		var l1sub = new Subscription(DataType.Level1, Security);
		l1sub.MarketData.BuildField = Level1Fields.BestBidPrice;
		SubscribeLevel1(l1sub)
		.Bind(ProcessLevel1)
		.Start();
	}

	private void ProcessLevel1(Level1ChangeMessage message)
	{
		if (message.Changes.TryGetValue(Level1Fields.BestBidPrice, out var bidPrice))
		_lastBid = (decimal)bidPrice;

		if (message.Changes.TryGetValue(Level1Fields.BestAskPrice, out var askPrice))
		_lastAsk = (decimal)askPrice;

		if (_lastBid <= 0m || _lastAsk <= 0m)
		return;

		if (ShouldCloseLong())
		CloseLongPositions();

		if (ShouldCloseShort())
		CloseShortPositions();

		if (ShouldOpenLong())
		OpenLongPosition();

		if (ShouldOpenShort())
		OpenShortPosition();
	}

	private bool ShouldCloseLong()
	{
		if (_longEntries.Count == 0)
		return false;

		var entry = GetMaxVolumeEntry(_longEntries);
		if (entry == null)
		return false;

		var profitPips = (_lastBid - entry.Price) / _pointValue;
		var bufferedTarget = entry.Price + _takeProfitDistance;
		var reachedBufferedTarget = _takeProfitDistance > 0m && _lastBid >= bufferedTarget;

		return profitPips > _takeProfitThreshold || reachedBufferedTarget;
	}

	private bool ShouldCloseShort()
	{
		if (_shortEntries.Count == 0)
		return false;

		var entry = GetMaxVolumeEntry(_shortEntries);
		if (entry == null)
		return false;

		var profitPips = (entry.Price - _lastAsk) / _pointValue;
		var bufferedTarget = entry.Price - _takeProfitDistance;
		var reachedBufferedTarget = _takeProfitDistance > 0m && _lastAsk <= bufferedTarget;

		return profitPips > _takeProfitThreshold || reachedBufferedTarget;
	}

	private bool ShouldOpenLong()
	{
		if (_baseVolume <= 0m)
		return false;

		if (!HasEnoughMargin())
		return false;

		if (_longEntries.Count == 0)
		return true;

		var lowestPrice = GetExtremePrice(_longEntries, true);
		return lowestPrice - _reEntryDistance > _lastAsk;
	}

	private bool ShouldOpenShort()
	{
		if (_baseVolume <= 0m)
		return false;

		if (!HasEnoughMargin())
		return false;

		if (_shortEntries.Count == 0)
		return true;

		var highestPrice = GetExtremePrice(_shortEntries, false);
		return highestPrice + _reEntryDistance < _lastBid;
	}

	private void OpenLongPosition()
	{
		var volume = DetermineNextVolume(_longEntries);
		if (volume <= 0m)
		return;

		var order = BuyMarket(volume);
		RegisterOrder(order, OrderActions.OpenLong);
	}

	private void OpenShortPosition()
	{
		var volume = DetermineNextVolume(_shortEntries);
		if (volume <= 0m)
		return;

		var order = SellMarket(volume);
		RegisterOrder(order, OrderActions.OpenShort);
	}

	private void CloseLongPositions()
	{
		var volume = GetTotalVolume(_longEntries);
		if (volume <= 0m)
		return;

		var order = SellMarket(volume);
		RegisterOrder(order, OrderActions.CloseLong);
	}

	private void CloseShortPositions()
	{
		var volume = GetTotalVolume(_shortEntries);
		if (volume <= 0m)
		return;

		var order = BuyMarket(volume);
		RegisterOrder(order, OrderActions.CloseShort);
	}

	private void RegisterOrder(Order order, OrderActions action)
	{
		if (order == null)
		return;

		if (order.Id is long id)
			_orderActions[id] = action;
	}

	/// <inheritdoc />
	protected override void OnOwnTradeReceived(MyTrade trade)
	{
		base.OnOwnTradeReceived(trade);

		if (trade.Order.Id is not long tradeOrderId || !_orderActions.TryGetValue(tradeOrderId, out var action))
		return;

		var price = trade.Trade.Price;
		var volume = trade.Trade.Volume;

		switch (action)
		{
			case OrderActions.OpenLong:
			AddEntry(_longEntries, price, volume);
			break;

			case OrderActions.OpenShort:
			AddEntry(_shortEntries, price, volume);
			break;

			case OrderActions.CloseLong:
			RemoveVolume(_longEntries, volume);
			break;

			case OrderActions.CloseShort:
			RemoveVolume(_shortEntries, volume);
			break;
		}
	}

	/// <inheritdoc />
	protected override void OnOrderReceived(Order order)
	{
		base.OnOrderReceived(order);

		if (order.Id is long oid && order.State is OrderStates.Done or OrderStates.Failed)
		_orderActions.Remove(oid);
	}

	/// <inheritdoc />
	protected override void OnOrderRegisterFailed(OrderFail fail, bool calcRisk)
	{
		base.OnOrderRegisterFailed(fail, calcRisk);

		if (fail.Order.Id is long foid)
			_orderActions.Remove(foid);
	}

	private decimal DetermineNextVolume(List<PositionEntry> entries)
	{
		if (_baseVolume <= 0m)
		return 0m;

		var volume = entries.Count == 0
		? _baseVolume
		: GetMaxVolume(entries) * 2m;

		return AdjustVolume(volume);
	}

	private decimal AdjustVolume(decimal volume)
	{
		if (volume <= 0m)
		return 0m;

		var security = Security;

		if (security?.VolumeStep is decimal step && step > 0m)
		{
			var steps = Math.Floor(volume / step);
			volume = steps * step;
		}

		if (security?.MinVolume is decimal min && min > 0m && volume < min)
		volume = min;

		if (security?.MaxVolume is decimal max && max > 0m && volume > max)
		volume = max;

		return volume;
	}

	private bool HasEnoughMargin()
	{
		if (MinimumFreeMarginRatio <= 0m)
		return true;

		var portfolio = Portfolio;
		if (portfolio == null)
		return true;

		var balance = portfolio.CurrentValue ?? portfolio.BeginValue ?? 0m;
		if (balance <= 0m)
		return true;

		var blocked = portfolio.Commission ?? 0m;
		var baseValue = portfolio.CurrentValue ?? portfolio.BeginValue;
		if (baseValue == null)
		return true;

		var freeMargin = baseValue.Value - blocked;
		return freeMargin > balance * MinimumFreeMarginRatio;
	}

	private static void AddEntry(List<PositionEntry> entries, decimal price, decimal volume)
	{
		if (volume <= 0m)
		return;

		entries.Add(new PositionEntry(price, volume));
	}

	private static void RemoveVolume(List<PositionEntry> entries, decimal volume)
	{
		var remaining = volume;

		for (var i = entries.Count - 1; i >= 0 && remaining > 0m; i--)
		{
			var entry = entries[i];

			if (entry.Volume <= remaining)
			{
				remaining -= entry.Volume;
				entries.RemoveAt(i);
			}
			else
			{
				entries[i] = entry.WithVolume(entry.Volume - remaining);
				remaining = 0m;
			}
		}
	}

	private static decimal GetTotalVolume(List<PositionEntry> entries)
	{
		decimal total = 0m;

		foreach (var entry in entries)
		total += entry.Volume;

		return total;
	}

	private static PositionEntry GetMaxVolumeEntry(List<PositionEntry> entries)
	{
		PositionEntry result = null;
		decimal maxVolume = 0m;

		foreach (var entry in entries)
		{
			if (entry.Volume > maxVolume)
			{
				maxVolume = entry.Volume;
				result = entry;
			}
		}

		return result;
	}

	private static decimal GetMaxVolume(List<PositionEntry> entries)
	{
		decimal maxVolume = 0m;

		foreach (var entry in entries)
		if (entry.Volume > maxVolume)
		maxVolume = entry.Volume;

		return maxVolume;
	}

	private static decimal GetExtremePrice(List<PositionEntry> entries, bool isLong)
	{
		var hasValue = false;
		decimal result = 0m;

		foreach (var entry in entries)
		{
			var price = entry.Price;

			if (!hasValue)
			{
				result = price;
				hasValue = true;
				continue;
			}

			if (isLong)
			{
				if (price < result)
				result = price;
			}
			else if (price > result)
			{
				result = price;
			}
		}

		return result;
	}

	private sealed class PositionEntry
	{
		public PositionEntry(decimal price, decimal volume)
		{
			Price = price;
			Volume = volume;
		}

		public decimal Price { get; }

		public decimal Volume { get; }

		public PositionEntry WithVolume(decimal volume)
		{
			return new PositionEntry(Price, volume);
		}
	}

	private enum OrderActions
	{
		OpenLong,
		CloseLong,
		OpenShort,
		CloseShort
	}
}