Intermediate Trading Tutorial — Confirmed Volume-Weighted Candle Body Direction in NinjaTrader 8
Counting bullish and bearish candles gives each bar the same influence, whether it contains ten contracts or ten thousand. That may be useful for studying frequency, but it does not describe how recorded volume is distributed across candle directions. This tutorial builds a native NinjaScript indicator that assigns each completed candle's volume a sign according to its body direction, then normalizes the signed sum by total volume across a rolling window. The result is a bounded oscillator with an explicit zero reference. It is important to distinguish this statistic from actual bid/ask volume delta: the indicator does not classify individual trades or identify aggressive buyers and sellers.
Define the weighted measurement
For each candle, define its sign as +1 when Close exceeds Open, −1 when Close is below Open, and zero when they are equal. Multiply the sign by recorded bar volume. Add the signed volumes across N completed candles and divide by the sum of their unsigned volumes. A positive result means more recorded volume belonged to bullish-bodied candles than bearish-bodied candles. A negative result means the reverse. Equal-open-close candles contribute to the denominator but not the numerator. For nonnegative volume and a positive total, the result lies between −1 and +1. A zero denominator is unavailable rather than neutral.

Manual calculation and window updates
Set Period to three. Suppose candle A opens at 100, closes at 102 and records volume 100. Candle B opens at 102, closes at 101 and records volume 300. Candle C opens at 101, closes at 103 and records volume 200. Their signed contributions are +100, −300 and +200. The total signed contribution is zero, while the unsigned total is 600. The weighted oscillator therefore equals zero. An unweighted body-sign average would instead equal (1−1+1)/3, or approximately +0.3333.
Now suppose candle D opens and closes at 103 with volume 100. The window advances to B, C and D. The numerator becomes −300+200+0 = −100 and the denominator becomes 300+200+100 = 600. The result is approximately −0.1667. Notice that the doji has not been silently omitted from total volume. If a later window contains only dojis with positive volume, its score is zero. These observations are hypothetical and are not evidence of market performance.
Complete native NinjaScript source
using System;
using System.ComponentModel.DataAnnotations;
using System.Windows.Media;
using NinjaTrader.NinjaScript;
namespace NinjaTrader.NinjaScript.Indicators
{
public class PSVolumeWeightedBodyDirection : Indicator
{
[NinjaScriptProperty]
[Range(1, 10000)]
[Display(Name = "Period", Order = 1,
GroupName = "Parameters")]
public int Period { get; set; }
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Name = "PSVolumeWeightedBodyDirection";
Description = "Closed-bar volume-weighted body sign.";
Calculate = Calculate.OnBarClose;
IsOverlay = false;
Period = 20;
BarsRequiredToPlot = 0;
AddPlot(Brushes.SteelBlue, "Direction");
AddLine(Brushes.Gray, 0, "Zero");
}
}
protected override void OnBarUpdate()
{
// In OnBarClose mode, index zero is completed.
if (CurrentBar < Period - 1)
{
Value.Reset();
return;
}
double signed = 0.0;
double total = 0.0;
for (int i = 0; i < Period; i++)
{
double v = Volume[i];
if (v < 0.0 || double.IsNaN(v) ||
double.IsInfinity(v))
{
Value.Reset();
return;
}
// A doji contributes to total but not signed volume.
if (Close[i] > Open[i])
signed += v;
else if (Close[i] < Open[i])
signed -= v;
total += v;
}
if (total <= 0.0)
{
Value.Reset();
return;
}
Value[0] = signed / total;
PlotBrushes[0][0] = Value[0] > 0
? Brushes.SeaGreen : Value[0] < 0
? Brushes.IndianRed : Brushes.SteelBlue;
}
}
}
Implementation and the NinjaScript lifecycle
State.SetDefaults configures the indicator name, separate chart panel, period, calculation mode and plot. The Range attribute limits the parameter to positive practical values. NinjaScriptProperty makes it an indicator input. The code sets Calculate.OnBarClose explicitly so that standalone chart calculations evaluate completed bars. A plot and zero reference line make the output easy to interpret, while PlotBrushes assigns colors individually according to the sign of each reading.
CurrentBar is a zero-based index, so Period minus one is the earliest eligible calculation index. The loop reads exactly Period observations from the bars-ago series. It uses double accumulators to avoid integer truncation and resets the plot when volume is invalid or the denominator is not positive. A valid zero reading is distinct from an unset plot. If another program consumes this output, check the plot's validity rather than assuming that every returned zero is meaningful.
The loop recomputes the window directly instead of maintaining mutable sums. Its cost is proportional to Period, but it is straightforward to audit and insensitive to duplicate calculation calls with unchanged input data. A rolling accumulator could reduce normal update cost, although its implementation would have to account for historical recalculation, bar replacement, and repeated evaluations. For ordinary research windows the simpler approach is a reasonable starting point. If hosting the indicator inside another NinjaScript object, configure that host to calculate on bar close as well: the parent calculation mode can govern embedded indicators. This example assumes a single primary bar series and ordinary nonnegative bar volume.
Installation and inspection
Open the NinjaScript Editor in NinjaTrader 8, create a new indicator named PSVolumeWeightedBodyDirection, and replace its user-authored indicator class with the source above. Retain or allow the platform to regenerate its standard generated access code. Compile in the editor and resolve diagnostics in your installed version. Add the indicator to a chart and set Period to three for the worked example or another appropriate research window. Inspect the Data Box and verify the zero line and the plot colors. The source has not been compiled or executed in NinjaTrader here.
Closed-bar timing and repainting
During an active candle, both volume and the relationship between open and close can change. A positive signed contribution could become negative before the candle ends. With OnBarClose, the formula is evaluated after bar completion according to NinjaTrader's event scheduling; in live markets confirmation may depend on the arrival of the next tick or bar. The plot is aligned with the completed candle, not with an earlier intrabar decision point. Do not change the calculation mode to OnEachTick without redesigning the confirmation rule. Historical data corrections, reconstructed bars, or different session templates can legitimately change the result, although the formula does not intentionally reference future prices or repaint finalized data.
Testing and practical boundaries
First reproduce the four-candle example in a spreadsheet. Test a window of only bullish bars, only bearish bars, only dojis with positive volume, and zero total volume. Expected valid extremes are +1 and −1. Check the first eligible index and compare historical and live completed-bar values using the same dataset. Verify that no provisional candle contribution is displayed in the intended mode. Compare volume definitions across providers and instruments: exchange volume, tick volume and other feed-specific quantities are not interchangeable. A high score does not establish actual buying pressure, and a low score does not guarantee a reversal. Session boundaries and isolated high-volume observations can dominate the statistic. Evaluate any proposed threshold on independent samples and account for transaction costs.
For rolling-sum optimization, configurable doji handling, alerts or integration with NinjaScript strategies, contact our Custom NinjaTrader indicator Development Services.
Risk disclosure: educational material only. Trading involves risk of loss. Hypothetical examples do not demonstrate profitability.