Intermediate Trading Tutorial — Confirmed Directional Opening Gap Frequency in cTrader

Opening gaps are often discussed in terms of their magnitude or whether they subsequently close. Another useful research question is how frequently opening prices differ from the preceding close in each direction. A market may exhibit frequent small upward gaps but only occasional large downward gaps. A magnitude-weighted statistic and a frequency statistic would describe that situation differently. This tutorial develops a native cTrader C# indicator that counts qualifying upward and downward opening gaps across a rolling window of completed candles, reports each frequency, and calculates their signed difference in percentage points. It deliberately measures event frequency rather than size, profitability or the probability of the next event.

Define the event and reference sample

For each evaluated candle, subtract the immediately preceding candle's close from the evaluated candle's open. Divide that difference by the symbol's TickSize and round it to the nearest integer using a symmetric midpoint convention. A positive result means the open is above the preceding close. A negative result means the open is below it. Define a qualifying upward event when the rounded difference is at least the positive minimum threshold, and a downward event when it is at most the negative threshold. All remaining candles are neutral for this classification.

The denominator is the total number N of eligible candles, including neutral observations. If U candles qualify upward and D candles qualify downward, the upward frequency is 100 times U divided by N, the downward frequency is 100 times D divided by N, and the net frequency is their difference. Each directional frequency lies between zero and one hundred percent. Their sum cannot exceed one hundred percent because a single candle cannot qualify in both directions. The net lies between minus one hundred and plus one hundred percentage points. It is not a relative percentage change between the two frequencies.

Confirmed Directional Opening Gap Frequency Indicator
Five hypothetical signed opening gaps are +3, −4, +1, +2 and 0 ticks. With a two-tick minimum, two upward events and one downward event qualify. Their frequencies are 40% and 20%, giving a net difference of +20 percentage points.

Calculate the example manually

Set Period to five and Minimum Gap Ticks to two. Suppose the tick size is 0.25 and the preceding closes for the five event candles are 100, 101, 99, 100 and 102. The corresponding opens are 100.75, 100, 99.25, 100.50 and 102. These pairs yield signed differences of +0.75, −1.00, +0.25, +0.50 and zero price units, equivalent to +3, −4, +1, +2 and zero ticks. The first and fourth candles qualify upward, the second qualifies downward, and the third and fifth are neutral. The counts are two and one, so the output frequencies are 40% and 20%, and net is +20 percentage points.

Now suppose a new completed event with a gap of −2 ticks enters the window and the oldest +3-tick event leaves it. The new sample is −4, +1, +2, zero and −2. Upward frequency becomes 20%, downward frequency becomes 40%, and net becomes −20 percentage points. This illustrates that the net can change because an old event expires as well as because a new event enters. All examples are hypothetical arithmetic demonstrations. A one-tick event does not qualify with the chosen threshold, whereas exactly two ticks does qualify.

Complete native C# indicator source

using System;
using cAlgo.API;

namespace cAlgo
{
    [Indicator(IsOverlay = false, AccessRights = AccessRights.None)]
    public class PSDirectionalGapFrequency : Indicator
    {
        [Parameter("Period", DefaultValue = 30,
            MinValue = 1, MaxValue = 10000)]
        public int Period { get; set; }

        [Parameter("Minimum Gap Ticks", DefaultValue = 2,
            MinValue = 1)]
        public int MinimumGapTicks { get; set; }

        [Output("Up Gap %", LineColor = "SeaGreen")]
        public IndicatorDataSeries Up { get; set; }

        [Output("Down Gap %", LineColor = "IndianRed")]
        public IndicatorDataSeries Down { get; set; }

        [Output("Net Percentage Points", LineColor = "SteelBlue",
            Thickness = 2)]
        public IndicatorDataSeries Net { get; set; }

        public override void Calculate(int index)
        {
            // Publish previous completed bars only.
            Up[index] = Down[index] = Net[index] = double.NaN;

            // At display index t use event bars t-N ... t-1.
            // The oldest event also needs its preceding close.
            if (index <= Period || Symbol.TickSize <= 0)
                return;

            int upCount = 0;
            int downCount = 0;

            for (int j = index - Period; j < index; j++)
            {
                double gap = (Bars.OpenPrices[j] -
                    Bars.ClosePrices[j - 1]) / Symbol.TickSize;

                if (double.IsNaN(gap) || double.IsInfinity(gap))
                    return;

                // Compare on the symbol's tick grid.
                double ticks = Math.Round(gap,
                    MidpointRounding.AwayFromZero);

                if (ticks >= MinimumGapTicks)
                    upCount++;
                else if (ticks <= -MinimumGapTicks)
                    downCount++;
            }

            Up[index] = 100.0 * upCount / Period;
            Down[index] = 100.0 * downCount / Period;
            Net[index] = Up[index] - Down[index];
        }
    }
}

Implementation and chronological indexing

The Indicator attribute creates a separate output panel without requiring additional access rights. Two parameters control the observation count and minimum gap size independently. The three Output properties define separate numerical series. In cTrader, Calculate receives a chronological bar index, beginning at zero for the oldest loaded candle. At display index t, the loop examines event bars t−N through t−1. Each event requires its own preceding close, so the earliest usable display index is N+1. Earlier values are set to NaN rather than zero. This distinguishes missing history from a valid window containing no qualifying events.

Each call initializes the three output values, then performs a direct scan. Symbol.TickSize converts the price difference to tick units. Math.Round with MidpointRounding.AwayFromZero supplies an explicit symmetric rounding convention. This is appropriate for ordinary data represented on the instrument's tick grid. For adjusted or synthetic prices that do not align with that grid, rounding changes the event definition; consider whether a different policy is appropriate before applying the statistic. Invalid nonfinite gaps invalidate the entire sample rather than silently reducing the denominator.

Each calculation requires N comparisons, giving linear computational cost. The implementation avoids mutable cross-bar accumulators, so repeated calculations for the same index with unchanged historical inputs produce the same output. A rolling count could improve performance for large periods, but would need careful handling of historical reloads, expired events and repeated evaluations. This direct version is intended as an auditable reference.

Installation and chart inspection

Open the Algo workspace in cTrader and create a new C# indicator named PSDirectionalGapFrequency. Replace the generated source with the complete example and build it. Resolve any compiler diagnostics in your installed version, then attach it to a chart. Set Period to five and the minimum to two when verifying the worked example. Inspect the three series numerically rather than relying only on their colors. The source has not been compiled or executed in cTrader here.

Completed-bar behavior and repainting

Although an opening gap can be known shortly after a candle opens, this implementation intentionally excludes the active candle to maintain a consistent completed-event convention. The value at the current chart index depends entirely on earlier candles and is available when the new bar is recognized. It is plotted one bar after the most recently counted event. No backward displacement is used to imply earlier availability. Under unchanged data, incoming changes to the active candle's high, low and close do not affect its displayed output. Historical corrections, session changes and chart rebuilding may legitimately alter past observations. The latest event may remain excluded during a closure until another bar appears.

Testing and limitations

Reproduce both samples in a spreadsheet. Verify exact threshold equality, neutral events, all-up and all-down samples, insufficient history and Period equal to one. Confirm that the directional frequencies sum to no more than one hundred and that net equals their difference. Compare historical and replay observations using the same feed and session settings. An opening gap frequency does not describe intrabar retracement, eventual gap closure, absolute gap size or executable prices. Consecutive windows overlap and are statistically dependent. Broker quote conventions, weekend closures and aggregation choices can materially change the event count. Evaluate downstream research hypotheses with independent data and realistic costs.

For session-specific gap classification, magnitude weighting, alerts or cBot integration, contact our Custom cTrader indicator Development Services.

Risk disclosure: educational material only. Trading involves risk of loss. Hypothetical examples do not establish profitability.

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.