Pine Script函数内布尔变量控制request.security失效问题求助
问题排查与解决方案
核心问题分析
你的代码存在两个关键问题:
时间框架字符串错误:
你使用timeframe.in_seconds('65')获取65分钟的秒数,但Pine Script中'65'会被解析为65秒而非65分钟。正确的65分钟时间框架字符串应为'65M',否则My65TFInSec的值会是65,导致时间框架判断逻辑完全错误。request.security执行逻辑误解:
你将图表上下文计算的My65_AvailFlag作为参数传入request.security的表达式,但request.security会在被请求的时间框架(65分钟)的bar上下文中执行表达式。即使图表上下文的My65_AvailFlag为false,request.security仍会执行请求并返回数据——因为函数中的paramFlag是图表bar对应的值,但被请求的TF的bar可能对应图表的多个bar,其中某些bar的My65_AvailFlag可能被误判为true,或者request.security会保留之前的有效值而非NA。
修正后的代码
//@version=5 indicator(title="ZZ_MyMiscInfo_V01", shorttitle="ZZ_MyMiscInfo_V01", overlay=true) //Functions - BEGIN MyFunc_GetSecurity() => [time, open, high, low, close, high[1], low[1]] //Functions - END //Information about last bar candle of 'monitored' TimeFrames (TFs) is only available for higher TFs than the chart one var MyCurrTFInSec = timeframe.in_seconds(timeframe.period) var My65TFInSec = timeframe.in_seconds('65M') // 修正为65分钟的时间框架字符串 My65_AvailFlag = barstate.islast and (My65TFInSec >= MyCurrTFInSec) //Information about last (and before last) candle is requested (only for higher TFs than the chart one) // 仅在条件满足时调用request.security,否则直接赋值NA if My65_AvailFlag [My65_OTime, My65_O, My65_H, My65_L, My65_C, My65_H1, My65_L1] = request.security(syminfo.tickerid, '65M', MyFunc_GetSecurity()) else My65_OTime = int(na) My65_O = float(na) My65_H = float(na) My65_L = float(na) My65_C = float(na) My65_H1 = float(na) My65_L1 = float(na) //Debug in Data-Window - BEGIN plotchar(My65_AvailFlag, "My65_AvailFlag", "", location=location.top) //Debug in Data-Window - END var MyTable = table(na) //Table with collected information if barstate.islast //Table initialization if not na(MyTable) table.delete(MyTable) MyTable := table(na) MyTable := table.new('bottom_right', columns=1, rows=1, border_width=1) table.cell(MyTable, 0, 0, ("65-min ( " + str.tostring(My65TFInSec) + " - " + str.tostring(My65_AvailFlag) + " ) " + (na(My65_OTime) ? "_NA_" : str.format_time(My65_OTime, "YYYY-MM-dd HH:mm", syminfo.timezone))), text_color=color.white, bgcolor=color.blue, text_size=size.small, width=0, height=0)
关键修正点说明
- 时间框架修正:将
'65'改为'65M',确保My65TFInSec正确计算为65分钟对应的秒数(3900)。 - 条件判断移至外部:仅当
My65_AvailFlag为true时,才调用request.security获取数据;否则直接将所有变量赋值为NA,彻底避免不必要的数据请求和错误的有效值返回。 - 简化函数逻辑:既然仅在条件满足时调用函数,函数无需再接收flag参数,直接返回所需数据即可,代码更简洁。
内容的提问来源于stack exchange,提问作者lp6970
相关产品推荐
相关产品推荐

