I'm making a bot in node.js and I collected historical data + real time data by using binance api and binance websocket, by doing that I can give my bot the most recent data in real time.
I'm trying to calculate the RSI and the values I get are different from Trading View (and binance).
This is my function:
The function accepts 2 parameters, period and table name. Period is the number of candles it should consider in order to make the calculations, tableName is where it should get the candles from my db and also the type of candle (1m, 5m, 1h etc...)
Klines is an array of candles, they are already sorted from newest to oldest, so Kline[i] is new compared to Kline[i+1].
async function calculateRSI(period, tableName) {
const klines = await getKlines(period, tableName);
// Calculate percentage changes in price
const percentageChanges = [];
for (let i = klines.length - 1; i > 0; i--) {
const closePricePrev = klines[i - 1].close_price;
const closePriceCurr = klines[i].close_price;
const percentageChange = ((closePricePrev - closePriceCurr) / closePricePrev) * 100;
percentageChanges.push(percentageChange);
}
// Calculate gains and losses
const gains = [];
const losses = [];
for (let i = 0; i < percentageChanges.length; i++) {
if (percentageChanges[i] >= 0) {
gains.push(percentageChanges[i]);
losses.push(0);
} else {
gains.push(0);
losses.push(-percentageChanges[i]);
}
}
const sumGain = gains.reduce((acc, curr) => acc + curr, 0);
const sumLoss = losses.reduce((acc, curr) => acc + curr, 0);
// Calculate Relative Strength (RS)
const RS = sumGain / sumLoss;
// Calculate RSI
const RSI = 100 - (100 / (1 + RS));
console.log(`RSI:${tableName} ${period}`, RSI);
}