Pine Script Stochastic %K and %D

Master this essential momentum oscillator in TradingView's Pine Script for identifying overbought/oversold conditions, trend strength, and reversals.

Last Updated on: Expertise: Intermediate

What is the Stochastic Oscillator (%K and %D)?

The Stochastic Oscillator, developed by George C. Lane, is a momentum indicator that shows the location of the closing price relative to the high-low range over a set number of periods. Unlike RSI, which measures the speed of price changes, Stochastic measures the *strength of a close* in relation to its price range. It consists of two lines: %K (the main line) and %D (the signal line, which is a smoothed version of %K).

Stochastic %K and %D oscillate between 0 and 100. They are particularly effective at identifying overbought and oversold conditions, as well as divergence from price, making them a crucial tool for anticipating reversals.

Components and Calculation

The Stochastic Oscillator's calculation involves a few key components:

  1. %K Line (Fast Stochastic):
    • `%K = ((Current Close - Lowest Low) / (Highest High - Lowest Low)) * 100`
    • Where `Lowest Low` is the lowest price over the look-back period (e.g., 14 bars) and `Highest High` is the highest price over the same period.
  2. %D Line (Slow Stochastic / Signal Line):
    • `%D = Simple Moving Average of %K` over a specified smoothing period (e.g., 3 periods).
  3. Slow %D (Optional): Sometimes, an additional smoothing is applied to the %D line, which is then often referred to as "Slow %D" or "%D of %D".

The core idea is that in an uptrend, prices tend to close near their high, and in a downtrend, prices tend to close near their low.

Basic Stochastic %K and %D Implementation in Pine Script

Pine Script v5 provides a straightforward built-in function `ta.stoch()` for calculating the Stochastic Oscillator.

//@version=5
indicator("My Stochastic Oscillator", overlay=false) // overlay=false to plot in a separate pane

// Inputs for Stochastic parameters
kLength = input.int(14, title="%K Length", minval=1)
dLength = input.int(3, title="%D Smoothing", minval=1)
smoothing = input.int(3, title="%K Smoothing", minval=1) // This is the internal smoothing for %K

// Calculate Stochastic %K and %D values using the built-in function
// ta.stoch returns %K and %D based on the provided lengths and smoothing
[kValue, dValue] = ta.stoch(close, high, low, kLength, smoothing, dLength)

// Plot the %K line
plot(kValue, title="%K", color=color.blue, linewidth=2)

// Plot the %D line
plot(dValue, title="%D", color=color.orange, linewidth=2)

// Plot horizontal lines for overbought and oversold levels
h_overbought = hline(80, "Overbought", color=color.red)
h_oversold = hline(20, "Oversold", color=color.green)

// Fill background between Stochastic lines and levels for visual clarity
fill(h_overbought, h_oversold, color.new(color.gray, 90))
Standard Levels: The conventional overbought level is 80 and the oversold level is 20 for Stochastic.

Practical Stochastic %K and %D Trading Strategies

1. Overbought and Oversold Conditions

When %K and %D enter the overbought region (above 80) or oversold region (below 20), it signals potential turning points. Trading signals are often generated when the lines move *out* of these extreme regions.

//@version=5
strategy("Stochastic Overbought/Oversold Strategy", overlay=true)

// Inputs for Stochastic
kLength = input.int(14, title="%K Length", minval=1)
dLength = input.int(3, title="%D Smoothing", minval=1)
smoothing = input.int(3, title="%K Smoothing", minval=1)
overboughtLevel = input.int(80, title="Overbought Level")
oversoldLevel = input.int(20, title="Oversold Level")

// Calculate Stochastic
[kValue, dValue] = ta.stoch(close, high, low, kLength, smoothing, dLength)

// Define conditions for entries and exits
// Buy when K crosses above D in oversold zone, then D rises above oversold level
longCondition = ta.crossover(kValue, dValue) and dValue < oversoldLevel

// Sell when K crosses below D in overbought zone, then D falls below overbought level
shortCondition = ta.crossunder(kValue, dValue) and dValue > overboughtLevel

// Strategy entries/exits
if (longCondition)
    strategy.entry("Long", strategy.long)

if (shortCondition)
    strategy.entry("Short", strategy.short)

// Optional: Plot Stochastic in a separate pane for visualization
// plot(kValue, "%K", color.blue)
// plot(dValue, "%D", color.orange)
// hline(overboughtLevel, "Overbought", color.red)
// hline(oversoldLevel, "Oversold", color.green)

2. Stochastic Crossover Strategy (%K and %D)

Crossovers between the %K and %D lines are frequent signals, indicating shifts in momentum. These are often combined with overbought/oversold zones for higher probability trades.

//@version=5
strategy("Stochastic Crossover Strategy", overlay=true)

// Inputs for Stochastic
kLength = input.int(14, title="%K Length", minval=1)
dLength = input.int(3, title="%D Smoothing", minval=1)
smoothing = input.int(3, title="%K Smoothing", minval=1)

// Calculate Stochastic
[kValue, dValue] = ta.stoch(close, high, low, kLength, smoothing, dLength)

// Define conditions for entries and exits
longSignal = ta.crossover(kValue, dValue) // %K crosses above %D
shortSignal = ta.crossunder(kValue, dValue) // %K crosses below %D

// Strategy entries/exits
if (longSignal)
    strategy.entry("Long", strategy.long)

if (shortSignal)
    strategy.entry("Short", strategy.short)

// Optional: Plot Stochastic in a separate pane
// plot(kValue, "%K", color.blue)
// plot(dValue, "%D", color.orange)
// hline(80, "Overbought", color.red)
// hline(20, "Oversold", color.green)

3. Stochastic Divergence Strategy

Divergence occurs when price and Stochastic move in opposite directions, often signaling a strong potential trend reversal. It suggests that the current trend is weakening or losing conviction.

//@version=5
indicator("Stochastic Divergence Scanner", overlay=true)

// Inputs for Stochastic
kLength = input.int(14, title="%K Length", minval=1)
dLength = input.int(3, title="%D Smoothing", minval=1)
smoothing = input.int(3, title="%K Smoothing", minval=1)
overboughtLevel = input.int(80, title="Overbought Level")
oversoldLevel = input.int(20, title="Oversold Level")

// Calculate Stochastic
[kValue, dValue] = ta.stoch(close, high, low, kLength, smoothing, dLength)

// Plot Stochastic in a separate pane
plot(kValue, "%K", color=color.blue)
plot(dValue, "%D", color=color.orange)
hline(overboughtLevel, "Overbought", color=color.red)
hline(oversoldLevel, "Oversold", color=color.green)
hline(50, "Centerline", color=color.gray)

// Simple divergence detection (conceptual, robust detection requires advanced pivot logic)
// This is a simplified example and might need refinement for actual trading.

// Bullish Divergence (Price lower low, %D higher low)
bullishDivergence = close[2] > close[1] and close[1] > close and dValue[2] < dValue[1] and dValue[1] < dValue

// Bearish Divergence (Price higher high, %D lower high)
bearishDivergence = close[2] < close[1] and close[1] < close and dValue[2] > dValue[1] and dValue[1] > dValue

plotshape(bullishDivergence, title="Bullish Divergence", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
plotshape(bearishDivergence, title="Bearish Divergence", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)

alertcondition(bullishDivergence, "Bullish Stochastic Divergence", "Potential bullish reversal based on Stochastic divergence.")
alertcondition(bearishDivergence, "Bearish Stochastic Divergence", "Potential bearish reversal based on Stochastic divergence.")

Optimizing Stochastic %K and %D Performance

To get the most from the Stochastic Oscillator in Pine Script:

Stochastic vs. RSI: While both are momentum oscillators, Stochastic focuses on the price's position relative to its recent range, whereas RSI focuses on the speed of price changes. They can complement each other well.

Common Stochastic %K and %D Pitfalls

Conclusion

The Stochastic Oscillator (%K and %D) is a fundamental and highly versatile momentum indicator in Pine Script for TradingView. Its ability to show the current closing price relative to its recent range makes it invaluable for identifying overbought and oversold conditions, assessing momentum, and spotting potential reversals through divergence. By understanding its calculation, thoughtfully tuning its parameters, and integrating it strategically with other technical analysis tools, you can leverage the Stochastic Oscillator to gain deeper insights into market dynamics and enhance your trading decisions.