ta.barssince is a Pine Script function that counts how many bars have passed since a specified condition last returned true. Pass it any boolean test — close > open, ta.crossover(fast, slow), whatever you need — and it returns an integer: 0 if the condition fired right now, 1 if one bar ago, 2 if two, and so on. If the condition never triggered, you get na.
I've been writing Pine Script for about three years, and ta.barssince keeps showing up in almost every script I build. During the August 2024 selloff on AAPL, I used it to enforce a 5-bar cooldown between RSI-based entries. That one line saved me from averaging into a falling knife. On a weekly SPY chart I track bars since the last all-time high to guess whether the trend is getting long in the tooth. Not everything worked. I tried the same trick for mean reversion on TSLA and the lag was brutal — by the time ta.barssince said "condition met," the move was already done.