Pine Script for循环传参报错:series int与simple int类型不匹配咨询
Pine Script v6:循环调用自定义RSI函数的类型不匹配错误解决
问题重现
你编写的自定义RSI函数pine_rsi直接调用时正常运行,但放入for循环后出现编译错误:
Error at 25:45 Cannot call 'pine_rsi' with argument 'len'='call 'operator -' (series int)'. An argument of 'series int' type was used but a 'simple int' is expected.
报错原因
- 变量类型差异:
- 直接调用时,
rsi_period-0、rsi_period-1这类表达式是编译期可确定的常量,属于simple int类型,符合pine_rsi函数定义中int len参数的类型要求。 for循环中的i是序列类型(series int):Pine Script的循环是逐K线执行的,循环变量i会被视为随K线变化的序列值,因此rsi_period-i的计算结果是series int,与函数要求的simple int类型不匹配。
- 直接调用时,
- 函数参数约束:原
pine_rsi函数定义的len参数默认是simple int类型,即使ta.rma支持序列类型的长度参数,函数的类型声明也会限制传入值的类型。
解决方法
方法1:修改函数参数类型为序列int
将pine_rsi函数的len参数类型从int改为series int,允许接受序列类型的长度值:
//@version=6 indicator("RSI Future test") // 修改参数类型为series int pine_rsi(float src, series int len) => change = ta.change(src) up = ta.rma(math.max(change, 0), len) down = ta.rma(-math.min(change, 0), len) down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down)) rsi_period = 14 rsi = pine_rsi(close, rsi_period) plot(rsi, color=color.blue) var rsiFuture = array.new_float(4) // 数组长度对应循环0-3的4个元素 // 循环可正常运行 for i=0 to 3 array.set(rsiFuture, i, pine_rsi(close, rsi_period-i))
方法2:提前预定义常量长度数组
如果不想修改函数参数类型,可以提前将需要的长度值定义为常量数组,避免循环中生成序列类型的长度:
//@version=6 indicator("RSI Future test") pine_rsi(float src, int len) => change = ta.change(src) up = ta.rma(math.max(change, 0), len) down = ta.rma(-math.min(change, 0), len) down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down)) rsi_period = 14 // 预定义所有需要的长度(常量数组) length_list = [rsi_period, rsi_period-1, rsi_period-2, rsi_period-3] rsi = pine_rsi(close, rsi_period) plot(rsi, color=color.blue) var rsiFuture = array.new_float(4) for i=0 to 3 array.set(rsiFuture, i, pine_rsi(close, length_list[i]))
额外注意
原代码中array.new_float(3)只初始化了3个元素的数组,但循环是i=0 to 3(共4个索引),会导致数组越界,建议修改数组长度为4。
内容的提问来源于stack exchange,提问作者Wangtae
相关产品推荐
相关产品推荐

