Indicator · Pine Script v6 · Own pane

Stochastic W%R

by SiegerTerpstra· code credited to sajjetti

Stochastic W%R is a momentum oscillator that combines Stochastic smoothing techniques with Williams %R concepts.

View on GitHub

GitHub stars5on the repository
Pine versionv6current
Lines of code163
Settings8inputs
LicenceNone statedfile: MPL-2.0
Last update9 months ago14 Jan 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

163 lines of Pine Script v6 from 4 - Stochastic W%R (v6).pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

4 - Stochastic W%R (v6).pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © sajjetti

//@version=6

//-------------------------------------

// Release:                     2025-12-29
// Update:                      2026-01-04
// Author:                      sajjetti
// Email:                       contact@sajjetti.ai
// Website:                     sajjetti.ai
// Profile:                     https://www.tradingview.com/u/stmd/
// Pineversion:                 6
// Filename:                    4 - Stochastic W%R (v6).pine

//-------------------------------------
// PURPOSE
// Stochastic-style Williams %R - a momentum oscillator using Stochastic
// calculation with K and D lines. Combines Stochastic smoothing with
// Williams %R concepts for crossover signals.

//-------------------------------------
// FEATURES
// - Multi-timeframe support via Indicator Timeframe input
// - K line: Smoothed Stochastic
// - D line: Signal line (SMA of K)
// - K/D crossover signals
// - Configurable bands and entry/exit levels
// - Dynamic color based on K vs D and rising/falling

//-------------------------------------
// NOTES
// - Values oscillate between 0 and 100
// - K above D = bullish momentum
// - K below D = bearish momentum
// - Entry signal: K crosses above D below entry level
// - Exit signal: K crosses below D above exit level

//-------------------------------------
// INDICATOR PARAMETERS

vVersion                        = "V2.1"
vPineVersion                    = "ps6"
vTitle                          = "Stochastic W%R"
vShort                          = "Sto W%R"
vOverlay                        = false
vPrecision                      = 2

indicator( title = vTitle+" ["+vVersion+"|"+vPineVersion+"]", shorttitle = vShort+" ["+vVersion+"|"+vPineVersion+"]", overlay = vOverlay, precision = vPrecision )

//-------------------------------------
// INPUTS

var groupSwr                    = "Stochastic W%R (Standard: close, 13, 4, 6)"

vTimeframe                      = input.timeframe( defval = "", title = "Indicator Timeframe" )
vSource                         = input.source( defval = close, title = "Source", group = groupSwr )
vLengthK                        = input.int( defval = 13, minval = 1, maxval = 1024, title = "K - Length", group = groupSwr )
vSmoothK                        = input.int( defval = 4, minval = 1, maxval = 1024, title = "K - Smooth", group = groupSwr )
vPeriodD                        = input.int( defval = 6, minval = 1, maxval = 1024, title = "D - Period", group = groupSwr )
vOffSet                         = input.int( defval = 0, minval = 0, maxval = 1024, title = "Offset", group = groupSwr )
vLowerBandValue                 = input.int( defval = 5, minval = 0, maxval = 100, title = "Lower Band", group = groupSwr )
vUpperBandValue                 = input.int( defval = 95, minval = 0, maxval = 100, title = "Upper Band", group = groupSwr )

//-------------------------------------
// COLORS

cBullish                        = #26A69A
cBearish                        = #EF5350
cMedian                         = color.gray
cUpperBand                      = color.red
cLowerBand                      = color.green
cD                              = color.gray
cFillTransparency               = 75

//-------------------------------------
// FUNCTIONS

// @function    Simple Moving Average
// @param       n (int) Offset for lookback starting point
// @param       s (series float) Source data
// @param       le (int) Length of the averaging period
// @returns     (float) Average value over the specified period
fMa( n, s, le ) =>
    r = float( 0 )
    for i = n + 0 to ( n + ( le - 1 ) )
        r := ( r + s[ i ] )
    a = r / le
    a

// @function    Stochastic calculation
// @param       n (int) Offset for lookback
// @param       s (series float) Source data
// @param       le (int) Lookback period
// @returns     (float) Stochastic value between 0 and 100
fStoch( n, s, le ) =>
    hi  = ta.highest( high[ n ], le )
    lo  = ta.lowest( low[ n ], le )
    rng = hi - lo
    r   = rng == 0 ? 50.0 : ( ( s[ n ] - lo ) / rng * 100 )
    r

// @function    Calculate K line (smoothed stochastic)
// @param       n (int) Offset
// @param       s (series float) Source data
// @param       le (int) Stochastic length
// @param       sm (int) Smoothing period
// @returns     (float) Smoothed K value
fK( n, s, le, sm ) =>
    stochRaw = fStoch( n, s, le )
    fMa( 0, stochRaw, sm )

// @function    Calculate D line (signal line)
// @param       k (series float) K line values
// @param       pe (int) Period for D line
// @returns     (float) D value (SMA of K)
fD( k, pe ) =>
    fMa( 0, k, pe )

// @function    Calculate Stochastic W%R for MTF support
// @returns     (tuple) K and D values
fCalcStoWpr() =>
    k = fK( vOffSet, vSource, vLengthK, vSmoothK )
    d = fD( k, vPeriodD )
    [ k, d ]

// @function    Color based on rising/falling K
// @param       s (series float) K line
// @returns     (color) Green if rising, red if falling
fColorRising( s ) =>
    r = s > s[ 1 ] ? cBullish : cBearish
    r

// @function    Color based on K vs D
// @param       k (series float) K line
// @param       d (series float) D line
// @returns     (color) Green if K > D, red if K < D
fColorKvsD( k, d ) =>
    r = k > d ? cBullish : cBearish
    r

//-------------------------------------
// CALCULATIONS

[ vK, vD ] = if vTimeframe == ""
    fCalcStoWpr()
else
    request.security( syminfo.tickerid, vTimeframe, fCalcStoWpr() )

//-------------------------------------
// PLOT

vLineMedian                     = hline( 50, color = cMedian, linestyle = hline.style_dashed, linewidth = 1, title = "Median" )
vLineLowerBand                  = hline( vLowerBandValue, color = cLowerBand, linestyle = hline.style_dotted, linewidth = 2, title = "Lower Band" )
vLineUpperBand                  = hline( vUpperBandValue, color = cUpperBand, linestyle = hline.style_dotted, linewidth = 2, title = "Upper Band" )

vPlotK                          = plot( vK, color = fColorRising( vK ), style = plot.style_line, linewidth = 2, title = "SWPR K - ST" )
vPlotD                          = plot( vD, color = cD, style = plot.style_line, linewidth = 1, title = "SWPR D - ST" )

fill( vPlotK, vPlotD, color = color.new( fColorKvsD( vK, vD ), cFillTransparency ), title = "K/D Background" )

//-------------------------------------

Overview

Stochastic W%R calculates a smoothed K line alongside a D signal line derived from a simple moving average of K. The indicator plots in a separate pane with bounded values ranging between 0 and 100, featuring customizable upper and lower threshold bands. Crossovers between the K and D lines help identify potential momentum shifts and reversal points. Settings allow users to adjust lookback periods, smoothing, offset, and indicator timeframe.

Details

Published by

SiegerTerpstra on GitHub

Code credit

sajjetti, as written in the script's header

Draws

Separate pane below the chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

tradingviewindicatorindicators

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Indicator TimeframetimeframevTimeframe
SourcesourceclosevSource
K - Lengthint13vLengthK
K - Smoothint4vSmoothK
D - Periodint6vPeriodD
Offsetint0vOffSet
Lower Bandint5vLowerBandValue
Upper Bandint95vUpperBandValue
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Asymmetrical RSI

by everget
947 stars

Asymmetrical RSI is an indicator that computes a custom relative strength index from the rate of change of a user-selected source. It plots the resulting ARSI line in a separate pane with color coding that turns green above the overbought level and red below t

Indicator v4 Oscillators & momentum
Updated 12 days ago · GPL-3.0 GitHub repository of Asymmetrical RSI

This indicator calculates momentum setups based on the Relative Strength Index (RSI) and plots in a separate pane. It offers multiple scanning modes such as Continuous Break, Continuous Retracement, Flip Break, Flip Retracement, and both regular and hidden div

Indicator v6 Oscillators & momentumDivergence Repaints
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - RSI Directional Momentum Indicator

Beep Boop

by magic8bot
409 stars

This indicator calculates a modified MACD oscillator and signal line alongside a trend EMA filter, plotting the output as a stylized column histogram in a separate pane. Instead of plotting true MACD distance, it quantifies positive and negative histogram mome

Indicator v4 Oscillators & momentumTrend
Updated 3 years ago · MIT GitHub repository of Beep Boop
261 stars

This indicator demonstrates an experimental graph-style scatter visualization within a separate pane using Pine Script arrays. It tracks two features across recent bars: the single-bar price change and a scaled 14-period Relative Strength Index. Values are loa

Indicator v4 Oscillators & momentum
Updated 4 years ago · None stated GitHub repository of Example: Graph Style - 4th Dimension RSI
228 stars

This indicator detects a Bollinger Band squeeze when the bands sit inside Keltner Channels, marking low volatility. It plots red dots during a squeeze and green dots when the bands are outside, in a separate pane. An optional histogram shows momentum as the cl

Indicator v6 Volatility & bandsOscillators & momentum
Updated 3 months ago · None stated GitHub repository of Bollinger Band Squeeze Detector

More Oscillators & momentum scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers