request.security函数返回值异常求助:日线调用月线收盘价出错
解决日线框架下request.security获取月线收盘价重复值问题
问题描述
在日线时间框架下使用request.security函数获取月线收盘价时,约半数场景返回重复值,即便使用官方文档中的示例代码也无法解决。原代码如下:
newMonth = ta.change(time("M")) indexHighTF = barstate.isrealtime ? 1 : 0 indexCurrTF = barstate.isrealtime ? 0 : 1 nonRepaintingClose = request.security(syminfo.tickerid, "1M", close[indexHighTF])[indexCurrTF] if newMonth label.new(bar_index, high, str.tostring(nonRepaintingClose, format.mintick), color = color.aqua)
问题根源
- 原代码的索引逻辑(
indexHighTF/indexCurrTF)混淆了实时与历史K线的取值规则,导致历史K线场景下错误获取旧值 ta.change(time("M"))的月线切换判断不够精准,容易触发误判- 未指定
request.security的合并规则参数,默认规则可能导致取值延迟或重复
修正方案
简化取值逻辑,明确指定request.security的非重绘参数,同时用更精准的月线起始判断:
// 精准判断月线起始K线 isNewMonth = ta.ismonthstart // 获取月线收盘价,指定非重绘合并规则 monthlyClose = request.security(syminfo.tickerid, "1M", close, barmerge.gaps_on, barmerge.lookahead_off) // 在月线第一根K线标注上月收盘价(或当前月最新价) if isNewMonth // 若需上月收盘价,取monthlyClose[1];若需当前月实时收盘价,直接用monthlyClose label.new(bar_index, high, str.tostring(monthlyClose[1], format.mintick), color = color.aqua)
关键改动说明
- 用
ta.ismonthstart替代ta.change(time("M")),更精准识别每月第一根日线K线 - 给
request.security添加barmerge.gaps_on和barmerge.lookahead_off参数,强制非重绘模式,确保取值稳定 - 去掉冗余的索引判断,直接通过
[1]获取上月收盘价(若需当前月实时价则去掉索引)
内容的提问来源于stack exchange,提问作者AmphibianTrading
相关产品推荐
相关产品推荐

