[JL] Stoch Candle
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jesselau76


//This script display stoch crossover/crossunder as candles.
//K>D then display Green bars,
//K<D then display Red bars.
//It can not be traded directly. You can use these candles to watch the strong/weak trend or reverse.
//I normally use higher timeframe to watch it. I am trading 15 min, so I will watch 1 hour/4 hour/Daily chart.
//Combine with my other script  Stochastic Divergence Alert https://www.tradingview.com/script/lJiDn2VR-JL-Stochastic-Divergence-Alert/ looks better
//@version=5
indicator(title="[JL] Stoch Candle", overlay=true,max_boxes_count=500,max_bars_back = 4900)

// Getting inputs
periodK = input.int(9, title="%K Length", minval=1)
smoothK = input.int(3, title="%K Smoothing", minval=1)
periodD = input.int(3, title="%D Smoothing", minval=1)

// Calculating
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(k, periodD)

turnGreen = ta.crossover(k,d)
turnRed   = ta.crossunder(k,d)


barsturngreen = bar_index - ta.valuewhen(turnGreen, bar_index, 0)
barsturnred = bar_index - ta.valuewhen(turnRed, bar_index, 0)
barsg = barsturngreen>0 ? barsturngreen : 1

h1 = ta.highest(high,barsg)
l1 = ta.lowest(low,barsg)
barsr = barsturnred>0 ? barsturnred : 1

h2 = ta.highest(high,barsr)
l2 = ta.lowest(low,barsr)
 

if turnRed 
	box.new(bar_index - barsg, h1, bar_index, l1, border_color = na, bgcolor = color.new(color.green, 50),border_width=2)
if turnGreen
	
    box.new(bar_index - barsr, h2, bar_index, l2, border_color = na, bgcolor = color.new(color.red, 50),border_width=2)