Pine Script ta.supertrend: Direction Values Guide (v5)

If you have tried adding ta.supertrend() to your Pine Script and are not sure what to do with the two values it returns, this guide explains exactly how the function works, what the direction output means in practice, and how to turn those signals into automated trades using PineConnector.
What ta.supertrend() Returns
The ta.supertrend() function returns two values, not one. You have to capture both:
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
The first value, supertrend, is the actual line plotted on the chart. It is a price-based series that moves above or below the candles depending on the current trend.
The second value, direction, is what your strategy logic reads. It works like this:
-
direction < 0means the SuperTrend line is below price (uptrend, long bias) -
direction > 0means the SuperTrend line is above price (downtrend, short bias)
A common point of confusion: the sign feels counterintuitive. Negative direction means bullish. This is how Pine Script defines it natively, so read direction < 0 as "SuperTrend is green" and direction > 0 as "SuperTrend is red".
The Two Parameters: Factor and ATR Period
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
factor is the ATR multiplier. It controls how far the SuperTrend line sits from price. A higher factor means the line stays further from price, generating fewer but more reliable signals. A lower factor keeps it closer, producing more signals with more noise. The default used by most implementations is 3.
atrPeriod is the lookback period for the Average True Range calculation. It determines how much historical volatility the indicator uses to position its line. The standard default is 10. Changing this affects how quickly the SuperTrend reacts to volatility shifts.
These two inputs together make the indicator adaptive. In a high-volatility environment, the ATR grows and the SuperTrend gives price more room before switching direction. In quiet markets, it stays tighter to price.
Detecting Direction Changes with ta.change()
Knowing the current direction is useful. Knowing the exact bar when direction changed is what drives entry logic.
ta.change(direction) returns a non-zero value only on the bar where direction flipped. This is the core of the strategy trigger:
if ta.change(direction) < 0
// direction just flipped to uptrend, go long
if ta.change(direction) > 0
// direction just flipped to downtrend, go short
Without ta.change(), your if block would evaluate as true on every bar of a trend, not just the entry bar. The change wrapper isolates the flip.
Plotting the SuperTrend Line
To render the SuperTrend correctly on a v5 chart, split the line into two plots and use na to hide the inactive side:
plot(direction < 0 ? supertrend : na, 'Up Trend', color=color.green, style=plot.style_linebr)
plot(direction > 0 ? supertrend : na, 'Down Trend', color=color.red, style=plot.style_linebr)
plot.style_linebr prevents a connecting line from drawing across the gap when direction switches. Without it you get an ugly diagonal line bridging the two trend colours at every crossover.
To add the shaded fill between price and the SuperTrend line:
bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, 'Up Trend', color=color.new(color.green, 0), style=plot.style_linebr)
downTrend = plot(direction < 0 ? na : supertrend, 'Down Trend', color=color.new(color.red, 0), style=plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
The bodyMiddle plot tracks the midpoint between open and close. The fill stretches between that midpoint and the trend line, giving the chart the characteristic shaded look without overloading the visual.
The Full Automated Strategy Script
The following is the complete PineConnector-compatible SuperTrend strategy, sourced from the PineConnector SuperTrend Strategy guide. Paste it into a new Pine Editor strategy file, update your License ID, and it is ready to run:
//@version=5
strategy('Supertrend Strategy - PineConnector', overlay=true)
LicenseID = 601234567890 // 1. change to your PineConnector License ID (required)
riskvalue = input.int(1, 'Risk Value') // 2. Change the risk value (optional)
atrPeriod = input(10, 'ATR Length')
factor = input(3, 'Factor')
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
bodyMiddle = plot((open + close) / 2, display=display.none)
upTrend = plot(direction < 0 ? supertrend : na, 'Up Trend', color=color.new(color.green, 0), style=plot.style_linebr)
downTrend = plot(direction < 0 ? na : supertrend, 'Down Trend', color=color.new(color.red, 0), style=plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)
if ta.change(direction) < 0
strategy.entry('Long', strategy.long)
alert(str.tostring(LicenseID)+',buy,' + syminfo.ticker + ',risk=' + str.tostring(riskvalue), alert.freq_once_per_bar_close)
if ta.change(direction) > 0
strategy.entry('Short', strategy.short)
alert(str.tostring(LicenseID)+',sell,' + syminfo.ticker + ',risk=' + str.tostring(riskvalue), alert.freq_once_per_bar_close)
plotshape(ta.change(direction) < 0, style=shape.labelup, location=location.belowbar, color=color.new(#046ff9, 0), size=size.large, text='PineConnector \\n Buy', textcolor=color.new(color.white, 0))
plotshape(ta.change(direction) > 0, style=shape.labeldown, location=location.abovebar, color=color.new(#046ff9, 0), size=size.large, text='PineConnector \\n Sell', textcolor=color.new(color.white, 0))
⚠️ Update this before saving:
LicenseID = 601234567890: replace601234567890with your actual License ID from the PineConnector portal. It is a long string of numbers starting with 6 or 7.
Also adjust riskvalue if needed. A higher number increases volume per trade based on your EA Volume Type setting.
How the alert() Calls Work in This Script
If you read last week's guide on the Pine Script alert() function, this section will look familiar.
Each direction change fires one alert. The message string is built dynamically:
str.tostring(LicenseID)+',buy,' + syminfo.ticker + ',risk=' + str.tostring(riskvalue)
syminfo.ticker pulls the symbol from whatever chart the script is applied to, so one script covers every pair or instrument without editing the code. str.tostring() converts the integer License ID and risk value into strings so they can be concatenated into the alert message.
With this setup, one TradingView alert handles both buy and sell entries for the current symbol and timeframe. You do not need separate alerts for each direction.
Why SuperTrend Needs Close on Reverse
The SuperTrend script fires a buy signal when direction flips bullish and a sell signal when direction flips bearish. What it does not do is send a dedicated exit command. There is no closelong or closeshort in the code. Without the right EA setting, an incoming sell signal would open a new short position while the existing long position stays open, leaving you simultaneously long and short on the same instrument.
Close on Reverse solves this. It is a setting in the PineConnector EA found under General Trading Behavior Settings in your MetaTrader terminal (press F7 to open EA settings). Set it to On — Hedging and the EA will automatically close any open positions in the opposite direction before executing the new one.
In practice this means: when a sell signal fires, the EA closes all open buy positions for that symbol first, then opens the sell. When the next buy signal fires, it closes the sell and opens the buy. The strategy stays in the market continuously without stacking conflicting positions.
The two available modes are:
On — Hedging closes the existing position and opens the new one in the opposite direction. This is the correct setting for SuperTrend since you want to stay in a trade at all times.
On — Netting closes the existing position but does not open a new one in the opposite direction. Use this if you only want to exit on a reversal without entering a new trade.
For the SuperTrend strategy, always use On — Hedging. You can read the full Close on Reverse documentation in the PineConnector EA guide.
Setting Up the Alert in TradingView
Once the script is saved and added to your chart, press Alt+A (Windows) or Option+A (Mac) to create the alert.
| Setting | Value |
|---|---|
| Condition | SuperTrend Strategy, then "alert() function calls only" |
| Webhook URL | https://webhook.pineconnector.com |
For testing, switch to the 1-minute chart first. Signals will trigger faster and let you verify the full chain: TradingView Alerts Log, PineConnector Signal Log, and MetaTrader terminal, before committing to your actual trading timeframe.
One reminder that trips up new users: if you update the script code after creating an alert, the existing alert keeps running on the old code. Delete it and create a new one every time you make changes.
Choosing the Right Market for SuperTrend
This matters more than parameter tuning. SuperTrend is a trend-following system. It works well when price is making sustained directional moves and performs poorly in ranging or sideways conditions.
The PineConnector documentation notes explicitly that EURUSD on the 24-hour chart tends to perform poorly with this strategy because the pair spends significant time in consolidation. Instruments with stronger trending behaviour including commodity pairs, indices, or crypto during momentum phases, tend to produce cleaner signals.
Before running it live, use the Strategy Tester tab in TradingView to check performance on your specific instrument and timeframe. Backtest results will differ between data providers, so test on the same broker data feed you intend to trade on.
Start Automating Your Strategy
The SuperTrend strategy is ready to run the moment you paste the code, update your License ID, and create one alert. No indicator configuration, no separate buy and sell alerts, no manual execution. Just a trend flip and a trade.
Start your 7-day trial for $14 at PineConnector and automate your first SuperTrend strategy today.