even_better_sinewave_mod
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © palitoj_endthen

//@version=5
indicator(title = 'even_better_sinewave_modified', shorttitle = 'even_better_sinewave', overlay = false, timeframe = '', timeframe_gaps = true)


// input
hp_period = input.int(defval = 89, title = 'High-pass Period', group = 'Value', tooltip = 'Determines the length of High-pass period.')
src = input.source(defval = ohlc4, title = 'Source', group = 'Options', tooltip = 'Determines the input data, default to ohlc4, user could change to other input e.g. close.')
apply_bar_color = input.bool(defval = false, title = 'Bar color', group = 'Options', tooltip = 'Determines whether to apply bar color, based on even better sinewave indicator signal')


// variable
alpha1 = 0.0
hp = 0.0
filt = 0.0
wave = 0.0
pwr = 0.0


// even better sinewave
// high-pass filter
pi = 2*math.asin(1)
alpha1 := (math.cos(.707*2*pi/hp_period) + math.sin(.707*2*pi/hp_period)-1)/math.cos(.707*2*pi/hp_period)
hp := (1-alpha1/2)*(1-alpha1/2)*(src-2*src[1]+src[2])+2*(1-alpha1)*nz(hp[1])-(1-alpha1)*(1-alpha1)*nz(hp[2])

// smoothed (modified)
filt := (7*hp+6*hp[1]+5*hp[2]+4*hp[3]+3*hp[4]+2*hp[5]+hp[6])/28

// 3 bar average of wave amplitude and power
wave := (filt+filt[1]+filt[2])/3
pwr := (filt*filt+filt[1]*filt[1]+filt[2]*filt[2])/3

// normalize
wave := wave/math.sqrt(pwr)


// Visualize
// color condition
con = 0
if wave < -.8
    con := con
else if wave > wave[1]
    con := 1
else if wave > .8
    con := 1
else if wave < wave[1]
    con := con

color_ = con == 1 ? color.green : color.red

// sine wave
p1 = plot(wave, color = color_, linewidth = 3)
plot(wave*.8, color = color.new(color.aqua, 80))

// threshold
// h1 = hline(.85, linewidth = 1, color = color.new(color.yellow, 50), linestyle = hline.style_solid)
// h2 = hline(.75, linewidth = 1, color = color.new(color.yellow, 50), linestyle = hline.style_solid)
// fill(h1, h2, color = color.new(color.yellow, 80))

// h3 = hline(-.75, linewidth = 1, color = color.new(color.yellow, 50), linestyle = hline.style_solid)
// h4 = hline(-.85, linewidth = 1, color = color.new(color.yellow, 50), linestyle = hline.style_solid)
// fill(h3, h4, color = color.new(color.yellow, 80))

// bar color
barcolor(apply_bar_color ? color_ : na)


// create alert
alertcondition(con == 1 , title = 'Entry', message = 'Buy/Long entry point detected')
alertcondition(con == 0, title = 'Close', message = 'Sell/Short entry point detected')
