Please tell me the issues with the Python code that calculates RSI 7, RSI 21, stoch rsi K, and stoch rsi D values using the Binance API.

I would like to know the Python code to fetch data from the Binance API and calculate RSI 7, RSI 21, stochrsi K, and stochrsi D values. I have already obtained the Binance API key.
Here is the code I have written:
The problem is that the values calculated by running this code differ significantly from the values shown on the Binance app. I would appreciate the help of experts

[my code]

import ccxt
import pandas as pd

def fetch_binance_data(symbol, timeframe, limit=1000):
binance = ccxt.binance()
ohlcv = binance.fetch_ohlcv(symbol=symbol, timeframe=timeframe, limit=limit)
df = pd.DataFrame(ohlcv, columns=[‘timestamp’, ‘open’, ‘high’, ‘low’, ‘close’, ‘volume’])
df[‘timestamp’] = pd.to_datetime(df[‘timestamp’], unit=‘ms’)
return df

def rsi_calc(ohlc: pd.DataFrame, period: int):
delta = ohlc[‘close’].diff()
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)

avg_gain = gain.ewm(span=period, adjust=False).mean()
avg_loss = loss.ewm(span=period, adjust=False).mean()

rs = avg_gain / avg_loss
rsi = 100 - (100 / (1 + rs))

return rsi

def stoch_rsi_calc(rsi: pd.Series, stoch_period=14, k_period=3, d_period=3):
min_rsi = rsi.rolling(window=stoch_period).min()
max_rsi = rsi.rolling(window=stoch_period).max()
stoch_rsi = (rsi - min_rsi) / (max_rsi - min_rsi) * 100

K = stoch_rsi.rolling(window=k_period).mean()
D = K.rolling(window=d_period).mean()

return K, D

def rsi_and_stoch_rsi(symbol, timeframe):
df = fetch_binance_data(symbol, timeframe)

rsi_7 = rsi_calc(df, 7)
rsi_21 = rsi_calc(df, 21)

rsi_7_value = rsi_7.iloc[-1]
rsi_21_value = rsi_21.iloc[-1]

stoch_rsi_k, stoch_rsi_d = stoch_rsi_calc(rsi_7, 14, 3, 3)
stoch_rsi_k_value = stoch_rsi_k.iloc[-1]
stoch_rsi_d_value = stoch_rsi_d.iloc[-1]

return rsi_7_value, rsi_21_value, stoch_rsi_k_value, stoch_rsi_d_value

Parameters

symbol = ‘ALGO/USDT’
timeframe = ‘1h’

Get RSI and Stoch RSI values

rsi_7_value, rsi_21_value, stoch_rsi_k_value, stoch_rsi_d_value = rsi_and_stoch_rsi(symbol, timeframe)

Print results

print(f"RSI 7: {rsi_7_value:.4f}“)
print(f"RSI 21: {rsi_21_value:.4f}”)
print(f"Stochastic RSI K: {stoch_rsi_k_value:.4f}“)
print(f"Stochastic RSI D: {stoch_rsi_d_value:.4f}”)

Here are a few suggestions to potentially improve your code and address discrepancies:

  1. Ensure Data Consistency: Make sure the data you fetch (ohlcv) matches exactly with what you see on the Binance platform. Ensure the timeframe and limit parameters are correctly set.
  2. Adjust Calculation Methods: Sometimes slight adjustments in how averages are calculated (like using different types of moving averages or adjusting smoothing parameters) can align your calculated values more closely with those on Binance.
  3. Verify Indicator Settings: Check if Binance uses different default settings for RSI or Stochastic RSI. For example, they might use a different period or a different type of moving average for smoothing.
  4. Time Zone Handling: Ensure that timestamp conversions (if any) between UTC and your local time zone are consistent.

Here’s a revised version of your code with some adjustments and comments:

python

Copy code

import ccxt
import pandas as pd

def fetch_binance_data(symbol, timeframe, limit=1000):
    binance = ccxt.binance()
    ohlcv = binance.fetch_ohlcv(symbol=symbol, timeframe=timeframe, limit=limit)
    df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
    df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')  # Convert timestamp to datetime
    return df

def rsi_calc(ohlc: pd.DataFrame, period: int):
    delta = ohlc['close'].diff()
    gain = delta.where(delta > 0, 0)
    loss = -delta.where(delta < 0, 0)

    avg_gain = gain.ewm(span=period, adjust=False).mean()
    avg_loss = loss.ewm(span=period, adjust=False).mean()

    rs = avg_gain / avg_loss
    rsi = 100 - (100 / (1 + rs))

    return rsi

def stoch_rsi_calc(rsi: pd.Series, stoch_period=14, k_period=3, d_period=3):
    min_rsi = rsi.rolling(window=stoch_period).min()
    max_rsi = rsi.rolling(window=stoch_period).max()
    stoch_rsi = (rsi - min_rsi) / (max_rsi - min_rsi) * 100

    K = stoch_rsi.rolling(window=k_period).mean()
    D = K.rolling(window=d_period).mean()

    return K, D

def rsi_and_stoch_rsi(symbol, timeframe):
    df = fetch_binance_data(symbol, timeframe)

    rsi_7 = rsi_calc(df, 7)
    rsi_21 = rsi_calc(df, 21)

    rsi_7_value = rsi_7.iloc[-1]
    rsi_21_value = rsi_21.iloc[-1]

    stoch_rsi_k, stoch_rsi_d = stoch_rsi_calc(rsi_7, 14, 3, 3)
    stoch_rsi_k_value = stoch_rsi_k.iloc[-1]
    stoch_rsi_d_value = stoch_rsi_d.iloc[-1]

    return rsi_7_value, rsi_21_value, stoch_rsi_k_value, stoch_rsi_d_value

# Parameters
symbol = 'ALGO/USDT'
timeframe = '1h'

# Get RSI and Stoch RSI values
rsi_7_value, rsi_21_value, stoch_rsi_k_value, stoch_rsi_d_value = rsi_and_stoch_rsi(symbol, timeframe)

# Print results
print(f"RSI 7: {rsi_7_value:.4f}")
print(f"RSI 21: {rsi_21_value:.4f}")
print(f"Stochastic RSI K: {stoch_rsi_k_value:.4f}")
print(f"Stochastic RSI D: {stoch_rsi_d_value:.4f}")

Thank you for your response.
As I searched the internet, I found similar suggestions to what you provided, but strangely, the problem persists. Upon closer inspection, it seems that the values received through the Binance API differ from the actual data.
I would like to get expert advice on whether there might be an issue with my Python code for receiving real-time data through the Binance API that I’ve uploaded

This is a known issue and it seems that it is not fixed :frowning:
You can check this post: https://dev.binance.vision/t/inconsistency-of-websockets-since-yesterday/17240/8