编写Pine Script买入信号代码遇报错:plotshape无法在局部作用域使用
Pine Script 报错解决:Cannot use 'plotshape' in local scope
问题场景
编写Pine Script代码时,需求为:当收盘价满足连续下跌m天 + 连续上涨n天的条件时触发买入信号。运行代码时出现报错:
Cannot use 'plotshape' in local scope
备注提示:
Use plotshape function in conjuction with 'overlay=true' indicator parameter
原代码如下:
//@version=5 indicator("Price Movement Check", overlay = true) // Set input parameters for n and m n = input.int(title="Days for price increase check", defval=5) m = input.int(title="Days for price decrease check", defval=2) // Check if close price is increasing for n days isIncreasing = true for i = 1 to n isIncreasing := isIncreasing and close[i] > close[i-1] // Check if close price is decreasing for m days isDecreasing = true for i = 1 to m isDecreasing := isDecreasing and close[i] < close[i-1] // Plot a shape if both conditions are true if isIncreasing and isDecreasing plotshape(true, style=shape.triangleup, location=location.abovebar, offset=-n, color=#009688, size=size.small)
报错原因
Pine Script v5的绘图函数(如plotshape)不允许放在局部作用域内(比如if代码块),必须在全局作用域中直接调用,通过函数的条件参数控制是否显示图形,而非用if包裹函数调用。
修复后的代码
//@version=5 indicator("Price Movement Check", overlay = true) // Set input parameters for n and m n = input.int(title="Days for price increase check", defval=5) m = input.int(title="Days for price decrease check", defval=2) // Check if close price is increasing for n days isIncreasing = true for i = 1 to n isIncreasing := isIncreasing and close[i] > close[i-1] // Check if close price is decreasing for m days isDecreasing = true for i = 1 to m isDecreasing := isDecreasing and close[i] < close[i-1] // Plot a shape when both conditions are true (直接在全局作用域调用plotshape) plotshape(isIncreasing and isDecreasing, style=shape.triangleup, location=location.abovebar, offset=-n, color=#009688, size=size.small)
修复说明
- 移除了包裹
plotshape的if语句,将条件isIncreasing and isDecreasing直接作为plotshape的第一个参数传入 plotshape会在每个K线周期自动评估该条件,仅当条件为true时绘制三角形信号- 保留原有的
offset=-n设置,确保信号绘制在连续上涨阶段结束的位置
内容的提问来源于stack exchange,提问作者D3ADL8CK
相关产品推荐
相关产品推荐

