在 GitHub 上查看

Hedger 策略

基于 MetaTrader 5 专家顾问 hedger.mq5(MQL #23511)的 StockSharp 移植版。原始系统在已有仓位的浮亏达到指定点数时建立一个反向对冲头寸;价格回撤一段距离后,无论该对冲是否亏损都会被平掉,从而让原始方向继续恢复。本移植版本使用 StockSharp 的高级 API 实现相同的循环,并针对平台的净持仓模型进行了适配。

交易逻辑

  1. 策略监听所选时间框架的每根收盘K线。
  2. 对于每个非对冲的多头仓位,如果入场价与当前收盘价之间的距离大于或等于 DrawdownOpenPips,且没有激活的空头对冲,则按相同手数开空对冲。
  3. 对于非对冲的空头仓位应用相同规则:亏损达到阈值时开多对冲。
  4. 已激活的对冲腿在其浮亏达到 DrawdownClosePips 时被平仓,对应 MetaTrader 在部分回撤后解除保护的做法。
  5. 当账户净持仓为零且启用了 StartWithLong 时,策略会建立一个初始多单以启动循环。

由于 StockSharp 记录的是净头寸,策略内部维护了多头与空头的登记簿,并标记哪些是对冲单。每次市价单都会同步更新登记簿,使对冲仓位即便在经纪商端被净额结算也能正确开合。

参数

参数 说明
DrawdownOpenPips 触发开立反向对冲的亏损点数。
DrawdownClosePips 触发关闭对冲仓位的亏损点数。
InitialVolume 启动循环时开立的初始仓位手数。
StartWithLong 为 true 时在空仓状态下自动开多单启动。
EnableVerboseLogging 将对冲操作写入日志,便于调试。
CandleType 用于监控浮亏的蜡烛序列。

与 MetaTrader 版本的差异

  • 原脚本通过订单备注 (hedge_buy / hedge_sell) 区分对冲仓位;移植版在内存中保存标记,以适应 StockSharp 的净额模式。
  • 省略了保证金校验与滑点设置,订单通过 BuyMarket / SellMarket 辅助方法提交。
  • 为点数阈值与手数配置了优化范围,方便在 StockSharp 优化器中调参。

使用提示

  1. 将策略绑定到目标证券与投资组合。
  2. 根据标的波动性调整开仓与平仓阈值。
  3. 在验证阶段启用详细日志,可查看每次对冲的开立与释放以及对应的点数。
  4. 建议在 M15 至 H1 等具备代表性的时间框架上运行,以避免过度交易。
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 HedgerDrawdownStrategy : 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 HedgerDrawdownStrategy()
	{
		_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;
	}
}