You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pine Script报错:标识符'day'未声明,求原因及解决方法

Pine Script 标识符'day'未声明错误的解决方法

错误原因

Pine Script v5 没有内置的day变量,你在timestamp()函数里直接用day会触发未声明错误。要获取当前K线的日份,必须使用dayofmonth函数(或ta.dayofmonth,两者功能等价)。

另外你的代码还有两处逻辑问题需要修正:

  • lastBarOfDay判断错误:ta.change(time("D"))会在新一天的第一根K线返回true,并非当天最后一根K线。
  • rangeTime用法错误:ta.highest()/ta.lowest()的第二个参数是K线数量,不是时间戳差值,直接传时间差会导致计算异常。

修正后的代码

//@version=5
indicator("Daily Box", overlay=true)

// 判断当前是否为当天最后一根K线
lastBarOfDay = ta.barstate.islast and ta.time_close == ta.time_close(time("D"))

// 定义目标时间范围:17:00-18:00
targetHourStart = 17
targetHourEnd = 18
// 获取当前K线的年、月、日
currentYear = year
currentMonth = month
currentDay = dayofmonth

// 生成时间戳
startTime = timestamp(currentYear, currentMonth, currentDay, targetHourStart, 0)
endTime = timestamp(currentYear, currentMonth, currentDay, targetHourEnd, 0)

// 判断当前K线是否在目标时间范围内
inTimeRange = time >= startTime and time < endTime

// 跟踪时间范围内的高低点(用var变量持续更新)
var float sessionHigh = na
var float sessionLow = na

if inTimeRange
    sessionHigh := ta.highest(high, 0)  // 0表示从条件触发开始计算所有K线的最高值
    sessionLow := ta.lowest(low, 0)
else
    // 不在时间范围时重置变量
    sessionHigh := na
    sessionLow := na

// 当天最后一根K线且有有效高低点时绘制箱体
if lastBarOfDay and not na(sessionHigh) and not na(sessionLow)
    box.new(bar_index - ta.barssince(inTimeRange), sessionHigh, bar_index, sessionLow, 
            border_color=color.black, border_width=2, bgcolor=color.new(color.green, 80))

关键修改说明

  1. 替换day为dayofmonth:用currentDay = dayofmonth获取当前日份,传入timestamp()函数解决未声明错误。
  2. 修正当天最后一根K线判断:用ta.barstate.islast结合ta.time_close(time("D"))(当天最后一根K线的收盘时间等于当日收盘时间)实现准确判断。
  3. 修复高低点计算逻辑:使用var变量在时间范围内持续更新高低点,避免用时间差作为ta.highest()参数,确保计算逻辑正确。
  4. 优化箱体绘制位置:通过bar_index - ta.barssince(inTimeRange)定位到时间范围的起始K线,让箱体完整覆盖目标时间段。

内容的提问来源于stack exchange,提问作者feaseyweiss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 07:17:31