DEV Community

Cover image for Calculating the Stochastic Oscillator (STOCH) with JavaScript
Mustafa Onur Çelik
Mustafa Onur Çelik

Posted on • Edited on

2 1

Calculating the Stochastic Oscillator (STOCH) with JavaScript

To calculate the Stochastic Oscillator (STOCH) with JavaScript, you can use the following formula:

STOCH = (current closing price - lowest low in the period) / (highest high in the period - lowest low in the period)

Enter fullscreen mode Exit fullscreen mode

Here's an example of how you can implement this formula to calculate the STOCH for a given array of closing prices:

function calculateSTOCH(closingPrices) {
  let lowestLow = Number.MAX_VALUE;
  let highestHigh = Number.MIN_VALUE;

  // Find the lowest low and the highest high in the period
  for (let i = 0; i < closingPrices.length; i++) {
    lowestLow = Math.min(lowestLow, closingPrices[i]);
    highestHigh = Math.max(highestHigh, closingPrices[i]);
  }

  // Calculate the STOCH
  const stoch = (closingPrices[closingPrices.length - 1] - lowestLow) /
    (highestHigh - lowestLow);

  return stoch;
}

// Example usage
const closingPrices = [100, 110, 105, 115, 120, 130, 140, 150, 145, 155];
const stoch = calculateSTOCH(closingPrices);
console.log(stoch); // Output: 0.88

Enter fullscreen mode Exit fullscreen mode

This code calculates the STOCH for a given array of closing prices by first finding the lowest low and the highest high in the period, and then applying the STOCH formula to these values. You can adjust the number of closing prices used in the calculation by changing the length of the array passed to the calculateSTOCH() function.

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more