在 GitHub 上查看

OCO挂单策略

概述

OCO挂单策略 将 MetaTrader4 专家顾问 OCO_EA.mq4 的逻辑迁移到 StockSharp 高级 API。交易者可以同时设定四个价格触发器(买入限价、买入止损、卖出限价、卖出止损),当实时最优买价或卖价触及任一触发价格时,策略立即发送市价单,并可在经典的一撤其他(OCO)模式下清除剩余触发器。

策略完全依赖一级行情数据,不需要历史指标。非常适合手动或半自动交易流程:交易者自行规划关键价位,而平台负责在触发条件满足时立即执行,同时自动附加保护性止损和止盈。

交易逻辑

  1. 交易者设置任意组合的触发价格,并把 Armed(激活) 参数切换为 true。
  2. 策略订阅一级行情,持续保存最新的最优买价与最优卖价。
  3. 每当收到新的行情,策略会将保存的价格与触发条件对比:
    • 当最优卖价 小于或等于 买入限价 时,按照设定手数发送市价买单;
    • 当最优卖价 大于或等于 买入止损价 时,发送市价买单;
    • 当最优买价 大于或等于 卖出限价 时,发送市价卖单;
    • 当最优买价 小于或等于 卖出止损价 时,发送市价卖单。
  4. 每次触发后,对应的触发价格会被清零。如果 Use OCO link(使用OCO链) 为 true,其余触发器会立即清除,复刻原始 MT4 脚本的“一笔成交,全部撤销”逻辑;若关闭该参数,其余触发器继续有效,直到各自触发或被手动清除。
  5. 当所有触发价格均为零时,策略会自动将 Armed 复位为 false,防止误触发。

所有交易均通过 BuyMarket / SellMarket 完成,从而确保使用 StockSharp 环境中配置的市场接入方式,并在日志中输出详细信息,方便监控。

参数说明

  • 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。

风险控制

策略在 OnStarted 中调用 StartProtection,根据 Stop loss (pips) 和 Take profit (pips) 计算出绝对价格差,并为持仓自动挂出市价止损和止盈单。这样即使交易品种流动性较差,也能确保退出指令被执行。

由于策略是事件驱动式实现,不会在交易所挂出真实的限价单,而是等待行情触发后提交市价单。这与原始 MQL 版本相同——先立即成交,再根据点数距离设置止损与止盈。

使用建议

  1. 在 StockSharp 中完成标的、投资组合和连接的常规配置。
  2. 设置 Order volume 以匹配目标手数。
  3. 输入任意需要的触发价格,并将 Armed 打开为 true。保持 0 的触发器会被忽略。
  4. 如需在首笔成交后保留其他触发器,可将 Use OCO link 设为 false。
  5. 关注策略日志,确认每次触发及自动复位的状态。

请注意策略使用券商提供的价格步长。如果交易品种存在非常规跳动点或“迷你点”,在激活策略前请相应调整基于点数的止损和止盈参数。

与原始 MQL 脚本的差异

  • 使用 StockSharp 的 StartProtection 代替手动修改订单来设置止损/止盈;
  • 一级行情通过高层绑定获得,而不是直接读取 Bid、Ask、High、Low 变量;
  • 所有配置都通过 StrategyParam<T> 暴露,可在 StockSharp 界面中直接修改或用于优化;
  • 使用日志输出来替代 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.");
	}
}