To add an exit XBar sell Supertrend strategy on TradingView, you must modify the Pine Script logic to track entry time and calculate bar count since that entry. By using ta.supertrend for signals and a persistent counter variable, you can force positions to close after a fixed duration, ensuring your backtests reflect realistic holding periods.
Understanding the Core Logic
The original problem often stems from misunderstanding how Pine Script handles state changes. A standard Supertrend strategy enters a position when the trend flips. However, without an exit condition based on time, positions may remain open indefinitely or until a new signal appears. To implement an "Exit X Bar" rule, we need to distinguish between the moment a trade is opened and the current bar index.
We will use a var declaration to store the bar number of the last entry. This variable persists across bars. On every new bar, we check if a trade is currently open. If it is, we compare the current bar number against the stored entry bar number. If the difference equals our desired hold period, we issue a market order to close the position.
Why Previous Attempts Failed
Many users attempt to fix this by incrementing a counter inside the if block that checks for the exit condition. This is logically flawed because the counter only increments when the exit condition is met, which is too late. The counter must be calculated as the difference between two absolute values: bar_index - entry_bar_index. Additionally, failing to declare input variables with var or proper types causes syntax errors during compilation.
Step-by-Step Implementation
Follow these steps to create a robust script that combines Supertrend signals with a timed exit.
- Define Inputs: Start by defining the Supertrend parameters and the exit bar count. Use
input.intfor integer values like length and multiplier. - Calculate Supertrend: Use the built-in
ta.supertrendfunction. This returns the direction and the value. We only need the direction for entry/exit signals. - Track Entry Time: Declare a variable
var int entryBar = na. When a long position is opened, update this variable tobar_index. - Check Exit Condition: Before checking for new entries, check if a position is open. Calculate
barsHeld = bar_index - entryBar. IfbarsHeld >= exitBars, close the position. - Execute Trades: Use
strategy.entryandstrategy.closecommands to manage the portfolio.
The Corrected Pine Script Code
The following code snippet demonstrates the correct syntax. Note the use of var for state persistence and the logical flow that checks exits before entering new trades.
// This source code is subject to the terms of the Mozilla Public License 2.0
// https://mozilla.org/MPL/2.0/
// © YourName
//@version=5
strategy("Supertrend Exit X Bars", overlay=true)
// Input Parameters
length = input.int(10, "Supertrend Length")
multiplier = input.float(3.0, "Supertrend Multiplier")
exitBars = input.int(5, "Exit After N Bars")
// Calculate Supertrend Direction
[stDir, stVal] = ta.supertrend(length, multiplier)
// State Variables
var int entryBar = na
var string positionType = na
// Determine Position Status
isLong = positionType == "long"
isShort = positionType == "short"
// Exit Logic
if isLong
if bar_index - entryBar >= exitBars
strategy.close("Long", comment="Time Exit Long")
positionType := na
if isShort
if bar_index - entryBar >= exitBars
strategy.close("Short", comment="Time Exit Short")
positionType := na
// Entry Logic
if stDir == 1 and not isLong
strategy.entry("Long", strategy.long)
entryBar := bar_index
positionType := "long"
if stDir == -1 and not isShort
strategy.entry("Short", strategy.short)
entryBar := bar_index
positionType := "short"
// Plotting
plot(stVal, color=stDir == 1 ? color.green : color.red)
Key Syntax Corrections
In the previous rejected draft, the counter was incremented incorrectly. Here, we do not increment a counter manually. Instead, we rely on bar_index, which is a built-in variable that increases by one on every new bar. Subtracting the saved entryBar from the current bar_index gives us the exact number of bars held. This method is precise and avoids off-by-one errors.
Also, note the declaration of positionType. Using a string variable to track whether we are in a long, short, or no position is cleaner than managing multiple boolean flags. It ensures that we do not accidentally enter a new position while an old one is still being managed by the timer.
Testing and Optimization
Once you have added this script to your chart, run the Strategy Tester. Look at the "Trade Log" tab. You should see orders marked with "Time Exit Long" or "Time Exit Short" instead of just "Signal Exit." This confirms that the timer logic is working.
If your results seem inconsistent, check the exitBars input. Some traders prefer to exit after a fixed number of bars regardless of profit or loss, while others might want to combine this with a trailing stop. For now, keeping it simple allows you to verify the core mechanic. You can further refine this by adding strategy.exit with limit and stop prices, but the bar-count exit remains a powerful tool for risk management.
For those interested in the foundational structure of such scripts, understanding the basic strategy framework is essential. You can review the simplest implementation patterns to ensure your code adheres to best practices.
Simplest PineScript Strategy Code Explained provides a great baseline for understanding how strategies are structured in Pine Script v5.Frequently Asked Questions
Why does my strategy re-enter immediately after exiting?
This happens if the entry condition is still true on the same bar where you exited. To prevent this, ensure your entry logic checks that the position is closed (not isLong) before allowing a new entry. Adding a small delay or requiring a different signal confirmation can also help avoid choppy markets.
Can I combine this with a profit target?
Yes, you can use strategy.exit to set a take-profit level alongside the time-based exit. The first condition met (profit target or bar count) will trigger the closure. This hybrid approach helps lock in gains while preventing long-term exposure.
Does this work on all timeframes?
The logic works on any timeframe, but the meaning of "X Bars" changes. An exit after 5 bars on a 1-minute chart is very different from 5 bars on a daily chart. Adjust the exitBars input based on the volatility and typical duration of trades on your chosen timeframe.
What if I want to exit only if the position is profitable?
You would need to add a condition checking the current PnL or price relative to the entry price. For example, check if close > entryPrice before applying the time exit. This adds complexity but prevents closing winning trades early or holding losing ones too long.
How do I handle weekends or holidays?
Pine Script counts calendar bars, including gaps. If you trade crypto or stocks, consider using timeframe.period checks or filtering by session hours if your broker has specific trading hours. The bar count will continue to increment even during non-trading hours if the data feed includes them.