Advanced Trading Tutorial — NinjaTrader 8 custom indicator development

Closing prices within a rolling window may cluster near their average while a few observations extend far above or below it. A simple count of closes above the average ignores how far those observations are from the center. Standard deviation measures total dispersion but does not identify which side contributes more. Close Dispersion Balance separates squared deviations above the window mean from total squared deviations, producing a bounded descriptive measure of asymmetry. This tutorial develops a native NinjaScript indicator that evaluates the completed bar without generating orders or claiming to forecast future returns.

Define the feature precisely

Take N consecutive closing prices ending at the candidate candle. Calculate their arithmetic mean. For every close, subtract that same mean and square the difference. Sum all squared differences to form the denominator. Sum only squared differences whose original difference is strictly positive to form the numerator. The output is one hundred times the numerator divided by the denominator. All observations are centered on the same window mean; they are not compared with different historical moving averages. This distinction makes the feature a decomposition of within-window dispersion rather than a measure of moving-average crossovers.

The default period is twenty completed bars. A positive denominator gives a result between zero and one hundred. A symmetric distribution of deviations has a score of fifty, although fifty does not prove the distribution is symmetric. When every close is identical, total dispersion is zero. The implementation adopts fifty as an explicit neutral convention for that case rather than dividing by zero. A separate validity flag could distinguish a flat window from an evenly balanced nonflat window in a more elaborate implementation.

Worked example

Consider four hypothetical closes: 97, 99, 100 and 104. Their mean is 100. Deviations are -3, -1, 0 and +4. Their squares are 9, 1, 0 and 16, respectively. The total is 26 and the above-mean contribution is 16. With Period set to four, the indicator reports approximately 61.54%. Although only one close is strictly above the mean, it accounts for more than half of squared dispersion. Counting above-mean closes would instead produce 25%, demonstrating why the two statistics answer different questions.

Close Dispersion Balance Indicator: Measuring Asymmetric Squared Deviations
Red and green bars show signed deviations from the common mean. The calculation squares their magnitudes; 16 of 26 squared units belong to the upper side.

Complete NinjaScript indicator

using System;
using System.ComponentModel.DataAnnotations;
using System.Windows.Media;
using NinjaTrader.NinjaScript;

namespace NinjaTrader.NinjaScript.Indicators
{
    public class CloseDispersionBalance : Indicator
    {
        protected override void OnStateChange()
        {
            if (State == State.SetDefaults)
            {
                Name = "CloseDispersionBalance";
                Description = "Share of squared close deviations above the window mean.";
                Calculate = Calculate.OnBarClose;
                IsOverlay = false;
                BarsRequiredToPlot = 0;
                Period = 20;
                AddPlot(Brushes.RoyalBlue, "Balance");
                AddLine(Brushes.Gray, 50, "Neutral");
            }
        }

        protected override void OnBarUpdate()
        {
            if (CurrentBar < Period - 1)
            {
                Value.Reset();
                return;
            }

            // Center all observations on the same window mean.
            double sum = 0;
            for (int i = 0; i < Period; i++)
                sum += Close[i];
            double mean = sum / Period;

            double upper = 0, total = 0;
            for (int i = 0; i < Period; i++)
            {
                double d = Close[i] - mean;
                double square = d * d;
                total += square;
                if (d > 0)
                    upper += square;
            }

            // A constant window has no dispersion.
            Value[0] = total > 0 ? 100 * upper / total : 50;
        }

        [NinjaScriptProperty]
        [Range(2, 1000)]
        [Display(Name = "Period", Order = 1, GroupName = "Parameters")]
        public int Period { get; set; }
    }
}

Installation in NinjaTrader 8

Open the NinjaScript Editor from the Control Center. Create an indicator named CloseDispersionBalance and replace the user-authored class with the supplied code. If the editor has generated integration wrappers, allow NinjaTrader to manage and regenerate them rather than manually creating duplicate wrappers. Compile and resolve any environment-specific issues before adding the indicator through the chart Indicators dialog. The blue plot shows the balance and the gray horizontal line marks fifty. The indicator is designed for Calculate.OnBarClose. Keep that calculation setting when comparing chart output with the examples. No terminal compilation has been performed for this tutorial.

How to interpret the number

A reading above fifty means that observations above the common mean contribute a larger share of squared dispersion than those below it. This can happen when a few unusually high prices are separated from a cluster of lower prices. A reading below fifty indicates that negative deviations dominate squared dispersion. Neither case specifies the direction of the next bar. The same collection of prices produces exactly the same score regardless of their chronological order. For instance, reversing the four-close example leaves the result unchanged even though its apparent price trajectory changes dramatically. If chronological direction matters, use an independently defined trend or path measure.

Choosing the observation period

A small window responds quickly when an extreme close enters or leaves it. However, with exactly two distinct observations, the deviations around their mean have equal magnitude and the result is always fifty. A period of two is technically valid but rarely informative for this statistic. Twenty observations provide a more varied sample. Increasing the period may reduce the impact of a single routine fluctuation while also retaining an older extreme for longer. Squaring magnitudes intentionally makes outliers influential; it does not guarantee robustness. If an application requires resistance to outliers, a separate absolute-deviation or winsorized version may be considered and documented as a different feature.

Calculation timing and performance

OnBarUpdate uses Close[0] through Close[Period-1]. Under the default OnBarClose setting, Close[0] is the bar being processed at completion. There is no centered future window and no access to negative bars-ago indices. The first Period minus one bars are explicitly reset because the sample is incomplete. Each calculation uses two passes over the window, with linear work in Period and constant auxiliary storage. This straightforward implementation avoids persistent rolling state and is easy to compare with a spreadsheet. For very large watchlists or periods, a carefully tested rolling-moment implementation may be faster, but subtracting nearly equal sums of squares can introduce numerical cancellation. Do not change the method merely for theoretical speed without measuring the actual workload.

Validation before integration

  • Set Period to four and reproduce the 61.54% worked example.
  • Reverse the same closes and verify that the result is unchanged.
  • Check a symmetric set such as 98, 99, 101, 102; the output should be fifty.
  • Check a constant window and confirm the explicit neutral convention.
  • Confirm that incomplete history does not produce a valid plotted value.
  • Compare the latest completed output against an independent spreadsheet and repeat after reloading identical data.
  • Test session boundaries, price adjustments and different chart types. If a parent strategy controls calculation frequency, verify the effective update timing separately.

Limitations and further development

The feature describes the distribution of close levels rather than returns, volume or intrabar execution. It can be dominated by an isolated extreme, and overlapping windows are statistically dependent. Price corrections and chart construction changes can alter historical values. The neutral line is not a calibrated trading threshold. If you want a custom validity flag, additional distribution measures, or integration into an existing NinjaTrader strategy, contact us through our Custom NinjaTrader indicator Development Services.

Trading involves risk of loss. The example is hypothetical and the source has not been tested in a live terminal. Validate data, calculations and execution assumptions independently before using any derived rule in live trading.

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.