Concept 44 / 52·Momentum·Bounded oscillators
‹ Relative Volume & Volume SpikesSuperTrend ›

Stochastic Oscillator in Pine Script

stochastic · stoch · %K and %D · slow stochastic · Lane's stochastic

A bounded oscillator that places the latest close inside the high-low range of the last 14 bars, smoothed into %K and %D lines, with 80 and 20 as the extreme zones.

Reads best on: Ranging markets on any timeframe: index futures and forex pairs on 5-minute to 4-hour charts, and daily stocks inside a base. In strong trends it is a pullback tool only.
On this page: the Pine v6 script, checked, drawn on real NVDA bars. Backtest it free, costs charged, every trade on the chart.
Backtest results: Stochastic strategy: SPY, QQQ and more since 2016, costs charged, every trade listed.
01

Definition

The stochastic oscillator is a bounded momentum oscillator that reads where the latest close sits inside the range of the last n bars. A close at the very top of the range gives 100; a close at the bottom gives 0. The raw reading is called %K, and a short moving average of it is called %D, the signal line. The slow stochastic, which is what most platforms show, smooths %K once more before %D is taken from it. It belongs with RSI and Williams %R in the bounded family, because the scale is fixed from 0 to 100 on every market.

The idea behind it is that closes cluster near the top of the range while a rise is healthy and drift towards the middle before a top. The same holds in reverse for a decline. So the oscillator does not measure the size of a move; it measures where the market is choosing to close relative to what it has recently traded. That makes it fast: a single strong close can lift %K from 20 to 60 in one bar. The %D line exists to slow that down and to give %K something to cross.

George Lane popularised the stochastic in the 1950s and taught it for decades afterwards. The defaults on nearly every platform are 14 bars for the range, a 3-bar smoothing of %K and a 3-bar %D, written 14, 3, 3, with 80 and 20 as the overbought and oversold lines. The fast version, 14, 1, 3, skips the first smoothing and is used by scalpers; 5, 3, 3 is a common intraday setting. Lane's own emphasis was on divergence between %D and price rather than on the zones themselves.

Mechanically the lines swing across the whole scale far more often than RSI does. On daily bars a 14, 3, 3 stochastic visits 80 or 20 several times a month. In a trend it can sit above 80 for weeks while price grinds higher, a state traders call embedded. The %K and %D lines cross often in the middle of the scale, and those crosses carry little information. The crosses that matter form inside the zones. That is why the library's script only marks a cross up while %K is below 20 and a cross down while %K is above 80.

02

Reading the chart

Read the stochastic in three parts: the zone, the cross, and the agreement with the price swing.

  1. Add a slow stochastic, 14, 3, 3, in its own pane with lines at 80 and 20. Confirm it is the slow version: the fast version, with no %K smoothing, gives twice as many crosses and is a different tool.
  2. Locate the pair. %K is the faster line and %D the slower; when %K is above %D the oscillator is rising. Note whether both lines are inside a zone, and for how many bars.
  3. Wait for %K to cross %D while inside the zone. A cross up below 20 is the classic long setup, a cross down above 80 the short setup. Crosses in the middle of the scale are noise and are best ignored.
  4. Check the price swing that produced the reading. A cross up from oversold at a higher low in price, or at a known support, is stronger than the same cross in the middle of a fall.
  5. Look for divergence between %D and price at consecutive swings. A higher %D low against a lower price low was Lane's preferred signal, and it tends to lead the zone cross by a few bars.
  6. Decide whether the market is trending. If the oscillator has been embedded above 80 for many bars, the trend is strong and a cross down is a pause, not a short; exit rules use it to tighten stops instead.
03

The maths

The raw stochastic is the position of the close within the recent range; the slow version smooths it twice.

%Ktraw=100 Ct−LnHn−Ln\%K^{\mathrm{raw}}_t = 100 \, \frac{C_t - L_n}{H_n - L_n}
%Ktslow=1sK∑i=t−sK+1t%Kiraw\%K^{\mathrm{slow}}_t = \frac{1}{s_K} \sum_{i=t-s_K+1}^{t} \%K^{\mathrm{raw}}_i
%Dt=1sD∑i=t−sD+1t%Kislow\%D_t = \frac{1}{s_D} \sum_{i=t-s_D+1}^{t} \%K^{\mathrm{slow}}_i
CtC_tclose of the current bar
HnH_nhighest high of the last n bars, including the current one
LnL_nlowest low of the last n bars, including the current one
nnthe range length, 14 by default
sKs_Kthe smoothing length applied to raw %K, 3 by default
sDs_Dthe length of the %D signal line, 3 by default
SMA\mathrm{SMA}a simple moving average of the series over the given length
iithe bar index inside the averaging window
Raw%Kt\mathrm{Raw} \%K_tthe unsmoothed stochastic at bar t
Slow%Kt\mathrm{Slow} \%K_tthe smoothed %K line at bar t
%Dt\%D_tthe signal line at bar t

The fast stochastic sets s_K to 1, so %K is the raw reading and %D is its 3-bar average. The slow stochastic's %K is the fast stochastic's %D.

When the range is zero, because every bar in the window has the same high and low, the division is undefined; platforms hold the previous value or print 0.

The range uses highs and lows, not closes, so a long wick changes the reading even when the close does not move.

The full stochastic lets each of the three numbers vary independently; 14, 3, 3 is the full form of the slow default.

04

Inputs that matter

InputTypicalWhat changing it does
%K length14Shorter ranges make the oscillator reach 80 and 20 on almost every swing; longer ranges keep it in the middle and reserve the zones for large moves against the recent range.
%K smoothing31 gives the fast stochastic with many crosses; 3 to 5 removes single-bar spikes at the cost of a bar or two of lag.
%D smoothing3Longer values slow the signal line, so %K crosses it later and less often; shorter values give earlier crosses with more whipsaws.
Overbought and oversold80 and 20Moving them to 90 and 10 waits for rarer extremes; 70 and 30 turns the tool into a pullback trigger inside trends.
05

In practice

  • As a range timing tool: the rule goes long on the %K cross above %D below 20 and short on the cross below %D above 80, which is exactly what the library's script marks as Long and Short.
  • As a pullback trigger in a trend: with a higher-timeframe trend filter, the filter keeps only the crosses that point with the trend, so an uptrend takes longs on oversold crosses and no shorts on overbought ones.
  • As an embedded-trend reader: %K holding above 80 for many bars is a sign of strength, not of an imminent top. The hold rule keeps the position and moves the stop up until the oscillator drops out of the zone.
  • As a divergence tool: compare %D swings with price swings. A lower price low with a higher %D low, followed by a cross up, was Lane's primary setup and still reads well on daily bars.
  • As a fast intraday oscillator: a 5, 3, 3 stochastic on 5-minute bars times entries inside a range that a session VWAP or an opening range has already defined.
  • As a confirmation for a candle pattern: a hammer at support with the stochastic crossing up below 20 gives two independent reasons to expect a bounce. The cross also gives a clean bar for the alert.
06

Where it goes wrong

  • Trading every cross. Most %K and %D crosses happen in the middle of the scale and reverse within bars; only the crosses inside the zones deserve attention.
  • Shorting an embedded reading. When %K holds above 80 for weeks the market is trending hard; wait for the drop out of the zone and for price to confirm with a lower high.
  • Using the fast stochastic by accident. The 14, 1, 3 version fires far more often; check the smoothing setting before comparing signals across platforms.
  • Ignoring the range that produced the reading. A 14-bar stochastic on a quiet day flags overbought after a tiny move; read it against the size of the recent range and the higher-timeframe trend.
07

Compared with

RSI. RSI compares average gains with average losses, so it moves smoothly and holds a level; the stochastic reads the close's place in the recent range, so it moves fast and swings edge to edge. Use the stochastic for timing inside a defined range and RSI for the regime and for divergence on slower charts.

Williams %R. Williams %R is the raw stochastic %K measured from the top of the range instead of the bottom, plotted from 0 to −100 with no smoothing. The two carry the same information; the stochastic adds the %D line and the cross signal, which %R does not have.

CCI. CCI measures how far typical price sits from its average in units of mean deviation, and it is unbounded, so it can run to 300 in a strong move. The stochastic is capped at 100 and asks a narrower question, where the close sits in the range. It reads better inside ranges; CCI reads better in trends.

MACD. MACD tracks the gap between two EMAs and turns slowly with the trend; the stochastic turns with every swing. Traders pair them: MACD for direction, stochastic for the entry inside that direction. Taking stochastic signals against the MACD slope is where most of its losing trades come from.

08

Build it in Quant

Type one of these in the Quant desk, or click it. A request that fits a checked template is assembled on the spot without a credit; anything beyond the blanks goes to the copilot, which edits on top of the checked script.

Open Stochastic Oscillator on the workbench chart
Drawn on real data; then audit, backtest and refine in conversation.
Open in Quant →
09

Questions

  • What do 14, 3, 3 mean?

    The first number is the range length: the highest high and lowest low of the last 14 bars. The second is the smoothing applied to the raw %K, 3 bars for the slow stochastic. The third is the length of %D, the moving average of the smoothed %K that acts as the signal line. Change the first to alter how many swings the oscillator sees; change the other two to alter how jumpy it is.

  • Which is better, fast or slow stochastic?

    Slow, for almost everyone. The fast version uses the raw %K, which jumps on every wide bar and crosses %D constantly. The slow version smooths %K over 3 bars first, cutting the false crosses at the cost of a bar of lag. Scalpers who want the earliest turn use the fast version and accept the noise; swing traders use the slow one.

  • Does a stochastic above 80 mean the market will fall?

    No. It means the recent closes sit near the top of the recent range, which is what an uptrend does. In a strong move the oscillator stays above 80 for many bars, and the first drop below it is usually a pause. The short setup is a %K cross below %D while above 80, kept only when the trend on the chart allows it.

  • What is the difference between the stochastic and Williams %R?

    Almost nothing in the maths: %R measures the close from the top of the range and plots from 0 to −100, the stochastic measures from the bottom and plots from 0 to 100. Invert one and you have the other. The stochastic adds smoothing and the %D signal line, so it has a cross signal; %R is raw and is read against its zones only.

  • How does the library's stochastic script decide on a mark?

    It computes the slow stochastic with 14, 3, 3, and plots %K in green and %D in red with dashed lines at 80 and 20. It marks Long when %K crosses above %D while %K is below 20. Short is the mirror: %K crossing below %D while above 80. Crosses in the neutral band are drawn but never marked, and every mark waits for the bar to close.

  • Can I use the stochastic in a trend?

    Yes, as a pullback tool rather than a reversal tool. The trend comes from a higher timeframe or a moving average, then a trend rule takes only the oversold crosses in an uptrend and the overbought crosses in a downtrend. The marks against the trend are the ones that fail; many traders also raise the lines to 70 and 30 so that pullbacks register.