Bentrix Docs
HomePricingDashboard

Stochastic Oscillator Stochastic

Oscillatorsoscillator2 linesin every package

Where the close sits inside the highest high and lowest low of the last K bars, as 0 to 100, smoothed by the slowing factor into %K, with %D the average of %K.

It measures position within the recent range, which is a different question from how far price has travelled. Readings: above 80 called overbought, below 20 oversold, and %K crossing %D. The conventions genuinely differ: MT5 sums the numerators and denominators over the slowing window and then divides, TA-Lib averages the fast %K. On the same bars the two can differ by tens of points, and on a range of zero height (a flat market) one answers 100 where the other answers 0.

01The study, live

Live figureScroll to zoom, drag the bars to pan.
2080
bar —O — H — L — C —main line —signal —first value at —
Show where:

Computed by Bentrix’s own code over the same synthetic bars on every page — an illustration of how the study behaves, not a market.

What this figure shows

The figure is computed over 300 sample bars. Stochastic has no value on the first 8 — the bars it needs before it can answer — and its first value stands on bar 9. Its line runs between 3.67 and 97.98 on these bars, and the last value is 31.79. The pane's scale is fixed at 0 to 100, the range the study can take. Counting the conditions the study declares on these bars: crosses above 20 13 times; crosses below 20 13 times; crosses above 80 15 times; crosses below 80 16 times; crosses above its signal line 35 times; crosses below its signal line 34 times. Press a condition under the figure to see each place marked. As states rather than moments: is above 20 on 230 bars; is below 20 on 62 bars; is above 80 on 56 bars; is below 80 on 236 bars; is above its signal line on 140 bars; is below its signal line on 152 bars.

02Its parts, named

The bars it readseach bar's open, high, low and closeWarm-upno value on the first 8 bars: thestudy needs them before it cananswerThe second linedrawn with the main line: its signalor its partnerLevel 80a fixed reference the study is readagainstThe main linethe study's own value on each barLevel 20a fixed reference the study is readagainst
Computed by Bentrix’s own code over the sample bars. It is drawn on once, as you reach the figure.

03What you see

Two lines between 0 and 100 — %K and its average %D — with reference lines at 20 and 80. %K shows where the close sits within the recent high-low range.

04Where it comes from

Credited to George C. Lane, who taught and wrote about it from the 1950s on. Its idea: in a rise, closes tend to sit near the top of the recent range; in a fall, near the bottom.

05The formula

%Kfast=100·Ct−min(LN)max(HN)−min(LN)
Ctthe close
max(HN), min(LN)the highest high and the lowest low of the last N bars
Nthe %K period — 5 by default

over the last N bars (5 by default in MetaTrader 5). The slow %K averages it over the slowing window (3), and %D averages the slow %K again (3). Bentrix also offers the method of %D's average and whether the range is taken from highs and lows or from closes.

06A worked example

The sample bars used here are eight: closes 20, 21, 23, 22, 24, 25, 24, 26; highs 21, 22, 24, 24, 25, 26, 26, 27; lows 18, 19, 20, 21, 21, 23, 23, 23; opens 19, 20, 21, 23, 22, 24, 25, 24.

Take %K period 5. On the last bar the highest high of the last five bars is 27 and the lowest low 21; the close is 26.

Raw %K = (26 − 21) / (27 − 21) × 100 = 83.33

The close sits 83 % of the way up the five-bar range. The same step on the two bars before gives 85.71 and 66.67.

With Slowing 3 the %K that is drawn is the average of the last three raw values: (85.71 + 66.67 + 83.33) / 3 = 78.57. %D is then the average of the last three drawn %K values — a smoothing of a smoothing, which is why it trails.

07Built in Assay

The same study written in Assay, Bentrix’s script language, and drawn by Bentrix itself as the script’s graph: each block is one step of the formula. On the ladder the steps stand in the script’s order, one a row; on the board each wire carries a value from the block that gives it to the block that reads it, left to right. The script computes exactly what the study computes — Bentrix checks the two against each other, candle by candle.

THE SCRIPT’S GRAPH
//@version=6
indicator("Stochastic Oscillator")
kLength = input.int(5, "%K length")
slowing = input.int(3, "Slowing")
dLength = input.int(3, "%D length")
lowest = ta.lowest(low, kLength)
highest = ta.highest(high, kLength)
// Where the close stands inside the window's range: 0 at its low, 100 at its high.
fastK = na(highest) ? na : highest - lowest != 0 ? (close - lowest) / (highest - lowest) * 100 : 0.0
// %K is that reading averaged over `slowing` bars; %D is %K averaged again.
k = ta.sma(fastK, slowing)
d = ta.sma(k, dLength)
// Both lines start on the bar %D has its first value.
plot(na(d) ? na : k, "%K")
plot(d, "%D")
hline(80)
hline(20)

Paste it into the Assay IDE to put it on a chart, or to change it. Looking at the graph is free in every package; editing it as blocks is Plus.

08Readings — what traders look for

Above 80, below 20 are read as the close sitting near the top, or the bottom, of the recent range.

%K crossing %D is read as the position within the range changing direction.

Crosses inside an extreme zone — %K crossing below %D above 80 — are read by many traders as the close starting to slip from the top of its range.

Divergence with price, as with the RSI.

How the 80 and 20 readings fail. A close near the top of its recent range is what a rising market produces bar after bar. In a strong trend the line stays at one end of its scale for a long time; a high reading there describes the trend and does not mark its end.

How %K crossing %D fails. Inside a narrow range of prices the two lines cross every few bars, and most crossings are followed by nothing; George Lane himself read crossings together with where on the scale they happened.

09In different markets and timeframes

The stochastic is a range instrument: it says where the close stands between the recent extremes, which is the right question when price oscillates between them. In a trend the close stays near one extreme and the lines stay pinned above 80 or below 20. Short windows on low timeframes cross constantly; the slowing input exists to calm that.

10With other studies

Read beside a trend filter (a moving average, the ADX) so that readings against the larger direction can be told from readings with it; beside Williams %R, which is the same measurement upside down; and beside the RSI, which measures changes where the stochastic measures position.

11What it does not tell you

!

The Stochastic measures the close's place in a range, not momentum or value. In a steady trend it pins near one extreme. A cross describes the last few bars.

12Inputs and defaults

Stochastic (3, 5)settings card
1%D period3
2%K period5
3Slowing3
4TimeframeChart
5CalculationTA-Lib
6Wait for the candle to closeOn
  1. 1
    %D period — 3The smoothing of %K that makes the second line. Longer: fewer crossings, each later.
  2. 2
    %K period — 5The window of highs and lows the close is placed within. Longer: the range is wider and the close reaches its ends less often.
  3. 3
    Slowing — 3The smoothing of raw %K before it is drawn. 1 gives the fast stochastic; 3 the usual slow one.
  4. 4
    Timeframe — ChartThe chart's own by default; any higher one, read on the last closed candle. A finer one is never offered.
  5. 5
    Calculation — TA-LibOr MT5, which computes it as MetaTrader 5 does — see the calculation convention below.
  6. 6
    Wait for the candle to close — OnThe value of a higher timeframe is taken only from a candle that has finished.

The settings in use

  • In use5, 3, 3 is the fast-moving default here; 14, 3, 3 the classic slow stochastic; 21, 5, 5 and longer for a calmer line. The first number is the range's window, the second the smoothing of %K, the third the %D average.

13Calculation convention

This is one of the studies whose result differs between the two conventions Bentrix offers. The difference is in how the first values are seeded and how the series is smoothed, so the two agree after the warm-up and differ at its start. Choose it on the settings card's Calculation row.

defaultTA-Lib

The convention of the TA-Lib library, which most charting software follows.

MT5

Computed as MetaTrader 5 computes it, so a value matches the terminal's own.

14Limits and common misreadings

Short settings make it very fast and noisy; on most markets it changes direction many times a day on M5.

15Conditions an alert or a strategy can watch

crosses above 20 eventcrosses below 20 eventis above 20 stateis below 20 statecrosses above 80 eventcrosses below 80 eventis above 80 stateis below 80 statecrosses above its signal line eventcrosses below its signal line eventis above its signal line stateis below its signal line state

Event: the bar it happens on an event happens on one barState: every bar while it holds a state holds on every bar while it lasts

These are the conditions the study itself declares — the same rules the alert editor and the strategy engine read, and the ones the figure's chips show.

16Practise it in the laboratory

Toggle crosses below 80 on the figure above and count how often it came in a rise that kept going.

Open the laboratory

18On pages of their own

19In Bentrix

  • From the menu: a chart's Indicators button › Oscillators › Stochastic, or type Stochastic in its search.
  • Its settings: the settings card opens when it is added; its legend's name opens it again.

20From an agent or a program

Two tools reach it. study_values computes it over a workbench’s candles up to the clock — no chart needed — and study_attach puts it on a chart, where it is drawn and saved with the chart ({"chart": "<chart uri>", "kind": "stoch"}).

The study, as a chart files it

This is a new Stochastic’s entry — its kind, its calculation, the price it reads and its settings. Change a setting here to read it with other inputs.

{
  "applied": "close",
  "convention": "talib",
  "kind": "stoch",
  "settings": {
    "d": 3,
    "k": 5,
    "shape": "stoch",
    "slowing": 3
  }
}

An agent

An agent calls the MCP tool with it:

{
  "name": "study_values",
  "arguments": {
    "bench": "bentrix://lab/\u2026/bench/\u2026",
    "symbol": "EURUSD",
    "timeframe": "H1",
    "limit": 5,
    "study": {
      "applied": "close",
      "convention": "talib",
      "kind": "stoch",
      "settings": {
        "d": 3,
        "k": 5,
        "shape": "stoch",
        "slowing": 3
      }
    }
  }
}

A program

A program does the same in its language — bench and market as in the built-in indicators guide:

Python

values = client.study.values(bench, market, "H1", {"applied": "close", "convention": "talib", "kind": "stoch", "settings": {"d": 3, "k": 5, "shape": "stoch", "slowing": 3}}, limit=5)
print("times:", values["times"])
for line in values["lines"]:
    print("line:", line["line"])
    print("  newest values:", line["values"])

JSJavaScript

const values = await client.study.values({ bench, symbol: market, timeframe: "H1", study: { "applied": "close", "convention": "talib", "kind": "stoch", "settings": { "d": 3, "k": 5, "shape": "stoch", "slowing": 3 } }, limit: 5 });
console.log("times:", values.times);
for (const line of values.lines) {
  console.log("line:", line.line);
  console.log("  newest values:", line.values);
}

C#C#

var values = await client.Study.Values(bench, market, "H1", new Dictionary<string, object?> { ["applied"] = "close", ["convention"] = "talib", ["kind"] = "stoch", ["settings"] = new Dictionary<string, object?> { ["d"] = 3, ["k"] = 5, ["shape"] = "stoch", ["slowing"] = 3 } }, limit: 5);
Console.WriteLine($"times: {values!["times"]!}");
foreach (var line in values!["lines"]!.AsArray())
{
    Console.WriteLine($"line: {line!["line"]!}");
    Console.WriteLine($"  newest values: {line!["values"]!}");
}

GOGo

values := must(client.Study.Values(ctx, mcp.StudyValuesArgs{Bench: bench, Symbol: market, Timeframe: "H1", Study: map[string]any{"applied": "close", "convention": "talib", "kind": "stoch", "settings": map[string]any{"d": 3, "k": 5, "shape": "stoch", "slowing": 3}}, Limit: mcp.Ptr[int64](5)}))
fmt.Println("times:", at(values, "times"))
for _, line := range at(values, "lines").([]any) {
	fmt.Println("line:", at(line, "line"))
	fmt.Println("  newest values:", at(line, "values"))
}

Java

Object values = client.study.values(new Bentrix.StudyApi.ValuesArgs(bench, market, "H1", obj("applied", "close", "convention", "talib", "kind", "stoch", "settings", obj("d", 3, "k", 5, "shape", "stoch", "slowing", 3))).limit(5L));
System.out.println("times:" + " " + at(values, "times"));
for (Object line : (List<Object>) at(values, "lines")) {
    System.out.println("line:" + " " + at(line, "line"));
    System.out.println("  newest values:" + " " + at(line, "values"));
}

C++C++

auto values = client.study.values_(StudyApi::ValuesArgs(bench, market, "H1", Json::Object{{"applied", "close"}, {"convention", "talib"}, {"kind", "stoch"}, {"settings", Json::Object{{"d", 3}, {"k", 5}, {"shape", "stoch"}, {"slowing", 3}}}}).limit(5));
std::cout << "times:" << " " << values["times"].dump() << std::endl;
for (const Json &line : values["lines"].arr()) {
    std::cout << "line:" << " " << line["line"].dump() << std::endl;
    std::cout << "  newest values:" << " " << line["values"].dump() << std::endl;
}

Julia

values = client.study.values(bench, market, "H1", Dict{String,Any}("applied" => "close", "convention" => "talib", "kind" => "stoch", "settings" => Dict{String,Any}("d" => 3, "k" => 5, "shape" => "stoch", "slowing" => 3)); limit = 5)
println("times:", " ", values["times"])
for line in values["lines"]
    println("line:", " ", line["line"])
    println("  newest values:", " ", line["values"])
end

RR

values <- client$study$values(bench, market, "H1", list(applied = "close", convention = "talib", kind = "stoch", settings = list(d = 3, k = 5, shape = "stoch", slowing = 3)), limit = 5)
cat("times:", format(values$times), "\n")
for (line in values$lines) {
  cat("line:", format(line$line), "\n")
  cat("  newest values:", format(line$values), "\n")
}

RRust

let values = client.study().values(mcp::StudyValuesArgs::new(bench.clone(), market.clone(), "H1", serde_json::json!({"applied": "close", "convention": "talib", "kind": "stoch", "settings": {"d": 3, "k": 5, "shape": "stoch", "slowing": 3}})).limit(5))?;
println!("times: {}", values["times"]);
for line in values["lines"].as_array().into_iter().flatten() {
    println!("line: {}", line["line"]);
    println!("  newest values: {}", line["values"]);
}

Reading the answer

  • times — the candles’ open times, in milliseconds since 1970 (UTC), oldest first.
  • lines — one entry per line, in this order, each with its line name and its values; values[i] belongs to the candle at times[i].
  • The last value is the candle at the clock’s, which may still be forming: it changes until that candle closes, as on the chart. Nothing after the clock is ever computed.
  • null is a candle with no value yet — the warm-up, about 1 × the period at the start of the history.
  • Its fixed levels, drawn on the chart: [20.0, 80.0].
lineWhat it is
Mainthe indicator's own value
Signala smoothing of the main line, drawn beside it

In a strategy

Filed under a key of your choice in a strategy document’s studies — here stoch: {"stoch": {"applied": "close", "convention": "talib", "kind": "stoch", "settings": {"d": 3, "k": 5, "shape": "stoch", "slowing": 3}}} — its rules can name:

WriteWhat it is
stochits main line, as a value in a compare
stoch.signalthis line, as a value in a compare
{"cond": "stoch:level.cross_up:20"}a condition it declares itself
{"cond": "stoch:level.cross_down:20"}a condition it declares itself
{"cond": "stoch:level.above:20"}a condition it declares itself
{"cond": "stoch:level.below:20"}a condition it declares itself
{"cond": "stoch:level.cross_up:80"}a condition it declares itself
{"cond": "stoch:level.cross_down:80"}a condition it declares itself
{"cond": "stoch:level.above:80"}a condition it declares itself
{"cond": "stoch:level.below:80"}a condition it declares itself
{"cond": "stoch:signal.cross_up"}a condition it declares itself
{"cond": "stoch:signal.cross_down"}a condition it declares itself
{"cond": "stoch:signal.above"}a condition it declares itself
{"cond": "stoch:signal.below"}a condition it declares itself

21Sources

  1. Murphy, John J. Technical Analysis of the Financial Markets. New York Institute of Finance, 1999, ch. 10.
  2. Colby, Robert W. The Encyclopedia of Technical Market Indicators, 2nd ed. McGraw-Hill, 2003, "Stochastics".

Bentrix 0.1.382Every number, name and default on these pages is read from the application itself.What is comingWhat changed