如何在Pine Script中获取日内高低点对应的时间?
获取Pine Script当日高低点对应的时间
要获取当日高点、低点对应的时间并用于更低周期的条件判断,核心思路是在日线级别上下文里定位高低价出现的K线时间,再通过request.security将时间值传递到当前周期。以下是完整实现代码:
//@version=5 indicator('HiLo', overlay=true, shorttitle='HiLo') // 初始化交易时段和合约信息 isess = session.regular t = ticker.new(syminfo.prefix, syminfo.ticker, session=isess) // 定义日线级别下获取高低点时间的逻辑 getHighTime() => // 定位当日起始,获取当日最高价格对应的K线时间 ta.valuewhen(high == ta.highest(high, ta.barssince(ta.sessionisnew) + 1), time, 0) getLowTime() => // 定位当日起始,获取当日最低价格对应的K线时间 ta.valuewhen(low == ta.lowest(low, ta.barssince(ta.sessionisnew) + 1), time, 0) // 批量获取日线级别的高低价及对应时间 [todayHigh, todayHighTime] = request.security(t, 'D', [high[0], getHighTime()], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on) [todayLow, todayLowTime] = request.security(t, 'D', [low[0], getLowTime()], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on) // ------------------------------ // 示例:时间远近对比逻辑 // ------------------------------ // 计算当前时间与高低点时间的差值(单位:毫秒) timeDiffToHigh = time - todayHighTime timeDiffToLow = time - todayLowTime // 判断哪个点距离当前更近 isHighCloser = timeDiffToHigh < timeDiffToLow plotshape(isHighCloser, title="High Closer", location=location.belowbar, color=color.green, style=shape.labelup, text="High Near") plotshape(not isHighCloser, title="Low Closer", location=location.abovebar, color=color.red, style=shape.labeldown, text="Low Near")
关键说明
- 自定义时间获取函数:
ta.sessionisnew用于标记新交易日的起始K线,ta.barssince(ta.sessionisnew)+1得到当日已产生的K线数量。ta.valuewhen()函数匹配到当日最高/最低价出现的K线,并返回其时间戳。
- 多值请求优化:通过
request.security的多返回值特性,一次性获取高低价和对应时间,减少重复调用开销。 - 时间对比逻辑:通过计算当前时间与高低点时间的差值,直接判断哪个点在时间上更近,差值越小则距离当前越近。
内容的提问来源于stack exchange,提问作者matin
相关产品推荐
相关产品推荐

