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

如何获取最后一根日线K线的日期?当前仅能获取当前日期

获取Bareplay中最后一根日线K线的日期方法

在Bareplay(Pine Script)里,timenow()返回固定的系统当前时间,不会随K线变化。要获取最后一根日线K线的日期,你需要利用K线自身的时间戳和barstate.islast条件定位目标K线:

核心操作方式

  • 提取年份:用year(time)配合barstate.islast,仅在最后一根K线时获取对应时间
  • 提取月份:month(time)返回数字(1-12),若需要英文月份名称,用str.tostring(month(time), "MMMM")转换
  • 提取日期:dayofmonth(time)

完整示例代码

//@version=5
indicator("最后一根日线K线日期", overlay=true)

// 仅针对最后一根K线计算日期
if barstate.islast
    last_year = year(time)
    last_month_num = month(time)
    last_day = dayofmonth(time)
    // 转换为英文月份名称
    last_month_name = str.tostring(last_month_num, "MMMM")
    
    // 在K线高点位置显示日期信息
    label.new(bar_index, high, 
        str.format("Year: %d\nMonth: %s\nDay: %d", last_year, last_month_name, last_day),
        color=color.blue, textcolor=color.white, style=label.style_label_down)

关键说明

  • barstate.islast是核心判断条件,确保只对最后一根日线K线执行日期提取逻辑
  • time变量存储当前K线的开盘时间,对于日线周期来说,这个时间就对应K线的日期
  • 示例代码会在最后一根K线的上方标注出年、英文月份、日,和你给出的示例数据格式完全匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 07:20:27