Ver en GitHub

Estrategia Probe

Descripción general

La estrategia Probe reproduce el asesor experto de MetaTrader 5 "Probe" dentro del marco de alto nivel de StockSharp. Monitorea el Commodity Channel Index (CCI) en un marco temporal configurable y reacciona cuando el oscilador rompe fuera de un canal simétrico. Cuando ocurre un breakout, la estrategia coloca una orden stop con un desplazamiento del precio de mercado actual basado en pips. El enfoque busca capturar la continuación del momentum tras el breakout mientras mantiene el riesgo limitado mediante niveles protectores basados en pips y un trailing stop adaptativo.

Lógica de trading

  1. Calcular el CCI en el tipo de vela configurado.
  2. Rastrear los valores anteriores y actuales del CCI para detectar cuándo el indicador sale del límite inferior o superior del canal.
  3. Cuando el CCI cruza hacia arriba a través de -CCI Channel, enviar una orden stop de compra por encima del último cierre usando la distancia Indent (pips).
  4. Cuando el CCI cruza hacia abajo a través de +CCI Channel, enviar una orden stop de venta por debajo del último cierre usando el mismo indent en pips.
  5. Solo puede permanecer activa una orden stop pendiente a la vez. Las órdenes opuestas se cancelan y las nuevas señales se ignoran mientras una orden está activa.

Gestión de órdenes

  • Las órdenes stop pendientes se retiran si el mercado se aleja del precio de entrada más de 1.5 * Indent (pips). Esto refleja la lógica de MetaTrader que evita que órdenes obsoletas permanezcan en el libro cuando el momentum se desvanece.
  • Una vez que se ejecuta una orden stop, la estrategia almacena el precio ejecutado como la referencia de entrada. Cualquier orden pendiente opuesta se cancela inmediatamente.

Gestión de riesgo

  • Un stop-loss inicial se deriva de Stop Loss (pips) y se adjunta a la posición activa mediante monitoreo interno. Cuando el precio toca el stop, la posición se sale con una orden de mercado.
  • El comportamiento de trailing comienza después de que el beneficio flotante supera Trailing Stop (pips) + Trailing Step (pips). El stop se mueve entonces para asegurar ganancias respetando la distancia mínima de trailing.
  • Todas las distancias basadas en pips se ajustan automáticamente para cotizaciones de 3 y 5 dígitos escalando el tamaño del tick de la bolsa.

Parámetros

Parámetro Descripción
CandleType Marco temporal principal usado para construir velas y calcular el CCI.
CciLength Período de promediado del oscilador CCI.
CciChannelLevel Umbral absoluto del CCI que forma el canal de breakout simétrico.
IndentPips Distancia en pips agregada al último cierre al colocar la orden stop pendiente.
StopLossPips Distancia del stop-loss protector medida en pips.
TrailingStopPips Umbral de beneficio en pips requerido antes de que se active el trailing stop.
TrailingStepPips Distancia adicional de beneficio necesaria antes de que el trailing stop se mueva de nuevo.

Notas

  • Use la propiedad Volume de la estrategia para controlar el tamaño negociado.
  • La estrategia está diseñada para netting de posición única, coincidiendo con el comportamiento del Asesor Experto original.
  • La renderización del gráfico dibuja velas, el indicador CCI y operaciones ejecutadas cuando hay un área de gráfico disponible.
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;
	}
}