Intermediate Trading Tutorial | TradingView | Pine Script v6

A chart can contain many rising candles while still showing relatively weak net candle-body movement. Counting green candles treats a tiny positive body and a large positive body as identical observations. Averaging individual body-to-range ratios has a different limitation: a narrow candle can receive the same weight as a very wide one. In this tutorial we build a signed candle-body balance oscillator that measures net open-to-close movement relative to the sum of candle ranges in a rolling window. The indicator reports confirmed chart-bar values only and includes adjustable visual reference levels.

Define the statistic before interpreting it

For each candle, define the signed body as close minus open. A bullish body is positive, a bearish body is negative, and a doji contributes zero. Define the full candle range as high minus low. Over N consecutive candles, calculate 100 multiplied by the sum of signed bodies divided by the sum of full ranges. The default N is 20. Provided the price data are internally consistent and total range is positive, the statistic is between −100% and +100%.

A positive value means positive bodies outweigh negative bodies in aggregate relative to total range; a negative value means the opposite. A result near zero can arise from small bodies, opposing bodies cancelling one another, or both. It does not mean that the market was quiet. The denominator is a sum of bar ranges, not a distance travelled by price or a true range incorporating prior closes. The numerator does not include the price gaps between candles.

Worked example: three completed candles

Suppose the first candle has open 100, high 104, low 100 and close 103. Its full range is 4 and signed body is +3. The second has open 103, high 104, low 101 and close 102, giving range 3 and body −1. The third has open 102, high 106, low 101 and close 104, giving range 5 and body +2. With a three-bar window the total range is 12 and the net body is +4. The output is 100 × 4 / 12 = +33.333…%.

TradingView Pine Script v6 Signed Candle Body Balance Indicator on Confirmed Bars
Figure 1. The three candle ranges sum to 12 and the signed bodies sum to +4. Their ratio produces a balance of +33.33%.

An unweighted mean of the three individual body-to-range ratios would instead be (75% − 33.33% + 40%) / 3, approximately +27.22%. Our statistic weights each nonzero-range candle by its share of the total range. Thus a large candle has greater influence than a tiny candle. This distinction is essential when comparing outputs from different indicators with similar names.

Complete Pine Script v6 indicator

//@version=6
indicator("PatternSmart Signed Body Balance", shorttitle="PS SBB", overlay=false, precision=2)

int length = input.int(20, "Window", minval=1, maxval=1000)
float level = input.float(25.0, "Reference level", minval=0.1, maxval=100.0)

// Require internally consistent, nonmissing OHLC.
bool valid = not na(open) and not na(high) and not na(low) and not na(close) and high >= math.max(open, close) and low <= math.min(open, close)

float body = valid ? close - open : 0.0
float span = valid ? high - low : 0.0

// Run rolling calculations on every execution.
// Count valid bars so invalid placeholders cannot enter a result.
float bodySum = math.sum(body, length)
float rangeSum = math.sum(span, length)
float validCount = math.sum(valid ? 1.0 : 0.0, length)

bool ready = bar_index >= length - 1 and validCount == length and rangeSum > 0.0

// Output only when the current chart bar is confirmed.
float balance = barstate.isconfirmed and ready ? 100.0 * bodySum / rangeSum : na

color columnColor = balance > 0 ? color.teal : balance < 0 ? color.red : color.gray
plot(balance, title="Signed body balance (%)", style=plot.style_columns, color=columnColor, histbase=0)
hline(0, "Zero", color=color.gray)
hline(level, "Positive reference", color=color.teal, linestyle=hline.style_dashed)
hline(-level, "Negative reference", color=color.red, linestyle=hline.style_dashed)

Why the rolling sums execute unconditionally

The three math.sum calls run on every script execution, not only inside an if block that executes at bar close. They calculate rolling sums of signed bodies, ranges and the number of valid observations. Invalid bars contribute temporary zeros to the sums, but the separate validCount condition prevents any window containing them from producing a value. This avoids relying on a function's missing-value behavior to determine the effective observation count.

The bar_index check ensures that at least N chart bars exist. A zero-range candle with consistent OHLC is a valid observation and contributes zero to both sums. An entirely flat window has a zero denominator, so the output is unavailable rather than zero. Do not confuse these cases: zero balance is a meaningful measurement of cancellation or zero net body within a positive-range window, whereas an unavailable value means the formula could not be evaluated under its stated rules.

Confirmation and realtime execution

TradingView indicators normally execute on updates to the realtime bar. High, low and close can change until that bar is confirmed. The code calculates its provisional rolling inputs but plots a value only when barstate.isconfirmed is true. On historical bars, the confirmation condition is true; on the open realtime bar it becomes true at the closing update. The plot appears on the completed candle itself, not one candle later.

Do not move the calculation into a higher-timeframe request and assume the same confirmation condition will work there. This example deliberately uses the chart's own timeframe and no request.security calls, negative offsets or future data. It also does not promise identical values after a data provider revises historical prices or a user changes chart type. Synthetic OHLC charts, such as Heikin Ashi, measure their transformed candles rather than the underlying raw market candles.

Installation and practical settings

  1. Open a regular candlestick chart in TradingView and select Pine Editor.
  2. Create a new indicator, replace the editor contents with the source above, and save it.
  3. Add it to the chart and inspect its separate pane. The default 20-bar window displays green positive columns, red negative columns and a gray zero reference.
  4. Set the window to three to reproduce the worked example by hand using chart OHLC data.
  5. Switch back to a representative window and compare different market conditions with the Data Window.

Input Default Interpretation
Window 20 Short windows respond more quickly to individual candles; long windows capture a broader sample but may smooth changes.
Reference level 25% Draws symmetric guide lines. Changing it does not alter the underlying calculation.

For a one-bar window, the formula reduces to the signed body-to-range ratio whenever the bar has positive range. For longer windows, it emphasizes the net directional contribution of bodies relative to total bar range. A threshold of 25% is illustrative, not a universal signal. The same threshold may behave differently on one-minute and daily charts, or on assets with different trading hours and liquidity.

Validation checklist

  • Confirm the example produces approximately +33.33%, and reversing the body signs produces −33.33%.
  • Check a window of full-range positive bodies with no wicks: its theoretical result is +100%; full-range negative bodies produce −100%.
  • Test equally sized opposing bodies: the net result should be zero when the denominator is positive.
  • Check an all-flat window: the value must remain unavailable.
  • Watch an open realtime candle: no new column should appear until confirmation.
  • Change the reference level and confirm that existing numerical values do not change.

Limitations and responsible interpretation

This oscillator uses OHLC geometry, not actual order-flow imbalance, signed volume, bid-ask delta or buying and selling pressure measured from trade executions. It cannot distinguish between an orderly trend and a single dominant candle, and a gap between adjacent bars can cause close-to-close performance to diverge from the statistic. It does not place orders, estimate execution costs or manage risk. Inspect the underlying price structure and test the formula independently rather than treating a reference-line crossing as a validated entry rule.

Official Pine Script documentation for bar states and rolling sums was reviewed; the source has not been compiled or live-tested for this article. Confirm its operation in your Pine Editor before using it. This tutorial is educational and not investment advice. Trading involves a risk of loss.

If you are interested in this free indicator and want session resets, a different weighting method, confirmed alerts or strategy integration, please 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.