Box.new低时间周期不显示及箱体破位删除问题求助
解决方案:日线图绘制周线箱体并自动移除跌破低点的箱体
问题分析
你的代码在周线图正常显示但日线图失效,核心问题是时间周期索引不匹配:
- 用
request.security获取周线数据后,bar_index[2]取的是当前日线的历史bar索引,而非周线bar对应的日线起始位置,导致箱体绘制在错误时间点。 - 直接用
last_bar_index作为右边界,在日线图上会让箱体覆盖到最新bar,但周线的结束位置应该是该周最后一个日线bar的索引。 request.security内部无法调用绘图函数,因为绘图API只能在当前图表时间周期的上下文运行。
另外,要实现“移除低点已被跌破的箱体”,需要用数组存储所有绘制的箱体对象,实时检查当前价格是否跌破箱体低点,触发删除逻辑。
修正后的完整代码
//@version=5 indicator("SR (NEW)", "SR (NEW)", true, max_lines_count = 500) // 存储箱体对象的数组 var box[] boxArray = array.new_box() // 获取指定周期的OHLC数据(包含当前bar的起始/结束时间戳) f_get_weekly_data() => [open_w, high_w, low_w, close_w, time_start_w, time_end_w] = request.security(syminfo.tickerid, "W", [open, high, low, close, time, time_close], lookahead=barmerge.lookahead_on) [open_w, high_w, low_w, close_w, time_start_w, time_end_w] // 绘制箱体的函数 drawBox(time_start, time_end, top, bottom, diff, extend = extend.right) => // 找到时间戳对应的日线bar索引 left_bar = bar_index_from_time(time_start) right_bar = bar_index_from_time(time_end) drawnBox = box.new(left_bar, top, right_bar, bottom, extend = extend) if diff == "res" box.set_border_color(drawnBox, #f4433666) box.set_bgcolor(drawnBox, #f4433633) else box.set_border_color(drawnBox, #00968866) box.set_bgcolor(drawnBox, #00968833) // 将箱体加入数组 array.push(boxArray, drawnBox) drawnBox // 获取周线数据 [open_w, high_w, low_w, close_w, time_start_w, time_end_w] = f_get_weekly_data() // 周线蜡烛形态判断 isrc = (high_w - low_w) / 2 > math.abs(open_w - close_w) ibullCandle = (close_w > open_w and not isrc) ibearCandle = (open_w > close_w and not isrc) // 识别符合条件的支撑形态(基于周线bar的历史索引) ibull1ContiSupp = ibullCandle[1] and isrc[2] and ibullCandle[3] // 当形态触发时,绘制对应周线的箱体 if ibull1ContiSupp // 获取2根周线前的时间范围和高低点 [_, h_2, l_2, _, t_start_2, t_end_2] = request.security(syminfo.tickerid, "W", [open, high, low, close, time, time_close], lookahead=barmerge.lookahead_on, barmerge.gaps_on) drawBox(t_start_2, t_end_2, h_2, l_2, "sup") // 移除低点被跌破的箱体 if barstate.islast // 反向遍历避免索引混乱 for i = array.size(boxArray) - 1 to 0 by -1 currentBox = array.get(boxArray, i) boxLow = box.get_bottom(currentBox) // 检查当前价格是否跌破箱体低点 if low < boxLow box.delete(currentBox) array.remove(boxArray, i)
关键修改说明
- 时间戳匹配:
- 在
request.security中额外获取周线bar的time(起始时间)和time_close(结束时间),用bar_index_from_time()转换为日线图对应的bar索引,确保箱体绘制在正确的时间区间。
- 在
- 箱体存储与清理:
- 用
var box[] boxArray存储所有绘制的箱体对象,在最后一根bar时遍历数组,检查当前低点是否跌破箱体底部,若跌破则删除箱体并从数组移除。
- 用
- 形态判断修正:
- 调整周线形态的判断逻辑,确保
ibull1ContiSupp的历史索引基于周线bar,而非日线bar,避免形态触发时机错误。
- 调整周线形态的判断逻辑,确保
- 数据对齐优化:
- 补充
barmerge.gaps_on参数确保周线数据与日线bar正确对齐,同时在形态触发时单独请求历史周线数据,避免实时数据的提前加载问题。
- 补充
内容的提问来源于stack exchange,提问作者Kunthu Dhadda
相关产品推荐
相关产品推荐

