You have an entry rule you trust enough to test, and a stop and a target that already work. Then you notice something in the trade list: a handful of positions that sat open for forty bars, going nowhere, tying up your position while the original reason for the trade quietly expired. You want a rule that says "if this trade has not done its job within N bars, get out." Pine Script has no single exit_after_bars argument, so you have to build it yourself, and the first version most people write is off by one bar or breaks the moment a second entry opens.
This guide builds a bar-count exit properly. We will define what "N bars" means for an order that fills on the next bar, read the entry bar of the open trade with strategy.opentrades.entry_bar_index(), combine the time exit with a stop and a target without the three orders fighting each other, handle pyramided positions, and then check the result in the Strategy Tester so you know the exit does what you intended. Everything here is Pine Script v6.
What a time-based exit does, and why you would add one
A time-based exit closes a position after a fixed number of bars, whatever price is doing. It is not a stop and it is not a target. A stop answers "how wrong can I be?" and a target answers "how right is enough?" A time exit answers a different question: "how long am I willing to wait for the idea to play out?"
That makes it useful for strategies built on short-lived conditions. A mean reversion entry after an oversold reading assumes price snaps back within a few bars. If it has not snapped back in ten bars, the premise is weaker than when you entered, and holding on is a decision to trade a different idea than the one you coded. A breakout entry works the same way: the move should follow through quickly or the breakout has probably failed. A time exit encodes that expectation instead of leaving it to whichever stop or target happens to trigger eventually.
It also changes how you read the Strategy Tester. Without it, the average trade length in your report is whatever the stops and targets happened to produce. With it, you set an upper bound on exposure per trade, which is a cleaner variable to test. You can run the same strategy with a hold limit of 5, 10, and 20 bars and compare the results, as long as you remember that more variations tested means more chances of fooling yourself with a lucky one.
One thing to be clear about before the code: counting bars is not counting clock time. On a 1 hour chart, 24 bars is a day on a market that trades around the clock, but on a symbol with a session break, 24 bars can span a weekend. If you need real elapsed time rather than a bar count, the same approach works with strategy.opentrades.entry_time() and a comparison against time, and we come back to that near the end.
When the clock starts: the next-bar fill
Before writing the counter, you need to decide where it starts, because that is where almost every off-by-one error comes from.
By default a strategy evaluates your script at the close of each bar. If your entry condition is true on bar 100, the script calls strategy.entry() on bar 100, but the order cannot fill at the close that has already printed. It fills at the open of bar 101. So the trade's entry bar, the number strategy.opentrades.entry_bar_index() reports, is 101, not 100.
The exit has the same delay. When your script decides on bar 110 that the trade has lasted long enough and calls strategy.close(), the order fills at the open of bar 111. If you want a trade that spans exactly 10 bars, from the open of bar 101 to the open of bar 111, the script must issue the close on bar 110, when the trade has been open for 9 bars since its entry bar. So the condition is bar_index - entryBar >= holdBars - 1, not >= holdBars.
That - 1 surprises people the first time, and it is easy to forget. The alternative is to use the bare comparison and accept that your "10 bar exit" really holds for 11 bars. Neither choice is wrong, but you should choose it on purpose and write it down in a comment, because six months from now you will not remember which one your script uses. The scripts below use the exact version, so holdBars means the number of bars the trade is exposed to price.
If you want the exit to fill on the close of the final bar instead of the next open, strategy settings include process_orders_on_close, covered in Pine Script process_orders_on_close: Fill on the Signal Bar. With that setting on, the close order fills on the bar where it is issued and the condition becomes >= holdBars. Be careful with it: it makes the backtest fill at prices you can only know after the bar has closed, which a live order cannot always match.
The simplest version: read the entry bar from the open trade
Pine Script v6 gives the strategy a list of open trades and lets you ask about each one. strategy.opentrades is the number of open trades, and strategy.opentrades.entry_bar_index(trade_num) returns the bar index where a given trade was entered. Trade numbers start at 0 for the oldest open trade. With a single open position, the oldest and newest trade are the same one, so the index you want is strategy.opentrades - 1.
Here is a complete strategy that enters long on an EMA crossover and closes after a set number of bars. The EMA crossover is only a placeholder entry so the example compiles and runs on its own. Replace it with your own condition.
//@version=6
strategy("Time Exit After N Bars", overlay=true,
default_qty_type=strategy.percent_of_equity, default_qty_value=10)
int holdBars = input.int(10, "Hold bars", minval=1)
int fastLen = input.int(20, "Fast EMA", minval=1)
int slowLen = input.int(50, "Slow EMA", minval=2)
float fast = ta.ema(close, fastLen)
float slow = ta.ema(close, slowLen)
bool longEntry = ta.crossover(fast, slow)
if longEntry and strategy.position_size == 0
strategy.entry("Long", strategy.long)
if strategy.opentrades > 0
int barsSinceEntry = bar_index - strategy.opentrades.entry_bar_index(strategy.opentrades - 1)
if barsSinceEntry >= holdBars - 1
strategy.close("Long", comment="Time exit")
plot(fast, "Fast EMA", color=color.new(color.teal, 0))
plot(slow, "Slow EMA", color=color.new(color.orange, 0))Read the middle block slowly. The if strategy.opentrades > 0 guard matters: calling entry_bar_index() with no open trade is an error, so you only ask when a trade exists. barsSinceEntry is zero on the entry bar itself (the bar where the order filled), one on the next bar, and so on. When it reaches holdBars - 1 the script issues the close, and the order fills at the next open, completing exactly holdBars bars of exposure.
The comment string "Time exit" shows up next to the exit in the List of Trades, which makes it easy to see later which trades ended because of the clock and which ended some other way. Name your exits. When you review a strategy, the column that tells you why a trade closed is worth more than most of the others.
An alternative: store the entry bar yourself
You do not have to use strategy.opentrades. A common older pattern stores the entry bar in a variable that persists across bars. It is worth knowing because it works in situations where you want to track something other than the trade, such as the bar where a setup condition first appeared, and because you will meet it in scripts written by other people. The persistence works through var, which is explained in var, varip, and Persistent State in Pine Script.
The idea is to detect the moment a position opens, record bar_index once, and clear it when the position is flat. The detection compares the current position size with the previous bar's: a position that is nonzero now and was zero a bar ago has just opened.
Another option is ta.barssince(), which counts bars since a condition was last true, as described in Pine Script ta.barssince: Count Bars Since a Condition. It is tempting here, but it has a trap: ta.barssince(longEntry) counts from the bar where the entry condition was true, which is the decision bar, one bar before the fill. It also keeps counting after the trade closes, and it resets to zero if the condition fires again while a trade is open. Both of those make it a weaker choice than reading the entry bar from the trade itself. If you use it, add the position check, and subtract one to account for the fill delay.
Combining the time exit with a stop and a target
Most real strategies already have a protective stop and a target. The time exit sits alongside them as a third way out. The structure is simple, but there are two details that cause trouble.
First, the stop and target should be placed once relative to the entry, not recomputed every bar from the current ATR. If you write stop = close - atr * 2 inside the exit call and the ATR moves, the stop moves with it, which is a trailing behavior you did not ask for. The script below stores the ATR at the time of entry and uses the trade's average entry price as the reference. For a full treatment of how strategy.exit handles stops, limits, and trails in one call, see Pine Script strategy.exit: Stop, Limit and Trail in One Call.
Second, the stop, the target, and the time exit are all live at the same time, and only one of them can end the trade. Your script issues the time exit on the last bar of the hold, and it fills at the next open. If a stop or target fills first, the position is already flat and the pending close does nothing. Which order fills first on a given bar is decided by TradingView's broker emulator, not by your code, so label every exit with a comment and let the trade list tell you what happened.
//@version=6
strategy("Stop, Target and Time Exit", overlay=true,
default_qty_type=strategy.percent_of_equity, default_qty_value=10)
int holdBars = input.int(10, "Hold bars", minval=1)
float atrMult = input.float(2.0, "Stop distance (ATR multiple)", minval=0.1, step=0.1)
float rewardR = input.float(2.0, "Target (multiple of stop distance)", minval=0.1, step=0.1)
float atr = ta.atr(14)
float rsi = ta.rsi(close, 14)
var int entryBar = na
var float entryAtr = na
bool justOpened = strategy.position_size > 0 and strategy.position_size[1] <= 0
if justOpened
entryBar := bar_index
entryAtr := atr[1]
if strategy.position_size == 0
entryBar := na
entryAtr := na
if ta.crossover(rsi, 30) and strategy.position_size == 0
strategy.entry("Long", strategy.long)
if strategy.position_size > 0 and not na(entryAtr)
float stopPrice = strategy.position_avg_price - entryAtr * atrMult
float targetPrice = strategy.position_avg_price + entryAtr * atrMult * rewardR
strategy.exit("Stop/Target", "Long", stop=stopPrice, limit=targetPrice)
if bar_index - entryBar >= holdBars - 1
strategy.close("Long", comment="Time exit")The justOpened line is the detection described earlier. On that bar the script records bar_index and the ATR from the previous bar, which is the value the script saw when it made the decision to enter. Using atr[1] rather than atr matters because the entry order was placed on the previous bar's close.
After the position closes, the strategy.position_size == 0 block clears both variables, so stale values from a finished trade cannot leak into the next one. This is the same discipline you would apply to any persistent state: set it at a known moment, clear it at a known moment, and never leave a var holding something whose meaning has expired.
If you also want the stop to move to break-even after some profit, that is a separate exit layer with its own traps, covered in Pine Script Break-Even Stop: Move Your Stop After Profit. For a broader look at protective orders, see Stop Loss and Take Profit in Pine Script: A Full Guide.
Pyramiding: one clock per trade
Everything above assumes one open trade at a time. If you set pyramiding above 0, your strategy can hold several entries at once, and a single entryBar variable cannot describe them. The second entry would overwrite the first one's clock, and the oldest trade would be held longer than intended.
The fix is to ask each open trade for its own entry bar and close it individually. Loop over the open trades, and give each entry a unique ID so closing one does not close the others. Closing by a shared ID closes every entry with that ID, which is the opposite of what you want here.
//@version=6
strategy("Per-Trade Time Exit", overlay=true, pyramiding=3,
default_qty_type=strategy.percent_of_equity, default_qty_value=5)
int holdBars = input.int(8, "Hold bars", minval=1)
float basis = ta.sma(close, 20)
bool dip = ta.crossunder(close, basis)
if dip and strategy.opentrades < 3
strategy.entry("L" + str.tostring(bar_index), strategy.long)
if strategy.opentrades > 0
for i = strategy.opentrades - 1 to 0
if bar_index - strategy.opentrades.entry_bar_index(i) >= holdBars - 1
strategy.close(strategy.opentrades.entry_id(i), comment="Time exit")The loop runs from the newest open trade down to trade 0. The if strategy.opentrades > 0 guard is not decoration: a for loop from -1 to 0 would count upward and run twice, so you never want the loop to start when the list is empty. Each trade is closed by its own ID, returned by strategy.opentrades.entry_id(i), so the entries expire independently on their own schedules.
Common mistakes
The first mistake is the off-by-one described earlier. If your 10 bar exit consistently produces trades with 11 bars in the List of Trades, you are comparing with >= holdBars on a next-bar fill. Check one or two trades by hand against the chart before trusting any summary number.
The second is counting the decision bar instead of the entry bar. Anything based on a condition rather than the fill, like a raw ta.barssince(), starts one bar early. The trade's own record is the reliable source.
The third is forgetting that a position can end for other reasons. If a stop or target closes the trade before the time exit, any variable tracking the entry bar must be cleared, or the next trade inherits an old value and may be closed on its first bar. Clearing state when the position is flat prevents this entire class of bug.
The fourth is treating the bar count as time. A 10 bar exit on a daily chart is two trading weeks on a stock and ten calendar days on a market that never closes. If calendar time is what your idea cares about, compare time - strategy.opentrades.entry_time(strategy.opentrades - 1) against a duration in milliseconds, for example holdHours * 3600 * 1000. The bar count and the clock agree only on markets without gaps.
The fifth is over-tuning. It is easy to sweep holdBars from 1 to 50 and pick the best-looking value. The value that wins in one data window is often just the one that fit that window. Pick a small, defensible set of values based on how long your idea is supposed to take, and treat a result that only works at one exact number with suspicion.
Check the result in the Strategy Tester
Adding an exit changes the whole trade list, so verify it in three steps before drawing any conclusion.
Open the List of Trades and look at the exit comments. You should see "Time exit", plus whatever your stop and target orders are named. If no trade ever ends with "Time exit", your hold limit is longer than your stops and targets ever allow, and the exit is dead code. If nearly every trade ends that way, the stop and target are too far away to matter and the time exit is doing all the work.
Then check bars in trade. The Strategy Tester's summary shows the average number of bars in trades, and no trade that ended on the time exit should have a count above holdBars. Spot check two or three by clicking the trade and looking at the chart.
Finally, compare the same strategy with and without the exit, using the same date range and the same settings otherwise. Look at more than net profit: the number of trades, the maximum drawdown, and the average trade all tell you what the exit changed. Pine Script Strategy Tester: Every Metric Explained walks through what each of those numbers does and does not tell you. A time exit that improves one number and worsens three others has not improved the strategy.
Adding the exit to a strategy you already have
If your strategy is already a few hundred lines long, adding the exit by hand means finding the right place for the entry-bar tracking, avoiding a name collision with an existing variable, and making sure the new close does not interfere with the existing exit logic. It is a small change, but it touches state that other parts of the script depend on.
This is the kind of edit where an AI editor that changes only the affected lines is useful. In PineScripter's editor, you can paste the strategy, ask for "close the trade after N bars, with N as an input, and label the exit Time exit," and see the change in the Code Changes view as a line-by-line diff rather than a rewritten file. The built-in linting checks the result the way TradingView does, so you find out about a compile error before you paste it back. You still run the result through TradingView's Strategy Tester to judge it, since PineScripter does not simulate trades for TradingView strategies. For turning an indicator into something you can test, From Indicator to Backtestable Strategy in Pine Script covers the full conversion.
Disclaimer
PineScripter is a coding tool for Pine Script, not a financial advisor, broker, or trading service. The code in this article is educational and describes how the language behaves. It does not recommend any trade, and a backtest describes only past data and says nothing certain about future results. Test any script yourself before relying on it.
Frequently asked questions
Is there a built-in way to exit after N bars in Pine Script?
No. strategy.exit has no bar-count argument. You compare bar_index with the entry bar of the open trade, read from strategy.opentrades.entry_bar_index(), and call strategy.close when the count is reached.
Why does my N bar exit hold the trade for N+1 bars?
Orders fill at the next bar's open by default. The close issued on bar N fills on bar N+1. Compare with holdBars - 1 for an exact hold, or use process_orders_on_close to fill on the same bar.
Can I combine a time exit with a stop loss and take profit?
Yes. Use strategy.exit for the stop and limit, and strategy.close for the time exit. Whichever order fills first ends the trade, so label each exit with a comment.
How do I exit after a number of hours instead of bars?
Compare time with strategy.opentrades.entry_time() and a duration in milliseconds, such as hours * 3600 * 1000. Bar counts and clock time differ on markets with gaps.
How do I handle several open trades with pyramiding?
Loop over strategy.opentrades, check each trade's entry_bar_index, and close it by its own entry ID. Give each entry a unique ID so closing one does not close the others.
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.