Ver en GitHub

Estrategia I-Gap

La Estrategia I-Gap replica el asesor experto "i-GAP" de MetaTrader. Monitoriza la brecha de precio entre el cierre de la vela anterior y la apertura de la vela actual. Una brecha de apertura bajista que supere un número especificado de pasos de precio puede desencadenar una entrada larga y opcionalmente cerrar posiciones cortas existentes. Una brecha alcista funciona de la misma manera para las posiciones cortas.

Detalles

  • Criterios de entrada: La brecha de apertura entre velas consecutivas supera el tamaño configurado.
  • Largo/Corto: Ambos.
  • Criterios de salida: Señal de brecha opuesta.
  • Stops: Sin stop loss ni take profit fijos.
  • Valores predeterminados:
    • CandleType = 1 hour
    • GapSize = 5
    • BuyPosOpen = true
    • SellPosOpen = true
    • BuyPosClose = true
    • SellPosClose = true
  • Filtros:
    • Categoría: Ruptura
    • Dirección: Ambos
    • Indicadores: Ninguno
    • Stops: No
    • Complejidad: Principiante
    • Marco temporal: Intradía
    • Estacionalidad: No
    • Redes neuronales: No
    • Divergencia: No
    • Nivel de riesgo: Bajo
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;



/// <summary>
/// Strategy based on gap between previous close and current open.
/// </summary>
public class IGapStrategy : Strategy
{
	private readonly StrategyParam<decimal> _gapSize;
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<bool> _buyPosOpen;
	private readonly StrategyParam<bool> _sellPosOpen;
	private readonly StrategyParam<bool> _buyPosClose;
	private readonly StrategyParam<bool> _sellPosClose;

	private decimal? _prevClose;

	/// <summary>
	/// Gap size in price steps.
	/// </summary>
	public decimal GapSize
	{
		get => _gapSize.Value;
		set => _gapSize.Value = value;
	}

	/// <summary>
	/// Candle type used for analysis.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Allow opening long positions on gap down.
	/// </summary>
	public bool BuyPosOpen
	{
		get => _buyPosOpen.Value;
		set => _buyPosOpen.Value = value;
	}

	/// <summary>
	/// Allow opening short positions on gap up.
	/// </summary>
	public bool SellPosOpen
	{
		get => _sellPosOpen.Value;
		set => _sellPosOpen.Value = value;
	}

	/// <summary>
	/// Close long position on opposite signal.
	/// </summary>
	public bool BuyPosClose
	{
		get => _buyPosClose.Value;
		set => _buyPosClose.Value = value;
	}

	/// <summary>
	/// Close short position on opposite signal.
	/// </summary>
	public bool SellPosClose
	{
		get => _sellPosClose.Value;
		set => _sellPosClose.Value = value;
	}

	/// <summary>
	/// Constructor.
	/// </summary>
	public IGapStrategy()
	{
		_gapSize = Param(nameof(GapSize), 5m)
			.SetGreaterThanZero()
			.SetDisplay("Gap Size", "Gap in price steps required to trigger signal", "General")
			;

		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
			.SetDisplay("Candle Type", "Timeframe for gap detection", "General");

		_buyPosOpen = Param(nameof(BuyPosOpen), true)
			.SetDisplay("Enable Buy", "Allow opening long positions", "Trading");

		_sellPosOpen = Param(nameof(SellPosOpen), true)
			.SetDisplay("Enable Sell", "Allow opening short positions", "Trading");

		_buyPosClose = Param(nameof(BuyPosClose), true)
			.SetDisplay("Close Buy", "Close long on opposite signal", "Trading");

		_sellPosClose = Param(nameof(SellPosClose), true)
			.SetDisplay("Close Sell", "Close short on opposite signal", "Trading");
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		return new[] { (Security, CandleType) };
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevClose = null;
	}

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

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

		StartProtection(
			takeProfit: new Unit(2, UnitTypes.Percent),
			stopLoss: new Unit(1, UnitTypes.Percent)
		);
	}

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

		if (_prevClose is null)
		{
			_prevClose = candle.ClosePrice;
			return;
		}

		// Use percentage-based gap: GapSize * 0.01%
		var threshold = _prevClose.Value * GapSize * 0.01m / 100m;
		var gap = _prevClose.Value - candle.OpenPrice;

		if (gap > threshold && Position == 0)
		{
			if (BuyPosOpen)
				BuyMarket();
		}
		else if (-gap > threshold && Position == 0)
		{
			if (SellPosOpen)
				SellMarket();
		}

		_prevClose = candle.ClosePrice;
	}
}