首页 > 解决方案 > 无法在 IF 语句中声明全局变量(Pine 脚本)

问题描述

我是 Pine Script 的新手,在 if 中声明一个变量并在另一个 if 中使用它时遇到了一些问题...

在第一个 if 语句中,我试图获取多头信号(LongPrice)的“收盘价”。在第二个 if中,我尝试获取空头信号 ( ShortPrice ) 的“收盘价”并将其从“LongPrice”中减去。但是“LongPrice”的值在它自己的 if 语句之外没有改变!

据我了解,这意味着该变量在 if 语句之外无效。有没有办法改变这个?

LongPrice = 0
ShortPrice = 0

if mmeLong
    LongPrice = close  // Get the Long signal's close price
    label.new(bar_index, na, tostring(LongPrice), 
         color=color.green, 
         textcolor=color.white,
         style=label.style_labelup, yloc=yloc.belowbar)

if mmeShort
    ShortPrice = close - LongPrice  // Get the Short signal's close price and minus it with the last Long close price.
    label.new(bar_index, na, tostring(ShortPrice), 
         color=color.red, 
         textcolor=color.white,
         style=label.style_label_down, yloc=yloc.abovebar)

谢谢

标签: if-statementglobal-variablespine-script

解决方案


:=当你再次声明它时,让它成为全球性的。

var float LongPrice = na
var float ShortPrice = na

if mmeLong
    LongPrice := close  // Get the Long signal's close price
    label.new(bar_index, na, tostring(LongPrice), 
         color=color.green, 
         textcolor=color.white,
         style=label.style_labelup, yloc=yloc.belowbar)

if mmeShort
    ShortPrice := close - LongPrice  // Get the Short signal's close price and minus it with the last Long close price.
    label.new(bar_index, na, tostring(ShortPrice), 
         color=color.red, 
         textcolor=color.white,
         style=label.style_label_down, yloc=yloc.abovebar)

推荐阅读