plotpine-scriptstochastic

Built-in stochastic(8,3,3) computes different than the one I coded in Pine


Built-in Stoch vs test:

enter image description here

It looks as if another smoothing perhaps is applied. Same settings:

enter image description here enter image description here

Notice I use (8,3,3) and that D is actually not used or plotted here.

Is the functions, built-in and the one I use, not WYSIWYG?

Built-in:

//@version=5
indicator(title="Stochastic", shorttitle="Stoch", format=format.price, precision=2, timeframe="", timeframe_gaps=true)
periodK = input.int(8, title="%K Length", minval=1)
smoothK = input.int(3, title="%K Smoothing", minval=1)
periodD = input.int(3, title="%D Smoothing", minval=1)
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(k, periodD)
plot(k, title="%K", color=#2962FF)
plot(d, title="%D", color=#FF6D00)
h0 = hline(80, "Upper Band", color=#787B86)
h1 = hline(20, "Lower Band", color=#787B86)
fill(h0, h1, color=color.rgb(33, 150, 243, 90), title="Background")

Mine:

//@version=4
study(title="test", overlay=false)

src  = input(close, title="Index Source")
v2 = security("OANDA:USDJPY", timeframe.period, src)
h2 = security("OANDA:USDJPY", timeframe.period, high)
l2 = security("OANDA:USDJPY", timeframe.period, low)

Length = input (8, minval=1, title = "Stochastic Length")
k = input (3, minval=1, title = "Stochastic %K")
StoV2 = stoch (v2, highest(h2, Length), lowest(l2, Length), Length)
Kv2 = sma (StoV2, k)
plot (Kv2, title  ="%K", color = color.blue, linewidth=2)

Remember to use USDJPY for comparison!


Solution

  • Yes, they're different because your code does something different than the built in's code. The result differs because you're using highest() and lowest() in the stoch() call. They aren't needed if you're trying to reproduce the built in function. The stoch() function performs the equivalent of highest/lowest already in it's process, so what you have is the equivalent of doing highest(highest()). Also you can reduce the number of security calls by performing the operation within one security call like so :

    stoch_k = security("OANDA:USDJPY", timeframe.period, sma(stoch(src, high, low, Length), k))