How can I create a Stochastic Oscillator in Pine Script?

Asked by Radhesh Joshi · SOLVED
1 reply 278 views Jump to solution Reply
Radhesh Joshi Original Post
Strategy Builder

I’m trying to create a Stochastic Oscillator in Pine Script to understand how the %K and %D lines are calculated instead of simply using the built-in indicator.

I want to plot both lines and add the standard 80 and 20 levels so the overbought and oversold zones are easy to identify.

I’m also looking for a way to keep the settings configurable, such as the %K length, %D length, and smoothing.

Can anyone help me with the correct way to implement this in Pine Script?

Posted Aug 19
Reply

    1 Reply

    Tech Support AlgoDelta
    Tech Support AlgoDelta Automation Expert ·

    Yes sir, you can definitely create a Stochastic Oscillator in Pine Script.

    The Stochastic Oscillator mainly uses the current close compared with the highest high and lowest low over a selected period.

    -> %K measures the current price position within that high-low range.

    -> %D is a moving average of the %K line.

    You can create a basic version using:

    //@version=6
    indicator("Custom Stochastic", overlay=false)
    
    kLength = input.int(14, "%K Length")
    kSmooth = input.int(3, "%K Smoothing")
    dLength = input.int(3, "%D Length")
    
    rawK = ta.stoch(close, high, low, kLength)
    k = ta.sma(rawK, kSmooth)
    d = ta.sma(k, dLength)
    
    kPlot = plot(k, "%K")
    dPlot = plot(d, "%D", color = color.orange)
    
    overbought = hline(80, "Overbought")
    MiddLine = hline(50, "Midline")
    oversold = hline(20, "Oversold")
    
    fill(overbought, oversold, color=color.new(color.blue, 90))

    -> The %K line represents the current price position within the selected high-low range.

    -> The %D line is a smoothed version of %K.

    -> 80 is commonly used as the overbought level.

    -> 20 is commonly used as the oversold level.

    -> The input values allow to adjust the calculation from the indicator settings.

    => This gives you a configurable Stochastic Oscillator without depending on the built-in chart indicator.

    So that’s how you can create a basic Stochastic Oscillator in Pine Script.

    Verified Solution
      Markdown supported · ```json for code blocks · paste or drop screenshots

      Be specific and kind. Never share API keys, passwords or personal account details.

      Welcome to the community

      Log in or create your account in under a minute.

      1. 1Mobile
      2. 2E-mail
      3. 3Password
      +91

      Have a password?

      By continuing you agree to the community guidelines. We’ll send a one-time code by SMS.