IKH Cloud V1.0 (nextSignals)
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © justatradebro

//@version=5
indicator("IKH Cloud V1.0 (nextSignals)", shorttitle='KumoDoc', overlay=true)

ima_color = input.color(color.orange, title = 'IMA Color')
trail_color_up = input.color(color.rgb(76, 175, 79, 70), title = 'Trail Up')
trail_color_down = input.color(color.rgb(255, 82, 82, 70), title = 'Trail Down')
candle_color_up = input.color(color.green, title = 'Candle Up')
candle_color_down = input.color(color.red, title = 'Candle Down')

// IMA Calculation
length = 5  // Length parameter for IMA calculation
ph = 0.0
pl = 0.0
alpha = 2.5 / (length + 1)
ima = 0.0
ima := alpha * ohlc4[1] + (1 - alpha) * nz(ima[1])

p1 = plot(ima, color=ima_color, linewidth=2, title="Instantaneous Moving Average")

lowest_low = ta.lowest(low[1], 5)
highest_high = ta.highest(high[1], 5)
avg_low = ta.sma(low[1], 5)
avg_high = ta.sma(high[1], 5)

// Trailing stop
a = 0.0
b = 0.0
z = 0.0
c = 0.0
l = 0.0
s = 0.0
trail = 0.0

if bar_index > 1 and nz(a[1]) == 1
    b := math.max(lowest_low, nz(b[1]))
    z := avg_high < nz(b[1]) and close < low[1] ? 1 : nz(z[1])
    a := avg_high < nz(b[1]) and close < low[1] ? 0 : nz(a[1])
    c := avg_high < nz(b[1]) and close < low[1] ? highest_high : nz(c[1])
else if nz(a[1]) == 0
    c := math.min(highest_high, nz(c[1]))
    z := avg_low > nz(c[1]) and close > high[1] ? 0 : nz(z[1])
    a := avg_low > nz(c[1]) and close > high[1] ? 1 : nz(a[1])
    b := avg_low > nz(c[1]) and close > high[1] ? lowest_low : nz(b[1])
else
    b := nz(b[1])
    z := nz(z[1])
    a := nz(a[1])
    c := nz(c[1])

if z == 0
    l := nz(z[1]) != 0 ? nz(s[1]) : math.max(nz(b[1]), nz(l[1]))
    s := 0
else if nz(z[1]) != 1
    s := nz(l[1])
    l := 0
else if z == 1
    s := math.min(c, nz(s[1]))
    l := nz(l[1])
else
    l := nz(l[1])
    s := nz(s[1])

if l > 0
    trail := l
else
    trail := s

trail_color_cond = ima < trail ? trail_color_down : trail_color_up
candle_color_cond = ohlc4 < trail ? candle_color_down : candle_color_up

p2 = plot(trail, color=trail_color_cond, title = "Trail")

plotcandle(open,high,low,close, color=candle_color_cond, wickcolor=candle_color_cond, bordercolor = candle_color_cond)

fill(plot1=p1, plot2=p2, color=trail_color_cond)