Appearance
RSI with alerts
How do you build an indicator with its own settings that alerts you when something happens? This one plots the RSI, marks where it leaves the oversold and overbought zones, and offers an alert for each.
pine
//@version=6
indicator("RSI with alerts")
int len = input.int(14, "Length", minval = 2)
float overbought = input.float(70, "Overbought", minval = 50, maxval = 100)
float oversold = input.float(30, "Oversold", minval = 0, maxval = 50)
float r = ta.rsi(close, len)
plot(r, "RSI", color.blue)
hline(overbought, "Overbought", color.gray)
hline(oversold, "Oversold", color.gray)
bool leftOversold = ta.crossover(r, oversold)
bool leftOverbought = ta.crossunder(r, overbought)
plotshape(leftOversold, "Left oversold", shape.triangleup,
location.bottom, color.teal)
plotshape(leftOverbought, "Left overbought", shape.triangledown,
location.top, color.maroon)
// Fires on each bar where its condition is true
alertcondition(leftOversold, "RSI left oversold",
"RSI crossed back above the oversold line")
// Fires when the code reaches it, with a message built from values
if leftOverbought
alert("RSI on " + syminfo.ticker + " left overbought",
alert.freq_once_per_bar_close)How it works
input.intandinput.floatput the length and the two levels in the study's Settings. Each returns its default until you change it there, and then the script runs again.minvalandmaxvalkeep the values sensible.ta.rsi(close, len)is the relative strength index of the closes.hlinedraws a horizontal line at a fixed level. It takes a number known before the first bar, which an input is.ta.crossover(r, oversold)is true on the bar where the RSI moves from at or below the level to above it.ta.crossunderis the opposite.plotshapedraws a marker on each bar where its condition is true, here at the pane's bottom or top.alertconditiondeclares an alert with a fixed title and message. It fires on each bar where its condition is true.alertfires when the code inside itsifruns.alert.freq_once_per_bar_closefires it at most once a bar, at the bar's close.
Getting the alerts
On a chart, neither call does anything. Save the script, open the Alerts pane, add an alert of kind A script's alerts, and pick this script, a symbol and a timeframe. The server then runs the script at each bar's close and fires both alerts where they hold. Alerts has the rest.
Traps
- A cross is decided at the close. On a live bar,
ta.crossovercan be true for a few ticks and false at the close. An alert rule here runs the script on closed bars only, so such a cross never fires, and on TradingViewalert.freq_once_per_bar_closedoes the same. ta.*calls belong outside theif. Ata.rsiinside a branch runs only on the bars that reach it, so it would see a different history. Compute first, then decide.