You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Pine Script中Plot函数使用样式变量报错,请求解决

解决Pine Script中plot函数样式动态切换的报错问题

Hey there, let's break down what's going wrong here and get your code working smoothly.

问题根源

The error you're hitting comes down to a core Pine Script rule: the style parameter in the plot() function requires a constant value (a fixed integer that doesn't change per bar). But your cr20style variable is a series integer—it can flip between 1 and 2 on every candlestick based on your cr20_50up condition. The interpreter is clear: it can't accept a dynamic, bar-by-bar value for this parameter.

修正方案

Instead of trying to pass a changing variable to style, you'll need to create two separate plot() calls—one for each style you want—and toggle their visibility using the display parameter. Here's your adjusted code:

// Assuming d1 and d9 are already defined in your script
cr20_50up = cross(d1, d9) and d1 > d9

// Plot with first style (e.g., line with breaks, matching your original "1")
plot(d1, title='%K SMA20', color=cr20_50_color, transp=0, 
     style=plot.style_linebr,
     display=cr20_50up ? display.data : display.none)

// Plot with second style (e.g., circles, matching your original "2")
plot(d1, title='%K SMA20', color=cr20_50_color, transp=0, 
     style=plot.style_circles,
     display=not cr20_50up ? display.data : display.none)

细节说明

  • We use named style constants like plot.style_linebr and plot.style_circles instead of raw numbers—they’re far more readable and align with Pine Script’s official style definitions (you can look up all available styles in the Pine Script docs).
  • The display parameter handles visibility: when cr20_50up is true, we show the first plot and hide the second; when it’s false, we flip that behavior.

进阶优化:让样式在交叉后保持不变

If you want the style to stay set after a cross (instead of flipping on every bar), use a var variable to track the state:

var bool cr20_state = false
// Update state only when a cross occurs
cr20_state := cross(d1, d9) ? d1 > d9 : cr20_state

plot(d1, title='%K SMA20', color=cr20_50_color, transp=0, 
     style=plot.style_linebr, 
     display=cr20_state ? display.data : display.none)

plot(d1, title='%K SMA20', color=cr20_50_color, transp=0, 
     style=plot.style_circles, 
     display=not cr20_state ? display.data : display.none)

This way, the style will only change when cross(d1,d9) triggers, and stay consistent until the next cross event.

内容的提问来源于stack exchange,提问作者scottsanpedro

火山引擎 最新活动