Skip to main content

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.

pine-alertcondition() syntax and patterns
1//@version=6
2indicator("Alert Conditions Demo", overlay=true)
3
4ema21 = ta.ema(close, 21)
5ema50 = ta.ema(close, 50)
6rsi = ta.rsi(close, 14)
7
8// Basic crossover alerts
9bullCross = ta.crossover(ema21, ema50)
10bearCross = ta.crossunder(ema21, ema50)
11
12alertcondition(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")
16
17// RSI extreme alerts
18alertcondition(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")
22
23// Multi-factor confluence alert
24strongBull = bullCross and rsi > 50 and volume > ta.sma(volume, 20) * 1.5
25alertcondition(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.

pine-alert() with dynamic messages
1//@version=6
2indicator("Dynamic Alerts", overlay=true)
3
4ema21 = ta.ema(close, 21)
5rsi = ta.rsi(close, 14)
6
7bullCross = ta.crossover(close, ema21) and barstate.isconfirmed
8
9if bullCross
10 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)
18
19bearCross = ta.crossunder(close, ema21) and barstate.isconfirmed
20
21if bearCross
22 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_barFires 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_closeFires only when the bar CLOSES with the condition true. Non-repainting: the safest option for trading signals. Use this for most alerts.
alert.freq_allFires 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

For trading signals, always 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.

pine-Webhook-ready JSON alert messages
1//@version=6
2indicator("Webhook Alerts", overlay=true)
3
4ema21 = ta.ema(close, 21)
5atr = ta.atr(14)
6rsi = ta.rsi(close, 14)
7
8longSignal = ta.crossover(close, ema21) and barstate.isconfirmed
9shortSignal = ta.crossunder(close, ema21) and barstate.isconfirmed
10
11// Build a JSON payload for webhook consumption
12if longSignal
13 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)
23
24if shortSignal
25 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)
35
36plot(ema21, "EMA 21", close > ema21 ? color.green : color.red, 2)
1

Create the indicator with alert() calls

Write your PineScript indicator with alert() calls that produce JSON-formatted messages. Include all data the receiving service needs: symbol, price, stop loss, take profit, RSI, timeframe, and timestamp.
2

Add the indicator to your chart

Add the script to the chart of each asset you want to monitor. The script must be actively running on a chart for alerts to fire.
3

Create a TradingView alert

Right-click the chart β†’ β€œAdd alert” β†’ select your indicator from the dropdown β†’ choose the alert condition β†’ in the β€œWebhook URL” field, paste your endpoint URL. The message from your alert() call becomes the POST body.
4

Configure the receiving service

Set up a webhook receiver (3Commas, Alertatron, a custom server, or a Telegram bot) to parse the incoming JSON and execute the desired action. Place a trade, log to a spreadsheet, or send a notification.

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:

Open Source

Full source code is visible to everyone. Best for community contribution, getting feedback, and qualifying for TradingView's Editors' Pick program. Builds reputation.

Protected

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.

Invite-Only

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

1

Write a detailed description

Explain what the indicator does, what market conditions it works best in, how to interpret the signals, and what the configurable inputs control. Include example charts showing the indicator in action. Descriptions with 500+ words and multiple screenshots get significantly more engagement.
2

Choose the right category

TradingView categorizes scripts into types: Indicators, Strategies, Libraries, and Education. Within indicators, choose the most specific subcategory: Trend Analysis, Oscillators, Volume, Volatility, etc. Proper categorization improves discoverability.
3

Include release notes

When you update a published script, write clear release notes explaining what changed. Users who have your script on their charts will see the update notification. Professional changelogs build trust.
4

Respond to comments

Active community engagement dramatically increases script visibility. Answer questions, accept feature requests, and acknowledge bug reports. TradingView's algorithm promotes scripts with active authors.

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 tabClick "Indicators" on the chart toolbar, then browse "Community Scripts." Filter by type, sort by likes or recency.
Source code reviewFor open-source scripts, always read the code before using. Look for clean structure, proper na handling, and no repainting issues.
Pine WizardsTradingView's top script authors are verified "Pine Wizards." Their scripts are generally high quality and well-maintained.
Script searchUse 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.

pine-Importing a library
1//@version=6
2indicator("Library Usage Demo", overlay=true)
3
4// Import a published library (format: Username/LibraryName/version)
5// import TradingViewUsername/MathUtils/1 as utils
6
7// After importing, call exported functions with the alias
8// smoothedRSI = utils.customSmoothing(ta.rsi(close, 14), 5)
9
10// You can import multiple libraries
11// import AnotherUser/RiskCalc/2 as risk
12// import AnotherUser/Plotting/1 as viz
13
14// Libraries are versioned: /1 means version 1
15// If the author publishes /2, your script keeps using /1 until you update
16
17// Common library categories on TradingView:
18// - Mathematical utilities (custom smoothing, statistics)
19// - Drawing helpers (auto-fibonacci, zone detection)
20// - Risk management calculators
21// - Signal generation frameworks
22// - String formatting utilities
23
24plot(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.

Language Reference

Complete API documentation for every built-in function, variable, constant, and type. Searchable and organized by namespace.

User Manual

Conceptual guides covering the execution model, type system, scoping rules, and advanced features like UDTs and methods.

Pine Editor Tooltips

Hover over any function in the editor to see inline documentation with parameter descriptions and examples.

Migration Guides

Step-by-step instructions for converting scripts between PineScript versions (v4β†’v5, v5β†’v6).

Release Notes

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 inferencev6 is smarter about inferring types, reducing the need for explicit declarations in many common patterns.
Error messagesSignificantly improved: more specific, more actionable, with better line number reporting and suggestions.
Runtime performanceOptimized execution engine with faster array operations, reduced memory usage, and better handling of large datasets.
Function overloadingDefine multiple versions of a function with different parameter types: the compiler selects the right one based on call arguments.
Backward compatibilityMost 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.

pine-Professional Alert System (full script)
1//@version=6
2indicator("Pro Alert System", overlay=true, max_labels_count=50)
3
4// ── Inputs ──────────────────────────────────────
5grpTrend = "Trend"
6emaFast = input.int(9, "Fast EMA", group=grpTrend)
7emaSlow = input.int(21, "Slow EMA", group=grpTrend)
8
9grpMom = "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)
13
14grpVol = "Volume"
15volMult = input.float(1.5, "Volume Spike Multiplier", step=0.1, group=grpVol)
16
17grpAlert = "Alerts"
18useWebhook = input.bool(false, "Format as JSON Webhook", group=grpAlert)
19
20// ── 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 * volMult
27confirmed = barstate.isconfirmed
28
29// ── Signal Definitions (confirmed bars only) ────
30bullTrend = ta.crossover(fast, slow) and confirmed
31bearTrend = ta.crossunder(fast, slow) and confirmed
32bullMom = ta.crossover(rsi, rsiOS) and confirmed
33bearMom = ta.crossunder(rsi, rsiOB) and confirmed
34bullConflu = bullTrend and rsi > 50 and isVolSpike
35bearConflu = bearTrend and rsi < 50 and isVolSpike
36
37// ── Alert Message Builder ───────────────────────
38buildMsg(signalType, direction) =>
39 if useWebhook
40 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 else
49 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, "#.#"))
54
55// ── Fire Alerts ─────────────────────────────────
56if bullTrend
57 alert(buildMsg("EMA_CROSS", "LONG"), alert.freq_once_per_bar_close)
58if bearTrend
59 alert(buildMsg("EMA_CROSS", "SHORT"), alert.freq_once_per_bar_close)
60if bullMom
61 alert(buildMsg("RSI_BOUNCE", "LONG"), alert.freq_once_per_bar_close)
62if bearMom
63 alert(buildMsg("RSI_BREAK", "SHORT"), alert.freq_once_per_bar_close)
64if bullConflu
65 alert(buildMsg("CONFLUENCE", "LONG"), alert.freq_once_per_bar_close)
66if bearConflu
67 alert(buildMsg("CONFLUENCE", "SHORT"), alert.freq_once_per_bar_close)
68
69// ── Static alertconditions for backward compatibility ──
70alertcondition(bullConflu, "Bull Confluence", "Bullish confluence signal")
71alertcondition(bearConflu, "Bear Confluence", "Bearish confluence signal")
72
73// ── 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)
80
81// Confluence labels (rare, high-value signals)
82if bullConflu
83 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 bearConflu
88 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)
92
93bgcolor(isVolSpike ? color.new(color.yellow, 94) : na, title="Vol Spike BG")
1

Multiple signal tiers

The system fires different alerts for different signal types: simple EMA crosses, RSI bounces, and full confluence signals. This lets you set up different notification channels: Telegram for confluence only, email for all signals.
2

Dual message format

The useWebhook toggle switches between human-readable messages (for push notifications) and JSON payloads (for webhook endpoints). One indicator serves both use cases.
3

Anti-repainting safeguards

Every signal is gated by barstate.isconfirmed and uses alert.freq_once_per_bar_close. Double protection ensures signals only fire on confirmed bar closes, never on intrabar fluctuations.
4

Visual confirmation

Every alert type has a corresponding visual marker on the chart. When you receive a notification, you can open the chart and immediately see the signal that triggered it. Visual confirmation is essential for building trust in your alert system.

You have completed PineScript Foundations

You now understand variables, types, the execution model, operators, control flow, functions, arrays, maps, matrices, all visualization techniques, alert systems, and publishing. The next step is practice: pick a trading idea, build it in PineScript, iterate until it is polished, and consider publishing it to the TradingView community. Every professional-grade indicator started as someone's learning project.
Module Quiz

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?

0/5 answered

Put this lesson to work

Free on Thrive, no account needed.