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

Pine Script V5跨时间框架获取指定日期开盘价并存储的问题求助

Pine Script V5跨时间框架获取指定日期开盘价并存储的问题求助

我现在遇到个问题,想要获取2024年1月2日的开盘价并存到数组里,在日线图上运行这段代码是正常的,但切换到1分钟图时,当天的历史K线数据就找不到了,代码直接失效。有没有大佬能帮忙看看?

我的代码如下:

//@version=5
indicator("Open Price Storage", overlay = true, dynamic_requests=true)

// Define the target date for 2024 January 2nd
targetYear = 2024
targetMonth = 1
targetDay = 2

// Get the open price on the target date from the daily timeframe
dailyOpenPrice = request.security(syminfo.tickerid, "D", (year == targetYear and month == targetMonth and dayofmonth == targetDay) ? open : na)

// Initialize an array to store the open price
var float[] openPriceArray = array.new_float(1, na)

// Store the open price in the array once
if na(array.get(openPriceArray, 0)) and not na(dailyOpenPrice)
    array.set(openPriceArray, 0, dailyOpenPrice)

// Plot the s...

别急,问题出在你用request.security请求日线数据时,在1分钟图上的逻辑有点小瑕疵:当1分钟图的当前K线不在目标日期范围内时,request.security返回的na会导致你拿不到正确的开盘价。

给你调整了代码,核心思路是先在日线级别锁定目标日期的开盘价,再把这个值传递到小周期图里,不管当前是1分钟还是其他周期,都能稳定拿到数据:

//@version=5
indicator("Open Price Storage", overlay = true, dynamic_requests=true)

// 定义目标日期
targetYear = 2024
targetMonth = 1
targetDay = 2

// 在日线级别筛选目标日期开盘价,用var变量确保只计算一次
var float targetDailyOpen = na
if barstate.islast
    // 仅在最后一根K线请求数据,避免重复计算浪费资源
    targetDailyOpen := request.security(syminfo.tickerid, "D", 
         (year == targetYear and month == targetMonth and dayofmonth == targetDay) ? open : na)

// 初始化存储开盘价的数组
var float[] openPriceArray = array.new_float(1, na)

// 当数组为空且成功获取到目标开盘价时,存入数组
if na(array.get(openPriceArray, 0)) and not na(targetDailyOpen)
    array.set(openPriceArray, 0, targetDailyOpen)

// 可选:添加标签验证结果
if barstate.islast and not na(targetDailyOpen)
    label.new(bar_index, high, "目标开盘价: " + str.tostring(targetDailyOpen), color=color.green, textcolor=color.white)

关键改动说明:

  • 用var声明targetDailyOpen,保证这个变量只会被赋值一次,不会随K线刷新反复重置
  • 将request.security放在barstate.islast条件下,只在最后一根K线请求日线数据,既减少资源消耗,又能确保拿到目标日期的开盘价(只要日线数据里存在该日期的K线,小周期就能获取到)
  • 这样切换到1分钟图时,就不会因为当前K线不在目标日期而返回na,代码就能正常把开盘价存入数组了

备注:内容来源于stack exchange,提问作者daft.punk.trader4life

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.16 07:40:28