如何在Pine Script中绘制绝对位置固定的图表方框
Pine Script 实现屏幕固定位置的方框
问题分析
你之前的代码无法实现需求的核心原因:
location.bottom是绘图位置枚举值,仅适用于plot()等函数,不能直接作为box.new的价格坐标参数;- 基于
bar_index计算的X坐标会随K线滚动而移动,无法固定在屏幕位置; - 语法错误:
location.absolute需作为box.new的参数传入,而非单独写在语句末尾。
解决方案代码
//@version=5 indicator("固定位置方框", overlay=true) // 定义方框的像素尺寸 bottomBoxWidth = 200 // 底部方框宽度(像素) bottomBoxHeight = 50 // 底部方框高度(像素) rightBoxWidth = 100 // 右侧方框宽度(像素) rightBoxHeight = 150 // 右侧方框高度(像素) // 声明持久化的方框变量(仅初始化一次) var box bottomBox = na var box rightBox = na // 仅在最后一根K线更新方框位置(确保图表刷新时同步更新) if barstate.islast // ---------------------- 底部居中方框 ---------------------- // 计算屏幕底部居中的像素坐标 bottomCenterX = chart.width / 2 bottomY = chart.height - bottomBoxHeight // 方框底部贴屏幕底部 // 像素坐标转换为Pine Script可用的bar索引和价格值 bottomLeftX = pixel_to_bar_index(bottomCenterX - bottomBoxWidth/2) bottomRightX = pixel_to_bar_index(bottomCenterX + bottomBoxWidth/2) bottomTopPrice = pixel_to_price(bottomY - bottomBoxHeight) bottomBottomPrice = pixel_to_price(bottomY) // 创建或更新底部方框 if na(bottomBox) bottomBox := box.new(left=bottomLeftX, top=bottomTopPrice, right=bottomRightX, bottom=bottomBottomPrice, bgcolor=color.new(color.blue, 80), border_width=2, text="底部居中", textcolor=color.white) else box.set_left(bottomBox, bottomLeftX) box.set_right(bottomBox, bottomRightX) box.set_top(bottomBox, bottomTopPrice) box.set_bottom(bottomBox, bottomBottomPrice) // ---------------------- 右侧垂直居中方框 ---------------------- // 计算屏幕右侧垂直居中的像素坐标 rightX = chart.width - rightBoxWidth // 方框左侧贴屏幕右侧内边缘 rightCenterY = chart.height / 2 // 像素坐标转换为Pine Script可用的bar索引和价格值 rightLeftX = pixel_to_bar_index(rightX) rightRightX = pixel_to_bar_index(chart.width) rightTopPrice = pixel_to_price(rightCenterY - rightBoxHeight/2) rightBottomPrice = pixel_to_price(rightCenterY + rightBoxHeight/2) // 创建或更新右侧方框 if na(rightBox) rightBox := box.new(left=rightLeftX, top=rightTopPrice, right=rightRightX, bottom=rightBottomPrice, bgcolor=color.new(color.red, 80), border_width=2, text="右侧居中", textcolor=color.white) else box.set_left(rightBox, rightLeftX) box.set_right(rightBox, rightRightX) box.set_top(rightBox, rightTopPrice) box.set_bottom(rightBox, rightBottomPrice)
关键实现逻辑
- 持久化方框:用
var声明方框变量,避免每次K线刷新都重建方框,仅在首次运行时创建,后续只更新位置。 - 屏幕像素定位:利用
chart.width/chart.height获取图表容器的像素尺寸,计算屏幕固定位置的像素坐标。 - 坐标转换:通过
pixel_to_bar_index()和pixel_to_price()将屏幕像素坐标转换为Pine Script识别的bar索引和价格值,实现方框与屏幕位置绑定。 - 实时更新:在
barstate.islast条件下更新位置,确保图表滚动、缩放时,方框始终保持在设定的屏幕固定点。
内容的提问来源于stack exchange,提问作者Wolfyx
相关产品推荐
相关产品推荐

