在 GitHub 上查看

Probe 策略

概述

Probe 策略在 StockSharp 高层框架中复刻了 MetaTrader 5 专家顾问 “Probe”。策略在可配置的时间框架上计算商品通道指数(CCI),当振荡指标突破对称通道时做出反应。出现突破信号后,策略会以设定的点距在当前价格附近挂出止损单,试图跟随突破后的动量,同时利用点距参数化的止损和跟踪止损来限制风险。

交易逻辑

  1. 在选定的 CandleType 时间框架上生成蜡烛并计算 CCI。
  2. 保存上一根和当前 CCI 数值,以便识别指标突破上下通道边界的瞬间。
  3. 当 CCI 自下向上穿越 -CCI Channel 时,在最近收盘价上方 Indent (pips) 点的位置放置买入止损单。
  4. 当 CCI 自上向下跌破 +CCI Channel 时,在最近收盘价下方 Indent (pips) 点的位置放置卖出止损单。
  5. 任意时刻只允许一张挂单处于激活状态。若方向发生改变,原有挂单会被取消,在挂单激活期间新的信号会被忽略。

挂单管理

  • 如果市场价格偏离挂单价格超过 1.5 * Indent (pips),止损单将被撤销,以避免在动能减弱时保留失效订单。
  • 止损单成交后,策略会记录实际成交价作为入场价,并立即撤销所有方向相反的挂单。

风险管理

  • 初始止损基于 Stop Loss (pips) 参数计算,策略在内部监控该价格水平,一旦触发立即以市价平仓。
  • 当浮动盈利超过 Trailing Stop (pips) + Trailing Step (pips) 时启动跟踪止损。之后每当盈利再次增加指定的跟踪步长,止损价位都会按最小距离进行上移或下移。
  • 所有以点表示的距离会根据交易品种的报价精度自动缩放,适配 3 位或 5 位小数的品种。

参数

参数 说明
CandleType 用于生成蜡烛并计算 CCI 的主要时间框架。
CciLength CCI 指标的平均周期。
CciChannelLevel 构成对称通道边界的绝对 CCI 阈值。
IndentPips 在最近收盘价基础上偏移的点数,用于设置止损挂单价格。
StopLossPips 初始保护性止损的点数。
TrailingStopPips 启动跟踪止损所需的最小盈利点数。
TrailingStepPips 每次调整跟踪止损之前需要增加的额外盈利点数。

说明

  • 交易手数通过策略的 Volume 属性设置。
  • 策略按照净头寸模式运行,与原始 EA 的行为保持一致。
  • 如果存在图表区域,策略会绘制蜡烛、CCI 指标以及实际成交。
using System;
using System.Collections.Generic;

using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Probe CCI breakout strategy converted from the original MetaTrader 5 expert advisor.
/// Listens for Commodity Channel Index threshold crossovers and enters with market orders.
/// </summary>
public class ProbeStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _cciLength;
	private readonly StrategyParam<decimal> _cciChannelLevel;
	private readonly StrategyParam<decimal> _stopLossPips;
	private readonly StrategyParam<decimal> _trailingStopPips;
	private readonly StrategyParam<decimal> _trailingStepPips;

	private decimal? _previousCci;
	private decimal? _entryPrice;
	private decimal? _stopPrice;
	private decimal _pipSize;

	public ProbeStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
			.SetDisplay("Candle Type", "Primary timeframe used for indicator calculations", "General");

		_cciLength = Param(nameof(CciLength), 60)
			.SetGreaterThanZero()
			.SetDisplay("CCI Length", "Averaging period of the Commodity Channel Index", "Indicators");

		_cciChannelLevel = Param(nameof(CciChannelLevel), 120m)
			.SetGreaterThanZero()
			.SetDisplay("CCI Channel", "Absolute CCI level used as the channel boundary", "Indicators");

		_stopLossPips = Param(nameof(StopLossPips), 50m)
			.SetNotNegative()
			.SetDisplay("Stop Loss (pips)", "Protective stop loss distance expressed in pips", "Risk");

		_trailingStopPips = Param(nameof(TrailingStopPips), 5m)
			.SetNotNegative()
			.SetDisplay("Trailing Stop (pips)", "Minimum profit required before trailing activates", "Risk");

		_trailingStepPips = Param(nameof(TrailingStepPips), 5m)
			.SetNotNegative()
			.SetDisplay("Trailing Step (pips)", "Additional profit required before the stop is moved again", "Risk");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities() => [(Security, CandleType)];

	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	public int CciLength
	{
		get => _cciLength.Value;
		set => _cciLength.Value = value;
	}

	public decimal CciChannelLevel
	{
		get => _cciChannelLevel.Value;
		set => _cciChannelLevel.Value = value;
	}

	public decimal StopLossPips
	{
		get => _stopLossPips.Value;
		set => _stopLossPips.Value = value;
	}

	public decimal TrailingStopPips
	{
		get => _trailingStopPips.Value;
		set => _trailingStopPips.Value = value;
	}

	public decimal TrailingStepPips
	{
		get => _trailingStepPips.Value;
		set => _trailingStepPips.Value = value;
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_previousCci = null;
		_entryPrice = null;
		_stopPrice = null;
		_pipSize = 0m;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		_pipSize = CalculatePipSize();
		_previousCci = null;
		_entryPrice = null;
		_stopPrice = null;

		var cci = new CommodityChannelIndex { Length = CciLength };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(cci, ProcessCandle)
			.Start();

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, cci);
			DrawOwnTrades(area);
		}
	}

	private void ProcessCandle(ICandleMessage candle, decimal cciValue)
	{
		if (candle.State != CandleStates.Finished)
			return;

		if (_pipSize <= 0m)
			_pipSize = CalculatePipSize();

		// Manage existing position (stop loss / trailing)
		var exited = ManagePosition(candle);
		if (exited)
		{
			_previousCci = cciValue;
			return;
		}

		// Check for CCI crossover signals
		if (_previousCci.HasValue && Position == 0m)
		{
			var channel = CciChannelLevel;
			var lower = -channel;

			// CCI crosses up from below -channel -> buy signal
			var crossUp = _previousCci.Value < lower && cciValue > lower;
			// CCI crosses down from above +channel -> sell signal
			var crossDown = _previousCci.Value > channel && cciValue < channel;

			if (crossUp)
			{
				BuyMarket();
				_entryPrice = candle.ClosePrice;

				var stopDistance = StopLossPips * _pipSize;
				_stopPrice = stopDistance > 0m ? candle.ClosePrice - stopDistance : null;
			}
			else if (crossDown)
			{
				SellMarket();
				_entryPrice = candle.ClosePrice;

				var stopDistance = StopLossPips * _pipSize;
				_stopPrice = stopDistance > 0m ? candle.ClosePrice + stopDistance : null;
			}
		}

		_previousCci = cciValue;
	}

	private bool ManagePosition(ICandleMessage candle)
	{
		if (Position == 0m)
		{
			_entryPrice = null;
			_stopPrice = null;
			return false;
		}

		var trailingStop = TrailingStopPips * _pipSize;
		var trailingStep = TrailingStepPips * _pipSize;

		if (Position > 0m)
		{
			if (_entryPrice == null)
				_entryPrice = candle.ClosePrice;

			// Check stop loss
			if (_stopPrice.HasValue && candle.LowPrice <= _stopPrice.Value)
			{
				SellMarket();
				ResetTradeState();
				return true;
			}

			// Trailing stop logic
			if (TrailingStopPips > 0m && trailingStop > 0m && _entryPrice.HasValue)
			{
				var profit = candle.ClosePrice - _entryPrice.Value;
				var threshold = trailingStop + trailingStep;

				if (profit > threshold)
				{
					var desiredStop = candle.ClosePrice - trailingStop;
					if (!_stopPrice.HasValue || desiredStop > _stopPrice.Value)
						_stopPrice = desiredStop;
				}
			}
		}
		else if (Position < 0m)
		{
			if (_entryPrice == null)
				_entryPrice = candle.ClosePrice;

			// Check stop loss
			if (_stopPrice.HasValue && candle.HighPrice >= _stopPrice.Value)
			{
				BuyMarket();
				ResetTradeState();
				return true;
			}

			// Trailing stop logic
			if (TrailingStopPips > 0m && trailingStop > 0m && _entryPrice.HasValue)
			{
				var profit = _entryPrice.Value - candle.ClosePrice;
				var threshold = trailingStop + trailingStep;

				if (profit > threshold)
				{
					var desiredStop = candle.ClosePrice + trailingStop;
					if (!_stopPrice.HasValue || desiredStop < _stopPrice.Value)
						_stopPrice = desiredStop;
				}
			}
		}

		return false;
	}

	private void ResetTradeState()
	{
		_entryPrice = null;
		_stopPrice = null;
	}

	private decimal CalculatePipSize()
	{
		var step = Security?.PriceStep ?? 0m;
		if (step <= 0m)
			return 0.01m;

		return step;
	}
}