i am trying to calculate rsi by fetching kline data from binance futures. i take closing prices from that which matches exactly with what binance ui shows. But, my rsi differs from rsi shown on binance ui chart. what could be the reason and how to solve it. i m working on 1min data.
Approach:
Extract Closing Prices: Pulls closing prices from the klines data (assumed to be in the 5th column, index 4).
Calculate Gains and Losses: Iterates through closing prices to compute:
Gains: Positive price changes (current price - previous price).
Losses: Absolute value of negative price changes. Non-positive changes are recorded as 0 for gains, and vice versa.
Initial Averages: For the first period data points:
Computes average gain as the sum of gains divided by the period.
Computes average loss as the sum of losses divided by the period.
RSI Calculation:
For the first RSI value (at index period): RSI = 100 - (100 / (1 + avgGain / avgLoss)).
For subsequent values:
Updates average gain and loss using a smoothed formula: (previous_avg * (period - 1) + current_gain_or_loss) / period
Computes RS = avgGain / avgLoss.
Computes RSI = 100 - (100 / (1 + RS)), rounded to two decimal places