简体   繁体   English

TradingView Pinescript valuewhen 不适用于迭代器变量(i)

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

I want to get lastest five curPosition with valuewhen.我想获得最新的五个带有 valuewhen 的 curPosition。 But It isn't working.但它不起作用。 I think calling valuewhen(curPosition>0, curPosition, i) with for i iterator is problem.我认为用 for i 迭代器调用 valuewhen(curPosition>0, curPosition, i) 是有问题的。 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. Pins 脚本引擎工作起来很奇怪。

Refer to pine script document, See below description.参考 pine 脚本文档,见下文描述。

//@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.虽然您可能期望 sum 将包含 sma(close, 1) + sma(close, 2),但事实并非如此。 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.它将包含 sma(close, 1) + sma(close, 1) 因为一旦 sma 以长度 1 初始化,这个长度就会被存储,直到脚本从图表中删除。 To avoid this you may use your own, stateless function implementation.为避免这种情况,您可以使用自己的无状态 function 实现。 This is the list of built-in functions which have the same behavior:这是具有相同行为的内置函数列表:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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