在 GitHub 上查看

Spreader 策略

概述

Spreader 策略 源自 MetaTrader 专家顾问 "Spreader",属于经典的价差交易(对冲)模型。策略同时观察两只具有正相关性的品种,当它们的短期波动出现轻微背离时入场构建市场中性头寸,并在组合利润达到预设金额后立即平仓。

默认使用 1 分钟 K 线,与原始 EA 的工作频率一致;在 StockSharp Designer、Shell 或 API 运行器中可以根据需要调整时间框架。

交易逻辑

  1. 数据准备

    • 订阅主品种和副品种的 K 线数据,并仅处理收盘完成的 K 线。
    • 为每个品种保存最近 2 * ShiftLength + 1 根 K 线的收盘价,默认移位值为 30 根。
    • 只有当两只品种的最新 K 线具有相同的开盘时间时才会继续计算,确保信号同步。
  2. 趋势过滤

    • 分别计算当前收盘价与 ShiftLength 根前收盘价之间的变化,以及中间样本与最早样本之间的变化。
    • 如果同一品种的两个变化值符号相同,则被视为趋势行情,策略放弃本次信号。
  3. 相关性检查

    • 要求两只品种最近一次波动的方向相同;若符号不同则判定为负相关,放弃开仓。
  4. 波动率匹配

    • 统计两只品种近期波动幅度的绝对值,并使用它们的比值来调整副腿下单手数。
    • 比值超出 [0.3, 3] 范围时会被拒绝,避免在波动结构失衡时交易。
  5. 入场逻辑

    • 比较主、副腿的归一化波动幅度。如果主腿强于副腿,则买入主品种、卖出副品种;反之卖出主品种、买入副品种。
    • 下单使用市价方式,并根据各品种的最小手数、步长和上限自动规范化交易量。
  6. 持仓管理

    • 如果只剩副腿仓位(例如网络延迟导致另一侧未成交),策略会立即以相反方向补建主腿仓位以恢复对冲。
    • 如果只剩主腿仓位,则立即平仓以避免裸露方向风险。
    • 当两条腿都存在时,持续监控组合浮动盈亏,达到 TargetProfit 设置的金额后同时平仓。
  7. 安全约束

    • 若两只品种的合约乘数不同,策略会禁止交易,因为原始 EA 假定两腿合约规格一致。
    • IsFormedAndOnlineAndAllowTrading 返回允许之前不会发送任何交易指令,确保连接和权限正常。

参数说明

参数 描述
SecondSecurity 价差中的副品种,必须指定。
PrimaryVolume 主品种的基础下单手数,副腿手数将按波动比率自动缩放。
TargetProfit 组合达到的绝对盈金额度(账户货币),达到即平仓。
ShiftLength 计算波动时使用的移位长度,策略共需 2 * ShiftLength + 1 根 K 线。
CandleType 使用的 K 线类型,默认 1 分钟。

使用建议

  • 适合流动性好、正相关性稳定的品种组合,例如高度相关的外汇货币对或指数期货。
  • 建议确保两腿合约的点值、最小手数、保证金要求等规格一致,否则归一化后的下单量可能过小。
  • 因策略依赖 K 线数据,请确认数据源能够同时为两只品种提供同步的收盘信息。

前置条件

  • 拥有两只可交易且正相关的标的。
  • 通过 StockSharp 连接器获得两只标的的行情与交易权限。
  • 在策略实例中正确指定投资组合(Portfolio)。
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 SpreaderStrategy : 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 SpreaderStrategy()
	{
		_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;
	}
}