How to Add Exit XBar Sell Supertrend Strategy on TradingView

Abstract: Resolves indefinite holding periods in Supertrend strategies by implementing a fixed bar-count exit condition using persistent state variables.

Created: 2026-09-07 by

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.

  1. Define Inputs: Start by defining the Supertrend parameters and the exit bar count. Use input.int for integer values like length and multiplier.
  2. Calculate Supertrend: Use the built-in ta.supertrend function. This returns the direction and the value. We only need the direction for entry/exit signals.
  3. Track Entry Time: Declare a variable var int entryBar = na. When a long position is opened, update this variable to bar_index.
  4. Check Exit Condition: Before checking for new entries, check if a position is open. Calculate barsHeld = bar_index - entryBar. If barsHeld >= exitBars, close the position.
  5. Execute Trades: Use strategy.entry and strategy.close commands 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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More