Pine Script 5:如何基于会话输入数据绘制价格水平线?
解决方案:利用TradingView内置会话输入绘制时段水平线
不用手动解析会话字符串或生成Unix时间,直接用Pine Script的内置会话输入和时间判断函数就能实现需求,代码简洁且可靠:
//@version=5 indicator("会话时段价格水平线", overlay=true) // 1. 直接定义会话输入,自动适配图表时区(可指定时区参数) target_session = input.session("1800-2100", title="目标时段", tooltip="格式为HHMM-HHMM") // 2. 判断当前K线是否处于目标会话内 in_session = not na(time(timeframe.period, target_session)) // 3. 捕捉会话开始时刻的开盘价 session_open_price = valuewhen(in_session and not in_session[1], open, 0) // 捕捉会话结束时刻的收盘价 session_close_price = valuewhen(not in_session and in_session[1], close, 0) // 4. 在会话时段内绘制水平线(非会话时段隐藏) plot(in_session ? session_open_price : na, title="会话开盘线", color=color.new(color.blue, 0), linewidth=2, style=plot.style_linebr) plot(in_session ? session_close_price : na, title="会话收盘线", color=color.new(color.red, 0), linewidth=2, style=plot.style_linebr)
关键逻辑说明
- 会话输入处理:
input.session()是TradingView专门用于时段输入的内置函数,自动处理时区和格式验证,无需手动解析字符串。 - 会话判断:
time(timeframe.period, target_session)会返回当前K线在目标会话内的时间戳,非会话时段返回na,通过not na即可快速判断是否处于目标时段。 - 价格提取:
valuewhen()函数用于捕捉会话状态切换的时刻(开始/结束),精准提取对应时刻的开盘价/收盘价。 - 线条绘制:通过
plot的条件判断in_session ? 价格 : na,实现仅在目标会话时段显示水平线,非时段自动隐藏,避免线条冗余。
如果需要让线条在整个图表显示(而非仅会话时段),可以将plot的条件去掉,直接绘制session_open_price或session_close_price,这样会在全图表显示当日会话的开盘/收盘价格线。
内容的提问来源于stack exchange,提问作者Ezra Peace
相关产品推荐
相关产品推荐

