简体   繁体   中英

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)

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM