Edgoro
Momentum indicator

Stochastic oscillator: %K, %D, settings and Pine Script v6 code

How the stochastic oscillator compares the close with the recent range, how traders read %K/%D crosses and 80/20 zones, settings, and a free script.

What it measures

The stochastic oscillator asks a simple question: where did the bar close relative to the high-low range of the last N bars? A reading of 100 means the close was at the top of that range, 0 means at the bottom, 50 means in the middle.

In rising markets closes tend to cluster near the top of the range, and in falling markets near the bottom. When that changes, momentum is changing. George Lane popularised the indicator in the 1950s; today it usually comes as two lines, %K and its average %D.

The formula in words

  1. Find the highest high and lowest low of the last N bars (14 by default).
  2. Raw %K = 100 × (close − lowest low) ÷ (highest high − lowest low).
  3. Optionally smooth raw %K with a short simple moving average (3 is common). The smoothed version is often called the slow stochastic.
  4. %D = a 3-period simple moving average of %K.

If the high and low of the window are equal (a completely flat market), the division has no answer and the value is undefined for that bar.

How traders read it

  • Zones. Above 80 is called overbought and below 20 oversold. Like RSI, the stochastic can stay in a zone for a long time during a trend.
  • %K / %D crosses. %K crossing above %D is read as momentum turning up. Many traders only count crosses that happen inside a zone, for example a bullish cross below 20.
  • Trend alignment. A common approach is to use the stochastic only for pullback timing in the direction of a higher-timeframe trend: in an uptrend, look for bullish crosses in the lower zone and ignore bearish ones.
  • Divergence. Price makes a lower low while the stochastic makes a higher low. It needs a trigger, just as with RSI divergence.

Common settings

SettingTypical valueNotes
%K length14The lookback window for the high-low range.
%K smoothing3 (slow) or 1 (fast)Smoothing removes much of the raw line's jitter.
%D length3The signal line.
Zones80 / 2070 / 30 gives more readings in the zones.

The stochastic reacts faster than a 14-period RSI, because it looks at the position in the range rather than the size of the moves. That means more signals and more noise.

Pine Script v6 code

The complete, self-contained script is below. Copy it into a new indicator in TradingView's Pine Editor, or download the .pine file.

Pine Script v6
//@version=6
indicator("Stochastic oscillator", shorttitle = "Stoch", format = format.price, precision = 2)

kLen    = input.int(14, "%K length", minval = 1)
kSmooth = input.int(3, "%K smoothing", minval = 1)
dLen    = input.int(3, "%D length", minval = 1)
obLevel = input.int(80, "Overbought", minval = 50, maxval = 100)
osLevel = input.int(20, "Oversold", minval = 0, maxval = 50)

k = ta.sma(ta.stoch(close, high, low, kLen), kSmooth)
d = ta.sma(k, dLen)

crossUp   = ta.crossover(k, d)
crossDown = ta.crossunder(k, d)

// Only crosses inside the zones are marked.
bullCross = crossUp and k < osLevel
bearCross = crossDown and k > obLevel

plot(k, "%K", color = color.new(color.blue, 0), linewidth = 2)
plot(d, "%D", color = color.new(color.orange, 0))
obLine = hline(obLevel, "Overbought", color = color.gray, linestyle = hline.style_dashed)
osLine = hline(osLevel, "Oversold", color = color.gray, linestyle = hline.style_dashed)
fill(obLine, osLine, color = color.new(color.blue, 93), title = "Range")

plotshape(bullCross, "Bullish cross in oversold", shape.triangleup, location.bottom, color.new(color.teal, 0), size = size.tiny)
plotshape(bearCross, "Bearish cross in overbought", shape.triangledown, location.top, color.new(color.red, 0), size = size.tiny)

alertcondition(bullCross, "Bullish stochastic cross", "%K crossed above %D below the oversold level on {{ticker}} ({{interval}})")
alertcondition(bearCross, "Bearish stochastic cross", "%K crossed below %D above the overbought level on {{ticker}} ({{interval}})")

This is the slow stochastic by default (%K smoothed over 3 bars, %D over 3 more). Set "%K smoothing" to 1 for the fast version. Triangles mark only the crosses that happen inside a zone, which is how most traders filter the many crosses the indicator produces, and the same two events are available as alert conditions.

Add it to your chart

  1. Open any chart on TradingView and open the Pine Editor.
  2. Create a new indicator, delete the template code and paste the script.
  3. Click Save, then Add to chart. Change lengths and levels from the indicator's settings.

Stuck on an error? See how to add a Pine Script indicator to TradingView.

Pitfalls

  • Taking every cross. %K and %D cross constantly. Without a zone or trend filter most crosses are noise.
  • Fighting the trend. An overbought stochastic in a strong uptrend is normal. Shorting it repeatedly is a common way to lose.
  • Flat windows. When the high-low range is zero the value is undefined. It's rare on liquid symbols, but it happens on illiquid ones and outside sessions.
  • Live-bar crosses. The close is still moving on the current bar. Use once-per-bar-close alerts.

The script is an educational example: test it on your own markets before relying on it. Indicators describe the past; they don't predict the future. Trading involves substantial risk of loss and is not suitable for every investor. Edgoro is a software tool, not a broker or financial adviser: nothing it produces is investment advice, and past or backtested performance does not guarantee future results.

Make it yours with Edgoro

Describe the change in plain English and Edgoro writes the Pine Script v6 for you, ready to paste. For example:

“Plot a slow stochastic (14, 3, 3) and alert on a bullish %K/%D cross below 20 only when the 1-hour close is above the 1-hour 50 EMA, non-repainting.”

Build your Stochastic indicator