GitHub で見る

OCO 保留注文戦略

概要

OCO 保留注文戦略は、StockSharpのハイレベルAPI内でMetaTrader4エキスパートアドバイザーOCO_EA.mq4の動作を再現します。このアルゴリズムにより、トレーダーは最大4つの独立した価格トリガー(buy limit、buy stop、sell limit、sell stop)を設定できます。ライブの最良の買値または売値が設定した価格レベルに触れると、戦略は即座にマーケット注文を送信し、古典的な「一つが成立したら残りをキャンセル」(OCO)方式でオプションで他のすべての保留トリガーをキャンセルします。

戦略は純粋にレベル1市場データに依存しており、履歴インジケーターは必要ありません。トレーダーが手動で価格レベルを定義し、レベルに達したら即座にプラットフォームが執行し、保護的な退出注文も添付することを望む裁量的または半自動化された取引ワークフロー向けです。

取引ロジック

  1. トレーダーは4つのトリガー価格の任意の組み合わせを設定し、Armedパラメーターをtrueに切り替えます。
  2. 戦略はレベル1の更新を購読し、最新の最良買値と売値をメモリに保持します。
  3. 各更新で保存された価格を設定されたしきい値と比較します:
    • 最良の売値がBuy limit価格以下の場合、設定されたボリュームでマーケット買い注文が送信されます。
    • 最良の売値がBuy stop価格以上の場合、マーケット買い注文が送信されます。
    • 最良の買値がSell limit価格以上の場合、マーケット売り注文が送信されます。
    • 最良の買値がSell stop価格以下の場合、マーケット売り注文が送信されます。
  4. 各トリガー実行後、対応するレベルはクリアされます(ゼロに戻されます)。Use OCO linkが有効の場合、他のすべてのレベルが即座にクリアされ、元のMT4の動作を反映します。OCOリンクが無効の場合、他のレベルはトリガーするか手動でクリアされるまでアクティブのままです。
  5. すべてのトリガー価格がゼロの場合、戦略はArmedをfalseに戻して自動的に解除します。

すべての実行はStockSharp環境で設定された取引所ルーティングを尊重する即座の注文フィルを確保するためにBuyMarketとSellMarket呼び出しで行われます。監視を簡単にするために各トリガーの情報ログエントリが作成されます。

パラメーター

  • Order volume – 各マーケット注文で送信されるボリューム。値は正でなければなりません。
  • Buy limit price – 制限スタイルのロングエントリーを起動する売値しきい値。0に設定すると無効。
  • Buy stop price – ストップスタイルのロングエントリーを起動する売値しきい値。0に設定すると無効。
  • Sell limit price – 制限スタイルのショートエントリーを起動する買値しきい値。0に設定すると無効。
  • Sell stop price – ストップスタイルのショートエントリーを起動する買値しきい値。0に設定すると無効。
  • Stop loss (pips) – 保護ストップのインストゥルメントポイント単位の距離。Security.PriceStepを掛けて価格に変換されます(インストゥルメントがティックサイズを報告しない場合はフォールバック1)。
  • Take profit (pips) – 利益目標のインストゥルメントポイント単位の距離。ストップロスと同じ変換ロジックが使用されます。
  • Use OCO link – trueの場合、最初に約定した注文が残りの価格レベルをクリアして戦略を解除します。falseの場合、残りのレベルは個別にトリガーされるまでアクティブのままです。
  • Armed – 取引ロジックを有効/無効にする安全スイッチ。アクティブなトリガーレベルが残っていない場合、戦略は自動的にfalseにリセットします。

リスク管理

StartProtectionはOnStarted中に有効化され、各オープンポジションに絶対価格ストップロスとテイクプロフィットオフセットを添付します。オフセットはインストゥルメントのティックサイズを使用して**Stop loss (pips)とTake profit (pips)**パラメーターから導出されます。保護注文は、基礎となるインストゥルメントが流動性が低い場合でも退出執行を保証するために常にマーケット注文として送信されます。

戦略は純粋にイベント駆動型であるため、取引所に保留リミット注文を維持しません。市場データに反応してマーケット注文を送信します。これは即座の注文を発行してからストップロスとテイクプロフィット距離を適用するために修正した元のMQLバージョンと同様です。

使用上のヒント

  1. StockSharp内で通常通り証券、ポートフォリオ、接続を設定します。
  2. 希望するロットサイズに合わせてOrder volumeを設定します。
  3. トリガー価格のサブセットを入力し、Armedをtrueに切り替えます。0のままの値は無視されます。
  4. オプションで最初の約定後に残りのトリガーをアクティブに保つためにUse OCO linkを無効にします。
  5. 各トリガーと自動リセット状態を確認するメッセージのログを監視します。

戦略はブローカーが提供する価格ステップを使用することに注意してください。取引インストゥルメントが分数ピップで表示されているか、非従来的なティックサイズを使用している場合は、戦略を設定する前にピップベースの距離を適切に調整してください。

元のMQLスクリプトとの違い

  • 戦略はストップロスとテイクプロフィットレベルを適用するために注文を手動で修正する代わりにStockSharpのStartProtectionヘルパーを使用します。
  • レベル1データの購読はBid、Ask、High、Low値の手動ポーリングではなくハイレベルバインディングを通じて処理されます。
  • パラメーターはStrategyParam<T>を通じて公開されているため、StockSharp UIで直接調整・最適化できます。
  • ロギングはMT4のCommentとPlaySound通知を置き換え、StockSharpログ内で実行の透明性を提供します。
using System;
using System.Collections.Generic;

using Ecng.Common;

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

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Manually armed OCO price triggers driven by Level1 bid/ask updates.
/// </summary>
public class OcoPendingOrdersStrategy : Strategy
{
	private readonly StrategyParam<decimal> _orderVolume;
	private readonly StrategyParam<decimal> _buyLimitPrice;
	private readonly StrategyParam<decimal> _buyStopPrice;
	private readonly StrategyParam<decimal> _sellLimitPrice;
	private readonly StrategyParam<decimal> _sellStopPrice;
	private readonly StrategyParam<int> _stopLossPips;
	private readonly StrategyParam<int> _takeProfitPips;
	private readonly StrategyParam<bool> _useOcoLink;
	private readonly StrategyParam<bool> _armed;
	private decimal[] _initialLevels;
	private bool _initialArmed;
	private decimal? _bestBid;
	private decimal? _bestAsk;

	public decimal OrderVolume { get => _orderVolume.Value; set => _orderVolume.Value = value; }
	public decimal BuyLimitPrice { get => _buyLimitPrice.Value; set => _buyLimitPrice.Value = value; }
	public decimal BuyStopPrice { get => _buyStopPrice.Value; set => _buyStopPrice.Value = value; }
	public decimal SellLimitPrice { get => _sellLimitPrice.Value; set => _sellLimitPrice.Value = value; }
	public decimal SellStopPrice { get => _sellStopPrice.Value; set => _sellStopPrice.Value = value; }
	public int StopLossPips { get => _stopLossPips.Value; set => _stopLossPips.Value = value; }
	public int TakeProfitPips { get => _takeProfitPips.Value; set => _takeProfitPips.Value = value; }
	public bool UseOcoLink { get => _useOcoLink.Value; set => _useOcoLink.Value = value; }
	public bool Armed { get => _armed.Value; set => _armed.Value = value; }

	public OcoPendingOrdersStrategy()
	{
		_orderVolume = Param(nameof(OrderVolume), 1m)
			.SetGreaterThanZero()
			.SetDisplay("Order volume", "Volume sent with each market order", "Trading");
		_buyLimitPrice = Param(nameof(BuyLimitPrice), 0m)
			.SetNotNegative()
			.SetDisplay("Buy limit price", "Ask price threshold that activates a limit-style long entry, 0 disables", "Levels");
		_buyStopPrice = Param(nameof(BuyStopPrice), 0m)
			.SetNotNegative()
			.SetDisplay("Buy stop price", "Ask price threshold that activates a stop-style long entry, 0 disables", "Levels");
		_sellLimitPrice = Param(nameof(SellLimitPrice), 0m)
			.SetNotNegative()
			.SetDisplay("Sell limit price", "Bid price threshold that activates a limit-style short entry, 0 disables", "Levels");
		_sellStopPrice = Param(nameof(SellStopPrice), 0m)
			.SetNotNegative()
			.SetDisplay("Sell stop price", "Bid price threshold that activates a stop-style short entry, 0 disables", "Levels");
		_stopLossPips = Param(nameof(StopLossPips), 0)
			.SetNotNegative()
			.SetDisplay("Stop loss (pips)", "Protective stop distance in instrument points, multiplied by the price step", "Risk");
		_takeProfitPips = Param(nameof(TakeProfitPips), 0)
			.SetNotNegative()
			.SetDisplay("Take profit (pips)", "Profit target distance in instrument points, multiplied by the price step", "Risk");
		_useOcoLink = Param(nameof(UseOcoLink), true)
			.SetDisplay("Use OCO link", "The first filled order clears the remaining price levels and disarms the strategy", "Control");
		_armed = Param(nameof(Armed), false)
			.SetDisplay("Armed", "Safety switch for the triggers, reset to false when no active level remains", "Control");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
		=> [(Security, DataType.Level1)];

	protected override void OnReseted()
	{
		base.OnReseted();
		if (_initialLevels != null)
		{
			BuyLimitPrice = _initialLevels[0];
			BuyStopPrice = _initialLevels[1];
			SellLimitPrice = _initialLevels[2];
			SellStopPrice = _initialLevels[3];
			Armed = _initialArmed;
		}
		_initialLevels = null;
		_initialArmed = false;
		_bestBid = null;
		_bestAsk = null;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);
		_initialLevels = [BuyLimitPrice, BuyStopPrice, SellLimitPrice, SellStopPrice];
		_initialArmed = Armed;

		var step = Security?.PriceStep ?? 1m;
		if (step <= 0m)
			step = 1m;

		var take = TakeProfitPips > 0 ? new Unit(TakeProfitPips * step, UnitTypes.Absolute) : null;
		var stop = StopLossPips > 0 ? new Unit(StopLossPips * step, UnitTypes.Absolute) : null;
		if (take is not null || stop is not null)
			StartProtection(takeProfit: take, stopLoss: stop, useMarketOrders: true);

		// A Level1 binding only sees updates carrying its build field, so bid-only and ask-only updates need one binding each.
		foreach (var field in new[] { Level1Fields.BestBidPrice, Level1Fields.BestAskPrice })
		{
			var quotes = new Subscription(DataType.Level1, Security);
			quotes.MarketData.BuildField = field;
			SubscribeLevel1(quotes).Bind(ProcessLevel1).Start();
		}
	}

	private void ProcessLevel1(Level1ChangeMessage message)
	{
		if (message.TryGetDecimal(Level1Fields.BestBidPrice) is decimal bid)
			_bestBid = bid;

		if (message.TryGetDecimal(Level1Fields.BestAskPrice) is decimal ask)
			_bestAsk = ask;

		if (!Armed)
			return;

		if (_bestAsk is decimal bestAsk)
		{
			if (BuyLimitPrice > 0m && bestAsk <= BuyLimitPrice)
			{
				var level = BuyLimitPrice;
				BuyLimitPrice = 0m;
				Execute(Sides.Buy, $"Buy limit {level} hit by ask {bestAsk}");

				if (!Armed)
					return;
			}

			if (BuyStopPrice > 0m && bestAsk >= BuyStopPrice)
			{
				var level = BuyStopPrice;
				BuyStopPrice = 0m;
				Execute(Sides.Buy, $"Buy stop {level} hit by ask {bestAsk}");

				if (!Armed)
					return;
			}
		}

		if (_bestBid is decimal bestBid)
		{
			if (SellLimitPrice > 0m && bestBid >= SellLimitPrice)
			{
				var level = SellLimitPrice;
				SellLimitPrice = 0m;
				Execute(Sides.Sell, $"Sell limit {level} hit by bid {bestBid}");

				if (!Armed)
					return;
			}

			if (SellStopPrice > 0m && bestBid <= SellStopPrice)
			{
				var level = SellStopPrice;
				SellStopPrice = 0m;
				Execute(Sides.Sell, $"Sell stop {level} hit by bid {bestBid}");

				if (!Armed)
					return;
			}
		}

		DisarmIfEmpty();
	}

	private void Execute(Sides side, string trigger)
	{
		LogInfo($"{trigger}: {side} {OrderVolume} at market.");

		if (side == Sides.Buy)
			BuyMarket(OrderVolume);
		else
			SellMarket(OrderVolume);

		if (!UseOcoLink)
			return;

		ClearLevels();
		Armed = false;
		LogInfo("OCO link cleared all trigger levels; strategy disarmed.");
	}

	private void ClearLevels()
	{
		BuyLimitPrice = 0m;
		BuyStopPrice = 0m;
		SellLimitPrice = 0m;
		SellStopPrice = 0m;
	}

	private void DisarmIfEmpty()
	{
		if (BuyLimitPrice > 0m || BuyStopPrice > 0m || SellLimitPrice > 0m || SellStopPrice > 0m)
			return;

		Armed = false;
		LogInfo("No trigger levels remain; strategy disarmed.");
	}
}