pythonbinancebinance-api-client

Python binance api rsi calculation with last 15 value is wrong


I want to use 15 minutes data to calculate my own RSI strategy. I am using binance API with python. So I need the last 15 closes data of BTCUSDT. I am getting it like this.

start = str(dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=15*15))
end = str(dt.datetime.now())

trades = client.get_historical_klines(symbol='BTCUSDT',
                                      interval=Client.KLINE_INTERVAL_15MINUTE,
                                      start_str=start,
                                      end_str=end)

Gets last 15 data And calculates the rsi value like following.

closes = [float(row[4]) for row in trades]
c = numpy.array(closes)

rsi = talib.RSI(c, timeperiod=14)

print(rsi[-1])

The print the value of last RSI is different from binance online chart. For example my calculated is 34.41 and binance web application shows latest RSI is 39.68 on chart for 15 minutes.

If I calculate of the initial RSI value, I will put new close values in my array using web socket of. But it is wrong. How can I do this?


Solution

  • As Binance is integrated with Trading View, the rsi should be calculated using an exponential moving average (EMA), whereas talib is using the SMMA (smoothed moving average).

    Note that you will probably find less discrepancies if you use a larger sample (assumption made that the first bar is 0 gain and 0 loss will have less weight).

    See below talib code if you want to go in details :

    ta-lib : https://github.com/TA-Lib/ta-lib/blob/master/src/ta_func/ta_RSI.c

    If you want to change your calculation using EMA, consider this code : https://github.com/lukaszbinden/rsi_tradingview/blob/main/rsi.py