Pine Script中request.security返回非预期值问题求助
问题
我此前频繁使用request.security功能,原本运行正常的脚本今日失效。精简脚本后发现,request.security未返回指定时间框架的预期值,反而受图表时间框架影响。
我编写测试脚本用于获取前几个月的月度高点,按逻辑该脚本应在任意图表时间框架下正常运行,但实际仅当图表设为1M时间框架时,才能得到过去3个月的正确月度高点。以AAPL为例,我预期得到$249.10、$260.10和$237.81,但其他时间框架下返回值均不正确,恳请各位提供反馈。
测试脚本如下:
//@version=6 indicator("Test Request Sec", overlay = true) // Request monthly highs testHigh = request.security(symbol = syminfo.tickerid, timeframe = "1M", expression = high) // Create a small table for debugging output testTable = table.new(position=position.top_right, columns=1, rows=3) // Write the last three values of the monthly highs into the table. This is only giving the correct values if the Chart is set to 1M as well. table.cell(table_id = testTable, column = 0, row = 0, text=str.tostring(testHigh[1]), text_color = color.white) table.cell(table_id = testTable, column = 0, row = 1, text=str.tostring(testHigh[2]), text_color = color.white) table.cell(table_id = testTable, column = 0, row = 2, text=str.tostring(testHigh[3]), text_color = color.white)
解决方案
问题核心是:request.security返回的是目标时间框架当前bar的实时值,而非历史完整周期的聚合值。当图表时间框架小于1M时,testHigh会在每个小周期bar上重复返回当前月度的高点,此时调用testHigh[1]、testHigh[2]取到的是小周期的重复值,而非不同月份的高点。
要准确获取历史月度高点,需在request.security内部捕捉月度切换节点,直接提取对应周期的高点数据。修改后的脚本如下:
//@version=6 indicator("Test Request Sec Fixed", overlay = true) // 捕捉月度bar切换的节点 monthChange = ta.change(time("1M")) // 直接在1M框架内获取过去3个完整月份的高点 prev1MonthHigh = request.security(syminfo.tickerid, "1M", ta.valuewhen(monthChange, high, 1)) prev2MonthHigh = request.security(syminfo.tickerid, "1M", ta.valuewhen(monthChange, high, 2)) prev3MonthHigh = request.security(syminfo.tickerid, "1M", ta.valuewhen(monthChange, high, 3)) // 生成调试表格 testTable = table.new(position=position.top_right, columns=1, rows=3) table.cell(testTable, 0, 0, str.tostring(prev1MonthHigh), color.white) table.cell(testTable, 0, 1, str.tostring(prev2MonthHigh), color.white) table.cell(testTable, 0, 2, str.tostring(prev3MonthHigh), color.white)
关键说明
ta.change(time("1M")):精准识别月度bar的切换点,确保只在周期切换时记录对应月份的高点ta.valuewhen(monthChange, high, N):在1M时间框架内直接提取第N个历史切换点对应的月度高点,完全不受图表小周期bar的干扰- 该方案在任意图表时间框架下,都能稳定返回过去完整月份的高点数据
内容的提问来源于stack exchange,提问作者KsSo
相关产品推荐
相关产品推荐

