๐ŸŽ“ Tutorials

TradingView SuperTrend Alerts: Pine Script V5 Guide (2026)

โš ๏ธ Disclosure: Some links on this page are affiliate links. If you sign up through them, I may earn a commission โ€” at no extra cost to you. I only review tools I actually use.
> About this guide: I'm Lawrence, the writer behind supa.is. Between February and May 2026 I've published 150+ articles on supa.is across crypto and brokerage tooling โ€” including 30+ TradingView-specific guides (recent examples: TradingView Pine Script SuperTrend Strategy, TradingView Alert Not Triggering? 12 Fixes, TradingView Alert: Once Per Bar vs Once Per Bar Close). The most-repeated reader question across that TradingView archive is exactly how to automate SuperTrend direction flips with reliable alerts, which is why I'm publishing this standardized guide instead of answering one-off.

> Disclosure: This article contains affiliate links. We may earn a commission at no extra cost to you if you sign up through our links.

Why SuperTrend Alerts Fail (And How to Fix Them)

Most traders treat the SuperTrend indicator as a simple buy/sell overlay. It's not. It's a dynamic volatility filter. When you slap a basic SuperTrend on a chart and set a default "crosses" alert, you get noise. You get false triggers on low-volume sessions. You get alerts that fire three times in a row because the indicator repainted slightly during a wick.

The difference between a retail alert setup and a professional one comes down to three things:

1. Pine Script v5 logic: Using ta.supertrend() correctly instead of relying on outdated v4 libraries. 2. Alert conditions: Triggering on *direction changes*, not just crossovers. 3. Webhook routing: Sending that signal to an exchange like OKX or Hyperliquid without latency.

This guide covers the exact code, the alert configuration, and the webhook payload you need to automate SuperTrend direction changes in 2026.

The SuperTrend Logic: How It Actually Works

Before writing the script, you need to understand what you're automating. SuperTrend is built on the Average True Range (ATR). It plots a line above price in a downtrend and below price in an uptrend.

The formula is straightforward:

When price crosses this line, the trend flips. That flip is your signal. But here's the catch: ATR is lagging. In choppy markets, price will poke above and below the line repeatedly. If your alert triggers on every single cross, your trading account will bleed fees.

The solution is to filter for confirmed direction changes. We'll build a Pine Script v5 strategy that only alerts when the SuperTrend state actually switches from Bull to Bear, or vice versa, on a closed candle.

Step 1: The Pine Script v5 Code

Copy and paste this code into the Pine Editor on TradingView. This is a clean, v5-compliant script that calculates the SuperTrend and generates alerts on direction changes.

//@version=5
indicator("SuperTrend Direction Alerts [supa.is]", overlay=true)

// --- Inputs ---
atrLength = input.int(10, "ATR Length")
factor = input.float(3.0, "ATR Multiplier")

// --- SuperTrend Calculation ---
atr = ta.atr(atrLength)
trendUp = true
trendDown = false

upperBand = (close + factor * atr)
lowerBand = (close - factor * atr)

// Previous bands
prevUpperBand = nz(upperBand[1])
prevLowerBand = nz(lowerBand[1])

// Current trend state
if (close > prevUpperBand)
    trendUp := true
    trendDown := false
else if (close < prevLowerBand)
    trendUp := false
    trendDown := true

// Final SuperTrend line
superTrend = trendUp ? lowerBand : upperBand

// --- Plotting ---
plot(superTrend, "SuperTrend", color = trendUp ? color.green : color.red, linewidth=2)

// --- Alert Conditions ---
// Alert only when the trend actually flips
alertConditionLong = trendUp and not trendUp[1]
alertConditionShort = trendDown and not trendDown[1]

// --- Visual Confirmation ---
plotshape(alertConditionLong, "Long Alert", shape.triangleup, location.belowbar, color.green, size=size.small)
plotshape(alertConditionShort, "Short Alert", shape.triangledown, location.abovebar, color.red, size=size.small)

// --- Alert Triggers ---
alert(alertConditionLong, "SuperTrend: Direction Changed to BULLISH", alert.freq_once_per_bar)
alert(alertConditionShort, "SuperTrend: Direction Changed to BEARISH", alert.freq_once_per_bar)

Why This Code Works

Step 2: Adding the Indicator to Your Chart

1. Open a chart on TradingView.

2. Click Pine Editor at the bottom. 3. Delete any existing code and paste the script above. 4. Click Add to Chart. 5. You'll see the green/red SuperTrend line overlay your price candles. Green triangles appear below bullish candles; red triangles appear above bearish candles.

> Note: If you're on the free TradingView plan, you're limited to three indicators per chart. If you hit this limit, combine your RSI, EMA, and MACD into a single custom script to free up slots. See our guide on TradingView Free Plan Indicator Limit for the exact code.

Step 3: Configuring the Alert

This is where most setups fail. You don't just click "Create Alert." You need to configure it correctly.

๐Ÿ’ก TradingView

Like what you're reading? Try it yourself โ€” this link supports ChartedTrader at no cost to you.

Try TradingView โ†’
๐ŸŽ You receive: 30-day free trial (Essential / Plus / Premium) ยท no credit card needed

1. Right-click the chart and select Add Alert.

2. Condition: Select SuperTrend Direction Alerts [supa.is]. 3. Alert on: Choose Custom Event. 4. Select Event: You'll see two options: SuperTrend: Direction Changed to BULLISH and SuperTrend: Direction Changed to BEARISH. Pick one. 5. Frequency: Set to Once per bar close. This is non-negotiable for avoiding false signals. 6. Click Create.

Repeat this process for the opposite direction if you want to trade both longs and shorts.

Step 4: Setting Up the Webhook

TradingView alerts are useless if they just send a push notification to your phone. To automate trades, you need a webhook. A webhook sends a JSON payload to a URL when the alert triggers.

Where to Send the Webhook?

You have two main paths: 1. Direct Exchange API: Connect directly to OKX or Hyperliquid using a bridge service like 3Commas, Cryptohopper, or a custom Python script. 2. Discord/Telegram Bot: Use a service like Alertatron or a custom webhook to send a message to your phone or a trading bot.

For this guide, we'll assume you're using a bridge service that accepts standard JSON payloads.

The JSON Payload

In the Alert setup, check the box Webhook URL. Paste your bridge service URL. Then, in the Message field, enter this JSON:

{
  "symbol": "{{ticker}}",
  "direction": "{{alertmessage}}",
  "price": "{{close}}",
  "time": "{{timenow}}"
}

Your bridge service will parse this JSON and execute the trade. For example, if direction contains "BULLISH", it opens a long. If "BEARISH", it opens a short.

Step 5: Testing the Alert

Never automate live money without testing.

1. Paper Trading: Enable TradingView's paper trading mode. Place manual trades when the alert fires to see if the logic holds.

2. Webhook Tester: Use a free service like webhook.site to generate a temporary URL. Paste it into your TradingView alert. Trigger the alert manually by moving the chart's replay bar to a candle where the SuperTrend flips. Check webhook.site to ensure the JSON payload arrives correctly. 3. Small Position: Once verified, set your bridge service to execute with a 0.1% position size. Run it for 10-20 trades. Check for slippage, failed orders, or duplicate triggers.

Common Pitfalls and Fixes

Pitfall 1: Alerts Fire on Every Candle

Cause: You selected "Crosses" instead of "Custom Event," or you didn't use alert.freq_once_per_bar in the script. Fix: Use the script provided above. It explicitly checks for state changes (not trendUp[1]) and sets frequency to once per bar close.

Pitfall 2: Webhook Returns 403 Forbidden

Cause: Your exchange or bridge service has IP whitelisting enabled, or the API key lacks trading permissions. Fix: Check your API key settings on OKX or your bridge dashboard. Ensure "Trade" permissions are enabled. If you're using IP whitelisting, add your bridge service's server IPs to the whitelist. See our guide on OKX API Key Invalid IP Whitelist for detailed steps.

Pitfall 3: Repainting Signals

Cause: You're using a custom SuperTrend library that calculates ATR on open price instead of close price. Fix: The native ta.atr in Pine Script v5 uses close price by default. Stick to the script provided. It does not repaint.

Pitfall 4: Latency on Execution

Cause: TradingView sends the webhook, but your bridge service takes 5-10 seconds to process and execute. In fast markets, the price moves against you. Fix: Use a bridge service with low-latency servers (e.g., AWS us-east-1). Alternatively, use a direct API connection via Python if you have coding skills. For Hyperliquid, the Hyperliquid Python SDK offers near-instant execution.

Risk Management for Automated SuperTrend

SuperTrend is a trend-following indicator. It thrives in strong, directional markets. It dies in ranging, choppy markets.

When to Turn It Off

Position Sizing

Never risk more than 1-2% of your account on a single automated trade. SuperTrend stops are dynamic, but slippage can occur. Set a hard stop-loss in your exchange order (e.g., 2x ATR below entry) to protect against extreme gaps.

FAQ

Can I use this script on the free TradingView plan?

Yes. The script uses native Pine Script functions and does not require paid indicators. However, free plans are limited to three indicators per chart. If you need more, combine them into one script or upgrade via our TradingView affiliate link.

Does this work for stocks and forex?

Absolutely. SuperTrend is asset-agnostic. It works on any chart where price and volume data exist. Adjust the ATR length and multiplier based on the asset's volatility. Forex pairs often require a lower multiplier (e.g., 2.0) due to tighter ranges.

How do I fix "Alert Not Triggering" errors?

Check three things: 1) Is the indicator actually on the chart? 2) Is the alert frequency set to "Once per bar close"? 3) Is the chart timeframe matching your strategy? See our comprehensive guide on TradingView Alert Not Triggering? 12 Fixes.

Can I connect this directly to OKX without a bridge?

Yes, but it requires coding. You can use the OKX Signal Bot feature, which accepts TradingView webhooks natively. You'll need to format the JSON payload to match OKX's API requirements and generate an API key with trading permissions.

What's the best timeframe for SuperTrend alerts?

It depends on your strategy. Scalpers use 1-minute or 5-minute charts with a low multiplier (2.0). Swing traders use 4-hour or daily charts with a higher multiplier (3.0-4.0). Backtest your specific asset to find the sweet spot.

Risk Warning

> Risk Warning: Crypto trading involves substantial risk of loss. Automated trading strategies, including SuperTrend alerts, are not guaranteed to be profitable. Past performance does not indicate future results. Never invest more than you can afford to lose. This is not financial advice. Always verify your alerts and risk management settings before going live.

Final Thoughts

Automating SuperTrend alerts is one of the highest-ROI upgrades you can make to your trading workflow. It removes emotion, eliminates screen-staring fatigue, and ensures you never miss a trend flip. But automation is only as good as your setup. Use the Pine Script v5 code provided, configure your alerts with "Once per bar close," and test your webhook thoroughly.

Ready to start? Open TradingView, paste the script, and set up your first alert today. If you need a reliable exchange to execute these signals, OKX offers robust API support and low fees for automated trading.

๐Ÿงฎ Free TradingView calculator

Strategy Expectancy โ†’
TP / SL / win-rate / Kelly criterion math โ€” no fake backtest required
TradingView

Ready to get started? Use the link below โ€” it helps support ChartedTrader at no cost to you.

Try TradingView โ†’
๐ŸŽ You receive: 30-day free trial (Essential / Plus / Premium) ยท no credit card needed
๐Ÿ“ˆ

About the author

I'm a systematic trader running live strategies on IB (USDJPY momentum) and Hyperliquid (crypto perps). Every tool reviewed here is something I've used with real capital. Questions? Reach out.

๐Ÿ“š Related Articles

๐ŸŽ“
Tutorials

Fix TA.ADX Pine Script V5 Compilation Error (2026)

Resolve the ta.adx() Pine Script v5/v6 compilation error. Learn the correct namespace syntax, fix lookahead bias, and set up reliable alerts.

June 19, 2026 โฑ 11 min read
๐ŸŽ“
Tutorials

Fix Pine Script v6 request.security() Lookahead Error (2026)

TradingView Pine Script v6 broke request.security() lookahead handling. Learn the exact syntax fixes, gap parameters, and repainting prevention steps to migrate your indicators without breaking backtests.

May 27, 2026 โฑ 9 min read
๐ŸŽ“
Tutorials

Hyperliquid Python SDK Tutorial: Build a Bot (2026)

Build a production-ready trading bot on Hyperliquid using the official Python SDK. Covers API wallet security, order execution, WebSocket feeds, and common pitfalls to avoid.

May 6, 2026 โฑ 12 min read

๐Ÿ“ฌ Get weekly trading insights

Real trades, honest reviews, no fluff. One email per week.