在 GitHub 上查看

Consolidation Breakout 策略

该策略复刻了 MetaTrader 上的 Consolidation Breakout 智能交易系统的核心逻辑。它寻找短期盘整区间,并在 Momentum 与 MACD 同向确认后,沿突破方向开仓。风险通过以价格跳动(点)为单位的固定止盈与止损距离来控制。

工作流程

  1. CandleType 参数决定主图时间框架,所有趋势与盘整条件均在该时间框架的K线中判断。
  2. 采用典型价格计算的两条线性加权移动平均线(LWMA)用来筛选趋势。做多时需要快线高于慢线,做空则相反。
  3. 当前两根K线互相重叠时视为盘整:做多时要求两根之前的最低价低于上一根K线的最高价;做空则要求上一根K线的最低价低于两根之前的最高价。这与原始 MQL 脚本中的重叠条形逻辑一致。
  4. Momentum 指标必须超过多头或空头阈值,以确认动能(这里的阈值近似于 MQL 版本在 100 附近的过滤器)。
  5. MacdCandleType 时间框架上计算的 MACD 需要与交易方向一致。策略检查 MACD 线在正负两个区域是否都领先于信号线,从而还原原策略的多时间框架确认。
  6. 当所有条件满足且账户持仓为空或反向时,策略按照 TradeVolume 参数提交市价单。随后立即根据价格跳动重新计算止损与止盈,以便K线的最高价/最低价能够触发离场。
  7. 每根完成的K线都会检查已有仓位;若价格触及止损或止盈,策略会以市价平仓并重置保护水平。

指标

  • 线性加权移动平均线(快线、慢线,基于典型价格)
  • Momentum
  • MACD(12/26/9 参数,运行在更高时间框架)

参数

  • CandleType —— 主时间框架,用于识别突破。
  • MacdCandleType —— 计算 MACD 的确认时间框架。
  • FastMaPeriod —— 快速 LWMA 的周期。
  • SlowMaPeriod —— 慢速 LWMA 的周期。
  • MomentumLength —— Momentum 的回溯长度。
  • MomentumBuyThreshold —— 多头信号所需的最小 Momentum 值。
  • MomentumSellThreshold —— 空头信号所需的最小 Momentum 绝对值。
  • StopLossPips —— 止损距离(价格跳动数)。
  • TakeProfitPips —— 止盈距离(价格跳动数)。
  • TradeVolume —— 每次下单的成交量。

默认值与原始 EA 保持一致:LWMA 周期 6 与 85,Momentum 长度 14,动能阈值 0.3,止损 20 点,止盈 50 点。不同品种的报价步长不同,请相应调整点值距离。

说明

  • 为突出主要突破逻辑,原脚本中的追踪止损、保本移动以及资金管理模块未在此移植。
  • 请确认数据源支持所选时间框架;若 MacdCandleType 过大导致数据稀疏,可选择更低时间框架以保持 MACD 过滤器的灵敏度。
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 ConsolidationBreakoutStrategy : 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 ConsolidationBreakoutStrategy()
	{
		_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;
	}
}