Functions in Pine Script are powerful tools that simplify and enhance the coding experience. They allow you to create reusable blocks of code, making your scripts more organized and efficient.
This function, named 'ochl', returns an array containing four values: open, close, high, and low. The square brackets '' indicate the return values, and they must be placed at the end of the function. To utilize the returned values, we can assign them to variables like this:
In this example, we set 'isOver' to 'true' if the current 'open' is greater than the previous 'open'. This demonstrates the basic usage of functions. Now, let's explore a more practical example.
In this case, we have a function named 'newSMA' that takes two parameters: 'src' for the source and 'len' for the length. We use 'float' and 'int' before the parameters to specify their types, improving code clarity and preventing errors.
Inside the function, we can perform any desired operations. It's worth noting that variables inside the function can have the same names as outside variables without causing conflicts.
In this example, we declare a variable 'sma' that calculates the simple moving average (SMA) using the 'ta.sma' function with the specified 'src' and 'len'. Finally, we return the 'sma' value. If a function returns only one value, we don't need to use ''.
To use this function, we call it with different inputs:
Here, we define two functions: 'getVol' and 'getSum'.
'getVol' takes 'vol' as the input (volume), and it returns +1 if the current volume is greater than the previous volume; otherwise, it returns -1.
'getSum' has two parameters, 'n1' and 'n2', which will be used later.
Within 'getSum', we declare a variable 'id' and set it to 'na' (Not Available) initially.
We then check conditions using 'getVol(v)', where 'v' is the volume. Depending on the result and the values of 'n1' and 'n2', we set 'id' to either 'true' or 'false'.
Consequently, 'out1' will be 'true' if the volume > volume and 'n1' is 0 and 'n2' is 5, otherwise it will be 'false'. Similarly, 'out2' will always be 'false' as we pass 1 and 5, which do not match any of the conditions (0, 5 or 9, 7).
Functions can be very useful when running inside a security call:
This line outputs the 'ochl' values on the 1-hour time frame. It allows us to obtain four values from a security call without manually writing each one.
I hope you now have a better understanding of how Pine Script functions work! If you encounter any issues, feel free to comment below, and I'll be glad to assist you!
Informasi dan publikasi tidak dimaksudkan untuk menjadi, dan bukan merupakan saran keuangan, investasi, perdagangan, atau rekomendasi lainnya yang diberikan atau didukung oleh TradingView. Baca selengkapnya di Persyaratan Penggunaan.