如何在Pinescript中判断价格是否处于绘制的矩形区域内?
在Pine Script中判断价格是否处于已绘制矩形区域内
刚接触Pine Script很正常,直接说两种常见场景的解决方法:
一、判断价格是否在脚本绘制的矩形内
如果你是用代码绘制的矩形,直接存储矩形的上下边界变量,用简单的比较逻辑就能判断价格是否在区间里。
示例代码:
//@version=5 indicator("价格在脚本矩形内判断", overlay=true) // 定义矩形的时间和价格边界 rect_left_bar = bar_index[50] // 矩形左边界对应50根K线前 rect_right_bar = bar_index // 矩形右边界对应当前K线 rect_top = ta.highest(high, 50)// 矩形顶部取过去50根K线的最高价 rect_bottom = ta.lowest(low, 50)// 矩形底部取过去50根K线的最低价 // 绘制矩形(仅在最后一根K线绘制) var rect my_rect = na if barstate.islast my_rect := rect.new(rect_left_bar, rect_top, rect_right_bar, rect_bottom, color=color.new(color.blue, 80)) // 核心判断逻辑:收盘价是否在矩形的上下价格区间内 price_in_rect = close >= rect_bottom and close <= rect_top // 标记符合条件的K线 plotshape(price_in_rect, title="在矩形内", location=location.belowbar, color=color.green, style=shape.labelup, text="在矩形内")
关键说明:
- 先把矩形的
rect_top(顶部价格)和rect_bottom(底部价格)用变量存起来 - 用
close >= rect_bottom and close <= rect_top判断价格是否落在区间内 - 如果需要同时判断时间是否在矩形的左右边界内,再加
time >= rect_left_time and time <= rect_right_time(把rect_left_bar转成时间戳即可)
二、判断价格是否在手动绘制的矩形内
目前Pine Script v5没有提供直接读取手动绘制图形(比如你在图表上用鼠标画的矩形)属性的API,所以没法直接获取手动矩形的边界。可以用以下两种替代方案:
方案1:手动输入矩形参数
把你手动画的矩形的左时间、右时间、顶部价格、底部价格,手动输入到脚本的参数里,再做判断:
//@version=5 indicator("价格在手动矩形内判断", overlay=true) // 手动输入你画的矩形的参数 rect_left_time = input.time(timestamp("2024-01-01T00:00:00"), "矩形左边界时间") rect_right_time = input.time(timestamp("2024-01-10T00:00:00"), "矩形右边界时间") rect_top_price = input.float(50.0, "矩形顶部价格") rect_bottom_price = input.float(40.0, "矩形底部价格") // 判断时间在矩形范围内,且价格在区间内 in_time_range = time >= rect_left_time and time <= rect_right_time price_in_rect = close >= rect_bottom_price and close <= rect_top_price is_in_rect = in_time_range and price_in_rect // 标记符合条件的K线 plotshape(is_in_rect, title="在手动矩形内", location=location.belowbar, color=color.orange, style=shape.labelup, text="在矩形内")
方案2:改用脚本绘制矩形
如果经常需要做这类判断,建议直接用代码绘制矩形,这样就能像第一种场景那样直接用变量获取边界,不用手动输入参数。
内容的提问来源于stack exchange,提问作者user2463517
相关产品推荐
相关产品推荐

