WRBHG with visual gap block
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MalibuKenny

//@version=5
indicator("v.2 WRBHG with visual gap box", overlay = true, max_bars_back=5000, max_lines_count=500, max_labels_count=500, max_boxes_count = 500)

group0 = 'Period under study'
startDate = input.time(title='Start Date', defval=timestamp("2000-01-19 09:00:00 GMT+8"), group=group0)
endDate = input.time(title='End Date', defval=timestamp('2099-09-01 09:00:00 GMT+8'), tooltip='Date & time to stop analysis', group=group0)
use_custom_period = input.bool(title='use_custom_period', defval=true, group=group0, inline='HLline')

var timeSession = '0900-0800'

// This function returns true if the current bar falls within the given time session (:1234567 is to include all weekdays)
inSession(sess) =>  //custom function input sess
    na(time(timeframe.period, sess + ':1234567', 'GMT+8')) == false and time >= startDate and time <= endDate

// Check if a new session has begun (not in ==> in)
var withinSession = false
if not inSession(timeSession)[1] and inSession(timeSession)
    withinSession := true

if inSession(timeSession)[1] and not inSession(timeSession)
    withinSession := false

var WRBHG_upper = 0.0
var WRBHG_upper_index = 0
var WRBHG_lower = 0.0
var WRBHG_lower_index = 0
var fillColor = color.black
bool rising = na
x_extend_count = input.int(title="x extend count", defval = 30)
transp  = input.int(title="Transparency", defval = 70)

// WRBHQ begin
body = math.abs(open-close)
wrb_value = body>body[1] and body>body[2] and body>body[3] ? math.avg(open,close) : na
hg_value = (wrb_value[1] and (low>high[2] or high<low[2]))? wrb_value[1] : na
wrb = body>body[1] and body>body[2] and body>body[3] 
hg = (wrb[1] and (low>high[2] or high<low[2]))

if withinSession
    if hg
        if close[1] > open[1] and low > high [2]// rising HG
            WRBHG_upper := low
            WRBHG_lower := high[2]
            rising := true
            fillColor := color.new(color.green, transp)
        else if close[1] < open[1] and low > high [2]// rising HG
            WRBHG_upper := low
            WRBHG_lower := high[2]
            rising := true
            fillColor := color.new(color.green, transp)
        else // dropping HG
            WRBHG_upper := low[2]
            WRBHG_lower := high
            rising := false
            fillColor := color.new(color.red, transp)

        box.new(bar_index-1, WRBHG_upper, bar_index + x_extend_count, WRBHG_lower, border_color = na, bgcolor = fillColor)  


s3=ta.ema(ohlc4,3)
plot(s3,color=color.new(color.black,0))
