Question

Why is there an undeclared identifier 'alert' in Pine Script?

Answer and Explanation

The error "undeclared identifier 'alert' in Pine Script" occurs because Pine Script, which is the scripting language used on TradingView, does not support the alert() function familiar from languages like JavaScript.

Pine Script is designed for creating trading strategies and indicators, and it provides its own set of functions for tasks such as generating visual outputs on charts and triggering alerts through TradingView's alert system. The alert() function, which displays a popup message in a web browser, is not relevant to Pine Script's purpose.

Instead of alert(), you should use Pine Script's built-in functions for triggering alerts, such as the alert() function (note the capitalization is important in Pine Script), or for displaying information on the chart using functions like plot() or label.new().

Here's a breakdown:

1. Pine Script's Purpose: Pine Script is specific to TradingView and is intended for chart analysis and strategy backtesting, not for general-purpose programming. It's environment is server-side, not client-side like a web browser.

2. TradingView Alerts: To trigger an alert through TradingView, use the alert() function in Pine Script. This function can be configured to send notifications when specific conditions are met.

Example of using the alert() function in Pine Script:

//@version=5
indicator(title="Example Alert", shorttitle="Alert Example", overlay=true)

// Condition for generating an alert
longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))

if (longCondition)
   alert("Price crossed above moving average!", alert.freq_once_per_bar)
if (shortCondition)
   alert("Price crossed below moving average!", alert.freq_once_per_bar)

In this example, an alert will be triggered when the 14-period Simple Moving Average (SMA) crosses above or below the 28-period SMA. The alert.freq_once_per_bar argument ensures that the alert is only triggered once per bar.

3. Displaying Information: If you want to display information directly on the chart, use functions like plot(), label.new(), or line.new(). These functions create visual elements on the chart.

For example:

//@version=5
indicator(title="Price Label", shorttitle="PriceLabel", overlay=true)

label.new(bar_index, high, text=str.tostring(close), color=color.blue, style=label.style_labeldown)

In summary, the "undeclared identifier 'alert'" error means you're trying to use a JavaScript function in Pine Script, which isn't supported. Use Pine Script's alert() function for TradingView alerts, and plot() or label.new() to display information on the chart.

More questions