Tutorial

Stochastic Oscillator in Pine Script: A Complete Guide

What the stochastic oscillator measures, why %K and %D are read together, and how to build the indicator and a strategy in Pine Script v6.

10 min read

The stochastic oscillator is a momentum indicator that answers a deceptively simple question: where does the current close sit within the recent high-to-low range? If price is closing near the top of its recent range, momentum is strong; near the bottom, weak. Developed by George Lane in the late 1950s, it plots as two lines, %K and %D, swinging between 0 and 100 in a pane below the chart. This guide explains what the stochastic measures, why traders read its two lines together, and how to build it from scratch in Pine Script v6 on TradingView.

This is a coding tutorial, not trading advice. The stochastic is a way to express a question about closing strength within a range in code, and building it yourself is the best way to understand where it helps and where it fires too early.

What the stochastic measures

The core calculation, called %K, takes the current close, subtracts the lowest low over the lookback period, and divides by the range between the highest high and lowest low over that same period, scaled to a percentage. If the close equals the period's high, %K reads 100; if it equals the period's low, %K reads 0. So the raw %K is purely a measure of where in its recent range price is closing, which is a different flavor of momentum from the up-versus-down averaging that the RSI uses.

Raw %K is jumpy, so in practice it is smoothed with a short moving average, and %D is a further moving average of that smoothed %K. The result is two lines: a faster %K that reacts quickly and a slower %D that confirms. Reading them together, rather than either alone, is central to how the indicator is used. The traditional overbought and oversold levels sit at 80 and 20 rather than the 70 and 30 the RSI uses.

%K%D
What it isRaw position in the rangeMoving average of %K
SpeedFaster, choppierSlower, smoother
RoleThe trigger lineThe confirmation line
Pine sourceta.stoch()ta.sma() of ta.stoch()

Why traders use it

Traders use the stochastic in two main ways. The first is the same overbought and oversold logic as the RSI: readings above 80 suggest price is closing near the top of its range and may be stretched, while readings below 20 suggest the opposite. The second, and more characteristic, is the crossover of the two lines. When the faster %K crosses above the slower %D from a low reading, it is read as momentum turning back up, and the mirror case as momentum turning down. Because %K leads and %D confirms, the crossover gives a defined trigger rather than a vague zone.

If the stochastic reminds you of the RSI, that is fair: both are bounded momentum oscillators with overbought and oversold zones, and both work best in range-bound markets and struggle in trends, where they can stay pinned in an extreme for a long time. The difference is what they measure, closing strength within a range versus the ratio of up moves to down moves, and the stochastic's two-line crossover gives it a distinct signal the single-line RSI does not have. Our RSI in Pine Script guide is a useful companion for the comparison.

Building the indicator

Pine Script gives you the raw %K through the ta.stoch() function, and you build the smoothing yourself with moving averages, which makes the construction explicit and easy to adjust. Here is the complete v6 indicator.

pine
//@version=6
indicator("Stochastic", overlay = false)

periodK  = input.int(14, "%K Length")
smoothK  = input.int(3, "%K Smoothing")
periodD  = input.int(3, "%D Smoothing")

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

plot(k, "%K", color = color.blue, linewidth = 2)
plot(d, "%D", color = color.orange, linewidth = 2)

hline(80, "Overbought", color = color.red)
hline(20, "Oversold", color = color.green)

The line ta.stoch(close, high, low, periodK) computes the raw %K, the close's position within the period's high-to-low range. Wrapping it in ta.sma(..., smoothK) produces the smoothed %K that traders actually watch, and ta.sma(k, periodD) produces %D as a moving average of that. Setting overlay = false keeps the oscillator in its own pane, and the two hline() calls mark the 80 and 20 levels. Exposing all three lengths as inputs lets you tune the balance between responsiveness and smoothing without editing the code.

Turning it into a strategy

A classic stochastic strategy combines the oversold zone with the line crossover: enter long when %K crosses above %D while both are in oversold territory, and exit when they cross back down from overbought. Here it is in v6.

pine
//@version=6
strategy("Stochastic Strategy", overlay = true, margin_long = 100, margin_short = 100)

periodK = input.int(14, "%K Length")
smoothK = input.int(3, "%K Smoothing")
periodD = input.int(3, "%D Smoothing")

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

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

if crossUp and oversold
    strategy.entry("Long", strategy.long)

if crossDown
    strategy.close("Long")

The entry requires two things at once: a bullish crossover of %K over %D, and %K being in the oversold zone, so the strategy only acts on turns that begin from a stretched reading rather than every crossover. Each crossover is assigned to its own variable before the if condition, which matters because in v6 the and operator evaluates lazily and could otherwise skip a ta.crossover() call that needs to run on every bar. This is the same hoisting habit we stress throughout these tutorials, and skipping it causes a subtle class of bugs covered in why Pine Script won't compile.

Fast, slow, and full stochastic

You will see the stochastic described as fast, slow, or full, and the difference is only how much smoothing is applied. The fast stochastic uses the raw %K with minimal smoothing, which reacts quickly but is noisy. The slow stochastic smooths %K more heavily before computing %D, trading some responsiveness for far fewer false crossovers. The full stochastic exposes all the smoothing lengths as separate settings, which is exactly what the indicator above does. There is no universally correct choice; faster settings suit shorter timeframes and slower ones suit calmer, higher-timeframe analysis.

The honest pitfalls

The main pitfall is the same trap the RSI sets: in a strong trend the stochastic can sit in overbought or oversold for a long stretch while price keeps going, so fading every extreme reading gets you run over. The overbought and oversold zones are meaningful in a range and misleading in a trend, which is why many traders add a trend filter and only take oversold crossovers when the broader market is pointing up.

The second pitfall is over-smoothing or under-smoothing to fit one chart. More smoothing removes false signals but adds lag; less smoothing does the reverse. Pick a balance you can justify and test it across a meaningful sample of trades and more than one symbol. To see exactly how %K and %D are computed from a set of OHLC data, our stochastic oscillator calculator shows the arithmetic with the Pine Script equivalent beside it.

Building it faster

Coding the stochastic by hand is worthwhile because the smoothing layers are where the fast, slow, and full variants come from, and typing them out makes that concrete. When you already know the exact settings you want, describing them in plain English is faster than wiring the moving averages together. A tool like PineScripter generates the v6 code and fixes compile errors automatically by reading TradingView's messages, and you can compare it with other options in our roundup of the best AI Pine Script generators.

The takeaway

The stochastic oscillator measures where price closes within its recent range, delivered by ta.stoch() and smoothed into the %K and %D lines you read together. Its crossover gives a defined trigger the RSI lacks, but it shares the RSI's weakness in trends. Build it, decide how much smoothing you want, filter it for the market you trade, and judge it across a real sample.


Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.