如何基于4H TF数据在30m TF时间框架上绘制对应水平线
TradingView 4H周期数据在30m图表绘制水平线解决方案
问题根源
你当前的写法失效的核心原因是:不同时间框架的bar_index是独立计数的,4H周期下的bar_index数值仅在4H图表中能对应正确的K线位置,放到30m图表中没有对应关系,自然无法匹配到正确的K线区间。
跨时间框架定位x轴位置应该使用通用的时间戳,不管当前查看的是什么周期,同一时间点的时间戳数值是完全一致的。
正确实现方案
你需要从4H周期取的是目标K线的开始/结束时间戳、以及水平线对应的价格,再用时间戳作为x轴参数创建线条,就能让4H的水平线完整覆盖对应时段的所有30m K线。
示例代码
//@version=5 indicator("4H水平线同步到30m", overlay=true) // 定义4H周期,批量取4H K线的开始时间、结束时间、最低价(可替换为你需要的candle2Low等自定义价格) [start_4h, end_4h, price_4h] = request.security(syminfo.tickerid, "240", [time, time_close, low]) // 仅在4H周期切换时新建线条,避免重复生成冗余对象 if ta.change(start_4h) and barstate.islastconfirmedhistory // x轴用时间戳定位,y轴价格统一,即可画出横跨整段4H周期的水平线 line.new( x1 = start_4h, y1 = price_4h, x2 = end_4h, y2 = price_4h, width = 1, color = color.new(color.green, 0) )
多根历史4H线扩展写法
如果需要绘制最近3根4H K线对应的水平线,调整请求参数即可:
// 同时取最近3根4H K线的价格 [start_4h, end_4h, price_curr, price_prev1, price_prev2] = request.security(syminfo.tickerid, "240", [time, time_close, low, low[1], low[2]]) if ta.change(start_4h) and barstate.islastconfirmedhistory // 当前4H K线的水平线 line.new(start_4h, price_curr, end_4h, price_curr, width=1, color=color.green) // 上一根4H K线的水平线 line.new(start_4h - 240 * 60 * 1000, price_prev1, start_4h, price_prev1, width=1, color=color.yellow) // 上两根4H K线的水平线 line.new(start_4h - 480 * 60 * 1000, price_prev2, start_4h - 240 * 60 * 1000, price_prev2, width=1, color=color.red)
注意事项
- 如果你需要保留的历史线条数量有限,可以把创建的
line对象存入var array队列,超过指定数量时删除最早的线条,避免图表线条过多卡顿 - 如果你使用的是自定义计算的价格(而非内置的low/high),只要把
request.security的返回参数替换为你自定义的变量即可,时间戳定位的逻辑不变
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

