PineScript 4计算Bar价差 判定收盘价处于K线百分位区间问题求助
代码问题排查
你原有代码的逻辑错误来自运算优先级和波幅计算逻辑遗漏:
Pine Script中除法运算优先级高于加法,你写的low[0] + high[0] / 2实际执行逻辑是「当前bar最低价 + 当前bar最高价的1/2」,并不是当前bar高低点区间的中位值。
正确的区间百分位计算逻辑为:区间百分位价格 = 最低价 + (最高价 - 最低价) * 目标百分比
正确实现方案
基础版:仅50%中位值判定
//@version=4 study("收盘价区间百分位判定", overlay=true) // 计算50%中位值 bar_mid = low + (high - low) * 0.5 // 买入条件:收盘价高于中位值 buy = close > bar_mid // 标记信号 plotshape(buy, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
进阶版:多百分位阈值判定(33%/50%/66%)
//@version=4 study("多阈值收盘价区间判定", overlay=true) // 自定义百分位阈值参数 pct1 = input(0.33, "第一阈值百分位") pct2 = input(0.5, "第二阈值百分位") pct3 = input(0.66, "第三阈值百分位") // 计算各阈值对应价格 threshold_33 = low + (high - low) * pct1 threshold_50 = low + (high - low) * pct2 threshold_66 = low + (high - low) * pct3 // 判定收盘价所在区间 price_level = 0 price_level := close > threshold_66 ? 3 : close > threshold_50 ? 2 : close > threshold_33 ? 1 : 0 // 可选:在K线上绘制阈值线 plot(threshold_33, color=color.yellow, title="33%阈值") plot(threshold_50, color=color.orange, title="50%阈值") plot(threshold_66, color=color.red, title="66%阈值")
如果不需要显示阈值线,删除最后三行plot代码即可。price_level返回值对应区间:0=低于33%分位,1=33%-50%分位,2=50%-66%分位,3=高于66%分位,可直接用于后续交易条件编写。
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

