The library()
function in Pine Script is a declaration statement that identifies a script as a library. Libraries in Pine Script are used to create modular, reusable code that can be imported and used in other scripts. This functionality is crucial for developers who want to build a collection of commonly used functions and access them across multiple scripts.
Syntax of the library()
Function
The general syntax of the library()
function is as follows:
library(title, overlay) → void
Arguments
- title (
const string
): This argument represents the title of the library and serves as its unique identifier. The title must adhere to specific rules:- It cannot contain spaces or special characters.
- It cannot begin with a digit.
- The title is used as the publication’s default title and to uniquely identify the library in the import statement when another script uses it.
- It also serves as the script’s name on the chart.
- overlay (
const bool
): This boolean argument determines how the library is displayed.- If set to
true
, the library will be added over the chart. - If
false
(which is the default value), it will be added in a separate pane.
- If set to
Example
Consider an example where we create a simple math library to calculate the hyperbolic sine function:
//@version=5 // @description Math library library("num_methods", overlay = true) // Calculate "sinh()" from the float parameter `x` export sinh(float x) => (math.exp(x) - math.exp(-x)) / 2.0 plot(sinh(0))
In this example:
- The library is declared with the title
num_methods
and is set to overlay on the chart (overlay = true
). - We define a function
sinh
using theexport
keyword, making it available for use in other scripts that import this library. - The
sinh
function calculates the hyperbolic sine of a given float parameterx
. - Finally, we use the
plot
function to display the value ofsinh(0)
on the chart.
Key Features and Takeaways
- Function Usability: The
library()
function is essential for creating modular, reusable code in Pine Script, improving code organization and efficiency. - Syntax and Application: Its syntax is straightforward, with the title and overlay arguments, making it easy to declare and use.
- Overlay Option: The
overlay
argument provides flexibility in how the library’s output is displayed on the chart, catering to different visualization needs.
By understanding and utilizing the library()
function, Pine Script users can significantly enhance their scripting capabilities, leading to more organized, efficient, and reusable code in their trading analysis.