005 — Conditions and signals
A signal begins as a Boolean condition: an expression that is either true or false.
In this lesson, we will mark fast and slow exponential moving-average crossovers.
Complete script
Section titled “Complete script”//@version=6indicator("EMA Crossover Signals", overlay = true)
int fastLength = input.int(9, "Fast EMA", minval = 1)int slowLength = input.int(21, "Slow EMA", minval = 1)
float fastEma = ta.ema(close, fastLength)float slowEma = ta.ema(close, slowLength)
bool bullishCross = ta.crossover(fastEma, slowEma)bool bearishCross = ta.crossunder(fastEma, slowEma)
bool bullishSignal = barstate.isconfirmed and bullishCrossbool bearishSignal = barstate.isconfirmed and bearishCross
plot(fastEma, "Fast EMA", color = color.teal, linewidth = 2)plot(slowEma, "Slow EMA", color = color.orange, linewidth = 2)
plotshape( bullishSignal, title = "Bullish signal", style = shape.triangleup, location = location.belowbar, color = color.green, size = size.small, text = "BUY")
plotshape( bearishSignal, title = "Bearish signal", style = shape.triangledown, location = location.abovebar, color = color.red, size = size.small, text = "SELL")
alertcondition( bullishSignal, title = "Bullish EMA crossover", message = "Fast EMA crossed above slow EMA")
alertcondition( bearishSignal, title = "Bearish EMA crossover", message = "Fast EMA crossed below slow EMA")Crossover conditions
Section titled “Crossover conditions”bool bullishCross = ta.crossover(fastEma, slowEma)bool bearishCross = ta.crossunder(fastEma, slowEma)ta.crossover(a, b) becomes true when a moves from at or below b to above b.
ta.crossunder(a, b) becomes true when a moves from at or above b to below b.
Confirm the bar
Section titled “Confirm the bar”bool bullishSignal = barstate.isconfirmed and bullishCrossOn a realtime bar, values can change before the bar closes. Requiring barstate.isconfirmed means the marker is accepted only when the bar is confirmed.
We calculate the crossover first and then combine it with confirmation. This keeps the time-series calculation explicit and consistent.
Draw signal markers
Section titled “Draw signal markers”plotshape() displays a shape only when its first argument is true. The bullish marker appears below the bar; the bearish marker appears above it.
Add alert conditions
Section titled “Add alert conditions”alertcondition() makes a named condition available when creating a TradingView alert. It defines the trigger in code; you still create and activate the alert from TradingView’s alert interface.
Important distinction
Section titled “Important distinction”This script displays signals, but it does not simulate trades. A backtest requires a strategy() script and order functions such as strategy.entry() and strategy.exit(). We will cover those later.