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

Pine Script v5如何获取非可视历史日期高低价并绘制水平线

解决方案:Pine Script v5 绘制指定日期高点水平线

核心思路

Pine Script 确实无法在逐Bar循环中调用request.security,但可以通过**barstate.islast单次循环+日线级别数据请求**的方式避开限制,同时精准捕获目标日期的高点。以下是具体实现步骤和完整代码:


步骤1:计算目标日期(过去5个月每月第一个周一)

先动态生成过去5个月每个月第一个周一的时间戳,处理跨年份的月份逻辑(比如1月往前推1个月为去年12月):

//@version=5
indicator("每月第一个周一高点水平线", overlay=true)

var int[] targetDates = array.new_int()
if barstate.islast
    currentYear = year
    currentMonth = month
    for i = 0 to 4
        // 计算往前推i个月的年份和月份
        targetMonth = currentMonth - i
        targetYear = currentYear
        if targetMonth < 1
            targetMonth += 12
            targetYear -= 1
        // 获取该月第一天的时间戳(交易所时区)
        monthStart = timestamp(targetYear, targetMonth, 1, 0, 0)
        // 计算该月第一个周一(ta.dayofweek返回0=周日,1=周一)
        firstDayWeek = ta.dayofweek(monthStart)
        daysToAdd = (1 - firstDayWeek + 7) % 7
        firstMonday = monthStart + daysToAdd * 86400000  // 1天=86400000毫秒
        array.push(targetDates, firstMonday)

步骤2:获取目标日期的高点

在barstate.islast中循环调用request.security,仅在最后一根Bar执行一次,避免触发请求限制:

var float[] targetHighs = array.new_float()
if barstate.islast
    for date in targetDates
        // 请求日线级别数据,匹配目标日期的开盘时间,获取当天高点
        dailyHigh = request.security(syminfo.tickerid, "D", ta.valuewhen(time == date, high, 0), gaps=barmerge.gaps_on)
        array.push(targetHighs, dailyHigh)

步骤3:绘制水平线

使用line.new绘制从目标日期Bar到当前最后一根Bar的水平线,无需显示目标日期之前的图表数据:

if barstate.islast
    for i = 0 to array.size(targetHighs) - 1
        highVal = array.get(targetHighs, i)
        dateVal = array.get(targetDates, i)
        // 找到目标日期对应的Bar索引
        targetBarIndex = ta.barssince(time == dateVal)
        if targetBarIndex != na
            // 绘制带日期标注的虚线
            line.new(bar_index - targetBarIndex, highVal, bar_index, highVal, 
                color=color.red, 
                width=2, 
                style=line.style_dashed,
                title=str.tostring(dateVal, "yyyy-MM-dd") + " 高点")
        // 可选:添加价格+日期标签
        label.new(bar_index, highVal, str.tostring(dateVal, "yyyy-MM-dd") + "\n" + str.tostring(highVal, "#.##"), 
            color=color.white, 
            textcolor=color.red, 
            style=label.style_label_left)

关键说明

  1. barstate.islast的作用:仅在图表最后一根Bar执行循环和请求,完全符合Pine Script的调用限制,不会触发数据源请求过多的问题。
  2. 日线数据请求的必要性:如果是小周期图表(如1小时),直接取当前周期的K线高点可能只是当天某一段的高点,调用日线级别数据能确保拿到目标日期的全天最高值。
  3. 时区一致性:所有时间戳计算基于交易所时区,和Pine Script默认时区保持一致,避免日期匹配错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 08:15:17