I want to receive a buy signal when the moving averages are first placed in the order below:
sma200>sma100>sma50>sma20
and get a sell signal when the following order was first established:
sma200<sma100<sma50<sma20
this is my code :
study(title="4SMA", shorttitle="4SMA", overlay=true)
SMA1 = input(20, minval=1, title="SMA1"),
SMA2 = input(50, minval=1, title="SMA2")
SMA3 = input(100, minval=1, title="SMA3")
SMA4 = input(200, minval=1, title="SMA4"),
plot(sma(close, SMA1), color=green, linewidth=2)
plot(sma(close, SMA2), color=yellow, linewidth=2)
plot(sma(close, SMA3), color=orange, linewidth=2)
plot(sma(close, SMA4), color=red, linewidth=2)
Here is your Pine v4 4SMA
study turned into a Pine v5 indicator on which you can create the buy/sell alerts:
//@version=5
indicator(title = "4SMA", shorttitle = "4SMA", overlay = true, max_labels_count = 500)
// Inputs
int sma1Length = input.int(20, minval = 1, title = "SMA1")
int sma2Length = input.int(50, minval = 1, title = "SMA2")
int sma3Length = input.int(100, minval = 1, title = "SMA3")
int sma4Length = input.int(200, minval = 1, title = "SMA4")
// TA calculations
float sma1 = ta.sma(close, sma1Length)
float sma2 = ta.sma(close, sma2Length)
float sma3 = ta.sma(close, sma3Length)
float sma4 = ta.sma(close, sma4Length)
// Signals
// Every time the SMAs are aligned as sma4 > sma3 > sma2 > sma1 on bar close, consider it as a buy signal (only once every time the EMAs are aligned)
bool buySignal = barstate.isconfirmed and ta.change(sma4 > sma3 and sma3 > sma2 and sma2 > sma1) and (sma4 > sma3 and sma3 > sma2 and sma2 > sma1)
// Every time the SMAs are aligned as sma4 < sma3 < sma2 < sma1 on bar close, consider it as a sell signal (only once every time the EMAs are aligned)
bool sellSignal = barstate.isconfirmed and ta.change(sma4 < sma3 and sma3 < sma2 and sma2 < sma1) and (sma4 < sma3 and sma3 < sma2 and sma2 < sma1)
// Alerts
// Create alert conditions so they can be used as a "Condition" in the alert creation dialog
alertcondition(buySignal, "Buy signal", "Buy signal message")
alertcondition(sellSignal, "Sell signal", "Sell signal message")
// Plots
plot(sma1, color = color.green, linewidth = 2)
plot(sma2, color = color.yellow, linewidth = 2)
plot(sma3, color = color.orange, linewidth = 2)
plot(sma4, color = color.red, linewidth = 2)
// Labels (for debugging purposes, so that you know where each alert would have been sent in the past)
if buySignal
label.new(bar_index, high, "Buy signal", style = label.style_label_down, color = color.green, textcolor = color.white)
if sellSignal
label.new(bar_index, low, "Sell signal", style = label.style_label_up, color = color.red, textcolor = color.white)
When you create the alert, select the indicator & the desired signal: