在 GitHub 上查看

三重顶与三重底策略

三重顶与三重底策略移植自同名的 MetaTrader 智能交易系统。原始版本在开仓前会同时检查趋势方向、动量强度以及 MACD 过滤。本移植版本保留了相同的核心思想,并将关键阈值暴露为可配置参数,方便在 StockSharp 框架中进行优化 与回测。

策略逻辑

  1. 趋势过滤:基于典型价 (高+低+收)/3 计算两条线性加权移动平均线。只有当快线位于慢线上方时才允许做多,位于 下方时才允许做空。
  2. 动量确认:内置的 Momentum 指标需要在最近三根收盘 K 线内至少有一次偏离中性值 100 超过设定的阈值,用于 避免在震荡市中交易。
  3. MACD 过滤:采用 12/26/9 参数的 MACD。只有当 MACD 主线高于信号线时才买入,当主线低于信号线时才卖出, 以避免逆势操作。
  4. 风险控制:市价单会同时设置止损和止盈,单位为绝对价格。参数可以设为 0 来禁用。策略在每根完成 K 线时也 会检查价格是否触及这些阈值,从而确保在服务器无法维护保护单时仍能及时退出。

参数说明

  • Entry Candle – 决定策略运行时间框架的 DataType。
  • Fast LWMA / Slow LWMA – 快速与慢速线性加权移动平均线的周期。
  • Momentum Period / Momentum Threshold – Momentum 指标的回溯长度以及确认交易所需的最小偏离。
  • Stop Loss / Take Profit – 止损与止盈距离,单位为绝对价格,同时会通过 SetStopLossSetTakeProfit 提交至交易柜台。

与 MQL 版本的差异

  • 为保持 StockSharp 端的简洁性,移除了原始版本中的加倍下单、资金回撤保护、蜡烛图跟踪、保本移动以及依赖图形对 象的趋势线判断。
  • 风险阈值以绝对价格表示而非点值。这样可避免不同经纪商的点值定义差异,用户只需根据合约的价格步长自行换算。
  • 图表输出使用 StockSharp 的图形区域绘制 K 线、移动平均线、动量和 MACD。

使用建议

  1. 在启动策略前选择交易标的并设定合适的蜡烛类型。
  2. 根据品种波动率调整动量阈值和止损/止盈距离。
  3. 策略仅保持一个净头寸,若出现反向信号会先平仓,避免多空同时持有。

代码遵循仓库中的高层 API 指南,并提供了英文注释以便阅读与维护。

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 TripleTopTripleBottomStrategy : 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 TripleTopTripleBottomStrategy()
	{
		_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;
	}
}