Skip to main content

Stochastic Oscillator in a JavaScript or React Financial Chart

The Stochastic Oscillator shows where the latest close sits within the recent high–low range. This page explains what the Stochastic indicator is, how its %K and %D lines are calculated and how traders read them, and shows how to add a Stochastic Oscillator to a JavaScript or React financial chart with SciTrader.js's StochasticStudy, with live examples you can edit in CodePen.

info

The Stochastic Oscillator is one of the 32 built-in technical indicators and studies in the SciTrader SDK. For the full list, with each one's options and defaults, see Every Built-in Indicator and Study. To add and remove any of them, or build an indicator picker, see Add Technical Indicators to a Financial Chart.

What Is the Stochastic Oscillator?​

The Stochastic Oscillator, developed by George Lane, is a momentum oscillator on a scale from 0 to 100. It is drawn as two lines:

  • %K is where the close sits in the range of the last length candles: 100 at the top of the range, 0 at the bottom.
  • %D is a moving average of %K, a slower signal line.

The idea is that in an uptrend, closes tend to be near the top of the range, and in a downtrend near the bottom. It has its own 0–100 scale, so a chart draws it in a pane of its own below the price chart.

How Is the Stochastic Oscillator Calculated?​

With nn = length (14 by default) and mm = signalPeriod (3 by default):

%K=100×close−lowest lownhighest highn−lowest lown%D=SMAm(%K)\%K = 100 \times \frac{\text{close} - \text{lowest low}_n}{\text{highest high}_n - \text{lowest low}_n} \qquad \%D = \text{SMA}_m(\%K)

where the highest high and lowest low are over the last nn candles, including the latest, and SMAm\text{SMA}_m is a simple moving average of the last mm %K values. If the range is zero, because every candle has the same price, %K is 0.

note

StochasticStudy is the fast stochastic: %K is used as it is. Many platforms default to the slow stochastic, which smooths %K with a 3-candle average first, so their lines are smoother than StochasticStudy's with the same settings.

%K starts after nn candles and %D after n+m−1n + m - 1. SciTrader loads length + signalPeriod extra candles to the left of the visible period, so the lines start at the left edge.

How to Read the Stochastic Oscillator​

These are the common readings. They are conventions traders use, not signals that hold every time:

  • Overbought and oversold. Above 80 is commonly read as overbought, and below 20 as oversold. In a strong trend, the Stochastic can stay there for a long time. StochasticStudy doesn't draw these levels; read them from the axis.
  • %K/%D crossovers. %K crossing above %D is read as bullish, and below as bearish, especially in the oversold or overbought zones.
  • Divergence. Price making a new low while the Stochastic makes a higher low suggests selling pressure is fading. The same applies to highs.

How to Add a Stochastic Oscillator to a JavaScript Financial Chart​

Add a StochasticStudy to the chart's studies. The example below is a 6-hour BTC-USD chart from Coinbase with a 14, 3 Stochastic Oscillator in its own pane: %K in teal and %D in amber.

The code for this example is found below.

import "scichart-scitrader/scitrader.css";
import {
CandleInterval,
CoinbaseExchange,
defaultExchangeProvider,
idbPriceStore,
OHLCStudy,
SciFinanceChartPanel,
StochasticStudy,
VolumeStudy,
} from "scichart-scitrader";

// This example expects this HTML:
// <div id="chart" style="height: 100%"></div>

// Register a data source, once, at app startup
defaultExchangeProvider.registerExchange(CoinbaseExchange, idbPriceStore);

async function createChart() {
// A financial chart is a SciFinanceChartPanel. Its indicators are studies, passed in `studies`
const financeChartPanel = await SciFinanceChartPanel.create(document.getElementById("chart"), {
exchangeName: CoinbaseExchange.name, // name="Coinbase" matches the built-in CoinbaseExchange
symbol: "BTC-USD",
interval: CandleInterval.SIX_HOURS,
period: "3M",
studies: [
new OHLCStudy(), // the price series, as candlesticks
new VolumeStudy(), // volume, along the bottom of the price pane
// Stochastic Oscillator: an oscillator, so it gets a pane of its own, scaled 0 to 100.
// length: candles in the high-low range %K is measured against (default 14).
// signalPeriod: the length of %D, the moving average of %K (default 3)
new StochasticStudy({
length: 14,
signalPeriod: 3,
strokeK: "#2ec4b6", // %K
strokeD: "#ff9f1c", // %D
strokeThickness: 2,
}),
],
});

// When the page goes away: financeChartPanel.cleanup();
return financeChartPanel;
}

createChart();

How to Add a Stochastic Oscillator to a React Financial Chart​

In React, pass the same studies in the config of SciFinanceChartView, from scichart-scitrader-react. Create them in a useMemo, once per mounted chart: a study is a live object, bound to one chart.

The code for this example is found below.

import "scichart-scitrader/scitrader.css";
import * as React from "react";
import {
CandleInterval,
CoinbaseExchange,
defaultExchangeProvider,
idbPriceStore,
ISciFinanceChartPanelConfig,
OHLCStudy,
StochasticStudy,
VolumeStudy,
} from "scichart-scitrader";
import { SciFinanceChartView } from "scichart-scitrader-react";

// Register a data source, once, at app startup
defaultExchangeProvider.registerExchange(CoinbaseExchange, idbPriceStore);

export function StochasticChart() {
// Create the config once per mounted chart: studies are live objects bound to one chart
const config = React.useMemo<ISciFinanceChartPanelConfig>(
() => ({
exchangeName: CoinbaseExchange.name, // name="Coinbase" matches the built-in CoinbaseExchange
symbol: "BTC-USD",
interval: CandleInterval.SIX_HOURS,
period: "3M",
studies: [
new OHLCStudy(), // the price series, as candlesticks
new VolumeStudy(), // volume, along the bottom of the price pane
// Stochastic Oscillator: an oscillator, so it gets a pane of its own, scaled 0 to 100.
// length: candles in the high-low range %K is measured against (default 14).
// signalPeriod: the length of %D, the moving average of %K (default 3)
new StochasticStudy({
length: 14,
signalPeriod: 3,
strokeK: "#2ec4b6", // %K
strokeD: "#ff9f1c", // %D
strokeThickness: 2,
}),
],
}),
[]
);

// SciFinanceChartView fills its parent, so give the parent a height
return <SciFinanceChartView config={config} />;
}

Adding and Removing the Stochastic Oscillator at Runtime​

StochasticStudy is a study like any other, so you can add it to a chart that is already showing, and remove it again:

import { EStudyType, StochasticStudy, studyProvider } from "scichart-scitrader";

const chart = financeChartPanel.financeApi;

// Add one with your own settings...
const study = new StochasticStudy();
await chart.attachStudy(study);

// ...or by type, with the default settings, e.g. from an indicator picker
await chart.attachStudy(studyProvider.getStudy(EStudyType.Stochastic));

// Remove it
chart.detachStudy(study);

See Add Technical Indicators to a Financial Chart for more, including a ready-made indicator picker.

StochasticStudy Options and Settings​

OptionDefaultWhat it does
length14Candles in the high–low range %K is measured against
signalPeriod3The length of %D, the moving average of %K
strokeKThe theme's colourThe %K line
strokeDThe theme's colourThe %D line
strokeThickness2The thickness of both lines
paneIdA new paneThe pane to draw in

Users can change the same settings in the Settings Form, and you can change them from code with applyDescriptor. There, length is named period:

StudyInputsStyles
StochasticStudyperiod, signalPeriodstrokeK, strokeD, strokeThickness
The StochasticStudy class, with its TSDoc
/**
* Stochastic Oscillator — %K and %D lines (0–100) on their own pane. HLC input.
* Two outputs, so the output ids are created with distinct names (mirroring
* MACD) — the {@link StudyBase.createOutputSourceId} helper is single-output
* only (it would collide both ids on the same key).
*/
class StochasticStudy extends StudyBase<number> {
/** Indicator pane — small relative weight (price pane defaults to 3×). */
readonly paneSizeConfig: {
grow: number;
};
length: number;
signalPeriod: number;
strokeK: string;
strokeD: string;
strokeThickness: number;
getRequiredWarmup(): number;
constructor(options?: IStochasticOptions);
static getOptionsFromDescriptor(descriptor: TStudyDescriptor): IStochasticOptions;
get supportsLiveApply(): boolean;
createInputOutputIds(): void;
createDataSeries(): void;
createAxes(): AxisBase2D[];
/** @inheritDoc */
getLegendColor(outputId: DataSourceId): string | undefined;
createRenderableSeries(): IRenderableSeries[];
}
The IStochasticOptions interface, with its TSDoc
interface IStochasticOptions extends IStudyOptions {
length?: number;
signalPeriod?: number;
strokeK?: string;
strokeD?: string;
strokeThickness?: number;
}