Ectopic Bar by Moti Rakam
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © MotiRakam

//@version=5
indicator("Ectopic Bar by Moti Rakam", "Ectopic Bar", overlay=true)

var bool highClose = false
var bool lowClose = false
var bool bullishPinBar = false
var bool bearishPinBar = false
var bool ectopicPinBar = false


useCustomTimeframeInput = input.bool(false, "Use custom timeframe")
lowerTimeframeInput = input.timeframe("1", "Volume Timeframe")
closeRange = input.float(0.35, title="Close Range", minval=0.05, maxval=0.75, step=0.05)

//Find Ectopic candle
upAndDownVolume() =>
    posVol = 0.0
    negVol = 0.0
    
    switch
        close >  open     => posVol += volume
        close <  open     => negVol -= volume
        close >= close[1] => posVol += volume
        close <  close[1] => negVol -= volume

    [posVol, negVol]

lowerTimeframe = switch
    useCustomTimeframeInput => lowerTimeframeInput
    timeframe.isintraday    => "1"
    timeframe.isdaily       => "5"
    => "60"

[upVolumeArray, downVolumeArray] = request.security_lower_tf(syminfo.tickerid, lowerTimeframe, upAndDownVolume())

upVolume = array.sum(upVolumeArray)
downVolume = array.sum(downVolumeArray)
delta = upVolume + downVolume

//Close Above or Below Mid-Point
barRange = math.abs(high - low)
if close > (high - (barRange / 2))
    highClose := true
else
    lowClose := true

//Check if Close is closer to High
if highClose and (close >= high - (barRange * closeRange)) and (open >= high - (barRange * closeRange))
    bullishPinBar := true
else
    bullishPinBar := false

//Check if Close is closer to Low
if lowClose and (close <= low + (barRange * closeRange)) and (open <= low + (barRange * closeRange))
    bearishPinBar := true
else
    bearishPinBar := false

//Ectopic Pin Bar
ectopicPinBar := (bullishPinBar and (math.abs(downVolume) > upVolume)) or (bearishPinBar and (upVolume > math.abs(downVolume)))
ectopicPinBarColor = ectopicPinBar ? color.yellow : na
barcolor(ectopicPinBarColor, title="Ectopic Pin Bar")

//reset the variables
highClose := false
lowClose := false
bullishPinBar := false
bearishPinBar := false
ectopicPinBar := false