Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last value that equals the current value in TradingView Pine Script?

Tags:

pine-script

I am using Pine Script which is used in tradingview.com.

My question is: how I can get the last value that equals the current value? I thought about using a for loop or something else.

I tried this code but it returns an error:

getval(x,y) =>
    for i = 1 to 100
        val = valuewhen(i, y, 1)
        val2 = valuewhen(x=i, val, 1)
    val2
like image 820
Bassel Alahmad Avatar asked Oct 17 '22 15:10

Bassel Alahmad


1 Answers

To get the last value that equals the current value (using pine script version 3), you should write something like this :

getval(x,y) =>
    val = 0.0
    val2 = 0.0
    for i = 1 to 100 //has to be indented as well
        val := valuewhen(i,y, 1)
        val2 := valuewhen(x == i, val, 1) //== for a condition, = is to assign a value to a variable
    val2 ? val2 : val //if val2 exists, return val2, else return val)

It works, I tried it, when you will be calling your function, don't forget to give it the parameters, for example :

getval(1, 3) 
like image 69
MIG-23 Avatar answered Oct 21 '22 01:10

MIG-23