Skip to content

A script as a function ​

How do you reuse a saved indicator in another script without copying its code? Import it and call .run(). You get its plots as values, can set its inputs, and can run it on another timeframe, while the original keeps working on its own chart.

Save this indicator as SmaCross:

pine
//@version=6
indicator("SMA cross", overlay = true)
int fastLen = input.int(20, "Fast")
int slowLen = input.int(50, "Slow")
float fast = ta.sma(close, fastLen)
float slow = ta.sma(close, slowLen)
plot(fast, "Fast", color.teal)
plot(slow, "Slow", color.orange)

Then read it from another script:

ameno
indicator("Two crosses", overlay = true)
import Me/SmaCross/1 as cross

// Every plot, in order
[fast, slow] = cross.run()
// The "Slow" plot, with its slowLen input set to 200
float slow200 = cross.run("Slow", slowLen = 200)
// The whole script on weekly bars
float wkSlow = request.security(syminfo.tickerid, "1W", cross.run("Slow"))
bool up = fast > slow

plot(slow200, "SMA 200", color.gray)
plot(wkSlow, "Weekly SMA 50", color.purple)
bgcolor(up ? color.new(color.teal, 92) : na)

How it works ​

  • import Me/SmaCross/1 as cross finds the saved script by its name, the word before the version number. The author and the version are there for TradingView's form; here only the name decides.
  • cross.run() runs the whole script in this one's context and returns its plots, in the order it plots them: here a tuple of two.
  • cross.run("Slow", slowLen = 200) returns only the plot titled "Slow", with the input declared as slowLen set to 200. It runs side by side with the first call, each with its own state.
  • request.security(..., "1W", cross.run("Slow")) runs the whole script on weekly bars, as any expression inside a request runs.
  • A call draws nothing. The imported script's plots become values, and its bgcolor or hline calls are dropped. Its inputs don't appear in this script's Settings.

Change SmaCross, and every script that reads it follows on its next run.

Traps ​

  • The read is AmenoScript. .run() is an addition, so a script that calls it is AmenoScript and runs leak-safe, and the imported script can't use lookahead_on or varip either.
  • A call inside a for loop shares one state across the loop, as a ta.* call there does.

See also ​

AmenoScript is compatible with Pine Script v6. Pine Script is a trademark of TradingView, Inc., which has no part in AmenoScript.