Logo
OFFLINEPIXEL
/ pinescript-strategies / pine-script-stochastic

$ 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.

500+ Clients Helped
100% Satisfaction
Live Trading Ready
⚠️
Trading financial markets carries risk. All content (PineScript code, indicators, strategies) on this website is for educational purposes only. Past performance is not indicative of future results. By using any code or information from this site, you agree that you are solely responsible for your trading decisions. The author disclaims all liability for any losses incurred. To gain from experts experiences, You can always try our Invite Only Scripts
01

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.

02

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".
03

Basic Stochastic %K and %D Implementation in Pine Script

pine-script@terminal
//@version=5
indicator("My Stochastic Oscillator", overlay=false)

// 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)

// Calculate Stochastic %K and %D values using the built-in function
[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))
$ ✓ Compiled successfully
04

Standard Levels

Standard Levels

The conventional overbought level is 80 and the oversold level is 20 for Stochastic.

05

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.

  • Buy Signal: Both %K and %D are in the oversold region (below 20), and then %K crosses above %D from below the 20 level.
  • Sell Signal: Both %K and %D are in the overbought region (above 80), and then %K crosses below %D from above the 80 level.
//@version=5
strategy("Stochastic Overbought/Oversold Strategy", overlay=true)

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")

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

longCondition = ta.crossover(kValue, dValue) and dValue < oversoldLevel
shortCondition = ta.crossunder(kValue, dValue) and dValue > overboughtLevel

if (longCondition)
    strategy.entry("Long", strategy.long)

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

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

Crossovers between the %K and %D lines are frequent signals, indicating shifts in momentum.

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

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)

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

longSignal = ta.crossover(kValue, dValue)
shortSignal = ta.crossunder(kValue, dValue)

if (longSignal)
    strategy.entry("Long", strategy.long)

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

3. Stochastic Divergence Strategy

Divergence occurs when price and Stochastic move in opposite directions, often signaling a strong potential trend reversal.

  • Bullish Divergence: Price makes a lower low, but Stochastic (%K or %D) makes a higher low.
  • Bearish Divergence: Price makes a higher high, but Stochastic (%K or %D) makes a lower high.
//@version=5
indicator("Stochastic Divergence Scanner", overlay=true)

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")

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

plot(kValue, "%K", color.blue)
plot(dValue, "%D", color.orange)
hline(overboughtLevel, "Overbought", color.red)
hline(oversoldLevel, "Oversold", color.green)
hline(50, "Centerline", color.gray)

bullishDivergence = close[2] > close[1] and close[1] > close and dValue[2] < dValue[1] and dValue[1] < dValue
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.")
06

Optimizing Stochastic %K and %D Performance

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

  • Parameter Tuning: The `kLength`, `dLength`, and `smoothing` parameters are crucial. While (14, 3, 3) are standard, shorter lengths make Stochastic more sensitive but prone to noise, while longer lengths smooth it more but add lag.
  • Combine with Trend Filters: Stochastic performs best in trending markets or within range-bound markets. Use a trend filter (like a moving average or ADX) to confirm a clear trend before relying on Stochastic signals.
  • Multi-Timeframe Analysis: Confirm Stochastic signals on a higher timeframe before acting on signals from a lower timeframe.
  • Confluence with Price Action: Always look for Stochastic signals to be confirmed by price action, such as candlestick patterns, breaks of support/resistance, or chart patterns.
  • Focus on Divergence in Trends: Divergence signals are often more powerful when they occur during an established trend, suggesting its exhaustion.
07

Stochastic vs. RSI

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.

08

Common Stochastic %K and %D Pitfalls

  • False Overbought/Oversold Signals: In strong, sustained trends, Stochastic can remain at extreme overbought or oversold levels for extended periods.
  • Whipsaws in Ranging Markets: In choppy or consolidating markets, %K and %D can cross frequently and fluctuate rapidly within the 20-80 range.
  • Divergence Can Be Early: While divergence is a powerful signal, it can appear early, and a trend might continue for some time after the divergence signal.
  • Not a Standalone Indicator: Stochastic should always be used as part of a broader trading system, combined with other indicators and price action analysis.
09

Conclusion

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 strategies.

Enhance Your Trading

Get a high-performance Pine Script analysis tool for actionable market insights, designed for traders on the move.

This strategy runs in live mode on TradingView, helping you identify potential opportunities.

Get Pine Script Strategy