Advanced Trading Tutorial | Pine Script v6 | A closed-bar measure of directional midpoint crossings
A candle can finish higher than it opened without overcoming an important reference price. Conversely, a small candle can cross a meaningful boundary despite having little absolute movement. The prior bar's midpoint is a simple reference that is already known when the next candle begins. This tutorial constructs a signed indicator that distinguishes upward and downward open-to-close crossings of that reference, then measures their balance over a rolling window. It is a descriptive price-structure tool, not an entry system.
What the indicator measures
For each evaluated candle, calculate M = (previous high + previous low) / 2. If its open is strictly below M and its close strictly above M, count one upward reclaim. If its open is strictly above M and its close strictly below M, count one downward crossing. All other usable observations are neutral. The word reclaim here describes endpoints on opposite sides; it does not imply an order-book event or a confirmed reversal of a larger trend.
The window contains the last N completed candles. Let U and D be the number of upward and downward events and V the number of usable observations. The balance is 100 × (U − D) / V. Its theoretical range is −100 to +100. Unlike a ratio based only on crossing events, this denominator retains information about how frequently the pattern occurs. One upward event among twenty usable candles produces +5, not +100. A neutral candle contributes to V but not U or D. When V is zero the result is undefined and the script plots no value.
A five-bar hypothetical example
Consider five observations with previous midpoints of 100, 101, 100, 102 and 103. The first candle opens at 98 and closes at 102, an upward event. The second opens at 103 and closes at 99, a downward event. The third opens and closes at 99, both below its midpoint. The fourth moves from 101 to 104 across its midpoint of 102. The fifth opens exactly at 103 and closes at 105; equality is neutral under our strict rule. Assume all previous ranges pass the minimum threshold.

With U = 2, D = 1 and V = 5, the output is +20%. The result does not mean the instrument rose 20%, nor does it indicate a 20% probability of success. It means upward crossings exceeded downward crossings by one observation per five usable candles. If the third candle had an unusable reference range, V would fall to four and the result would become +25%, even though the two event counts were unchanged. The valid-count output is therefore important context.
Complete Pine Script v6 indicator
//@version=6
indicator("Prior Midpoint Reclaim Balance", overlay=false, max_bars_back=502)
int n = input.int(20, "Completed bars", minval=2, maxval=500)
int minTicks = input.int(1, "Minimum prior range (ticks)", minval=1)
float up = 0.0
float down = 0.0
int valid = 0
// Start at offset 1: never include the forming bar.
if bar_index >= n + 1
for i = 1 to n
float ph = high[i + 1]
float pl = low[i + 1]
float mid = (ph + pl) / 2.0
bool usable = not na(open[i]) and not na(close[i]) and not na(mid) and ph - pl >= minTicks * syminfo.mintick
if usable
valid += 1
if open[i] < mid and close[i] > mid
up += 1
else if open[i] > mid and close[i] < mid
down += 1
// Neutral bars contribute to the denominator.
float balance = valid > 0 ? 100.0 * (up - down) / valid : na
color shade = balance > 0 ? color.teal : balance < 0 ? color.red : color.gray
plot(balance, "Balance (%)", color=shade, style=plot.style_histogram, linewidth=3)
hline(0, "Neutral", color=color.gray)
plot(valid, "Valid bars", display=display.data_window)
plot(up, "Up reclaims", display=display.data_window)
plot(down, "Down reclaims", display=display.data_window)
The script explicitly loops over historical offsets 1 through N. For each offset i, the reference is taken from i + 1, not from the evaluation candle itself. The extra historical observation is required because the oldest candle in the rolling window also needs its own reference. An explicit history buffer supports the bounded input. The valid-count filter excludes missing input values and previous ranges smaller than the specified number of minimum ticks. The output is recalculated on each execution, but only from confirmed earlier candles. No persistent counter is needed, which avoids accidentally adding the same observation multiple times during realtime updates.
Installation and chart configuration
Open a standard candlestick chart in TradingView and select Pine Editor. Create a new indicator, replace the template with the complete source above, save it under a recognizable name and add it to the chart. The histogram appears in a separate pane, with green indicating positive balance and red indicating negative balance. The Data Window provides counts to audit the calculation. The example is written for Pine Script v6; it has been reviewed against the language documentation, but has not been compiled in a live TradingView editor here.
The default length is 20 completed bars and the minimum reference range is one tick. A 5-minute chart therefore uses the last twenty available 5-minute candles rather than a fixed number of clock minutes across session gaps. Set length to five to reproduce the illustrative arithmetic using matching hypothetical data. Shorter windows react quickly but can produce abrupt changes when one event enters or leaves the sample. Longer windows emphasize persistent behavior and may obscure a recent change in directional character. The minimum range input can suppress tiny reference candles, but increasing it also changes which observations are counted. Review V before comparing settings.
Interpretation without hindsight
The histogram is deliberately aligned to the bar on which the completed history becomes available. At the opening of a new realtime bar the preceding candle is final, so the indicator can incorporate that candle immediately. It does not attempt to backdate its value onto that earlier candle. In a historical review, a positive bar in the indicator pane therefore summarizes price action that took place before the plotted bar began. No negative offsets, higher-timeframe lookahead or current-bar closing values enter the calculation.
A positive reading during a rising market can describe repeated recovery through the previous reference level. A negative reading can describe the opposite tendency. Neither necessarily confirms continuation: a volatile sideways market may generate alternating crossings, and a powerful trend can yield very few crossings because candles consistently open and close on the same side. Near zero, both counts might be low or both might be high and balanced. Open the Data Window to distinguish these cases. Treat midpoint balance as an additional observation alongside market structure, liquidity and volatility, not as a stand-alone forecast.
Validation checklist
- Compare five manually classified candles with the reported counts and percentage.
- Test a candle opening exactly at the reference, and one closing exactly at it; both must be neutral.
- Verify that an unusable previous range reduces V without contributing either event.
- Check the warm-up region: the first valid calculation requires N + 1 previous bars.
- Use replay and observe that the histogram does not change on every tick within a forming candle when the prior data remains unchanged.
- Switch to a different symbol and inspect its minimum tick size, session settings and available history.
Limitations and practical extensions
Session breaks may cause a candle to open far from the previous midpoint. This implementation treats such openings by the same endpoint rules as other candles; it does not separately identify overnight gaps. Synthetic chart types may supply transformed OHLC values instead of actual traded prices. Use ordinary candles for comparisons with raw OHLC data. Feed corrections, corporate actions and changed session settings can alter historical inputs, so completed-bar logic is not a guarantee that all historical data remains immutable. For a session-specific variant, exclude comparisons crossing session boundaries and recalculate the denominator consistently. A separate event-frequency output, 100 × (U + D) / V, could help distinguish quiet from highly contested conditions.
If this free indicator is useful and you would like session-aware filtering, alerts or integration with an existing analytical workflow, explore our Custom TradingView indicator Development Services.
Risk disclosure: This indicator and the hypothetical illustration are educational. They do not establish profitability, predict future returns or provide investment advice. Test with representative data and account for execution costs before relying on any trading method.