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_linebrandplot.style_circlesinstead 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
displayparameter handles visibility: whencr20_50upis 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




