首页 > 解决方案 > Pinescript 嵌套的 if(或 else if)条件对 crossunder() 的评估不同于首先将其计算为变量

问题描述

所以我正在编写一个关于 pinescript 的指标。在编写同一段代码的两种方式之间使用嵌套的 if 语句,我似乎得到了不同的行为

crossover  = crossover(tradeEntrySource, ind)
crossunder = crossunder(tradeEntrySource, ind)
  // use statement directly
  longStopLossCheck := if (not crossover)
      if (crossunder(tradeEntrySource, ind))
          true
      else
          false

对比

  // precalculate and use variable
  longStopLossCheck := if (not crossover)
      if (crossunder)
          true
      else
          false
plot(series=longStopLossCheck?3:2, title="longStopLossCheck", color = color.red)
plot(series=crossunder?2:1, title="crossunder", color = color.blue)
plot(series=crossover?1:0, title="crossover", color = color.green)

在嵌套 if 语句中使用 crossunder() 函数 在嵌套 if 语句中使用 crossunder 变量

第一张图显示了当我直接使用语句时返回的值,第二张图是当我使用变量时

我似乎无法弄清楚为什么我会看到不同的价值观/行为。关于为什么会发生这种情况的任何见解?提前致谢!

标签: pine-script

解决方案


像这样的函数crossover()需要在每根柱上执行才能返回正确的结果,当它们从阻止它们在每根柱上执行的条件块中调用时就不会出现这种情况。在进入结构之前预先评估这些功能if是解决方案。

请参阅有关该主题的Pine 用户手册,以及有关该主题的 PineCoders 常见问题解答中可能更易于理解的文章。

披露:此答案中的链接指向 PineCoders 常见问题解答条目。我是 PineCoders 社区的成员,我很可能写了那个常见问题解答条目。PineCoders 是由 TradingView 支持的志愿者 Pine 编码员小组,PineCoders 的网站具有严格的教育性质。TradingView 和 PineCoders 都不会从向 pinecoders.com 发送流量中获得经济利益,并且该网站不包含任何附属/推荐链接。


推荐阅读