Library Feature introduced in PineScript version 5

Library in PineScript 5

PineScript 5 launched in Oct 2021 has Library Feature that allows users to import functions from another file saved as library file. 

Library filetype has been introduced in pinescript 5, the way a study code or strategy code were created in version 4 of pinescript, now you can also create a library file. This library file can contain one or more functions that can be exported from the library file. 

Export in PineScript 5

For export of function from pinescript , you will be required to add export keyword before the function name and save the file containing function as a library file. A example is shown below for understanding 

01: //@version=5
02:
03: library("myEMA")
04:
05: export myEMA(int x) =>
06:  ta.ema(close,x)

In the above code at line no 5 export keyword is used with the custom function myEMA which takes one integer variable as input. At line no 3, the file has been defined as a library file. A library file can have one or many functions and all or some of them can be exported from the file. 

To be able to export a function, the saved library file has to be published. You can either publish the library file as "public" or "private". Each library file when publish will prove a link for importing thr functions exported in the library file.  

Import in PineScript 5

The functions can be imported in a indicator or a strategy file as per the requirement of use, The "import" keyword can be used for importing all the functions exported by the export keyword from the librry file that has been published. 

The import keyword is followed by the path of the published library file. Usually the name of the path is [username]/[title of the library file]/[version of the library file]

Below is a simple code to import the function exported vide the library file discussed in the code of previous section.

01: //@version=5
02: indicator("test lib")
03: import username/myEMA/1 as s
04: plot(s.myEMA(7))
05: plot(s.myEMA(14))

The above code will import the functions of the library file and store all the functions thus imported in the container or alias name "S". Any of the function exported can be accessed from this alias name by using a dot operator. For example "s.myEMA".

Resources

Highest Rated Udemy Course on PineScript - Grab your Seat Now 

Udemy Discount Coupon Code : UDEMY-JAN23 (Valid upto 30th Nov 2023)

Learn more about coding on tradingview in PineScript through Books on pinescript available on amazon and kindle.


200+ pages book100 pages book200+ pages book


Point and Figure Charts : A Time-Tested Tool for Technical Analysis

In the dynamic world of financial markets, investors and traders constantly seek tools that can provide valuable insights into market trends...