Libraries
A library is a script that holds functions, types and enums for other scripts to use. It draws nothing and cannot be added to the chart.
Writing one
Begin the script with library("Name"), then define things. Put export before each one other scripts should be able to use.
//@version=5
library("MyMath")
sq(float x) =>
x * x
export hyp(float a, float b) =>
math.sqrt(sq(a) + sq(b))
export type Pair
float a
float b = 2
export enum Side
buy = "Buy"
sell
Press Save. The editor checks a library as you type, and Add to chart tells you it is a library instead of adding it.
Using one
//@version=5
indicator("Hypotenuse")
import me/MyMath/1 as m
p = m.Pair.new(3, 4)
plot(m.hyp(p.a, p.b))
import author/Name/version as alias finds the saved script whose library() title is Name. Case does not matter, and the author and version are ignored, so import MyMath as m works too. Everything exported is reached through the alias: m.hyp(...), m.Pair.new(...), m.Side.buy.
Rules
- A library can only hold
library(), imports, and function, method, type and enum definitions. - Functions without
exportare private to the library (sqabove). - A library cannot see the importing script's variables. Pass what it needs as arguments.
- Libraries can import other libraries. A loop between them is an error.
- Only saved scripts can be imported, not the unsaved text in the editor. Save the library first.
- Saving a change to a library re-runs every script on the chart that imports it.
- An error inside a library is reported on the
importline, with the library's own line number in the message.