Auf GitHub ansehen

I Gap Strategy

The I Gap Strategy replicates the MetaTrader "i-GAP" expert advisor. It monitors the price gap between the previous candle's close and the current candle's open. A downward opening gap exceeding a specified number of price steps can trigger a long entry and optionally close existing short positions. An upward gap works the same way for shorts.

Details

  • Entry Criteria: Opening gap between consecutive candles exceeds the configured size.
  • Long/Short: Both.
  • Exit Criteria: Opposite gap signal.
  • Stops: No fixed stop loss or take profit.
  • Default Values:
    • CandleType = 1 hour
    • GapSize = 5
    • BuyPosOpen = true
    • SellPosOpen = true
    • BuyPosClose = true
    • SellPosClose = true
  • Filters:
    • Category: Gap
    • Direction: Both
    • Indicators: None
    • Stops: No
    • Complexity: Beginner
    • Timeframe: Intraday
    • Seasonality: No
    • Neural networks: No
    • Divergence: No
    • Risk level: Low
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;
	}
}