Intermediate Trading Tutorial | MultiCharts .NET | PowerLanguage C#
When a single unusually large price change enters a rolling sample, the arithmetic average of absolute price changes can increase considerably even if the majority of observations remain small. A median responds differently: it describes the middle of a sorted sample rather than the total magnitude divided by the observation count. This tutorial builds a MultiCharts .NET indicator that compares the median and mean of recent absolute close-to-close changes. It offers a compact descriptive view of the relationship between typical and average movement, while demonstrating historical indexing, configurable windows, plotting and handling unavailable calculations in PowerLanguage C#.
Define the observations precisely
For each pair of adjacent completed closing prices, calculate the absolute difference in price units. The direction of movement is deliberately discarded: an increase of two points and a decrease of two points both contribute an observation of two. Use the most recent N completed changes, which require N+1 completed closing prices. Calculate their arithmetic mean and their median. For an odd sample size the median is the middle sorted observation; for an even sample size it is the average of the two middle observations.
The indicator is 100 × median / mean, provided the mean is positive. A value of 100% means the two statistics coincide. Values below 100% indicate that the median is smaller than the mean; values above 100% indicate the reverse. Unlike a percentile rank, this ratio is not restricted to 0–100%. It should not be clipped at 100. The default sample length is 21, chosen to provide an odd-sized example window with a moderate lookback, not because it is optimal for any market.
Worked example: the effect of a large observation
Suppose six hypothetical closes generate five absolute changes of 1, 1, 2, 2 and 14 price units. The sorted sample is already shown in increasing order. The sum is 20, the mean is 4, and the middle observation is 2. The median-to-mean ratio is 100 × 2/4 = 50%. The large change contributes 70% of the total absolute movement, but the median remains two.

Replace the observation of 14 with 4, leaving the other observations unchanged. The total becomes 10 and both the mean and median are 2, producing 100%. Conversely, a sample of 0, 4 and 4 has median 4 and mean 8/3, producing 150%. A reading above 100 is therefore mathematically legitimate. These examples show that the statistic measures the relationship between two measures of central tendency; it does not identify a unique distribution or quantify the probability of an outlier.
Complete PowerLanguage .NET C# indicator
// PatternSmart: median/mean ratio of absolute close changes.
// Set MaxBarsBack to at least Length + 2.
using System;
using System.Drawing;
namespace PowerLanguage.Indicator
{
public class PSAbsoluteChangeMedianRatio : IndicatorObject
{
private IPlotObject ratioPlot;
private IPlotObject referencePlot;
public PSAbsoluteChangeMedianRatio(object ctx) : base(ctx)
{
Length = 21;
}
[Input]
public int Length { get; set; }
protected override void Create()
{
ratioPlot = AddPlot(new PlotAttributes("MedianMean",
EPlotShapes.Line, Color.RoyalBlue));
referencePlot = AddPlot(new PlotAttributes("Equal",
EPlotShapes.Line, Color.Gray));
}
protected override void CalcBar()
{
referencePlot.Set(100.0);
if (Length < 2 || Length > 500)
{
ratioPlot.Reset();
return;
}
// Offset 1 is completed; offset 0 is never read.
double[] changes = new double[Length];
double sum = 0.0;
for (int i = 1; i <= Length; i++)
{
double a = Bars.Close[i];
double b = Bars.Close[i + 1];
double change = Math.Abs(a - b);
if (!Finite(a) || !Finite(b) || !Finite(change))
{
ratioPlot.Reset();
return;
}
changes[i - 1] = change;
sum += change;
}
if (!Finite(sum) || sum <= 0.0)
{
ratioPlot.Reset();
return;
}
Array.Sort(changes);
int mid = Length / 2;
double median = Length % 2 == 1
? changes[mid]
: 0.5 * changes[mid - 1] + 0.5 * changes[mid];
double mean = sum / Length;
ratioPlot.Set(100.0 * (median / mean));
}
private bool Finite(double x)
{
return !double.IsNaN(x) && !double.IsInfinity(x);
}
}
}
Historical indexing and the indicator lifecycle
MultiCharts .NET indicators are derived from IndicatorObject. The constructor sets the default input, Create defines the plots, and CalcBar evaluates the calculation. Bars.Close[i] uses a historical offset relative to the bar being processed. The loop starts at one rather than zero, so even when the indicator executes on every realtime tick, it never reads the changing current close. The oldest referenced close is at Length+1.
Set the maximum number of referenced bars manually to at least Length+2, using a conservative count that includes the current bar. For the default Length of 21, that means 23 bars. The loop accesses offsets dynamically, and a user should not rely solely on automatic detection to infer this history requirement. The limit of 500 prevents excessively large inputs but is not a performance guarantee. Increasing Length requires checking the historical setting again.
The output is plotted at the current evaluation bar, using the preceding completed sample. When Update on Every Tick is enabled, it can become available on the first update of the new bar. In close-only calculation it becomes available at the following bar's close. This deliberate one-bar indexing policy differs from an indicator that calculates and plots at the candidate candle's closing event. No historical displacement is used to make the result appear available earlier.
Installation and parameter choices
- Open the MultiCharts .NET PowerLanguage editor and create a new C# Indicator called PSAbsoluteChangeMedianRatio.
- Replace its editable source with the code above, compile and review diagnostics.
- Insert the indicator into a chart in a separate subchart.
- Set the maximum referenced bars to at least Length+2 and ensure that enough historical data are loaded.
- Format the blue ratio and gray 100% reference lines. Use the same data series when checking the calculation manually.
| Length | Interpretation | Tradeoff |
|---|---|---|
| 5 | Five absolute changes | Responsive but sensitive to small-sample composition. |
| 21 | Default | Moderate lookback with a single central observation. |
| 100 | Even-sized sample | Broader context but slower removal of older large changes. |
Changing from intraday to daily bars changes the observation horizon. Because the ratio uses absolute price differences in both numerator and denominator, multiplication of every price by the same positive constant leaves the ratio unchanged. That does not make distributions comparable across all timeframes, markets, or session templates. A gap at the next session's open can influence a close-to-close change, as can a futures contract roll or an unadjusted stock split.
Missing values, performance and numerical tests
An all-flat sample has a zero mean, so the ratio plot is reset rather than showing a false zero. A zero median with a positive mean is a valid zero ratio. The source rejects nonfinite closing prices, changes and sums. It does not require prices to be positive because the calculation uses differences rather than percentage returns. Sorting is performed on a new local array for clarity, with roughly O(N log N) work per calculation. On large portfolios or high-frequency charts, a reusable buffer or a more efficient median algorithm may reduce allocations, but any optimization must preserve both median conventions and the same historical sample.
- Check the five-change example and confirm 50%.
- Verify an even sample such as 1, 2, 3, 4: both mean and median are 2.5.
- Test 0, 4, 4 and confirm 150% rather than an artificially capped value.
- Test a completely flat sample and a sample with zero median but positive mean.
- Observe multiple updates of one realtime bar and confirm the ratio is stable for unchanged historical inputs.
- Increase Length and verify that the maximum referenced bars setting is adjusted.
What the ratio cannot tell you
A low reading can be consistent with a large outlying change, but the ratio alone cannot distinguish one extreme observation from several large observations. It does not measure the absolute level of volatility, the direction of price, or the probability of a future price move. Both a quiet and a very volatile market can produce the same ratio. Combine the reading with independent information about absolute movement and data quality if needed.
MultiCharts' official documentation on creating .NET indicators, data access, calculation timing and plot Reset/Set methods was consulted. This example has not been compiled or tested in an actual MultiCharts .NET terminal. Verify it using your version and historical data before integrating it into a trading system. It is educational code, not investment advice; trading involves risk of loss.
If you are interested in this free indicator and would like a rolling median absolute deviation, robust volatility filters or a strategy integration, please contact us through our Custom Trading Software Development Services.