0

Calculation of the actual RSI(Relative Strength Index) of the Bitcoin price via API:

My script currently makes 14 individual requests to the API to calculate the actual RSI for the Bitcoin. Now I have found a request with which I only have to make one request to the API.

https://min-api.cryptocompare.com/data/histoday?fsym=BTC&tsym=USD&limit=14

What do I need to do to integrate the new API into the existing script? I just want to make one request to the API.

// Create a url for currencies + date
const getURL = (currencyFrom, currencyTo, timestamp) => 
  `https://min-api.cryptocompare.com/data/pricehistorical?fsym=${currencyFrom}&tsyms=${currencyTo}&ts=${timestamp}`;

// Get a timestamp from exactly x days ago
const timeStampForDaysAgo = 
 nrOfDays => Date.now() - 1000 * 60 * 60 * 24 * nrOfDays;

const getBTCDollarValueForDays = nrOfDays => Promise
  .all(Array.from(
       Array(nrOfDays),
        (_, i) => 
         fetch(getURL("BTC", "USD", timeStampForDaysAgo(i)))
            .then(r => r.json()))
  );

const getDollarValueFromResponse = obj => obj.BTC.USD;

// Main:
getBTCDollarValueForDays(14)
  .then(vals => vals.map(getDollarValueFromResponse))
  .then(calcRSI)
  .then(console.log.bind(console, "RSI is:"));
  
  
function calcRSI(xs) {
  let sumGain = 0;
  let sumLoss = 0;
  const TOLERANCE = 50;
  
  for (let i = 1; 
    i < xs.length; 
    i += 1) {
   const curr = xs[i];
    const prev = xs[i - 1]
    const diff = curr - prev;
    
    if (diff >= 0) {
      sumGain += diff;
    } else {
      sumLoss -= diff;
    }
  }
  
  if (sumGain === 0) return 0;
  if (Math.abs(sumLoss) < TOLERANCE) return 100;
  
  const relStrength = sumGain / sumLoss;
  
  return 100 - (100 / (1 + relStrength));
};
D.D.
  • 33
  • 4
  • What's your specific problem? – robertklep Aug 10 '17 at 17:02
  • I have edited my specific question. Is this now easier to understand? – D.D. Aug 11 '17 at 07:09
  • I still don't understand your specific problem. As you asking people to rewrite the code so it will use the new URL? – robertklep Aug 11 '17 at 07:33
  • I am not able to get the 14 prices from the new API request and then forward these correctly to the function. So I made the detour with the 14 separate requests. A rewrite of the code with the new API URL would be awesome, but I really want to understand how to get these many prices from the api with just one request and then foreward them correctly to calculate the RSI. – D.D. Aug 11 '17 at 09:07
  • Why can't you get the 14 prices from the new API request? Its structure seems pretty straightforward. – robertklep Aug 11 '17 at 09:26

0 Answers0