Intermediate Trading Tutorial | cTrader Algo | C# Custom Indicator
Two adjacent candles can have identical high-to-low ranges while occupying entirely different price intervals. One pair may revisit nearly the same territory; another may move into a new price region with little or no overlap. Comparing candle sizes alone cannot distinguish these situations. This tutorial builds a cTrader indicator that measures the intersection of two completed candle ranges relative to their union. It provides a bounded geometric statistic for examining how much consecutive price intervals overlap, with an explicit closed-bar calculation policy.
Measure the common interval, not just the candle sizes
Represent each candle as a continuous price interval from its low to its high. For adjacent candles A and B, the common interval starts at the larger low and ends at the smaller high, provided that the end exceeds the start. Its length I is max(0, min(high A, high B) − max(low A, low B)). The lengths of the individual intervals are high A minus low A and high B minus low B.
The union length U is the sum of the two interval lengths minus their intersection. Subtracting the intersection avoids counting shared territory twice. The overlap percentage is 100 × I / U whenever U is positive. This is an interval intersection-over-union measurement. It is dimensionless and symmetric: exchanging A and B does not change the result. Identical positive-width intervals produce 100%; disjoint intervals produce zero.
Worked example: partial overlap
Assume the earlier candle has a low of 100 and a high of 106. The next completed candle has a low of 103 and a high of 108. Their widths are 6 and 5. The shared price interval extends from 103 to 106, giving a length of 3. The union length is 6 + 5 − 3 = 8. Consequently, the overlap is 100 × 3 / 8 = 37.5%.

Now consider a small interval of 102 to 104 contained within the earlier range of 100 to 106. Although every point in the small interval is contained in the larger one, the overlap percentage is only 2 / 6 × 100, or approximately 33.33%. A metric that divides by the smaller range would return 100% instead. That alternative measures containment rather than symmetric similarity. The distinction matters when comparing indicators that use different denominators.
For disjoint intervals such as 100–102 and 105–107, the intersection is zero and the union length is 4, not the enclosing span of 7. Both denominators would give zero overlap in this particular case, but the union definition is clearer and consistent with the underlying geometry.
Complete cTrader C# source
// PatternSmart: adjacent completed candle range overlap
using System;
using cAlgo.API;
namespace cAlgo.Indicators
{
[Indicator(IsOverlay = false, TimeZone = TimeZones.UTC,
AccessRights = AccessRights.None)]
public class PSClosedRangeOverlap : Indicator
{
[Output("Overlap (%)", LineColor = "RoyalBlue",
PlotType = PlotType.Line, Thickness = 2)]
public IndicatorDataSeries Result { get; set; }
public override void Calculate(int index)
{
// Historical bars can be evaluated directly.
if (index < Bars.Count - 1)
{
Result[index] = OverlapAt(index);
return;
}
// The last available bar may still be forming.
Result[index] = double.NaN;
// A new bar confirms its predecessor.
if (index >= 1)
Result[index - 1] = OverlapAt(index - 1);
}
private double OverlapAt(int index)
{
if (index < 1)
return double.NaN;
double h0 = Bars.HighPrices[index];
double l0 = Bars.LowPrices[index];
double h1 = Bars.HighPrices[index - 1];
double l1 = Bars.LowPrices[index - 1];
if (!Finite(h0) || !Finite(l0) ||
!Finite(h1) || !Finite(l1) ||
h0 < l0 || h1 < l1)
return double.NaN;
// Length of the common price interval.
double intersection = Math.Max(0.0,
Math.Min(h0, h1) - Math.Max(l0, l1));
// True union length excludes any gap between intervals.
double union = (h0 - l0) + (h1 - l1) - intersection;
if (!Finite(union) || union <= 0.0)
return double.NaN;
return 100.0 * intersection / union;
}
private bool Finite(double value)
{
return !double.IsNaN(value) &&
!double.IsInfinity(value);
}
}
}
How the implementation confirms a candle
Unlike a calculation mode that executes only at bar close, an indicator's Calculate method may be called repeatedly for the latest bar. The index argument is an absolute position in the Bars collection, not a number of bars ago. During ordinary historical calculations, an index strictly before the last available bar is already followed by another bar. The program can calculate its value directly using that index and its predecessor.
The last available bar is treated as potentially incomplete. The indicator deliberately writes NaN to that position. It then recalculates the previous position, ensuring that the formerly developing candle receives its final value as soon as a successor is available. Repeated ticks in the same newest candle may recompute the previous result, but they do not incorporate the developing candle's high or low. This avoids the common problem of displaying an apparently confirmed number that fluctuates with live prices.
This policy waits for a following bar to exist, so a last candle at a session boundary can remain blank until a new bar is created. On illiquid instruments the delay may be noticeable. This is a deliberate conservative confirmation policy, not a guarantee of an immediate signal at a scheduled clock time. The code does not subscribe to trading events or execute orders.
Installation and visual inspection
- Open cTrader desktop and select the Algo section.
- In Indicators, create a new C# indicator named PSClosedRangeOverlap.
- Replace the editable source with the complete code, build it and review diagnostics.
- Add the indicator to a conventional time-based candlestick chart.
- Inspect two adjacent historical bars and calculate their intersection and union manually. Compare the value with the separate indicator pane.
There are no tunable calculation inputs in this version. The reference window is exactly two adjacent candles, the denominator is the union length, and confirmation requires a successor bar. This keeps the example easy to audit. A threshold such as 70% could be used as an exploratory classification level, but it is not a built-in threshold and has no validated universal meaning.
Boundary cases worth testing
| Prior range | Next range | Expected |
|---|---|---|
| 100–106 | 103–108 | 37.5% |
| 100–106 | 100–106 | 100% |
| 100–106 | 102–104 | 33.33% |
| 100–102 | 102–104 | 0% (touch only) |
| 100–102 | 105–107 | 0% |
| 100–100 | 100–100 | Unavailable |
A touching boundary has zero shared length in the continuous interval definition. A zero-width candle paired with a positive-width candle also produces zero overlap, even when the point falls inside the other interval. If both intervals have zero width, their union length is zero and the output remains unavailable. Invalid or nonfinite prices and reversed high-low ordering are rejected.
Validation and possible extensions
- Confirm that the first historical candle has no result, since it has no predecessor.
- Reproduce the numerical cases above using chart data or a separate calculation harness.
- Observe the latest candle through several ticks: its output must remain blank.
- When a new candle begins, verify that the previous candle receives its completed result.
- Compare calculations after a chart reload using the same underlying price history.
- Check that exchanging the two input intervals gives the same mathematical result.
An average of recent overlap percentages would reduce sensitivity to single pairs, but averaging introduces choices about window length and missing data. Another extension could separate overlapping intervals by their relative vertical displacement, so rising and falling price regions are distinguishable. Neither is implemented here. The basic calculation requires a fixed number of operations per evaluated bar and no rolling array allocation.
Interpretation and risk
High overlap can occur in a consolidating market, but it can also occur during a trend with wide candles. Low overlap may reflect displacement, a gap, or a small candle relative to a much larger one. The statistic has no directional sign and does not measure trade volume, actual executed price distribution, or probability of a breakout. A high-low interval does not prove that every price inside it traded. Changes to historical data or synthetic chart construction can revise results despite the closed-bar policy.
The official cTrader Algo documentation for Indicator.Calculate, IndicatorDataSeries and the standard indicator code samples was reviewed. This code has not been compiled or live-tested in cTrader for this article. Verify the calculation in your own terminal before using it in another program. This educational example is not investment advice; trading involves risk of loss.
If you are interested in this free indicator and would like a rolling overlap filter, directional classification, or cBot integration, please contact us through our Custom Trading Software Development Services.