You wrote an indicator that marks a moving average cross, and on the chart it looks fine until you zoom out. In a choppy stretch the same cross fires four times in six bars, the markers stack on top of each other, and your alert fires four times for what is really one event. The fix most people reach for is a cooldown: do not fire again until a few bars have passed. Pine Script has a function built for counting those bars, ta.barssince(), and it is also the quickest way to answer questions like "how long has it been since RSI was oversold?" or "how many bars has this position been open?"
This guide covers what ta.barssince() returns, the na case that catches almost everyone, three working patterns (a quiet-period filter, a true cooldown, and a time-based exit), and the mistakes that make the function behave strangely. Every code block is Pine Script v6 and complete, so you can paste it into the Pine Editor and run it.
What ta.barssince() returns
The signature is short: ta.barssince(condition) → series int. You give it a boolean series, and on every bar it returns how many bars have passed since that condition was last true. If the condition is true on the current bar, the result is 0. If it was true on the previous bar, the result is 1, and so on. The count keeps growing until the condition is true again, at which point it resets to 0.
The simplest way to see this is to plot it. The script below counts bars since the last green candle, so on a run of red candles the plot climbs one step per bar and drops to zero the moment a green candle prints.
//@version=6
indicator("ta.barssince basics", overlay=false)
greenCandle = close > open
barsSinceGreen = ta.barssince(greenCandle)
plot(barsSinceGreen, "Bars since green candle", style=plot.style_columns)Two details matter here. First, the return type is an integer series, so you can compare it, subtract from it, and use it as an offset like any other series int. Second, it counts bars, not time. On a 4-hour chart a value of 6 means 24 hours; on a daily chart it means six days. If you need a cooldown that means the same wall-clock time on every timeframe, convert it with timeframe.in_seconds() instead of hard-coding a bar count.
The na case you must handle
If the condition has never been true since the start of the chart's history, ta.barssince() returns na. This is the single most common source of bugs with this function, because na does not behave like zero or like a big number.
In Pine Script, any comparison involving na evaluates to false. So ta.barssince(raw) >= 5 is false on every bar before the first trigger, which is probably what you want if you are asking "has enough time passed since the last one?" but exactly wrong if you are asking "may I fire now?" before anything has ever fired. On the first trigger of the chart, the cooldown test fails and the first real event is silently swallowed.
The defensive pattern is to test for na explicitly with na(), and decide what the empty case means. For a cooldown, "never fired" means "free to fire", so the condition reads na(since) or since >= cooldown. For a display value, you probably want to show a placeholder instead of a number. We will use both patterns below. Our guide to how Pine Script handles na goes deeper on why it spreads through calculations without raising an error.
Pattern 1: a quiet-period filter
The first way to use ta.barssince() is to require silence before a trigger counts. Here the rule is: a moving average cross only counts if no other cross happened in the previous N bars. That removes the clusters of back-to-back crosses you get in sideways price action, and keeps the first cross after a calm stretch.
//@version=6
indicator("Quiet period filter", overlay=true)
maLen = input.int(20, "MA length", minval=2)
quietBars = input.int(5, "Quiet bars", minval=1)
ma = ta.sma(close, maLen)
rawCross = ta.crossover(close, ma)
// Bars since the previous bar's raw cross, i.e. bars with no cross in between
sinceEarlier = ta.barssince(rawCross[1])
quiet = na(sinceEarlier) or sinceEarlier >= quietBars
trigger = rawCross and quiet
plot(ma, "MA", color=color.orange)
plotshape(rawCross and not trigger, "Suppressed", style=shape.xcross, location=location.belowbar, color=color.gray, size=size.tiny)
plotshape(trigger, "Trigger", style=shape.triangleup, location=location.belowbar, color=color.teal, size=size.small)Notice that the script measures rawCross[1], the previous bar's value, rather than rawCross itself. If you measured the current bar, ta.barssince(rawCross) would be 0 on exactly the bar where the cross happens, and the test would compare the cross to itself. Shifting by one bar means the function reports how long the chart was quiet before this bar. A result of quietBars or more means at least that many bars passed with no cross between the two events.
This version has one property you should know about: the quiet period is measured from the last raw cross, whether or not it was accepted. If crosses keep arriving every three bars with a quiet requirement of five, none of them ever pass, because each suppressed cross restarts the clock. Sometimes that is what you want, a strict "wait for calm" rule. When it is not, you need the second pattern.
Pattern 2: a true cooldown after an accepted trigger
A cooldown is different from a quiet period. It starts counting only when a trigger was actually accepted, and ignores everything that was suppressed. In that case you cannot use ta.barssince() on the final trigger directly, because the trigger depends on the cooldown, which depends on the trigger, and Pine Script does not allow a series to reference itself that way.
The clean solution is to store the bar index of the last accepted trigger in a var variable and compare it with bar_index. This is still the same idea as counting bars since, just maintained by hand. If var is new to you, we cover how persistence works in our post on var, varip, and persistent state.
//@version=6
indicator("Cooldown after accepted trigger", overlay=true)
maLen = input.int(20, "MA length", minval=2)
cooldown = input.int(8, "Cooldown bars", minval=1)
ma = ta.sma(close, maLen)
rawCross = ta.crossover(close, ma)
var int lastTrigger = na
canTrigger = na(lastTrigger) or bar_index - lastTrigger >= cooldown
trigger = rawCross and canTrigger
if trigger
lastTrigger := bar_index
plot(ma, "MA", color=color.orange)
plotshape(trigger, "Trigger", style=shape.triangleup, location=location.belowbar, color=color.teal, size=size.small)
alertcondition(trigger, "Cooldown trigger", "Moving average cross accepted after cooldown")Run both patterns on the same chart and the difference is visible. The quiet-period version can go dark for long stretches in a choppy market. The cooldown version always lets a trigger through eight bars after the last accepted one, if a raw cross happens by then. Pick the quiet period when you want to avoid noisy regimes entirely, and the cooldown when you only want to space out accepted events.
One more thing worth saying plainly: neither pattern makes a rule better or worse. They change how often your conditions fire, and nothing more. Whether the filtered version is any use is a question for testing on data, which is why it helps to step through it bar by bar before you trust it. Our post on checking a Pine Script before and after it goes live walks through that.
Pattern 3: time-based exits and a bars-in-trade counter
The other everyday use is measuring how long a position has been open. A common rule is to close a trade after a fixed number of bars if neither exit has been reached, so capital is not tied up in a trade that has gone nowhere.
//@version=6
strategy("Time-based exit example", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=10)
maLen = input.int(20, "MA length", minval=2)
maxBars = input.int(10, "Max bars in trade", minval=1)
ma = ta.sma(close, maLen)
entryCondition = ta.crossover(close, ma)
if entryCondition and strategy.position_size == 0
strategy.entry("Long", strategy.long)
// Compute outside any if block so it runs on every bar
justOpened = strategy.position_size > 0 and strategy.position_size[1] == 0
barsHeld = ta.barssince(justOpened)
if strategy.position_size > 0 and barsHeld >= maxBars
strategy.close("Long", comment="Time exit")
plot(ma, "MA", color=color.orange)The condition justOpened is true on the single bar where the position size goes from zero to positive. From then on barsHeld reads 0, 1, 2, ... for as long as the trade is open. When no trade has ever opened, barsHeld is na, and na >= maxBars is false, so nothing closes by accident. This is a coding example of how to count, not a suggested rule: choose the number of bars with your own testing. If your strategy sits idle and you cannot see why, our guide on why a strategy is not taking trades lists the usual causes.
For a quick on-chart readout of the same kind of counter, you can draw it on the last bar:
//@version=6
indicator("Bars since last cross readout", overlay=true)
rawCross = ta.crossover(close, ta.sma(close, 20))
since = ta.barssince(rawCross)
if barstate.islast
label.new(bar_index, high, na(since) ? "No cross yet" : "Bars since cross: " + str.tostring(since), style=label.style_label_down)Mistakes that make ta.barssince() misbehave
Calling it inside an if or a ternary. ta.barssince() keeps internal history, and Pine Script needs to run it on every bar to keep that history correct. If you wrap it in if cond or cond ? ta.barssince(x) : na, the compiler warns you about calling a function in a local scope, and the results can be wrong because the function skips the bars where the branch did not run. Always assign the result to a variable at the top level of the script, then use that variable inside your conditionals. The patterns above all do this.
Forgetting the na branch. Covered earlier, but it deserves a second mention because it passes every test you run on a long history and breaks on the very first bar of a short one. If your script looks fine on 5,000 bars but never fires on a freshly listed market with 200 bars, this is the first place to look.
Using it for repainting-sensitive conditions. On a real-time bar, a condition can flip between true and false as price ticks. Because ta.barssince() depends on that condition, the count can change within a bar too, then settle when the bar closes. If a trigger depends on it, gate the trigger with barstate.isconfirmed. We explain exactly when to do that in barstate.isconfirmed in Pine Script.
Expecting it to return a price. It returns a count of bars, nothing else. If you want the value of something at the last trigger, such as the close at the last cross, that is a job for ta.valuewhen(), and our post on ta.valuewhen shows how the two pair up. A frequent combination is using ta.barssince() to know how old a level is and ta.valuewhen() to know what it was.
Using the count as a history offset. You can write close[ta.barssince(cond)] to read the close from the bar where a condition last held, and it works, but it can raise a max_bars_back error when the offset is large or unpredictable. If that happens, see our guide on the max_bars_back error rather than raising the limit blindly.
Where to take it next
Once the counter is working, there are plenty of ways to extend it. You can color a background by how stale the last trigger is, expire a drawn level after N bars, or only allow entries during a window after a higher-timeframe condition. In each case the work is to decide what the condition means, whether "never happened" is allowed, and what should reset the count.
If you would rather describe the rule than write the plumbing, you can paste your existing script into PineScripter and say what you want in plain English, for example "only allow a trigger if at least eight bars have passed since the last accepted one." The AI edits only the lines that change, checks the result for compile errors itself, and you can see the plots on a chart inside the workspace and step through them bar by bar in Replay before copying the script to TradingView. It is a coding tool: it changes how your conditions behave, it does not tell you whether a rule is worth using. See the pricing page for plans.
PineScripter is a coding tool, not a financial advisor. Nothing here is a recommendation to buy or sell, and examples show how to write code, not how to trade. Test any script on your own data before relying on it.
Describe your indicator in plain English and get Pine Script that compiles →
Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.