TradingView Pine Script自定义指标报错:Conversion failed错误排查
TradingView Pine Script 指标错误分析与修复
直接报错原因
你代码里的time.dayofweek是Python式的属性访问写法,但Pine Script不支持这种语法,必须用内置函数dayofweek(time)来提取星期几。这就是第8行报错的核心原因。
规则逻辑与语法的双重修正
规则1修正
- 当日首根K线判断:用星期几判断会有跨周误判,改用日期切换更准确:
dayofmonth(time[1]) != dayofmonth(time) - 前一日波动区间获取:原代码对比前一根K线的高低是错误的,需要提取前一日所有K线的最高/最低价,用
ta.valuewhen配合ta.highest/ta.lowest实现
规则2修正
原代码写死了固定数量的K线,不符合“两根及以上阳线”的要求,用ta.barssince函数可以灵活判断连续阳线数量≥2,再接阴线和阳线的形态。
完整可运行代码
//@version=4 study(title="Custom Rules Indicator", shorttitle="CRI", overlay=true) // 规则1:当日首根K线收盘价高于前一日波动区间 is_first_bar_of_day = dayofmonth(time[1]) != dayofmonth(time) // 获取前一日的最高、最低价 prev_day_high = ta.valuewhen(is_first_bar_of_day[1], ta.highest(high, barssince(is_first_bar_of_day)), 0) prev_day_low = ta.valuewhen(is_first_bar_of_day[1], ta.lowest(low, barssince(is_first_bar_of_day)), 0) rule1_condition = is_first_bar_of_day and close > prev_day_high and close > prev_day_low // 规则2:两根及以上阳线 + 一根阴线 + 一根阳线 is_bullish = close > open is_bearish = close < open // 当前是阳线,前一根是阴线,最近一次非阳线在2根及以上之前(说明连续≥2根阳线) rule2_condition = is_bullish and is_bearish[1] and ta.barssince(not is_bullish) >= 2 and ta.barssince(is_bearish) == 1 // 绘制信号 plotshape(series=rule1_condition, title="1st Rule Completed", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small, text="1st Rule") plotshape(series=rule2_condition, title="2nd Rule Completed", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small, text="2nd Rule")
关键说明
- 用
dayofmonth判断当日首K,避免周末跨周导致的错误识别 - 规则2的逻辑支持任意连续2根及以上的阳线,而非固定的2根,符合需求描述
- 新增
text参数让信号标注更直观
内容的提问来源于stack exchange,提问作者Parvinder Singh
相关产品推荐
相关产品推荐

