Sheisback
Sheisback

Reputation: 33

TradingView Pinescript valuewhen don't work with for iterator variable(i)

I want to get lastest five curPosition with valuewhen. But It isn't working. I think calling valuewhen(curPosition>0, curPosition, i) with for i iterator is problem. Could you help me?

//@version=4
strategy(title="Test", shorttitle="Test", overlay=true)

// curPosition
// 0 == "-"
// 1 == "LONG"
// 2 == "SHORT"
curPosition = 0

longCnt = 0
shortCnt = 0
noneCnt = 0

prevPosition = 0
for i = 1 to 5
    prevPosition := valuewhen(curPosition>0, curPosition, i)
    if (prevPosition == 1)
        longCnt := longCnt + 1
    if (prevPosition == 2)
        shortCnt := shortCnt + 1
    if na(prevPosition)
        noneCnt := noneCnt + 1

if (open>close)
    curPosition := 1
if (open<close)
    curPosition := 2
plotchar(longCnt, "LONG CNT", "", location=location.top)
plotchar(shortCnt, "SHORT CNT", "", location=location.top)
plotchar(noneCnt , "NONE CNT", "", location=location.top)

Upvotes: 0

Views: 887

Answers (1)

Sheisback
Sheisback

Reputation: 33

I found root of cause. Pins script engine work strange.

Refer to pine script document, See below description.

//@version=4
study("SMA in for loop")
sum = 0
for i = 1 to 2
    sum := sum + sma(close, i)
plot(sum)

While you may expect that sum will contain sma(close, 1) + sma(close, 2), this is not so. It will contain sma(close, 1) + sma(close, 1) because once sma is initialized with length 1, this length is stored until the script is removed from chart. To avoid this you may use your own, stateless function implementation. This is the list of built-in functions which have the same behavior:

Upvotes: 1

Related Questions