Skip to main content

Stochastic Oscillator

What is the stochastic oscillator?​

The stochastic oscillator (also called stochastics) is a momentum indicator that measures where the latest close sits within the high–low range of the last N bars, on a scale from 0 to 100. Its main line, %K, is 100 at the top of that range and 0 at the bottom; %D is a moving average of %K.

A dark navy two-pane chart: about a year of simulated daily candles on top, moving through a sideways range, a steady uptrend, a downtrend and a second range, and below it the stochastic oscillator's %K and %D lines on a 0 to 100 scale, with the zone above 80 shaded red and the zone below 20 shaded green. The lines stay mostly above 80 during the uptrend and mostly below 20 during the downtrend. A yellow box on the price chart marks the high-low range of the last 14 bars.

Simulated daily candles with a slow 14,3,3 stochastic oscillator below them: %K and %D swing across the 0 to 100 scale in the ranges and stay near one end in the trends. Try the interactive version.

Key takeaways
  • %K measures where the close sits in the N-bar range: 100 at the highest high, 0 at the lowest low.
  • %D is a moving average of %K. Fast, slow and full stochastics differ only in how much they smooth.
  • 14,3,3 is a 14-bar look-back with two 3-bar averages, and it is a common default.
  • Above 80 and below 20 are conventional zones. In a strong trend the oscillator can stay in one of them for weeks.
  • Crossovers and divergence are ways traders read the lines, not rules that hold every time.

This page explains how the stochastic oscillator is calculated, read and drawn. It is not investment advice.

What does the stochastic oscillator measure?​

It measures the close's position inside the recent trading range, as a percentage of that range.

Take a 14-day range from a low of 90 to a high of 110. A close of 108 is 18 points above the low in a 20-point range, so %K is 90: the market finished near the top of where it has traded for two weeks. A close of 92 gives a %K of 10, near the bottom.

The idea behind it is that in a rising market, closes tend to land near the top of each bar's range, and in a falling market near the bottom. When closes start to slip away from the extreme while the price is still trending, momentum may be fading. The oscillator turns that position into a number that can be compared over time and across instruments, because it is always between 0 and 100 whatever the price.

It uses three inputs from every bar: the high, the low and the close. The open and volume play no part.

The indicator is usually credited to George Lane, a US technical analyst and educator, in the 1950s; he described %K and %D in his article "Lane's Stochastics" (1984). Despite its name, it is a fixed calculation on past prices and has no link with stochastic processes in probability theory.

How to calculate the stochastic oscillator​

Raw %K places the close in the N-bar high–low range, and %D is a short moving average of %K.

With nn as the look-back (14 by default), HnH_n the highest high and LnL_n the lowest low over the last nn bars including the current one, and CC the current close:

%Kraw=100×C−LnHn−Ln\%K_{\text{raw}} = 100 \times \frac{C - L_n}{H_n - L_n} %K=SMAk(%Kraw)%D=SMAd(%K)\%K = \text{SMA}_{k}\left(\%K_{\text{raw}}\right) \qquad \%D = \text{SMA}_{d}\left(\%K\right)

where SMAm\text{SMA}_m is the simple moving average of the last mm values. With k=1k = 1, %K is the raw value; that is the fast stochastic. The steps on each bar are:

  1. Look back over the last nn bars, including this one, and find the highest high and the lowest low.
  2. Subtract the lowest low from the close, divide by the range and multiply by 100. That is raw %K.
  3. Average the last kk raw values to get %K, then the last dd values of %K to get %D.

A few details vary between charting packages:

  • Flat range. If every bar in the window has the same high and low, the range is zero and the formula divides by zero. Software returns 0, 50 or the previous value. The demo on this page uses 50, the middle of the scale.
  • Warm-up. Raw %K needs nn bars, %K needs k−1k - 1 more and %D another d−1d - 1. With 14,3,3, the first %D value is on bar 18.
  • Kind of average. Most packages use a simple moving average for both steps; some offer an exponential one, which changes the values.

Worked example: 12 bars with a 5-bar look-back​

A 5-bar look-back keeps the table short; the steps are the same for 14. Fast %K is raw %K, its 3-bar average is the fast %D (which is also the slow %K), and the 3-bar average of that is the slow %D.

BarHighLowClose5-bar highest high5-bar lowest lowFast %KFast %D = slow %KSlow %D
151.050.050.6–––––
251.650.651.4–––––
352.451.251.9–––––
452.050.951.3–––––
553.151.952.953.150.093.5––
653.852.653.453.850.687.5––
753.552.452.653.850.958.679.9–
852.651.351.653.850.924.156.8–
951.950.851.153.850.810.030.955.9
1051.250.250.653.850.211.115.134.3
1151.850.651.653.550.242.421.222.4
1252.951.552.752.950.292.648.728.3
  • On bar 12 the window is bars 8 to 12. The highest high is 52.9 (bar 12) and the lowest low 50.2 (bar 10), a range of 2.7. The close of 52.7 is 2.5 above the low, so fast %K = 100 × 2.5 ÷ 2.7 = 92.6.
  • On bar 9 the close of 51.1 is only 0.3 above a 50.8 low in a 3.0 range, so fast %K is 10.0, in the oversold zone below 20.
  • Fast %D on bar 7 is (93.5 + 87.5 + 58.6) ÷ 3 = 79.9.
  • Fast %K is below fast %D on bar 10 (11.1 against 15.1) and above it on bar 11 (42.4 against 21.2): a bullish crossover.
  • The slow %D lags well behind: on bar 12 it is still 28.3 while fast %K is back above 90.

The numbers come from the same function the live demo uses, so the demo set to look-back 5, %K smoothing 1 and %D smoothing 3 on these bars would give the same values.

Fast, slow and full stochastic​

The three versions use the same raw %K and differ only in how many times it is averaged before it is plotted.

VersionUsual settingsPlotted %KPlotted %DSmoothing
Fast14,3Raw %K3-bar average of raw %KNone on %K
Slow14,33-bar average of raw %K (the fast %D)3-bar average of slow %KFixed: 3 on %K, then 3 on %D
Full14,3,3kk-bar average of raw %Kdd-bar average of full %KBoth set by the user
  • The fast stochastic reacts first and crosses most often. Raw %K can jump from near 0 to near 100 in a single bar when one bar closes at the other end of the range.
  • The slow stochastic smooths out the fast version's whipsaws. Its %K is the fast %D, so the lines turn about a bar later and cross less often.
  • The full stochastic is the general form. Full 14,1,3 is the fast stochastic and full 14,3,3 is the slow one, so the full version gives more settings without a new calculation.

Names vary between texts and packages. Older texts describe three lines, %K, %D and a further average of %D called "%D-slow"; the slow stochastic plots the last two and calls them slow %K and slow %D. Some packages label the fast stochastic simply "Stochastic", others mean the slow one by the same word, and the second number in "14,3" can be the %D length or the %K smoothing. Check which lines a chart draws before comparing its values with another's.

In the demo's simulated year, the fast 14,3 lines cross each other 104 times and the slow 14,3 lines 62 times.

Where does 14,3,3 come from?​

The 14-bar look-back with two 3-bar averages is a common default in charting software today; it is a convention, and nothing in the maths singles out 14. Published examples use other look-backs too, and 5, 9 and 14 bars are all common. The look-back is counted in bars of the chart's own timeframe, so 14 is about three weeks on a daily chart and 70 minutes on a 5-minute chart.

A shorter look-back makes the range narrower, so the close reaches the extremes more often and the oscillator swings harder. A longer one gives a wider range and fewer readings near 0 or 100. In the demo, raising the look-back from 5 to 30 with slow smoothing cuts the share of bars in the first range with %K above 80 or below 20 only a little, but it lifts the share of uptrend bars above 80 from 49% to 73%.

How to read the stochastic oscillator​

Read the level first, then the crossovers, then any divergence from price, and treat each as a description of momentum so far.

Anatomy of the stochastic oscillator. Top: twelve price bars, each a vertical high-low line with a tick for the close; a dashed box marks the 5-bar window from bar 8 to bar 12, from a lowest low of 50.20 to a highest high of 52.90, and a bracket shows the close of 52.70 sitting 2.50 above the low, so %K equals 2.50 divided by 2.70 times 100, or 92.6. Bottom: fast %K and its 3-bar average %D on a 0 to 100 scale, with the overbought zone above 80 shaded red and the oversold zone below 20 shaded green; %K is 93.5 on bar 5, falls to 10.0 on bar 9, and crosses above %D between bars 10 and 11.

Overbought and oversold: the 80 and 20 levels​

Above 80 is conventionally called overbought and below 20 oversold. The words describe position: a reading of 90 says the close is near the top of the recent range, and nothing about whether the price is too high. Some traders use 70 and 30 to get more readings in the zones, or 90 and 10 to get fewer. A common reading is to wait for the oscillator to leave a zone (fall back below 80, or rise back above 20) rather than act while it is inside it.

%K and %D crossovers​

%K crossing above %D means the latest readings have moved above their recent average: the close is climbing within its range. %K crossing below %D is the opposite. Crossovers happen often, so traders tend to give more weight to those that happen inside a zone, such as a cross upwards below 20. The worked example has one on bar 11.

Divergence between price and the oscillator​

A bullish divergence is a lower low in price with a higher low in the oscillator: the price reached a new low, but the close finished higher in its range than at the previous low. A bearish divergence is a higher high in price with a lower high in the oscillator. Both suggest the move is losing momentum. They can last a long time before the price turns, and many never lead to a reversal, so they are usually read alongside the trend and support or resistance levels.

Why the stochastic stays near 100 in a strong trend​

In a steady trend each new bar tends to close near the edge of a range that keeps moving with it, so %K stays near 100 in an uptrend and near 0 in a downtrend.

In an uptrend, the 14-bar highest high is usually a recent bar, and closes land near it day after day. %K stays high and "overbought" can last for weeks while the price keeps rising. Selling every time %K crosses 80 in that market would mean selling all the way up. The same happens in reverse in a downtrend.

The simulated data in the demo shows this. With the slow 14,3,3 setting and 80/20 zones:

Phase in the demoBars%K above 80%K below 20
First range10014%19%
Uptrend7069%0%
Downtrend500%74%
Second range4010%5%

The oscillator is in a zone on about a third of the bars in the first range, swinging between them, and on most bars of each trend, stuck at one end. The usual zone readings assume a range-bound market. In a trend, a reading at the extreme tells you the trend is still running; a fall from 100 that fails to reach 20 before turning back up is how a pullback within an uptrend often looks.

Stochastic vs RSI vs Stochastic RSI​

All three are bounded momentum oscillators, but they measure different things and suit different jobs.

Stochastic oscillatorRSI (relative strength index)Stochastic RSI
What it measuresClose's position in the N-bar high–low rangeAverage size of up closes against down closes over N barsRSI's position in its own N-bar range
InputsHigh, low and closeClose onlyClose only, through RSI
Scale and usual zones0 to 100; 80 and 200 to 100; 70 and 300 to 1 (or 0 to 100); 0.8 and 0.2
Introduced byGeorge Lane (usually credited, 1950s; article 1984)J. Welles Wilder Jr. (1978)Tushar Chande and Stanley Kroll (1994)
BehaviourQuick; reaches both ends oftenSmoother; extremes are rarerMost sensitive; often sits at 0 or 1
Choose it whenYou care where price closes within its bars' range, including the wicksYou want the strength of closing moves, less affected by single-bar spikesYou want RSI turns to show sooner, and accept many more signals

Stochastic RSI uses the same formula as raw %K with RSI values in place of highs, lows and closes: (RSI − lowest RSI) ÷ (highest RSI − lowest RSI) over the look-back. Because RSI often moves within a narrow band, stretching that band to fill 0 to 1 makes the result swing hard. A long wick changes the stochastic but not RSI, since RSI ignores highs and lows.

Common stochastic oscillator mistakes​

Most mistakes come from using the zones as signals in the wrong market, or comparing lines that were calculated differently.

  • Selling every reading above 80. In a trend the oscillator stays in the zone (see the table above). Check the trend first.
  • Comparing two charts with different versions. A fast and a slow stochastic with the "same" 14,3 settings plot different lines. So do packages that use different averages or handle a flat range differently.
  • Reading the current bar as final. Until a bar closes, its high, low and close keep changing, so %K for the latest bar moves around and can cross %D and back again.
  • Feeding it closes only. Without real highs and lows, the range is built from closes and every reading changes. Data with no intraday range, such as a daily close-only series, needs a different indicator or must say what it used.
  • Ignoring the warm-up. The first values need n+k+d−2n + k + d - 2 bars of history. Start the calculation earlier than the chart's first visible bar, or the left edge shows nothing or a misleading value.
  • Tuning the settings until a backtest looks good. Trying many look-backs and zone levels on past data finds one that fits by chance. Park and Irwin's review of 95 studies of technical trading rules found that most reported profits, at least until the early 1990s, but that most also had problems in how they were tested, such as data snooping, choosing rules after the fact, and difficulty estimating risk and trading costs.
  • Treating divergence as a timing signal. A divergence can persist through several further highs or lows before anything happens, or never resolve.

How to plot a stochastic oscillator in JavaScript, React or Angular​

The demo below simulates 260 daily candles in four phases (a 100-bar range, a 70-bar uptrend, a 50-bar downtrend and a 40-bar range) and recomputes raw %K, %K, %D, the shaded zones and the readout each time you change a setting. SciChart.js draws the candles and both oscillator lines with WebGL and WebGPU; the stochastic maths is plain JavaScript.

Set Look-back N, %K smoothing and %D smoothing to build any full stochastic, or press a preset: Fast 14,3 turns the %K smoothing off, and Slow 14,3 and Full 14,3,3 both select 14,3,3 and light up together because they are the same lines. Zones moves the shaded levels between 80/20, 70/30 and 90/10, and the readout gives the share of each phase's bars in each zone. With Show the N-bar high–low range ticked, hover over any bar to see the window behind its %K drawn on the price chart, with its highest high and lowest low; the readout shows that bar's close, range, raw %K, %K and %D. Scroll to zoom, drag to pan, and double-click to reset; both charts move together.

Here is the code for this demo. The stochastic calculation and the time-in-zone shares are plain JavaScript; SciChart.js draws the candles, the two lines, the zones and the hover window. The React and Angular versions below draw the oscillator pane from your own candles.

// A candlestick chart with a stochastic oscillator (%K and %D) in a pane below it, with SciChart.js
const {
SciChartSurface,
SciChartVerticalGroup,
NumericAxis,
NumberRange,
EAutoRange,
EXyDirection,
ECoordinateMode,
EHorizontalAnchorPoint,
EVerticalAnchorPoint,
ELabelPlacement,
OhlcDataSeries,
XyDataSeries,
FastCandlestickRenderableSeries,
FastLineRenderableSeries,
BoxAnnotation,
TextAnnotation,
HorizontalLineAnnotation,
SciChartJsNavyTheme,
LegendModifier,
ELegendPlacement,
ELegendOrientation,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
CustomChartModifier2D,
translateFromCanvasToSeriesViewRect,
Thickness
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// --- Stochastic maths (plain JavaScript) ---
// Simple moving average over the last m values; NaN until m values exist. m = 1 returns the values unchanged.
function sma(values, m) {
return values.map((_, i) => {
if (i < m - 1) return NaN;
let sum = 0;
for (let j = i - m + 1; j <= i; j++) sum += values[j];
return sum / m; // NaN if any value in the window is NaN
});
}

// The full stochastic: raw %K over n bars, %K = raw %K smoothed over kSmoothing bars, %D = %K smoothed over dSmoothing.
// kSmoothing = 1 gives the fast stochastic; kSmoothing = 3 gives the slow stochastic.
function stochastic(high, low, close, n, kSmoothing, dSmoothing) {
const highestHigh = [];
const lowestLow = [];
const rawK = [];
for (let i = 0; i < close.length; i++) {
if (i < n - 1) {
highestHigh.push(NaN);
lowestLow.push(NaN);
rawK.push(NaN);
continue;
}
let hh = -Infinity;
let ll = Infinity;
for (let j = i - n + 1; j <= i; j++) {
hh = Math.max(hh, high[j]);
ll = Math.min(ll, low[j]);
}
highestHigh.push(hh);
lowestLow.push(ll);
// where the close sits in the n-bar range, 0 to 100; a flat range (high = low) is taken as 50
rawK.push(hh > ll ? (100 * (close[i] - ll)) / (hh - ll) : 50);
}
const k = sma(rawK, kSmoothing);
const d = sma(k, dSmoothing);
return { highestHigh, lowestLow, rawK, k, d };
}

// Share of each phase's bars with %K above the upper zone and below the lower zone
function timeInZones(k, upper, lower) {
return PHASES.map((phase) => {
let above = 0;
let below = 0;
let count = 0;
for (let i = phase.from; i < phase.to; i++) {
if (!Number.isFinite(k[i])) continue;
count++;
if (k[i] > upper) above++;
if (k[i] < lower) below++;
}
return { name: phase.name, above: above / count, below: below / count };
});
}

// --- The charts ---
const theme = new SciChartJsNavyTheme();
const COLOURS = { up: "#26a69a", down: "#ef5350", k: "#50C7E0", d: "#F48420", range: "#F6E05E" };
const fmtDate = (index) => {
const t = dates[Math.round(index)];
return t === undefined ? "" : new Date(t * 1000).toLocaleDateString("en-GB", { day: "numeric", month: "short", timeZone: "UTC" });
};
// x is the bar number (no weekend gaps); the labels show each bar's date
const makeXAxis = (wasmContext) => {
const axis = new NumericAxis(wasmContext, { growBy: new NumberRange(0.01, 0.03) });
axis.labelProvider.formatLabel = fmtDate;
axis.labelProvider.formatCursorLabel = fmtDate;
return axis;
};
const modifiers = () => [
new CursorModifier({ showTooltip: false, modifierGroup: "stochastic" }),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier({ xyDirection: EXyDirection.XDirection }),
new LegendModifier({ placement: ELegendPlacement.TopLeft, orientation: ELegendOrientation.Horizontal, showCheckboxes: false })
];

// 1. Price: daily candles
const top = await SciChartSurface.create(ui.priceDiv, { theme });
const priceX = makeXAxis(top.wasmContext);
top.sciChartSurface.xAxes.add(priceX);
top.sciChartSurface.yAxes.add(
new NumericAxis(top.wasmContext, { axisTitle: "Price", autoRange: EAutoRange.Always, growBy: new NumberRange(0.05, 0.3), labelPrecision: 0 })
);
const barNumbers = dates.map((_, i) => i);
top.sciChartSurface.renderableSeries.add(
new FastCandlestickRenderableSeries(top.wasmContext, {
dataSeries: new OhlcDataSeries(top.wasmContext, {
xValues: barNumbers,
openValues: candles.open,
highValues: candles.high,
lowValues: candles.low,
closeValues: candles.close,
dataSeriesName: "Price (simulated daily candles)"
}),
brushUp: COLOURS.up,
brushDown: COLOURS.down,
strokeUp: COLOURS.up,
strokeDown: COLOURS.down
})
);
// Label the phases of the simulation along the top of the price chart, and shade the trends
for (const phase of PHASES) {
top.sciChartSurface.annotations.add(
new TextAnnotation({
x1: (phase.from + phase.to - 1) / 2, // centred on the phase, below the legend
y1: 0.12,
yCoordinateMode: ECoordinateMode.Relative,
text: phase.name,
fontSize: 13,
textColor: "#C8D3E6",
horizontalAnchorPoint: EHorizontalAnchorPoint.Center,
verticalAnchorPoint: EVerticalAnchorPoint.Top
})
);
if (phase.name !== "Range") {
top.sciChartSurface.annotations.add(
new BoxAnnotation({ x1: phase.from - 0.5, x2: phase.to - 0.5, yCoordinateMode: ECoordinateMode.Relative, y1: 0, y2: 1, fill: "#FFFFFF0D", strokeThickness: 0 })
);
}
}
// The N-bar window behind the selected %K value: a box from the lowest low to the highest high, with labels
const rangeBox = new BoxAnnotation({ x1: 0, x2: 1, y1: 0, y2: 1, fill: COLOURS.range + "22", stroke: COLOURS.range, strokeThickness: 1 });
const label = (vertical) =>
new TextAnnotation({
x1: 0,
y1: 0,
text: "",
fontSize: 12,
textColor: "#FFFFFF",
background: "#14233CCC",
padding: new Thickness(2, 4, 2, 4),
horizontalAnchorPoint: EHorizontalAnchorPoint.Right,
verticalAnchorPoint: vertical
});
const highLabel = label(EVerticalAnchorPoint.Bottom);
const lowLabel = label(EVerticalAnchorPoint.Top);
top.sciChartSurface.annotations.add(rangeBox, highLabel, lowLabel);
top.sciChartSurface.chartModifiers.add(...modifiers());

// 2. Oscillator: %K and %D on a fixed 0 to 100 scale, with the overbought and oversold zones shaded
const bottom = await SciChartSurface.create(ui.oscillatorDiv, { theme });
const oscillatorX = makeXAxis(bottom.wasmContext);
bottom.sciChartSurface.xAxes.add(oscillatorX);
bottom.sciChartSurface.yAxes.add(
new NumericAxis(bottom.wasmContext, { axisTitle: "Stochastic", autoRange: EAutoRange.Never, visibleRange: new NumberRange(-4, 104), labelPrecision: 0 })
);
const kData = new XyDataSeries(bottom.wasmContext, { dataSeriesName: "%K", isSorted: true, containsNaN: true });
const dData = new XyDataSeries(bottom.wasmContext, { dataSeriesName: "%D", isSorted: true, containsNaN: true });
bottom.sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(bottom.wasmContext, { dataSeries: kData, stroke: COLOURS.k, strokeThickness: 2 }),
new FastLineRenderableSeries(bottom.wasmContext, { dataSeries: dData, stroke: COLOURS.d, strokeThickness: 2, strokeDashArray: [5, 3] })
);
const zone = (fill) => new BoxAnnotation({ xCoordinateMode: ECoordinateMode.Relative, x1: 0, x2: 1, y1: 0, y2: 0, fill, strokeThickness: 0 });
const upperZone = zone("#EF535033");
const lowerZone = zone("#26A69A33");
const level = () =>
new HorizontalLineAnnotation({ y1: 0, stroke: "#C8D3E6", strokeThickness: 1, strokeDashArray: [4, 4], showLabel: true, labelPlacement: ELabelPlacement.Axis, axisLabelFill: "#C8D3E6" });
const upperLine = level();
const lowerLine = level();
bottom.sciChartSurface.annotations.add(upperZone, lowerZone, upperLine, lowerLine);
bottom.sciChartSurface.chartModifiers.add(...modifiers());

// Line up the y-axes and keep both charts on the same bars when you zoom or pan either one
const group = new SciChartVerticalGroup();
group.addSurfaceToGroup(top.sciChartSurface);
group.addSurfaceToGroup(bottom.sciChartSurface);
const link = (from, to) =>
from.visibleRangeChanged.subscribe(({ visibleRange }) => {
if (!to.visibleRange.equals(visibleRange)) to.visibleRange = visibleRange;
});
link(priceX, oscillatorX);
link(oscillatorX, priceX);

// Hovering either chart selects a bar; leaving the charts selects the latest bar again
class HoverBarModifier extends CustomChartModifier2D {
onBar = (index) => {};
modifierMouseMove(args) {
super.modifierMouseMove(args);
const point = translateFromCanvasToSeriesViewRect(args.mousePoint, this.parentSurface.seriesViewRect);
if (!point) return this.onBar(-1);
const x = this.parentSurface.xAxes.get(0).getCurrentCoordinateCalculator().getDataValue(point.x);
this.onBar(Math.max(0, Math.min(BARS - 1, Math.round(x))));
}
modifierMouseLeave(args) {
super.modifierMouseLeave(args);
this.onBar(-1);
}
}

// --- The controls: recompute, redraw and explain the selected bar ---
let result = null;
let selected = -1; // -1: the latest bar
const settings = () => ({ n: Number(ui.lookback.value), kS: Number(ui.kSmoothing.value), dS: Number(ui.dSmoothing.value) });
const name = ({ n, kS, dS }) => (kS === 1 ? `Fast ${n},${dS}` : kS === 3 && dS === 3 ? `Slow ${n},3 (full ${n},3,3)` : `Full ${n},${kS},${dS}`);
const one = (value) => (Number.isFinite(value) ? value.toFixed(1) : "–");
const percent = (share) => `${Math.round(share * 100)}%`;

function showBar() {
const i = selected >= 0 ? selected : BARS - 1;
const { n } = settings();
const hh = result.highestHigh[i];
const ll = result.lowestLow[i];
const hasRange = Number.isFinite(hh);
const visible = ui.range.checked && hasRange;
for (const annotation of [rangeBox, highLabel, lowLabel]) annotation.isHidden = !visible;
if (hasRange) {
rangeBox.x1 = i - n + 1 - 0.5;
rangeBox.x2 = i + 0.5;
rangeBox.y1 = ll;
rangeBox.y2 = hh;
highLabel.x1 = lowLabel.x1 = i - n + 1 - 0.5;
highLabel.y1 = hh;
lowLabel.y1 = ll;
highLabel.text = `Highest high ${hh.toFixed(2)}`;
lowLabel.text = `Lowest low ${ll.toFixed(2)}`;
}
const upper = Number(ui.zones.value);
const shares = timeInZones(result.k, upper, 100 - upper)
.map((s) => `${s.name}: ${percent(s.above)} above ${upper}, ${percent(s.below)} below ${100 - upper}`)
.join(" · ");
const where = selected >= 0 ? "Hovered bar" : "Latest bar";
ui.readout.innerHTML =
`<div><strong>${name(settings())}</strong> · ${where}, ${fmtDate(i)}: close ${candles.close[i].toFixed(2)}, ` +
(hasRange
? `${n}-bar highest high ${hh.toFixed(2)}, lowest low ${ll.toFixed(2)}, raw %K ${one(result.rawK[i])}, ` +
`<span style="color:${COLOURS.k}">%K ${one(result.k[i])}</span>, <span style="color:${COLOURS.d}">%D ${one(result.d[i])}</span>`
: `not enough bars yet for a ${n}-bar range`) +
`</div><div>Share of bars with %K in the zones · ${shares}</div>`;
}

function update() {
const s = settings();
ui.lookbackOut.textContent = `${s.n} bars`;
ui.kSmoothingOut.textContent = s.kS === 1 ? "1 (none)" : `${s.kS}`;
ui.dSmoothingOut.textContent = `${s.dS}`;
for (const [key, button] of Object.entries(ui.presets)) {
const on = s.n === 14 && s.dS === 3 && (key === "fast" ? s.kS === 1 : s.kS === 3);
button.setAttribute("aria-pressed", String(on));
button.style.background = on ? "#50C7E0" : "transparent";
button.style.color = on ? "#14233C" : "#ffffff";
}
result = stochastic(candles.high, candles.low, candles.close, s.n, s.kS, s.dS);
kData.clear();
kData.appendRange(barNumbers, result.k);
dData.clear();
dData.appendRange(barNumbers, result.d);
const upper = Number(ui.zones.value);
upperZone.y1 = upper;
upperZone.y2 = 100;
lowerZone.y1 = 0;
lowerZone.y2 = 100 - upper;
upperLine.y1 = upper;
lowerLine.y1 = 100 - upper;
showBar();
}

const preset = (n, kS, dS) => () => {
ui.lookback.value = String(n);
ui.kSmoothing.value = String(kS);
ui.dSmoothing.value = String(dS);
update();
};
ui.presets.fast.addEventListener("click", preset(14, 1, 3));
ui.presets.slow.addEventListener("click", preset(14, 3, 3));
ui.presets.full.addEventListener("click", preset(14, 3, 3));
for (const input of [ui.lookback, ui.kSmoothing, ui.dSmoothing]) input.addEventListener("input", update);
ui.zones.addEventListener("change", update);
ui.range.addEventListener("change", showBar);
for (const surface of [top.sciChartSurface, bottom.sciChartSurface]) {
const hover = new HoverBarModifier();
hover.onBar = (index) => {
if (index === selected) return;
selected = index;
showBar();
};
surface.chartModifiers.add(hover);
}
update();

Key points:

  • The price pane is a FastCandlestickRenderableSeries over an OhlcDataSeries, with the bar number on the x axis so weekends leave no gaps; labelProvider.formatLabel turns each bar number back into its date.
  • %K and %D are two FastLineRenderableSeries over XyDataSeries created with containsNaN: true, so the warm-up bars are left blank. The oscillator's y axis has autoRange: EAutoRange.Never and a fixed range, so 80 and 20 stay in the same place as you zoom.
  • The zones are BoxAnnotations with xCoordinateMode: ECoordinateMode.Relative, so they span the full width; the hover window on the price pane is another BoxAnnotation in data coordinates, moved by a small CustomChartModifier2D that turns the mouse position into a bar number.
  • SciChartVerticalGroup lines up the two panes' y axes, and each x axis's visibleRangeChanged event sets the other's range, so zooming one pane zooms both (see synchronising vertical charts).

See it in the demo app: JavaScript synchronised multi-chart · React synchronised multi-chart · Angular synchronised multi-chart. Related techniques: the React line chart and React chart annotations.

Go deeper: SciTrader.js stochastic oscillator documentation, the candlestick series documentation, synchronising vertical charts, and the learning center guides to the candlestick chart, the OHLC chart and the line chart. For how trading software uses SciChart, see SciChart for financial and stock trading applications.

Building a full trading app?​

SciTrader.js, SciChart's financial charts SDK, has the stochastic oscillator built in. Its stochastic oscillator study adds %K and %D in their own pane under a live price chart as a single study object; it draws the fast stochastic, with a 14-bar look-back and a 3-bar %D by default. The RSI study and the other built-in indicators sit alongside it, with drawing tools, multiple panes and live exchange feeds. See what SciChart can do for trading apps on the JavaScript stock charts page.

Frequently asked questions​

What is the stochastic oscillator?​

The stochastic oscillator is a momentum indicator that measures where the latest close sits within the high-low range of the last N bars, on a scale from 0 to 100. A reading of 100 means the close is at the highest high of the period and 0 means it is at the lowest low. It is drawn as two lines, %K and its moving average %D, in a pane below the price chart.

How is the stochastic oscillator calculated?​

Find the highest high and lowest low of the last N bars, usually 14, including the current bar. Raw %K = 100 x (close - lowest low) / (highest high - lowest low). %D is a simple moving average of %K, usually over 3 bars. The slow and full versions also average raw %K before %D is worked out.

What is the difference between the fast, slow and full stochastic?​

The fast stochastic plots raw %K and a 3-bar average of it as %D. The slow stochastic averages raw %K over 3 bars first, so its %K is the fast %D, and its %D is a 3-bar average of that. The full stochastic lets you set the look-back, the %K smoothing and the %D smoothing separately; full 14,3,3 gives the same lines as slow 14,3.

What do the stochastic settings 14,3,3 mean?​

14,3,3 means a 14-bar look-back for the high-low range, a 3-bar average to smooth raw %K, and a 3-bar average of the smoothed %K to make %D. The bars are whatever the chart uses, so on a daily chart 14 means 14 trading days and on a 5-minute chart it means 70 minutes. It is a common default today; nothing about the numbers makes them better than nearby settings.

What is the difference between the stochastic oscillator and RSI?​

The stochastic compares the close with the high-low range of recent bars, so it reacts as soon as the close moves within that range. RSI compares the size of recent up closes with recent down closes, using closes only, and reaches its extremes less often. Stochastic RSI applies the stochastic formula to RSI values instead of prices, which makes it more sensitive than either.

How do I plot a stochastic oscillator in JavaScript?​

Work out raw %K, %K and %D from your candles' highs, lows and closes in plain JavaScript, using NaN for the warm-up bars. Draw the candles on one SciChart.js surface and the two lines as FastLineRenderableSeries on a second surface below it with a fixed 0 to 100 axis, shade the zones with BoxAnnotation, and link the two x axes so they zoom together. The same function works in React through scichart-react and in Angular through scichart-angular.

Sources​

  • Lane, G. C. (1984), "Lane's Stochastics", Technical Analysis of Stocks & Commodities, 2(3), 87–90. Lane's own description of %K, %D and how he read them.
  • Murphy, J. J. (1999), Technical Analysis of the Financial Markets, New York Institute of Finance. The standard textbook treatment of oscillators, including stochastics, overbought and oversold zones, and divergence.
  • Wilder, J. W., Jr. (1978), New Concepts in Technical Trading Systems, Trend Research. Introduces the relative strength index (RSI).
  • Chande, T. S. and Kroll, S. (1994), The New Technical Trader, Wiley. Introduces the stochastic RSI.
  • Park, C.-H. and Irwin, S. H. (2007), What do we know about the profitability of technical analysis?, Journal of Economic Surveys, 21(4), 786–826. A review of 95 studies of technical trading rules and the problems in how they were tested.