BT Leading Candle Indicator
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Baiju89

//@version=4

study("BT Leading Candle Indicator", overlay=false)

//functions
xrf(values, length) =>
    r_val = float(na)
    if length >= 1
        for i = 0 to length by 1
            if na(r_val) or not na(values[i])
                r_val  :=  values[i]
                r_val
    r_val
xsa(src,len,wei) =>
    sumf = 0.0
    ma = 0.0
    out = 0.0
    sumf  :=  nz(sumf[1]) - nz(src[len]) + src
    ma  :=  na(src[len]) ? na : sumf/len
    out  :=  na(out[1]) ? ma : (src*wei+out[1]*(len-wei))/len
    out


// inputs
n1 = input(30, title="n1", type=input.integer, minval = 1)

//threshold lines
h1 = hline(80,color=color.red, linestyle=hline.style_dotted)
h2 = hline(20, color=color.yellow, linestyle=hline.style_dotted)
h3 = hline(30,color=color.lime, linestyle=hline.style_dotted)
h4 = hline(90, color=color.fuchsia, linestyle=hline.style_dotted)
fill(h2,h3,color=color.yellow,transp=70)
fill(h1,h4,color=color.fuchsia,transp=70)

//KDJ indicator
rsv = (close-lowest(low,n1))/(highest(high,n1)-lowest(low,n1))*100
k = xsa(rsv,3,1)
d = xsa(k,3,1)
buysig =  iff(d<25 and crossover(k,d) ,30,0)
selsig =  iff(d>75 and crossunder(d,k) ,70,100)

//plot buy and sell signal
ple = plot(buysig,color=color.green, linewidth=1,style=plot.style_area, transp=0)
pse = plot(selsig,color=color.red, linewidth=2,style=plot.style_line, transp=0)

//plot KD candles
plotcandle(k, d, k, d, color=k>=d?color.green:na)
plotcandle(k, d, k, d, color=d>k?color.red:na)

// KDJ leading line
var1 = (close-sma(close,13))/sma(close,13)*100
var2 = (close-sma(close,26))/sma(close,21)*100
var3 = (close-sma(close,90))/sma(close,34)*100
var4 = (var1+3*var2+9*var3)/13
var5 = (100-abs(var4))
var10 = lowest(low,10)
var13 = highest(high,25)
leadingline =  ema((close-var10)/(var13-var10)*4,4)*25
pbias = plot(leadingline,color=k>=d?color.green:color.red, linewidth=4,style=plot.style_line, transp=10)
