Build an Opening Gap Percentage Indicator in cTrader with C#

Beginner Trading Tutorial | cTrader Algo | C# Custom Indicator

Price charts frequently show discontinuities between consecutive bars. A market may open above its previous close after a news announcement, reopen lower after a weekend, or begin a new intraday bar near the price where the previous one ended. Looking at these distances in raw price units is useful for a single instrument, but a percentage makes it easier to understand their relative size.

In this tutorial we build a cTrader indicator that measures the signed percentage change from the preceding bar's close to the current bar's open. The calculation is deliberately simple. It is a practical introduction to indexed bar data, custom output series, and why some measurements can be known near the beginning of a bar rather than waiting until the close. The indicator also offers a configurable filter to hide small gaps.

1. Define exactly what an opening gap means

Here, the term opening gap refers to the difference between adjacent bar endpoints, not necessarily a daily session gap or a price region in which no trades occurred. Let O(t) be the current bar's open and C(t−1) be the preceding bar's close. The signed percentage is Gap (%) = 100 × (O(t) − C(t−1)) / C(t−1).

A positive result indicates an opening price above the preceding close, a negative result indicates an opening price below it, and zero indicates equality. The formula assumes positive prices. Unlike a candle's open-to-close return, it does not measure what happened after the bar opened. Unlike true range, it does not combine the gap with the current high and low.

Build an Opening Gap Percentage Indicator in cTrader with C#
Figure 1. Hypothetical opens of 103, 100 and 97 against the same preceding close of 100 yield +3%, 0% and −3%.
Previous close Current open Gap (%) Interpretation
100 103 +3.00% Upward gap
100 100 0.00% No gap
100 97 −3.00% Downward gap
200 206 +3.00% Same relative upward gap
0 100 Undefined Invalid denominator

All numerical examples are hypothetical. In the fourth row, the absolute price difference is six instead of three, but the percentage difference is identical. This is the reason for normalizing by the preceding close. The percentage calculation removes the nominal price scale but does not adjust for volatility, liquidity, leverage or trading costs.

2. What the indicator displays

The indicator plots one histogram in a separate pane. Positive and negative values extend from zero in their respective directions, and the magnitude represents percentage points. A reading of 0.5 means a gap of one half of one percent, not a return of 50%. The optional minimum absolute gap parameter filters both signs symmetrically. Its default is zero, meaning that valid values are not filtered.

Suppose the minimum is set to 0.50%. A gap of +0.70% is retained, as is a gap of −0.70%, while +0.20% and −0.20% are hidden. The comparison uses full calculation precision, not the rounded numbers displayed on a chart. At the exact threshold, the intended rule retains the observation, subject to normal floating-point representation. Hidden observations are assigned an empty value instead of a fabricated zero.

3. Complete cTrader C# indicator

// PatternSmart Opening Gap Percent - cTrader Algo
using System;
using cAlgo.API;

namespace cAlgo.Indicators
{
    [Indicator(IsOverlay = false, TimeZone = TimeZones.UTC,
        AccessRights = AccessRights.None)]
    public class PSOpeningGapPercent : Indicator
    {
        [Parameter("Minimum absolute gap (%)",
            DefaultValue = 0.0, MinValue = 0.0)]
        public double MinimumGapPercent { get; set; }

        [Output("Gap (%)", LineColor = "RoyalBlue",
            PlotType = PlotType.Histogram)]
        public IndicatorDataSeries Gap { get; set; }

        public override void Calculate(int index)
        {
            // Clear any previous value at this index.
            Gap[index] = double.NaN;

            // The first bar has no preceding close.
            if (index < 1)
                return;

            double previousClose = Bars.ClosePrices[index - 1];
            double currentOpen = Bars.OpenPrices[index];

            // Percentage interpretation assumes positive prices.
            if (double.IsNaN(previousClose) ||
                double.IsInfinity(previousClose) ||
                previousClose <= 0 ||
                double.IsNaN(currentOpen) ||
                double.IsInfinity(currentOpen) ||
                currentOpen <= 0)
                return;

            double gap = 100.0 *
                (currentOpen - previousClose) / previousClose;

            // Hide small gaps without replacing them with zero.
            if (Math.Abs(gap) < MinimumGapPercent)
                return;

            // Preserve sign: positive up, negative down.
            Gap[index] = gap;
        }
    }
}

4. How the indexed calculation works

cTrader custom indicators derive from the Indicator class. The Indicator attribute sets the presentation and access rights, while the Parameter attribute exposes the minimum gap size to the user. The Output attribute declares the public IndicatorDataSeries where the calculated result is stored. Because the code uses only the available chart bars, it needs no external access rights, network connection or trade execution methods.

The Calculate method receives the index of the bar being evaluated. The platform calls it across historical observations and updates the live bar as new data arrives. In this implementation Bars.OpenPrices[index] reads the current bar's open, while Bars.ClosePrices[index – 1] reads the preceding bar's close. cTrader uses an increasing bar index for this calculation, so subtracting one refers to the earlier observation. This is different from the bars-ago indexing conventions used by some other trading platforms.

The first bar has no earlier observation available in the loaded dataset, which is why the method returns immediately when index is less than one. It also rejects nonpositive or invalid prices, protecting the denominator and the interpretation of the ratio. The output is initialized to double.NaN before each calculation. If a value is unavailable or fails the filter, that index remains empty.

5. Does this calculation need a closed-bar filter?

Most indicators involving the current high, low or close can change substantially while the current candle forms. This calculation is different: the inputs are the current open and preceding close. On a conventional time-based chart, once the new bar is created, both prices are normally established. Repeated Calculate calls for the same index therefore recompute the same gap even while the current last price fluctuates.

That does not mean the number exists before the first quote or trade used to construct the new bar. Nor does it guarantee historical immutability: data-feed corrections, chart reconstruction and changes in the underlying series can alter the inputs. On synthetic chart types, the displayed open may also be constructed rather than directly comparable with a standard bar open. The code intentionally does not use any future price, and it does not claim that an opening gap predicts where the bar will close.

6. Choose a minimum gap and chart timeframe

Minimum absolute gap (%) Behavior
0.00 (default) Show all valid gaps
0.10 Hide gaps with magnitude below 0.10%
0.50 Focus on relatively larger discontinuities
1.00 Retain only gaps of at least 1% in magnitude

There is no universally appropriate minimum threshold. On a continuously traded one-minute chart, many opening differences may be extremely small. On daily bars, overnight or weekend discontinuities may be more apparent. Begin with zero to inspect the underlying distribution, then increase the threshold only to suit your research objective. Compare like-for-like chart intervals and symbol data. Note that the indicator does not identify the start of a trading session; it measures every adjacent pair of bars on the selected chart.

7. Installation and manual verification

  1. Open the Algo workspace in cTrader and create a new C# indicator named PSOpeningGapPercent.
  2. Replace the generated source with the complete code above and build the indicator.
  3. Review build messages and attach the indicator to a standard candlestick chart.
  4. Set Minimum absolute gap (%) to zero and inspect a bar with a visibly different opening price.
  5. Read the current open and preceding close, calculate the percentage manually and compare it with the output.
  6. Increase the minimum gap and verify that small values disappear while larger positive and negative values remain.

Test the indicator on both daily and intraday bars. Include a flat opening, a positive gap, a negative gap and the first loaded observation. If a zero reading is difficult to see in the histogram, inspect the indicator value with the chart's data display. Observe a live bar as quotes change; the gap should normally remain unchanged because neither input is its developing close. If values differ from your manual calculation, first verify the symbol, chart type and exact historical bar index.

8. Applications and limitations

The indicator can support descriptive gap statistics, event studies and the construction of research filters. A large gap does not demonstrate that the market will fill it, continue in the same direction, or offer an executable price at the preceding close. Spreads and liquidity can be unusually unfavorable around session transitions, and data-provider conventions can affect the recorded opening price. If your objective is a daily session-opening scanner, add an explicit session boundary definition rather than assuming every bar is a session opener.

Interested in extending this free indicator with session filters, gap statistics, notifications or a custom cBot integration? Contact us through our Custom Trading Software Development Services.

This example was reviewed against the cTrader Algo indicator API documentation but has not been built or run inside cTrader. Verify the implementation with your own data and installation. Trading involves risk, and gap size alone cannot guarantee future outcomes.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.