Patterns worth knowing
Carry a value forward
var level: float = nan
level := nz(level[1], nan)
if ta.crossover(close, ta.sma(close, 50)) {
level := close
}
plot.hline(level, "#22C55E", 1, "dashed", "Trigger")Reset something once per session
History indexing works on a series name, never on a call, so store the session test in a series first and read its previous value from there.
let in_cash: bool = session.in("0930-1600", "America/New_York")
let was_in_cash: bool = bar_index > 0 && in_cash[1]
let first_bar: bool = in_cash && !was_in_cash
var session_high: float = nan
session_high := nz(session_high[1], high)
if first_bar {
session_high := high
}
if in_cash {
session_high := math.max(session_high, high)
}
plot.hline(session_high, "#22C55E", 1, "dashed", "Session high")Values that can be absent
Divide anyway, because division by zero returns nan rather than infinity, and then decide what an absent value should read as with nz, or with ? : when the two cases need different values. Use an if branch when they need different work.
let total: float = tape.volume()
let delta_percent: float = tape.delta() / total * 100
let readable: string = format.fixed(nz(delta_percent, 0), 1)
let known: bool = !is_nan(delta_percent)
plot.text(known, high, readable, "#9CA3AF", "above", 9, 4, 60)Use a data family when it is there, and never assume it
let has_depth: bool = l2.supported() && l2.available()
let book_lean: float = l2.imbalance(10)
let tape_lean: float = tape.delta() / tape.volume()
var lean: float = 0
lean := nz(tape_lean, 0)
if has_depth {
lean := nz(book_lean, 0)
}
plot.histogram(lean, "#22C55E", "#EF4444")Draw once at the right edge
let projection: float = close + ta.stdev(close, 20) * 2
plot.text(last_bar, projection, format.fixed(projection, 2), "#E5E7EB", "above", 10, 12, 40)
plot.marker(last_bar, projection, "#22C55E", "diamond", "above", 8, 3)
plot.label(str.concat("BARS ", format.compact(bar_count)), "#6B7280")Count the bars since something happened
let crossed: bool = ta.crossunder(close, ta.ema(close, 21))
plot.histogram(nz(ta.barssince(crossed), 0), "#6B7280", "#6B7280")Pick between several colours
let strength: float = tape.delta() / tape.volume()
let bar_color: color = strength > 0.3 ? "#22C55E" : strength < -0.3 ? "#EF4444" : "#6B7280"
plot.candle_color(tape.available(), bar_color, 0.8)Colour on a scale
let strength: float = tape.delta() / tape.volume()
let heat: color = color.from_gradient(nz(strength, 0), -0.5, 0.5, "#EF4444", "#22C55E")
let faded: color = color.new(heat, 60)
plot.candle_color(tape.available(), faded, 1)