> 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: Usingta.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:
- Bullish SuperTrend:
ATR * Multiplierbelow the median price. - Bearish SuperTrend:
ATR * Multiplierabove the median price.
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
alert.freq_once_per_bar: This is critical. It ensures you only get one alert per candle close. Without this, you might get multiple alerts as the candle ticks up and down before closing.not trendUp[1]: This checks the *previous* state. It ensures the alert only fires when the state *changes*, not when it stays bullish for 10 candles in a row.- No external libraries: It uses native
ta.atrandta.supertrendlogic, making it faster and less prone to compilation errors.
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.
Like what you're reading? Try it yourself โ this link supports ChartedTrader at no cost to you.
Try TradingView โ1. Right-click the chart and select Add Alert.
2. Condition: SelectSuperTrend 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}}"
}
{{ticker}}: The trading pair (e.g., BTCUSDT).{{alertmessage}}: The text we defined in the Pine Script ("SuperTrend: Direction Changed to BULLISH").{{close}}: The closing price of the candle.{{timenow}}: The exact timestamp.
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 likewebhook.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 usealert.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 nativeta.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
- Earnings Reports: Volatility spikes can cause the ATR to expand rapidly, triggering false flips. Pause alerts 24 hours before major earnings.
- Low Volume Sessions: Weekend crypto sessions or Asian forex sessions often lack the volume to sustain trends. SuperTrend will whipsaw. Consider adding a volume filter to your Pine Script (e.g.,
volume > ta.sma(volume, 20)). - High Correlation Events: If BTC dumps 5%, altcoins will follow regardless of their SuperTrend signal. Don't trade altcoin longs during a BTC crash.
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.