如何在Pine Script中将固定变量动态化?实现a遍历0至100
Pine Script实现变量遍历0到100的解决方案
你可以用Pine Script v5的**for循环**来实现遍历0到100的数值,不需要创建多个变量。核心思路是循环遍历每个目标值,逐一判断交叉条件并执行对应的逻辑。
修改后的完整代码
//@version=5 indicator(title="Stochastic", shorttitle="Stoch", overlay = true, format=format.price, precision=2, max_bars_back=1000) periodK = input.int(14, title="%K Length", minval=1) smoothK = input.int(3, title="%K Smoothing", minval=1) periodD = input.int(3, title="%D Smoothing", minval=1) k = ta.sma(ta.stoch(close, high, low, periodK), smoothK) d = int(ta.sma(k, periodD)) //plot(k, title="%K", color=#2962FF) plot(d, title="%D", color=#FF6D00) // 遍历0到100的所有数值 for val in 0..100 // 可选:如果需要显示所有水平线,取消下面注释(但会导致图表过于密集) // plot(val, tostring(val), color=color.new(color.yellow, 90)) // 判断当前值与d线的交叉条件 bool isCond1 = ta.cross(d, val) if isCond1 // 标签文本显示对应的交叉数值,方便识别 label.new(bar_index, val, text = "cross " + tostring(val), color=color.yellow, textcolor=color.black)
关键修改说明
- 用
for val in 0..100遍历0到100的整数,val会依次取0、1、2……100 - 循环内对每个
val执行交叉判断ta.cross(d, val),满足条件时创建标签,标签文本附带当前val值,方便区分是哪个数值的交叉 - 如果你不需要显示所有0-100的水平线,可以保留原来的单条水平线代码,或者完全移除;如果要显示,取消
plot(val)的注释,但因为线太多会很密集,建议给颜色加透明度(比如color.new(color.yellow, 90))
内容的提问来源于stack exchange,提问作者Владислав Паршаков
相关产品推荐
相关产品推荐

