Trading Tips — Tracking Volatility Compression Streaks in cTrader

A single narrow candle is often unremarkable. Several consecutive candles with unusually small ranges, however, describe a different kind of market environment: a persistent contraction in observed intrabar price movement. Conventional volatility indicators usually report a magnitude or a smoothed average, not the duration of a particular condition. This tutorial develops a native cTrader C# indicator that counts consecutive completed candles whose ranges fall below a configurable fraction of their own preceding average range. It is intended to support market-structure research, not to issue orders or forecast the direction of a breakout.

Define the compression event

For each completed candidate candle, calculate its high minus low. Calculate the arithmetic mean of the same range measurement over the N candles immediately preceding that candidate. Divide the candidate range by the earlier mean. If the ratio is strictly below a threshold such as 0.80, classify the candle as compressed. A value of 0.80 means that the candidate range must be less than 80 percent of the preceding mean; equality does not qualify. When the baseline is zero or unavailable, the observation is undefined.

The baseline must not include the candidate itself. Including the candle would allow its unusually small range to lower the average against which it is being tested. The reference used here is the simple high-low range, not true range or ATR. It measures intrabar movement and deliberately excludes gaps between bars.

Volatility Compression Streak Indicator
Six hypothetical range ratios with a threshold of 0.80. The consecutive compression count progresses as 0, 1, 2, 3, 0 and 1. The fifth observation resets the streak.

Worked examples

Assume that six successive candidate candles have ratios of 0.95, 0.65, 0.55, 0.70, 1.10 and 0.60 against their respective earlier averages. With the threshold set to 0.80, the classifications are false, true, true, true, false and true. Their streak counts are therefore zero, one, two, three, zero and one. These ratios are illustrative derived observations, not a claim about recorded market prices. The earlier average may differ for every candidate as the reference window advances.

For a separate numerical example, suppose the preceding three candle ranges are 8, 10 and 12 points. Their mean is 10. A candidate range of 7 yields a ratio of 0.70 and qualifies. A candidate range of exactly 8 yields 0.80 and does not qualify. A zero-range candle qualifies when its reference mean is positive, whereas a zero reference mean makes the ratio undefined. If this happens, the implementation breaks continuity and starts any subsequent valid compression streak from one.

Complete native cTrader C# indicator

using cAlgo.API;
using cAlgo.API.Indicators;

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

        [Parameter("Compression Ratio", DefaultValue = 0.8,
                   MinValue = 0.01, MaxValue = 1.0)]
        public double Threshold { get; set; }

        [Output("Streak", LineColor = "DodgerBlue", PlotType = PlotType.Histogram)]
        public IndicatorDataSeries Streak { get; set; }

        public override void Calculate(int index)
        {
            // Candidate is the last completed bar.
            int c = index - 1;
            if (c < Period)
            {
                Streak[index] = double.NaN;
                return;
            }

            // Baseline excludes the candidate and the forming bar.
            double sum = 0.0;
            for (int j = c - Period; j < c; j++)
                sum += Bars.HighPrices[j] - Bars.LowPrices[j];

            double mean = sum / Period;
            if (mean <= 0.0)
            {
                Streak[index] = double.NaN;
                return;
            }

            double range = Bars.HighPrices[c] - Bars.LowPrices[c];
            bool compressed = range / mean < Threshold;

            // Derive state from the previous index, not a tick counter.
            double previous = Streak[index - 1];
            if (double.IsNaN(previous))
                previous = 0.0;
            Streak[index] = compressed ? previous + 1.0 : 0.0;
        }
    }
}

Why index-based state matters

Unlike reverse-indexed price arrays on some other trading platforms, cTrader uses chronological indexes in its Calculate callback. The code sets the candidate index to index minus one, deliberately excluding the developing candle. The baseline starts at candidate minus Period and ends at candidate minus one. The first output requires Period earlier reference candles plus the candidate itself.

The most important implementation detail is how the streak is updated. Calculate can execute repeatedly for the last chart index as incoming prices change. A persistent integer incremented on every call would accidentally count ticks as new candles. This source instead reads Streak[index-1] and assigns the current output from that earlier value. Repeated evaluations of the same index do not accumulate additional counts. The state is thus associated with bar positions rather than callback frequency. The previous value is treated as zero when it is undefined, ensuring that a missing reference does not silently connect two otherwise independent streaks.

The direct summation requires O(N) work per calculation. This is straightforward for moderate periods, and keeps the reference window easy to audit. A larger deployment might replace the loop with a rolling sum, but the optimized implementation must preserve the same exclusion of the candidate candle and handle recalculation correctly.

Installation

Open cTrader Algo and create a new C# indicator named VolatilityCompressionStreak. Replace the generated class with the source, build the project and attach the indicator to a chart. The histogram appears in a separate panel. Begin with Baseline Period 20 and Compression Ratio 0.8. Adjust the parameters to study different reference windows and classification frequencies, not to assume that the defaults are profitable. The code has not been compiled or run in cTrader here; confirm the build and behavior in your installed version before deployment.

Closed-bar timing and repainting

The value drawn at index t describes the candidate at t−1. The latest completed candle becomes eligible when a new candle is recognized. This produces a deliberate one-bar alignment difference between the plotted timestamp and the final input candle. While the current candle develops, its high and low cannot change the input window under ordinary data updates. The implementation contains no future references or centered calculations and does not intentionally repaint confirmed values. Historical corrections, loading additional earlier history and changes to bar construction can still change a recalculated historical streak. In particular, a streak near the beginning of a finite history may be truncated by the available warm-up data.

Testing and interpretation

Check the six-ratio example by manually following the classification and counter logic. On a real chart, calculate candidate ranges and earlier means independently. Test ratios below, equal to and above the threshold, a zero baseline and multiple consecutive compressed candles. Observe repeated updates of a forming candle to confirm that the counter does not increase on every tick. Reload the chart with matching history and session settings and compare the results. A streak measures the number of qualifying bars, not elapsed clock time. On irregular or synthetic charts, equal counts may correspond to very different durations.

Persistent compression does not guarantee imminent expansion or a profitable breakout. A streak can be common during quiet sessions or periods of low liquidity, and the rolling baseline may itself shrink as narrow candles enter the reference window. A reset can therefore occur even without a large absolute expansion. The indicator does not capture volume, spread, transaction costs, overnight gaps or breakout direction. Any additional filters should be tested on independent data, and the threshold should not be selected solely because it produced favorable historical outcomes.

For adaptive thresholds, true-range variants, alerts or integration into a cBot, contact our Custom cTrader indicator Development Services.

Risk disclosure: educational material only. Trading involves risk of loss. Hypothetical examples do not demonstrate 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.