Intermediate Trading Tutorial | MultiCharts | PowerLanguage Custom Indicator

Volatility measures often combine rising and falling price changes into a single number. That is useful for measuring overall movement, but it can hide an important distinction: whether large positive or negative returns contributed most of the recent variability. A market with a series of modest gains and one sharp decline may have more positive bars than negative bars, yet most of its squared-return energy may come from the decline. This tutorial develops a PowerLanguage oscillator that measures the downside share of squared close-to-close percentage returns. It is a descriptive statistic, not a prediction of losses or a substitute for a complete risk model.

Define the return sample

Use simple percentage returns between consecutive completed closes. If C is the more recent close and P the previous close, the return is 100 × (C/P − 1). Both prices must be strictly positive. Take N consecutive completed returns, square each return, and sum all squared values to obtain T. Separately sum the squares of only the negative returns to obtain D. When T is positive, the indicator is 100 × D/T. The default window contains 20 returns, and therefore requires 21 completed closing prices.

Squaring the return makes a large observation contribute disproportionately more than a small one. A move of −3% contributes nine squared percentage-point units, whereas a move of −1% contributes one. Positive returns contribute to the denominator but not the numerator. Zero returns add nothing to either sum. The output is bounded between zero and 100, and a result of 50 means the two directions contributed equally to the total squared-return sum.

A four-return example

Suppose the four latest completed percentage returns, ordered from oldest to newest, are +1%, −3%, +2% and −1%. Their squared contributions are 1, 9, 4 and 1. The total is 15, and the negative returns contribute 9 + 1 = 10. The resulting downside share is 100 × 10/15 = 66.666…%. There are two negative and two positive returns, but the downside accounts for two-thirds of the squared-return total.

MultiCharts PowerLanguage Downside Squared Return Share Indicator on Completed Bars
Figure 1. Four hypothetical returns contribute fifteen squared percentage-point units in total; ten come from negative returns. The downside share is approximately 66.67%.

Contrast this with a frequency statistic, which would report two negative returns out of four, or 50%. The downside share is sensitive to the magnitude of movement, not only its sign. The example also illustrates why the output does not estimate the probability of a decline: 66.67% describes the historical squared contributions, not the chance of a future negative return.

Complete PowerLanguage source

{ PatternSmart: downside share of squared returns.
  Set MaxBarsBack manually to at least Length + 1.
  Uses only completed bars; output is on the following bar. }

Inputs: Length(20);

Variables:
    idx(0),
    retPct(0),
    retSq(0),
    downSq(0),
    totalSq(0),
    validWindow(False),
    sharePct(0);

downSq = 0;
totalSq = 0;
validWindow = False;

If Length >= 1 and Length <= 500 and
   Length = IntPortion(Length) then
begin
    validWindow = True;

    For idx = 1 to Length begin
        { Close[1] is the latest completed candle. }
        If Close[idx] > 0 and Close[idx + 1] > 0 then
        begin
            retPct = 100 * (Close[idx] / Close[idx + 1] - 1);
            retSq = retPct * retPct;
            totalSq = totalSq + retSq;

            If retPct < 0 then
                downSq = downSq + retSq;
        end
        else
            validWindow = False;
    end;
end;

If validWindow and totalSq > 0 then
begin
    sharePct = 100 * downSq / totalSq;
    Plot1(sharePct, "DownShare");
end
else
    NoPlot(1);

Plot2(50, "Half");

Bar indexing and calculation timing

PowerLanguage uses square-bracket offsets to access historical values. Close[0], or Close, refers to the bar being evaluated. Close[1] is the preceding bar, and Close[2] is the one before that. This version always starts its loop at offset one, so the newest return uses Close[1] and Close[2]. At the default length of 20, the oldest return uses Close[20] and Close[21]. No value from the developing bar enters the return sample.

The result is plotted on the following chart bar, which is the bar on which the indicator can first evaluate the completed sample when intrabar updating is enabled. On a chart configured to calculate only at bar close, that same observation is available at the following bar's closing calculation instead. This intentional timing distinction should be documented when consuming the output from a trading system. Do not shift the plot backward to imply that an observation was available before its input data were known.

Set the indicator's MaxBarsBack manually to at least Length + 1 because the code indexes historical closes using a loop variable. With the default length of 20, set it to at least 21. If you increase the input to 100, increase the history requirement to at least 101. Alternatively, setting 501 covers all permitted window sizes at the expense of a longer initial history requirement. The platform's automatic detection should not be assumed to infer every dynamic historical offset correctly.

Installation in MultiCharts

  1. Open PowerLanguage Editor and create a new Indicator, not a Signal.
  2. Name the indicator PSDownsideReturnShare and insert the complete source.
  3. Compile it, resolve any diagnostics, then add it to a standard time-based chart.
  4. Open its study properties and set MaxBarsBack to the appropriate manual value. Configure a separate subchart for the percentage scale.
  5. Set the line styles and colors to distinguish the calculated series from the 50% reference. Enable intrabar updating if you want the prior completed sample evaluated as soon as the next bar begins.

Choosing the window

Length Behavior
5 Highly responsive to individual large moves; unstable across short samples.
20 (default) A moderate observation window for illustrating the calculation.
100 More historical context, but slower adjustment when older large moves leave the window.

The same length represents different elapsed times on different chart resolutions. A 20-bar sample on a five-minute chart is not equivalent to 20 daily returns. This implementation includes consecutive chart closes across session boundaries, so overnight gaps can contribute significantly. A session-only variant would need to define whether to exclude cross-session returns and how to handle the resulting sample size.

Validation before integration

  • Test the four-return example and confirm approximately 66.67%.
  • Use a window containing only positive nonzero returns and verify zero; with only negative nonzero returns the expected output is 100.
  • Use equal-magnitude positive and negative returns and verify 50.
  • Test a completely flat sample: the denominator is zero and Plot1 must be unavailable, not zero.
  • Verify that the live bar's price changes do not enter the sample until it becomes a completed historical bar.
  • Increase Length and confirm the manually configured history requirement is adequate.

Limitations and extensions

This statistic divides uncentered squared returns according to their signs. It is related to the idea of decomposing return variation into positive and negative components, but it is not a sample variance calculated around the mean, an annualized volatility estimate, or the conventional downside deviation relative to a target return. It also discards the absolute size of total movement: a small negative return in an otherwise flat window can yield 100 just as a substantial decline can. A separate total-volatility measure may help distinguish such cases.

The code assumes valid, positive closing prices and is not intended for spreads or instruments whose prices can cross zero. A price discontinuity caused by an unadjusted split or futures roll can dominate the statistic. Review data quality and contract adjustment policies before drawing conclusions. The platform keyword reference was checked on a best-effort basis; the source has not been compiled or live-tested in MultiCharts. Validate it against your version of PowerLanguage and chart settings. This educational example does not place orders or constitute investment advice. Trading involves risk of loss.

If you are interested in this free indicator and would like a session-aware version, a companion total-volatility plot or a customized strategy filter, contact us through our Custom Trading Software Development Services.

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.