Stochastic oscillator: fast, slow and full
Understand the two smoothing stages before comparing settings or signals.
The stochastic oscillator measures where the close sits within a recent high-low range. Fast, slow and full versions use the same raw calculation with different smoothing choices. A reading above 80 can persist throughout an uptrend; it does not establish that a reversal is due. This guide includes a configurable TradingView indicator with alerts confirmed at bar close.
What does the stochastic indicator measure?
The stochastic oscillator indicator expresses the close's position in a rolling price range on a scale from 0 to 100. Raw %K measures that position; the displayed %K may be smoothed, and %D averages the displayed %K. A value of 80 is a relative position, not an 80% chance of a price move.
To add it on TradingView, open Indicators, search Stochastic and choose the built-in study. Check the named inputs: %K Length, %K Smoothing and %D Smoothing. TradingView's STOCH documentation lists 14, 3 and 3 respectively. These are bars at the calculation timeframe, not always days.
Stochastic RSI applies a range calculation to RSI values instead of price. Select the ordinary Stochastic study for the rules below. Browse the TradingView indicators guide for other studies, or use the stochastic oscillator calculator to inspect a separate calculation workflow.
Why Traders Use This Indicator
- Locate the close within its recent trading range.
- Define repeatable line-crossing and threshold-crossing events.
- Compare selected price swings with oscillator readings to examine divergence.
| Parameter | Default | Description |
|---|---|---|
| %K length | 14 | Bars used to find the highest high and lowest low. This is the range window, not the signal-line average. |
| %K smoothing | 3 in this example | SMA length applied to raw %K. Set 1 for fast %K; 3 produces the conventional slow %K. Pineify visual STOCH starts at 1, so change it when matching this example. |
| %D smoothing | 3 | SMA length applied to displayed %K. Changing it alters %D without changing %K. |
| Upper / lower levels | 80 / 20 | Reference thresholds used for the zone-exit alerts. They do not change the oscillator calculation. |
Formula and the fast, slow and full versions
For a lookback of n bars, let H be the highest high and L the lowest low, including the current bar. Then raw %K = 100 × (Close - L) / (H - L). Apply %K = SMA(raw %K, kSmooth), followed by %D = SMA(%K, dSmooth).
Illustrative arithmetic: H = 250, L = 230 and Close = 245 gives raw %K = 75. If the latest three raw readings are 45, 60 and 75, a three-bar %K average is 60. %D then averages displayed %K readings, not those raw readings again. When H equals L the fraction is undefined; the script retains ta.stoch behavior and blocks events without a valid current and previous range.
Use named settings, because platforms order them differently
- Fast: raw %K and a three-bar SMA signal line. In this page's order of length / K smoothing / D smoothing, that is 14/1/3.
- Slow: apply a three-bar SMA to raw %K, then another three-bar SMA to form %D: 14/3/3. Slow %K therefore equals fast %D when the range length and data match.
- Full: expose the range length and both smoothing lengths. It can reproduce fast or slow settings; it is not a separate price formula.
StockCharts' official fast, slow and full comparison documents these conventions. More smoothing changes the timing and frequency of crossings, so a setting cannot be judged by the visual smoothness alone. Using EMA instead of SMA creates a different variant.
Signal Interpretation
Line crosses, threshold crosses and divergence are separate rules
A bullish line cross requires previous %K at or below previous %D and current %K above current %D. It can occur anywhere in the scale. An oversold exit instead requires previous %K at or below 20 and current %K above 20. Neither condition implies the other.
Hypothetical sequence: %K changes from 12 to 18 while %D changes from 15 to 16. That is an upward line cross, but %K has not exited below-20 territory. With the next readings at %K = 23 and %D = 19, the threshold exit occurs without a new line cross. The code exposes separate alerts for these events.
Regular bullish divergence pairs a lower price low with a higher oscillator low; bearish divergence pairs a higher price high with a lower oscillator high. Choose either %K or %D and use the same swing-pairing rule throughout. The script below does not detect divergence. A pivot method using three bars to the right only confirms the pivot three bars later; a marker placed back at the pivot must not be treated as available on that earlier bar. See TradingView's repainting documentation.
Why repeated overbought readings can fail as sell signals
During a strong advance, successive closes can remain near the top of the rolling range even as that range moves higher. %K can stay above 80 or cross below it briefly before returning. Fidelity's Fast Stochastic guide describes persistent extremes and the limits of reversal signals in strong trends. Repeatedly selling that state can oppose the continuing trend.
The plotted lines update on an open chart bar. The example waits for barstate.isconfirmed before marking an event or enabling its alert. Create the chosen named condition in TradingView's alert dialog with Once Per Bar Close. An existing alert retains its saved script and inputs, so recreate it after relevant changes. TradingView's alert documentation explains this setup. Confirmation delays the signal until close; it does not establish profitability.
Combining with Other Indicators
A price moving average can define which direction a rule permits. For an illustrative long-only test, require Close above a 200-bar EMA when %K crosses upward through 20. The EMA filter is not included in the example code, and 200 is a test input rather than an optimum. Compare filtered and unfiltered events using identical market data.
Adding RSI adds another transformation of price; agreement does not provide independent evidence of future returns. Before turning any event into a strategy, define entry timing, exit, position size and costs. The Strategy Optimizer workflow below applies only after those strategy rules exist.
Writing Pine Script Manually
Challenges of Manual Coding
Match the chart timeframe, OHLC data and both SMA stages before comparing two implementations.
Evaluate crossing functions on every bar, then gate their results with confirmation and data validity.
Keep a line cross, a zone exit and a divergence detector separate in code and alert names.
//@version=6
indicator("Stochastic: confirmed events", shorttitle="Stoch events", overlay=false, precision=2)
kLength = input.int(14, "%K length", minval=1)
kSmooth = input.int(3, "%K smoothing", minval=1)
dSmooth = input.int(3, "%D smoothing", minval=1)
upperLevel = input.float(80, "Upper level", minval=50.1, maxval=100)
lowerLevel = input.float(20, "Lower level", minval=0, maxval=49.9)
rawK = ta.stoch(close, high, low, kLength)
k = ta.sma(rawK, kSmooth)
d = ta.sma(k, dSmooth)
priceRange = ta.highest(high, kLength) - ta.lowest(low, kLength)
// Evaluate all crossing functions before applying the confirmation gate.
lineUp = ta.crossover(k, d)
lineDown = ta.crossunder(k, d)
exitLow = ta.crossover(k, lowerLevel)
exitHigh = ta.crossunder(k, upperLevel)
ready = priceRange > 0 and priceRange[1] > 0 and not na(k) and not na(k[1]) and not na(d) and not na(d[1])
confirmed = barstate.isconfirmed and ready
plot(k, "%K", color=#2962FF, linewidth=2)
plot(d, "%D", color=#FF6D00, linewidth=2)
hline(upperLevel, "Upper level", color=color.gray)
hline(lowerLevel, "Lower level", color=color.gray)
hline(50, "Midpoint", color=color.new(color.gray, 60))
plotshape(confirmed and exitLow, title="Oversold exit", text="Exit low", style=shape.triangleup, location=location.bottom, color=color.green, size=size.tiny)
plotshape(confirmed and exitHigh, title="Overbought exit", text="Exit high", style=shape.triangledown, location=location.top, color=color.red, size=size.tiny)
alertcondition(confirmed and lineUp, title="%K crossed above %D", message="Confirmed Stochastic line cross up on {{ticker}}")
alertcondition(confirmed and lineDown, title="%K crossed below %D", message="Confirmed Stochastic line cross down on {{ticker}}")
alertcondition(confirmed and exitLow, title="%K exited oversold", message="Confirmed Stochastic exit above lower level on {{ticker}}")
alertcondition(confirmed and exitHigh, title="%K exited overbought", message="Confirmed Stochastic exit below upper level on {{ticker}}")Maintenance Note: This indicator uses chart OHLC data and SMA smoothing. It plots zone-exit markers and exposes four separate alert conditions. It does not detect divergence, request another timeframe, place orders or calculate strategy returns. Review any later additions separately.
Build with Pineify Visual Editor
Pineify lets you configure supported indicators and export Pine Script. Available settings and plan requirements vary by indicator. Compare the generated rules with the example before using its signals.
| Feature | Manual Pine Script | Pineify Visual Editor |
|---|---|---|
| Calculation settings | The example starts at 14/3/3 and exposes all three lengths. | The visual STOCH module exposes the same three lengths, with defaults of 14/1/3. |
| Outputs and conditions | Edit the four named events and their bar-close gate in the code. | Use the K and D module outputs in supported conditions; inspect exported logic for the intended confirmation rule. |
| Validation | Compare closed-bar values and test each selected alert. | Generated scripts need the same checks. Syntax validation does not prove the trading rule works. |
Configure K length, K smoothing and D smoothing in the visual STOCH module.
Use its K and D outputs when composing supported indicator conditions.
Ask the AI Coding Agent for custom rules, then inspect and test the generated code.
Step-by-Step Tutorial
Choose the visual STOCH module
Open the Visual Pine Script Editor and add Stochastic Oscillator. Check current plan requirements for the product features you need.
Set each smoothing stage
For the slow example, use K Length 14, K Smoothing 3 and D Smoothing 3. The visual module starts with K Smoothing 1.
Specify one event precisely
Choose a K/D cross or a threshold exit and decide whether it must wait for the chart bar to close. Use the AI Coding Agent for custom logic beyond the supported visual controls.
Verify the exported script
Compare closed-bar K and D values against the built-in Stochastic with matching settings. Inspect alert conditions before creating the corresponding TradingView alert.
Trading Strategies & Pro Tips
A zone-exit experiment
Illustrative protocol: enter long after a confirmed K cross above 20, exit after a confirmed cross below 80, and define the next-bar fill, position size and protective stop separately. This is a rule to test, not a recommendation or a result produced by the indicator.
Pro Tip: A new downtrend can keep K below 20 while price falls. A bounce through 20 can also fail before reaching 80; an exit rule cannot rely on the upper threshold alone.
Compare smoothing under fixed assumptions
Once you have a strategy with orders, compare 14/1/3 with 14/3/3 on the same symbol, timeframe and date range. Record trade count and drawdown alongside net results. Keep a separate period out of the parameter selection process.
Pro Tip: Pineify Strategy Optimizer can vary exposed strategy inputs. Set commission and slippage in strategy properties, repeat the comparison under another cost assumption, and retain those assumptions with each result. It cannot backtest this indicator as supplied.
Common Mistakes to Avoid
- Treating every reading above 80 as a short entry in a rising market.
- Comparing a 14/1/3 visual module with a 14/3/3 built-in study and blaming the formula.
- Switching between K and D when selecting the most attractive divergence after the fact.
- Treating a pivot marker drawn on an earlier bar as a signal known at that time.
- Ranking settings without accounting for transaction costs or checking a separate period.
Frequently Asked Questions
Build your Stochastic rules in Pineify
- Configure the visual module with explicit K and D smoothing.
- Describe custom event logic to the AI Coding Agent.
- Review the output and validate it on your TradingView chart.
Disclaimer: Trading involves significant risk. The indicators, code, and strategies provided are for educational purposes only and do not constitute financial advice. Past performance is not indicative of future results.