无法在Pine Script中添加时段条件以显示分形图形求助
解决Pine Script中仅在伦敦/纽约时段显示分形的问题
问题说明
需要在Pine Script中实现仅在伦敦或纽约交易时段显示分形图形,尝试添加时段判断代码后,直接用if语句包裹plotshape的方式无法正常工作。
错误原因
你之前用if语句包裹plotshape的写法不符合Pine Script的逻辑:plotshape是逐K线执行的绘图函数,需要通过布尔条件参数来控制是否绘制,而非用流程控制语句包裹。
正确修改方法
- 先将时段判断代码插入到原指标的开头(
indicator声明之后) - 在
plotshape的第一个参数中,将分形条件与时段条件做**逻辑与(and)**运算,只有同时满足分形条件和时段条件时,才会绘制图形。
修改后的完整代码
//@version=5 indicator("Test", overlay=true) // 插入时段判断代码 london_sess = input.session("0700-1600", "London") newyork_sess = input.session("1300-2200", "New York") is_in_london = time(timeframe.period, london_sess) is_in_newyork = time(timeframe.period, newyork_sess) is_target_session = is_in_london or is_in_newyork // 合并为一个条件变量,代码更简洁 bool confirmed_fractal = input.bool(defval = true, title = 'Plot only confirmed Fractals', tooltip = 'Switch "OFF" during backtest') bool IB = input.bool(defval = true, title = 'Plot Inside Bar') isBWFractal(mode) => ret = mode == 1 ? high[4] < high[2] and high[3] <= high[2] and high[2] >= high[1] and high[2] > high[0] : mode == -1 ? low[4] > low[2] and low[3] >= low[2] and low[2] <= low[1] and low[2] < low[0] : false ret filteredtopf = isBWFractal(1) filteredbotf = isBWFractal(-1) if confirmed_fractal == true filteredtopf := barstate.isconfirmed and isBWFractal(1) filteredbotf := barstate.isconfirmed and isBWFractal(-1) // 修改plotshape的条件,加入时段判断 plotshape(filteredtopf and is_target_session, title='Top Fractals', style=shape.triangledown, location=location.abovebar, color=color.new(color.white, 0), offset=-2, display = display.all - display.price_scale - display.status_line) plotshape(filteredbotf and is_target_session, title='Bottom Fractals', style=shape.triangleup, location=location.belowbar, color=color.new(color.white, 0), offset=-2, display = display.all - display.price_scale - display.status_line)
关键修改点
- 新增
is_target_session变量,合并伦敦和纽约时段的判断,让代码更简洁 - 在
plotshape的第一个参数中,将原分形条件filteredtopf/filteredbotf与is_target_session做逻辑与运算,确保只有在目标时段且满足分形条件时才绘制图形
内容的提问来源于stack exchange,提问作者Marcel Fernandes
相关产品推荐
相关产品推荐

