FlowScript: Code Your Own Indicators · Lesson 6 of 10 · 11 min

Your own functions, lists and maps

Package logic with def, keep many values in a list, and count things in a map.

Once a script grows, repeat yourself less. def creates a function. Each place you call it keeps its own state, so a function that uses ema() or var behaves like a built-in: two calls never share an average.

indicator("Trend score", overlay = false)

// +1 above a rising average, -1 below a falling one, 0 otherwise.
def trend(length)
    e = ema(close, length)
    close > e and e > e[1] ? 1 : close < e and e < e[1] ? -1 : 0

score = trend(20) + trend(50) + trend(200)
plot(score, "Score", style = columns, color = score > 0 ? green : score < 0 ? red : gray)

A list holds many values: write [1, 2, 3] or start empty with array(). Add with push, drop the oldest with shift, read with xs[0] (negative positions count from the end). Methods read naturally: levels.push(high) is the same as push(levels, high).

indicator("Last five swing highs", overlay = true)

var swings = array()
ph = pivothigh(5, 5)
if not na(ph)
    swings.push(ph)
    if swings.size() > 5
        swings.shift()

for level in swings
    if close > level
        bgcolor(fade(green, 4))
        break
plot(swings.size() > 0 ? max(swings) : na, "Highest of the five", color = amber, style = step)

A map stores values by name. Loop over it with for key, value in m.

indicator("Up and down days", overlay = false)

var counts = map()
if new_session
    side = close[1] > open[1] ? "up" : "down"
    counts[side] = nz(counts[side]) + 1
plot(nz(get(counts, "up")) - nz(get(counts, "down")), "Up minus down")

Key takeaways

  • def packages logic; every call site keeps its own state.
  • Lists: push, shift, xs[i], for item in xs.
  • Maps: m["key"] = value, for key, value in m.

Next: Labels, lines, boxes and tables