Calculating the Stochastic Oscillator (STOCH) with JavaScript

onurcelik

Mustafa Onur Çelik

Posted on December 11, 2022

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.

💖 💪 🙅 🚩
onurcelik
Mustafa Onur Çelik

Posted on December 11, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related