Your own functions in Pine Script (and the if-trap) · Pine Script EP 09 #shorts

Stop copy-pasting the same Pine code for 20, 50 and 100 bars. Write it once as a user-defined function: name(params) => and an indented body below the header. Each call returns the result of the last line of the body, so mid(len) returns (hi + lo) / 2 and you can call mid(20), mid(50), mid(100) as often as you like. Functions are defined in the script’s global scope. The deep point: a function that uses ta.* keeps its own history, so it should be called on every bar — calling it inside an if makes the compiler warn that it “should be called on each calculation for consistency”. Call it in the global scope, store the result, and use the result inside the if.

The code:
//@version=6
indicator(“Demo · function”, overlay = true)
mid(len) =>
hi = ta.highest(high, len)
lo = ta.lowest(low, len)
(hi + lo) / 2
plot(mid(20), color = color.orange)
plot(mid(50), color = color.gray)

Pine Script EP 09. Next: EP 10 — other timeframes (request.security).

Educational example.

Your rules. Coded. · marketalgobot.com
https://marketalgobot.com

#pinescript #tradingview #coding #learntocode #marketalgobot