Alerts, Publishing & the Pine Ecosystem
Generating alerts, alertcondition vs alert(), publishing open-source, protected, and invite-only scripts, finding reference scripts, community libraries, and official documentation.
alertcondition(): Static Alert Definitions
alertcondition() defines a named condition that users can subscribe to via TradingView's alert system. When you add your indicator to a chart and create an alert, you will see a dropdown listing all alert conditions defined in the script. When the condition becomes true on a bar close (or tick, depending on settings), TradingView sends a notification.
1//@version=62indicator("Alert Conditions Demo", overlay=true)34ema21 = ta.ema(close, 21)5ema50 = ta.ema(close, 50)6rsi = ta.rsi(close, 14)78// Basic crossover alerts9bullCross = ta.crossover(ema21, ema50)10bearCross = ta.crossunder(ema21, ema50)1112alertcondition(bullCross, title="Bullish EMA Cross",13 message="EMA 21 crossed above EMA 50: potential trend reversal")14alertcondition(bearCross, title="Bearish EMA Cross",15 message="EMA 21 crossed below EMA 50: momentum shifting bearish")1617// RSI extreme alerts18alertcondition(rsi > 80, title="RSI Overbought",19 message="RSI is above 80: extreme overbought conditions")20alertcondition(rsi < 20, title="RSI Oversold",21 message="RSI is below 20: extreme oversold conditions")2223// Multi-factor confluence alert24strongBull = bullCross and rsi > 50 and volume > ta.sma(volume, 20) * 1.525alertcondition(strongBull, title="Strong Bullish Confluence",26 message="EMA cross + RSI above 50 + elevated volume")alertcondition() limitations
alertcondition() has important restrictions: the message is a static string (no dynamic values like current price), it can only be used in indicators (not strategies), and the condition is always evaluated on bar close. For dynamic messages and more control, use the alert() function instead.alert(): Dynamic Alert Messages
The alert() function is more flexible than alertcondition(). It fires programmatically from within your code, supports dynamic messages with current price/indicator values, and offers granular control over alert frequency. This is what you should use for production alert systems.
1//@version=62indicator("Dynamic Alerts", overlay=true)34ema21 = ta.ema(close, 21)5rsi = ta.rsi(close, 14)67bullCross = ta.crossover(close, ema21) and barstate.isconfirmed89if bullCross10 msg = str.format(11 "π’ BULL SIGNAL on {0}\nPrice: {1}\nRSI: {2}\nVolume: {3}\nTimeframe: {4}",12 syminfo.ticker,13 str.tostring(close, "#.##"),14 str.tostring(rsi, "#.#"),15 str.tostring(volume, "#,###"),16 timeframe.period)17 alert(msg, alert.freq_once_per_bar_close)1819bearCross = ta.crossunder(close, ema21) and barstate.isconfirmed2021if bearCross22 msg = str.format(23 "π΄ BEAR SIGNAL on {0}\nPrice: {1}\nRSI: {2}\nVolume: {3}\nTimeframe: {4}",24 syminfo.ticker,25 str.tostring(close, "#.##"),26 str.tostring(rsi, "#.#"),27 str.tostring(volume, "#,###"),28 timeframe.period)29 alert(msg, alert.freq_once_per_bar_close)Alert Frequency Options
The frequency parameter controls how often the alert fires when the condition is continuously true. Choosing the right frequency prevents alert spam while ensuring you do not miss signals.
| alert.freq_once_per_bar | Fires once when the condition first becomes true during the current bar. May repaint: the alert could fire mid-bar and the condition could become false by close. |
| alert.freq_once_per_bar_close | Fires only when the bar CLOSES with the condition true. Non-repainting: the safest option for trading signals. Use this for most alerts. |
| alert.freq_all | Fires on every tick where the condition is true. Use for monitoring, not trading signals. Can generate hundreds of alerts per bar. |
Which frequency to use
alert.freq_once_per_bar_close combined with barstate.isconfirmed. This ensures the alert only fires on confirmed (closed) bars, eliminating false signals from intrabar price fluctuations. The combination of both is belt-and-suspenders safety.Webhook Alerts: Connecting to External Services
TradingView alerts can send HTTP POST requests (webhooks) to external URLs. This means your PineScript indicator can trigger actions in external systems: send messages to Discord or Telegram, log signals to a database, or even place real trades through a broker API. The alert message becomes the webhook payload.
1//@version=62indicator("Webhook Alerts", overlay=true)34ema21 = ta.ema(close, 21)5atr = ta.atr(14)6rsi = ta.rsi(close, 14)78longSignal = ta.crossover(close, ema21) and barstate.isconfirmed9shortSignal = ta.crossunder(close, ema21) and barstate.isconfirmed1011// Build a JSON payload for webhook consumption12if longSignal13 jsonMsg = str.format(14 '\{"action": "buy", "symbol": "{0}", "price": {1}, "sl": {2}, "tp": {3}, "rsi": {4}, "timeframe": "{5}", "timestamp": "{6}"\}',15 syminfo.ticker,16 str.tostring(close, "#.####"),17 str.tostring(close - atr * 2, "#.####"),18 str.tostring(close + atr * 3, "#.####"),19 str.tostring(rsi, "#.#"),20 timeframe.period,21 str.tostring(timenow))22 alert(jsonMsg, alert.freq_once_per_bar_close)2324if shortSignal25 jsonMsg = str.format(26 '\{"action": "sell", "symbol": "{0}", "price": {1}, "sl": {2}, "tp": {3}, "rsi": {4}, "timeframe": "{5}", "timestamp": "{6}"\}',27 syminfo.ticker,28 str.tostring(close, "#.####"),29 str.tostring(close + atr * 2, "#.####"),30 str.tostring(close - atr * 3, "#.####"),31 str.tostring(rsi, "#.#"),32 timeframe.period,33 str.tostring(timenow))34 alert(jsonMsg, alert.freq_once_per_bar_close)3536plot(ema21, "EMA 21", close > ema21 ? color.green : color.red, 2)Create the indicator with alert() calls
alert() calls that produce JSON-formatted messages. Include all data the receiving service needs: symbol, price, stop loss, take profit, RSI, timeframe, and timestamp.Add the indicator to your chart
Create a TradingView alert
alert() call becomes the POST body.Configure the receiving service
Publishing Scripts on TradingView
TradingView lets you share your indicators with the community or restrict access. There are three publication modes, each serving a different purpose:
Full source code is visible to everyone. Best for community contribution, getting feedback, and qualifying for TradingView's Editors' Pick program. Builds reputation.
Code is compiled and hidden: users can add to chart but cannot see the source. Use for proprietary algorithms you want to share freely without revealing the logic.
Only users you explicitly approve can access the script. This is the basis for paid indicator businesses. Sell access via Gumroad, Patreon, or a custom website.
Publishing Best Practices
Write a detailed description
Choose the right category
Include release notes
Respond to comments
Finding and Using Community Scripts
TradingView hosts thousands of community-created scripts. Learning to find, evaluate, and adapt existing scripts accelerates your development dramatically. The best scripts come from authors with high reputation scores, detailed documentation, and active comment sections.
| Indicators tab | Click "Indicators" on the chart toolbar, then browse "Community Scripts." Filter by type, sort by likes or recency. |
| Source code review | For open-source scripts, always read the code before using. Look for clean structure, proper na handling, and no repainting issues. |
| Pine Wizards | TradingView's top script authors are verified "Pine Wizards." Their scripts are generally high quality and well-maintained. |
| Script search | Use specific terms: "RSI divergence," "supply demand zones," "market cipher," "funding rate." Generic searches return too many results. |
Importing and Using Libraries
Libraries are reusable PineScript modules that export functions you can import into your own scripts. They eliminate code duplication and let you leverage battle-tested utilities built by the community or your own team.
1//@version=62indicator("Library Usage Demo", overlay=true)34// Import a published library (format: Username/LibraryName/version)5// import TradingViewUsername/MathUtils/1 as utils67// After importing, call exported functions with the alias8// smoothedRSI = utils.customSmoothing(ta.rsi(close, 14), 5)910// You can import multiple libraries11// import AnotherUser/RiskCalc/2 as risk12// import AnotherUser/Plotting/1 as viz1314// Libraries are versioned: /1 means version 115// If the author publishes /2, your script keeps using /1 until you update1617// Common library categories on TradingView:18// - Mathematical utilities (custom smoothing, statistics)19// - Drawing helpers (auto-fibonacci, zone detection)20// - Risk management calculators21// - Signal generation frameworks22// - String formatting utilities2324plot(ta.ema(close, 21), "EMA", color.white)Official Documentation and Reference Manual
The official PineScript documentation at pine-script-docs.tradingview.com is comprehensive and well-maintained. It includes a language reference (every function, variable, and type), a user manual (conceptual explanations with examples), and a migration guide for upgrading between versions.
Complete API documentation for every built-in function, variable, constant, and type. Searchable and organized by namespace.
Conceptual guides covering the execution model, type system, scoping rules, and advanced features like UDTs and methods.
Hover over any function in the editor to see inline documentation with parameter descriptions and examples.
Step-by-step instructions for converting scripts between PineScript versions (v4βv5, v5βv6).
Changelog of new features, bug fixes, and deprecations in each PineScript release.
PineScript v6 Overview and Migration
PineScript v6 is the latest version, building on v5's foundation with improvements to type inference, error messaging, and runtime performance. If you are starting fresh, write in v6. If you are maintaining existing v5 scripts, migration is straightforward. Most v5 code works in v6 with minimal changes.
| Type inference | v6 is smarter about inferring types, reducing the need for explicit declarations in many common patterns. |
| Error messages | Significantly improved: more specific, more actionable, with better line number reporting and suggestions. |
| Runtime performance | Optimized execution engine with faster array operations, reduced memory usage, and better handling of large datasets. |
| Function overloading | Define multiple versions of a function with different parameter types: the compiler selects the right one based on call arguments. |
| Backward compatibility | Most v5 scripts work in v6. The main changes are stricter type checking (catches bugs earlier) and some function signature refinements. |
Complete Build: Professional Alert System
Let's build a complete, production-ready alert system that combines multiple signal types, dynamic webhook-formatted messages, visual confirmation on the chart, and proper anti-repainting safeguards. This is the template you should use for any serious alert indicator.
1//@version=62indicator("Pro Alert System", overlay=true, max_labels_count=50)34// ββ Inputs ββββββββββββββββββββββββββββββββββββββ5grpTrend = "Trend"6emaFast = input.int(9, "Fast EMA", group=grpTrend)7emaSlow = input.int(21, "Slow EMA", group=grpTrend)89grpMom = "Momentum"10rsiLen = input.int(14, "RSI Length", group=grpMom)11rsiOB = input.int(70, "RSI Overbought", group=grpMom)12rsiOS = input.int(30, "RSI Oversold", group=grpMom)1314grpVol = "Volume"15volMult = input.float(1.5, "Volume Spike Multiplier", step=0.1, group=grpVol)1617grpAlert = "Alerts"18useWebhook = input.bool(false, "Format as JSON Webhook", group=grpAlert)1920// ββ Calculations ββββββββββββββββββββββββββββββββ21fast = ta.ema(close, emaFast)22slow = ta.ema(close, emaSlow)23rsi = ta.rsi(close, rsiLen)24atr = ta.atr(14)25avgVol = ta.sma(volume, 20)26isVolSpike = volume > avgVol * volMult27confirmed = barstate.isconfirmed2829// ββ Signal Definitions (confirmed bars only) ββββ30bullTrend = ta.crossover(fast, slow) and confirmed31bearTrend = ta.crossunder(fast, slow) and confirmed32bullMom = ta.crossover(rsi, rsiOS) and confirmed33bearMom = ta.crossunder(rsi, rsiOB) and confirmed34bullConflu = bullTrend and rsi > 50 and isVolSpike35bearConflu = bearTrend and rsi < 50 and isVolSpike3637// ββ Alert Message Builder βββββββββββββββββββββββ38buildMsg(signalType, direction) =>39 if useWebhook40 str.format(41 '\{"signal": "{0}", "direction": "{1}", "symbol": "{2}", "price": {3}, "rsi": {4}, "atr": {5}, "volume_ratio": {6}, "timeframe": "{7}"\}',42 signalType, direction, syminfo.ticker,43 str.tostring(close, "#.####"),44 str.tostring(rsi, "#.#"),45 str.tostring(atr, "#.####"),46 str.tostring(volume / avgVol, "#.##"),47 timeframe.period)48 else49 str.format("{0} {1} on {2} @ {3} | RSI: {4} | Vol: {5}x avg",50 direction, signalType, syminfo.ticker,51 str.tostring(close, "#.##"),52 str.tostring(rsi, "#.#"),53 str.tostring(volume / avgVol, "#.#"))5455// ββ Fire Alerts βββββββββββββββββββββββββββββββββ56if bullTrend57 alert(buildMsg("EMA_CROSS", "LONG"), alert.freq_once_per_bar_close)58if bearTrend59 alert(buildMsg("EMA_CROSS", "SHORT"), alert.freq_once_per_bar_close)60if bullMom61 alert(buildMsg("RSI_BOUNCE", "LONG"), alert.freq_once_per_bar_close)62if bearMom63 alert(buildMsg("RSI_BREAK", "SHORT"), alert.freq_once_per_bar_close)64if bullConflu65 alert(buildMsg("CONFLUENCE", "LONG"), alert.freq_once_per_bar_close)66if bearConflu67 alert(buildMsg("CONFLUENCE", "SHORT"), alert.freq_once_per_bar_close)6869// ββ Static alertconditions for backward compatibility ββ70alertcondition(bullConflu, "Bull Confluence", "Bullish confluence signal")71alertcondition(bearConflu, "Bear Confluence", "Bearish confluence signal")7273// ββ Visual Confirmation βββββββββββββββββββββββββ74plot(fast, "Fast EMA", close > fast ? color.green : color.red, 1)75plot(slow, "Slow EMA", color.new(color.gray, 40), 2)76plotshape(bullTrend, "Bull Cross", shape.triangleup,77 location.belowbar, color.green, size=size.small)78plotshape(bearTrend, "Bear Cross", shape.triangledown,79 location.abovebar, color.red, size=size.small)8081// Confluence labels (rare, high-value signals)82if bullConflu83 label.new(bar_index, low, "STRONG\nBUY",84 color=color.new(color.green, 10),85 textcolor=color.white,86 style=label.style_label_up, size=size.normal)87if bearConflu88 label.new(bar_index, high, "STRONG\nSELL",89 color=color.new(color.red, 10),90 textcolor=color.white,91 style=label.style_label_down, size=size.normal)9293bgcolor(isVolSpike ? color.new(color.yellow, 94) : na, title="Vol Spike BG")Multiple signal tiers
Dual message format
useWebhook toggle switches between human-readable messages (for push notifications) and JSON payloads (for webhook endpoints). One indicator serves both use cases.Anti-repainting safeguards
barstate.isconfirmed and uses alert.freq_once_per_bar_close. Double protection ensures signals only fire on confirmed bar closes, never on intrabar fluctuations.Visual confirmation
You have completed PineScript Foundations
1.In PineScript, what is the difference between 'var' and regular variable declaration?
2.What does the PineScript function 'plot()' do versus 'plotshape()'?
3.What is the maximum number of plot outputs allowed per PineScript script?
4.What is the difference between 'alert()' and 'alertcondition()' in PineScript?
5.When publishing a PineScript indicator, what is the key difference between 'open-source' and 'invite-only' access?
Put this lesson to work
Free on Thrive, no account needed.