Intermediate Trading Tutorial | Sierra Chart ACSIL C++ indicators

A candle with an eight-tick range may represent an unusually active bar in one trading session and an ordinary observation in another. A fixed range threshold cannot distinguish these circumstances without constant recalibration. A percentile comparison offers a different approach: instead of asking how large the current range is in absolute terms, ask where it ranks among recent completed ranges. This tutorial develops a free Sierra Chart ACSIL indicator that compares the most recently completed candle against a separate historical reference window, handles tied ranges explicitly, and publishes the result without relying on the forming candle. The resulting statistic describes relative range expansion, not a prediction of price direction.

Specify the comparison window

The candidate is the preceding completed candle. Its reference window contains N candles immediately before it, excluding the candidate itself. Use the high-low range rather than true range because the research question concerns the interval covered by each candle, not gaps between closes and subsequent highs or lows. Convert each range to ticks by dividing by the chart tick size and rounding to the nearest whole tick. For ordinary tick-aligned OHLC data this removes small floating-point differences that might otherwise prevent equal-sized ranges from being recognized as ties.

Count the reference ranges strictly smaller than the candidate as B, and the reference ranges equal to it as T. The percentile score is 100 × (B + 0.5 × T) / N. Assigning half credit to ties is a midrank-style empirical percentile convention. It differs from counting all equal observations as smaller or excluding them entirely. A candidate smaller than every reference receives zero, one larger than every reference receives 100, and an all-equal reference window with a matching candidate produces 50.

Worked example: a candidate of eight ticks

For clarity, set the reference length temporarily to five. Suppose the five preceding completed ranges are 3, 5, 8, 10 and 12 ticks. Their chronological order is not required for the percentile formula, although the original time sequence determines which bars enter and leave the rolling reference window. The candidate range is eight ticks.

Reference range Comparison with candidate Rank contribution
3 Smaller 1
5 Smaller 1
8 Equal 0.5
10 Larger 0
12 Larger 0

Build a Closed-Bar Range Shock Percentile Indicator in ACSIL
Figure 1. Two reference ranges are smaller, one is tied and two are larger. The dashed blue line represents the eight-tick candidate. The midrank score is 100 × 2.5 / 5 = 50%.

With the same reference sample, a candidate of thirteen ticks produces 100 because every reference is smaller. A two-tick candidate produces zero because no reference is smaller or equal. If the candidate is ten ticks, three references are smaller and one is equal, producing 70. These values are hypothetical calculation examples. In live operation the reference window moves as new completed bars become candidates. The reference distribution therefore changes over time.

Complete ACSIL study source

#include "sierrachart.h"
#include <cmath>

SCDLLName("PatternSmart Range Shock Percentile")

SCSFExport scsf_PSRangeShockPercentile(SCStudyInterfaceRef sc)
{
    SCSubgraphRef Score = sc.Subgraph[0];
    SCInputRef Length = sc.Input[0];

    if (sc.SetDefaults)
    {
        sc.GraphName = "PS Range Shock Percentile";
        sc.StudyDescription = "Midrank percentile of the last completed range.";
        sc.AutoLoop = 1;
        sc.GraphRegion = 1;

        Score.Name = "Range Percentile";
        Score.DrawStyle = DRAWSTYLE_LINE;
        Score.PrimaryColor = RGB(58, 99, 201);
        Score.LineWidth = 2;
        Score.DrawZeros = true;

        Length.Name = "Reference Bars";
        Length.SetInt(20);
        Length.SetIntLimits(1, 500);
        return;
    }

    const int n = Length.GetInt();
    const int i = sc.Index;
    sc.DataStartIndex = n + 1;

    // Candidate = prior bar; references precede the candidate.
    if (i < n + 1 || sc.TickSize <= 0.0f)
    {
        Score[i] = 0.0f;
        return;
    }

    const int candidate = i - 1;
    const long long candidateTicks = std::llround(
        (static_cast<double>(sc.High[candidate]) -
         static_cast<double>(sc.Low[candidate])) / sc.TickSize);

    int below = 0;
    int ties = 0;
    for (int j = i - 2; j >= i - n - 1; --j)
    {
        const long long referenceTicks = std::llround(
            (static_cast<double>(sc.High[j]) -
             static_cast<double>(sc.Low[j])) / sc.TickSize);

        if (referenceTicks < candidateTicks)
            ++below;
        else if (referenceTicks == candidateTicks)
            ++ties;
    }

    // Equal ranges receive half a rank.
    Score[i] = static_cast<float>(
        100.0 * (below + 0.5 * ties) / n);
}

Understand AutoLoop and the one-bar offset

The SetDefaults section describes the study, configures an independent graph region, and creates an adjustable reference length. The default is twenty bars, while the five-bar illustration is deliberately shorter for manual verification. With AutoLoop enabled, Sierra Chart sets sc.Index to the bar currently being calculated. The study uses index i − 1 as the candidate and indices i − 2 through i − N − 1 as references. This requires N + 1 earlier bars before any valid calculation can be made.

sc.DataStartIndex specifies where the study's valid drawing region begins. Initial array entries are assigned zero but are outside that drawing region. A valid percentile of zero must remain visible, which is why DrawZeros is enabled. A valid tick size is a prerequisite: if the chart has no usable tick size, the implementation returns a zero placeholder, not a meaningful percentile. Check chart configuration before interpreting the output. The source assumes valid tick-aligned prices and a positive tick size; synthetic data that do not follow tick increments require a deliberately chosen alternative comparison convention.

The value is plotted on the bar after the candidate, rather than backdated onto the candidate. As the current bar develops, its high and low cannot affect the calculation because no input uses index i. This avoids intrabar fluctuations caused by the forming candle. It does not imply that a historical output was available before the calculation bar began, nor does it protect against corrections to historical OHLC data. When another study or trading system consumes the output, ensure its timing matches this explicit alignment.

Build and install in Sierra Chart

  1. Save the complete source as PSRangeShockPercentile.cpp in the ACS_Source directory.
  2. Open Analysis → Build Custom Studies DLL, select the source, and use the available build method in your installation.
  3. Open the Studies window on your chart, select Add Custom Study, and locate PS Range Shock Percentile in the resulting DLL.
  4. Initially set Reference Bars to five, and locate a sequence of six completed ranges to verify by hand.
  5. Compare the manually computed percentile with the displayed value on the next bar. Restore the default twenty-bar reference length for further research.

The implementation uses the ACSIL study interface and standard C++ rounding. It has not been compiled or run in a Sierra Chart installation for this article. Confirm the build, chart tick size and calculation behavior locally before operational use.

Parameter selection and performance

Short reference windows react rapidly but yield coarse rank increments. With five references, a single strictly smaller observation changes the score by twenty points, and a tie contributes ten. With twenty references, the corresponding increments are five and 2.5 points. Longer windows offer finer rank resolution but can retain obsolete volatility conditions after a session transition or structural change. The formula weights every reference equally, so one extremely large reference counts as one observation just like a moderately large one.

The direct loop requires O(N) comparisons per calculation and avoids sorting the historical window. This is straightforward for normal chart studies. If the study is applied to many high-frequency charts, performance should be measured before introducing more complex rolling frequency tables. A histogram-based implementation could reduce repeated comparisons but must maintain the same tick conversion, candidate exclusion, tie convention and history boundary.

Validation and interpretation

Test all-equal samples, a candidate strictly above or below all references, several ties, flat candles and insufficient history. Verify that a matching all-zero reference window yields 50; this is a valid rank convention, not evidence of trading activity. Check that the score remains within zero and 100 and does not change simply because the current bar expands. Compare full recalculation with normal updates using identical underlying chart data.

A high percentile does not describe the magnitude of the excess range, nor does it distinguish bullish from bearish moves. A candidate one tick above the largest reference and one hundreds of ticks larger both produce 100. Fixed-range or other synthetic bars may show little variation by design. Session boundaries and bar construction also affect the reference distribution. For an actual trading rule, use independently tested price context, activity filters and risk controls, accounting for costs and out-of-sample performance.

If you would like session-specific references, separate true-range ranks, alerts, or integration into another ACSIL study, contact us for Custom Sierra Chart indicator Development Services.

Risk disclosure: This tutorial is educational and does not constitute investment advice. Hypothetical calculations do not establish profitability. Trading involves risk of loss.

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.