HTF Candle Support & Resistance «NoaTrader»
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © NoaTrader

//@version=5
indicator("Support & Resistance based on Higher Timeframe Candle «NoaTrader»","HTF CBSR",overlay = true,max_lines_count = 500)
var mh_array = array.new_line()
var ml_array = array.new_line()
var mc_array = array.new_line()
var timeframe_input = input.string("W","Source time frame",["12M","3M","M","W","D","240","60"],"M -> Month | W -> Week | D -> Day | 240 -> 4Hour | 60 -> 1Hour")
// var auto_timeframe = input.bool(false,"Set source time frame automatically based on chart timeframe ")
// var percent_difference_input = input.float(5,"Near candles show (%)")
var last_bar_offset_input = 10 //input.int(10,"Last candle SR offset")

// tf = auto_timeframe ? timeframe.isseconds ? "D" : timeframe.isminutes ? "W" : "M" : timeframe_input
[C_h,C_l,C_c] = request.security(syminfo.tickerid,timeframe_input,[high,low,close],barmerge.gaps_on)

is_candle = not na(C_h)
if is_candle
    mh_array.push(line.new(bar_index,C_h,bar_index,C_h,color = color.rgb(255, 82, 82, 50)))
    ml_array.push(line.new(bar_index,C_l,bar_index,C_l,color = color.rgb(76, 175, 79, 50)))
    mc_array.push(line.new(bar_index,C_c,bar_index,C_c,color = color.rgb(76, 96, 175, 50)))

hl_diff_percent_abs(X) => 
    h = (high - X) * 100 / X
    l = (low - X) * 100 / X
    math.abs(math.min(h,l))

last_bar_offset = bar_index == last_bar_index ? last_bar_offset_input : 0
percent_difference = ta.sma(math.abs(close-open)*100/open,100) * 5

for [i, h] in mh_array
    if hl_diff_percent_abs(line.get_y1(h)) < percent_difference
        line.set_x2(h,bar_index+last_bar_offset)

for [i, l] in ml_array
    if hl_diff_percent_abs(line.get_y1(l)) < percent_difference
        line.set_x2(l,bar_index+last_bar_offset)

for [i, c] in mc_array
    if hl_diff_percent_abs(line.get_y1(c)) < percent_difference
        line.set_x2(c,bar_index+last_bar_offset)