Advanced Trading Tutorial — TradingView Pine Script v6 indicator development
Breakout indicators often answer whether price has crossed a recent boundary, but they rarely describe the spacing between successive confirmed breakouts. A market that establishes new closing breakouts every few bars behaves differently from one that requires dozens of bars to do so. The Breakout Interval Monitor measures this spacing separately for upper and lower breakouts. It turns a sequence of discrete price events into a simple stateful time series, useful for exploratory market-structure research and for learning how to manage persistent variables in Pine Script without relying on intrabar signals.
Design the event before counting its interval
For each candidate bar, calculate the highest high and lowest low of the preceding N bars. The candidate itself must not participate in either boundary. In the source, ta.highest(high[1], length) and ta.lowest(low[1], length) enforce this exclusion. The default reference window contains twenty bars. An upper event requires the candidate close to exceed the prior upper boundary by at least the configured minimum extension in price ticks. A lower event requires the close to finish below the prior lower boundary by that amount. The default minimum is one tick, calculated from syminfo.mintick. Both events require a confirmed bar and sufficient reference history.
This event definition is intentionally different from an intrabar high or low breaking a boundary. A candle can trade above the upper boundary and then close back inside the range; it does not count. A consecutive series of qualifying closes can create consecutive events. The script does not require a return inside the range or a crossover from below. That choice allows a sustained sequence of new price extremes to register a short event interval. If your research requires separate breakout episodes rather than individual qualifying bars, an additional reset rule is needed.
Measure elapsed bars, not the size of the breakout
Maintain independent persistent variables for the bar index of the most recent upper and lower events. When a new event occurs, subtract the previous index of the same direction from the current bar index. Store the result as the most recent completed interval. The first event in either direction establishes an anchor but cannot produce an interval, because no earlier event of that type has been observed. Between events, the most recent completed interval remains unchanged. This is not a time-since-last-event oscillator: such an oscillator would increase on every intervening bar. Here the output answers how many bars separated the last two observed events of the selected direction.
Worked example
Suppose upper breakout conditions are satisfied on bars 20, 23 and 28, with no other upper events between them. The first upper event at bar 20 initializes its anchor. At bar 23, the interval becomes 23 minus 20, or three bars. The value remains three until the event at bar 28, when it updates to five. The lower event history is unaffected, even if a lower event occurs between these upper events. This example assumes the preceding reference bars exist and every marked event has met the close and minimum-extension conditions. It illustrates the timing arithmetic, not a forecast.

Complete Pine Script v6 source
//@version=6
indicator("Breakout Interval Monitor", overlay=false)
length = input.int(20, "Reference bars", minval=2, maxval=500)
minTicks = input.int(1, "Minimum extension ticks", minval=1)
mode = input.string("Both", "Display",
options=["Both", "Upper", "Lower"])
// Exclude the candidate from the rolling reference.
upper = ta.highest(high[1], length)
lower = ta.lowest(low[1], length)
ready = not na(high[length]) and not na(low[length])
extension = minTicks * syminfo.mintick
upEvent = barstate.isconfirmed and ready and
close > upper and close - upper >= extension
downEvent = barstate.isconfirmed and ready and
close < lower and lower - close >= extension
var int lastUp = na
var int lastDown = na
var int upGap = na
var int downGap = na
// Store intervals only after a confirmed event.
if upEvent
upGap := na(lastUp) ? na : bar_index - lastUp
lastUp := bar_index
if downEvent
downGap := na(lastDown) ? na : bar_index - lastDown
lastDown := bar_index
showUp = mode != "Lower"
showDown = mode != "Upper"
plot(showUp ? upGap : na, "Upper interval",
color=color.teal, style=plot.style_stepline, linewidth=2)
plot(showDown ? downGap : na, "Lower interval",
color=color.red, style=plot.style_stepline, linewidth=2)
plotshape(showUp and upEvent, title="Upper event",
style=shape.triangleup, location=location.bottom,
color=color.teal, size=size.tiny)
plotshape(showDown and downEvent, title="Lower event",
style=shape.triangledown, location=location.top,
color=color.red, size=size.tiny)
Installation and reading the plots
Open a TradingView chart and select Pine Editor. Create a new indicator, replace the sample script with the complete source above, save it, and select Add to chart. The indicator appears in its own pane. The teal step line displays the most recently completed upper interval and the red step line displays the lower interval. The small triangles identify qualifying events, including the first event before an interval becomes available. Use the Display input to hide either direction without altering the calculations. The underlying state is still maintained independently for both directions. The source is supplied for local validation; it has not been compiled in a TradingView session for this article.
Confirmed-bar execution and persistence
Pine Script indicators normally evaluate the realtime bar repeatedly as new updates arrive. The barstate.isconfirmed condition prevents event anchors from changing during those intermediate executions. On historical bars the condition is true, and on a realtime bar the update is made on its closing execution. Persistent variables declared with var retain the committed values between bars. The script does not need varip because it does not accumulate intrabar changes. It uses only current confirmed information and earlier bars, without request.security, future indexing or a centered reference window. Consequently, it does not intentionally revise previous event decisions based on later prices.
Historical calculations still depend on the available dataset. If additional earlier history becomes available, the first observable event anchor may move earlier, altering the earliest displayed interval. Corporate action adjustments, session settings, data corrections and changes to chart type can also affect event detection. These are data and initialization effects rather than evidence of a future-looking calculation. When comparing different chart sessions, ensure that the same symbol, timeframe and history are being used.
Parameter tradeoffs
A shorter lookback makes the rolling boundaries more responsive, potentially producing more events and shorter intervals. A longer reference window can require a more substantial historical extreme to be exceeded, often making events less frequent. Increasing the minimum tick extension eliminates some marginal closes but may be disproportionately restrictive for quiet instruments. The tick rule standardizes price increments rather than volatility or economic value. For comparisons across instruments, consider independently evaluating a volatility-normalized extension rule. That would be a new event definition and should be tested as such.
The interval itself is expressed in chart bars rather than minutes. Five bars on a five-minute chart do not necessarily represent exactly twenty-five minutes of elapsed clock time when a session gap intervenes. On range-based or other non-time-based charts, the distinction is even more important. If wall-clock duration matters, replace the index difference with a carefully specified timestamp calculation and decide how to handle overnight closures.
Validation checklist
- Confirm the reference window excludes the candidate bar and contains the intended number of preceding bars.
- Test an intrabar excursion that closes inside the boundary; no event should appear.
- Verify that the first event produces a marker but no interval.
- Reproduce the bar 20, 23 and 28 example and check the independent lower state.
- Test consecutive qualifying bars, which should produce a one-bar interval.
- Observe an open realtime bar and verify that the stored interval changes only when an event is confirmed.
- Reload matching chart history and compare the event sequence after its initial anchors are established.
Limitations and further development
Event intervals are descriptive, not estimates of the probability or expected time of the next breakout. Short intervals can occur in a strong trend or during repeated volatile excursions, and a long interval does not guarantee an impending move. The last measured interval can become stale during an extended period without events. A companion age measure or a distribution of historical intervals may provide additional context. If you would like to adapt the event definition, add alerts, or incorporate the feature into a custom indicator, contact us through our Custom TradingView indicator Development Services.
Trading involves risk of loss. The worked example is hypothetical, and the indicator does not place orders or establish a profitable strategy. Verify the code, market data and any derived decision rules independently before live use.